1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2016, 2019 by Delphix. All rights reserved.
24  */
25 
26 #include <sys/spa.h>
27 #include <sys/spa_impl.h>
28 #include <sys/txg.h>
29 #include <sys/vdev_impl.h>
30 #include <sys/metaslab_impl.h>
31 #include <sys/dsl_synctask.h>
32 #include <sys/zap.h>
33 #include <sys/dmu_tx.h>
34 #include <sys/vdev_initialize.h>
35 
36 /*
37  * Value that is written to disk during initialization.
38  */
39 #ifdef _ILP32
40 unsigned long zfs_initialize_value = 0xdeadbeefUL;
41 #else
42 unsigned long zfs_initialize_value = 0xdeadbeefdeadbeeeULL;
43 #endif
44 
45 /* maximum number of I/Os outstanding per leaf vdev */
46 int zfs_initialize_limit = 1;
47 
48 /* size of initializing writes; default 1MiB, see zfs_remove_max_segment */
49 unsigned long zfs_initialize_chunk_size = 1024 * 1024;
50 
51 static boolean_t
52 vdev_initialize_should_stop(vdev_t *vd)
53 {
54 	return (vd->vdev_initialize_exit_wanted || !vdev_writeable(vd) ||
55 	    vd->vdev_detached || vd->vdev_top->vdev_removing);
56 }
57 
58 static void
59 vdev_initialize_zap_update_sync(void *arg, dmu_tx_t *tx)
60 {
61 	/*
62 	 * We pass in the guid instead of the vdev_t since the vdev may
63 	 * have been freed prior to the sync task being processed. This
64 	 * happens when a vdev is detached as we call spa_config_vdev_exit(),
65 	 * stop the initializing thread, schedule the sync task, and free
66 	 * the vdev. Later when the scheduled sync task is invoked, it would
67 	 * find that the vdev has been freed.
68 	 */
69 	uint64_t guid = *(uint64_t *)arg;
70 	uint64_t txg = dmu_tx_get_txg(tx);
71 	kmem_free(arg, sizeof (uint64_t));
72 
73 	vdev_t *vd = spa_lookup_by_guid(tx->tx_pool->dp_spa, guid, B_FALSE);
74 	if (vd == NULL || vd->vdev_top->vdev_removing || !vdev_is_concrete(vd))
75 		return;
76 
77 	uint64_t last_offset = vd->vdev_initialize_offset[txg & TXG_MASK];
78 	vd->vdev_initialize_offset[txg & TXG_MASK] = 0;
79 
80 	VERIFY(vd->vdev_leaf_zap != 0);
81 
82 	objset_t *mos = vd->vdev_spa->spa_meta_objset;
83 
84 	if (last_offset > 0) {
85 		vd->vdev_initialize_last_offset = last_offset;
86 		VERIFY0(zap_update(mos, vd->vdev_leaf_zap,
87 		    VDEV_LEAF_ZAP_INITIALIZE_LAST_OFFSET,
88 		    sizeof (last_offset), 1, &last_offset, tx));
89 	}
90 	if (vd->vdev_initialize_action_time > 0) {
91 		uint64_t val = (uint64_t)vd->vdev_initialize_action_time;
92 		VERIFY0(zap_update(mos, vd->vdev_leaf_zap,
93 		    VDEV_LEAF_ZAP_INITIALIZE_ACTION_TIME, sizeof (val),
94 		    1, &val, tx));
95 	}
96 
97 	uint64_t initialize_state = vd->vdev_initialize_state;
98 	VERIFY0(zap_update(mos, vd->vdev_leaf_zap,
99 	    VDEV_LEAF_ZAP_INITIALIZE_STATE, sizeof (initialize_state), 1,
100 	    &initialize_state, tx));
101 }
102 
103 static void
104 vdev_initialize_change_state(vdev_t *vd, vdev_initializing_state_t new_state)
105 {
106 	ASSERT(MUTEX_HELD(&vd->vdev_initialize_lock));
107 	spa_t *spa = vd->vdev_spa;
108 
109 	if (new_state == vd->vdev_initialize_state)
110 		return;
111 
112 	/*
113 	 * Copy the vd's guid, this will be freed by the sync task.
114 	 */
115 	uint64_t *guid = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
116 	*guid = vd->vdev_guid;
117 
118 	/*
119 	 * If we're suspending, then preserving the original start time.
120 	 */
121 	if (vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED) {
122 		vd->vdev_initialize_action_time = gethrestime_sec();
123 	}
124 
125 	vdev_initializing_state_t old_state = vd->vdev_initialize_state;
126 	vd->vdev_initialize_state = new_state;
127 
128 	dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
129 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
130 	dsl_sync_task_nowait(spa_get_dsl(spa), vdev_initialize_zap_update_sync,
131 	    guid, tx);
132 
133 	switch (new_state) {
134 	case VDEV_INITIALIZE_ACTIVE:
135 		spa_history_log_internal(spa, "initialize", tx,
136 		    "vdev=%s activated", vd->vdev_path);
137 		break;
138 	case VDEV_INITIALIZE_SUSPENDED:
139 		spa_history_log_internal(spa, "initialize", tx,
140 		    "vdev=%s suspended", vd->vdev_path);
141 		break;
142 	case VDEV_INITIALIZE_CANCELED:
143 		if (old_state == VDEV_INITIALIZE_ACTIVE ||
144 		    old_state == VDEV_INITIALIZE_SUSPENDED)
145 			spa_history_log_internal(spa, "initialize", tx,
146 			    "vdev=%s canceled", vd->vdev_path);
147 		break;
148 	case VDEV_INITIALIZE_COMPLETE:
149 		spa_history_log_internal(spa, "initialize", tx,
150 		    "vdev=%s complete", vd->vdev_path);
151 		break;
152 	default:
153 		panic("invalid state %llu", (unsigned long long)new_state);
154 	}
155 
156 	dmu_tx_commit(tx);
157 
158 	if (new_state != VDEV_INITIALIZE_ACTIVE)
159 		spa_notify_waiters(spa);
160 }
161 
162 static void
163 vdev_initialize_cb(zio_t *zio)
164 {
165 	vdev_t *vd = zio->io_vd;
166 	mutex_enter(&vd->vdev_initialize_io_lock);
167 	if (zio->io_error == ENXIO && !vdev_writeable(vd)) {
168 		/*
169 		 * The I/O failed because the vdev was unavailable; roll the
170 		 * last offset back. (This works because spa_sync waits on
171 		 * spa_txg_zio before it runs sync tasks.)
172 		 */
173 		uint64_t *off =
174 		    &vd->vdev_initialize_offset[zio->io_txg & TXG_MASK];
175 		*off = MIN(*off, zio->io_offset);
176 	} else {
177 		/*
178 		 * Since initializing is best-effort, we ignore I/O errors and
179 		 * rely on vdev_probe to determine if the errors are more
180 		 * critical.
181 		 */
182 		if (zio->io_error != 0)
183 			vd->vdev_stat.vs_initialize_errors++;
184 
185 		vd->vdev_initialize_bytes_done += zio->io_orig_size;
186 	}
187 	ASSERT3U(vd->vdev_initialize_inflight, >, 0);
188 	vd->vdev_initialize_inflight--;
189 	cv_broadcast(&vd->vdev_initialize_io_cv);
190 	mutex_exit(&vd->vdev_initialize_io_lock);
191 
192 	spa_config_exit(vd->vdev_spa, SCL_STATE_ALL, vd);
193 }
194 
195 /* Takes care of physical writing and limiting # of concurrent ZIOs. */
196 static int
197 vdev_initialize_write(vdev_t *vd, uint64_t start, uint64_t size, abd_t *data)
198 {
199 	spa_t *spa = vd->vdev_spa;
200 
201 	/* Limit inflight initializing I/Os */
202 	mutex_enter(&vd->vdev_initialize_io_lock);
203 	while (vd->vdev_initialize_inflight >= zfs_initialize_limit) {
204 		cv_wait(&vd->vdev_initialize_io_cv,
205 		    &vd->vdev_initialize_io_lock);
206 	}
207 	vd->vdev_initialize_inflight++;
208 	mutex_exit(&vd->vdev_initialize_io_lock);
209 
210 	dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
211 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
212 	uint64_t txg = dmu_tx_get_txg(tx);
213 
214 	spa_config_enter(spa, SCL_STATE_ALL, vd, RW_READER);
215 	mutex_enter(&vd->vdev_initialize_lock);
216 
217 	if (vd->vdev_initialize_offset[txg & TXG_MASK] == 0) {
218 		uint64_t *guid = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
219 		*guid = vd->vdev_guid;
220 
221 		/* This is the first write of this txg. */
222 		dsl_sync_task_nowait(spa_get_dsl(spa),
223 		    vdev_initialize_zap_update_sync, guid, tx);
224 	}
225 
226 	/*
227 	 * We know the vdev struct will still be around since all
228 	 * consumers of vdev_free must stop the initialization first.
229 	 */
230 	if (vdev_initialize_should_stop(vd)) {
231 		mutex_enter(&vd->vdev_initialize_io_lock);
232 		ASSERT3U(vd->vdev_initialize_inflight, >, 0);
233 		vd->vdev_initialize_inflight--;
234 		mutex_exit(&vd->vdev_initialize_io_lock);
235 		spa_config_exit(vd->vdev_spa, SCL_STATE_ALL, vd);
236 		mutex_exit(&vd->vdev_initialize_lock);
237 		dmu_tx_commit(tx);
238 		return (SET_ERROR(EINTR));
239 	}
240 	mutex_exit(&vd->vdev_initialize_lock);
241 
242 	vd->vdev_initialize_offset[txg & TXG_MASK] = start + size;
243 	zio_nowait(zio_write_phys(spa->spa_txg_zio[txg & TXG_MASK], vd, start,
244 	    size, data, ZIO_CHECKSUM_OFF, vdev_initialize_cb, NULL,
245 	    ZIO_PRIORITY_INITIALIZING, ZIO_FLAG_CANFAIL, B_FALSE));
246 	/* vdev_initialize_cb releases SCL_STATE_ALL */
247 
248 	dmu_tx_commit(tx);
249 
250 	return (0);
251 }
252 
253 /*
254  * Callback to fill each ABD chunk with zfs_initialize_value. len must be
255  * divisible by sizeof (uint64_t), and buf must be 8-byte aligned. The ABD
256  * allocation will guarantee these for us.
257  */
258 /* ARGSUSED */
259 static int
260 vdev_initialize_block_fill(void *buf, size_t len, void *unused)
261 {
262 	ASSERT0(len % sizeof (uint64_t));
263 #ifdef _ILP32
264 	for (uint64_t i = 0; i < len; i += sizeof (uint32_t)) {
265 		*(uint32_t *)((char *)(buf) + i) = zfs_initialize_value;
266 	}
267 #else
268 	for (uint64_t i = 0; i < len; i += sizeof (uint64_t)) {
269 		*(uint64_t *)((char *)(buf) + i) = zfs_initialize_value;
270 	}
271 #endif
272 	return (0);
273 }
274 
275 static abd_t *
276 vdev_initialize_block_alloc(void)
277 {
278 	/* Allocate ABD for filler data */
279 	abd_t *data = abd_alloc_for_io(zfs_initialize_chunk_size, B_FALSE);
280 
281 	ASSERT0(zfs_initialize_chunk_size % sizeof (uint64_t));
282 	(void) abd_iterate_func(data, 0, zfs_initialize_chunk_size,
283 	    vdev_initialize_block_fill, NULL);
284 
285 	return (data);
286 }
287 
288 static void
289 vdev_initialize_block_free(abd_t *data)
290 {
291 	abd_free(data);
292 }
293 
294 static int
295 vdev_initialize_ranges(vdev_t *vd, abd_t *data)
296 {
297 	range_tree_t *rt = vd->vdev_initialize_tree;
298 	zfs_btree_t *bt = &rt->rt_root;
299 	zfs_btree_index_t where;
300 
301 	for (range_seg_t *rs = zfs_btree_first(bt, &where); rs != NULL;
302 	    rs = zfs_btree_next(bt, &where, &where)) {
303 		uint64_t size = rs_get_end(rs, rt) - rs_get_start(rs, rt);
304 
305 		/* Split range into legally-sized physical chunks */
306 		uint64_t writes_required =
307 		    ((size - 1) / zfs_initialize_chunk_size) + 1;
308 
309 		for (uint64_t w = 0; w < writes_required; w++) {
310 			int error;
311 
312 			error = vdev_initialize_write(vd,
313 			    VDEV_LABEL_START_SIZE + rs_get_start(rs, rt) +
314 			    (w * zfs_initialize_chunk_size),
315 			    MIN(size - (w * zfs_initialize_chunk_size),
316 			    zfs_initialize_chunk_size), data);
317 			if (error != 0)
318 				return (error);
319 		}
320 	}
321 	return (0);
322 }
323 
324 static void
325 vdev_initialize_xlate_last_rs_end(void *arg, range_seg64_t *physical_rs)
326 {
327 	uint64_t *last_rs_end = (uint64_t *)arg;
328 
329 	if (physical_rs->rs_end > *last_rs_end)
330 		*last_rs_end = physical_rs->rs_end;
331 }
332 
333 static void
334 vdev_initialize_xlate_progress(void *arg, range_seg64_t *physical_rs)
335 {
336 	vdev_t *vd = (vdev_t *)arg;
337 
338 	uint64_t size = physical_rs->rs_end - physical_rs->rs_start;
339 	vd->vdev_initialize_bytes_est += size;
340 
341 	if (vd->vdev_initialize_last_offset > physical_rs->rs_end) {
342 		vd->vdev_initialize_bytes_done += size;
343 	} else if (vd->vdev_initialize_last_offset > physical_rs->rs_start &&
344 	    vd->vdev_initialize_last_offset < physical_rs->rs_end) {
345 		vd->vdev_initialize_bytes_done +=
346 		    vd->vdev_initialize_last_offset - physical_rs->rs_start;
347 	}
348 }
349 
350 static void
351 vdev_initialize_calculate_progress(vdev_t *vd)
352 {
353 	ASSERT(spa_config_held(vd->vdev_spa, SCL_CONFIG, RW_READER) ||
354 	    spa_config_held(vd->vdev_spa, SCL_CONFIG, RW_WRITER));
355 	ASSERT(vd->vdev_leaf_zap != 0);
356 
357 	vd->vdev_initialize_bytes_est = 0;
358 	vd->vdev_initialize_bytes_done = 0;
359 
360 	for (uint64_t i = 0; i < vd->vdev_top->vdev_ms_count; i++) {
361 		metaslab_t *msp = vd->vdev_top->vdev_ms[i];
362 		mutex_enter(&msp->ms_lock);
363 
364 		uint64_t ms_free = (msp->ms_size -
365 		    metaslab_allocated_space(msp)) /
366 		    vdev_get_ndisks(vd->vdev_top);
367 
368 		/*
369 		 * Convert the metaslab range to a physical range
370 		 * on our vdev. We use this to determine if we are
371 		 * in the middle of this metaslab range.
372 		 */
373 		range_seg64_t logical_rs, physical_rs, remain_rs;
374 		logical_rs.rs_start = msp->ms_start;
375 		logical_rs.rs_end = msp->ms_start + msp->ms_size;
376 
377 		/* Metaslab space after this offset has not been initialized */
378 		vdev_xlate(vd, &logical_rs, &physical_rs, &remain_rs);
379 		if (vd->vdev_initialize_last_offset <= physical_rs.rs_start) {
380 			vd->vdev_initialize_bytes_est += ms_free;
381 			mutex_exit(&msp->ms_lock);
382 			continue;
383 		}
384 
385 		/* Metaslab space before this offset has been initialized */
386 		uint64_t last_rs_end = physical_rs.rs_end;
387 		if (!vdev_xlate_is_empty(&remain_rs)) {
388 			vdev_xlate_walk(vd, &remain_rs,
389 			    vdev_initialize_xlate_last_rs_end, &last_rs_end);
390 		}
391 
392 		if (vd->vdev_initialize_last_offset > last_rs_end) {
393 			vd->vdev_initialize_bytes_done += ms_free;
394 			vd->vdev_initialize_bytes_est += ms_free;
395 			mutex_exit(&msp->ms_lock);
396 			continue;
397 		}
398 
399 		/*
400 		 * If we get here, we're in the middle of initializing this
401 		 * metaslab. Load it and walk the free tree for more accurate
402 		 * progress estimation.
403 		 */
404 		VERIFY0(metaslab_load(msp));
405 
406 		zfs_btree_index_t where;
407 		range_tree_t *rt = msp->ms_allocatable;
408 		for (range_seg_t *rs =
409 		    zfs_btree_first(&rt->rt_root, &where); rs;
410 		    rs = zfs_btree_next(&rt->rt_root, &where,
411 		    &where)) {
412 			logical_rs.rs_start = rs_get_start(rs, rt);
413 			logical_rs.rs_end = rs_get_end(rs, rt);
414 
415 			vdev_xlate_walk(vd, &logical_rs,
416 			    vdev_initialize_xlate_progress, vd);
417 		}
418 		mutex_exit(&msp->ms_lock);
419 	}
420 }
421 
422 static int
423 vdev_initialize_load(vdev_t *vd)
424 {
425 	int err = 0;
426 	ASSERT(spa_config_held(vd->vdev_spa, SCL_CONFIG, RW_READER) ||
427 	    spa_config_held(vd->vdev_spa, SCL_CONFIG, RW_WRITER));
428 	ASSERT(vd->vdev_leaf_zap != 0);
429 
430 	if (vd->vdev_initialize_state == VDEV_INITIALIZE_ACTIVE ||
431 	    vd->vdev_initialize_state == VDEV_INITIALIZE_SUSPENDED) {
432 		err = zap_lookup(vd->vdev_spa->spa_meta_objset,
433 		    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_INITIALIZE_LAST_OFFSET,
434 		    sizeof (vd->vdev_initialize_last_offset), 1,
435 		    &vd->vdev_initialize_last_offset);
436 		if (err == ENOENT) {
437 			vd->vdev_initialize_last_offset = 0;
438 			err = 0;
439 		}
440 	}
441 
442 	vdev_initialize_calculate_progress(vd);
443 	return (err);
444 }
445 
446 static void
447 vdev_initialize_xlate_range_add(void *arg, range_seg64_t *physical_rs)
448 {
449 	vdev_t *vd = arg;
450 
451 	/* Only add segments that we have not visited yet */
452 	if (physical_rs->rs_end <= vd->vdev_initialize_last_offset)
453 		return;
454 
455 	/* Pick up where we left off mid-range. */
456 	if (vd->vdev_initialize_last_offset > physical_rs->rs_start) {
457 		zfs_dbgmsg("range write: vd %s changed (%llu, %llu) to "
458 		    "(%llu, %llu)", vd->vdev_path,
459 		    (u_longlong_t)physical_rs->rs_start,
460 		    (u_longlong_t)physical_rs->rs_end,
461 		    (u_longlong_t)vd->vdev_initialize_last_offset,
462 		    (u_longlong_t)physical_rs->rs_end);
463 		ASSERT3U(physical_rs->rs_end, >,
464 		    vd->vdev_initialize_last_offset);
465 		physical_rs->rs_start = vd->vdev_initialize_last_offset;
466 	}
467 
468 	ASSERT3U(physical_rs->rs_end, >, physical_rs->rs_start);
469 
470 	range_tree_add(vd->vdev_initialize_tree, physical_rs->rs_start,
471 	    physical_rs->rs_end - physical_rs->rs_start);
472 }
473 
474 /*
475  * Convert the logical range into a physical range and add it to our
476  * avl tree.
477  */
478 static void
479 vdev_initialize_range_add(void *arg, uint64_t start, uint64_t size)
480 {
481 	vdev_t *vd = arg;
482 	range_seg64_t logical_rs;
483 	logical_rs.rs_start = start;
484 	logical_rs.rs_end = start + size;
485 
486 	ASSERT(vd->vdev_ops->vdev_op_leaf);
487 	vdev_xlate_walk(vd, &logical_rs, vdev_initialize_xlate_range_add, arg);
488 }
489 
490 static void
491 vdev_initialize_thread(void *arg)
492 {
493 	vdev_t *vd = arg;
494 	spa_t *spa = vd->vdev_spa;
495 	int error = 0;
496 	uint64_t ms_count = 0;
497 
498 	ASSERT(vdev_is_concrete(vd));
499 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
500 
501 	vd->vdev_initialize_last_offset = 0;
502 	VERIFY0(vdev_initialize_load(vd));
503 
504 	abd_t *deadbeef = vdev_initialize_block_alloc();
505 
506 	vd->vdev_initialize_tree = range_tree_create(NULL, RANGE_SEG64, NULL,
507 	    0, 0);
508 
509 	for (uint64_t i = 0; !vd->vdev_detached &&
510 	    i < vd->vdev_top->vdev_ms_count; i++) {
511 		metaslab_t *msp = vd->vdev_top->vdev_ms[i];
512 		boolean_t unload_when_done = B_FALSE;
513 
514 		/*
515 		 * If we've expanded the top-level vdev or it's our
516 		 * first pass, calculate our progress.
517 		 */
518 		if (vd->vdev_top->vdev_ms_count != ms_count) {
519 			vdev_initialize_calculate_progress(vd);
520 			ms_count = vd->vdev_top->vdev_ms_count;
521 		}
522 
523 		spa_config_exit(spa, SCL_CONFIG, FTAG);
524 		metaslab_disable(msp);
525 		mutex_enter(&msp->ms_lock);
526 		if (!msp->ms_loaded && !msp->ms_loading)
527 			unload_when_done = B_TRUE;
528 		VERIFY0(metaslab_load(msp));
529 
530 		range_tree_walk(msp->ms_allocatable, vdev_initialize_range_add,
531 		    vd);
532 		mutex_exit(&msp->ms_lock);
533 
534 		error = vdev_initialize_ranges(vd, deadbeef);
535 		metaslab_enable(msp, B_TRUE, unload_when_done);
536 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
537 
538 		range_tree_vacate(vd->vdev_initialize_tree, NULL, NULL);
539 		if (error != 0)
540 			break;
541 	}
542 
543 	spa_config_exit(spa, SCL_CONFIG, FTAG);
544 	mutex_enter(&vd->vdev_initialize_io_lock);
545 	while (vd->vdev_initialize_inflight > 0) {
546 		cv_wait(&vd->vdev_initialize_io_cv,
547 		    &vd->vdev_initialize_io_lock);
548 	}
549 	mutex_exit(&vd->vdev_initialize_io_lock);
550 
551 	range_tree_destroy(vd->vdev_initialize_tree);
552 	vdev_initialize_block_free(deadbeef);
553 	vd->vdev_initialize_tree = NULL;
554 
555 	mutex_enter(&vd->vdev_initialize_lock);
556 	if (!vd->vdev_initialize_exit_wanted) {
557 		if (vdev_writeable(vd)) {
558 			vdev_initialize_change_state(vd,
559 			    VDEV_INITIALIZE_COMPLETE);
560 		} else if (vd->vdev_faulted) {
561 			vdev_initialize_change_state(vd,
562 			    VDEV_INITIALIZE_CANCELED);
563 		}
564 	}
565 	ASSERT(vd->vdev_initialize_thread != NULL ||
566 	    vd->vdev_initialize_inflight == 0);
567 
568 	/*
569 	 * Drop the vdev_initialize_lock while we sync out the
570 	 * txg since it's possible that a device might be trying to
571 	 * come online and must check to see if it needs to restart an
572 	 * initialization. That thread will be holding the spa_config_lock
573 	 * which would prevent the txg_wait_synced from completing.
574 	 */
575 	mutex_exit(&vd->vdev_initialize_lock);
576 	txg_wait_synced(spa_get_dsl(spa), 0);
577 	mutex_enter(&vd->vdev_initialize_lock);
578 
579 	vd->vdev_initialize_thread = NULL;
580 	cv_broadcast(&vd->vdev_initialize_cv);
581 	mutex_exit(&vd->vdev_initialize_lock);
582 
583 	thread_exit();
584 }
585 
586 /*
587  * Initiates a device. Caller must hold vdev_initialize_lock.
588  * Device must be a leaf and not already be initializing.
589  */
590 void
591 vdev_initialize(vdev_t *vd)
592 {
593 	ASSERT(MUTEX_HELD(&vd->vdev_initialize_lock));
594 	ASSERT(vd->vdev_ops->vdev_op_leaf);
595 	ASSERT(vdev_is_concrete(vd));
596 	ASSERT3P(vd->vdev_initialize_thread, ==, NULL);
597 	ASSERT(!vd->vdev_detached);
598 	ASSERT(!vd->vdev_initialize_exit_wanted);
599 	ASSERT(!vd->vdev_top->vdev_removing);
600 
601 	vdev_initialize_change_state(vd, VDEV_INITIALIZE_ACTIVE);
602 	vd->vdev_initialize_thread = thread_create(NULL, 0,
603 	    vdev_initialize_thread, vd, 0, &p0, TS_RUN, maxclsyspri);
604 }
605 
606 /*
607  * Wait for the initialize thread to be terminated (cancelled or stopped).
608  */
609 static void
610 vdev_initialize_stop_wait_impl(vdev_t *vd)
611 {
612 	ASSERT(MUTEX_HELD(&vd->vdev_initialize_lock));
613 
614 	while (vd->vdev_initialize_thread != NULL)
615 		cv_wait(&vd->vdev_initialize_cv, &vd->vdev_initialize_lock);
616 
617 	ASSERT3P(vd->vdev_initialize_thread, ==, NULL);
618 	vd->vdev_initialize_exit_wanted = B_FALSE;
619 }
620 
621 /*
622  * Wait for vdev initialize threads which were either to cleanly exit.
623  */
624 void
625 vdev_initialize_stop_wait(spa_t *spa, list_t *vd_list)
626 {
627 	vdev_t *vd;
628 
629 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
630 
631 	while ((vd = list_remove_head(vd_list)) != NULL) {
632 		mutex_enter(&vd->vdev_initialize_lock);
633 		vdev_initialize_stop_wait_impl(vd);
634 		mutex_exit(&vd->vdev_initialize_lock);
635 	}
636 }
637 
638 /*
639  * Stop initializing a device, with the resultant initializing state being
640  * tgt_state.  For blocking behavior pass NULL for vd_list.  Otherwise, when
641  * a list_t is provided the stopping vdev is inserted in to the list.  Callers
642  * are then required to call vdev_initialize_stop_wait() to block for all the
643  * initialization threads to exit.  The caller must hold vdev_initialize_lock
644  * and must not be writing to the spa config, as the initializing thread may
645  * try to enter the config as a reader before exiting.
646  */
647 void
648 vdev_initialize_stop(vdev_t *vd, vdev_initializing_state_t tgt_state,
649     list_t *vd_list)
650 {
651 	ASSERT(!spa_config_held(vd->vdev_spa, SCL_CONFIG|SCL_STATE, RW_WRITER));
652 	ASSERT(MUTEX_HELD(&vd->vdev_initialize_lock));
653 	ASSERT(vd->vdev_ops->vdev_op_leaf);
654 	ASSERT(vdev_is_concrete(vd));
655 
656 	/*
657 	 * Allow cancel requests to proceed even if the initialize thread
658 	 * has stopped.
659 	 */
660 	if (vd->vdev_initialize_thread == NULL &&
661 	    tgt_state != VDEV_INITIALIZE_CANCELED) {
662 		return;
663 	}
664 
665 	vdev_initialize_change_state(vd, tgt_state);
666 	vd->vdev_initialize_exit_wanted = B_TRUE;
667 
668 	if (vd_list == NULL) {
669 		vdev_initialize_stop_wait_impl(vd);
670 	} else {
671 		ASSERT(MUTEX_HELD(&spa_namespace_lock));
672 		list_insert_tail(vd_list, vd);
673 	}
674 }
675 
676 static void
677 vdev_initialize_stop_all_impl(vdev_t *vd, vdev_initializing_state_t tgt_state,
678     list_t *vd_list)
679 {
680 	if (vd->vdev_ops->vdev_op_leaf && vdev_is_concrete(vd)) {
681 		mutex_enter(&vd->vdev_initialize_lock);
682 		vdev_initialize_stop(vd, tgt_state, vd_list);
683 		mutex_exit(&vd->vdev_initialize_lock);
684 		return;
685 	}
686 
687 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
688 		vdev_initialize_stop_all_impl(vd->vdev_child[i], tgt_state,
689 		    vd_list);
690 	}
691 }
692 
693 /*
694  * Convenience function to stop initializing of a vdev tree and set all
695  * initialize thread pointers to NULL.
696  */
697 void
698 vdev_initialize_stop_all(vdev_t *vd, vdev_initializing_state_t tgt_state)
699 {
700 	spa_t *spa = vd->vdev_spa;
701 	list_t vd_list;
702 
703 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
704 
705 	list_create(&vd_list, sizeof (vdev_t),
706 	    offsetof(vdev_t, vdev_initialize_node));
707 
708 	vdev_initialize_stop_all_impl(vd, tgt_state, &vd_list);
709 	vdev_initialize_stop_wait(spa, &vd_list);
710 
711 	if (vd->vdev_spa->spa_sync_on) {
712 		/* Make sure that our state has been synced to disk */
713 		txg_wait_synced(spa_get_dsl(vd->vdev_spa), 0);
714 	}
715 
716 	list_destroy(&vd_list);
717 }
718 
719 void
720 vdev_initialize_restart(vdev_t *vd)
721 {
722 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
723 	ASSERT(!spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
724 
725 	if (vd->vdev_leaf_zap != 0) {
726 		mutex_enter(&vd->vdev_initialize_lock);
727 		uint64_t initialize_state = VDEV_INITIALIZE_NONE;
728 		int err = zap_lookup(vd->vdev_spa->spa_meta_objset,
729 		    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_INITIALIZE_STATE,
730 		    sizeof (initialize_state), 1, &initialize_state);
731 		ASSERT(err == 0 || err == ENOENT);
732 		vd->vdev_initialize_state = initialize_state;
733 
734 		uint64_t timestamp = 0;
735 		err = zap_lookup(vd->vdev_spa->spa_meta_objset,
736 		    vd->vdev_leaf_zap, VDEV_LEAF_ZAP_INITIALIZE_ACTION_TIME,
737 		    sizeof (timestamp), 1, &timestamp);
738 		ASSERT(err == 0 || err == ENOENT);
739 		vd->vdev_initialize_action_time = timestamp;
740 
741 		if (vd->vdev_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
742 		    vd->vdev_offline) {
743 			/* load progress for reporting, but don't resume */
744 			VERIFY0(vdev_initialize_load(vd));
745 		} else if (vd->vdev_initialize_state ==
746 		    VDEV_INITIALIZE_ACTIVE && vdev_writeable(vd) &&
747 		    !vd->vdev_top->vdev_removing &&
748 		    vd->vdev_initialize_thread == NULL) {
749 			vdev_initialize(vd);
750 		}
751 
752 		mutex_exit(&vd->vdev_initialize_lock);
753 	}
754 
755 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
756 		vdev_initialize_restart(vd->vdev_child[i]);
757 	}
758 }
759 
760 EXPORT_SYMBOL(vdev_initialize);
761 EXPORT_SYMBOL(vdev_initialize_stop);
762 EXPORT_SYMBOL(vdev_initialize_stop_all);
763 EXPORT_SYMBOL(vdev_initialize_stop_wait);
764 EXPORT_SYMBOL(vdev_initialize_restart);
765 
766 /* BEGIN CSTYLED */
767 ZFS_MODULE_PARAM(zfs, zfs_, initialize_value, ULONG, ZMOD_RW,
768 	"Value written during zpool initialize");
769 
770 ZFS_MODULE_PARAM(zfs, zfs_, initialize_chunk_size, ULONG, ZMOD_RW,
771 	"Size in bytes of writes by zpool initialize");
772 /* END CSTYLED */
773