Documentation/fault-injection/fault-injection.rst GitHub 원문 ↗

Linux 6.18.37 · Fault Injection

Fault injection capabilities infrastructure

Kernel fault injection capability, debugfs 조건, error-injectable 함수 계약과 실전 시험 예제를 설명하는 한국어 전문 번역입니다.

Source pathDocumentation/fault-injection/fault-injection.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

fault-injection.rst:1-611

Linux fault injection infrastructure는 allocation, usercopy, futex, RPC, block·MMC·NVMe I/O, 특정 함수 반환, SKB 재할당을 의도적으로 실패시킵니다. Probability·interval·times·space, task와 stack range filter를 조합해 재현 가능한 범위를 만들 수 있습니다.

Function-level injection은 `ALLOW_ERROR_INJECTION()`으로 명시된, 실패 반환 contract와 state-neutral 조건을 만족하는 함수에만 사용해야 합니다. `fail-nth`는 한 task의 system call 안에 있는 fault point를 순서대로 전수 시험합니다.

Fault injection 시험 설계
Select a capability and target scopeConfigure deterministic probability, interval or fail-nthRun one focused operationValidate error handling and resource cleanupDisable injection and restore controls

대상 선택부터 복구 검증과 설정 정리까지의 안전한 흐름입니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ===========================================
2 Fault injection capabilities infrastructure
3 ===========================================
4
5 See also "every_nth" module option for scsi_debug.
6
7
8 Available fault injection capabilities
9 --------------------------------------
10
11 - failslab
12
13 injects slab allocation failures. (kmalloc(), kmem_cache_alloc(), ...)
14
15 - fail_page_alloc
16
17 injects page allocation failures. (alloc_pages(), get_free_pages(), ...)
18
19 - fail_usercopy
20
21 injects failures in user memory access functions. (copy_from_user(), get_user(), ...)
22
23 - fail_futex
24
25 injects futex deadlock and uaddr fault errors.
26
27 - fail_sunrpc
28
29 injects kernel RPC client and server failures.
30
31 - fail_make_request
32
33 injects disk IO errors on devices permitted by setting
34 /sys/block/<device>/make-it-fail or
35 /sys/block/<device>/<partition>/make-it-fail. (submit_bio_noacct())
36
37 - fail_mmc_request
38
39 injects MMC data errors on devices permitted by setting
40 debugfs entries under /sys/kernel/debug/mmc0/fail_mmc_request
41
42 - fail_function
43
44 injects error return on specific functions, which are marked by
45 ALLOW_ERROR_INJECTION() macro, by setting debugfs entries
46 under /sys/kernel/debug/fail_function. No boot option supported.
47
48 - fail_skb_realloc
49
50 inject skb (socket buffer) reallocation events into the network path. The
51 primary goal is to identify and prevent issues related to pointer
52 mismanagement in the network subsystem. By forcing skb reallocation at
53 strategic points, this feature creates scenarios where existing pointers to
54 skb headers become invalid.
55
56 When the fault is injected and the reallocation is triggered, cached pointers
57 to skb headers and data no longer reference valid memory locations. This
58 deliberate invalidation helps expose code paths where proper pointer updating
59 is neglected after a reallocation event.
60
61 By creating these controlled fault scenarios, the system can catch instances
62 where stale pointers are used, potentially leading to memory corruption or
63 system instability.
64
65 To select the interface to act on, write the network name to
66 /sys/kernel/debug/fail_skb_realloc/devname.
67 If this field is left empty (which is the default value), skb reallocation
68 will be forced on all network interfaces.
69
70 The effectiveness of this fault detection is enhanced when KASAN is
71 enabled, as it helps identify invalid memory references and use-after-free
72 (UAF) issues.
73
74 - NVMe fault injection
75
76 inject NVMe status code and retry flag on devices permitted by setting
77 debugfs entries under /sys/kernel/debug/nvme*/fault_inject. The default
78 status code is NVME_SC_INVALID_OPCODE with no retry. The status code and
79 retry flag can be set via the debugfs.
80
81 - Null test block driver fault injection
82
83 inject IO timeouts by setting config items under
84 /sys/kernel/config/nullb/<disk>/timeout_inject,
85 inject requeue requests by setting config items under
86 /sys/kernel/config/nullb/<disk>/requeue_inject, and
87 inject init_hctx() errors by setting config items under
88 /sys/kernel/config/nullb/<disk>/init_hctx_fault_inject.
89
90 Configure fault-injection capabilities behavior
91 -----------------------------------------------
92
93 debugfs entries
94 ^^^^^^^^^^^^^^^
95
96 fault-inject-debugfs kernel module provides some debugfs entries for runtime
97 configuration of fault-injection capabilities.
98
99 - /sys/kernel/debug/fail*/probability:
100
101 likelihood of failure injection, in percent.
102
103 Format: <percent>
104
105 Note that one-failure-per-hundred is a very high error rate
106 for some testcases. Consider setting probability=100 and configure
107 /sys/kernel/debug/fail*/interval for such testcases.
108
109 - /sys/kernel/debug/fail*/interval:
110
111 specifies the interval between failures, for calls to
112 should_fail() that pass all the other tests.
113
114 Note that if you enable this, by setting interval>1, you will
115 probably want to set probability=100.
116
117 - /sys/kernel/debug/fail*/times:
118
119 specifies how many times failures may happen at most. A value of -1
120 means "no limit".
121
122 - /sys/kernel/debug/fail*/space:
123
124 specifies an initial resource "budget", decremented by "size"
125 on each call to should_fail(,size). Failure injection is
126 suppressed until "space" reaches zero.
127
128 - /sys/kernel/debug/fail*/verbose
129
130 Format: { 0 | 1 | 2 }
131
132 specifies the verbosity of the messages when failure is
133 injected. '0' means no messages; '1' will print only a single
134 log line per failure; '2' will print a call trace too -- useful
135 to debug the problems revealed by fault injection.
136
137 - /sys/kernel/debug/fail*/task-filter:
138
139 Format: { 'Y' | 'N' }
140
141 A value of 'N' disables filtering by process (default).
142 Any positive value limits failures to only processes indicated by
143 /proc/<pid>/make-it-fail==1.
144
145 - /sys/kernel/debug/fail*/require-start,
146 /sys/kernel/debug/fail*/require-end,
147 /sys/kernel/debug/fail*/reject-start,
148 /sys/kernel/debug/fail*/reject-end:
149
150 specifies the range of virtual addresses tested during
151 stacktrace walking. Failure is injected only if some caller
152 in the walked stacktrace lies within the required range, and
153 none lies within the rejected range.
154 Default required range is [0,ULONG_MAX) (whole of virtual address space).
155 Default rejected range is [0,0).
156
157 - /sys/kernel/debug/fail*/stacktrace-depth:
158
159 specifies the maximum stacktrace depth walked during search
160 for a caller within [require-start,require-end) OR
161 [reject-start,reject-end).
162
163 - /sys/kernel/debug/fail_page_alloc/ignore-gfp-highmem:
164
165 Format: { 'Y' | 'N' }
166
167 default is 'Y', setting it to 'N' will also inject failures into
168 highmem/user allocations (__GFP_HIGHMEM allocations).
169
170 - /sys/kernel/debug/failslab/cache-filter
171 Format: { 'Y' | 'N' }
172
173 default is 'N', setting it to 'Y' will only inject failures when
174 objects are requests from certain caches.
175
176 Select the cache by writing '1' to /sys/kernel/slab/<cache>/failslab:
177
178 - /sys/kernel/debug/failslab/ignore-gfp-wait:
179 - /sys/kernel/debug/fail_page_alloc/ignore-gfp-wait:
180
181 Format: { 'Y' | 'N' }
182
183 default is 'Y', setting it to 'N' will also inject failures
184 into allocations that can sleep (__GFP_DIRECT_RECLAIM allocations).
185
186 - /sys/kernel/debug/fail_page_alloc/min-order:
187
188 specifies the minimum page allocation order to be injected
189 failures.
190
191 - /sys/kernel/debug/fail_futex/ignore-private:
192
193 Format: { 'Y' | 'N' }
194
195 default is 'N', setting it to 'Y' will disable failure injections
196 when dealing with private (address space) futexes.
197
198 - /sys/kernel/debug/fail_sunrpc/ignore-client-disconnect:
199
200 Format: { 'Y' | 'N' }
201
202 default is 'N', setting it to 'Y' will disable disconnect
203 injection on the RPC client.
204
205 - /sys/kernel/debug/fail_sunrpc/ignore-server-disconnect:
206
207 Format: { 'Y' | 'N' }
208
209 default is 'N', setting it to 'Y' will disable disconnect
210 injection on the RPC server.
211
212 - /sys/kernel/debug/fail_sunrpc/ignore-cache-wait:
213
214 Format: { 'Y' | 'N' }
215
216 default is 'N', setting it to 'Y' will disable cache wait
217 injection on the RPC server.
218
219 - /sys/kernel/debug/fail_function/inject:
220
221 Format: { 'function-name' | '!function-name' | '' }
222
223 specifies the target function of error injection by name.
224 If the function name leads '!' prefix, given function is
225 removed from injection list. If nothing specified ('')
226 injection list is cleared.
227
228 - /sys/kernel/debug/fail_function/injectable:
229
230 (read only) shows error injectable functions and what type of
231 error values can be specified. The error type will be one of
232 below;
233 - NULL: retval must be 0.
234 - ERRNO: retval must be -1 to -MAX_ERRNO (-4096).
235 - ERR_NULL: retval must be 0 or -1 to -MAX_ERRNO (-4096).
236
237 - /sys/kernel/debug/fail_function/<function-name>/retval:
238
239 specifies the "error" return value to inject to the given function.
240 This will be created when the user specifies a new injection entry.
241 Note that this file only accepts unsigned values. So, if you want to
242 use a negative errno, you better use 'printf' instead of 'echo', e.g.:
243 $ printf %#x -12 > retval
244
245 - /sys/kernel/debug/fail_skb_realloc/devname:
246
247 Specifies the network interface on which to force SKB reallocation. If
248 left empty, SKB reallocation will be applied to all network interfaces.
249
250 Example usage::
251
252 # Force skb reallocation on eth0
253 echo "eth0" > /sys/kernel/debug/fail_skb_realloc/devname
254
255 # Clear the selection and force skb reallocation on all interfaces
256 echo "" > /sys/kernel/debug/fail_skb_realloc/devname
257
258 Boot option
259 ^^^^^^^^^^^
260
261 In order to inject faults while debugfs is not available (early boot time),
262 use the boot option::
263
264 failslab=
265 fail_page_alloc=
266 fail_usercopy=
267 fail_make_request=
268 fail_futex=
269 fail_skb_realloc=
270 mmc_core.fail_request=<interval>,<probability>,<space>,<times>
271
272 proc entries
273 ^^^^^^^^^^^^
274
275 - /proc/<pid>/fail-nth,
276 /proc/self/task/<tid>/fail-nth:
277
278 Write to this file of integer N makes N-th call in the task fail.
279 Read from this file returns a integer value. A value of '0' indicates
280 that the fault setup with a previous write to this file was injected.
281 A positive integer N indicates that the fault wasn't yet injected.
282 Note that this file enables all types of faults (slab, futex, etc).
283 This setting takes precedence over all other generic debugfs settings
284 like probability, interval, times, etc. But per-capability settings
285 (e.g. fail_futex/ignore-private) take precedence over it.
286
287 This feature is intended for systematic testing of faults in a single
288 system call. See an example below.
289
290
291 Error Injectable Functions
292 --------------------------
293
294 This part is for the kernel developers considering to add a function to
295 ALLOW_ERROR_INJECTION() macro.
296
297 Requirements for the Error Injectable Functions
298 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
299
300 Since the function-level error injection forcibly changes the code path
301 and returns an error even if the input and conditions are proper, this can
302 cause unexpected kernel crash if you allow error injection on the function
303 which is NOT error injectable. Thus, you (and reviewers) must ensure;
304
305 - The function returns an error code if it fails, and the callers must check
306 it correctly (need to recover from it).
307
308 - The function does not execute any code which can change any state before
309 the first error return. The state includes global or local, or input
310 variable. For example, clear output address storage (e.g. `*ret = NULL`),
311 increments/decrements counter, set a flag, preempt/irq disable or get
312 a lock (if those are recovered before returning error, that will be OK.)
313
314 The first requirement is important, and it will result in that the release
315 (free objects) functions are usually harder to inject errors than allocate
316 functions. If errors of such release functions are not correctly handled
317 it will cause a memory leak easily (the caller will confuse that the object
318 has been released or corrupted.)
319
320 The second one is for the caller which expects the function should always
321 does something. Thus if the function error injection skips whole of the
322 function, the expectation is betrayed and causes an unexpected error.
323
324 Type of the Error Injectable Functions
325 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
326
327 Each error injectable functions will have the error type specified by the
328 ALLOW_ERROR_INJECTION() macro. You have to choose it carefully if you add
329 a new error injectable function. If the wrong error type is chosen, the
330 kernel may crash because it may not be able to handle the error.
331 There are 4 types of errors defined in include/asm-generic/error-injection.h
332
333 EI_ETYPE_NULL
334 This function will return `NULL` if it fails. e.g. return an allocated
335 object address.
336
337 EI_ETYPE_ERRNO
338 This function will return an `-errno` error code if it fails. e.g. return
339 -EINVAL if the input is wrong. This will include the functions which will
340 return an address which encodes `-errno` by ERR_PTR() macro.
341
342 EI_ETYPE_ERRNO_NULL
343 This function will return an `-errno` or `NULL` if it fails. If the caller
344 of this function checks the return value with IS_ERR_OR_NULL() macro, this
345 type will be appropriate.
346
347 EI_ETYPE_TRUE
348 This function will return `true` (non-zero positive value) if it fails.
349
350 If you specifies a wrong type, for example, EI_TYPE_ERRNO for the function
351 which returns an allocated object, it may cause a problem because the returned
352 value is not an object address and the caller can not access to the address.
353
354
355 How to add new fault injection capability
356 -----------------------------------------
357
358 - #include <linux/fault-inject.h>
359
360 - define the fault attributes
361
362 DECLARE_FAULT_ATTR(name);
363
364 Please see the definition of struct fault_attr in fault-inject.h
365 for details.
366
367 - provide a way to configure fault attributes
368
369 - boot option
370
371 If you need to enable the fault injection capability from boot time, you can
372 provide boot option to configure it. There is a helper function for it:
373
374 setup_fault_attr(attr, str);
375
376 - debugfs entries
377
378 failslab, fail_page_alloc, fail_usercopy, and fail_make_request use this way.
379 Helper functions:
380
381 fault_create_debugfs_attr(name, parent, attr);
382
383 - module parameters
384
385 If the scope of the fault injection capability is limited to a
386 single kernel module, it is better to provide module parameters to
387 configure the fault attributes.
388
389 - add a hook to insert failures
390
391 Upon should_fail() returning true, client code should inject a failure:
392
393 should_fail(attr, size);
394
395 Application Examples
396 --------------------
397
398 - Inject slab allocation failures into module init/exit code::
399
400 #!/bin/bash
401
402 FAILTYPE=failslab
403 echo Y > /sys/kernel/debug/$FAILTYPE/task-filter
404 echo 10 > /sys/kernel/debug/$FAILTYPE/probability
405 echo 100 > /sys/kernel/debug/$FAILTYPE/interval
406 echo -1 > /sys/kernel/debug/$FAILTYPE/times
407 echo 0 > /sys/kernel/debug/$FAILTYPE/space
408 echo 2 > /sys/kernel/debug/$FAILTYPE/verbose
409 echo Y > /sys/kernel/debug/$FAILTYPE/ignore-gfp-wait
410
411 faulty_system()
412 {
413 bash -c "echo 1 > /proc/self/make-it-fail && exec $*"
414 }
415
416 if [ $# -eq 0 ]
417 then
418 echo "Usage: $0 modulename [ modulename ... ]"
419 exit 1
420 fi
421
422 for m in $*
423 do
424 echo inserting $m...
425 faulty_system modprobe $m
426
427 echo removing $m...
428 faulty_system modprobe -r $m
429 done
430
431 ------------------------------------------------------------------------------
432
433 - Inject page allocation failures only for a specific module::
434
435 #!/bin/bash
436
437 FAILTYPE=fail_page_alloc
438 module=$1
439
440 if [ -z $module ]
441 then
442 echo "Usage: $0 <modulename>"
443 exit 1
444 fi
445
446 modprobe $module
447
448 if [ ! -d /sys/module/$module/sections ]
449 then
450 echo Module $module is not loaded
451 exit 1
452 fi
453
454 cat /sys/module/$module/sections/.text > /sys/kernel/debug/$FAILTYPE/require-start
455 cat /sys/module/$module/sections/.data > /sys/kernel/debug/$FAILTYPE/require-end
456
457 echo N > /sys/kernel/debug/$FAILTYPE/task-filter
458 echo 10 > /sys/kernel/debug/$FAILTYPE/probability
459 echo 100 > /sys/kernel/debug/$FAILTYPE/interval
460 echo -1 > /sys/kernel/debug/$FAILTYPE/times
461 echo 0 > /sys/kernel/debug/$FAILTYPE/space
462 echo 2 > /sys/kernel/debug/$FAILTYPE/verbose
463 echo Y > /sys/kernel/debug/$FAILTYPE/ignore-gfp-wait
464 echo Y > /sys/kernel/debug/$FAILTYPE/ignore-gfp-highmem
465 echo 10 > /sys/kernel/debug/$FAILTYPE/stacktrace-depth
466
467 trap "echo 0 > /sys/kernel/debug/$FAILTYPE/probability" SIGINT SIGTERM EXIT
468
469 echo "Injecting errors into the module $module... (interrupt to stop)"
470 sleep 1000000
471
472 ------------------------------------------------------------------------------
473
474 - Inject open_ctree error while btrfs mount::
475
476 #!/bin/bash
477
478 rm -f testfile.img
479 dd if=/dev/zero of=testfile.img bs=1M seek=1000 count=1
480 DEVICE=$(losetup --show -f testfile.img)
481 mkfs.btrfs -f $DEVICE
482 mkdir -p tmpmnt
483
484 FAILTYPE=fail_function
485 FAILFUNC=open_ctree
486 echo $FAILFUNC > /sys/kernel/debug/$FAILTYPE/inject
487 printf %#x -12 > /sys/kernel/debug/$FAILTYPE/$FAILFUNC/retval
488 echo N > /sys/kernel/debug/$FAILTYPE/task-filter
489 echo 100 > /sys/kernel/debug/$FAILTYPE/probability
490 echo 0 > /sys/kernel/debug/$FAILTYPE/interval
491 echo -1 > /sys/kernel/debug/$FAILTYPE/times
492 echo 0 > /sys/kernel/debug/$FAILTYPE/space
493 echo 1 > /sys/kernel/debug/$FAILTYPE/verbose
494
495 mount -t btrfs $DEVICE tmpmnt
496 if [ $? -ne 0 ]
497 then
498 echo "SUCCESS!"
499 else
500 echo "FAILED!"
501 umount tmpmnt
502 fi
503
504 echo > /sys/kernel/debug/$FAILTYPE/inject
505
506 rmdir tmpmnt
507 losetup -d $DEVICE
508 rm testfile.img
509
510 ------------------------------------------------------------------------------
511
512 - Inject only skbuff allocation failures ::
513
514 # mark skbuff_head_cache as faulty
515 echo 1 > /sys/kernel/slab/skbuff_head_cache/failslab
516 # Turn on cache filter (off by default)
517 echo 1 > /sys/kernel/debug/failslab/cache-filter
518 # Turn on fault injection
519 echo 1 > /sys/kernel/debug/failslab/times
520 echo 1 > /sys/kernel/debug/failslab/probability
521
522
523 Tool to run command with failslab or fail_page_alloc
524 ----------------------------------------------------
525 In order to make it easier to accomplish the tasks mentioned above, we can use
526 tools/testing/fault-injection/failcmd.sh. Please run a command
527 "./tools/testing/fault-injection/failcmd.sh --help" for more information and
528 see the following examples.
529
530 Examples:
531
532 Run a command "make -C tools/testing/selftests/ run_tests" with injecting slab
533 allocation failure::
534
535 # ./tools/testing/fault-injection/failcmd.sh \
536 -- make -C tools/testing/selftests/ run_tests
537
538 Same as above except to specify 100 times failures at most instead of one time
539 at most by default::
540
541 # ./tools/testing/fault-injection/failcmd.sh --times=100 \
542 -- make -C tools/testing/selftests/ run_tests
543
544 Same as above except to inject page allocation failure instead of slab
545 allocation failure::
546
547 # env FAILCMD_TYPE=fail_page_alloc \
548 ./tools/testing/fault-injection/failcmd.sh --times=100 \
549 -- make -C tools/testing/selftests/ run_tests
550
551 Systematic faults using fail-nth
552 ---------------------------------
553
554 The following code systematically faults 0-th, 1-st, 2-nd and so on
555 capabilities in the socketpair() system call::
556
557 #include <sys/types.h>
558 #include <sys/stat.h>
559 #include <sys/socket.h>
560 #include <sys/syscall.h>
561 #include <fcntl.h>
562 #include <unistd.h>
563 #include <string.h>
564 #include <stdlib.h>
565 #include <stdio.h>
566 #include <errno.h>
567
568 int main()
569 {
570 int i, err, res, fail_nth, fds[2];
571 char buf[128];
572
573 system("echo N > /sys/kernel/debug/failslab/ignore-gfp-wait");
574 sprintf(buf, "/proc/self/task/%ld/fail-nth", syscall(SYS_gettid));
575 fail_nth = open(buf, O_RDWR);
576 for (i = 1;; i++) {
577 sprintf(buf, "%d", i);
578 write(fail_nth, buf, strlen(buf));
579 res = socketpair(AF_LOCAL, SOCK_STREAM, 0, fds);
580 err = errno;
581 pread(fail_nth, buf, sizeof(buf), 0);
582 if (res == 0) {
583 close(fds[0]);
584 close(fds[1]);
585 }
586 printf("%d-th fault %c: res=%d/%d\n", i, atoi(buf) ? 'N' : 'Y',
587 res, err);
588 if (atoi(buf))
589 break;
590 }
591 return 0;
592 }
593
594 An example output::
595
596 1-th fault Y: res=-1/23
597 2-th fault Y: res=-1/23
598 3-th fault Y: res=-1/12
599 4-th fault Y: res=-1/12
600 5-th fault Y: res=-1/23
601 6-th fault Y: res=-1/23
602 7-th fault Y: res=-1/23
603 8-th fault Y: res=-1/12
604 9-th fault Y: res=-1/12
605 10-th fault Y: res=-1/12
606 11-th fault Y: res=-1/12
607 12-th fault Y: res=-1/12
608 13-th fault Y: res=-1/12
609 14-th fault Y: res=-1/12
610 15-th fault Y: res=-1/12
611 16-th fault N: res=0/12
612

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

사용 가능한 fault injection 기능

1-89

Kernel fault injection infrastructure는 정상 조건에서는 드물게 실행되는 오류 처리 경로를 의도적으로 활성화해 복구 코드의 정확성을 시험합니다. SCSI `scsi_debug`의 `every_nth` module option도 관련 도구입니다.

`failslab`은 `kmalloc()`·`kmem_cache_alloc()` 같은 slab allocation을, `fail_page_alloc`은 `alloc_pages()`·`get_free_pages()` 같은 page allocation을 실패시킵니다. `fail_usercopy`는 `copy_from_user()`·`get_user()` 같은 userspace memory access를 실패시킵니다.

`fail_futex`는 futex deadlock과 user-address fault를, `fail_sunrpc`는 kernel RPC client·server 오류를 주입합니다. `fail_make_request`는 허용된 block device 또는 partition의 `/sys/block/.../make-it-fail`을 통해 `submit_bio_noacct()` disk I/O 오류를 만듭니다. `fail_mmc_request`는 `/sys/kernel/debug/mmc0/fail_mmc_request` 아래에서 MMC data error를 설정합니다.

`fail_function`은 `ALLOW_ERROR_INJECTION()`으로 표시된 특정 함수가 오류 값을 반환하도록 합니다. `/sys/kernel/debug/fail_function`으로 구성하며 boot option은 지원하지 않습니다.

`fail_skb_realloc`은 network path의 전략적 지점에서 socket buffer를 재할당해 skb header·data를 가리키던 cached pointer를 무효화합니다. 재할당 뒤 pointer를 갱신하지 않는 code path를 드러내 memory corruption과 instability를 찾습니다. `/sys/kernel/debug/fail_skb_realloc/devname`에 interface 이름을 쓰며 빈 값이면 모든 interface에 적용합니다. KASAN과 함께 쓰면 invalid reference와 use-after-free 탐지가 강화됩니다.

NVMe fault injection은 `/sys/kernel/debug/nvme*/fault_inject`에서 status code와 retry flag를 주입합니다. 기본값은 retry가 없는 `NVME_SC_INVALID_OPCODE`입니다. Null block driver는 configfs의 `timeout_inject`, `requeue_inject`, `init_hctx_fault_inject`에서 timeout, requeue, `init_hctx()` 오류를 각각 주입합니다.

Fault injection capability
기능주입 대상대표 제어
`failslab`Slab allocation failure`/sys/kernel/debug/failslab`
`fail_page_alloc`Page allocation failure`/sys/kernel/debug/fail_page_alloc`
`fail_usercopy`User memory access failureGeneric fail controls
`fail_futex`Futex deadlock·uaddr fault`ignore-private`
`fail_sunrpc`RPC client·server failureRPC ignore filters
`fail_make_request`Block I/O error`make-it-fail`
`fail_mmc_request`MMC data errorMMC debugfs
`fail_function`Marked function error return`inject` and `retval`
`fail_skb_realloc`SKB pointer invalidation`devname`
NVMeStatus code and retry flagNVMe debugfs
Null blockTimeout·requeue·init_hctx failureConfigfs inject items

===========================================
Fault injection capabilities infrastructure
===========================================

See also "every_nth" module option for scsi_debug.


Available fault injection capabilities
--------------------------------------

- failslab

  injects slab allocation failures. (kmalloc(), kmem_cache_alloc(), ...)

- fail_page_alloc

  injects page allocation failures. (alloc_pages(), get_free_pages(), ...)

- fail_usercopy

  injects failures in user memory access functions. (copy_from_user(), get_user(), ...)

- fail_futex

  injects futex deadlock and uaddr fault errors.

- fail_sunrpc

  injects kernel RPC client and server failures.

- fail_make_request

  injects disk IO errors on devices permitted by setting
  /sys/block/<device>/make-it-fail or
  /sys/block/<device>/<partition>/make-it-fail. (submit_bio_noacct())

- fail_mmc_request

  injects MMC data errors on devices permitted by setting
  debugfs entries under /sys/kernel/debug/mmc0/fail_mmc_request

- fail_function

  injects error return on specific functions, which are marked by
  ALLOW_ERROR_INJECTION() macro, by setting debugfs entries
  under /sys/kernel/debug/fail_function. No boot option supported.

- fail_skb_realloc

  inject skb (socket buffer) reallocation events into the network path. The
  primary goal is to identify and prevent issues related to pointer
  mismanagement in the network subsystem.  By forcing skb reallocation at
  strategic points, this feature creates scenarios where existing pointers to
  skb headers become invalid.

  When the fault is injected and the reallocation is triggered, cached pointers
  to skb headers and data no longer reference valid memory locations. This
  deliberate invalidation helps expose code paths where proper pointer updating
  is neglected after a reallocation event.

  By creating these controlled fault scenarios, the system can catch instances
  where stale pointers are used, potentially leading to memory corruption or
  system instability.

  To select the interface to act on, write the network name to
  /sys/kernel/debug/fail_skb_realloc/devname.
  If this field is left empty (which is the default value), skb reallocation
  will be forced on all network interfaces.

  The effectiveness of this fault detection is enhanced when KASAN is
  enabled, as it helps identify invalid memory references and use-after-free
  (UAF) issues.

- NVMe fault injection

  inject NVMe status code and retry flag on devices permitted by setting
  debugfs entries under /sys/kernel/debug/nvme*/fault_inject. The default
  status code is NVME_SC_INVALID_OPCODE with no retry. The status code and
  retry flag can be set via the debugfs.

- Null test block driver fault injection

  inject IO timeouts by setting config items under
  /sys/kernel/config/nullb/<disk>/timeout_inject,
  inject requeue requests by setting config items under
  /sys/kernel/config/nullb/<disk>/requeue_inject, and
  inject init_hctx() errors by setting config items under
  /sys/kernel/config/nullb/<disk>/init_hctx_fault_inject.

공통 debugfs 발생 조건과 stack filter

90-161

`fault-inject-debugfs` kernel module은 runtime fault configuration을 위한 `/sys/kernel/debug/fail*/` 항목을 제공합니다.

`probability`는 주입 확률을 percent로 지정합니다. 일부 test에서 100회당 한 번도 매우 높은 error rate이므로 정확한 주기를 원하면 `probability=100`과 `interval`을 함께 사용합니다. `interval`은 다른 조건을 모두 통과한 `should_fail()` 호출 중 몇 번째마다 실패할지 지정하며 1보다 크면 일반적으로 probability를 100으로 둡니다.

`times`는 발생 가능한 최대 실패 횟수이며 `-1`은 제한 없음입니다. `space`는 초기 resource budget으로, `should_fail(attr, size)`마다 `size`만큼 감소하고 0이 될 때까지 주입을 억제합니다.

`verbose`는 0, 1, 2 중 하나입니다. 0은 메시지 없음, 1은 실패당 log line 하나, 2는 문제 분석용 call trace까지 출력합니다.

`task-filter`의 기본값 `N`은 process filtering을 끕니다. 양수 값은 `/proc/<pid>/make-it-fail == 1`로 표시한 process로 실패를 제한합니다.

`require-start`·`require-end`와 `reject-start`·`reject-end`는 stacktrace를 순회할 때 검사할 virtual-address half-open range를 지정합니다. Caller 하나가 required range 안에 있고 rejected range 안에는 caller가 하나도 없을 때만 실패를 주입합니다. 기본 required range는 `[0, ULONG_MAX)`, rejected range는 `[0, 0)`입니다. `stacktrace-depth`는 이 검색에서 순회할 최대 stack depth입니다.

공통 fail* 제어
항목의미
`probability`주입 확률 percent
`interval`다른 조건을 통과한 호출 사이의 실패 간격
`times`최대 실패 횟수, -1은 무제한
`space`0이 될 때까지 감소하는 resource budget
`verbose`0: 없음, 1: log, 2: call trace
`task-filter`표시한 process로 주입 제한
`require-*`Stack caller가 반드시 포함될 주소 범위
`reject-*`Stack caller가 없어야 할 주소 범위
`stacktrace-depth`주소 범위 검색의 최대 깊이

Configure fault-injection capabilities behavior
-----------------------------------------------

debugfs entries
^^^^^^^^^^^^^^^

fault-inject-debugfs kernel module provides some debugfs entries for runtime
configuration of fault-injection capabilities.

- /sys/kernel/debug/fail*/probability:

        likelihood of failure injection, in percent.

        Format: <percent>

        Note that one-failure-per-hundred is a very high error rate
        for some testcases.  Consider setting probability=100 and configure
        /sys/kernel/debug/fail*/interval for such testcases.

- /sys/kernel/debug/fail*/interval:

        specifies the interval between failures, for calls to
        should_fail() that pass all the other tests.

        Note that if you enable this, by setting interval>1, you will
        probably want to set probability=100.

- /sys/kernel/debug/fail*/times:

        specifies how many times failures may happen at most. A value of -1
        means "no limit".

- /sys/kernel/debug/fail*/space:

        specifies an initial resource "budget", decremented by "size"
        on each call to should_fail(,size).  Failure injection is
        suppressed until "space" reaches zero.

- /sys/kernel/debug/fail*/verbose

        Format: { 0 | 1 | 2 }

        specifies the verbosity of the messages when failure is
        injected.  '0' means no messages; '1' will print only a single
        log line per failure; '2' will print a call trace too -- useful
        to debug the problems revealed by fault injection.

- /sys/kernel/debug/fail*/task-filter:

        Format: { 'Y' | 'N' }

        A value of 'N' disables filtering by process (default).
        Any positive value limits failures to only processes indicated by
        /proc/<pid>/make-it-fail==1.

- /sys/kernel/debug/fail*/require-start,
  /sys/kernel/debug/fail*/require-end,
  /sys/kernel/debug/fail*/reject-start,
  /sys/kernel/debug/fail*/reject-end:

        specifies the range of virtual addresses tested during
        stacktrace walking.  Failure is injected only if some caller
        in the walked stacktrace lies within the required range, and
        none lies within the rejected range.
        Default required range is [0,ULONG_MAX) (whole of virtual address space).
        Default rejected range is [0,0).

- /sys/kernel/debug/fail*/stacktrace-depth:

        specifies the maximum stacktrace depth walked during search
        for a caller within [require-start,require-end) OR
        [reject-start,reject-end).

Allocation·futex·SUNRPC별 filter

162-217

`fail_page_alloc/ignore-gfp-highmem`의 기본값 `Y`는 `__GFP_HIGHMEM` highmem·user allocation을 제외합니다. `N`으로 바꾸면 해당 allocation에도 실패를 주입합니다.

`failslab/cache-filter`는 기본 `N`이며 `Y`로 바꾸면 선택한 cache의 object request에만 주입합니다. Cache는 `/sys/kernel/slab/<cache>/failslab`에 `1`을 써서 선택합니다.

`failslab/ignore-gfp-wait`와 `fail_page_alloc/ignore-gfp-wait`의 기본값 `Y`는 sleep 가능한 `__GFP_DIRECT_RECLAIM` allocation을 제외합니다. `N`으로 바꾸면 포함됩니다. `fail_page_alloc/min-order`는 실패를 주입할 최소 page allocation order입니다.

`fail_futex/ignore-private=Y`는 private address-space futex의 주입을 끕니다. 기본값은 `N`입니다.

SUNRPC filter 세 개의 기본값도 `N`입니다. `ignore-client-disconnect=Y`는 RPC client disconnect, `ignore-server-disconnect=Y`는 server disconnect, `ignore-cache-wait=Y`는 server cache-wait 주입을 각각 끕니다.

Capability별 filter
경로Y일 때의 동작
`fail_page_alloc/ignore-gfp-highmem`Highmem·user allocation 제외
`failslab/cache-filter`선택한 slab cache만 대상
`*/ignore-gfp-wait`Sleep 가능한 allocation 제외
`fail_futex/ignore-private`Private futex 제외
`fail_sunrpc/ignore-client-disconnect`Client disconnect 제외
`fail_sunrpc/ignore-server-disconnect`Server disconnect 제외
`fail_sunrpc/ignore-cache-wait`Server cache wait 제외


- /sys/kernel/debug/fail_page_alloc/ignore-gfp-highmem:

        Format: { 'Y' | 'N' }

        default is 'Y', setting it to 'N' will also inject failures into
        highmem/user allocations (__GFP_HIGHMEM allocations).

- /sys/kernel/debug/failslab/cache-filter
        Format: { 'Y' | 'N' }

        default is 'N', setting it to 'Y' will only inject failures when
        objects are requests from certain caches.

        Select the cache by writing '1' to /sys/kernel/slab/<cache>/failslab:

- /sys/kernel/debug/failslab/ignore-gfp-wait:
- /sys/kernel/debug/fail_page_alloc/ignore-gfp-wait:

        Format: { 'Y' | 'N' }

        default is 'Y', setting it to 'N' will also inject failures
        into allocations that can sleep (__GFP_DIRECT_RECLAIM allocations).

- /sys/kernel/debug/fail_page_alloc/min-order:

        specifies the minimum page allocation order to be injected
        failures.

- /sys/kernel/debug/fail_futex/ignore-private:

        Format: { 'Y' | 'N' }

        default is 'N', setting it to 'Y' will disable failure injections
        when dealing with private (address space) futexes.

- /sys/kernel/debug/fail_sunrpc/ignore-client-disconnect:

        Format: { 'Y' | 'N' }

        default is 'N', setting it to 'Y' will disable disconnect
        injection on the RPC client.

- /sys/kernel/debug/fail_sunrpc/ignore-server-disconnect:

        Format: { 'Y' | 'N' }

        default is 'N', setting it to 'Y' will disable disconnect
        injection on the RPC server.

- /sys/kernel/debug/fail_sunrpc/ignore-cache-wait:

        Format: { 'Y' | 'N' }

        default is 'N', setting it to 'Y' will disable cache wait
        injection on the RPC server.

함수 오류 반환과 SKB 재할당 대상

218-257

`fail_function/inject`에는 function name, `!function-name`, 빈 문자열을 씁니다. 이름은 주입 목록에 추가하고 `!` 접두사는 해당 함수를 제거하며 빈 값은 전체 목록을 지웁니다.

읽기 전용 `fail_function/injectable`은 주입 가능한 함수와 허용된 오류 값 종류를 보여줍니다. `NULL`은 retval 0, `ERRNO`는 -1부터 `-MAX_ERRNO`(-4096), `ERR_NULL`은 0 또는 해당 음수 errno 범위를 허용합니다.

`fail_function/<function-name>/retval`은 해당 함수에 주입할 오류 반환값입니다. 새 inject entry를 지정하면 생성됩니다. 파일은 unsigned value만 받으므로 `-12` 같은 errno를 쓰려면 `echo` 대신 `$ printf %#x -12 > retval`처럼 16진 표현을 사용합니다.

`fail_skb_realloc/devname`은 강제로 SKB를 재할당할 network interface를 지정합니다. `eth0`을 쓰면 해당 interface만, 빈 문자열을 쓰면 모든 interface가 대상입니다.

Function·SKB 제어 형식
제어입력효과
`inject``function-name`함수 추가
`inject``!function-name`함수 제거
`inject`빈 문자열목록 초기화
`retval`Unsigned 표현오류 반환값 지정
`devname`Interface 이름 또는 빈 값한 interface 또는 전체에 SKB 재할당


- /sys/kernel/debug/fail_function/inject:

        Format: { 'function-name' | '!function-name' | '' }

        specifies the target function of error injection by name.
        If the function name leads '!' prefix, given function is
        removed from injection list. If nothing specified ('')
        injection list is cleared.

- /sys/kernel/debug/fail_function/injectable:

        (read only) shows error injectable functions and what type of
        error values can be specified. The error type will be one of
        below;
        - NULL:        retval must be 0.
        - ERRNO: retval must be -1 to -MAX_ERRNO (-4096).
        - ERR_NULL: retval must be 0 or -1 to -MAX_ERRNO (-4096).

- /sys/kernel/debug/fail_function/<function-name>/retval:

        specifies the "error" return value to inject to the given function.
        This will be created when the user specifies a new injection entry.
        Note that this file only accepts unsigned values. So, if you want to
        use a negative errno, you better use 'printf' instead of 'echo', e.g.:
        $ printf %#x -12 > retval

- /sys/kernel/debug/fail_skb_realloc/devname:

        Specifies the network interface on which to force SKB reallocation.  If
        left empty, SKB reallocation will be applied to all network interfaces.

        Example usage::

          # Force skb reallocation on eth0
          echo "eth0" > /sys/kernel/debug/fail_skb_realloc/devname

          # Clear the selection and force skb reallocation on all interfaces
          echo "" > /sys/kernel/debug/fail_skb_realloc/devname

Early boot option과 task별 fail-nth

258-290

Debugfs를 사용할 수 없는 early boot에 fault를 주입하려면 `failslab=`, `fail_page_alloc=`, `fail_usercopy=`, `fail_make_request=`, `fail_futex=`, `fail_skb_realloc=` boot option을 사용합니다. MMC는 `mmc_core.fail_request=<interval>,<probability>,<space>,<times>` 형식을 사용합니다.

`/proc/<pid>/fail-nth` 또는 `/proc/self/task/<tid>/fail-nth`에 정수 N을 쓰면 해당 task의 N번째 fault-capable 호출을 실패시킵니다. 읽었을 때 0이면 주입이 이미 발생했고 양수 N이면 아직 발생하지 않은 남은 상태입니다.

`fail-nth`는 slab, futex 등을 포함한 모든 fault type을 활성화하고 probability·interval·times 같은 generic debugfs 설정보다 우선합니다. 다만 `fail_futex/ignore-private` 같은 capability별 설정은 `fail-nth`보다 우선합니다.

이 기능은 system call 하나 안의 fault point를 순서대로 체계적으로 시험하기 위한 것입니다.

Task별 N번째 fault
Choose process or thread IDWrite N to `fail-nth`Run one target system callRead back 0 if injection happenedIncrease N until no fault point remains

Generic 확률 설정을 대신해 한 task의 fault point를 순서대로 재현합니다.

Boot option
^^^^^^^^^^^

In order to inject faults while debugfs is not available (early boot time),
use the boot option::

        failslab=
        fail_page_alloc=
        fail_usercopy=
        fail_make_request=
        fail_futex=
        fail_skb_realloc=
        mmc_core.fail_request=<interval>,<probability>,<space>,<times>

proc entries
^^^^^^^^^^^^

- /proc/<pid>/fail-nth,
  /proc/self/task/<tid>/fail-nth:

        Write to this file of integer N makes N-th call in the task fail.
        Read from this file returns a integer value. A value of '0' indicates
        that the fault setup with a previous write to this file was injected.
        A positive integer N indicates that the fault wasn't yet injected.
        Note that this file enables all types of faults (slab, futex, etc).
        This setting takes precedence over all other generic debugfs settings
        like probability, interval, times, etc. But per-capability settings
        (e.g. fail_futex/ignore-private) take precedence over it.

        This feature is intended for systematic testing of faults in a single
        system call. See an example below.

Error-injectable 함수의 안전 요건

291-323

이 절은 `ALLOW_ERROR_INJECTION()` macro에 새 함수를 추가하려는 kernel developer와 reviewer를 위한 지침입니다.

Function-level injection은 입력과 조건이 정상이어도 code path를 강제로 바꾸고 오류를 반환합니다. 실제로 오류 주입이 안전하지 않은 함수를 허용하면 예기치 않은 kernel crash가 발생할 수 있습니다.

첫째, 함수는 실패 시 오류 코드를 반환해야 하며 모든 caller가 이를 올바르게 검사하고 복구해야 합니다. Release 함수는 caller가 object가 해제되었다고 오해해 leak이나 corruption을 만들 수 있어 allocation 함수보다 오류 주입이 어렵습니다.

둘째, 첫 오류 반환 전에 어떠한 상태도 변경하면 안 됩니다. Global·local·input variable 변경, `*ret = NULL` 같은 output 초기화, counter 증감, flag 설정, preemption·IRQ disable, lock 획득이 모두 상태 변경입니다. 오류 반환 전 완전히 복구한다면 허용할 수 있습니다.

Caller가 함수가 항상 어떤 동작을 수행한다고 기대하는 경우 전체 함수 실행을 건너뛰는 injection은 그 계약을 깨므로 사용할 수 없습니다.

Error injection 안전성 점검
요건검토 내용
오류 contract실패 반환값이 있고 모든 caller가 검사·복구
State neutrality첫 오류 반환 전에 관찰 가능한 상태 변경 없음
Release semantics실패 시 object 소유권과 leak 처리가 명확
Caller expectation함수를 건너뛰어도 필수 side effect 계약을 깨지 않음

Error Injectable Functions
--------------------------

This part is for the kernel developers considering to add a function to
ALLOW_ERROR_INJECTION() macro.

Requirements for the Error Injectable Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Since the function-level error injection forcibly changes the code path
and returns an error even if the input and conditions are proper, this can
cause unexpected kernel crash if you allow error injection on the function
which is NOT error injectable. Thus, you (and reviewers) must ensure;

- The function returns an error code if it fails, and the callers must check
  it correctly (need to recover from it).

- The function does not execute any code which can change any state before
  the first error return. The state includes global or local, or input
  variable. For example, clear output address storage (e.g. `*ret = NULL`),
  increments/decrements counter, set a flag, preempt/irq disable or get
  a lock (if those are recovered before returning error, that will be OK.)

The first requirement is important, and it will result in that the release
(free objects) functions are usually harder to inject errors than allocate
functions. If errors of such release functions are not correctly handled
it will cause a memory leak easily (the caller will confuse that the object
has been released or corrupted.)

The second one is for the caller which expects the function should always
does something. Thus if the function error injection skips whole of the
function, the expectation is betrayed and causes an unexpected error.

ALLOW_ERROR_INJECTION 오류 유형

324-354

각 error-injectable 함수는 `ALLOW_ERROR_INJECTION()`에서 오류 유형을 지정합니다. 잘못된 유형은 caller가 반환값을 처리하지 못해 kernel crash를 일으킬 수 있으므로 함수의 실제 contract와 일치해야 합니다. 유형은 `include/asm-generic/error-injection.h`에 정의됩니다.

`EI_ETYPE_NULL`은 실패 시 `NULL`을 반환하는 함수에 사용합니다. 할당된 object address를 반환하는 함수가 대표적입니다.

`EI_ETYPE_ERRNO`는 `-EINVAL` 같은 `-errno`를 반환하는 함수에 사용하며 `ERR_PTR()`로 errno를 encode한 address를 반환하는 함수도 포함합니다.

`EI_ETYPE_ERRNO_NULL`은 `-errno` 또는 `NULL`을 반환하며 caller가 `IS_ERR_OR_NULL()`로 검사하는 함수에 맞습니다. `EI_ETYPE_TRUE`는 실패 시 `true`, 즉 0이 아닌 양수를 반환하는 함수용입니다.

Object pointer를 반환하는 함수에 errno type을 잘못 지정하면 반환값이 유효한 object address가 아니므로 caller가 접근할 때 장애가 발생합니다.

Error injection type
유형주입 반환일반적인 caller 검사
`EI_ETYPE_NULL``NULL`Pointer NULL check
`EI_ETYPE_ERRNO``-errno` 또는 `ERR_PTR(-errno)`음수 또는 `IS_ERR()`
`EI_ETYPE_ERRNO_NULL``NULL` 또는 `-errno``IS_ERR_OR_NULL()`
`EI_ETYPE_TRUE``true`Boolean failure check

Type of the Error Injectable Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Each error injectable functions will have the error type specified by the
ALLOW_ERROR_INJECTION() macro. You have to choose it carefully if you add
a new error injectable function. If the wrong error type is chosen, the
kernel may crash because it may not be able to handle the error.
There are 4 types of errors defined in include/asm-generic/error-injection.h

EI_ETYPE_NULL
  This function will return `NULL` if it fails. e.g. return an allocated
  object address.

EI_ETYPE_ERRNO
  This function will return an `-errno` error code if it fails. e.g. return
  -EINVAL if the input is wrong. This will include the functions which will
  return an address which encodes `-errno` by ERR_PTR() macro.

EI_ETYPE_ERRNO_NULL
  This function will return an `-errno` or `NULL` if it fails. If the caller
  of this function checks the return value with IS_ERR_OR_NULL() macro, this
  type will be appropriate.

EI_ETYPE_TRUE
  This function will return `true` (non-zero positive value) if it fails.

If you specifies a wrong type, for example, EI_TYPE_ERRNO for the function
which returns an allocated object, it may cause a problem because the returned
value is not an object address and the caller can not access to the address.

새 fault injection capability 추가

355-394

새 capability는 먼저 `<linux/fault-inject.h>`를 include하고 `DECLARE_FAULT_ATTR(name)`으로 fault attribute를 정의합니다. 세부 field는 `fault-inject.h`의 `struct fault_attr`을 참조합니다.

Boot부터 활성화해야 하면 `setup_fault_attr(attr, str)`를 사용해 boot option을 제공합니다. Runtime debugfs 방식은 failslab, fail_page_alloc, fail_usercopy, fail_make_request가 사용하며 `fault_create_debugfs_attr(name, parent, attr)` helper로 항목을 만듭니다.

Capability 범위가 kernel module 하나에 한정되면 module parameter로 fault attribute를 구성하는 편이 좋습니다.

마지막으로 실패를 삽입할 hook을 추가합니다. Client code는 `should_fail(attr, size)`가 true를 반환할 때 해당 작업의 실패를 실제로 주입해야 합니다.

새 capability 구현
Include `<linux/fault-inject.h>`Declare `fault_attr` with `DECLARE_FAULT_ATTR()`Expose boot, debugfs or module-parameter controlsCall `should_fail(attr, size)` at the target pointReturn or perform the intended synthetic failure

공통 fault_attr에 구성 경로와 실제 실패 hook을 연결합니다.

How to add new fault injection capability
-----------------------------------------

- #include <linux/fault-inject.h>

- define the fault attributes

  DECLARE_FAULT_ATTR(name);

  Please see the definition of struct fault_attr in fault-inject.h
  for details.

- provide a way to configure fault attributes

- boot option

  If you need to enable the fault injection capability from boot time, you can
  provide boot option to configure it. There is a helper function for it:

        setup_fault_attr(attr, str);

- debugfs entries

  failslab, fail_page_alloc, fail_usercopy, and fail_make_request use this way.
  Helper functions:

        fault_create_debugfs_attr(name, parent, attr);

- module parameters

  If the scope of the fault injection capability is limited to a
  single kernel module, it is better to provide module parameters to
  configure the fault attributes.

- add a hook to insert failures

  Upon should_fail() returning true, client code should inject a failure:

        should_fail(attr, size);

Module init·exit의 slab allocation 실패 예제

395-432

첫 번째 shell script는 `FAILTYPE=failslab`을 선택하고 task filter를 켠 뒤 probability 10%, interval 100, times 무제한, space 0, verbose 2, `ignore-gfp-wait=Y`를 설정합니다.

`faulty_system()`은 subshell의 `/proc/self/make-it-fail`에 1을 쓰고 대상 명령을 `exec`하여 표시된 process에만 slab fault를 주입합니다.

인자로 받은 각 module을 `modprobe`로 삽입하고 `modprobe -r`로 제거하므로 module init과 exit의 allocation error path를 모두 시험합니다.

Slab failure module test
Configure `failslab` controlsMark child process with `make-it-fail`Insert each moduleExercise initialization failure handlingRemove each module and exercise exit paths

Task filter로 modprobe process만 선택해 init·exit를 반복합니다.

Application Examples
--------------------

- Inject slab allocation failures into module init/exit code::

    #!/bin/bash

    FAILTYPE=failslab
    echo Y > /sys/kernel/debug/$FAILTYPE/task-filter
    echo 10 > /sys/kernel/debug/$FAILTYPE/probability
    echo 100 > /sys/kernel/debug/$FAILTYPE/interval
    echo -1 > /sys/kernel/debug/$FAILTYPE/times
    echo 0 > /sys/kernel/debug/$FAILTYPE/space
    echo 2 > /sys/kernel/debug/$FAILTYPE/verbose
    echo Y > /sys/kernel/debug/$FAILTYPE/ignore-gfp-wait

    faulty_system()
    {
        bash -c "echo 1 > /proc/self/make-it-fail && exec $*"
    }

    if [ $# -eq 0 ]
    then
        echo "Usage: $0 modulename [ modulename ... ]"
        exit 1
    fi

    for m in $*
    do
        echo inserting $m...
        faulty_system modprobe $m

        echo removing $m...
        faulty_system modprobe -r $m
    done

------------------------------------------------------------------------------

특정 module의 page allocation 실패 예제

433-473

두 번째 script는 `fail_page_alloc`을 사용해 특정 module의 code path에서만 page allocation을 실패시킵니다. Module을 로드한 뒤 `/sys/module/<module>/sections` 존재 여부를 확인합니다.

Module의 `.text` 시작 주소를 `require-start`, `.data` 주소를 `require-end`에 써서 stack caller가 module 범위 안에 있을 때만 주입합니다.

Task filter는 끄고 probability 10%, interval 100, times 무제한, space 0, verbose 2를 설정합니다. Sleep 가능한 allocation과 highmem allocation은 제외하고 stacktrace depth는 10으로 둡니다.

SIGINT, SIGTERM, EXIT trap은 probability를 0으로 되돌려 주입을 안전하게 중단합니다. 이후 script는 중단될 때까지 대기합니다.

Module-range page fault 설정
설정값·목적
`require-start`Module `.text` 주소
`require-end`Module `.data` 주소
`stacktrace-depth`10 frame
`ignore-gfp-wait`Sleep allocation 제외
`ignore-gfp-highmem`Highmem allocation 제외
Trap종료 시 probability=0

- Inject page allocation failures only for a specific module::

    #!/bin/bash

    FAILTYPE=fail_page_alloc
    module=$1

    if [ -z $module ]
    then
        echo "Usage: $0 <modulename>"
        exit 1
    fi

    modprobe $module

    if [ ! -d /sys/module/$module/sections ]
    then
        echo Module $module is not loaded
        exit 1
    fi

    cat /sys/module/$module/sections/.text > /sys/kernel/debug/$FAILTYPE/require-start
    cat /sys/module/$module/sections/.data > /sys/kernel/debug/$FAILTYPE/require-end

    echo N > /sys/kernel/debug/$FAILTYPE/task-filter
    echo 10 > /sys/kernel/debug/$FAILTYPE/probability
    echo 100 > /sys/kernel/debug/$FAILTYPE/interval
    echo -1 > /sys/kernel/debug/$FAILTYPE/times
    echo 0 > /sys/kernel/debug/$FAILTYPE/space
    echo 2 > /sys/kernel/debug/$FAILTYPE/verbose
    echo Y > /sys/kernel/debug/$FAILTYPE/ignore-gfp-wait
    echo Y > /sys/kernel/debug/$FAILTYPE/ignore-gfp-highmem
    echo 10 > /sys/kernel/debug/$FAILTYPE/stacktrace-depth

    trap "echo 0 > /sys/kernel/debug/$FAILTYPE/probability" SIGINT SIGTERM EXIT

    echo "Injecting errors into the module $module... (interrupt to stop)"
    sleep 1000000

------------------------------------------------------------------------------

Btrfs open_ctree 오류 주입 예제

474-511

이 script는 sparse image와 loop device를 만들고 Btrfs filesystem을 생성한 뒤 임시 mount point를 준비합니다.

`FAILTYPE=fail_function`, `FAILFUNC=open_ctree`를 선택하고 inject 목록에 `open_ctree`를 추가합니다. `printf %#x -12`로 retval에 `-ENOMEM`에 해당하는 음수 errno의 unsigned 표현을 씁니다.

Probability 100%, interval 0, times 무제한, space 0, verbose 1로 설정한 뒤 Btrfs mount를 실행합니다. Mount가 실패하면 expected error path가 작동한 것이므로 성공으로 판단하고, 예상과 달리 mount되면 실패로 표시한 뒤 unmount합니다.

시험 후 inject 목록을 비우고 mount point, loop device와 image를 정리합니다.

Btrfs function injection
Create Btrfs loop imageAdd `open_ctree` to `fail_function/inject`Set injected retval to -12Attempt Btrfs mountVerify failure and clean every resource

`open_ctree`가 강제로 오류를 반환할 때 mount cleanup path를 검증합니다.

- Inject open_ctree error while btrfs mount::

    #!/bin/bash

    rm -f testfile.img
    dd if=/dev/zero of=testfile.img bs=1M seek=1000 count=1
    DEVICE=$(losetup --show -f testfile.img)
    mkfs.btrfs -f $DEVICE
    mkdir -p tmpmnt

    FAILTYPE=fail_function
    FAILFUNC=open_ctree
    echo $FAILFUNC > /sys/kernel/debug/$FAILTYPE/inject
    printf %#x -12 > /sys/kernel/debug/$FAILTYPE/$FAILFUNC/retval
    echo N > /sys/kernel/debug/$FAILTYPE/task-filter
    echo 100 > /sys/kernel/debug/$FAILTYPE/probability
    echo 0 > /sys/kernel/debug/$FAILTYPE/interval
    echo -1 > /sys/kernel/debug/$FAILTYPE/times
    echo 0 > /sys/kernel/debug/$FAILTYPE/space
    echo 1 > /sys/kernel/debug/$FAILTYPE/verbose

    mount -t btrfs $DEVICE tmpmnt
    if [ $? -ne 0 ]
    then
        echo "SUCCESS!"
    else
        echo "FAILED!"
        umount tmpmnt
    fi

    echo > /sys/kernel/debug/$FAILTYPE/inject

    rmdir tmpmnt
    losetup -d $DEVICE
    rm testfile.img

------------------------------------------------------------------------------

Skbuff cache allocation만 실패시키기

512-522

Skbuff allocation만 시험하려면 `/sys/kernel/slab/skbuff_head_cache/failslab`에 1을 써서 `skbuff_head_cache`를 fault 대상으로 표시합니다.

기본적으로 꺼진 `failslab/cache-filter`를 1로 켠 뒤 `times=1`, `probability=1`을 설정해 선택한 cache에 한 번 fault injection을 활성화합니다.

Skbuff-only failslab
Mark `skbuff_head_cache` as faultyEnable `failslab/cache-filter`Set one allowed failureSet injection probabilityRun the network allocation path under test

Slab cache filter를 이용해 다른 allocation은 건드리지 않습니다.

- Inject only skbuff allocation failures ::

    # mark skbuff_head_cache as faulty
    echo 1 > /sys/kernel/slab/skbuff_head_cache/failslab
    # Turn on cache filter (off by default)
    echo 1 > /sys/kernel/debug/failslab/cache-filter
    # Turn on fault injection
    echo 1 > /sys/kernel/debug/failslab/times
    echo 1 > /sys/kernel/debug/failslab/probability

failcmd.sh로 명령 실행

523-550

`tools/testing/fault-injection/failcmd.sh`는 failslab 또는 fail_page_alloc을 설정한 상태에서 명령을 실행하는 과정을 단순화합니다. 전체 option은 `./tools/testing/fault-injection/failcmd.sh --help`로 확인합니다.

Option 없이 `-- make -C tools/testing/selftests/ run_tests`를 넘기면 기본 failslab fault를 최대 한 번 주입합니다. `--times=100`은 최대 실패 횟수를 100으로 늘립니다.

Environment variable `FAILCMD_TYPE=fail_page_alloc`을 지정하면 같은 명령에 slab 대신 page allocation failure를 주입합니다.

failcmd 사용 예
설정효과
기본Failslab, 최대 1회
`--times=100`최대 100회
`FAILCMD_TYPE=fail_page_alloc`Page allocation fault로 전환
`-- <command>`Fault 환경에서 실행할 명령 구분

Tool to run command with failslab or fail_page_alloc
----------------------------------------------------
In order to make it easier to accomplish the tasks mentioned above, we can use
tools/testing/fault-injection/failcmd.sh.  Please run a command
"./tools/testing/fault-injection/failcmd.sh --help" for more information and
see the following examples.

Examples:

Run a command "make -C tools/testing/selftests/ run_tests" with injecting slab
allocation failure::

        # ./tools/testing/fault-injection/failcmd.sh \
                -- make -C tools/testing/selftests/ run_tests

Same as above except to specify 100 times failures at most instead of one time
at most by default::

        # ./tools/testing/fault-injection/failcmd.sh --times=100 \
                -- make -C tools/testing/selftests/ run_tests

Same as above except to inject page allocation failure instead of slab
allocation failure::

        # env FAILCMD_TYPE=fail_page_alloc \
                ./tools/testing/fault-injection/failcmd.sh --times=100 \
                -- make -C tools/testing/selftests/ run_tests

Socketpair의 fault point 체계적 순회

551-611

C 예제는 `socketpair()` system call 안의 1번째, 2번째, 3번째 fault point를 차례로 실패시키고 더 이상 주입할 point가 없을 때까지 반복합니다.

먼저 failslab의 `ignore-gfp-wait`를 `N`으로 바꾸고 현재 thread의 `/proc/self/task/<tid>/fail-nth`를 read-write로 엽니다.

Loop에서 i를 파일에 써서 i번째 fault를 선택하고 `socketpair(AF_LOCAL, SOCK_STREAM, 0, fds)`를 호출합니다. `errno`를 보존하고 `pread()`로 fail-nth 상태를 읽습니다. Socketpair가 성공했다면 두 file descriptor를 닫습니다.

출력의 `Y`는 해당 순번의 fault가 실제 주입되었음을, `N`은 주입할 point가 더 없음을 뜻합니다. 예시에서는 1~15번째 호출이 errno 23 또는 12로 실패하고 16번째는 주입되지 않아 성공하면서 반복을 끝냅니다.

Systematic fail-nth 탐색
Open current thread `fail-nth` controlWrite fault index iInvoke `socketpair()` onceRead whether the fault firedClose successful descriptorsStop when readback remains positive and no fault fires

단일 system call의 모든 fault-capable 위치를 번호 순서로 재실행합니다.

Systematic faults using fail-nth
---------------------------------

The following code systematically faults 0-th, 1-st, 2-nd and so on
capabilities in the socketpair() system call::

  #include <sys/types.h>
  #include <sys/stat.h>
  #include <sys/socket.h>
  #include <sys/syscall.h>
  #include <fcntl.h>
  #include <unistd.h>
  #include <string.h>
  #include <stdlib.h>
  #include <stdio.h>
  #include <errno.h>

  int main()
  {
        int i, err, res, fail_nth, fds[2];
        char buf[128];

        system("echo N > /sys/kernel/debug/failslab/ignore-gfp-wait");
        sprintf(buf, "/proc/self/task/%ld/fail-nth", syscall(SYS_gettid));
        fail_nth = open(buf, O_RDWR);
        for (i = 1;; i++) {
                sprintf(buf, "%d", i);
                write(fail_nth, buf, strlen(buf));
                res = socketpair(AF_LOCAL, SOCK_STREAM, 0, fds);
                err = errno;
                pread(fail_nth, buf, sizeof(buf), 0);
                if (res == 0) {
                        close(fds[0]);
                        close(fds[1]);
                }
                printf("%d-th fault %c: res=%d/%d\n", i, atoi(buf) ? 'N' : 'Y',
                        res, err);
                if (atoi(buf))
                        break;
        }
        return 0;
  }

An example output::

        1-th fault Y: res=-1/23
        2-th fault Y: res=-1/23
        3-th fault Y: res=-1/12
        4-th fault Y: res=-1/12
        5-th fault Y: res=-1/23
        6-th fault Y: res=-1/23
        7-th fault Y: res=-1/23
        8-th fault Y: res=-1/12
        9-th fault Y: res=-1/12
        10-th fault Y: res=-1/12
        11-th fault Y: res=-1/12
        12-th fault Y: res=-1/12
        13-th fault Y: res=-1/12
        14-th fault Y: res=-1/12
        15-th fault Y: res=-1/12
        16-th fault N: res=0/12