zinject.c revision 248369
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 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2012 by Delphix. All rights reserved.
24 */
25
26/*
27 * ZFS Fault Injector
28 *
29 * This userland component takes a set of options and uses libzpool to translate
30 * from a user-visible object type and name to an internal representation.
31 * There are two basic types of faults: device faults and data faults.
32 *
33 *
34 * DEVICE FAULTS
35 *
36 * Errors can be injected into a particular vdev using the '-d' option.  This
37 * option takes a path or vdev GUID to uniquely identify the device within a
38 * pool.  There are two types of errors that can be injected, EIO and ENXIO,
39 * that can be controlled through the '-e' option.  The default is ENXIO.  For
40 * EIO failures, any attempt to read data from the device will return EIO, but
41 * subsequent attempt to reopen the device will succeed.  For ENXIO failures,
42 * any attempt to read from the device will return EIO, but any attempt to
43 * reopen the device will also return ENXIO.
44 * For label faults, the -L option must be specified. This allows faults
45 * to be injected into either the nvlist, uberblock, pad1, or pad2 region
46 * of all the labels for the specified device.
47 *
48 * This form of the command looks like:
49 *
50 * 	zinject -d device [-e errno] [-L <uber | nvlist | pad1 | pad2>] pool
51 *
52 *
53 * DATA FAULTS
54 *
55 * We begin with a tuple of the form:
56 *
57 * 	<type,level,range,object>
58 *
59 * 	type	A string describing the type of data to target.  Each type
60 * 		implicitly describes how to interpret 'object'. Currently,
61 * 		the following values are supported:
62 *
63 * 		data		User data for a file
64 * 		dnode		Dnode for a file or directory
65 *
66 *		The following MOS objects are special.  Instead of injecting
67 *		errors on a particular object or blkid, we inject errors across
68 *		all objects of the given type.
69 *
70 * 		mos		Any data in the MOS
71 * 		mosdir		object directory
72 * 		config		pool configuration
73 * 		bpobj		blkptr list
74 * 		spacemap	spacemap
75 * 		metaslab	metaslab
76 * 		errlog		persistent error log
77 *
78 * 	level	Object level.  Defaults to '0', not applicable to all types.  If
79 * 		a range is given, this corresponds to the indirect block
80 * 		corresponding to the specific range.
81 *
82 *	range	A numerical range [start,end) within the object.  Defaults to
83 *		the full size of the file.
84 *
85 * 	object	A string describing the logical location of the object.  For
86 * 		files and directories (currently the only supported types),
87 * 		this is the path of the object on disk.
88 *
89 * This is translated, via libzpool, into the following internal representation:
90 *
91 * 	<type,objset,object,level,range>
92 *
93 * These types should be self-explanatory.  This tuple is then passed to the
94 * kernel via a special ioctl() to initiate fault injection for the given
95 * object.  Note that 'type' is not strictly necessary for fault injection, but
96 * is used when translating existing faults into a human-readable string.
97 *
98 *
99 * The command itself takes one of the forms:
100 *
101 * 	zinject
102 * 	zinject <-a | -u pool>
103 * 	zinject -c <id|all>
104 * 	zinject [-q] <-t type> [-f freq] [-u] [-a] [-m] [-e errno] [-l level]
105 *	    [-r range] <object>
106 * 	zinject [-f freq] [-a] [-m] [-u] -b objset:object:level:start:end pool
107 *
108 * With no arguments, the command prints all currently registered injection
109 * handlers, with their numeric identifiers.
110 *
111 * The '-c' option will clear the given handler, or all handlers if 'all' is
112 * specified.
113 *
114 * The '-e' option takes a string describing the errno to simulate.  This must
115 * be either 'io' or 'checksum'.  In most cases this will result in the same
116 * behavior, but RAID-Z will produce a different set of ereports for this
117 * situation.
118 *
119 * The '-a', '-u', and '-m' flags toggle internal flush behavior.  If '-a' is
120 * specified, then the ARC cache is flushed appropriately.  If '-u' is
121 * specified, then the underlying SPA is unloaded.  Either of these flags can be
122 * specified independently of any other handlers.  The '-m' flag automatically
123 * does an unmount and remount of the underlying dataset to aid in flushing the
124 * cache.
125 *
126 * The '-f' flag controls the frequency of errors injected, expressed as a
127 * integer percentage between 1 and 100.  The default is 100.
128 *
129 * The this form is responsible for actually injecting the handler into the
130 * framework.  It takes the arguments described above, translates them to the
131 * internal tuple using libzpool, and then issues an ioctl() to register the
132 * handler.
133 *
134 * The final form can target a specific bookmark, regardless of whether a
135 * human-readable interface has been designed.  It allows developers to specify
136 * a particular block by number.
137 */
138
139#include <errno.h>
140#include <fcntl.h>
141#include <stdio.h>
142#include <stdlib.h>
143#include <strings.h>
144#include <unistd.h>
145
146#include <sys/fs/zfs.h>
147#include <sys/param.h>
148#include <sys/mount.h>
149
150#include <libzfs.h>
151
152#undef verify	/* both libzfs.h and zfs_context.h want to define this */
153
154#include "zinject.h"
155
156libzfs_handle_t *g_zfs;
157int zfs_fd;
158
159#ifndef ECKSUM
160#define	ECKSUM	EBADE
161#endif
162
163static const char *errtable[TYPE_INVAL] = {
164	"data",
165	"dnode",
166	"mos",
167	"mosdir",
168	"metaslab",
169	"config",
170	"bpobj",
171	"spacemap",
172	"errlog",
173	"uber",
174	"nvlist",
175	"pad1",
176	"pad2"
177};
178
179static err_type_t
180name_to_type(const char *arg)
181{
182	int i;
183	for (i = 0; i < TYPE_INVAL; i++)
184		if (strcmp(errtable[i], arg) == 0)
185			return (i);
186
187	return (TYPE_INVAL);
188}
189
190static const char *
191type_to_name(uint64_t type)
192{
193	switch (type) {
194	case DMU_OT_OBJECT_DIRECTORY:
195		return ("mosdir");
196	case DMU_OT_OBJECT_ARRAY:
197		return ("metaslab");
198	case DMU_OT_PACKED_NVLIST:
199		return ("config");
200	case DMU_OT_BPOBJ:
201		return ("bpobj");
202	case DMU_OT_SPACE_MAP:
203		return ("spacemap");
204	case DMU_OT_ERROR_LOG:
205		return ("errlog");
206	default:
207		return ("-");
208	}
209}
210
211
212/*
213 * Print usage message.
214 */
215void
216usage(void)
217{
218	(void) printf(
219	    "usage:\n"
220	    "\n"
221	    "\tzinject\n"
222	    "\n"
223	    "\t\tList all active injection records.\n"
224	    "\n"
225	    "\tzinject -c <id|all>\n"
226	    "\n"
227	    "\t\tClear the particular record (if given a numeric ID), or\n"
228	    "\t\tall records if 'all' is specificed.\n"
229	    "\n"
230	    "\tzinject -p <function name> pool\n"
231	    "\t\tInject a panic fault at the specified function. Only \n"
232	    "\t\tfunctions which call spa_vdev_config_exit(), or \n"
233	    "\t\tspa_vdev_exit() will trigger a panic.\n"
234	    "\n"
235	    "\tzinject -d device [-e errno] [-L <nvlist|uber|pad1|pad2>] [-F]\n"
236	    "\t    [-T <read|write|free|claim|all> pool\n"
237	    "\t\tInject a fault into a particular device or the device's\n"
238	    "\t\tlabel.  Label injection can either be 'nvlist', 'uber',\n "
239	    "\t\t'pad1', or 'pad2'.\n"
240	    "\t\t'errno' can be 'nxio' (the default), 'io', or 'dtl'.\n"
241	    "\n"
242	    "\tzinject -d device -A <degrade|fault> pool\n"
243	    "\t\tPerform a specific action on a particular device\n"
244	    "\n"
245	    "\tzinject -I [-s <seconds> | -g <txgs>] pool\n"
246	    "\t\tCause the pool to stop writing blocks yet not\n"
247	    "\t\treport errors for a duration.  Simulates buggy hardware\n"
248	    "\t\tthat fails to honor cache flush requests.\n"
249	    "\t\tDefault duration is 30 seconds.  The machine is panicked\n"
250	    "\t\tat the end of the duration.\n"
251	    "\n"
252	    "\tzinject -b objset:object:level:blkid pool\n"
253	    "\n"
254	    "\t\tInject an error into pool 'pool' with the numeric bookmark\n"
255	    "\t\tspecified by the remaining tuple.  Each number is in\n"
256	    "\t\thexidecimal, and only one block can be specified.\n"
257	    "\n"
258	    "\tzinject [-q] <-t type> [-e errno] [-l level] [-r range]\n"
259	    "\t    [-a] [-m] [-u] [-f freq] <object>\n"
260	    "\n"
261	    "\t\tInject an error into the object specified by the '-t' option\n"
262	    "\t\tand the object descriptor.  The 'object' parameter is\n"
263	    "\t\tinterperted depending on the '-t' option.\n"
264	    "\n"
265	    "\t\t-q\tQuiet mode.  Only print out the handler number added.\n"
266	    "\t\t-e\tInject a specific error.  Must be either 'io' or\n"
267	    "\t\t\t'checksum'.  Default is 'io'.\n"
268	    "\t\t-l\tInject error at a particular block level. Default is "
269	    "0.\n"
270	    "\t\t-m\tAutomatically remount underlying filesystem.\n"
271	    "\t\t-r\tInject error over a particular logical range of an\n"
272	    "\t\t\tobject.  Will be translated to the appropriate blkid\n"
273	    "\t\t\trange according to the object's properties.\n"
274	    "\t\t-a\tFlush the ARC cache.  Can be specified without any\n"
275	    "\t\t\tassociated object.\n"
276	    "\t\t-u\tUnload the associated pool.  Can be specified with only\n"
277	    "\t\t\ta pool object.\n"
278	    "\t\t-f\tOnly inject errors a fraction of the time.  Expressed as\n"
279	    "\t\t\ta percentage between 1 and 100.\n"
280	    "\n"
281	    "\t-t data\t\tInject an error into the plain file contents of a\n"
282	    "\t\t\tfile.  The object must be specified as a complete path\n"
283	    "\t\t\tto a file on a ZFS filesystem.\n"
284	    "\n"
285	    "\t-t dnode\tInject an error into the metadnode in the block\n"
286	    "\t\t\tcorresponding to the dnode for a file or directory.  The\n"
287	    "\t\t\t'-r' option is incompatible with this mode.  The object\n"
288	    "\t\t\tis specified as a complete path to a file or directory\n"
289	    "\t\t\ton a ZFS filesystem.\n"
290	    "\n"
291	    "\t-t <mos>\tInject errors into the MOS for objects of the given\n"
292	    "\t\t\ttype.  Valid types are: mos, mosdir, config, bpobj,\n"
293	    "\t\t\tspacemap, metaslab, errlog.  The only valid <object> is\n"
294	    "\t\t\tthe poolname.\n");
295}
296
297static int
298iter_handlers(int (*func)(int, const char *, zinject_record_t *, void *),
299    void *data)
300{
301	zfs_cmd_t zc = { 0 };
302	int ret;
303
304	while (ioctl(zfs_fd, ZFS_IOC_INJECT_LIST_NEXT, &zc) == 0)
305		if ((ret = func((int)zc.zc_guid, zc.zc_name,
306		    &zc.zc_inject_record, data)) != 0)
307			return (ret);
308
309	if (errno != ENOENT) {
310		(void) fprintf(stderr, "Unable to list handlers: %s\n",
311		    strerror(errno));
312		return (-1);
313	}
314
315	return (0);
316}
317
318static int
319print_data_handler(int id, const char *pool, zinject_record_t *record,
320    void *data)
321{
322	int *count = data;
323
324	if (record->zi_guid != 0 || record->zi_func[0] != '\0')
325		return (0);
326
327	if (*count == 0) {
328		(void) printf("%3s  %-15s  %-6s  %-6s  %-8s  %3s  %-15s\n",
329		    "ID", "POOL", "OBJSET", "OBJECT", "TYPE", "LVL",  "RANGE");
330		(void) printf("---  ---------------  ------  "
331		    "------  --------  ---  ---------------\n");
332	}
333
334	*count += 1;
335
336	(void) printf("%3d  %-15s  %-6llu  %-6llu  %-8s  %3d  ", id, pool,
337	    (u_longlong_t)record->zi_objset, (u_longlong_t)record->zi_object,
338	    type_to_name(record->zi_type), record->zi_level);
339
340	if (record->zi_start == 0 &&
341	    record->zi_end == -1ULL)
342		(void) printf("all\n");
343	else
344		(void) printf("[%llu, %llu]\n", (u_longlong_t)record->zi_start,
345		    (u_longlong_t)record->zi_end);
346
347	return (0);
348}
349
350static int
351print_device_handler(int id, const char *pool, zinject_record_t *record,
352    void *data)
353{
354	int *count = data;
355
356	if (record->zi_guid == 0 || record->zi_func[0] != '\0')
357		return (0);
358
359	if (*count == 0) {
360		(void) printf("%3s  %-15s  %s\n", "ID", "POOL", "GUID");
361		(void) printf("---  ---------------  ----------------\n");
362	}
363
364	*count += 1;
365
366	(void) printf("%3d  %-15s  %llx\n", id, pool,
367	    (u_longlong_t)record->zi_guid);
368
369	return (0);
370}
371
372static int
373print_panic_handler(int id, const char *pool, zinject_record_t *record,
374    void *data)
375{
376	int *count = data;
377
378	if (record->zi_func[0] == '\0')
379		return (0);
380
381	if (*count == 0) {
382		(void) printf("%3s  %-15s  %s\n", "ID", "POOL", "FUNCTION");
383		(void) printf("---  ---------------  ----------------\n");
384	}
385
386	*count += 1;
387
388	(void) printf("%3d  %-15s  %s\n", id, pool, record->zi_func);
389
390	return (0);
391}
392
393/*
394 * Print all registered error handlers.  Returns the number of handlers
395 * registered.
396 */
397static int
398print_all_handlers(void)
399{
400	int count = 0, total = 0;
401
402	(void) iter_handlers(print_device_handler, &count);
403	if (count > 0) {
404		total += count;
405		(void) printf("\n");
406		count = 0;
407	}
408
409	(void) iter_handlers(print_data_handler, &count);
410	if (count > 0) {
411		total += count;
412		(void) printf("\n");
413		count = 0;
414	}
415
416	(void) iter_handlers(print_panic_handler, &count);
417
418	return (count + total);
419}
420
421/* ARGSUSED */
422static int
423cancel_one_handler(int id, const char *pool, zinject_record_t *record,
424    void *data)
425{
426	zfs_cmd_t zc = { 0 };
427
428	zc.zc_guid = (uint64_t)id;
429
430	if (ioctl(zfs_fd, ZFS_IOC_CLEAR_FAULT, &zc) != 0) {
431		(void) fprintf(stderr, "failed to remove handler %d: %s\n",
432		    id, strerror(errno));
433		return (1);
434	}
435
436	return (0);
437}
438
439/*
440 * Remove all fault injection handlers.
441 */
442static int
443cancel_all_handlers(void)
444{
445	int ret = iter_handlers(cancel_one_handler, NULL);
446
447	if (ret == 0)
448		(void) printf("removed all registered handlers\n");
449
450	return (ret);
451}
452
453/*
454 * Remove a specific fault injection handler.
455 */
456static int
457cancel_handler(int id)
458{
459	zfs_cmd_t zc = { 0 };
460
461	zc.zc_guid = (uint64_t)id;
462
463	if (ioctl(zfs_fd, ZFS_IOC_CLEAR_FAULT, &zc) != 0) {
464		(void) fprintf(stderr, "failed to remove handler %d: %s\n",
465		    id, strerror(errno));
466		return (1);
467	}
468
469	(void) printf("removed handler %d\n", id);
470
471	return (0);
472}
473
474/*
475 * Register a new fault injection handler.
476 */
477static int
478register_handler(const char *pool, int flags, zinject_record_t *record,
479    int quiet)
480{
481	zfs_cmd_t zc = { 0 };
482
483	(void) strcpy(zc.zc_name, pool);
484	zc.zc_inject_record = *record;
485	zc.zc_guid = flags;
486
487	if (ioctl(zfs_fd, ZFS_IOC_INJECT_FAULT, &zc) != 0) {
488		(void) fprintf(stderr, "failed to add handler: %s\n",
489		    strerror(errno));
490		return (1);
491	}
492
493	if (flags & ZINJECT_NULL)
494		return (0);
495
496	if (quiet) {
497		(void) printf("%llu\n", (u_longlong_t)zc.zc_guid);
498	} else {
499		(void) printf("Added handler %llu with the following "
500		    "properties:\n", (u_longlong_t)zc.zc_guid);
501		(void) printf("  pool: %s\n", pool);
502		if (record->zi_guid) {
503			(void) printf("  vdev: %llx\n",
504			    (u_longlong_t)record->zi_guid);
505		} else if (record->zi_func[0] != '\0') {
506			(void) printf("  panic function: %s\n",
507			    record->zi_func);
508		} else if (record->zi_duration > 0) {
509			(void) printf(" time: %lld seconds\n",
510			    (u_longlong_t)record->zi_duration);
511		} else if (record->zi_duration < 0) {
512			(void) printf(" txgs: %lld \n",
513			    (u_longlong_t)-record->zi_duration);
514		} else {
515			(void) printf("objset: %llu\n",
516			    (u_longlong_t)record->zi_objset);
517			(void) printf("object: %llu\n",
518			    (u_longlong_t)record->zi_object);
519			(void) printf("  type: %llu\n",
520			    (u_longlong_t)record->zi_type);
521			(void) printf(" level: %d\n", record->zi_level);
522			if (record->zi_start == 0 &&
523			    record->zi_end == -1ULL)
524				(void) printf(" range: all\n");
525			else
526				(void) printf(" range: [%llu, %llu)\n",
527				    (u_longlong_t)record->zi_start,
528				    (u_longlong_t)record->zi_end);
529		}
530	}
531
532	return (0);
533}
534
535int
536perform_action(const char *pool, zinject_record_t *record, int cmd)
537{
538	zfs_cmd_t zc = { 0 };
539
540	ASSERT(cmd == VDEV_STATE_DEGRADED || cmd == VDEV_STATE_FAULTED);
541	(void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
542	zc.zc_guid = record->zi_guid;
543	zc.zc_cookie = cmd;
544
545	if (ioctl(zfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
546		return (0);
547
548	return (1);
549}
550
551int
552main(int argc, char **argv)
553{
554	int c;
555	char *range = NULL;
556	char *cancel = NULL;
557	char *end;
558	char *raw = NULL;
559	char *device = NULL;
560	int level = 0;
561	int quiet = 0;
562	int error = 0;
563	int domount = 0;
564	int io_type = ZIO_TYPES;
565	int action = VDEV_STATE_UNKNOWN;
566	err_type_t type = TYPE_INVAL;
567	err_type_t label = TYPE_INVAL;
568	zinject_record_t record = { 0 };
569	char pool[MAXNAMELEN];
570	char dataset[MAXNAMELEN];
571	zfs_handle_t *zhp;
572	int nowrites = 0;
573	int dur_txg = 0;
574	int dur_secs = 0;
575	int ret;
576	int flags = 0;
577
578	if ((g_zfs = libzfs_init()) == NULL) {
579		(void) fprintf(stderr, "internal error: failed to "
580		    "initialize ZFS library\n");
581		return (1);
582	}
583
584	libzfs_print_on_error(g_zfs, B_TRUE);
585
586	if ((zfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
587		(void) fprintf(stderr, "failed to open ZFS device\n");
588		return (1);
589	}
590
591	if (argc == 1) {
592		/*
593		 * No arguments.  Print the available handlers.  If there are no
594		 * available handlers, direct the user to '-h' for help
595		 * information.
596		 */
597		if (print_all_handlers() == 0) {
598			(void) printf("No handlers registered.\n");
599			(void) printf("Run 'zinject -h' for usage "
600			    "information.\n");
601		}
602
603		return (0);
604	}
605
606	while ((c = getopt(argc, argv,
607	    ":aA:b:d:D:f:Fg:qhIc:t:T:l:mr:s:e:uL:p:")) != -1) {
608		switch (c) {
609		case 'a':
610			flags |= ZINJECT_FLUSH_ARC;
611			break;
612		case 'A':
613			if (strcasecmp(optarg, "degrade") == 0) {
614				action = VDEV_STATE_DEGRADED;
615			} else if (strcasecmp(optarg, "fault") == 0) {
616				action = VDEV_STATE_FAULTED;
617			} else {
618				(void) fprintf(stderr, "invalid action '%s': "
619				    "must be 'degrade' or 'fault'\n", optarg);
620				usage();
621				return (1);
622			}
623			break;
624		case 'b':
625			raw = optarg;
626			break;
627		case 'c':
628			cancel = optarg;
629			break;
630		case 'd':
631			device = optarg;
632			break;
633		case 'D':
634			record.zi_timer = strtoull(optarg, &end, 10);
635			if (errno != 0 || *end != '\0') {
636				(void) fprintf(stderr, "invalid i/o delay "
637				    "value: '%s'\n", optarg);
638				usage();
639				return (1);
640			}
641			break;
642		case 'e':
643			if (strcasecmp(optarg, "io") == 0) {
644				error = EIO;
645			} else if (strcasecmp(optarg, "checksum") == 0) {
646				error = ECKSUM;
647			} else if (strcasecmp(optarg, "nxio") == 0) {
648				error = ENXIO;
649			} else if (strcasecmp(optarg, "dtl") == 0) {
650				error = ECHILD;
651			} else {
652				(void) fprintf(stderr, "invalid error type "
653				    "'%s': must be 'io', 'checksum' or "
654				    "'nxio'\n", optarg);
655				usage();
656				return (1);
657			}
658			break;
659		case 'f':
660			record.zi_freq = atoi(optarg);
661			if (record.zi_freq < 1 || record.zi_freq > 100) {
662				(void) fprintf(stderr, "frequency range must "
663				    "be in the range (0, 100]\n");
664				return (1);
665			}
666			break;
667		case 'F':
668			record.zi_failfast = B_TRUE;
669			break;
670		case 'g':
671			dur_txg = 1;
672			record.zi_duration = (int)strtol(optarg, &end, 10);
673			if (record.zi_duration <= 0 || *end != '\0') {
674				(void) fprintf(stderr, "invalid duration '%s': "
675				    "must be a positive integer\n", optarg);
676				usage();
677				return (1);
678			}
679			/* store duration of txgs as its negative */
680			record.zi_duration *= -1;
681			break;
682		case 'h':
683			usage();
684			return (0);
685		case 'I':
686			/* default duration, if one hasn't yet been defined */
687			nowrites = 1;
688			if (dur_secs == 0 && dur_txg == 0)
689				record.zi_duration = 30;
690			break;
691		case 'l':
692			level = (int)strtol(optarg, &end, 10);
693			if (*end != '\0') {
694				(void) fprintf(stderr, "invalid level '%s': "
695				    "must be an integer\n", optarg);
696				usage();
697				return (1);
698			}
699			break;
700		case 'm':
701			domount = 1;
702			break;
703		case 'p':
704			(void) strlcpy(record.zi_func, optarg,
705			    sizeof (record.zi_func));
706			record.zi_cmd = ZINJECT_PANIC;
707			break;
708		case 'q':
709			quiet = 1;
710			break;
711		case 'r':
712			range = optarg;
713			break;
714		case 's':
715			dur_secs = 1;
716			record.zi_duration = (int)strtol(optarg, &end, 10);
717			if (record.zi_duration <= 0 || *end != '\0') {
718				(void) fprintf(stderr, "invalid duration '%s': "
719				    "must be a positive integer\n", optarg);
720				usage();
721				return (1);
722			}
723			break;
724		case 'T':
725			if (strcasecmp(optarg, "read") == 0) {
726				io_type = ZIO_TYPE_READ;
727			} else if (strcasecmp(optarg, "write") == 0) {
728				io_type = ZIO_TYPE_WRITE;
729			} else if (strcasecmp(optarg, "free") == 0) {
730				io_type = ZIO_TYPE_FREE;
731			} else if (strcasecmp(optarg, "claim") == 0) {
732				io_type = ZIO_TYPE_CLAIM;
733			} else if (strcasecmp(optarg, "all") == 0) {
734				io_type = ZIO_TYPES;
735			} else {
736				(void) fprintf(stderr, "invalid I/O type "
737				    "'%s': must be 'read', 'write', 'free', "
738				    "'claim' or 'all'\n", optarg);
739				usage();
740				return (1);
741			}
742			break;
743		case 't':
744			if ((type = name_to_type(optarg)) == TYPE_INVAL &&
745			    !MOS_TYPE(type)) {
746				(void) fprintf(stderr, "invalid type '%s'\n",
747				    optarg);
748				usage();
749				return (1);
750			}
751			break;
752		case 'u':
753			flags |= ZINJECT_UNLOAD_SPA;
754			break;
755		case 'L':
756			if ((label = name_to_type(optarg)) == TYPE_INVAL &&
757			    !LABEL_TYPE(type)) {
758				(void) fprintf(stderr, "invalid label type "
759				    "'%s'\n", optarg);
760				usage();
761				return (1);
762			}
763			break;
764		case ':':
765			(void) fprintf(stderr, "option -%c requires an "
766			    "operand\n", optopt);
767			usage();
768			return (1);
769		case '?':
770			(void) fprintf(stderr, "invalid option '%c'\n",
771			    optopt);
772			usage();
773			return (2);
774		}
775	}
776
777	argc -= optind;
778	argv += optind;
779
780	if (record.zi_duration != 0)
781		record.zi_cmd = ZINJECT_IGNORED_WRITES;
782
783	if (cancel != NULL) {
784		/*
785		 * '-c' is invalid with any other options.
786		 */
787		if (raw != NULL || range != NULL || type != TYPE_INVAL ||
788		    level != 0 || record.zi_cmd != ZINJECT_UNINITIALIZED) {
789			(void) fprintf(stderr, "cancel (-c) incompatible with "
790			    "any other options\n");
791			usage();
792			return (2);
793		}
794		if (argc != 0) {
795			(void) fprintf(stderr, "extraneous argument to '-c'\n");
796			usage();
797			return (2);
798		}
799
800		if (strcmp(cancel, "all") == 0) {
801			return (cancel_all_handlers());
802		} else {
803			int id = (int)strtol(cancel, &end, 10);
804			if (*end != '\0') {
805				(void) fprintf(stderr, "invalid handle id '%s':"
806				    " must be an integer or 'all'\n", cancel);
807				usage();
808				return (1);
809			}
810			return (cancel_handler(id));
811		}
812	}
813
814	if (device != NULL) {
815		/*
816		 * Device (-d) injection uses a completely different mechanism
817		 * for doing injection, so handle it separately here.
818		 */
819		if (raw != NULL || range != NULL || type != TYPE_INVAL ||
820		    level != 0 || record.zi_cmd != ZINJECT_UNINITIALIZED) {
821			(void) fprintf(stderr, "device (-d) incompatible with "
822			    "data error injection\n");
823			usage();
824			return (2);
825		}
826
827		if (argc != 1) {
828			(void) fprintf(stderr, "device (-d) injection requires "
829			    "a single pool name\n");
830			usage();
831			return (2);
832		}
833
834		(void) strcpy(pool, argv[0]);
835		dataset[0] = '\0';
836
837		if (error == ECKSUM) {
838			(void) fprintf(stderr, "device error type must be "
839			    "'io' or 'nxio'\n");
840			return (1);
841		}
842
843		record.zi_iotype = io_type;
844		if (translate_device(pool, device, label, &record) != 0)
845			return (1);
846		if (!error)
847			error = ENXIO;
848
849		if (action != VDEV_STATE_UNKNOWN)
850			return (perform_action(pool, &record, action));
851
852	} else if (raw != NULL) {
853		if (range != NULL || type != TYPE_INVAL || level != 0 ||
854		    record.zi_cmd != ZINJECT_UNINITIALIZED) {
855			(void) fprintf(stderr, "raw (-b) format with "
856			    "any other options\n");
857			usage();
858			return (2);
859		}
860
861		if (argc != 1) {
862			(void) fprintf(stderr, "raw (-b) format expects a "
863			    "single pool name\n");
864			usage();
865			return (2);
866		}
867
868		(void) strcpy(pool, argv[0]);
869		dataset[0] = '\0';
870
871		if (error == ENXIO) {
872			(void) fprintf(stderr, "data error type must be "
873			    "'checksum' or 'io'\n");
874			return (1);
875		}
876
877		record.zi_cmd = ZINJECT_DATA_FAULT;
878		if (translate_raw(raw, &record) != 0)
879			return (1);
880		if (!error)
881			error = EIO;
882	} else if (record.zi_cmd == ZINJECT_PANIC) {
883		if (raw != NULL || range != NULL || type != TYPE_INVAL ||
884		    level != 0 || device != NULL) {
885			(void) fprintf(stderr, "panic (-p) incompatible with "
886			    "other options\n");
887			usage();
888			return (2);
889		}
890
891		if (argc < 1 || argc > 2) {
892			(void) fprintf(stderr, "panic (-p) injection requires "
893			    "a single pool name and an optional id\n");
894			usage();
895			return (2);
896		}
897
898		(void) strcpy(pool, argv[0]);
899		if (argv[1] != NULL)
900			record.zi_type = atoi(argv[1]);
901		dataset[0] = '\0';
902	} else if (record.zi_cmd == ZINJECT_IGNORED_WRITES) {
903		if (nowrites == 0) {
904			(void) fprintf(stderr, "-s or -g meaningless "
905			    "without -I (ignore writes)\n");
906			usage();
907			return (2);
908		} else if (dur_secs && dur_txg) {
909			(void) fprintf(stderr, "choose a duration either "
910			    "in seconds (-s) or a number of txgs (-g) "
911			    "but not both\n");
912			usage();
913			return (2);
914		} else if (argc != 1) {
915			(void) fprintf(stderr, "ignore writes (-I) "
916			    "injection requires a single pool name\n");
917			usage();
918			return (2);
919		}
920
921		(void) strcpy(pool, argv[0]);
922		dataset[0] = '\0';
923	} else if (type == TYPE_INVAL) {
924		if (flags == 0) {
925			(void) fprintf(stderr, "at least one of '-b', '-d', "
926			    "'-t', '-a', '-p', '-I' or '-u' "
927			    "must be specified\n");
928			usage();
929			return (2);
930		}
931
932		if (argc == 1 && (flags & ZINJECT_UNLOAD_SPA)) {
933			(void) strcpy(pool, argv[0]);
934			dataset[0] = '\0';
935		} else if (argc != 0) {
936			(void) fprintf(stderr, "extraneous argument for "
937			    "'-f'\n");
938			usage();
939			return (2);
940		}
941
942		flags |= ZINJECT_NULL;
943	} else {
944		if (argc != 1) {
945			(void) fprintf(stderr, "missing object\n");
946			usage();
947			return (2);
948		}
949
950		if (error == ENXIO) {
951			(void) fprintf(stderr, "data error type must be "
952			    "'checksum' or 'io'\n");
953			return (1);
954		}
955
956		record.zi_cmd = ZINJECT_DATA_FAULT;
957		if (translate_record(type, argv[0], range, level, &record, pool,
958		    dataset) != 0)
959			return (1);
960		if (!error)
961			error = EIO;
962	}
963
964	/*
965	 * If this is pool-wide metadata, unmount everything.  The ioctl() will
966	 * unload the pool, so that we trigger spa-wide reopen of metadata next
967	 * time we access the pool.
968	 */
969	if (dataset[0] != '\0' && domount) {
970		if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_DATASET)) == NULL)
971			return (1);
972
973		if (zfs_unmount(zhp, NULL, 0) != 0)
974			return (1);
975	}
976
977	record.zi_error = error;
978
979	ret = register_handler(pool, flags, &record, quiet);
980
981	if (dataset[0] != '\0' && domount)
982		ret = (zfs_mount(zhp, NULL, 0) != 0);
983
984	libzfs_fini(g_zfs);
985
986	return (ret);
987}
988