blob: b1e48078c3189c9527218ee18872415f6e7b1e33 [file] [log] [blame]
David Sterbac1d7c512018-04-03 19:23:33 +02001// SPDX-License-Identifier: GPL-2.0
Chris Mason0b86a832008-03-24 15:01:56 -04002/*
3 * Copyright (C) 2007 Oracle. All rights reserved.
Chris Mason0b86a832008-03-24 15:01:56 -04004 */
David Sterbac1d7c512018-04-03 19:23:33 +02005
Chris Mason0b86a832008-03-24 15:01:56 -04006#include <linux/sched.h>
Josef Bacikfccc0002020-08-31 10:52:42 -04007#include <linux/sched/mm.h>
Chris Mason0b86a832008-03-24 15:01:56 -04008#include <linux/bio.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +09009#include <linux/slab.h>
Chris Masonf2d8d742008-04-21 10:03:05 -040010#include <linux/blkdev.h>
Stefan Behrens442a4f62012-05-25 16:06:08 +020011#include <linux/ratelimit.h>
Ilya Dryomov59641012012-01-16 22:04:48 +020012#include <linux/kthread.h>
David Woodhouse53b381b2013-01-29 18:40:14 -050013#include <linux/raid/pq.h>
Stefan Behrens803b2f52013-08-15 17:11:21 +020014#include <linux/semaphore.h>
Andy Shevchenko8da4b8c2016-05-20 17:01:00 -070015#include <linux/uuid.h>
Anand Jainf8e10cd2018-01-22 14:49:36 -080016#include <linux/list_sort.h>
David Sterba784352f2019-08-21 18:54:28 +020017#include "misc.h"
Chris Mason0b86a832008-03-24 15:01:56 -040018#include "ctree.h"
19#include "extent_map.h"
20#include "disk-io.h"
21#include "transaction.h"
22#include "print-tree.h"
23#include "volumes.h"
David Woodhouse53b381b2013-01-29 18:40:14 -050024#include "raid56.h"
Chris Mason8b712842008-06-11 16:50:36 -040025#include "async-thread.h"
Stefan Behrens21adbd52011-11-09 13:44:05 +010026#include "check-integrity.h"
Josef Bacik606686e2012-06-04 14:03:51 -040027#include "rcu-string.h"
Stefan Behrens8dabb742012-11-06 13:15:27 +010028#include "dev-replace.h"
Anand Jain99994cd2014-06-03 11:36:00 +080029#include "sysfs.h"
Qu Wenruo82fc28f2019-03-20 13:16:42 +080030#include "tree-checker.h"
Josef Bacik8719aaa2019-06-18 16:09:16 -040031#include "space-info.h"
Josef Bacikaac00232019-06-20 15:37:44 -040032#include "block-group.h"
Dennis Zhoub0643e52019-12-13 16:22:14 -080033#include "discard.h"
Chris Mason0b86a832008-03-24 15:01:56 -040034
Zhao Leiaf902042015-09-15 21:08:06 +080035const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
36 [BTRFS_RAID_RAID10] = {
37 .sub_stripes = 2,
38 .dev_stripes = 1,
39 .devs_max = 0, /* 0 == as many as possible */
40 .devs_min = 4,
Zhao Lei8789f4f2015-09-15 21:08:07 +080041 .tolerated_failures = 1,
Zhao Leiaf902042015-09-15 21:08:06 +080042 .devs_increment = 2,
43 .ncopies = 2,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +020044 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +080045 .raid_name = "raid10",
Anand Jain41a6e892018-04-25 19:01:43 +080046 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
Anand Jainf9fbcaa2018-04-25 19:01:44 +080047 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
Zhao Leiaf902042015-09-15 21:08:06 +080048 },
49 [BTRFS_RAID_RAID1] = {
50 .sub_stripes = 1,
51 .dev_stripes = 1,
52 .devs_max = 2,
53 .devs_min = 2,
Zhao Lei8789f4f2015-09-15 21:08:07 +080054 .tolerated_failures = 1,
Zhao Leiaf902042015-09-15 21:08:06 +080055 .devs_increment = 2,
56 .ncopies = 2,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +020057 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +080058 .raid_name = "raid1",
Anand Jain41a6e892018-04-25 19:01:43 +080059 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
Anand Jainf9fbcaa2018-04-25 19:01:44 +080060 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
Zhao Leiaf902042015-09-15 21:08:06 +080061 },
David Sterba47e6f742018-03-02 22:56:53 +010062 [BTRFS_RAID_RAID1C3] = {
63 .sub_stripes = 1,
64 .dev_stripes = 1,
David Sterbacf93e152019-11-27 16:10:54 +010065 .devs_max = 3,
David Sterba47e6f742018-03-02 22:56:53 +010066 .devs_min = 3,
67 .tolerated_failures = 2,
68 .devs_increment = 3,
69 .ncopies = 3,
David Sterbadb26a022019-11-25 15:34:48 +010070 .nparity = 0,
David Sterba47e6f742018-03-02 22:56:53 +010071 .raid_name = "raid1c3",
72 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
73 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
74 },
David Sterba8d6fac02018-03-02 22:56:53 +010075 [BTRFS_RAID_RAID1C4] = {
76 .sub_stripes = 1,
77 .dev_stripes = 1,
David Sterbacf93e152019-11-27 16:10:54 +010078 .devs_max = 4,
David Sterba8d6fac02018-03-02 22:56:53 +010079 .devs_min = 4,
80 .tolerated_failures = 3,
81 .devs_increment = 4,
82 .ncopies = 4,
David Sterbadb26a022019-11-25 15:34:48 +010083 .nparity = 0,
David Sterba8d6fac02018-03-02 22:56:53 +010084 .raid_name = "raid1c4",
85 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
86 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
87 },
Zhao Leiaf902042015-09-15 21:08:06 +080088 [BTRFS_RAID_DUP] = {
89 .sub_stripes = 1,
90 .dev_stripes = 2,
91 .devs_max = 1,
92 .devs_min = 1,
Zhao Lei8789f4f2015-09-15 21:08:07 +080093 .tolerated_failures = 0,
Zhao Leiaf902042015-09-15 21:08:06 +080094 .devs_increment = 1,
95 .ncopies = 2,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +020096 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +080097 .raid_name = "dup",
Anand Jain41a6e892018-04-25 19:01:43 +080098 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
Anand Jainf9fbcaa2018-04-25 19:01:44 +080099 .mindev_error = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800100 },
101 [BTRFS_RAID_RAID0] = {
102 .sub_stripes = 1,
103 .dev_stripes = 1,
104 .devs_max = 0,
105 .devs_min = 2,
Zhao Lei8789f4f2015-09-15 21:08:07 +0800106 .tolerated_failures = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800107 .devs_increment = 1,
108 .ncopies = 1,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +0200109 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +0800110 .raid_name = "raid0",
Anand Jain41a6e892018-04-25 19:01:43 +0800111 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800112 .mindev_error = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800113 },
114 [BTRFS_RAID_SINGLE] = {
115 .sub_stripes = 1,
116 .dev_stripes = 1,
117 .devs_max = 1,
118 .devs_min = 1,
Zhao Lei8789f4f2015-09-15 21:08:07 +0800119 .tolerated_failures = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800120 .devs_increment = 1,
121 .ncopies = 1,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +0200122 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +0800123 .raid_name = "single",
Anand Jain41a6e892018-04-25 19:01:43 +0800124 .bg_flag = 0,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800125 .mindev_error = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800126 },
127 [BTRFS_RAID_RAID5] = {
128 .sub_stripes = 1,
129 .dev_stripes = 1,
130 .devs_max = 0,
131 .devs_min = 2,
Zhao Lei8789f4f2015-09-15 21:08:07 +0800132 .tolerated_failures = 1,
Zhao Leiaf902042015-09-15 21:08:06 +0800133 .devs_increment = 1,
Hans van Kranenburgda612e32018-10-04 23:24:41 +0200134 .ncopies = 1,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +0200135 .nparity = 1,
Anand Jained234672018-04-25 19:01:42 +0800136 .raid_name = "raid5",
Anand Jain41a6e892018-04-25 19:01:43 +0800137 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800138 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
Zhao Leiaf902042015-09-15 21:08:06 +0800139 },
140 [BTRFS_RAID_RAID6] = {
141 .sub_stripes = 1,
142 .dev_stripes = 1,
143 .devs_max = 0,
144 .devs_min = 3,
Zhao Lei8789f4f2015-09-15 21:08:07 +0800145 .tolerated_failures = 2,
Zhao Leiaf902042015-09-15 21:08:06 +0800146 .devs_increment = 1,
Hans van Kranenburgda612e32018-10-04 23:24:41 +0200147 .ncopies = 1,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +0200148 .nparity = 2,
Anand Jained234672018-04-25 19:01:42 +0800149 .raid_name = "raid6",
Anand Jain41a6e892018-04-25 19:01:43 +0800150 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800151 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
Zhao Leiaf902042015-09-15 21:08:06 +0800152 },
153};
154
David Sterba158da512019-05-17 11:43:41 +0200155const char *btrfs_bg_type_to_raid_name(u64 flags)
Anand Jained234672018-04-25 19:01:42 +0800156{
David Sterba158da512019-05-17 11:43:41 +0200157 const int index = btrfs_bg_flags_to_raid_index(flags);
158
159 if (index >= BTRFS_NR_RAID_TYPES)
Anand Jained234672018-04-25 19:01:42 +0800160 return NULL;
161
David Sterba158da512019-05-17 11:43:41 +0200162 return btrfs_raid_array[index].raid_name;
Anand Jained234672018-04-25 19:01:42 +0800163}
164
Anand Jainf89e09c2018-11-20 16:12:55 +0800165/*
166 * Fill @buf with textual description of @bg_flags, no more than @size_buf
167 * bytes including terminating null byte.
168 */
169void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
170{
171 int i;
172 int ret;
173 char *bp = buf;
174 u64 flags = bg_flags;
175 u32 size_bp = size_buf;
176
177 if (!flags) {
178 strcpy(bp, "NONE");
179 return;
180 }
181
182#define DESCRIBE_FLAG(flag, desc) \
183 do { \
184 if (flags & (flag)) { \
185 ret = snprintf(bp, size_bp, "%s|", (desc)); \
186 if (ret < 0 || ret >= size_bp) \
187 goto out_overflow; \
188 size_bp -= ret; \
189 bp += ret; \
190 flags &= ~(flag); \
191 } \
192 } while (0)
193
194 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
195 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
196 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
197
198 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
199 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
200 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
201 btrfs_raid_array[i].raid_name);
202#undef DESCRIBE_FLAG
203
204 if (flags) {
205 ret = snprintf(bp, size_bp, "0x%llx|", flags);
206 size_bp -= ret;
207 }
208
209 if (size_bp < size_buf)
210 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
211
212 /*
213 * The text is trimmed, it's up to the caller to provide sufficiently
214 * large buffer
215 */
216out_overflow:;
217}
218
David Sterba6f8e0fc2019-03-20 16:29:13 +0100219static int init_first_rw_device(struct btrfs_trans_handle *trans);
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400220static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
Eric Sandeen48a3b632013-04-25 20:41:01 +0000221static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
Stefan Behrens733f4fb2012-05-25 16:06:10 +0200222static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
Liu Bo5ab56092017-03-14 13:33:57 -0700223static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
224 enum btrfs_map_op op,
225 u64 logical, u64 *length,
226 struct btrfs_bio **bbio_ret,
227 int mirror_num, int need_raid_map);
Yan Zheng2b820322008-11-17 21:11:30 -0500228
David Sterba9c6b1c42017-06-16 22:30:00 +0200229/*
230 * Device locking
231 * ==============
232 *
233 * There are several mutexes that protect manipulation of devices and low-level
234 * structures like chunks but not block groups, extents or files
235 *
236 * uuid_mutex (global lock)
237 * ------------------------
238 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
239 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
240 * device) or requested by the device= mount option
241 *
242 * the mutex can be very coarse and can cover long-running operations
243 *
244 * protects: updates to fs_devices counters like missing devices, rw devices,
Andrea Gelmini52042d82018-11-28 12:05:13 +0100245 * seeding, structure cloning, opening/closing devices at mount/umount time
David Sterba9c6b1c42017-06-16 22:30:00 +0200246 *
247 * global::fs_devs - add, remove, updates to the global list
248 *
Josef Bacik18c850f2020-07-17 15:12:27 -0400249 * does not protect: manipulation of the fs_devices::devices list in general
250 * but in mount context it could be used to exclude list modifications by eg.
251 * scan ioctl
David Sterba9c6b1c42017-06-16 22:30:00 +0200252 *
253 * btrfs_device::name - renames (write side), read is RCU
254 *
255 * fs_devices::device_list_mutex (per-fs, with RCU)
256 * ------------------------------------------------
257 * protects updates to fs_devices::devices, ie. adding and deleting
258 *
259 * simple list traversal with read-only actions can be done with RCU protection
260 *
261 * may be used to exclude some operations from running concurrently without any
262 * modifications to the list (see write_all_supers)
263 *
Josef Bacik18c850f2020-07-17 15:12:27 -0400264 * Is not required at mount and close times, because our device list is
265 * protected by the uuid_mutex at that point.
266 *
David Sterba9c6b1c42017-06-16 22:30:00 +0200267 * balance_mutex
268 * -------------
269 * protects balance structures (status, state) and context accessed from
270 * several places (internally, ioctl)
271 *
272 * chunk_mutex
273 * -----------
274 * protects chunks, adding or removing during allocation, trim or when a new
Nikolay Borisov0b6f5d42019-05-09 18:11:11 +0300275 * device is added/removed. Additionally it also protects post_commit_list of
276 * individual devices, since they can be added to the transaction's
277 * post_commit_list only with chunk_mutex held.
David Sterba9c6b1c42017-06-16 22:30:00 +0200278 *
279 * cleaner_mutex
280 * -------------
281 * a big lock that is held by the cleaner thread and prevents running subvolume
282 * cleaning together with relocation or delayed iputs
283 *
284 *
285 * Lock nesting
286 * ============
287 *
288 * uuid_mutex
Anand Jainae3e7152020-05-14 01:42:45 +0800289 * device_list_mutex
290 * chunk_mutex
291 * balance_mutex
Anand Jain89595e82018-04-18 14:59:25 +0800292 *
293 *
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -0500294 * Exclusive operations
295 * ====================
Anand Jain89595e82018-04-18 14:59:25 +0800296 *
297 * Maintains the exclusivity of the following operations that apply to the
298 * whole filesystem and cannot run in parallel.
299 *
300 * - Balance (*)
301 * - Device add
302 * - Device remove
303 * - Device replace (*)
304 * - Resize
305 *
306 * The device operations (as above) can be in one of the following states:
307 *
308 * - Running state
309 * - Paused state
310 * - Completed state
311 *
312 * Only device operations marked with (*) can go into the Paused state for the
313 * following reasons:
314 *
315 * - ioctl (only Balance can be Paused through ioctl)
316 * - filesystem remounted as read-only
317 * - filesystem unmounted and mounted as read-only
318 * - system power-cycle and filesystem mounted as read-only
319 * - filesystem or device errors leading to forced read-only
320 *
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -0500321 * The status of exclusive operation is set and cleared atomically.
322 * During the course of Paused state, fs_info::exclusive_operation remains set.
Anand Jain89595e82018-04-18 14:59:25 +0800323 * A device operation in Paused or Running state can be canceled or resumed
324 * either by ioctl (Balance only) or when remounted as read-write.
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -0500325 * The exclusive status is cleared when the device operation is canceled or
Anand Jain89595e82018-04-18 14:59:25 +0800326 * completed.
David Sterba9c6b1c42017-06-16 22:30:00 +0200327 */
328
Miao Xie67a2c452014-09-03 21:35:43 +0800329DEFINE_MUTEX(uuid_mutex);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400330static LIST_HEAD(fs_uuids);
David Sterba4143cb82019-10-01 19:57:37 +0200331struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
Anand Jainc73eccf2015-03-10 06:38:30 +0800332{
333 return &fs_uuids;
334}
Chris Mason8a4b83c2008-03-24 15:02:07 -0400335
David Sterba2dfeca92017-06-14 02:48:07 +0200336/*
337 * alloc_fs_devices - allocate struct btrfs_fs_devices
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200338 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
339 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
David Sterba2dfeca92017-06-14 02:48:07 +0200340 *
341 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
342 * The returned struct is not linked onto any lists and can be destroyed with
343 * kfree() right away.
344 */
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200345static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
346 const u8 *metadata_fsid)
Ilya Dryomov2208a372013-08-12 14:33:03 +0300347{
348 struct btrfs_fs_devices *fs_devs;
349
David Sterba78f2c9e2016-02-11 14:25:38 +0100350 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300351 if (!fs_devs)
352 return ERR_PTR(-ENOMEM);
353
354 mutex_init(&fs_devs->device_list_mutex);
355
356 INIT_LIST_HEAD(&fs_devs->devices);
357 INIT_LIST_HEAD(&fs_devs->alloc_list);
Anand Jainc4babc52018-04-12 10:29:25 +0800358 INIT_LIST_HEAD(&fs_devs->fs_list);
Nikolay Borisov944d3f92020-07-16 10:25:33 +0300359 INIT_LIST_HEAD(&fs_devs->seed_list);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300360 if (fsid)
361 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300362
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200363 if (metadata_fsid)
364 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
365 else if (fsid)
366 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
367
Ilya Dryomov2208a372013-08-12 14:33:03 +0300368 return fs_devs;
369}
370
David Sterbaa425f9d2018-03-20 15:47:33 +0100371void btrfs_free_device(struct btrfs_device *device)
David Sterba48dae9c2017-10-30 18:10:25 +0100372{
Nikolay Borisovbbbf7242019-03-25 14:31:22 +0200373 WARN_ON(!list_empty(&device->post_commit_list));
David Sterba48dae9c2017-10-30 18:10:25 +0100374 rcu_string_free(device->name);
Jeff Mahoney1c11b632019-03-27 14:24:12 +0200375 extent_io_tree_release(&device->alloc_state);
David Sterba48dae9c2017-10-30 18:10:25 +0100376 bio_put(device->flush_bio);
377 kfree(device);
378}
379
Yan Zhenge4404d62008-12-12 10:03:26 -0500380static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
381{
382 struct btrfs_device *device;
383 WARN_ON(fs_devices->opened);
384 while (!list_empty(&fs_devices->devices)) {
385 device = list_entry(fs_devices->devices.next,
386 struct btrfs_device, dev_list);
387 list_del(&device->dev_list);
David Sterbaa425f9d2018-03-20 15:47:33 +0100388 btrfs_free_device(device);
Yan Zhenge4404d62008-12-12 10:03:26 -0500389 }
390 kfree(fs_devices);
391}
392
David Sterbaffc5a372018-02-19 17:24:15 +0100393void __exit btrfs_cleanup_fs_uuids(void)
Chris Mason8a4b83c2008-03-24 15:02:07 -0400394{
395 struct btrfs_fs_devices *fs_devices;
Chris Mason8a4b83c2008-03-24 15:02:07 -0400396
Yan Zheng2b820322008-11-17 21:11:30 -0500397 while (!list_empty(&fs_uuids)) {
398 fs_devices = list_entry(fs_uuids.next,
Anand Jainc4babc52018-04-12 10:29:25 +0800399 struct btrfs_fs_devices, fs_list);
400 list_del(&fs_devices->fs_list);
Yan Zhenge4404d62008-12-12 10:03:26 -0500401 free_fs_devices(fs_devices);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400402 }
Chris Mason8a4b83c2008-03-24 15:02:07 -0400403}
404
David Sterba48dae9c2017-10-30 18:10:25 +0100405/*
406 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
407 * Returned struct is not linked onto any lists and must be destroyed using
David Sterbaa425f9d2018-03-20 15:47:33 +0100408 * btrfs_free_device.
David Sterba48dae9c2017-10-30 18:10:25 +0100409 */
Qu Wenruo154f7cb2020-08-20 15:42:46 +0800410static struct btrfs_device *__alloc_device(struct btrfs_fs_info *fs_info)
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300411{
412 struct btrfs_device *dev;
413
David Sterba78f2c9e2016-02-11 14:25:38 +0100414 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300415 if (!dev)
416 return ERR_PTR(-ENOMEM);
417
David Sterbae0ae9992017-06-06 17:06:06 +0200418 /*
419 * Preallocate a bio that's always going to be used for flushing device
420 * barriers and matches the device lifespan
421 */
422 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
423 if (!dev->flush_bio) {
424 kfree(dev);
425 return ERR_PTR(-ENOMEM);
426 }
David Sterbae0ae9992017-06-06 17:06:06 +0200427
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300428 INIT_LIST_HEAD(&dev->dev_list);
429 INIT_LIST_HEAD(&dev->dev_alloc_list);
Nikolay Borisovbbbf7242019-03-25 14:31:22 +0200430 INIT_LIST_HEAD(&dev->post_commit_list);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300431
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300432 atomic_set(&dev->reada_in_flight, 0);
Miao Xieaddc3fa2014-07-24 11:37:11 +0800433 atomic_set(&dev->dev_stats_ccnt, 0);
Davidlohr Buesod5c82382020-10-21 13:17:24 -0700434 btrfs_device_data_ordered_init(dev, fs_info);
Chris Mason9bcaaea2017-05-04 16:08:08 -0700435 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
Mel Gormand0164ad2015-11-06 16:28:21 -0800436 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
Qu Wenruo154f7cb2020-08-20 15:42:46 +0800437 extent_io_tree_init(fs_info, &dev->alloc_state,
438 IO_TREE_DEVICE_ALLOC_STATE, NULL);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300439
440 return dev;
441}
442
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200443static noinline struct btrfs_fs_devices *find_fsid(
444 const u8 *fsid, const u8 *metadata_fsid)
Chris Mason8a4b83c2008-03-24 15:02:07 -0400445{
Chris Mason8a4b83c2008-03-24 15:02:07 -0400446 struct btrfs_fs_devices *fs_devices;
447
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200448 ASSERT(fsid);
449
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200450 /* Handle non-split brain cases */
Anand Jainc4babc52018-04-12 10:29:25 +0800451 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200452 if (metadata_fsid) {
453 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
454 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
455 BTRFS_FSID_SIZE) == 0)
456 return fs_devices;
457 } else {
458 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
459 return fs_devices;
460 }
Chris Mason8a4b83c2008-03-24 15:02:07 -0400461 }
462 return NULL;
463}
464
Su Yuec6730a02020-01-10 14:11:33 +0200465static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
466 struct btrfs_super_block *disk_super)
467{
468
469 struct btrfs_fs_devices *fs_devices;
470
471 /*
472 * Handle scanned device having completed its fsid change but
473 * belonging to a fs_devices that was created by first scanning
474 * a device which didn't have its fsid/metadata_uuid changed
475 * at all and the CHANGING_FSID_V2 flag set.
476 */
477 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
478 if (fs_devices->fsid_change &&
479 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
480 BTRFS_FSID_SIZE) == 0 &&
481 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
482 BTRFS_FSID_SIZE) == 0) {
483 return fs_devices;
484 }
485 }
486 /*
487 * Handle scanned device having completed its fsid change but
488 * belonging to a fs_devices that was created by a device that
489 * has an outdated pair of fsid/metadata_uuid and
490 * CHANGING_FSID_V2 flag set.
491 */
492 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
493 if (fs_devices->fsid_change &&
494 memcmp(fs_devices->metadata_uuid,
495 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
496 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
497 BTRFS_FSID_SIZE) == 0) {
498 return fs_devices;
499 }
500 }
501
502 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
503}
504
505
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100506static int
507btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
508 int flush, struct block_device **bdev,
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900509 struct btrfs_super_block **disk_super)
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100510{
511 int ret;
512
513 *bdev = blkdev_get_by_path(device_path, flags, holder);
514
515 if (IS_ERR(*bdev)) {
516 ret = PTR_ERR(*bdev);
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100517 goto error;
518 }
519
520 if (flush)
521 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
David Sterba9f6d2512017-06-16 01:48:05 +0200522 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100523 if (ret) {
524 blkdev_put(*bdev, flags);
525 goto error;
526 }
527 invalidate_bdev(*bdev);
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900528 *disk_super = btrfs_read_dev_super(*bdev);
529 if (IS_ERR(*disk_super)) {
530 ret = PTR_ERR(*disk_super);
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100531 blkdev_put(*bdev, flags);
532 goto error;
533 }
534
535 return 0;
536
537error:
538 *bdev = NULL;
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100539 return ret;
540}
541
Anand Jain70bc7082019-01-04 13:31:53 +0800542static bool device_path_matched(const char *path, struct btrfs_device *device)
543{
544 int found;
545
546 rcu_read_lock();
547 found = strcmp(rcu_str_deref(device->name), path);
548 rcu_read_unlock();
549
550 return found == 0;
551}
552
Anand Jaind8367db2018-01-18 22:00:37 +0800553/*
554 * Search and remove all stale (devices which are not mounted) devices.
555 * When both inputs are NULL, it will search and release all stale devices.
556 * path: Optional. When provided will it release all unmounted devices
557 * matching this path only.
558 * skip_dev: Optional. Will skip this device when searching for the stale
559 * devices.
Anand Jain70bc7082019-01-04 13:31:53 +0800560 * Return: 0 for success or if @path is NULL.
561 * -EBUSY if @path is a mounted device.
562 * -ENOENT if @path does not match any device in the list.
Anand Jaind8367db2018-01-18 22:00:37 +0800563 */
Anand Jain70bc7082019-01-04 13:31:53 +0800564static int btrfs_free_stale_devices(const char *path,
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800565 struct btrfs_device *skip_device)
Anand Jain4fde46f2015-06-17 21:10:48 +0800566{
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800567 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
568 struct btrfs_device *device, *tmp_device;
Anand Jain70bc7082019-01-04 13:31:53 +0800569 int ret = 0;
570
571 if (path)
572 ret = -ENOENT;
Anand Jain4fde46f2015-06-17 21:10:48 +0800573
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800574 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
Anand Jain4fde46f2015-06-17 21:10:48 +0800575
Anand Jain70bc7082019-01-04 13:31:53 +0800576 mutex_lock(&fs_devices->device_list_mutex);
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800577 list_for_each_entry_safe(device, tmp_device,
578 &fs_devices->devices, dev_list) {
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800579 if (skip_device && skip_device == device)
Anand Jaind8367db2018-01-18 22:00:37 +0800580 continue;
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800581 if (path && !device->name)
Anand Jain4fde46f2015-06-17 21:10:48 +0800582 continue;
Anand Jain70bc7082019-01-04 13:31:53 +0800583 if (path && !device_path_matched(path, device))
Anand Jain38cf6652018-01-18 22:00:34 +0800584 continue;
Anand Jain70bc7082019-01-04 13:31:53 +0800585 if (fs_devices->opened) {
586 /* for an already deleted device return 0 */
587 if (path && ret != 0)
588 ret = -EBUSY;
589 break;
590 }
Anand Jain4fde46f2015-06-17 21:10:48 +0800591
Anand Jain4fde46f2015-06-17 21:10:48 +0800592 /* delete the stale device */
Anand Jain7bcb8162018-05-29 17:23:20 +0800593 fs_devices->num_devices--;
594 list_del(&device->dev_list);
595 btrfs_free_device(device);
596
Anand Jain70bc7082019-01-04 13:31:53 +0800597 ret = 0;
Anand Jain7bcb8162018-05-29 17:23:20 +0800598 }
599 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jain70bc7082019-01-04 13:31:53 +0800600
Anand Jain7bcb8162018-05-29 17:23:20 +0800601 if (fs_devices->num_devices == 0) {
602 btrfs_sysfs_remove_fsid(fs_devices);
603 list_del(&fs_devices->fs_list);
604 free_fs_devices(fs_devices);
Anand Jain4fde46f2015-06-17 21:10:48 +0800605 }
606 }
Anand Jain70bc7082019-01-04 13:31:53 +0800607
608 return ret;
Anand Jain4fde46f2015-06-17 21:10:48 +0800609}
610
Josef Bacik18c850f2020-07-17 15:12:27 -0400611/*
612 * This is only used on mount, and we are protected from competing things
613 * messing with our fs_devices by the uuid_mutex, thus we do not need the
614 * fs_devices->device_list_mutex here.
615 */
Anand Jain0fb08bc2017-11-09 23:45:24 +0800616static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
617 struct btrfs_device *device, fmode_t flags,
618 void *holder)
619{
620 struct request_queue *q;
621 struct block_device *bdev;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800622 struct btrfs_super_block *disk_super;
623 u64 devid;
624 int ret;
625
626 if (device->bdev)
627 return -EINVAL;
628 if (!device->name)
629 return -EINVAL;
630
631 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900632 &bdev, &disk_super);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800633 if (ret)
634 return ret;
635
Anand Jain0fb08bc2017-11-09 23:45:24 +0800636 devid = btrfs_stack_device_id(&disk_super->dev_item);
637 if (devid != device->devid)
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900638 goto error_free_page;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800639
640 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900641 goto error_free_page;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800642
643 device->generation = btrfs_super_generation(disk_super);
644
645 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200646 if (btrfs_super_incompat_flags(disk_super) &
647 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
648 pr_err(
649 "BTRFS: Invalid seeding and uuid-changed device detected\n");
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900650 goto error_free_page;
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200651 }
652
Anand Jainebbede42017-12-04 12:54:52 +0800653 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Johannes Thumshirn0395d842019-11-13 11:27:27 +0100654 fs_devices->seeding = true;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800655 } else {
Anand Jainebbede42017-12-04 12:54:52 +0800656 if (bdev_read_only(bdev))
657 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
658 else
659 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800660 }
661
662 q = bdev_get_queue(bdev);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800663 if (!blk_queue_nonrot(q))
Johannes Thumshirn7f0432d2019-11-13 11:27:28 +0100664 fs_devices->rotating = true;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800665
666 device->bdev = bdev;
Anand Jaine12c9622017-12-04 12:54:53 +0800667 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800668 device->mode = flags;
669
670 fs_devices->open_devices++;
Anand Jainebbede42017-12-04 12:54:52 +0800671 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
672 device->devid != BTRFS_DEV_REPLACE_DEVID) {
Anand Jain0fb08bc2017-11-09 23:45:24 +0800673 fs_devices->rw_devices++;
Anand Jainb1b8e382018-01-22 14:49:37 -0800674 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800675 }
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900676 btrfs_release_disk_super(disk_super);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800677
678 return 0;
679
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900680error_free_page:
681 btrfs_release_disk_super(disk_super);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800682 blkdev_put(bdev, flags);
683
684 return -EINVAL;
685}
686
David Sterba60999ca2014-03-26 18:26:36 +0100687/*
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200688 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
Su Yuec0d81c72020-01-10 14:11:32 +0200689 * being created with a disk that has already completed its fsid change. Such
690 * disk can belong to an fs which has its FSID changed or to one which doesn't.
691 * Handle both cases here.
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200692 */
693static struct btrfs_fs_devices *find_fsid_inprogress(
694 struct btrfs_super_block *disk_super)
695{
696 struct btrfs_fs_devices *fs_devices;
697
698 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
699 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
700 BTRFS_FSID_SIZE) != 0 &&
701 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
702 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
703 return fs_devices;
704 }
705 }
706
Su Yuec0d81c72020-01-10 14:11:32 +0200707 return find_fsid(disk_super->fsid, NULL);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200708}
709
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200710
711static struct btrfs_fs_devices *find_fsid_changed(
712 struct btrfs_super_block *disk_super)
713{
714 struct btrfs_fs_devices *fs_devices;
715
716 /*
717 * Handles the case where scanned device is part of an fs that had
718 * multiple successful changes of FSID but curently device didn't
Nikolay Borisov05840712020-01-10 14:11:34 +0200719 * observe it. Meaning our fsid will be different than theirs. We need
720 * to handle two subcases :
721 * 1 - The fs still continues to have different METADATA/FSID uuids.
722 * 2 - The fs is switched back to its original FSID (METADATA/FSID
723 * are equal).
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200724 */
725 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
Nikolay Borisov05840712020-01-10 14:11:34 +0200726 /* Changed UUIDs */
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200727 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
728 BTRFS_FSID_SIZE) != 0 &&
729 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
730 BTRFS_FSID_SIZE) == 0 &&
731 memcmp(fs_devices->fsid, disk_super->fsid,
Nikolay Borisov05840712020-01-10 14:11:34 +0200732 BTRFS_FSID_SIZE) != 0)
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200733 return fs_devices;
Nikolay Borisov05840712020-01-10 14:11:34 +0200734
735 /* Unchanged UUIDs */
736 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
737 BTRFS_FSID_SIZE) == 0 &&
738 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
739 BTRFS_FSID_SIZE) == 0)
740 return fs_devices;
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200741 }
742
743 return NULL;
744}
Nikolay Borisov13620892020-01-10 14:11:35 +0200745
746static struct btrfs_fs_devices *find_fsid_reverted_metadata(
747 struct btrfs_super_block *disk_super)
748{
749 struct btrfs_fs_devices *fs_devices;
750
751 /*
752 * Handle the case where the scanned device is part of an fs whose last
753 * metadata UUID change reverted it to the original FSID. At the same
754 * time * fs_devices was first created by another constitutent device
755 * which didn't fully observe the operation. This results in an
756 * btrfs_fs_devices created with metadata/fsid different AND
757 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
758 * fs_devices equal to the FSID of the disk.
759 */
760 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
761 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
762 BTRFS_FSID_SIZE) != 0 &&
763 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
764 BTRFS_FSID_SIZE) == 0 &&
765 fs_devices->fsid_change)
766 return fs_devices;
767 }
768
769 return NULL;
770}
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200771/*
David Sterba60999ca2014-03-26 18:26:36 +0100772 * Add new device to list of registered devices
773 *
774 * Returns:
Anand Jaine124ece2018-01-18 22:02:35 +0800775 * device pointer which was just added or updated when successful
776 * error pointer when failed
David Sterba60999ca2014-03-26 18:26:36 +0100777 */
Anand Jaine124ece2018-01-18 22:02:35 +0800778static noinline struct btrfs_device *device_list_add(const char *path,
Anand Jain4306a972018-05-29 12:28:37 +0800779 struct btrfs_super_block *disk_super,
780 bool *new_device_added)
Chris Mason8a4b83c2008-03-24 15:02:07 -0400781{
782 struct btrfs_device *device;
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200783 struct btrfs_fs_devices *fs_devices = NULL;
Josef Bacik606686e2012-06-04 14:03:51 -0400784 struct rcu_string *name;
Chris Mason8a4b83c2008-03-24 15:02:07 -0400785 u64 found_transid = btrfs_super_generation(disk_super);
Anand Jain3acbcbf2018-01-18 22:02:36 +0800786 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200787 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
788 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
Nikolay Borisovd1a63002018-10-30 16:43:26 +0200789 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
790 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400791
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200792 if (fsid_change_in_progress) {
Su Yuec0d81c72020-01-10 14:11:32 +0200793 if (!has_metadata_uuid)
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200794 fs_devices = find_fsid_inprogress(disk_super);
Su Yuec0d81c72020-01-10 14:11:32 +0200795 else
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200796 fs_devices = find_fsid_changed(disk_super);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200797 } else if (has_metadata_uuid) {
Su Yuec6730a02020-01-10 14:11:33 +0200798 fs_devices = find_fsid_with_metadata_uuid(disk_super);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200799 } else {
Nikolay Borisov13620892020-01-10 14:11:35 +0200800 fs_devices = find_fsid_reverted_metadata(disk_super);
801 if (!fs_devices)
802 fs_devices = find_fsid(disk_super->fsid, NULL);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200803 }
804
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200805
Chris Mason8a4b83c2008-03-24 15:02:07 -0400806 if (!fs_devices) {
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200807 if (has_metadata_uuid)
808 fs_devices = alloc_fs_devices(disk_super->fsid,
809 disk_super->metadata_uuid);
810 else
811 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
812
Ilya Dryomov2208a372013-08-12 14:33:03 +0300813 if (IS_ERR(fs_devices))
Anand Jaine124ece2018-01-18 22:02:35 +0800814 return ERR_CAST(fs_devices);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300815
Al Viro92900e52019-01-27 04:58:00 +0000816 fs_devices->fsid_change = fsid_change_in_progress;
817
Anand Jain9c6d1732018-05-29 14:10:20 +0800818 mutex_lock(&fs_devices->device_list_mutex);
Anand Jainc4babc52018-04-12 10:29:25 +0800819 list_add(&fs_devices->fs_list, &fs_uuids);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300820
Chris Mason8a4b83c2008-03-24 15:02:07 -0400821 device = NULL;
822 } else {
Anand Jain9c6d1732018-05-29 14:10:20 +0800823 mutex_lock(&fs_devices->device_list_mutex);
Anand Jain09ba3bc2019-01-19 14:48:55 +0800824 device = btrfs_find_device(fs_devices, devid,
825 disk_super->dev_item.uuid, NULL, false);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200826
827 /*
828 * If this disk has been pulled into an fs devices created by
829 * a device which had the CHANGING_FSID_V2 flag then replace the
830 * metadata_uuid/fsid values of the fs_devices.
831 */
Nikolay Borisov13620892020-01-10 14:11:35 +0200832 if (fs_devices->fsid_change &&
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200833 found_transid > fs_devices->latest_generation) {
834 memcpy(fs_devices->fsid, disk_super->fsid,
835 BTRFS_FSID_SIZE);
Nikolay Borisov13620892020-01-10 14:11:35 +0200836
837 if (has_metadata_uuid)
838 memcpy(fs_devices->metadata_uuid,
839 disk_super->metadata_uuid,
840 BTRFS_FSID_SIZE);
841 else
842 memcpy(fs_devices->metadata_uuid,
843 disk_super->fsid, BTRFS_FSID_SIZE);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200844
845 fs_devices->fsid_change = false;
846 }
Chris Mason8a4b83c2008-03-24 15:02:07 -0400847 }
Miao Xie443f24f2014-07-24 11:37:15 +0800848
Chris Mason8a4b83c2008-03-24 15:02:07 -0400849 if (!device) {
Anand Jain9c6d1732018-05-29 14:10:20 +0800850 if (fs_devices->opened) {
851 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800852 return ERR_PTR(-EBUSY);
Anand Jain9c6d1732018-05-29 14:10:20 +0800853 }
Yan Zheng2b820322008-11-17 21:11:30 -0500854
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300855 device = btrfs_alloc_device(NULL, &devid,
856 disk_super->dev_item.uuid);
857 if (IS_ERR(device)) {
Anand Jain9c6d1732018-05-29 14:10:20 +0800858 mutex_unlock(&fs_devices->device_list_mutex);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400859 /* we can safely leave the fs_devices entry around */
Anand Jaine124ece2018-01-18 22:02:35 +0800860 return device;
Chris Mason8a4b83c2008-03-24 15:02:07 -0400861 }
Josef Bacik606686e2012-06-04 14:03:51 -0400862
863 name = rcu_string_strdup(path, GFP_NOFS);
864 if (!name) {
David Sterbaa425f9d2018-03-20 15:47:33 +0100865 btrfs_free_device(device);
Anand Jain9c6d1732018-05-29 14:10:20 +0800866 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800867 return ERR_PTR(-ENOMEM);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400868 }
Josef Bacik606686e2012-06-04 14:03:51 -0400869 rcu_assign_pointer(device->name, name);
Arne Jansen90519d62011-05-23 14:30:00 +0200870
Xiao Guangrong1f781602011-04-20 10:09:16 +0000871 list_add_rcu(&device->dev_list, &fs_devices->devices);
Filipe David Borba Mananaf7171752013-08-12 20:56:58 +0100872 fs_devices->num_devices++;
Chris Masone5e9a522009-06-10 15:17:02 -0400873
Yan Zheng2b820322008-11-17 21:11:30 -0500874 device->fs_devices = fs_devices;
Anand Jain4306a972018-05-29 12:28:37 +0800875 *new_device_added = true;
Anand Jain327f18c2018-01-18 22:02:33 +0800876
877 if (disk_super->label[0])
Anand Jainaa6c0df2019-10-02 18:30:48 +0800878 pr_info(
879 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
880 disk_super->label, devid, found_transid, path,
881 current->comm, task_pid_nr(current));
Anand Jain327f18c2018-01-18 22:02:33 +0800882 else
Anand Jainaa6c0df2019-10-02 18:30:48 +0800883 pr_info(
884 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
885 disk_super->fsid, devid, found_transid, path,
886 current->comm, task_pid_nr(current));
Anand Jain327f18c2018-01-18 22:02:33 +0800887
Josef Bacik606686e2012-06-04 14:03:51 -0400888 } else if (!device->name || strcmp(device->name->str, path)) {
Anand Jainb96de002014-07-03 18:22:05 +0800889 /*
890 * When FS is already mounted.
891 * 1. If you are here and if the device->name is NULL that
892 * means this device was missing at time of FS mount.
893 * 2. If you are here and if the device->name is different
894 * from 'path' that means either
895 * a. The same device disappeared and reappeared with
896 * different name. or
897 * b. The missing-disk-which-was-replaced, has
898 * reappeared now.
899 *
900 * We must allow 1 and 2a above. But 2b would be a spurious
901 * and unintentional.
902 *
903 * Further in case of 1 and 2a above, the disk at 'path'
904 * would have missed some transaction when it was away and
905 * in case of 2a the stale bdev has to be updated as well.
906 * 2b must not be allowed at all time.
907 */
908
909 /*
Chris Mason0f23ae72014-09-18 07:49:05 -0700910 * For now, we do allow update to btrfs_fs_device through the
911 * btrfs dev scan cli after FS has been mounted. We're still
912 * tracking a problem where systems fail mount by subvolume id
913 * when we reject replacement on a mounted FS.
Anand Jainb96de002014-07-03 18:22:05 +0800914 */
Chris Mason0f23ae72014-09-18 07:49:05 -0700915 if (!fs_devices->opened && found_transid < device->generation) {
Anand Jain77bdae42014-07-03 18:22:06 +0800916 /*
917 * That is if the FS is _not_ mounted and if you
918 * are here, that means there is more than one
919 * disk with same uuid and devid.We keep the one
920 * with larger generation number or the last-in if
921 * generation are equal.
922 */
Anand Jain9c6d1732018-05-29 14:10:20 +0800923 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800924 return ERR_PTR(-EEXIST);
Anand Jain77bdae42014-07-03 18:22:06 +0800925 }
Anand Jainb96de002014-07-03 18:22:05 +0800926
Anand Jaina9261d42018-10-15 10:45:17 +0800927 /*
928 * We are going to replace the device path for a given devid,
929 * make sure it's the same device if the device is mounted
930 */
931 if (device->bdev) {
932 struct block_device *path_bdev;
933
934 path_bdev = lookup_bdev(path);
935 if (IS_ERR(path_bdev)) {
936 mutex_unlock(&fs_devices->device_list_mutex);
937 return ERR_CAST(path_bdev);
938 }
939
940 if (device->bdev != path_bdev) {
941 bdput(path_bdev);
942 mutex_unlock(&fs_devices->device_list_mutex);
943 btrfs_warn_in_rcu(device->fs_info,
Anand Jain79dae172020-09-03 21:30:12 +0800944 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
945 path, devid, found_transid,
946 current->comm,
947 task_pid_nr(current));
Anand Jaina9261d42018-10-15 10:45:17 +0800948 return ERR_PTR(-EEXIST);
949 }
950 bdput(path_bdev);
951 btrfs_info_in_rcu(device->fs_info,
Anand Jain79dae172020-09-03 21:30:12 +0800952 "devid %llu device path %s changed to %s scanned by %s (%d)",
953 devid, rcu_str_deref(device->name),
954 path, current->comm,
955 task_pid_nr(current));
Anand Jaina9261d42018-10-15 10:45:17 +0800956 }
957
Josef Bacik606686e2012-06-04 14:03:51 -0400958 name = rcu_string_strdup(path, GFP_NOFS);
Anand Jain9c6d1732018-05-29 14:10:20 +0800959 if (!name) {
960 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800961 return ERR_PTR(-ENOMEM);
Anand Jain9c6d1732018-05-29 14:10:20 +0800962 }
Josef Bacik606686e2012-06-04 14:03:51 -0400963 rcu_string_free(device->name);
964 rcu_assign_pointer(device->name, name);
Anand Jaine6e674b2017-12-04 12:54:54 +0800965 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
Chris Masoncd02dca2010-12-13 14:56:23 -0500966 fs_devices->missing_devices--;
Anand Jaine6e674b2017-12-04 12:54:54 +0800967 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
Chris Masoncd02dca2010-12-13 14:56:23 -0500968 }
Chris Mason8a4b83c2008-03-24 15:02:07 -0400969 }
970
Anand Jain77bdae42014-07-03 18:22:06 +0800971 /*
972 * Unmount does not free the btrfs_device struct but would zero
973 * generation along with most of the other members. So just update
974 * it back. We need it to pick the disk with largest generation
975 * (as above).
976 */
Nikolay Borisovd1a63002018-10-30 16:43:26 +0200977 if (!fs_devices->opened) {
Anand Jain77bdae42014-07-03 18:22:06 +0800978 device->generation = found_transid;
Nikolay Borisovd1a63002018-10-30 16:43:26 +0200979 fs_devices->latest_generation = max_t(u64, found_transid,
980 fs_devices->latest_generation);
981 }
Anand Jain77bdae42014-07-03 18:22:06 +0800982
Anand Jainf2788d22018-01-18 22:02:34 +0800983 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
984
Anand Jain9c6d1732018-05-29 14:10:20 +0800985 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800986 return device;
Chris Mason8a4b83c2008-03-24 15:02:07 -0400987}
988
Yan Zhenge4404d62008-12-12 10:03:26 -0500989static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
990{
991 struct btrfs_fs_devices *fs_devices;
992 struct btrfs_device *device;
993 struct btrfs_device *orig_dev;
Anand Jaind2979aa2019-08-27 15:40:45 +0800994 int ret = 0;
Yan Zhenge4404d62008-12-12 10:03:26 -0500995
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200996 fs_devices = alloc_fs_devices(orig->fsid, NULL);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300997 if (IS_ERR(fs_devices))
998 return fs_devices;
Yan Zhenge4404d62008-12-12 10:03:26 -0500999
Miao Xieadbbb862014-09-03 21:35:42 +08001000 mutex_lock(&orig->device_list_mutex);
Josef Bacik02db0842012-06-21 16:03:58 -04001001 fs_devices->total_devices = orig->total_devices;
Yan Zhenge4404d62008-12-12 10:03:26 -05001002
1003 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
Josef Bacik606686e2012-06-04 14:03:51 -04001004 struct rcu_string *name;
1005
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03001006 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1007 orig_dev->uuid);
Anand Jaind2979aa2019-08-27 15:40:45 +08001008 if (IS_ERR(device)) {
1009 ret = PTR_ERR(device);
Yan Zhenge4404d62008-12-12 10:03:26 -05001010 goto error;
Anand Jaind2979aa2019-08-27 15:40:45 +08001011 }
Yan Zhenge4404d62008-12-12 10:03:26 -05001012
Josef Bacik606686e2012-06-04 14:03:51 -04001013 /*
1014 * This is ok to do without rcu read locked because we hold the
1015 * uuid mutex so nothing we touch in here is going to disappear.
1016 */
Anand Jaine755f782014-06-30 17:12:47 +08001017 if (orig_dev->name) {
David Sterba78f2c9e2016-02-11 14:25:38 +01001018 name = rcu_string_strdup(orig_dev->name->str,
1019 GFP_KERNEL);
Anand Jaine755f782014-06-30 17:12:47 +08001020 if (!name) {
David Sterbaa425f9d2018-03-20 15:47:33 +01001021 btrfs_free_device(device);
Anand Jaind2979aa2019-08-27 15:40:45 +08001022 ret = -ENOMEM;
Anand Jaine755f782014-06-30 17:12:47 +08001023 goto error;
1024 }
1025 rcu_assign_pointer(device->name, name);
Julia Lawallfd2696f2009-09-29 13:51:04 -04001026 }
Yan Zhenge4404d62008-12-12 10:03:26 -05001027
Yan Zhenge4404d62008-12-12 10:03:26 -05001028 list_add(&device->dev_list, &fs_devices->devices);
1029 device->fs_devices = fs_devices;
1030 fs_devices->num_devices++;
1031 }
Miao Xieadbbb862014-09-03 21:35:42 +08001032 mutex_unlock(&orig->device_list_mutex);
Yan Zhenge4404d62008-12-12 10:03:26 -05001033 return fs_devices;
1034error:
Miao Xieadbbb862014-09-03 21:35:42 +08001035 mutex_unlock(&orig->device_list_mutex);
Yan Zhenge4404d62008-12-12 10:03:26 -05001036 free_fs_devices(fs_devices);
Anand Jaind2979aa2019-08-27 15:40:45 +08001037 return ERR_PTR(ret);
Yan Zhenge4404d62008-12-12 10:03:26 -05001038}
1039
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001040static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1041 int step, struct btrfs_device **latest_dev)
Chris Masondfe25022008-05-13 13:46:40 -04001042{
Qinghuang Fengc6e30872009-01-21 10:59:08 -05001043 struct btrfs_device *device, *next;
Chris Masona6b0d5c2012-02-20 20:53:43 -05001044
Xiao Guangrong46224702011-04-20 10:08:47 +00001045 /* This is the initialized path, it is safe to release the devices. */
Qinghuang Fengc6e30872009-01-21 10:59:08 -05001046 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001047 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
Anand Jain401e29c2017-12-04 12:54:55 +08001048 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001049 &device->dev_state) &&
Anand Jain998a0672020-05-05 02:58:25 +08001050 !test_bit(BTRFS_DEV_STATE_MISSING,
1051 &device->dev_state) &&
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001052 (!*latest_dev ||
1053 device->generation > (*latest_dev)->generation)) {
1054 *latest_dev = device;
Chris Masona6b0d5c2012-02-20 20:53:43 -05001055 }
Yan Zheng2b820322008-11-17 21:11:30 -05001056 continue;
Chris Masona6b0d5c2012-02-20 20:53:43 -05001057 }
Yan Zheng2b820322008-11-17 21:11:30 -05001058
Stefan Behrens8dabb742012-11-06 13:15:27 +01001059 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1060 /*
1061 * In the first step, keep the device which has
1062 * the correct fsid and the devid that is used
1063 * for the dev_replace procedure.
1064 * In the second step, the dev_replace state is
1065 * read from the device tree and it is known
1066 * whether the procedure is really active or
1067 * not, which means whether this device is
1068 * used or whether it should be removed.
1069 */
Anand Jain401e29c2017-12-04 12:54:55 +08001070 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1071 &device->dev_state)) {
Stefan Behrens8dabb742012-11-06 13:15:27 +01001072 continue;
1073 }
1074 }
Yan Zheng2b820322008-11-17 21:11:30 -05001075 if (device->bdev) {
Tejun Heod4d77622010-11-13 11:55:18 +01001076 blkdev_put(device->bdev, device->mode);
Yan Zheng2b820322008-11-17 21:11:30 -05001077 device->bdev = NULL;
1078 fs_devices->open_devices--;
1079 }
Anand Jainebbede42017-12-04 12:54:52 +08001080 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
Yan Zheng2b820322008-11-17 21:11:30 -05001081 list_del_init(&device->dev_alloc_list);
Anand Jainebbede42017-12-04 12:54:52 +08001082 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Anand Jain401e29c2017-12-04 12:54:55 +08001083 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1084 &device->dev_state))
Stefan Behrens8dabb742012-11-06 13:15:27 +01001085 fs_devices->rw_devices--;
Yan Zheng2b820322008-11-17 21:11:30 -05001086 }
Yan Zhenge4404d62008-12-12 10:03:26 -05001087 list_del_init(&device->dev_list);
1088 fs_devices->num_devices--;
David Sterbaa425f9d2018-03-20 15:47:33 +01001089 btrfs_free_device(device);
Chris Masondfe25022008-05-13 13:46:40 -04001090 }
Yan Zheng2b820322008-11-17 21:11:30 -05001091
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001092}
1093
1094/*
1095 * After we have read the system tree and know devids belonging to this
1096 * filesystem, remove the device which does not belong there.
1097 */
1098void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1099{
1100 struct btrfs_device *latest_dev = NULL;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001101 struct btrfs_fs_devices *seed_dev;
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001102
1103 mutex_lock(&uuid_mutex);
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001104 __btrfs_free_extra_devids(fs_devices, step, &latest_dev);
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001105
1106 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1107 __btrfs_free_extra_devids(seed_dev, step, &latest_dev);
Yan Zheng2b820322008-11-17 21:11:30 -05001108
Miao Xie443f24f2014-07-24 11:37:15 +08001109 fs_devices->latest_bdev = latest_dev->bdev;
Chris Masona6b0d5c2012-02-20 20:53:43 -05001110
Chris Masondfe25022008-05-13 13:46:40 -04001111 mutex_unlock(&uuid_mutex);
Chris Masondfe25022008-05-13 13:46:40 -04001112}
Chris Masona0af4692008-05-13 16:03:06 -04001113
Anand Jain14238812016-07-22 06:04:53 +08001114static void btrfs_close_bdev(struct btrfs_device *device)
1115{
David Sterba08ffcae2017-06-19 16:55:35 +02001116 if (!device->bdev)
1117 return;
1118
Anand Jainebbede42017-12-04 12:54:52 +08001119 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
Anand Jain14238812016-07-22 06:04:53 +08001120 sync_blockdev(device->bdev);
1121 invalidate_bdev(device->bdev);
1122 }
1123
David Sterba08ffcae2017-06-19 16:55:35 +02001124 blkdev_put(device->bdev, device->mode);
Anand Jain14238812016-07-22 06:04:53 +08001125}
1126
Nikolay Borisov959b1c02018-06-29 08:26:05 +03001127static void btrfs_close_one_device(struct btrfs_device *device)
Anand Jainf448341a2016-06-14 18:55:25 +08001128{
1129 struct btrfs_fs_devices *fs_devices = device->fs_devices;
Anand Jainf448341a2016-06-14 18:55:25 +08001130
Anand Jainebbede42017-12-04 12:54:52 +08001131 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
Anand Jainf448341a2016-06-14 18:55:25 +08001132 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1133 list_del_init(&device->dev_alloc_list);
1134 fs_devices->rw_devices--;
1135 }
1136
Anand Jaine6e674b2017-12-04 12:54:54 +08001137 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
Anand Jainf448341a2016-06-14 18:55:25 +08001138 fs_devices->missing_devices--;
1139
Nikolay Borisov959b1c02018-06-29 08:26:05 +03001140 btrfs_close_bdev(device);
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001141 if (device->bdev) {
Johannes Thumshirn3fff3972019-11-26 09:40:05 +01001142 fs_devices->open_devices--;
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001143 device->bdev = NULL;
Anand Jainf448341a2016-06-14 18:55:25 +08001144 }
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001145 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Anand Jainf448341a2016-06-14 18:55:25 +08001146
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001147 device->fs_info = NULL;
1148 atomic_set(&device->dev_stats_ccnt, 0);
1149 extent_io_tree_release(&device->alloc_state);
Nikolay Borisov959b1c02018-06-29 08:26:05 +03001150
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001151 /* Verify the device is back in a pristine state */
1152 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1153 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1154 ASSERT(list_empty(&device->dev_alloc_list));
1155 ASSERT(list_empty(&device->post_commit_list));
1156 ASSERT(atomic_read(&device->reada_in_flight) == 0);
Anand Jainf448341a2016-06-14 18:55:25 +08001157}
1158
Nikolay Borisov54eed6a2020-07-15 13:48:48 +03001159static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
Chris Mason8a4b83c2008-03-24 15:02:07 -04001160{
Sasha Levin2037a092015-05-12 19:31:37 -04001161 struct btrfs_device *device, *tmp;
Yan Zhenge4404d62008-12-12 10:03:26 -05001162
Josef Bacik425c6ed2020-08-10 11:42:28 -04001163 lockdep_assert_held(&uuid_mutex);
1164
Yan Zheng2b820322008-11-17 21:11:30 -05001165 if (--fs_devices->opened > 0)
Nikolay Borisov54eed6a2020-07-15 13:48:48 +03001166 return;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001167
Josef Bacik425c6ed2020-08-10 11:42:28 -04001168 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
Nikolay Borisov959b1c02018-06-29 08:26:05 +03001169 btrfs_close_one_device(device);
Xiao Guangrongc9513ed2011-04-20 10:07:30 +00001170
Yan Zhenge4404d62008-12-12 10:03:26 -05001171 WARN_ON(fs_devices->open_devices);
1172 WARN_ON(fs_devices->rw_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05001173 fs_devices->opened = 0;
Johannes Thumshirn0395d842019-11-13 11:27:27 +01001174 fs_devices->seeding = false;
Nikolay Borisovc4989c2f2020-07-15 13:48:49 +03001175 fs_devices->fs_info = NULL;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001176}
1177
Nikolay Borisov54eed6a2020-07-15 13:48:48 +03001178void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
Yan Zheng2b820322008-11-17 21:11:30 -05001179{
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001180 LIST_HEAD(list);
1181 struct btrfs_fs_devices *tmp;
Yan Zheng2b820322008-11-17 21:11:30 -05001182
1183 mutex_lock(&uuid_mutex);
Nikolay Borisov54eed6a2020-07-15 13:48:48 +03001184 close_fs_devices(fs_devices);
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001185 if (!fs_devices->opened)
1186 list_splice_init(&fs_devices->seed_list, &list);
Yan Zhenge4404d62008-12-12 10:03:26 -05001187
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001188 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
Anand Jain0226e0e2018-04-12 10:29:27 +08001189 close_fs_devices(fs_devices);
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001190 list_del(&fs_devices->seed_list);
Yan Zhenge4404d62008-12-12 10:03:26 -05001191 free_fs_devices(fs_devices);
1192 }
Josef Bacik425c6ed2020-08-10 11:42:28 -04001193 mutex_unlock(&uuid_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05001194}
1195
Anand Jain897fb572018-04-12 10:29:28 +08001196static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
Yan Zhenge4404d62008-12-12 10:03:26 -05001197 fmode_t flags, void *holder)
Chris Mason8a4b83c2008-03-24 15:02:07 -04001198{
Chris Mason8a4b83c2008-03-24 15:02:07 -04001199 struct btrfs_device *device;
Miao Xie443f24f2014-07-24 11:37:15 +08001200 struct btrfs_device *latest_dev = NULL;
Anand Jain96c2e062020-09-30 21:09:52 +08001201 struct btrfs_device *tmp_device;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001202
Tejun Heod4d77622010-11-13 11:55:18 +01001203 flags |= FMODE_EXCL;
1204
Anand Jain96c2e062020-09-30 21:09:52 +08001205 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1206 dev_list) {
1207 int ret;
Chris Masona0af4692008-05-13 16:03:06 -04001208
Anand Jain96c2e062020-09-30 21:09:52 +08001209 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1210 if (ret == 0 &&
1211 (!latest_dev || device->generation > latest_dev->generation)) {
Anand Jain9f050db2017-11-09 23:45:25 +08001212 latest_dev = device;
Anand Jain96c2e062020-09-30 21:09:52 +08001213 } else if (ret == -ENODATA) {
1214 fs_devices->num_devices--;
1215 list_del(&device->dev_list);
1216 btrfs_free_device(device);
1217 }
Chris Mason8a4b83c2008-03-24 15:02:07 -04001218 }
Anand Jain1ed802c2020-04-28 23:22:25 +08001219 if (fs_devices->open_devices == 0)
1220 return -EINVAL;
1221
Yan Zheng2b820322008-11-17 21:11:30 -05001222 fs_devices->opened = 1;
Miao Xie443f24f2014-07-24 11:37:15 +08001223 fs_devices->latest_bdev = latest_dev->bdev;
Yan Zheng2b820322008-11-17 21:11:30 -05001224 fs_devices->total_rw_bytes = 0;
Naohiro Aotac4a816c2020-02-25 12:56:08 +09001225 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
Anand Jain1ed802c2020-04-28 23:22:25 +08001226
1227 return 0;
Yan Zheng2b820322008-11-17 21:11:30 -05001228}
1229
Anand Jainf8e10cd2018-01-22 14:49:36 -08001230static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1231{
1232 struct btrfs_device *dev1, *dev2;
1233
1234 dev1 = list_entry(a, struct btrfs_device, dev_list);
1235 dev2 = list_entry(b, struct btrfs_device, dev_list);
1236
1237 if (dev1->devid < dev2->devid)
1238 return -1;
1239 else if (dev1->devid > dev2->devid)
1240 return 1;
1241 return 0;
1242}
1243
Yan Zheng2b820322008-11-17 21:11:30 -05001244int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
Christoph Hellwig97288f22008-12-02 06:36:09 -05001245 fmode_t flags, void *holder)
Yan Zheng2b820322008-11-17 21:11:30 -05001246{
1247 int ret;
1248
David Sterbaf5194e32018-06-19 17:09:47 +02001249 lockdep_assert_held(&uuid_mutex);
Josef Bacik18c850f2020-07-17 15:12:27 -04001250 /*
1251 * The device_list_mutex cannot be taken here in case opening the
1252 * underlying device takes further locks like bd_mutex.
1253 *
1254 * We also don't need the lock here as this is called during mount and
1255 * exclusion is provided by uuid_mutex
1256 */
David Sterbaf5194e32018-06-19 17:09:47 +02001257
Yan Zheng2b820322008-11-17 21:11:30 -05001258 if (fs_devices->opened) {
Yan Zhenge4404d62008-12-12 10:03:26 -05001259 fs_devices->opened++;
1260 ret = 0;
Yan Zheng2b820322008-11-17 21:11:30 -05001261 } else {
Anand Jainf8e10cd2018-01-22 14:49:36 -08001262 list_sort(NULL, &fs_devices->devices, devid_cmp);
Anand Jain897fb572018-04-12 10:29:28 +08001263 ret = open_fs_devices(fs_devices, flags, holder);
Yan Zheng2b820322008-11-17 21:11:30 -05001264 }
Anand Jain542c5902018-04-12 10:29:34 +08001265
Chris Mason8a4b83c2008-03-24 15:02:07 -04001266 return ret;
1267}
1268
Johannes Thumshirn8f323802020-02-14 00:24:32 +09001269void btrfs_release_disk_super(struct btrfs_super_block *super)
Anand Jain6cf86a002016-02-13 10:01:29 +08001270{
Johannes Thumshirn8f323802020-02-14 00:24:32 +09001271 struct page *page = virt_to_page(super);
1272
Anand Jain6cf86a002016-02-13 10:01:29 +08001273 put_page(page);
1274}
1275
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001276static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1277 u64 bytenr)
Anand Jain6cf86a002016-02-13 10:01:29 +08001278{
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001279 struct btrfs_super_block *disk_super;
1280 struct page *page;
Anand Jain6cf86a002016-02-13 10:01:29 +08001281 void *p;
1282 pgoff_t index;
1283
1284 /* make sure our super fits in the device */
1285 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001286 return ERR_PTR(-EINVAL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001287
1288 /* make sure our super fits in the page */
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001289 if (sizeof(*disk_super) > PAGE_SIZE)
1290 return ERR_PTR(-EINVAL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001291
1292 /* make sure our super doesn't straddle pages on disk */
1293 index = bytenr >> PAGE_SHIFT;
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001294 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1295 return ERR_PTR(-EINVAL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001296
1297 /* pull in the page with our super */
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001298 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001299
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001300 if (IS_ERR(page))
1301 return ERR_CAST(page);
Anand Jain6cf86a002016-02-13 10:01:29 +08001302
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001303 p = page_address(page);
Anand Jain6cf86a002016-02-13 10:01:29 +08001304
1305 /* align our pointer to the offset of the super block */
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001306 disk_super = p + offset_in_page(bytenr);
Anand Jain6cf86a002016-02-13 10:01:29 +08001307
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001308 if (btrfs_super_bytenr(disk_super) != bytenr ||
1309 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
Johannes Thumshirn8f323802020-02-14 00:24:32 +09001310 btrfs_release_disk_super(p);
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001311 return ERR_PTR(-EINVAL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001312 }
1313
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001314 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1315 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
Anand Jain6cf86a002016-02-13 10:01:29 +08001316
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001317 return disk_super;
Anand Jain6cf86a002016-02-13 10:01:29 +08001318}
1319
Anand Jain228a73a2019-01-04 13:31:54 +08001320int btrfs_forget_devices(const char *path)
1321{
1322 int ret;
1323
1324 mutex_lock(&uuid_mutex);
1325 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1326 mutex_unlock(&uuid_mutex);
1327
1328 return ret;
1329}
1330
David Sterba6f60cbd2013-02-15 11:31:02 -07001331/*
1332 * Look for a btrfs signature on a device. This may be called out of the mount path
1333 * and we are not allowed to call set_blocksize during the scan. The superblock
1334 * is read via pagecache
1335 */
Gu Jinxiang36350e92018-07-12 14:23:16 +08001336struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1337 void *holder)
Chris Mason8a4b83c2008-03-24 15:02:07 -04001338{
1339 struct btrfs_super_block *disk_super;
Anand Jain4306a972018-05-29 12:28:37 +08001340 bool new_device_added = false;
Gu Jinxiang36350e92018-07-12 14:23:16 +08001341 struct btrfs_device *device = NULL;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001342 struct block_device *bdev;
David Sterba6f60cbd2013-02-15 11:31:02 -07001343 u64 bytenr;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001344
David Sterba899f9302018-06-19 16:37:36 +02001345 lockdep_assert_held(&uuid_mutex);
1346
David Sterba6f60cbd2013-02-15 11:31:02 -07001347 /*
1348 * we would like to check all the supers, but that would make
1349 * a btrfs mount succeed after a mkfs from a different FS.
1350 * So, we need to add a special mount option to scan for
1351 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1352 */
1353 bytenr = btrfs_sb_offset(0);
Tejun Heod4d77622010-11-13 11:55:18 +01001354 flags |= FMODE_EXCL;
David Sterba6f60cbd2013-02-15 11:31:02 -07001355
1356 bdev = blkdev_get_by_path(path, flags, holder);
Anand Jainb6ed73b2018-04-12 10:29:24 +08001357 if (IS_ERR(bdev))
Gu Jinxiang36350e92018-07-12 14:23:16 +08001358 return ERR_CAST(bdev);
David Sterba6f60cbd2013-02-15 11:31:02 -07001359
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001360 disk_super = btrfs_read_disk_super(bdev, bytenr);
1361 if (IS_ERR(disk_super)) {
1362 device = ERR_CAST(disk_super);
David Sterba6f60cbd2013-02-15 11:31:02 -07001363 goto error_bdev_put;
Anand Jain05a5c552017-12-15 15:40:16 +08001364 }
David Sterba6f60cbd2013-02-15 11:31:02 -07001365
Anand Jain4306a972018-05-29 12:28:37 +08001366 device = device_list_add(path, disk_super, &new_device_added);
Gu Jinxiang36350e92018-07-12 14:23:16 +08001367 if (!IS_ERR(device)) {
Anand Jain4306a972018-05-29 12:28:37 +08001368 if (new_device_added)
1369 btrfs_free_stale_devices(path, device);
1370 }
David Sterba6f60cbd2013-02-15 11:31:02 -07001371
Johannes Thumshirn8f323802020-02-14 00:24:32 +09001372 btrfs_release_disk_super(disk_super);
David Sterba6f60cbd2013-02-15 11:31:02 -07001373
1374error_bdev_put:
Tejun Heod4d77622010-11-13 11:55:18 +01001375 blkdev_put(bdev, flags);
Anand Jainb6ed73b2018-04-12 10:29:24 +08001376
Gu Jinxiang36350e92018-07-12 14:23:16 +08001377 return device;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001378}
Chris Mason0b86a832008-03-24 15:01:56 -04001379
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001380/*
1381 * Try to find a chunk that intersects [start, start + len] range and when one
1382 * such is found, record the end of it in *start
1383 */
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001384static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1385 u64 len)
Josef Bacik6df9a952013-06-27 13:22:46 -04001386{
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001387 u64 physical_start, physical_end;
Josef Bacik6df9a952013-06-27 13:22:46 -04001388
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001389 lockdep_assert_held(&device->fs_info->chunk_mutex);
Josef Bacik6df9a952013-06-27 13:22:46 -04001390
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001391 if (!find_first_extent_bit(&device->alloc_state, *start,
1392 &physical_start, &physical_end,
1393 CHUNK_ALLOCATED, NULL)) {
Filipe Mananac152b632015-05-14 10:46:03 +01001394
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001395 if (in_range(physical_start, *start, len) ||
1396 in_range(*start, physical_start,
1397 physical_end - physical_start)) {
1398 *start = physical_end + 1;
1399 return true;
Josef Bacik6df9a952013-06-27 13:22:46 -04001400 }
1401 }
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001402 return false;
Josef Bacik6df9a952013-06-27 13:22:46 -04001403}
1404
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001405static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1406{
1407 switch (device->fs_devices->chunk_alloc_policy) {
1408 case BTRFS_CHUNK_ALLOC_REGULAR:
1409 /*
1410 * We don't want to overwrite the superblock on the drive nor
1411 * any area used by the boot loader (grub for example), so we
1412 * make sure to start at an offset of at least 1MB.
1413 */
1414 return max_t(u64, start, SZ_1M);
1415 default:
1416 BUG();
1417 }
1418}
1419
1420/**
1421 * dev_extent_hole_check - check if specified hole is suitable for allocation
1422 * @device: the device which we have the hole
1423 * @hole_start: starting position of the hole
1424 * @hole_size: the size of the hole
1425 * @num_bytes: the size of the free space that we need
1426 *
1427 * This function may modify @hole_start and @hole_end to reflect the suitable
1428 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1429 */
1430static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1431 u64 *hole_size, u64 num_bytes)
1432{
1433 bool changed = false;
1434 u64 hole_end = *hole_start + *hole_size;
1435
1436 /*
1437 * Check before we set max_hole_start, otherwise we could end up
1438 * sending back this offset anyway.
1439 */
1440 if (contains_pending_extent(device, hole_start, *hole_size)) {
1441 if (hole_end >= *hole_start)
1442 *hole_size = hole_end - *hole_start;
1443 else
1444 *hole_size = 0;
1445 changed = true;
1446 }
1447
1448 switch (device->fs_devices->chunk_alloc_policy) {
1449 case BTRFS_CHUNK_ALLOC_REGULAR:
1450 /* No extra check */
1451 break;
1452 default:
1453 BUG();
1454 }
1455
1456 return changed;
1457}
Josef Bacik6df9a952013-06-27 13:22:46 -04001458
Chris Mason0b86a832008-03-24 15:01:56 -04001459/*
Jeff Mahoney499f3772015-06-15 09:41:17 -04001460 * find_free_dev_extent_start - find free space in the specified device
1461 * @device: the device which we search the free space in
1462 * @num_bytes: the size of the free space that we need
1463 * @search_start: the position from which to begin the search
1464 * @start: store the start of the free space.
1465 * @len: the size of the free space. that we find, or the size
1466 * of the max free space if we don't find suitable free space
Miao Xie7bfc8372011-01-05 10:07:26 +00001467 *
Chris Mason0b86a832008-03-24 15:01:56 -04001468 * this uses a pretty simple search, the expectation is that it is
1469 * called very infrequently and that a given device has a small number
1470 * of extents
Miao Xie7bfc8372011-01-05 10:07:26 +00001471 *
1472 * @start is used to store the start of the free space if we find. But if we
1473 * don't find suitable free space, it will be used to store the start position
1474 * of the max free space.
1475 *
1476 * @len is used to store the size of the free space that we find.
1477 * But if we don't find suitable free space, it is used to store the size of
1478 * the max free space.
Qu Wenruo135da972019-07-19 14:51:42 +08001479 *
1480 * NOTE: This function will search *commit* root of device tree, and does extra
1481 * check to ensure dev extents are not double allocated.
1482 * This makes the function safe to allocate dev extents but may not report
1483 * correct usable device space, as device extent freed in current transaction
1484 * is not reported as avaiable.
Chris Mason0b86a832008-03-24 15:01:56 -04001485 */
Qu Wenruo9e3246a2019-07-19 14:51:41 +08001486static int find_free_dev_extent_start(struct btrfs_device *device,
1487 u64 num_bytes, u64 search_start, u64 *start,
1488 u64 *len)
Chris Mason0b86a832008-03-24 15:01:56 -04001489{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04001490 struct btrfs_fs_info *fs_info = device->fs_info;
1491 struct btrfs_root *root = fs_info->dev_root;
Chris Mason0b86a832008-03-24 15:01:56 -04001492 struct btrfs_key key;
Miao Xie7bfc8372011-01-05 10:07:26 +00001493 struct btrfs_dev_extent *dev_extent;
Yan Zheng2b820322008-11-17 21:11:30 -05001494 struct btrfs_path *path;
Miao Xie7bfc8372011-01-05 10:07:26 +00001495 u64 hole_size;
1496 u64 max_hole_start;
1497 u64 max_hole_size;
1498 u64 extent_end;
Chris Mason0b86a832008-03-24 15:01:56 -04001499 u64 search_end = device->total_bytes;
1500 int ret;
Miao Xie7bfc8372011-01-05 10:07:26 +00001501 int slot;
Chris Mason0b86a832008-03-24 15:01:56 -04001502 struct extent_buffer *l;
Filipe Manana8cdc7c52016-01-06 22:42:35 +00001503
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001504 search_start = dev_extent_search_start(device, search_start);
Chris Mason0b86a832008-03-24 15:01:56 -04001505
Josef Bacik6df9a952013-06-27 13:22:46 -04001506 path = btrfs_alloc_path();
1507 if (!path)
1508 return -ENOMEM;
Zhao Leif2ab7612015-02-16 18:52:17 +08001509
Miao Xie7bfc8372011-01-05 10:07:26 +00001510 max_hole_start = search_start;
1511 max_hole_size = 0;
1512
Zhao Leif2ab7612015-02-16 18:52:17 +08001513again:
Anand Jain401e29c2017-12-04 12:54:55 +08001514 if (search_start >= search_end ||
1515 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
Miao Xie7bfc8372011-01-05 10:07:26 +00001516 ret = -ENOSPC;
Josef Bacik6df9a952013-06-27 13:22:46 -04001517 goto out;
Miao Xie7bfc8372011-01-05 10:07:26 +00001518 }
1519
David Sterbae4058b52015-11-27 16:31:35 +01001520 path->reada = READA_FORWARD;
Josef Bacik6df9a952013-06-27 13:22:46 -04001521 path->search_commit_root = 1;
1522 path->skip_locking = 1;
Miao Xie7bfc8372011-01-05 10:07:26 +00001523
Chris Mason0b86a832008-03-24 15:01:56 -04001524 key.objectid = device->devid;
1525 key.offset = search_start;
1526 key.type = BTRFS_DEV_EXTENT_KEY;
Miao Xie7bfc8372011-01-05 10:07:26 +00001527
Li Zefan125ccb02011-12-08 15:07:24 +08001528 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
Chris Mason0b86a832008-03-24 15:01:56 -04001529 if (ret < 0)
Miao Xie7bfc8372011-01-05 10:07:26 +00001530 goto out;
Yan Zheng1fcbac52009-07-24 11:06:53 -04001531 if (ret > 0) {
1532 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1533 if (ret < 0)
Miao Xie7bfc8372011-01-05 10:07:26 +00001534 goto out;
Yan Zheng1fcbac52009-07-24 11:06:53 -04001535 }
Miao Xie7bfc8372011-01-05 10:07:26 +00001536
Chris Mason0b86a832008-03-24 15:01:56 -04001537 while (1) {
1538 l = path->nodes[0];
1539 slot = path->slots[0];
1540 if (slot >= btrfs_header_nritems(l)) {
1541 ret = btrfs_next_leaf(root, path);
1542 if (ret == 0)
1543 continue;
1544 if (ret < 0)
Miao Xie7bfc8372011-01-05 10:07:26 +00001545 goto out;
1546
1547 break;
Chris Mason0b86a832008-03-24 15:01:56 -04001548 }
1549 btrfs_item_key_to_cpu(l, &key, slot);
1550
1551 if (key.objectid < device->devid)
1552 goto next;
1553
1554 if (key.objectid > device->devid)
Miao Xie7bfc8372011-01-05 10:07:26 +00001555 break;
Chris Mason0b86a832008-03-24 15:01:56 -04001556
David Sterba962a2982014-06-04 18:41:45 +02001557 if (key.type != BTRFS_DEV_EXTENT_KEY)
Chris Mason0b86a832008-03-24 15:01:56 -04001558 goto next;
Chris Mason0b86a832008-03-24 15:01:56 -04001559
Miao Xie7bfc8372011-01-05 10:07:26 +00001560 if (key.offset > search_start) {
1561 hole_size = key.offset - search_start;
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001562 dev_extent_hole_check(device, &search_start, &hole_size,
1563 num_bytes);
Josef Bacik6df9a952013-06-27 13:22:46 -04001564
Miao Xie7bfc8372011-01-05 10:07:26 +00001565 if (hole_size > max_hole_size) {
1566 max_hole_start = search_start;
1567 max_hole_size = hole_size;
1568 }
1569
1570 /*
1571 * If this free space is greater than which we need,
1572 * it must be the max free space that we have found
1573 * until now, so max_hole_start must point to the start
1574 * of this free space and the length of this free space
1575 * is stored in max_hole_size. Thus, we return
1576 * max_hole_start and max_hole_size and go back to the
1577 * caller.
1578 */
1579 if (hole_size >= num_bytes) {
1580 ret = 0;
1581 goto out;
1582 }
1583 }
1584
Chris Mason0b86a832008-03-24 15:01:56 -04001585 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
Miao Xie7bfc8372011-01-05 10:07:26 +00001586 extent_end = key.offset + btrfs_dev_extent_length(l,
1587 dev_extent);
1588 if (extent_end > search_start)
1589 search_start = extent_end;
Chris Mason0b86a832008-03-24 15:01:56 -04001590next:
1591 path->slots[0]++;
1592 cond_resched();
1593 }
Chris Mason0b86a832008-03-24 15:01:56 -04001594
liubo38c01b92011-08-02 02:39:03 +00001595 /*
1596 * At this point, search_start should be the end of
1597 * allocated dev extents, and when shrinking the device,
1598 * search_end may be smaller than search_start.
1599 */
Zhao Leif2ab7612015-02-16 18:52:17 +08001600 if (search_end > search_start) {
liubo38c01b92011-08-02 02:39:03 +00001601 hole_size = search_end - search_start;
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001602 if (dev_extent_hole_check(device, &search_start, &hole_size,
1603 num_bytes)) {
Zhao Leif2ab7612015-02-16 18:52:17 +08001604 btrfs_release_path(path);
1605 goto again;
1606 }
Chris Mason0b86a832008-03-24 15:01:56 -04001607
Zhao Leif2ab7612015-02-16 18:52:17 +08001608 if (hole_size > max_hole_size) {
1609 max_hole_start = search_start;
1610 max_hole_size = hole_size;
1611 }
Josef Bacik6df9a952013-06-27 13:22:46 -04001612 }
1613
Miao Xie7bfc8372011-01-05 10:07:26 +00001614 /* See above. */
Zhao Leif2ab7612015-02-16 18:52:17 +08001615 if (max_hole_size < num_bytes)
Miao Xie7bfc8372011-01-05 10:07:26 +00001616 ret = -ENOSPC;
1617 else
1618 ret = 0;
1619
1620out:
Yan Zheng2b820322008-11-17 21:11:30 -05001621 btrfs_free_path(path);
Miao Xie7bfc8372011-01-05 10:07:26 +00001622 *start = max_hole_start;
Miao Xieb2117a32011-01-05 10:07:28 +00001623 if (len)
Miao Xie7bfc8372011-01-05 10:07:26 +00001624 *len = max_hole_size;
Chris Mason0b86a832008-03-24 15:01:56 -04001625 return ret;
1626}
1627
Nikolay Borisov60dfdf22019-03-27 14:24:14 +02001628int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
Jeff Mahoney499f3772015-06-15 09:41:17 -04001629 u64 *start, u64 *len)
1630{
Jeff Mahoney499f3772015-06-15 09:41:17 -04001631 /* FIXME use last free of some kind */
Nikolay Borisov60dfdf22019-03-27 14:24:14 +02001632 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
Jeff Mahoney499f3772015-06-15 09:41:17 -04001633}
1634
Christoph Hellwigb2950862008-12-02 09:54:17 -05001635static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
Chris Mason8f18cf12008-04-25 16:53:30 -04001636 struct btrfs_device *device,
Miao Xie2196d6e2014-09-03 21:35:41 +08001637 u64 start, u64 *dev_extent_len)
Chris Mason8f18cf12008-04-25 16:53:30 -04001638{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04001639 struct btrfs_fs_info *fs_info = device->fs_info;
1640 struct btrfs_root *root = fs_info->dev_root;
Chris Mason8f18cf12008-04-25 16:53:30 -04001641 int ret;
1642 struct btrfs_path *path;
Chris Mason8f18cf12008-04-25 16:53:30 -04001643 struct btrfs_key key;
Chris Masona061fc82008-05-07 11:43:44 -04001644 struct btrfs_key found_key;
1645 struct extent_buffer *leaf = NULL;
1646 struct btrfs_dev_extent *extent = NULL;
Chris Mason8f18cf12008-04-25 16:53:30 -04001647
1648 path = btrfs_alloc_path();
1649 if (!path)
1650 return -ENOMEM;
1651
1652 key.objectid = device->devid;
1653 key.offset = start;
1654 key.type = BTRFS_DEV_EXTENT_KEY;
Miao Xie924cd8f2011-11-10 20:45:04 -05001655again:
Chris Mason8f18cf12008-04-25 16:53:30 -04001656 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
Chris Masona061fc82008-05-07 11:43:44 -04001657 if (ret > 0) {
1658 ret = btrfs_previous_item(root, path, key.objectid,
1659 BTRFS_DEV_EXTENT_KEY);
Tsutomu Itohb0b802d2011-05-19 07:03:42 +00001660 if (ret)
1661 goto out;
Chris Masona061fc82008-05-07 11:43:44 -04001662 leaf = path->nodes[0];
1663 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1664 extent = btrfs_item_ptr(leaf, path->slots[0],
1665 struct btrfs_dev_extent);
1666 BUG_ON(found_key.offset > start || found_key.offset +
1667 btrfs_dev_extent_length(leaf, extent) < start);
Miao Xie924cd8f2011-11-10 20:45:04 -05001668 key = found_key;
1669 btrfs_release_path(path);
1670 goto again;
Chris Masona061fc82008-05-07 11:43:44 -04001671 } else if (ret == 0) {
1672 leaf = path->nodes[0];
1673 extent = btrfs_item_ptr(leaf, path->slots[0],
1674 struct btrfs_dev_extent);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01001675 } else {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04001676 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
Jeff Mahoney79787ea2012-03-12 16:03:00 +01001677 goto out;
Chris Masona061fc82008-05-07 11:43:44 -04001678 }
Chris Mason8f18cf12008-04-25 16:53:30 -04001679
Miao Xie2196d6e2014-09-03 21:35:41 +08001680 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1681
Chris Mason8f18cf12008-04-25 16:53:30 -04001682 ret = btrfs_del_item(trans, root, path);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01001683 if (ret) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04001684 btrfs_handle_fs_error(fs_info, ret,
1685 "Failed to remove dev extent item");
Zhao Lei13212b52015-02-12 14:18:17 +08001686 } else {
Josef Bacik3204d332015-09-24 10:46:10 -04001687 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01001688 }
Tsutomu Itohb0b802d2011-05-19 07:03:42 +00001689out:
Chris Mason8f18cf12008-04-25 16:53:30 -04001690 btrfs_free_path(path);
1691 return ret;
1692}
1693
Eric Sandeen48a3b632013-04-25 20:41:01 +00001694static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1695 struct btrfs_device *device,
Eric Sandeen48a3b632013-04-25 20:41:01 +00001696 u64 chunk_offset, u64 start, u64 num_bytes)
Chris Mason0b86a832008-03-24 15:01:56 -04001697{
1698 int ret;
1699 struct btrfs_path *path;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04001700 struct btrfs_fs_info *fs_info = device->fs_info;
1701 struct btrfs_root *root = fs_info->dev_root;
Chris Mason0b86a832008-03-24 15:01:56 -04001702 struct btrfs_dev_extent *extent;
1703 struct extent_buffer *leaf;
1704 struct btrfs_key key;
1705
Anand Jaine12c9622017-12-04 12:54:53 +08001706 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
Anand Jain401e29c2017-12-04 12:54:55 +08001707 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
Chris Mason0b86a832008-03-24 15:01:56 -04001708 path = btrfs_alloc_path();
1709 if (!path)
1710 return -ENOMEM;
1711
Chris Mason0b86a832008-03-24 15:01:56 -04001712 key.objectid = device->devid;
Yan Zheng2b820322008-11-17 21:11:30 -05001713 key.offset = start;
Chris Mason0b86a832008-03-24 15:01:56 -04001714 key.type = BTRFS_DEV_EXTENT_KEY;
1715 ret = btrfs_insert_empty_item(trans, root, path, &key,
1716 sizeof(*extent));
Mark Fasheh2cdcecb2011-09-08 17:14:32 -07001717 if (ret)
1718 goto out;
Chris Mason0b86a832008-03-24 15:01:56 -04001719
1720 leaf = path->nodes[0];
1721 extent = btrfs_item_ptr(leaf, path->slots[0],
1722 struct btrfs_dev_extent);
Nikolay Borisovb5d90712017-08-18 17:58:23 +03001723 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1724 BTRFS_CHUNK_TREE_OBJECTID);
Nikolay Borisov0ca00af2017-08-18 17:58:22 +03001725 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1726 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
Chris Masone17cade2008-04-15 15:41:47 -04001727 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1728
Chris Mason0b86a832008-03-24 15:01:56 -04001729 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1730 btrfs_mark_buffer_dirty(leaf);
Mark Fasheh2cdcecb2011-09-08 17:14:32 -07001731out:
Chris Mason0b86a832008-03-24 15:01:56 -04001732 btrfs_free_path(path);
1733 return ret;
1734}
1735
Josef Bacik6df9a952013-06-27 13:22:46 -04001736static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
Chris Mason0b86a832008-03-24 15:01:56 -04001737{
Josef Bacik6df9a952013-06-27 13:22:46 -04001738 struct extent_map_tree *em_tree;
1739 struct extent_map *em;
1740 struct rb_node *n;
1741 u64 ret = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04001742
David Sterbac8bf1b62019-05-17 11:43:17 +02001743 em_tree = &fs_info->mapping_tree;
Josef Bacik6df9a952013-06-27 13:22:46 -04001744 read_lock(&em_tree->lock);
Liu Bo07e1ce02018-08-23 03:51:52 +08001745 n = rb_last(&em_tree->map.rb_root);
Josef Bacik6df9a952013-06-27 13:22:46 -04001746 if (n) {
1747 em = rb_entry(n, struct extent_map, rb_node);
1748 ret = em->start + em->len;
Chris Mason0b86a832008-03-24 15:01:56 -04001749 }
Josef Bacik6df9a952013-06-27 13:22:46 -04001750 read_unlock(&em_tree->lock);
1751
Chris Mason0b86a832008-03-24 15:01:56 -04001752 return ret;
1753}
1754
Ilya Dryomov53f10652013-08-12 14:33:01 +03001755static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1756 u64 *devid_ret)
Chris Mason0b86a832008-03-24 15:01:56 -04001757{
1758 int ret;
1759 struct btrfs_key key;
1760 struct btrfs_key found_key;
Yan Zheng2b820322008-11-17 21:11:30 -05001761 struct btrfs_path *path;
1762
Yan Zheng2b820322008-11-17 21:11:30 -05001763 path = btrfs_alloc_path();
1764 if (!path)
1765 return -ENOMEM;
Chris Mason0b86a832008-03-24 15:01:56 -04001766
1767 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1768 key.type = BTRFS_DEV_ITEM_KEY;
1769 key.offset = (u64)-1;
1770
Ilya Dryomov53f10652013-08-12 14:33:01 +03001771 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
Chris Mason0b86a832008-03-24 15:01:56 -04001772 if (ret < 0)
1773 goto error;
1774
Anand Jaina06dee4d2019-08-27 15:40:44 +08001775 if (ret == 0) {
1776 /* Corruption */
1777 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1778 ret = -EUCLEAN;
1779 goto error;
1780 }
Chris Mason0b86a832008-03-24 15:01:56 -04001781
Ilya Dryomov53f10652013-08-12 14:33:01 +03001782 ret = btrfs_previous_item(fs_info->chunk_root, path,
1783 BTRFS_DEV_ITEMS_OBJECTID,
Chris Mason0b86a832008-03-24 15:01:56 -04001784 BTRFS_DEV_ITEM_KEY);
1785 if (ret) {
Ilya Dryomov53f10652013-08-12 14:33:01 +03001786 *devid_ret = 1;
Chris Mason0b86a832008-03-24 15:01:56 -04001787 } else {
1788 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1789 path->slots[0]);
Ilya Dryomov53f10652013-08-12 14:33:01 +03001790 *devid_ret = found_key.offset + 1;
Chris Mason0b86a832008-03-24 15:01:56 -04001791 }
1792 ret = 0;
1793error:
Yan Zheng2b820322008-11-17 21:11:30 -05001794 btrfs_free_path(path);
Chris Mason0b86a832008-03-24 15:01:56 -04001795 return ret;
1796}
1797
1798/*
1799 * the device information is stored in the chunk root
1800 * the btrfs_device struct should be fully filled in
1801 */
Anand Jainc74a0b02017-11-06 16:36:15 +08001802static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
Eric Sandeen48a3b632013-04-25 20:41:01 +00001803 struct btrfs_device *device)
Chris Mason0b86a832008-03-24 15:01:56 -04001804{
1805 int ret;
1806 struct btrfs_path *path;
1807 struct btrfs_dev_item *dev_item;
1808 struct extent_buffer *leaf;
1809 struct btrfs_key key;
1810 unsigned long ptr;
Chris Mason0b86a832008-03-24 15:01:56 -04001811
Chris Mason0b86a832008-03-24 15:01:56 -04001812 path = btrfs_alloc_path();
1813 if (!path)
1814 return -ENOMEM;
1815
Chris Mason0b86a832008-03-24 15:01:56 -04001816 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1817 key.type = BTRFS_DEV_ITEM_KEY;
Yan Zheng2b820322008-11-17 21:11:30 -05001818 key.offset = device->devid;
Chris Mason0b86a832008-03-24 15:01:56 -04001819
Nikolay Borisov8e87e852018-07-20 19:37:47 +03001820 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1821 &key, sizeof(*dev_item));
Chris Mason0b86a832008-03-24 15:01:56 -04001822 if (ret)
1823 goto out;
1824
1825 leaf = path->nodes[0];
1826 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1827
1828 btrfs_set_device_id(leaf, dev_item, device->devid);
Yan Zheng2b820322008-11-17 21:11:30 -05001829 btrfs_set_device_generation(leaf, dev_item, 0);
Chris Mason0b86a832008-03-24 15:01:56 -04001830 btrfs_set_device_type(leaf, dev_item, device->type);
1831 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1832 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1833 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
Miao Xie7cc8e582014-09-03 21:35:38 +08001834 btrfs_set_device_total_bytes(leaf, dev_item,
1835 btrfs_device_get_disk_total_bytes(device));
1836 btrfs_set_device_bytes_used(leaf, dev_item,
1837 btrfs_device_get_bytes_used(device));
Chris Masone17cade2008-04-15 15:41:47 -04001838 btrfs_set_device_group(leaf, dev_item, 0);
1839 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1840 btrfs_set_device_bandwidth(leaf, dev_item, 0);
Chris Masonc3027eb2008-12-08 16:40:21 -05001841 btrfs_set_device_start_offset(leaf, dev_item, 0);
Chris Mason0b86a832008-03-24 15:01:56 -04001842
Geert Uytterhoeven410ba3a2013-08-20 13:20:11 +02001843 ptr = btrfs_device_uuid(dev_item);
Chris Masone17cade2008-04-15 15:41:47 -04001844 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
Geert Uytterhoeven1473b242013-08-20 13:20:12 +02001845 ptr = btrfs_device_fsid(dev_item);
Nikolay Borisovde37aa52018-10-30 16:43:24 +02001846 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1847 ptr, BTRFS_FSID_SIZE);
Chris Mason0b86a832008-03-24 15:01:56 -04001848 btrfs_mark_buffer_dirty(leaf);
Chris Mason0b86a832008-03-24 15:01:56 -04001849
Yan Zheng2b820322008-11-17 21:11:30 -05001850 ret = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04001851out:
1852 btrfs_free_path(path);
1853 return ret;
1854}
Chris Mason8f18cf12008-04-25 16:53:30 -04001855
Qu Wenruo5a1972b2014-04-16 17:02:32 +08001856/*
1857 * Function to update ctime/mtime for a given device path.
1858 * Mainly used for ctime/mtime based probe like libblkid.
1859 */
David Sterbada353f62017-02-14 17:55:53 +01001860static void update_dev_time(const char *path_name)
Qu Wenruo5a1972b2014-04-16 17:02:32 +08001861{
1862 struct file *filp;
1863
1864 filp = filp_open(path_name, O_RDWR, 0);
Al Viro98af5922014-12-14 02:59:17 -05001865 if (IS_ERR(filp))
Qu Wenruo5a1972b2014-04-16 17:02:32 +08001866 return;
1867 file_update_time(filp);
1868 filp_close(filp, NULL);
Qu Wenruo5a1972b2014-04-16 17:02:32 +08001869}
1870
David Sterbaf331a952019-03-20 16:31:53 +01001871static int btrfs_rm_dev_item(struct btrfs_device *device)
Chris Masona061fc82008-05-07 11:43:44 -04001872{
David Sterbaf331a952019-03-20 16:31:53 +01001873 struct btrfs_root *root = device->fs_info->chunk_root;
Chris Masona061fc82008-05-07 11:43:44 -04001874 int ret;
1875 struct btrfs_path *path;
Chris Masona061fc82008-05-07 11:43:44 -04001876 struct btrfs_key key;
Chris Masona061fc82008-05-07 11:43:44 -04001877 struct btrfs_trans_handle *trans;
1878
Chris Masona061fc82008-05-07 11:43:44 -04001879 path = btrfs_alloc_path();
1880 if (!path)
1881 return -ENOMEM;
1882
Yan, Zhenga22285a2010-05-16 10:48:46 -04001883 trans = btrfs_start_transaction(root, 0);
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00001884 if (IS_ERR(trans)) {
1885 btrfs_free_path(path);
1886 return PTR_ERR(trans);
1887 }
Chris Masona061fc82008-05-07 11:43:44 -04001888 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1889 key.type = BTRFS_DEV_ITEM_KEY;
1890 key.offset = device->devid;
1891
1892 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
Nikolay Borisov5e9f2ad2017-10-23 09:58:46 +03001893 if (ret) {
1894 if (ret > 0)
1895 ret = -ENOENT;
1896 btrfs_abort_transaction(trans, ret);
1897 btrfs_end_transaction(trans);
Chris Masona061fc82008-05-07 11:43:44 -04001898 goto out;
1899 }
1900
1901 ret = btrfs_del_item(trans, root, path);
Nikolay Borisov5e9f2ad2017-10-23 09:58:46 +03001902 if (ret) {
1903 btrfs_abort_transaction(trans, ret);
1904 btrfs_end_transaction(trans);
1905 }
1906
Chris Masona061fc82008-05-07 11:43:44 -04001907out:
1908 btrfs_free_path(path);
Nikolay Borisov5e9f2ad2017-10-23 09:58:46 +03001909 if (!ret)
1910 ret = btrfs_commit_transaction(trans);
Chris Masona061fc82008-05-07 11:43:44 -04001911 return ret;
1912}
1913
David Sterba3cc31a02016-02-15 16:00:26 +01001914/*
1915 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1916 * filesystem. It's up to the caller to adjust that number regarding eg. device
1917 * replace.
1918 */
1919static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1920 u64 num_devices)
Chris Masona061fc82008-05-07 11:43:44 -04001921{
Chris Masona061fc82008-05-07 11:43:44 -04001922 u64 all_avail;
Miao Xiede98ced2013-01-29 10:13:12 +00001923 unsigned seq;
David Sterba418775a2016-02-15 16:28:14 +01001924 int i;
Chris Masona061fc82008-05-07 11:43:44 -04001925
Miao Xiede98ced2013-01-29 10:13:12 +00001926 do {
Anand Jainbd45ffb2016-02-13 10:01:34 +08001927 seq = read_seqbegin(&fs_info->profiles_lock);
Miao Xiede98ced2013-01-29 10:13:12 +00001928
Anand Jainbd45ffb2016-02-13 10:01:34 +08001929 all_avail = fs_info->avail_data_alloc_bits |
1930 fs_info->avail_system_alloc_bits |
1931 fs_info->avail_metadata_alloc_bits;
1932 } while (read_seqretry(&fs_info->profiles_lock, seq));
Anand Jainf1fa7f22016-02-13 10:01:33 +08001933
David Sterba418775a2016-02-15 16:28:14 +01001934 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
Anand Jain41a6e892018-04-25 19:01:43 +08001935 if (!(all_avail & btrfs_raid_array[i].bg_flag))
David Sterba418775a2016-02-15 16:28:14 +01001936 continue;
Chris Masona061fc82008-05-07 11:43:44 -04001937
David Sterba418775a2016-02-15 16:28:14 +01001938 if (num_devices < btrfs_raid_array[i].devs_min) {
Anand Jainf9fbcaa2018-04-25 19:01:44 +08001939 int ret = btrfs_raid_array[i].mindev_error;
Chris Masona061fc82008-05-07 11:43:44 -04001940
David Sterba418775a2016-02-15 16:28:14 +01001941 if (ret)
1942 return ret;
1943 }
Anand Jainbd45ffb2016-02-13 10:01:34 +08001944 }
1945
1946 return 0;
Anand Jainf1fa7f22016-02-13 10:01:33 +08001947}
1948
Omar Sandovalc9162bd2017-08-22 23:46:04 -07001949static struct btrfs_device * btrfs_find_next_active_device(
1950 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
Anand Jain88acff62016-05-03 17:44:43 +08001951{
1952 struct btrfs_device *next_device;
1953
1954 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1955 if (next_device != device &&
Anand Jaine6e674b2017-12-04 12:54:54 +08001956 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1957 && next_device->bdev)
Anand Jain88acff62016-05-03 17:44:43 +08001958 return next_device;
1959 }
1960
1961 return NULL;
1962}
1963
1964/*
1965 * Helper function to check if the given device is part of s_bdev / latest_bdev
1966 * and replace it with the provided or the next active device, in the context
1967 * where this function called, there should be always be another device (or
1968 * this_dev) which is active.
1969 */
David Sterbab105e922019-10-01 19:57:35 +02001970void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
Anand Jaine493e8f2020-09-05 01:34:34 +08001971 struct btrfs_device *next_device)
Anand Jain88acff62016-05-03 17:44:43 +08001972{
Nikolay Borisovd6507cf2018-07-20 19:37:50 +03001973 struct btrfs_fs_info *fs_info = device->fs_info;
Anand Jain88acff62016-05-03 17:44:43 +08001974
Anand Jaine493e8f2020-09-05 01:34:34 +08001975 if (!next_device)
Anand Jain88acff62016-05-03 17:44:43 +08001976 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
Anand Jaine493e8f2020-09-05 01:34:34 +08001977 device);
Anand Jain88acff62016-05-03 17:44:43 +08001978 ASSERT(next_device);
1979
1980 if (fs_info->sb->s_bdev &&
1981 (fs_info->sb->s_bdev == device->bdev))
1982 fs_info->sb->s_bdev = next_device->bdev;
1983
1984 if (fs_info->fs_devices->latest_bdev == device->bdev)
1985 fs_info->fs_devices->latest_bdev = next_device->bdev;
1986}
1987
Anand Jain1da73962018-08-10 13:53:21 +08001988/*
1989 * Return btrfs_fs_devices::num_devices excluding the device that's being
1990 * currently replaced.
1991 */
1992static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1993{
1994 u64 num_devices = fs_info->fs_devices->num_devices;
1995
David Sterbacb5583d2018-09-07 16:11:23 +02001996 down_read(&fs_info->dev_replace.rwsem);
Anand Jain1da73962018-08-10 13:53:21 +08001997 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1998 ASSERT(num_devices > 1);
1999 num_devices--;
2000 }
David Sterbacb5583d2018-09-07 16:11:23 +02002001 up_read(&fs_info->dev_replace.rwsem);
Anand Jain1da73962018-08-10 13:53:21 +08002002
2003 return num_devices;
2004}
2005
Josef Bacik313b0852020-08-20 11:18:26 -04002006void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2007 struct block_device *bdev,
2008 const char *device_path)
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002009{
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002010 struct btrfs_super_block *disk_super;
2011 int copy_num;
2012
2013 if (!bdev)
2014 return;
2015
2016 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002017 struct page *page;
2018 int ret;
2019
2020 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2021 if (IS_ERR(disk_super))
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002022 continue;
2023
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002024 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002025
2026 page = virt_to_page(disk_super);
2027 set_page_dirty(page);
2028 lock_page(page);
2029 /* write_on_page() unlocks the page */
2030 ret = write_one_page(page);
2031 if (ret)
2032 btrfs_warn(fs_info,
2033 "error clearing superblock number %d (%d)",
2034 copy_num, ret);
2035 btrfs_release_disk_super(disk_super);
2036
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002037 }
2038
2039 /* Notify udev that device has changed */
2040 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2041
2042 /* Update ctime/mtime for device path for libblkid */
2043 update_dev_time(device_path);
2044}
2045
David Sterbada353f62017-02-14 17:55:53 +01002046int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
Anand Jain53f8a742020-09-05 01:34:27 +08002047 u64 devid)
Anand Jainf1fa7f22016-02-13 10:01:33 +08002048{
2049 struct btrfs_device *device;
Anand Jainf1fa7f22016-02-13 10:01:33 +08002050 struct btrfs_fs_devices *cur_devices;
Anand Jainb5185192018-04-12 10:29:30 +08002051 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Anand Jainf1fa7f22016-02-13 10:01:33 +08002052 u64 num_devices;
Anand Jainf1fa7f22016-02-13 10:01:33 +08002053 int ret = 0;
Anand Jainf1fa7f22016-02-13 10:01:33 +08002054
2055 mutex_lock(&uuid_mutex);
Chris Masona061fc82008-05-07 11:43:44 -04002056
Anand Jain1da73962018-08-10 13:53:21 +08002057 num_devices = btrfs_num_devices(fs_info);
Chris Masona061fc82008-05-07 11:43:44 -04002058
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002059 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
Anand Jainf1fa7f22016-02-13 10:01:33 +08002060 if (ret)
Chris Masona061fc82008-05-07 11:43:44 -04002061 goto out;
Chris Masona061fc82008-05-07 11:43:44 -04002062
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002063 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2064
2065 if (IS_ERR(device)) {
2066 if (PTR_ERR(device) == -ENOENT &&
2067 strcmp(device_path, "missing") == 0)
2068 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2069 else
2070 ret = PTR_ERR(device);
Chris Masona061fc82008-05-07 11:43:44 -04002071 goto out;
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002072 }
Yan Zheng2b820322008-11-17 21:11:30 -05002073
Omar Sandovaleede2bf2016-11-03 10:28:12 -07002074 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2075 btrfs_warn_in_rcu(fs_info,
2076 "cannot remove device %s (devid %llu) due to active swapfile",
2077 rcu_str_deref(device->name), device->devid);
2078 ret = -ETXTBSY;
2079 goto out;
2080 }
2081
Anand Jain401e29c2017-12-04 12:54:55 +08002082 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
Anand Jain183860f2013-05-17 10:52:45 +00002083 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
Anand Jain24fc5722016-02-13 10:01:36 +08002084 goto out;
Stefan Behrens63a212a2012-11-05 18:29:28 +01002085 }
2086
Anand Jainebbede42017-12-04 12:54:52 +08002087 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2088 fs_info->fs_devices->rw_devices == 1) {
Anand Jain183860f2013-05-17 10:52:45 +00002089 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
Anand Jain24fc5722016-02-13 10:01:36 +08002090 goto out;
Yan Zheng2b820322008-11-17 21:11:30 -05002091 }
2092
Anand Jainebbede42017-12-04 12:54:52 +08002093 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
David Sterba34441362016-10-04 19:34:27 +02002094 mutex_lock(&fs_info->chunk_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05002095 list_del_init(&device->dev_alloc_list);
Miao Xiec3929c32014-09-03 21:35:47 +08002096 device->fs_devices->rw_devices--;
David Sterba34441362016-10-04 19:34:27 +02002097 mutex_unlock(&fs_info->chunk_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05002098 }
Chris Masona061fc82008-05-07 11:43:44 -04002099
Carey Underwoodd7901552013-03-04 16:37:06 -06002100 mutex_unlock(&uuid_mutex);
Chris Masona061fc82008-05-07 11:43:44 -04002101 ret = btrfs_shrink_device(device, 0);
Filipe Manana66d204a2020-10-12 11:55:24 +01002102 if (!ret)
2103 btrfs_reada_remove_dev(device);
Carey Underwoodd7901552013-03-04 16:37:06 -06002104 mutex_lock(&uuid_mutex);
Chris Masona061fc82008-05-07 11:43:44 -04002105 if (ret)
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002106 goto error_undo;
Chris Masona061fc82008-05-07 11:43:44 -04002107
Stefan Behrens63a212a2012-11-05 18:29:28 +01002108 /*
2109 * TODO: the superblock still includes this device in its num_devices
2110 * counter although write_all_supers() is not locked out. This
2111 * could give a filesystem state which requires a degraded mount.
2112 */
David Sterbaf331a952019-03-20 16:31:53 +01002113 ret = btrfs_rm_dev_item(device);
Chris Masona061fc82008-05-07 11:43:44 -04002114 if (ret)
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002115 goto error_undo;
Chris Masona061fc82008-05-07 11:43:44 -04002116
Anand Jaine12c9622017-12-04 12:54:53 +08002117 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
David Sterba163e97e2019-03-20 16:32:55 +01002118 btrfs_scrub_cancel_dev(device);
Chris Masone5e9a522009-06-10 15:17:02 -04002119
2120 /*
2121 * the device list mutex makes sure that we don't change
2122 * the device list while someone else is writing out all
Filipe David Borba Mananad7306802013-08-09 15:41:36 +01002123 * the device supers. Whoever is writing all supers, should
2124 * lock the device list mutex before getting the number of
2125 * devices in the super block (super_copy). Conversely,
2126 * whoever updates the number of devices in the super block
2127 * (super_copy) should hold the device list mutex.
Chris Masone5e9a522009-06-10 15:17:02 -04002128 */
Xiao Guangrong1f781602011-04-20 10:09:16 +00002129
Anand Jain41a52a02018-04-12 10:29:31 +08002130 /*
2131 * In normal cases the cur_devices == fs_devices. But in case
2132 * of deleting a seed device, the cur_devices should point to
2133 * its own fs_devices listed under the fs_devices->seed.
2134 */
Xiao Guangrong1f781602011-04-20 10:09:16 +00002135 cur_devices = device->fs_devices;
Anand Jainb5185192018-04-12 10:29:30 +08002136 mutex_lock(&fs_devices->device_list_mutex);
Xiao Guangrong1f781602011-04-20 10:09:16 +00002137 list_del_rcu(&device->dev_list);
Chris Masone5e9a522009-06-10 15:17:02 -04002138
Anand Jain41a52a02018-04-12 10:29:31 +08002139 cur_devices->num_devices--;
2140 cur_devices->total_devices--;
Anand Jainb4993e62018-07-03 17:07:23 +08002141 /* Update total_devices of the parent fs_devices if it's seed */
2142 if (cur_devices != fs_devices)
2143 fs_devices->total_devices--;
Yan Zheng2b820322008-11-17 21:11:30 -05002144
Anand Jaine6e674b2017-12-04 12:54:54 +08002145 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
Anand Jain41a52a02018-04-12 10:29:31 +08002146 cur_devices->missing_devices--;
Chris Masoncd02dca2010-12-13 14:56:23 -05002147
Nikolay Borisovd6507cf2018-07-20 19:37:50 +03002148 btrfs_assign_next_active_device(device, NULL);
Yan Zheng2b820322008-11-17 21:11:30 -05002149
Eric Sandeen0bfaa9c2014-07-07 12:34:49 -05002150 if (device->bdev) {
Anand Jain41a52a02018-04-12 10:29:31 +08002151 cur_devices->open_devices--;
Eric Sandeen0bfaa9c2014-07-07 12:34:49 -05002152 /* remove sysfs entry */
Anand Jain53f8a742020-09-05 01:34:27 +08002153 btrfs_sysfs_remove_device(device);
Eric Sandeen0bfaa9c2014-07-07 12:34:49 -05002154 }
Anand Jain99994cd2014-06-03 11:36:00 +08002155
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002156 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2157 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
Anand Jainb5185192018-04-12 10:29:30 +08002158 mutex_unlock(&fs_devices->device_list_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05002159
Jeff Mahoneycea67ab2016-09-20 08:50:21 -04002160 /*
2161 * at this point, the device is zero sized and detached from
2162 * the devices list. All that's left is to zero out the old
2163 * supers and free the device.
2164 */
Anand Jainebbede42017-12-04 12:54:52 +08002165 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002166 btrfs_scratch_superblocks(fs_info, device->bdev,
2167 device->name->str);
Jeff Mahoneycea67ab2016-09-20 08:50:21 -04002168
2169 btrfs_close_bdev(device);
Nikolay Borisov8e75fd82019-03-27 14:24:11 +02002170 synchronize_rcu();
2171 btrfs_free_device(device);
Jeff Mahoneycea67ab2016-09-20 08:50:21 -04002172
Xiao Guangrong1f781602011-04-20 10:09:16 +00002173 if (cur_devices->open_devices == 0) {
Nikolay Borisov944d3f92020-07-16 10:25:33 +03002174 list_del_init(&cur_devices->seed_list);
Anand Jain0226e0e2018-04-12 10:29:27 +08002175 close_fs_devices(cur_devices);
Xiao Guangrong1f781602011-04-20 10:09:16 +00002176 free_fs_devices(cur_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05002177 }
2178
Chris Masona061fc82008-05-07 11:43:44 -04002179out:
2180 mutex_unlock(&uuid_mutex);
Chris Masona061fc82008-05-07 11:43:44 -04002181 return ret;
Anand Jain24fc5722016-02-13 10:01:36 +08002182
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002183error_undo:
Filipe Manana66d204a2020-10-12 11:55:24 +01002184 btrfs_reada_undo_remove_dev(device);
Anand Jainebbede42017-12-04 12:54:52 +08002185 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
David Sterba34441362016-10-04 19:34:27 +02002186 mutex_lock(&fs_info->chunk_mutex);
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002187 list_add(&device->dev_alloc_list,
Anand Jainb5185192018-04-12 10:29:30 +08002188 &fs_devices->alloc_list);
Miao Xiec3929c32014-09-03 21:35:47 +08002189 device->fs_devices->rw_devices++;
David Sterba34441362016-10-04 19:34:27 +02002190 mutex_unlock(&fs_info->chunk_mutex);
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002191 }
Anand Jain24fc5722016-02-13 10:01:36 +08002192 goto out;
Chris Masona061fc82008-05-07 11:43:44 -04002193}
2194
Nikolay Borisov68a9db52018-07-20 19:37:48 +03002195void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
Stefan Behrense93c89c2012-11-05 17:33:06 +01002196{
Anand Jaind51908c2014-08-13 14:24:19 +08002197 struct btrfs_fs_devices *fs_devices;
2198
Nikolay Borisov68a9db52018-07-20 19:37:48 +03002199 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
Ilya Dryomov13572722013-10-02 20:41:01 +03002200
Anand Jain25e8e912014-08-20 10:56:56 +08002201 /*
2202 * in case of fs with no seed, srcdev->fs_devices will point
2203 * to fs_devices of fs_info. However when the dev being replaced is
2204 * a seed dev it will point to the seed's local fs_devices. In short
2205 * srcdev will have its correct fs_devices in both the cases.
2206 */
2207 fs_devices = srcdev->fs_devices;
Anand Jaind51908c2014-08-13 14:24:19 +08002208
Stefan Behrense93c89c2012-11-05 17:33:06 +01002209 list_del_rcu(&srcdev->dev_list);
David Sterba619c47f2017-06-19 14:14:22 +02002210 list_del(&srcdev->dev_alloc_list);
Anand Jaind51908c2014-08-13 14:24:19 +08002211 fs_devices->num_devices--;
Anand Jaine6e674b2017-12-04 12:54:54 +08002212 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
Anand Jaind51908c2014-08-13 14:24:19 +08002213 fs_devices->missing_devices--;
Stefan Behrense93c89c2012-11-05 17:33:06 +01002214
Anand Jainebbede42017-12-04 12:54:52 +08002215 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
Miao Xie82372bc2014-09-03 21:35:44 +08002216 fs_devices->rw_devices--;
Ilya Dryomov13572722013-10-02 20:41:01 +03002217
Miao Xie82372bc2014-09-03 21:35:44 +08002218 if (srcdev->bdev)
Anand Jaind51908c2014-08-13 14:24:19 +08002219 fs_devices->open_devices--;
Qu Wenruo084b6e7c2014-10-30 16:52:31 +08002220}
2221
David Sterba65237ee2019-03-20 16:34:54 +01002222void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
Qu Wenruo084b6e7c2014-10-30 16:52:31 +08002223{
2224 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
Stefan Behrense93c89c2012-11-05 17:33:06 +01002225
Josef Bacika466c852020-08-20 11:18:27 -04002226 mutex_lock(&uuid_mutex);
2227
Anand Jain14238812016-07-22 06:04:53 +08002228 btrfs_close_bdev(srcdev);
Nikolay Borisov8e75fd82019-03-27 14:24:11 +02002229 synchronize_rcu();
2230 btrfs_free_device(srcdev);
Anand Jain94d5f0c2014-08-13 14:24:22 +08002231
Anand Jain94d5f0c2014-08-13 14:24:22 +08002232 /* if this is no devs we rather delete the fs_devices */
2233 if (!fs_devices->num_devices) {
Anand Jain6dd38f82017-10-17 06:53:50 +08002234 /*
2235 * On a mounted FS, num_devices can't be zero unless it's a
2236 * seed. In case of a seed device being replaced, the replace
2237 * target added to the sprout FS, so there will be no more
2238 * device left under the seed FS.
2239 */
2240 ASSERT(fs_devices->seeding);
2241
Nikolay Borisov944d3f92020-07-16 10:25:33 +03002242 list_del_init(&fs_devices->seed_list);
Anand Jain0226e0e2018-04-12 10:29:27 +08002243 close_fs_devices(fs_devices);
Anand Jain8bef8402014-08-13 14:24:23 +08002244 free_fs_devices(fs_devices);
Anand Jain94d5f0c2014-08-13 14:24:22 +08002245 }
Josef Bacika466c852020-08-20 11:18:27 -04002246 mutex_unlock(&uuid_mutex);
Stefan Behrense93c89c2012-11-05 17:33:06 +01002247}
2248
Nikolay Borisov4f5ad7b2018-07-20 19:37:51 +03002249void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
Stefan Behrense93c89c2012-11-05 17:33:06 +01002250{
Nikolay Borisov4f5ad7b2018-07-20 19:37:51 +03002251 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
Anand Jaind2ff1b22015-03-10 06:38:42 +08002252
Anand Jaind9a071f2018-04-12 10:29:38 +08002253 mutex_lock(&fs_devices->device_list_mutex);
2254
Anand Jain53f8a742020-09-05 01:34:27 +08002255 btrfs_sysfs_remove_device(tgtdev);
Anand Jaind2ff1b22015-03-10 06:38:42 +08002256
Anand Jain779bf3fe2016-04-18 16:51:23 +08002257 if (tgtdev->bdev)
Anand Jaind9a071f2018-04-12 10:29:38 +08002258 fs_devices->open_devices--;
Anand Jain779bf3fe2016-04-18 16:51:23 +08002259
Anand Jaind9a071f2018-04-12 10:29:38 +08002260 fs_devices->num_devices--;
Stefan Behrense93c89c2012-11-05 17:33:06 +01002261
Nikolay Borisovd6507cf2018-07-20 19:37:50 +03002262 btrfs_assign_next_active_device(tgtdev, NULL);
Stefan Behrense93c89c2012-11-05 17:33:06 +01002263
Stefan Behrense93c89c2012-11-05 17:33:06 +01002264 list_del_rcu(&tgtdev->dev_list);
Stefan Behrense93c89c2012-11-05 17:33:06 +01002265
Anand Jaind9a071f2018-04-12 10:29:38 +08002266 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jain779bf3fe2016-04-18 16:51:23 +08002267
2268 /*
2269 * The update_dev_time() with in btrfs_scratch_superblocks()
2270 * may lead to a call to btrfs_show_devname() which will try
2271 * to hold device_list_mutex. And here this device
2272 * is already out of device list, so we don't have to hold
2273 * the device_list_mutex lock.
2274 */
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002275 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2276 tgtdev->name->str);
Anand Jain14238812016-07-22 06:04:53 +08002277
2278 btrfs_close_bdev(tgtdev);
Nikolay Borisov8e75fd82019-03-27 14:24:11 +02002279 synchronize_rcu();
2280 btrfs_free_device(tgtdev);
Stefan Behrense93c89c2012-11-05 17:33:06 +01002281}
2282
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002283static struct btrfs_device *btrfs_find_device_by_path(
2284 struct btrfs_fs_info *fs_info, const char *device_path)
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002285{
2286 int ret = 0;
2287 struct btrfs_super_block *disk_super;
2288 u64 devid;
2289 u8 *dev_uuid;
2290 struct block_device *bdev;
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002291 struct btrfs_device *device;
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002292
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002293 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002294 fs_info->bdev_holder, 0, &bdev, &disk_super);
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002295 if (ret)
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002296 return ERR_PTR(ret);
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002297
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002298 devid = btrfs_stack_device_id(&disk_super->dev_item);
2299 dev_uuid = disk_super->dev_item.uuid;
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002300 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
Anand Jaine4319cd2019-01-17 23:32:31 +08002301 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
Anand Jain09ba3bc2019-01-19 14:48:55 +08002302 disk_super->metadata_uuid, true);
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002303 else
Anand Jaine4319cd2019-01-17 23:32:31 +08002304 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
Anand Jain09ba3bc2019-01-19 14:48:55 +08002305 disk_super->fsid, true);
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002306
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002307 btrfs_release_disk_super(disk_super);
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002308 if (!device)
2309 device = ERR_PTR(-ENOENT);
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002310 blkdev_put(bdev, FMODE_READ);
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002311 return device;
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002312}
2313
Yan Zheng2b820322008-11-17 21:11:30 -05002314/*
David Sterba5c5c0df2016-02-15 16:39:55 +01002315 * Lookup a device given by device id, or the path if the id is 0.
2316 */
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002317struct btrfs_device *btrfs_find_device_by_devspec(
Anand Jain6e927ce2019-01-17 23:32:29 +08002318 struct btrfs_fs_info *fs_info, u64 devid,
2319 const char *device_path)
Anand Jain24e04742016-02-13 10:01:35 +08002320{
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002321 struct btrfs_device *device;
Anand Jain24e04742016-02-13 10:01:35 +08002322
David Sterba5c5c0df2016-02-15 16:39:55 +01002323 if (devid) {
Anand Jaine4319cd2019-01-17 23:32:31 +08002324 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
Anand Jain09ba3bc2019-01-19 14:48:55 +08002325 NULL, true);
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002326 if (!device)
2327 return ERR_PTR(-ENOENT);
Anand Jain6e927ce2019-01-17 23:32:29 +08002328 return device;
Anand Jain24e04742016-02-13 10:01:35 +08002329 }
Anand Jain6e927ce2019-01-17 23:32:29 +08002330
2331 if (!device_path || !device_path[0])
2332 return ERR_PTR(-EINVAL);
2333
2334 if (strcmp(device_path, "missing") == 0) {
2335 /* Find first missing device */
2336 list_for_each_entry(device, &fs_info->fs_devices->devices,
2337 dev_list) {
2338 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2339 &device->dev_state) && !device->bdev)
2340 return device;
2341 }
2342 return ERR_PTR(-ENOENT);
2343 }
2344
2345 return btrfs_find_device_by_path(fs_info, device_path);
Anand Jain24e04742016-02-13 10:01:35 +08002346}
2347
Yan Zheng2b820322008-11-17 21:11:30 -05002348/*
2349 * does all the dirty work required for changing file system's UUID.
2350 */
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04002351static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
Yan Zheng2b820322008-11-17 21:11:30 -05002352{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002353 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05002354 struct btrfs_fs_devices *old_devices;
Yan Zhenge4404d62008-12-12 10:03:26 -05002355 struct btrfs_fs_devices *seed_devices;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002356 struct btrfs_super_block *disk_super = fs_info->super_copy;
Yan Zheng2b820322008-11-17 21:11:30 -05002357 struct btrfs_device *device;
2358 u64 super_flags;
2359
David Sterbaa32bf9a2018-03-16 02:21:22 +01002360 lockdep_assert_held(&uuid_mutex);
Yan Zhenge4404d62008-12-12 10:03:26 -05002361 if (!fs_devices->seeding)
Yan Zheng2b820322008-11-17 21:11:30 -05002362 return -EINVAL;
2363
Nikolay Borisov427c8fd2020-08-12 17:04:36 +03002364 /*
2365 * Private copy of the seed devices, anchored at
2366 * fs_info->fs_devices->seed_list
2367 */
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002368 seed_devices = alloc_fs_devices(NULL, NULL);
Ilya Dryomov2208a372013-08-12 14:33:03 +03002369 if (IS_ERR(seed_devices))
2370 return PTR_ERR(seed_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05002371
Nikolay Borisov427c8fd2020-08-12 17:04:36 +03002372 /*
2373 * It's necessary to retain a copy of the original seed fs_devices in
2374 * fs_uuids so that filesystems which have been seeded can successfully
2375 * reference the seed device from open_seed_devices. This also supports
2376 * multiple fs seed.
2377 */
Yan Zhenge4404d62008-12-12 10:03:26 -05002378 old_devices = clone_fs_devices(fs_devices);
2379 if (IS_ERR(old_devices)) {
2380 kfree(seed_devices);
2381 return PTR_ERR(old_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05002382 }
Yan Zhenge4404d62008-12-12 10:03:26 -05002383
Anand Jainc4babc52018-04-12 10:29:25 +08002384 list_add(&old_devices->fs_list, &fs_uuids);
Yan Zheng2b820322008-11-17 21:11:30 -05002385
Yan Zhenge4404d62008-12-12 10:03:26 -05002386 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2387 seed_devices->opened = 1;
2388 INIT_LIST_HEAD(&seed_devices->devices);
2389 INIT_LIST_HEAD(&seed_devices->alloc_list);
Chris Masone5e9a522009-06-10 15:17:02 -04002390 mutex_init(&seed_devices->device_list_mutex);
Xiao Guangrongc9513ed2011-04-20 10:07:30 +00002391
Anand Jain321a4bf2018-07-16 22:58:09 +08002392 mutex_lock(&fs_devices->device_list_mutex);
Xiao Guangrong1f781602011-04-20 10:09:16 +00002393 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2394 synchronize_rcu);
Miao Xie2196d6e2014-09-03 21:35:41 +08002395 list_for_each_entry(device, &seed_devices->devices, dev_list)
Yan Zhenge4404d62008-12-12 10:03:26 -05002396 device->fs_devices = seed_devices;
Miao Xie2196d6e2014-09-03 21:35:41 +08002397
Johannes Thumshirn0395d842019-11-13 11:27:27 +01002398 fs_devices->seeding = false;
Yan Zheng2b820322008-11-17 21:11:30 -05002399 fs_devices->num_devices = 0;
2400 fs_devices->open_devices = 0;
Miao Xie69611ac2014-07-03 18:22:12 +08002401 fs_devices->missing_devices = 0;
Johannes Thumshirn7f0432d2019-11-13 11:27:28 +01002402 fs_devices->rotating = false;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03002403 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
Yan Zheng2b820322008-11-17 21:11:30 -05002404
2405 generate_random_uuid(fs_devices->fsid);
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002406 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
Yan Zheng2b820322008-11-17 21:11:30 -05002407 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
Anand Jain321a4bf2018-07-16 22:58:09 +08002408 mutex_unlock(&fs_devices->device_list_mutex);
Filipe David Borba Mananaf7171752013-08-12 20:56:58 +01002409
Yan Zheng2b820322008-11-17 21:11:30 -05002410 super_flags = btrfs_super_flags(disk_super) &
2411 ~BTRFS_SUPER_FLAG_SEEDING;
2412 btrfs_set_super_flags(disk_super, super_flags);
2413
2414 return 0;
2415}
2416
2417/*
Nicholas D Steeves01327612016-05-19 21:18:45 -04002418 * Store the expected generation for seed devices in device items.
Yan Zheng2b820322008-11-17 21:11:30 -05002419 */
David Sterba5c4666292019-03-20 16:36:39 +01002420static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
Yan Zheng2b820322008-11-17 21:11:30 -05002421{
David Sterba5c4666292019-03-20 16:36:39 +01002422 struct btrfs_fs_info *fs_info = trans->fs_info;
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04002423 struct btrfs_root *root = fs_info->chunk_root;
Yan Zheng2b820322008-11-17 21:11:30 -05002424 struct btrfs_path *path;
2425 struct extent_buffer *leaf;
2426 struct btrfs_dev_item *dev_item;
2427 struct btrfs_device *device;
2428 struct btrfs_key key;
Anand Jain44880fd2017-07-29 17:50:09 +08002429 u8 fs_uuid[BTRFS_FSID_SIZE];
Yan Zheng2b820322008-11-17 21:11:30 -05002430 u8 dev_uuid[BTRFS_UUID_SIZE];
2431 u64 devid;
2432 int ret;
2433
2434 path = btrfs_alloc_path();
2435 if (!path)
2436 return -ENOMEM;
2437
Yan Zheng2b820322008-11-17 21:11:30 -05002438 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2439 key.offset = 0;
2440 key.type = BTRFS_DEV_ITEM_KEY;
2441
2442 while (1) {
2443 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2444 if (ret < 0)
2445 goto error;
2446
2447 leaf = path->nodes[0];
2448next_slot:
2449 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2450 ret = btrfs_next_leaf(root, path);
2451 if (ret > 0)
2452 break;
2453 if (ret < 0)
2454 goto error;
2455 leaf = path->nodes[0];
2456 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
David Sterbab3b4aa72011-04-21 01:20:15 +02002457 btrfs_release_path(path);
Yan Zheng2b820322008-11-17 21:11:30 -05002458 continue;
2459 }
2460
2461 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2462 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2463 key.type != BTRFS_DEV_ITEM_KEY)
2464 break;
2465
2466 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2467 struct btrfs_dev_item);
2468 devid = btrfs_device_id(leaf, dev_item);
Geert Uytterhoeven410ba3a2013-08-20 13:20:11 +02002469 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
Yan Zheng2b820322008-11-17 21:11:30 -05002470 BTRFS_UUID_SIZE);
Geert Uytterhoeven1473b242013-08-20 13:20:12 +02002471 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
Anand Jain44880fd2017-07-29 17:50:09 +08002472 BTRFS_FSID_SIZE);
Anand Jaine4319cd2019-01-17 23:32:31 +08002473 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
Anand Jain09ba3bc2019-01-19 14:48:55 +08002474 fs_uuid, true);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002475 BUG_ON(!device); /* Logic error */
Yan Zheng2b820322008-11-17 21:11:30 -05002476
2477 if (device->fs_devices->seeding) {
2478 btrfs_set_device_generation(leaf, dev_item,
2479 device->generation);
2480 btrfs_mark_buffer_dirty(leaf);
2481 }
2482
2483 path->slots[0]++;
2484 goto next_slot;
2485 }
2486 ret = 0;
2487error:
2488 btrfs_free_path(path);
2489 return ret;
2490}
2491
David Sterbada353f62017-02-14 17:55:53 +01002492int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
Chris Mason788f20e2008-04-28 15:29:42 -04002493{
Jeff Mahoney5112feb2016-06-21 20:16:08 -04002494 struct btrfs_root *root = fs_info->dev_root;
Josef Bacikd5e20032011-08-04 14:52:27 +00002495 struct request_queue *q;
Chris Mason788f20e2008-04-28 15:29:42 -04002496 struct btrfs_trans_handle *trans;
2497 struct btrfs_device *device;
2498 struct block_device *bdev;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002499 struct super_block *sb = fs_info->sb;
Josef Bacik606686e2012-06-04 14:03:51 -04002500 struct rcu_string *name;
Anand Jain5da54bc2018-07-03 13:14:50 +08002501 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Naohiro Aota39379fa2018-07-27 09:04:55 +09002502 u64 orig_super_total_bytes;
2503 u64 orig_super_num_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05002504 int seeding_dev = 0;
Chris Mason788f20e2008-04-28 15:29:42 -04002505 int ret = 0;
Nikolay Borisov44cab9b2020-07-22 11:09:23 +03002506 bool locked = false;
Chris Mason788f20e2008-04-28 15:29:42 -04002507
Anand Jain5da54bc2018-07-03 13:14:50 +08002508 if (sb_rdonly(sb) && !fs_devices->seeding)
Liu Bof8c5d0b2012-05-10 18:10:38 +08002509 return -EROFS;
Chris Mason788f20e2008-04-28 15:29:42 -04002510
Li Zefana5d163332011-12-07 20:08:40 -05002511 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002512 fs_info->bdev_holder);
Josef Bacik7f592032010-01-27 02:09:00 +00002513 if (IS_ERR(bdev))
2514 return PTR_ERR(bdev);
Chris Masona2135012008-06-25 16:01:30 -04002515
Anand Jain5da54bc2018-07-03 13:14:50 +08002516 if (fs_devices->seeding) {
Yan Zheng2b820322008-11-17 21:11:30 -05002517 seeding_dev = 1;
2518 down_write(&sb->s_umount);
2519 mutex_lock(&uuid_mutex);
Nikolay Borisov44cab9b2020-07-22 11:09:23 +03002520 locked = true;
Yan Zheng2b820322008-11-17 21:11:30 -05002521 }
2522
Nikolay Borisovb9ba0172020-07-22 11:09:25 +03002523 sync_blockdev(bdev);
Chris Masona2135012008-06-25 16:01:30 -04002524
Nikolay Borisovf4cfa9b2020-07-22 11:09:22 +03002525 rcu_read_lock();
2526 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
Chris Mason788f20e2008-04-28 15:29:42 -04002527 if (device->bdev == bdev) {
2528 ret = -EEXIST;
Nikolay Borisovf4cfa9b2020-07-22 11:09:22 +03002529 rcu_read_unlock();
Yan Zheng2b820322008-11-17 21:11:30 -05002530 goto error;
Chris Mason788f20e2008-04-28 15:29:42 -04002531 }
2532 }
Nikolay Borisovf4cfa9b2020-07-22 11:09:22 +03002533 rcu_read_unlock();
Chris Mason788f20e2008-04-28 15:29:42 -04002534
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002535 device = btrfs_alloc_device(fs_info, NULL, NULL);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03002536 if (IS_ERR(device)) {
Chris Mason788f20e2008-04-28 15:29:42 -04002537 /* we can safely leave the fs_devices entry around */
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03002538 ret = PTR_ERR(device);
Yan Zheng2b820322008-11-17 21:11:30 -05002539 goto error;
Chris Mason788f20e2008-04-28 15:29:42 -04002540 }
2541
David Sterba78f2c9e2016-02-11 14:25:38 +01002542 name = rcu_string_strdup(device_path, GFP_KERNEL);
Josef Bacik606686e2012-06-04 14:03:51 -04002543 if (!name) {
Yan Zheng2b820322008-11-17 21:11:30 -05002544 ret = -ENOMEM;
David Sterba5c4cf6c2017-10-30 19:29:46 +01002545 goto error_free_device;
Chris Mason788f20e2008-04-28 15:29:42 -04002546 }
Josef Bacik606686e2012-06-04 14:03:51 -04002547 rcu_assign_pointer(device->name, name);
Yan Zheng2b820322008-11-17 21:11:30 -05002548
Yan, Zhenga22285a2010-05-16 10:48:46 -04002549 trans = btrfs_start_transaction(root, 0);
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00002550 if (IS_ERR(trans)) {
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00002551 ret = PTR_ERR(trans);
David Sterba5c4cf6c2017-10-30 19:29:46 +01002552 goto error_free_device;
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00002553 }
2554
Josef Bacikd5e20032011-08-04 14:52:27 +00002555 q = bdev_get_queue(bdev);
Anand Jainebbede42017-12-04 12:54:52 +08002556 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Yan Zheng2b820322008-11-17 21:11:30 -05002557 device->generation = trans->transid;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002558 device->io_width = fs_info->sectorsize;
2559 device->io_align = fs_info->sectorsize;
2560 device->sector_size = fs_info->sectorsize;
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03002561 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2562 fs_info->sectorsize);
Yan Zheng2cc3c552009-06-04 09:23:50 -04002563 device->disk_total_bytes = device->total_bytes;
Miao Xie935e5cc2014-09-03 21:35:33 +08002564 device->commit_total_bytes = device->total_bytes;
Jeff Mahoneyfb456252016-06-22 18:54:56 -04002565 device->fs_info = fs_info;
Chris Mason788f20e2008-04-28 15:29:42 -04002566 device->bdev = bdev;
Anand Jaine12c9622017-12-04 12:54:53 +08002567 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
Anand Jain401e29c2017-12-04 12:54:55 +08002568 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
Ilya Dryomovfb01aa82011-02-15 18:12:57 +00002569 device->mode = FMODE_EXCL;
Stefan Behrens27087f32013-10-11 15:20:42 +02002570 device->dev_stats_valid = 1;
David Sterba9f6d2512017-06-16 01:48:05 +02002571 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
Zheng Yan325cd4b2008-09-05 16:43:54 -04002572
Yan Zheng2b820322008-11-17 21:11:30 -05002573 if (seeding_dev) {
Linus Torvalds1751e8a2017-11-27 13:05:09 -08002574 sb->s_flags &= ~SB_RDONLY;
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04002575 ret = btrfs_prepare_sprout(fs_info);
Anand Jaind31c32f2017-09-28 14:51:10 +08002576 if (ret) {
2577 btrfs_abort_transaction(trans, ret);
2578 goto error_trans;
2579 }
Yan Zheng2b820322008-11-17 21:11:30 -05002580 }
2581
Anand Jain5da54bc2018-07-03 13:14:50 +08002582 device->fs_devices = fs_devices;
Chris Masone5e9a522009-06-10 15:17:02 -04002583
Anand Jain5da54bc2018-07-03 13:14:50 +08002584 mutex_lock(&fs_devices->device_list_mutex);
David Sterba34441362016-10-04 19:34:27 +02002585 mutex_lock(&fs_info->chunk_mutex);
Anand Jain5da54bc2018-07-03 13:14:50 +08002586 list_add_rcu(&device->dev_list, &fs_devices->devices);
2587 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2588 fs_devices->num_devices++;
2589 fs_devices->open_devices++;
2590 fs_devices->rw_devices++;
2591 fs_devices->total_devices++;
2592 fs_devices->total_rw_bytes += device->total_bytes;
Yan Zheng2b820322008-11-17 21:11:30 -05002593
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03002594 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
Josef Bacik2bf64752011-09-26 17:12:22 -04002595
Anand Jaine884f4f2017-04-04 18:40:19 +08002596 if (!blk_queue_nonrot(q))
Johannes Thumshirn7f0432d2019-11-13 11:27:28 +01002597 fs_devices->rotating = true;
Chris Masonc2898112009-06-10 09:51:32 -04002598
Naohiro Aota39379fa2018-07-27 09:04:55 +09002599 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002600 btrfs_set_super_total_bytes(fs_info->super_copy,
Naohiro Aota39379fa2018-07-27 09:04:55 +09002601 round_down(orig_super_total_bytes + device->total_bytes,
2602 fs_info->sectorsize));
Chris Mason788f20e2008-04-28 15:29:42 -04002603
Naohiro Aota39379fa2018-07-27 09:04:55 +09002604 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2605 btrfs_set_super_num_devices(fs_info->super_copy,
2606 orig_super_num_devices + 1);
Anand Jain0d393762014-06-03 11:36:01 +08002607
Miao Xie2196d6e2014-09-03 21:35:41 +08002608 /*
2609 * we've got more storage, clear any full flags on the space
2610 * infos
2611 */
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002612 btrfs_clear_space_info_full(fs_info);
Miao Xie2196d6e2014-09-03 21:35:41 +08002613
David Sterba34441362016-10-04 19:34:27 +02002614 mutex_unlock(&fs_info->chunk_mutex);
Josef Bacikca108452020-09-01 08:09:01 -04002615
2616 /* Add sysfs device entry */
Anand Jaincd36da22020-09-05 01:34:26 +08002617 btrfs_sysfs_add_device(device);
Josef Bacikca108452020-09-01 08:09:01 -04002618
Anand Jain5da54bc2018-07-03 13:14:50 +08002619 mutex_unlock(&fs_devices->device_list_mutex);
Chris Mason788f20e2008-04-28 15:29:42 -04002620
Yan Zheng2b820322008-11-17 21:11:30 -05002621 if (seeding_dev) {
David Sterba34441362016-10-04 19:34:27 +02002622 mutex_lock(&fs_info->chunk_mutex);
David Sterba6f8e0fc2019-03-20 16:29:13 +01002623 ret = init_first_rw_device(trans);
David Sterba34441362016-10-04 19:34:27 +02002624 mutex_unlock(&fs_info->chunk_mutex);
David Sterba005d6422012-09-18 07:52:32 -06002625 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04002626 btrfs_abort_transaction(trans, ret);
Anand Jaind31c32f2017-09-28 14:51:10 +08002627 goto error_sysfs;
David Sterba005d6422012-09-18 07:52:32 -06002628 }
Miao Xie2196d6e2014-09-03 21:35:41 +08002629 }
2630
Nikolay Borisov8e87e852018-07-20 19:37:47 +03002631 ret = btrfs_add_dev_item(trans, device);
Miao Xie2196d6e2014-09-03 21:35:41 +08002632 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04002633 btrfs_abort_transaction(trans, ret);
Anand Jaind31c32f2017-09-28 14:51:10 +08002634 goto error_sysfs;
Miao Xie2196d6e2014-09-03 21:35:41 +08002635 }
2636
2637 if (seeding_dev) {
David Sterba5c4666292019-03-20 16:36:39 +01002638 ret = btrfs_finish_sprout(trans);
David Sterba005d6422012-09-18 07:52:32 -06002639 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04002640 btrfs_abort_transaction(trans, ret);
Anand Jaind31c32f2017-09-28 14:51:10 +08002641 goto error_sysfs;
David Sterba005d6422012-09-18 07:52:32 -06002642 }
Anand Jainb2373f22014-06-03 11:36:03 +08002643
Nikolay Borisov8e560082020-08-12 16:18:51 +03002644 /*
2645 * fs_devices now represents the newly sprouted filesystem and
2646 * its fsid has been changed by btrfs_prepare_sprout
2647 */
2648 btrfs_sysfs_update_sprout_fsid(fs_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05002649 }
2650
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04002651 ret = btrfs_commit_transaction(trans);
Yan Zheng2b820322008-11-17 21:11:30 -05002652
2653 if (seeding_dev) {
2654 mutex_unlock(&uuid_mutex);
2655 up_write(&sb->s_umount);
Nikolay Borisov44cab9b2020-07-22 11:09:23 +03002656 locked = false;
Yan Zheng2b820322008-11-17 21:11:30 -05002657
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002658 if (ret) /* transaction commit */
2659 return ret;
2660
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04002661 ret = btrfs_relocate_sys_chunks(fs_info);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002662 if (ret < 0)
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002663 btrfs_handle_fs_error(fs_info, ret,
Jeff Mahoney5d163e02016-09-20 10:05:00 -04002664 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
Miao Xie671415b2012-10-16 11:26:46 +00002665 trans = btrfs_attach_transaction(root);
2666 if (IS_ERR(trans)) {
2667 if (PTR_ERR(trans) == -ENOENT)
2668 return 0;
Anand Jain7132a262017-09-28 14:51:11 +08002669 ret = PTR_ERR(trans);
2670 trans = NULL;
2671 goto error_sysfs;
Miao Xie671415b2012-10-16 11:26:46 +00002672 }
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04002673 ret = btrfs_commit_transaction(trans);
Yan Zheng2b820322008-11-17 21:11:30 -05002674 }
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02002675
Anand Jain7f551d92020-05-05 02:58:26 +08002676 /*
2677 * Now that we have written a new super block to this device, check all
2678 * other fs_devices list if device_path alienates any other scanned
2679 * device.
2680 * We can ignore the return value as it typically returns -EINVAL and
2681 * only succeeds if the device was an alien.
2682 */
2683 btrfs_forget_devices(device_path);
2684
2685 /* Update ctime/mtime for blkid or udev */
Qu Wenruo5a1972b2014-04-16 17:02:32 +08002686 update_dev_time(device_path);
Anand Jain7f551d92020-05-05 02:58:26 +08002687
Chris Mason788f20e2008-04-28 15:29:42 -04002688 return ret;
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002689
Anand Jaind31c32f2017-09-28 14:51:10 +08002690error_sysfs:
Anand Jain53f8a742020-09-05 01:34:27 +08002691 btrfs_sysfs_remove_device(device);
Naohiro Aota39379fa2018-07-27 09:04:55 +09002692 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2693 mutex_lock(&fs_info->chunk_mutex);
2694 list_del_rcu(&device->dev_list);
2695 list_del(&device->dev_alloc_list);
2696 fs_info->fs_devices->num_devices--;
2697 fs_info->fs_devices->open_devices--;
2698 fs_info->fs_devices->rw_devices--;
2699 fs_info->fs_devices->total_devices--;
2700 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2701 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2702 btrfs_set_super_total_bytes(fs_info->super_copy,
2703 orig_super_total_bytes);
2704 btrfs_set_super_num_devices(fs_info->super_copy,
2705 orig_super_num_devices);
2706 mutex_unlock(&fs_info->chunk_mutex);
2707 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002708error_trans:
Anand Jain0af2c4b2017-09-28 14:51:09 +08002709 if (seeding_dev)
Linus Torvalds1751e8a2017-11-27 13:05:09 -08002710 sb->s_flags |= SB_RDONLY;
Anand Jain7132a262017-09-28 14:51:11 +08002711 if (trans)
2712 btrfs_end_transaction(trans);
David Sterba5c4cf6c2017-10-30 19:29:46 +01002713error_free_device:
David Sterbaa425f9d2018-03-20 15:47:33 +01002714 btrfs_free_device(device);
Yan Zheng2b820322008-11-17 21:11:30 -05002715error:
Tejun Heoe525fd82010-11-13 11:55:17 +01002716 blkdev_put(bdev, FMODE_EXCL);
Nikolay Borisov44cab9b2020-07-22 11:09:23 +03002717 if (locked) {
Yan Zheng2b820322008-11-17 21:11:30 -05002718 mutex_unlock(&uuid_mutex);
2719 up_write(&sb->s_umount);
2720 }
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02002721 return ret;
Chris Mason788f20e2008-04-28 15:29:42 -04002722}
2723
Chris Masond3977122009-01-05 21:25:51 -05002724static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2725 struct btrfs_device *device)
Chris Mason0b86a832008-03-24 15:01:56 -04002726{
2727 int ret;
2728 struct btrfs_path *path;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002729 struct btrfs_root *root = device->fs_info->chunk_root;
Chris Mason0b86a832008-03-24 15:01:56 -04002730 struct btrfs_dev_item *dev_item;
2731 struct extent_buffer *leaf;
2732 struct btrfs_key key;
2733
Chris Mason0b86a832008-03-24 15:01:56 -04002734 path = btrfs_alloc_path();
2735 if (!path)
2736 return -ENOMEM;
2737
2738 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2739 key.type = BTRFS_DEV_ITEM_KEY;
2740 key.offset = device->devid;
2741
2742 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2743 if (ret < 0)
2744 goto out;
2745
2746 if (ret > 0) {
2747 ret = -ENOENT;
2748 goto out;
2749 }
2750
2751 leaf = path->nodes[0];
2752 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2753
2754 btrfs_set_device_id(leaf, dev_item, device->devid);
2755 btrfs_set_device_type(leaf, dev_item, device->type);
2756 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2757 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2758 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
Miao Xie7cc8e582014-09-03 21:35:38 +08002759 btrfs_set_device_total_bytes(leaf, dev_item,
2760 btrfs_device_get_disk_total_bytes(device));
2761 btrfs_set_device_bytes_used(leaf, dev_item,
2762 btrfs_device_get_bytes_used(device));
Chris Mason0b86a832008-03-24 15:01:56 -04002763 btrfs_mark_buffer_dirty(leaf);
2764
2765out:
2766 btrfs_free_path(path);
2767 return ret;
2768}
2769
Miao Xie2196d6e2014-09-03 21:35:41 +08002770int btrfs_grow_device(struct btrfs_trans_handle *trans,
Chris Mason8f18cf12008-04-25 16:53:30 -04002771 struct btrfs_device *device, u64 new_size)
2772{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002773 struct btrfs_fs_info *fs_info = device->fs_info;
2774 struct btrfs_super_block *super_copy = fs_info->super_copy;
Miao Xie2196d6e2014-09-03 21:35:41 +08002775 u64 old_total;
2776 u64 diff;
Chris Mason8f18cf12008-04-25 16:53:30 -04002777
Anand Jainebbede42017-12-04 12:54:52 +08002778 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
Yan Zheng2b820322008-11-17 21:11:30 -05002779 return -EACCES;
Miao Xie2196d6e2014-09-03 21:35:41 +08002780
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03002781 new_size = round_down(new_size, fs_info->sectorsize);
2782
David Sterba34441362016-10-04 19:34:27 +02002783 mutex_lock(&fs_info->chunk_mutex);
Miao Xie2196d6e2014-09-03 21:35:41 +08002784 old_total = btrfs_super_total_bytes(super_copy);
Nikolay Borisov0e4324a2017-07-21 11:28:24 +03002785 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
Miao Xie2196d6e2014-09-03 21:35:41 +08002786
Stefan Behrens63a212a2012-11-05 18:29:28 +01002787 if (new_size <= device->total_bytes ||
Anand Jain401e29c2017-12-04 12:54:55 +08002788 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
David Sterba34441362016-10-04 19:34:27 +02002789 mutex_unlock(&fs_info->chunk_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05002790 return -EINVAL;
Miao Xie2196d6e2014-09-03 21:35:41 +08002791 }
Yan Zheng2b820322008-11-17 21:11:30 -05002792
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03002793 btrfs_set_super_total_bytes(super_copy,
2794 round_down(old_total + diff, fs_info->sectorsize));
Yan Zheng2b820322008-11-17 21:11:30 -05002795 device->fs_devices->total_rw_bytes += diff;
2796
Miao Xie7cc8e582014-09-03 21:35:38 +08002797 btrfs_device_set_total_bytes(device, new_size);
2798 btrfs_device_set_disk_total_bytes(device, new_size);
Jeff Mahoneyfb456252016-06-22 18:54:56 -04002799 btrfs_clear_space_info_full(device->fs_info);
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02002800 if (list_empty(&device->post_commit_list))
2801 list_add_tail(&device->post_commit_list,
2802 &trans->transaction->dev_update_list);
David Sterba34441362016-10-04 19:34:27 +02002803 mutex_unlock(&fs_info->chunk_mutex);
Chris Mason4184ea72009-03-10 12:39:20 -04002804
Chris Mason8f18cf12008-04-25 16:53:30 -04002805 return btrfs_update_device(trans, device);
2806}
2807
Nikolay Borisovf4208792018-07-20 19:37:52 +03002808static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
Chris Mason8f18cf12008-04-25 16:53:30 -04002809{
Nikolay Borisovf4208792018-07-20 19:37:52 +03002810 struct btrfs_fs_info *fs_info = trans->fs_info;
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04002811 struct btrfs_root *root = fs_info->chunk_root;
Chris Mason8f18cf12008-04-25 16:53:30 -04002812 int ret;
2813 struct btrfs_path *path;
2814 struct btrfs_key key;
2815
Chris Mason8f18cf12008-04-25 16:53:30 -04002816 path = btrfs_alloc_path();
2817 if (!path)
2818 return -ENOMEM;
2819
Nikolay Borisov408fbf12017-07-27 14:37:29 +03002820 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
Chris Mason8f18cf12008-04-25 16:53:30 -04002821 key.offset = chunk_offset;
2822 key.type = BTRFS_CHUNK_ITEM_KEY;
2823
2824 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002825 if (ret < 0)
2826 goto out;
2827 else if (ret > 0) { /* Logic error or corruption */
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002828 btrfs_handle_fs_error(fs_info, -ENOENT,
2829 "Failed lookup while freeing chunk.");
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002830 ret = -ENOENT;
2831 goto out;
2832 }
Chris Mason8f18cf12008-04-25 16:53:30 -04002833
2834 ret = btrfs_del_item(trans, root, path);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002835 if (ret < 0)
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002836 btrfs_handle_fs_error(fs_info, ret,
2837 "Failed to delete chunk item.");
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002838out:
Chris Mason8f18cf12008-04-25 16:53:30 -04002839 btrfs_free_path(path);
Tsutomu Itoh65a246c2011-05-19 04:37:44 +00002840 return ret;
Chris Mason8f18cf12008-04-25 16:53:30 -04002841}
2842
Nikolay Borisov408fbf12017-07-27 14:37:29 +03002843static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
Chris Mason8f18cf12008-04-25 16:53:30 -04002844{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002845 struct btrfs_super_block *super_copy = fs_info->super_copy;
Chris Mason8f18cf12008-04-25 16:53:30 -04002846 struct btrfs_disk_key *disk_key;
2847 struct btrfs_chunk *chunk;
2848 u8 *ptr;
2849 int ret = 0;
2850 u32 num_stripes;
2851 u32 array_size;
2852 u32 len = 0;
2853 u32 cur;
2854 struct btrfs_key key;
2855
David Sterba34441362016-10-04 19:34:27 +02002856 mutex_lock(&fs_info->chunk_mutex);
Chris Mason8f18cf12008-04-25 16:53:30 -04002857 array_size = btrfs_super_sys_array_size(super_copy);
2858
2859 ptr = super_copy->sys_chunk_array;
2860 cur = 0;
2861
2862 while (cur < array_size) {
2863 disk_key = (struct btrfs_disk_key *)ptr;
2864 btrfs_disk_key_to_cpu(&key, disk_key);
2865
2866 len = sizeof(*disk_key);
2867
2868 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2869 chunk = (struct btrfs_chunk *)(ptr + len);
2870 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2871 len += btrfs_chunk_item_size(num_stripes);
2872 } else {
2873 ret = -EIO;
2874 break;
2875 }
Nikolay Borisov408fbf12017-07-27 14:37:29 +03002876 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
Chris Mason8f18cf12008-04-25 16:53:30 -04002877 key.offset == chunk_offset) {
2878 memmove(ptr, ptr + len, array_size - (cur + len));
2879 array_size -= len;
2880 btrfs_set_super_sys_array_size(super_copy, array_size);
2881 } else {
2882 ptr += len;
2883 cur += len;
2884 }
2885 }
David Sterba34441362016-10-04 19:34:27 +02002886 mutex_unlock(&fs_info->chunk_mutex);
Chris Mason8f18cf12008-04-25 16:53:30 -04002887 return ret;
2888}
2889
Omar Sandoval60ca8422018-05-16 16:34:31 -07002890/*
2891 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2892 * @logical: Logical block offset in bytes.
2893 * @length: Length of extent in bytes.
2894 *
2895 * Return: Chunk mapping or ERR_PTR.
2896 */
2897struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2898 u64 logical, u64 length)
Liu Bo592d92e2017-03-14 13:33:55 -07002899{
2900 struct extent_map_tree *em_tree;
2901 struct extent_map *em;
2902
David Sterbac8bf1b62019-05-17 11:43:17 +02002903 em_tree = &fs_info->mapping_tree;
Liu Bo592d92e2017-03-14 13:33:55 -07002904 read_lock(&em_tree->lock);
2905 em = lookup_extent_mapping(em_tree, logical, length);
2906 read_unlock(&em_tree->lock);
2907
2908 if (!em) {
2909 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2910 logical, length);
2911 return ERR_PTR(-EINVAL);
2912 }
2913
2914 if (em->start > logical || em->start + em->len < logical) {
2915 btrfs_crit(fs_info,
2916 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2917 logical, length, em->start, em->start + em->len);
2918 free_extent_map(em);
2919 return ERR_PTR(-EINVAL);
2920 }
2921
2922 /* callers are responsible for dropping em's ref. */
2923 return em;
2924}
2925
Nikolay Borisov97aff912018-07-20 19:37:53 +03002926int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
Josef Bacik47ab2a62014-09-18 11:20:02 -04002927{
Nikolay Borisov97aff912018-07-20 19:37:53 +03002928 struct btrfs_fs_info *fs_info = trans->fs_info;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002929 struct extent_map *em;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002930 struct map_lookup *map;
2931 u64 dev_extent_len = 0;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002932 int i, ret = 0;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002933 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002934
Omar Sandoval60ca8422018-05-16 16:34:31 -07002935 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
Liu Bo592d92e2017-03-14 13:33:55 -07002936 if (IS_ERR(em)) {
Josef Bacik47ab2a62014-09-18 11:20:02 -04002937 /*
2938 * This is a logic error, but we don't want to just rely on the
Adam Buchbinderbb7ab3b2016-03-04 11:23:12 -08002939 * user having built with ASSERT enabled, so if ASSERT doesn't
Josef Bacik47ab2a62014-09-18 11:20:02 -04002940 * do anything we still error out.
2941 */
2942 ASSERT(0);
Liu Bo592d92e2017-03-14 13:33:55 -07002943 return PTR_ERR(em);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002944 }
Jeff Mahoney95617d62015-06-03 10:55:48 -04002945 map = em->map_lookup;
David Sterba34441362016-10-04 19:34:27 +02002946 mutex_lock(&fs_info->chunk_mutex);
Nikolay Borisov451a2c12018-06-20 15:49:07 +03002947 check_system_chunk(trans, map->type);
David Sterba34441362016-10-04 19:34:27 +02002948 mutex_unlock(&fs_info->chunk_mutex);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002949
Filipe Manana57ba4cb2016-05-20 04:34:23 +01002950 /*
2951 * Take the device list mutex to prevent races with the final phase of
2952 * a device replace operation that replaces the device object associated
2953 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2954 */
2955 mutex_lock(&fs_devices->device_list_mutex);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002956 for (i = 0; i < map->num_stripes; i++) {
2957 struct btrfs_device *device = map->stripes[i].dev;
2958 ret = btrfs_free_dev_extent(trans, device,
2959 map->stripes[i].physical,
2960 &dev_extent_len);
2961 if (ret) {
Filipe Manana57ba4cb2016-05-20 04:34:23 +01002962 mutex_unlock(&fs_devices->device_list_mutex);
Jeff Mahoney66642832016-06-10 18:19:25 -04002963 btrfs_abort_transaction(trans, ret);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002964 goto out;
2965 }
2966
2967 if (device->bytes_used > 0) {
David Sterba34441362016-10-04 19:34:27 +02002968 mutex_lock(&fs_info->chunk_mutex);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002969 btrfs_device_set_bytes_used(device,
2970 device->bytes_used - dev_extent_len);
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03002971 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002972 btrfs_clear_space_info_full(fs_info);
David Sterba34441362016-10-04 19:34:27 +02002973 mutex_unlock(&fs_info->chunk_mutex);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002974 }
2975
Nikolay Borisov64bc6c22018-10-26 14:43:19 +03002976 ret = btrfs_update_device(trans, device);
2977 if (ret) {
2978 mutex_unlock(&fs_devices->device_list_mutex);
2979 btrfs_abort_transaction(trans, ret);
2980 goto out;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002981 }
2982 }
Filipe Manana57ba4cb2016-05-20 04:34:23 +01002983 mutex_unlock(&fs_devices->device_list_mutex);
2984
Nikolay Borisovf4208792018-07-20 19:37:52 +03002985 ret = btrfs_free_chunk(trans, chunk_offset);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002986 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04002987 btrfs_abort_transaction(trans, ret);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002988 goto out;
2989 }
2990
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04002991 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002992
2993 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
Nikolay Borisov408fbf12017-07-27 14:37:29 +03002994 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002995 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04002996 btrfs_abort_transaction(trans, ret);
Josef Bacik47ab2a62014-09-18 11:20:02 -04002997 goto out;
2998 }
2999 }
3000
Nikolay Borisov5a98ec02018-06-20 15:48:56 +03003001 ret = btrfs_remove_block_group(trans, chunk_offset, em);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003002 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04003003 btrfs_abort_transaction(trans, ret);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003004 goto out;
3005 }
3006
Josef Bacik47ab2a62014-09-18 11:20:02 -04003007out:
3008 /* once for us */
3009 free_extent_map(em);
Chris Mason8f18cf12008-04-25 16:53:30 -04003010 return ret;
3011}
3012
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04003013static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
Chris Mason8f18cf12008-04-25 16:53:30 -04003014{
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04003015 struct btrfs_root *root = fs_info->chunk_root;
Chris Mason19c4d2f2016-10-10 13:43:31 -07003016 struct btrfs_trans_handle *trans;
Dennis Zhoub0643e52019-12-13 16:22:14 -08003017 struct btrfs_block_group *block_group;
Chris Mason8f18cf12008-04-25 16:53:30 -04003018 int ret;
Chris Mason8f18cf12008-04-25 16:53:30 -04003019
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003020 /*
3021 * Prevent races with automatic removal of unused block groups.
3022 * After we relocate and before we remove the chunk with offset
3023 * chunk_offset, automatic removal of the block group can kick in,
3024 * resulting in a failure when calling btrfs_remove_chunk() below.
3025 *
3026 * Make sure to acquire this mutex before doing a tree search (dev
3027 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3028 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3029 * we release the path used to search the chunk/dev tree and before
3030 * the current task acquires this mutex and calls us.
3031 */
David Sterbaa32bf9a2018-03-16 02:21:22 +01003032 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003033
Chris Mason8f18cf12008-04-25 16:53:30 -04003034 /* step one, relocate all the extents inside this chunk */
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04003035 btrfs_scrub_pause(fs_info);
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003036 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04003037 btrfs_scrub_continue(fs_info);
Yan, Zhenga22285a2010-05-16 10:48:46 -04003038 if (ret)
3039 return ret;
Chris Mason8f18cf12008-04-25 16:53:30 -04003040
Dennis Zhoub0643e52019-12-13 16:22:14 -08003041 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3042 if (!block_group)
3043 return -ENOENT;
3044 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3045 btrfs_put_block_group(block_group);
3046
Chris Mason19c4d2f2016-10-10 13:43:31 -07003047 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3048 chunk_offset);
3049 if (IS_ERR(trans)) {
3050 ret = PTR_ERR(trans);
3051 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3052 return ret;
3053 }
Naohiro Aota5d8eb6f2016-09-02 16:46:32 +09003054
Chris Mason19c4d2f2016-10-10 13:43:31 -07003055 /*
3056 * step two, delete the device extents and the
3057 * chunk tree entries
3058 */
Nikolay Borisov97aff912018-07-20 19:37:53 +03003059 ret = btrfs_remove_chunk(trans, chunk_offset);
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04003060 btrfs_end_transaction(trans);
Chris Mason19c4d2f2016-10-10 13:43:31 -07003061 return ret;
Chris Mason8f18cf12008-04-25 16:53:30 -04003062}
3063
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04003064static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
Yan Zheng2b820322008-11-17 21:11:30 -05003065{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003066 struct btrfs_root *chunk_root = fs_info->chunk_root;
Yan Zheng2b820322008-11-17 21:11:30 -05003067 struct btrfs_path *path;
3068 struct extent_buffer *leaf;
3069 struct btrfs_chunk *chunk;
3070 struct btrfs_key key;
3071 struct btrfs_key found_key;
Yan Zheng2b820322008-11-17 21:11:30 -05003072 u64 chunk_type;
Josef Bacikba1bf482009-09-11 16:11:19 -04003073 bool retried = false;
3074 int failed = 0;
Yan Zheng2b820322008-11-17 21:11:30 -05003075 int ret;
3076
3077 path = btrfs_alloc_path();
3078 if (!path)
3079 return -ENOMEM;
3080
Josef Bacikba1bf482009-09-11 16:11:19 -04003081again:
Yan Zheng2b820322008-11-17 21:11:30 -05003082 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3083 key.offset = (u64)-1;
3084 key.type = BTRFS_CHUNK_ITEM_KEY;
3085
3086 while (1) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003087 mutex_lock(&fs_info->delete_unused_bgs_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05003088 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003089 if (ret < 0) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003090 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05003091 goto error;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003092 }
Jeff Mahoney79787ea2012-03-12 16:03:00 +01003093 BUG_ON(ret == 0); /* Corruption */
Yan Zheng2b820322008-11-17 21:11:30 -05003094
3095 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3096 key.type);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003097 if (ret)
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003098 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05003099 if (ret < 0)
3100 goto error;
3101 if (ret > 0)
3102 break;
3103
3104 leaf = path->nodes[0];
3105 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3106
3107 chunk = btrfs_item_ptr(leaf, path->slots[0],
3108 struct btrfs_chunk);
3109 chunk_type = btrfs_chunk_type(leaf, chunk);
David Sterbab3b4aa72011-04-21 01:20:15 +02003110 btrfs_release_path(path);
Yan Zheng2b820322008-11-17 21:11:30 -05003111
3112 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003113 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
Josef Bacikba1bf482009-09-11 16:11:19 -04003114 if (ret == -ENOSPC)
3115 failed++;
HIMANGI SARAOGI14586652014-07-09 03:51:41 +05303116 else
3117 BUG_ON(ret);
Yan Zheng2b820322008-11-17 21:11:30 -05003118 }
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003119 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05003120
3121 if (found_key.offset == 0)
3122 break;
3123 key.offset = found_key.offset - 1;
3124 }
3125 ret = 0;
Josef Bacikba1bf482009-09-11 16:11:19 -04003126 if (failed && !retried) {
3127 failed = 0;
3128 retried = true;
3129 goto again;
Dulshani Gunawardhanafae7f212013-10-31 10:30:08 +05303130 } else if (WARN_ON(failed && retried)) {
Josef Bacikba1bf482009-09-11 16:11:19 -04003131 ret = -ENOSPC;
3132 }
Yan Zheng2b820322008-11-17 21:11:30 -05003133error:
3134 btrfs_free_path(path);
3135 return ret;
3136}
3137
Liu Boa6f93c72017-11-15 16:28:11 -07003138/*
3139 * return 1 : allocate a data chunk successfully,
3140 * return <0: errors during allocating a data chunk,
3141 * return 0 : no need to allocate a data chunk.
3142 */
3143static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3144 u64 chunk_offset)
3145{
David Sterba32da53862019-10-29 19:20:18 +01003146 struct btrfs_block_group *cache;
Liu Boa6f93c72017-11-15 16:28:11 -07003147 u64 bytes_used;
3148 u64 chunk_type;
3149
3150 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3151 ASSERT(cache);
3152 chunk_type = cache->flags;
3153 btrfs_put_block_group(cache);
3154
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003155 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3156 return 0;
Liu Boa6f93c72017-11-15 16:28:11 -07003157
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003158 spin_lock(&fs_info->data_sinfo->lock);
3159 bytes_used = fs_info->data_sinfo->bytes_used;
3160 spin_unlock(&fs_info->data_sinfo->lock);
Liu Boa6f93c72017-11-15 16:28:11 -07003161
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003162 if (!bytes_used) {
3163 struct btrfs_trans_handle *trans;
3164 int ret;
Liu Boa6f93c72017-11-15 16:28:11 -07003165
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003166 trans = btrfs_join_transaction(fs_info->tree_root);
3167 if (IS_ERR(trans))
3168 return PTR_ERR(trans);
3169
3170 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3171 btrfs_end_transaction(trans);
3172 if (ret < 0)
3173 return ret;
3174 return 1;
Liu Boa6f93c72017-11-15 16:28:11 -07003175 }
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003176
Liu Boa6f93c72017-11-15 16:28:11 -07003177 return 0;
3178}
3179
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003180static int insert_balance_item(struct btrfs_fs_info *fs_info,
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003181 struct btrfs_balance_control *bctl)
3182{
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003183 struct btrfs_root *root = fs_info->tree_root;
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003184 struct btrfs_trans_handle *trans;
3185 struct btrfs_balance_item *item;
3186 struct btrfs_disk_balance_args disk_bargs;
3187 struct btrfs_path *path;
3188 struct extent_buffer *leaf;
3189 struct btrfs_key key;
3190 int ret, err;
3191
3192 path = btrfs_alloc_path();
3193 if (!path)
3194 return -ENOMEM;
3195
3196 trans = btrfs_start_transaction(root, 0);
3197 if (IS_ERR(trans)) {
3198 btrfs_free_path(path);
3199 return PTR_ERR(trans);
3200 }
3201
3202 key.objectid = BTRFS_BALANCE_OBJECTID;
David Sterbac479cb42016-01-25 17:51:31 +01003203 key.type = BTRFS_TEMPORARY_ITEM_KEY;
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003204 key.offset = 0;
3205
3206 ret = btrfs_insert_empty_item(trans, root, path, &key,
3207 sizeof(*item));
3208 if (ret)
3209 goto out;
3210
3211 leaf = path->nodes[0];
3212 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3213
David Sterbab159fa22016-11-08 18:09:03 +01003214 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003215
3216 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3217 btrfs_set_balance_data(leaf, item, &disk_bargs);
3218 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3219 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3220 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3221 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3222
3223 btrfs_set_balance_flags(leaf, item, bctl->flags);
3224
3225 btrfs_mark_buffer_dirty(leaf);
3226out:
3227 btrfs_free_path(path);
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04003228 err = btrfs_commit_transaction(trans);
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003229 if (err && !ret)
3230 ret = err;
3231 return ret;
3232}
3233
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003234static int del_balance_item(struct btrfs_fs_info *fs_info)
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003235{
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003236 struct btrfs_root *root = fs_info->tree_root;
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003237 struct btrfs_trans_handle *trans;
3238 struct btrfs_path *path;
3239 struct btrfs_key key;
3240 int ret, err;
3241
3242 path = btrfs_alloc_path();
3243 if (!path)
3244 return -ENOMEM;
3245
David Sterba3502a8c2020-06-25 12:35:28 +02003246 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003247 if (IS_ERR(trans)) {
3248 btrfs_free_path(path);
3249 return PTR_ERR(trans);
3250 }
3251
3252 key.objectid = BTRFS_BALANCE_OBJECTID;
David Sterbac479cb42016-01-25 17:51:31 +01003253 key.type = BTRFS_TEMPORARY_ITEM_KEY;
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003254 key.offset = 0;
3255
3256 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3257 if (ret < 0)
3258 goto out;
3259 if (ret > 0) {
3260 ret = -ENOENT;
3261 goto out;
3262 }
3263
3264 ret = btrfs_del_item(trans, root, path);
3265out:
3266 btrfs_free_path(path);
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04003267 err = btrfs_commit_transaction(trans);
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003268 if (err && !ret)
3269 ret = err;
3270 return ret;
3271}
3272
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003273/*
Ilya Dryomov59641012012-01-16 22:04:48 +02003274 * This is a heuristic used to reduce the number of chunks balanced on
3275 * resume after balance was interrupted.
3276 */
3277static void update_balance_args(struct btrfs_balance_control *bctl)
3278{
3279 /*
3280 * Turn on soft mode for chunk types that were being converted.
3281 */
3282 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3283 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3284 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3285 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3286 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3287 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3288
3289 /*
3290 * Turn on usage filter if is not already used. The idea is
3291 * that chunks that we have already balanced should be
3292 * reasonably full. Don't do it for chunks that are being
3293 * converted - that will keep us from relocating unconverted
3294 * (albeit full) chunks.
3295 */
3296 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
David Sterbabc309462015-10-20 18:22:13 +02003297 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
Ilya Dryomov59641012012-01-16 22:04:48 +02003298 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3299 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3300 bctl->data.usage = 90;
3301 }
3302 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
David Sterbabc309462015-10-20 18:22:13 +02003303 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
Ilya Dryomov59641012012-01-16 22:04:48 +02003304 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3305 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3306 bctl->sys.usage = 90;
3307 }
3308 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
David Sterbabc309462015-10-20 18:22:13 +02003309 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
Ilya Dryomov59641012012-01-16 22:04:48 +02003310 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3311 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3312 bctl->meta.usage = 90;
3313 }
3314}
3315
3316/*
David Sterba149196a2018-03-20 20:23:09 +01003317 * Clear the balance status in fs_info and delete the balance item from disk.
3318 */
3319static void reset_balance_state(struct btrfs_fs_info *fs_info)
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003320{
3321 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
David Sterba149196a2018-03-20 20:23:09 +01003322 int ret;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003323
3324 BUG_ON(!fs_info->balance_ctl);
3325
3326 spin_lock(&fs_info->balance_lock);
3327 fs_info->balance_ctl = NULL;
3328 spin_unlock(&fs_info->balance_lock);
3329
3330 kfree(bctl);
David Sterba149196a2018-03-20 20:23:09 +01003331 ret = del_balance_item(fs_info);
3332 if (ret)
3333 btrfs_handle_fs_error(fs_info, ret, NULL);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003334}
3335
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003336/*
3337 * Balance filters. Return 1 if chunk should be filtered out
3338 * (should not be balanced).
3339 */
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003340static int chunk_profiles_filter(u64 chunk_type,
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003341 struct btrfs_balance_args *bargs)
3342{
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003343 chunk_type = chunk_to_extended(chunk_type) &
3344 BTRFS_EXTENDED_PROFILE_MASK;
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003345
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003346 if (bargs->profiles & chunk_type)
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003347 return 0;
3348
3349 return 1;
3350}
3351
Holger Hoffstättedba72cb2015-11-17 12:29:32 +01003352static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003353 struct btrfs_balance_args *bargs)
3354{
David Sterba32da53862019-10-29 19:20:18 +01003355 struct btrfs_block_group *cache;
David Sterbabc309462015-10-20 18:22:13 +02003356 u64 chunk_used;
3357 u64 user_thresh_min;
3358 u64 user_thresh_max;
3359 int ret = 1;
3360
3361 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
David Sterbabf38be62019-10-23 18:48:11 +02003362 chunk_used = cache->used;
David Sterbabc309462015-10-20 18:22:13 +02003363
3364 if (bargs->usage_min == 0)
3365 user_thresh_min = 0;
3366 else
David Sterbab3470b52019-10-23 18:48:22 +02003367 user_thresh_min = div_factor_fine(cache->length,
3368 bargs->usage_min);
David Sterbabc309462015-10-20 18:22:13 +02003369
3370 if (bargs->usage_max == 0)
3371 user_thresh_max = 1;
3372 else if (bargs->usage_max > 100)
David Sterbab3470b52019-10-23 18:48:22 +02003373 user_thresh_max = cache->length;
David Sterbabc309462015-10-20 18:22:13 +02003374 else
David Sterbab3470b52019-10-23 18:48:22 +02003375 user_thresh_max = div_factor_fine(cache->length,
3376 bargs->usage_max);
David Sterbabc309462015-10-20 18:22:13 +02003377
3378 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3379 ret = 0;
3380
3381 btrfs_put_block_group(cache);
3382 return ret;
3383}
3384
Holger Hoffstättedba72cb2015-11-17 12:29:32 +01003385static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
David Sterbabc309462015-10-20 18:22:13 +02003386 u64 chunk_offset, struct btrfs_balance_args *bargs)
3387{
David Sterba32da53862019-10-29 19:20:18 +01003388 struct btrfs_block_group *cache;
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003389 u64 chunk_used, user_thresh;
3390 int ret = 1;
3391
3392 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
David Sterbabf38be62019-10-23 18:48:11 +02003393 chunk_used = cache->used;
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003394
David Sterbabc309462015-10-20 18:22:13 +02003395 if (bargs->usage_min == 0)
Ilya Dryomov3e39cea2013-02-12 16:28:59 +00003396 user_thresh = 1;
Ilya Dryomova105bb82013-01-21 15:15:56 +02003397 else if (bargs->usage > 100)
David Sterbab3470b52019-10-23 18:48:22 +02003398 user_thresh = cache->length;
Ilya Dryomova105bb82013-01-21 15:15:56 +02003399 else
David Sterbab3470b52019-10-23 18:48:22 +02003400 user_thresh = div_factor_fine(cache->length, bargs->usage);
Ilya Dryomova105bb82013-01-21 15:15:56 +02003401
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003402 if (chunk_used < user_thresh)
3403 ret = 0;
3404
3405 btrfs_put_block_group(cache);
3406 return ret;
3407}
3408
Ilya Dryomov409d4042012-01-16 22:04:47 +02003409static int chunk_devid_filter(struct extent_buffer *leaf,
3410 struct btrfs_chunk *chunk,
3411 struct btrfs_balance_args *bargs)
3412{
3413 struct btrfs_stripe *stripe;
3414 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3415 int i;
3416
3417 for (i = 0; i < num_stripes; i++) {
3418 stripe = btrfs_stripe_nr(chunk, i);
3419 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3420 return 0;
3421 }
3422
3423 return 1;
3424}
3425
David Sterba946c9252019-05-17 11:43:34 +02003426static u64 calc_data_stripes(u64 type, int num_stripes)
3427{
3428 const int index = btrfs_bg_flags_to_raid_index(type);
3429 const int ncopies = btrfs_raid_array[index].ncopies;
3430 const int nparity = btrfs_raid_array[index].nparity;
3431
3432 if (nparity)
3433 return num_stripes - nparity;
3434 else
3435 return num_stripes / ncopies;
3436}
3437
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003438/* [pstart, pend) */
3439static int chunk_drange_filter(struct extent_buffer *leaf,
3440 struct btrfs_chunk *chunk,
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003441 struct btrfs_balance_args *bargs)
3442{
3443 struct btrfs_stripe *stripe;
3444 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3445 u64 stripe_offset;
3446 u64 stripe_length;
David Sterba946c9252019-05-17 11:43:34 +02003447 u64 type;
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003448 int factor;
3449 int i;
3450
3451 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3452 return 0;
3453
David Sterba946c9252019-05-17 11:43:34 +02003454 type = btrfs_chunk_type(leaf, chunk);
3455 factor = calc_data_stripes(type, num_stripes);
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003456
3457 for (i = 0; i < num_stripes; i++) {
3458 stripe = btrfs_stripe_nr(chunk, i);
3459 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3460 continue;
3461
3462 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3463 stripe_length = btrfs_chunk_length(leaf, chunk);
David Sterbab8b93ad2015-01-16 17:26:13 +01003464 stripe_length = div_u64(stripe_length, factor);
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003465
3466 if (stripe_offset < bargs->pend &&
3467 stripe_offset + stripe_length > bargs->pstart)
3468 return 0;
3469 }
3470
3471 return 1;
3472}
3473
Ilya Dryomovea671762012-01-16 22:04:48 +02003474/* [vstart, vend) */
3475static int chunk_vrange_filter(struct extent_buffer *leaf,
3476 struct btrfs_chunk *chunk,
3477 u64 chunk_offset,
3478 struct btrfs_balance_args *bargs)
3479{
3480 if (chunk_offset < bargs->vend &&
3481 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3482 /* at least part of the chunk is inside this vrange */
3483 return 0;
3484
3485 return 1;
3486}
3487
Gabríel Arthúr Péturssondee32d02015-09-28 22:32:41 +00003488static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3489 struct btrfs_chunk *chunk,
3490 struct btrfs_balance_args *bargs)
3491{
3492 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3493
3494 if (bargs->stripes_min <= num_stripes
3495 && num_stripes <= bargs->stripes_max)
3496 return 0;
3497
3498 return 1;
3499}
3500
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003501static int chunk_soft_convert_filter(u64 chunk_type,
Ilya Dryomovcfa4c962012-01-16 22:04:48 +02003502 struct btrfs_balance_args *bargs)
3503{
3504 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3505 return 0;
3506
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003507 chunk_type = chunk_to_extended(chunk_type) &
3508 BTRFS_EXTENDED_PROFILE_MASK;
Ilya Dryomovcfa4c962012-01-16 22:04:48 +02003509
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003510 if (bargs->target == chunk_type)
Ilya Dryomovcfa4c962012-01-16 22:04:48 +02003511 return 1;
3512
3513 return 0;
3514}
3515
David Sterba6ec08962019-03-20 16:38:52 +01003516static int should_balance_chunk(struct extent_buffer *leaf,
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003517 struct btrfs_chunk *chunk, u64 chunk_offset)
3518{
David Sterba6ec08962019-03-20 16:38:52 +01003519 struct btrfs_fs_info *fs_info = leaf->fs_info;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003520 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003521 struct btrfs_balance_args *bargs = NULL;
3522 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3523
3524 /* type filter */
3525 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3526 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3527 return 0;
3528 }
3529
3530 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3531 bargs = &bctl->data;
3532 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3533 bargs = &bctl->sys;
3534 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3535 bargs = &bctl->meta;
3536
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003537 /* profiles filter */
3538 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3539 chunk_profiles_filter(chunk_type, bargs)) {
3540 return 0;
3541 }
3542
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003543 /* usage filter */
3544 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003545 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003546 return 0;
David Sterbabc309462015-10-20 18:22:13 +02003547 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003548 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
David Sterbabc309462015-10-20 18:22:13 +02003549 return 0;
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003550 }
3551
Ilya Dryomov409d4042012-01-16 22:04:47 +02003552 /* devid filter */
3553 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3554 chunk_devid_filter(leaf, chunk, bargs)) {
3555 return 0;
3556 }
3557
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003558 /* drange filter, makes sense only with devid filter */
3559 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
Nikolay Borisove4ff5fb2017-07-19 10:48:42 +03003560 chunk_drange_filter(leaf, chunk, bargs)) {
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003561 return 0;
3562 }
3563
Ilya Dryomovea671762012-01-16 22:04:48 +02003564 /* vrange filter */
3565 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3566 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3567 return 0;
3568 }
3569
Gabríel Arthúr Péturssondee32d02015-09-28 22:32:41 +00003570 /* stripes filter */
3571 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3572 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3573 return 0;
3574 }
3575
Ilya Dryomovcfa4c962012-01-16 22:04:48 +02003576 /* soft profile changing mode */
3577 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3578 chunk_soft_convert_filter(chunk_type, bargs)) {
3579 return 0;
3580 }
3581
David Sterba7d824b62014-05-07 17:37:51 +02003582 /*
3583 * limited by count, must be the last filter
3584 */
3585 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3586 if (bargs->limit == 0)
3587 return 0;
3588 else
3589 bargs->limit--;
David Sterba12907fc2015-10-10 17:16:50 +02003590 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3591 /*
3592 * Same logic as the 'limit' filter; the minimum cannot be
Nicholas D Steeves01327612016-05-19 21:18:45 -04003593 * determined here because we do not have the global information
David Sterba12907fc2015-10-10 17:16:50 +02003594 * about the count of all chunks that satisfy the filters.
3595 */
3596 if (bargs->limit_max == 0)
3597 return 0;
3598 else
3599 bargs->limit_max--;
David Sterba7d824b62014-05-07 17:37:51 +02003600 }
3601
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003602 return 1;
3603}
3604
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003605static int __btrfs_balance(struct btrfs_fs_info *fs_info)
Chris Masonec44a352008-04-28 15:29:52 -04003606{
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003607 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003608 struct btrfs_root *chunk_root = fs_info->chunk_root;
David Sterba12907fc2015-10-10 17:16:50 +02003609 u64 chunk_type;
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003610 struct btrfs_chunk *chunk;
Liu Bo5a488b92016-07-12 11:24:21 -07003611 struct btrfs_path *path = NULL;
Chris Masonec44a352008-04-28 15:29:52 -04003612 struct btrfs_key key;
Chris Masonec44a352008-04-28 15:29:52 -04003613 struct btrfs_key found_key;
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003614 struct extent_buffer *leaf;
3615 int slot;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003616 int ret;
3617 int enospc_errors = 0;
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003618 bool counting = true;
David Sterba12907fc2015-10-10 17:16:50 +02003619 /* The single value limit and min/max limits use the same bytes in the */
David Sterba7d824b62014-05-07 17:37:51 +02003620 u64 limit_data = bctl->data.limit;
3621 u64 limit_meta = bctl->meta.limit;
3622 u64 limit_sys = bctl->sys.limit;
David Sterba12907fc2015-10-10 17:16:50 +02003623 u32 count_data = 0;
3624 u32 count_meta = 0;
3625 u32 count_sys = 0;
Zhao Lei2c9fe832015-11-09 11:51:32 +08003626 int chunk_reserved = 0;
Chris Masonec44a352008-04-28 15:29:52 -04003627
Chris Masonec44a352008-04-28 15:29:52 -04003628 path = btrfs_alloc_path();
Mark Fasheh17e9f792011-07-12 11:10:23 -07003629 if (!path) {
3630 ret = -ENOMEM;
3631 goto error;
3632 }
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003633
3634 /* zero out stat counters */
3635 spin_lock(&fs_info->balance_lock);
3636 memset(&bctl->stat, 0, sizeof(bctl->stat));
3637 spin_unlock(&fs_info->balance_lock);
3638again:
David Sterba7d824b62014-05-07 17:37:51 +02003639 if (!counting) {
David Sterba12907fc2015-10-10 17:16:50 +02003640 /*
3641 * The single value limit and min/max limits use the same bytes
3642 * in the
3643 */
David Sterba7d824b62014-05-07 17:37:51 +02003644 bctl->data.limit = limit_data;
3645 bctl->meta.limit = limit_meta;
3646 bctl->sys.limit = limit_sys;
3647 }
Chris Masonec44a352008-04-28 15:29:52 -04003648 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3649 key.offset = (u64)-1;
3650 key.type = BTRFS_CHUNK_ITEM_KEY;
3651
Chris Masond3977122009-01-05 21:25:51 -05003652 while (1) {
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003653 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
Ilya Dryomova7e99c62012-01-16 22:04:49 +02003654 atomic_read(&fs_info->balance_cancel_req)) {
Ilya Dryomov837d5b62012-01-16 22:04:49 +02003655 ret = -ECANCELED;
3656 goto error;
3657 }
3658
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003659 mutex_lock(&fs_info->delete_unused_bgs_mutex);
Chris Masonec44a352008-04-28 15:29:52 -04003660 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003661 if (ret < 0) {
3662 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Chris Masonec44a352008-04-28 15:29:52 -04003663 goto error;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003664 }
Chris Masonec44a352008-04-28 15:29:52 -04003665
3666 /*
3667 * this shouldn't happen, it means the last relocate
3668 * failed
3669 */
3670 if (ret == 0)
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003671 BUG(); /* FIXME break ? */
Chris Masonec44a352008-04-28 15:29:52 -04003672
3673 ret = btrfs_previous_item(chunk_root, path, 0,
3674 BTRFS_CHUNK_ITEM_KEY);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003675 if (ret) {
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003676 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003677 ret = 0;
Chris Masonec44a352008-04-28 15:29:52 -04003678 break;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003679 }
Chris Mason7d9eb122008-07-08 14:19:17 -04003680
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003681 leaf = path->nodes[0];
3682 slot = path->slots[0];
3683 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3684
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003685 if (found_key.objectid != key.objectid) {
3686 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Chris Masonec44a352008-04-28 15:29:52 -04003687 break;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003688 }
Chris Mason7d9eb122008-07-08 14:19:17 -04003689
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003690 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
David Sterba12907fc2015-10-10 17:16:50 +02003691 chunk_type = btrfs_chunk_type(leaf, chunk);
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003692
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003693 if (!counting) {
3694 spin_lock(&fs_info->balance_lock);
3695 bctl->stat.considered++;
3696 spin_unlock(&fs_info->balance_lock);
3697 }
3698
David Sterba6ec08962019-03-20 16:38:52 +01003699 ret = should_balance_chunk(leaf, chunk, found_key.offset);
Zhao Lei2c9fe832015-11-09 11:51:32 +08003700
David Sterbab3b4aa72011-04-21 01:20:15 +02003701 btrfs_release_path(path);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003702 if (!ret) {
3703 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003704 goto loop;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003705 }
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003706
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003707 if (counting) {
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003708 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003709 spin_lock(&fs_info->balance_lock);
3710 bctl->stat.expected++;
3711 spin_unlock(&fs_info->balance_lock);
David Sterba12907fc2015-10-10 17:16:50 +02003712
3713 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3714 count_data++;
3715 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3716 count_sys++;
3717 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3718 count_meta++;
3719
3720 goto loop;
3721 }
3722
3723 /*
3724 * Apply limit_min filter, no need to check if the LIMITS
3725 * filter is used, limit_min is 0 by default
3726 */
3727 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3728 count_data < bctl->data.limit_min)
3729 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3730 count_meta < bctl->meta.limit_min)
3731 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3732 count_sys < bctl->sys.limit_min)) {
3733 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003734 goto loop;
3735 }
3736
Liu Boa6f93c72017-11-15 16:28:11 -07003737 if (!chunk_reserved) {
3738 /*
3739 * We may be relocating the only data chunk we have,
3740 * which could potentially end up with losing data's
3741 * raid profile, so lets allocate an empty one in
3742 * advance.
3743 */
3744 ret = btrfs_may_alloc_data_chunk(fs_info,
3745 found_key.offset);
Zhao Lei2c9fe832015-11-09 11:51:32 +08003746 if (ret < 0) {
3747 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3748 goto error;
Liu Boa6f93c72017-11-15 16:28:11 -07003749 } else if (ret == 1) {
3750 chunk_reserved = 1;
Zhao Lei2c9fe832015-11-09 11:51:32 +08003751 }
Zhao Lei2c9fe832015-11-09 11:51:32 +08003752 }
3753
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04003754 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003755 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003756 if (ret == -ENOSPC) {
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003757 enospc_errors++;
Omar Sandovaleede2bf2016-11-03 10:28:12 -07003758 } else if (ret == -ETXTBSY) {
3759 btrfs_info(fs_info,
3760 "skipping relocation of block group %llu due to active swapfile",
3761 found_key.offset);
3762 ret = 0;
3763 } else if (ret) {
3764 goto error;
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003765 } else {
3766 spin_lock(&fs_info->balance_lock);
3767 bctl->stat.completed++;
3768 spin_unlock(&fs_info->balance_lock);
3769 }
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003770loop:
Ilya Dryomov795a3322013-08-27 13:50:44 +03003771 if (found_key.offset == 0)
3772 break;
Josef Bacikba1bf482009-09-11 16:11:19 -04003773 key.offset = found_key.offset - 1;
Chris Masonec44a352008-04-28 15:29:52 -04003774 }
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003775
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003776 if (counting) {
3777 btrfs_release_path(path);
3778 counting = false;
3779 goto again;
3780 }
Chris Masonec44a352008-04-28 15:29:52 -04003781error:
3782 btrfs_free_path(path);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003783 if (enospc_errors) {
Frank Holtonefe120a2013-12-20 11:37:06 -05003784 btrfs_info(fs_info, "%d enospc errors during balance",
Jeff Mahoney5d163e02016-09-20 10:05:00 -04003785 enospc_errors);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003786 if (!ret)
3787 ret = -ENOSPC;
3788 }
3789
Chris Masonec44a352008-04-28 15:29:52 -04003790 return ret;
3791}
3792
Ilya Dryomov0c460c02012-03-27 17:09:17 +03003793/**
3794 * alloc_profile_is_valid - see if a given profile is valid and reduced
3795 * @flags: profile to validate
3796 * @extended: if true @flags is treated as an extended profile
3797 */
3798static int alloc_profile_is_valid(u64 flags, int extended)
3799{
3800 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3801 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3802
3803 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3804
3805 /* 1) check that all other bits are zeroed */
3806 if (flags & ~mask)
3807 return 0;
3808
3809 /* 2) see if profile is reduced */
3810 if (flags == 0)
3811 return !extended; /* "0" is valid for usual profiles */
3812
David Sterbac1499162019-10-01 19:44:42 +02003813 return has_single_bit_set(flags);
Ilya Dryomov0c460c02012-03-27 17:09:17 +03003814}
3815
Ilya Dryomov837d5b62012-01-16 22:04:49 +02003816static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3817{
Ilya Dryomova7e99c62012-01-16 22:04:49 +02003818 /* cancel requested || normal exit path */
3819 return atomic_read(&fs_info->balance_cancel_req) ||
3820 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3821 atomic_read(&fs_info->balance_cancel_req) == 0);
Ilya Dryomov837d5b62012-01-16 22:04:49 +02003822}
3823
David Sterba5ba366c2020-02-27 21:00:52 +01003824/*
3825 * Validate target profile against allowed profiles and return true if it's OK.
3826 * Otherwise print the error message and return false.
3827 */
3828static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
3829 const struct btrfs_balance_args *bargs,
3830 u64 allowed, const char *type)
Alexandru Moisebdcd3c92015-09-22 20:02:25 +00003831{
David Sterba5ba366c2020-02-27 21:00:52 +01003832 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3833 return true;
3834
3835 /* Profile is valid and does not have bits outside of the allowed set */
3836 if (alloc_profile_is_valid(bargs->target, 1) &&
3837 (bargs->target & ~allowed) == 0)
3838 return true;
3839
3840 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
3841 type, btrfs_bg_type_to_raid_name(bargs->target));
3842 return false;
Alexandru Moisebdcd3c92015-09-22 20:02:25 +00003843}
3844
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003845/*
Anand Jain56fc37d2018-11-20 16:12:56 +08003846 * Fill @buf with textual description of balance filter flags @bargs, up to
3847 * @size_buf including the terminating null. The output may be trimmed if it
3848 * does not fit into the provided buffer.
3849 */
3850static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3851 u32 size_buf)
3852{
3853 int ret;
3854 u32 size_bp = size_buf;
3855 char *bp = buf;
3856 u64 flags = bargs->flags;
3857 char tmp_buf[128] = {'\0'};
3858
3859 if (!flags)
3860 return;
3861
3862#define CHECK_APPEND_NOARG(a) \
3863 do { \
3864 ret = snprintf(bp, size_bp, (a)); \
3865 if (ret < 0 || ret >= size_bp) \
3866 goto out_overflow; \
3867 size_bp -= ret; \
3868 bp += ret; \
3869 } while (0)
3870
3871#define CHECK_APPEND_1ARG(a, v1) \
3872 do { \
3873 ret = snprintf(bp, size_bp, (a), (v1)); \
3874 if (ret < 0 || ret >= size_bp) \
3875 goto out_overflow; \
3876 size_bp -= ret; \
3877 bp += ret; \
3878 } while (0)
3879
3880#define CHECK_APPEND_2ARG(a, v1, v2) \
3881 do { \
3882 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3883 if (ret < 0 || ret >= size_bp) \
3884 goto out_overflow; \
3885 size_bp -= ret; \
3886 bp += ret; \
3887 } while (0)
3888
David Sterba158da512019-05-17 11:43:41 +02003889 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3890 CHECK_APPEND_1ARG("convert=%s,",
3891 btrfs_bg_type_to_raid_name(bargs->target));
Anand Jain56fc37d2018-11-20 16:12:56 +08003892
3893 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3894 CHECK_APPEND_NOARG("soft,");
3895
3896 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3897 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3898 sizeof(tmp_buf));
3899 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3900 }
3901
3902 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3903 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3904
3905 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3906 CHECK_APPEND_2ARG("usage=%u..%u,",
3907 bargs->usage_min, bargs->usage_max);
3908
3909 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3910 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3911
3912 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3913 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3914 bargs->pstart, bargs->pend);
3915
3916 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3917 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3918 bargs->vstart, bargs->vend);
3919
3920 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
3921 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
3922
3923 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
3924 CHECK_APPEND_2ARG("limit=%u..%u,",
3925 bargs->limit_min, bargs->limit_max);
3926
3927 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
3928 CHECK_APPEND_2ARG("stripes=%u..%u,",
3929 bargs->stripes_min, bargs->stripes_max);
3930
3931#undef CHECK_APPEND_2ARG
3932#undef CHECK_APPEND_1ARG
3933#undef CHECK_APPEND_NOARG
3934
3935out_overflow:
3936
3937 if (size_bp < size_buf)
3938 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
3939 else
3940 buf[0] = '\0';
3941}
3942
3943static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
3944{
3945 u32 size_buf = 1024;
3946 char tmp_buf[192] = {'\0'};
3947 char *buf;
3948 char *bp;
3949 u32 size_bp = size_buf;
3950 int ret;
3951 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3952
3953 buf = kzalloc(size_buf, GFP_KERNEL);
3954 if (!buf)
3955 return;
3956
3957 bp = buf;
3958
3959#define CHECK_APPEND_1ARG(a, v1) \
3960 do { \
3961 ret = snprintf(bp, size_bp, (a), (v1)); \
3962 if (ret < 0 || ret >= size_bp) \
3963 goto out_overflow; \
3964 size_bp -= ret; \
3965 bp += ret; \
3966 } while (0)
3967
3968 if (bctl->flags & BTRFS_BALANCE_FORCE)
3969 CHECK_APPEND_1ARG("%s", "-f ");
3970
3971 if (bctl->flags & BTRFS_BALANCE_DATA) {
3972 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
3973 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
3974 }
3975
3976 if (bctl->flags & BTRFS_BALANCE_METADATA) {
3977 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
3978 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
3979 }
3980
3981 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
3982 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
3983 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
3984 }
3985
3986#undef CHECK_APPEND_1ARG
3987
3988out_overflow:
3989
3990 if (size_bp < size_buf)
3991 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
3992 btrfs_info(fs_info, "balance: %s %s",
3993 (bctl->flags & BTRFS_BALANCE_RESUME) ?
3994 "resume" : "start", buf);
3995
3996 kfree(buf);
3997}
3998
3999/*
David Sterbadccdb072018-03-21 00:20:05 +01004000 * Should be called with balance mutexe held
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004001 */
David Sterba6fcf6e22018-05-07 17:44:03 +02004002int btrfs_balance(struct btrfs_fs_info *fs_info,
4003 struct btrfs_balance_control *bctl,
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004004 struct btrfs_ioctl_balance_args *bargs)
4005{
Adam Borowski14506122017-03-07 23:34:44 +01004006 u64 meta_target, data_target;
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02004007 u64 allowed;
Ilya Dryomove4837f82012-03-27 17:09:17 +03004008 int mixed = 0;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004009 int ret;
Stefan Behrens8dabb742012-11-06 13:15:27 +01004010 u64 num_devices;
Miao Xiede98ced2013-01-29 10:13:12 +00004011 unsigned seq;
Anand Jaine62869b2019-09-25 14:29:28 +08004012 bool reducing_redundancy;
David Sterba081db892019-05-17 11:43:27 +02004013 int i;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004014
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004015 if (btrfs_fs_closing(fs_info) ||
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004016 atomic_read(&fs_info->balance_pause_req) ||
Qu Wenruo726a3422020-02-17 14:16:52 +08004017 btrfs_should_cancel_balance(fs_info)) {
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004018 ret = -EINVAL;
4019 goto out;
4020 }
4021
Ilya Dryomove4837f82012-03-27 17:09:17 +03004022 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4023 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4024 mixed = 1;
4025
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02004026 /*
4027 * In case of mixed groups both data and meta should be picked,
4028 * and identical options should be given for both of them.
4029 */
Ilya Dryomove4837f82012-03-27 17:09:17 +03004030 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4031 if (mixed && (bctl->flags & allowed)) {
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02004032 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4033 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4034 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
Jeff Mahoney5d163e02016-09-20 10:05:00 -04004035 btrfs_err(fs_info,
Anand Jain6dac13f2018-05-16 10:51:26 +08004036 "balance: mixed groups data and metadata options must be the same");
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02004037 ret = -EINVAL;
4038 goto out;
4039 }
4040 }
4041
Josef Bacikb35cf1f2020-01-10 11:11:24 -05004042 /*
4043 * rw_devices will not change at the moment, device add/delete/replace
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004044 * are exclusive
Josef Bacikb35cf1f2020-01-10 11:11:24 -05004045 */
4046 num_devices = fs_info->fs_devices->rw_devices;
Qu Wenruofab27352019-09-25 10:13:27 +08004047
4048 /*
4049 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4050 * special bit for it, to make it easier to distinguish. Thus we need
4051 * to set it manually, or balance would refuse the profile.
4052 */
4053 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
David Sterba081db892019-05-17 11:43:27 +02004054 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4055 if (num_devices >= btrfs_raid_array[i].devs_min)
4056 allowed |= btrfs_raid_array[i].bg_flag;
Anand Jain1da73962018-08-10 13:53:21 +08004057
David Sterba5ba366c2020-02-27 21:00:52 +01004058 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4059 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4060 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
Ilya Dryomove4d8ec02012-01-16 22:04:48 +02004061 ret = -EINVAL;
4062 goto out;
4063 }
4064
David Sterba6079e122019-05-17 11:43:29 +02004065 /*
4066 * Allow to reduce metadata or system integrity only if force set for
4067 * profiles with redundancy (copies, parity)
4068 */
4069 allowed = 0;
4070 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4071 if (btrfs_raid_array[i].ncopies >= 2 ||
4072 btrfs_raid_array[i].tolerated_failures >= 1)
4073 allowed |= btrfs_raid_array[i].bg_flag;
4074 }
Miao Xiede98ced2013-01-29 10:13:12 +00004075 do {
4076 seq = read_seqbegin(&fs_info->profiles_lock);
4077
4078 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4079 (fs_info->avail_system_alloc_bits & allowed) &&
4080 !(bctl->sys.target & allowed)) ||
4081 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4082 (fs_info->avail_metadata_alloc_bits & allowed) &&
Filipe Manana5a8067c2018-11-19 09:48:12 +00004083 !(bctl->meta.target & allowed)))
Anand Jaine62869b2019-09-25 14:29:28 +08004084 reducing_redundancy = true;
Filipe Manana5a8067c2018-11-19 09:48:12 +00004085 else
Anand Jaine62869b2019-09-25 14:29:28 +08004086 reducing_redundancy = false;
Filipe Manana5a8067c2018-11-19 09:48:12 +00004087
4088 /* if we're not converting, the target field is uninitialized */
4089 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4090 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4091 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4092 bctl->data.target : fs_info->avail_data_alloc_bits;
Miao Xiede98ced2013-01-29 10:13:12 +00004093 } while (read_seqretry(&fs_info->profiles_lock, seq));
Ilya Dryomove4d8ec02012-01-16 22:04:48 +02004094
Anand Jaine62869b2019-09-25 14:29:28 +08004095 if (reducing_redundancy) {
Filipe Manana5a8067c2018-11-19 09:48:12 +00004096 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4097 btrfs_info(fs_info,
Anand Jaine62869b2019-09-25 14:29:28 +08004098 "balance: force reducing metadata redundancy");
Filipe Manana5a8067c2018-11-19 09:48:12 +00004099 } else {
4100 btrfs_err(fs_info,
Anand Jaine62869b2019-09-25 14:29:28 +08004101 "balance: reduces metadata redundancy, use --force if you want this");
Filipe Manana5a8067c2018-11-19 09:48:12 +00004102 ret = -EINVAL;
4103 goto out;
4104 }
4105 }
4106
Adam Borowski14506122017-03-07 23:34:44 +01004107 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4108 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
Sam Tygieree592d02016-01-06 08:46:12 +00004109 btrfs_warn(fs_info,
Anand Jain6dac13f2018-05-16 10:51:26 +08004110 "balance: metadata profile %s has lower redundancy than data profile %s",
David Sterba158da512019-05-17 11:43:41 +02004111 btrfs_bg_type_to_raid_name(meta_target),
4112 btrfs_bg_type_to_raid_name(data_target));
Sam Tygieree592d02016-01-06 08:46:12 +00004113 }
4114
Filipe Manana9e967492019-04-22 16:44:09 +01004115 if (fs_info->send_in_progress) {
4116 btrfs_warn_rl(fs_info,
4117"cannot run balance while send operations are in progress (%d in progress)",
4118 fs_info->send_in_progress);
4119 ret = -EAGAIN;
4120 goto out;
4121 }
4122
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04004123 ret = insert_balance_item(fs_info, bctl);
Ilya Dryomov59641012012-01-16 22:04:48 +02004124 if (ret && ret != -EEXIST)
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02004125 goto out;
4126
Ilya Dryomov59641012012-01-16 22:04:48 +02004127 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4128 BUG_ON(ret == -EEXIST);
David Sterba833aae12018-03-21 02:41:30 +01004129 BUG_ON(fs_info->balance_ctl);
4130 spin_lock(&fs_info->balance_lock);
4131 fs_info->balance_ctl = bctl;
4132 spin_unlock(&fs_info->balance_lock);
Ilya Dryomov59641012012-01-16 22:04:48 +02004133 } else {
4134 BUG_ON(ret != -EEXIST);
4135 spin_lock(&fs_info->balance_lock);
4136 update_balance_args(bctl);
4137 spin_unlock(&fs_info->balance_lock);
4138 }
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004139
David Sterba3009a622018-03-21 01:31:04 +01004140 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4141 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
Anand Jain56fc37d2018-11-20 16:12:56 +08004142 describe_balance_start_or_resume(fs_info);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004143 mutex_unlock(&fs_info->balance_mutex);
4144
4145 ret = __btrfs_balance(fs_info);
4146
4147 mutex_lock(&fs_info->balance_mutex);
Anand Jain7333bd02018-11-20 16:12:57 +08004148 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4149 btrfs_info(fs_info, "balance: paused");
Qu Wenruo44d354a2020-07-13 09:03:21 +08004150 /*
4151 * Balance can be canceled by:
4152 *
4153 * - Regular cancel request
4154 * Then ret == -ECANCELED and balance_cancel_req > 0
4155 *
4156 * - Fatal signal to "btrfs" process
4157 * Either the signal caught by wait_reserve_ticket() and callers
4158 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4159 * got -ECANCELED.
4160 * Either way, in this case balance_cancel_req = 0, and
4161 * ret == -EINTR or ret == -ECANCELED.
4162 *
4163 * So here we only check the return value to catch canceled balance.
4164 */
4165 else if (ret == -ECANCELED || ret == -EINTR)
Anand Jain7333bd02018-11-20 16:12:57 +08004166 btrfs_info(fs_info, "balance: canceled");
4167 else
4168 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4169
David Sterba3009a622018-03-21 01:31:04 +01004170 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004171
4172 if (bargs) {
4173 memset(bargs, 0, sizeof(*bargs));
David Sterba008ef092018-03-21 02:05:27 +01004174 btrfs_update_ioctl_balance_args(fs_info, bargs);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004175 }
4176
Ilya Dryomov3a01aa72013-03-06 01:57:55 -07004177 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4178 balance_need_close(fs_info)) {
David Sterba149196a2018-03-20 20:23:09 +01004179 reset_balance_state(fs_info);
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004180 btrfs_exclop_finish(fs_info);
Ilya Dryomov3a01aa72013-03-06 01:57:55 -07004181 }
4182
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004183 wake_up(&fs_info->balance_wait_q);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004184
4185 return ret;
4186out:
Ilya Dryomov59641012012-01-16 22:04:48 +02004187 if (bctl->flags & BTRFS_BALANCE_RESUME)
David Sterba149196a2018-03-20 20:23:09 +01004188 reset_balance_state(fs_info);
David Sterbaa17c95d2018-03-20 17:28:05 +01004189 else
Ilya Dryomov59641012012-01-16 22:04:48 +02004190 kfree(bctl);
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004191 btrfs_exclop_finish(fs_info);
David Sterbaa17c95d2018-03-20 17:28:05 +01004192
Ilya Dryomov59641012012-01-16 22:04:48 +02004193 return ret;
4194}
4195
4196static int balance_kthread(void *data)
4197{
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004198 struct btrfs_fs_info *fs_info = data;
Ilya Dryomov9555c6c2012-01-16 22:04:48 +02004199 int ret = 0;
Ilya Dryomov59641012012-01-16 22:04:48 +02004200
Ilya Dryomov59641012012-01-16 22:04:48 +02004201 mutex_lock(&fs_info->balance_mutex);
Anand Jain56fc37d2018-11-20 16:12:56 +08004202 if (fs_info->balance_ctl)
David Sterba6fcf6e22018-05-07 17:44:03 +02004203 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
Ilya Dryomov59641012012-01-16 22:04:48 +02004204 mutex_unlock(&fs_info->balance_mutex);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004205
Ilya Dryomov59641012012-01-16 22:04:48 +02004206 return ret;
4207}
4208
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004209int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4210{
4211 struct task_struct *tsk;
4212
David Sterba1354e1a2018-03-21 02:29:13 +01004213 mutex_lock(&fs_info->balance_mutex);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004214 if (!fs_info->balance_ctl) {
David Sterba1354e1a2018-03-21 02:29:13 +01004215 mutex_unlock(&fs_info->balance_mutex);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004216 return 0;
4217 }
David Sterba1354e1a2018-03-21 02:29:13 +01004218 mutex_unlock(&fs_info->balance_mutex);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004219
Jeff Mahoney3cdde222016-06-09 21:38:35 -04004220 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
Anand Jain6dac13f2018-05-16 10:51:26 +08004221 btrfs_info(fs_info, "balance: resume skipped");
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004222 return 0;
4223 }
4224
Anand Jain02ee6542018-05-17 15:16:51 +08004225 /*
4226 * A ro->rw remount sequence should continue with the paused balance
4227 * regardless of who pauses it, system or the user as of now, so set
4228 * the resume flag.
4229 */
4230 spin_lock(&fs_info->balance_lock);
4231 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4232 spin_unlock(&fs_info->balance_lock);
4233
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004234 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
Sachin Kamatcd633972013-07-15 16:52:18 +05304235 return PTR_ERR_OR_ZERO(tsk);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004236}
4237
Ilya Dryomov68310a52012-06-22 12:24:12 -06004238int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
Ilya Dryomov59641012012-01-16 22:04:48 +02004239{
Ilya Dryomov59641012012-01-16 22:04:48 +02004240 struct btrfs_balance_control *bctl;
4241 struct btrfs_balance_item *item;
4242 struct btrfs_disk_balance_args disk_bargs;
4243 struct btrfs_path *path;
4244 struct extent_buffer *leaf;
4245 struct btrfs_key key;
4246 int ret;
4247
4248 path = btrfs_alloc_path();
4249 if (!path)
4250 return -ENOMEM;
4251
Ilya Dryomov68310a52012-06-22 12:24:12 -06004252 key.objectid = BTRFS_BALANCE_OBJECTID;
David Sterbac479cb42016-01-25 17:51:31 +01004253 key.type = BTRFS_TEMPORARY_ITEM_KEY;
Ilya Dryomov68310a52012-06-22 12:24:12 -06004254 key.offset = 0;
4255
4256 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4257 if (ret < 0)
4258 goto out;
4259 if (ret > 0) { /* ret = -ENOENT; */
4260 ret = 0;
4261 goto out;
4262 }
4263
Ilya Dryomov59641012012-01-16 22:04:48 +02004264 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4265 if (!bctl) {
4266 ret = -ENOMEM;
4267 goto out;
4268 }
4269
Ilya Dryomov59641012012-01-16 22:04:48 +02004270 leaf = path->nodes[0];
4271 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4272
Ilya Dryomov68310a52012-06-22 12:24:12 -06004273 bctl->flags = btrfs_balance_flags(leaf, item);
4274 bctl->flags |= BTRFS_BALANCE_RESUME;
Ilya Dryomov59641012012-01-16 22:04:48 +02004275
4276 btrfs_balance_data(leaf, item, &disk_bargs);
4277 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4278 btrfs_balance_meta(leaf, item, &disk_bargs);
4279 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4280 btrfs_balance_sys(leaf, item, &disk_bargs);
4281 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4282
David Sterbaeee95e32018-03-20 20:07:58 +01004283 /*
4284 * This should never happen, as the paused balance state is recovered
4285 * during mount without any chance of other exclusive ops to collide.
4286 *
4287 * This gives the exclusive op status to balance and keeps in paused
4288 * state until user intervention (cancel or umount). If the ownership
4289 * cannot be assigned, show a message but do not fail. The balance
4290 * is in a paused state and must have fs_info::balance_ctl properly
4291 * set up.
4292 */
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004293 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
David Sterbaeee95e32018-03-20 20:07:58 +01004294 btrfs_warn(fs_info,
Anand Jain6dac13f2018-05-16 10:51:26 +08004295 "balance: cannot set exclusive op status, resume manually");
Ilya Dryomoved0fb782013-01-20 15:57:57 +02004296
Ilya Dryomov68310a52012-06-22 12:24:12 -06004297 mutex_lock(&fs_info->balance_mutex);
David Sterba833aae12018-03-21 02:41:30 +01004298 BUG_ON(fs_info->balance_ctl);
4299 spin_lock(&fs_info->balance_lock);
4300 fs_info->balance_ctl = bctl;
4301 spin_unlock(&fs_info->balance_lock);
Ilya Dryomov68310a52012-06-22 12:24:12 -06004302 mutex_unlock(&fs_info->balance_mutex);
Ilya Dryomov59641012012-01-16 22:04:48 +02004303out:
4304 btrfs_free_path(path);
Chris Mason8f18cf12008-04-25 16:53:30 -04004305 return ret;
4306}
4307
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004308int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4309{
4310 int ret = 0;
4311
4312 mutex_lock(&fs_info->balance_mutex);
4313 if (!fs_info->balance_ctl) {
4314 mutex_unlock(&fs_info->balance_mutex);
4315 return -ENOTCONN;
4316 }
4317
David Sterba3009a622018-03-21 01:31:04 +01004318 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004319 atomic_inc(&fs_info->balance_pause_req);
4320 mutex_unlock(&fs_info->balance_mutex);
4321
4322 wait_event(fs_info->balance_wait_q,
David Sterba3009a622018-03-21 01:31:04 +01004323 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004324
4325 mutex_lock(&fs_info->balance_mutex);
4326 /* we are good with balance_ctl ripped off from under us */
David Sterba3009a622018-03-21 01:31:04 +01004327 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004328 atomic_dec(&fs_info->balance_pause_req);
4329 } else {
4330 ret = -ENOTCONN;
4331 }
4332
4333 mutex_unlock(&fs_info->balance_mutex);
4334 return ret;
4335}
4336
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004337int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4338{
4339 mutex_lock(&fs_info->balance_mutex);
4340 if (!fs_info->balance_ctl) {
4341 mutex_unlock(&fs_info->balance_mutex);
4342 return -ENOTCONN;
4343 }
4344
David Sterbacf7d20f2018-03-21 01:45:32 +01004345 /*
4346 * A paused balance with the item stored on disk can be resumed at
4347 * mount time if the mount is read-write. Otherwise it's still paused
4348 * and we must not allow cancelling as it deletes the item.
4349 */
4350 if (sb_rdonly(fs_info->sb)) {
4351 mutex_unlock(&fs_info->balance_mutex);
4352 return -EROFS;
4353 }
4354
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004355 atomic_inc(&fs_info->balance_cancel_req);
4356 /*
4357 * if we are running just wait and return, balance item is
4358 * deleted in btrfs_balance in this case
4359 */
David Sterba3009a622018-03-21 01:31:04 +01004360 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004361 mutex_unlock(&fs_info->balance_mutex);
4362 wait_event(fs_info->balance_wait_q,
David Sterba3009a622018-03-21 01:31:04 +01004363 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004364 mutex_lock(&fs_info->balance_mutex);
4365 } else {
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004366 mutex_unlock(&fs_info->balance_mutex);
David Sterbadccdb072018-03-21 00:20:05 +01004367 /*
4368 * Lock released to allow other waiters to continue, we'll
4369 * reexamine the status again.
4370 */
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004371 mutex_lock(&fs_info->balance_mutex);
4372
David Sterbaa17c95d2018-03-20 17:28:05 +01004373 if (fs_info->balance_ctl) {
David Sterba149196a2018-03-20 20:23:09 +01004374 reset_balance_state(fs_info);
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004375 btrfs_exclop_finish(fs_info);
Anand Jain6dac13f2018-05-16 10:51:26 +08004376 btrfs_info(fs_info, "balance: canceled");
David Sterbaa17c95d2018-03-20 17:28:05 +01004377 }
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004378 }
4379
David Sterba3009a622018-03-21 01:31:04 +01004380 BUG_ON(fs_info->balance_ctl ||
4381 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004382 atomic_dec(&fs_info->balance_cancel_req);
4383 mutex_unlock(&fs_info->balance_mutex);
4384 return 0;
4385}
4386
Nikolay Borisov97f4dd02020-02-18 16:56:08 +02004387int btrfs_uuid_scan_kthread(void *data)
Stefan Behrens803b2f52013-08-15 17:11:21 +02004388{
4389 struct btrfs_fs_info *fs_info = data;
4390 struct btrfs_root *root = fs_info->tree_root;
4391 struct btrfs_key key;
Stefan Behrens803b2f52013-08-15 17:11:21 +02004392 struct btrfs_path *path = NULL;
4393 int ret = 0;
4394 struct extent_buffer *eb;
4395 int slot;
4396 struct btrfs_root_item root_item;
4397 u32 item_size;
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004398 struct btrfs_trans_handle *trans = NULL;
Josef Bacikc94bec22020-02-14 15:05:01 -05004399 bool closing = false;
Stefan Behrens803b2f52013-08-15 17:11:21 +02004400
4401 path = btrfs_alloc_path();
4402 if (!path) {
4403 ret = -ENOMEM;
4404 goto out;
4405 }
4406
4407 key.objectid = 0;
4408 key.type = BTRFS_ROOT_ITEM_KEY;
4409 key.offset = 0;
4410
Stefan Behrens803b2f52013-08-15 17:11:21 +02004411 while (1) {
Josef Bacikc94bec22020-02-14 15:05:01 -05004412 if (btrfs_fs_closing(fs_info)) {
4413 closing = true;
4414 break;
4415 }
Anand Jain7c829b72018-03-07 17:29:18 +08004416 ret = btrfs_search_forward(root, &key, path,
4417 BTRFS_OLDEST_GENERATION);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004418 if (ret) {
4419 if (ret > 0)
4420 ret = 0;
4421 break;
4422 }
4423
4424 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4425 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4426 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4427 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4428 goto skip;
4429
4430 eb = path->nodes[0];
4431 slot = path->slots[0];
4432 item_size = btrfs_item_size_nr(eb, slot);
4433 if (item_size < sizeof(root_item))
4434 goto skip;
4435
Stefan Behrens803b2f52013-08-15 17:11:21 +02004436 read_extent_buffer(eb, &root_item,
4437 btrfs_item_ptr_offset(eb, slot),
4438 (int)sizeof(root_item));
4439 if (btrfs_root_refs(&root_item) == 0)
4440 goto skip;
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004441
4442 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4443 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4444 if (trans)
4445 goto update_tree;
4446
4447 btrfs_release_path(path);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004448 /*
4449 * 1 - subvol uuid item
4450 * 1 - received_subvol uuid item
4451 */
4452 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4453 if (IS_ERR(trans)) {
4454 ret = PTR_ERR(trans);
4455 break;
4456 }
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004457 continue;
4458 } else {
4459 goto skip;
4460 }
4461update_tree:
Josef Bacik9771a5cf2020-08-10 11:42:26 -04004462 btrfs_release_path(path);
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004463 if (!btrfs_is_empty_uuid(root_item.uuid)) {
Lu Fengqicdb345a2018-05-29 15:01:53 +08004464 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
Stefan Behrens803b2f52013-08-15 17:11:21 +02004465 BTRFS_UUID_KEY_SUBVOL,
4466 key.objectid);
4467 if (ret < 0) {
Frank Holtonefe120a2013-12-20 11:37:06 -05004468 btrfs_warn(fs_info, "uuid_tree_add failed %d",
Stefan Behrens803b2f52013-08-15 17:11:21 +02004469 ret);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004470 break;
4471 }
4472 }
4473
4474 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
Lu Fengqicdb345a2018-05-29 15:01:53 +08004475 ret = btrfs_uuid_tree_add(trans,
Stefan Behrens803b2f52013-08-15 17:11:21 +02004476 root_item.received_uuid,
4477 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4478 key.objectid);
4479 if (ret < 0) {
Frank Holtonefe120a2013-12-20 11:37:06 -05004480 btrfs_warn(fs_info, "uuid_tree_add failed %d",
Stefan Behrens803b2f52013-08-15 17:11:21 +02004481 ret);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004482 break;
4483 }
4484 }
4485
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004486skip:
Josef Bacik9771a5cf2020-08-10 11:42:26 -04004487 btrfs_release_path(path);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004488 if (trans) {
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04004489 ret = btrfs_end_transaction(trans);
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004490 trans = NULL;
Stefan Behrens803b2f52013-08-15 17:11:21 +02004491 if (ret)
4492 break;
4493 }
4494
Stefan Behrens803b2f52013-08-15 17:11:21 +02004495 if (key.offset < (u64)-1) {
4496 key.offset++;
4497 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4498 key.offset = 0;
4499 key.type = BTRFS_ROOT_ITEM_KEY;
4500 } else if (key.objectid < (u64)-1) {
4501 key.offset = 0;
4502 key.type = BTRFS_ROOT_ITEM_KEY;
4503 key.objectid++;
4504 } else {
4505 break;
4506 }
4507 cond_resched();
4508 }
4509
4510out:
4511 btrfs_free_path(path);
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004512 if (trans && !IS_ERR(trans))
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04004513 btrfs_end_transaction(trans);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004514 if (ret)
Frank Holtonefe120a2013-12-20 11:37:06 -05004515 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
Josef Bacikc94bec22020-02-14 15:05:01 -05004516 else if (!closing)
Josef Bacikafcdd122016-09-02 15:40:02 -04004517 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004518 up(&fs_info->uuid_tree_rescan_sem);
4519 return 0;
4520}
4521
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004522int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4523{
4524 struct btrfs_trans_handle *trans;
4525 struct btrfs_root *tree_root = fs_info->tree_root;
4526 struct btrfs_root *uuid_root;
Stefan Behrens803b2f52013-08-15 17:11:21 +02004527 struct task_struct *task;
4528 int ret;
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004529
4530 /*
4531 * 1 - root node
4532 * 1 - root item
4533 */
4534 trans = btrfs_start_transaction(tree_root, 2);
4535 if (IS_ERR(trans))
4536 return PTR_ERR(trans);
4537
David Sterba9b7a2442019-03-20 13:20:49 +01004538 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004539 if (IS_ERR(uuid_root)) {
David Sterba6d13f542015-04-24 19:12:01 +02004540 ret = PTR_ERR(uuid_root);
Jeff Mahoney66642832016-06-10 18:19:25 -04004541 btrfs_abort_transaction(trans, ret);
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04004542 btrfs_end_transaction(trans);
David Sterba6d13f542015-04-24 19:12:01 +02004543 return ret;
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004544 }
4545
4546 fs_info->uuid_root = uuid_root;
4547
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04004548 ret = btrfs_commit_transaction(trans);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004549 if (ret)
4550 return ret;
4551
4552 down(&fs_info->uuid_tree_rescan_sem);
4553 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4554 if (IS_ERR(task)) {
Stefan Behrens70f80172013-08-15 17:11:23 +02004555 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
Frank Holtonefe120a2013-12-20 11:37:06 -05004556 btrfs_warn(fs_info, "failed to start uuid_scan task");
Stefan Behrens803b2f52013-08-15 17:11:21 +02004557 up(&fs_info->uuid_tree_rescan_sem);
4558 return PTR_ERR(task);
4559 }
4560
4561 return 0;
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004562}
Stefan Behrens803b2f52013-08-15 17:11:21 +02004563
Chris Mason8f18cf12008-04-25 16:53:30 -04004564/*
4565 * shrinking a device means finding all of the device extents past
4566 * the new size, and then following the back refs to the chunks.
4567 * The chunk relocation code actually frees the device extent
4568 */
4569int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4570{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004571 struct btrfs_fs_info *fs_info = device->fs_info;
4572 struct btrfs_root *root = fs_info->dev_root;
Chris Mason8f18cf12008-04-25 16:53:30 -04004573 struct btrfs_trans_handle *trans;
Chris Mason8f18cf12008-04-25 16:53:30 -04004574 struct btrfs_dev_extent *dev_extent = NULL;
4575 struct btrfs_path *path;
4576 u64 length;
Chris Mason8f18cf12008-04-25 16:53:30 -04004577 u64 chunk_offset;
4578 int ret;
4579 int slot;
Josef Bacikba1bf482009-09-11 16:11:19 -04004580 int failed = 0;
4581 bool retried = false;
Chris Mason8f18cf12008-04-25 16:53:30 -04004582 struct extent_buffer *l;
4583 struct btrfs_key key;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004584 struct btrfs_super_block *super_copy = fs_info->super_copy;
Chris Mason8f18cf12008-04-25 16:53:30 -04004585 u64 old_total = btrfs_super_total_bytes(super_copy);
Miao Xie7cc8e582014-09-03 21:35:38 +08004586 u64 old_size = btrfs_device_get_total_bytes(device);
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03004587 u64 diff;
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004588 u64 start;
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03004589
4590 new_size = round_down(new_size, fs_info->sectorsize);
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004591 start = new_size;
Nikolay Borisov0e4324a2017-07-21 11:28:24 +03004592 diff = round_down(old_size - new_size, fs_info->sectorsize);
Chris Mason8f18cf12008-04-25 16:53:30 -04004593
Anand Jain401e29c2017-12-04 12:54:55 +08004594 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
Stefan Behrens63a212a2012-11-05 18:29:28 +01004595 return -EINVAL;
4596
Chris Mason8f18cf12008-04-25 16:53:30 -04004597 path = btrfs_alloc_path();
4598 if (!path)
4599 return -ENOMEM;
4600
Gu Jinxiang0338dff2018-04-27 16:22:07 +08004601 path->reada = READA_BACK;
Chris Mason8f18cf12008-04-25 16:53:30 -04004602
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004603 trans = btrfs_start_transaction(root, 0);
4604 if (IS_ERR(trans)) {
4605 btrfs_free_path(path);
4606 return PTR_ERR(trans);
4607 }
4608
David Sterba34441362016-10-04 19:34:27 +02004609 mutex_lock(&fs_info->chunk_mutex);
Chris Mason7d9eb122008-07-08 14:19:17 -04004610
Miao Xie7cc8e582014-09-03 21:35:38 +08004611 btrfs_device_set_total_bytes(device, new_size);
Anand Jainebbede42017-12-04 12:54:52 +08004612 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
Yan Zheng2b820322008-11-17 21:11:30 -05004613 device->fs_devices->total_rw_bytes -= diff;
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03004614 atomic64_sub(diff, &fs_info->free_chunk_space);
Josef Bacik2bf64752011-09-26 17:12:22 -04004615 }
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004616
4617 /*
4618 * Once the device's size has been set to the new size, ensure all
4619 * in-memory chunks are synced to disk so that the loop below sees them
4620 * and relocates them accordingly.
4621 */
Jeff Mahoney1c11b632019-03-27 14:24:12 +02004622 if (contains_pending_extent(device, &start, diff)) {
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004623 mutex_unlock(&fs_info->chunk_mutex);
4624 ret = btrfs_commit_transaction(trans);
4625 if (ret)
4626 goto done;
4627 } else {
4628 mutex_unlock(&fs_info->chunk_mutex);
4629 btrfs_end_transaction(trans);
4630 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004631
Josef Bacikba1bf482009-09-11 16:11:19 -04004632again:
Chris Mason8f18cf12008-04-25 16:53:30 -04004633 key.objectid = device->devid;
4634 key.offset = (u64)-1;
4635 key.type = BTRFS_DEV_EXTENT_KEY;
4636
Ilya Dryomov213e64d2012-03-27 17:09:18 +03004637 do {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004638 mutex_lock(&fs_info->delete_unused_bgs_mutex);
Chris Mason8f18cf12008-04-25 16:53:30 -04004639 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01004640 if (ret < 0) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004641 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Chris Mason8f18cf12008-04-25 16:53:30 -04004642 goto done;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01004643 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004644
4645 ret = btrfs_previous_item(root, path, 0, key.type);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01004646 if (ret)
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004647 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Chris Mason8f18cf12008-04-25 16:53:30 -04004648 if (ret < 0)
4649 goto done;
4650 if (ret) {
4651 ret = 0;
David Sterbab3b4aa72011-04-21 01:20:15 +02004652 btrfs_release_path(path);
Yan Zhengbf1fb512009-07-22 09:59:00 -04004653 break;
Chris Mason8f18cf12008-04-25 16:53:30 -04004654 }
4655
4656 l = path->nodes[0];
4657 slot = path->slots[0];
4658 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4659
Josef Bacikba1bf482009-09-11 16:11:19 -04004660 if (key.objectid != device->devid) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004661 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
David Sterbab3b4aa72011-04-21 01:20:15 +02004662 btrfs_release_path(path);
Yan Zhengbf1fb512009-07-22 09:59:00 -04004663 break;
Josef Bacikba1bf482009-09-11 16:11:19 -04004664 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004665
4666 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4667 length = btrfs_dev_extent_length(l, dev_extent);
4668
Josef Bacikba1bf482009-09-11 16:11:19 -04004669 if (key.offset + length <= new_size) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004670 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
David Sterbab3b4aa72011-04-21 01:20:15 +02004671 btrfs_release_path(path);
Chris Balld6397ba2009-04-27 07:29:03 -04004672 break;
Josef Bacikba1bf482009-09-11 16:11:19 -04004673 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004674
Chris Mason8f18cf12008-04-25 16:53:30 -04004675 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
David Sterbab3b4aa72011-04-21 01:20:15 +02004676 btrfs_release_path(path);
Chris Mason8f18cf12008-04-25 16:53:30 -04004677
Liu Boa6f93c72017-11-15 16:28:11 -07004678 /*
4679 * We may be relocating the only data chunk we have,
4680 * which could potentially end up with losing data's
4681 * raid profile, so lets allocate an empty one in
4682 * advance.
4683 */
4684 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4685 if (ret < 0) {
4686 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4687 goto done;
4688 }
4689
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004690 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4691 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Omar Sandovaleede2bf2016-11-03 10:28:12 -07004692 if (ret == -ENOSPC) {
Josef Bacikba1bf482009-09-11 16:11:19 -04004693 failed++;
Omar Sandovaleede2bf2016-11-03 10:28:12 -07004694 } else if (ret) {
4695 if (ret == -ETXTBSY) {
4696 btrfs_warn(fs_info,
4697 "could not shrink block group %llu due to active swapfile",
4698 chunk_offset);
4699 }
4700 goto done;
4701 }
Ilya Dryomov213e64d2012-03-27 17:09:18 +03004702 } while (key.offset-- > 0);
Josef Bacikba1bf482009-09-11 16:11:19 -04004703
4704 if (failed && !retried) {
4705 failed = 0;
4706 retried = true;
4707 goto again;
4708 } else if (failed && retried) {
4709 ret = -ENOSPC;
Josef Bacikba1bf482009-09-11 16:11:19 -04004710 goto done;
Chris Mason8f18cf12008-04-25 16:53:30 -04004711 }
4712
Chris Balld6397ba2009-04-27 07:29:03 -04004713 /* Shrinking succeeded, else we would be at "done". */
Yan, Zhenga22285a2010-05-16 10:48:46 -04004714 trans = btrfs_start_transaction(root, 0);
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00004715 if (IS_ERR(trans)) {
4716 ret = PTR_ERR(trans);
4717 goto done;
4718 }
4719
David Sterba34441362016-10-04 19:34:27 +02004720 mutex_lock(&fs_info->chunk_mutex);
Qu Wenruoc57dd1f2020-07-31 19:29:11 +08004721 /* Clear all state bits beyond the shrunk device size */
4722 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4723 CHUNK_STATE_MASK);
4724
Miao Xie7cc8e582014-09-03 21:35:38 +08004725 btrfs_device_set_disk_total_bytes(device, new_size);
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02004726 if (list_empty(&device->post_commit_list))
4727 list_add_tail(&device->post_commit_list,
4728 &trans->transaction->dev_update_list);
Chris Balld6397ba2009-04-27 07:29:03 -04004729
Chris Balld6397ba2009-04-27 07:29:03 -04004730 WARN_ON(diff > old_total);
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03004731 btrfs_set_super_total_bytes(super_copy,
4732 round_down(old_total - diff, fs_info->sectorsize));
David Sterba34441362016-10-04 19:34:27 +02004733 mutex_unlock(&fs_info->chunk_mutex);
Miao Xie2196d6e2014-09-03 21:35:41 +08004734
4735 /* Now btrfs_update_device() will change the on-disk size. */
4736 ret = btrfs_update_device(trans, device);
Anand Jain801660b2018-08-06 18:12:37 +08004737 if (ret < 0) {
4738 btrfs_abort_transaction(trans, ret);
4739 btrfs_end_transaction(trans);
4740 } else {
4741 ret = btrfs_commit_transaction(trans);
4742 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004743done:
4744 btrfs_free_path(path);
Filipe Manana53e489b2015-06-02 14:43:21 +01004745 if (ret) {
David Sterba34441362016-10-04 19:34:27 +02004746 mutex_lock(&fs_info->chunk_mutex);
Filipe Manana53e489b2015-06-02 14:43:21 +01004747 btrfs_device_set_total_bytes(device, old_size);
Anand Jainebbede42017-12-04 12:54:52 +08004748 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
Filipe Manana53e489b2015-06-02 14:43:21 +01004749 device->fs_devices->total_rw_bytes += diff;
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03004750 atomic64_add(diff, &fs_info->free_chunk_space);
David Sterba34441362016-10-04 19:34:27 +02004751 mutex_unlock(&fs_info->chunk_mutex);
Filipe Manana53e489b2015-06-02 14:43:21 +01004752 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004753 return ret;
4754}
4755
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04004756static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
Chris Mason0b86a832008-03-24 15:01:56 -04004757 struct btrfs_key *key,
4758 struct btrfs_chunk *chunk, int item_size)
4759{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004760 struct btrfs_super_block *super_copy = fs_info->super_copy;
Chris Mason0b86a832008-03-24 15:01:56 -04004761 struct btrfs_disk_key disk_key;
4762 u32 array_size;
4763 u8 *ptr;
4764
David Sterba34441362016-10-04 19:34:27 +02004765 mutex_lock(&fs_info->chunk_mutex);
Chris Mason0b86a832008-03-24 15:01:56 -04004766 array_size = btrfs_super_sys_array_size(super_copy);
Gui Hecheng5f43f862014-04-21 20:13:11 +08004767 if (array_size + item_size + sizeof(disk_key)
Miao Xiefe48a5c2014-09-03 21:35:39 +08004768 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
David Sterba34441362016-10-04 19:34:27 +02004769 mutex_unlock(&fs_info->chunk_mutex);
Chris Mason0b86a832008-03-24 15:01:56 -04004770 return -EFBIG;
Miao Xiefe48a5c2014-09-03 21:35:39 +08004771 }
Chris Mason0b86a832008-03-24 15:01:56 -04004772
4773 ptr = super_copy->sys_chunk_array + array_size;
4774 btrfs_cpu_key_to_disk(&disk_key, key);
4775 memcpy(ptr, &disk_key, sizeof(disk_key));
4776 ptr += sizeof(disk_key);
4777 memcpy(ptr, chunk, item_size);
4778 item_size += sizeof(disk_key);
4779 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
David Sterba34441362016-10-04 19:34:27 +02004780 mutex_unlock(&fs_info->chunk_mutex);
Miao Xiefe48a5c2014-09-03 21:35:39 +08004781
Chris Mason0b86a832008-03-24 15:01:56 -04004782 return 0;
4783}
4784
Miao Xieb2117a32011-01-05 10:07:28 +00004785/*
Arne Jansen73c5de02011-04-12 12:07:57 +02004786 * sort the devices in descending order by max_avail, total_avail
Miao Xieb2117a32011-01-05 10:07:28 +00004787 */
Arne Jansen73c5de02011-04-12 12:07:57 +02004788static int btrfs_cmp_device_info(const void *a, const void *b)
Miao Xieb2117a32011-01-05 10:07:28 +00004789{
Arne Jansen73c5de02011-04-12 12:07:57 +02004790 const struct btrfs_device_info *di_a = a;
4791 const struct btrfs_device_info *di_b = b;
Miao Xieb2117a32011-01-05 10:07:28 +00004792
Arne Jansen73c5de02011-04-12 12:07:57 +02004793 if (di_a->max_avail > di_b->max_avail)
4794 return -1;
4795 if (di_a->max_avail < di_b->max_avail)
4796 return 1;
4797 if (di_a->total_avail > di_b->total_avail)
4798 return -1;
4799 if (di_a->total_avail < di_b->total_avail)
4800 return 1;
Miao Xieb2117a32011-01-05 10:07:28 +00004801 return 0;
4802}
4803
David Woodhouse53b381b2013-01-29 18:40:14 -05004804static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4805{
Zhao Leiffe2d202015-01-20 15:11:44 +08004806 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
David Woodhouse53b381b2013-01-29 18:40:14 -05004807 return;
4808
Miao Xieceda0862013-04-11 10:30:16 +00004809 btrfs_set_fs_incompat(info, RAID56);
David Woodhouse53b381b2013-01-29 18:40:14 -05004810}
4811
David Sterbacfbb8252018-07-10 18:15:05 +02004812static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4813{
4814 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4815 return;
4816
4817 btrfs_set_fs_incompat(info, RAID1C34);
4818}
4819
Naohiro Aota4f2bafe2020-02-25 12:56:10 +09004820/*
4821 * Structure used internally for __btrfs_alloc_chunk() function.
4822 * Wraps needed parameters.
4823 */
4824struct alloc_chunk_ctl {
4825 u64 start;
4826 u64 type;
4827 /* Total number of stripes to allocate */
4828 int num_stripes;
4829 /* sub_stripes info for map */
4830 int sub_stripes;
4831 /* Stripes per device */
4832 int dev_stripes;
4833 /* Maximum number of devices to use */
4834 int devs_max;
4835 /* Minimum number of devices to use */
4836 int devs_min;
4837 /* ndevs has to be a multiple of this */
4838 int devs_increment;
4839 /* Number of copies */
4840 int ncopies;
4841 /* Number of stripes worth of bytes to store parity information */
4842 int nparity;
4843 u64 max_stripe_size;
4844 u64 max_chunk_size;
Naohiro Aota6aafb302020-02-25 12:56:15 +09004845 u64 dev_extent_min;
Naohiro Aota4f2bafe2020-02-25 12:56:10 +09004846 u64 stripe_size;
4847 u64 chunk_size;
4848 int ndevs;
4849};
4850
Naohiro Aota27c314d2020-02-25 12:56:11 +09004851static void init_alloc_chunk_ctl_policy_regular(
4852 struct btrfs_fs_devices *fs_devices,
4853 struct alloc_chunk_ctl *ctl)
4854{
4855 u64 type = ctl->type;
4856
4857 if (type & BTRFS_BLOCK_GROUP_DATA) {
4858 ctl->max_stripe_size = SZ_1G;
4859 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4860 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4861 /* For larger filesystems, use larger metadata chunks */
4862 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4863 ctl->max_stripe_size = SZ_1G;
4864 else
4865 ctl->max_stripe_size = SZ_256M;
4866 ctl->max_chunk_size = ctl->max_stripe_size;
4867 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4868 ctl->max_stripe_size = SZ_32M;
4869 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
4870 ctl->devs_max = min_t(int, ctl->devs_max,
4871 BTRFS_MAX_DEVS_SYS_CHUNK);
4872 } else {
4873 BUG();
4874 }
4875
4876 /* We don't want a chunk larger than 10% of writable space */
4877 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4878 ctl->max_chunk_size);
Naohiro Aota6aafb302020-02-25 12:56:15 +09004879 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
Naohiro Aota27c314d2020-02-25 12:56:11 +09004880}
4881
4882static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
4883 struct alloc_chunk_ctl *ctl)
4884{
4885 int index = btrfs_bg_flags_to_raid_index(ctl->type);
4886
4887 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
4888 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
4889 ctl->devs_max = btrfs_raid_array[index].devs_max;
4890 if (!ctl->devs_max)
4891 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
4892 ctl->devs_min = btrfs_raid_array[index].devs_min;
4893 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
4894 ctl->ncopies = btrfs_raid_array[index].ncopies;
4895 ctl->nparity = btrfs_raid_array[index].nparity;
4896 ctl->ndevs = 0;
4897
4898 switch (fs_devices->chunk_alloc_policy) {
4899 case BTRFS_CHUNK_ALLOC_REGULAR:
4900 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
4901 break;
4902 default:
4903 BUG();
4904 }
4905}
4906
Naohiro Aota560156c2020-02-25 12:56:12 +09004907static int gather_device_info(struct btrfs_fs_devices *fs_devices,
4908 struct alloc_chunk_ctl *ctl,
4909 struct btrfs_device_info *devices_info)
4910{
4911 struct btrfs_fs_info *info = fs_devices->fs_info;
4912 struct btrfs_device *device;
4913 u64 total_avail;
4914 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
Naohiro Aota560156c2020-02-25 12:56:12 +09004915 int ret;
4916 int ndevs = 0;
4917 u64 max_avail;
4918 u64 dev_offset;
4919
4920 /*
4921 * in the first pass through the devices list, we gather information
4922 * about the available holes on each device.
4923 */
4924 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4925 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4926 WARN(1, KERN_ERR
4927 "BTRFS: read-only device in alloc_list\n");
4928 continue;
4929 }
4930
4931 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4932 &device->dev_state) ||
4933 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4934 continue;
4935
4936 if (device->total_bytes > device->bytes_used)
4937 total_avail = device->total_bytes - device->bytes_used;
4938 else
4939 total_avail = 0;
4940
4941 /* If there is no space on this device, skip it. */
Naohiro Aota6aafb302020-02-25 12:56:15 +09004942 if (total_avail < ctl->dev_extent_min)
Naohiro Aota560156c2020-02-25 12:56:12 +09004943 continue;
4944
4945 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
4946 &max_avail);
4947 if (ret && ret != -ENOSPC)
4948 return ret;
4949
4950 if (ret == 0)
4951 max_avail = dev_extent_want;
4952
Naohiro Aota6aafb302020-02-25 12:56:15 +09004953 if (max_avail < ctl->dev_extent_min) {
Naohiro Aota560156c2020-02-25 12:56:12 +09004954 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4955 btrfs_debug(info,
4956 "%s: devid %llu has no free space, have=%llu want=%llu",
4957 __func__, device->devid, max_avail,
Naohiro Aota6aafb302020-02-25 12:56:15 +09004958 ctl->dev_extent_min);
Naohiro Aota560156c2020-02-25 12:56:12 +09004959 continue;
4960 }
4961
4962 if (ndevs == fs_devices->rw_devices) {
4963 WARN(1, "%s: found more than %llu devices\n",
4964 __func__, fs_devices->rw_devices);
4965 break;
4966 }
4967 devices_info[ndevs].dev_offset = dev_offset;
4968 devices_info[ndevs].max_avail = max_avail;
4969 devices_info[ndevs].total_avail = total_avail;
4970 devices_info[ndevs].dev = device;
4971 ++ndevs;
4972 }
4973 ctl->ndevs = ndevs;
4974
4975 /*
4976 * now sort the devices by hole size / available space
4977 */
4978 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4979 btrfs_cmp_device_info, NULL);
4980
4981 return 0;
4982}
4983
Naohiro Aota5badf512020-02-25 12:56:13 +09004984static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
4985 struct btrfs_device_info *devices_info)
4986{
4987 /* Number of stripes that count for block group size */
4988 int data_stripes;
4989
4990 /*
4991 * The primary goal is to maximize the number of stripes, so use as
4992 * many devices as possible, even if the stripes are not maximum sized.
4993 *
4994 * The DUP profile stores more than one stripe per device, the
4995 * max_avail is the total size so we have to adjust.
4996 */
4997 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
4998 ctl->dev_stripes);
4999 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5000
5001 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5002 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5003
5004 /*
5005 * Use the number of data stripes to figure out how big this chunk is
5006 * really going to be in terms of logical address space, and compare
5007 * that answer with the max chunk size. If it's higher, we try to
5008 * reduce stripe_size.
5009 */
5010 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5011 /*
5012 * Reduce stripe_size, round it up to a 16MB boundary again and
5013 * then use it, unless it ends up being even bigger than the
5014 * previous value we had already.
5015 */
5016 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5017 data_stripes), SZ_16M),
5018 ctl->stripe_size);
5019 }
5020
5021 /* Align to BTRFS_STRIPE_LEN */
5022 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5023 ctl->chunk_size = ctl->stripe_size * data_stripes;
5024
5025 return 0;
5026}
5027
5028static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5029 struct alloc_chunk_ctl *ctl,
5030 struct btrfs_device_info *devices_info)
5031{
5032 struct btrfs_fs_info *info = fs_devices->fs_info;
5033
5034 /*
5035 * Round down to number of usable stripes, devs_increment can be any
5036 * number so we can't use round_down() that requires power of 2, while
5037 * rounddown is safe.
5038 */
5039 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5040
5041 if (ctl->ndevs < ctl->devs_min) {
5042 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5043 btrfs_debug(info,
5044 "%s: not enough devices with free space: have=%d minimum required=%d",
5045 __func__, ctl->ndevs, ctl->devs_min);
5046 }
5047 return -ENOSPC;
5048 }
5049
5050 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5051
5052 switch (fs_devices->chunk_alloc_policy) {
5053 case BTRFS_CHUNK_ALLOC_REGULAR:
5054 return decide_stripe_size_regular(ctl, devices_info);
5055 default:
5056 BUG();
5057 }
5058}
5059
Naohiro Aotadce580c2020-02-25 12:56:14 +09005060static int create_chunk(struct btrfs_trans_handle *trans,
5061 struct alloc_chunk_ctl *ctl,
5062 struct btrfs_device_info *devices_info)
5063{
5064 struct btrfs_fs_info *info = trans->fs_info;
5065 struct map_lookup *map = NULL;
5066 struct extent_map_tree *em_tree;
5067 struct extent_map *em;
5068 u64 start = ctl->start;
5069 u64 type = ctl->type;
5070 int ret;
5071 int i;
5072 int j;
5073
5074 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5075 if (!map)
5076 return -ENOMEM;
5077 map->num_stripes = ctl->num_stripes;
5078
5079 for (i = 0; i < ctl->ndevs; ++i) {
5080 for (j = 0; j < ctl->dev_stripes; ++j) {
5081 int s = i * ctl->dev_stripes + j;
5082 map->stripes[s].dev = devices_info[i].dev;
5083 map->stripes[s].physical = devices_info[i].dev_offset +
5084 j * ctl->stripe_size;
5085 }
5086 }
5087 map->stripe_len = BTRFS_STRIPE_LEN;
5088 map->io_align = BTRFS_STRIPE_LEN;
5089 map->io_width = BTRFS_STRIPE_LEN;
5090 map->type = type;
5091 map->sub_stripes = ctl->sub_stripes;
5092
5093 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5094
5095 em = alloc_extent_map();
5096 if (!em) {
5097 kfree(map);
5098 return -ENOMEM;
5099 }
5100 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5101 em->map_lookup = map;
5102 em->start = start;
5103 em->len = ctl->chunk_size;
5104 em->block_start = 0;
5105 em->block_len = em->len;
5106 em->orig_block_len = ctl->stripe_size;
5107
5108 em_tree = &info->mapping_tree;
5109 write_lock(&em_tree->lock);
5110 ret = add_extent_mapping(em_tree, em, 0);
5111 if (ret) {
5112 write_unlock(&em_tree->lock);
5113 free_extent_map(em);
5114 return ret;
5115 }
5116 write_unlock(&em_tree->lock);
5117
5118 ret = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5119 if (ret)
5120 goto error_del_extent;
5121
5122 for (i = 0; i < map->num_stripes; i++) {
5123 struct btrfs_device *dev = map->stripes[i].dev;
5124
5125 btrfs_device_set_bytes_used(dev,
5126 dev->bytes_used + ctl->stripe_size);
5127 if (list_empty(&dev->post_commit_list))
5128 list_add_tail(&dev->post_commit_list,
5129 &trans->transaction->dev_update_list);
5130 }
5131
5132 atomic64_sub(ctl->stripe_size * map->num_stripes,
5133 &info->free_chunk_space);
5134
5135 free_extent_map(em);
5136 check_raid56_incompat_flag(info, type);
5137 check_raid1c34_incompat_flag(info, type);
5138
5139 return 0;
5140
5141error_del_extent:
5142 write_lock(&em_tree->lock);
5143 remove_extent_mapping(em_tree, em);
5144 write_unlock(&em_tree->lock);
5145
5146 /* One for our allocation */
5147 free_extent_map(em);
5148 /* One for the tree reference */
5149 free_extent_map(em);
5150
5151 return ret;
5152}
5153
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005154int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
Miao Xieb2117a32011-01-05 10:07:28 +00005155{
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04005156 struct btrfs_fs_info *info = trans->fs_info;
Miao Xieb2117a32011-01-05 10:07:28 +00005157 struct btrfs_fs_devices *fs_devices = info->fs_devices;
Arne Jansen73c5de02011-04-12 12:07:57 +02005158 struct btrfs_device_info *devices_info = NULL;
Naohiro Aota4f2bafe2020-02-25 12:56:10 +09005159 struct alloc_chunk_ctl ctl;
Miao Xieb2117a32011-01-05 10:07:28 +00005160 int ret;
Miao Xieb2117a32011-01-05 10:07:28 +00005161
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005162 lockdep_assert_held(&info->chunk_mutex);
5163
Naohiro Aotab25c19f2020-02-25 12:56:07 +09005164 if (!alloc_profile_is_valid(type, 0)) {
5165 ASSERT(0);
5166 return -EINVAL;
5167 }
Arne Jansen73c5de02011-04-12 12:07:57 +02005168
Qu Wenruo4117f202018-01-22 13:50:54 +08005169 if (list_empty(&fs_devices->alloc_list)) {
5170 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5171 btrfs_debug(info, "%s: no writable device", __func__);
Miao Xieb2117a32011-01-05 10:07:28 +00005172 return -ENOSPC;
Qu Wenruo4117f202018-01-22 13:50:54 +08005173 }
Miao Xieb2117a32011-01-05 10:07:28 +00005174
Naohiro Aota27c314d2020-02-25 12:56:11 +09005175 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5176 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5177 ASSERT(0);
5178 return -EINVAL;
Arne Jansen73c5de02011-04-12 12:07:57 +02005179 }
5180
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005181 ctl.start = find_next_chunk(info);
Naohiro Aota27c314d2020-02-25 12:56:11 +09005182 ctl.type = type;
5183 init_alloc_chunk_ctl(fs_devices, &ctl);
Miao Xieb2117a32011-01-05 10:07:28 +00005184
David Sterba31e818f2015-02-20 18:00:26 +01005185 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
Miao Xieb2117a32011-01-05 10:07:28 +00005186 GFP_NOFS);
5187 if (!devices_info)
5188 return -ENOMEM;
5189
Naohiro Aota560156c2020-02-25 12:56:12 +09005190 ret = gather_device_info(fs_devices, &ctl, devices_info);
5191 if (ret < 0)
Naohiro Aotadce580c2020-02-25 12:56:14 +09005192 goto out;
Arne Jansen73c5de02011-04-12 12:07:57 +02005193
Naohiro Aota5badf512020-02-25 12:56:13 +09005194 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5195 if (ret < 0)
Naohiro Aotadce580c2020-02-25 12:56:14 +09005196 goto out;
Arne Jansen73c5de02011-04-12 12:07:57 +02005197
Naohiro Aotadce580c2020-02-25 12:56:14 +09005198 ret = create_chunk(trans, &ctl, devices_info);
Chris Mason9b3f68b2008-04-18 10:29:51 -04005199
Naohiro Aotadce580c2020-02-25 12:56:14 +09005200out:
Miao Xieb2117a32011-01-05 10:07:28 +00005201 kfree(devices_info);
5202 return ret;
Yan Zheng2b820322008-11-17 21:11:30 -05005203}
5204
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005205/*
5206 * Chunk allocation falls into two parts. The first part does work
5207 * that makes the new allocated chunk usable, but does not do any operation
5208 * that modifies the chunk tree. The second part does the work that
5209 * requires modifying the chunk tree. This division is important for the
5210 * bootstrap process of adding storage to a seed btrfs.
5211 */
Josef Bacik6df9a952013-06-27 13:22:46 -04005212int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
Nikolay Borisov97aff912018-07-20 19:37:53 +03005213 u64 chunk_offset, u64 chunk_size)
Yan Zheng2b820322008-11-17 21:11:30 -05005214{
Nikolay Borisov97aff912018-07-20 19:37:53 +03005215 struct btrfs_fs_info *fs_info = trans->fs_info;
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04005216 struct btrfs_root *extent_root = fs_info->extent_root;
5217 struct btrfs_root *chunk_root = fs_info->chunk_root;
Yan Zheng2b820322008-11-17 21:11:30 -05005218 struct btrfs_key key;
Yan Zheng2b820322008-11-17 21:11:30 -05005219 struct btrfs_device *device;
5220 struct btrfs_chunk *chunk;
5221 struct btrfs_stripe *stripe;
Josef Bacik6df9a952013-06-27 13:22:46 -04005222 struct extent_map *em;
5223 struct map_lookup *map;
5224 size_t item_size;
5225 u64 dev_offset;
5226 u64 stripe_size;
5227 int i = 0;
Chris Mason140e6392015-12-23 13:30:51 -08005228 int ret = 0;
Yan Zheng2b820322008-11-17 21:11:30 -05005229
Omar Sandoval60ca8422018-05-16 16:34:31 -07005230 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
Liu Bo592d92e2017-03-14 13:33:55 -07005231 if (IS_ERR(em))
5232 return PTR_ERR(em);
Josef Bacik6df9a952013-06-27 13:22:46 -04005233
Jeff Mahoney95617d62015-06-03 10:55:48 -04005234 map = em->map_lookup;
Josef Bacik6df9a952013-06-27 13:22:46 -04005235 item_size = btrfs_chunk_item_size(map->num_stripes);
5236 stripe_size = em->orig_block_len;
5237
5238 chunk = kzalloc(item_size, GFP_NOFS);
5239 if (!chunk) {
5240 ret = -ENOMEM;
5241 goto out;
5242 }
5243
Filipe Manana50460e32015-11-20 10:42:47 +00005244 /*
5245 * Take the device list mutex to prevent races with the final phase of
5246 * a device replace operation that replaces the device object associated
5247 * with the map's stripes, because the device object's id can change
5248 * at any time during that final phase of the device replace operation
5249 * (dev-replace.c:btrfs_dev_replace_finishing()).
5250 */
Jeff Mahoney0b246af2016-06-22 18:54:23 -04005251 mutex_lock(&fs_info->fs_devices->device_list_mutex);
Josef Bacik6df9a952013-06-27 13:22:46 -04005252 for (i = 0; i < map->num_stripes; i++) {
5253 device = map->stripes[i].dev;
5254 dev_offset = map->stripes[i].physical;
5255
Yan Zheng2b820322008-11-17 21:11:30 -05005256 ret = btrfs_update_device(trans, device);
Mark Fasheh3acd3952011-09-08 17:40:01 -07005257 if (ret)
Filipe Manana50460e32015-11-20 10:42:47 +00005258 break;
Nikolay Borisovb5d90712017-08-18 17:58:23 +03005259 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5260 dev_offset, stripe_size);
Josef Bacik6df9a952013-06-27 13:22:46 -04005261 if (ret)
Filipe Manana50460e32015-11-20 10:42:47 +00005262 break;
5263 }
5264 if (ret) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04005265 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
Filipe Manana50460e32015-11-20 10:42:47 +00005266 goto out;
Yan Zheng2b820322008-11-17 21:11:30 -05005267 }
5268
Yan Zheng2b820322008-11-17 21:11:30 -05005269 stripe = &chunk->stripe;
Josef Bacik6df9a952013-06-27 13:22:46 -04005270 for (i = 0; i < map->num_stripes; i++) {
5271 device = map->stripes[i].dev;
5272 dev_offset = map->stripes[i].physical;
Yan Zheng2b820322008-11-17 21:11:30 -05005273
5274 btrfs_set_stack_stripe_devid(stripe, device->devid);
5275 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5276 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5277 stripe++;
Yan Zheng2b820322008-11-17 21:11:30 -05005278 }
Jeff Mahoney0b246af2016-06-22 18:54:23 -04005279 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05005280
5281 btrfs_set_stack_chunk_length(chunk, chunk_size);
5282 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5283 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5284 btrfs_set_stack_chunk_type(chunk, map->type);
5285 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5286 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5287 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
Jeff Mahoney0b246af2016-06-22 18:54:23 -04005288 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
Yan Zheng2b820322008-11-17 21:11:30 -05005289 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5290
5291 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5292 key.type = BTRFS_CHUNK_ITEM_KEY;
5293 key.offset = chunk_offset;
5294
5295 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
Mark Fasheh4ed1d162011-08-10 12:32:10 -07005296 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5297 /*
5298 * TODO: Cleanup of inserted chunk root in case of
5299 * failure.
5300 */
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04005301 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
Yan Zheng2b820322008-11-17 21:11:30 -05005302 }
liubo1abe9b82011-03-24 11:18:59 +00005303
Josef Bacik6df9a952013-06-27 13:22:46 -04005304out:
Yan Zheng2b820322008-11-17 21:11:30 -05005305 kfree(chunk);
Josef Bacik6df9a952013-06-27 13:22:46 -04005306 free_extent_map(em);
Mark Fasheh4ed1d162011-08-10 12:32:10 -07005307 return ret;
Yan Zheng2b820322008-11-17 21:11:30 -05005308}
5309
David Sterba6f8e0fc2019-03-20 16:29:13 +01005310static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
Yan Zheng2b820322008-11-17 21:11:30 -05005311{
David Sterba6f8e0fc2019-03-20 16:29:13 +01005312 struct btrfs_fs_info *fs_info = trans->fs_info;
Yan Zheng2b820322008-11-17 21:11:30 -05005313 u64 alloc_profile;
Yan Zheng2b820322008-11-17 21:11:30 -05005314 int ret;
5315
Jeff Mahoney1b868262017-05-17 11:38:35 -04005316 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005317 ret = btrfs_alloc_chunk(trans, alloc_profile);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01005318 if (ret)
5319 return ret;
Yan Zheng2b820322008-11-17 21:11:30 -05005320
Jeff Mahoney1b868262017-05-17 11:38:35 -04005321 alloc_profile = btrfs_system_alloc_profile(fs_info);
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005322 ret = btrfs_alloc_chunk(trans, alloc_profile);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01005323 return ret;
Yan Zheng2b820322008-11-17 21:11:30 -05005324}
5325
Miao Xied20983b2014-07-03 18:22:13 +08005326static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5327{
David Sterbafc9a2ac2019-05-17 11:43:22 +02005328 const int index = btrfs_bg_flags_to_raid_index(map->type);
Miao Xied20983b2014-07-03 18:22:13 +08005329
David Sterbafc9a2ac2019-05-17 11:43:22 +02005330 return btrfs_raid_array[index].tolerated_failures;
Yan Zheng2b820322008-11-17 21:11:30 -05005331}
5332
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04005333int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
Yan Zheng2b820322008-11-17 21:11:30 -05005334{
5335 struct extent_map *em;
5336 struct map_lookup *map;
Yan Zheng2b820322008-11-17 21:11:30 -05005337 int readonly = 0;
Miao Xied20983b2014-07-03 18:22:13 +08005338 int miss_ndevs = 0;
Yan Zheng2b820322008-11-17 21:11:30 -05005339 int i;
5340
Omar Sandoval60ca8422018-05-16 16:34:31 -07005341 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
Liu Bo592d92e2017-03-14 13:33:55 -07005342 if (IS_ERR(em))
Yan Zheng2b820322008-11-17 21:11:30 -05005343 return 1;
5344
Jeff Mahoney95617d62015-06-03 10:55:48 -04005345 map = em->map_lookup;
Yan Zheng2b820322008-11-17 21:11:30 -05005346 for (i = 0; i < map->num_stripes; i++) {
Anand Jaine6e674b2017-12-04 12:54:54 +08005347 if (test_bit(BTRFS_DEV_STATE_MISSING,
5348 &map->stripes[i].dev->dev_state)) {
Miao Xied20983b2014-07-03 18:22:13 +08005349 miss_ndevs++;
5350 continue;
5351 }
Anand Jainebbede42017-12-04 12:54:52 +08005352 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5353 &map->stripes[i].dev->dev_state)) {
Yan Zheng2b820322008-11-17 21:11:30 -05005354 readonly = 1;
Miao Xied20983b2014-07-03 18:22:13 +08005355 goto end;
Yan Zheng2b820322008-11-17 21:11:30 -05005356 }
5357 }
Miao Xied20983b2014-07-03 18:22:13 +08005358
5359 /*
5360 * If the number of missing devices is larger than max errors,
5361 * we can not write the data into that chunk successfully, so
5362 * set it readonly.
5363 */
5364 if (miss_ndevs > btrfs_chunk_max_errors(map))
5365 readonly = 1;
5366end:
Yan Zheng2b820322008-11-17 21:11:30 -05005367 free_extent_map(em);
5368 return readonly;
Chris Mason0b86a832008-03-24 15:01:56 -04005369}
5370
David Sterbac8bf1b62019-05-17 11:43:17 +02005371void btrfs_mapping_tree_free(struct extent_map_tree *tree)
Chris Mason0b86a832008-03-24 15:01:56 -04005372{
5373 struct extent_map *em;
5374
Chris Masond3977122009-01-05 21:25:51 -05005375 while (1) {
David Sterbac8bf1b62019-05-17 11:43:17 +02005376 write_lock(&tree->lock);
5377 em = lookup_extent_mapping(tree, 0, (u64)-1);
Chris Mason0b86a832008-03-24 15:01:56 -04005378 if (em)
David Sterbac8bf1b62019-05-17 11:43:17 +02005379 remove_extent_mapping(tree, em);
5380 write_unlock(&tree->lock);
Chris Mason0b86a832008-03-24 15:01:56 -04005381 if (!em)
5382 break;
Chris Mason0b86a832008-03-24 15:01:56 -04005383 /* once for us */
5384 free_extent_map(em);
5385 /* once for the tree */
5386 free_extent_map(em);
5387 }
5388}
5389
Stefan Behrens5d964052012-11-05 14:59:07 +01005390int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
Chris Masonf1885912008-04-09 16:28:12 -04005391{
5392 struct extent_map *em;
5393 struct map_lookup *map;
Chris Masonf1885912008-04-09 16:28:12 -04005394 int ret;
5395
Omar Sandoval60ca8422018-05-16 16:34:31 -07005396 em = btrfs_get_chunk_map(fs_info, logical, len);
Liu Bo592d92e2017-03-14 13:33:55 -07005397 if (IS_ERR(em))
5398 /*
5399 * We could return errors for these cases, but that could get
5400 * ugly and we'd probably do the same thing which is just not do
5401 * anything else and exit, so return 1 so the callers don't try
5402 * to use other copies.
5403 */
Josef Bacikfb7669b2013-04-23 10:53:18 -04005404 return 1;
Josef Bacikfb7669b2013-04-23 10:53:18 -04005405
Jeff Mahoney95617d62015-06-03 10:55:48 -04005406 map = em->map_lookup;
David Sterbac7369b32019-05-31 15:39:31 +02005407 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
Chris Masonf1885912008-04-09 16:28:12 -04005408 ret = map->num_stripes;
Chris Mason321aecc2008-04-16 10:49:51 -04005409 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5410 ret = map->sub_stripes;
David Woodhouse53b381b2013-01-29 18:40:14 -05005411 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5412 ret = 2;
5413 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
Liu Bo8810f752018-01-02 13:36:41 -07005414 /*
5415 * There could be two corrupted data stripes, we need
5416 * to loop retry in order to rebuild the correct data.
Nikolay Borisove7e02092018-06-20 15:48:55 +03005417 *
Liu Bo8810f752018-01-02 13:36:41 -07005418 * Fail a stripe at a time on every retry except the
5419 * stripe under reconstruction.
5420 */
5421 ret = map->num_stripes;
Chris Masonf1885912008-04-09 16:28:12 -04005422 else
5423 ret = 1;
5424 free_extent_map(em);
Stefan Behrensad6d6202012-11-06 15:06:47 +01005425
David Sterbacb5583d2018-09-07 16:11:23 +02005426 down_read(&fs_info->dev_replace.rwsem);
Liu Bo6fad8232017-03-14 13:33:59 -07005427 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5428 fs_info->dev_replace.tgtdev)
Stefan Behrensad6d6202012-11-06 15:06:47 +01005429 ret++;
David Sterbacb5583d2018-09-07 16:11:23 +02005430 up_read(&fs_info->dev_replace.rwsem);
Stefan Behrensad6d6202012-11-06 15:06:47 +01005431
Chris Masonf1885912008-04-09 16:28:12 -04005432 return ret;
5433}
5434
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04005435unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
David Woodhouse53b381b2013-01-29 18:40:14 -05005436 u64 logical)
5437{
5438 struct extent_map *em;
5439 struct map_lookup *map;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04005440 unsigned long len = fs_info->sectorsize;
David Woodhouse53b381b2013-01-29 18:40:14 -05005441
Omar Sandoval60ca8422018-05-16 16:34:31 -07005442 em = btrfs_get_chunk_map(fs_info, logical, len);
David Woodhouse53b381b2013-01-29 18:40:14 -05005443
Nikolay Borisov69f03f12017-07-11 16:55:51 +03005444 if (!WARN_ON(IS_ERR(em))) {
5445 map = em->map_lookup;
5446 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5447 len = map->stripe_len * nr_data_stripes(map);
5448 free_extent_map(em);
5449 }
David Woodhouse53b381b2013-01-29 18:40:14 -05005450 return len;
5451}
5452
Nikolay Borisove4ff5fb2017-07-19 10:48:42 +03005453int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
David Woodhouse53b381b2013-01-29 18:40:14 -05005454{
5455 struct extent_map *em;
5456 struct map_lookup *map;
David Woodhouse53b381b2013-01-29 18:40:14 -05005457 int ret = 0;
5458
Omar Sandoval60ca8422018-05-16 16:34:31 -07005459 em = btrfs_get_chunk_map(fs_info, logical, len);
David Woodhouse53b381b2013-01-29 18:40:14 -05005460
Nikolay Borisov69f03f12017-07-11 16:55:51 +03005461 if(!WARN_ON(IS_ERR(em))) {
5462 map = em->map_lookup;
5463 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5464 ret = 1;
5465 free_extent_map(em);
5466 }
David Woodhouse53b381b2013-01-29 18:40:14 -05005467 return ret;
5468}
5469
Stefan Behrens30d98612012-11-06 14:52:18 +01005470static int find_live_mirror(struct btrfs_fs_info *fs_info,
Anand Jain99f92a72018-03-14 16:29:12 +08005471 struct map_lookup *map, int first,
Anand Jain8ba0ae72018-03-14 16:29:13 +08005472 int dev_replace_is_ongoing)
Chris Masondfe25022008-05-13 13:46:40 -04005473{
5474 int i;
Anand Jain99f92a72018-03-14 16:29:12 +08005475 int num_stripes;
Anand Jain8ba0ae72018-03-14 16:29:13 +08005476 int preferred_mirror;
Stefan Behrens30d98612012-11-06 14:52:18 +01005477 int tolerance;
5478 struct btrfs_device *srcdev;
5479
Anand Jain99f92a72018-03-14 16:29:12 +08005480 ASSERT((map->type &
David Sterbac7369b32019-05-31 15:39:31 +02005481 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
Anand Jain99f92a72018-03-14 16:29:12 +08005482
5483 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5484 num_stripes = map->sub_stripes;
5485 else
5486 num_stripes = map->num_stripes;
5487
Anand Jain8ba0ae72018-03-14 16:29:13 +08005488 preferred_mirror = first + current->pid % num_stripes;
5489
Stefan Behrens30d98612012-11-06 14:52:18 +01005490 if (dev_replace_is_ongoing &&
5491 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5492 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5493 srcdev = fs_info->dev_replace.srcdev;
5494 else
5495 srcdev = NULL;
5496
5497 /*
5498 * try to avoid the drive that is the source drive for a
5499 * dev-replace procedure, only choose it if no other non-missing
5500 * mirror is available
5501 */
5502 for (tolerance = 0; tolerance < 2; tolerance++) {
Anand Jain8ba0ae72018-03-14 16:29:13 +08005503 if (map->stripes[preferred_mirror].dev->bdev &&
5504 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5505 return preferred_mirror;
Anand Jain99f92a72018-03-14 16:29:12 +08005506 for (i = first; i < first + num_stripes; i++) {
Stefan Behrens30d98612012-11-06 14:52:18 +01005507 if (map->stripes[i].dev->bdev &&
5508 (tolerance || map->stripes[i].dev != srcdev))
5509 return i;
5510 }
Chris Masondfe25022008-05-13 13:46:40 -04005511 }
Stefan Behrens30d98612012-11-06 14:52:18 +01005512
Chris Masondfe25022008-05-13 13:46:40 -04005513 /* we couldn't find one that doesn't fail. Just return something
5514 * and the io error handling code will clean up eventually
5515 */
Anand Jain8ba0ae72018-03-14 16:29:13 +08005516 return preferred_mirror;
Chris Masondfe25022008-05-13 13:46:40 -04005517}
5518
David Woodhouse53b381b2013-01-29 18:40:14 -05005519/* Bubble-sort the stripe set to put the parity/syndrome stripes last */
Zhao Lei8e5cfb52015-01-20 15:11:33 +08005520static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
David Woodhouse53b381b2013-01-29 18:40:14 -05005521{
David Woodhouse53b381b2013-01-29 18:40:14 -05005522 int i;
David Woodhouse53b381b2013-01-29 18:40:14 -05005523 int again = 1;
5524
5525 while (again) {
5526 again = 0;
Zhao Leicc7539e2015-01-20 15:11:32 +08005527 for (i = 0; i < num_stripes - 1; i++) {
David Sterbaeeb6f172019-11-28 15:31:17 +01005528 /* Swap if parity is on a smaller index */
5529 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5530 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5531 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
David Woodhouse53b381b2013-01-29 18:40:14 -05005532 again = 1;
5533 }
5534 }
5535 }
5536}
5537
Zhao Lei6e9606d2015-01-20 15:11:34 +08005538static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5539{
5540 struct btrfs_bio *bbio = kzalloc(
Chris Masone57cf212015-02-19 17:51:39 -08005541 /* the size of the btrfs_bio */
Zhao Lei6e9606d2015-01-20 15:11:34 +08005542 sizeof(struct btrfs_bio) +
Chris Masone57cf212015-02-19 17:51:39 -08005543 /* plus the variable array for the stripes */
Zhao Lei6e9606d2015-01-20 15:11:34 +08005544 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
Chris Masone57cf212015-02-19 17:51:39 -08005545 /* plus the variable array for the tgt dev */
Zhao Lei6e9606d2015-01-20 15:11:34 +08005546 sizeof(int) * (real_stripes) +
Chris Masone57cf212015-02-19 17:51:39 -08005547 /*
5548 * plus the raid_map, which includes both the tgt dev
5549 * and the stripes
5550 */
5551 sizeof(u64) * (total_stripes),
Michal Hocko277fb5f2015-08-19 14:17:41 +02005552 GFP_NOFS|__GFP_NOFAIL);
Zhao Lei6e9606d2015-01-20 15:11:34 +08005553
5554 atomic_set(&bbio->error, 0);
Elena Reshetova140475a2017-03-03 10:55:10 +02005555 refcount_set(&bbio->refs, 1);
Zhao Lei6e9606d2015-01-20 15:11:34 +08005556
Nikolay Borisov608769a2020-07-02 16:46:41 +03005557 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5558 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5559
Zhao Lei6e9606d2015-01-20 15:11:34 +08005560 return bbio;
5561}
5562
5563void btrfs_get_bbio(struct btrfs_bio *bbio)
5564{
Elena Reshetova140475a2017-03-03 10:55:10 +02005565 WARN_ON(!refcount_read(&bbio->refs));
5566 refcount_inc(&bbio->refs);
Zhao Lei6e9606d2015-01-20 15:11:34 +08005567}
5568
5569void btrfs_put_bbio(struct btrfs_bio *bbio)
5570{
5571 if (!bbio)
5572 return;
Elena Reshetova140475a2017-03-03 10:55:10 +02005573 if (refcount_dec_and_test(&bbio->refs))
Zhao Lei6e9606d2015-01-20 15:11:34 +08005574 kfree(bbio);
5575}
5576
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005577/* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5578/*
5579 * Please note that, discard won't be sent to target device of device
5580 * replace.
5581 */
5582static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
Qu Wenruo6b7faad2019-10-23 21:57:27 +08005583 u64 logical, u64 *length_ret,
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005584 struct btrfs_bio **bbio_ret)
5585{
5586 struct extent_map *em;
5587 struct map_lookup *map;
5588 struct btrfs_bio *bbio;
Qu Wenruo6b7faad2019-10-23 21:57:27 +08005589 u64 length = *length_ret;
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005590 u64 offset;
5591 u64 stripe_nr;
5592 u64 stripe_nr_end;
5593 u64 stripe_end_offset;
5594 u64 stripe_cnt;
5595 u64 stripe_len;
5596 u64 stripe_offset;
5597 u64 num_stripes;
5598 u32 stripe_index;
5599 u32 factor = 0;
5600 u32 sub_stripes = 0;
5601 u64 stripes_per_dev = 0;
5602 u32 remaining_stripes = 0;
5603 u32 last_stripe = 0;
5604 int ret = 0;
5605 int i;
5606
5607 /* discard always return a bbio */
5608 ASSERT(bbio_ret);
5609
Omar Sandoval60ca8422018-05-16 16:34:31 -07005610 em = btrfs_get_chunk_map(fs_info, logical, length);
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005611 if (IS_ERR(em))
5612 return PTR_ERR(em);
5613
5614 map = em->map_lookup;
5615 /* we don't discard raid56 yet */
5616 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5617 ret = -EOPNOTSUPP;
5618 goto out;
5619 }
5620
5621 offset = logical - em->start;
Qu Wenruo2d974612019-10-23 21:57:26 +08005622 length = min_t(u64, em->start + em->len - logical, length);
Qu Wenruo6b7faad2019-10-23 21:57:27 +08005623 *length_ret = length;
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005624
5625 stripe_len = map->stripe_len;
5626 /*
5627 * stripe_nr counts the total number of stripes we have to stride
5628 * to get to this block
5629 */
5630 stripe_nr = div64_u64(offset, stripe_len);
5631
5632 /* stripe_offset is the offset of this block in its stripe */
5633 stripe_offset = offset - stripe_nr * stripe_len;
5634
5635 stripe_nr_end = round_up(offset + length, map->stripe_len);
Liu Bo42c61ab2017-04-03 13:45:24 -07005636 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005637 stripe_cnt = stripe_nr_end - stripe_nr;
5638 stripe_end_offset = stripe_nr_end * map->stripe_len -
5639 (offset + length);
5640 /*
5641 * after this, stripe_nr is the number of stripes on this
5642 * device we have to walk to find the data, and stripe_index is
5643 * the number of our device in the stripe array
5644 */
5645 num_stripes = 1;
5646 stripe_index = 0;
5647 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5648 BTRFS_BLOCK_GROUP_RAID10)) {
5649 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5650 sub_stripes = 1;
5651 else
5652 sub_stripes = map->sub_stripes;
5653
5654 factor = map->num_stripes / sub_stripes;
5655 num_stripes = min_t(u64, map->num_stripes,
5656 sub_stripes * stripe_cnt);
5657 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5658 stripe_index *= sub_stripes;
5659 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5660 &remaining_stripes);
5661 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5662 last_stripe *= sub_stripes;
David Sterbac7369b32019-05-31 15:39:31 +02005663 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005664 BTRFS_BLOCK_GROUP_DUP)) {
5665 num_stripes = map->num_stripes;
5666 } else {
5667 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5668 &stripe_index);
5669 }
5670
5671 bbio = alloc_btrfs_bio(num_stripes, 0);
5672 if (!bbio) {
5673 ret = -ENOMEM;
5674 goto out;
5675 }
5676
5677 for (i = 0; i < num_stripes; i++) {
5678 bbio->stripes[i].physical =
5679 map->stripes[stripe_index].physical +
5680 stripe_offset + stripe_nr * map->stripe_len;
5681 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5682
5683 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5684 BTRFS_BLOCK_GROUP_RAID10)) {
5685 bbio->stripes[i].length = stripes_per_dev *
5686 map->stripe_len;
5687
5688 if (i / sub_stripes < remaining_stripes)
5689 bbio->stripes[i].length +=
5690 map->stripe_len;
5691
5692 /*
5693 * Special for the first stripe and
5694 * the last stripe:
5695 *
5696 * |-------|...|-------|
5697 * |----------|
5698 * off end_off
5699 */
5700 if (i < sub_stripes)
5701 bbio->stripes[i].length -=
5702 stripe_offset;
5703
5704 if (stripe_index >= last_stripe &&
5705 stripe_index <= (last_stripe +
5706 sub_stripes - 1))
5707 bbio->stripes[i].length -=
5708 stripe_end_offset;
5709
5710 if (i == sub_stripes - 1)
5711 stripe_offset = 0;
5712 } else {
5713 bbio->stripes[i].length = length;
5714 }
5715
5716 stripe_index++;
5717 if (stripe_index == map->num_stripes) {
5718 stripe_index = 0;
5719 stripe_nr++;
5720 }
5721 }
5722
5723 *bbio_ret = bbio;
5724 bbio->map_type = map->type;
5725 bbio->num_stripes = num_stripes;
5726out:
5727 free_extent_map(em);
5728 return ret;
5729}
5730
Liu Bo5ab56092017-03-14 13:33:57 -07005731/*
5732 * In dev-replace case, for repair case (that's the only case where the mirror
5733 * is selected explicitly when calling btrfs_map_block), blocks left of the
5734 * left cursor can also be read from the target drive.
5735 *
5736 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5737 * array of stripes.
5738 * For READ, it also needs to be supported using the same mirror number.
5739 *
5740 * If the requested block is not left of the left cursor, EIO is returned. This
5741 * can happen because btrfs_num_copies() returns one more in the dev-replace
5742 * case.
5743 */
5744static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5745 u64 logical, u64 length,
5746 u64 srcdev_devid, int *mirror_num,
5747 u64 *physical)
5748{
5749 struct btrfs_bio *bbio = NULL;
5750 int num_stripes;
5751 int index_srcdev = 0;
5752 int found = 0;
5753 u64 physical_of_found = 0;
5754 int i;
5755 int ret = 0;
5756
5757 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5758 logical, &length, &bbio, 0, 0);
5759 if (ret) {
5760 ASSERT(bbio == NULL);
5761 return ret;
5762 }
5763
5764 num_stripes = bbio->num_stripes;
5765 if (*mirror_num > num_stripes) {
5766 /*
5767 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5768 * that means that the requested area is not left of the left
5769 * cursor
5770 */
5771 btrfs_put_bbio(bbio);
5772 return -EIO;
5773 }
5774
5775 /*
5776 * process the rest of the function using the mirror_num of the source
5777 * drive. Therefore look it up first. At the end, patch the device
5778 * pointer to the one of the target drive.
5779 */
5780 for (i = 0; i < num_stripes; i++) {
5781 if (bbio->stripes[i].dev->devid != srcdev_devid)
5782 continue;
5783
5784 /*
5785 * In case of DUP, in order to keep it simple, only add the
5786 * mirror with the lowest physical address
5787 */
5788 if (found &&
5789 physical_of_found <= bbio->stripes[i].physical)
5790 continue;
5791
5792 index_srcdev = i;
5793 found = 1;
5794 physical_of_found = bbio->stripes[i].physical;
5795 }
5796
5797 btrfs_put_bbio(bbio);
5798
5799 ASSERT(found);
5800 if (!found)
5801 return -EIO;
5802
5803 *mirror_num = index_srcdev + 1;
5804 *physical = physical_of_found;
5805 return ret;
5806}
5807
Liu Bo73c0f222017-03-14 13:33:58 -07005808static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5809 struct btrfs_bio **bbio_ret,
5810 struct btrfs_dev_replace *dev_replace,
5811 int *num_stripes_ret, int *max_errors_ret)
5812{
5813 struct btrfs_bio *bbio = *bbio_ret;
5814 u64 srcdev_devid = dev_replace->srcdev->devid;
5815 int tgtdev_indexes = 0;
5816 int num_stripes = *num_stripes_ret;
5817 int max_errors = *max_errors_ret;
5818 int i;
5819
5820 if (op == BTRFS_MAP_WRITE) {
5821 int index_where_to_add;
5822
5823 /*
5824 * duplicate the write operations while the dev replace
5825 * procedure is running. Since the copying of the old disk to
5826 * the new disk takes place at run time while the filesystem is
5827 * mounted writable, the regular write operations to the old
5828 * disk have to be duplicated to go to the new disk as well.
5829 *
5830 * Note that device->missing is handled by the caller, and that
5831 * the write to the old disk is already set up in the stripes
5832 * array.
5833 */
5834 index_where_to_add = num_stripes;
5835 for (i = 0; i < num_stripes; i++) {
5836 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5837 /* write to new disk, too */
5838 struct btrfs_bio_stripe *new =
5839 bbio->stripes + index_where_to_add;
5840 struct btrfs_bio_stripe *old =
5841 bbio->stripes + i;
5842
5843 new->physical = old->physical;
5844 new->length = old->length;
5845 new->dev = dev_replace->tgtdev;
5846 bbio->tgtdev_map[i] = index_where_to_add;
5847 index_where_to_add++;
5848 max_errors++;
5849 tgtdev_indexes++;
5850 }
5851 }
5852 num_stripes = index_where_to_add;
5853 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5854 int index_srcdev = 0;
5855 int found = 0;
5856 u64 physical_of_found = 0;
5857
5858 /*
5859 * During the dev-replace procedure, the target drive can also
5860 * be used to read data in case it is needed to repair a corrupt
5861 * block elsewhere. This is possible if the requested area is
5862 * left of the left cursor. In this area, the target drive is a
5863 * full copy of the source drive.
5864 */
5865 for (i = 0; i < num_stripes; i++) {
5866 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5867 /*
5868 * In case of DUP, in order to keep it simple,
5869 * only add the mirror with the lowest physical
5870 * address
5871 */
5872 if (found &&
5873 physical_of_found <=
5874 bbio->stripes[i].physical)
5875 continue;
5876 index_srcdev = i;
5877 found = 1;
5878 physical_of_found = bbio->stripes[i].physical;
5879 }
5880 }
5881 if (found) {
5882 struct btrfs_bio_stripe *tgtdev_stripe =
5883 bbio->stripes + num_stripes;
5884
5885 tgtdev_stripe->physical = physical_of_found;
5886 tgtdev_stripe->length =
5887 bbio->stripes[index_srcdev].length;
5888 tgtdev_stripe->dev = dev_replace->tgtdev;
5889 bbio->tgtdev_map[index_srcdev] = num_stripes;
5890
5891 tgtdev_indexes++;
5892 num_stripes++;
5893 }
5894 }
5895
5896 *num_stripes_ret = num_stripes;
5897 *max_errors_ret = max_errors;
5898 bbio->num_tgtdevs = tgtdev_indexes;
5899 *bbio_ret = bbio;
5900}
5901
Liu Bo2b19a1f2017-03-14 13:34:00 -07005902static bool need_full_stripe(enum btrfs_map_op op)
5903{
5904 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5905}
5906
Nikolay Borisov5f141122019-06-03 12:05:03 +03005907/*
5908 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
5909 * tuple. This information is used to calculate how big a
5910 * particular bio can get before it straddles a stripe.
5911 *
5912 * @fs_info - the filesystem
5913 * @logical - address that we want to figure out the geometry of
5914 * @len - the length of IO we are going to perform, starting at @logical
5915 * @op - type of operation - write or read
5916 * @io_geom - pointer used to return values
5917 *
5918 * Returns < 0 in case a chunk for the given logical address cannot be found,
5919 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
5920 */
5921int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
Nikolay Borisov89b798a2019-06-03 12:05:05 +03005922 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
Nikolay Borisov5f141122019-06-03 12:05:03 +03005923{
5924 struct extent_map *em;
5925 struct map_lookup *map;
5926 u64 offset;
5927 u64 stripe_offset;
5928 u64 stripe_nr;
5929 u64 stripe_len;
5930 u64 raid56_full_stripe_start = (u64)-1;
5931 int data_stripes;
Johannes Thumshirn373c3b82019-07-15 15:16:12 +02005932 int ret = 0;
Nikolay Borisov5f141122019-06-03 12:05:03 +03005933
5934 ASSERT(op != BTRFS_MAP_DISCARD);
5935
5936 em = btrfs_get_chunk_map(fs_info, logical, len);
5937 if (IS_ERR(em))
5938 return PTR_ERR(em);
5939
5940 map = em->map_lookup;
5941 /* Offset of this logical address in the chunk */
5942 offset = logical - em->start;
5943 /* Len of a stripe in a chunk */
5944 stripe_len = map->stripe_len;
5945 /* Stripe wher this block falls in */
5946 stripe_nr = div64_u64(offset, stripe_len);
5947 /* Offset of stripe in the chunk */
5948 stripe_offset = stripe_nr * stripe_len;
5949 if (offset < stripe_offset) {
5950 btrfs_crit(fs_info,
5951"stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
5952 stripe_offset, offset, em->start, logical, stripe_len);
Johannes Thumshirn373c3b82019-07-15 15:16:12 +02005953 ret = -EINVAL;
5954 goto out;
Nikolay Borisov5f141122019-06-03 12:05:03 +03005955 }
5956
5957 /* stripe_offset is the offset of this block in its stripe */
5958 stripe_offset = offset - stripe_offset;
5959 data_stripes = nr_data_stripes(map);
5960
5961 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5962 u64 max_len = stripe_len - stripe_offset;
5963
5964 /*
5965 * In case of raid56, we need to know the stripe aligned start
5966 */
5967 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5968 unsigned long full_stripe_len = stripe_len * data_stripes;
5969 raid56_full_stripe_start = offset;
5970
5971 /*
5972 * Allow a write of a full stripe, but make sure we
5973 * don't allow straddling of stripes
5974 */
5975 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5976 full_stripe_len);
5977 raid56_full_stripe_start *= full_stripe_len;
5978
5979 /*
5980 * For writes to RAID[56], allow a full stripeset across
5981 * all disks. For other RAID types and for RAID[56]
5982 * reads, just allow a single stripe (on a single disk).
5983 */
5984 if (op == BTRFS_MAP_WRITE) {
5985 max_len = stripe_len * data_stripes -
5986 (offset - raid56_full_stripe_start);
5987 }
5988 }
5989 len = min_t(u64, em->len - offset, max_len);
5990 } else {
5991 len = em->len - offset;
5992 }
5993
5994 io_geom->len = len;
5995 io_geom->offset = offset;
5996 io_geom->stripe_len = stripe_len;
5997 io_geom->stripe_nr = stripe_nr;
5998 io_geom->stripe_offset = stripe_offset;
5999 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6000
Johannes Thumshirn373c3b82019-07-15 15:16:12 +02006001out:
6002 /* once for us */
6003 free_extent_map(em);
6004 return ret;
Nikolay Borisov5f141122019-06-03 12:05:03 +03006005}
6006
Christoph Hellwigcf8cddd2016-10-27 09:27:36 +02006007static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6008 enum btrfs_map_op op,
Chris Masonf2d8d742008-04-21 10:03:05 -04006009 u64 logical, u64 *length,
Jan Schmidta1d3c472011-08-04 17:15:33 +02006010 struct btrfs_bio **bbio_ret,
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006011 int mirror_num, int need_raid_map)
Chris Mason0b86a832008-03-24 15:01:56 -04006012{
6013 struct extent_map *em;
6014 struct map_lookup *map;
Chris Mason593060d2008-03-25 16:50:33 -04006015 u64 stripe_offset;
6016 u64 stripe_nr;
David Woodhouse53b381b2013-01-29 18:40:14 -05006017 u64 stripe_len;
David Sterba9d644a62015-02-20 18:42:11 +01006018 u32 stripe_index;
David Sterbacff82672019-05-17 11:43:45 +02006019 int data_stripes;
Chris Masoncea9e442008-04-09 16:28:12 -04006020 int i;
Li Zefande11cc12011-12-01 12:55:47 +08006021 int ret = 0;
Chris Masonf2d8d742008-04-21 10:03:05 -04006022 int num_stripes;
Chris Masona236aed2008-04-29 09:38:00 -04006023 int max_errors = 0;
Miao Xie2c8cdd62014-11-14 16:06:25 +08006024 int tgtdev_indexes = 0;
Jan Schmidta1d3c472011-08-04 17:15:33 +02006025 struct btrfs_bio *bbio = NULL;
Stefan Behrens472262f2012-11-06 14:43:46 +01006026 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6027 int dev_replace_is_ongoing = 0;
6028 int num_alloc_stripes;
Stefan Behrensad6d6202012-11-06 15:06:47 +01006029 int patch_the_first_stripe_for_dev_replace = 0;
6030 u64 physical_to_patch_in_first_stripe = 0;
David Woodhouse53b381b2013-01-29 18:40:14 -05006031 u64 raid56_full_stripe_start = (u64)-1;
Nikolay Borisov89b798a2019-06-03 12:05:05 +03006032 struct btrfs_io_geometry geom;
6033
6034 ASSERT(bbio_ret);
David Sterba75fb2e92018-08-03 00:36:29 +02006035 ASSERT(op != BTRFS_MAP_DISCARD);
Liu Bo0b3d4cd2017-03-14 13:33:56 -07006036
Nikolay Borisov89b798a2019-06-03 12:05:05 +03006037 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
6038 if (ret < 0)
6039 return ret;
6040
Omar Sandoval60ca8422018-05-16 16:34:31 -07006041 em = btrfs_get_chunk_map(fs_info, logical, *length);
Dan Carpenterf1136982019-08-09 17:07:39 +03006042 ASSERT(!IS_ERR(em));
Jeff Mahoney95617d62015-06-03 10:55:48 -04006043 map = em->map_lookup;
Chris Mason593060d2008-03-25 16:50:33 -04006044
Nikolay Borisov89b798a2019-06-03 12:05:05 +03006045 *length = geom.len;
Nikolay Borisov89b798a2019-06-03 12:05:05 +03006046 stripe_len = geom.stripe_len;
6047 stripe_nr = geom.stripe_nr;
6048 stripe_offset = geom.stripe_offset;
6049 raid56_full_stripe_start = geom.raid56_stripe_offset;
David Sterbacff82672019-05-17 11:43:45 +02006050 data_stripes = nr_data_stripes(map);
Chris Mason593060d2008-03-25 16:50:33 -04006051
David Sterbacb5583d2018-09-07 16:11:23 +02006052 down_read(&dev_replace->rwsem);
Stefan Behrens472262f2012-11-06 14:43:46 +01006053 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
David Sterba53176dd2018-04-05 01:41:06 +02006054 /*
6055 * Hold the semaphore for read during the whole operation, write is
6056 * requested at commit time but must wait.
6057 */
Stefan Behrens472262f2012-11-06 14:43:46 +01006058 if (!dev_replace_is_ongoing)
David Sterbacb5583d2018-09-07 16:11:23 +02006059 up_read(&dev_replace->rwsem);
Stefan Behrens472262f2012-11-06 14:43:46 +01006060
Stefan Behrensad6d6202012-11-06 15:06:47 +01006061 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
Liu Bo2b19a1f2017-03-14 13:34:00 -07006062 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
Liu Bo5ab56092017-03-14 13:33:57 -07006063 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6064 dev_replace->srcdev->devid,
6065 &mirror_num,
6066 &physical_to_patch_in_first_stripe);
6067 if (ret)
Stefan Behrensad6d6202012-11-06 15:06:47 +01006068 goto out;
Liu Bo5ab56092017-03-14 13:33:57 -07006069 else
6070 patch_the_first_stripe_for_dev_replace = 1;
Stefan Behrensad6d6202012-11-06 15:06:47 +01006071 } else if (mirror_num > map->num_stripes) {
6072 mirror_num = 0;
6073 }
6074
Chris Masonf2d8d742008-04-21 10:03:05 -04006075 num_stripes = 1;
Chris Masoncea9e442008-04-09 16:28:12 -04006076 stripe_index = 0;
Li Dongyangfce3bb92011-03-24 10:24:26 +00006077 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
David Sterba47c57132015-02-20 18:43:47 +01006078 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6079 &stripe_index);
Anand Jainde483732017-10-12 16:43:00 +08006080 if (!need_full_stripe(op))
Miao Xie28e1cc72014-09-12 18:44:02 +08006081 mirror_num = 1;
David Sterbac7369b32019-05-31 15:39:31 +02006082 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
Anand Jainde483732017-10-12 16:43:00 +08006083 if (need_full_stripe(op))
Chris Masonf2d8d742008-04-21 10:03:05 -04006084 num_stripes = map->num_stripes;
Chris Mason2fff7342008-04-29 14:12:09 -04006085 else if (mirror_num)
Chris Masonf1885912008-04-09 16:28:12 -04006086 stripe_index = mirror_num - 1;
Chris Masondfe25022008-05-13 13:46:40 -04006087 else {
Stefan Behrens30d98612012-11-06 14:52:18 +01006088 stripe_index = find_live_mirror(fs_info, map, 0,
Stefan Behrens30d98612012-11-06 14:52:18 +01006089 dev_replace_is_ongoing);
Jan Schmidta1d3c472011-08-04 17:15:33 +02006090 mirror_num = stripe_index + 1;
Chris Masondfe25022008-05-13 13:46:40 -04006091 }
Chris Mason2fff7342008-04-29 14:12:09 -04006092
Chris Mason611f0e02008-04-03 16:29:03 -04006093 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
Anand Jainde483732017-10-12 16:43:00 +08006094 if (need_full_stripe(op)) {
Chris Masonf2d8d742008-04-21 10:03:05 -04006095 num_stripes = map->num_stripes;
Jan Schmidta1d3c472011-08-04 17:15:33 +02006096 } else if (mirror_num) {
Chris Masonf1885912008-04-09 16:28:12 -04006097 stripe_index = mirror_num - 1;
Jan Schmidta1d3c472011-08-04 17:15:33 +02006098 } else {
6099 mirror_num = 1;
6100 }
Chris Mason2fff7342008-04-29 14:12:09 -04006101
Chris Mason321aecc2008-04-16 10:49:51 -04006102 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
David Sterba9d644a62015-02-20 18:42:11 +01006103 u32 factor = map->num_stripes / map->sub_stripes;
Chris Mason321aecc2008-04-16 10:49:51 -04006104
David Sterba47c57132015-02-20 18:43:47 +01006105 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
Chris Mason321aecc2008-04-16 10:49:51 -04006106 stripe_index *= map->sub_stripes;
6107
Anand Jainde483732017-10-12 16:43:00 +08006108 if (need_full_stripe(op))
Chris Masonf2d8d742008-04-21 10:03:05 -04006109 num_stripes = map->sub_stripes;
Chris Mason321aecc2008-04-16 10:49:51 -04006110 else if (mirror_num)
6111 stripe_index += mirror_num - 1;
Chris Masondfe25022008-05-13 13:46:40 -04006112 else {
Jan Schmidt3e743172012-04-27 12:41:45 -04006113 int old_stripe_index = stripe_index;
Stefan Behrens30d98612012-11-06 14:52:18 +01006114 stripe_index = find_live_mirror(fs_info, map,
6115 stripe_index,
Stefan Behrens30d98612012-11-06 14:52:18 +01006116 dev_replace_is_ongoing);
Jan Schmidt3e743172012-04-27 12:41:45 -04006117 mirror_num = stripe_index - old_stripe_index + 1;
Chris Masondfe25022008-05-13 13:46:40 -04006118 }
David Woodhouse53b381b2013-01-29 18:40:14 -05006119
Zhao Leiffe2d202015-01-20 15:11:44 +08006120 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
Anand Jainde483732017-10-12 16:43:00 +08006121 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
David Woodhouse53b381b2013-01-29 18:40:14 -05006122 /* push stripe_nr back to the start of the full stripe */
Liu Bo42c61ab2017-04-03 13:45:24 -07006123 stripe_nr = div64_u64(raid56_full_stripe_start,
David Sterbacff82672019-05-17 11:43:45 +02006124 stripe_len * data_stripes);
David Woodhouse53b381b2013-01-29 18:40:14 -05006125
6126 /* RAID[56] write or recovery. Return all stripes */
6127 num_stripes = map->num_stripes;
6128 max_errors = nr_parity_stripes(map);
6129
David Woodhouse53b381b2013-01-29 18:40:14 -05006130 *length = map->stripe_len;
6131 stripe_index = 0;
6132 stripe_offset = 0;
6133 } else {
6134 /*
6135 * Mirror #0 or #1 means the original data block.
6136 * Mirror #2 is RAID5 parity block.
6137 * Mirror #3 is RAID6 Q block.
6138 */
David Sterba47c57132015-02-20 18:43:47 +01006139 stripe_nr = div_u64_rem(stripe_nr,
David Sterbacff82672019-05-17 11:43:45 +02006140 data_stripes, &stripe_index);
David Woodhouse53b381b2013-01-29 18:40:14 -05006141 if (mirror_num > 1)
David Sterbacff82672019-05-17 11:43:45 +02006142 stripe_index = data_stripes + mirror_num - 2;
David Woodhouse53b381b2013-01-29 18:40:14 -05006143
6144 /* We distribute the parity blocks across stripes */
David Sterba47c57132015-02-20 18:43:47 +01006145 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6146 &stripe_index);
Anand Jainde483732017-10-12 16:43:00 +08006147 if (!need_full_stripe(op) && mirror_num <= 1)
Miao Xie28e1cc72014-09-12 18:44:02 +08006148 mirror_num = 1;
David Woodhouse53b381b2013-01-29 18:40:14 -05006149 }
Chris Mason8790d502008-04-03 16:29:03 -04006150 } else {
6151 /*
David Sterba47c57132015-02-20 18:43:47 +01006152 * after this, stripe_nr is the number of stripes on this
6153 * device we have to walk to find the data, and stripe_index is
6154 * the number of our device in the stripe array
Chris Mason8790d502008-04-03 16:29:03 -04006155 */
David Sterba47c57132015-02-20 18:43:47 +01006156 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6157 &stripe_index);
Jan Schmidta1d3c472011-08-04 17:15:33 +02006158 mirror_num = stripe_index + 1;
Chris Mason8790d502008-04-03 16:29:03 -04006159 }
Josef Bacike042d1e2016-04-12 12:54:40 -04006160 if (stripe_index >= map->num_stripes) {
Jeff Mahoney5d163e02016-09-20 10:05:00 -04006161 btrfs_crit(fs_info,
6162 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
Josef Bacike042d1e2016-04-12 12:54:40 -04006163 stripe_index, map->num_stripes);
6164 ret = -EINVAL;
6165 goto out;
6166 }
Chris Mason593060d2008-03-25 16:50:33 -04006167
Stefan Behrens472262f2012-11-06 14:43:46 +01006168 num_alloc_stripes = num_stripes;
Liu Bo6fad8232017-03-14 13:33:59 -07006169 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
Liu Bo0b3d4cd2017-03-14 13:33:56 -07006170 if (op == BTRFS_MAP_WRITE)
Stefan Behrensad6d6202012-11-06 15:06:47 +01006171 num_alloc_stripes <<= 1;
Christoph Hellwigcf8cddd2016-10-27 09:27:36 +02006172 if (op == BTRFS_MAP_GET_READ_MIRRORS)
Stefan Behrensad6d6202012-11-06 15:06:47 +01006173 num_alloc_stripes++;
Miao Xie2c8cdd62014-11-14 16:06:25 +08006174 tgtdev_indexes = num_stripes;
Stefan Behrensad6d6202012-11-06 15:06:47 +01006175 }
Miao Xie2c8cdd62014-11-14 16:06:25 +08006176
Zhao Lei6e9606d2015-01-20 15:11:34 +08006177 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
Li Zefande11cc12011-12-01 12:55:47 +08006178 if (!bbio) {
6179 ret = -ENOMEM;
6180 goto out;
6181 }
Nikolay Borisov608769a2020-07-02 16:46:41 +03006182
6183 for (i = 0; i < num_stripes; i++) {
6184 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6185 stripe_offset + stripe_nr * map->stripe_len;
6186 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6187 stripe_index++;
6188 }
Li Zefande11cc12011-12-01 12:55:47 +08006189
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006190 /* build raid_map */
Liu Bo2b19a1f2017-03-14 13:34:00 -07006191 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6192 (need_full_stripe(op) || mirror_num > 1)) {
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006193 u64 tmp;
David Sterba9d644a62015-02-20 18:42:11 +01006194 unsigned rot;
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006195
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006196 /* Work out the disk rotation on this stripe-set */
David Sterba47c57132015-02-20 18:43:47 +01006197 div_u64_rem(stripe_nr, num_stripes, &rot);
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006198
6199 /* Fill in the logical address of each stripe */
David Sterbacff82672019-05-17 11:43:45 +02006200 tmp = stripe_nr * data_stripes;
6201 for (i = 0; i < data_stripes; i++)
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006202 bbio->raid_map[(i+rot) % num_stripes] =
6203 em->start + (tmp + i) * map->stripe_len;
6204
6205 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6206 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6207 bbio->raid_map[(i+rot+1) % num_stripes] =
6208 RAID6_Q_STRIPE;
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006209
Nikolay Borisov608769a2020-07-02 16:46:41 +03006210 sort_parity_stripes(bbio, num_stripes);
Chris Mason593060d2008-03-25 16:50:33 -04006211 }
Li Zefande11cc12011-12-01 12:55:47 +08006212
Liu Bo2b19a1f2017-03-14 13:34:00 -07006213 if (need_full_stripe(op))
Miao Xied20983b2014-07-03 18:22:13 +08006214 max_errors = btrfs_chunk_max_errors(map);
Li Zefande11cc12011-12-01 12:55:47 +08006215
Liu Bo73c0f222017-03-14 13:33:58 -07006216 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
Liu Bo2b19a1f2017-03-14 13:34:00 -07006217 need_full_stripe(op)) {
Liu Bo73c0f222017-03-14 13:33:58 -07006218 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6219 &max_errors);
Stefan Behrens472262f2012-11-06 14:43:46 +01006220 }
6221
Li Zefande11cc12011-12-01 12:55:47 +08006222 *bbio_ret = bbio;
Zhao Lei10f11902015-01-20 15:11:43 +08006223 bbio->map_type = map->type;
Li Zefande11cc12011-12-01 12:55:47 +08006224 bbio->num_stripes = num_stripes;
6225 bbio->max_errors = max_errors;
6226 bbio->mirror_num = mirror_num;
Stefan Behrensad6d6202012-11-06 15:06:47 +01006227
6228 /*
6229 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6230 * mirror_num == num_stripes + 1 && dev_replace target drive is
6231 * available as a mirror
6232 */
6233 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6234 WARN_ON(num_stripes > 1);
6235 bbio->stripes[0].dev = dev_replace->tgtdev;
6236 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6237 bbio->mirror_num = map->num_stripes + 1;
6238 }
Chris Masoncea9e442008-04-09 16:28:12 -04006239out:
Liu Bo73beece2015-07-17 16:49:19 +08006240 if (dev_replace_is_ongoing) {
David Sterba53176dd2018-04-05 01:41:06 +02006241 lockdep_assert_held(&dev_replace->rwsem);
6242 /* Unlock and let waiting writers proceed */
David Sterbacb5583d2018-09-07 16:11:23 +02006243 up_read(&dev_replace->rwsem);
Liu Bo73beece2015-07-17 16:49:19 +08006244 }
Chris Mason0b86a832008-03-24 15:01:56 -04006245 free_extent_map(em);
Li Zefande11cc12011-12-01 12:55:47 +08006246 return ret;
Chris Mason0b86a832008-03-24 15:01:56 -04006247}
6248
Christoph Hellwigcf8cddd2016-10-27 09:27:36 +02006249int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
Chris Masonf2d8d742008-04-21 10:03:05 -04006250 u64 logical, u64 *length,
Jan Schmidta1d3c472011-08-04 17:15:33 +02006251 struct btrfs_bio **bbio_ret, int mirror_num)
Chris Masonf2d8d742008-04-21 10:03:05 -04006252{
David Sterba75fb2e92018-08-03 00:36:29 +02006253 if (op == BTRFS_MAP_DISCARD)
6254 return __btrfs_map_block_for_discard(fs_info, logical,
6255 length, bbio_ret);
6256
Mike Christieb3d3fa52016-06-05 14:31:53 -05006257 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006258 mirror_num, 0);
Chris Masonf2d8d742008-04-21 10:03:05 -04006259}
6260
Miao Xieaf8e2d12014-10-23 14:42:50 +08006261/* For Scrub/replace */
Christoph Hellwigcf8cddd2016-10-27 09:27:36 +02006262int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
Miao Xieaf8e2d12014-10-23 14:42:50 +08006263 u64 logical, u64 *length,
David Sterba825ad4c2017-03-28 14:45:22 +02006264 struct btrfs_bio **bbio_ret)
Miao Xieaf8e2d12014-10-23 14:42:50 +08006265{
David Sterba825ad4c2017-03-28 14:45:22 +02006266 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
Miao Xieaf8e2d12014-10-23 14:42:50 +08006267}
6268
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006269static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
Miao Xie8408c712014-06-19 10:42:55 +08006270{
Mike Snitzer326e1db2015-05-22 09:14:03 -04006271 bio->bi_private = bbio->private;
6272 bio->bi_end_io = bbio->end_io;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006273 bio_endio(bio);
Mike Snitzer326e1db2015-05-22 09:14:03 -04006274
Zhao Lei6e9606d2015-01-20 15:11:34 +08006275 btrfs_put_bbio(bbio);
Miao Xie8408c712014-06-19 10:42:55 +08006276}
6277
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006278static void btrfs_end_bio(struct bio *bio)
Chris Mason8790d502008-04-03 16:29:03 -04006279{
Chris Mason9be33952013-05-17 18:30:14 -04006280 struct btrfs_bio *bbio = bio->bi_private;
Chris Mason7d2b4da2008-08-05 10:13:57 -04006281 int is_orig_bio = 0;
Chris Mason8790d502008-04-03 16:29:03 -04006282
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02006283 if (bio->bi_status) {
Jan Schmidta1d3c472011-08-04 17:15:33 +02006284 atomic_inc(&bbio->error);
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02006285 if (bio->bi_status == BLK_STS_IOERR ||
6286 bio->bi_status == BLK_STS_TARGET) {
Nikolay Borisovc31efbd2020-07-03 11:14:27 +03006287 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
Stefan Behrens442a4f62012-05-25 16:06:08 +02006288
Nikolay Borisov3eee86c2020-07-02 15:23:31 +03006289 ASSERT(dev->bdev);
6290 if (bio_op(bio) == REQ_OP_WRITE)
6291 btrfs_dev_stat_inc_and_print(dev,
Stefan Behrens597a60f2012-06-14 16:42:31 +02006292 BTRFS_DEV_STAT_WRITE_ERRS);
Nikolay Borisov3eee86c2020-07-02 15:23:31 +03006293 else if (!(bio->bi_opf & REQ_RAHEAD))
6294 btrfs_dev_stat_inc_and_print(dev,
Stefan Behrens597a60f2012-06-14 16:42:31 +02006295 BTRFS_DEV_STAT_READ_ERRS);
Nikolay Borisov3eee86c2020-07-02 15:23:31 +03006296 if (bio->bi_opf & REQ_PREFLUSH)
6297 btrfs_dev_stat_inc_and_print(dev,
Stefan Behrens597a60f2012-06-14 16:42:31 +02006298 BTRFS_DEV_STAT_FLUSH_ERRS);
Stefan Behrens442a4f62012-05-25 16:06:08 +02006299 }
6300 }
Chris Mason8790d502008-04-03 16:29:03 -04006301
Jan Schmidta1d3c472011-08-04 17:15:33 +02006302 if (bio == bbio->orig_bio)
Chris Mason7d2b4da2008-08-05 10:13:57 -04006303 is_orig_bio = 1;
6304
Miao Xiec404e0d2014-01-30 16:46:55 +08006305 btrfs_bio_counter_dec(bbio->fs_info);
6306
Jan Schmidta1d3c472011-08-04 17:15:33 +02006307 if (atomic_dec_and_test(&bbio->stripes_pending)) {
Chris Mason7d2b4da2008-08-05 10:13:57 -04006308 if (!is_orig_bio) {
6309 bio_put(bio);
Jan Schmidta1d3c472011-08-04 17:15:33 +02006310 bio = bbio->orig_bio;
Chris Mason7d2b4da2008-08-05 10:13:57 -04006311 }
Muthu Kumarc7b22bb2014-01-08 14:19:52 -07006312
Chris Mason9be33952013-05-17 18:30:14 -04006313 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
Chris Masona236aed2008-04-29 09:38:00 -04006314 /* only send an error to the higher layers if it is
David Woodhouse53b381b2013-01-29 18:40:14 -05006315 * beyond the tolerance of the btrfs bio
Chris Masona236aed2008-04-29 09:38:00 -04006316 */
Jan Schmidta1d3c472011-08-04 17:15:33 +02006317 if (atomic_read(&bbio->error) > bbio->max_errors) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02006318 bio->bi_status = BLK_STS_IOERR;
Chris Mason5dbc8fc2011-12-09 11:07:37 -05006319 } else {
Chris Mason1259ab72008-05-12 13:39:03 -04006320 /*
6321 * this bio is actually up to date, we didn't
6322 * go over the max number of errors
6323 */
Anand Jain2dbe0c72017-10-14 08:35:56 +08006324 bio->bi_status = BLK_STS_OK;
Chris Mason1259ab72008-05-12 13:39:03 -04006325 }
Miao Xiec55f1392014-06-19 10:42:54 +08006326
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006327 btrfs_end_bbio(bbio, bio);
Chris Mason7d2b4da2008-08-05 10:13:57 -04006328 } else if (!is_orig_bio) {
Chris Mason8790d502008-04-03 16:29:03 -04006329 bio_put(bio);
6330 }
Chris Mason8790d502008-04-03 16:29:03 -04006331}
6332
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006333static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
Nikolay Borisovc31efbd2020-07-03 11:14:27 +03006334 u64 physical, struct btrfs_device *dev)
Josef Bacikde1ee922012-10-19 16:50:56 -04006335{
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006336 struct btrfs_fs_info *fs_info = bbio->fs_info;
Josef Bacikde1ee922012-10-19 16:50:56 -04006337
6338 bio->bi_private = bbio;
Nikolay Borisovc31efbd2020-07-03 11:14:27 +03006339 btrfs_io_bio(bio)->device = dev;
Josef Bacikde1ee922012-10-19 16:50:56 -04006340 bio->bi_end_io = btrfs_end_bio;
Kent Overstreet4f024f32013-10-11 15:44:27 -07006341 bio->bi_iter.bi_sector = physical >> 9;
Misono Tomohiro672d5992018-08-02 16:19:07 +09006342 btrfs_debug_in_rcu(fs_info,
6343 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6344 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
David Sterba1db45a32019-11-28 15:31:46 +01006345 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6346 dev->devid, bio->bi_iter.bi_size);
Christoph Hellwig74d46992017-08-23 19:10:32 +02006347 bio_set_dev(bio, dev->bdev);
Miao Xiec404e0d2014-01-30 16:46:55 +08006348
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006349 btrfs_bio_counter_inc_noblocked(fs_info);
Miao Xiec404e0d2014-01-30 16:46:55 +08006350
Chris Mason08635ba2019-07-10 12:28:14 -07006351 btrfsic_submit_bio(bio);
Josef Bacikde1ee922012-10-19 16:50:56 -04006352}
6353
Josef Bacikde1ee922012-10-19 16:50:56 -04006354static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6355{
6356 atomic_inc(&bbio->error);
6357 if (atomic_dec_and_test(&bbio->stripes_pending)) {
Nicholas D Steeves01327612016-05-19 21:18:45 -04006358 /* Should be the original bio. */
Miao Xie8408c712014-06-19 10:42:55 +08006359 WARN_ON(bio != bbio->orig_bio);
6360
Chris Mason9be33952013-05-17 18:30:14 -04006361 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
Kent Overstreet4f024f32013-10-11 15:44:27 -07006362 bio->bi_iter.bi_sector = logical >> 9;
Anand Jain102ed2c2017-10-14 08:34:02 +08006363 if (atomic_read(&bbio->error) > bbio->max_errors)
6364 bio->bi_status = BLK_STS_IOERR;
6365 else
6366 bio->bi_status = BLK_STS_OK;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006367 btrfs_end_bbio(bbio, bio);
Josef Bacikde1ee922012-10-19 16:50:56 -04006368 }
6369}
6370
Omar Sandoval58efbc92017-08-22 23:45:59 -07006371blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
Chris Mason08635ba2019-07-10 12:28:14 -07006372 int mirror_num)
Chris Mason0b86a832008-03-24 15:01:56 -04006373{
Chris Mason0b86a832008-03-24 15:01:56 -04006374 struct btrfs_device *dev;
Chris Mason8790d502008-04-03 16:29:03 -04006375 struct bio *first_bio = bio;
Kent Overstreet4f024f32013-10-11 15:44:27 -07006376 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
Chris Mason0b86a832008-03-24 15:01:56 -04006377 u64 length = 0;
6378 u64 map_length;
Chris Mason0b86a832008-03-24 15:01:56 -04006379 int ret;
Zhao Lei08da7572015-02-12 15:42:16 +08006380 int dev_nr;
6381 int total_devs;
Jan Schmidta1d3c472011-08-04 17:15:33 +02006382 struct btrfs_bio *bbio = NULL;
Chris Mason0b86a832008-03-24 15:01:56 -04006383
Kent Overstreet4f024f32013-10-11 15:44:27 -07006384 length = bio->bi_iter.bi_size;
Chris Mason0b86a832008-03-24 15:01:56 -04006385 map_length = length;
Chris Masoncea9e442008-04-09 16:28:12 -04006386
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006387 btrfs_bio_counter_inc_blocked(fs_info);
Liu Bobd7d63c2017-09-19 17:50:09 -06006388 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
Mike Christie37226b22016-06-05 14:31:52 -05006389 &map_length, &bbio, mirror_num, 1);
Miao Xiec404e0d2014-01-30 16:46:55 +08006390 if (ret) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006391 btrfs_bio_counter_dec(fs_info);
Omar Sandoval58efbc92017-08-22 23:45:59 -07006392 return errno_to_blk_status(ret);
Miao Xiec404e0d2014-01-30 16:46:55 +08006393 }
Chris Masoncea9e442008-04-09 16:28:12 -04006394
Jan Schmidta1d3c472011-08-04 17:15:33 +02006395 total_devs = bbio->num_stripes;
David Woodhouse53b381b2013-01-29 18:40:14 -05006396 bbio->orig_bio = first_bio;
6397 bbio->private = first_bio->bi_private;
6398 bbio->end_io = first_bio->bi_end_io;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006399 bbio->fs_info = fs_info;
David Woodhouse53b381b2013-01-29 18:40:14 -05006400 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6401
Zhao Leiad1ba2a2015-12-15 18:18:09 +08006402 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
Mike Christie37226b22016-06-05 14:31:52 -05006403 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
David Woodhouse53b381b2013-01-29 18:40:14 -05006404 /* In this case, map_length has been set to the length of
6405 a single stripe; not the whole write */
Mike Christie37226b22016-06-05 14:31:52 -05006406 if (bio_op(bio) == REQ_OP_WRITE) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006407 ret = raid56_parity_write(fs_info, bio, bbio,
6408 map_length);
David Woodhouse53b381b2013-01-29 18:40:14 -05006409 } else {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006410 ret = raid56_parity_recover(fs_info, bio, bbio,
6411 map_length, mirror_num, 1);
David Woodhouse53b381b2013-01-29 18:40:14 -05006412 }
Miao Xie42452152014-11-25 16:39:28 +08006413
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006414 btrfs_bio_counter_dec(fs_info);
Omar Sandoval58efbc92017-08-22 23:45:59 -07006415 return errno_to_blk_status(ret);
David Woodhouse53b381b2013-01-29 18:40:14 -05006416 }
6417
Chris Masoncea9e442008-04-09 16:28:12 -04006418 if (map_length < length) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006419 btrfs_crit(fs_info,
Jeff Mahoney5d163e02016-09-20 10:05:00 -04006420 "mapping failed logical %llu bio len %llu len %llu",
6421 logical, length, map_length);
Chris Masoncea9e442008-04-09 16:28:12 -04006422 BUG();
6423 }
Jan Schmidta1d3c472011-08-04 17:15:33 +02006424
Zhao Lei08da7572015-02-12 15:42:16 +08006425 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
Josef Bacikde1ee922012-10-19 16:50:56 -04006426 dev = bbio->stripes[dev_nr].dev;
Nikolay Borisovfc8a1682018-11-08 16:16:38 +02006427 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6428 &dev->dev_state) ||
Anand Jainebbede42017-12-04 12:54:52 +08006429 (bio_op(first_bio) == REQ_OP_WRITE &&
6430 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
Josef Bacikde1ee922012-10-19 16:50:56 -04006431 bbio_error(bbio, first_bio, logical);
Josef Bacikde1ee922012-10-19 16:50:56 -04006432 continue;
6433 }
6434
David Sterba3aa8e072017-06-02 17:38:30 +02006435 if (dev_nr < total_devs - 1)
David Sterba8b6c1d52017-06-02 17:48:13 +02006436 bio = btrfs_bio_clone(first_bio);
David Sterba3aa8e072017-06-02 17:38:30 +02006437 else
Jan Schmidta1d3c472011-08-04 17:15:33 +02006438 bio = first_bio;
Josef Bacik606686e2012-06-04 14:03:51 -04006439
Nikolay Borisovc31efbd2020-07-03 11:14:27 +03006440 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
Chris Mason239b14b2008-03-24 15:02:07 -04006441 }
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006442 btrfs_bio_counter_dec(fs_info);
Omar Sandoval58efbc92017-08-22 23:45:59 -07006443 return BLK_STS_OK;
Chris Mason0b86a832008-03-24 15:01:56 -04006444}
6445
Anand Jain09ba3bc2019-01-19 14:48:55 +08006446/*
6447 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6448 * return NULL.
6449 *
6450 * If devid and uuid are both specified, the match must be exact, otherwise
6451 * only devid is used.
6452 *
6453 * If @seed is true, traverse through the seed devices.
6454 */
Anand Jaine4319cd2019-01-17 23:32:31 +08006455struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
Anand Jain09ba3bc2019-01-19 14:48:55 +08006456 u64 devid, u8 *uuid, u8 *fsid,
6457 bool seed)
Chris Mason0b86a832008-03-24 15:01:56 -04006458{
Yan Zheng2b820322008-11-17 21:11:30 -05006459 struct btrfs_device *device;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006460 struct btrfs_fs_devices *seed_devs;
Chris Mason0b86a832008-03-24 15:01:56 -04006461
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006462 if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6463 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6464 if (device->devid == devid &&
6465 (!uuid || memcmp(device->uuid, uuid,
6466 BTRFS_UUID_SIZE) == 0))
6467 return device;
6468 }
6469 }
6470
6471 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
Yan Zheng2b820322008-11-17 21:11:30 -05006472 if (!fsid ||
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006473 !memcmp(seed_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6474 list_for_each_entry(device, &seed_devs->devices,
Anand Jain09ba3bc2019-01-19 14:48:55 +08006475 dev_list) {
6476 if (device->devid == devid &&
6477 (!uuid || memcmp(device->uuid, uuid,
6478 BTRFS_UUID_SIZE) == 0))
6479 return device;
6480 }
Yan Zheng2b820322008-11-17 21:11:30 -05006481 }
Yan Zheng2b820322008-11-17 21:11:30 -05006482 }
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006483
Yan Zheng2b820322008-11-17 21:11:30 -05006484 return NULL;
Chris Mason0b86a832008-03-24 15:01:56 -04006485}
6486
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006487static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
Chris Masondfe25022008-05-13 13:46:40 -04006488 u64 devid, u8 *dev_uuid)
6489{
6490 struct btrfs_device *device;
Josef Bacikfccc0002020-08-31 10:52:42 -04006491 unsigned int nofs_flag;
Chris Masondfe25022008-05-13 13:46:40 -04006492
Josef Bacikfccc0002020-08-31 10:52:42 -04006493 /*
6494 * We call this under the chunk_mutex, so we want to use NOFS for this
6495 * allocation, however we don't want to change btrfs_alloc_device() to
6496 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6497 * places.
6498 */
6499 nofs_flag = memalloc_nofs_save();
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006500 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
Josef Bacikfccc0002020-08-31 10:52:42 -04006501 memalloc_nofs_restore(nofs_flag);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006502 if (IS_ERR(device))
Anand Jainadfb69a2017-10-11 12:46:18 +08006503 return device;
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006504
6505 list_add(&device->dev_list, &fs_devices->devices);
Yan Zhenge4404d62008-12-12 10:03:26 -05006506 device->fs_devices = fs_devices;
Chris Masondfe25022008-05-13 13:46:40 -04006507 fs_devices->num_devices++;
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006508
Anand Jaine6e674b2017-12-04 12:54:54 +08006509 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
Chris Masoncd02dca2010-12-13 14:56:23 -05006510 fs_devices->missing_devices++;
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006511
Chris Masondfe25022008-05-13 13:46:40 -04006512 return device;
6513}
6514
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006515/**
6516 * btrfs_alloc_device - allocate struct btrfs_device
6517 * @fs_info: used only for generating a new devid, can be NULL if
6518 * devid is provided (i.e. @devid != NULL).
6519 * @devid: a pointer to devid for this device. If NULL a new devid
6520 * is generated.
6521 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6522 * is generated.
6523 *
6524 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
David Sterba48dae9c2017-10-30 18:10:25 +01006525 * on error. Returned struct is not linked onto any lists and must be
David Sterbaa425f9d2018-03-20 15:47:33 +01006526 * destroyed with btrfs_free_device.
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006527 */
6528struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6529 const u64 *devid,
6530 const u8 *uuid)
6531{
6532 struct btrfs_device *dev;
6533 u64 tmp;
6534
Dulshani Gunawardhanafae7f212013-10-31 10:30:08 +05306535 if (WARN_ON(!devid && !fs_info))
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006536 return ERR_PTR(-EINVAL);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006537
Qu Wenruo154f7cb2020-08-20 15:42:46 +08006538 dev = __alloc_device(fs_info);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006539 if (IS_ERR(dev))
6540 return dev;
6541
6542 if (devid)
6543 tmp = *devid;
6544 else {
6545 int ret;
6546
6547 ret = find_next_devid(fs_info, &tmp);
6548 if (ret) {
David Sterbaa425f9d2018-03-20 15:47:33 +01006549 btrfs_free_device(dev);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006550 return ERR_PTR(ret);
6551 }
6552 }
6553 dev->devid = tmp;
6554
6555 if (uuid)
6556 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6557 else
6558 generate_random_uuid(dev->uuid);
6559
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006560 return dev;
6561}
6562
Anand Jain5a2b8e62017-10-09 11:07:45 +08006563static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
Anand Jain2b902df2017-10-09 11:07:46 +08006564 u64 devid, u8 *uuid, bool error)
Anand Jain5a2b8e62017-10-09 11:07:45 +08006565{
Anand Jain2b902df2017-10-09 11:07:46 +08006566 if (error)
6567 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6568 devid, uuid);
6569 else
6570 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6571 devid, uuid);
Anand Jain5a2b8e62017-10-09 11:07:45 +08006572}
6573
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006574static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6575{
6576 int index = btrfs_bg_flags_to_raid_index(type);
6577 int ncopies = btrfs_raid_array[index].ncopies;
David Sterbae4f6c6b2019-05-14 01:59:54 +02006578 const int nparity = btrfs_raid_array[index].nparity;
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006579 int data_stripes;
6580
David Sterbae4f6c6b2019-05-14 01:59:54 +02006581 if (nparity)
6582 data_stripes = num_stripes - nparity;
6583 else
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006584 data_stripes = num_stripes / ncopies;
David Sterbae4f6c6b2019-05-14 01:59:54 +02006585
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006586 return div_u64(chunk_len, data_stripes);
6587}
6588
David Sterba9690ac02019-03-20 16:43:07 +01006589static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
Chris Mason0b86a832008-03-24 15:01:56 -04006590 struct btrfs_chunk *chunk)
6591{
David Sterba9690ac02019-03-20 16:43:07 +01006592 struct btrfs_fs_info *fs_info = leaf->fs_info;
David Sterbac8bf1b62019-05-17 11:43:17 +02006593 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
Chris Mason0b86a832008-03-24 15:01:56 -04006594 struct map_lookup *map;
6595 struct extent_map *em;
6596 u64 logical;
6597 u64 length;
6598 u64 devid;
Chris Masona4437552008-04-18 10:29:38 -04006599 u8 uuid[BTRFS_UUID_SIZE];
Chris Mason593060d2008-03-25 16:50:33 -04006600 int num_stripes;
Chris Mason0b86a832008-03-24 15:01:56 -04006601 int ret;
Chris Mason593060d2008-03-25 16:50:33 -04006602 int i;
Chris Mason0b86a832008-03-24 15:01:56 -04006603
Chris Masone17cade2008-04-15 15:41:47 -04006604 logical = key->offset;
6605 length = btrfs_chunk_length(leaf, chunk);
Qu Wenruof04b7722015-12-15 09:14:37 +08006606 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
Liu Boe06cd3d2016-06-03 12:05:15 -07006607
Qu Wenruo075cb3c2019-03-20 13:42:33 +08006608 /*
6609 * Only need to verify chunk item if we're reading from sys chunk array,
6610 * as chunk item in tree block is already verified by tree-checker.
6611 */
6612 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
David Sterbaddaf1d52019-03-20 16:40:48 +01006613 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
Qu Wenruo075cb3c2019-03-20 13:42:33 +08006614 if (ret)
6615 return ret;
6616 }
Chris Masona061fc82008-05-07 11:43:44 -04006617
David Sterbac8bf1b62019-05-17 11:43:17 +02006618 read_lock(&map_tree->lock);
6619 em = lookup_extent_mapping(map_tree, logical, 1);
6620 read_unlock(&map_tree->lock);
Chris Mason0b86a832008-03-24 15:01:56 -04006621
6622 /* already mapped? */
6623 if (em && em->start <= logical && em->start + em->len > logical) {
6624 free_extent_map(em);
Chris Mason0b86a832008-03-24 15:01:56 -04006625 return 0;
6626 } else if (em) {
6627 free_extent_map(em);
6628 }
Chris Mason0b86a832008-03-24 15:01:56 -04006629
David Sterba172ddd62011-04-21 00:48:27 +02006630 em = alloc_extent_map();
Chris Mason0b86a832008-03-24 15:01:56 -04006631 if (!em)
6632 return -ENOMEM;
Chris Mason593060d2008-03-25 16:50:33 -04006633 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
Chris Mason0b86a832008-03-24 15:01:56 -04006634 if (!map) {
6635 free_extent_map(em);
6636 return -ENOMEM;
6637 }
6638
Wang Shilong298a8f92014-06-19 10:42:52 +08006639 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
Jeff Mahoney95617d62015-06-03 10:55:48 -04006640 em->map_lookup = map;
Chris Mason0b86a832008-03-24 15:01:56 -04006641 em->start = logical;
6642 em->len = length;
Josef Bacik70c8a912012-10-11 16:54:30 -04006643 em->orig_start = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04006644 em->block_start = 0;
Chris Masonc8b97812008-10-29 14:49:59 -04006645 em->block_len = em->len;
Chris Mason0b86a832008-03-24 15:01:56 -04006646
Chris Mason593060d2008-03-25 16:50:33 -04006647 map->num_stripes = num_stripes;
6648 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6649 map->io_align = btrfs_chunk_io_align(leaf, chunk);
Chris Mason593060d2008-03-25 16:50:33 -04006650 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6651 map->type = btrfs_chunk_type(leaf, chunk);
Chris Mason321aecc2008-04-16 10:49:51 -04006652 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
Qu Wenruocf90d882018-08-01 10:37:19 +08006653 map->verified_stripes = 0;
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006654 em->orig_block_len = calc_stripe_length(map->type, em->len,
6655 map->num_stripes);
Chris Mason593060d2008-03-25 16:50:33 -04006656 for (i = 0; i < num_stripes; i++) {
6657 map->stripes[i].physical =
6658 btrfs_stripe_offset_nr(leaf, chunk, i);
6659 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
Chris Masona4437552008-04-18 10:29:38 -04006660 read_extent_buffer(leaf, uuid, (unsigned long)
6661 btrfs_stripe_dev_uuid_nr(chunk, i),
6662 BTRFS_UUID_SIZE);
Anand Jaine4319cd2019-01-17 23:32:31 +08006663 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
Anand Jain09ba3bc2019-01-19 14:48:55 +08006664 devid, uuid, NULL, true);
Jeff Mahoney3cdde222016-06-09 21:38:35 -04006665 if (!map->stripes[i].dev &&
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006666 !btrfs_test_opt(fs_info, DEGRADED)) {
Chris Mason593060d2008-03-25 16:50:33 -04006667 free_extent_map(em);
Anand Jain2b902df2017-10-09 11:07:46 +08006668 btrfs_report_missing_device(fs_info, devid, uuid, true);
Anand Jain45dbdbc2017-10-09 11:07:44 +08006669 return -ENOENT;
Chris Mason593060d2008-03-25 16:50:33 -04006670 }
Chris Masondfe25022008-05-13 13:46:40 -04006671 if (!map->stripes[i].dev) {
6672 map->stripes[i].dev =
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006673 add_missing_dev(fs_info->fs_devices, devid,
6674 uuid);
Anand Jainadfb69a2017-10-11 12:46:18 +08006675 if (IS_ERR(map->stripes[i].dev)) {
Chris Masondfe25022008-05-13 13:46:40 -04006676 free_extent_map(em);
Anand Jainadfb69a2017-10-11 12:46:18 +08006677 btrfs_err(fs_info,
6678 "failed to init missing dev %llu: %ld",
6679 devid, PTR_ERR(map->stripes[i].dev));
6680 return PTR_ERR(map->stripes[i].dev);
Chris Masondfe25022008-05-13 13:46:40 -04006681 }
Anand Jain2b902df2017-10-09 11:07:46 +08006682 btrfs_report_missing_device(fs_info, devid, uuid, false);
Chris Masondfe25022008-05-13 13:46:40 -04006683 }
Anand Jaine12c9622017-12-04 12:54:53 +08006684 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6685 &(map->stripes[i].dev->dev_state));
6686
Chris Mason0b86a832008-03-24 15:01:56 -04006687 }
6688
David Sterbac8bf1b62019-05-17 11:43:17 +02006689 write_lock(&map_tree->lock);
6690 ret = add_extent_mapping(map_tree, em, 0);
6691 write_unlock(&map_tree->lock);
Qu Wenruo64f64f42018-08-01 10:37:20 +08006692 if (ret < 0) {
6693 btrfs_err(fs_info,
6694 "failed to add chunk map, start=%llu len=%llu: %d",
6695 em->start, em->len, ret);
6696 }
Chris Mason0b86a832008-03-24 15:01:56 -04006697 free_extent_map(em);
6698
Qu Wenruo64f64f42018-08-01 10:37:20 +08006699 return ret;
Chris Mason0b86a832008-03-24 15:01:56 -04006700}
6701
Jeff Mahoney143bede2012-03-01 14:56:26 +01006702static void fill_device_from_item(struct extent_buffer *leaf,
Chris Mason0b86a832008-03-24 15:01:56 -04006703 struct btrfs_dev_item *dev_item,
6704 struct btrfs_device *device)
6705{
6706 unsigned long ptr;
Chris Mason0b86a832008-03-24 15:01:56 -04006707
6708 device->devid = btrfs_device_id(leaf, dev_item);
Chris Balld6397ba2009-04-27 07:29:03 -04006709 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6710 device->total_bytes = device->disk_total_bytes;
Miao Xie935e5cc2014-09-03 21:35:33 +08006711 device->commit_total_bytes = device->disk_total_bytes;
Chris Mason0b86a832008-03-24 15:01:56 -04006712 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
Miao Xiece7213c2014-09-03 21:35:34 +08006713 device->commit_bytes_used = device->bytes_used;
Chris Mason0b86a832008-03-24 15:01:56 -04006714 device->type = btrfs_device_type(leaf, dev_item);
6715 device->io_align = btrfs_device_io_align(leaf, dev_item);
6716 device->io_width = btrfs_device_io_width(leaf, dev_item);
6717 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
Stefan Behrens8dabb742012-11-06 13:15:27 +01006718 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
Anand Jain401e29c2017-12-04 12:54:55 +08006719 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
Chris Mason0b86a832008-03-24 15:01:56 -04006720
Geert Uytterhoeven410ba3a2013-08-20 13:20:11 +02006721 ptr = btrfs_device_uuid(dev_item);
Chris Masone17cade2008-04-15 15:41:47 -04006722 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
Chris Mason0b86a832008-03-24 15:01:56 -04006723}
6724
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006725static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
Miao Xie5f375832014-09-03 21:35:46 +08006726 u8 *fsid)
Yan Zheng2b820322008-11-17 21:11:30 -05006727{
6728 struct btrfs_fs_devices *fs_devices;
6729 int ret;
6730
David Sterbaa32bf9a2018-03-16 02:21:22 +01006731 lockdep_assert_held(&uuid_mutex);
David Sterba2dfeca92017-06-14 02:48:07 +02006732 ASSERT(fsid);
Yan Zheng2b820322008-11-17 21:11:30 -05006733
Nikolay Borisov427c8fd2020-08-12 17:04:36 +03006734 /* This will match only for multi-device seed fs */
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006735 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
Anand Jain44880fd2017-07-29 17:50:09 +08006736 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
Miao Xie5f375832014-09-03 21:35:46 +08006737 return fs_devices;
6738
Yan Zheng2b820322008-11-17 21:11:30 -05006739
Nikolay Borisov7239ff42018-10-30 16:43:23 +02006740 fs_devices = find_fsid(fsid, NULL);
Yan Zheng2b820322008-11-17 21:11:30 -05006741 if (!fs_devices) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006742 if (!btrfs_test_opt(fs_info, DEGRADED))
Miao Xie5f375832014-09-03 21:35:46 +08006743 return ERR_PTR(-ENOENT);
6744
Nikolay Borisov7239ff42018-10-30 16:43:23 +02006745 fs_devices = alloc_fs_devices(fsid, NULL);
Miao Xie5f375832014-09-03 21:35:46 +08006746 if (IS_ERR(fs_devices))
6747 return fs_devices;
6748
Johannes Thumshirn0395d842019-11-13 11:27:27 +01006749 fs_devices->seeding = true;
Miao Xie5f375832014-09-03 21:35:46 +08006750 fs_devices->opened = 1;
6751 return fs_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05006752 }
Yan Zhenge4404d62008-12-12 10:03:26 -05006753
Nikolay Borisov427c8fd2020-08-12 17:04:36 +03006754 /*
6755 * Upon first call for a seed fs fsid, just create a private copy of the
6756 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
6757 */
Yan Zhenge4404d62008-12-12 10:03:26 -05006758 fs_devices = clone_fs_devices(fs_devices);
Miao Xie5f375832014-09-03 21:35:46 +08006759 if (IS_ERR(fs_devices))
6760 return fs_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05006761
Anand Jain897fb572018-04-12 10:29:28 +08006762 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
Julia Lawall48d28232012-04-14 11:24:33 +02006763 if (ret) {
6764 free_fs_devices(fs_devices);
Anand Jainc83b60c2020-09-05 01:34:35 +08006765 return ERR_PTR(ret);
Julia Lawall48d28232012-04-14 11:24:33 +02006766 }
Yan Zheng2b820322008-11-17 21:11:30 -05006767
6768 if (!fs_devices->seeding) {
Anand Jain0226e0e2018-04-12 10:29:27 +08006769 close_fs_devices(fs_devices);
Yan Zhenge4404d62008-12-12 10:03:26 -05006770 free_fs_devices(fs_devices);
Anand Jainc83b60c2020-09-05 01:34:35 +08006771 return ERR_PTR(-EINVAL);
Yan Zheng2b820322008-11-17 21:11:30 -05006772 }
6773
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006774 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
Anand Jainc83b60c2020-09-05 01:34:35 +08006775
Miao Xie5f375832014-09-03 21:35:46 +08006776 return fs_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05006777}
6778
David Sterba17850752019-03-20 16:45:15 +01006779static int read_one_dev(struct extent_buffer *leaf,
Chris Mason0b86a832008-03-24 15:01:56 -04006780 struct btrfs_dev_item *dev_item)
6781{
David Sterba17850752019-03-20 16:45:15 +01006782 struct btrfs_fs_info *fs_info = leaf->fs_info;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006783 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Chris Mason0b86a832008-03-24 15:01:56 -04006784 struct btrfs_device *device;
6785 u64 devid;
6786 int ret;
Anand Jain44880fd2017-07-29 17:50:09 +08006787 u8 fs_uuid[BTRFS_FSID_SIZE];
Chris Masona4437552008-04-18 10:29:38 -04006788 u8 dev_uuid[BTRFS_UUID_SIZE];
6789
Chris Mason0b86a832008-03-24 15:01:56 -04006790 devid = btrfs_device_id(leaf, dev_item);
Geert Uytterhoeven410ba3a2013-08-20 13:20:11 +02006791 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
Chris Masona4437552008-04-18 10:29:38 -04006792 BTRFS_UUID_SIZE);
Geert Uytterhoeven1473b242013-08-20 13:20:12 +02006793 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
Anand Jain44880fd2017-07-29 17:50:09 +08006794 BTRFS_FSID_SIZE);
Yan Zheng2b820322008-11-17 21:11:30 -05006795
Nikolay Borisovde37aa52018-10-30 16:43:24 +02006796 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006797 fs_devices = open_seed_devices(fs_info, fs_uuid);
Miao Xie5f375832014-09-03 21:35:46 +08006798 if (IS_ERR(fs_devices))
6799 return PTR_ERR(fs_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05006800 }
6801
Anand Jaine4319cd2019-01-17 23:32:31 +08006802 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
Anand Jain09ba3bc2019-01-19 14:48:55 +08006803 fs_uuid, true);
Miao Xie5f375832014-09-03 21:35:46 +08006804 if (!device) {
Qu Wenruoc5502452017-03-09 09:34:42 +08006805 if (!btrfs_test_opt(fs_info, DEGRADED)) {
Anand Jain2b902df2017-10-09 11:07:46 +08006806 btrfs_report_missing_device(fs_info, devid,
6807 dev_uuid, true);
Anand Jain45dbdbc2017-10-09 11:07:44 +08006808 return -ENOENT;
Qu Wenruoc5502452017-03-09 09:34:42 +08006809 }
Yan Zheng2b820322008-11-17 21:11:30 -05006810
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006811 device = add_missing_dev(fs_devices, devid, dev_uuid);
Anand Jainadfb69a2017-10-11 12:46:18 +08006812 if (IS_ERR(device)) {
6813 btrfs_err(fs_info,
6814 "failed to add missing dev %llu: %ld",
6815 devid, PTR_ERR(device));
6816 return PTR_ERR(device);
6817 }
Anand Jain2b902df2017-10-09 11:07:46 +08006818 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
Miao Xie5f375832014-09-03 21:35:46 +08006819 } else {
Qu Wenruoc5502452017-03-09 09:34:42 +08006820 if (!device->bdev) {
Anand Jain2b902df2017-10-09 11:07:46 +08006821 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6822 btrfs_report_missing_device(fs_info,
6823 devid, dev_uuid, true);
Anand Jain45dbdbc2017-10-09 11:07:44 +08006824 return -ENOENT;
Anand Jain2b902df2017-10-09 11:07:46 +08006825 }
6826 btrfs_report_missing_device(fs_info, devid,
6827 dev_uuid, false);
Qu Wenruoc5502452017-03-09 09:34:42 +08006828 }
Miao Xie5f375832014-09-03 21:35:46 +08006829
Anand Jaine6e674b2017-12-04 12:54:54 +08006830 if (!device->bdev &&
6831 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
Chris Masoncd02dca2010-12-13 14:56:23 -05006832 /*
6833 * this happens when a device that was properly setup
6834 * in the device info lists suddenly goes bad.
6835 * device->bdev is NULL, and so we have to set
6836 * device->missing to one here
6837 */
Miao Xie5f375832014-09-03 21:35:46 +08006838 device->fs_devices->missing_devices++;
Anand Jaine6e674b2017-12-04 12:54:54 +08006839 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
Yan Zheng2b820322008-11-17 21:11:30 -05006840 }
Miao Xie5f375832014-09-03 21:35:46 +08006841
6842 /* Move the device to its own fs_devices */
6843 if (device->fs_devices != fs_devices) {
Anand Jaine6e674b2017-12-04 12:54:54 +08006844 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6845 &device->dev_state));
Miao Xie5f375832014-09-03 21:35:46 +08006846
6847 list_move(&device->dev_list, &fs_devices->devices);
6848 device->fs_devices->num_devices--;
6849 fs_devices->num_devices++;
6850
6851 device->fs_devices->missing_devices--;
6852 fs_devices->missing_devices++;
6853
6854 device->fs_devices = fs_devices;
6855 }
Yan Zheng2b820322008-11-17 21:11:30 -05006856 }
6857
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006858 if (device->fs_devices != fs_info->fs_devices) {
Anand Jainebbede42017-12-04 12:54:52 +08006859 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
Yan Zheng2b820322008-11-17 21:11:30 -05006860 if (device->generation !=
6861 btrfs_device_generation(leaf, dev_item))
6862 return -EINVAL;
Chris Mason6324fbf2008-03-24 15:01:59 -04006863 }
Chris Mason0b86a832008-03-24 15:01:56 -04006864
6865 fill_device_from_item(leaf, dev_item, device);
Anand Jaine12c9622017-12-04 12:54:53 +08006866 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
Anand Jainebbede42017-12-04 12:54:52 +08006867 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
Anand Jain401e29c2017-12-04 12:54:55 +08006868 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
Yan Zheng2b820322008-11-17 21:11:30 -05006869 device->fs_devices->total_rw_bytes += device->total_bytes;
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03006870 atomic64_add(device->total_bytes - device->bytes_used,
6871 &fs_info->free_chunk_space);
Josef Bacik2bf64752011-09-26 17:12:22 -04006872 }
Chris Mason0b86a832008-03-24 15:01:56 -04006873 ret = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04006874 return ret;
6875}
6876
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04006877int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
Chris Mason0b86a832008-03-24 15:01:56 -04006878{
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04006879 struct btrfs_root *root = fs_info->tree_root;
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04006880 struct btrfs_super_block *super_copy = fs_info->super_copy;
Chris Masona061fc82008-05-07 11:43:44 -04006881 struct extent_buffer *sb;
Chris Mason0b86a832008-03-24 15:01:56 -04006882 struct btrfs_disk_key *disk_key;
Chris Mason0b86a832008-03-24 15:01:56 -04006883 struct btrfs_chunk *chunk;
David Sterba1ffb22c2014-10-31 19:02:42 +01006884 u8 *array_ptr;
6885 unsigned long sb_array_offset;
Chris Mason84eed902008-04-25 09:04:37 -04006886 int ret = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04006887 u32 num_stripes;
6888 u32 array_size;
6889 u32 len = 0;
David Sterba1ffb22c2014-10-31 19:02:42 +01006890 u32 cur_offset;
Liu Boe06cd3d2016-06-03 12:05:15 -07006891 u64 type;
Chris Mason84eed902008-04-25 09:04:37 -04006892 struct btrfs_key key;
Chris Mason0b86a832008-03-24 15:01:56 -04006893
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006894 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
David Sterbaa83fffb2014-06-15 02:39:54 +02006895 /*
6896 * This will create extent buffer of nodesize, superblock size is
6897 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6898 * overallocate but we can keep it as-is, only the first page is used.
6899 */
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006900 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
Liu Boc871b0f2016-06-06 12:01:23 -07006901 if (IS_ERR(sb))
6902 return PTR_ERR(sb);
David Sterba4db8c522015-12-03 13:06:46 +01006903 set_extent_buffer_uptodate(sb);
Chris Mason85d4e462011-07-26 16:11:19 -04006904 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
David Sterba8a334422011-10-07 18:06:13 +02006905 /*
Nicholas D Steeves01327612016-05-19 21:18:45 -04006906 * The sb extent buffer is artificial and just used to read the system array.
David Sterba4db8c522015-12-03 13:06:46 +01006907 * set_extent_buffer_uptodate() call does not properly mark all it's
David Sterba8a334422011-10-07 18:06:13 +02006908 * pages up-to-date when the page is larger: extent does not cover the
6909 * whole page and consequently check_page_uptodate does not find all
6910 * the page's extents up-to-date (the hole beyond sb),
6911 * write_extent_buffer then triggers a WARN_ON.
6912 *
6913 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6914 * but sb spans only this function. Add an explicit SetPageUptodate call
6915 * to silence the warning eg. on PowerPC 64.
6916 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03006917 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
Chris Mason727011e2010-08-06 13:21:20 -04006918 SetPageUptodate(sb->pages[0]);
Chris Mason4008c042009-02-12 14:09:45 -05006919
Chris Masona061fc82008-05-07 11:43:44 -04006920 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
Chris Mason0b86a832008-03-24 15:01:56 -04006921 array_size = btrfs_super_sys_array_size(super_copy);
6922
David Sterba1ffb22c2014-10-31 19:02:42 +01006923 array_ptr = super_copy->sys_chunk_array;
6924 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6925 cur_offset = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04006926
David Sterba1ffb22c2014-10-31 19:02:42 +01006927 while (cur_offset < array_size) {
6928 disk_key = (struct btrfs_disk_key *)array_ptr;
David Sterbae3540ea2014-11-05 15:24:51 +01006929 len = sizeof(*disk_key);
6930 if (cur_offset + len > array_size)
6931 goto out_short_read;
6932
Chris Mason0b86a832008-03-24 15:01:56 -04006933 btrfs_disk_key_to_cpu(&key, disk_key);
6934
David Sterba1ffb22c2014-10-31 19:02:42 +01006935 array_ptr += len;
6936 sb_array_offset += len;
6937 cur_offset += len;
Chris Mason0b86a832008-03-24 15:01:56 -04006938
Johannes Thumshirn32ab3d12019-10-18 11:58:23 +02006939 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04006940 btrfs_err(fs_info,
6941 "unexpected item type %u in sys_array at offset %u",
6942 (u32)key.type, cur_offset);
Chris Mason84eed902008-04-25 09:04:37 -04006943 ret = -EIO;
6944 break;
Chris Mason0b86a832008-03-24 15:01:56 -04006945 }
Johannes Thumshirn32ab3d12019-10-18 11:58:23 +02006946
6947 chunk = (struct btrfs_chunk *)sb_array_offset;
6948 /*
6949 * At least one btrfs_chunk with one stripe must be present,
6950 * exact stripe count check comes afterwards
6951 */
6952 len = btrfs_chunk_item_size(1);
6953 if (cur_offset + len > array_size)
6954 goto out_short_read;
6955
6956 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6957 if (!num_stripes) {
6958 btrfs_err(fs_info,
6959 "invalid number of stripes %u in sys_array at offset %u",
6960 num_stripes, cur_offset);
6961 ret = -EIO;
6962 break;
6963 }
6964
6965 type = btrfs_chunk_type(sb, chunk);
6966 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6967 btrfs_err(fs_info,
6968 "invalid chunk type %llu in sys_array at offset %u",
6969 type, cur_offset);
6970 ret = -EIO;
6971 break;
6972 }
6973
6974 len = btrfs_chunk_item_size(num_stripes);
6975 if (cur_offset + len > array_size)
6976 goto out_short_read;
6977
6978 ret = read_one_chunk(&key, sb, chunk);
6979 if (ret)
6980 break;
6981
David Sterba1ffb22c2014-10-31 19:02:42 +01006982 array_ptr += len;
6983 sb_array_offset += len;
6984 cur_offset += len;
Chris Mason0b86a832008-03-24 15:01:56 -04006985 }
Liu Bod8651772016-06-03 17:41:42 -07006986 clear_extent_buffer_uptodate(sb);
Liu Bo1c8b5b62016-05-13 17:06:59 -07006987 free_extent_buffer_stale(sb);
Chris Mason84eed902008-04-25 09:04:37 -04006988 return ret;
David Sterbae3540ea2014-11-05 15:24:51 +01006989
6990out_short_read:
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04006991 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
David Sterbae3540ea2014-11-05 15:24:51 +01006992 len, cur_offset);
Liu Bod8651772016-06-03 17:41:42 -07006993 clear_extent_buffer_uptodate(sb);
Liu Bo1c8b5b62016-05-13 17:06:59 -07006994 free_extent_buffer_stale(sb);
David Sterbae3540ea2014-11-05 15:24:51 +01006995 return -EIO;
Chris Mason0b86a832008-03-24 15:01:56 -04006996}
6997
Qu Wenruo21634a12017-03-09 09:34:36 +08006998/*
6999 * Check if all chunks in the fs are OK for read-write degraded mount
7000 *
Anand Jain6528b992017-12-18 17:08:59 +08007001 * If the @failing_dev is specified, it's accounted as missing.
7002 *
Qu Wenruo21634a12017-03-09 09:34:36 +08007003 * Return true if all chunks meet the minimal RW mount requirements.
7004 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7005 */
Anand Jain6528b992017-12-18 17:08:59 +08007006bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7007 struct btrfs_device *failing_dev)
Qu Wenruo21634a12017-03-09 09:34:36 +08007008{
David Sterbac8bf1b62019-05-17 11:43:17 +02007009 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
Qu Wenruo21634a12017-03-09 09:34:36 +08007010 struct extent_map *em;
7011 u64 next_start = 0;
7012 bool ret = true;
7013
David Sterbac8bf1b62019-05-17 11:43:17 +02007014 read_lock(&map_tree->lock);
7015 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7016 read_unlock(&map_tree->lock);
Qu Wenruo21634a12017-03-09 09:34:36 +08007017 /* No chunk at all? Return false anyway */
7018 if (!em) {
7019 ret = false;
7020 goto out;
7021 }
7022 while (em) {
7023 struct map_lookup *map;
7024 int missing = 0;
7025 int max_tolerated;
7026 int i;
7027
7028 map = em->map_lookup;
7029 max_tolerated =
7030 btrfs_get_num_tolerated_disk_barrier_failures(
7031 map->type);
7032 for (i = 0; i < map->num_stripes; i++) {
7033 struct btrfs_device *dev = map->stripes[i].dev;
7034
Anand Jaine6e674b2017-12-04 12:54:54 +08007035 if (!dev || !dev->bdev ||
7036 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
Qu Wenruo21634a12017-03-09 09:34:36 +08007037 dev->last_flush_error)
7038 missing++;
Anand Jain6528b992017-12-18 17:08:59 +08007039 else if (failing_dev && failing_dev == dev)
7040 missing++;
Qu Wenruo21634a12017-03-09 09:34:36 +08007041 }
7042 if (missing > max_tolerated) {
Anand Jain6528b992017-12-18 17:08:59 +08007043 if (!failing_dev)
7044 btrfs_warn(fs_info,
Andrea Gelmini52042d82018-11-28 12:05:13 +01007045 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
Qu Wenruo21634a12017-03-09 09:34:36 +08007046 em->start, missing, max_tolerated);
7047 free_extent_map(em);
7048 ret = false;
7049 goto out;
7050 }
7051 next_start = extent_map_end(em);
7052 free_extent_map(em);
7053
David Sterbac8bf1b62019-05-17 11:43:17 +02007054 read_lock(&map_tree->lock);
7055 em = lookup_extent_mapping(map_tree, next_start,
Qu Wenruo21634a12017-03-09 09:34:36 +08007056 (u64)(-1) - next_start);
David Sterbac8bf1b62019-05-17 11:43:17 +02007057 read_unlock(&map_tree->lock);
Qu Wenruo21634a12017-03-09 09:34:36 +08007058 }
7059out:
7060 return ret;
7061}
7062
David Sterbad85327b12020-07-08 22:55:14 +02007063static void readahead_tree_node_children(struct extent_buffer *node)
7064{
7065 int i;
7066 const int nr_items = btrfs_header_nritems(node);
7067
7068 for (i = 0; i < nr_items; i++) {
7069 u64 start;
7070
7071 start = btrfs_node_blockptr(node, i);
7072 readahead_tree_block(node->fs_info, start);
7073 }
7074}
7075
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04007076int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
Chris Mason0b86a832008-03-24 15:01:56 -04007077{
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04007078 struct btrfs_root *root = fs_info->chunk_root;
Chris Mason0b86a832008-03-24 15:01:56 -04007079 struct btrfs_path *path;
7080 struct extent_buffer *leaf;
7081 struct btrfs_key key;
7082 struct btrfs_key found_key;
7083 int ret;
7084 int slot;
Liu Bo99e3ecf2016-06-03 12:05:14 -07007085 u64 total_dev = 0;
David Sterbad85327b12020-07-08 22:55:14 +02007086 u64 last_ra_node = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04007087
Chris Mason0b86a832008-03-24 15:01:56 -04007088 path = btrfs_alloc_path();
7089 if (!path)
7090 return -ENOMEM;
7091
Anand Jain3dd0f7a2018-04-12 10:29:32 +08007092 /*
7093 * uuid_mutex is needed only if we are mounting a sprout FS
7094 * otherwise we don't need it.
7095 */
Li Zefanb367e472011-12-07 11:38:24 +08007096 mutex_lock(&uuid_mutex);
Li Zefanb367e472011-12-07 11:38:24 +08007097
Filipe David Borba Manana395927a2013-07-30 12:03:04 +01007098 /*
Boris Burkov48cfa612020-07-16 13:29:46 -07007099 * It is possible for mount and umount to race in such a way that
7100 * we execute this code path, but open_fs_devices failed to clear
7101 * total_rw_bytes. We certainly want it cleared before reading the
7102 * device items, so clear it here.
7103 */
7104 fs_info->fs_devices->total_rw_bytes = 0;
7105
7106 /*
Filipe David Borba Manana395927a2013-07-30 12:03:04 +01007107 * Read all device items, and then all the chunk items. All
7108 * device items are found before any chunk item (their object id
7109 * is smaller than the lowest possible object id for a chunk
7110 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
Chris Mason0b86a832008-03-24 15:01:56 -04007111 */
7112 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7113 key.offset = 0;
7114 key.type = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04007115 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
Zhao Leiab593812010-03-25 12:34:49 +00007116 if (ret < 0)
7117 goto error;
Chris Masond3977122009-01-05 21:25:51 -05007118 while (1) {
David Sterbad85327b12020-07-08 22:55:14 +02007119 struct extent_buffer *node;
7120
Chris Mason0b86a832008-03-24 15:01:56 -04007121 leaf = path->nodes[0];
7122 slot = path->slots[0];
7123 if (slot >= btrfs_header_nritems(leaf)) {
7124 ret = btrfs_next_leaf(root, path);
7125 if (ret == 0)
7126 continue;
7127 if (ret < 0)
7128 goto error;
7129 break;
7130 }
David Sterbad85327b12020-07-08 22:55:14 +02007131 /*
7132 * The nodes on level 1 are not locked but we don't need to do
7133 * that during mount time as nothing else can access the tree
7134 */
7135 node = path->nodes[1];
7136 if (node) {
7137 if (last_ra_node != node->start) {
7138 readahead_tree_node_children(node);
7139 last_ra_node = node->start;
7140 }
7141 }
Chris Mason0b86a832008-03-24 15:01:56 -04007142 btrfs_item_key_to_cpu(leaf, &found_key, slot);
Filipe David Borba Manana395927a2013-07-30 12:03:04 +01007143 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7144 struct btrfs_dev_item *dev_item;
7145 dev_item = btrfs_item_ptr(leaf, slot,
Chris Mason0b86a832008-03-24 15:01:56 -04007146 struct btrfs_dev_item);
David Sterba17850752019-03-20 16:45:15 +01007147 ret = read_one_dev(leaf, dev_item);
Filipe David Borba Manana395927a2013-07-30 12:03:04 +01007148 if (ret)
7149 goto error;
Liu Bo99e3ecf2016-06-03 12:05:14 -07007150 total_dev++;
Chris Mason0b86a832008-03-24 15:01:56 -04007151 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7152 struct btrfs_chunk *chunk;
7153 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
Josef Bacik01d01ca2020-07-17 15:12:28 -04007154 mutex_lock(&fs_info->chunk_mutex);
David Sterba9690ac02019-03-20 16:43:07 +01007155 ret = read_one_chunk(&found_key, leaf, chunk);
Josef Bacik01d01ca2020-07-17 15:12:28 -04007156 mutex_unlock(&fs_info->chunk_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05007157 if (ret)
7158 goto error;
Chris Mason0b86a832008-03-24 15:01:56 -04007159 }
7160 path->slots[0]++;
7161 }
Liu Bo99e3ecf2016-06-03 12:05:14 -07007162
7163 /*
7164 * After loading chunk tree, we've got all device information,
7165 * do another round of validation checks.
7166 */
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007167 if (total_dev != fs_info->fs_devices->total_devices) {
7168 btrfs_err(fs_info,
Liu Bo99e3ecf2016-06-03 12:05:14 -07007169 "super_num_devices %llu mismatch with num_devices %llu found here",
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007170 btrfs_super_num_devices(fs_info->super_copy),
Liu Bo99e3ecf2016-06-03 12:05:14 -07007171 total_dev);
7172 ret = -EINVAL;
7173 goto error;
7174 }
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007175 if (btrfs_super_total_bytes(fs_info->super_copy) <
7176 fs_info->fs_devices->total_rw_bytes) {
7177 btrfs_err(fs_info,
Liu Bo99e3ecf2016-06-03 12:05:14 -07007178 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007179 btrfs_super_total_bytes(fs_info->super_copy),
7180 fs_info->fs_devices->total_rw_bytes);
Liu Bo99e3ecf2016-06-03 12:05:14 -07007181 ret = -EINVAL;
7182 goto error;
7183 }
Chris Mason0b86a832008-03-24 15:01:56 -04007184 ret = 0;
7185error:
Li Zefanb367e472011-12-07 11:38:24 +08007186 mutex_unlock(&uuid_mutex);
7187
Yan Zheng2b820322008-11-17 21:11:30 -05007188 btrfs_free_path(path);
Chris Mason0b86a832008-03-24 15:01:56 -04007189 return ret;
7190}
Stefan Behrens442a4f62012-05-25 16:06:08 +02007191
Miao Xiecb517ea2013-05-15 07:48:19 +00007192void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7193{
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007194 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
Miao Xiecb517ea2013-05-15 07:48:19 +00007195 struct btrfs_device *device;
7196
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007197 fs_devices->fs_info = fs_info;
Liu Bo29cc83f2014-05-11 23:14:59 +08007198
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007199 mutex_lock(&fs_devices->device_list_mutex);
7200 list_for_each_entry(device, &fs_devices->devices, dev_list)
7201 device->fs_info = fs_info;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007202
7203 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007204 list_for_each_entry(device, &seed_devs->devices, dev_list)
7205 device->fs_info = fs_info;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007206
7207 seed_devs->fs_info = fs_info;
Liu Bo29cc83f2014-05-11 23:14:59 +08007208 }
Anand Jaine17125b2020-09-05 01:34:31 +08007209 mutex_unlock(&fs_devices->device_list_mutex);
Miao Xiecb517ea2013-05-15 07:48:19 +00007210}
7211
David Sterba1dc990d2019-08-21 20:05:32 +02007212static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7213 const struct btrfs_dev_stats_item *ptr,
7214 int index)
7215{
7216 u64 val;
7217
7218 read_extent_buffer(eb, &val,
7219 offsetof(struct btrfs_dev_stats_item, values) +
7220 ((unsigned long)ptr) + (index * sizeof(u64)),
7221 sizeof(val));
7222 return val;
7223}
7224
7225static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7226 struct btrfs_dev_stats_item *ptr,
7227 int index, u64 val)
7228{
7229 write_extent_buffer(eb, &val,
7230 offsetof(struct btrfs_dev_stats_item, values) +
7231 ((unsigned long)ptr) + (index * sizeof(u64)),
7232 sizeof(val));
7233}
7234
Josef Bacik92e26df2020-09-18 16:44:33 -04007235static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7236 struct btrfs_path *path)
Josef Bacik124604e2020-09-18 16:44:32 -04007237{
7238 struct btrfs_dev_stats_item *ptr;
7239 struct extent_buffer *eb;
7240 struct btrfs_key key;
7241 int item_size;
7242 int i, ret, slot;
7243
7244 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7245 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7246 key.offset = device->devid;
7247 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7248 if (ret) {
7249 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7250 btrfs_dev_stat_set(device, i, 0);
7251 device->dev_stats_valid = 1;
7252 btrfs_release_path(path);
Josef Bacik92e26df2020-09-18 16:44:33 -04007253 return ret < 0 ? ret : 0;
Josef Bacik124604e2020-09-18 16:44:32 -04007254 }
7255 slot = path->slots[0];
7256 eb = path->nodes[0];
7257 item_size = btrfs_item_size_nr(eb, slot);
7258
7259 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7260
7261 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7262 if (item_size >= (1 + i) * sizeof(__le64))
7263 btrfs_dev_stat_set(device, i,
7264 btrfs_dev_stats_value(eb, ptr, i));
7265 else
7266 btrfs_dev_stat_set(device, i, 0);
7267 }
7268
7269 device->dev_stats_valid = 1;
7270 btrfs_dev_stat_print_on_load(device);
7271 btrfs_release_path(path);
Josef Bacik92e26df2020-09-18 16:44:33 -04007272
7273 return 0;
Josef Bacik124604e2020-09-18 16:44:32 -04007274}
7275
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007276int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7277{
Josef Bacik124604e2020-09-18 16:44:32 -04007278 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007279 struct btrfs_device *device;
7280 struct btrfs_path *path = NULL;
Josef Bacik92e26df2020-09-18 16:44:33 -04007281 int ret = 0;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007282
7283 path = btrfs_alloc_path();
Anand Jain3b80a9842019-08-21 17:26:32 +08007284 if (!path)
7285 return -ENOMEM;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007286
7287 mutex_lock(&fs_devices->device_list_mutex);
Josef Bacik92e26df2020-09-18 16:44:33 -04007288 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7289 ret = btrfs_device_init_dev_stats(device, path);
7290 if (ret)
7291 goto out;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007292 }
Josef Bacik92e26df2020-09-18 16:44:33 -04007293 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7294 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7295 ret = btrfs_device_init_dev_stats(device, path);
7296 if (ret)
7297 goto out;
7298 }
7299 }
7300out:
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007301 mutex_unlock(&fs_devices->device_list_mutex);
7302
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007303 btrfs_free_path(path);
Josef Bacik92e26df2020-09-18 16:44:33 -04007304 return ret;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007305}
7306
7307static int update_dev_stat_item(struct btrfs_trans_handle *trans,
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007308 struct btrfs_device *device)
7309{
Nikolay Borisov5495f192018-07-20 19:37:49 +03007310 struct btrfs_fs_info *fs_info = trans->fs_info;
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04007311 struct btrfs_root *dev_root = fs_info->dev_root;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007312 struct btrfs_path *path;
7313 struct btrfs_key key;
7314 struct extent_buffer *eb;
7315 struct btrfs_dev_stats_item *ptr;
7316 int ret;
7317 int i;
7318
David Sterba242e2952016-01-25 17:51:31 +01007319 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7320 key.type = BTRFS_PERSISTENT_ITEM_KEY;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007321 key.offset = device->devid;
7322
7323 path = btrfs_alloc_path();
David Sterbafa252992017-02-15 09:35:01 +01007324 if (!path)
7325 return -ENOMEM;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007326 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7327 if (ret < 0) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007328 btrfs_warn_in_rcu(fs_info,
David Sterbaecaeb142015-10-08 09:01:03 +02007329 "error %d while searching for dev_stats item for device %s",
Josef Bacik606686e2012-06-04 14:03:51 -04007330 ret, rcu_str_deref(device->name));
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007331 goto out;
7332 }
7333
7334 if (ret == 0 &&
7335 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7336 /* need to delete old one and insert a new one */
7337 ret = btrfs_del_item(trans, dev_root, path);
7338 if (ret != 0) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007339 btrfs_warn_in_rcu(fs_info,
David Sterbaecaeb142015-10-08 09:01:03 +02007340 "delete too small dev_stats item for device %s failed %d",
Josef Bacik606686e2012-06-04 14:03:51 -04007341 rcu_str_deref(device->name), ret);
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007342 goto out;
7343 }
7344 ret = 1;
7345 }
7346
7347 if (ret == 1) {
7348 /* need to insert a new item */
7349 btrfs_release_path(path);
7350 ret = btrfs_insert_empty_item(trans, dev_root, path,
7351 &key, sizeof(*ptr));
7352 if (ret < 0) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007353 btrfs_warn_in_rcu(fs_info,
David Sterbaecaeb142015-10-08 09:01:03 +02007354 "insert dev_stats item for device %s failed %d",
7355 rcu_str_deref(device->name), ret);
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007356 goto out;
7357 }
7358 }
7359
7360 eb = path->nodes[0];
7361 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7362 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7363 btrfs_set_dev_stats_value(eb, ptr, i,
7364 btrfs_dev_stat_read(device, i));
7365 btrfs_mark_buffer_dirty(eb);
7366
7367out:
7368 btrfs_free_path(path);
7369 return ret;
7370}
7371
7372/*
7373 * called from commit_transaction. Writes all changed device stats to disk.
7374 */
David Sterba196c9d82019-03-20 16:50:38 +01007375int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007376{
David Sterba196c9d82019-03-20 16:50:38 +01007377 struct btrfs_fs_info *fs_info = trans->fs_info;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007378 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7379 struct btrfs_device *device;
Miao Xieaddc3fa2014-07-24 11:37:11 +08007380 int stats_cnt;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007381 int ret = 0;
7382
7383 mutex_lock(&fs_devices->device_list_mutex);
7384 list_for_each_entry(device, &fs_devices->devices, dev_list) {
Nikolay Borisov9deae962017-10-24 13:47:37 +03007385 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7386 if (!device->dev_stats_valid || stats_cnt == 0)
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007387 continue;
7388
Nikolay Borisov9deae962017-10-24 13:47:37 +03007389
7390 /*
7391 * There is a LOAD-LOAD control dependency between the value of
7392 * dev_stats_ccnt and updating the on-disk values which requires
7393 * reading the in-memory counters. Such control dependencies
7394 * require explicit read memory barriers.
7395 *
7396 * This memory barriers pairs with smp_mb__before_atomic in
7397 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7398 * barrier implied by atomic_xchg in
7399 * btrfs_dev_stats_read_and_reset
7400 */
7401 smp_rmb();
7402
Nikolay Borisov5495f192018-07-20 19:37:49 +03007403 ret = update_dev_stat_item(trans, device);
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007404 if (!ret)
Miao Xieaddc3fa2014-07-24 11:37:11 +08007405 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007406 }
7407 mutex_unlock(&fs_devices->device_list_mutex);
7408
7409 return ret;
7410}
7411
Stefan Behrens442a4f62012-05-25 16:06:08 +02007412void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7413{
7414 btrfs_dev_stat_inc(dev, index);
7415 btrfs_dev_stat_print_on_error(dev);
7416}
7417
Eric Sandeen48a3b632013-04-25 20:41:01 +00007418static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
Stefan Behrens442a4f62012-05-25 16:06:08 +02007419{
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007420 if (!dev->dev_stats_valid)
7421 return;
Jeff Mahoneyfb456252016-06-22 18:54:56 -04007422 btrfs_err_rl_in_rcu(dev->fs_info,
David Sterbab14af3b2015-10-08 10:43:10 +02007423 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
Josef Bacik606686e2012-06-04 14:03:51 -04007424 rcu_str_deref(dev->name),
Stefan Behrens442a4f62012-05-25 16:06:08 +02007425 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7426 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7427 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
Frank Holtonefe120a2013-12-20 11:37:06 -05007428 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7429 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
Stefan Behrens442a4f62012-05-25 16:06:08 +02007430}
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007431
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007432static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7433{
Stefan Behrensa98cdb82012-07-17 09:02:11 -06007434 int i;
7435
7436 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7437 if (btrfs_dev_stat_read(dev, i) != 0)
7438 break;
7439 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7440 return; /* all values == 0, suppress message */
7441
Jeff Mahoneyfb456252016-06-22 18:54:56 -04007442 btrfs_info_in_rcu(dev->fs_info,
David Sterbaecaeb142015-10-08 09:01:03 +02007443 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
Josef Bacik606686e2012-06-04 14:03:51 -04007444 rcu_str_deref(dev->name),
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007445 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7446 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7447 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7448 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7449 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7450}
7451
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04007452int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
David Sterbab27f7c02012-06-22 06:30:39 -06007453 struct btrfs_ioctl_get_dev_stats *stats)
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007454{
7455 struct btrfs_device *dev;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007456 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007457 int i;
7458
7459 mutex_lock(&fs_devices->device_list_mutex);
Anand Jain09ba3bc2019-01-19 14:48:55 +08007460 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7461 true);
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007462 mutex_unlock(&fs_devices->device_list_mutex);
7463
7464 if (!dev) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007465 btrfs_warn(fs_info, "get dev_stats failed, device not found");
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007466 return -ENODEV;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007467 } else if (!dev->dev_stats_valid) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007468 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007469 return -ENODEV;
David Sterbab27f7c02012-06-22 06:30:39 -06007470 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007471 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7472 if (stats->nr_items > i)
7473 stats->values[i] =
7474 btrfs_dev_stat_read_and_reset(dev, i);
7475 else
Anand Jain4e411a72019-08-07 16:21:19 +08007476 btrfs_dev_stat_set(dev, i, 0);
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007477 }
Anand Jaina69976b2020-01-10 12:26:34 +08007478 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7479 current->comm, task_pid_nr(current));
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007480 } else {
7481 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7482 if (stats->nr_items > i)
7483 stats->values[i] = btrfs_dev_stat_read(dev, i);
7484 }
7485 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7486 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7487 return 0;
7488}
Stefan Behrensa8a6dab2012-11-05 15:50:14 +01007489
Miao Xie935e5cc2014-09-03 21:35:33 +08007490/*
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007491 * Update the size and bytes used for each device where it changed. This is
7492 * delayed since we would otherwise get errors while writing out the
7493 * superblocks.
7494 *
7495 * Must be invoked during transaction commit.
Miao Xie935e5cc2014-09-03 21:35:33 +08007496 */
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007497void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
Miao Xie935e5cc2014-09-03 21:35:33 +08007498{
Miao Xie935e5cc2014-09-03 21:35:33 +08007499 struct btrfs_device *curr, *next;
7500
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007501 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7502
7503 if (list_empty(&trans->dev_update_list))
Miao Xie935e5cc2014-09-03 21:35:33 +08007504 return;
7505
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007506 /*
7507 * We don't need the device_list_mutex here. This list is owned by the
7508 * transaction and the transaction must complete before the device is
7509 * released.
7510 */
7511 mutex_lock(&trans->fs_info->chunk_mutex);
7512 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7513 post_commit_list) {
7514 list_del_init(&curr->post_commit_list);
Miao Xie935e5cc2014-09-03 21:35:33 +08007515 curr->commit_total_bytes = curr->disk_total_bytes;
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007516 curr->commit_bytes_used = curr->bytes_used;
Miao Xie935e5cc2014-09-03 21:35:33 +08007517 }
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007518 mutex_unlock(&trans->fs_info->chunk_mutex);
Miao Xiece7213c2014-09-03 21:35:34 +08007519}
Anand Jain5a13f432015-03-10 06:38:31 +08007520
David Sterba46df06b2018-07-13 20:46:30 +02007521/*
7522 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7523 */
7524int btrfs_bg_type_to_factor(u64 flags)
7525{
David Sterba44b28ad2019-05-17 11:43:31 +02007526 const int index = btrfs_bg_flags_to_raid_index(flags);
7527
7528 return btrfs_raid_array[index].ncopies;
David Sterba46df06b2018-07-13 20:46:30 +02007529}
Qu Wenruocf90d882018-08-01 10:37:19 +08007530
7531
Qu Wenruocf90d882018-08-01 10:37:19 +08007532
7533static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7534 u64 chunk_offset, u64 devid,
7535 u64 physical_offset, u64 physical_len)
7536{
David Sterbac8bf1b62019-05-17 11:43:17 +02007537 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
Qu Wenruocf90d882018-08-01 10:37:19 +08007538 struct extent_map *em;
7539 struct map_lookup *map;
Qu Wenruo05a37c42018-10-05 17:45:55 +08007540 struct btrfs_device *dev;
Qu Wenruocf90d882018-08-01 10:37:19 +08007541 u64 stripe_len;
7542 bool found = false;
7543 int ret = 0;
7544 int i;
7545
7546 read_lock(&em_tree->lock);
7547 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7548 read_unlock(&em_tree->lock);
7549
7550 if (!em) {
7551 btrfs_err(fs_info,
7552"dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7553 physical_offset, devid);
7554 ret = -EUCLEAN;
7555 goto out;
7556 }
7557
7558 map = em->map_lookup;
7559 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7560 if (physical_len != stripe_len) {
7561 btrfs_err(fs_info,
7562"dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7563 physical_offset, devid, em->start, physical_len,
7564 stripe_len);
7565 ret = -EUCLEAN;
7566 goto out;
7567 }
7568
7569 for (i = 0; i < map->num_stripes; i++) {
7570 if (map->stripes[i].dev->devid == devid &&
7571 map->stripes[i].physical == physical_offset) {
7572 found = true;
7573 if (map->verified_stripes >= map->num_stripes) {
7574 btrfs_err(fs_info,
7575 "too many dev extents for chunk %llu found",
7576 em->start);
7577 ret = -EUCLEAN;
7578 goto out;
7579 }
7580 map->verified_stripes++;
7581 break;
7582 }
7583 }
7584 if (!found) {
7585 btrfs_err(fs_info,
7586 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7587 physical_offset, devid);
7588 ret = -EUCLEAN;
7589 }
Qu Wenruo05a37c42018-10-05 17:45:55 +08007590
7591 /* Make sure no dev extent is beyond device bondary */
Anand Jain09ba3bc2019-01-19 14:48:55 +08007592 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
Qu Wenruo05a37c42018-10-05 17:45:55 +08007593 if (!dev) {
7594 btrfs_err(fs_info, "failed to find devid %llu", devid);
7595 ret = -EUCLEAN;
7596 goto out;
7597 }
Qu Wenruo1b3922a2019-01-08 14:08:18 +08007598
7599 /* It's possible this device is a dummy for seed device */
7600 if (dev->disk_total_bytes == 0) {
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007601 struct btrfs_fs_devices *devs;
7602
7603 devs = list_first_entry(&fs_info->fs_devices->seed_list,
7604 struct btrfs_fs_devices, seed_list);
7605 dev = btrfs_find_device(devs, devid, NULL, NULL, false);
Qu Wenruo1b3922a2019-01-08 14:08:18 +08007606 if (!dev) {
7607 btrfs_err(fs_info, "failed to find seed devid %llu",
7608 devid);
7609 ret = -EUCLEAN;
7610 goto out;
7611 }
7612 }
7613
Qu Wenruo05a37c42018-10-05 17:45:55 +08007614 if (physical_offset + physical_len > dev->disk_total_bytes) {
7615 btrfs_err(fs_info,
7616"dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7617 devid, physical_offset, physical_len,
7618 dev->disk_total_bytes);
7619 ret = -EUCLEAN;
7620 goto out;
7621 }
Qu Wenruocf90d882018-08-01 10:37:19 +08007622out:
7623 free_extent_map(em);
7624 return ret;
7625}
7626
7627static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7628{
David Sterbac8bf1b62019-05-17 11:43:17 +02007629 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
Qu Wenruocf90d882018-08-01 10:37:19 +08007630 struct extent_map *em;
7631 struct rb_node *node;
7632 int ret = 0;
7633
7634 read_lock(&em_tree->lock);
Liu Bo07e1ce02018-08-23 03:51:52 +08007635 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
Qu Wenruocf90d882018-08-01 10:37:19 +08007636 em = rb_entry(node, struct extent_map, rb_node);
7637 if (em->map_lookup->num_stripes !=
7638 em->map_lookup->verified_stripes) {
7639 btrfs_err(fs_info,
7640 "chunk %llu has missing dev extent, have %d expect %d",
7641 em->start, em->map_lookup->verified_stripes,
7642 em->map_lookup->num_stripes);
7643 ret = -EUCLEAN;
7644 goto out;
7645 }
7646 }
7647out:
7648 read_unlock(&em_tree->lock);
7649 return ret;
7650}
7651
7652/*
7653 * Ensure that all dev extents are mapped to correct chunk, otherwise
7654 * later chunk allocation/free would cause unexpected behavior.
7655 *
7656 * NOTE: This will iterate through the whole device tree, which should be of
7657 * the same size level as the chunk tree. This slightly increases mount time.
7658 */
7659int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7660{
7661 struct btrfs_path *path;
7662 struct btrfs_root *root = fs_info->dev_root;
7663 struct btrfs_key key;
Qu Wenruo5eb19382018-10-05 17:45:54 +08007664 u64 prev_devid = 0;
7665 u64 prev_dev_ext_end = 0;
Qu Wenruocf90d882018-08-01 10:37:19 +08007666 int ret = 0;
7667
7668 key.objectid = 1;
7669 key.type = BTRFS_DEV_EXTENT_KEY;
7670 key.offset = 0;
7671
7672 path = btrfs_alloc_path();
7673 if (!path)
7674 return -ENOMEM;
7675
7676 path->reada = READA_FORWARD;
7677 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7678 if (ret < 0)
7679 goto out;
7680
7681 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7682 ret = btrfs_next_item(root, path);
7683 if (ret < 0)
7684 goto out;
7685 /* No dev extents at all? Not good */
7686 if (ret > 0) {
7687 ret = -EUCLEAN;
7688 goto out;
7689 }
7690 }
7691 while (1) {
7692 struct extent_buffer *leaf = path->nodes[0];
7693 struct btrfs_dev_extent *dext;
7694 int slot = path->slots[0];
7695 u64 chunk_offset;
7696 u64 physical_offset;
7697 u64 physical_len;
7698 u64 devid;
7699
7700 btrfs_item_key_to_cpu(leaf, &key, slot);
7701 if (key.type != BTRFS_DEV_EXTENT_KEY)
7702 break;
7703 devid = key.objectid;
7704 physical_offset = key.offset;
7705
7706 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7707 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7708 physical_len = btrfs_dev_extent_length(leaf, dext);
7709
Qu Wenruo5eb19382018-10-05 17:45:54 +08007710 /* Check if this dev extent overlaps with the previous one */
7711 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7712 btrfs_err(fs_info,
7713"dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7714 devid, physical_offset, prev_dev_ext_end);
7715 ret = -EUCLEAN;
7716 goto out;
7717 }
7718
Qu Wenruocf90d882018-08-01 10:37:19 +08007719 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7720 physical_offset, physical_len);
7721 if (ret < 0)
7722 goto out;
Qu Wenruo5eb19382018-10-05 17:45:54 +08007723 prev_devid = devid;
7724 prev_dev_ext_end = physical_offset + physical_len;
7725
Qu Wenruocf90d882018-08-01 10:37:19 +08007726 ret = btrfs_next_item(root, path);
7727 if (ret < 0)
7728 goto out;
7729 if (ret > 0) {
7730 ret = 0;
7731 break;
7732 }
7733 }
7734
7735 /* Ensure all chunks have corresponding dev extents */
7736 ret = verify_chunk_dev_extent_mapping(fs_info);
7737out:
7738 btrfs_free_path(path);
7739 return ret;
7740}
Omar Sandovaleede2bf2016-11-03 10:28:12 -07007741
7742/*
7743 * Check whether the given block group or device is pinned by any inode being
7744 * used as a swapfile.
7745 */
7746bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7747{
7748 struct btrfs_swapfile_pin *sp;
7749 struct rb_node *node;
7750
7751 spin_lock(&fs_info->swapfile_pins_lock);
7752 node = fs_info->swapfile_pins.rb_node;
7753 while (node) {
7754 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7755 if (ptr < sp->ptr)
7756 node = node->rb_left;
7757 else if (ptr > sp->ptr)
7758 node = node->rb_right;
7759 else
7760 break;
7761 }
7762 spin_unlock(&fs_info->swapfile_pins_lock);
7763 return node != NULL;
7764}