/* 2008-10-21: File added and changed by Sony Corporation */
/*
 *  Kernel Probes (KProbes)
 *  arch/arm/kernel/kprobes.c
 *
 *  Copyright 2007 Sony Corp.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <linux/kprobes.h>
#include <linux/ptrace.h>
#include <linux/preempt.h>
#include <linux/kdebug.h>
#include <linux/module.h>

#include <asm/cacheflush.h>
#include <asm/uaccess.h>

DEFINE_PER_CPU(struct kprobe *, current_kprobe) = NULL;
DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk);

/* Following macros define opcode values for data processing
 * instructions which should be checked if Rd happens to be
 * R15(PC) and currently kprobes are not supported for such
 * instructions which directly modify PC
 */
#define OP_MASK 0x01e00000
#define OP_AND  0x00000000
#define OP_EOR  0x00200000
#define OP_SUB  0x00400000
#define OP_RSB  0x00600000
#define OP_ADD  0x00800000
#define OP_ADC  0x00a00000
#define OP_SBC  0x00c00000
#define OP_RSC  0x00e00000
#define OP_ORR  0x01800000
#define OP_MOV  0x01a00000
#define OP_BIC  0x01c00000
#define OP_MVN  0x01e00000

/* To avoid the SMP problems that can occur when we temporarily
 * put back the original opcode to single-step, we single-step
 * a copy of the instruction. The address of this copy is present
 * in p->ainsn.insn.
 */
int __kprobes arch_prepare_kprobe(struct kprobe *p)
{
	unsigned long insn;
	int ret = 0;

	if ((unsigned long)p->addr & 0x03) {
		printk("Attempt to register kprobe at an unaligned address\n");
		ret = -EINVAL;
		goto kprobe_out;
	}

	insn = *p->addr;

	/* Check 25-27 bits for specific instruction types */
	switch (insn & 0x0e000000) {
	/* Below case covers..
	 * branch/link with exchange types
	 * data processing immediate/register shift if Rd=PC
	 */
	case 0x00000000:
	case 0x02000000:{
			if ((insn & 0x0fffffd0) == 0x012fff10) {
				/*
				 * bx or blx
				 */
				printk("Kprobe for branch/link with exchange instruction type is not supported\n");
				ret = -EINVAL;
				goto kprobe_out;
			}

			/* If Rd is not PC, then break and kprobe is possible */
			if ((insn & 0xf000) != 0xf000)
				break;


			/* If Rd happens to be PC for below insn types */
			switch (insn & OP_MASK) {
			case OP_AND:
			case OP_EOR:
			case OP_SUB:
			case OP_RSB:
			case OP_ADD:
			case OP_ADC:
			case OP_SBC:
			case OP_RSC:
			case OP_ORR:
			case OP_MOV:
			case OP_BIC:
			case OP_MVN:
				printk("Kprobe for data processing instructions with Rd=PC not supported\n");
				ret = -EINVAL;
				goto kprobe_out;
			}
			break;
		}

	/* Below case covers..
	 * load immediate offset
	 * load register offset
	 */
	case 0x04000000:
	case 0x06000000:
		/*
		 * ldr
		 */
		if ((insn & 0x0010f000) == 0x0010f000) {
			printk("Kprobe for load instructions with Rd=PC not supported\n");
			ret = -EINVAL;
			goto kprobe_out;
		}
		break;

	/* Check for load multiple types with PC */
	case 0x08000000:
		/*
		 * ldm
		 */
		if ((insn & 0x00108000) == 0x00108000) {
			printk("Kprobe for multiple load type instructions not supported\n");
			ret = -EINVAL;
			goto kprobe_out;
		}
		break;

	/* Check for branch and branch with link */
	case 0x0a000000:
		/*
		 * bl or b
		 */
		printk("Kprobe for branch and branch with link type instructions not supported\n");
		ret = -EINVAL;
		goto kprobe_out;

	default:
		break;
	}

	/* insn: must be on special executable page on arm. */
	p->ainsn.insn = get_insn_slot();
	if (!p->ainsn.insn)
		ret = -ENOMEM;

	p->ainsn.insn[0] = *p->addr;
	p->ainsn.insn[1] = BREAKPOINT_INSTRUCTION_2;
	p->opcode = *p->addr;

kprobe_out:
	return ret;
}

void __kprobes arch_arm_kprobe(struct kprobe *p)
{
	*p->addr = BREAKPOINT_INSTRUCTION;
	flush_icache_range((unsigned long)p->addr,
			   (unsigned long)p->addr + sizeof(kprobe_opcode_t));
}

void __kprobes arch_disarm_kprobe(struct kprobe *p)
{
	*p->addr = p->opcode;
	flush_icache_range((unsigned long)p->addr,
			   (unsigned long)p->addr + sizeof(kprobe_opcode_t));
}

void __kprobes arch_remove_kprobe(struct kprobe *p)
{
	mutex_lock(&kprobe_mutex);
	free_insn_slot(p->ainsn.insn,0);
	mutex_unlock(&kprobe_mutex);
}

static void __kprobes save_previous_kprobe(struct kprobe_ctlblk *kcb)
{
	kcb->prev_kprobe.kp = kprobe_running();
	kcb->prev_kprobe.status = kcb->kprobe_status;
	kcb->prev_kprobe.old_cpsr = kcb->kprobe_old_cpsr;
	kcb->prev_kprobe.saved_cpsr = kcb->kprobe_saved_cpsr;
}

static void __kprobes restore_previous_kprobe(struct kprobe_ctlblk *kcb)
{
	__get_cpu_var(current_kprobe) = kcb->prev_kprobe.kp;
	kcb->kprobe_status = kcb->prev_kprobe.status;
	kcb->kprobe_old_cpsr = kcb->prev_kprobe.old_cpsr;
	kcb->kprobe_saved_cpsr = kcb->prev_kprobe.saved_cpsr;
}

static void __kprobes set_current_kprobe(struct kprobe *p, struct pt_regs *regs,
				      struct kprobe_ctlblk *kcb)
{
	__get_cpu_var(current_kprobe) = p;
	kcb->kprobe_saved_cpsr = kcb->kprobe_old_cpsr = (regs)->ARM_cpsr;
}

static void __kprobes prepare_singlestep(struct kprobe *p, struct pt_regs *regs)
{

	(regs)->ARM_cpsr |= (PSR_F_BIT | PSR_I_BIT);

	/*single step inline if the instruction is a BREAKPOINT_INSTRUCTION */
	if ((p->opcode == BREAKPOINT_INSTRUCTION)
	    || (p->opcode == BREAKPOINT_INSTRUCTION_2))
		(regs)->ARM_pc = (unsigned long)p->addr;
	else
		(regs)->ARM_pc = (unsigned long)&p->ainsn.insn[0];

}


/* Called with kretprobe_lock held */
void __kprobes arch_prepare_kretprobe(struct kretprobe_instance *ri,
				      struct pt_regs *regs)
{
	/* Save the original return addr from stack */
	ri->ret_addr = (kprobe_opcode_t *)(regs)->ARM_lr;

	/* Replace the return addr with trampoline addr */
	(regs)->ARM_lr = (unsigned long)&kretprobe_trampoline;
}


static int __kprobes kprobe_handler(struct pt_regs *regs)
{
	struct kprobe *p;
	int ret = 0;
	kprobe_opcode_t *addr = NULL;
	struct kprobe_ctlblk *kcb;

	addr = (kprobe_opcode_t *) (regs)->ARM_pc;

	/*
	 * We don't want to be preempted for the entire
	 * duration of kprobe processing
	 */
	preempt_disable();
	kcb = get_kprobe_ctlblk();

	/* Check we're not actually recursing */
	if (kprobe_running()) {
		p = get_kprobe(addr);
		if (p) {
			if (kcb->kprobe_status == KPROBE_HIT_SS &&
			    p->ainsn.insn[0] == BREAKPOINT_INSTRUCTION) {
				(regs)->ARM_cpsr &= kcb->kprobe_saved_cpsr;
				goto no_kprobe;
			}
			/* We have reentered the kprobe_handler(), since
			 * another probe was hit while within the handler.
			 * We here save the original kprobes variables and
			 * just single step on the instruction of the new probe
			 * without calling any user handlers.
			 */
			save_previous_kprobe(kcb);
			set_current_kprobe(p, regs, kcb);
			kprobes_inc_nmissed_count(p);
			prepare_singlestep(p, regs);
			kcb->kprobe_status = KPROBE_REENTER;
			return 1;
		} else {
			if (*addr != BREAKPOINT_INSTRUCTION) {
				/* The breakpoint instruction was removed by
				 * another cpu right after we hit, no further
				 * handling of this interrupt is appropriate
				 */
				ret = 1;
				goto no_kprobe;
			}
			p = __get_cpu_var(current_kprobe);
			if (p->break_handler && p->break_handler(p, regs)) {
				goto ss_probe;
			}
		}
		goto no_kprobe;
	}

	p = get_kprobe(addr);
	if (!p) {
		if (*addr != BREAKPOINT_INSTRUCTION) {
			/*
			 * The breakpoint instruction was removed right
			 * after we hit it.  Another cpu has removed
			 * either a probepoint or a debugger breakpoint
			 * at this address.  In either case, no further
			 * handling of this interrupt is appropriate.
			 * Back up over the (now missing) break instruction
			 * and run the original instruction.
			 */
			ret = 1;
		}
		/* Not one of ours: let kernel handle it */
		goto no_kprobe;
	}

	set_current_kprobe(p, regs, kcb);
	kcb->kprobe_status = KPROBE_HIT_ACTIVE;

	if (p->pre_handler && p->pre_handler(p, regs))
		/* handler has already set things up, so skip ss setup */
		return 1;

ss_probe:
	prepare_singlestep(p, regs);
	kcb->kprobe_status = KPROBE_HIT_SS;
	return 1;

no_kprobe:
	preempt_enable_no_resched();
	return ret;
}

/*
 * Called after single-stepping.  p->addr is the address of the
 * instruction which has been replaced by the BREAK_INSTRUCTION.
 * This function prepares to return from the post-single-step
 * breakpoint trap.
 */
static void __kprobes resume_execution(struct kprobe *p,
				       struct pt_regs *regs,
				       struct kprobe_ctlblk *kcb)
{

	(regs)->ARM_pc = (unsigned long)p->addr + sizeof(kprobe_opcode_t);
}

static int __kprobes post_kprobe_handler(struct pt_regs *regs)
{
	struct kprobe *cur = kprobe_running();
	struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();

	if (!cur)
		return 0;

	if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler) {
		kcb->kprobe_status = KPROBE_HIT_SSDONE;
		cur->post_handler(cur, regs, 0);
	}

	resume_execution(cur, regs, kcb);

	(regs)->ARM_cpsr &= kcb->kprobe_saved_cpsr;

	/*Restore back the original saved kprobes variables and continue. */
	if (kcb->kprobe_status == KPROBE_REENTER) {
		restore_previous_kprobe(kcb);
		goto out;
	}
	reset_current_kprobe();
out:
	preempt_enable_no_resched();
	return 1;
}


int __kprobes kprobe_fault_handler(struct pt_regs *regs, int trapnr)
{
	struct kprobe *cur = kprobe_running();
	struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
	const struct exception_table_entry *entry;

	switch(kcb->kprobe_status) {
	case KPROBE_HIT_SS:
	case KPROBE_REENTER:
		/*
		 * We are here because the instruction being single
		 * stepped caused a page fault. We reset the current
		 * kprobe and the PC points back to the probe address
		 * and allow the page fault handler to continue as a
		 * normal page fault.
		 */

		regs->ARM_pc = (unsigned long)cur->addr;
		(regs)->ARM_cpsr |= kcb->kprobe_saved_cpsr;

		if (kcb->kprobe_status == KPROBE_REENTER)
			restore_previous_kprobe(kcb);
		else
			reset_current_kprobe();
		/* preempt_enable_no_resched(); */

		break;
	case KPROBE_HIT_ACTIVE:
	case KPROBE_HIT_SSDONE:
		/*
		 * We increment the nmissed count for accounting,
		 * we can also use npre/npostfault count for accouting
		 * these specific fault cases.
		 */
		kprobes_inc_nmissed_count(cur);

		/*
		 * We come here because instructions in the pre/post
		 * handler caused the page_fault, this could happen
		 * if handler tries to access user space by
		 * copy_from_user(), get_user() etc. Let the
		 * user-specified handler try to fix it first.
		 */
		if (cur->fault_handler && cur->fault_handler(cur, regs, trapnr))
			return 1;

		/*
		 * In case the user-specified fault handler returned
		 * zero, try to fix up.
		 */
		if ((entry = search_exception_tables(regs->ARM_pc)) != NULL) {
			regs->ARM_pc = entry->fixup;
			return 1;
		}

		/*
		 * fixup_exception() could not handle it,
		 * Let do_page_fault() fix it.
		 */
		break;
	default:
		break;
	}
	return 0;
}

/*
 * Wrapper routine to for handling exceptions.
 */
int __kprobes kprobe_exceptions_notify(struct notifier_block *self,
				       unsigned long val, void *data)
{
	struct die_args *args = (struct die_args *)data;
	int ret = NOTIFY_DONE;

	if (args->regs && user_mode(args->regs))
		return ret;

	switch (val) {
	case DIE_UNDEF_1:
		if (kprobe_handler(args->regs))
			ret = NOTIFY_STOP;
		break;
	case DIE_UNDEF_2:
		if (post_kprobe_handler(args->regs))
			ret = NOTIFY_STOP;
		break;
#if 0
	case DIE_PAGE_FAULT:
		/* kprobe_running() needs smp_processor_id() */
		preempt_disable();
		if (kprobe_running() &&
		    kprobe_fault_handler(args->regs, args->trapnr))
			ret = NOTIFY_STOP;
		preempt_enable();
		break;
	case DIE_BADSYSCALL:
		/* kprobe_running() needs smp_processor_id() */
		preempt_disable();
		if (kprobe_running() &&
		    kprobe_fault_handler(args->regs, args->trapnr))
			ret = NOTIFY_STOP;
		preempt_enable();
		break;
	case DIE_BADSYSCALL2:
		/* kprobe_running() needs smp_processor_id() */
		preempt_disable();
		if (kprobe_running() &&
		    kprobe_fault_handler(args->regs, args->trapnr))
			ret = NOTIFY_STOP;
		preempt_enable();
		break;
	case DIE_UNKNOWN_ABORT:
		/* kprobe_running() needs smp_processor_id() */
		preempt_disable();
		if (kprobe_running() &&
		    kprobe_fault_handler(args->regs, args->trapnr))
			ret = NOTIFY_STOP;
		preempt_enable();
		break;
#endif
	default:
		break;
	}
	return ret;
}


int __kprobes setjmp_pre_handler(struct kprobe *p, struct pt_regs *regs)
{
	struct jprobe *jp = container_of(p, struct jprobe, kp);
	struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
	unsigned long addr;

	kcb->jprobe_saved_sp = (long*)regs->ARM_sp;

	memcpy(&kcb->jprobe_saved_regs, regs, sizeof(struct pt_regs));

 	addr = (unsigned long)(kcb->jprobe_saved_sp);

	/* Copy of stack is also required when we return from longjmp */
	memcpy(kcb->jprobes_stack, (kprobe_opcode_t *)addr, MIN_STACK_SIZE(addr));

	/* setup return addr to the jprobe handler routine */
	regs->ARM_pc = arch_deref_entry_point(jp->entry);


	/* This is required since jprobe_return will generate exception */
	(regs)->ARM_cpsr |= (PSR_F_BIT | PSR_I_BIT);

	return 1;
}

void __kprobes jprobe_return(void)
{
	asm volatile ("	.word 0xe7f001f8	\n");
}

void __kprobes jprobe_return_end(void)
{
	asm volatile("	nop	\n");
}

int __kprobes longjmp_break_handler(struct kprobe *p, struct pt_regs *regs)
{
	struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
	unsigned long stack_addr  = kcb->jprobe_saved_regs.ARM_sp;
	u8 *addr = (u8 *)(regs->ARM_pc - 1);


	if ((addr > (u8 *)jprobe_return) && (addr < (u8 *)jprobe_return_end)) {
		memcpy(regs, &kcb->jprobe_saved_regs, sizeof(struct pt_regs));
		memcpy((kprobe_opcode_t *)stack_addr, kcb->jprobes_stack,
			MIN_STACK_SIZE(stack_addr));
		preempt_enable_no_resched();
		return 1;
	}
	return 0;
}



/*
 * Function return probe trampoline:
 * 	- init_kprobes() establishes a probepoint here
 * 	- When the probed function returns, this probe
 * 		causes the handlers to fire
 */
void kretprobe_trampoline_holder(void)
{
	asm volatile(".global kretprobe_trampoline\n"
			"kretprobe_trampoline:\n"
			"nop\n");
}

/*
 * Called when the probe at kretprobe trampoline is hit
 */
int __kprobes trampoline_probe_handler(struct kprobe *p, struct pt_regs *regs)
{
	struct kretprobe_instance *ri = NULL;
	struct hlist_head *head, empty_rp;
	struct hlist_node *node, *tmp;
	unsigned long flags, orig_ret_address = 0;
	unsigned long trampoline_address =(unsigned long)&kretprobe_trampoline;


	INIT_HLIST_HEAD(&empty_rp);
	spin_lock_irqsave(&kretprobe_lock, flags);
	head = kretprobe_inst_table_head(current);

	/*
	 * It is possible to have multiple instances associated with a given
	 * task either because an multiple functions in the call path
	 * have a return probe installed on them, and/or more then one return
	 * return probe was registered for a target function.
	 *
	 * We can handle this because:
	 *     - instances are always inserted at the head of the list
	 *     - when multiple return probes are registered for the same
	 *       function, the first instance's ret_addr will point to the
	 *       real return address, and all the rest will point to
	 *       kretprobe_trampoline
	 */
	hlist_for_each_entry_safe(ri, node, tmp, head, hlist) {
		if (ri->task != current)
			/* another task is sharing our hash bucket */
			continue;

		if (ri->rp && ri->rp->handler) {
			__get_cpu_var(current_kprobe) = &ri->rp->kp;
			get_kprobe_ctlblk()->kprobe_status = KPROBE_HIT_ACTIVE;
			ri->rp->handler(ri, regs);
			__get_cpu_var(current_kprobe) = NULL;
		}

		orig_ret_address = (unsigned long)ri->ret_addr;
		recycle_rp_inst(ri, &empty_rp);

		if (orig_ret_address != trampoline_address)
			/*
			 * This is the real return address. Any other
			 * instances associated with this task are for
			 * other calls deeper on the call stack
			 */
			break;
	}

	kretprobe_assert(ri, orig_ret_address, trampoline_address);

	/* Restore back original lr */
	regs->ARM_lr = orig_ret_address;

	regs->ARM_pc =  regs->ARM_lr;


	reset_current_kprobe();
	spin_unlock_irqrestore(&kretprobe_lock, flags);
	preempt_enable_no_resched();

	hlist_for_each_entry_safe(ri, node, tmp, &empty_rp, hlist) {
		hlist_del(&ri->hlist);
		kfree(ri);
	}
	/*
	 * By returning a non-zero value, we are telling
	 * kprobe_handler() that we don't want the post_handler
	 * to run (and have re-enabled preemption)
	 */
	return 1;
}


static struct kprobe trampoline_p = {
	.addr = (kprobe_opcode_t *) &kretprobe_trampoline,
	.pre_handler = trampoline_probe_handler
};


int __init arch_init_kprobes(void)
{
	return register_kprobe(&trampoline_p);
}

int __kprobes arch_trampoline_kprobe(struct kprobe *p)
{
	if (p->addr == (kprobe_opcode_t *)&kretprobe_trampoline)
		return 1;

	return 0;
}


