xref: /haiku/src/system/kernel/arch/x86/64/thread.cpp (revision 8c78892580f132d10e624aef96f835df8d94bf19)
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 		| (3 << X86_EFLAGS_IO_PRIVILEG_LEVEL_SHIFT);
270 	frame.sp = stackTop;
271 	frame.ss = USER_DATA_SELECTOR;
272 
273 	// Return to userland. Never returns.
274 	x86_initial_return_to_userland(thread, &frame);
275 
276 	return B_OK;
277 }
278 
279 
280 /*!	Sets up the user iframe for invoking a signal handler.
281 
282 	The function fills in the remaining fields of the given \a signalFrameData,
283 	copies it to the thread's userland stack (the one on which the signal shall
284 	be handled), and sets up the user iframe so that when returning to userland
285 	a wrapper function is executed that calls the user-defined signal handler.
286 	When the signal handler returns, the wrapper function shall call the
287 	"restore signal frame" syscall with the (possibly modified) signal frame
288 	data.
289 
290 	The following fields of the \a signalFrameData structure still need to be
291 	filled in:
292 	- \c context.uc_stack: The stack currently used by the thread.
293 	- \c context.uc_mcontext: The current userland state of the registers.
294 	- \c syscall_restart_return_value: Architecture specific use. On x86_64 the
295 		value of rax which is overwritten by the syscall return value.
296 
297 	Furthermore the function needs to set \c thread->user_signal_context to the
298 	userland pointer to the \c ucontext_t on the user stack.
299 
300 	\param thread The current thread.
301 	\param action The signal action specified for the signal to be handled.
302 	\param signalFrameData A partially initialized structure of all the data
303 		that need to be copied to userland.
304 	\return \c B_OK on success, another error code, if something goes wrong.
305 */
306 status_t
307 arch_setup_signal_frame(Thread* thread, struct sigaction* action,
308 	struct signal_frame_data* signalFrameData)
309 {
310 	iframe* frame = x86_get_current_iframe();
311 	if (!IFRAME_IS_USER(frame)) {
312 		panic("arch_setup_signal_frame(): No user iframe!");
313 		return B_BAD_VALUE;
314 	}
315 
316 	// Store the register state.
317 	signalFrameData->context.uc_mcontext.rax = frame->ax;
318 	signalFrameData->context.uc_mcontext.rbx = frame->bx;
319 	signalFrameData->context.uc_mcontext.rcx = frame->cx;
320 	signalFrameData->context.uc_mcontext.rdx = frame->dx;
321 	signalFrameData->context.uc_mcontext.rdi = frame->di;
322 	signalFrameData->context.uc_mcontext.rsi = frame->si;
323 	signalFrameData->context.uc_mcontext.rbp = frame->bp;
324 	signalFrameData->context.uc_mcontext.r8 = frame->r8;
325 	signalFrameData->context.uc_mcontext.r9 = frame->r9;
326 	signalFrameData->context.uc_mcontext.r10 = frame->r10;
327 	signalFrameData->context.uc_mcontext.r11 = frame->r11;
328 	signalFrameData->context.uc_mcontext.r12 = frame->r12;
329 	signalFrameData->context.uc_mcontext.r13 = frame->r13;
330 	signalFrameData->context.uc_mcontext.r14 = frame->r14;
331 	signalFrameData->context.uc_mcontext.r15 = frame->r15;
332 	signalFrameData->context.uc_mcontext.rsp = frame->user_sp;
333 	signalFrameData->context.uc_mcontext.rip = frame->ip;
334 	signalFrameData->context.uc_mcontext.rflags = frame->flags;
335 
336 	if (frame->fpu != nullptr) {
337 		memcpy((void*)&signalFrameData->context.uc_mcontext.fpu, frame->fpu,
338 			gFPUSaveLength);
339 	} else {
340 		memcpy((void*)&signalFrameData->context.uc_mcontext.fpu,
341 			sInitialState.fpu_state, gFPUSaveLength);
342 	}
343 
344 	// Fill in signalFrameData->context.uc_stack.
345 	signal_get_user_stack(frame->user_sp, &signalFrameData->context.uc_stack);
346 
347 	// Store syscall_restart_return_value.
348 	signalFrameData->syscall_restart_return_value = frame->orig_rax;
349 
350 	// Get the stack to use and copy the frame data to it.
351 	uint8* userStack = get_signal_stack(thread, frame, action,
352 		sizeof(*signalFrameData) + sizeof(frame->ip));
353 
354 	signal_frame_data* userSignalFrameData
355 		= (signal_frame_data*)(userStack + sizeof(frame->ip));
356 
357 	if (user_memcpy(userSignalFrameData, signalFrameData,
358 			sizeof(*signalFrameData)) != B_OK) {
359 		return B_BAD_ADDRESS;
360 	}
361 
362 	// Copy a return address to the stack so that backtraces will be correct.
363 	if (user_memcpy(userStack, &frame->ip, sizeof(frame->ip)) != B_OK)
364 		return B_BAD_ADDRESS;
365 
366 	// Update Thread::user_signal_context, now that everything seems to have
367 	// gone fine.
368 	thread->user_signal_context = &userSignalFrameData->context;
369 
370 	// Set up the iframe to execute the signal handler wrapper on our prepared
371 	// stack. First argument points to the frame data.
372 	addr_t* commPageAddress = (addr_t*)thread->team->commpage_address;
373 	frame->user_sp = (addr_t)userStack;
374 	set_ac();
375 	frame->ip = commPageAddress[COMMPAGE_ENTRY_X86_SIGNAL_HANDLER]
376 		+ (addr_t)commPageAddress;
377 	clear_ac();
378 	frame->di = (addr_t)userSignalFrameData;
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