Avoid ARC buffer transfrom operations in prefetch
[zfs.git] / cmd / zinject / zinject.c
blob4374e69a7f94d9529f9db33c8646bd30010f0ec7
1 /*
2 * CDDL HEADER START
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.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or https://opensource.org/licenses/CDDL-1.0.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
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]
19 * CDDL HEADER END
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
24 * Copyright (c) 2017, Intel Corporation.
25 * Copyright (c) 2023-2025, Klara, Inc.
29 * ZFS Fault Injector
31 * This userland component takes a set of options and uses libzpool to translate
32 * from a user-visible object type and name to an internal representation.
33 * There are two basic types of faults: device faults and data faults.
36 * DEVICE FAULTS
38 * Errors can be injected into a particular vdev using the '-d' option. This
39 * option takes a path or vdev GUID to uniquely identify the device within a
40 * pool. There are four types of errors that can be injected, IO, ENXIO,
41 * ECHILD, and EILSEQ. These can be controlled through the '-e' option and the
42 * default is ENXIO. For EIO failures, any attempt to read data from the device
43 * will return EIO, but a subsequent attempt to reopen the device will succeed.
44 * For ENXIO failures, any attempt to read from the device will return EIO, but
45 * any attempt to reopen the device will also return ENXIO. The EILSEQ failures
46 * only apply to read operations (-T read) and will flip a bit after the device
47 * has read the original data.
49 * For label faults, the -L option must be specified. This allows faults
50 * to be injected into either the nvlist, uberblock, pad1, or pad2 region
51 * of all the labels for the specified device.
53 * This form of the command looks like:
55 * zinject -d device [-e errno] [-L <uber | nvlist | pad1 | pad2>] pool
58 * DATA FAULTS
60 * We begin with a tuple of the form:
62 * <type,level,range,object>
64 * type A string describing the type of data to target. Each type
65 * implicitly describes how to interpret 'object'. Currently,
66 * the following values are supported:
68 * data User data for a file
69 * dnode Dnode for a file or directory
71 * The following MOS objects are special. Instead of injecting
72 * errors on a particular object or blkid, we inject errors across
73 * all objects of the given type.
75 * mos Any data in the MOS
76 * mosdir object directory
77 * config pool configuration
78 * bpobj blkptr list
79 * spacemap spacemap
80 * metaslab metaslab
81 * errlog persistent error log
83 * level Object level. Defaults to '0', not applicable to all types. If
84 * a range is given, this corresponds to the indirect block
85 * corresponding to the specific range.
87 * range A numerical range [start,end) within the object. Defaults to
88 * the full size of the file.
90 * object A string describing the logical location of the object. For
91 * files and directories (currently the only supported types),
92 * this is the path of the object on disk.
94 * This is translated, via libzpool, into the following internal representation:
96 * <type,objset,object,level,range>
98 * These types should be self-explanatory. This tuple is then passed to the
99 * kernel via a special ioctl() to initiate fault injection for the given
100 * object. Note that 'type' is not strictly necessary for fault injection, but
101 * is used when translating existing faults into a human-readable string.
104 * The command itself takes one of the forms:
106 * zinject
107 * zinject <-a | -u pool>
108 * zinject -c <id|all>
109 * zinject [-q] <-t type> [-f freq] [-u] [-a] [-m] [-e errno] [-l level]
110 * [-r range] <object>
111 * zinject [-f freq] [-a] [-m] [-u] -b objset:object:level:start:end pool
113 * With no arguments, the command prints all currently registered injection
114 * handlers, with their numeric identifiers.
116 * The '-c' option will clear the given handler, or all handlers if 'all' is
117 * specified.
119 * The '-e' option takes a string describing the errno to simulate. This must
120 * be one of 'io', 'checksum', 'decompress', or 'decrypt'. In most cases this
121 * will result in the same behavior, but RAID-Z will produce a different set of
122 * ereports for this situation.
124 * The '-a', '-u', and '-m' flags toggle internal flush behavior. If '-a' is
125 * specified, then the ARC cache is flushed appropriately. If '-u' is
126 * specified, then the underlying SPA is unloaded. Either of these flags can be
127 * specified independently of any other handlers. The '-m' flag automatically
128 * does an unmount and remount of the underlying dataset to aid in flushing the
129 * cache.
131 * The '-f' flag controls the frequency of errors injected, expressed as a
132 * real number percentage between 0.0001 and 100. The default is 100.
134 * The this form is responsible for actually injecting the handler into the
135 * framework. It takes the arguments described above, translates them to the
136 * internal tuple using libzpool, and then issues an ioctl() to register the
137 * handler.
139 * The final form can target a specific bookmark, regardless of whether a
140 * human-readable interface has been designed. It allows developers to specify
141 * a particular block by number.
144 #include <errno.h>
145 #include <fcntl.h>
146 #include <stdio.h>
147 #include <stdlib.h>
148 #include <string.h>
149 #include <strings.h>
150 #include <unistd.h>
152 #include <sys/fs/zfs.h>
153 #include <sys/mount.h>
155 #include <libzfs.h>
157 #undef verify /* both libzfs.h and zfs_context.h want to define this */
159 #include "zinject.h"
161 libzfs_handle_t *g_zfs;
162 int zfs_fd;
164 static const char *const errtable[TYPE_INVAL] = {
165 "data",
166 "dnode",
167 "mos",
168 "mosdir",
169 "metaslab",
170 "config",
171 "bpobj",
172 "spacemap",
173 "errlog",
174 "uber",
175 "nvlist",
176 "pad1",
177 "pad2"
180 static err_type_t
181 name_to_type(const char *arg)
183 int i;
184 for (i = 0; i < TYPE_INVAL; i++)
185 if (strcmp(errtable[i], arg) == 0)
186 return (i);
188 return (TYPE_INVAL);
191 static const char *
192 type_to_name(uint64_t type)
194 switch (type) {
195 case DMU_OT_OBJECT_DIRECTORY:
196 return ("mosdir");
197 case DMU_OT_OBJECT_ARRAY:
198 return ("metaslab");
199 case DMU_OT_PACKED_NVLIST:
200 return ("config");
201 case DMU_OT_BPOBJ:
202 return ("bpobj");
203 case DMU_OT_SPACE_MAP:
204 return ("spacemap");
205 case DMU_OT_ERROR_LOG:
206 return ("errlog");
207 default:
208 return ("-");
212 struct errstr {
213 int err;
214 const char *str;
216 static const struct errstr errstrtable[] = {
217 { EIO, "io" },
218 { ECKSUM, "checksum" },
219 { EINVAL, "decompress" },
220 { EACCES, "decrypt" },
221 { ENXIO, "nxio" },
222 { ECHILD, "dtl" },
223 { EILSEQ, "corrupt" },
224 { ENOSYS, "noop" },
225 { 0, NULL },
228 static int
229 str_to_err(const char *str)
231 for (int i = 0; errstrtable[i].str != NULL; i++)
232 if (strcasecmp(errstrtable[i].str, str) == 0)
233 return (errstrtable[i].err);
234 return (-1);
236 static const char *
237 err_to_str(int err)
239 for (int i = 0; errstrtable[i].str != NULL; i++)
240 if (errstrtable[i].err == err)
241 return (errstrtable[i].str);
242 return ("[unknown]");
245 static const char *const iotypestrtable[ZINJECT_IOTYPES] = {
246 [ZINJECT_IOTYPE_NULL] = "null",
247 [ZINJECT_IOTYPE_READ] = "read",
248 [ZINJECT_IOTYPE_WRITE] = "write",
249 [ZINJECT_IOTYPE_FREE] = "free",
250 [ZINJECT_IOTYPE_CLAIM] = "claim",
251 [ZINJECT_IOTYPE_FLUSH] = "flush",
252 [ZINJECT_IOTYPE_TRIM] = "trim",
253 [ZINJECT_IOTYPE_ALL] = "all",
254 [ZINJECT_IOTYPE_PROBE] = "probe",
257 static zinject_iotype_t
258 str_to_iotype(const char *arg)
260 for (uint_t iotype = 0; iotype < ZINJECT_IOTYPES; iotype++)
261 if (iotypestrtable[iotype] != NULL &&
262 strcasecmp(iotypestrtable[iotype], arg) == 0)
263 return (iotype);
264 return (ZINJECT_IOTYPES);
267 static const char *
268 iotype_to_str(zinject_iotype_t iotype)
270 if (iotype >= ZINJECT_IOTYPES || iotypestrtable[iotype] == NULL)
271 return ("[unknown]");
272 return (iotypestrtable[iotype]);
276 * Print usage message.
278 void
279 usage(void)
281 (void) printf(
282 "usage:\n"
283 "\n"
284 "\tzinject\n"
285 "\n"
286 "\t\tList all active injection records.\n"
287 "\n"
288 "\tzinject -c <id|all>\n"
289 "\n"
290 "\t\tClear the particular record (if given a numeric ID), or\n"
291 "\t\tall records if 'all' is specified.\n"
292 "\n"
293 "\tzinject -p <function name> pool\n"
294 "\t\tInject a panic fault at the specified function. Only \n"
295 "\t\tfunctions which call spa_vdev_config_exit(), or \n"
296 "\t\tspa_vdev_exit() will trigger a panic.\n"
297 "\n"
298 "\tzinject -d device [-e errno] [-L <nvlist|uber|pad1|pad2>] [-F]\n"
299 "\t\t[-T <read|write|free|claim|flush|all>] [-f frequency] pool\n\n"
300 "\t\tInject a fault into a particular device or the device's\n"
301 "\t\tlabel. Label injection can either be 'nvlist', 'uber',\n "
302 "\t\t'pad1', or 'pad2'.\n"
303 "\t\t'errno' can be 'nxio' (the default), 'io', 'dtl',\n"
304 "\t\t'corrupt' (bit flip), or 'noop' (successfully do nothing).\n"
305 "\t\t'frequency' is a value between 0.0001 and 100.0 that limits\n"
306 "\t\tdevice error injection to a percentage of the IOs.\n"
307 "\n"
308 "\tzinject -d device -A <degrade|fault> -D <delay secs> pool\n"
309 "\t\tPerform a specific action on a particular device.\n"
310 "\n"
311 "\tzinject -d device -D latency:lanes pool\n"
312 "\n"
313 "\t\tAdd an artificial delay to IO requests on a particular\n"
314 "\t\tdevice, such that the requests take a minimum of 'latency'\n"
315 "\t\tmilliseconds to complete. Each delay has an associated\n"
316 "\t\tnumber of 'lanes' which defines the number of concurrent\n"
317 "\t\tIO requests that can be processed.\n"
318 "\n"
319 "\t\tFor example, with a single lane delay of 10 ms (-D 10:1),\n"
320 "\t\tthe device will only be able to service a single IO request\n"
321 "\t\tat a time with each request taking 10 ms to complete. So,\n"
322 "\t\tif only a single request is submitted every 10 ms, the\n"
323 "\t\taverage latency will be 10 ms; but if more than one request\n"
324 "\t\tis submitted every 10 ms, the average latency will be more\n"
325 "\t\tthan 10 ms.\n"
326 "\n"
327 "\t\tSimilarly, if a delay of 10 ms is specified to have two\n"
328 "\t\tlanes (-D 10:2), then the device will be able to service\n"
329 "\t\ttwo requests at a time, each with a minimum latency of\n"
330 "\t\t10 ms. So, if two requests are submitted every 10 ms, then\n"
331 "\t\tthe average latency will be 10 ms; but if more than two\n"
332 "\t\trequests are submitted every 10 ms, the average latency\n"
333 "\t\twill be more than 10 ms.\n"
334 "\n"
335 "\t\tAlso note, these delays are additive. So two invocations\n"
336 "\t\tof '-D 10:1', is roughly equivalent to a single invocation\n"
337 "\t\tof '-D 10:2'. This also means, one can specify multiple\n"
338 "\t\tlanes with differing target latencies. For example, an\n"
339 "\t\tinvocation of '-D 10:1' followed by '-D 25:2' will\n"
340 "\t\tcreate 3 lanes on the device; one lane with a latency\n"
341 "\t\tof 10 ms and two lanes with a 25 ms latency.\n"
342 "\n"
343 "\tzinject -P import|export -s <seconds> pool\n"
344 "\t\tAdd an artificial delay to a future pool import or export,\n"
345 "\t\tsuch that the operation takes a minimum of supplied seconds\n"
346 "\t\tto complete.\n"
347 "\n"
348 "\tzinject -I [-s <seconds> | -g <txgs>] pool\n"
349 "\t\tCause the pool to stop writing blocks yet not\n"
350 "\t\treport errors for a duration. Simulates buggy hardware\n"
351 "\t\tthat fails to honor cache flush requests.\n"
352 "\t\tDefault duration is 30 seconds. The machine is panicked\n"
353 "\t\tat the end of the duration.\n"
354 "\n"
355 "\tzinject -b objset:object:level:blkid pool\n"
356 "\n"
357 "\t\tInject an error into pool 'pool' with the numeric bookmark\n"
358 "\t\tspecified by the remaining tuple. Each number is in\n"
359 "\t\thexadecimal, and only one block can be specified.\n"
360 "\n"
361 "\tzinject [-q] <-t type> [-C dvas] [-e errno] [-l level]\n"
362 "\t\t[-r range] [-a] [-m] [-u] [-f freq] <object>\n"
363 "\n"
364 "\t\tInject an error into the object specified by the '-t' option\n"
365 "\t\tand the object descriptor. The 'object' parameter is\n"
366 "\t\tinterpreted depending on the '-t' option.\n"
367 "\n"
368 "\t\t-q\tQuiet mode. Only print out the handler number added.\n"
369 "\t\t-e\tInject a specific error. Must be one of 'io',\n"
370 "\t\t\t'checksum', 'decompress', or 'decrypt'. Default is 'io'.\n"
371 "\t\t-C\tInject the given error only into specific DVAs. The\n"
372 "\t\t\tDVAs should be specified as a list of 0-indexed DVAs\n"
373 "\t\t\tseparated by commas (ex. '0,2').\n"
374 "\t\t-l\tInject error at a particular block level. Default is "
375 "0.\n"
376 "\t\t-m\tAutomatically remount underlying filesystem.\n"
377 "\t\t-r\tInject error over a particular logical range of an\n"
378 "\t\t\tobject. Will be translated to the appropriate blkid\n"
379 "\t\t\trange according to the object's properties.\n"
380 "\t\t-a\tFlush the ARC cache. Can be specified without any\n"
381 "\t\t\tassociated object.\n"
382 "\t\t-u\tUnload the associated pool. Can be specified with only\n"
383 "\t\t\ta pool object.\n"
384 "\t\t-f\tOnly inject errors a fraction of the time. Expressed as\n"
385 "\t\t\ta percentage between 0.0001 and 100.\n"
386 "\n"
387 "\t-t data\t\tInject an error into the plain file contents of a\n"
388 "\t\t\tfile. The object must be specified as a complete path\n"
389 "\t\t\tto a file on a ZFS filesystem.\n"
390 "\n"
391 "\t-t dnode\tInject an error into the metadnode in the block\n"
392 "\t\t\tcorresponding to the dnode for a file or directory. The\n"
393 "\t\t\t'-r' option is incompatible with this mode. The object\n"
394 "\t\t\tis specified as a complete path to a file or directory\n"
395 "\t\t\ton a ZFS filesystem.\n"
396 "\n"
397 "\t-t <mos>\tInject errors into the MOS for objects of the given\n"
398 "\t\t\ttype. Valid types are: mos, mosdir, config, bpobj,\n"
399 "\t\t\tspacemap, metaslab, errlog. The only valid <object> is\n"
400 "\t\t\tthe poolname.\n");
403 static int
404 iter_handlers(int (*func)(int, const char *, zinject_record_t *, void *),
405 void *data)
407 zfs_cmd_t zc = {"\0"};
408 int ret;
410 while (zfs_ioctl(g_zfs, ZFS_IOC_INJECT_LIST_NEXT, &zc) == 0)
411 if ((ret = func((int)zc.zc_guid, zc.zc_name,
412 &zc.zc_inject_record, data)) != 0)
413 return (ret);
415 if (errno != ENOENT) {
416 (void) fprintf(stderr, "Unable to list handlers: %s\n",
417 strerror(errno));
418 return (-1);
421 return (0);
424 static int
425 print_data_handler(int id, const char *pool, zinject_record_t *record,
426 void *data)
428 int *count = data;
430 if (record->zi_guid != 0 || record->zi_func[0] != '\0' ||
431 record->zi_duration != 0) {
432 return (0);
435 if (*count == 0) {
436 (void) printf("%3s %-15s %-6s %-6s %-8s %3s %-4s "
437 "%-15s %-6s %-15s\n", "ID", "POOL", "OBJSET", "OBJECT",
438 "TYPE", "LVL", "DVAs", "RANGE", "MATCH", "INJECT");
439 (void) printf("--- --------------- ------ "
440 "------ -------- --- ---- --------------- "
441 "------ ------\n");
444 *count += 1;
446 char rangebuf[32];
447 if (record->zi_start == 0 && record->zi_end == -1ULL)
448 snprintf(rangebuf, sizeof (rangebuf), "all");
449 else
450 snprintf(rangebuf, sizeof (rangebuf), "[%llu, %llu]",
451 (u_longlong_t)record->zi_start,
452 (u_longlong_t)record->zi_end);
455 (void) printf("%3d %-15s %-6llu %-6llu %-8s %-3d 0x%02x %-15s "
456 "%6lu %6lu\n", id, pool, (u_longlong_t)record->zi_objset,
457 (u_longlong_t)record->zi_object, type_to_name(record->zi_type),
458 record->zi_level, record->zi_dvas, rangebuf,
459 record->zi_match_count, record->zi_inject_count);
461 return (0);
464 static int
465 print_device_handler(int id, const char *pool, zinject_record_t *record,
466 void *data)
468 int *count = data;
470 if (record->zi_guid == 0 || record->zi_func[0] != '\0')
471 return (0);
473 if (record->zi_cmd == ZINJECT_DELAY_IO)
474 return (0);
476 if (*count == 0) {
477 (void) printf("%3s %-15s %-16s %-5s %-10s %-9s "
478 "%-6s %-6s\n",
479 "ID", "POOL", "GUID", "TYPE", "ERROR", "FREQ",
480 "MATCH", "INJECT");
481 (void) printf(
482 "--- --------------- ---------------- "
483 "----- ---------- --------- "
484 "------ ------\n");
487 *count += 1;
489 double freq = record->zi_freq == 0 ? 100.0f :
490 (((double)record->zi_freq) / ZI_PERCENTAGE_MAX) * 100.0f;
492 (void) printf("%3d %-15s %llx %-5s %-10s %8.4f%% "
493 "%6lu %6lu\n", id, pool, (u_longlong_t)record->zi_guid,
494 iotype_to_str(record->zi_iotype), err_to_str(record->zi_error),
495 freq, record->zi_match_count, record->zi_inject_count);
497 return (0);
500 static int
501 print_delay_handler(int id, const char *pool, zinject_record_t *record,
502 void *data)
504 int *count = data;
506 if (record->zi_guid == 0 || record->zi_func[0] != '\0')
507 return (0);
509 if (record->zi_cmd != ZINJECT_DELAY_IO)
510 return (0);
512 if (*count == 0) {
513 (void) printf("%3s %-15s %-16s %-10s %-5s %-9s "
514 "%-6s %-6s\n",
515 "ID", "POOL", "GUID", "DELAY (ms)", "LANES", "FREQ",
516 "MATCH", "INJECT");
517 (void) printf("--- --------------- ---------------- "
518 "---------- ----- --------- "
519 "------ ------\n");
522 *count += 1;
524 double freq = record->zi_freq == 0 ? 100.0f :
525 (((double)record->zi_freq) / ZI_PERCENTAGE_MAX) * 100.0f;
527 (void) printf("%3d %-15s %llx %10llu %5llu %8.4f%% "
528 "%6lu %6lu\n", id, pool, (u_longlong_t)record->zi_guid,
529 (u_longlong_t)NSEC2MSEC(record->zi_timer),
530 (u_longlong_t)record->zi_nlanes,
531 freq, record->zi_match_count, record->zi_inject_count);
533 return (0);
536 static int
537 print_panic_handler(int id, const char *pool, zinject_record_t *record,
538 void *data)
540 int *count = data;
542 if (record->zi_func[0] == '\0')
543 return (0);
545 if (*count == 0) {
546 (void) printf("%3s %-15s %s\n", "ID", "POOL", "FUNCTION");
547 (void) printf("--- --------------- ----------------\n");
550 *count += 1;
552 (void) printf("%3d %-15s %s\n", id, pool, record->zi_func);
554 return (0);
557 static int
558 print_pool_delay_handler(int id, const char *pool, zinject_record_t *record,
559 void *data)
561 int *count = data;
563 if (record->zi_cmd != ZINJECT_DELAY_IMPORT &&
564 record->zi_cmd != ZINJECT_DELAY_EXPORT) {
565 return (0);
568 if (*count == 0) {
569 (void) printf("%3s %-19s %-11s %s\n",
570 "ID", "POOL", "DELAY (sec)", "COMMAND");
571 (void) printf("--- ------------------- -----------"
572 " -------\n");
575 *count += 1;
577 (void) printf("%3d %-19s %-11llu %s\n",
578 id, pool, (u_longlong_t)record->zi_duration,
579 record->zi_cmd == ZINJECT_DELAY_IMPORT ? "import": "export");
581 return (0);
585 * Print all registered error handlers. Returns the number of handlers
586 * registered.
588 static int
589 print_all_handlers(void)
591 int count = 0, total = 0;
593 (void) iter_handlers(print_device_handler, &count);
594 if (count > 0) {
595 total += count;
596 (void) printf("\n");
597 count = 0;
600 (void) iter_handlers(print_delay_handler, &count);
601 if (count > 0) {
602 total += count;
603 (void) printf("\n");
604 count = 0;
607 (void) iter_handlers(print_data_handler, &count);
608 if (count > 0) {
609 total += count;
610 (void) printf("\n");
611 count = 0;
614 (void) iter_handlers(print_pool_delay_handler, &count);
615 if (count > 0) {
616 total += count;
617 (void) printf("\n");
618 count = 0;
621 (void) iter_handlers(print_panic_handler, &count);
623 return (count + total);
626 static int
627 cancel_one_handler(int id, const char *pool, zinject_record_t *record,
628 void *data)
630 (void) pool, (void) record, (void) data;
631 zfs_cmd_t zc = {"\0"};
633 zc.zc_guid = (uint64_t)id;
635 if (zfs_ioctl(g_zfs, ZFS_IOC_CLEAR_FAULT, &zc) != 0) {
636 (void) fprintf(stderr, "failed to remove handler %d: %s\n",
637 id, strerror(errno));
638 return (1);
641 return (0);
645 * Remove all fault injection handlers.
647 static int
648 cancel_all_handlers(void)
650 int ret = iter_handlers(cancel_one_handler, NULL);
652 if (ret == 0)
653 (void) printf("removed all registered handlers\n");
655 return (ret);
659 * Remove a specific fault injection handler.
661 static int
662 cancel_handler(int id)
664 zfs_cmd_t zc = {"\0"};
666 zc.zc_guid = (uint64_t)id;
668 if (zfs_ioctl(g_zfs, ZFS_IOC_CLEAR_FAULT, &zc) != 0) {
669 (void) fprintf(stderr, "failed to remove handler %d: %s\n",
670 id, strerror(errno));
671 return (1);
674 (void) printf("removed handler %d\n", id);
676 return (0);
680 * Register a new fault injection handler.
682 static int
683 register_handler(const char *pool, int flags, zinject_record_t *record,
684 int quiet)
686 zfs_cmd_t zc = {"\0"};
688 (void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
689 zc.zc_inject_record = *record;
690 zc.zc_guid = flags;
692 if (zfs_ioctl(g_zfs, ZFS_IOC_INJECT_FAULT, &zc) != 0) {
693 const char *errmsg = strerror(errno);
695 switch (errno) {
696 case EDOM:
697 errmsg = "block level exceeds max level of object";
698 break;
699 case EEXIST:
700 if (record->zi_cmd == ZINJECT_DELAY_IMPORT)
701 errmsg = "pool already imported";
702 if (record->zi_cmd == ZINJECT_DELAY_EXPORT)
703 errmsg = "a handler already exists";
704 break;
705 case ENOENT:
706 /* import delay injector running on older zfs module */
707 if (record->zi_cmd == ZINJECT_DELAY_IMPORT)
708 errmsg = "import delay injector not supported";
709 break;
710 default:
711 break;
713 (void) fprintf(stderr, "failed to add handler: %s\n", errmsg);
714 return (1);
717 if (flags & ZINJECT_NULL)
718 return (0);
720 if (quiet) {
721 (void) printf("%llu\n", (u_longlong_t)zc.zc_guid);
722 } else {
723 (void) printf("Added handler %llu with the following "
724 "properties:\n", (u_longlong_t)zc.zc_guid);
725 (void) printf(" pool: %s\n", pool);
726 if (record->zi_guid) {
727 (void) printf(" vdev: %llx\n",
728 (u_longlong_t)record->zi_guid);
729 } else if (record->zi_func[0] != '\0') {
730 (void) printf(" panic function: %s\n",
731 record->zi_func);
732 } else if (record->zi_duration > 0) {
733 (void) printf(" time: %lld seconds\n",
734 (u_longlong_t)record->zi_duration);
735 } else if (record->zi_duration < 0) {
736 (void) printf(" txgs: %lld \n",
737 (u_longlong_t)-record->zi_duration);
738 } else if (record->zi_timer > 0) {
739 (void) printf(" timer: %lld ms\n",
740 (u_longlong_t)NSEC2MSEC(record->zi_timer));
741 } else {
742 (void) printf("objset: %llu\n",
743 (u_longlong_t)record->zi_objset);
744 (void) printf("object: %llu\n",
745 (u_longlong_t)record->zi_object);
746 (void) printf(" type: %llu\n",
747 (u_longlong_t)record->zi_type);
748 (void) printf(" level: %d\n", record->zi_level);
749 if (record->zi_start == 0 &&
750 record->zi_end == -1ULL)
751 (void) printf(" range: all\n");
752 else
753 (void) printf(" range: [%llu, %llu)\n",
754 (u_longlong_t)record->zi_start,
755 (u_longlong_t)record->zi_end);
756 (void) printf(" dvas: 0x%x\n", record->zi_dvas);
760 return (0);
763 static int
764 perform_action(const char *pool, zinject_record_t *record, int cmd)
766 zfs_cmd_t zc = {"\0"};
768 ASSERT(cmd == VDEV_STATE_DEGRADED || cmd == VDEV_STATE_FAULTED);
769 (void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
770 zc.zc_guid = record->zi_guid;
771 zc.zc_cookie = cmd;
773 if (zfs_ioctl(g_zfs, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
774 return (0);
776 return (1);
779 static int
780 parse_delay(char *str, uint64_t *delay, uint64_t *nlanes)
782 unsigned long scan_delay;
783 unsigned long scan_nlanes;
785 if (sscanf(str, "%lu:%lu", &scan_delay, &scan_nlanes) != 2)
786 return (1);
789 * We explicitly disallow a delay of zero here, because we key
790 * off this value being non-zero in translate_device(), to
791 * determine if the fault is a ZINJECT_DELAY_IO fault or not.
793 if (scan_delay == 0)
794 return (1);
797 * The units for the CLI delay parameter is milliseconds, but
798 * the data passed to the kernel is interpreted as nanoseconds.
799 * Thus we scale the milliseconds to nanoseconds here, and this
800 * nanosecond value is used to pass the delay to the kernel.
802 *delay = MSEC2NSEC(scan_delay);
803 *nlanes = scan_nlanes;
805 return (0);
808 static int
809 parse_frequency(const char *str, uint32_t *percent)
811 double val;
812 char *post;
814 val = strtod(str, &post);
815 if (post == NULL || *post != '\0')
816 return (EINVAL);
818 /* valid range is [0.0001, 100.0] */
819 val /= 100.0f;
820 if (val < 0.000001f || val > 1.0f)
821 return (ERANGE);
823 /* convert to an integer for use by kernel */
824 *percent = ((uint32_t)(val * ZI_PERCENTAGE_MAX));
826 return (0);
830 * This function converts a string specifier for DVAs into a bit mask.
831 * The dva's provided by the user should be 0 indexed and separated by
832 * a comma. For example:
833 * "1" -> 0b0010 (0x2)
834 * "0,1" -> 0b0011 (0x3)
835 * "0,1,2" -> 0b0111 (0x7)
837 static int
838 parse_dvas(const char *str, uint32_t *dvas_out)
840 const char *c = str;
841 uint32_t mask = 0;
842 boolean_t need_delim = B_FALSE;
844 /* max string length is 5 ("0,1,2") */
845 if (strlen(str) > 5 || strlen(str) == 0)
846 return (EINVAL);
848 while (*c != '\0') {
849 switch (*c) {
850 case '0':
851 case '1':
852 case '2':
853 /* check for pipe between DVAs */
854 if (need_delim)
855 return (EINVAL);
857 /* check if this DVA has been set already */
858 if (mask & (1 << ((*c) - '0')))
859 return (EINVAL);
861 mask |= (1 << ((*c) - '0'));
862 need_delim = B_TRUE;
863 break;
864 case ',':
865 need_delim = B_FALSE;
866 break;
867 default:
868 /* check for invalid character */
869 return (EINVAL);
871 c++;
874 /* check for dangling delimiter */
875 if (!need_delim)
876 return (EINVAL);
878 *dvas_out = mask;
879 return (0);
883 main(int argc, char **argv)
885 int c;
886 char *range = NULL;
887 char *cancel = NULL;
888 char *end;
889 char *raw = NULL;
890 char *device = NULL;
891 int level = 0;
892 int quiet = 0;
893 int error = 0;
894 int domount = 0;
895 int io_type = ZINJECT_IOTYPE_ALL;
896 int action = VDEV_STATE_UNKNOWN;
897 err_type_t type = TYPE_INVAL;
898 err_type_t label = TYPE_INVAL;
899 zinject_record_t record = { 0 };
900 char pool[MAXNAMELEN] = "";
901 char dataset[MAXNAMELEN] = "";
902 zfs_handle_t *zhp = NULL;
903 int nowrites = 0;
904 int dur_txg = 0;
905 int dur_secs = 0;
906 int ret;
907 int flags = 0;
908 uint32_t dvas = 0;
910 if ((g_zfs = libzfs_init()) == NULL) {
911 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
912 return (1);
915 libzfs_print_on_error(g_zfs, B_TRUE);
917 if ((zfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
918 (void) fprintf(stderr, "failed to open ZFS device\n");
919 libzfs_fini(g_zfs);
920 return (1);
923 if (argc == 1) {
925 * No arguments. Print the available handlers. If there are no
926 * available handlers, direct the user to '-h' for help
927 * information.
929 if (print_all_handlers() == 0) {
930 (void) printf("No handlers registered.\n");
931 (void) printf("Run 'zinject -h' for usage "
932 "information.\n");
934 libzfs_fini(g_zfs);
935 return (0);
938 while ((c = getopt(argc, argv,
939 ":aA:b:C:d:D:f:Fg:qhIc:t:T:l:mr:s:e:uL:p:P:")) != -1) {
940 switch (c) {
941 case 'a':
942 flags |= ZINJECT_FLUSH_ARC;
943 break;
944 case 'A':
945 if (strcasecmp(optarg, "degrade") == 0) {
946 action = VDEV_STATE_DEGRADED;
947 } else if (strcasecmp(optarg, "fault") == 0) {
948 action = VDEV_STATE_FAULTED;
949 } else {
950 (void) fprintf(stderr, "invalid action '%s': "
951 "must be 'degrade' or 'fault'\n", optarg);
952 usage();
953 libzfs_fini(g_zfs);
954 return (1);
956 break;
957 case 'b':
958 raw = optarg;
959 break;
960 case 'c':
961 cancel = optarg;
962 break;
963 case 'C':
964 ret = parse_dvas(optarg, &dvas);
965 if (ret != 0) {
966 (void) fprintf(stderr, "invalid DVA list '%s': "
967 "DVAs should be 0 indexed and separated by "
968 "commas.\n", optarg);
969 usage();
970 libzfs_fini(g_zfs);
971 return (1);
973 break;
974 case 'd':
975 device = optarg;
976 break;
977 case 'D':
978 errno = 0;
979 ret = parse_delay(optarg, &record.zi_timer,
980 &record.zi_nlanes);
981 if (ret != 0) {
983 (void) fprintf(stderr, "invalid i/o delay "
984 "value: '%s'\n", optarg);
985 usage();
986 libzfs_fini(g_zfs);
987 return (1);
989 break;
990 case 'e':
991 error = str_to_err(optarg);
992 if (error < 0) {
993 (void) fprintf(stderr, "invalid error type "
994 "'%s': must be one of: io decompress "
995 "decrypt nxio dtl corrupt noop\n",
996 optarg);
997 usage();
998 libzfs_fini(g_zfs);
999 return (1);
1001 break;
1002 case 'f':
1003 ret = parse_frequency(optarg, &record.zi_freq);
1004 if (ret != 0) {
1005 (void) fprintf(stderr, "%sfrequency value must "
1006 "be in the range [0.0001, 100.0]\n",
1007 ret == EINVAL ? "invalid value: " :
1008 ret == ERANGE ? "out of range: " : "");
1009 libzfs_fini(g_zfs);
1010 return (1);
1012 break;
1013 case 'F':
1014 record.zi_failfast = B_TRUE;
1015 break;
1016 case 'g':
1017 dur_txg = 1;
1018 record.zi_duration = (int)strtol(optarg, &end, 10);
1019 if (record.zi_duration <= 0 || *end != '\0') {
1020 (void) fprintf(stderr, "invalid duration '%s': "
1021 "must be a positive integer\n", optarg);
1022 usage();
1023 libzfs_fini(g_zfs);
1024 return (1);
1026 /* store duration of txgs as its negative */
1027 record.zi_duration *= -1;
1028 break;
1029 case 'h':
1030 usage();
1031 libzfs_fini(g_zfs);
1032 return (0);
1033 case 'I':
1034 /* default duration, if one hasn't yet been defined */
1035 nowrites = 1;
1036 if (dur_secs == 0 && dur_txg == 0)
1037 record.zi_duration = 30;
1038 break;
1039 case 'l':
1040 level = (int)strtol(optarg, &end, 10);
1041 if (*end != '\0') {
1042 (void) fprintf(stderr, "invalid level '%s': "
1043 "must be an integer\n", optarg);
1044 usage();
1045 libzfs_fini(g_zfs);
1046 return (1);
1048 break;
1049 case 'm':
1050 domount = 1;
1051 break;
1052 case 'p':
1053 (void) strlcpy(record.zi_func, optarg,
1054 sizeof (record.zi_func));
1055 record.zi_cmd = ZINJECT_PANIC;
1056 break;
1057 case 'P':
1058 if (strcasecmp(optarg, "import") == 0) {
1059 record.zi_cmd = ZINJECT_DELAY_IMPORT;
1060 } else if (strcasecmp(optarg, "export") == 0) {
1061 record.zi_cmd = ZINJECT_DELAY_EXPORT;
1062 } else {
1063 (void) fprintf(stderr, "invalid command '%s': "
1064 "must be 'import' or 'export'\n", optarg);
1065 usage();
1066 libzfs_fini(g_zfs);
1067 return (1);
1069 break;
1070 case 'q':
1071 quiet = 1;
1072 break;
1073 case 'r':
1074 range = optarg;
1075 flags |= ZINJECT_CALC_RANGE;
1076 break;
1077 case 's':
1078 dur_secs = 1;
1079 record.zi_duration = (int)strtol(optarg, &end, 10);
1080 if (record.zi_duration <= 0 || *end != '\0') {
1081 (void) fprintf(stderr, "invalid duration '%s': "
1082 "must be a positive integer\n", optarg);
1083 usage();
1084 libzfs_fini(g_zfs);
1085 return (1);
1087 break;
1088 case 'T':
1089 io_type = str_to_iotype(optarg);
1090 if (io_type == ZINJECT_IOTYPES) {
1091 (void) fprintf(stderr, "invalid I/O type "
1092 "'%s': must be 'read', 'write', 'free', "
1093 "'claim', 'flush' or 'all'\n", optarg);
1094 usage();
1095 libzfs_fini(g_zfs);
1096 return (1);
1098 break;
1099 case 't':
1100 if ((type = name_to_type(optarg)) == TYPE_INVAL &&
1101 !MOS_TYPE(type)) {
1102 (void) fprintf(stderr, "invalid type '%s'\n",
1103 optarg);
1104 usage();
1105 libzfs_fini(g_zfs);
1106 return (1);
1108 break;
1109 case 'u':
1110 flags |= ZINJECT_UNLOAD_SPA;
1111 break;
1112 case 'L':
1113 if ((label = name_to_type(optarg)) == TYPE_INVAL &&
1114 !LABEL_TYPE(type)) {
1115 (void) fprintf(stderr, "invalid label type "
1116 "'%s'\n", optarg);
1117 usage();
1118 libzfs_fini(g_zfs);
1119 return (1);
1121 break;
1122 case ':':
1123 (void) fprintf(stderr, "option -%c requires an "
1124 "operand\n", optopt);
1125 usage();
1126 libzfs_fini(g_zfs);
1127 return (1);
1128 case '?':
1129 (void) fprintf(stderr, "invalid option '%c'\n",
1130 optopt);
1131 usage();
1132 libzfs_fini(g_zfs);
1133 return (2);
1137 argc -= optind;
1138 argv += optind;
1140 if (record.zi_duration != 0 && record.zi_cmd == 0)
1141 record.zi_cmd = ZINJECT_IGNORED_WRITES;
1143 if (cancel != NULL) {
1145 * '-c' is invalid with any other options.
1147 if (raw != NULL || range != NULL || type != TYPE_INVAL ||
1148 level != 0 || record.zi_cmd != ZINJECT_UNINITIALIZED ||
1149 record.zi_freq > 0 || dvas != 0) {
1150 (void) fprintf(stderr, "cancel (-c) incompatible with "
1151 "any other options\n");
1152 usage();
1153 libzfs_fini(g_zfs);
1154 return (2);
1156 if (argc != 0) {
1157 (void) fprintf(stderr, "extraneous argument to '-c'\n");
1158 usage();
1159 libzfs_fini(g_zfs);
1160 return (2);
1163 if (strcmp(cancel, "all") == 0) {
1164 return (cancel_all_handlers());
1165 } else {
1166 int id = (int)strtol(cancel, &end, 10);
1167 if (*end != '\0') {
1168 (void) fprintf(stderr, "invalid handle id '%s':"
1169 " must be an integer or 'all'\n", cancel);
1170 usage();
1171 libzfs_fini(g_zfs);
1172 return (1);
1174 return (cancel_handler(id));
1178 if (device != NULL) {
1180 * Device (-d) injection uses a completely different mechanism
1181 * for doing injection, so handle it separately here.
1183 if (raw != NULL || range != NULL || type != TYPE_INVAL ||
1184 level != 0 || record.zi_cmd != ZINJECT_UNINITIALIZED ||
1185 dvas != 0) {
1186 (void) fprintf(stderr, "device (-d) incompatible with "
1187 "data error injection\n");
1188 usage();
1189 libzfs_fini(g_zfs);
1190 return (2);
1193 if (argc != 1) {
1194 (void) fprintf(stderr, "device (-d) injection requires "
1195 "a single pool name\n");
1196 usage();
1197 libzfs_fini(g_zfs);
1198 return (2);
1201 (void) strlcpy(pool, argv[0], sizeof (pool));
1202 dataset[0] = '\0';
1204 if (error == ECKSUM) {
1205 (void) fprintf(stderr, "device error type must be "
1206 "'io', 'nxio' or 'corrupt'\n");
1207 libzfs_fini(g_zfs);
1208 return (1);
1211 if (error == EILSEQ &&
1212 (record.zi_freq == 0 || io_type != ZINJECT_IOTYPE_READ)) {
1213 (void) fprintf(stderr, "device corrupt errors require "
1214 "io type read and a frequency value\n");
1215 libzfs_fini(g_zfs);
1216 return (1);
1219 record.zi_iotype = io_type;
1220 if (translate_device(pool, device, label, &record) != 0) {
1221 libzfs_fini(g_zfs);
1222 return (1);
1225 if (record.zi_nlanes) {
1226 switch (io_type) {
1227 case ZINJECT_IOTYPE_READ:
1228 case ZINJECT_IOTYPE_WRITE:
1229 case ZINJECT_IOTYPE_ALL:
1230 break;
1231 default:
1232 (void) fprintf(stderr, "I/O type for a delay "
1233 "must be 'read' or 'write'\n");
1234 usage();
1235 libzfs_fini(g_zfs);
1236 return (1);
1240 if (!error)
1241 error = ENXIO;
1243 if (action != VDEV_STATE_UNKNOWN)
1244 return (perform_action(pool, &record, action));
1246 } else if (raw != NULL) {
1247 if (range != NULL || type != TYPE_INVAL || level != 0 ||
1248 record.zi_cmd != ZINJECT_UNINITIALIZED ||
1249 record.zi_freq > 0 || dvas != 0) {
1250 (void) fprintf(stderr, "raw (-b) format with "
1251 "any other options\n");
1252 usage();
1253 libzfs_fini(g_zfs);
1254 return (2);
1257 if (argc != 1) {
1258 (void) fprintf(stderr, "raw (-b) format expects a "
1259 "single pool name\n");
1260 usage();
1261 libzfs_fini(g_zfs);
1262 return (2);
1265 (void) strlcpy(pool, argv[0], sizeof (pool));
1266 dataset[0] = '\0';
1268 if (error == ENXIO) {
1269 (void) fprintf(stderr, "data error type must be "
1270 "'checksum' or 'io'\n");
1271 libzfs_fini(g_zfs);
1272 return (1);
1275 record.zi_cmd = ZINJECT_DATA_FAULT;
1276 if (translate_raw(raw, &record) != 0) {
1277 libzfs_fini(g_zfs);
1278 return (1);
1280 if (!error)
1281 error = EIO;
1282 } else if (record.zi_cmd == ZINJECT_PANIC) {
1283 if (raw != NULL || range != NULL || type != TYPE_INVAL ||
1284 level != 0 || device != NULL || record.zi_freq > 0 ||
1285 dvas != 0) {
1286 (void) fprintf(stderr, "%s incompatible with other "
1287 "options\n", "import|export delay (-P)");
1288 usage();
1289 libzfs_fini(g_zfs);
1290 return (2);
1293 if (argc < 1 || argc > 2) {
1294 (void) fprintf(stderr, "panic (-p) injection requires "
1295 "a single pool name and an optional id\n");
1296 usage();
1297 libzfs_fini(g_zfs);
1298 return (2);
1301 (void) strlcpy(pool, argv[0], sizeof (pool));
1302 if (argv[1] != NULL)
1303 record.zi_type = atoi(argv[1]);
1304 dataset[0] = '\0';
1305 } else if (record.zi_cmd == ZINJECT_DELAY_IMPORT ||
1306 record.zi_cmd == ZINJECT_DELAY_EXPORT) {
1307 if (raw != NULL || range != NULL || type != TYPE_INVAL ||
1308 level != 0 || device != NULL || record.zi_freq > 0 ||
1309 dvas != 0) {
1310 (void) fprintf(stderr, "%s incompatible with other "
1311 "options\n", "import|export delay (-P)");
1312 usage();
1313 libzfs_fini(g_zfs);
1314 return (2);
1317 if (argc != 1 || record.zi_duration <= 0) {
1318 (void) fprintf(stderr, "import|export delay (-P) "
1319 "injection requires a duration (-s) and a single "
1320 "pool name\n");
1321 usage();
1322 libzfs_fini(g_zfs);
1323 return (2);
1326 (void) strlcpy(pool, argv[0], sizeof (pool));
1327 } else if (record.zi_cmd == ZINJECT_IGNORED_WRITES) {
1328 if (raw != NULL || range != NULL || type != TYPE_INVAL ||
1329 level != 0 || record.zi_freq > 0 || dvas != 0) {
1330 (void) fprintf(stderr, "hardware failure (-I) "
1331 "incompatible with other options\n");
1332 usage();
1333 libzfs_fini(g_zfs);
1334 return (2);
1337 if (nowrites == 0) {
1338 (void) fprintf(stderr, "-s or -g meaningless "
1339 "without -I (ignore writes)\n");
1340 usage();
1341 libzfs_fini(g_zfs);
1342 return (2);
1343 } else if (dur_secs && dur_txg) {
1344 (void) fprintf(stderr, "choose a duration either "
1345 "in seconds (-s) or a number of txgs (-g) "
1346 "but not both\n");
1347 usage();
1348 libzfs_fini(g_zfs);
1349 return (2);
1350 } else if (argc != 1) {
1351 (void) fprintf(stderr, "ignore writes (-I) "
1352 "injection requires a single pool name\n");
1353 usage();
1354 libzfs_fini(g_zfs);
1355 return (2);
1358 (void) strlcpy(pool, argv[0], sizeof (pool));
1359 dataset[0] = '\0';
1360 } else if (type == TYPE_INVAL) {
1361 if (flags == 0) {
1362 (void) fprintf(stderr, "at least one of '-b', '-d', "
1363 "'-t', '-a', '-p', '-I' or '-u' "
1364 "must be specified\n");
1365 usage();
1366 libzfs_fini(g_zfs);
1367 return (2);
1370 if (argc == 1 && (flags & ZINJECT_UNLOAD_SPA)) {
1371 (void) strlcpy(pool, argv[0], sizeof (pool));
1372 dataset[0] = '\0';
1373 } else if (argc != 0) {
1374 (void) fprintf(stderr, "extraneous argument for "
1375 "'-f'\n");
1376 usage();
1377 libzfs_fini(g_zfs);
1378 return (2);
1381 flags |= ZINJECT_NULL;
1382 } else {
1383 if (argc != 1) {
1384 (void) fprintf(stderr, "missing object\n");
1385 usage();
1386 libzfs_fini(g_zfs);
1387 return (2);
1390 if (error == ENXIO || error == EILSEQ) {
1391 (void) fprintf(stderr, "data error type must be "
1392 "'checksum' or 'io'\n");
1393 libzfs_fini(g_zfs);
1394 return (1);
1397 if (dvas != 0) {
1398 if (error == EACCES || error == EINVAL) {
1399 (void) fprintf(stderr, "the '-C' option may "
1400 "not be used with logical data errors "
1401 "'decrypt' and 'decompress'\n");
1402 libzfs_fini(g_zfs);
1403 return (1);
1406 record.zi_dvas = dvas;
1409 if (error == EACCES) {
1410 if (type != TYPE_DATA) {
1411 (void) fprintf(stderr, "decryption errors "
1412 "may only be injected for 'data' types\n");
1413 libzfs_fini(g_zfs);
1414 return (1);
1417 record.zi_cmd = ZINJECT_DECRYPT_FAULT;
1419 * Internally, ZFS actually uses ECKSUM for decryption
1420 * errors since EACCES is used to indicate the key was
1421 * not found.
1423 error = ECKSUM;
1424 } else {
1425 record.zi_cmd = ZINJECT_DATA_FAULT;
1428 if (translate_record(type, argv[0], range, level, &record, pool,
1429 dataset) != 0) {
1430 libzfs_fini(g_zfs);
1431 return (1);
1433 if (!error)
1434 error = EIO;
1438 * If this is pool-wide metadata, unmount everything. The ioctl() will
1439 * unload the pool, so that we trigger spa-wide reopen of metadata next
1440 * time we access the pool.
1442 if (dataset[0] != '\0' && domount) {
1443 if ((zhp = zfs_open(g_zfs, dataset,
1444 ZFS_TYPE_DATASET)) == NULL) {
1445 libzfs_fini(g_zfs);
1446 return (1);
1448 if (zfs_unmount(zhp, NULL, 0) != 0) {
1449 libzfs_fini(g_zfs);
1450 return (1);
1454 record.zi_error = error;
1456 ret = register_handler(pool, flags, &record, quiet);
1458 if (dataset[0] != '\0' && domount)
1459 ret = (zfs_mount(zhp, NULL, 0) != 0);
1461 libzfs_fini(g_zfs);
1463 return (ret);