spa.c revision c7cd242109c82107ec2e50013369e92be9d77702
17c2fbfbApril Chin/*
27c2fbfbApril Chin * CDDL HEADER START
37c2fbfbApril Chin *
47c2fbfbApril Chin * The contents of this file are subject to the terms of the
57c2fbfbApril Chin * Common Development and Distribution License (the "License").
67c2fbfbApril Chin * You may not use this file except in compliance with the License.
77c2fbfbApril Chin *
87c2fbfbApril Chin * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
97c2fbfbApril Chin * or http://www.opensolaris.org/os/licensing.
107c2fbfbApril Chin * See the License for the specific language governing permissions
117c2fbfbApril Chin * and limitations under the License.
127c2fbfbApril Chin *
137c2fbfbApril Chin * When distributing Covered Code, include this CDDL HEADER in each
147c2fbfbApril Chin * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
157c2fbfbApril Chin * If applicable, add the following below this CDDL HEADER, with the
167c2fbfbApril Chin * fields enclosed by brackets "[]" replaced with your own identifying
177c2fbfbApril Chin * information: Portions Copyright [yyyy] [name of copyright owner]
187c2fbfbApril Chin *
197c2fbfbApril Chin * CDDL HEADER END
207c2fbfbApril Chin */
217c2fbfbApril Chin
227c2fbfbApril Chin/*
237c2fbfbApril Chin * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
247c2fbfbApril Chin */
253e14f97Roger A. Faulkner
267c2fbfbApril Chin/*
277c2fbfbApril Chin * This file contains all the routines used when modifying on-disk SPA state.
287c2fbfbApril Chin * This includes opening, importing, destroying, exporting a pool, and syncing a
297c2fbfbApril Chin * pool.
307c2fbfbApril Chin */
317c2fbfbApril Chin
327c2fbfbApril Chin#include <sys/zfs_context.h>
337c2fbfbApril Chin#include <sys/fm/fs/zfs.h>
347c2fbfbApril Chin#include <sys/spa_impl.h>
357c2fbfbApril Chin#include <sys/zio.h>
367c2fbfbApril Chin#include <sys/zio_checksum.h>
377c2fbfbApril Chin#include <sys/dmu.h>
387c2fbfbApril Chin#include <sys/dmu_tx.h>
397c2fbfbApril Chin#include <sys/zap.h>
407c2fbfbApril Chin#include <sys/zil.h>
417c2fbfbApril Chin#include <sys/ddt.h>
427c2fbfbApril Chin#include <sys/vdev_impl.h>
437c2fbfbApril Chin#include <sys/metaslab.h>
447c2fbfbApril Chin#include <sys/metaslab_impl.h>
457c2fbfbApril Chin#include <sys/uberblock_impl.h>
467c2fbfbApril Chin#include <sys/txg.h>
477c2fbfbApril Chin#include <sys/avl.h>
487c2fbfbApril Chin#include <sys/dmu_traverse.h>
497c2fbfbApril Chin#include <sys/dmu_objset.h>
507c2fbfbApril Chin#include <sys/unique.h>
517c2fbfbApril Chin#include <sys/dsl_pool.h>
527c2fbfbApril Chin#include <sys/dsl_dataset.h>
537c2fbfbApril Chin#include <sys/dsl_dir.h>
547c2fbfbApril Chin#include <sys/dsl_prop.h>
557c2fbfbApril Chin#include <sys/dsl_synctask.h>
567c2fbfbApril Chin#include <sys/fs/zfs.h>
577c2fbfbApril Chin#include <sys/arc.h>
587c2fbfbApril Chin#include <sys/callb.h>
597c2fbfbApril Chin#include <sys/systeminfo.h>
607c2fbfbApril Chin#include <sys/spa_boot.h>
617c2fbfbApril Chin#include <sys/zfs_ioctl.h>
627c2fbfbApril Chin#include <sys/dsl_scan.h>
637c2fbfbApril Chin
647c2fbfbApril Chin#ifdef	_KERNEL
657c2fbfbApril Chin#include <sys/bootprops.h>
667c2fbfbApril Chin#include <sys/callb.h>
677c2fbfbApril Chin#include <sys/cpupart.h>
687c2fbfbApril Chin#include <sys/pool.h>
697c2fbfbApril Chin#include <sys/sysdc.h>
707c2fbfbApril Chin#include <sys/zone.h>
717c2fbfbApril Chin#endif	/* _KERNEL */
727c2fbfbApril Chin
737c2fbfbApril Chin#include "zfs_prop.h"
747c2fbfbApril Chin#include "zfs_comutil.h"
757c2fbfbApril Chin
767c2fbfbApril Chintypedef enum zti_modes {
777c2fbfbApril Chin	zti_mode_fixed,			/* value is # of threads (min 1) */
787c2fbfbApril Chin	zti_mode_online_percent,	/* value is % of online CPUs */
797c2fbfbApril Chin	zti_mode_batch,			/* cpu-intensive; value is ignored */
807c2fbfbApril Chin	zti_mode_null,			/* don't create a taskq */
817c2fbfbApril Chin	zti_nmodes
827c2fbfbApril Chin} zti_modes_t;
837c2fbfbApril Chin
847c2fbfbApril Chin#define	ZTI_FIX(n)	{ zti_mode_fixed, (n) }
857c2fbfbApril Chin#define	ZTI_PCT(n)	{ zti_mode_online_percent, (n) }
867c2fbfbApril Chin#define	ZTI_BATCH	{ zti_mode_batch, 0 }
877c2fbfbApril Chin#define	ZTI_NULL	{ zti_mode_null, 0 }
887c2fbfbApril Chin
897c2fbfbApril Chin#define	ZTI_ONE		ZTI_FIX(1)
907c2fbfbApril Chin
917c2fbfbApril Chintypedef struct zio_taskq_info {
927c2fbfbApril Chin	enum zti_modes zti_mode;
937c2fbfbApril Chin	uint_t zti_value;
947c2fbfbApril Chin} zio_taskq_info_t;
957c2fbfbApril Chin
967c2fbfbApril Chinstatic const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
977c2fbfbApril Chin	"issue", "issue_high", "intr", "intr_high"
987c2fbfbApril Chin};
997c2fbfbApril Chin
1007c2fbfbApril Chin/*
1017c2fbfbApril Chin * Define the taskq threads for the following I/O types:
1027c2fbfbApril Chin * 	NULL, READ, WRITE, FREE, CLAIM, and IOCTL
1037c2fbfbApril Chin */
1047c2fbfbApril Chinconst zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
1057c2fbfbApril Chin	/* ISSUE	ISSUE_HIGH	INTR		INTR_HIGH */
1067c2fbfbApril Chin	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL },
1077c2fbfbApril Chin	{ ZTI_FIX(8),	ZTI_NULL,	ZTI_BATCH,	ZTI_NULL },
1087c2fbfbApril Chin	{ ZTI_BATCH,	ZTI_FIX(5),	ZTI_FIX(8),	ZTI_FIX(5) },
1097c2fbfbApril Chin	{ ZTI_FIX(100),	ZTI_NULL,	ZTI_ONE,	ZTI_NULL },
1107c2fbfbApril Chin	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL },
1117c2fbfbApril Chin	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL },
1127c2fbfbApril Chin};
1137c2fbfbApril Chin
1147c2fbfbApril Chinstatic dsl_syncfunc_t spa_sync_props;
1157c2fbfbApril Chinstatic boolean_t spa_has_active_shared_spare(spa_t *spa);
1167c2fbfbApril Chinstatic int spa_load_impl(spa_t *spa, uint64_t, nvlist_t *config,
1177c2fbfbApril Chin    spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
1187c2fbfbApril Chin    char **ereport);
1197c2fbfbApril Chin
1207c2fbfbApril Chinuint_t		zio_taskq_batch_pct = 100;	/* 1 thread per cpu in pset */
1217c2fbfbApril Chinid_t		zio_taskq_psrset_bind = PS_NONE;
1227c2fbfbApril Chinboolean_t	zio_taskq_sysdc = B_TRUE;	/* use SDC scheduling class */
1237c2fbfbApril Chinuint_t		zio_taskq_basedc = 80;		/* base duty cycle */
1247c2fbfbApril Chin
1257c2fbfbApril Chinboolean_t	spa_create_process = B_TRUE;	/* no process ==> no sysdc */
1267c2fbfbApril Chin
1277c2fbfbApril Chin/*
1287c2fbfbApril Chin * This (illegal) pool name is used when temporarily importing a spa_t in order
1297c2fbfbApril Chin * to get the vdev stats associated with the imported devices.
1307c2fbfbApril Chin */
1317c2fbfbApril Chin#define	TRYIMPORT_NAME	"$import"
1327c2fbfbApril Chin
1337c2fbfbApril Chin/*
1347c2fbfbApril Chin * ==========================================================================
1357c2fbfbApril Chin * SPA properties routines
1367c2fbfbApril Chin * ==========================================================================
1377c2fbfbApril Chin */
1387c2fbfbApril Chin
1397c2fbfbApril Chin/*
1407c2fbfbApril Chin * Add a (source=src, propname=propval) list to an nvlist.
1417c2fbfbApril Chin */
1427c2fbfbApril Chinstatic void
1437c2fbfbApril Chinspa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
1447c2fbfbApril Chin    uint64_t intval, zprop_source_t src)
1457c2fbfbApril Chin{
1467c2fbfbApril Chin	const char *propname = zpool_prop_to_name(prop);
1477c2fbfbApril Chin	nvlist_t *propval;
1487c2fbfbApril Chin
1497c2fbfbApril Chin	VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1507c2fbfbApril Chin	VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
151
152	if (strval != NULL)
153		VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
154	else
155		VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
156
157	VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
158	nvlist_free(propval);
159}
160
161/*
162 * Get property values from the spa configuration.
163 */
164static void
165spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
166{
167	uint64_t size;
168	uint64_t alloc;
169	uint64_t cap, version;
170	zprop_source_t src = ZPROP_SRC_NONE;
171	spa_config_dirent_t *dp;
172
173	ASSERT(MUTEX_HELD(&spa->spa_props_lock));
174
175	if (spa->spa_root_vdev != NULL) {
176		alloc = metaslab_class_get_alloc(spa_normal_class(spa));
177		size = metaslab_class_get_space(spa_normal_class(spa));
178		spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
179		spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
180		spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
181		spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
182		    size - alloc, src);
183
184		cap = (size == 0) ? 0 : (alloc * 100 / size);
185		spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
186
187		spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
188		    ddt_get_pool_dedup_ratio(spa), src);
189
190		spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
191		    spa->spa_root_vdev->vdev_state, src);
192
193		version = spa_version(spa);
194		if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
195			src = ZPROP_SRC_DEFAULT;
196		else
197			src = ZPROP_SRC_LOCAL;
198		spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
199	}
200
201	spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
202
203	if (spa->spa_root != NULL)
204		spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
205		    0, ZPROP_SRC_LOCAL);
206
207	if ((dp = list_head(&spa->spa_config_list)) != NULL) {
208		if (dp->scd_path == NULL) {
209			spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
210			    "none", 0, ZPROP_SRC_LOCAL);
211		} else if (strcmp(dp->scd_path, spa_config_path) != 0) {
212			spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
213			    dp->scd_path, 0, ZPROP_SRC_LOCAL);
214		}
215	}
216}
217
218/*
219 * Get zpool property values.
220 */
221int
222spa_prop_get(spa_t *spa, nvlist_t **nvp)
223{
224	objset_t *mos = spa->spa_meta_objset;
225	zap_cursor_t zc;
226	zap_attribute_t za;
227	int err;
228
229	VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
230
231	mutex_enter(&spa->spa_props_lock);
232
233	/*
234	 * Get properties from the spa config.
235	 */
236	spa_prop_get_config(spa, nvp);
237
238	/* If no pool property object, no more prop to get. */
239	if (mos == NULL || spa->spa_pool_props_object == 0) {
240		mutex_exit(&spa->spa_props_lock);
241		return (0);
242	}
243
244	/*
245	 * Get properties from the MOS pool property object.
246	 */
247	for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
248	    (err = zap_cursor_retrieve(&zc, &za)) == 0;
249	    zap_cursor_advance(&zc)) {
250		uint64_t intval = 0;
251		char *strval = NULL;
252		zprop_source_t src = ZPROP_SRC_DEFAULT;
253		zpool_prop_t prop;
254
255		if ((prop = zpool_name_to_prop(za.za_name)) == ZPROP_INVAL)
256			continue;
257
258		switch (za.za_integer_length) {
259		case 8:
260			/* integer property */
261			if (za.za_first_integer !=
262			    zpool_prop_default_numeric(prop))
263				src = ZPROP_SRC_LOCAL;
264
265			if (prop == ZPOOL_PROP_BOOTFS) {
266				dsl_pool_t *dp;
267				dsl_dataset_t *ds = NULL;
268
269				dp = spa_get_dsl(spa);
270				rw_enter(&dp->dp_config_rwlock, RW_READER);
271				if (err = dsl_dataset_hold_obj(dp,
272				    za.za_first_integer, FTAG, &ds)) {
273					rw_exit(&dp->dp_config_rwlock);
274					break;
275				}
276
277				strval = kmem_alloc(
278				    MAXNAMELEN + strlen(MOS_DIR_NAME) + 1,
279				    KM_SLEEP);
280				dsl_dataset_name(ds, strval);
281				dsl_dataset_rele(ds, FTAG);
282				rw_exit(&dp->dp_config_rwlock);
283			} else {
284				strval = NULL;
285				intval = za.za_first_integer;
286			}
287
288			spa_prop_add_list(*nvp, prop, strval, intval, src);
289
290			if (strval != NULL)
291				kmem_free(strval,
292				    MAXNAMELEN + strlen(MOS_DIR_NAME) + 1);
293
294			break;
295
296		case 1:
297			/* string property */
298			strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
299			err = zap_lookup(mos, spa->spa_pool_props_object,
300			    za.za_name, 1, za.za_num_integers, strval);
301			if (err) {
302				kmem_free(strval, za.za_num_integers);
303				break;
304			}
305			spa_prop_add_list(*nvp, prop, strval, 0, src);
306			kmem_free(strval, za.za_num_integers);
307			break;
308
309		default:
310			break;
311		}
312	}
313	zap_cursor_fini(&zc);
314	mutex_exit(&spa->spa_props_lock);
315out:
316	if (err && err != ENOENT) {
317		nvlist_free(*nvp);
318		*nvp = NULL;
319		return (err);
320	}
321
322	return (0);
323}
324
325/*
326 * Validate the given pool properties nvlist and modify the list
327 * for the property values to be set.
328 */
329static int
330spa_prop_validate(spa_t *spa, nvlist_t *props)
331{
332	nvpair_t *elem;
333	int error = 0, reset_bootfs = 0;
334	uint64_t objnum;
335
336	elem = NULL;
337	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
338		zpool_prop_t prop;
339		char *propname, *strval;
340		uint64_t intval;
341		objset_t *os;
342		char *slash;
343
344		propname = nvpair_name(elem);
345
346		if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL)
347			return (EINVAL);
348
349		switch (prop) {
350		case ZPOOL_PROP_VERSION:
351			error = nvpair_value_uint64(elem, &intval);
352			if (!error &&
353			    (intval < spa_version(spa) || intval > SPA_VERSION))
354				error = EINVAL;
355			break;
356
357		case ZPOOL_PROP_DELEGATION:
358		case ZPOOL_PROP_AUTOREPLACE:
359		case ZPOOL_PROP_LISTSNAPS:
360		case ZPOOL_PROP_AUTOEXPAND:
361			error = nvpair_value_uint64(elem, &intval);
362			if (!error && intval > 1)
363				error = EINVAL;
364			break;
365
366		case ZPOOL_PROP_BOOTFS:
367			/*
368			 * If the pool version is less than SPA_VERSION_BOOTFS,
369			 * or the pool is still being created (version == 0),
370			 * the bootfs property cannot be set.
371			 */
372			if (spa_version(spa) < SPA_VERSION_BOOTFS) {
373				error = ENOTSUP;
374				break;
375			}
376
377			/*
378			 * Make sure the vdev config is bootable
379			 */
380			if (!vdev_is_bootable(spa->spa_root_vdev)) {
381				error = ENOTSUP;
382				break;
383			}
384
385			reset_bootfs = 1;
386
387			error = nvpair_value_string(elem, &strval);
388
389			if (!error) {
390				uint64_t compress;
391
392				if (strval == NULL || strval[0] == '\0') {
393					objnum = zpool_prop_default_numeric(
394					    ZPOOL_PROP_BOOTFS);
395					break;
396				}
397
398				if (error = dmu_objset_hold(strval, FTAG, &os))
399					break;
400
401				/* Must be ZPL and not gzip compressed. */
402
403				if (dmu_objset_type(os) != DMU_OST_ZFS) {
404					error = ENOTSUP;
405				} else if ((error = dsl_prop_get_integer(strval,
406				    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
407				    &compress, NULL)) == 0 &&
408				    !BOOTFS_COMPRESS_VALID(compress)) {
409					error = ENOTSUP;
410				} else {
411					objnum = dmu_objset_id(os);
412				}
413				dmu_objset_rele(os, FTAG);
414			}
415			break;
416
417		case ZPOOL_PROP_FAILUREMODE:
418			error = nvpair_value_uint64(elem, &intval);
419			if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
420			    intval > ZIO_FAILURE_MODE_PANIC))
421				error = EINVAL;
422
423			/*
424			 * This is a special case which only occurs when
425			 * the pool has completely failed. This allows
426			 * the user to change the in-core failmode property
427			 * without syncing it out to disk (I/Os might
428			 * currently be blocked). We do this by returning
429			 * EIO to the caller (spa_prop_set) to trick it
430			 * into thinking we encountered a property validation
431			 * error.
432			 */
433			if (!error && spa_suspended(spa)) {
434				spa->spa_failmode = intval;
435				error = EIO;
436			}
437			break;
438
439		case ZPOOL_PROP_CACHEFILE:
440			if ((error = nvpair_value_string(elem, &strval)) != 0)
441				break;
442
443			if (strval[0] == '\0')
444				break;
445
446			if (strcmp(strval, "none") == 0)
447				break;
448
449			if (strval[0] != '/') {
450				error = EINVAL;
451				break;
452			}
453
454			slash = strrchr(strval, '/');
455			ASSERT(slash != NULL);
456
457			if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
458			    strcmp(slash, "/..") == 0)
459				error = EINVAL;
460			break;
461
462		case ZPOOL_PROP_DEDUPDITTO:
463			if (spa_version(spa) < SPA_VERSION_DEDUP)
464				error = ENOTSUP;
465			else
466				error = nvpair_value_uint64(elem, &intval);
467			if (error == 0 &&
468			    intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
469				error = EINVAL;
470			break;
471		}
472
473		if (error)
474			break;
475	}
476
477	if (!error && reset_bootfs) {
478		error = nvlist_remove(props,
479		    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
480
481		if (!error) {
482			error = nvlist_add_uint64(props,
483			    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
484		}
485	}
486
487	return (error);
488}
489
490void
491spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
492{
493	char *cachefile;
494	spa_config_dirent_t *dp;
495
496	if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
497	    &cachefile) != 0)
498		return;
499
500	dp = kmem_alloc(sizeof (spa_config_dirent_t),
501	    KM_SLEEP);
502
503	if (cachefile[0] == '\0')
504		dp->scd_path = spa_strdup(spa_config_path);
505	else if (strcmp(cachefile, "none") == 0)
506		dp->scd_path = NULL;
507	else
508		dp->scd_path = spa_strdup(cachefile);
509
510	list_insert_head(&spa->spa_config_list, dp);
511	if (need_sync)
512		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
513}
514
515int
516spa_prop_set(spa_t *spa, nvlist_t *nvp)
517{
518	int error;
519	nvpair_t *elem;
520	boolean_t need_sync = B_FALSE;
521	zpool_prop_t prop;
522
523	if ((error = spa_prop_validate(spa, nvp)) != 0)
524		return (error);
525
526	elem = NULL;
527	while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
528		if ((prop = zpool_name_to_prop(
529		    nvpair_name(elem))) == ZPROP_INVAL)
530			return (EINVAL);
531
532		if (prop == ZPOOL_PROP_CACHEFILE || prop == ZPOOL_PROP_ALTROOT)
533			continue;
534
535		need_sync = B_TRUE;
536		break;
537	}
538
539	if (need_sync)
540		return (dsl_sync_task_do(spa_get_dsl(spa), NULL, spa_sync_props,
541		    spa, nvp, 3));
542	else
543		return (0);
544}
545
546/*
547 * If the bootfs property value is dsobj, clear it.
548 */
549void
550spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
551{
552	if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
553		VERIFY(zap_remove(spa->spa_meta_objset,
554		    spa->spa_pool_props_object,
555		    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
556		spa->spa_bootfs = 0;
557	}
558}
559
560/*
561 * ==========================================================================
562 * SPA state manipulation (open/create/destroy/import/export)
563 * ==========================================================================
564 */
565
566static int
567spa_error_entry_compare(const void *a, const void *b)
568{
569	spa_error_entry_t *sa = (spa_error_entry_t *)a;
570	spa_error_entry_t *sb = (spa_error_entry_t *)b;
571	int ret;
572
573	ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
574	    sizeof (zbookmark_t));
575
576	if (ret < 0)
577		return (-1);
578	else if (ret > 0)
579		return (1);
580	else
581		return (0);
582}
583
584/*
585 * Utility function which retrieves copies of the current logs and
586 * re-initializes them in the process.
587 */
588void
589spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
590{
591	ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
592
593	bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
594	bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
595
596	avl_create(&spa->spa_errlist_scrub,
597	    spa_error_entry_compare, sizeof (spa_error_entry_t),
598	    offsetof(spa_error_entry_t, se_avl));
599	avl_create(&spa->spa_errlist_last,
600	    spa_error_entry_compare, sizeof (spa_error_entry_t),
601	    offsetof(spa_error_entry_t, se_avl));
602}
603
604static taskq_t *
605spa_taskq_create(spa_t *spa, const char *name, enum zti_modes mode,
606    uint_t value)
607{
608	uint_t flags = TASKQ_PREPOPULATE;
609	boolean_t batch = B_FALSE;
610
611	switch (mode) {
612	case zti_mode_null:
613		return (NULL);		/* no taskq needed */
614
615	case zti_mode_fixed:
616		ASSERT3U(value, >=, 1);
617		value = MAX(value, 1);
618		break;
619
620	case zti_mode_batch:
621		batch = B_TRUE;
622		flags |= TASKQ_THREADS_CPU_PCT;
623		value = zio_taskq_batch_pct;
624		break;
625
626	case zti_mode_online_percent:
627		flags |= TASKQ_THREADS_CPU_PCT;
628		break;
629
630	default:
631		panic("unrecognized mode for %s taskq (%u:%u) in "
632		    "spa_activate()",
633		    name, mode, value);
634		break;
635	}
636
637	if (zio_taskq_sysdc && spa->spa_proc != &p0) {
638		if (batch)
639			flags |= TASKQ_DC_BATCH;
640
641		return (taskq_create_sysdc(name, value, 50, INT_MAX,
642		    spa->spa_proc, zio_taskq_basedc, flags));
643	}
644	return (taskq_create_proc(name, value, maxclsyspri, 50, INT_MAX,
645	    spa->spa_proc, flags));
646}
647
648static void
649spa_create_zio_taskqs(spa_t *spa)
650{
651	for (int t = 0; t < ZIO_TYPES; t++) {
652		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
653			const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
654			enum zti_modes mode = ztip->zti_mode;
655			uint_t value = ztip->zti_value;
656			char name[32];
657
658			(void) snprintf(name, sizeof (name),
659			    "%s_%s", zio_type_name[t], zio_taskq_types[q]);
660
661			spa->spa_zio_taskq[t][q] =
662			    spa_taskq_create(spa, name, mode, value);
663		}
664	}
665}
666
667#ifdef _KERNEL
668static void
669spa_thread(void *arg)
670{
671	callb_cpr_t cprinfo;
672
673	spa_t *spa = arg;
674	user_t *pu = PTOU(curproc);
675
676	CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
677	    spa->spa_name);
678
679	ASSERT(curproc != &p0);
680	(void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
681	    "zpool-%s", spa->spa_name);
682	(void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
683
684	/* bind this thread to the requested psrset */
685	if (zio_taskq_psrset_bind != PS_NONE) {
686		pool_lock();
687		mutex_enter(&cpu_lock);
688		mutex_enter(&pidlock);
689		mutex_enter(&curproc->p_lock);
690
691		if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
692		    0, NULL, NULL) == 0)  {
693			curthread->t_bind_pset = zio_taskq_psrset_bind;
694		} else {
695			cmn_err(CE_WARN,
696			    "Couldn't bind process for zfs pool \"%s\" to "
697			    "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
698		}
699
700		mutex_exit(&curproc->p_lock);
701		mutex_exit(&pidlock);
702		mutex_exit(&cpu_lock);
703		pool_unlock();
704	}
705
706	if (zio_taskq_sysdc) {
707		sysdc_thread_enter(curthread, 100, 0);
708	}
709
710	spa->spa_proc = curproc;
711	spa->spa_did = curthread->t_did;
712
713	spa_create_zio_taskqs(spa);
714
715	mutex_enter(&spa->spa_proc_lock);
716	ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
717
718	spa->spa_proc_state = SPA_PROC_ACTIVE;
719	cv_broadcast(&spa->spa_proc_cv);
720
721	CALLB_CPR_SAFE_BEGIN(&cprinfo);
722	while (spa->spa_proc_state == SPA_PROC_ACTIVE)
723		cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
724	CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
725
726	ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
727	spa->spa_proc_state = SPA_PROC_GONE;
728	spa->spa_proc = &p0;
729	cv_broadcast(&spa->spa_proc_cv);
730	CALLB_CPR_EXIT(&cprinfo);	/* drops spa_proc_lock */
731
732	mutex_enter(&curproc->p_lock);
733	lwp_exit();
734}
735#endif
736
737/*
738 * Activate an uninitialized pool.
739 */
740static void
741spa_activate(spa_t *spa, int mode)
742{
743	ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
744
745	spa->spa_state = POOL_STATE_ACTIVE;
746	spa->spa_mode = mode;
747
748	spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
749	spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
750
751	/* Try to create a covering process */
752	mutex_enter(&spa->spa_proc_lock);
753	ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
754	ASSERT(spa->spa_proc == &p0);
755	spa->spa_did = 0;
756
757	/* Only create a process if we're going to be around a while. */
758	if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
759		if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
760		    NULL, 0) == 0) {
761			spa->spa_proc_state = SPA_PROC_CREATED;
762			while (spa->spa_proc_state == SPA_PROC_CREATED) {
763				cv_wait(&spa->spa_proc_cv,
764				    &spa->spa_proc_lock);
765			}
766			ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
767			ASSERT(spa->spa_proc != &p0);
768			ASSERT(spa->spa_did != 0);
769		} else {
770#ifdef _KERNEL
771			cmn_err(CE_WARN,
772			    "Couldn't create process for zfs pool \"%s\"\n",
773			    spa->spa_name);
774#endif
775		}
776	}
777	mutex_exit(&spa->spa_proc_lock);
778
779	/* If we didn't create a process, we need to create our taskqs. */
780	if (spa->spa_proc == &p0) {
781		spa_create_zio_taskqs(spa);
782	}
783
784	list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
785	    offsetof(vdev_t, vdev_config_dirty_node));
786	list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
787	    offsetof(vdev_t, vdev_state_dirty_node));
788
789	txg_list_create(&spa->spa_vdev_txg_list,
790	    offsetof(struct vdev, vdev_txg_node));
791
792	avl_create(&spa->spa_errlist_scrub,
793	    spa_error_entry_compare, sizeof (spa_error_entry_t),
794	    offsetof(spa_error_entry_t, se_avl));
795	avl_create(&spa->spa_errlist_last,
796	    spa_error_entry_compare, sizeof (spa_error_entry_t),
797	    offsetof(spa_error_entry_t, se_avl));
798}
799
800/*
801 * Opposite of spa_activate().
802 */
803static void
804spa_deactivate(spa_t *spa)
805{
806	ASSERT(spa->spa_sync_on == B_FALSE);
807	ASSERT(spa->spa_dsl_pool == NULL);
808	ASSERT(spa->spa_root_vdev == NULL);
809	ASSERT(spa->spa_async_zio_root == NULL);
810	ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
811
812	txg_list_destroy(&spa->spa_vdev_txg_list);
813
814	list_destroy(&spa->spa_config_dirty_list);
815	list_destroy(&spa->spa_state_dirty_list);
816
817	for (int t = 0; t < ZIO_TYPES; t++) {
818		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
819			if (spa->spa_zio_taskq[t][q] != NULL)
820				taskq_destroy(spa->spa_zio_taskq[t][q]);
821			spa->spa_zio_taskq[t][q] = NULL;
822		}
823	}
824
825	metaslab_class_destroy(spa->spa_normal_class);
826	spa->spa_normal_class = NULL;
827
828	metaslab_class_destroy(spa->spa_log_class);
829	spa->spa_log_class = NULL;
830
831	/*
832	 * If this was part of an import or the open otherwise failed, we may
833	 * still have errors left in the queues.  Empty them just in case.
834	 */
835	spa_errlog_drain(spa);
836
837	avl_destroy(&spa->spa_errlist_scrub);
838	avl_destroy(&spa->spa_errlist_last);
839
840	spa->spa_state = POOL_STATE_UNINITIALIZED;
841
842	mutex_enter(&spa->spa_proc_lock);
843	if (spa->spa_proc_state != SPA_PROC_NONE) {
844		ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
845		spa->spa_proc_state = SPA_PROC_DEACTIVATE;
846		cv_broadcast(&spa->spa_proc_cv);
847		while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
848			ASSERT(spa->spa_proc != &p0);
849			cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
850		}
851		ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
852		spa->spa_proc_state = SPA_PROC_NONE;
853	}
854	ASSERT(spa->spa_proc == &p0);
855	mutex_exit(&spa->spa_proc_lock);
856
857	/*
858	 * We want to make sure spa_thread() has actually exited the ZFS
859	 * module, so that the module can't be unloaded out from underneath
860	 * it.
861	 */
862	if (spa->spa_did != 0) {
863		thread_join(spa->spa_did);
864		spa->spa_did = 0;
865	}
866}
867
868/*
869 * Verify a pool configuration, and construct the vdev tree appropriately.  This
870 * will create all the necessary vdevs in the appropriate layout, with each vdev
871 * in the CLOSED state.  This will prep the pool before open/creation/import.
872 * All vdev validation is done by the vdev_alloc() routine.
873 */
874static int
875spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
876    uint_t id, int atype)
877{
878	nvlist_t **child;
879	uint_t children;
880	int error;
881
882	if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
883		return (error);
884
885	if ((*vdp)->vdev_ops->vdev_op_leaf)
886		return (0);
887
888	error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
889	    &child, &children);
890
891	if (error == ENOENT)
892		return (0);
893
894	if (error) {
895		vdev_free(*vdp);
896		*vdp = NULL;
897		return (EINVAL);
898	}
899
900	for (int c = 0; c < children; c++) {
901		vdev_t *vd;
902		if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
903		    atype)) != 0) {
904			vdev_free(*vdp);
905			*vdp = NULL;
906			return (error);
907		}
908	}
909
910	ASSERT(*vdp != NULL);
911
912	return (0);
913}
914
915/*
916 * Opposite of spa_load().
917 */
918static void
919spa_unload(spa_t *spa)
920{
921	int i;
922
923	ASSERT(MUTEX_HELD(&spa_namespace_lock));
924
925	/*
926	 * Stop async tasks.
927	 */
928	spa_async_suspend(spa);
929
930	/*
931	 * Stop syncing.
932	 */
933	if (spa->spa_sync_on) {
934		txg_sync_stop(spa->spa_dsl_pool);
935		spa->spa_sync_on = B_FALSE;
936	}
937
938	/*
939	 * Wait for any outstanding async I/O to complete.
940	 */
941	if (spa->spa_async_zio_root != NULL) {
942		(void) zio_wait(spa->spa_async_zio_root);
943		spa->spa_async_zio_root = NULL;
944	}
945
946	/*
947	 * Close the dsl pool.
948	 */
949	if (spa->spa_dsl_pool) {
950		dsl_pool_close(spa->spa_dsl_pool);
951		spa->spa_dsl_pool = NULL;
952		spa->spa_meta_objset = NULL;
953	}
954
955	ddt_unload(spa);
956
957	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
958
959	/*
960	 * Drop and purge level 2 cache
961	 */
962	spa_l2cache_drop(spa);
963
964	/*
965	 * Close all vdevs.
966	 */
967	if (spa->spa_root_vdev)
968		vdev_free(spa->spa_root_vdev);
969	ASSERT(spa->spa_root_vdev == NULL);
970
971	for (i = 0; i < spa->spa_spares.sav_count; i++)
972		vdev_free(spa->spa_spares.sav_vdevs[i]);
973	if (spa->spa_spares.sav_vdevs) {
974		kmem_free(spa->spa_spares.sav_vdevs,
975		    spa->spa_spares.sav_count * sizeof (void *));
976		spa->spa_spares.sav_vdevs = NULL;
977	}
978	if (spa->spa_spares.sav_config) {
979		nvlist_free(spa->spa_spares.sav_config);
980		spa->spa_spares.sav_config = NULL;
981	}
982	spa->spa_spares.sav_count = 0;
983
984	for (i = 0; i < spa->spa_l2cache.sav_count; i++)
985		vdev_free(spa->spa_l2cache.sav_vdevs[i]);
986	if (spa->spa_l2cache.sav_vdevs) {
987		kmem_free(spa->spa_l2cache.sav_vdevs,
988		    spa->spa_l2cache.sav_count * sizeof (void *));
989		spa->spa_l2cache.sav_vdevs = NULL;
990	}
991	if (spa->spa_l2cache.sav_config) {
992		nvlist_free(spa->spa_l2cache.sav_config);
993		spa->spa_l2cache.sav_config = NULL;
994	}
995	spa->spa_l2cache.sav_count = 0;
996
997	spa->spa_async_suspended = 0;
998
999	spa_config_exit(spa, SCL_ALL, FTAG);
1000}
1001
1002/*
1003 * Load (or re-load) the current list of vdevs describing the active spares for
1004 * this pool.  When this is called, we have some form of basic information in
1005 * 'spa_spares.sav_config'.  We parse this into vdevs, try to open them, and
1006 * then re-generate a more complete list including status information.
1007 */
1008static void
1009spa_load_spares(spa_t *spa)
1010{
1011	nvlist_t **spares;
1012	uint_t nspares;
1013	int i;
1014	vdev_t *vd, *tvd;
1015
1016	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1017
1018	/*
1019	 * First, close and free any existing spare vdevs.
1020	 */
1021	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1022		vd = spa->spa_spares.sav_vdevs[i];
1023
1024		/* Undo the call to spa_activate() below */
1025		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1026		    B_FALSE)) != NULL && tvd->vdev_isspare)
1027			spa_spare_remove(tvd);
1028		vdev_close(vd);
1029		vdev_free(vd);
1030	}
1031
1032	if (spa->spa_spares.sav_vdevs)
1033		kmem_free(spa->spa_spares.sav_vdevs,
1034		    spa->spa_spares.sav_count * sizeof (void *));
1035
1036	if (spa->spa_spares.sav_config == NULL)
1037		nspares = 0;
1038	else
1039		VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1040		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1041
1042	spa->spa_spares.sav_count = (int)nspares;
1043	spa->spa_spares.sav_vdevs = NULL;
1044
1045	if (nspares == 0)
1046		return;
1047
1048	/*
1049	 * Construct the array of vdevs, opening them to get status in the
1050	 * process.   For each spare, there is potentially two different vdev_t
1051	 * structures associated with it: one in the list of spares (used only
1052	 * for basic validation purposes) and one in the active vdev
1053	 * configuration (if it's spared in).  During this phase we open and
1054	 * validate each vdev on the spare list.  If the vdev also exists in the
1055	 * active configuration, then we also mark this vdev as an active spare.
1056	 */
1057	spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1058	    KM_SLEEP);
1059	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1060		VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1061		    VDEV_ALLOC_SPARE) == 0);
1062		ASSERT(vd != NULL);
1063
1064		spa->spa_spares.sav_vdevs[i] = vd;
1065
1066		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1067		    B_FALSE)) != NULL) {
1068			if (!tvd->vdev_isspare)
1069				spa_spare_add(tvd);
1070
1071			/*
1072			 * We only mark the spare active if we were successfully
1073			 * able to load the vdev.  Otherwise, importing a pool
1074			 * with a bad active spare would result in strange
1075			 * behavior, because multiple pool would think the spare
1076			 * is actively in use.
1077			 *
1078			 * There is a vulnerability here to an equally bizarre
1079			 * circumstance, where a dead active spare is later
1080			 * brought back to life (onlined or otherwise).  Given
1081			 * the rarity of this scenario, and the extra complexity
1082			 * it adds, we ignore the possibility.
1083			 */
1084			if (!vdev_is_dead(tvd))
1085				spa_spare_activate(tvd);
1086		}
1087
1088		vd->vdev_top = vd;
1089		vd->vdev_aux = &spa->spa_spares;
1090
1091		if (vdev_open(vd) != 0)
1092			continue;
1093
1094		if (vdev_validate_aux(vd) == 0)
1095			spa_spare_add(vd);
1096	}
1097
1098	/*
1099	 * Recompute the stashed list of spares, with status information
1100	 * this time.
1101	 */
1102	VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1103	    DATA_TYPE_NVLIST_ARRAY) == 0);
1104
1105	spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1106	    KM_SLEEP);
1107	for (i = 0; i < spa->spa_spares.sav_count; i++)
1108		spares[i] = vdev_config_generate(spa,
1109		    spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1110	VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1111	    ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1112	for (i = 0; i < spa->spa_spares.sav_count; i++)
1113		nvlist_free(spares[i]);
1114	kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1115}
1116
1117/*
1118 * Load (or re-load) the current list of vdevs describing the active l2cache for
1119 * this pool.  When this is called, we have some form of basic information in
1120 * 'spa_l2cache.sav_config'.  We parse this into vdevs, try to open them, and
1121 * then re-generate a more complete list including status information.
1122 * Devices which are already active have their details maintained, and are
1123 * not re-opened.
1124 */
1125static void
1126spa_load_l2cache(spa_t *spa)
1127{
1128	nvlist_t **l2cache;
1129	uint_t nl2cache;
1130	int i, j, oldnvdevs;
1131	uint64_t guid;
1132	vdev_t *vd, **oldvdevs, **newvdevs;
1133	spa_aux_vdev_t *sav = &spa->spa_l2cache;
1134
1135	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1136
1137	if (sav->sav_config != NULL) {
1138		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1139		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1140		newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1141	} else {
1142		nl2cache = 0;
1143	}
1144
1145	oldvdevs = sav->sav_vdevs;
1146	oldnvdevs = sav->sav_count;
1147	sav->sav_vdevs = NULL;
1148	sav->sav_count = 0;
1149
1150	/*
1151	 * Process new nvlist of vdevs.
1152	 */
1153	for (i = 0; i < nl2cache; i++) {
1154		VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1155		    &guid) == 0);
1156
1157		newvdevs[i] = NULL;
1158		for (j = 0; j < oldnvdevs; j++) {
1159			vd = oldvdevs[j];
1160			if (vd != NULL && guid == vd->vdev_guid) {
1161				/*
1162				 * Retain previous vdev for add/remove ops.
1163				 */
1164				newvdevs[i] = vd;
1165				oldvdevs[j] = NULL;
1166				break;
1167			}
1168		}
1169
1170		if (newvdevs[i] == NULL) {
1171			/*
1172			 * Create new vdev
1173			 */
1174			VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1175			    VDEV_ALLOC_L2CACHE) == 0);
1176			ASSERT(vd != NULL);
1177			newvdevs[i] = vd;
1178
1179			/*
1180			 * Commit this vdev as an l2cache device,
1181			 * even if it fails to open.
1182			 */
1183			spa_l2cache_add(vd);
1184
1185			vd->vdev_top = vd;
1186			vd->vdev_aux = sav;
1187
1188			spa_l2cache_activate(vd);
1189
1190			if (vdev_open(vd) != 0)
1191				continue;
1192
1193			(void) vdev_validate_aux(vd);
1194
1195			if (!vdev_is_dead(vd))
1196				l2arc_add_vdev(spa, vd);
1197		}
1198	}
1199
1200	/*
1201	 * Purge vdevs that were dropped
1202	 */
1203	for (i = 0; i < oldnvdevs; i++) {
1204		uint64_t pool;
1205
1206		vd = oldvdevs[i];
1207		if (vd != NULL) {
1208			if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1209			    pool != 0ULL && l2arc_vdev_present(vd))
1210				l2arc_remove_vdev(vd);
1211			(void) vdev_close(vd);
1212			spa_l2cache_remove(vd);
1213		}
1214	}
1215
1216	if (oldvdevs)
1217		kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1218
1219	if (sav->sav_config == NULL)
1220		goto out;
1221
1222	sav->sav_vdevs = newvdevs;
1223	sav->sav_count = (int)nl2cache;
1224
1225	/*
1226	 * Recompute the stashed list of l2cache devices, with status
1227	 * information this time.
1228	 */
1229	VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1230	    DATA_TYPE_NVLIST_ARRAY) == 0);
1231
1232	l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1233	for (i = 0; i < sav->sav_count; i++)
1234		l2cache[i] = vdev_config_generate(spa,
1235		    sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1236	VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1237	    ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1238out:
1239	for (i = 0; i < sav->sav_count; i++)
1240		nvlist_free(l2cache[i]);
1241	if (sav->sav_count)
1242		kmem_free(l2cache, sav->sav_count * sizeof (void *));
1243}
1244
1245static int
1246load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1247{
1248	dmu_buf_t *db;
1249	char *packed = NULL;
1250	size_t nvsize = 0;
1251	int error;
1252	*value = NULL;
1253
1254	VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
1255	nvsize = *(uint64_t *)db->db_data;
1256	dmu_buf_rele(db, FTAG);
1257
1258	packed = kmem_alloc(nvsize, KM_SLEEP);
1259	error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1260	    DMU_READ_PREFETCH);
1261	if (error == 0)
1262		error = nvlist_unpack(packed, nvsize, value, 0);
1263	kmem_free(packed, nvsize);
1264
1265	return (error);
1266}
1267
1268/*
1269 * Checks to see if the given vdev could not be opened, in which case we post a
1270 * sysevent to notify the autoreplace code that the device has been removed.
1271 */
1272static void
1273spa_check_removed(vdev_t *vd)
1274{
1275	for (int c = 0; c < vd->vdev_children; c++)
1276		spa_check_removed(vd->vdev_child[c]);
1277
1278	if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd)) {
1279		zfs_post_autoreplace(vd->vdev_spa, vd);
1280		spa_event_notify(vd->vdev_spa, vd, ESC_ZFS_VDEV_CHECK);
1281	}
1282}
1283
1284/*
1285 * Load the slog device state from the config object since it's possible
1286 * that the label does not contain the most up-to-date information.
1287 */
1288void
1289spa_load_log_state(spa_t *spa, nvlist_t *nv)
1290{
1291	vdev_t *ovd, *rvd = spa->spa_root_vdev;
1292
1293	/*
1294	 * Load the original root vdev tree from the passed config.
1295	 */
1296	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1297	VERIFY(spa_config_parse(spa, &ovd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
1298
1299	for (int c = 0; c < rvd->vdev_children; c++) {
1300		vdev_t *cvd = rvd->vdev_child[c];
1301		if (cvd->vdev_islog)
1302			vdev_load_log_state(cvd, ovd->vdev_child[c]);
1303	}
1304	vdev_free(ovd);
1305	spa_config_exit(spa, SCL_ALL, FTAG);
1306}
1307
1308/*
1309 * Check for missing log devices
1310 */
1311int
1312spa_check_logs(spa_t *spa)
1313{
1314	switch (spa->spa_log_state) {
1315	case SPA_LOG_MISSING:
1316		/* need to recheck in case slog has been restored */
1317	case SPA_LOG_UNKNOWN:
1318		if (dmu_objset_find(spa->spa_name, zil_check_log_chain, NULL,
1319		    DS_FIND_CHILDREN)) {
1320			spa_set_log_state(spa, SPA_LOG_MISSING);
1321			return (1);
1322		}
1323		break;
1324	}
1325	return (0);
1326}
1327
1328static boolean_t
1329spa_passivate_log(spa_t *spa)
1330{
1331	vdev_t *rvd = spa->spa_root_vdev;
1332	boolean_t slog_found = B_FALSE;
1333
1334	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1335
1336	if (!spa_has_slogs(spa))
1337		return (B_FALSE);
1338
1339	for (int c = 0; c < rvd->vdev_children; c++) {
1340		vdev_t *tvd = rvd->vdev_child[c];
1341		metaslab_group_t *mg = tvd->vdev_mg;
1342
1343		if (tvd->vdev_islog) {
1344			metaslab_group_passivate(mg);
1345			slog_found = B_TRUE;
1346		}
1347	}
1348
1349	return (slog_found);
1350}
1351
1352static void
1353spa_activate_log(spa_t *spa)
1354{
1355	vdev_t *rvd = spa->spa_root_vdev;
1356
1357	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1358
1359	for (int c = 0; c < rvd->vdev_children; c++) {
1360		vdev_t *tvd = rvd->vdev_child[c];
1361		metaslab_group_t *mg = tvd->vdev_mg;
1362
1363		if (tvd->vdev_islog)
1364			metaslab_group_activate(mg);
1365	}
1366}
1367
1368int
1369spa_offline_log(spa_t *spa)
1370{
1371	int error = 0;
1372
1373	if ((error = dmu_objset_find(spa_name(spa), zil_vdev_offline,
1374	    NULL, DS_FIND_CHILDREN)) == 0) {
1375
1376		/*
1377		 * We successfully offlined the log device, sync out the
1378		 * current txg so that the "stubby" block can be removed
1379		 * by zil_sync().
1380		 */
1381		txg_wait_synced(spa->spa_dsl_pool, 0);
1382	}
1383	return (error);
1384}
1385
1386static void
1387spa_aux_check_removed(spa_aux_vdev_t *sav)
1388{
1389	for (int i = 0; i < sav->sav_count; i++)
1390		spa_check_removed(sav->sav_vdevs[i]);
1391}
1392
1393void
1394spa_claim_notify(zio_t *zio)
1395{
1396	spa_t *spa = zio->io_spa;
1397
1398	if (zio->io_error)
1399		return;
1400
1401	mutex_enter(&spa->spa_props_lock);	/* any mutex will do */
1402	if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1403		spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1404	mutex_exit(&spa->spa_props_lock);
1405}
1406
1407typedef struct spa_load_error {
1408	uint64_t	sle_meta_count;
1409	uint64_t	sle_data_count;
1410} spa_load_error_t;
1411
1412static void
1413spa_load_verify_done(zio_t *zio)
1414{
1415	blkptr_t *bp = zio->io_bp;
1416	spa_load_error_t *sle = zio->io_private;
1417	dmu_object_type_t type = BP_GET_TYPE(bp);
1418	int error = zio->io_error;
1419
1420	if (error) {
1421		if ((BP_GET_LEVEL(bp) != 0 || dmu_ot[type].ot_metadata) &&
1422		    type != DMU_OT_INTENT_LOG)
1423			atomic_add_64(&sle->sle_meta_count, 1);
1424		else
1425			atomic_add_64(&sle->sle_data_count, 1);
1426	}
1427	zio_data_buf_free(zio->io_data, zio->io_size);
1428}
1429
1430/*ARGSUSED*/
1431static int
1432spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1433    arc_buf_t *pbuf, const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
1434{
1435	if (bp != NULL) {
1436		zio_t *rio = arg;
1437		size_t size = BP_GET_PSIZE(bp);
1438		void *data = zio_data_buf_alloc(size);
1439
1440		zio_nowait(zio_read(rio, spa, bp, data, size,
1441		    spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
1442		    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
1443		    ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
1444	}
1445	return (0);
1446}
1447
1448static int
1449spa_load_verify(spa_t *spa)
1450{
1451	zio_t *rio;
1452	spa_load_error_t sle = { 0 };
1453	zpool_rewind_policy_t policy;
1454	boolean_t verify_ok = B_FALSE;
1455	int error;
1456
1457	zpool_get_rewind_policy(spa->spa_config, &policy);
1458
1459	if (policy.zrp_request & ZPOOL_NEVER_REWIND)
1460		return (0);
1461
1462	rio = zio_root(spa, NULL, &sle,
1463	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
1464
1465	error = traverse_pool(spa, spa->spa_verify_min_txg,
1466	    TRAVERSE_PRE | TRAVERSE_PREFETCH, spa_load_verify_cb, rio);
1467
1468	(void) zio_wait(rio);
1469
1470	spa->spa_load_meta_errors = sle.sle_meta_count;
1471	spa->spa_load_data_errors = sle.sle_data_count;
1472
1473	if (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
1474	    sle.sle_data_count <= policy.zrp_maxdata) {
1475		verify_ok = B_TRUE;
1476		spa->spa_load_txg = spa->spa_uberblock.ub_txg;
1477		spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
1478	} else {
1479		spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
1480	}
1481
1482	if (error) {
1483		if (error != ENXIO && error != EIO)
1484			error = EIO;
1485		return (error);
1486	}
1487
1488	return (verify_ok ? 0 : EIO);
1489}
1490
1491/*
1492 * Find a value in the pool props object.
1493 */
1494static void
1495spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
1496{
1497	(void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
1498	    zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
1499}
1500
1501/*
1502 * Find a value in the pool directory object.
1503 */
1504static int
1505spa_dir_prop(spa_t *spa, const char *name, uint64_t *val)
1506{
1507	return (zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1508	    name, sizeof (uint64_t), 1, val));
1509}
1510
1511static int
1512spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
1513{
1514	vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
1515	return (err);
1516}
1517
1518/*
1519 * Fix up config after a partly-completed split.  This is done with the
1520 * ZPOOL_CONFIG_SPLIT nvlist.  Both the splitting pool and the split-off
1521 * pool have that entry in their config, but only the splitting one contains
1522 * a list of all the guids of the vdevs that are being split off.
1523 *
1524 * This function determines what to do with that list: either rejoin
1525 * all the disks to the pool, or complete the splitting process.  To attempt
1526 * the rejoin, each disk that is offlined is marked online again, and
1527 * we do a reopen() call.  If the vdev label for every disk that was
1528 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
1529 * then we call vdev_split() on each disk, and complete the split.
1530 *
1531 * Otherwise we leave the config alone, with all the vdevs in place in
1532 * the original pool.
1533 */
1534static void
1535spa_try_repair(spa_t *spa, nvlist_t *config)
1536{
1537	uint_t extracted;
1538	uint64_t *glist;
1539	uint_t i, gcount;
1540	nvlist_t *nvl;
1541	vdev_t **vd;
1542	boolean_t attempt_reopen;
1543
1544	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
1545		return;
1546
1547	/* check that the config is complete */
1548	if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
1549	    &glist, &gcount) != 0)
1550		return;
1551
1552	vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
1553
1554	/* attempt to online all the vdevs & validate */
1555	attempt_reopen = B_TRUE;
1556	for (i = 0; i < gcount; i++) {
1557		if (glist[i] == 0)	/* vdev is hole */
1558			continue;
1559
1560		vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
1561		if (vd[i] == NULL) {
1562			/*
1563			 * Don't bother attempting to reopen the disks;
1564			 * just do the split.
1565			 */
1566			attempt_reopen = B_FALSE;
1567		} else {
1568			/* attempt to re-online it */
1569			vd[i]->vdev_offline = B_FALSE;
1570		}
1571	}
1572
1573	if (attempt_reopen) {
1574		vdev_reopen(spa->spa_root_vdev);
1575
1576		/* check each device to see what state it's in */
1577		for (extracted = 0, i = 0; i < gcount; i++) {
1578			if (vd[i] != NULL &&
1579			    vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
1580				break;
1581			++extracted;
1582		}
1583	}
1584
1585	/*
1586	 * If every disk has been moved to the new pool, or if we never
1587	 * even attempted to look at them, then we split them off for
1588	 * good.
1589	 */
1590	if (!attempt_reopen || gcount == extracted) {
1591		for (i = 0; i < gcount; i++)
1592			if (vd[i] != NULL)
1593				vdev_split(vd[i]);
1594		vdev_reopen(spa->spa_root_vdev);
1595	}
1596
1597	kmem_free(vd, gcount * sizeof (vdev_t *));
1598}
1599
1600static int
1601spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type,
1602    boolean_t mosconfig)
1603{
1604	nvlist_t *config = spa->spa_config;
1605	char *ereport = FM_EREPORT_ZFS_POOL;
1606	int error;
1607	uint64_t pool_guid;
1608	nvlist_t *nvl;
1609
1610	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
1611		return (EINVAL);
1612
1613	/*
1614	 * Versioning wasn't explicitly added to the label until later, so if
1615	 * it's not present treat it as the initial version.
1616	 */
1617	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
1618	    &spa->spa_ubsync.ub_version) != 0)
1619		spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
1620
1621	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
1622	    &spa->spa_config_txg);
1623
1624	if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
1625	    spa_guid_exists(pool_guid, 0)) {
1626		error = EEXIST;
1627	} else {
1628		spa->spa_load_guid = pool_guid;
1629
1630		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
1631		    &nvl) == 0) {
1632			VERIFY(nvlist_dup(nvl, &spa->spa_config_splitting,
1633			    KM_SLEEP) == 0);
1634		}
1635
1636		error = spa_load_impl(spa, pool_guid, config, state, type,
1637		    mosconfig, &ereport);
1638	}
1639
1640	spa->spa_minref = refcount_count(&spa->spa_refcount);
1641	if (error && error != EBADF)
1642		zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
1643	spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
1644	spa->spa_ena = 0;
1645
1646	return (error);
1647}
1648
1649/*
1650 * Load an existing storage pool, using the pool's builtin spa_config as a
1651 * source of configuration information.
1652 */
1653static int
1654spa_load_impl(spa_t *spa, uint64_t pool_guid, nvlist_t *config,
1655    spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
1656    char **ereport)
1657{
1658	int error = 0;
1659	nvlist_t *nvroot = NULL;
1660	vdev_t *rvd;
1661	uberblock_t *ub = &spa->spa_uberblock;
1662	uint64_t config_cache_txg = spa->spa_config_txg;
1663	int orig_mode = spa->spa_mode;
1664	int parse;
1665
1666	/*
1667	 * If this is an untrusted config, access the pool in read-only mode.
1668	 * This prevents things like resilvering recently removed devices.
1669	 */
1670	if (!mosconfig)
1671		spa->spa_mode = FREAD;
1672
1673	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1674
1675	spa->spa_load_state = state;
1676
1677	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot))
1678		return (EINVAL);
1679
1680	parse = (type == SPA_IMPORT_EXISTING ?
1681	    VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
1682
1683	/*
1684	 * Create "The Godfather" zio to hold all async IOs
1685	 */
1686	spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
1687	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_GODFATHER);
1688
1689	/*
1690	 * Parse the configuration into a vdev tree.  We explicitly set the
1691	 * value that will be returned by spa_version() since parsing the
1692	 * configuration requires knowing the version number.
1693	 */
1694	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1695	error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, parse);
1696	spa_config_exit(spa, SCL_ALL, FTAG);
1697
1698	if (error != 0)
1699		return (error);
1700
1701	ASSERT(spa->spa_root_vdev == rvd);
1702
1703	if (type != SPA_IMPORT_ASSEMBLE) {
1704		ASSERT(spa_guid(spa) == pool_guid);
1705	}
1706
1707	/*
1708	 * Try to open all vdevs, loading each label in the process.
1709	 */
1710	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1711	error = vdev_open(rvd);
1712	spa_config_exit(spa, SCL_ALL, FTAG);
1713	if (error != 0)
1714		return (error);
1715
1716	/*
1717	 * We need to validate the vdev labels against the configuration that
1718	 * we have in hand, which is dependent on the setting of mosconfig. If
1719	 * mosconfig is true then we're validating the vdev labels based on
1720	 * that config.  Otherwise, we're validating against the cached config
1721	 * (zpool.cache) that was read when we loaded the zfs module, and then
1722	 * later we will recursively call spa_load() and validate against
1723	 * the vdev config.
1724	 *
1725	 * If we're assembling a new pool that's been split off from an
1726	 * existing pool, the labels haven't yet been updated so we skip
1727	 * validation for now.
1728	 */
1729	if (type != SPA_IMPORT_ASSEMBLE) {
1730		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1731		error = vdev_validate(rvd);
1732		spa_config_exit(spa, SCL_ALL, FTAG);
1733
1734		if (error != 0)
1735			return (error);
1736
1737		if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
1738			return (ENXIO);
1739	}
1740
1741	/*
1742	 * Find the best uberblock.
1743	 */
1744	vdev_uberblock_load(NULL, rvd, ub);
1745
1746	/*
1747	 * If we weren't able to find a single valid uberblock, return failure.
1748	 */
1749	if (ub->ub_txg == 0)
1750		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
1751
1752	/*
1753	 * If the pool is newer than the code, we can't open it.
1754	 */
1755	if (ub->ub_version > SPA_VERSION)
1756		return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
1757
1758	/*
1759	 * If the vdev guid sum doesn't match the uberblock, we have an
1760	 * incomplete configuration.
1761	 */
1762	if (mosconfig && type != SPA_IMPORT_ASSEMBLE &&
1763	    rvd->vdev_guid_sum != ub->ub_guid_sum)
1764		return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
1765
1766	if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
1767		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1768		spa_try_repair(spa, config);
1769		spa_config_exit(spa, SCL_ALL, FTAG);
1770		nvlist_free(spa->spa_config_splitting);
1771		spa->spa_config_splitting = NULL;
1772	}
1773
1774	/*
1775	 * Initialize internal SPA structures.
1776	 */
1777	spa->spa_state = POOL_STATE_ACTIVE;
1778	spa->spa_ubsync = spa->spa_uberblock;
1779	spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
1780	    TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
1781