xref: /haiku/src/system/kernel/arch/x86/64/thread.cpp (revision 7323d0a21daaded71c6231c5b7bcba9db4024a40)
1 /*
2  * Copyright 2018, Jérôme Duval, jerome.duval@gmail.com.
3  * Copyright 2012, Alex Smith, alex@alex-smith.me.uk.
4  * Copyright 2002-2008, Axel Dörfler, axeld@pinc-software.de.
5  * Distributed under the terms of the MIT License.
6  *
7  * Copyright 2001, Travis Geiselbrecht. All rights reserved.
8  * Distributed under the terms of the NewOS License.
9  */
10 
11 
12 #include <arch/thread.h>
13 
14 #include <string.h>
15 
16 #include <commpage.h>
17 #include <cpu.h>
18 #include <debug.h>
19 #include <kernel.h>
20 #include <ksignal.h>
21 #include <int.h>
22 #include <team.h>
23 #include <thread.h>
24 #include <tls.h>
25 #include <tracing.h>
26 #include <util/Random.h>
27 #include <vm/vm_types.h>
28 #include <vm/VMAddressSpace.h>
29 
30 #include "paging/X86PagingStructures.h"
31 #include "paging/X86VMTranslationMap.h"
32 
33 
34 //#define TRACE_ARCH_THREAD
35 #ifdef TRACE_ARCH_THREAD
36 #	define TRACE(x...) dprintf(x)
37 #else
38 #	define TRACE(x...) ;
39 #endif
40 
41 
42 #ifdef SYSCALL_TRACING
43 
44 namespace SyscallTracing {
45 
46 class RestartSyscall : public AbstractTraceEntry {
47 	public:
48 		RestartSyscall()
49 		{
50 			Initialized();
51 		}
52 
53 		virtual void AddDump(TraceOutput& out)
54 		{
55 			out.Print("syscall restart");
56 		}
57 };
58 
59 }
60 
61 #	define TSYSCALL(x)	new(std::nothrow) SyscallTracing::x
62 
63 #else
64 #	define TSYSCALL(x)
65 #endif	// SYSCALL_TRACING
66 
67 
68 extern "C" void x86_64_thread_entry();
69 
70 // Initial thread saved state.
71 static arch_thread sInitialState _ALIGNED(64);
72 extern uint64 gFPUSaveLength;
73 extern bool gHasXsave;
74 extern bool gHasXsavec;
75 
76 
77 void
78 x86_restart_syscall(iframe* frame)
79 {
80 	Thread* thread = thread_get_current_thread();
81 
82 	atomic_and(&thread->flags, ~THREAD_FLAGS_RESTART_SYSCALL);
83 	atomic_or(&thread->flags, THREAD_FLAGS_SYSCALL_RESTARTED);
84 
85 	// Get back the original system call number and modify the frame to
86 	// re-execute the syscall instruction.
87 	frame->ax = frame->orig_rax;
88 	frame->ip -= 2;
89 
90 	TSYSCALL(RestartSyscall());
91 }
92 
93 
94 void
95 x86_set_tls_context(Thread* thread)
96 {
97 	// Set FS segment base address to the TLS segment.
98 	x86_write_msr(IA32_MSR_FS_BASE, thread->user_local_storage);
99 }
100 
101 
102 static addr_t
103 arch_randomize_stack_pointer(addr_t value)
104 {
105 	static_assert(MAX_RANDOM_VALUE >= B_PAGE_SIZE - 1,
106 		"randomization range is too big");
107 	value -= random_value() & (B_PAGE_SIZE - 1);
108 	return (value & ~addr_t(0xf)) - 8;
109 		// This means, result % 16 == 8, which is what rsp should adhere to
110 		// when a function is entered for the stack to be considered aligned to
111 		// 16 byte.
112 }
113 
114 
115 static uint8*
116 get_signal_stack(Thread* thread, iframe* frame, struct sigaction* action,
117 	size_t spaceNeeded)
118 {
119 	// Use the alternate signal stack if we should and can.
120 	if (thread->signal_stack_enabled
121 			&& (action->sa_flags & SA_ONSTACK) != 0
122 			&& (frame->user_sp < thread->signal_stack_base
123 				|| frame->user_sp >= thread->signal_stack_base
124 					+ thread->signal_stack_size)) {
125 		addr_t stackTop = thread->signal_stack_base + thread->signal_stack_size;
126 		return (uint8*)arch_randomize_stack_pointer(stackTop - spaceNeeded);
127 	}
128 
129 	// We are going to use the stack that we are already on. We must not touch
130 	// the red zone (128 byte area below the stack pointer, reserved for use
131 	// by functions to store temporary data and guaranteed not to be modified
132 	// by signal handlers).
133 	return (uint8*)((frame->user_sp - 128 - spaceNeeded) & ~addr_t(0xf)) - 8;
134 		// align stack pointer (cf. arch_randomize_stack_pointer())
135 }
136 
137 
138 //	#pragma mark -
139 
140 
141 status_t
142 arch_thread_init(kernel_args* args)
143 {
144 	// Save one global valid FPU state; it will be copied in the arch dependent
145 	// part of each new thread.
146 	if (gHasXsave || gHasXsavec) {
147 		memset(sInitialState.fpu_state, 0, gFPUSaveLength);
148 		if (gHasXsavec) {
149 			asm volatile (
150 				"clts;"		\
151 				"fninit;"	\
152 				"fnclex;"	\
153 				"movl $0x7,%%eax;"	\
154 				"movl $0x0,%%edx;"	\
155 				"xsavec64 %0"
156 				:: "m" (sInitialState.fpu_state));
157 		} else {
158 			asm volatile (
159 				"clts;"		\
160 				"fninit;"	\
161 				"fnclex;"	\
162 				"movl $0x7,%%eax;"	\
163 				"movl $0x0,%%edx;"	\
164 				"xsave64 %0"
165 				:: "m" (sInitialState.fpu_state));
166 		}
167 	} else {
168 		asm volatile (
169 			"clts;"		\
170 			"fninit;"	\
171 			"fnclex;"	\
172 			"fxsaveq %0"
173 			:: "m" (sInitialState.fpu_state));
174 	}
175 	return B_OK;
176 }
177 
178 
179 status_t
180 arch_thread_init_thread_struct(Thread* thread)
181 {
182 	// Copy the initial saved FPU state to the new thread.
183 	memcpy(&thread->arch_info, &sInitialState, sizeof(arch_thread));
184 
185 	// Initialise the current thread pointer.
186 	thread->arch_info.thread = thread;
187 
188 	return B_OK;
189 }
190 
191 
192 /*!	Prepares the given thread's kernel stack for executing its entry function.
193 
194 	\param thread The thread.
195 	\param stack The usable bottom of the thread's kernel stack.
196 	\param stackTop The usable top of the thread's kernel stack.
197 	\param function The entry function the thread shall execute.
198 	\param data Pointer to be passed to the entry function.
199 */
200 void
201 arch_thread_init_kthread_stack(Thread* thread, void* _stack, void* _stackTop,
202 	void (*function)(void*), const void* data)
203 {
204 	uintptr_t* stackTop = static_cast<uintptr_t*>(_stackTop);
205 
206 	TRACE("arch_thread_init_kthread_stack: stack top %p, function %p, data: "
207 		"%p\n", _stackTop, function, data);
208 
209 	// Save the stack top for system call entry.
210 	thread->arch_info.syscall_rsp = (uint64*)thread->kernel_stack_top;
211 
212 	thread->arch_info.instruction_pointer
213 		= reinterpret_cast<uintptr_t>(x86_64_thread_entry);
214 
215 	*--stackTop = uintptr_t(data);
216 	*--stackTop = uintptr_t(function);
217 
218 	// Save the stack position.
219 	thread->arch_info.current_stack = stackTop;
220 }
221 
222 
223 void
224 arch_thread_dump_info(void* info)
225 {
226 	arch_thread* thread = (arch_thread*)info;
227 
228 	kprintf("\trsp: %p\n", thread->current_stack);
229 	kprintf("\tsyscall_rsp: %p\n", thread->syscall_rsp);
230 	kprintf("\tuser_rsp: %p\n", thread->user_rsp);
231 	kprintf("\tfpu_state at %p\n", thread->fpu_state);
232 }
233 
234 
235 /*!	Sets up initial thread context and enters user space
236 */
237 status_t
238 arch_thread_enter_userspace(Thread* thread, addr_t entry, void* args1,
239 	void* args2)
240 {
241 	addr_t stackTop = thread->user_stack_base + thread->user_stack_size;
242 	addr_t codeAddr;
243 
244 	TRACE("arch_thread_enter_userspace: entry %#lx, args %p %p, "
245 		"stackTop %#lx\n", entry, args1, args2, stackTop);
246 
247 	stackTop = arch_randomize_stack_pointer(stackTop - sizeof(codeAddr));
248 
249 	// Copy the address of the stub that calls exit_thread() when the thread
250 	// entry function returns to the top of the stack to act as the return
251 	// address. The stub is inside commpage.
252 	addr_t commPageAddress = (addr_t)thread->team->commpage_address;
253 	set_ac();
254 	codeAddr = ((addr_t*)commPageAddress)[COMMPAGE_ENTRY_X86_THREAD_EXIT]
255 		+ commPageAddress;
256 	clear_ac();
257 	if (user_memcpy((void*)stackTop, (const void*)&codeAddr, sizeof(codeAddr))
258 			!= B_OK)
259 		return B_BAD_ADDRESS;
260 
261 	// Prepare the user iframe.
262 	iframe frame = {};
263 	frame.type = IFRAME_TYPE_SYSCALL;
264 	frame.si = (uint64)args2;
265 	frame.di = (uint64)args1;
266 	frame.ip = entry;
267 	frame.cs = USER_CODE_SELECTOR;
268 	frame.flags = X86_EFLAGS_RESERVED1 | X86_EFLAGS_INTERRUPT;
269 	frame.sp = stackTop;
270 	frame.ss = USER_DATA_SELECTOR;
271 
272 	// Return to userland. Never returns.
273 	x86_initial_return_to_userland(thread, &frame);
274 
275 	return B_OK;
276 }
277 
278 
279 /*!	Sets up the user iframe for invoking a signal handler.
280 
281 	The function fills in the remaining fields of the given \a signalFrameData,
282 	copies it to the thread's userland stack (the one on which the signal shall
283 	be handled), and sets up the user iframe so that when returning to userland
284 	a wrapper function is executed that calls the user-defined signal handler.
285 	When the signal handler returns, the wrapper function shall call the
286 	"restore signal frame" syscall with the (possibly modified) signal frame
287 	data.
288 
289 	The following fields of the \a signalFrameData structure still need to be
290 	filled in:
291 	- \c context.uc_stack: The stack currently used by the thread.
292 	- \c context.uc_mcontext: The current userland state of the registers.
293 	- \c syscall_restart_return_value: Architecture specific use. On x86_64 the
294 		value of rax which is overwritten by the syscall return value.
295 
296 	Furthermore the function needs to set \c thread->user_signal_context to the
297 	userland pointer to the \c ucontext_t on the user stack.
298 
299 	\param thread The current thread.
300 	\param action The signal action specified for the signal to be handled.
301 	\param signalFrameData A partially initialized structure of all the data
302 		that need to be copied to userland.
303 	\return \c B_OK on success, another error code, if something goes wrong.
304 */
305 status_t
306 arch_setup_signal_frame(Thread* thread, struct sigaction* action,
307 	struct signal_frame_data* signalFrameData)
308 {
309 	iframe* frame = x86_get_current_iframe();
310 	if (!IFRAME_IS_USER(frame)) {
311 		panic("arch_setup_signal_frame(): No user iframe!");
312 		return B_BAD_VALUE;
313 	}
314 
315 	// Store the register state.
316 	signalFrameData->context.uc_mcontext.rax = frame->ax;
317 	signalFrameData->context.uc_mcontext.rbx = frame->bx;
318 	signalFrameData->context.uc_mcontext.rcx = frame->cx;
319 	signalFrameData->context.uc_mcontext.rdx = frame->dx;
320 	signalFrameData->context.uc_mcontext.rdi = frame->di;
321 	signalFrameData->context.uc_mcontext.rsi = frame->si;
322 	signalFrameData->context.uc_mcontext.rbp = frame->bp;
323 	signalFrameData->context.uc_mcontext.r8 = frame->r8;
324 	signalFrameData->context.uc_mcontext.r9 = frame->r9;
325 	signalFrameData->context.uc_mcontext.r10 = frame->r10;
326 	signalFrameData->context.uc_mcontext.r11 = frame->r11;
327 	signalFrameData->context.uc_mcontext.r12 = frame->r12;
328 	signalFrameData->context.uc_mcontext.r13 = frame->r13;
329 	signalFrameData->context.uc_mcontext.r14 = frame->r14;
330 	signalFrameData->context.uc_mcontext.r15 = frame->r15;
331 	signalFrameData->context.uc_mcontext.rsp = frame->user_sp;
332 	signalFrameData->context.uc_mcontext.rip = frame->ip;
333 	signalFrameData->context.uc_mcontext.rflags = frame->flags;
334 
335 	if (frame->fpu != nullptr) {
336 		memcpy((void*)&signalFrameData->context.uc_mcontext.fpu, frame->fpu,
337 			gFPUSaveLength);
338 	} else {
339 		memcpy((void*)&signalFrameData->context.uc_mcontext.fpu,
340 			sInitialState.fpu_state, gFPUSaveLength);
341 	}
342 
343 	// Fill in signalFrameData->context.uc_stack.
344 	signal_get_user_stack(frame->user_sp, &signalFrameData->context.uc_stack);
345 
346 	// Store syscall_restart_return_value.
347 	signalFrameData->syscall_restart_return_value = frame->orig_rax;
348 
349 	// Get the stack to use and copy the frame data to it.
350 	uint8* userStack = get_signal_stack(thread, frame, action,
351 		sizeof(*signalFrameData) + sizeof(frame->ip));
352 
353 	signal_frame_data* userSignalFrameData
354 		= (signal_frame_data*)(userStack + sizeof(frame->ip));
355 
356 	if (user_memcpy(userSignalFrameData, signalFrameData,
357 			sizeof(*signalFrameData)) != B_OK) {
358 		return B_BAD_ADDRESS;
359 	}
360 
361 	// Copy a return address to the stack so that backtraces will be correct.
362 	if (user_memcpy(userStack, &frame->ip, sizeof(frame->ip)) != B_OK)
363 		return B_BAD_ADDRESS;
364 
365 	// Update Thread::user_signal_context, now that everything seems to have
366 	// gone fine.
367 	thread->user_signal_context = &userSignalFrameData->context;
368 
369 	// Set up the iframe to execute the signal handler wrapper on our prepared
370 	// stack. First argument points to the frame data.
371 	addr_t* commPageAddress = (addr_t*)thread->team->commpage_address;
372 	frame->user_sp = (addr_t)userStack;
373 	set_ac();
374 	frame->ip = commPageAddress[COMMPAGE_ENTRY_X86_SIGNAL_HANDLER]
375 		+ (addr_t)commPageAddress;
376 	clear_ac();
377 	frame->di = (addr_t)userSignalFrameData;
378 	frame->flags &= ~(uint64)(X86_EFLAGS_TRAP | X86_EFLAGS_DIRECTION);
379 
380 	return B_OK;
381 }
382 
383 
384 int64
385 arch_restore_signal_frame(struct signal_frame_data* signalFrameData)
386 {
387 	iframe* frame = x86_get_current_iframe();
388 
389 	frame->orig_rax = signalFrameData->syscall_restart_return_value;
390 	frame->ax = signalFrameData->context.uc_mcontext.rax;
391 	frame->bx = signalFrameData->context.uc_mcontext.rbx;
392 	frame->cx = signalFrameData->context.uc_mcontext.rcx;
393 	frame->dx = signalFrameData->context.uc_mcontext.rdx;
394 	frame->di = signalFrameData->context.uc_mcontext.rdi;
395 	frame->si = signalFrameData->context.uc_mcontext.rsi;
396 	frame->bp = signalFrameData->context.uc_mcontext.rbp;
397 	frame->r8 = signalFrameData->context.uc_mcontext.r8;
398 	frame->r9 = signalFrameData->context.uc_mcontext.r9;
399 	frame->r10 = signalFrameData->context.uc_mcontext.r10;
400 	frame->r11 = signalFrameData->context.uc_mcontext.r11;
401 	frame->r12 = signalFrameData->context.uc_mcontext.r12;
402 	frame->r13 = signalFrameData->context.uc_mcontext.r13;
403 	frame->r14 = signalFrameData->context.uc_mcontext.r14;
404 	frame->r15 = signalFrameData->context.uc_mcontext.r15;
405 	frame->user_sp = signalFrameData->context.uc_mcontext.rsp;
406 	frame->ip = signalFrameData->context.uc_mcontext.rip;
407 	frame->flags = (frame->flags & ~(uint64)X86_EFLAGS_USER_FLAGS)
408 		| (signalFrameData->context.uc_mcontext.rflags & X86_EFLAGS_USER_FLAGS);
409 
410 	Thread* thread = thread_get_current_thread();
411 
412 	memcpy(thread->arch_info.fpu_state,
413 		(void*)&signalFrameData->context.uc_mcontext.fpu, gFPUSaveLength);
414 	frame->fpu = &thread->arch_info.fpu_state;
415 
416 	// The syscall return code overwrites frame->ax with the return value of
417 	// the syscall, need to return it here to ensure the correct value is
418 	// restored.
419 	return frame->ax;
420 }
421