/* Program and starts the timer */
static int watchdog_config_and_start(u32 newtimeout, u32 newpretimeout)
{
int ret;

	timeout = newtimeout;
	pre_timeout = newpretimeout;

	pr_warn(PFX "Configuration: %dkHz, timeout=%ds, pre_timeout=%ds, timer=%ds\n",
		watchdog_device.timer7_tbl_ptr->freq_hz / 1000, timeout,
		pre_timeout, timer_timeout);

	/* Configure the watchdog */
	ret = watchdog_set_timeouts(timer_timeout, pre_timeout, timeout);
	if (ret) {
		pr_err(PFX "%s: Cannot configure the watchdog\n", __func__);

		/* Make sure the watchdog timer is stopped */
		intel_scu_stop();
		return ret;
	}

	watchdog_device.started = true;

	return 0;
}
/* tasklet */
static void watchdog_interrupt_tasklet_body(unsigned long data)
{
	int ret;

	pr_warn(PFX "interrupt tasklet body start\n");

	if (disable_kernel_watchdog) {
		/* disable the timer */
		pr_warn(PFX "interrupt tasklet body disable set\n");
		ret = intel_scu_stop();
		if (ret)
			pr_err(PFX "cannot disable the timer\n");
		return;
	}

	/* wake up read to send data to user (reminder for keep alive */
	warning_flag = 1;

#ifdef CONFIG_INTEL_SCU_SOFT_LOCKUP
	{
		int i;
		/*start timer for softlock detection */
		beattime = jiffies;
		for_each_possible_cpu(i) {
			heartbeats[i] = kcpustat_cpu(i).cpustat[CPUTIME_SYSTEM];
		}
		mod_timer(&softlock_timer, jiffies + SOFT_LOCK_TIME * HZ);
	}
#endif

	/* Wake up the daemon */
	wake_up_interruptible(&read_wq);

	/*
	 * Hold a timeout wakelock so user space watchdogd has a chance
	 * to run after waking up from s3
	 */
	wake_lock_timeout(&watchdog_wake_lock, 5 * HZ);
}
static long intel_scu_ioctl(struct file *file,
			   unsigned int cmd,
			   unsigned long arg)
{
	void __user *argp = (void __user *)arg;
	u32 __user *p = argp;
	u32 new_margin;


	static const struct watchdog_info ident = {
		.options =          WDIOF_SETTIMEOUT
				    | WDIOF_KEEPALIVEPING,
		.firmware_version = 0,  /* @todo Get from SCU via
						 ipc_get_scu_fw_version()? */
		.identity =         "Intel_SCU IOH Watchdog"  /* len < 32 */
	};

	switch (cmd) {
	case WDIOC_GETSUPPORT:
		return copy_to_user(argp,
				    &ident,
				    sizeof(ident)) ? -EFAULT : 0;
	case WDIOC_GETSTATUS:
	case WDIOC_GETBOOTSTATUS:
		return put_user(0, p);
	case WDIOC_KEEPALIVE:
		intel_scu_keepalive();

		return 0;
	case WDIOC_SETTIMEOUT:
		if (get_user(new_margin, p))
			return -EFAULT;

		if (check_timer_margin(new_margin))
			return -EINVAL;

		if (intel_scu_set_heartbeat(new_margin))
			return -EINVAL;
		return 0;
	case WDIOC_GETTIMEOUT:
		return put_user(watchdog_device.soft_threshold, p);

	default:
		return -ENOTTY;
	}
}

/*
 *      Notifier for system down
 */
static int intel_scu_notify_sys(struct notifier_block *this,
			       unsigned long code,
			       void *another_unused)
{
	if (code == SYS_DOWN || code == SYS_HALT)
		/* Turn off the watchdog timer. */
		intel_scu_stop();
	return NOTIFY_DONE;
}

/*
 *      Kernel Interfaces
 */
static const struct file_operations intel_scu_fops = {
	.owner          = THIS_MODULE,
	.llseek         = no_llseek,
	.write          = intel_scu_write,
	.unlocked_ioctl = intel_scu_ioctl,
	.open           = intel_scu_open,
	.release        = intel_scu_release,
};

static int __init intel_scu_watchdog_init(void)
{
	int ret;
	u32 __iomem *tmp_addr;

	/*
	 * We don't really need to check this as the SFI timer get will fail
	 * but if we do so we can exit with a clearer reason and no noise.
	 *
	 * If it isn't an intel MID device then it doesn't have this watchdog
	 */
	if (!mrst_identify_cpu())
		return -ENODEV;

	/* Check boot parameters to verify that their initial values */
	/* are in range. */
	/* Check value of timer_set boot parameter */
	if ((timer_set < MIN_TIME_CYCLE) ||
	    (timer_set > MAX_TIME - MIN_TIME_CYCLE)) {
		pr_err("Watchdog timer: value of timer_set %x (hex) "
		  "is out of range from %x to %x (hex)\n",
		  timer_set, MIN_TIME_CYCLE, MAX_TIME - MIN_TIME_CYCLE);
		return -EINVAL;
	}

	/* Check value of timer_margin boot parameter */
	if (check_timer_margin(timer_margin))
		return -EINVAL;

	watchdog_device.timer_tbl_ptr = sfi_get_mtmr(sfi_mtimer_num-1);

	if (watchdog_device.timer_tbl_ptr == NULL) {
		pr_debug("Watchdog timer - Intel SCU watchdog: timer is not available\n");
		return -ENODEV;
	}
	/* make sure the timer exists */
	if (watchdog_device.timer_tbl_ptr->phys_addr == 0) {
		pr_debug("Watchdog timer - Intel SCU watchdog - timer %d does not have valid physical memory\n",
								sfi_mtimer_num);
		return -ENODEV;
	}

	if (watchdog_device.timer_tbl_ptr->irq == 0) {
		pr_debug("Watchdog timer: timer %d invalid irq\n",
							sfi_mtimer_num);
		return -ENODEV;
	}

	tmp_addr = ioremap_nocache(watchdog_device.timer_tbl_ptr->phys_addr,
			20);

	if (tmp_addr == NULL) {
		pr_debug("Watchdog timer: timer unable to ioremap\n");
		return -ENOMEM;
	}

	watchdog_device.timer_load_count_addr = tmp_addr++;
	watchdog_device.timer_current_value_addr = tmp_addr++;
	watchdog_device.timer_control_addr = tmp_addr++;
	watchdog_device.timer_clear_interrupt_addr = tmp_addr++;
	watchdog_device.timer_interrupt_status_addr = tmp_addr++;

	/* Set the default time values in device structure */

	watchdog_device.timer_set = timer_set;
	watchdog_device.threshold =
		timer_margin * watchdog_device.timer_tbl_ptr->freq_hz;
	watchdog_device.soft_threshold =
		(watchdog_device.timer_set - timer_margin)
		* watchdog_device.timer_tbl_ptr->freq_hz;


	watchdog_device.intel_scu_notifier.notifier_call =
		intel_scu_notify_sys;

	ret = register_reboot_notifier(&watchdog_device.intel_scu_notifier);
	if (ret) {
		pr_err("Watchdog timer: cannot register notifier %d)\n", ret);
		goto register_reboot_error;
	}

	watchdog_device.miscdev.minor = WATCHDOG_MINOR;
	watchdog_device.miscdev.name = "watchdog";
	watchdog_device.miscdev.fops = &intel_scu_fops;

	ret = misc_register(&watchdog_device.miscdev);
	if (ret) {
		pr_err("Watchdog timer: cannot register miscdev %d err =%d\n",
							WATCHDOG_MINOR, ret);
		goto misc_register_error;
	}

	ret = request_irq((unsigned int)watchdog_device.timer_tbl_ptr->irq,
		watchdog_timer_interrupt,
		IRQF_SHARED, "watchdog",
		&watchdog_device.timer_load_count_addr);
	if (ret) {
		pr_err("Watchdog timer: error requesting irq %d\n", ret);
		goto request_irq_error;
	}
	/* Make sure timer is disabled before returning */
	intel_scu_stop();
	return 0;

/* error cleanup */

request_irq_error:
	misc_deregister(&watchdog_device.miscdev);
misc_register_error:
	unregister_reboot_notifier(&watchdog_device.intel_scu_notifier);
register_reboot_error:
	intel_scu_stop();
	iounmap(watchdog_device.timer_load_count_addr);
	return ret;
}
static int intel_scu_set_heartbeat(u32 t)
{
	int			 ipc_ret;
	int			 retry_count;
	u32			 soft_value;
	u32			 hw_pre_value;
	u32			 hw_value;

	watchdog_device.timer_set = t;
	watchdog_device.threshold =
		timer_margin * watchdog_device.timer_tbl_ptr->freq_hz;
	watchdog_device.soft_threshold =
		(watchdog_device.timer_set - timer_margin)
		* watchdog_device.timer_tbl_ptr->freq_hz;

	pr_debug("Watchdog timer: set_heartbeat: timer freq is %d\n",
		watchdog_device.timer_tbl_ptr->freq_hz);
	pr_debug("Watchdog timer: set_heartbeat: timer_set is %x (hex)\n",
		watchdog_device.timer_set);
	pr_debug("Watchdog timer: set_hearbeat: timer_margin is %x (hex)\n",
		timer_margin);
	pr_debug("Watchdog timer: set_heartbeat: threshold is %x (hex)\n",
		watchdog_device.threshold);
	pr_debug("Watchdog timer: set_heartbeat: soft_threshold is %x (hex)\n",
		watchdog_device.soft_threshold);

	/* Adjust thresholds by FREQ_ADJUSTMENT factor, to make the */
	/* watchdog timing come out right. */
	watchdog_device.threshold =
		watchdog_device.threshold / FREQ_ADJUSTMENT;
	watchdog_device.soft_threshold =
		watchdog_device.soft_threshold / FREQ_ADJUSTMENT;

	/* temporarily disable the timer */
	iowrite32(0x00000002, watchdog_device.timer_control_addr);

	/* send the threshold and soft_threshold via IPC to the processor */
	ipc_ret = watchdog_set_ipc(watchdog_device.soft_threshold,
				   watchdog_device.threshold);

	if (ipc_ret != 0) {
		/* Make sure the watchdog timer is stopped */
		intel_scu_stop();
		return ipc_ret;
	}

	/* Soft Threshold set loop. Early versions of silicon did */
	/* not always set this count correctly.  This loop checks */
	/* the value and retries if it was not set correctly.     */

	retry_count = 0;
	soft_value = watchdog_device.soft_threshold & 0xFFFF0000;
	do {

		/* Make sure timer is stopped */
		intel_scu_stop();

		if (MAX_RETRY < retry_count++) {
			/* Unable to set timer value */
			pr_err("Watchdog timer: Unable to set timer\n");
			return -ENODEV;
		}

		/* set the timer to the soft threshold */
		iowrite32(watchdog_device.soft_threshold,
			watchdog_device.timer_load_count_addr);

		/* read count value before starting timer */
		hw_pre_value = ioread32(watchdog_device.timer_load_count_addr);
		hw_pre_value = hw_pre_value & 0xFFFF0000;

		/* Start the timer */
		iowrite32(0x00000003, watchdog_device.timer_control_addr);

		/* read the value the time loaded into its count reg */
		hw_value = ioread32(watchdog_device.timer_load_count_addr);
		hw_value = hw_value & 0xFFFF0000;


	} while (soft_value != hw_value);

	watchdog_device.timer_started = 1;

	return 0;
}
/* ioctl */
static long intel_scu_ioctl(struct file *file, unsigned int cmd,
			    unsigned long arg)
{
void __user *argp = (void __user *)arg;
u32 __user *p = argp;
u32 val;
int options;

	static const struct watchdog_info ident = {
		.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
		/* @todo Get from SCU via ipc_get_scu_fw_version()? */
		.firmware_version = 0,
		/* len < 32 */
		.identity = "Intel_SCU IOH Watchdog"
	};

	switch (cmd) {
	case WDIOC_GETSUPPORT:
		return copy_to_user(argp, &ident,
				    sizeof(ident)) ? -EFAULT : 0;
	case WDIOC_GETSTATUS:
	case WDIOC_GETBOOTSTATUS:
		return put_user(0, p);
	case WDIOC_KEEPALIVE:
		pr_warn(PFX "%s: KeepAlive ioctl\n", __func__);
		if (!watchdog_device.started)
			return -EINVAL;

		watchdog_keepalive();
		return 0;
	case WDIOC_SETTIMERTIMEOUT:
		pr_warn(PFX "%s: SetTimerTimeout ioctl\n", __func__);

		if (watchdog_device.started)
			return -EBUSY;

		/* Timeout to start scheduling the daemon */
		if (get_user(val, p))
			return -EFAULT;

		timer_timeout = val;
		return 0;
	case WDIOC_SETPRETIMEOUT:
		pr_warn(PFX "%s: SetPreTimeout ioctl\n", __func__);

		if (watchdog_device.started)
			return -EBUSY;

		/* Timeout to warn */
		if (get_user(val, p))
			return -EFAULT;

		pre_timeout = val;
		return 0;
	case WDIOC_SETTIMEOUT:
		pr_warn(PFX "%s: SetTimeout ioctl\n", __func__);

		if (watchdog_device.started)
			return -EBUSY;

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

		timeout = val;
		return 0;
	case WDIOC_GETTIMEOUT:
		return put_user(timeout, p);
	case WDIOC_SETOPTIONS:
		if (get_user(options, p))
			return -EFAULT;

		if (options & WDIOS_DISABLECARD) {
			pr_warn(PFX "%s: Stopping the watchdog\n", __func__);
			intel_scu_stop();
			return 0;
		}

		if (options & WDIOS_ENABLECARD) {
			pr_warn(PFX "%s: Starting the watchdog\n", __func__);

			if (watchdog_device.started)
				return -EBUSY;

			if (check_timeouts(timer_timeout,
					   pre_timeout, timeout)) {
				pr_warn(PFX "%s: Invalid thresholds\n",
					__func__);
				return -EINVAL;
			}
			if (watchdog_config_and_start(timeout, pre_timeout))
				return -EINVAL;
			return 0;
		}
		return 0;
	default:
		return -ENOTTY;
	}
}

static int watchdog_set_reset_type(int reset_type)
{
	int ret;

	ret = rpmsg_send_command(watchdog_instance,
				  IPC_SET_WATCHDOG_TIMER,
				  reset_type,
				  NULL, NULL, 0, 0);

	if (ret) {
		pr_crit(PFX "Error setting watchdog action: %d\n", ret);
		return -EIO;
	}

	watchdog_device.normal_wd_action = reset_type;

	return 0;
}