syzbot


ID Workflow Result Correct Bug Created Started Finished Revision Error
e8a9d68b-3db4-4e66-a3df-1abbef210f10 repro 💥 KCSAN: data-race in __stop_tty / pty_write (16) 2026/03/09 22:34 2026/03/09 22:34 2026/03/09 22:57 6972f30219093b03bcc1a54487e12a7097245c01 Error 504, Message: Deadline expired before operation could complete., Status: DEADLINE_EXCEEDED, Details: [map[@type:type.googleapis.com/google.rpc.DebugInfo detail:[ORIGINAL ERROR] generic::deadline_exceeded: [original: beyond::dependency::DEADLINE_EXCEEDED] while running coroutine; Failed while fetching a stream from leaf at '<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at '<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>' [type.googleapis.com/stairways.orch.ErrorLoc='learning/serving/servables/wiz/orch_wiz_servable.cc:1077'] === Source Location Trace: === net/rpc/common/stream/stream-context.cc:1470 learning/brain/research/stairways/orchestrator/root/remote_chain.cc:150 learning/serving/servables/wiz/orch_wiz_servable.cc:1085 ; Failed to run inference for model: go/debugstr name: "prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975" version { value: 1 } signature_name: "serving_default" ; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService]; for endpoint: [google.rpc.error_details_ext] { message: "Deadline expired before operation could complete." details { type_url: "type.googleapis.com/language_labs.genai.debug.GeminiApiDebugInfo" value: "\222\001\375\t\n\335\twhile running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\' [type.googleapis.com/stairways.orch.ErrorLoc=\'learning/serving/servables/wiz/orch_wiz_servable.cc:1077\']\n=== Source Location Trace: ===\nnet/rpc/common/stream/stream-context.cc:1470\nlearning/brain/research/stairways/orchestrator/root/remote_chain.cc:150\nlearning/serving/servables/wiz/orch_wiz_servable.cc:1085\n; Failed to run inference for model: go/debugstr \nname: \"prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975\"\nversion {\n value: 1\n}\nsignature_name: \"serving_default\"\n; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService]; for endpoint: \022\033net/rpc/rpc-status.cc:562:0" } } 525002922 { 3 { 1: "/aistudio/gemini-v4p1m-rev24-snowball-lc" } 6 { 5 { 1 { 1: "/aistudio/gemini-v4p1m-rev24-snowball-lc" 3: "serving_default" } 2: 1048576 3: 1 } 6 { 2: 1 3: 0 4: "Non-retryable error: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\' [type.googleapis.com/stairways.orch.ErrorLoc=\'learning/serving/servables/wiz/orch_wiz_servable.cc:1077\']\n=== Source Location Trace: ===\nnet/rpc/common/stream/stream-context.cc:1470\nlearning/brain/research/stairways/orchestrator/root/remote_chain.cc:150\nlearning/serving/servables/wiz/orch_wiz_servable.cc:1085\n

Crash report:
==================================================================
BUG: KCSAN: data-race in __stop_tty / pty_write

write to 0xffff888112056dbc of 1 bytes by task 6116 on cpu 1:
 __stop_tty+0x36/0x90 drivers/tty/tty_io.c:744
 n_tty_ioctl_helper+0x2d1/0x370 drivers/tty/tty_ioctl.c:951
 n_tty_ioctl+0x101/0x230 drivers/tty/n_tty.c:2496
 tty_ioctl+0x83e/0xb80 drivers/tty/tty_io.c:2801
 vfs_ioctl fs/ioctl.c:51 [inline]
 __do_sys_ioctl fs/ioctl.c:597 [inline]
 __se_sys_ioctl+0xce/0x140 fs/ioctl.c:583
 __x64_sys_ioctl+0x43/0x50 fs/ioctl.c:583
 x64_sys_call+0x14b0/0x3000 arch/x86/include/generated/asm/syscalls_64.h:17
 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
 do_syscall_64+0xc0/0x2a0 arch/x86/entry/syscall_64.c:94
 entry_SYSCALL_64_after_hwframe+0x77/0x7f

read to 0xffff888112056dbc of 1 bytes by task 2044 on cpu 0:
 pty_write+0x24/0x90 drivers/tty/pty.c:113
 tty_put_char+0x8f/0xc0 drivers/tty/tty_io.c:3154
 n_tty_process_echo_ops drivers/tty/n_tty.c:643 [inline]
 __process_echoes+0x2f9/0x6b0 drivers/tty/n_tty.c:689
 flush_echoes drivers/tty/n_tty.c:785 [inline]
 __receive_buf drivers/tty/n_tty.c:1618 [inline]
 n_tty_receive_buf_common+0x918/0xc10 drivers/tty/n_tty.c:1715
 n_tty_receive_buf2+0x33/0x40 drivers/tty/n_tty.c:1759
 tty_ldisc_receive_buf+0x66/0xf0 drivers/tty/tty_buffer.c:387
 tty_port_default_receive_buf+0x59/0x90 drivers/tty/tty_port.c:37
 receive_buf drivers/tty/tty_buffer.c:445 [inline]
 flush_to_ldisc+0x148/0x340 drivers/tty/tty_buffer.c:495
 process_one_work kernel/workqueue.c:3257 [inline]
 process_scheduled_works+0x4cd/0x9d0 kernel/workqueue.c:3340
 worker_thread+0x6bc/0x8b0 kernel/workqueue.c:3421
 kthread+0x488/0x510 kernel/kthread.c:463
 ret_from_fork+0x148/0x280 arch/x86/kernel/process.c:158
 ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:246

value changed: 0x00 -> 0x01

Reported by Kernel Concurrency Sanitizer on:
CPU: 0 UID: 0 PID: 2044 Comm: kworker/u8:6 Not tainted syzkaller #0 PREEMPT(voluntary) 
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 10/25/2025
Workqueue: events_unbound flush_to_ldisc
==================================================================

Trajectory:
Seq Timestamp Type Name Duration
0/0 2026/03/09 22:34 flow repro
23m Error:
Error 504, Message: Deadline expired before operation could complete., Status: DEADLINE_EXCEEDED, Details: [map[@type:type.googleapis.com/google.rpc.DebugInfo detail:[ORIGINAL ERROR] generic::deadline_exceeded: [original: beyond::dependency::DEADLINE_EXCEEDED] while running coroutine; Failed while fetching a stream from leaf at '<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at '<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>' [type.googleapis.com/stairways.orch.ErrorLoc='learning/serving/servables/wiz/orch_wiz_servable.cc:1077']
=== Source Location Trace: ===
net/rpc/common/stream/stream-context.cc:1470
learning/brain/research/stairways/orchestrator/root/remote_chain.cc:150
learning/serving/servables/wiz/orch_wiz_servable.cc:1085
;  Failed to run inference for model: go/debugstr   
name: "prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975"
version {
  value: 1
}
signature_name: "serving_default"
; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint:  [google.rpc.error_details_ext] { message: "Deadline expired before operation could complete." details { type_url: "type.googleapis.com/language_labs.genai.debug.GeminiApiDebugInfo" value: "\222\001\375\t\n\335\twhile running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\' [type.googleapis.com/stairways.orch.ErrorLoc=\'learning/serving/servables/wiz/orch_wiz_servable.cc:1077\']\n=== Source Location Trace: ===\nnet/rpc/common/stream/stream-context.cc:1470\nlearning/brain/research/stairways/orchestrator/root/remote_chain.cc:150\nlearning/serving/servables/wiz/orch_wiz_servable.cc:1085\n;  Failed to run inference for model: go/debugstr   \nname: \"prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975\"\nversion {\n  value: 1\n}\nsignature_name: \"serving_default\"\n; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint: \022\033net/rpc/rpc-status.cc:562:0" } } 525002922 { 3 { 1: "/aistudio/gemini-v4p1m-rev24-snowball-lc" } 6 { 5 { 1 { 1: "/aistudio/gemini-v4p1m-rev24-snowball-lc" 3: "serving_default" } 2: 1048576 3: 1 } 6 { 2: 1 3: 0 4: "Non-retryable error: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\' [type.googleapis.com/stairways.orch.ErrorLoc=\'learning/serving/servables/wiz/orch_wiz_servable.cc:1077\']\n=== Source Location Trace: ===\nnet/rpc/common/stream/stream-context.cc:1470\nlearning/brain/research/stairways/orchestrator/root/remote_chain.cc:150\nlearning/serving/servables/wiz/orch_wiz_servable.cc:1085\n;  Failed to run inference for model: go/debugstr   \nname: \"prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975\"\nversion {\n  value: 1\n}\nsignature_name: \"serving_default\"\n; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint: " 5 { 1 { 1: 1773096473 2: 991776351 } 2 { 1: 596 2: 826949732 } } 6: "\200\200\004" } } }]]

1/1 2026/03/09 22:34 action kernel-checkouter
0m Results:
map[KernelSrc:/usr/local/google/home/dvyukov/syzkaller/agent/workdir/cache/src/6bf99a46fe07931230f0a455cc816adb64b10fd9]

2/1 2026/03/09 22:35 action kernel-builder
4m Results:
map[KernelObj:/usr/local/google/home/dvyukov/syzkaller/agent/workdir/cache/build/a73b7d1e787dc98e60639807307595fccfcc422e]

3/1 2026/03/09 22:39 action codesearch-prepare
5m Results:
map[Index:codesearch-index]

4/1 2026/03/09 22:45 agent crash-repro-finder
12m Model:
gemini-3-pro-preview

Error:
Error 504, Message: Deadline expired before operation could complete., Status: DEADLINE_EXCEEDED, Details: [map[@type:type.googleapis.com/google.rpc.DebugInfo detail:[ORIGINAL ERROR] generic::deadline_exceeded: [original: beyond::dependency::DEADLINE_EXCEEDED] while running coroutine; Failed while fetching a stream from leaf at '<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at '<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>' [type.googleapis.com/stairways.orch.ErrorLoc='learning/serving/servables/wiz/orch_wiz_servable.cc:1077']
=== Source Location Trace: ===
net/rpc/common/stream/stream-context.cc:1470
learning/brain/research/stairways/orchestrator/root/remote_chain.cc:150
learning/serving/servables/wiz/orch_wiz_servable.cc:1085
;  Failed to run inference for model: go/debugstr   
name: "prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975"
version {
  value: 1
}
signature_name: "serving_default"
; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint:  [google.rpc.error_details_ext] { message: "Deadline expired before operation could complete." details { type_url: "type.googleapis.com/language_labs.genai.debug.GeminiApiDebugInfo" value: "\222\001\375\t\n\335\twhile running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\' [type.googleapis.com/stairways.orch.ErrorLoc=\'learning/serving/servables/wiz/orch_wiz_servable.cc:1077\']\n=== Source Location Trace: ===\nnet/rpc/common/stream/stream-context.cc:1470\nlearning/brain/research/stairways/orchestrator/root/remote_chain.cc:150\nlearning/serving/servables/wiz/orch_wiz_servable.cc:1085\n;  Failed to run inference for model: go/debugstr   \nname: \"prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975\"\nversion {\n  value: 1\n}\nsignature_name: \"serving_default\"\n; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint: \022\033net/rpc/rpc-status.cc:562:0" } } 525002922 { 3 { 1: "/aistudio/gemini-v4p1m-rev24-snowball-lc" } 6 { 5 { 1 { 1: "/aistudio/gemini-v4p1m-rev24-snowball-lc" 3: "serving_default" } 2: 1048576 3: 1 } 6 { 2: 1 3: 0 4: "Non-retryable error: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\' [type.googleapis.com/stairways.orch.ErrorLoc=\'learning/serving/servables/wiz/orch_wiz_servable.cc:1077\']\n=== Source Location Trace: ===\nnet/rpc/common/stream/stream-context.cc:1470\nlearning/brain/research/stairways/orchestrator/root/remote_chain.cc:150\nlearning/serving/servables/wiz/orch_wiz_servable.cc:1085\n;  Failed to run inference for model: go/debugstr   \nname: \"prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975\"\nversion {\n  value: 1\n}\nsignature_name: \"serving_default\"\n; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint: " 5 { 1 { 1: 1773096473 2: 991776351 } 2 { 1: 596 2: 826949732 } } 6: "\200\200\004" } } }]]

Instruction:
You are an expert in the Linux kernel fuzzing. Your goal is to write a syzkaller program to trigger a specific bug.
In the final output provide only the syz program that triggers the bug, and could be executed directly,
without backticks.

Don't make assumptions about the kernel source code, use the provided codesearch tools
to examine the kernel code instead.

Document about syzkaller program syntax:
===
# Program syntax

Syzkaller uses a compact domain-specific language (DSL) for programs
to log executed programs, test its code, and persist programs in the
corpus. This page provides a brief description of the corresponding
syntax. Some useful information can also be found in the
[existing examples](/sys/linux/test) and in the program
[deserialization code](/prog/encoding.go).

Together with execution options, the DSL provides everything that
syz-executor needs to run a program.

For example, consider the program:
```
r0 = syz_open_dev$loop(&(0x7f00000011c0), 0x0, 0x0)
r1 = openat$6lowpan_control(0xffffffffffffff9c, &(0x7f00000000c0), 0x2, 0x0)
ioctl$LOOP_SET_FD(r0, 0x4c00, r1)
```

Each line in this program describes a particular syscall invocation,
with the first two calls saving the result in temporary variables `r0`
and `r1`, which are passed to the third call.

```
line = assignment | call
assignment = variable " = " call
call = syscall-name "(" [arg ["," arg]*] ")"  ["(" [call-prop ["," call-prop*] ")"]
arg = "nil" | "AUTO" | const-arg | resource-arg | result-arg | pointer-arg | string-arg | struct-arg | array-arg | union-arg
const-arg = "0x" hex-integer
resource-arg = variable ["/" hex-integer] ["+" hex-integer]
result-arg = "<" variable "=>" arg
pointer-arg = "&" pointer-arg-addr ["=ANY"] "=" arg
pointer-arg-addr = "AUTO" | "(" pointer-addr ["/" region-size] ")"
string-arg = "'" escaped-string "'" | "\"" escaped-string "\"" | "\"$" escaped-string "\""
struct-arg =  "{" [arg ["," arg]*] "}"
array-arg = "[" [arg ["," arg]*] "]"
union-arg = "@" field-name ["=" arg]
call-prop = prop-name ": " prop-value
variable = "r" dec-integer
pointer-addr = hex-integer
region-size = hex-integer
```

Programs may also contain blank lines and comments.
```
# Obtain a file handle
r0 = openat(0xffffffffffffff9c, &AUTO='./file1\x00', 0x42, 0x1ff)

# Perform a write operation
write(r0, &AUTO="01010101", 0x4)
```

### Memory management

Memory management is performed by syzkaller itself. It will allocate
virtual memory regions of the necessary size and set the final values
of pointer arguments.

By using the `AUTO` keyword, programs can give syzkaller the full
control over storing the data. This may be convenient e.g. when a
parameter must be passed by reference, but the exact location of its
value is not of particular importance.

```
r1 = syz_genetlink_get_family_id$nl80211(&AUTO='nl80211\x00', 0xffffffffffffffff)
ioctl$sock_SIOCGIFINDEX_80211(r0, 0x8933, &AUTO={'wlan0\x00', <r2=>0x0})
```

Alternatively, some data can be "anchored" to specific addresses. It
may be especially important when a memory region must be shared
between multiple calls.  In this case, pointer addresses must be given
at the 0x7f0000000000 offset. Before the actual execution, syzkaller
will adjust pointers to the start of the actual mmap'ed region.

### Call properties

Call properties specify extra information about how a specific call
must be executed. Each call within a program has its own set of call
properties. If no properties are provided, syzkaller takes the default
ones.

Currently, syzkaller supports the following call properties.

#### Fault injection
Syntax: `fail_nth: N`.

It takes an integer (base 10) argument `N`. If the argument is
non-negative, a fault will be injected into the `N`-th occasion.

```
r0 = openat$6lowpan_control(0xffffffffffffff9c, &(0x7f00000000c0), 0x2, 0x0)
ioctl$LOOP_SET_FD(r0, 0x4c00, r0) (fail_nth: 5)
```

#### Async
Syntax: `async`.

Instructs `syz-executor` not to wait until the call completes and
to proceed immediately to the next call.

```
r0 = openat(0xffffffffffffff9c, &AUTO='./file1\x00', 0x42, 0x1ff)
write(r0, &AUTO="01010101", 0x4) (async)
read(r0, &AUTO=""/4, 0x4)
close(r0)
```

When setting `async` flags be aware of the following considerations:
* Such programs should only be executed in threaded mode (i.e. `-threaded`
flag must be passed to `syz-executor`.
* Each `async` call is executed in a separate thread and there's a
limited number of available threads (`kMaxThreads = 16`).
* If an `async` call produces a resource, keep in mind that some other call
might take it as input and `syz-executor` will just pass 0 if the resource-
producing call has not finished by that time.

===

Document about syzlang system call descriptions syntax:
===
# Syscall description language

aka `syzlang` (`[siːzˈlæŋg]`)

Pseudo-formal grammar of syscall description:

```
syscallname "(" [arg ["," arg]*] ")" [type] ["(" attribute* ")"]
arg = argname type
argname = identifier
type = typename [ "[" type-options "]" ]
typename = "const" | "intN" | "intptr" | "flags" | "array" | "ptr" |
	   "string" | "filename" | "glob" | "len" |
	   "bytesize" | "bytesizeN" | "bitsize" | "vma" | "proc" |
	   "compressed_image"
type-options = [type-opt ["," type-opt]]
```

common type-options include:

```
"opt" - the argument is optional (like mmap fd argument, or accept peer argument)
```

rest of the type-options are type-specific:

```
"const": integer constant, type-options:
	value, underlying type (one of "intN", "intptr")
"intN"/"intptr": an integer without a particular meaning, type-options:
	either an optional range of values (e.g. "5:10", or "100:200")
	or a reference to flags description (see below),
	or a single value
	optionally followed by an alignment parameter if using a range
"flags": a set of values, type-options:
	reference to flags description (see below), underlying int type (e.g. "int32")
"array": a variable/fixed-length array, type-options:
	type of elements, optional size (fixed "5", or ranged "5:10", boundaries inclusive)
"ptr"/"ptr64": a pointer to an object, type-options:
	direction (in/out/inout); type of the object
	ptr64 has size of 8 bytes regardless of target pointer size
"string": a zero-terminated memory buffer (no pointer indirection implied), type-options:
	either a string value in quotes for constant strings (e.g. "foo" or `deadbeef` for hex literal),
	or a reference to string flags (special value `filename` produces file names),
	optionally followed by a buffer size (string values will be padded with \x00 to that size)
"stringnoz": a non-zero-terminated memory buffer (no pointer indirection implied), type-options:
	either a string value in quotes for constant strings (e.g. "foo" or `deadbeef` for hex literal),
	or a reference to string flags,
"glob": glob pattern to match on the target files, type-options:
	a pattern string in quotes (syntax: https://golang.org/pkg/path/filepath/#Match)
	(e.g. "/sys/" or "/sys/**/*"),
	or include exclude glob too (e.g. "/sys/**/*:-/sys/power/state")
"fmt": a string representation of an integer (not zero-terminated), type-options:
	format (one of "dec", "hex", "oct") and the value (a resource, int, flags or proc)
	the resulting data is always fixed-size (formatted as "%020llu", "0x%016llx" or "%023llo", respectively)
"len": length of another field (for array it is number of elements), type-options:
	argname of the object
"bytesize": similar to "len", but always denotes the size in bytes, type-options:
	argname of the object
"bitsize": similar to "len", but always denotes the size in bits, type-options:
	argname of the object
"offsetof": offset of the field from the beginning of the parent struct, type-options:
	field
"vma"/"vma64": a pointer to a set of pages (used as input for mmap/munmap/mremap/madvise), type-options:
	optional number of pages (e.g. vma[7]), or a range of pages (e.g. vma[2-4])
	vma64 has size of 8 bytes regardless of target pointer size
"proc": per process int (see description below), type-options:
	value range start, how many values per process, underlying type
"compressed_image": zlib-compressed disk image
	syscalls accepting compressed images must be marked with `no_generate`
	and `no_minimize` call attributes. if the content of the decompressed image
	can be checked by a `fsck`-like command, use the `fsck` syscall attribute
"text": machine code of the specified type, type-options:
	text type (x86_real, x86_16, x86_32, x86_64, arm64)
"void": type with static size 0
	mostly useful inside of templates and varlen unions, can't be syscall argument
```

flags/len/flags also have trailing underlying type type-option when used in structs/unions/pointers.

Flags are described as:

```
flagname = const ["," const]*
```

or for string flags as:

```
flagname = "\"" literal "\"" ["," "\"" literal "\""]*
```

Call attributes are:

```
"disabled": the call will not be used in fuzzing; useful to temporary disable some calls
	or prohibit particular argument combinations.
"timeout[N]": additional execution timeout (in ms) for the call on top of some default value.
"prog_timeout[N]": additional execution timeout (in ms) for the whole program if it contains this call;
	if a program contains several such calls, the max value is used.
"ignore_return": ignore return value of this syscall in fallback feedback; need to be used for calls
	that don't return fixed error codes but rather something else (e.g. the current time).
"breaks_returns": ignore return values of all subsequent calls in the program in fallback feedback (can't be trusted).
"no_generate": do not try to generate this syscall, i.e. use only seed descriptions to produce it.
"no_minimize": do not modify instances of this syscall when trying to minimize a crashing program.
"no_squash": do not attempt to pass squashed arguments to this syscall.
	Without that, the fuzzer will sometimes attempt to replace complex structures with arrays of bytes,
	possibly triggering interesting mutations, but also making programs hard to reason about.
"fsck": the content of the compressed buffer argument for this syscall is a file system and the
	string argument is a fsck-like command that will be called to verify the filesystem.
"remote_cover": wait longer to collect remote coverage for this call.
"kfuzz_test": the call is a kfuzztest target.
"snapshot": the call is enabled by default only in snapshot fuzzing mode, but can also be enabled in
    the non-snasphot mode when listed in "enable_syscalls" with its full name (as opposed to a wildcard match).
    It can also always be disabled via "disable_syscalls".
    The attribute is generally used to mark calls that are not safe to execute in non-snapshot mode
	(can lead to false positives, or lost connections to test machines.
```

## Ints

`int8`, `int16`, `int32` and `int64` denote an integer of the corresponding size.
`intptr` denotes a pointer-sized integer, i.e. C `long` type.

By appending `be` suffix (e.g. `int16be`) integers become big-endian.

It's possible to specify a range of values for an integer in the format of `int32[0:100]` or `int32[0:4096, 512]` for a 512-aligned int.

Integers can also take a reference to flags description or a value as its first type-option.
In that case, the alignment parameter is not supported.

To denote a bitfield of size N use `int64:N`.

It's possible to use these various kinds of ints as base types for `const`, `flags`, `len` and `proc`.

```
example_struct {
	f0	int8			# random 1-byte integer
	f1	const[0x42, int16be]	# const 2-byte integer with value 0x4200 (big-endian 0x42)
	f2	int32[0:100]		# random 4-byte integer with values from 0 to 100 inclusive
	f3	int32[1:10, 2]		# random 4-byte integer with values {1, 3, 5, 7, 9}
	f4	int64:20		# random 20-bit bitfield
	f5	int8[10]		# const 1-byte integer with value 10
	f6	int32[flagname]		# random 4-byte integer from the set of values referenced by flagname
}
```

## Structs

Structs are described as:

```
structname "{" "\n"
	(fieldname type ("(" fieldattribute* ")")? (if[expression])? "\n")+
"}" ("[" attribute* "]")?
```

Fields can have attributes specified in parentheses after the field, independent
of their type. `in/out/inout` attribute specify per-field direction, for example:

```
foo {
	field0	const[1, int32]	(in)
	field1	int32		(inout)
	field2	fd		(out)
}
```

You may specify conditions that determine whether a field will be included:

```
foo {
	field0	int32
	field1	int32 (if[value[field0] == 0x1])
}
```

See [the corresponding section](syscall_descriptions_syntax.md#conditional-fields)
for more details.

`out_overlay` attribute allows to have separate input and output layouts for the struct.
Fields before the `out_overlay` field are input, fields starting from `out_overlay` are output.
Input and output fields overlap in memory (both start from the beginning of the struct in memory).
For example:

```
foo {
	in0	const[1, int32]
	in1	flags[bar, int8]
	in2	ptr[in, string]
	out0	fd	(out_overlay)
	out1	int32
}
```

Structs can have attributes specified in square brackets after the struct.
Attributes are:

- `packed`: the struct does not have paddings between fields and has alignment 1; this is similar to GNU C `__attribute__((packed))`; struct alignment can be overridden with `align` attribute
- `align[N]`: the struct has alignment N and padded up to multiple of `N`; contents of the padding are unspecified (though, frequently are zeros); similar to GNU C `__attribute__((aligned(N)))`
- `size[N]`: the struct is padded up to the specified size `N`; contents of the padding are unspecified (though, frequently are zeros)

## Unions

Unions are described as:

```
unionname "[" "\n"
	(fieldname type (if[expression])? "\n")+
"]" ("[" attribute* "]")?
```

During fuzzing, syzkaller randomly picks one of the union options.

You may also specify conditions that determine whether the corresponding
option may or may not be selected, depending on values of other fields. See
[the corresponding section](syscall_descriptions_syntax.md#conditional-fields)
for more details.

Unions can have attributes specified in square brackets after the union.
Attributes are:

- `varlen`: union size is the size of the particular chosen option (not statically known); without this attribute unions are statically sized as maximum of all options (similar to C unions)
- `size[N]`: the union is padded up to the specified size `N`; contents of the padding are unspecified (though, frequently are zeros)

## Resources

Resources represent values that need to be passed from output of one syscall to input of another syscall. For example, `close` syscall requires an input value (fd) previously returned by `open` or `pipe` syscall. To achieve this, `fd` is declared as a resource. This is a way of modelling dependencies between syscalls, as defining a syscall as the producer of a resource and another syscall as the consumer defines a loose sense of ordering between them. Resources are described as:

```
"resource" identifier "[" underlying_type "]" [ ":" const ("," const)* ]
```

`underlying_type` is either one of `int8`, `int16`, `int32`, `int64`, `intptr` or another resource (which models inheritance, for example, a socket is a subtype of fd). The optional set of constants represent resource special values, for example, `0xffffffffffffffff` (-1) for "no fd", or `AT_FDCWD` for "the current dir". Special values are used once in a while as resource values. If no special values specified, special value of `0` is used. Resources can then be used as types, for example:

```
resource fd[int32]: 0xffffffffffffffff, AT_FDCWD, 1000000
resource sock[fd]
resource sock_unix[sock]

socket(...) sock
accept(fd sock, ...) sock
listen(fd sock, backlog int32)
```

Resources don't have to be necessarily returned by a syscall. They can be used as any other data type. For example:

```
resource my_resource[int32]

request_producer(..., arg ptr[out, my_resource])
request_consumer(..., arg ptr[inout, test_struct])

test_struct {
	...
	attr	my_resource
}
```

For more complex producer/consumer scenarios, field attributes can be utilized.
For example:

```
resource my_resource_1[int32]
resource my_resource_2[int32]

request_produce1_consume2(..., arg ptr[inout, test_struct])

test_struct {
	...
	field0	my_resource_1	(out)
	field1	my_resource_2	(in)
}
```

Each resource type must be "produced" (used as an output) by at least one syscall
(outside of unions and optional pointers) and "consumed" (used as an input)
by at least one syscall.

## Type Aliases

Complex types that are often repeated can be given short type aliases using the
following syntax:

```
type identifier underlying_type
```

For example:

```
type signalno int32[0:65]
type net_port proc[20000, 4, int16be]
```

Then, type alias can be used instead of the underlying type in any contexts.
Underlying type needs to be described as if it's a struct field, that is,
with the base type if it's required. However, type alias can be used as syscall
arguments as well. Underlying types are currently restricted to integer types,
`ptr`, `ptr64`, `const`, `flags` and `proc` types.

There are some builtin type aliases:

```
type bool8	int8[0:1]
type bool16	int16[0:1]
type bool32	int32[0:1]
type bool64	int64[0:1]
type boolptr	intptr[0:1]

type fileoff[BASE] BASE

type filename string[filename]

type buffer[DIR] ptr[DIR, array[int8]]
```

## Type Templates

Type templates can be declared as follows:

```
type buffer[DIR] ptr[DIR, array[int8]]
type fileoff[BASE] BASE
type nlattr[TYPE, PAYLOAD] {
	nla_len		len[parent, int16]
	nla_type	const[TYPE, int16]
	payload		PAYLOAD
} [align_4]
```

and later used as follows:

```
syscall(a buffer[in], b fileoff[int64], c ptr[in, nlattr[FOO, int32]])
```

There is builtin type template `optional` defined as:

```
type optional[T] [
	val	T
	void	void
] [varlen]
```

## Length

You can specify length of a particular field in struct or a named argument by
using `len`, `bytesize` and `bitsize` types, for example:

```
write(fd fd, buf ptr[in, array[int8]], count len[buf])

sock_fprog {
	len	len[filter, int16]
	filter	ptr[in, array[sock_filter]]
}
```

If `len`'s argument is a pointer, then the length of the pointee argument is used.

To denote the length of a field in N-byte words use `bytesizeN`, possible values
for N are 1, 2, 4 and 8.

To denote the length of the parent struct, you can use `len[parent, int8]`.
To denote the length of the higher level parent when structs are embedded into
one another, you can specify the type name of the particular parent:

```
s1 {
    f0      len[s2]  # length of s2
}

s2 {
    f0      s1
    f1      array[int32]
    f2      len[parent, int32]
}
```

`len` argument can also be a path expression which allows more complex
addressing. Path expressions are similar to C field references, but also allow
referencing parent and sibling elements. A special reference `syscall` used
in the beginning of the path allows to refer directly to the syscall arguments.
For example:

```
s1 {
	a	ptr[in, s2]
	b	ptr[in, s3]
	c	array[int8]
}

s2 {
	d	array[int8]
}

s3 {
# This refers to the array c in the parent s1.
	e	len[s1:c, int32]
# This refers to the array d in the sibling s2.
	f	len[s1:a:d, int32]
# This refers to the array k in the child s4.
	g	len[i:j, int32]
# This refers to syscall argument l.
	h	len[syscall:l, int32]
	i	ptr[in, s4]
}

s4 {
	j	array[int8]
}

foo(k ptr[in, s1], l ptr[in, array[int8]])
```

## Proc

The `proc` type can be used to denote per process integers.
The idea is to have a separate range of values for each executor, so they don't interfere.

The simplest example is a port number.
The `proc[20000, 4, int16be]` type means that we want to generate an `int16be`
integer starting from `20000` and assign `4` values for each process.
As a result the executor number `n` will get values in the `[20000 + n * 4, 20000 + (n + 1) * 4)` range.

## Integer Constants

Integer constants can be specified as decimal literals, as `0x`-prefixed
hex literals, as `'`-surrounded char literals, or as symbolic constants
extracted from kernel headers or defined by `define` directives. For example:

```
foo(a const[10], b const[-10])
foo(a const[0xabcd])
foo(a int8['a':'z'])
foo(a const[PATH_MAX])
foo(a int32[PATH_MAX])
foo(a ptr[in, array[int8, MY_PATH_MAX]])
define MY_PATH_MAX	PATH_MAX + 2
```

## Conditional fields

### In structures

In syzlang, it's possible to specify a condition for every struct field that
determines whether the field should be included or omitted:

```
header_fields {
  magic       const[0xabcd, int16]
  haveInteger int8
} [packed]

packet {
  header  header_fields
  integer int64  (if[value[header:haveInteger] == 0x1])
  body    array[int8]
} [packed]

some_call(a ptr[in, packet])
```

In this example, the `packet` structure will include the field `integer` only
if `header.haveInteger == 1`. In memory, `packet` will have the following
layout:

| header.magic = 0xabcd | header.haveInteger = 0x1 | integer | body |
| --------------------- | ------------------------ | ------- | ---- |

That corresponds to e.g. the following program:

```
some_call(&AUTO={{AUTO, 0x1}, @value=0xabcd, []})
```

If `header.haveInteger` is not `1`, syzkaller will just pretend that the field
`integer` does not exist.

```
some_call(&AUTO={{AUTO, 0x0}, @void, []})
```

| header.magic = 0xabcd | header.haveInteger = 0x0 | body |
| --------------------- | ------------------------ | ---- |

Every conditional field is assumed to be of variable length and so is the struct
to which this field belongs.

When a variable length field appears in the middle of a structure, the structure
must be marked with `[packed].`

Conditions on bitfields are prohibited:

```
struct {
  f0 int
  f1 int:3 (if[value[f0] == 0x1])  # It will not compile.
}
```

But you may reference bitfields in your conditions:

```
struct {
  f0 int:1
  f1 int:7
  f2 int   (if[value[f0] == value[f1]])
} [packed]
```

### In unions

Let's consider the following example.

```
struct {
  type int
  body alternatives
}

alternatives [
  int     int64 (if[value[struct:type] == 0x1])
  arr     array[int64, 5] (if[value[struct:type] == 0x2])
  default int32
] [varlen]

some_call(a ptr[in, struct])
```

In this case, the union option will be selected depending on the value of the
`type` field. For example, if `type` is `0x1`, then it can be either `int` or
`default`:

```
some_call(&AUTO={0x1, @int=0x123})
some_call(&AUTO={0x1, @default=0x123})
```

If `type` is `0x2`, it can be either `arr` or `default`.

If `type` is neither `0x1` nor `0x2`, syzkaller may only select `default`:

```
some_call(&AUTO={0x0, @default=0xabcd})
```

To ensure that a union can always be constructed, the last union field **must always
have no condition**.

Thus, the following definition would fail to compile:

```
alternatives [
  int int64 (if[value[struct:type] == 0x1])
  arr array[int64, 5] (if[value[struct:type] == 0x1])
] [varlen]
```

During prog mutation and generation syzkaller will select a random union field
whose condition is satisfied.

### Expression syntax

Currently, only `==`, `!=`, `&` and `||` operators are supported. However, the
functionality was designed in such a way that adding more operators is easy.
Feel free to file a GitHub issue or write us an email in case it's needed.

Expressions are evaluated as `int64` values. If the final result of an
expression is not 0, it's assumed to be satisfied.

If you want to reference a field's value, you can do it via
`value[path:to:field]`, which is similar to the `len[]` argument.

```
sub_struct {
  f0 int
  # Reference a field in a parent struct.
  f1 int (if[value[struct:f2]]) # Same as if[value[struct:f2] != 0].
}

struct {
  f2 int
  f3 sub_struct
  f4 int (if[value[f2] == 0x2]) # Reference a sibling field.
  f5 int (if[value[f3:f0] == 0x1]) # Reference a nested field.
  f6 int (if[value[f3:f0] == 0x1 || value[f3:f0] == 0x2]) # Reference a nested field which either equals to 0x1 or 0x2.
} [packed]

call(a ptr[in, struct])
```

The referenced field must be of integer type and there must be no
conditional fields in the path to it. For example, the following
descriptions will not compile.

```
struct {
  f0 int
  f1 int (if[value[f0] == 0x1])
  f2 int (if[value[f1] == 0x1])
}
```

You may also reference constants in expressions:

```
struct {
  f0 int
  f1 int
  f2 int (if[value[f0] & SOME_CONST == OTHER_CONST])
}
```

## Meta

Description files can also contain `meta` directives that specify meta-information for the whole file.

```
meta noextract
```

Tells `make extract` to not extract constants for this file.
Though, `syz-extract` can still be invoked manually on this file.

```
meta arches["arch1", "arch2"]
```

Restricts this file only to the given set of architectures.
`make extract` and `make generate` will not use it on other architectures.

## Misc

Description files also contain `include` directives that refer to Linux kernel header files,
`incdir` directives that refer to custom Linux kernel header directories
and `define` directives that define symbolic constant values.

The syzkaller executor defines some [pseudo system calls](./pseudo_syscalls.md)
that can be used as any other syscall in a description file. These pseudo
system calls expand to literal C code and can perform user-defined
custom actions. You can find some examples in
[executor/common_linux.h](../executor/common_linux.h).

Also see [tips](syscall_descriptions.md#tips) on writing good descriptions.

===

Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Bug title: KCSAN: data-race in __stop_tty / pty_write

The bug report to reproduce:
==================================================================
BUG: KCSAN: data-race in __stop_tty / pty_write

write to 0xffff888112056dbc of 1 bytes by task 6116 on cpu 1:
 __stop_tty+0x36/0x90 drivers/tty/tty_io.c:744
 n_tty_ioctl_helper+0x2d1/0x370 drivers/tty/tty_ioctl.c:951
 n_tty_ioctl+0x101/0x230 drivers/tty/n_tty.c:2496
 tty_ioctl+0x83e/0xb80 drivers/tty/tty_io.c:2801
 vfs_ioctl fs/ioctl.c:51 [inline]
 __do_sys_ioctl fs/ioctl.c:597 [inline]
 __se_sys_ioctl+0xce/0x140 fs/ioctl.c:583
 __x64_sys_ioctl+0x43/0x50 fs/ioctl.c:583
 x64_sys_call+0x14b0/0x3000 arch/x86/include/generated/asm/syscalls_64.h:17
 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
 do_syscall_64+0xc0/0x2a0 arch/x86/entry/syscall_64.c:94
 entry_SYSCALL_64_after_hwframe+0x77/0x7f

read to 0xffff888112056dbc of 1 bytes by task 2044 on cpu 0:
 pty_write+0x24/0x90 drivers/tty/pty.c:113
 tty_put_char+0x8f/0xc0 drivers/tty/tty_io.c:3154
 n_tty_process_echo_ops drivers/tty/n_tty.c:643 [inline]
 __process_echoes+0x2f9/0x6b0 drivers/tty/n_tty.c:689
 flush_echoes drivers/tty/n_tty.c:785 [inline]
 __receive_buf drivers/tty/n_tty.c:1618 [inline]
 n_tty_receive_buf_common+0x918/0xc10 drivers/tty/n_tty.c:1715
 n_tty_receive_buf2+0x33/0x40 drivers/tty/n_tty.c:1759
 tty_ldisc_receive_buf+0x66/0xf0 drivers/tty/tty_buffer.c:387
 tty_port_default_receive_buf+0x59/0x90 drivers/tty/tty_port.c:37
 receive_buf drivers/tty/tty_buffer.c:445 [inline]
 flush_to_ldisc+0x148/0x340 drivers/tty/tty_buffer.c:495
 process_one_work kernel/workqueue.c:3257 [inline]
 process_scheduled_works+0x4cd/0x9d0 kernel/workqueue.c:3340
 worker_thread+0x6bc/0x8b0 kernel/workqueue.c:3421
 kthread+0x488/0x510 kernel/kthread.c:463
 ret_from_fork+0x148/0x280 arch/x86/kernel/process.c:158
 ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:246

value changed: 0x00 -> 0x01

Reported by Kernel Concurrency Sanitizer on:
CPU: 0 UID: 0 PID: 2044 Comm: kworker/u8:6 Not tainted syzkaller #0 PREEMPT(voluntary) 
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 10/25/2025
Workqueue: events_unbound flush_to_ldisc
==================================================================


The list of existing description files:
acpi_thermal_rel.txt
aio.txt
auto.txt
binfmt.txt
bpf.txt
bpf_prog.txt
bpf_trace.txt
cgroup.txt
damon.txt
dev_ashmem.txt
dev_bifrost.txt
dev_binder.txt
dev_binderfs.txt
dev_block.txt
dev_bsg.txt
dev_bus_usb.txt
dev_camx.txt
dev_cdrom.txt
dev_cec.txt
dev_char_usb.txt
dev_comedi.txt
dev_dma_heap.txt
dev_dri.txt
dev_dsp.txt
dev_dvb_demux.txt
dev_dvb_dvr.txt
dev_dvb_frontend.txt
dev_fb.txt
dev_floppy.txt
dev_hidraw.txt
dev_i2c.txt
dev_i915.txt
dev_img_rogue.txt
dev_infiniband_rdma.txt
dev_infiniband_rdma_cm.txt
dev_input.txt
dev_iommu.txt
dev_kvm.txt
dev_kvm_amd64.txt
dev_kvm_arm64.txt
dev_kvm_extra.txt
dev_kvm_riscv64.txt
dev_loop.txt
dev_mali.txt
dev_media.txt
dev_msm.txt
dev_msr.txt
dev_nbd.txt
dev_net_tun.txt
dev_panthor.txt
dev_ppp.txt
dev_ptmx.txt
dev_ptp.txt
dev_qat_adf_ctl.txt
dev_qrtr_tun.txt
dev_random.txt
dev_rfkill.txt
dev_rtc.txt
dev_sequencer.txt
dev_sg.txt
dev_snapshot.txt
dev_snd_control.txt
dev_snd_hw.txt
dev_snd_midi.txt
dev_snd_pcm.txt
dev_snd_seq.txt
dev_snd_timer.txt
dev_sr.txt
dev_sw_sync.txt
dev_tlk_device.txt
dev_trusty.txt
dev_udmabuf.txt
dev_uhid.txt
dev_uinput.txt
dev_usb_hiddev.txt
dev_usbmon.txt
dev_userio.txt
dev_vfio.txt
dev_vga_arbiter.txt
dev_vhci.txt
dev_video4linux.txt
dev_video4linux_vim2m.txt
dev_virtual_nci.txt
dev_vtpm.txt
fanotify.txt
filesystem.txt
fs_9p.txt
fs_fuse.txt
fs_incfs.txt
fs_ioctl.txt
fs_ioctl_autofs.txt
fs_ioctl_btrfs.txt
fs_ioctl_ext4.txt
fs_ioctl_f2fs.txt
fs_ioctl_fat.txt
fs_ioctl_fscrypt.txt
fs_ioctl_fsverity.txt
fs_ioctl_xfs.txt
futex.txt
hafnium.txt
inotify.txt
io_uring.txt
ipc.txt
key.txt
kfuzztest.txt
l2cap.txt
landlock.txt
lsm.txt
namespaces.txt
net_80211.txt
netfilter.txt
netfilter_arp.txt
netfilter_bridge.txt
netfilter_ipv4.txt
netfilter_ipv6.txt
netfilter_ipvs.txt
netfilter_targets.txt
pagemap_ioctl.txt
perf.txt
prctl.txt
quotactl.txt
seccomp.txt
security_apparmor.txt
security_selinux.txt
security_smack.txt
socket.txt
socket_alg.txt
socket_ax25.txt
socket_bluetooth.txt
socket_caif.txt
socket_can.txt
socket_ieee802154.txt
socket_inet.txt
socket_inet6.txt
socket_inet_dccp.txt
socket_inet_icmp.txt
socket_inet_igmp.txt
socket_inet_l2tp.txt
socket_inet_sctp.txt
socket_inet_tcp.txt
socket_inet_udp.txt
socket_ip_tunnel.txt
socket_isdn.txt
socket_kcm.txt
socket_key.txt
socket_llc.txt
socket_netlink.txt
socket_netlink_audit.txt
socket_netlink_crypto.txt
socket_netlink_generic.txt
socket_netlink_generic_80211.txt
socket_netlink_generic_batadv.txt
socket_netlink_generic_devlink.txt
socket_netlink_generic_ethtool.txt
socket_netlink_generic_fou.txt
socket_netlink_generic_gtp.txt
socket_netlink_generic_mptcp.txt
socket_netlink_generic_net_dm.txt
socket_netlink_generic_netlabel.txt
socket_netlink_generic_nfc.txt
socket_netlink_generic_seg6.txt
socket_netlink_generic_smc.txt
socket_netlink_generic_team.txt
socket_netlink_generic_wireguard.txt
socket_netlink_netfilter.txt
socket_netlink_netfilter_acct.txt
socket_netlink_netfilter_conntrack.txt
socket_netlink_netfilter_conntrack_exp.txt
socket_netlink_netfilter_conntrack_helper.txt
socket_netlink_netfilter_ipset.txt
socket_netlink_netfilter_log.txt
socket_netlink_netfilter_nft_compat.txt
socket_netlink_netfilter_nftables.txt
socket_netlink_netfilter_osf.txt
socket_netlink_netfilter_queue.txt
socket_netlink_netfilter_timeout.txt
socket_netlink_rdma.txt
socket_netlink_route.txt
socket_netlink_route_sched.txt
socket_netlink_route_sched_retired.txt
socket_netlink_sock_diag.txt
socket_netlink_xfrm.txt
socket_netrom.txt
socket_nfc.txt
socket_nvme_of_tcp.txt
socket_packet.txt
socket_phonet.txt
socket_pppox.txt
socket_qipcrtr.txt
socket_rds.txt
socket_rose.txt
socket_rxrpc.txt
socket_tipc.txt
socket_tipc_netlink.txt
socket_unix.txt
socket_vnet.txt
socket_x25.txt
socket_xdp.txt
sys.txt
uffd.txt
usbip.txt
vmw_vmci.txt
vnet.txt
vnet_mptcp.txt
vusb.txt
watch_queue.txt
xattr.txt


5/2 2026/03/09 22:45 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 13327
							output: 24
							thoughts: 658
						

Thoughts:
**Analyzing a KCSAN Data-Race Report in TTY Subsystem**

Okay, so I've got a KCSAN data-race report that's caught my attention. It's flagging a potential issue in the `__stop_tty` function, specifically when it's interacting with `pty_write`. The report pinpoints the race happening on a single byte at the address `0xffff888112056dbc`.

My immediate instinct is to dissect the stack traces to understand the execution paths involved in both the write and the read operations.

On the *write* side, it starts in `__stop_tty` at `tty_io.c:744`, then cascades through `n_tty_ioctl_helper`, `n_tty_ioctl`, and `tty_ioctl` before hitting the virtual filesystem interface (`vfs_ioctl`) and eventually the system call layer. This suggests a control flow involving an ioctl call, which is very common.

The *read* side shows a different path, originating in `pty_write` at `pty.c:113` and moving through various tty layer functions. It includes `tty_put_char`, `n_tty_process_echo_ops`, `n_tty_receive_buf_common`, and ultimately `flush_to_ldisc`. This looks like data being written through a pty device, passing through the n_tty layer, and finally being processed.

Now, my next step is to examine the specific lines of code where the potential race is flagged. I need to dive into `drivers/tty/tty_io.c:744` within `__stop_tty` and `drivers/tty/pty.c:113` within `pty_write`. I have to pinpoint what data is being accessed and how these two functions interact. From the stack traces I would have to conclude that an ioctl call in the write path is interfering with a read path through the pty device. My suspicions lean towards a lock or a shared data structure that isn't being protected correctly during the interaction between these seemingly disparate functions. Time to get down to the code!



6/2 2026/03/09 22:45 tool read-file
0m Args:
map[File:drivers/tty/tty_io.c]

Results:
map[Contents:// SPDX-License-Identifier: GPL-2.0
/*
 *  Copyright (C) 1991, 1992  Linus Torvalds
 */

/*
 * 'tty_io.c' gives an orthogonal feeling to tty's, be they consoles
 * or rs-channels. It also implements echoing, cooked mode etc.
 *
 * Kill-line thanks to John T Kohl, who also corrected VMIN = VTIME = 0.
 *
 * Modified by Theodore Ts'o, 9/14/92, to dynamically allocate the
 * tty_struct and tty_queue structures.  Previously there was an array
 * of 256 tty_struct's which was statically allocated, and the
 * tty_queue structures were allocated at boot time.  Both are now
 * dynamically allocated only when the tty is open.
 *
 * Also restructured routines so that there is more of a separation
 * between the high-level tty routines (tty_io.c and tty_ioctl.c) and
 * the low-level tty routines (serial.c, pty.c, console.c).  This
 * makes for cleaner and more compact code.  -TYT, 9/17/92
 *
 * Modified by Fred N. van Kempen, 01/29/93, to add line disciplines
 * which can be dynamically activated and de-activated by the line
 * discipline handling modules (like SLIP).
 *
 * NOTE: pay no attention to the line discipline code (yet); its
 * interface is still subject to change in this version...
 * -- TYT, 1/31/92
 *
 * Added functionality to the OPOST tty handling.  No delays, but all
 * other bits should be there.
 *	-- Nick Holloway <alfie@dcs.warwick.ac.uk>, 27th May 1993.
 *
 * Rewrote canonical mode and added more termios flags.
 *	-- julian@uhunix.uhcc.hawaii.edu (J. Cowley), 13Jan94
 *
 * Reorganized FASYNC support so mouse code can share it.
 *	-- ctm@ardi.com, 9Sep95
 *
 * New TIOCLINUX variants added.
 *	-- mj@k332.feld.cvut.cz, 19-Nov-95
 *
 * Restrict vt switching via ioctl()
 *      -- grif@cs.ucr.edu, 5-Dec-95
 *
 * Move console and virtual terminal code to more appropriate files,
 * implement CONFIG_VT and generalize console device interface.
 *	-- Marko Kohtala <Marko.Kohtala@hut.fi>, March 97
 *
 * Rewrote tty_init_dev and tty_release_dev to eliminate races.
 *	-- Bill Hawes <whawes@star.net>, June 97
 *
 * Added devfs support.
 *      -- C. Scott Ananian <cananian@alumni.princeton.edu>, 13-Jan-1998
 *
 * Added support for a Unix98-style ptmx device.
 *      -- C. Scott Ananian <cananian@alumni.princeton.edu>, 14-Jan-1998
 *
 * Reduced memory usage for older ARM systems
 *      -- Russell King <rmk@arm.linux.org.uk>
 *
 * Move do_SAK() into process context.  Less stack use in devfs functions.
 * alloc_tty_struct() always uses kmalloc()
 *			 -- Andrew Morton <andrewm@uow.edu.eu> 17Mar01
 */

#include <linux/types.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/fcntl.h>
#include <linux/sched/signal.h>
#include <linux/sched/task.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/devpts_fs.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/console.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/kd.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/ppp-ioctl.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/seq_file.h>
#include <linux/serial.h>
#include <linux/ratelimit.h>
#include <linux/compat.h>
#include <linux/uaccess.h>
#include <linux/termios_internal.h>
#include <linux/fs.h>

#include <linux/kbd_kern.h>
#include <linux/vt_kern.h>
#include <linux/selection.h>

#include <linux/kmod.h>
#include <linux/nsproxy.h>
#include "tty.h"

#undef TTY_DEBUG_HANGUP
#ifdef TTY_DEBUG_HANGUP
# define tty_debug_hangup(tty, f, args...)	tty_debug(tty, f, ##args)
#else
# define tty_debug_hangup(tty, f, args...)	do { } while (0)
#endif

#define TTY_PARANOIA_CHECK 1
#define CHECK_TTY_COUNT 1

struct ktermios tty_std_termios = {	/* for the benefit of tty drivers  */
	.c_iflag = ICRNL | IXON,
	.c_oflag = OPOST | ONLCR,
	.c_cflag = B38400 | CS8 | CREAD | HUPCL,
	.c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK |
		   ECHOCTL | ECHOKE | IEXTEN,
	.c_cc = INIT_C_CC,
	.c_ispeed = 38400,
	.c_ospeed = 38400,
	/* .c_line = N_TTY, */
};
EXPORT_SYMBOL(tty_std_termios);

/* This list gets poked at by procfs and various bits of boot up code. This
 * could do with some rationalisation such as pulling the tty proc function
 * into this file.
 */

LIST_HEAD(tty_drivers);			/* linked list of tty drivers */

/* Mutex to protect creating and releasing a tty */
DEFINE_MUTEX(tty_mutex);

static ssize_t tty_read(struct kiocb *, struct iov_iter *);
static ssize_t tty_write(struct kiocb *, struct iov_iter *);
static __poll_t tty_poll(struct file *, poll_table *);
static int tty_open(struct inode *, struct file *);
#ifdef CONFIG_COMPAT
static long tty_compat_ioctl(struct file *file, unsigned int cmd,
				unsigned long arg);
#else
#define tty_compat_ioctl NULL
#endif
static int __tty_fasync(int fd, struct file *filp, int on);
static int tty_fasync(int fd, struct file *filp, int on);
static void release_tty(struct tty_struct *tty, int idx);

/**
 * free_tty_struct - free a disused tty
 * @tty: tty struct to free
 *
 * Free the write buffers, tty queue and tty memory itself.
 *
 * Locking: none. Must be called after tty is definitely unused
 */
static void free_tty_struct(struct tty_struct *tty)
{
	tty_ldisc_deinit(tty);
	put_device(tty->dev);
	kvfree(tty->write_buf);
	kfree(tty);
}

static inline struct tty_struct *file_tty(struct file *file)
{
	return ((struct tty_file_private *)file->private_data)->tty;
}

int tty_alloc_file(struct file *file)
{
	struct tty_file_private *priv;

	priv = kmalloc(sizeof(*priv), GFP_KERNEL);
	if (!priv)
		return -ENOMEM;

	file->private_data = priv;

	return 0;
}

/* Associate a new file with the tty structure */
void tty_add_file(struct tty_struct *tty, struct file *file)
{
	struct tty_file_private *priv = file->private_data;

	priv->tty = tty;
	priv->file = file;

	spin_lock(&tty->files_lock);
	list_add(&priv->list, &tty->tty_files);
	spin_unlock(&tty->files_lock);
}

/**
 * tty_free_file - free file->private_data
 * @file: to free private_data of
 *
 * This shall be used only for fail path handling when tty_add_file was not
 * called yet.
 */
void tty_free_file(struct file *file)
{
	struct tty_file_private *priv = file->private_data;

	file->private_data = NULL;
	kfree(priv);
}

/* Delete file from its tty */
static void tty_del_file(struct file *file)
{
	struct tty_file_private *priv = file->private_data;
	struct tty_struct *tty = priv->tty;

	spin_lock(&tty->files_lock);
	list_del(&priv->list);
	spin_unlock(&tty->files_lock);
	tty_free_file(file);
}

/**
 * tty_name - return tty naming
 * @tty: tty structure
 *
 * Convert a tty structure into a name. The name reflects the kernel naming
 * policy and if udev is in use may not reflect user space
 *
 * Locking: none
 */
const char *tty_name(const struct tty_struct *tty)
{
	if (!tty) /* Hmm.  NULL pointer.  That's fun. */
		return "NULL tty";
	return tty->name;
}
EXPORT_SYMBOL(tty_name);

const char *tty_driver_name(const struct tty_struct *tty)
{
	if (!tty || !tty->driver)
		return "";
	return tty->driver->name;
}

static int tty_paranoia_check(struct tty_struct *tty, struct inode *inode,
			      const char *routine)
{
#ifdef TTY_PARANOIA_CHECK
	if (!tty) {
		pr_warn("(%d:%d): %s: NULL tty\n",
			imajor(inode), iminor(inode), routine);
		return 1;
	}
#endif
	return 0;
}

/* Caller must hold tty_lock */
static void check_tty_count(struct tty_struct *tty, const char *routine)
{
#ifdef CHECK_TTY_COUNT
	struct list_head *p;
	int count = 0, kopen_count = 0;

	scoped_guard(spinlock, &tty->files_lock)
		list_for_each(p, &tty->tty_files)
			count++;

	if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
	    tty->driver->subtype == PTY_TYPE_SLAVE &&
	    tty->link && tty->link->count)
		count++;
	if (tty_port_kopened(tty->port))
		kopen_count++;
	if (tty->count != (count + kopen_count)) {
		tty_warn(tty, "%s: tty->count(%d) != (#fd's(%d) + #kopen's(%d))\n",
			 routine, tty->count, count, kopen_count);
	}
#endif
}

/**
 * get_tty_driver - find device of a tty
 * @device: device identifier
 * @index: returns the index of the tty
 *
 * This routine returns a tty driver structure, given a device number and also
 * passes back the index number.
 *
 * Locking: caller must hold tty_mutex
 */
static struct tty_driver *get_tty_driver(dev_t device, int *index)
{
	struct tty_driver *p;

	list_for_each_entry(p, &tty_drivers, tty_drivers) {
		dev_t base = MKDEV(p->major, p->minor_start);

		if (device < base || device >= base + p->num)
			continue;
		*index = device - base;
		return tty_driver_kref_get(p);
	}
	return NULL;
}

/**
 * tty_dev_name_to_number - return dev_t for device name
 * @name: user space name of device under /dev
 * @number: pointer to dev_t that this function will populate
 *
 * This function converts device names like ttyS0 or ttyUSB1 into dev_t like
 * (4, 64) or (188, 1). If no corresponding driver is registered then the
 * function returns -%ENODEV.
 *
 * Locking: this acquires tty_mutex to protect the tty_drivers list from
 *	being modified while we are traversing it, and makes sure to
 *	release it before exiting.
 */
int tty_dev_name_to_number(const char *name, dev_t *number)
{
	struct tty_driver *p;
	int ret;
	int index, prefix_length = 0;
	const char *str;

	for (str = name; *str && !isdigit(*str); str++)
		;

	if (!*str)
		return -EINVAL;

	ret = kstrtoint(str, 10, &index);
	if (ret)
		return ret;

	prefix_length = str - name;

	guard(mutex)(&tty_mutex);

	list_for_each_entry(p, &tty_drivers, tty_drivers)
		if (prefix_length == strlen(p->name) && strncmp(name,
					p->name, prefix_length) == 0) {
			if (index < p->num) {
				*number = MKDEV(p->major, p->minor_start + index);
				return 0;
			}
		}

	return -ENODEV;
}
EXPORT_SYMBOL_GPL(tty_dev_name_to_number);

#ifdef CONFIG_CONSOLE_POLL

/**
 * tty_find_polling_driver - find device of a polled tty
 * @name: name string to match
 * @line: pointer to resulting tty line nr
 *
 * This routine returns a tty driver structure, given a name and the condition
 * that the tty driver is capable of polled operation.
 */
struct tty_driver *tty_find_polling_driver(char *name, int *line)
{
	struct tty_driver *p;
	int tty_line = 0;
	int len;
	char *str, *stp;

	for (str = name; *str; str++)
		if ((*str >= '0' && *str <= '9') || *str == ',')
			break;
	if (!*str)
		return NULL;

	len = str - name;
	tty_line = simple_strtoul(str, &str, 10);

	guard(mutex)(&tty_mutex);

	/* Search through the tty devices to look for a match */
	list_for_each_entry(p, &tty_drivers, tty_drivers) {
		if (!len || strncmp(name, p->name, len) != 0)
			continue;
		stp = str;
		if (*stp == ',')
			stp++;
		if (*stp == '\0')
			stp = NULL;

		if (tty_line >= 0 && tty_line < p->num && p->ops &&
		    p->ops->poll_init && !p->ops->poll_init(p, tty_line, stp)) {
			*line = tty_line;
			return tty_driver_kref_get(p);
		}
	}

	return NULL;
}
EXPORT_SYMBOL_GPL(tty_find_polling_driver);
#endif

static ssize_t hung_up_tty_read(struct kiocb *iocb, struct iov_iter *to)
{
	return 0;
}

static ssize_t hung_up_tty_write(struct kiocb *iocb, struct iov_iter *from)
{
	return -EIO;
}

/* No kernel lock held - none needed ;) */
static __poll_t hung_up_tty_poll(struct file *filp, poll_table *wait)
{
	return EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLRDNORM | EPOLLWRNORM;
}

static long hung_up_tty_ioctl(struct file *file, unsigned int cmd,
		unsigned long arg)
{
	return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
}

static long hung_up_tty_compat_ioctl(struct file *file,
				     unsigned int cmd, unsigned long arg)
{
	return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
}

static int hung_up_tty_fasync(int fd, struct file *file, int on)
{
	return -ENOTTY;
}

static void tty_show_fdinfo(struct seq_file *m, struct file *file)
{
	struct tty_struct *tty = file_tty(file);

	if (tty && tty->ops && tty->ops->show_fdinfo)
		tty->ops->show_fdinfo(tty, m);
}

static const struct file_operations tty_fops = {
	.read_iter	= tty_read,
	.write_iter	= tty_write,
	.splice_read	= copy_splice_read,
	.splice_write	= iter_file_splice_write,
	.poll		= tty_poll,
	.unlocked_ioctl	= tty_ioctl,
	.compat_ioctl	= tty_compat_ioctl,
	.open		= tty_open,
	.release	= tty_release,
	.fasync		= tty_fasync,
	.show_fdinfo	= tty_show_fdinfo,
};

static const struct file_operations console_fops = {
	.read_iter	= tty_read,
	.write_iter	= redirected_tty_write,
	.splice_read	= copy_splice_read,
	.splice_write	= iter_file_splice_write,
	.poll		= tty_poll,
	.unlocked_ioctl	= tty_ioctl,
	.compat_ioctl	= tty_compat_ioctl,
	.open		= tty_open,
	.release	= tty_release,
	.fasync		= tty_fasync,
};

static const struct file_operations hung_up_tty_fops = {
	.read_iter	= hung_up_tty_read,
	.write_iter	= hung_up_tty_write,
	.poll		= hung_up_tty_poll,
	.unlocked_ioctl	= hung_up_tty_ioctl,
	.compat_ioctl	= hung_up_tty_compat_ioctl,
	.release	= tty_release,
	.fasync		= hung_up_tty_fasync,
};

static DEFINE_SPINLOCK(redirect_lock);
static struct file *redirect;

/**
 * tty_wakeup - request more data
 * @tty: terminal
 *
 * Internal and external helper for wakeups of tty. This function informs the
 * line discipline if present that the driver is ready to receive more output
 * data.
 */
void tty_wakeup(struct tty_struct *tty)
{
	struct tty_ldisc *ld;

	if (test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) {
		ld = tty_ldisc_ref(tty);
		if (ld) {
			if (ld->ops->write_wakeup)
				ld->ops->write_wakeup(tty);
			tty_ldisc_deref(ld);
		}
	}
	wake_up_interruptible_poll(&tty->write_wait, EPOLLOUT);
}
EXPORT_SYMBOL_GPL(tty_wakeup);

/**
 * tty_release_redirect - Release a redirect on a pty if present
 * @tty: tty device
 *
 * This is available to the pty code so if the master closes, if the slave is a
 * redirect it can release the redirect.
 */
static struct file *tty_release_redirect(struct tty_struct *tty)
{
	guard(spinlock)(&redirect_lock);

	if (redirect && file_tty(redirect) == tty) {
		struct file *f = redirect;
		redirect = NULL;
		return f;
	}

	return NULL;
}

/**
 * __tty_hangup - actual handler for hangup events
 * @tty: tty device
 * @exit_session: if non-zero, signal all foreground group processes
 *
 * This can be called by a "kworker" kernel thread. That is process synchronous
 * but doesn't hold any locks, so we need to make sure we have the appropriate
 * locks for what we're doing.
 *
 * The hangup event clears any pending redirections onto the hung up device. It
 * ensures future writes will error and it does the needed line discipline
 * hangup and signal delivery. The tty object itself remains intact.
 *
 * Locking:
 *  * BTM
 *
 *   * redirect lock for undoing redirection
 *   * file list lock for manipulating list of ttys
 *   * tty_ldiscs_lock from called functions
 *   * termios_rwsem resetting termios data
 *   * tasklist_lock to walk task list for hangup event
 *
 *    * ->siglock to protect ->signal/->sighand
 *
 */
static void __tty_hangup(struct tty_struct *tty, int exit_session)
{
	struct file *cons_filp = NULL;
	struct file *filp, *f;
	struct tty_file_private *priv;
	int    closecount = 0, n;
	int refs;

	if (!tty)
		return;

	f = tty_release_redirect(tty);

	tty_lock(tty);

	if (test_bit(TTY_HUPPED, &tty->flags)) {
		tty_unlock(tty);
		return;
	}

	/*
	 * Some console devices aren't actually hung up for technical and
	 * historical reasons, which can lead to indefinite interruptible
	 * sleep in n_tty_read().  The following explicitly tells
	 * n_tty_read() to abort readers.
	 */
	set_bit(TTY_HUPPING, &tty->flags);

	/* inuse_filps is protected by the single tty lock,
	 * this really needs to change if we want to flush the
	 * workqueue with the lock held.
	 */
	check_tty_count(tty, "tty_hangup");

	spin_lock(&tty->files_lock);
	/* This breaks for file handles being sent over AF_UNIX sockets ? */
	list_for_each_entry(priv, &tty->tty_files, list) {
		filp = priv->file;
		if (filp->f_op->write_iter == redirected_tty_write)
			cons_filp = filp;
		if (filp->f_op->write_iter != tty_write)
			continue;
		closecount++;
		__tty_fasync(-1, filp, 0);	/* can't block */
		filp->f_op = &hung_up_tty_fops;
	}
	spin_unlock(&tty->files_lock);

	refs = tty_signal_session_leader(tty, exit_session);
	/* Account for the p->signal references we killed */
	while (refs--)
		tty_kref_put(tty);

	tty_ldisc_hangup(tty, cons_filp != NULL);

	spin_lock_irq(&tty->ctrl.lock);
	clear_bit(TTY_THROTTLED, &tty->flags);
	clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
	put_pid(tty->ctrl.session);
	put_pid(tty->ctrl.pgrp);
	tty->ctrl.session = NULL;
	tty->ctrl.pgrp = NULL;
	tty->ctrl.pktstatus = 0;
	spin_unlock_irq(&tty->ctrl.lock);

	/*
	 * If one of the devices matches a console pointer, we
	 * cannot just call hangup() because that will cause
	 * tty->count and state->count to go out of sync.
	 * So we just call close() the right number of times.
	 */
	if (cons_filp) {
		if (tty->ops->close)
			for (n = 0; n < closecount; n++)
				tty->ops->close(tty, cons_filp);
	} else if (tty->ops->hangup)
		tty->ops->hangup(tty);
	/*
	 * We don't want to have driver/ldisc interactions beyond the ones
	 * we did here. The driver layer expects no calls after ->hangup()
	 * from the ldisc side, which is now guaranteed.
	 */
	set_bit(TTY_HUPPED, &tty->flags);
	clear_bit(TTY_HUPPING, &tty->flags);
	tty_unlock(tty);

	if (f)
		fput(f);
}

static void do_tty_hangup(struct work_struct *work)
{
	struct tty_struct *tty =
		container_of(work, struct tty_struct, hangup_work);

	__tty_hangup(tty, 0);
}

/**
 * tty_hangup - trigger a hangup event
 * @tty: tty to hangup
 *
 * A carrier loss (virtual or otherwise) has occurred on @tty. Schedule a
 * hangup sequence to run after this event.
 */
void tty_hangup(struct tty_struct *tty)
{
	tty_debug_hangup(tty, "hangup\n");
	schedule_work(&tty->hangup_work);
}
EXPORT_SYMBOL(tty_hangup);

/**
 * tty_vhangup - process vhangup
 * @tty: tty to hangup
 *
 * The user has asked via system call for the terminal to be hung up. We do
 * this synchronously so that when the syscall returns the process is complete.
 * That guarantee is necessary for security reasons.
 */
void tty_vhangup(struct tty_struct *tty)
{
	tty_debug_hangup(tty, "vhangup\n");
	__tty_hangup(tty, 0);
}
EXPORT_SYMBOL(tty_vhangup);


/**
 * tty_vhangup_self - process vhangup for own ctty
 *
 * Perform a vhangup on the current controlling tty
 */
void tty_vhangup_self(void)
{
	struct tty_struct *tty;

	tty = get_current_tty();
	if (tty) {
		tty_vhangup(tty);
		tty_kref_put(tty);
	}
}

/**
 * tty_vhangup_session - hangup session leader exit
 * @tty: tty to hangup
 *
 * The session leader is exiting and hanging up its controlling terminal.
 * Every process in the foreground process group is signalled %SIGHUP.
 *
 * We do this synchronously so that when the syscall returns the process is
 * complete. That guarantee is necessary for security reasons.
 */
void tty_vhangup_session(struct tty_struct *tty)
{
	tty_debug_hangup(tty, "session hangup\n");
	__tty_hangup(tty, 1);
}

/**
 * tty_hung_up_p - was tty hung up
 * @filp: file pointer of tty
 *
 * Return: true if the tty has been subject to a vhangup or a carrier loss
 */
int tty_hung_up_p(struct file *filp)
{
	return (filp && filp->f_op == &hung_up_tty_fops);
}
EXPORT_SYMBOL(tty_hung_up_p);

void __stop_tty(struct tty_struct *tty)
{
	if (tty->flow.stopped)
		return;
	tty->flow.stopped = true;
	if (tty->ops->stop)
		tty->ops->stop(tty);
}

/**
 * stop_tty - propagate flow control
 * @tty: tty to stop
 *
 * Perform flow control to the driver. May be called on an already stopped
 * device and will not re-call the &tty_driver->stop() method.
 *
 * This functionality is used by both the line disciplines for halting incoming
 * flow and by the driver. It may therefore be called from any context, may be
 * under the tty %atomic_write_lock but not always.
 *
 * Locking:
 *	flow.lock
 */
void stop_tty(struct tty_struct *tty)
{
	guard(spinlock_irqsave)(&tty->flow.lock);
	__stop_tty(tty);
}
EXPORT_SYMBOL(stop_tty);

void __start_tty(struct tty_struct *tty)
{
	if (!tty->flow.stopped || tty->flow.tco_stopped)
		return;
	tty->flow.stopped = false;
	if (tty->ops->start)
		tty->ops->start(tty);
	tty_wakeup(tty);
}

/**
 * start_tty - propagate flow control
 * @tty: tty to start
 *
 * Start a tty that has been stopped if at all possible. If @tty was previously
 * stopped and is now being started, the &tty_driver->start() method is invoked
 * and the line discipline woken.
 *
 * Locking:
 *	flow.lock
 */
void start_tty(struct tty_struct *tty)
{
	guard(spinlock_irqsave)(&tty->flow.lock);
	__start_tty(tty);
}
EXPORT_SYMBOL(start_tty);

static void tty_update_time(struct tty_struct *tty, bool mtime)
{
	time64_t sec = ktime_get_real_seconds();
	struct tty_file_private *priv;

	guard(spinlock)(&tty->files_lock);

	list_for_each_entry(priv, &tty->tty_files, list) {
		struct inode *inode = file_inode(priv->file);
		struct timespec64 time = mtime ? inode_get_mtime(inode) : inode_get_atime(inode);

		/*
		 * We only care if the two values differ in anything other than the
		 * lower three bits (i.e every 8 seconds).  If so, then we can update
		 * the time of the tty device, otherwise it could be construded as a
		 * security leak to let userspace know the exact timing of the tty.
		 */
		if ((sec ^ time.tv_sec) & ~7) {
			if (mtime)
				inode_set_mtime(inode, sec, 0);
			else
				inode_set_atime(inode, sec, 0);
		}
	}
}

/*
 * Iterate on the ldisc ->read() function until we've gotten all
 * the data the ldisc has for us.
 *
 * The "cookie" is something that the ldisc read function can fill
 * in to let us know that there is more data to be had.
 *
 * We promise to continue to call the ldisc until it stops returning
 * data or clears the cookie. The cookie may be something that the
 * ldisc maintains state for and needs to free.
 */
static ssize_t iterate_tty_read(struct tty_ldisc *ld, struct tty_struct *tty,
				struct file *file, struct iov_iter *to)
{
	void *cookie = NULL;
	unsigned long offset = 0;
	ssize_t retval = 0;
	size_t copied, count = iov_iter_count(to);
	u8 kernel_buf[64];

	do {
		ssize_t size = min(count, sizeof(kernel_buf));

		size = ld->ops->read(tty, file, kernel_buf, size, &cookie, offset);
		if (!size)
			break;

		if (size < 0) {
			/* Did we have an earlier error (ie -EFAULT)? */
			if (retval)
				break;
			retval = size;

			/*
			 * -EOVERFLOW means we didn't have enough space
			 * for a whole packet, and we shouldn't return
			 * a partial result.
			 */
			if (retval == -EOVERFLOW)
				offset = 0;
			break;
		}

		copied = copy_to_iter(kernel_buf, size, to);
		offset += copied;
		count -= copied;

		/*
		 * If the user copy failed, we still need to do another ->read()
		 * call if we had a cookie to let the ldisc clear up.
		 *
		 * But make sure size is zeroed.
		 */
		if (unlikely(copied != size)) {
			count = 0;
			retval = -EFAULT;
		}
	} while (cookie);

	/* We always clear tty buffer in case they contained passwords */
	memzero_explicit(kernel_buf, sizeof(kernel_buf));
	return offset ? offset : retval;
}


/**
 * tty_read - read method for tty device files
 * @iocb: kernel I/O control block
 * @to: destination for the data read
 *
 * Perform the read system call function on this terminal device. Checks
 * for hung up devices before calling the line discipline method.
 *
 * Locking:
 *	Locks the line discipline internally while needed. Multiple read calls
 *	may be outstanding in parallel.
 */
static ssize_t tty_read(struct kiocb *iocb, struct iov_iter *to)
{
	struct file *file = iocb->ki_filp;
	struct inode *inode = file_inode(file);
	struct tty_struct *tty = file_tty(file);
	struct tty_ldisc *ld;
	ssize_t ret;

	if (tty_paranoia_check(tty, inode, "tty_read"))
		return -EIO;
	if (!tty || tty_io_error(tty))
		return -EIO;

	/* We want to wait for the line discipline to sort out in this
	 * situation.
	 */
	ld = tty_ldisc_ref_wait(tty);
	if (!ld)
		return hung_up_tty_read(iocb, to);
	ret = -EIO;
	if (ld->ops->read)
		ret = iterate_tty_read(ld, tty, file, to);
	tty_ldisc_deref(ld);

	if (ret > 0)
		tty_update_time(tty, false);

	return ret;
}

void tty_write_unlock(struct tty_struct *tty)
{
	mutex_unlock(&tty->atomic_write_lock);
	wake_up_interruptible_poll(&tty->write_wait, EPOLLOUT);
}

int tty_write_lock(struct tty_struct *tty, bool ndelay)
{
	if (!mutex_trylock(&tty->atomic_write_lock)) {
		if (ndelay)
			return -EAGAIN;
		if (mutex_lock_interruptible(&tty->atomic_write_lock))
			return -ERESTARTSYS;
	}
	return 0;
}

/*
 * Split writes up in sane blocksizes to avoid
 * denial-of-service type attacks
 */
static ssize_t iterate_tty_write(struct tty_ldisc *ld, struct tty_struct *tty,
				 struct file *file, struct iov_iter *from)
{
	size_t chunk, count = iov_iter_count(from);
	ssize_t ret, written = 0;

	ret = tty_write_lock(tty, file->f_flags & O_NDELAY);
	if (ret < 0)
		return ret;

	/*
	 * We chunk up writes into a temporary buffer. This
	 * simplifies low-level drivers immensely, since they
	 * don't have locking issues and user mode accesses.
	 *
	 * But if TTY_NO_WRITE_SPLIT is set, we should use a
	 * big chunk-size..
	 *
	 * The default chunk-size is 2kB, because the NTTY
	 * layer has problems with bigger chunks. It will
	 * claim to be able to handle more characters than
	 * it actually does.
	 */
	chunk = 2048;
	if (test_bit(TTY_NO_WRITE_SPLIT, &tty->flags))
		chunk = 65536;
	if (count < chunk)
		chunk = count;

	/* write_buf/write_cnt is protected by the atomic_write_lock mutex */
	if (tty->write_cnt < chunk) {
		u8 *buf_chunk;

		if (chunk < 1024)
			chunk = 1024;

		buf_chunk = kvmalloc(chunk, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
		if (!buf_chunk) {
			ret = -ENOMEM;
			goto out;
		}
		kvfree(tty->write_buf);
		tty->write_cnt = chunk;
		tty->write_buf = buf_chunk;
	}

	/* Do the write .. */
	for (;;) {
		size_t size = min(chunk, count);

		ret = -EFAULT;
		if (copy_from_iter(tty->write_buf, size, from) != size)
			break;

		ret = ld->ops->write(tty, file, tty->write_buf, size);
		if (ret <= 0)
			break;

		written += ret;
		if (ret > size)
			break;

		/* FIXME! Have Al check this! */
		if (ret != size)
			iov_iter_revert(from, size-ret);

		count -= ret;
		if (!count)
			break;
		ret = -ERESTARTSYS;
		if (signal_pending(current))
			break;
		cond_resched();
	}
	if (written) {
		tty_update_time(tty, true);
		ret = written;
	}
out:
	tty_write_unlock(tty);
	return ret;
}

#ifdef CONFIG_PRINT_QUOTA_WARNING
/**
 * tty_write_message - write a message to a certain tty, not just the console.
 * @tty: the destination tty_struct
 * @msg: the message to write
 *
 * This is used for messages that need to be redirected to a specific tty. We
 * don't put it into the syslog queue right now maybe in the future if really
 * needed.
 *
 * We must still hold the BTM and test the CLOSING flag for the moment.
 *
 * This function is DEPRECATED, do not use in new code.
 */
void tty_write_message(struct tty_struct *tty, char *msg)
{
	if (tty) {
		mutex_lock(&tty->atomic_write_lock);
		tty_lock(tty);
		if (tty->ops->write && tty->count > 0)
			tty->ops->write(tty, msg, strlen(msg));
		tty_unlock(tty);
		tty_write_unlock(tty);
	}
}
#endif

static ssize_t file_tty_write(struct file *file, struct kiocb *iocb, struct iov_iter *from)
{
	struct tty_struct *tty = file_tty(file);
	struct tty_ldisc *ld;
	ssize_t ret;

	if (tty_paranoia_check(tty, file_inode(file), "tty_write"))
		return -EIO;
	if (!tty || !tty->ops->write ||	tty_io_error(tty))
		return -EIO;
	/* Short term debug to catch buggy drivers */
	if (tty->ops->write_room == NULL)
		tty_err(tty, "missing write_room method\n");
	ld = tty_ldisc_ref_wait(tty);
	if (!ld)
		return hung_up_tty_write(iocb, from);
	if (!ld->ops->write)
		ret = -EIO;
	else
		ret = iterate_tty_write(ld, tty, file, from);
	tty_ldisc_deref(ld);
	return ret;
}

/**
 * tty_write - write method for tty device file
 * @iocb: kernel I/O control block
 * @from: iov_iter with data to write
 *
 * Write data to a tty device via the line discipline.
 *
 * Locking:
 *	Locks the line discipline as required
 *	Writes to the tty driver are serialized by the atomic_write_lock
 *	and are then processed in chunks to the device. The line
 *	discipline write method will not be invoked in parallel for
 *	each device.
 */
static ssize_t tty_write(struct kiocb *iocb, struct iov_iter *from)
{
	return file_tty_write(iocb->ki_filp, iocb, from);
}

ssize_t redirected_tty_write(struct kiocb *iocb, struct iov_iter *iter)
{
	struct file *p = NULL;

	spin_lock(&redirect_lock);
	if (redirect)
		p = get_file(redirect);
	spin_unlock(&redirect_lock);

	/*
	 * We know the redirected tty is just another tty, we can
	 * call file_tty_write() directly with that file pointer.
	 */
	if (p) {
		ssize_t res;

		res = file_tty_write(p, iocb, iter);
		fput(p);
		return res;
	}
	return tty_write(iocb, iter);
}

/**
 * tty_send_xchar - send priority character
 * @tty: the tty to send to
 * @ch: xchar to send
 *
 * Send a high priority character to the tty even if stopped.
 *
 * Locking: none for xchar method, write ordering for write method.
 */
int tty_send_xchar(struct tty_struct *tty, u8 ch)
{
	bool was_stopped = tty->flow.stopped;

	if (tty->ops->send_xchar) {
		down_read(&tty->termios_rwsem);
		tty->ops->send_xchar(tty, ch);
		up_read(&tty->termios_rwsem);
		return 0;
	}

	if (tty_write_lock(tty, false) < 0)
		return -ERESTARTSYS;

	down_read(&tty->termios_rwsem);
	if (was_stopped)
		start_tty(tty);
	tty->ops->write(tty, &ch, 1);
	if (was_stopped)
		stop_tty(tty);
	up_read(&tty->termios_rwsem);
	tty_write_unlock(tty);
	return 0;
}

/**
 * pty_line_name - generate name for a pty
 * @driver: the tty driver in use
 * @index: the minor number
 * @p: output buffer of at least 6 bytes
 *
 * Generate a name from a @driver reference and write it to the output buffer
 * @p.
 *
 * Locking: None
 */
static void pty_line_name(struct tty_driver *driver, int index, char *p)
{
	static const char ptychar[] = "pqrstuvwxyzabcde";
	int i = index + driver->name_base;
	/* ->name is initialized to "ttyp", but "tty" is expected */
	sprintf(p, "%s%c%x",
		driver->subtype == PTY_TYPE_SLAVE ? "tty" : driver->name,
		ptychar[i >> 4 & 0xf], i & 0xf);
}

/**
 * tty_line_name - generate name for a tty
 * @driver: the tty driver in use
 * @index: the minor number
 * @p: output buffer of at least 7 bytes
 *
 * Generate a name from a @driver reference and write it to the output buffer
 * @p.
 *
 * Locking: None
 */
static ssize_t tty_line_name(struct tty_driver *driver, int index, char *p)
{
	if (driver->flags & TTY_DRIVER_UNNUMBERED_NODE)
		return sprintf(p, "%s", driver->name);
	else
		return sprintf(p, "%s%d", driver->name,
			       index + driver->name_base);
}

/**
 * tty_driver_lookup_tty() - find an existing tty, if any
 * @driver: the driver for the tty
 * @file: file object
 * @idx: the minor number
 *
 * Return: the tty, if found. If not found, return %NULL or ERR_PTR() if the
 * driver lookup() method returns an error.
 *
 * Locking: tty_mutex must be held. If the tty is found, bump the tty kref.
 */
static struct tty_struct *tty_driver_lookup_tty(struct tty_driver *driver,
		struct file *file, int idx)
{
	struct tty_struct *tty;

	if (driver->ops->lookup) {
		if (!file)
			tty = ERR_PTR(-EIO);
		else
			tty = driver->ops->lookup(driver, file, idx);
	} else {
		if (idx >= driver->num)
			return ERR_PTR(-EINVAL);
		tty = driver->ttys[idx];
	}
	if (!IS_ERR(tty))
		tty_kref_get(tty);
	return tty;
}

/**
 * tty_init_termios - helper for termios setup
 * @tty: the tty to set up
 *
 * Initialise the termios structure for this tty. This runs under the
 * %tty_mutex currently so we can be relaxed about ordering.
 */
void tty_init_termios(struct tty_struct *tty)
{
	struct ktermios *tp;
	int idx = tty->index;

	if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
		tty->termios = tty->driver->init_termios;
	else {
		/* Check for lazy saved data */
		tp = tty->driver->termios[idx];
		if (tp != NULL) {
			tty->termios = *tp;
			tty->termios.c_line  = tty->driver->init_termios.c_line;
		} else
			tty->termios = tty->driver->init_termios;
	}
	/* Compatibility until drivers always set this */
	tty->termios.c_ispeed = tty_termios_input_baud_rate(&tty->termios);
	tty->termios.c_ospeed = tty_termios_baud_rate(&tty->termios);
}
EXPORT_SYMBOL_GPL(tty_init_termios);

/**
 * tty_standard_install - usual tty->ops->install
 * @driver: the driver for the tty
 * @tty: the tty
 *
 * If the @driver overrides @tty->ops->install, it still can call this function
 * to perform the standard install operations.
 */
int tty_standard_install(struct tty_driver *driver, struct tty_struct *tty)
{
	tty_init_termios(tty);
	tty_driver_kref_get(driver);
	tty->count++;
	driver->ttys[tty->index] = tty;
	return 0;
}
EXPORT_SYMBOL_GPL(tty_standard_install);

/**
 * tty_driver_install_tty() - install a tty entry in the driver
 * @driver: the driver for the tty
 * @tty: the tty
 *
 * Install a tty object into the driver tables. The @tty->index field will be
 * set by the time this is called. This method is responsible for ensuring any
 * need additional structures are allocated and configured.
 *
 * Locking: tty_mutex for now
 */
static int tty_driver_install_tty(struct tty_driver *driver,
						struct tty_struct *tty)
{
	return driver->ops->install ? driver->ops->install(driver, tty) :
		tty_standard_install(driver, tty);
}

/**
 * tty_driver_remove_tty() - remove a tty from the driver tables
 * @driver: the driver for the tty
 * @tty: tty to remove
 *
 * Remove a tty object from the driver tables. The tty->index field will be set
 * by the time this is called.
 *
 * Locking: tty_mutex for now
 */
static void tty_driver_remove_tty(struct tty_driver *driver, struct tty_struct *tty)
{
	if (driver->ops->remove)
		driver->ops->remove(driver, tty);
	else
		driver->ttys[tty->index] = NULL;
}

/**
 * tty_reopen() - fast re-open of an open tty
 * @tty: the tty to open
 *
 * Re-opens on master ptys are not allowed and return -%EIO.
 *
 * Locking: Caller must hold tty_lock
 * Return: 0 on success, -errno on error.
 */
static int tty_reopen(struct tty_struct *tty)
{
	struct tty_driver *driver = tty->driver;
	struct tty_ldisc *ld;
	int retval = 0;

	if (driver->type == TTY_DRIVER_TYPE_PTY &&
	    driver->subtype == PTY_TYPE_MASTER)
		return -EIO;

	if (!tty->count)
		return -EAGAIN;

	if (test_bit(TTY_EXCLUSIVE, &tty->flags) && !capable(CAP_SYS_ADMIN))
		return -EBUSY;

	ld = tty_ldisc_ref_wait(tty);
	if (ld) {
		tty_ldisc_deref(ld);
	} else {
		retval = tty_ldisc_lock(tty, 5 * HZ);
		if (retval)
			return retval;

		if (!tty->ldisc)
			retval = tty_ldisc_reinit(tty, tty->termios.c_line);
		tty_ldisc_unlock(tty);
	}

	if (retval == 0)
		tty->count++;

	return retval;
}

/**
 * tty_init_dev - initialise a tty device
 * @driver: tty driver we are opening a device on
 * @idx: device index
 *
 * Prepare a tty device. This may not be a "new" clean device but could also be
 * an active device. The pty drivers require special handling because of this.
 *
 * Locking:
 *	The function is called under the tty_mutex, which protects us from the
 *	tty struct or driver itself going away.
 *
 * On exit the tty device has the line discipline attached and a reference
 * count of 1. If a pair was created for pty/tty use and the other was a pty
 * master then it too has a reference count of 1.
 *
 * WSH 06/09/97: Rewritten to remove races and properly clean up after a failed
 * open. The new code protects the open with a mutex, so it's really quite
 * straightforward. The mutex locking can probably be relaxed for the (most
 * common) case of reopening a tty.
 *
 * Return: new tty structure
 */
struct tty_struct *tty_init_dev(struct tty_driver *driver, int idx)
{
	struct tty_struct *tty;
	int retval;

	/*
	 * First time open is complex, especially for PTY devices.
	 * This code guarantees that either everything succeeds and the
	 * TTY is ready for operation, or else the table slots are vacated
	 * and the allocated memory released.  (Except that the termios
	 * may be retained.)
	 */

	if (!try_module_get(driver->owner))
		return ERR_PTR(-ENODEV);

	tty = alloc_tty_struct(driver, idx);
	if (!tty) {
		retval = -ENOMEM;
		goto err_module_put;
	}

	tty_lock(tty);
	retval = tty_driver_install_tty(driver, tty);
	if (retval < 0)
		goto err_free_tty;

	if (!tty->port)
		tty->port = driver->ports[idx];

	if (WARN_RATELIMIT(!tty->port,
			"%s: %s driver does not set tty->port. This would crash the kernel. Fix the driver!\n",
			__func__, tty->driver->name)) {
		retval = -EINVAL;
		goto err_release_lock;
	}

	retval = tty_ldisc_lock(tty, 5 * HZ);
	if (retval)
		goto err_release_lock;
	tty->port->itty = tty;

	/*
	 * Structures all installed ... call the ldisc open routines.
	 * If we fail here just call release_tty to clean up.  No need
	 * to decrement the use counts, as release_tty doesn't care.
	 */
	retval = tty_ldisc_setup(tty, tty->link);
	if (retval)
		goto err_release_tty;
	tty_ldisc_unlock(tty);
	/* Return the tty locked so that it cannot vanish under the caller */
	return tty;

err_free_tty:
	tty_unlock(tty);
	free_tty_struct(tty);
err_module_put:
	module_put(driver->owner);
	return ERR_PTR(retval);

	/* call the tty release_tty routine to clean out this slot */
err_release_tty:
	tty_ldisc_unlock(tty);
	tty_info_ratelimited(tty, "ldisc open failed (%d), clearing slot %d\n",
			     retval, idx);
err_release_lock:
	tty_unlock(tty);
	release_tty(tty, idx);
	return ERR_PTR(retval);
}

/**
 * tty_save_termios() - save tty termios data in driver table
 * @tty: tty whose termios data to save
 *
 * Locking: Caller guarantees serialisation with tty_init_termios().
 */
void tty_save_termios(struct tty_struct *tty)
{
	struct ktermios *tp;
	int idx = tty->index;

	/* If the port is going to reset then it has no termios to save */
	if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
		return;

	/* Stash the termios data */
	tp = tty->driver->termios[idx];
	if (tp == NULL) {
		tp = kmalloc(sizeof(*tp), GFP_KERNEL);
		if (tp == NULL)
			return;
		tty->driver->termios[idx] = tp;
	}
	*tp = tty->termios;
}
EXPORT_SYMBOL_GPL(tty_save_termios);

/**
 * tty_flush_works - flush all works of a tty/pty pair
 * @tty: tty device to flush works for (or either end of a pty pair)
 *
 * Sync flush all works belonging to @tty (and the 'other' tty).
 */
static void tty_flush_works(struct tty_struct *tty)
{
	flush_work(&tty->SAK_work);
	flush_work(&tty->hangup_work);
	if (tty->link) {
		flush_work(&tty->link->SAK_work);
		flush_work(&tty->link->hangup_work);
	}
}

/**
 * release_one_tty - release tty structure memory
 * @work: work of tty we are obliterating
 *
 * Releases memory associated with a tty structure, and clears out the
 * driver table slots. This function is called when a device is no longer
 * in use. It also gets called when setup of a device fails.
 *
 * Locking:
 *	takes the file list lock internally when working on the list of ttys
 *	that the driver keeps.
 *
 * This method gets called from a work queue so that the driver private
 * cleanup ops can sleep (needed for USB at least)
 */
static void release_one_tty(struct work_struct *work)
{
	struct tty_struct *tty =
		container_of(work, struct tty_struct, hangup_work);
	struct tty_driver *driver = tty->driver;
	struct module *owner = driver->owner;

	if (tty->ops->cleanup)
		tty->ops->cleanup(tty);

	tty_driver_kref_put(driver);
	module_put(owner);

	spin_lock(&tty->files_lock);
	list_del_init(&tty->tty_files);
	spin_unlock(&tty->files_lock);

	put_pid(tty->ctrl.pgrp);
	put_pid(tty->ctrl.session);
	free_tty_struct(tty);
}

static void queue_release_one_tty(struct kref *kref)
{
	struct tty_struct *tty = container_of(kref, struct tty_struct, kref);

	/* The hangup queue is now free so we can reuse it rather than
	 *  waste a chunk of memory for each port.
	 */
	INIT_WORK(&tty->hangup_work, release_one_tty);
	schedule_work(&tty->hangup_work);
}

/**
 * tty_kref_put - release a tty kref
 * @tty: tty device
 *
 * Release a reference to the @tty device and if need be let the kref layer
 * destruct the object for us.
 */
void tty_kref_put(struct tty_struct *tty)
{
	if (tty)
		kref_put(&tty->kref, queue_release_one_tty);
}
EXPORT_SYMBOL(tty_kref_put);

/**
 * release_tty - release tty structure memory
 * @tty: tty device release
 * @idx: index of the tty device release
 *
 * Release both @tty and a possible linked partner (think pty pair),
 * and decrement the refcount of the backing module.
 *
 * Locking:
 *	tty_mutex
 *	takes the file list lock internally when working on the list of ttys
 *	that the driver keeps.
 */
static void release_tty(struct tty_struct *tty, int idx)
{
	/* This should always be true but check for the moment */
	WARN_ON(tty->index != idx);
	WARN_ON(!mutex_is_locked(&tty_mutex));
	if (tty->ops->shutdown)
		tty->ops->shutdown(tty);
	tty_save_termios(tty);
	tty_driver_remove_tty(tty->driver, tty);
	if (tty->port)
		tty->port->itty = NULL;
	if (tty->link)
		tty->link->port->itty = NULL;
	if (tty->port)
		tty_buffer_cancel_work(tty->port);
	if (tty->link)
		tty_buffer_cancel_work(tty->link->port);

	tty_kref_put(tty->link);
	tty_kref_put(tty);
}

/**
 * tty_release_checks - check a tty before real release
 * @tty: tty to check
 * @idx: index of the tty
 *
 * Performs some paranoid checking before true release of the @tty. This is a
 * no-op unless %TTY_PARANOIA_CHECK is defined.
 */
static int tty_release_checks(struct tty_struct *tty, int idx)
{
#ifdef TTY_PARANOIA_CHECK
	if (idx < 0 || idx >= tty->driver->num) {
		tty_debug(tty, "bad idx %d\n", idx);
		return -1;
	}

	/* not much to check for devpts */
	if (tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)
		return 0;

	if (tty != tty->driver->ttys[idx]) {
		tty_debug(tty, "bad driver table[%d] = %p\n",
			  idx, tty->driver->ttys[idx]);
		return -1;
	}
	if (tty->driver->other) {
		struct tty_struct *o_tty = tty->link;

		if (o_tty != tty->driver->other->ttys[idx]) {
			tty_debug(tty, "bad other table[%d] = %p\n",
				  idx, tty->driver->other->ttys[idx]);
			return -1;
		}
		if (o_tty->link != tty) {
			tty_debug(tty, "bad link = %p\n", o_tty->link);
			return -1;
		}
	}
#endif
	return 0;
}

/**
 * tty_kclose - closes tty opened by tty_kopen
 * @tty: tty device
 *
 * Performs the final steps to release and free a tty device. It is the same as
 * tty_release_struct() except that it also resets %TTY_PORT_KOPENED flag on
 * @tty->port.
 */
void tty_kclose(struct tty_struct *tty)
{
	/*
	 * Ask the line discipline code to release its structures
	 */
	tty_ldisc_release(tty);

	/* Wait for pending work before tty destruction commences */
	tty_flush_works(tty);

	tty_debug_hangup(tty, "freeing structure\n");
	/*
	 * The release_tty function takes care of the details of clearing
	 * the slots and preserving the termios structure.
	 */
	mutex_lock(&tty_mutex);
	tty_port_set_kopened(tty->port, 0);
	release_tty(tty, tty->index);
	mutex_unlock(&tty_mutex);
}
EXPORT_SYMBOL_GPL(tty_kclose);

/**
 * tty_release_struct - release a tty struct
 * @tty: tty device
 * @idx: index of the tty
 *
 * Performs the final steps to release and free a tty device. It is roughly the
 * reverse of tty_init_dev().
 */
void tty_release_struct(struct tty_struct *tty, int idx)
{
	/*
	 * Ask the line discipline code to release its structures
	 */
	tty_ldisc_release(tty);

	/* Wait for pending work before tty destruction commmences */
	tty_flush_works(tty);

	tty_debug_hangup(tty, "freeing structure\n");
	/*
	 * The release_tty function takes care of the details of clearing
	 * the slots and preserving the termios structure.
	 */
	mutex_lock(&tty_mutex);
	release_tty(tty, idx);
	mutex_unlock(&tty_mutex);
}
EXPORT_SYMBOL_GPL(tty_release_struct);

/**
 * tty_release - vfs callback for close
 * @inode: inode of tty
 * @filp: file pointer for handle to tty
 *
 * Called the last time each file handle is closed that references this tty.
 * There may however be several such references.
 *
 * Locking:
 *	Takes BKL. See tty_release_dev().
 *
 * Even releasing the tty structures is a tricky business. We have to be very
 * careful that the structures are all released at the same time, as interrupts
 * might otherwise get the wrong pointers.
 *
 * WSH 09/09/97: rewritten to avoid some nasty race conditions that could
 * lead to double frees or releasing memory still in use.
 */
int tty_release(struct inode *inode, struct file *filp)
{
	struct tty_struct *tty = file_tty(filp);
	struct tty_struct *o_tty = NULL;
	int	do_sleep, final;
	int	idx;
	long	timeout = 0;
	int	once = 1;

	if (tty_paranoia_check(tty, inode, __func__))
		return 0;

	tty_lock(tty);
	check_tty_count(tty, __func__);

	__tty_fasync(-1, filp, 0);

	idx = tty->index;
	if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
	    tty->driver->subtype == PTY_TYPE_MASTER)
		o_tty = tty->link;

	if (tty_release_checks(tty, idx)) {
		tty_unlock(tty);
		return 0;
	}

	tty_debug_hangup(tty, "releasing (count=%d)\n", tty->count);

	if (tty->ops->close)
		tty->ops->close(tty, filp);

	/* If tty is pty master, lock the slave pty (stable lock order) */
	tty_lock_slave(o_tty);

	/*
	 * Sanity check: if tty->count is going to zero, there shouldn't be
	 * any waiters on tty->read_wait or tty->write_wait.  We test the
	 * wait queues and kick everyone out _before_ actually starting to
	 * close.  This ensures that we won't block while releasing the tty
	 * structure.
	 *
	 * The test for the o_tty closing is necessary, since the master and
	 * slave sides may close in any order.  If the slave side closes out
	 * first, its count will be one, since the master side holds an open.
	 * Thus this test wouldn't be triggered at the time the slave closed,
	 * so we do it now.
	 */
	while (1) {
		do_sleep = 0;

		if (tty->count <= 1) {
			if (waitqueue_active(&tty->read_wait)) {
				wake_up_poll(&tty->read_wait, EPOLLIN);
				do_sleep++;
			}
			if (waitqueue_active(&tty->write_wait)) {
				wake_up_poll(&tty->write_wait, EPOLLOUT);
				do_sleep++;
			}
		}
		if (o_tty && o_tty->count <= 1) {
			if (waitqueue_active(&o_tty->read_wait)) {
				wake_up_poll(&o_tty->read_wait, EPOLLIN);
				do_sleep++;
			}
			if (waitqueue_active(&o_tty->write_wait)) {
				wake_up_poll(&o_tty->write_wait, EPOLLOUT);
				do_sleep++;
			}
		}
		if (!do_sleep)
			break;

		if (once) {
			once = 0;
			tty_warn(tty, "read/write wait queue active!\n");
		}
		schedule_timeout_killable(timeout);
		if (timeout < 120 * HZ)
			timeout = 2 * timeout + 1;
		else
			timeout = MAX_SCHEDULE_TIMEOUT;
	}

	if (o_tty) {
		if (--o_tty->count < 0) {
			tty_warn(tty, "bad slave count (%d)\n", o_tty->count);
			o_tty->count = 0;
		}
	}
	if (--tty->count < 0) {
		tty_warn(tty, "bad tty->count (%d)\n", tty->count);
		tty->count = 0;
	}

	/*
	 * We've decremented tty->count, so we need to remove this file
	 * descriptor off the tty->tty_files list; this serves two
	 * purposes:
	 *  - check_tty_count sees the correct number of file descriptors
	 *    associated with this tty.
	 *  - do_tty_hangup no longer sees this file descriptor as
	 *    something that needs to be handled for hangups.
	 */
	tty_del_file(filp);

	/*
	 * Perform some housekeeping before deciding whether to return.
	 *
	 * If _either_ side is closing, make sure there aren't any
	 * processes that still think tty or o_tty is their controlling
	 * tty.
	 */
	if (!tty->count) {
		read_lock(&tasklist_lock);
		session_clear_tty(tty->ctrl.session);
		if (o_tty)
			session_clear_tty(o_tty->ctrl.session);
		read_unlock(&tasklist_lock);
	}

	/* check whether both sides are closing ... */
	final = !tty->count && !(o_tty && o_tty->count);

	tty_unlock_slave(o_tty);
	tty_unlock(tty);

	/* At this point, the tty->count == 0 should ensure a dead tty
	 * cannot be re-opened by a racing opener.
	 */

	if (!final)
		return 0;

	tty_debug_hangup(tty, "final close\n");

	tty_release_struct(tty, idx);
	return 0;
}

/**
 * tty_open_current_tty - get locked tty of current task
 * @device: device number
 * @filp: file pointer to tty
 * @return: locked tty of the current task iff @device is /dev/tty
 *
 * Performs a re-open of the current task's controlling tty.
 *
 * We cannot return driver and index like for the other nodes because devpts
 * will not work then. It expects inodes to be from devpts FS.
 */
static struct tty_struct *tty_open_current_tty(dev_t device, struct file *filp)
{
	struct tty_struct *tty;
	int retval;

	if (device != MKDEV(TTYAUX_MAJOR, 0))
		return NULL;

	tty = get_current_tty();
	if (!tty)
		return ERR_PTR(-ENXIO);

	filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
	/* noctty = 1; */
	tty_lock(tty);
	tty_kref_put(tty);	/* safe to drop the kref now */

	retval = tty_reopen(tty);
	if (retval < 0) {
		tty_unlock(tty);
		tty = ERR_PTR(retval);
	}
	return tty;
}

/**
 * tty_lookup_driver - lookup a tty driver for a given device file
 * @device: device number
 * @filp: file pointer to tty
 * @index: index for the device in the @return driver
 *
 * If returned value is not erroneous, the caller is responsible to decrement
 * the refcount by tty_driver_kref_put().
 *
 * Locking: %tty_mutex protects get_tty_driver()
 *
 * Return: driver for this inode (with increased refcount)
 */
static struct tty_driver *tty_lookup_driver(dev_t device, struct file *filp,
		int *index)
{
	struct tty_driver *driver = NULL;

	switch (device) {
#ifdef CONFIG_VT
	case MKDEV(TTY_MAJOR, 0): {
		extern struct tty_driver *console_driver;

		driver = tty_driver_kref_get(console_driver);
		*index = fg_console;
		break;
	}
#endif
	case MKDEV(TTYAUX_MAJOR, 1): {
		struct tty_driver *console_driver = console_device(index);

		if (console_driver) {
			driver = tty_driver_kref_get(console_driver);
			if (driver && filp) {
				/* Don't let /dev/console block */
				filp->f_flags |= O_NONBLOCK;
				break;
			}
		}
		if (driver)
			tty_driver_kref_put(driver);
		return ERR_PTR(-ENODEV);
	}
	default:
		driver = get_tty_driver(device, index);
		if (!driver)
			return ERR_PTR(-ENODEV);
		break;
	}
	return driver;
}

static struct tty_struct *tty_kopen(dev_t device, int shared)
{
	struct tty_struct *tty;
	struct tty_driver *driver;
	int index = -1;

	mutex_lock(&tty_mutex);
	driver = tty_lookup_driver(device, NULL, &index);
	if (IS_ERR(driver)) {
		mutex_unlock(&tty_mutex);
		return ERR_CAST(driver);
	}

	/* check whether we're reopening an existing tty */
	tty = tty_driver_lookup_tty(driver, NULL, index);
	if (IS_ERR(tty) || shared)
		goto out;

	if (tty) {
		/* drop kref from tty_driver_lookup_tty() */
		tty_kref_put(tty);
		tty = ERR_PTR(-EBUSY);
	} else { /* tty_init_dev returns tty with the tty_lock held */
		tty = tty_init_dev(driver, index);
		if (IS_ERR(tty))
			goto out;
		tty_port_set_kopened(tty->port, 1);
	}
out:
	mutex_unlock(&tty_mutex);
	tty_driver_kref_put(driver);
	return tty;
}

/**
 * tty_kopen_exclusive - open a tty device for kernel
 * @device: dev_t of device to open
 *
 * Opens tty exclusively for kernel. Performs the driver lookup, makes sure
 * it's not already opened and performs the first-time tty initialization.
 *
 * Claims the global %tty_mutex to serialize:
 *  * concurrent first-time tty initialization
 *  * concurrent tty driver removal w/ lookup
 *  * concurrent tty removal from driver table
 *
 * Return: the locked initialized &tty_struct
 */
struct tty_struct *tty_kopen_exclusive(dev_t device)
{
	return tty_kopen(device, 0);
}
EXPORT_SYMBOL_GPL(tty_kopen_exclusive);

/**
 * tty_kopen_shared - open a tty device for shared in-kernel use
 * @device: dev_t of device to open
 *
 * Opens an already existing tty for in-kernel use. Compared to
 * tty_kopen_exclusive() above it doesn't ensure to be the only user.
 *
 * Locking: identical to tty_kopen() above.
 */
struct tty_struct *tty_kopen_shared(dev_t device)
{
	return tty_kopen(device, 1);
}
EXPORT_SYMBOL_GPL(tty_kopen_shared);

/**
 * tty_open_by_driver - open a tty device
 * @device: dev_t of device to open
 * @filp: file pointer to tty
 *
 * Performs the driver lookup, checks for a reopen, or otherwise performs the
 * first-time tty initialization.
 *
 *
 * Claims the global tty_mutex to serialize:
 *  * concurrent first-time tty initialization
 *  * concurrent tty driver removal w/ lookup
 *  * concurrent tty removal from driver table
 *
 * Return: the locked initialized or re-opened &tty_struct
 */
static struct tty_struct *tty_open_by_driver(dev_t device,
					     struct file *filp)
{
	struct tty_struct *tty;
	struct tty_driver *driver = NULL;
	int index = -1;
	int retval;

	mutex_lock(&tty_mutex);
	driver = tty_lookup_driver(device, filp, &index);
	if (IS_ERR(driver)) {
		mutex_unlock(&tty_mutex);
		return ERR_CAST(driver);
	}

	/* check whether we're reopening an existing tty */
	tty = tty_driver_lookup_tty(driver, filp, index);
	if (IS_ERR(tty)) {
		mutex_unlock(&tty_mutex);
		goto out;
	}

	if (tty) {
		if (tty_port_kopened(tty->port)) {
			tty_kref_put(tty);
			mutex_unlock(&tty_mutex);
			tty = ERR_PTR(-EBUSY);
			goto out;
		}
		mutex_unlock(&tty_mutex);
		retval = tty_lock_interruptible(tty);
		tty_kref_put(tty);  /* drop kref from tty_driver_lookup_tty() */
		if (retval) {
			if (retval == -EINTR)
				retval = -ERESTARTSYS;
			tty = ERR_PTR(retval);
			goto out;
		}
		retval = tty_reopen(tty);
		if (retval < 0) {
			tty_unlock(tty);
			tty = ERR_PTR(retval);
		}
	} else { /* Returns with the tty_lock held for now */
		tty = tty_init_dev(driver, index);
		mutex_unlock(&tty_mutex);
	}
out:
	tty_driver_kref_put(driver);
	return tty;
}

/**
 * tty_open - open a tty device
 * @inode: inode of device file
 * @filp: file pointer to tty
 *
 * tty_open() and tty_release() keep up the tty count that contains the number
 * of opens done on a tty. We cannot use the inode-count, as different inodes
 * might point to the same tty.
 *
 * Open-counting is needed for pty masters, as well as for keeping track of
 * serial lines: DTR is dropped when the last close happens.
 * (This is not done solely through tty->count, now.  - Ted 1/27/92)
 *
 * The termios state of a pty is reset on the first open so that settings don't
 * persist across reuse.
 *
 * Locking:
 *  * %tty_mutex protects tty, tty_lookup_driver() and tty_init_dev().
 *  * @tty->count should protect the rest.
 *  * ->siglock protects ->signal/->sighand
 *
 * Note: the tty_unlock/lock cases without a ref are only safe due to %tty_mutex
 */
static int tty_open(struct inode *inode, struct file *filp)
{
	struct tty_struct *tty;
	int noctty, retval;
	dev_t device = inode->i_rdev;
	unsigned saved_flags = filp->f_flags;

	nonseekable_open(inode, filp);

retry_open:
	retval = tty_alloc_file(filp);
	if (retval)
		return -ENOMEM;

	tty = tty_open_current_tty(device, filp);
	if (!tty)
		tty = tty_open_by_driver(device, filp);

	if (IS_ERR(tty)) {
		tty_free_file(filp);
		retval = PTR_ERR(tty);
		if (retval != -EAGAIN || signal_pending(current))
			return retval;
		schedule();
		goto retry_open;
	}

	tty_add_file(tty, filp);

	check_tty_count(tty, __func__);
	tty_debug_hangup(tty, "opening (count=%d)\n", tty->count);

	if (tty->ops->open)
		retval = tty->ops->open(tty, filp);
	else
		retval = -ENODEV;
	filp->f_flags = saved_flags;

	if (retval) {
		tty_debug_hangup(tty, "open error %d, releasing\n", retval);

		tty_unlock(tty); /* need to call tty_release without BTM */
		tty_release(inode, filp);
		if (retval != -ERESTARTSYS)
			return retval;

		if (signal_pending(current))
			return retval;

		schedule();
		/*
		 * Need to reset f_op in case a hangup happened.
		 */
		if (tty_hung_up_p(filp))
			filp->f_op = &tty_fops;
		goto retry_open;
	}
	clear_bit(TTY_HUPPED, &tty->flags);

	noctty = (filp->f_flags & O_NOCTTY) ||
		 (IS_ENABLED(CONFIG_VT) && device == MKDEV(TTY_MAJOR, 0)) ||
		 device == MKDEV(TTYAUX_MAJOR, 1) ||
		 (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
		  tty->driver->subtype == PTY_TYPE_MASTER);
	if (!noctty)
		tty_open_proc_set_tty(filp, tty);
	tty_unlock(tty);
	return 0;
}


/**
 * tty_poll - check tty status
 * @filp: file being polled
 * @wait: poll wait structures to update
 *
 * Call the line discipline polling method to obtain the poll status of the
 * device.
 *
 * Locking: locks called line discipline but ldisc poll method may be
 * re-entered freely by other callers.
 */
static __poll_t tty_poll(struct file *filp, poll_table *wait)
{
	struct tty_struct *tty = file_tty(filp);
	struct tty_ldisc *ld;
	__poll_t ret = 0;

	if (tty_paranoia_check(tty, file_inode(filp), "tty_poll"))
		return 0;

	ld = tty_ldisc_ref_wait(tty);
	if (!ld)
		return hung_up_tty_poll(filp, wait);
	if (ld->ops->poll)
		ret = ld->ops->poll(tty, filp, wait);
	tty_ldisc_deref(ld);
	return ret;
}

static int __tty_fasync(int fd, struct file *filp, int on)
{
	struct tty_struct *tty = file_tty(filp);
	unsigned long flags;
	int retval = 0;

	if (tty_paranoia_check(tty, file_inode(filp), "tty_fasync"))
		goto out;

	if (on) {
		retval = file_f_owner_allocate(filp);
		if (retval)
			goto out;
	}

	retval = fasync_helper(fd, filp, on, &tty->fasync);
	if (retval <= 0)
		goto out;

	if (on) {
		enum pid_type type;
		struct pid *pid;

		spin_lock_irqsave(&tty->ctrl.lock, flags);
		if (tty->ctrl.pgrp) {
			pid = tty->ctrl.pgrp;
			type = PIDTYPE_PGID;
		} else {
			pid = task_pid(current);
			type = PIDTYPE_TGID;
		}
		get_pid(pid);
		spin_unlock_irqrestore(&tty->ctrl.lock, flags);
		__f_setown(filp, pid, type, 0);
		put_pid(pid);
		retval = 0;
	}
out:
	return retval;
}

static int tty_fasync(int fd, struct file *filp, int on)
{
	struct tty_struct *tty = file_tty(filp);
	int retval = -ENOTTY;

	tty_lock(tty);
	if (!tty_hung_up_p(filp))
		retval = __tty_fasync(fd, filp, on);
	tty_unlock(tty);

	return retval;
}

static bool tty_legacy_tiocsti __read_mostly = IS_ENABLED(CONFIG_LEGACY_TIOCSTI);
/**
 * tiocsti - fake input character
 * @tty: tty to fake input into
 * @p: pointer to character
 *
 * Fake input to a tty device. Does the necessary locking and input management.
 *
 * FIXME: does not honour flow control ??
 *
 * Locking:
 *  * Called functions take tty_ldiscs_lock
 *  * current->signal->tty check is safe without locks
 */
static int tiocsti(struct tty_struct *tty, u8 __user *p)
{
	struct tty_ldisc *ld;
	u8 ch;

	if (!tty_legacy_tiocsti && !capable(CAP_SYS_ADMIN))
		return -EIO;

	if ((current->signal->tty != tty) && !capable(CAP_SYS_ADMIN))
		return -EPERM;
	if (get_user(ch, p))
		return -EFAULT;
	tty_audit_tiocsti(tty, ch);
	ld = tty_ldisc_ref_wait(tty);
	if (!ld)
		return -EIO;
	tty_buffer_lock_exclusive(tty->port);
	if (ld->ops->receive_buf)
		ld->ops->receive_buf(tty, &ch, NULL, 1);
	tty_buffer_unlock_exclusive(tty->port);
	tty_ldisc_deref(ld);
	return 0;
}

/**
 * tiocgwinsz - implement window query ioctl
 * @tty: tty
 * @arg: user buffer for result
 *
 * Copies the kernel idea of the window size into the user buffer.
 *
 * Locking: @tty->winsize_mutex is taken to ensure the winsize data is
 * consistent.
 */
static int tiocgwinsz(struct tty_struct *tty, struct winsize __user *arg)
{
	guard(mutex)(&tty->winsize_mutex);

	if (copy_to_user(arg, &tty->winsize, sizeof(*arg)))
		return -EFAULT;

	return 0;
}

/**
 * tty_do_resize - resize event
 * @tty: tty being resized
 * @ws: new dimensions
 *
 * Update the termios variables and send the necessary signals to peform a
 * terminal resize correctly.
 */
int tty_do_resize(struct tty_struct *tty, struct winsize *ws)
{
	struct pid *pgrp;

	guard(mutex)(&tty->winsize_mutex);

	if (!memcmp(ws, &tty->winsize, sizeof(*ws)))
		return 0;

	/* Signal the foreground process group */
	pgrp = tty_get_pgrp(tty);
	if (pgrp)
		kill_pgrp(pgrp, SIGWINCH, 1);
	put_pid(pgrp);

	tty->winsize = *ws;

	return 0;
}
EXPORT_SYMBOL(tty_do_resize);

/**
 * tiocswinsz - implement window size set ioctl
 * @tty: tty side of tty
 * @arg: user buffer for result
 *
 * Copies the user idea of the window size to the kernel. Traditionally this is
 * just advisory information but for the Linux console it actually has driver
 * level meaning and triggers a VC resize.
 *
 * Locking:
 *	Driver dependent. The default do_resize method takes the tty termios
 *	mutex and ctrl.lock. The console takes its own lock then calls into the
 *	default method.
 */
static int tiocswinsz(struct tty_struct *tty, struct winsize __user *arg)
{
	struct winsize tmp_ws;

	if (copy_from_user(&tmp_ws, arg, sizeof(*arg)))
		return -EFAULT;

	if (tty->ops->resize)
		return tty->ops->resize(tty, &tmp_ws);
	else
		return tty_do_resize(tty, &tmp_ws);
}

/**
 * tioccons - allow admin to move logical console
 * @file: the file to become console
 *
 * Allow the administrator to move the redirected console device.
 *
 * Locking: uses redirect_lock to guard the redirect information
 */
static int tioccons(struct file *file)
{
	if (!capable(CAP_SYS_ADMIN))
		return -EPERM;
	if (file->f_op->write_iter == redirected_tty_write) {
		struct file *f;

		spin_lock(&redirect_lock);
		f = redirect;
		redirect = NULL;
		spin_unlock(&redirect_lock);
		if (f)
			fput(f);
		return 0;
	}
	if (file->f_op->write_iter != tty_write)
		return -ENOTTY;
	if (!(file->f_mode & FMODE_WRITE))
		return -EBADF;
	if (!(file->f_mode & FMODE_CAN_WRITE))
		return -EINVAL;

	guard(spinlock)(&redirect_lock);

	if (redirect)
		return -EBUSY;

	redirect = get_file(file);

	return 0;
}

/**
 * tiocsetd - set line discipline
 * @tty: tty device
 * @p: pointer to user data
 *
 * Set the line discipline according to user request.
 *
 * Locking: see tty_set_ldisc(), this function is just a helper
 */
static int tiocsetd(struct tty_struct *tty, int __user *p)
{
	int disc;
	int ret;

	if (get_user(disc, p))
		return -EFAULT;

	ret = tty_set_ldisc(tty, disc);

	return ret;
}

/**
 * tiocgetd - get line discipline
 * @tty: tty device
 * @p: pointer to user data
 *
 * Retrieves the line discipline id directly from the ldisc.
 *
 * Locking: waits for ldisc reference (in case the line discipline is changing
 * or the @tty is being hungup)
 */
static int tiocgetd(struct tty_struct *tty, int __user *p)
{
	struct tty_ldisc *ld;
	int ret;

	ld = tty_ldisc_ref_wait(tty);
	if (!ld)
		return -EIO;
	ret = put_user(ld->ops->num, p);
	tty_ldisc_deref(ld);
	return ret;
}

/**
 * send_break - performed time break
 * @tty: device to break on
 * @duration: timeout in mS
 *
 * Perform a timed break on hardware that lacks its own driver level timed
 * break functionality.
 *
 * Locking:
 *	@tty->atomic_write_lock serializes
 */
static int send_break(struct tty_struct *tty, unsigned int duration)
{
	int retval;

	if (tty->ops->break_ctl == NULL)
		return 0;

	if (tty->driver->flags & TTY_DRIVER_HARDWARE_BREAK)
		return tty->ops->break_ctl(tty, duration);

	/* Do the work ourselves */
	if (tty_write_lock(tty, false) < 0)
		return -EINTR;

	retval = tty->ops->break_ctl(tty, -1);
	if (!retval) {
		msleep_interruptible(duration);
		retval = tty->ops->break_ctl(tty, 0);
	} else if (retval == -EOPNOTSUPP) {
		/* some drivers can tell only dynamically */
		retval = 0;
	}
	tty_write_unlock(tty);

	if (signal_pending(current))
		retval = -EINTR;

	return retval;
}

/**
 * tty_get_tiocm - get tiocm status register
 * @tty: tty device
 *
 * Obtain the modem status bits from the tty driver if the feature
 * is supported.
 */
int tty_get_tiocm(struct tty_struct *tty)
{
	int retval = -ENOTTY;

	if (tty->ops->tiocmget)
		retval = tty->ops->tiocmget(tty);

	return retval;
}
EXPORT_SYMBOL_GPL(tty_get_tiocm);

/**
 * tty_tiocmget - get modem status
 * @tty: tty device
 * @p: pointer to result
 *
 * Obtain the modem status bits from the tty driver if the feature is
 * supported. Return -%ENOTTY if it is not available.
 *
 * Locking: none (up to the driver)
 */
static int tty_tiocmget(struct tty_struct *tty, int __user *p)
{
	int retval;

	retval = tty_get_tiocm(tty);
	if (retval >= 0)
		retval = put_user(retval, p);

	return retval;
}

/**
 * tty_tiocmset - set modem status
 * @tty: tty device
 * @cmd: command - clear bits, set bits or set all
 * @p: pointer to desired bits
 *
 * Set the modem status bits from the tty driver if the feature
 * is supported. Return -%ENOTTY if it is not available.
 *
 * Locking: none (up to the driver)
 */
static int tty_tiocmset(struct tty_struct *tty, unsigned int cmd,
	     unsigned __user *p)
{
	int retval;
	unsigned int set, clear, val;

	if (tty->ops->tiocmset == NULL)
		return -ENOTTY;

	retval = get_user(val, p);
	if (retval)
		return retval;
	set = clear = 0;
	switch (cmd) {
	case TIOCMBIS:
		set = val;
		break;
	case TIOCMBIC:
		clear = val;
		break;
	case TIOCMSET:
		set = val;
		clear = ~val;
		break;
	}
	set &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
	clear &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
	return tty->ops->tiocmset(tty, set, clear);
}

/**
 * tty_get_icount - get tty statistics
 * @tty: tty device
 * @icount: output parameter
 *
 * Gets a copy of the @tty's icount statistics.
 *
 * Locking: none (up to the driver)
 */
int tty_get_icount(struct tty_struct *tty,
		   struct serial_icounter_struct *icount)
{
	memset(icount, 0, sizeof(*icount));

	if (tty->ops->get_icount)
		return tty->ops->get_icount(tty, icount);
	else
		return -ENOTTY;
}
EXPORT_SYMBOL_GPL(tty_get_icount);

static int tty_tiocgicount(struct tty_struct *tty, void __user *arg)
{
	struct serial_icounter_struct icount;
	int retval;

	retval = tty_get_icount(tty, &icount);
	if (retval != 0)
		return retval;

	if (copy_to_user(arg, &icount, sizeof(icount)))
		return -EFAULT;
	return 0;
}

static int tty_set_serial(struct tty_struct *tty, struct serial_struct *ss)
{
	int flags;

	flags = ss->flags & ASYNC_DEPRECATED;

	if (flags)
		pr_warn_ratelimited("%s: '%s' is using deprecated serial flags (with no effect): %.8x\n",
				__func__, current->comm, flags);

	if (!tty->ops->set_serial)
		return -ENOTTY;

	return tty->ops->set_serial(tty, ss);
}

static int tty_tiocsserial(struct tty_struct *tty, struct serial_struct __user *ss)
{
	struct serial_struct v;

	if (copy_from_user(&v, ss, sizeof(*ss)))
		return -EFAULT;

	return tty_set_serial(tty, &v);
}

static int tty_tiocgserial(struct tty_struct *tty, struct serial_struct __user *ss)
{
	struct serial_struct v;
	int err;

	memset(&v, 0, sizeof(v));
	if (!tty->ops->get_serial)
		return -ENOTTY;
	err = tty->ops->get_serial(tty, &v);
	if (!err && copy_to_user(ss, &v, sizeof(v)))
		err = -EFAULT;
	return err;
}

/*
 * if pty, return the slave side (real_tty)
 * otherwise, return self
 */
static struct tty_struct *tty_pair_get_tty(struct tty_struct *tty)
{
	if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
	    tty->driver->subtype == PTY_TYPE_MASTER)
		tty = tty->link;
	return tty;
}

/*
 * Split this up, as gcc can choke on it otherwise..
 */
long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
	struct tty_struct *tty = file_tty(file);
	struct tty_struct *real_tty;
	void __user *p = (void __user *)arg;
	int retval;
	struct tty_ldisc *ld;

	if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
		return -EINVAL;

	real_tty = tty_pair_get_tty(tty);

	/*
	 * Factor out some common prep work
	 */
	switch (cmd) {
	case TIOCSETD:
	case TIOCSBRK:
	case TIOCCBRK:
	case TCSBRK:
	case TCSBRKP:
		retval = tty_check_change(tty);
		if (retval)
			return retval;
		if (cmd != TIOCCBRK) {
			tty_wait_until_sent(tty, 0);
			if (signal_pending(current))
				return -EINTR;
		}
		break;
	}

	/*
	 *	Now do the stuff.
	 */
	switch (cmd) {
	case TIOCSTI:
		return tiocsti(tty, p);
	case TIOCGWINSZ:
		return tiocgwinsz(real_tty, p);
	case TIOCSWINSZ:
		return tiocswinsz(real_tty, p);
	case TIOCCONS:
		return real_tty != tty ? -EINVAL : tioccons(file);
	case TIOCEXCL:
		set_bit(TTY_EXCLUSIVE, &tty->flags);
		return 0;
	case TIOCNXCL:
		clear_bit(TTY_EXCLUSIVE, &tty->flags);
		return 0;
	case TIOCGEXCL:
	{
		int excl = test_bit(TTY_EXCLUSIVE, &tty->flags);

		return put_user(excl, (int __user *)p);
	}
	case TIOCGETD:
		return tiocgetd(tty, p);
	case TIOCSETD:
		return tiocsetd(tty, p);
	case TIOCVHANGUP:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		tty_vhangup(tty);
		return 0;
	case TIOCGDEV:
	{
		unsigned int ret = new_encode_dev(tty_devnum(real_tty));

		return put_user(ret, (unsigned int __user *)p);
	}
	/*
	 * Break handling
	 */
	case TIOCSBRK:	/* Turn break on, unconditionally */
		if (tty->ops->break_ctl)
			return tty->ops->break_ctl(tty, -1);
		return 0;
	case TIOCCBRK:	/* Turn break off, unconditionally */
		if (tty->ops->break_ctl)
			return tty->ops->break_ctl(tty, 0);
		return 0;
	case TCSBRK:   /* SVID version: non-zero arg --> no break */
		/* non-zero arg means wait for all output data
		 * to be sent (performed above) but don't send break.
		 * This is used by the tcdrain() termios function.
		 */
		if (!arg)
			return send_break(tty, 250);
		return 0;
	case TCSBRKP:	/* support for POSIX tcsendbreak() */
		return send_break(tty, arg ? arg*100 : 250);

	case TIOCMGET:
		return tty_tiocmget(tty, p);
	case TIOCMSET:
	case TIOCMBIC:
	case TIOCMBIS:
		return tty_tiocmset(tty, cmd, p);
	case TIOCGICOUNT:
		return tty_tiocgicount(tty, p);
	case TCFLSH:
		switch (arg) {
		case TCIFLUSH:
		case TCIOFLUSH:
		/* flush tty buffer and allow ldisc to process ioctl */
			tty_buffer_flush(tty, NULL);
			break;
		}
		break;
	case TIOCSSERIAL:
		return tty_tiocsserial(tty, p);
	case TIOCGSERIAL:
		return tty_tiocgserial(tty, p);
	case TIOCGPTPEER:
		/* Special because the struct file is needed */
		return ptm_open_peer(file, tty, (int)arg);
	default:
		retval = tty_jobctrl_ioctl(tty, real_tty, file, cmd, arg);
		if (retval != -ENOIOCTLCMD)
			return retval;
	}
	if (tty->ops->ioctl) {
		retval = tty->ops->ioctl(tty, cmd, arg);
		if (retval != -ENOIOCTLCMD)
			return retval;
	}
	ld = tty_ldisc_ref_wait(tty);
	if (!ld)
		return hung_up_tty_ioctl(file, cmd, arg);
	retval = -EINVAL;
	if (ld->ops->ioctl) {
		retval = ld->ops->ioctl(tty, cmd, arg);
		if (retval == -ENOIOCTLCMD)
			retval = -ENOTTY;
	}
	tty_ldisc_deref(ld);
	return retval;
}

#ifdef CONFIG_COMPAT

struct serial_struct32 {
	compat_int_t    type;
	compat_int_t    line;
	compat_uint_t   port;
	compat_int_t    irq;
	compat_int_t    flags;
	compat_int_t    xmit_fifo_size;
	compat_int_t    custom_divisor;
	compat_int_t    baud_base;
	unsigned short  close_delay;
	char    io_type;
	char    reserved_char;
	compat_int_t    hub6;
	unsigned short  closing_wait; /* time to wait before closing */
	unsigned short  closing_wait2; /* no longer used... */
	compat_uint_t   iomem_base;
	unsigned short  iomem_reg_shift;
	unsigned int    port_high;
	/* compat_ulong_t  iomap_base FIXME */
	compat_int_t    reserved;
};

static int compat_tty_tiocsserial(struct tty_struct *tty,
		struct serial_struct32 __user *ss)
{
	struct serial_struct32 v32;
	struct serial_struct v;

	if (copy_from_user(&v32, ss, sizeof(*ss)))
		return -EFAULT;

	memcpy(&v, &v32, offsetof(struct serial_struct32, iomem_base));
	v.iomem_base = compat_ptr(v32.iomem_base);
	v.iomem_reg_shift = v32.iomem_reg_shift;
	v.port_high = v32.port_high;
	v.iomap_base = 0;

	return tty_set_serial(tty, &v);
}

static int compat_tty_tiocgserial(struct tty_struct *tty,
			struct serial_struct32 __user *ss)
{
	struct serial_struct32 v32;
	struct serial_struct v;
	int err;

	memset(&v, 0, sizeof(v));
	memset(&v32, 0, sizeof(v32));

	if (!tty->ops->get_serial)
		return -ENOTTY;
	err = tty->ops->get_serial(tty, &v);
	if (!err) {
		memcpy(&v32, &v, offsetof(struct serial_struct32, iomem_base));
		v32.iomem_base = (unsigned long)v.iomem_base >> 32 ?
			0xfffffff : ptr_to_compat(v.iomem_base);
		v32.iomem_reg_shift = v.iomem_reg_shift;
		v32.port_high = v.port_high;
		if (copy_to_user(ss, &v32, sizeof(v32)))
			err = -EFAULT;
	}
	return err;
}
static long tty_compat_ioctl(struct file *file, unsigned int cmd,
				unsigned long arg)
{
	struct tty_struct *tty = file_tty(file);
	struct tty_ldisc *ld;
	int retval = -ENOIOCTLCMD;

	switch (cmd) {
	case TIOCOUTQ:
	case TIOCSTI:
	case TIOCGWINSZ:
	case TIOCSWINSZ:
	case TIOCGEXCL:
	case TIOCGETD:
	case TIOCSETD:
	case TIOCGDEV:
	case TIOCMGET:
	case TIOCMSET:
	case TIOCMBIC:
	case TIOCMBIS:
	case TIOCGICOUNT:
	case TIOCGPGRP:
	case TIOCSPGRP:
	case TIOCGSID:
	case TIOCSERGETLSR:
	case TIOCGRS485:
	case TIOCSRS485:
#ifdef TIOCGETP
	case TIOCGETP:
	case TIOCSETP:
	case TIOCSETN:
#endif
#ifdef TIOCGETC
	case TIOCGETC:
	case TIOCSETC:
#endif
#ifdef TIOCGLTC
	case TIOCGLTC:
	case TIOCSLTC:
#endif
	case TCSETSF:
	case TCSETSW:
	case TCSETS:
	case TCGETS:
#ifdef TCGETS2
	case TCGETS2:
	case TCSETSF2:
	case TCSETSW2:
	case TCSETS2:
#endif
	case TCGETA:
	case TCSETAF:
	case TCSETAW:
	case TCSETA:
	case TIOCGLCKTRMIOS:
	case TIOCSLCKTRMIOS:
#ifdef TCGETX
	case TCGETX:
	case TCSETX:
	case TCSETXW:
	case TCSETXF:
#endif
	case TIOCGSOFTCAR:
	case TIOCSSOFTCAR:

	case PPPIOCGCHAN:
	case PPPIOCGUNIT:
		return tty_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
	case TIOCCONS:
	case TIOCEXCL:
	case TIOCNXCL:
	case TIOCVHANGUP:
	case TIOCSBRK:
	case TIOCCBRK:
	case TCSBRK:
	case TCSBRKP:
	case TCFLSH:
	case TIOCGPTPEER:
	case TIOCNOTTY:
	case TIOCSCTTY:
	case TCXONC:
	case TIOCMIWAIT:
	case TIOCSERCONFIG:
		return tty_ioctl(file, cmd, arg);
	}

	if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
		return -EINVAL;

	switch (cmd) {
	case TIOCSSERIAL:
		return compat_tty_tiocsserial(tty, compat_ptr(arg));
	case TIOCGSERIAL:
		return compat_tty_tiocgserial(tty, compat_ptr(arg));
	}
	if (tty->ops->compat_ioctl) {
		retval = tty->ops->compat_ioctl(tty, cmd, arg);
		if (retval != -ENOIOCTLCMD)
			return retval;
	}

	ld = tty_ldisc_ref_wait(tty);
	if (!ld)
		return hung_up_tty_compat_ioctl(file, cmd, arg);
	if (ld->ops->compat_ioctl)
		retval = ld->ops->compat_ioctl(tty, cmd, arg);
	if (retval == -ENOIOCTLCMD && ld->ops->ioctl)
		retval = ld->ops->ioctl(tty, (unsigned long)compat_ptr(cmd),
				arg);
	tty_ldisc_deref(ld);

	return retval;
}
#endif

static int this_tty(const void *t, struct file *file, unsigned fd)
{
	if (likely(file->f_op->read_iter != tty_read))
		return 0;
	return file_tty(file) != t ? 0 : fd + 1;
}

/*
 * This implements the "Secure Attention Key" ---  the idea is to
 * prevent trojan horses by killing all processes associated with this
 * tty when the user hits the "Secure Attention Key".  Required for
 * super-paranoid applications --- see the Orange Book for more details.
 *
 * This code could be nicer; ideally it should send a HUP, wait a few
 * seconds, then send a INT, and then a KILL signal.  But you then
 * have to coordinate with the init process, since all processes associated
 * with the current tty must be dead before the new getty is allowed
 * to spawn.
 *
 * Now, if it would be correct ;-/ The current code has a nasty hole -
 * it doesn't catch files in flight. We may send the descriptor to ourselves
 * via AF_UNIX socket, close it and later fetch from socket. FIXME.
 *
 * Nasty bug: do_SAK is being called in interrupt context.  This can
 * deadlock.  We punt it up to process context.  AKPM - 16Mar2001
 */
void __do_SAK(struct tty_struct *tty)
{
	struct task_struct *g, *p;
	struct pid *session;
	int i;

	scoped_guard(spinlock_irqsave, &tty->ctrl.lock)
		session = get_pid(tty->ctrl.session);

	tty_ldisc_flush(tty);

	tty_driver_flush_buffer(tty);

	read_lock(&tasklist_lock);
	/* Kill the entire session */
	do_each_pid_task(session, PIDTYPE_SID, p) {
		tty_notice(tty, "SAK: killed process %d (%s): by session\n",
			   task_pid_nr(p), p->comm);
		group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);
	} while_each_pid_task(session, PIDTYPE_SID, p);

	/* Now kill any processes that happen to have the tty open */
	for_each_process_thread(g, p) {
		if (p->signal->tty == tty) {
			tty_notice(tty, "SAK: killed process %d (%s): by controlling tty\n",
				   task_pid_nr(p), p->comm);
			group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p,
					PIDTYPE_SID);
			continue;
		}
		guard(task_lock)(p);
		i = iterate_fd(p->files, 0, this_tty, tty);
		if (i != 0) {
			tty_notice(tty, "SAK: killed process %d (%s): by fd#%d\n",
				   task_pid_nr(p), p->comm, i - 1);
			group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p,
					PIDTYPE_SID);
		}
	}
	read_unlock(&tasklist_lock);
	put_pid(session);
}

static void do_SAK_work(struct work_struct *work)
{
	struct tty_struct *tty =
		container_of(work, struct tty_struct, SAK_work);
	__do_SAK(tty);
}

/*
 * The tq handling here is a little racy - tty->SAK_work may already be queued.
 * Fortunately we don't need to worry, because if ->SAK_work is already queued,
 * the values which we write to it will be identical to the values which it
 * already has. --akpm
 */
void do_SAK(struct tty_struct *tty)
{
	if (!tty)
		return;
	schedule_work(&tty->SAK_work);
}
EXPORT_SYMBOL(do_SAK);

/* Must put_device() after it's unused! */
static struct device *tty_get_device(struct tty_struct *tty)
{
	dev_t devt = tty_devnum(tty);

	return class_find_device_by_devt(&tty_class, devt);
}


/**
 * alloc_tty_struct - allocate a new tty
 * @driver: driver which will handle the returned tty
 * @idx: minor of the tty
 *
 * This subroutine allocates and initializes a tty structure.
 *
 * Locking: none - @tty in question is not exposed at this point
 */
struct tty_struct *alloc_tty_struct(struct tty_driver *driver, int idx)
{
	struct tty_struct *tty;

	tty = kzalloc(sizeof(*tty), GFP_KERNEL_ACCOUNT);
	if (!tty)
		return NULL;

	kref_init(&tty->kref);
	if (tty_ldisc_init(tty)) {
		kfree(tty);
		return NULL;
	}
	tty->ctrl.session = NULL;
	tty->ctrl.pgrp = NULL;
	mutex_init(&tty->legacy_mutex);
	mutex_init(&tty->throttle_mutex);
	init_rwsem(&tty->termios_rwsem);
	mutex_init(&tty->winsize_mutex);
	init_ldsem(&tty->ldisc_sem);
	init_waitqueue_head(&tty->write_wait);
	init_waitqueue_head(&tty->read_wait);
	INIT_WORK(&tty->hangup_work, do_tty_hangup);
	mutex_init(&tty->atomic_write_lock);
	spin_lock_init(&tty->ctrl.lock);
	spin_lock_init(&tty->flow.lock);
	spin_lock_init(&tty->files_lock);
	INIT_LIST_HEAD(&tty->tty_files);
	INIT_WORK(&tty->SAK_work, do_SAK_work);

	tty->driver = driver;
	tty->ops = driver->ops;
	tty->index = idx;
	tty_line_name(driver, idx, tty->name);
	tty->dev = tty_get_device(tty);

	return tty;
}

/**
 * tty_put_char - write one character to a tty
 * @tty: tty
 * @ch: character to write
 *
 * Write one byte to the @tty using the provided @tty->ops->put_char() method
 * if present.
 *
 * Note: the specific put_char operation in the driver layer may go
 * away soon. Don't call it directly, use this method
 *
 * Return: the number of characters successfully output.
 */
int tty_put_char(struct tty_struct *tty, u8 ch)
{
	if (tty->ops->put_char)
		return tty->ops->put_char(tty, ch);
	return tty->ops->write(tty, &ch, 1);
}
EXPORT_SYMBOL_GPL(tty_put_char);

static int tty_cdev_add(struct tty_driver *driver, dev_t dev,
		unsigned int index, unsigned int count)
{
	int err;

	/* init here, since reused cdevs cause crashes */
	driver->cdevs[index] = cdev_alloc();
	if (!driver->cdevs[index])
		return -ENOMEM;
	driver->cdevs[index]->ops = &tty_fops;
	driver->cdevs[index]->owner = driver->owner;
	err = cdev_add(driver->cdevs[index], dev, count);
	if (err)
		kobject_put(&driver->cdevs[index]->kobj);
	return err;
}

/**
 * tty_register_device - register a tty device
 * @driver: the tty driver that describes the tty device
 * @index: the index in the tty driver for this tty device
 * @device: a struct device that is associated with this tty device.
 *	This field is optional, if there is no known struct device
 *	for this tty device it can be set to NULL safely.
 *
 * This call is required to be made to register an individual tty device
 * if the tty driver's flags have the %TTY_DRIVER_DYNAMIC_DEV bit set.  If
 * that bit is not set, this function should not be called by a tty
 * driver.
 *
 * Locking: ??
 *
 * Return: A pointer to the struct device for this tty device (or
 * ERR_PTR(-EFOO) on error).
 */
struct device *tty_register_device(struct tty_driver *driver, unsigned index,
				   struct device *device)
{
	return tty_register_device_attr(driver, index, device, NULL, NULL);
}
EXPORT_SYMBOL(tty_register_device);

static void tty_device_create_release(struct device *dev)
{
	dev_dbg(dev, "releasing...\n");
	kfree(dev);
}

/**
 * tty_register_device_attr - register a tty device
 * @driver: the tty driver that describes the tty device
 * @index: the index in the tty driver for this tty device
 * @device: a struct device that is associated with this tty device.
 *	This field is optional, if there is no known struct device
 *	for this tty device it can be set to %NULL safely.
 * @drvdata: Driver data to be set to device.
 * @attr_grp: Attribute group to be set on device.
 *
 * This call is required to be made to register an individual tty device if the
 * tty driver's flags have the %TTY_DRIVER_DYNAMIC_DEV bit set. If that bit is
 * not set, this function should not be called by a tty driver.
 *
 * Locking: ??
 *
 * Return: A pointer to the struct device for this tty device (or
 * ERR_PTR(-EFOO) on error).
 */
struct device *tty_register_device_attr(struct tty_driver *driver,
				   unsigned index, struct device *device,
				   void *drvdata,
				   const struct attribute_group **attr_grp)
{
	char name[64];
	dev_t devt = MKDEV(driver->major, driver->minor_start) + index;
	struct ktermios *tp;
	struct device *dev;
	int retval;

	if (index >= driver->num) {
		pr_err("%s: Attempt to register invalid tty line number (%d)\n",
		       driver->name, index);
		return ERR_PTR(-EINVAL);
	}

	if (driver->type == TTY_DRIVER_TYPE_PTY)
		pty_line_name(driver, index, name);
	else
		tty_line_name(driver, index, name);

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (!dev)
		return ERR_PTR(-ENOMEM);

	dev->devt = devt;
	dev->class = &tty_class;
	dev->parent = device;
	dev->release = tty_device_create_release;
	dev_set_name(dev, "%s", name);
	dev->groups = attr_grp;
	dev_set_drvdata(dev, drvdata);

	dev_set_uevent_suppress(dev, 1);

	retval = device_register(dev);
	if (retval)
		goto err_put;

	if (!(driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
		/*
		 * Free any saved termios data so that the termios state is
		 * reset when reusing a minor number.
		 */
		tp = driver->termios[index];
		if (tp) {
			driver->termios[index] = NULL;
			kfree(tp);
		}

		retval = tty_cdev_add(driver, devt, index, 1);
		if (retval)
			goto err_del;
	}

	dev_set_uevent_suppress(dev, 0);
	kobject_uevent(&dev->kobj, KOBJ_ADD);

	return dev;

err_del:
	device_del(dev);
err_put:
	put_device(dev);

	return ERR_PTR(retval);
}
EXPORT_SYMBOL_GPL(tty_register_device_attr);

/**
 * tty_unregister_device - unregister a tty device
 * @driver: the tty driver that describes the tty device
 * @index: the index in the tty driver for this tty device
 *
 * If a tty device is registered with a call to tty_register_device() then
 * this function must be called when the tty device is gone.
 *
 * Locking: ??
 */
void tty_unregister_device(struct tty_driver *driver, unsigned index)
{
	device_destroy(&tty_class, MKDEV(driver->major, driver->minor_start) + index);
	if (!(driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
		cdev_del(driver->cdevs[index]);
		driver->cdevs[index] = NULL;
	}
}
EXPORT_SYMBOL(tty_unregister_device);

/**
 * __tty_alloc_driver - allocate tty driver
 * @lines: count of lines this driver can handle at most
 * @owner: module which is responsible for this driver
 * @flags: some of enum tty_driver_flag, will be set in driver->flags
 *
 * This should not be called directly, tty_alloc_driver() should be used
 * instead.
 *
 * Returns: struct tty_driver or a PTR-encoded error (use IS_ERR() and friends).
 */
struct tty_driver *__tty_alloc_driver(unsigned int lines, struct module *owner,
		unsigned long flags)
{
	struct tty_driver *driver;
	unsigned int cdevs = 1;
	int err;

	if (!lines || (flags & TTY_DRIVER_UNNUMBERED_NODE && lines > 1))
		return ERR_PTR(-EINVAL);

	driver = kzalloc(sizeof(*driver), GFP_KERNEL);
	if (!driver)
		return ERR_PTR(-ENOMEM);

	kref_init(&driver->kref);
	driver->num = lines;
	driver->owner = owner;
	driver->flags = flags;

	if (!(flags & TTY_DRIVER_DEVPTS_MEM)) {
		driver->ttys = kcalloc(lines, sizeof(*driver->ttys),
				GFP_KERNEL);
		driver->termios = kcalloc(lines, sizeof(*driver->termios),
				GFP_KERNEL);
		if (!driver->ttys || !driver->termios) {
			err = -ENOMEM;
			goto err_free_all;
		}
	}

	if (!(flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
		driver->ports = kcalloc(lines, sizeof(*driver->ports),
				GFP_KERNEL);
		if (!driver->ports) {
			err = -ENOMEM;
			goto err_free_all;
		}
		cdevs = lines;
	}

	driver->cdevs = kcalloc(cdevs, sizeof(*driver->cdevs), GFP_KERNEL);
	if (!driver->cdevs) {
		err = -ENOMEM;
		goto err_free_all;
	}

	return driver;
err_free_all:
	kfree(driver->ports);
	kfree(driver->ttys);
	kfree(driver->termios);
	kfree(driver->cdevs);
	kfree(driver);
	return ERR_PTR(err);
}
EXPORT_SYMBOL(__tty_alloc_driver);

static void destruct_tty_driver(struct kref *kref)
{
	struct tty_driver *driver = container_of(kref, struct tty_driver, kref);
	int i;
	struct ktermios *tp;

	if (driver->flags & TTY_DRIVER_INSTALLED) {
		for (i = 0; i < driver->num; i++) {
			tp = driver->termios[i];
			if (tp) {
				driver->termios[i] = NULL;
				kfree(tp);
			}
			if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV))
				tty_unregister_device(driver, i);
		}
		proc_tty_unregister_driver(driver);
		if (driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)
			cdev_del(driver->cdevs[0]);
	}
	kfree(driver->cdevs);
	kfree(driver->ports);
	kfree(driver->termios);
	kfree(driver->ttys);
	kfree(driver);
}

/**
 * tty_driver_kref_put - drop a reference to a tty driver
 * @driver: driver of which to drop the reference
 *
 * The final put will destroy and free up the driver.
 */
void tty_driver_kref_put(struct tty_driver *driver)
{
	kref_put(&driver->kref, destruct_tty_driver);
}
EXPORT_SYMBOL(tty_driver_kref_put);

/**
 * tty_register_driver - register a tty driver
 * @driver: driver to register
 *
 * Called by a tty driver to register itself.
 */
int tty_register_driver(struct tty_driver *driver)
{
	int error;
	int i;
	dev_t dev;
	struct device *d;

	if (!driver->major) {
		error = alloc_chrdev_region(&dev, driver->minor_start,
						driver->num, driver->name);
		if (!error) {
			driver->major = MAJOR(dev);
			driver->minor_start = MINOR(dev);
		}
	} else {
		dev = MKDEV(driver->major, driver->minor_start);
		error = register_chrdev_region(dev, driver->num, driver->name);
	}
	if (error < 0)
		goto err;

	if (driver->flags & TTY_DRIVER_DYNAMIC_ALLOC) {
		error = tty_cdev_add(driver, dev, 0, driver->num);
		if (error)
			goto err_unreg_char;
	}

	scoped_guard(mutex, &tty_mutex)
		list_add(&driver->tty_drivers, &tty_drivers);

	if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV)) {
		for (i = 0; i < driver->num; i++) {
			d = tty_register_device(driver, i, NULL);
			if (IS_ERR(d)) {
				error = PTR_ERR(d);
				goto err_unreg_devs;
			}
		}
	}
	proc_tty_register_driver(driver);
	driver->flags |= TTY_DRIVER_INSTALLED;
	return 0;

err_unreg_devs:
	for (i--; i >= 0; i--)
		tty_unregister_device(driver, i);

	scoped_guard(mutex, &tty_mutex)
		list_del(&driver->tty_drivers);

err_unreg_char:
	unregister_chrdev_region(dev, driver->num);
err:
	return error;
}
EXPORT_SYMBOL(tty_register_driver);

/**
 * tty_unregister_driver - unregister a tty driver
 * @driver: driver to unregister
 *
 * Called by a tty driver to unregister itself.
 */
void tty_unregister_driver(struct tty_driver *driver)
{
	unregister_chrdev_region(MKDEV(driver->major, driver->minor_start),
				driver->num);
	scoped_guard(mutex, &tty_mutex)
		list_del(&driver->tty_drivers);
}
EXPORT_SYMBOL(tty_unregister_driver);

dev_t tty_devnum(struct tty_struct *tty)
{
	return MKDEV(tty->driver->major, tty->driver->minor_start) + tty->index;
}
EXPORT_SYMBOL(tty_devnum);

void tty_default_fops(struct file_operations *fops)
{
	*fops = tty_fops;
}

static char *tty_devnode(const struct device *dev, umode_t *mode)
{
	if (!mode)
		return NULL;
	if (dev->devt == MKDEV(TTYAUX_MAJOR, 0) ||
	    dev->devt == MKDEV(TTYAUX_MAJOR, 2))
		*mode = 0666;
	return NULL;
}

const struct class tty_class = {
	.name		= "tty",
	.devnode	= tty_devnode,
};

static int __init tty_class_init(void)
{
	return class_register(&tty_class);
}

postcore_initcall(tty_class_init);

/* 3/2004 jmc: why do these devices exist? */
static struct cdev tty_cdev, console_cdev;

static ssize_t show_cons_active(struct device *dev,
				struct device_attribute *attr, char *buf)
{
	struct console *cs[16];
	int i = 0;
	struct console *c;
	ssize_t count = 0;

	/*
	 * Hold the console_list_lock to guarantee that no consoles are
	 * unregistered until all console processing is complete.
	 * This also allows safe traversal of the console list and
	 * race-free reading of @flags.
	 */
	console_list_lock();

	for_each_console(c) {
		if (!c->device)
			continue;
		if (!(c->flags & CON_NBCON) && !c->write)
			continue;
		if ((c->flags & CON_ENABLED) == 0)
			continue;
		cs[i++] = c;
		if (i >= ARRAY_SIZE(cs))
			break;
	}

	/*
	 * Take console_lock to serialize device() callback with
	 * other console operations. For example, fg_console is
	 * modified under console_lock when switching vt.
	 */
	console_lock();
	while (i--) {
		int index = cs[i]->index;
		struct tty_driver *drv = cs[i]->device(cs[i], &index);

		/* don't resolve tty0 as some programs depend on it */
		if (drv && (cs[i]->index > 0 || drv->major != TTY_MAJOR))
			count += tty_line_name(drv, index, buf + count);
		else
			count += sprintf(buf + count, "%s%d",
					 cs[i]->name, cs[i]->index);

		count += sprintf(buf + count, "%c", i ? ' ':'\n');
	}
	console_unlock();

	console_list_unlock();

	return count;
}
static DEVICE_ATTR(active, S_IRUGO, show_cons_active, NULL);

static struct attribute *cons_dev_attrs[] = {
	&dev_attr_active.attr,
	NULL
};

ATTRIBUTE_GROUPS(cons_dev);

static struct device *consdev;

void console_sysfs_notify(void)
{
	if (consdev)
		sysfs_notify(&consdev->kobj, NULL, "active");
}

static const struct ctl_table tty_table[] = {
	{
		.procname	= "legacy_tiocsti",
		.data		= &tty_legacy_tiocsti,
		.maxlen		= sizeof(tty_legacy_tiocsti),
		.mode		= 0644,
		.proc_handler	= proc_dobool,
	},
	{
		.procname	= "ldisc_autoload",
		.data		= &tty_ldisc_autoload,
		.maxlen		= sizeof(tty_ldisc_autoload),
		.mode		= 0644,
		.proc_handler	= proc_dointvec_minmax,
		.extra1		= SYSCTL_ZERO,
		.extra2		= SYSCTL_ONE,
	},
};

/*
 * Ok, now we can initialize the rest of the tty devices and can count
 * on memory allocations, interrupts etc..
 */
int __init tty_init(void)
{
	register_sysctl_init("dev/tty", tty_table);
	cdev_init(&tty_cdev, &tty_fops);
	if (cdev_add(&tty_cdev, MKDEV(TTYAUX_MAJOR, 0), 1) ||
	    register_chrdev_region(MKDEV(TTYAUX_MAJOR, 0), 1, "/dev/tty") < 0)
		panic("Couldn't register /dev/tty driver\n");
	device_create(&tty_class, NULL, MKDEV(TTYAUX_MAJOR, 0), NULL, "tty");

	cdev_init(&console_cdev, &console_fops);
	if (cdev_add(&console_cdev, MKDEV(TTYAUX_MAJOR, 1), 1) ||
	    register_chrdev_region(MKDEV(TTYAUX_MAJOR, 1), 1, "/dev/console") < 0)
		panic("Couldn't register /dev/console driver\n");
	consdev = device_create_with_groups(&tty_class, NULL,
					    MKDEV(TTYAUX_MAJOR, 1), NULL,
					    cons_dev_groups, "console");
	if (IS_ERR(consdev))
		consdev = NULL;

#ifdef CONFIG_VT
	vty_init(&console_fops);
#endif
	return 0;
}
]

7/2 2026/03/09 22:45 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 47965
							output: 41
							thoughts: 119
						

Thoughts:
Okay, here's my breakdown of what's going on, thinking through this code:

**Analyzing the TTY Flow Control Race**

Alright, so we've got a potential race condition here. The key players are `__stop_tty` and `pty_write`. My initial instinct is to dig into `__stop_tty` first. Looking at the code for `__stop_tty`, it appears straightforward. It checks a flag, `tty->flow.stopped`. If that flag is already set, it bails out, which makes sense; we don't need to stop something that's already stopped. If the flag isn't set, it sets it to true and then calls the `stop` operation on the tty, if the tty has one. That `tty->flow.stopped` variable is the critical piece here, that's what we need to verify.

Now, that `tty->flow.stopped` member... I'll bet it's either a bitfield or a simple boolean flag within the `tty_struct`. I'm going to quickly reference the definition of `struct tty_struct` to make sure of the exact type. It would be easy to create a race if that variable is accessed in two operations without a proper locking mechanism. I need to understand that flag's use to understand how to synchronize access to it correctly.



8/2 2026/03/09 22:45 tool codesearch-definition-source
0m Args:
map[ContextFile:drivers/tty/tty_io.c IncludeLines:true Name:tty_struct]

Results:
map[SourceCode: 121:	/**
 122:	 * struct tty_struct - state associated with a tty while open
 123:	 *
 124:	 * @kref: reference counting by tty_kref_get() and tty_kref_put(), reaching zero
 125:	 *	  frees the structure
 126:	 * @dev: class device or %NULL (e.g. ptys, serdev)
 127:	 * @driver: &struct tty_driver operating this tty
 128:	 * @ops: &struct tty_operations of @driver for this tty (open, close, etc.)
 129:	 * @index: index of this tty (e.g. to construct @name like tty12)
 130:	 * @ldisc_sem: protects line discipline changes (@ldisc) -- lock tty not pty
 131:	 * @ldisc: the current line discipline for this tty (n_tty by default)
 132:	 * @atomic_write_lock: protects against concurrent writers, i.e. locks
 133:	 *		       @write_cnt, @write_buf and similar
 134:	 * @legacy_mutex: leftover from history (BKL -> BTM -> @legacy_mutex),
 135:	 *		  protecting several operations on this tty
 136:	 * @throttle_mutex: protects against concurrent tty_throttle_safe() and
 137:	 *		    tty_unthrottle_safe() (but not tty_unthrottle())
 138:	 * @termios_rwsem: protects @termios and @termios_locked
 139:	 * @winsize_mutex: protects @winsize
 140:	 * @termios: termios for the current tty, copied from/to @driver.termios
 141:	 * @termios_locked: locked termios (by %TIOCGLCKTRMIOS and %TIOCSLCKTRMIOS
 142:	 *		    ioctls)
 143:	 * @name: name of the tty constructed by tty_line_name() (e.g. ttyS3)
 144:	 * @flags: bitwise OR of %TTY_THROTTLED, %TTY_IO_ERROR, ...
 145:	 * @count: count of open processes, reaching zero cancels all the work for
 146:	 *	   this tty and drops a @kref too (but does not free this tty)
 147:	 * @winsize: size of the terminal "window" (cf. @winsize_mutex)
 148:	 * @flow: flow settings grouped together
 149:	 * @flow.lock: lock for @flow members
 150:	 * @flow.stopped: tty stopped/started by stop_tty()/start_tty()
 151:	 * @flow.tco_stopped: tty stopped/started by %TCOOFF/%TCOON ioctls (it has
 152:	 *		      precedence over @flow.stopped)
 153:	 * @ctrl: control settings grouped together
 154:	 * @ctrl.lock: lock for @ctrl members
 155:	 * @ctrl.pgrp: process group of this tty (setpgrp(2))
 156:	 * @ctrl.session: session of this tty (setsid(2)). Writes are protected by both
 157:	 *		  @ctrl.lock and @legacy_mutex, readers must use at least one of
 158:	 *		  them.
 159:	 * @ctrl.pktstatus: packet mode status (bitwise OR of %TIOCPKT_ constants)
 160:	 * @ctrl.packet: packet mode enabled
 161:	 * @hw_stopped: not controlled by the tty layer, under @driver's control for CTS
 162:	 *		handling
 163:	 * @receive_room: bytes permitted to feed to @ldisc without any being lost
 164:	 * @flow_change: controls behavior of throttling, see tty_throttle_safe() and
 165:	 *		 tty_unthrottle_safe()
 166:	 * @link: link to another pty (master -> slave and vice versa)
 167:	 * @fasync: state for %O_ASYNC (for %SIGIO); managed by fasync_helper()
 168:	 * @write_wait: concurrent writers are waiting in this queue until they are
 169:	 *		allowed to write
 170:	 * @read_wait: readers wait for data in this queue
 171:	 * @hangup_work: normally a work to perform a hangup (do_tty_hangup()); while
 172:	 *		 freeing the tty, (re)used to release_one_tty()
 173:	 * @disc_data: pointer to @ldisc's private data (e.g. to &struct n_tty_data)
 174:	 * @driver_data: pointer to @driver's private data (e.g. &struct uart_state)
 175:	 * @files_lock:	protects @tty_files list
 176:	 * @tty_files: list of (re)openers of this tty (i.e. linked &struct
 177:	 *	       tty_file_private)
 178:	 * @closing: when set during close, n_tty processes only START & STOP chars
 179:	 * @write_buf: temporary buffer used during tty_write() to copy user data to
 180:	 * @write_cnt: count of bytes written in tty_write() to @write_buf
 181:	 * @SAK_work: if the tty has a pending do_SAK, it is queued here
 182:	 * @port: persistent storage for this device (i.e. &struct tty_port)
 183:	 *
 184:	 * All of the state associated with a tty while the tty is open. Persistent
 185:	 * storage for tty devices is referenced here as @port and is documented in
 186:	 * &struct tty_port.
 187:	 */
 188:	struct tty_struct {
 189:		struct kref kref;
 190:		int index;
 191:		struct device *dev;
 192:		struct tty_driver *driver;
 193:		struct tty_port *port;
 194:		const struct tty_operations *ops;
 195:	
 196:		struct tty_ldisc *ldisc;
 197:		struct ld_semaphore ldisc_sem;
 198:	
 199:		struct mutex atomic_write_lock;
 200:		struct mutex legacy_mutex;
 201:		struct mutex throttle_mutex;
 202:		struct rw_semaphore termios_rwsem;
 203:		struct mutex winsize_mutex;
 204:		struct ktermios termios, termios_locked;
 205:		char name[64];
 206:		unsigned long flags;
 207:		int count;
 208:		unsigned int receive_room;
 209:		struct winsize winsize;
 210:	
 211:		struct {
 212:			spinlock_t lock;
 213:			bool stopped;
 214:			bool tco_stopped;
 215:		} flow;
 216:	
 217:		struct {
 218:			struct pid *pgrp;
 219:			struct pid *session;
 220:			spinlock_t lock;
 221:			unsigned char pktstatus;
 222:			bool packet;
 223:		} ctrl;
 224:	
 225:		bool hw_stopped;
 226:		bool closing;
 227:		int flow_change;
 228:	
 229:		struct tty_struct *link;
 230:		struct fasync_struct *fasync;
 231:		wait_queue_head_t write_wait;
 232:		wait_queue_head_t read_wait;
 233:		struct work_struct hangup_work;
 234:		void *disc_data;
 235:		void *driver_data;
 236:		spinlock_t files_lock;
 237:		int write_cnt;
 238:		u8 *write_buf;
 239:	
 240:		struct list_head tty_files;
 241:	
 242:		struct work_struct SAK_work;
 243:	} __randomize_layout;
 SourceFile:include/linux/tty.h]

9/2 2026/03/09 22:45 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 50717
							output: 39
							thoughts: 23
						

Thoughts:
Here's my summary, as though I'm thinking through this process:

**Diving into `pty_write` and Flow Control**

Okay, so I'm looking at this code and specifically need to understand the interaction between the terminal's flow control and the `pty_write` function. First things first, `tty->flow.stopped` is clearly a boolean – a simple flag. I need to remember that; that's the basic state variable that dictates whether the terminal is signaling that it's "stopped" receiving data, using flow control. Now, let's zoom in on `pty_write` itself. I need to understand how `pty_write` behaves when this `tty->flow.stopped` flag is set or not set. How does it handle backpressure? Does it block? Does it just discard data, or does it buffer and how? I need to understand how the driver respects that flow control mechanism. This is the heart of ensuring no data gets dropped due to a full buffer or overwhelmed terminal. That variable is key.



10/2 2026/03/09 22:45 tool codesearch-definition-source
0m Args:
map[ContextFile:drivers/tty/pty.c IncludeLines:true Name:pty_write]

Results:
map[SourceCode: 109:	static ssize_t pty_write(struct tty_struct *tty, const u8 *buf, size_t c)
 110:	{
 111:		struct tty_struct *to = tty->link;
 112:	
 113:		if (tty->flow.stopped || !c)
 114:			return 0;
 115:	
 116:		return tty_insert_flip_string_and_push_buffer(to->port, buf, c);
 117:	}
 SourceFile:drivers/tty/pty.c]

11/2 2026/03/09 22:45 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 51176
							output: 45
							thoughts: 113
						

Thoughts:
Okay, let me break this down.

**Unraveling the Concurrency in TTY Flow Control**

Right, so I'm looking at this `pty_write` function and I see it's reading `tty->flow.stopped` without any sort of locking mechanism. That immediately raises a red flag. We know this is potentially a race condition. Then I dig into where this `tty->flow.stopped` is being written to. `__stop_tty` is the function that actually sets that flag. Now, the documentation says `__stop_tty` is called with a lock held. *However*, if you trace the call stack back from `__stop_tty` to the source, I need to verify how `n_tty_ioctl_helper` is being called and how it then calls `__stop_tty`. I thought `stop_tty` was handling the lock, but now I'm thinking I need to confirm `n_tty_ioctl_helper` isn't calling `__stop_tty` directly without a lock. Let's trace it back through the code, I need to check the call graph for `n_tty_ioctl_helper`. This is going to be my next investigation.



12/2 2026/03/09 22:45 tool codesearch-definition-source
0m Args:
map[ContextFile:drivers/tty/tty_ioctl.c IncludeLines:true Name:n_tty_ioctl_helper]

Results:
map[SourceCode: 936:	int n_tty_ioctl_helper(struct tty_struct *tty, unsigned int cmd,
 937:			unsigned long arg)
 938:	{
 939:		int retval;
 940:	
 941:		switch (cmd) {
 942:		case TCXONC:
 943:			retval = tty_check_change(tty);
 944:			if (retval)
 945:				return retval;
 946:			switch (arg) {
 947:			case TCOOFF:
 948:				spin_lock_irq(&tty->flow.lock);
 949:				if (!tty->flow.tco_stopped) {
 950:					tty->flow.tco_stopped = true;
 951:					__stop_tty(tty);
 952:				}
 953:				spin_unlock_irq(&tty->flow.lock);
 954:				break;
 955:			case TCOON:
 956:				spin_lock_irq(&tty->flow.lock);
 957:				if (tty->flow.tco_stopped) {
 958:					tty->flow.tco_stopped = false;
 959:					__start_tty(tty);
 960:				}
 961:				spin_unlock_irq(&tty->flow.lock);
 962:				break;
 963:			case TCIOFF:
 964:				if (STOP_CHAR(tty) != __DISABLED_CHAR)
 965:					retval = tty_send_xchar(tty, STOP_CHAR(tty));
 966:				break;
 967:			case TCION:
 968:				if (START_CHAR(tty) != __DISABLED_CHAR)
 969:					retval = tty_send_xchar(tty, START_CHAR(tty));
 970:				break;
 971:			default:
 972:				return -EINVAL;
 973:			}
 974:			return retval;
 975:		case TCFLSH:
 976:			retval = tty_check_change(tty);
 977:			if (retval)
 978:				return retval;
 979:			return __tty_perform_flush(tty, arg);
 980:		default:
 981:			/* Try the mode commands */
 982:			return tty_mode_ioctl(tty, cmd, arg);
 983:		}
 984:	}
 SourceFile:drivers/tty/tty_ioctl.c]

13/2 2026/03/09 22:45 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 52305
							output: 21
							thoughts: 456
						

Thoughts:
**Race Condition Analysis and Syzkaller Program Design**

Okay, so I've been digging into this `n_tty_ioctl_helper` issue, and I've got a handle on the race condition. It seems that `n_tty_ioctl_helper` *does* acquire `tty->flow.lock`, but `pty_write` doesn't. The vulnerability lies in the fact that `pty_write` reads `tty->flow.stopped` without the necessary locking. The aim is to reproduce this.

The reproduction steps are pretty clear now: we need to fire off an `ioctl(fd, TCXONC, TCOOFF)` call on a pty *concurrently* with writes to that pty.  I need to get some data flowing through. The write operation can trigger echoing on a pty. The race is between the flow control changes and echo processing.

Thinking through the call chain helps. The relevant path to trigger this appears to be: `pty_write` is called from `tty_put_char`, which is, in turn, called from `n_tty_process_echo_ops`, which is called from `flush_echoes`, which is called from `__receive_buf`, which is called from `flush_to_ldisc`. That explains the master-slave setup.

So the strategy is to write to the master pty, which sends data to the slave pty, which then echoes that data back, thereby calling `pty_write` on the slave pty.  *Concurrently*, we hit the slave with that `ioctl(slave_fd, TCXONC, TCOOFF)` call.

Alright, let's write a syzkaller program to trigger this. I'll need a way to set up the pty master and slave. Here's what I'm thinking:

1.  Open a pty master.
2.  Open the corresponding pty slave.
3.  Thread 1: Execute `write` to either the master or slave pty.  It looks like if I write to the master, it'll go into the slave's receive buffer, which is processed by the `flush_to_ldisc` worker, which echoes the data back to the slave pty, triggering `pty_write` on the slave. Perfect!
4.  Thread 2: Execute `ioctl(slave_fd, TCXONC, TCOOFF)` on the slave pty.

Now, let's see how we can handle this in syzkaller.

`syz_open_dev$ptmx` should work for the master, and then `syz_open_pts` for the slave. Wait, `syz_open_pts` takes the master fd and returns the slave fd. That's slick! I should probably check `dev_ptmx.txt` to be sure.



14/2 2026/03/09 22:45 tool read-description
0m Args:
map[File:dev_ptmx.txt]

Results:
map[Output:# Copyright 2015 syzkaller project authors. All rights reserved.
# Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

include <asm/ioctls.h>
include <uapi/linux/kd.h>
include <uapi/linux/vt.h>
include <uapi/linux/fcntl.h>
include <uapi/linux/tty.h>
include <uapi/linux/serial.h>
include <uapi/linux/termios.h>
include <uapi/linux/tiocl.h>

resource fd_tty[fd]

# UNIX 98 pseudoterminal pairs (see man pts and man pty):
openat$ptmx(fd const[AT_FDCWD], file ptr[in, string["/dev/ptmx"]], flags flags[open_flags], mode const[0]) fd_tty
syz_open_pts(fd fd_tty, flags flags[open_flags]) fd_tty

# BSD pseudoterminal pair (see man pty):
syz_open_dev$ttys(dev const[0xc], major const[2], minor proc[20, 2]) fd_tty
syz_open_dev$ptys(dev const[0xc], major const[3], minor proc[20, 2]) fd_tty

# Some special tty devices.
# Note /dev/{tty,tty1,tty2,tty7} seem to be of different types.
openat$tty(fd const[AT_FDCWD], file ptr[in, string["/dev/tty"]], flags flags[open_flags], mode const[0]) fd_tty
syz_open_dev$tty1(dev const[0xc], major const[4], minor intptr[1:4]) fd_tty
syz_open_dev$tty20(dev const[0xc], major const[4], minor proc[20, 2]) fd_tty
openat$ttyS3(fd const[AT_FDCWD], file ptr[in, string["/dev/ttyS3"]], flags flags[open_flags], mode const[0]) fd_tty
openat$ttynull(fd const[AT_FDCWD], file ptr[in, string["/dev/ttynull"]], flags flags[open_flags], mode const[0]) fd_tty
openat$ttyprintk(fd const[AT_FDCWD], file ptr[in, string["/dev/ttyprintk"]], flags flags[open_flags], mode const[0]) fd_tty

ioctl$TCGETS(fd fd_tty, cmd const[TCGETS], arg ptr[out, termios])
ioctl$TCSETS(fd fd_tty, cmd const[TCSETS], arg ptr[in, termios])
ioctl$TCSETSW(fd fd_tty, cmd const[TCSETSW], arg ptr[in, termios])
ioctl$TCSETSF(fd fd_tty, cmd const[TCSETSF], arg ptr[in, termios])
ioctl$TCGETA(fd fd_tty, cmd const[TCGETA], arg ptr[out, termio])
ioctl$TCSETA(fd fd_tty, cmd const[TCSETA], arg ptr[in, termio])
ioctl$TCSETAW(fd fd_tty, cmd const[TCSETAW], arg ptr[in, termio])
ioctl$TCSETAF(fd fd_tty, cmd const[TCSETAF], arg ptr[in, termio])
ioctl$TIOCGLCKTRMIOS(fd fd_tty, cmd const[TIOCGLCKTRMIOS], arg ptr[in, termios])
ioctl$TIOCSLCKTRMIOS(fd fd_tty, cmd const[TIOCSLCKTRMIOS], arg ptr[out, termios])
ioctl$TIOCGWINSZ(fd fd_tty, cmd const[TIOCGWINSZ], arg ptr[out, winsize])
ioctl$TIOCSWINSZ(fd fd_tty, cmd const[TIOCSWINSZ], arg ptr[in, winsize])
ioctl$TCSBRK(fd fd_tty, cmd const[TCSBRK], arg intptr)
ioctl$TCSBRKP(fd fd_tty, cmd const[TCSBRKP], arg intptr)
ioctl$TIOCSBRK(fd fd_tty, cmd const[TIOCSBRK])
ioctl$TIOCCBRK(fd fd_tty, cmd const[TIOCCBRK])
ioctl$TCXONC(fd fd_tty, cmd const[TCXONC], arg flags[tcxonc_arg])
ioctl$FIONREAD(fd fd_tty, cmd const[FIONREAD], arg ptr[out, int32])
ioctl$TIOCOUTQ(fd fd_tty, cmd const[TIOCOUTQ], arg ptr[out, int32])
ioctl$TCFLSH(fd fd_tty, cmd const[TCFLSH], arg intptr[TCIFLUSH:TCIOFLUSH])
ioctl$TIOCGPTPEER(fd fd_tty, cmd const[TIOCGPTPEER], arg intptr) fd_tty
ioctl$TIOCSTI(fd fd_tty, cmd const[TIOCSTI], arg ptr[in, int8])
ioctl$TIOCCONS(fd fd_tty, cmd const[TIOCCONS])
ioctl$TIOCSCTTY(fd fd_tty, cmd const[TIOCSCTTY], arg intptr)
ioctl$TIOCNOTTY(fd fd_tty, cmd const[TIOCNOTTY])
ioctl$TIOCGPGRP(fd fd_tty, cmd const[TIOCGPGRP], arg ptr[out, pid])
ioctl$TIOCSPGRP(fd fd_tty, cmd const[TIOCSPGRP], arg ptr[in, pid])
ioctl$TIOCGSID(fd fd_tty, cmd const[TIOCGSID], arg ptr[out, pid])
ioctl$TIOCEXCL(fd fd_tty, cmd const[TIOCEXCL])
ioctl$TIOCNXCL(fd fd_tty, cmd const[TIOCNXCL])
ioctl$TIOCGETD(fd fd_tty, cmd const[TIOCGETD], arg ptr[out, int32])
ioctl$TIOCSETD(fd fd_tty, cmd const[TIOCSETD], arg ptr[in, int32[N_TTY:N_NULL]])
ioctl$TIOCPKT(fd fd_tty, cmd const[TIOCPKT], arg ptr[in, int32])
ioctl$TIOCMGET(fd fd_tty, cmd const[TIOCMGET], arg ptr[out, int32])
ioctl$TIOCMSET(fd fd_tty, cmd const[TIOCMSET], arg ptr[in, int32])
ioctl$TIOCMBIC(fd fd_tty, cmd const[TIOCMBIC], arg ptr[in, int32])
ioctl$TIOCMBIS(fd fd_tty, cmd const[TIOCMBIS], arg ptr[in, int32])
ioctl$TIOCGSOFTCAR(fd fd_tty, cmd const[TIOCGSOFTCAR], arg ptr[out, int32])
ioctl$TIOCSSOFTCAR(fd fd_tty, cmd const[TIOCSSOFTCAR], arg ptr[in, int32])

ioctl$KDGETLED(fd fd_tty, cmd const[KDGETLED], arg ptr[out, int8])
ioctl$KDSETLED(fd fd_tty, cmd const[KDSETLED], arg intptr)
ioctl$KDGKBLED(fd fd_tty, cmd const[KDGKBLED], arg ptr[out, int8])
ioctl$KDSKBLED(fd fd_tty, cmd const[KDSKBLED], arg intptr)
ioctl$KDGKBTYPE(fd fd_tty, cmd const[KDGKBTYPE], arg ptr[out, int8])
ioctl$KDADDIO(fd fd_tty, cmd const[KDADDIO], arg intptr)
ioctl$KDDELIO(fd fd_tty, cmd const[KDDELIO], arg intptr)
ioctl$KDENABIO(fd fd_tty, cmd const[KDENABIO])
ioctl$KDDISABIO(fd fd_tty, cmd const[KDDISABIO])
ioctl$KDSETMODE(fd fd_tty, cmd const[KDSETMODE], arg intptr[KD_TEXT:KD_GRAPHICS])
ioctl$KDGETMODE(fd fd_tty, cmd const[KDGETMODE], arg ptr[out, intptr])
ioctl$KDMKTONE(fd fd_tty, cmd const[KDMKTONE], arg intptr)
ioctl$KIOCSOUND(fd fd_tty, cmd const[KIOCSOUND], arg intptr)
ioctl$GIO_CMAP(fd fd_tty, cmd const[GIO_CMAP], arg ptr[out, io_cmap])
ioctl$PIO_CMAP(fd fd_tty, cmd const[PIO_CMAP], arg ptr[in, io_cmap])
ioctl$GIO_FONT(fd fd_tty, cmd const[GIO_FONT], arg buffer[out])
ioctl$GIO_FONTX(fd fd_tty, cmd const[GIO_FONTX], arg ptr[in, consolefontdesc[out]])
ioctl$PIO_FONT(fd fd_tty, cmd const[PIO_FONT], arg buffer[in])
ioctl$PIO_FONTX(fd fd_tty, cmd const[PIO_FONTX], arg ptr[in, consolefontdesc[in]])
ioctl$PIO_FONTRESET(fd fd_tty, cmd const[PIO_FONTRESET], arg const[0])
ioctl$KDFONTOP_SET(fd fd_tty, cmd const[KDFONTOP], arg ptr[in, console_font_op[KD_FONT_OP_SET, in]])
ioctl$KDFONTOP_GET(fd fd_tty, cmd const[KDFONTOP], arg ptr[in, console_font_op[KD_FONT_OP_GET, out]])
ioctl$KDFONTOP_SET_DEF(fd fd_tty, cmd const[KDFONTOP], arg ptr[in, console_font_op[KD_FONT_OP_SET_DEFAULT, in]])
ioctl$KDFONTOP_COPY(fd fd_tty, cmd const[KDFONTOP], arg ptr[in, console_font_op[KD_FONT_OP_COPY, out]])
ioctl$GIO_SCRNMAP(fd fd_tty, cmd const[GIO_SCRNMAP], arg buffer[out])
ioctl$GIO_UNISCRNMAP(fd fd_tty, cmd const[GIO_UNISCRNMAP], arg buffer[out])
ioctl$PIO_SCRNMAP(fd fd_tty, cmd const[PIO_SCRNMAP], arg buffer[in])
ioctl$PIO_UNISCRNMAP(fd fd_tty, cmd const[PIO_UNISCRNMAP], arg buffer[in])
ioctl$GIO_UNIMAP(fd fd_tty, cmd const[GIO_UNIMAP], arg ptr[in, unimapdesc_out])
ioctl$PIO_UNIMAP(fd fd_tty, cmd const[PIO_UNIMAP], arg ptr[in, unimapdesc_in])
ioctl$PIO_UNIMAPCLR(fd fd_tty, cmd const[PIO_UNIMAPCLR], arg ptr[in, unimapinit])
ioctl$KDGKBMODE(fd fd_tty, cmd const[KDGKBMODE], arg ptr[out, intptr])
ioctl$KDSKBMODE(fd fd_tty, cmd const[KDSKBMODE], arg ptr[in, intptr[K_RAW:K_OFF]])
ioctl$KDGKBMETA(fd fd_tty, cmd const[KDGKBMETA], arg ptr[out, intptr])
ioctl$KDSKBMETA(fd fd_tty, cmd const[KDSKBMETA], arg ptr[in, intptr[K_METABIT:K_ESCPREFIX]])
ioctl$KDGKBENT(fd fd_tty, cmd const[KDGKBENT], arg ptr[in, kbentry])
ioctl$KDSKBENT(fd fd_tty, cmd const[KDSKBENT], arg ptr[in, kbentry])
ioctl$KDGKBSENT(fd fd_tty, cmd const[KDGKBSENT], arg ptr[in, kbsentry])
ioctl$KDSKBSENT(fd fd_tty, cmd const[KDSKBSENT], arg ptr[in, kbsentry])
ioctl$KDGKBDIACR(fd fd_tty, cmd const[KDGKBDIACR], arg buffer[out])
ioctl$KDGETKEYCODE(fd fd_tty, cmd const[KDGETKEYCODE], arg ptr[in, kbkeycode])
ioctl$KDSETKEYCODE(fd fd_tty, cmd const[KDSETKEYCODE], arg ptr[in, kbkeycode])
ioctl$KDSIGACCEPT(fd fd_tty, cmd const[KDSIGACCEPT], arg signalnoptr)
ioctl$VT_OPENQRY(fd fd_tty, cmd const[VT_OPENQRY], arg ptr[out, int32])
ioctl$VT_GETMODE(fd fd_tty, cmd const[VT_GETMODE], arg ptr[out, vt_mode])
ioctl$VT_SETMODE(fd fd_tty, cmd const[VT_SETMODE], arg ptr[in, vt_mode])
ioctl$VT_GETSTATE(fd fd_tty, cmd const[VT_GETSTATE], arg ptr[in, vt_stat])
ioctl$VT_RELDISP(fd fd_tty, cmd const[VT_RELDISP])
ioctl$VT_ACTIVATE(fd fd_tty, cmd const[VT_ACTIVATE], arg intptr)
ioctl$VT_WAITACTIVE(fd fd_tty, cmd const[VT_WAITACTIVE])
ioctl$VT_DISALLOCATE(fd fd_tty, cmd const[VT_DISALLOCATE])
ioctl$VT_RESIZE(fd fd_tty, cmd const[VT_RESIZE], arg ptr[in, vt_sizes])
ioctl$VT_RESIZEX(fd fd_tty, cmd const[VT_RESIZEX], arg ptr[in, vt_consize])

# For the TIOCLINUX ioctl, see console_ioctl(4).
ioctl$TIOCL_SETSEL(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, tiocl_selection_arg])
ioctl$TIOCL_PASTESEL(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, const[TIOCL_PASTESEL, int8]])
ioctl$TIOCL_UNBLANKSCREEN(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, const[TIOCL_UNBLANKSCREEN, int8]])
ioctl$TIOCL_SELLOADLUT(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, loadlut])
ioctl$TIOCL_GETSHIFTSTATE(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, tiocl_shift_state])
ioctl$TIOCL_GETMOUSEREPORTING(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, const[TIOCL_GETMOUSEREPORTING, int8]])
ioctl$TIOCL_SETVESABLANK(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, const[TIOCL_SETVESABLANK, int8]])

ioctl$TIOCL_GETKMSGREDIRECT(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, const[TIOCL_GETKMSGREDIRECT, int8]])
ioctl$TIOCL_SCROLLCONSOLE(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, tioctl_scroll_console])
ioctl$TIOCL_BLANKSCREEN(fd fd_tty, cmd const[TIOCLINUX], arg ptr[in, const[TIOCL_BLANKSCREEN, int8]])

# TIOCSSERIAL can do nasty things under root, like causing writes to random memory
# pretty much like /dev/mem, but this is also working as intended.
# For details see:
# https://groups.google.com/g/syzkaller-bugs/c/1rVENJf9P4U/m/QtGpapRxAgAJ
# https://syzkaller.appspot.com/bug?extid=f4f1e871965064ae689e
# TODO: TIOCSSERIAL does some other things that are not dangerous
# and would be nice to test, if/when we can neutralize based on sandbox value
# we could prohibit it only under sandbox=none.
ioctl$TIOCSSERIAL(fd fd, cmd const[TIOCSSERIAL], arg ptr[in, serial_struct]) (disabled)

ioctl$TIOCGSERIAL(fd fd_tty, cmd const[TIOCGSERIAL], arg ptr[out, serial_struct])
ioctl$TCGETS2(fd fd_tty, cmd const[TCGETS2], arg ptr[out, termios2])
ioctl$TCSETS2(fd fd_tty, cmd const[TCSETS2], arg ptr[in, termios2])
ioctl$TCSETSF2(fd fd_tty, cmd const[TCSETSF2], arg ptr[in, termios2])
ioctl$TCSETSW2(fd fd_tty, cmd const[TCSETSW2], arg ptr[in, termios2])
ioctl$TIOCSERGETLSR(fd fd_tty, cmd const[TIOCSERGETLSR], arg ptr[out, int32])
ioctl$TIOCGRS485(fd fd_tty, cmd const[TIOCGRS485], arg ptr[out, serial_rs485])
ioctl$TIOCSRS485(fd fd_tty, cmd const[TIOCSRS485], arg ptr[in, serial_rs485])
ioctl$TIOCGISO7816(fd fd_tty, cmd const[TIOCGISO7816], arg ptr[out, serial_iso7816])
ioctl$TIOCSISO7816(fd fd_tty, cmd const[TIOCSISO7816], arg ptr[in, serial_iso7816])
ioctl$TIOCSPTLCK(fd fd_tty, cmd const[TIOCSPTLCK], arg ptr[in, bool32])
ioctl$TIOCGPTLCK(fd fd_tty, cmd const[TIOCGPTLCK], arg ptr[out, int32])
ioctl$TIOCGPKT(fd fd_tty, cmd const[TIOCGPKT], arg ptr[out, int32])
ioctl$TIOCSIG(fd fd_tty, cmd const[TIOCSIG], arg signalnoptr)
ioctl$TIOCVHANGUP(fd fd_tty, cmd const[TIOCVHANGUP], arg const[0])
ioctl$TIOCGDEV(fd fd_tty, cmd const[TIOCGDEV], arg ptr[out, int32])
ioctl$TIOCMIWAIT(fd fd_tty, cmd const[TIOCMIWAIT], arg const[0])
ioctl$TIOCGICOUNT(fd fd_tty, cmd const[TIOCGICOUNT], arg const[0])

# See tty_mode_ioctl.
ioctl$TIOCGETP(fd fd_tty, cmd const[TIOCGETP], arg ptr[out, sgttyb])
ioctl$TIOCSETP(fd fd_tty, cmd const[TIOCSETP], arg ptr[in, sgttyb])
ioctl$TIOCGETC(fd fd_tty, cmd const[TIOCGETC], arg ptr[out, array[int8]])
ioctl$TIOCSETC(fd fd_tty, cmd const[TIOCSETC], arg ptr[in, array[int8]])
ioctl$TIOCGLTC(fd fd_tty, cmd const[TIOCGLTC], arg ptr[out, array[int8]])
ioctl$TIOCSLTC(fd fd_tty, cmd const[TIOCSLTC], arg ptr[in, array[int8]])

sgttyb {
	sg_ispeed	int8
	sg_ospeed	int8
	sg_erase	int8
	sg_kill		int8
	sg_flags	int16
}

tcxonc_arg = TCOOFF, TCOON, TCIOFF, TCION

termios {
	c_iflag	int32
	c_oflag	int32
	c_cflag	int32
	c_lflag	int32
	c_line	int8[N_TTY:N_NULL]
	c_cc	array[int8, NCCS]
}

termios2 {
	c_iflag		int32
	c_oflag		int32
	c_cflag		int32
	c_lflag		int32
	c_line		int8
	c_cc		array[int8, NCCS]
	c_ispeed	int32
	c_ospeed	int32
}

termio {
	c_iflag	int16
	c_oflag	int16
	c_cflag	int16
	c_lflag	int16
	c_line	int8[N_TTY:N_NULL]
	c_cc	array[int8, NCC]
}

winsize {
	row	int16
	col	int16
	xpix	int16
	upix	int16
}

io_cmap {
	map0	int64
	map1	int64
	map2	int64
	map3	int64
	map4	int64
	map5	int64
}

unimapdesc_in {
	cnt	len[entries, int16]
	entries	ptr[in, array[unipair]]
}

unimapdesc_out {
	cnt	len[entries, int16]
	entries	ptr[out, array[unipair]]
}

unipair {
	unicode	int16
	fontpos	int16
}

unimapinit {
	size	int16
	step	int16
	level	int16
}

kbentry {
	table	int8
	index	int8
	value	int16
}

kbsentry {
	kb_func		int8
	kb_string	array[int8, 512]
}

kbkeycode {
	scan	int32
	key	int32
}

vt_mode {
	mode	int8
	waitv	int8
	relsig	int16
	acqsig	int16
	frsig	int16
}

vt_stat {
	active	int16
	signal	int16
	state	int16
}

vt_sizes {
	rows	int16
	cols	int16
	scroll	int16
}

vt_consize {
	rows	int16
	cols	int16
	vlin	int16
	clin	int16
	vcol	int16
	ccol	int16
}

tiocl_selection_arg {
	subcode	const[TIOCL_SETSEL, int8]
	data	tiocl_selection
} [packed]

tiocl_selection {
	subcode	const[TIOCL_SETSEL, int8]
	xs	int16
	ys	int16
	xe	int16
	ye	int16
	mode	flags[tiocl_selection_mode, int16]
} [packed]

tiocl_selection_mode = TIOCL_SELCHAR, TIOCL_SELWORD, TIOCL_SELLINE, TIOCL_SELPOINTER, TIOCL_SELCLEAR, TIOCL_SELMOUSEREPORT, TIOCL_SELBUTTONMASK

loadlut {
	submode	const[TIOCL_SELLOADLUT, int8]
	tab0	int64
	tab1	int64
	tab2	int64
	tab3	int64
} [packed]

tiocl_shift_state {
	subcode	const[TIOCL_GETSHIFTSTATE, int8]
	shift	int8
} [packed]

tioctl_scroll_console {
	subcode	const[TIOCL_SCROLLCONSOLE, int8]
	lines	int32
}

serial_struct {
	type		int32
	line		int32
	port		int32
	irq		int32
	flags		int32
	xmit_fifo_size	int32
	custom_divisor	int32
	baud_base	int32
	close_delay	int16
	io_type		int8
	reserved_char	int8
	hub6		int32
	closing_wait	int16
	closing_wait2	int16
	iomem_base	ptr[out, array[int8]]
	iomem_reg_shift	int16
	port_high	int32
	iomap_base	intptr
}

serial_rs485 {
	flags			int32
	delay_rts_before_send	int32
	delay_rts_after_send	int32
	padding			array[const[0, int32], 5]
}

serial_iso7816 {
	flags		int32
	tg		int32
	sc_fi		int32
	sc_di		int32
	clk		int32
	reserved	array[const[0, int32], 5]
}

type consolefontdesc[DIR] {
	charcount	int16[0:512]
	charheight	int16[0:32]
	chardata	ptr[DIR, array[int8, 1024]]
}

type console_font_op[OP, DIR] {
	op		const[OP, int32]
	flags		bool32
	width		int32[0:32]
	height		int32[0:32]
	charcount	int32[0:512]
	data		ptr[DIR, array[int8, 1024]]
}
]

15/2 2026/03/09 22:45 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 59604
							output: 20
							thoughts: 1625
						

Thoughts:
**Deconstructing the pty Race Condition**

Okay, so I've got a handle on this pty race condition. First, I'm thinking, let's start by opening a pty master using `openat$ptmx` and then the slave with `syz_open_pts`. I quickly remembered that `syz_open_pts` is a pseudo-syscall, but a quick check in `executor/common_linux.h` confirms it's available. That should give me file descriptors `r0` for the master and `r1` for the slave.

The crux of the matter is triggering the race. Writing to the master pty (`r0`) will place the data in the slave's receive buffer.  With echoing enabled, which is the default for pty slaves, the slave will echo the data back to the master, calling `pty_write` on the slave's end.  This is key. Let me quickly double check `pty_write`.  Ah, yes, if the `tty` is the slave, `to` is the master and the function copies the input buffer `buf` to the master.  The race will be between `pty_write` and `__stop_tty` which can be called by `n_tty_ioctl_helper` via `TCXONC` with `TCOOFF`.

So, the plan is this:  concurrently with the write to the master, I need to use `ioctl$TCXONC` on the slave (`r1`) with `TCOOFF` to stop the flow. `TCXONC` is `0x540A`. Checking `dev_ptmx.txt` confirms that `TCOOFF` is 0. Thus, I'll use `ioctl$TCXONC(r1, 0x540a, 0x0)`.

Now, to trigger the `pty_write` on the slave, I can write to the slave pty. A quick look at the stack trace in the report confirms that the write operation is initiated by echoing and calls `tty_put_char`, which eventually calls `pty_write`.  So writing to the master pty and triggering the echo process is enough. This happens within a workqueue via `flush_to_ldisc`, which means it can execute concurrently. I can trigger this by writing to the master.

So, the program becomes: open a pty master and slave. Write to the master pty (async). Concurrently, call `ioctl$TCXONC` on the slave.  I've double-checked the documentation to confirm `syz_open_pts` is defined in `dev_ptmx.txt`. I will confirm that `TCXONC` is indeed `0x540a` at runtime. Hopefully, this race condition is triggered by this setup.



16/2 2026/03/09 22:46 tool grepper
0m Args:
map[Expression:#define TCXONC]

Results:
map[Output:arch/alpha/include/uapi/asm/ioctls.h-31-#define TCSBRK		_IO('t', 29)
arch/alpha/include/uapi/asm/ioctls.h:32:#define TCXONC		_IO('t', 30)
arch/alpha/include/uapi/asm/ioctls.h-33-#define TCFLSH		_IO('t', 31)
--
arch/mips/include/uapi/asm/ioctls.h-20-#define TCSBRK		0x5405
arch/mips/include/uapi/asm/ioctls.h:21:#define TCXONC		0x5406
arch/mips/include/uapi/asm/ioctls.h-22-#define TCFLSH		0x5407
--
arch/parisc/include/uapi/asm/ioctls.h-17-#define TCSBRK		_IO('T', 5)
arch/parisc/include/uapi/asm/ioctls.h:18:#define TCXONC		_IO('T', 6)
arch/parisc/include/uapi/asm/ioctls.h-19-#define TCFLSH		_IO('T', 7)
--
arch/powerpc/include/uapi/asm/ioctls.h-31-#define TCSBRK		_IO('t', 29)
arch/powerpc/include/uapi/asm/ioctls.h:32:#define TCXONC		_IO('t', 30)
arch/powerpc/include/uapi/asm/ioctls.h-33-#define TCFLSH		_IO('t', 31)
--
arch/sh/include/uapi/asm/ioctls.h-25-#define TCSBRK		_IO('t', 29)
arch/sh/include/uapi/asm/ioctls.h:26:#define TCXONC		_IO('t', 30)
arch/sh/include/uapi/asm/ioctls.h-27-#define TCFLSH		_IO('t', 31)
--
arch/sparc/include/uapi/asm/ioctls.h-12-#define TCSBRK		_IO('T', 5)
arch/sparc/include/uapi/asm/ioctls.h:13:#define TCXONC		_IO('T', 6)
arch/sparc/include/uapi/asm/ioctls.h-14-#define TCFLSH		_IO('T', 7)
--
arch/xtensa/include/uapi/asm/ioctls.h-37-#define TCSBRK		_IO('t', 29)
arch/xtensa/include/uapi/asm/ioctls.h:38:#define TCXONC		_IO('t', 30)
arch/xtensa/include/uapi/asm/ioctls.h-39-#define TCFLSH		_IO('t', 31)
--
include/uapi/asm-generic/ioctls.h-28-#define TCSBRK		0x5409
include/uapi/asm-generic/ioctls.h:29:#define TCXONC		0x540A
include/uapi/asm-generic/ioctls.h-30-#define TCFLSH		0x540B
--
tools/include/uapi/asm-generic/ioctls.h-28-#define TCSBRK		0x5409
tools/include/uapi/asm-generic/ioctls.h:29:#define TCXONC		0x540A
tools/include/uapi/asm-generic/ioctls.h-30-#define TCFLSH		0x540B
]

17/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 62823
							output: 19
							thoughts: 28
						

Thoughts:
Okay, here's my interpretation of those thoughts, summarized from an expert's perspective:

**Decoding the Timer Configuration**

Alright, let's see, confirmed. The register `TCXONC` – that's the Timer/Counter x Control Register, specifically the one controlling this particular instance – is indeed set to `0x540A`. I recognize the bit pattern immediately, confirming the timer's active state and specific operating mode. I can deduce from this setting quite a bit about how the timer is running. And, just as expected, the `TCOOFF` register, which presumably relates to some kind of timer offset, is set to `0`. So, no offset applied. This is the base configuration I anticipated, now I can move on to other areas to understand more fully the overall implementation.



18/2 2026/03/09 22:46 tool grepper
0m Args:
map[Expression:#define TCOOFF]

Results:
map[Output:include/uapi/asm-generic/termbits-common.h=6=typedef unsigned int	speed_t;
--
include/uapi/asm-generic/termbits-common.h-55-/* tcflow() ACTION argument and TCXONC use these */
include/uapi/asm-generic/termbits-common.h:56:#define TCOOFF		0		/* Suspend output */
include/uapi/asm-generic/termbits-common.h-57-#define TCOON		1		/* Restart suspended output */
]

19/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 63181
							output: 17
							thoughts: 192
						

Thoughts:
**Analyzing the Syzkaller Program**

Okay, so I'm looking at this syzkaller program. The first thing I see is that `TCOOFF` is definitely zero – that's a good starting point. I can clearly see the structure: open a pseudo-terminal master (`ptmx`), then use `syz_open_pts` (a helper function, most likely) to open the corresponding slave. There's a `write` call on `r0` (the ptmx master) writing "01010101" to it, and finally an `ioctl` call with `TCXONC`.

But hang on… is that `write` call correct? It's a fundamental system call, so that part is fine. I need to make sure I’m interpreting this correctly within the syzkaller context. I usually see `write(fd, buf, len)` in the standard form. The register usage looks reasonable, `r0` is the file descriptor from `openat$ptmx`, the string should be the buffer, and `0x4` is the length. So that part seems right, but I need to quickly confirm it's not being obscured by some other structure within the syzkaller translation. I'll check `sys.txt` and `filesystem.txt` to confirm that standard calls, like write, are not being redefined or shadowed by custom structs. I need to be absolutely sure this `write` is behaving as expected, before I continue analyzing this program.



20/2 2026/03/09 22:46 tool grepper
0m Args:
map[Expression:^write\(]

Results:
map[Output:Documentation/driver-api/nfc/nfc-hci.rst=138=disable():
Documentation/driver-api/nfc/nfc-hci.rst-139-	turn the phy off
Documentation/driver-api/nfc/nfc-hci.rst:140:write():
Documentation/driver-api/nfc/nfc-hci.rst-141-	Send a data frame to the chip. Note that to enable higher
--
Documentation/driver-api/xillybus.rst=295=driver to submit all data it has in the buffers to the FPGA, by issuing a
Documentation/driver-api/xillybus.rst:296:write() with the byte count set to zero. This is similar to a flush request,
Documentation/driver-api/xillybus.rst-297-but it doesn't block. There is also an autoflushing mechanism, which triggers
--
Documentation/filesystems/configfs.rst=24=readdir(3)/read(2).  It may allow some attributes to be modified via
Documentation/filesystems/configfs.rst:25:write(2).  The important point is that the object is created and
Documentation/filesystems/configfs.rst-26-destroyed in kernel, the kernel controls the lifecycle of the sysfs
--
Documentation/filesystems/dlmfs.rst=130=Exclusive modes via the read(2) system call. It can be written via
Documentation/filesystems/dlmfs.rst:131:write(2) only when open in Exclusive mode.
Documentation/filesystems/dlmfs.rst-132-
--
Documentation/filesystems/proc.rst=1847=Attempt to count the number of write I/O operations, i.e. syscalls like
Documentation/filesystems/proc.rst:1848:write() and pwrite().
Documentation/filesystems/proc.rst-1849-
--
Documentation/hid/hidraw.rst=54=will begin at the first byte.
Documentation/hid/hidraw.rst-55-
Documentation/hid/hidraw.rst:56:write()
Documentation/hid/hidraw.rst-57--------
--
Documentation/hid/uhid.rst=24=device you want to register. All further communication is done by read()'ing or
Documentation/hid/uhid.rst:25:write()'ing "struct uhid_event" objects. Non-blocking operations are supported
Documentation/hid/uhid.rst-26-by setting O_NONBLOCK::
--
Documentation/hid/uhid.rst=78=internally.
Documentation/hid/uhid.rst-79-
Documentation/hid/uhid.rst:80:write()
Documentation/hid/uhid.rst-81--------
Documentation/hid/uhid.rst:82:write() allows you to modify the state of the device and feed input data into
Documentation/hid/uhid.rst-83-the kernel. The kernel will parse the event immediately and if the event ID is
--
Documentation/misc-devices/ibmvmc.rst=179=sending data to the hypervisor, the management application performs a
Documentation/misc-devices/ibmvmc.rst:180:write() to the VMC device, and the driver RDMA’s the data to the hypervisor
Documentation/misc-devices/ibmvmc.rst-181-and then sends a Signal Message. If a write() is attempted before VMC
--
Documentation/misc-devices/ibmvmc.rst=183=are currently available, EBUSY is returned in response to the write(). A
Documentation/misc-devices/ibmvmc.rst:184:write() will return EIO for all other errors, such as an invalid device
Documentation/misc-devices/ibmvmc.rst-185-state. When the hypervisor sends a message to the management, the data is
--
Documentation/scsi/libsas.rst=430=open(2)
--
Documentation/scsi/libsas.rst-433-
Documentation/scsi/libsas.rst:434:write(2)
Documentation/scsi/libsas.rst-435-
--
Documentation/translations/zh_CN/scsi/libsas.rst=402=open(2)
--
Documentation/translations/zh_CN/scsi/libsas.rst-405-
Documentation/translations/zh_CN/scsi/libsas.rst:406:write(2)
Documentation/translations/zh_CN/scsi/libsas.rst-407-
--
Documentation/userspace-api/media/dvb/legacy_dvb_audio.rst=1558=Return Value
--
Documentation/userspace-api/media/dvb/legacy_dvb_audio.rst-1573-
Documentation/userspace-api/media/dvb/legacy_dvb_audio.rst:1574:write()
Documentation/userspace-api/media/dvb/legacy_dvb_audio.rst-1575--------
--
Documentation/userspace-api/media/dvb/legacy_dvb_video.rst=2344=Return Value
--
Documentation/userspace-api/media/dvb/legacy_dvb_video.rst-2360-
Documentation/userspace-api/media/dvb/legacy_dvb_video.rst:2361:write()
Documentation/userspace-api/media/dvb/legacy_dvb_video.rst-2362--------
]

21/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 65042
							output: 17
							thoughts: 13
						

Thoughts:
Here's a summary of my immediate thought process:

**Analyzing the Code for Write Operations**

Okay, so I need to figure out if there are any write operations occurring within this context. My instinct is to zero in on `sys.txt` – that's often a key file to examine for system-level interaction or potentially configuration changes. The immediate focus is on the *function* `write`. I'm going to look for any instances of that term within `sys.txt`. The goal is to determine if any write actions are performed in this context. I'm going to quickly scan it for that term, as that will give me a first handle on the functionality I'm examining.



22/2 2026/03/09 22:46 tool grepper
0m Args:
map[Expression:^write\(]

Results:
map[Output:Documentation/driver-api/nfc/nfc-hci.rst=138=disable():
Documentation/driver-api/nfc/nfc-hci.rst-139-	turn the phy off
Documentation/driver-api/nfc/nfc-hci.rst:140:write():
Documentation/driver-api/nfc/nfc-hci.rst-141-	Send a data frame to the chip. Note that to enable higher
--
Documentation/driver-api/xillybus.rst=295=driver to submit all data it has in the buffers to the FPGA, by issuing a
Documentation/driver-api/xillybus.rst:296:write() with the byte count set to zero. This is similar to a flush request,
Documentation/driver-api/xillybus.rst-297-but it doesn't block. There is also an autoflushing mechanism, which triggers
--
Documentation/filesystems/configfs.rst=24=readdir(3)/read(2).  It may allow some attributes to be modified via
Documentation/filesystems/configfs.rst:25:write(2).  The important point is that the object is created and
Documentation/filesystems/configfs.rst-26-destroyed in kernel, the kernel controls the lifecycle of the sysfs
--
Documentation/filesystems/dlmfs.rst=130=Exclusive modes via the read(2) system call. It can be written via
Documentation/filesystems/dlmfs.rst:131:write(2) only when open in Exclusive mode.
Documentation/filesystems/dlmfs.rst-132-
--
Documentation/filesystems/proc.rst=1847=Attempt to count the number of write I/O operations, i.e. syscalls like
Documentation/filesystems/proc.rst:1848:write() and pwrite().
Documentation/filesystems/proc.rst-1849-
--
Documentation/hid/hidraw.rst=54=will begin at the first byte.
Documentation/hid/hidraw.rst-55-
Documentation/hid/hidraw.rst:56:write()
Documentation/hid/hidraw.rst-57--------
--
Documentation/hid/uhid.rst=24=device you want to register. All further communication is done by read()'ing or
Documentation/hid/uhid.rst:25:write()'ing "struct uhid_event" objects. Non-blocking operations are supported
Documentation/hid/uhid.rst-26-by setting O_NONBLOCK::
--
Documentation/hid/uhid.rst=78=internally.
Documentation/hid/uhid.rst-79-
Documentation/hid/uhid.rst:80:write()
Documentation/hid/uhid.rst-81--------
Documentation/hid/uhid.rst:82:write() allows you to modify the state of the device and feed input data into
Documentation/hid/uhid.rst-83-the kernel. The kernel will parse the event immediately and if the event ID is
--
Documentation/misc-devices/ibmvmc.rst=179=sending data to the hypervisor, the management application performs a
Documentation/misc-devices/ibmvmc.rst:180:write() to the VMC device, and the driver RDMA’s the data to the hypervisor
Documentation/misc-devices/ibmvmc.rst-181-and then sends a Signal Message. If a write() is attempted before VMC
--
Documentation/misc-devices/ibmvmc.rst=183=are currently available, EBUSY is returned in response to the write(). A
Documentation/misc-devices/ibmvmc.rst:184:write() will return EIO for all other errors, such as an invalid device
Documentation/misc-devices/ibmvmc.rst-185-state. When the hypervisor sends a message to the management, the data is
--
Documentation/scsi/libsas.rst=430=open(2)
--
Documentation/scsi/libsas.rst-433-
Documentation/scsi/libsas.rst:434:write(2)
Documentation/scsi/libsas.rst-435-
--
Documentation/translations/zh_CN/scsi/libsas.rst=402=open(2)
--
Documentation/translations/zh_CN/scsi/libsas.rst-405-
Documentation/translations/zh_CN/scsi/libsas.rst:406:write(2)
Documentation/translations/zh_CN/scsi/libsas.rst-407-
--
Documentation/userspace-api/media/dvb/legacy_dvb_audio.rst=1558=Return Value
--
Documentation/userspace-api/media/dvb/legacy_dvb_audio.rst-1573-
Documentation/userspace-api/media/dvb/legacy_dvb_audio.rst:1574:write()
Documentation/userspace-api/media/dvb/legacy_dvb_audio.rst-1575--------
--
Documentation/userspace-api/media/dvb/legacy_dvb_video.rst=2344=Return Value
--
Documentation/userspace-api/media/dvb/legacy_dvb_video.rst-2360-
Documentation/userspace-api/media/dvb/legacy_dvb_video.rst:2361:write()
Documentation/userspace-api/media/dvb/legacy_dvb_video.rst-2362--------
]

23/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 66547
							output: 18
							thoughts: 28
						

Thoughts:
Here's my thought process, summarized as you requested:

**Navigating the Codebase: The Search for 'write'**

Okay, so I see this `write` function mentioned. Hmm, it's apparently defined in `sys.txt`. Right, that makes sense. Let's see... my immediate next step is to actually go read that `sys.txt` file. I need to understand *how* `write` is implemented. I'm going to scan the contents of that file and do a direct string search for "write(". That opening parenthesis is crucial; it helps me distinguish between the function itself and any references to the word "write" that might be just text. This will help me narrow down the specific function definition I'm looking for. Let's see what's in there.



24/2 2026/03/09 22:46 tool read-description
0m Args:
map[File:sys.txt]

Results:
map[Output:# Copyright 2015 syzkaller project authors. All rights reserved.
# Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

# Description of syscall arguments. See README.md for details.

include <linux/socket.h>
include <linux/ptrace.h>
include <linux/resource.h>
include <linux/stat.h>
include <linux/mman.h>
include <linux/time.h>
include <linux/mount.h>
include <linux/fs.h>
include <linux/eventpoll.h>
include <linux/signalfd.h>
include <linux/eventfd.h>
include <linux/timerfd.h>
include <linux/personality.h>
include <linux/wait.h>
include <linux/user.h>
include <linux/un.h>
include <linux/ioctl.h>
include <linux/fadvise.h>
include <linux/falloc.h>
include <linux/kexec.h>
include <linux/elf.h>
include <linux/fiemap.h>
include <linux/kd.h>
include <linux/vt.h>
include <linux/if_alg.h>
include <linux/nfc.h>
include <linux/sockios.h>
include <linux/net_tstamp.h>
include <linux/termios.h>
include <linux/fcntl.h>
include <linux/sched.h>
include <linux/mqueue.h>
include <linux/mempolicy.h>
include <linux/in.h>
include <linux/ip.h>
include <linux/tcp.h>
include <linux/udp.h>
include <linux/kcmp.h>
include <linux/nfs.h>
include <linux/syslog.h>
include <linux/exportfs.h>
include <linux/splice.h>
include <linux/filelock.h>
include <fs/overlayfs/overlayfs.h>
include <uapi/linux/memfd.h>
include <uapi/linux/module.h>
include <linux/ioprio.h>
include <linux/membarrier.h>
include <uapi/linux/kcov.h>
include <uapi/linux/membarrier.h>
include <uapi/linux/capability.h>
include <uapi/linux/seccomp.h>
include <uapi/linux/wait.h>
include <uapi/linux/watch_queue.h>
include <kernel/sched/sched.h>
include <uapi/linux/close_range.h>
include <uapi/linux/netfilter/xt_cgroup.h>
include <fs/smb/client/cifsglob.h>
include <xen/interface/io/xs_wire.h>
include <uapi/linux/prctl.h>
include <asm/prctl.h>
include <linux/reboot.h>
include <linux/swap.h>

resource fd[int32]: -1
resource fd_dir[fd]: AT_FDCWD

# alignptr/align32/align64/padto64 can be used when ABI uses int64/intptr to hold a smaller type.
# E.g. pid/uid stored as intptr/int64.
type alignptr[T] {
	v	T
} [align[PTR_SIZE]]

type align32[T] {
	v	T
} [align[4]]

type align64[T] {
	v	T
} [align[8]]

type padto32[T] {
	v	T
} [size[4]]

type padto64[T] {
	v	T
} [size[8]]

type signalno int32[0:65]
type signalnoptr intptr[0:65]

# syz_execute_func caused multiple problems:
# 1. First it lead to corpus explosion. The program used existing values in registers
# to pollute output area. We tried to zero registers (though, not reliably).
# 2. It lead to explosion again. The exact mechanics are unknown, here is one sample:
# syz_execute_func(&(0x7f0000000440)="f2af91930f0124eda133fa20430fbafce842f66188d0d4
#	430fc7f314c1ab5bf9e2f9660f3a0fae5e090000ba023c1fb63ac4817d73d74ec482310d46f44
#	9f216c863fa438036a91bdbae95aaaa420f383c02c401405c6bfd49d768d768f833fefbab6464
#	660f38323c8f26dbc1a1fe5ff6f6df0804f4c4efa59c0f01c4288ba6452e000054c4431d5cc100")
# 3. The code can also execute syscalls (and it is know to), but it's not subject to
# target.SanitizeCall. As the result it can do things that programs are not supposed to do.
# 4. Besides linux, corpus explosion also happens on freebsd and is clearly attributable
# to syz_execute_func based on corpus contents. Mechanics are also not known.
# It also did not cause finding of any new bugs (at least not that I know of).
# So it's disabled on all OSes until we figure out how to resolve all these problems.
syz_execute_func(text ptr[in, text[target]]) (disabled)

# Exclude /sys/power/state as reported in https://lkml.org/lkml/2021/5/27/653
openat$sysfs(fd const[AT_FDCWD], dir ptr[in, glob["/sys/**/*:-/sys/power/state"]], flags flags[open_flags], mode flags[open_mode]) fd

open(file ptr[in, filename], flags flags[open_flags], mode flags[open_mode]) fd (automatic_helper)
# Just so that we have something that creates fd_dir resources.
open$dir(file ptr[in, filename], flags flags[open_flags], mode flags[open_mode]) fd_dir (automatic_helper)
openat$dir(fd const[AT_FDCWD], file ptr[in, filename], flags flags[open_flags], mode flags[open_mode]) fd_dir (automatic_helper)
openat(fd fd_dir[opt], file ptr[in, filename], flags flags[open_flags], mode flags[open_mode]) fd
openat2$dir(fd const[AT_FDCWD], file ptr[in, filename], how ptr[in, open_how], size bytesize[how]) fd_dir (automatic_helper)
openat2(fd fd_dir[opt], file ptr[in, filename], how ptr[in, open_how], size bytesize[how]) fd
creat(file ptr[in, filename], mode flags[open_mode]) fd
close(fd fd)
read(fd fd, buf buffer[out], count len[buf])
pread64(fd fd, buf buffer[out], count len[buf], pos fileoff)
readv(fd fd, vec ptr[in, array[iovec_out]], vlen len[vec])
preadv(fd fd, vec ptr[in, array[iovec_out]], vlen len[vec], off_low int32, off_high int32)
preadv2(fd fd, vec ptr[in, array[iovec_out]], vlen len[vec], off_low int32, off_high int32, flags flags[rwf_flags])
write(fd fd, buf buffer[in], count len[buf])
pwrite64(fd fd, buf buffer[in], count len[buf], pos fileoff)
writev(fd fd, vec ptr[in, array[iovec_in]], vlen len[vec])
pwritev(fd fd, vec ptr[in, array[iovec_in]], vlen len[vec], off_low int32, off_high int32)
pwritev2(fd fd, vec ptr[in, array[iovec_in]], vlen len[vec], off_low int32, off_high int32, flags flags[rwf_flags])
# lseek can return negative offsets when the file has FMODE_UNSIGNED_OFFSET flag:
# https://elixir.bootlin.com/linux/v6.11-rc7/source/fs/read_write.c#L56
# It's unclear how it's then even possible to distinguish error from valid offset, but it's not our problem.
# We just have to ignore return values of lseek.
lseek(fd fd, offset fileoff, whence flags[seek_whence]) (ignore_return)
copy_file_range(fd_in fd, off_in ptr[inout, fileoff[int64], opt], fd_out fd, off_out ptr[inout, fileoff[int64], opt], len intptr, flags flags[copy_file_range_flags])

rwf_flags = RWF_DSYNC, RWF_HIPRI, RWF_SYNC, RWF_NOWAIT, RWF_APPEND
copy_file_range_flags = 0

dup(oldfd fd) fd
dup2(oldfd fd, newfd fd) fd
dup3(oldfd fd, newfd fd, flags flags[dup_flags]) fd

pipe(pipefd ptr[out, pipefd])
pipe2(pipefd ptr[out, pipefd], flags flags[pipe_flags])

tee(fdin fd, fdout fd, len intptr, f flags[splice_flags])
splice(fdin fd, offin ptr[in, fileoff[int64]], fdout fd, offout ptr[in, fileoff[int64]], len intptr, f flags[splice_flags])
vmsplice(fd fd, vec ptr[in, array[iovec_in]], vlen len[vec], f flags[splice_flags])
sendfile(fdout fd, fdin fd, off ptr[inout, fileoff[intptr], opt], count intptr)
sendfile64(fdout fd, fdin fd, off ptr[inout, fileoff[int64], opt], count intptr)

cachestat_range {
	off	fileoff[int64]
	len	int64
}

cachestat {
	nr_cache		int64
	nr_dirty		int64
	nr_writeback		int64
	nr_evicted		int64
	nr_recently_evicted	int64
}

stat(file ptr[in, filename], statbuf ptr[out, stat])
lstat(file ptr[in, filename], statbuf ptr[out, stat])
fstat(fd fd, statbuf ptr[out, stat])
newfstatat(dfd const[AT_FDCWD], file ptr[in, filename], statbuf ptr[out, stat], flag flags[statx_flags])
stat64(file ptr[in, filename], statbuf ptr[out, stat64])
lstat64(file ptr[in, filename], statbuf ptr[out, stat64])
fstat64(fd fd, statbuf ptr[out, stat64])
fstatat64(dfd const[AT_FDCWD], file ptr[in, filename], statbuf ptr[out, stat64], flag flags[statx_flags])
statx(fd fd_dir, file ptr[in, filename], flags flags[statx_flags], mask flags[statx_mask], statxbuf ptr[out, statx])
cachestat(fd fd, cstat_range ptr[in, cachestat_range], cstat ptr[out, cachestat], flags const[0])

poll(fds ptr[in, array[pollfd]], nfds len[fds], timeout int32)
ppoll(fds ptr[in, array[pollfd]], nfds len[fds], tsp ptr[in, timespec], sigmask ptr[in, sigset_t], size len[sigmask])
select(n len[inp], inp ptr[inout, fd_set], outp ptr[inout, fd_set], exp ptr[inout, fd_set], tvp ptr[inout, timeval])
pselect6(n len[inp], inp ptr[inout, fd_set], outp ptr[inout, fd_set], exp ptr[inout, fd_set], tvp ptr[inout, timespec], sig ptr[in, sigset_size])

resource fd_epoll[fd]
epoll_create(size int32) fd_epoll
epoll_create1(flags flags[epoll_flags]) fd_epoll
epoll_ctl$EPOLL_CTL_ADD(epfd fd_epoll, op const[EPOLL_CTL_ADD], fd fd, ev ptr[in, epoll_event])
epoll_ctl$EPOLL_CTL_MOD(epfd fd_epoll, op const[EPOLL_CTL_MOD], fd fd, ev ptr[in, epoll_event])
epoll_ctl$EPOLL_CTL_DEL(epfd fd_epoll, op const[EPOLL_CTL_DEL], fd fd)
epoll_wait(epfd fd_epoll, events ptr[out, array[epoll_event]], maxevents len[events], timeout int32)
epoll_pwait(epfd fd_epoll, events ptr[out, array[epoll_event]], maxevents len[events], timeout int32, sigmask ptr[in, sigset_t], size bytesize[sigmask])
epoll_pwait2(epfd fd_epoll, events ptr[out, array[epoll_event]], maxevents len[events], timeout ptr[in, timespec], sigmask ptr[in, sigset_t], size bytesize[sigmask])

resource fd_timer[fd]
signalfd(fd fd, mask ptr[in, sigset_t], size len[mask]) fd
signalfd4(fd fd, mask ptr[in, sigset_t], size len[mask], flags flags[signalfd_flags]) fd
timerfd_create(clockid flags[clock_type], flags flags[timerfd_create_flags]) fd_timer
timerfd_settime(fd fd_timer, flags flags[timerfd_settime_flags], new ptr[in, itimerspec], old ptr[out, itimerspec])
timerfd_gettime(fd fd_timer, cur ptr[out, itimerspec])
ioctl$TFD_IOC_SET_TICKS(fd fd_timer, cmd const[TFD_IOC_SET_TICKS], arg ptr[in, int64])

resource fd_event[fd]
eventfd(initval int32) fd_event
eventfd2(initval int32, flags flags[eventfd_flags]) fd_event
read$eventfd(fd fd_event, val ptr[out, int64], len len[val])
write$eventfd(fd fd_event, val ptr[in, int64], len len[val])

brk(brk intptr)
mmap(addr vma, len len[addr], prot flags[mmap_prot], flags flags[mmap_flags], fd fd, offset intptr[0:0xffffffff, 0x1000])
munmap(addr vma, len len[addr])
mremap(addr vma, len len[addr], newlen len[newaddr], flags flags[mremap_flags], newaddr vma)
remap_file_pages(addr vma, size len[addr], prot flags[mmap_prot], pgoff intptr, flags flags[mmap_flags])
mprotect(addr vma, len len[addr], prot flags[mmap_prot])
msync(addr vma, len len[addr], f flags[msync_flags])
madvise(addr vma, len len[addr], advice flags[madvise_flags])
process_madvise(pidfd fd_pidfd, vec ptr[in, array[iovec_in]], vlen len[vec], advice flags[madvise_flags], flags const[0])
process_mrelease(pidfd fd_pidfd, flags const[0])
fadvise64(fd fd, offset fileoff, len intptr, advice flags[fadvise_flags])
readahead(fd fd, off intptr, count intptr)
mbind(addr vma, len len[addr], mode flags[mbind_mode], nodemask ptr[in, int64], maxnode intptr, flags flags[mbind_flags])
move_pages(pid pid, nr len[pages], pages ptr[in, array[vma]], nodes ptr[in, array[int32], opt], status ptr[out, array[int32]], flags flags[move_pages_flags])
migrate_pages(pid pid, maxnode intptr, old ptr[in, int64], new ptr[in, int64])
set_mempolicy(mode flags[mbind_mode], nodemask ptr[in, int64], maxnode intptr)
get_mempolicy(mode ptr[out, int32], nodemask ptr[out, int64], maxnode intptr, addr vma, flags flags[mempolicy_flags])
set_mempolicy_home_node(addr vma, len len[addr], home_node intptr[0:3], flags const[0])
mincore(addr vma, size len[addr], vec buffer[out])
mlock(addr vma, size len[addr])
mlock2(addr vma, size len[addr], flags flags[mlock_flags])
munlock(addr vma, size len[addr])
mlockall(flags flags[mlockall_flags])
munlockall()
kcmp(pid1 pid, pid2 pid, type flags[kcmp_flags], fd1 fd, fd2 fd)
kcmp$KCMP_EPOLL_TFD(pid1 pid, pid2 pid, type const[KCMP_EPOLL_TFD], fd1 fd, idx2 ptr[in, kcmp_epoll_slot])

resource fd_memfd[fd]
memfd_create(name ptr[in, string], flags flags[memfd_flags]) fd_memfd
memfd_flags = MFD_CLOEXEC, MFD_ALLOW_SEALING, MFD_HUGETLB
_ = MFD_HUGE_SHIFT, MFD_HUGE_MASK, MFD_HUGE_64KB, MFD_HUGE_512KB, MFD_HUGE_1MB, MFD_HUGE_2MB, MFD_HUGE_8MB, MFD_HUGE_16MB

memfd_secret(flags flags[memfd_secret_flags]) fd
memfd_secret_flags = O_CLOEXEC

resource pkey[int32]: -1
pkey_alloc(flags const[0], val flags[pkey_flags]) pkey
pkey_free(key pkey)
pkey_mprotect(addr vma, len len[addr], prot flags[mmap_prot], key pkey)
syz_pkey_set(key pkey, val flags[pkey_flags])

pkey_flags = PKEY_DISABLE_ACCESS, PKEY_DISABLE_WRITE

restart_syscall()

# Almighty!
ioctl(fd fd, cmd int32, arg buffer[in])

ioctl$int_in(fd fd, cmd flags[ioctl_int_in], v ptr[in, int64])
ioctl$int_out(fd fd, cmd flags[ioctl_int_out], v ptr[out, intptr])

ioctl$FIOCLEX(fd fd, cmd const[FIOCLEX])
ioctl$FIONCLEX(fd fd, cmd const[FIONCLEX])
ioctl$FITHAW(fd fd, cmd const[FITHAW])

# FIFREEZE is enabled in sandbox mode only because it can easily kill the machine.
ioctl$FIFREEZE(fd fd, cmd const[FIFREEZE]) (snapshot)

fcntl$dupfd(fd fd, cmd flags[fcntl_dupfd], arg fd) fd
fcntl$getflags(fd fd, cmd flags[fcntl_getflags])
fcntl$setflags(fd fd, cmd const[F_SETFD], flags flags[fcntl_flags])
fcntl$setstatus(fd fd, cmd const[F_SETFL], flags flags[fcntl_status])
fcntl$lock(fd fd, cmd flags[fcntl_lock], lock ptr[in, flock])
fcntl$getown(fd fd, cmd const[F_GETOWN]) pid (automatic_helper)
fcntl$setown(fd fd, cmd const[F_SETOWN], pid pid)
fcntl$getownex(fd fd, cmd const[F_GETOWN_EX], arg ptr[out, f_owner_ex])
fcntl$setownex(fd fd, cmd const[F_SETOWN_EX], arg ptr[in, f_owner_ex])
fcntl$setsig(fd fd, cmd const[F_SETSIG], sig signalnoptr)
fcntl$setlease(fd fd, cmd const[F_SETLEASE], typ flags[flock_type])
fcntl$notify(fd fd, cmd const[F_NOTIFY], typ flags[fcntl_notify])
fcntl$setpipe(fd fd, cmd const[F_SETPIPE_SZ], sz intptr)
fcntl$addseals(fd fd, cmd const[F_ADD_SEALS], seals flags[seal_types])
fcntl$F_GET_RW_HINT(fd fd, cmd const[F_GET_RW_HINT], hint ptr[out, int64])
fcntl$F_GET_FILE_RW_HINT(fd fd, cmd const[F_GET_FILE_RW_HINT], hint ptr[out, int64])
fcntl$F_SET_RW_HINT(fd fd, cmd const[F_SET_RW_HINT], hint ptr[in, flags[fcntl_rw_hint, int64]])
fcntl$F_SET_FILE_RW_HINT(fd fd, cmd const[F_SET_FILE_RW_HINT], hint ptr[in, flags[fcntl_rw_hint, int64]])

# Only some commands break return values.
# When/if we have stricter enforcement of arguments, we may remove some of breaks_returns attributes.
ptrace(req flags[ptrace_req], pid pid) (breaks_returns)
ptrace$peek(req flags[ptrace_req_peek], pid pid, addr ptr[out, intptr]) (breaks_returns)
ptrace$poke(req flags[ptrace_req_poke], pid pid, addr ptr[out, intptr], data intptr) (breaks_returns)
ptrace$peekuser(req const[PTRACE_PEEKUSR], pid pid, addr intptr) (breaks_returns)
ptrace$pokeuser(req const[PTRACE_POKEUSR], pid pid, addr intptr, data intptr) (breaks_returns)
ptrace$getregs(req flags[ptrace_req_getregs], pid pid, ignored intptr, data buffer[out]) (breaks_returns)
ptrace$getregset(req const[PTRACE_GETREGSET], pid pid, what flags[pthread_regset], data ptr[in, iovec_out]) (breaks_returns)
ptrace$setregs(req flags[ptrace_req_setregs], pid pid, ignored intptr, data buffer[in]) (breaks_returns)
ptrace$setregset(req const[PTRACE_SETREGSET], pid pid, what flags[pthread_regset], data ptr[in, iovec_in]) (breaks_returns)
ptrace$getsig(req const[PTRACE_GETSIGINFO], pid pid, ignored intptr, data ptr[out, siginfo]) (breaks_returns)
ptrace$setsig(req const[PTRACE_SETSIGINFO], pid pid, ignored intptr, data ptr[in, siginfo]) (breaks_returns)
ptrace$setopts(req flags[ptrace_req_setopts], pid pid, ignored intptr, flags flags[ptrace_options]) (breaks_returns)
ptrace$getenv(req const[PTRACE_GETEVENTMSG], pid pid, ignored intptr, data ptr[out, intptr]) (breaks_returns)
ptrace$cont(req flags[ptrace_req_cont], pid pid, ignored intptr, data intptr) (breaks_returns)
ptrace$PTRACE_SECCOMP_GET_FILTER(req const[PTRACE_SECCOMP_GET_FILTER], pid pid, addr intptr, data ptr[out, array[int8]]) (breaks_returns)
ptrace$PTRACE_SECCOMP_GET_METADATA(req const[PTRACE_SECCOMP_GET_METADATA], pid pid, addr len[data], data ptr[in, seccomp_metadata]) (breaks_returns)
ptrace$PTRACE_SETSIGMASK(req const[PTRACE_SETSIGMASK], pid pid, size bytesize[data], data ptr[in, sigset_t]) (breaks_returns)
ptrace$PTRACE_GETSIGMASK(req const[PTRACE_GETSIGMASK], pid pid, size bytesize[data], data ptr[out, sigset_t]) (breaks_returns)
ptrace$ARCH_GET_FS(req const[PTRACE_ARCH_PRCTL], pid pid, arg ptr[out, intptr], code const[ARCH_GET_FS]) (breaks_returns)
ptrace$ARCH_GET_GS(req const[PTRACE_ARCH_PRCTL], pid pid, arg ptr[out, intptr], code const[ARCH_GET_GS]) (breaks_returns)
ptrace$ARCH_SET_GS(req const[PTRACE_ARCH_PRCTL], pid pid, arg ptr[out, intptr], code const[ARCH_SET_GS]) (breaks_returns)
ptrace$ARCH_GET_CPUID(req const[PTRACE_ARCH_PRCTL], pid pid, arg const[0], code const[ARCH_GET_CPUID]) (breaks_returns)
ptrace$ARCH_SET_CPUID(req const[PTRACE_ARCH_PRCTL], pid pid, arg boolptr, code const[ARCH_SET_CPUID]) (breaks_returns)
ptrace$ARCH_MAP_VDSO_X32(req const[PTRACE_ARCH_PRCTL], pid pid, arg intptr, code const[ARCH_MAP_VDSO_X32]) (breaks_returns)
ptrace$ARCH_MAP_VDSO_32(req const[PTRACE_ARCH_PRCTL], pid pid, arg intptr, code const[ARCH_MAP_VDSO_32]) (breaks_returns)
ptrace$ARCH_MAP_VDSO_64(req const[PTRACE_ARCH_PRCTL], pid pid, arg intptr, code const[ARCH_MAP_VDSO_64]) (breaks_returns)
ptrace$ARCH_SHSTK_STATUS(req const[PTRACE_ARCH_PRCTL], pid pid, res ptr[out, intptr], cmd const[ARCH_SHSTK_STATUS]) (breaks_returns)
ptrace$ARCH_SHSTK_LOCK(req const[PTRACE_ARCH_PRCTL], pid pid, features flags[shadow_stack_features], cmd const[ARCH_SHSTK_LOCK]) (breaks_returns)
ptrace$ARCH_SHSTK_UNLOCK(req const[PTRACE_ARCH_PRCTL], pid pid, features flags[shadow_stack_features], cmd const[ARCH_SHSTK_UNLOCK]) (breaks_returns)
ptrace$ARCH_SHSTK_ENABLE(req const[PTRACE_ARCH_PRCTL], pid pid, features flags[shadow_stack_features], cmd const[ARCH_SHSTK_ENABLE]) (breaks_returns)
ptrace$ARCH_SHSTK_DISABLE(req const[PTRACE_ARCH_PRCTL], pid pid, features flags[shadow_stack_features], cmd const[ARCH_SHSTK_DISABLE]) (breaks_returns)
ptrace$ARCH_GET_UNTAG_MASK(req const[PTRACE_ARCH_PRCTL], pid pid, arg ptr[out, intptr], cmd const[ARCH_GET_UNTAG_MASK]) (breaks_returns)
ptrace$ARCH_GET_MAX_TAG_BITS(req const[PTRACE_ARCH_PRCTL], pid pid, arg ptr[out, intptr], cmd const[ARCH_GET_MAX_TAG_BITS]) (breaks_returns)
ptrace$ARCH_ENABLE_TAGGED_ADDR(req const[PTRACE_ARCH_PRCTL], pid pid, arg intptr[1:6], cmd const[ARCH_ENABLE_TAGGED_ADDR]) (breaks_returns)
ptrace$ARCH_FORCE_TAGGED_SVA(req const[PTRACE_ARCH_PRCTL], pid pid, arg const[0], cmd const[ARCH_FORCE_TAGGED_SVA]) (breaks_returns)

map_shadow_stack(addr vma, size bytesize[addr], flags boolptr)

seccomp_metadata {
	filter_off	int64
	flags		const[0, int64]
}

ptrace_peeksiginfo_args {
	off	int64
	flags	flags[ptrace_peeksiginfo_flags, int32]
	nr	len[syscall:data, int32]
}

ptrace$peeksig(req const[PTRACE_PEEKSIGINFO], pid pid, args ptr[in, ptrace_peeksiginfo_args], data ptr[out, array[siginfo]])

capget(hdr ptr[in, cap_header], data ptr[in, cap_data])
capset(hdr ptr[in, cap_header], data ptr[in, cap_data])

resource fd_mq[fd]
mq_open(name ptr[in, string], flags flags[mq_open_flags], mode flags[open_mode], attr ptr[in, mq_attr]) fd_mq
mq_timedsend(mqd fd_mq, msg buffer[in], msglen len[msg], prio intptr, timeout ptr[in, timespec, opt])
mq_timedreceive(mqd fd_mq, msg buffer[out], msglen len[msg], prio intptr, timeout ptr[in, timespec, opt])
mq_notify(mqd fd_mq, notif ptr[in, sigevent])
mq_getsetattr(mqd fd_mq, attr ptr[in, mq_attr], oldattr ptr[out, mq_attr, opt])
mq_unlink(name ptr[in, string])

mknod(file ptr[in, filename], mode flags[mknod_mode], dev int32)
mknod$loop(file ptr[in, filename], mode flags[mknod_mode], dev proc[1792, 2])
mknodat$loop(dirfd fd_dir, file ptr[in, filename], mode flags[mknod_mode], dev proc[1792, 2])
mknodat$null(dirfd fd_dir, file ptr[in, filename], mode flags[mknod_mode], dev const[0x103])
mknodat(dirfd fd_dir, file ptr[in, filename], mode flags[mknod_mode], dev int32)
chmod(file ptr[in, filename], mode flags[open_mode])
fchmod(fd fd, mode flags[open_mode])
fchmodat(dirfd fd_dir, file ptr[in, filename], mode flags[open_mode])
chown(file ptr[in, filename], uid uid, gid gid)
lchown(file ptr[in, filename], uid uid, gid gid)
fchown(fd fd, uid uid, gid gid)
fchownat(dirfd fd_dir, file ptr[in, filename], uid uid, gid gid, flags flags[at_flags])
fallocate(fd fd, mode flags[fallocate_mode], off intptr, len intptr)
faccessat(dirfd fd_dir, pathname ptr[in, filename], mode flags[open_mode])
faccessat2(dirfd fd_dir, pathname ptr[in, filename], mode flags[open_mode], flags flags[faccessat_flags])
utime(filename ptr[in, filename], times ptr[in, utimbuf])
utimes(filename ptr[in, filename], times ptr[in, itimerval])
futimesat(dir fd_dir, pathname ptr[in, filename], times ptr[in, itimerval])
utimensat(dir fd_dir, pathname ptr[in, filename], times ptr[in, itimerval], flags flags[utimensat_flags])

# Small trick - syzkaller cannot give the proper stack pointer to clone(), but we can do it with the aid of pseudo syscalls.
syz_clone(flags flags[clone_flags], stack buffer[in], stack_len bytesize[stack], parentid ptr[out, int32], childtid ptr[out, int32], tls buffer[in]) pid (automatic_helper)

syz_clone3(args ptr[in, clone_args], size bytesize[args]) pid (automatic_helper)

# We need these disabled definitions to simplify the presence and the NR checking.
clone(flags flags[clone_flags], sp buffer[in], parentid ptr[out, int32], childtid ptr[out, int32], tls buffer[in]) (breaks_returns, disabled)
clone3(args ptr[in, clone_args], size bytesize[args]) pid (breaks_returns, disabled)

clone_args {
	flags		flags[clone3_flags, int64]
	pidfd		ptr64[out, fd_pidfd]
	child_tid	ptr64[out, pid]
	parent_tid	ptr64[out, pid]
	exit_signal	align64[signalno]
	stack		ptr64[out, array[int8]]
	stack_size	bytesize[stack, int64]
	tls		ptr64[out, array[int8]]
	set_tid		ptr64[in, array[pid]]
	set_tid_size	len[set_tid, int64]
	cgroup		align64[fd_cgroup]
}

resource pid[int32]: 0, -1
resource uid[int32]: 0, -1, 0xee00, 0xee01
resource gid[int32]: 0, -1, 0xee00, 0xee01

getgid() gid (automatic_helper)
getegid() gid (automatic_helper)
setuid(uid uid)
setgid(gid gid)
getuid() uid (automatic_helper)
geteuid() uid (automatic_helper)
setpgid(pid pid, pgid pid)
getpgid(pid pid) pid (automatic_helper)
getpgrp(pid pid) pid (automatic_helper)
getpid() pid (automatic_helper)
gettid() pid (automatic_helper)
setreuid(ruid uid, euid uid)
setregid(rgid gid, egid gid)
setresuid(ruid uid, euid uid, suid uid)
setresgid(rgid gid, egid gid, sgid gid)
getresuid(ruid ptr[out, uid], euid ptr[out, uid], suid ptr[out, uid])
getresgid(rgid ptr[out, gid], egid ptr[out, gid], sgid ptr[out, gid])
setfsuid(fsuid uid)
setfsgid(fsgid gid)
getgroups(size len[list], list ptr[inout, array[gid]])
setgroups(size len[list], list ptr[in, array[gid]])
personality(persona flags[personality_flags])
# Don't mess with parent (fuzzer). If we ptrace attach to it, it will hang.
# If we setrlimit for parent, it will misbehave. Killing - the same. Nothing good.
#getppid() pid
#getsid(pid pid) pid
#setsid() pid

link(old ptr[in, filename], new ptr[in, filename])
linkat(oldfd fd_dir, old ptr[in, filename], newfd fd_dir, new ptr[in, filename], flags flags[linkat_flags])
symlinkat(old ptr[in, filename], newfd fd_dir, new ptr[in, filename])
symlink(old ptr[in, filename], new ptr[in, filename])
unlink(path ptr[in, filename])
unlinkat(fd fd_dir, path ptr[in, filename], flags flags[unlinkat_flags])
readlink(path ptr[in, filename], buf buffer[out], siz len[buf])
readlinkat(fd fd_dir, path ptr[in, filename], buf buffer[out], siz len[buf])
rename(old ptr[in, filename], new ptr[in, filename])
renameat(oldfd fd_dir, old ptr[in, filename], newfd fd_dir, new ptr[in, filename])
renameat2(oldfd fd_dir, old ptr[in, filename], newfd fd_dir, new ptr[in, filename], flags flags[renameat2_flags])
mkdir(path ptr[in, filename], mode flags[open_mode])
mkdirat(fd fd_dir[opt], path ptr[in, filename], mode flags[open_mode])
rmdir(path ptr[in, filename])
truncate(file ptr[in, filename], len intptr)
ftruncate(fd fd, len intptr)
flock(fd fd, op flags[flock_op])
fsync(fd fd)
fdatasync(fd fd)
sync()
syncfs(fd fd)
sync_file_range(fd fd, off intptr, nbytes intptr, flags flags[sync_file_flags])
lookup_dcookie(cookie intptr, buf buffer[out], len len[buf])
getdents(fd fd_dir, ent buffer[out], count len[ent])
getdents64(fd fd_dir, ent buffer[out], count len[ent])
name_to_handle_at(fd fd_dir, file ptr[in, filename], handle ptr[in, file_handle], mnt ptr[out, int32], flags flags[name_to_handle_at_flags])
open_by_handle_at(mountdirfd fd, handle ptr[in, file_handle], flags flags[open_flags])
chroot(dir ptr[in, filename])
getcwd(buf buffer[out], size len[buf])
chdir(dir ptr[in, filename])
fchdir(fd fd)
pivot_root(new_root ptr[in, filename], put_old ptr[in, filename])

sysfs$1(option const[1], fsname ptr[in, string])
sysfs$2(option const[2], fsindex intptr, fsname buffer[out])
sysfs$3(option const[3])
statfs(path ptr[in, filename], buf buffer[out])
fstatfs(fd fd, buf buffer[out])

uselib(lib ptr_binfmt_file)
init_module(mod ptr[in, binfmt_elf64], len len[mod], args ptr[in, string])
finit_module(fd fd_binfmt, args ptr[in, string], flags flags[finit_module_flags])
delete_module(name ptr[in, string], flags flags[delete_module_flags])
kexec_load(entry intptr, nr_segments len[segments], segments ptr[in, array[kexec_segment]], flags flags[kexec_load_flags])
syslog(cmd flags[syslog_cmd], buf ptr[out, array[int8], opt], len len[buf])
uname(buf buffer[out])
sysinfo(info buffer[out])
ustat(dev intptr, buf ptr[out, ustat])
acct(filename ptr[in, filename, opt])

getrusage(who flags[rusage_who], usage ptr[out, rusage])
getrlimit(res flags[rlimit_type], rlim ptr[out, rlimit])
setrlimit(res flags[rlimit_type], rlim ptr[in, rlimit])
prlimit64(pid pid, res flags[rlimit_type], new ptr[in, rlimit, opt], old ptr[out, rlimit, opt])

iopl(level int8)
ioperm(from intptr, num intptr, on intptr)
ioprio_get$pid(which flags[ioprio_which_pid], who pid)
ioprio_get$uid(which flags[ioprio_which_uid], who uid)
ioprio_set$pid(which flags[ioprio_which_pid], who pid, ioprio flags[ioprio_priorities])
ioprio_set$uid(which flags[ioprio_which_uid], who uid, ioprio flags[ioprio_priorities])

# NEED: we can express the construction of integers using structs with flags
# and bitfields, which are normally obtained using a combination of bitwise
# operations with the help of macros. However, structs can't be directly passed
# as a syscall argument; therefore, such constructions can't be directly passed either.
# One example is ioprio argument for ioprio_set, where we could have expressed the
# construction less messy. For now, some subset of valid values are enumerated as
# in ioprio_priorities.

# ioprio priority values are obtained using IOPRIO_PRIO_VALUE(class, data) macro.
# the behaviour of the macro is mimicked below and some priority values are enumerated.
ioprio_priorities = IOPRIO_CLASS_NONE_PRIO, IOPRIO_CLASS_IDLE_PRIO, IOPRIO_CLASS_RT_HIGH_PRIO, IOPRIO_CLASS_BE_HIGH_PRIO, IOPRIO_CLASS_RT_MID_PRIO, IOPRIO_CLASS_BE_MID_PRIO, IOPRIO_CLASS_RT_LOW_PRIO, IOPRIO_CLASS_BE_LOW_PRIO

# The classes RT and BE take data values from the range [0:7]. Use a subset of the available
# values (0, 4, 7) to ease collisions, and to avoid redundancy. The classes NONE and IDLE
# have only one valid priority value each with data set to 0.
define IOPRIO_CLASS_NONE_PRIO	(IOPRIO_CLASS_NONE << IOPRIO_CLASS_SHIFT)
define IOPRIO_CLASS_IDLE_PRIO	(IOPRIO_CLASS_IDLE << IOPRIO_CLASS_SHIFT)
define IOPRIO_CLASS_RT_HIGH_PRIO	(IOPRIO_CLASS_RT << IOPRIO_CLASS_SHIFT)
define IOPRIO_CLASS_BE_HIGH_PRIO	(IOPRIO_CLASS_BE << IOPRIO_CLASS_SHIFT)
define IOPRIO_CLASS_RT_MID_PRIO	((IOPRIO_CLASS_RT << IOPRIO_CLASS_SHIFT) + 4)
define IOPRIO_CLASS_BE_MID_PRIO	((IOPRIO_CLASS_BE << IOPRIO_CLASS_SHIFT) + 4)
define IOPRIO_CLASS_RT_LOW_PRIO	((IOPRIO_CLASS_RT << IOPRIO_CLASS_SHIFT) + 7)
define IOPRIO_CLASS_BE_LOW_PRIO	((IOPRIO_CLASS_BE << IOPRIO_CLASS_SHIFT) + 7)

resource timerid[int32]
timer_create(id flags[clock_id], ev ptr[in, sigevent], timerid ptr[out, timerid])
timer_gettime(timerid timerid, setting ptr[out, itimerspec])
timer_getoverrun(timerid timerid)
timer_settime(timerid timerid, flags flags[timer_flags], new ptr[in, itimerspec], old ptr[out, itimerspec, opt])
timer_delete(timerid timerid)

time(t ptr[out, intptr])
clock_gettime(id flags[clock_id], tp ptr[out, timespec])
clock_settime(id flags[clock_id], tp ptr[in, timespec])
clock_adjtime(id flags[clock_id], tx ptr[in, timex])
clock_getres(id flags[clock_id], tp ptr[out, timespec])
clock_nanosleep(id flags[clock_id], flags flags[timer_flags], rqtp ptr[in, timespec], rmtp ptr[out, timespec, opt])
rt_sigaction(sig signalno, act ptr[in, sigaction], oact ptr[out, sigaction, opt], sigsetsize len[fake], fake ptr[out, sigset_t])
rt_sigprocmask(how flags[sigprocmask_how], nset ptr[in, sigset_t], oset ptr[out, sigset_t, opt], sigsetsize len[nset])
rt_sigreturn()
rt_sigpending(set ptr[out, sigset_t], sigsetsize len[set])
rt_sigtimedwait(these ptr[in, sigset_t], info ptr[out, siginfo, opt], ts ptr[in, timespec], sigsetsize len[these])
rt_sigsuspend(new ptr[in, sigset_t], sigsetsize len[new])
rt_sigqueueinfo(pid pid, sig signalno, info ptr[in, siginfo])
rt_tgsigqueueinfo(gid pid, tid pid, sig signalno, info ptr[in, siginfo])
sigaltstack(ss ptr[in, sigaltstack], oss ptr[out, sigaltstack, opt])
tgkill(gid pid, tid pid, sig signalno)
tkill(tid pid, sig signalno)
pause()
alarm(seconds intptr)
nanosleep(req ptr[in, timespec], rem ptr[out, timespec, opt])
getitimer(which flags[getitimer_which], cur ptr[out, itimerval])
setitimer(which flags[getitimer_which], new ptr[in, itimerval], old ptr[out, itimerval, opt])
exit(code intptr)
exit_group(code intptr)
waitid(which flags[waitid_which], pid pid, infop ptr[out, siginfo, opt], options flags[wait_options], ru ptr[out, rusage, opt])
waitid$P_PIDFD(which const[P_PIDFD], pidfd fd_pidfd, infop ptr[out, siginfo, opt], options flags[wait_options], ru ptr[out, rusage, opt])
wait4(pid pid, status ptr[out, int32, opt], options flags[wait_options], ru ptr[out, rusage, opt])
times(buf ptr[out, tms])
# Can send signals to all processes (pid=-1) so it's enabled only in snapshot mode.
kill(pid pid, sig signalno) (snapshot)

set_thread_area(info ptr[in, user_desc])
get_thread_area(info ptr[in, user_desc])
modify_ldt$read(func const[0], buf buffer[out], len len[buf])
modify_ldt$write(func const[1], buf ptr[in, user_desc], len len[buf])
modify_ldt$read_default(func const[2], buf buffer[out], len len[buf])
modify_ldt$write2(func const[17], buf ptr[in, user_desc], len len[buf])
process_vm_readv(pid pid, loc_vec ptr[in, array[iovec_out]], loc_vlen len[loc_vec], rem_vec ptr[in, array[iovec_out]], rem_vlen len[rem_vec], flags const[0])
process_vm_writev(pid pid, loc_vec ptr[in, array[iovec_out]], loc_vlen len[loc_vec], rem_vec ptr[in, array[iovec_out]], rem_vlen len[rem_vec], flags const[0])
set_tid_address(tidptr ptr[out, int32])
getpriority(which flags[priority_which], who pid)
setpriority(which flags[priority_which], who pid, prio intptr)
sched_getscheduler(pid pid)
sched_setscheduler(pid pid, policy flags[sched_policy], prio ptr[in, int32])
sched_rr_get_interval(pid pid, tp ptr[out, timespec])
sched_getparam(pid pid, prio ptr[out, int32])
sched_setparam(pid pid, prio ptr[in, int32])
sched_getaffinity(pid pid, cpusetsize len[mask], mask ptr[out, int64])
sched_setaffinity(pid pid, cpusetsize len[mask], mask ptr[in, int64])
sched_getattr(pid pid, attr ptr[out, sched_attr], size len[attr], flags const[0])
sched_setattr(pid pid, attr ptr[in, sched_attr], flags const[0])
sched_yield()
getrandom(buf buffer[out], len len[buf], flags flags[getrandom_flags])

reboot(magic1 const[LINUX_REBOOT_MAGIC1], magic2 const[LINUX_REBOOT_MAGIC2], cmd flags[reboot_commands], arg const[0]) (snapshot)

reboot_commands = LINUX_REBOOT_CMD_RESTART, LINUX_REBOOT_CMD_HALT, LINUX_REBOOT_CMD_CAD_ON, LINUX_REBOOT_CMD_CAD_OFF, LINUX_REBOOT_CMD_POWER_OFF, LINUX_REBOOT_CMD_RESTART2, LINUX_REBOOT_CMD_SW_SUSPEND, LINUX_REBOOT_CMD_KEXEC

swapon(specialfile ptr[in, filename], swap_flags flags[swap_flags]) (snapshot)
swapoff(specialfile ptr[in, filename]) (snapshot)

swap_flags = SWAP_FLAG_PRIO_MASK, SWAP_FLAG_PREFER, SWAP_FLAG_DISCARD, SWAP_FLAG_DISCARD_ONCE, SWAP_FLAG_DISCARD_PAGES

sethostname(name ptr[in, array[int8]], len bytesize[name]) (snapshot)
setdomainname(name ptr[in, array[int8]], len bytesize[name]) (snapshot)

gettimeofday(tv ptr[out, timeval], tz ptr[out, timezone])
settimeofday(tv ptr[out, timeval], tz ptr[out, timezone]) (snapshot)
adjtimex(txc_p ptr[in, __kernel_timex]) (snapshot)

timezone {
	tz_minuteswest	int32
	tz_dsttime	int32
}

__kernel_timex {
	modes		flags[adjtimex_modes, int32]
	pad0		const[0, int32]
	offset		int64
	freq		int64
	maxerror	int64
	esterror	int64
	status		int32
	pad1		const[0, int32]
	constant	int64
	precision	int64
	tolerance	int64
	int		timeval
	tick		int64
	ppsfreq		int64
	jitter		int64
	shift		int32
	pad2		const[0, int32]
	stabil		int64
	jitcnt		int64
	calcnt		int64
	errcnt		int64
	stbcnt		int64
	tai		int32
	pad3		array[const[0, int32], 11]
}

adjtimex_modes = ADJ_OFFSET, ADJ_FREQUENCY, ADJ_MAXERROR, ADJ_ESTERROR, ADJ_STATUS, ADJ_TIMECONST, ADJ_TAI, ADJ_SETOFFSET, ADJ_MICRO, ADJ_NANO, ADJ_TICK

membarrier(cmd flags[membarrier_cmd], flags const[0])

membarrier_cmd = MEMBARRIER_CMD_GLOBAL, MEMBARRIER_CMD_GLOBAL_EXPEDITED, MEMBARRIER_CMD_PRIVATE_EXPEDITED, MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED, MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE, MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE, MEMBARRIER_CMD_QUERY, MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED, MEMBARRIER_CMD_SHARED

rseq(rseq ptr[in, rseq], rseq_len bytesize[rseq], flags boolptr, sig const[0])

rseq {
	cpu_id_start	const[0, int32]
	cpu_id		const[0, int32]
	rseq_cs		ptr64[in, rseq_cs, opt]
	flags		flags[rseq_cs_flags, int32]
} [align[32]]

rseq_cs {
	version			const[0, int32]
	flags			flags[rseq_cs_flags, int32]
	start_ip		int64
	post_commit_offset	int64
	abort_ip		int64
} [align[32]]

rseq_cs_flags = RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT, RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL, RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE

# start/end are unused for now, no definition of SYS_RISCV_FLUSH_ICACHE_LOCAL in uapi headers.
riscv_flush_icache(start const[0], end const[0], flags bool32)

syz_open_procfs(pid pid, file ptr[in, string[procfs_proc_file]]) fd

# TODO: some of net files are only available in the init namespace (e.g. bluetooth bnep and hci).
# We could find some way to open these files in the init namespace
# esp. taking into account that we create bluetooth sockets in init namespace.
procfs_proc_file = "auxv", "cmdline", "environ", "autogroup", "cgroup", "clear_refs", "comm", "coredump_filter", "cpuset", "gid_map", "io", "limits", "loginuid", "maps", "mountinfo", "mounts", "mountstats", "numa_maps", "oom_adj", "oom_score", "oom_score_adj", "pagemap", "personality", "projid_map", "sched", "schedstat", "sessionid", "setgroups", "smaps", "smaps_rollup", "totmaps", "stack", "stat", "statm", "status", "syscall", "timers", "uid_map", "wchan", "map_files", "attr", "attr/current", "attr/exec", "attr/fscreate", "attr/keycreate", "attr/prev", "attr/sockcreate", "ns", "children", "task", "fd", "fd/3", "fd/4", "fdinfo", "fdinfo/3", "fdinfo/4", "net", "net/anycast6", "net/arp", "net/bnep", "net/connector", "net/dev", "net/dev_mcast", "net/dev_snmp6", "net/fib_trie", "net/fib_triestat", "net/hci", "net/icmp", "net/icmp6", "net/if_inet6", "net/igmp", "net/igmp6", "net/ip6_flowlabel", "net/ip6_mr_cache", "net/ip6_mr_vif", "net/ip6_tables_matches", "net/ip6_tables_names", "net/ip6_tables_targets", "net/ip_mr_cache", "net/ip_mr_vif", "net/ip_tables_matches", "net/ip_tables_names", "net/ip_tables_targets", "net/ipv6_route", "net/l2cap", "net/llc/core", "net/llc/socket", "net/mcfilter", "net/mcfilter6", "net/netfilter", "net/netlink", "net/netstat", "net/nfsfs", "net/packet", "net/protocols", "net/psched", "net/ptype", "net/raw", "net/raw6", "net/rfcomm", "net/route", "net/rpc", "net/rt6_stats", "net/rt_acct", "net/rt_cache", "net/sco", "net/sctp", "net/snmp", "net/snmp6", "net/sockstat", "net/sockstat6", "net/softnet_stat", "net/stat", "net/tcp", "net/tcp6", "net/udp", "net/udp6", "net/udplite", "net/udplite6", "net/unix", "net/wireless", "net/xfrm_stat", "net/ip_vs", "net/ip_vs_stats", "net/ip_vs_stats_percpu", "net/nf_conntrack", "net/nf_conntrack_expect", "net/vlan/config", "net/vlan/vlan0", "net/vlan/vlan1", "net/kcm", "net/psched", "timerslack_ns"

openat$procfs(fd const[AT_FDCWD], file ptr[in, string[procfs_file]], flags const[O_RDONLY], mode const[0]) fd

procfs_file = "/proc/keys", "/proc/key-users", "/proc/crypto", "/proc/consoles", "/proc/cgroups", "/proc/zoneinfo", "/proc/vmstat", "/proc/vmallocinfo", "/proc/tty/drivers", "/proc/tty/ldiscs", "/proc/timer_list", "/proc/sysvipc/sem", "/proc/sysvipc/msg", "/proc/sysvipc/shm", "/proc/stat", "/proc/slabinfo", "/proc/schedstat", "/proc/partitions", "/proc/meminfo", "/proc/mdstat", "/proc/locks", "/proc/diskstats", "/proc/cpuinfo", "/proc/consoles", "/proc/bus/input/devices", "/proc/bus/input/handlers", "/proc/asound/seq/clients", "/proc/asound/seq/clients", "/proc/asound/seq/timer", "/proc/asound/timers"

resource fd_yama_ptrace_scope[fd]

# 0 - YAMA_SCOPE_DISABLED
# 1 - YAMA_SCOPE_RELATIONAL
# 2 - YAMA_SCOPE_CAPABILITY
# 3 - YAMA_SCOPE_NO_ATTACH
yama_modes = "0", "1", "2", "3"

openat$yama_ptrace_scope(fd const[AT_FDCWD], file ptr[in, string["/proc/sys/kernel/yama/ptrace_scope"]], flags const[O_RDWR], mode const[0]) fd_yama_ptrace_scope
write$yama_ptrace_scope(fd fd_yama_ptrace_scope, data ptr[in, string[yama_modes]], count len[data])

# Write into some interesting sysct's and sysfs/procfs files.
resource fd_sysctl[fd]

openat$sysctl(fd const[AT_FDCWD], file ptr[in, string[sysctl_file]], flags const[O_WRONLY], mode const[0]) fd_sysctl
write$sysctl(fd fd_sysctl, val ptr[in, string[sysctl_value]], len len[val])

sysctl_file = "/sys/kernel/mm/ksm/run", "/proc/sys/vm/compact_memory", "/proc/sys/vm/drop_caches", "/proc/sys/net/ipv4/tcp_timestamps", "/proc/sys/net/ipv4/tcp_sack", "/proc/sys/net/ipv4/tcp_dsack", "/proc/sys/net/ipv4/tcp_window_scaling", "/proc/sys/net/ipv4/tcp_syncookies", "/proc/sys/net/ipv4/tcp_recovery", "/proc/sys/net/ipv4/tcp_mtu_probing", "/proc/sys/net/ipv4/tcp_rfc1337", "/proc/self/clear_refs"
# Most of these values are suitable for all sysctl_file files.
sysctl_value = "0", "1", "2", "3", "4", "5", "6", "7"

# Write to this file triggers khugepaged scan.
# We don't want to write small values as we only want the explicitly triggered scan.
resource fd_khugepaged_scan[fd]

openat$khugepaged_scan(fd const[AT_FDCWD], file ptr[in, string["/sys/kernel/mm/transparent_hugepage/khugepaged/scan_sleep_millisecs"]], flags const[O_WRONLY], mode const[0]) fd_khugepaged_scan
write$khugepaged_scan(fd fd_khugepaged_scan, val ptr[in, string["1000000"]], len len[val])

resource fd_tcp_congestion[fd]

openat$tcp_congestion(fd const[AT_FDCWD], file ptr[in, string["/proc/sys/net/ipv4/tcp_congestion_control"]], flags const[O_WRONLY], mode const[0]) fd_tcp_congestion
write$tcp_congestion(fd fd_tcp_congestion, val ptr[in, string[tcp_congestion]], len len[val])

tcp_congestion = "reno", "bbr", "bic", "cdg", "cubic", "dctcp", "westwood", "highspeed", "hybla", "htcp", "vegas", "nv", "veno", "scalable", "lp", "yeah", "illinois"

resource fd_tcp_mem[fd]

openat$tcp_mem(fd const[AT_FDCWD], file ptr[in, string[tcp_mem_files]], flags const[O_WRONLY], mode const[0]) fd_tcp_mem
write$tcp_mem(fd fd_tcp_mem, val ptr[in, tcp_mem_values], len len[val])

tcp_mem_files = "/proc/sys/net/ipv4/tcp_rmem", "/proc/sys/net/ipv4/tcp_wmem"

tcp_mem_values {
	v0	fmt[oct, int64]
	sp0	const[' ', int8]
	v1	fmt[oct, int64]
	sp1	const[' ', int8]
	v2	fmt[oct, int64]
	z	const[0, int8]
} [packed]

# /proc/self/reclaim is ChromeOS-specific:
# https://chromium.googlesource.com/chromiumos/third_party/kernel/+/4c3ad28b9c913%5E%21/
resource fd_proc_reclaim[fd]

openat$proc_reclaim(fd const[AT_FDCWD], file ptr[in, string["/proc/self/reclaim"]], flags const[O_WRONLY], mode const[0]) fd_proc_reclaim
write$proc_reclaim(fd fd_proc_reclaim, val ptr[in, string[proc_reclaim_vals]], len len[val])

proc_reclaim_vals = "file", "anon", "all"

resource fd_pidfd[fd]

openat$pidfd(fd const[AT_FDCWD], file ptr[in, string["/proc/self"]], flags flags[open_flags], mode const[0]) fd_pidfd
openat$thread_pidfd(fd const[AT_FDCWD], file ptr[in, string["/proc/thread-self"]], flags flags[open_flags], mode const[0]) fd_pidfd
pidfd_send_signal(fd fd_pidfd, sig signalno, info ptr[in, siginfo], flags const[0])

# pidfd_open is dangerous, so we use syz_pidfd_open instead.
pidfd_open(pid pid, flags const[0]) fd_pidfd (disabled)
syz_pidfd_open(pid pid, flags const[0]) fd_pidfd
pidfd_getfd(pidfd fd_pidfd, fd fd, flags const[0]) fd

close_range(fd fd, max_fd fd, flags flags[close_range_flags])

# Uncomment on your own account.
#syz_open_dev$char(dev const[0xc], major intptr, minor intptr) fd
#syz_open_dev$block(dev const[0xb], major intptr, minor intptr) fd

# /dev/console known to cause problems on at least two different kernels.
# It can turn off all output or produce massive amounts of garbage on console.
# Disable it for now.
#syz_open_dev$console(dev ptr[in, string["/dev/console"]], id const[0], flags flags[open_flags]) fd

resource fd_autofs[fd]

# These devices are relatively safe (don't reboot and don't corrupt kernel memory).
# They need a more comprehensive support. But let at least open them for now,
# maybe fuzzer will be able to skrew them in a useful way.
# TODO: all these devices returning just fd need proper interface descriptions.
openat$vcs(fd const[AT_FDCWD], file ptr[in, string["/dev/vcs"]], flags flags[open_flags], mode const[0]) fd
syz_open_dev$vcsn(dev ptr[in, string["/dev/vcs#"]], id intptr, flags flags[open_flags]) fd
openat$vcsa(fd const[AT_FDCWD], file ptr[in, string["/dev/vcsa"]], flags flags[open_flags], mode const[0]) fd
syz_open_dev$vcsa(dev ptr[in, string["/dev/vcsa#"]], id intptr, flags flags[open_flags]) fd
openat$vcsu(fd const[AT_FDCWD], file ptr[in, string["/dev/vcsu"]], flags flags[open_flags], mode const[0]) fd
syz_open_dev$vcsu(dev ptr[in, string["/dev/vcsu#"]], id intptr, flags flags[open_flags]) fd
syz_open_dev$ircomm(dev ptr[in, string["/dev/ircomm#"]], id intptr, flags flags[open_flags]) fd
syz_open_dev$audion(dev ptr[in, string["/dev/audio#"]], id intptr, flags flags[open_flags]) fd

openat$null(fd const[AT_FDCWD], file ptr[in, string["/dev/null"]], flags flags[open_flags], mode const[0]) fd
openat$zero(fd const[AT_FDCWD], file ptr[in, string["/dev/zero"]], flags flags[open_flags], mode const[0]) fd
openat$full(fd const[AT_FDCWD], file ptr[in, string["/dev/full"]], flags flags[open_flags], mode const[0]) fd
openat$irnet(fd const[AT_FDCWD], file ptr[in, string["/dev/irnet"]], flags flags[open_flags], mode const[0]) fd
openat$hwrng(fd const[AT_FDCWD], file ptr[in, string["/dev/hwrng"]], flags flags[open_flags], mode const[0]) fd
openat$hpet(fd const[AT_FDCWD], file ptr[in, string["/dev/hpet"]], flags flags[open_flags], mode const[0]) fd
openat$autofs(fd const[AT_FDCWD], file ptr[in, string["/dev/autofs"]], flags flags[open_flags], mode const[0]) fd_autofs
openat$keychord(fd const[AT_FDCWD], file ptr[in, string["/dev/keychord"]], flags flags[open_flags], mode const[0]) fd
openat$zygote(fd const[AT_FDCWD], file ptr[in, string["/dev/socket/zygote"]], flags flags[open_flags], mode const[0]) fd
openat$pktcdvd(fd const[AT_FDCWD], file ptr[in, string["/dev/pktcdvd/control"]], flags flags[open_flags], mode const[0]) fd
openat$lightnvm(fd const[AT_FDCWD], file ptr[in, string["/dev/lightnvm/control"]], flags flags[open_flags], mode const[0]) fd
openat$xenevtchn(fd const[AT_FDCWD], file ptr[in, string["/dev/xen/evtchn"]], flags flags[open_flags], mode const[0]) fd
openat$dlm_control(fd const[AT_FDCWD], file ptr[in, string["/dev/dlm-control"]], flags flags[open_flags], mode const[0]) fd
openat$dlm_monitor(fd const[AT_FDCWD], file ptr[in, string["/dev/dlm-monitor"]], flags flags[open_flags], mode const[0]) fd
openat$dlm_plock(fd const[AT_FDCWD], file ptr[in, string["/dev/dlm_plock"]], flags flags[open_flags], mode const[0]) fd
openat$btrfs_control(fd const[AT_FDCWD], file ptr[in, string["/dev/btrfs-control"]], flags flags[open_flags], mode const[0]) fd
openat$ubi_ctrl(fd const[AT_FDCWD], file ptr[in, string["/dev/ubi_ctrl"]], flags flags[open_flags], mode const[0]) fd
openat$cachefiles(fd const[AT_FDCWD], file ptr[in, string["/dev/cachefiles"]], flags flags[open_flags], mode const[0]) fd
openat$ndctl0(fd const[AT_FDCWD], file ptr[in, string["/dev/ndctl0"]], flags flags[open_flags], mode const[0]) fd
openat$nmem0(fd const[AT_FDCWD], file ptr[in, string["/dev/nmem0"]], flags flags[open_flags], mode const[0]) fd
openat$nvram(fd const[AT_FDCWD], file ptr[in, string["/dev/nvram"]], flags flags[open_flags], mode const[0]) fd
openat$ocfs2_control(fd const[AT_FDCWD], file ptr[in, string["/dev/ocfs2_control"]], flags flags[open_flags], mode const[0]) fd
openat$nvme_fabrics(fd const[AT_FDCWD], file ptr[in, string["/dev/nvme-fabrics"]], flags flags[open_flags], mode const[0]) fd

pipefd {
	rfd	fd
	wfd	fd
}

type iovec[DIR, T] {
	addr	ptr[DIR, T]
	len	len[addr, intptr]
}
type iovec_in iovec[in, array[int8]]
type iovec_out iovec[out, array[int8]]

stat {
	st_dev		intptr
	st_ino		intptr
	st_mode		int32
	st_nlink	int32
	st_uid		uid
	st_gid		gid
	st_rdev		intptr
	__pad1		const[0, intptr]
	st_size		intptr
	st_blksize	int32
	__pad2		const[0, int32]
	st_blocks	intptr
	st_atime	intptr
	st_atime_nsec	intptr
	st_mtime	intptr
	st_mtime_nsec	intptr
	st_ctime	intptr
	st_ctime_nsec	intptr
	__unused4	const[0, int32]
	__unused5	const[0, int32]
}

statx {
	mask		int32
	blksize		int32
	attributes	int64
	nlink		int32
	uid		uid
	gid		gid
	mode		int16
	__spare0	int16
	ino		int64
	size		int64
	blocks		int64
	__spare1	int64
	atime		statx_timestamp
	btime		statx_timestamp
	ctime		statx_timestamp
	mtime		statx_timestamp
	rdev_major	int32
	rdev_minor	int32
	dev_major	int32
	dev_minor	int32
	__spare2	array[int64, 14]
}

define STAT64_SIZE	sizeof(struct stat64)

type stat64 array[int8, STAT64_SIZE]

pollfd {
	fd	fd
	events	flags[pollfd_events, int16]
	revents	const[0, int16]
}

sigset_t {
	mask	array[intptr, _NSIG_WORDS]
}

sigset_size {
	ss	ptr[inout, sigset_t]
	len	len[ss, intptr]
}

resource time_sec[intptr]
resource time_nsec[intptr]
resource time_usec[intptr]

# prog knowns about this struct type
timespec {
	sec	time_sec
	nsec	time_nsec
}

# prog knowns about this struct type
timeval {
	sec	time_sec
	usec	time_usec
}

statx_timestamp {
	sec		int64
	nsec		int32
	__reserved	int32
}

itimerspec {
	interv	timespec
	value	timespec
}

itimerval {
	interv	timeval
	value	timeval
}

utimbuf {
	actime	intptr
	modtime	intptr
}

sigevent {
	val	const[0, intptr]
	signo	signalno
	notify	flags[sigev_notify, int32]
	u	sigevent_u
} [size[SIGEVENT_SIZE]]

sigevent_u [
	tid	pid
	thr	sigevent_thread
]

define SIGEVENT_SIZE	sizeof(struct sigevent)

sigevent_thread {
# NEED: this is function pointer and pthread_attr_t (?)
	func	buffer[in]
	attr	buffer[in]
}

cap_header {
	var	flags[cap_version, int32]
	pid	pid
}

cap_data {
	eff0	int32
	perm0	int32
	inher0	int32
	eff1	int32
	perm1	int32
	inher1	int32
}

epoll_event {
	ev	flags[epoll_ev, int32]
	data	const[0, int64]
# TODO: this packed only on amd64
} [packed]

# TODO: fd_set needs to be a separate type
fd_set {
	mask0	int64
	mask1	int64
	mask2	int64
	mask3	int64
	mask4	int64
	mask5	int64
	mask6	int64
	mask7	int64
}

sock_fprog {
	len	len[filter, int16]
	filter	ptr[in, array[sock_filter]]
}

sock_filter {
	code	int16
	jt	int8
	jf	int8
	k	int32
}

file_handle [
	raw				file_handle_raw
	shmem				file_handle_t[1, fid_shmem]
	fuse				file_handle_t[0x81, fid_fuse]
	fuse_with_parent		file_handle_t[0x82, fid_fuse_with_parent]
	nfs				file_handle_t[36, fid_nfs]
	FILEID_INO32_GEN		file_handle_t[FILEID_INO32_GEN, fid_FILEID_INO32_GEN]
	FILEID_INO32_GEN_PARENT		file_handle_t[FILEID_INO32_GEN_PARENT, fid_FILEID_INO32_GEN_PARENT]
	FILEID_UDF_WITHOUT_PARENT	file_handle_t[FILEID_UDF_WITHOUT_PARENT, fid_FILEID_UDF_WITHOUT_PARENT]
	FILEID_UDF_WITH_PARENT		file_handle_t[FILEID_UDF_WITH_PARENT, fid_FILEID_UDF_WITH_PARENT]
	FILEID_BTRFS_WITH_PARENT	file_handle_t[FILEID_BTRFS_WITH_PARENT, btrfs_fid]
	FILEID_BTRFS_WITH_PARENT_ROOT	file_handle_t[FILEID_BTRFS_WITH_PARENT, btrfs_fid]
	FILEID_BTRFS_WITHOUT_PARENT	file_handle_t[FILEID_BTRFS_WITH_PARENT, btrfs_fid]
	ceph_nfs_snapfh			file_handle_t[FILEID_BTRFS_WITH_PARENT, ceph_nfs_snapfh]
	ceph_nfs_fh			file_handle_t[FILEID_INO32_GEN, ceph_nfs_fh]
	ceph_nfs_confh			file_handle_t[FILEID_INO32_GEN_PARENT, ceph_nfs_confh]
	GFS2_SMALL_FH_SIZE		file_handle_t[GFS2_SMALL_FH_SIZE, fid_GFS2_SMALL_FH_SIZE]
	GFS2_LARGE_FH_SIZE		file_handle_t[GFS2_LARGE_FH_SIZE, fid_GFS2_LARGE_FH_SIZE]
	OVL_FILEID_V0			file_handle_t[OVL_FILEID_V0, ovl_fb]
	OVL_FILEID_V1			file_handle_t[OVL_FILEID_V1, ovl_fh]
	FILEID_NILFS_WITHOUT_PARENT	file_handle_t[FILEID_NILFS_WITHOUT_PARENT, nilfs_fid]
	FILEID_NILFS_WITH_PARENT	file_handle_t[FILEID_NILFS_WITH_PARENT, nilfs_fid]
	reiserfs_2			file_handle_t[2, fid_reiserfs_2]
	reiserfs_3			file_handle_t[3, fid_reiserfs_3]
	reiserfs_4			file_handle_t[4, fid_reiserfs_4]
	reiserfs_5			file_handle_t[5, fid_reiserfs_5]
	reiserfs_6			file_handle_t[6, fid_reiserfs_6]
	xfs				file_handle_t[0x81, xfs_fid64]
	xfs_parent			file_handle_t[0x82, xfs_fid64]
	orangefs			file_handle_t[1, fid_orangefs]
	orangefs_parent			file_handle_t[2, fid_orangefs_parent]
	isofs				file_handle_t[1, isofs_fid]
	isofs_parent			file_handle_t[2, isofs_fid]
	ocfs2				file_handle_t[1, fid_ocfs2]
	ocfs2_parent			file_handle_t[2, fid_ocfs2_parent]
] [varlen]

file_handle_raw {
	handle_bytes	bytesize[f_handle, int32]
	handle_type	flags[fid_type, int32]
	f_handle	align32[array[int8]]
}

type file_handle_t[TYPE, FID] {
	handle_bytes	bytesize[f_handle, int32]
	handle_type	const[TYPE, int32]
	f_handle	FID
}

fid_shmem {
	gen	int32
	ino	int64
} [packed]

fid_fuse {
	nodeid_hi	int32
	nodeid_lo	int32
	generation	int32
}

fid_fuse_with_parent {
	base		fid_fuse
	parent_fid	fid_fuse
} [packed]

fid_FILEID_INO32_GEN {
	ino	int32
	gen	int32
}

fid_FILEID_INO32_GEN_PARENT {
	base		fid_FILEID_INO32_GEN
	parent_ino	int32
	parent_gen	int32
}

fid_FILEID_UDF_WITHOUT_PARENT {
	block		int32
	partref		int16
	parent_partref	int16
	generation	int32
}

fid_FILEID_UDF_WITH_PARENT {
	base			fid_FILEID_UDF_WITHOUT_PARENT
	parent_block		int32
	parent_generation	int32
}

btrfs_fid {
	objectid		int64
	root_objectid		int64
	gen			int32
	parent_objectid		int64
	parent_gen		int32
	parent_root_objectid	int64
} [packed]

ceph_nfs_snapfh {
	ino		int64
	snapid		int64
	parent_ino	int64
	hash		int32
} [packed]

ceph_nfs_fh {
	ino	int64
}

ceph_nfs_confh {
	ino		int64
	parent_ino	int64
}

fid_GFS2_SMALL_FH_SIZE {
	no_formal_ino_hi	int32be
	no_formal_ino_lo	int32be
	no_addr_hi		int32be
	no_addr_lo		int32be
}

fid_GFS2_LARGE_FH_SIZE {
	base		fid_GFS2_SMALL_FH_SIZE
	parent_fid	fid_GFS2_SMALL_FH_SIZE
}

define GFS2_SMALL_FH_SIZE	4
define GFS2_LARGE_FH_SIZE	8

fid_nfs {
	fileid_hi	int32
	fileid_lo	int32
	type		int32
# The total size is encoded in file_handle.handle_type, so we make this const size.
	size		const[NFS_MAXFHSIZE, int16]
	data		array[int8, NFS_MAXFHSIZE]
} [align[4]]

fid_reiserfs_2 {
	objectid	int32
	dir_id		int32
}

fid_reiserfs_3 {
	objectid	int32
	dir_id		int32
	generation	int32
}

fid_reiserfs_4 {
	objectid	int32
	dir_id		int32
	parent_objectid	int32
	parent_dir_id	int32
}

fid_reiserfs_5 {
	objectid	int32
	dir_id		int32
	generation	int32
	parent_objectid	int32
	parent_dir_id	int32
}

fid_reiserfs_6 {
	objectid		int32
	dir_id			int32
	generation		int32
	parent_objectid		int32
	parent_dir_id		int32
	parent_generation	int32
}

xfs_fid64 {
	ino		int64
	gen		int32
	parent_ino	int64
	parent_gen	int32
} [align[4]]

fid_orangefs {
	khandle	array[int8, 16]
	fs_id	int32
}

fid_orangefs_parent {
	base		fid_orangefs
	parent_fid	fid_orangefs
}

nilfs_fid {
	cno		int64
	ino		int64
	gen		int32
	parent_gen	int32
	parent_ino	int64
} [packed]

isofs_fid {
	block			int32
	offset			int16
	parent_offset		int16
	generation		int32
	parent_block		int32
	parent_generation	int32
}

fid_ocfs2 {
	blkno_hi	int32
	blkno_lo	int32
	generation	int32
}

fid_ocfs2_parent {
	base		fid_ocfs2
	parent_fid	fid_ocfs2
}

fid_type = FILEID_ROOT, FILEID_INO32_GEN, FILEID_INO32_GEN_PARENT, FILEID_BTRFS_WITHOUT_PARENT, FILEID_BTRFS_WITH_PARENT, FILEID_BTRFS_WITH_PARENT_ROOT, FILEID_UDF_WITHOUT_PARENT, FILEID_UDF_WITH_PARENT, FILEID_NILFS_WITHOUT_PARENT, FILEID_NILFS_WITH_PARENT, FILEID_FAT_WITHOUT_PARENT, FILEID_FAT_WITH_PARENT, FILEID_LUSTRE, FILEID_KERNFS

mq_attr {
	mq_flags	intptr
	mq_maxmsg	intptr
	mq_msgsize	intptr
	mq_curmsgs	intptr
	__reserved	array[const[0, intptr], 4]
}

kexec_segment {
	buf	buffer[in]
	sz	len[buf, intptr]
# TODO: this is address in kernel
	mem	intptr
	memsz	intptr
}

rusage {
	utime	timeval
	stime	timeval
	maxrss	intptr
	ixrss	intptr
	idrss	intptr
	isrss	intptr
	minflt	intptr
	majflt	intptr
	nswap	intptr
	inblock	intptr
	oublock	intptr
	msgsnd	intptr
	msgrcv	intptr
	signals	intptr
	nvcsw	intptr
	nivcsw	intptr
}

rlimit {
	soft	intptr
	hard	intptr
}

sigaction {
	sa_handler	ptr[in, text[target]]
	sa_flags	flags[sigaction_flags, intptr]
	sa_restorer	ptr[in, text[target]]
	sa_mask		sigset_t
}

sigaltstack {
	ss_sp		ptr[out, array[int8]]
	ss_flags	flags[sigaltstack_flags, int32]
	ss_size		bytesize[ss_sp, intptr]
}

sigaltstack_flags = SS_ONSTACK, SS_DISABLE, SS_AUTODISARM

tms {
	utime	intptr
	stime	intptr
	cutime	intptr
	cstime	intptr
}

siginfo {
	signo	signalno
	errno	int32
	code	int32
} [size[SIGINFO_SIZE]]

define SIGINFO_SIZE	sizeof(struct siginfo)

timex {
	stuff0	intptr
	stuff1	intptr
	stuff2	intptr
	stuff3	intptr
	stuff4	intptr
	stuff5	intptr
	stuff6	intptr
	stuff7	intptr
	stuff8	intptr
	stuff9	intptr
	stuff10	intptr
	stuff11	intptr
	stuff12	intptr
	stuff13	intptr
	stuff14	intptr
	stuff15	intptr
	stuff16	intptr
	stuff17	intptr
	stuff18	intptr
	stuff19	intptr
	stuff20	intptr
	stuff21	intptr
	stuff22	intptr
	stuff23	intptr
	stuff24	intptr
	stuff25	intptr
}

ustat {
	f_tfree		int32
	f_tinode	intptr
	f_fname		array[int8, 6]
	f_fpack		array[int8, 6]
}

user_desc {
	entry_number	int32
# Base should be vma and limit should be len[base]
# But these fields are int32, so we can't use vma.
	base_addr	flags[user_desc_bases, int32]
	limit		flags[user_desc_limits, int32]
	seg_32bit	int32:1
	contents	int32:2
	read_exec_only	int32:1
	limit_in_pages	int32:1
	seg_not_present	int32:1
	useable		int32:1
	lm		int32:1
}

user_desc_bases = 0, 4096, 1048576, 536870912, 536872960, 536875008, -1
user_desc_limits = 0, 1024, 4096, 8192, 16384, -1

sched_attr {
	size		bytesize[parent, int32]
	sched_policy	flags[sched_policy, int32]
	sched_flags	flags[sched_attr_flags, int64]
	sched_nice	int32
	sched_priority	int32
	sched_runtime	int64
	sched_deadline	int64
	sched_period	int64
	sched_util_min	int32
	sched_util_max	int32
}

sched_policy = SCHED_NORMAL, SCHED_FIFO, SCHED_RR, SCHED_BATCH, SCHED_IDLE, SCHED_DEADLINE
sched_attr_flags = SCHED_FLAG_RESET_ON_FORK, SCHED_FLAG_RECLAIM, SCHED_FLAG_DL_OVERRUN, SCHED_FLAG_KEEP_POLICY, SCHED_FLAG_KEEP_PARAMS, SCHED_FLAG_UTIL_CLAMP_MIN, SCHED_FLAG_UTIL_CLAMP_MAX, SCHED_FLAG_SUGOV

flock {
	type	flags[flock_type, int16]
	whence	flags[seek_whence, int16]
	start	intptr
	len	intptr
	pid	pid
}

f_owner_ex {
	type	flags[f_owner_type, int32]
	pid	pid
}

ucred {
	pid	pid
	uid	uid
	gid	gid
}

kcmp_epoll_slot {
	efd	fd_epoll
	tfd	fd
	toff	int32
}

open_how {
	flags	flags[open_flags, int64]
	mode	flags[open_mode, int64]
	resolve	flags[resolve_flags, int64]
}

# Not providing O_WRONLY means O_RDONLY.
open_flags = O_WRONLY, O_RDWR, O_APPEND, FASYNC, O_CLOEXEC, O_CREAT, O_DIRECT, O_DIRECTORY, O_EXCL, O_LARGEFILE, O_NOATIME, O_NOCTTY, O_NOFOLLOW, O_NONBLOCK, O_PATH, O_SYNC, O_TRUNC, __O_TMPFILE
open_mode = S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH
resolve_flags = RESOLVE_CACHED, RESOLVE_BENEATH, RESOLVE_IN_ROOT, RESOLVE_NO_MAGICLINKS, RESOLVE_NO_SYMLINKS, RESOLVE_NO_XDEV
madvise_flags = MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL, MADV_WILLNEED, MADV_DONTNEED, MADV_REMOVE, MADV_DONTFORK, MADV_DOFORK, MADV_HWPOISON, MADV_SOFT_OFFLINE, MADV_MERGEABLE, MADV_UNMERGEABLE, MADV_HUGEPAGE, MADV_NOHUGEPAGE, MADV_DONTDUMP, MADV_DODUMP, MADV_WIPEONFORK, MADV_KEEPONFORK, MADV_COLD, MADV_PAGEOUT, MADV_POPULATE_READ, MADV_POPULATE_WRITE, MADV_COLLAPSE
fadvise_flags = POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL, POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, POSIX_FADV_DONTNEED
move_pages_flags = MPOL_MF_MOVE, MPOL_MF_MOVE_ALL
msync_flags = MS_ASYNC, MS_SYNC, MS_INVALIDATE
mmap_prot = PROT_EXEC, PROT_READ, PROT_WRITE, PROT_SEM, PROT_GROWSDOWN, PROT_GROWSUP
mmap_flags = MAP_SHARED, MAP_PRIVATE, MAP_32BIT, MAP_ANONYMOUS, MAP_DENYWRITE, MAP_EXECUTABLE, MAP_FILE, MAP_FIXED, MAP_GROWSDOWN, MAP_HUGETLB, MAP_LOCKED, MAP_NONBLOCK, MAP_NORESERVE, MAP_POPULATE, MAP_STACK, MAP_UNINITIALIZED, MAP_SHARED_VALIDATE, MAP_SYNC, MAP_FIXED_NOREPLACE
mremap_flags = MREMAP_MAYMOVE, MREMAP_FIXED, MREMAP_DONTUNMAP
mbind_mode = MPOL_DEFAULT, MPOL_BIND, MPOL_INTERLEAVE, MPOL_PREFERRED, MPOL_F_STATIC_NODES, MPOL_F_RELATIVE_NODES
mbind_flags = MPOL_MF_STRICT, MPOL_MF_MOVE, MPOL_MF_MOVE_ALL
pipe_flags = O_NONBLOCK, O_CLOEXEC, O_DIRECT, O_NOTIFICATION_PIPE
mlock_flags = MLOCK_ONFAULT
mlockall_flags = MCL_CURRENT, MCL_FUTURE, MCL_ONFAULT
dup_flags = O_CLOEXEC
splice_flags = SPLICE_F_MOVE, SPLICE_F_NONBLOCK, SPLICE_F_MORE, SPLICE_F_GIFT
seek_whence = SEEK_SET, SEEK_CUR, SEEK_END, SEEK_DATA, SEEK_HOLE
signalfd_flags = SFD_NONBLOCK, SFD_CLOEXEC
eventfd_flags = EFD_CLOEXEC, EFD_NONBLOCK, EFD_SEMAPHORE
timerfd_create_flags = TFD_NONBLOCK, TFD_CLOEXEC
timerfd_settime_flags = TFD_TIMER_ABSTIME, TFD_TIMER_CANCEL_ON_SET
clock_type = CLOCK_REALTIME, CLOCK_REALTIME_COARSE, CLOCK_MONOTONIC, CLOCK_MONOTONIC_COARSE, CLOCK_MONOTONIC_RAW, CLOCK_BOOTTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, CLOCK_REALTIME_ALARM, CLOCK_BOOTTIME_ALARM
sigev_notify = SIGEV_NONE, SIGEV_SIGNAL, SIGEV_THREAD, SIGEV_THREAD_ID
cap_version = _LINUX_CAPABILITY_VERSION_1, _LINUX_CAPABILITY_VERSION_2, _LINUX_CAPABILITY_VERSION_3
epoll_flags = EPOLL_CLOEXEC
epoll_ev = POLLIN, POLLOUT, POLLRDHUP, POLLPRI, POLLERR, POLLHUP, EPOLLET, EPOLLONESHOT, EPOLLEXCLUSIVE, EPOLLWAKEUP
pollfd_events = POLLIN, POLLPRI, POLLOUT, POLLERR, POLLHUP, POLLNVAL, POLLRDNORM, POLLRDBAND, POLLWRNORM, POLLWRBAND, POLLMSG, POLLREMOVE, POLLRDHUP, POLLFREE, POLL_BUSY_LOOP
mknod_mode = S_IFREG, S_IFCHR, S_IFBLK, S_IFIFO, S_IFSOCK, S_ISUID, S_ISGID, S_ISVTX, open_mode
at_flags = AT_EMPTY_PATH, AT_SYMLINK_NOFOLLOW, AT_SYMLINK_FOLLOW, AT_NO_AUTOMOUNT, AT_EMPTY_PATH
fallocate_mode = FALLOC_FL_KEEP_SIZE, FALLOC_FL_PUNCH_HOLE, FALLOC_FL_COLLAPSE_RANGE, FALLOC_FL_ZERO_RANGE, FALLOC_FL_INSERT_RANGE, FALLOC_FL_UNSHARE_RANGE, FALLOC_FL_NO_HIDE_STALE
linkat_flags = AT_EMPTY_PATH, AT_SYMLINK_FOLLOW
unlinkat_flags = AT_REMOVEDIR
renameat2_flags = RENAME_EXCHANGE, RENAME_NOREPLACE, RENAME_WHITEOUT
flock_op = LOCK_SH, LOCK_EX, LOCK_UN, LOCK_NB
statx_flags = AT_SYMLINK_NOFOLLOW, AT_SYMLINK_FOLLOW, AT_NO_AUTOMOUNT, AT_EMPTY_PATH, AT_STATX_SYNC_TYPE, AT_STATX_SYNC_AS_STAT, AT_STATX_FORCE_SYNC, AT_STATX_DONT_SYNC
statx_mask = STATX_TYPE, STATX_MODE, STATX_NLINK, STATX_UID, STATX_GID, STATX_ATIME, STATX_MTIME, STATX_CTIME, STATX_INO, STATX_SIZE, STATX_BLOCKS, STATX_BASIC_STATS, STATX_BTIME
name_to_handle_at_flags = AT_EMPTY_PATH, AT_SYMLINK_FOLLOW, AT_HANDLE_FID
mq_open_flags = O_WRONLY, O_RDWR, O_NONBLOCK, O_CREAT, O_EXCL, O_CREAT
finit_module_flags = MODULE_INIT_IGNORE_MODVERSIONS, MODULE_INIT_IGNORE_VERMAGIC
delete_module_flags = O_NONBLOCK, O_TRUNC
kexec_load_flags = KEXEC_ON_CRASH, KEXEC_PRESERVE_CONTEXT, KEXEC_ARCH_386, KEXEC_ARCH_X86_64, KEXEC_ARCH_PPC, KEXEC_ARCH_PPC64, KEXEC_ARCH_IA_64, KEXEC_ARCH_ARM, KEXEC_ARCH_S390, KEXEC_ARCH_SH, KEXEC_ARCH_MIPS, KEXEC_ARCH_MIPS_LE, KEXEC_ARCH_DEFAULT
faccessat_flags = AT_EACCESS, AT_SYMLINK_NOFOLLOW, AT_EMPTY_PATH
sync_file_flags = SYNC_FILE_RANGE_WAIT_BEFORE, SYNC_FILE_RANGE_WRITE, SYNC_FILE_RANGE_WAIT_AFTER
kcmp_flags = KCMP_FILE, KCMP_FILES, KCMP_FS, KCMP_IO, KCMP_SIGHAND, KCMP_SYSVSEM, KCMP_VM
rusage_who = RUSAGE_SELF, RUSAGE_CHILDREN, RUSAGE_THREAD
rlimit_type = RLIMIT_AS, RLIMIT_CORE, RLIMIT_CPU, RLIMIT_DATA, RLIMIT_FSIZE, RLIMIT_LOCKS, RLIMIT_MEMLOCK, RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_NOFILE, RLIMIT_NPROC, RLIMIT_RSS, RLIMIT_RTPRIO, RLIMIT_RTTIME, RLIMIT_SIGPENDING, RLIMIT_STACK
# The ones that disable console output are intentionally omitted.
syslog_cmd = SYSLOG_ACTION_CLOSE, SYSLOG_ACTION_OPEN, SYSLOG_ACTION_READ, SYSLOG_ACTION_READ_ALL, SYSLOG_ACTION_READ_CLEAR, SYSLOG_ACTION_SIZE_UNREAD, SYSLOG_ACTION_SIZE_BUFFER
ioprio_which_pid = IOPRIO_WHO_PROCESS, IOPRIO_WHO_PGRP
ioprio_which_uid = IOPRIO_WHO_USER
personality_flags = PER_LINUX, PER_SVR4, PER_SVR3, PER_OSR5, PER_WYSEV386, PER_ISCR4, PER_BSD, PER_XENIX, PER_LINUX32, PER_IRIX32, PER_IRIXN32, PER_IRIX64, PER_RISCOS, PER_SOLARIS, PER_UW7, PER_OSF4, PER_HPUX, ADDR_NO_RANDOMIZE, MMAP_PAGE_ZERO, ADDR_COMPAT_LAYOUT, READ_IMPLIES_EXEC, ADDR_LIMIT_32BIT, SHORT_INODE, WHOLE_SECONDS, STICKY_TIMEOUTS, ADDR_LIMIT_3GB
clock_id = CLOCK_REALTIME, CLOCK_REALTIME_COARSE, CLOCK_MONOTONIC, CLOCK_MONOTONIC_COARSE, CLOCK_MONOTONIC_RAW, CLOCK_BOOTTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID
sigprocmask_how = SIG_BLOCK, SIG_UNBLOCK, SIG_SETMASK
getitimer_which = ITIMER_REAL, ITIMER_VIRTUAL, ITIMER_PROF
wait_options = WNOHANG, WUNTRACED, WCONTINUED, WEXITED, WSTOPPED, WCONTINUED, WNOHANG, WNOWAIT, __WCLONE, __WALL, __WNOTHREAD
waitid_which = P_PID, P_PGID, P_ALL
sigaction_flags = SA_NOCLDSTOP, SA_NOCLDWAIT, SA_NODEFER, SA_ONSTACK, SA_RESETHAND, SA_RESTART, SA_SIGINFO
timer_flags = TIMER_ABSTIME
utimensat_flags = AT_SYMLINK_NOFOLLOW
priority_which = PRIO_PROCESS, PRIO_PGRP, PRIO_USER
mempolicy_flags = MPOL_F_MEMS_ALLOWED, MPOL_F_ADDR, MPOL_F_NODE
ptrace_req = PTRACE_LISTEN, PTRACE_KILL, PTRACE_INTERRUPT, PTRACE_ATTACH, PTRACE_DETACH
ptrace_req_peek = PTRACE_PEEKTEXT, PTRACE_PEEKDATA
ptrace_req_poke = PTRACE_POKETEXT, PTRACE_POKEDATA
ptrace_req_getregs = PTRACE_GETREGS, PTRACE_GETFPREGS
ptrace_req_setregs = PTRACE_SETREGS, PTRACE_SETFPREGS
ptrace_req_setopts = PTRACE_SETOPTIONS, PTRACE_SEIZE
ptrace_req_cont = PTRACE_CONT, PTRACE_SYSCALL, PTRACE_SINGLESTEP, PTRACE_SYSEMU, PTRACE_SYSEMU_SINGLESTEP
pthread_regset = NT_PRSTATUS, NT_PRFPREG, NT_PRPSINFO, NT_TASKSTRUCT, NT_AUXV, NT_386_TLS, NT_386_IOPERM, NT_X86_XSTATE
ptrace_options = PTRACE_O_EXITKILL, PTRACE_O_TRACECLONE, PTRACE_O_TRACEEXEC, PTRACE_O_TRACEEXIT, PTRACE_O_TRACEFORK, PTRACE_O_TRACESYSGOOD, PTRACE_O_TRACEVFORK, PTRACE_O_TRACEVFORKDONE
fcntl_dupfd = F_DUPFD, F_DUPFD_CLOEXEC
fcntl_getflags = F_GETFD, F_GETFL, F_GETSIG, F_GETLEASE, F_GETPIPE_SZ, F_GET_SEALS
fcntl_lock = F_SETLK, F_SETLKW, F_GETLK, F_OFD_GETLK, F_OFD_SETLK, F_OFD_SETLKW
fcntl_flags = FD_CLOEXEC
fcntl_status = O_APPEND, FASYNC, O_DIRECT, O_NOATIME, O_NONBLOCK
flock_type = F_RDLCK, F_WRLCK, F_UNLCK
f_owner_type = F_OWNER_TID, F_OWNER_PID, F_OWNER_PGRP
fcntl_notify = DN_MULTISHOT, DN_ACCESS, DN_MODIFY, DN_CREATE, DN_DELETE, DN_RENAME, DN_ATTRIB
seal_types = F_SEAL_SEAL, F_SEAL_SHRINK, F_SEAL_GROW, F_SEAL_WRITE
ioctl_int_in = FIONBIO, FIOASYNC
ioctl_int_out = FIOQSIZE, FIGETBSZ
fcntl_rw_hint = RWF_WRITE_LIFE_NOT_SET, RWH_WRITE_LIFE_NONE, RWH_WRITE_LIFE_SHORT, RWH_WRITE_LIFE_MEDIUM, RWH_WRITE_LIFE_LONG, RWH_WRITE_LIFE_EXTREME
fiemap_flags = FIEMAP_FLAG_SYNC, FIEMAP_FLAG_XATTR, FIEMAP_FLAG_CACHE
fiemap_extent_flags = FIEMAP_EXTENT_LAST, FIEMAP_EXTENT_UNKNOWN, FIEMAP_EXTENT_DELALLOC, FIEMAP_EXTENT_ENCODED, FIEMAP_EXTENT_DATA_ENCRYPTED, FIEMAP_EXTENT_NOT_ALIGNED, FIEMAP_EXTENT_DATA_INLINE, FIEMAP_EXTENT_DATA_TAIL, FIEMAP_EXTENT_UNWRITTEN, FIEMAP_EXTENT_MERGED, FIEMAP_EXTENT_SHARED
getrandom_flags = GRND_NONBLOCK, GRND_RANDOM
clone_flags = CLONE_VM, CLONE_FS, CLONE_FILES, CLONE_SIGHAND, CLONE_PTRACE, CLONE_VFORK, CLONE_PARENT, CLONE_THREAD, CLONE_NEWNS, CLONE_SYSVSEM, CLONE_SETTLS, CLONE_PARENT_SETTID, CLONE_CHILD_CLEARTID, CLONE_UNTRACED, CLONE_CHILD_SETTID, CLONE_NEWCGROUP, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWUSER, CLONE_NEWPID, CLONE_NEWNET, CLONE_IO, CLONE_PIDFD, CLONE_NEWTIME
clone3_flags = CLONE_CLEAR_SIGHAND, CLONE_INTO_CGROUP, clone_flags
ptrace_peeksiginfo_flags = PTRACE_PEEKSIGINFO_SHARED
close_range_flags = CLOSE_RANGE_UNSHARE

# Consts for target.SpecialFileLenghts.
_ = SMB_PATH_MAX, XT_CGROUP_PATH_MAX, XENSTORE_REL_PATH_MAX

# misc
_ = KCOV_INIT_TRACE, KCOV_ENABLE, KCOV_DISABLE, KCOV_TRACE_PC, KCOV_TRACE_CMP, PTRACE_TRACEME, SYSLOG_ACTION_CONSOLE_ON, SYSLOG_ACTION_CONSOLE_OFF, SYSLOG_ACTION_CONSOLE_LEVEL, SYSLOG_ACTION_CLEAR, __NR_mmap2

# Hardcode KCOV_REMOTE_ENABLE value for amd64 until new kcov patches reach mainline.
define KCOV_REMOTE_ENABLE	1075340134

# Not yet implemented syscalls:
# umask
# vhangup
# _sysctl
# nfsservctl
# getcpu

# Probably no sense in calling these.
# Also affect system-wide state, so not reproducible anyway.
# sched_get_priority_max
# sched_get_priority_min
]

25/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 92728
							output: 127
							thoughts: 337
						

Thoughts:
**My Analysis of a Potential Race Condition**

Okay, so I've identified that the `write(fd fd, buf buffer[in], count len[buf])` system call is definitely present in `sys.txt`. That's good, so I *can* use it in my exploit. Specifically, I'm thinking of using `write(r0, &AUTO="01010101", 0x4)`.

Now, the interesting part is the race. It looks like the critical race is between `pty_write` and `__stop_tty`. I know `pty_write` is triggered when there's I/O, either from the slave writing to the master or the master echoing back to the slave. If I write to the master (which I'm calling `r0`), that data should go to the slave's receive buffer. The slave's line discipline, likely `n_tty`, will handle it and echo it back to the slave's output, which, in turn, calls `pty_write` on the slave.

Concurrently, I'm going to hit the slave device (`r1`) with `ioctl$TCXONC(r1, 0x540a, 0x0)`. This should, in turn, call `__stop_tty` on the slave side of the pseudo-terminal.

So, the plan I'm formulating is something like this:

```
r0 = openat$ptmx(0xffffffffffffff9c, &AUTO='/dev/ptmx\x00', 0x2, 0x0)
r1 = syz_open_pts(r0, 0x2)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0)
```

Now, the key is to see if this reproduces the bug. Let's verify it.



26/2 2026/03/09 22:46 tool crash-reproducer
0m Args:
map[ReproSyz:r0 = openat$ptmx(0xffffffffffffff9c, &AUTO='/dev/ptmx\x00', 0x2, 0x0)
r1 = syz_open_pts(r0, 0x2)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0)]

Results:
map[ReproducedBugTitle: ReproducedCrashReport:]

27/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 93660
							output: 43
							thoughts: 500
						

Thoughts:
**Debugging a Potential Data Race in PTY Handling**

Okay, so no crash, which means we need to dig deeper. I'm thinking maybe the timing is the issue. Could it be that the echo mechanism takes longer than the `ioctl` call, and the `ioctl` completes before the echo fully happens? I remember `syz_open_pts`, that might be useful, but perhaps we need to write multiple times or loop to trigger the race.

Hold on, I recall `write` is asynchronous, but maybe it's completing *too* quickly. I can either try writing more data or looping the write. Fault injection isn't relevant here, since it's a data race, not a memory corruption.

Alright, here's a simpler approach. I'll just write directly to the ptmx master and then trigger the `ioctl`, see if that helps, like so:

```
r0 = openat$ptmx(0xffffffffffffff9c, &AUTO='/dev/ptmx\x00', 0x2, 0x0)
r1 = syz_open_pts(r0, 0x2)
write(r0, &AUTO="01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", 0x40) (async)
ioctl$TCXONC(r1, 0x540a, 0x0)
```

But wait... hang on, writing to `r1` - the slave - *directly* calls `pty_write` on the slave, bypassing the whole master/echo thing! Why am I even bothering with writing to the master? That's not the path. If I'm writing directly to the slave (`r1`), the code flow is straightforward. That goes straight to `pty_write`.

Alright, let's step back and look at the control flow. I need to confirm: `tty_write` calls `ld->ops->write`, which calls `n_tty_write`. And *then* does `n_tty_write` call `tty_put_char` which then calls `pty_write`? Or does `n_tty_write` call `tty->ops->write` directly? I need to check `n_tty_write`.



28/2 2026/03/09 22:46 tool codesearch-definition-source
0m Args:
map[ContextFile:drivers/tty/n_tty.c IncludeLines:true Name:n_tty_write]

Results:
map[SourceCode:2335:	static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
2336:				   const u8 *buf, size_t nr)
2337:	{
2338:		const u8 *b = buf;
2339:		DEFINE_WAIT_FUNC(wait, woken_wake_function);
2340:		ssize_t num, retval = 0;
2341:	
2342:		/* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
2343:		if (L_TOSTOP(tty) && file->f_op->write_iter != redirected_tty_write) {
2344:			retval = tty_check_change(tty);
2345:			if (retval)
2346:				return retval;
2347:		}
2348:	
2349:		guard(rwsem_read)(&tty->termios_rwsem);
2350:	
2351:		/* Write out any echoed characters that are still pending */
2352:		process_echoes(tty);
2353:	
2354:		add_wait_queue(&tty->write_wait, &wait);
2355:		while (1) {
2356:			if (signal_pending(current)) {
2357:				retval = -ERESTARTSYS;
2358:				break;
2359:			}
2360:			if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
2361:				retval = -EIO;
2362:				break;
2363:			}
2364:			if (O_OPOST(tty)) {
2365:				while (nr > 0) {
2366:					num = process_output_block(tty, b, nr);
2367:					if (num < 0) {
2368:						if (num == -EAGAIN)
2369:							break;
2370:						retval = num;
2371:						goto break_out;
2372:					}
2373:					b += num;
2374:					nr -= num;
2375:					if (nr == 0)
2376:						break;
2377:					if (process_output(*b, tty) < 0)
2378:						break;
2379:					b++; nr--;
2380:				}
2381:				if (tty->ops->flush_chars)
2382:					tty->ops->flush_chars(tty);
2383:			} else {
2384:				struct n_tty_data *ldata = tty->disc_data;
2385:	
2386:				while (nr > 0) {
2387:					scoped_guard(mutex, &ldata->output_lock)
2388:						num = tty->ops->write(tty, b, nr);
2389:					if (num < 0) {
2390:						retval = num;
2391:						goto break_out;
2392:					}
2393:					if (!num)
2394:						break;
2395:					b += num;
2396:					nr -= num;
2397:				}
2398:			}
2399:			if (!nr)
2400:				break;
2401:			if (tty_io_nonblock(tty, file)) {
2402:				retval = -EAGAIN;
2403:				break;
2404:			}
2405:			up_read(&tty->termios_rwsem);
2406:	
2407:			wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
2408:	
2409:			down_read(&tty->termios_rwsem);
2410:		}
2411:	break_out:
2412:		remove_wait_queue(&tty->write_wait, &wait);
2413:		if (nr && tty->fasync)
2414:			set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
2415:	
2416:		return (b - buf) ? b - buf : retval;
2417:	}
 SourceFile:drivers/tty/n_tty.c]

29/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 96017
							output: 41
							thoughts: 109
						

Thoughts:
**Digging into the Terminal Driver's Read/Write Semantics**

Okay, so I'm tracing a write operation and it looks like when we're dealing with a slave device, like in a pseudo-terminal (pty), a `n_tty_write` ultimately calls `pty_write` through the `tty->ops->write` function pointer. Makes sense so far. But hold on, I've got to check something.  `n_tty_write` is supposed to acquire the `tty->termios_rwsem` semaphore *for read* at some point. That's the crux of this investigation.

Now, I'm pretty sure that `n_tty_ioctl_helper` gets called by `n_tty_ioctl`, and `n_tty_ioctl` is, in turn, called by `tty_ioctl`. So, that leads me to my core question: *does* `tty_ioctl` have an impact on that very same `termios_rwsem` semaphore?

I need to see if `tty_ioctl` interacts with that read/write semaphore. Let me just go and check its implementation. This is going to be key to understanding whether there are any potential race conditions here.



30/2 2026/03/09 22:46 tool codesearch-definition-source
0m Args:
map[ContextFile:drivers/tty/tty_io.c IncludeLines:true Name:tty_ioctl]

Results:
map[SourceCode:2665:	/*
2666:	 * Split this up, as gcc can choke on it otherwise..
2667:	 */
2668:	long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2669:	{
2670:		struct tty_struct *tty = file_tty(file);
2671:		struct tty_struct *real_tty;
2672:		void __user *p = (void __user *)arg;
2673:		int retval;
2674:		struct tty_ldisc *ld;
2675:	
2676:		if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
2677:			return -EINVAL;
2678:	
2679:		real_tty = tty_pair_get_tty(tty);
2680:	
2681:		/*
2682:		 * Factor out some common prep work
2683:		 */
2684:		switch (cmd) {
2685:		case TIOCSETD:
2686:		case TIOCSBRK:
2687:		case TIOCCBRK:
2688:		case TCSBRK:
2689:		case TCSBRKP:
2690:			retval = tty_check_change(tty);
2691:			if (retval)
2692:				return retval;
2693:			if (cmd != TIOCCBRK) {
2694:				tty_wait_until_sent(tty, 0);
2695:				if (signal_pending(current))
2696:					return -EINTR;
2697:			}
2698:			break;
2699:		}
2700:	
2701:		/*
2702:		 *	Now do the stuff.
2703:		 */
2704:		switch (cmd) {
2705:		case TIOCSTI:
2706:			return tiocsti(tty, p);
2707:		case TIOCGWINSZ:
2708:			return tiocgwinsz(real_tty, p);
2709:		case TIOCSWINSZ:
2710:			return tiocswinsz(real_tty, p);
2711:		case TIOCCONS:
2712:			return real_tty != tty ? -EINVAL : tioccons(file);
2713:		case TIOCEXCL:
2714:			set_bit(TTY_EXCLUSIVE, &tty->flags);
2715:			return 0;
2716:		case TIOCNXCL:
2717:			clear_bit(TTY_EXCLUSIVE, &tty->flags);
2718:			return 0;
2719:		case TIOCGEXCL:
2720:		{
2721:			int excl = test_bit(TTY_EXCLUSIVE, &tty->flags);
2722:	
2723:			return put_user(excl, (int __user *)p);
2724:		}
2725:		case TIOCGETD:
2726:			return tiocgetd(tty, p);
2727:		case TIOCSETD:
2728:			return tiocsetd(tty, p);
2729:		case TIOCVHANGUP:
2730:			if (!capable(CAP_SYS_ADMIN))
2731:				return -EPERM;
2732:			tty_vhangup(tty);
2733:			return 0;
2734:		case TIOCGDEV:
2735:		{
2736:			unsigned int ret = new_encode_dev(tty_devnum(real_tty));
2737:	
2738:			return put_user(ret, (unsigned int __user *)p);
2739:		}
2740:		/*
2741:		 * Break handling
2742:		 */
2743:		case TIOCSBRK:	/* Turn break on, unconditionally */
2744:			if (tty->ops->break_ctl)
2745:				return tty->ops->break_ctl(tty, -1);
2746:			return 0;
2747:		case TIOCCBRK:	/* Turn break off, unconditionally */
2748:			if (tty->ops->break_ctl)
2749:				return tty->ops->break_ctl(tty, 0);
2750:			return 0;
2751:		case TCSBRK:   /* SVID version: non-zero arg --> no break */
2752:			/* non-zero arg means wait for all output data
2753:			 * to be sent (performed above) but don't send break.
2754:			 * This is used by the tcdrain() termios function.
2755:			 */
2756:			if (!arg)
2757:				return send_break(tty, 250);
2758:			return 0;
2759:		case TCSBRKP:	/* support for POSIX tcsendbreak() */
2760:			return send_break(tty, arg ? arg*100 : 250);
2761:	
2762:		case TIOCMGET:
2763:			return tty_tiocmget(tty, p);
2764:		case TIOCMSET:
2765:		case TIOCMBIC:
2766:		case TIOCMBIS:
2767:			return tty_tiocmset(tty, cmd, p);
2768:		case TIOCGICOUNT:
2769:			return tty_tiocgicount(tty, p);
2770:		case TCFLSH:
2771:			switch (arg) {
2772:			case TCIFLUSH:
2773:			case TCIOFLUSH:
2774:			/* flush tty buffer and allow ldisc to process ioctl */
2775:				tty_buffer_flush(tty, NULL);
2776:				break;
2777:			}
2778:			break;
2779:		case TIOCSSERIAL:
2780:			return tty_tiocsserial(tty, p);
2781:		case TIOCGSERIAL:
2782:			return tty_tiocgserial(tty, p);
2783:		case TIOCGPTPEER:
2784:			/* Special because the struct file is needed */
2785:			return ptm_open_peer(file, tty, (int)arg);
2786:		default:
2787:			retval = tty_jobctrl_ioctl(tty, real_tty, file, cmd, arg);
2788:			if (retval != -ENOIOCTLCMD)
2789:				return retval;
2790:		}
2791:		if (tty->ops->ioctl) {
2792:			retval = tty->ops->ioctl(tty, cmd, arg);
2793:			if (retval != -ENOIOCTLCMD)
2794:				return retval;
2795:		}
2796:		ld = tty_ldisc_ref_wait(tty);
2797:		if (!ld)
2798:			return hung_up_tty_ioctl(file, cmd, arg);
2799:		retval = -EINVAL;
2800:		if (ld->ops->ioctl) {
2801:			retval = ld->ops->ioctl(tty, cmd, arg);
2802:			if (retval == -ENOIOCTLCMD)
2803:				retval = -ENOTTY;
2804:		}
2805:		tty_ldisc_deref(ld);
2806:		return retval;
2807:	}
 SourceFile:drivers/tty/tty_io.c]

31/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 98550
							output: 43
							thoughts: 40
						

Thoughts:
Okay, here's my interpretation of this technical information, presented as my own thought process:

**Diving into the ioctl handling**

Alright, so I'm focusing on how `tty_ioctl` works here. The key takeaway is that `tty_ioctl` *doesn't* directly manage the `termios_rwsem` semaphore. Instead, it seems to delegate the core functionality. I see that it calls `ld->ops->ioctl`. This `ld` likely refers to a line discipline structure, which means `tty_ioctl` is handing off the control to the particular line discipline. In the case of `n_tty`, the function that ultimately gets called is `n_tty_ioctl`. I know `n_tty` is the normal terminal line discipline, so this tells me the typical ioctl actions are managed within that function. Makes perfect sense. I'll need to dig into `n_tty_ioctl` to understand the specifics of how the terminal is managed.



32/2 2026/03/09 22:46 tool codesearch-definition-source
0m Args:
map[ContextFile:drivers/tty/n_tty.c IncludeLines:true Name:n_tty_ioctl]

Results:
map[SourceCode:2479:	static int n_tty_ioctl(struct tty_struct *tty, unsigned int cmd,
2480:			       unsigned long arg)
2481:	{
2482:		struct n_tty_data *ldata = tty->disc_data;
2483:		unsigned int num;
2484:	
2485:		switch (cmd) {
2486:		case TIOCOUTQ:
2487:			return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
2488:		case TIOCINQ:
2489:			scoped_guard(rwsem_write, &tty->termios_rwsem)
2490:				if (L_ICANON(tty) && !L_EXTPROC(tty))
2491:					num = inq_canon(ldata);
2492:				else
2493:					num = read_cnt(ldata);
2494:			return put_user(num, (unsigned int __user *) arg);
2495:		default:
2496:			return n_tty_ioctl_helper(tty, cmd, arg);
2497:		}
2498:	}
 SourceFile:drivers/tty/n_tty.c]

33/2 2026/03/09 22:46 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 99187
							output: 286
							thoughts: 1270
						

Thoughts:
**Data Race Deep Dive in TTY Driver**

Okay, so here's the breakdown of what I'm seeing. `n_tty_ioctl` doesn't hold `termios_rwsem` when calling `n_tty_ioctl_helper`. Consequently, `n_tty_ioctl_helper` calls `__stop_tty` without the `termios_rwsem` lock. However, `n_tty_write` *does* hold `termios_rwsem` for read. This creates a potential data race scenario. If we write to the slave PTY, `n_tty_write` takes the read lock and calls `tty->ops->write`, which in our case is `pty_write`. At the same time, if we call an `ioctl` on the slave, `__stop_tty` can be called concurrently without the lock. Data race confirmed!

My initial reproducer didn't work, which is strange. I suspect the timing was off—either the `write` completed before the `ioctl` started, or vice versa. To increase the race condition's probability, I need to create a higher concurrency scenario through loops or multiple threads. In syzkaller, which lacks native loops, I can use a strategy like duplicating calls to achieve concurrency.

I initially thought that my syzkaller code would work but I thought wrong. I initially assumed that I needed to write to the slave and do an IOCTL to cause a crash:

```
r0 = openat$ptmx(0xffffffffffffff9c, &AUTO='/dev/ptmx\x00', 0x2, 0x0)
r1 = syz_open_pts(r0, 0x2)
write(r1, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0)
```

However, something wasn't right. I went back to the crash report and the stack trace showed `pty_write` being called from `tty_put_char` in `n_tty_process_echo_ops`. This indicated that the write was not directly triggered by the `write` syscall on the slave. Rather, it came from echoing of the input back from the master! I was mistaken. 

The initial assumptions about `n_tty_write` were also off; I needed to double-check that part and ensure my understanding of the data flow was spot on. `n_tty_write` calls `tty->ops->write` directly.

After analyzing the stack trace, here is what I concluded. The race occurs between the `ioctl` on the slave and the `flush_to_ldisc` workqueue. This workqueue handles the data received from the master, echoes it back to the slave's output, and calls `pty_write` on the slave. Crucially, the write must occur on the *master* side to trigger the echoing, which then leads to the conflicting calls on the slave.

To successfully reproduce the race, I'll need to write to the master and concurrently call `ioctl` on the slave. The write to the master is then written to the slave's receive buffer. The `flush_to_ldisc` workqueue processes this buffer, echoes the data back to the slave, and that triggers `pty_write`. All this must happen concurrently with the `ioctl` on the slave.

So, the new syzkaller code would look like this:

```
r0 = openat$ptmx(0xffffffffffffff9c, &AUTO='/dev/ptmx\x00', 0x2, 0x0)
r1 = syz_open_pts(r0, 0x2)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0)
```

I'll need to multiply these write/ioctl calls since it might still be a matter of timing to successfully trigger the data race.



34/2 2026/03/09 22:47 tool crash-reproducer
0m Args:
map[ReproSyz:r0 = openat$ptmx(0xffffffffffffff9c, &AUTO='/dev/ptmx\x00', 0x2, 0x0)
r1 = syz_open_pts(r0, 0x2)
write(r0, &AUTO="01010101", 0x4) (async)
write(r0, &AUTO="01010101", 0x4) (async)
write(r0, &AUTO="01010101", 0x4) (async)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x0)]

Results:
map[ReproducedBugTitle: ReproducedCrashReport:]

35/2 2026/03/09 22:47 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 101670
							output: 342
							thoughts: 621
						

Thoughts:
**Debugging a Potential Kernel Crash**

Okay, still no crash, which means I need to dig deeper. First, I need to confirm that `syz_open_pts` is actually functioning correctly. Is it present and available in the executor? Yes, good. Next, I need to verify that `ECHO` is enabled by default on the slave pty, which it is. This looks like a reasonable baseline, so I can start to explore potential issues.

Now, let's trace this logic more carefully. Hang on - `TCXONC` with `TCOOFF` looks like it sets `tty->flow.tco_stopped = true` and calls `__stop_tty`. But if `tty->flow.tco_stopped` is *already* true, it simply does nothing. That's a critical detail I overlooked! The second `ioctl$TCXONC(r1, 0x540a, 0x0)` call in a row will be a no-op!

Aha! So, what I need to do is alternate `TCOOFF` and `TCOON`. `TCOON` is represented by `1`, so I should be able to alternate those ioctl values to properly trigger that tty flow control.

The revised sequence should look like this:

```
r0 = openat$ptmx(0xffffffffffffff9c, &AUTO='/dev/ptmx\x00', 0x2, 0x0)
r1 = syz_open_pts(r0, 0x2)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1)
```

Right, let's give *this* a shot. Hopefully, this alternation will uncover the bug.



36/2 2026/03/09 22:47 tool crash-reproducer
0m Args:
map[ReproSyz:r0 = openat$ptmx(0xffffffffffffff9c, &AUTO='/dev/ptmx\x00', 0x2, 0x0)
r1 = syz_open_pts(r0, 0x2)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1)]

Results:
map[ReproducedBugTitle: ReproducedCrashReport:]

37/2 2026/03/09 22:47 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 103289
							output: 339
							thoughts: 418
						

Thoughts:
**Debugging Pseudo-System Call Behavior**

Okay, still no crash, which is strange. I suspect `syz_open_pts` might be the culprit – either it's not working as expected or perhaps it isn't even available in the current setup. First things first, let's verify its presence in `dev_ptmx.txt`. Ah, yes, there it is: `syz_open_pts(fd fd_tty, flags flags[open_flags]) fd_tty`. But wait a minute... this is a pseudo-syscall. That's a good reminder. Let's explore if we can bypass it altogether and use `syz_open_dev$ptys` instead.

Looking at some existing examples, I see:
```
r0 = syz_open_dev$ptys(0xc, 0x3, 0x0)
r1 = syz_open_dev$ttys(0xc, 0x2, 0x0)
```

Alright, `0xc` translates to 12. Let's double-check the `major const` values. I see that `major const[3]` corresponds to ptys and `major const[2]` corresponds to ttys. So, the correct usage looks like:

Back to `dev_ptmx.txt`, let's confirm the arguments for these system calls.

```
syz_open_dev$ttys(dev const[0xc], major const[2], minor proc[20, 2]) fd_tty
syz_open_dev$ptys(dev const[0xc], major const[3], minor proc[20, 2]) fd_tty
```

Got it. It looks like it uses the value from the executor ID. Let's formulate the new calls based on this.

Okay, so we can construct this.
```
r0 = syz_open_dev$ptys(0xc, 0x3, 0x14)
r1 = syz_open_dev$ttys(0xc, 0x2, 0x14)
```
Wait, the `proc[20, 2]` means a base value of 20, plus executor index times 2. So the minor number will be `20 + n * 2` where `n` is the executor number. In this case, I will simply use 20.

Let's implement this and give it a shot.



38/2 2026/03/09 22:47 tool crash-reproducer
0m Error:
call #0 syz_open_dev$ptys: per proc arg 'proc' has bad value 20

Args:
map[ReproSyz:r0 = syz_open_dev$ptys(0xc, 0x3, 0x14)
r1 = syz_open_dev$ttys(0xc, 0x2, 0x14)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1)]

Results:
map[ReproducedBugTitle: ReproducedCrashReport:]

39/2 2026/03/09 22:47 llm crash-repro-finder
0m Model:
gemini-3-pro-preview

Tokens:
							input: 104630
							output: 331
							thoughts: 19
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**`AUTO` is the Way to Go**

Right, so I was reviewing the code and immediately hit on the `proc` argument. The natural inclination, considering the context, is that `AUTO` is the only sensible choice here. The nuance is always to ensure that implicit behavior is correct, and I've reviewed the design to arrive at this conclusion. Therefore, it's settled – `AUTO` it is. No need to overthink this.



40/2 2026/03/09 22:47 tool crash-reproducer
0m Error:
wrong type *prog.ProcType for AUTO

Args:
map[ReproSyz:r0 = syz_open_dev$ptys(0xc, 0x3, AUTO)
r1 = syz_open_dev$ttys(0xc, 0x2, AUTO)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
write(r0, &AUTO="01010101", 0x4) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1) (async)
ioctl$TCXONC(r1, 0x540a, 0x0) (async)
ioctl$TCXONC(r1, 0x540a, 0x1)]

Results:
map[ReproducedBugTitle: ReproducedCrashReport:]

41/2 2026/03/09 22:47 llm crash-repro-finder
9m Model:
gemini-3-pro-preview

Error:
Error 504, Message: Deadline expired before operation could complete., Status: DEADLINE_EXCEEDED, Details: [map[@type:type.googleapis.com/google.rpc.DebugInfo detail:[ORIGINAL ERROR] generic::deadline_exceeded: [original: beyond::dependency::DEADLINE_EXCEEDED] while running coroutine; Failed while fetching a stream from leaf at '<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at '<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>' [type.googleapis.com/stairways.orch.ErrorLoc='learning/serving/servables/wiz/orch_wiz_servable.cc:1077']
=== Source Location Trace: ===
net/rpc/common/stream/stream-context.cc:1470
learning/brain/research/stairways/orchestrator/root/remote_chain.cc:150
learning/serving/servables/wiz/orch_wiz_servable.cc:1085
;  Failed to run inference for model: go/debugstr   
name: "prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975"
version {
  value: 1
}
signature_name: "serving_default"
; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint:  [google.rpc.error_details_ext] { message: "Deadline expired before operation could complete." details { type_url: "type.googleapis.com/language_labs.genai.debug.GeminiApiDebugInfo" value: "\222\001\375\t\n\335\twhile running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\' [type.googleapis.com/stairways.orch.ErrorLoc=\'learning/serving/servables/wiz/orch_wiz_servable.cc:1077\']\n=== Source Location Trace: ===\nnet/rpc/common/stream/stream-context.cc:1470\nlearning/brain/research/stairways/orchestrator/root/remote_chain.cc:150\nlearning/serving/servables/wiz/orch_wiz_servable.cc:1085\n;  Failed to run inference for model: go/debugstr   \nname: \"prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975\"\nversion {\n  value: 1\n}\nsignature_name: \"serving_default\"\n; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint: \022\033net/rpc/rpc-status.cc:562:0" } } 525002922 { 3 { 1: "/aistudio/gemini-v4p1m-rev24-snowball-lc" } 6 { 5 { 1 { 1: "/aistudio/gemini-v4p1m-rev24-snowball-lc" 3: "serving_default" } 2: 1048576 3: 1 } 6 { 2: 1 3: 0 4: "Non-retryable error: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\'; Failed to close the streaming context; status = DEADLINE_EXCEEDED: while running coroutine; Failed while fetching a stream from leaf at \'<bns:/bns/mh/borg/mh/bns/uniserve-model-server-common-prod-jobs/uniserve.prod-common-mh.prod-common-global.ghostlite_pod-16x16.d25843e7-34fd-4991-a772-fc875026757d/128>\' [type.googleapis.com/stairways.orch.ErrorLoc=\'learning/serving/servables/wiz/orch_wiz_servable.cc:1077\']\n=== Source Location Trace: ===\nnet/rpc/common/stream/stream-context.cc:1470\nlearning/brain/research/stairways/orchestrator/root/remote_chain.cc:150\nlearning/serving/servables/wiz/orch_wiz_servable.cc:1085\n;  Failed to run inference for model: go/debugstr   \nname: \"prod-common-global__/aistudio/gemini-v4p1m-rev24-snowball-lc__main__/aistudio/gemini-v4p1m-rev24-snowball-lc__2026022700__prefill__variant__c3238ed4-cb0b-41c1-a7f5-a73f3b419975\"\nversion {\n  value: 1\n}\nsignature_name: \"serving_default\"\n; [model=/aistudio/gemini-v4p1m-rev24-snowball-lc,target=PredictionService];  for endpoint: " 5 { 1 { 1: 1773096473 2: 991776351 } 2 { 1: 596 2: 826949732 } } 6: "\200\200\004" } } }]]

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)