blob: 01127a4dfe91e61cb37c0439e0ad66f6cdf8aea8 [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"
Naohiro Aota5b316462020-11-10 20:26:07 +090034#include "zoned.h"
Chris Mason0b86a832008-03-24 15:01:56 -040035
Zhao Leiaf902042015-09-15 21:08:06 +080036const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
37 [BTRFS_RAID_RAID10] = {
38 .sub_stripes = 2,
39 .dev_stripes = 1,
40 .devs_max = 0, /* 0 == as many as possible */
41 .devs_min = 4,
Zhao Lei8789f4f2015-09-15 21:08:07 +080042 .tolerated_failures = 1,
Zhao Leiaf902042015-09-15 21:08:06 +080043 .devs_increment = 2,
44 .ncopies = 2,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +020045 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +080046 .raid_name = "raid10",
Anand Jain41a6e892018-04-25 19:01:43 +080047 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
Anand Jainf9fbcaa2018-04-25 19:01:44 +080048 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
Zhao Leiaf902042015-09-15 21:08:06 +080049 },
50 [BTRFS_RAID_RAID1] = {
51 .sub_stripes = 1,
52 .dev_stripes = 1,
53 .devs_max = 2,
54 .devs_min = 2,
Zhao Lei8789f4f2015-09-15 21:08:07 +080055 .tolerated_failures = 1,
Zhao Leiaf902042015-09-15 21:08:06 +080056 .devs_increment = 2,
57 .ncopies = 2,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +020058 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +080059 .raid_name = "raid1",
Anand Jain41a6e892018-04-25 19:01:43 +080060 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
Anand Jainf9fbcaa2018-04-25 19:01:44 +080061 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
Zhao Leiaf902042015-09-15 21:08:06 +080062 },
David Sterba47e6f742018-03-02 22:56:53 +010063 [BTRFS_RAID_RAID1C3] = {
64 .sub_stripes = 1,
65 .dev_stripes = 1,
David Sterbacf93e152019-11-27 16:10:54 +010066 .devs_max = 3,
David Sterba47e6f742018-03-02 22:56:53 +010067 .devs_min = 3,
68 .tolerated_failures = 2,
69 .devs_increment = 3,
70 .ncopies = 3,
David Sterbadb26a022019-11-25 15:34:48 +010071 .nparity = 0,
David Sterba47e6f742018-03-02 22:56:53 +010072 .raid_name = "raid1c3",
73 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
74 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
75 },
David Sterba8d6fac02018-03-02 22:56:53 +010076 [BTRFS_RAID_RAID1C4] = {
77 .sub_stripes = 1,
78 .dev_stripes = 1,
David Sterbacf93e152019-11-27 16:10:54 +010079 .devs_max = 4,
David Sterba8d6fac02018-03-02 22:56:53 +010080 .devs_min = 4,
81 .tolerated_failures = 3,
82 .devs_increment = 4,
83 .ncopies = 4,
David Sterbadb26a022019-11-25 15:34:48 +010084 .nparity = 0,
David Sterba8d6fac02018-03-02 22:56:53 +010085 .raid_name = "raid1c4",
86 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
87 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
88 },
Zhao Leiaf902042015-09-15 21:08:06 +080089 [BTRFS_RAID_DUP] = {
90 .sub_stripes = 1,
91 .dev_stripes = 2,
92 .devs_max = 1,
93 .devs_min = 1,
Zhao Lei8789f4f2015-09-15 21:08:07 +080094 .tolerated_failures = 0,
Zhao Leiaf902042015-09-15 21:08:06 +080095 .devs_increment = 1,
96 .ncopies = 2,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +020097 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +080098 .raid_name = "dup",
Anand Jain41a6e892018-04-25 19:01:43 +080099 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800100 .mindev_error = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800101 },
102 [BTRFS_RAID_RAID0] = {
103 .sub_stripes = 1,
104 .dev_stripes = 1,
105 .devs_max = 0,
106 .devs_min = 2,
Zhao Lei8789f4f2015-09-15 21:08:07 +0800107 .tolerated_failures = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800108 .devs_increment = 1,
109 .ncopies = 1,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +0200110 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +0800111 .raid_name = "raid0",
Anand Jain41a6e892018-04-25 19:01:43 +0800112 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800113 .mindev_error = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800114 },
115 [BTRFS_RAID_SINGLE] = {
116 .sub_stripes = 1,
117 .dev_stripes = 1,
118 .devs_max = 1,
119 .devs_min = 1,
Zhao Lei8789f4f2015-09-15 21:08:07 +0800120 .tolerated_failures = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800121 .devs_increment = 1,
122 .ncopies = 1,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +0200123 .nparity = 0,
Anand Jained234672018-04-25 19:01:42 +0800124 .raid_name = "single",
Anand Jain41a6e892018-04-25 19:01:43 +0800125 .bg_flag = 0,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800126 .mindev_error = 0,
Zhao Leiaf902042015-09-15 21:08:06 +0800127 },
128 [BTRFS_RAID_RAID5] = {
129 .sub_stripes = 1,
130 .dev_stripes = 1,
131 .devs_max = 0,
132 .devs_min = 2,
Zhao Lei8789f4f2015-09-15 21:08:07 +0800133 .tolerated_failures = 1,
Zhao Leiaf902042015-09-15 21:08:06 +0800134 .devs_increment = 1,
Hans van Kranenburgda612e32018-10-04 23:24:41 +0200135 .ncopies = 1,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +0200136 .nparity = 1,
Anand Jained234672018-04-25 19:01:42 +0800137 .raid_name = "raid5",
Anand Jain41a6e892018-04-25 19:01:43 +0800138 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800139 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
Zhao Leiaf902042015-09-15 21:08:06 +0800140 },
141 [BTRFS_RAID_RAID6] = {
142 .sub_stripes = 1,
143 .dev_stripes = 1,
144 .devs_max = 0,
145 .devs_min = 3,
Zhao Lei8789f4f2015-09-15 21:08:07 +0800146 .tolerated_failures = 2,
Zhao Leiaf902042015-09-15 21:08:06 +0800147 .devs_increment = 1,
Hans van Kranenburgda612e32018-10-04 23:24:41 +0200148 .ncopies = 1,
Hans van Kranenburgb50836e2018-10-04 23:24:42 +0200149 .nparity = 2,
Anand Jained234672018-04-25 19:01:42 +0800150 .raid_name = "raid6",
Anand Jain41a6e892018-04-25 19:01:43 +0800151 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
Anand Jainf9fbcaa2018-04-25 19:01:44 +0800152 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
Zhao Leiaf902042015-09-15 21:08:06 +0800153 },
154};
155
David Sterba158da512019-05-17 11:43:41 +0200156const char *btrfs_bg_type_to_raid_name(u64 flags)
Anand Jained234672018-04-25 19:01:42 +0800157{
David Sterba158da512019-05-17 11:43:41 +0200158 const int index = btrfs_bg_flags_to_raid_index(flags);
159
160 if (index >= BTRFS_NR_RAID_TYPES)
Anand Jained234672018-04-25 19:01:42 +0800161 return NULL;
162
David Sterba158da512019-05-17 11:43:41 +0200163 return btrfs_raid_array[index].raid_name;
Anand Jained234672018-04-25 19:01:42 +0800164}
165
Anand Jainf89e09c2018-11-20 16:12:55 +0800166/*
167 * Fill @buf with textual description of @bg_flags, no more than @size_buf
168 * bytes including terminating null byte.
169 */
170void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
171{
172 int i;
173 int ret;
174 char *bp = buf;
175 u64 flags = bg_flags;
176 u32 size_bp = size_buf;
177
178 if (!flags) {
179 strcpy(bp, "NONE");
180 return;
181 }
182
183#define DESCRIBE_FLAG(flag, desc) \
184 do { \
185 if (flags & (flag)) { \
186 ret = snprintf(bp, size_bp, "%s|", (desc)); \
187 if (ret < 0 || ret >= size_bp) \
188 goto out_overflow; \
189 size_bp -= ret; \
190 bp += ret; \
191 flags &= ~(flag); \
192 } \
193 } while (0)
194
195 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
196 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
197 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
198
199 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
200 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
201 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
202 btrfs_raid_array[i].raid_name);
203#undef DESCRIBE_FLAG
204
205 if (flags) {
206 ret = snprintf(bp, size_bp, "0x%llx|", flags);
207 size_bp -= ret;
208 }
209
210 if (size_bp < size_buf)
211 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
212
213 /*
214 * The text is trimmed, it's up to the caller to provide sufficiently
215 * large buffer
216 */
217out_overflow:;
218}
219
David Sterba6f8e0fc2019-03-20 16:29:13 +0100220static int init_first_rw_device(struct btrfs_trans_handle *trans);
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400221static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
Eric Sandeen48a3b632013-04-25 20:41:01 +0000222static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
Stefan Behrens733f4fb2012-05-25 16:06:10 +0200223static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
Liu Bo5ab56092017-03-14 13:33:57 -0700224static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
225 enum btrfs_map_op op,
226 u64 logical, u64 *length,
227 struct btrfs_bio **bbio_ret,
228 int mirror_num, int need_raid_map);
Yan Zheng2b820322008-11-17 21:11:30 -0500229
David Sterba9c6b1c42017-06-16 22:30:00 +0200230/*
231 * Device locking
232 * ==============
233 *
234 * There are several mutexes that protect manipulation of devices and low-level
235 * structures like chunks but not block groups, extents or files
236 *
237 * uuid_mutex (global lock)
238 * ------------------------
239 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
240 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
241 * device) or requested by the device= mount option
242 *
243 * the mutex can be very coarse and can cover long-running operations
244 *
245 * protects: updates to fs_devices counters like missing devices, rw devices,
Andrea Gelmini52042d82018-11-28 12:05:13 +0100246 * seeding, structure cloning, opening/closing devices at mount/umount time
David Sterba9c6b1c42017-06-16 22:30:00 +0200247 *
248 * global::fs_devs - add, remove, updates to the global list
249 *
Josef Bacik18c850f2020-07-17 15:12:27 -0400250 * does not protect: manipulation of the fs_devices::devices list in general
251 * but in mount context it could be used to exclude list modifications by eg.
252 * scan ioctl
David Sterba9c6b1c42017-06-16 22:30:00 +0200253 *
254 * btrfs_device::name - renames (write side), read is RCU
255 *
256 * fs_devices::device_list_mutex (per-fs, with RCU)
257 * ------------------------------------------------
258 * protects updates to fs_devices::devices, ie. adding and deleting
259 *
260 * simple list traversal with read-only actions can be done with RCU protection
261 *
262 * may be used to exclude some operations from running concurrently without any
263 * modifications to the list (see write_all_supers)
264 *
Josef Bacik18c850f2020-07-17 15:12:27 -0400265 * Is not required at mount and close times, because our device list is
266 * protected by the uuid_mutex at that point.
267 *
David Sterba9c6b1c42017-06-16 22:30:00 +0200268 * balance_mutex
269 * -------------
270 * protects balance structures (status, state) and context accessed from
271 * several places (internally, ioctl)
272 *
273 * chunk_mutex
274 * -----------
275 * protects chunks, adding or removing during allocation, trim or when a new
Nikolay Borisov0b6f5d42019-05-09 18:11:11 +0300276 * device is added/removed. Additionally it also protects post_commit_list of
277 * individual devices, since they can be added to the transaction's
278 * post_commit_list only with chunk_mutex held.
David Sterba9c6b1c42017-06-16 22:30:00 +0200279 *
280 * cleaner_mutex
281 * -------------
282 * a big lock that is held by the cleaner thread and prevents running subvolume
283 * cleaning together with relocation or delayed iputs
284 *
285 *
286 * Lock nesting
287 * ============
288 *
289 * uuid_mutex
Anand Jainae3e7152020-05-14 01:42:45 +0800290 * device_list_mutex
291 * chunk_mutex
292 * balance_mutex
Anand Jain89595e82018-04-18 14:59:25 +0800293 *
294 *
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -0500295 * Exclusive operations
296 * ====================
Anand Jain89595e82018-04-18 14:59:25 +0800297 *
298 * Maintains the exclusivity of the following operations that apply to the
299 * whole filesystem and cannot run in parallel.
300 *
301 * - Balance (*)
302 * - Device add
303 * - Device remove
304 * - Device replace (*)
305 * - Resize
306 *
307 * The device operations (as above) can be in one of the following states:
308 *
309 * - Running state
310 * - Paused state
311 * - Completed state
312 *
313 * Only device operations marked with (*) can go into the Paused state for the
314 * following reasons:
315 *
316 * - ioctl (only Balance can be Paused through ioctl)
317 * - filesystem remounted as read-only
318 * - filesystem unmounted and mounted as read-only
319 * - system power-cycle and filesystem mounted as read-only
320 * - filesystem or device errors leading to forced read-only
321 *
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -0500322 * The status of exclusive operation is set and cleared atomically.
323 * During the course of Paused state, fs_info::exclusive_operation remains set.
Anand Jain89595e82018-04-18 14:59:25 +0800324 * A device operation in Paused or Running state can be canceled or resumed
325 * either by ioctl (Balance only) or when remounted as read-write.
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -0500326 * The exclusive status is cleared when the device operation is canceled or
Anand Jain89595e82018-04-18 14:59:25 +0800327 * completed.
David Sterba9c6b1c42017-06-16 22:30:00 +0200328 */
329
Miao Xie67a2c452014-09-03 21:35:43 +0800330DEFINE_MUTEX(uuid_mutex);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400331static LIST_HEAD(fs_uuids);
David Sterba4143cb82019-10-01 19:57:37 +0200332struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
Anand Jainc73eccf2015-03-10 06:38:30 +0800333{
334 return &fs_uuids;
335}
Chris Mason8a4b83c2008-03-24 15:02:07 -0400336
David Sterba2dfeca92017-06-14 02:48:07 +0200337/*
338 * alloc_fs_devices - allocate struct btrfs_fs_devices
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200339 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
340 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
David Sterba2dfeca92017-06-14 02:48:07 +0200341 *
342 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
343 * The returned struct is not linked onto any lists and can be destroyed with
344 * kfree() right away.
345 */
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200346static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
347 const u8 *metadata_fsid)
Ilya Dryomov2208a372013-08-12 14:33:03 +0300348{
349 struct btrfs_fs_devices *fs_devs;
350
David Sterba78f2c9e2016-02-11 14:25:38 +0100351 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300352 if (!fs_devs)
353 return ERR_PTR(-ENOMEM);
354
355 mutex_init(&fs_devs->device_list_mutex);
356
357 INIT_LIST_HEAD(&fs_devs->devices);
358 INIT_LIST_HEAD(&fs_devs->alloc_list);
Anand Jainc4babc52018-04-12 10:29:25 +0800359 INIT_LIST_HEAD(&fs_devs->fs_list);
Nikolay Borisov944d3f92020-07-16 10:25:33 +0300360 INIT_LIST_HEAD(&fs_devs->seed_list);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300361 if (fsid)
362 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300363
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200364 if (metadata_fsid)
365 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
366 else if (fsid)
367 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
368
Ilya Dryomov2208a372013-08-12 14:33:03 +0300369 return fs_devs;
370}
371
David Sterbaa425f9d2018-03-20 15:47:33 +0100372void btrfs_free_device(struct btrfs_device *device)
David Sterba48dae9c2017-10-30 18:10:25 +0100373{
Nikolay Borisovbbbf7242019-03-25 14:31:22 +0200374 WARN_ON(!list_empty(&device->post_commit_list));
David Sterba48dae9c2017-10-30 18:10:25 +0100375 rcu_string_free(device->name);
Jeff Mahoney1c11b632019-03-27 14:24:12 +0200376 extent_io_tree_release(&device->alloc_state);
David Sterba48dae9c2017-10-30 18:10:25 +0100377 bio_put(device->flush_bio);
Naohiro Aota5b316462020-11-10 20:26:07 +0900378 btrfs_destroy_dev_zone_info(device);
David Sterba48dae9c2017-10-30 18:10:25 +0100379 kfree(device);
380}
381
Yan Zhenge4404d62008-12-12 10:03:26 -0500382static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
383{
384 struct btrfs_device *device;
385 WARN_ON(fs_devices->opened);
386 while (!list_empty(&fs_devices->devices)) {
387 device = list_entry(fs_devices->devices.next,
388 struct btrfs_device, dev_list);
389 list_del(&device->dev_list);
David Sterbaa425f9d2018-03-20 15:47:33 +0100390 btrfs_free_device(device);
Yan Zhenge4404d62008-12-12 10:03:26 -0500391 }
392 kfree(fs_devices);
393}
394
David Sterbaffc5a372018-02-19 17:24:15 +0100395void __exit btrfs_cleanup_fs_uuids(void)
Chris Mason8a4b83c2008-03-24 15:02:07 -0400396{
397 struct btrfs_fs_devices *fs_devices;
Chris Mason8a4b83c2008-03-24 15:02:07 -0400398
Yan Zheng2b820322008-11-17 21:11:30 -0500399 while (!list_empty(&fs_uuids)) {
400 fs_devices = list_entry(fs_uuids.next,
Anand Jainc4babc52018-04-12 10:29:25 +0800401 struct btrfs_fs_devices, fs_list);
402 list_del(&fs_devices->fs_list);
Yan Zhenge4404d62008-12-12 10:03:26 -0500403 free_fs_devices(fs_devices);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400404 }
Chris Mason8a4b83c2008-03-24 15:02:07 -0400405}
406
David Sterba48dae9c2017-10-30 18:10:25 +0100407/*
408 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
409 * Returned struct is not linked onto any lists and must be destroyed using
David Sterbaa425f9d2018-03-20 15:47:33 +0100410 * btrfs_free_device.
David Sterba48dae9c2017-10-30 18:10:25 +0100411 */
Qu Wenruo154f7cb2020-08-20 15:42:46 +0800412static struct btrfs_device *__alloc_device(struct btrfs_fs_info *fs_info)
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300413{
414 struct btrfs_device *dev;
415
David Sterba78f2c9e2016-02-11 14:25:38 +0100416 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300417 if (!dev)
418 return ERR_PTR(-ENOMEM);
419
David Sterbae0ae9992017-06-06 17:06:06 +0200420 /*
421 * Preallocate a bio that's always going to be used for flushing device
422 * barriers and matches the device lifespan
423 */
Christoph Hellwig616c6a62021-01-26 15:52:32 +0100424 dev->flush_bio = bio_kmalloc(GFP_KERNEL, 0);
David Sterbae0ae9992017-06-06 17:06:06 +0200425 if (!dev->flush_bio) {
426 kfree(dev);
427 return ERR_PTR(-ENOMEM);
428 }
David Sterbae0ae9992017-06-06 17:06:06 +0200429
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300430 INIT_LIST_HEAD(&dev->dev_list);
431 INIT_LIST_HEAD(&dev->dev_alloc_list);
Nikolay Borisovbbbf7242019-03-25 14:31:22 +0200432 INIT_LIST_HEAD(&dev->post_commit_list);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300433
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300434 atomic_set(&dev->reada_in_flight, 0);
Miao Xieaddc3fa2014-07-24 11:37:11 +0800435 atomic_set(&dev->dev_stats_ccnt, 0);
Su Yuec41ec452021-01-21 19:39:10 +0800436 btrfs_device_data_ordered_init(dev);
Chris Mason9bcaaea2017-05-04 16:08:08 -0700437 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
Mel Gormand0164ad2015-11-06 16:28:21 -0800438 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
Qu Wenruo154f7cb2020-08-20 15:42:46 +0800439 extent_io_tree_init(fs_info, &dev->alloc_state,
440 IO_TREE_DEVICE_ALLOC_STATE, NULL);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300441
442 return dev;
443}
444
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200445static noinline struct btrfs_fs_devices *find_fsid(
446 const u8 *fsid, const u8 *metadata_fsid)
Chris Mason8a4b83c2008-03-24 15:02:07 -0400447{
Chris Mason8a4b83c2008-03-24 15:02:07 -0400448 struct btrfs_fs_devices *fs_devices;
449
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200450 ASSERT(fsid);
451
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200452 /* Handle non-split brain cases */
Anand Jainc4babc52018-04-12 10:29:25 +0800453 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200454 if (metadata_fsid) {
455 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
456 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
457 BTRFS_FSID_SIZE) == 0)
458 return fs_devices;
459 } else {
460 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
461 return fs_devices;
462 }
Chris Mason8a4b83c2008-03-24 15:02:07 -0400463 }
464 return NULL;
465}
466
Su Yuec6730a02020-01-10 14:11:33 +0200467static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
468 struct btrfs_super_block *disk_super)
469{
470
471 struct btrfs_fs_devices *fs_devices;
472
473 /*
474 * Handle scanned device having completed its fsid change but
475 * belonging to a fs_devices that was created by first scanning
476 * a device which didn't have its fsid/metadata_uuid changed
477 * at all and the CHANGING_FSID_V2 flag set.
478 */
479 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
480 if (fs_devices->fsid_change &&
481 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
482 BTRFS_FSID_SIZE) == 0 &&
483 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
484 BTRFS_FSID_SIZE) == 0) {
485 return fs_devices;
486 }
487 }
488 /*
489 * Handle scanned device having completed its fsid change but
490 * belonging to a fs_devices that was created by a device that
491 * has an outdated pair of fsid/metadata_uuid and
492 * CHANGING_FSID_V2 flag set.
493 */
494 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
495 if (fs_devices->fsid_change &&
496 memcmp(fs_devices->metadata_uuid,
497 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
498 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
499 BTRFS_FSID_SIZE) == 0) {
500 return fs_devices;
501 }
502 }
503
504 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
505}
506
507
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100508static int
509btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
510 int flush, struct block_device **bdev,
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900511 struct btrfs_super_block **disk_super)
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100512{
513 int ret;
514
515 *bdev = blkdev_get_by_path(device_path, flags, holder);
516
517 if (IS_ERR(*bdev)) {
518 ret = PTR_ERR(*bdev);
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100519 goto error;
520 }
521
522 if (flush)
523 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
David Sterba9f6d2512017-06-16 01:48:05 +0200524 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100525 if (ret) {
526 blkdev_put(*bdev, flags);
527 goto error;
528 }
529 invalidate_bdev(*bdev);
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900530 *disk_super = btrfs_read_dev_super(*bdev);
531 if (IS_ERR(*disk_super)) {
532 ret = PTR_ERR(*disk_super);
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100533 blkdev_put(*bdev, flags);
534 goto error;
535 }
536
537 return 0;
538
539error:
540 *bdev = NULL;
Stefan Behrensbeaf8ab2012-11-12 14:03:45 +0100541 return ret;
542}
543
Anand Jain70bc7082019-01-04 13:31:53 +0800544static bool device_path_matched(const char *path, struct btrfs_device *device)
545{
546 int found;
547
548 rcu_read_lock();
549 found = strcmp(rcu_str_deref(device->name), path);
550 rcu_read_unlock();
551
552 return found == 0;
553}
554
Anand Jaind8367db2018-01-18 22:00:37 +0800555/*
556 * Search and remove all stale (devices which are not mounted) devices.
557 * When both inputs are NULL, it will search and release all stale devices.
558 * path: Optional. When provided will it release all unmounted devices
559 * matching this path only.
560 * skip_dev: Optional. Will skip this device when searching for the stale
561 * devices.
Anand Jain70bc7082019-01-04 13:31:53 +0800562 * Return: 0 for success or if @path is NULL.
563 * -EBUSY if @path is a mounted device.
564 * -ENOENT if @path does not match any device in the list.
Anand Jaind8367db2018-01-18 22:00:37 +0800565 */
Anand Jain70bc7082019-01-04 13:31:53 +0800566static int btrfs_free_stale_devices(const char *path,
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800567 struct btrfs_device *skip_device)
Anand Jain4fde46f2015-06-17 21:10:48 +0800568{
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800569 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
570 struct btrfs_device *device, *tmp_device;
Anand Jain70bc7082019-01-04 13:31:53 +0800571 int ret = 0;
572
573 if (path)
574 ret = -ENOENT;
Anand Jain4fde46f2015-06-17 21:10:48 +0800575
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800576 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
Anand Jain4fde46f2015-06-17 21:10:48 +0800577
Anand Jain70bc7082019-01-04 13:31:53 +0800578 mutex_lock(&fs_devices->device_list_mutex);
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800579 list_for_each_entry_safe(device, tmp_device,
580 &fs_devices->devices, dev_list) {
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800581 if (skip_device && skip_device == device)
Anand Jaind8367db2018-01-18 22:00:37 +0800582 continue;
Anand Jainfa6d2ae2018-05-29 15:33:08 +0800583 if (path && !device->name)
Anand Jain4fde46f2015-06-17 21:10:48 +0800584 continue;
Anand Jain70bc7082019-01-04 13:31:53 +0800585 if (path && !device_path_matched(path, device))
Anand Jain38cf6652018-01-18 22:00:34 +0800586 continue;
Anand Jain70bc7082019-01-04 13:31:53 +0800587 if (fs_devices->opened) {
588 /* for an already deleted device return 0 */
589 if (path && ret != 0)
590 ret = -EBUSY;
591 break;
592 }
Anand Jain4fde46f2015-06-17 21:10:48 +0800593
Anand Jain4fde46f2015-06-17 21:10:48 +0800594 /* delete the stale device */
Anand Jain7bcb8162018-05-29 17:23:20 +0800595 fs_devices->num_devices--;
596 list_del(&device->dev_list);
597 btrfs_free_device(device);
598
Anand Jain70bc7082019-01-04 13:31:53 +0800599 ret = 0;
Anand Jain7bcb8162018-05-29 17:23:20 +0800600 }
601 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jain70bc7082019-01-04 13:31:53 +0800602
Anand Jain7bcb8162018-05-29 17:23:20 +0800603 if (fs_devices->num_devices == 0) {
604 btrfs_sysfs_remove_fsid(fs_devices);
605 list_del(&fs_devices->fs_list);
606 free_fs_devices(fs_devices);
Anand Jain4fde46f2015-06-17 21:10:48 +0800607 }
608 }
Anand Jain70bc7082019-01-04 13:31:53 +0800609
610 return ret;
Anand Jain4fde46f2015-06-17 21:10:48 +0800611}
612
Josef Bacik18c850f2020-07-17 15:12:27 -0400613/*
614 * This is only used on mount, and we are protected from competing things
615 * messing with our fs_devices by the uuid_mutex, thus we do not need the
616 * fs_devices->device_list_mutex here.
617 */
Anand Jain0fb08bc2017-11-09 23:45:24 +0800618static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
619 struct btrfs_device *device, fmode_t flags,
620 void *holder)
621{
622 struct request_queue *q;
623 struct block_device *bdev;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800624 struct btrfs_super_block *disk_super;
625 u64 devid;
626 int ret;
627
628 if (device->bdev)
629 return -EINVAL;
630 if (!device->name)
631 return -EINVAL;
632
633 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900634 &bdev, &disk_super);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800635 if (ret)
636 return ret;
637
Anand Jain0fb08bc2017-11-09 23:45:24 +0800638 devid = btrfs_stack_device_id(&disk_super->dev_item);
639 if (devid != device->devid)
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900640 goto error_free_page;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800641
642 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900643 goto error_free_page;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800644
645 device->generation = btrfs_super_generation(disk_super);
646
647 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200648 if (btrfs_super_incompat_flags(disk_super) &
649 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
650 pr_err(
651 "BTRFS: Invalid seeding and uuid-changed device detected\n");
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900652 goto error_free_page;
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200653 }
654
Anand Jainebbede42017-12-04 12:54:52 +0800655 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Johannes Thumshirn0395d842019-11-13 11:27:27 +0100656 fs_devices->seeding = true;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800657 } else {
Anand Jainebbede42017-12-04 12:54:52 +0800658 if (bdev_read_only(bdev))
659 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
660 else
661 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800662 }
663
664 q = bdev_get_queue(bdev);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800665 if (!blk_queue_nonrot(q))
Johannes Thumshirn7f0432d2019-11-13 11:27:28 +0100666 fs_devices->rotating = true;
Anand Jain0fb08bc2017-11-09 23:45:24 +0800667
668 device->bdev = bdev;
Anand Jaine12c9622017-12-04 12:54:53 +0800669 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800670 device->mode = flags;
671
672 fs_devices->open_devices++;
Anand Jainebbede42017-12-04 12:54:52 +0800673 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
674 device->devid != BTRFS_DEV_REPLACE_DEVID) {
Anand Jain0fb08bc2017-11-09 23:45:24 +0800675 fs_devices->rw_devices++;
Anand Jainb1b8e382018-01-22 14:49:37 -0800676 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800677 }
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900678 btrfs_release_disk_super(disk_super);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800679
680 return 0;
681
Johannes Thumshirn8f323802020-02-14 00:24:32 +0900682error_free_page:
683 btrfs_release_disk_super(disk_super);
Anand Jain0fb08bc2017-11-09 23:45:24 +0800684 blkdev_put(bdev, flags);
685
686 return -EINVAL;
687}
688
David Sterba60999ca2014-03-26 18:26:36 +0100689/*
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200690 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
Su Yuec0d81c72020-01-10 14:11:32 +0200691 * being created with a disk that has already completed its fsid change. Such
692 * disk can belong to an fs which has its FSID changed or to one which doesn't.
693 * Handle both cases here.
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200694 */
695static struct btrfs_fs_devices *find_fsid_inprogress(
696 struct btrfs_super_block *disk_super)
697{
698 struct btrfs_fs_devices *fs_devices;
699
700 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
701 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
702 BTRFS_FSID_SIZE) != 0 &&
703 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
704 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
705 return fs_devices;
706 }
707 }
708
Su Yuec0d81c72020-01-10 14:11:32 +0200709 return find_fsid(disk_super->fsid, NULL);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200710}
711
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200712
713static struct btrfs_fs_devices *find_fsid_changed(
714 struct btrfs_super_block *disk_super)
715{
716 struct btrfs_fs_devices *fs_devices;
717
718 /*
719 * Handles the case where scanned device is part of an fs that had
David Sterba1a9fd412021-05-21 17:42:23 +0200720 * multiple successful changes of FSID but currently device didn't
Nikolay Borisov05840712020-01-10 14:11:34 +0200721 * observe it. Meaning our fsid will be different than theirs. We need
722 * to handle two subcases :
723 * 1 - The fs still continues to have different METADATA/FSID uuids.
724 * 2 - The fs is switched back to its original FSID (METADATA/FSID
725 * are equal).
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200726 */
727 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
Nikolay Borisov05840712020-01-10 14:11:34 +0200728 /* Changed UUIDs */
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200729 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
730 BTRFS_FSID_SIZE) != 0 &&
731 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
732 BTRFS_FSID_SIZE) == 0 &&
733 memcmp(fs_devices->fsid, disk_super->fsid,
Nikolay Borisov05840712020-01-10 14:11:34 +0200734 BTRFS_FSID_SIZE) != 0)
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200735 return fs_devices;
Nikolay Borisov05840712020-01-10 14:11:34 +0200736
737 /* Unchanged UUIDs */
738 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
739 BTRFS_FSID_SIZE) == 0 &&
740 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
741 BTRFS_FSID_SIZE) == 0)
742 return fs_devices;
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200743 }
744
745 return NULL;
746}
Nikolay Borisov13620892020-01-10 14:11:35 +0200747
748static struct btrfs_fs_devices *find_fsid_reverted_metadata(
749 struct btrfs_super_block *disk_super)
750{
751 struct btrfs_fs_devices *fs_devices;
752
753 /*
754 * Handle the case where the scanned device is part of an fs whose last
755 * metadata UUID change reverted it to the original FSID. At the same
756 * time * fs_devices was first created by another constitutent device
757 * which didn't fully observe the operation. This results in an
758 * btrfs_fs_devices created with metadata/fsid different AND
759 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
760 * fs_devices equal to the FSID of the disk.
761 */
762 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
763 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
764 BTRFS_FSID_SIZE) != 0 &&
765 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
766 BTRFS_FSID_SIZE) == 0 &&
767 fs_devices->fsid_change)
768 return fs_devices;
769 }
770
771 return NULL;
772}
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200773/*
David Sterba60999ca2014-03-26 18:26:36 +0100774 * Add new device to list of registered devices
775 *
776 * Returns:
Anand Jaine124ece2018-01-18 22:02:35 +0800777 * device pointer which was just added or updated when successful
778 * error pointer when failed
David Sterba60999ca2014-03-26 18:26:36 +0100779 */
Anand Jaine124ece2018-01-18 22:02:35 +0800780static noinline struct btrfs_device *device_list_add(const char *path,
Anand Jain4306a972018-05-29 12:28:37 +0800781 struct btrfs_super_block *disk_super,
782 bool *new_device_added)
Chris Mason8a4b83c2008-03-24 15:02:07 -0400783{
784 struct btrfs_device *device;
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200785 struct btrfs_fs_devices *fs_devices = NULL;
Josef Bacik606686e2012-06-04 14:03:51 -0400786 struct rcu_string *name;
Chris Mason8a4b83c2008-03-24 15:02:07 -0400787 u64 found_transid = btrfs_super_generation(disk_super);
Anand Jain3acbcbf2018-01-18 22:02:36 +0800788 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200789 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
790 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
Nikolay Borisovd1a63002018-10-30 16:43:26 +0200791 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
792 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400793
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200794 if (fsid_change_in_progress) {
Su Yuec0d81c72020-01-10 14:11:32 +0200795 if (!has_metadata_uuid)
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200796 fs_devices = find_fsid_inprogress(disk_super);
Su Yuec0d81c72020-01-10 14:11:32 +0200797 else
Nikolay Borisovcc5de4e2018-10-30 16:43:28 +0200798 fs_devices = find_fsid_changed(disk_super);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200799 } else if (has_metadata_uuid) {
Su Yuec6730a02020-01-10 14:11:33 +0200800 fs_devices = find_fsid_with_metadata_uuid(disk_super);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200801 } else {
Nikolay Borisov13620892020-01-10 14:11:35 +0200802 fs_devices = find_fsid_reverted_metadata(disk_super);
803 if (!fs_devices)
804 fs_devices = find_fsid(disk_super->fsid, NULL);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200805 }
806
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200807
Chris Mason8a4b83c2008-03-24 15:02:07 -0400808 if (!fs_devices) {
Nikolay Borisov7239ff42018-10-30 16:43:23 +0200809 if (has_metadata_uuid)
810 fs_devices = alloc_fs_devices(disk_super->fsid,
811 disk_super->metadata_uuid);
812 else
813 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
814
Ilya Dryomov2208a372013-08-12 14:33:03 +0300815 if (IS_ERR(fs_devices))
Anand Jaine124ece2018-01-18 22:02:35 +0800816 return ERR_CAST(fs_devices);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300817
Al Viro92900e52019-01-27 04:58:00 +0000818 fs_devices->fsid_change = fsid_change_in_progress;
819
Anand Jain9c6d1732018-05-29 14:10:20 +0800820 mutex_lock(&fs_devices->device_list_mutex);
Anand Jainc4babc52018-04-12 10:29:25 +0800821 list_add(&fs_devices->fs_list, &fs_uuids);
Ilya Dryomov2208a372013-08-12 14:33:03 +0300822
Chris Mason8a4b83c2008-03-24 15:02:07 -0400823 device = NULL;
824 } else {
Anand Jain9c6d1732018-05-29 14:10:20 +0800825 mutex_lock(&fs_devices->device_list_mutex);
Anand Jain09ba3bc2019-01-19 14:48:55 +0800826 device = btrfs_find_device(fs_devices, devid,
Anand Jainb2598ed2020-11-03 13:49:43 +0800827 disk_super->dev_item.uuid, NULL);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200828
829 /*
830 * If this disk has been pulled into an fs devices created by
831 * a device which had the CHANGING_FSID_V2 flag then replace the
832 * metadata_uuid/fsid values of the fs_devices.
833 */
Nikolay Borisov13620892020-01-10 14:11:35 +0200834 if (fs_devices->fsid_change &&
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200835 found_transid > fs_devices->latest_generation) {
836 memcpy(fs_devices->fsid, disk_super->fsid,
837 BTRFS_FSID_SIZE);
Nikolay Borisov13620892020-01-10 14:11:35 +0200838
839 if (has_metadata_uuid)
840 memcpy(fs_devices->metadata_uuid,
841 disk_super->metadata_uuid,
842 BTRFS_FSID_SIZE);
843 else
844 memcpy(fs_devices->metadata_uuid,
845 disk_super->fsid, BTRFS_FSID_SIZE);
Nikolay Borisov7a62d0f2018-10-30 16:43:27 +0200846
847 fs_devices->fsid_change = false;
848 }
Chris Mason8a4b83c2008-03-24 15:02:07 -0400849 }
Miao Xie443f24f2014-07-24 11:37:15 +0800850
Chris Mason8a4b83c2008-03-24 15:02:07 -0400851 if (!device) {
Anand Jain9c6d1732018-05-29 14:10:20 +0800852 if (fs_devices->opened) {
853 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800854 return ERR_PTR(-EBUSY);
Anand Jain9c6d1732018-05-29 14:10:20 +0800855 }
Yan Zheng2b820322008-11-17 21:11:30 -0500856
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +0300857 device = btrfs_alloc_device(NULL, &devid,
858 disk_super->dev_item.uuid);
859 if (IS_ERR(device)) {
Anand Jain9c6d1732018-05-29 14:10:20 +0800860 mutex_unlock(&fs_devices->device_list_mutex);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400861 /* we can safely leave the fs_devices entry around */
Anand Jaine124ece2018-01-18 22:02:35 +0800862 return device;
Chris Mason8a4b83c2008-03-24 15:02:07 -0400863 }
Josef Bacik606686e2012-06-04 14:03:51 -0400864
865 name = rcu_string_strdup(path, GFP_NOFS);
866 if (!name) {
David Sterbaa425f9d2018-03-20 15:47:33 +0100867 btrfs_free_device(device);
Anand Jain9c6d1732018-05-29 14:10:20 +0800868 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800869 return ERR_PTR(-ENOMEM);
Chris Mason8a4b83c2008-03-24 15:02:07 -0400870 }
Josef Bacik606686e2012-06-04 14:03:51 -0400871 rcu_assign_pointer(device->name, name);
Arne Jansen90519d62011-05-23 14:30:00 +0200872
Xiao Guangrong1f781602011-04-20 10:09:16 +0000873 list_add_rcu(&device->dev_list, &fs_devices->devices);
Filipe David Borba Mananaf7171752013-08-12 20:56:58 +0100874 fs_devices->num_devices++;
Chris Masone5e9a522009-06-10 15:17:02 -0400875
Yan Zheng2b820322008-11-17 21:11:30 -0500876 device->fs_devices = fs_devices;
Anand Jain4306a972018-05-29 12:28:37 +0800877 *new_device_added = true;
Anand Jain327f18c2018-01-18 22:02:33 +0800878
879 if (disk_super->label[0])
Anand Jainaa6c0df2019-10-02 18:30:48 +0800880 pr_info(
881 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
882 disk_super->label, devid, found_transid, path,
883 current->comm, task_pid_nr(current));
Anand Jain327f18c2018-01-18 22:02:33 +0800884 else
Anand Jainaa6c0df2019-10-02 18:30:48 +0800885 pr_info(
886 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
887 disk_super->fsid, devid, found_transid, path,
888 current->comm, task_pid_nr(current));
Anand Jain327f18c2018-01-18 22:02:33 +0800889
Josef Bacik606686e2012-06-04 14:03:51 -0400890 } else if (!device->name || strcmp(device->name->str, path)) {
Anand Jainb96de002014-07-03 18:22:05 +0800891 /*
892 * When FS is already mounted.
893 * 1. If you are here and if the device->name is NULL that
894 * means this device was missing at time of FS mount.
895 * 2. If you are here and if the device->name is different
896 * from 'path' that means either
897 * a. The same device disappeared and reappeared with
898 * different name. or
899 * b. The missing-disk-which-was-replaced, has
900 * reappeared now.
901 *
902 * We must allow 1 and 2a above. But 2b would be a spurious
903 * and unintentional.
904 *
905 * Further in case of 1 and 2a above, the disk at 'path'
906 * would have missed some transaction when it was away and
907 * in case of 2a the stale bdev has to be updated as well.
908 * 2b must not be allowed at all time.
909 */
910
911 /*
Chris Mason0f23ae72014-09-18 07:49:05 -0700912 * For now, we do allow update to btrfs_fs_device through the
913 * btrfs dev scan cli after FS has been mounted. We're still
914 * tracking a problem where systems fail mount by subvolume id
915 * when we reject replacement on a mounted FS.
Anand Jainb96de002014-07-03 18:22:05 +0800916 */
Chris Mason0f23ae72014-09-18 07:49:05 -0700917 if (!fs_devices->opened && found_transid < device->generation) {
Anand Jain77bdae42014-07-03 18:22:06 +0800918 /*
919 * That is if the FS is _not_ mounted and if you
920 * are here, that means there is more than one
921 * disk with same uuid and devid.We keep the one
922 * with larger generation number or the last-in if
923 * generation are equal.
924 */
Anand Jain9c6d1732018-05-29 14:10:20 +0800925 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800926 return ERR_PTR(-EEXIST);
Anand Jain77bdae42014-07-03 18:22:06 +0800927 }
Anand Jainb96de002014-07-03 18:22:05 +0800928
Anand Jaina9261d42018-10-15 10:45:17 +0800929 /*
930 * We are going to replace the device path for a given devid,
931 * make sure it's the same device if the device is mounted
932 */
933 if (device->bdev) {
Christoph Hellwig4e7b5672020-11-23 13:38:40 +0100934 int error;
935 dev_t path_dev;
Anand Jaina9261d42018-10-15 10:45:17 +0800936
Christoph Hellwig4e7b5672020-11-23 13:38:40 +0100937 error = lookup_bdev(path, &path_dev);
938 if (error) {
Anand Jaina9261d42018-10-15 10:45:17 +0800939 mutex_unlock(&fs_devices->device_list_mutex);
Christoph Hellwig4e7b5672020-11-23 13:38:40 +0100940 return ERR_PTR(error);
Anand Jaina9261d42018-10-15 10:45:17 +0800941 }
942
Christoph Hellwig4e7b5672020-11-23 13:38:40 +0100943 if (device->bdev->bd_dev != path_dev) {
Anand Jaina9261d42018-10-15 10:45:17 +0800944 mutex_unlock(&fs_devices->device_list_mutex);
Johannes Thumshirn0697d9a2020-11-18 18:03:26 +0900945 /*
946 * device->fs_info may not be reliable here, so
947 * pass in a NULL instead. This avoids a
948 * possible use-after-free when the fs_info and
949 * fs_info->sb are already torn down.
950 */
951 btrfs_warn_in_rcu(NULL,
Anand Jain79dae172020-09-03 21:30:12 +0800952 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
953 path, devid, found_transid,
954 current->comm,
955 task_pid_nr(current));
Anand Jaina9261d42018-10-15 10:45:17 +0800956 return ERR_PTR(-EEXIST);
957 }
Anand Jaina9261d42018-10-15 10:45:17 +0800958 btrfs_info_in_rcu(device->fs_info,
Anand Jain79dae172020-09-03 21:30:12 +0800959 "devid %llu device path %s changed to %s scanned by %s (%d)",
960 devid, rcu_str_deref(device->name),
961 path, current->comm,
962 task_pid_nr(current));
Anand Jaina9261d42018-10-15 10:45:17 +0800963 }
964
Josef Bacik606686e2012-06-04 14:03:51 -0400965 name = rcu_string_strdup(path, GFP_NOFS);
Anand Jain9c6d1732018-05-29 14:10:20 +0800966 if (!name) {
967 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800968 return ERR_PTR(-ENOMEM);
Anand Jain9c6d1732018-05-29 14:10:20 +0800969 }
Josef Bacik606686e2012-06-04 14:03:51 -0400970 rcu_string_free(device->name);
971 rcu_assign_pointer(device->name, name);
Anand Jaine6e674b2017-12-04 12:54:54 +0800972 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
Chris Masoncd02dca2010-12-13 14:56:23 -0500973 fs_devices->missing_devices--;
Anand Jaine6e674b2017-12-04 12:54:54 +0800974 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
Chris Masoncd02dca2010-12-13 14:56:23 -0500975 }
Chris Mason8a4b83c2008-03-24 15:02:07 -0400976 }
977
Anand Jain77bdae42014-07-03 18:22:06 +0800978 /*
979 * Unmount does not free the btrfs_device struct but would zero
980 * generation along with most of the other members. So just update
981 * it back. We need it to pick the disk with largest generation
982 * (as above).
983 */
Nikolay Borisovd1a63002018-10-30 16:43:26 +0200984 if (!fs_devices->opened) {
Anand Jain77bdae42014-07-03 18:22:06 +0800985 device->generation = found_transid;
Nikolay Borisovd1a63002018-10-30 16:43:26 +0200986 fs_devices->latest_generation = max_t(u64, found_transid,
987 fs_devices->latest_generation);
988 }
Anand Jain77bdae42014-07-03 18:22:06 +0800989
Anand Jainf2788d22018-01-18 22:02:34 +0800990 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
991
Anand Jain9c6d1732018-05-29 14:10:20 +0800992 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jaine124ece2018-01-18 22:02:35 +0800993 return device;
Chris Mason8a4b83c2008-03-24 15:02:07 -0400994}
995
Yan Zhenge4404d62008-12-12 10:03:26 -0500996static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
997{
998 struct btrfs_fs_devices *fs_devices;
999 struct btrfs_device *device;
1000 struct btrfs_device *orig_dev;
Anand Jaind2979aa2019-08-27 15:40:45 +08001001 int ret = 0;
Yan Zhenge4404d62008-12-12 10:03:26 -05001002
Nikolay Borisov7239ff42018-10-30 16:43:23 +02001003 fs_devices = alloc_fs_devices(orig->fsid, NULL);
Ilya Dryomov2208a372013-08-12 14:33:03 +03001004 if (IS_ERR(fs_devices))
1005 return fs_devices;
Yan Zhenge4404d62008-12-12 10:03:26 -05001006
Miao Xieadbbb862014-09-03 21:35:42 +08001007 mutex_lock(&orig->device_list_mutex);
Josef Bacik02db0842012-06-21 16:03:58 -04001008 fs_devices->total_devices = orig->total_devices;
Yan Zhenge4404d62008-12-12 10:03:26 -05001009
1010 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
Josef Bacik606686e2012-06-04 14:03:51 -04001011 struct rcu_string *name;
1012
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03001013 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1014 orig_dev->uuid);
Anand Jaind2979aa2019-08-27 15:40:45 +08001015 if (IS_ERR(device)) {
1016 ret = PTR_ERR(device);
Yan Zhenge4404d62008-12-12 10:03:26 -05001017 goto error;
Anand Jaind2979aa2019-08-27 15:40:45 +08001018 }
Yan Zhenge4404d62008-12-12 10:03:26 -05001019
Josef Bacik606686e2012-06-04 14:03:51 -04001020 /*
1021 * This is ok to do without rcu read locked because we hold the
1022 * uuid mutex so nothing we touch in here is going to disappear.
1023 */
Anand Jaine755f782014-06-30 17:12:47 +08001024 if (orig_dev->name) {
David Sterba78f2c9e2016-02-11 14:25:38 +01001025 name = rcu_string_strdup(orig_dev->name->str,
1026 GFP_KERNEL);
Anand Jaine755f782014-06-30 17:12:47 +08001027 if (!name) {
David Sterbaa425f9d2018-03-20 15:47:33 +01001028 btrfs_free_device(device);
Anand Jaind2979aa2019-08-27 15:40:45 +08001029 ret = -ENOMEM;
Anand Jaine755f782014-06-30 17:12:47 +08001030 goto error;
1031 }
1032 rcu_assign_pointer(device->name, name);
Julia Lawallfd2696f2009-09-29 13:51:04 -04001033 }
Yan Zhenge4404d62008-12-12 10:03:26 -05001034
Yan Zhenge4404d62008-12-12 10:03:26 -05001035 list_add(&device->dev_list, &fs_devices->devices);
1036 device->fs_devices = fs_devices;
1037 fs_devices->num_devices++;
1038 }
Miao Xieadbbb862014-09-03 21:35:42 +08001039 mutex_unlock(&orig->device_list_mutex);
Yan Zhenge4404d62008-12-12 10:03:26 -05001040 return fs_devices;
1041error:
Miao Xieadbbb862014-09-03 21:35:42 +08001042 mutex_unlock(&orig->device_list_mutex);
Yan Zhenge4404d62008-12-12 10:03:26 -05001043 free_fs_devices(fs_devices);
Anand Jaind2979aa2019-08-27 15:40:45 +08001044 return ERR_PTR(ret);
Yan Zhenge4404d62008-12-12 10:03:26 -05001045}
1046
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001047static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
Anand Jainbacce862020-11-06 16:06:33 +08001048 struct btrfs_device **latest_dev)
Chris Masondfe25022008-05-13 13:46:40 -04001049{
Qinghuang Fengc6e30872009-01-21 10:59:08 -05001050 struct btrfs_device *device, *next;
Chris Masona6b0d5c2012-02-20 20:53:43 -05001051
Xiao Guangrong46224702011-04-20 10:08:47 +00001052 /* This is the initialized path, it is safe to release the devices. */
Qinghuang Fengc6e30872009-01-21 10:59:08 -05001053 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001054 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
Anand Jain401e29c2017-12-04 12:54:55 +08001055 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001056 &device->dev_state) &&
Anand Jain998a0672020-05-05 02:58:25 +08001057 !test_bit(BTRFS_DEV_STATE_MISSING,
1058 &device->dev_state) &&
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001059 (!*latest_dev ||
1060 device->generation > (*latest_dev)->generation)) {
1061 *latest_dev = device;
Chris Masona6b0d5c2012-02-20 20:53:43 -05001062 }
Yan Zheng2b820322008-11-17 21:11:30 -05001063 continue;
Chris Masona6b0d5c2012-02-20 20:53:43 -05001064 }
Yan Zheng2b820322008-11-17 21:11:30 -05001065
Anand Jaincf89af12020-10-30 06:53:56 +08001066 /*
1067 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1068 * in btrfs_init_dev_replace() so just continue.
1069 */
1070 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1071 continue;
1072
Yan Zheng2b820322008-11-17 21:11:30 -05001073 if (device->bdev) {
Tejun Heod4d77622010-11-13 11:55:18 +01001074 blkdev_put(device->bdev, device->mode);
Yan Zheng2b820322008-11-17 21:11:30 -05001075 device->bdev = NULL;
1076 fs_devices->open_devices--;
1077 }
Anand Jainebbede42017-12-04 12:54:52 +08001078 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
Yan Zheng2b820322008-11-17 21:11:30 -05001079 list_del_init(&device->dev_alloc_list);
Anand Jainebbede42017-12-04 12:54:52 +08001080 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Desmond Cheong Zhi Xib2a61662021-07-27 15:13:03 +08001081 fs_devices->rw_devices--;
Yan Zheng2b820322008-11-17 21:11:30 -05001082 }
Yan Zhenge4404d62008-12-12 10:03:26 -05001083 list_del_init(&device->dev_list);
1084 fs_devices->num_devices--;
David Sterbaa425f9d2018-03-20 15:47:33 +01001085 btrfs_free_device(device);
Chris Masondfe25022008-05-13 13:46:40 -04001086 }
Yan Zheng2b820322008-11-17 21:11:30 -05001087
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001088}
1089
1090/*
1091 * After we have read the system tree and know devids belonging to this
1092 * filesystem, remove the device which does not belong there.
1093 */
Anand Jainbacce862020-11-06 16:06:33 +08001094void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices)
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001095{
1096 struct btrfs_device *latest_dev = NULL;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001097 struct btrfs_fs_devices *seed_dev;
Nikolay Borisov3712ccb2020-07-16 10:17:04 +03001098
1099 mutex_lock(&uuid_mutex);
Anand Jainbacce862020-11-06 16:06:33 +08001100 __btrfs_free_extra_devids(fs_devices, &latest_dev);
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001101
1102 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
Anand Jainbacce862020-11-06 16:06:33 +08001103 __btrfs_free_extra_devids(seed_dev, &latest_dev);
Yan Zheng2b820322008-11-17 21:11:30 -05001104
Miao Xie443f24f2014-07-24 11:37:15 +08001105 fs_devices->latest_bdev = latest_dev->bdev;
Chris Masona6b0d5c2012-02-20 20:53:43 -05001106
Chris Masondfe25022008-05-13 13:46:40 -04001107 mutex_unlock(&uuid_mutex);
Chris Masondfe25022008-05-13 13:46:40 -04001108}
Chris Masona0af4692008-05-13 16:03:06 -04001109
Anand Jain14238812016-07-22 06:04:53 +08001110static void btrfs_close_bdev(struct btrfs_device *device)
1111{
David Sterba08ffcae2017-06-19 16:55:35 +02001112 if (!device->bdev)
1113 return;
1114
Anand Jainebbede42017-12-04 12:54:52 +08001115 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
Anand Jain14238812016-07-22 06:04:53 +08001116 sync_blockdev(device->bdev);
1117 invalidate_bdev(device->bdev);
1118 }
1119
David Sterba08ffcae2017-06-19 16:55:35 +02001120 blkdev_put(device->bdev, device->mode);
Anand Jain14238812016-07-22 06:04:53 +08001121}
1122
Nikolay Borisov959b1c02018-06-29 08:26:05 +03001123static void btrfs_close_one_device(struct btrfs_device *device)
Anand Jainf448341a2016-06-14 18:55:25 +08001124{
1125 struct btrfs_fs_devices *fs_devices = device->fs_devices;
Anand Jainf448341a2016-06-14 18:55:25 +08001126
Anand Jainebbede42017-12-04 12:54:52 +08001127 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
Anand Jainf448341a2016-06-14 18:55:25 +08001128 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1129 list_del_init(&device->dev_alloc_list);
1130 fs_devices->rw_devices--;
1131 }
1132
Anand Jaine6e674b2017-12-04 12:54:54 +08001133 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
Anand Jainf448341a2016-06-14 18:55:25 +08001134 fs_devices->missing_devices--;
1135
Nikolay Borisov959b1c02018-06-29 08:26:05 +03001136 btrfs_close_bdev(device);
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001137 if (device->bdev) {
Johannes Thumshirn3fff3972019-11-26 09:40:05 +01001138 fs_devices->open_devices--;
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001139 device->bdev = NULL;
Anand Jainf448341a2016-06-14 18:55:25 +08001140 }
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001141 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Naohiro Aota5b316462020-11-10 20:26:07 +09001142 btrfs_destroy_dev_zone_info(device);
Anand Jainf448341a2016-06-14 18:55:25 +08001143
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001144 device->fs_info = NULL;
1145 atomic_set(&device->dev_stats_ccnt, 0);
1146 extent_io_tree_release(&device->alloc_state);
Nikolay Borisov959b1c02018-06-29 08:26:05 +03001147
Johannes Thumshirn321f69f2019-12-04 14:36:39 +01001148 /* Verify the device is back in a pristine state */
1149 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1150 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1151 ASSERT(list_empty(&device->dev_alloc_list));
1152 ASSERT(list_empty(&device->post_commit_list));
1153 ASSERT(atomic_read(&device->reada_in_flight) == 0);
Anand Jainf448341a2016-06-14 18:55:25 +08001154}
1155
Nikolay Borisov54eed6a2020-07-15 13:48:48 +03001156static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
Chris Mason8a4b83c2008-03-24 15:02:07 -04001157{
Sasha Levin2037a092015-05-12 19:31:37 -04001158 struct btrfs_device *device, *tmp;
Yan Zhenge4404d62008-12-12 10:03:26 -05001159
Josef Bacik425c6ed2020-08-10 11:42:28 -04001160 lockdep_assert_held(&uuid_mutex);
1161
Yan Zheng2b820322008-11-17 21:11:30 -05001162 if (--fs_devices->opened > 0)
Nikolay Borisov54eed6a2020-07-15 13:48:48 +03001163 return;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001164
Josef Bacik425c6ed2020-08-10 11:42:28 -04001165 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
Nikolay Borisov959b1c02018-06-29 08:26:05 +03001166 btrfs_close_one_device(device);
Xiao Guangrongc9513ed2011-04-20 10:07:30 +00001167
Yan Zhenge4404d62008-12-12 10:03:26 -05001168 WARN_ON(fs_devices->open_devices);
1169 WARN_ON(fs_devices->rw_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05001170 fs_devices->opened = 0;
Johannes Thumshirn0395d842019-11-13 11:27:27 +01001171 fs_devices->seeding = false;
Nikolay Borisovc4989c2f2020-07-15 13:48:49 +03001172 fs_devices->fs_info = NULL;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001173}
1174
Nikolay Borisov54eed6a2020-07-15 13:48:48 +03001175void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
Yan Zheng2b820322008-11-17 21:11:30 -05001176{
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001177 LIST_HEAD(list);
1178 struct btrfs_fs_devices *tmp;
Yan Zheng2b820322008-11-17 21:11:30 -05001179
1180 mutex_lock(&uuid_mutex);
Nikolay Borisov54eed6a2020-07-15 13:48:48 +03001181 close_fs_devices(fs_devices);
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001182 if (!fs_devices->opened)
1183 list_splice_init(&fs_devices->seed_list, &list);
Yan Zhenge4404d62008-12-12 10:03:26 -05001184
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001185 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
Anand Jain0226e0e2018-04-12 10:29:27 +08001186 close_fs_devices(fs_devices);
Nikolay Borisov944d3f92020-07-16 10:25:33 +03001187 list_del(&fs_devices->seed_list);
Yan Zhenge4404d62008-12-12 10:03:26 -05001188 free_fs_devices(fs_devices);
1189 }
Josef Bacik425c6ed2020-08-10 11:42:28 -04001190 mutex_unlock(&uuid_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05001191}
1192
Anand Jain897fb572018-04-12 10:29:28 +08001193static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
Yan Zhenge4404d62008-12-12 10:03:26 -05001194 fmode_t flags, void *holder)
Chris Mason8a4b83c2008-03-24 15:02:07 -04001195{
Chris Mason8a4b83c2008-03-24 15:02:07 -04001196 struct btrfs_device *device;
Miao Xie443f24f2014-07-24 11:37:15 +08001197 struct btrfs_device *latest_dev = NULL;
Anand Jain96c2e062020-09-30 21:09:52 +08001198 struct btrfs_device *tmp_device;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001199
Tejun Heod4d77622010-11-13 11:55:18 +01001200 flags |= FMODE_EXCL;
1201
Anand Jain96c2e062020-09-30 21:09:52 +08001202 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1203 dev_list) {
1204 int ret;
Chris Masona0af4692008-05-13 16:03:06 -04001205
Anand Jain96c2e062020-09-30 21:09:52 +08001206 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1207 if (ret == 0 &&
1208 (!latest_dev || device->generation > latest_dev->generation)) {
Anand Jain9f050db2017-11-09 23:45:25 +08001209 latest_dev = device;
Anand Jain96c2e062020-09-30 21:09:52 +08001210 } else if (ret == -ENODATA) {
1211 fs_devices->num_devices--;
1212 list_del(&device->dev_list);
1213 btrfs_free_device(device);
1214 }
Chris Mason8a4b83c2008-03-24 15:02:07 -04001215 }
Anand Jain1ed802c2020-04-28 23:22:25 +08001216 if (fs_devices->open_devices == 0)
1217 return -EINVAL;
1218
Yan Zheng2b820322008-11-17 21:11:30 -05001219 fs_devices->opened = 1;
Miao Xie443f24f2014-07-24 11:37:15 +08001220 fs_devices->latest_bdev = latest_dev->bdev;
Yan Zheng2b820322008-11-17 21:11:30 -05001221 fs_devices->total_rw_bytes = 0;
Naohiro Aotac4a816c2020-02-25 12:56:08 +09001222 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
Anand Jain33fd2f72020-10-28 21:14:46 +08001223 fs_devices->read_policy = BTRFS_READ_POLICY_PID;
Anand Jain1ed802c2020-04-28 23:22:25 +08001224
1225 return 0;
Yan Zheng2b820322008-11-17 21:11:30 -05001226}
1227
Sami Tolvanen4f0f5862021-04-08 11:28:34 -07001228static int devid_cmp(void *priv, const struct list_head *a,
1229 const struct list_head *b)
Anand Jainf8e10cd2018-01-22 14:49:36 -08001230{
1231 struct btrfs_device *dev1, *dev2;
1232
1233 dev1 = list_entry(a, struct btrfs_device, dev_list);
1234 dev2 = list_entry(b, struct btrfs_device, dev_list);
1235
1236 if (dev1->devid < dev2->devid)
1237 return -1;
1238 else if (dev1->devid > dev2->devid)
1239 return 1;
1240 return 0;
1241}
1242
Yan Zheng2b820322008-11-17 21:11:30 -05001243int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
Christoph Hellwig97288f22008-12-02 06:36:09 -05001244 fmode_t flags, void *holder)
Yan Zheng2b820322008-11-17 21:11:30 -05001245{
1246 int ret;
1247
David Sterbaf5194e32018-06-19 17:09:47 +02001248 lockdep_assert_held(&uuid_mutex);
Josef Bacik18c850f2020-07-17 15:12:27 -04001249 /*
1250 * The device_list_mutex cannot be taken here in case opening the
Christoph Hellwiga8698702021-05-25 08:12:56 +02001251 * underlying device takes further locks like open_mutex.
Josef Bacik18c850f2020-07-17 15:12:27 -04001252 *
1253 * We also don't need the lock here as this is called during mount and
1254 * exclusion is provided by uuid_mutex
1255 */
David Sterbaf5194e32018-06-19 17:09:47 +02001256
Yan Zheng2b820322008-11-17 21:11:30 -05001257 if (fs_devices->opened) {
Yan Zhenge4404d62008-12-12 10:03:26 -05001258 fs_devices->opened++;
1259 ret = 0;
Yan Zheng2b820322008-11-17 21:11:30 -05001260 } else {
Anand Jainf8e10cd2018-01-22 14:49:36 -08001261 list_sort(NULL, &fs_devices->devices, devid_cmp);
Anand Jain897fb572018-04-12 10:29:28 +08001262 ret = open_fs_devices(fs_devices, flags, holder);
Yan Zheng2b820322008-11-17 21:11:30 -05001263 }
Anand Jain542c5902018-04-12 10:29:34 +08001264
Chris Mason8a4b83c2008-03-24 15:02:07 -04001265 return ret;
1266}
1267
Johannes Thumshirn8f323802020-02-14 00:24:32 +09001268void btrfs_release_disk_super(struct btrfs_super_block *super)
Anand Jain6cf86a002016-02-13 10:01:29 +08001269{
Johannes Thumshirn8f323802020-02-14 00:24:32 +09001270 struct page *page = virt_to_page(super);
1271
Anand Jain6cf86a002016-02-13 10:01:29 +08001272 put_page(page);
1273}
1274
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001275static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
Naohiro Aota12659252020-11-10 20:26:14 +09001276 u64 bytenr, u64 bytenr_orig)
Anand Jain6cf86a002016-02-13 10:01:29 +08001277{
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001278 struct btrfs_super_block *disk_super;
1279 struct page *page;
Anand Jain6cf86a002016-02-13 10:01:29 +08001280 void *p;
1281 pgoff_t index;
1282
1283 /* make sure our super fits in the device */
1284 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001285 return ERR_PTR(-EINVAL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001286
1287 /* make sure our super fits in the page */
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001288 if (sizeof(*disk_super) > PAGE_SIZE)
1289 return ERR_PTR(-EINVAL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001290
1291 /* make sure our super doesn't straddle pages on disk */
1292 index = bytenr >> PAGE_SHIFT;
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001293 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1294 return ERR_PTR(-EINVAL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001295
1296 /* pull in the page with our super */
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001297 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001298
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001299 if (IS_ERR(page))
1300 return ERR_CAST(page);
Anand Jain6cf86a002016-02-13 10:01:29 +08001301
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001302 p = page_address(page);
Anand Jain6cf86a002016-02-13 10:01:29 +08001303
1304 /* align our pointer to the offset of the super block */
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001305 disk_super = p + offset_in_page(bytenr);
Anand Jain6cf86a002016-02-13 10:01:29 +08001306
Naohiro Aota12659252020-11-10 20:26:14 +09001307 if (btrfs_super_bytenr(disk_super) != bytenr_orig ||
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001308 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
Johannes Thumshirn8f323802020-02-14 00:24:32 +09001309 btrfs_release_disk_super(p);
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001310 return ERR_PTR(-EINVAL);
Anand Jain6cf86a002016-02-13 10:01:29 +08001311 }
1312
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001313 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1314 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
Anand Jain6cf86a002016-02-13 10:01:29 +08001315
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001316 return disk_super;
Anand Jain6cf86a002016-02-13 10:01:29 +08001317}
1318
Anand Jain228a73a2019-01-04 13:31:54 +08001319int btrfs_forget_devices(const char *path)
1320{
1321 int ret;
1322
1323 mutex_lock(&uuid_mutex);
1324 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1325 mutex_unlock(&uuid_mutex);
1326
1327 return ret;
1328}
1329
David Sterba6f60cbd2013-02-15 11:31:02 -07001330/*
1331 * Look for a btrfs signature on a device. This may be called out of the mount path
1332 * and we are not allowed to call set_blocksize during the scan. The superblock
1333 * is read via pagecache
1334 */
Gu Jinxiang36350e92018-07-12 14:23:16 +08001335struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1336 void *holder)
Chris Mason8a4b83c2008-03-24 15:02:07 -04001337{
1338 struct btrfs_super_block *disk_super;
Anand Jain4306a972018-05-29 12:28:37 +08001339 bool new_device_added = false;
Gu Jinxiang36350e92018-07-12 14:23:16 +08001340 struct btrfs_device *device = NULL;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001341 struct block_device *bdev;
Naohiro Aota12659252020-11-10 20:26:14 +09001342 u64 bytenr, bytenr_orig;
1343 int ret;
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 */
Tejun Heod4d77622010-11-13 11:55:18 +01001353 flags |= FMODE_EXCL;
David Sterba6f60cbd2013-02-15 11:31:02 -07001354
1355 bdev = blkdev_get_by_path(path, flags, holder);
Anand Jainb6ed73b2018-04-12 10:29:24 +08001356 if (IS_ERR(bdev))
Gu Jinxiang36350e92018-07-12 14:23:16 +08001357 return ERR_CAST(bdev);
David Sterba6f60cbd2013-02-15 11:31:02 -07001358
Naohiro Aota12659252020-11-10 20:26:14 +09001359 bytenr_orig = btrfs_sb_offset(0);
1360 ret = btrfs_sb_log_location_bdev(bdev, 0, READ, &bytenr);
1361 if (ret)
1362 return ERR_PTR(ret);
1363
1364 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr_orig);
Nikolay Borisovb335eab2020-04-15 15:53:46 +03001365 if (IS_ERR(disk_super)) {
1366 device = ERR_CAST(disk_super);
David Sterba6f60cbd2013-02-15 11:31:02 -07001367 goto error_bdev_put;
Anand Jain05a5c552017-12-15 15:40:16 +08001368 }
David Sterba6f60cbd2013-02-15 11:31:02 -07001369
Anand Jain4306a972018-05-29 12:28:37 +08001370 device = device_list_add(path, disk_super, &new_device_added);
Gu Jinxiang36350e92018-07-12 14:23:16 +08001371 if (!IS_ERR(device)) {
Anand Jain4306a972018-05-29 12:28:37 +08001372 if (new_device_added)
1373 btrfs_free_stale_devices(path, device);
1374 }
David Sterba6f60cbd2013-02-15 11:31:02 -07001375
Johannes Thumshirn8f323802020-02-14 00:24:32 +09001376 btrfs_release_disk_super(disk_super);
David Sterba6f60cbd2013-02-15 11:31:02 -07001377
1378error_bdev_put:
Tejun Heod4d77622010-11-13 11:55:18 +01001379 blkdev_put(bdev, flags);
Anand Jainb6ed73b2018-04-12 10:29:24 +08001380
Gu Jinxiang36350e92018-07-12 14:23:16 +08001381 return device;
Chris Mason8a4b83c2008-03-24 15:02:07 -04001382}
Chris Mason0b86a832008-03-24 15:01:56 -04001383
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001384/*
1385 * Try to find a chunk that intersects [start, start + len] range and when one
1386 * such is found, record the end of it in *start
1387 */
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001388static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1389 u64 len)
Josef Bacik6df9a952013-06-27 13:22:46 -04001390{
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001391 u64 physical_start, physical_end;
Josef Bacik6df9a952013-06-27 13:22:46 -04001392
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001393 lockdep_assert_held(&device->fs_info->chunk_mutex);
Josef Bacik6df9a952013-06-27 13:22:46 -04001394
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001395 if (!find_first_extent_bit(&device->alloc_state, *start,
1396 &physical_start, &physical_end,
1397 CHUNK_ALLOCATED, NULL)) {
Filipe Mananac152b632015-05-14 10:46:03 +01001398
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001399 if (in_range(physical_start, *start, len) ||
1400 in_range(*start, physical_start,
1401 physical_end - physical_start)) {
1402 *start = physical_end + 1;
1403 return true;
Josef Bacik6df9a952013-06-27 13:22:46 -04001404 }
1405 }
Jeff Mahoney1c11b632019-03-27 14:24:12 +02001406 return false;
Josef Bacik6df9a952013-06-27 13:22:46 -04001407}
1408
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001409static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1410{
1411 switch (device->fs_devices->chunk_alloc_policy) {
1412 case BTRFS_CHUNK_ALLOC_REGULAR:
1413 /*
1414 * We don't want to overwrite the superblock on the drive nor
1415 * any area used by the boot loader (grub for example), so we
1416 * make sure to start at an offset of at least 1MB.
1417 */
1418 return max_t(u64, start, SZ_1M);
Naohiro Aota1cd61212021-02-04 19:21:48 +09001419 case BTRFS_CHUNK_ALLOC_ZONED:
1420 /*
1421 * We don't care about the starting region like regular
1422 * allocator, because we anyway use/reserve the first two zones
1423 * for superblock logging.
1424 */
1425 return ALIGN(start, device->zone_info->zone_size);
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001426 default:
1427 BUG();
1428 }
1429}
1430
Naohiro Aota1cd61212021-02-04 19:21:48 +09001431static bool dev_extent_hole_check_zoned(struct btrfs_device *device,
1432 u64 *hole_start, u64 *hole_size,
1433 u64 num_bytes)
1434{
1435 u64 zone_size = device->zone_info->zone_size;
1436 u64 pos;
1437 int ret;
1438 bool changed = false;
1439
1440 ASSERT(IS_ALIGNED(*hole_start, zone_size));
1441
1442 while (*hole_size > 0) {
1443 pos = btrfs_find_allocatable_zones(device, *hole_start,
1444 *hole_start + *hole_size,
1445 num_bytes);
1446 if (pos != *hole_start) {
1447 *hole_size = *hole_start + *hole_size - pos;
1448 *hole_start = pos;
1449 changed = true;
1450 if (*hole_size < num_bytes)
1451 break;
1452 }
1453
1454 ret = btrfs_ensure_empty_zones(device, pos, num_bytes);
1455
1456 /* Range is ensured to be empty */
1457 if (!ret)
1458 return changed;
1459
1460 /* Given hole range was invalid (outside of device) */
1461 if (ret == -ERANGE) {
1462 *hole_start += *hole_size;
Johannes Thumshirnd6f67af2021-05-10 22:39:38 +09001463 *hole_size = 0;
Jiapeng Chong7000bab2021-03-03 17:45:28 +08001464 return true;
Naohiro Aota1cd61212021-02-04 19:21:48 +09001465 }
1466
1467 *hole_start += zone_size;
1468 *hole_size -= zone_size;
1469 changed = true;
1470 }
1471
1472 return changed;
1473}
1474
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001475/**
1476 * dev_extent_hole_check - check if specified hole is suitable for allocation
1477 * @device: the device which we have the hole
1478 * @hole_start: starting position of the hole
1479 * @hole_size: the size of the hole
1480 * @num_bytes: the size of the free space that we need
1481 *
Naohiro Aota1cd61212021-02-04 19:21:48 +09001482 * This function may modify @hole_start and @hole_size to reflect the suitable
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001483 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1484 */
1485static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1486 u64 *hole_size, u64 num_bytes)
1487{
1488 bool changed = false;
1489 u64 hole_end = *hole_start + *hole_size;
1490
Naohiro Aota1cd61212021-02-04 19:21:48 +09001491 for (;;) {
1492 /*
1493 * Check before we set max_hole_start, otherwise we could end up
1494 * sending back this offset anyway.
1495 */
1496 if (contains_pending_extent(device, hole_start, *hole_size)) {
1497 if (hole_end >= *hole_start)
1498 *hole_size = hole_end - *hole_start;
1499 else
1500 *hole_size = 0;
1501 changed = true;
1502 }
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001503
Naohiro Aota1cd61212021-02-04 19:21:48 +09001504 switch (device->fs_devices->chunk_alloc_policy) {
1505 case BTRFS_CHUNK_ALLOC_REGULAR:
1506 /* No extra check */
1507 break;
1508 case BTRFS_CHUNK_ALLOC_ZONED:
1509 if (dev_extent_hole_check_zoned(device, hole_start,
1510 hole_size, num_bytes)) {
1511 changed = true;
1512 /*
1513 * The changed hole can contain pending extent.
1514 * Loop again to check that.
1515 */
1516 continue;
1517 }
1518 break;
1519 default:
1520 BUG();
1521 }
1522
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001523 break;
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001524 }
1525
1526 return changed;
1527}
Josef Bacik6df9a952013-06-27 13:22:46 -04001528
Chris Mason0b86a832008-03-24 15:01:56 -04001529/*
Jeff Mahoney499f3772015-06-15 09:41:17 -04001530 * find_free_dev_extent_start - find free space in the specified device
1531 * @device: the device which we search the free space in
1532 * @num_bytes: the size of the free space that we need
1533 * @search_start: the position from which to begin the search
1534 * @start: store the start of the free space.
1535 * @len: the size of the free space. that we find, or the size
1536 * of the max free space if we don't find suitable free space
Miao Xie7bfc8372011-01-05 10:07:26 +00001537 *
Chris Mason0b86a832008-03-24 15:01:56 -04001538 * this uses a pretty simple search, the expectation is that it is
1539 * called very infrequently and that a given device has a small number
1540 * of extents
Miao Xie7bfc8372011-01-05 10:07:26 +00001541 *
1542 * @start is used to store the start of the free space if we find. But if we
1543 * don't find suitable free space, it will be used to store the start position
1544 * of the max free space.
1545 *
1546 * @len is used to store the size of the free space that we find.
1547 * But if we don't find suitable free space, it is used to store the size of
1548 * the max free space.
Qu Wenruo135da972019-07-19 14:51:42 +08001549 *
1550 * NOTE: This function will search *commit* root of device tree, and does extra
1551 * check to ensure dev extents are not double allocated.
1552 * This makes the function safe to allocate dev extents but may not report
1553 * correct usable device space, as device extent freed in current transaction
David Sterba1a9fd412021-05-21 17:42:23 +02001554 * is not reported as available.
Chris Mason0b86a832008-03-24 15:01:56 -04001555 */
Qu Wenruo9e3246a2019-07-19 14:51:41 +08001556static int find_free_dev_extent_start(struct btrfs_device *device,
1557 u64 num_bytes, u64 search_start, u64 *start,
1558 u64 *len)
Chris Mason0b86a832008-03-24 15:01:56 -04001559{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04001560 struct btrfs_fs_info *fs_info = device->fs_info;
1561 struct btrfs_root *root = fs_info->dev_root;
Chris Mason0b86a832008-03-24 15:01:56 -04001562 struct btrfs_key key;
Miao Xie7bfc8372011-01-05 10:07:26 +00001563 struct btrfs_dev_extent *dev_extent;
Yan Zheng2b820322008-11-17 21:11:30 -05001564 struct btrfs_path *path;
Miao Xie7bfc8372011-01-05 10:07:26 +00001565 u64 hole_size;
1566 u64 max_hole_start;
1567 u64 max_hole_size;
1568 u64 extent_end;
Chris Mason0b86a832008-03-24 15:01:56 -04001569 u64 search_end = device->total_bytes;
1570 int ret;
Miao Xie7bfc8372011-01-05 10:07:26 +00001571 int slot;
Chris Mason0b86a832008-03-24 15:01:56 -04001572 struct extent_buffer *l;
Filipe Manana8cdc7c52016-01-06 22:42:35 +00001573
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001574 search_start = dev_extent_search_start(device, search_start);
Chris Mason0b86a832008-03-24 15:01:56 -04001575
Naohiro Aota1cd61212021-02-04 19:21:48 +09001576 WARN_ON(device->zone_info &&
1577 !IS_ALIGNED(num_bytes, device->zone_info->zone_size));
1578
Josef Bacik6df9a952013-06-27 13:22:46 -04001579 path = btrfs_alloc_path();
1580 if (!path)
1581 return -ENOMEM;
Zhao Leif2ab7612015-02-16 18:52:17 +08001582
Miao Xie7bfc8372011-01-05 10:07:26 +00001583 max_hole_start = search_start;
1584 max_hole_size = 0;
1585
Zhao Leif2ab7612015-02-16 18:52:17 +08001586again:
Anand Jain401e29c2017-12-04 12:54:55 +08001587 if (search_start >= search_end ||
1588 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
Miao Xie7bfc8372011-01-05 10:07:26 +00001589 ret = -ENOSPC;
Josef Bacik6df9a952013-06-27 13:22:46 -04001590 goto out;
Miao Xie7bfc8372011-01-05 10:07:26 +00001591 }
1592
David Sterbae4058b52015-11-27 16:31:35 +01001593 path->reada = READA_FORWARD;
Josef Bacik6df9a952013-06-27 13:22:46 -04001594 path->search_commit_root = 1;
1595 path->skip_locking = 1;
Miao Xie7bfc8372011-01-05 10:07:26 +00001596
Chris Mason0b86a832008-03-24 15:01:56 -04001597 key.objectid = device->devid;
1598 key.offset = search_start;
1599 key.type = BTRFS_DEV_EXTENT_KEY;
Miao Xie7bfc8372011-01-05 10:07:26 +00001600
Li Zefan125ccb02011-12-08 15:07:24 +08001601 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
Chris Mason0b86a832008-03-24 15:01:56 -04001602 if (ret < 0)
Miao Xie7bfc8372011-01-05 10:07:26 +00001603 goto out;
Yan Zheng1fcbac52009-07-24 11:06:53 -04001604 if (ret > 0) {
1605 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1606 if (ret < 0)
Miao Xie7bfc8372011-01-05 10:07:26 +00001607 goto out;
Yan Zheng1fcbac52009-07-24 11:06:53 -04001608 }
Miao Xie7bfc8372011-01-05 10:07:26 +00001609
Chris Mason0b86a832008-03-24 15:01:56 -04001610 while (1) {
1611 l = path->nodes[0];
1612 slot = path->slots[0];
1613 if (slot >= btrfs_header_nritems(l)) {
1614 ret = btrfs_next_leaf(root, path);
1615 if (ret == 0)
1616 continue;
1617 if (ret < 0)
Miao Xie7bfc8372011-01-05 10:07:26 +00001618 goto out;
1619
1620 break;
Chris Mason0b86a832008-03-24 15:01:56 -04001621 }
1622 btrfs_item_key_to_cpu(l, &key, slot);
1623
1624 if (key.objectid < device->devid)
1625 goto next;
1626
1627 if (key.objectid > device->devid)
Miao Xie7bfc8372011-01-05 10:07:26 +00001628 break;
Chris Mason0b86a832008-03-24 15:01:56 -04001629
David Sterba962a2982014-06-04 18:41:45 +02001630 if (key.type != BTRFS_DEV_EXTENT_KEY)
Chris Mason0b86a832008-03-24 15:01:56 -04001631 goto next;
Chris Mason0b86a832008-03-24 15:01:56 -04001632
Miao Xie7bfc8372011-01-05 10:07:26 +00001633 if (key.offset > search_start) {
1634 hole_size = key.offset - search_start;
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001635 dev_extent_hole_check(device, &search_start, &hole_size,
1636 num_bytes);
Josef Bacik6df9a952013-06-27 13:22:46 -04001637
Miao Xie7bfc8372011-01-05 10:07:26 +00001638 if (hole_size > max_hole_size) {
1639 max_hole_start = search_start;
1640 max_hole_size = hole_size;
1641 }
1642
1643 /*
1644 * If this free space is greater than which we need,
1645 * it must be the max free space that we have found
1646 * until now, so max_hole_start must point to the start
1647 * of this free space and the length of this free space
1648 * is stored in max_hole_size. Thus, we return
1649 * max_hole_start and max_hole_size and go back to the
1650 * caller.
1651 */
1652 if (hole_size >= num_bytes) {
1653 ret = 0;
1654 goto out;
1655 }
1656 }
1657
Chris Mason0b86a832008-03-24 15:01:56 -04001658 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
Miao Xie7bfc8372011-01-05 10:07:26 +00001659 extent_end = key.offset + btrfs_dev_extent_length(l,
1660 dev_extent);
1661 if (extent_end > search_start)
1662 search_start = extent_end;
Chris Mason0b86a832008-03-24 15:01:56 -04001663next:
1664 path->slots[0]++;
1665 cond_resched();
1666 }
Chris Mason0b86a832008-03-24 15:01:56 -04001667
liubo38c01b92011-08-02 02:39:03 +00001668 /*
1669 * At this point, search_start should be the end of
1670 * allocated dev extents, and when shrinking the device,
1671 * search_end may be smaller than search_start.
1672 */
Zhao Leif2ab7612015-02-16 18:52:17 +08001673 if (search_end > search_start) {
liubo38c01b92011-08-02 02:39:03 +00001674 hole_size = search_end - search_start;
Naohiro Aota3b4ffa42020-02-25 12:56:09 +09001675 if (dev_extent_hole_check(device, &search_start, &hole_size,
1676 num_bytes)) {
Zhao Leif2ab7612015-02-16 18:52:17 +08001677 btrfs_release_path(path);
1678 goto again;
1679 }
Chris Mason0b86a832008-03-24 15:01:56 -04001680
Zhao Leif2ab7612015-02-16 18:52:17 +08001681 if (hole_size > max_hole_size) {
1682 max_hole_start = search_start;
1683 max_hole_size = hole_size;
1684 }
Josef Bacik6df9a952013-06-27 13:22:46 -04001685 }
1686
Miao Xie7bfc8372011-01-05 10:07:26 +00001687 /* See above. */
Zhao Leif2ab7612015-02-16 18:52:17 +08001688 if (max_hole_size < num_bytes)
Miao Xie7bfc8372011-01-05 10:07:26 +00001689 ret = -ENOSPC;
1690 else
1691 ret = 0;
1692
1693out:
Yan Zheng2b820322008-11-17 21:11:30 -05001694 btrfs_free_path(path);
Miao Xie7bfc8372011-01-05 10:07:26 +00001695 *start = max_hole_start;
Miao Xieb2117a32011-01-05 10:07:28 +00001696 if (len)
Miao Xie7bfc8372011-01-05 10:07:26 +00001697 *len = max_hole_size;
Chris Mason0b86a832008-03-24 15:01:56 -04001698 return ret;
1699}
1700
Nikolay Borisov60dfdf22019-03-27 14:24:14 +02001701int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
Jeff Mahoney499f3772015-06-15 09:41:17 -04001702 u64 *start, u64 *len)
1703{
Jeff Mahoney499f3772015-06-15 09:41:17 -04001704 /* FIXME use last free of some kind */
Nikolay Borisov60dfdf22019-03-27 14:24:14 +02001705 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
Jeff Mahoney499f3772015-06-15 09:41:17 -04001706}
1707
Christoph Hellwigb2950862008-12-02 09:54:17 -05001708static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
Chris Mason8f18cf12008-04-25 16:53:30 -04001709 struct btrfs_device *device,
Miao Xie2196d6e2014-09-03 21:35:41 +08001710 u64 start, u64 *dev_extent_len)
Chris Mason8f18cf12008-04-25 16:53:30 -04001711{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04001712 struct btrfs_fs_info *fs_info = device->fs_info;
1713 struct btrfs_root *root = fs_info->dev_root;
Chris Mason8f18cf12008-04-25 16:53:30 -04001714 int ret;
1715 struct btrfs_path *path;
Chris Mason8f18cf12008-04-25 16:53:30 -04001716 struct btrfs_key key;
Chris Masona061fc82008-05-07 11:43:44 -04001717 struct btrfs_key found_key;
1718 struct extent_buffer *leaf = NULL;
1719 struct btrfs_dev_extent *extent = NULL;
Chris Mason8f18cf12008-04-25 16:53:30 -04001720
1721 path = btrfs_alloc_path();
1722 if (!path)
1723 return -ENOMEM;
1724
1725 key.objectid = device->devid;
1726 key.offset = start;
1727 key.type = BTRFS_DEV_EXTENT_KEY;
Miao Xie924cd8f2011-11-10 20:45:04 -05001728again:
Chris Mason8f18cf12008-04-25 16:53:30 -04001729 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
Chris Masona061fc82008-05-07 11:43:44 -04001730 if (ret > 0) {
1731 ret = btrfs_previous_item(root, path, key.objectid,
1732 BTRFS_DEV_EXTENT_KEY);
Tsutomu Itohb0b802d2011-05-19 07:03:42 +00001733 if (ret)
1734 goto out;
Chris Masona061fc82008-05-07 11:43:44 -04001735 leaf = path->nodes[0];
1736 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1737 extent = btrfs_item_ptr(leaf, path->slots[0],
1738 struct btrfs_dev_extent);
1739 BUG_ON(found_key.offset > start || found_key.offset +
1740 btrfs_dev_extent_length(leaf, extent) < start);
Miao Xie924cd8f2011-11-10 20:45:04 -05001741 key = found_key;
1742 btrfs_release_path(path);
1743 goto again;
Chris Masona061fc82008-05-07 11:43:44 -04001744 } else if (ret == 0) {
1745 leaf = path->nodes[0];
1746 extent = btrfs_item_ptr(leaf, path->slots[0],
1747 struct btrfs_dev_extent);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01001748 } else {
Jeff Mahoney79787ea2012-03-12 16:03:00 +01001749 goto out;
Chris Masona061fc82008-05-07 11:43:44 -04001750 }
Chris Mason8f18cf12008-04-25 16:53:30 -04001751
Miao Xie2196d6e2014-09-03 21:35:41 +08001752 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1753
Chris Mason8f18cf12008-04-25 16:53:30 -04001754 ret = btrfs_del_item(trans, root, path);
Filipe Manana79bd3712021-06-29 14:43:06 +01001755 if (ret == 0)
Josef Bacik3204d332015-09-24 10:46:10 -04001756 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
Tsutomu Itohb0b802d2011-05-19 07:03:42 +00001757out:
Chris Mason8f18cf12008-04-25 16:53:30 -04001758 btrfs_free_path(path);
1759 return ret;
1760}
1761
Josef Bacik6df9a952013-06-27 13:22:46 -04001762static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
Chris Mason0b86a832008-03-24 15:01:56 -04001763{
Josef Bacik6df9a952013-06-27 13:22:46 -04001764 struct extent_map_tree *em_tree;
1765 struct extent_map *em;
1766 struct rb_node *n;
1767 u64 ret = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04001768
David Sterbac8bf1b62019-05-17 11:43:17 +02001769 em_tree = &fs_info->mapping_tree;
Josef Bacik6df9a952013-06-27 13:22:46 -04001770 read_lock(&em_tree->lock);
Liu Bo07e1ce02018-08-23 03:51:52 +08001771 n = rb_last(&em_tree->map.rb_root);
Josef Bacik6df9a952013-06-27 13:22:46 -04001772 if (n) {
1773 em = rb_entry(n, struct extent_map, rb_node);
1774 ret = em->start + em->len;
Chris Mason0b86a832008-03-24 15:01:56 -04001775 }
Josef Bacik6df9a952013-06-27 13:22:46 -04001776 read_unlock(&em_tree->lock);
1777
Chris Mason0b86a832008-03-24 15:01:56 -04001778 return ret;
1779}
1780
Ilya Dryomov53f10652013-08-12 14:33:01 +03001781static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1782 u64 *devid_ret)
Chris Mason0b86a832008-03-24 15:01:56 -04001783{
1784 int ret;
1785 struct btrfs_key key;
1786 struct btrfs_key found_key;
Yan Zheng2b820322008-11-17 21:11:30 -05001787 struct btrfs_path *path;
1788
Yan Zheng2b820322008-11-17 21:11:30 -05001789 path = btrfs_alloc_path();
1790 if (!path)
1791 return -ENOMEM;
Chris Mason0b86a832008-03-24 15:01:56 -04001792
1793 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1794 key.type = BTRFS_DEV_ITEM_KEY;
1795 key.offset = (u64)-1;
1796
Ilya Dryomov53f10652013-08-12 14:33:01 +03001797 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
Chris Mason0b86a832008-03-24 15:01:56 -04001798 if (ret < 0)
1799 goto error;
1800
Anand Jaina06dee4d2019-08-27 15:40:44 +08001801 if (ret == 0) {
1802 /* Corruption */
1803 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1804 ret = -EUCLEAN;
1805 goto error;
1806 }
Chris Mason0b86a832008-03-24 15:01:56 -04001807
Ilya Dryomov53f10652013-08-12 14:33:01 +03001808 ret = btrfs_previous_item(fs_info->chunk_root, path,
1809 BTRFS_DEV_ITEMS_OBJECTID,
Chris Mason0b86a832008-03-24 15:01:56 -04001810 BTRFS_DEV_ITEM_KEY);
1811 if (ret) {
Ilya Dryomov53f10652013-08-12 14:33:01 +03001812 *devid_ret = 1;
Chris Mason0b86a832008-03-24 15:01:56 -04001813 } else {
1814 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1815 path->slots[0]);
Ilya Dryomov53f10652013-08-12 14:33:01 +03001816 *devid_ret = found_key.offset + 1;
Chris Mason0b86a832008-03-24 15:01:56 -04001817 }
1818 ret = 0;
1819error:
Yan Zheng2b820322008-11-17 21:11:30 -05001820 btrfs_free_path(path);
Chris Mason0b86a832008-03-24 15:01:56 -04001821 return ret;
1822}
1823
1824/*
1825 * the device information is stored in the chunk root
1826 * the btrfs_device struct should be fully filled in
1827 */
Anand Jainc74a0b02017-11-06 16:36:15 +08001828static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
Eric Sandeen48a3b632013-04-25 20:41:01 +00001829 struct btrfs_device *device)
Chris Mason0b86a832008-03-24 15:01:56 -04001830{
1831 int ret;
1832 struct btrfs_path *path;
1833 struct btrfs_dev_item *dev_item;
1834 struct extent_buffer *leaf;
1835 struct btrfs_key key;
1836 unsigned long ptr;
Chris Mason0b86a832008-03-24 15:01:56 -04001837
Chris Mason0b86a832008-03-24 15:01:56 -04001838 path = btrfs_alloc_path();
1839 if (!path)
1840 return -ENOMEM;
1841
Chris Mason0b86a832008-03-24 15:01:56 -04001842 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1843 key.type = BTRFS_DEV_ITEM_KEY;
Yan Zheng2b820322008-11-17 21:11:30 -05001844 key.offset = device->devid;
Chris Mason0b86a832008-03-24 15:01:56 -04001845
Nikolay Borisov8e87e852018-07-20 19:37:47 +03001846 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1847 &key, sizeof(*dev_item));
Chris Mason0b86a832008-03-24 15:01:56 -04001848 if (ret)
1849 goto out;
1850
1851 leaf = path->nodes[0];
1852 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1853
1854 btrfs_set_device_id(leaf, dev_item, device->devid);
Yan Zheng2b820322008-11-17 21:11:30 -05001855 btrfs_set_device_generation(leaf, dev_item, 0);
Chris Mason0b86a832008-03-24 15:01:56 -04001856 btrfs_set_device_type(leaf, dev_item, device->type);
1857 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1858 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1859 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
Miao Xie7cc8e582014-09-03 21:35:38 +08001860 btrfs_set_device_total_bytes(leaf, dev_item,
1861 btrfs_device_get_disk_total_bytes(device));
1862 btrfs_set_device_bytes_used(leaf, dev_item,
1863 btrfs_device_get_bytes_used(device));
Chris Masone17cade2008-04-15 15:41:47 -04001864 btrfs_set_device_group(leaf, dev_item, 0);
1865 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1866 btrfs_set_device_bandwidth(leaf, dev_item, 0);
Chris Masonc3027eb2008-12-08 16:40:21 -05001867 btrfs_set_device_start_offset(leaf, dev_item, 0);
Chris Mason0b86a832008-03-24 15:01:56 -04001868
Geert Uytterhoeven410ba3a2013-08-20 13:20:11 +02001869 ptr = btrfs_device_uuid(dev_item);
Chris Masone17cade2008-04-15 15:41:47 -04001870 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
Geert Uytterhoeven1473b242013-08-20 13:20:12 +02001871 ptr = btrfs_device_fsid(dev_item);
Nikolay Borisovde37aa52018-10-30 16:43:24 +02001872 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1873 ptr, BTRFS_FSID_SIZE);
Chris Mason0b86a832008-03-24 15:01:56 -04001874 btrfs_mark_buffer_dirty(leaf);
Chris Mason0b86a832008-03-24 15:01:56 -04001875
Yan Zheng2b820322008-11-17 21:11:30 -05001876 ret = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04001877out:
1878 btrfs_free_path(path);
1879 return ret;
1880}
Chris Mason8f18cf12008-04-25 16:53:30 -04001881
Qu Wenruo5a1972b2014-04-16 17:02:32 +08001882/*
1883 * Function to update ctime/mtime for a given device path.
1884 * Mainly used for ctime/mtime based probe like libblkid.
1885 */
David Sterbada353f62017-02-14 17:55:53 +01001886static void update_dev_time(const char *path_name)
Qu Wenruo5a1972b2014-04-16 17:02:32 +08001887{
1888 struct file *filp;
1889
1890 filp = filp_open(path_name, O_RDWR, 0);
Al Viro98af5922014-12-14 02:59:17 -05001891 if (IS_ERR(filp))
Qu Wenruo5a1972b2014-04-16 17:02:32 +08001892 return;
1893 file_update_time(filp);
1894 filp_close(filp, NULL);
Qu Wenruo5a1972b2014-04-16 17:02:32 +08001895}
1896
David Sterbaf331a952019-03-20 16:31:53 +01001897static int btrfs_rm_dev_item(struct btrfs_device *device)
Chris Masona061fc82008-05-07 11:43:44 -04001898{
David Sterbaf331a952019-03-20 16:31:53 +01001899 struct btrfs_root *root = device->fs_info->chunk_root;
Chris Masona061fc82008-05-07 11:43:44 -04001900 int ret;
1901 struct btrfs_path *path;
Chris Masona061fc82008-05-07 11:43:44 -04001902 struct btrfs_key key;
Chris Masona061fc82008-05-07 11:43:44 -04001903 struct btrfs_trans_handle *trans;
1904
Chris Masona061fc82008-05-07 11:43:44 -04001905 path = btrfs_alloc_path();
1906 if (!path)
1907 return -ENOMEM;
1908
Yan, Zhenga22285a2010-05-16 10:48:46 -04001909 trans = btrfs_start_transaction(root, 0);
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00001910 if (IS_ERR(trans)) {
1911 btrfs_free_path(path);
1912 return PTR_ERR(trans);
1913 }
Chris Masona061fc82008-05-07 11:43:44 -04001914 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1915 key.type = BTRFS_DEV_ITEM_KEY;
1916 key.offset = device->devid;
1917
1918 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
Nikolay Borisov5e9f2ad2017-10-23 09:58:46 +03001919 if (ret) {
1920 if (ret > 0)
1921 ret = -ENOENT;
1922 btrfs_abort_transaction(trans, ret);
1923 btrfs_end_transaction(trans);
Chris Masona061fc82008-05-07 11:43:44 -04001924 goto out;
1925 }
1926
1927 ret = btrfs_del_item(trans, root, path);
Nikolay Borisov5e9f2ad2017-10-23 09:58:46 +03001928 if (ret) {
1929 btrfs_abort_transaction(trans, ret);
1930 btrfs_end_transaction(trans);
1931 }
1932
Chris Masona061fc82008-05-07 11:43:44 -04001933out:
1934 btrfs_free_path(path);
Nikolay Borisov5e9f2ad2017-10-23 09:58:46 +03001935 if (!ret)
1936 ret = btrfs_commit_transaction(trans);
Chris Masona061fc82008-05-07 11:43:44 -04001937 return ret;
1938}
1939
David Sterba3cc31a02016-02-15 16:00:26 +01001940/*
1941 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1942 * filesystem. It's up to the caller to adjust that number regarding eg. device
1943 * replace.
1944 */
1945static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1946 u64 num_devices)
Chris Masona061fc82008-05-07 11:43:44 -04001947{
Chris Masona061fc82008-05-07 11:43:44 -04001948 u64 all_avail;
Miao Xiede98ced2013-01-29 10:13:12 +00001949 unsigned seq;
David Sterba418775a2016-02-15 16:28:14 +01001950 int i;
Chris Masona061fc82008-05-07 11:43:44 -04001951
Miao Xiede98ced2013-01-29 10:13:12 +00001952 do {
Anand Jainbd45ffb2016-02-13 10:01:34 +08001953 seq = read_seqbegin(&fs_info->profiles_lock);
Miao Xiede98ced2013-01-29 10:13:12 +00001954
Anand Jainbd45ffb2016-02-13 10:01:34 +08001955 all_avail = fs_info->avail_data_alloc_bits |
1956 fs_info->avail_system_alloc_bits |
1957 fs_info->avail_metadata_alloc_bits;
1958 } while (read_seqretry(&fs_info->profiles_lock, seq));
Anand Jainf1fa7f22016-02-13 10:01:33 +08001959
David Sterba418775a2016-02-15 16:28:14 +01001960 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
Anand Jain41a6e892018-04-25 19:01:43 +08001961 if (!(all_avail & btrfs_raid_array[i].bg_flag))
David Sterba418775a2016-02-15 16:28:14 +01001962 continue;
Chris Masona061fc82008-05-07 11:43:44 -04001963
David Sterba418775a2016-02-15 16:28:14 +01001964 if (num_devices < btrfs_raid_array[i].devs_min) {
Anand Jainf9fbcaa2018-04-25 19:01:44 +08001965 int ret = btrfs_raid_array[i].mindev_error;
Chris Masona061fc82008-05-07 11:43:44 -04001966
David Sterba418775a2016-02-15 16:28:14 +01001967 if (ret)
1968 return ret;
1969 }
Anand Jainbd45ffb2016-02-13 10:01:34 +08001970 }
1971
1972 return 0;
Anand Jainf1fa7f22016-02-13 10:01:33 +08001973}
1974
Omar Sandovalc9162bd2017-08-22 23:46:04 -07001975static struct btrfs_device * btrfs_find_next_active_device(
1976 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
Anand Jain88acff62016-05-03 17:44:43 +08001977{
1978 struct btrfs_device *next_device;
1979
1980 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1981 if (next_device != device &&
Anand Jaine6e674b2017-12-04 12:54:54 +08001982 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1983 && next_device->bdev)
Anand Jain88acff62016-05-03 17:44:43 +08001984 return next_device;
1985 }
1986
1987 return NULL;
1988}
1989
1990/*
1991 * Helper function to check if the given device is part of s_bdev / latest_bdev
1992 * and replace it with the provided or the next active device, in the context
1993 * where this function called, there should be always be another device (or
1994 * this_dev) which is active.
1995 */
David Sterbab105e922019-10-01 19:57:35 +02001996void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
Anand Jaine493e8f2020-09-05 01:34:34 +08001997 struct btrfs_device *next_device)
Anand Jain88acff62016-05-03 17:44:43 +08001998{
Nikolay Borisovd6507cf2018-07-20 19:37:50 +03001999 struct btrfs_fs_info *fs_info = device->fs_info;
Anand Jain88acff62016-05-03 17:44:43 +08002000
Anand Jaine493e8f2020-09-05 01:34:34 +08002001 if (!next_device)
Anand Jain88acff62016-05-03 17:44:43 +08002002 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
Anand Jaine493e8f2020-09-05 01:34:34 +08002003 device);
Anand Jain88acff62016-05-03 17:44:43 +08002004 ASSERT(next_device);
2005
2006 if (fs_info->sb->s_bdev &&
2007 (fs_info->sb->s_bdev == device->bdev))
2008 fs_info->sb->s_bdev = next_device->bdev;
2009
2010 if (fs_info->fs_devices->latest_bdev == device->bdev)
2011 fs_info->fs_devices->latest_bdev = next_device->bdev;
2012}
2013
Anand Jain1da73962018-08-10 13:53:21 +08002014/*
2015 * Return btrfs_fs_devices::num_devices excluding the device that's being
2016 * currently replaced.
2017 */
2018static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2019{
2020 u64 num_devices = fs_info->fs_devices->num_devices;
2021
David Sterbacb5583d2018-09-07 16:11:23 +02002022 down_read(&fs_info->dev_replace.rwsem);
Anand Jain1da73962018-08-10 13:53:21 +08002023 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2024 ASSERT(num_devices > 1);
2025 num_devices--;
2026 }
David Sterbacb5583d2018-09-07 16:11:23 +02002027 up_read(&fs_info->dev_replace.rwsem);
Anand Jain1da73962018-08-10 13:53:21 +08002028
2029 return num_devices;
2030}
2031
Josef Bacik313b0852020-08-20 11:18:26 -04002032void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2033 struct block_device *bdev,
2034 const char *device_path)
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002035{
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002036 struct btrfs_super_block *disk_super;
2037 int copy_num;
2038
2039 if (!bdev)
2040 return;
2041
2042 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002043 struct page *page;
2044 int ret;
2045
2046 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2047 if (IS_ERR(disk_super))
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002048 continue;
2049
Naohiro Aota12659252020-11-10 20:26:14 +09002050 if (bdev_is_zoned(bdev)) {
2051 btrfs_reset_sb_log_zones(bdev, copy_num);
2052 continue;
2053 }
2054
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002055 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002056
2057 page = virt_to_page(disk_super);
2058 set_page_dirty(page);
2059 lock_page(page);
2060 /* write_on_page() unlocks the page */
2061 ret = write_one_page(page);
2062 if (ret)
2063 btrfs_warn(fs_info,
2064 "error clearing superblock number %d (%d)",
2065 copy_num, ret);
2066 btrfs_release_disk_super(disk_super);
2067
Johannes Thumshirn6fbceb92020-02-14 00:24:31 +09002068 }
2069
2070 /* Notify udev that device has changed */
2071 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2072
2073 /* Update ctime/mtime for device path for libblkid */
2074 update_dev_time(device_path);
2075}
2076
David Sterbada353f62017-02-14 17:55:53 +01002077int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
Anand Jain53f8a742020-09-05 01:34:27 +08002078 u64 devid)
Anand Jainf1fa7f22016-02-13 10:01:33 +08002079{
2080 struct btrfs_device *device;
Anand Jainf1fa7f22016-02-13 10:01:33 +08002081 struct btrfs_fs_devices *cur_devices;
Anand Jainb5185192018-04-12 10:29:30 +08002082 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Anand Jainf1fa7f22016-02-13 10:01:33 +08002083 u64 num_devices;
Anand Jainf1fa7f22016-02-13 10:01:33 +08002084 int ret = 0;
Anand Jainf1fa7f22016-02-13 10:01:33 +08002085
2086 mutex_lock(&uuid_mutex);
Chris Masona061fc82008-05-07 11:43:44 -04002087
Anand Jain1da73962018-08-10 13:53:21 +08002088 num_devices = btrfs_num_devices(fs_info);
Chris Masona061fc82008-05-07 11:43:44 -04002089
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002090 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
Anand Jainf1fa7f22016-02-13 10:01:33 +08002091 if (ret)
Chris Masona061fc82008-05-07 11:43:44 -04002092 goto out;
Chris Masona061fc82008-05-07 11:43:44 -04002093
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002094 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2095
2096 if (IS_ERR(device)) {
2097 if (PTR_ERR(device) == -ENOENT &&
2098 strcmp(device_path, "missing") == 0)
2099 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2100 else
2101 ret = PTR_ERR(device);
Chris Masona061fc82008-05-07 11:43:44 -04002102 goto out;
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002103 }
Yan Zheng2b820322008-11-17 21:11:30 -05002104
Omar Sandovaleede2bf2016-11-03 10:28:12 -07002105 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2106 btrfs_warn_in_rcu(fs_info,
2107 "cannot remove device %s (devid %llu) due to active swapfile",
2108 rcu_str_deref(device->name), device->devid);
2109 ret = -ETXTBSY;
2110 goto out;
2111 }
2112
Anand Jain401e29c2017-12-04 12:54:55 +08002113 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
Anand Jain183860f2013-05-17 10:52:45 +00002114 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
Anand Jain24fc5722016-02-13 10:01:36 +08002115 goto out;
Stefan Behrens63a212a2012-11-05 18:29:28 +01002116 }
2117
Anand Jainebbede42017-12-04 12:54:52 +08002118 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2119 fs_info->fs_devices->rw_devices == 1) {
Anand Jain183860f2013-05-17 10:52:45 +00002120 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
Anand Jain24fc5722016-02-13 10:01:36 +08002121 goto out;
Yan Zheng2b820322008-11-17 21:11:30 -05002122 }
2123
Anand Jainebbede42017-12-04 12:54:52 +08002124 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
David Sterba34441362016-10-04 19:34:27 +02002125 mutex_lock(&fs_info->chunk_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05002126 list_del_init(&device->dev_alloc_list);
Miao Xiec3929c32014-09-03 21:35:47 +08002127 device->fs_devices->rw_devices--;
David Sterba34441362016-10-04 19:34:27 +02002128 mutex_unlock(&fs_info->chunk_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05002129 }
Chris Masona061fc82008-05-07 11:43:44 -04002130
Carey Underwoodd7901552013-03-04 16:37:06 -06002131 mutex_unlock(&uuid_mutex);
Chris Masona061fc82008-05-07 11:43:44 -04002132 ret = btrfs_shrink_device(device, 0);
Filipe Manana66d204a2020-10-12 11:55:24 +01002133 if (!ret)
2134 btrfs_reada_remove_dev(device);
Carey Underwoodd7901552013-03-04 16:37:06 -06002135 mutex_lock(&uuid_mutex);
Chris Masona061fc82008-05-07 11:43:44 -04002136 if (ret)
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002137 goto error_undo;
Chris Masona061fc82008-05-07 11:43:44 -04002138
Stefan Behrens63a212a2012-11-05 18:29:28 +01002139 /*
2140 * TODO: the superblock still includes this device in its num_devices
2141 * counter although write_all_supers() is not locked out. This
2142 * could give a filesystem state which requires a degraded mount.
2143 */
David Sterbaf331a952019-03-20 16:31:53 +01002144 ret = btrfs_rm_dev_item(device);
Chris Masona061fc82008-05-07 11:43:44 -04002145 if (ret)
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002146 goto error_undo;
Chris Masona061fc82008-05-07 11:43:44 -04002147
Anand Jaine12c9622017-12-04 12:54:53 +08002148 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
David Sterba163e97e2019-03-20 16:32:55 +01002149 btrfs_scrub_cancel_dev(device);
Chris Masone5e9a522009-06-10 15:17:02 -04002150
2151 /*
2152 * the device list mutex makes sure that we don't change
2153 * the device list while someone else is writing out all
Filipe David Borba Mananad7306802013-08-09 15:41:36 +01002154 * the device supers. Whoever is writing all supers, should
2155 * lock the device list mutex before getting the number of
2156 * devices in the super block (super_copy). Conversely,
2157 * whoever updates the number of devices in the super block
2158 * (super_copy) should hold the device list mutex.
Chris Masone5e9a522009-06-10 15:17:02 -04002159 */
Xiao Guangrong1f781602011-04-20 10:09:16 +00002160
Anand Jain41a52a02018-04-12 10:29:31 +08002161 /*
2162 * In normal cases the cur_devices == fs_devices. But in case
2163 * of deleting a seed device, the cur_devices should point to
2164 * its own fs_devices listed under the fs_devices->seed.
2165 */
Xiao Guangrong1f781602011-04-20 10:09:16 +00002166 cur_devices = device->fs_devices;
Anand Jainb5185192018-04-12 10:29:30 +08002167 mutex_lock(&fs_devices->device_list_mutex);
Xiao Guangrong1f781602011-04-20 10:09:16 +00002168 list_del_rcu(&device->dev_list);
Chris Masone5e9a522009-06-10 15:17:02 -04002169
Anand Jain41a52a02018-04-12 10:29:31 +08002170 cur_devices->num_devices--;
2171 cur_devices->total_devices--;
Anand Jainb4993e62018-07-03 17:07:23 +08002172 /* Update total_devices of the parent fs_devices if it's seed */
2173 if (cur_devices != fs_devices)
2174 fs_devices->total_devices--;
Yan Zheng2b820322008-11-17 21:11:30 -05002175
Anand Jaine6e674b2017-12-04 12:54:54 +08002176 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
Anand Jain41a52a02018-04-12 10:29:31 +08002177 cur_devices->missing_devices--;
Chris Masoncd02dca2010-12-13 14:56:23 -05002178
Nikolay Borisovd6507cf2018-07-20 19:37:50 +03002179 btrfs_assign_next_active_device(device, NULL);
Yan Zheng2b820322008-11-17 21:11:30 -05002180
Eric Sandeen0bfaa9c2014-07-07 12:34:49 -05002181 if (device->bdev) {
Anand Jain41a52a02018-04-12 10:29:31 +08002182 cur_devices->open_devices--;
Eric Sandeen0bfaa9c2014-07-07 12:34:49 -05002183 /* remove sysfs entry */
Anand Jain53f8a742020-09-05 01:34:27 +08002184 btrfs_sysfs_remove_device(device);
Eric Sandeen0bfaa9c2014-07-07 12:34:49 -05002185 }
Anand Jain99994cd2014-06-03 11:36:00 +08002186
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002187 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2188 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
Anand Jainb5185192018-04-12 10:29:30 +08002189 mutex_unlock(&fs_devices->device_list_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05002190
Jeff Mahoneycea67ab2016-09-20 08:50:21 -04002191 /*
2192 * at this point, the device is zero sized and detached from
2193 * the devices list. All that's left is to zero out the old
2194 * supers and free the device.
2195 */
Anand Jainebbede42017-12-04 12:54:52 +08002196 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002197 btrfs_scratch_superblocks(fs_info, device->bdev,
2198 device->name->str);
Jeff Mahoneycea67ab2016-09-20 08:50:21 -04002199
2200 btrfs_close_bdev(device);
Nikolay Borisov8e75fd82019-03-27 14:24:11 +02002201 synchronize_rcu();
2202 btrfs_free_device(device);
Jeff Mahoneycea67ab2016-09-20 08:50:21 -04002203
Xiao Guangrong1f781602011-04-20 10:09:16 +00002204 if (cur_devices->open_devices == 0) {
Nikolay Borisov944d3f92020-07-16 10:25:33 +03002205 list_del_init(&cur_devices->seed_list);
Anand Jain0226e0e2018-04-12 10:29:27 +08002206 close_fs_devices(cur_devices);
Xiao Guangrong1f781602011-04-20 10:09:16 +00002207 free_fs_devices(cur_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05002208 }
2209
Chris Masona061fc82008-05-07 11:43:44 -04002210out:
2211 mutex_unlock(&uuid_mutex);
Chris Masona061fc82008-05-07 11:43:44 -04002212 return ret;
Anand Jain24fc5722016-02-13 10:01:36 +08002213
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002214error_undo:
Filipe Manana66d204a2020-10-12 11:55:24 +01002215 btrfs_reada_undo_remove_dev(device);
Anand Jainebbede42017-12-04 12:54:52 +08002216 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
David Sterba34441362016-10-04 19:34:27 +02002217 mutex_lock(&fs_info->chunk_mutex);
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002218 list_add(&device->dev_alloc_list,
Anand Jainb5185192018-04-12 10:29:30 +08002219 &fs_devices->alloc_list);
Miao Xiec3929c32014-09-03 21:35:47 +08002220 device->fs_devices->rw_devices++;
David Sterba34441362016-10-04 19:34:27 +02002221 mutex_unlock(&fs_info->chunk_mutex);
Ilya Dryomov9b3517e2011-02-15 18:14:25 +00002222 }
Anand Jain24fc5722016-02-13 10:01:36 +08002223 goto out;
Chris Masona061fc82008-05-07 11:43:44 -04002224}
2225
Nikolay Borisov68a9db52018-07-20 19:37:48 +03002226void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
Stefan Behrense93c89c2012-11-05 17:33:06 +01002227{
Anand Jaind51908c2014-08-13 14:24:19 +08002228 struct btrfs_fs_devices *fs_devices;
2229
Nikolay Borisov68a9db52018-07-20 19:37:48 +03002230 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
Ilya Dryomov13572722013-10-02 20:41:01 +03002231
Anand Jain25e8e912014-08-20 10:56:56 +08002232 /*
2233 * in case of fs with no seed, srcdev->fs_devices will point
2234 * to fs_devices of fs_info. However when the dev being replaced is
2235 * a seed dev it will point to the seed's local fs_devices. In short
2236 * srcdev will have its correct fs_devices in both the cases.
2237 */
2238 fs_devices = srcdev->fs_devices;
Anand Jaind51908c2014-08-13 14:24:19 +08002239
Stefan Behrense93c89c2012-11-05 17:33:06 +01002240 list_del_rcu(&srcdev->dev_list);
David Sterba619c47f2017-06-19 14:14:22 +02002241 list_del(&srcdev->dev_alloc_list);
Anand Jaind51908c2014-08-13 14:24:19 +08002242 fs_devices->num_devices--;
Anand Jaine6e674b2017-12-04 12:54:54 +08002243 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
Anand Jaind51908c2014-08-13 14:24:19 +08002244 fs_devices->missing_devices--;
Stefan Behrense93c89c2012-11-05 17:33:06 +01002245
Anand Jainebbede42017-12-04 12:54:52 +08002246 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
Miao Xie82372bc2014-09-03 21:35:44 +08002247 fs_devices->rw_devices--;
Ilya Dryomov13572722013-10-02 20:41:01 +03002248
Miao Xie82372bc2014-09-03 21:35:44 +08002249 if (srcdev->bdev)
Anand Jaind51908c2014-08-13 14:24:19 +08002250 fs_devices->open_devices--;
Qu Wenruo084b6e7c2014-10-30 16:52:31 +08002251}
2252
David Sterba65237ee2019-03-20 16:34:54 +01002253void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
Qu Wenruo084b6e7c2014-10-30 16:52:31 +08002254{
2255 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
Stefan Behrense93c89c2012-11-05 17:33:06 +01002256
Josef Bacika466c852020-08-20 11:18:27 -04002257 mutex_lock(&uuid_mutex);
2258
Anand Jain14238812016-07-22 06:04:53 +08002259 btrfs_close_bdev(srcdev);
Nikolay Borisov8e75fd82019-03-27 14:24:11 +02002260 synchronize_rcu();
2261 btrfs_free_device(srcdev);
Anand Jain94d5f0c2014-08-13 14:24:22 +08002262
Anand Jain94d5f0c2014-08-13 14:24:22 +08002263 /* if this is no devs we rather delete the fs_devices */
2264 if (!fs_devices->num_devices) {
Anand Jain6dd38f82017-10-17 06:53:50 +08002265 /*
2266 * On a mounted FS, num_devices can't be zero unless it's a
2267 * seed. In case of a seed device being replaced, the replace
2268 * target added to the sprout FS, so there will be no more
2269 * device left under the seed FS.
2270 */
2271 ASSERT(fs_devices->seeding);
2272
Nikolay Borisov944d3f92020-07-16 10:25:33 +03002273 list_del_init(&fs_devices->seed_list);
Anand Jain0226e0e2018-04-12 10:29:27 +08002274 close_fs_devices(fs_devices);
Anand Jain8bef8402014-08-13 14:24:23 +08002275 free_fs_devices(fs_devices);
Anand Jain94d5f0c2014-08-13 14:24:22 +08002276 }
Josef Bacika466c852020-08-20 11:18:27 -04002277 mutex_unlock(&uuid_mutex);
Stefan Behrense93c89c2012-11-05 17:33:06 +01002278}
2279
Nikolay Borisov4f5ad7b2018-07-20 19:37:51 +03002280void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
Stefan Behrense93c89c2012-11-05 17:33:06 +01002281{
Nikolay Borisov4f5ad7b2018-07-20 19:37:51 +03002282 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
Anand Jaind2ff1b22015-03-10 06:38:42 +08002283
Anand Jaind9a071f2018-04-12 10:29:38 +08002284 mutex_lock(&fs_devices->device_list_mutex);
2285
Anand Jain53f8a742020-09-05 01:34:27 +08002286 btrfs_sysfs_remove_device(tgtdev);
Anand Jaind2ff1b22015-03-10 06:38:42 +08002287
Anand Jain779bf3fe2016-04-18 16:51:23 +08002288 if (tgtdev->bdev)
Anand Jaind9a071f2018-04-12 10:29:38 +08002289 fs_devices->open_devices--;
Anand Jain779bf3fe2016-04-18 16:51:23 +08002290
Anand Jaind9a071f2018-04-12 10:29:38 +08002291 fs_devices->num_devices--;
Stefan Behrense93c89c2012-11-05 17:33:06 +01002292
Nikolay Borisovd6507cf2018-07-20 19:37:50 +03002293 btrfs_assign_next_active_device(tgtdev, NULL);
Stefan Behrense93c89c2012-11-05 17:33:06 +01002294
Stefan Behrense93c89c2012-11-05 17:33:06 +01002295 list_del_rcu(&tgtdev->dev_list);
Stefan Behrense93c89c2012-11-05 17:33:06 +01002296
Anand Jaind9a071f2018-04-12 10:29:38 +08002297 mutex_unlock(&fs_devices->device_list_mutex);
Anand Jain779bf3fe2016-04-18 16:51:23 +08002298
2299 /*
2300 * The update_dev_time() with in btrfs_scratch_superblocks()
2301 * may lead to a call to btrfs_show_devname() which will try
2302 * to hold device_list_mutex. And here this device
2303 * is already out of device list, so we don't have to hold
2304 * the device_list_mutex lock.
2305 */
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002306 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2307 tgtdev->name->str);
Anand Jain14238812016-07-22 06:04:53 +08002308
2309 btrfs_close_bdev(tgtdev);
Nikolay Borisov8e75fd82019-03-27 14:24:11 +02002310 synchronize_rcu();
2311 btrfs_free_device(tgtdev);
Stefan Behrense93c89c2012-11-05 17:33:06 +01002312}
2313
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002314static struct btrfs_device *btrfs_find_device_by_path(
2315 struct btrfs_fs_info *fs_info, const char *device_path)
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002316{
2317 int ret = 0;
2318 struct btrfs_super_block *disk_super;
2319 u64 devid;
2320 u8 *dev_uuid;
2321 struct block_device *bdev;
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002322 struct btrfs_device *device;
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002323
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002324 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002325 fs_info->bdev_holder, 0, &bdev, &disk_super);
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002326 if (ret)
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002327 return ERR_PTR(ret);
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002328
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002329 devid = btrfs_stack_device_id(&disk_super->dev_item);
2330 dev_uuid = disk_super->dev_item.uuid;
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002331 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
Anand Jaine4319cd2019-01-17 23:32:31 +08002332 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
Anand Jainb2598ed2020-11-03 13:49:43 +08002333 disk_super->metadata_uuid);
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002334 else
Anand Jaine4319cd2019-01-17 23:32:31 +08002335 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
Anand Jainb2598ed2020-11-03 13:49:43 +08002336 disk_super->fsid);
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002337
Johannes Thumshirn8f323802020-02-14 00:24:32 +09002338 btrfs_release_disk_super(disk_super);
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002339 if (!device)
2340 device = ERR_PTR(-ENOENT);
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002341 blkdev_put(bdev, FMODE_READ);
Nikolay Borisovb444ad42018-09-03 12:46:12 +03002342 return device;
Stefan Behrens7ba15b72012-11-05 14:42:30 +01002343}
2344
Yan Zheng2b820322008-11-17 21:11:30 -05002345/*
David Sterba5c5c0df2016-02-15 16:39:55 +01002346 * Lookup a device given by device id, or the path if the id is 0.
2347 */
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002348struct btrfs_device *btrfs_find_device_by_devspec(
Anand Jain6e927ce2019-01-17 23:32:29 +08002349 struct btrfs_fs_info *fs_info, u64 devid,
2350 const char *device_path)
Anand Jain24e04742016-02-13 10:01:35 +08002351{
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002352 struct btrfs_device *device;
Anand Jain24e04742016-02-13 10:01:35 +08002353
David Sterba5c5c0df2016-02-15 16:39:55 +01002354 if (devid) {
Anand Jaine4319cd2019-01-17 23:32:31 +08002355 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
Anand Jainb2598ed2020-11-03 13:49:43 +08002356 NULL);
Nikolay Borisova27a94c2018-09-03 12:46:14 +03002357 if (!device)
2358 return ERR_PTR(-ENOENT);
Anand Jain6e927ce2019-01-17 23:32:29 +08002359 return device;
Anand Jain24e04742016-02-13 10:01:35 +08002360 }
Anand Jain6e927ce2019-01-17 23:32:29 +08002361
2362 if (!device_path || !device_path[0])
2363 return ERR_PTR(-EINVAL);
2364
2365 if (strcmp(device_path, "missing") == 0) {
2366 /* Find first missing device */
2367 list_for_each_entry(device, &fs_info->fs_devices->devices,
2368 dev_list) {
2369 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2370 &device->dev_state) && !device->bdev)
2371 return device;
2372 }
2373 return ERR_PTR(-ENOENT);
2374 }
2375
2376 return btrfs_find_device_by_path(fs_info, device_path);
Anand Jain24e04742016-02-13 10:01:35 +08002377}
2378
Yan Zheng2b820322008-11-17 21:11:30 -05002379/*
2380 * does all the dirty work required for changing file system's UUID.
2381 */
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04002382static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
Yan Zheng2b820322008-11-17 21:11:30 -05002383{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002384 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05002385 struct btrfs_fs_devices *old_devices;
Yan Zhenge4404d62008-12-12 10:03:26 -05002386 struct btrfs_fs_devices *seed_devices;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002387 struct btrfs_super_block *disk_super = fs_info->super_copy;
Yan Zheng2b820322008-11-17 21:11:30 -05002388 struct btrfs_device *device;
2389 u64 super_flags;
2390
David Sterbaa32bf9a2018-03-16 02:21:22 +01002391 lockdep_assert_held(&uuid_mutex);
Yan Zhenge4404d62008-12-12 10:03:26 -05002392 if (!fs_devices->seeding)
Yan Zheng2b820322008-11-17 21:11:30 -05002393 return -EINVAL;
2394
Nikolay Borisov427c8fd2020-08-12 17:04:36 +03002395 /*
2396 * Private copy of the seed devices, anchored at
2397 * fs_info->fs_devices->seed_list
2398 */
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002399 seed_devices = alloc_fs_devices(NULL, NULL);
Ilya Dryomov2208a372013-08-12 14:33:03 +03002400 if (IS_ERR(seed_devices))
2401 return PTR_ERR(seed_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05002402
Nikolay Borisov427c8fd2020-08-12 17:04:36 +03002403 /*
2404 * It's necessary to retain a copy of the original seed fs_devices in
2405 * fs_uuids so that filesystems which have been seeded can successfully
2406 * reference the seed device from open_seed_devices. This also supports
2407 * multiple fs seed.
2408 */
Yan Zhenge4404d62008-12-12 10:03:26 -05002409 old_devices = clone_fs_devices(fs_devices);
2410 if (IS_ERR(old_devices)) {
2411 kfree(seed_devices);
2412 return PTR_ERR(old_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05002413 }
Yan Zhenge4404d62008-12-12 10:03:26 -05002414
Anand Jainc4babc52018-04-12 10:29:25 +08002415 list_add(&old_devices->fs_list, &fs_uuids);
Yan Zheng2b820322008-11-17 21:11:30 -05002416
Yan Zhenge4404d62008-12-12 10:03:26 -05002417 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2418 seed_devices->opened = 1;
2419 INIT_LIST_HEAD(&seed_devices->devices);
2420 INIT_LIST_HEAD(&seed_devices->alloc_list);
Chris Masone5e9a522009-06-10 15:17:02 -04002421 mutex_init(&seed_devices->device_list_mutex);
Xiao Guangrongc9513ed2011-04-20 10:07:30 +00002422
Anand Jain321a4bf2018-07-16 22:58:09 +08002423 mutex_lock(&fs_devices->device_list_mutex);
Xiao Guangrong1f781602011-04-20 10:09:16 +00002424 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2425 synchronize_rcu);
Miao Xie2196d6e2014-09-03 21:35:41 +08002426 list_for_each_entry(device, &seed_devices->devices, dev_list)
Yan Zhenge4404d62008-12-12 10:03:26 -05002427 device->fs_devices = seed_devices;
Miao Xie2196d6e2014-09-03 21:35:41 +08002428
Johannes Thumshirn0395d842019-11-13 11:27:27 +01002429 fs_devices->seeding = false;
Yan Zheng2b820322008-11-17 21:11:30 -05002430 fs_devices->num_devices = 0;
2431 fs_devices->open_devices = 0;
Miao Xie69611ac2014-07-03 18:22:12 +08002432 fs_devices->missing_devices = 0;
Johannes Thumshirn7f0432d2019-11-13 11:27:28 +01002433 fs_devices->rotating = false;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03002434 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
Yan Zheng2b820322008-11-17 21:11:30 -05002435
2436 generate_random_uuid(fs_devices->fsid);
Nikolay Borisov7239ff42018-10-30 16:43:23 +02002437 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
Yan Zheng2b820322008-11-17 21:11:30 -05002438 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
Anand Jain321a4bf2018-07-16 22:58:09 +08002439 mutex_unlock(&fs_devices->device_list_mutex);
Filipe David Borba Mananaf7171752013-08-12 20:56:58 +01002440
Yan Zheng2b820322008-11-17 21:11:30 -05002441 super_flags = btrfs_super_flags(disk_super) &
2442 ~BTRFS_SUPER_FLAG_SEEDING;
2443 btrfs_set_super_flags(disk_super, super_flags);
2444
2445 return 0;
2446}
2447
2448/*
Nicholas D Steeves01327612016-05-19 21:18:45 -04002449 * Store the expected generation for seed devices in device items.
Yan Zheng2b820322008-11-17 21:11:30 -05002450 */
David Sterba5c4666292019-03-20 16:36:39 +01002451static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
Yan Zheng2b820322008-11-17 21:11:30 -05002452{
David Sterba5c4666292019-03-20 16:36:39 +01002453 struct btrfs_fs_info *fs_info = trans->fs_info;
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04002454 struct btrfs_root *root = fs_info->chunk_root;
Yan Zheng2b820322008-11-17 21:11:30 -05002455 struct btrfs_path *path;
2456 struct extent_buffer *leaf;
2457 struct btrfs_dev_item *dev_item;
2458 struct btrfs_device *device;
2459 struct btrfs_key key;
Anand Jain44880fd2017-07-29 17:50:09 +08002460 u8 fs_uuid[BTRFS_FSID_SIZE];
Yan Zheng2b820322008-11-17 21:11:30 -05002461 u8 dev_uuid[BTRFS_UUID_SIZE];
2462 u64 devid;
2463 int ret;
2464
2465 path = btrfs_alloc_path();
2466 if (!path)
2467 return -ENOMEM;
2468
Yan Zheng2b820322008-11-17 21:11:30 -05002469 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2470 key.offset = 0;
2471 key.type = BTRFS_DEV_ITEM_KEY;
2472
2473 while (1) {
2474 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2475 if (ret < 0)
2476 goto error;
2477
2478 leaf = path->nodes[0];
2479next_slot:
2480 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2481 ret = btrfs_next_leaf(root, path);
2482 if (ret > 0)
2483 break;
2484 if (ret < 0)
2485 goto error;
2486 leaf = path->nodes[0];
2487 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
David Sterbab3b4aa72011-04-21 01:20:15 +02002488 btrfs_release_path(path);
Yan Zheng2b820322008-11-17 21:11:30 -05002489 continue;
2490 }
2491
2492 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2493 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2494 key.type != BTRFS_DEV_ITEM_KEY)
2495 break;
2496
2497 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2498 struct btrfs_dev_item);
2499 devid = btrfs_device_id(leaf, dev_item);
Geert Uytterhoeven410ba3a2013-08-20 13:20:11 +02002500 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
Yan Zheng2b820322008-11-17 21:11:30 -05002501 BTRFS_UUID_SIZE);
Geert Uytterhoeven1473b242013-08-20 13:20:12 +02002502 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
Anand Jain44880fd2017-07-29 17:50:09 +08002503 BTRFS_FSID_SIZE);
Anand Jaine4319cd2019-01-17 23:32:31 +08002504 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
Anand Jainb2598ed2020-11-03 13:49:43 +08002505 fs_uuid);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002506 BUG_ON(!device); /* Logic error */
Yan Zheng2b820322008-11-17 21:11:30 -05002507
2508 if (device->fs_devices->seeding) {
2509 btrfs_set_device_generation(leaf, dev_item,
2510 device->generation);
2511 btrfs_mark_buffer_dirty(leaf);
2512 }
2513
2514 path->slots[0]++;
2515 goto next_slot;
2516 }
2517 ret = 0;
2518error:
2519 btrfs_free_path(path);
2520 return ret;
2521}
2522
David Sterbada353f62017-02-14 17:55:53 +01002523int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
Chris Mason788f20e2008-04-28 15:29:42 -04002524{
Jeff Mahoney5112feb2016-06-21 20:16:08 -04002525 struct btrfs_root *root = fs_info->dev_root;
Josef Bacikd5e20032011-08-04 14:52:27 +00002526 struct request_queue *q;
Chris Mason788f20e2008-04-28 15:29:42 -04002527 struct btrfs_trans_handle *trans;
2528 struct btrfs_device *device;
2529 struct block_device *bdev;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002530 struct super_block *sb = fs_info->sb;
Josef Bacik606686e2012-06-04 14:03:51 -04002531 struct rcu_string *name;
Anand Jain5da54bc2018-07-03 13:14:50 +08002532 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Naohiro Aota39379fa2018-07-27 09:04:55 +09002533 u64 orig_super_total_bytes;
2534 u64 orig_super_num_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05002535 int seeding_dev = 0;
Chris Mason788f20e2008-04-28 15:29:42 -04002536 int ret = 0;
Nikolay Borisov44cab9b2020-07-22 11:09:23 +03002537 bool locked = false;
Chris Mason788f20e2008-04-28 15:29:42 -04002538
Anand Jain5da54bc2018-07-03 13:14:50 +08002539 if (sb_rdonly(sb) && !fs_devices->seeding)
Liu Bof8c5d0b2012-05-10 18:10:38 +08002540 return -EROFS;
Chris Mason788f20e2008-04-28 15:29:42 -04002541
Li Zefana5d163332011-12-07 20:08:40 -05002542 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002543 fs_info->bdev_holder);
Josef Bacik7f592032010-01-27 02:09:00 +00002544 if (IS_ERR(bdev))
2545 return PTR_ERR(bdev);
Chris Masona2135012008-06-25 16:01:30 -04002546
Naohiro Aotab70f5092020-11-10 20:26:08 +09002547 if (!btrfs_check_device_zone_type(fs_info, bdev)) {
2548 ret = -EINVAL;
2549 goto error;
2550 }
2551
Anand Jain5da54bc2018-07-03 13:14:50 +08002552 if (fs_devices->seeding) {
Yan Zheng2b820322008-11-17 21:11:30 -05002553 seeding_dev = 1;
2554 down_write(&sb->s_umount);
2555 mutex_lock(&uuid_mutex);
Nikolay Borisov44cab9b2020-07-22 11:09:23 +03002556 locked = true;
Yan Zheng2b820322008-11-17 21:11:30 -05002557 }
2558
Nikolay Borisovb9ba0172020-07-22 11:09:25 +03002559 sync_blockdev(bdev);
Chris Masona2135012008-06-25 16:01:30 -04002560
Nikolay Borisovf4cfa9b2020-07-22 11:09:22 +03002561 rcu_read_lock();
2562 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
Chris Mason788f20e2008-04-28 15:29:42 -04002563 if (device->bdev == bdev) {
2564 ret = -EEXIST;
Nikolay Borisovf4cfa9b2020-07-22 11:09:22 +03002565 rcu_read_unlock();
Yan Zheng2b820322008-11-17 21:11:30 -05002566 goto error;
Chris Mason788f20e2008-04-28 15:29:42 -04002567 }
2568 }
Nikolay Borisovf4cfa9b2020-07-22 11:09:22 +03002569 rcu_read_unlock();
Chris Mason788f20e2008-04-28 15:29:42 -04002570
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002571 device = btrfs_alloc_device(fs_info, NULL, NULL);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03002572 if (IS_ERR(device)) {
Chris Mason788f20e2008-04-28 15:29:42 -04002573 /* we can safely leave the fs_devices entry around */
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03002574 ret = PTR_ERR(device);
Yan Zheng2b820322008-11-17 21:11:30 -05002575 goto error;
Chris Mason788f20e2008-04-28 15:29:42 -04002576 }
2577
David Sterba78f2c9e2016-02-11 14:25:38 +01002578 name = rcu_string_strdup(device_path, GFP_KERNEL);
Josef Bacik606686e2012-06-04 14:03:51 -04002579 if (!name) {
Yan Zheng2b820322008-11-17 21:11:30 -05002580 ret = -ENOMEM;
David Sterba5c4cf6c2017-10-30 19:29:46 +01002581 goto error_free_device;
Chris Mason788f20e2008-04-28 15:29:42 -04002582 }
Josef Bacik606686e2012-06-04 14:03:51 -04002583 rcu_assign_pointer(device->name, name);
Yan Zheng2b820322008-11-17 21:11:30 -05002584
Naohiro Aota5b316462020-11-10 20:26:07 +09002585 device->fs_info = fs_info;
2586 device->bdev = bdev;
2587
2588 ret = btrfs_get_dev_zone_info(device);
2589 if (ret)
2590 goto error_free_device;
2591
Yan, Zhenga22285a2010-05-16 10:48:46 -04002592 trans = btrfs_start_transaction(root, 0);
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00002593 if (IS_ERR(trans)) {
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00002594 ret = PTR_ERR(trans);
Naohiro Aota5b316462020-11-10 20:26:07 +09002595 goto error_free_zone;
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00002596 }
2597
Josef Bacikd5e20032011-08-04 14:52:27 +00002598 q = bdev_get_queue(bdev);
Anand Jainebbede42017-12-04 12:54:52 +08002599 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
Yan Zheng2b820322008-11-17 21:11:30 -05002600 device->generation = trans->transid;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002601 device->io_width = fs_info->sectorsize;
2602 device->io_align = fs_info->sectorsize;
2603 device->sector_size = fs_info->sectorsize;
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03002604 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2605 fs_info->sectorsize);
Yan Zheng2cc3c552009-06-04 09:23:50 -04002606 device->disk_total_bytes = device->total_bytes;
Miao Xie935e5cc2014-09-03 21:35:33 +08002607 device->commit_total_bytes = device->total_bytes;
Anand Jaine12c9622017-12-04 12:54:53 +08002608 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
Anand Jain401e29c2017-12-04 12:54:55 +08002609 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
Ilya Dryomovfb01aa82011-02-15 18:12:57 +00002610 device->mode = FMODE_EXCL;
Stefan Behrens27087f32013-10-11 15:20:42 +02002611 device->dev_stats_valid = 1;
David Sterba9f6d2512017-06-16 01:48:05 +02002612 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
Zheng Yan325cd4b2008-09-05 16:43:54 -04002613
Yan Zheng2b820322008-11-17 21:11:30 -05002614 if (seeding_dev) {
Filipe Mananaa0a1db72020-12-14 10:10:47 +00002615 btrfs_clear_sb_rdonly(sb);
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04002616 ret = btrfs_prepare_sprout(fs_info);
Anand Jaind31c32f2017-09-28 14:51:10 +08002617 if (ret) {
2618 btrfs_abort_transaction(trans, ret);
2619 goto error_trans;
2620 }
Yan Zheng2b820322008-11-17 21:11:30 -05002621 }
2622
Anand Jain5da54bc2018-07-03 13:14:50 +08002623 device->fs_devices = fs_devices;
Chris Masone5e9a522009-06-10 15:17:02 -04002624
Anand Jain5da54bc2018-07-03 13:14:50 +08002625 mutex_lock(&fs_devices->device_list_mutex);
David Sterba34441362016-10-04 19:34:27 +02002626 mutex_lock(&fs_info->chunk_mutex);
Anand Jain5da54bc2018-07-03 13:14:50 +08002627 list_add_rcu(&device->dev_list, &fs_devices->devices);
2628 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2629 fs_devices->num_devices++;
2630 fs_devices->open_devices++;
2631 fs_devices->rw_devices++;
2632 fs_devices->total_devices++;
2633 fs_devices->total_rw_bytes += device->total_bytes;
Yan Zheng2b820322008-11-17 21:11:30 -05002634
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03002635 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
Josef Bacik2bf64752011-09-26 17:12:22 -04002636
Anand Jaine884f4f2017-04-04 18:40:19 +08002637 if (!blk_queue_nonrot(q))
Johannes Thumshirn7f0432d2019-11-13 11:27:28 +01002638 fs_devices->rotating = true;
Chris Masonc2898112009-06-10 09:51:32 -04002639
Naohiro Aota39379fa2018-07-27 09:04:55 +09002640 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002641 btrfs_set_super_total_bytes(fs_info->super_copy,
Naohiro Aota39379fa2018-07-27 09:04:55 +09002642 round_down(orig_super_total_bytes + device->total_bytes,
2643 fs_info->sectorsize));
Chris Mason788f20e2008-04-28 15:29:42 -04002644
Naohiro Aota39379fa2018-07-27 09:04:55 +09002645 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2646 btrfs_set_super_num_devices(fs_info->super_copy,
2647 orig_super_num_devices + 1);
Anand Jain0d393762014-06-03 11:36:01 +08002648
Miao Xie2196d6e2014-09-03 21:35:41 +08002649 /*
2650 * we've got more storage, clear any full flags on the space
2651 * infos
2652 */
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002653 btrfs_clear_space_info_full(fs_info);
Miao Xie2196d6e2014-09-03 21:35:41 +08002654
David Sterba34441362016-10-04 19:34:27 +02002655 mutex_unlock(&fs_info->chunk_mutex);
Josef Bacikca108452020-09-01 08:09:01 -04002656
2657 /* Add sysfs device entry */
Anand Jaincd36da22020-09-05 01:34:26 +08002658 btrfs_sysfs_add_device(device);
Josef Bacikca108452020-09-01 08:09:01 -04002659
Anand Jain5da54bc2018-07-03 13:14:50 +08002660 mutex_unlock(&fs_devices->device_list_mutex);
Chris Mason788f20e2008-04-28 15:29:42 -04002661
Yan Zheng2b820322008-11-17 21:11:30 -05002662 if (seeding_dev) {
David Sterba34441362016-10-04 19:34:27 +02002663 mutex_lock(&fs_info->chunk_mutex);
David Sterba6f8e0fc2019-03-20 16:29:13 +01002664 ret = init_first_rw_device(trans);
David Sterba34441362016-10-04 19:34:27 +02002665 mutex_unlock(&fs_info->chunk_mutex);
David Sterba005d6422012-09-18 07:52:32 -06002666 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04002667 btrfs_abort_transaction(trans, ret);
Anand Jaind31c32f2017-09-28 14:51:10 +08002668 goto error_sysfs;
David Sterba005d6422012-09-18 07:52:32 -06002669 }
Miao Xie2196d6e2014-09-03 21:35:41 +08002670 }
2671
Nikolay Borisov8e87e852018-07-20 19:37:47 +03002672 ret = btrfs_add_dev_item(trans, device);
Miao Xie2196d6e2014-09-03 21:35:41 +08002673 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04002674 btrfs_abort_transaction(trans, ret);
Anand Jaind31c32f2017-09-28 14:51:10 +08002675 goto error_sysfs;
Miao Xie2196d6e2014-09-03 21:35:41 +08002676 }
2677
2678 if (seeding_dev) {
David Sterba5c4666292019-03-20 16:36:39 +01002679 ret = btrfs_finish_sprout(trans);
David Sterba005d6422012-09-18 07:52:32 -06002680 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04002681 btrfs_abort_transaction(trans, ret);
Anand Jaind31c32f2017-09-28 14:51:10 +08002682 goto error_sysfs;
David Sterba005d6422012-09-18 07:52:32 -06002683 }
Anand Jainb2373f22014-06-03 11:36:03 +08002684
Nikolay Borisov8e560082020-08-12 16:18:51 +03002685 /*
2686 * fs_devices now represents the newly sprouted filesystem and
2687 * its fsid has been changed by btrfs_prepare_sprout
2688 */
2689 btrfs_sysfs_update_sprout_fsid(fs_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05002690 }
2691
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04002692 ret = btrfs_commit_transaction(trans);
Yan Zheng2b820322008-11-17 21:11:30 -05002693
2694 if (seeding_dev) {
2695 mutex_unlock(&uuid_mutex);
2696 up_write(&sb->s_umount);
Nikolay Borisov44cab9b2020-07-22 11:09:23 +03002697 locked = false;
Yan Zheng2b820322008-11-17 21:11:30 -05002698
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002699 if (ret) /* transaction commit */
2700 return ret;
2701
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04002702 ret = btrfs_relocate_sys_chunks(fs_info);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002703 if (ret < 0)
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002704 btrfs_handle_fs_error(fs_info, ret,
Jeff Mahoney5d163e02016-09-20 10:05:00 -04002705 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
Miao Xie671415b2012-10-16 11:26:46 +00002706 trans = btrfs_attach_transaction(root);
2707 if (IS_ERR(trans)) {
2708 if (PTR_ERR(trans) == -ENOENT)
2709 return 0;
Anand Jain7132a262017-09-28 14:51:11 +08002710 ret = PTR_ERR(trans);
2711 trans = NULL;
2712 goto error_sysfs;
Miao Xie671415b2012-10-16 11:26:46 +00002713 }
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04002714 ret = btrfs_commit_transaction(trans);
Yan Zheng2b820322008-11-17 21:11:30 -05002715 }
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02002716
Anand Jain7f551d92020-05-05 02:58:26 +08002717 /*
2718 * Now that we have written a new super block to this device, check all
2719 * other fs_devices list if device_path alienates any other scanned
2720 * device.
2721 * We can ignore the return value as it typically returns -EINVAL and
2722 * only succeeds if the device was an alien.
2723 */
2724 btrfs_forget_devices(device_path);
2725
2726 /* Update ctime/mtime for blkid or udev */
Qu Wenruo5a1972b2014-04-16 17:02:32 +08002727 update_dev_time(device_path);
Anand Jain7f551d92020-05-05 02:58:26 +08002728
Chris Mason788f20e2008-04-28 15:29:42 -04002729 return ret;
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002730
Anand Jaind31c32f2017-09-28 14:51:10 +08002731error_sysfs:
Anand Jain53f8a742020-09-05 01:34:27 +08002732 btrfs_sysfs_remove_device(device);
Naohiro Aota39379fa2018-07-27 09:04:55 +09002733 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2734 mutex_lock(&fs_info->chunk_mutex);
2735 list_del_rcu(&device->dev_list);
2736 list_del(&device->dev_alloc_list);
2737 fs_info->fs_devices->num_devices--;
2738 fs_info->fs_devices->open_devices--;
2739 fs_info->fs_devices->rw_devices--;
2740 fs_info->fs_devices->total_devices--;
2741 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2742 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2743 btrfs_set_super_total_bytes(fs_info->super_copy,
2744 orig_super_total_bytes);
2745 btrfs_set_super_num_devices(fs_info->super_copy,
2746 orig_super_num_devices);
2747 mutex_unlock(&fs_info->chunk_mutex);
2748 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002749error_trans:
Anand Jain0af2c4b2017-09-28 14:51:09 +08002750 if (seeding_dev)
Filipe Mananaa0a1db72020-12-14 10:10:47 +00002751 btrfs_set_sb_rdonly(sb);
Anand Jain7132a262017-09-28 14:51:11 +08002752 if (trans)
2753 btrfs_end_transaction(trans);
Naohiro Aota5b316462020-11-10 20:26:07 +09002754error_free_zone:
2755 btrfs_destroy_dev_zone_info(device);
David Sterba5c4cf6c2017-10-30 19:29:46 +01002756error_free_device:
David Sterbaa425f9d2018-03-20 15:47:33 +01002757 btrfs_free_device(device);
Yan Zheng2b820322008-11-17 21:11:30 -05002758error:
Tejun Heoe525fd82010-11-13 11:55:17 +01002759 blkdev_put(bdev, FMODE_EXCL);
Nikolay Borisov44cab9b2020-07-22 11:09:23 +03002760 if (locked) {
Yan Zheng2b820322008-11-17 21:11:30 -05002761 mutex_unlock(&uuid_mutex);
2762 up_write(&sb->s_umount);
2763 }
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02002764 return ret;
Chris Mason788f20e2008-04-28 15:29:42 -04002765}
2766
Chris Masond3977122009-01-05 21:25:51 -05002767static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2768 struct btrfs_device *device)
Chris Mason0b86a832008-03-24 15:01:56 -04002769{
2770 int ret;
2771 struct btrfs_path *path;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002772 struct btrfs_root *root = device->fs_info->chunk_root;
Chris Mason0b86a832008-03-24 15:01:56 -04002773 struct btrfs_dev_item *dev_item;
2774 struct extent_buffer *leaf;
2775 struct btrfs_key key;
2776
Chris Mason0b86a832008-03-24 15:01:56 -04002777 path = btrfs_alloc_path();
2778 if (!path)
2779 return -ENOMEM;
2780
2781 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2782 key.type = BTRFS_DEV_ITEM_KEY;
2783 key.offset = device->devid;
2784
2785 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2786 if (ret < 0)
2787 goto out;
2788
2789 if (ret > 0) {
2790 ret = -ENOENT;
2791 goto out;
2792 }
2793
2794 leaf = path->nodes[0];
2795 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2796
2797 btrfs_set_device_id(leaf, dev_item, device->devid);
2798 btrfs_set_device_type(leaf, dev_item, device->type);
2799 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2800 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2801 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
Miao Xie7cc8e582014-09-03 21:35:38 +08002802 btrfs_set_device_total_bytes(leaf, dev_item,
2803 btrfs_device_get_disk_total_bytes(device));
2804 btrfs_set_device_bytes_used(leaf, dev_item,
2805 btrfs_device_get_bytes_used(device));
Chris Mason0b86a832008-03-24 15:01:56 -04002806 btrfs_mark_buffer_dirty(leaf);
2807
2808out:
2809 btrfs_free_path(path);
2810 return ret;
2811}
2812
Miao Xie2196d6e2014-09-03 21:35:41 +08002813int btrfs_grow_device(struct btrfs_trans_handle *trans,
Chris Mason8f18cf12008-04-25 16:53:30 -04002814 struct btrfs_device *device, u64 new_size)
2815{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002816 struct btrfs_fs_info *fs_info = device->fs_info;
2817 struct btrfs_super_block *super_copy = fs_info->super_copy;
Miao Xie2196d6e2014-09-03 21:35:41 +08002818 u64 old_total;
2819 u64 diff;
Chris Mason8f18cf12008-04-25 16:53:30 -04002820
Anand Jainebbede42017-12-04 12:54:52 +08002821 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
Yan Zheng2b820322008-11-17 21:11:30 -05002822 return -EACCES;
Miao Xie2196d6e2014-09-03 21:35:41 +08002823
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03002824 new_size = round_down(new_size, fs_info->sectorsize);
2825
David Sterba34441362016-10-04 19:34:27 +02002826 mutex_lock(&fs_info->chunk_mutex);
Miao Xie2196d6e2014-09-03 21:35:41 +08002827 old_total = btrfs_super_total_bytes(super_copy);
Nikolay Borisov0e4324a2017-07-21 11:28:24 +03002828 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
Miao Xie2196d6e2014-09-03 21:35:41 +08002829
Stefan Behrens63a212a2012-11-05 18:29:28 +01002830 if (new_size <= device->total_bytes ||
Anand Jain401e29c2017-12-04 12:54:55 +08002831 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
David Sterba34441362016-10-04 19:34:27 +02002832 mutex_unlock(&fs_info->chunk_mutex);
Yan Zheng2b820322008-11-17 21:11:30 -05002833 return -EINVAL;
Miao Xie2196d6e2014-09-03 21:35:41 +08002834 }
Yan Zheng2b820322008-11-17 21:11:30 -05002835
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03002836 btrfs_set_super_total_bytes(super_copy,
2837 round_down(old_total + diff, fs_info->sectorsize));
Yan Zheng2b820322008-11-17 21:11:30 -05002838 device->fs_devices->total_rw_bytes += diff;
2839
Miao Xie7cc8e582014-09-03 21:35:38 +08002840 btrfs_device_set_total_bytes(device, new_size);
2841 btrfs_device_set_disk_total_bytes(device, new_size);
Jeff Mahoneyfb456252016-06-22 18:54:56 -04002842 btrfs_clear_space_info_full(device->fs_info);
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02002843 if (list_empty(&device->post_commit_list))
2844 list_add_tail(&device->post_commit_list,
2845 &trans->transaction->dev_update_list);
David Sterba34441362016-10-04 19:34:27 +02002846 mutex_unlock(&fs_info->chunk_mutex);
Chris Mason4184ea72009-03-10 12:39:20 -04002847
Chris Mason8f18cf12008-04-25 16:53:30 -04002848 return btrfs_update_device(trans, device);
2849}
2850
Nikolay Borisovf4208792018-07-20 19:37:52 +03002851static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
Chris Mason8f18cf12008-04-25 16:53:30 -04002852{
Nikolay Borisovf4208792018-07-20 19:37:52 +03002853 struct btrfs_fs_info *fs_info = trans->fs_info;
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04002854 struct btrfs_root *root = fs_info->chunk_root;
Chris Mason8f18cf12008-04-25 16:53:30 -04002855 int ret;
2856 struct btrfs_path *path;
2857 struct btrfs_key key;
2858
Chris Mason8f18cf12008-04-25 16:53:30 -04002859 path = btrfs_alloc_path();
2860 if (!path)
2861 return -ENOMEM;
2862
Nikolay Borisov408fbf12017-07-27 14:37:29 +03002863 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
Chris Mason8f18cf12008-04-25 16:53:30 -04002864 key.offset = chunk_offset;
2865 key.type = BTRFS_CHUNK_ITEM_KEY;
2866
2867 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002868 if (ret < 0)
2869 goto out;
2870 else if (ret > 0) { /* Logic error or corruption */
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002871 btrfs_handle_fs_error(fs_info, -ENOENT,
2872 "Failed lookup while freeing chunk.");
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002873 ret = -ENOENT;
2874 goto out;
2875 }
Chris Mason8f18cf12008-04-25 16:53:30 -04002876
2877 ret = btrfs_del_item(trans, root, path);
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002878 if (ret < 0)
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002879 btrfs_handle_fs_error(fs_info, ret,
2880 "Failed to delete chunk item.");
Jeff Mahoney79787ea2012-03-12 16:03:00 +01002881out:
Chris Mason8f18cf12008-04-25 16:53:30 -04002882 btrfs_free_path(path);
Tsutomu Itoh65a246c2011-05-19 04:37:44 +00002883 return ret;
Chris Mason8f18cf12008-04-25 16:53:30 -04002884}
2885
Nikolay Borisov408fbf12017-07-27 14:37:29 +03002886static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
Chris Mason8f18cf12008-04-25 16:53:30 -04002887{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002888 struct btrfs_super_block *super_copy = fs_info->super_copy;
Chris Mason8f18cf12008-04-25 16:53:30 -04002889 struct btrfs_disk_key *disk_key;
2890 struct btrfs_chunk *chunk;
2891 u8 *ptr;
2892 int ret = 0;
2893 u32 num_stripes;
2894 u32 array_size;
2895 u32 len = 0;
2896 u32 cur;
2897 struct btrfs_key key;
2898
Filipe Manana79bd3712021-06-29 14:43:06 +01002899 lockdep_assert_held(&fs_info->chunk_mutex);
Chris Mason8f18cf12008-04-25 16:53:30 -04002900 array_size = btrfs_super_sys_array_size(super_copy);
2901
2902 ptr = super_copy->sys_chunk_array;
2903 cur = 0;
2904
2905 while (cur < array_size) {
2906 disk_key = (struct btrfs_disk_key *)ptr;
2907 btrfs_disk_key_to_cpu(&key, disk_key);
2908
2909 len = sizeof(*disk_key);
2910
2911 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2912 chunk = (struct btrfs_chunk *)(ptr + len);
2913 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2914 len += btrfs_chunk_item_size(num_stripes);
2915 } else {
2916 ret = -EIO;
2917 break;
2918 }
Nikolay Borisov408fbf12017-07-27 14:37:29 +03002919 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
Chris Mason8f18cf12008-04-25 16:53:30 -04002920 key.offset == chunk_offset) {
2921 memmove(ptr, ptr + len, array_size - (cur + len));
2922 array_size -= len;
2923 btrfs_set_super_sys_array_size(super_copy, array_size);
2924 } else {
2925 ptr += len;
2926 cur += len;
2927 }
2928 }
2929 return ret;
2930}
2931
Omar Sandoval60ca8422018-05-16 16:34:31 -07002932/*
2933 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2934 * @logical: Logical block offset in bytes.
2935 * @length: Length of extent in bytes.
2936 *
2937 * Return: Chunk mapping or ERR_PTR.
2938 */
2939struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2940 u64 logical, u64 length)
Liu Bo592d92e2017-03-14 13:33:55 -07002941{
2942 struct extent_map_tree *em_tree;
2943 struct extent_map *em;
2944
David Sterbac8bf1b62019-05-17 11:43:17 +02002945 em_tree = &fs_info->mapping_tree;
Liu Bo592d92e2017-03-14 13:33:55 -07002946 read_lock(&em_tree->lock);
2947 em = lookup_extent_mapping(em_tree, logical, length);
2948 read_unlock(&em_tree->lock);
2949
2950 if (!em) {
2951 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2952 logical, length);
2953 return ERR_PTR(-EINVAL);
2954 }
2955
2956 if (em->start > logical || em->start + em->len < logical) {
2957 btrfs_crit(fs_info,
2958 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2959 logical, length, em->start, em->start + em->len);
2960 free_extent_map(em);
2961 return ERR_PTR(-EINVAL);
2962 }
2963
2964 /* callers are responsible for dropping em's ref. */
2965 return em;
2966}
2967
Filipe Manana79bd3712021-06-29 14:43:06 +01002968static int remove_chunk_item(struct btrfs_trans_handle *trans,
2969 struct map_lookup *map, u64 chunk_offset)
2970{
2971 int i;
2972
2973 /*
2974 * Removing chunk items and updating the device items in the chunks btree
2975 * requires holding the chunk_mutex.
2976 * See the comment at btrfs_chunk_alloc() for the details.
2977 */
2978 lockdep_assert_held(&trans->fs_info->chunk_mutex);
2979
2980 for (i = 0; i < map->num_stripes; i++) {
2981 int ret;
2982
2983 ret = btrfs_update_device(trans, map->stripes[i].dev);
2984 if (ret)
2985 return ret;
2986 }
2987
2988 return btrfs_free_chunk(trans, chunk_offset);
2989}
2990
Nikolay Borisov97aff912018-07-20 19:37:53 +03002991int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
Josef Bacik47ab2a62014-09-18 11:20:02 -04002992{
Nikolay Borisov97aff912018-07-20 19:37:53 +03002993 struct btrfs_fs_info *fs_info = trans->fs_info;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002994 struct extent_map *em;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002995 struct map_lookup *map;
2996 u64 dev_extent_len = 0;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002997 int i, ret = 0;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04002998 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Josef Bacik47ab2a62014-09-18 11:20:02 -04002999
Omar Sandoval60ca8422018-05-16 16:34:31 -07003000 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
Liu Bo592d92e2017-03-14 13:33:55 -07003001 if (IS_ERR(em)) {
Josef Bacik47ab2a62014-09-18 11:20:02 -04003002 /*
3003 * This is a logic error, but we don't want to just rely on the
Adam Buchbinderbb7ab3b2016-03-04 11:23:12 -08003004 * user having built with ASSERT enabled, so if ASSERT doesn't
Josef Bacik47ab2a62014-09-18 11:20:02 -04003005 * do anything we still error out.
3006 */
3007 ASSERT(0);
Liu Bo592d92e2017-03-14 13:33:55 -07003008 return PTR_ERR(em);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003009 }
Jeff Mahoney95617d62015-06-03 10:55:48 -04003010 map = em->map_lookup;
Josef Bacik47ab2a62014-09-18 11:20:02 -04003011
Filipe Manana57ba4cb2016-05-20 04:34:23 +01003012 /*
Filipe Manana79bd3712021-06-29 14:43:06 +01003013 * First delete the device extent items from the devices btree.
3014 * We take the device_list_mutex to avoid racing with the finishing phase
3015 * of a device replace operation. See the comment below before acquiring
3016 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3017 * because that can result in a deadlock when deleting the device extent
3018 * items from the devices btree - COWing an extent buffer from the btree
3019 * may result in allocating a new metadata chunk, which would attempt to
3020 * lock again fs_info->chunk_mutex.
Filipe Manana57ba4cb2016-05-20 04:34:23 +01003021 */
3022 mutex_lock(&fs_devices->device_list_mutex);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003023 for (i = 0; i < map->num_stripes; i++) {
3024 struct btrfs_device *device = map->stripes[i].dev;
3025 ret = btrfs_free_dev_extent(trans, device,
3026 map->stripes[i].physical,
3027 &dev_extent_len);
3028 if (ret) {
Filipe Manana57ba4cb2016-05-20 04:34:23 +01003029 mutex_unlock(&fs_devices->device_list_mutex);
Jeff Mahoney66642832016-06-10 18:19:25 -04003030 btrfs_abort_transaction(trans, ret);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003031 goto out;
3032 }
3033
3034 if (device->bytes_used > 0) {
David Sterba34441362016-10-04 19:34:27 +02003035 mutex_lock(&fs_info->chunk_mutex);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003036 btrfs_device_set_bytes_used(device,
3037 device->bytes_used - dev_extent_len);
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03003038 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003039 btrfs_clear_space_info_full(fs_info);
David Sterba34441362016-10-04 19:34:27 +02003040 mutex_unlock(&fs_info->chunk_mutex);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003041 }
Josef Bacik47ab2a62014-09-18 11:20:02 -04003042 }
Filipe Manana57ba4cb2016-05-20 04:34:23 +01003043 mutex_unlock(&fs_devices->device_list_mutex);
3044
Filipe Manana79bd3712021-06-29 14:43:06 +01003045 /*
3046 * We acquire fs_info->chunk_mutex for 2 reasons:
3047 *
3048 * 1) Just like with the first phase of the chunk allocation, we must
3049 * reserve system space, do all chunk btree updates and deletions, and
3050 * update the system chunk array in the superblock while holding this
3051 * mutex. This is for similar reasons as explained on the comment at
3052 * the top of btrfs_chunk_alloc();
3053 *
3054 * 2) Prevent races with the final phase of a device replace operation
3055 * that replaces the device object associated with the map's stripes,
3056 * because the device object's id can change at any time during that
3057 * final phase of the device replace operation
3058 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3059 * replaced device and then see it with an ID of
3060 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3061 * the device item, which does not exists on the chunk btree.
3062 * The finishing phase of device replace acquires both the
3063 * device_list_mutex and the chunk_mutex, in that order, so we are
3064 * safe by just acquiring the chunk_mutex.
3065 */
3066 trans->removing_chunk = true;
3067 mutex_lock(&fs_info->chunk_mutex);
3068
3069 check_system_chunk(trans, map->type);
3070
3071 ret = remove_chunk_item(trans, map, chunk_offset);
3072 /*
3073 * Normally we should not get -ENOSPC since we reserved space before
3074 * through the call to check_system_chunk().
3075 *
3076 * Despite our system space_info having enough free space, we may not
3077 * be able to allocate extents from its block groups, because all have
3078 * an incompatible profile, which will force us to allocate a new system
3079 * block group with the right profile, or right after we called
3080 * check_system_space() above, a scrub turned the only system block group
3081 * with enough free space into RO mode.
3082 * This is explained with more detail at do_chunk_alloc().
3083 *
3084 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3085 */
3086 if (ret == -ENOSPC) {
3087 const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3088 struct btrfs_block_group *sys_bg;
3089
3090 sys_bg = btrfs_alloc_chunk(trans, sys_flags);
3091 if (IS_ERR(sys_bg)) {
3092 ret = PTR_ERR(sys_bg);
3093 btrfs_abort_transaction(trans, ret);
3094 goto out;
3095 }
3096
3097 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3098 if (ret) {
3099 btrfs_abort_transaction(trans, ret);
3100 goto out;
3101 }
3102
3103 ret = remove_chunk_item(trans, map, chunk_offset);
3104 if (ret) {
3105 btrfs_abort_transaction(trans, ret);
3106 goto out;
3107 }
3108 } else if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04003109 btrfs_abort_transaction(trans, ret);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003110 goto out;
3111 }
3112
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003113 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003114
3115 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
Nikolay Borisov408fbf12017-07-27 14:37:29 +03003116 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003117 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04003118 btrfs_abort_transaction(trans, ret);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003119 goto out;
3120 }
3121 }
3122
Filipe Manana79bd3712021-06-29 14:43:06 +01003123 mutex_unlock(&fs_info->chunk_mutex);
3124 trans->removing_chunk = false;
3125
3126 /*
3127 * We are done with chunk btree updates and deletions, so release the
3128 * system space we previously reserved (with check_system_chunk()).
3129 */
3130 btrfs_trans_release_chunk_metadata(trans);
3131
Nikolay Borisov5a98ec02018-06-20 15:48:56 +03003132 ret = btrfs_remove_block_group(trans, chunk_offset, em);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003133 if (ret) {
Jeff Mahoney66642832016-06-10 18:19:25 -04003134 btrfs_abort_transaction(trans, ret);
Josef Bacik47ab2a62014-09-18 11:20:02 -04003135 goto out;
3136 }
3137
Josef Bacik47ab2a62014-09-18 11:20:02 -04003138out:
Filipe Manana79bd3712021-06-29 14:43:06 +01003139 if (trans->removing_chunk) {
3140 mutex_unlock(&fs_info->chunk_mutex);
3141 trans->removing_chunk = false;
3142 }
Josef Bacik47ab2a62014-09-18 11:20:02 -04003143 /* once for us */
3144 free_extent_map(em);
Chris Mason8f18cf12008-04-25 16:53:30 -04003145 return ret;
3146}
3147
Johannes Thumshirn18bb8bb2021-04-19 16:41:02 +09003148int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
Chris Mason8f18cf12008-04-25 16:53:30 -04003149{
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04003150 struct btrfs_root *root = fs_info->chunk_root;
Chris Mason19c4d2f2016-10-10 13:43:31 -07003151 struct btrfs_trans_handle *trans;
Dennis Zhoub0643e52019-12-13 16:22:14 -08003152 struct btrfs_block_group *block_group;
Johannes Thumshirn01e86002021-04-19 16:41:00 +09003153 u64 length;
Chris Mason8f18cf12008-04-25 16:53:30 -04003154 int ret;
Chris Mason8f18cf12008-04-25 16:53:30 -04003155
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003156 /*
3157 * Prevent races with automatic removal of unused block groups.
3158 * After we relocate and before we remove the chunk with offset
3159 * chunk_offset, automatic removal of the block group can kick in,
3160 * resulting in a failure when calling btrfs_remove_chunk() below.
3161 *
3162 * Make sure to acquire this mutex before doing a tree search (dev
3163 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3164 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3165 * we release the path used to search the chunk/dev tree and before
3166 * the current task acquires this mutex and calls us.
3167 */
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003168 lockdep_assert_held(&fs_info->reclaim_bgs_lock);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003169
Chris Mason8f18cf12008-04-25 16:53:30 -04003170 /* step one, relocate all the extents inside this chunk */
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04003171 btrfs_scrub_pause(fs_info);
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003172 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04003173 btrfs_scrub_continue(fs_info);
Yan, Zhenga22285a2010-05-16 10:48:46 -04003174 if (ret)
3175 return ret;
Chris Mason8f18cf12008-04-25 16:53:30 -04003176
Dennis Zhoub0643e52019-12-13 16:22:14 -08003177 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3178 if (!block_group)
3179 return -ENOENT;
3180 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
Johannes Thumshirn01e86002021-04-19 16:41:00 +09003181 length = block_group->length;
Dennis Zhoub0643e52019-12-13 16:22:14 -08003182 btrfs_put_block_group(block_group);
3183
Johannes Thumshirn01e86002021-04-19 16:41:00 +09003184 /*
3185 * On a zoned file system, discard the whole block group, this will
3186 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3187 * resetting the zone fails, don't treat it as a fatal problem from the
3188 * filesystem's point of view.
3189 */
3190 if (btrfs_is_zoned(fs_info)) {
3191 ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3192 if (ret)
3193 btrfs_info(fs_info,
3194 "failed to reset zone %llu after relocation",
3195 chunk_offset);
3196 }
3197
Chris Mason19c4d2f2016-10-10 13:43:31 -07003198 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3199 chunk_offset);
3200 if (IS_ERR(trans)) {
3201 ret = PTR_ERR(trans);
3202 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3203 return ret;
3204 }
Naohiro Aota5d8eb6f2016-09-02 16:46:32 +09003205
Chris Mason19c4d2f2016-10-10 13:43:31 -07003206 /*
3207 * step two, delete the device extents and the
3208 * chunk tree entries
3209 */
Nikolay Borisov97aff912018-07-20 19:37:53 +03003210 ret = btrfs_remove_chunk(trans, chunk_offset);
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04003211 btrfs_end_transaction(trans);
Chris Mason19c4d2f2016-10-10 13:43:31 -07003212 return ret;
Chris Mason8f18cf12008-04-25 16:53:30 -04003213}
3214
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04003215static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
Yan Zheng2b820322008-11-17 21:11:30 -05003216{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003217 struct btrfs_root *chunk_root = fs_info->chunk_root;
Yan Zheng2b820322008-11-17 21:11:30 -05003218 struct btrfs_path *path;
3219 struct extent_buffer *leaf;
3220 struct btrfs_chunk *chunk;
3221 struct btrfs_key key;
3222 struct btrfs_key found_key;
Yan Zheng2b820322008-11-17 21:11:30 -05003223 u64 chunk_type;
Josef Bacikba1bf482009-09-11 16:11:19 -04003224 bool retried = false;
3225 int failed = 0;
Yan Zheng2b820322008-11-17 21:11:30 -05003226 int ret;
3227
3228 path = btrfs_alloc_path();
3229 if (!path)
3230 return -ENOMEM;
3231
Josef Bacikba1bf482009-09-11 16:11:19 -04003232again:
Yan Zheng2b820322008-11-17 21:11:30 -05003233 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3234 key.offset = (u64)-1;
3235 key.type = BTRFS_CHUNK_ITEM_KEY;
3236
3237 while (1) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003238 mutex_lock(&fs_info->reclaim_bgs_lock);
Yan Zheng2b820322008-11-17 21:11:30 -05003239 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003240 if (ret < 0) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003241 mutex_unlock(&fs_info->reclaim_bgs_lock);
Yan Zheng2b820322008-11-17 21:11:30 -05003242 goto error;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003243 }
Jeff Mahoney79787ea2012-03-12 16:03:00 +01003244 BUG_ON(ret == 0); /* Corruption */
Yan Zheng2b820322008-11-17 21:11:30 -05003245
3246 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3247 key.type);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003248 if (ret)
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003249 mutex_unlock(&fs_info->reclaim_bgs_lock);
Yan Zheng2b820322008-11-17 21:11:30 -05003250 if (ret < 0)
3251 goto error;
3252 if (ret > 0)
3253 break;
3254
3255 leaf = path->nodes[0];
3256 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3257
3258 chunk = btrfs_item_ptr(leaf, path->slots[0],
3259 struct btrfs_chunk);
3260 chunk_type = btrfs_chunk_type(leaf, chunk);
David Sterbab3b4aa72011-04-21 01:20:15 +02003261 btrfs_release_path(path);
Yan Zheng2b820322008-11-17 21:11:30 -05003262
3263 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003264 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
Josef Bacikba1bf482009-09-11 16:11:19 -04003265 if (ret == -ENOSPC)
3266 failed++;
HIMANGI SARAOGI14586652014-07-09 03:51:41 +05303267 else
3268 BUG_ON(ret);
Yan Zheng2b820322008-11-17 21:11:30 -05003269 }
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003270 mutex_unlock(&fs_info->reclaim_bgs_lock);
Yan Zheng2b820322008-11-17 21:11:30 -05003271
3272 if (found_key.offset == 0)
3273 break;
3274 key.offset = found_key.offset - 1;
3275 }
3276 ret = 0;
Josef Bacikba1bf482009-09-11 16:11:19 -04003277 if (failed && !retried) {
3278 failed = 0;
3279 retried = true;
3280 goto again;
Dulshani Gunawardhanafae7f212013-10-31 10:30:08 +05303281 } else if (WARN_ON(failed && retried)) {
Josef Bacikba1bf482009-09-11 16:11:19 -04003282 ret = -ENOSPC;
3283 }
Yan Zheng2b820322008-11-17 21:11:30 -05003284error:
3285 btrfs_free_path(path);
3286 return ret;
3287}
3288
Liu Boa6f93c72017-11-15 16:28:11 -07003289/*
3290 * return 1 : allocate a data chunk successfully,
3291 * return <0: errors during allocating a data chunk,
3292 * return 0 : no need to allocate a data chunk.
3293 */
3294static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3295 u64 chunk_offset)
3296{
David Sterba32da53862019-10-29 19:20:18 +01003297 struct btrfs_block_group *cache;
Liu Boa6f93c72017-11-15 16:28:11 -07003298 u64 bytes_used;
3299 u64 chunk_type;
3300
3301 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3302 ASSERT(cache);
3303 chunk_type = cache->flags;
3304 btrfs_put_block_group(cache);
3305
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003306 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3307 return 0;
Liu Boa6f93c72017-11-15 16:28:11 -07003308
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003309 spin_lock(&fs_info->data_sinfo->lock);
3310 bytes_used = fs_info->data_sinfo->bytes_used;
3311 spin_unlock(&fs_info->data_sinfo->lock);
Liu Boa6f93c72017-11-15 16:28:11 -07003312
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003313 if (!bytes_used) {
3314 struct btrfs_trans_handle *trans;
3315 int ret;
Liu Boa6f93c72017-11-15 16:28:11 -07003316
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003317 trans = btrfs_join_transaction(fs_info->tree_root);
3318 if (IS_ERR(trans))
3319 return PTR_ERR(trans);
3320
3321 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3322 btrfs_end_transaction(trans);
3323 if (ret < 0)
3324 return ret;
3325 return 1;
Liu Boa6f93c72017-11-15 16:28:11 -07003326 }
Johannes Thumshirn5ae21692019-10-18 11:58:22 +02003327
Liu Boa6f93c72017-11-15 16:28:11 -07003328 return 0;
3329}
3330
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003331static int insert_balance_item(struct btrfs_fs_info *fs_info,
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003332 struct btrfs_balance_control *bctl)
3333{
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003334 struct btrfs_root *root = fs_info->tree_root;
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003335 struct btrfs_trans_handle *trans;
3336 struct btrfs_balance_item *item;
3337 struct btrfs_disk_balance_args disk_bargs;
3338 struct btrfs_path *path;
3339 struct extent_buffer *leaf;
3340 struct btrfs_key key;
3341 int ret, err;
3342
3343 path = btrfs_alloc_path();
3344 if (!path)
3345 return -ENOMEM;
3346
3347 trans = btrfs_start_transaction(root, 0);
3348 if (IS_ERR(trans)) {
3349 btrfs_free_path(path);
3350 return PTR_ERR(trans);
3351 }
3352
3353 key.objectid = BTRFS_BALANCE_OBJECTID;
David Sterbac479cb42016-01-25 17:51:31 +01003354 key.type = BTRFS_TEMPORARY_ITEM_KEY;
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003355 key.offset = 0;
3356
3357 ret = btrfs_insert_empty_item(trans, root, path, &key,
3358 sizeof(*item));
3359 if (ret)
3360 goto out;
3361
3362 leaf = path->nodes[0];
3363 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3364
David Sterbab159fa22016-11-08 18:09:03 +01003365 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003366
3367 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3368 btrfs_set_balance_data(leaf, item, &disk_bargs);
3369 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3370 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3371 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3372 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3373
3374 btrfs_set_balance_flags(leaf, item, bctl->flags);
3375
3376 btrfs_mark_buffer_dirty(leaf);
3377out:
3378 btrfs_free_path(path);
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04003379 err = btrfs_commit_transaction(trans);
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003380 if (err && !ret)
3381 ret = err;
3382 return ret;
3383}
3384
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003385static int del_balance_item(struct btrfs_fs_info *fs_info)
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003386{
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04003387 struct btrfs_root *root = fs_info->tree_root;
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003388 struct btrfs_trans_handle *trans;
3389 struct btrfs_path *path;
3390 struct btrfs_key key;
3391 int ret, err;
3392
3393 path = btrfs_alloc_path();
3394 if (!path)
3395 return -ENOMEM;
3396
David Sterba3502a8c2020-06-25 12:35:28 +02003397 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003398 if (IS_ERR(trans)) {
3399 btrfs_free_path(path);
3400 return PTR_ERR(trans);
3401 }
3402
3403 key.objectid = BTRFS_BALANCE_OBJECTID;
David Sterbac479cb42016-01-25 17:51:31 +01003404 key.type = BTRFS_TEMPORARY_ITEM_KEY;
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003405 key.offset = 0;
3406
3407 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3408 if (ret < 0)
3409 goto out;
3410 if (ret > 0) {
3411 ret = -ENOENT;
3412 goto out;
3413 }
3414
3415 ret = btrfs_del_item(trans, root, path);
3416out:
3417 btrfs_free_path(path);
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04003418 err = btrfs_commit_transaction(trans);
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02003419 if (err && !ret)
3420 ret = err;
3421 return ret;
3422}
3423
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003424/*
Ilya Dryomov59641012012-01-16 22:04:48 +02003425 * This is a heuristic used to reduce the number of chunks balanced on
3426 * resume after balance was interrupted.
3427 */
3428static void update_balance_args(struct btrfs_balance_control *bctl)
3429{
3430 /*
3431 * Turn on soft mode for chunk types that were being converted.
3432 */
3433 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3434 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3435 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3436 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3437 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3438 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3439
3440 /*
3441 * Turn on usage filter if is not already used. The idea is
3442 * that chunks that we have already balanced should be
3443 * reasonably full. Don't do it for chunks that are being
3444 * converted - that will keep us from relocating unconverted
3445 * (albeit full) chunks.
3446 */
3447 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
David Sterbabc309462015-10-20 18:22:13 +02003448 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
Ilya Dryomov59641012012-01-16 22:04:48 +02003449 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3450 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3451 bctl->data.usage = 90;
3452 }
3453 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
David Sterbabc309462015-10-20 18:22:13 +02003454 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
Ilya Dryomov59641012012-01-16 22:04:48 +02003455 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3456 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3457 bctl->sys.usage = 90;
3458 }
3459 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
David Sterbabc309462015-10-20 18:22:13 +02003460 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
Ilya Dryomov59641012012-01-16 22:04:48 +02003461 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3462 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3463 bctl->meta.usage = 90;
3464 }
3465}
3466
3467/*
David Sterba149196a2018-03-20 20:23:09 +01003468 * Clear the balance status in fs_info and delete the balance item from disk.
3469 */
3470static void reset_balance_state(struct btrfs_fs_info *fs_info)
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003471{
3472 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
David Sterba149196a2018-03-20 20:23:09 +01003473 int ret;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003474
3475 BUG_ON(!fs_info->balance_ctl);
3476
3477 spin_lock(&fs_info->balance_lock);
3478 fs_info->balance_ctl = NULL;
3479 spin_unlock(&fs_info->balance_lock);
3480
3481 kfree(bctl);
David Sterba149196a2018-03-20 20:23:09 +01003482 ret = del_balance_item(fs_info);
3483 if (ret)
3484 btrfs_handle_fs_error(fs_info, ret, NULL);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003485}
3486
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003487/*
3488 * Balance filters. Return 1 if chunk should be filtered out
3489 * (should not be balanced).
3490 */
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003491static int chunk_profiles_filter(u64 chunk_type,
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003492 struct btrfs_balance_args *bargs)
3493{
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003494 chunk_type = chunk_to_extended(chunk_type) &
3495 BTRFS_EXTENDED_PROFILE_MASK;
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003496
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003497 if (bargs->profiles & chunk_type)
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003498 return 0;
3499
3500 return 1;
3501}
3502
Holger Hoffstättedba72cb2015-11-17 12:29:32 +01003503static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003504 struct btrfs_balance_args *bargs)
3505{
David Sterba32da53862019-10-29 19:20:18 +01003506 struct btrfs_block_group *cache;
David Sterbabc309462015-10-20 18:22:13 +02003507 u64 chunk_used;
3508 u64 user_thresh_min;
3509 u64 user_thresh_max;
3510 int ret = 1;
3511
3512 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
David Sterbabf38be62019-10-23 18:48:11 +02003513 chunk_used = cache->used;
David Sterbabc309462015-10-20 18:22:13 +02003514
3515 if (bargs->usage_min == 0)
3516 user_thresh_min = 0;
3517 else
David Sterbab3470b52019-10-23 18:48:22 +02003518 user_thresh_min = div_factor_fine(cache->length,
3519 bargs->usage_min);
David Sterbabc309462015-10-20 18:22:13 +02003520
3521 if (bargs->usage_max == 0)
3522 user_thresh_max = 1;
3523 else if (bargs->usage_max > 100)
David Sterbab3470b52019-10-23 18:48:22 +02003524 user_thresh_max = cache->length;
David Sterbabc309462015-10-20 18:22:13 +02003525 else
David Sterbab3470b52019-10-23 18:48:22 +02003526 user_thresh_max = div_factor_fine(cache->length,
3527 bargs->usage_max);
David Sterbabc309462015-10-20 18:22:13 +02003528
3529 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3530 ret = 0;
3531
3532 btrfs_put_block_group(cache);
3533 return ret;
3534}
3535
Holger Hoffstättedba72cb2015-11-17 12:29:32 +01003536static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
David Sterbabc309462015-10-20 18:22:13 +02003537 u64 chunk_offset, struct btrfs_balance_args *bargs)
3538{
David Sterba32da53862019-10-29 19:20:18 +01003539 struct btrfs_block_group *cache;
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003540 u64 chunk_used, user_thresh;
3541 int ret = 1;
3542
3543 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
David Sterbabf38be62019-10-23 18:48:11 +02003544 chunk_used = cache->used;
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003545
David Sterbabc309462015-10-20 18:22:13 +02003546 if (bargs->usage_min == 0)
Ilya Dryomov3e39cea2013-02-12 16:28:59 +00003547 user_thresh = 1;
Ilya Dryomova105bb82013-01-21 15:15:56 +02003548 else if (bargs->usage > 100)
David Sterbab3470b52019-10-23 18:48:22 +02003549 user_thresh = cache->length;
Ilya Dryomova105bb82013-01-21 15:15:56 +02003550 else
David Sterbab3470b52019-10-23 18:48:22 +02003551 user_thresh = div_factor_fine(cache->length, bargs->usage);
Ilya Dryomova105bb82013-01-21 15:15:56 +02003552
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003553 if (chunk_used < user_thresh)
3554 ret = 0;
3555
3556 btrfs_put_block_group(cache);
3557 return ret;
3558}
3559
Ilya Dryomov409d4042012-01-16 22:04:47 +02003560static int chunk_devid_filter(struct extent_buffer *leaf,
3561 struct btrfs_chunk *chunk,
3562 struct btrfs_balance_args *bargs)
3563{
3564 struct btrfs_stripe *stripe;
3565 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3566 int i;
3567
3568 for (i = 0; i < num_stripes; i++) {
3569 stripe = btrfs_stripe_nr(chunk, i);
3570 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3571 return 0;
3572 }
3573
3574 return 1;
3575}
3576
David Sterba946c9252019-05-17 11:43:34 +02003577static u64 calc_data_stripes(u64 type, int num_stripes)
3578{
3579 const int index = btrfs_bg_flags_to_raid_index(type);
3580 const int ncopies = btrfs_raid_array[index].ncopies;
3581 const int nparity = btrfs_raid_array[index].nparity;
3582
3583 if (nparity)
3584 return num_stripes - nparity;
3585 else
3586 return num_stripes / ncopies;
3587}
3588
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003589/* [pstart, pend) */
3590static int chunk_drange_filter(struct extent_buffer *leaf,
3591 struct btrfs_chunk *chunk,
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003592 struct btrfs_balance_args *bargs)
3593{
3594 struct btrfs_stripe *stripe;
3595 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3596 u64 stripe_offset;
3597 u64 stripe_length;
David Sterba946c9252019-05-17 11:43:34 +02003598 u64 type;
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003599 int factor;
3600 int i;
3601
3602 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3603 return 0;
3604
David Sterba946c9252019-05-17 11:43:34 +02003605 type = btrfs_chunk_type(leaf, chunk);
3606 factor = calc_data_stripes(type, num_stripes);
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003607
3608 for (i = 0; i < num_stripes; i++) {
3609 stripe = btrfs_stripe_nr(chunk, i);
3610 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3611 continue;
3612
3613 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3614 stripe_length = btrfs_chunk_length(leaf, chunk);
David Sterbab8b93ad2015-01-16 17:26:13 +01003615 stripe_length = div_u64(stripe_length, factor);
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003616
3617 if (stripe_offset < bargs->pend &&
3618 stripe_offset + stripe_length > bargs->pstart)
3619 return 0;
3620 }
3621
3622 return 1;
3623}
3624
Ilya Dryomovea671762012-01-16 22:04:48 +02003625/* [vstart, vend) */
3626static int chunk_vrange_filter(struct extent_buffer *leaf,
3627 struct btrfs_chunk *chunk,
3628 u64 chunk_offset,
3629 struct btrfs_balance_args *bargs)
3630{
3631 if (chunk_offset < bargs->vend &&
3632 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3633 /* at least part of the chunk is inside this vrange */
3634 return 0;
3635
3636 return 1;
3637}
3638
Gabríel Arthúr Péturssondee32d02015-09-28 22:32:41 +00003639static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3640 struct btrfs_chunk *chunk,
3641 struct btrfs_balance_args *bargs)
3642{
3643 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3644
3645 if (bargs->stripes_min <= num_stripes
3646 && num_stripes <= bargs->stripes_max)
3647 return 0;
3648
3649 return 1;
3650}
3651
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003652static int chunk_soft_convert_filter(u64 chunk_type,
Ilya Dryomovcfa4c962012-01-16 22:04:48 +02003653 struct btrfs_balance_args *bargs)
3654{
3655 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3656 return 0;
3657
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003658 chunk_type = chunk_to_extended(chunk_type) &
3659 BTRFS_EXTENDED_PROFILE_MASK;
Ilya Dryomovcfa4c962012-01-16 22:04:48 +02003660
Ilya Dryomov899c81e2012-03-27 17:09:16 +03003661 if (bargs->target == chunk_type)
Ilya Dryomovcfa4c962012-01-16 22:04:48 +02003662 return 1;
3663
3664 return 0;
3665}
3666
David Sterba6ec08962019-03-20 16:38:52 +01003667static int should_balance_chunk(struct extent_buffer *leaf,
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003668 struct btrfs_chunk *chunk, u64 chunk_offset)
3669{
David Sterba6ec08962019-03-20 16:38:52 +01003670 struct btrfs_fs_info *fs_info = leaf->fs_info;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003671 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003672 struct btrfs_balance_args *bargs = NULL;
3673 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3674
3675 /* type filter */
3676 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3677 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3678 return 0;
3679 }
3680
3681 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3682 bargs = &bctl->data;
3683 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3684 bargs = &bctl->sys;
3685 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3686 bargs = &bctl->meta;
3687
Ilya Dryomoved25e9b2012-01-16 22:04:47 +02003688 /* profiles filter */
3689 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3690 chunk_profiles_filter(chunk_type, bargs)) {
3691 return 0;
3692 }
3693
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003694 /* usage filter */
3695 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003696 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003697 return 0;
David Sterbabc309462015-10-20 18:22:13 +02003698 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
Jeff Mahoney0b246af2016-06-22 18:54:23 -04003699 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
David Sterbabc309462015-10-20 18:22:13 +02003700 return 0;
Ilya Dryomov5ce5b3c2012-01-16 22:04:47 +02003701 }
3702
Ilya Dryomov409d4042012-01-16 22:04:47 +02003703 /* devid filter */
3704 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3705 chunk_devid_filter(leaf, chunk, bargs)) {
3706 return 0;
3707 }
3708
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003709 /* drange filter, makes sense only with devid filter */
3710 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
Nikolay Borisove4ff5fb2017-07-19 10:48:42 +03003711 chunk_drange_filter(leaf, chunk, bargs)) {
Ilya Dryomov94e60d52012-01-16 22:04:48 +02003712 return 0;
3713 }
3714
Ilya Dryomovea671762012-01-16 22:04:48 +02003715 /* vrange filter */
3716 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3717 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3718 return 0;
3719 }
3720
Gabríel Arthúr Péturssondee32d02015-09-28 22:32:41 +00003721 /* stripes filter */
3722 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3723 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3724 return 0;
3725 }
3726
Ilya Dryomovcfa4c962012-01-16 22:04:48 +02003727 /* soft profile changing mode */
3728 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3729 chunk_soft_convert_filter(chunk_type, bargs)) {
3730 return 0;
3731 }
3732
David Sterba7d824b62014-05-07 17:37:51 +02003733 /*
3734 * limited by count, must be the last filter
3735 */
3736 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3737 if (bargs->limit == 0)
3738 return 0;
3739 else
3740 bargs->limit--;
David Sterba12907fc2015-10-10 17:16:50 +02003741 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3742 /*
3743 * Same logic as the 'limit' filter; the minimum cannot be
Nicholas D Steeves01327612016-05-19 21:18:45 -04003744 * determined here because we do not have the global information
David Sterba12907fc2015-10-10 17:16:50 +02003745 * about the count of all chunks that satisfy the filters.
3746 */
3747 if (bargs->limit_max == 0)
3748 return 0;
3749 else
3750 bargs->limit_max--;
David Sterba7d824b62014-05-07 17:37:51 +02003751 }
3752
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003753 return 1;
3754}
3755
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003756static int __btrfs_balance(struct btrfs_fs_info *fs_info)
Chris Masonec44a352008-04-28 15:29:52 -04003757{
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003758 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003759 struct btrfs_root *chunk_root = fs_info->chunk_root;
David Sterba12907fc2015-10-10 17:16:50 +02003760 u64 chunk_type;
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003761 struct btrfs_chunk *chunk;
Liu Bo5a488b92016-07-12 11:24:21 -07003762 struct btrfs_path *path = NULL;
Chris Masonec44a352008-04-28 15:29:52 -04003763 struct btrfs_key key;
Chris Masonec44a352008-04-28 15:29:52 -04003764 struct btrfs_key found_key;
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003765 struct extent_buffer *leaf;
3766 int slot;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003767 int ret;
3768 int enospc_errors = 0;
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003769 bool counting = true;
David Sterba12907fc2015-10-10 17:16:50 +02003770 /* The single value limit and min/max limits use the same bytes in the */
David Sterba7d824b62014-05-07 17:37:51 +02003771 u64 limit_data = bctl->data.limit;
3772 u64 limit_meta = bctl->meta.limit;
3773 u64 limit_sys = bctl->sys.limit;
David Sterba12907fc2015-10-10 17:16:50 +02003774 u32 count_data = 0;
3775 u32 count_meta = 0;
3776 u32 count_sys = 0;
Zhao Lei2c9fe832015-11-09 11:51:32 +08003777 int chunk_reserved = 0;
Chris Masonec44a352008-04-28 15:29:52 -04003778
Chris Masonec44a352008-04-28 15:29:52 -04003779 path = btrfs_alloc_path();
Mark Fasheh17e9f792011-07-12 11:10:23 -07003780 if (!path) {
3781 ret = -ENOMEM;
3782 goto error;
3783 }
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003784
3785 /* zero out stat counters */
3786 spin_lock(&fs_info->balance_lock);
3787 memset(&bctl->stat, 0, sizeof(bctl->stat));
3788 spin_unlock(&fs_info->balance_lock);
3789again:
David Sterba7d824b62014-05-07 17:37:51 +02003790 if (!counting) {
David Sterba12907fc2015-10-10 17:16:50 +02003791 /*
3792 * The single value limit and min/max limits use the same bytes
3793 * in the
3794 */
David Sterba7d824b62014-05-07 17:37:51 +02003795 bctl->data.limit = limit_data;
3796 bctl->meta.limit = limit_meta;
3797 bctl->sys.limit = limit_sys;
3798 }
Chris Masonec44a352008-04-28 15:29:52 -04003799 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3800 key.offset = (u64)-1;
3801 key.type = BTRFS_CHUNK_ITEM_KEY;
3802
Chris Masond3977122009-01-05 21:25:51 -05003803 while (1) {
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003804 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
Ilya Dryomova7e99c62012-01-16 22:04:49 +02003805 atomic_read(&fs_info->balance_cancel_req)) {
Ilya Dryomov837d5b62012-01-16 22:04:49 +02003806 ret = -ECANCELED;
3807 goto error;
3808 }
3809
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003810 mutex_lock(&fs_info->reclaim_bgs_lock);
Chris Masonec44a352008-04-28 15:29:52 -04003811 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003812 if (ret < 0) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003813 mutex_unlock(&fs_info->reclaim_bgs_lock);
Chris Masonec44a352008-04-28 15:29:52 -04003814 goto error;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003815 }
Chris Masonec44a352008-04-28 15:29:52 -04003816
3817 /*
3818 * this shouldn't happen, it means the last relocate
3819 * failed
3820 */
3821 if (ret == 0)
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003822 BUG(); /* FIXME break ? */
Chris Masonec44a352008-04-28 15:29:52 -04003823
3824 ret = btrfs_previous_item(chunk_root, path, 0,
3825 BTRFS_CHUNK_ITEM_KEY);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003826 if (ret) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003827 mutex_unlock(&fs_info->reclaim_bgs_lock);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003828 ret = 0;
Chris Masonec44a352008-04-28 15:29:52 -04003829 break;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003830 }
Chris Mason7d9eb122008-07-08 14:19:17 -04003831
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003832 leaf = path->nodes[0];
3833 slot = path->slots[0];
3834 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3835
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003836 if (found_key.objectid != key.objectid) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003837 mutex_unlock(&fs_info->reclaim_bgs_lock);
Chris Masonec44a352008-04-28 15:29:52 -04003838 break;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003839 }
Chris Mason7d9eb122008-07-08 14:19:17 -04003840
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003841 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
David Sterba12907fc2015-10-10 17:16:50 +02003842 chunk_type = btrfs_chunk_type(leaf, chunk);
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003843
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003844 if (!counting) {
3845 spin_lock(&fs_info->balance_lock);
3846 bctl->stat.considered++;
3847 spin_unlock(&fs_info->balance_lock);
3848 }
3849
David Sterba6ec08962019-03-20 16:38:52 +01003850 ret = should_balance_chunk(leaf, chunk, found_key.offset);
Zhao Lei2c9fe832015-11-09 11:51:32 +08003851
David Sterbab3b4aa72011-04-21 01:20:15 +02003852 btrfs_release_path(path);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003853 if (!ret) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003854 mutex_unlock(&fs_info->reclaim_bgs_lock);
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003855 goto loop;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01003856 }
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003857
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003858 if (counting) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003859 mutex_unlock(&fs_info->reclaim_bgs_lock);
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003860 spin_lock(&fs_info->balance_lock);
3861 bctl->stat.expected++;
3862 spin_unlock(&fs_info->balance_lock);
David Sterba12907fc2015-10-10 17:16:50 +02003863
3864 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3865 count_data++;
3866 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3867 count_sys++;
3868 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3869 count_meta++;
3870
3871 goto loop;
3872 }
3873
3874 /*
3875 * Apply limit_min filter, no need to check if the LIMITS
3876 * filter is used, limit_min is 0 by default
3877 */
3878 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3879 count_data < bctl->data.limit_min)
3880 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3881 count_meta < bctl->meta.limit_min)
3882 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3883 count_sys < bctl->sys.limit_min)) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003884 mutex_unlock(&fs_info->reclaim_bgs_lock);
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003885 goto loop;
3886 }
3887
Liu Boa6f93c72017-11-15 16:28:11 -07003888 if (!chunk_reserved) {
3889 /*
3890 * We may be relocating the only data chunk we have,
3891 * which could potentially end up with losing data's
3892 * raid profile, so lets allocate an empty one in
3893 * advance.
3894 */
3895 ret = btrfs_may_alloc_data_chunk(fs_info,
3896 found_key.offset);
Zhao Lei2c9fe832015-11-09 11:51:32 +08003897 if (ret < 0) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003898 mutex_unlock(&fs_info->reclaim_bgs_lock);
Zhao Lei2c9fe832015-11-09 11:51:32 +08003899 goto error;
Liu Boa6f93c72017-11-15 16:28:11 -07003900 } else if (ret == 1) {
3901 chunk_reserved = 1;
Zhao Lei2c9fe832015-11-09 11:51:32 +08003902 }
Zhao Lei2c9fe832015-11-09 11:51:32 +08003903 }
3904
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04003905 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
Johannes Thumshirnf3372062021-04-19 16:41:01 +09003906 mutex_unlock(&fs_info->reclaim_bgs_lock);
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003907 if (ret == -ENOSPC) {
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003908 enospc_errors++;
Omar Sandovaleede2bf2016-11-03 10:28:12 -07003909 } else if (ret == -ETXTBSY) {
3910 btrfs_info(fs_info,
3911 "skipping relocation of block group %llu due to active swapfile",
3912 found_key.offset);
3913 ret = 0;
3914 } else if (ret) {
3915 goto error;
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003916 } else {
3917 spin_lock(&fs_info->balance_lock);
3918 bctl->stat.completed++;
3919 spin_unlock(&fs_info->balance_lock);
3920 }
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02003921loop:
Ilya Dryomov795a3322013-08-27 13:50:44 +03003922 if (found_key.offset == 0)
3923 break;
Josef Bacikba1bf482009-09-11 16:11:19 -04003924 key.offset = found_key.offset - 1;
Chris Masonec44a352008-04-28 15:29:52 -04003925 }
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003926
Ilya Dryomov19a39dc2012-01-16 22:04:49 +02003927 if (counting) {
3928 btrfs_release_path(path);
3929 counting = false;
3930 goto again;
3931 }
Chris Masonec44a352008-04-28 15:29:52 -04003932error:
3933 btrfs_free_path(path);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003934 if (enospc_errors) {
Frank Holtonefe120a2013-12-20 11:37:06 -05003935 btrfs_info(fs_info, "%d enospc errors during balance",
Jeff Mahoney5d163e02016-09-20 10:05:00 -04003936 enospc_errors);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003937 if (!ret)
3938 ret = -ENOSPC;
3939 }
3940
Chris Masonec44a352008-04-28 15:29:52 -04003941 return ret;
3942}
3943
Ilya Dryomov0c460c02012-03-27 17:09:17 +03003944/**
3945 * alloc_profile_is_valid - see if a given profile is valid and reduced
3946 * @flags: profile to validate
3947 * @extended: if true @flags is treated as an extended profile
3948 */
3949static int alloc_profile_is_valid(u64 flags, int extended)
3950{
3951 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3952 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3953
3954 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3955
3956 /* 1) check that all other bits are zeroed */
3957 if (flags & ~mask)
3958 return 0;
3959
3960 /* 2) see if profile is reduced */
3961 if (flags == 0)
3962 return !extended; /* "0" is valid for usual profiles */
3963
David Sterbac1499162019-10-01 19:44:42 +02003964 return has_single_bit_set(flags);
Ilya Dryomov0c460c02012-03-27 17:09:17 +03003965}
3966
Ilya Dryomov837d5b62012-01-16 22:04:49 +02003967static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3968{
Ilya Dryomova7e99c62012-01-16 22:04:49 +02003969 /* cancel requested || normal exit path */
3970 return atomic_read(&fs_info->balance_cancel_req) ||
3971 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3972 atomic_read(&fs_info->balance_cancel_req) == 0);
Ilya Dryomov837d5b62012-01-16 22:04:49 +02003973}
3974
David Sterba5ba366c2020-02-27 21:00:52 +01003975/*
3976 * Validate target profile against allowed profiles and return true if it's OK.
3977 * Otherwise print the error message and return false.
3978 */
3979static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
3980 const struct btrfs_balance_args *bargs,
3981 u64 allowed, const char *type)
Alexandru Moisebdcd3c92015-09-22 20:02:25 +00003982{
David Sterba5ba366c2020-02-27 21:00:52 +01003983 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3984 return true;
3985
3986 /* Profile is valid and does not have bits outside of the allowed set */
3987 if (alloc_profile_is_valid(bargs->target, 1) &&
3988 (bargs->target & ~allowed) == 0)
3989 return true;
3990
3991 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
3992 type, btrfs_bg_type_to_raid_name(bargs->target));
3993 return false;
Alexandru Moisebdcd3c92015-09-22 20:02:25 +00003994}
3995
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02003996/*
Anand Jain56fc37d2018-11-20 16:12:56 +08003997 * Fill @buf with textual description of balance filter flags @bargs, up to
3998 * @size_buf including the terminating null. The output may be trimmed if it
3999 * does not fit into the provided buffer.
4000 */
4001static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4002 u32 size_buf)
4003{
4004 int ret;
4005 u32 size_bp = size_buf;
4006 char *bp = buf;
4007 u64 flags = bargs->flags;
4008 char tmp_buf[128] = {'\0'};
4009
4010 if (!flags)
4011 return;
4012
4013#define CHECK_APPEND_NOARG(a) \
4014 do { \
4015 ret = snprintf(bp, size_bp, (a)); \
4016 if (ret < 0 || ret >= size_bp) \
4017 goto out_overflow; \
4018 size_bp -= ret; \
4019 bp += ret; \
4020 } while (0)
4021
4022#define CHECK_APPEND_1ARG(a, v1) \
4023 do { \
4024 ret = snprintf(bp, size_bp, (a), (v1)); \
4025 if (ret < 0 || ret >= size_bp) \
4026 goto out_overflow; \
4027 size_bp -= ret; \
4028 bp += ret; \
4029 } while (0)
4030
4031#define CHECK_APPEND_2ARG(a, v1, v2) \
4032 do { \
4033 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4034 if (ret < 0 || ret >= size_bp) \
4035 goto out_overflow; \
4036 size_bp -= ret; \
4037 bp += ret; \
4038 } while (0)
4039
David Sterba158da512019-05-17 11:43:41 +02004040 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4041 CHECK_APPEND_1ARG("convert=%s,",
4042 btrfs_bg_type_to_raid_name(bargs->target));
Anand Jain56fc37d2018-11-20 16:12:56 +08004043
4044 if (flags & BTRFS_BALANCE_ARGS_SOFT)
4045 CHECK_APPEND_NOARG("soft,");
4046
4047 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4048 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4049 sizeof(tmp_buf));
4050 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4051 }
4052
4053 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4054 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4055
4056 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4057 CHECK_APPEND_2ARG("usage=%u..%u,",
4058 bargs->usage_min, bargs->usage_max);
4059
4060 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4061 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4062
4063 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4064 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4065 bargs->pstart, bargs->pend);
4066
4067 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4068 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4069 bargs->vstart, bargs->vend);
4070
4071 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4072 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4073
4074 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4075 CHECK_APPEND_2ARG("limit=%u..%u,",
4076 bargs->limit_min, bargs->limit_max);
4077
4078 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4079 CHECK_APPEND_2ARG("stripes=%u..%u,",
4080 bargs->stripes_min, bargs->stripes_max);
4081
4082#undef CHECK_APPEND_2ARG
4083#undef CHECK_APPEND_1ARG
4084#undef CHECK_APPEND_NOARG
4085
4086out_overflow:
4087
4088 if (size_bp < size_buf)
4089 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4090 else
4091 buf[0] = '\0';
4092}
4093
4094static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4095{
4096 u32 size_buf = 1024;
4097 char tmp_buf[192] = {'\0'};
4098 char *buf;
4099 char *bp;
4100 u32 size_bp = size_buf;
4101 int ret;
4102 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4103
4104 buf = kzalloc(size_buf, GFP_KERNEL);
4105 if (!buf)
4106 return;
4107
4108 bp = buf;
4109
4110#define CHECK_APPEND_1ARG(a, v1) \
4111 do { \
4112 ret = snprintf(bp, size_bp, (a), (v1)); \
4113 if (ret < 0 || ret >= size_bp) \
4114 goto out_overflow; \
4115 size_bp -= ret; \
4116 bp += ret; \
4117 } while (0)
4118
4119 if (bctl->flags & BTRFS_BALANCE_FORCE)
4120 CHECK_APPEND_1ARG("%s", "-f ");
4121
4122 if (bctl->flags & BTRFS_BALANCE_DATA) {
4123 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4124 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4125 }
4126
4127 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4128 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4129 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4130 }
4131
4132 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4133 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4134 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4135 }
4136
4137#undef CHECK_APPEND_1ARG
4138
4139out_overflow:
4140
4141 if (size_bp < size_buf)
4142 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4143 btrfs_info(fs_info, "balance: %s %s",
4144 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4145 "resume" : "start", buf);
4146
4147 kfree(buf);
4148}
4149
4150/*
David Sterbadccdb072018-03-21 00:20:05 +01004151 * Should be called with balance mutexe held
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004152 */
David Sterba6fcf6e22018-05-07 17:44:03 +02004153int btrfs_balance(struct btrfs_fs_info *fs_info,
4154 struct btrfs_balance_control *bctl,
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004155 struct btrfs_ioctl_balance_args *bargs)
4156{
Adam Borowski14506122017-03-07 23:34:44 +01004157 u64 meta_target, data_target;
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02004158 u64 allowed;
Ilya Dryomove4837f82012-03-27 17:09:17 +03004159 int mixed = 0;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004160 int ret;
Stefan Behrens8dabb742012-11-06 13:15:27 +01004161 u64 num_devices;
Miao Xiede98ced2013-01-29 10:13:12 +00004162 unsigned seq;
Anand Jaine62869b2019-09-25 14:29:28 +08004163 bool reducing_redundancy;
David Sterba081db892019-05-17 11:43:27 +02004164 int i;
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004165
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004166 if (btrfs_fs_closing(fs_info) ||
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004167 atomic_read(&fs_info->balance_pause_req) ||
Qu Wenruo726a3422020-02-17 14:16:52 +08004168 btrfs_should_cancel_balance(fs_info)) {
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004169 ret = -EINVAL;
4170 goto out;
4171 }
4172
Ilya Dryomove4837f82012-03-27 17:09:17 +03004173 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4174 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4175 mixed = 1;
4176
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02004177 /*
4178 * In case of mixed groups both data and meta should be picked,
4179 * and identical options should be given for both of them.
4180 */
Ilya Dryomove4837f82012-03-27 17:09:17 +03004181 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4182 if (mixed && (bctl->flags & allowed)) {
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02004183 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4184 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4185 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
Jeff Mahoney5d163e02016-09-20 10:05:00 -04004186 btrfs_err(fs_info,
Anand Jain6dac13f2018-05-16 10:51:26 +08004187 "balance: mixed groups data and metadata options must be the same");
Ilya Dryomovf43ffb62012-01-16 22:04:47 +02004188 ret = -EINVAL;
4189 goto out;
4190 }
4191 }
4192
Josef Bacikb35cf1f2020-01-10 11:11:24 -05004193 /*
4194 * rw_devices will not change at the moment, device add/delete/replace
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004195 * are exclusive
Josef Bacikb35cf1f2020-01-10 11:11:24 -05004196 */
4197 num_devices = fs_info->fs_devices->rw_devices;
Qu Wenruofab27352019-09-25 10:13:27 +08004198
4199 /*
4200 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4201 * special bit for it, to make it easier to distinguish. Thus we need
4202 * to set it manually, or balance would refuse the profile.
4203 */
4204 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
David Sterba081db892019-05-17 11:43:27 +02004205 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4206 if (num_devices >= btrfs_raid_array[i].devs_min)
4207 allowed |= btrfs_raid_array[i].bg_flag;
Anand Jain1da73962018-08-10 13:53:21 +08004208
David Sterba5ba366c2020-02-27 21:00:52 +01004209 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4210 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4211 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
Ilya Dryomove4d8ec02012-01-16 22:04:48 +02004212 ret = -EINVAL;
4213 goto out;
4214 }
4215
David Sterba6079e122019-05-17 11:43:29 +02004216 /*
4217 * Allow to reduce metadata or system integrity only if force set for
4218 * profiles with redundancy (copies, parity)
4219 */
4220 allowed = 0;
4221 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4222 if (btrfs_raid_array[i].ncopies >= 2 ||
4223 btrfs_raid_array[i].tolerated_failures >= 1)
4224 allowed |= btrfs_raid_array[i].bg_flag;
4225 }
Miao Xiede98ced2013-01-29 10:13:12 +00004226 do {
4227 seq = read_seqbegin(&fs_info->profiles_lock);
4228
4229 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4230 (fs_info->avail_system_alloc_bits & allowed) &&
4231 !(bctl->sys.target & allowed)) ||
4232 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4233 (fs_info->avail_metadata_alloc_bits & allowed) &&
Filipe Manana5a8067c2018-11-19 09:48:12 +00004234 !(bctl->meta.target & allowed)))
Anand Jaine62869b2019-09-25 14:29:28 +08004235 reducing_redundancy = true;
Filipe Manana5a8067c2018-11-19 09:48:12 +00004236 else
Anand Jaine62869b2019-09-25 14:29:28 +08004237 reducing_redundancy = false;
Filipe Manana5a8067c2018-11-19 09:48:12 +00004238
4239 /* if we're not converting, the target field is uninitialized */
4240 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4241 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4242 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4243 bctl->data.target : fs_info->avail_data_alloc_bits;
Miao Xiede98ced2013-01-29 10:13:12 +00004244 } while (read_seqretry(&fs_info->profiles_lock, seq));
Ilya Dryomove4d8ec02012-01-16 22:04:48 +02004245
Anand Jaine62869b2019-09-25 14:29:28 +08004246 if (reducing_redundancy) {
Filipe Manana5a8067c2018-11-19 09:48:12 +00004247 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4248 btrfs_info(fs_info,
Anand Jaine62869b2019-09-25 14:29:28 +08004249 "balance: force reducing metadata redundancy");
Filipe Manana5a8067c2018-11-19 09:48:12 +00004250 } else {
4251 btrfs_err(fs_info,
Anand Jaine62869b2019-09-25 14:29:28 +08004252 "balance: reduces metadata redundancy, use --force if you want this");
Filipe Manana5a8067c2018-11-19 09:48:12 +00004253 ret = -EINVAL;
4254 goto out;
4255 }
4256 }
4257
Adam Borowski14506122017-03-07 23:34:44 +01004258 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4259 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
Sam Tygieree592d02016-01-06 08:46:12 +00004260 btrfs_warn(fs_info,
Anand Jain6dac13f2018-05-16 10:51:26 +08004261 "balance: metadata profile %s has lower redundancy than data profile %s",
David Sterba158da512019-05-17 11:43:41 +02004262 btrfs_bg_type_to_raid_name(meta_target),
4263 btrfs_bg_type_to_raid_name(data_target));
Sam Tygieree592d02016-01-06 08:46:12 +00004264 }
4265
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04004266 ret = insert_balance_item(fs_info, bctl);
Ilya Dryomov59641012012-01-16 22:04:48 +02004267 if (ret && ret != -EEXIST)
Ilya Dryomov0940ebf2012-01-16 22:04:48 +02004268 goto out;
4269
Ilya Dryomov59641012012-01-16 22:04:48 +02004270 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4271 BUG_ON(ret == -EEXIST);
David Sterba833aae12018-03-21 02:41:30 +01004272 BUG_ON(fs_info->balance_ctl);
4273 spin_lock(&fs_info->balance_lock);
4274 fs_info->balance_ctl = bctl;
4275 spin_unlock(&fs_info->balance_lock);
Ilya Dryomov59641012012-01-16 22:04:48 +02004276 } else {
4277 BUG_ON(ret != -EEXIST);
4278 spin_lock(&fs_info->balance_lock);
4279 update_balance_args(bctl);
4280 spin_unlock(&fs_info->balance_lock);
4281 }
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004282
David Sterba3009a622018-03-21 01:31:04 +01004283 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4284 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
Anand Jain56fc37d2018-11-20 16:12:56 +08004285 describe_balance_start_or_resume(fs_info);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004286 mutex_unlock(&fs_info->balance_mutex);
4287
4288 ret = __btrfs_balance(fs_info);
4289
4290 mutex_lock(&fs_info->balance_mutex);
Anand Jain7333bd02018-11-20 16:12:57 +08004291 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4292 btrfs_info(fs_info, "balance: paused");
Qu Wenruo44d354a2020-07-13 09:03:21 +08004293 /*
4294 * Balance can be canceled by:
4295 *
4296 * - Regular cancel request
4297 * Then ret == -ECANCELED and balance_cancel_req > 0
4298 *
4299 * - Fatal signal to "btrfs" process
4300 * Either the signal caught by wait_reserve_ticket() and callers
4301 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4302 * got -ECANCELED.
4303 * Either way, in this case balance_cancel_req = 0, and
4304 * ret == -EINTR or ret == -ECANCELED.
4305 *
4306 * So here we only check the return value to catch canceled balance.
4307 */
4308 else if (ret == -ECANCELED || ret == -EINTR)
Anand Jain7333bd02018-11-20 16:12:57 +08004309 btrfs_info(fs_info, "balance: canceled");
4310 else
4311 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4312
David Sterba3009a622018-03-21 01:31:04 +01004313 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004314
4315 if (bargs) {
4316 memset(bargs, 0, sizeof(*bargs));
David Sterba008ef092018-03-21 02:05:27 +01004317 btrfs_update_ioctl_balance_args(fs_info, bargs);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004318 }
4319
Ilya Dryomov3a01aa72013-03-06 01:57:55 -07004320 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4321 balance_need_close(fs_info)) {
David Sterba149196a2018-03-20 20:23:09 +01004322 reset_balance_state(fs_info);
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004323 btrfs_exclop_finish(fs_info);
Ilya Dryomov3a01aa72013-03-06 01:57:55 -07004324 }
4325
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004326 wake_up(&fs_info->balance_wait_q);
Ilya Dryomovc9e9f972012-01-16 22:04:47 +02004327
4328 return ret;
4329out:
Ilya Dryomov59641012012-01-16 22:04:48 +02004330 if (bctl->flags & BTRFS_BALANCE_RESUME)
David Sterba149196a2018-03-20 20:23:09 +01004331 reset_balance_state(fs_info);
David Sterbaa17c95d2018-03-20 17:28:05 +01004332 else
Ilya Dryomov59641012012-01-16 22:04:48 +02004333 kfree(bctl);
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004334 btrfs_exclop_finish(fs_info);
David Sterbaa17c95d2018-03-20 17:28:05 +01004335
Ilya Dryomov59641012012-01-16 22:04:48 +02004336 return ret;
4337}
4338
4339static int balance_kthread(void *data)
4340{
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004341 struct btrfs_fs_info *fs_info = data;
Ilya Dryomov9555c6c2012-01-16 22:04:48 +02004342 int ret = 0;
Ilya Dryomov59641012012-01-16 22:04:48 +02004343
Ilya Dryomov59641012012-01-16 22:04:48 +02004344 mutex_lock(&fs_info->balance_mutex);
Anand Jain56fc37d2018-11-20 16:12:56 +08004345 if (fs_info->balance_ctl)
David Sterba6fcf6e22018-05-07 17:44:03 +02004346 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
Ilya Dryomov59641012012-01-16 22:04:48 +02004347 mutex_unlock(&fs_info->balance_mutex);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004348
Ilya Dryomov59641012012-01-16 22:04:48 +02004349 return ret;
4350}
4351
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004352int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4353{
4354 struct task_struct *tsk;
4355
David Sterba1354e1a2018-03-21 02:29:13 +01004356 mutex_lock(&fs_info->balance_mutex);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004357 if (!fs_info->balance_ctl) {
David Sterba1354e1a2018-03-21 02:29:13 +01004358 mutex_unlock(&fs_info->balance_mutex);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004359 return 0;
4360 }
David Sterba1354e1a2018-03-21 02:29:13 +01004361 mutex_unlock(&fs_info->balance_mutex);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004362
Jeff Mahoney3cdde222016-06-09 21:38:35 -04004363 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
Anand Jain6dac13f2018-05-16 10:51:26 +08004364 btrfs_info(fs_info, "balance: resume skipped");
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004365 return 0;
4366 }
4367
Anand Jain02ee6542018-05-17 15:16:51 +08004368 /*
4369 * A ro->rw remount sequence should continue with the paused balance
4370 * regardless of who pauses it, system or the user as of now, so set
4371 * the resume flag.
4372 */
4373 spin_lock(&fs_info->balance_lock);
4374 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4375 spin_unlock(&fs_info->balance_lock);
4376
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004377 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
Sachin Kamatcd633972013-07-15 16:52:18 +05304378 return PTR_ERR_OR_ZERO(tsk);
Ilya Dryomov2b6ba622012-06-22 12:24:13 -06004379}
4380
Ilya Dryomov68310a52012-06-22 12:24:12 -06004381int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
Ilya Dryomov59641012012-01-16 22:04:48 +02004382{
Ilya Dryomov59641012012-01-16 22:04:48 +02004383 struct btrfs_balance_control *bctl;
4384 struct btrfs_balance_item *item;
4385 struct btrfs_disk_balance_args disk_bargs;
4386 struct btrfs_path *path;
4387 struct extent_buffer *leaf;
4388 struct btrfs_key key;
4389 int ret;
4390
4391 path = btrfs_alloc_path();
4392 if (!path)
4393 return -ENOMEM;
4394
Ilya Dryomov68310a52012-06-22 12:24:12 -06004395 key.objectid = BTRFS_BALANCE_OBJECTID;
David Sterbac479cb42016-01-25 17:51:31 +01004396 key.type = BTRFS_TEMPORARY_ITEM_KEY;
Ilya Dryomov68310a52012-06-22 12:24:12 -06004397 key.offset = 0;
4398
4399 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4400 if (ret < 0)
4401 goto out;
4402 if (ret > 0) { /* ret = -ENOENT; */
4403 ret = 0;
4404 goto out;
4405 }
4406
Ilya Dryomov59641012012-01-16 22:04:48 +02004407 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4408 if (!bctl) {
4409 ret = -ENOMEM;
4410 goto out;
4411 }
4412
Ilya Dryomov59641012012-01-16 22:04:48 +02004413 leaf = path->nodes[0];
4414 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4415
Ilya Dryomov68310a52012-06-22 12:24:12 -06004416 bctl->flags = btrfs_balance_flags(leaf, item);
4417 bctl->flags |= BTRFS_BALANCE_RESUME;
Ilya Dryomov59641012012-01-16 22:04:48 +02004418
4419 btrfs_balance_data(leaf, item, &disk_bargs);
4420 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4421 btrfs_balance_meta(leaf, item, &disk_bargs);
4422 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4423 btrfs_balance_sys(leaf, item, &disk_bargs);
4424 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4425
David Sterbaeee95e32018-03-20 20:07:58 +01004426 /*
4427 * This should never happen, as the paused balance state is recovered
4428 * during mount without any chance of other exclusive ops to collide.
4429 *
4430 * This gives the exclusive op status to balance and keeps in paused
4431 * state until user intervention (cancel or umount). If the ownership
4432 * cannot be assigned, show a message but do not fail. The balance
4433 * is in a paused state and must have fs_info::balance_ctl properly
4434 * set up.
4435 */
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004436 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
David Sterbaeee95e32018-03-20 20:07:58 +01004437 btrfs_warn(fs_info,
Anand Jain6dac13f2018-05-16 10:51:26 +08004438 "balance: cannot set exclusive op status, resume manually");
Ilya Dryomoved0fb782013-01-20 15:57:57 +02004439
Josef Bacikfb286102020-12-16 11:22:14 -05004440 btrfs_release_path(path);
4441
Ilya Dryomov68310a52012-06-22 12:24:12 -06004442 mutex_lock(&fs_info->balance_mutex);
David Sterba833aae12018-03-21 02:41:30 +01004443 BUG_ON(fs_info->balance_ctl);
4444 spin_lock(&fs_info->balance_lock);
4445 fs_info->balance_ctl = bctl;
4446 spin_unlock(&fs_info->balance_lock);
Ilya Dryomov68310a52012-06-22 12:24:12 -06004447 mutex_unlock(&fs_info->balance_mutex);
Ilya Dryomov59641012012-01-16 22:04:48 +02004448out:
4449 btrfs_free_path(path);
Chris Mason8f18cf12008-04-25 16:53:30 -04004450 return ret;
4451}
4452
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004453int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4454{
4455 int ret = 0;
4456
4457 mutex_lock(&fs_info->balance_mutex);
4458 if (!fs_info->balance_ctl) {
4459 mutex_unlock(&fs_info->balance_mutex);
4460 return -ENOTCONN;
4461 }
4462
David Sterba3009a622018-03-21 01:31:04 +01004463 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004464 atomic_inc(&fs_info->balance_pause_req);
4465 mutex_unlock(&fs_info->balance_mutex);
4466
4467 wait_event(fs_info->balance_wait_q,
David Sterba3009a622018-03-21 01:31:04 +01004468 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004469
4470 mutex_lock(&fs_info->balance_mutex);
4471 /* we are good with balance_ctl ripped off from under us */
David Sterba3009a622018-03-21 01:31:04 +01004472 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
Ilya Dryomov837d5b62012-01-16 22:04:49 +02004473 atomic_dec(&fs_info->balance_pause_req);
4474 } else {
4475 ret = -ENOTCONN;
4476 }
4477
4478 mutex_unlock(&fs_info->balance_mutex);
4479 return ret;
4480}
4481
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004482int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4483{
4484 mutex_lock(&fs_info->balance_mutex);
4485 if (!fs_info->balance_ctl) {
4486 mutex_unlock(&fs_info->balance_mutex);
4487 return -ENOTCONN;
4488 }
4489
David Sterbacf7d20f2018-03-21 01:45:32 +01004490 /*
4491 * A paused balance with the item stored on disk can be resumed at
4492 * mount time if the mount is read-write. Otherwise it's still paused
4493 * and we must not allow cancelling as it deletes the item.
4494 */
4495 if (sb_rdonly(fs_info->sb)) {
4496 mutex_unlock(&fs_info->balance_mutex);
4497 return -EROFS;
4498 }
4499
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004500 atomic_inc(&fs_info->balance_cancel_req);
4501 /*
4502 * if we are running just wait and return, balance item is
4503 * deleted in btrfs_balance in this case
4504 */
David Sterba3009a622018-03-21 01:31:04 +01004505 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004506 mutex_unlock(&fs_info->balance_mutex);
4507 wait_event(fs_info->balance_wait_q,
David Sterba3009a622018-03-21 01:31:04 +01004508 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004509 mutex_lock(&fs_info->balance_mutex);
4510 } else {
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004511 mutex_unlock(&fs_info->balance_mutex);
David Sterbadccdb072018-03-21 00:20:05 +01004512 /*
4513 * Lock released to allow other waiters to continue, we'll
4514 * reexamine the status again.
4515 */
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004516 mutex_lock(&fs_info->balance_mutex);
4517
David Sterbaa17c95d2018-03-20 17:28:05 +01004518 if (fs_info->balance_ctl) {
David Sterba149196a2018-03-20 20:23:09 +01004519 reset_balance_state(fs_info);
Goldwyn Rodriguesc3e1f962020-08-25 10:02:32 -05004520 btrfs_exclop_finish(fs_info);
Anand Jain6dac13f2018-05-16 10:51:26 +08004521 btrfs_info(fs_info, "balance: canceled");
David Sterbaa17c95d2018-03-20 17:28:05 +01004522 }
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004523 }
4524
David Sterba3009a622018-03-21 01:31:04 +01004525 BUG_ON(fs_info->balance_ctl ||
4526 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
Ilya Dryomova7e99c62012-01-16 22:04:49 +02004527 atomic_dec(&fs_info->balance_cancel_req);
4528 mutex_unlock(&fs_info->balance_mutex);
4529 return 0;
4530}
4531
Nikolay Borisov97f4dd02020-02-18 16:56:08 +02004532int btrfs_uuid_scan_kthread(void *data)
Stefan Behrens803b2f52013-08-15 17:11:21 +02004533{
4534 struct btrfs_fs_info *fs_info = data;
4535 struct btrfs_root *root = fs_info->tree_root;
4536 struct btrfs_key key;
Stefan Behrens803b2f52013-08-15 17:11:21 +02004537 struct btrfs_path *path = NULL;
4538 int ret = 0;
4539 struct extent_buffer *eb;
4540 int slot;
4541 struct btrfs_root_item root_item;
4542 u32 item_size;
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004543 struct btrfs_trans_handle *trans = NULL;
Josef Bacikc94bec22020-02-14 15:05:01 -05004544 bool closing = false;
Stefan Behrens803b2f52013-08-15 17:11:21 +02004545
4546 path = btrfs_alloc_path();
4547 if (!path) {
4548 ret = -ENOMEM;
4549 goto out;
4550 }
4551
4552 key.objectid = 0;
4553 key.type = BTRFS_ROOT_ITEM_KEY;
4554 key.offset = 0;
4555
Stefan Behrens803b2f52013-08-15 17:11:21 +02004556 while (1) {
Josef Bacikc94bec22020-02-14 15:05:01 -05004557 if (btrfs_fs_closing(fs_info)) {
4558 closing = true;
4559 break;
4560 }
Anand Jain7c829b72018-03-07 17:29:18 +08004561 ret = btrfs_search_forward(root, &key, path,
4562 BTRFS_OLDEST_GENERATION);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004563 if (ret) {
4564 if (ret > 0)
4565 ret = 0;
4566 break;
4567 }
4568
4569 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4570 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4571 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4572 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4573 goto skip;
4574
4575 eb = path->nodes[0];
4576 slot = path->slots[0];
4577 item_size = btrfs_item_size_nr(eb, slot);
4578 if (item_size < sizeof(root_item))
4579 goto skip;
4580
Stefan Behrens803b2f52013-08-15 17:11:21 +02004581 read_extent_buffer(eb, &root_item,
4582 btrfs_item_ptr_offset(eb, slot),
4583 (int)sizeof(root_item));
4584 if (btrfs_root_refs(&root_item) == 0)
4585 goto skip;
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004586
4587 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4588 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4589 if (trans)
4590 goto update_tree;
4591
4592 btrfs_release_path(path);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004593 /*
4594 * 1 - subvol uuid item
4595 * 1 - received_subvol uuid item
4596 */
4597 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4598 if (IS_ERR(trans)) {
4599 ret = PTR_ERR(trans);
4600 break;
4601 }
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004602 continue;
4603 } else {
4604 goto skip;
4605 }
4606update_tree:
Josef Bacik9771a5cf2020-08-10 11:42:26 -04004607 btrfs_release_path(path);
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004608 if (!btrfs_is_empty_uuid(root_item.uuid)) {
Lu Fengqicdb345a2018-05-29 15:01:53 +08004609 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
Stefan Behrens803b2f52013-08-15 17:11:21 +02004610 BTRFS_UUID_KEY_SUBVOL,
4611 key.objectid);
4612 if (ret < 0) {
Frank Holtonefe120a2013-12-20 11:37:06 -05004613 btrfs_warn(fs_info, "uuid_tree_add failed %d",
Stefan Behrens803b2f52013-08-15 17:11:21 +02004614 ret);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004615 break;
4616 }
4617 }
4618
4619 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
Lu Fengqicdb345a2018-05-29 15:01:53 +08004620 ret = btrfs_uuid_tree_add(trans,
Stefan Behrens803b2f52013-08-15 17:11:21 +02004621 root_item.received_uuid,
4622 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4623 key.objectid);
4624 if (ret < 0) {
Frank Holtonefe120a2013-12-20 11:37:06 -05004625 btrfs_warn(fs_info, "uuid_tree_add failed %d",
Stefan Behrens803b2f52013-08-15 17:11:21 +02004626 ret);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004627 break;
4628 }
4629 }
4630
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004631skip:
Josef Bacik9771a5cf2020-08-10 11:42:26 -04004632 btrfs_release_path(path);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004633 if (trans) {
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04004634 ret = btrfs_end_transaction(trans);
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004635 trans = NULL;
Stefan Behrens803b2f52013-08-15 17:11:21 +02004636 if (ret)
4637 break;
4638 }
4639
Stefan Behrens803b2f52013-08-15 17:11:21 +02004640 if (key.offset < (u64)-1) {
4641 key.offset++;
4642 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4643 key.offset = 0;
4644 key.type = BTRFS_ROOT_ITEM_KEY;
4645 } else if (key.objectid < (u64)-1) {
4646 key.offset = 0;
4647 key.type = BTRFS_ROOT_ITEM_KEY;
4648 key.objectid++;
4649 } else {
4650 break;
4651 }
4652 cond_resched();
4653 }
4654
4655out:
4656 btrfs_free_path(path);
Filipe David Borba Mananaf45388f2013-08-28 10:28:34 +01004657 if (trans && !IS_ERR(trans))
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04004658 btrfs_end_transaction(trans);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004659 if (ret)
Frank Holtonefe120a2013-12-20 11:37:06 -05004660 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
Josef Bacikc94bec22020-02-14 15:05:01 -05004661 else if (!closing)
Josef Bacikafcdd122016-09-02 15:40:02 -04004662 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004663 up(&fs_info->uuid_tree_rescan_sem);
4664 return 0;
4665}
4666
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004667int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4668{
4669 struct btrfs_trans_handle *trans;
4670 struct btrfs_root *tree_root = fs_info->tree_root;
4671 struct btrfs_root *uuid_root;
Stefan Behrens803b2f52013-08-15 17:11:21 +02004672 struct task_struct *task;
4673 int ret;
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004674
4675 /*
4676 * 1 - root node
4677 * 1 - root item
4678 */
4679 trans = btrfs_start_transaction(tree_root, 2);
4680 if (IS_ERR(trans))
4681 return PTR_ERR(trans);
4682
David Sterba9b7a2442019-03-20 13:20:49 +01004683 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004684 if (IS_ERR(uuid_root)) {
David Sterba6d13f542015-04-24 19:12:01 +02004685 ret = PTR_ERR(uuid_root);
Jeff Mahoney66642832016-06-10 18:19:25 -04004686 btrfs_abort_transaction(trans, ret);
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04004687 btrfs_end_transaction(trans);
David Sterba6d13f542015-04-24 19:12:01 +02004688 return ret;
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004689 }
4690
4691 fs_info->uuid_root = uuid_root;
4692
Jeff Mahoney3a45bb22016-09-09 21:39:03 -04004693 ret = btrfs_commit_transaction(trans);
Stefan Behrens803b2f52013-08-15 17:11:21 +02004694 if (ret)
4695 return ret;
4696
4697 down(&fs_info->uuid_tree_rescan_sem);
4698 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4699 if (IS_ERR(task)) {
Stefan Behrens70f80172013-08-15 17:11:23 +02004700 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
Frank Holtonefe120a2013-12-20 11:37:06 -05004701 btrfs_warn(fs_info, "failed to start uuid_scan task");
Stefan Behrens803b2f52013-08-15 17:11:21 +02004702 up(&fs_info->uuid_tree_rescan_sem);
4703 return PTR_ERR(task);
4704 }
4705
4706 return 0;
Stefan Behrensf7a81ea2013-08-15 17:11:19 +02004707}
Stefan Behrens803b2f52013-08-15 17:11:21 +02004708
Chris Mason8f18cf12008-04-25 16:53:30 -04004709/*
4710 * shrinking a device means finding all of the device extents past
4711 * the new size, and then following the back refs to the chunks.
4712 * The chunk relocation code actually frees the device extent
4713 */
4714int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4715{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004716 struct btrfs_fs_info *fs_info = device->fs_info;
4717 struct btrfs_root *root = fs_info->dev_root;
Chris Mason8f18cf12008-04-25 16:53:30 -04004718 struct btrfs_trans_handle *trans;
Chris Mason8f18cf12008-04-25 16:53:30 -04004719 struct btrfs_dev_extent *dev_extent = NULL;
4720 struct btrfs_path *path;
4721 u64 length;
Chris Mason8f18cf12008-04-25 16:53:30 -04004722 u64 chunk_offset;
4723 int ret;
4724 int slot;
Josef Bacikba1bf482009-09-11 16:11:19 -04004725 int failed = 0;
4726 bool retried = false;
Chris Mason8f18cf12008-04-25 16:53:30 -04004727 struct extent_buffer *l;
4728 struct btrfs_key key;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004729 struct btrfs_super_block *super_copy = fs_info->super_copy;
Chris Mason8f18cf12008-04-25 16:53:30 -04004730 u64 old_total = btrfs_super_total_bytes(super_copy);
Miao Xie7cc8e582014-09-03 21:35:38 +08004731 u64 old_size = btrfs_device_get_total_bytes(device);
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03004732 u64 diff;
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004733 u64 start;
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03004734
4735 new_size = round_down(new_size, fs_info->sectorsize);
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004736 start = new_size;
Nikolay Borisov0e4324a2017-07-21 11:28:24 +03004737 diff = round_down(old_size - new_size, fs_info->sectorsize);
Chris Mason8f18cf12008-04-25 16:53:30 -04004738
Anand Jain401e29c2017-12-04 12:54:55 +08004739 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
Stefan Behrens63a212a2012-11-05 18:29:28 +01004740 return -EINVAL;
4741
Chris Mason8f18cf12008-04-25 16:53:30 -04004742 path = btrfs_alloc_path();
4743 if (!path)
4744 return -ENOMEM;
4745
Gu Jinxiang0338dff2018-04-27 16:22:07 +08004746 path->reada = READA_BACK;
Chris Mason8f18cf12008-04-25 16:53:30 -04004747
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004748 trans = btrfs_start_transaction(root, 0);
4749 if (IS_ERR(trans)) {
4750 btrfs_free_path(path);
4751 return PTR_ERR(trans);
4752 }
4753
David Sterba34441362016-10-04 19:34:27 +02004754 mutex_lock(&fs_info->chunk_mutex);
Chris Mason7d9eb122008-07-08 14:19:17 -04004755
Miao Xie7cc8e582014-09-03 21:35:38 +08004756 btrfs_device_set_total_bytes(device, new_size);
Anand Jainebbede42017-12-04 12:54:52 +08004757 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
Yan Zheng2b820322008-11-17 21:11:30 -05004758 device->fs_devices->total_rw_bytes -= diff;
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03004759 atomic64_sub(diff, &fs_info->free_chunk_space);
Josef Bacik2bf64752011-09-26 17:12:22 -04004760 }
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004761
4762 /*
4763 * Once the device's size has been set to the new size, ensure all
4764 * in-memory chunks are synced to disk so that the loop below sees them
4765 * and relocates them accordingly.
4766 */
Jeff Mahoney1c11b632019-03-27 14:24:12 +02004767 if (contains_pending_extent(device, &start, diff)) {
Nikolay Borisov61d0d0d2019-03-25 14:31:23 +02004768 mutex_unlock(&fs_info->chunk_mutex);
4769 ret = btrfs_commit_transaction(trans);
4770 if (ret)
4771 goto done;
4772 } else {
4773 mutex_unlock(&fs_info->chunk_mutex);
4774 btrfs_end_transaction(trans);
4775 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004776
Josef Bacikba1bf482009-09-11 16:11:19 -04004777again:
Chris Mason8f18cf12008-04-25 16:53:30 -04004778 key.objectid = device->devid;
4779 key.offset = (u64)-1;
4780 key.type = BTRFS_DEV_EXTENT_KEY;
4781
Ilya Dryomov213e64d2012-03-27 17:09:18 +03004782 do {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09004783 mutex_lock(&fs_info->reclaim_bgs_lock);
Chris Mason8f18cf12008-04-25 16:53:30 -04004784 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
Filipe Manana67c5e7d2015-06-11 00:58:53 +01004785 if (ret < 0) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09004786 mutex_unlock(&fs_info->reclaim_bgs_lock);
Chris Mason8f18cf12008-04-25 16:53:30 -04004787 goto done;
Filipe Manana67c5e7d2015-06-11 00:58:53 +01004788 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004789
4790 ret = btrfs_previous_item(root, path, 0, key.type);
Chris Mason8f18cf12008-04-25 16:53:30 -04004791 if (ret) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09004792 mutex_unlock(&fs_info->reclaim_bgs_lock);
Nikolay Borisov7056bf62020-12-17 15:21:16 +02004793 if (ret < 0)
4794 goto done;
Chris Mason8f18cf12008-04-25 16:53:30 -04004795 ret = 0;
David Sterbab3b4aa72011-04-21 01:20:15 +02004796 btrfs_release_path(path);
Yan Zhengbf1fb512009-07-22 09:59:00 -04004797 break;
Chris Mason8f18cf12008-04-25 16:53:30 -04004798 }
4799
4800 l = path->nodes[0];
4801 slot = path->slots[0];
4802 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4803
Josef Bacikba1bf482009-09-11 16:11:19 -04004804 if (key.objectid != device->devid) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09004805 mutex_unlock(&fs_info->reclaim_bgs_lock);
David Sterbab3b4aa72011-04-21 01:20:15 +02004806 btrfs_release_path(path);
Yan Zhengbf1fb512009-07-22 09:59:00 -04004807 break;
Josef Bacikba1bf482009-09-11 16:11:19 -04004808 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004809
4810 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4811 length = btrfs_dev_extent_length(l, dev_extent);
4812
Josef Bacikba1bf482009-09-11 16:11:19 -04004813 if (key.offset + length <= new_size) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09004814 mutex_unlock(&fs_info->reclaim_bgs_lock);
David Sterbab3b4aa72011-04-21 01:20:15 +02004815 btrfs_release_path(path);
Chris Balld6397ba2009-04-27 07:29:03 -04004816 break;
Josef Bacikba1bf482009-09-11 16:11:19 -04004817 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004818
Chris Mason8f18cf12008-04-25 16:53:30 -04004819 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
David Sterbab3b4aa72011-04-21 01:20:15 +02004820 btrfs_release_path(path);
Chris Mason8f18cf12008-04-25 16:53:30 -04004821
Liu Boa6f93c72017-11-15 16:28:11 -07004822 /*
4823 * We may be relocating the only data chunk we have,
4824 * which could potentially end up with losing data's
4825 * raid profile, so lets allocate an empty one in
4826 * advance.
4827 */
4828 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4829 if (ret < 0) {
Johannes Thumshirnf3372062021-04-19 16:41:01 +09004830 mutex_unlock(&fs_info->reclaim_bgs_lock);
Liu Boa6f93c72017-11-15 16:28:11 -07004831 goto done;
4832 }
4833
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004834 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
Johannes Thumshirnf3372062021-04-19 16:41:01 +09004835 mutex_unlock(&fs_info->reclaim_bgs_lock);
Omar Sandovaleede2bf2016-11-03 10:28:12 -07004836 if (ret == -ENOSPC) {
Josef Bacikba1bf482009-09-11 16:11:19 -04004837 failed++;
Omar Sandovaleede2bf2016-11-03 10:28:12 -07004838 } else if (ret) {
4839 if (ret == -ETXTBSY) {
4840 btrfs_warn(fs_info,
4841 "could not shrink block group %llu due to active swapfile",
4842 chunk_offset);
4843 }
4844 goto done;
4845 }
Ilya Dryomov213e64d2012-03-27 17:09:18 +03004846 } while (key.offset-- > 0);
Josef Bacikba1bf482009-09-11 16:11:19 -04004847
4848 if (failed && !retried) {
4849 failed = 0;
4850 retried = true;
4851 goto again;
4852 } else if (failed && retried) {
4853 ret = -ENOSPC;
Josef Bacikba1bf482009-09-11 16:11:19 -04004854 goto done;
Chris Mason8f18cf12008-04-25 16:53:30 -04004855 }
4856
Chris Balld6397ba2009-04-27 07:29:03 -04004857 /* Shrinking succeeded, else we would be at "done". */
Yan, Zhenga22285a2010-05-16 10:48:46 -04004858 trans = btrfs_start_transaction(root, 0);
Tsutomu Itoh98d5dc12011-01-20 06:19:37 +00004859 if (IS_ERR(trans)) {
4860 ret = PTR_ERR(trans);
4861 goto done;
4862 }
4863
David Sterba34441362016-10-04 19:34:27 +02004864 mutex_lock(&fs_info->chunk_mutex);
Qu Wenruoc57dd1f2020-07-31 19:29:11 +08004865 /* Clear all state bits beyond the shrunk device size */
4866 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4867 CHUNK_STATE_MASK);
4868
Miao Xie7cc8e582014-09-03 21:35:38 +08004869 btrfs_device_set_disk_total_bytes(device, new_size);
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02004870 if (list_empty(&device->post_commit_list))
4871 list_add_tail(&device->post_commit_list,
4872 &trans->transaction->dev_update_list);
Chris Balld6397ba2009-04-27 07:29:03 -04004873
Chris Balld6397ba2009-04-27 07:29:03 -04004874 WARN_ON(diff > old_total);
Nikolay Borisov7dfb8be2017-06-16 14:39:20 +03004875 btrfs_set_super_total_bytes(super_copy,
4876 round_down(old_total - diff, fs_info->sectorsize));
David Sterba34441362016-10-04 19:34:27 +02004877 mutex_unlock(&fs_info->chunk_mutex);
Miao Xie2196d6e2014-09-03 21:35:41 +08004878
4879 /* Now btrfs_update_device() will change the on-disk size. */
4880 ret = btrfs_update_device(trans, device);
Anand Jain801660b2018-08-06 18:12:37 +08004881 if (ret < 0) {
4882 btrfs_abort_transaction(trans, ret);
4883 btrfs_end_transaction(trans);
4884 } else {
4885 ret = btrfs_commit_transaction(trans);
4886 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004887done:
4888 btrfs_free_path(path);
Filipe Manana53e489b2015-06-02 14:43:21 +01004889 if (ret) {
David Sterba34441362016-10-04 19:34:27 +02004890 mutex_lock(&fs_info->chunk_mutex);
Filipe Manana53e489b2015-06-02 14:43:21 +01004891 btrfs_device_set_total_bytes(device, old_size);
Anand Jainebbede42017-12-04 12:54:52 +08004892 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
Filipe Manana53e489b2015-06-02 14:43:21 +01004893 device->fs_devices->total_rw_bytes += diff;
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03004894 atomic64_add(diff, &fs_info->free_chunk_space);
David Sterba34441362016-10-04 19:34:27 +02004895 mutex_unlock(&fs_info->chunk_mutex);
Filipe Manana53e489b2015-06-02 14:43:21 +01004896 }
Chris Mason8f18cf12008-04-25 16:53:30 -04004897 return ret;
4898}
4899
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04004900static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
Chris Mason0b86a832008-03-24 15:01:56 -04004901 struct btrfs_key *key,
4902 struct btrfs_chunk *chunk, int item_size)
4903{
Jeff Mahoney0b246af2016-06-22 18:54:23 -04004904 struct btrfs_super_block *super_copy = fs_info->super_copy;
Chris Mason0b86a832008-03-24 15:01:56 -04004905 struct btrfs_disk_key disk_key;
4906 u32 array_size;
4907 u8 *ptr;
4908
Filipe Manana79bd3712021-06-29 14:43:06 +01004909 lockdep_assert_held(&fs_info->chunk_mutex);
4910
Chris Mason0b86a832008-03-24 15:01:56 -04004911 array_size = btrfs_super_sys_array_size(super_copy);
Gui Hecheng5f43f862014-04-21 20:13:11 +08004912 if (array_size + item_size + sizeof(disk_key)
Filipe Manana79bd3712021-06-29 14:43:06 +01004913 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
Chris Mason0b86a832008-03-24 15:01:56 -04004914 return -EFBIG;
4915
4916 ptr = super_copy->sys_chunk_array + array_size;
4917 btrfs_cpu_key_to_disk(&disk_key, key);
4918 memcpy(ptr, &disk_key, sizeof(disk_key));
4919 ptr += sizeof(disk_key);
4920 memcpy(ptr, chunk, item_size);
4921 item_size += sizeof(disk_key);
4922 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
Miao Xiefe48a5c2014-09-03 21:35:39 +08004923
Chris Mason0b86a832008-03-24 15:01:56 -04004924 return 0;
4925}
4926
Miao Xieb2117a32011-01-05 10:07:28 +00004927/*
Arne Jansen73c5de02011-04-12 12:07:57 +02004928 * sort the devices in descending order by max_avail, total_avail
Miao Xieb2117a32011-01-05 10:07:28 +00004929 */
Arne Jansen73c5de02011-04-12 12:07:57 +02004930static int btrfs_cmp_device_info(const void *a, const void *b)
Miao Xieb2117a32011-01-05 10:07:28 +00004931{
Arne Jansen73c5de02011-04-12 12:07:57 +02004932 const struct btrfs_device_info *di_a = a;
4933 const struct btrfs_device_info *di_b = b;
Miao Xieb2117a32011-01-05 10:07:28 +00004934
Arne Jansen73c5de02011-04-12 12:07:57 +02004935 if (di_a->max_avail > di_b->max_avail)
4936 return -1;
4937 if (di_a->max_avail < di_b->max_avail)
4938 return 1;
4939 if (di_a->total_avail > di_b->total_avail)
4940 return -1;
4941 if (di_a->total_avail < di_b->total_avail)
4942 return 1;
Miao Xieb2117a32011-01-05 10:07:28 +00004943 return 0;
4944}
4945
David Woodhouse53b381b2013-01-29 18:40:14 -05004946static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4947{
Zhao Leiffe2d202015-01-20 15:11:44 +08004948 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
David Woodhouse53b381b2013-01-29 18:40:14 -05004949 return;
4950
Miao Xieceda0862013-04-11 10:30:16 +00004951 btrfs_set_fs_incompat(info, RAID56);
David Woodhouse53b381b2013-01-29 18:40:14 -05004952}
4953
David Sterbacfbb8252018-07-10 18:15:05 +02004954static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4955{
4956 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4957 return;
4958
4959 btrfs_set_fs_incompat(info, RAID1C34);
4960}
4961
Naohiro Aota4f2bafe2020-02-25 12:56:10 +09004962/*
4963 * Structure used internally for __btrfs_alloc_chunk() function.
4964 * Wraps needed parameters.
4965 */
4966struct alloc_chunk_ctl {
4967 u64 start;
4968 u64 type;
4969 /* Total number of stripes to allocate */
4970 int num_stripes;
4971 /* sub_stripes info for map */
4972 int sub_stripes;
4973 /* Stripes per device */
4974 int dev_stripes;
4975 /* Maximum number of devices to use */
4976 int devs_max;
4977 /* Minimum number of devices to use */
4978 int devs_min;
4979 /* ndevs has to be a multiple of this */
4980 int devs_increment;
4981 /* Number of copies */
4982 int ncopies;
4983 /* Number of stripes worth of bytes to store parity information */
4984 int nparity;
4985 u64 max_stripe_size;
4986 u64 max_chunk_size;
Naohiro Aota6aafb302020-02-25 12:56:15 +09004987 u64 dev_extent_min;
Naohiro Aota4f2bafe2020-02-25 12:56:10 +09004988 u64 stripe_size;
4989 u64 chunk_size;
4990 int ndevs;
4991};
4992
Naohiro Aota27c314d2020-02-25 12:56:11 +09004993static void init_alloc_chunk_ctl_policy_regular(
4994 struct btrfs_fs_devices *fs_devices,
4995 struct alloc_chunk_ctl *ctl)
4996{
4997 u64 type = ctl->type;
4998
4999 if (type & BTRFS_BLOCK_GROUP_DATA) {
5000 ctl->max_stripe_size = SZ_1G;
5001 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5002 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5003 /* For larger filesystems, use larger metadata chunks */
5004 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5005 ctl->max_stripe_size = SZ_1G;
5006 else
5007 ctl->max_stripe_size = SZ_256M;
5008 ctl->max_chunk_size = ctl->max_stripe_size;
5009 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5010 ctl->max_stripe_size = SZ_32M;
5011 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5012 ctl->devs_max = min_t(int, ctl->devs_max,
5013 BTRFS_MAX_DEVS_SYS_CHUNK);
5014 } else {
5015 BUG();
5016 }
5017
5018 /* We don't want a chunk larger than 10% of writable space */
5019 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5020 ctl->max_chunk_size);
Naohiro Aota6aafb302020-02-25 12:56:15 +09005021 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
Naohiro Aota27c314d2020-02-25 12:56:11 +09005022}
5023
Naohiro Aota1cd61212021-02-04 19:21:48 +09005024static void init_alloc_chunk_ctl_policy_zoned(
5025 struct btrfs_fs_devices *fs_devices,
5026 struct alloc_chunk_ctl *ctl)
5027{
5028 u64 zone_size = fs_devices->fs_info->zone_size;
5029 u64 limit;
5030 int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5031 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5032 u64 min_chunk_size = min_data_stripes * zone_size;
5033 u64 type = ctl->type;
5034
5035 ctl->max_stripe_size = zone_size;
5036 if (type & BTRFS_BLOCK_GROUP_DATA) {
5037 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5038 zone_size);
5039 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5040 ctl->max_chunk_size = ctl->max_stripe_size;
5041 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5042 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5043 ctl->devs_max = min_t(int, ctl->devs_max,
5044 BTRFS_MAX_DEVS_SYS_CHUNK);
Arnd Bergmannbb05b292021-03-23 15:31:19 +01005045 } else {
5046 BUG();
Naohiro Aota1cd61212021-02-04 19:21:48 +09005047 }
5048
5049 /* We don't want a chunk larger than 10% of writable space */
5050 limit = max(round_down(div_factor(fs_devices->total_rw_bytes, 1),
5051 zone_size),
5052 min_chunk_size);
5053 ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5054 ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5055}
5056
Naohiro Aota27c314d2020-02-25 12:56:11 +09005057static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5058 struct alloc_chunk_ctl *ctl)
5059{
5060 int index = btrfs_bg_flags_to_raid_index(ctl->type);
5061
5062 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5063 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5064 ctl->devs_max = btrfs_raid_array[index].devs_max;
5065 if (!ctl->devs_max)
5066 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5067 ctl->devs_min = btrfs_raid_array[index].devs_min;
5068 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5069 ctl->ncopies = btrfs_raid_array[index].ncopies;
5070 ctl->nparity = btrfs_raid_array[index].nparity;
5071 ctl->ndevs = 0;
5072
5073 switch (fs_devices->chunk_alloc_policy) {
5074 case BTRFS_CHUNK_ALLOC_REGULAR:
5075 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5076 break;
Naohiro Aota1cd61212021-02-04 19:21:48 +09005077 case BTRFS_CHUNK_ALLOC_ZONED:
5078 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5079 break;
Naohiro Aota27c314d2020-02-25 12:56:11 +09005080 default:
5081 BUG();
5082 }
5083}
5084
Naohiro Aota560156c2020-02-25 12:56:12 +09005085static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5086 struct alloc_chunk_ctl *ctl,
5087 struct btrfs_device_info *devices_info)
5088{
5089 struct btrfs_fs_info *info = fs_devices->fs_info;
5090 struct btrfs_device *device;
5091 u64 total_avail;
5092 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
Naohiro Aota560156c2020-02-25 12:56:12 +09005093 int ret;
5094 int ndevs = 0;
5095 u64 max_avail;
5096 u64 dev_offset;
5097
5098 /*
5099 * in the first pass through the devices list, we gather information
5100 * about the available holes on each device.
5101 */
5102 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5103 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5104 WARN(1, KERN_ERR
5105 "BTRFS: read-only device in alloc_list\n");
5106 continue;
5107 }
5108
5109 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5110 &device->dev_state) ||
5111 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5112 continue;
5113
5114 if (device->total_bytes > device->bytes_used)
5115 total_avail = device->total_bytes - device->bytes_used;
5116 else
5117 total_avail = 0;
5118
5119 /* If there is no space on this device, skip it. */
Naohiro Aota6aafb302020-02-25 12:56:15 +09005120 if (total_avail < ctl->dev_extent_min)
Naohiro Aota560156c2020-02-25 12:56:12 +09005121 continue;
5122
5123 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5124 &max_avail);
5125 if (ret && ret != -ENOSPC)
5126 return ret;
5127
5128 if (ret == 0)
5129 max_avail = dev_extent_want;
5130
Naohiro Aota6aafb302020-02-25 12:56:15 +09005131 if (max_avail < ctl->dev_extent_min) {
Naohiro Aota560156c2020-02-25 12:56:12 +09005132 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5133 btrfs_debug(info,
5134 "%s: devid %llu has no free space, have=%llu want=%llu",
5135 __func__, device->devid, max_avail,
Naohiro Aota6aafb302020-02-25 12:56:15 +09005136 ctl->dev_extent_min);
Naohiro Aota560156c2020-02-25 12:56:12 +09005137 continue;
5138 }
5139
5140 if (ndevs == fs_devices->rw_devices) {
5141 WARN(1, "%s: found more than %llu devices\n",
5142 __func__, fs_devices->rw_devices);
5143 break;
5144 }
5145 devices_info[ndevs].dev_offset = dev_offset;
5146 devices_info[ndevs].max_avail = max_avail;
5147 devices_info[ndevs].total_avail = total_avail;
5148 devices_info[ndevs].dev = device;
5149 ++ndevs;
5150 }
5151 ctl->ndevs = ndevs;
5152
5153 /*
5154 * now sort the devices by hole size / available space
5155 */
5156 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5157 btrfs_cmp_device_info, NULL);
5158
5159 return 0;
5160}
5161
Naohiro Aota5badf512020-02-25 12:56:13 +09005162static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5163 struct btrfs_device_info *devices_info)
5164{
5165 /* Number of stripes that count for block group size */
5166 int data_stripes;
5167
5168 /*
5169 * The primary goal is to maximize the number of stripes, so use as
5170 * many devices as possible, even if the stripes are not maximum sized.
5171 *
5172 * The DUP profile stores more than one stripe per device, the
5173 * max_avail is the total size so we have to adjust.
5174 */
5175 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5176 ctl->dev_stripes);
5177 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5178
5179 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5180 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5181
5182 /*
5183 * Use the number of data stripes to figure out how big this chunk is
5184 * really going to be in terms of logical address space, and compare
5185 * that answer with the max chunk size. If it's higher, we try to
5186 * reduce stripe_size.
5187 */
5188 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5189 /*
5190 * Reduce stripe_size, round it up to a 16MB boundary again and
5191 * then use it, unless it ends up being even bigger than the
5192 * previous value we had already.
5193 */
5194 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5195 data_stripes), SZ_16M),
5196 ctl->stripe_size);
5197 }
5198
5199 /* Align to BTRFS_STRIPE_LEN */
5200 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5201 ctl->chunk_size = ctl->stripe_size * data_stripes;
5202
5203 return 0;
5204}
5205
Naohiro Aota1cd61212021-02-04 19:21:48 +09005206static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5207 struct btrfs_device_info *devices_info)
5208{
5209 u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5210 /* Number of stripes that count for block group size */
5211 int data_stripes;
5212
5213 /*
5214 * It should hold because:
5215 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5216 */
5217 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min);
5218
5219 ctl->stripe_size = zone_size;
5220 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5221 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5222
5223 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5224 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5225 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5226 ctl->stripe_size) + ctl->nparity,
5227 ctl->dev_stripes);
5228 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5229 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5230 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size);
5231 }
5232
5233 ctl->chunk_size = ctl->stripe_size * data_stripes;
5234
5235 return 0;
5236}
5237
Naohiro Aota5badf512020-02-25 12:56:13 +09005238static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5239 struct alloc_chunk_ctl *ctl,
5240 struct btrfs_device_info *devices_info)
5241{
5242 struct btrfs_fs_info *info = fs_devices->fs_info;
5243
5244 /*
5245 * Round down to number of usable stripes, devs_increment can be any
5246 * number so we can't use round_down() that requires power of 2, while
5247 * rounddown is safe.
5248 */
5249 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5250
5251 if (ctl->ndevs < ctl->devs_min) {
5252 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5253 btrfs_debug(info,
5254 "%s: not enough devices with free space: have=%d minimum required=%d",
5255 __func__, ctl->ndevs, ctl->devs_min);
5256 }
5257 return -ENOSPC;
5258 }
5259
5260 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5261
5262 switch (fs_devices->chunk_alloc_policy) {
5263 case BTRFS_CHUNK_ALLOC_REGULAR:
5264 return decide_stripe_size_regular(ctl, devices_info);
Naohiro Aota1cd61212021-02-04 19:21:48 +09005265 case BTRFS_CHUNK_ALLOC_ZONED:
5266 return decide_stripe_size_zoned(ctl, devices_info);
Naohiro Aota5badf512020-02-25 12:56:13 +09005267 default:
5268 BUG();
5269 }
5270}
5271
Filipe Manana79bd3712021-06-29 14:43:06 +01005272static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
Naohiro Aotadce580c2020-02-25 12:56:14 +09005273 struct alloc_chunk_ctl *ctl,
5274 struct btrfs_device_info *devices_info)
5275{
5276 struct btrfs_fs_info *info = trans->fs_info;
5277 struct map_lookup *map = NULL;
5278 struct extent_map_tree *em_tree;
Filipe Manana79bd3712021-06-29 14:43:06 +01005279 struct btrfs_block_group *block_group;
Naohiro Aotadce580c2020-02-25 12:56:14 +09005280 struct extent_map *em;
5281 u64 start = ctl->start;
5282 u64 type = ctl->type;
5283 int ret;
5284 int i;
5285 int j;
5286
5287 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5288 if (!map)
Filipe Manana79bd3712021-06-29 14:43:06 +01005289 return ERR_PTR(-ENOMEM);
Naohiro Aotadce580c2020-02-25 12:56:14 +09005290 map->num_stripes = ctl->num_stripes;
5291
5292 for (i = 0; i < ctl->ndevs; ++i) {
5293 for (j = 0; j < ctl->dev_stripes; ++j) {
5294 int s = i * ctl->dev_stripes + j;
5295 map->stripes[s].dev = devices_info[i].dev;
5296 map->stripes[s].physical = devices_info[i].dev_offset +
5297 j * ctl->stripe_size;
5298 }
5299 }
5300 map->stripe_len = BTRFS_STRIPE_LEN;
5301 map->io_align = BTRFS_STRIPE_LEN;
5302 map->io_width = BTRFS_STRIPE_LEN;
5303 map->type = type;
5304 map->sub_stripes = ctl->sub_stripes;
5305
5306 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5307
5308 em = alloc_extent_map();
5309 if (!em) {
5310 kfree(map);
Filipe Manana79bd3712021-06-29 14:43:06 +01005311 return ERR_PTR(-ENOMEM);
Naohiro Aotadce580c2020-02-25 12:56:14 +09005312 }
5313 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5314 em->map_lookup = map;
5315 em->start = start;
5316 em->len = ctl->chunk_size;
5317 em->block_start = 0;
5318 em->block_len = em->len;
5319 em->orig_block_len = ctl->stripe_size;
5320
5321 em_tree = &info->mapping_tree;
5322 write_lock(&em_tree->lock);
5323 ret = add_extent_mapping(em_tree, em, 0);
5324 if (ret) {
5325 write_unlock(&em_tree->lock);
5326 free_extent_map(em);
Filipe Manana79bd3712021-06-29 14:43:06 +01005327 return ERR_PTR(ret);
Naohiro Aotadce580c2020-02-25 12:56:14 +09005328 }
5329 write_unlock(&em_tree->lock);
5330
Filipe Manana79bd3712021-06-29 14:43:06 +01005331 block_group = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5332 if (IS_ERR(block_group))
Naohiro Aotadce580c2020-02-25 12:56:14 +09005333 goto error_del_extent;
5334
5335 for (i = 0; i < map->num_stripes; i++) {
5336 struct btrfs_device *dev = map->stripes[i].dev;
5337
5338 btrfs_device_set_bytes_used(dev,
5339 dev->bytes_used + ctl->stripe_size);
5340 if (list_empty(&dev->post_commit_list))
5341 list_add_tail(&dev->post_commit_list,
5342 &trans->transaction->dev_update_list);
5343 }
5344
5345 atomic64_sub(ctl->stripe_size * map->num_stripes,
5346 &info->free_chunk_space);
5347
5348 free_extent_map(em);
5349 check_raid56_incompat_flag(info, type);
5350 check_raid1c34_incompat_flag(info, type);
5351
Filipe Manana79bd3712021-06-29 14:43:06 +01005352 return block_group;
Naohiro Aotadce580c2020-02-25 12:56:14 +09005353
5354error_del_extent:
5355 write_lock(&em_tree->lock);
5356 remove_extent_mapping(em_tree, em);
5357 write_unlock(&em_tree->lock);
5358
5359 /* One for our allocation */
5360 free_extent_map(em);
5361 /* One for the tree reference */
5362 free_extent_map(em);
5363
Filipe Manana79bd3712021-06-29 14:43:06 +01005364 return block_group;
Naohiro Aotadce580c2020-02-25 12:56:14 +09005365}
5366
Filipe Manana79bd3712021-06-29 14:43:06 +01005367struct btrfs_block_group *btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5368 u64 type)
Miao Xieb2117a32011-01-05 10:07:28 +00005369{
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04005370 struct btrfs_fs_info *info = trans->fs_info;
Miao Xieb2117a32011-01-05 10:07:28 +00005371 struct btrfs_fs_devices *fs_devices = info->fs_devices;
Arne Jansen73c5de02011-04-12 12:07:57 +02005372 struct btrfs_device_info *devices_info = NULL;
Naohiro Aota4f2bafe2020-02-25 12:56:10 +09005373 struct alloc_chunk_ctl ctl;
Filipe Manana79bd3712021-06-29 14:43:06 +01005374 struct btrfs_block_group *block_group;
Miao Xieb2117a32011-01-05 10:07:28 +00005375 int ret;
Miao Xieb2117a32011-01-05 10:07:28 +00005376
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005377 lockdep_assert_held(&info->chunk_mutex);
5378
Naohiro Aotab25c19f2020-02-25 12:56:07 +09005379 if (!alloc_profile_is_valid(type, 0)) {
5380 ASSERT(0);
Filipe Manana79bd3712021-06-29 14:43:06 +01005381 return ERR_PTR(-EINVAL);
Naohiro Aotab25c19f2020-02-25 12:56:07 +09005382 }
Arne Jansen73c5de02011-04-12 12:07:57 +02005383
Qu Wenruo4117f202018-01-22 13:50:54 +08005384 if (list_empty(&fs_devices->alloc_list)) {
5385 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5386 btrfs_debug(info, "%s: no writable device", __func__);
Filipe Manana79bd3712021-06-29 14:43:06 +01005387 return ERR_PTR(-ENOSPC);
Qu Wenruo4117f202018-01-22 13:50:54 +08005388 }
Miao Xieb2117a32011-01-05 10:07:28 +00005389
Naohiro Aota27c314d2020-02-25 12:56:11 +09005390 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5391 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5392 ASSERT(0);
Filipe Manana79bd3712021-06-29 14:43:06 +01005393 return ERR_PTR(-EINVAL);
Arne Jansen73c5de02011-04-12 12:07:57 +02005394 }
5395
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005396 ctl.start = find_next_chunk(info);
Naohiro Aota27c314d2020-02-25 12:56:11 +09005397 ctl.type = type;
5398 init_alloc_chunk_ctl(fs_devices, &ctl);
Miao Xieb2117a32011-01-05 10:07:28 +00005399
David Sterba31e818f2015-02-20 18:00:26 +01005400 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
Miao Xieb2117a32011-01-05 10:07:28 +00005401 GFP_NOFS);
5402 if (!devices_info)
Filipe Manana79bd3712021-06-29 14:43:06 +01005403 return ERR_PTR(-ENOMEM);
Miao Xieb2117a32011-01-05 10:07:28 +00005404
Naohiro Aota560156c2020-02-25 12:56:12 +09005405 ret = gather_device_info(fs_devices, &ctl, devices_info);
Filipe Manana79bd3712021-06-29 14:43:06 +01005406 if (ret < 0) {
5407 block_group = ERR_PTR(ret);
Naohiro Aotadce580c2020-02-25 12:56:14 +09005408 goto out;
Filipe Manana79bd3712021-06-29 14:43:06 +01005409 }
Arne Jansen73c5de02011-04-12 12:07:57 +02005410
Naohiro Aota5badf512020-02-25 12:56:13 +09005411 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
Filipe Manana79bd3712021-06-29 14:43:06 +01005412 if (ret < 0) {
5413 block_group = ERR_PTR(ret);
Naohiro Aotadce580c2020-02-25 12:56:14 +09005414 goto out;
Filipe Manana79bd3712021-06-29 14:43:06 +01005415 }
Arne Jansen73c5de02011-04-12 12:07:57 +02005416
Filipe Manana79bd3712021-06-29 14:43:06 +01005417 block_group = create_chunk(trans, &ctl, devices_info);
Chris Mason9b3f68b2008-04-18 10:29:51 -04005418
Naohiro Aotadce580c2020-02-25 12:56:14 +09005419out:
Miao Xieb2117a32011-01-05 10:07:28 +00005420 kfree(devices_info);
Filipe Manana79bd3712021-06-29 14:43:06 +01005421 return block_group;
Yan Zheng2b820322008-11-17 21:11:30 -05005422}
5423
Nikolay Borisov11c67b12020-03-02 12:29:25 +02005424/*
Filipe Manana79bd3712021-06-29 14:43:06 +01005425 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5426 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5427 * chunks.
5428 *
5429 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5430 * phases.
5431 */
5432int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5433 struct btrfs_block_group *bg)
5434{
5435 struct btrfs_fs_info *fs_info = trans->fs_info;
5436 struct btrfs_root *extent_root = fs_info->extent_root;
5437 struct btrfs_root *chunk_root = fs_info->chunk_root;
5438 struct btrfs_key key;
5439 struct btrfs_chunk *chunk;
5440 struct btrfs_stripe *stripe;
5441 struct extent_map *em;
5442 struct map_lookup *map;
5443 size_t item_size;
5444 int i;
5445 int ret;
5446
5447 /*
5448 * We take the chunk_mutex for 2 reasons:
5449 *
5450 * 1) Updates and insertions in the chunk btree must be done while holding
5451 * the chunk_mutex, as well as updating the system chunk array in the
5452 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5453 * details;
5454 *
5455 * 2) To prevent races with the final phase of a device replace operation
5456 * that replaces the device object associated with the map's stripes,
5457 * because the device object's id can change at any time during that
5458 * final phase of the device replace operation
5459 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5460 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5461 * which would cause a failure when updating the device item, which does
5462 * not exists, or persisting a stripe of the chunk item with such ID.
5463 * Here we can't use the device_list_mutex because our caller already
5464 * has locked the chunk_mutex, and the final phase of device replace
5465 * acquires both mutexes - first the device_list_mutex and then the
5466 * chunk_mutex. Using any of those two mutexes protects us from a
5467 * concurrent device replace.
5468 */
5469 lockdep_assert_held(&fs_info->chunk_mutex);
5470
5471 em = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5472 if (IS_ERR(em)) {
5473 ret = PTR_ERR(em);
5474 btrfs_abort_transaction(trans, ret);
5475 return ret;
5476 }
5477
5478 map = em->map_lookup;
5479 item_size = btrfs_chunk_item_size(map->num_stripes);
5480
5481 chunk = kzalloc(item_size, GFP_NOFS);
5482 if (!chunk) {
5483 ret = -ENOMEM;
5484 btrfs_abort_transaction(trans, ret);
Filipe Manana50460e32015-11-20 10:42:47 +00005485 goto out;
Yan Zheng2b820322008-11-17 21:11:30 -05005486 }
5487
Filipe Manana79bd3712021-06-29 14:43:06 +01005488 for (i = 0; i < map->num_stripes; i++) {
5489 struct btrfs_device *device = map->stripes[i].dev;
5490
5491 ret = btrfs_update_device(trans, device);
5492 if (ret)
5493 goto out;
5494 }
5495
Yan Zheng2b820322008-11-17 21:11:30 -05005496 stripe = &chunk->stripe;
Josef Bacik6df9a952013-06-27 13:22:46 -04005497 for (i = 0; i < map->num_stripes; i++) {
Filipe Manana79bd3712021-06-29 14:43:06 +01005498 struct btrfs_device *device = map->stripes[i].dev;
5499 const u64 dev_offset = map->stripes[i].physical;
Yan Zheng2b820322008-11-17 21:11:30 -05005500
5501 btrfs_set_stack_stripe_devid(stripe, device->devid);
5502 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5503 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5504 stripe++;
Yan Zheng2b820322008-11-17 21:11:30 -05005505 }
5506
Filipe Manana79bd3712021-06-29 14:43:06 +01005507 btrfs_set_stack_chunk_length(chunk, bg->length);
Yan Zheng2b820322008-11-17 21:11:30 -05005508 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5509 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5510 btrfs_set_stack_chunk_type(chunk, map->type);
5511 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5512 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5513 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
Jeff Mahoney0b246af2016-06-22 18:54:23 -04005514 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
Yan Zheng2b820322008-11-17 21:11:30 -05005515 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5516
5517 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5518 key.type = BTRFS_CHUNK_ITEM_KEY;
Filipe Manana79bd3712021-06-29 14:43:06 +01005519 key.offset = bg->start;
Yan Zheng2b820322008-11-17 21:11:30 -05005520
5521 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
Filipe Manana79bd3712021-06-29 14:43:06 +01005522 if (ret)
5523 goto out;
5524
5525 bg->chunk_item_inserted = 1;
5526
5527 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04005528 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
Filipe Manana79bd3712021-06-29 14:43:06 +01005529 if (ret)
5530 goto out;
Yan Zheng2b820322008-11-17 21:11:30 -05005531 }
liubo1abe9b82011-03-24 11:18:59 +00005532
Josef Bacik6df9a952013-06-27 13:22:46 -04005533out:
Yan Zheng2b820322008-11-17 21:11:30 -05005534 kfree(chunk);
Josef Bacik6df9a952013-06-27 13:22:46 -04005535 free_extent_map(em);
Mark Fasheh4ed1d162011-08-10 12:32:10 -07005536 return ret;
Yan Zheng2b820322008-11-17 21:11:30 -05005537}
5538
David Sterba6f8e0fc2019-03-20 16:29:13 +01005539static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
Yan Zheng2b820322008-11-17 21:11:30 -05005540{
David Sterba6f8e0fc2019-03-20 16:29:13 +01005541 struct btrfs_fs_info *fs_info = trans->fs_info;
Yan Zheng2b820322008-11-17 21:11:30 -05005542 u64 alloc_profile;
Filipe Manana79bd3712021-06-29 14:43:06 +01005543 struct btrfs_block_group *meta_bg;
5544 struct btrfs_block_group *sys_bg;
5545
5546 /*
5547 * When adding a new device for sprouting, the seed device is read-only
5548 * so we must first allocate a metadata and a system chunk. But before
5549 * adding the block group items to the extent, device and chunk btrees,
5550 * we must first:
5551 *
5552 * 1) Create both chunks without doing any changes to the btrees, as
5553 * otherwise we would get -ENOSPC since the block groups from the
5554 * seed device are read-only;
5555 *
5556 * 2) Add the device item for the new sprout device - finishing the setup
5557 * of a new block group requires updating the device item in the chunk
5558 * btree, so it must exist when we attempt to do it. The previous step
5559 * ensures this does not fail with -ENOSPC.
5560 *
5561 * After that we can add the block group items to their btrees:
5562 * update existing device item in the chunk btree, add a new block group
5563 * item to the extent btree, add a new chunk item to the chunk btree and
5564 * finally add the new device extent items to the devices btree.
5565 */
Yan Zheng2b820322008-11-17 21:11:30 -05005566
Jeff Mahoney1b868262017-05-17 11:38:35 -04005567 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
Filipe Manana79bd3712021-06-29 14:43:06 +01005568 meta_bg = btrfs_alloc_chunk(trans, alloc_profile);
5569 if (IS_ERR(meta_bg))
5570 return PTR_ERR(meta_bg);
Yan Zheng2b820322008-11-17 21:11:30 -05005571
Jeff Mahoney1b868262017-05-17 11:38:35 -04005572 alloc_profile = btrfs_system_alloc_profile(fs_info);
Filipe Manana79bd3712021-06-29 14:43:06 +01005573 sys_bg = btrfs_alloc_chunk(trans, alloc_profile);
5574 if (IS_ERR(sys_bg))
5575 return PTR_ERR(sys_bg);
5576
5577 return 0;
Yan Zheng2b820322008-11-17 21:11:30 -05005578}
5579
Miao Xied20983b2014-07-03 18:22:13 +08005580static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5581{
David Sterbafc9a2ac2019-05-17 11:43:22 +02005582 const int index = btrfs_bg_flags_to_raid_index(map->type);
Miao Xied20983b2014-07-03 18:22:13 +08005583
David Sterbafc9a2ac2019-05-17 11:43:22 +02005584 return btrfs_raid_array[index].tolerated_failures;
Yan Zheng2b820322008-11-17 21:11:30 -05005585}
5586
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04005587int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
Yan Zheng2b820322008-11-17 21:11:30 -05005588{
5589 struct extent_map *em;
5590 struct map_lookup *map;
Yan Zheng2b820322008-11-17 21:11:30 -05005591 int readonly = 0;
Miao Xied20983b2014-07-03 18:22:13 +08005592 int miss_ndevs = 0;
Yan Zheng2b820322008-11-17 21:11:30 -05005593 int i;
5594
Omar Sandoval60ca8422018-05-16 16:34:31 -07005595 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
Liu Bo592d92e2017-03-14 13:33:55 -07005596 if (IS_ERR(em))
Yan Zheng2b820322008-11-17 21:11:30 -05005597 return 1;
5598
Jeff Mahoney95617d62015-06-03 10:55:48 -04005599 map = em->map_lookup;
Yan Zheng2b820322008-11-17 21:11:30 -05005600 for (i = 0; i < map->num_stripes; i++) {
Anand Jaine6e674b2017-12-04 12:54:54 +08005601 if (test_bit(BTRFS_DEV_STATE_MISSING,
5602 &map->stripes[i].dev->dev_state)) {
Miao Xied20983b2014-07-03 18:22:13 +08005603 miss_ndevs++;
5604 continue;
5605 }
Anand Jainebbede42017-12-04 12:54:52 +08005606 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5607 &map->stripes[i].dev->dev_state)) {
Yan Zheng2b820322008-11-17 21:11:30 -05005608 readonly = 1;
Miao Xied20983b2014-07-03 18:22:13 +08005609 goto end;
Yan Zheng2b820322008-11-17 21:11:30 -05005610 }
5611 }
Miao Xied20983b2014-07-03 18:22:13 +08005612
5613 /*
5614 * If the number of missing devices is larger than max errors,
5615 * we can not write the data into that chunk successfully, so
5616 * set it readonly.
5617 */
5618 if (miss_ndevs > btrfs_chunk_max_errors(map))
5619 readonly = 1;
5620end:
Yan Zheng2b820322008-11-17 21:11:30 -05005621 free_extent_map(em);
5622 return readonly;
Chris Mason0b86a832008-03-24 15:01:56 -04005623}
5624
David Sterbac8bf1b62019-05-17 11:43:17 +02005625void btrfs_mapping_tree_free(struct extent_map_tree *tree)
Chris Mason0b86a832008-03-24 15:01:56 -04005626{
5627 struct extent_map *em;
5628
Chris Masond3977122009-01-05 21:25:51 -05005629 while (1) {
David Sterbac8bf1b62019-05-17 11:43:17 +02005630 write_lock(&tree->lock);
5631 em = lookup_extent_mapping(tree, 0, (u64)-1);
Chris Mason0b86a832008-03-24 15:01:56 -04005632 if (em)
David Sterbac8bf1b62019-05-17 11:43:17 +02005633 remove_extent_mapping(tree, em);
5634 write_unlock(&tree->lock);
Chris Mason0b86a832008-03-24 15:01:56 -04005635 if (!em)
5636 break;
Chris Mason0b86a832008-03-24 15:01:56 -04005637 /* once for us */
5638 free_extent_map(em);
5639 /* once for the tree */
5640 free_extent_map(em);
5641 }
5642}
5643
Stefan Behrens5d964052012-11-05 14:59:07 +01005644int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
Chris Masonf1885912008-04-09 16:28:12 -04005645{
5646 struct extent_map *em;
5647 struct map_lookup *map;
Chris Masonf1885912008-04-09 16:28:12 -04005648 int ret;
5649
Omar Sandoval60ca8422018-05-16 16:34:31 -07005650 em = btrfs_get_chunk_map(fs_info, logical, len);
Liu Bo592d92e2017-03-14 13:33:55 -07005651 if (IS_ERR(em))
5652 /*
5653 * We could return errors for these cases, but that could get
5654 * ugly and we'd probably do the same thing which is just not do
5655 * anything else and exit, so return 1 so the callers don't try
5656 * to use other copies.
5657 */
Josef Bacikfb7669b2013-04-23 10:53:18 -04005658 return 1;
Josef Bacikfb7669b2013-04-23 10:53:18 -04005659
Jeff Mahoney95617d62015-06-03 10:55:48 -04005660 map = em->map_lookup;
David Sterbac7369b32019-05-31 15:39:31 +02005661 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
Chris Masonf1885912008-04-09 16:28:12 -04005662 ret = map->num_stripes;
Chris Mason321aecc2008-04-16 10:49:51 -04005663 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5664 ret = map->sub_stripes;
David Woodhouse53b381b2013-01-29 18:40:14 -05005665 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5666 ret = 2;
5667 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
Liu Bo8810f752018-01-02 13:36:41 -07005668 /*
5669 * There could be two corrupted data stripes, we need
5670 * to loop retry in order to rebuild the correct data.
Nikolay Borisove7e02092018-06-20 15:48:55 +03005671 *
Liu Bo8810f752018-01-02 13:36:41 -07005672 * Fail a stripe at a time on every retry except the
5673 * stripe under reconstruction.
5674 */
5675 ret = map->num_stripes;
Chris Masonf1885912008-04-09 16:28:12 -04005676 else
5677 ret = 1;
5678 free_extent_map(em);
Stefan Behrensad6d6202012-11-06 15:06:47 +01005679
David Sterbacb5583d2018-09-07 16:11:23 +02005680 down_read(&fs_info->dev_replace.rwsem);
Liu Bo6fad8232017-03-14 13:33:59 -07005681 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5682 fs_info->dev_replace.tgtdev)
Stefan Behrensad6d6202012-11-06 15:06:47 +01005683 ret++;
David Sterbacb5583d2018-09-07 16:11:23 +02005684 up_read(&fs_info->dev_replace.rwsem);
Stefan Behrensad6d6202012-11-06 15:06:47 +01005685
Chris Masonf1885912008-04-09 16:28:12 -04005686 return ret;
5687}
5688
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04005689unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
David Woodhouse53b381b2013-01-29 18:40:14 -05005690 u64 logical)
5691{
5692 struct extent_map *em;
5693 struct map_lookup *map;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04005694 unsigned long len = fs_info->sectorsize;
David Woodhouse53b381b2013-01-29 18:40:14 -05005695
Omar Sandoval60ca8422018-05-16 16:34:31 -07005696 em = btrfs_get_chunk_map(fs_info, logical, len);
David Woodhouse53b381b2013-01-29 18:40:14 -05005697
Nikolay Borisov69f03f12017-07-11 16:55:51 +03005698 if (!WARN_ON(IS_ERR(em))) {
5699 map = em->map_lookup;
5700 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5701 len = map->stripe_len * nr_data_stripes(map);
5702 free_extent_map(em);
5703 }
David Woodhouse53b381b2013-01-29 18:40:14 -05005704 return len;
5705}
5706
Nikolay Borisove4ff5fb2017-07-19 10:48:42 +03005707int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
David Woodhouse53b381b2013-01-29 18:40:14 -05005708{
5709 struct extent_map *em;
5710 struct map_lookup *map;
David Woodhouse53b381b2013-01-29 18:40:14 -05005711 int ret = 0;
5712
Omar Sandoval60ca8422018-05-16 16:34:31 -07005713 em = btrfs_get_chunk_map(fs_info, logical, len);
David Woodhouse53b381b2013-01-29 18:40:14 -05005714
Nikolay Borisov69f03f12017-07-11 16:55:51 +03005715 if(!WARN_ON(IS_ERR(em))) {
5716 map = em->map_lookup;
5717 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5718 ret = 1;
5719 free_extent_map(em);
5720 }
David Woodhouse53b381b2013-01-29 18:40:14 -05005721 return ret;
5722}
5723
Stefan Behrens30d98612012-11-06 14:52:18 +01005724static int find_live_mirror(struct btrfs_fs_info *fs_info,
Anand Jain99f92a72018-03-14 16:29:12 +08005725 struct map_lookup *map, int first,
Anand Jain8ba0ae72018-03-14 16:29:13 +08005726 int dev_replace_is_ongoing)
Chris Masondfe25022008-05-13 13:46:40 -04005727{
5728 int i;
Anand Jain99f92a72018-03-14 16:29:12 +08005729 int num_stripes;
Anand Jain8ba0ae72018-03-14 16:29:13 +08005730 int preferred_mirror;
Stefan Behrens30d98612012-11-06 14:52:18 +01005731 int tolerance;
5732 struct btrfs_device *srcdev;
5733
Anand Jain99f92a72018-03-14 16:29:12 +08005734 ASSERT((map->type &
David Sterbac7369b32019-05-31 15:39:31 +02005735 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
Anand Jain99f92a72018-03-14 16:29:12 +08005736
5737 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5738 num_stripes = map->sub_stripes;
5739 else
5740 num_stripes = map->num_stripes;
5741
Anand Jain33fd2f72020-10-28 21:14:46 +08005742 switch (fs_info->fs_devices->read_policy) {
5743 default:
5744 /* Shouldn't happen, just warn and use pid instead of failing */
5745 btrfs_warn_rl(fs_info,
5746 "unknown read_policy type %u, reset to pid",
5747 fs_info->fs_devices->read_policy);
5748 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID;
5749 fallthrough;
5750 case BTRFS_READ_POLICY_PID:
5751 preferred_mirror = first + (current->pid % num_stripes);
5752 break;
5753 }
Anand Jain8ba0ae72018-03-14 16:29:13 +08005754
Stefan Behrens30d98612012-11-06 14:52:18 +01005755 if (dev_replace_is_ongoing &&
5756 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5757 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5758 srcdev = fs_info->dev_replace.srcdev;
5759 else
5760 srcdev = NULL;
5761
5762 /*
5763 * try to avoid the drive that is the source drive for a
5764 * dev-replace procedure, only choose it if no other non-missing
5765 * mirror is available
5766 */
5767 for (tolerance = 0; tolerance < 2; tolerance++) {
Anand Jain8ba0ae72018-03-14 16:29:13 +08005768 if (map->stripes[preferred_mirror].dev->bdev &&
5769 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5770 return preferred_mirror;
Anand Jain99f92a72018-03-14 16:29:12 +08005771 for (i = first; i < first + num_stripes; i++) {
Stefan Behrens30d98612012-11-06 14:52:18 +01005772 if (map->stripes[i].dev->bdev &&
5773 (tolerance || map->stripes[i].dev != srcdev))
5774 return i;
5775 }
Chris Masondfe25022008-05-13 13:46:40 -04005776 }
Stefan Behrens30d98612012-11-06 14:52:18 +01005777
Chris Masondfe25022008-05-13 13:46:40 -04005778 /* we couldn't find one that doesn't fail. Just return something
5779 * and the io error handling code will clean up eventually
5780 */
Anand Jain8ba0ae72018-03-14 16:29:13 +08005781 return preferred_mirror;
Chris Masondfe25022008-05-13 13:46:40 -04005782}
5783
David Woodhouse53b381b2013-01-29 18:40:14 -05005784/* Bubble-sort the stripe set to put the parity/syndrome stripes last */
Zhao Lei8e5cfb52015-01-20 15:11:33 +08005785static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
David Woodhouse53b381b2013-01-29 18:40:14 -05005786{
David Woodhouse53b381b2013-01-29 18:40:14 -05005787 int i;
David Woodhouse53b381b2013-01-29 18:40:14 -05005788 int again = 1;
5789
5790 while (again) {
5791 again = 0;
Zhao Leicc7539e2015-01-20 15:11:32 +08005792 for (i = 0; i < num_stripes - 1; i++) {
David Sterbaeeb6f172019-11-28 15:31:17 +01005793 /* Swap if parity is on a smaller index */
5794 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5795 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5796 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
David Woodhouse53b381b2013-01-29 18:40:14 -05005797 again = 1;
5798 }
5799 }
5800 }
5801}
5802
Zhao Lei6e9606d2015-01-20 15:11:34 +08005803static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5804{
5805 struct btrfs_bio *bbio = kzalloc(
Chris Masone57cf212015-02-19 17:51:39 -08005806 /* the size of the btrfs_bio */
Zhao Lei6e9606d2015-01-20 15:11:34 +08005807 sizeof(struct btrfs_bio) +
Chris Masone57cf212015-02-19 17:51:39 -08005808 /* plus the variable array for the stripes */
Zhao Lei6e9606d2015-01-20 15:11:34 +08005809 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
Chris Masone57cf212015-02-19 17:51:39 -08005810 /* plus the variable array for the tgt dev */
Zhao Lei6e9606d2015-01-20 15:11:34 +08005811 sizeof(int) * (real_stripes) +
Chris Masone57cf212015-02-19 17:51:39 -08005812 /*
5813 * plus the raid_map, which includes both the tgt dev
5814 * and the stripes
5815 */
5816 sizeof(u64) * (total_stripes),
Michal Hocko277fb5f2015-08-19 14:17:41 +02005817 GFP_NOFS|__GFP_NOFAIL);
Zhao Lei6e9606d2015-01-20 15:11:34 +08005818
5819 atomic_set(&bbio->error, 0);
Elena Reshetova140475a2017-03-03 10:55:10 +02005820 refcount_set(&bbio->refs, 1);
Zhao Lei6e9606d2015-01-20 15:11:34 +08005821
Nikolay Borisov608769a2020-07-02 16:46:41 +03005822 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5823 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5824
Zhao Lei6e9606d2015-01-20 15:11:34 +08005825 return bbio;
5826}
5827
5828void btrfs_get_bbio(struct btrfs_bio *bbio)
5829{
Elena Reshetova140475a2017-03-03 10:55:10 +02005830 WARN_ON(!refcount_read(&bbio->refs));
5831 refcount_inc(&bbio->refs);
Zhao Lei6e9606d2015-01-20 15:11:34 +08005832}
5833
5834void btrfs_put_bbio(struct btrfs_bio *bbio)
5835{
5836 if (!bbio)
5837 return;
Elena Reshetova140475a2017-03-03 10:55:10 +02005838 if (refcount_dec_and_test(&bbio->refs))
Zhao Lei6e9606d2015-01-20 15:11:34 +08005839 kfree(bbio);
5840}
5841
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005842/* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5843/*
5844 * Please note that, discard won't be sent to target device of device
5845 * replace.
5846 */
5847static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
Qu Wenruo6b7faad2019-10-23 21:57:27 +08005848 u64 logical, u64 *length_ret,
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005849 struct btrfs_bio **bbio_ret)
5850{
5851 struct extent_map *em;
5852 struct map_lookup *map;
5853 struct btrfs_bio *bbio;
Qu Wenruo6b7faad2019-10-23 21:57:27 +08005854 u64 length = *length_ret;
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005855 u64 offset;
5856 u64 stripe_nr;
5857 u64 stripe_nr_end;
5858 u64 stripe_end_offset;
5859 u64 stripe_cnt;
5860 u64 stripe_len;
5861 u64 stripe_offset;
5862 u64 num_stripes;
5863 u32 stripe_index;
5864 u32 factor = 0;
5865 u32 sub_stripes = 0;
5866 u64 stripes_per_dev = 0;
5867 u32 remaining_stripes = 0;
5868 u32 last_stripe = 0;
5869 int ret = 0;
5870 int i;
5871
5872 /* discard always return a bbio */
5873 ASSERT(bbio_ret);
5874
Omar Sandoval60ca8422018-05-16 16:34:31 -07005875 em = btrfs_get_chunk_map(fs_info, logical, length);
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005876 if (IS_ERR(em))
5877 return PTR_ERR(em);
5878
5879 map = em->map_lookup;
5880 /* we don't discard raid56 yet */
5881 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5882 ret = -EOPNOTSUPP;
5883 goto out;
5884 }
5885
5886 offset = logical - em->start;
Qu Wenruo2d974612019-10-23 21:57:26 +08005887 length = min_t(u64, em->start + em->len - logical, length);
Qu Wenruo6b7faad2019-10-23 21:57:27 +08005888 *length_ret = length;
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005889
5890 stripe_len = map->stripe_len;
5891 /*
5892 * stripe_nr counts the total number of stripes we have to stride
5893 * to get to this block
5894 */
5895 stripe_nr = div64_u64(offset, stripe_len);
5896
5897 /* stripe_offset is the offset of this block in its stripe */
5898 stripe_offset = offset - stripe_nr * stripe_len;
5899
5900 stripe_nr_end = round_up(offset + length, map->stripe_len);
Liu Bo42c61ab2017-04-03 13:45:24 -07005901 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005902 stripe_cnt = stripe_nr_end - stripe_nr;
5903 stripe_end_offset = stripe_nr_end * map->stripe_len -
5904 (offset + length);
5905 /*
5906 * after this, stripe_nr is the number of stripes on this
5907 * device we have to walk to find the data, and stripe_index is
5908 * the number of our device in the stripe array
5909 */
5910 num_stripes = 1;
5911 stripe_index = 0;
5912 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5913 BTRFS_BLOCK_GROUP_RAID10)) {
5914 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5915 sub_stripes = 1;
5916 else
5917 sub_stripes = map->sub_stripes;
5918
5919 factor = map->num_stripes / sub_stripes;
5920 num_stripes = min_t(u64, map->num_stripes,
5921 sub_stripes * stripe_cnt);
5922 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5923 stripe_index *= sub_stripes;
5924 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5925 &remaining_stripes);
5926 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5927 last_stripe *= sub_stripes;
David Sterbac7369b32019-05-31 15:39:31 +02005928 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
Liu Bo0b3d4cd2017-03-14 13:33:56 -07005929 BTRFS_BLOCK_GROUP_DUP)) {
5930 num_stripes = map->num_stripes;
5931 } else {
5932 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5933 &stripe_index);
5934 }
5935
5936 bbio = alloc_btrfs_bio(num_stripes, 0);
5937 if (!bbio) {
5938 ret = -ENOMEM;
5939 goto out;
5940 }
5941
5942 for (i = 0; i < num_stripes; i++) {
5943 bbio->stripes[i].physical =
5944 map->stripes[stripe_index].physical +
5945 stripe_offset + stripe_nr * map->stripe_len;
5946 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5947
5948 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5949 BTRFS_BLOCK_GROUP_RAID10)) {
5950 bbio->stripes[i].length = stripes_per_dev *
5951 map->stripe_len;
5952
5953 if (i / sub_stripes < remaining_stripes)
5954 bbio->stripes[i].length +=
5955 map->stripe_len;
5956
5957 /*
5958 * Special for the first stripe and
5959 * the last stripe:
5960 *
5961 * |-------|...|-------|
5962 * |----------|
5963 * off end_off
5964 */
5965 if (i < sub_stripes)
5966 bbio->stripes[i].length -=
5967 stripe_offset;
5968
5969 if (stripe_index >= last_stripe &&
5970 stripe_index <= (last_stripe +
5971 sub_stripes - 1))
5972 bbio->stripes[i].length -=
5973 stripe_end_offset;
5974
5975 if (i == sub_stripes - 1)
5976 stripe_offset = 0;
5977 } else {
5978 bbio->stripes[i].length = length;
5979 }
5980
5981 stripe_index++;
5982 if (stripe_index == map->num_stripes) {
5983 stripe_index = 0;
5984 stripe_nr++;
5985 }
5986 }
5987
5988 *bbio_ret = bbio;
5989 bbio->map_type = map->type;
5990 bbio->num_stripes = num_stripes;
5991out:
5992 free_extent_map(em);
5993 return ret;
5994}
5995
Liu Bo5ab56092017-03-14 13:33:57 -07005996/*
5997 * In dev-replace case, for repair case (that's the only case where the mirror
5998 * is selected explicitly when calling btrfs_map_block), blocks left of the
5999 * left cursor can also be read from the target drive.
6000 *
6001 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
6002 * array of stripes.
6003 * For READ, it also needs to be supported using the same mirror number.
6004 *
6005 * If the requested block is not left of the left cursor, EIO is returned. This
6006 * can happen because btrfs_num_copies() returns one more in the dev-replace
6007 * case.
6008 */
6009static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
6010 u64 logical, u64 length,
6011 u64 srcdev_devid, int *mirror_num,
6012 u64 *physical)
6013{
6014 struct btrfs_bio *bbio = NULL;
6015 int num_stripes;
6016 int index_srcdev = 0;
6017 int found = 0;
6018 u64 physical_of_found = 0;
6019 int i;
6020 int ret = 0;
6021
6022 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
6023 logical, &length, &bbio, 0, 0);
6024 if (ret) {
6025 ASSERT(bbio == NULL);
6026 return ret;
6027 }
6028
6029 num_stripes = bbio->num_stripes;
6030 if (*mirror_num > num_stripes) {
6031 /*
6032 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
6033 * that means that the requested area is not left of the left
6034 * cursor
6035 */
6036 btrfs_put_bbio(bbio);
6037 return -EIO;
6038 }
6039
6040 /*
6041 * process the rest of the function using the mirror_num of the source
6042 * drive. Therefore look it up first. At the end, patch the device
6043 * pointer to the one of the target drive.
6044 */
6045 for (i = 0; i < num_stripes; i++) {
6046 if (bbio->stripes[i].dev->devid != srcdev_devid)
6047 continue;
6048
6049 /*
6050 * In case of DUP, in order to keep it simple, only add the
6051 * mirror with the lowest physical address
6052 */
6053 if (found &&
6054 physical_of_found <= bbio->stripes[i].physical)
6055 continue;
6056
6057 index_srcdev = i;
6058 found = 1;
6059 physical_of_found = bbio->stripes[i].physical;
6060 }
6061
6062 btrfs_put_bbio(bbio);
6063
6064 ASSERT(found);
6065 if (!found)
6066 return -EIO;
6067
6068 *mirror_num = index_srcdev + 1;
6069 *physical = physical_of_found;
6070 return ret;
6071}
6072
Naohiro Aota6143c232021-02-04 19:22:12 +09006073static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6074{
6075 struct btrfs_block_group *cache;
6076 bool ret;
6077
Naohiro Aotade17add2021-02-04 19:22:13 +09006078 /* Non zoned filesystem does not use "to_copy" flag */
Naohiro Aota6143c232021-02-04 19:22:12 +09006079 if (!btrfs_is_zoned(fs_info))
6080 return false;
6081
6082 cache = btrfs_lookup_block_group(fs_info, logical);
6083
6084 spin_lock(&cache->lock);
6085 ret = cache->to_copy;
6086 spin_unlock(&cache->lock);
6087
6088 btrfs_put_block_group(cache);
6089 return ret;
6090}
6091
Liu Bo73c0f222017-03-14 13:33:58 -07006092static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6093 struct btrfs_bio **bbio_ret,
6094 struct btrfs_dev_replace *dev_replace,
Naohiro Aota6143c232021-02-04 19:22:12 +09006095 u64 logical,
Liu Bo73c0f222017-03-14 13:33:58 -07006096 int *num_stripes_ret, int *max_errors_ret)
6097{
6098 struct btrfs_bio *bbio = *bbio_ret;
6099 u64 srcdev_devid = dev_replace->srcdev->devid;
6100 int tgtdev_indexes = 0;
6101 int num_stripes = *num_stripes_ret;
6102 int max_errors = *max_errors_ret;
6103 int i;
6104
6105 if (op == BTRFS_MAP_WRITE) {
6106 int index_where_to_add;
6107
6108 /*
Naohiro Aota6143c232021-02-04 19:22:12 +09006109 * A block group which have "to_copy" set will eventually
6110 * copied by dev-replace process. We can avoid cloning IO here.
6111 */
6112 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6113 return;
6114
6115 /*
Liu Bo73c0f222017-03-14 13:33:58 -07006116 * duplicate the write operations while the dev replace
6117 * procedure is running. Since the copying of the old disk to
6118 * the new disk takes place at run time while the filesystem is
6119 * mounted writable, the regular write operations to the old
6120 * disk have to be duplicated to go to the new disk as well.
6121 *
6122 * Note that device->missing is handled by the caller, and that
6123 * the write to the old disk is already set up in the stripes
6124 * array.
6125 */
6126 index_where_to_add = num_stripes;
6127 for (i = 0; i < num_stripes; i++) {
6128 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6129 /* write to new disk, too */
6130 struct btrfs_bio_stripe *new =
6131 bbio->stripes + index_where_to_add;
6132 struct btrfs_bio_stripe *old =
6133 bbio->stripes + i;
6134
6135 new->physical = old->physical;
6136 new->length = old->length;
6137 new->dev = dev_replace->tgtdev;
6138 bbio->tgtdev_map[i] = index_where_to_add;
6139 index_where_to_add++;
6140 max_errors++;
6141 tgtdev_indexes++;
6142 }
6143 }
6144 num_stripes = index_where_to_add;
6145 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
6146 int index_srcdev = 0;
6147 int found = 0;
6148 u64 physical_of_found = 0;
6149
6150 /*
6151 * During the dev-replace procedure, the target drive can also
6152 * be used to read data in case it is needed to repair a corrupt
6153 * block elsewhere. This is possible if the requested area is
6154 * left of the left cursor. In this area, the target drive is a
6155 * full copy of the source drive.
6156 */
6157 for (i = 0; i < num_stripes; i++) {
6158 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6159 /*
6160 * In case of DUP, in order to keep it simple,
6161 * only add the mirror with the lowest physical
6162 * address
6163 */
6164 if (found &&
6165 physical_of_found <=
6166 bbio->stripes[i].physical)
6167 continue;
6168 index_srcdev = i;
6169 found = 1;
6170 physical_of_found = bbio->stripes[i].physical;
6171 }
6172 }
6173 if (found) {
6174 struct btrfs_bio_stripe *tgtdev_stripe =
6175 bbio->stripes + num_stripes;
6176
6177 tgtdev_stripe->physical = physical_of_found;
6178 tgtdev_stripe->length =
6179 bbio->stripes[index_srcdev].length;
6180 tgtdev_stripe->dev = dev_replace->tgtdev;
6181 bbio->tgtdev_map[index_srcdev] = num_stripes;
6182
6183 tgtdev_indexes++;
6184 num_stripes++;
6185 }
6186 }
6187
6188 *num_stripes_ret = num_stripes;
6189 *max_errors_ret = max_errors;
6190 bbio->num_tgtdevs = tgtdev_indexes;
6191 *bbio_ret = bbio;
6192}
6193
Liu Bo2b19a1f2017-03-14 13:34:00 -07006194static bool need_full_stripe(enum btrfs_map_op op)
6195{
6196 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
6197}
6198
Nikolay Borisov5f141122019-06-03 12:05:03 +03006199/*
Michal Rostecki42034312021-01-27 14:57:27 +01006200 * Calculate the geometry of a particular (address, len) tuple. This
6201 * information is used to calculate how big a particular bio can get before it
6202 * straddles a stripe.
Nikolay Borisov5f141122019-06-03 12:05:03 +03006203 *
Michal Rostecki42034312021-01-27 14:57:27 +01006204 * @fs_info: the filesystem
6205 * @em: mapping containing the logical extent
6206 * @op: type of operation - write or read
6207 * @logical: address that we want to figure out the geometry of
Michal Rostecki42034312021-01-27 14:57:27 +01006208 * @io_geom: pointer used to return values
Nikolay Borisov5f141122019-06-03 12:05:03 +03006209 *
6210 * Returns < 0 in case a chunk for the given logical address cannot be found,
6211 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
6212 */
Michal Rostecki42034312021-01-27 14:57:27 +01006213int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, struct extent_map *em,
Qu Wenruo43c0d1a2021-04-13 17:58:48 +08006214 enum btrfs_map_op op, u64 logical,
Michal Rostecki42034312021-01-27 14:57:27 +01006215 struct btrfs_io_geometry *io_geom)
Nikolay Borisov5f141122019-06-03 12:05:03 +03006216{
Nikolay Borisov5f141122019-06-03 12:05:03 +03006217 struct map_lookup *map;
Qu Wenruo43c0d1a2021-04-13 17:58:48 +08006218 u64 len;
Nikolay Borisov5f141122019-06-03 12:05:03 +03006219 u64 offset;
6220 u64 stripe_offset;
6221 u64 stripe_nr;
6222 u64 stripe_len;
6223 u64 raid56_full_stripe_start = (u64)-1;
6224 int data_stripes;
6225
6226 ASSERT(op != BTRFS_MAP_DISCARD);
6227
Nikolay Borisov5f141122019-06-03 12:05:03 +03006228 map = em->map_lookup;
6229 /* Offset of this logical address in the chunk */
6230 offset = logical - em->start;
6231 /* Len of a stripe in a chunk */
6232 stripe_len = map->stripe_len;
David Sterba1a9fd412021-05-21 17:42:23 +02006233 /* Stripe where this block falls in */
Nikolay Borisov5f141122019-06-03 12:05:03 +03006234 stripe_nr = div64_u64(offset, stripe_len);
6235 /* Offset of stripe in the chunk */
6236 stripe_offset = stripe_nr * stripe_len;
6237 if (offset < stripe_offset) {
6238 btrfs_crit(fs_info,
6239"stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
6240 stripe_offset, offset, em->start, logical, stripe_len);
Michal Rostecki42034312021-01-27 14:57:27 +01006241 return -EINVAL;
Nikolay Borisov5f141122019-06-03 12:05:03 +03006242 }
6243
6244 /* stripe_offset is the offset of this block in its stripe */
6245 stripe_offset = offset - stripe_offset;
6246 data_stripes = nr_data_stripes(map);
6247
6248 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6249 u64 max_len = stripe_len - stripe_offset;
6250
6251 /*
6252 * In case of raid56, we need to know the stripe aligned start
6253 */
6254 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6255 unsigned long full_stripe_len = stripe_len * data_stripes;
6256 raid56_full_stripe_start = offset;
6257
6258 /*
6259 * Allow a write of a full stripe, but make sure we
6260 * don't allow straddling of stripes
6261 */
6262 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6263 full_stripe_len);
6264 raid56_full_stripe_start *= full_stripe_len;
6265
6266 /*
6267 * For writes to RAID[56], allow a full stripeset across
6268 * all disks. For other RAID types and for RAID[56]
6269 * reads, just allow a single stripe (on a single disk).
6270 */
6271 if (op == BTRFS_MAP_WRITE) {
6272 max_len = stripe_len * data_stripes -
6273 (offset - raid56_full_stripe_start);
6274 }
6275 }
6276 len = min_t(u64, em->len - offset, max_len);
6277 } else {
6278 len = em->len - offset;
6279 }
6280
6281 io_geom->len = len;
6282 io_geom->offset = offset;
6283 io_geom->stripe_len = stripe_len;
6284 io_geom->stripe_nr = stripe_nr;
6285 io_geom->stripe_offset = stripe_offset;
6286 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6287
Michal Rostecki42034312021-01-27 14:57:27 +01006288 return 0;
Nikolay Borisov5f141122019-06-03 12:05:03 +03006289}
6290
Christoph Hellwigcf8cddd2016-10-27 09:27:36 +02006291static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6292 enum btrfs_map_op op,
Chris Masonf2d8d742008-04-21 10:03:05 -04006293 u64 logical, u64 *length,
Jan Schmidta1d3c472011-08-04 17:15:33 +02006294 struct btrfs_bio **bbio_ret,
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006295 int mirror_num, int need_raid_map)
Chris Mason0b86a832008-03-24 15:01:56 -04006296{
6297 struct extent_map *em;
6298 struct map_lookup *map;
Chris Mason593060d2008-03-25 16:50:33 -04006299 u64 stripe_offset;
6300 u64 stripe_nr;
David Woodhouse53b381b2013-01-29 18:40:14 -05006301 u64 stripe_len;
David Sterba9d644a62015-02-20 18:42:11 +01006302 u32 stripe_index;
David Sterbacff82672019-05-17 11:43:45 +02006303 int data_stripes;
Chris Masoncea9e442008-04-09 16:28:12 -04006304 int i;
Li Zefande11cc12011-12-01 12:55:47 +08006305 int ret = 0;
Chris Masonf2d8d742008-04-21 10:03:05 -04006306 int num_stripes;
Chris Masona236aed2008-04-29 09:38:00 -04006307 int max_errors = 0;
Miao Xie2c8cdd62014-11-14 16:06:25 +08006308 int tgtdev_indexes = 0;
Jan Schmidta1d3c472011-08-04 17:15:33 +02006309 struct btrfs_bio *bbio = NULL;
Stefan Behrens472262f2012-11-06 14:43:46 +01006310 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6311 int dev_replace_is_ongoing = 0;
6312 int num_alloc_stripes;
Stefan Behrensad6d6202012-11-06 15:06:47 +01006313 int patch_the_first_stripe_for_dev_replace = 0;
6314 u64 physical_to_patch_in_first_stripe = 0;
David Woodhouse53b381b2013-01-29 18:40:14 -05006315 u64 raid56_full_stripe_start = (u64)-1;
Nikolay Borisov89b798a2019-06-03 12:05:05 +03006316 struct btrfs_io_geometry geom;
6317
6318 ASSERT(bbio_ret);
David Sterba75fb2e92018-08-03 00:36:29 +02006319 ASSERT(op != BTRFS_MAP_DISCARD);
Liu Bo0b3d4cd2017-03-14 13:33:56 -07006320
Michal Rostecki42034312021-01-27 14:57:27 +01006321 em = btrfs_get_chunk_map(fs_info, logical, *length);
6322 ASSERT(!IS_ERR(em));
6323
Qu Wenruo43c0d1a2021-04-13 17:58:48 +08006324 ret = btrfs_get_io_geometry(fs_info, em, op, logical, &geom);
Nikolay Borisov89b798a2019-06-03 12:05:05 +03006325 if (ret < 0)
6326 return ret;
6327
Jeff Mahoney95617d62015-06-03 10:55:48 -04006328 map = em->map_lookup;
Chris Mason593060d2008-03-25 16:50:33 -04006329
Nikolay Borisov89b798a2019-06-03 12:05:05 +03006330 *length = geom.len;
Nikolay Borisov89b798a2019-06-03 12:05:05 +03006331 stripe_len = geom.stripe_len;
6332 stripe_nr = geom.stripe_nr;
6333 stripe_offset = geom.stripe_offset;
6334 raid56_full_stripe_start = geom.raid56_stripe_offset;
David Sterbacff82672019-05-17 11:43:45 +02006335 data_stripes = nr_data_stripes(map);
Chris Mason593060d2008-03-25 16:50:33 -04006336
David Sterbacb5583d2018-09-07 16:11:23 +02006337 down_read(&dev_replace->rwsem);
Stefan Behrens472262f2012-11-06 14:43:46 +01006338 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
David Sterba53176dd2018-04-05 01:41:06 +02006339 /*
6340 * Hold the semaphore for read during the whole operation, write is
6341 * requested at commit time but must wait.
6342 */
Stefan Behrens472262f2012-11-06 14:43:46 +01006343 if (!dev_replace_is_ongoing)
David Sterbacb5583d2018-09-07 16:11:23 +02006344 up_read(&dev_replace->rwsem);
Stefan Behrens472262f2012-11-06 14:43:46 +01006345
Stefan Behrensad6d6202012-11-06 15:06:47 +01006346 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
Liu Bo2b19a1f2017-03-14 13:34:00 -07006347 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
Liu Bo5ab56092017-03-14 13:33:57 -07006348 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6349 dev_replace->srcdev->devid,
6350 &mirror_num,
6351 &physical_to_patch_in_first_stripe);
6352 if (ret)
Stefan Behrensad6d6202012-11-06 15:06:47 +01006353 goto out;
Liu Bo5ab56092017-03-14 13:33:57 -07006354 else
6355 patch_the_first_stripe_for_dev_replace = 1;
Stefan Behrensad6d6202012-11-06 15:06:47 +01006356 } else if (mirror_num > map->num_stripes) {
6357 mirror_num = 0;
6358 }
6359
Chris Masonf2d8d742008-04-21 10:03:05 -04006360 num_stripes = 1;
Chris Masoncea9e442008-04-09 16:28:12 -04006361 stripe_index = 0;
Li Dongyangfce3bb92011-03-24 10:24:26 +00006362 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
David Sterba47c57132015-02-20 18:43:47 +01006363 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6364 &stripe_index);
Anand Jainde483732017-10-12 16:43:00 +08006365 if (!need_full_stripe(op))
Miao Xie28e1cc72014-09-12 18:44:02 +08006366 mirror_num = 1;
David Sterbac7369b32019-05-31 15:39:31 +02006367 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
Anand Jainde483732017-10-12 16:43:00 +08006368 if (need_full_stripe(op))
Chris Masonf2d8d742008-04-21 10:03:05 -04006369 num_stripes = map->num_stripes;
Chris Mason2fff7342008-04-29 14:12:09 -04006370 else if (mirror_num)
Chris Masonf1885912008-04-09 16:28:12 -04006371 stripe_index = mirror_num - 1;
Chris Masondfe25022008-05-13 13:46:40 -04006372 else {
Stefan Behrens30d98612012-11-06 14:52:18 +01006373 stripe_index = find_live_mirror(fs_info, map, 0,
Stefan Behrens30d98612012-11-06 14:52:18 +01006374 dev_replace_is_ongoing);
Jan Schmidta1d3c472011-08-04 17:15:33 +02006375 mirror_num = stripe_index + 1;
Chris Masondfe25022008-05-13 13:46:40 -04006376 }
Chris Mason2fff7342008-04-29 14:12:09 -04006377
Chris Mason611f0e02008-04-03 16:29:03 -04006378 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
Anand Jainde483732017-10-12 16:43:00 +08006379 if (need_full_stripe(op)) {
Chris Masonf2d8d742008-04-21 10:03:05 -04006380 num_stripes = map->num_stripes;
Jan Schmidta1d3c472011-08-04 17:15:33 +02006381 } else if (mirror_num) {
Chris Masonf1885912008-04-09 16:28:12 -04006382 stripe_index = mirror_num - 1;
Jan Schmidta1d3c472011-08-04 17:15:33 +02006383 } else {
6384 mirror_num = 1;
6385 }
Chris Mason2fff7342008-04-29 14:12:09 -04006386
Chris Mason321aecc2008-04-16 10:49:51 -04006387 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
David Sterba9d644a62015-02-20 18:42:11 +01006388 u32 factor = map->num_stripes / map->sub_stripes;
Chris Mason321aecc2008-04-16 10:49:51 -04006389
David Sterba47c57132015-02-20 18:43:47 +01006390 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
Chris Mason321aecc2008-04-16 10:49:51 -04006391 stripe_index *= map->sub_stripes;
6392
Anand Jainde483732017-10-12 16:43:00 +08006393 if (need_full_stripe(op))
Chris Masonf2d8d742008-04-21 10:03:05 -04006394 num_stripes = map->sub_stripes;
Chris Mason321aecc2008-04-16 10:49:51 -04006395 else if (mirror_num)
6396 stripe_index += mirror_num - 1;
Chris Masondfe25022008-05-13 13:46:40 -04006397 else {
Jan Schmidt3e743172012-04-27 12:41:45 -04006398 int old_stripe_index = stripe_index;
Stefan Behrens30d98612012-11-06 14:52:18 +01006399 stripe_index = find_live_mirror(fs_info, map,
6400 stripe_index,
Stefan Behrens30d98612012-11-06 14:52:18 +01006401 dev_replace_is_ongoing);
Jan Schmidt3e743172012-04-27 12:41:45 -04006402 mirror_num = stripe_index - old_stripe_index + 1;
Chris Masondfe25022008-05-13 13:46:40 -04006403 }
David Woodhouse53b381b2013-01-29 18:40:14 -05006404
Zhao Leiffe2d202015-01-20 15:11:44 +08006405 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
Anand Jainde483732017-10-12 16:43:00 +08006406 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
David Woodhouse53b381b2013-01-29 18:40:14 -05006407 /* push stripe_nr back to the start of the full stripe */
Liu Bo42c61ab2017-04-03 13:45:24 -07006408 stripe_nr = div64_u64(raid56_full_stripe_start,
David Sterbacff82672019-05-17 11:43:45 +02006409 stripe_len * data_stripes);
David Woodhouse53b381b2013-01-29 18:40:14 -05006410
6411 /* RAID[56] write or recovery. Return all stripes */
6412 num_stripes = map->num_stripes;
6413 max_errors = nr_parity_stripes(map);
6414
David Woodhouse53b381b2013-01-29 18:40:14 -05006415 *length = map->stripe_len;
6416 stripe_index = 0;
6417 stripe_offset = 0;
6418 } else {
6419 /*
6420 * Mirror #0 or #1 means the original data block.
6421 * Mirror #2 is RAID5 parity block.
6422 * Mirror #3 is RAID6 Q block.
6423 */
David Sterba47c57132015-02-20 18:43:47 +01006424 stripe_nr = div_u64_rem(stripe_nr,
David Sterbacff82672019-05-17 11:43:45 +02006425 data_stripes, &stripe_index);
David Woodhouse53b381b2013-01-29 18:40:14 -05006426 if (mirror_num > 1)
David Sterbacff82672019-05-17 11:43:45 +02006427 stripe_index = data_stripes + mirror_num - 2;
David Woodhouse53b381b2013-01-29 18:40:14 -05006428
6429 /* We distribute the parity blocks across stripes */
David Sterba47c57132015-02-20 18:43:47 +01006430 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6431 &stripe_index);
Anand Jainde483732017-10-12 16:43:00 +08006432 if (!need_full_stripe(op) && mirror_num <= 1)
Miao Xie28e1cc72014-09-12 18:44:02 +08006433 mirror_num = 1;
David Woodhouse53b381b2013-01-29 18:40:14 -05006434 }
Chris Mason8790d502008-04-03 16:29:03 -04006435 } else {
6436 /*
David Sterba47c57132015-02-20 18:43:47 +01006437 * after this, stripe_nr is the number of stripes on this
6438 * device we have to walk to find the data, and stripe_index is
6439 * the number of our device in the stripe array
Chris Mason8790d502008-04-03 16:29:03 -04006440 */
David Sterba47c57132015-02-20 18:43:47 +01006441 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6442 &stripe_index);
Jan Schmidta1d3c472011-08-04 17:15:33 +02006443 mirror_num = stripe_index + 1;
Chris Mason8790d502008-04-03 16:29:03 -04006444 }
Josef Bacike042d1e2016-04-12 12:54:40 -04006445 if (stripe_index >= map->num_stripes) {
Jeff Mahoney5d163e02016-09-20 10:05:00 -04006446 btrfs_crit(fs_info,
6447 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
Josef Bacike042d1e2016-04-12 12:54:40 -04006448 stripe_index, map->num_stripes);
6449 ret = -EINVAL;
6450 goto out;
6451 }
Chris Mason593060d2008-03-25 16:50:33 -04006452
Stefan Behrens472262f2012-11-06 14:43:46 +01006453 num_alloc_stripes = num_stripes;
Liu Bo6fad8232017-03-14 13:33:59 -07006454 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
Liu Bo0b3d4cd2017-03-14 13:33:56 -07006455 if (op == BTRFS_MAP_WRITE)
Stefan Behrensad6d6202012-11-06 15:06:47 +01006456 num_alloc_stripes <<= 1;
Christoph Hellwigcf8cddd2016-10-27 09:27:36 +02006457 if (op == BTRFS_MAP_GET_READ_MIRRORS)
Stefan Behrensad6d6202012-11-06 15:06:47 +01006458 num_alloc_stripes++;
Miao Xie2c8cdd62014-11-14 16:06:25 +08006459 tgtdev_indexes = num_stripes;
Stefan Behrensad6d6202012-11-06 15:06:47 +01006460 }
Miao Xie2c8cdd62014-11-14 16:06:25 +08006461
Zhao Lei6e9606d2015-01-20 15:11:34 +08006462 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
Li Zefande11cc12011-12-01 12:55:47 +08006463 if (!bbio) {
6464 ret = -ENOMEM;
6465 goto out;
6466 }
Nikolay Borisov608769a2020-07-02 16:46:41 +03006467
6468 for (i = 0; i < num_stripes; i++) {
6469 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6470 stripe_offset + stripe_nr * map->stripe_len;
6471 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6472 stripe_index++;
6473 }
Li Zefande11cc12011-12-01 12:55:47 +08006474
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006475 /* build raid_map */
Liu Bo2b19a1f2017-03-14 13:34:00 -07006476 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6477 (need_full_stripe(op) || mirror_num > 1)) {
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006478 u64 tmp;
David Sterba9d644a62015-02-20 18:42:11 +01006479 unsigned rot;
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006480
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006481 /* Work out the disk rotation on this stripe-set */
David Sterba47c57132015-02-20 18:43:47 +01006482 div_u64_rem(stripe_nr, num_stripes, &rot);
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006483
6484 /* Fill in the logical address of each stripe */
David Sterbacff82672019-05-17 11:43:45 +02006485 tmp = stripe_nr * data_stripes;
6486 for (i = 0; i < data_stripes; i++)
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006487 bbio->raid_map[(i+rot) % num_stripes] =
6488 em->start + (tmp + i) * map->stripe_len;
6489
6490 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6491 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6492 bbio->raid_map[(i+rot+1) % num_stripes] =
6493 RAID6_Q_STRIPE;
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006494
Nikolay Borisov608769a2020-07-02 16:46:41 +03006495 sort_parity_stripes(bbio, num_stripes);
Chris Mason593060d2008-03-25 16:50:33 -04006496 }
Li Zefande11cc12011-12-01 12:55:47 +08006497
Liu Bo2b19a1f2017-03-14 13:34:00 -07006498 if (need_full_stripe(op))
Miao Xied20983b2014-07-03 18:22:13 +08006499 max_errors = btrfs_chunk_max_errors(map);
Li Zefande11cc12011-12-01 12:55:47 +08006500
Liu Bo73c0f222017-03-14 13:33:58 -07006501 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
Liu Bo2b19a1f2017-03-14 13:34:00 -07006502 need_full_stripe(op)) {
Naohiro Aota6143c232021-02-04 19:22:12 +09006503 handle_ops_on_dev_replace(op, &bbio, dev_replace, logical,
6504 &num_stripes, &max_errors);
Stefan Behrens472262f2012-11-06 14:43:46 +01006505 }
6506
Li Zefande11cc12011-12-01 12:55:47 +08006507 *bbio_ret = bbio;
Zhao Lei10f11902015-01-20 15:11:43 +08006508 bbio->map_type = map->type;
Li Zefande11cc12011-12-01 12:55:47 +08006509 bbio->num_stripes = num_stripes;
6510 bbio->max_errors = max_errors;
6511 bbio->mirror_num = mirror_num;
Stefan Behrensad6d6202012-11-06 15:06:47 +01006512
6513 /*
6514 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6515 * mirror_num == num_stripes + 1 && dev_replace target drive is
6516 * available as a mirror
6517 */
6518 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6519 WARN_ON(num_stripes > 1);
6520 bbio->stripes[0].dev = dev_replace->tgtdev;
6521 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6522 bbio->mirror_num = map->num_stripes + 1;
6523 }
Chris Masoncea9e442008-04-09 16:28:12 -04006524out:
Liu Bo73beece2015-07-17 16:49:19 +08006525 if (dev_replace_is_ongoing) {
David Sterba53176dd2018-04-05 01:41:06 +02006526 lockdep_assert_held(&dev_replace->rwsem);
6527 /* Unlock and let waiting writers proceed */
David Sterbacb5583d2018-09-07 16:11:23 +02006528 up_read(&dev_replace->rwsem);
Liu Bo73beece2015-07-17 16:49:19 +08006529 }
Chris Mason0b86a832008-03-24 15:01:56 -04006530 free_extent_map(em);
Li Zefande11cc12011-12-01 12:55:47 +08006531 return ret;
Chris Mason0b86a832008-03-24 15:01:56 -04006532}
6533
Christoph Hellwigcf8cddd2016-10-27 09:27:36 +02006534int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
Chris Masonf2d8d742008-04-21 10:03:05 -04006535 u64 logical, u64 *length,
Jan Schmidta1d3c472011-08-04 17:15:33 +02006536 struct btrfs_bio **bbio_ret, int mirror_num)
Chris Masonf2d8d742008-04-21 10:03:05 -04006537{
David Sterba75fb2e92018-08-03 00:36:29 +02006538 if (op == BTRFS_MAP_DISCARD)
6539 return __btrfs_map_block_for_discard(fs_info, logical,
6540 length, bbio_ret);
6541
Mike Christieb3d3fa52016-06-05 14:31:53 -05006542 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
Zhao Lei8e5cfb52015-01-20 15:11:33 +08006543 mirror_num, 0);
Chris Masonf2d8d742008-04-21 10:03:05 -04006544}
6545
Miao Xieaf8e2d12014-10-23 14:42:50 +08006546/* For Scrub/replace */
Christoph Hellwigcf8cddd2016-10-27 09:27:36 +02006547int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
Miao Xieaf8e2d12014-10-23 14:42:50 +08006548 u64 logical, u64 *length,
David Sterba825ad4c2017-03-28 14:45:22 +02006549 struct btrfs_bio **bbio_ret)
Miao Xieaf8e2d12014-10-23 14:42:50 +08006550{
David Sterba825ad4c2017-03-28 14:45:22 +02006551 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
Miao Xieaf8e2d12014-10-23 14:42:50 +08006552}
6553
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006554static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
Miao Xie8408c712014-06-19 10:42:55 +08006555{
Mike Snitzer326e1db2015-05-22 09:14:03 -04006556 bio->bi_private = bbio->private;
6557 bio->bi_end_io = bbio->end_io;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006558 bio_endio(bio);
Mike Snitzer326e1db2015-05-22 09:14:03 -04006559
Zhao Lei6e9606d2015-01-20 15:11:34 +08006560 btrfs_put_bbio(bbio);
Miao Xie8408c712014-06-19 10:42:55 +08006561}
6562
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006563static void btrfs_end_bio(struct bio *bio)
Chris Mason8790d502008-04-03 16:29:03 -04006564{
Chris Mason9be33952013-05-17 18:30:14 -04006565 struct btrfs_bio *bbio = bio->bi_private;
Chris Mason7d2b4da2008-08-05 10:13:57 -04006566 int is_orig_bio = 0;
Chris Mason8790d502008-04-03 16:29:03 -04006567
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02006568 if (bio->bi_status) {
Jan Schmidta1d3c472011-08-04 17:15:33 +02006569 atomic_inc(&bbio->error);
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02006570 if (bio->bi_status == BLK_STS_IOERR ||
6571 bio->bi_status == BLK_STS_TARGET) {
Nikolay Borisovc31efbd2020-07-03 11:14:27 +03006572 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
Stefan Behrens442a4f62012-05-25 16:06:08 +02006573
Nikolay Borisov3eee86c2020-07-02 15:23:31 +03006574 ASSERT(dev->bdev);
Naohiro Aotacfe94442021-02-04 19:21:59 +09006575 if (btrfs_op(bio) == BTRFS_MAP_WRITE)
Nikolay Borisov3eee86c2020-07-02 15:23:31 +03006576 btrfs_dev_stat_inc_and_print(dev,
Stefan Behrens597a60f2012-06-14 16:42:31 +02006577 BTRFS_DEV_STAT_WRITE_ERRS);
Nikolay Borisov3eee86c2020-07-02 15:23:31 +03006578 else if (!(bio->bi_opf & REQ_RAHEAD))
6579 btrfs_dev_stat_inc_and_print(dev,
Stefan Behrens597a60f2012-06-14 16:42:31 +02006580 BTRFS_DEV_STAT_READ_ERRS);
Nikolay Borisov3eee86c2020-07-02 15:23:31 +03006581 if (bio->bi_opf & REQ_PREFLUSH)
6582 btrfs_dev_stat_inc_and_print(dev,
Stefan Behrens597a60f2012-06-14 16:42:31 +02006583 BTRFS_DEV_STAT_FLUSH_ERRS);
Stefan Behrens442a4f62012-05-25 16:06:08 +02006584 }
6585 }
Chris Mason8790d502008-04-03 16:29:03 -04006586
Jan Schmidta1d3c472011-08-04 17:15:33 +02006587 if (bio == bbio->orig_bio)
Chris Mason7d2b4da2008-08-05 10:13:57 -04006588 is_orig_bio = 1;
6589
Miao Xiec404e0d2014-01-30 16:46:55 +08006590 btrfs_bio_counter_dec(bbio->fs_info);
6591
Jan Schmidta1d3c472011-08-04 17:15:33 +02006592 if (atomic_dec_and_test(&bbio->stripes_pending)) {
Chris Mason7d2b4da2008-08-05 10:13:57 -04006593 if (!is_orig_bio) {
6594 bio_put(bio);
Jan Schmidta1d3c472011-08-04 17:15:33 +02006595 bio = bbio->orig_bio;
Chris Mason7d2b4da2008-08-05 10:13:57 -04006596 }
Muthu Kumarc7b22bb2014-01-08 14:19:52 -07006597
Chris Mason9be33952013-05-17 18:30:14 -04006598 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
Chris Masona236aed2008-04-29 09:38:00 -04006599 /* only send an error to the higher layers if it is
David Woodhouse53b381b2013-01-29 18:40:14 -05006600 * beyond the tolerance of the btrfs bio
Chris Masona236aed2008-04-29 09:38:00 -04006601 */
Jan Schmidta1d3c472011-08-04 17:15:33 +02006602 if (atomic_read(&bbio->error) > bbio->max_errors) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02006603 bio->bi_status = BLK_STS_IOERR;
Chris Mason5dbc8fc2011-12-09 11:07:37 -05006604 } else {
Chris Mason1259ab72008-05-12 13:39:03 -04006605 /*
6606 * this bio is actually up to date, we didn't
6607 * go over the max number of errors
6608 */
Anand Jain2dbe0c72017-10-14 08:35:56 +08006609 bio->bi_status = BLK_STS_OK;
Chris Mason1259ab72008-05-12 13:39:03 -04006610 }
Miao Xiec55f1392014-06-19 10:42:54 +08006611
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006612 btrfs_end_bbio(bbio, bio);
Chris Mason7d2b4da2008-08-05 10:13:57 -04006613 } else if (!is_orig_bio) {
Chris Mason8790d502008-04-03 16:29:03 -04006614 bio_put(bio);
6615 }
Chris Mason8790d502008-04-03 16:29:03 -04006616}
6617
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006618static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
Nikolay Borisovc31efbd2020-07-03 11:14:27 +03006619 u64 physical, struct btrfs_device *dev)
Josef Bacikde1ee922012-10-19 16:50:56 -04006620{
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006621 struct btrfs_fs_info *fs_info = bbio->fs_info;
Josef Bacikde1ee922012-10-19 16:50:56 -04006622
6623 bio->bi_private = bbio;
Nikolay Borisovc31efbd2020-07-03 11:14:27 +03006624 btrfs_io_bio(bio)->device = dev;
Josef Bacikde1ee922012-10-19 16:50:56 -04006625 bio->bi_end_io = btrfs_end_bio;
Kent Overstreet4f024f32013-10-11 15:44:27 -07006626 bio->bi_iter.bi_sector = physical >> 9;
Naohiro Aotad8e3fb12021-02-04 19:22:05 +09006627 /*
6628 * For zone append writing, bi_sector must point the beginning of the
6629 * zone
6630 */
6631 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
6632 if (btrfs_dev_is_sequential(dev, physical)) {
6633 u64 zone_start = round_down(physical, fs_info->zone_size);
6634
6635 bio->bi_iter.bi_sector = zone_start >> SECTOR_SHIFT;
6636 } else {
6637 bio->bi_opf &= ~REQ_OP_ZONE_APPEND;
6638 bio->bi_opf |= REQ_OP_WRITE;
6639 }
6640 }
Misono Tomohiro672d5992018-08-02 16:19:07 +09006641 btrfs_debug_in_rcu(fs_info,
6642 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
David Sterba1201b582020-11-26 15:41:27 +01006643 bio_op(bio), bio->bi_opf, bio->bi_iter.bi_sector,
David Sterba1db45a32019-11-28 15:31:46 +01006644 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6645 dev->devid, bio->bi_iter.bi_size);
Christoph Hellwig74d46992017-08-23 19:10:32 +02006646 bio_set_dev(bio, dev->bdev);
Miao Xiec404e0d2014-01-30 16:46:55 +08006647
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006648 btrfs_bio_counter_inc_noblocked(fs_info);
Miao Xiec404e0d2014-01-30 16:46:55 +08006649
Chris Mason08635ba2019-07-10 12:28:14 -07006650 btrfsic_submit_bio(bio);
Josef Bacikde1ee922012-10-19 16:50:56 -04006651}
6652
Josef Bacikde1ee922012-10-19 16:50:56 -04006653static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6654{
6655 atomic_inc(&bbio->error);
6656 if (atomic_dec_and_test(&bbio->stripes_pending)) {
Nicholas D Steeves01327612016-05-19 21:18:45 -04006657 /* Should be the original bio. */
Miao Xie8408c712014-06-19 10:42:55 +08006658 WARN_ON(bio != bbio->orig_bio);
6659
Chris Mason9be33952013-05-17 18:30:14 -04006660 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
Kent Overstreet4f024f32013-10-11 15:44:27 -07006661 bio->bi_iter.bi_sector = logical >> 9;
Anand Jain102ed2c2017-10-14 08:34:02 +08006662 if (atomic_read(&bbio->error) > bbio->max_errors)
6663 bio->bi_status = BLK_STS_IOERR;
6664 else
6665 bio->bi_status = BLK_STS_OK;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +02006666 btrfs_end_bbio(bbio, bio);
Josef Bacikde1ee922012-10-19 16:50:56 -04006667 }
6668}
6669
Omar Sandoval58efbc92017-08-22 23:45:59 -07006670blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
Chris Mason08635ba2019-07-10 12:28:14 -07006671 int mirror_num)
Chris Mason0b86a832008-03-24 15:01:56 -04006672{
Chris Mason0b86a832008-03-24 15:01:56 -04006673 struct btrfs_device *dev;
Chris Mason8790d502008-04-03 16:29:03 -04006674 struct bio *first_bio = bio;
David Sterba1201b582020-11-26 15:41:27 +01006675 u64 logical = bio->bi_iter.bi_sector << 9;
Chris Mason0b86a832008-03-24 15:01:56 -04006676 u64 length = 0;
6677 u64 map_length;
Chris Mason0b86a832008-03-24 15:01:56 -04006678 int ret;
Zhao Lei08da7572015-02-12 15:42:16 +08006679 int dev_nr;
6680 int total_devs;
Jan Schmidta1d3c472011-08-04 17:15:33 +02006681 struct btrfs_bio *bbio = NULL;
Chris Mason0b86a832008-03-24 15:01:56 -04006682
Kent Overstreet4f024f32013-10-11 15:44:27 -07006683 length = bio->bi_iter.bi_size;
Chris Mason0b86a832008-03-24 15:01:56 -04006684 map_length = length;
Chris Masoncea9e442008-04-09 16:28:12 -04006685
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006686 btrfs_bio_counter_inc_blocked(fs_info);
Liu Bobd7d63c2017-09-19 17:50:09 -06006687 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
Mike Christie37226b22016-06-05 14:31:52 -05006688 &map_length, &bbio, mirror_num, 1);
Miao Xiec404e0d2014-01-30 16:46:55 +08006689 if (ret) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006690 btrfs_bio_counter_dec(fs_info);
Omar Sandoval58efbc92017-08-22 23:45:59 -07006691 return errno_to_blk_status(ret);
Miao Xiec404e0d2014-01-30 16:46:55 +08006692 }
Chris Masoncea9e442008-04-09 16:28:12 -04006693
Jan Schmidta1d3c472011-08-04 17:15:33 +02006694 total_devs = bbio->num_stripes;
David Woodhouse53b381b2013-01-29 18:40:14 -05006695 bbio->orig_bio = first_bio;
6696 bbio->private = first_bio->bi_private;
6697 bbio->end_io = first_bio->bi_end_io;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006698 bbio->fs_info = fs_info;
David Woodhouse53b381b2013-01-29 18:40:14 -05006699 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6700
Zhao Leiad1ba2a2015-12-15 18:18:09 +08006701 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
Naohiro Aotacfe94442021-02-04 19:21:59 +09006702 ((btrfs_op(bio) == BTRFS_MAP_WRITE) || (mirror_num > 1))) {
David Woodhouse53b381b2013-01-29 18:40:14 -05006703 /* In this case, map_length has been set to the length of
6704 a single stripe; not the whole write */
Naohiro Aotacfe94442021-02-04 19:21:59 +09006705 if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006706 ret = raid56_parity_write(fs_info, bio, bbio,
6707 map_length);
David Woodhouse53b381b2013-01-29 18:40:14 -05006708 } else {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006709 ret = raid56_parity_recover(fs_info, bio, bbio,
6710 map_length, mirror_num, 1);
David Woodhouse53b381b2013-01-29 18:40:14 -05006711 }
Miao Xie42452152014-11-25 16:39:28 +08006712
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006713 btrfs_bio_counter_dec(fs_info);
Omar Sandoval58efbc92017-08-22 23:45:59 -07006714 return errno_to_blk_status(ret);
David Woodhouse53b381b2013-01-29 18:40:14 -05006715 }
6716
Chris Masoncea9e442008-04-09 16:28:12 -04006717 if (map_length < length) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006718 btrfs_crit(fs_info,
Jeff Mahoney5d163e02016-09-20 10:05:00 -04006719 "mapping failed logical %llu bio len %llu len %llu",
6720 logical, length, map_length);
Chris Masoncea9e442008-04-09 16:28:12 -04006721 BUG();
6722 }
Jan Schmidta1d3c472011-08-04 17:15:33 +02006723
Zhao Lei08da7572015-02-12 15:42:16 +08006724 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
Josef Bacikde1ee922012-10-19 16:50:56 -04006725 dev = bbio->stripes[dev_nr].dev;
Nikolay Borisovfc8a1682018-11-08 16:16:38 +02006726 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6727 &dev->dev_state) ||
Naohiro Aotacfe94442021-02-04 19:21:59 +09006728 (btrfs_op(first_bio) == BTRFS_MAP_WRITE &&
Anand Jainebbede42017-12-04 12:54:52 +08006729 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
Josef Bacikde1ee922012-10-19 16:50:56 -04006730 bbio_error(bbio, first_bio, logical);
Josef Bacikde1ee922012-10-19 16:50:56 -04006731 continue;
6732 }
6733
David Sterba3aa8e072017-06-02 17:38:30 +02006734 if (dev_nr < total_devs - 1)
David Sterba8b6c1d52017-06-02 17:48:13 +02006735 bio = btrfs_bio_clone(first_bio);
David Sterba3aa8e072017-06-02 17:38:30 +02006736 else
Jan Schmidta1d3c472011-08-04 17:15:33 +02006737 bio = first_bio;
Josef Bacik606686e2012-06-04 14:03:51 -04006738
Nikolay Borisovc31efbd2020-07-03 11:14:27 +03006739 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
Chris Mason239b14b2008-03-24 15:02:07 -04006740 }
Jeff Mahoney0b246af2016-06-22 18:54:23 -04006741 btrfs_bio_counter_dec(fs_info);
Omar Sandoval58efbc92017-08-22 23:45:59 -07006742 return BLK_STS_OK;
Chris Mason0b86a832008-03-24 15:01:56 -04006743}
6744
Anand Jain09ba3bc2019-01-19 14:48:55 +08006745/*
6746 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6747 * return NULL.
6748 *
6749 * If devid and uuid are both specified, the match must be exact, otherwise
6750 * only devid is used.
Anand Jain09ba3bc2019-01-19 14:48:55 +08006751 */
Anand Jaine4319cd2019-01-17 23:32:31 +08006752struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
Anand Jainb2598ed2020-11-03 13:49:43 +08006753 u64 devid, u8 *uuid, u8 *fsid)
Chris Mason0b86a832008-03-24 15:01:56 -04006754{
Yan Zheng2b820322008-11-17 21:11:30 -05006755 struct btrfs_device *device;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006756 struct btrfs_fs_devices *seed_devs;
Chris Mason0b86a832008-03-24 15:01:56 -04006757
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006758 if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6759 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6760 if (device->devid == devid &&
6761 (!uuid || memcmp(device->uuid, uuid,
6762 BTRFS_UUID_SIZE) == 0))
6763 return device;
6764 }
6765 }
6766
6767 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
Yan Zheng2b820322008-11-17 21:11:30 -05006768 if (!fsid ||
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006769 !memcmp(seed_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6770 list_for_each_entry(device, &seed_devs->devices,
Anand Jain09ba3bc2019-01-19 14:48:55 +08006771 dev_list) {
6772 if (device->devid == devid &&
6773 (!uuid || memcmp(device->uuid, uuid,
6774 BTRFS_UUID_SIZE) == 0))
6775 return device;
6776 }
Yan Zheng2b820322008-11-17 21:11:30 -05006777 }
Yan Zheng2b820322008-11-17 21:11:30 -05006778 }
Nikolay Borisov944d3f92020-07-16 10:25:33 +03006779
Yan Zheng2b820322008-11-17 21:11:30 -05006780 return NULL;
Chris Mason0b86a832008-03-24 15:01:56 -04006781}
6782
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04006783static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
Chris Masondfe25022008-05-13 13:46:40 -04006784 u64 devid, u8 *dev_uuid)
6785{
6786 struct btrfs_device *device;
Josef Bacikfccc0002020-08-31 10:52:42 -04006787 unsigned int nofs_flag;
Chris Masondfe25022008-05-13 13:46:40 -04006788
Josef Bacikfccc0002020-08-31 10:52:42 -04006789 /*
6790 * We call this under the chunk_mutex, so we want to use NOFS for this
6791 * allocation, however we don't want to change btrfs_alloc_device() to
6792 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6793 * places.
6794 */
6795 nofs_flag = memalloc_nofs_save();
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006796 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
Josef Bacikfccc0002020-08-31 10:52:42 -04006797 memalloc_nofs_restore(nofs_flag);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006798 if (IS_ERR(device))
Anand Jainadfb69a2017-10-11 12:46:18 +08006799 return device;
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006800
6801 list_add(&device->dev_list, &fs_devices->devices);
Yan Zhenge4404d62008-12-12 10:03:26 -05006802 device->fs_devices = fs_devices;
Chris Masondfe25022008-05-13 13:46:40 -04006803 fs_devices->num_devices++;
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006804
Anand Jaine6e674b2017-12-04 12:54:54 +08006805 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
Chris Masoncd02dca2010-12-13 14:56:23 -05006806 fs_devices->missing_devices++;
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006807
Chris Masondfe25022008-05-13 13:46:40 -04006808 return device;
6809}
6810
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006811/**
6812 * btrfs_alloc_device - allocate struct btrfs_device
6813 * @fs_info: used only for generating a new devid, can be NULL if
6814 * devid is provided (i.e. @devid != NULL).
6815 * @devid: a pointer to devid for this device. If NULL a new devid
6816 * is generated.
6817 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6818 * is generated.
6819 *
6820 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
David Sterba48dae9c2017-10-30 18:10:25 +01006821 * on error. Returned struct is not linked onto any lists and must be
David Sterbaa425f9d2018-03-20 15:47:33 +01006822 * destroyed with btrfs_free_device.
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006823 */
6824struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6825 const u64 *devid,
6826 const u8 *uuid)
6827{
6828 struct btrfs_device *dev;
6829 u64 tmp;
6830
Dulshani Gunawardhanafae7f212013-10-31 10:30:08 +05306831 if (WARN_ON(!devid && !fs_info))
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006832 return ERR_PTR(-EINVAL);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006833
Qu Wenruo154f7cb2020-08-20 15:42:46 +08006834 dev = __alloc_device(fs_info);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006835 if (IS_ERR(dev))
6836 return dev;
6837
6838 if (devid)
6839 tmp = *devid;
6840 else {
6841 int ret;
6842
6843 ret = find_next_devid(fs_info, &tmp);
6844 if (ret) {
David Sterbaa425f9d2018-03-20 15:47:33 +01006845 btrfs_free_device(dev);
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006846 return ERR_PTR(ret);
6847 }
6848 }
6849 dev->devid = tmp;
6850
6851 if (uuid)
6852 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6853 else
6854 generate_random_uuid(dev->uuid);
6855
Ilya Dryomov12bd2fc2013-08-23 13:20:17 +03006856 return dev;
6857}
6858
Anand Jain5a2b8e62017-10-09 11:07:45 +08006859static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
Anand Jain2b902df2017-10-09 11:07:46 +08006860 u64 devid, u8 *uuid, bool error)
Anand Jain5a2b8e62017-10-09 11:07:45 +08006861{
Anand Jain2b902df2017-10-09 11:07:46 +08006862 if (error)
6863 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6864 devid, uuid);
6865 else
6866 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6867 devid, uuid);
Anand Jain5a2b8e62017-10-09 11:07:45 +08006868}
6869
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006870static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6871{
6872 int index = btrfs_bg_flags_to_raid_index(type);
6873 int ncopies = btrfs_raid_array[index].ncopies;
David Sterbae4f6c6b2019-05-14 01:59:54 +02006874 const int nparity = btrfs_raid_array[index].nparity;
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006875 int data_stripes;
6876
David Sterbae4f6c6b2019-05-14 01:59:54 +02006877 if (nparity)
6878 data_stripes = num_stripes - nparity;
6879 else
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006880 data_stripes = num_stripes / ncopies;
David Sterbae4f6c6b2019-05-14 01:59:54 +02006881
Nikolay Borisov39e264a2019-03-25 14:31:25 +02006882 return div_u64(chunk_len, data_stripes);
6883}
6884
Qu Wenruoe9306ad2021-02-25 09:18:14 +08006885#if BITS_PER_LONG == 32
6886/*
6887 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6888 * can't be accessed on 32bit systems.
6889 *
6890 * This function do mount time check to reject the fs if it already has
6891 * metadata chunk beyond that limit.
6892 */
6893static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6894 u64 logical, u64 length, u64 type)
6895{
6896 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6897 return 0;
6898
6899 if (logical + length < MAX_LFS_FILESIZE)
6900 return 0;
6901
6902 btrfs_err_32bit_limit(fs_info);
6903 return -EOVERFLOW;
6904}
6905
6906/*
6907 * This is to give early warning for any metadata chunk reaching
6908 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6909 * Although we can still access the metadata, it's not going to be possible
6910 * once the limit is reached.
6911 */
6912static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6913 u64 logical, u64 length, u64 type)
6914{
6915 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6916 return;
6917
6918 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6919 return;
6920
6921 btrfs_warn_32bit_limit(fs_info);
6922}
6923#endif
6924
David Sterba9690ac02019-03-20 16:43:07 +01006925static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
Chris Mason0b86a832008-03-24 15:01:56 -04006926 struct btrfs_chunk *chunk)
6927{
David Sterba9690ac02019-03-20 16:43:07 +01006928 struct btrfs_fs_info *fs_info = leaf->fs_info;
David Sterbac8bf1b62019-05-17 11:43:17 +02006929 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
Chris Mason0b86a832008-03-24 15:01:56 -04006930 struct map_lookup *map;
6931 struct extent_map *em;
6932 u64 logical;
6933 u64 length;
6934 u64 devid;
Qu Wenruoe9306ad2021-02-25 09:18:14 +08006935 u64 type;
Chris Masona4437552008-04-18 10:29:38 -04006936 u8 uuid[BTRFS_UUID_SIZE];
Chris Mason593060d2008-03-25 16:50:33 -04006937 int num_stripes;
Chris Mason0b86a832008-03-24 15:01:56 -04006938 int ret;
Chris Mason593060d2008-03-25 16:50:33 -04006939 int i;
Chris Mason0b86a832008-03-24 15:01:56 -04006940
Chris Masone17cade2008-04-15 15:41:47 -04006941 logical = key->offset;
6942 length = btrfs_chunk_length(leaf, chunk);
Qu Wenruoe9306ad2021-02-25 09:18:14 +08006943 type = btrfs_chunk_type(leaf, chunk);
Qu Wenruof04b7722015-12-15 09:14:37 +08006944 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
Liu Boe06cd3d2016-06-03 12:05:15 -07006945
Qu Wenruoe9306ad2021-02-25 09:18:14 +08006946#if BITS_PER_LONG == 32
6947 ret = check_32bit_meta_chunk(fs_info, logical, length, type);
6948 if (ret < 0)
6949 return ret;
6950 warn_32bit_meta_chunk(fs_info, logical, length, type);
6951#endif
6952
Qu Wenruo075cb3c2019-03-20 13:42:33 +08006953 /*
6954 * Only need to verify chunk item if we're reading from sys chunk array,
6955 * as chunk item in tree block is already verified by tree-checker.
6956 */
6957 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
David Sterbaddaf1d52019-03-20 16:40:48 +01006958 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
Qu Wenruo075cb3c2019-03-20 13:42:33 +08006959 if (ret)
6960 return ret;
6961 }
Chris Masona061fc82008-05-07 11:43:44 -04006962
David Sterbac8bf1b62019-05-17 11:43:17 +02006963 read_lock(&map_tree->lock);
6964 em = lookup_extent_mapping(map_tree, logical, 1);
6965 read_unlock(&map_tree->lock);
Chris Mason0b86a832008-03-24 15:01:56 -04006966
6967 /* already mapped? */
6968 if (em && em->start <= logical && em->start + em->len > logical) {
6969 free_extent_map(em);
Chris Mason0b86a832008-03-24 15:01:56 -04006970 return 0;
6971 } else if (em) {
6972 free_extent_map(em);
6973 }
Chris Mason0b86a832008-03-24 15:01:56 -04006974
David Sterba172ddd62011-04-21 00:48:27 +02006975 em = alloc_extent_map();
Chris Mason0b86a832008-03-24 15:01:56 -04006976 if (!em)
6977 return -ENOMEM;
Chris Mason593060d2008-03-25 16:50:33 -04006978 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
Chris Mason0b86a832008-03-24 15:01:56 -04006979 if (!map) {
6980 free_extent_map(em);
6981 return -ENOMEM;
6982 }
6983
Wang Shilong298a8f92014-06-19 10:42:52 +08006984 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
Jeff Mahoney95617d62015-06-03 10:55:48 -04006985 em->map_lookup = map;
Chris Mason0b86a832008-03-24 15:01:56 -04006986 em->start = logical;
6987 em->len = length;
Josef Bacik70c8a912012-10-11 16:54:30 -04006988 em->orig_start = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04006989 em->block_start = 0;
Chris Masonc8b97812008-10-29 14:49:59 -04006990 em->block_len = em->len;
Chris Mason0b86a832008-03-24 15:01:56 -04006991
Chris Mason593060d2008-03-25 16:50:33 -04006992 map->num_stripes = num_stripes;
6993 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6994 map->io_align = btrfs_chunk_io_align(leaf, chunk);
Chris Mason593060d2008-03-25 16:50:33 -04006995 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
Qu Wenruoe9306ad2021-02-25 09:18:14 +08006996 map->type = type;
Chris Mason321aecc2008-04-16 10:49:51 -04006997 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
Qu Wenruocf90d882018-08-01 10:37:19 +08006998 map->verified_stripes = 0;
Qu Wenruoe9306ad2021-02-25 09:18:14 +08006999 em->orig_block_len = calc_stripe_length(type, em->len,
Nikolay Borisov39e264a2019-03-25 14:31:25 +02007000 map->num_stripes);
Chris Mason593060d2008-03-25 16:50:33 -04007001 for (i = 0; i < num_stripes; i++) {
7002 map->stripes[i].physical =
7003 btrfs_stripe_offset_nr(leaf, chunk, i);
7004 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
Chris Masona4437552008-04-18 10:29:38 -04007005 read_extent_buffer(leaf, uuid, (unsigned long)
7006 btrfs_stripe_dev_uuid_nr(chunk, i),
7007 BTRFS_UUID_SIZE);
Anand Jaine4319cd2019-01-17 23:32:31 +08007008 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
Anand Jainb2598ed2020-11-03 13:49:43 +08007009 devid, uuid, NULL);
Jeff Mahoney3cdde222016-06-09 21:38:35 -04007010 if (!map->stripes[i].dev &&
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007011 !btrfs_test_opt(fs_info, DEGRADED)) {
Chris Mason593060d2008-03-25 16:50:33 -04007012 free_extent_map(em);
Anand Jain2b902df2017-10-09 11:07:46 +08007013 btrfs_report_missing_device(fs_info, devid, uuid, true);
Anand Jain45dbdbc2017-10-09 11:07:44 +08007014 return -ENOENT;
Chris Mason593060d2008-03-25 16:50:33 -04007015 }
Chris Masondfe25022008-05-13 13:46:40 -04007016 if (!map->stripes[i].dev) {
7017 map->stripes[i].dev =
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04007018 add_missing_dev(fs_info->fs_devices, devid,
7019 uuid);
Anand Jainadfb69a2017-10-11 12:46:18 +08007020 if (IS_ERR(map->stripes[i].dev)) {
Chris Masondfe25022008-05-13 13:46:40 -04007021 free_extent_map(em);
Anand Jainadfb69a2017-10-11 12:46:18 +08007022 btrfs_err(fs_info,
7023 "failed to init missing dev %llu: %ld",
7024 devid, PTR_ERR(map->stripes[i].dev));
7025 return PTR_ERR(map->stripes[i].dev);
Chris Masondfe25022008-05-13 13:46:40 -04007026 }
Anand Jain2b902df2017-10-09 11:07:46 +08007027 btrfs_report_missing_device(fs_info, devid, uuid, false);
Chris Masondfe25022008-05-13 13:46:40 -04007028 }
Anand Jaine12c9622017-12-04 12:54:53 +08007029 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7030 &(map->stripes[i].dev->dev_state));
7031
Chris Mason0b86a832008-03-24 15:01:56 -04007032 }
7033
David Sterbac8bf1b62019-05-17 11:43:17 +02007034 write_lock(&map_tree->lock);
7035 ret = add_extent_mapping(map_tree, em, 0);
7036 write_unlock(&map_tree->lock);
Qu Wenruo64f64f42018-08-01 10:37:20 +08007037 if (ret < 0) {
7038 btrfs_err(fs_info,
7039 "failed to add chunk map, start=%llu len=%llu: %d",
7040 em->start, em->len, ret);
7041 }
Chris Mason0b86a832008-03-24 15:01:56 -04007042 free_extent_map(em);
7043
Qu Wenruo64f64f42018-08-01 10:37:20 +08007044 return ret;
Chris Mason0b86a832008-03-24 15:01:56 -04007045}
7046
Jeff Mahoney143bede2012-03-01 14:56:26 +01007047static void fill_device_from_item(struct extent_buffer *leaf,
Chris Mason0b86a832008-03-24 15:01:56 -04007048 struct btrfs_dev_item *dev_item,
7049 struct btrfs_device *device)
7050{
7051 unsigned long ptr;
Chris Mason0b86a832008-03-24 15:01:56 -04007052
7053 device->devid = btrfs_device_id(leaf, dev_item);
Chris Balld6397ba2009-04-27 07:29:03 -04007054 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7055 device->total_bytes = device->disk_total_bytes;
Miao Xie935e5cc2014-09-03 21:35:33 +08007056 device->commit_total_bytes = device->disk_total_bytes;
Chris Mason0b86a832008-03-24 15:01:56 -04007057 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
Miao Xiece7213c2014-09-03 21:35:34 +08007058 device->commit_bytes_used = device->bytes_used;
Chris Mason0b86a832008-03-24 15:01:56 -04007059 device->type = btrfs_device_type(leaf, dev_item);
7060 device->io_align = btrfs_device_io_align(leaf, dev_item);
7061 device->io_width = btrfs_device_io_width(leaf, dev_item);
7062 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
Stefan Behrens8dabb742012-11-06 13:15:27 +01007063 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
Anand Jain401e29c2017-12-04 12:54:55 +08007064 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
Chris Mason0b86a832008-03-24 15:01:56 -04007065
Geert Uytterhoeven410ba3a2013-08-20 13:20:11 +02007066 ptr = btrfs_device_uuid(dev_item);
Chris Masone17cade2008-04-15 15:41:47 -04007067 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
Chris Mason0b86a832008-03-24 15:01:56 -04007068}
7069
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04007070static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
Miao Xie5f375832014-09-03 21:35:46 +08007071 u8 *fsid)
Yan Zheng2b820322008-11-17 21:11:30 -05007072{
7073 struct btrfs_fs_devices *fs_devices;
7074 int ret;
7075
David Sterbaa32bf9a2018-03-16 02:21:22 +01007076 lockdep_assert_held(&uuid_mutex);
David Sterba2dfeca92017-06-14 02:48:07 +02007077 ASSERT(fsid);
Yan Zheng2b820322008-11-17 21:11:30 -05007078
Nikolay Borisov427c8fd2020-08-12 17:04:36 +03007079 /* This will match only for multi-device seed fs */
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007080 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
Anand Jain44880fd2017-07-29 17:50:09 +08007081 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
Miao Xie5f375832014-09-03 21:35:46 +08007082 return fs_devices;
7083
Yan Zheng2b820322008-11-17 21:11:30 -05007084
Nikolay Borisov7239ff42018-10-30 16:43:23 +02007085 fs_devices = find_fsid(fsid, NULL);
Yan Zheng2b820322008-11-17 21:11:30 -05007086 if (!fs_devices) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007087 if (!btrfs_test_opt(fs_info, DEGRADED))
Miao Xie5f375832014-09-03 21:35:46 +08007088 return ERR_PTR(-ENOENT);
7089
Nikolay Borisov7239ff42018-10-30 16:43:23 +02007090 fs_devices = alloc_fs_devices(fsid, NULL);
Miao Xie5f375832014-09-03 21:35:46 +08007091 if (IS_ERR(fs_devices))
7092 return fs_devices;
7093
Johannes Thumshirn0395d842019-11-13 11:27:27 +01007094 fs_devices->seeding = true;
Miao Xie5f375832014-09-03 21:35:46 +08007095 fs_devices->opened = 1;
7096 return fs_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05007097 }
Yan Zhenge4404d62008-12-12 10:03:26 -05007098
Nikolay Borisov427c8fd2020-08-12 17:04:36 +03007099 /*
7100 * Upon first call for a seed fs fsid, just create a private copy of the
7101 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7102 */
Yan Zhenge4404d62008-12-12 10:03:26 -05007103 fs_devices = clone_fs_devices(fs_devices);
Miao Xie5f375832014-09-03 21:35:46 +08007104 if (IS_ERR(fs_devices))
7105 return fs_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05007106
Anand Jain897fb572018-04-12 10:29:28 +08007107 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
Julia Lawall48d28232012-04-14 11:24:33 +02007108 if (ret) {
7109 free_fs_devices(fs_devices);
Anand Jainc83b60c2020-09-05 01:34:35 +08007110 return ERR_PTR(ret);
Julia Lawall48d28232012-04-14 11:24:33 +02007111 }
Yan Zheng2b820322008-11-17 21:11:30 -05007112
7113 if (!fs_devices->seeding) {
Anand Jain0226e0e2018-04-12 10:29:27 +08007114 close_fs_devices(fs_devices);
Yan Zhenge4404d62008-12-12 10:03:26 -05007115 free_fs_devices(fs_devices);
Anand Jainc83b60c2020-09-05 01:34:35 +08007116 return ERR_PTR(-EINVAL);
Yan Zheng2b820322008-11-17 21:11:30 -05007117 }
7118
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007119 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
Anand Jainc83b60c2020-09-05 01:34:35 +08007120
Miao Xie5f375832014-09-03 21:35:46 +08007121 return fs_devices;
Yan Zheng2b820322008-11-17 21:11:30 -05007122}
7123
David Sterba17850752019-03-20 16:45:15 +01007124static int read_one_dev(struct extent_buffer *leaf,
Chris Mason0b86a832008-03-24 15:01:56 -04007125 struct btrfs_dev_item *dev_item)
7126{
David Sterba17850752019-03-20 16:45:15 +01007127 struct btrfs_fs_info *fs_info = leaf->fs_info;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007128 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Chris Mason0b86a832008-03-24 15:01:56 -04007129 struct btrfs_device *device;
7130 u64 devid;
7131 int ret;
Anand Jain44880fd2017-07-29 17:50:09 +08007132 u8 fs_uuid[BTRFS_FSID_SIZE];
Chris Masona4437552008-04-18 10:29:38 -04007133 u8 dev_uuid[BTRFS_UUID_SIZE];
7134
Chris Mason0b86a832008-03-24 15:01:56 -04007135 devid = btrfs_device_id(leaf, dev_item);
Geert Uytterhoeven410ba3a2013-08-20 13:20:11 +02007136 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
Chris Masona4437552008-04-18 10:29:38 -04007137 BTRFS_UUID_SIZE);
Geert Uytterhoeven1473b242013-08-20 13:20:12 +02007138 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
Anand Jain44880fd2017-07-29 17:50:09 +08007139 BTRFS_FSID_SIZE);
Yan Zheng2b820322008-11-17 21:11:30 -05007140
Nikolay Borisovde37aa52018-10-30 16:43:24 +02007141 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04007142 fs_devices = open_seed_devices(fs_info, fs_uuid);
Miao Xie5f375832014-09-03 21:35:46 +08007143 if (IS_ERR(fs_devices))
7144 return PTR_ERR(fs_devices);
Yan Zheng2b820322008-11-17 21:11:30 -05007145 }
7146
Anand Jaine4319cd2019-01-17 23:32:31 +08007147 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
Anand Jainb2598ed2020-11-03 13:49:43 +08007148 fs_uuid);
Miao Xie5f375832014-09-03 21:35:46 +08007149 if (!device) {
Qu Wenruoc5502452017-03-09 09:34:42 +08007150 if (!btrfs_test_opt(fs_info, DEGRADED)) {
Anand Jain2b902df2017-10-09 11:07:46 +08007151 btrfs_report_missing_device(fs_info, devid,
7152 dev_uuid, true);
Anand Jain45dbdbc2017-10-09 11:07:44 +08007153 return -ENOENT;
Qu Wenruoc5502452017-03-09 09:34:42 +08007154 }
Yan Zheng2b820322008-11-17 21:11:30 -05007155
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04007156 device = add_missing_dev(fs_devices, devid, dev_uuid);
Anand Jainadfb69a2017-10-11 12:46:18 +08007157 if (IS_ERR(device)) {
7158 btrfs_err(fs_info,
7159 "failed to add missing dev %llu: %ld",
7160 devid, PTR_ERR(device));
7161 return PTR_ERR(device);
7162 }
Anand Jain2b902df2017-10-09 11:07:46 +08007163 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
Miao Xie5f375832014-09-03 21:35:46 +08007164 } else {
Qu Wenruoc5502452017-03-09 09:34:42 +08007165 if (!device->bdev) {
Anand Jain2b902df2017-10-09 11:07:46 +08007166 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7167 btrfs_report_missing_device(fs_info,
7168 devid, dev_uuid, true);
Anand Jain45dbdbc2017-10-09 11:07:44 +08007169 return -ENOENT;
Anand Jain2b902df2017-10-09 11:07:46 +08007170 }
7171 btrfs_report_missing_device(fs_info, devid,
7172 dev_uuid, false);
Qu Wenruoc5502452017-03-09 09:34:42 +08007173 }
Miao Xie5f375832014-09-03 21:35:46 +08007174
Anand Jaine6e674b2017-12-04 12:54:54 +08007175 if (!device->bdev &&
7176 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
Chris Masoncd02dca2010-12-13 14:56:23 -05007177 /*
7178 * this happens when a device that was properly setup
7179 * in the device info lists suddenly goes bad.
7180 * device->bdev is NULL, and so we have to set
7181 * device->missing to one here
7182 */
Miao Xie5f375832014-09-03 21:35:46 +08007183 device->fs_devices->missing_devices++;
Anand Jaine6e674b2017-12-04 12:54:54 +08007184 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
Yan Zheng2b820322008-11-17 21:11:30 -05007185 }
Miao Xie5f375832014-09-03 21:35:46 +08007186
7187 /* Move the device to its own fs_devices */
7188 if (device->fs_devices != fs_devices) {
Anand Jaine6e674b2017-12-04 12:54:54 +08007189 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7190 &device->dev_state));
Miao Xie5f375832014-09-03 21:35:46 +08007191
7192 list_move(&device->dev_list, &fs_devices->devices);
7193 device->fs_devices->num_devices--;
7194 fs_devices->num_devices++;
7195
7196 device->fs_devices->missing_devices--;
7197 fs_devices->missing_devices++;
7198
7199 device->fs_devices = fs_devices;
7200 }
Yan Zheng2b820322008-11-17 21:11:30 -05007201 }
7202
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007203 if (device->fs_devices != fs_info->fs_devices) {
Anand Jainebbede42017-12-04 12:54:52 +08007204 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
Yan Zheng2b820322008-11-17 21:11:30 -05007205 if (device->generation !=
7206 btrfs_device_generation(leaf, dev_item))
7207 return -EINVAL;
Chris Mason6324fbf2008-03-24 15:01:59 -04007208 }
Chris Mason0b86a832008-03-24 15:01:56 -04007209
7210 fill_device_from_item(leaf, dev_item, device);
Anand Jain3a160a92020-11-03 13:49:42 +08007211 if (device->bdev) {
7212 u64 max_total_bytes = i_size_read(device->bdev->bd_inode);
7213
7214 if (device->total_bytes > max_total_bytes) {
7215 btrfs_err(fs_info,
7216 "device total_bytes should be at most %llu but found %llu",
7217 max_total_bytes, device->total_bytes);
7218 return -EINVAL;
7219 }
7220 }
Anand Jaine12c9622017-12-04 12:54:53 +08007221 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
Anand Jainebbede42017-12-04 12:54:52 +08007222 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
Anand Jain401e29c2017-12-04 12:54:55 +08007223 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
Yan Zheng2b820322008-11-17 21:11:30 -05007224 device->fs_devices->total_rw_bytes += device->total_bytes;
Nikolay Borisova5ed45f2017-05-11 09:17:46 +03007225 atomic64_add(device->total_bytes - device->bytes_used,
7226 &fs_info->free_chunk_space);
Josef Bacik2bf64752011-09-26 17:12:22 -04007227 }
Chris Mason0b86a832008-03-24 15:01:56 -04007228 ret = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04007229 return ret;
7230}
7231
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04007232int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
Chris Mason0b86a832008-03-24 15:01:56 -04007233{
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04007234 struct btrfs_root *root = fs_info->tree_root;
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04007235 struct btrfs_super_block *super_copy = fs_info->super_copy;
Chris Masona061fc82008-05-07 11:43:44 -04007236 struct extent_buffer *sb;
Chris Mason0b86a832008-03-24 15:01:56 -04007237 struct btrfs_disk_key *disk_key;
Chris Mason0b86a832008-03-24 15:01:56 -04007238 struct btrfs_chunk *chunk;
David Sterba1ffb22c2014-10-31 19:02:42 +01007239 u8 *array_ptr;
7240 unsigned long sb_array_offset;
Chris Mason84eed902008-04-25 09:04:37 -04007241 int ret = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04007242 u32 num_stripes;
7243 u32 array_size;
7244 u32 len = 0;
David Sterba1ffb22c2014-10-31 19:02:42 +01007245 u32 cur_offset;
Liu Boe06cd3d2016-06-03 12:05:15 -07007246 u64 type;
Chris Mason84eed902008-04-25 09:04:37 -04007247 struct btrfs_key key;
Chris Mason0b86a832008-03-24 15:01:56 -04007248
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007249 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
David Sterbaa83fffb2014-06-15 02:39:54 +02007250 /*
7251 * This will create extent buffer of nodesize, superblock size is
7252 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7253 * overallocate but we can keep it as-is, only the first page is used.
7254 */
Josef Bacik3fbaf252020-11-05 10:45:20 -05007255 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET,
7256 root->root_key.objectid, 0);
Liu Boc871b0f2016-06-06 12:01:23 -07007257 if (IS_ERR(sb))
7258 return PTR_ERR(sb);
David Sterba4db8c522015-12-03 13:06:46 +01007259 set_extent_buffer_uptodate(sb);
David Sterba8a334422011-10-07 18:06:13 +02007260 /*
Nicholas D Steeves01327612016-05-19 21:18:45 -04007261 * The sb extent buffer is artificial and just used to read the system array.
David Sterba4db8c522015-12-03 13:06:46 +01007262 * set_extent_buffer_uptodate() call does not properly mark all it's
David Sterba8a334422011-10-07 18:06:13 +02007263 * pages up-to-date when the page is larger: extent does not cover the
7264 * whole page and consequently check_page_uptodate does not find all
7265 * the page's extents up-to-date (the hole beyond sb),
7266 * write_extent_buffer then triggers a WARN_ON.
7267 *
7268 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7269 * but sb spans only this function. Add an explicit SetPageUptodate call
7270 * to silence the warning eg. on PowerPC 64.
7271 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03007272 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
Chris Mason727011e2010-08-06 13:21:20 -04007273 SetPageUptodate(sb->pages[0]);
Chris Mason4008c042009-02-12 14:09:45 -05007274
Chris Masona061fc82008-05-07 11:43:44 -04007275 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
Chris Mason0b86a832008-03-24 15:01:56 -04007276 array_size = btrfs_super_sys_array_size(super_copy);
7277
David Sterba1ffb22c2014-10-31 19:02:42 +01007278 array_ptr = super_copy->sys_chunk_array;
7279 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7280 cur_offset = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04007281
David Sterba1ffb22c2014-10-31 19:02:42 +01007282 while (cur_offset < array_size) {
7283 disk_key = (struct btrfs_disk_key *)array_ptr;
David Sterbae3540ea2014-11-05 15:24:51 +01007284 len = sizeof(*disk_key);
7285 if (cur_offset + len > array_size)
7286 goto out_short_read;
7287
Chris Mason0b86a832008-03-24 15:01:56 -04007288 btrfs_disk_key_to_cpu(&key, disk_key);
7289
David Sterba1ffb22c2014-10-31 19:02:42 +01007290 array_ptr += len;
7291 sb_array_offset += len;
7292 cur_offset += len;
Chris Mason0b86a832008-03-24 15:01:56 -04007293
Johannes Thumshirn32ab3d12019-10-18 11:58:23 +02007294 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04007295 btrfs_err(fs_info,
7296 "unexpected item type %u in sys_array at offset %u",
7297 (u32)key.type, cur_offset);
Chris Mason84eed902008-04-25 09:04:37 -04007298 ret = -EIO;
7299 break;
Chris Mason0b86a832008-03-24 15:01:56 -04007300 }
Johannes Thumshirn32ab3d12019-10-18 11:58:23 +02007301
7302 chunk = (struct btrfs_chunk *)sb_array_offset;
7303 /*
7304 * At least one btrfs_chunk with one stripe must be present,
7305 * exact stripe count check comes afterwards
7306 */
7307 len = btrfs_chunk_item_size(1);
7308 if (cur_offset + len > array_size)
7309 goto out_short_read;
7310
7311 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7312 if (!num_stripes) {
7313 btrfs_err(fs_info,
7314 "invalid number of stripes %u in sys_array at offset %u",
7315 num_stripes, cur_offset);
7316 ret = -EIO;
7317 break;
7318 }
7319
7320 type = btrfs_chunk_type(sb, chunk);
7321 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7322 btrfs_err(fs_info,
7323 "invalid chunk type %llu in sys_array at offset %u",
7324 type, cur_offset);
7325 ret = -EIO;
7326 break;
7327 }
7328
7329 len = btrfs_chunk_item_size(num_stripes);
7330 if (cur_offset + len > array_size)
7331 goto out_short_read;
7332
7333 ret = read_one_chunk(&key, sb, chunk);
7334 if (ret)
7335 break;
7336
David Sterba1ffb22c2014-10-31 19:02:42 +01007337 array_ptr += len;
7338 sb_array_offset += len;
7339 cur_offset += len;
Chris Mason0b86a832008-03-24 15:01:56 -04007340 }
Liu Bod8651772016-06-03 17:41:42 -07007341 clear_extent_buffer_uptodate(sb);
Liu Bo1c8b5b62016-05-13 17:06:59 -07007342 free_extent_buffer_stale(sb);
Chris Mason84eed902008-04-25 09:04:37 -04007343 return ret;
David Sterbae3540ea2014-11-05 15:24:51 +01007344
7345out_short_read:
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04007346 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
David Sterbae3540ea2014-11-05 15:24:51 +01007347 len, cur_offset);
Liu Bod8651772016-06-03 17:41:42 -07007348 clear_extent_buffer_uptodate(sb);
Liu Bo1c8b5b62016-05-13 17:06:59 -07007349 free_extent_buffer_stale(sb);
David Sterbae3540ea2014-11-05 15:24:51 +01007350 return -EIO;
Chris Mason0b86a832008-03-24 15:01:56 -04007351}
7352
Qu Wenruo21634a12017-03-09 09:34:36 +08007353/*
7354 * Check if all chunks in the fs are OK for read-write degraded mount
7355 *
Anand Jain6528b992017-12-18 17:08:59 +08007356 * If the @failing_dev is specified, it's accounted as missing.
7357 *
Qu Wenruo21634a12017-03-09 09:34:36 +08007358 * Return true if all chunks meet the minimal RW mount requirements.
7359 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7360 */
Anand Jain6528b992017-12-18 17:08:59 +08007361bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7362 struct btrfs_device *failing_dev)
Qu Wenruo21634a12017-03-09 09:34:36 +08007363{
David Sterbac8bf1b62019-05-17 11:43:17 +02007364 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
Qu Wenruo21634a12017-03-09 09:34:36 +08007365 struct extent_map *em;
7366 u64 next_start = 0;
7367 bool ret = true;
7368
David Sterbac8bf1b62019-05-17 11:43:17 +02007369 read_lock(&map_tree->lock);
7370 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7371 read_unlock(&map_tree->lock);
Qu Wenruo21634a12017-03-09 09:34:36 +08007372 /* No chunk at all? Return false anyway */
7373 if (!em) {
7374 ret = false;
7375 goto out;
7376 }
7377 while (em) {
7378 struct map_lookup *map;
7379 int missing = 0;
7380 int max_tolerated;
7381 int i;
7382
7383 map = em->map_lookup;
7384 max_tolerated =
7385 btrfs_get_num_tolerated_disk_barrier_failures(
7386 map->type);
7387 for (i = 0; i < map->num_stripes; i++) {
7388 struct btrfs_device *dev = map->stripes[i].dev;
7389
Anand Jaine6e674b2017-12-04 12:54:54 +08007390 if (!dev || !dev->bdev ||
7391 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
Qu Wenruo21634a12017-03-09 09:34:36 +08007392 dev->last_flush_error)
7393 missing++;
Anand Jain6528b992017-12-18 17:08:59 +08007394 else if (failing_dev && failing_dev == dev)
7395 missing++;
Qu Wenruo21634a12017-03-09 09:34:36 +08007396 }
7397 if (missing > max_tolerated) {
Anand Jain6528b992017-12-18 17:08:59 +08007398 if (!failing_dev)
7399 btrfs_warn(fs_info,
Andrea Gelmini52042d82018-11-28 12:05:13 +01007400 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
Qu Wenruo21634a12017-03-09 09:34:36 +08007401 em->start, missing, max_tolerated);
7402 free_extent_map(em);
7403 ret = false;
7404 goto out;
7405 }
7406 next_start = extent_map_end(em);
7407 free_extent_map(em);
7408
David Sterbac8bf1b62019-05-17 11:43:17 +02007409 read_lock(&map_tree->lock);
7410 em = lookup_extent_mapping(map_tree, next_start,
Qu Wenruo21634a12017-03-09 09:34:36 +08007411 (u64)(-1) - next_start);
David Sterbac8bf1b62019-05-17 11:43:17 +02007412 read_unlock(&map_tree->lock);
Qu Wenruo21634a12017-03-09 09:34:36 +08007413 }
7414out:
7415 return ret;
7416}
7417
David Sterbad85327b12020-07-08 22:55:14 +02007418static void readahead_tree_node_children(struct extent_buffer *node)
7419{
7420 int i;
7421 const int nr_items = btrfs_header_nritems(node);
7422
Josef Bacikbfb484d2020-11-05 10:45:09 -05007423 for (i = 0; i < nr_items; i++)
7424 btrfs_readahead_node_child(node, i);
David Sterbad85327b12020-07-08 22:55:14 +02007425}
7426
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04007427int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
Chris Mason0b86a832008-03-24 15:01:56 -04007428{
Jeff Mahoney5b4aace2016-06-21 10:40:19 -04007429 struct btrfs_root *root = fs_info->chunk_root;
Chris Mason0b86a832008-03-24 15:01:56 -04007430 struct btrfs_path *path;
7431 struct extent_buffer *leaf;
7432 struct btrfs_key key;
7433 struct btrfs_key found_key;
7434 int ret;
7435 int slot;
Liu Bo99e3ecf2016-06-03 12:05:14 -07007436 u64 total_dev = 0;
David Sterbad85327b12020-07-08 22:55:14 +02007437 u64 last_ra_node = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04007438
Chris Mason0b86a832008-03-24 15:01:56 -04007439 path = btrfs_alloc_path();
7440 if (!path)
7441 return -ENOMEM;
7442
Anand Jain3dd0f7a2018-04-12 10:29:32 +08007443 /*
7444 * uuid_mutex is needed only if we are mounting a sprout FS
7445 * otherwise we don't need it.
7446 */
Li Zefanb367e472011-12-07 11:38:24 +08007447 mutex_lock(&uuid_mutex);
Li Zefanb367e472011-12-07 11:38:24 +08007448
Filipe David Borba Manana395927a2013-07-30 12:03:04 +01007449 /*
Boris Burkov48cfa612020-07-16 13:29:46 -07007450 * It is possible for mount and umount to race in such a way that
7451 * we execute this code path, but open_fs_devices failed to clear
7452 * total_rw_bytes. We certainly want it cleared before reading the
7453 * device items, so clear it here.
7454 */
7455 fs_info->fs_devices->total_rw_bytes = 0;
7456
7457 /*
Filipe David Borba Manana395927a2013-07-30 12:03:04 +01007458 * Read all device items, and then all the chunk items. All
7459 * device items are found before any chunk item (their object id
7460 * is smaller than the lowest possible object id for a chunk
7461 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
Chris Mason0b86a832008-03-24 15:01:56 -04007462 */
7463 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7464 key.offset = 0;
7465 key.type = 0;
Chris Mason0b86a832008-03-24 15:01:56 -04007466 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
Zhao Leiab593812010-03-25 12:34:49 +00007467 if (ret < 0)
7468 goto error;
Chris Masond3977122009-01-05 21:25:51 -05007469 while (1) {
David Sterbad85327b12020-07-08 22:55:14 +02007470 struct extent_buffer *node;
7471
Chris Mason0b86a832008-03-24 15:01:56 -04007472 leaf = path->nodes[0];
7473 slot = path->slots[0];
7474 if (slot >= btrfs_header_nritems(leaf)) {
7475 ret = btrfs_next_leaf(root, path);
7476 if (ret == 0)
7477 continue;
7478 if (ret < 0)
7479 goto error;
7480 break;
7481 }
David Sterbad85327b12020-07-08 22:55:14 +02007482 /*
7483 * The nodes on level 1 are not locked but we don't need to do
7484 * that during mount time as nothing else can access the tree
7485 */
7486 node = path->nodes[1];
7487 if (node) {
7488 if (last_ra_node != node->start) {
7489 readahead_tree_node_children(node);
7490 last_ra_node = node->start;
7491 }
7492 }
Chris Mason0b86a832008-03-24 15:01:56 -04007493 btrfs_item_key_to_cpu(leaf, &found_key, slot);
Filipe David Borba Manana395927a2013-07-30 12:03:04 +01007494 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7495 struct btrfs_dev_item *dev_item;
7496 dev_item = btrfs_item_ptr(leaf, slot,
Chris Mason0b86a832008-03-24 15:01:56 -04007497 struct btrfs_dev_item);
David Sterba17850752019-03-20 16:45:15 +01007498 ret = read_one_dev(leaf, dev_item);
Filipe David Borba Manana395927a2013-07-30 12:03:04 +01007499 if (ret)
7500 goto error;
Liu Bo99e3ecf2016-06-03 12:05:14 -07007501 total_dev++;
Chris Mason0b86a832008-03-24 15:01:56 -04007502 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7503 struct btrfs_chunk *chunk;
Filipe Manana79bd3712021-06-29 14:43:06 +01007504
7505 /*
7506 * We are only called at mount time, so no need to take
7507 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7508 * we always lock first fs_info->chunk_mutex before
7509 * acquiring any locks on the chunk tree. This is a
7510 * requirement for chunk allocation, see the comment on
7511 * top of btrfs_chunk_alloc() for details.
7512 */
7513 ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
Chris Mason0b86a832008-03-24 15:01:56 -04007514 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
David Sterba9690ac02019-03-20 16:43:07 +01007515 ret = read_one_chunk(&found_key, leaf, chunk);
Yan Zheng2b820322008-11-17 21:11:30 -05007516 if (ret)
7517 goto error;
Chris Mason0b86a832008-03-24 15:01:56 -04007518 }
7519 path->slots[0]++;
7520 }
Liu Bo99e3ecf2016-06-03 12:05:14 -07007521
7522 /*
7523 * After loading chunk tree, we've got all device information,
7524 * do another round of validation checks.
7525 */
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007526 if (total_dev != fs_info->fs_devices->total_devices) {
7527 btrfs_err(fs_info,
Liu Bo99e3ecf2016-06-03 12:05:14 -07007528 "super_num_devices %llu mismatch with num_devices %llu found here",
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007529 btrfs_super_num_devices(fs_info->super_copy),
Liu Bo99e3ecf2016-06-03 12:05:14 -07007530 total_dev);
7531 ret = -EINVAL;
7532 goto error;
7533 }
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007534 if (btrfs_super_total_bytes(fs_info->super_copy) <
7535 fs_info->fs_devices->total_rw_bytes) {
7536 btrfs_err(fs_info,
Liu Bo99e3ecf2016-06-03 12:05:14 -07007537 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007538 btrfs_super_total_bytes(fs_info->super_copy),
7539 fs_info->fs_devices->total_rw_bytes);
Liu Bo99e3ecf2016-06-03 12:05:14 -07007540 ret = -EINVAL;
7541 goto error;
7542 }
Chris Mason0b86a832008-03-24 15:01:56 -04007543 ret = 0;
7544error:
Li Zefanb367e472011-12-07 11:38:24 +08007545 mutex_unlock(&uuid_mutex);
7546
Yan Zheng2b820322008-11-17 21:11:30 -05007547 btrfs_free_path(path);
Chris Mason0b86a832008-03-24 15:01:56 -04007548 return ret;
7549}
Stefan Behrens442a4f62012-05-25 16:06:08 +02007550
Miao Xiecb517ea2013-05-15 07:48:19 +00007551void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7552{
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007553 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
Miao Xiecb517ea2013-05-15 07:48:19 +00007554 struct btrfs_device *device;
7555
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007556 fs_devices->fs_info = fs_info;
Liu Bo29cc83f2014-05-11 23:14:59 +08007557
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007558 mutex_lock(&fs_devices->device_list_mutex);
7559 list_for_each_entry(device, &fs_devices->devices, dev_list)
7560 device->fs_info = fs_info;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007561
7562 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007563 list_for_each_entry(device, &seed_devs->devices, dev_list)
7564 device->fs_info = fs_info;
Nikolay Borisov944d3f92020-07-16 10:25:33 +03007565
7566 seed_devs->fs_info = fs_info;
Liu Bo29cc83f2014-05-11 23:14:59 +08007567 }
Anand Jaine17125b2020-09-05 01:34:31 +08007568 mutex_unlock(&fs_devices->device_list_mutex);
Miao Xiecb517ea2013-05-15 07:48:19 +00007569}
7570
David Sterba1dc990d2019-08-21 20:05:32 +02007571static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7572 const struct btrfs_dev_stats_item *ptr,
7573 int index)
7574{
7575 u64 val;
7576
7577 read_extent_buffer(eb, &val,
7578 offsetof(struct btrfs_dev_stats_item, values) +
7579 ((unsigned long)ptr) + (index * sizeof(u64)),
7580 sizeof(val));
7581 return val;
7582}
7583
7584static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7585 struct btrfs_dev_stats_item *ptr,
7586 int index, u64 val)
7587{
7588 write_extent_buffer(eb, &val,
7589 offsetof(struct btrfs_dev_stats_item, values) +
7590 ((unsigned long)ptr) + (index * sizeof(u64)),
7591 sizeof(val));
7592}
7593
Josef Bacik92e26df2020-09-18 16:44:33 -04007594static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7595 struct btrfs_path *path)
Josef Bacik124604e2020-09-18 16:44:32 -04007596{
7597 struct btrfs_dev_stats_item *ptr;
7598 struct extent_buffer *eb;
7599 struct btrfs_key key;
7600 int item_size;
7601 int i, ret, slot;
7602
Josef Bacik82d62d02021-03-11 11:23:15 -05007603 if (!device->fs_info->dev_root)
7604 return 0;
7605
Josef Bacik124604e2020-09-18 16:44:32 -04007606 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7607 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7608 key.offset = device->devid;
7609 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7610 if (ret) {
7611 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7612 btrfs_dev_stat_set(device, i, 0);
7613 device->dev_stats_valid = 1;
7614 btrfs_release_path(path);
Josef Bacik92e26df2020-09-18 16:44:33 -04007615 return ret < 0 ? ret : 0;
Josef Bacik124604e2020-09-18 16:44:32 -04007616 }
7617 slot = path->slots[0];
7618 eb = path->nodes[0];
7619 item_size = btrfs_item_size_nr(eb, slot);
7620
7621 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7622
7623 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7624 if (item_size >= (1 + i) * sizeof(__le64))
7625 btrfs_dev_stat_set(device, i,
7626 btrfs_dev_stats_value(eb, ptr, i));
7627 else
7628 btrfs_dev_stat_set(device, i, 0);
7629 }
7630
7631 device->dev_stats_valid = 1;
7632 btrfs_dev_stat_print_on_load(device);
7633 btrfs_release_path(path);
Josef Bacik92e26df2020-09-18 16:44:33 -04007634
7635 return 0;
Josef Bacik124604e2020-09-18 16:44:32 -04007636}
7637
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007638int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7639{
Josef Bacik124604e2020-09-18 16:44:32 -04007640 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007641 struct btrfs_device *device;
7642 struct btrfs_path *path = NULL;
Josef Bacik92e26df2020-09-18 16:44:33 -04007643 int ret = 0;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007644
7645 path = btrfs_alloc_path();
Anand Jain3b80a9842019-08-21 17:26:32 +08007646 if (!path)
7647 return -ENOMEM;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007648
7649 mutex_lock(&fs_devices->device_list_mutex);
Josef Bacik92e26df2020-09-18 16:44:33 -04007650 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7651 ret = btrfs_device_init_dev_stats(device, path);
7652 if (ret)
7653 goto out;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007654 }
Josef Bacik92e26df2020-09-18 16:44:33 -04007655 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7656 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7657 ret = btrfs_device_init_dev_stats(device, path);
7658 if (ret)
7659 goto out;
7660 }
7661 }
7662out:
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007663 mutex_unlock(&fs_devices->device_list_mutex);
7664
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007665 btrfs_free_path(path);
Josef Bacik92e26df2020-09-18 16:44:33 -04007666 return ret;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007667}
7668
7669static int update_dev_stat_item(struct btrfs_trans_handle *trans,
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007670 struct btrfs_device *device)
7671{
Nikolay Borisov5495f192018-07-20 19:37:49 +03007672 struct btrfs_fs_info *fs_info = trans->fs_info;
Jeff Mahoney6bccf3a2016-06-21 21:16:51 -04007673 struct btrfs_root *dev_root = fs_info->dev_root;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007674 struct btrfs_path *path;
7675 struct btrfs_key key;
7676 struct extent_buffer *eb;
7677 struct btrfs_dev_stats_item *ptr;
7678 int ret;
7679 int i;
7680
David Sterba242e2952016-01-25 17:51:31 +01007681 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7682 key.type = BTRFS_PERSISTENT_ITEM_KEY;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007683 key.offset = device->devid;
7684
7685 path = btrfs_alloc_path();
David Sterbafa252992017-02-15 09:35:01 +01007686 if (!path)
7687 return -ENOMEM;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007688 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7689 if (ret < 0) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007690 btrfs_warn_in_rcu(fs_info,
David Sterbaecaeb142015-10-08 09:01:03 +02007691 "error %d while searching for dev_stats item for device %s",
Josef Bacik606686e2012-06-04 14:03:51 -04007692 ret, rcu_str_deref(device->name));
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007693 goto out;
7694 }
7695
7696 if (ret == 0 &&
7697 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7698 /* need to delete old one and insert a new one */
7699 ret = btrfs_del_item(trans, dev_root, path);
7700 if (ret != 0) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007701 btrfs_warn_in_rcu(fs_info,
David Sterbaecaeb142015-10-08 09:01:03 +02007702 "delete too small dev_stats item for device %s failed %d",
Josef Bacik606686e2012-06-04 14:03:51 -04007703 rcu_str_deref(device->name), ret);
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007704 goto out;
7705 }
7706 ret = 1;
7707 }
7708
7709 if (ret == 1) {
7710 /* need to insert a new item */
7711 btrfs_release_path(path);
7712 ret = btrfs_insert_empty_item(trans, dev_root, path,
7713 &key, sizeof(*ptr));
7714 if (ret < 0) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007715 btrfs_warn_in_rcu(fs_info,
David Sterbaecaeb142015-10-08 09:01:03 +02007716 "insert dev_stats item for device %s failed %d",
7717 rcu_str_deref(device->name), ret);
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007718 goto out;
7719 }
7720 }
7721
7722 eb = path->nodes[0];
7723 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7724 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7725 btrfs_set_dev_stats_value(eb, ptr, i,
7726 btrfs_dev_stat_read(device, i));
7727 btrfs_mark_buffer_dirty(eb);
7728
7729out:
7730 btrfs_free_path(path);
7731 return ret;
7732}
7733
7734/*
7735 * called from commit_transaction. Writes all changed device stats to disk.
7736 */
David Sterba196c9d82019-03-20 16:50:38 +01007737int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007738{
David Sterba196c9d82019-03-20 16:50:38 +01007739 struct btrfs_fs_info *fs_info = trans->fs_info;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007740 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7741 struct btrfs_device *device;
Miao Xieaddc3fa2014-07-24 11:37:11 +08007742 int stats_cnt;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007743 int ret = 0;
7744
7745 mutex_lock(&fs_devices->device_list_mutex);
7746 list_for_each_entry(device, &fs_devices->devices, dev_list) {
Nikolay Borisov9deae962017-10-24 13:47:37 +03007747 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7748 if (!device->dev_stats_valid || stats_cnt == 0)
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007749 continue;
7750
Nikolay Borisov9deae962017-10-24 13:47:37 +03007751
7752 /*
7753 * There is a LOAD-LOAD control dependency between the value of
7754 * dev_stats_ccnt and updating the on-disk values which requires
7755 * reading the in-memory counters. Such control dependencies
7756 * require explicit read memory barriers.
7757 *
7758 * This memory barriers pairs with smp_mb__before_atomic in
7759 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7760 * barrier implied by atomic_xchg in
7761 * btrfs_dev_stats_read_and_reset
7762 */
7763 smp_rmb();
7764
Nikolay Borisov5495f192018-07-20 19:37:49 +03007765 ret = update_dev_stat_item(trans, device);
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007766 if (!ret)
Miao Xieaddc3fa2014-07-24 11:37:11 +08007767 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007768 }
7769 mutex_unlock(&fs_devices->device_list_mutex);
7770
7771 return ret;
7772}
7773
Stefan Behrens442a4f62012-05-25 16:06:08 +02007774void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7775{
7776 btrfs_dev_stat_inc(dev, index);
7777 btrfs_dev_stat_print_on_error(dev);
7778}
7779
Eric Sandeen48a3b632013-04-25 20:41:01 +00007780static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
Stefan Behrens442a4f62012-05-25 16:06:08 +02007781{
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007782 if (!dev->dev_stats_valid)
7783 return;
Jeff Mahoneyfb456252016-06-22 18:54:56 -04007784 btrfs_err_rl_in_rcu(dev->fs_info,
David Sterbab14af3b2015-10-08 10:43:10 +02007785 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
Josef Bacik606686e2012-06-04 14:03:51 -04007786 rcu_str_deref(dev->name),
Stefan Behrens442a4f62012-05-25 16:06:08 +02007787 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7788 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7789 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
Frank Holtonefe120a2013-12-20 11:37:06 -05007790 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7791 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
Stefan Behrens442a4f62012-05-25 16:06:08 +02007792}
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007793
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007794static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7795{
Stefan Behrensa98cdb82012-07-17 09:02:11 -06007796 int i;
7797
7798 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7799 if (btrfs_dev_stat_read(dev, i) != 0)
7800 break;
7801 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7802 return; /* all values == 0, suppress message */
7803
Jeff Mahoneyfb456252016-06-22 18:54:56 -04007804 btrfs_info_in_rcu(dev->fs_info,
David Sterbaecaeb142015-10-08 09:01:03 +02007805 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
Josef Bacik606686e2012-06-04 14:03:51 -04007806 rcu_str_deref(dev->name),
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007807 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7808 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7809 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7810 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7811 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7812}
7813
Jeff Mahoney2ff7e612016-06-22 18:54:24 -04007814int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
David Sterbab27f7c02012-06-22 06:30:39 -06007815 struct btrfs_ioctl_get_dev_stats *stats)
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007816{
7817 struct btrfs_device *dev;
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007818 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007819 int i;
7820
7821 mutex_lock(&fs_devices->device_list_mutex);
Anand Jainb2598ed2020-11-03 13:49:43 +08007822 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL);
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007823 mutex_unlock(&fs_devices->device_list_mutex);
7824
7825 if (!dev) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007826 btrfs_warn(fs_info, "get dev_stats failed, device not found");
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007827 return -ENODEV;
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007828 } else if (!dev->dev_stats_valid) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -04007829 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
Stefan Behrens733f4fb2012-05-25 16:06:10 +02007830 return -ENODEV;
David Sterbab27f7c02012-06-22 06:30:39 -06007831 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007832 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7833 if (stats->nr_items > i)
7834 stats->values[i] =
7835 btrfs_dev_stat_read_and_reset(dev, i);
7836 else
Anand Jain4e411a72019-08-07 16:21:19 +08007837 btrfs_dev_stat_set(dev, i, 0);
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007838 }
Anand Jaina69976b2020-01-10 12:26:34 +08007839 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7840 current->comm, task_pid_nr(current));
Stefan Behrensc11d2c22012-05-25 16:06:09 +02007841 } else {
7842 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7843 if (stats->nr_items > i)
7844 stats->values[i] = btrfs_dev_stat_read(dev, i);
7845 }
7846 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7847 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7848 return 0;
7849}
Stefan Behrensa8a6dab2012-11-05 15:50:14 +01007850
Miao Xie935e5cc2014-09-03 21:35:33 +08007851/*
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007852 * Update the size and bytes used for each device where it changed. This is
7853 * delayed since we would otherwise get errors while writing out the
7854 * superblocks.
7855 *
7856 * Must be invoked during transaction commit.
Miao Xie935e5cc2014-09-03 21:35:33 +08007857 */
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007858void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
Miao Xie935e5cc2014-09-03 21:35:33 +08007859{
Miao Xie935e5cc2014-09-03 21:35:33 +08007860 struct btrfs_device *curr, *next;
7861
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007862 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7863
7864 if (list_empty(&trans->dev_update_list))
Miao Xie935e5cc2014-09-03 21:35:33 +08007865 return;
7866
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007867 /*
7868 * We don't need the device_list_mutex here. This list is owned by the
7869 * transaction and the transaction must complete before the device is
7870 * released.
7871 */
7872 mutex_lock(&trans->fs_info->chunk_mutex);
7873 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7874 post_commit_list) {
7875 list_del_init(&curr->post_commit_list);
Miao Xie935e5cc2014-09-03 21:35:33 +08007876 curr->commit_total_bytes = curr->disk_total_bytes;
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007877 curr->commit_bytes_used = curr->bytes_used;
Miao Xie935e5cc2014-09-03 21:35:33 +08007878 }
Nikolay Borisovbbbf7242019-03-25 14:31:22 +02007879 mutex_unlock(&trans->fs_info->chunk_mutex);
Miao Xiece7213c2014-09-03 21:35:34 +08007880}
Anand Jain5a13f432015-03-10 06:38:31 +08007881
David Sterba46df06b2018-07-13 20:46:30 +02007882/*
7883 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7884 */
7885int btrfs_bg_type_to_factor(u64 flags)
7886{
David Sterba44b28ad2019-05-17 11:43:31 +02007887 const int index = btrfs_bg_flags_to_raid_index(flags);
7888
7889 return btrfs_raid_array[index].ncopies;
David Sterba46df06b2018-07-13 20:46:30 +02007890}
Qu Wenruocf90d882018-08-01 10:37:19 +08007891
7892
Qu Wenruocf90d882018-08-01 10:37:19 +08007893
7894static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7895 u64 chunk_offset, u64 devid,
7896 u64 physical_offset, u64 physical_len)
7897{
David Sterbac8bf1b62019-05-17 11:43:17 +02007898 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
Qu Wenruocf90d882018-08-01 10:37:19 +08007899 struct extent_map *em;
7900 struct map_lookup *map;
Qu Wenruo05a37c42018-10-05 17:45:55 +08007901 struct btrfs_device *dev;
Qu Wenruocf90d882018-08-01 10:37:19 +08007902 u64 stripe_len;
7903 bool found = false;
7904 int ret = 0;
7905 int i;
7906
7907 read_lock(&em_tree->lock);
7908 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7909 read_unlock(&em_tree->lock);
7910
7911 if (!em) {
7912 btrfs_err(fs_info,
7913"dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7914 physical_offset, devid);
7915 ret = -EUCLEAN;
7916 goto out;
7917 }
7918
7919 map = em->map_lookup;
7920 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7921 if (physical_len != stripe_len) {
7922 btrfs_err(fs_info,
7923"dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7924 physical_offset, devid, em->start, physical_len,
7925 stripe_len);
7926 ret = -EUCLEAN;
7927 goto out;
7928 }
7929
7930 for (i = 0; i < map->num_stripes; i++) {
7931 if (map->stripes[i].dev->devid == devid &&
7932 map->stripes[i].physical == physical_offset) {
7933 found = true;
7934 if (map->verified_stripes >= map->num_stripes) {
7935 btrfs_err(fs_info,
7936 "too many dev extents for chunk %llu found",
7937 em->start);
7938 ret = -EUCLEAN;
7939 goto out;
7940 }
7941 map->verified_stripes++;
7942 break;
7943 }
7944 }
7945 if (!found) {
7946 btrfs_err(fs_info,
7947 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7948 physical_offset, devid);
7949 ret = -EUCLEAN;
7950 }
Qu Wenruo05a37c42018-10-05 17:45:55 +08007951
David Sterba1a9fd412021-05-21 17:42:23 +02007952 /* Make sure no dev extent is beyond device boundary */
Anand Jainb2598ed2020-11-03 13:49:43 +08007953 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);
Qu Wenruo05a37c42018-10-05 17:45:55 +08007954 if (!dev) {
7955 btrfs_err(fs_info, "failed to find devid %llu", devid);
7956 ret = -EUCLEAN;
7957 goto out;
7958 }
Qu Wenruo1b3922a2019-01-08 14:08:18 +08007959
Qu Wenruo05a37c42018-10-05 17:45:55 +08007960 if (physical_offset + physical_len > dev->disk_total_bytes) {
7961 btrfs_err(fs_info,
7962"dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7963 devid, physical_offset, physical_len,
7964 dev->disk_total_bytes);
7965 ret = -EUCLEAN;
7966 goto out;
7967 }
Naohiro Aota381a6962021-02-04 19:21:49 +09007968
7969 if (dev->zone_info) {
7970 u64 zone_size = dev->zone_info->zone_size;
7971
7972 if (!IS_ALIGNED(physical_offset, zone_size) ||
7973 !IS_ALIGNED(physical_len, zone_size)) {
7974 btrfs_err(fs_info,
7975"zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
7976 devid, physical_offset, physical_len);
7977 ret = -EUCLEAN;
7978 goto out;
7979 }
7980 }
7981
Qu Wenruocf90d882018-08-01 10:37:19 +08007982out:
7983 free_extent_map(em);
7984 return ret;
7985}
7986
7987static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7988{
David Sterbac8bf1b62019-05-17 11:43:17 +02007989 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
Qu Wenruocf90d882018-08-01 10:37:19 +08007990 struct extent_map *em;
7991 struct rb_node *node;
7992 int ret = 0;
7993
7994 read_lock(&em_tree->lock);
Liu Bo07e1ce02018-08-23 03:51:52 +08007995 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
Qu Wenruocf90d882018-08-01 10:37:19 +08007996 em = rb_entry(node, struct extent_map, rb_node);
7997 if (em->map_lookup->num_stripes !=
7998 em->map_lookup->verified_stripes) {
7999 btrfs_err(fs_info,
8000 "chunk %llu has missing dev extent, have %d expect %d",
8001 em->start, em->map_lookup->verified_stripes,
8002 em->map_lookup->num_stripes);
8003 ret = -EUCLEAN;
8004 goto out;
8005 }
8006 }
8007out:
8008 read_unlock(&em_tree->lock);
8009 return ret;
8010}
8011
8012/*
8013 * Ensure that all dev extents are mapped to correct chunk, otherwise
8014 * later chunk allocation/free would cause unexpected behavior.
8015 *
8016 * NOTE: This will iterate through the whole device tree, which should be of
8017 * the same size level as the chunk tree. This slightly increases mount time.
8018 */
8019int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8020{
8021 struct btrfs_path *path;
8022 struct btrfs_root *root = fs_info->dev_root;
8023 struct btrfs_key key;
Qu Wenruo5eb19382018-10-05 17:45:54 +08008024 u64 prev_devid = 0;
8025 u64 prev_dev_ext_end = 0;
Qu Wenruocf90d882018-08-01 10:37:19 +08008026 int ret = 0;
8027
Josef Bacik42437a62020-10-16 11:29:18 -04008028 /*
8029 * We don't have a dev_root because we mounted with ignorebadroots and
8030 * failed to load the root, so we want to skip the verification in this
8031 * case for sure.
8032 *
8033 * However if the dev root is fine, but the tree itself is corrupted
8034 * we'd still fail to mount. This verification is only to make sure
8035 * writes can happen safely, so instead just bypass this check
8036 * completely in the case of IGNOREBADROOTS.
8037 */
8038 if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8039 return 0;
8040
Qu Wenruocf90d882018-08-01 10:37:19 +08008041 key.objectid = 1;
8042 key.type = BTRFS_DEV_EXTENT_KEY;
8043 key.offset = 0;
8044
8045 path = btrfs_alloc_path();
8046 if (!path)
8047 return -ENOMEM;
8048
8049 path->reada = READA_FORWARD;
8050 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8051 if (ret < 0)
8052 goto out;
8053
8054 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
Marcos Paulo de Souzaad9a9372021-07-13 10:58:03 -03008055 ret = btrfs_next_leaf(root, path);
Qu Wenruocf90d882018-08-01 10:37:19 +08008056 if (ret < 0)
8057 goto out;
8058 /* No dev extents at all? Not good */
8059 if (ret > 0) {
8060 ret = -EUCLEAN;
8061 goto out;
8062 }
8063 }
8064 while (1) {
8065 struct extent_buffer *leaf = path->nodes[0];
8066 struct btrfs_dev_extent *dext;
8067 int slot = path->slots[0];
8068 u64 chunk_offset;
8069 u64 physical_offset;
8070 u64 physical_len;
8071 u64 devid;
8072
8073 btrfs_item_key_to_cpu(leaf, &key, slot);
8074 if (key.type != BTRFS_DEV_EXTENT_KEY)
8075 break;
8076 devid = key.objectid;
8077 physical_offset = key.offset;
8078
8079 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8080 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8081 physical_len = btrfs_dev_extent_length(leaf, dext);
8082
Qu Wenruo5eb19382018-10-05 17:45:54 +08008083 /* Check if this dev extent overlaps with the previous one */
8084 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
8085 btrfs_err(fs_info,
8086"dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8087 devid, physical_offset, prev_dev_ext_end);
8088 ret = -EUCLEAN;
8089 goto out;
8090 }
8091
Qu Wenruocf90d882018-08-01 10:37:19 +08008092 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8093 physical_offset, physical_len);
8094 if (ret < 0)
8095 goto out;
Qu Wenruo5eb19382018-10-05 17:45:54 +08008096 prev_devid = devid;
8097 prev_dev_ext_end = physical_offset + physical_len;
8098
Qu Wenruocf90d882018-08-01 10:37:19 +08008099 ret = btrfs_next_item(root, path);
8100 if (ret < 0)
8101 goto out;
8102 if (ret > 0) {
8103 ret = 0;
8104 break;
8105 }
8106 }
8107
8108 /* Ensure all chunks have corresponding dev extents */
8109 ret = verify_chunk_dev_extent_mapping(fs_info);
8110out:
8111 btrfs_free_path(path);
8112 return ret;
8113}
Omar Sandovaleede2bf2016-11-03 10:28:12 -07008114
8115/*
8116 * Check whether the given block group or device is pinned by any inode being
8117 * used as a swapfile.
8118 */
8119bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8120{
8121 struct btrfs_swapfile_pin *sp;
8122 struct rb_node *node;
8123
8124 spin_lock(&fs_info->swapfile_pins_lock);
8125 node = fs_info->swapfile_pins.rb_node;
8126 while (node) {
8127 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8128 if (ptr < sp->ptr)
8129 node = node->rb_left;
8130 else if (ptr > sp->ptr)
8131 node = node->rb_right;
8132 else
8133 break;
8134 }
8135 spin_unlock(&fs_info->swapfile_pins_lock);
8136 return node != NULL;
8137}
Naohiro Aotaf7ef5282021-02-04 19:22:16 +09008138
8139static int relocating_repair_kthread(void *data)
8140{
8141 struct btrfs_block_group *cache = (struct btrfs_block_group *)data;
8142 struct btrfs_fs_info *fs_info = cache->fs_info;
8143 u64 target;
8144 int ret = 0;
8145
8146 target = cache->start;
8147 btrfs_put_block_group(cache);
8148
8149 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8150 btrfs_info(fs_info,
8151 "zoned: skip relocating block group %llu to repair: EBUSY",
8152 target);
8153 return -EBUSY;
8154 }
8155
Johannes Thumshirnf3372062021-04-19 16:41:01 +09008156 mutex_lock(&fs_info->reclaim_bgs_lock);
Naohiro Aotaf7ef5282021-02-04 19:22:16 +09008157
8158 /* Ensure block group still exists */
8159 cache = btrfs_lookup_block_group(fs_info, target);
8160 if (!cache)
8161 goto out;
8162
8163 if (!cache->relocating_repair)
8164 goto out;
8165
8166 ret = btrfs_may_alloc_data_chunk(fs_info, target);
8167 if (ret < 0)
8168 goto out;
8169
8170 btrfs_info(fs_info,
8171 "zoned: relocating block group %llu to repair IO failure",
8172 target);
8173 ret = btrfs_relocate_chunk(fs_info, target);
8174
8175out:
8176 if (cache)
8177 btrfs_put_block_group(cache);
Johannes Thumshirnf3372062021-04-19 16:41:01 +09008178 mutex_unlock(&fs_info->reclaim_bgs_lock);
Naohiro Aotaf7ef5282021-02-04 19:22:16 +09008179 btrfs_exclop_finish(fs_info);
8180
8181 return ret;
8182}
8183
8184int btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8185{
8186 struct btrfs_block_group *cache;
8187
8188 /* Do not attempt to repair in degraded state */
8189 if (btrfs_test_opt(fs_info, DEGRADED))
8190 return 0;
8191
8192 cache = btrfs_lookup_block_group(fs_info, logical);
8193 if (!cache)
8194 return 0;
8195
8196 spin_lock(&cache->lock);
8197 if (cache->relocating_repair) {
8198 spin_unlock(&cache->lock);
8199 btrfs_put_block_group(cache);
8200 return 0;
8201 }
8202 cache->relocating_repair = 1;
8203 spin_unlock(&cache->lock);
8204
8205 kthread_run(relocating_repair_kthread, cache,
8206 "btrfs-relocating-repair");
8207
8208 return 0;
8209}