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