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