linux/fs/btrfs/volumes.c
<<
>>
Prefs
   1/*
   2 * Copyright (C) 2007 Oracle.  All rights reserved.
   3 *
   4 * This program is free software; you can redistribute it and/or
   5 * modify it under the terms of the GNU General Public
   6 * License v2 as published by the Free Software Foundation.
   7 *
   8 * This program is distributed in the hope that it will be useful,
   9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  11 * General Public License for more details.
  12 *
  13 * You should have received a copy of the GNU General Public
  14 * License along with this program; if not, write to the
  15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  16 * Boston, MA 021110-1307, USA.
  17 */
  18#include <linux/sched.h>
  19#include <linux/bio.h>
  20#include <linux/slab.h>
  21#include <linux/buffer_head.h>
  22#include <linux/blkdev.h>
  23#include <linux/random.h>
  24#include <linux/iocontext.h>
  25#include <linux/capability.h>
  26#include <asm/div64.h>
  27#include "compat.h"
  28#include "ctree.h"
  29#include "extent_map.h"
  30#include "disk-io.h"
  31#include "transaction.h"
  32#include "print-tree.h"
  33#include "volumes.h"
  34#include "async-thread.h"
  35
  36struct map_lookup {
  37        u64 type;
  38        int io_align;
  39        int io_width;
  40        int stripe_len;
  41        int sector_size;
  42        int num_stripes;
  43        int sub_stripes;
  44        struct btrfs_bio_stripe stripes[];
  45};
  46
  47static int init_first_rw_device(struct btrfs_trans_handle *trans,
  48                                struct btrfs_root *root,
  49                                struct btrfs_device *device);
  50static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
  51
  52#define map_lookup_size(n) (sizeof(struct map_lookup) + \
  53                            (sizeof(struct btrfs_bio_stripe) * (n)))
  54
  55static DEFINE_MUTEX(uuid_mutex);
  56static LIST_HEAD(fs_uuids);
  57
  58void btrfs_lock_volumes(void)
  59{
  60        mutex_lock(&uuid_mutex);
  61}
  62
  63void btrfs_unlock_volumes(void)
  64{
  65        mutex_unlock(&uuid_mutex);
  66}
  67
  68static void lock_chunks(struct btrfs_root *root)
  69{
  70        mutex_lock(&root->fs_info->chunk_mutex);
  71}
  72
  73static void unlock_chunks(struct btrfs_root *root)
  74{
  75        mutex_unlock(&root->fs_info->chunk_mutex);
  76}
  77
  78static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
  79{
  80        struct btrfs_device *device;
  81        WARN_ON(fs_devices->opened);
  82        while (!list_empty(&fs_devices->devices)) {
  83                device = list_entry(fs_devices->devices.next,
  84                                    struct btrfs_device, dev_list);
  85                list_del(&device->dev_list);
  86                kfree(device->name);
  87                kfree(device);
  88        }
  89        kfree(fs_devices);
  90}
  91
  92int btrfs_cleanup_fs_uuids(void)
  93{
  94        struct btrfs_fs_devices *fs_devices;
  95
  96        while (!list_empty(&fs_uuids)) {
  97                fs_devices = list_entry(fs_uuids.next,
  98                                        struct btrfs_fs_devices, list);
  99                list_del(&fs_devices->list);
 100                free_fs_devices(fs_devices);
 101        }
 102        return 0;
 103}
 104
 105static noinline struct btrfs_device *__find_device(struct list_head *head,
 106                                                   u64 devid, u8 *uuid)
 107{
 108        struct btrfs_device *dev;
 109
 110        list_for_each_entry(dev, head, dev_list) {
 111                if (dev->devid == devid &&
 112                    (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
 113                        return dev;
 114                }
 115        }
 116        return NULL;
 117}
 118
 119static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
 120{
 121        struct btrfs_fs_devices *fs_devices;
 122
 123        list_for_each_entry(fs_devices, &fs_uuids, list) {
 124                if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
 125                        return fs_devices;
 126        }
 127        return NULL;
 128}
 129
 130static void requeue_list(struct btrfs_pending_bios *pending_bios,
 131                        struct bio *head, struct bio *tail)
 132{
 133
 134        struct bio *old_head;
 135
 136        old_head = pending_bios->head;
 137        pending_bios->head = head;
 138        if (pending_bios->tail)
 139                tail->bi_next = old_head;
 140        else
 141                pending_bios->tail = tail;
 142}
 143
 144/*
 145 * we try to collect pending bios for a device so we don't get a large
 146 * number of procs sending bios down to the same device.  This greatly
 147 * improves the schedulers ability to collect and merge the bios.
 148 *
 149 * But, it also turns into a long list of bios to process and that is sure
 150 * to eventually make the worker thread block.  The solution here is to
 151 * make some progress and then put this work struct back at the end of
 152 * the list if the block device is congested.  This way, multiple devices
 153 * can make progress from a single worker thread.
 154 */
 155static noinline int run_scheduled_bios(struct btrfs_device *device)
 156{
 157        struct bio *pending;
 158        struct backing_dev_info *bdi;
 159        struct btrfs_fs_info *fs_info;
 160        struct btrfs_pending_bios *pending_bios;
 161        struct bio *tail;
 162        struct bio *cur;
 163        int again = 0;
 164        unsigned long num_run;
 165        unsigned long num_sync_run;
 166        unsigned long batch_run = 0;
 167        unsigned long limit;
 168        unsigned long last_waited = 0;
 169        int force_reg = 0;
 170
 171        bdi = blk_get_backing_dev_info(device->bdev);
 172        fs_info = device->dev_root->fs_info;
 173        limit = btrfs_async_submit_limit(fs_info);
 174        limit = limit * 2 / 3;
 175
 176        /* we want to make sure that every time we switch from the sync
 177         * list to the normal list, we unplug
 178         */
 179        num_sync_run = 0;
 180
 181loop:
 182        spin_lock(&device->io_lock);
 183
 184loop_lock:
 185        num_run = 0;
 186
 187        /* take all the bios off the list at once and process them
 188         * later on (without the lock held).  But, remember the
 189         * tail and other pointers so the bios can be properly reinserted
 190         * into the list if we hit congestion
 191         */
 192        if (!force_reg && device->pending_sync_bios.head) {
 193                pending_bios = &device->pending_sync_bios;
 194                force_reg = 1;
 195        } else {
 196                pending_bios = &device->pending_bios;
 197                force_reg = 0;
 198        }
 199
 200        pending = pending_bios->head;
 201        tail = pending_bios->tail;
 202        WARN_ON(pending && !tail);
 203
 204        /*
 205         * if pending was null this time around, no bios need processing
 206         * at all and we can stop.  Otherwise it'll loop back up again
 207         * and do an additional check so no bios are missed.
 208         *
 209         * device->running_pending is used to synchronize with the
 210         * schedule_bio code.
 211         */
 212        if (device->pending_sync_bios.head == NULL &&
 213            device->pending_bios.head == NULL) {
 214                again = 0;
 215                device->running_pending = 0;
 216        } else {
 217                again = 1;
 218                device->running_pending = 1;
 219        }
 220
 221        pending_bios->head = NULL;
 222        pending_bios->tail = NULL;
 223
 224        spin_unlock(&device->io_lock);
 225
 226        /*
 227         * if we're doing the regular priority list, make sure we unplug
 228         * for any high prio bios we've sent down
 229         */
 230        if (pending_bios == &device->pending_bios && num_sync_run > 0) {
 231                num_sync_run = 0;
 232                blk_run_backing_dev(bdi, NULL);
 233        }
 234
 235        while (pending) {
 236
 237                rmb();
 238                /* we want to work on both lists, but do more bios on the
 239                 * sync list than the regular list
 240                 */
 241                if ((num_run > 32 &&
 242                    pending_bios != &device->pending_sync_bios &&
 243                    device->pending_sync_bios.head) ||
 244                   (num_run > 64 && pending_bios == &device->pending_sync_bios &&
 245                    device->pending_bios.head)) {
 246                        spin_lock(&device->io_lock);
 247                        requeue_list(pending_bios, pending, tail);
 248                        goto loop_lock;
 249                }
 250
 251                cur = pending;
 252                pending = pending->bi_next;
 253                cur->bi_next = NULL;
 254                atomic_dec(&fs_info->nr_async_bios);
 255
 256                if (atomic_read(&fs_info->nr_async_bios) < limit &&
 257                    waitqueue_active(&fs_info->async_submit_wait))
 258                        wake_up(&fs_info->async_submit_wait);
 259
 260                BUG_ON(atomic_read(&cur->bi_cnt) == 0);
 261
 262                if (cur->bi_rw & REQ_SYNC)
 263                        num_sync_run++;
 264
 265                submit_bio(cur->bi_rw, cur);
 266                num_run++;
 267                batch_run++;
 268                if (need_resched()) {
 269                        if (num_sync_run) {
 270                                blk_run_backing_dev(bdi, NULL);
 271                                num_sync_run = 0;
 272                        }
 273                        cond_resched();
 274                }
 275
 276                /*
 277                 * we made progress, there is more work to do and the bdi
 278                 * is now congested.  Back off and let other work structs
 279                 * run instead
 280                 */
 281                if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
 282                    fs_info->fs_devices->open_devices > 1) {
 283                        struct io_context *ioc;
 284
 285                        ioc = current->io_context;
 286
 287                        /*
 288                         * the main goal here is that we don't want to
 289                         * block if we're going to be able to submit
 290                         * more requests without blocking.
 291                         *
 292                         * This code does two great things, it pokes into
 293                         * the elevator code from a filesystem _and_
 294                         * it makes assumptions about how batching works.
 295                         */
 296                        if (ioc && ioc->nr_batch_requests > 0 &&
 297                            time_before(jiffies, ioc->last_waited + HZ/50UL) &&
 298                            (last_waited == 0 ||
 299                             ioc->last_waited == last_waited)) {
 300                                /*
 301                                 * we want to go through our batch of
 302                                 * requests and stop.  So, we copy out
 303                                 * the ioc->last_waited time and test
 304                                 * against it before looping
 305                                 */
 306                                last_waited = ioc->last_waited;
 307                                if (need_resched()) {
 308                                        if (num_sync_run) {
 309                                                blk_run_backing_dev(bdi, NULL);
 310                                                num_sync_run = 0;
 311                                        }
 312                                        cond_resched();
 313                                }
 314                                continue;
 315                        }
 316                        spin_lock(&device->io_lock);
 317                        requeue_list(pending_bios, pending, tail);
 318                        device->running_pending = 1;
 319
 320                        spin_unlock(&device->io_lock);
 321                        btrfs_requeue_work(&device->work);
 322                        goto done;
 323                }
 324        }
 325
 326        if (num_sync_run) {
 327                num_sync_run = 0;
 328                blk_run_backing_dev(bdi, NULL);
 329        }
 330        /*
 331         * IO has already been through a long path to get here.  Checksumming,
 332         * async helper threads, perhaps compression.  We've done a pretty
 333         * good job of collecting a batch of IO and should just unplug
 334         * the device right away.
 335         *
 336         * This will help anyone who is waiting on the IO, they might have
 337         * already unplugged, but managed to do so before the bio they
 338         * cared about found its way down here.
 339         */
 340        blk_run_backing_dev(bdi, NULL);
 341
 342        cond_resched();
 343        if (again)
 344                goto loop;
 345
 346        spin_lock(&device->io_lock);
 347        if (device->pending_bios.head || device->pending_sync_bios.head)
 348                goto loop_lock;
 349        spin_unlock(&device->io_lock);
 350
 351done:
 352        return 0;
 353}
 354
 355static void pending_bios_fn(struct btrfs_work *work)
 356{
 357        struct btrfs_device *device;
 358
 359        device = container_of(work, struct btrfs_device, work);
 360        run_scheduled_bios(device);
 361}
 362
 363static noinline int device_list_add(const char *path,
 364                           struct btrfs_super_block *disk_super,
 365                           u64 devid, struct btrfs_fs_devices **fs_devices_ret)
 366{
 367        struct btrfs_device *device;
 368        struct btrfs_fs_devices *fs_devices;
 369        u64 found_transid = btrfs_super_generation(disk_super);
 370        char *name;
 371
 372        fs_devices = find_fsid(disk_super->fsid);
 373        if (!fs_devices) {
 374                fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
 375                if (!fs_devices)
 376                        return -ENOMEM;
 377                INIT_LIST_HEAD(&fs_devices->devices);
 378                INIT_LIST_HEAD(&fs_devices->alloc_list);
 379                list_add(&fs_devices->list, &fs_uuids);
 380                memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
 381                fs_devices->latest_devid = devid;
 382                fs_devices->latest_trans = found_transid;
 383                mutex_init(&fs_devices->device_list_mutex);
 384                device = NULL;
 385        } else {
 386                device = __find_device(&fs_devices->devices, devid,
 387                                       disk_super->dev_item.uuid);
 388        }
 389        if (!device) {
 390                if (fs_devices->opened)
 391                        return -EBUSY;
 392
 393                device = kzalloc(sizeof(*device), GFP_NOFS);
 394                if (!device) {
 395                        /* we can safely leave the fs_devices entry around */
 396                        return -ENOMEM;
 397                }
 398                device->devid = devid;
 399                device->work.func = pending_bios_fn;
 400                memcpy(device->uuid, disk_super->dev_item.uuid,
 401                       BTRFS_UUID_SIZE);
 402                spin_lock_init(&device->io_lock);
 403                device->name = kstrdup(path, GFP_NOFS);
 404                if (!device->name) {
 405                        kfree(device);
 406                        return -ENOMEM;
 407                }
 408                INIT_LIST_HEAD(&device->dev_alloc_list);
 409
 410                mutex_lock(&fs_devices->device_list_mutex);
 411                list_add(&device->dev_list, &fs_devices->devices);
 412                mutex_unlock(&fs_devices->device_list_mutex);
 413
 414                device->fs_devices = fs_devices;
 415                fs_devices->num_devices++;
 416        } else if (!device->name || strcmp(device->name, path)) {
 417                name = kstrdup(path, GFP_NOFS);
 418                if (!name)
 419                        return -ENOMEM;
 420                kfree(device->name);
 421                device->name = name;
 422                if (device->missing) {
 423                        fs_devices->missing_devices--;
 424                        device->missing = 0;
 425                }
 426        }
 427
 428        if (found_transid > fs_devices->latest_trans) {
 429                fs_devices->latest_devid = devid;
 430                fs_devices->latest_trans = found_transid;
 431        }
 432        *fs_devices_ret = fs_devices;
 433        return 0;
 434}
 435
 436static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
 437{
 438        struct btrfs_fs_devices *fs_devices;
 439        struct btrfs_device *device;
 440        struct btrfs_device *orig_dev;
 441
 442        fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
 443        if (!fs_devices)
 444                return ERR_PTR(-ENOMEM);
 445
 446        INIT_LIST_HEAD(&fs_devices->devices);
 447        INIT_LIST_HEAD(&fs_devices->alloc_list);
 448        INIT_LIST_HEAD(&fs_devices->list);
 449        mutex_init(&fs_devices->device_list_mutex);
 450        fs_devices->latest_devid = orig->latest_devid;
 451        fs_devices->latest_trans = orig->latest_trans;
 452        memcpy(fs_devices->fsid, orig->fsid, sizeof(fs_devices->fsid));
 453
 454        mutex_lock(&orig->device_list_mutex);
 455        list_for_each_entry(orig_dev, &orig->devices, dev_list) {
 456                device = kzalloc(sizeof(*device), GFP_NOFS);
 457                if (!device)
 458                        goto error;
 459
 460                device->name = kstrdup(orig_dev->name, GFP_NOFS);
 461                if (!device->name) {
 462                        kfree(device);
 463                        goto error;
 464                }
 465
 466                device->devid = orig_dev->devid;
 467                device->work.func = pending_bios_fn;
 468                memcpy(device->uuid, orig_dev->uuid, sizeof(device->uuid));
 469                spin_lock_init(&device->io_lock);
 470                INIT_LIST_HEAD(&device->dev_list);
 471                INIT_LIST_HEAD(&device->dev_alloc_list);
 472
 473                list_add(&device->dev_list, &fs_devices->devices);
 474                device->fs_devices = fs_devices;
 475                fs_devices->num_devices++;
 476        }
 477        mutex_unlock(&orig->device_list_mutex);
 478        return fs_devices;
 479error:
 480        mutex_unlock(&orig->device_list_mutex);
 481        free_fs_devices(fs_devices);
 482        return ERR_PTR(-ENOMEM);
 483}
 484
 485int btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
 486{
 487        struct btrfs_device *device, *next;
 488
 489        mutex_lock(&uuid_mutex);
 490again:
 491        mutex_lock(&fs_devices->device_list_mutex);
 492        list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
 493                if (device->in_fs_metadata)
 494                        continue;
 495
 496                if (device->bdev) {
 497                        blkdev_put(device->bdev, device->mode);
 498                        device->bdev = NULL;
 499                        fs_devices->open_devices--;
 500                }
 501                if (device->writeable) {
 502                        list_del_init(&device->dev_alloc_list);
 503                        device->writeable = 0;
 504                        fs_devices->rw_devices--;
 505                }
 506                list_del_init(&device->dev_list);
 507                fs_devices->num_devices--;
 508                kfree(device->name);
 509                kfree(device);
 510        }
 511        mutex_unlock(&fs_devices->device_list_mutex);
 512
 513        if (fs_devices->seed) {
 514                fs_devices = fs_devices->seed;
 515                goto again;
 516        }
 517
 518        mutex_unlock(&uuid_mutex);
 519        return 0;
 520}
 521
 522static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
 523{
 524        struct btrfs_device *device;
 525
 526        if (--fs_devices->opened > 0)
 527                return 0;
 528
 529        list_for_each_entry(device, &fs_devices->devices, dev_list) {
 530                if (device->bdev) {
 531                        blkdev_put(device->bdev, device->mode);
 532                        fs_devices->open_devices--;
 533                }
 534                if (device->writeable) {
 535                        list_del_init(&device->dev_alloc_list);
 536                        fs_devices->rw_devices--;
 537                }
 538
 539                device->bdev = NULL;
 540                device->writeable = 0;
 541                device->in_fs_metadata = 0;
 542        }
 543        WARN_ON(fs_devices->open_devices);
 544        WARN_ON(fs_devices->rw_devices);
 545        fs_devices->opened = 0;
 546        fs_devices->seeding = 0;
 547
 548        return 0;
 549}
 550
 551int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
 552{
 553        struct btrfs_fs_devices *seed_devices = NULL;
 554        int ret;
 555
 556        mutex_lock(&uuid_mutex);
 557        ret = __btrfs_close_devices(fs_devices);
 558        if (!fs_devices->opened) {
 559                seed_devices = fs_devices->seed;
 560                fs_devices->seed = NULL;
 561        }
 562        mutex_unlock(&uuid_mutex);
 563
 564        while (seed_devices) {
 565                fs_devices = seed_devices;
 566                seed_devices = fs_devices->seed;
 567                __btrfs_close_devices(fs_devices);
 568                free_fs_devices(fs_devices);
 569        }
 570        return ret;
 571}
 572
 573static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
 574                                fmode_t flags, void *holder)
 575{
 576        struct block_device *bdev;
 577        struct list_head *head = &fs_devices->devices;
 578        struct btrfs_device *device;
 579        struct block_device *latest_bdev = NULL;
 580        struct buffer_head *bh;
 581        struct btrfs_super_block *disk_super;
 582        u64 latest_devid = 0;
 583        u64 latest_transid = 0;
 584        u64 devid;
 585        int seeding = 1;
 586        int ret = 0;
 587
 588        flags |= FMODE_EXCL;
 589
 590        list_for_each_entry(device, head, dev_list) {
 591                if (device->bdev)
 592                        continue;
 593                if (!device->name)
 594                        continue;
 595
 596                bdev = blkdev_get_by_path(device->name, flags, holder);
 597                if (IS_ERR(bdev)) {
 598                        printk(KERN_INFO "open %s failed\n", device->name);
 599                        goto error;
 600                }
 601                set_blocksize(bdev, 4096);
 602
 603                bh = btrfs_read_dev_super(bdev);
 604                if (!bh) {
 605                        ret = -EINVAL;
 606                        goto error_close;
 607                }
 608
 609                disk_super = (struct btrfs_super_block *)bh->b_data;
 610                devid = btrfs_stack_device_id(&disk_super->dev_item);
 611                if (devid != device->devid)
 612                        goto error_brelse;
 613
 614                if (memcmp(device->uuid, disk_super->dev_item.uuid,
 615                           BTRFS_UUID_SIZE))
 616                        goto error_brelse;
 617
 618                device->generation = btrfs_super_generation(disk_super);
 619                if (!latest_transid || device->generation > latest_transid) {
 620                        latest_devid = devid;
 621                        latest_transid = device->generation;
 622                        latest_bdev = bdev;
 623                }
 624
 625                if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
 626                        device->writeable = 0;
 627                } else {
 628                        device->writeable = !bdev_read_only(bdev);
 629                        seeding = 0;
 630                }
 631
 632                device->bdev = bdev;
 633                device->in_fs_metadata = 0;
 634                device->mode = flags;
 635
 636                if (!blk_queue_nonrot(bdev_get_queue(bdev)))
 637                        fs_devices->rotating = 1;
 638
 639                fs_devices->open_devices++;
 640                if (device->writeable) {
 641                        fs_devices->rw_devices++;
 642                        list_add(&device->dev_alloc_list,
 643                                 &fs_devices->alloc_list);
 644                }
 645                continue;
 646
 647error_brelse:
 648                brelse(bh);
 649error_close:
 650                blkdev_put(bdev, flags);
 651error:
 652                continue;
 653        }
 654        if (fs_devices->open_devices == 0) {
 655                ret = -EIO;
 656                goto out;
 657        }
 658        fs_devices->seeding = seeding;
 659        fs_devices->opened = 1;
 660        fs_devices->latest_bdev = latest_bdev;
 661        fs_devices->latest_devid = latest_devid;
 662        fs_devices->latest_trans = latest_transid;
 663        fs_devices->total_rw_bytes = 0;
 664out:
 665        return ret;
 666}
 667
 668int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
 669                       fmode_t flags, void *holder)
 670{
 671        int ret;
 672
 673        mutex_lock(&uuid_mutex);
 674        if (fs_devices->opened) {
 675                fs_devices->opened++;
 676                ret = 0;
 677        } else {
 678                ret = __btrfs_open_devices(fs_devices, flags, holder);
 679        }
 680        mutex_unlock(&uuid_mutex);
 681        return ret;
 682}
 683
 684int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
 685                          struct btrfs_fs_devices **fs_devices_ret)
 686{
 687        struct btrfs_super_block *disk_super;
 688        struct block_device *bdev;
 689        struct buffer_head *bh;
 690        int ret;
 691        u64 devid;
 692        u64 transid;
 693
 694        mutex_lock(&uuid_mutex);
 695
 696        flags |= FMODE_EXCL;
 697        bdev = blkdev_get_by_path(path, flags, holder);
 698
 699        if (IS_ERR(bdev)) {
 700                ret = PTR_ERR(bdev);
 701                goto error;
 702        }
 703
 704        ret = set_blocksize(bdev, 4096);
 705        if (ret)
 706                goto error_close;
 707        bh = btrfs_read_dev_super(bdev);
 708        if (!bh) {
 709                ret = -EINVAL;
 710                goto error_close;
 711        }
 712        disk_super = (struct btrfs_super_block *)bh->b_data;
 713        devid = btrfs_stack_device_id(&disk_super->dev_item);
 714        transid = btrfs_super_generation(disk_super);
 715        if (disk_super->label[0])
 716                printk(KERN_INFO "device label %s ", disk_super->label);
 717        else {
 718                /* FIXME, make a readl uuid parser */
 719                printk(KERN_INFO "device fsid %llx-%llx ",
 720                       *(unsigned long long *)disk_super->fsid,
 721                       *(unsigned long long *)(disk_super->fsid + 8));
 722        }
 723        printk(KERN_CONT "devid %llu transid %llu %s\n",
 724               (unsigned long long)devid, (unsigned long long)transid, path);
 725        ret = device_list_add(path, disk_super, devid, fs_devices_ret);
 726
 727        brelse(bh);
 728error_close:
 729        blkdev_put(bdev, flags);
 730error:
 731        mutex_unlock(&uuid_mutex);
 732        return ret;
 733}
 734
 735/* helper to account the used device space in the range */
 736int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
 737                                   u64 end, u64 *length)
 738{
 739        struct btrfs_key key;
 740        struct btrfs_root *root = device->dev_root;
 741        struct btrfs_dev_extent *dev_extent;
 742        struct btrfs_path *path;
 743        u64 extent_end;
 744        int ret;
 745        int slot;
 746        struct extent_buffer *l;
 747
 748        *length = 0;
 749
 750        if (start >= device->total_bytes)
 751                return 0;
 752
 753        path = btrfs_alloc_path();
 754        if (!path)
 755                return -ENOMEM;
 756        path->reada = 2;
 757
 758        key.objectid = device->devid;
 759        key.offset = start;
 760        key.type = BTRFS_DEV_EXTENT_KEY;
 761
 762        ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
 763        if (ret < 0)
 764                goto out;
 765        if (ret > 0) {
 766                ret = btrfs_previous_item(root, path, key.objectid, key.type);
 767                if (ret < 0)
 768                        goto out;
 769        }
 770
 771        while (1) {
 772                l = path->nodes[0];
 773                slot = path->slots[0];
 774                if (slot >= btrfs_header_nritems(l)) {
 775                        ret = btrfs_next_leaf(root, path);
 776                        if (ret == 0)
 777                                continue;
 778                        if (ret < 0)
 779                                goto out;
 780
 781                        break;
 782                }
 783                btrfs_item_key_to_cpu(l, &key, slot);
 784
 785                if (key.objectid < device->devid)
 786                        goto next;
 787
 788                if (key.objectid > device->devid)
 789                        break;
 790
 791                if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
 792                        goto next;
 793
 794                dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
 795                extent_end = key.offset + btrfs_dev_extent_length(l,
 796                                                                  dev_extent);
 797                if (key.offset <= start && extent_end > end) {
 798                        *length = end - start + 1;
 799                        break;
 800                } else if (key.offset <= start && extent_end > start)
 801                        *length += extent_end - start;
 802                else if (key.offset > start && extent_end <= end)
 803                        *length += extent_end - key.offset;
 804                else if (key.offset > start && key.offset <= end) {
 805                        *length += end - key.offset + 1;
 806                        break;
 807                } else if (key.offset > end)
 808                        break;
 809
 810next:
 811                path->slots[0]++;
 812        }
 813        ret = 0;
 814out:
 815        btrfs_free_path(path);
 816        return ret;
 817}
 818
 819/*
 820 * find_free_dev_extent - find free space in the specified device
 821 * @trans:      transaction handler
 822 * @device:     the device which we search the free space in
 823 * @num_bytes:  the size of the free space that we need
 824 * @start:      store the start of the free space.
 825 * @len:        the size of the free space. that we find, or the size of the max
 826 *              free space if we don't find suitable free space
 827 *
 828 * this uses a pretty simple search, the expectation is that it is
 829 * called very infrequently and that a given device has a small number
 830 * of extents
 831 *
 832 * @start is used to store the start of the free space if we find. But if we
 833 * don't find suitable free space, it will be used to store the start position
 834 * of the max free space.
 835 *
 836 * @len is used to store the size of the free space that we find.
 837 * But if we don't find suitable free space, it is used to store the size of
 838 * the max free space.
 839 */
 840int find_free_dev_extent(struct btrfs_trans_handle *trans,
 841                         struct btrfs_device *device, u64 num_bytes,
 842                         u64 *start, u64 *len)
 843{
 844        struct btrfs_key key;
 845        struct btrfs_root *root = device->dev_root;
 846        struct btrfs_dev_extent *dev_extent;
 847        struct btrfs_path *path;
 848        u64 hole_size;
 849        u64 max_hole_start;
 850        u64 max_hole_size;
 851        u64 extent_end;
 852        u64 search_start;
 853        u64 search_end = device->total_bytes;
 854        int ret;
 855        int slot;
 856        struct extent_buffer *l;
 857
 858        /* FIXME use last free of some kind */
 859
 860        /* we don't want to overwrite the superblock on the drive,
 861         * so we make sure to start at an offset of at least 1MB
 862         */
 863        search_start = 1024 * 1024;
 864
 865        if (root->fs_info->alloc_start + num_bytes <= search_end)
 866                search_start = max(root->fs_info->alloc_start, search_start);
 867
 868        max_hole_start = search_start;
 869        max_hole_size = 0;
 870
 871        if (search_start >= search_end) {
 872                ret = -ENOSPC;
 873                goto error;
 874        }
 875
 876        path = btrfs_alloc_path();
 877        if (!path) {
 878                ret = -ENOMEM;
 879                goto error;
 880        }
 881        path->reada = 2;
 882
 883        key.objectid = device->devid;
 884        key.offset = search_start;
 885        key.type = BTRFS_DEV_EXTENT_KEY;
 886
 887        ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
 888        if (ret < 0)
 889                goto out;
 890        if (ret > 0) {
 891                ret = btrfs_previous_item(root, path, key.objectid, key.type);
 892                if (ret < 0)
 893                        goto out;
 894        }
 895
 896        while (1) {
 897                l = path->nodes[0];
 898                slot = path->slots[0];
 899                if (slot >= btrfs_header_nritems(l)) {
 900                        ret = btrfs_next_leaf(root, path);
 901                        if (ret == 0)
 902                                continue;
 903                        if (ret < 0)
 904                                goto out;
 905
 906                        break;
 907                }
 908                btrfs_item_key_to_cpu(l, &key, slot);
 909
 910                if (key.objectid < device->devid)
 911                        goto next;
 912
 913                if (key.objectid > device->devid)
 914                        break;
 915
 916                if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
 917                        goto next;
 918
 919                if (key.offset > search_start) {
 920                        hole_size = key.offset - search_start;
 921
 922                        if (hole_size > max_hole_size) {
 923                                max_hole_start = search_start;
 924                                max_hole_size = hole_size;
 925                        }
 926
 927                        /*
 928                         * If this free space is greater than which we need,
 929                         * it must be the max free space that we have found
 930                         * until now, so max_hole_start must point to the start
 931                         * of this free space and the length of this free space
 932                         * is stored in max_hole_size. Thus, we return
 933                         * max_hole_start and max_hole_size and go back to the
 934                         * caller.
 935                         */
 936                        if (hole_size >= num_bytes) {
 937                                ret = 0;
 938                                goto out;
 939                        }
 940                }
 941
 942                dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
 943                extent_end = key.offset + btrfs_dev_extent_length(l,
 944                                                                  dev_extent);
 945                if (extent_end > search_start)
 946                        search_start = extent_end;
 947next:
 948                path->slots[0]++;
 949                cond_resched();
 950        }
 951
 952        hole_size = search_end- search_start;
 953        if (hole_size > max_hole_size) {
 954                max_hole_start = search_start;
 955                max_hole_size = hole_size;
 956        }
 957
 958        /* See above. */
 959        if (hole_size < num_bytes)
 960                ret = -ENOSPC;
 961        else
 962                ret = 0;
 963
 964out:
 965        btrfs_free_path(path);
 966error:
 967        *start = max_hole_start;
 968        if (len)
 969                *len = max_hole_size;
 970        return ret;
 971}
 972
 973static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
 974                          struct btrfs_device *device,
 975                          u64 start)
 976{
 977        int ret;
 978        struct btrfs_path *path;
 979        struct btrfs_root *root = device->dev_root;
 980        struct btrfs_key key;
 981        struct btrfs_key found_key;
 982        struct extent_buffer *leaf = NULL;
 983        struct btrfs_dev_extent *extent = NULL;
 984
 985        path = btrfs_alloc_path();
 986        if (!path)
 987                return -ENOMEM;
 988
 989        key.objectid = device->devid;
 990        key.offset = start;
 991        key.type = BTRFS_DEV_EXTENT_KEY;
 992
 993        ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
 994        if (ret > 0) {
 995                ret = btrfs_previous_item(root, path, key.objectid,
 996                                          BTRFS_DEV_EXTENT_KEY);
 997                BUG_ON(ret);
 998                leaf = path->nodes[0];
 999                btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1000                extent = btrfs_item_ptr(leaf, path->slots[0],
1001                                        struct btrfs_dev_extent);
1002                BUG_ON(found_key.offset > start || found_key.offset +
1003                       btrfs_dev_extent_length(leaf, extent) < start);
1004                ret = 0;
1005        } else if (ret == 0) {
1006                leaf = path->nodes[0];
1007                extent = btrfs_item_ptr(leaf, path->slots[0],
1008                                        struct btrfs_dev_extent);
1009        }
1010        BUG_ON(ret);
1011
1012        if (device->bytes_used > 0)
1013                device->bytes_used -= btrfs_dev_extent_length(leaf, extent);
1014        ret = btrfs_del_item(trans, root, path);
1015        BUG_ON(ret);
1016
1017        btrfs_free_path(path);
1018        return ret;
1019}
1020
1021int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1022                           struct btrfs_device *device,
1023                           u64 chunk_tree, u64 chunk_objectid,
1024                           u64 chunk_offset, u64 start, u64 num_bytes)
1025{
1026        int ret;
1027        struct btrfs_path *path;
1028        struct btrfs_root *root = device->dev_root;
1029        struct btrfs_dev_extent *extent;
1030        struct extent_buffer *leaf;
1031        struct btrfs_key key;
1032
1033        WARN_ON(!device->in_fs_metadata);
1034        path = btrfs_alloc_path();
1035        if (!path)
1036                return -ENOMEM;
1037
1038        key.objectid = device->devid;
1039        key.offset = start;
1040        key.type = BTRFS_DEV_EXTENT_KEY;
1041        ret = btrfs_insert_empty_item(trans, root, path, &key,
1042                                      sizeof(*extent));
1043        BUG_ON(ret);
1044
1045        leaf = path->nodes[0];
1046        extent = btrfs_item_ptr(leaf, path->slots[0],
1047                                struct btrfs_dev_extent);
1048        btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1049        btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1050        btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1051
1052        write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1053                    (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1054                    BTRFS_UUID_SIZE);
1055
1056        btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1057        btrfs_mark_buffer_dirty(leaf);
1058        btrfs_free_path(path);
1059        return ret;
1060}
1061
1062static noinline int find_next_chunk(struct btrfs_root *root,
1063                                    u64 objectid, u64 *offset)
1064{
1065        struct btrfs_path *path;
1066        int ret;
1067        struct btrfs_key key;
1068        struct btrfs_chunk *chunk;
1069        struct btrfs_key found_key;
1070
1071        path = btrfs_alloc_path();
1072        BUG_ON(!path);
1073
1074        key.objectid = objectid;
1075        key.offset = (u64)-1;
1076        key.type = BTRFS_CHUNK_ITEM_KEY;
1077
1078        ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1079        if (ret < 0)
1080                goto error;
1081
1082        BUG_ON(ret == 0);
1083
1084        ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
1085        if (ret) {
1086                *offset = 0;
1087        } else {
1088                btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1089                                      path->slots[0]);
1090                if (found_key.objectid != objectid)
1091                        *offset = 0;
1092                else {
1093                        chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
1094                                               struct btrfs_chunk);
1095                        *offset = found_key.offset +
1096                                btrfs_chunk_length(path->nodes[0], chunk);
1097                }
1098        }
1099        ret = 0;
1100error:
1101        btrfs_free_path(path);
1102        return ret;
1103}
1104
1105static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
1106{
1107        int ret;
1108        struct btrfs_key key;
1109        struct btrfs_key found_key;
1110        struct btrfs_path *path;
1111
1112        root = root->fs_info->chunk_root;
1113
1114        path = btrfs_alloc_path();
1115        if (!path)
1116                return -ENOMEM;
1117
1118        key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1119        key.type = BTRFS_DEV_ITEM_KEY;
1120        key.offset = (u64)-1;
1121
1122        ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1123        if (ret < 0)
1124                goto error;
1125
1126        BUG_ON(ret == 0);
1127
1128        ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
1129                                  BTRFS_DEV_ITEM_KEY);
1130        if (ret) {
1131                *objectid = 1;
1132        } else {
1133                btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1134                                      path->slots[0]);
1135                *objectid = found_key.offset + 1;
1136        }
1137        ret = 0;
1138error:
1139        btrfs_free_path(path);
1140        return ret;
1141}
1142
1143/*
1144 * the device information is stored in the chunk root
1145 * the btrfs_device struct should be fully filled in
1146 */
1147int btrfs_add_device(struct btrfs_trans_handle *trans,
1148                     struct btrfs_root *root,
1149                     struct btrfs_device *device)
1150{
1151        int ret;
1152        struct btrfs_path *path;
1153        struct btrfs_dev_item *dev_item;
1154        struct extent_buffer *leaf;
1155        struct btrfs_key key;
1156        unsigned long ptr;
1157
1158        root = root->fs_info->chunk_root;
1159
1160        path = btrfs_alloc_path();
1161        if (!path)
1162                return -ENOMEM;
1163
1164        key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1165        key.type = BTRFS_DEV_ITEM_KEY;
1166        key.offset = device->devid;
1167
1168        ret = btrfs_insert_empty_item(trans, root, path, &key,
1169                                      sizeof(*dev_item));
1170        if (ret)
1171                goto out;
1172
1173        leaf = path->nodes[0];
1174        dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1175
1176        btrfs_set_device_id(leaf, dev_item, device->devid);
1177        btrfs_set_device_generation(leaf, dev_item, 0);
1178        btrfs_set_device_type(leaf, dev_item, device->type);
1179        btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1180        btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1181        btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1182        btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1183        btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1184        btrfs_set_device_group(leaf, dev_item, 0);
1185        btrfs_set_device_seek_speed(leaf, dev_item, 0);
1186        btrfs_set_device_bandwidth(leaf, dev_item, 0);
1187        btrfs_set_device_start_offset(leaf, dev_item, 0);
1188
1189        ptr = (unsigned long)btrfs_device_uuid(dev_item);
1190        write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1191        ptr = (unsigned long)btrfs_device_fsid(dev_item);
1192        write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1193        btrfs_mark_buffer_dirty(leaf);
1194
1195        ret = 0;
1196out:
1197        btrfs_free_path(path);
1198        return ret;
1199}
1200
1201static int btrfs_rm_dev_item(struct btrfs_root *root,
1202                             struct btrfs_device *device)
1203{
1204        int ret;
1205        struct btrfs_path *path;
1206        struct btrfs_key key;
1207        struct btrfs_trans_handle *trans;
1208
1209        root = root->fs_info->chunk_root;
1210
1211        path = btrfs_alloc_path();
1212        if (!path)
1213                return -ENOMEM;
1214
1215        trans = btrfs_start_transaction(root, 0);
1216        if (IS_ERR(trans)) {
1217                btrfs_free_path(path);
1218                return PTR_ERR(trans);
1219        }
1220        key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1221        key.type = BTRFS_DEV_ITEM_KEY;
1222        key.offset = device->devid;
1223        lock_chunks(root);
1224
1225        ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1226        if (ret < 0)
1227                goto out;
1228
1229        if (ret > 0) {
1230                ret = -ENOENT;
1231                goto out;
1232        }
1233
1234        ret = btrfs_del_item(trans, root, path);
1235        if (ret)
1236                goto out;
1237out:
1238        btrfs_free_path(path);
1239        unlock_chunks(root);
1240        btrfs_commit_transaction(trans, root);
1241        return ret;
1242}
1243
1244int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1245{
1246        struct btrfs_device *device;
1247        struct btrfs_device *next_device;
1248        struct block_device *bdev;
1249        struct buffer_head *bh = NULL;
1250        struct btrfs_super_block *disk_super;
1251        u64 all_avail;
1252        u64 devid;
1253        u64 num_devices;
1254        u8 *dev_uuid;
1255        int ret = 0;
1256
1257        mutex_lock(&uuid_mutex);
1258        mutex_lock(&root->fs_info->volume_mutex);
1259
1260        all_avail = root->fs_info->avail_data_alloc_bits |
1261                root->fs_info->avail_system_alloc_bits |
1262                root->fs_info->avail_metadata_alloc_bits;
1263
1264        if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
1265            root->fs_info->fs_devices->num_devices <= 4) {
1266                printk(KERN_ERR "btrfs: unable to go below four devices "
1267                       "on raid10\n");
1268                ret = -EINVAL;
1269                goto out;
1270        }
1271
1272        if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
1273            root->fs_info->fs_devices->num_devices <= 2) {
1274                printk(KERN_ERR "btrfs: unable to go below two "
1275                       "devices on raid1\n");
1276                ret = -EINVAL;
1277                goto out;
1278        }
1279
1280        if (strcmp(device_path, "missing") == 0) {
1281                struct list_head *devices;
1282                struct btrfs_device *tmp;
1283
1284                device = NULL;
1285                devices = &root->fs_info->fs_devices->devices;
1286                mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1287                list_for_each_entry(tmp, devices, dev_list) {
1288                        if (tmp->in_fs_metadata && !tmp->bdev) {
1289                                device = tmp;
1290                                break;
1291                        }
1292                }
1293                mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1294                bdev = NULL;
1295                bh = NULL;
1296                disk_super = NULL;
1297                if (!device) {
1298                        printk(KERN_ERR "btrfs: no missing devices found to "
1299                               "remove\n");
1300                        goto out;
1301                }
1302        } else {
1303                bdev = blkdev_get_by_path(device_path, FMODE_READ | FMODE_EXCL,
1304                                          root->fs_info->bdev_holder);
1305                if (IS_ERR(bdev)) {
1306                        ret = PTR_ERR(bdev);
1307                        goto out;
1308                }
1309
1310                set_blocksize(bdev, 4096);
1311                bh = btrfs_read_dev_super(bdev);
1312                if (!bh) {
1313                        ret = -EINVAL;
1314                        goto error_close;
1315                }
1316                disk_super = (struct btrfs_super_block *)bh->b_data;
1317                devid = btrfs_stack_device_id(&disk_super->dev_item);
1318                dev_uuid = disk_super->dev_item.uuid;
1319                device = btrfs_find_device(root, devid, dev_uuid,
1320                                           disk_super->fsid);
1321                if (!device) {
1322                        ret = -ENOENT;
1323                        goto error_brelse;
1324                }
1325        }
1326
1327        if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1328                printk(KERN_ERR "btrfs: unable to remove the only writeable "
1329                       "device\n");
1330                ret = -EINVAL;
1331                goto error_brelse;
1332        }
1333
1334        if (device->writeable) {
1335                list_del_init(&device->dev_alloc_list);
1336                root->fs_info->fs_devices->rw_devices--;
1337        }
1338
1339        ret = btrfs_shrink_device(device, 0);
1340        if (ret)
1341                goto error_undo;
1342
1343        ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1344        if (ret)
1345                goto error_undo;
1346
1347        device->in_fs_metadata = 0;
1348
1349        /*
1350         * the device list mutex makes sure that we don't change
1351         * the device list while someone else is writing out all
1352         * the device supers.
1353         */
1354        mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1355        list_del_init(&device->dev_list);
1356        mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1357
1358        device->fs_devices->num_devices--;
1359
1360        if (device->missing)
1361                root->fs_info->fs_devices->missing_devices--;
1362
1363        next_device = list_entry(root->fs_info->fs_devices->devices.next,
1364                                 struct btrfs_device, dev_list);
1365        if (device->bdev == root->fs_info->sb->s_bdev)
1366                root->fs_info->sb->s_bdev = next_device->bdev;
1367        if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1368                root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1369
1370        if (device->bdev) {
1371                blkdev_put(device->bdev, device->mode);
1372                device->bdev = NULL;
1373                device->fs_devices->open_devices--;
1374        }
1375
1376        num_devices = btrfs_super_num_devices(&root->fs_info->super_copy) - 1;
1377        btrfs_set_super_num_devices(&root->fs_info->super_copy, num_devices);
1378
1379        if (device->fs_devices->open_devices == 0) {
1380                struct btrfs_fs_devices *fs_devices;
1381                fs_devices = root->fs_info->fs_devices;
1382                while (fs_devices) {
1383                        if (fs_devices->seed == device->fs_devices)
1384                                break;
1385                        fs_devices = fs_devices->seed;
1386                }
1387                fs_devices->seed = device->fs_devices->seed;
1388                device->fs_devices->seed = NULL;
1389                __btrfs_close_devices(device->fs_devices);
1390                free_fs_devices(device->fs_devices);
1391        }
1392
1393        /*
1394         * at this point, the device is zero sized.  We want to
1395         * remove it from the devices list and zero out the old super
1396         */
1397        if (device->writeable) {
1398                /* make sure this device isn't detected as part of
1399                 * the FS anymore
1400                 */
1401                memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1402                set_buffer_dirty(bh);
1403                sync_dirty_buffer(bh);
1404        }
1405
1406        kfree(device->name);
1407        kfree(device);
1408        ret = 0;
1409
1410error_brelse:
1411        brelse(bh);
1412error_close:
1413        if (bdev)
1414                blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1415out:
1416        mutex_unlock(&root->fs_info->volume_mutex);
1417        mutex_unlock(&uuid_mutex);
1418        return ret;
1419error_undo:
1420        if (device->writeable) {
1421                list_add(&device->dev_alloc_list,
1422                         &root->fs_info->fs_devices->alloc_list);
1423                root->fs_info->fs_devices->rw_devices++;
1424        }
1425        goto error_brelse;
1426}
1427
1428/*
1429 * does all the dirty work required for changing file system's UUID.
1430 */
1431static int btrfs_prepare_sprout(struct btrfs_trans_handle *trans,
1432                                struct btrfs_root *root)
1433{
1434        struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1435        struct btrfs_fs_devices *old_devices;
1436        struct btrfs_fs_devices *seed_devices;
1437        struct btrfs_super_block *disk_super = &root->fs_info->super_copy;
1438        struct btrfs_device *device;
1439        u64 super_flags;
1440
1441        BUG_ON(!mutex_is_locked(&uuid_mutex));
1442        if (!fs_devices->seeding)
1443                return -EINVAL;
1444
1445        seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1446        if (!seed_devices)
1447                return -ENOMEM;
1448
1449        old_devices = clone_fs_devices(fs_devices);
1450        if (IS_ERR(old_devices)) {
1451                kfree(seed_devices);
1452                return PTR_ERR(old_devices);
1453        }
1454
1455        list_add(&old_devices->list, &fs_uuids);
1456
1457        memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1458        seed_devices->opened = 1;
1459        INIT_LIST_HEAD(&seed_devices->devices);
1460        INIT_LIST_HEAD(&seed_devices->alloc_list);
1461        mutex_init(&seed_devices->device_list_mutex);
1462        list_splice_init(&fs_devices->devices, &seed_devices->devices);
1463        list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1464        list_for_each_entry(device, &seed_devices->devices, dev_list) {
1465                device->fs_devices = seed_devices;
1466        }
1467
1468        fs_devices->seeding = 0;
1469        fs_devices->num_devices = 0;
1470        fs_devices->open_devices = 0;
1471        fs_devices->seed = seed_devices;
1472
1473        generate_random_uuid(fs_devices->fsid);
1474        memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1475        memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1476        super_flags = btrfs_super_flags(disk_super) &
1477                      ~BTRFS_SUPER_FLAG_SEEDING;
1478        btrfs_set_super_flags(disk_super, super_flags);
1479
1480        return 0;
1481}
1482
1483/*
1484 * strore the expected generation for seed devices in device items.
1485 */
1486static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1487                               struct btrfs_root *root)
1488{
1489        struct btrfs_path *path;
1490        struct extent_buffer *leaf;
1491        struct btrfs_dev_item *dev_item;
1492        struct btrfs_device *device;
1493        struct btrfs_key key;
1494        u8 fs_uuid[BTRFS_UUID_SIZE];
1495        u8 dev_uuid[BTRFS_UUID_SIZE];
1496        u64 devid;
1497        int ret;
1498
1499        path = btrfs_alloc_path();
1500        if (!path)
1501                return -ENOMEM;
1502
1503        root = root->fs_info->chunk_root;
1504        key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1505        key.offset = 0;
1506        key.type = BTRFS_DEV_ITEM_KEY;
1507
1508        while (1) {
1509                ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1510                if (ret < 0)
1511                        goto error;
1512
1513                leaf = path->nodes[0];
1514next_slot:
1515                if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1516                        ret = btrfs_next_leaf(root, path);
1517                        if (ret > 0)
1518                                break;
1519                        if (ret < 0)
1520                                goto error;
1521                        leaf = path->nodes[0];
1522                        btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1523                        btrfs_release_path(root, path);
1524                        continue;
1525                }
1526
1527                btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1528                if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1529                    key.type != BTRFS_DEV_ITEM_KEY)
1530                        break;
1531
1532                dev_item = btrfs_item_ptr(leaf, path->slots[0],
1533                                          struct btrfs_dev_item);
1534                devid = btrfs_device_id(leaf, dev_item);
1535                read_extent_buffer(leaf, dev_uuid,
1536                                   (unsigned long)btrfs_device_uuid(dev_item),
1537                                   BTRFS_UUID_SIZE);
1538                read_extent_buffer(leaf, fs_uuid,
1539                                   (unsigned long)btrfs_device_fsid(dev_item),
1540                                   BTRFS_UUID_SIZE);
1541                device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1542                BUG_ON(!device);
1543
1544                if (device->fs_devices->seeding) {
1545                        btrfs_set_device_generation(leaf, dev_item,
1546                                                    device->generation);
1547                        btrfs_mark_buffer_dirty(leaf);
1548                }
1549
1550                path->slots[0]++;
1551                goto next_slot;
1552        }
1553        ret = 0;
1554error:
1555        btrfs_free_path(path);
1556        return ret;
1557}
1558
1559int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1560{
1561        struct btrfs_trans_handle *trans;
1562        struct btrfs_device *device;
1563        struct block_device *bdev;
1564        struct list_head *devices;
1565        struct super_block *sb = root->fs_info->sb;
1566        u64 total_bytes;
1567        int seeding_dev = 0;
1568        int ret = 0;
1569
1570        if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1571                return -EINVAL;
1572
1573        bdev = blkdev_get_by_path(device_path, FMODE_EXCL,
1574                                  root->fs_info->bdev_holder);
1575        if (IS_ERR(bdev))
1576                return PTR_ERR(bdev);
1577
1578        if (root->fs_info->fs_devices->seeding) {
1579                seeding_dev = 1;
1580                down_write(&sb->s_umount);
1581                mutex_lock(&uuid_mutex);
1582        }
1583
1584        filemap_write_and_wait(bdev->bd_inode->i_mapping);
1585        mutex_lock(&root->fs_info->volume_mutex);
1586
1587        devices = &root->fs_info->fs_devices->devices;
1588        /*
1589         * we have the volume lock, so we don't need the extra
1590         * device list mutex while reading the list here.
1591         */
1592        list_for_each_entry(device, devices, dev_list) {
1593                if (device->bdev == bdev) {
1594                        ret = -EEXIST;
1595                        goto error;
1596                }
1597        }
1598
1599        device = kzalloc(sizeof(*device), GFP_NOFS);
1600        if (!device) {
1601                /* we can safely leave the fs_devices entry around */
1602                ret = -ENOMEM;
1603                goto error;
1604        }
1605
1606        device->name = kstrdup(device_path, GFP_NOFS);
1607        if (!device->name) {
1608                kfree(device);
1609                ret = -ENOMEM;
1610                goto error;
1611        }
1612
1613        ret = find_next_devid(root, &device->devid);
1614        if (ret) {
1615                kfree(device->name);
1616                kfree(device);
1617                goto error;
1618        }
1619
1620        trans = btrfs_start_transaction(root, 0);
1621        if (IS_ERR(trans)) {
1622                kfree(device->name);
1623                kfree(device);
1624                ret = PTR_ERR(trans);
1625                goto error;
1626        }
1627
1628        lock_chunks(root);
1629
1630        device->writeable = 1;
1631        device->work.func = pending_bios_fn;
1632        generate_random_uuid(device->uuid);
1633        spin_lock_init(&device->io_lock);
1634        device->generation = trans->transid;
1635        device->io_width = root->sectorsize;
1636        device->io_align = root->sectorsize;
1637        device->sector_size = root->sectorsize;
1638        device->total_bytes = i_size_read(bdev->bd_inode);
1639        device->disk_total_bytes = device->total_bytes;
1640        device->dev_root = root->fs_info->dev_root;
1641        device->bdev = bdev;
1642        device->in_fs_metadata = 1;
1643        device->mode = FMODE_EXCL;
1644        set_blocksize(device->bdev, 4096);
1645
1646        if (seeding_dev) {
1647                sb->s_flags &= ~MS_RDONLY;
1648                ret = btrfs_prepare_sprout(trans, root);
1649                BUG_ON(ret);
1650        }
1651
1652        device->fs_devices = root->fs_info->fs_devices;
1653
1654        /*
1655         * we don't want write_supers to jump in here with our device
1656         * half setup
1657         */
1658        mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1659        list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
1660        list_add(&device->dev_alloc_list,
1661                 &root->fs_info->fs_devices->alloc_list);
1662        root->fs_info->fs_devices->num_devices++;
1663        root->fs_info->fs_devices->open_devices++;
1664        root->fs_info->fs_devices->rw_devices++;
1665        root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
1666
1667        if (!blk_queue_nonrot(bdev_get_queue(bdev)))
1668                root->fs_info->fs_devices->rotating = 1;
1669
1670        total_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
1671        btrfs_set_super_total_bytes(&root->fs_info->super_copy,
1672                                    total_bytes + device->total_bytes);
1673
1674        total_bytes = btrfs_super_num_devices(&root->fs_info->super_copy);
1675        btrfs_set_super_num_devices(&root->fs_info->super_copy,
1676                                    total_bytes + 1);
1677        mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1678
1679        if (seeding_dev) {
1680                ret = init_first_rw_device(trans, root, device);
1681                BUG_ON(ret);
1682                ret = btrfs_finish_sprout(trans, root);
1683                BUG_ON(ret);
1684        } else {
1685                ret = btrfs_add_device(trans, root, device);
1686        }
1687
1688        /*
1689         * we've got more storage, clear any full flags on the space
1690         * infos
1691         */
1692        btrfs_clear_space_info_full(root->fs_info);
1693
1694        unlock_chunks(root);
1695        btrfs_commit_transaction(trans, root);
1696
1697        if (seeding_dev) {
1698                mutex_unlock(&uuid_mutex);
1699                up_write(&sb->s_umount);
1700
1701                ret = btrfs_relocate_sys_chunks(root);
1702                BUG_ON(ret);
1703        }
1704out:
1705        mutex_unlock(&root->fs_info->volume_mutex);
1706        return ret;
1707error:
1708        blkdev_put(bdev, FMODE_EXCL);
1709        if (seeding_dev) {
1710                mutex_unlock(&uuid_mutex);
1711                up_write(&sb->s_umount);
1712        }
1713        goto out;
1714}
1715
1716static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
1717                                        struct btrfs_device *device)
1718{
1719        int ret;
1720        struct btrfs_path *path;
1721        struct btrfs_root *root;
1722        struct btrfs_dev_item *dev_item;
1723        struct extent_buffer *leaf;
1724        struct btrfs_key key;
1725
1726        root = device->dev_root->fs_info->chunk_root;
1727
1728        path = btrfs_alloc_path();
1729        if (!path)
1730                return -ENOMEM;
1731
1732        key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1733        key.type = BTRFS_DEV_ITEM_KEY;
1734        key.offset = device->devid;
1735
1736        ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1737        if (ret < 0)
1738                goto out;
1739
1740        if (ret > 0) {
1741                ret = -ENOENT;
1742                goto out;
1743        }
1744
1745        leaf = path->nodes[0];
1746        dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1747
1748        btrfs_set_device_id(leaf, dev_item, device->devid);
1749        btrfs_set_device_type(leaf, dev_item, device->type);
1750        btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1751        btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1752        btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1753        btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
1754        btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1755        btrfs_mark_buffer_dirty(leaf);
1756
1757out:
1758        btrfs_free_path(path);
1759        return ret;
1760}
1761
1762static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
1763                      struct btrfs_device *device, u64 new_size)
1764{
1765        struct btrfs_super_block *super_copy =
1766                &device->dev_root->fs_info->super_copy;
1767        u64 old_total = btrfs_super_total_bytes(super_copy);
1768        u64 diff = new_size - device->total_bytes;
1769
1770        if (!device->writeable)
1771                return -EACCES;
1772        if (new_size <= device->total_bytes)
1773                return -EINVAL;
1774
1775        btrfs_set_super_total_bytes(super_copy, old_total + diff);
1776        device->fs_devices->total_rw_bytes += diff;
1777
1778        device->total_bytes = new_size;
1779        device->disk_total_bytes = new_size;
1780        btrfs_clear_space_info_full(device->dev_root->fs_info);
1781
1782        return btrfs_update_device(trans, device);
1783}
1784
1785int btrfs_grow_device(struct btrfs_trans_handle *trans,
1786                      struct btrfs_device *device, u64 new_size)
1787{
1788        int ret;
1789        lock_chunks(device->dev_root);
1790        ret = __btrfs_grow_device(trans, device, new_size);
1791        unlock_chunks(device->dev_root);
1792        return ret;
1793}
1794
1795static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1796                            struct btrfs_root *root,
1797                            u64 chunk_tree, u64 chunk_objectid,
1798                            u64 chunk_offset)
1799{
1800        int ret;
1801        struct btrfs_path *path;
1802        struct btrfs_key key;
1803
1804        root = root->fs_info->chunk_root;
1805        path = btrfs_alloc_path();
1806        if (!path)
1807                return -ENOMEM;
1808
1809        key.objectid = chunk_objectid;
1810        key.offset = chunk_offset;
1811        key.type = BTRFS_CHUNK_ITEM_KEY;
1812
1813        ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1814        BUG_ON(ret);
1815
1816        ret = btrfs_del_item(trans, root, path);
1817        BUG_ON(ret);
1818
1819        btrfs_free_path(path);
1820        return 0;
1821}
1822
1823static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
1824                        chunk_offset)
1825{
1826        struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1827        struct btrfs_disk_key *disk_key;
1828        struct btrfs_chunk *chunk;
1829        u8 *ptr;
1830        int ret = 0;
1831        u32 num_stripes;
1832        u32 array_size;
1833        u32 len = 0;
1834        u32 cur;
1835        struct btrfs_key key;
1836
1837        array_size = btrfs_super_sys_array_size(super_copy);
1838
1839        ptr = super_copy->sys_chunk_array;
1840        cur = 0;
1841
1842        while (cur < array_size) {
1843                disk_key = (struct btrfs_disk_key *)ptr;
1844                btrfs_disk_key_to_cpu(&key, disk_key);
1845
1846                len = sizeof(*disk_key);
1847
1848                if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1849                        chunk = (struct btrfs_chunk *)(ptr + len);
1850                        num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1851                        len += btrfs_chunk_item_size(num_stripes);
1852                } else {
1853                        ret = -EIO;
1854                        break;
1855                }
1856                if (key.objectid == chunk_objectid &&
1857                    key.offset == chunk_offset) {
1858                        memmove(ptr, ptr + len, array_size - (cur + len));
1859                        array_size -= len;
1860                        btrfs_set_super_sys_array_size(super_copy, array_size);
1861                } else {
1862                        ptr += len;
1863                        cur += len;
1864                }
1865        }
1866        return ret;
1867}
1868
1869static int btrfs_relocate_chunk(struct btrfs_root *root,
1870                         u64 chunk_tree, u64 chunk_objectid,
1871                         u64 chunk_offset)
1872{
1873        struct extent_map_tree *em_tree;
1874        struct btrfs_root *extent_root;
1875        struct btrfs_trans_handle *trans;
1876        struct extent_map *em;
1877        struct map_lookup *map;
1878        int ret;
1879        int i;
1880
1881        root = root->fs_info->chunk_root;
1882        extent_root = root->fs_info->extent_root;
1883        em_tree = &root->fs_info->mapping_tree.map_tree;
1884
1885        ret = btrfs_can_relocate(extent_root, chunk_offset);
1886        if (ret)
1887                return -ENOSPC;
1888
1889        /* step one, relocate all the extents inside this chunk */
1890        ret = btrfs_relocate_block_group(extent_root, chunk_offset);
1891        if (ret)
1892                return ret;
1893
1894        trans = btrfs_start_transaction(root, 0);
1895        BUG_ON(IS_ERR(trans));
1896
1897        lock_chunks(root);
1898
1899        /*
1900         * step two, delete the device extents and the
1901         * chunk tree entries
1902         */
1903        read_lock(&em_tree->lock);
1904        em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1905        read_unlock(&em_tree->lock);
1906
1907        BUG_ON(em->start > chunk_offset ||
1908               em->start + em->len < chunk_offset);
1909        map = (struct map_lookup *)em->bdev;
1910
1911        for (i = 0; i < map->num_stripes; i++) {
1912                ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
1913                                            map->stripes[i].physical);
1914                BUG_ON(ret);
1915
1916                if (map->stripes[i].dev) {
1917                        ret = btrfs_update_device(trans, map->stripes[i].dev);
1918                        BUG_ON(ret);
1919                }
1920        }
1921        ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
1922                               chunk_offset);
1923
1924        BUG_ON(ret);
1925
1926        if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
1927                ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
1928                BUG_ON(ret);
1929        }
1930
1931        ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
1932        BUG_ON(ret);
1933
1934        write_lock(&em_tree->lock);
1935        remove_extent_mapping(em_tree, em);
1936        write_unlock(&em_tree->lock);
1937
1938        kfree(map);
1939        em->bdev = NULL;
1940
1941        /* once for the tree */
1942        free_extent_map(em);
1943        /* once for us */
1944        free_extent_map(em);
1945
1946        unlock_chunks(root);
1947        btrfs_end_transaction(trans, root);
1948        return 0;
1949}
1950
1951static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
1952{
1953        struct btrfs_root *chunk_root = root->fs_info->chunk_root;
1954        struct btrfs_path *path;
1955        struct extent_buffer *leaf;
1956        struct btrfs_chunk *chunk;
1957        struct btrfs_key key;
1958        struct btrfs_key found_key;
1959        u64 chunk_tree = chunk_root->root_key.objectid;
1960        u64 chunk_type;
1961        bool retried = false;
1962        int failed = 0;
1963        int ret;
1964
1965        path = btrfs_alloc_path();
1966        if (!path)
1967                return -ENOMEM;
1968
1969again:
1970        key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1971        key.offset = (u64)-1;
1972        key.type = BTRFS_CHUNK_ITEM_KEY;
1973
1974        while (1) {
1975                ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
1976                if (ret < 0)
1977                        goto error;
1978                BUG_ON(ret == 0);
1979
1980                ret = btrfs_previous_item(chunk_root, path, key.objectid,
1981                                          key.type);
1982                if (ret < 0)
1983                        goto error;
1984                if (ret > 0)
1985                        break;
1986
1987                leaf = path->nodes[0];
1988                btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1989
1990                chunk = btrfs_item_ptr(leaf, path->slots[0],
1991                                       struct btrfs_chunk);
1992                chunk_type = btrfs_chunk_type(leaf, chunk);
1993                btrfs_release_path(chunk_root, path);
1994
1995                if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
1996                        ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
1997                                                   found_key.objectid,
1998                                                   found_key.offset);
1999                        if (ret == -ENOSPC)
2000                                failed++;
2001                        else if (ret)
2002                                BUG();
2003                }
2004
2005                if (found_key.offset == 0)
2006                        break;
2007                key.offset = found_key.offset - 1;
2008        }
2009        ret = 0;
2010        if (failed && !retried) {
2011                failed = 0;
2012                retried = true;
2013                goto again;
2014        } else if (failed && retried) {
2015                WARN_ON(1);
2016                ret = -ENOSPC;
2017        }
2018error:
2019        btrfs_free_path(path);
2020        return ret;
2021}
2022
2023static u64 div_factor(u64 num, int factor)
2024{
2025        if (factor == 10)
2026                return num;
2027        num *= factor;
2028        do_div(num, 10);
2029        return num;
2030}
2031
2032int btrfs_balance(struct btrfs_root *dev_root)
2033{
2034        int ret;
2035        struct list_head *devices = &dev_root->fs_info->fs_devices->devices;
2036        struct btrfs_device *device;
2037        u64 old_size;
2038        u64 size_to_free;
2039        struct btrfs_path *path;
2040        struct btrfs_key key;
2041        struct btrfs_root *chunk_root = dev_root->fs_info->chunk_root;
2042        struct btrfs_trans_handle *trans;
2043        struct btrfs_key found_key;
2044
2045        if (dev_root->fs_info->sb->s_flags & MS_RDONLY)
2046                return -EROFS;
2047
2048        if (!capable(CAP_SYS_ADMIN))
2049                return -EPERM;
2050
2051        mutex_lock(&dev_root->fs_info->volume_mutex);
2052        dev_root = dev_root->fs_info->dev_root;
2053
2054        /* step one make some room on all the devices */
2055        list_for_each_entry(device, devices, dev_list) {
2056                old_size = device->total_bytes;
2057                size_to_free = div_factor(old_size, 1);
2058                size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2059                if (!device->writeable ||
2060                    device->total_bytes - device->bytes_used > size_to_free)
2061                        continue;
2062
2063                ret = btrfs_shrink_device(device, old_size - size_to_free);
2064                if (ret == -ENOSPC)
2065                        break;
2066                BUG_ON(ret);
2067
2068                trans = btrfs_start_transaction(dev_root, 0);
2069                BUG_ON(IS_ERR(trans));
2070
2071                ret = btrfs_grow_device(trans, device, old_size);
2072                BUG_ON(ret);
2073
2074                btrfs_end_transaction(trans, dev_root);
2075        }
2076
2077        /* step two, relocate all the chunks */
2078        path = btrfs_alloc_path();
2079        BUG_ON(!path);
2080
2081        key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2082        key.offset = (u64)-1;
2083        key.type = BTRFS_CHUNK_ITEM_KEY;
2084
2085        while (1) {
2086                ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2087                if (ret < 0)
2088                        goto error;
2089
2090                /*
2091                 * this shouldn't happen, it means the last relocate
2092                 * failed
2093                 */
2094                if (ret == 0)
2095                        break;
2096
2097                ret = btrfs_previous_item(chunk_root, path, 0,
2098                                          BTRFS_CHUNK_ITEM_KEY);
2099                if (ret)
2100                        break;
2101
2102                btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2103                                      path->slots[0]);
2104                if (found_key.objectid != key.objectid)
2105                        break;
2106
2107                /* chunk zero is special */
2108                if (found_key.offset == 0)
2109                        break;
2110
2111                btrfs_release_path(chunk_root, path);
2112                ret = btrfs_relocate_chunk(chunk_root,
2113                                           chunk_root->root_key.objectid,
2114                                           found_key.objectid,
2115                                           found_key.offset);
2116                BUG_ON(ret && ret != -ENOSPC);
2117                key.offset = found_key.offset - 1;
2118        }
2119        ret = 0;
2120error:
2121        btrfs_free_path(path);
2122        mutex_unlock(&dev_root->fs_info->volume_mutex);
2123        return ret;
2124}
2125
2126/*
2127 * shrinking a device means finding all of the device extents past
2128 * the new size, and then following the back refs to the chunks.
2129 * The chunk relocation code actually frees the device extent
2130 */
2131int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
2132{
2133        struct btrfs_trans_handle *trans;
2134        struct btrfs_root *root = device->dev_root;
2135        struct btrfs_dev_extent *dev_extent = NULL;
2136        struct btrfs_path *path;
2137        u64 length;
2138        u64 chunk_tree;
2139        u64 chunk_objectid;
2140        u64 chunk_offset;
2141        int ret;
2142        int slot;
2143        int failed = 0;
2144        bool retried = false;
2145        struct extent_buffer *l;
2146        struct btrfs_key key;
2147        struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
2148        u64 old_total = btrfs_super_total_bytes(super_copy);
2149        u64 old_size = device->total_bytes;
2150        u64 diff = device->total_bytes - new_size;
2151
2152        if (new_size >= device->total_bytes)
2153                return -EINVAL;
2154
2155        path = btrfs_alloc_path();
2156        if (!path)
2157                return -ENOMEM;
2158
2159        path->reada = 2;
2160
2161        lock_chunks(root);
2162
2163        device->total_bytes = new_size;
2164        if (device->writeable)
2165                device->fs_devices->total_rw_bytes -= diff;
2166        unlock_chunks(root);
2167
2168again:
2169        key.objectid = device->devid;
2170        key.offset = (u64)-1;
2171        key.type = BTRFS_DEV_EXTENT_KEY;
2172
2173        while (1) {
2174                ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2175                if (ret < 0)
2176                        goto done;
2177
2178                ret = btrfs_previous_item(root, path, 0, key.type);
2179                if (ret < 0)
2180                        goto done;
2181                if (ret) {
2182                        ret = 0;
2183                        btrfs_release_path(root, path);
2184                        break;
2185                }
2186
2187                l = path->nodes[0];
2188                slot = path->slots[0];
2189                btrfs_item_key_to_cpu(l, &key, path->slots[0]);
2190
2191                if (key.objectid != device->devid) {
2192                        btrfs_release_path(root, path);
2193                        break;
2194                }
2195
2196                dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
2197                length = btrfs_dev_extent_length(l, dev_extent);
2198
2199                if (key.offset + length <= new_size) {
2200                        btrfs_release_path(root, path);
2201                        break;
2202                }
2203
2204                chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
2205                chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
2206                chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
2207                btrfs_release_path(root, path);
2208
2209                ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
2210                                           chunk_offset);
2211                if (ret && ret != -ENOSPC)
2212                        goto done;
2213                if (ret == -ENOSPC)
2214                        failed++;
2215                key.offset -= 1;
2216        }
2217
2218        if (failed && !retried) {
2219                failed = 0;
2220                retried = true;
2221                goto again;
2222        } else if (failed && retried) {
2223                ret = -ENOSPC;
2224                lock_chunks(root);
2225
2226                device->total_bytes = old_size;
2227                if (device->writeable)
2228                        device->fs_devices->total_rw_bytes += diff;
2229                unlock_chunks(root);
2230                goto done;
2231        }
2232
2233        /* Shrinking succeeded, else we would be at "done". */
2234        trans = btrfs_start_transaction(root, 0);
2235        if (IS_ERR(trans)) {
2236                ret = PTR_ERR(trans);
2237                goto done;
2238        }
2239
2240        lock_chunks(root);
2241
2242        device->disk_total_bytes = new_size;
2243        /* Now btrfs_update_device() will change the on-disk size. */
2244        ret = btrfs_update_device(trans, device);
2245        if (ret) {
2246                unlock_chunks(root);
2247                btrfs_end_transaction(trans, root);
2248                goto done;
2249        }
2250        WARN_ON(diff > old_total);
2251        btrfs_set_super_total_bytes(super_copy, old_total - diff);
2252        unlock_chunks(root);
2253        btrfs_end_transaction(trans, root);
2254done:
2255        btrfs_free_path(path);
2256        return ret;
2257}
2258
2259static int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
2260                           struct btrfs_root *root,
2261                           struct btrfs_key *key,
2262                           struct btrfs_chunk *chunk, int item_size)
2263{
2264        struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
2265        struct btrfs_disk_key disk_key;
2266        u32 array_size;
2267        u8 *ptr;
2268
2269        array_size = btrfs_super_sys_array_size(super_copy);
2270        if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
2271                return -EFBIG;
2272
2273        ptr = super_copy->sys_chunk_array + array_size;
2274        btrfs_cpu_key_to_disk(&disk_key, key);
2275        memcpy(ptr, &disk_key, sizeof(disk_key));
2276        ptr += sizeof(disk_key);
2277        memcpy(ptr, chunk, item_size);
2278        item_size += sizeof(disk_key);
2279        btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
2280        return 0;
2281}
2282
2283static noinline u64 chunk_bytes_by_type(u64 type, u64 calc_size,
2284                                        int num_stripes, int sub_stripes)
2285{
2286        if (type & (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP))
2287                return calc_size;
2288        else if (type & BTRFS_BLOCK_GROUP_RAID10)
2289                return calc_size * (num_stripes / sub_stripes);
2290        else
2291                return calc_size * num_stripes;
2292}
2293
2294/* Used to sort the devices by max_avail(descending sort) */
2295int btrfs_cmp_device_free_bytes(const void *dev_info1, const void *dev_info2)
2296{
2297        if (((struct btrfs_device_info *)dev_info1)->max_avail >
2298            ((struct btrfs_device_info *)dev_info2)->max_avail)
2299                return -1;
2300        else if (((struct btrfs_device_info *)dev_info1)->max_avail <
2301                 ((struct btrfs_device_info *)dev_info2)->max_avail)
2302                return 1;
2303        else
2304                return 0;
2305}
2306
2307static int __btrfs_calc_nstripes(struct btrfs_fs_devices *fs_devices, u64 type,
2308                                 int *num_stripes, int *min_stripes,
2309                                 int *sub_stripes)
2310{
2311        *num_stripes = 1;
2312        *min_stripes = 1;
2313        *sub_stripes = 0;
2314
2315        if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
2316                *num_stripes = fs_devices->rw_devices;
2317                *min_stripes = 2;
2318        }
2319        if (type & (BTRFS_BLOCK_GROUP_DUP)) {
2320                *num_stripes = 2;
2321                *min_stripes = 2;
2322        }
2323        if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
2324                if (fs_devices->rw_devices < 2)
2325                        return -ENOSPC;
2326                *num_stripes = 2;
2327                *min_stripes = 2;
2328        }
2329        if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
2330                *num_stripes = fs_devices->rw_devices;
2331                if (*num_stripes < 4)
2332                        return -ENOSPC;
2333                *num_stripes &= ~(u32)1;
2334                *sub_stripes = 2;
2335                *min_stripes = 4;
2336        }
2337
2338        return 0;
2339}
2340
2341static u64 __btrfs_calc_stripe_size(struct btrfs_fs_devices *fs_devices,
2342                                    u64 proposed_size, u64 type,
2343                                    int num_stripes, int small_stripe)
2344{
2345        int min_stripe_size = 1 * 1024 * 1024;
2346        u64 calc_size = proposed_size;
2347        u64 max_chunk_size = calc_size;
2348        int ncopies = 1;
2349
2350        if (type & (BTRFS_BLOCK_GROUP_RAID1 |
2351                    BTRFS_BLOCK_GROUP_DUP |
2352                    BTRFS_BLOCK_GROUP_RAID10))
2353                ncopies = 2;
2354
2355        if (type & BTRFS_BLOCK_GROUP_DATA) {
2356                max_chunk_size = 10 * calc_size;
2357                min_stripe_size = 64 * 1024 * 1024;
2358        } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
2359                max_chunk_size = 256 * 1024 * 1024;
2360                min_stripe_size = 32 * 1024 * 1024;
2361        } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
2362                calc_size = 8 * 1024 * 1024;
2363                max_chunk_size = calc_size * 2;
2364                min_stripe_size = 1 * 1024 * 1024;
2365        }
2366
2367        /* we don't want a chunk larger than 10% of writeable space */
2368        max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
2369                             max_chunk_size);
2370
2371        if (calc_size * num_stripes > max_chunk_size * ncopies) {
2372                calc_size = max_chunk_size * ncopies;
2373                do_div(calc_size, num_stripes);
2374                do_div(calc_size, BTRFS_STRIPE_LEN);
2375                calc_size *= BTRFS_STRIPE_LEN;
2376        }
2377
2378        /* we don't want tiny stripes */
2379        if (!small_stripe)
2380                calc_size = max_t(u64, min_stripe_size, calc_size);
2381
2382        /*
2383         * we're about to do_div by the BTRFS_STRIPE_LEN so lets make sure
2384         * we end up with something bigger than a stripe
2385         */
2386        calc_size = max_t(u64, calc_size, BTRFS_STRIPE_LEN);
2387
2388        do_div(calc_size, BTRFS_STRIPE_LEN);
2389        calc_size *= BTRFS_STRIPE_LEN;
2390
2391        return calc_size;
2392}
2393
2394static struct map_lookup *__shrink_map_lookup_stripes(struct map_lookup *map,
2395                                                      int num_stripes)
2396{
2397        struct map_lookup *new;
2398        size_t len = map_lookup_size(num_stripes);
2399
2400        BUG_ON(map->num_stripes < num_stripes);
2401
2402        if (map->num_stripes == num_stripes)
2403                return map;
2404
2405        new = kmalloc(len, GFP_NOFS);
2406        if (!new) {
2407                /* just change map->num_stripes */
2408                map->num_stripes = num_stripes;
2409                return map;
2410        }
2411
2412        memcpy(new, map, len);
2413        new->num_stripes = num_stripes;
2414        kfree(map);
2415        return new;
2416}
2417
2418/*
2419 * helper to allocate device space from btrfs_device_info, in which we stored
2420 * max free space information of every device. It is used when we can not
2421 * allocate chunks by default size.
2422 *
2423 * By this helper, we can allocate a new chunk as larger as possible.
2424 */
2425static int __btrfs_alloc_tiny_space(struct btrfs_trans_handle *trans,
2426                                    struct btrfs_fs_devices *fs_devices,
2427                                    struct btrfs_device_info *devices,
2428                                    int nr_device, u64 type,
2429                                    struct map_lookup **map_lookup,
2430                                    int min_stripes, u64 *stripe_size)
2431{
2432        int i, index, sort_again = 0;
2433        int min_devices = min_stripes;
2434        u64 max_avail, min_free;
2435        struct map_lookup *map = *map_lookup;
2436        int ret;
2437
2438        if (nr_device < min_stripes)
2439                return -ENOSPC;
2440
2441        btrfs_descending_sort_devices(devices, nr_device);
2442
2443        max_avail = devices[0].max_avail;
2444        if (!max_avail)
2445                return -ENOSPC;
2446
2447        for (i = 0; i < nr_device; i++) {
2448                /*
2449                 * if dev_offset = 0, it means the free space of this device
2450                 * is less than what we need, and we didn't search max avail
2451                 * extent on this device, so do it now.
2452                 */
2453                if (!devices[i].dev_offset) {
2454                        ret = find_free_dev_extent(trans, devices[i].dev,
2455                                                   max_avail,
2456                                                   &devices[i].dev_offset,
2457                                                   &devices[i].max_avail);
2458                        if (ret != 0 && ret != -ENOSPC)
2459                                return ret;
2460                        sort_again = 1;
2461                }
2462        }
2463
2464        /* we update the max avail free extent of each devices, sort again */
2465        if (sort_again)
2466                btrfs_descending_sort_devices(devices, nr_device);
2467
2468        if (type & BTRFS_BLOCK_GROUP_DUP)
2469                min_devices = 1;
2470
2471        if (!devices[min_devices - 1].max_avail)
2472                return -ENOSPC;
2473
2474        max_avail = devices[min_devices - 1].max_avail;
2475        if (type & BTRFS_BLOCK_GROUP_DUP)
2476                do_div(max_avail, 2);
2477
2478        max_avail = __btrfs_calc_stripe_size(fs_devices, max_avail, type,
2479                                             min_stripes, 1);
2480        if (type & BTRFS_BLOCK_GROUP_DUP)
2481                min_free = max_avail * 2;
2482        else
2483                min_free = max_avail;
2484
2485        if (min_free > devices[min_devices - 1].max_avail)
2486                return -ENOSPC;
2487
2488        map = __shrink_map_lookup_stripes(map, min_stripes);
2489        *stripe_size = max_avail;
2490
2491        index = 0;
2492        for (i = 0; i < min_stripes; i++) {
2493                map->stripes[i].dev = devices[index].dev;
2494                map->stripes[i].physical = devices[index].dev_offset;
2495                if (type & BTRFS_BLOCK_GROUP_DUP) {
2496                        i++;
2497                        map->stripes[i].dev = devices[index].dev;
2498                        map->stripes[i].physical = devices[index].dev_offset +
2499                                                   max_avail;
2500                }
2501                index++;
2502        }
2503        *map_lookup = map;
2504
2505        return 0;
2506}
2507
2508static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
2509                               struct btrfs_root *extent_root,
2510                               struct map_lookup **map_ret,
2511                               u64 *num_bytes, u64 *stripe_size,
2512                               u64 start, u64 type)
2513{
2514        struct btrfs_fs_info *info = extent_root->fs_info;
2515        struct btrfs_device *device = NULL;
2516        struct btrfs_fs_devices *fs_devices = info->fs_devices;
2517        struct list_head *cur;
2518        struct map_lookup *map;
2519        struct extent_map_tree *em_tree;
2520        struct extent_map *em;
2521        struct btrfs_device_info *devices_info;
2522        struct list_head private_devs;
2523        u64 calc_size = 1024 * 1024 * 1024;
2524        u64 min_free;
2525        u64 avail;
2526        u64 dev_offset;
2527        int num_stripes;
2528        int min_stripes;
2529        int sub_stripes;
2530        int min_devices;        /* the min number of devices we need */
2531        int i;
2532        int ret;
2533        int index;
2534
2535        if ((type & BTRFS_BLOCK_GROUP_RAID1) &&
2536            (type & BTRFS_BLOCK_GROUP_DUP)) {
2537                WARN_ON(1);
2538                type &= ~BTRFS_BLOCK_GROUP_DUP;
2539        }
2540        if (list_empty(&fs_devices->alloc_list))
2541                return -ENOSPC;
2542
2543        ret = __btrfs_calc_nstripes(fs_devices, type, &num_stripes,
2544                                    &min_stripes, &sub_stripes);
2545        if (ret)
2546                return ret;
2547
2548        devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
2549                               GFP_NOFS);
2550        if (!devices_info)
2551                return -ENOMEM;
2552
2553        map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
2554        if (!map) {
2555                ret = -ENOMEM;
2556                goto error;
2557        }
2558        map->num_stripes = num_stripes;
2559
2560        cur = fs_devices->alloc_list.next;
2561        index = 0;
2562        i = 0;
2563
2564        calc_size = __btrfs_calc_stripe_size(fs_devices, calc_size, type,
2565                                             num_stripes, 0);
2566
2567        if (type & BTRFS_BLOCK_GROUP_DUP) {
2568                min_free = calc_size * 2;
2569                min_devices = 1;
2570        } else {
2571                min_free = calc_size;
2572                min_devices = min_stripes;
2573        }
2574
2575        INIT_LIST_HEAD(&private_devs);
2576        while (index < num_stripes) {
2577                device = list_entry(cur, struct btrfs_device, dev_alloc_list);
2578                BUG_ON(!device->writeable);
2579                if (device->total_bytes > device->bytes_used)
2580                        avail = device->total_bytes - device->bytes_used;
2581                else
2582                        avail = 0;
2583                cur = cur->next;
2584
2585                if (device->in_fs_metadata && avail >= min_free) {
2586                        ret = find_free_dev_extent(trans, device, min_free,
2587                                                   &devices_info[i].dev_offset,
2588                                                   &devices_info[i].max_avail);
2589                        if (ret == 0) {
2590                                list_move_tail(&device->dev_alloc_list,
2591                                               &private_devs);
2592                                map->stripes[index].dev = device;
2593                                map->stripes[index].physical =
2594                                                devices_info[i].dev_offset;
2595                                index++;
2596                                if (type & BTRFS_BLOCK_GROUP_DUP) {
2597                                        map->stripes[index].dev = device;
2598                                        map->stripes[index].physical =
2599                                                devices_info[i].dev_offset +
2600                                                calc_size;
2601                                        index++;
2602                                }
2603                        } else if (ret != -ENOSPC)
2604                                goto error;
2605
2606                        devices_info[i].dev = device;
2607                        i++;
2608                } else if (device->in_fs_metadata &&
2609                           avail >= BTRFS_STRIPE_LEN) {
2610                        devices_info[i].dev = device;
2611                        devices_info[i].max_avail = avail;
2612                        i++;
2613                }
2614
2615                if (cur == &fs_devices->alloc_list)
2616                        break;
2617        }
2618
2619        list_splice(&private_devs, &fs_devices->alloc_list);
2620        if (index < num_stripes) {
2621                if (index >= min_stripes) {
2622                        num_stripes = index;
2623                        if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
2624                                num_stripes /= sub_stripes;
2625                                num_stripes *= sub_stripes;
2626                        }
2627
2628                        map = __shrink_map_lookup_stripes(map, num_stripes);
2629                } else if (i >= min_devices) {
2630                        ret = __btrfs_alloc_tiny_space(trans, fs_devices,
2631                                                       devices_info, i, type,
2632                                                       &map, min_stripes,
2633                                                       &calc_size);
2634                        if (ret)
2635                                goto error;
2636                } else {
2637                        ret = -ENOSPC;
2638                        goto error;
2639                }
2640        }
2641        map->sector_size = extent_root->sectorsize;
2642        map->stripe_len = BTRFS_STRIPE_LEN;
2643        map->io_align = BTRFS_STRIPE_LEN;
2644        map->io_width = BTRFS_STRIPE_LEN;
2645        map->type = type;
2646        map->sub_stripes = sub_stripes;
2647
2648        *map_ret = map;
2649        *stripe_size = calc_size;
2650        *num_bytes = chunk_bytes_by_type(type, calc_size,
2651                                         map->num_stripes, sub_stripes);
2652
2653        em = alloc_extent_map(GFP_NOFS);
2654        if (!em) {
2655                ret = -ENOMEM;
2656                goto error;
2657        }
2658        em->bdev = (struct block_device *)map;
2659        em->start = start;
2660        em->len = *num_bytes;
2661        em->block_start = 0;
2662        em->block_len = em->len;
2663
2664        em_tree = &extent_root->fs_info->mapping_tree.map_tree;
2665        write_lock(&em_tree->lock);
2666        ret = add_extent_mapping(em_tree, em);
2667        write_unlock(&em_tree->lock);
2668        BUG_ON(ret);
2669        free_extent_map(em);
2670
2671        ret = btrfs_make_block_group(trans, extent_root, 0, type,
2672                                     BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2673                                     start, *num_bytes);
2674        BUG_ON(ret);
2675
2676        index = 0;
2677        while (index < map->num_stripes) {
2678                device = map->stripes[index].dev;
2679                dev_offset = map->stripes[index].physical;
2680
2681                ret = btrfs_alloc_dev_extent(trans, device,
2682                                info->chunk_root->root_key.objectid,
2683                                BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2684                                start, dev_offset, calc_size);
2685                BUG_ON(ret);
2686                index++;
2687        }
2688
2689        kfree(devices_info);
2690        return 0;
2691
2692error:
2693        kfree(map);
2694        kfree(devices_info);
2695        return ret;
2696}
2697
2698static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
2699                                struct btrfs_root *extent_root,
2700                                struct map_lookup *map, u64 chunk_offset,
2701                                u64 chunk_size, u64 stripe_size)
2702{
2703        u64 dev_offset;
2704        struct btrfs_key key;
2705        struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
2706        struct btrfs_device *device;
2707        struct btrfs_chunk *chunk;
2708        struct btrfs_stripe *stripe;
2709        size_t item_size = btrfs_chunk_item_size(map->num_stripes);
2710        int index = 0;
2711        int ret;
2712
2713        chunk = kzalloc(item_size, GFP_NOFS);
2714        if (!chunk)
2715                return -ENOMEM;
2716
2717        index = 0;
2718        while (index < map->num_stripes) {
2719                device = map->stripes[index].dev;
2720                device->bytes_used += stripe_size;
2721                ret = btrfs_update_device(trans, device);
2722                BUG_ON(ret);
2723                index++;
2724        }
2725
2726        index = 0;
2727        stripe = &chunk->stripe;
2728        while (index < map->num_stripes) {
2729                device = map->stripes[index].dev;
2730                dev_offset = map->stripes[index].physical;
2731
2732                btrfs_set_stack_stripe_devid(stripe, device->devid);
2733                btrfs_set_stack_stripe_offset(stripe, dev_offset);
2734                memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
2735                stripe++;
2736                index++;
2737        }
2738
2739        btrfs_set_stack_chunk_length(chunk, chunk_size);
2740        btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
2741        btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
2742        btrfs_set_stack_chunk_type(chunk, map->type);
2743        btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
2744        btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
2745        btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
2746        btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
2747        btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
2748
2749        key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2750        key.type = BTRFS_CHUNK_ITEM_KEY;
2751        key.offset = chunk_offset;
2752
2753        ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
2754        BUG_ON(ret);
2755
2756        if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2757                ret = btrfs_add_system_chunk(trans, chunk_root, &key, chunk,
2758                                             item_size);
2759                BUG_ON(ret);
2760        }
2761        kfree(chunk);
2762        return 0;
2763}
2764
2765/*
2766 * Chunk allocation falls into two parts. The first part does works
2767 * that make the new allocated chunk useable, but not do any operation
2768 * that modifies the chunk tree. The second part does the works that
2769 * require modifying the chunk tree. This division is important for the
2770 * bootstrap process of adding storage to a seed btrfs.
2771 */
2772int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
2773                      struct btrfs_root *extent_root, u64 type)
2774{
2775        u64 chunk_offset;
2776        u64 chunk_size;
2777        u64 stripe_size;
2778        struct map_lookup *map;
2779        struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
2780        int ret;
2781
2782        ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2783                              &chunk_offset);
2784        if (ret)
2785                return ret;
2786
2787        ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
2788                                  &stripe_size, chunk_offset, type);
2789        if (ret)
2790                return ret;
2791
2792        ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
2793                                   chunk_size, stripe_size);
2794        BUG_ON(ret);
2795        return 0;
2796}
2797
2798static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
2799                                         struct btrfs_root *root,
2800                                         struct btrfs_device *device)
2801{
2802        u64 chunk_offset;
2803        u64 sys_chunk_offset;
2804        u64 chunk_size;
2805        u64 sys_chunk_size;
2806        u64 stripe_size;
2807        u64 sys_stripe_size;
2808        u64 alloc_profile;
2809        struct map_lookup *map;
2810        struct map_lookup *sys_map;
2811        struct btrfs_fs_info *fs_info = root->fs_info;
2812        struct btrfs_root *extent_root = fs_info->extent_root;
2813        int ret;
2814
2815        ret = find_next_chunk(fs_info->chunk_root,
2816                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
2817        BUG_ON(ret);
2818
2819        alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
2820                        (fs_info->metadata_alloc_profile &
2821                         fs_info->avail_metadata_alloc_bits);
2822        alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
2823
2824        ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
2825                                  &stripe_size, chunk_offset, alloc_profile);
2826        BUG_ON(ret);
2827
2828        sys_chunk_offset = chunk_offset + chunk_size;
2829
2830        alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
2831                        (fs_info->system_alloc_profile &
2832                         fs_info->avail_system_alloc_bits);
2833        alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
2834
2835        ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
2836                                  &sys_chunk_size, &sys_stripe_size,
2837                                  sys_chunk_offset, alloc_profile);
2838        BUG_ON(ret);
2839
2840        ret = btrfs_add_device(trans, fs_info->chunk_root, device);
2841        BUG_ON(ret);
2842
2843        /*
2844         * Modifying chunk tree needs allocating new blocks from both
2845         * system block group and metadata block group. So we only can
2846         * do operations require modifying the chunk tree after both
2847         * block groups were created.
2848         */
2849        ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
2850                                   chunk_size, stripe_size);
2851        BUG_ON(ret);
2852
2853        ret = __finish_chunk_alloc(trans, extent_root, sys_map,
2854                                   sys_chunk_offset, sys_chunk_size,
2855                                   sys_stripe_size);
2856        BUG_ON(ret);
2857        return 0;
2858}
2859
2860int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
2861{
2862        struct extent_map *em;
2863        struct map_lookup *map;
2864        struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
2865        int readonly = 0;
2866        int i;
2867
2868        read_lock(&map_tree->map_tree.lock);
2869        em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
2870        read_unlock(&map_tree->map_tree.lock);
2871        if (!em)
2872                return 1;
2873
2874        if (btrfs_test_opt(root, DEGRADED)) {
2875                free_extent_map(em);
2876                return 0;
2877        }
2878
2879        map = (struct map_lookup *)em->bdev;
2880        for (i = 0; i < map->num_stripes; i++) {
2881                if (!map->stripes[i].dev->writeable) {
2882                        readonly = 1;
2883                        break;
2884                }
2885        }
2886        free_extent_map(em);
2887        return readonly;
2888}
2889
2890void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
2891{
2892        extent_map_tree_init(&tree->map_tree, GFP_NOFS);
2893}
2894
2895void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
2896{
2897        struct extent_map *em;
2898
2899        while (1) {
2900                write_lock(&tree->map_tree.lock);
2901                em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
2902                if (em)
2903                        remove_extent_mapping(&tree->map_tree, em);
2904                write_unlock(&tree->map_tree.lock);
2905                if (!em)
2906                        break;
2907                kfree(em->bdev);
2908                /* once for us */
2909                free_extent_map(em);
2910                /* once for the tree */
2911                free_extent_map(em);
2912        }
2913}
2914
2915int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
2916{
2917        struct extent_map *em;
2918        struct map_lookup *map;
2919        struct extent_map_tree *em_tree = &map_tree->map_tree;
2920        int ret;
2921
2922        read_lock(&em_tree->lock);
2923        em = lookup_extent_mapping(em_tree, logical, len);
2924        read_unlock(&em_tree->lock);
2925        BUG_ON(!em);
2926
2927        BUG_ON(em->start > logical || em->start + em->len < logical);
2928        map = (struct map_lookup *)em->bdev;
2929        if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
2930                ret = map->num_stripes;
2931        else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
2932                ret = map->sub_stripes;
2933        else
2934                ret = 1;
2935        free_extent_map(em);
2936        return ret;
2937}
2938
2939static int find_live_mirror(struct map_lookup *map, int first, int num,
2940                            int optimal)
2941{
2942        int i;
2943        if (map->stripes[optimal].dev->bdev)
2944                return optimal;
2945        for (i = first; i < first + num; i++) {
2946                if (map->stripes[i].dev->bdev)
2947                        return i;
2948        }
2949        /* we couldn't find one that doesn't fail.  Just return something
2950         * and the io error handling code will clean up eventually
2951         */
2952        return optimal;
2953}
2954
2955static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
2956                             u64 logical, u64 *length,
2957                             struct btrfs_multi_bio **multi_ret,
2958                             int mirror_num, struct page *unplug_page)
2959{
2960        struct extent_map *em;
2961        struct map_lookup *map;
2962        struct extent_map_tree *em_tree = &map_tree->map_tree;
2963        u64 offset;
2964        u64 stripe_offset;
2965        u64 stripe_nr;
2966        int stripes_allocated = 8;
2967        int stripes_required = 1;
2968        int stripe_index;
2969        int i;
2970        int num_stripes;
2971        int max_errors = 0;
2972        struct btrfs_multi_bio *multi = NULL;
2973
2974        if (multi_ret && !(rw & REQ_WRITE))
2975                stripes_allocated = 1;
2976again:
2977        if (multi_ret) {
2978                multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
2979                                GFP_NOFS);
2980                if (!multi)
2981                        return -ENOMEM;
2982
2983                atomic_set(&multi->error, 0);
2984        }
2985
2986        read_lock(&em_tree->lock);
2987        em = lookup_extent_mapping(em_tree, logical, *length);
2988        read_unlock(&em_tree->lock);
2989
2990        if (!em && unplug_page) {
2991                kfree(multi);
2992                return 0;
2993        }
2994
2995        if (!em) {
2996                printk(KERN_CRIT "unable to find logical %llu len %llu\n",
2997                       (unsigned long long)logical,
2998                       (unsigned long long)*length);
2999                BUG();
3000        }
3001
3002        BUG_ON(em->start > logical || em->start + em->len < logical);
3003        map = (struct map_lookup *)em->bdev;
3004        offset = logical - em->start;
3005
3006        if (mirror_num > map->num_stripes)
3007                mirror_num = 0;
3008
3009        /* if our multi bio struct is too small, back off and try again */
3010        if (rw & REQ_WRITE) {
3011                if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
3012                                 BTRFS_BLOCK_GROUP_DUP)) {
3013                        stripes_required = map->num_stripes;
3014                        max_errors = 1;
3015                } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3016                        stripes_required = map->sub_stripes;
3017                        max_errors = 1;
3018                }
3019        }
3020        if (multi_ret && (rw & REQ_WRITE) &&
3021            stripes_allocated < stripes_required) {
3022                stripes_allocated = map->num_stripes;
3023                free_extent_map(em);
3024                kfree(multi);
3025                goto again;
3026        }
3027        stripe_nr = offset;
3028        /*
3029         * stripe_nr counts the total number of stripes we have to stride
3030         * to get to this block
3031         */
3032        do_div(stripe_nr, map->stripe_len);
3033
3034        stripe_offset = stripe_nr * map->stripe_len;
3035        BUG_ON(offset < stripe_offset);
3036
3037        /* stripe_offset is the offset of this block in its stripe*/
3038        stripe_offset = offset - stripe_offset;
3039
3040        if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
3041                         BTRFS_BLOCK_GROUP_RAID10 |
3042                         BTRFS_BLOCK_GROUP_DUP)) {
3043                /* we limit the length of each bio to what fits in a stripe */
3044                *length = min_t(u64, em->len - offset,
3045                              map->stripe_len - stripe_offset);
3046        } else {
3047                *length = em->len - offset;
3048        }
3049
3050        if (!multi_ret && !unplug_page)
3051                goto out;
3052
3053        num_stripes = 1;
3054        stripe_index = 0;
3055        if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
3056                if (unplug_page || (rw & REQ_WRITE))
3057                        num_stripes = map->num_stripes;
3058                else if (mirror_num)
3059                        stripe_index = mirror_num - 1;
3060                else {
3061                        stripe_index = find_live_mirror(map, 0,
3062                                            map->num_stripes,
3063                                            current->pid % map->num_stripes);
3064                }
3065
3066        } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
3067                if (rw & REQ_WRITE)
3068                        num_stripes = map->num_stripes;
3069                else if (mirror_num)
3070                        stripe_index = mirror_num - 1;
3071
3072        } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3073                int factor = map->num_stripes / map->sub_stripes;
3074
3075                stripe_index = do_div(stripe_nr, factor);
3076                stripe_index *= map->sub_stripes;
3077
3078                if (unplug_page || (rw & REQ_WRITE))
3079                        num_stripes = map->sub_stripes;
3080                else if (mirror_num)
3081                        stripe_index += mirror_num - 1;
3082                else {
3083                        stripe_index = find_live_mirror(map, stripe_index,
3084                                              map->sub_stripes, stripe_index +
3085                                              current->pid % map->sub_stripes);
3086                }
3087        } else {
3088                /*
3089                 * after this do_div call, stripe_nr is the number of stripes
3090                 * on this device we have to walk to find the data, and
3091                 * stripe_index is the number of our device in the stripe array
3092                 */
3093                stripe_index = do_div(stripe_nr, map->num_stripes);
3094        }
3095        BUG_ON(stripe_index >= map->num_stripes);
3096
3097        for (i = 0; i < num_stripes; i++) {
3098                if (unplug_page) {
3099                        struct btrfs_device *device;
3100                        struct backing_dev_info *bdi;
3101
3102                        device = map->stripes[stripe_index].dev;
3103                        if (device->bdev) {
3104                                bdi = blk_get_backing_dev_info(device->bdev);
3105                                if (bdi->unplug_io_fn)
3106                                        bdi->unplug_io_fn(bdi, unplug_page);
3107                        }
3108                } else {
3109                        multi->stripes[i].physical =
3110                                map->stripes[stripe_index].physical +
3111                                stripe_offset + stripe_nr * map->stripe_len;
3112                        multi->stripes[i].dev = map->stripes[stripe_index].dev;
3113                }
3114                stripe_index++;
3115        }
3116        if (multi_ret) {
3117                *multi_ret = multi;
3118                multi->num_stripes = num_stripes;
3119                multi->max_errors = max_errors;
3120        }
3121out:
3122        free_extent_map(em);
3123        return 0;
3124}
3125
3126int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3127                      u64 logical, u64 *length,
3128                      struct btrfs_multi_bio **multi_ret, int mirror_num)
3129{
3130        return __btrfs_map_block(map_tree, rw, logical, length, multi_ret,
3131                                 mirror_num, NULL);
3132}
3133
3134int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
3135                     u64 chunk_start, u64 physical, u64 devid,
3136                     u64 **logical, int *naddrs, int *stripe_len)
3137{
3138        struct extent_map_tree *em_tree = &map_tree->map_tree;
3139        struct extent_map *em;
3140        struct map_lookup *map;
3141        u64 *buf;
3142        u64 bytenr;
3143        u64 length;
3144        u64 stripe_nr;
3145        int i, j, nr = 0;
3146
3147        read_lock(&em_tree->lock);
3148        em = lookup_extent_mapping(em_tree, chunk_start, 1);
3149        read_unlock(&em_tree->lock);
3150
3151        BUG_ON(!em || em->start != chunk_start);
3152        map = (struct map_lookup *)em->bdev;
3153
3154        length = em->len;
3155        if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3156                do_div(length, map->num_stripes / map->sub_stripes);
3157        else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3158                do_div(length, map->num_stripes);
3159
3160        buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
3161        BUG_ON(!buf);
3162
3163        for (i = 0; i < map->num_stripes; i++) {
3164                if (devid && map->stripes[i].dev->devid != devid)
3165                        continue;
3166                if (map->stripes[i].physical > physical ||
3167                    map->stripes[i].physical + length <= physical)
3168                        continue;
3169
3170                stripe_nr = physical - map->stripes[i].physical;
3171                do_div(stripe_nr, map->stripe_len);
3172
3173                if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3174                        stripe_nr = stripe_nr * map->num_stripes + i;
3175                        do_div(stripe_nr, map->sub_stripes);
3176                } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3177                        stripe_nr = stripe_nr * map->num_stripes + i;
3178                }
3179                bytenr = chunk_start + stripe_nr * map->stripe_len;
3180                WARN_ON(nr >= map->num_stripes);
3181                for (j = 0; j < nr; j++) {
3182                        if (buf[j] == bytenr)
3183                                break;
3184                }
3185                if (j == nr) {
3186                        WARN_ON(nr >= map->num_stripes);
3187                        buf[nr++] = bytenr;
3188                }
3189        }
3190
3191        *logical = buf;
3192        *naddrs = nr;
3193        *stripe_len = map->stripe_len;
3194
3195        free_extent_map(em);
3196        return 0;
3197}
3198
3199int btrfs_unplug_page(struct btrfs_mapping_tree *map_tree,
3200                      u64 logical, struct page *page)
3201{
3202        u64 length = PAGE_CACHE_SIZE;
3203        return __btrfs_map_block(map_tree, READ, logical, &length,
3204                                 NULL, 0, page);
3205}
3206
3207static void end_bio_multi_stripe(struct bio *bio, int err)
3208{
3209        struct btrfs_multi_bio *multi = bio->bi_private;
3210        int is_orig_bio = 0;
3211
3212        if (err)
3213                atomic_inc(&multi->error);
3214
3215        if (bio == multi->orig_bio)
3216                is_orig_bio = 1;
3217
3218        if (atomic_dec_and_test(&multi->stripes_pending)) {
3219                if (!is_orig_bio) {
3220                        bio_put(bio);
3221                        bio = multi->orig_bio;
3222                }
3223                bio->bi_private = multi->private;
3224                bio->bi_end_io = multi->end_io;
3225                /* only send an error to the higher layers if it is
3226                 * beyond the tolerance of the multi-bio
3227                 */
3228                if (atomic_read(&multi->error) > multi->max_errors) {
3229                        err = -EIO;
3230                } else if (err) {
3231                        /*
3232                         * this bio is actually up to date, we didn't
3233                         * go over the max number of errors
3234                         */
3235                        set_bit(BIO_UPTODATE, &bio->bi_flags);
3236                        err = 0;
3237                }
3238                kfree(multi);
3239
3240                bio_endio(bio, err);
3241        } else if (!is_orig_bio) {
3242                bio_put(bio);
3243        }
3244}
3245
3246struct async_sched {
3247        struct bio *bio;
3248        int rw;
3249        struct btrfs_fs_info *info;
3250        struct btrfs_work work;
3251};
3252
3253/*
3254 * see run_scheduled_bios for a description of why bios are collected for
3255 * async submit.
3256 *
3257 * This will add one bio to the pending list for a device and make sure
3258 * the work struct is scheduled.
3259 */
3260static noinline int schedule_bio(struct btrfs_root *root,
3261                                 struct btrfs_device *device,
3262                                 int rw, struct bio *bio)
3263{
3264        int should_queue = 1;
3265        struct btrfs_pending_bios *pending_bios;
3266
3267        /* don't bother with additional async steps for reads, right now */
3268        if (!(rw & REQ_WRITE)) {
3269                bio_get(bio);
3270                submit_bio(rw, bio);
3271                bio_put(bio);
3272                return 0;
3273        }
3274
3275        /*
3276         * nr_async_bios allows us to reliably return congestion to the
3277         * higher layers.  Otherwise, the async bio makes it appear we have
3278         * made progress against dirty pages when we've really just put it
3279         * on a queue for later
3280         */
3281        atomic_inc(&root->fs_info->nr_async_bios);
3282        WARN_ON(bio->bi_next);
3283        bio->bi_next = NULL;
3284        bio->bi_rw |= rw;
3285
3286        spin_lock(&device->io_lock);
3287        if (bio->bi_rw & REQ_SYNC)
3288                pending_bios = &device->pending_sync_bios;
3289        else
3290                pending_bios = &device->pending_bios;
3291
3292        if (pending_bios->tail)
3293                pending_bios->tail->bi_next = bio;
3294
3295        pending_bios->tail = bio;
3296        if (!pending_bios->head)
3297                pending_bios->head = bio;
3298        if (device->running_pending)
3299                should_queue = 0;
3300
3301        spin_unlock(&device->io_lock);
3302
3303        if (should_queue)
3304                btrfs_queue_worker(&root->fs_info->submit_workers,
3305                                   &device->work);
3306        return 0;
3307}
3308
3309int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
3310                  int mirror_num, int async_submit)
3311{
3312        struct btrfs_mapping_tree *map_tree;
3313        struct btrfs_device *dev;
3314        struct bio *first_bio = bio;
3315        u64 logical = (u64)bio->bi_sector << 9;
3316        u64 length = 0;
3317        u64 map_length;
3318        struct btrfs_multi_bio *multi = NULL;
3319        int ret;
3320        int dev_nr = 0;
3321        int total_devs = 1;
3322
3323        length = bio->bi_size;
3324        map_tree = &root->fs_info->mapping_tree;
3325        map_length = length;
3326
3327        ret = btrfs_map_block(map_tree, rw, logical, &map_length, &multi,
3328                              mirror_num);
3329        BUG_ON(ret);
3330
3331        total_devs = multi->num_stripes;
3332        if (map_length < length) {
3333                printk(KERN_CRIT "mapping failed logical %llu bio len %llu "
3334                       "len %llu\n", (unsigned long long)logical,
3335                       (unsigned long long)length,
3336                       (unsigned long long)map_length);
3337                BUG();
3338        }
3339        multi->end_io = first_bio->bi_end_io;
3340        multi->private = first_bio->bi_private;
3341        multi->orig_bio = first_bio;
3342        atomic_set(&multi->stripes_pending, multi->num_stripes);
3343
3344        while (dev_nr < total_devs) {
3345                if (total_devs > 1) {
3346                        if (dev_nr < total_devs - 1) {
3347                                bio = bio_clone(first_bio, GFP_NOFS);
3348                                BUG_ON(!bio);
3349                        } else {
3350                                bio = first_bio;
3351                        }
3352                        bio->bi_private = multi;
3353                        bio->bi_end_io = end_bio_multi_stripe;
3354                }
3355                bio->bi_sector = multi->stripes[dev_nr].physical >> 9;
3356                dev = multi->stripes[dev_nr].dev;
3357                if (dev && dev->bdev && (rw != WRITE || dev->writeable)) {
3358                        bio->bi_bdev = dev->bdev;
3359                        if (async_submit)
3360                                schedule_bio(root, dev, rw, bio);
3361                        else
3362                                submit_bio(rw, bio);
3363                } else {
3364                        bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
3365                        bio->bi_sector = logical >> 9;
3366                        bio_endio(bio, -EIO);
3367                }
3368                dev_nr++;
3369        }
3370        if (total_devs == 1)
3371                kfree(multi);
3372        return 0;
3373}
3374
3375struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
3376                                       u8 *uuid, u8 *fsid)
3377{
3378        struct btrfs_device *device;
3379        struct btrfs_fs_devices *cur_devices;
3380
3381        cur_devices = root->fs_info->fs_devices;
3382        while (cur_devices) {
3383                if (!fsid ||
3384                    !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
3385                        device = __find_device(&cur_devices->devices,
3386                                               devid, uuid);
3387                        if (device)
3388                                return device;
3389                }
3390                cur_devices = cur_devices->seed;
3391        }
3392        return NULL;
3393}
3394
3395static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
3396                                            u64 devid, u8 *dev_uuid)
3397{
3398        struct btrfs_device *device;
3399        struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
3400
3401        device = kzalloc(sizeof(*device), GFP_NOFS);
3402        if (!device)
3403                return NULL;
3404        list_add(&device->dev_list,
3405                 &fs_devices->devices);
3406        device->dev_root = root->fs_info->dev_root;
3407        device->devid = devid;
3408        device->work.func = pending_bios_fn;
3409        device->fs_devices = fs_devices;
3410        device->missing = 1;
3411        fs_devices->num_devices++;
3412        fs_devices->missing_devices++;
3413        spin_lock_init(&device->io_lock);
3414        INIT_LIST_HEAD(&device->dev_alloc_list);
3415        memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
3416        return device;
3417}
3418
3419static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
3420                          struct extent_buffer *leaf,
3421                          struct btrfs_chunk *chunk)
3422{
3423        struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
3424        struct map_lookup *map;
3425        struct extent_map *em;
3426        u64 logical;
3427        u64 length;
3428        u64 devid;
3429        u8 uuid[BTRFS_UUID_SIZE];
3430        int num_stripes;
3431        int ret;
3432        int i;
3433
3434        logical = key->offset;
3435        length = btrfs_chunk_length(leaf, chunk);
3436
3437        read_lock(&map_tree->map_tree.lock);
3438        em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
3439        read_unlock(&map_tree->map_tree.lock);
3440
3441        /* already mapped? */
3442        if (em && em->start <= logical && em->start + em->len > logical) {
3443                free_extent_map(em);
3444                return 0;
3445        } else if (em) {
3446                free_extent_map(em);
3447        }
3448
3449        em = alloc_extent_map(GFP_NOFS);
3450        if (!em)
3451                return -ENOMEM;
3452        num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3453        map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
3454        if (!map) {
3455                free_extent_map(em);
3456                return -ENOMEM;
3457        }
3458
3459        em->bdev = (struct block_device *)map;
3460        em->start = logical;
3461        em->len = length;
3462        em->block_start = 0;
3463        em->block_len = em->len;
3464
3465        map->num_stripes = num_stripes;
3466        map->io_width = btrfs_chunk_io_width(leaf, chunk);
3467        map->io_align = btrfs_chunk_io_align(leaf, chunk);
3468        map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
3469        map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
3470        map->type = btrfs_chunk_type(leaf, chunk);
3471        map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
3472        for (i = 0; i < num_stripes; i++) {
3473                map->stripes[i].physical =
3474                        btrfs_stripe_offset_nr(leaf, chunk, i);
3475                devid = btrfs_stripe_devid_nr(leaf, chunk, i);
3476                read_extent_buffer(leaf, uuid, (unsigned long)
3477                                   btrfs_stripe_dev_uuid_nr(chunk, i),
3478                                   BTRFS_UUID_SIZE);
3479                map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
3480                                                        NULL);
3481                if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
3482                        kfree(map);
3483                        free_extent_map(em);
3484                        return -EIO;
3485                }
3486                if (!map->stripes[i].dev) {
3487                        map->stripes[i].dev =
3488                                add_missing_dev(root, devid, uuid);
3489                        if (!map->stripes[i].dev) {
3490                                kfree(map);
3491                                free_extent_map(em);
3492                                return -EIO;
3493                        }
3494                }
3495                map->stripes[i].dev->in_fs_metadata = 1;
3496        }
3497
3498        write_lock(&map_tree->map_tree.lock);
3499        ret = add_extent_mapping(&map_tree->map_tree, em);
3500        write_unlock(&map_tree->map_tree.lock);
3501        BUG_ON(ret);
3502        free_extent_map(em);
3503
3504        return 0;
3505}
3506
3507static int fill_device_from_item(struct extent_buffer *leaf,
3508                                 struct btrfs_dev_item *dev_item,
3509                                 struct btrfs_device *device)
3510{
3511        unsigned long ptr;
3512
3513        device->devid = btrfs_device_id(leaf, dev_item);
3514        device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
3515        device->total_bytes = device->disk_total_bytes;
3516        device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
3517        device->type = btrfs_device_type(leaf, dev_item);
3518        device->io_align = btrfs_device_io_align(leaf, dev_item);
3519        device->io_width = btrfs_device_io_width(leaf, dev_item);
3520        device->sector_size = btrfs_device_sector_size(leaf, dev_item);
3521
3522        ptr = (unsigned long)btrfs_device_uuid(dev_item);
3523        read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
3524
3525        return 0;
3526}
3527
3528static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
3529{
3530        struct btrfs_fs_devices *fs_devices;
3531        int ret;
3532
3533        mutex_lock(&uuid_mutex);
3534
3535        fs_devices = root->fs_info->fs_devices->seed;
3536        while (fs_devices) {
3537                if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
3538                        ret = 0;
3539                        goto out;
3540                }
3541                fs_devices = fs_devices->seed;
3542        }
3543
3544        fs_devices = find_fsid(fsid);
3545        if (!fs_devices) {
3546                ret = -ENOENT;
3547                goto out;
3548        }
3549
3550        fs_devices = clone_fs_devices(fs_devices);
3551        if (IS_ERR(fs_devices)) {
3552                ret = PTR_ERR(fs_devices);
3553                goto out;
3554        }
3555
3556        ret = __btrfs_open_devices(fs_devices, FMODE_READ,
3557                                   root->fs_info->bdev_holder);
3558        if (ret)
3559                goto out;
3560
3561        if (!fs_devices->seeding) {
3562                __btrfs_close_devices(fs_devices);
3563                free_fs_devices(fs_devices);
3564                ret = -EINVAL;
3565                goto out;
3566        }
3567
3568        fs_devices->seed = root->fs_info->fs_devices->seed;
3569        root->fs_info->fs_devices->seed = fs_devices;
3570out:
3571        mutex_unlock(&uuid_mutex);
3572        return ret;
3573}
3574
3575static int read_one_dev(struct btrfs_root *root,
3576                        struct extent_buffer *leaf,
3577                        struct btrfs_dev_item *dev_item)
3578{
3579        struct btrfs_device *device;
3580        u64 devid;
3581        int ret;
3582        u8 fs_uuid[BTRFS_UUID_SIZE];
3583        u8 dev_uuid[BTRFS_UUID_SIZE];
3584
3585        devid = btrfs_device_id(leaf, dev_item);
3586        read_extent_buffer(leaf, dev_uuid,
3587                           (unsigned long)btrfs_device_uuid(dev_item),
3588                           BTRFS_UUID_SIZE);
3589        read_extent_buffer(leaf, fs_uuid,
3590                           (unsigned long)btrfs_device_fsid(dev_item),
3591                           BTRFS_UUID_SIZE);
3592
3593        if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
3594                ret = open_seed_devices(root, fs_uuid);
3595                if (ret && !btrfs_test_opt(root, DEGRADED))
3596                        return ret;
3597        }
3598
3599        device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
3600        if (!device || !device->bdev) {
3601                if (!btrfs_test_opt(root, DEGRADED))
3602                        return -EIO;
3603
3604                if (!device) {
3605                        printk(KERN_WARNING "warning devid %llu missing\n",
3606                               (unsigned long long)devid);
3607                        device = add_missing_dev(root, devid, dev_uuid);
3608                        if (!device)
3609                                return -ENOMEM;
3610                } else if (!device->missing) {
3611                        /*
3612                         * this happens when a device that was properly setup
3613                         * in the device info lists suddenly goes bad.
3614                         * device->bdev is NULL, and so we have to set
3615                         * device->missing to one here
3616                         */
3617                        root->fs_info->fs_devices->missing_devices++;
3618                        device->missing = 1;
3619                }
3620        }
3621
3622        if (device->fs_devices != root->fs_info->fs_devices) {
3623                BUG_ON(device->writeable);
3624                if (device->generation !=
3625                    btrfs_device_generation(leaf, dev_item))
3626                        return -EINVAL;
3627        }
3628
3629        fill_device_from_item(leaf, dev_item, device);
3630        device->dev_root = root->fs_info->dev_root;
3631        device->in_fs_metadata = 1;
3632        if (device->writeable)
3633                device->fs_devices->total_rw_bytes += device->total_bytes;
3634        ret = 0;
3635        return ret;
3636}
3637
3638int btrfs_read_super_device(struct btrfs_root *root, struct extent_buffer *buf)
3639{
3640        struct btrfs_dev_item *dev_item;
3641
3642        dev_item = (struct btrfs_dev_item *)offsetof(struct btrfs_super_block,
3643                                                     dev_item);
3644        return read_one_dev(root, buf, dev_item);
3645}
3646
3647int btrfs_read_sys_array(struct btrfs_root *root)
3648{
3649        struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
3650        struct extent_buffer *sb;
3651        struct btrfs_disk_key *disk_key;
3652        struct btrfs_chunk *chunk;
3653        u8 *ptr;
3654        unsigned long sb_ptr;
3655        int ret = 0;
3656        u32 num_stripes;
3657        u32 array_size;
3658        u32 len = 0;
3659        u32 cur;
3660        struct btrfs_key key;
3661
3662        sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
3663                                          BTRFS_SUPER_INFO_SIZE);
3664        if (!sb)
3665                return -ENOMEM;
3666        btrfs_set_buffer_uptodate(sb);
3667        btrfs_set_buffer_lockdep_class(sb, 0);
3668
3669        write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
3670        array_size = btrfs_super_sys_array_size(super_copy);
3671
3672        ptr = super_copy->sys_chunk_array;
3673        sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
3674        cur = 0;
3675
3676        while (cur < array_size) {
3677                disk_key = (struct btrfs_disk_key *)ptr;
3678                btrfs_disk_key_to_cpu(&key, disk_key);
3679
3680                len = sizeof(*disk_key); ptr += len;
3681                sb_ptr += len;
3682                cur += len;
3683
3684                if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3685                        chunk = (struct btrfs_chunk *)sb_ptr;
3686                        ret = read_one_chunk(root, &key, sb, chunk);
3687                        if (ret)
3688                                break;
3689                        num_stripes = btrfs_chunk_num_stripes(sb, chunk);
3690                        len = btrfs_chunk_item_size(num_stripes);
3691                } else {
3692                        ret = -EIO;
3693                        break;
3694                }
3695                ptr += len;
3696                sb_ptr += len;
3697                cur += len;
3698        }
3699        free_extent_buffer(sb);
3700        return ret;
3701}
3702
3703int btrfs_read_chunk_tree(struct btrfs_root *root)
3704{
3705        struct btrfs_path *path;
3706        struct extent_buffer *leaf;
3707        struct btrfs_key key;
3708        struct btrfs_key found_key;
3709        int ret;
3710        int slot;
3711
3712        root = root->fs_info->chunk_root;
3713
3714        path = btrfs_alloc_path();
3715        if (!path)
3716                return -ENOMEM;
3717
3718        /* first we search for all of the device items, and then we
3719         * read in all of the chunk items.  This way we can create chunk
3720         * mappings that reference all of the devices that are afound
3721         */
3722        key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
3723        key.offset = 0;
3724        key.type = 0;
3725again:
3726        ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3727        if (ret < 0)
3728                goto error;
3729        while (1) {
3730                leaf = path->nodes[0];
3731                slot = path->slots[0];
3732                if (slot >= btrfs_header_nritems(leaf)) {
3733                        ret = btrfs_next_leaf(root, path);
3734                        if (ret == 0)
3735                                continue;
3736                        if (ret < 0)
3737                                goto error;
3738                        break;
3739                }
3740                btrfs_item_key_to_cpu(leaf, &found_key, slot);
3741                if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
3742                        if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
3743                                break;
3744                        if (found_key.type == BTRFS_DEV_ITEM_KEY) {
3745                                struct btrfs_dev_item *dev_item;
3746                                dev_item = btrfs_item_ptr(leaf, slot,
3747                                                  struct btrfs_dev_item);
3748                                ret = read_one_dev(root, leaf, dev_item);
3749                                if (ret)
3750                                        goto error;
3751                        }
3752                } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
3753                        struct btrfs_chunk *chunk;
3754                        chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3755                        ret = read_one_chunk(root, &found_key, leaf, chunk);
3756                        if (ret)
3757                                goto error;
3758                }
3759                path->slots[0]++;
3760        }
3761        if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
3762                key.objectid = 0;
3763                btrfs_release_path(root, path);
3764                goto again;
3765        }
3766        ret = 0;
3767error:
3768        btrfs_free_path(path);
3769        return ret;
3770}
3771