1/*
2 * Copyright 2010 Tilera Corporation. All Rights Reserved.
3 *
4 *   This program is free software; you can redistribute it and/or
5 *   modify it under the terms of the GNU General Public License
6 *   as published by the Free Software Foundation, version 2.
7 *
8 *   This program is distributed in the hope that it will be useful, but
9 *   WITHOUT ANY WARRANTY; without even the implied warranty of
10 *   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
11 *   NON INFRINGEMENT.  See the GNU General Public License for
12 *   more details.
13 */
14
15#include <linux/sched.h>
16#include <linux/preempt.h>
17#include <linux/module.h>
18#include <linux/fs.h>
19#include <linux/kprobes.h>
20#include <linux/elfcore.h>
21#include <linux/tick.h>
22#include <linux/init.h>
23#include <linux/mm.h>
24#include <linux/compat.h>
25#include <linux/hardirq.h>
26#include <linux/syscalls.h>
27#include <linux/kernel.h>
28#include <linux/tracehook.h>
29#include <linux/signal.h>
30#include <linux/context_tracking.h>
31#include <asm/stack.h>
32#include <asm/switch_to.h>
33#include <asm/homecache.h>
34#include <asm/syscalls.h>
35#include <asm/traps.h>
36#include <asm/setup.h>
37#include <asm/uaccess.h>
38#ifdef CONFIG_HARDWALL
39#include <asm/hardwall.h>
40#endif
41#include <arch/chip.h>
42#include <arch/abi.h>
43#include <arch/sim_def.h>
44
45/*
46 * Use the (x86) "idle=poll" option to prefer low latency when leaving the
47 * idle loop over low power while in the idle loop, e.g. if we have
48 * one thread per core and we want to get threads out of futex waits fast.
49 */
50static int __init idle_setup(char *str)
51{
52	if (!str)
53		return -EINVAL;
54
55	if (!strcmp(str, "poll")) {
56		pr_info("using polling idle threads\n");
57		cpu_idle_poll_ctrl(true);
58		return 0;
59	} else if (!strcmp(str, "halt")) {
60		return 0;
61	}
62	return -1;
63}
64early_param("idle", idle_setup);
65
66void arch_cpu_idle(void)
67{
68	__this_cpu_write(irq_stat.idle_timestamp, jiffies);
69	_cpu_idle();
70}
71
72/*
73 * Release a thread_info structure
74 */
75void arch_release_thread_info(struct thread_info *info)
76{
77	struct single_step_state *step_state = info->step_state;
78
79	if (step_state) {
80
81		/*
82		 * FIXME: we don't munmap step_state->buffer
83		 * because the mm_struct for this process (info->task->mm)
84		 * has already been zeroed in exit_mm().  Keeping a
85		 * reference to it here seems like a bad move, so this
86		 * means we can't munmap() the buffer, and therefore if we
87		 * ptrace multiple threads in a process, we will slowly
88		 * leak user memory.  (Note that as soon as the last
89		 * thread in a process dies, we will reclaim all user
90		 * memory including single-step buffers in the usual way.)
91		 * We should either assign a kernel VA to this buffer
92		 * somehow, or we should associate the buffer(s) with the
93		 * mm itself so we can clean them up that way.
94		 */
95		kfree(step_state);
96	}
97}
98
99static void save_arch_state(struct thread_struct *t);
100
101int copy_thread(unsigned long clone_flags, unsigned long sp,
102		unsigned long arg, struct task_struct *p)
103{
104	struct pt_regs *childregs = task_pt_regs(p);
105	unsigned long ksp;
106	unsigned long *callee_regs;
107
108	/*
109	 * Set up the stack and stack pointer appropriately for the
110	 * new child to find itself woken up in __switch_to().
111	 * The callee-saved registers must be on the stack to be read;
112	 * the new task will then jump to assembly support to handle
113	 * calling schedule_tail(), etc., and (for userspace tasks)
114	 * returning to the context set up in the pt_regs.
115	 */
116	ksp = (unsigned long) childregs;
117	ksp -= C_ABI_SAVE_AREA_SIZE;   /* interrupt-entry save area */
118	((long *)ksp)[0] = ((long *)ksp)[1] = 0;
119	ksp -= CALLEE_SAVED_REGS_COUNT * sizeof(unsigned long);
120	callee_regs = (unsigned long *)ksp;
121	ksp -= C_ABI_SAVE_AREA_SIZE;   /* __switch_to() save area */
122	((long *)ksp)[0] = ((long *)ksp)[1] = 0;
123	p->thread.ksp = ksp;
124
125	/* Record the pid of the task that created this one. */
126	p->thread.creator_pid = current->pid;
127
128	if (unlikely(p->flags & PF_KTHREAD)) {
129		/* kernel thread */
130		memset(childregs, 0, sizeof(struct pt_regs));
131		memset(&callee_regs[2], 0,
132		       (CALLEE_SAVED_REGS_COUNT - 2) * sizeof(unsigned long));
133		callee_regs[0] = sp;   /* r30 = function */
134		callee_regs[1] = arg;  /* r31 = arg */
135		childregs->ex1 = PL_ICS_EX1(KERNEL_PL, 0);
136		p->thread.pc = (unsigned long) ret_from_kernel_thread;
137		return 0;
138	}
139
140	/*
141	 * Start new thread in ret_from_fork so it schedules properly
142	 * and then return from interrupt like the parent.
143	 */
144	p->thread.pc = (unsigned long) ret_from_fork;
145
146	/*
147	 * Do not clone step state from the parent; each thread
148	 * must make its own lazily.
149	 */
150	task_thread_info(p)->step_state = NULL;
151
152#ifdef __tilegx__
153	/*
154	 * Do not clone unalign jit fixup from the parent; each thread
155	 * must allocate its own on demand.
156	 */
157	task_thread_info(p)->unalign_jit_base = NULL;
158#endif
159
160	/*
161	 * Copy the registers onto the kernel stack so the
162	 * return-from-interrupt code will reload it into registers.
163	 */
164	*childregs = *current_pt_regs();
165	childregs->regs[0] = 0;         /* return value is zero */
166	if (sp)
167		childregs->sp = sp;  /* override with new user stack pointer */
168	memcpy(callee_regs, &childregs->regs[CALLEE_SAVED_FIRST_REG],
169	       CALLEE_SAVED_REGS_COUNT * sizeof(unsigned long));
170
171	/* Save user stack top pointer so we can ID the stack vm area later. */
172	p->thread.usp0 = childregs->sp;
173
174	/*
175	 * If CLONE_SETTLS is set, set "tp" in the new task to "r4",
176	 * which is passed in as arg #5 to sys_clone().
177	 */
178	if (clone_flags & CLONE_SETTLS)
179		childregs->tp = childregs->regs[4];
180
181
182#if CHIP_HAS_TILE_DMA()
183	/*
184	 * No DMA in the new thread.  We model this on the fact that
185	 * fork() clears the pending signals, alarms, and aio for the child.
186	 */
187	memset(&p->thread.tile_dma_state, 0, sizeof(struct tile_dma_state));
188	memset(&p->thread.dma_async_tlb, 0, sizeof(struct async_tlb));
189#endif
190
191	/* New thread has its miscellaneous processor state bits clear. */
192	p->thread.proc_status = 0;
193
194#ifdef CONFIG_HARDWALL
195	/* New thread does not own any networks. */
196	memset(&p->thread.hardwall[0], 0,
197	       sizeof(struct hardwall_task) * HARDWALL_TYPES);
198#endif
199
200
201	/*
202	 * Start the new thread with the current architecture state
203	 * (user interrupt masks, etc.).
204	 */
205	save_arch_state(&p->thread);
206
207	return 0;
208}
209
210int set_unalign_ctl(struct task_struct *tsk, unsigned int val)
211{
212	task_thread_info(tsk)->align_ctl = val;
213	return 0;
214}
215
216int get_unalign_ctl(struct task_struct *tsk, unsigned long adr)
217{
218	return put_user(task_thread_info(tsk)->align_ctl,
219			(unsigned int __user *)adr);
220}
221
222static struct task_struct corrupt_current = { .comm = "<corrupt>" };
223
224/*
225 * Return "current" if it looks plausible, or else a pointer to a dummy.
226 * This can be helpful if we are just trying to emit a clean panic.
227 */
228struct task_struct *validate_current(void)
229{
230	struct task_struct *tsk = current;
231	if (unlikely((unsigned long)tsk < PAGE_OFFSET ||
232		     (high_memory && (void *)tsk > high_memory) ||
233		     ((unsigned long)tsk & (__alignof__(*tsk) - 1)) != 0)) {
234		pr_err("Corrupt 'current' %p (sp %#lx)\n", tsk, stack_pointer);
235		tsk = &corrupt_current;
236	}
237	return tsk;
238}
239
240/* Take and return the pointer to the previous task, for schedule_tail(). */
241struct task_struct *sim_notify_fork(struct task_struct *prev)
242{
243	struct task_struct *tsk = current;
244	__insn_mtspr(SPR_SIM_CONTROL, SIM_CONTROL_OS_FORK_PARENT |
245		     (tsk->thread.creator_pid << _SIM_CONTROL_OPERATOR_BITS));
246	__insn_mtspr(SPR_SIM_CONTROL, SIM_CONTROL_OS_FORK |
247		     (tsk->pid << _SIM_CONTROL_OPERATOR_BITS));
248	return prev;
249}
250
251int dump_task_regs(struct task_struct *tsk, elf_gregset_t *regs)
252{
253	struct pt_regs *ptregs = task_pt_regs(tsk);
254	elf_core_copy_regs(regs, ptregs);
255	return 1;
256}
257
258#if CHIP_HAS_TILE_DMA()
259
260/* Allow user processes to access the DMA SPRs */
261void grant_dma_mpls(void)
262{
263#if CONFIG_KERNEL_PL == 2
264	__insn_mtspr(SPR_MPL_DMA_CPL_SET_1, 1);
265	__insn_mtspr(SPR_MPL_DMA_NOTIFY_SET_1, 1);
266#else
267	__insn_mtspr(SPR_MPL_DMA_CPL_SET_0, 1);
268	__insn_mtspr(SPR_MPL_DMA_NOTIFY_SET_0, 1);
269#endif
270}
271
272/* Forbid user processes from accessing the DMA SPRs */
273void restrict_dma_mpls(void)
274{
275#if CONFIG_KERNEL_PL == 2
276	__insn_mtspr(SPR_MPL_DMA_CPL_SET_2, 1);
277	__insn_mtspr(SPR_MPL_DMA_NOTIFY_SET_2, 1);
278#else
279	__insn_mtspr(SPR_MPL_DMA_CPL_SET_1, 1);
280	__insn_mtspr(SPR_MPL_DMA_NOTIFY_SET_1, 1);
281#endif
282}
283
284/* Pause the DMA engine, then save off its state registers. */
285static void save_tile_dma_state(struct tile_dma_state *dma)
286{
287	unsigned long state = __insn_mfspr(SPR_DMA_USER_STATUS);
288	unsigned long post_suspend_state;
289
290	/* If we're running, suspend the engine. */
291	if ((state & DMA_STATUS_MASK) == SPR_DMA_STATUS__RUNNING_MASK)
292		__insn_mtspr(SPR_DMA_CTR, SPR_DMA_CTR__SUSPEND_MASK);
293
294	/*
295	 * Wait for the engine to idle, then save regs.  Note that we
296	 * want to record the "running" bit from before suspension,
297	 * and the "done" bit from after, so that we can properly
298	 * distinguish a case where the user suspended the engine from
299	 * the case where the kernel suspended as part of the context
300	 * swap.
301	 */
302	do {
303		post_suspend_state = __insn_mfspr(SPR_DMA_USER_STATUS);
304	} while (post_suspend_state & SPR_DMA_STATUS__BUSY_MASK);
305
306	dma->src = __insn_mfspr(SPR_DMA_SRC_ADDR);
307	dma->src_chunk = __insn_mfspr(SPR_DMA_SRC_CHUNK_ADDR);
308	dma->dest = __insn_mfspr(SPR_DMA_DST_ADDR);
309	dma->dest_chunk = __insn_mfspr(SPR_DMA_DST_CHUNK_ADDR);
310	dma->strides = __insn_mfspr(SPR_DMA_STRIDE);
311	dma->chunk_size = __insn_mfspr(SPR_DMA_CHUNK_SIZE);
312	dma->byte = __insn_mfspr(SPR_DMA_BYTE);
313	dma->status = (state & SPR_DMA_STATUS__RUNNING_MASK) |
314		(post_suspend_state & SPR_DMA_STATUS__DONE_MASK);
315}
316
317/* Restart a DMA that was running before we were context-switched out. */
318static void restore_tile_dma_state(struct thread_struct *t)
319{
320	const struct tile_dma_state *dma = &t->tile_dma_state;
321
322	/*
323	 * The only way to restore the done bit is to run a zero
324	 * length transaction.
325	 */
326	if ((dma->status & SPR_DMA_STATUS__DONE_MASK) &&
327	    !(__insn_mfspr(SPR_DMA_USER_STATUS) & SPR_DMA_STATUS__DONE_MASK)) {
328		__insn_mtspr(SPR_DMA_BYTE, 0);
329		__insn_mtspr(SPR_DMA_CTR, SPR_DMA_CTR__REQUEST_MASK);
330		while (__insn_mfspr(SPR_DMA_USER_STATUS) &
331		       SPR_DMA_STATUS__BUSY_MASK)
332			;
333	}
334
335	__insn_mtspr(SPR_DMA_SRC_ADDR, dma->src);
336	__insn_mtspr(SPR_DMA_SRC_CHUNK_ADDR, dma->src_chunk);
337	__insn_mtspr(SPR_DMA_DST_ADDR, dma->dest);
338	__insn_mtspr(SPR_DMA_DST_CHUNK_ADDR, dma->dest_chunk);
339	__insn_mtspr(SPR_DMA_STRIDE, dma->strides);
340	__insn_mtspr(SPR_DMA_CHUNK_SIZE, dma->chunk_size);
341	__insn_mtspr(SPR_DMA_BYTE, dma->byte);
342
343	/*
344	 * Restart the engine if we were running and not done.
345	 * Clear a pending async DMA fault that we were waiting on return
346	 * to user space to execute, since we expect the DMA engine
347	 * to regenerate those faults for us now.  Note that we don't
348	 * try to clear the TIF_ASYNC_TLB flag, since it's relatively
349	 * harmless if set, and it covers both DMA and the SN processor.
350	 */
351	if ((dma->status & DMA_STATUS_MASK) == SPR_DMA_STATUS__RUNNING_MASK) {
352		t->dma_async_tlb.fault_num = 0;
353		__insn_mtspr(SPR_DMA_CTR, SPR_DMA_CTR__REQUEST_MASK);
354	}
355}
356
357#endif
358
359static void save_arch_state(struct thread_struct *t)
360{
361#if CHIP_HAS_SPLIT_INTR_MASK()
362	t->interrupt_mask = __insn_mfspr(SPR_INTERRUPT_MASK_0_0) |
363		((u64)__insn_mfspr(SPR_INTERRUPT_MASK_0_1) << 32);
364#else
365	t->interrupt_mask = __insn_mfspr(SPR_INTERRUPT_MASK_0);
366#endif
367	t->ex_context[0] = __insn_mfspr(SPR_EX_CONTEXT_0_0);
368	t->ex_context[1] = __insn_mfspr(SPR_EX_CONTEXT_0_1);
369	t->system_save[0] = __insn_mfspr(SPR_SYSTEM_SAVE_0_0);
370	t->system_save[1] = __insn_mfspr(SPR_SYSTEM_SAVE_0_1);
371	t->system_save[2] = __insn_mfspr(SPR_SYSTEM_SAVE_0_2);
372	t->system_save[3] = __insn_mfspr(SPR_SYSTEM_SAVE_0_3);
373	t->intctrl_0 = __insn_mfspr(SPR_INTCTRL_0_STATUS);
374	t->proc_status = __insn_mfspr(SPR_PROC_STATUS);
375#if !CHIP_HAS_FIXED_INTVEC_BASE()
376	t->interrupt_vector_base = __insn_mfspr(SPR_INTERRUPT_VECTOR_BASE_0);
377#endif
378	t->tile_rtf_hwm = __insn_mfspr(SPR_TILE_RTF_HWM);
379#if CHIP_HAS_DSTREAM_PF()
380	t->dstream_pf = __insn_mfspr(SPR_DSTREAM_PF);
381#endif
382}
383
384static void restore_arch_state(const struct thread_struct *t)
385{
386#if CHIP_HAS_SPLIT_INTR_MASK()
387	__insn_mtspr(SPR_INTERRUPT_MASK_0_0, (u32) t->interrupt_mask);
388	__insn_mtspr(SPR_INTERRUPT_MASK_0_1, t->interrupt_mask >> 32);
389#else
390	__insn_mtspr(SPR_INTERRUPT_MASK_0, t->interrupt_mask);
391#endif
392	__insn_mtspr(SPR_EX_CONTEXT_0_0, t->ex_context[0]);
393	__insn_mtspr(SPR_EX_CONTEXT_0_1, t->ex_context[1]);
394	__insn_mtspr(SPR_SYSTEM_SAVE_0_0, t->system_save[0]);
395	__insn_mtspr(SPR_SYSTEM_SAVE_0_1, t->system_save[1]);
396	__insn_mtspr(SPR_SYSTEM_SAVE_0_2, t->system_save[2]);
397	__insn_mtspr(SPR_SYSTEM_SAVE_0_3, t->system_save[3]);
398	__insn_mtspr(SPR_INTCTRL_0_STATUS, t->intctrl_0);
399	__insn_mtspr(SPR_PROC_STATUS, t->proc_status);
400#if !CHIP_HAS_FIXED_INTVEC_BASE()
401	__insn_mtspr(SPR_INTERRUPT_VECTOR_BASE_0, t->interrupt_vector_base);
402#endif
403	__insn_mtspr(SPR_TILE_RTF_HWM, t->tile_rtf_hwm);
404#if CHIP_HAS_DSTREAM_PF()
405	__insn_mtspr(SPR_DSTREAM_PF, t->dstream_pf);
406#endif
407}
408
409
410void _prepare_arch_switch(struct task_struct *next)
411{
412#if CHIP_HAS_TILE_DMA()
413	struct tile_dma_state *dma = &current->thread.tile_dma_state;
414	if (dma->enabled)
415		save_tile_dma_state(dma);
416#endif
417}
418
419
420struct task_struct *__sched _switch_to(struct task_struct *prev,
421				       struct task_struct *next)
422{
423	/* DMA state is already saved; save off other arch state. */
424	save_arch_state(&prev->thread);
425
426#if CHIP_HAS_TILE_DMA()
427	/*
428	 * Restore DMA in new task if desired.
429	 * Note that it is only safe to restart here since interrupts
430	 * are disabled, so we can't take any DMATLB miss or access
431	 * interrupts before we have finished switching stacks.
432	 */
433	if (next->thread.tile_dma_state.enabled) {
434		restore_tile_dma_state(&next->thread);
435		grant_dma_mpls();
436	} else {
437		restrict_dma_mpls();
438	}
439#endif
440
441	/* Restore other arch state. */
442	restore_arch_state(&next->thread);
443
444#ifdef CONFIG_HARDWALL
445	/* Enable or disable access to the network registers appropriately. */
446	hardwall_switch_tasks(prev, next);
447#endif
448
449	/*
450	 * Switch kernel SP, PC, and callee-saved registers.
451	 * In the context of the new task, return the old task pointer
452	 * (i.e. the task that actually called __switch_to).
453	 * Pass the value to use for SYSTEM_SAVE_K_0 when we reset our sp.
454	 */
455	return __switch_to(prev, next, next_current_ksp0(next));
456}
457
458/*
459 * This routine is called on return from interrupt if any of the
460 * TIF_WORK_MASK flags are set in thread_info->flags.  It is
461 * entered with interrupts disabled so we don't miss an event
462 * that modified the thread_info flags.  If any flag is set, we
463 * handle it and return, and the calling assembly code will
464 * re-disable interrupts, reload the thread flags, and call back
465 * if more flags need to be handled.
466 *
467 * We return whether we need to check the thread_info flags again
468 * or not.  Note that we don't clear TIF_SINGLESTEP here, so it's
469 * important that it be tested last, and then claim that we don't
470 * need to recheck the flags.
471 */
472int do_work_pending(struct pt_regs *regs, u32 thread_info_flags)
473{
474	/* If we enter in kernel mode, do nothing and exit the caller loop. */
475	if (!user_mode(regs))
476		return 0;
477
478	user_exit();
479
480	/* Enable interrupts; they are disabled again on return to caller. */
481	local_irq_enable();
482
483	if (thread_info_flags & _TIF_NEED_RESCHED) {
484		schedule();
485		return 1;
486	}
487#if CHIP_HAS_TILE_DMA()
488	if (thread_info_flags & _TIF_ASYNC_TLB) {
489		do_async_page_fault(regs);
490		return 1;
491	}
492#endif
493	if (thread_info_flags & _TIF_SIGPENDING) {
494		do_signal(regs);
495		return 1;
496	}
497	if (thread_info_flags & _TIF_NOTIFY_RESUME) {
498		clear_thread_flag(TIF_NOTIFY_RESUME);
499		tracehook_notify_resume(regs);
500		return 1;
501	}
502	if (thread_info_flags & _TIF_SINGLESTEP)
503		single_step_once(regs);
504
505	user_enter();
506
507	return 0;
508}
509
510unsigned long get_wchan(struct task_struct *p)
511{
512	struct KBacktraceIterator kbt;
513
514	if (!p || p == current || p->state == TASK_RUNNING)
515		return 0;
516
517	for (KBacktraceIterator_init(&kbt, p, NULL);
518	     !KBacktraceIterator_end(&kbt);
519	     KBacktraceIterator_next(&kbt)) {
520		if (!in_sched_functions(kbt.it.pc))
521			return kbt.it.pc;
522	}
523
524	return 0;
525}
526
527/* Flush thread state. */
528void flush_thread(void)
529{
530	/* Nothing */
531}
532
533/*
534 * Free current thread data structures etc..
535 */
536void exit_thread(void)
537{
538#ifdef CONFIG_HARDWALL
539	/*
540	 * Remove the task from the list of tasks that are associated
541	 * with any live hardwalls.  (If the task that is exiting held
542	 * the last reference to a hardwall fd, it would already have
543	 * been released and deactivated at this point.)
544	 */
545	hardwall_deactivate_all(current);
546#endif
547}
548
549void show_regs(struct pt_regs *regs)
550{
551	struct task_struct *tsk = validate_current();
552	int i;
553
554	if (tsk != &corrupt_current)
555		show_regs_print_info(KERN_ERR);
556#ifdef __tilegx__
557	for (i = 0; i < 17; i++)
558		pr_err(" r%-2d: " REGFMT " r%-2d: " REGFMT " r%-2d: " REGFMT "\n",
559		       i, regs->regs[i], i+18, regs->regs[i+18],
560		       i+36, regs->regs[i+36]);
561	pr_err(" r17: " REGFMT " r35: " REGFMT " tp : " REGFMT "\n",
562	       regs->regs[17], regs->regs[35], regs->tp);
563	pr_err(" sp : " REGFMT " lr : " REGFMT "\n", regs->sp, regs->lr);
564#else
565	for (i = 0; i < 13; i++)
566		pr_err(" r%-2d: " REGFMT " r%-2d: " REGFMT " r%-2d: " REGFMT " r%-2d: " REGFMT "\n",
567		       i, regs->regs[i], i+14, regs->regs[i+14],
568		       i+27, regs->regs[i+27], i+40, regs->regs[i+40]);
569	pr_err(" r13: " REGFMT " tp : " REGFMT " sp : " REGFMT " lr : " REGFMT "\n",
570	       regs->regs[13], regs->tp, regs->sp, regs->lr);
571#endif
572	pr_err(" pc : " REGFMT " ex1: %ld     faultnum: %ld\n",
573	       regs->pc, regs->ex1, regs->faultnum);
574
575	dump_stack_regs(regs);
576}
577