요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
===========================================
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.
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).
- /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.
- /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
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 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.
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.
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);
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
------------------------------------------------------------------------------
- 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
------------------------------------------------------------------------------
- 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
------------------------------------------------------------------------------
- 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
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
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
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
사용 가능한 fault injection 기능
1-89Kernel 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 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입니다.
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 주입을 각각 끕니다.
- /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가 대상입니다.
- /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-290Debugfs를 사용할 수 없는 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를 순서대로 체계적으로 시험하기 위한 것입니다.
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 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가 접근할 때 장애가 발생합니다.
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를 반환할 때 해당 작업의 실패를 실제로 주입해야 합니다.
공통 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를 모두 시험합니다.
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는 중단될 때까지 대기합니다.
- 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를 정리합니다.
`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-522Skbuff allocation만 시험하려면 `/sys/kernel/slab/skbuff_head_cache/failslab`에 1을 써서 `skbuff_head_cache`를 fault 대상으로 표시합니다.
기본적으로 꺼진 `failslab/cache-filter`를 1로 켠 뒤 `times=1`, `probability=1`을 설정해 선택한 cache에 한 번 fault injection을 활성화합니다.
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를 주입합니다.
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-611C 예제는 `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번째는 주입되지 않아 성공하면서 반복을 끝냅니다.
단일 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
요약·해설
fault-injection.rst:1-611Linux 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를 순서대로 전수 시험합니다.
대상 선택부터 복구 검증과 설정 정리까지의 안전한 흐름입니다.