xref: /titanic_51/usr/src/cmd/zinject/zinject.c (revision 0db3240d392634cfff2f95fb6da34b56b8dc574f)
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 2010 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
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 or uberblock region of all the labels
46  * for the specified device.
47  *
48  * This form of the command looks like:
49  *
50  * 	zinject -d device [-e errno] [-L <uber | nvlist>] 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  * 		bplist		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/mount.h>
148 
149 #include <libzfs.h>
150 
151 #undef verify	/* both libzfs.h and zfs_context.h want to define this */
152 
153 #include "zinject.h"
154 
155 libzfs_handle_t *g_zfs;
156 int zfs_fd;
157 
158 #define	ECKSUM	EBADE
159 
160 static const char *errtable[TYPE_INVAL] = {
161 	"data",
162 	"dnode",
163 	"mos",
164 	"mosdir",
165 	"metaslab",
166 	"config",
167 	"bplist",
168 	"spacemap",
169 	"errlog",
170 	"uber",
171 	"nvlist"
172 };
173 
174 static err_type_t
175 name_to_type(const char *arg)
176 {
177 	int i;
178 	for (i = 0; i < TYPE_INVAL; i++)
179 		if (strcmp(errtable[i], arg) == 0)
180 			return (i);
181 
182 	return (TYPE_INVAL);
183 }
184 
185 static const char *
186 type_to_name(uint64_t type)
187 {
188 	switch (type) {
189 	case DMU_OT_OBJECT_DIRECTORY:
190 		return ("mosdir");
191 	case DMU_OT_OBJECT_ARRAY:
192 		return ("metaslab");
193 	case DMU_OT_PACKED_NVLIST:
194 		return ("config");
195 	case DMU_OT_BPLIST:
196 		return ("bplist");
197 	case DMU_OT_SPACE_MAP:
198 		return ("spacemap");
199 	case DMU_OT_ERROR_LOG:
200 		return ("errlog");
201 	default:
202 		return ("-");
203 	}
204 }
205 
206 
207 /*
208  * Print usage message.
209  */
210 void
211 usage(void)
212 {
213 	(void) printf(
214 	    "usage:\n"
215 	    "\n"
216 	    "\tzinject\n"
217 	    "\n"
218 	    "\t\tList all active injection records.\n"
219 	    "\n"
220 	    "\tzinject -c <id|all>\n"
221 	    "\n"
222 	    "\t\tClear the particular record (if given a numeric ID), or\n"
223 	    "\t\tall records if 'all' is specificed.\n"
224 	    "\n"
225 	    "\tzinject -p <function name> pool\n"
226 	    "\t\tInject a panic fault at the specified function. Only \n"
227 	    "\t\tfunctions which call spa_vdev_config_exit(), or \n"
228 	    "\t\tspa_vdev_exit() will trigger a panic.\n"
229 	    "\n"
230 	    "\tzinject -d device [-e errno] [-L <nvlist|uber>] [-F]\n"
231 	    "\t    [-T <read|write|free|claim|all> pool\n"
232 	    "\t\tInject a fault into a particular device or the device's\n"
233 	    "\t\tlabel.  Label injection can either be 'nvlist' or 'uber'.\n"
234 	    "\t\t'errno' can either be 'nxio' (the default) or 'io'.\n"
235 	    "\n"
236 	    "\tzinject -d device -A <degrade|fault> pool\n"
237 	    "\t\tPerform a specific action on a particular device\n"
238 	    "\n"
239 	    "\tzinject -I [-s <seconds> | -g <txgs>] pool\n"
240 	    "\t\tCause the pool to stop writing blocks yet not\n"
241 	    "\t\treport errors for a duration.  Simulates buggy hardware\n"
242 	    "\t\tthat fails to honor cache flush requests.\n"
243 	    "\t\tDefault duration is 30 seconds.  The machine is panicked\n"
244 	    "\t\tat the end of the duration.\n"
245 	    "\n"
246 	    "\tzinject -b objset:object:level:blkid pool\n"
247 	    "\n"
248 	    "\t\tInject an error into pool 'pool' with the numeric bookmark\n"
249 	    "\t\tspecified by the remaining tuple.  Each number is in\n"
250 	    "\t\thexidecimal, and only one block can be specified.\n"
251 	    "\n"
252 	    "\tzinject [-q] <-t type> [-e errno] [-l level] [-r range]\n"
253 	    "\t    [-a] [-m] [-u] [-f freq] <object>\n"
254 	    "\n"
255 	    "\t\tInject an error into the object specified by the '-t' option\n"
256 	    "\t\tand the object descriptor.  The 'object' parameter is\n"
257 	    "\t\tinterperted depending on the '-t' option.\n"
258 	    "\n"
259 	    "\t\t-q\tQuiet mode.  Only print out the handler number added.\n"
260 	    "\t\t-e\tInject a specific error.  Must be either 'io' or\n"
261 	    "\t\t\t'checksum'.  Default is 'io'.\n"
262 	    "\t\t-l\tInject error at a particular block level. Default is "
263 	    "0.\n"
264 	    "\t\t-m\tAutomatically remount underlying filesystem.\n"
265 	    "\t\t-r\tInject error over a particular logical range of an\n"
266 	    "\t\t\tobject.  Will be translated to the appropriate blkid\n"
267 	    "\t\t\trange according to the object's properties.\n"
268 	    "\t\t-a\tFlush the ARC cache.  Can be specified without any\n"
269 	    "\t\t\tassociated object.\n"
270 	    "\t\t-u\tUnload the associated pool.  Can be specified with only\n"
271 	    "\t\t\ta pool object.\n"
272 	    "\t\t-f\tOnly inject errors a fraction of the time.  Expressed as\n"
273 	    "\t\t\ta percentage between 1 and 100.\n"
274 	    "\n"
275 	    "\t-t data\t\tInject an error into the plain file contents of a\n"
276 	    "\t\t\tfile.  The object must be specified as a complete path\n"
277 	    "\t\t\tto a file on a ZFS filesystem.\n"
278 	    "\n"
279 	    "\t-t dnode\tInject an error into the metadnode in the block\n"
280 	    "\t\t\tcorresponding to the dnode for a file or directory.  The\n"
281 	    "\t\t\t'-r' option is incompatible with this mode.  The object\n"
282 	    "\t\t\tis specified as a complete path to a file or directory\n"
283 	    "\t\t\ton a ZFS filesystem.\n"
284 	    "\n"
285 	    "\t-t <mos>\tInject errors into the MOS for objects of the given\n"
286 	    "\t\t\ttype.  Valid types are: mos, mosdir, config, bplist,\n"
287 	    "\t\t\tspacemap, metaslab, errlog.  The only valid <object> is\n"
288 	    "\t\t\tthe poolname.\n");
289 }
290 
291 static int
292 iter_handlers(int (*func)(int, const char *, zinject_record_t *, void *),
293     void *data)
294 {
295 	zfs_cmd_t zc;
296 	int ret;
297 
298 	zc.zc_guid = 0;
299 
300 	while (ioctl(zfs_fd, ZFS_IOC_INJECT_LIST_NEXT, &zc) == 0)
301 		if ((ret = func((int)zc.zc_guid, zc.zc_name,
302 		    &zc.zc_inject_record, data)) != 0)
303 			return (ret);
304 
305 	if (errno != ENOENT) {
306 		(void) fprintf(stderr, "Unable to list handlers: %s\n",
307 		    strerror(errno));
308 		return (-1);
309 	}
310 
311 	return (0);
312 }
313 
314 static int
315 print_data_handler(int id, const char *pool, zinject_record_t *record,
316     void *data)
317 {
318 	int *count = data;
319 
320 	if (record->zi_guid != 0 || record->zi_func[0] != '\0')
321 		return (0);
322 
323 	if (*count == 0) {
324 		(void) printf("%3s  %-15s  %-6s  %-6s  %-8s  %3s  %-15s\n",
325 		    "ID", "POOL", "OBJSET", "OBJECT", "TYPE", "LVL",  "RANGE");
326 		(void) printf("---  ---------------  ------  "
327 		    "------  --------  ---  ---------------\n");
328 	}
329 
330 	*count += 1;
331 
332 	(void) printf("%3d  %-15s  %-6llu  %-6llu  %-8s  %3d  ", id, pool,
333 	    (u_longlong_t)record->zi_objset, (u_longlong_t)record->zi_object,
334 	    type_to_name(record->zi_type), record->zi_level);
335 
336 	if (record->zi_start == 0 &&
337 	    record->zi_end == -1ULL)
338 		(void) printf("all\n");
339 	else
340 		(void) printf("[%llu, %llu]\n", (u_longlong_t)record->zi_start,
341 		    (u_longlong_t)record->zi_end);
342 
343 	return (0);
344 }
345 
346 static int
347 print_device_handler(int id, const char *pool, zinject_record_t *record,
348     void *data)
349 {
350 	int *count = data;
351 
352 	if (record->zi_guid == 0 || record->zi_func[0] != '\0')
353 		return (0);
354 
355 	if (*count == 0) {
356 		(void) printf("%3s  %-15s  %s\n", "ID", "POOL", "GUID");
357 		(void) printf("---  ---------------  ----------------\n");
358 	}
359 
360 	*count += 1;
361 
362 	(void) printf("%3d  %-15s  %llx\n", id, pool,
363 	    (u_longlong_t)record->zi_guid);
364 
365 	return (0);
366 }
367 
368 static int
369 print_panic_handler(int id, const char *pool, zinject_record_t *record,
370     void *data)
371 {
372 	int *count = data;
373 
374 	if (record->zi_func[0] == '\0')
375 		return (0);
376 
377 	if (*count == 0) {
378 		(void) printf("%3s  %-15s  %s\n", "ID", "POOL", "FUNCTION");
379 		(void) printf("---  ---------------  ----------------\n");
380 	}
381 
382 	*count += 1;
383 
384 	(void) printf("%3d  %-15s  %s\n", id, pool, record->zi_func);
385 
386 	return (0);
387 }
388 
389 /*
390  * Print all registered error handlers.  Returns the number of handlers
391  * registered.
392  */
393 static int
394 print_all_handlers(void)
395 {
396 	int count = 0;
397 
398 	(void) iter_handlers(print_device_handler, &count);
399 	(void) printf("\n");
400 	count = 0;
401 	(void) iter_handlers(print_data_handler, &count);
402 	(void) printf("\n");
403 	count = 0;
404 	(void) iter_handlers(print_panic_handler, &count);
405 
406 	return (count);
407 }
408 
409 /* ARGSUSED */
410 static int
411 cancel_one_handler(int id, const char *pool, zinject_record_t *record,
412     void *data)
413 {
414 	zfs_cmd_t zc;
415 
416 	zc.zc_guid = (uint64_t)id;
417 
418 	if (ioctl(zfs_fd, ZFS_IOC_CLEAR_FAULT, &zc) != 0) {
419 		(void) fprintf(stderr, "failed to remove handler %d: %s\n",
420 		    id, strerror(errno));
421 		return (1);
422 	}
423 
424 	return (0);
425 }
426 
427 /*
428  * Remove all fault injection handlers.
429  */
430 static int
431 cancel_all_handlers(void)
432 {
433 	int ret = iter_handlers(cancel_one_handler, NULL);
434 
435 	if (ret == 0)
436 		(void) printf("removed all registered handlers\n");
437 
438 	return (ret);
439 }
440 
441 /*
442  * Remove a specific fault injection handler.
443  */
444 static int
445 cancel_handler(int id)
446 {
447 	zfs_cmd_t zc;
448 
449 	zc.zc_guid = (uint64_t)id;
450 
451 	if (ioctl(zfs_fd, ZFS_IOC_CLEAR_FAULT, &zc) != 0) {
452 		(void) fprintf(stderr, "failed to remove handler %d: %s\n",
453 		    id, strerror(errno));
454 		return (1);
455 	}
456 
457 	(void) printf("removed handler %d\n", id);
458 
459 	return (0);
460 }
461 
462 /*
463  * Register a new fault injection handler.
464  */
465 static int
466 register_handler(const char *pool, int flags, zinject_record_t *record,
467     int quiet)
468 {
469 	zfs_cmd_t zc;
470 
471 	(void) strcpy(zc.zc_name, pool);
472 	zc.zc_inject_record = *record;
473 	zc.zc_guid = flags;
474 
475 	if (ioctl(zfs_fd, ZFS_IOC_INJECT_FAULT, &zc) != 0) {
476 		(void) fprintf(stderr, "failed to add handler: %s\n",
477 		    strerror(errno));
478 		return (1);
479 	}
480 
481 	if (flags & ZINJECT_NULL)
482 		return (0);
483 
484 	if (quiet) {
485 		(void) printf("%llu\n", (u_longlong_t)zc.zc_guid);
486 	} else {
487 		(void) printf("Added handler %llu with the following "
488 		    "properties:\n", (u_longlong_t)zc.zc_guid);
489 		(void) printf("  pool: %s\n", pool);
490 		if (record->zi_guid) {
491 			(void) printf("  vdev: %llx\n",
492 			    (u_longlong_t)record->zi_guid);
493 		} else if (record->zi_func[0] != '\0') {
494 			(void) printf("  panic function: %s\n",
495 			    record->zi_func);
496 		} else if (record->zi_duration > 0) {
497 			(void) printf(" time: %lld seconds\n",
498 			    (u_longlong_t)record->zi_duration);
499 		} else if (record->zi_duration < 0) {
500 			(void) printf(" txgs: %lld \n",
501 			    (u_longlong_t)-record->zi_duration);
502 		} else {
503 			(void) printf("objset: %llu\n",
504 			    (u_longlong_t)record->zi_objset);
505 			(void) printf("object: %llu\n",
506 			    (u_longlong_t)record->zi_object);
507 			(void) printf("  type: %llu\n",
508 			    (u_longlong_t)record->zi_type);
509 			(void) printf(" level: %d\n", record->zi_level);
510 			if (record->zi_start == 0 &&
511 			    record->zi_end == -1ULL)
512 				(void) printf(" range: all\n");
513 			else
514 				(void) printf(" range: [%llu, %llu)\n",
515 				    (u_longlong_t)record->zi_start,
516 				    (u_longlong_t)record->zi_end);
517 		}
518 	}
519 
520 	return (0);
521 }
522 
523 int
524 perform_action(const char *pool, zinject_record_t *record, int cmd)
525 {
526 	zfs_cmd_t zc;
527 
528 	ASSERT(cmd == VDEV_STATE_DEGRADED || cmd == VDEV_STATE_FAULTED);
529 	(void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
530 	zc.zc_guid = record->zi_guid;
531 	zc.zc_cookie = cmd;
532 
533 	if (ioctl(zfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
534 		return (0);
535 
536 	return (1);
537 }
538 
539 int
540 main(int argc, char **argv)
541 {
542 	int c;
543 	char *range = NULL;
544 	char *cancel = NULL;
545 	char *end;
546 	char *raw = NULL;
547 	char *device = NULL;
548 	int level = 0;
549 	int quiet = 0;
550 	int error = 0;
551 	int domount = 0;
552 	int io_type = ZIO_TYPES;
553 	int action = VDEV_STATE_UNKNOWN;
554 	err_type_t type = TYPE_INVAL;
555 	err_type_t label = TYPE_INVAL;
556 	zinject_record_t record = { 0 };
557 	char pool[MAXNAMELEN];
558 	char dataset[MAXNAMELEN];
559 	zfs_handle_t *zhp;
560 	int nowrites = 0;
561 	int dur_txg = 0;
562 	int dur_secs = 0;
563 	int ret;
564 	int flags = 0;
565 
566 	if ((g_zfs = libzfs_init()) == NULL) {
567 		(void) fprintf(stderr, "internal error: failed to "
568 		    "initialize ZFS library\n");
569 		return (1);
570 	}
571 
572 	libzfs_print_on_error(g_zfs, B_TRUE);
573 
574 	if ((zfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
575 		(void) fprintf(stderr, "failed to open ZFS device\n");
576 		return (1);
577 	}
578 
579 	if (argc == 1) {
580 		/*
581 		 * No arguments.  Print the available handlers.  If there are no
582 		 * available handlers, direct the user to '-h' for help
583 		 * information.
584 		 */
585 		if (print_all_handlers() == 0) {
586 			(void) printf("No handlers registered.\n");
587 			(void) printf("Run 'zinject -h' for usage "
588 			    "information.\n");
589 		}
590 
591 		return (0);
592 	}
593 
594 	while ((c = getopt(argc, argv,
595 	    ":aA:b:d:f:Fg:qhIc:t:T:l:mr:s:e:uL:p:")) != -1) {
596 		switch (c) {
597 		case 'a':
598 			flags |= ZINJECT_FLUSH_ARC;
599 			break;
600 		case 'A':
601 			if (strcasecmp(optarg, "degrade") == 0) {
602 				action = VDEV_STATE_DEGRADED;
603 			} else if (strcasecmp(optarg, "fault") == 0) {
604 				action = VDEV_STATE_FAULTED;
605 			} else {
606 				(void) fprintf(stderr, "invalid action '%s': "
607 				    "must be 'degrade' or 'fault'\n", optarg);
608 				usage();
609 				return (1);
610 			}
611 			break;
612 		case 'b':
613 			raw = optarg;
614 			break;
615 		case 'c':
616 			cancel = optarg;
617 			break;
618 		case 'd':
619 			device = optarg;
620 			break;
621 		case 'e':
622 			if (strcasecmp(optarg, "io") == 0) {
623 				error = EIO;
624 			} else if (strcasecmp(optarg, "checksum") == 0) {
625 				error = ECKSUM;
626 			} else if (strcasecmp(optarg, "nxio") == 0) {
627 				error = ENXIO;
628 			} else {
629 				(void) fprintf(stderr, "invalid error type "
630 				    "'%s': must be 'io', 'checksum' or "
631 				    "'nxio'\n", optarg);
632 				usage();
633 				return (1);
634 			}
635 			break;
636 		case 'f':
637 			record.zi_freq = atoi(optarg);
638 			if (record.zi_freq < 1 || record.zi_freq > 100) {
639 				(void) fprintf(stderr, "frequency range must "
640 				    "be in the range (0, 100]\n");
641 				return (1);
642 			}
643 			break;
644 		case 'F':
645 			record.zi_failfast = B_TRUE;
646 			break;
647 		case 'g':
648 			dur_txg = 1;
649 			record.zi_duration = (int)strtol(optarg, &end, 10);
650 			if (record.zi_duration <= 0 || *end != '\0') {
651 				(void) fprintf(stderr, "invalid duration '%s': "
652 				    "must be a positive integer\n", optarg);
653 				usage();
654 				return (1);
655 			}
656 			/* store duration of txgs as its negative */
657 			record.zi_duration *= -1;
658 			break;
659 		case 'h':
660 			usage();
661 			return (0);
662 		case 'I':
663 			/* default duration, if one hasn't yet been defined */
664 			nowrites = 1;
665 			if (dur_secs == 0 && dur_txg == 0)
666 				record.zi_duration = 30;
667 			break;
668 		case 'l':
669 			level = (int)strtol(optarg, &end, 10);
670 			if (*end != '\0') {
671 				(void) fprintf(stderr, "invalid level '%s': "
672 				    "must be an integer\n", optarg);
673 				usage();
674 				return (1);
675 			}
676 			break;
677 		case 'm':
678 			domount = 1;
679 			break;
680 		case 'p':
681 			(void) strlcpy(record.zi_func, optarg,
682 			    sizeof (record.zi_func));
683 			break;
684 		case 'q':
685 			quiet = 1;
686 			break;
687 		case 'r':
688 			range = optarg;
689 			break;
690 		case 's':
691 			dur_secs = 1;
692 			record.zi_duration = (int)strtol(optarg, &end, 10);
693 			if (record.zi_duration <= 0 || *end != '\0') {
694 				(void) fprintf(stderr, "invalid duration '%s': "
695 				    "must be a positive integer\n", optarg);
696 				usage();
697 				return (1);
698 			}
699 			break;
700 		case 'T':
701 			if (strcasecmp(optarg, "read") == 0) {
702 				io_type = ZIO_TYPE_READ;
703 			} else if (strcasecmp(optarg, "write") == 0) {
704 				io_type = ZIO_TYPE_WRITE;
705 			} else if (strcasecmp(optarg, "free") == 0) {
706 				io_type = ZIO_TYPE_FREE;
707 			} else if (strcasecmp(optarg, "claim") == 0) {
708 				io_type = ZIO_TYPE_CLAIM;
709 			} else if (strcasecmp(optarg, "all") == 0) {
710 				io_type = ZIO_TYPES;
711 			} else {
712 				(void) fprintf(stderr, "invalid I/O type "
713 				    "'%s': must be 'read', 'write', 'free', "
714 				    "'claim' or 'all'\n", optarg);
715 				usage();
716 				return (1);
717 			}
718 			break;
719 		case 't':
720 			if ((type = name_to_type(optarg)) == TYPE_INVAL &&
721 			    !MOS_TYPE(type)) {
722 				(void) fprintf(stderr, "invalid type '%s'\n",
723 				    optarg);
724 				usage();
725 				return (1);
726 			}
727 			break;
728 		case 'u':
729 			flags |= ZINJECT_UNLOAD_SPA;
730 			break;
731 		case 'L':
732 			if ((label = name_to_type(optarg)) == TYPE_INVAL &&
733 			    !LABEL_TYPE(type)) {
734 				(void) fprintf(stderr, "invalid label type "
735 				    "'%s'\n", optarg);
736 				usage();
737 				return (1);
738 			}
739 			break;
740 		case ':':
741 			(void) fprintf(stderr, "option -%c requires an "
742 			    "operand\n", optopt);
743 			usage();
744 			return (1);
745 		case '?':
746 			(void) fprintf(stderr, "invalid option '%c'\n",
747 			    optopt);
748 			usage();
749 			return (2);
750 		}
751 	}
752 
753 	argc -= optind;
754 	argv += optind;
755 
756 	if (cancel != NULL) {
757 		/*
758 		 * '-c' is invalid with any other options.
759 		 */
760 		if (raw != NULL || range != NULL || type != TYPE_INVAL ||
761 		    level != 0 || record.zi_func[0] != '\0' ||
762 		    record.zi_duration != 0) {
763 			(void) fprintf(stderr, "cancel (-c) incompatible with "
764 			    "any other options\n");
765 			usage();
766 			return (2);
767 		}
768 		if (argc != 0) {
769 			(void) fprintf(stderr, "extraneous argument to '-c'\n");
770 			usage();
771 			return (2);
772 		}
773 
774 		if (strcmp(cancel, "all") == 0) {
775 			return (cancel_all_handlers());
776 		} else {
777 			int id = (int)strtol(cancel, &end, 10);
778 			if (*end != '\0') {
779 				(void) fprintf(stderr, "invalid handle id '%s':"
780 				    " must be an integer or 'all'\n", cancel);
781 				usage();
782 				return (1);
783 			}
784 			return (cancel_handler(id));
785 		}
786 	}
787 
788 	if (device != NULL) {
789 		/*
790 		 * Device (-d) injection uses a completely different mechanism
791 		 * for doing injection, so handle it separately here.
792 		 */
793 		if (raw != NULL || range != NULL || type != TYPE_INVAL ||
794 		    level != 0 || record.zi_func[0] != '\0' ||
795 		    record.zi_duration != 0) {
796 			(void) fprintf(stderr, "device (-d) incompatible with "
797 			    "data error injection\n");
798 			usage();
799 			return (2);
800 		}
801 
802 		if (argc != 1) {
803 			(void) fprintf(stderr, "device (-d) injection requires "
804 			    "a single pool name\n");
805 			usage();
806 			return (2);
807 		}
808 
809 		(void) strcpy(pool, argv[0]);
810 		dataset[0] = '\0';
811 
812 		if (error == ECKSUM) {
813 			(void) fprintf(stderr, "device error type must be "
814 			    "'io' or 'nxio'\n");
815 			return (1);
816 		}
817 
818 		record.zi_iotype = io_type;
819 		if (translate_device(pool, device, label, &record) != 0)
820 			return (1);
821 		if (!error)
822 			error = ENXIO;
823 
824 		if (action != VDEV_STATE_UNKNOWN)
825 			return (perform_action(pool, &record, action));
826 
827 	} else if (raw != NULL) {
828 		if (range != NULL || type != TYPE_INVAL || level != 0 ||
829 		    record.zi_func[0] != '\0' || record.zi_duration != 0) {
830 			(void) fprintf(stderr, "raw (-b) format with "
831 			    "any other options\n");
832 			usage();
833 			return (2);
834 		}
835 
836 		if (argc != 1) {
837 			(void) fprintf(stderr, "raw (-b) format expects a "
838 			    "single pool name\n");
839 			usage();
840 			return (2);
841 		}
842 
843 		(void) strcpy(pool, argv[0]);
844 		dataset[0] = '\0';
845 
846 		if (error == ENXIO) {
847 			(void) fprintf(stderr, "data error type must be "
848 			    "'checksum' or 'io'\n");
849 			return (1);
850 		}
851 
852 		if (translate_raw(raw, &record) != 0)
853 			return (1);
854 		if (!error)
855 			error = EIO;
856 	} else if (record.zi_func[0] != '\0') {
857 		if (raw != NULL || range != NULL || type != TYPE_INVAL ||
858 		    level != 0 || device != NULL || record.zi_duration != 0) {
859 			(void) fprintf(stderr, "panic (-p) incompatible with "
860 			    "other options\n");
861 			usage();
862 			return (2);
863 		}
864 
865 		if (argc < 1 || argc > 2) {
866 			(void) fprintf(stderr, "panic (-p) injection requires "
867 			    "a single pool name and an optional id\n");
868 			usage();
869 			return (2);
870 		}
871 
872 		(void) strcpy(pool, argv[0]);
873 		if (argv[1] != NULL)
874 			record.zi_type = atoi(argv[1]);
875 		dataset[0] = '\0';
876 	} else if (record.zi_duration != 0) {
877 		if (nowrites == 0) {
878 			(void) fprintf(stderr, "-s or -g meaningless "
879 			    "without -I (ignore writes)\n");
880 			usage();
881 			return (2);
882 		} else if (dur_secs && dur_txg) {
883 			(void) fprintf(stderr, "choose a duration either "
884 			    "in seconds (-s) or a number of txgs (-g) "
885 			    "but not both\n");
886 			usage();
887 			return (2);
888 		} else if (argc != 1) {
889 			(void) fprintf(stderr, "ignore writes (-I) "
890 			    "injection requires a single pool name\n");
891 			usage();
892 			return (2);
893 		}
894 
895 		(void) strcpy(pool, argv[0]);
896 		dataset[0] = '\0';
897 	} else if (type == TYPE_INVAL) {
898 		if (flags == 0) {
899 			(void) fprintf(stderr, "at least one of '-b', '-d', "
900 			    "'-t', '-a', '-p', '-I' or '-u' "
901 			    "must be specified\n");
902 			usage();
903 			return (2);
904 		}
905 
906 		if (argc == 1 && (flags & ZINJECT_UNLOAD_SPA)) {
907 			(void) strcpy(pool, argv[0]);
908 			dataset[0] = '\0';
909 		} else if (argc != 0) {
910 			(void) fprintf(stderr, "extraneous argument for "
911 			    "'-f'\n");
912 			usage();
913 			return (2);
914 		}
915 
916 		flags |= ZINJECT_NULL;
917 	} else {
918 		if (argc != 1) {
919 			(void) fprintf(stderr, "missing object\n");
920 			usage();
921 			return (2);
922 		}
923 
924 		if (error == ENXIO) {
925 			(void) fprintf(stderr, "data error type must be "
926 			    "'checksum' or 'io'\n");
927 			return (1);
928 		}
929 
930 		if (translate_record(type, argv[0], range, level, &record, pool,
931 		    dataset) != 0)
932 			return (1);
933 		if (!error)
934 			error = EIO;
935 	}
936 
937 	/*
938 	 * If this is pool-wide metadata, unmount everything.  The ioctl() will
939 	 * unload the pool, so that we trigger spa-wide reopen of metadata next
940 	 * time we access the pool.
941 	 */
942 	if (dataset[0] != '\0' && domount) {
943 		if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_DATASET)) == NULL)
944 			return (1);
945 
946 		if (zfs_unmount(zhp, NULL, 0) != 0)
947 			return (1);
948 	}
949 
950 	record.zi_error = error;
951 
952 	ret = register_handler(pool, flags, &record, quiet);
953 
954 	if (dataset[0] != '\0' && domount)
955 		ret = (zfs_mount(zhp, NULL, 0) != 0);
956 
957 	libzfs_fini(g_zfs);
958 
959 	return (ret);
960 }
961