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