repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
MassStash/htc_jewel_kernel_sense | drivers/acpi/sleep.c | 516 | 24609 | /*
* sleep.c - ACPI sleep support.
*
* Copyright (c) 2005 Alexey Starikovskiy <alexey.y.starikovskiy@intel.com>
* Copyright (c) 2004 David Shaohua Li <shaohua.li@intel.com>
* Copyright (c) 2000-2003 Patrick Mochel
* Copyright (c) 2003 Open Source Development Lab
*
* This file is released under the GPLv2.
*
*/
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/dmi.h>
#include <linux/device.h>
#include <linux/suspend.h>
#include <linux/reboot.h>
#include <linux/acpi.h>
#include <linux/module.h>
#include <linux/pm_runtime.h>
#include <asm/io.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include "internal.h"
#include "sleep.h"
u8 wake_sleep_flags = ACPI_NO_OPTIONAL_METHODS;
static unsigned int gts, bfs;
static int set_param_wake_flag(const char *val, struct kernel_param *kp)
{
int ret = param_set_int(val, kp);
if (ret)
return ret;
if (kp->arg == (const char *)>s) {
if (gts)
wake_sleep_flags |= ACPI_EXECUTE_GTS;
else
wake_sleep_flags &= ~ACPI_EXECUTE_GTS;
}
if (kp->arg == (const char *)&bfs) {
if (bfs)
wake_sleep_flags |= ACPI_EXECUTE_BFS;
else
wake_sleep_flags &= ~ACPI_EXECUTE_BFS;
}
return ret;
}
module_param_call(gts, set_param_wake_flag, param_get_int, >s, 0644);
module_param_call(bfs, set_param_wake_flag, param_get_int, &bfs, 0644);
MODULE_PARM_DESC(gts, "Enable evaluation of _GTS on suspend.");
MODULE_PARM_DESC(bfs, "Enable evaluation of _BFS on resume".);
static u8 sleep_states[ACPI_S_STATE_COUNT];
static void acpi_sleep_tts_switch(u32 acpi_state)
{
union acpi_object in_arg = { ACPI_TYPE_INTEGER };
struct acpi_object_list arg_list = { 1, &in_arg };
acpi_status status = AE_OK;
in_arg.integer.value = acpi_state;
status = acpi_evaluate_object(NULL, "\\_TTS", &arg_list, NULL);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
/*
* OS can't evaluate the _TTS object correctly. Some warning
* message will be printed. But it won't break anything.
*/
printk(KERN_NOTICE "Failure in evaluating _TTS object\n");
}
}
static int tts_notify_reboot(struct notifier_block *this,
unsigned long code, void *x)
{
acpi_sleep_tts_switch(ACPI_STATE_S5);
return NOTIFY_DONE;
}
static struct notifier_block tts_notifier = {
.notifier_call = tts_notify_reboot,
.next = NULL,
.priority = 0,
};
static int acpi_sleep_prepare(u32 acpi_state)
{
#ifdef CONFIG_ACPI_SLEEP
/* do we have a wakeup address for S2 and S3? */
if (acpi_state == ACPI_STATE_S3) {
if (!acpi_wakeup_address) {
return -EFAULT;
}
acpi_set_firmware_waking_vector(
(acpi_physical_address)acpi_wakeup_address);
}
ACPI_FLUSH_CPU_CACHE();
#endif
printk(KERN_INFO PREFIX "Preparing to enter system sleep state S%d\n",
acpi_state);
acpi_enable_wakeup_devices(acpi_state);
acpi_enter_sleep_state_prep(acpi_state);
return 0;
}
#ifdef CONFIG_ACPI_SLEEP
static u32 acpi_target_sleep_state = ACPI_STATE_S0;
/*
* The ACPI specification wants us to save NVS memory regions during hibernation
* and to restore them during the subsequent resume. Windows does that also for
* suspend to RAM. However, it is known that this mechanism does not work on
* all machines, so we allow the user to disable it with the help of the
* 'acpi_sleep=nonvs' kernel command line option.
*/
static bool nvs_nosave;
void __init acpi_nvs_nosave(void)
{
nvs_nosave = true;
}
/*
* ACPI 1.0 wants us to execute _PTS before suspending devices, so we allow the
* user to request that behavior by using the 'acpi_old_suspend_ordering'
* kernel command line option that causes the following variable to be set.
*/
static bool old_suspend_ordering;
void __init acpi_old_suspend_ordering(void)
{
old_suspend_ordering = true;
}
/**
* acpi_pm_freeze - Disable the GPEs and suspend EC transactions.
*/
static int acpi_pm_freeze(void)
{
acpi_disable_all_gpes();
acpi_os_wait_events_complete(NULL);
acpi_ec_block_transactions();
return 0;
}
/**
* acpi_pre_suspend - Enable wakeup devices, "freeze" EC and save NVS.
*/
static int acpi_pm_pre_suspend(void)
{
acpi_pm_freeze();
return suspend_nvs_save();
}
/**
* __acpi_pm_prepare - Prepare the platform to enter the target state.
*
* If necessary, set the firmware waking vector and do arch-specific
* nastiness to get the wakeup code to the waking vector.
*/
static int __acpi_pm_prepare(void)
{
int error = acpi_sleep_prepare(acpi_target_sleep_state);
if (error)
acpi_target_sleep_state = ACPI_STATE_S0;
return error;
}
/**
* acpi_pm_prepare - Prepare the platform to enter the target sleep
* state and disable the GPEs.
*/
static int acpi_pm_prepare(void)
{
int error = __acpi_pm_prepare();
if (!error)
error = acpi_pm_pre_suspend();
return error;
}
/**
* acpi_pm_finish - Instruct the platform to leave a sleep state.
*
* This is called after we wake back up (or if entering the sleep state
* failed).
*/
static void acpi_pm_finish(void)
{
u32 acpi_state = acpi_target_sleep_state;
acpi_ec_unblock_transactions();
suspend_nvs_free();
if (acpi_state == ACPI_STATE_S0)
return;
printk(KERN_INFO PREFIX "Waking up from system sleep state S%d\n",
acpi_state);
acpi_disable_wakeup_devices(acpi_state);
acpi_leave_sleep_state(acpi_state);
/* reset firmware waking vector */
acpi_set_firmware_waking_vector((acpi_physical_address) 0);
acpi_target_sleep_state = ACPI_STATE_S0;
}
/**
* acpi_pm_end - Finish up suspend sequence.
*/
static void acpi_pm_end(void)
{
/*
* This is necessary in case acpi_pm_finish() is not called during a
* failing transition to a sleep state.
*/
acpi_target_sleep_state = ACPI_STATE_S0;
acpi_sleep_tts_switch(acpi_target_sleep_state);
}
#else /* !CONFIG_ACPI_SLEEP */
#define acpi_target_sleep_state ACPI_STATE_S0
#endif /* CONFIG_ACPI_SLEEP */
#ifdef CONFIG_SUSPEND
static u32 acpi_suspend_states[] = {
[PM_SUSPEND_ON] = ACPI_STATE_S0,
[PM_SUSPEND_STANDBY] = ACPI_STATE_S1,
[PM_SUSPEND_MEM] = ACPI_STATE_S3,
[PM_SUSPEND_MAX] = ACPI_STATE_S5
};
/**
* acpi_suspend_begin - Set the target system sleep state to the state
* associated with given @pm_state, if supported.
*/
static int acpi_suspend_begin(suspend_state_t pm_state)
{
u32 acpi_state = acpi_suspend_states[pm_state];
int error = 0;
error = nvs_nosave ? 0 : suspend_nvs_alloc();
if (error)
return error;
if (sleep_states[acpi_state]) {
acpi_target_sleep_state = acpi_state;
acpi_sleep_tts_switch(acpi_target_sleep_state);
} else {
printk(KERN_ERR "ACPI does not support this state: %d\n",
pm_state);
error = -ENOSYS;
}
return error;
}
/**
* acpi_suspend_enter - Actually enter a sleep state.
* @pm_state: ignored
*
* Flush caches and go to sleep. For STR we have to call arch-specific
* assembly, which in turn call acpi_enter_sleep_state().
* It's unfortunate, but it works. Please fix if you're feeling frisky.
*/
static int acpi_suspend_enter(suspend_state_t pm_state)
{
acpi_status status = AE_OK;
u32 acpi_state = acpi_target_sleep_state;
int error;
ACPI_FLUSH_CPU_CACHE();
switch (acpi_state) {
case ACPI_STATE_S1:
barrier();
status = acpi_enter_sleep_state(acpi_state, wake_sleep_flags);
break;
case ACPI_STATE_S3:
error = acpi_suspend_lowlevel();
if (error)
return error;
pr_info(PREFIX "Low-level resume complete\n");
break;
}
/* This violates the spec but is required for bug compatibility. */
acpi_write_bit_register(ACPI_BITREG_SCI_ENABLE, 1);
/* Reprogram control registers and execute _BFS */
acpi_leave_sleep_state_prep(acpi_state, wake_sleep_flags);
/* ACPI 3.0 specs (P62) says that it's the responsibility
* of the OSPM to clear the status bit [ implying that the
* POWER_BUTTON event should not reach userspace ]
*/
if (ACPI_SUCCESS(status) && (acpi_state == ACPI_STATE_S3))
acpi_clear_event(ACPI_EVENT_POWER_BUTTON);
/*
* Disable and clear GPE status before interrupt is enabled. Some GPEs
* (like wakeup GPE) haven't handler, this can avoid such GPE misfire.
* acpi_leave_sleep_state will reenable specific GPEs later
*/
acpi_disable_all_gpes();
/* Allow EC transactions to happen. */
acpi_ec_unblock_transactions_early();
suspend_nvs_restore();
return ACPI_SUCCESS(status) ? 0 : -EFAULT;
}
static int acpi_suspend_state_valid(suspend_state_t pm_state)
{
u32 acpi_state;
switch (pm_state) {
case PM_SUSPEND_ON:
case PM_SUSPEND_STANDBY:
case PM_SUSPEND_MEM:
acpi_state = acpi_suspend_states[pm_state];
return sleep_states[acpi_state];
default:
return 0;
}
}
static const struct platform_suspend_ops acpi_suspend_ops = {
.valid = acpi_suspend_state_valid,
.begin = acpi_suspend_begin,
.prepare_late = acpi_pm_prepare,
.enter = acpi_suspend_enter,
.wake = acpi_pm_finish,
.end = acpi_pm_end,
};
/**
* acpi_suspend_begin_old - Set the target system sleep state to the
* state associated with given @pm_state, if supported, and
* execute the _PTS control method. This function is used if the
* pre-ACPI 2.0 suspend ordering has been requested.
*/
static int acpi_suspend_begin_old(suspend_state_t pm_state)
{
int error = acpi_suspend_begin(pm_state);
if (!error)
error = __acpi_pm_prepare();
return error;
}
/*
* The following callbacks are used if the pre-ACPI 2.0 suspend ordering has
* been requested.
*/
static const struct platform_suspend_ops acpi_suspend_ops_old = {
.valid = acpi_suspend_state_valid,
.begin = acpi_suspend_begin_old,
.prepare_late = acpi_pm_pre_suspend,
.enter = acpi_suspend_enter,
.wake = acpi_pm_finish,
.end = acpi_pm_end,
.recover = acpi_pm_finish,
};
static int __init init_old_suspend_ordering(const struct dmi_system_id *d)
{
old_suspend_ordering = true;
return 0;
}
static int __init init_nvs_nosave(const struct dmi_system_id *d)
{
acpi_nvs_nosave();
return 0;
}
static struct dmi_system_id __initdata acpisleep_dmi_table[] = {
{
.callback = init_old_suspend_ordering,
.ident = "Abit KN9 (nForce4 variant)",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "http://www.abit.com.tw/"),
DMI_MATCH(DMI_BOARD_NAME, "KN9 Series(NF-CK804)"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "HP xw4600 Workstation",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP xw4600 Workstation"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus Pundit P1-AH2 (M2N8L motherboard)",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTek Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "M2N8L"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Panasonic CF51-2L",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR,
"Matsushita Electric Industrial Co.,Ltd."),
DMI_MATCH(DMI_BOARD_NAME, "CF51-2L"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-FW21E",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-FW21E"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCEB17FX",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCEB17FX"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-SR11M",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-SR11M"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Everex StepNote Series",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Everex Systems, Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "Everex StepNote Series"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCEB1Z1E",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCEB1Z1E"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-NW130D",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-NW130D"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCCW29FX",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCCW29FX"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Averatec AV1020-ED2",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "AVERATEC"),
DMI_MATCH(DMI_PRODUCT_NAME, "1000 Series"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus A8N-SLI DELUXE",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "A8N-SLI DELUXE"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus A8N-SLI Premium",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "A8N-SLI Premium"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-SR26GN_P",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-SR26GN_P"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-FW520F",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-FW520F"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Asus K54C",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "K54C"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Asus K54HR",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "K54HR"),
},
},
{},
};
#endif /* CONFIG_SUSPEND */
#ifdef CONFIG_HIBERNATION
static unsigned long s4_hardware_signature;
static struct acpi_table_facs *facs;
static bool nosigcheck;
void __init acpi_no_s4_hw_signature(void)
{
nosigcheck = true;
}
static int acpi_hibernation_begin(void)
{
int error;
error = nvs_nosave ? 0 : suspend_nvs_alloc();
if (!error) {
acpi_target_sleep_state = ACPI_STATE_S4;
acpi_sleep_tts_switch(acpi_target_sleep_state);
}
return error;
}
static int acpi_hibernation_enter(void)
{
acpi_status status = AE_OK;
ACPI_FLUSH_CPU_CACHE();
/* This shouldn't return. If it returns, we have a problem */
status = acpi_enter_sleep_state(ACPI_STATE_S4, wake_sleep_flags);
/* Reprogram control registers and execute _BFS */
acpi_leave_sleep_state_prep(ACPI_STATE_S4, wake_sleep_flags);
return ACPI_SUCCESS(status) ? 0 : -EFAULT;
}
static void acpi_hibernation_leave(void)
{
/*
* If ACPI is not enabled by the BIOS and the boot kernel, we need to
* enable it here.
*/
acpi_enable();
/* Reprogram control registers and execute _BFS */
acpi_leave_sleep_state_prep(ACPI_STATE_S4, wake_sleep_flags);
/* Check the hardware signature */
if (facs && s4_hardware_signature != facs->hardware_signature) {
printk(KERN_EMERG "ACPI: Hardware changed while hibernated, "
"cannot resume!\n");
panic("ACPI S4 hardware signature mismatch");
}
/* Restore the NVS memory area */
suspend_nvs_restore();
/* Allow EC transactions to happen. */
acpi_ec_unblock_transactions_early();
}
static void acpi_pm_thaw(void)
{
acpi_ec_unblock_transactions();
acpi_enable_all_runtime_gpes();
}
static const struct platform_hibernation_ops acpi_hibernation_ops = {
.begin = acpi_hibernation_begin,
.end = acpi_pm_end,
.pre_snapshot = acpi_pm_prepare,
.finish = acpi_pm_finish,
.prepare = acpi_pm_prepare,
.enter = acpi_hibernation_enter,
.leave = acpi_hibernation_leave,
.pre_restore = acpi_pm_freeze,
.restore_cleanup = acpi_pm_thaw,
};
/**
* acpi_hibernation_begin_old - Set the target system sleep state to
* ACPI_STATE_S4 and execute the _PTS control method. This
* function is used if the pre-ACPI 2.0 suspend ordering has been
* requested.
*/
static int acpi_hibernation_begin_old(void)
{
int error;
/*
* The _TTS object should always be evaluated before the _PTS object.
* When the old_suspended_ordering is true, the _PTS object is
* evaluated in the acpi_sleep_prepare.
*/
acpi_sleep_tts_switch(ACPI_STATE_S4);
error = acpi_sleep_prepare(ACPI_STATE_S4);
if (!error) {
if (!nvs_nosave)
error = suspend_nvs_alloc();
if (!error)
acpi_target_sleep_state = ACPI_STATE_S4;
}
return error;
}
/*
* The following callbacks are used if the pre-ACPI 2.0 suspend ordering has
* been requested.
*/
static const struct platform_hibernation_ops acpi_hibernation_ops_old = {
.begin = acpi_hibernation_begin_old,
.end = acpi_pm_end,
.pre_snapshot = acpi_pm_pre_suspend,
.prepare = acpi_pm_freeze,
.finish = acpi_pm_finish,
.enter = acpi_hibernation_enter,
.leave = acpi_hibernation_leave,
.pre_restore = acpi_pm_freeze,
.restore_cleanup = acpi_pm_thaw,
.recover = acpi_pm_finish,
};
#endif /* CONFIG_HIBERNATION */
int acpi_suspend(u32 acpi_state)
{
suspend_state_t states[] = {
[1] = PM_SUSPEND_STANDBY,
[3] = PM_SUSPEND_MEM,
[5] = PM_SUSPEND_MAX
};
if (acpi_state < 6 && states[acpi_state])
return pm_suspend(states[acpi_state]);
if (acpi_state == 4)
return hibernate();
return -EINVAL;
}
#ifdef CONFIG_PM
/**
* acpi_pm_device_sleep_state - return preferred power state of ACPI device
* in the system sleep state given by %acpi_target_sleep_state
* @dev: device to examine; its driver model wakeup flags control
* whether it should be able to wake up the system
* @d_min_p: used to store the upper limit of allowed states range
* Return value: preferred power state of the device on success, -ENODEV on
* failure (ie. if there's no 'struct acpi_device' for @dev)
*
* Find the lowest power (highest number) ACPI device power state that
* device @dev can be in while the system is in the sleep state represented
* by %acpi_target_sleep_state. If @wake is nonzero, the device should be
* able to wake up the system from this sleep state. If @d_min_p is set,
* the highest power (lowest number) device power state of @dev allowed
* in this system sleep state is stored at the location pointed to by it.
*
* The caller must ensure that @dev is valid before using this function.
* The caller is also responsible for figuring out if the device is
* supposed to be able to wake up the system and passing this information
* via @wake.
*/
int acpi_pm_device_sleep_state(struct device *dev, int *d_min_p)
{
acpi_handle handle = DEVICE_ACPI_HANDLE(dev);
struct acpi_device *adev;
char acpi_method[] = "_SxD";
unsigned long long d_min, d_max;
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &adev))) {
printk(KERN_DEBUG "ACPI handle has no context!\n");
return -ENODEV;
}
acpi_method[2] = '0' + acpi_target_sleep_state;
/*
* If the sleep state is S0, we will return D3, but if the device has
* _S0W, we will use the value from _S0W
*/
d_min = ACPI_STATE_D0;
d_max = ACPI_STATE_D3;
/*
* If present, _SxD methods return the minimum D-state (highest power
* state) we can use for the corresponding S-states. Otherwise, the
* minimum D-state is D0 (ACPI 3.x).
*
* NOTE: We rely on acpi_evaluate_integer() not clobbering the integer
* provided -- that's our fault recovery, we ignore retval.
*/
if (acpi_target_sleep_state > ACPI_STATE_S0)
acpi_evaluate_integer(handle, acpi_method, NULL, &d_min);
/*
* If _PRW says we can wake up the system from the target sleep state,
* the D-state returned by _SxD is sufficient for that (we assume a
* wakeup-aware driver if wake is set). Still, if _SxW exists
* (ACPI 3.x), it should return the maximum (lowest power) D-state that
* can wake the system. _S0W may be valid, too.
*/
if (acpi_target_sleep_state == ACPI_STATE_S0 ||
(device_may_wakeup(dev) && adev->wakeup.flags.valid &&
adev->wakeup.sleep_state >= acpi_target_sleep_state)) {
acpi_status status;
acpi_method[3] = 'W';
status = acpi_evaluate_integer(handle, acpi_method, NULL,
&d_max);
if (ACPI_FAILURE(status)) {
if (acpi_target_sleep_state != ACPI_STATE_S0 ||
status != AE_NOT_FOUND)
d_max = d_min;
} else if (d_max < d_min) {
/* Warn the user of the broken DSDT */
printk(KERN_WARNING "ACPI: Wrong value from %s\n",
acpi_method);
/* Sanitize it */
d_min = d_max;
}
}
if (d_min_p)
*d_min_p = d_min;
return d_max;
}
#endif /* CONFIG_PM */
#ifdef CONFIG_PM_SLEEP
/**
* acpi_pm_device_run_wake - Enable/disable wake-up for given device.
* @phys_dev: Device to enable/disable the platform to wake-up the system for.
* @enable: Whether enable or disable the wake-up functionality.
*
* Find the ACPI device object corresponding to @pci_dev and try to
* enable/disable the GPE associated with it.
*/
int acpi_pm_device_run_wake(struct device *phys_dev, bool enable)
{
struct acpi_device *dev;
acpi_handle handle;
if (!device_run_wake(phys_dev))
return -EINVAL;
handle = DEVICE_ACPI_HANDLE(phys_dev);
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &dev))) {
dev_dbg(phys_dev, "ACPI handle has no context in %s!\n",
__func__);
return -ENODEV;
}
if (enable) {
acpi_enable_wakeup_device_power(dev, ACPI_STATE_S0);
acpi_enable_gpe(dev->wakeup.gpe_device, dev->wakeup.gpe_number);
} else {
acpi_disable_gpe(dev->wakeup.gpe_device, dev->wakeup.gpe_number);
acpi_disable_wakeup_device_power(dev);
}
return 0;
}
/**
* acpi_pm_device_sleep_wake - enable or disable the system wake-up
* capability of given device
* @dev: device to handle
* @enable: 'true' - enable, 'false' - disable the wake-up capability
*/
int acpi_pm_device_sleep_wake(struct device *dev, bool enable)
{
acpi_handle handle;
struct acpi_device *adev;
int error;
if (!device_can_wakeup(dev))
return -EINVAL;
handle = DEVICE_ACPI_HANDLE(dev);
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &adev))) {
dev_dbg(dev, "ACPI handle has no context in %s!\n", __func__);
return -ENODEV;
}
error = enable ?
acpi_enable_wakeup_device_power(adev, acpi_target_sleep_state) :
acpi_disable_wakeup_device_power(adev);
if (!error)
dev_info(dev, "wake-up capability %s by ACPI\n",
enable ? "enabled" : "disabled");
return error;
}
#endif /* CONFIG_PM_SLEEP */
static void acpi_power_off_prepare(void)
{
/* Prepare to power off the system */
acpi_sleep_prepare(ACPI_STATE_S5);
acpi_disable_all_gpes();
}
static void acpi_power_off(void)
{
/* acpi_sleep_prepare(ACPI_STATE_S5) should have already been called */
printk(KERN_DEBUG "%s called\n", __func__);
local_irq_disable();
acpi_enter_sleep_state(ACPI_STATE_S5, wake_sleep_flags);
}
/*
* ACPI 2.0 created the optional _GTS and _BFS,
* but industry adoption has been neither rapid nor broad.
*
* Linux gets into trouble when it executes poorly validated
* paths through the BIOS, so disable _GTS and _BFS by default,
* but do speak up and offer the option to enable them.
*/
static void __init acpi_gts_bfs_check(void)
{
acpi_handle dummy;
if (ACPI_SUCCESS(acpi_get_handle(ACPI_ROOT_OBJECT, METHOD_PATHNAME__GTS, &dummy)))
{
printk(KERN_NOTICE PREFIX "BIOS offers _GTS\n");
printk(KERN_NOTICE PREFIX "If \"acpi.gts=1\" improves suspend, "
"please notify linux-acpi@vger.kernel.org\n");
}
if (ACPI_SUCCESS(acpi_get_handle(ACPI_ROOT_OBJECT, METHOD_PATHNAME__BFS, &dummy)))
{
printk(KERN_NOTICE PREFIX "BIOS offers _BFS\n");
printk(KERN_NOTICE PREFIX "If \"acpi.bfs=1\" improves resume, "
"please notify linux-acpi@vger.kernel.org\n");
}
}
int __init acpi_sleep_init(void)
{
acpi_status status;
u8 type_a, type_b;
#ifdef CONFIG_SUSPEND
int i = 0;
dmi_check_system(acpisleep_dmi_table);
#endif
if (acpi_disabled)
return 0;
sleep_states[ACPI_STATE_S0] = 1;
printk(KERN_INFO PREFIX "(supports S0");
#ifdef CONFIG_SUSPEND
for (i = ACPI_STATE_S1; i < ACPI_STATE_S4; i++) {
status = acpi_get_sleep_type_data(i, &type_a, &type_b);
if (ACPI_SUCCESS(status)) {
sleep_states[i] = 1;
printk(" S%d", i);
}
}
suspend_set_ops(old_suspend_ordering ?
&acpi_suspend_ops_old : &acpi_suspend_ops);
#endif
#ifdef CONFIG_HIBERNATION
status = acpi_get_sleep_type_data(ACPI_STATE_S4, &type_a, &type_b);
if (ACPI_SUCCESS(status)) {
hibernation_set_ops(old_suspend_ordering ?
&acpi_hibernation_ops_old : &acpi_hibernation_ops);
sleep_states[ACPI_STATE_S4] = 1;
printk(" S4");
if (!nosigcheck) {
acpi_get_table(ACPI_SIG_FACS, 1,
(struct acpi_table_header **)&facs);
if (facs)
s4_hardware_signature =
facs->hardware_signature;
}
}
#endif
status = acpi_get_sleep_type_data(ACPI_STATE_S5, &type_a, &type_b);
if (ACPI_SUCCESS(status)) {
sleep_states[ACPI_STATE_S5] = 1;
printk(" S5");
pm_power_off_prepare = acpi_power_off_prepare;
pm_power_off = acpi_power_off;
}
printk(")\n");
/*
* Register the tts_notifier to reboot notifier list so that the _TTS
* object can also be evaluated when the system enters S5.
*/
register_reboot_notifier(&tts_notifier);
acpi_gts_bfs_check();
return 0;
}
| gpl-2.0 |
wgoossens/linux-nios2 | arch/arm/mach-tegra/cpuidle-tegra20.c | 516 | 5181 | /*
* CPU idle driver for Tegra CPUs
*
* Copyright (c) 2010-2012, NVIDIA Corporation.
* Copyright (c) 2011 Google, Inc.
* Author: Colin Cross <ccross@android.com>
* Gary King <gking@nvidia.com>
*
* Rework for 3.3 by Peter De Schrijver <pdeschrijver@nvidia.com>
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/cpuidle.h>
#include <linux/cpu_pm.h>
#include <linux/clockchips.h>
#include <linux/clk/tegra.h>
#include <asm/cpuidle.h>
#include <asm/proc-fns.h>
#include <asm/suspend.h>
#include <asm/smp_plat.h>
#include "pm.h"
#include "sleep.h"
#include "iomap.h"
#include "irq.h"
#include "flowctrl.h"
#ifdef CONFIG_PM_SLEEP
static bool abort_flag;
static atomic_t abort_barrier;
static int tegra20_idle_lp2_coupled(struct cpuidle_device *dev,
struct cpuidle_driver *drv,
int index);
#define TEGRA20_MAX_STATES 2
#else
#define TEGRA20_MAX_STATES 1
#endif
static struct cpuidle_driver tegra_idle_driver = {
.name = "tegra_idle",
.owner = THIS_MODULE,
.states = {
ARM_CPUIDLE_WFI_STATE_PWR(600),
#ifdef CONFIG_PM_SLEEP
{
.enter = tegra20_idle_lp2_coupled,
.exit_latency = 5000,
.target_residency = 10000,
.power_usage = 0,
.flags = CPUIDLE_FLAG_TIME_VALID |
CPUIDLE_FLAG_COUPLED,
.name = "powered-down",
.desc = "CPU power gated",
},
#endif
},
.state_count = TEGRA20_MAX_STATES,
.safe_state_index = 0,
};
#ifdef CONFIG_PM_SLEEP
#ifdef CONFIG_SMP
static void __iomem *pmc = IO_ADDRESS(TEGRA_PMC_BASE);
static int tegra20_reset_sleeping_cpu_1(void)
{
int ret = 0;
tegra_pen_lock();
if (readl(pmc + PMC_SCRATCH41) == CPU_RESETTABLE)
tegra20_cpu_shutdown(1);
else
ret = -EINVAL;
tegra_pen_unlock();
return ret;
}
static void tegra20_wake_cpu1_from_reset(void)
{
tegra_pen_lock();
tegra20_cpu_clear_resettable();
/* enable cpu clock on cpu */
tegra_enable_cpu_clock(1);
/* take the CPU out of reset */
tegra_cpu_out_of_reset(1);
/* unhalt the cpu */
flowctrl_write_cpu_halt(1, 0);
tegra_pen_unlock();
}
static int tegra20_reset_cpu_1(void)
{
if (!cpu_online(1) || !tegra20_reset_sleeping_cpu_1())
return 0;
tegra20_wake_cpu1_from_reset();
return -EBUSY;
}
#else
static inline void tegra20_wake_cpu1_from_reset(void)
{
}
static inline int tegra20_reset_cpu_1(void)
{
return 0;
}
#endif
static bool tegra20_cpu_cluster_power_down(struct cpuidle_device *dev,
struct cpuidle_driver *drv,
int index)
{
while (tegra20_cpu_is_resettable_soon())
cpu_relax();
if (tegra20_reset_cpu_1() || !tegra_cpu_rail_off_ready())
return false;
clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_ENTER, &dev->cpu);
tegra_idle_lp2_last();
clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_EXIT, &dev->cpu);
if (cpu_online(1))
tegra20_wake_cpu1_from_reset();
return true;
}
#ifdef CONFIG_SMP
static bool tegra20_idle_enter_lp2_cpu_1(struct cpuidle_device *dev,
struct cpuidle_driver *drv,
int index)
{
clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_ENTER, &dev->cpu);
cpu_suspend(0, tegra20_sleep_cpu_secondary_finish);
tegra20_cpu_clear_resettable();
clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_EXIT, &dev->cpu);
return true;
}
#else
static inline bool tegra20_idle_enter_lp2_cpu_1(struct cpuidle_device *dev,
struct cpuidle_driver *drv,
int index)
{
return true;
}
#endif
static int tegra20_idle_lp2_coupled(struct cpuidle_device *dev,
struct cpuidle_driver *drv,
int index)
{
bool entered_lp2 = false;
if (tegra_pending_sgi())
ACCESS_ONCE(abort_flag) = true;
cpuidle_coupled_parallel_barrier(dev, &abort_barrier);
if (abort_flag) {
cpuidle_coupled_parallel_barrier(dev, &abort_barrier);
abort_flag = false; /* clean flag for next coming */
return -EINTR;
}
local_fiq_disable();
tegra_set_cpu_in_lp2();
cpu_pm_enter();
if (dev->cpu == 0)
entered_lp2 = tegra20_cpu_cluster_power_down(dev, drv, index);
else
entered_lp2 = tegra20_idle_enter_lp2_cpu_1(dev, drv, index);
cpu_pm_exit();
tegra_clear_cpu_in_lp2();
local_fiq_enable();
smp_rmb();
return entered_lp2 ? index : 0;
}
#endif
/*
* Tegra20 HW appears to have a bug such that PCIe device interrupts, whether
* they are legacy IRQs or MSI, are lost when LP2 is enabled. To work around
* this, simply disable LP2 if the PCI driver and DT node are both enabled.
*/
void tegra20_cpuidle_pcie_irqs_in_use(void)
{
pr_info_once(
"Disabling cpuidle LP2 state, since PCIe IRQs are in use\n");
tegra_idle_driver.states[1].disabled = true;
}
int __init tegra20_cpuidle_init(void)
{
return cpuidle_register(&tegra_idle_driver, cpu_possible_mask);
}
| gpl-2.0 |
Victor-android/kernel_u8800 | net/rds/info.c | 516 | 6598 | /*
* Copyright (c) 2006 Oracle. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/percpu.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include "rds.h"
/*
* This file implements a getsockopt() call which copies a set of fixed
* sized structs into a user-specified buffer as a means of providing
* read-only information about RDS.
*
* For a given information source there are a given number of fixed sized
* structs at a given time. The structs are only copied if the user-specified
* buffer is big enough. The destination pages that make up the buffer
* are pinned for the duration of the copy.
*
* This gives us the following benefits:
*
* - simple implementation, no copy "position" across multiple calls
* - consistent snapshot of an info source
* - atomic copy works well with whatever locking info source has
* - one portable tool to get rds info across implementations
* - long-lived tool can get info without allocating
*
* at the following costs:
*
* - info source copy must be pinned, may be "large"
*/
struct rds_info_iterator {
struct page **pages;
void *addr;
unsigned long offset;
};
static DEFINE_SPINLOCK(rds_info_lock);
static rds_info_func rds_info_funcs[RDS_INFO_LAST - RDS_INFO_FIRST + 1];
void rds_info_register_func(int optname, rds_info_func func)
{
int offset = optname - RDS_INFO_FIRST;
BUG_ON(optname < RDS_INFO_FIRST || optname > RDS_INFO_LAST);
spin_lock(&rds_info_lock);
BUG_ON(rds_info_funcs[offset] != NULL);
rds_info_funcs[offset] = func;
spin_unlock(&rds_info_lock);
}
EXPORT_SYMBOL_GPL(rds_info_register_func);
void rds_info_deregister_func(int optname, rds_info_func func)
{
int offset = optname - RDS_INFO_FIRST;
BUG_ON(optname < RDS_INFO_FIRST || optname > RDS_INFO_LAST);
spin_lock(&rds_info_lock);
BUG_ON(rds_info_funcs[offset] != func);
rds_info_funcs[offset] = NULL;
spin_unlock(&rds_info_lock);
}
EXPORT_SYMBOL_GPL(rds_info_deregister_func);
/*
* Typically we hold an atomic kmap across multiple rds_info_copy() calls
* because the kmap is so expensive. This must be called before using blocking
* operations while holding the mapping and as the iterator is torn down.
*/
void rds_info_iter_unmap(struct rds_info_iterator *iter)
{
if (iter->addr != NULL) {
kunmap_atomic(iter->addr, KM_USER0);
iter->addr = NULL;
}
}
/*
* get_user_pages() called flush_dcache_page() on the pages for us.
*/
void rds_info_copy(struct rds_info_iterator *iter, void *data,
unsigned long bytes)
{
unsigned long this;
while (bytes) {
if (iter->addr == NULL)
iter->addr = kmap_atomic(*iter->pages, KM_USER0);
this = min(bytes, PAGE_SIZE - iter->offset);
rdsdebug("page %p addr %p offset %lu this %lu data %p "
"bytes %lu\n", *iter->pages, iter->addr,
iter->offset, this, data, bytes);
memcpy(iter->addr + iter->offset, data, this);
data += this;
bytes -= this;
iter->offset += this;
if (iter->offset == PAGE_SIZE) {
kunmap_atomic(iter->addr, KM_USER0);
iter->addr = NULL;
iter->offset = 0;
iter->pages++;
}
}
}
EXPORT_SYMBOL_GPL(rds_info_copy);
/*
* @optval points to the userspace buffer that the information snapshot
* will be copied into.
*
* @optlen on input is the size of the buffer in userspace. @optlen
* on output is the size of the requested snapshot in bytes.
*
* This function returns -errno if there is a failure, particularly -ENOSPC
* if the given userspace buffer was not large enough to fit the snapshot.
* On success it returns the positive number of bytes of each array element
* in the snapshot.
*/
int rds_info_getsockopt(struct socket *sock, int optname, char __user *optval,
int __user *optlen)
{
struct rds_info_iterator iter;
struct rds_info_lengths lens;
unsigned long nr_pages = 0;
unsigned long start;
unsigned long i;
rds_info_func func;
struct page **pages = NULL;
int ret;
int len;
int total;
if (get_user(len, optlen)) {
ret = -EFAULT;
goto out;
}
/* check for all kinds of wrapping and the like */
start = (unsigned long)optval;
if (len < 0 || len + PAGE_SIZE - 1 < len || start + len < start) {
ret = -EINVAL;
goto out;
}
/* a 0 len call is just trying to probe its length */
if (len == 0)
goto call_func;
nr_pages = (PAGE_ALIGN(start + len) - (start & PAGE_MASK))
>> PAGE_SHIFT;
pages = kmalloc(nr_pages * sizeof(struct page *), GFP_KERNEL);
if (pages == NULL) {
ret = -ENOMEM;
goto out;
}
ret = get_user_pages_fast(start, nr_pages, 1, pages);
if (ret != nr_pages) {
if (ret > 0)
nr_pages = ret;
else
nr_pages = 0;
ret = -EAGAIN; /* XXX ? */
goto out;
}
rdsdebug("len %d nr_pages %lu\n", len, nr_pages);
call_func:
func = rds_info_funcs[optname - RDS_INFO_FIRST];
if (func == NULL) {
ret = -ENOPROTOOPT;
goto out;
}
iter.pages = pages;
iter.addr = NULL;
iter.offset = start & (PAGE_SIZE - 1);
func(sock, len, &iter, &lens);
BUG_ON(lens.each == 0);
total = lens.nr * lens.each;
rds_info_iter_unmap(&iter);
if (total > len) {
len = total;
ret = -ENOSPC;
} else {
len = total;
ret = lens.each;
}
if (put_user(len, optlen))
ret = -EFAULT;
out:
for (i = 0; pages != NULL && i < nr_pages; i++)
put_page(pages[i]);
kfree(pages);
return ret;
}
| gpl-2.0 |
paranoiacblack/gcc | zlib/test/infcover.c | 772 | 24700 | /* infcover.c -- test zlib's inflate routines with full code coverage
* Copyright (C) 2011 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* to use, do: ./configure --cover && make cover */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "zlib.h"
/* get definition of internal structure so we can mess with it (see pull()),
and so we can call inflate_trees() (see cover5()) */
#define ZLIB_INTERNAL
#include "inftrees.h"
#include "inflate.h"
#define local static
/* -- memory tracking routines -- */
/*
These memory tracking routines are provided to zlib and track all of zlib's
allocations and deallocations, check for LIFO operations, keep a current
and high water mark of total bytes requested, optionally set a limit on the
total memory that can be allocated, and when done check for memory leaks.
They are used as follows:
z_stream strm;
mem_setup(&strm) initializes the memory tracking and sets the
zalloc, zfree, and opaque members of strm to use
memory tracking for all zlib operations on strm
mem_limit(&strm, limit) sets a limit on the total bytes requested -- a
request that exceeds this limit will result in an
allocation failure (returns NULL) -- setting the
limit to zero means no limit, which is the default
after mem_setup()
mem_used(&strm, "msg") prints to stderr "msg" and the total bytes used
mem_high(&strm, "msg") prints to stderr "msg" and the high water mark
mem_done(&strm, "msg") ends memory tracking, releases all allocations
for the tracking as well as leaked zlib blocks, if
any. If there was anything unusual, such as leaked
blocks, non-FIFO frees, or frees of addresses not
allocated, then "msg" and information about the
problem is printed to stderr. If everything is
normal, nothing is printed. mem_done resets the
strm members to Z_NULL to use the default memory
allocation routines on the next zlib initialization
using strm.
*/
/* these items are strung together in a linked list, one for each allocation */
struct mem_item {
void *ptr; /* pointer to allocated memory */
size_t size; /* requested size of allocation */
struct mem_item *next; /* pointer to next item in list, or NULL */
};
/* this structure is at the root of the linked list, and tracks statistics */
struct mem_zone {
struct mem_item *first; /* pointer to first item in list, or NULL */
size_t total, highwater; /* total allocations, and largest total */
size_t limit; /* memory allocation limit, or 0 if no limit */
int notlifo, rogue; /* counts of non-LIFO frees and rogue frees */
};
/* memory allocation routine to pass to zlib */
local void *mem_alloc(void *mem, unsigned count, unsigned size)
{
void *ptr;
struct mem_item *item;
struct mem_zone *zone = mem;
size_t len = count * (size_t)size;
/* induced allocation failure */
if (zone == NULL || (zone->limit && zone->total + len > zone->limit))
return NULL;
/* perform allocation using the standard library, fill memory with a
non-zero value to make sure that the code isn't depending on zeros */
ptr = malloc(len);
if (ptr == NULL)
return NULL;
memset(ptr, 0xa5, len);
/* create a new item for the list */
item = malloc(sizeof(struct mem_item));
if (item == NULL) {
free(ptr);
return NULL;
}
item->ptr = ptr;
item->size = len;
/* insert item at the beginning of the list */
item->next = zone->first;
zone->first = item;
/* update the statistics */
zone->total += item->size;
if (zone->total > zone->highwater)
zone->highwater = zone->total;
/* return the allocated memory */
return ptr;
}
/* memory free routine to pass to zlib */
local void mem_free(void *mem, void *ptr)
{
struct mem_item *item, *next;
struct mem_zone *zone = mem;
/* if no zone, just do a free */
if (zone == NULL) {
free(ptr);
return;
}
/* point next to the item that matches ptr, or NULL if not found -- remove
the item from the linked list if found */
next = zone->first;
if (next) {
if (next->ptr == ptr)
zone->first = next->next; /* first one is it, remove from list */
else {
do { /* search the linked list */
item = next;
next = item->next;
} while (next != NULL && next->ptr != ptr);
if (next) { /* if found, remove from linked list */
item->next = next->next;
zone->notlifo++; /* not a LIFO free */
}
}
}
/* if found, update the statistics and free the item */
if (next) {
zone->total -= next->size;
free(next);
}
/* if not found, update the rogue count */
else
zone->rogue++;
/* in any case, do the requested free with the standard library function */
free(ptr);
}
/* set up a controlled memory allocation space for monitoring, set the stream
parameters to the controlled routines, with opaque pointing to the space */
local void mem_setup(z_stream *strm)
{
struct mem_zone *zone;
zone = malloc(sizeof(struct mem_zone));
assert(zone != NULL);
zone->first = NULL;
zone->total = 0;
zone->highwater = 0;
zone->limit = 0;
zone->notlifo = 0;
zone->rogue = 0;
strm->opaque = zone;
strm->zalloc = mem_alloc;
strm->zfree = mem_free;
}
/* set a limit on the total memory allocation, or 0 to remove the limit */
local void mem_limit(z_stream *strm, size_t limit)
{
struct mem_zone *zone = strm->opaque;
zone->limit = limit;
}
/* show the current total requested allocations in bytes */
local void mem_used(z_stream *strm, char *prefix)
{
struct mem_zone *zone = strm->opaque;
fprintf(stderr, "%s: %lu allocated\n", prefix, zone->total);
}
/* show the high water allocation in bytes */
local void mem_high(z_stream *strm, char *prefix)
{
struct mem_zone *zone = strm->opaque;
fprintf(stderr, "%s: %lu high water mark\n", prefix, zone->highwater);
}
/* release the memory allocation zone -- if there are any surprises, notify */
local void mem_done(z_stream *strm, char *prefix)
{
int count = 0;
struct mem_item *item, *next;
struct mem_zone *zone = strm->opaque;
/* show high water mark */
mem_high(strm, prefix);
/* free leftover allocations and item structures, if any */
item = zone->first;
while (item != NULL) {
free(item->ptr);
next = item->next;
free(item);
item = next;
count++;
}
/* issue alerts about anything unexpected */
if (count || zone->total)
fprintf(stderr, "** %s: %lu bytes in %d blocks not freed\n",
prefix, zone->total, count);
if (zone->notlifo)
fprintf(stderr, "** %s: %d frees not LIFO\n", prefix, zone->notlifo);
if (zone->rogue)
fprintf(stderr, "** %s: %d frees not recognized\n",
prefix, zone->rogue);
/* free the zone and delete from the stream */
free(zone);
strm->opaque = Z_NULL;
strm->zalloc = Z_NULL;
strm->zfree = Z_NULL;
}
/* -- inflate test routines -- */
/* Decode a hexadecimal string, set *len to length, in[] to the bytes. This
decodes liberally, in that hex digits can be adjacent, in which case two in
a row writes a byte. Or they can delimited by any non-hex character, where
the delimiters are ignored except when a single hex digit is followed by a
delimiter in which case that single digit writes a byte. The returned
data is allocated and must eventually be freed. NULL is returned if out of
memory. If the length is not needed, then len can be NULL. */
local unsigned char *h2b(const char *hex, unsigned *len)
{
unsigned char *in;
unsigned next, val;
in = malloc((strlen(hex) + 1) >> 1);
if (in == NULL)
return NULL;
next = 0;
val = 1;
do {
if (*hex >= '0' && *hex <= '9')
val = (val << 4) + *hex - '0';
else if (*hex >= 'A' && *hex <= 'F')
val = (val << 4) + *hex - 'A' + 10;
else if (*hex >= 'a' && *hex <= 'f')
val = (val << 4) + *hex - 'a' + 10;
else if (val != 1 && val < 32) /* one digit followed by delimiter */
val += 240; /* make it look like two digits */
if (val > 255) { /* have two digits */
in[next++] = val & 0xff; /* save the decoded byte */
val = 1; /* start over */
}
} while (*hex++); /* go through the loop with the terminating null */
if (len != NULL)
*len = next;
in = reallocf(in, next);
return in;
}
/* generic inflate() run, where hex is the hexadecimal input data, what is the
text to include in an error message, step is how much input data to feed
inflate() on each call, or zero to feed it all, win is the window bits
parameter to inflateInit2(), len is the size of the output buffer, and err
is the error code expected from the first inflate() call (the second
inflate() call is expected to return Z_STREAM_END). If win is 47, then
header information is collected with inflateGetHeader(). If a zlib stream
is looking for a dictionary, then an empty dictionary is provided.
inflate() is run until all of the input data is consumed. */
local void inf(char *hex, char *what, unsigned step, int win, unsigned len,
int err)
{
int ret;
unsigned have;
unsigned char *in, *out;
z_stream strm, copy;
gz_header head;
mem_setup(&strm);
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit2(&strm, win);
if (ret != Z_OK) {
mem_done(&strm, what);
return;
}
out = malloc(len); assert(out != NULL);
if (win == 47) {
head.extra = out;
head.extra_max = len;
head.name = out;
head.name_max = len;
head.comment = out;
head.comm_max = len;
ret = inflateGetHeader(&strm, &head); assert(ret == Z_OK);
}
in = h2b(hex, &have); assert(in != NULL);
if (step == 0 || step > have)
step = have;
strm.avail_in = step;
have -= step;
strm.next_in = in;
do {
strm.avail_out = len;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH); assert(err == 9 || ret == err);
if (ret != Z_OK && ret != Z_BUF_ERROR && ret != Z_NEED_DICT)
break;
if (ret == Z_NEED_DICT) {
ret = inflateSetDictionary(&strm, in, 1);
assert(ret == Z_DATA_ERROR);
mem_limit(&strm, 1);
ret = inflateSetDictionary(&strm, out, 0);
assert(ret == Z_MEM_ERROR);
mem_limit(&strm, 0);
((struct inflate_state *)strm.state)->mode = DICT;
ret = inflateSetDictionary(&strm, out, 0);
assert(ret == Z_OK);
ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_BUF_ERROR);
}
ret = inflateCopy(©, &strm); assert(ret == Z_OK);
ret = inflateEnd(©); assert(ret == Z_OK);
err = 9; /* don't care next time around */
have += strm.avail_in;
strm.avail_in = step > have ? have : step;
have -= strm.avail_in;
} while (strm.avail_in);
free(in);
free(out);
ret = inflateReset2(&strm, -8); assert(ret == Z_OK);
ret = inflateEnd(&strm); assert(ret == Z_OK);
mem_done(&strm, what);
}
/* cover all of the lines in inflate.c up to inflate() */
local void cover_support(void)
{
int ret;
z_stream strm;
mem_setup(&strm);
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm); assert(ret == Z_OK);
mem_used(&strm, "inflate init");
ret = inflatePrime(&strm, 5, 31); assert(ret == Z_OK);
ret = inflatePrime(&strm, -1, 0); assert(ret == Z_OK);
ret = inflateSetDictionary(&strm, Z_NULL, 0);
assert(ret == Z_STREAM_ERROR);
ret = inflateEnd(&strm); assert(ret == Z_OK);
mem_done(&strm, "prime");
inf("63 0", "force window allocation", 0, -15, 1, Z_OK);
inf("63 18 5", "force window replacement", 0, -8, 259, Z_OK);
inf("63 18 68 30 d0 0 0", "force split window update", 4, -8, 259, Z_OK);
inf("3 0", "use fixed blocks", 0, -15, 1, Z_STREAM_END);
inf("", "bad window size", 0, 1, 0, Z_STREAM_ERROR);
mem_setup(&strm);
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit_(&strm, ZLIB_VERSION - 1, (int)sizeof(z_stream));
assert(ret == Z_VERSION_ERROR);
mem_done(&strm, "wrong version");
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm); assert(ret == Z_OK);
ret = inflateEnd(&strm); assert(ret == Z_OK);
fputs("inflate built-in memory routines\n", stderr);
}
/* cover all inflate() header and trailer cases and code after inflate() */
local void cover_wrap(void)
{
int ret;
z_stream strm, copy;
unsigned char dict[257];
ret = inflate(Z_NULL, 0); assert(ret == Z_STREAM_ERROR);
ret = inflateEnd(Z_NULL); assert(ret == Z_STREAM_ERROR);
ret = inflateCopy(Z_NULL, Z_NULL); assert(ret == Z_STREAM_ERROR);
fputs("inflate bad parameters\n", stderr);
inf("1f 8b 0 0", "bad gzip method", 0, 31, 0, Z_DATA_ERROR);
inf("1f 8b 8 80", "bad gzip flags", 0, 31, 0, Z_DATA_ERROR);
inf("77 85", "bad zlib method", 0, 15, 0, Z_DATA_ERROR);
inf("8 99", "set window size from header", 0, 0, 0, Z_OK);
inf("78 9c", "bad zlib window size", 0, 8, 0, Z_DATA_ERROR);
inf("78 9c 63 0 0 0 1 0 1", "check adler32", 0, 15, 1, Z_STREAM_END);
inf("1f 8b 8 1e 0 0 0 0 0 0 1 0 0 0 0 0 0", "bad header crc", 0, 47, 1,
Z_DATA_ERROR);
inf("1f 8b 8 2 0 0 0 0 0 0 1d 26 3 0 0 0 0 0 0 0 0 0", "check gzip length",
0, 47, 0, Z_STREAM_END);
inf("78 90", "bad zlib header check", 0, 47, 0, Z_DATA_ERROR);
inf("8 b8 0 0 0 1", "need dictionary", 0, 8, 0, Z_NEED_DICT);
inf("78 9c 63 0", "compute adler32", 0, 15, 1, Z_OK);
mem_setup(&strm);
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit2(&strm, -8);
strm.avail_in = 2;
strm.next_in = (void *)"\x63";
strm.avail_out = 1;
strm.next_out = (void *)&ret;
mem_limit(&strm, 1);
ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_MEM_ERROR);
ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_MEM_ERROR);
mem_limit(&strm, 0);
memset(dict, 0, 257);
ret = inflateSetDictionary(&strm, dict, 257);
assert(ret == Z_OK);
mem_limit(&strm, (sizeof(struct inflate_state) << 1) + 256);
ret = inflatePrime(&strm, 16, 0); assert(ret == Z_OK);
strm.avail_in = 2;
strm.next_in = (void *)"\x80";
ret = inflateSync(&strm); assert(ret == Z_DATA_ERROR);
ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_STREAM_ERROR);
strm.avail_in = 4;
strm.next_in = (void *)"\0\0\xff\xff";
ret = inflateSync(&strm); assert(ret == Z_OK);
(void)inflateSyncPoint(&strm);
ret = inflateCopy(©, &strm); assert(ret == Z_MEM_ERROR);
mem_limit(&strm, 0);
ret = inflateUndermine(&strm, 1); assert(ret == Z_DATA_ERROR);
(void)inflateMark(&strm);
ret = inflateEnd(&strm); assert(ret == Z_OK);
mem_done(&strm, "miscellaneous, force memory errors");
}
/* input and output functions for inflateBack() */
local unsigned pull(void *desc, unsigned char **buf)
{
static unsigned int next = 0;
static unsigned char dat[] = {0x63, 0, 2, 0};
struct inflate_state *state;
if (desc == Z_NULL) {
next = 0;
return 0; /* no input (already provided at next_in) */
}
state = (void *)((z_stream *)desc)->state;
if (state != Z_NULL)
state->mode = SYNC; /* force an otherwise impossible situation */
return next < sizeof(dat) ? (*buf = dat + next++, 1) : 0;
}
local int push(void *desc, unsigned char *buf, unsigned len)
{
buf += len;
return desc != Z_NULL; /* force error if desc not null */
}
/* cover inflateBack() up to common deflate data cases and after those */
local void cover_back(void)
{
int ret;
z_stream strm;
unsigned char win[32768];
ret = inflateBackInit_(Z_NULL, 0, win, 0, 0);
assert(ret == Z_VERSION_ERROR);
ret = inflateBackInit(Z_NULL, 0, win); assert(ret == Z_STREAM_ERROR);
ret = inflateBack(Z_NULL, Z_NULL, Z_NULL, Z_NULL, Z_NULL);
assert(ret == Z_STREAM_ERROR);
ret = inflateBackEnd(Z_NULL); assert(ret == Z_STREAM_ERROR);
fputs("inflateBack bad parameters\n", stderr);
mem_setup(&strm);
ret = inflateBackInit(&strm, 15, win); assert(ret == Z_OK);
strm.avail_in = 2;
strm.next_in = (void *)"\x03";
ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL);
assert(ret == Z_STREAM_END);
/* force output error */
strm.avail_in = 3;
strm.next_in = (void *)"\x63\x00";
ret = inflateBack(&strm, pull, Z_NULL, push, &strm);
assert(ret == Z_BUF_ERROR);
/* force mode error by mucking with state */
ret = inflateBack(&strm, pull, &strm, push, Z_NULL);
assert(ret == Z_STREAM_ERROR);
ret = inflateBackEnd(&strm); assert(ret == Z_OK);
mem_done(&strm, "inflateBack bad state");
ret = inflateBackInit(&strm, 15, win); assert(ret == Z_OK);
ret = inflateBackEnd(&strm); assert(ret == Z_OK);
fputs("inflateBack built-in memory routines\n", stderr);
}
/* do a raw inflate of data in hexadecimal with both inflate and inflateBack */
local int try(char *hex, char *id, int err)
{
int ret;
unsigned len, size;
unsigned char *in, *out, *win;
char *prefix;
z_stream strm;
/* convert to hex */
in = h2b(hex, &len);
assert(in != NULL);
/* allocate work areas */
size = len << 3;
out = malloc(size);
assert(out != NULL);
win = malloc(32768);
assert(win != NULL);
prefix = malloc(strlen(id) + 6);
assert(prefix != NULL);
/* first with inflate */
strcpy(prefix, id);
strcat(prefix, "-late");
mem_setup(&strm);
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit2(&strm, err < 0 ? 47 : -15);
assert(ret == Z_OK);
strm.avail_in = len;
strm.next_in = in;
do {
strm.avail_out = size;
strm.next_out = out;
ret = inflate(&strm, Z_TREES);
assert(ret != Z_STREAM_ERROR && ret != Z_MEM_ERROR);
if (ret == Z_DATA_ERROR || ret == Z_NEED_DICT)
break;
} while (strm.avail_in || strm.avail_out == 0);
if (err) {
assert(ret == Z_DATA_ERROR);
assert(strcmp(id, strm.msg) == 0);
}
inflateEnd(&strm);
mem_done(&strm, prefix);
/* then with inflateBack */
if (err >= 0) {
strcpy(prefix, id);
strcat(prefix, "-back");
mem_setup(&strm);
ret = inflateBackInit(&strm, 15, win);
assert(ret == Z_OK);
strm.avail_in = len;
strm.next_in = in;
ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL);
assert(ret != Z_STREAM_ERROR);
if (err) {
assert(ret == Z_DATA_ERROR);
assert(strcmp(id, strm.msg) == 0);
}
inflateBackEnd(&strm);
mem_done(&strm, prefix);
}
/* clean up */
free(prefix);
free(win);
free(out);
free(in);
return ret;
}
/* cover deflate data cases in both inflate() and inflateBack() */
local void cover_inflate(void)
{
try("0 0 0 0 0", "invalid stored block lengths", 1);
try("3 0", "fixed", 0);
try("6", "invalid block type", 1);
try("1 1 0 fe ff 0", "stored", 0);
try("fc 0 0", "too many length or distance symbols", 1);
try("4 0 fe ff", "invalid code lengths set", 1);
try("4 0 24 49 0", "invalid bit length repeat", 1);
try("4 0 24 e9 ff ff", "invalid bit length repeat", 1);
try("4 0 24 e9 ff 6d", "invalid code -- missing end-of-block", 1);
try("4 80 49 92 24 49 92 24 71 ff ff 93 11 0",
"invalid literal/lengths set", 1);
try("4 80 49 92 24 49 92 24 f b4 ff ff c3 84", "invalid distances set", 1);
try("4 c0 81 8 0 0 0 0 20 7f eb b 0 0", "invalid literal/length code", 1);
try("2 7e ff ff", "invalid distance code", 1);
try("c c0 81 0 0 0 0 0 90 ff 6b 4 0", "invalid distance too far back", 1);
/* also trailer mismatch just in inflate() */
try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 1", "incorrect data check", -1);
try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 1",
"incorrect length check", -1);
try("5 c0 21 d 0 0 0 80 b0 fe 6d 2f 91 6c", "pull 17", 0);
try("5 e0 81 91 24 cb b2 2c 49 e2 f 2e 8b 9a 47 56 9f fb fe ec d2 ff 1f",
"long code", 0);
try("ed c0 1 1 0 0 0 40 20 ff 57 1b 42 2c 4f", "length extra", 0);
try("ed cf c1 b1 2c 47 10 c4 30 fa 6f 35 1d 1 82 59 3d fb be 2e 2a fc f c",
"long distance and extra", 0);
try("ed c0 81 0 0 0 0 80 a0 fd a9 17 a9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6", "window end", 0);
inf("2 8 20 80 0 3 0", "inflate_fast TYPE return", 0, -15, 258,
Z_STREAM_END);
inf("63 18 5 40 c 0", "window wrap", 3, -8, 300, Z_OK);
}
/* cover remaining lines in inftrees.c */
local void cover_trees(void)
{
int ret;
unsigned bits;
unsigned short lens[16], work[16];
code *next, table[ENOUGH_DISTS];
/* we need to call inflate_table() directly in order to manifest not-
enough errors, since zlib insures that enough is always enough */
for (bits = 0; bits < 15; bits++)
lens[bits] = (unsigned short)(bits + 1);
lens[15] = 15;
next = table;
bits = 15;
ret = inflate_table(DISTS, lens, 16, &next, &bits, work);
assert(ret == 1);
next = table;
bits = 1;
ret = inflate_table(DISTS, lens, 16, &next, &bits, work);
assert(ret == 1);
fputs("inflate_table not enough errors\n", stderr);
}
/* cover remaining inffast.c decoding and window copying */
local void cover_fast(void)
{
inf("e5 e0 81 ad 6d cb b2 2c c9 01 1e 59 63 ae 7d ee fb 4d fd b5 35 41 68"
" ff 7f 0f 0 0 0", "fast length extra bits", 0, -8, 258, Z_DATA_ERROR);
inf("25 fd 81 b5 6d 59 b6 6a 49 ea af 35 6 34 eb 8c b9 f6 b9 1e ef 67 49"
" 50 fe ff ff 3f 0 0", "fast distance extra bits", 0, -8, 258,
Z_DATA_ERROR);
inf("3 7e 0 0 0 0 0", "fast invalid distance code", 0, -8, 258,
Z_DATA_ERROR);
inf("1b 7 0 0 0 0 0", "fast invalid literal/length code", 0, -8, 258,
Z_DATA_ERROR);
inf("d c7 1 ae eb 38 c 4 41 a0 87 72 de df fb 1f b8 36 b1 38 5d ff ff 0",
"fast 2nd level codes and too far back", 0, -8, 258, Z_DATA_ERROR);
inf("63 18 5 8c 10 8 0 0 0 0", "very common case", 0, -8, 259, Z_OK);
inf("63 60 60 18 c9 0 8 18 18 18 26 c0 28 0 29 0 0 0",
"contiguous and wrap around window", 6, -8, 259, Z_OK);
inf("63 0 3 0 0 0 0 0", "copy direct from output", 0, -8, 259,
Z_STREAM_END);
}
int main(void)
{
fprintf(stderr, "%s\n", zlibVersion());
cover_support();
cover_wrap();
cover_back();
cover_inflate();
cover_trees();
cover_fast();
return 0;
}
| gpl-2.0 |
thicklizard/m9-patches | drivers/soc/qcom/jtagv8.c | 772 | 22999 | /* Copyright (c) 2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/smp.h>
#include <linux/export.h>
#include <linux/printk.h>
#include <linux/ratelimit.h>
#include <linux/coresight.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/bitops.h>
#include <soc/qcom/scm.h>
#include <soc/qcom/jtag.h>
#ifdef CONFIG_ARM64
#include <asm/debugv8.h>
#else
#include <asm/hardware/debugv8.h>
#endif
#define CORESIGHT_LAR (0xFB0)
#define CORESIGHT_UNLOCK (0xC5ACCE55)
#define TIMEOUT_US (100)
#define BM(lsb, msb) ((BIT(msb) - BIT(lsb)) + BIT(msb))
#define BMVAL(val, lsb, msb) ((val & BM(lsb, msb)) >> lsb)
#define BVAL(val, n) ((val & BIT(n)) >> n)
#define ARM_DEBUG_ARCH_V8 (0x6)
#define MAX_DBG_REGS (66)
#define MAX_DBG_STATE_SIZE (MAX_DBG_REGS * num_possible_cpus())
#define OSLOCK_MAGIC (0xC5ACCE55)
#define TZ_DBG_ETM_FEAT_ID (0x8)
#define TZ_DBG_ETM_VER (0x400000)
uint32_t msm_jtag_save_cntr[NR_CPUS];
uint32_t msm_jtag_restore_cntr[NR_CPUS];
/* access debug registers using system instructions */
struct dbg_cpu_ctx {
uint32_t *state;
};
struct dbg_ctx {
uint8_t arch;
bool save_restore_enabled;
uint8_t nr_wp;
uint8_t nr_bp;
uint8_t nr_ctx_cmp;
#ifdef CONFIG_ARM64
uint64_t *state;
#else
uint32_t *state;
#endif
};
static struct dbg_ctx dbg;
#ifdef CONFIG_ARM64
static int dbg_read_arch64_bxr(uint64_t *state, int i, int j)
{
switch (j) {
case 0:
state[i++] = dbg_readq(DBGBVR0_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR0_EL1);
break;
case 1:
state[i++] = dbg_readq(DBGBVR1_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR1_EL1);
break;
case 2:
state[i++] = dbg_readq(DBGBVR2_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR2_EL1);
break;
case 3:
state[i++] = dbg_readq(DBGBVR3_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR3_EL1);
break;
case 4:
state[i++] = dbg_readq(DBGBVR4_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR4_EL1);
break;
case 5:
state[i++] = dbg_readq(DBGBVR5_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR5_EL1);
break;
case 6:
state[i++] = dbg_readq(DBGBVR6_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR6_EL1);
break;
case 7:
state[i++] = dbg_readq(DBGBVR7_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR7_EL1);
break;
case 8:
state[i++] = dbg_readq(DBGBVR8_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR8_EL1);
break;
case 9:
state[i++] = dbg_readq(DBGBVR9_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR9_EL1);
break;
case 10:
state[i++] = dbg_readq(DBGBVR10_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR10_EL1);
break;
case 11:
state[i++] = dbg_readq(DBGBVR11_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR11_EL1);
break;
case 12:
state[i++] = dbg_readq(DBGBVR12_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR12_EL1);
break;
case 13:
state[i++] = dbg_readq(DBGBVR13_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR13_EL1);
break;
case 14:
state[i++] = dbg_readq(DBGBVR14_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR14_EL1);
break;
case 15:
state[i++] = dbg_readq(DBGBVR15_EL1);
state[i++] = (uint64_t)dbg_readl(DBGBCR15_EL1);
break;
default:
pr_err_ratelimited("idx %d out of bounds in %s\n", j, __func__);
}
return i;
}
static int dbg_write_arch64_bxr(uint64_t *state, int i, int j)
{
switch (j) {
case 0:
dbg_write(state[i++], DBGBVR0_EL1);
dbg_write(state[i++], DBGBCR0_EL1);
break;
case 1:
dbg_write(state[i++], DBGBVR1_EL1);
dbg_write(state[i++], DBGBCR1_EL1);
break;
case 2:
dbg_write(state[i++], DBGBVR2_EL1);
dbg_write(state[i++], DBGBCR2_EL1);
break;
case 3:
dbg_write(state[i++], DBGBVR3_EL1);
dbg_write(state[i++], DBGBCR3_EL1);
break;
case 4:
dbg_write(state[i++], DBGBVR4_EL1);
dbg_write(state[i++], DBGBCR4_EL1);
break;
case 5:
dbg_write(state[i++], DBGBVR5_EL1);
dbg_write(state[i++], DBGBCR5_EL1);
break;
case 6:
dbg_write(state[i++], DBGBVR6_EL1);
dbg_write(state[i++], DBGBCR6_EL1);
break;
case 7:
dbg_write(state[i++], DBGBVR7_EL1);
dbg_write(state[i++], DBGBCR7_EL1);
break;
case 8:
dbg_write(state[i++], DBGBVR8_EL1);
dbg_write(state[i++], DBGBCR8_EL1);
break;
case 9:
dbg_write(state[i++], DBGBVR9_EL1);
dbg_write(state[i++], DBGBCR9_EL1);
break;
case 10:
dbg_write(state[i++], DBGBVR10_EL1);
dbg_write(state[i++], DBGBCR10_EL1);
break;
case 11:
dbg_write(state[i++], DBGBVR11_EL1);
dbg_write(state[i++], DBGBCR11_EL1);
break;
case 12:
dbg_write(state[i++], DBGBVR12_EL1);
dbg_write(state[i++], DBGBCR12_EL1);
break;
case 13:
dbg_write(state[i++], DBGBVR13_EL1);
dbg_write(state[i++], DBGBCR13_EL1);
break;
case 14:
dbg_write(state[i++], DBGBVR14_EL1);
dbg_write(state[i++], DBGBCR14_EL1);
break;
case 15:
dbg_write(state[i++], DBGBVR15_EL1);
dbg_write(state[i++], DBGBCR15_EL1);
break;
default:
pr_err_ratelimited("idx %d out of bounds in %s\n", j, __func__);
}
return i;
}
static int dbg_read_arch64_wxr(uint64_t *state, int i, int j)
{
switch (j) {
case 0:
state[i++] = dbg_readq(DBGWVR0_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR0_EL1);
break;
case 1:
state[i++] = dbg_readq(DBGWVR1_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR1_EL1);
break;
case 2:
state[i++] = dbg_readq(DBGWVR2_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR2_EL1);
break;
case 3:
state[i++] = dbg_readq(DBGWVR3_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR3_EL1);
break;
case 4:
state[i++] = dbg_readq(DBGWVR4_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR4_EL1);
break;
case 5:
state[i++] = dbg_readq(DBGWVR5_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR5_EL1);
break;
case 6:
state[i++] = dbg_readq(DBGWVR6_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR6_EL1);
break;
case 7:
state[i++] = dbg_readq(DBGWVR7_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR7_EL1);
break;
case 8:
state[i++] = dbg_readq(DBGWVR8_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR8_EL1);
break;
case 9:
state[i++] = dbg_readq(DBGWVR9_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR9_EL1);
break;
case 10:
state[i++] = dbg_readq(DBGWVR10_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR10_EL1);
break;
case 11:
state[i++] = dbg_readq(DBGWVR11_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR11_EL1);
break;
case 12:
state[i++] = dbg_readq(DBGWVR12_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR12_EL1);
break;
case 13:
state[i++] = dbg_readq(DBGWVR13_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR13_EL1);
break;
case 14:
state[i++] = dbg_readq(DBGWVR14_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR14_EL1);
break;
case 15:
state[i++] = dbg_readq(DBGWVR15_EL1);
state[i++] = (uint64_t)dbg_readl(DBGWCR15_EL1);
break;
default:
pr_err_ratelimited("idx %d out of bounds in %s\n", j, __func__);
}
return i;
}
static int dbg_write_arch64_wxr(uint64_t *state, int i, int j)
{
switch (j) {
case 0:
dbg_write(state[i++], DBGWVR0_EL1);
dbg_write(state[i++], DBGWCR0_EL1);
break;
case 1:
dbg_write(state[i++], DBGWVR1_EL1);
dbg_write(state[i++], DBGWCR1_EL1);
break;
case 2:
dbg_write(state[i++], DBGWVR2_EL1);
dbg_write(state[i++], DBGWCR2_EL1);
break;
case 3:
dbg_write(state[i++], DBGWVR3_EL1);
dbg_write(state[i++], DBGWCR3_EL1);
break;
case 4:
dbg_write(state[i++], DBGWVR4_EL1);
dbg_write(state[i++], DBGWCR4_EL1);
break;
case 5:
dbg_write(state[i++], DBGWVR5_EL1);
dbg_write(state[i++], DBGWCR5_EL1);
break;
case 6:
dbg_write(state[i++], DBGWVR0_EL1);
dbg_write(state[i++], DBGWCR6_EL1);
break;
case 7:
dbg_write(state[i++], DBGWVR7_EL1);
dbg_write(state[i++], DBGWCR7_EL1);
break;
case 8:
dbg_write(state[i++], DBGWVR8_EL1);
dbg_write(state[i++], DBGWCR8_EL1);
break;
case 9:
dbg_write(state[i++], DBGWVR9_EL1);
dbg_write(state[i++], DBGWCR9_EL1);
break;
case 10:
dbg_write(state[i++], DBGWVR10_EL1);
dbg_write(state[i++], DBGWCR10_EL1);
break;
case 11:
dbg_write(state[i++], DBGWVR11_EL1);
dbg_write(state[i++], DBGWCR11_EL1);
break;
case 12:
dbg_write(state[i++], DBGWVR12_EL1);
dbg_write(state[i++], DBGWCR12_EL1);
break;
case 13:
dbg_write(state[i++], DBGWVR13_EL1);
dbg_write(state[i++], DBGWCR13_EL1);
break;
case 14:
dbg_write(state[i++], DBGWVR14_EL1);
dbg_write(state[i++], DBGWCR14_EL1);
break;
case 15:
dbg_write(state[i++], DBGWVR15_EL1);
dbg_write(state[i++], DBGWCR15_EL1);
break;
default:
pr_err_ratelimited("idx %d out of bounds in %s\n", j, __func__);
}
return i;
}
static inline void dbg_save_state(int cpu)
{
int i, j;
i = cpu * MAX_DBG_REGS;
switch (dbg.arch) {
case ARM_DEBUG_ARCH_V8:
/* Set OS Lock to inform the debugger that the OS is in the
* process of saving debug registers. It prevents accidental
* modification of the debug regs by the external debugger.
*/
dbg_write(0x1, OSLAR_EL1);
/* Ensure OS lock is set before proceeding */
isb();
dbg.state[i++] = (uint32_t)dbg_readl(MDSCR_EL1);
for (j = 0; j < dbg.nr_bp; j++)
i = dbg_read_arch64_bxr((uint64_t *)dbg.state, i, j);
for (j = 0; j < dbg.nr_wp; j++)
i = dbg_read_arch64_wxr((uint64_t *)dbg.state, i, j);
dbg.state[i++] = (uint32_t)dbg_readl(MDCCINT_EL1);
dbg.state[i++] = (uint32_t)dbg_readl(DBGCLAIMCLR_EL1);
dbg.state[i++] = (uint32_t)dbg_readl(OSECCR_EL1);
dbg.state[i++] = (uint32_t)dbg_readl(OSDTRRX_EL1);
dbg.state[i++] = (uint32_t)dbg_readl(OSDTRTX_EL1);
/* Set the OS double lock */
isb();
dbg_write(0x1, OSDLR_EL1);
isb();
break;
default:
pr_err_ratelimited("unsupported dbg arch %d in %s\n", dbg.arch,
__func__);
}
}
static inline void dbg_restore_state(int cpu)
{
int i, j;
i = cpu * MAX_DBG_REGS;
switch (dbg.arch) {
case ARM_DEBUG_ARCH_V8:
/* Clear the OS double lock */
isb();
dbg_write(0x0, OSDLR_EL1);
isb();
/* Set OS lock. Lock will already be set after power collapse
* but this write is included to ensure it is set.
*/
dbg_write(0x1, OSLAR_EL1);
isb();
dbg_write(dbg.state[i++], MDSCR_EL1);
for (j = 0; j < dbg.nr_bp; j++)
i = dbg_write_arch64_bxr((uint64_t *)dbg.state, i, j);
for (j = 0; j < dbg.nr_wp; j++)
i = dbg_write_arch64_wxr((uint64_t *)dbg.state, i, j);
dbg_write(dbg.state[i++], MDCCINT_EL1);
dbg_write(dbg.state[i++], DBGCLAIMSET_EL1);
dbg_write(dbg.state[i++], OSECCR_EL1);
dbg_write(dbg.state[i++], OSDTRRX_EL1);
dbg_write(dbg.state[i++], OSDTRTX_EL1);
isb();
dbg_write(0x0, OSLAR_EL1);
isb();
break;
default:
pr_err_ratelimited("unsupported dbg arch %d in %s\n", dbg.arch,
__func__);
}
}
static void dbg_init_arch_data(void)
{
uint64_t dbgfr;
/* This will run on core0 so use it to populate parameters */
dbgfr = dbg_readq(ID_AA64DFR0_EL1);
dbg.arch = BMVAL(dbgfr, 0, 3);
dbg.nr_bp = BMVAL(dbgfr, 12, 15) + 1;
dbg.nr_wp = BMVAL(dbgfr, 20, 23) + 1;
dbg.nr_ctx_cmp = BMVAL(dbgfr, 28, 31) + 1;
}
#else
static int dbg_read_arch32_bxr(uint32_t *state, int i, int j)
{
switch (j) {
case 0:
state[i++] = dbg_read(DBGBVR0);
state[i++] = dbg_read(DBGBCR0);
break;
case 1:
state[i++] = dbg_read(DBGBVR1);
state[i++] = dbg_read(DBGBCR1);
break;
case 2:
state[i++] = dbg_read(DBGBVR2);
state[i++] = dbg_read(DBGBCR2);
break;
case 3:
state[i++] = dbg_read(DBGBVR3);
state[i++] = dbg_read(DBGBCR3);
break;
case 4:
state[i++] = dbg_read(DBGBVR4);
state[i++] = dbg_read(DBGBCR4);
break;
case 5:
state[i++] = dbg_read(DBGBVR5);
state[i++] = dbg_read(DBGBCR5);
break;
case 6:
state[i++] = dbg_read(DBGBVR6);
state[i++] = dbg_read(DBGBCR6);
break;
case 7:
state[i++] = dbg_read(DBGBVR7);
state[i++] = dbg_read(DBGBCR7);
break;
case 8:
state[i++] = dbg_read(DBGBVR8);
state[i++] = dbg_read(DBGBCR8);
break;
case 9:
state[i++] = dbg_read(DBGBVR9);
state[i++] = dbg_read(DBGBCR9);
break;
case 10:
state[i++] = dbg_read(DBGBVR10);
state[i++] = dbg_read(DBGBCR10);
break;
case 11:
state[i++] = dbg_read(DBGBVR11);
state[i++] = dbg_read(DBGBCR11);
break;
case 12:
state[i++] = dbg_read(DBGBVR12);
state[i++] = dbg_read(DBGBCR12);
break;
case 13:
state[i++] = dbg_read(DBGBVR13);
state[i++] = dbg_read(DBGBCR13);
break;
case 14:
state[i++] = dbg_read(DBGBVR14);
state[i++] = dbg_read(DBGBCR14);
break;
case 15:
state[i++] = dbg_read(DBGBVR15);
state[i++] = dbg_read(DBGBCR15);
break;
default:
pr_err_ratelimited("idx %d out of bounds in %s\n", j, __func__);
}
return i;
}
static int dbg_write_arch32_bxr(uint32_t *state, int i, int j)
{
switch (j) {
case 0:
dbg_write(state[i++], DBGBVR0);
dbg_write(state[i++], DBGBCR0);
break;
case 1:
dbg_write(state[i++], DBGBVR1);
dbg_write(state[i++], DBGBCR1);
break;
case 2:
dbg_write(state[i++], DBGBVR2);
dbg_write(state[i++], DBGBCR2);
break;
case 3:
dbg_write(state[i++], DBGBVR3);
dbg_write(state[i++], DBGBCR3);
break;
case 4:
dbg_write(state[i++], DBGBVR4);
dbg_write(state[i++], DBGBCR4);
break;
case 5:
dbg_write(state[i++], DBGBVR5);
dbg_write(state[i++], DBGBCR5);
break;
case 6:
dbg_write(state[i++], DBGBVR6);
dbg_write(state[i++], DBGBCR6);
break;
case 7:
dbg_write(state[i++], DBGBVR7);
dbg_write(state[i++], DBGBCR7);
break;
case 8:
dbg_write(state[i++], DBGBVR8);
dbg_write(state[i++], DBGBCR8);
break;
case 9:
dbg_write(state[i++], DBGBVR9);
dbg_write(state[i++], DBGBCR9);
break;
case 10:
dbg_write(state[i++], DBGBVR10);
dbg_write(state[i++], DBGBCR10);
break;
case 11:
dbg_write(state[i++], DBGBVR11);
dbg_write(state[i++], DBGBCR11);
break;
case 12:
dbg_write(state[i++], DBGBVR12);
dbg_write(state[i++], DBGBCR12);
break;
case 13:
dbg_write(state[i++], DBGBVR13);
dbg_write(state[i++], DBGBCR13);
break;
case 14:
dbg_write(state[i++], DBGBVR14);
dbg_write(state[i++], DBGBCR14);
break;
case 15:
dbg_write(state[i++], DBGBVR15);
dbg_write(state[i++], DBGBCR15);
break;
default:
pr_err_ratelimited("idx %d out of bounds in %s\n", j, __func__);
}
return i;
}
static int dbg_read_arch32_wxr(uint32_t *state, int i, int j)
{
switch (j) {
case 0:
state[i++] = dbg_read(DBGWVR0);
state[i++] = dbg_read(DBGWCR0);
break;
case 1:
state[i++] = dbg_read(DBGWVR1);
state[i++] = dbg_read(DBGWCR1);
break;
case 2:
state[i++] = dbg_read(DBGWVR2);
state[i++] = dbg_read(DBGWCR2);
break;
case 3:
state[i++] = dbg_read(DBGWVR3);
state[i++] = dbg_read(DBGWCR3);
break;
case 4:
state[i++] = dbg_read(DBGWVR4);
state[i++] = dbg_read(DBGWCR4);
break;
case 5:
state[i++] = dbg_read(DBGWVR5);
state[i++] = dbg_read(DBGWCR5);
break;
case 6:
state[i++] = dbg_read(DBGWVR6);
state[i++] = dbg_read(DBGWCR6);
break;
case 7:
state[i++] = dbg_read(DBGWVR7);
state[i++] = dbg_read(DBGWCR7);
break;
case 8:
state[i++] = dbg_read(DBGWVR8);
state[i++] = dbg_read(DBGWCR8);
break;
case 9:
state[i++] = dbg_read(DBGWVR9);
state[i++] = dbg_read(DBGWCR9);
break;
case 10:
state[i++] = dbg_read(DBGWVR10);
state[i++] = dbg_read(DBGWCR10);
break;
case 11:
state[i++] = dbg_read(DBGWVR11);
state[i++] = dbg_read(DBGWCR11);
break;
case 12:
state[i++] = dbg_read(DBGWVR12);
state[i++] = dbg_read(DBGWCR12);
break;
case 13:
state[i++] = dbg_read(DBGWVR13);
state[i++] = dbg_read(DBGWCR13);
break;
case 14:
state[i++] = dbg_read(DBGWVR14);
state[i++] = dbg_read(DBGWCR14);
break;
case 15:
state[i++] = dbg_read(DBGWVR15);
state[i++] = dbg_read(DBGWCR15);
break;
default:
pr_err_ratelimited("idx %d out of bounds in %s\n", j, __func__);
}
return i;
}
static int dbg_write_arch32_wxr(uint32_t *state, int i, int j)
{
switch (j) {
case 0:
dbg_write(state[i++], DBGWVR0);
dbg_write(state[i++], DBGWCR0);
break;
case 1:
dbg_write(state[i++], DBGWVR1);
dbg_write(state[i++], DBGWCR1);
break;
case 2:
dbg_write(state[i++], DBGWVR2);
dbg_write(state[i++], DBGWCR2);
break;
case 3:
dbg_write(state[i++], DBGWVR3);
dbg_write(state[i++], DBGWCR3);
break;
case 4:
dbg_write(state[i++], DBGWVR4);
dbg_write(state[i++], DBGWCR4);
break;
case 5:
dbg_write(state[i++], DBGWVR5);
dbg_write(state[i++], DBGWCR5);
break;
case 6:
dbg_write(state[i++], DBGWVR6);
dbg_write(state[i++], DBGWCR6);
break;
case 7:
dbg_write(state[i++], DBGWVR7);
dbg_write(state[i++], DBGWCR7);
break;
case 8:
dbg_write(state[i++], DBGWVR8);
dbg_write(state[i++], DBGWCR8);
break;
case 9:
dbg_write(state[i++], DBGWVR9);
dbg_write(state[i++], DBGWCR9);
break;
case 10:
dbg_write(state[i++], DBGWVR10);
dbg_write(state[i++], DBGWCR10);
break;
case 11:
dbg_write(state[i++], DBGWVR11);
dbg_write(state[i++], DBGWCR11);
break;
case 12:
dbg_write(state[i++], DBGWVR12);
dbg_write(state[i++], DBGWCR12);
break;
case 13:
dbg_write(state[i++], DBGWVR13);
dbg_write(state[i++], DBGWCR13);
break;
case 14:
dbg_write(state[i++], DBGWVR14);
dbg_write(state[i++], DBGWCR14);
break;
case 15:
dbg_write(state[i++], DBGWVR15);
dbg_write(state[i++], DBGWCR15);
break;
default:
pr_err_ratelimited("idx %d out of bounds in %s\n", j, __func__);
}
return i;
}
static inline void dbg_save_state(int cpu)
{
int i, j;
i = cpu * MAX_DBG_REGS;
switch (dbg.arch) {
case ARM_DEBUG_ARCH_V8:
/* Set OS Lock to inform the debugger that the OS is in the
* process of saving debug registers. It prevents accidental
* modification of the debug regs by the external debugger.
*/
dbg_write(OSLOCK_MAGIC, DBGOSLAR);
/* Ensure OS lock is set before proceeding */
isb();
dbg.state[i++] = dbg_read(DBGDSCRext);
for (j = 0; j < dbg.nr_bp; j++)
i = dbg_read_arch32_bxr(dbg.state, i, j);
for (j = 0; j < dbg.nr_wp; j++)
i = dbg_read_arch32_wxr(dbg.state, i, j);
dbg.state[i++] = dbg_read(DBGDCCINT);
dbg.state[i++] = dbg_read(DBGCLAIMCLR);
dbg.state[i++] = dbg_read(DBGOSECCR);
dbg.state[i++] = dbg_read(DBGDTRRXext);
dbg.state[i++] = dbg_read(DBGDTRTXext);
/* Set the OS double lock */
isb();
dbg_write(0x1, DBGOSDLR);
isb();
break;
default:
pr_err_ratelimited("unsupported dbg arch %d in %s\n", dbg.arch,
__func__);
}
}
static inline void dbg_restore_state(int cpu)
{
int i, j;
i = cpu * MAX_DBG_REGS;
switch (dbg.arch) {
case ARM_DEBUG_ARCH_V8:
/* Clear the OS double lock */
isb();
dbg_write(0x0, DBGOSDLR);
isb();
/* Set OS lock. Lock will already be set after power collapse
* but this write is included to ensure it is set.
*/
dbg_write(OSLOCK_MAGIC, DBGOSLAR);
isb();
dbg_write(dbg.state[i++], DBGDSCRext);
for (j = 0; j < dbg.nr_bp; j++)
i = dbg_write_arch32_bxr((uint32_t *)dbg.state, i, j);
for (j = 0; j < dbg.nr_wp; j++)
i = dbg_write_arch32_wxr((uint32_t *)dbg.state, i, j);
dbg_write(dbg.state[i++], DBGDCCINT);
dbg_write(dbg.state[i++], DBGCLAIMSET);
dbg_write(dbg.state[i++], DBGOSECCR);
dbg_write(dbg.state[i++], DBGDTRRXext);
dbg_write(dbg.state[i++], DBGDTRTXext);
isb();
dbg_write(0x0, DBGOSLAR);
isb();
break;
default:
pr_err_ratelimited("unsupported dbg arch %d in %s\n", dbg.arch,
__func__);
}
}
static void dbg_init_arch_data(void)
{
uint32_t dbgdidr;
/* This will run on core0 so use it to populate parameters */
dbgdidr = dbg_read(DBGDIDR);
dbg.arch = BMVAL(dbgdidr, 16, 19);
dbg.nr_ctx_cmp = BMVAL(dbgdidr, 20, 23) + 1;
dbg.nr_bp = BMVAL(dbgdidr, 24, 27) + 1;
dbg.nr_wp = BMVAL(dbgdidr, 28, 31) + 1;
}
#endif
/*
* msm_jtag_save_state - save debug registers
*
* Debug registers are saved before power collapse if debug
* architecture is supported respectively and TZ isn't supporting
* the save and restore of debug registers.
*
* CONTEXT:
* Called with preemption off and interrupts locked from:
* 1. per_cpu idle thread context for idle power collapses
* or
* 2. per_cpu idle thread context for hotplug/suspend power collapse
* for nonboot cpus
* or
* 3. suspend thread context for suspend power collapse for core0
*
* In all cases we will run on the same cpu for the entire duration.
*/
void msm_jtag_save_state(void)
{
int cpu;
cpu = raw_smp_processor_id();
msm_jtag_save_cntr[cpu]++;
/* ensure counter is updated before moving forward */
mb();
msm_jtag_mm_save_state();
if (dbg.save_restore_enabled)
dbg_save_state(cpu);
}
EXPORT_SYMBOL(msm_jtag_save_state);
void msm_jtag_restore_state(void)
{
int cpu;
cpu = raw_smp_processor_id();
/* Attempt restore only if save has been done. If power collapse
* is disabled, hotplug off of non-boot core will result in WFI
* and hence msm_jtag_save_state will not occur. Subsequently,
* during hotplug on of non-boot core when msm_jtag_restore_state
* is called via msm_platform_secondary_init, this check will help
* bail us out without restoring.
*/
if (msm_jtag_save_cntr[cpu] == msm_jtag_restore_cntr[cpu])
return;
else if (msm_jtag_save_cntr[cpu] != msm_jtag_restore_cntr[cpu] + 1)
pr_err_ratelimited("jtag imbalance, save:%lu, restore:%lu\n",
(unsigned long)msm_jtag_save_cntr[cpu],
(unsigned long)msm_jtag_restore_cntr[cpu]);
msm_jtag_restore_cntr[cpu]++;
/* ensure counter is updated before moving forward */
mb();
if (dbg.save_restore_enabled)
dbg_restore_state(cpu);
msm_jtag_mm_restore_state();
}
EXPORT_SYMBOL(msm_jtag_restore_state);
static inline bool dbg_arch_supported(uint8_t arch)
{
switch (arch) {
case ARM_DEBUG_ARCH_V8:
break;
default:
return false;
}
return true;
}
static int __init msm_jtag_dbg_init(void)
{
int ret;
if (msm_jtag_fuse_apps_access_disabled())
return -EPERM;
/* This will run on core0 so use it to populate parameters */
dbg_init_arch_data();
if (dbg_arch_supported(dbg.arch)) {
if (scm_get_feat_version(TZ_DBG_ETM_FEAT_ID) < TZ_DBG_ETM_VER) {
dbg.save_restore_enabled = true;
} else {
pr_info("dbg save-restore supported by TZ\n");
goto dbg_out;
}
} else {
pr_info("dbg arch %u not supported\n", dbg.arch);
goto dbg_out;
}
/* Allocate dbg state save space */
#ifdef CONFIG_ARM64
dbg.state = kzalloc(MAX_DBG_STATE_SIZE * sizeof(uint64_t), GFP_KERNEL);
#else
dbg.state = kzalloc(MAX_DBG_STATE_SIZE * sizeof(uint32_t), GFP_KERNEL);
#endif
if (!dbg.state) {
ret = -ENOMEM;
goto dbg_err;
}
dbg_out:
return 0;
dbg_err:
return ret;
}
arch_initcall(msm_jtag_dbg_init);
| gpl-2.0 |
andr00ib/3.0.94-victor-kernel | drivers/net/wireless/mwifiex/join.c | 1796 | 45854 | /*
* Marvell Wireless LAN device driver: association and ad-hoc start/join
*
* Copyright (C) 2011, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
#define CAPINFO_MASK (~(BIT(15) | BIT(14) | BIT(12) | BIT(11) | BIT(9)))
/*
* Append a generic IE as a pass through TLV to a TLV buffer.
*
* This function is called from the network join command preparation routine.
*
* If the IE buffer has been setup by the application, this routine appends
* the buffer as a pass through TLV type to the request.
*/
static int
mwifiex_cmd_append_generic_ie(struct mwifiex_private *priv, u8 **buffer)
{
int ret_len = 0;
struct mwifiex_ie_types_header ie_header;
/* Null Checks */
if (!buffer)
return 0;
if (!(*buffer))
return 0;
/*
* If there is a generic ie buffer setup, append it to the return
* parameter buffer pointer.
*/
if (priv->gen_ie_buf_len) {
dev_dbg(priv->adapter->dev, "info: %s: append generic %d to %p\n",
__func__, priv->gen_ie_buf_len, *buffer);
/* Wrap the generic IE buffer with a pass through TLV type */
ie_header.type = cpu_to_le16(TLV_TYPE_PASSTHROUGH);
ie_header.len = cpu_to_le16(priv->gen_ie_buf_len);
memcpy(*buffer, &ie_header, sizeof(ie_header));
/* Increment the return size and the return buffer pointer
param */
*buffer += sizeof(ie_header);
ret_len += sizeof(ie_header);
/* Copy the generic IE buffer to the output buffer, advance
pointer */
memcpy(*buffer, priv->gen_ie_buf, priv->gen_ie_buf_len);
/* Increment the return size and the return buffer pointer
param */
*buffer += priv->gen_ie_buf_len;
ret_len += priv->gen_ie_buf_len;
/* Reset the generic IE buffer */
priv->gen_ie_buf_len = 0;
}
/* return the length appended to the buffer */
return ret_len;
}
/*
* Append TSF tracking info from the scan table for the target AP.
*
* This function is called from the network join command preparation routine.
*
* The TSF table TSF sent to the firmware contains two TSF values:
* - The TSF of the target AP from its previous beacon/probe response
* - The TSF timestamp of our local MAC at the time we observed the
* beacon/probe response.
*
* The firmware uses the timestamp values to set an initial TSF value
* in the MAC for the new association after a reassociation attempt.
*/
static int
mwifiex_cmd_append_tsf_tlv(struct mwifiex_private *priv, u8 **buffer,
struct mwifiex_bssdescriptor *bss_desc)
{
struct mwifiex_ie_types_tsf_timestamp tsf_tlv;
__le64 tsf_val;
/* Null Checks */
if (buffer == NULL)
return 0;
if (*buffer == NULL)
return 0;
memset(&tsf_tlv, 0x00, sizeof(struct mwifiex_ie_types_tsf_timestamp));
tsf_tlv.header.type = cpu_to_le16(TLV_TYPE_TSFTIMESTAMP);
tsf_tlv.header.len = cpu_to_le16(2 * sizeof(tsf_val));
memcpy(*buffer, &tsf_tlv, sizeof(tsf_tlv.header));
*buffer += sizeof(tsf_tlv.header);
/* TSF at the time when beacon/probe_response was received */
tsf_val = cpu_to_le64(bss_desc->network_tsf);
memcpy(*buffer, &tsf_val, sizeof(tsf_val));
*buffer += sizeof(tsf_val);
memcpy(&tsf_val, bss_desc->time_stamp, sizeof(tsf_val));
dev_dbg(priv->adapter->dev, "info: %s: TSF offset calc: %016llx - "
"%016llx\n", __func__, tsf_val, bss_desc->network_tsf);
memcpy(*buffer, &tsf_val, sizeof(tsf_val));
*buffer += sizeof(tsf_val);
return sizeof(tsf_tlv.header) + (2 * sizeof(tsf_val));
}
/*
* This function finds out the common rates between rate1 and rate2.
*
* It will fill common rates in rate1 as output if found.
*
* NOTE: Setting the MSB of the basic rates needs to be taken
* care of, either before or after calling this function.
*/
static int mwifiex_get_common_rates(struct mwifiex_private *priv, u8 *rate1,
u32 rate1_size, u8 *rate2, u32 rate2_size)
{
int ret;
u8 *ptr = rate1, *tmp;
u32 i, j;
tmp = kmalloc(rate1_size, GFP_KERNEL);
if (!tmp) {
dev_err(priv->adapter->dev, "failed to alloc tmp buf\n");
return -ENOMEM;
}
memcpy(tmp, rate1, rate1_size);
memset(rate1, 0, rate1_size);
for (i = 0; rate2[i] && i < rate2_size; i++) {
for (j = 0; tmp[j] && j < rate1_size; j++) {
/* Check common rate, excluding the bit for
basic rate */
if ((rate2[i] & 0x7F) == (tmp[j] & 0x7F)) {
*rate1++ = tmp[j];
break;
}
}
}
dev_dbg(priv->adapter->dev, "info: Tx data rate set to %#x\n",
priv->data_rate);
if (!priv->is_data_rate_auto) {
while (*ptr) {
if ((*ptr & 0x7f) == priv->data_rate) {
ret = 0;
goto done;
}
ptr++;
}
dev_err(priv->adapter->dev, "previously set fixed data rate %#x"
" is not compatible with the network\n",
priv->data_rate);
ret = -1;
goto done;
}
ret = 0;
done:
kfree(tmp);
return ret;
}
/*
* This function creates the intersection of the rates supported by a
* target BSS and our adapter settings for use in an assoc/join command.
*/
static int
mwifiex_setup_rates_from_bssdesc(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc,
u8 *out_rates, u32 *out_rates_size)
{
u8 card_rates[MWIFIEX_SUPPORTED_RATES];
u32 card_rates_size;
/* Copy AP supported rates */
memcpy(out_rates, bss_desc->supported_rates, MWIFIEX_SUPPORTED_RATES);
/* Get the STA supported rates */
card_rates_size = mwifiex_get_active_data_rates(priv, card_rates);
/* Get the common rates between AP and STA supported rates */
if (mwifiex_get_common_rates(priv, out_rates, MWIFIEX_SUPPORTED_RATES,
card_rates, card_rates_size)) {
*out_rates_size = 0;
dev_err(priv->adapter->dev, "%s: cannot get common rates\n",
__func__);
return -1;
}
*out_rates_size =
min_t(size_t, strlen(out_rates), MWIFIEX_SUPPORTED_RATES);
return 0;
}
/*
* This function updates the scan entry TSF timestamps to reflect
* a new association.
*/
static void
mwifiex_update_tsf_timestamps(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *new_bss_desc)
{
struct mwifiex_adapter *adapter = priv->adapter;
u32 table_idx;
long long new_tsf_base;
signed long long tsf_delta;
memcpy(&new_tsf_base, new_bss_desc->time_stamp, sizeof(new_tsf_base));
tsf_delta = new_tsf_base - new_bss_desc->network_tsf;
dev_dbg(adapter->dev, "info: TSF: update TSF timestamps, "
"0x%016llx -> 0x%016llx\n",
new_bss_desc->network_tsf, new_tsf_base);
for (table_idx = 0; table_idx < adapter->num_in_scan_table;
table_idx++)
adapter->scan_table[table_idx].network_tsf += tsf_delta;
}
/*
* This function appends a WAPI IE.
*
* This function is called from the network join command preparation routine.
*
* If the IE buffer has been setup by the application, this routine appends
* the buffer as a WAPI TLV type to the request.
*/
static int
mwifiex_cmd_append_wapi_ie(struct mwifiex_private *priv, u8 **buffer)
{
int retLen = 0;
struct mwifiex_ie_types_header ie_header;
/* Null Checks */
if (buffer == NULL)
return 0;
if (*buffer == NULL)
return 0;
/*
* If there is a wapi ie buffer setup, append it to the return
* parameter buffer pointer.
*/
if (priv->wapi_ie_len) {
dev_dbg(priv->adapter->dev, "cmd: append wapi ie %d to %p\n",
priv->wapi_ie_len, *buffer);
/* Wrap the generic IE buffer with a pass through TLV type */
ie_header.type = cpu_to_le16(TLV_TYPE_WAPI_IE);
ie_header.len = cpu_to_le16(priv->wapi_ie_len);
memcpy(*buffer, &ie_header, sizeof(ie_header));
/* Increment the return size and the return buffer pointer
param */
*buffer += sizeof(ie_header);
retLen += sizeof(ie_header);
/* Copy the wapi IE buffer to the output buffer, advance
pointer */
memcpy(*buffer, priv->wapi_ie, priv->wapi_ie_len);
/* Increment the return size and the return buffer pointer
param */
*buffer += priv->wapi_ie_len;
retLen += priv->wapi_ie_len;
}
/* return the length appended to the buffer */
return retLen;
}
/*
* This function appends rsn ie tlv for wpa/wpa2 security modes.
* It is called from the network join command preparation routine.
*/
static int mwifiex_append_rsn_ie_wpa_wpa2(struct mwifiex_private *priv,
u8 **buffer)
{
struct mwifiex_ie_types_rsn_param_set *rsn_ie_tlv;
int rsn_ie_len;
if (!buffer || !(*buffer))
return 0;
rsn_ie_tlv = (struct mwifiex_ie_types_rsn_param_set *) (*buffer);
rsn_ie_tlv->header.type = cpu_to_le16((u16) priv->wpa_ie[0]);
rsn_ie_tlv->header.type = cpu_to_le16(
le16_to_cpu(rsn_ie_tlv->header.type) & 0x00FF);
rsn_ie_tlv->header.len = cpu_to_le16((u16) priv->wpa_ie[1]);
rsn_ie_tlv->header.len = cpu_to_le16(le16_to_cpu(rsn_ie_tlv->header.len)
& 0x00FF);
if (le16_to_cpu(rsn_ie_tlv->header.len) <= (sizeof(priv->wpa_ie) - 2))
memcpy(rsn_ie_tlv->rsn_ie, &priv->wpa_ie[2],
le16_to_cpu(rsn_ie_tlv->header.len));
else
return -1;
rsn_ie_len = sizeof(rsn_ie_tlv->header) +
le16_to_cpu(rsn_ie_tlv->header.len);
*buffer += rsn_ie_len;
return rsn_ie_len;
}
/*
* This function prepares command for association.
*
* This sets the following parameters -
* - Peer MAC address
* - Listen interval
* - Beacon interval
* - Capability information
*
* ...and the following TLVs, as required -
* - SSID TLV
* - PHY TLV
* - SS TLV
* - Rates TLV
* - Authentication TLV
* - Channel TLV
* - WPA/WPA2 IE
* - 11n TLV
* - Vendor specific TLV
* - WMM TLV
* - WAPI IE
* - Generic IE
* - TSF TLV
*
* Preparation also includes -
* - Setting command ID and proper size
* - Ensuring correct endian-ness
*/
int mwifiex_cmd_802_11_associate(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd,
void *data_buf)
{
struct host_cmd_ds_802_11_associate *assoc = &cmd->params.associate;
struct mwifiex_bssdescriptor *bss_desc;
struct mwifiex_ie_types_ssid_param_set *ssid_tlv;
struct mwifiex_ie_types_phy_param_set *phy_tlv;
struct mwifiex_ie_types_ss_param_set *ss_tlv;
struct mwifiex_ie_types_rates_param_set *rates_tlv;
struct mwifiex_ie_types_auth_type *auth_tlv;
struct mwifiex_ie_types_chan_list_param_set *chan_tlv;
u8 rates[MWIFIEX_SUPPORTED_RATES];
u32 rates_size;
u16 tmp_cap;
u8 *pos;
int rsn_ie_len = 0;
bss_desc = (struct mwifiex_bssdescriptor *) data_buf;
pos = (u8 *) assoc;
mwifiex_cfg_tx_buf(priv, bss_desc);
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_ASSOCIATE);
/* Save so we know which BSS Desc to use in the response handler */
priv->attempted_bss_desc = bss_desc;
memcpy(assoc->peer_sta_addr,
bss_desc->mac_address, sizeof(assoc->peer_sta_addr));
pos += sizeof(assoc->peer_sta_addr);
/* Set the listen interval */
assoc->listen_interval = cpu_to_le16(priv->listen_interval);
/* Set the beacon period */
assoc->beacon_period = cpu_to_le16(bss_desc->beacon_period);
pos += sizeof(assoc->cap_info_bitmap);
pos += sizeof(assoc->listen_interval);
pos += sizeof(assoc->beacon_period);
pos += sizeof(assoc->dtim_period);
ssid_tlv = (struct mwifiex_ie_types_ssid_param_set *) pos;
ssid_tlv->header.type = cpu_to_le16(WLAN_EID_SSID);
ssid_tlv->header.len = cpu_to_le16((u16) bss_desc->ssid.ssid_len);
memcpy(ssid_tlv->ssid, bss_desc->ssid.ssid,
le16_to_cpu(ssid_tlv->header.len));
pos += sizeof(ssid_tlv->header) + le16_to_cpu(ssid_tlv->header.len);
phy_tlv = (struct mwifiex_ie_types_phy_param_set *) pos;
phy_tlv->header.type = cpu_to_le16(WLAN_EID_DS_PARAMS);
phy_tlv->header.len = cpu_to_le16(sizeof(phy_tlv->fh_ds.ds_param_set));
memcpy(&phy_tlv->fh_ds.ds_param_set,
&bss_desc->phy_param_set.ds_param_set.current_chan,
sizeof(phy_tlv->fh_ds.ds_param_set));
pos += sizeof(phy_tlv->header) + le16_to_cpu(phy_tlv->header.len);
ss_tlv = (struct mwifiex_ie_types_ss_param_set *) pos;
ss_tlv->header.type = cpu_to_le16(WLAN_EID_CF_PARAMS);
ss_tlv->header.len = cpu_to_le16(sizeof(ss_tlv->cf_ibss.cf_param_set));
pos += sizeof(ss_tlv->header) + le16_to_cpu(ss_tlv->header.len);
/* Get the common rates supported between the driver and the BSS Desc */
if (mwifiex_setup_rates_from_bssdesc
(priv, bss_desc, rates, &rates_size))
return -1;
/* Save the data rates into Current BSS state structure */
priv->curr_bss_params.num_of_rates = rates_size;
memcpy(&priv->curr_bss_params.data_rates, rates, rates_size);
/* Setup the Rates TLV in the association command */
rates_tlv = (struct mwifiex_ie_types_rates_param_set *) pos;
rates_tlv->header.type = cpu_to_le16(WLAN_EID_SUPP_RATES);
rates_tlv->header.len = cpu_to_le16((u16) rates_size);
memcpy(rates_tlv->rates, rates, rates_size);
pos += sizeof(rates_tlv->header) + rates_size;
dev_dbg(priv->adapter->dev, "info: ASSOC_CMD: rates size = %d\n",
rates_size);
/* Add the Authentication type to be used for Auth frames */
auth_tlv = (struct mwifiex_ie_types_auth_type *) pos;
auth_tlv->header.type = cpu_to_le16(TLV_TYPE_AUTH_TYPE);
auth_tlv->header.len = cpu_to_le16(sizeof(auth_tlv->auth_type));
if (priv->sec_info.wep_status == MWIFIEX_802_11_WEP_ENABLED)
auth_tlv->auth_type = cpu_to_le16(
(u16) priv->sec_info.authentication_mode);
else
auth_tlv->auth_type = cpu_to_le16(NL80211_AUTHTYPE_OPEN_SYSTEM);
pos += sizeof(auth_tlv->header) + le16_to_cpu(auth_tlv->header.len);
if (IS_SUPPORT_MULTI_BANDS(priv->adapter)
&& !(ISSUPP_11NENABLED(priv->adapter->fw_cap_info)
&& (!bss_desc->disable_11n)
&& (priv->adapter->config_bands & BAND_GN
|| priv->adapter->config_bands & BAND_AN)
&& (bss_desc->bcn_ht_cap)
)
) {
/* Append a channel TLV for the channel the attempted AP was
found on */
chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos;
chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
chan_tlv->header.len =
cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set));
memset(chan_tlv->chan_scan_param, 0x00,
sizeof(struct mwifiex_chan_scan_param_set));
chan_tlv->chan_scan_param[0].chan_number =
(bss_desc->phy_param_set.ds_param_set.current_chan);
dev_dbg(priv->adapter->dev, "info: Assoc: TLV Chan = %d\n",
chan_tlv->chan_scan_param[0].chan_number);
chan_tlv->chan_scan_param[0].radio_type =
mwifiex_band_to_radio_type((u8) bss_desc->bss_band);
dev_dbg(priv->adapter->dev, "info: Assoc: TLV Band = %d\n",
chan_tlv->chan_scan_param[0].radio_type);
pos += sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
}
if (!priv->wps.session_enable) {
if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled)
rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos);
if (rsn_ie_len == -1)
return -1;
}
if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info)
&& (!bss_desc->disable_11n)
&& (priv->adapter->config_bands & BAND_GN
|| priv->adapter->config_bands & BAND_AN))
mwifiex_cmd_append_11n_tlv(priv, bss_desc, &pos);
/* Append vendor specific IE TLV */
mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_ASSOC, &pos);
mwifiex_wmm_process_association_req(priv, &pos, &bss_desc->wmm_ie,
bss_desc->bcn_ht_cap);
if (priv->sec_info.wapi_enabled && priv->wapi_ie_len)
mwifiex_cmd_append_wapi_ie(priv, &pos);
mwifiex_cmd_append_generic_ie(priv, &pos);
mwifiex_cmd_append_tsf_tlv(priv, &pos, bss_desc);
cmd->size = cpu_to_le16((u16) (pos - (u8 *) assoc) + S_DS_GEN);
/* Set the Capability info at last */
tmp_cap = bss_desc->cap_info_bitmap;
if (priv->adapter->config_bands == BAND_B)
tmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
tmp_cap &= CAPINFO_MASK;
dev_dbg(priv->adapter->dev, "info: ASSOC_CMD: tmp_cap=%4X CAPINFO_MASK=%4lX\n",
tmp_cap, CAPINFO_MASK);
assoc->cap_info_bitmap = cpu_to_le16(tmp_cap);
return 0;
}
/*
* Association firmware command response handler
*
* The response buffer for the association command has the following
* memory layout.
*
* For cases where an association response was not received (indicated
* by the CapInfo and AId field):
*
* .------------------------------------------------------------.
* | Header(4 * sizeof(t_u16)): Standard command response hdr |
* .------------------------------------------------------------.
* | cap_info/Error Return(t_u16): |
* | 0xFFFF(-1): Internal error |
* | 0xFFFE(-2): Authentication unhandled message |
* | 0xFFFD(-3): Authentication refused |
* | 0xFFFC(-4): Timeout waiting for AP response |
* .------------------------------------------------------------.
* | status_code(t_u16): |
* | If cap_info is -1: |
* | An internal firmware failure prevented the |
* | command from being processed. The status_code |
* | will be set to 1. |
* | |
* | If cap_info is -2: |
* | An authentication frame was received but was |
* | not handled by the firmware. IEEE Status |
* | code for the failure is returned. |
* | |
* | If cap_info is -3: |
* | An authentication frame was received and the |
* | status_code is the IEEE Status reported in the |
* | response. |
* | |
* | If cap_info is -4: |
* | (1) Association response timeout |
* | (2) Authentication response timeout |
* .------------------------------------------------------------.
* | a_id(t_u16): 0xFFFF |
* .------------------------------------------------------------.
*
*
* For cases where an association response was received, the IEEE
* standard association response frame is returned:
*
* .------------------------------------------------------------.
* | Header(4 * sizeof(t_u16)): Standard command response hdr |
* .------------------------------------------------------------.
* | cap_info(t_u16): IEEE Capability |
* .------------------------------------------------------------.
* | status_code(t_u16): IEEE Status Code |
* .------------------------------------------------------------.
* | a_id(t_u16): IEEE Association ID |
* .------------------------------------------------------------.
* | IEEE IEs(variable): Any received IEs comprising the |
* | remaining portion of a received |
* | association response frame. |
* .------------------------------------------------------------.
*
* For simplistic handling, the status_code field can be used to determine
* an association success (0) or failure (non-zero).
*/
int mwifiex_ret_802_11_associate(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct mwifiex_adapter *adapter = priv->adapter;
int ret = 0;
struct ieee_types_assoc_rsp *assoc_rsp;
struct mwifiex_bssdescriptor *bss_desc;
u8 enable_data = true;
assoc_rsp = (struct ieee_types_assoc_rsp *) &resp->params;
priv->assoc_rsp_size = min(le16_to_cpu(resp->size) - S_DS_GEN,
sizeof(priv->assoc_rsp_buf));
memcpy(priv->assoc_rsp_buf, &resp->params, priv->assoc_rsp_size);
if (le16_to_cpu(assoc_rsp->status_code)) {
priv->adapter->dbg.num_cmd_assoc_failure++;
dev_err(priv->adapter->dev, "ASSOC_RESP: association failed, "
"status code = %d, error = 0x%x, a_id = 0x%x\n",
le16_to_cpu(assoc_rsp->status_code),
le16_to_cpu(assoc_rsp->cap_info_bitmap),
le16_to_cpu(assoc_rsp->a_id));
ret = -1;
goto done;
}
/* Send a Media Connected event, according to the Spec */
priv->media_connected = true;
priv->adapter->ps_state = PS_STATE_AWAKE;
priv->adapter->pps_uapsd_mode = false;
priv->adapter->tx_lock_flag = false;
/* Set the attempted BSSID Index to current */
bss_desc = priv->attempted_bss_desc;
dev_dbg(priv->adapter->dev, "info: ASSOC_RESP: %s\n",
bss_desc->ssid.ssid);
/* Make a copy of current BSSID descriptor */
memcpy(&priv->curr_bss_params.bss_descriptor,
bss_desc, sizeof(struct mwifiex_bssdescriptor));
/* Update curr_bss_params */
priv->curr_bss_params.bss_descriptor.channel
= bss_desc->phy_param_set.ds_param_set.current_chan;
priv->curr_bss_params.band = (u8) bss_desc->bss_band;
/*
* Adjust the timestamps in the scan table to be relative to the newly
* associated AP's TSF
*/
mwifiex_update_tsf_timestamps(priv, bss_desc);
if (bss_desc->wmm_ie.vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC)
priv->curr_bss_params.wmm_enabled = true;
else
priv->curr_bss_params.wmm_enabled = false;
if ((priv->wmm_required || bss_desc->bcn_ht_cap)
&& priv->curr_bss_params.wmm_enabled)
priv->wmm_enabled = true;
else
priv->wmm_enabled = false;
priv->curr_bss_params.wmm_uapsd_enabled = false;
if (priv->wmm_enabled)
priv->curr_bss_params.wmm_uapsd_enabled
= ((bss_desc->wmm_ie.qos_info_bitmap &
IEEE80211_WMM_IE_AP_QOSINFO_UAPSD) ? 1 : 0);
dev_dbg(priv->adapter->dev, "info: ASSOC_RESP: curr_pkt_filter is %#x\n",
priv->curr_pkt_filter);
if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled)
priv->wpa_is_gtk_set = false;
if (priv->wmm_enabled) {
/* Don't re-enable carrier until we get the WMM_GET_STATUS
event */
enable_data = false;
} else {
/* Since WMM is not enabled, setup the queues with the
defaults */
mwifiex_wmm_setup_queue_priorities(priv, NULL);
mwifiex_wmm_setup_ac_downgrade(priv);
}
if (enable_data)
dev_dbg(priv->adapter->dev,
"info: post association, re-enabling data flow\n");
/* Reset SNR/NF/RSSI values */
priv->data_rssi_last = 0;
priv->data_nf_last = 0;
priv->data_rssi_avg = 0;
priv->data_nf_avg = 0;
priv->bcn_rssi_last = 0;
priv->bcn_nf_last = 0;
priv->bcn_rssi_avg = 0;
priv->bcn_nf_avg = 0;
priv->rxpd_rate = 0;
priv->rxpd_htinfo = 0;
mwifiex_save_curr_bcn(priv);
priv->adapter->dbg.num_cmd_assoc_success++;
dev_dbg(priv->adapter->dev, "info: ASSOC_RESP: associated\n");
/* Add the ra_list here for infra mode as there will be only 1 ra
always */
mwifiex_ralist_add(priv,
priv->curr_bss_params.bss_descriptor.mac_address);
if (!netif_carrier_ok(priv->netdev))
netif_carrier_on(priv->netdev);
if (netif_queue_stopped(priv->netdev))
netif_wake_queue(priv->netdev);
if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled)
priv->scan_block = true;
done:
/* Need to indicate IOCTL complete */
if (adapter->curr_cmd->wait_q_enabled) {
if (ret)
adapter->cmd_wait_q.status = -1;
else
adapter->cmd_wait_q.status = 0;
}
return ret;
}
/*
* This function prepares command for ad-hoc start.
*
* Driver will fill up SSID, BSS mode, IBSS parameters, physical
* parameters, probe delay, and capability information. Firmware
* will fill up beacon period, basic rates and operational rates.
*
* In addition, the following TLVs are added -
* - Channel TLV
* - Vendor specific IE
* - WPA/WPA2 IE
* - HT Capabilities IE
* - HT Information IE
*
* Preparation also includes -
* - Setting command ID and proper size
* - Ensuring correct endian-ness
*/
int
mwifiex_cmd_802_11_ad_hoc_start(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd, void *data_buf)
{
int rsn_ie_len = 0;
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_ad_hoc_start *adhoc_start =
&cmd->params.adhoc_start;
struct mwifiex_bssdescriptor *bss_desc;
u32 cmd_append_size = 0;
u32 i;
u16 tmp_cap;
uint16_t ht_cap_info;
struct mwifiex_ie_types_chan_list_param_set *chan_tlv;
struct mwifiex_ie_types_htcap *ht_cap;
struct mwifiex_ie_types_htinfo *ht_info;
u8 *pos = (u8 *) adhoc_start +
sizeof(struct host_cmd_ds_802_11_ad_hoc_start);
if (!adapter)
return -1;
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_START);
bss_desc = &priv->curr_bss_params.bss_descriptor;
priv->attempted_bss_desc = bss_desc;
/*
* Fill in the parameters for 2 data structures:
* 1. struct host_cmd_ds_802_11_ad_hoc_start command
* 2. bss_desc
* Driver will fill up SSID, bss_mode,IBSS param, Physical Param,
* probe delay, and Cap info.
* Firmware will fill up beacon period, Basic rates
* and operational rates.
*/
memset(adhoc_start->ssid, 0, IEEE80211_MAX_SSID_LEN);
memcpy(adhoc_start->ssid,
((struct mwifiex_802_11_ssid *) data_buf)->ssid,
((struct mwifiex_802_11_ssid *) data_buf)->ssid_len);
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: SSID = %s\n",
adhoc_start->ssid);
memset(bss_desc->ssid.ssid, 0, IEEE80211_MAX_SSID_LEN);
memcpy(bss_desc->ssid.ssid,
((struct mwifiex_802_11_ssid *) data_buf)->ssid,
((struct mwifiex_802_11_ssid *) data_buf)->ssid_len);
bss_desc->ssid.ssid_len =
((struct mwifiex_802_11_ssid *) data_buf)->ssid_len;
/* Set the BSS mode */
adhoc_start->bss_mode = HostCmd_BSS_MODE_IBSS;
bss_desc->bss_mode = NL80211_IFTYPE_ADHOC;
adhoc_start->beacon_period = cpu_to_le16(priv->beacon_period);
bss_desc->beacon_period = priv->beacon_period;
/* Set Physical param set */
/* Parameter IE Id */
#define DS_PARA_IE_ID 3
/* Parameter IE length */
#define DS_PARA_IE_LEN 1
adhoc_start->phy_param_set.ds_param_set.element_id = DS_PARA_IE_ID;
adhoc_start->phy_param_set.ds_param_set.len = DS_PARA_IE_LEN;
if (!mwifiex_get_cfp_by_band_and_channel_from_cfg80211
(priv, adapter->adhoc_start_band, (u16)
priv->adhoc_channel)) {
struct mwifiex_chan_freq_power *cfp;
cfp = mwifiex_get_cfp_by_band_and_channel_from_cfg80211(priv,
adapter->adhoc_start_band, FIRST_VALID_CHANNEL);
if (cfp)
priv->adhoc_channel = (u8) cfp->channel;
}
if (!priv->adhoc_channel) {
dev_err(adapter->dev, "ADHOC_S_CMD: adhoc_channel cannot be 0\n");
return -1;
}
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: creating ADHOC on channel %d\n",
priv->adhoc_channel);
priv->curr_bss_params.bss_descriptor.channel = priv->adhoc_channel;
priv->curr_bss_params.band = adapter->adhoc_start_band;
bss_desc->channel = priv->adhoc_channel;
adhoc_start->phy_param_set.ds_param_set.current_chan =
priv->adhoc_channel;
memcpy(&bss_desc->phy_param_set, &adhoc_start->phy_param_set,
sizeof(union ieee_types_phy_param_set));
/* Set IBSS param set */
/* IBSS parameter IE Id */
#define IBSS_PARA_IE_ID 6
/* IBSS parameter IE length */
#define IBSS_PARA_IE_LEN 2
adhoc_start->ss_param_set.ibss_param_set.element_id = IBSS_PARA_IE_ID;
adhoc_start->ss_param_set.ibss_param_set.len = IBSS_PARA_IE_LEN;
adhoc_start->ss_param_set.ibss_param_set.atim_window
= cpu_to_le16(priv->atim_window);
memcpy(&bss_desc->ss_param_set, &adhoc_start->ss_param_set,
sizeof(union ieee_types_ss_param_set));
/* Set Capability info */
bss_desc->cap_info_bitmap |= WLAN_CAPABILITY_IBSS;
tmp_cap = le16_to_cpu(adhoc_start->cap_info_bitmap);
tmp_cap &= ~WLAN_CAPABILITY_ESS;
tmp_cap |= WLAN_CAPABILITY_IBSS;
/* Set up privacy in bss_desc */
if (priv->sec_info.encryption_mode) {
/* Ad-Hoc capability privacy on */
dev_dbg(adapter->dev,
"info: ADHOC_S_CMD: wep_status set privacy to WEP\n");
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP;
tmp_cap |= WLAN_CAPABILITY_PRIVACY;
} else {
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: wep_status NOT set,"
" setting privacy to ACCEPT ALL\n");
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL;
}
memset(adhoc_start->DataRate, 0, sizeof(adhoc_start->DataRate));
mwifiex_get_active_data_rates(priv, adhoc_start->DataRate);
if ((adapter->adhoc_start_band & BAND_G) &&
(priv->curr_pkt_filter & HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON)) {
if (mwifiex_send_cmd_async(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET, 0,
&priv->curr_pkt_filter)) {
dev_err(adapter->dev,
"ADHOC_S_CMD: G Protection config failed\n");
return -1;
}
}
/* Find the last non zero */
for (i = 0; i < sizeof(adhoc_start->DataRate) &&
adhoc_start->DataRate[i];
i++)
;
priv->curr_bss_params.num_of_rates = i;
/* Copy the ad-hoc creating rates into Current BSS rate structure */
memcpy(&priv->curr_bss_params.data_rates,
&adhoc_start->DataRate, priv->curr_bss_params.num_of_rates);
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: rates=%02x %02x %02x %02x\n",
adhoc_start->DataRate[0], adhoc_start->DataRate[1],
adhoc_start->DataRate[2], adhoc_start->DataRate[3]);
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: AD-HOC Start command is ready\n");
if (IS_SUPPORT_MULTI_BANDS(adapter)) {
/* Append a channel TLV */
chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos;
chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
chan_tlv->header.len =
cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set));
memset(chan_tlv->chan_scan_param, 0x00,
sizeof(struct mwifiex_chan_scan_param_set));
chan_tlv->chan_scan_param[0].chan_number =
(u8) priv->curr_bss_params.bss_descriptor.channel;
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: TLV Chan = %d\n",
chan_tlv->chan_scan_param[0].chan_number);
chan_tlv->chan_scan_param[0].radio_type
= mwifiex_band_to_radio_type(priv->curr_bss_params.band);
if (adapter->adhoc_start_band & BAND_GN
|| adapter->adhoc_start_band & BAND_AN) {
if (adapter->chan_offset == SEC_CHANNEL_ABOVE)
chan_tlv->chan_scan_param[0].radio_type |=
SECOND_CHANNEL_ABOVE;
else if (adapter->chan_offset == SEC_CHANNEL_BELOW)
chan_tlv->chan_scan_param[0].radio_type |=
SECOND_CHANNEL_BELOW;
}
dev_dbg(adapter->dev, "info: ADHOC_S_CMD: TLV Band = %d\n",
chan_tlv->chan_scan_param[0].radio_type);
pos += sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
cmd_append_size +=
sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
}
/* Append vendor specific IE TLV */
cmd_append_size += mwifiex_cmd_append_vsie_tlv(priv,
MWIFIEX_VSIE_MASK_ADHOC, &pos);
if (priv->sec_info.wpa_enabled) {
rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos);
if (rsn_ie_len == -1)
return -1;
cmd_append_size += rsn_ie_len;
}
if (adapter->adhoc_11n_enabled) {
{
ht_cap = (struct mwifiex_ie_types_htcap *) pos;
memset(ht_cap, 0,
sizeof(struct mwifiex_ie_types_htcap));
ht_cap->header.type =
cpu_to_le16(WLAN_EID_HT_CAPABILITY);
ht_cap->header.len =
cpu_to_le16(sizeof(struct ieee80211_ht_cap));
ht_cap_info = le16_to_cpu(ht_cap->ht_cap.cap_info);
ht_cap_info |= IEEE80211_HT_CAP_SGI_20;
if (adapter->chan_offset) {
ht_cap_info |= IEEE80211_HT_CAP_SGI_40;
ht_cap_info |= IEEE80211_HT_CAP_DSSSCCK40;
ht_cap_info |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
SETHT_MCS32(ht_cap->ht_cap.mcs.rx_mask);
}
ht_cap->ht_cap.ampdu_params_info
= IEEE80211_HT_MAX_AMPDU_64K;
ht_cap->ht_cap.mcs.rx_mask[0] = 0xff;
pos += sizeof(struct mwifiex_ie_types_htcap);
cmd_append_size +=
sizeof(struct mwifiex_ie_types_htcap);
}
{
ht_info = (struct mwifiex_ie_types_htinfo *) pos;
memset(ht_info, 0,
sizeof(struct mwifiex_ie_types_htinfo));
ht_info->header.type =
cpu_to_le16(WLAN_EID_HT_INFORMATION);
ht_info->header.len =
cpu_to_le16(sizeof(struct ieee80211_ht_info));
ht_info->ht_info.control_chan =
(u8) priv->curr_bss_params.bss_descriptor.
channel;
if (adapter->chan_offset) {
ht_info->ht_info.ht_param =
adapter->chan_offset;
ht_info->ht_info.ht_param |=
IEEE80211_HT_PARAM_CHAN_WIDTH_ANY;
}
ht_info->ht_info.operation_mode =
cpu_to_le16(IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT);
ht_info->ht_info.basic_set[0] = 0xff;
pos += sizeof(struct mwifiex_ie_types_htinfo);
cmd_append_size +=
sizeof(struct mwifiex_ie_types_htinfo);
}
}
cmd->size = cpu_to_le16((u16)
(sizeof(struct host_cmd_ds_802_11_ad_hoc_start)
+ S_DS_GEN + cmd_append_size));
if (adapter->adhoc_start_band == BAND_B)
tmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
else
tmp_cap |= WLAN_CAPABILITY_SHORT_SLOT_TIME;
adhoc_start->cap_info_bitmap = cpu_to_le16(tmp_cap);
return 0;
}
/*
* This function prepares command for ad-hoc join.
*
* Most of the parameters are set up by copying from the target BSS descriptor
* from the scan response.
*
* In addition, the following TLVs are added -
* - Channel TLV
* - Vendor specific IE
* - WPA/WPA2 IE
* - 11n IE
*
* Preparation also includes -
* - Setting command ID and proper size
* - Ensuring correct endian-ness
*/
int
mwifiex_cmd_802_11_ad_hoc_join(struct mwifiex_private *priv,
struct host_cmd_ds_command *cmd, void *data_buf)
{
int rsn_ie_len = 0;
struct host_cmd_ds_802_11_ad_hoc_join *adhoc_join =
&cmd->params.adhoc_join;
struct mwifiex_bssdescriptor *bss_desc =
(struct mwifiex_bssdescriptor *) data_buf;
struct mwifiex_ie_types_chan_list_param_set *chan_tlv;
u32 cmd_append_size = 0;
u16 tmp_cap;
u32 i, rates_size = 0;
u16 curr_pkt_filter;
u8 *pos =
(u8 *) adhoc_join +
sizeof(struct host_cmd_ds_802_11_ad_hoc_join);
/* Use G protection */
#define USE_G_PROTECTION 0x02
if (bss_desc->erp_flags & USE_G_PROTECTION) {
curr_pkt_filter =
priv->
curr_pkt_filter | HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON;
if (mwifiex_send_cmd_async(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET, 0,
&curr_pkt_filter)) {
dev_err(priv->adapter->dev,
"ADHOC_J_CMD: G Protection config failed\n");
return -1;
}
}
priv->attempted_bss_desc = bss_desc;
cmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_JOIN);
adhoc_join->bss_descriptor.bss_mode = HostCmd_BSS_MODE_IBSS;
adhoc_join->bss_descriptor.beacon_period
= cpu_to_le16(bss_desc->beacon_period);
memcpy(&adhoc_join->bss_descriptor.bssid,
&bss_desc->mac_address, ETH_ALEN);
memcpy(&adhoc_join->bss_descriptor.ssid,
&bss_desc->ssid.ssid, bss_desc->ssid.ssid_len);
memcpy(&adhoc_join->bss_descriptor.phy_param_set,
&bss_desc->phy_param_set,
sizeof(union ieee_types_phy_param_set));
memcpy(&adhoc_join->bss_descriptor.ss_param_set,
&bss_desc->ss_param_set, sizeof(union ieee_types_ss_param_set));
tmp_cap = bss_desc->cap_info_bitmap;
tmp_cap &= CAPINFO_MASK;
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: tmp_cap=%4X"
" CAPINFO_MASK=%4lX\n", tmp_cap, CAPINFO_MASK);
/* Information on BSSID descriptor passed to FW */
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: BSSID = %pM, SSID = %s\n",
adhoc_join->bss_descriptor.bssid,
adhoc_join->bss_descriptor.ssid);
for (i = 0; bss_desc->supported_rates[i] &&
i < MWIFIEX_SUPPORTED_RATES;
i++)
;
rates_size = i;
/* Copy Data Rates from the Rates recorded in scan response */
memset(adhoc_join->bss_descriptor.data_rates, 0,
sizeof(adhoc_join->bss_descriptor.data_rates));
memcpy(adhoc_join->bss_descriptor.data_rates,
bss_desc->supported_rates, rates_size);
/* Copy the adhoc join rates into Current BSS state structure */
priv->curr_bss_params.num_of_rates = rates_size;
memcpy(&priv->curr_bss_params.data_rates, bss_desc->supported_rates,
rates_size);
/* Copy the channel information */
priv->curr_bss_params.bss_descriptor.channel = bss_desc->channel;
priv->curr_bss_params.band = (u8) bss_desc->bss_band;
if (priv->sec_info.wep_status == MWIFIEX_802_11_WEP_ENABLED
|| priv->sec_info.wpa_enabled)
tmp_cap |= WLAN_CAPABILITY_PRIVACY;
if (IS_SUPPORT_MULTI_BANDS(priv->adapter)) {
/* Append a channel TLV */
chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos;
chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
chan_tlv->header.len =
cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set));
memset(chan_tlv->chan_scan_param, 0x00,
sizeof(struct mwifiex_chan_scan_param_set));
chan_tlv->chan_scan_param[0].chan_number =
(bss_desc->phy_param_set.ds_param_set.current_chan);
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: TLV Chan = %d\n",
chan_tlv->chan_scan_param[0].chan_number);
chan_tlv->chan_scan_param[0].radio_type =
mwifiex_band_to_radio_type((u8) bss_desc->bss_band);
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: TLV Band = %d\n",
chan_tlv->chan_scan_param[0].radio_type);
pos += sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
cmd_append_size += sizeof(chan_tlv->header) +
sizeof(struct mwifiex_chan_scan_param_set);
}
if (priv->sec_info.wpa_enabled)
rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos);
if (rsn_ie_len == -1)
return -1;
cmd_append_size += rsn_ie_len;
if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info))
cmd_append_size += mwifiex_cmd_append_11n_tlv(priv,
bss_desc, &pos);
/* Append vendor specific IE TLV */
cmd_append_size += mwifiex_cmd_append_vsie_tlv(priv,
MWIFIEX_VSIE_MASK_ADHOC, &pos);
cmd->size = cpu_to_le16((u16)
(sizeof(struct host_cmd_ds_802_11_ad_hoc_join)
+ S_DS_GEN + cmd_append_size));
adhoc_join->bss_descriptor.cap_info_bitmap = cpu_to_le16(tmp_cap);
return 0;
}
/*
* This function handles the command response of ad-hoc start and
* ad-hoc join.
*
* The function generates a device-connected event to notify
* the applications, in case of successful ad-hoc start/join, and
* saves the beacon buffer.
*/
int mwifiex_ret_802_11_ad_hoc(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
int ret = 0;
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_ad_hoc_result *adhoc_result;
struct mwifiex_bssdescriptor *bss_desc;
adhoc_result = &resp->params.adhoc_result;
bss_desc = priv->attempted_bss_desc;
/* Join result code 0 --> SUCCESS */
if (le16_to_cpu(resp->result)) {
dev_err(priv->adapter->dev, "ADHOC_RESP: failed\n");
if (priv->media_connected)
mwifiex_reset_connect_state(priv);
memset(&priv->curr_bss_params.bss_descriptor,
0x00, sizeof(struct mwifiex_bssdescriptor));
ret = -1;
goto done;
}
/* Send a Media Connected event, according to the Spec */
priv->media_connected = true;
if (le16_to_cpu(resp->command) == HostCmd_CMD_802_11_AD_HOC_START) {
dev_dbg(priv->adapter->dev, "info: ADHOC_S_RESP %s\n",
bss_desc->ssid.ssid);
/* Update the created network descriptor with the new BSSID */
memcpy(bss_desc->mac_address,
adhoc_result->bssid, ETH_ALEN);
priv->adhoc_state = ADHOC_STARTED;
} else {
/*
* Now the join cmd should be successful.
* If BSSID has changed use SSID to compare instead of BSSID
*/
dev_dbg(priv->adapter->dev, "info: ADHOC_J_RESP %s\n",
bss_desc->ssid.ssid);
/*
* Make a copy of current BSSID descriptor, only needed for
* join since the current descriptor is already being used
* for adhoc start
*/
memcpy(&priv->curr_bss_params.bss_descriptor,
bss_desc, sizeof(struct mwifiex_bssdescriptor));
priv->adhoc_state = ADHOC_JOINED;
}
dev_dbg(priv->adapter->dev, "info: ADHOC_RESP: channel = %d\n",
priv->adhoc_channel);
dev_dbg(priv->adapter->dev, "info: ADHOC_RESP: BSSID = %pM\n",
priv->curr_bss_params.bss_descriptor.mac_address);
if (!netif_carrier_ok(priv->netdev))
netif_carrier_on(priv->netdev);
if (netif_queue_stopped(priv->netdev))
netif_wake_queue(priv->netdev);
mwifiex_save_curr_bcn(priv);
done:
/* Need to indicate IOCTL complete */
if (adapter->curr_cmd->wait_q_enabled) {
if (ret)
adapter->cmd_wait_q.status = -1;
else
adapter->cmd_wait_q.status = 0;
}
return ret;
}
/*
* This function associates to a specific BSS discovered in a scan.
*
* It clears any past association response stored for application
* retrieval and calls the command preparation routine to send the
* command to firmware.
*/
int mwifiex_associate(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
u8 current_bssid[ETH_ALEN];
/* Return error if the adapter or table entry is not marked as infra */
if ((priv->bss_mode != NL80211_IFTYPE_STATION) ||
(bss_desc->bss_mode != NL80211_IFTYPE_STATION))
return -1;
memcpy(¤t_bssid,
&priv->curr_bss_params.bss_descriptor.mac_address,
sizeof(current_bssid));
/* Clear any past association response stored for application
retrieval */
priv->assoc_rsp_size = 0;
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_ASSOCIATE,
HostCmd_ACT_GEN_SET, 0, bss_desc);
}
/*
* This function starts an ad-hoc network.
*
* It calls the command preparation routine to send the command to firmware.
*/
int
mwifiex_adhoc_start(struct mwifiex_private *priv,
struct mwifiex_802_11_ssid *adhoc_ssid)
{
dev_dbg(priv->adapter->dev, "info: Adhoc Channel = %d\n",
priv->adhoc_channel);
dev_dbg(priv->adapter->dev, "info: curr_bss_params.channel = %d\n",
priv->curr_bss_params.bss_descriptor.channel);
dev_dbg(priv->adapter->dev, "info: curr_bss_params.band = %d\n",
priv->curr_bss_params.band);
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_AD_HOC_START,
HostCmd_ACT_GEN_SET, 0, adhoc_ssid);
}
/*
* This function joins an ad-hoc network found in a previous scan.
*
* It calls the command preparation routine to send the command to firmware,
* if already not connected to the requested SSID.
*/
int mwifiex_adhoc_join(struct mwifiex_private *priv,
struct mwifiex_bssdescriptor *bss_desc)
{
dev_dbg(priv->adapter->dev, "info: adhoc join: curr_bss ssid =%s\n",
priv->curr_bss_params.bss_descriptor.ssid.ssid);
dev_dbg(priv->adapter->dev, "info: adhoc join: curr_bss ssid_len =%u\n",
priv->curr_bss_params.bss_descriptor.ssid.ssid_len);
dev_dbg(priv->adapter->dev, "info: adhoc join: ssid =%s\n",
bss_desc->ssid.ssid);
dev_dbg(priv->adapter->dev, "info: adhoc join: ssid_len =%u\n",
bss_desc->ssid.ssid_len);
/* Check if the requested SSID is already joined */
if (priv->curr_bss_params.bss_descriptor.ssid.ssid_len &&
!mwifiex_ssid_cmp(&bss_desc->ssid,
&priv->curr_bss_params.bss_descriptor.ssid) &&
(priv->curr_bss_params.bss_descriptor.bss_mode ==
NL80211_IFTYPE_ADHOC)) {
dev_dbg(priv->adapter->dev, "info: ADHOC_J_CMD: new ad-hoc SSID"
" is the same as current; not attempting to re-join\n");
return -1;
}
dev_dbg(priv->adapter->dev, "info: curr_bss_params.channel = %d\n",
priv->curr_bss_params.bss_descriptor.channel);
dev_dbg(priv->adapter->dev, "info: curr_bss_params.band = %c\n",
priv->curr_bss_params.band);
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_AD_HOC_JOIN,
HostCmd_ACT_GEN_SET, 0, bss_desc);
}
/*
* This function deauthenticates/disconnects from infra network by sending
* deauthentication request.
*/
static int mwifiex_deauthenticate_infra(struct mwifiex_private *priv, u8 *mac)
{
u8 mac_address[ETH_ALEN];
int ret;
u8 zero_mac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };
if (mac) {
if (!memcmp(mac, zero_mac, sizeof(zero_mac)))
memcpy((u8 *) &mac_address,
(u8 *) &priv->curr_bss_params.bss_descriptor.
mac_address, ETH_ALEN);
else
memcpy((u8 *) &mac_address, (u8 *) mac, ETH_ALEN);
} else {
memcpy((u8 *) &mac_address, (u8 *) &priv->curr_bss_params.
bss_descriptor.mac_address, ETH_ALEN);
}
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_DEAUTHENTICATE,
HostCmd_ACT_GEN_SET, 0, &mac_address);
return ret;
}
/*
* This function deauthenticates/disconnects from a BSS.
*
* In case of infra made, it sends deauthentication request, and
* in case of ad-hoc mode, a stop network request is sent to the firmware.
*/
int mwifiex_deauthenticate(struct mwifiex_private *priv, u8 *mac)
{
int ret = 0;
if (priv->media_connected) {
if (priv->bss_mode == NL80211_IFTYPE_STATION) {
ret = mwifiex_deauthenticate_infra(priv, mac);
} else if (priv->bss_mode == NL80211_IFTYPE_ADHOC) {
ret = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_AD_HOC_STOP,
HostCmd_ACT_GEN_SET, 0, NULL);
}
}
return ret;
}
EXPORT_SYMBOL_GPL(mwifiex_deauthenticate);
/*
* This function converts band to radio type used in channel TLV.
*/
u8
mwifiex_band_to_radio_type(u8 band)
{
switch (band) {
case BAND_A:
case BAND_AN:
case BAND_A | BAND_AN:
return HostCmd_SCAN_RADIO_TYPE_A;
case BAND_B:
case BAND_G:
case BAND_B | BAND_G:
default:
return HostCmd_SCAN_RADIO_TYPE_BG;
}
}
| gpl-2.0 |
netico-solutions/linux-am335x-xeno | drivers/staging/comedi/drivers/pcmuio.c | 3076 | 31642 | /*
comedi/drivers/pcmuio.c
Driver for Winsystems PC-104 based 48-channel and 96-channel DIO boards.
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2006 Calin A. Culianu <calin@ajvar.org>
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; either version 2 of the License, or
(at your option) any later version.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: pcmuio
Description: A driver for the PCM-UIO48A and PCM-UIO96A boards from Winsystems.
Devices: [Winsystems] PCM-UIO48A (pcmuio48), PCM-UIO96A (pcmuio96)
Author: Calin Culianu <calin@ajvar.org>
Updated: Fri, 13 Jan 2006 12:01:01 -0500
Status: works
A driver for the relatively straightforward-to-program PCM-UIO48A and
PCM-UIO96A boards from Winsystems. These boards use either one or two
(in the 96-DIO version) WS16C48 ASIC HighDensity I/O Chips (HDIO).
This chip is interesting in that each I/O line is individually
programmable for INPUT or OUTPUT (thus comedi_dio_config can be done
on a per-channel basis). Also, each chip supports edge-triggered
interrupts for the first 24 I/O lines. Of course, since the
96-channel version of the board has two ASICs, it can detect polarity
changes on up to 48 I/O lines. Since this is essentially an (non-PnP)
ISA board, I/O Address and IRQ selection are done through jumpers on
the board. You need to pass that information to this driver as the
first and second comedi_config option, respectively. Note that the
48-channel version uses 16 bytes of IO memory and the 96-channel
version uses 32-bytes (in case you are worried about conflicts). The
48-channel board is split into two 24-channel comedi subdevices.
The 96-channel board is split into 4 24-channel DIO subdevices.
Note that IRQ support has been added, but it is untested.
To use edge-detection IRQ support, pass the IRQs of both ASICS
(for the 96 channel version) or just 1 ASIC (for 48-channel version).
Then, use use comedi_commands with TRIG_NOW.
Your callback will be called each time an edge is triggered, and the data
values will be two sample_t's, which should be concatenated to form one
32-bit unsigned int. This value is the mask of channels that had
edges detected from your channel list. Note that the bits positions
in the mask correspond to positions in your chanlist when you specified
the command and *not* channel id's!
To set the polarity of the edge-detection interrupts pass a nonzero value for
either CR_RANGE or CR_AREF for edge-up polarity, or a zero value for both
CR_RANGE and CR_AREF if you want edge-down polarity.
In the 48-channel version:
On subdev 0, the first 24 channels channels are edge-detect channels.
In the 96-channel board you have the collowing channels that can do edge detection:
subdev 0, channels 0-24 (first 24 channels of 1st ASIC)
subdev 2, channels 0-24 (first 24 channels of 2nd ASIC)
Configuration Options:
[0] - I/O port base address
[1] - IRQ (for first ASIC, or first 24 channels)
[2] - IRQ for second ASIC (pcmuio96 only - IRQ for chans 48-72 .. can be the same as first irq!)
*/
#include <linux/interrupt.h>
#include <linux/slab.h>
#include "../comedidev.h"
#include "pcm_common.h"
#include <linux/pci.h> /* for PCI devices */
#define CHANS_PER_PORT 8
#define PORTS_PER_ASIC 6
#define INTR_PORTS_PER_ASIC 3
#define MAX_CHANS_PER_SUBDEV 24 /* number of channels per comedi subdevice */
#define PORTS_PER_SUBDEV (MAX_CHANS_PER_SUBDEV/CHANS_PER_PORT)
#define CHANS_PER_ASIC (CHANS_PER_PORT*PORTS_PER_ASIC)
#define INTR_CHANS_PER_ASIC 24
#define INTR_PORTS_PER_SUBDEV (INTR_CHANS_PER_ASIC/CHANS_PER_PORT)
#define MAX_DIO_CHANS (PORTS_PER_ASIC*2*CHANS_PER_PORT)
#define MAX_ASICS (MAX_DIO_CHANS/CHANS_PER_ASIC)
#define SDEV_NO ((int)(s - dev->subdevices))
#define CALC_N_SUBDEVS(nchans) ((nchans)/MAX_CHANS_PER_SUBDEV + (!!((nchans)%MAX_CHANS_PER_SUBDEV)) /*+ (nchans > INTR_CHANS_PER_ASIC ? 2 : 1)*/)
/* IO Memory sizes */
#define ASIC_IOSIZE (0x10)
#define PCMUIO48_IOSIZE ASIC_IOSIZE
#define PCMUIO96_IOSIZE (ASIC_IOSIZE*2)
/* Some offsets - these are all in the 16byte IO memory offset from
the base address. Note that there is a paging scheme to swap out
offsets 0x8-0xA using the PAGELOCK register. See the table below.
Register(s) Pages R/W? Description
--------------------------------------------------------------
REG_PORTx All R/W Read/Write/Configure IO
REG_INT_PENDING All ReadOnly Quickly see which INT_IDx has int.
REG_PAGELOCK All WriteOnly Select a page
REG_POLx Pg. 1 only WriteOnly Select edge-detection polarity
REG_ENABx Pg. 2 only WriteOnly Enable/Disable edge-detect. int.
REG_INT_IDx Pg. 3 only R/W See which ports/bits have ints.
*/
#define REG_PORT0 0x0
#define REG_PORT1 0x1
#define REG_PORT2 0x2
#define REG_PORT3 0x3
#define REG_PORT4 0x4
#define REG_PORT5 0x5
#define REG_INT_PENDING 0x6
#define REG_PAGELOCK 0x7 /* page selector register, upper 2 bits select a page
and bits 0-5 are used to 'lock down' a particular
port above to make it readonly. */
#define REG_POL0 0x8
#define REG_POL1 0x9
#define REG_POL2 0xA
#define REG_ENAB0 0x8
#define REG_ENAB1 0x9
#define REG_ENAB2 0xA
#define REG_INT_ID0 0x8
#define REG_INT_ID1 0x9
#define REG_INT_ID2 0xA
#define NUM_PAGED_REGS 3
#define NUM_PAGES 4
#define FIRST_PAGED_REG 0x8
#define REG_PAGE_BITOFFSET 6
#define REG_LOCK_BITOFFSET 0
#define REG_PAGE_MASK (~((0x1<<REG_PAGE_BITOFFSET)-1))
#define REG_LOCK_MASK ~(REG_PAGE_MASK)
#define PAGE_POL 1
#define PAGE_ENAB 2
#define PAGE_INT_ID 3
/*
* Board descriptions for two imaginary boards. Describing the
* boards in this way is optional, and completely driver-dependent.
* Some drivers use arrays such as this, other do not.
*/
struct pcmuio_board {
const char *name;
const int num_asics;
const int num_channels_per_port;
const int num_ports;
};
static const struct pcmuio_board pcmuio_boards[] = {
{
.name = "pcmuio48",
.num_asics = 1,
.num_ports = 6,
},
{
.name = "pcmuio96",
.num_asics = 2,
.num_ports = 12,
},
};
/*
* Useful for shorthand access to the particular board structure
*/
#define thisboard ((const struct pcmuio_board *)dev->board_ptr)
/* this structure is for data unique to this subdevice. */
struct pcmuio_subdev_private {
/* mapping of halfwords (bytes) in port/chanarray to iobase */
unsigned long iobases[PORTS_PER_SUBDEV];
/* The below is only used for intr subdevices */
struct {
int asic; /* if non-negative, this subdev has an interrupt asic */
int first_chan; /* if nonnegative, the first channel id for
interrupts. */
int num_asic_chans; /* the number of asic channels in this subdev
that have interrutps */
int asic_chan; /* if nonnegative, the first channel id with
respect to the asic that has interrupts */
int enabled_mask; /* subdev-relative channel mask for channels
we are interested in */
int active;
int stop_count;
int continuous;
spinlock_t spinlock;
} intr;
};
/* this structure is for data unique to this hardware driver. If
several hardware drivers keep similar information in this structure,
feel free to suggest moving the variable to the struct comedi_device struct. */
struct pcmuio_private {
struct {
unsigned char pagelock; /* current page and lock */
unsigned char pol[NUM_PAGED_REGS]; /* shadow of POLx registers */
unsigned char enab[NUM_PAGED_REGS]; /* shadow of ENABx registers */
int num;
unsigned long iobase;
unsigned int irq;
spinlock_t spinlock;
} asics[MAX_ASICS];
struct pcmuio_subdev_private *sprivs;
};
/*
* most drivers define the following macro to make it easy to
* access the private structure.
*/
#define devpriv ((struct pcmuio_private *)dev->private)
#define subpriv ((struct pcmuio_subdev_private *)s->private)
/*
* The struct comedi_driver structure tells the Comedi core module
* which functions to call to configure/deconfigure (attach/detach)
* the board, and also about the kernel module that contains
* the device code.
*/
static int pcmuio_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int pcmuio_detach(struct comedi_device *dev);
static struct comedi_driver driver = {
.driver_name = "pcmuio",
.module = THIS_MODULE,
.attach = pcmuio_attach,
.detach = pcmuio_detach,
/* It is not necessary to implement the following members if you are
* writing a driver for a ISA PnP or PCI card */
/* Most drivers will support multiple types of boards by
* having an array of board structures. These were defined
* in pcmuio_boards[] above. Note that the element 'name'
* was first in the structure -- Comedi uses this fact to
* extract the name of the board without knowing any details
* about the structure except for its length.
* When a device is attached (by comedi_config), the name
* of the device is given to Comedi, and Comedi tries to
* match it by going through the list of board names. If
* there is a match, the address of the pointer is put
* into dev->board_ptr and driver->attach() is called.
*
* Note that these are not necessary if you can determine
* the type of board in software. ISA PnP, PCI, and PCMCIA
* devices are such boards.
*/
.board_name = &pcmuio_boards[0].name,
.offset = sizeof(struct pcmuio_board),
.num_names = ARRAY_SIZE(pcmuio_boards),
};
static int pcmuio_dio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int pcmuio_dio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static irqreturn_t interrupt_pcmuio(int irq, void *d);
static void pcmuio_stop_intr(struct comedi_device *, struct comedi_subdevice *);
static int pcmuio_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
static int pcmuio_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
static int pcmuio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_cmd *cmd);
/* some helper functions to deal with specifics of this device's registers */
static void init_asics(struct comedi_device *dev); /* sets up/clears ASIC chips to defaults */
static void switch_page(struct comedi_device *dev, int asic, int page);
#ifdef notused
static void lock_port(struct comedi_device *dev, int asic, int port);
static void unlock_port(struct comedi_device *dev, int asic, int port);
#endif
/*
* Attach is called by the Comedi core to configure the driver
* for a particular board. If you specified a board_name array
* in the driver structure, dev->board_ptr contains that
* address.
*/
static int pcmuio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
int sdev_no, chans_left, n_subdevs, port, asic, thisasic_chanct = 0;
unsigned long iobase;
unsigned int irq[MAX_ASICS];
iobase = it->options[0];
irq[0] = it->options[1];
irq[1] = it->options[2];
printk("comedi%d: %s: io: %lx ", dev->minor, driver.driver_name,
iobase);
dev->iobase = iobase;
if (!iobase || !request_region(iobase,
thisboard->num_asics * ASIC_IOSIZE,
driver.driver_name)) {
printk("I/O port conflict\n");
return -EIO;
}
/*
* Initialize dev->board_name. Note that we can use the "thisboard"
* macro now, since we just initialized it in the last line.
*/
dev->board_name = thisboard->name;
/*
* Allocate the private structure area. alloc_private() is a
* convenient macro defined in comedidev.h.
*/
if (alloc_private(dev, sizeof(struct pcmuio_private)) < 0) {
printk("cannot allocate private data structure\n");
return -ENOMEM;
}
for (asic = 0; asic < MAX_ASICS; ++asic) {
devpriv->asics[asic].num = asic;
devpriv->asics[asic].iobase = dev->iobase + asic * ASIC_IOSIZE;
devpriv->asics[asic].irq = 0; /* this gets actually set at the end of
this function when we
request_irqs */
spin_lock_init(&devpriv->asics[asic].spinlock);
}
chans_left = CHANS_PER_ASIC * thisboard->num_asics;
n_subdevs = CALC_N_SUBDEVS(chans_left);
devpriv->sprivs =
kcalloc(n_subdevs, sizeof(struct pcmuio_subdev_private),
GFP_KERNEL);
if (!devpriv->sprivs) {
printk("cannot allocate subdevice private data structures\n");
return -ENOMEM;
}
/*
* Allocate the subdevice structures. alloc_subdevice() is a
* convenient macro defined in comedidev.h.
*
* Allocate 2 subdevs (32 + 16 DIO lines) or 3 32 DIO subdevs for the
* 96-channel version of the board.
*/
if (alloc_subdevices(dev, n_subdevs) < 0) {
printk("cannot allocate subdevice data structures\n");
return -ENOMEM;
}
port = 0;
asic = 0;
for (sdev_no = 0; sdev_no < (int)dev->n_subdevices; ++sdev_no) {
int byte_no;
s = dev->subdevices + sdev_no;
s->private = devpriv->sprivs + sdev_no;
s->maxdata = 1;
s->range_table = &range_digital;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
s->type = COMEDI_SUBD_DIO;
s->insn_bits = pcmuio_dio_insn_bits;
s->insn_config = pcmuio_dio_insn_config;
s->n_chan = min(chans_left, MAX_CHANS_PER_SUBDEV);
subpriv->intr.asic = -1;
subpriv->intr.first_chan = -1;
subpriv->intr.asic_chan = -1;
subpriv->intr.num_asic_chans = -1;
subpriv->intr.active = 0;
s->len_chanlist = 1;
/* save the ioport address for each 'port' of 8 channels in the
subdevice */
for (byte_no = 0; byte_no < PORTS_PER_SUBDEV; ++byte_no, ++port) {
if (port >= PORTS_PER_ASIC) {
port = 0;
++asic;
thisasic_chanct = 0;
}
subpriv->iobases[byte_no] =
devpriv->asics[asic].iobase + port;
if (thisasic_chanct <
CHANS_PER_PORT * INTR_PORTS_PER_ASIC
&& subpriv->intr.asic < 0) {
/* this is an interrupt subdevice, so setup the struct */
subpriv->intr.asic = asic;
subpriv->intr.active = 0;
subpriv->intr.stop_count = 0;
subpriv->intr.first_chan = byte_no * 8;
subpriv->intr.asic_chan = thisasic_chanct;
subpriv->intr.num_asic_chans =
s->n_chan - subpriv->intr.first_chan;
dev->read_subdev = s;
s->subdev_flags |= SDF_CMD_READ;
s->cancel = pcmuio_cancel;
s->do_cmd = pcmuio_cmd;
s->do_cmdtest = pcmuio_cmdtest;
s->len_chanlist = subpriv->intr.num_asic_chans;
}
thisasic_chanct += CHANS_PER_PORT;
}
spin_lock_init(&subpriv->intr.spinlock);
chans_left -= s->n_chan;
if (!chans_left) {
asic = 0; /* reset the asic to our first asic, to do intr subdevs */
port = 0;
}
}
init_asics(dev); /* clear out all the registers, basically */
for (asic = 0; irq[0] && asic < MAX_ASICS; ++asic) {
if (irq[asic]
&& request_irq(irq[asic], interrupt_pcmuio,
IRQF_SHARED, thisboard->name, dev)) {
int i;
/* unroll the allocated irqs.. */
for (i = asic - 1; i >= 0; --i) {
free_irq(irq[i], dev);
devpriv->asics[i].irq = irq[i] = 0;
}
irq[asic] = 0;
}
devpriv->asics[asic].irq = irq[asic];
}
dev->irq = irq[0]; /* grr.. wish comedi dev struct supported multiple
irqs.. */
if (irq[0]) {
printk("irq: %u ", irq[0]);
if (irq[1] && thisboard->num_asics == 2)
printk("second ASIC irq: %u ", irq[1]);
} else {
printk("(IRQ mode disabled) ");
}
printk("attached\n");
return 1;
}
/*
* _detach is called to deconfigure a device. It should deallocate
* resources.
* This function is also called when _attach() fails, so it should be
* careful not to release resources that were not necessarily
* allocated by _attach(). dev->private and dev->subdevices are
* deallocated automatically by the core.
*/
static int pcmuio_detach(struct comedi_device *dev)
{
int i;
printk("comedi%d: %s: remove\n", dev->minor, driver.driver_name);
if (dev->iobase)
release_region(dev->iobase, ASIC_IOSIZE * thisboard->num_asics);
for (i = 0; i < MAX_ASICS; ++i) {
if (devpriv->asics[i].irq)
free_irq(devpriv->asics[i].irq, dev);
}
if (devpriv && devpriv->sprivs)
kfree(devpriv->sprivs);
return 0;
}
/* DIO devices are slightly special. Although it is possible to
* implement the insn_read/insn_write interface, it is much more
* useful to applications if you implement the insn_bits interface.
* This allows packed reading/writing of the DIO channels. The
* comedi core can convert between insn_bits and insn_read/write */
static int pcmuio_dio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int byte_no;
if (insn->n != 2)
return -EINVAL;
/* NOTE:
reading a 0 means this channel was high
writine a 0 sets the channel high
reading a 1 means this channel was low
writing a 1 means set this channel low
Therefore everything is always inverted. */
/* The insn data is a mask in data[0] and the new data
* in data[1], each channel cooresponding to a bit. */
#ifdef DAMMIT_ITS_BROKEN
/* DEBUG */
printk("write mask: %08x data: %08x\n", data[0], data[1]);
#endif
s->state = 0;
for (byte_no = 0; byte_no < s->n_chan / CHANS_PER_PORT; ++byte_no) {
/* address of 8-bit port */
unsigned long ioaddr = subpriv->iobases[byte_no],
/* bit offset of port in 32-bit doubleword */
offset = byte_no * 8;
/* this 8-bit port's data */
unsigned char byte = 0,
/* The write mask for this port (if any) */
write_mask_byte = (data[0] >> offset) & 0xff,
/* The data byte for this port */
data_byte = (data[1] >> offset) & 0xff;
byte = inb(ioaddr); /* read all 8-bits for this port */
#ifdef DAMMIT_ITS_BROKEN
/* DEBUG */
printk
("byte %d wmb %02x db %02x offset %02d io %04x, data_in %02x ",
byte_no, (unsigned)write_mask_byte, (unsigned)data_byte,
offset, ioaddr, (unsigned)byte);
#endif
if (write_mask_byte) {
/* this byte has some write_bits -- so set the output lines */
byte &= ~write_mask_byte; /* clear bits for write mask */
byte |= ~data_byte & write_mask_byte; /* set to inverted data_byte */
/* Write out the new digital output state */
outb(byte, ioaddr);
}
#ifdef DAMMIT_ITS_BROKEN
/* DEBUG */
printk("data_out_byte %02x\n", (unsigned)byte);
#endif
/* save the digital input lines for this byte.. */
s->state |= ((unsigned int)byte) << offset;
}
/* now return the DIO lines to data[1] - note they came inverted! */
data[1] = ~s->state;
#ifdef DAMMIT_ITS_BROKEN
/* DEBUG */
printk("s->state %08x data_out %08x\n", s->state, data[1]);
#endif
return 2;
}
/* The input or output configuration of each digital line is
* configured by a special insn_config instruction. chanspec
* contains the channel to be changed, and data[0] contains the
* value COMEDI_INPUT or COMEDI_OUTPUT. */
static int pcmuio_dio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int chan = CR_CHAN(insn->chanspec), byte_no = chan / 8, bit_no =
chan % 8;
unsigned long ioaddr;
unsigned char byte;
/* Compute ioaddr for this channel */
ioaddr = subpriv->iobases[byte_no];
/* NOTE:
writing a 0 an IO channel's bit sets the channel to INPUT
and pulls the line high as well
writing a 1 to an IO channel's bit pulls the line low
All channels are implicitly always in OUTPUT mode -- but when
they are high they can be considered to be in INPUT mode..
Thus, we only force channels low if the config request was INPUT,
otherwise we do nothing to the hardware. */
switch (data[0]) {
case INSN_CONFIG_DIO_OUTPUT:
/* save to io_bits -- don't actually do anything since
all input channels are also output channels... */
s->io_bits |= 1 << chan;
break;
case INSN_CONFIG_DIO_INPUT:
/* write a 0 to the actual register representing the channel
to set it to 'input'. 0 means "float high". */
byte = inb(ioaddr);
byte &= ~(1 << bit_no);
/**< set input channel to '0' */
/* write out byte -- this is the only time we actually affect the
hardware as all channels are implicitly output -- but input
channels are set to float-high */
outb(byte, ioaddr);
/* save to io_bits */
s->io_bits &= ~(1 << chan);
break;
case INSN_CONFIG_DIO_QUERY:
/* retrieve from shadow register */
data[1] =
(s->io_bits & (1 << chan)) ? COMEDI_OUTPUT : COMEDI_INPUT;
return insn->n;
break;
default:
return -EINVAL;
break;
}
return insn->n;
}
static void init_asics(struct comedi_device *dev)
{ /* sets up an
ASIC chip to defaults */
int asic;
for (asic = 0; asic < thisboard->num_asics; ++asic) {
int port, page;
unsigned long baseaddr = dev->iobase + asic * ASIC_IOSIZE;
switch_page(dev, asic, 0); /* switch back to page 0 */
/* first, clear all the DIO port bits */
for (port = 0; port < PORTS_PER_ASIC; ++port)
outb(0, baseaddr + REG_PORT0 + port);
/* Next, clear all the paged registers for each page */
for (page = 1; page < NUM_PAGES; ++page) {
int reg;
/* now clear all the paged registers */
switch_page(dev, asic, page);
for (reg = FIRST_PAGED_REG;
reg < FIRST_PAGED_REG + NUM_PAGED_REGS; ++reg)
outb(0, baseaddr + reg);
}
/* DEBUG set rising edge interrupts on port0 of both asics */
/*switch_page(dev, asic, PAGE_POL);
outb(0xff, baseaddr + REG_POL0);
switch_page(dev, asic, PAGE_ENAB);
outb(0xff, baseaddr + REG_ENAB0); */
/* END DEBUG */
switch_page(dev, asic, 0); /* switch back to default page 0 */
}
}
static void switch_page(struct comedi_device *dev, int asic, int page)
{
if (asic < 0 || asic >= thisboard->num_asics)
return; /* paranoia */
if (page < 0 || page >= NUM_PAGES)
return; /* more paranoia */
devpriv->asics[asic].pagelock &= ~REG_PAGE_MASK;
devpriv->asics[asic].pagelock |= page << REG_PAGE_BITOFFSET;
/* now write out the shadow register */
outb(devpriv->asics[asic].pagelock,
dev->iobase + ASIC_IOSIZE * asic + REG_PAGELOCK);
}
#ifdef notused
static void lock_port(struct comedi_device *dev, int asic, int port)
{
if (asic < 0 || asic >= thisboard->num_asics)
return; /* paranoia */
if (port < 0 || port >= PORTS_PER_ASIC)
return; /* more paranoia */
devpriv->asics[asic].pagelock |= 0x1 << port;
/* now write out the shadow register */
outb(devpriv->asics[asic].pagelock,
dev->iobase + ASIC_IOSIZE * asic + REG_PAGELOCK);
}
static void unlock_port(struct comedi_device *dev, int asic, int port)
{
if (asic < 0 || asic >= thisboard->num_asics)
return; /* paranoia */
if (port < 0 || port >= PORTS_PER_ASIC)
return; /* more paranoia */
devpriv->asics[asic].pagelock &= ~(0x1 << port) | REG_LOCK_MASK;
/* now write out the shadow register */
outb(devpriv->asics[asic].pagelock,
dev->iobase + ASIC_IOSIZE * asic + REG_PAGELOCK);
}
#endif /* notused */
static irqreturn_t interrupt_pcmuio(int irq, void *d)
{
int asic, got1 = 0;
struct comedi_device *dev = (struct comedi_device *)d;
for (asic = 0; asic < MAX_ASICS; ++asic) {
if (irq == devpriv->asics[asic].irq) {
unsigned long flags;
unsigned triggered = 0;
unsigned long iobase = devpriv->asics[asic].iobase;
/* it is an interrupt for ASIC #asic */
unsigned char int_pend;
spin_lock_irqsave(&devpriv->asics[asic].spinlock,
flags);
int_pend = inb(iobase + REG_INT_PENDING) & 0x07;
if (int_pend) {
int port;
for (port = 0; port < INTR_PORTS_PER_ASIC;
++port) {
if (int_pend & (0x1 << port)) {
unsigned char
io_lines_with_edges = 0;
switch_page(dev, asic,
PAGE_INT_ID);
io_lines_with_edges =
inb(iobase +
REG_INT_ID0 + port);
if (io_lines_with_edges)
/* clear pending interrupt */
outb(0, iobase +
REG_INT_ID0 +
port);
triggered |=
io_lines_with_edges <<
port * 8;
}
}
++got1;
}
spin_unlock_irqrestore(&devpriv->asics[asic].spinlock,
flags);
if (triggered) {
struct comedi_subdevice *s;
/* TODO here: dispatch io lines to subdevs with commands.. */
printk
("PCMUIO DEBUG: got edge detect interrupt %d asic %d which_chans: %06x\n",
irq, asic, triggered);
for (s = dev->subdevices;
s < dev->subdevices + dev->n_subdevices;
++s) {
if (subpriv->intr.asic == asic) { /* this is an interrupt subdev, and it matches this asic! */
unsigned long flags;
unsigned oldevents;
spin_lock_irqsave(&subpriv->
intr.spinlock,
flags);
oldevents = s->async->events;
if (subpriv->intr.active) {
unsigned mytrig =
((triggered >>
subpriv->intr.asic_chan)
&
((0x1 << subpriv->
intr.
num_asic_chans) -
1)) << subpriv->
intr.first_chan;
if (mytrig &
subpriv->intr.enabled_mask)
{
unsigned int val
= 0;
unsigned int n,
ch, len;
len =
s->
async->cmd.chanlist_len;
for (n = 0;
n < len;
n++) {
ch = CR_CHAN(s->async->cmd.chanlist[n]);
if (mytrig & (1U << ch)) {
val |= (1U << n);
}
}
/* Write the scan to the buffer. */
if (comedi_buf_put(s->async, ((short *)&val)[0])
&&
comedi_buf_put
(s->async,
((short *)
&val)[1]))
{
s->async->events |= (COMEDI_CB_BLOCK | COMEDI_CB_EOS);
} else {
/* Overflow! Stop acquisition!! */
/* TODO: STOP_ACQUISITION_CALL_HERE!! */
pcmuio_stop_intr
(dev,
s);
}
/* Check for end of acquisition. */
if (!subpriv->intr.continuous) {
/* stop_src == TRIG_COUNT */
if (subpriv->intr.stop_count > 0) {
subpriv->intr.stop_count--;
if (subpriv->intr.stop_count == 0) {
s->async->events |= COMEDI_CB_EOA;
/* TODO: STOP_ACQUISITION_CALL_HERE!! */
pcmuio_stop_intr
(dev,
s);
}
}
}
}
}
spin_unlock_irqrestore
(&subpriv->intr.spinlock,
flags);
if (oldevents !=
s->async->events) {
comedi_event(dev, s);
}
}
}
}
}
}
if (!got1)
return IRQ_NONE; /* interrupt from other source */
return IRQ_HANDLED;
}
static void pcmuio_stop_intr(struct comedi_device *dev,
struct comedi_subdevice *s)
{
int nports, firstport, asic, port;
asic = subpriv->intr.asic;
if (asic < 0)
return; /* not an interrupt subdev */
subpriv->intr.enabled_mask = 0;
subpriv->intr.active = 0;
s->async->inttrig = 0;
nports = subpriv->intr.num_asic_chans / CHANS_PER_PORT;
firstport = subpriv->intr.asic_chan / CHANS_PER_PORT;
switch_page(dev, asic, PAGE_ENAB);
for (port = firstport; port < firstport + nports; ++port) {
/* disable all intrs for this subdev.. */
outb(0, devpriv->asics[asic].iobase + REG_ENAB0 + port);
}
}
static int pcmuio_start_intr(struct comedi_device *dev,
struct comedi_subdevice *s)
{
if (!subpriv->intr.continuous && subpriv->intr.stop_count == 0) {
/* An empty acquisition! */
s->async->events |= COMEDI_CB_EOA;
subpriv->intr.active = 0;
return 1;
} else {
unsigned bits = 0, pol_bits = 0, n;
int nports, firstport, asic, port;
struct comedi_cmd *cmd = &s->async->cmd;
asic = subpriv->intr.asic;
if (asic < 0)
return 1; /* not an interrupt
subdev */
subpriv->intr.enabled_mask = 0;
subpriv->intr.active = 1;
nports = subpriv->intr.num_asic_chans / CHANS_PER_PORT;
firstport = subpriv->intr.asic_chan / CHANS_PER_PORT;
if (cmd->chanlist) {
for (n = 0; n < cmd->chanlist_len; n++) {
bits |= (1U << CR_CHAN(cmd->chanlist[n]));
pol_bits |= (CR_AREF(cmd->chanlist[n])
|| CR_RANGE(cmd->
chanlist[n]) ? 1U : 0U)
<< CR_CHAN(cmd->chanlist[n]);
}
}
bits &= ((0x1 << subpriv->intr.num_asic_chans) -
1) << subpriv->intr.first_chan;
subpriv->intr.enabled_mask = bits;
switch_page(dev, asic, PAGE_ENAB);
for (port = firstport; port < firstport + nports; ++port) {
unsigned enab =
bits >> (subpriv->intr.first_chan + (port -
firstport) *
8) & 0xff, pol =
pol_bits >> (subpriv->intr.first_chan +
(port - firstport) * 8) & 0xff;
/* set enab intrs for this subdev.. */
outb(enab,
devpriv->asics[asic].iobase + REG_ENAB0 + port);
switch_page(dev, asic, PAGE_POL);
outb(pol,
devpriv->asics[asic].iobase + REG_ENAB0 + port);
}
}
return 0;
}
static int pcmuio_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
unsigned long flags;
spin_lock_irqsave(&subpriv->intr.spinlock, flags);
if (subpriv->intr.active)
pcmuio_stop_intr(dev, s);
spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
return 0;
}
/*
* Internal trigger function to start acquisition for an 'INTERRUPT' subdevice.
*/
static int
pcmuio_inttrig_start_intr(struct comedi_device *dev, struct comedi_subdevice *s,
unsigned int trignum)
{
unsigned long flags;
int event = 0;
if (trignum != 0)
return -EINVAL;
spin_lock_irqsave(&subpriv->intr.spinlock, flags);
s->async->inttrig = 0;
if (subpriv->intr.active) {
event = pcmuio_start_intr(dev, s);
}
spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
if (event) {
comedi_event(dev, s);
}
return 1;
}
/*
* 'do_cmd' function for an 'INTERRUPT' subdevice.
*/
static int pcmuio_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_cmd *cmd = &s->async->cmd;
unsigned long flags;
int event = 0;
spin_lock_irqsave(&subpriv->intr.spinlock, flags);
subpriv->intr.active = 1;
/* Set up end of acquisition. */
switch (cmd->stop_src) {
case TRIG_COUNT:
subpriv->intr.continuous = 0;
subpriv->intr.stop_count = cmd->stop_arg;
break;
default:
/* TRIG_NONE */
subpriv->intr.continuous = 1;
subpriv->intr.stop_count = 0;
break;
}
/* Set up start of acquisition. */
switch (cmd->start_src) {
case TRIG_INT:
s->async->inttrig = pcmuio_inttrig_start_intr;
break;
default:
/* TRIG_NOW */
event = pcmuio_start_intr(dev, s);
break;
}
spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
if (event) {
comedi_event(dev, s);
}
return 0;
}
static int
pcmuio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
return comedi_pcm_cmdtest(dev, s, cmd);
}
/*
* A convenient macro that defines init_module() and cleanup_module(),
* as necessary.
*/
static int __init driver_init_module(void)
{
return comedi_driver_register(&driver);
}
static void __exit driver_cleanup_module(void)
{
comedi_driver_unregister(&driver);
}
module_init(driver_init_module);
module_exit(driver_cleanup_module);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TeamRegular/android_kernel_hisense_m470 | drivers/media/video/et61x251/et61x251_tas5130d1b.c | 4868 | 4058 | /***************************************************************************
* Plug-in for TAS5130D1B image sensor connected to the ET61X[12]51 *
* PC Camera Controllers *
* *
* Copyright (C) 2006-2007 by Luca Risolia <luca.risolia@studio.unibo.it> *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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., 675 Mass Ave, Cambridge, MA 02139, USA. *
***************************************************************************/
#include "et61x251_sensor.h"
static int tas5130d1b_init(struct et61x251_device* cam)
{
int err = 0;
err += et61x251_write_reg(cam, 0x14, 0x01);
err += et61x251_write_reg(cam, 0x1b, 0x02);
err += et61x251_write_reg(cam, 0x02, 0x12);
err += et61x251_write_reg(cam, 0x0e, 0x60);
err += et61x251_write_reg(cam, 0x80, 0x61);
err += et61x251_write_reg(cam, 0xf0, 0x62);
err += et61x251_write_reg(cam, 0x03, 0x63);
err += et61x251_write_reg(cam, 0x14, 0x64);
err += et61x251_write_reg(cam, 0xf4, 0x65);
err += et61x251_write_reg(cam, 0x01, 0x66);
err += et61x251_write_reg(cam, 0x05, 0x67);
err += et61x251_write_reg(cam, 0x8f, 0x68);
err += et61x251_write_reg(cam, 0x0f, 0x8d);
err += et61x251_write_reg(cam, 0x08, 0x8e);
return err;
}
static int tas5130d1b_set_ctrl(struct et61x251_device* cam,
const struct v4l2_control* ctrl)
{
int err = 0;
switch (ctrl->id) {
case V4L2_CID_GAIN:
err += et61x251_i2c_raw_write(cam, 2, 0x20,
0xf6-ctrl->value, 0, 0, 0,
0, 0, 0, 0);
break;
case V4L2_CID_EXPOSURE:
err += et61x251_i2c_raw_write(cam, 2, 0x40,
0x47-ctrl->value, 0, 0, 0,
0, 0, 0, 0);
break;
default:
return -EINVAL;
}
return err ? -EIO : 0;
}
static const struct et61x251_sensor tas5130d1b = {
.name = "TAS5130D1B",
.interface = ET61X251_I2C_3WIRES,
.rsta = ET61X251_I2C_RSTA_STOP,
.active_pixel = {
.left = 106,
.top = 13,
},
.init = &tas5130d1b_init,
.qctrl = {
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "global gain",
.minimum = 0x00,
.maximum = 0xf6,
.step = 0x02,
.default_value = 0x0d,
.flags = 0,
},
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "exposure",
.minimum = 0x00,
.maximum = 0x47,
.step = 0x01,
.default_value = 0x23,
.flags = 0,
},
},
.set_ctrl = &tas5130d1b_set_ctrl,
.cropcap = {
.bounds = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
.defrect = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
},
.pix_format = {
.width = 640,
.height = 480,
.pixelformat = V4L2_PIX_FMT_SBGGR8,
.priv = 8,
},
};
int et61x251_probe_tas5130d1b(struct et61x251_device* cam)
{
const struct usb_device_id tas5130d1b_id_table[] = {
{ USB_DEVICE(0x102c, 0x6251), },
{ }
};
/* Sensor detection is based on USB pid/vid */
if (!et61x251_match_id(cam, tas5130d1b_id_table))
return -ENODEV;
et61x251_attach_sensor(cam, &tas5130d1b);
return 0;
}
| gpl-2.0 |
iHateWEBos/shooter_kernel_34 | arch/arm/mach-ixp4xx/fsg-pci.c | 5380 | 1766 | /*
* arch/arch/mach-ixp4xx/fsg-pci.c
*
* FSG board-level PCI initialization
*
* Author: Rod Whitby <rod@whitby.id.au>
* Maintainer: http://www.nslu2-linux.org/
*
* based on ixdp425-pci.c:
* Copyright (C) 2002 Intel Corporation.
* Copyright (C) 2003-2004 MontaVista Software, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <asm/mach/pci.h>
#include <asm/mach-types.h>
#define MAX_DEV 3
#define IRQ_LINES 3
/* PCI controller GPIO to IRQ pin mappings */
#define INTA 6
#define INTB 7
#define INTC 5
void __init fsg_pci_preinit(void)
{
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTA), IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTB), IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTC), IRQ_TYPE_LEVEL_LOW);
ixp4xx_pci_preinit();
}
static int __init fsg_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
static int pci_irq_table[IRQ_LINES] = {
IXP4XX_GPIO_IRQ(INTC),
IXP4XX_GPIO_IRQ(INTB),
IXP4XX_GPIO_IRQ(INTA),
};
int irq = -1;
slot -= 11;
if (slot >= 1 && slot <= MAX_DEV && pin >= 1 && pin <= IRQ_LINES)
irq = pci_irq_table[slot - 1];
printk(KERN_INFO "%s: Mapped slot %d pin %d to IRQ %d\n",
__func__, slot, pin, irq);
return irq;
}
struct hw_pci fsg_pci __initdata = {
.nr_controllers = 1,
.preinit = fsg_pci_preinit,
.swizzle = pci_std_swizzle,
.setup = ixp4xx_setup,
.scan = ixp4xx_scan_bus,
.map_irq = fsg_map_irq,
};
int __init fsg_pci_init(void)
{
if (machine_is_fsg())
pci_common_init(&fsg_pci);
return 0;
}
subsys_initcall(fsg_pci_init);
| gpl-2.0 |
flar2/bulletproof-flo | arch/powerpc/sysdev/simple_gpio.c | 8964 | 3283 | /*
* Simple Memory-Mapped GPIOs
*
* Copyright (c) MontaVista Software, Inc. 2008.
*
* Author: Anton Vorontsov <avorontsov@ru.mvista.com>
*
* 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; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/ioport.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <asm/prom.h>
#include "simple_gpio.h"
struct u8_gpio_chip {
struct of_mm_gpio_chip mm_gc;
spinlock_t lock;
/* shadowed data register to clear/set bits safely */
u8 data;
};
static struct u8_gpio_chip *to_u8_gpio_chip(struct of_mm_gpio_chip *mm_gc)
{
return container_of(mm_gc, struct u8_gpio_chip, mm_gc);
}
static u8 u8_pin2mask(unsigned int pin)
{
return 1 << (8 - 1 - pin);
}
static int u8_gpio_get(struct gpio_chip *gc, unsigned int gpio)
{
struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc);
return in_8(mm_gc->regs) & u8_pin2mask(gpio);
}
static void u8_gpio_set(struct gpio_chip *gc, unsigned int gpio, int val)
{
struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc);
struct u8_gpio_chip *u8_gc = to_u8_gpio_chip(mm_gc);
unsigned long flags;
spin_lock_irqsave(&u8_gc->lock, flags);
if (val)
u8_gc->data |= u8_pin2mask(gpio);
else
u8_gc->data &= ~u8_pin2mask(gpio);
out_8(mm_gc->regs, u8_gc->data);
spin_unlock_irqrestore(&u8_gc->lock, flags);
}
static int u8_gpio_dir_in(struct gpio_chip *gc, unsigned int gpio)
{
return 0;
}
static int u8_gpio_dir_out(struct gpio_chip *gc, unsigned int gpio, int val)
{
u8_gpio_set(gc, gpio, val);
return 0;
}
static void u8_gpio_save_regs(struct of_mm_gpio_chip *mm_gc)
{
struct u8_gpio_chip *u8_gc = to_u8_gpio_chip(mm_gc);
u8_gc->data = in_8(mm_gc->regs);
}
static int __init u8_simple_gpiochip_add(struct device_node *np)
{
int ret;
struct u8_gpio_chip *u8_gc;
struct of_mm_gpio_chip *mm_gc;
struct gpio_chip *gc;
u8_gc = kzalloc(sizeof(*u8_gc), GFP_KERNEL);
if (!u8_gc)
return -ENOMEM;
spin_lock_init(&u8_gc->lock);
mm_gc = &u8_gc->mm_gc;
gc = &mm_gc->gc;
mm_gc->save_regs = u8_gpio_save_regs;
gc->ngpio = 8;
gc->direction_input = u8_gpio_dir_in;
gc->direction_output = u8_gpio_dir_out;
gc->get = u8_gpio_get;
gc->set = u8_gpio_set;
ret = of_mm_gpiochip_add(np, mm_gc);
if (ret)
goto err;
return 0;
err:
kfree(u8_gc);
return ret;
}
void __init simple_gpiochip_init(const char *compatible)
{
struct device_node *np;
for_each_compatible_node(np, NULL, compatible) {
int ret;
struct resource r;
ret = of_address_to_resource(np, 0, &r);
if (ret)
goto err;
switch (resource_size(&r)) {
case 1:
ret = u8_simple_gpiochip_add(np);
if (ret)
goto err;
break;
default:
/*
* Whenever you need support for GPIO bank width > 1,
* please just turn u8_ code into huge macros, and
* construct needed uX_ code with it.
*/
ret = -ENOSYS;
goto err;
}
continue;
err:
pr_err("%s: registration failed, status %d\n",
np->full_name, ret);
}
}
| gpl-2.0 |
Motorola-CyanogenMod/android_kernel_motorola_msm8916 | arch/cris/arch-v32/kernel/irq.c | 9732 | 12748 | /*
* Copyright (C) 2003, Axis Communications AB.
*/
#include <asm/irq.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/profile.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/threads.h>
#include <linux/spinlock.h>
#include <linux/kernel_stat.h>
#include <hwregs/reg_map.h>
#include <hwregs/reg_rdwr.h>
#include <hwregs/intr_vect.h>
#include <hwregs/intr_vect_defs.h>
#define CPU_FIXED -1
/* IRQ masks (refer to comment for crisv32_do_multiple) */
#if TIMER0_INTR_VECT - FIRST_IRQ < 32
#define TIMER_MASK (1 << (TIMER0_INTR_VECT - FIRST_IRQ))
#undef TIMER_VECT1
#else
#define TIMER_MASK (1 << (TIMER0_INTR_VECT - FIRST_IRQ - 32))
#define TIMER_VECT1
#endif
#ifdef CONFIG_ETRAX_KGDB
#if defined(CONFIG_ETRAX_KGDB_PORT0)
#define IGNOREMASK (1 << (SER0_INTR_VECT - FIRST_IRQ))
#elif defined(CONFIG_ETRAX_KGDB_PORT1)
#define IGNOREMASK (1 << (SER1_INTR_VECT - FIRST_IRQ))
#elif defined(CONFIG_ETRAX_KGB_PORT2)
#define IGNOREMASK (1 << (SER2_INTR_VECT - FIRST_IRQ))
#elif defined(CONFIG_ETRAX_KGDB_PORT3)
#define IGNOREMASK (1 << (SER3_INTR_VECT - FIRST_IRQ))
#endif
#endif
DEFINE_SPINLOCK(irq_lock);
struct cris_irq_allocation
{
int cpu; /* The CPU to which the IRQ is currently allocated. */
cpumask_t mask; /* The CPUs to which the IRQ may be allocated. */
};
struct cris_irq_allocation irq_allocations[NR_REAL_IRQS] =
{ [0 ... NR_REAL_IRQS - 1] = {0, CPU_MASK_ALL} };
static unsigned long irq_regs[NR_CPUS] =
{
regi_irq,
#ifdef CONFIG_SMP
regi_irq2,
#endif
};
#if NR_REAL_IRQS > 32
#define NBR_REGS 2
#else
#define NBR_REGS 1
#endif
unsigned long cpu_irq_counters[NR_CPUS];
unsigned long irq_counters[NR_REAL_IRQS];
/* From irq.c. */
extern void weird_irq(void);
/* From entry.S. */
extern void system_call(void);
extern void nmi_interrupt(void);
extern void multiple_interrupt(void);
extern void gdb_handle_exception(void);
extern void i_mmu_refill(void);
extern void i_mmu_invalid(void);
extern void i_mmu_access(void);
extern void i_mmu_execute(void);
extern void d_mmu_refill(void);
extern void d_mmu_invalid(void);
extern void d_mmu_access(void);
extern void d_mmu_write(void);
/* From kgdb.c. */
extern void kgdb_init(void);
extern void breakpoint(void);
/* From traps.c. */
extern void breakh_BUG(void);
/*
* Build the IRQ handler stubs using macros from irq.h.
*/
#ifdef CONFIG_CRIS_MACH_ARTPEC3
BUILD_TIMER_IRQ(0x31, 0)
#else
BUILD_IRQ(0x31)
#endif
BUILD_IRQ(0x32)
BUILD_IRQ(0x33)
BUILD_IRQ(0x34)
BUILD_IRQ(0x35)
BUILD_IRQ(0x36)
BUILD_IRQ(0x37)
BUILD_IRQ(0x38)
BUILD_IRQ(0x39)
BUILD_IRQ(0x3a)
BUILD_IRQ(0x3b)
BUILD_IRQ(0x3c)
BUILD_IRQ(0x3d)
BUILD_IRQ(0x3e)
BUILD_IRQ(0x3f)
BUILD_IRQ(0x40)
BUILD_IRQ(0x41)
BUILD_IRQ(0x42)
BUILD_IRQ(0x43)
BUILD_IRQ(0x44)
BUILD_IRQ(0x45)
BUILD_IRQ(0x46)
BUILD_IRQ(0x47)
BUILD_IRQ(0x48)
BUILD_IRQ(0x49)
BUILD_IRQ(0x4a)
#ifdef CONFIG_ETRAXFS
BUILD_TIMER_IRQ(0x4b, 0)
#else
BUILD_IRQ(0x4b)
#endif
BUILD_IRQ(0x4c)
BUILD_IRQ(0x4d)
BUILD_IRQ(0x4e)
BUILD_IRQ(0x4f)
BUILD_IRQ(0x50)
#if MACH_IRQS > 32
BUILD_IRQ(0x51)
BUILD_IRQ(0x52)
BUILD_IRQ(0x53)
BUILD_IRQ(0x54)
BUILD_IRQ(0x55)
BUILD_IRQ(0x56)
BUILD_IRQ(0x57)
BUILD_IRQ(0x58)
BUILD_IRQ(0x59)
BUILD_IRQ(0x5a)
BUILD_IRQ(0x5b)
BUILD_IRQ(0x5c)
BUILD_IRQ(0x5d)
BUILD_IRQ(0x5e)
BUILD_IRQ(0x5f)
BUILD_IRQ(0x60)
BUILD_IRQ(0x61)
BUILD_IRQ(0x62)
BUILD_IRQ(0x63)
BUILD_IRQ(0x64)
BUILD_IRQ(0x65)
BUILD_IRQ(0x66)
BUILD_IRQ(0x67)
BUILD_IRQ(0x68)
BUILD_IRQ(0x69)
BUILD_IRQ(0x6a)
BUILD_IRQ(0x6b)
BUILD_IRQ(0x6c)
BUILD_IRQ(0x6d)
BUILD_IRQ(0x6e)
BUILD_IRQ(0x6f)
BUILD_IRQ(0x70)
#endif
/* Pointers to the low-level handlers. */
static void (*interrupt[MACH_IRQS])(void) = {
IRQ0x31_interrupt, IRQ0x32_interrupt, IRQ0x33_interrupt,
IRQ0x34_interrupt, IRQ0x35_interrupt, IRQ0x36_interrupt,
IRQ0x37_interrupt, IRQ0x38_interrupt, IRQ0x39_interrupt,
IRQ0x3a_interrupt, IRQ0x3b_interrupt, IRQ0x3c_interrupt,
IRQ0x3d_interrupt, IRQ0x3e_interrupt, IRQ0x3f_interrupt,
IRQ0x40_interrupt, IRQ0x41_interrupt, IRQ0x42_interrupt,
IRQ0x43_interrupt, IRQ0x44_interrupt, IRQ0x45_interrupt,
IRQ0x46_interrupt, IRQ0x47_interrupt, IRQ0x48_interrupt,
IRQ0x49_interrupt, IRQ0x4a_interrupt, IRQ0x4b_interrupt,
IRQ0x4c_interrupt, IRQ0x4d_interrupt, IRQ0x4e_interrupt,
IRQ0x4f_interrupt, IRQ0x50_interrupt,
#if MACH_IRQS > 32
IRQ0x51_interrupt, IRQ0x52_interrupt, IRQ0x53_interrupt,
IRQ0x54_interrupt, IRQ0x55_interrupt, IRQ0x56_interrupt,
IRQ0x57_interrupt, IRQ0x58_interrupt, IRQ0x59_interrupt,
IRQ0x5a_interrupt, IRQ0x5b_interrupt, IRQ0x5c_interrupt,
IRQ0x5d_interrupt, IRQ0x5e_interrupt, IRQ0x5f_interrupt,
IRQ0x60_interrupt, IRQ0x61_interrupt, IRQ0x62_interrupt,
IRQ0x63_interrupt, IRQ0x64_interrupt, IRQ0x65_interrupt,
IRQ0x66_interrupt, IRQ0x67_interrupt, IRQ0x68_interrupt,
IRQ0x69_interrupt, IRQ0x6a_interrupt, IRQ0x6b_interrupt,
IRQ0x6c_interrupt, IRQ0x6d_interrupt, IRQ0x6e_interrupt,
IRQ0x6f_interrupt, IRQ0x70_interrupt,
#endif
};
void
block_irq(int irq, int cpu)
{
int intr_mask;
unsigned long flags;
spin_lock_irqsave(&irq_lock, flags);
/* Remember, 1 let thru, 0 block. */
if (irq - FIRST_IRQ < 32) {
intr_mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
rw_mask, 0);
intr_mask &= ~(1 << (irq - FIRST_IRQ));
REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask,
0, intr_mask);
} else {
intr_mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
rw_mask, 1);
intr_mask &= ~(1 << (irq - FIRST_IRQ - 32));
REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask,
1, intr_mask);
}
spin_unlock_irqrestore(&irq_lock, flags);
}
void
unblock_irq(int irq, int cpu)
{
int intr_mask;
unsigned long flags;
spin_lock_irqsave(&irq_lock, flags);
/* Remember, 1 let thru, 0 block. */
if (irq - FIRST_IRQ < 32) {
intr_mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
rw_mask, 0);
intr_mask |= (1 << (irq - FIRST_IRQ));
REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask,
0, intr_mask);
} else {
intr_mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
rw_mask, 1);
intr_mask |= (1 << (irq - FIRST_IRQ - 32));
REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask,
1, intr_mask);
}
spin_unlock_irqrestore(&irq_lock, flags);
}
/* Find out which CPU the irq should be allocated to. */
static int irq_cpu(int irq)
{
int cpu;
unsigned long flags;
spin_lock_irqsave(&irq_lock, flags);
cpu = irq_allocations[irq - FIRST_IRQ].cpu;
/* Fixed interrupts stay on the local CPU. */
if (cpu == CPU_FIXED)
{
spin_unlock_irqrestore(&irq_lock, flags);
return smp_processor_id();
}
/* Let the interrupt stay if possible */
if (cpumask_test_cpu(cpu, &irq_allocations[irq - FIRST_IRQ].mask))
goto out;
/* IRQ must be moved to another CPU. */
cpu = cpumask_first(&irq_allocations[irq - FIRST_IRQ].mask);
irq_allocations[irq - FIRST_IRQ].cpu = cpu;
out:
spin_unlock_irqrestore(&irq_lock, flags);
return cpu;
}
void crisv32_mask_irq(int irq)
{
int cpu;
for (cpu = 0; cpu < NR_CPUS; cpu++)
block_irq(irq, cpu);
}
void crisv32_unmask_irq(int irq)
{
unblock_irq(irq, irq_cpu(irq));
}
static void enable_crisv32_irq(struct irq_data *data)
{
crisv32_unmask_irq(data->irq);
}
static void disable_crisv32_irq(struct irq_data *data)
{
crisv32_mask_irq(data->irq);
}
static int set_affinity_crisv32_irq(struct irq_data *data,
const struct cpumask *dest, bool force)
{
unsigned long flags;
spin_lock_irqsave(&irq_lock, flags);
irq_allocations[data->irq - FIRST_IRQ].mask = *dest;
spin_unlock_irqrestore(&irq_lock, flags);
return 0;
}
static struct irq_chip crisv32_irq_type = {
.name = "CRISv32",
.irq_shutdown = disable_crisv32_irq,
.irq_enable = enable_crisv32_irq,
.irq_disable = disable_crisv32_irq,
.irq_set_affinity = set_affinity_crisv32_irq,
};
void
set_exception_vector(int n, irqvectptr addr)
{
etrax_irv->v[n] = (irqvectptr) addr;
}
extern void do_IRQ(int irq, struct pt_regs * regs);
void
crisv32_do_IRQ(int irq, int block, struct pt_regs* regs)
{
/* Interrupts that may not be moved to another CPU and
* are IRQF_DISABLED may skip blocking. This is currently
* only valid for the timer IRQ and the IPI and is used
* for the timer interrupt to avoid watchdog starvation.
*/
if (!block) {
do_IRQ(irq, regs);
return;
}
block_irq(irq, smp_processor_id());
do_IRQ(irq, regs);
unblock_irq(irq, irq_cpu(irq));
}
/* If multiple interrupts occur simultaneously we get a multiple
* interrupt from the CPU and software has to sort out which
* interrupts that happened. There are two special cases here:
*
* 1. Timer interrupts may never be blocked because of the
* watchdog (refer to comment in include/asr/arch/irq.h)
* 2. GDB serial port IRQs are unhandled here and will be handled
* as a single IRQ when it strikes again because the GDB
* stubb wants to save the registers in its own fashion.
*/
void
crisv32_do_multiple(struct pt_regs* regs)
{
int cpu;
int mask;
int masked[NBR_REGS];
int bit;
int i;
cpu = smp_processor_id();
/* An extra irq_enter here to prevent softIRQs to run after
* each do_IRQ. This will decrease the interrupt latency.
*/
irq_enter();
for (i = 0; i < NBR_REGS; i++) {
/* Get which IRQs that happened. */
masked[i] = REG_RD_INT_VECT(intr_vect, irq_regs[cpu],
r_masked_vect, i);
/* Calculate new IRQ mask with these IRQs disabled. */
mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu], rw_mask, i);
mask &= ~masked[i];
/* Timer IRQ is never masked */
#ifdef TIMER_VECT1
if ((i == 1) && (masked[0] & TIMER_MASK))
mask |= TIMER_MASK;
#else
if ((i == 0) && (masked[0] & TIMER_MASK))
mask |= TIMER_MASK;
#endif
/* Block all the IRQs */
REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask, i, mask);
/* Check for timer IRQ and handle it special. */
#ifdef TIMER_VECT1
if ((i == 1) && (masked[i] & TIMER_MASK)) {
masked[i] &= ~TIMER_MASK;
do_IRQ(TIMER0_INTR_VECT, regs);
}
#else
if ((i == 0) && (masked[i] & TIMER_MASK)) {
masked[i] &= ~TIMER_MASK;
do_IRQ(TIMER0_INTR_VECT, regs);
}
#endif
}
#ifdef IGNORE_MASK
/* Remove IRQs that can't be handled as multiple. */
masked[0] &= ~IGNORE_MASK;
#endif
/* Handle the rest of the IRQs. */
for (i = 0; i < NBR_REGS; i++) {
for (bit = 0; bit < 32; bit++) {
if (masked[i] & (1 << bit))
do_IRQ(bit + FIRST_IRQ + i*32, regs);
}
}
/* Unblock all the IRQs. */
for (i = 0; i < NBR_REGS; i++) {
mask = REG_RD_INT_VECT(intr_vect, irq_regs[cpu], rw_mask, i);
mask |= masked[i];
REG_WR_INT_VECT(intr_vect, irq_regs[cpu], rw_mask, i, mask);
}
/* This irq_exit() will trigger the soft IRQs. */
irq_exit();
}
/*
* This is called by start_kernel. It fixes the IRQ masks and setup the
* interrupt vector table to point to bad_interrupt pointers.
*/
void __init
init_IRQ(void)
{
int i;
int j;
reg_intr_vect_rw_mask vect_mask = {0};
/* Clear all interrupts masks. */
for (i = 0; i < NBR_REGS; i++)
REG_WR_VECT(intr_vect, regi_irq, rw_mask, i, vect_mask);
for (i = 0; i < 256; i++)
etrax_irv->v[i] = weird_irq;
/* Point all IRQ's to bad handlers. */
for (i = FIRST_IRQ, j = 0; j < NR_IRQS; i++, j++) {
irq_set_chip_and_handler(j, &crisv32_irq_type,
handle_simple_irq);
set_exception_vector(i, interrupt[j]);
}
/* Mark Timer and IPI IRQs as CPU local */
irq_allocations[TIMER0_INTR_VECT - FIRST_IRQ].cpu = CPU_FIXED;
irq_set_status_flags(TIMER0_INTR_VECT, IRQ_PER_CPU);
irq_allocations[IPI_INTR_VECT - FIRST_IRQ].cpu = CPU_FIXED;
irq_set_status_flags(IPI_INTR_VECT, IRQ_PER_CPU);
set_exception_vector(0x00, nmi_interrupt);
set_exception_vector(0x30, multiple_interrupt);
/* Set up handler for various MMU bus faults. */
set_exception_vector(0x04, i_mmu_refill);
set_exception_vector(0x05, i_mmu_invalid);
set_exception_vector(0x06, i_mmu_access);
set_exception_vector(0x07, i_mmu_execute);
set_exception_vector(0x08, d_mmu_refill);
set_exception_vector(0x09, d_mmu_invalid);
set_exception_vector(0x0a, d_mmu_access);
set_exception_vector(0x0b, d_mmu_write);
#ifdef CONFIG_BUG
/* Break 14 handler, used to implement cheap BUG(). */
set_exception_vector(0x1e, breakh_BUG);
#endif
/* The system-call trap is reached by "break 13". */
set_exception_vector(0x1d, system_call);
/* Exception handlers for debugging, both user-mode and kernel-mode. */
/* Break 8. */
set_exception_vector(0x18, gdb_handle_exception);
/* Hardware single step. */
set_exception_vector(0x3, gdb_handle_exception);
/* Hardware breakpoint. */
set_exception_vector(0xc, gdb_handle_exception);
#ifdef CONFIG_ETRAX_KGDB
kgdb_init();
/* Everything is set up; now trap the kernel. */
breakpoint();
#endif
}
| gpl-2.0 |
f00barbob/vba-rr-mod | src/win32/7zip/7z/CPP/7zip/Crypto/WzAes.cpp | 5 | 5283 | // Crypto/WzAes.cpp
/*
This code implements Brian Gladman's scheme
specified in password Based File Encryption Utility.
Note: you must include MyAes.cpp to project to initialize AES tables
*/
#include "StdAfx.h"
#include "../Common/StreamObjects.h"
#include "../Common/StreamUtils.h"
#include "Pbkdf2HmacSha1.h"
#include "RandGen.h"
#include "WzAes.h"
// define it if you don't want to use speed-optimized version of Pbkdf2HmacSha1
// #define _NO_WZAES_OPTIMIZATIONS
namespace NCrypto {
namespace NWzAes {
const unsigned int kAesKeySizeMax = 32;
static const UInt32 kNumKeyGenIterations = 1000;
STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size)
{
if(size > kPasswordSizeMax)
return E_INVALIDARG;
_key.Password.SetCapacity(size);
memcpy(_key.Password, data, size);
return S_OK;
}
#define SetUi32(p, d) { UInt32 x = (d); (p)[0] = (Byte)x; (p)[1] = (Byte)(x >> 8); \
(p)[2] = (Byte)(x >> 16); (p)[3] = (Byte)(x >> 24); }
void CBaseCoder::EncryptData(Byte *data, UInt32 size)
{
unsigned int pos = _blockPos;
for (; size > 0; size--)
{
if (pos == AES_BLOCK_SIZE)
{
if (++_counter[0] == 0)
_counter[1]++;
UInt32 temp[4];
Aes_Encode32(&Aes, temp, _counter);
SetUi32(_buffer, temp[0]);
SetUi32(_buffer + 4, temp[1]);
SetUi32(_buffer + 8, temp[2]);
SetUi32(_buffer + 12, temp[3]);
pos = 0;
}
*data++ ^= _buffer[pos++];
}
_blockPos = pos;
}
#ifndef _NO_WZAES_OPTIMIZATIONS
static void BytesToBeUInt32s(const Byte *src, UInt32 *dest, int destSize)
{
for (int i = 0 ; i < destSize; i++)
dest[i] =
((UInt32)(src[i * 4 + 0]) << 24) |
((UInt32)(src[i * 4 + 1]) << 16) |
((UInt32)(src[i * 4 + 2]) << 8) |
((UInt32)(src[i * 4 + 3]));
}
#endif
STDMETHODIMP CBaseCoder::Init()
{
UInt32 keySize = _key.GetKeySize();
UInt32 keysTotalSize = 2 * keySize + kPwdVerifCodeSize;
Byte buf[2 * kAesKeySizeMax + kPwdVerifCodeSize];
// for (int ii = 0; ii < 1000; ii++)
{
#ifdef _NO_WZAES_OPTIMIZATIONS
NSha1::Pbkdf2Hmac(
_key.Password, _key.Password.GetCapacity(),
_key.Salt, _key.GetSaltSize(),
kNumKeyGenIterations,
buf, keysTotalSize);
#else
UInt32 buf32[(2 * kAesKeySizeMax + kPwdVerifCodeSize + 3) / 4];
UInt32 key32SizeTotal = (keysTotalSize + 3) / 4;
UInt32 salt[kSaltSizeMax * 4];
UInt32 saltSizeInWords = _key.GetSaltSize() / 4;
BytesToBeUInt32s(_key.Salt, salt, saltSizeInWords);
NSha1::Pbkdf2Hmac32(
_key.Password, _key.Password.GetCapacity(),
salt, saltSizeInWords,
kNumKeyGenIterations,
buf32, key32SizeTotal);
for (UInt32 j = 0; j < keysTotalSize; j++)
buf[j] = (Byte)(buf32[j / 4] >> (24 - 8 * (j & 3)));
#endif
}
_hmac.SetKey(buf + keySize, keySize);
memcpy(_key.PwdVerifComputed, buf + 2 * keySize, kPwdVerifCodeSize);
_blockPos = AES_BLOCK_SIZE;
for (int i = 0; i < 4; i++)
_counter[i] = 0;
Aes_SetKeyEncode(&Aes, buf, keySize);
return S_OK;
}
/*
STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)
{
Byte keySizeMode = 3;
return outStream->Write(&keySizeMode, 1, NULL);
}
*/
HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream)
{
UInt32 saltSize = _key.GetSaltSize();
g_RandomGenerator.Generate(_key.Salt, saltSize);
Init();
RINOK(WriteStream(outStream, _key.Salt, saltSize));
return WriteStream(outStream, _key.PwdVerifComputed, kPwdVerifCodeSize);
}
HRESULT CEncoder::WriteFooter(ISequentialOutStream *outStream)
{
Byte mac[kMacSize];
_hmac.Final(mac, kMacSize);
return WriteStream(outStream, mac, kMacSize);
}
STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)
{
if (size != 1)
return E_INVALIDARG;
_key.Init();
Byte keySizeMode = data[0];
if (keySizeMode < 1 || keySizeMode > 3)
return E_INVALIDARG;
_key.KeySizeMode = keySizeMode;
return S_OK;
}
HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream)
{
UInt32 saltSize = _key.GetSaltSize();
UInt32 extraSize = saltSize + kPwdVerifCodeSize;
Byte temp[kSaltSizeMax + kPwdVerifCodeSize];
RINOK(ReadStream_FAIL(inStream, temp, extraSize));
UInt32 i;
for (i = 0; i < saltSize; i++)
_key.Salt[i] = temp[i];
for (i = 0; i < kPwdVerifCodeSize; i++)
_pwdVerifFromArchive[i] = temp[saltSize + i];
return S_OK;
}
static bool CompareArrays(const Byte *p1, const Byte *p2, UInt32 size)
{
for (UInt32 i = 0; i < size; i++)
if (p1[i] != p2[i])
return false;
return true;
}
bool CDecoder::CheckPasswordVerifyCode()
{
return CompareArrays(_key.PwdVerifComputed, _pwdVerifFromArchive, kPwdVerifCodeSize);
}
HRESULT CDecoder::CheckMac(ISequentialInStream *inStream, bool &isOK)
{
isOK = false;
Byte mac1[kMacSize];
RINOK(ReadStream_FAIL(inStream, mac1, kMacSize));
Byte mac2[kMacSize];
_hmac.Final(mac2, kMacSize);
isOK = CompareArrays(mac1, mac2, kMacSize);
return S_OK;
}
STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size)
{
EncryptData(data, size);
_hmac.Update(data, size);
return size;
}
STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size)
{
_hmac.Update(data, size);
EncryptData(data, size);
return size;
}
}}
| gpl-2.0 |
rhuitl/uClinux | user/busybox/miscutils/mountpoint.c | 5 | 1535 | /* vi: set sw=4 ts=4: */
/*
* mountpoint implementation for busybox
*
* Copyright (C) 2005 Bernhard Fischer
*
* Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
*
* Based on sysvinit's mountpoint
*/
#include "libbb.h"
int mountpoint_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int mountpoint_main(int argc, char **argv)
{
struct stat st;
char *arg;
int opt = getopt32(argv, "qdx");
#define OPT_q (1)
#define OPT_d (2)
#define OPT_x (4)
if (optind != argc - 1)
bb_show_usage();
arg = argv[optind];
if ( (opt & OPT_x && stat(arg, &st) == 0) || (lstat(arg, &st) == 0) ) {
if (opt & OPT_x) {
if (S_ISBLK(st.st_mode)) {
printf("%u:%u\n", major(st.st_rdev),
minor(st.st_rdev));
return EXIT_SUCCESS;
} else {
if (opt & OPT_q)
bb_putchar('\n');
else
bb_error_msg("%s: not a block device", arg);
}
return EXIT_FAILURE;
} else
if (S_ISDIR(st.st_mode)) {
dev_t st_dev = st.st_dev;
ino_t st_ino = st.st_ino;
char *p = xasprintf("%s/..", arg);
if (stat(p, &st) == 0) {
int ret = (st_dev != st.st_dev) ||
(st_dev == st.st_dev && st_ino == st.st_ino);
if (opt & OPT_d)
printf("%u:%u\n", major(st_dev), minor(st_dev));
else if (!(opt & OPT_q))
printf("%s is %sa mountpoint\n", arg, ret?"":"not ");
return !ret;
}
} else {
if (!(opt & OPT_q))
bb_error_msg("%s: not a directory", arg);
return EXIT_FAILURE;
}
}
if (!(opt & OPT_q))
bb_simple_perror_msg(arg);
return EXIT_FAILURE;
}
| gpl-2.0 |
linuxmint/systemd-betsy | src/core/killall.c | 5 | 7197 | /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 ProFUSION embedded systems
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include "util.h"
#include "def.h"
#include "killall.h"
#include "set.h"
#define TIMEOUT_USEC (10 * USEC_PER_SEC)
static bool ignore_proc(pid_t pid) {
_cleanup_fclose_ FILE *f = NULL;
char c;
const char *p;
size_t count;
uid_t uid;
int r;
/* We are PID 1, let's not commit suicide */
if (pid == 1)
return true;
r = get_process_uid(pid, &uid);
if (r < 0)
return true; /* not really, but better safe than sorry */
/* Non-root processes otherwise are always subject to be killed */
if (uid != 0)
return false;
p = procfs_file_alloca(pid, "cmdline");
f = fopen(p, "re");
if (!f)
return true; /* not really, but has the desired effect */
count = fread(&c, 1, 1, f);
/* Kernel threads have an empty cmdline */
if (count <= 0)
return true;
/* Processes with argv[0][0] = '@' we ignore from the killing
* spree.
*
* http://www.freedesktop.org/wiki/Software/systemd/RootStorageDaemons */
if (count == 1 && c == '@')
return true;
return false;
}
static void wait_for_children(Set *pids, sigset_t *mask) {
usec_t until;
assert(mask);
if (set_isempty(pids))
return;
until = now(CLOCK_MONOTONIC) + TIMEOUT_USEC;
for (;;) {
struct timespec ts;
int k;
usec_t n;
void *p;
Iterator i;
/* First, let the kernel inform us about killed
* children. Most processes will probably be our
* children, but some are not (might be our
* grandchildren instead...). */
for (;;) {
pid_t pid;
pid = waitpid(-1, NULL, WNOHANG);
if (pid == 0)
break;
if (pid < 0) {
if (errno == ECHILD)
break;
log_error("waitpid() failed: %m");
return;
}
set_remove(pids, ULONG_TO_PTR(pid));
}
/* Now explicitly check who might be remaining, who
* might not be our child. */
SET_FOREACH(p, pids, i) {
/* We misuse getpgid as a check whether a
* process still exists. */
if (getpgid((pid_t) PTR_TO_ULONG(p)) >= 0)
continue;
if (errno != ESRCH)
continue;
set_remove(pids, p);
}
if (set_isempty(pids))
return;
n = now(CLOCK_MONOTONIC);
if (n >= until)
return;
timespec_store(&ts, until - n);
k = sigtimedwait(mask, NULL, &ts);
if (k != SIGCHLD) {
if (k < 0 && errno != EAGAIN) {
log_error("sigtimedwait() failed: %m");
return;
}
if (k >= 0)
log_warning("sigtimedwait() returned unexpected signal.");
}
}
}
static int killall(int sig, Set *pids, bool send_sighup) {
_cleanup_closedir_ DIR *dir = NULL;
struct dirent *d;
dir = opendir("/proc");
if (!dir)
return -errno;
while ((d = readdir(dir))) {
pid_t pid;
if (d->d_type != DT_DIR &&
d->d_type != DT_UNKNOWN)
continue;
if (parse_pid(d->d_name, &pid) < 0)
continue;
if (ignore_proc(pid))
continue;
if (sig == SIGKILL) {
_cleanup_free_ char *s = NULL;
get_process_comm(pid, &s);
log_notice("Sending SIGKILL to PID "PID_FMT" (%s).", pid, strna(s));
}
if (kill(pid, sig) >= 0) {
if (pids)
set_put(pids, ULONG_TO_PTR(pid));
} else if (errno != ENOENT)
log_warning("Could not kill %d: %m", pid);
if (send_sighup) {
/* Optionally, also send a SIGHUP signal, but
only if the process has a controlling
tty. This is useful to allow handling of
shells which ignore SIGTERM but react to
SIGHUP. We do not send this to processes that
have no controlling TTY since we don't want to
trigger reloads of daemon processes. Also we
make sure to only send this after SIGTERM so
that SIGTERM is always first in the queue. */
if (get_ctty_devnr(pid, NULL) >= 0)
kill(pid, SIGHUP);
}
}
return set_size(pids);
}
void broadcast_signal(int sig, bool wait_for_exit, bool send_sighup) {
sigset_t mask, oldmask;
_cleanup_set_free_ Set *pids = NULL;
if (wait_for_exit)
pids = set_new(trivial_hash_func, trivial_compare_func);
assert_se(sigemptyset(&mask) == 0);
assert_se(sigaddset(&mask, SIGCHLD) == 0);
assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
if (kill(-1, SIGSTOP) < 0 && errno != ESRCH)
log_warning("kill(-1, SIGSTOP) failed: %m");
killall(sig, pids, send_sighup);
if (kill(-1, SIGCONT) < 0 && errno != ESRCH)
log_warning("kill(-1, SIGCONT) failed: %m");
if (wait_for_exit)
wait_for_children(pids, &mask);
assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) == 0);
}
| gpl-2.0 |
fedux/linux | fs/proc/task_nommu.c | 5 | 7264 |
#include <linux/mm.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/fs_struct.h>
#include <linux/mount.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include "internal.h"
/*
* Logic: we've got two memory sums for each process, "shared", and
* "non-shared". Shared memory may get counted more than once, for
* each process that owns it. Non-shared memory is counted
* accurately.
*/
void task_mem(struct seq_file *m, struct mm_struct *mm)
{
struct vm_area_struct *vma;
struct vm_region *region;
struct rb_node *p;
unsigned long bytes = 0, sbytes = 0, slack = 0, size;
down_read(&mm->mmap_sem);
for (p = rb_first(&mm->mm_rb); p; p = rb_next(p)) {
vma = rb_entry(p, struct vm_area_struct, vm_rb);
bytes += kobjsize(vma);
region = vma->vm_region;
if (region) {
size = kobjsize(region);
size += region->vm_end - region->vm_start;
} else {
size = vma->vm_end - vma->vm_start;
}
if (atomic_read(&mm->mm_count) > 1 ||
vma->vm_flags & VM_MAYSHARE) {
sbytes += size;
} else {
bytes += size;
if (region)
slack = region->vm_end - vma->vm_end;
}
}
if (atomic_read(&mm->mm_count) > 1)
sbytes += kobjsize(mm);
else
bytes += kobjsize(mm);
if (current->fs && current->fs->users > 1)
sbytes += kobjsize(current->fs);
else
bytes += kobjsize(current->fs);
if (current->files && atomic_read(¤t->files->count) > 1)
sbytes += kobjsize(current->files);
else
bytes += kobjsize(current->files);
if (current->sighand && atomic_read(¤t->sighand->count) > 1)
sbytes += kobjsize(current->sighand);
else
bytes += kobjsize(current->sighand);
bytes += kobjsize(current); /* includes kernel stack */
seq_printf(m,
"Mem:\t%8lu bytes\n"
"Slack:\t%8lu bytes\n"
"Shared:\t%8lu bytes\n",
bytes, slack, sbytes);
up_read(&mm->mmap_sem);
}
unsigned long task_vsize(struct mm_struct *mm)
{
struct vm_area_struct *vma;
struct rb_node *p;
unsigned long vsize = 0;
down_read(&mm->mmap_sem);
for (p = rb_first(&mm->mm_rb); p; p = rb_next(p)) {
vma = rb_entry(p, struct vm_area_struct, vm_rb);
vsize += vma->vm_end - vma->vm_start;
}
up_read(&mm->mmap_sem);
return vsize;
}
unsigned long task_statm(struct mm_struct *mm,
unsigned long *shared, unsigned long *text,
unsigned long *data, unsigned long *resident)
{
struct vm_area_struct *vma;
struct vm_region *region;
struct rb_node *p;
unsigned long size = kobjsize(mm);
down_read(&mm->mmap_sem);
for (p = rb_first(&mm->mm_rb); p; p = rb_next(p)) {
vma = rb_entry(p, struct vm_area_struct, vm_rb);
size += kobjsize(vma);
region = vma->vm_region;
if (region) {
size += kobjsize(region);
size += region->vm_end - region->vm_start;
}
}
*text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK))
>> PAGE_SHIFT;
*data = (PAGE_ALIGN(mm->start_stack) - (mm->start_data & PAGE_MASK))
>> PAGE_SHIFT;
up_read(&mm->mmap_sem);
size >>= PAGE_SHIFT;
size += *text + *data;
*resident = size;
return size;
}
static void pad_len_spaces(struct seq_file *m, int len)
{
len = 25 + sizeof(void*) * 6 - len;
if (len < 1)
len = 1;
seq_printf(m, "%*c", len, ' ');
}
/*
* display a single VMA to a sequenced file
*/
static int nommu_vma_show(struct seq_file *m, struct vm_area_struct *vma,
int is_pid)
{
struct mm_struct *mm = vma->vm_mm;
struct proc_maps_private *priv = m->private;
unsigned long ino = 0;
struct file *file;
dev_t dev = 0;
int flags, len;
unsigned long long pgoff = 0;
flags = vma->vm_flags;
file = vma->vm_file;
if (file) {
struct inode *inode;
file = vma_pr_or_file(file);
inode = file_inode(file);
dev = inode->i_sb->s_dev;
ino = inode->i_ino;
pgoff = (loff_t)vma->vm_pgoff << PAGE_SHIFT;
}
seq_printf(m,
"%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu %n",
vma->vm_start,
vma->vm_end,
flags & VM_READ ? 'r' : '-',
flags & VM_WRITE ? 'w' : '-',
flags & VM_EXEC ? 'x' : '-',
flags & VM_MAYSHARE ? flags & VM_SHARED ? 'S' : 's' : 'p',
pgoff,
MAJOR(dev), MINOR(dev), ino, &len);
if (file) {
pad_len_spaces(m, len);
seq_path(m, &file->f_path, "");
} else if (mm) {
pid_t tid = vm_is_stack(priv->task, vma, is_pid);
if (tid != 0) {
pad_len_spaces(m, len);
/*
* Thread stack in /proc/PID/task/TID/maps or
* the main process stack.
*/
if (!is_pid || (vma->vm_start <= mm->start_stack &&
vma->vm_end >= mm->start_stack))
seq_printf(m, "[stack]");
else
seq_printf(m, "[stack:%d]", tid);
}
}
seq_putc(m, '\n');
return 0;
}
/*
* display mapping lines for a particular process's /proc/pid/maps
*/
static int show_map(struct seq_file *m, void *_p, int is_pid)
{
struct rb_node *p = _p;
return nommu_vma_show(m, rb_entry(p, struct vm_area_struct, vm_rb),
is_pid);
}
static int show_pid_map(struct seq_file *m, void *_p)
{
return show_map(m, _p, 1);
}
static int show_tid_map(struct seq_file *m, void *_p)
{
return show_map(m, _p, 0);
}
static void *m_start(struct seq_file *m, loff_t *pos)
{
struct proc_maps_private *priv = m->private;
struct mm_struct *mm;
struct rb_node *p;
loff_t n = *pos;
/* pin the task and mm whilst we play with them */
priv->task = get_pid_task(priv->pid, PIDTYPE_PID);
if (!priv->task)
return ERR_PTR(-ESRCH);
mm = mm_access(priv->task, PTRACE_MODE_READ_FSCREDS);
if (!mm || IS_ERR(mm)) {
put_task_struct(priv->task);
priv->task = NULL;
return mm;
}
down_read(&mm->mmap_sem);
/* start from the Nth VMA */
for (p = rb_first(&mm->mm_rb); p; p = rb_next(p))
if (n-- == 0)
return p;
return NULL;
}
static void m_stop(struct seq_file *m, void *_vml)
{
struct proc_maps_private *priv = m->private;
if (priv->task) {
struct mm_struct *mm = priv->task->mm;
up_read(&mm->mmap_sem);
mmput(mm);
put_task_struct(priv->task);
}
}
static void *m_next(struct seq_file *m, void *_p, loff_t *pos)
{
struct rb_node *p = _p;
(*pos)++;
return p ? rb_next(p) : NULL;
}
static const struct seq_operations proc_pid_maps_ops = {
.start = m_start,
.next = m_next,
.stop = m_stop,
.show = show_pid_map
};
static const struct seq_operations proc_tid_maps_ops = {
.start = m_start,
.next = m_next,
.stop = m_stop,
.show = show_tid_map
};
static int maps_open(struct inode *inode, struct file *file,
const struct seq_operations *ops)
{
struct proc_maps_private *priv;
int ret = -ENOMEM;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (priv) {
priv->pid = proc_pid(inode);
ret = seq_open(file, ops);
if (!ret) {
struct seq_file *m = file->private_data;
m->private = priv;
} else {
kfree(priv);
}
}
return ret;
}
static int pid_maps_open(struct inode *inode, struct file *file)
{
return maps_open(inode, file, &proc_pid_maps_ops);
}
static int tid_maps_open(struct inode *inode, struct file *file)
{
return maps_open(inode, file, &proc_tid_maps_ops);
}
const struct file_operations proc_pid_maps_operations = {
.open = pid_maps_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
const struct file_operations proc_tid_maps_operations = {
.open = tid_maps_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
| gpl-2.0 |
simark/binutils-gdb | gdb/debug.c | 5 | 1027 | /* Debug printing functions.
Copyright (C) 2014-2021 Free Software Foundation, Inc.
This file is part of GDB.
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; either version 3 of the License, or
(at your option) any later version.
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, see <http://www.gnu.org/licenses/>. */
#include "defs.h"
#include "gdbsupport/common-debug.h"
/* See gdbsupport/common-debug.h. */
int debug_print_depth = 0;
/* See gdbsupport/common-debug.h. */
void
debug_vprintf (const char *fmt, va_list ap)
{
vfprintf_unfiltered (gdb_stdlog, fmt, ap);
}
| gpl-2.0 |
canjiangsu/u-boot-1.3.4-sucj | lib_arm/bootm.c | 5 | 7764 | /*
* (C) Copyright 2002
* Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Marius Groeger <mgroeger@sysgo.de>
*
* Copyright (C) 2001 Erik Mouw (J.A.K.Mouw@its.tudelft.nl)
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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 <common.h>
#include <command.h>
#include <image.h>
#include <zlib.h>
#include <asm/byteorder.h>
DECLARE_GLOBAL_DATA_PTR;
#if defined (CONFIG_SETUP_MEMORY_TAGS) || \
defined (CONFIG_CMDLINE_TAG) || \
defined (CONFIG_INITRD_TAG) || \
defined (CONFIG_SERIAL_TAG) || \
defined (CONFIG_REVISION_TAG) || \
defined (CONFIG_VFD) || \
defined (CONFIG_LCD)
static void setup_start_tag (bd_t *bd);
# ifdef CONFIG_SETUP_MEMORY_TAGS
static void setup_memory_tags (bd_t *bd);
# endif
static void setup_commandline_tag (bd_t *bd, char *commandline);
# ifdef CONFIG_INITRD_TAG
static void setup_initrd_tag (bd_t *bd, ulong initrd_start,
ulong initrd_end);
# endif
static void setup_end_tag (bd_t *bd);
# if defined (CONFIG_VFD) || defined (CONFIG_LCD)
static void setup_videolfb_tag (gd_t *gd);
# endif
static struct tag *params;
#endif /* CONFIG_SETUP_MEMORY_TAGS || CONFIG_CMDLINE_TAG || CONFIG_INITRD_TAG */
extern int do_reset (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[]);
void do_bootm_linux (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[],
bootm_headers_t *images)
{
ulong initrd_start, initrd_end;
ulong ep = 0;
bd_t *bd = gd->bd;
char *s;
int machid = bd->bi_arch_number;
void (*theKernel)(int zero, int arch, uint params);
int ret;
#ifdef CONFIG_CMDLINE_TAG
char *commandline = getenv ("bootargs");
#endif
/* find kernel entry point */
if (images->legacy_hdr_valid) {
ep = image_get_ep (&images->legacy_hdr_os_copy);
#if defined(CONFIG_FIT)
} else if (images->fit_uname_os) {
ret = fit_image_get_entry (images->fit_hdr_os,
images->fit_noffset_os, &ep);
if (ret) {
puts ("Can't get entry point property!\n");
goto error;
}
#endif
} else {
puts ("Could not find kernel entry point!\n");
goto error;
}
theKernel = (void (*)(int, int, uint))ep;
s = getenv ("machid");
if (s) {
machid = simple_strtoul (s, NULL, 16);
printf ("Using machid 0x%x from environment\n", machid);
}
ret = boot_get_ramdisk (argc, argv, images, IH_ARCH_ARM,
&initrd_start, &initrd_end);
if (ret)
goto error;
show_boot_progress (15);
debug ("## Transferring control to Linux (at address %08lx) ...\n",
(ulong) theKernel);
#if defined (CONFIG_SETUP_MEMORY_TAGS) || \
defined (CONFIG_CMDLINE_TAG) || \
defined (CONFIG_INITRD_TAG) || \
defined (CONFIG_SERIAL_TAG) || \
defined (CONFIG_REVISION_TAG) || \
defined (CONFIG_LCD) || \
defined (CONFIG_VFD)
setup_start_tag (bd);
#ifdef CONFIG_SERIAL_TAG
setup_serial_tag (¶ms);
#endif
#ifdef CONFIG_REVISION_TAG
setup_revision_tag (¶ms);
#endif
#ifdef CONFIG_SETUP_MEMORY_TAGS
setup_memory_tags (bd);
#endif
#ifdef CONFIG_CMDLINE_TAG
setup_commandline_tag (bd, commandline);
#endif
#ifdef CONFIG_INITRD_TAG
if (initrd_start && initrd_end)
setup_initrd_tag (bd, initrd_start, initrd_end);
#endif
#if defined (CONFIG_VFD) || defined (CONFIG_LCD)
setup_videolfb_tag ((gd_t *) gd);
#endif
setup_end_tag (bd);
#endif
/* we assume that the kernel is in place */
printf ("\nStarting kernel ...\n\n");
#ifdef CONFIG_USB_DEVICE
{
extern void udc_disconnect (void);
udc_disconnect ();
}
#endif
cleanup_before_linux ();
theKernel (0, machid, bd->bi_boot_params);
/* does not return */
return;
error:
do_reset (cmdtp, flag, argc, argv);
return;
}
#if defined (CONFIG_SETUP_MEMORY_TAGS) || \
defined (CONFIG_CMDLINE_TAG) || \
defined (CONFIG_INITRD_TAG) || \
defined (CONFIG_SERIAL_TAG) || \
defined (CONFIG_REVISION_TAG) || \
defined (CONFIG_LCD) || \
defined (CONFIG_VFD)
static void setup_start_tag (bd_t *bd)
{
params = (struct tag *) bd->bi_boot_params;
params->hdr.tag = ATAG_CORE;
params->hdr.size = tag_size (tag_core);
params->u.core.flags = 0;
params->u.core.pagesize = 0;
params->u.core.rootdev = 0;
params = tag_next (params);
}
#ifdef CONFIG_SETUP_MEMORY_TAGS
static void setup_memory_tags (bd_t *bd)
{
int i;
for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
params->hdr.tag = ATAG_MEM;
params->hdr.size = tag_size (tag_mem32);
params->u.mem.start = bd->bi_dram[i].start;
params->u.mem.size = bd->bi_dram[i].size;
params = tag_next (params);
}
}
#endif /* CONFIG_SETUP_MEMORY_TAGS */
static void setup_commandline_tag (bd_t *bd, char *commandline)
{
char *p;
if (!commandline)
return;
/* eat leading white space */
for (p = commandline; *p == ' '; p++);
/* skip non-existent command lines so the kernel will still
* use its default command line.
*/
if (*p == '\0')
return;
params->hdr.tag = ATAG_CMDLINE;
params->hdr.size =
(sizeof (struct tag_header) + strlen (p) + 1 + 4) >> 2;
strcpy (params->u.cmdline.cmdline, p);
params = tag_next (params);
}
#ifdef CONFIG_INITRD_TAG
static void setup_initrd_tag (bd_t *bd, ulong initrd_start, ulong initrd_end)
{
/* an ATAG_INITRD node tells the kernel where the compressed
* ramdisk can be found. ATAG_RDIMG is a better name, actually.
*/
params->hdr.tag = ATAG_INITRD2;
params->hdr.size = tag_size (tag_initrd);
params->u.initrd.start = initrd_start;
params->u.initrd.size = initrd_end - initrd_start;
params = tag_next (params);
}
#endif /* CONFIG_INITRD_TAG */
#if defined (CONFIG_VFD) || defined (CONFIG_LCD)
extern ulong calc_fbsize (void);
static void setup_videolfb_tag (gd_t *gd)
{
/* An ATAG_VIDEOLFB node tells the kernel where and how large
* the framebuffer for video was allocated (among other things).
* Note that a _physical_ address is passed !
*
* We only use it to pass the address and size, the other entries
* in the tag_videolfb are not of interest.
*/
params->hdr.tag = ATAG_VIDEOLFB;
params->hdr.size = tag_size (tag_videolfb);
params->u.videolfb.lfb_base = (u32) gd->fb_base;
/* Fb size is calculated according to parameters for our panel
*/
params->u.videolfb.lfb_size = calc_fbsize();
params = tag_next (params);
}
#endif /* CONFIG_VFD || CONFIG_LCD */
#ifdef CONFIG_SERIAL_TAG
void setup_serial_tag (struct tag **tmp)
{
struct tag *params = *tmp;
struct tag_serialnr serialnr;
void get_board_serial(struct tag_serialnr *serialnr);
get_board_serial(&serialnr);
params->hdr.tag = ATAG_SERIAL;
params->hdr.size = tag_size (tag_serialnr);
params->u.serialnr.low = serialnr.low;
params->u.serialnr.high= serialnr.high;
params = tag_next (params);
*tmp = params;
}
#endif
#ifdef CONFIG_REVISION_TAG
void setup_revision_tag(struct tag **in_params)
{
u32 rev = 0;
u32 get_board_rev(void);
rev = get_board_rev();
params->hdr.tag = ATAG_REVISION;
params->hdr.size = tag_size (tag_revision);
params->u.revision.rev = rev;
params = tag_next (params);
}
#endif /* CONFIG_REVISION_TAG */
static void setup_end_tag (bd_t *bd)
{
params->hdr.tag = ATAG_NONE;
params->hdr.size = 0;
}
#endif /* CONFIG_SETUP_MEMORY_TAGS || CONFIG_CMDLINE_TAG || CONFIG_INITRD_TAG */
| gpl-2.0 |
renesas-devel/gst-plugins-bad | sys/dshowdecwrapper/gstdshowaudiodec.cpp | 5 | 37894 | /*
* GStreamer DirectShow codecs wrapper
* Copyright <2006, 2007, 2008, 2009, 2010> Fluendo <support@fluendo.com>
* Copyright <2006, 2007, 2008> Pioneers of the Inevitable <songbird@songbirdnest.com>
* Copyright <2007,2008> Sebastien Moutte <sebastien@moutte.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstdshowaudiodec.h"
#include <mmreg.h>
#include <dmoreg.h>
#include <wmcodecdsp.h>
GST_DEBUG_CATEGORY_STATIC (dshowaudiodec_debug);
#define GST_CAT_DEFAULT dshowaudiodec_debug
GST_BOILERPLATE (GstDshowAudioDec, gst_dshowaudiodec, GstElement,
GST_TYPE_ELEMENT);
static void gst_dshowaudiodec_dispose (GObject * object);
static GstStateChangeReturn gst_dshowaudiodec_change_state
(GstElement * element, GstStateChange transition);
/* sink pad overwrites */
static gboolean gst_dshowaudiodec_sink_setcaps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_dshowaudiodec_chain (GstPad * pad, GstBuffer * buffer);
static gboolean gst_dshowaudiodec_sink_event (GstPad * pad, GstEvent * event);
/* utils */
static gboolean gst_dshowaudiodec_create_graph_and_filters (GstDshowAudioDec *
adec);
static gboolean gst_dshowaudiodec_destroy_graph_and_filters (GstDshowAudioDec *
adec);
static gboolean gst_dshowaudiodec_flush (GstDshowAudioDec * adec);
static gboolean gst_dshowaudiodec_get_filter_settings (GstDshowAudioDec * adec);
static gboolean gst_dshowaudiodec_setup_graph (GstDshowAudioDec * adec, GstCaps *caps);
/* All the GUIDs we want are generated from the FOURCC like this */
#define GUID_MEDIASUBTYPE_FROM_FOURCC(fourcc) \
{ fourcc , 0x0000, 0x0010, \
{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 }}
/* WMA we should always use the DMO */
static PreferredFilter preferred_wma_filters[] = {
{&CLSID_CWMADecMediaObject, &DMOCATEGORY_AUDIO_DECODER},
{0}
};
/* Prefer the Vista (DMO) decoder if present, otherwise the XP
* decoder (not a DMO), otherwise fallback to highest-merit */
static const GUID CLSID_XP_MP3_DECODER = {0x38BE3000, 0xDBF4, 0x11D0,
{0x86,0x0E,0x00,0xA0,0x24,0xCF,0xEF,0x6D}};
static PreferredFilter preferred_mp3_filters[] = {
{&CLSID_CMP3DecMediaObject, &DMOCATEGORY_AUDIO_DECODER},
{&CLSID_XP_MP3_DECODER},
{0}
};
/* MPEG 1/2: use the MPEG Audio Decoder filter */
static const GUID CLSID_WINDOWS_MPEG_AUDIO_DECODER =
{0x4A2286E0, 0x7BEF, 0x11CE,
{0x9B, 0xD9, 0x00, 0x00, 0xE2, 0x02, 0x59, 0x9C}};
static PreferredFilter preferred_mpegaudio_filters[] = {
{&CLSID_WINDOWS_MPEG_AUDIO_DECODER},
{0}
};
static const AudioCodecEntry audio_dec_codecs[] = {
{"dshowadec_wma1", "Windows Media Audio 7",
WAVE_FORMAT_MSAUDIO1,
"audio/x-wma, wmaversion = (int) 1",
preferred_wma_filters},
{"dshowadec_wma2", "Windows Media Audio 8",
WAVE_FORMAT_WMAUDIO2,
"audio/x-wma, wmaversion = (int) 2",
preferred_wma_filters},
{"dshowadec_wma3", "Windows Media Audio 9 Professional",
WAVE_FORMAT_WMAUDIO3,
"audio/x-wma, wmaversion = (int) 3",
preferred_wma_filters},
{"dshowadec_wma4", "Windows Media Audio 9 Lossless",
WAVE_FORMAT_WMAUDIO_LOSSLESS,
"audio/x-wma, wmaversion = (int) 4",
preferred_wma_filters},
{"dshowadec_wms", "Windows Media Audio Voice v9",
WAVE_FORMAT_WMAVOICE9,
"audio/x-wms",
preferred_wma_filters},
{"dshowadec_mp3", "MPEG Layer 3 Audio",
WAVE_FORMAT_MPEGLAYER3,
"audio/mpeg, "
"mpegversion = (int) 1, "
"layer = (int)3, "
"rate = (int) [ 8000, 48000 ], "
"channels = (int) [ 1, 2 ], "
"parsed= (boolean) true",
preferred_mp3_filters},
{"dshowadec_mpeg_1_2", "MPEG Layer 1,2 Audio",
WAVE_FORMAT_MPEG,
"audio/mpeg, "
"mpegversion = (int) 1, "
"layer = (int) [ 1, 2 ], "
"rate = (int) [ 8000, 48000 ], "
"channels = (int) [ 1, 2 ], "
"parsed= (boolean) true",
preferred_mpegaudio_filters},
};
HRESULT AudioFakeSink::DoRenderSample(IMediaSample *pMediaSample)
{
GstBuffer *out_buf = NULL;
gboolean in_seg = FALSE;
GstClockTime buf_start, buf_stop;
gint64 clip_start = 0, clip_stop = 0;
guint start_offset = 0, stop_offset;
GstClockTime duration;
if(pMediaSample)
{
BYTE *pBuffer = NULL;
LONGLONG lStart = 0, lStop = 0;
long size = pMediaSample->GetActualDataLength();
pMediaSample->GetPointer(&pBuffer);
pMediaSample->GetTime(&lStart, &lStop);
if (!GST_CLOCK_TIME_IS_VALID (mDec->timestamp)) {
// Convert REFERENCE_TIME to GST_CLOCK_TIME
mDec->timestamp = (GstClockTime)lStart * 100;
}
duration = (lStop - lStart) * 100;
buf_start = mDec->timestamp;
buf_stop = mDec->timestamp + duration;
/* save stop position to start next buffer with it */
mDec->timestamp = buf_stop;
/* check if this buffer is in our current segment */
in_seg = gst_segment_clip (mDec->segment, GST_FORMAT_TIME,
buf_start, buf_stop, &clip_start, &clip_stop);
/* if the buffer is out of segment do not push it downstream */
if (!in_seg) {
GST_DEBUG_OBJECT (mDec,
"buffer is out of segment, start %" GST_TIME_FORMAT " stop %"
GST_TIME_FORMAT, GST_TIME_ARGS (buf_start), GST_TIME_ARGS (buf_stop));
goto done;
}
/* buffer is entirely or partially in-segment, so allocate a
* GstBuffer for output, and clip if required */
/* allocate a new buffer for raw audio */
mDec->last_ret = gst_pad_alloc_buffer (mDec->srcpad,
GST_BUFFER_OFFSET_NONE,
size,
GST_PAD_CAPS (mDec->srcpad), &out_buf);
if (!out_buf) {
GST_WARNING_OBJECT (mDec, "cannot allocate a new GstBuffer");
goto done;
}
/* set buffer properties */
GST_BUFFER_TIMESTAMP (out_buf) = buf_start;
GST_BUFFER_DURATION (out_buf) = duration;
memcpy (GST_BUFFER_DATA (out_buf), pBuffer,
MIN ((unsigned int)size, GST_BUFFER_SIZE (out_buf)));
/* we have to remove some heading samples */
if ((GstClockTime) clip_start > buf_start) {
start_offset = (guint)gst_util_uint64_scale_int (clip_start - buf_start,
mDec->rate, GST_SECOND) * mDec->depth / 8 * mDec->channels;
}
else
start_offset = 0;
/* we have to remove some trailing samples */
if ((GstClockTime) clip_stop < buf_stop) {
stop_offset = (guint)gst_util_uint64_scale_int (buf_stop - clip_stop,
mDec->rate, GST_SECOND) * mDec->depth / 8 * mDec->channels;
}
else
stop_offset = size;
/* truncating */
if ((start_offset != 0) || (stop_offset != (size_t) size)) {
GstBuffer *subbuf = gst_buffer_create_sub (out_buf, start_offset,
stop_offset - start_offset);
if (subbuf) {
gst_buffer_set_caps (subbuf, GST_PAD_CAPS (mDec->srcpad));
gst_buffer_unref (out_buf);
out_buf = subbuf;
}
}
GST_BUFFER_TIMESTAMP (out_buf) = clip_start;
GST_BUFFER_DURATION (out_buf) = clip_stop - clip_start;
/* replace the saved stop position by the clipped one */
mDec->timestamp = clip_stop;
GST_DEBUG_OBJECT (mDec,
"push_buffer (size %d)=> pts %" GST_TIME_FORMAT " stop %" GST_TIME_FORMAT
" duration %" GST_TIME_FORMAT, size,
GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (out_buf)),
GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (out_buf) +
GST_BUFFER_DURATION (out_buf)),
GST_TIME_ARGS (GST_BUFFER_DURATION (out_buf)));
mDec->last_ret = gst_pad_push (mDec->srcpad, out_buf);
}
done:
return S_OK;
}
HRESULT AudioFakeSink::CheckMediaType(const CMediaType *pmt)
{
if(pmt != NULL)
{
/* The Vista MP3 decoder (and possibly others?) outputs an
* AM_MEDIA_TYPE with the wrong cbFormat. So, rather than using
* CMediaType.operator==, we implement a sufficient check ourselves.
* I think this is a bug in the MP3 decoder.
*/
if (IsEqualGUID (pmt->majortype, m_MediaType.majortype) &&
IsEqualGUID (pmt->subtype, m_MediaType.subtype) &&
IsEqualGUID (pmt->formattype, m_MediaType.formattype))
{
/* Types are the same at the top-level. Now, we need to compare
* the format blocks.
* We special case WAVEFORMATEX to not check that
* pmt->cbFormat == m_MediaType.cbFormat, though the actual format
* blocks must still be the same.
*/
if (pmt->formattype == FORMAT_WaveFormatEx) {
if (pmt->cbFormat >= sizeof (WAVEFORMATEX) &&
m_MediaType.cbFormat >= sizeof (WAVEFORMATEX))
{
WAVEFORMATEX *wf1 = (WAVEFORMATEX *)pmt->pbFormat;
WAVEFORMATEX *wf2 = (WAVEFORMATEX *)m_MediaType.pbFormat;
if (wf1->cbSize == wf2->cbSize &&
memcmp (wf1, wf2, sizeof(WAVEFORMATEX) + wf1->cbSize) == 0)
return S_OK;
}
}
else {
if (pmt->cbFormat == m_MediaType.cbFormat &&
pmt->cbFormat == 0 ||
(pmt->pbFormat != NULL && m_MediaType.pbFormat != NULL &&
memcmp (pmt->pbFormat, m_MediaType.pbFormat, pmt->cbFormat) == 0))
return S_OK;
}
}
}
return S_FALSE;
}
static void
gst_dshowaudiodec_base_init (gpointer klass)
{
GstDshowAudioDecClass *audiodec_class = (GstDshowAudioDecClass *) klass;
GstPadTemplate *src, *sink;
GstCaps *srccaps, *sinkcaps;
GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
GstElementDetails details;
const AudioCodecEntry *tmp;
gpointer qdata;
qdata = g_type_get_qdata (G_OBJECT_CLASS_TYPE (klass), DSHOW_CODEC_QDATA);
/* element details */
tmp = audiodec_class->entry = (AudioCodecEntry *) qdata;
details.longname = g_strdup_printf ("DirectShow %s Decoder Wrapper",
tmp->element_longname);
details.klass = g_strdup ("Codec/Decoder/Audio");
details.description = g_strdup_printf ("DirectShow %s Decoder Wrapper",
tmp->element_longname);
details.author = "Sebastien Moutte <sebastien@moutte.net>";
gst_element_class_set_details (element_class, &details);
g_free (details.longname);
g_free (details.klass);
g_free (details.description);
sinkcaps = gst_caps_from_string (tmp->sinkcaps);
srccaps = gst_caps_from_string (
"audio/x-raw-int,"
"width = (int)[1, 32],"
"depth = (int)[1, 32],"
"rate = (int)[1, MAX],"
"channels = (int)[1, MAX],"
"signed = (boolean)true,"
"endianness = (int)" G_STRINGIFY(G_LITTLE_ENDIAN));
sink = gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, sinkcaps);
src = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS, srccaps);
/* register */
gst_element_class_add_pad_template (element_class, src);
gst_element_class_add_pad_template (element_class, sink);
gst_object_unref (src);
gst_object_unref (sink);
}
static void
gst_dshowaudiodec_class_init (GstDshowAudioDecClass * klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_dshowaudiodec_dispose);
gstelement_class->change_state =
GST_DEBUG_FUNCPTR (gst_dshowaudiodec_change_state);
parent_class = (GstElementClass *) g_type_class_peek_parent (klass);
}
static void
gst_dshowaudiodec_com_thread (GstDshowAudioDec * adec)
{
HRESULT res;
g_mutex_lock (adec->com_init_lock);
/* Initialize COM with a MTA for this process. This thread will
* be the first one to enter the apartement and the last one to leave
* it, unitializing COM properly */
res = CoInitializeEx (0, COINIT_MULTITHREADED);
if (res == S_FALSE)
GST_WARNING_OBJECT (adec, "COM has been already initialized in the same process");
else if (res == RPC_E_CHANGED_MODE)
GST_WARNING_OBJECT (adec, "The concurrency model of COM has changed.");
else
GST_INFO_OBJECT (adec, "COM intialized succesfully");
adec->comInitialized = TRUE;
/* Signal other threads waiting on this condition that COM was initialized */
g_cond_signal (adec->com_initialized);
g_mutex_unlock (adec->com_init_lock);
/* Wait until the unitialize condition is met to leave the COM apartement */
g_mutex_lock (adec->com_deinit_lock);
g_cond_wait (adec->com_uninitialize, adec->com_deinit_lock);
CoUninitialize ();
GST_INFO_OBJECT (adec, "COM unintialized succesfully");
adec->comInitialized = FALSE;
g_cond_signal (adec->com_uninitialized);
g_mutex_unlock (adec->com_deinit_lock);
}
static void
gst_dshowaudiodec_init (GstDshowAudioDec * adec,
GstDshowAudioDecClass * adec_class)
{
GstElementClass *element_class = GST_ELEMENT_GET_CLASS (adec);
/* setup pads */
adec->sinkpad =
gst_pad_new_from_template (gst_element_class_get_pad_template
(element_class, "sink"), "sink");
gst_pad_set_setcaps_function (adec->sinkpad, gst_dshowaudiodec_sink_setcaps);
gst_pad_set_event_function (adec->sinkpad, gst_dshowaudiodec_sink_event);
gst_pad_set_chain_function (adec->sinkpad, gst_dshowaudiodec_chain);
gst_element_add_pad (GST_ELEMENT (adec), adec->sinkpad);
adec->srcpad =
gst_pad_new_from_template (gst_element_class_get_pad_template
(element_class, "src"), "src");
gst_element_add_pad (GST_ELEMENT (adec), adec->srcpad);
adec->fakesrc = NULL;
adec->fakesink = NULL;
adec->decfilter = 0;
adec->filtergraph = 0;
adec->mediafilter = 0;
adec->timestamp = GST_CLOCK_TIME_NONE;
adec->segment = gst_segment_new ();
adec->setup = FALSE;
adec->depth = 0;
adec->bitrate = 0;
adec->block_align = 0;
adec->channels = 0;
adec->rate = 0;
adec->layer = 0;
adec->codec_data = NULL;
adec->last_ret = GST_FLOW_OK;
adec->com_init_lock = g_mutex_new();
adec->com_deinit_lock = g_mutex_new();
adec->com_initialized = g_cond_new();
adec->com_uninitialize = g_cond_new();
adec->com_uninitialized = g_cond_new();
g_mutex_lock (adec->com_init_lock);
/* create the COM initialization thread */
g_thread_create ((GThreadFunc)gst_dshowaudiodec_com_thread,
adec, FALSE, NULL);
/* wait until the COM thread signals that COM has been initialized */
g_cond_wait (adec->com_initialized, adec->com_init_lock);
g_mutex_unlock (adec->com_init_lock);
}
static void
gst_dshowaudiodec_dispose (GObject * object)
{
GstDshowAudioDec *adec = (GstDshowAudioDec *) (object);
if (adec->segment) {
gst_segment_free (adec->segment);
adec->segment = NULL;
}
if (adec->codec_data) {
gst_buffer_unref (adec->codec_data);
adec->codec_data = NULL;
}
/* signal the COM thread that it sould uninitialize COM */
if (adec->comInitialized) {
g_mutex_lock (adec->com_deinit_lock);
g_cond_signal (adec->com_uninitialize);
g_cond_wait (adec->com_uninitialized, adec->com_deinit_lock);
g_mutex_unlock (adec->com_deinit_lock);
}
g_mutex_free (adec->com_init_lock);
g_mutex_free (adec->com_deinit_lock);
g_cond_free (adec->com_initialized);
g_cond_free (adec->com_uninitialize);
g_cond_free (adec->com_uninitialized);
G_OBJECT_CLASS (parent_class)->dispose (object);
}
static GstStateChangeReturn
gst_dshowaudiodec_change_state (GstElement * element, GstStateChange transition)
{
GstDshowAudioDec *adec = (GstDshowAudioDec *) (element);
switch (transition) {
case GST_STATE_CHANGE_NULL_TO_READY:
if (!gst_dshowaudiodec_create_graph_and_filters (adec))
return GST_STATE_CHANGE_FAILURE;
break;
case GST_STATE_CHANGE_READY_TO_PAUSED:
break;
case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
break;
case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
break;
case GST_STATE_CHANGE_PAUSED_TO_READY:
adec->depth = 0;
adec->bitrate = 0;
adec->block_align = 0;
adec->channels = 0;
adec->rate = 0;
adec->layer = 0;
if (adec->codec_data) {
gst_buffer_unref (adec->codec_data);
adec->codec_data = NULL;
}
break;
case GST_STATE_CHANGE_READY_TO_NULL:
if (!gst_dshowaudiodec_destroy_graph_and_filters (adec))
return GST_STATE_CHANGE_FAILURE;
break;
default:
break;
}
return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
}
static gboolean
gst_dshowaudiodec_sink_setcaps (GstPad * pad, GstCaps * caps)
{
gboolean ret = FALSE;
GstDshowAudioDec *adec = (GstDshowAudioDec *) gst_pad_get_parent (pad);
GstStructure *s = gst_caps_get_structure (caps, 0);
const GValue *v = NULL;
adec->timestamp = GST_CLOCK_TIME_NONE;
/* read data, only rate and channels are needed */
if (!gst_structure_get_int (s, "rate", &adec->rate) ||
!gst_structure_get_int (s, "channels", &adec->channels)) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("error getting audio specs from caps"), (NULL));
goto end;
}
gst_structure_get_int (s, "depth", &adec->depth);
gst_structure_get_int (s, "bitrate", &adec->bitrate);
gst_structure_get_int (s, "block_align", &adec->block_align);
gst_structure_get_int (s, "layer", &adec->layer);
if (adec->codec_data) {
gst_buffer_unref (adec->codec_data);
adec->codec_data = NULL;
}
if ((v = gst_structure_get_value (s, "codec_data")))
adec->codec_data = gst_buffer_ref (gst_value_get_buffer (v));
ret = gst_dshowaudiodec_setup_graph (adec, caps);
end:
gst_object_unref (adec);
return ret;
}
static GstFlowReturn
gst_dshowaudiodec_chain (GstPad * pad, GstBuffer * buffer)
{
GstDshowAudioDec *adec = (GstDshowAudioDec *) gst_pad_get_parent (pad);
bool discont = FALSE;
if (!adec->setup) {
/* we are not set up */
GST_WARNING_OBJECT (adec, "Decoder not set up, failing");
adec->last_ret = GST_FLOW_WRONG_STATE;
goto beach;
}
if (adec->last_ret < GST_FLOW_UNEXPECTED) {
GST_DEBUG_OBJECT (adec, "last decoding iteration generated a fatal error "
"%s", gst_flow_get_name (adec->last_ret));
goto beach;
}
GST_CAT_DEBUG_OBJECT (dshowaudiodec_debug, adec, "chain (size %d)=> pts %"
GST_TIME_FORMAT " stop %" GST_TIME_FORMAT,
GST_BUFFER_SIZE (buffer), GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer) +
GST_BUFFER_DURATION (buffer)));
/* if the incoming buffer has discont flag set => flush decoder data */
if (buffer && GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT)) {
GST_CAT_DEBUG_OBJECT (dshowaudiodec_debug, adec,
"this buffer has a DISCONT flag (%" GST_TIME_FORMAT "), flushing",
GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)));
gst_dshowaudiodec_flush (adec);
discont = TRUE;
}
/* push the buffer to the directshow decoder */
adec->fakesrc->GetOutputPin()->PushBuffer (
GST_BUFFER_DATA (buffer), GST_BUFFER_TIMESTAMP (buffer),
GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer),
GST_BUFFER_SIZE (buffer), (bool)discont);
beach:
gst_buffer_unref (buffer);
gst_object_unref (adec);
return adec->last_ret;
}
static gboolean
gst_dshowaudiodec_sink_event (GstPad * pad, GstEvent * event)
{
gboolean ret = TRUE;
GstDshowAudioDec *adec = (GstDshowAudioDec *) gst_pad_get_parent (pad);
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_FLUSH_STOP:{
gst_dshowaudiodec_flush (adec);
ret = gst_pad_event_default (pad, event);
break;
}
case GST_EVENT_NEWSEGMENT:
{
GstFormat format;
gdouble rate;
gint64 start, stop, time;
gboolean update;
gst_event_parse_new_segment (event, &update, &rate, &format, &start,
&stop, &time);
GST_CAT_DEBUG_OBJECT (dshowaudiodec_debug, adec,
"received new segment from %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
if (update) {
GST_CAT_DEBUG_OBJECT (dshowaudiodec_debug, adec,
"closing current segment flushing..");
gst_dshowaudiodec_flush (adec);
}
/* save the new segment in our local current segment */
gst_segment_set_newsegment (adec->segment, update, rate, format, start,
stop, time);
ret = gst_pad_event_default (pad, event);
break;
}
default:
ret = gst_pad_event_default (pad, event);
break;
}
gst_object_unref (adec);
return ret;
}
static gboolean
gst_dshowaudiodec_flush (GstDshowAudioDec * adec)
{
if (!adec->fakesrc)
return FALSE;
/* flush dshow decoder and reset timestamp */
adec->fakesrc->GetOutputPin()->Flush();
adec->timestamp = GST_CLOCK_TIME_NONE;
adec->last_ret = GST_FLOW_OK;
return TRUE;
}
static AM_MEDIA_TYPE *
dshowaudiodec_set_input_format (GstDshowAudioDec *adec, GstCaps *caps)
{
AM_MEDIA_TYPE *mediatype;
WAVEFORMATEX *format;
GstDshowAudioDecClass *klass =
(GstDshowAudioDecClass *) G_OBJECT_GET_CLASS (adec);
const AudioCodecEntry *codec_entry = klass->entry;
int size;
mediatype = (AM_MEDIA_TYPE *)g_malloc0 (sizeof(AM_MEDIA_TYPE));
mediatype->majortype = MEDIATYPE_Audio;
GUID subtype = GUID_MEDIASUBTYPE_FROM_FOURCC (0x00000000);
subtype.Data1 = codec_entry->format;
mediatype->subtype = subtype;
mediatype->bFixedSizeSamples = TRUE;
mediatype->bTemporalCompression = FALSE;
if (adec->block_align)
mediatype->lSampleSize = adec->block_align;
else
mediatype->lSampleSize = 8192; /* need to evaluate it dynamically */
mediatype->formattype = FORMAT_WaveFormatEx;
/* We need this special behaviour for layers 1 and 2 (layer 3 uses a different
* decoder which doesn't need this */
if (adec->layer == 1 || adec->layer == 2) {
MPEG1WAVEFORMAT *mpeg1_format;
int samples, version;
GstStructure *structure = gst_caps_get_structure (caps, 0);
size = sizeof (MPEG1WAVEFORMAT);
format = (WAVEFORMATEX *)g_malloc0 (size);
format->cbSize = sizeof (MPEG1WAVEFORMAT) - sizeof (WAVEFORMATEX);
format->wFormatTag = WAVE_FORMAT_MPEG;
mpeg1_format = (MPEG1WAVEFORMAT *) format;
mpeg1_format->wfx.nChannels = adec->channels;
if (adec->channels == 2)
mpeg1_format->fwHeadMode = ACM_MPEG_STEREO;
else
mpeg1_format->fwHeadMode = ACM_MPEG_SINGLECHANNEL;
mpeg1_format->fwHeadModeExt = 0;
mpeg1_format->wHeadEmphasis = 0;
mpeg1_format->fwHeadFlags = 0;
switch (adec->layer) {
case 1:
mpeg1_format->fwHeadLayer = ACM_MPEG_LAYER3;
break;
case 2:
mpeg1_format->fwHeadLayer = ACM_MPEG_LAYER2;
break;
case 3:
mpeg1_format->fwHeadLayer = ACM_MPEG_LAYER1;
break;
};
gst_structure_get_int (structure, "mpegaudioversion", &version);
if (adec->layer == 1) {
samples = 384;
} else {
if (version == 1) {
samples = 576;
} else {
samples = 1152;
}
}
mpeg1_format->wfx.nBlockAlign = (WORD) samples;
mpeg1_format->wfx.nSamplesPerSec = adec->rate;
mpeg1_format->dwHeadBitrate = 128000; /* This doesn't seem to matter */
mpeg1_format->wfx.nAvgBytesPerSec = mpeg1_format->dwHeadBitrate / 8;
}
else
{
size = sizeof (WAVEFORMATEX) +
(adec->codec_data ? GST_BUFFER_SIZE (adec->codec_data) : 0);
if (adec->layer == 3) {
MPEGLAYER3WAVEFORMAT *mp3format;
/* The WinXP mp3 decoder doesn't actually check the size of this structure,
* but requires that this be allocated and filled out (or we get obscure
* random crashes)
*/
size = sizeof (MPEGLAYER3WAVEFORMAT);
mp3format = (MPEGLAYER3WAVEFORMAT *)g_malloc0 (size);
format = (WAVEFORMATEX *)mp3format;
format->cbSize = MPEGLAYER3_WFX_EXTRA_BYTES;
mp3format->wID = MPEGLAYER3_ID_MPEG;
mp3format->fdwFlags = MPEGLAYER3_FLAG_PADDING_ISO; /* No idea what this means for a decoder */
/* The XP decoder divides by nBlockSize, so we must set this to a
non-zero value, but it doesn't matter what - this is meaningless
for VBR mp3 anyway */
mp3format->nBlockSize = 1;
mp3format->nFramesPerBlock = 1;
mp3format->nCodecDelay = 0;
}
else {
format = (WAVEFORMATEX *)g_malloc0 (size);
if (adec->codec_data) { /* Codec data is appended after our header */
memcpy (((guchar *) format) + sizeof (WAVEFORMATEX),
GST_BUFFER_DATA (adec->codec_data),
GST_BUFFER_SIZE (adec->codec_data));
format->cbSize = GST_BUFFER_SIZE (adec->codec_data);
}
}
format->wFormatTag = codec_entry->format;
format->nChannels = adec->channels;
format->nSamplesPerSec = adec->rate;
format->nAvgBytesPerSec = adec->bitrate / 8;
format->nBlockAlign = adec->block_align;
format->wBitsPerSample = adec->depth;
}
mediatype->cbFormat = size;
mediatype->pbFormat = (BYTE *) format;
return mediatype;
}
static AM_MEDIA_TYPE *
dshowaudiodec_set_output_format (GstDshowAudioDec *adec)
{
AM_MEDIA_TYPE *mediatype;
WAVEFORMATEX *format;
GstDshowAudioDecClass *klass =
(GstDshowAudioDecClass *) G_OBJECT_GET_CLASS (adec);
const AudioCodecEntry *codec_entry = klass->entry;
if (!gst_dshowaudiodec_get_filter_settings (adec)) {
return NULL;
}
format = (WAVEFORMATEX *)g_malloc0(sizeof (WAVEFORMATEX));
format->wFormatTag = WAVE_FORMAT_PCM;
format->wBitsPerSample = adec->depth;
format->nChannels = adec->channels;
format->nBlockAlign = adec->channels * (adec->depth / 8);
format->nSamplesPerSec = adec->rate;
format->nAvgBytesPerSec = format->nBlockAlign * adec->rate;
mediatype = (AM_MEDIA_TYPE *)g_malloc0(sizeof (AM_MEDIA_TYPE));
mediatype->majortype = MEDIATYPE_Audio;
GUID subtype = GUID_MEDIASUBTYPE_FROM_FOURCC (WAVE_FORMAT_PCM);
mediatype->subtype = subtype;
mediatype->bFixedSizeSamples = TRUE;
mediatype->bTemporalCompression = FALSE;
mediatype->lSampleSize = format->nBlockAlign;
mediatype->formattype = FORMAT_WaveFormatEx;
mediatype->cbFormat = sizeof (WAVEFORMATEX);
mediatype->pbFormat = (BYTE *)format;
return mediatype;
}
static void
dshowadec_free_mediatype (AM_MEDIA_TYPE *mediatype)
{
if (mediatype->pbFormat)
g_free (mediatype->pbFormat);
g_free (mediatype);
}
static gboolean
gst_dshowaudiodec_setup_graph (GstDshowAudioDec * adec, GstCaps *caps)
{
gboolean ret = FALSE;
GstDshowAudioDecClass *klass =
(GstDshowAudioDecClass *) G_OBJECT_GET_CLASS (adec);
HRESULT hres;
GstCaps *outcaps;
AM_MEDIA_TYPE *output_mediatype = NULL;
AM_MEDIA_TYPE *input_mediatype = NULL;
CComPtr<IPin> output_pin;
CComPtr<IPin> input_pin;
const AudioCodecEntry *codec_entry = klass->entry;
CComQIPtr<IBaseFilter> srcfilter;
CComQIPtr<IBaseFilter> sinkfilter;
input_mediatype = dshowaudiodec_set_input_format (adec, caps);
adec->fakesrc->GetOutputPin()->SetMediaType (input_mediatype);
srcfilter = adec->fakesrc;
/* connect our fake source to decoder */
output_pin = gst_dshow_get_pin_from_filter (srcfilter, PINDIR_OUTPUT);
if (!output_pin) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Can't get output pin from our directshow fakesrc filter"), (NULL));
goto end;
}
input_pin = gst_dshow_get_pin_from_filter (adec->decfilter, PINDIR_INPUT);
if (!input_pin) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Can't get input pin from decoder filter"), (NULL));
goto end;
}
hres = adec->filtergraph->ConnectDirect (output_pin, input_pin,
NULL);
if (hres != S_OK) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Can't connect fakesrc with decoder (error=%x)", hres), (NULL));
goto end;
}
output_mediatype = dshowaudiodec_set_output_format (adec);
if (!output_mediatype) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Can't get audio output format from decoder"), (NULL));
goto end;
}
adec->fakesink->SetMediaType(output_mediatype);
outcaps = gst_caps_new_simple ("audio/x-raw-int",
"width", G_TYPE_INT, adec->depth,
"depth", G_TYPE_INT, adec->depth,
"rate", G_TYPE_INT, adec->rate,
"channels", G_TYPE_INT, adec->channels,
"signed", G_TYPE_BOOLEAN, TRUE,
"endianness", G_TYPE_INT, G_LITTLE_ENDIAN,
NULL);
if (!gst_pad_set_caps (adec->srcpad, outcaps)) {
gst_caps_unref (outcaps);
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Failed to negotiate output"), (NULL));
goto end;
}
gst_caps_unref (outcaps);
/* connect the decoder to our fake sink */
output_pin = gst_dshow_get_pin_from_filter (adec->decfilter, PINDIR_OUTPUT);
if (!output_pin) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Can't get output pin from our decoder filter"), (NULL));
goto end;
}
sinkfilter = adec->fakesink;
input_pin = gst_dshow_get_pin_from_filter (sinkfilter, PINDIR_INPUT);
if (!input_pin) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Can't get input pin from our directshow fakesink filter"), (NULL));
goto end;
}
hres = adec->filtergraph->ConnectDirect(output_pin, input_pin, NULL);
if (hres != S_OK) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Can't connect decoder with fakesink (error=%x)", hres), (NULL));
goto end;
}
hres = adec->mediafilter->Run (-1);
if (hres != S_OK) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("Can't run the directshow graph (error=%x)", hres), (NULL));
goto end;
}
ret = TRUE;
adec->setup = TRUE;
end:
if (input_mediatype)
dshowadec_free_mediatype (input_mediatype);
if (output_mediatype)
dshowadec_free_mediatype (output_mediatype);
return ret;
}
static gboolean
gst_dshowaudiodec_get_filter_settings (GstDshowAudioDec * adec)
{
CComPtr<IPin> output_pin;
CComPtr<IEnumMediaTypes> enum_mediatypes;
HRESULT hres;
ULONG fetched;
BOOL ret = FALSE;
if (adec->decfilter == 0)
return FALSE;
output_pin = gst_dshow_get_pin_from_filter (adec->decfilter, PINDIR_OUTPUT);
if (!output_pin) {
GST_ELEMENT_ERROR (adec, CORE, NEGOTIATION,
("failed getting ouput pin from the decoder"), (NULL));
return FALSE;
}
hres = output_pin->EnumMediaTypes (&enum_mediatypes);
if (hres == S_OK && enum_mediatypes) {
AM_MEDIA_TYPE *mediatype = NULL;
enum_mediatypes->Reset();
while (!ret && enum_mediatypes->Next(1, &mediatype, &fetched) == S_OK)
{
if (IsEqualGUID (mediatype->subtype, MEDIASUBTYPE_PCM) &&
IsEqualGUID (mediatype->formattype, FORMAT_WaveFormatEx))
{
WAVEFORMATEX *audio_info = (WAVEFORMATEX *) mediatype->pbFormat;
adec->channels = audio_info->nChannels;
adec->depth = audio_info->wBitsPerSample;
adec->rate = audio_info->nSamplesPerSec;
ret = TRUE;
}
DeleteMediaType (mediatype);
}
}
return ret;
}
static gboolean
gst_dshowaudiodec_create_graph_and_filters (GstDshowAudioDec * adec)
{
HRESULT hres;
GstDshowAudioDecClass *klass =
(GstDshowAudioDecClass *) G_OBJECT_GET_CLASS (adec);
CComQIPtr<IBaseFilter> srcfilter;
CComQIPtr<IBaseFilter> sinkfilter;
GUID insubtype = GUID_MEDIASUBTYPE_FROM_FOURCC (klass->entry->format);
GUID outsubtype = GUID_MEDIASUBTYPE_FROM_FOURCC (WAVE_FORMAT_PCM);
/* create the filter graph manager object */
hres = adec->filtergraph.CoCreateInstance (
CLSID_FilterGraph, NULL, CLSCTX_INPROC);
if (FAILED (hres)) {
GST_ELEMENT_ERROR (adec, STREAM, FAILED,
("Can't create an instance of the directshow graph manager (error=%d)",
hres), (NULL));
goto error;
}
hres = adec->filtergraph->QueryInterface (&adec->mediafilter);
if (FAILED (hres)) {
GST_WARNING_OBJECT (adec, "Can't QI filtergraph to mediafilter");
goto error;
}
/* create fake src filter */
adec->fakesrc = new FakeSrc();
/* Created with a refcount of zero, so increment that */
adec->fakesrc->AddRef();
/* create decoder filter */
adec->decfilter = gst_dshow_find_filter (MEDIATYPE_Audio,
insubtype,
MEDIATYPE_Audio,
outsubtype,
klass->entry->preferred_filters);
if (adec->decfilter == NULL) {
GST_ELEMENT_ERROR (adec, STREAM, FAILED,
("Can't create an instance of the decoder filter"), (NULL));
goto error;
}
/* create fake sink filter */
adec->fakesink = new AudioFakeSink(adec);
/* Created with a refcount of zero, so increment that */
adec->fakesink->AddRef();
/* add filters to the graph */
srcfilter = adec->fakesrc;
hres = adec->filtergraph->AddFilter (srcfilter, L"src");
if (hres != S_OK) {
GST_ELEMENT_ERROR (adec, STREAM, FAILED,
("Can't add fakesrc filter to the graph (error=%d)", hres), (NULL));
goto error;
}
hres = adec->filtergraph->AddFilter(adec->decfilter, L"decoder");
if (hres != S_OK) {
GST_ELEMENT_ERROR (adec, STREAM, FAILED,
("Can't add decoder filter to the graph (error=%d)", hres), (NULL));
goto error;
}
sinkfilter = adec->fakesink;
hres = adec->filtergraph->AddFilter(sinkfilter, L"sink");
if (hres != S_OK) {
GST_ELEMENT_ERROR (adec, STREAM, FAILED,
("Can't add fakesink filter to the graph (error=%d)", hres), (NULL));
goto error;
}
return TRUE;
error:
if (adec->fakesrc) {
adec->fakesrc->Release();
adec->fakesrc = NULL;
}
if (adec->fakesink) {
adec->fakesink->Release();
adec->fakesink = NULL;
}
adec->decfilter = 0;
adec->mediafilter = 0;
adec->filtergraph = 0;
return FALSE;
}
static gboolean
gst_dshowaudiodec_destroy_graph_and_filters (GstDshowAudioDec * adec)
{
if (adec->mediafilter) {
adec->mediafilter->Stop();
}
if (adec->fakesrc) {
if (adec->filtergraph) {
CComQIPtr<IBaseFilter> filter = adec->fakesrc;
adec->filtergraph->RemoveFilter(filter);
}
adec->fakesrc->Release();
adec->fakesrc = NULL;
}
if (adec->decfilter) {
if (adec->filtergraph)
adec->filtergraph->RemoveFilter(adec->decfilter);
adec->decfilter = 0;
}
if (adec->fakesink) {
if (adec->filtergraph) {
CComQIPtr<IBaseFilter> filter = adec->fakesink;
adec->filtergraph->RemoveFilter(filter);
}
adec->fakesink->Release();
adec->fakesink = NULL;
}
adec->mediafilter = 0;
adec->filtergraph = 0;
adec->setup = FALSE;
return TRUE;
}
gboolean
dshow_adec_register (GstPlugin * plugin)
{
GTypeInfo info = {
sizeof (GstDshowAudioDecClass),
(GBaseInitFunc) gst_dshowaudiodec_base_init,
NULL,
(GClassInitFunc) gst_dshowaudiodec_class_init,
NULL,
NULL,
sizeof (GstDshowAudioDec),
0,
(GInstanceInitFunc) gst_dshowaudiodec_init,
};
gint i;
HRESULT hr;
GST_DEBUG_CATEGORY_INIT (dshowaudiodec_debug, "dshowaudiodec", 0,
"Directshow filter audio decoder");
hr = CoInitialize(0);
for (i = 0; i < sizeof (audio_dec_codecs) / sizeof (AudioCodecEntry); i++) {
GType type;
CComPtr<IBaseFilter> filter;
GUID insubtype = GUID_MEDIASUBTYPE_FROM_FOURCC (audio_dec_codecs[i].format);
GUID outsubtype = GUID_MEDIASUBTYPE_FROM_FOURCC (WAVE_FORMAT_PCM);
filter = gst_dshow_find_filter (MEDIATYPE_Audio,
insubtype,
MEDIATYPE_Audio,
outsubtype,
audio_dec_codecs[i].preferred_filters);
if (filter)
{
GST_DEBUG ("Registering %s", audio_dec_codecs[i].element_name);
type = g_type_register_static (GST_TYPE_ELEMENT,
audio_dec_codecs[i].element_name, &info, (GTypeFlags)0);
g_type_set_qdata (type, DSHOW_CODEC_QDATA, (gpointer) (audio_dec_codecs + i));
if (!gst_element_register (plugin, audio_dec_codecs[i].element_name,
GST_RANK_SECONDARY, type)) {
return FALSE;
}
GST_CAT_DEBUG (dshowaudiodec_debug, "Registered %s",
audio_dec_codecs[i].element_name);
}
else {
GST_DEBUG ("Element %s not registered "
"(the format is not supported by the system)",
audio_dec_codecs[i].element_name);
}
}
if (SUCCEEDED(hr))
CoUninitialize ();
return TRUE;
}
| gpl-2.0 |
kelchuan/snac_thesis | StGermain/Base/Automation/src/VariableAllVC.c | 5 | 19954 | /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**
** Copyright (C), 2003, Victorian Partnership for Advanced Computing (VPAC) Ltd, 110 Victoria Street, Melbourne, 3053, Australia.
**
** Authors:
** Stevan M. Quenette, Senior Software Engineer, VPAC. (steve@vpac.org)
** Patrick D. Sunter, Software Engineer, VPAC. (pds@vpac.org)
** Luke J. Hodkinson, Computational Engineer, VPAC. (lhodkins@vpac.org)
** Siew-Ching Tan, Software Engineer, VPAC. (siew@vpac.org)
** Alan H. Lo, Computational Engineer, VPAC. (alan@vpac.org)
** Raquibul Hassan, Computational Engineer, VPAC. (raq@vpac.org)
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library 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
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
**
** $Id: VariableAllVC.c 2509 2005-01-10 23:39:07Z LukeHodkinson $
**
**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <mpi.h>
#include "Base/Foundation/Foundation.h"
#include "Base/IO/IO.h"
#include "Base/Container/Container.h"
#include "types.h"
#include "shortcuts.h"
#include "Stg_Component.h"
#include "Stg_ComponentFactory.h"
#include "Variable.h"
#include "Variable_Register.h"
#include "ConditionFunction.h"
#include "ConditionFunction_Register.h"
#include "VariableCondition.h"
#include "VariableAllVC.h"
#include <string.h>
#include <assert.h>
const Type VariableAllVC_Type = "VariableAllVC";
const Name defaultVariableAllVCName = "defaultVariableAllVCName";
/*--------------------------------------------------------------------------------------------------------------------------
** Constructor
*/
VariableCondition* VariableAllVC_Factory(
Variable_Register* variable_Register,
ConditionFunction_Register* conFunc_Register,
Dictionary* dictionary,
void* data )
{
return (VariableCondition*)VariableAllVC_New( defaultVariableAllVCName, NULL, variable_Register, conFunc_Register, dictionary, data );
}
VariableAllVC* VariableAllVC_New(
Name name,
Name _dictionaryEntryName,
Variable_Register* variable_Register,
ConditionFunction_Register* conFunc_Register,
Dictionary* dictionary,
void* data )
{
return _VariableAllVC_New(
sizeof(VariableAllVC),
VariableAllVC_Type,
_VariableAllVC_Delete,
_VariableAllVC_Print,
_VariableAllVC_Copy,
(Stg_Component_DefaultConstructorFunction*)VariableAllVC_DefaultNew,
_VariableCondition_Construct,
_VariableAllVC_Build,
_VariableCondition_Initialise,
_VariableCondition_Execute,
_VariableCondition_Destroy,
name,
True,
_VariableAllVC_BuildSelf,
_VariableAllVC_PrintConcise,
_VariableAllVC_ReadDictionary,
_VariableAllVC_GetSet,
_VariableAllVC_GetVariableCount,
_VariableAllVC_GetVariableIndex,
_VariableAllVC_GetValueIndex,
_VariableAllVC_GetValueCount,
_VariableAllVC_GetValue,
_dictionaryEntryName,
variable_Register,
conFunc_Register,
dictionary,
data );
}
VariableAllVC* VariableAllVC_DefaultNew( Name name )
{
return (VariableAllVC*)_VariableAllVC_New(
sizeof(VariableAllVC),
VariableAllVC_Type,
_VariableAllVC_Delete,
_VariableAllVC_Print,
_VariableAllVC_Copy,
(Stg_Component_DefaultConstructorFunction*)VariableAllVC_DefaultNew,
_VariableCondition_Construct,
_VariableAllVC_Build,
_VariableCondition_Initialise,
_VariableCondition_Execute,
_VariableCondition_Destroy,
name,
False,
_VariableAllVC_BuildSelf,
_VariableAllVC_PrintConcise,
_VariableAllVC_ReadDictionary,
_VariableAllVC_GetSet,
_VariableAllVC_GetVariableCount,
_VariableAllVC_GetVariableIndex,
_VariableAllVC_GetValueIndex,
_VariableAllVC_GetValueCount,
_VariableAllVC_GetValue,
NULL,
NULL/*variable_Register*/,
NULL/*conFunc_Register*/,
NULL,
NULL );
}
void VariableAllVC_Init(
Name name,
Name _dictionaryEntryName,
VariableAllVC* self,
Variable_Register* variable_Register,
ConditionFunction_Register* conFunc_Register,
Dictionary* dictionary,
void* data )
{
/* General info */
self->type = VariableAllVC_Type;
self->_sizeOfSelf = sizeof(VariableAllVC);
self->_deleteSelf = False;
/* Virtual info */
self->_delete = _VariableAllVC_Delete;
self->_print = _VariableAllVC_Print;
self->_copy = _VariableAllVC_Copy;
self->_build = _VariableAllVC_Build;
self->_initialise = _VariableCondition_Initialise;
self->_execute = _VariableCondition_Execute;
self->_buildSelf = _VariableAllVC_BuildSelf;
self->_printConcise = _VariableAllVC_PrintConcise;
self->_readDictionary = _VariableAllVC_ReadDictionary;
self->_getSet = _VariableAllVC_GetSet;
self->_getVariableCount = _VariableAllVC_GetVariableCount;
self->_getVariableIndex = _VariableAllVC_GetVariableIndex;
self->_getValueIndex = _VariableAllVC_GetValueIndex;
self->_getValueCount = _VariableAllVC_GetValueCount;
self->_getValue = _VariableAllVC_GetValue;
_Stg_Class_Init( (Stg_Class*)self );
_Stg_Object_Init( (Stg_Object*)self, name, NON_GLOBAL );
_Stg_Component_Init( (Stg_Component*)self );
_VariableCondition_Init( (VariableCondition*)self, variable_Register, conFunc_Register, dictionary );
/* Stg_Class info */
_VariableAllVC_Init( self, _dictionaryEntryName, data );
}
VariableAllVC* _VariableAllVC_New(
SizeT _sizeOfSelf,
Type type,
Stg_Class_DeleteFunction* _delete,
Stg_Class_PrintFunction* _print,
Stg_Class_CopyFunction* _copy,
Stg_Component_DefaultConstructorFunction* _defaultConstructor,
Stg_Component_ConstructFunction* _construct,
Stg_Component_BuildFunction* _build,
Stg_Component_InitialiseFunction* _initialise,
Stg_Component_ExecuteFunction* _execute,
Stg_Component_DestroyFunction* _destroy,
Name name,
Bool initFlag,
VariableCondition_BuildSelfFunc* _buildSelf,
VariableCondition_PrintConciseFunc* _printConcise,
VariableCondition_ReadDictionaryFunc* _readDictionary,
VariableCondition_GetSetFunc* _getSet,
VariableCondition_GetVariableCountFunc* _getVariableCount,
VariableCondition_GetVariableIndexFunc* _getVariableIndex,
VariableCondition_GetValueIndexFunc* _getValueIndex,
VariableCondition_GetValueCountFunc* _getValueCount,
VariableCondition_GetValueFunc* _getValue,
Name _dictionaryEntryName,
Variable_Register* variable_Register,
ConditionFunction_Register* conFunc_Register,
Dictionary* dictionary,
void* data)
{
VariableAllVC* self;
/* Allocate memory/General info */
assert(_sizeOfSelf >= sizeof(VariableAllVC));
self = (VariableAllVC*)_VariableCondition_New(
_sizeOfSelf,
type,
_delete,
_print,
_copy,
_defaultConstructor,
_construct,
_build,
_initialise,
_execute,
_destroy,
name,
initFlag,
_buildSelf,
_printConcise,
_readDictionary,
_getSet,
_getVariableCount,
_getVariableIndex,
_getValueIndex,
_getValueCount,
_getValue,
variable_Register,
conFunc_Register,
dictionary );
/* Virtual info */
/* Stg_Class info */
if( initFlag ){
_VariableAllVC_Init( self, _dictionaryEntryName, data );
}
return self;
}
void _VariableAllVC_Init(
void* allElementsVC,
Name _dictionaryEntryName,
void* data )
{
VariableAllVC* self = (VariableAllVC*)allElementsVC;
self->isConstructed = True;
self->_dictionaryEntryName = _dictionaryEntryName;
self->data = data;
}
/*--------------------------------------------------------------------------------------------------------------------------
** General virtual functions
*/
void _VariableAllVC_ReadDictionary( void* variableCondition, void* dictionary ) {
VariableAllVC* self = (VariableAllVC*)variableCondition;
Dictionary_Entry_Value* vcDictVal;
Dictionary_Entry_Value _vcDictVal;
Dictionary_Entry_Value* varsVal;
VariableAllVC_Entry_Index entry_I;
/* Find dictionary entry */
if (self->_dictionaryEntryName)
vcDictVal = Dictionary_Get( dictionary, self->_dictionaryEntryName );
else
{
vcDictVal = &_vcDictVal;
Dictionary_Entry_Value_InitFromStruct( vcDictVal, dictionary );
}
if (vcDictVal)
{
/* Obtain the variable entries */
self->_entryCount = Dictionary_Entry_Value_GetCount(Dictionary_Entry_Value_GetMember(vcDictVal, "variables"));
self->_entryTbl = Memory_Alloc_Array( VariableAllVC_Entry, self->_entryCount, "VariableAllVC->_entryTbl" );
varsVal = Dictionary_Entry_Value_GetMember(vcDictVal, "variables");
for (entry_I = 0; entry_I < self->_entryCount; entry_I++)
{
char* valType;
Dictionary_Entry_Value* valueEntry;
Dictionary_Entry_Value* varDictListVal;
varDictListVal = Dictionary_Entry_Value_GetElement(varsVal, entry_I);
valueEntry = Dictionary_Entry_Value_GetMember(varDictListVal, "value");
self->_entryTbl[entry_I].varName = Dictionary_Entry_Value_AsString(
Dictionary_Entry_Value_GetMember(varDictListVal, "name"));
valType = Dictionary_Entry_Value_AsString(Dictionary_Entry_Value_GetMember(varDictListVal, "type"));
if (!strcasecmp(valType, "func"))
{
char* funcName = Dictionary_Entry_Value_AsString(valueEntry);
self->_entryTbl[entry_I].value.type = VC_ValueType_CFIndex;
self->_entryTbl[entry_I].value.as.typeCFIndex = ConditionFunction_Register_GetIndex(
self->conFunc_Register, funcName);
}
else if (!strcasecmp(valType, "array"))
{
Dictionary_Entry_Value* valueElement;
Index i;
self->_entryTbl[entry_I].value.type = VC_ValueType_DoubleArray;
self->_entryTbl[entry_I].value.as.typeArray.size = Dictionary_Entry_Value_GetCount(valueEntry);
self->_entryTbl[entry_I].value.as.typeArray.array = Memory_Alloc_Array( double,
self->_entryTbl[entry_I].value.as.typeArray.size,"VariableAllVC->_entryTbl[].value.as.typeArray.array" );
for (i = 0; i < self->_entryTbl[entry_I].value.as.typeArray.size; i++)
{
valueElement = Dictionary_Entry_Value_GetElement(valueEntry, i);
self->_entryTbl[entry_I].value.as.typeArray.array[i] =
Dictionary_Entry_Value_AsDouble(valueElement);
}
}
else if( !strcasecmp( valType, "double" ) || !strcasecmp( valType, "d" ) || !strcasecmp( valType, "float" ) || !strcasecmp( valType, "f" ) ) {
self->_entryTbl[entry_I].value.type = VC_ValueType_Double;
self->_entryTbl[entry_I].value.as.typeDouble = Dictionary_Entry_Value_AsDouble( valueEntry );
}
else if( !strcasecmp( valType, "integer" ) || !strcasecmp( valType, "int" ) || !strcasecmp( valType, "i" ) ) {
self->_entryTbl[entry_I].value.type = VC_ValueType_Int;
self->_entryTbl[entry_I].value.as.typeInt = Dictionary_Entry_Value_AsUnsignedInt( valueEntry );
}
else if( !strcasecmp( valType, "short" ) || !strcasecmp( valType, "s" ) ) {
self->_entryTbl[entry_I].value.type = VC_ValueType_Short;
self->_entryTbl[entry_I].value.as.typeShort = Dictionary_Entry_Value_AsUnsignedInt( valueEntry );
}
else if( !strcasecmp( valType, "char" ) || !strcasecmp( valType, "c" ) ) {
self->_entryTbl[entry_I].value.type = VC_ValueType_Char;
self->_entryTbl[entry_I].value.as.typeChar = Dictionary_Entry_Value_AsUnsignedInt( valueEntry );
}
else if( !strcasecmp( valType, "pointer" ) || !strcasecmp( valType, "ptr" ) || !strcasecmp( valType, "p" ) ) {
self->_entryTbl[entry_I].value.type = VC_ValueType_Ptr;
self->_entryTbl[entry_I].value.as.typePtr = (void*) ( (ArithPointer) Dictionary_Entry_Value_AsUnsignedInt( valueEntry ));
}
else {
/* Assume double */
Journal_DPrintf( Journal_Register( InfoStream_Type, "myStream" ), "Type to variable on variable condition not given, assuming double\n" );
self->_entryTbl[entry_I].value.type = VC_ValueType_Double;
self->_entryTbl[entry_I].value.as.typeDouble = Dictionary_Entry_Value_AsDouble( valueEntry );
}
}
}
else
{
self->_entryCount = 0;
self->_entryTbl = NULL;
}
}
void _VariableAllVC_Delete( void* allElementsVC ) {
VariableAllVC* self = (VariableAllVC*)allElementsVC;
if (self->_entryTbl) Memory_Free(self->_entryTbl);
/* Stg_Class_Delete parent */
_VariableCondition_Delete(self);
}
void _VariableAllVC_Print( void* allElementsVC, Stream* stream ) {
VariableAllVC* self = (VariableAllVC*)allElementsVC;
VariableAllVC_Entry_Index entry_I;
Index i;
/* Set the Journal for printing informations */
Stream* info = stream;
/* General info */
Journal_Printf( info, "VariableAllVC (ptr): %p\n", self);
/* Print parent */
_VariableCondition_Print(self);
/* Virtual info */
/* Stg_Class info */
Journal_Printf( info, "\tdictionary (ptr): %p\n", self->dictionary);
Journal_Printf( info, "\t_dictionaryEntryName (ptr): %p\n", self->_dictionaryEntryName);
if (self->_dictionaryEntryName)
Journal_Printf( info, "\t\t_dictionaryEntryName: %s\n", self->_dictionaryEntryName);
Journal_Printf( info, "\t_entryCount: %u\n", self->_entryCount);
Journal_Printf( info, "\t_entryTbl (ptr): %p\n", self->_entryTbl);
if( self->_entryTbl ) {
for (entry_I = 0; entry_I < self->_entryCount; entry_I++)
{
Journal_Printf( info, "\t\t_entryTbl[%u]:\n", entry_I);
Journal_Printf( info, "\t\t\tvarName (ptr): %p\n", self->_entryTbl[entry_I].varName);
if (self->_entryTbl[entry_I].varName)
Journal_Printf( info, "\t\t\t\tvarName: %s\n", self->_entryTbl[entry_I].varName);
Journal_Printf( info, "\t\t\tvalue:\n");
switch (self->_entryTbl[entry_I].value.type)
{
case VC_ValueType_Double:
Journal_Printf( info, "\t\t\t\ttype: VC_ValueType_Double\n" );
Journal_Printf( info, "\t\t\t\tasDouble: %g\n", self->_entryTbl[entry_I].value.as.typeDouble );
break;
case VC_ValueType_Int:
Journal_Printf( info, "\t\t\t\ttype: VC_ValueType_Int\n" );
Journal_Printf( info, "\t\t\t\tasInt: %i\n", self->_entryTbl[entry_I].value.as.typeInt );
break;
case VC_ValueType_Short:
Journal_Printf( info, "\t\t\t\ttype: VC_ValueType_Short\n" );
Journal_Printf( info, "\t\t\t\tasShort: %i\n", self->_entryTbl[entry_I].value.as.typeShort );
break;
case VC_ValueType_Char:
Journal_Printf( info, "\t\t\t\ttype: VC_ValueType_Char\n");
Journal_Printf( info, "\t\t\t\tasChar: %c\n", self->_entryTbl[entry_I].value.as.typeChar );
break;
case VC_ValueType_Ptr:
Journal_Printf( info, "\t\t\t\ttype: VC_ValueType_Ptr\n");
Journal_Printf( info, "\t\t\t\tasPtr: %g\n", self->_entryTbl[entry_I].value.as.typePtr );
break;
case VC_ValueType_DoubleArray:
Journal_Printf( info, "\t\t\t\ttype: VC_ValueType_DoubleArray\n");
Journal_Printf( info, "\t\t\t\tarraySize: %u\n", self->_entryTbl[entry_I].value.as.typeArray.size);
Journal_Printf( info, "\t\t\t\tasDoubleArray (ptr): %p\n",
self->_entryTbl[entry_I].value.as.typeArray.array);
if (self->_entryTbl[entry_I].value.as.typeArray.array)
for (i = 0; i < self->_entryTbl[entry_I].value.as.typeArray.size; i++)
Journal_Printf( info, "\t\t\t\tasDoubleArray[%u]: %g\n", i,
self->_entryTbl[entry_I].value.as.typeArray.array[i]);
break;
case VC_ValueType_CFIndex:
Journal_Printf( info, "\t\t\t\ttype: VC_ValueType_CFIndex\n");
Journal_Printf( info, "\t\t\t\tasCFIndex: %u\n", self->_entryTbl[entry_I].value.as.typeCFIndex);
break;
}
}
}
}
void* _VariableAllVC_Copy( void* allElementsVC, void* dest, Bool deep, Name nameExt, struct PtrMap* ptrMap ) {
VariableAllVC* self = (VariableAllVC*)allElementsVC;
VariableAllVC* newVariableAllVC;
PtrMap* map = ptrMap;
Bool ownMap = False;
if( !map ) {
map = PtrMap_New( 10 );
ownMap = True;
}
newVariableAllVC = (VariableAllVC*)_VariableCondition_Copy( self, dest, deep, nameExt, map );
newVariableAllVC->_dictionaryEntryName = self->_dictionaryEntryName;
newVariableAllVC->_entryCount = self->_entryCount;
if( deep ) {
newVariableAllVC->data = Stg_Class_Copy( self->data, NULL, deep, nameExt, map );
if( (newVariableAllVC->_entryTbl = PtrMap_Find( map, self->_entryTbl )) == NULL && self->_entryTbl ) {
newVariableAllVC->_entryTbl = Memory_Alloc_Array( VariableAllVC_Entry, newVariableAllVC->_entryCount, "VariableAllVC->_entryTbl");
memcpy( newVariableAllVC->_entryTbl, self->_entryTbl, sizeof(VariableAllVC_Entry) * newVariableAllVC->_entryCount );
PtrMap_Append( map, newVariableAllVC->_entryTbl, self->_entryTbl );
}
}
else {
newVariableAllVC->data = self->data;
newVariableAllVC->_entryTbl = self->_entryTbl;
}
if( ownMap ) {
Stg_Class_Delete( map );
}
return (void*)newVariableAllVC;
}
void _VariableAllVC_Build( void* allElementsVC, void* data ) {
VariableAllVC* self = (VariableAllVC*)allElementsVC;
_VariableAllVC_BuildSelf( self, data );
_VariableCondition_Build( self, data );
}
/*--------------------------------------------------------------------------------------------------------------------------
** Macros
*/
/*--------------------------------------------------------------------------------------------------------------------------
** Virtual functions
*/
void _VariableAllVC_BuildSelf( void* allElementsVC, void* data ) {
VariableAllVC* self = (VariableAllVC*)allElementsVC;
if( self->data ) {
Build( self->data, data, False );
}
}
IndexSet* _VariableAllVC_GetSet( void* variableCondition ) {
VariableAllVC* self = (VariableAllVC*)variableCondition;
Variable* var = self->variable_Register->_variable[0];
IndexSet* set = IndexSet_New( var->arraySize );
IndexSet_AddAll( set );
return set;
}
VariableCondition_VariableIndex _VariableAllVC_GetVariableCount( void* variableCondition, Index globalIndex ) {
VariableAllVC* self = (VariableAllVC*)variableCondition;
return self->_entryCount;
}
Variable_Index _VariableAllVC_GetVariableIndex(
void* variableCondition,
Index globalIndex,
VariableCondition_VariableIndex varIndex)
{
VariableAllVC* self = (VariableAllVC*)variableCondition;
return Variable_Register_GetIndex(self->variable_Register, self->_entryTbl[varIndex].varName);
}
VariableCondition_ValueIndex _VariableAllVC_GetValueIndex(
void* variableCondition,
Index globalIndex,
VariableCondition_VariableIndex varIndex)
{
return varIndex;
}
VariableCondition_ValueIndex _VariableAllVC_GetValueCount( void* variableCondition ) {
VariableAllVC* self = (VariableAllVC*)variableCondition;
return self->_entryCount;
}
VariableCondition_Value _VariableAllVC_GetValue( void* variableCondition, VariableCondition_ValueIndex valIndex ) {
VariableAllVC* self = (VariableAllVC*)variableCondition;
return self->_entryTbl[valIndex].value;
}
void _VariableAllVC_PrintConcise( void* variableCondition, Stream* stream ) {
VariableAllVC* self = (VariableAllVC*)variableCondition;
Journal_Printf( stream, "\ttype: %s, set: all\n", self->type );
}
/*--------------------------------------------------------------------------------------------------------------------------
** Build functions
*/
/*--------------------------------------------------------------------------------------------------------------------------
** Functions
*/
| gpl-2.0 |
viaembedded/vab1000-uboot-bsp | drivers/dma/MCD_dmaApi.c | 261 | 36189 | /*
* Copyright (C) 2004-2007 Freescale Semiconductor, Inc.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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; either version 2 of
* the License, or (at your option) any later version.
*
* 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
*/
/*Main C file for multi-channel DMA API. */
#include <common.h>
#include <MCD_dma.h>
#include <MCD_tasksInit.h>
#include <MCD_progCheck.h>
/********************************************************************/
/* This is an API-internal pointer to the DMA's registers */
dmaRegs *MCD_dmaBar;
/*
* These are the real and model task tables as generated by the
* build process
*/
extern TaskTableEntry MCD_realTaskTableSrc[NCHANNELS];
extern TaskTableEntry MCD_modelTaskTableSrc[NUMOFVARIANTS];
/*
* However, this (usually) gets relocated to on-chip SRAM, at which
* point we access them as these tables
*/
volatile TaskTableEntry *MCD_taskTable;
TaskTableEntry *MCD_modelTaskTable;
/*
* MCD_chStatus[] is an array of status indicators for remembering
* whether a DMA has ever been attempted on each channel, pausing
* status, etc.
*/
static int MCD_chStatus[NCHANNELS] = {
MCD_NO_DMA, MCD_NO_DMA, MCD_NO_DMA, MCD_NO_DMA,
MCD_NO_DMA, MCD_NO_DMA, MCD_NO_DMA, MCD_NO_DMA,
MCD_NO_DMA, MCD_NO_DMA, MCD_NO_DMA, MCD_NO_DMA,
MCD_NO_DMA, MCD_NO_DMA, MCD_NO_DMA, MCD_NO_DMA
};
/* Prototypes for local functions */
static void MCD_memcpy(int *dest, int *src, u32 size);
static void MCD_resmActions(int channel);
/*
* Buffer descriptors used for storage of progress info for single Dmas
* Also used as storage for the DMA for CRCs for single DMAs
* Otherwise, the DMA does not parse these buffer descriptors
*/
#ifdef MCD_INCLUDE_EU
extern MCD_bufDesc MCD_singleBufDescs[NCHANNELS];
#else
MCD_bufDesc MCD_singleBufDescs[NCHANNELS];
#endif
MCD_bufDesc *MCD_relocBuffDesc;
/* Defines for the debug control register's functions */
#define DBG_CTL_COMP1_TASK (0x00002000)
#define DBG_CTL_ENABLE (DBG_CTL_AUTO_ARM | \
DBG_CTL_BREAK | \
DBG_CTL_INT_BREAK | \
DBG_CTL_COMP1_TASK)
#define DBG_CTL_DISABLE (DBG_CTL_AUTO_ARM | \
DBG_CTL_INT_BREAK | \
DBG_CTL_COMP1_TASK)
#define DBG_KILL_ALL_STAT (0xFFFFFFFF)
/* Offset to context save area where progress info is stored */
#define CSAVE_OFFSET 10
/* Defines for Byte Swapping */
#define MCD_BYTE_SWAP_KILLER 0xFFF8888F
#define MCD_NO_BYTE_SWAP_ATALL 0x00040000
/* Execution Unit Identifiers */
#define MAC 0 /* legacy - not used */
#define LUAC 1 /* legacy - not used */
#define CRC 2 /* legacy - not used */
#define LURC 3 /* Logic Unit with CRC */
/* Task Identifiers */
#define TASK_CHAINNOEU 0
#define TASK_SINGLENOEU 1
#ifdef MCD_INCLUDE_EU
#define TASK_CHAINEU 2
#define TASK_SINGLEEU 3
#define TASK_FECRX 4
#define TASK_FECTX 5
#else
#define TASK_CHAINEU 0
#define TASK_SINGLEEU 1
#define TASK_FECRX 2
#define TASK_FECTX 3
#endif
/*
* Structure to remember which variant is on which channel
* TBD- need this?
*/
typedef struct MCD_remVariants_struct MCD_remVariant;
struct MCD_remVariants_struct {
int remDestRsdIncr[NCHANNELS]; /* -1,0,1 */
int remSrcRsdIncr[NCHANNELS]; /* -1,0,1 */
s16 remDestIncr[NCHANNELS]; /* DestIncr */
s16 remSrcIncr[NCHANNELS]; /* srcIncr */
u32 remXferSize[NCHANNELS]; /* xferSize */
};
/* Structure to remember the startDma parameters for each channel */
MCD_remVariant MCD_remVariants;
/********************************************************************/
/* Function: MCD_initDma
* Purpose: Initializes the DMA API by setting up a pointer to the DMA
* registers, relocating and creating the appropriate task
* structures, and setting up some global settings
* Arguments:
* dmaBarAddr - pointer to the multichannel DMA registers
* taskTableDest - location to move DMA task code and structs to
* flags - operational parameters
* Return Value:
* MCD_TABLE_UNALIGNED if taskTableDest is not 512-byte aligned
* MCD_OK otherwise
*/
extern u32 MCD_funcDescTab0[];
int MCD_initDma(dmaRegs * dmaBarAddr, void *taskTableDest, u32 flags)
{
int i;
TaskTableEntry *entryPtr;
/* setup the local pointer to register set */
MCD_dmaBar = dmaBarAddr;
/* do we need to move/create a task table */
if ((flags & MCD_RELOC_TASKS) != 0) {
int fixedSize;
u32 *fixedPtr;
/*int *tablePtr = taskTableDest;TBD */
int varTabsOffset, funcDescTabsOffset, contextSavesOffset;
int taskDescTabsOffset;
int taskTableSize, varTabsSize, funcDescTabsSize,
contextSavesSize;
int taskDescTabSize;
int i;
/* check if physical address is aligned on 512 byte boundary */
if (((u32) taskTableDest & 0x000001ff) != 0)
return (MCD_TABLE_UNALIGNED);
/* set up local pointer to task Table */
MCD_taskTable = taskTableDest;
/*
* Create a task table:
* - compute aligned base offsets for variable tables and
* function descriptor tables, then
* - loop through the task table and setup the pointers
* - copy over model task table with the the actual task
* descriptor tables
*/
taskTableSize = NCHANNELS * sizeof(TaskTableEntry);
/* align variable tables to size */
varTabsOffset = taskTableSize + (u32) taskTableDest;
if ((varTabsOffset & (VAR_TAB_SIZE - 1)) != 0)
varTabsOffset =
(varTabsOffset + VAR_TAB_SIZE) & (~VAR_TAB_SIZE);
/* align function descriptor tables */
varTabsSize = NCHANNELS * VAR_TAB_SIZE;
funcDescTabsOffset = varTabsOffset + varTabsSize;
if ((funcDescTabsOffset & (FUNCDESC_TAB_SIZE - 1)) != 0)
funcDescTabsOffset =
(funcDescTabsOffset +
FUNCDESC_TAB_SIZE) & (~FUNCDESC_TAB_SIZE);
funcDescTabsSize = FUNCDESC_TAB_NUM * FUNCDESC_TAB_SIZE;
contextSavesOffset = funcDescTabsOffset + funcDescTabsSize;
contextSavesSize = (NCHANNELS * CONTEXT_SAVE_SIZE);
fixedSize =
taskTableSize + varTabsSize + funcDescTabsSize +
contextSavesSize;
/* zero the thing out */
fixedPtr = (u32 *) taskTableDest;
for (i = 0; i < (fixedSize / 4); i++)
fixedPtr[i] = 0;
entryPtr = (TaskTableEntry *) MCD_taskTable;
/* set up fixed pointers */
for (i = 0; i < NCHANNELS; i++) {
/* update ptr to local value */
entryPtr[i].varTab = (u32) varTabsOffset;
entryPtr[i].FDTandFlags =
(u32) funcDescTabsOffset | MCD_TT_FLAGS_DEF;
entryPtr[i].contextSaveSpace = (u32) contextSavesOffset;
varTabsOffset += VAR_TAB_SIZE;
#ifdef MCD_INCLUDE_EU
/* if not there is only one, just point to the
same one */
funcDescTabsOffset += FUNCDESC_TAB_SIZE;
#endif
contextSavesOffset += CONTEXT_SAVE_SIZE;
}
/* copy over the function descriptor table */
for (i = 0; i < FUNCDESC_TAB_NUM; i++) {
MCD_memcpy((void *)(entryPtr[i].
FDTandFlags & ~MCD_TT_FLAGS_MASK),
(void *)MCD_funcDescTab0, FUNCDESC_TAB_SIZE);
}
/* copy model task table to where the context saves stuff
leaves off */
MCD_modelTaskTable = (TaskTableEntry *) contextSavesOffset;
MCD_memcpy((void *)MCD_modelTaskTable,
(void *)MCD_modelTaskTableSrc,
NUMOFVARIANTS * sizeof(TaskTableEntry));
/* point to local version of model task table */
entryPtr = MCD_modelTaskTable;
taskDescTabsOffset = (u32) MCD_modelTaskTable +
(NUMOFVARIANTS * sizeof(TaskTableEntry));
/* copy actual task code and update TDT ptrs in local
model task table */
for (i = 0; i < NUMOFVARIANTS; i++) {
taskDescTabSize =
entryPtr[i].TDTend - entryPtr[i].TDTstart + 4;
MCD_memcpy((void *)taskDescTabsOffset,
(void *)entryPtr[i].TDTstart,
taskDescTabSize);
entryPtr[i].TDTstart = (u32) taskDescTabsOffset;
taskDescTabsOffset += taskDescTabSize;
entryPtr[i].TDTend = (u32) taskDescTabsOffset - 4;
}
#ifdef MCD_INCLUDE_EU
/* Tack single DMA BDs onto end of code so API controls
where they are since DMA might write to them */
MCD_relocBuffDesc =
(MCD_bufDesc *) (entryPtr[NUMOFVARIANTS - 1].TDTend + 4);
#else
/* DMA does not touch them so they can be wherever and we
don't need to waste SRAM on them */
MCD_relocBuffDesc = MCD_singleBufDescs;
#endif
} else {
/* point the would-be relocated task tables and the
buffer descriptors to the ones the linker generated */
if (((u32) MCD_realTaskTableSrc & 0x000001ff) != 0)
return (MCD_TABLE_UNALIGNED);
/* need to add code to make sure that every thing else is
aligned properly TBD. this is problematic if we init
more than once or after running tasks, need to add
variable to see if we have aleady init'd */
entryPtr = MCD_realTaskTableSrc;
for (i = 0; i < NCHANNELS; i++) {
if (((entryPtr[i].varTab & (VAR_TAB_SIZE - 1)) != 0) ||
((entryPtr[i].
FDTandFlags & (FUNCDESC_TAB_SIZE - 1)) != 0))
return (MCD_TABLE_UNALIGNED);
}
MCD_taskTable = MCD_realTaskTableSrc;
MCD_modelTaskTable = MCD_modelTaskTableSrc;
MCD_relocBuffDesc = MCD_singleBufDescs;
}
/* Make all channels as totally inactive, and remember them as such: */
MCD_dmaBar->taskbar = (u32) MCD_taskTable;
for (i = 0; i < NCHANNELS; i++) {
MCD_dmaBar->taskControl[i] = 0x0;
MCD_chStatus[i] = MCD_NO_DMA;
}
/* Set up pausing mechanism to inactive state: */
/* no particular values yet for either comparator registers */
MCD_dmaBar->debugComp1 = 0;
MCD_dmaBar->debugComp2 = 0;
MCD_dmaBar->debugControl = DBG_CTL_DISABLE;
MCD_dmaBar->debugStatus = DBG_KILL_ALL_STAT;
/* enable or disable commbus prefetch, really need an ifdef or
something to keep from trying to set this in the 8220 */
if ((flags & MCD_COMM_PREFETCH_EN) != 0)
MCD_dmaBar->ptdControl &= ~PTD_CTL_COMM_PREFETCH;
else
MCD_dmaBar->ptdControl |= PTD_CTL_COMM_PREFETCH;
return (MCD_OK);
}
/*********************** End of MCD_initDma() ***********************/
/********************************************************************/
/* Function: MCD_dmaStatus
* Purpose: Returns the status of the DMA on the requested channel
* Arguments: channel - channel number
* Returns: Predefined status indicators
*/
int MCD_dmaStatus(int channel)
{
u16 tcrValue;
if ((channel < 0) || (channel >= NCHANNELS))
return (MCD_CHANNEL_INVALID);
tcrValue = MCD_dmaBar->taskControl[channel];
if ((tcrValue & TASK_CTL_EN) == 0) { /* nothing running */
/* if last reported with task enabled */
if (MCD_chStatus[channel] == MCD_RUNNING
|| MCD_chStatus[channel] == MCD_IDLE)
MCD_chStatus[channel] = MCD_DONE;
} else { /* something is running */
/* There are three possibilities: paused, running or idle. */
if (MCD_chStatus[channel] == MCD_RUNNING
|| MCD_chStatus[channel] == MCD_IDLE) {
MCD_dmaBar->ptdDebug = PTD_DBG_TSK_VLD_INIT;
/* This register is selected to know which initiator is
actually asserted. */
if ((MCD_dmaBar->ptdDebug >> channel) & 0x1)
MCD_chStatus[channel] = MCD_RUNNING;
else
MCD_chStatus[channel] = MCD_IDLE;
/* do not change the status if it is already paused. */
}
}
return MCD_chStatus[channel];
}
/******************** End of MCD_dmaStatus() ************************/
/********************************************************************/
/* Function: MCD_startDma
* Ppurpose: Starts a particular kind of DMA
* Arguments:
* srcAddr - the channel on which to run the DMA
* srcIncr - the address to move data from, or buffer-descriptor address
* destAddr - the amount to increment the source address per transfer
* destIncr - the address to move data to
* dmaSize - the amount to increment the destination address per transfer
* xferSize - the number bytes in of each data movement (1, 2, or 4)
* initiator - what device initiates the DMA
* priority - priority of the DMA
* flags - flags describing the DMA
* funcDesc - description of byte swapping, bit swapping, and CRC actions
* srcAddrVirt - virtual buffer descriptor address TBD
* Returns: MCD_CHANNEL_INVALID if channel is invalid, else MCD_OK
*/
int MCD_startDma(int channel, s8 * srcAddr, s16 srcIncr, s8 * destAddr,
s16 destIncr, u32 dmaSize, u32 xferSize, u32 initiator,
int priority, u32 flags, u32 funcDesc
#ifdef MCD_NEED_ADDR_TRANS
s8 * srcAddrVirt
#endif
)
{
int srcRsdIncr, destRsdIncr;
int *cSave;
short xferSizeIncr;
int tcrCount = 0;
#ifdef MCD_INCLUDE_EU
u32 *realFuncArray;
#endif
if ((channel < 0) || (channel >= NCHANNELS))
return (MCD_CHANNEL_INVALID);
/* tbd - need to determine the proper response to a bad funcDesc when
not including EU functions, for now, assign a benign funcDesc, but
maybe should return an error */
#ifndef MCD_INCLUDE_EU
funcDesc = MCD_FUNC_NOEU1;
#endif
#ifdef MCD_DEBUG
printf("startDma:Setting up params\n");
#endif
/* Set us up for task-wise priority. We don't technically need to do
this on every start, but since the register involved is in the same
longword as other registers that users are in control of, setting
it more than once is probably preferable. That since the
documentation doesn't seem to be completely consistent about the
nature of the PTD control register. */
MCD_dmaBar->ptdControl |= (u16) 0x8000;
/* Not sure what we need to keep here rtm TBD */
#if 1
/* Calculate additional parameters to the regular DMA calls. */
srcRsdIncr = srcIncr < 0 ? -1 : (srcIncr > 0 ? 1 : 0);
destRsdIncr = destIncr < 0 ? -1 : (destIncr > 0 ? 1 : 0);
xferSizeIncr = (xferSize & 0xffff) | 0x20000000;
/* Remember for each channel which variant is running. */
MCD_remVariants.remSrcRsdIncr[channel] = srcRsdIncr;
MCD_remVariants.remDestRsdIncr[channel] = destRsdIncr;
MCD_remVariants.remDestIncr[channel] = destIncr;
MCD_remVariants.remSrcIncr[channel] = srcIncr;
MCD_remVariants.remXferSize[channel] = xferSize;
#endif
cSave =
(int *)(MCD_taskTable[channel].contextSaveSpace) + CSAVE_OFFSET +
CURRBD;
#ifdef MCD_INCLUDE_EU
/* may move this to EU specific calls */
realFuncArray =
(u32 *) (MCD_taskTable[channel].FDTandFlags & 0xffffff00);
/* Modify the LURC's normal and byte-residue-loop functions according
to parameter. */
realFuncArray[(LURC * 16)] = xferSize == 4 ?
funcDesc : xferSize == 2 ?
funcDesc & 0xfffff00f : funcDesc & 0xffff000f;
realFuncArray[(LURC * 16 + 1)] =
(funcDesc & MCD_BYTE_SWAP_KILLER) | MCD_NO_BYTE_SWAP_ATALL;
#endif
/* Write the initiator field in the TCR, and also set the
initiator-hold bit. Note that,due to a hardware quirk, this could
collide with an MDE access to the initiator-register file, so we
have to verify that the write reads back correctly. */
MCD_dmaBar->taskControl[channel] =
(initiator << 8) | TASK_CTL_HIPRITSKEN | TASK_CTL_HLDINITNUM;
while (((MCD_dmaBar->taskControl[channel] & 0x1fff) !=
((initiator << 8) | TASK_CTL_HIPRITSKEN | TASK_CTL_HLDINITNUM))
&& (tcrCount < 1000)) {
tcrCount++;
/*MCD_dmaBar->ptd_tcr[channel] = (initiator << 8) | 0x0020; */
MCD_dmaBar->taskControl[channel] =
(initiator << 8) | TASK_CTL_HIPRITSKEN |
TASK_CTL_HLDINITNUM;
}
MCD_dmaBar->priority[channel] = (u8) priority & PRIORITY_PRI_MASK;
/* should be albe to handle this stuff with only one write to ts reg
- tbd */
if (channel < 8 && channel >= 0) {
MCD_dmaBar->taskSize0 &= ~(0xf << (7 - channel) * 4);
MCD_dmaBar->taskSize0 |=
(xferSize & 3) << (((7 - channel) * 4) + 2);
MCD_dmaBar->taskSize0 |= (xferSize & 3) << ((7 - channel) * 4);
} else {
MCD_dmaBar->taskSize1 &= ~(0xf << (15 - channel) * 4);
MCD_dmaBar->taskSize1 |=
(xferSize & 3) << (((15 - channel) * 4) + 2);
MCD_dmaBar->taskSize1 |= (xferSize & 3) << ((15 - channel) * 4);
}
/* setup task table flags/options which mostly control the line
buffers */
MCD_taskTable[channel].FDTandFlags &= ~MCD_TT_FLAGS_MASK;
MCD_taskTable[channel].FDTandFlags |= (MCD_TT_FLAGS_MASK & flags);
if (flags & MCD_FECTX_DMA) {
/* TDTStart and TDTEnd */
MCD_taskTable[channel].TDTstart =
MCD_modelTaskTable[TASK_FECTX].TDTstart;
MCD_taskTable[channel].TDTend =
MCD_modelTaskTable[TASK_FECTX].TDTend;
MCD_startDmaENetXmit((char *)srcAddr, (char *)srcAddr,
(char *)destAddr, MCD_taskTable,
channel);
} else if (flags & MCD_FECRX_DMA) {
/* TDTStart and TDTEnd */
MCD_taskTable[channel].TDTstart =
MCD_modelTaskTable[TASK_FECRX].TDTstart;
MCD_taskTable[channel].TDTend =
MCD_modelTaskTable[TASK_FECRX].TDTend;
MCD_startDmaENetRcv((char *)srcAddr, (char *)srcAddr,
(char *)destAddr, MCD_taskTable,
channel);
} else if (flags & MCD_SINGLE_DMA) {
/* this buffer descriptor is used for storing off initial
parameters for later progress query calculation and for the
DMA to write the resulting checksum. The DMA does not use
this to determine how to operate, that info is passed with
the init routine */
MCD_relocBuffDesc[channel].srcAddr = srcAddr;
MCD_relocBuffDesc[channel].destAddr = destAddr;
/* definitely not its final value */
MCD_relocBuffDesc[channel].lastDestAddr = destAddr;
MCD_relocBuffDesc[channel].dmaSize = dmaSize;
MCD_relocBuffDesc[channel].flags = 0; /* not used */
MCD_relocBuffDesc[channel].csumResult = 0; /* not used */
MCD_relocBuffDesc[channel].next = 0; /* not used */
/* Initialize the progress-querying stuff to show no
progress: */
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[SRCPTR + CSAVE_OFFSET] = (int)srcAddr;
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[DESTPTR + CSAVE_OFFSET] = (int)destAddr;
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[DCOUNT + CSAVE_OFFSET] = 0;
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[CURRBD + CSAVE_OFFSET] =
(u32) & (MCD_relocBuffDesc[channel]);
/* tbd - need to keep the user from trying to call the EU
routine when MCD_INCLUDE_EU is not defined */
if (funcDesc == MCD_FUNC_NOEU1 || funcDesc == MCD_FUNC_NOEU2) {
/* TDTStart and TDTEnd */
MCD_taskTable[channel].TDTstart =
MCD_modelTaskTable[TASK_SINGLENOEU].TDTstart;
MCD_taskTable[channel].TDTend =
MCD_modelTaskTable[TASK_SINGLENOEU].TDTend;
MCD_startDmaSingleNoEu((char *)srcAddr, srcIncr,
(char *)destAddr, destIncr,
(int)dmaSize, xferSizeIncr,
flags, (int *)
&(MCD_relocBuffDesc[channel]),
cSave, MCD_taskTable, channel);
} else {
/* TDTStart and TDTEnd */
MCD_taskTable[channel].TDTstart =
MCD_modelTaskTable[TASK_SINGLEEU].TDTstart;
MCD_taskTable[channel].TDTend =
MCD_modelTaskTable[TASK_SINGLEEU].TDTend;
MCD_startDmaSingleEu((char *)srcAddr, srcIncr,
(char *)destAddr, destIncr,
(int)dmaSize, xferSizeIncr,
flags, (int *)
&(MCD_relocBuffDesc[channel]),
cSave, MCD_taskTable, channel);
}
} else { /* chained DMAS */
/* Initialize the progress-querying stuff to show no
progress: */
#if 1
/* (!defined(MCD_NEED_ADDR_TRANS)) */
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[SRCPTR + CSAVE_OFFSET]
= (int)((MCD_bufDesc *) srcAddr)->srcAddr;
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[DESTPTR + CSAVE_OFFSET]
= (int)((MCD_bufDesc *) srcAddr)->destAddr;
#else
/* if using address translation, need the virtual addr of the
first buffdesc */
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[SRCPTR + CSAVE_OFFSET]
= (int)((MCD_bufDesc *) srcAddrVirt)->srcAddr;
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[DESTPTR + CSAVE_OFFSET]
= (int)((MCD_bufDesc *) srcAddrVirt)->destAddr;
#endif
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[DCOUNT + CSAVE_OFFSET] = 0;
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[CURRBD + CSAVE_OFFSET] = (u32) srcAddr;
if (funcDesc == MCD_FUNC_NOEU1 || funcDesc == MCD_FUNC_NOEU2) {
/*TDTStart and TDTEnd */
MCD_taskTable[channel].TDTstart =
MCD_modelTaskTable[TASK_CHAINNOEU].TDTstart;
MCD_taskTable[channel].TDTend =
MCD_modelTaskTable[TASK_CHAINNOEU].TDTend;
MCD_startDmaChainNoEu((int *)srcAddr, srcIncr,
destIncr, xferSize,
xferSizeIncr, cSave,
MCD_taskTable, channel);
} else {
/*TDTStart and TDTEnd */
MCD_taskTable[channel].TDTstart =
MCD_modelTaskTable[TASK_CHAINEU].TDTstart;
MCD_taskTable[channel].TDTend =
MCD_modelTaskTable[TASK_CHAINEU].TDTend;
MCD_startDmaChainEu((int *)srcAddr, srcIncr, destIncr,
xferSize, xferSizeIncr, cSave,
MCD_taskTable, channel);
}
}
MCD_chStatus[channel] = MCD_IDLE;
return (MCD_OK);
}
/************************ End of MCD_startDma() *********************/
/********************************************************************/
/* Function: MCD_XferProgrQuery
* Purpose: Returns progress of DMA on requested channel
* Arguments: channel - channel to retrieve progress for
* progRep - pointer to user supplied MCD_XferProg struct
* Returns: MCD_CHANNEL_INVALID if channel is invalid, else MCD_OK
*
* Notes:
* MCD_XferProgrQuery() upon completing or after aborting a DMA, or
* while the DMA is in progress, this function returns the first
* DMA-destination address not (or not yet) used in the DMA. When
* encountering a non-ready buffer descriptor, the information for
* the last completed descriptor is returned.
*
* MCD_XferProgQuery() has to avoid the possibility of getting
* partially-updated information in the event that we should happen
* to query DMA progress just as the DMA is updating it. It does that
* by taking advantage of the fact context is not saved frequently for
* the most part. We therefore read it at least twice until we get the
* same information twice in a row.
*
* Because a small, but not insignificant, amount of time is required
* to write out the progress-query information, especially upon
* completion of the DMA, it would be wise to guarantee some time lag
* between successive readings of the progress-query information.
*/
/* How many iterations of the loop below to execute to stabilize values */
#define STABTIME 0
int MCD_XferProgrQuery(int channel, MCD_XferProg * progRep)
{
MCD_XferProg prevRep;
int again; /* true if we are to try again to ge
consistent results */
int i; /* used as a time-waste counter */
int destDiffBytes; /* Total no of bytes that we think actually
got xfered. */
int numIterations; /* number of iterations */
int bytesNotXfered; /* bytes that did not get xfered. */
s8 *LWAlignedInitDestAddr, *LWAlignedCurrDestAddr;
int subModVal, addModVal; /* Mode values to added and subtracted
from the final destAddr */
if ((channel < 0) || (channel >= NCHANNELS))
return (MCD_CHANNEL_INVALID);
/* Read a trial value for the progress-reporting values */
prevRep.lastSrcAddr =
(s8 *) ((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[SRCPTR + CSAVE_OFFSET];
prevRep.lastDestAddr =
(s8 *) ((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[DESTPTR + CSAVE_OFFSET];
prevRep.dmaSize =
((volatile int *)MCD_taskTable[channel].contextSaveSpace)[DCOUNT +
CSAVE_OFFSET];
prevRep.currBufDesc =
(MCD_bufDesc *) ((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[CURRBD + CSAVE_OFFSET];
/* Repeatedly reread those values until they match previous values: */
do {
/* Waste a little bit of time to ensure stability: */
for (i = 0; i < STABTIME; i++) {
/* make sure this loop does something so that it
doesn't get optimized out */
i += i >> 2;
}
/* Check them again: */
progRep->lastSrcAddr =
(s8 *) ((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[SRCPTR + CSAVE_OFFSET];
progRep->lastDestAddr =
(s8 *) ((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[DESTPTR + CSAVE_OFFSET];
progRep->dmaSize =
((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[DCOUNT + CSAVE_OFFSET];
progRep->currBufDesc =
(MCD_bufDesc *) ((volatile int *)MCD_taskTable[channel].
contextSaveSpace)[CURRBD + CSAVE_OFFSET];
/* See if they match: */
if (prevRep.lastSrcAddr != progRep->lastSrcAddr
|| prevRep.lastDestAddr != progRep->lastDestAddr
|| prevRep.dmaSize != progRep->dmaSize
|| prevRep.currBufDesc != progRep->currBufDesc) {
/* If they don't match, remember previous values and
try again: */
prevRep.lastSrcAddr = progRep->lastSrcAddr;
prevRep.lastDestAddr = progRep->lastDestAddr;
prevRep.dmaSize = progRep->dmaSize;
prevRep.currBufDesc = progRep->currBufDesc;
again = MCD_TRUE;
} else
again = MCD_FALSE;
} while (again == MCD_TRUE);
/* Update the dCount, srcAddr and destAddr */
/* To calculate dmaCount, we consider destination address. C
overs M1,P1,Z for destination */
switch (MCD_remVariants.remDestRsdIncr[channel]) {
case MINUS1:
subModVal =
((int)progRep->
lastDestAddr) & ((MCD_remVariants.remXferSize[channel]) -
1);
addModVal =
((int)progRep->currBufDesc->
destAddr) & ((MCD_remVariants.remXferSize[channel]) - 1);
LWAlignedInitDestAddr =
(progRep->currBufDesc->destAddr) - addModVal;
LWAlignedCurrDestAddr = (progRep->lastDestAddr) - subModVal;
destDiffBytes = LWAlignedInitDestAddr - LWAlignedCurrDestAddr;
bytesNotXfered =
(destDiffBytes / MCD_remVariants.remDestIncr[channel]) *
(MCD_remVariants.remDestIncr[channel]
+ MCD_remVariants.remXferSize[channel]);
progRep->dmaSize =
destDiffBytes - bytesNotXfered + addModVal - subModVal;
break;
case ZERO:
progRep->lastDestAddr = progRep->currBufDesc->destAddr;
break;
case PLUS1:
/* This value has to be subtracted from the final
calculated dCount. */
subModVal =
((int)progRep->currBufDesc->
destAddr) & ((MCD_remVariants.remXferSize[channel]) - 1);
/* These bytes are already in lastDestAddr. */
addModVal =
((int)progRep->
lastDestAddr) & ((MCD_remVariants.remXferSize[channel]) -
1);
LWAlignedInitDestAddr =
(progRep->currBufDesc->destAddr) - subModVal;
LWAlignedCurrDestAddr = (progRep->lastDestAddr) - addModVal;
destDiffBytes = (progRep->lastDestAddr - LWAlignedInitDestAddr);
numIterations =
(LWAlignedCurrDestAddr -
LWAlignedInitDestAddr) /
MCD_remVariants.remDestIncr[channel];
bytesNotXfered =
numIterations * (MCD_remVariants.remDestIncr[channel]
- MCD_remVariants.remXferSize[channel]);
progRep->dmaSize = destDiffBytes - bytesNotXfered - subModVal;
break;
default:
break;
}
/* This covers M1,P1,Z for source */
switch (MCD_remVariants.remSrcRsdIncr[channel]) {
case MINUS1:
progRep->lastSrcAddr =
progRep->currBufDesc->srcAddr +
(MCD_remVariants.remSrcIncr[channel] *
(progRep->dmaSize / MCD_remVariants.remXferSize[channel]));
break;
case ZERO:
progRep->lastSrcAddr = progRep->currBufDesc->srcAddr;
break;
case PLUS1:
progRep->lastSrcAddr =
progRep->currBufDesc->srcAddr +
(MCD_remVariants.remSrcIncr[channel] *
(progRep->dmaSize / MCD_remVariants.remXferSize[channel]));
break;
default:
break;
}
return (MCD_OK);
}
/******************* End of MCD_XferProgrQuery() ********************/
/********************************************************************/
/* MCD_resmActions() does the majority of the actions of a DMA resume.
* It is called from MCD_killDma() and MCD_resumeDma(). It has to be
* a separate function because the kill function has to negate the task
* enable before resuming it, but the resume function has to do nothing
* if there is no DMA on that channel (i.e., if the enable bit is 0).
*/
static void MCD_resmActions(int channel)
{
MCD_dmaBar->debugControl = DBG_CTL_DISABLE;
MCD_dmaBar->debugStatus = MCD_dmaBar->debugStatus;
/* This register is selected to know which initiator is
actually asserted. */
MCD_dmaBar->ptdDebug = PTD_DBG_TSK_VLD_INIT;
if ((MCD_dmaBar->ptdDebug >> channel) & 0x1)
MCD_chStatus[channel] = MCD_RUNNING;
else
MCD_chStatus[channel] = MCD_IDLE;
}
/********************* End of MCD_resmActions() *********************/
/********************************************************************/
/* Function: MCD_killDma
* Purpose: Halt the DMA on the requested channel, without any
* intention of resuming the DMA.
* Arguments: channel - requested channel
* Returns: MCD_CHANNEL_INVALID if channel is invalid, else MCD_OK
*
* Notes:
* A DMA may be killed from any state, including paused state, and it
* always goes to the MCD_HALTED state even if it is killed while in
* the MCD_NO_DMA or MCD_IDLE states.
*/
int MCD_killDma(int channel)
{
/* MCD_XferProg progRep; */
if ((channel < 0) || (channel >= NCHANNELS))
return (MCD_CHANNEL_INVALID);
MCD_dmaBar->taskControl[channel] = 0x0;
MCD_resumeDma(channel);
/*
* This must be after the write to the TCR so that the task doesn't
* start up again momentarily, and before the status assignment so
* as to override whatever MCD_resumeDma() may do to the channel
* status.
*/
MCD_chStatus[channel] = MCD_HALTED;
/*
* Update the current buffer descriptor's lastDestAddr field
*
* MCD_XferProgrQuery (channel, &progRep);
* progRep.currBufDesc->lastDestAddr = progRep.lastDestAddr;
*/
return (MCD_OK);
}
/************************ End of MCD_killDma() **********************/
/********************************************************************/
/* Function: MCD_continDma
* Purpose: Continue a DMA which as stopped due to encountering an
* unready buffer descriptor.
* Arguments: channel - channel to continue the DMA on
* Returns: MCD_CHANNEL_INVALID if channel is invalid, else MCD_OK
*
* Notes:
* This routine does not check to see if there is a task which can
* be continued. Also this routine should not be used with single DMAs.
*/
int MCD_continDma(int channel)
{
if ((channel < 0) || (channel >= NCHANNELS))
return (MCD_CHANNEL_INVALID);
MCD_dmaBar->taskControl[channel] |= TASK_CTL_EN;
MCD_chStatus[channel] = MCD_RUNNING;
return (MCD_OK);
}
/********************** End of MCD_continDma() **********************/
/*********************************************************************
* MCD_pauseDma() and MCD_resumeDma() below use the DMA's debug unit
* to freeze a task and resume it. We freeze a task by breakpointing
* on the stated task. That is, not any specific place in the task,
* but any time that task executes. In particular, when that task
* executes, we want to freeze that task and only that task.
*
* The bits of the debug control register influence interrupts vs.
* breakpoints as follows:
* - Bits 14 and 0 enable or disable debug functions. If enabled, you
* will get the interrupt but you may or may not get a breakpoint.
* - Bits 2 and 1 decide whether you also get a breakpoint in addition
* to an interrupt.
*
* The debug unit can do these actions in response to either internally
* detected breakpoint conditions from the comparators, or in response
* to the external breakpoint pin, or both.
* - Bits 14 and 1 perform the above-described functions for
* internally-generated conditions, i.e., the debug comparators.
* - Bits 0 and 2 perform the above-described functions for external
* conditions, i.e., the breakpoint external pin.
*
* Note that, although you "always" get the interrupt when you turn
* the debug functions, the interrupt can nevertheless, if desired, be
* masked by the corresponding bit in the PTD's IMR. Note also that
* this means that bits 14 and 0 must enable debug functions before
* bits 1 and 2, respectively, have any effect.
*
* NOTE: It's extremely important to not pause more than one DMA channel
* at a time.
********************************************************************/
/********************************************************************/
/* Function: MCD_pauseDma
* Purpose: Pauses the DMA on a given channel (if any DMA is running
* on that channel).
* Arguments: channel
* Returns: MCD_CHANNEL_INVALID if channel is invalid, else MCD_OK
*/
int MCD_pauseDma(int channel)
{
/* MCD_XferProg progRep; */
if ((channel < 0) || (channel >= NCHANNELS))
return (MCD_CHANNEL_INVALID);
if (MCD_dmaBar->taskControl[channel] & TASK_CTL_EN) {
MCD_dmaBar->debugComp1 = channel;
MCD_dmaBar->debugControl =
DBG_CTL_ENABLE | (1 << (channel + 16));
MCD_chStatus[channel] = MCD_PAUSED;
/*
* Update the current buffer descriptor's lastDestAddr field
*
* MCD_XferProgrQuery (channel, &progRep);
* progRep.currBufDesc->lastDestAddr = progRep.lastDestAddr;
*/
}
return (MCD_OK);
}
/************************* End of MCD_pauseDma() ********************/
/********************************************************************/
/* Function: MCD_resumeDma
* Purpose: Resumes the DMA on a given channel (if any DMA is
* running on that channel).
* Arguments: channel - channel on which to resume DMA
* Returns: MCD_CHANNEL_INVALID if channel is invalid, else MCD_OK
*/
int MCD_resumeDma(int channel)
{
if ((channel < 0) || (channel >= NCHANNELS))
return (MCD_CHANNEL_INVALID);
if (MCD_dmaBar->taskControl[channel] & TASK_CTL_EN)
MCD_resmActions(channel);
return (MCD_OK);
}
/************************ End of MCD_resumeDma() ********************/
/********************************************************************/
/* Function: MCD_csumQuery
* Purpose: Provide the checksum after performing a non-chained DMA
* Arguments: channel - channel to report on
* csum - pointer to where to write the checksum/CRC
* Returns: MCD_ERROR if the channel is invalid, else MCD_OK
*
* Notes:
*
*/
int MCD_csumQuery(int channel, u32 * csum)
{
#ifdef MCD_INCLUDE_EU
if ((channel < 0) || (channel >= NCHANNELS))
return (MCD_CHANNEL_INVALID);
*csum = MCD_relocBuffDesc[channel].csumResult;
return (MCD_OK);
#else
return (MCD_ERROR);
#endif
}
/*********************** End of MCD_resumeDma() *********************/
/********************************************************************/
/* Function: MCD_getCodeSize
* Purpose: Provide the size requirements of the microcoded tasks
* Returns: Size in bytes
*/
int MCD_getCodeSize(void)
{
#ifdef MCD_INCLUDE_EU
return (0x2b5c);
#else
return (0x173c);
#endif
}
/********************** End of MCD_getCodeSize() ********************/
/********************************************************************/
/* Function: MCD_getVersion
* Purpose: Provide the version string and number
* Arguments: longVersion - user supplied pointer to a pointer to a char
* which points to the version string
* Returns: Version number and version string (by reference)
*/
char MCD_versionString[] = "Multi-channel DMA API Alpha v0.3 (2004-04-26)";
#define MCD_REV_MAJOR 0x00
#define MCD_REV_MINOR 0x03
int MCD_getVersion(char **longVersion)
{
*longVersion = MCD_versionString;
return ((MCD_REV_MAJOR << 8) | MCD_REV_MINOR);
}
/********************** End of MCD_getVersion() *********************/
/********************************************************************/
/* Private version of memcpy()
* Note that everything this is used for is longword-aligned.
*/
static void MCD_memcpy(int *dest, int *src, u32 size)
{
u32 i;
for (i = 0; i < size; i += sizeof(int), dest++, src++)
*dest = *src;
}
| gpl-2.0 |
GHackAnonymous/linux | arch/parisc/kernel/pci-dma.c | 517 | 16038 | /*
** PARISC 1.1 Dynamic DMA mapping support.
** This implementation is for PA-RISC platforms that do not support
** I/O TLBs (aka DMA address translation hardware).
** See Documentation/DMA-API-HOWTO.txt for interface definitions.
**
** (c) Copyright 1999,2000 Hewlett-Packard Company
** (c) Copyright 2000 Grant Grundler
** (c) Copyright 2000 Philipp Rumpf <prumpf@tux.org>
** (c) Copyright 2000 John Marvin
**
** "leveraged" from 2.3.47: arch/ia64/kernel/pci-dma.c.
** (I assume it's from David Mosberger-Tang but there was no Copyright)
**
** AFAIK, all PA7100LC and PA7300LC platforms can use this code.
**
** - ggg
*/
#include <linux/init.h>
#include <linux/gfp.h>
#include <linux/mm.h>
#include <linux/pci.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/scatterlist.h>
#include <linux/export.h>
#include <asm/cacheflush.h>
#include <asm/dma.h> /* for DMA_CHUNK_SIZE */
#include <asm/io.h>
#include <asm/page.h> /* get_order */
#include <asm/pgalloc.h>
#include <asm/uaccess.h>
#include <asm/tlbflush.h> /* for purge_tlb_*() macros */
static struct proc_dir_entry * proc_gsc_root __read_mostly = NULL;
static unsigned long pcxl_used_bytes __read_mostly = 0;
static unsigned long pcxl_used_pages __read_mostly = 0;
extern unsigned long pcxl_dma_start; /* Start of pcxl dma mapping area */
static spinlock_t pcxl_res_lock;
static char *pcxl_res_map;
static int pcxl_res_hint;
static int pcxl_res_size;
#ifdef DEBUG_PCXL_RESOURCE
#define DBG_RES(x...) printk(x)
#else
#define DBG_RES(x...)
#endif
/*
** Dump a hex representation of the resource map.
*/
#ifdef DUMP_RESMAP
static
void dump_resmap(void)
{
u_long *res_ptr = (unsigned long *)pcxl_res_map;
u_long i = 0;
printk("res_map: ");
for(; i < (pcxl_res_size / sizeof(unsigned long)); ++i, ++res_ptr)
printk("%08lx ", *res_ptr);
printk("\n");
}
#else
static inline void dump_resmap(void) {;}
#endif
static int pa11_dma_supported( struct device *dev, u64 mask)
{
return 1;
}
static inline int map_pte_uncached(pte_t * pte,
unsigned long vaddr,
unsigned long size, unsigned long *paddr_ptr)
{
unsigned long end;
unsigned long orig_vaddr = vaddr;
vaddr &= ~PMD_MASK;
end = vaddr + size;
if (end > PMD_SIZE)
end = PMD_SIZE;
do {
unsigned long flags;
if (!pte_none(*pte))
printk(KERN_ERR "map_pte_uncached: page already exists\n");
set_pte(pte, __mk_pte(*paddr_ptr, PAGE_KERNEL_UNC));
purge_tlb_start(flags);
pdtlb_kernel(orig_vaddr);
purge_tlb_end(flags);
vaddr += PAGE_SIZE;
orig_vaddr += PAGE_SIZE;
(*paddr_ptr) += PAGE_SIZE;
pte++;
} while (vaddr < end);
return 0;
}
static inline int map_pmd_uncached(pmd_t * pmd, unsigned long vaddr,
unsigned long size, unsigned long *paddr_ptr)
{
unsigned long end;
unsigned long orig_vaddr = vaddr;
vaddr &= ~PGDIR_MASK;
end = vaddr + size;
if (end > PGDIR_SIZE)
end = PGDIR_SIZE;
do {
pte_t * pte = pte_alloc_kernel(pmd, vaddr);
if (!pte)
return -ENOMEM;
if (map_pte_uncached(pte, orig_vaddr, end - vaddr, paddr_ptr))
return -ENOMEM;
vaddr = (vaddr + PMD_SIZE) & PMD_MASK;
orig_vaddr += PMD_SIZE;
pmd++;
} while (vaddr < end);
return 0;
}
static inline int map_uncached_pages(unsigned long vaddr, unsigned long size,
unsigned long paddr)
{
pgd_t * dir;
unsigned long end = vaddr + size;
dir = pgd_offset_k(vaddr);
do {
pmd_t *pmd;
pmd = pmd_alloc(NULL, dir, vaddr);
if (!pmd)
return -ENOMEM;
if (map_pmd_uncached(pmd, vaddr, end - vaddr, &paddr))
return -ENOMEM;
vaddr = vaddr + PGDIR_SIZE;
dir++;
} while (vaddr && (vaddr < end));
return 0;
}
static inline void unmap_uncached_pte(pmd_t * pmd, unsigned long vaddr,
unsigned long size)
{
pte_t * pte;
unsigned long end;
unsigned long orig_vaddr = vaddr;
if (pmd_none(*pmd))
return;
if (pmd_bad(*pmd)) {
pmd_ERROR(*pmd);
pmd_clear(pmd);
return;
}
pte = pte_offset_map(pmd, vaddr);
vaddr &= ~PMD_MASK;
end = vaddr + size;
if (end > PMD_SIZE)
end = PMD_SIZE;
do {
unsigned long flags;
pte_t page = *pte;
pte_clear(&init_mm, vaddr, pte);
purge_tlb_start(flags);
pdtlb_kernel(orig_vaddr);
purge_tlb_end(flags);
vaddr += PAGE_SIZE;
orig_vaddr += PAGE_SIZE;
pte++;
if (pte_none(page) || pte_present(page))
continue;
printk(KERN_CRIT "Whee.. Swapped out page in kernel page table\n");
} while (vaddr < end);
}
static inline void unmap_uncached_pmd(pgd_t * dir, unsigned long vaddr,
unsigned long size)
{
pmd_t * pmd;
unsigned long end;
unsigned long orig_vaddr = vaddr;
if (pgd_none(*dir))
return;
if (pgd_bad(*dir)) {
pgd_ERROR(*dir);
pgd_clear(dir);
return;
}
pmd = pmd_offset(dir, vaddr);
vaddr &= ~PGDIR_MASK;
end = vaddr + size;
if (end > PGDIR_SIZE)
end = PGDIR_SIZE;
do {
unmap_uncached_pte(pmd, orig_vaddr, end - vaddr);
vaddr = (vaddr + PMD_SIZE) & PMD_MASK;
orig_vaddr += PMD_SIZE;
pmd++;
} while (vaddr < end);
}
static void unmap_uncached_pages(unsigned long vaddr, unsigned long size)
{
pgd_t * dir;
unsigned long end = vaddr + size;
dir = pgd_offset_k(vaddr);
do {
unmap_uncached_pmd(dir, vaddr, end - vaddr);
vaddr = vaddr + PGDIR_SIZE;
dir++;
} while (vaddr && (vaddr < end));
}
#define PCXL_SEARCH_LOOP(idx, mask, size) \
for(; res_ptr < res_end; ++res_ptr) \
{ \
if(0 == ((*res_ptr) & mask)) { \
*res_ptr |= mask; \
idx = (int)((u_long)res_ptr - (u_long)pcxl_res_map); \
pcxl_res_hint = idx + (size >> 3); \
goto resource_found; \
} \
}
#define PCXL_FIND_FREE_MAPPING(idx, mask, size) { \
u##size *res_ptr = (u##size *)&(pcxl_res_map[pcxl_res_hint & ~((size >> 3) - 1)]); \
u##size *res_end = (u##size *)&pcxl_res_map[pcxl_res_size]; \
PCXL_SEARCH_LOOP(idx, mask, size); \
res_ptr = (u##size *)&pcxl_res_map[0]; \
PCXL_SEARCH_LOOP(idx, mask, size); \
}
unsigned long
pcxl_alloc_range(size_t size)
{
int res_idx;
u_long mask, flags;
unsigned int pages_needed = size >> PAGE_SHIFT;
mask = (u_long) -1L;
mask >>= BITS_PER_LONG - pages_needed;
DBG_RES("pcxl_alloc_range() size: %d pages_needed %d pages_mask 0x%08lx\n",
size, pages_needed, mask);
spin_lock_irqsave(&pcxl_res_lock, flags);
if(pages_needed <= 8) {
PCXL_FIND_FREE_MAPPING(res_idx, mask, 8);
} else if(pages_needed <= 16) {
PCXL_FIND_FREE_MAPPING(res_idx, mask, 16);
} else if(pages_needed <= 32) {
PCXL_FIND_FREE_MAPPING(res_idx, mask, 32);
} else {
panic("%s: pcxl_alloc_range() Too many pages to map.\n",
__FILE__);
}
dump_resmap();
panic("%s: pcxl_alloc_range() out of dma mapping resources\n",
__FILE__);
resource_found:
DBG_RES("pcxl_alloc_range() res_idx %d mask 0x%08lx res_hint: %d\n",
res_idx, mask, pcxl_res_hint);
pcxl_used_pages += pages_needed;
pcxl_used_bytes += ((pages_needed >> 3) ? (pages_needed >> 3) : 1);
spin_unlock_irqrestore(&pcxl_res_lock, flags);
dump_resmap();
/*
** return the corresponding vaddr in the pcxl dma map
*/
return (pcxl_dma_start + (res_idx << (PAGE_SHIFT + 3)));
}
#define PCXL_FREE_MAPPINGS(idx, m, size) \
u##size *res_ptr = (u##size *)&(pcxl_res_map[(idx) + (((size >> 3) - 1) & (~((size >> 3) - 1)))]); \
/* BUG_ON((*res_ptr & m) != m); */ \
*res_ptr &= ~m;
/*
** clear bits in the pcxl resource map
*/
static void
pcxl_free_range(unsigned long vaddr, size_t size)
{
u_long mask, flags;
unsigned int res_idx = (vaddr - pcxl_dma_start) >> (PAGE_SHIFT + 3);
unsigned int pages_mapped = size >> PAGE_SHIFT;
mask = (u_long) -1L;
mask >>= BITS_PER_LONG - pages_mapped;
DBG_RES("pcxl_free_range() res_idx: %d size: %d pages_mapped %d mask 0x%08lx\n",
res_idx, size, pages_mapped, mask);
spin_lock_irqsave(&pcxl_res_lock, flags);
if(pages_mapped <= 8) {
PCXL_FREE_MAPPINGS(res_idx, mask, 8);
} else if(pages_mapped <= 16) {
PCXL_FREE_MAPPINGS(res_idx, mask, 16);
} else if(pages_mapped <= 32) {
PCXL_FREE_MAPPINGS(res_idx, mask, 32);
} else {
panic("%s: pcxl_free_range() Too many pages to unmap.\n",
__FILE__);
}
pcxl_used_pages -= (pages_mapped ? pages_mapped : 1);
pcxl_used_bytes -= ((pages_mapped >> 3) ? (pages_mapped >> 3) : 1);
spin_unlock_irqrestore(&pcxl_res_lock, flags);
dump_resmap();
}
static int proc_pcxl_dma_show(struct seq_file *m, void *v)
{
#if 0
u_long i = 0;
unsigned long *res_ptr = (u_long *)pcxl_res_map;
#endif
unsigned long total_pages = pcxl_res_size << 3; /* 8 bits per byte */
seq_printf(m, "\nDMA Mapping Area size : %d bytes (%ld pages)\n",
PCXL_DMA_MAP_SIZE, total_pages);
seq_printf(m, "Resource bitmap : %d bytes\n", pcxl_res_size);
seq_puts(m, " total: free: used: % used:\n");
seq_printf(m, "blocks %8d %8ld %8ld %8ld%%\n", pcxl_res_size,
pcxl_res_size - pcxl_used_bytes, pcxl_used_bytes,
(pcxl_used_bytes * 100) / pcxl_res_size);
seq_printf(m, "pages %8ld %8ld %8ld %8ld%%\n", total_pages,
total_pages - pcxl_used_pages, pcxl_used_pages,
(pcxl_used_pages * 100 / total_pages));
#if 0
seq_puts(m, "\nResource bitmap:");
for(; i < (pcxl_res_size / sizeof(u_long)); ++i, ++res_ptr) {
if ((i & 7) == 0)
seq_puts(m,"\n ");
seq_printf(m, "%s %08lx", buf, *res_ptr);
}
#endif
seq_putc(m, '\n');
return 0;
}
static int proc_pcxl_dma_open(struct inode *inode, struct file *file)
{
return single_open(file, proc_pcxl_dma_show, NULL);
}
static const struct file_operations proc_pcxl_dma_ops = {
.owner = THIS_MODULE,
.open = proc_pcxl_dma_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init
pcxl_dma_init(void)
{
if (pcxl_dma_start == 0)
return 0;
spin_lock_init(&pcxl_res_lock);
pcxl_res_size = PCXL_DMA_MAP_SIZE >> (PAGE_SHIFT + 3);
pcxl_res_hint = 0;
pcxl_res_map = (char *)__get_free_pages(GFP_KERNEL,
get_order(pcxl_res_size));
memset(pcxl_res_map, 0, pcxl_res_size);
proc_gsc_root = proc_mkdir("gsc", NULL);
if (!proc_gsc_root)
printk(KERN_WARNING
"pcxl_dma_init: Unable to create gsc /proc dir entry\n");
else {
struct proc_dir_entry* ent;
ent = proc_create("pcxl_dma", 0, proc_gsc_root,
&proc_pcxl_dma_ops);
if (!ent)
printk(KERN_WARNING
"pci-dma.c: Unable to create pcxl_dma /proc entry.\n");
}
return 0;
}
__initcall(pcxl_dma_init);
static void * pa11_dma_alloc_consistent (struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flag)
{
unsigned long vaddr;
unsigned long paddr;
int order;
order = get_order(size);
size = 1 << (order + PAGE_SHIFT);
vaddr = pcxl_alloc_range(size);
paddr = __get_free_pages(flag, order);
flush_kernel_dcache_range(paddr, size);
paddr = __pa(paddr);
map_uncached_pages(vaddr, size, paddr);
*dma_handle = (dma_addr_t) paddr;
#if 0
/* This probably isn't needed to support EISA cards.
** ISA cards will certainly only support 24-bit DMA addressing.
** Not clear if we can, want, or need to support ISA.
*/
if (!dev || *dev->coherent_dma_mask < 0xffffffff)
gfp |= GFP_DMA;
#endif
return (void *)vaddr;
}
static void pa11_dma_free_consistent (struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle)
{
int order;
order = get_order(size);
size = 1 << (order + PAGE_SHIFT);
unmap_uncached_pages((unsigned long)vaddr, size);
pcxl_free_range((unsigned long)vaddr, size);
free_pages((unsigned long)__va(dma_handle), order);
}
static dma_addr_t pa11_dma_map_single(struct device *dev, void *addr, size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
flush_kernel_dcache_range((unsigned long) addr, size);
return virt_to_phys(addr);
}
static void pa11_dma_unmap_single(struct device *dev, dma_addr_t dma_handle, size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
if (direction == DMA_TO_DEVICE)
return;
/*
* For PCI_DMA_FROMDEVICE this flush is not necessary for the
* simple map/unmap case. However, it IS necessary if if
* pci_dma_sync_single_* has been called and the buffer reused.
*/
flush_kernel_dcache_range((unsigned long) phys_to_virt(dma_handle), size);
return;
}
static int pa11_dma_map_sg(struct device *dev, struct scatterlist *sglist, int nents, enum dma_data_direction direction)
{
int i;
struct scatterlist *sg;
BUG_ON(direction == DMA_NONE);
for_each_sg(sglist, sg, nents, i) {
unsigned long vaddr = (unsigned long)sg_virt(sg);
sg_dma_address(sg) = (dma_addr_t) virt_to_phys(vaddr);
sg_dma_len(sg) = sg->length;
flush_kernel_dcache_range(vaddr, sg->length);
}
return nents;
}
static void pa11_dma_unmap_sg(struct device *dev, struct scatterlist *sglist, int nents, enum dma_data_direction direction)
{
int i;
struct scatterlist *sg;
BUG_ON(direction == DMA_NONE);
if (direction == DMA_TO_DEVICE)
return;
/* once we do combining we'll need to use phys_to_virt(sg_dma_address(sglist)) */
for_each_sg(sglist, sg, nents, i)
flush_kernel_vmap_range(sg_virt(sg), sg->length);
return;
}
static void pa11_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle, unsigned long offset, size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
flush_kernel_dcache_range((unsigned long) phys_to_virt(dma_handle) + offset, size);
}
static void pa11_dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle, unsigned long offset, size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
flush_kernel_dcache_range((unsigned long) phys_to_virt(dma_handle) + offset, size);
}
static void pa11_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sglist, int nents, enum dma_data_direction direction)
{
int i;
struct scatterlist *sg;
/* once we do combining we'll need to use phys_to_virt(sg_dma_address(sglist)) */
for_each_sg(sglist, sg, nents, i)
flush_kernel_vmap_range(sg_virt(sg), sg->length);
}
static void pa11_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sglist, int nents, enum dma_data_direction direction)
{
int i;
struct scatterlist *sg;
/* once we do combining we'll need to use phys_to_virt(sg_dma_address(sglist)) */
for_each_sg(sglist, sg, nents, i)
flush_kernel_vmap_range(sg_virt(sg), sg->length);
}
struct hppa_dma_ops pcxl_dma_ops = {
.dma_supported = pa11_dma_supported,
.alloc_consistent = pa11_dma_alloc_consistent,
.alloc_noncoherent = pa11_dma_alloc_consistent,
.free_consistent = pa11_dma_free_consistent,
.map_single = pa11_dma_map_single,
.unmap_single = pa11_dma_unmap_single,
.map_sg = pa11_dma_map_sg,
.unmap_sg = pa11_dma_unmap_sg,
.dma_sync_single_for_cpu = pa11_dma_sync_single_for_cpu,
.dma_sync_single_for_device = pa11_dma_sync_single_for_device,
.dma_sync_sg_for_cpu = pa11_dma_sync_sg_for_cpu,
.dma_sync_sg_for_device = pa11_dma_sync_sg_for_device,
};
static void *fail_alloc_consistent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flag)
{
return NULL;
}
static void *pa11_dma_alloc_noncoherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flag)
{
void *addr;
addr = (void *)__get_free_pages(flag, get_order(size));
if (addr)
*dma_handle = (dma_addr_t)virt_to_phys(addr);
return addr;
}
static void pa11_dma_free_noncoherent(struct device *dev, size_t size,
void *vaddr, dma_addr_t iova)
{
free_pages((unsigned long)vaddr, get_order(size));
return;
}
struct hppa_dma_ops pcx_dma_ops = {
.dma_supported = pa11_dma_supported,
.alloc_consistent = fail_alloc_consistent,
.alloc_noncoherent = pa11_dma_alloc_noncoherent,
.free_consistent = pa11_dma_free_noncoherent,
.map_single = pa11_dma_map_single,
.unmap_single = pa11_dma_unmap_single,
.map_sg = pa11_dma_map_sg,
.unmap_sg = pa11_dma_unmap_sg,
.dma_sync_single_for_cpu = pa11_dma_sync_single_for_cpu,
.dma_sync_single_for_device = pa11_dma_sync_single_for_device,
.dma_sync_sg_for_cpu = pa11_dma_sync_sg_for_cpu,
.dma_sync_sg_for_device = pa11_dma_sync_sg_for_device,
};
| gpl-2.0 |
dpuyosa/android_kernel_wiko_l5460 | sound/isa/es18xx.c | 517 | 70519 | /*
* Driver for generic ESS AudioDrive ES18xx soundcards
* Copyright (c) by Christian Fischbach <fishbach@pool.informatik.rwth-aachen.de>
* Copyright (c) by Abramo Bagnara <abramo@alsa-project.org>
*
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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
*
*/
/* GENERAL NOTES:
*
* BUGS:
* - There are pops (we can't delay in trigger function, cause midlevel
* often need to trigger down and then up very quickly).
* Any ideas?
* - Support for 16 bit DMA seems to be broken. I've no hardware to tune it.
*/
/*
* ES1868 NOTES:
* - The chip has one half duplex pcm (with very limited full duplex support).
*
* - Duplex stereophonic sound is impossible.
* - Record and playback must share the same frequency rate.
*
* - The driver use dma2 for playback and dma1 for capture.
*/
/*
* ES1869 NOTES:
*
* - there are a first full duplex pcm and a second playback only pcm
* (incompatible with first pcm capture)
*
* - there is support for the capture volume and ESS Spatializer 3D effect.
*
* - contrarily to some pages in DS_1869.PDF the rates can be set
* independently.
*
* - Zoom Video is implemented by sharing the FM DAC, thus the user can
* have either FM playback or Video playback but not both simultaneously.
* The Video Playback Switch mixer control toggles this choice.
*
* BUGS:
*
* - There is a major trouble I noted:
*
* using both channel for playback stereo 16 bit samples at 44100 Hz
* the second pcm (Audio1) DMA slows down irregularly and sound is garbled.
*
* The same happens using Audio1 for captureing.
*
* The Windows driver does not suffer of this (although it use Audio1
* only for captureing). I'm unable to discover why.
*
*/
/*
* ES1879 NOTES:
* - When Zoom Video is enabled (reg 0x71 bit 6 toggled on) the PCM playback
* seems to be effected (speaker_test plays a lower frequency). Can't find
* anything in the datasheet to account for this, so a Video Playback Switch
* control has been included to allow ZV to be enabled only when necessary.
* Then again on at least one test system the 0x71 bit 6 enable bit is not
* needed for ZV, so maybe the datasheet is entirely wrong here.
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/pnp.h>
#include <linux/isapnp.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#define SNDRV_LEGACY_FIND_FREE_IRQ
#define SNDRV_LEGACY_FIND_FREE_DMA
#include <sound/initval.h>
#define PFX "es18xx: "
struct snd_es18xx {
unsigned long port; /* port of ESS chip */
unsigned long ctrl_port; /* Control port of ESS chip */
struct resource *res_port;
struct resource *res_mpu_port;
struct resource *res_ctrl_port;
int irq; /* IRQ number of ESS chip */
int dma1; /* DMA1 */
int dma2; /* DMA2 */
unsigned short version; /* version of ESS chip */
int caps; /* Chip capabilities */
unsigned short audio2_vol; /* volume level of audio2 */
unsigned short active; /* active channel mask */
unsigned int dma1_shift;
unsigned int dma2_shift;
struct snd_pcm *pcm;
struct snd_pcm_substream *playback_a_substream;
struct snd_pcm_substream *capture_a_substream;
struct snd_pcm_substream *playback_b_substream;
struct snd_rawmidi *rmidi;
struct snd_kcontrol *hw_volume;
struct snd_kcontrol *hw_switch;
struct snd_kcontrol *master_volume;
struct snd_kcontrol *master_switch;
spinlock_t reg_lock;
spinlock_t mixer_lock;
#ifdef CONFIG_PM
unsigned char pm_reg;
#endif
#ifdef CONFIG_PNP
struct pnp_dev *dev;
struct pnp_dev *devc;
#endif
};
#define AUDIO1_IRQ 0x01
#define AUDIO2_IRQ 0x02
#define HWV_IRQ 0x04
#define MPU_IRQ 0x08
#define ES18XX_PCM2 0x0001 /* Has two useable PCM */
#define ES18XX_SPATIALIZER 0x0002 /* Has 3D Spatializer */
#define ES18XX_RECMIX 0x0004 /* Has record mixer */
#define ES18XX_DUPLEX_MONO 0x0008 /* Has mono duplex only */
#define ES18XX_DUPLEX_SAME 0x0010 /* Playback and record must share the same rate */
#define ES18XX_NEW_RATE 0x0020 /* More precise rate setting */
#define ES18XX_AUXB 0x0040 /* AuxB mixer control */
#define ES18XX_HWV 0x0080 /* Has separate hardware volume mixer controls*/
#define ES18XX_MONO 0x0100 /* Mono_in mixer control */
#define ES18XX_I2S 0x0200 /* I2S mixer control */
#define ES18XX_MUTEREC 0x0400 /* Record source can be muted */
#define ES18XX_CONTROL 0x0800 /* Has control ports */
/* Power Management */
#define ES18XX_PM 0x07
#define ES18XX_PM_GPO0 0x01
#define ES18XX_PM_GPO1 0x02
#define ES18XX_PM_PDR 0x04
#define ES18XX_PM_ANA 0x08
#define ES18XX_PM_FM 0x020
#define ES18XX_PM_SUS 0x080
/* Lowlevel */
#define DAC1 0x01
#define ADC1 0x02
#define DAC2 0x04
#define MILLISECOND 10000
static int snd_es18xx_dsp_command(struct snd_es18xx *chip, unsigned char val)
{
int i;
for(i = MILLISECOND; i; i--)
if ((inb(chip->port + 0x0C) & 0x80) == 0) {
outb(val, chip->port + 0x0C);
return 0;
}
snd_printk(KERN_ERR "dsp_command: timeout (0x%x)\n", val);
return -EINVAL;
}
static int snd_es18xx_dsp_get_byte(struct snd_es18xx *chip)
{
int i;
for(i = MILLISECOND/10; i; i--)
if (inb(chip->port + 0x0C) & 0x40)
return inb(chip->port + 0x0A);
snd_printk(KERN_ERR "dsp_get_byte failed: 0x%lx = 0x%x!!!\n",
chip->port + 0x0A, inb(chip->port + 0x0A));
return -ENODEV;
}
#undef REG_DEBUG
static int snd_es18xx_write(struct snd_es18xx *chip,
unsigned char reg, unsigned char data)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&chip->reg_lock, flags);
ret = snd_es18xx_dsp_command(chip, reg);
if (ret < 0)
goto end;
ret = snd_es18xx_dsp_command(chip, data);
end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
#ifdef REG_DEBUG
snd_printk(KERN_DEBUG "Reg %02x set to %02x\n", reg, data);
#endif
return ret;
}
static int snd_es18xx_read(struct snd_es18xx *chip, unsigned char reg)
{
unsigned long flags;
int ret, data;
spin_lock_irqsave(&chip->reg_lock, flags);
ret = snd_es18xx_dsp_command(chip, 0xC0);
if (ret < 0)
goto end;
ret = snd_es18xx_dsp_command(chip, reg);
if (ret < 0)
goto end;
data = snd_es18xx_dsp_get_byte(chip);
ret = data;
#ifdef REG_DEBUG
snd_printk(KERN_DEBUG "Reg %02x now is %02x (%d)\n", reg, data, ret);
#endif
end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
return ret;
}
/* Return old value */
static int snd_es18xx_bits(struct snd_es18xx *chip, unsigned char reg,
unsigned char mask, unsigned char val)
{
int ret;
unsigned char old, new, oval;
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
ret = snd_es18xx_dsp_command(chip, 0xC0);
if (ret < 0)
goto end;
ret = snd_es18xx_dsp_command(chip, reg);
if (ret < 0)
goto end;
ret = snd_es18xx_dsp_get_byte(chip);
if (ret < 0) {
goto end;
}
old = ret;
oval = old & mask;
if (val != oval) {
ret = snd_es18xx_dsp_command(chip, reg);
if (ret < 0)
goto end;
new = (old & ~mask) | (val & mask);
ret = snd_es18xx_dsp_command(chip, new);
if (ret < 0)
goto end;
#ifdef REG_DEBUG
snd_printk(KERN_DEBUG "Reg %02x was %02x, set to %02x (%d)\n",
reg, old, new, ret);
#endif
}
ret = oval;
end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
return ret;
}
static inline void snd_es18xx_mixer_write(struct snd_es18xx *chip,
unsigned char reg, unsigned char data)
{
unsigned long flags;
spin_lock_irqsave(&chip->mixer_lock, flags);
outb(reg, chip->port + 0x04);
outb(data, chip->port + 0x05);
spin_unlock_irqrestore(&chip->mixer_lock, flags);
#ifdef REG_DEBUG
snd_printk(KERN_DEBUG "Mixer reg %02x set to %02x\n", reg, data);
#endif
}
static inline int snd_es18xx_mixer_read(struct snd_es18xx *chip, unsigned char reg)
{
unsigned long flags;
int data;
spin_lock_irqsave(&chip->mixer_lock, flags);
outb(reg, chip->port + 0x04);
data = inb(chip->port + 0x05);
spin_unlock_irqrestore(&chip->mixer_lock, flags);
#ifdef REG_DEBUG
snd_printk(KERN_DEBUG "Mixer reg %02x now is %02x\n", reg, data);
#endif
return data;
}
/* Return old value */
static inline int snd_es18xx_mixer_bits(struct snd_es18xx *chip, unsigned char reg,
unsigned char mask, unsigned char val)
{
unsigned char old, new, oval;
unsigned long flags;
spin_lock_irqsave(&chip->mixer_lock, flags);
outb(reg, chip->port + 0x04);
old = inb(chip->port + 0x05);
oval = old & mask;
if (val != oval) {
new = (old & ~mask) | (val & mask);
outb(new, chip->port + 0x05);
#ifdef REG_DEBUG
snd_printk(KERN_DEBUG "Mixer reg %02x was %02x, set to %02x\n",
reg, old, new);
#endif
}
spin_unlock_irqrestore(&chip->mixer_lock, flags);
return oval;
}
static inline int snd_es18xx_mixer_writable(struct snd_es18xx *chip, unsigned char reg,
unsigned char mask)
{
int old, expected, new;
unsigned long flags;
spin_lock_irqsave(&chip->mixer_lock, flags);
outb(reg, chip->port + 0x04);
old = inb(chip->port + 0x05);
expected = old ^ mask;
outb(expected, chip->port + 0x05);
new = inb(chip->port + 0x05);
spin_unlock_irqrestore(&chip->mixer_lock, flags);
#ifdef REG_DEBUG
snd_printk(KERN_DEBUG "Mixer reg %02x was %02x, set to %02x, now is %02x\n",
reg, old, expected, new);
#endif
return expected == new;
}
static int snd_es18xx_reset(struct snd_es18xx *chip)
{
int i;
outb(0x03, chip->port + 0x06);
inb(chip->port + 0x06);
outb(0x00, chip->port + 0x06);
for(i = 0; i < MILLISECOND && !(inb(chip->port + 0x0E) & 0x80); i++);
if (inb(chip->port + 0x0A) != 0xAA)
return -1;
return 0;
}
static int snd_es18xx_reset_fifo(struct snd_es18xx *chip)
{
outb(0x02, chip->port + 0x06);
inb(chip->port + 0x06);
outb(0x00, chip->port + 0x06);
return 0;
}
static struct snd_ratnum new_clocks[2] = {
{
.num = 793800,
.den_min = 1,
.den_max = 128,
.den_step = 1,
},
{
.num = 768000,
.den_min = 1,
.den_max = 128,
.den_step = 1,
}
};
static struct snd_pcm_hw_constraint_ratnums new_hw_constraints_clocks = {
.nrats = 2,
.rats = new_clocks,
};
static struct snd_ratnum old_clocks[2] = {
{
.num = 795444,
.den_min = 1,
.den_max = 128,
.den_step = 1,
},
{
.num = 397722,
.den_min = 1,
.den_max = 128,
.den_step = 1,
}
};
static struct snd_pcm_hw_constraint_ratnums old_hw_constraints_clocks = {
.nrats = 2,
.rats = old_clocks,
};
static void snd_es18xx_rate_set(struct snd_es18xx *chip,
struct snd_pcm_substream *substream,
int mode)
{
unsigned int bits, div0;
struct snd_pcm_runtime *runtime = substream->runtime;
if (chip->caps & ES18XX_NEW_RATE) {
if (runtime->rate_num == new_clocks[0].num)
bits = 128 - runtime->rate_den;
else
bits = 256 - runtime->rate_den;
} else {
if (runtime->rate_num == old_clocks[0].num)
bits = 256 - runtime->rate_den;
else
bits = 128 - runtime->rate_den;
}
/* set filter register */
div0 = 256 - 7160000*20/(8*82*runtime->rate);
if ((chip->caps & ES18XX_PCM2) && mode == DAC2) {
snd_es18xx_mixer_write(chip, 0x70, bits);
/*
* Comment from kernel oss driver:
* FKS: fascinating: 0x72 doesn't seem to work.
*/
snd_es18xx_write(chip, 0xA2, div0);
snd_es18xx_mixer_write(chip, 0x72, div0);
} else {
snd_es18xx_write(chip, 0xA1, bits);
snd_es18xx_write(chip, 0xA2, div0);
}
}
static int snd_es18xx_playback_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
int shift, err;
shift = 0;
if (params_channels(hw_params) == 2)
shift++;
if (snd_pcm_format_width(params_format(hw_params)) == 16)
shift++;
if (substream->number == 0 && (chip->caps & ES18XX_PCM2)) {
if ((chip->caps & ES18XX_DUPLEX_MONO) &&
(chip->capture_a_substream) &&
params_channels(hw_params) != 1) {
_snd_pcm_hw_param_setempty(hw_params, SNDRV_PCM_HW_PARAM_CHANNELS);
return -EBUSY;
}
chip->dma2_shift = shift;
} else {
chip->dma1_shift = shift;
}
if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0)
return err;
return 0;
}
static int snd_es18xx_pcm_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
static int snd_es18xx_playback1_prepare(struct snd_es18xx *chip,
struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned int size = snd_pcm_lib_buffer_bytes(substream);
unsigned int count = snd_pcm_lib_period_bytes(substream);
snd_es18xx_rate_set(chip, substream, DAC2);
/* Transfer Count Reload */
count = 0x10000 - count;
snd_es18xx_mixer_write(chip, 0x74, count & 0xff);
snd_es18xx_mixer_write(chip, 0x76, count >> 8);
/* Set format */
snd_es18xx_mixer_bits(chip, 0x7A, 0x07,
((runtime->channels == 1) ? 0x00 : 0x02) |
(snd_pcm_format_width(runtime->format) == 16 ? 0x01 : 0x00) |
(snd_pcm_format_unsigned(runtime->format) ? 0x00 : 0x04));
/* Set DMA controller */
snd_dma_program(chip->dma2, runtime->dma_addr, size, DMA_MODE_WRITE | DMA_AUTOINIT);
return 0;
}
static int snd_es18xx_playback1_trigger(struct snd_es18xx *chip,
struct snd_pcm_substream *substream,
int cmd)
{
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (chip->active & DAC2)
return 0;
chip->active |= DAC2;
/* Start DMA */
if (chip->dma2 >= 4)
snd_es18xx_mixer_write(chip, 0x78, 0xb3);
else
snd_es18xx_mixer_write(chip, 0x78, 0x93);
#ifdef AVOID_POPS
/* Avoid pops */
mdelay(100);
if (chip->caps & ES18XX_PCM2)
/* Restore Audio 2 volume */
snd_es18xx_mixer_write(chip, 0x7C, chip->audio2_vol);
else
/* Enable PCM output */
snd_es18xx_dsp_command(chip, 0xD1);
#endif
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
if (!(chip->active & DAC2))
return 0;
chip->active &= ~DAC2;
/* Stop DMA */
snd_es18xx_mixer_write(chip, 0x78, 0x00);
#ifdef AVOID_POPS
mdelay(25);
if (chip->caps & ES18XX_PCM2)
/* Set Audio 2 volume to 0 */
snd_es18xx_mixer_write(chip, 0x7C, 0);
else
/* Disable PCM output */
snd_es18xx_dsp_command(chip, 0xD3);
#endif
break;
default:
return -EINVAL;
}
return 0;
}
static int snd_es18xx_capture_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
int shift, err;
shift = 0;
if ((chip->caps & ES18XX_DUPLEX_MONO) &&
chip->playback_a_substream &&
params_channels(hw_params) != 1) {
_snd_pcm_hw_param_setempty(hw_params, SNDRV_PCM_HW_PARAM_CHANNELS);
return -EBUSY;
}
if (params_channels(hw_params) == 2)
shift++;
if (snd_pcm_format_width(params_format(hw_params)) == 16)
shift++;
chip->dma1_shift = shift;
if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0)
return err;
return 0;
}
static int snd_es18xx_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned int size = snd_pcm_lib_buffer_bytes(substream);
unsigned int count = snd_pcm_lib_period_bytes(substream);
snd_es18xx_reset_fifo(chip);
/* Set stereo/mono */
snd_es18xx_bits(chip, 0xA8, 0x03, runtime->channels == 1 ? 0x02 : 0x01);
snd_es18xx_rate_set(chip, substream, ADC1);
/* Transfer Count Reload */
count = 0x10000 - count;
snd_es18xx_write(chip, 0xA4, count & 0xff);
snd_es18xx_write(chip, 0xA5, count >> 8);
#ifdef AVOID_POPS
mdelay(100);
#endif
/* Set format */
snd_es18xx_write(chip, 0xB7,
snd_pcm_format_unsigned(runtime->format) ? 0x51 : 0x71);
snd_es18xx_write(chip, 0xB7, 0x90 |
((runtime->channels == 1) ? 0x40 : 0x08) |
(snd_pcm_format_width(runtime->format) == 16 ? 0x04 : 0x00) |
(snd_pcm_format_unsigned(runtime->format) ? 0x00 : 0x20));
/* Set DMA controller */
snd_dma_program(chip->dma1, runtime->dma_addr, size, DMA_MODE_READ | DMA_AUTOINIT);
return 0;
}
static int snd_es18xx_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (chip->active & ADC1)
return 0;
chip->active |= ADC1;
/* Start DMA */
snd_es18xx_write(chip, 0xB8, 0x0f);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
if (!(chip->active & ADC1))
return 0;
chip->active &= ~ADC1;
/* Stop DMA */
snd_es18xx_write(chip, 0xB8, 0x00);
break;
default:
return -EINVAL;
}
return 0;
}
static int snd_es18xx_playback2_prepare(struct snd_es18xx *chip,
struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned int size = snd_pcm_lib_buffer_bytes(substream);
unsigned int count = snd_pcm_lib_period_bytes(substream);
snd_es18xx_reset_fifo(chip);
/* Set stereo/mono */
snd_es18xx_bits(chip, 0xA8, 0x03, runtime->channels == 1 ? 0x02 : 0x01);
snd_es18xx_rate_set(chip, substream, DAC1);
/* Transfer Count Reload */
count = 0x10000 - count;
snd_es18xx_write(chip, 0xA4, count & 0xff);
snd_es18xx_write(chip, 0xA5, count >> 8);
/* Set format */
snd_es18xx_write(chip, 0xB6,
snd_pcm_format_unsigned(runtime->format) ? 0x80 : 0x00);
snd_es18xx_write(chip, 0xB7,
snd_pcm_format_unsigned(runtime->format) ? 0x51 : 0x71);
snd_es18xx_write(chip, 0xB7, 0x90 |
(runtime->channels == 1 ? 0x40 : 0x08) |
(snd_pcm_format_width(runtime->format) == 16 ? 0x04 : 0x00) |
(snd_pcm_format_unsigned(runtime->format) ? 0x00 : 0x20));
/* Set DMA controller */
snd_dma_program(chip->dma1, runtime->dma_addr, size, DMA_MODE_WRITE | DMA_AUTOINIT);
return 0;
}
static int snd_es18xx_playback2_trigger(struct snd_es18xx *chip,
struct snd_pcm_substream *substream,
int cmd)
{
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (chip->active & DAC1)
return 0;
chip->active |= DAC1;
/* Start DMA */
snd_es18xx_write(chip, 0xB8, 0x05);
#ifdef AVOID_POPS
/* Avoid pops */
mdelay(100);
/* Enable Audio 1 */
snd_es18xx_dsp_command(chip, 0xD1);
#endif
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
if (!(chip->active & DAC1))
return 0;
chip->active &= ~DAC1;
/* Stop DMA */
snd_es18xx_write(chip, 0xB8, 0x00);
#ifdef AVOID_POPS
/* Avoid pops */
mdelay(25);
/* Disable Audio 1 */
snd_es18xx_dsp_command(chip, 0xD3);
#endif
break;
default:
return -EINVAL;
}
return 0;
}
static int snd_es18xx_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
if (substream->number == 0 && (chip->caps & ES18XX_PCM2))
return snd_es18xx_playback1_prepare(chip, substream);
else
return snd_es18xx_playback2_prepare(chip, substream);
}
static int snd_es18xx_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
if (substream->number == 0 && (chip->caps & ES18XX_PCM2))
return snd_es18xx_playback1_trigger(chip, substream, cmd);
else
return snd_es18xx_playback2_trigger(chip, substream, cmd);
}
static irqreturn_t snd_es18xx_interrupt(int irq, void *dev_id)
{
struct snd_card *card = dev_id;
struct snd_es18xx *chip = card->private_data;
unsigned char status;
if (chip->caps & ES18XX_CONTROL) {
/* Read Interrupt status */
status = inb(chip->ctrl_port + 6);
} else {
/* Read Interrupt status */
status = snd_es18xx_mixer_read(chip, 0x7f) >> 4;
}
#if 0
else {
status = 0;
if (inb(chip->port + 0x0C) & 0x01)
status |= AUDIO1_IRQ;
if (snd_es18xx_mixer_read(chip, 0x7A) & 0x80)
status |= AUDIO2_IRQ;
if ((chip->caps & ES18XX_HWV) &&
snd_es18xx_mixer_read(chip, 0x64) & 0x10)
status |= HWV_IRQ;
}
#endif
/* Audio 1 & Audio 2 */
if (status & AUDIO2_IRQ) {
if (chip->active & DAC2)
snd_pcm_period_elapsed(chip->playback_a_substream);
/* ack interrupt */
snd_es18xx_mixer_bits(chip, 0x7A, 0x80, 0x00);
}
if (status & AUDIO1_IRQ) {
/* ok.. capture is active */
if (chip->active & ADC1)
snd_pcm_period_elapsed(chip->capture_a_substream);
/* ok.. playback2 is active */
else if (chip->active & DAC1)
snd_pcm_period_elapsed(chip->playback_b_substream);
/* ack interrupt */
inb(chip->port + 0x0E);
}
/* MPU */
if ((status & MPU_IRQ) && chip->rmidi)
snd_mpu401_uart_interrupt(irq, chip->rmidi->private_data);
/* Hardware volume */
if (status & HWV_IRQ) {
int split = 0;
if (chip->caps & ES18XX_HWV) {
split = snd_es18xx_mixer_read(chip, 0x64) & 0x80;
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->hw_switch->id);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->hw_volume->id);
}
if (!split) {
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->master_switch->id);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->master_volume->id);
}
/* ack interrupt */
snd_es18xx_mixer_write(chip, 0x66, 0x00);
}
return IRQ_HANDLED;
}
static snd_pcm_uframes_t snd_es18xx_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
unsigned int size = snd_pcm_lib_buffer_bytes(substream);
int pos;
if (substream->number == 0 && (chip->caps & ES18XX_PCM2)) {
if (!(chip->active & DAC2))
return 0;
pos = snd_dma_pointer(chip->dma2, size);
return pos >> chip->dma2_shift;
} else {
if (!(chip->active & DAC1))
return 0;
pos = snd_dma_pointer(chip->dma1, size);
return pos >> chip->dma1_shift;
}
}
static snd_pcm_uframes_t snd_es18xx_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
unsigned int size = snd_pcm_lib_buffer_bytes(substream);
int pos;
if (!(chip->active & ADC1))
return 0;
pos = snd_dma_pointer(chip->dma1, size);
return pos >> chip->dma1_shift;
}
static struct snd_pcm_hardware snd_es18xx_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = (SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S8 |
SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U16_LE),
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 65536,
.period_bytes_min = 64,
.period_bytes_max = 65536,
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_es18xx_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = (SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S8 |
SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U16_LE),
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 65536,
.period_bytes_min = 64,
.period_bytes_max = 65536,
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
static int snd_es18xx_playback_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
if (substream->number == 0 && (chip->caps & ES18XX_PCM2)) {
if ((chip->caps & ES18XX_DUPLEX_MONO) &&
chip->capture_a_substream &&
chip->capture_a_substream->runtime->channels != 1)
return -EAGAIN;
chip->playback_a_substream = substream;
} else if (substream->number <= 1) {
if (chip->capture_a_substream)
return -EAGAIN;
chip->playback_b_substream = substream;
} else {
snd_BUG();
return -EINVAL;
}
substream->runtime->hw = snd_es18xx_playback;
snd_pcm_hw_constraint_ratnums(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
(chip->caps & ES18XX_NEW_RATE) ? &new_hw_constraints_clocks : &old_hw_constraints_clocks);
return 0;
}
static int snd_es18xx_capture_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
if (chip->playback_b_substream)
return -EAGAIN;
if ((chip->caps & ES18XX_DUPLEX_MONO) &&
chip->playback_a_substream &&
chip->playback_a_substream->runtime->channels != 1)
return -EAGAIN;
chip->capture_a_substream = substream;
substream->runtime->hw = snd_es18xx_capture;
snd_pcm_hw_constraint_ratnums(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
(chip->caps & ES18XX_NEW_RATE) ? &new_hw_constraints_clocks : &old_hw_constraints_clocks);
return 0;
}
static int snd_es18xx_playback_close(struct snd_pcm_substream *substream)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
if (substream->number == 0 && (chip->caps & ES18XX_PCM2))
chip->playback_a_substream = NULL;
else
chip->playback_b_substream = NULL;
snd_pcm_lib_free_pages(substream);
return 0;
}
static int snd_es18xx_capture_close(struct snd_pcm_substream *substream)
{
struct snd_es18xx *chip = snd_pcm_substream_chip(substream);
chip->capture_a_substream = NULL;
snd_pcm_lib_free_pages(substream);
return 0;
}
/*
* MIXER part
*/
/* Record source mux routines:
* Depending on the chipset this mux switches between 4, 5, or 8 possible inputs.
* bit table for the 4/5 source mux:
* reg 1C:
* b2 b1 b0 muxSource
* x 0 x microphone
* 0 1 x CD
* 1 1 0 line
* 1 1 1 mixer
* if it's "mixer" and it's a 5 source mux chipset then reg 7A bit 3 determines
* either the play mixer or the capture mixer.
*
* "map4Source" translates from source number to reg bit pattern
* "invMap4Source" translates from reg bit pattern to source number
*/
static int snd_es18xx_info_mux(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts5Source[5] = {
"Mic", "CD", "Line", "Master", "Mix"
};
static char *texts8Source[8] = {
"Mic", "Mic Master", "CD", "AOUT",
"Mic1", "Mix", "Line", "Master"
};
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
switch (chip->version) {
case 0x1868:
case 0x1878:
uinfo->value.enumerated.items = 4;
if (uinfo->value.enumerated.item > 3)
uinfo->value.enumerated.item = 3;
strcpy(uinfo->value.enumerated.name,
texts5Source[uinfo->value.enumerated.item]);
break;
case 0x1887:
case 0x1888:
uinfo->value.enumerated.items = 5;
if (uinfo->value.enumerated.item > 4)
uinfo->value.enumerated.item = 4;
strcpy(uinfo->value.enumerated.name, texts5Source[uinfo->value.enumerated.item]);
break;
case 0x1869: /* DS somewhat contradictory for 1869: could be be 5 or 8 */
case 0x1879:
uinfo->value.enumerated.items = 8;
if (uinfo->value.enumerated.item > 7)
uinfo->value.enumerated.item = 7;
strcpy(uinfo->value.enumerated.name, texts8Source[uinfo->value.enumerated.item]);
break;
default:
return -EINVAL;
}
return 0;
}
static int snd_es18xx_get_mux(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
static unsigned char invMap4Source[8] = {0, 0, 1, 1, 0, 0, 2, 3};
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
int muxSource = snd_es18xx_mixer_read(chip, 0x1c) & 0x07;
if (!(chip->version == 0x1869 || chip->version == 0x1879)) {
muxSource = invMap4Source[muxSource];
if (muxSource==3 &&
(chip->version == 0x1887 || chip->version == 0x1888) &&
(snd_es18xx_mixer_read(chip, 0x7a) & 0x08)
)
muxSource = 4;
}
ucontrol->value.enumerated.item[0] = muxSource;
return 0;
}
static int snd_es18xx_put_mux(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
static unsigned char map4Source[4] = {0, 2, 6, 7};
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
unsigned char val = ucontrol->value.enumerated.item[0];
unsigned char retVal = 0;
switch (chip->version) {
/* 5 source chips */
case 0x1887:
case 0x1888:
if (val > 4)
return -EINVAL;
if (val == 4) {
retVal = snd_es18xx_mixer_bits(chip, 0x7a, 0x08, 0x08) != 0x08;
val = 3;
} else
retVal = snd_es18xx_mixer_bits(chip, 0x7a, 0x08, 0x00) != 0x00;
/* 4 source chips */
case 0x1868:
case 0x1878:
if (val > 3)
return -EINVAL;
val = map4Source[val];
break;
/* 8 source chips */
case 0x1869:
case 0x1879:
if (val > 7)
return -EINVAL;
break;
default:
return -EINVAL;
}
return (snd_es18xx_mixer_bits(chip, 0x1c, 0x07, val) != val) || retVal;
}
#define snd_es18xx_info_spatializer_enable snd_ctl_boolean_mono_info
static int snd_es18xx_get_spatializer_enable(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
unsigned char val = snd_es18xx_mixer_read(chip, 0x50);
ucontrol->value.integer.value[0] = !!(val & 8);
return 0;
}
static int snd_es18xx_put_spatializer_enable(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
unsigned char oval, nval;
int change;
nval = ucontrol->value.integer.value[0] ? 0x0c : 0x04;
oval = snd_es18xx_mixer_read(chip, 0x50) & 0x0c;
change = nval != oval;
if (change) {
snd_es18xx_mixer_write(chip, 0x50, nval & ~0x04);
snd_es18xx_mixer_write(chip, 0x50, nval);
}
return change;
}
static int snd_es18xx_info_hw_volume(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 63;
return 0;
}
static int snd_es18xx_get_hw_volume(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = snd_es18xx_mixer_read(chip, 0x61) & 0x3f;
ucontrol->value.integer.value[1] = snd_es18xx_mixer_read(chip, 0x63) & 0x3f;
return 0;
}
#define snd_es18xx_info_hw_switch snd_ctl_boolean_stereo_info
static int snd_es18xx_get_hw_switch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = !(snd_es18xx_mixer_read(chip, 0x61) & 0x40);
ucontrol->value.integer.value[1] = !(snd_es18xx_mixer_read(chip, 0x63) & 0x40);
return 0;
}
static void snd_es18xx_hwv_free(struct snd_kcontrol *kcontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
chip->master_volume = NULL;
chip->master_switch = NULL;
chip->hw_volume = NULL;
chip->hw_switch = NULL;
}
static int snd_es18xx_reg_bits(struct snd_es18xx *chip, unsigned char reg,
unsigned char mask, unsigned char val)
{
if (reg < 0xa0)
return snd_es18xx_mixer_bits(chip, reg, mask, val);
else
return snd_es18xx_bits(chip, reg, mask, val);
}
static int snd_es18xx_reg_read(struct snd_es18xx *chip, unsigned char reg)
{
if (reg < 0xa0)
return snd_es18xx_mixer_read(chip, reg);
else
return snd_es18xx_read(chip, reg);
}
#define ES18XX_SINGLE(xname, xindex, reg, shift, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_es18xx_info_single, \
.get = snd_es18xx_get_single, .put = snd_es18xx_put_single, \
.private_value = reg | (shift << 8) | (mask << 16) | (invert << 24) }
static int snd_es18xx_info_single(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 16) & 0xff;
uinfo->type = mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int snd_es18xx_get_single(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
int val;
val = snd_es18xx_reg_read(chip, reg);
ucontrol->value.integer.value[0] = (val >> shift) & mask;
if (invert)
ucontrol->value.integer.value[0] = mask - ucontrol->value.integer.value[0];
return 0;
}
static int snd_es18xx_put_single(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
unsigned char val;
val = (ucontrol->value.integer.value[0] & mask);
if (invert)
val = mask - val;
mask <<= shift;
val <<= shift;
return snd_es18xx_reg_bits(chip, reg, mask, val) != val;
}
#define ES18XX_DOUBLE(xname, xindex, left_reg, right_reg, shift_left, shift_right, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_es18xx_info_double, \
.get = snd_es18xx_get_double, .put = snd_es18xx_put_double, \
.private_value = left_reg | (right_reg << 8) | (shift_left << 16) | (shift_right << 19) | (mask << 24) | (invert << 22) }
static int snd_es18xx_info_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 24) & 0xff;
uinfo->type = mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int snd_es18xx_get_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
unsigned char left, right;
left = snd_es18xx_reg_read(chip, left_reg);
if (left_reg != right_reg)
right = snd_es18xx_reg_read(chip, right_reg);
else
right = left;
ucontrol->value.integer.value[0] = (left >> shift_left) & mask;
ucontrol->value.integer.value[1] = (right >> shift_right) & mask;
if (invert) {
ucontrol->value.integer.value[0] = mask - ucontrol->value.integer.value[0];
ucontrol->value.integer.value[1] = mask - ucontrol->value.integer.value[1];
}
return 0;
}
static int snd_es18xx_put_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_es18xx *chip = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
int change;
unsigned char val1, val2, mask1, mask2;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
if (invert) {
val1 = mask - val1;
val2 = mask - val2;
}
val1 <<= shift_left;
val2 <<= shift_right;
mask1 = mask << shift_left;
mask2 = mask << shift_right;
if (left_reg != right_reg) {
change = 0;
if (snd_es18xx_reg_bits(chip, left_reg, mask1, val1) != val1)
change = 1;
if (snd_es18xx_reg_bits(chip, right_reg, mask2, val2) != val2)
change = 1;
} else {
change = (snd_es18xx_reg_bits(chip, left_reg, mask1 | mask2,
val1 | val2) != (val1 | val2));
}
return change;
}
/* Mixer controls
* These arrays contain setup data for mixer controls.
*
* The controls that are universal to all chipsets are fully initialized
* here.
*/
static struct snd_kcontrol_new snd_es18xx_base_controls[] = {
ES18XX_DOUBLE("Master Playback Volume", 0, 0x60, 0x62, 0, 0, 63, 0),
ES18XX_DOUBLE("Master Playback Switch", 0, 0x60, 0x62, 6, 6, 1, 1),
ES18XX_DOUBLE("Line Playback Volume", 0, 0x3e, 0x3e, 4, 0, 15, 0),
ES18XX_DOUBLE("CD Playback Volume", 0, 0x38, 0x38, 4, 0, 15, 0),
ES18XX_DOUBLE("FM Playback Volume", 0, 0x36, 0x36, 4, 0, 15, 0),
ES18XX_DOUBLE("Mic Playback Volume", 0, 0x1a, 0x1a, 4, 0, 15, 0),
ES18XX_DOUBLE("Aux Playback Volume", 0, 0x3a, 0x3a, 4, 0, 15, 0),
ES18XX_SINGLE("Record Monitor", 0, 0xa8, 3, 1, 0),
ES18XX_DOUBLE("Capture Volume", 0, 0xb4, 0xb4, 4, 0, 15, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = snd_es18xx_info_mux,
.get = snd_es18xx_get_mux,
.put = snd_es18xx_put_mux,
}
};
static struct snd_kcontrol_new snd_es18xx_recmix_controls[] = {
ES18XX_DOUBLE("PCM Capture Volume", 0, 0x69, 0x69, 4, 0, 15, 0),
ES18XX_DOUBLE("Mic Capture Volume", 0, 0x68, 0x68, 4, 0, 15, 0),
ES18XX_DOUBLE("Line Capture Volume", 0, 0x6e, 0x6e, 4, 0, 15, 0),
ES18XX_DOUBLE("FM Capture Volume", 0, 0x6b, 0x6b, 4, 0, 15, 0),
ES18XX_DOUBLE("CD Capture Volume", 0, 0x6a, 0x6a, 4, 0, 15, 0),
ES18XX_DOUBLE("Aux Capture Volume", 0, 0x6c, 0x6c, 4, 0, 15, 0)
};
/*
* The chipset specific mixer controls
*/
static struct snd_kcontrol_new snd_es18xx_opt_speaker =
ES18XX_SINGLE("Beep Playback Volume", 0, 0x3c, 0, 7, 0);
static struct snd_kcontrol_new snd_es18xx_opt_1869[] = {
ES18XX_SINGLE("Capture Switch", 0, 0x1c, 4, 1, 1),
ES18XX_SINGLE("Video Playback Switch", 0, 0x7f, 0, 1, 0),
ES18XX_DOUBLE("Mono Playback Volume", 0, 0x6d, 0x6d, 4, 0, 15, 0),
ES18XX_DOUBLE("Mono Capture Volume", 0, 0x6f, 0x6f, 4, 0, 15, 0)
};
static struct snd_kcontrol_new snd_es18xx_opt_1878 =
ES18XX_DOUBLE("Video Playback Volume", 0, 0x68, 0x68, 4, 0, 15, 0);
static struct snd_kcontrol_new snd_es18xx_opt_1879[] = {
ES18XX_SINGLE("Video Playback Switch", 0, 0x71, 6, 1, 0),
ES18XX_DOUBLE("Video Playback Volume", 0, 0x6d, 0x6d, 4, 0, 15, 0),
ES18XX_DOUBLE("Video Capture Volume", 0, 0x6f, 0x6f, 4, 0, 15, 0)
};
static struct snd_kcontrol_new snd_es18xx_pcm1_controls[] = {
ES18XX_DOUBLE("PCM Playback Volume", 0, 0x14, 0x14, 4, 0, 15, 0),
};
static struct snd_kcontrol_new snd_es18xx_pcm2_controls[] = {
ES18XX_DOUBLE("PCM Playback Volume", 0, 0x7c, 0x7c, 4, 0, 15, 0),
ES18XX_DOUBLE("PCM Playback Volume", 1, 0x14, 0x14, 4, 0, 15, 0)
};
static struct snd_kcontrol_new snd_es18xx_spatializer_controls[] = {
ES18XX_SINGLE("3D Control - Level", 0, 0x52, 0, 63, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "3D Control - Switch",
.info = snd_es18xx_info_spatializer_enable,
.get = snd_es18xx_get_spatializer_enable,
.put = snd_es18xx_put_spatializer_enable,
}
};
static struct snd_kcontrol_new snd_es18xx_micpre1_control =
ES18XX_SINGLE("Mic Boost (+26dB)", 0, 0xa9, 2, 1, 0);
static struct snd_kcontrol_new snd_es18xx_micpre2_control =
ES18XX_SINGLE("Mic Boost (+26dB)", 0, 0x7d, 3, 1, 0);
static struct snd_kcontrol_new snd_es18xx_hw_volume_controls[] = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Hardware Master Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.info = snd_es18xx_info_hw_volume,
.get = snd_es18xx_get_hw_volume,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Hardware Master Playback Switch",
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.info = snd_es18xx_info_hw_switch,
.get = snd_es18xx_get_hw_switch,
},
ES18XX_SINGLE("Hardware Master Volume Split", 0, 0x64, 7, 1, 0),
};
static int snd_es18xx_config_read(struct snd_es18xx *chip, unsigned char reg)
{
int data;
outb(reg, chip->ctrl_port);
data = inb(chip->ctrl_port + 1);
return data;
}
static void snd_es18xx_config_write(struct snd_es18xx *chip,
unsigned char reg, unsigned char data)
{
/* No need for spinlocks, this function is used only in
otherwise protected init code */
outb(reg, chip->ctrl_port);
outb(data, chip->ctrl_port + 1);
#ifdef REG_DEBUG
snd_printk(KERN_DEBUG "Config reg %02x set to %02x\n", reg, data);
#endif
}
static int snd_es18xx_initialize(struct snd_es18xx *chip,
unsigned long mpu_port,
unsigned long fm_port)
{
int mask = 0;
/* enable extended mode */
snd_es18xx_dsp_command(chip, 0xC6);
/* Reset mixer registers */
snd_es18xx_mixer_write(chip, 0x00, 0x00);
/* Audio 1 DMA demand mode (4 bytes/request) */
snd_es18xx_write(chip, 0xB9, 2);
if (chip->caps & ES18XX_CONTROL) {
/* Hardware volume IRQ */
snd_es18xx_config_write(chip, 0x27, chip->irq);
if (fm_port > 0 && fm_port != SNDRV_AUTO_PORT) {
/* FM I/O */
snd_es18xx_config_write(chip, 0x62, fm_port >> 8);
snd_es18xx_config_write(chip, 0x63, fm_port & 0xff);
}
if (mpu_port > 0 && mpu_port != SNDRV_AUTO_PORT) {
/* MPU-401 I/O */
snd_es18xx_config_write(chip, 0x64, mpu_port >> 8);
snd_es18xx_config_write(chip, 0x65, mpu_port & 0xff);
/* MPU-401 IRQ */
snd_es18xx_config_write(chip, 0x28, chip->irq);
}
/* Audio1 IRQ */
snd_es18xx_config_write(chip, 0x70, chip->irq);
/* Audio2 IRQ */
snd_es18xx_config_write(chip, 0x72, chip->irq);
/* Audio1 DMA */
snd_es18xx_config_write(chip, 0x74, chip->dma1);
/* Audio2 DMA */
snd_es18xx_config_write(chip, 0x75, chip->dma2);
/* Enable Audio 1 IRQ */
snd_es18xx_write(chip, 0xB1, 0x50);
/* Enable Audio 2 IRQ */
snd_es18xx_mixer_write(chip, 0x7A, 0x40);
/* Enable Audio 1 DMA */
snd_es18xx_write(chip, 0xB2, 0x50);
/* Enable MPU and hardware volume interrupt */
snd_es18xx_mixer_write(chip, 0x64, 0x42);
/* Enable ESS wavetable input */
snd_es18xx_mixer_bits(chip, 0x48, 0x10, 0x10);
}
else {
int irqmask, dma1mask, dma2mask;
switch (chip->irq) {
case 2:
case 9:
irqmask = 0;
break;
case 5:
irqmask = 1;
break;
case 7:
irqmask = 2;
break;
case 10:
irqmask = 3;
break;
default:
snd_printk(KERN_ERR "invalid irq %d\n", chip->irq);
return -ENODEV;
}
switch (chip->dma1) {
case 0:
dma1mask = 1;
break;
case 1:
dma1mask = 2;
break;
case 3:
dma1mask = 3;
break;
default:
snd_printk(KERN_ERR "invalid dma1 %d\n", chip->dma1);
return -ENODEV;
}
switch (chip->dma2) {
case 0:
dma2mask = 0;
break;
case 1:
dma2mask = 1;
break;
case 3:
dma2mask = 2;
break;
case 5:
dma2mask = 3;
break;
default:
snd_printk(KERN_ERR "invalid dma2 %d\n", chip->dma2);
return -ENODEV;
}
/* Enable and set Audio 1 IRQ */
snd_es18xx_write(chip, 0xB1, 0x50 | (irqmask << 2));
/* Enable and set Audio 1 DMA */
snd_es18xx_write(chip, 0xB2, 0x50 | (dma1mask << 2));
/* Set Audio 2 DMA */
snd_es18xx_mixer_bits(chip, 0x7d, 0x07, 0x04 | dma2mask);
/* Enable Audio 2 IRQ and DMA
Set capture mixer input */
snd_es18xx_mixer_write(chip, 0x7A, 0x68);
/* Enable and set hardware volume interrupt */
snd_es18xx_mixer_write(chip, 0x64, 0x06);
if (mpu_port > 0 && mpu_port != SNDRV_AUTO_PORT) {
/* MPU401 share irq with audio
Joystick enabled
FM enabled */
snd_es18xx_mixer_write(chip, 0x40,
0x43 | (mpu_port & 0xf0) >> 1);
}
snd_es18xx_mixer_write(chip, 0x7f, ((irqmask + 1) << 1) | 0x01);
}
if (chip->caps & ES18XX_NEW_RATE) {
/* Change behaviour of register A1
4x oversampling
2nd channel DAC asynchronous */
snd_es18xx_mixer_write(chip, 0x71, 0x32);
}
if (!(chip->caps & ES18XX_PCM2)) {
/* Enable DMA FIFO */
snd_es18xx_write(chip, 0xB7, 0x80);
}
if (chip->caps & ES18XX_SPATIALIZER) {
/* Set spatializer parameters to recommended values */
snd_es18xx_mixer_write(chip, 0x54, 0x8f);
snd_es18xx_mixer_write(chip, 0x56, 0x95);
snd_es18xx_mixer_write(chip, 0x58, 0x94);
snd_es18xx_mixer_write(chip, 0x5a, 0x80);
}
/* Flip the "enable I2S" bits for those chipsets that need it */
switch (chip->version) {
case 0x1879:
//Leaving I2S enabled on the 1879 screws up the PCM playback (rate effected somehow)
//so a Switch control has been added to toggle this 0x71 bit on/off:
//snd_es18xx_mixer_bits(chip, 0x71, 0x40, 0x40);
/* Note: we fall through on purpose here. */
case 0x1878:
snd_es18xx_config_write(chip, 0x29, snd_es18xx_config_read(chip, 0x29) | 0x40);
break;
}
/* Mute input source */
if (chip->caps & ES18XX_MUTEREC)
mask = 0x10;
if (chip->caps & ES18XX_RECMIX)
snd_es18xx_mixer_write(chip, 0x1c, 0x05 | mask);
else {
snd_es18xx_mixer_write(chip, 0x1c, 0x00 | mask);
snd_es18xx_write(chip, 0xb4, 0x00);
}
#ifndef AVOID_POPS
/* Enable PCM output */
snd_es18xx_dsp_command(chip, 0xD1);
#endif
return 0;
}
static int snd_es18xx_identify(struct snd_es18xx *chip)
{
int hi,lo;
/* reset */
if (snd_es18xx_reset(chip) < 0) {
snd_printk(KERN_ERR "reset at 0x%lx failed!!!\n", chip->port);
return -ENODEV;
}
snd_es18xx_dsp_command(chip, 0xe7);
hi = snd_es18xx_dsp_get_byte(chip);
if (hi < 0) {
return hi;
}
lo = snd_es18xx_dsp_get_byte(chip);
if ((lo & 0xf0) != 0x80) {
return -ENODEV;
}
if (hi == 0x48) {
chip->version = 0x488;
return 0;
}
if (hi != 0x68) {
return -ENODEV;
}
if ((lo & 0x0f) < 8) {
chip->version = 0x688;
return 0;
}
outb(0x40, chip->port + 0x04);
udelay(10);
hi = inb(chip->port + 0x05);
udelay(10);
lo = inb(chip->port + 0x05);
if (hi != lo) {
chip->version = hi << 8 | lo;
chip->ctrl_port = inb(chip->port + 0x05) << 8;
udelay(10);
chip->ctrl_port += inb(chip->port + 0x05);
if ((chip->res_ctrl_port = request_region(chip->ctrl_port, 8, "ES18xx - CTRL")) == NULL) {
snd_printk(KERN_ERR PFX "unable go grab port 0x%lx\n", chip->ctrl_port);
return -EBUSY;
}
return 0;
}
/* If has Hardware volume */
if (snd_es18xx_mixer_writable(chip, 0x64, 0x04)) {
/* If has Audio2 */
if (snd_es18xx_mixer_writable(chip, 0x70, 0x7f)) {
/* If has volume count */
if (snd_es18xx_mixer_writable(chip, 0x64, 0x20)) {
chip->version = 0x1887;
} else {
chip->version = 0x1888;
}
} else {
chip->version = 0x1788;
}
}
else
chip->version = 0x1688;
return 0;
}
static int snd_es18xx_probe(struct snd_es18xx *chip,
unsigned long mpu_port,
unsigned long fm_port)
{
if (snd_es18xx_identify(chip) < 0) {
snd_printk(KERN_ERR PFX "[0x%lx] ESS chip not found\n", chip->port);
return -ENODEV;
}
switch (chip->version) {
case 0x1868:
chip->caps = ES18XX_DUPLEX_MONO | ES18XX_DUPLEX_SAME | ES18XX_CONTROL;
break;
case 0x1869:
chip->caps = ES18XX_PCM2 | ES18XX_SPATIALIZER | ES18XX_RECMIX | ES18XX_NEW_RATE | ES18XX_AUXB | ES18XX_MONO | ES18XX_MUTEREC | ES18XX_CONTROL | ES18XX_HWV;
break;
case 0x1878:
chip->caps = ES18XX_DUPLEX_MONO | ES18XX_DUPLEX_SAME | ES18XX_I2S | ES18XX_CONTROL;
break;
case 0x1879:
chip->caps = ES18XX_PCM2 | ES18XX_SPATIALIZER | ES18XX_RECMIX | ES18XX_NEW_RATE | ES18XX_AUXB | ES18XX_I2S | ES18XX_CONTROL | ES18XX_HWV;
break;
case 0x1887:
case 0x1888:
chip->caps = ES18XX_PCM2 | ES18XX_RECMIX | ES18XX_AUXB | ES18XX_DUPLEX_SAME;
break;
default:
snd_printk(KERN_ERR "[0x%lx] unsupported chip ES%x\n",
chip->port, chip->version);
return -ENODEV;
}
snd_printd("[0x%lx] ESS%x chip found\n", chip->port, chip->version);
if (chip->dma1 == chip->dma2)
chip->caps &= ~(ES18XX_PCM2 | ES18XX_DUPLEX_SAME);
return snd_es18xx_initialize(chip, mpu_port, fm_port);
}
static struct snd_pcm_ops snd_es18xx_playback_ops = {
.open = snd_es18xx_playback_open,
.close = snd_es18xx_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_es18xx_playback_hw_params,
.hw_free = snd_es18xx_pcm_hw_free,
.prepare = snd_es18xx_playback_prepare,
.trigger = snd_es18xx_playback_trigger,
.pointer = snd_es18xx_playback_pointer,
};
static struct snd_pcm_ops snd_es18xx_capture_ops = {
.open = snd_es18xx_capture_open,
.close = snd_es18xx_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_es18xx_capture_hw_params,
.hw_free = snd_es18xx_pcm_hw_free,
.prepare = snd_es18xx_capture_prepare,
.trigger = snd_es18xx_capture_trigger,
.pointer = snd_es18xx_capture_pointer,
};
static int snd_es18xx_pcm(struct snd_card *card, int device,
struct snd_pcm **rpcm)
{
struct snd_es18xx *chip = card->private_data;
struct snd_pcm *pcm;
char str[16];
int err;
if (rpcm)
*rpcm = NULL;
sprintf(str, "ES%x", chip->version);
if (chip->caps & ES18XX_PCM2)
err = snd_pcm_new(card, str, device, 2, 1, &pcm);
else
err = snd_pcm_new(card, str, device, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_es18xx_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_es18xx_capture_ops);
/* global setup */
pcm->private_data = chip;
pcm->info_flags = 0;
if (chip->caps & ES18XX_DUPLEX_SAME)
pcm->info_flags |= SNDRV_PCM_INFO_JOINT_DUPLEX;
if (! (chip->caps & ES18XX_PCM2))
pcm->info_flags |= SNDRV_PCM_INFO_HALF_DUPLEX;
sprintf(pcm->name, "ESS AudioDrive ES%x", chip->version);
chip->pcm = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_isa_data(),
64*1024,
chip->dma1 > 3 || chip->dma2 > 3 ? 128*1024 : 64*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
/* Power Management support functions */
#ifdef CONFIG_PM
static int snd_es18xx_suspend(struct snd_card *card, pm_message_t state)
{
struct snd_es18xx *chip = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
/* power down */
chip->pm_reg = (unsigned char)snd_es18xx_read(chip, ES18XX_PM);
chip->pm_reg |= (ES18XX_PM_FM | ES18XX_PM_SUS);
snd_es18xx_write(chip, ES18XX_PM, chip->pm_reg);
snd_es18xx_write(chip, ES18XX_PM, chip->pm_reg ^= ES18XX_PM_SUS);
return 0;
}
static int snd_es18xx_resume(struct snd_card *card)
{
struct snd_es18xx *chip = card->private_data;
/* restore PM register, we won't wake till (not 0x07) i/o activity though */
snd_es18xx_write(chip, ES18XX_PM, chip->pm_reg ^= ES18XX_PM_FM);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
static int snd_es18xx_free(struct snd_card *card)
{
struct snd_es18xx *chip = card->private_data;
release_and_free_resource(chip->res_port);
release_and_free_resource(chip->res_ctrl_port);
release_and_free_resource(chip->res_mpu_port);
if (chip->irq >= 0)
free_irq(chip->irq, (void *) card);
if (chip->dma1 >= 0) {
disable_dma(chip->dma1);
free_dma(chip->dma1);
}
if (chip->dma2 >= 0 && chip->dma1 != chip->dma2) {
disable_dma(chip->dma2);
free_dma(chip->dma2);
}
return 0;
}
static int snd_es18xx_dev_free(struct snd_device *device)
{
return snd_es18xx_free(device->card);
}
static int snd_es18xx_new_device(struct snd_card *card,
unsigned long port,
unsigned long mpu_port,
unsigned long fm_port,
int irq, int dma1, int dma2)
{
struct snd_es18xx *chip = card->private_data;
static struct snd_device_ops ops = {
.dev_free = snd_es18xx_dev_free,
};
int err;
spin_lock_init(&chip->reg_lock);
spin_lock_init(&chip->mixer_lock);
chip->port = port;
chip->irq = -1;
chip->dma1 = -1;
chip->dma2 = -1;
chip->audio2_vol = 0x00;
chip->active = 0;
chip->res_port = request_region(port, 16, "ES18xx");
if (chip->res_port == NULL) {
snd_es18xx_free(card);
snd_printk(KERN_ERR PFX "unable to grap ports 0x%lx-0x%lx\n", port, port + 16 - 1);
return -EBUSY;
}
if (request_irq(irq, snd_es18xx_interrupt, 0, "ES18xx",
(void *) card)) {
snd_es18xx_free(card);
snd_printk(KERN_ERR PFX "unable to grap IRQ %d\n", irq);
return -EBUSY;
}
chip->irq = irq;
if (request_dma(dma1, "ES18xx DMA 1")) {
snd_es18xx_free(card);
snd_printk(KERN_ERR PFX "unable to grap DMA1 %d\n", dma1);
return -EBUSY;
}
chip->dma1 = dma1;
if (dma2 != dma1 && request_dma(dma2, "ES18xx DMA 2")) {
snd_es18xx_free(card);
snd_printk(KERN_ERR PFX "unable to grap DMA2 %d\n", dma2);
return -EBUSY;
}
chip->dma2 = dma2;
if (snd_es18xx_probe(chip, mpu_port, fm_port) < 0) {
snd_es18xx_free(card);
return -ENODEV;
}
err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
if (err < 0) {
snd_es18xx_free(card);
return err;
}
return 0;
}
static int snd_es18xx_mixer(struct snd_card *card)
{
struct snd_es18xx *chip = card->private_data;
int err;
unsigned int idx;
strcpy(card->mixername, chip->pcm->name);
for (idx = 0; idx < ARRAY_SIZE(snd_es18xx_base_controls); idx++) {
struct snd_kcontrol *kctl;
kctl = snd_ctl_new1(&snd_es18xx_base_controls[idx], chip);
if (chip->caps & ES18XX_HWV) {
switch (idx) {
case 0:
chip->master_volume = kctl;
kctl->private_free = snd_es18xx_hwv_free;
break;
case 1:
chip->master_switch = kctl;
kctl->private_free = snd_es18xx_hwv_free;
break;
}
}
if ((err = snd_ctl_add(card, kctl)) < 0)
return err;
}
if (chip->caps & ES18XX_PCM2) {
for (idx = 0; idx < ARRAY_SIZE(snd_es18xx_pcm2_controls); idx++) {
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_es18xx_pcm2_controls[idx], chip))) < 0)
return err;
}
} else {
for (idx = 0; idx < ARRAY_SIZE(snd_es18xx_pcm1_controls); idx++) {
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_es18xx_pcm1_controls[idx], chip))) < 0)
return err;
}
}
if (chip->caps & ES18XX_RECMIX) {
for (idx = 0; idx < ARRAY_SIZE(snd_es18xx_recmix_controls); idx++) {
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_es18xx_recmix_controls[idx], chip))) < 0)
return err;
}
}
switch (chip->version) {
default:
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_es18xx_micpre1_control, chip))) < 0)
return err;
break;
case 0x1869:
case 0x1879:
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_es18xx_micpre2_control, chip))) < 0)
return err;
break;
}
if (chip->caps & ES18XX_SPATIALIZER) {
for (idx = 0; idx < ARRAY_SIZE(snd_es18xx_spatializer_controls); idx++) {
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_es18xx_spatializer_controls[idx], chip))) < 0)
return err;
}
}
if (chip->caps & ES18XX_HWV) {
for (idx = 0; idx < ARRAY_SIZE(snd_es18xx_hw_volume_controls); idx++) {
struct snd_kcontrol *kctl;
kctl = snd_ctl_new1(&snd_es18xx_hw_volume_controls[idx], chip);
if (idx == 0)
chip->hw_volume = kctl;
else
chip->hw_switch = kctl;
kctl->private_free = snd_es18xx_hwv_free;
if ((err = snd_ctl_add(card, kctl)) < 0)
return err;
}
}
/* finish initializing other chipset specific controls
*/
if (chip->version != 0x1868) {
err = snd_ctl_add(card, snd_ctl_new1(&snd_es18xx_opt_speaker,
chip));
if (err < 0)
return err;
}
if (chip->version == 0x1869) {
for (idx = 0; idx < ARRAY_SIZE(snd_es18xx_opt_1869); idx++) {
err = snd_ctl_add(card,
snd_ctl_new1(&snd_es18xx_opt_1869[idx],
chip));
if (err < 0)
return err;
}
} else if (chip->version == 0x1878) {
err = snd_ctl_add(card, snd_ctl_new1(&snd_es18xx_opt_1878,
chip));
if (err < 0)
return err;
} else if (chip->version == 0x1879) {
for (idx = 0; idx < ARRAY_SIZE(snd_es18xx_opt_1879); idx++) {
err = snd_ctl_add(card,
snd_ctl_new1(&snd_es18xx_opt_1879[idx],
chip));
if (err < 0)
return err;
}
}
return 0;
}
/* Card level */
MODULE_AUTHOR("Christian Fischbach <fishbach@pool.informatik.rwth-aachen.de>, Abramo Bagnara <abramo@alsa-project.org>");
MODULE_DESCRIPTION("ESS ES18xx AudioDrive");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{ESS,ES1868 PnP AudioDrive},"
"{ESS,ES1869 PnP AudioDrive},"
"{ESS,ES1878 PnP AudioDrive},"
"{ESS,ES1879 PnP AudioDrive},"
"{ESS,ES1887 PnP AudioDrive},"
"{ESS,ES1888 PnP AudioDrive},"
"{ESS,ES1887 AudioDrive},"
"{ESS,ES1888 AudioDrive}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */
#ifdef CONFIG_PNP
static bool isapnp[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP;
#endif
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x220,0x240,0x260,0x280 */
#ifndef CONFIG_PNP
static long mpu_port[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = -1};
#else
static long mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;
#endif
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,10 */
static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3 */
static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3 */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for ES18xx soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for ES18xx soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable ES18xx soundcard.");
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "PnP detection for specified soundcard.");
#endif
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for ES18xx driver.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 port # for ES18xx driver.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port # for ES18xx driver.");
module_param_array(irq, int, NULL, 0444);
MODULE_PARM_DESC(irq, "IRQ # for ES18xx driver.");
module_param_array(dma1, int, NULL, 0444);
MODULE_PARM_DESC(dma1, "DMA 1 # for ES18xx driver.");
module_param_array(dma2, int, NULL, 0444);
MODULE_PARM_DESC(dma2, "DMA 2 # for ES18xx driver.");
#ifdef CONFIG_PNP
static int isa_registered;
static int pnp_registered;
static int pnpc_registered;
static struct pnp_device_id snd_audiodrive_pnpbiosids[] = {
{ .id = "ESS1869" },
{ .id = "ESS1879" },
{ .id = "" } /* end */
};
MODULE_DEVICE_TABLE(pnp, snd_audiodrive_pnpbiosids);
/* PnP main device initialization */
static int snd_audiodrive_pnp_init_main(int dev, struct pnp_dev *pdev)
{
if (pnp_activate_dev(pdev) < 0) {
snd_printk(KERN_ERR PFX "PnP configure failure (out of resources?)\n");
return -EBUSY;
}
/* ok. hack using Vendor-Defined Card-Level registers */
/* skip csn and logdev initialization - already done in isapnp_configure */
if (pnp_device_is_isapnp(pdev)) {
isapnp_cfg_begin(isapnp_card_number(pdev), isapnp_csn_number(pdev));
isapnp_write_byte(0x27, pnp_irq(pdev, 0)); /* Hardware Volume IRQ Number */
if (mpu_port[dev] != SNDRV_AUTO_PORT)
isapnp_write_byte(0x28, pnp_irq(pdev, 0)); /* MPU-401 IRQ Number */
isapnp_write_byte(0x72, pnp_irq(pdev, 0)); /* second IRQ */
isapnp_cfg_end();
}
port[dev] = pnp_port_start(pdev, 0);
fm_port[dev] = pnp_port_start(pdev, 1);
mpu_port[dev] = pnp_port_start(pdev, 2);
dma1[dev] = pnp_dma(pdev, 0);
dma2[dev] = pnp_dma(pdev, 1);
irq[dev] = pnp_irq(pdev, 0);
snd_printdd("PnP ES18xx: port=0x%lx, fm port=0x%lx, mpu port=0x%lx\n", port[dev], fm_port[dev], mpu_port[dev]);
snd_printdd("PnP ES18xx: dma1=%i, dma2=%i, irq=%i\n", dma1[dev], dma2[dev], irq[dev]);
return 0;
}
static int snd_audiodrive_pnp(int dev, struct snd_es18xx *chip,
struct pnp_dev *pdev)
{
chip->dev = pdev;
if (snd_audiodrive_pnp_init_main(dev, chip->dev) < 0)
return -EBUSY;
return 0;
}
static struct pnp_card_device_id snd_audiodrive_pnpids[] = {
/* ESS 1868 (integrated on Compaq dual P-Pro motherboard and Genius 18PnP 3D) */
{ .id = "ESS1868", .devs = { { "ESS1868" }, { "ESS0000" } } },
/* ESS 1868 (integrated on Maxisound Cards) */
{ .id = "ESS1868", .devs = { { "ESS8601" }, { "ESS8600" } } },
/* ESS 1868 (integrated on Maxisound Cards) */
{ .id = "ESS1868", .devs = { { "ESS8611" }, { "ESS8610" } } },
/* ESS ES1869 Plug and Play AudioDrive */
{ .id = "ESS0003", .devs = { { "ESS1869" }, { "ESS0006" } } },
/* ESS 1869 */
{ .id = "ESS1869", .devs = { { "ESS1869" }, { "ESS0006" } } },
/* ESS 1878 */
{ .id = "ESS1878", .devs = { { "ESS1878" }, { "ESS0004" } } },
/* ESS 1879 */
{ .id = "ESS1879", .devs = { { "ESS1879" }, { "ESS0009" } } },
/* --- */
{ .id = "" } /* end */
};
MODULE_DEVICE_TABLE(pnp_card, snd_audiodrive_pnpids);
static int snd_audiodrive_pnpc(int dev, struct snd_es18xx *chip,
struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
chip->dev = pnp_request_card_device(card, id->devs[0].id, NULL);
if (chip->dev == NULL)
return -EBUSY;
chip->devc = pnp_request_card_device(card, id->devs[1].id, NULL);
if (chip->devc == NULL)
return -EBUSY;
/* Control port initialization */
if (pnp_activate_dev(chip->devc) < 0) {
snd_printk(KERN_ERR PFX "PnP control configure failure (out of resources?)\n");
return -EAGAIN;
}
snd_printdd("pnp: port=0x%llx\n",
(unsigned long long)pnp_port_start(chip->devc, 0));
if (snd_audiodrive_pnp_init_main(dev, chip->dev) < 0)
return -EBUSY;
return 0;
}
#endif /* CONFIG_PNP */
#ifdef CONFIG_PNP
#define is_isapnp_selected(dev) isapnp[dev]
#else
#define is_isapnp_selected(dev) 0
#endif
static int snd_es18xx_card_new(struct device *pdev, int dev,
struct snd_card **cardp)
{
return snd_card_new(pdev, index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_es18xx), cardp);
}
static int snd_audiodrive_probe(struct snd_card *card, int dev)
{
struct snd_es18xx *chip = card->private_data;
struct snd_opl3 *opl3;
int err;
err = snd_es18xx_new_device(card,
port[dev], mpu_port[dev], fm_port[dev],
irq[dev], dma1[dev], dma2[dev]);
if (err < 0)
return err;
sprintf(card->driver, "ES%x", chip->version);
sprintf(card->shortname, "ESS AudioDrive ES%x", chip->version);
if (dma1[dev] != dma2[dev])
sprintf(card->longname, "%s at 0x%lx, irq %d, dma1 %d, dma2 %d",
card->shortname,
chip->port,
irq[dev], dma1[dev], dma2[dev]);
else
sprintf(card->longname, "%s at 0x%lx, irq %d, dma %d",
card->shortname,
chip->port,
irq[dev], dma1[dev]);
err = snd_es18xx_pcm(card, 0, NULL);
if (err < 0)
return err;
err = snd_es18xx_mixer(card);
if (err < 0)
return err;
if (fm_port[dev] > 0 && fm_port[dev] != SNDRV_AUTO_PORT) {
if (snd_opl3_create(card, fm_port[dev], fm_port[dev] + 2,
OPL3_HW_OPL3, 0, &opl3) < 0) {
snd_printk(KERN_WARNING PFX
"opl3 not detected at 0x%lx\n",
fm_port[dev]);
} else {
err = snd_opl3_hwdep_new(opl3, 0, 1, NULL);
if (err < 0)
return err;
}
}
if (mpu_port[dev] > 0 && mpu_port[dev] != SNDRV_AUTO_PORT) {
err = snd_mpu401_uart_new(card, 0, MPU401_HW_ES18XX,
mpu_port[dev], MPU401_INFO_IRQ_HOOK,
-1, &chip->rmidi);
if (err < 0)
return err;
}
return snd_card_register(card);
}
static int snd_es18xx_isa_match(struct device *pdev, unsigned int dev)
{
return enable[dev] && !is_isapnp_selected(dev);
}
static int snd_es18xx_isa_probe1(int dev, struct device *devptr)
{
struct snd_card *card;
int err;
err = snd_es18xx_card_new(devptr, dev, &card);
if (err < 0)
return err;
if ((err = snd_audiodrive_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
dev_set_drvdata(devptr, card);
return 0;
}
static int snd_es18xx_isa_probe(struct device *pdev, unsigned int dev)
{
int err;
static int possible_irqs[] = {5, 9, 10, 7, 11, 12, -1};
static int possible_dmas[] = {1, 0, 3, 5, -1};
if (irq[dev] == SNDRV_AUTO_IRQ) {
if ((irq[dev] = snd_legacy_find_free_irq(possible_irqs)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free IRQ\n");
return -EBUSY;
}
}
if (dma1[dev] == SNDRV_AUTO_DMA) {
if ((dma1[dev] = snd_legacy_find_free_dma(possible_dmas)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free DMA1\n");
return -EBUSY;
}
}
if (dma2[dev] == SNDRV_AUTO_DMA) {
if ((dma2[dev] = snd_legacy_find_free_dma(possible_dmas)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free DMA2\n");
return -EBUSY;
}
}
if (port[dev] != SNDRV_AUTO_PORT) {
return snd_es18xx_isa_probe1(dev, pdev);
} else {
static unsigned long possible_ports[] = {0x220, 0x240, 0x260, 0x280};
int i;
for (i = 0; i < ARRAY_SIZE(possible_ports); i++) {
port[dev] = possible_ports[i];
err = snd_es18xx_isa_probe1(dev, pdev);
if (! err)
return 0;
}
return err;
}
}
static int snd_es18xx_isa_remove(struct device *devptr,
unsigned int dev)
{
snd_card_free(dev_get_drvdata(devptr));
return 0;
}
#ifdef CONFIG_PM
static int snd_es18xx_isa_suspend(struct device *dev, unsigned int n,
pm_message_t state)
{
return snd_es18xx_suspend(dev_get_drvdata(dev), state);
}
static int snd_es18xx_isa_resume(struct device *dev, unsigned int n)
{
return snd_es18xx_resume(dev_get_drvdata(dev));
}
#endif
#define DEV_NAME "es18xx"
static struct isa_driver snd_es18xx_isa_driver = {
.match = snd_es18xx_isa_match,
.probe = snd_es18xx_isa_probe,
.remove = snd_es18xx_isa_remove,
#ifdef CONFIG_PM
.suspend = snd_es18xx_isa_suspend,
.resume = snd_es18xx_isa_resume,
#endif
.driver = {
.name = DEV_NAME
},
};
#ifdef CONFIG_PNP
static int snd_audiodrive_pnp_detect(struct pnp_dev *pdev,
const struct pnp_device_id *id)
{
static int dev;
int err;
struct snd_card *card;
if (pnp_device_is_isapnp(pdev))
return -ENOENT; /* we have another procedure - card */
for (; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev >= SNDRV_CARDS)
return -ENODEV;
err = snd_es18xx_card_new(&pdev->dev, dev, &card);
if (err < 0)
return err;
if ((err = snd_audiodrive_pnp(dev, card->private_data, pdev)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_audiodrive_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
pnp_set_drvdata(pdev, card);
dev++;
return 0;
}
static void snd_audiodrive_pnp_remove(struct pnp_dev *pdev)
{
snd_card_free(pnp_get_drvdata(pdev));
}
#ifdef CONFIG_PM
static int snd_audiodrive_pnp_suspend(struct pnp_dev *pdev, pm_message_t state)
{
return snd_es18xx_suspend(pnp_get_drvdata(pdev), state);
}
static int snd_audiodrive_pnp_resume(struct pnp_dev *pdev)
{
return snd_es18xx_resume(pnp_get_drvdata(pdev));
}
#endif
static struct pnp_driver es18xx_pnp_driver = {
.name = "es18xx-pnpbios",
.id_table = snd_audiodrive_pnpbiosids,
.probe = snd_audiodrive_pnp_detect,
.remove = snd_audiodrive_pnp_remove,
#ifdef CONFIG_PM
.suspend = snd_audiodrive_pnp_suspend,
.resume = snd_audiodrive_pnp_resume,
#endif
};
static int snd_audiodrive_pnpc_detect(struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
static int dev;
struct snd_card *card;
int res;
for ( ; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev >= SNDRV_CARDS)
return -ENODEV;
res = snd_es18xx_card_new(&pcard->card->dev, dev, &card);
if (res < 0)
return res;
if ((res = snd_audiodrive_pnpc(dev, card->private_data, pcard, pid)) < 0) {
snd_card_free(card);
return res;
}
if ((res = snd_audiodrive_probe(card, dev)) < 0) {
snd_card_free(card);
return res;
}
pnp_set_card_drvdata(pcard, card);
dev++;
return 0;
}
static void snd_audiodrive_pnpc_remove(struct pnp_card_link *pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
#ifdef CONFIG_PM
static int snd_audiodrive_pnpc_suspend(struct pnp_card_link *pcard, pm_message_t state)
{
return snd_es18xx_suspend(pnp_get_card_drvdata(pcard), state);
}
static int snd_audiodrive_pnpc_resume(struct pnp_card_link *pcard)
{
return snd_es18xx_resume(pnp_get_card_drvdata(pcard));
}
#endif
static struct pnp_card_driver es18xx_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = "es18xx",
.id_table = snd_audiodrive_pnpids,
.probe = snd_audiodrive_pnpc_detect,
.remove = snd_audiodrive_pnpc_remove,
#ifdef CONFIG_PM
.suspend = snd_audiodrive_pnpc_suspend,
.resume = snd_audiodrive_pnpc_resume,
#endif
};
#endif /* CONFIG_PNP */
static int __init alsa_card_es18xx_init(void)
{
int err;
err = isa_register_driver(&snd_es18xx_isa_driver, SNDRV_CARDS);
#ifdef CONFIG_PNP
if (!err)
isa_registered = 1;
err = pnp_register_driver(&es18xx_pnp_driver);
if (!err)
pnp_registered = 1;
err = pnp_register_card_driver(&es18xx_pnpc_driver);
if (!err)
pnpc_registered = 1;
if (isa_registered || pnp_registered)
err = 0;
#endif
return err;
}
static void __exit alsa_card_es18xx_exit(void)
{
#ifdef CONFIG_PNP
if (pnpc_registered)
pnp_unregister_card_driver(&es18xx_pnpc_driver);
if (pnp_registered)
pnp_unregister_driver(&es18xx_pnp_driver);
if (isa_registered)
#endif
isa_unregister_driver(&snd_es18xx_isa_driver);
}
module_init(alsa_card_es18xx_init)
module_exit(alsa_card_es18xx_exit)
| gpl-2.0 |
zhjwpku/gsoc | crypto/asymmetric_keys/verify_pefile.c | 1029 | 12141 | /* Parse a signed PE binary
*
* Copyright (C) 2014 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#define pr_fmt(fmt) "PEFILE: "fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/pe.h>
#include <linux/asn1.h>
#include <crypto/pkcs7.h>
#include <crypto/hash.h>
#include "verify_pefile.h"
/*
* Parse a PE binary.
*/
static int pefile_parse_binary(const void *pebuf, unsigned int pelen,
struct pefile_context *ctx)
{
const struct mz_hdr *mz = pebuf;
const struct pe_hdr *pe;
const struct pe32_opt_hdr *pe32;
const struct pe32plus_opt_hdr *pe64;
const struct data_directory *ddir;
const struct data_dirent *dde;
const struct section_header *secs, *sec;
size_t cursor, datalen = pelen;
kenter("");
#define chkaddr(base, x, s) \
do { \
if ((x) < base || (s) >= datalen || (x) > datalen - (s)) \
return -ELIBBAD; \
} while (0)
chkaddr(0, 0, sizeof(*mz));
if (mz->magic != MZ_MAGIC)
return -ELIBBAD;
cursor = sizeof(*mz);
chkaddr(cursor, mz->peaddr, sizeof(*pe));
pe = pebuf + mz->peaddr;
if (pe->magic != PE_MAGIC)
return -ELIBBAD;
cursor = mz->peaddr + sizeof(*pe);
chkaddr(0, cursor, sizeof(pe32->magic));
pe32 = pebuf + cursor;
pe64 = pebuf + cursor;
switch (pe32->magic) {
case PE_OPT_MAGIC_PE32:
chkaddr(0, cursor, sizeof(*pe32));
ctx->image_checksum_offset =
(unsigned long)&pe32->csum - (unsigned long)pebuf;
ctx->header_size = pe32->header_size;
cursor += sizeof(*pe32);
ctx->n_data_dirents = pe32->data_dirs;
break;
case PE_OPT_MAGIC_PE32PLUS:
chkaddr(0, cursor, sizeof(*pe64));
ctx->image_checksum_offset =
(unsigned long)&pe64->csum - (unsigned long)pebuf;
ctx->header_size = pe64->header_size;
cursor += sizeof(*pe64);
ctx->n_data_dirents = pe64->data_dirs;
break;
default:
pr_debug("Unknown PEOPT magic = %04hx\n", pe32->magic);
return -ELIBBAD;
}
pr_debug("checksum @ %x\n", ctx->image_checksum_offset);
pr_debug("header size = %x\n", ctx->header_size);
if (cursor >= ctx->header_size || ctx->header_size >= datalen)
return -ELIBBAD;
if (ctx->n_data_dirents > (ctx->header_size - cursor) / sizeof(*dde))
return -ELIBBAD;
ddir = pebuf + cursor;
cursor += sizeof(*dde) * ctx->n_data_dirents;
ctx->cert_dirent_offset =
(unsigned long)&ddir->certs - (unsigned long)pebuf;
ctx->certs_size = ddir->certs.size;
if (!ddir->certs.virtual_address || !ddir->certs.size) {
pr_debug("Unsigned PE binary\n");
return -EKEYREJECTED;
}
chkaddr(ctx->header_size, ddir->certs.virtual_address,
ddir->certs.size);
ctx->sig_offset = ddir->certs.virtual_address;
ctx->sig_len = ddir->certs.size;
pr_debug("cert = %x @%x [%*ph]\n",
ctx->sig_len, ctx->sig_offset,
ctx->sig_len, pebuf + ctx->sig_offset);
ctx->n_sections = pe->sections;
if (ctx->n_sections > (ctx->header_size - cursor) / sizeof(*sec))
return -ELIBBAD;
ctx->secs = secs = pebuf + cursor;
return 0;
}
/*
* Check and strip the PE wrapper from around the signature and check that the
* remnant looks something like PKCS#7.
*/
static int pefile_strip_sig_wrapper(const void *pebuf,
struct pefile_context *ctx)
{
struct win_certificate wrapper;
const u8 *pkcs7;
unsigned len;
if (ctx->sig_len < sizeof(wrapper)) {
pr_debug("Signature wrapper too short\n");
return -ELIBBAD;
}
memcpy(&wrapper, pebuf + ctx->sig_offset, sizeof(wrapper));
pr_debug("sig wrapper = { %x, %x, %x }\n",
wrapper.length, wrapper.revision, wrapper.cert_type);
/* Both pesign and sbsign round up the length of certificate table
* (in optional header data directories) to 8 byte alignment.
*/
if (round_up(wrapper.length, 8) != ctx->sig_len) {
pr_debug("Signature wrapper len wrong\n");
return -ELIBBAD;
}
if (wrapper.revision != WIN_CERT_REVISION_2_0) {
pr_debug("Signature is not revision 2.0\n");
return -ENOTSUPP;
}
if (wrapper.cert_type != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
pr_debug("Signature certificate type is not PKCS\n");
return -ENOTSUPP;
}
/* It looks like the pkcs signature length in wrapper->length and the
* size obtained from the data dir entries, which lists the total size
* of certificate table, are both aligned to an octaword boundary, so
* we may have to deal with some padding.
*/
ctx->sig_len = wrapper.length;
ctx->sig_offset += sizeof(wrapper);
ctx->sig_len -= sizeof(wrapper);
if (ctx->sig_len < 4) {
pr_debug("Signature data missing\n");
return -EKEYREJECTED;
}
/* What's left should be a PKCS#7 cert */
pkcs7 = pebuf + ctx->sig_offset;
if (pkcs7[0] != (ASN1_CONS_BIT | ASN1_SEQ))
goto not_pkcs7;
switch (pkcs7[1]) {
case 0 ... 0x7f:
len = pkcs7[1] + 2;
goto check_len;
case ASN1_INDEFINITE_LENGTH:
return 0;
case 0x81:
len = pkcs7[2] + 3;
goto check_len;
case 0x82:
len = ((pkcs7[2] << 8) | pkcs7[3]) + 4;
goto check_len;
case 0x83 ... 0xff:
return -EMSGSIZE;
default:
goto not_pkcs7;
}
check_len:
if (len <= ctx->sig_len) {
/* There may be padding */
ctx->sig_len = len;
return 0;
}
not_pkcs7:
pr_debug("Signature data not PKCS#7\n");
return -ELIBBAD;
}
/*
* Compare two sections for canonicalisation.
*/
static int pefile_compare_shdrs(const void *a, const void *b)
{
const struct section_header *shdra = a;
const struct section_header *shdrb = b;
int rc;
if (shdra->data_addr > shdrb->data_addr)
return 1;
if (shdrb->data_addr > shdra->data_addr)
return -1;
if (shdra->virtual_address > shdrb->virtual_address)
return 1;
if (shdrb->virtual_address > shdra->virtual_address)
return -1;
rc = strcmp(shdra->name, shdrb->name);
if (rc != 0)
return rc;
if (shdra->virtual_size > shdrb->virtual_size)
return 1;
if (shdrb->virtual_size > shdra->virtual_size)
return -1;
if (shdra->raw_data_size > shdrb->raw_data_size)
return 1;
if (shdrb->raw_data_size > shdra->raw_data_size)
return -1;
return 0;
}
/*
* Load the contents of the PE binary into the digest, leaving out the image
* checksum and the certificate data block.
*/
static int pefile_digest_pe_contents(const void *pebuf, unsigned int pelen,
struct pefile_context *ctx,
struct shash_desc *desc)
{
unsigned *canon, tmp, loop, i, hashed_bytes;
int ret;
/* Digest the header and data directory, but leave out the image
* checksum and the data dirent for the signature.
*/
ret = crypto_shash_update(desc, pebuf, ctx->image_checksum_offset);
if (ret < 0)
return ret;
tmp = ctx->image_checksum_offset + sizeof(uint32_t);
ret = crypto_shash_update(desc, pebuf + tmp,
ctx->cert_dirent_offset - tmp);
if (ret < 0)
return ret;
tmp = ctx->cert_dirent_offset + sizeof(struct data_dirent);
ret = crypto_shash_update(desc, pebuf + tmp, ctx->header_size - tmp);
if (ret < 0)
return ret;
canon = kcalloc(ctx->n_sections, sizeof(unsigned), GFP_KERNEL);
if (!canon)
return -ENOMEM;
/* We have to canonicalise the section table, so we perform an
* insertion sort.
*/
canon[0] = 0;
for (loop = 1; loop < ctx->n_sections; loop++) {
for (i = 0; i < loop; i++) {
if (pefile_compare_shdrs(&ctx->secs[canon[i]],
&ctx->secs[loop]) > 0) {
memmove(&canon[i + 1], &canon[i],
(loop - i) * sizeof(canon[0]));
break;
}
}
canon[i] = loop;
}
hashed_bytes = ctx->header_size;
for (loop = 0; loop < ctx->n_sections; loop++) {
i = canon[loop];
if (ctx->secs[i].raw_data_size == 0)
continue;
ret = crypto_shash_update(desc,
pebuf + ctx->secs[i].data_addr,
ctx->secs[i].raw_data_size);
if (ret < 0) {
kfree(canon);
return ret;
}
hashed_bytes += ctx->secs[i].raw_data_size;
}
kfree(canon);
if (pelen > hashed_bytes) {
tmp = hashed_bytes + ctx->certs_size;
ret = crypto_shash_update(desc,
pebuf + hashed_bytes,
pelen - tmp);
if (ret < 0)
return ret;
}
return 0;
}
/*
* Digest the contents of the PE binary, leaving out the image checksum and the
* certificate data block.
*/
static int pefile_digest_pe(const void *pebuf, unsigned int pelen,
struct pefile_context *ctx)
{
struct crypto_shash *tfm;
struct shash_desc *desc;
size_t digest_size, desc_size;
void *digest;
int ret;
kenter(",%u", ctx->digest_algo);
/* Allocate the hashing algorithm we're going to need and find out how
* big the hash operational data will be.
*/
tfm = crypto_alloc_shash(hash_algo_name[ctx->digest_algo], 0, 0);
if (IS_ERR(tfm))
return (PTR_ERR(tfm) == -ENOENT) ? -ENOPKG : PTR_ERR(tfm);
desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
digest_size = crypto_shash_digestsize(tfm);
if (digest_size != ctx->digest_len) {
pr_debug("Digest size mismatch (%zx != %x)\n",
digest_size, ctx->digest_len);
ret = -EBADMSG;
goto error_no_desc;
}
pr_debug("Digest: desc=%zu size=%zu\n", desc_size, digest_size);
ret = -ENOMEM;
desc = kzalloc(desc_size + digest_size, GFP_KERNEL);
if (!desc)
goto error_no_desc;
desc->tfm = tfm;
desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
ret = crypto_shash_init(desc);
if (ret < 0)
goto error;
ret = pefile_digest_pe_contents(pebuf, pelen, ctx, desc);
if (ret < 0)
goto error;
digest = (void *)desc + desc_size;
ret = crypto_shash_final(desc, digest);
if (ret < 0)
goto error;
pr_debug("Digest calc = [%*ph]\n", ctx->digest_len, digest);
/* Check that the PE file digest matches that in the MSCODE part of the
* PKCS#7 certificate.
*/
if (memcmp(digest, ctx->digest, ctx->digest_len) != 0) {
pr_debug("Digest mismatch\n");
ret = -EKEYREJECTED;
} else {
pr_debug("The digests match!\n");
}
error:
kfree(desc);
error_no_desc:
crypto_free_shash(tfm);
kleave(" = %d", ret);
return ret;
}
/**
* verify_pefile_signature - Verify the signature on a PE binary image
* @pebuf: Buffer containing the PE binary image
* @pelen: Length of the binary image
* @trust_keyring: Signing certificates to use as starting points
* @_trusted: Set to true if trustworth, false otherwise
*
* Validate that the certificate chain inside the PKCS#7 message inside the PE
* binary image intersects keys we already know and trust.
*
* Returns, in order of descending priority:
*
* (*) -ELIBBAD if the image cannot be parsed, or:
*
* (*) -EKEYREJECTED if a signature failed to match for which we have a valid
* key, or:
*
* (*) 0 if at least one signature chain intersects with the keys in the trust
* keyring, or:
*
* (*) -ENOPKG if a suitable crypto module couldn't be found for a check on a
* chain.
*
* (*) -ENOKEY if we couldn't find a match for any of the signature chains in
* the message.
*
* May also return -ENOMEM.
*/
int verify_pefile_signature(const void *pebuf, unsigned pelen,
struct key *trusted_keyring, bool *_trusted)
{
struct pkcs7_message *pkcs7;
struct pefile_context ctx;
const void *data;
size_t datalen;
int ret;
kenter("");
memset(&ctx, 0, sizeof(ctx));
ret = pefile_parse_binary(pebuf, pelen, &ctx);
if (ret < 0)
return ret;
ret = pefile_strip_sig_wrapper(pebuf, &ctx);
if (ret < 0)
return ret;
pkcs7 = pkcs7_parse_message(pebuf + ctx.sig_offset, ctx.sig_len);
if (IS_ERR(pkcs7))
return PTR_ERR(pkcs7);
ctx.pkcs7 = pkcs7;
ret = pkcs7_get_content_data(ctx.pkcs7, &data, &datalen, false);
if (ret < 0 || datalen == 0) {
pr_devel("PKCS#7 message does not contain data\n");
ret = -EBADMSG;
goto error;
}
ret = mscode_parse(&ctx);
if (ret < 0)
goto error;
pr_debug("Digest: %u [%*ph]\n",
ctx.digest_len, ctx.digest_len, ctx.digest);
/* Generate the digest and check against the PKCS7 certificate
* contents.
*/
ret = pefile_digest_pe(pebuf, pelen, &ctx);
if (ret < 0)
goto error;
ret = pkcs7_verify(pkcs7);
if (ret < 0)
goto error;
ret = pkcs7_validate_trust(pkcs7, trusted_keyring, _trusted);
error:
pkcs7_free_message(ctx.pkcs7);
return ret;
}
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZE550ML_ZE551ML | linux/kernel/crypto/algif_skcipher.c | 1541 | 13547 | /*
* algif_skcipher: User-space interface for skcipher algorithms
*
* This file provides the user-space API for symmetric key ciphers.
*
* Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
*
* 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; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <crypto/scatterwalk.h>
#include <crypto/skcipher.h>
#include <crypto/if_alg.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/net.h>
#include <net/sock.h>
struct skcipher_sg_list {
struct list_head list;
int cur;
struct scatterlist sg[0];
};
struct skcipher_ctx {
struct list_head tsgl;
struct af_alg_sgl rsgl;
void *iv;
struct af_alg_completion completion;
unsigned used;
unsigned int len;
bool more;
bool merge;
bool enc;
struct ablkcipher_request req;
};
#define MAX_SGL_ENTS ((PAGE_SIZE - sizeof(struct skcipher_sg_list)) / \
sizeof(struct scatterlist) - 1)
static inline int skcipher_sndbuf(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
return max_t(int, max_t(int, sk->sk_sndbuf & PAGE_MASK, PAGE_SIZE) -
ctx->used, 0);
}
static inline bool skcipher_writable(struct sock *sk)
{
return PAGE_SIZE <= skcipher_sndbuf(sk);
}
static int skcipher_alloc_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg = NULL;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
if (!list_empty(&ctx->tsgl))
sg = sgl->sg;
if (!sg || sgl->cur >= MAX_SGL_ENTS) {
sgl = sock_kmalloc(sk, sizeof(*sgl) +
sizeof(sgl->sg[0]) * (MAX_SGL_ENTS + 1),
GFP_KERNEL);
if (!sgl)
return -ENOMEM;
sg_init_table(sgl->sg, MAX_SGL_ENTS + 1);
sgl->cur = 0;
if (sg)
scatterwalk_sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg);
list_add_tail(&sgl->list, &ctx->tsgl);
}
return 0;
}
static void skcipher_pull_sgl(struct sock *sk, int used)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
int i;
while (!list_empty(&ctx->tsgl)) {
sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list,
list);
sg = sgl->sg;
for (i = 0; i < sgl->cur; i++) {
int plen = min_t(int, used, sg[i].length);
if (!sg_page(sg + i))
continue;
sg[i].length -= plen;
sg[i].offset += plen;
used -= plen;
ctx->used -= plen;
if (sg[i].length)
return;
put_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
}
list_del(&sgl->list);
sock_kfree_s(sk, sgl,
sizeof(*sgl) + sizeof(sgl->sg[0]) *
(MAX_SGL_ENTS + 1));
}
if (!ctx->used)
ctx->merge = 0;
}
static void skcipher_free_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
skcipher_pull_sgl(sk, ctx->used);
}
static int skcipher_wait_for_wmem(struct sock *sk, unsigned flags)
{
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT)
return -EAGAIN;
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, skcipher_writable(sk))) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
static void skcipher_wmem_wakeup(struct sock *sk)
{
struct socket_wq *wq;
if (!skcipher_writable(sk))
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
static int skcipher_wait_for_data(struct sock *sk, unsigned flags)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT) {
return -EAGAIN;
}
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, ctx->used)) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
return err;
}
static void skcipher_data_wakeup(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct socket_wq *wq;
if (!ctx->used)
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
rcu_read_unlock();
}
static int skcipher_sendmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t size)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
unsigned ivsize = crypto_ablkcipher_ivsize(tfm);
struct skcipher_sg_list *sgl;
struct af_alg_control con = {};
long copied = 0;
bool enc = 0;
int err;
int i;
if (msg->msg_controllen) {
err = af_alg_cmsg_send(msg, &con);
if (err)
return err;
switch (con.op) {
case ALG_OP_ENCRYPT:
enc = 1;
break;
case ALG_OP_DECRYPT:
enc = 0;
break;
default:
return -EINVAL;
}
if (con.iv && con.iv->ivlen != ivsize)
return -EINVAL;
}
err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!ctx->used) {
ctx->enc = enc;
if (con.iv)
memcpy(ctx->iv, con.iv->iv, ivsize);
}
while (size) {
struct scatterlist *sg;
unsigned long len = size;
int plen;
if (ctx->merge) {
sgl = list_entry(ctx->tsgl.prev,
struct skcipher_sg_list, list);
sg = sgl->sg + sgl->cur - 1;
len = min_t(unsigned long, len,
PAGE_SIZE - sg->offset - sg->length);
err = memcpy_fromiovec(page_address(sg_page(sg)) +
sg->offset + sg->length,
msg->msg_iov, len);
if (err)
goto unlock;
sg->length += len;
ctx->merge = (sg->offset + sg->length) &
(PAGE_SIZE - 1);
ctx->used += len;
copied += len;
size -= len;
continue;
}
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, msg->msg_flags);
if (err)
goto unlock;
}
len = min_t(unsigned long, len, skcipher_sndbuf(sk));
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
sg = sgl->sg;
do {
i = sgl->cur;
plen = min_t(int, len, PAGE_SIZE);
sg_assign_page(sg + i, alloc_page(GFP_KERNEL));
err = -ENOMEM;
if (!sg_page(sg + i))
goto unlock;
err = memcpy_fromiovec(page_address(sg_page(sg + i)),
msg->msg_iov, plen);
if (err) {
__free_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
goto unlock;
}
sg[i].length = plen;
len -= plen;
ctx->used += plen;
copied += plen;
size -= plen;
sgl->cur++;
} while (len && sgl->cur < MAX_SGL_ENTS);
ctx->merge = plen & (PAGE_SIZE - 1);
}
err = 0;
ctx->more = msg->msg_flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static ssize_t skcipher_sendpage(struct socket *sock, struct page *page,
int offset, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
int err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!size)
goto done;
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, flags);
if (err)
goto unlock;
}
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
ctx->merge = 0;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
get_page(page);
sg_set_page(sgl->sg + sgl->cur, page, size, offset);
sgl->cur++;
ctx->used += size;
done:
ctx->more = flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return err ?: size;
}
static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
msg->msg_namelen = 0;
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static unsigned int skcipher_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
if (ctx->used)
mask |= POLLIN | POLLRDNORM;
if (skcipher_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static struct proto_ops algif_skcipher_ops = {
.family = PF_ALG,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.getname = sock_no_getname,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.getsockopt = sock_no_getsockopt,
.mmap = sock_no_mmap,
.bind = sock_no_bind,
.accept = sock_no_accept,
.setsockopt = sock_no_setsockopt,
.release = af_alg_release,
.sendmsg = skcipher_sendmsg,
.sendpage = skcipher_sendpage,
.recvmsg = skcipher_recvmsg,
.poll = skcipher_poll,
};
static void *skcipher_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_ablkcipher(name, type, mask);
}
static void skcipher_release(void *private)
{
crypto_free_ablkcipher(private);
}
static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_ablkcipher_setkey(private, key, keylen);
}
static void skcipher_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
skcipher_free_sgl(sk);
sock_kfree_s(sk, ctx->iv, crypto_ablkcipher_ivsize(tfm));
sock_kfree_s(sk, ctx, ctx->len);
af_alg_release_parent(sk);
}
static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_ablkcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_ablkcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_ablkcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
ablkcipher_request_set_tfm(&ctx->req, private);
ablkcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
static const struct af_alg_type algif_type_skcipher = {
.bind = skcipher_bind,
.release = skcipher_release,
.setkey = skcipher_setkey,
.accept = skcipher_accept_parent,
.ops = &algif_skcipher_ops,
.name = "skcipher",
.owner = THIS_MODULE
};
static int __init algif_skcipher_init(void)
{
return af_alg_register_type(&algif_type_skcipher);
}
static void __exit algif_skcipher_exit(void)
{
int err = af_alg_unregister_type(&algif_type_skcipher);
BUG_ON(err);
}
module_init(algif_skcipher_init);
module_exit(algif_skcipher_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
RenderBroken/dory_render_kernel | kernel/mutex.c | 1541 | 17177 | /*
* kernel/mutex.c
*
* Mutexes: blocking mutual exclusion locks
*
* Started by Ingo Molnar:
*
* Copyright (C) 2004, 2005, 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
*
* Many thanks to Arjan van de Ven, Thomas Gleixner, Steven Rostedt and
* David Howells for suggestions and improvements.
*
* - Adaptive spinning for mutexes by Peter Zijlstra. (Ported to mainline
* from the -rt tree, where it was originally implemented for rtmutexes
* by Steven Rostedt, based on work by Gregory Haskins, Peter Morreale
* and Sven Dietrich.
*
* Also see Documentation/mutex-design.txt.
*/
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/sched/rt.h>
#include <linux/export.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/debug_locks.h>
/*
* In the DEBUG case we are using the "NULL fastpath" for mutexes,
* which forces all calls into the slowpath:
*/
#ifdef CONFIG_DEBUG_MUTEXES
# include "mutex-debug.h"
# include <asm-generic/mutex-null.h>
#else
# include "mutex.h"
# include <asm/mutex.h>
#endif
/*
* A negative mutex count indicates that waiters are sleeping waiting for the
* mutex.
*/
#define MUTEX_SHOW_NO_WAITER(mutex) (atomic_read(&(mutex)->count) >= 0)
void
__mutex_init(struct mutex *lock, const char *name, struct lock_class_key *key)
{
atomic_set(&lock->count, 1);
spin_lock_init(&lock->wait_lock);
INIT_LIST_HEAD(&lock->wait_list);
mutex_clear_owner(lock);
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
lock->spin_mlock = NULL;
#endif
debug_mutex_init(lock, name, key);
}
EXPORT_SYMBOL(__mutex_init);
#ifndef CONFIG_DEBUG_LOCK_ALLOC
/*
* We split the mutex lock/unlock logic into separate fastpath and
* slowpath functions, to reduce the register pressure on the fastpath.
* We also put the fastpath first in the kernel image, to make sure the
* branch is predicted by the CPU as default-untaken.
*/
static __used noinline void __sched
__mutex_lock_slowpath(atomic_t *lock_count);
/**
* mutex_lock - acquire the mutex
* @lock: the mutex to be acquired
*
* Lock the mutex exclusively for this task. If the mutex is not
* available right now, it will sleep until it can get it.
*
* The mutex must later on be released by the same task that
* acquired it. Recursive locking is not allowed. The task
* may not exit without first unlocking the mutex. Also, kernel
* memory where the mutex resides mutex must not be freed with
* the mutex still locked. The mutex must first be initialized
* (or statically defined) before it can be locked. memset()-ing
* the mutex to 0 is not allowed.
*
* ( The CONFIG_DEBUG_MUTEXES .config option turns on debugging
* checks that will enforce the restrictions and will also do
* deadlock debugging. )
*
* This function is similar to (but not equivalent to) down().
*/
void __sched mutex_lock(struct mutex *lock)
{
might_sleep();
/*
* The locking fastpath is the 1->0 transition from
* 'unlocked' into 'locked' state.
*/
__mutex_fastpath_lock(&lock->count, __mutex_lock_slowpath);
mutex_set_owner(lock);
}
EXPORT_SYMBOL(mutex_lock);
#endif
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
/*
* In order to avoid a stampede of mutex spinners from acquiring the mutex
* more or less simultaneously, the spinners need to acquire a MCS lock
* first before spinning on the owner field.
*
* We don't inline mspin_lock() so that perf can correctly account for the
* time spent in this lock function.
*/
struct mspin_node {
struct mspin_node *next ;
int locked; /* 1 if lock acquired */
};
#define MLOCK(mutex) ((struct mspin_node **)&((mutex)->spin_mlock))
static noinline
void mspin_lock(struct mspin_node **lock, struct mspin_node *node)
{
struct mspin_node *prev;
/* Init node */
node->locked = 0;
node->next = NULL;
prev = xchg(lock, node);
if (likely(prev == NULL)) {
/* Lock acquired */
node->locked = 1;
return;
}
ACCESS_ONCE(prev->next) = node;
smp_wmb();
/* Wait until the lock holder passes the lock down */
while (!ACCESS_ONCE(node->locked))
arch_mutex_cpu_relax();
}
static void mspin_unlock(struct mspin_node **lock, struct mspin_node *node)
{
struct mspin_node *next = ACCESS_ONCE(node->next);
if (likely(!next)) {
/*
* Release the lock by setting it to NULL
*/
if (cmpxchg(lock, node, NULL) == node)
return;
/* Wait until the next pointer is set */
while (!(next = ACCESS_ONCE(node->next)))
arch_mutex_cpu_relax();
}
ACCESS_ONCE(next->locked) = 1;
smp_wmb();
}
/*
* Mutex spinning code migrated from kernel/sched/core.c
*/
static inline bool owner_running(struct mutex *lock, struct task_struct *owner)
{
if (lock->owner != owner)
return false;
/*
* Ensure we emit the owner->on_cpu, dereference _after_ checking
* lock->owner still matches owner, if that fails, owner might
* point to free()d memory, if it still matches, the rcu_read_lock()
* ensures the memory stays valid.
*/
barrier();
return owner->on_cpu;
}
/*
* Look out! "owner" is an entirely speculative pointer
* access and not reliable.
*/
static noinline
int mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner)
{
rcu_read_lock();
while (owner_running(lock, owner)) {
if (need_resched())
break;
arch_mutex_cpu_relax();
}
rcu_read_unlock();
/*
* We break out the loop above on need_resched() and when the
* owner changed, which is a sign for heavy contention. Return
* success only when lock->owner is NULL.
*/
return lock->owner == NULL;
}
/*
* Initial check for entering the mutex spinning loop
*/
static inline int mutex_can_spin_on_owner(struct mutex *lock)
{
int retval = 1;
rcu_read_lock();
if (lock->owner)
retval = lock->owner->on_cpu;
rcu_read_unlock();
/*
* if lock->owner is not set, the mutex owner may have just acquired
* it and not set the owner yet or the mutex has been released.
*/
return retval;
}
#endif
static __used noinline void __sched __mutex_unlock_slowpath(atomic_t *lock_count);
/**
* mutex_unlock - release the mutex
* @lock: the mutex to be released
*
* Unlock a mutex that has been locked by this task previously.
*
* This function must not be used in interrupt context. Unlocking
* of a not locked mutex is not allowed.
*
* This function is similar to (but not equivalent to) up().
*/
void __sched mutex_unlock(struct mutex *lock)
{
/*
* The unlocking fastpath is the 0->1 transition from 'locked'
* into 'unlocked' state:
*/
#ifndef CONFIG_DEBUG_MUTEXES
/*
* When debugging is enabled we must not clear the owner before time,
* the slow path will always be taken, and that clears the owner field
* after verifying that it was indeed current.
*/
mutex_clear_owner(lock);
#endif
__mutex_fastpath_unlock(&lock->count, __mutex_unlock_slowpath);
}
EXPORT_SYMBOL(mutex_unlock);
/*
* Lock a mutex (possibly interruptible), slowpath:
*/
static inline int __sched
__mutex_lock_common(struct mutex *lock, long state, unsigned int subclass,
struct lockdep_map *nest_lock, unsigned long ip)
{
struct task_struct *task = current;
struct mutex_waiter waiter;
unsigned long flags;
preempt_disable();
mutex_acquire_nest(&lock->dep_map, subclass, 0, nest_lock, ip);
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
/*
* Optimistic spinning.
*
* We try to spin for acquisition when we find that there are no
* pending waiters and the lock owner is currently running on a
* (different) CPU.
*
* The rationale is that if the lock owner is running, it is likely to
* release the lock soon.
*
* Since this needs the lock owner, and this mutex implementation
* doesn't track the owner atomically in the lock field, we need to
* track it non-atomically.
*
* We can't do this for DEBUG_MUTEXES because that relies on wait_lock
* to serialize everything.
*
* The mutex spinners are queued up using MCS lock so that only one
* spinner can compete for the mutex. However, if mutex spinning isn't
* going to happen, there is no point in going through the lock/unlock
* overhead.
*/
if (!mutex_can_spin_on_owner(lock))
goto slowpath;
for (;;) {
struct task_struct *owner;
struct mspin_node node;
/*
* If there's an owner, wait for it to either
* release the lock or go to sleep.
*/
mspin_lock(MLOCK(lock), &node);
owner = ACCESS_ONCE(lock->owner);
if (owner && !mutex_spin_on_owner(lock, owner)) {
mspin_unlock(MLOCK(lock), &node);
break;
}
if ((atomic_read(&lock->count) == 1) &&
(atomic_cmpxchg(&lock->count, 1, 0) == 1)) {
lock_acquired(&lock->dep_map, ip);
mutex_set_owner(lock);
mspin_unlock(MLOCK(lock), &node);
preempt_enable();
return 0;
}
mspin_unlock(MLOCK(lock), &node);
/*
* When there's no owner, we might have preempted between the
* owner acquiring the lock and setting the owner field. If
* we're an RT task that will live-lock because we won't let
* the owner complete.
*/
if (!owner && (need_resched() || rt_task(task)))
break;
/*
* The cpu_relax() call is a compiler barrier which forces
* everything in this loop to be re-loaded. We don't need
* memory barriers as we'll eventually observe the right
* values at the cost of a few extra spins.
*/
arch_mutex_cpu_relax();
}
slowpath:
#endif
spin_lock_mutex(&lock->wait_lock, flags);
debug_mutex_lock_common(lock, &waiter);
debug_mutex_add_waiter(lock, &waiter, task_thread_info(task));
/* add waiting tasks to the end of the waitqueue (FIFO): */
list_add_tail(&waiter.list, &lock->wait_list);
waiter.task = task;
if (MUTEX_SHOW_NO_WAITER(lock) && (atomic_xchg(&lock->count, -1) == 1))
goto done;
lock_contended(&lock->dep_map, ip);
for (;;) {
/*
* Lets try to take the lock again - this is needed even if
* we get here for the first time (shortly after failing to
* acquire the lock), to make sure that we get a wakeup once
* it's unlocked. Later on, if we sleep, this is the
* operation that gives us the lock. We xchg it to -1, so
* that when we release the lock, we properly wake up the
* other waiters:
*/
if (MUTEX_SHOW_NO_WAITER(lock) &&
(atomic_xchg(&lock->count, -1) == 1))
break;
/*
* got a signal? (This code gets eliminated in the
* TASK_UNINTERRUPTIBLE case.)
*/
if (unlikely(signal_pending_state(state, task))) {
mutex_remove_waiter(lock, &waiter,
task_thread_info(task));
mutex_release(&lock->dep_map, 1, ip);
spin_unlock_mutex(&lock->wait_lock, flags);
debug_mutex_free_waiter(&waiter);
preempt_enable();
return -EINTR;
}
__set_task_state(task, state);
/* didn't get the lock, go to sleep: */
spin_unlock_mutex(&lock->wait_lock, flags);
schedule_preempt_disabled();
spin_lock_mutex(&lock->wait_lock, flags);
}
done:
lock_acquired(&lock->dep_map, ip);
/* got the lock - rejoice! */
mutex_remove_waiter(lock, &waiter, current_thread_info());
mutex_set_owner(lock);
/* set it to 0 if there are no waiters left: */
if (likely(list_empty(&lock->wait_list)))
atomic_set(&lock->count, 0);
spin_unlock_mutex(&lock->wait_lock, flags);
debug_mutex_free_waiter(&waiter);
preempt_enable();
return 0;
}
#ifdef CONFIG_DEBUG_LOCK_ALLOC
void __sched
mutex_lock_nested(struct mutex *lock, unsigned int subclass)
{
might_sleep();
__mutex_lock_common(lock, TASK_UNINTERRUPTIBLE, subclass, NULL, _RET_IP_);
}
EXPORT_SYMBOL_GPL(mutex_lock_nested);
void __sched
_mutex_lock_nest_lock(struct mutex *lock, struct lockdep_map *nest)
{
might_sleep();
__mutex_lock_common(lock, TASK_UNINTERRUPTIBLE, 0, nest, _RET_IP_);
}
EXPORT_SYMBOL_GPL(_mutex_lock_nest_lock);
int __sched
mutex_lock_killable_nested(struct mutex *lock, unsigned int subclass)
{
might_sleep();
return __mutex_lock_common(lock, TASK_KILLABLE, subclass, NULL, _RET_IP_);
}
EXPORT_SYMBOL_GPL(mutex_lock_killable_nested);
int __sched
mutex_lock_interruptible_nested(struct mutex *lock, unsigned int subclass)
{
might_sleep();
return __mutex_lock_common(lock, TASK_INTERRUPTIBLE,
subclass, NULL, _RET_IP_);
}
EXPORT_SYMBOL_GPL(mutex_lock_interruptible_nested);
#endif
/*
* Release the lock, slowpath:
*/
static inline void
__mutex_unlock_common_slowpath(atomic_t *lock_count, int nested)
{
struct mutex *lock = container_of(lock_count, struct mutex, count);
unsigned long flags;
spin_lock_mutex(&lock->wait_lock, flags);
mutex_release(&lock->dep_map, nested, _RET_IP_);
debug_mutex_unlock(lock);
/*
* some architectures leave the lock unlocked in the fastpath failure
* case, others need to leave it locked. In the later case we have to
* unlock it here
*/
if (__mutex_slowpath_needs_to_unlock())
atomic_set(&lock->count, 1);
if (!list_empty(&lock->wait_list)) {
/* get the first entry from the wait-list: */
struct mutex_waiter *waiter =
list_entry(lock->wait_list.next,
struct mutex_waiter, list);
debug_mutex_wake_waiter(lock, waiter);
wake_up_process(waiter->task);
}
spin_unlock_mutex(&lock->wait_lock, flags);
}
/*
* Release the lock, slowpath:
*/
static __used noinline void
__mutex_unlock_slowpath(atomic_t *lock_count)
{
__mutex_unlock_common_slowpath(lock_count, 1);
}
#ifndef CONFIG_DEBUG_LOCK_ALLOC
/*
* Here come the less common (and hence less performance-critical) APIs:
* mutex_lock_interruptible() and mutex_trylock().
*/
static noinline int __sched
__mutex_lock_killable_slowpath(atomic_t *lock_count);
static noinline int __sched
__mutex_lock_interruptible_slowpath(atomic_t *lock_count);
/**
* mutex_lock_interruptible - acquire the mutex, interruptible
* @lock: the mutex to be acquired
*
* Lock the mutex like mutex_lock(), and return 0 if the mutex has
* been acquired or sleep until the mutex becomes available. If a
* signal arrives while waiting for the lock then this function
* returns -EINTR.
*
* This function is similar to (but not equivalent to) down_interruptible().
*/
int __sched mutex_lock_interruptible(struct mutex *lock)
{
int ret;
might_sleep();
ret = __mutex_fastpath_lock_retval
(&lock->count, __mutex_lock_interruptible_slowpath);
if (!ret)
mutex_set_owner(lock);
return ret;
}
EXPORT_SYMBOL(mutex_lock_interruptible);
int __sched mutex_lock_killable(struct mutex *lock)
{
int ret;
might_sleep();
ret = __mutex_fastpath_lock_retval
(&lock->count, __mutex_lock_killable_slowpath);
if (!ret)
mutex_set_owner(lock);
return ret;
}
EXPORT_SYMBOL(mutex_lock_killable);
static __used noinline void __sched
__mutex_lock_slowpath(atomic_t *lock_count)
{
struct mutex *lock = container_of(lock_count, struct mutex, count);
__mutex_lock_common(lock, TASK_UNINTERRUPTIBLE, 0, NULL, _RET_IP_);
}
static noinline int __sched
__mutex_lock_killable_slowpath(atomic_t *lock_count)
{
struct mutex *lock = container_of(lock_count, struct mutex, count);
return __mutex_lock_common(lock, TASK_KILLABLE, 0, NULL, _RET_IP_);
}
static noinline int __sched
__mutex_lock_interruptible_slowpath(atomic_t *lock_count)
{
struct mutex *lock = container_of(lock_count, struct mutex, count);
return __mutex_lock_common(lock, TASK_INTERRUPTIBLE, 0, NULL, _RET_IP_);
}
#endif
/*
* Spinlock based trylock, we take the spinlock and check whether we
* can get the lock:
*/
static inline int __mutex_trylock_slowpath(atomic_t *lock_count)
{
struct mutex *lock = container_of(lock_count, struct mutex, count);
unsigned long flags;
int prev;
spin_lock_mutex(&lock->wait_lock, flags);
prev = atomic_xchg(&lock->count, -1);
if (likely(prev == 1)) {
mutex_set_owner(lock);
mutex_acquire(&lock->dep_map, 0, 1, _RET_IP_);
}
/* Set it back to 0 if there are no waiters: */
if (likely(list_empty(&lock->wait_list)))
atomic_set(&lock->count, 0);
spin_unlock_mutex(&lock->wait_lock, flags);
return prev == 1;
}
/**
* mutex_trylock - try to acquire the mutex, without waiting
* @lock: the mutex to be acquired
*
* Try to acquire the mutex atomically. Returns 1 if the mutex
* has been acquired successfully, and 0 on contention.
*
* NOTE: this function follows the spin_trylock() convention, so
* it is negated from the down_trylock() return values! Be careful
* about this when converting semaphore users to mutexes.
*
* This function must not be used in interrupt context. The
* mutex must be released by the same task that acquired it.
*/
int __sched mutex_trylock(struct mutex *lock)
{
int ret;
ret = __mutex_fastpath_trylock(&lock->count, __mutex_trylock_slowpath);
if (ret)
mutex_set_owner(lock);
return ret;
}
EXPORT_SYMBOL(mutex_trylock);
/**
* atomic_dec_and_mutex_lock - return holding mutex if we dec to 0
* @cnt: the atomic which we are to dec
* @lock: the mutex to return holding if we dec to 0
*
* return true and hold lock if we dec to 0, return false otherwise
*/
int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock)
{
/* dec if we can't possibly hit 0 */
if (atomic_add_unless(cnt, -1, 1))
return 0;
/* we might hit 0, so take the lock */
mutex_lock(lock);
if (!atomic_dec_and_test(cnt)) {
/* when we actually did the dec, we didn't hit 0 */
mutex_unlock(lock);
return 0;
}
/* we hit 0, and we hold the lock */
return 1;
}
EXPORT_SYMBOL(atomic_dec_and_mutex_lock);
| gpl-2.0 |
Split-Screen/android_kernel_asus_fugu | drivers/platform/x86/pvpanic.c | 2309 | 2909 | /*
* pvpanic.c - pvpanic Device Support
*
* Copyright (C) 2013 Fujitsu.
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
MODULE_AUTHOR("Hu Tao <hutao@cn.fujitsu.com>");
MODULE_DESCRIPTION("pvpanic device driver");
MODULE_LICENSE("GPL");
static int pvpanic_add(struct acpi_device *device);
static int pvpanic_remove(struct acpi_device *device);
static const struct acpi_device_id pvpanic_device_ids[] = {
{ "QEMU0001", 0 },
{ "", 0 },
};
MODULE_DEVICE_TABLE(acpi, pvpanic_device_ids);
#define PVPANIC_PANICKED (1 << 0)
static u16 port;
static struct acpi_driver pvpanic_driver = {
.name = "pvpanic",
.class = "QEMU",
.ids = pvpanic_device_ids,
.ops = {
.add = pvpanic_add,
.remove = pvpanic_remove,
},
.owner = THIS_MODULE,
};
static void
pvpanic_send_event(unsigned int event)
{
outb(event, port);
}
static int
pvpanic_panic_notify(struct notifier_block *nb, unsigned long code,
void *unused)
{
pvpanic_send_event(PVPANIC_PANICKED);
return NOTIFY_DONE;
}
static struct notifier_block pvpanic_panic_nb = {
.notifier_call = pvpanic_panic_notify,
};
static acpi_status
pvpanic_walk_resources(struct acpi_resource *res, void *context)
{
switch (res->type) {
case ACPI_RESOURCE_TYPE_END_TAG:
return AE_OK;
case ACPI_RESOURCE_TYPE_IO:
port = res->data.io.minimum;
return AE_OK;
default:
return AE_ERROR;
}
}
static int pvpanic_add(struct acpi_device *device)
{
acpi_status status;
u64 ret;
status = acpi_evaluate_integer(device->handle, "_STA", NULL,
&ret);
if (ACPI_FAILURE(status) || (ret & 0x0B) != 0x0B)
return -ENODEV;
acpi_walk_resources(device->handle, METHOD_NAME__CRS,
pvpanic_walk_resources, NULL);
if (!port)
return -ENODEV;
atomic_notifier_chain_register(&panic_notifier_list,
&pvpanic_panic_nb);
return 0;
}
static int pvpanic_remove(struct acpi_device *device)
{
atomic_notifier_chain_unregister(&panic_notifier_list,
&pvpanic_panic_nb);
return 0;
}
module_acpi_driver(pvpanic_driver);
| gpl-2.0 |
goodhanrry/N915S_goodHanrry_kernel | drivers/net/ethernet/sfc/siena_sriov.c | 2309 | 45904 | /****************************************************************************
* Driver for Solarflare Solarstorm network controllers and boards
* Copyright 2010-2011 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/pci.h>
#include <linux/module.h>
#include "net_driver.h"
#include "efx.h"
#include "nic.h"
#include "io.h"
#include "mcdi.h"
#include "filter.h"
#include "mcdi_pcol.h"
#include "regs.h"
#include "vfdi.h"
/* Number of longs required to track all the VIs in a VF */
#define VI_MASK_LENGTH BITS_TO_LONGS(1 << EFX_VI_SCALE_MAX)
/* Maximum number of RX queues supported */
#define VF_MAX_RX_QUEUES 63
/**
* enum efx_vf_tx_filter_mode - TX MAC filtering behaviour
* @VF_TX_FILTER_OFF: Disabled
* @VF_TX_FILTER_AUTO: Enabled if MAC address assigned to VF and only
* 2 TX queues allowed per VF.
* @VF_TX_FILTER_ON: Enabled
*/
enum efx_vf_tx_filter_mode {
VF_TX_FILTER_OFF,
VF_TX_FILTER_AUTO,
VF_TX_FILTER_ON,
};
/**
* struct efx_vf - Back-end resource and protocol state for a PCI VF
* @efx: The Efx NIC owning this VF
* @pci_rid: The PCI requester ID for this VF
* @pci_name: The PCI name (formatted address) of this VF
* @index: Index of VF within its port and PF.
* @req: VFDI incoming request work item. Incoming USR_EV events are received
* by the NAPI handler, but must be handled by executing MCDI requests
* inside a work item.
* @req_addr: VFDI incoming request DMA address (in VF's PCI address space).
* @req_type: Expected next incoming (from VF) %VFDI_EV_TYPE member.
* @req_seqno: Expected next incoming (from VF) %VFDI_EV_SEQ member.
* @msg_seqno: Next %VFDI_EV_SEQ member to reply to VF. Protected by
* @status_lock
* @busy: VFDI request queued to be processed or being processed. Receiving
* a VFDI request when @busy is set is an error condition.
* @buf: Incoming VFDI requests are DMA from the VF into this buffer.
* @buftbl_base: Buffer table entries for this VF start at this index.
* @rx_filtering: Receive filtering has been requested by the VF driver.
* @rx_filter_flags: The flags sent in the %VFDI_OP_INSERT_FILTER request.
* @rx_filter_qid: VF relative qid for RX filter requested by VF.
* @rx_filter_id: Receive MAC filter ID. Only one filter per VF is supported.
* @tx_filter_mode: Transmit MAC filtering mode.
* @tx_filter_id: Transmit MAC filter ID.
* @addr: The MAC address and outer vlan tag of the VF.
* @status_addr: VF DMA address of page for &struct vfdi_status updates.
* @status_lock: Mutex protecting @msg_seqno, @status_addr, @addr,
* @peer_page_addrs and @peer_page_count from simultaneous
* updates by the VM and consumption by
* efx_sriov_update_vf_addr()
* @peer_page_addrs: Pointer to an array of guest pages for local addresses.
* @peer_page_count: Number of entries in @peer_page_count.
* @evq0_addrs: Array of guest pages backing evq0.
* @evq0_count: Number of entries in @evq0_addrs.
* @flush_waitq: wait queue used by %VFDI_OP_FINI_ALL_QUEUES handler
* to wait for flush completions.
* @txq_lock: Mutex for TX queue allocation.
* @txq_mask: Mask of initialized transmit queues.
* @txq_count: Number of initialized transmit queues.
* @rxq_mask: Mask of initialized receive queues.
* @rxq_count: Number of initialized receive queues.
* @rxq_retry_mask: Mask or receive queues that need to be flushed again
* due to flush failure.
* @rxq_retry_count: Number of receive queues in @rxq_retry_mask.
* @reset_work: Work item to schedule a VF reset.
*/
struct efx_vf {
struct efx_nic *efx;
unsigned int pci_rid;
char pci_name[13]; /* dddd:bb:dd.f */
unsigned int index;
struct work_struct req;
u64 req_addr;
int req_type;
unsigned req_seqno;
unsigned msg_seqno;
bool busy;
struct efx_buffer buf;
unsigned buftbl_base;
bool rx_filtering;
enum efx_filter_flags rx_filter_flags;
unsigned rx_filter_qid;
int rx_filter_id;
enum efx_vf_tx_filter_mode tx_filter_mode;
int tx_filter_id;
struct vfdi_endpoint addr;
u64 status_addr;
struct mutex status_lock;
u64 *peer_page_addrs;
unsigned peer_page_count;
u64 evq0_addrs[EFX_MAX_VF_EVQ_SIZE * sizeof(efx_qword_t) /
EFX_BUF_SIZE];
unsigned evq0_count;
wait_queue_head_t flush_waitq;
struct mutex txq_lock;
unsigned long txq_mask[VI_MASK_LENGTH];
unsigned txq_count;
unsigned long rxq_mask[VI_MASK_LENGTH];
unsigned rxq_count;
unsigned long rxq_retry_mask[VI_MASK_LENGTH];
atomic_t rxq_retry_count;
struct work_struct reset_work;
};
struct efx_memcpy_req {
unsigned int from_rid;
void *from_buf;
u64 from_addr;
unsigned int to_rid;
u64 to_addr;
unsigned length;
};
/**
* struct efx_local_addr - A MAC address on the vswitch without a VF.
*
* Siena does not have a switch, so VFs can't transmit data to each
* other. Instead the VFs must be made aware of the local addresses
* on the vswitch, so that they can arrange for an alternative
* software datapath to be used.
*
* @link: List head for insertion into efx->local_addr_list.
* @addr: Ethernet address
*/
struct efx_local_addr {
struct list_head link;
u8 addr[ETH_ALEN];
};
/**
* struct efx_endpoint_page - Page of vfdi_endpoint structures
*
* @link: List head for insertion into efx->local_page_list.
* @ptr: Pointer to page.
* @addr: DMA address of page.
*/
struct efx_endpoint_page {
struct list_head link;
void *ptr;
dma_addr_t addr;
};
/* Buffer table entries are reserved txq0,rxq0,evq0,txq1,rxq1,evq1 */
#define EFX_BUFTBL_TXQ_BASE(_vf, _qid) \
((_vf)->buftbl_base + EFX_VF_BUFTBL_PER_VI * (_qid))
#define EFX_BUFTBL_RXQ_BASE(_vf, _qid) \
(EFX_BUFTBL_TXQ_BASE(_vf, _qid) + \
(EFX_MAX_DMAQ_SIZE * sizeof(efx_qword_t) / EFX_BUF_SIZE))
#define EFX_BUFTBL_EVQ_BASE(_vf, _qid) \
(EFX_BUFTBL_TXQ_BASE(_vf, _qid) + \
(2 * EFX_MAX_DMAQ_SIZE * sizeof(efx_qword_t) / EFX_BUF_SIZE))
#define EFX_FIELD_MASK(_field) \
((1 << _field ## _WIDTH) - 1)
/* VFs can only use this many transmit channels */
static unsigned int vf_max_tx_channels = 2;
module_param(vf_max_tx_channels, uint, 0444);
MODULE_PARM_DESC(vf_max_tx_channels,
"Limit the number of TX channels VFs can use");
static int max_vfs = -1;
module_param(max_vfs, int, 0444);
MODULE_PARM_DESC(max_vfs,
"Reduce the number of VFs initialized by the driver");
/* Workqueue used by VFDI communication. We can't use the global
* workqueue because it may be running the VF driver's probe()
* routine, which will be blocked there waiting for a VFDI response.
*/
static struct workqueue_struct *vfdi_workqueue;
static unsigned abs_index(struct efx_vf *vf, unsigned index)
{
return EFX_VI_BASE + vf->index * efx_vf_size(vf->efx) + index;
}
static int efx_sriov_cmd(struct efx_nic *efx, bool enable,
unsigned *vi_scale_out, unsigned *vf_total_out)
{
u8 inbuf[MC_CMD_SRIOV_IN_LEN];
u8 outbuf[MC_CMD_SRIOV_OUT_LEN];
unsigned vi_scale, vf_total;
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, SRIOV_IN_ENABLE, enable ? 1 : 0);
MCDI_SET_DWORD(inbuf, SRIOV_IN_VI_BASE, EFX_VI_BASE);
MCDI_SET_DWORD(inbuf, SRIOV_IN_VF_COUNT, efx->vf_count);
rc = efx_mcdi_rpc(efx, MC_CMD_SRIOV, inbuf, MC_CMD_SRIOV_IN_LEN,
outbuf, MC_CMD_SRIOV_OUT_LEN, &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_SRIOV_OUT_LEN)
return -EIO;
vf_total = MCDI_DWORD(outbuf, SRIOV_OUT_VF_TOTAL);
vi_scale = MCDI_DWORD(outbuf, SRIOV_OUT_VI_SCALE);
if (vi_scale > EFX_VI_SCALE_MAX)
return -EOPNOTSUPP;
if (vi_scale_out)
*vi_scale_out = vi_scale;
if (vf_total_out)
*vf_total_out = vf_total;
return 0;
}
static void efx_sriov_usrev(struct efx_nic *efx, bool enabled)
{
efx_oword_t reg;
EFX_POPULATE_OWORD_2(reg,
FRF_CZ_USREV_DIS, enabled ? 0 : 1,
FRF_CZ_DFLT_EVQ, efx->vfdi_channel->channel);
efx_writeo(efx, ®, FR_CZ_USR_EV_CFG);
}
static int efx_sriov_memcpy(struct efx_nic *efx, struct efx_memcpy_req *req,
unsigned int count)
{
u8 *inbuf, *record;
unsigned int used;
u32 from_rid, from_hi, from_lo;
int rc;
mb(); /* Finish writing source/reading dest before DMA starts */
used = MC_CMD_MEMCPY_IN_LEN(count);
if (WARN_ON(used > MCDI_CTL_SDU_LEN_MAX))
return -ENOBUFS;
/* Allocate room for the largest request */
inbuf = kzalloc(MCDI_CTL_SDU_LEN_MAX, GFP_KERNEL);
if (inbuf == NULL)
return -ENOMEM;
record = inbuf;
MCDI_SET_DWORD(record, MEMCPY_IN_RECORD, count);
while (count-- > 0) {
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_TO_RID,
req->to_rid);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_TO_ADDR_LO,
(u32)req->to_addr);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_TO_ADDR_HI,
(u32)(req->to_addr >> 32));
if (req->from_buf == NULL) {
from_rid = req->from_rid;
from_lo = (u32)req->from_addr;
from_hi = (u32)(req->from_addr >> 32);
} else {
if (WARN_ON(used + req->length > MCDI_CTL_SDU_LEN_MAX)) {
rc = -ENOBUFS;
goto out;
}
from_rid = MC_CMD_MEMCPY_RECORD_TYPEDEF_RID_INLINE;
from_lo = used;
from_hi = 0;
memcpy(inbuf + used, req->from_buf, req->length);
used += req->length;
}
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_FROM_RID, from_rid);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_FROM_ADDR_LO,
from_lo);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_FROM_ADDR_HI,
from_hi);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_LENGTH,
req->length);
++req;
record += MC_CMD_MEMCPY_IN_RECORD_LEN;
}
rc = efx_mcdi_rpc(efx, MC_CMD_MEMCPY, inbuf, used, NULL, 0, NULL);
out:
kfree(inbuf);
mb(); /* Don't write source/read dest before DMA is complete */
return rc;
}
/* The TX filter is entirely controlled by this driver, and is modified
* underneath the feet of the VF
*/
static void efx_sriov_reset_tx_filter(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct efx_filter_spec filter;
u16 vlan;
int rc;
if (vf->tx_filter_id != -1) {
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
vf->tx_filter_id);
netif_dbg(efx, hw, efx->net_dev, "Removed vf %s tx filter %d\n",
vf->pci_name, vf->tx_filter_id);
vf->tx_filter_id = -1;
}
if (is_zero_ether_addr(vf->addr.mac_addr))
return;
/* Turn on TX filtering automatically if not explicitly
* enabled or disabled.
*/
if (vf->tx_filter_mode == VF_TX_FILTER_AUTO && vf_max_tx_channels <= 2)
vf->tx_filter_mode = VF_TX_FILTER_ON;
vlan = ntohs(vf->addr.tci) & VLAN_VID_MASK;
efx_filter_init_tx(&filter, abs_index(vf, 0));
rc = efx_filter_set_eth_local(&filter,
vlan ? vlan : EFX_FILTER_VID_UNSPEC,
vf->addr.mac_addr);
BUG_ON(rc);
rc = efx_filter_insert_filter(efx, &filter, true);
if (rc < 0) {
netif_warn(efx, hw, efx->net_dev,
"Unable to migrate tx filter for vf %s\n",
vf->pci_name);
} else {
netif_dbg(efx, hw, efx->net_dev, "Inserted vf %s tx filter %d\n",
vf->pci_name, rc);
vf->tx_filter_id = rc;
}
}
/* The RX filter is managed here on behalf of the VF driver */
static void efx_sriov_reset_rx_filter(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct efx_filter_spec filter;
u16 vlan;
int rc;
if (vf->rx_filter_id != -1) {
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
vf->rx_filter_id);
netif_dbg(efx, hw, efx->net_dev, "Removed vf %s rx filter %d\n",
vf->pci_name, vf->rx_filter_id);
vf->rx_filter_id = -1;
}
if (!vf->rx_filtering || is_zero_ether_addr(vf->addr.mac_addr))
return;
vlan = ntohs(vf->addr.tci) & VLAN_VID_MASK;
efx_filter_init_rx(&filter, EFX_FILTER_PRI_REQUIRED,
vf->rx_filter_flags,
abs_index(vf, vf->rx_filter_qid));
rc = efx_filter_set_eth_local(&filter,
vlan ? vlan : EFX_FILTER_VID_UNSPEC,
vf->addr.mac_addr);
BUG_ON(rc);
rc = efx_filter_insert_filter(efx, &filter, true);
if (rc < 0) {
netif_warn(efx, hw, efx->net_dev,
"Unable to insert rx filter for vf %s\n",
vf->pci_name);
} else {
netif_dbg(efx, hw, efx->net_dev, "Inserted vf %s rx filter %d\n",
vf->pci_name, rc);
vf->rx_filter_id = rc;
}
}
static void __efx_sriov_update_vf_addr(struct efx_vf *vf)
{
efx_sriov_reset_tx_filter(vf);
efx_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &vf->efx->peer_work);
}
/* Push the peer list to this VF. The caller must hold status_lock to interlock
* with VFDI requests, and they must be serialised against manipulation of
* local_page_list, either by acquiring local_lock or by running from
* efx_sriov_peer_work()
*/
static void __efx_sriov_push_vf_status(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_status *status = efx->vfdi_status.addr;
struct efx_memcpy_req copy[4];
struct efx_endpoint_page *epp;
unsigned int pos, count;
unsigned data_offset;
efx_qword_t event;
WARN_ON(!mutex_is_locked(&vf->status_lock));
WARN_ON(!vf->status_addr);
status->local = vf->addr;
status->generation_end = ++status->generation_start;
memset(copy, '\0', sizeof(copy));
/* Write generation_start */
copy[0].from_buf = &status->generation_start;
copy[0].to_rid = vf->pci_rid;
copy[0].to_addr = vf->status_addr + offsetof(struct vfdi_status,
generation_start);
copy[0].length = sizeof(status->generation_start);
/* DMA the rest of the structure (excluding the generations). This
* assumes that the non-generation portion of vfdi_status is in
* one chunk starting at the version member.
*/
data_offset = offsetof(struct vfdi_status, version);
copy[1].from_rid = efx->pci_dev->devfn;
copy[1].from_addr = efx->vfdi_status.dma_addr + data_offset;
copy[1].to_rid = vf->pci_rid;
copy[1].to_addr = vf->status_addr + data_offset;
copy[1].length = status->length - data_offset;
/* Copy the peer pages */
pos = 2;
count = 0;
list_for_each_entry(epp, &efx->local_page_list, link) {
if (count == vf->peer_page_count) {
/* The VF driver will know they need to provide more
* pages because peer_addr_count is too large.
*/
break;
}
copy[pos].from_buf = NULL;
copy[pos].from_rid = efx->pci_dev->devfn;
copy[pos].from_addr = epp->addr;
copy[pos].to_rid = vf->pci_rid;
copy[pos].to_addr = vf->peer_page_addrs[count];
copy[pos].length = EFX_PAGE_SIZE;
if (++pos == ARRAY_SIZE(copy)) {
efx_sriov_memcpy(efx, copy, ARRAY_SIZE(copy));
pos = 0;
}
++count;
}
/* Write generation_end */
copy[pos].from_buf = &status->generation_end;
copy[pos].to_rid = vf->pci_rid;
copy[pos].to_addr = vf->status_addr + offsetof(struct vfdi_status,
generation_end);
copy[pos].length = sizeof(status->generation_end);
efx_sriov_memcpy(efx, copy, pos + 1);
/* Notify the guest */
EFX_POPULATE_QWORD_3(event,
FSF_AZ_EV_CODE, FSE_CZ_EV_CODE_USER_EV,
VFDI_EV_SEQ, (vf->msg_seqno & 0xff),
VFDI_EV_TYPE, VFDI_EV_TYPE_STATUS);
++vf->msg_seqno;
efx_generate_event(efx, EFX_VI_BASE + vf->index * efx_vf_size(efx),
&event);
}
static void efx_sriov_bufs(struct efx_nic *efx, unsigned offset,
u64 *addr, unsigned count)
{
efx_qword_t buf;
unsigned pos;
for (pos = 0; pos < count; ++pos) {
EFX_POPULATE_QWORD_3(buf,
FRF_AZ_BUF_ADR_REGION, 0,
FRF_AZ_BUF_ADR_FBUF,
addr ? addr[pos] >> 12 : 0,
FRF_AZ_BUF_OWNER_ID_FBUF, 0);
efx_sram_writeq(efx, efx->membase + FR_BZ_BUF_FULL_TBL,
&buf, offset + pos);
}
}
static bool bad_vf_index(struct efx_nic *efx, unsigned index)
{
return index >= efx_vf_size(efx);
}
static bool bad_buf_count(unsigned buf_count, unsigned max_entry_count)
{
unsigned max_buf_count = max_entry_count *
sizeof(efx_qword_t) / EFX_BUF_SIZE;
return ((buf_count & (buf_count - 1)) || buf_count > max_buf_count);
}
/* Check that VI specified by per-port index belongs to a VF.
* Optionally set VF index and VI index within the VF.
*/
static bool map_vi_index(struct efx_nic *efx, unsigned abs_index,
struct efx_vf **vf_out, unsigned *rel_index_out)
{
unsigned vf_i;
if (abs_index < EFX_VI_BASE)
return true;
vf_i = (abs_index - EFX_VI_BASE) / efx_vf_size(efx);
if (vf_i >= efx->vf_init_count)
return true;
if (vf_out)
*vf_out = efx->vf + vf_i;
if (rel_index_out)
*rel_index_out = abs_index % efx_vf_size(efx);
return false;
}
static int efx_vfdi_init_evq(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_evq = req->u.init_evq.index;
unsigned buf_count = req->u.init_evq.buf_count;
unsigned abs_evq = abs_index(vf, vf_evq);
unsigned buftbl = EFX_BUFTBL_EVQ_BASE(vf, vf_evq);
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) ||
bad_buf_count(buf_count, EFX_MAX_VF_EVQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_EVQ from %s: evq %d bufs %d\n",
vf->pci_name, vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
efx_sriov_bufs(efx, buftbl, req->u.init_evq.addr, buf_count);
EFX_POPULATE_OWORD_3(reg,
FRF_CZ_TIMER_Q_EN, 1,
FRF_CZ_HOST_NOTIFY_MODE, 0,
FRF_CZ_TIMER_MODE, FFE_CZ_TIMER_MODE_DIS);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL, abs_evq);
EFX_POPULATE_OWORD_3(reg,
FRF_AZ_EVQ_EN, 1,
FRF_AZ_EVQ_SIZE, __ffs(buf_count),
FRF_AZ_EVQ_BUF_BASE_ID, buftbl);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL, abs_evq);
if (vf_evq == 0) {
memcpy(vf->evq0_addrs, req->u.init_evq.addr,
buf_count * sizeof(u64));
vf->evq0_count = buf_count;
}
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_init_rxq(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_rxq = req->u.init_rxq.index;
unsigned vf_evq = req->u.init_rxq.evq;
unsigned buf_count = req->u.init_rxq.buf_count;
unsigned buftbl = EFX_BUFTBL_RXQ_BASE(vf, vf_rxq);
unsigned label;
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) || bad_vf_index(efx, vf_rxq) ||
vf_rxq >= VF_MAX_RX_QUEUES ||
bad_buf_count(buf_count, EFX_MAX_DMAQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_RXQ from %s: rxq %d evq %d "
"buf_count %d\n", vf->pci_name, vf_rxq,
vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
if (__test_and_set_bit(req->u.init_rxq.index, vf->rxq_mask))
++vf->rxq_count;
efx_sriov_bufs(efx, buftbl, req->u.init_rxq.addr, buf_count);
label = req->u.init_rxq.label & EFX_FIELD_MASK(FRF_AZ_RX_DESCQ_LABEL);
EFX_POPULATE_OWORD_6(reg,
FRF_AZ_RX_DESCQ_BUF_BASE_ID, buftbl,
FRF_AZ_RX_DESCQ_EVQ_ID, abs_index(vf, vf_evq),
FRF_AZ_RX_DESCQ_LABEL, label,
FRF_AZ_RX_DESCQ_SIZE, __ffs(buf_count),
FRF_AZ_RX_DESCQ_JUMBO,
!!(req->u.init_rxq.flags &
VFDI_RXQ_FLAG_SCATTER_EN),
FRF_AZ_RX_DESCQ_EN, 1);
efx_writeo_table(efx, ®, FR_BZ_RX_DESC_PTR_TBL,
abs_index(vf, vf_rxq));
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_init_txq(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_txq = req->u.init_txq.index;
unsigned vf_evq = req->u.init_txq.evq;
unsigned buf_count = req->u.init_txq.buf_count;
unsigned buftbl = EFX_BUFTBL_TXQ_BASE(vf, vf_txq);
unsigned label, eth_filt_en;
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) || bad_vf_index(efx, vf_txq) ||
vf_txq >= vf_max_tx_channels ||
bad_buf_count(buf_count, EFX_MAX_DMAQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_TXQ from %s: txq %d evq %d "
"buf_count %d\n", vf->pci_name, vf_txq,
vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
mutex_lock(&vf->txq_lock);
if (__test_and_set_bit(req->u.init_txq.index, vf->txq_mask))
++vf->txq_count;
mutex_unlock(&vf->txq_lock);
efx_sriov_bufs(efx, buftbl, req->u.init_txq.addr, buf_count);
eth_filt_en = vf->tx_filter_mode == VF_TX_FILTER_ON;
label = req->u.init_txq.label & EFX_FIELD_MASK(FRF_AZ_TX_DESCQ_LABEL);
EFX_POPULATE_OWORD_8(reg,
FRF_CZ_TX_DPT_Q_MASK_WIDTH, min(efx->vi_scale, 1U),
FRF_CZ_TX_DPT_ETH_FILT_EN, eth_filt_en,
FRF_AZ_TX_DESCQ_EN, 1,
FRF_AZ_TX_DESCQ_BUF_BASE_ID, buftbl,
FRF_AZ_TX_DESCQ_EVQ_ID, abs_index(vf, vf_evq),
FRF_AZ_TX_DESCQ_LABEL, label,
FRF_AZ_TX_DESCQ_SIZE, __ffs(buf_count),
FRF_BZ_TX_NON_IP_DROP_DIS, 1);
efx_writeo_table(efx, ®, FR_BZ_TX_DESC_PTR_TBL,
abs_index(vf, vf_txq));
return VFDI_RC_SUCCESS;
}
/* Returns true when efx_vfdi_fini_all_queues should wake */
static bool efx_vfdi_flush_wake(struct efx_vf *vf)
{
/* Ensure that all updates are visible to efx_vfdi_fini_all_queues() */
smp_mb();
return (!vf->txq_count && !vf->rxq_count) ||
atomic_read(&vf->rxq_retry_count);
}
static void efx_vfdi_flush_clear(struct efx_vf *vf)
{
memset(vf->txq_mask, 0, sizeof(vf->txq_mask));
vf->txq_count = 0;
memset(vf->rxq_mask, 0, sizeof(vf->rxq_mask));
vf->rxq_count = 0;
memset(vf->rxq_retry_mask, 0, sizeof(vf->rxq_retry_mask));
atomic_set(&vf->rxq_retry_count, 0);
}
static int efx_vfdi_fini_all_queues(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
efx_oword_t reg;
unsigned count = efx_vf_size(efx);
unsigned vf_offset = EFX_VI_BASE + vf->index * efx_vf_size(efx);
unsigned timeout = HZ;
unsigned index, rxqs_count;
__le32 *rxqs;
int rc;
BUILD_BUG_ON(VF_MAX_RX_QUEUES >
MC_CMD_FLUSH_RX_QUEUES_IN_QID_OFST_MAXNUM);
rxqs = kmalloc(count * sizeof(*rxqs), GFP_KERNEL);
if (rxqs == NULL)
return VFDI_RC_ENOMEM;
rtnl_lock();
siena_prepare_flush(efx);
rtnl_unlock();
/* Flush all the initialized queues */
rxqs_count = 0;
for (index = 0; index < count; ++index) {
if (test_bit(index, vf->txq_mask)) {
EFX_POPULATE_OWORD_2(reg,
FRF_AZ_TX_FLUSH_DESCQ_CMD, 1,
FRF_AZ_TX_FLUSH_DESCQ,
vf_offset + index);
efx_writeo(efx, ®, FR_AZ_TX_FLUSH_DESCQ);
}
if (test_bit(index, vf->rxq_mask))
rxqs[rxqs_count++] = cpu_to_le32(vf_offset + index);
}
atomic_set(&vf->rxq_retry_count, 0);
while (timeout && (vf->rxq_count || vf->txq_count)) {
rc = efx_mcdi_rpc(efx, MC_CMD_FLUSH_RX_QUEUES, (u8 *)rxqs,
rxqs_count * sizeof(*rxqs), NULL, 0, NULL);
WARN_ON(rc < 0);
timeout = wait_event_timeout(vf->flush_waitq,
efx_vfdi_flush_wake(vf),
timeout);
rxqs_count = 0;
for (index = 0; index < count; ++index) {
if (test_and_clear_bit(index, vf->rxq_retry_mask)) {
atomic_dec(&vf->rxq_retry_count);
rxqs[rxqs_count++] =
cpu_to_le32(vf_offset + index);
}
}
}
rtnl_lock();
siena_finish_flush(efx);
rtnl_unlock();
/* Irrespective of success/failure, fini the queues */
EFX_ZERO_OWORD(reg);
for (index = 0; index < count; ++index) {
efx_writeo_table(efx, ®, FR_BZ_RX_DESC_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_TX_DESC_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL,
vf_offset + index);
}
efx_sriov_bufs(efx, vf->buftbl_base, NULL,
EFX_VF_BUFTBL_PER_VI * efx_vf_size(efx));
kfree(rxqs);
efx_vfdi_flush_clear(vf);
vf->evq0_count = 0;
return timeout ? 0 : VFDI_RC_ETIMEDOUT;
}
static int efx_vfdi_insert_filter(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_rxq = req->u.mac_filter.rxq;
unsigned flags;
if (bad_vf_index(efx, vf_rxq) || vf->rx_filtering) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INSERT_FILTER from %s: rxq %d "
"flags 0x%x\n", vf->pci_name, vf_rxq,
req->u.mac_filter.flags);
return VFDI_RC_EINVAL;
}
flags = 0;
if (req->u.mac_filter.flags & VFDI_MAC_FILTER_FLAG_RSS)
flags |= EFX_FILTER_FLAG_RX_RSS;
if (req->u.mac_filter.flags & VFDI_MAC_FILTER_FLAG_SCATTER)
flags |= EFX_FILTER_FLAG_RX_SCATTER;
vf->rx_filter_flags = flags;
vf->rx_filter_qid = vf_rxq;
vf->rx_filtering = true;
efx_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &efx->peer_work);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_remove_all_filters(struct efx_vf *vf)
{
vf->rx_filtering = false;
efx_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &vf->efx->peer_work);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_set_status_page(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
u64 page_count = req->u.set_status_page.peer_page_count;
u64 max_page_count =
(EFX_PAGE_SIZE -
offsetof(struct vfdi_req, u.set_status_page.peer_page_addr[0]))
/ sizeof(req->u.set_status_page.peer_page_addr[0]);
if (!req->u.set_status_page.dma_addr || page_count > max_page_count) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid SET_STATUS_PAGE from %s\n",
vf->pci_name);
return VFDI_RC_EINVAL;
}
mutex_lock(&efx->local_lock);
mutex_lock(&vf->status_lock);
vf->status_addr = req->u.set_status_page.dma_addr;
kfree(vf->peer_page_addrs);
vf->peer_page_addrs = NULL;
vf->peer_page_count = 0;
if (page_count) {
vf->peer_page_addrs = kcalloc(page_count, sizeof(u64),
GFP_KERNEL);
if (vf->peer_page_addrs) {
memcpy(vf->peer_page_addrs,
req->u.set_status_page.peer_page_addr,
page_count * sizeof(u64));
vf->peer_page_count = page_count;
}
}
__efx_sriov_push_vf_status(vf);
mutex_unlock(&vf->status_lock);
mutex_unlock(&efx->local_lock);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_clear_status_page(struct efx_vf *vf)
{
mutex_lock(&vf->status_lock);
vf->status_addr = 0;
mutex_unlock(&vf->status_lock);
return VFDI_RC_SUCCESS;
}
typedef int (*efx_vfdi_op_t)(struct efx_vf *vf);
static const efx_vfdi_op_t vfdi_ops[VFDI_OP_LIMIT] = {
[VFDI_OP_INIT_EVQ] = efx_vfdi_init_evq,
[VFDI_OP_INIT_TXQ] = efx_vfdi_init_txq,
[VFDI_OP_INIT_RXQ] = efx_vfdi_init_rxq,
[VFDI_OP_FINI_ALL_QUEUES] = efx_vfdi_fini_all_queues,
[VFDI_OP_INSERT_FILTER] = efx_vfdi_insert_filter,
[VFDI_OP_REMOVE_ALL_FILTERS] = efx_vfdi_remove_all_filters,
[VFDI_OP_SET_STATUS_PAGE] = efx_vfdi_set_status_page,
[VFDI_OP_CLEAR_STATUS_PAGE] = efx_vfdi_clear_status_page,
};
static void efx_sriov_vfdi(struct work_struct *work)
{
struct efx_vf *vf = container_of(work, struct efx_vf, req);
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
struct efx_memcpy_req copy[2];
int rc;
/* Copy this page into the local address space */
memset(copy, '\0', sizeof(copy));
copy[0].from_rid = vf->pci_rid;
copy[0].from_addr = vf->req_addr;
copy[0].to_rid = efx->pci_dev->devfn;
copy[0].to_addr = vf->buf.dma_addr;
copy[0].length = EFX_PAGE_SIZE;
rc = efx_sriov_memcpy(efx, copy, 1);
if (rc) {
/* If we can't get the request, we can't reply to the caller */
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Unable to fetch VFDI request from %s rc %d\n",
vf->pci_name, -rc);
vf->busy = false;
return;
}
if (req->op < VFDI_OP_LIMIT && vfdi_ops[req->op] != NULL) {
rc = vfdi_ops[req->op](vf);
if (rc == 0) {
netif_dbg(efx, hw, efx->net_dev,
"vfdi request %d from %s ok\n",
req->op, vf->pci_name);
}
} else {
netif_dbg(efx, hw, efx->net_dev,
"ERROR: Unrecognised request %d from VF %s addr "
"%llx\n", req->op, vf->pci_name,
(unsigned long long)vf->req_addr);
rc = VFDI_RC_EOPNOTSUPP;
}
/* Allow subsequent VF requests */
vf->busy = false;
smp_wmb();
/* Respond to the request */
req->rc = rc;
req->op = VFDI_OP_RESPONSE;
memset(copy, '\0', sizeof(copy));
copy[0].from_buf = &req->rc;
copy[0].to_rid = vf->pci_rid;
copy[0].to_addr = vf->req_addr + offsetof(struct vfdi_req, rc);
copy[0].length = sizeof(req->rc);
copy[1].from_buf = &req->op;
copy[1].to_rid = vf->pci_rid;
copy[1].to_addr = vf->req_addr + offsetof(struct vfdi_req, op);
copy[1].length = sizeof(req->op);
(void) efx_sriov_memcpy(efx, copy, ARRAY_SIZE(copy));
}
/* After a reset the event queues inside the guests no longer exist. Fill the
* event ring in guest memory with VFDI reset events, then (re-initialise) the
* event queue to raise an interrupt. The guest driver will then recover.
*/
static void efx_sriov_reset_vf(struct efx_vf *vf, struct efx_buffer *buffer)
{
struct efx_nic *efx = vf->efx;
struct efx_memcpy_req copy_req[4];
efx_qword_t event;
unsigned int pos, count, k, buftbl, abs_evq;
efx_oword_t reg;
efx_dword_t ptr;
int rc;
BUG_ON(buffer->len != EFX_PAGE_SIZE);
if (!vf->evq0_count)
return;
BUG_ON(vf->evq0_count & (vf->evq0_count - 1));
mutex_lock(&vf->status_lock);
EFX_POPULATE_QWORD_3(event,
FSF_AZ_EV_CODE, FSE_CZ_EV_CODE_USER_EV,
VFDI_EV_SEQ, vf->msg_seqno,
VFDI_EV_TYPE, VFDI_EV_TYPE_RESET);
vf->msg_seqno++;
for (pos = 0; pos < EFX_PAGE_SIZE; pos += sizeof(event))
memcpy(buffer->addr + pos, &event, sizeof(event));
for (pos = 0; pos < vf->evq0_count; pos += count) {
count = min_t(unsigned, vf->evq0_count - pos,
ARRAY_SIZE(copy_req));
for (k = 0; k < count; k++) {
copy_req[k].from_buf = NULL;
copy_req[k].from_rid = efx->pci_dev->devfn;
copy_req[k].from_addr = buffer->dma_addr;
copy_req[k].to_rid = vf->pci_rid;
copy_req[k].to_addr = vf->evq0_addrs[pos + k];
copy_req[k].length = EFX_PAGE_SIZE;
}
rc = efx_sriov_memcpy(efx, copy_req, count);
if (rc) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Unable to notify %s of reset"
": %d\n", vf->pci_name, -rc);
break;
}
}
/* Reinitialise, arm and trigger evq0 */
abs_evq = abs_index(vf, 0);
buftbl = EFX_BUFTBL_EVQ_BASE(vf, 0);
efx_sriov_bufs(efx, buftbl, vf->evq0_addrs, vf->evq0_count);
EFX_POPULATE_OWORD_3(reg,
FRF_CZ_TIMER_Q_EN, 1,
FRF_CZ_HOST_NOTIFY_MODE, 0,
FRF_CZ_TIMER_MODE, FFE_CZ_TIMER_MODE_DIS);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL, abs_evq);
EFX_POPULATE_OWORD_3(reg,
FRF_AZ_EVQ_EN, 1,
FRF_AZ_EVQ_SIZE, __ffs(vf->evq0_count),
FRF_AZ_EVQ_BUF_BASE_ID, buftbl);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL, abs_evq);
EFX_POPULATE_DWORD_1(ptr, FRF_AZ_EVQ_RPTR, 0);
efx_writed(efx, &ptr, FR_BZ_EVQ_RPTR + FR_BZ_EVQ_RPTR_STEP * abs_evq);
mutex_unlock(&vf->status_lock);
}
static void efx_sriov_reset_vf_work(struct work_struct *work)
{
struct efx_vf *vf = container_of(work, struct efx_vf, req);
struct efx_nic *efx = vf->efx;
struct efx_buffer buf;
if (!efx_nic_alloc_buffer(efx, &buf, EFX_PAGE_SIZE)) {
efx_sriov_reset_vf(vf, &buf);
efx_nic_free_buffer(efx, &buf);
}
}
static void efx_sriov_handle_no_channel(struct efx_nic *efx)
{
netif_err(efx, drv, efx->net_dev,
"ERROR: IOV requires MSI-X and 1 additional interrupt"
"vector. IOV disabled\n");
efx->vf_count = 0;
}
static int efx_sriov_probe_channel(struct efx_channel *channel)
{
channel->efx->vfdi_channel = channel;
return 0;
}
static void
efx_sriov_get_channel_name(struct efx_channel *channel, char *buf, size_t len)
{
snprintf(buf, len, "%s-iov", channel->efx->name);
}
static const struct efx_channel_type efx_sriov_channel_type = {
.handle_no_channel = efx_sriov_handle_no_channel,
.pre_probe = efx_sriov_probe_channel,
.post_remove = efx_channel_dummy_op_void,
.get_name = efx_sriov_get_channel_name,
/* no copy operation; channel must not be reallocated */
.keep_eventq = true,
};
void efx_sriov_probe(struct efx_nic *efx)
{
unsigned count;
if (!max_vfs)
return;
if (efx_sriov_cmd(efx, false, &efx->vi_scale, &count))
return;
if (count > 0 && count > max_vfs)
count = max_vfs;
/* efx_nic_dimension_resources() will reduce vf_count as appopriate */
efx->vf_count = count;
efx->extra_channel_type[EFX_EXTRA_CHANNEL_IOV] = &efx_sriov_channel_type;
}
/* Copy the list of individual addresses into the vfdi_status.peers
* array and auxillary pages, protected by %local_lock. Drop that lock
* and then broadcast the address list to every VF.
*/
static void efx_sriov_peer_work(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic, peer_work);
struct vfdi_status *vfdi_status = efx->vfdi_status.addr;
struct efx_vf *vf;
struct efx_local_addr *local_addr;
struct vfdi_endpoint *peer;
struct efx_endpoint_page *epp;
struct list_head pages;
unsigned int peer_space;
unsigned int peer_count;
unsigned int pos;
mutex_lock(&efx->local_lock);
/* Move the existing peer pages off %local_page_list */
INIT_LIST_HEAD(&pages);
list_splice_tail_init(&efx->local_page_list, &pages);
/* Populate the VF addresses starting from entry 1 (entry 0 is
* the PF address)
*/
peer = vfdi_status->peers + 1;
peer_space = ARRAY_SIZE(vfdi_status->peers) - 1;
peer_count = 1;
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = efx->vf + pos;
mutex_lock(&vf->status_lock);
if (vf->rx_filtering && !is_zero_ether_addr(vf->addr.mac_addr)) {
*peer++ = vf->addr;
++peer_count;
--peer_space;
BUG_ON(peer_space == 0);
}
mutex_unlock(&vf->status_lock);
}
/* Fill the remaining addresses */
list_for_each_entry(local_addr, &efx->local_addr_list, link) {
memcpy(peer->mac_addr, local_addr->addr, ETH_ALEN);
peer->tci = 0;
++peer;
++peer_count;
if (--peer_space == 0) {
if (list_empty(&pages)) {
epp = kmalloc(sizeof(*epp), GFP_KERNEL);
if (!epp)
break;
epp->ptr = dma_alloc_coherent(
&efx->pci_dev->dev, EFX_PAGE_SIZE,
&epp->addr, GFP_KERNEL);
if (!epp->ptr) {
kfree(epp);
break;
}
} else {
epp = list_first_entry(
&pages, struct efx_endpoint_page, link);
list_del(&epp->link);
}
list_add_tail(&epp->link, &efx->local_page_list);
peer = (struct vfdi_endpoint *)epp->ptr;
peer_space = EFX_PAGE_SIZE / sizeof(struct vfdi_endpoint);
}
}
vfdi_status->peer_count = peer_count;
mutex_unlock(&efx->local_lock);
/* Free any now unused endpoint pages */
while (!list_empty(&pages)) {
epp = list_first_entry(
&pages, struct efx_endpoint_page, link);
list_del(&epp->link);
dma_free_coherent(&efx->pci_dev->dev, EFX_PAGE_SIZE,
epp->ptr, epp->addr);
kfree(epp);
}
/* Finally, push the pages */
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = efx->vf + pos;
mutex_lock(&vf->status_lock);
if (vf->status_addr)
__efx_sriov_push_vf_status(vf);
mutex_unlock(&vf->status_lock);
}
}
static void efx_sriov_free_local(struct efx_nic *efx)
{
struct efx_local_addr *local_addr;
struct efx_endpoint_page *epp;
while (!list_empty(&efx->local_addr_list)) {
local_addr = list_first_entry(&efx->local_addr_list,
struct efx_local_addr, link);
list_del(&local_addr->link);
kfree(local_addr);
}
while (!list_empty(&efx->local_page_list)) {
epp = list_first_entry(&efx->local_page_list,
struct efx_endpoint_page, link);
list_del(&epp->link);
dma_free_coherent(&efx->pci_dev->dev, EFX_PAGE_SIZE,
epp->ptr, epp->addr);
kfree(epp);
}
}
static int efx_sriov_vf_alloc(struct efx_nic *efx)
{
unsigned index;
struct efx_vf *vf;
efx->vf = kzalloc(sizeof(struct efx_vf) * efx->vf_count, GFP_KERNEL);
if (!efx->vf)
return -ENOMEM;
for (index = 0; index < efx->vf_count; ++index) {
vf = efx->vf + index;
vf->efx = efx;
vf->index = index;
vf->rx_filter_id = -1;
vf->tx_filter_mode = VF_TX_FILTER_AUTO;
vf->tx_filter_id = -1;
INIT_WORK(&vf->req, efx_sriov_vfdi);
INIT_WORK(&vf->reset_work, efx_sriov_reset_vf_work);
init_waitqueue_head(&vf->flush_waitq);
mutex_init(&vf->status_lock);
mutex_init(&vf->txq_lock);
}
return 0;
}
static void efx_sriov_vfs_fini(struct efx_nic *efx)
{
struct efx_vf *vf;
unsigned int pos;
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = efx->vf + pos;
efx_nic_free_buffer(efx, &vf->buf);
kfree(vf->peer_page_addrs);
vf->peer_page_addrs = NULL;
vf->peer_page_count = 0;
vf->evq0_count = 0;
}
}
static int efx_sriov_vfs_init(struct efx_nic *efx)
{
struct pci_dev *pci_dev = efx->pci_dev;
unsigned index, devfn, sriov, buftbl_base;
u16 offset, stride;
struct efx_vf *vf;
int rc;
sriov = pci_find_ext_capability(pci_dev, PCI_EXT_CAP_ID_SRIOV);
if (!sriov)
return -ENOENT;
pci_read_config_word(pci_dev, sriov + PCI_SRIOV_VF_OFFSET, &offset);
pci_read_config_word(pci_dev, sriov + PCI_SRIOV_VF_STRIDE, &stride);
buftbl_base = efx->vf_buftbl_base;
devfn = pci_dev->devfn + offset;
for (index = 0; index < efx->vf_count; ++index) {
vf = efx->vf + index;
/* Reserve buffer entries */
vf->buftbl_base = buftbl_base;
buftbl_base += EFX_VF_BUFTBL_PER_VI * efx_vf_size(efx);
vf->pci_rid = devfn;
snprintf(vf->pci_name, sizeof(vf->pci_name),
"%04x:%02x:%02x.%d",
pci_domain_nr(pci_dev->bus), pci_dev->bus->number,
PCI_SLOT(devfn), PCI_FUNC(devfn));
rc = efx_nic_alloc_buffer(efx, &vf->buf, EFX_PAGE_SIZE);
if (rc)
goto fail;
devfn += stride;
}
return 0;
fail:
efx_sriov_vfs_fini(efx);
return rc;
}
int efx_sriov_init(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct vfdi_status *vfdi_status;
int rc;
/* Ensure there's room for vf_channel */
BUILD_BUG_ON(EFX_MAX_CHANNELS + 1 >= EFX_VI_BASE);
/* Ensure that VI_BASE is aligned on VI_SCALE */
BUILD_BUG_ON(EFX_VI_BASE & ((1 << EFX_VI_SCALE_MAX) - 1));
if (efx->vf_count == 0)
return 0;
rc = efx_sriov_cmd(efx, true, NULL, NULL);
if (rc)
goto fail_cmd;
rc = efx_nic_alloc_buffer(efx, &efx->vfdi_status, sizeof(*vfdi_status));
if (rc)
goto fail_status;
vfdi_status = efx->vfdi_status.addr;
memset(vfdi_status, 0, sizeof(*vfdi_status));
vfdi_status->version = 1;
vfdi_status->length = sizeof(*vfdi_status);
vfdi_status->max_tx_channels = vf_max_tx_channels;
vfdi_status->vi_scale = efx->vi_scale;
vfdi_status->rss_rxq_count = efx->rss_spread;
vfdi_status->peer_count = 1 + efx->vf_count;
vfdi_status->timer_quantum_ns = efx->timer_quantum_ns;
rc = efx_sriov_vf_alloc(efx);
if (rc)
goto fail_alloc;
mutex_init(&efx->local_lock);
INIT_WORK(&efx->peer_work, efx_sriov_peer_work);
INIT_LIST_HEAD(&efx->local_addr_list);
INIT_LIST_HEAD(&efx->local_page_list);
rc = efx_sriov_vfs_init(efx);
if (rc)
goto fail_vfs;
rtnl_lock();
memcpy(vfdi_status->peers[0].mac_addr,
net_dev->dev_addr, ETH_ALEN);
efx->vf_init_count = efx->vf_count;
rtnl_unlock();
efx_sriov_usrev(efx, true);
/* At this point we must be ready to accept VFDI requests */
rc = pci_enable_sriov(efx->pci_dev, efx->vf_count);
if (rc)
goto fail_pci;
netif_info(efx, probe, net_dev,
"enabled SR-IOV for %d VFs, %d VI per VF\n",
efx->vf_count, efx_vf_size(efx));
return 0;
fail_pci:
efx_sriov_usrev(efx, false);
rtnl_lock();
efx->vf_init_count = 0;
rtnl_unlock();
efx_sriov_vfs_fini(efx);
fail_vfs:
cancel_work_sync(&efx->peer_work);
efx_sriov_free_local(efx);
kfree(efx->vf);
fail_alloc:
efx_nic_free_buffer(efx, &efx->vfdi_status);
fail_status:
efx_sriov_cmd(efx, false, NULL, NULL);
fail_cmd:
return rc;
}
void efx_sriov_fini(struct efx_nic *efx)
{
struct efx_vf *vf;
unsigned int pos;
if (efx->vf_init_count == 0)
return;
/* Disable all interfaces to reconfiguration */
BUG_ON(efx->vfdi_channel->enabled);
efx_sriov_usrev(efx, false);
rtnl_lock();
efx->vf_init_count = 0;
rtnl_unlock();
/* Flush all reconfiguration work */
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = efx->vf + pos;
cancel_work_sync(&vf->req);
cancel_work_sync(&vf->reset_work);
}
cancel_work_sync(&efx->peer_work);
pci_disable_sriov(efx->pci_dev);
/* Tear down back-end state */
efx_sriov_vfs_fini(efx);
efx_sriov_free_local(efx);
kfree(efx->vf);
efx_nic_free_buffer(efx, &efx->vfdi_status);
efx_sriov_cmd(efx, false, NULL, NULL);
}
void efx_sriov_event(struct efx_channel *channel, efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
struct efx_vf *vf;
unsigned qid, seq, type, data;
qid = EFX_QWORD_FIELD(*event, FSF_CZ_USER_QID);
/* USR_EV_REG_VALUE is dword0, so access the VFDI_EV fields directly */
BUILD_BUG_ON(FSF_CZ_USER_EV_REG_VALUE_LBN != 0);
seq = EFX_QWORD_FIELD(*event, VFDI_EV_SEQ);
type = EFX_QWORD_FIELD(*event, VFDI_EV_TYPE);
data = EFX_QWORD_FIELD(*event, VFDI_EV_DATA);
netif_vdbg(efx, hw, efx->net_dev,
"USR_EV event from qid %d seq 0x%x type %d data 0x%x\n",
qid, seq, type, data);
if (map_vi_index(efx, qid, &vf, NULL))
return;
if (vf->busy)
goto error;
if (type == VFDI_EV_TYPE_REQ_WORD0) {
/* Resynchronise */
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->req_seqno = seq + 1;
vf->req_addr = 0;
} else if (seq != (vf->req_seqno++ & 0xff) || type != vf->req_type)
goto error;
switch (vf->req_type) {
case VFDI_EV_TYPE_REQ_WORD0:
case VFDI_EV_TYPE_REQ_WORD1:
case VFDI_EV_TYPE_REQ_WORD2:
vf->req_addr |= (u64)data << (vf->req_type << 4);
++vf->req_type;
return;
case VFDI_EV_TYPE_REQ_WORD3:
vf->req_addr |= (u64)data << 48;
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->busy = true;
queue_work(vfdi_workqueue, &vf->req);
return;
}
error:
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Screaming VFDI request from %s\n",
vf->pci_name);
/* Reset the request and sequence number */
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->req_seqno = seq + 1;
}
void efx_sriov_flr(struct efx_nic *efx, unsigned vf_i)
{
struct efx_vf *vf;
if (vf_i > efx->vf_init_count)
return;
vf = efx->vf + vf_i;
netif_info(efx, hw, efx->net_dev,
"FLR on VF %s\n", vf->pci_name);
vf->status_addr = 0;
efx_vfdi_remove_all_filters(vf);
efx_vfdi_flush_clear(vf);
vf->evq0_count = 0;
}
void efx_sriov_mac_address_changed(struct efx_nic *efx)
{
struct vfdi_status *vfdi_status = efx->vfdi_status.addr;
if (!efx->vf_init_count)
return;
memcpy(vfdi_status->peers[0].mac_addr,
efx->net_dev->dev_addr, ETH_ALEN);
queue_work(vfdi_workqueue, &efx->peer_work);
}
void efx_sriov_tx_flush_done(struct efx_nic *efx, efx_qword_t *event)
{
struct efx_vf *vf;
unsigned queue, qid;
queue = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_SUBDATA);
if (map_vi_index(efx, queue, &vf, &qid))
return;
/* Ignore flush completions triggered by an FLR */
if (!test_bit(qid, vf->txq_mask))
return;
__clear_bit(qid, vf->txq_mask);
--vf->txq_count;
if (efx_vfdi_flush_wake(vf))
wake_up(&vf->flush_waitq);
}
void efx_sriov_rx_flush_done(struct efx_nic *efx, efx_qword_t *event)
{
struct efx_vf *vf;
unsigned ev_failed, queue, qid;
queue = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_RX_DESCQ_ID);
ev_failed = EFX_QWORD_FIELD(*event,
FSF_AZ_DRIVER_EV_RX_FLUSH_FAIL);
if (map_vi_index(efx, queue, &vf, &qid))
return;
if (!test_bit(qid, vf->rxq_mask))
return;
if (ev_failed) {
set_bit(qid, vf->rxq_retry_mask);
atomic_inc(&vf->rxq_retry_count);
} else {
__clear_bit(qid, vf->rxq_mask);
--vf->rxq_count;
}
if (efx_vfdi_flush_wake(vf))
wake_up(&vf->flush_waitq);
}
/* Called from napi. Schedule the reset work item */
void efx_sriov_desc_fetch_err(struct efx_nic *efx, unsigned dmaq)
{
struct efx_vf *vf;
unsigned int rel;
if (map_vi_index(efx, dmaq, &vf, &rel))
return;
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"VF %d DMA Q %d reports descriptor fetch error.\n",
vf->index, rel);
queue_work(vfdi_workqueue, &vf->reset_work);
}
/* Reset all VFs */
void efx_sriov_reset(struct efx_nic *efx)
{
unsigned int vf_i;
struct efx_buffer buf;
struct efx_vf *vf;
ASSERT_RTNL();
if (efx->vf_init_count == 0)
return;
efx_sriov_usrev(efx, true);
(void)efx_sriov_cmd(efx, true, NULL, NULL);
if (efx_nic_alloc_buffer(efx, &buf, EFX_PAGE_SIZE))
return;
for (vf_i = 0; vf_i < efx->vf_init_count; ++vf_i) {
vf = efx->vf + vf_i;
efx_sriov_reset_vf(vf, &buf);
}
efx_nic_free_buffer(efx, &buf);
}
int efx_init_sriov(void)
{
/* A single threaded workqueue is sufficient. efx_sriov_vfdi() and
* efx_sriov_peer_work() spend almost all their time sleeping for
* MCDI to complete anyway
*/
vfdi_workqueue = create_singlethread_workqueue("sfc_vfdi");
if (!vfdi_workqueue)
return -ENOMEM;
return 0;
}
void efx_fini_sriov(void)
{
destroy_workqueue(vfdi_workqueue);
}
int efx_sriov_set_vf_mac(struct net_device *net_dev, int vf_i, u8 *mac)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_vf *vf;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = efx->vf + vf_i;
mutex_lock(&vf->status_lock);
memcpy(vf->addr.mac_addr, mac, ETH_ALEN);
__efx_sriov_update_vf_addr(vf);
mutex_unlock(&vf->status_lock);
return 0;
}
int efx_sriov_set_vf_vlan(struct net_device *net_dev, int vf_i,
u16 vlan, u8 qos)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_vf *vf;
u16 tci;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = efx->vf + vf_i;
mutex_lock(&vf->status_lock);
tci = (vlan & VLAN_VID_MASK) | ((qos & 0x7) << VLAN_PRIO_SHIFT);
vf->addr.tci = htons(tci);
__efx_sriov_update_vf_addr(vf);
mutex_unlock(&vf->status_lock);
return 0;
}
int efx_sriov_set_vf_spoofchk(struct net_device *net_dev, int vf_i,
bool spoofchk)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_vf *vf;
int rc;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = efx->vf + vf_i;
mutex_lock(&vf->txq_lock);
if (vf->txq_count == 0) {
vf->tx_filter_mode =
spoofchk ? VF_TX_FILTER_ON : VF_TX_FILTER_OFF;
rc = 0;
} else {
/* This cannot be changed while TX queues are running */
rc = -EBUSY;
}
mutex_unlock(&vf->txq_lock);
return rc;
}
int efx_sriov_get_vf_config(struct net_device *net_dev, int vf_i,
struct ifla_vf_info *ivi)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_vf *vf;
u16 tci;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = efx->vf + vf_i;
ivi->vf = vf_i;
memcpy(ivi->mac, vf->addr.mac_addr, ETH_ALEN);
ivi->tx_rate = 0;
tci = ntohs(vf->addr.tci);
ivi->vlan = tci & VLAN_VID_MASK;
ivi->qos = (tci >> VLAN_PRIO_SHIFT) & 0x7;
ivi->spoofchk = vf->tx_filter_mode == VF_TX_FILTER_ON;
return 0;
}
| gpl-2.0 |
FEDEVEL/imx6rex-linux-3.10.17 | drivers/net/ethernet/sfc/siena_sriov.c | 2309 | 45904 | /****************************************************************************
* Driver for Solarflare Solarstorm network controllers and boards
* Copyright 2010-2011 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/pci.h>
#include <linux/module.h>
#include "net_driver.h"
#include "efx.h"
#include "nic.h"
#include "io.h"
#include "mcdi.h"
#include "filter.h"
#include "mcdi_pcol.h"
#include "regs.h"
#include "vfdi.h"
/* Number of longs required to track all the VIs in a VF */
#define VI_MASK_LENGTH BITS_TO_LONGS(1 << EFX_VI_SCALE_MAX)
/* Maximum number of RX queues supported */
#define VF_MAX_RX_QUEUES 63
/**
* enum efx_vf_tx_filter_mode - TX MAC filtering behaviour
* @VF_TX_FILTER_OFF: Disabled
* @VF_TX_FILTER_AUTO: Enabled if MAC address assigned to VF and only
* 2 TX queues allowed per VF.
* @VF_TX_FILTER_ON: Enabled
*/
enum efx_vf_tx_filter_mode {
VF_TX_FILTER_OFF,
VF_TX_FILTER_AUTO,
VF_TX_FILTER_ON,
};
/**
* struct efx_vf - Back-end resource and protocol state for a PCI VF
* @efx: The Efx NIC owning this VF
* @pci_rid: The PCI requester ID for this VF
* @pci_name: The PCI name (formatted address) of this VF
* @index: Index of VF within its port and PF.
* @req: VFDI incoming request work item. Incoming USR_EV events are received
* by the NAPI handler, but must be handled by executing MCDI requests
* inside a work item.
* @req_addr: VFDI incoming request DMA address (in VF's PCI address space).
* @req_type: Expected next incoming (from VF) %VFDI_EV_TYPE member.
* @req_seqno: Expected next incoming (from VF) %VFDI_EV_SEQ member.
* @msg_seqno: Next %VFDI_EV_SEQ member to reply to VF. Protected by
* @status_lock
* @busy: VFDI request queued to be processed or being processed. Receiving
* a VFDI request when @busy is set is an error condition.
* @buf: Incoming VFDI requests are DMA from the VF into this buffer.
* @buftbl_base: Buffer table entries for this VF start at this index.
* @rx_filtering: Receive filtering has been requested by the VF driver.
* @rx_filter_flags: The flags sent in the %VFDI_OP_INSERT_FILTER request.
* @rx_filter_qid: VF relative qid for RX filter requested by VF.
* @rx_filter_id: Receive MAC filter ID. Only one filter per VF is supported.
* @tx_filter_mode: Transmit MAC filtering mode.
* @tx_filter_id: Transmit MAC filter ID.
* @addr: The MAC address and outer vlan tag of the VF.
* @status_addr: VF DMA address of page for &struct vfdi_status updates.
* @status_lock: Mutex protecting @msg_seqno, @status_addr, @addr,
* @peer_page_addrs and @peer_page_count from simultaneous
* updates by the VM and consumption by
* efx_sriov_update_vf_addr()
* @peer_page_addrs: Pointer to an array of guest pages for local addresses.
* @peer_page_count: Number of entries in @peer_page_count.
* @evq0_addrs: Array of guest pages backing evq0.
* @evq0_count: Number of entries in @evq0_addrs.
* @flush_waitq: wait queue used by %VFDI_OP_FINI_ALL_QUEUES handler
* to wait for flush completions.
* @txq_lock: Mutex for TX queue allocation.
* @txq_mask: Mask of initialized transmit queues.
* @txq_count: Number of initialized transmit queues.
* @rxq_mask: Mask of initialized receive queues.
* @rxq_count: Number of initialized receive queues.
* @rxq_retry_mask: Mask or receive queues that need to be flushed again
* due to flush failure.
* @rxq_retry_count: Number of receive queues in @rxq_retry_mask.
* @reset_work: Work item to schedule a VF reset.
*/
struct efx_vf {
struct efx_nic *efx;
unsigned int pci_rid;
char pci_name[13]; /* dddd:bb:dd.f */
unsigned int index;
struct work_struct req;
u64 req_addr;
int req_type;
unsigned req_seqno;
unsigned msg_seqno;
bool busy;
struct efx_buffer buf;
unsigned buftbl_base;
bool rx_filtering;
enum efx_filter_flags rx_filter_flags;
unsigned rx_filter_qid;
int rx_filter_id;
enum efx_vf_tx_filter_mode tx_filter_mode;
int tx_filter_id;
struct vfdi_endpoint addr;
u64 status_addr;
struct mutex status_lock;
u64 *peer_page_addrs;
unsigned peer_page_count;
u64 evq0_addrs[EFX_MAX_VF_EVQ_SIZE * sizeof(efx_qword_t) /
EFX_BUF_SIZE];
unsigned evq0_count;
wait_queue_head_t flush_waitq;
struct mutex txq_lock;
unsigned long txq_mask[VI_MASK_LENGTH];
unsigned txq_count;
unsigned long rxq_mask[VI_MASK_LENGTH];
unsigned rxq_count;
unsigned long rxq_retry_mask[VI_MASK_LENGTH];
atomic_t rxq_retry_count;
struct work_struct reset_work;
};
struct efx_memcpy_req {
unsigned int from_rid;
void *from_buf;
u64 from_addr;
unsigned int to_rid;
u64 to_addr;
unsigned length;
};
/**
* struct efx_local_addr - A MAC address on the vswitch without a VF.
*
* Siena does not have a switch, so VFs can't transmit data to each
* other. Instead the VFs must be made aware of the local addresses
* on the vswitch, so that they can arrange for an alternative
* software datapath to be used.
*
* @link: List head for insertion into efx->local_addr_list.
* @addr: Ethernet address
*/
struct efx_local_addr {
struct list_head link;
u8 addr[ETH_ALEN];
};
/**
* struct efx_endpoint_page - Page of vfdi_endpoint structures
*
* @link: List head for insertion into efx->local_page_list.
* @ptr: Pointer to page.
* @addr: DMA address of page.
*/
struct efx_endpoint_page {
struct list_head link;
void *ptr;
dma_addr_t addr;
};
/* Buffer table entries are reserved txq0,rxq0,evq0,txq1,rxq1,evq1 */
#define EFX_BUFTBL_TXQ_BASE(_vf, _qid) \
((_vf)->buftbl_base + EFX_VF_BUFTBL_PER_VI * (_qid))
#define EFX_BUFTBL_RXQ_BASE(_vf, _qid) \
(EFX_BUFTBL_TXQ_BASE(_vf, _qid) + \
(EFX_MAX_DMAQ_SIZE * sizeof(efx_qword_t) / EFX_BUF_SIZE))
#define EFX_BUFTBL_EVQ_BASE(_vf, _qid) \
(EFX_BUFTBL_TXQ_BASE(_vf, _qid) + \
(2 * EFX_MAX_DMAQ_SIZE * sizeof(efx_qword_t) / EFX_BUF_SIZE))
#define EFX_FIELD_MASK(_field) \
((1 << _field ## _WIDTH) - 1)
/* VFs can only use this many transmit channels */
static unsigned int vf_max_tx_channels = 2;
module_param(vf_max_tx_channels, uint, 0444);
MODULE_PARM_DESC(vf_max_tx_channels,
"Limit the number of TX channels VFs can use");
static int max_vfs = -1;
module_param(max_vfs, int, 0444);
MODULE_PARM_DESC(max_vfs,
"Reduce the number of VFs initialized by the driver");
/* Workqueue used by VFDI communication. We can't use the global
* workqueue because it may be running the VF driver's probe()
* routine, which will be blocked there waiting for a VFDI response.
*/
static struct workqueue_struct *vfdi_workqueue;
static unsigned abs_index(struct efx_vf *vf, unsigned index)
{
return EFX_VI_BASE + vf->index * efx_vf_size(vf->efx) + index;
}
static int efx_sriov_cmd(struct efx_nic *efx, bool enable,
unsigned *vi_scale_out, unsigned *vf_total_out)
{
u8 inbuf[MC_CMD_SRIOV_IN_LEN];
u8 outbuf[MC_CMD_SRIOV_OUT_LEN];
unsigned vi_scale, vf_total;
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, SRIOV_IN_ENABLE, enable ? 1 : 0);
MCDI_SET_DWORD(inbuf, SRIOV_IN_VI_BASE, EFX_VI_BASE);
MCDI_SET_DWORD(inbuf, SRIOV_IN_VF_COUNT, efx->vf_count);
rc = efx_mcdi_rpc(efx, MC_CMD_SRIOV, inbuf, MC_CMD_SRIOV_IN_LEN,
outbuf, MC_CMD_SRIOV_OUT_LEN, &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_SRIOV_OUT_LEN)
return -EIO;
vf_total = MCDI_DWORD(outbuf, SRIOV_OUT_VF_TOTAL);
vi_scale = MCDI_DWORD(outbuf, SRIOV_OUT_VI_SCALE);
if (vi_scale > EFX_VI_SCALE_MAX)
return -EOPNOTSUPP;
if (vi_scale_out)
*vi_scale_out = vi_scale;
if (vf_total_out)
*vf_total_out = vf_total;
return 0;
}
static void efx_sriov_usrev(struct efx_nic *efx, bool enabled)
{
efx_oword_t reg;
EFX_POPULATE_OWORD_2(reg,
FRF_CZ_USREV_DIS, enabled ? 0 : 1,
FRF_CZ_DFLT_EVQ, efx->vfdi_channel->channel);
efx_writeo(efx, ®, FR_CZ_USR_EV_CFG);
}
static int efx_sriov_memcpy(struct efx_nic *efx, struct efx_memcpy_req *req,
unsigned int count)
{
u8 *inbuf, *record;
unsigned int used;
u32 from_rid, from_hi, from_lo;
int rc;
mb(); /* Finish writing source/reading dest before DMA starts */
used = MC_CMD_MEMCPY_IN_LEN(count);
if (WARN_ON(used > MCDI_CTL_SDU_LEN_MAX))
return -ENOBUFS;
/* Allocate room for the largest request */
inbuf = kzalloc(MCDI_CTL_SDU_LEN_MAX, GFP_KERNEL);
if (inbuf == NULL)
return -ENOMEM;
record = inbuf;
MCDI_SET_DWORD(record, MEMCPY_IN_RECORD, count);
while (count-- > 0) {
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_TO_RID,
req->to_rid);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_TO_ADDR_LO,
(u32)req->to_addr);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_TO_ADDR_HI,
(u32)(req->to_addr >> 32));
if (req->from_buf == NULL) {
from_rid = req->from_rid;
from_lo = (u32)req->from_addr;
from_hi = (u32)(req->from_addr >> 32);
} else {
if (WARN_ON(used + req->length > MCDI_CTL_SDU_LEN_MAX)) {
rc = -ENOBUFS;
goto out;
}
from_rid = MC_CMD_MEMCPY_RECORD_TYPEDEF_RID_INLINE;
from_lo = used;
from_hi = 0;
memcpy(inbuf + used, req->from_buf, req->length);
used += req->length;
}
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_FROM_RID, from_rid);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_FROM_ADDR_LO,
from_lo);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_FROM_ADDR_HI,
from_hi);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_LENGTH,
req->length);
++req;
record += MC_CMD_MEMCPY_IN_RECORD_LEN;
}
rc = efx_mcdi_rpc(efx, MC_CMD_MEMCPY, inbuf, used, NULL, 0, NULL);
out:
kfree(inbuf);
mb(); /* Don't write source/read dest before DMA is complete */
return rc;
}
/* The TX filter is entirely controlled by this driver, and is modified
* underneath the feet of the VF
*/
static void efx_sriov_reset_tx_filter(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct efx_filter_spec filter;
u16 vlan;
int rc;
if (vf->tx_filter_id != -1) {
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
vf->tx_filter_id);
netif_dbg(efx, hw, efx->net_dev, "Removed vf %s tx filter %d\n",
vf->pci_name, vf->tx_filter_id);
vf->tx_filter_id = -1;
}
if (is_zero_ether_addr(vf->addr.mac_addr))
return;
/* Turn on TX filtering automatically if not explicitly
* enabled or disabled.
*/
if (vf->tx_filter_mode == VF_TX_FILTER_AUTO && vf_max_tx_channels <= 2)
vf->tx_filter_mode = VF_TX_FILTER_ON;
vlan = ntohs(vf->addr.tci) & VLAN_VID_MASK;
efx_filter_init_tx(&filter, abs_index(vf, 0));
rc = efx_filter_set_eth_local(&filter,
vlan ? vlan : EFX_FILTER_VID_UNSPEC,
vf->addr.mac_addr);
BUG_ON(rc);
rc = efx_filter_insert_filter(efx, &filter, true);
if (rc < 0) {
netif_warn(efx, hw, efx->net_dev,
"Unable to migrate tx filter for vf %s\n",
vf->pci_name);
} else {
netif_dbg(efx, hw, efx->net_dev, "Inserted vf %s tx filter %d\n",
vf->pci_name, rc);
vf->tx_filter_id = rc;
}
}
/* The RX filter is managed here on behalf of the VF driver */
static void efx_sriov_reset_rx_filter(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct efx_filter_spec filter;
u16 vlan;
int rc;
if (vf->rx_filter_id != -1) {
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
vf->rx_filter_id);
netif_dbg(efx, hw, efx->net_dev, "Removed vf %s rx filter %d\n",
vf->pci_name, vf->rx_filter_id);
vf->rx_filter_id = -1;
}
if (!vf->rx_filtering || is_zero_ether_addr(vf->addr.mac_addr))
return;
vlan = ntohs(vf->addr.tci) & VLAN_VID_MASK;
efx_filter_init_rx(&filter, EFX_FILTER_PRI_REQUIRED,
vf->rx_filter_flags,
abs_index(vf, vf->rx_filter_qid));
rc = efx_filter_set_eth_local(&filter,
vlan ? vlan : EFX_FILTER_VID_UNSPEC,
vf->addr.mac_addr);
BUG_ON(rc);
rc = efx_filter_insert_filter(efx, &filter, true);
if (rc < 0) {
netif_warn(efx, hw, efx->net_dev,
"Unable to insert rx filter for vf %s\n",
vf->pci_name);
} else {
netif_dbg(efx, hw, efx->net_dev, "Inserted vf %s rx filter %d\n",
vf->pci_name, rc);
vf->rx_filter_id = rc;
}
}
static void __efx_sriov_update_vf_addr(struct efx_vf *vf)
{
efx_sriov_reset_tx_filter(vf);
efx_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &vf->efx->peer_work);
}
/* Push the peer list to this VF. The caller must hold status_lock to interlock
* with VFDI requests, and they must be serialised against manipulation of
* local_page_list, either by acquiring local_lock or by running from
* efx_sriov_peer_work()
*/
static void __efx_sriov_push_vf_status(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_status *status = efx->vfdi_status.addr;
struct efx_memcpy_req copy[4];
struct efx_endpoint_page *epp;
unsigned int pos, count;
unsigned data_offset;
efx_qword_t event;
WARN_ON(!mutex_is_locked(&vf->status_lock));
WARN_ON(!vf->status_addr);
status->local = vf->addr;
status->generation_end = ++status->generation_start;
memset(copy, '\0', sizeof(copy));
/* Write generation_start */
copy[0].from_buf = &status->generation_start;
copy[0].to_rid = vf->pci_rid;
copy[0].to_addr = vf->status_addr + offsetof(struct vfdi_status,
generation_start);
copy[0].length = sizeof(status->generation_start);
/* DMA the rest of the structure (excluding the generations). This
* assumes that the non-generation portion of vfdi_status is in
* one chunk starting at the version member.
*/
data_offset = offsetof(struct vfdi_status, version);
copy[1].from_rid = efx->pci_dev->devfn;
copy[1].from_addr = efx->vfdi_status.dma_addr + data_offset;
copy[1].to_rid = vf->pci_rid;
copy[1].to_addr = vf->status_addr + data_offset;
copy[1].length = status->length - data_offset;
/* Copy the peer pages */
pos = 2;
count = 0;
list_for_each_entry(epp, &efx->local_page_list, link) {
if (count == vf->peer_page_count) {
/* The VF driver will know they need to provide more
* pages because peer_addr_count is too large.
*/
break;
}
copy[pos].from_buf = NULL;
copy[pos].from_rid = efx->pci_dev->devfn;
copy[pos].from_addr = epp->addr;
copy[pos].to_rid = vf->pci_rid;
copy[pos].to_addr = vf->peer_page_addrs[count];
copy[pos].length = EFX_PAGE_SIZE;
if (++pos == ARRAY_SIZE(copy)) {
efx_sriov_memcpy(efx, copy, ARRAY_SIZE(copy));
pos = 0;
}
++count;
}
/* Write generation_end */
copy[pos].from_buf = &status->generation_end;
copy[pos].to_rid = vf->pci_rid;
copy[pos].to_addr = vf->status_addr + offsetof(struct vfdi_status,
generation_end);
copy[pos].length = sizeof(status->generation_end);
efx_sriov_memcpy(efx, copy, pos + 1);
/* Notify the guest */
EFX_POPULATE_QWORD_3(event,
FSF_AZ_EV_CODE, FSE_CZ_EV_CODE_USER_EV,
VFDI_EV_SEQ, (vf->msg_seqno & 0xff),
VFDI_EV_TYPE, VFDI_EV_TYPE_STATUS);
++vf->msg_seqno;
efx_generate_event(efx, EFX_VI_BASE + vf->index * efx_vf_size(efx),
&event);
}
static void efx_sriov_bufs(struct efx_nic *efx, unsigned offset,
u64 *addr, unsigned count)
{
efx_qword_t buf;
unsigned pos;
for (pos = 0; pos < count; ++pos) {
EFX_POPULATE_QWORD_3(buf,
FRF_AZ_BUF_ADR_REGION, 0,
FRF_AZ_BUF_ADR_FBUF,
addr ? addr[pos] >> 12 : 0,
FRF_AZ_BUF_OWNER_ID_FBUF, 0);
efx_sram_writeq(efx, efx->membase + FR_BZ_BUF_FULL_TBL,
&buf, offset + pos);
}
}
static bool bad_vf_index(struct efx_nic *efx, unsigned index)
{
return index >= efx_vf_size(efx);
}
static bool bad_buf_count(unsigned buf_count, unsigned max_entry_count)
{
unsigned max_buf_count = max_entry_count *
sizeof(efx_qword_t) / EFX_BUF_SIZE;
return ((buf_count & (buf_count - 1)) || buf_count > max_buf_count);
}
/* Check that VI specified by per-port index belongs to a VF.
* Optionally set VF index and VI index within the VF.
*/
static bool map_vi_index(struct efx_nic *efx, unsigned abs_index,
struct efx_vf **vf_out, unsigned *rel_index_out)
{
unsigned vf_i;
if (abs_index < EFX_VI_BASE)
return true;
vf_i = (abs_index - EFX_VI_BASE) / efx_vf_size(efx);
if (vf_i >= efx->vf_init_count)
return true;
if (vf_out)
*vf_out = efx->vf + vf_i;
if (rel_index_out)
*rel_index_out = abs_index % efx_vf_size(efx);
return false;
}
static int efx_vfdi_init_evq(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_evq = req->u.init_evq.index;
unsigned buf_count = req->u.init_evq.buf_count;
unsigned abs_evq = abs_index(vf, vf_evq);
unsigned buftbl = EFX_BUFTBL_EVQ_BASE(vf, vf_evq);
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) ||
bad_buf_count(buf_count, EFX_MAX_VF_EVQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_EVQ from %s: evq %d bufs %d\n",
vf->pci_name, vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
efx_sriov_bufs(efx, buftbl, req->u.init_evq.addr, buf_count);
EFX_POPULATE_OWORD_3(reg,
FRF_CZ_TIMER_Q_EN, 1,
FRF_CZ_HOST_NOTIFY_MODE, 0,
FRF_CZ_TIMER_MODE, FFE_CZ_TIMER_MODE_DIS);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL, abs_evq);
EFX_POPULATE_OWORD_3(reg,
FRF_AZ_EVQ_EN, 1,
FRF_AZ_EVQ_SIZE, __ffs(buf_count),
FRF_AZ_EVQ_BUF_BASE_ID, buftbl);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL, abs_evq);
if (vf_evq == 0) {
memcpy(vf->evq0_addrs, req->u.init_evq.addr,
buf_count * sizeof(u64));
vf->evq0_count = buf_count;
}
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_init_rxq(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_rxq = req->u.init_rxq.index;
unsigned vf_evq = req->u.init_rxq.evq;
unsigned buf_count = req->u.init_rxq.buf_count;
unsigned buftbl = EFX_BUFTBL_RXQ_BASE(vf, vf_rxq);
unsigned label;
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) || bad_vf_index(efx, vf_rxq) ||
vf_rxq >= VF_MAX_RX_QUEUES ||
bad_buf_count(buf_count, EFX_MAX_DMAQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_RXQ from %s: rxq %d evq %d "
"buf_count %d\n", vf->pci_name, vf_rxq,
vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
if (__test_and_set_bit(req->u.init_rxq.index, vf->rxq_mask))
++vf->rxq_count;
efx_sriov_bufs(efx, buftbl, req->u.init_rxq.addr, buf_count);
label = req->u.init_rxq.label & EFX_FIELD_MASK(FRF_AZ_RX_DESCQ_LABEL);
EFX_POPULATE_OWORD_6(reg,
FRF_AZ_RX_DESCQ_BUF_BASE_ID, buftbl,
FRF_AZ_RX_DESCQ_EVQ_ID, abs_index(vf, vf_evq),
FRF_AZ_RX_DESCQ_LABEL, label,
FRF_AZ_RX_DESCQ_SIZE, __ffs(buf_count),
FRF_AZ_RX_DESCQ_JUMBO,
!!(req->u.init_rxq.flags &
VFDI_RXQ_FLAG_SCATTER_EN),
FRF_AZ_RX_DESCQ_EN, 1);
efx_writeo_table(efx, ®, FR_BZ_RX_DESC_PTR_TBL,
abs_index(vf, vf_rxq));
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_init_txq(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_txq = req->u.init_txq.index;
unsigned vf_evq = req->u.init_txq.evq;
unsigned buf_count = req->u.init_txq.buf_count;
unsigned buftbl = EFX_BUFTBL_TXQ_BASE(vf, vf_txq);
unsigned label, eth_filt_en;
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) || bad_vf_index(efx, vf_txq) ||
vf_txq >= vf_max_tx_channels ||
bad_buf_count(buf_count, EFX_MAX_DMAQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_TXQ from %s: txq %d evq %d "
"buf_count %d\n", vf->pci_name, vf_txq,
vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
mutex_lock(&vf->txq_lock);
if (__test_and_set_bit(req->u.init_txq.index, vf->txq_mask))
++vf->txq_count;
mutex_unlock(&vf->txq_lock);
efx_sriov_bufs(efx, buftbl, req->u.init_txq.addr, buf_count);
eth_filt_en = vf->tx_filter_mode == VF_TX_FILTER_ON;
label = req->u.init_txq.label & EFX_FIELD_MASK(FRF_AZ_TX_DESCQ_LABEL);
EFX_POPULATE_OWORD_8(reg,
FRF_CZ_TX_DPT_Q_MASK_WIDTH, min(efx->vi_scale, 1U),
FRF_CZ_TX_DPT_ETH_FILT_EN, eth_filt_en,
FRF_AZ_TX_DESCQ_EN, 1,
FRF_AZ_TX_DESCQ_BUF_BASE_ID, buftbl,
FRF_AZ_TX_DESCQ_EVQ_ID, abs_index(vf, vf_evq),
FRF_AZ_TX_DESCQ_LABEL, label,
FRF_AZ_TX_DESCQ_SIZE, __ffs(buf_count),
FRF_BZ_TX_NON_IP_DROP_DIS, 1);
efx_writeo_table(efx, ®, FR_BZ_TX_DESC_PTR_TBL,
abs_index(vf, vf_txq));
return VFDI_RC_SUCCESS;
}
/* Returns true when efx_vfdi_fini_all_queues should wake */
static bool efx_vfdi_flush_wake(struct efx_vf *vf)
{
/* Ensure that all updates are visible to efx_vfdi_fini_all_queues() */
smp_mb();
return (!vf->txq_count && !vf->rxq_count) ||
atomic_read(&vf->rxq_retry_count);
}
static void efx_vfdi_flush_clear(struct efx_vf *vf)
{
memset(vf->txq_mask, 0, sizeof(vf->txq_mask));
vf->txq_count = 0;
memset(vf->rxq_mask, 0, sizeof(vf->rxq_mask));
vf->rxq_count = 0;
memset(vf->rxq_retry_mask, 0, sizeof(vf->rxq_retry_mask));
atomic_set(&vf->rxq_retry_count, 0);
}
static int efx_vfdi_fini_all_queues(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
efx_oword_t reg;
unsigned count = efx_vf_size(efx);
unsigned vf_offset = EFX_VI_BASE + vf->index * efx_vf_size(efx);
unsigned timeout = HZ;
unsigned index, rxqs_count;
__le32 *rxqs;
int rc;
BUILD_BUG_ON(VF_MAX_RX_QUEUES >
MC_CMD_FLUSH_RX_QUEUES_IN_QID_OFST_MAXNUM);
rxqs = kmalloc(count * sizeof(*rxqs), GFP_KERNEL);
if (rxqs == NULL)
return VFDI_RC_ENOMEM;
rtnl_lock();
siena_prepare_flush(efx);
rtnl_unlock();
/* Flush all the initialized queues */
rxqs_count = 0;
for (index = 0; index < count; ++index) {
if (test_bit(index, vf->txq_mask)) {
EFX_POPULATE_OWORD_2(reg,
FRF_AZ_TX_FLUSH_DESCQ_CMD, 1,
FRF_AZ_TX_FLUSH_DESCQ,
vf_offset + index);
efx_writeo(efx, ®, FR_AZ_TX_FLUSH_DESCQ);
}
if (test_bit(index, vf->rxq_mask))
rxqs[rxqs_count++] = cpu_to_le32(vf_offset + index);
}
atomic_set(&vf->rxq_retry_count, 0);
while (timeout && (vf->rxq_count || vf->txq_count)) {
rc = efx_mcdi_rpc(efx, MC_CMD_FLUSH_RX_QUEUES, (u8 *)rxqs,
rxqs_count * sizeof(*rxqs), NULL, 0, NULL);
WARN_ON(rc < 0);
timeout = wait_event_timeout(vf->flush_waitq,
efx_vfdi_flush_wake(vf),
timeout);
rxqs_count = 0;
for (index = 0; index < count; ++index) {
if (test_and_clear_bit(index, vf->rxq_retry_mask)) {
atomic_dec(&vf->rxq_retry_count);
rxqs[rxqs_count++] =
cpu_to_le32(vf_offset + index);
}
}
}
rtnl_lock();
siena_finish_flush(efx);
rtnl_unlock();
/* Irrespective of success/failure, fini the queues */
EFX_ZERO_OWORD(reg);
for (index = 0; index < count; ++index) {
efx_writeo_table(efx, ®, FR_BZ_RX_DESC_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_TX_DESC_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL,
vf_offset + index);
}
efx_sriov_bufs(efx, vf->buftbl_base, NULL,
EFX_VF_BUFTBL_PER_VI * efx_vf_size(efx));
kfree(rxqs);
efx_vfdi_flush_clear(vf);
vf->evq0_count = 0;
return timeout ? 0 : VFDI_RC_ETIMEDOUT;
}
static int efx_vfdi_insert_filter(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_rxq = req->u.mac_filter.rxq;
unsigned flags;
if (bad_vf_index(efx, vf_rxq) || vf->rx_filtering) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INSERT_FILTER from %s: rxq %d "
"flags 0x%x\n", vf->pci_name, vf_rxq,
req->u.mac_filter.flags);
return VFDI_RC_EINVAL;
}
flags = 0;
if (req->u.mac_filter.flags & VFDI_MAC_FILTER_FLAG_RSS)
flags |= EFX_FILTER_FLAG_RX_RSS;
if (req->u.mac_filter.flags & VFDI_MAC_FILTER_FLAG_SCATTER)
flags |= EFX_FILTER_FLAG_RX_SCATTER;
vf->rx_filter_flags = flags;
vf->rx_filter_qid = vf_rxq;
vf->rx_filtering = true;
efx_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &efx->peer_work);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_remove_all_filters(struct efx_vf *vf)
{
vf->rx_filtering = false;
efx_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &vf->efx->peer_work);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_set_status_page(struct efx_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
u64 page_count = req->u.set_status_page.peer_page_count;
u64 max_page_count =
(EFX_PAGE_SIZE -
offsetof(struct vfdi_req, u.set_status_page.peer_page_addr[0]))
/ sizeof(req->u.set_status_page.peer_page_addr[0]);
if (!req->u.set_status_page.dma_addr || page_count > max_page_count) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid SET_STATUS_PAGE from %s\n",
vf->pci_name);
return VFDI_RC_EINVAL;
}
mutex_lock(&efx->local_lock);
mutex_lock(&vf->status_lock);
vf->status_addr = req->u.set_status_page.dma_addr;
kfree(vf->peer_page_addrs);
vf->peer_page_addrs = NULL;
vf->peer_page_count = 0;
if (page_count) {
vf->peer_page_addrs = kcalloc(page_count, sizeof(u64),
GFP_KERNEL);
if (vf->peer_page_addrs) {
memcpy(vf->peer_page_addrs,
req->u.set_status_page.peer_page_addr,
page_count * sizeof(u64));
vf->peer_page_count = page_count;
}
}
__efx_sriov_push_vf_status(vf);
mutex_unlock(&vf->status_lock);
mutex_unlock(&efx->local_lock);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_clear_status_page(struct efx_vf *vf)
{
mutex_lock(&vf->status_lock);
vf->status_addr = 0;
mutex_unlock(&vf->status_lock);
return VFDI_RC_SUCCESS;
}
typedef int (*efx_vfdi_op_t)(struct efx_vf *vf);
static const efx_vfdi_op_t vfdi_ops[VFDI_OP_LIMIT] = {
[VFDI_OP_INIT_EVQ] = efx_vfdi_init_evq,
[VFDI_OP_INIT_TXQ] = efx_vfdi_init_txq,
[VFDI_OP_INIT_RXQ] = efx_vfdi_init_rxq,
[VFDI_OP_FINI_ALL_QUEUES] = efx_vfdi_fini_all_queues,
[VFDI_OP_INSERT_FILTER] = efx_vfdi_insert_filter,
[VFDI_OP_REMOVE_ALL_FILTERS] = efx_vfdi_remove_all_filters,
[VFDI_OP_SET_STATUS_PAGE] = efx_vfdi_set_status_page,
[VFDI_OP_CLEAR_STATUS_PAGE] = efx_vfdi_clear_status_page,
};
static void efx_sriov_vfdi(struct work_struct *work)
{
struct efx_vf *vf = container_of(work, struct efx_vf, req);
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
struct efx_memcpy_req copy[2];
int rc;
/* Copy this page into the local address space */
memset(copy, '\0', sizeof(copy));
copy[0].from_rid = vf->pci_rid;
copy[0].from_addr = vf->req_addr;
copy[0].to_rid = efx->pci_dev->devfn;
copy[0].to_addr = vf->buf.dma_addr;
copy[0].length = EFX_PAGE_SIZE;
rc = efx_sriov_memcpy(efx, copy, 1);
if (rc) {
/* If we can't get the request, we can't reply to the caller */
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Unable to fetch VFDI request from %s rc %d\n",
vf->pci_name, -rc);
vf->busy = false;
return;
}
if (req->op < VFDI_OP_LIMIT && vfdi_ops[req->op] != NULL) {
rc = vfdi_ops[req->op](vf);
if (rc == 0) {
netif_dbg(efx, hw, efx->net_dev,
"vfdi request %d from %s ok\n",
req->op, vf->pci_name);
}
} else {
netif_dbg(efx, hw, efx->net_dev,
"ERROR: Unrecognised request %d from VF %s addr "
"%llx\n", req->op, vf->pci_name,
(unsigned long long)vf->req_addr);
rc = VFDI_RC_EOPNOTSUPP;
}
/* Allow subsequent VF requests */
vf->busy = false;
smp_wmb();
/* Respond to the request */
req->rc = rc;
req->op = VFDI_OP_RESPONSE;
memset(copy, '\0', sizeof(copy));
copy[0].from_buf = &req->rc;
copy[0].to_rid = vf->pci_rid;
copy[0].to_addr = vf->req_addr + offsetof(struct vfdi_req, rc);
copy[0].length = sizeof(req->rc);
copy[1].from_buf = &req->op;
copy[1].to_rid = vf->pci_rid;
copy[1].to_addr = vf->req_addr + offsetof(struct vfdi_req, op);
copy[1].length = sizeof(req->op);
(void) efx_sriov_memcpy(efx, copy, ARRAY_SIZE(copy));
}
/* After a reset the event queues inside the guests no longer exist. Fill the
* event ring in guest memory with VFDI reset events, then (re-initialise) the
* event queue to raise an interrupt. The guest driver will then recover.
*/
static void efx_sriov_reset_vf(struct efx_vf *vf, struct efx_buffer *buffer)
{
struct efx_nic *efx = vf->efx;
struct efx_memcpy_req copy_req[4];
efx_qword_t event;
unsigned int pos, count, k, buftbl, abs_evq;
efx_oword_t reg;
efx_dword_t ptr;
int rc;
BUG_ON(buffer->len != EFX_PAGE_SIZE);
if (!vf->evq0_count)
return;
BUG_ON(vf->evq0_count & (vf->evq0_count - 1));
mutex_lock(&vf->status_lock);
EFX_POPULATE_QWORD_3(event,
FSF_AZ_EV_CODE, FSE_CZ_EV_CODE_USER_EV,
VFDI_EV_SEQ, vf->msg_seqno,
VFDI_EV_TYPE, VFDI_EV_TYPE_RESET);
vf->msg_seqno++;
for (pos = 0; pos < EFX_PAGE_SIZE; pos += sizeof(event))
memcpy(buffer->addr + pos, &event, sizeof(event));
for (pos = 0; pos < vf->evq0_count; pos += count) {
count = min_t(unsigned, vf->evq0_count - pos,
ARRAY_SIZE(copy_req));
for (k = 0; k < count; k++) {
copy_req[k].from_buf = NULL;
copy_req[k].from_rid = efx->pci_dev->devfn;
copy_req[k].from_addr = buffer->dma_addr;
copy_req[k].to_rid = vf->pci_rid;
copy_req[k].to_addr = vf->evq0_addrs[pos + k];
copy_req[k].length = EFX_PAGE_SIZE;
}
rc = efx_sriov_memcpy(efx, copy_req, count);
if (rc) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Unable to notify %s of reset"
": %d\n", vf->pci_name, -rc);
break;
}
}
/* Reinitialise, arm and trigger evq0 */
abs_evq = abs_index(vf, 0);
buftbl = EFX_BUFTBL_EVQ_BASE(vf, 0);
efx_sriov_bufs(efx, buftbl, vf->evq0_addrs, vf->evq0_count);
EFX_POPULATE_OWORD_3(reg,
FRF_CZ_TIMER_Q_EN, 1,
FRF_CZ_HOST_NOTIFY_MODE, 0,
FRF_CZ_TIMER_MODE, FFE_CZ_TIMER_MODE_DIS);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL, abs_evq);
EFX_POPULATE_OWORD_3(reg,
FRF_AZ_EVQ_EN, 1,
FRF_AZ_EVQ_SIZE, __ffs(vf->evq0_count),
FRF_AZ_EVQ_BUF_BASE_ID, buftbl);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL, abs_evq);
EFX_POPULATE_DWORD_1(ptr, FRF_AZ_EVQ_RPTR, 0);
efx_writed(efx, &ptr, FR_BZ_EVQ_RPTR + FR_BZ_EVQ_RPTR_STEP * abs_evq);
mutex_unlock(&vf->status_lock);
}
static void efx_sriov_reset_vf_work(struct work_struct *work)
{
struct efx_vf *vf = container_of(work, struct efx_vf, req);
struct efx_nic *efx = vf->efx;
struct efx_buffer buf;
if (!efx_nic_alloc_buffer(efx, &buf, EFX_PAGE_SIZE)) {
efx_sriov_reset_vf(vf, &buf);
efx_nic_free_buffer(efx, &buf);
}
}
static void efx_sriov_handle_no_channel(struct efx_nic *efx)
{
netif_err(efx, drv, efx->net_dev,
"ERROR: IOV requires MSI-X and 1 additional interrupt"
"vector. IOV disabled\n");
efx->vf_count = 0;
}
static int efx_sriov_probe_channel(struct efx_channel *channel)
{
channel->efx->vfdi_channel = channel;
return 0;
}
static void
efx_sriov_get_channel_name(struct efx_channel *channel, char *buf, size_t len)
{
snprintf(buf, len, "%s-iov", channel->efx->name);
}
static const struct efx_channel_type efx_sriov_channel_type = {
.handle_no_channel = efx_sriov_handle_no_channel,
.pre_probe = efx_sriov_probe_channel,
.post_remove = efx_channel_dummy_op_void,
.get_name = efx_sriov_get_channel_name,
/* no copy operation; channel must not be reallocated */
.keep_eventq = true,
};
void efx_sriov_probe(struct efx_nic *efx)
{
unsigned count;
if (!max_vfs)
return;
if (efx_sriov_cmd(efx, false, &efx->vi_scale, &count))
return;
if (count > 0 && count > max_vfs)
count = max_vfs;
/* efx_nic_dimension_resources() will reduce vf_count as appopriate */
efx->vf_count = count;
efx->extra_channel_type[EFX_EXTRA_CHANNEL_IOV] = &efx_sriov_channel_type;
}
/* Copy the list of individual addresses into the vfdi_status.peers
* array and auxillary pages, protected by %local_lock. Drop that lock
* and then broadcast the address list to every VF.
*/
static void efx_sriov_peer_work(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic, peer_work);
struct vfdi_status *vfdi_status = efx->vfdi_status.addr;
struct efx_vf *vf;
struct efx_local_addr *local_addr;
struct vfdi_endpoint *peer;
struct efx_endpoint_page *epp;
struct list_head pages;
unsigned int peer_space;
unsigned int peer_count;
unsigned int pos;
mutex_lock(&efx->local_lock);
/* Move the existing peer pages off %local_page_list */
INIT_LIST_HEAD(&pages);
list_splice_tail_init(&efx->local_page_list, &pages);
/* Populate the VF addresses starting from entry 1 (entry 0 is
* the PF address)
*/
peer = vfdi_status->peers + 1;
peer_space = ARRAY_SIZE(vfdi_status->peers) - 1;
peer_count = 1;
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = efx->vf + pos;
mutex_lock(&vf->status_lock);
if (vf->rx_filtering && !is_zero_ether_addr(vf->addr.mac_addr)) {
*peer++ = vf->addr;
++peer_count;
--peer_space;
BUG_ON(peer_space == 0);
}
mutex_unlock(&vf->status_lock);
}
/* Fill the remaining addresses */
list_for_each_entry(local_addr, &efx->local_addr_list, link) {
memcpy(peer->mac_addr, local_addr->addr, ETH_ALEN);
peer->tci = 0;
++peer;
++peer_count;
if (--peer_space == 0) {
if (list_empty(&pages)) {
epp = kmalloc(sizeof(*epp), GFP_KERNEL);
if (!epp)
break;
epp->ptr = dma_alloc_coherent(
&efx->pci_dev->dev, EFX_PAGE_SIZE,
&epp->addr, GFP_KERNEL);
if (!epp->ptr) {
kfree(epp);
break;
}
} else {
epp = list_first_entry(
&pages, struct efx_endpoint_page, link);
list_del(&epp->link);
}
list_add_tail(&epp->link, &efx->local_page_list);
peer = (struct vfdi_endpoint *)epp->ptr;
peer_space = EFX_PAGE_SIZE / sizeof(struct vfdi_endpoint);
}
}
vfdi_status->peer_count = peer_count;
mutex_unlock(&efx->local_lock);
/* Free any now unused endpoint pages */
while (!list_empty(&pages)) {
epp = list_first_entry(
&pages, struct efx_endpoint_page, link);
list_del(&epp->link);
dma_free_coherent(&efx->pci_dev->dev, EFX_PAGE_SIZE,
epp->ptr, epp->addr);
kfree(epp);
}
/* Finally, push the pages */
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = efx->vf + pos;
mutex_lock(&vf->status_lock);
if (vf->status_addr)
__efx_sriov_push_vf_status(vf);
mutex_unlock(&vf->status_lock);
}
}
static void efx_sriov_free_local(struct efx_nic *efx)
{
struct efx_local_addr *local_addr;
struct efx_endpoint_page *epp;
while (!list_empty(&efx->local_addr_list)) {
local_addr = list_first_entry(&efx->local_addr_list,
struct efx_local_addr, link);
list_del(&local_addr->link);
kfree(local_addr);
}
while (!list_empty(&efx->local_page_list)) {
epp = list_first_entry(&efx->local_page_list,
struct efx_endpoint_page, link);
list_del(&epp->link);
dma_free_coherent(&efx->pci_dev->dev, EFX_PAGE_SIZE,
epp->ptr, epp->addr);
kfree(epp);
}
}
static int efx_sriov_vf_alloc(struct efx_nic *efx)
{
unsigned index;
struct efx_vf *vf;
efx->vf = kzalloc(sizeof(struct efx_vf) * efx->vf_count, GFP_KERNEL);
if (!efx->vf)
return -ENOMEM;
for (index = 0; index < efx->vf_count; ++index) {
vf = efx->vf + index;
vf->efx = efx;
vf->index = index;
vf->rx_filter_id = -1;
vf->tx_filter_mode = VF_TX_FILTER_AUTO;
vf->tx_filter_id = -1;
INIT_WORK(&vf->req, efx_sriov_vfdi);
INIT_WORK(&vf->reset_work, efx_sriov_reset_vf_work);
init_waitqueue_head(&vf->flush_waitq);
mutex_init(&vf->status_lock);
mutex_init(&vf->txq_lock);
}
return 0;
}
static void efx_sriov_vfs_fini(struct efx_nic *efx)
{
struct efx_vf *vf;
unsigned int pos;
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = efx->vf + pos;
efx_nic_free_buffer(efx, &vf->buf);
kfree(vf->peer_page_addrs);
vf->peer_page_addrs = NULL;
vf->peer_page_count = 0;
vf->evq0_count = 0;
}
}
static int efx_sriov_vfs_init(struct efx_nic *efx)
{
struct pci_dev *pci_dev = efx->pci_dev;
unsigned index, devfn, sriov, buftbl_base;
u16 offset, stride;
struct efx_vf *vf;
int rc;
sriov = pci_find_ext_capability(pci_dev, PCI_EXT_CAP_ID_SRIOV);
if (!sriov)
return -ENOENT;
pci_read_config_word(pci_dev, sriov + PCI_SRIOV_VF_OFFSET, &offset);
pci_read_config_word(pci_dev, sriov + PCI_SRIOV_VF_STRIDE, &stride);
buftbl_base = efx->vf_buftbl_base;
devfn = pci_dev->devfn + offset;
for (index = 0; index < efx->vf_count; ++index) {
vf = efx->vf + index;
/* Reserve buffer entries */
vf->buftbl_base = buftbl_base;
buftbl_base += EFX_VF_BUFTBL_PER_VI * efx_vf_size(efx);
vf->pci_rid = devfn;
snprintf(vf->pci_name, sizeof(vf->pci_name),
"%04x:%02x:%02x.%d",
pci_domain_nr(pci_dev->bus), pci_dev->bus->number,
PCI_SLOT(devfn), PCI_FUNC(devfn));
rc = efx_nic_alloc_buffer(efx, &vf->buf, EFX_PAGE_SIZE);
if (rc)
goto fail;
devfn += stride;
}
return 0;
fail:
efx_sriov_vfs_fini(efx);
return rc;
}
int efx_sriov_init(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct vfdi_status *vfdi_status;
int rc;
/* Ensure there's room for vf_channel */
BUILD_BUG_ON(EFX_MAX_CHANNELS + 1 >= EFX_VI_BASE);
/* Ensure that VI_BASE is aligned on VI_SCALE */
BUILD_BUG_ON(EFX_VI_BASE & ((1 << EFX_VI_SCALE_MAX) - 1));
if (efx->vf_count == 0)
return 0;
rc = efx_sriov_cmd(efx, true, NULL, NULL);
if (rc)
goto fail_cmd;
rc = efx_nic_alloc_buffer(efx, &efx->vfdi_status, sizeof(*vfdi_status));
if (rc)
goto fail_status;
vfdi_status = efx->vfdi_status.addr;
memset(vfdi_status, 0, sizeof(*vfdi_status));
vfdi_status->version = 1;
vfdi_status->length = sizeof(*vfdi_status);
vfdi_status->max_tx_channels = vf_max_tx_channels;
vfdi_status->vi_scale = efx->vi_scale;
vfdi_status->rss_rxq_count = efx->rss_spread;
vfdi_status->peer_count = 1 + efx->vf_count;
vfdi_status->timer_quantum_ns = efx->timer_quantum_ns;
rc = efx_sriov_vf_alloc(efx);
if (rc)
goto fail_alloc;
mutex_init(&efx->local_lock);
INIT_WORK(&efx->peer_work, efx_sriov_peer_work);
INIT_LIST_HEAD(&efx->local_addr_list);
INIT_LIST_HEAD(&efx->local_page_list);
rc = efx_sriov_vfs_init(efx);
if (rc)
goto fail_vfs;
rtnl_lock();
memcpy(vfdi_status->peers[0].mac_addr,
net_dev->dev_addr, ETH_ALEN);
efx->vf_init_count = efx->vf_count;
rtnl_unlock();
efx_sriov_usrev(efx, true);
/* At this point we must be ready to accept VFDI requests */
rc = pci_enable_sriov(efx->pci_dev, efx->vf_count);
if (rc)
goto fail_pci;
netif_info(efx, probe, net_dev,
"enabled SR-IOV for %d VFs, %d VI per VF\n",
efx->vf_count, efx_vf_size(efx));
return 0;
fail_pci:
efx_sriov_usrev(efx, false);
rtnl_lock();
efx->vf_init_count = 0;
rtnl_unlock();
efx_sriov_vfs_fini(efx);
fail_vfs:
cancel_work_sync(&efx->peer_work);
efx_sriov_free_local(efx);
kfree(efx->vf);
fail_alloc:
efx_nic_free_buffer(efx, &efx->vfdi_status);
fail_status:
efx_sriov_cmd(efx, false, NULL, NULL);
fail_cmd:
return rc;
}
void efx_sriov_fini(struct efx_nic *efx)
{
struct efx_vf *vf;
unsigned int pos;
if (efx->vf_init_count == 0)
return;
/* Disable all interfaces to reconfiguration */
BUG_ON(efx->vfdi_channel->enabled);
efx_sriov_usrev(efx, false);
rtnl_lock();
efx->vf_init_count = 0;
rtnl_unlock();
/* Flush all reconfiguration work */
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = efx->vf + pos;
cancel_work_sync(&vf->req);
cancel_work_sync(&vf->reset_work);
}
cancel_work_sync(&efx->peer_work);
pci_disable_sriov(efx->pci_dev);
/* Tear down back-end state */
efx_sriov_vfs_fini(efx);
efx_sriov_free_local(efx);
kfree(efx->vf);
efx_nic_free_buffer(efx, &efx->vfdi_status);
efx_sriov_cmd(efx, false, NULL, NULL);
}
void efx_sriov_event(struct efx_channel *channel, efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
struct efx_vf *vf;
unsigned qid, seq, type, data;
qid = EFX_QWORD_FIELD(*event, FSF_CZ_USER_QID);
/* USR_EV_REG_VALUE is dword0, so access the VFDI_EV fields directly */
BUILD_BUG_ON(FSF_CZ_USER_EV_REG_VALUE_LBN != 0);
seq = EFX_QWORD_FIELD(*event, VFDI_EV_SEQ);
type = EFX_QWORD_FIELD(*event, VFDI_EV_TYPE);
data = EFX_QWORD_FIELD(*event, VFDI_EV_DATA);
netif_vdbg(efx, hw, efx->net_dev,
"USR_EV event from qid %d seq 0x%x type %d data 0x%x\n",
qid, seq, type, data);
if (map_vi_index(efx, qid, &vf, NULL))
return;
if (vf->busy)
goto error;
if (type == VFDI_EV_TYPE_REQ_WORD0) {
/* Resynchronise */
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->req_seqno = seq + 1;
vf->req_addr = 0;
} else if (seq != (vf->req_seqno++ & 0xff) || type != vf->req_type)
goto error;
switch (vf->req_type) {
case VFDI_EV_TYPE_REQ_WORD0:
case VFDI_EV_TYPE_REQ_WORD1:
case VFDI_EV_TYPE_REQ_WORD2:
vf->req_addr |= (u64)data << (vf->req_type << 4);
++vf->req_type;
return;
case VFDI_EV_TYPE_REQ_WORD3:
vf->req_addr |= (u64)data << 48;
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->busy = true;
queue_work(vfdi_workqueue, &vf->req);
return;
}
error:
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Screaming VFDI request from %s\n",
vf->pci_name);
/* Reset the request and sequence number */
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->req_seqno = seq + 1;
}
void efx_sriov_flr(struct efx_nic *efx, unsigned vf_i)
{
struct efx_vf *vf;
if (vf_i > efx->vf_init_count)
return;
vf = efx->vf + vf_i;
netif_info(efx, hw, efx->net_dev,
"FLR on VF %s\n", vf->pci_name);
vf->status_addr = 0;
efx_vfdi_remove_all_filters(vf);
efx_vfdi_flush_clear(vf);
vf->evq0_count = 0;
}
void efx_sriov_mac_address_changed(struct efx_nic *efx)
{
struct vfdi_status *vfdi_status = efx->vfdi_status.addr;
if (!efx->vf_init_count)
return;
memcpy(vfdi_status->peers[0].mac_addr,
efx->net_dev->dev_addr, ETH_ALEN);
queue_work(vfdi_workqueue, &efx->peer_work);
}
void efx_sriov_tx_flush_done(struct efx_nic *efx, efx_qword_t *event)
{
struct efx_vf *vf;
unsigned queue, qid;
queue = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_SUBDATA);
if (map_vi_index(efx, queue, &vf, &qid))
return;
/* Ignore flush completions triggered by an FLR */
if (!test_bit(qid, vf->txq_mask))
return;
__clear_bit(qid, vf->txq_mask);
--vf->txq_count;
if (efx_vfdi_flush_wake(vf))
wake_up(&vf->flush_waitq);
}
void efx_sriov_rx_flush_done(struct efx_nic *efx, efx_qword_t *event)
{
struct efx_vf *vf;
unsigned ev_failed, queue, qid;
queue = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_RX_DESCQ_ID);
ev_failed = EFX_QWORD_FIELD(*event,
FSF_AZ_DRIVER_EV_RX_FLUSH_FAIL);
if (map_vi_index(efx, queue, &vf, &qid))
return;
if (!test_bit(qid, vf->rxq_mask))
return;
if (ev_failed) {
set_bit(qid, vf->rxq_retry_mask);
atomic_inc(&vf->rxq_retry_count);
} else {
__clear_bit(qid, vf->rxq_mask);
--vf->rxq_count;
}
if (efx_vfdi_flush_wake(vf))
wake_up(&vf->flush_waitq);
}
/* Called from napi. Schedule the reset work item */
void efx_sriov_desc_fetch_err(struct efx_nic *efx, unsigned dmaq)
{
struct efx_vf *vf;
unsigned int rel;
if (map_vi_index(efx, dmaq, &vf, &rel))
return;
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"VF %d DMA Q %d reports descriptor fetch error.\n",
vf->index, rel);
queue_work(vfdi_workqueue, &vf->reset_work);
}
/* Reset all VFs */
void efx_sriov_reset(struct efx_nic *efx)
{
unsigned int vf_i;
struct efx_buffer buf;
struct efx_vf *vf;
ASSERT_RTNL();
if (efx->vf_init_count == 0)
return;
efx_sriov_usrev(efx, true);
(void)efx_sriov_cmd(efx, true, NULL, NULL);
if (efx_nic_alloc_buffer(efx, &buf, EFX_PAGE_SIZE))
return;
for (vf_i = 0; vf_i < efx->vf_init_count; ++vf_i) {
vf = efx->vf + vf_i;
efx_sriov_reset_vf(vf, &buf);
}
efx_nic_free_buffer(efx, &buf);
}
int efx_init_sriov(void)
{
/* A single threaded workqueue is sufficient. efx_sriov_vfdi() and
* efx_sriov_peer_work() spend almost all their time sleeping for
* MCDI to complete anyway
*/
vfdi_workqueue = create_singlethread_workqueue("sfc_vfdi");
if (!vfdi_workqueue)
return -ENOMEM;
return 0;
}
void efx_fini_sriov(void)
{
destroy_workqueue(vfdi_workqueue);
}
int efx_sriov_set_vf_mac(struct net_device *net_dev, int vf_i, u8 *mac)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_vf *vf;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = efx->vf + vf_i;
mutex_lock(&vf->status_lock);
memcpy(vf->addr.mac_addr, mac, ETH_ALEN);
__efx_sriov_update_vf_addr(vf);
mutex_unlock(&vf->status_lock);
return 0;
}
int efx_sriov_set_vf_vlan(struct net_device *net_dev, int vf_i,
u16 vlan, u8 qos)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_vf *vf;
u16 tci;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = efx->vf + vf_i;
mutex_lock(&vf->status_lock);
tci = (vlan & VLAN_VID_MASK) | ((qos & 0x7) << VLAN_PRIO_SHIFT);
vf->addr.tci = htons(tci);
__efx_sriov_update_vf_addr(vf);
mutex_unlock(&vf->status_lock);
return 0;
}
int efx_sriov_set_vf_spoofchk(struct net_device *net_dev, int vf_i,
bool spoofchk)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_vf *vf;
int rc;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = efx->vf + vf_i;
mutex_lock(&vf->txq_lock);
if (vf->txq_count == 0) {
vf->tx_filter_mode =
spoofchk ? VF_TX_FILTER_ON : VF_TX_FILTER_OFF;
rc = 0;
} else {
/* This cannot be changed while TX queues are running */
rc = -EBUSY;
}
mutex_unlock(&vf->txq_lock);
return rc;
}
int efx_sriov_get_vf_config(struct net_device *net_dev, int vf_i,
struct ifla_vf_info *ivi)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_vf *vf;
u16 tci;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = efx->vf + vf_i;
ivi->vf = vf_i;
memcpy(ivi->mac, vf->addr.mac_addr, ETH_ALEN);
ivi->tx_rate = 0;
tci = ntohs(vf->addr.tci);
ivi->vlan = tci & VLAN_VID_MASK;
ivi->qos = (tci >> VLAN_PRIO_SHIFT) & 0x7;
ivi->spoofchk = vf->tx_filter_mode == VF_TX_FILTER_ON;
return 0;
}
| gpl-2.0 |
KFire-Android/kernel_omap_bowser-common | net/ipv6/netfilter/ip6_tables.c | 2565 | 59158 | /*
* Packet matching code.
*
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
* Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/capability.h>
#include <linux/in.h>
#include <linux/skbuff.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/poison.h>
#include <linux/icmpv6.h>
#include <net/ipv6.h>
#include <net/compat.h>
#include <asm/uaccess.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/err.h>
#include <linux/cpumask.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter/x_tables.h>
#include <net/netfilter/nf_log.h>
#include "../../netfilter/xt_repldata.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>");
MODULE_DESCRIPTION("IPv6 packet filter");
/*#define DEBUG_IP_FIREWALL*/
/*#define DEBUG_ALLOW_ALL*/ /* Useful for remote debugging */
/*#define DEBUG_IP_FIREWALL_USER*/
#ifdef DEBUG_IP_FIREWALL
#define dprintf(format, args...) pr_info(format , ## args)
#else
#define dprintf(format, args...)
#endif
#ifdef DEBUG_IP_FIREWALL_USER
#define duprintf(format, args...) pr_info(format , ## args)
#else
#define duprintf(format, args...)
#endif
#ifdef CONFIG_NETFILTER_DEBUG
#define IP_NF_ASSERT(x) WARN_ON(!(x))
#else
#define IP_NF_ASSERT(x)
#endif
#if 0
/* All the better to debug you with... */
#define static
#define inline
#endif
void *ip6t_alloc_initial_table(const struct xt_table *info)
{
return xt_alloc_initial_table(ip6t, IP6T);
}
EXPORT_SYMBOL_GPL(ip6t_alloc_initial_table);
/*
We keep a set of rules for each CPU, so we can avoid write-locking
them in the softirq when updating the counters and therefore
only need to read-lock in the softirq; doing a write_lock_bh() in user
context stops packets coming through and allows user context to read
the counters or update the rules.
Hence the start of any table is given by get_table() below. */
/* Check for an extension */
int
ip6t_ext_hdr(u8 nexthdr)
{
return (nexthdr == IPPROTO_HOPOPTS) ||
(nexthdr == IPPROTO_ROUTING) ||
(nexthdr == IPPROTO_FRAGMENT) ||
(nexthdr == IPPROTO_ESP) ||
(nexthdr == IPPROTO_AH) ||
(nexthdr == IPPROTO_NONE) ||
(nexthdr == IPPROTO_DSTOPTS);
}
/* Returns whether matches rule or not. */
/* Performance critical - called for every packet */
static inline bool
ip6_packet_match(const struct sk_buff *skb,
const char *indev,
const char *outdev,
const struct ip6t_ip6 *ip6info,
unsigned int *protoff,
int *fragoff, bool *hotdrop)
{
unsigned long ret;
const struct ipv6hdr *ipv6 = ipv6_hdr(skb);
#define FWINV(bool, invflg) ((bool) ^ !!(ip6info->invflags & (invflg)))
if (FWINV(ipv6_masked_addr_cmp(&ipv6->saddr, &ip6info->smsk,
&ip6info->src), IP6T_INV_SRCIP) ||
FWINV(ipv6_masked_addr_cmp(&ipv6->daddr, &ip6info->dmsk,
&ip6info->dst), IP6T_INV_DSTIP)) {
dprintf("Source or dest mismatch.\n");
/*
dprintf("SRC: %u. Mask: %u. Target: %u.%s\n", ip->saddr,
ipinfo->smsk.s_addr, ipinfo->src.s_addr,
ipinfo->invflags & IP6T_INV_SRCIP ? " (INV)" : "");
dprintf("DST: %u. Mask: %u. Target: %u.%s\n", ip->daddr,
ipinfo->dmsk.s_addr, ipinfo->dst.s_addr,
ipinfo->invflags & IP6T_INV_DSTIP ? " (INV)" : "");*/
return false;
}
ret = ifname_compare_aligned(indev, ip6info->iniface, ip6info->iniface_mask);
if (FWINV(ret != 0, IP6T_INV_VIA_IN)) {
dprintf("VIA in mismatch (%s vs %s).%s\n",
indev, ip6info->iniface,
ip6info->invflags&IP6T_INV_VIA_IN ?" (INV)":"");
return false;
}
ret = ifname_compare_aligned(outdev, ip6info->outiface, ip6info->outiface_mask);
if (FWINV(ret != 0, IP6T_INV_VIA_OUT)) {
dprintf("VIA out mismatch (%s vs %s).%s\n",
outdev, ip6info->outiface,
ip6info->invflags&IP6T_INV_VIA_OUT ?" (INV)":"");
return false;
}
/* ... might want to do something with class and flowlabel here ... */
/* look for the desired protocol header */
if((ip6info->flags & IP6T_F_PROTO)) {
int protohdr;
unsigned short _frag_off;
protohdr = ipv6_find_hdr(skb, protoff, -1, &_frag_off);
if (protohdr < 0) {
if (_frag_off == 0)
*hotdrop = true;
return false;
}
*fragoff = _frag_off;
dprintf("Packet protocol %hi ?= %s%hi.\n",
protohdr,
ip6info->invflags & IP6T_INV_PROTO ? "!":"",
ip6info->proto);
if (ip6info->proto == protohdr) {
if(ip6info->invflags & IP6T_INV_PROTO) {
return false;
}
return true;
}
/* We need match for the '-p all', too! */
if ((ip6info->proto != 0) &&
!(ip6info->invflags & IP6T_INV_PROTO))
return false;
}
return true;
}
/* should be ip6 safe */
static bool
ip6_checkentry(const struct ip6t_ip6 *ipv6)
{
if (ipv6->flags & ~IP6T_F_MASK) {
duprintf("Unknown flag bits set: %08X\n",
ipv6->flags & ~IP6T_F_MASK);
return false;
}
if (ipv6->invflags & ~IP6T_INV_MASK) {
duprintf("Unknown invflag bits set: %08X\n",
ipv6->invflags & ~IP6T_INV_MASK);
return false;
}
return true;
}
static unsigned int
ip6t_error(struct sk_buff *skb, const struct xt_action_param *par)
{
if (net_ratelimit())
pr_info("error: `%s'\n", (const char *)par->targinfo);
return NF_DROP;
}
static inline struct ip6t_entry *
get_entry(const void *base, unsigned int offset)
{
return (struct ip6t_entry *)(base + offset);
}
/* All zeroes == unconditional rule. */
/* Mildly perf critical (only if packet tracing is on) */
static inline bool unconditional(const struct ip6t_ip6 *ipv6)
{
static const struct ip6t_ip6 uncond;
return memcmp(ipv6, &uncond, sizeof(uncond)) == 0;
}
static inline const struct xt_entry_target *
ip6t_get_target_c(const struct ip6t_entry *e)
{
return ip6t_get_target((struct ip6t_entry *)e);
}
#if defined(CONFIG_NETFILTER_XT_TARGET_TRACE) || \
defined(CONFIG_NETFILTER_XT_TARGET_TRACE_MODULE)
/* This cries for unification! */
static const char *const hooknames[] = {
[NF_INET_PRE_ROUTING] = "PREROUTING",
[NF_INET_LOCAL_IN] = "INPUT",
[NF_INET_FORWARD] = "FORWARD",
[NF_INET_LOCAL_OUT] = "OUTPUT",
[NF_INET_POST_ROUTING] = "POSTROUTING",
};
enum nf_ip_trace_comments {
NF_IP6_TRACE_COMMENT_RULE,
NF_IP6_TRACE_COMMENT_RETURN,
NF_IP6_TRACE_COMMENT_POLICY,
};
static const char *const comments[] = {
[NF_IP6_TRACE_COMMENT_RULE] = "rule",
[NF_IP6_TRACE_COMMENT_RETURN] = "return",
[NF_IP6_TRACE_COMMENT_POLICY] = "policy",
};
static struct nf_loginfo trace_loginfo = {
.type = NF_LOG_TYPE_LOG,
.u = {
.log = {
.level = 4,
.logflags = NF_LOG_MASK,
},
},
};
/* Mildly perf critical (only if packet tracing is on) */
static inline int
get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_entry *e,
const char *hookname, const char **chainname,
const char **comment, unsigned int *rulenum)
{
const struct xt_standard_target *t = (void *)ip6t_get_target_c(s);
if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
/* Head of user chain: ERROR target with chainname */
*chainname = t->target.data;
(*rulenum) = 0;
} else if (s == e) {
(*rulenum)++;
if (s->target_offset == sizeof(struct ip6t_entry) &&
strcmp(t->target.u.kernel.target->name,
XT_STANDARD_TARGET) == 0 &&
t->verdict < 0 &&
unconditional(&s->ipv6)) {
/* Tail of chains: STANDARD target (return/policy) */
*comment = *chainname == hookname
? comments[NF_IP6_TRACE_COMMENT_POLICY]
: comments[NF_IP6_TRACE_COMMENT_RETURN];
}
return 1;
} else
(*rulenum)++;
return 0;
}
static void trace_packet(const struct sk_buff *skb,
unsigned int hook,
const struct net_device *in,
const struct net_device *out,
const char *tablename,
const struct xt_table_info *private,
const struct ip6t_entry *e)
{
const void *table_base;
const struct ip6t_entry *root;
const char *hookname, *chainname, *comment;
const struct ip6t_entry *iter;
unsigned int rulenum = 0;
table_base = private->entries[smp_processor_id()];
root = get_entry(table_base, private->hook_entry[hook]);
hookname = chainname = hooknames[hook];
comment = comments[NF_IP6_TRACE_COMMENT_RULE];
xt_entry_foreach(iter, root, private->size - private->hook_entry[hook])
if (get_chainname_rulenum(iter, e, hookname,
&chainname, &comment, &rulenum) != 0)
break;
nf_log_packet(AF_INET6, hook, skb, in, out, &trace_loginfo,
"TRACE: %s:%s:%s:%u ",
tablename, chainname, comment, rulenum);
}
#endif
static inline __pure struct ip6t_entry *
ip6t_next_entry(const struct ip6t_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Returns one of the generic firewall policies, like NF_ACCEPT. */
unsigned int
ip6t_do_table(struct sk_buff *skb,
unsigned int hook,
const struct net_device *in,
const struct net_device *out,
struct xt_table *table)
{
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ip6t_entry *e, **jumpstack;
unsigned int *stackptr, origptr, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
indev = in ? in->name : nulldevname;
outdev = out ? out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.hotdrop = false;
acpar.in = in;
acpar.out = out;
acpar.family = NFPROTO_IPV6;
acpar.hooknum = hook;
IP_NF_ASSERT(table->valid_hooks & (1 << hook));
local_bh_disable();
addend = xt_write_recseq_begin();
private = table->private;
cpu = smp_processor_id();
table_base = private->entries[cpu];
jumpstack = (struct ip6t_entry **)private->jumpstack[cpu];
stackptr = per_cpu_ptr(private->stackptr, cpu);
origptr = *stackptr;
e = get_entry(table_base, private->hook_entry[hook]);
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
IP_NF_ASSERT(e);
if (!ip6_packet_match(skb, indev, outdev, &e->ipv6,
&acpar.thoff, &acpar.fragoff, &acpar.hotdrop)) {
no_match:
e = ip6t_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
ADD_COUNTER(e->counters, skb->len, 1);
t = ip6t_get_target_c(e);
IP_NF_ASSERT(t->u.kernel.target);
#if defined(CONFIG_NETFILTER_XT_TARGET_TRACE) || \
defined(CONFIG_NETFILTER_XT_TARGET_TRACE_MODULE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(skb, hook, in, out,
table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned)(-v) - 1;
break;
}
if (*stackptr <= origptr)
e = get_entry(table_base,
private->underflow[hook]);
else
e = ip6t_next_entry(jumpstack[--*stackptr]);
continue;
}
if (table_base + v != ip6t_next_entry(e) &&
!(e->ipv6.flags & IP6T_F_GOTO)) {
if (*stackptr >= private->stacksize) {
verdict = NF_DROP;
break;
}
jumpstack[(*stackptr)++] = e;
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE)
e = ip6t_next_entry(e);
else
/* Verdict */
break;
} while (!acpar.hotdrop);
*stackptr = origptr;
xt_write_recseq_end(addend);
local_bh_enable();
#ifdef DEBUG_ALLOW_ALL
return NF_ACCEPT;
#else
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
#endif
}
/* Figures out from what hook each rule can be called: returns 0 if
there are loops. Puts hook bitmask in comefrom. */
static int
mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
to 0 as we leave), and comefrom to save source hook bitmask */
for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct ip6t_entry *e = (struct ip6t_entry *)(entry0 + pos);
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)ip6t_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
pr_err("iptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
/* Unconditional return/END. */
if ((e->target_offset == sizeof(struct ip6t_entry) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0 &&
unconditional(&e->ipv6)) || visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1) {
duprintf("mark_source_chains: bad "
"negative verdict (%i)\n",
t->verdict);
return 0;
}
/* Return: backtrack through the last
big jump. */
do {
e->comefrom ^= (1<<NF_INET_NUMHOOKS);
#ifdef DEBUG_IP_FIREWALL_USER
if (e->comefrom
& (1 << NF_INET_NUMHOOKS)) {
duprintf("Back unset "
"on hook %u "
"rule %u\n",
hook, pos);
}
#endif
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct ip6t_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct ip6t_entry *)
(entry0 + pos + size);
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
if (newpos > newinfo->size -
sizeof(struct ip6t_entry)) {
duprintf("mark_source_chains: "
"bad verdict (%i)\n",
newpos);
return 0;
}
/* This a jump; chase it. */
duprintf("Jump rule %u -> %u\n",
pos, newpos);
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
}
e = (struct ip6t_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
static void cleanup_match(struct xt_entry_match *m, struct net *net)
{
struct xt_mtdtor_param par;
par.net = net;
par.match = m->u.kernel.match;
par.matchinfo = m->data;
par.family = NFPROTO_IPV6;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
}
static int
check_entry(const struct ip6t_entry *e, const char *name)
{
const struct xt_entry_target *t;
if (!ip6_checkentry(&e->ipv6)) {
duprintf("ip_tables: ip check failed %p %s.\n", e, name);
return -EINVAL;
}
if (e->target_offset + sizeof(struct xt_entry_target) >
e->next_offset)
return -EINVAL;
t = ip6t_get_target_c(e);
if (e->target_offset + t->u.target_size > e->next_offset)
return -EINVAL;
return 0;
}
static int check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
{
const struct ip6t_ip6 *ipv6 = par->entryinfo;
int ret;
par->match = m->u.kernel.match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->u.match_size - sizeof(*m),
ipv6->proto, ipv6->invflags & IP6T_INV_PROTO);
if (ret < 0) {
duprintf("ip_tables: check failed for `%s'.\n",
par.match->name);
return ret;
}
return 0;
}
static int
find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
{
struct xt_match *match;
int ret;
match = xt_request_find_match(NFPROTO_IPV6, m->u.user.name,
m->u.user.revision);
if (IS_ERR(match)) {
duprintf("find_check_match: `%s' not found\n", m->u.user.name);
return PTR_ERR(match);
}
m->u.kernel.match = match;
ret = check_match(m, par);
if (ret)
goto err;
return 0;
err:
module_put(m->u.kernel.match->me);
return ret;
}
static int check_target(struct ip6t_entry *e, struct net *net, const char *name)
{
struct xt_entry_target *t = ip6t_get_target(e);
struct xt_tgchk_param par = {
.net = net,
.table = name,
.entryinfo = e,
.target = t->u.kernel.target,
.targinfo = t->data,
.hook_mask = e->comefrom,
.family = NFPROTO_IPV6,
};
int ret;
t = ip6t_get_target(e);
ret = xt_check_target(&par, t->u.target_size - sizeof(*t),
e->ipv6.proto, e->ipv6.invflags & IP6T_INV_PROTO);
if (ret < 0) {
duprintf("ip_tables: check failed for `%s'.\n",
t->u.kernel.target->name);
return ret;
}
return 0;
}
static int
find_check_entry(struct ip6t_entry *e, struct net *net, const char *name,
unsigned int size)
{
struct xt_entry_target *t;
struct xt_target *target;
int ret;
unsigned int j;
struct xt_mtchk_param mtpar;
struct xt_entry_match *ematch;
ret = check_entry(e, name);
if (ret)
return ret;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ipv6;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV6;
xt_ematch_foreach(ematch, e) {
ret = find_check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
t = ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("find_check_entry: `%s' not found\n", t->u.user.name);
ret = PTR_ERR(target);
goto cleanup_matches;
}
t->u.kernel.target = target;
ret = check_target(e, net, name);
if (ret)
goto err;
return 0;
err:
module_put(t->u.kernel.target->me);
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
return ret;
}
static bool check_underflow(const struct ip6t_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->ipv6))
return false;
t = ip6t_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
static int
check_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
static void cleanup_entry(struct ip6t_entry *e, struct net *net)
{
struct xt_tgdtor_param par;
struct xt_entry_target *t;
struct xt_entry_match *ematch;
/* Cleanup all matches */
xt_ematch_foreach(ematch, e)
cleanup_match(ematch, net);
t = ip6t_get_target(e);
par.net = net;
par.target = t->u.kernel.target;
par.targinfo = t->data;
par.family = NFPROTO_IPV6;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
}
/* Checks and translates the user-supplied table segment (held in
newinfo) */
static int
translate_table(struct net *net, struct xt_table_info *newinfo, void *entry0,
const struct ip6t_replace *repl)
{
struct ip6t_entry *iter;
unsigned int i;
int ret = 0;
newinfo->size = repl->size;
newinfo->number = repl->num_entries;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
newinfo->hook_entry[i] = 0xFFFFFFFF;
newinfo->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_table: size %u\n", newinfo->size);
i = 0;
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = check_entry_size_and_hooks(iter, newinfo, entry0,
entry0 + repl->size,
repl->hook_entry,
repl->underflow,
repl->valid_hooks);
if (ret != 0)
return ret;
++i;
if (strcmp(ip6t_get_target(iter)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (i != repl->num_entries) {
duprintf("translate_table: %u not %u entries\n",
i, repl->num_entries);
return -EINVAL;
}
/* Check hooks all assigned */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(repl->valid_hooks & (1 << i)))
continue;
if (newinfo->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, repl->hook_entry[i]);
return -EINVAL;
}
if (newinfo->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, repl->underflow[i]);
return -EINVAL;
}
}
if (!mark_source_chains(newinfo, repl->valid_hooks, entry0))
return -ELOOP;
/* Finally, each sanity check must pass */
i = 0;
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = find_check_entry(iter, net, repl->name, repl->size);
if (ret != 0)
break;
++i;
}
if (ret != 0) {
xt_entry_foreach(iter, entry0, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter, net);
}
return ret;
}
/* And one copy for every other CPU */
for_each_possible_cpu(i) {
if (newinfo->entries[i] && newinfo->entries[i] != entry0)
memcpy(newinfo->entries[i], entry0, newinfo->size);
}
return ret;
}
static void
get_counters(const struct xt_table_info *t,
struct xt_counters counters[])
{
struct ip6t_entry *iter;
unsigned int cpu;
unsigned int i;
for_each_possible_cpu(cpu) {
seqcount_t *s = &per_cpu(xt_recseq, cpu);
i = 0;
xt_entry_foreach(iter, t->entries[cpu], t->size) {
u64 bcnt, pcnt;
unsigned int start;
do {
start = read_seqcount_begin(s);
bcnt = iter->counters.bcnt;
pcnt = iter->counters.pcnt;
} while (read_seqcount_retry(s, start));
ADD_COUNTER(counters[i], bcnt, pcnt);
++i;
}
}
}
static struct xt_counters *alloc_counters(const struct xt_table *table)
{
unsigned int countersize;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
/* We need atomic snapshot of counters: rest doesn't change
(other than comefrom, which userspace doesn't care
about). */
countersize = sizeof(struct xt_counters) * private->number;
counters = vzalloc(countersize);
if (counters == NULL)
return ERR_PTR(-ENOMEM);
get_counters(private, counters);
return counters;
}
static int
copy_entries_to_user(unsigned int total_size,
const struct xt_table *table,
void __user *userptr)
{
unsigned int off, num;
const struct ip6t_entry *e;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
int ret = 0;
const void *loc_cpu_entry;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
/* choose the copy that is on our node/cpu, ...
* This choice is lazy (because current thread is
* allowed to migrate to another cpu)
*/
loc_cpu_entry = private->entries[raw_smp_processor_id()];
if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) {
ret = -EFAULT;
goto free_counters;
}
/* FIXME: use iterator macros --RR */
/* ... then go back and fix counters and names */
for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
unsigned int i;
const struct xt_entry_match *m;
const struct xt_entry_target *t;
e = (struct ip6t_entry *)(loc_cpu_entry + off);
if (copy_to_user(userptr + off
+ offsetof(struct ip6t_entry, counters),
&counters[num],
sizeof(counters[num])) != 0) {
ret = -EFAULT;
goto free_counters;
}
for (i = sizeof(struct ip6t_entry);
i < e->target_offset;
i += m->u.match_size) {
m = (void *)e + i;
if (copy_to_user(userptr + off + i
+ offsetof(struct xt_entry_match,
u.user.name),
m->u.kernel.match->name,
strlen(m->u.kernel.match->name)+1)
!= 0) {
ret = -EFAULT;
goto free_counters;
}
}
t = ip6t_get_target_c(e);
if (copy_to_user(userptr + off + e->target_offset
+ offsetof(struct xt_entry_target,
u.user.name),
t->u.kernel.target->name,
strlen(t->u.kernel.target->name)+1) != 0) {
ret = -EFAULT;
goto free_counters;
}
}
free_counters:
vfree(counters);
return ret;
}
#ifdef CONFIG_COMPAT
static void compat_standard_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v > 0)
v += xt_compat_calc_jump(AF_INET6, v);
memcpy(dst, &v, sizeof(v));
}
static int compat_standard_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv > 0)
cv -= xt_compat_calc_jump(AF_INET6, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
static int compat_calc_entry(const struct ip6t_entry *e,
const struct xt_table_info *info,
const void *base, struct xt_table_info *newinfo)
{
const struct xt_entry_match *ematch;
const struct xt_entry_target *t;
unsigned int entry_offset;
int off, i, ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - base;
xt_ematch_foreach(ematch, e)
off += xt_compat_match_offset(ematch->u.kernel.match);
t = ip6t_get_target_c(e);
off += xt_compat_target_offset(t->u.kernel.target);
newinfo->size -= off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
if (info->hook_entry[i] &&
(e < (struct ip6t_entry *)(base + info->hook_entry[i])))
newinfo->hook_entry[i] -= off;
if (info->underflow[i] &&
(e < (struct ip6t_entry *)(base + info->underflow[i])))
newinfo->underflow[i] -= off;
}
return 0;
}
static int compat_table_info(const struct xt_table_info *info,
struct xt_table_info *newinfo)
{
struct ip6t_entry *iter;
void *loc_cpu_entry;
int ret;
if (!newinfo || !info)
return -EINVAL;
/* we dont care about newinfo->entries[] */
memcpy(newinfo, info, offsetof(struct xt_table_info, entries));
newinfo->initial_entries = 0;
loc_cpu_entry = info->entries[raw_smp_processor_id()];
xt_compat_init_offsets(AF_INET6, info->number);
xt_entry_foreach(iter, loc_cpu_entry, info->size) {
ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo);
if (ret != 0)
return ret;
}
return 0;
}
#endif
static int get_info(struct net *net, void __user *user,
const int *len, int compat)
{
char name[XT_TABLE_MAXNAMELEN];
struct xt_table *t;
int ret;
if (*len != sizeof(struct ip6t_getinfo)) {
duprintf("length %u != %zu\n", *len,
sizeof(struct ip6t_getinfo));
return -EINVAL;
}
if (copy_from_user(name, user, sizeof(name)) != 0)
return -EFAULT;
name[XT_TABLE_MAXNAMELEN-1] = '\0';
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_lock(AF_INET6);
#endif
t = try_then_request_module(xt_find_table_lock(net, AF_INET6, name),
"ip6table_%s", name);
if (t && !IS_ERR(t)) {
struct ip6t_getinfo info;
const struct xt_table_info *private = t->private;
#ifdef CONFIG_COMPAT
struct xt_table_info tmp;
if (compat) {
ret = compat_table_info(private, &tmp);
xt_compat_flush_offsets(AF_INET6);
private = &tmp;
}
#endif
memset(&info, 0, sizeof(info));
info.valid_hooks = t->valid_hooks;
memcpy(info.hook_entry, private->hook_entry,
sizeof(info.hook_entry));
memcpy(info.underflow, private->underflow,
sizeof(info.underflow));
info.num_entries = private->number;
info.size = private->size;
strcpy(info.name, name);
if (copy_to_user(user, &info, *len) != 0)
ret = -EFAULT;
else
ret = 0;
xt_table_unlock(t);
module_put(t->me);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_unlock(AF_INET6);
#endif
return ret;
}
static int
get_entries(struct net *net, struct ip6t_get_entries __user *uptr,
const int *len)
{
int ret;
struct ip6t_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct ip6t_get_entries) + get.size) {
duprintf("get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
t = xt_find_table_lock(net, AF_INET6, get.name);
if (t && !IS_ERR(t)) {
struct xt_table_info *private = t->private;
duprintf("t->private->number = %u\n", private->number);
if (get.size == private->size)
ret = copy_entries_to_user(private->size,
t, uptr->entrytable);
else {
duprintf("get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
return ret;
}
static int
__do_replace(struct net *net, const char *name, unsigned int valid_hooks,
struct xt_table_info *newinfo, unsigned int num_counters,
void __user *counters_ptr)
{
int ret;
struct xt_table *t;
struct xt_table_info *oldinfo;
struct xt_counters *counters;
const void *loc_cpu_old_entry;
struct ip6t_entry *iter;
ret = 0;
counters = vzalloc(num_counters * sizeof(struct xt_counters));
if (!counters) {
ret = -ENOMEM;
goto out;
}
t = try_then_request_module(xt_find_table_lock(net, AF_INET6, name),
"ip6table_%s", name);
if (!t || IS_ERR(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free_newinfo_counters_untrans;
}
/* You lied! */
if (valid_hooks != t->valid_hooks) {
duprintf("Valid hook crap: %08X vs %08X\n",
valid_hooks, t->valid_hooks);
ret = -EINVAL;
goto put_module;
}
oldinfo = xt_replace_table(t, num_counters, newinfo, &ret);
if (!oldinfo)
goto put_module;
/* Update module usage count based on number of rules */
duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n",
oldinfo->number, oldinfo->initial_entries, newinfo->number);
if ((oldinfo->number > oldinfo->initial_entries) ||
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
if ((oldinfo->number > oldinfo->initial_entries) &&
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
/* Get the old counters, and synchronize with replace */
get_counters(oldinfo, counters);
/* Decrease module usage counts and free resource */
loc_cpu_old_entry = oldinfo->entries[raw_smp_processor_id()];
xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size)
cleanup_entry(iter, net);
xt_free_table_info(oldinfo);
if (copy_to_user(counters_ptr, counters,
sizeof(struct xt_counters) * num_counters) != 0)
ret = -EFAULT;
vfree(counters);
xt_table_unlock(t);
return ret;
put_module:
module_put(t->me);
xt_table_unlock(t);
free_newinfo_counters_untrans:
vfree(counters);
out:
return ret;
}
static int
do_replace(struct net *net, const void __user *user, unsigned int len)
{
int ret;
struct ip6t_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ip6t_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
/* choose the copy that is on our node/cpu */
loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_table(net, newinfo, loc_cpu_entry, &tmp);
if (ret != 0)
goto free_newinfo;
duprintf("ip_tables: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, tmp.counters);
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int
do_add_counters(struct net *net, const void __user *user, unsigned int len,
int compat)
{
unsigned int i, curcpu;
struct xt_counters_info tmp;
struct xt_counters *paddc;
unsigned int num_counters;
char *name;
int size;
void *ptmp;
struct xt_table *t;
const struct xt_table_info *private;
int ret = 0;
const void *loc_cpu_entry;
struct ip6t_entry *iter;
unsigned int addend;
#ifdef CONFIG_COMPAT
struct compat_xt_counters_info compat_tmp;
if (compat) {
ptmp = &compat_tmp;
size = sizeof(struct compat_xt_counters_info);
} else
#endif
{
ptmp = &tmp;
size = sizeof(struct xt_counters_info);
}
if (copy_from_user(ptmp, user, size) != 0)
return -EFAULT;
#ifdef CONFIG_COMPAT
if (compat) {
num_counters = compat_tmp.num_counters;
name = compat_tmp.name;
} else
#endif
{
num_counters = tmp.num_counters;
name = tmp.name;
}
if (len != size + num_counters * sizeof(struct xt_counters))
return -EINVAL;
paddc = vmalloc(len - size);
if (!paddc)
return -ENOMEM;
if (copy_from_user(paddc, user + size, len - size) != 0) {
ret = -EFAULT;
goto free;
}
t = xt_find_table_lock(net, AF_INET6, name);
if (!t || IS_ERR(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free;
}
local_bh_disable();
private = t->private;
if (private->number != num_counters) {
ret = -EINVAL;
goto unlock_up_free;
}
i = 0;
/* Choose the copy that is on our node */
curcpu = smp_processor_id();
addend = xt_write_recseq_begin();
loc_cpu_entry = private->entries[curcpu];
xt_entry_foreach(iter, loc_cpu_entry, private->size) {
ADD_COUNTER(iter->counters, paddc[i].bcnt, paddc[i].pcnt);
++i;
}
xt_write_recseq_end(addend);
unlock_up_free:
local_bh_enable();
xt_table_unlock(t);
module_put(t->me);
free:
vfree(paddc);
return ret;
}
#ifdef CONFIG_COMPAT
struct compat_ip6t_replace {
char name[XT_TABLE_MAXNAMELEN];
u32 valid_hooks;
u32 num_entries;
u32 size;
u32 hook_entry[NF_INET_NUMHOOKS];
u32 underflow[NF_INET_NUMHOOKS];
u32 num_counters;
compat_uptr_t counters; /* struct xt_counters * */
struct compat_ip6t_entry entries[0];
};
static int
compat_copy_entry_to_user(struct ip6t_entry *e, void __user **dstptr,
unsigned int *size, struct xt_counters *counters,
unsigned int i)
{
struct xt_entry_target *t;
struct compat_ip6t_entry __user *ce;
u_int16_t target_offset, next_offset;
compat_uint_t origsize;
const struct xt_entry_match *ematch;
int ret = 0;
origsize = *size;
ce = (struct compat_ip6t_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(struct ip6t_entry)) != 0 ||
copy_to_user(&ce->counters, &counters[i],
sizeof(counters[i])) != 0)
return -EFAULT;
*dstptr += sizeof(struct compat_ip6t_entry);
*size -= sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
xt_ematch_foreach(ematch, e) {
ret = xt_compat_match_to_user(ematch, dstptr, size);
if (ret != 0)
return ret;
}
target_offset = e->target_offset - (origsize - *size);
t = ip6t_get_target(e);
ret = xt_compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(target_offset, &ce->target_offset) != 0 ||
put_user(next_offset, &ce->next_offset) != 0)
return -EFAULT;
return 0;
}
static int
compat_find_calc_match(struct xt_entry_match *m,
const char *name,
const struct ip6t_ip6 *ipv6,
unsigned int hookmask,
int *size)
{
struct xt_match *match;
match = xt_request_find_match(NFPROTO_IPV6, m->u.user.name,
m->u.user.revision);
if (IS_ERR(match)) {
duprintf("compat_check_calc_match: `%s' not found\n",
m->u.user.name);
return PTR_ERR(match);
}
m->u.kernel.match = match;
*size += xt_compat_match_offset(match);
return 0;
}
static void compat_release_entry(struct compat_ip6t_entry *e)
{
struct xt_entry_target *t;
struct xt_entry_match *ematch;
/* Cleanup all matches */
xt_ematch_foreach(ematch, e)
module_put(ematch->u.kernel.match->me);
t = compat_ip6t_get_target(e);
module_put(t->u.kernel.target->me);
}
static int
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ip6t_entry *)e, name);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name,
&e->ipv6, e->comefrom, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
static int
compat_copy_entry_from_user(struct compat_ip6t_entry *e, void **dstptr,
unsigned int *size, const char *name,
struct xt_table_info *newinfo, unsigned char *base)
{
struct xt_entry_target *t;
struct ip6t_entry *de;
unsigned int origsize;
int ret, h;
struct xt_entry_match *ematch;
ret = 0;
origsize = *size;
de = (struct ip6t_entry *)*dstptr;
memcpy(de, e, sizeof(struct ip6t_entry));
memcpy(&de->counters, &e->counters, sizeof(e->counters));
*dstptr += sizeof(struct ip6t_entry);
*size += sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
xt_ematch_foreach(ematch, e) {
ret = xt_compat_match_from_user(ematch, dstptr, size);
if (ret != 0)
return ret;
}
de->target_offset = e->target_offset - (origsize - *size);
t = compat_ip6t_get_target(e);
xt_compat_target_from_user(t, dstptr, size);
de->next_offset = e->next_offset - (origsize - *size);
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)de - base < newinfo->hook_entry[h])
newinfo->hook_entry[h] -= origsize - *size;
if ((unsigned char *)de - base < newinfo->underflow[h])
newinfo->underflow[h] -= origsize - *size;
}
return ret;
}
static int compat_check_entry(struct ip6t_entry *e, struct net *net,
const char *name)
{
unsigned int j;
int ret = 0;
struct xt_mtchk_param mtpar;
struct xt_entry_match *ematch;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ipv6;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV6;
xt_ematch_foreach(ematch, e) {
ret = check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
ret = check_target(e, net, name);
if (ret)
goto cleanup_matches;
return 0;
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
return ret;
}
static int
translate_compat_table(struct net *net,
const char *name,
unsigned int valid_hooks,
struct xt_table_info **pinfo,
void **pentry0,
unsigned int total_size,
unsigned int number,
unsigned int *hook_entries,
unsigned int *underflows)
{
unsigned int i, j;
struct xt_table_info *newinfo, *info;
void *pos, *entry0, *entry1;
struct compat_ip6t_entry *iter0;
struct ip6t_entry *iter1;
unsigned int size;
int ret = 0;
info = *pinfo;
entry0 = *pentry0;
size = total_size;
info->number = number;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
info->hook_entry[i] = 0xFFFFFFFF;
info->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_compat_table: size %u\n", info->size);
j = 0;
xt_compat_lock(AF_INET6);
xt_compat_init_offsets(AF_INET6, number);
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter0, entry0, total_size) {
ret = check_compat_entry_size_and_hooks(iter0, info, &size,
entry0,
entry0 + total_size,
hook_entries,
underflows,
name);
if (ret != 0)
goto out_unlock;
++j;
}
ret = -EINVAL;
if (j != number) {
duprintf("translate_compat_table: %u not %u entries\n",
j, number);
goto out_unlock;
}
/* Check hooks all assigned */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(valid_hooks & (1 << i)))
continue;
if (info->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, hook_entries[i]);
goto out_unlock;
}
if (info->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, underflows[i]);
goto out_unlock;
}
}
ret = -ENOMEM;
newinfo = xt_alloc_table_info(size);
if (!newinfo)
goto out_unlock;
newinfo->number = number;
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
newinfo->hook_entry[i] = info->hook_entry[i];
newinfo->underflow[i] = info->underflow[i];
}
entry1 = newinfo->entries[raw_smp_processor_id()];
pos = entry1;
size = total_size;
xt_entry_foreach(iter0, entry0, total_size) {
ret = compat_copy_entry_from_user(iter0, &pos, &size,
name, newinfo, entry1);
if (ret != 0)
break;
}
xt_compat_flush_offsets(AF_INET6);
xt_compat_unlock(AF_INET6);
if (ret)
goto free_newinfo;
ret = -ELOOP;
if (!mark_source_chains(newinfo, valid_hooks, entry1))
goto free_newinfo;
i = 0;
xt_entry_foreach(iter1, entry1, newinfo->size) {
ret = compat_check_entry(iter1, net, name);
if (ret != 0)
break;
++i;
if (strcmp(ip6t_get_target(iter1)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (ret) {
/*
* The first i matches need cleanup_entry (calls ->destroy)
* because they had called ->check already. The other j-i
* entries need only release.
*/
int skip = i;
j -= i;
xt_entry_foreach(iter0, entry0, newinfo->size) {
if (skip-- > 0)
continue;
if (j-- == 0)
break;
compat_release_entry(iter0);
}
xt_entry_foreach(iter1, entry1, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter1, net);
}
xt_free_table_info(newinfo);
return ret;
}
/* And one copy for every other CPU */
for_each_possible_cpu(i)
if (newinfo->entries[i] && newinfo->entries[i] != entry1)
memcpy(newinfo->entries[i], entry1, newinfo->size);
*pinfo = newinfo;
*pentry0 = entry1;
xt_free_table_info(info);
return 0;
free_newinfo:
xt_free_table_info(newinfo);
out:
xt_entry_foreach(iter0, entry0, total_size) {
if (j-- == 0)
break;
compat_release_entry(iter0);
}
return ret;
out_unlock:
xt_compat_flush_offsets(AF_INET6);
xt_compat_unlock(AF_INET6);
goto out;
}
static int
compat_do_replace(struct net *net, void __user *user, unsigned int len)
{
int ret;
struct compat_ip6t_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ip6t_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.size >= INT_MAX / num_possible_cpus())
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
/* choose the copy that is on our node/cpu */
loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_compat_table(net, tmp.name, tmp.valid_hooks,
&newinfo, &loc_cpu_entry, tmp.size,
tmp.num_entries, tmp.hook_entry,
tmp.underflow);
if (ret != 0)
goto free_newinfo;
duprintf("compat_do_replace: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, compat_ptr(tmp.counters));
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int
compat_do_ip6t_set_ctl(struct sock *sk, int cmd, void __user *user,
unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IP6T_SO_SET_REPLACE:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case IP6T_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 1);
break;
default:
duprintf("do_ip6t_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
struct compat_ip6t_get_entries {
char name[XT_TABLE_MAXNAMELEN];
compat_uint_t size;
struct compat_ip6t_entry entrytable[0];
};
static int
compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table,
void __user *userptr)
{
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
void __user *pos;
unsigned int size;
int ret = 0;
const void *loc_cpu_entry;
unsigned int i = 0;
struct ip6t_entry *iter;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
/* choose the copy that is on our node/cpu, ...
* This choice is lazy (because current thread is
* allowed to migrate to another cpu)
*/
loc_cpu_entry = private->entries[raw_smp_processor_id()];
pos = userptr;
size = total_size;
xt_entry_foreach(iter, loc_cpu_entry, total_size) {
ret = compat_copy_entry_to_user(iter, &pos,
&size, counters, i++);
if (ret != 0)
break;
}
vfree(counters);
return ret;
}
static int
compat_get_entries(struct net *net, struct compat_ip6t_get_entries __user *uptr,
int *len)
{
int ret;
struct compat_ip6t_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct compat_ip6t_get_entries) + get.size) {
duprintf("compat_get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
xt_compat_lock(AF_INET6);
t = xt_find_table_lock(net, AF_INET6, get.name);
if (t && !IS_ERR(t)) {
const struct xt_table_info *private = t->private;
struct xt_table_info info;
duprintf("t->private->number = %u\n", private->number);
ret = compat_table_info(private, &info);
if (!ret && get.size == info.size) {
ret = compat_copy_entries_to_user(private->size,
t, uptr->entrytable);
} else if (!ret) {
duprintf("compat_get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
xt_compat_flush_offsets(AF_INET6);
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
xt_compat_unlock(AF_INET6);
return ret;
}
static int do_ip6t_get_ctl(struct sock *, int, void __user *, int *);
static int
compat_do_ip6t_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IP6T_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 1);
break;
case IP6T_SO_GET_ENTRIES:
ret = compat_get_entries(sock_net(sk), user, len);
break;
default:
ret = do_ip6t_get_ctl(sk, cmd, user, len);
}
return ret;
}
#endif
static int
do_ip6t_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IP6T_SO_SET_REPLACE:
ret = do_replace(sock_net(sk), user, len);
break;
case IP6T_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 0);
break;
default:
duprintf("do_ip6t_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static int
do_ip6t_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IP6T_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 0);
break;
case IP6T_SO_GET_ENTRIES:
ret = get_entries(sock_net(sk), user, len);
break;
case IP6T_SO_GET_REVISION_MATCH:
case IP6T_SO_GET_REVISION_TARGET: {
struct xt_get_revision rev;
int target;
if (*len != sizeof(rev)) {
ret = -EINVAL;
break;
}
if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
ret = -EFAULT;
break;
}
rev.name[sizeof(rev.name)-1] = 0;
if (cmd == IP6T_SO_GET_REVISION_TARGET)
target = 1;
else
target = 0;
try_then_request_module(xt_find_revision(AF_INET6, rev.name,
rev.revision,
target, &ret),
"ip6t_%s", rev.name);
break;
}
default:
duprintf("do_ip6t_get_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
struct xt_table *ip6t_register_table(struct net *net,
const struct xt_table *table,
const struct ip6t_replace *repl)
{
int ret;
struct xt_table_info *newinfo;
struct xt_table_info bootstrap = {0};
void *loc_cpu_entry;
struct xt_table *new_table;
newinfo = xt_alloc_table_info(repl->size);
if (!newinfo) {
ret = -ENOMEM;
goto out;
}
/* choose the copy on our node/cpu, but dont care about preemption */
loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
memcpy(loc_cpu_entry, repl->entries, repl->size);
ret = translate_table(net, newinfo, loc_cpu_entry, repl);
if (ret != 0)
goto out_free;
new_table = xt_register_table(net, table, &bootstrap, newinfo);
if (IS_ERR(new_table)) {
ret = PTR_ERR(new_table);
goto out_free;
}
return new_table;
out_free:
xt_free_table_info(newinfo);
out:
return ERR_PTR(ret);
}
void ip6t_unregister_table(struct net *net, struct xt_table *table)
{
struct xt_table_info *private;
void *loc_cpu_entry;
struct module *table_owner = table->me;
struct ip6t_entry *iter;
private = xt_unregister_table(table);
/* Decrease module usage counts and free resources */
loc_cpu_entry = private->entries[raw_smp_processor_id()];
xt_entry_foreach(iter, loc_cpu_entry, private->size)
cleanup_entry(iter, net);
if (private->number > private->initial_entries)
module_put(table_owner);
xt_free_table_info(private);
}
/* Returns 1 if the type and code is matched by the range, 0 otherwise */
static inline bool
icmp6_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code,
u_int8_t type, u_int8_t code,
bool invert)
{
return (type == test_type && code >= min_code && code <= max_code)
^ invert;
}
static bool
icmp6_match(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct icmp6hdr *ic;
struct icmp6hdr _icmph;
const struct ip6t_icmp *icmpinfo = par->matchinfo;
/* Must not be a fragment. */
if (par->fragoff != 0)
return false;
ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph);
if (ic == NULL) {
/* We've been asked to examine this packet, and we
* can't. Hence, no choice but to drop.
*/
duprintf("Dropping evil ICMP tinygram.\n");
par->hotdrop = true;
return false;
}
return icmp6_type_code_match(icmpinfo->type,
icmpinfo->code[0],
icmpinfo->code[1],
ic->icmp6_type, ic->icmp6_code,
!!(icmpinfo->invflags&IP6T_ICMP_INV));
}
/* Called when user tries to insert an entry of this type. */
static int icmp6_checkentry(const struct xt_mtchk_param *par)
{
const struct ip6t_icmp *icmpinfo = par->matchinfo;
/* Must specify no unknown invflags */
return (icmpinfo->invflags & ~IP6T_ICMP_INV) ? -EINVAL : 0;
}
/* The built-in targets: standard (NULL) and error. */
static struct xt_target ip6t_builtin_tg[] __read_mostly = {
{
.name = XT_STANDARD_TARGET,
.targetsize = sizeof(int),
.family = NFPROTO_IPV6,
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = compat_standard_from_user,
.compat_to_user = compat_standard_to_user,
#endif
},
{
.name = XT_ERROR_TARGET,
.target = ip6t_error,
.targetsize = XT_FUNCTION_MAXNAMELEN,
.family = NFPROTO_IPV6,
},
};
static struct nf_sockopt_ops ip6t_sockopts = {
.pf = PF_INET6,
.set_optmin = IP6T_BASE_CTL,
.set_optmax = IP6T_SO_SET_MAX+1,
.set = do_ip6t_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ip6t_set_ctl,
#endif
.get_optmin = IP6T_BASE_CTL,
.get_optmax = IP6T_SO_GET_MAX+1,
.get = do_ip6t_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ip6t_get_ctl,
#endif
.owner = THIS_MODULE,
};
static struct xt_match ip6t_builtin_mt[] __read_mostly = {
{
.name = "icmp6",
.match = icmp6_match,
.matchsize = sizeof(struct ip6t_icmp),
.checkentry = icmp6_checkentry,
.proto = IPPROTO_ICMPV6,
.family = NFPROTO_IPV6,
},
};
static int __net_init ip6_tables_net_init(struct net *net)
{
return xt_proto_init(net, NFPROTO_IPV6);
}
static void __net_exit ip6_tables_net_exit(struct net *net)
{
xt_proto_fini(net, NFPROTO_IPV6);
}
static struct pernet_operations ip6_tables_net_ops = {
.init = ip6_tables_net_init,
.exit = ip6_tables_net_exit,
};
static int __init ip6_tables_init(void)
{
int ret;
ret = register_pernet_subsys(&ip6_tables_net_ops);
if (ret < 0)
goto err1;
/* No one else will be downing sem now, so we won't sleep */
ret = xt_register_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg));
if (ret < 0)
goto err2;
ret = xt_register_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt));
if (ret < 0)
goto err4;
/* Register setsockopt */
ret = nf_register_sockopt(&ip6t_sockopts);
if (ret < 0)
goto err5;
pr_info("(C) 2000-2006 Netfilter Core Team\n");
return 0;
err5:
xt_unregister_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt));
err4:
xt_unregister_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg));
err2:
unregister_pernet_subsys(&ip6_tables_net_ops);
err1:
return ret;
}
static void __exit ip6_tables_fini(void)
{
nf_unregister_sockopt(&ip6t_sockopts);
xt_unregister_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt));
xt_unregister_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg));
unregister_pernet_subsys(&ip6_tables_net_ops);
}
/*
* find the offset to specified header or the protocol number of last header
* if target < 0. "last header" is transport protocol header, ESP, or
* "No next header".
*
* If target header is found, its offset is set in *offset and return protocol
* number. Otherwise, return -ENOENT or -EBADMSG.
*
* If the first fragment doesn't contain the final protocol header or
* NEXTHDR_NONE it is considered invalid.
*
* Note that non-1st fragment is special case that "the protocol number
* of last header" is "next header" field in Fragment header. In this case,
* *offset is meaningless. If fragoff is not NULL, the fragment offset is
* stored in *fragoff; if it is NULL, return -EINVAL.
*/
int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset,
int target, unsigned short *fragoff)
{
unsigned int start = skb_network_offset(skb) + sizeof(struct ipv6hdr);
u8 nexthdr = ipv6_hdr(skb)->nexthdr;
unsigned int len = skb->len - start;
if (fragoff)
*fragoff = 0;
while (nexthdr != target) {
struct ipv6_opt_hdr _hdr, *hp;
unsigned int hdrlen;
if ((!ipv6_ext_hdr(nexthdr)) || nexthdr == NEXTHDR_NONE) {
if (target < 0)
break;
return -ENOENT;
}
hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr);
if (hp == NULL)
return -EBADMSG;
if (nexthdr == NEXTHDR_FRAGMENT) {
unsigned short _frag_off;
__be16 *fp;
fp = skb_header_pointer(skb,
start+offsetof(struct frag_hdr,
frag_off),
sizeof(_frag_off),
&_frag_off);
if (fp == NULL)
return -EBADMSG;
_frag_off = ntohs(*fp) & ~0x7;
if (_frag_off) {
if (target < 0 &&
((!ipv6_ext_hdr(hp->nexthdr)) ||
hp->nexthdr == NEXTHDR_NONE)) {
if (fragoff) {
*fragoff = _frag_off;
return hp->nexthdr;
} else {
return -EINVAL;
}
}
return -ENOENT;
}
hdrlen = 8;
} else if (nexthdr == NEXTHDR_AUTH)
hdrlen = (hp->hdrlen + 2) << 2;
else
hdrlen = ipv6_optlen(hp);
nexthdr = hp->nexthdr;
len -= hdrlen;
start += hdrlen;
}
*offset = start;
return nexthdr;
}
EXPORT_SYMBOL(ip6t_register_table);
EXPORT_SYMBOL(ip6t_unregister_table);
EXPORT_SYMBOL(ip6t_do_table);
EXPORT_SYMBOL(ip6t_ext_hdr);
EXPORT_SYMBOL(ipv6_find_hdr);
module_init(ip6_tables_init);
module_exit(ip6_tables_fini);
| gpl-2.0 |
mythos234/AndromedaB-LL-N910F | drivers/net/can/sja1000/peak_pcmcia.c | 2565 | 18396 | /*
* Copyright (C) 2010-2012 Stephane Grosjean <s.grosjean@peak-system.com>
*
* CAN driver for PEAK-System PCAN-PC Card
* Derived from the PCAN project file driver/src/pcan_pccard.c
* Copyright (C) 2006-2010 PEAK System-Technik GmbH
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the version 2 of the GNU General Public License
* as published by the Free Software Foundation
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/io.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/ds.h>
#include <linux/can.h>
#include <linux/can/dev.h>
#include "sja1000.h"
MODULE_AUTHOR("Stephane Grosjean <s.grosjean@peak-system.com>");
MODULE_DESCRIPTION("CAN driver for PEAK-System PCAN-PC Cards");
MODULE_LICENSE("GPL v2");
MODULE_SUPPORTED_DEVICE("PEAK PCAN-PC Card");
/* PEAK-System PCMCIA driver name */
#define PCC_NAME "peak_pcmcia"
#define PCC_CHAN_MAX 2
#define PCC_CAN_CLOCK (16000000 / 2)
#define PCC_MANF_ID 0x0377
#define PCC_CARD_ID 0x0001
#define PCC_CHAN_SIZE 0x20
#define PCC_CHAN_OFF(c) ((c) * PCC_CHAN_SIZE)
#define PCC_COMN_OFF (PCC_CHAN_OFF(PCC_CHAN_MAX))
#define PCC_COMN_SIZE 0x40
/* common area registers */
#define PCC_CCR 0x00
#define PCC_CSR 0x02
#define PCC_CPR 0x04
#define PCC_SPI_DIR 0x06
#define PCC_SPI_DOR 0x08
#define PCC_SPI_ADR 0x0a
#define PCC_SPI_IR 0x0c
#define PCC_FW_MAJOR 0x10
#define PCC_FW_MINOR 0x12
/* CCR bits */
#define PCC_CCR_CLK_16 0x00
#define PCC_CCR_CLK_10 0x01
#define PCC_CCR_CLK_21 0x02
#define PCC_CCR_CLK_8 0x03
#define PCC_CCR_CLK_MASK PCC_CCR_CLK_8
#define PCC_CCR_RST_CHAN(c) (0x01 << ((c) + 2))
#define PCC_CCR_RST_ALL (PCC_CCR_RST_CHAN(0) | PCC_CCR_RST_CHAN(1))
#define PCC_CCR_RST_MASK PCC_CCR_RST_ALL
/* led selection bits */
#define PCC_LED(c) (1 << (c))
#define PCC_LED_ALL (PCC_LED(0) | PCC_LED(1))
/* led state value */
#define PCC_LED_ON 0x00
#define PCC_LED_FAST 0x01
#define PCC_LED_SLOW 0x02
#define PCC_LED_OFF 0x03
#define PCC_CCR_LED_CHAN(s, c) ((s) << (((c) + 2) << 1))
#define PCC_CCR_LED_ON_CHAN(c) PCC_CCR_LED_CHAN(PCC_LED_ON, c)
#define PCC_CCR_LED_FAST_CHAN(c) PCC_CCR_LED_CHAN(PCC_LED_FAST, c)
#define PCC_CCR_LED_SLOW_CHAN(c) PCC_CCR_LED_CHAN(PCC_LED_SLOW, c)
#define PCC_CCR_LED_OFF_CHAN(c) PCC_CCR_LED_CHAN(PCC_LED_OFF, c)
#define PCC_CCR_LED_MASK_CHAN(c) PCC_CCR_LED_OFF_CHAN(c)
#define PCC_CCR_LED_OFF_ALL (PCC_CCR_LED_OFF_CHAN(0) | \
PCC_CCR_LED_OFF_CHAN(1))
#define PCC_CCR_LED_MASK PCC_CCR_LED_OFF_ALL
#define PCC_CCR_INIT (PCC_CCR_CLK_16 | PCC_CCR_RST_ALL | PCC_CCR_LED_OFF_ALL)
/* CSR bits */
#define PCC_CSR_SPI_BUSY 0x04
/* time waiting for SPI busy (prevent from infinite loop) */
#define PCC_SPI_MAX_BUSY_WAIT_MS 3
/* max count of reading the SPI status register waiting for a change */
/* (prevent from infinite loop) */
#define PCC_WRITE_MAX_LOOP 1000
/* max nb of int handled by that isr in one shot (prevent from infinite loop) */
#define PCC_ISR_MAX_LOOP 10
/* EEPROM chip instruction set */
/* note: EEPROM Read/Write instructions include A8 bit */
#define PCC_EEP_WRITE(a) (0x02 | (((a) & 0x100) >> 5))
#define PCC_EEP_READ(a) (0x03 | (((a) & 0x100) >> 5))
#define PCC_EEP_WRDI 0x04 /* EEPROM Write Disable */
#define PCC_EEP_RDSR 0x05 /* EEPROM Read Status Register */
#define PCC_EEP_WREN 0x06 /* EEPROM Write Enable */
/* EEPROM Status Register bits */
#define PCC_EEP_SR_WEN 0x02 /* EEPROM SR Write Enable bit */
#define PCC_EEP_SR_WIP 0x01 /* EEPROM SR Write In Progress bit */
/*
* The board configuration is probably following:
* RX1 is connected to ground.
* TX1 is not connected.
* CLKO is not connected.
* Setting the OCR register to 0xDA is a good idea.
* This means normal output mode, push-pull and the correct polarity.
*/
#define PCC_OCR (OCR_TX0_PUSHPULL | OCR_TX1_PUSHPULL)
/*
* In the CDR register, you should set CBP to 1.
* You will probably also want to set the clock divider value to 7
* (meaning direct oscillator output) because the second SJA1000 chip
* is driven by the first one CLKOUT output.
*/
#define PCC_CDR (CDR_CBP | CDR_CLKOUT_MASK)
struct pcan_channel {
struct net_device *netdev;
unsigned long prev_rx_bytes;
unsigned long prev_tx_bytes;
};
/* PCAN-PC Card private structure */
struct pcan_pccard {
struct pcmcia_device *pdev;
int chan_count;
struct pcan_channel channel[PCC_CHAN_MAX];
u8 ccr;
u8 fw_major;
u8 fw_minor;
void __iomem *ioport_addr;
struct timer_list led_timer;
};
static struct pcmcia_device_id pcan_table[] = {
PCMCIA_DEVICE_MANF_CARD(PCC_MANF_ID, PCC_CARD_ID),
PCMCIA_DEVICE_NULL,
};
MODULE_DEVICE_TABLE(pcmcia, pcan_table);
static void pcan_set_leds(struct pcan_pccard *card, u8 mask, u8 state);
/*
* start timer which controls leds state
*/
static void pcan_start_led_timer(struct pcan_pccard *card)
{
if (!timer_pending(&card->led_timer))
mod_timer(&card->led_timer, jiffies + HZ);
}
/*
* stop the timer which controls leds state
*/
static void pcan_stop_led_timer(struct pcan_pccard *card)
{
del_timer_sync(&card->led_timer);
}
/*
* read a sja1000 register
*/
static u8 pcan_read_canreg(const struct sja1000_priv *priv, int port)
{
return ioread8(priv->reg_base + port);
}
/*
* write a sja1000 register
*/
static void pcan_write_canreg(const struct sja1000_priv *priv, int port, u8 v)
{
struct pcan_pccard *card = priv->priv;
int c = (priv->reg_base - card->ioport_addr) / PCC_CHAN_SIZE;
/* sja1000 register changes control the leds state */
if (port == SJA1000_MOD)
switch (v) {
case MOD_RM:
/* Reset Mode: set led on */
pcan_set_leds(card, PCC_LED(c), PCC_LED_ON);
break;
case 0x00:
/* Normal Mode: led slow blinking and start led timer */
pcan_set_leds(card, PCC_LED(c), PCC_LED_SLOW);
pcan_start_led_timer(card);
break;
default:
break;
}
iowrite8(v, priv->reg_base + port);
}
/*
* read a register from the common area
*/
static u8 pcan_read_reg(struct pcan_pccard *card, int port)
{
return ioread8(card->ioport_addr + PCC_COMN_OFF + port);
}
/*
* write a register into the common area
*/
static void pcan_write_reg(struct pcan_pccard *card, int port, u8 v)
{
/* cache ccr value */
if (port == PCC_CCR) {
if (card->ccr == v)
return;
card->ccr = v;
}
iowrite8(v, card->ioport_addr + PCC_COMN_OFF + port);
}
/*
* check whether the card is present by checking its fw version numbers
* against values read at probing time.
*/
static inline int pcan_pccard_present(struct pcan_pccard *card)
{
return ((pcan_read_reg(card, PCC_FW_MAJOR) == card->fw_major) &&
(pcan_read_reg(card, PCC_FW_MINOR) == card->fw_minor));
}
/*
* wait for SPI engine while it is busy
*/
static int pcan_wait_spi_busy(struct pcan_pccard *card)
{
unsigned long timeout = jiffies +
msecs_to_jiffies(PCC_SPI_MAX_BUSY_WAIT_MS) + 1;
/* be sure to read status at least once after sleeping */
while (pcan_read_reg(card, PCC_CSR) & PCC_CSR_SPI_BUSY) {
if (time_after(jiffies, timeout))
return -EBUSY;
schedule();
}
return 0;
}
/*
* write data in device eeprom
*/
static int pcan_write_eeprom(struct pcan_pccard *card, u16 addr, u8 v)
{
u8 status;
int err, i;
/* write instruction enabling write */
pcan_write_reg(card, PCC_SPI_IR, PCC_EEP_WREN);
err = pcan_wait_spi_busy(card);
if (err)
goto we_spi_err;
/* wait until write enabled */
for (i = 0; i < PCC_WRITE_MAX_LOOP; i++) {
/* write instruction reading the status register */
pcan_write_reg(card, PCC_SPI_IR, PCC_EEP_RDSR);
err = pcan_wait_spi_busy(card);
if (err)
goto we_spi_err;
/* get status register value and check write enable bit */
status = pcan_read_reg(card, PCC_SPI_DIR);
if (status & PCC_EEP_SR_WEN)
break;
}
if (i >= PCC_WRITE_MAX_LOOP) {
dev_err(&card->pdev->dev,
"stop waiting to be allowed to write in eeprom\n");
return -EIO;
}
/* set address and data */
pcan_write_reg(card, PCC_SPI_ADR, addr & 0xff);
pcan_write_reg(card, PCC_SPI_DOR, v);
/*
* write instruction with bit[3] set according to address value:
* if addr refers to upper half of the memory array: bit[3] = 1
*/
pcan_write_reg(card, PCC_SPI_IR, PCC_EEP_WRITE(addr));
err = pcan_wait_spi_busy(card);
if (err)
goto we_spi_err;
/* wait while write in progress */
for (i = 0; i < PCC_WRITE_MAX_LOOP; i++) {
/* write instruction reading the status register */
pcan_write_reg(card, PCC_SPI_IR, PCC_EEP_RDSR);
err = pcan_wait_spi_busy(card);
if (err)
goto we_spi_err;
/* get status register value and check write in progress bit */
status = pcan_read_reg(card, PCC_SPI_DIR);
if (!(status & PCC_EEP_SR_WIP))
break;
}
if (i >= PCC_WRITE_MAX_LOOP) {
dev_err(&card->pdev->dev,
"stop waiting for write in eeprom to complete\n");
return -EIO;
}
/* write instruction disabling write */
pcan_write_reg(card, PCC_SPI_IR, PCC_EEP_WRDI);
err = pcan_wait_spi_busy(card);
if (err)
goto we_spi_err;
return 0;
we_spi_err:
dev_err(&card->pdev->dev,
"stop waiting (spi engine always busy) err %d\n", err);
return err;
}
static void pcan_set_leds(struct pcan_pccard *card, u8 led_mask, u8 state)
{
u8 ccr = card->ccr;
int i;
for (i = 0; i < card->chan_count; i++)
if (led_mask & PCC_LED(i)) {
/* clear corresponding led bits in ccr */
ccr &= ~PCC_CCR_LED_MASK_CHAN(i);
/* then set new bits */
ccr |= PCC_CCR_LED_CHAN(state, i);
}
/* real write only if something has changed in ccr */
pcan_write_reg(card, PCC_CCR, ccr);
}
/*
* enable/disable CAN connectors power
*/
static inline void pcan_set_can_power(struct pcan_pccard *card, int onoff)
{
int err;
err = pcan_write_eeprom(card, 0, !!onoff);
if (err)
dev_err(&card->pdev->dev,
"failed setting power %s to can connectors (err %d)\n",
(onoff) ? "on" : "off", err);
}
/*
* set leds state according to channel activity
*/
static void pcan_led_timer(unsigned long arg)
{
struct pcan_pccard *card = (struct pcan_pccard *)arg;
struct net_device *netdev;
int i, up_count = 0;
u8 ccr;
ccr = card->ccr;
for (i = 0; i < card->chan_count; i++) {
/* default is: not configured */
ccr &= ~PCC_CCR_LED_MASK_CHAN(i);
ccr |= PCC_CCR_LED_ON_CHAN(i);
netdev = card->channel[i].netdev;
if (!netdev || !(netdev->flags & IFF_UP))
continue;
up_count++;
/* no activity (but configured) */
ccr &= ~PCC_CCR_LED_MASK_CHAN(i);
ccr |= PCC_CCR_LED_SLOW_CHAN(i);
/* if bytes counters changed, set fast blinking led */
if (netdev->stats.rx_bytes != card->channel[i].prev_rx_bytes) {
card->channel[i].prev_rx_bytes = netdev->stats.rx_bytes;
ccr &= ~PCC_CCR_LED_MASK_CHAN(i);
ccr |= PCC_CCR_LED_FAST_CHAN(i);
}
if (netdev->stats.tx_bytes != card->channel[i].prev_tx_bytes) {
card->channel[i].prev_tx_bytes = netdev->stats.tx_bytes;
ccr &= ~PCC_CCR_LED_MASK_CHAN(i);
ccr |= PCC_CCR_LED_FAST_CHAN(i);
}
}
/* write the new leds state */
pcan_write_reg(card, PCC_CCR, ccr);
/* restart timer (except if no more configured channels) */
if (up_count)
mod_timer(&card->led_timer, jiffies + HZ);
}
/*
* interrupt service routine
*/
static irqreturn_t pcan_isr(int irq, void *dev_id)
{
struct pcan_pccard *card = dev_id;
int irq_handled;
/* prevent from infinite loop */
for (irq_handled = 0; irq_handled < PCC_ISR_MAX_LOOP; irq_handled++) {
/* handle shared interrupt and next loop */
int nothing_to_handle = 1;
int i;
/* check interrupt for each channel */
for (i = 0; i < card->chan_count; i++) {
struct net_device *netdev;
/*
* check whether the card is present before calling
* sja1000_interrupt() to speed up hotplug detection
*/
if (!pcan_pccard_present(card)) {
/* card unplugged during isr */
return IRQ_NONE;
}
/*
* should check whether all or SJA1000_MAX_IRQ
* interrupts have been handled: loop again to be sure.
*/
netdev = card->channel[i].netdev;
if (netdev &&
sja1000_interrupt(irq, netdev) == IRQ_HANDLED)
nothing_to_handle = 0;
}
if (nothing_to_handle)
break;
}
return (irq_handled) ? IRQ_HANDLED : IRQ_NONE;
}
/*
* free all resources used by the channels and switch off leds and can power
*/
static void pcan_free_channels(struct pcan_pccard *card)
{
int i;
u8 led_mask = 0;
for (i = 0; i < card->chan_count; i++) {
struct net_device *netdev;
char name[IFNAMSIZ];
led_mask |= PCC_LED(i);
netdev = card->channel[i].netdev;
if (!netdev)
continue;
strncpy(name, netdev->name, IFNAMSIZ);
unregister_sja1000dev(netdev);
free_sja1000dev(netdev);
dev_info(&card->pdev->dev, "%s removed\n", name);
}
/* do it only if device not removed */
if (pcan_pccard_present(card)) {
pcan_set_leds(card, led_mask, PCC_LED_OFF);
pcan_set_can_power(card, 0);
}
}
/*
* check if a CAN controller is present at the specified location
*/
static inline int pcan_channel_present(struct sja1000_priv *priv)
{
/* make sure SJA1000 is in reset mode */
pcan_write_canreg(priv, SJA1000_MOD, 1);
pcan_write_canreg(priv, SJA1000_CDR, CDR_PELICAN);
/* read reset-values */
if (pcan_read_canreg(priv, SJA1000_CDR) == CDR_PELICAN)
return 1;
return 0;
}
static int pcan_add_channels(struct pcan_pccard *card)
{
struct pcmcia_device *pdev = card->pdev;
int i, err = 0;
u8 ccr = PCC_CCR_INIT;
/* init common registers (reset channels and leds off) */
card->ccr = ~ccr;
pcan_write_reg(card, PCC_CCR, ccr);
/* wait 2ms before unresetting channels */
mdelay(2);
ccr &= ~PCC_CCR_RST_ALL;
pcan_write_reg(card, PCC_CCR, ccr);
/* create one network device per channel detected */
for (i = 0; i < ARRAY_SIZE(card->channel); i++) {
struct net_device *netdev;
struct sja1000_priv *priv;
netdev = alloc_sja1000dev(0);
if (!netdev) {
err = -ENOMEM;
break;
}
/* update linkages */
priv = netdev_priv(netdev);
priv->priv = card;
SET_NETDEV_DEV(netdev, &pdev->dev);
priv->irq_flags = IRQF_SHARED;
netdev->irq = pdev->irq;
priv->reg_base = card->ioport_addr + PCC_CHAN_OFF(i);
/* check if channel is present */
if (!pcan_channel_present(priv)) {
dev_err(&pdev->dev, "channel %d not present\n", i);
free_sja1000dev(netdev);
continue;
}
priv->read_reg = pcan_read_canreg;
priv->write_reg = pcan_write_canreg;
priv->can.clock.freq = PCC_CAN_CLOCK;
priv->ocr = PCC_OCR;
priv->cdr = PCC_CDR;
/* Neither a slave device distributes the clock */
if (i > 0)
priv->cdr |= CDR_CLK_OFF;
priv->flags |= SJA1000_CUSTOM_IRQ_HANDLER;
/* register SJA1000 device */
err = register_sja1000dev(netdev);
if (err) {
free_sja1000dev(netdev);
continue;
}
card->channel[i].netdev = netdev;
card->chan_count++;
/* set corresponding led on in the new ccr */
ccr &= ~PCC_CCR_LED_OFF_CHAN(i);
dev_info(&pdev->dev,
"%s on channel %d at 0x%p irq %d\n",
netdev->name, i, priv->reg_base, pdev->irq);
}
/* write new ccr (change leds state) */
pcan_write_reg(card, PCC_CCR, ccr);
return err;
}
static int pcan_conf_check(struct pcmcia_device *pdev, void *priv_data)
{
pdev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
pdev->resource[0]->flags |= IO_DATA_PATH_WIDTH_8; /* only */
pdev->io_lines = 10;
/* This reserves IO space but doesn't actually enable it */
return pcmcia_request_io(pdev);
}
/*
* free all resources used by the device
*/
static void pcan_free(struct pcmcia_device *pdev)
{
struct pcan_pccard *card = pdev->priv;
if (!card)
return;
free_irq(pdev->irq, card);
pcan_stop_led_timer(card);
pcan_free_channels(card);
ioport_unmap(card->ioport_addr);
kfree(card);
pdev->priv = NULL;
}
/*
* setup PCMCIA socket and probe for PEAK-System PC-CARD
*/
static int pcan_probe(struct pcmcia_device *pdev)
{
struct pcan_pccard *card;
int err;
pdev->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO;
err = pcmcia_loop_config(pdev, pcan_conf_check, NULL);
if (err) {
dev_err(&pdev->dev, "pcmcia_loop_config() error %d\n", err);
goto probe_err_1;
}
if (!pdev->irq) {
dev_err(&pdev->dev, "no irq assigned\n");
err = -ENODEV;
goto probe_err_1;
}
err = pcmcia_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "pcmcia_enable_device failed err=%d\n",
err);
goto probe_err_1;
}
card = kzalloc(sizeof(struct pcan_pccard), GFP_KERNEL);
if (!card) {
err = -ENOMEM;
goto probe_err_2;
}
card->pdev = pdev;
pdev->priv = card;
/* sja1000 api uses iomem */
card->ioport_addr = ioport_map(pdev->resource[0]->start,
resource_size(pdev->resource[0]));
if (!card->ioport_addr) {
dev_err(&pdev->dev, "couldn't map io port into io memory\n");
err = -ENOMEM;
goto probe_err_3;
}
card->fw_major = pcan_read_reg(card, PCC_FW_MAJOR);
card->fw_minor = pcan_read_reg(card, PCC_FW_MINOR);
/* display board name and firware version */
dev_info(&pdev->dev, "PEAK-System pcmcia card %s fw %d.%d\n",
pdev->prod_id[1] ? pdev->prod_id[1] : "PCAN-PC Card",
card->fw_major, card->fw_minor);
/* detect available channels */
pcan_add_channels(card);
if (!card->chan_count) {
err = -ENOMEM;
goto probe_err_4;
}
/* init the timer which controls the leds */
init_timer(&card->led_timer);
card->led_timer.function = pcan_led_timer;
card->led_timer.data = (unsigned long)card;
/* request the given irq */
err = request_irq(pdev->irq, &pcan_isr, IRQF_SHARED, PCC_NAME, card);
if (err) {
dev_err(&pdev->dev, "couldn't request irq%d\n", pdev->irq);
goto probe_err_5;
}
/* power on the connectors */
pcan_set_can_power(card, 1);
return 0;
probe_err_5:
/* unregister can devices from network */
pcan_free_channels(card);
probe_err_4:
ioport_unmap(card->ioport_addr);
probe_err_3:
kfree(card);
pdev->priv = NULL;
probe_err_2:
pcmcia_disable_device(pdev);
probe_err_1:
return err;
}
/*
* release claimed resources
*/
static void pcan_remove(struct pcmcia_device *pdev)
{
pcan_free(pdev);
pcmcia_disable_device(pdev);
}
static struct pcmcia_driver pcan_driver = {
.name = PCC_NAME,
.probe = pcan_probe,
.remove = pcan_remove,
.id_table = pcan_table,
};
module_pcmcia_driver(pcan_driver);
| gpl-2.0 |
turtlepa/android_kernel_samsung_aries-old | sound/pci/via82xx_modem.c | 3589 | 35339 | /*
* ALSA modem driver for VIA VT82xx (South Bridge)
*
* VT82C686A/B/C, VT8233A/C, VT8235
*
* Copyright (c) 2000 Jaroslav Kysela <perex@perex.cz>
* Tjeerd.Mulder <Tjeerd.Mulder@fujitsu-siemens.com>
* 2002 Takashi Iwai <tiwai@suse.de>
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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
*
*/
/*
* Changes:
*
* Sep. 2, 2004 Sasha Khapyorsky <sashak@alsa-project.org>
* Modified from original audio driver 'via82xx.c' to support AC97
* modems.
*/
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/info.h>
#include <sound/ac97_codec.h>
#include <sound/initval.h>
#if 0
#define POINTER_DEBUG
#endif
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("VIA VT82xx modem");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{VIA,VT82C686A/B/C modem,pci}}");
static int index = -2; /* Exclude the first card */
static char *id = SNDRV_DEFAULT_STR1; /* ID for this card */
static int ac97_clock = 48000;
module_param(index, int, 0444);
MODULE_PARM_DESC(index, "Index value for VIA 82xx bridge.");
module_param(id, charp, 0444);
MODULE_PARM_DESC(id, "ID string for VIA 82xx bridge.");
module_param(ac97_clock, int, 0444);
MODULE_PARM_DESC(ac97_clock, "AC'97 codec clock (default 48000Hz).");
/* just for backward compatibility */
static int enable;
module_param(enable, bool, 0444);
/*
* Direct registers
*/
#define VIAREG(via, x) ((via)->port + VIA_REG_##x)
#define VIADEV_REG(viadev, x) ((viadev)->port + VIA_REG_##x)
/* common offsets */
#define VIA_REG_OFFSET_STATUS 0x00 /* byte - channel status */
#define VIA_REG_STAT_ACTIVE 0x80 /* RO */
#define VIA_REG_STAT_PAUSED 0x40 /* RO */
#define VIA_REG_STAT_TRIGGER_QUEUED 0x08 /* RO */
#define VIA_REG_STAT_STOPPED 0x04 /* RWC */
#define VIA_REG_STAT_EOL 0x02 /* RWC */
#define VIA_REG_STAT_FLAG 0x01 /* RWC */
#define VIA_REG_OFFSET_CONTROL 0x01 /* byte - channel control */
#define VIA_REG_CTRL_START 0x80 /* WO */
#define VIA_REG_CTRL_TERMINATE 0x40 /* WO */
#define VIA_REG_CTRL_AUTOSTART 0x20
#define VIA_REG_CTRL_PAUSE 0x08 /* RW */
#define VIA_REG_CTRL_INT_STOP 0x04
#define VIA_REG_CTRL_INT_EOL 0x02
#define VIA_REG_CTRL_INT_FLAG 0x01
#define VIA_REG_CTRL_RESET 0x01 /* RW - probably reset? undocumented */
#define VIA_REG_CTRL_INT (VIA_REG_CTRL_INT_FLAG | VIA_REG_CTRL_INT_EOL | VIA_REG_CTRL_AUTOSTART)
#define VIA_REG_OFFSET_TYPE 0x02 /* byte - channel type (686 only) */
#define VIA_REG_TYPE_AUTOSTART 0x80 /* RW - autostart at EOL */
#define VIA_REG_TYPE_16BIT 0x20 /* RW */
#define VIA_REG_TYPE_STEREO 0x10 /* RW */
#define VIA_REG_TYPE_INT_LLINE 0x00
#define VIA_REG_TYPE_INT_LSAMPLE 0x04
#define VIA_REG_TYPE_INT_LESSONE 0x08
#define VIA_REG_TYPE_INT_MASK 0x0c
#define VIA_REG_TYPE_INT_EOL 0x02
#define VIA_REG_TYPE_INT_FLAG 0x01
#define VIA_REG_OFFSET_TABLE_PTR 0x04 /* dword - channel table pointer */
#define VIA_REG_OFFSET_CURR_PTR 0x04 /* dword - channel current pointer */
#define VIA_REG_OFFSET_STOP_IDX 0x08 /* dword - stop index, channel type, sample rate */
#define VIA_REG_OFFSET_CURR_COUNT 0x0c /* dword - channel current count (24 bit) */
#define VIA_REG_OFFSET_CURR_INDEX 0x0f /* byte - channel current index (for via8233 only) */
#define DEFINE_VIA_REGSET(name,val) \
enum {\
VIA_REG_##name##_STATUS = (val),\
VIA_REG_##name##_CONTROL = (val) + 0x01,\
VIA_REG_##name##_TYPE = (val) + 0x02,\
VIA_REG_##name##_TABLE_PTR = (val) + 0x04,\
VIA_REG_##name##_CURR_PTR = (val) + 0x04,\
VIA_REG_##name##_STOP_IDX = (val) + 0x08,\
VIA_REG_##name##_CURR_COUNT = (val) + 0x0c,\
}
/* modem block */
DEFINE_VIA_REGSET(MO, 0x40);
DEFINE_VIA_REGSET(MI, 0x50);
/* AC'97 */
#define VIA_REG_AC97 0x80 /* dword */
#define VIA_REG_AC97_CODEC_ID_MASK (3<<30)
#define VIA_REG_AC97_CODEC_ID_SHIFT 30
#define VIA_REG_AC97_CODEC_ID_PRIMARY 0x00
#define VIA_REG_AC97_CODEC_ID_SECONDARY 0x01
#define VIA_REG_AC97_SECONDARY_VALID (1<<27)
#define VIA_REG_AC97_PRIMARY_VALID (1<<25)
#define VIA_REG_AC97_BUSY (1<<24)
#define VIA_REG_AC97_READ (1<<23)
#define VIA_REG_AC97_CMD_SHIFT 16
#define VIA_REG_AC97_CMD_MASK 0x7e
#define VIA_REG_AC97_DATA_SHIFT 0
#define VIA_REG_AC97_DATA_MASK 0xffff
#define VIA_REG_SGD_SHADOW 0x84 /* dword */
#define VIA_REG_SGD_STAT_PB_FLAG (1<<0)
#define VIA_REG_SGD_STAT_CP_FLAG (1<<1)
#define VIA_REG_SGD_STAT_FM_FLAG (1<<2)
#define VIA_REG_SGD_STAT_PB_EOL (1<<4)
#define VIA_REG_SGD_STAT_CP_EOL (1<<5)
#define VIA_REG_SGD_STAT_FM_EOL (1<<6)
#define VIA_REG_SGD_STAT_PB_STOP (1<<8)
#define VIA_REG_SGD_STAT_CP_STOP (1<<9)
#define VIA_REG_SGD_STAT_FM_STOP (1<<10)
#define VIA_REG_SGD_STAT_PB_ACTIVE (1<<12)
#define VIA_REG_SGD_STAT_CP_ACTIVE (1<<13)
#define VIA_REG_SGD_STAT_FM_ACTIVE (1<<14)
#define VIA_REG_SGD_STAT_MR_FLAG (1<<16)
#define VIA_REG_SGD_STAT_MW_FLAG (1<<17)
#define VIA_REG_SGD_STAT_MR_EOL (1<<20)
#define VIA_REG_SGD_STAT_MW_EOL (1<<21)
#define VIA_REG_SGD_STAT_MR_STOP (1<<24)
#define VIA_REG_SGD_STAT_MW_STOP (1<<25)
#define VIA_REG_SGD_STAT_MR_ACTIVE (1<<28)
#define VIA_REG_SGD_STAT_MW_ACTIVE (1<<29)
#define VIA_REG_GPI_STATUS 0x88
#define VIA_REG_GPI_INTR 0x8c
#define VIA_TBL_BIT_FLAG 0x40000000
#define VIA_TBL_BIT_EOL 0x80000000
/* pci space */
#define VIA_ACLINK_STAT 0x40
#define VIA_ACLINK_C11_READY 0x20
#define VIA_ACLINK_C10_READY 0x10
#define VIA_ACLINK_C01_READY 0x04 /* secondary codec ready */
#define VIA_ACLINK_LOWPOWER 0x02 /* low-power state */
#define VIA_ACLINK_C00_READY 0x01 /* primary codec ready */
#define VIA_ACLINK_CTRL 0x41
#define VIA_ACLINK_CTRL_ENABLE 0x80 /* 0: disable, 1: enable */
#define VIA_ACLINK_CTRL_RESET 0x40 /* 0: assert, 1: de-assert */
#define VIA_ACLINK_CTRL_SYNC 0x20 /* 0: release SYNC, 1: force SYNC hi */
#define VIA_ACLINK_CTRL_SDO 0x10 /* 0: release SDO, 1: force SDO hi */
#define VIA_ACLINK_CTRL_VRA 0x08 /* 0: disable VRA, 1: enable VRA */
#define VIA_ACLINK_CTRL_PCM 0x04 /* 0: disable PCM, 1: enable PCM */
#define VIA_ACLINK_CTRL_FM 0x02 /* via686 only */
#define VIA_ACLINK_CTRL_SB 0x01 /* via686 only */
#define VIA_ACLINK_CTRL_INIT (VIA_ACLINK_CTRL_ENABLE|\
VIA_ACLINK_CTRL_RESET|\
VIA_ACLINK_CTRL_PCM)
#define VIA_FUNC_ENABLE 0x42
#define VIA_FUNC_MIDI_PNP 0x80 /* FIXME: it's 0x40 in the datasheet! */
#define VIA_FUNC_MIDI_IRQMASK 0x40 /* FIXME: not documented! */
#define VIA_FUNC_RX2C_WRITE 0x20
#define VIA_FUNC_SB_FIFO_EMPTY 0x10
#define VIA_FUNC_ENABLE_GAME 0x08
#define VIA_FUNC_ENABLE_FM 0x04
#define VIA_FUNC_ENABLE_MIDI 0x02
#define VIA_FUNC_ENABLE_SB 0x01
#define VIA_PNP_CONTROL 0x43
#define VIA_MC97_CTRL 0x44
#define VIA_MC97_CTRL_ENABLE 0x80
#define VIA_MC97_CTRL_SECONDARY 0x40
#define VIA_MC97_CTRL_INIT (VIA_MC97_CTRL_ENABLE|\
VIA_MC97_CTRL_SECONDARY)
/*
* pcm stream
*/
struct snd_via_sg_table {
unsigned int offset;
unsigned int size;
} ;
#define VIA_TABLE_SIZE 255
struct viadev {
unsigned int reg_offset;
unsigned long port;
int direction; /* playback = 0, capture = 1 */
struct snd_pcm_substream *substream;
int running;
unsigned int tbl_entries; /* # descriptors */
struct snd_dma_buffer table;
struct snd_via_sg_table *idx_table;
/* for recovery from the unexpected pointer */
unsigned int lastpos;
unsigned int bufsize;
unsigned int bufsize2;
};
enum { TYPE_CARD_VIA82XX_MODEM = 1 };
#define VIA_MAX_MODEM_DEVS 2
struct via82xx_modem {
int irq;
unsigned long port;
unsigned int intr_mask; /* SGD_SHADOW mask to check interrupts */
struct pci_dev *pci;
struct snd_card *card;
unsigned int num_devs;
unsigned int playback_devno, capture_devno;
struct viadev devs[VIA_MAX_MODEM_DEVS];
struct snd_pcm *pcms[2];
struct snd_ac97_bus *ac97_bus;
struct snd_ac97 *ac97;
unsigned int ac97_clock;
unsigned int ac97_secondary; /* secondary AC'97 codec is present */
spinlock_t reg_lock;
struct snd_info_entry *proc_entry;
};
static DEFINE_PCI_DEVICE_TABLE(snd_via82xx_modem_ids) = {
{ PCI_VDEVICE(VIA, 0x3068), TYPE_CARD_VIA82XX_MODEM, },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, snd_via82xx_modem_ids);
/*
*/
/*
* allocate and initialize the descriptor buffers
* periods = number of periods
* fragsize = period size in bytes
*/
static int build_via_table(struct viadev *dev, struct snd_pcm_substream *substream,
struct pci_dev *pci,
unsigned int periods, unsigned int fragsize)
{
unsigned int i, idx, ofs, rest;
struct via82xx_modem *chip = snd_pcm_substream_chip(substream);
if (dev->table.area == NULL) {
/* the start of each lists must be aligned to 8 bytes,
* but the kernel pages are much bigger, so we don't care
*/
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci),
PAGE_ALIGN(VIA_TABLE_SIZE * 2 * 8),
&dev->table) < 0)
return -ENOMEM;
}
if (! dev->idx_table) {
dev->idx_table = kmalloc(sizeof(*dev->idx_table) * VIA_TABLE_SIZE, GFP_KERNEL);
if (! dev->idx_table)
return -ENOMEM;
}
/* fill the entries */
idx = 0;
ofs = 0;
for (i = 0; i < periods; i++) {
rest = fragsize;
/* fill descriptors for a period.
* a period can be split to several descriptors if it's
* over page boundary.
*/
do {
unsigned int r;
unsigned int flag;
unsigned int addr;
if (idx >= VIA_TABLE_SIZE) {
snd_printk(KERN_ERR "via82xx: too much table size!\n");
return -EINVAL;
}
addr = snd_pcm_sgbuf_get_addr(substream, ofs);
((u32 *)dev->table.area)[idx << 1] = cpu_to_le32(addr);
r = PAGE_SIZE - (ofs % PAGE_SIZE);
if (rest < r)
r = rest;
rest -= r;
if (! rest) {
if (i == periods - 1)
flag = VIA_TBL_BIT_EOL; /* buffer boundary */
else
flag = VIA_TBL_BIT_FLAG; /* period boundary */
} else
flag = 0; /* period continues to the next */
/*
printk(KERN_DEBUG "via: tbl %d: at %d size %d "
"(rest %d)\n", idx, ofs, r, rest);
*/
((u32 *)dev->table.area)[(idx<<1) + 1] = cpu_to_le32(r | flag);
dev->idx_table[idx].offset = ofs;
dev->idx_table[idx].size = r;
ofs += r;
idx++;
} while (rest > 0);
}
dev->tbl_entries = idx;
dev->bufsize = periods * fragsize;
dev->bufsize2 = dev->bufsize / 2;
return 0;
}
static int clean_via_table(struct viadev *dev, struct snd_pcm_substream *substream,
struct pci_dev *pci)
{
if (dev->table.area) {
snd_dma_free_pages(&dev->table);
dev->table.area = NULL;
}
kfree(dev->idx_table);
dev->idx_table = NULL;
return 0;
}
/*
* Basic I/O
*/
static inline unsigned int snd_via82xx_codec_xread(struct via82xx_modem *chip)
{
return inl(VIAREG(chip, AC97));
}
static inline void snd_via82xx_codec_xwrite(struct via82xx_modem *chip, unsigned int val)
{
outl(val, VIAREG(chip, AC97));
}
static int snd_via82xx_codec_ready(struct via82xx_modem *chip, int secondary)
{
unsigned int timeout = 1000; /* 1ms */
unsigned int val;
while (timeout-- > 0) {
udelay(1);
if (!((val = snd_via82xx_codec_xread(chip)) & VIA_REG_AC97_BUSY))
return val & 0xffff;
}
snd_printk(KERN_ERR "codec_ready: codec %i is not ready [0x%x]\n",
secondary, snd_via82xx_codec_xread(chip));
return -EIO;
}
static int snd_via82xx_codec_valid(struct via82xx_modem *chip, int secondary)
{
unsigned int timeout = 1000; /* 1ms */
unsigned int val, val1;
unsigned int stat = !secondary ? VIA_REG_AC97_PRIMARY_VALID :
VIA_REG_AC97_SECONDARY_VALID;
while (timeout-- > 0) {
val = snd_via82xx_codec_xread(chip);
val1 = val & (VIA_REG_AC97_BUSY | stat);
if (val1 == stat)
return val & 0xffff;
udelay(1);
}
return -EIO;
}
static void snd_via82xx_codec_wait(struct snd_ac97 *ac97)
{
struct via82xx_modem *chip = ac97->private_data;
int err;
err = snd_via82xx_codec_ready(chip, ac97->num);
/* here we need to wait fairly for long time.. */
msleep(500);
}
static void snd_via82xx_codec_write(struct snd_ac97 *ac97,
unsigned short reg,
unsigned short val)
{
struct via82xx_modem *chip = ac97->private_data;
unsigned int xval;
if(reg == AC97_GPIO_STATUS) {
outl(val, VIAREG(chip, GPI_STATUS));
return;
}
xval = !ac97->num ? VIA_REG_AC97_CODEC_ID_PRIMARY : VIA_REG_AC97_CODEC_ID_SECONDARY;
xval <<= VIA_REG_AC97_CODEC_ID_SHIFT;
xval |= reg << VIA_REG_AC97_CMD_SHIFT;
xval |= val << VIA_REG_AC97_DATA_SHIFT;
snd_via82xx_codec_xwrite(chip, xval);
snd_via82xx_codec_ready(chip, ac97->num);
}
static unsigned short snd_via82xx_codec_read(struct snd_ac97 *ac97, unsigned short reg)
{
struct via82xx_modem *chip = ac97->private_data;
unsigned int xval, val = 0xffff;
int again = 0;
xval = ac97->num << VIA_REG_AC97_CODEC_ID_SHIFT;
xval |= ac97->num ? VIA_REG_AC97_SECONDARY_VALID : VIA_REG_AC97_PRIMARY_VALID;
xval |= VIA_REG_AC97_READ;
xval |= (reg & 0x7f) << VIA_REG_AC97_CMD_SHIFT;
while (1) {
if (again++ > 3) {
snd_printk(KERN_ERR "codec_read: codec %i is not valid [0x%x]\n",
ac97->num, snd_via82xx_codec_xread(chip));
return 0xffff;
}
snd_via82xx_codec_xwrite(chip, xval);
udelay (20);
if (snd_via82xx_codec_valid(chip, ac97->num) >= 0) {
udelay(25);
val = snd_via82xx_codec_xread(chip);
break;
}
}
return val & 0xffff;
}
static void snd_via82xx_channel_reset(struct via82xx_modem *chip, struct viadev *viadev)
{
outb(VIA_REG_CTRL_PAUSE | VIA_REG_CTRL_TERMINATE | VIA_REG_CTRL_RESET,
VIADEV_REG(viadev, OFFSET_CONTROL));
inb(VIADEV_REG(viadev, OFFSET_CONTROL));
udelay(50);
/* disable interrupts */
outb(0x00, VIADEV_REG(viadev, OFFSET_CONTROL));
/* clear interrupts */
outb(0x03, VIADEV_REG(viadev, OFFSET_STATUS));
outb(0x00, VIADEV_REG(viadev, OFFSET_TYPE)); /* for via686 */
// outl(0, VIADEV_REG(viadev, OFFSET_CURR_PTR));
viadev->lastpos = 0;
}
/*
* Interrupt handler
*/
static irqreturn_t snd_via82xx_interrupt(int irq, void *dev_id)
{
struct via82xx_modem *chip = dev_id;
unsigned int status;
unsigned int i;
status = inl(VIAREG(chip, SGD_SHADOW));
if (! (status & chip->intr_mask)) {
return IRQ_NONE;
}
// _skip_sgd:
/* check status for each stream */
spin_lock(&chip->reg_lock);
for (i = 0; i < chip->num_devs; i++) {
struct viadev *viadev = &chip->devs[i];
unsigned char c_status = inb(VIADEV_REG(viadev, OFFSET_STATUS));
c_status &= (VIA_REG_STAT_EOL|VIA_REG_STAT_FLAG|VIA_REG_STAT_STOPPED);
if (! c_status)
continue;
if (viadev->substream && viadev->running) {
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(viadev->substream);
spin_lock(&chip->reg_lock);
}
outb(c_status, VIADEV_REG(viadev, OFFSET_STATUS)); /* ack */
}
spin_unlock(&chip->reg_lock);
return IRQ_HANDLED;
}
/*
* PCM callbacks
*/
/*
* trigger callback
*/
static int snd_via82xx_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct via82xx_modem *chip = snd_pcm_substream_chip(substream);
struct viadev *viadev = substream->runtime->private_data;
unsigned char val = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_SUSPEND:
val |= VIA_REG_CTRL_START;
viadev->running = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
val = VIA_REG_CTRL_TERMINATE;
viadev->running = 0;
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
val |= VIA_REG_CTRL_PAUSE;
viadev->running = 0;
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
viadev->running = 1;
break;
default:
return -EINVAL;
}
outb(val, VIADEV_REG(viadev, OFFSET_CONTROL));
if (cmd == SNDRV_PCM_TRIGGER_STOP)
snd_via82xx_channel_reset(chip, viadev);
return 0;
}
/*
* pointer callbacks
*/
/*
* calculate the linear position at the given sg-buffer index and the rest count
*/
#define check_invalid_pos(viadev,pos) \
((pos) < viadev->lastpos && ((pos) >= viadev->bufsize2 ||\
viadev->lastpos < viadev->bufsize2))
static inline unsigned int calc_linear_pos(struct viadev *viadev, unsigned int idx,
unsigned int count)
{
unsigned int size, res;
size = viadev->idx_table[idx].size;
res = viadev->idx_table[idx].offset + size - count;
/* check the validity of the calculated position */
if (size < count) {
snd_printd(KERN_ERR "invalid via82xx_cur_ptr (size = %d, count = %d)\n",
(int)size, (int)count);
res = viadev->lastpos;
} else if (check_invalid_pos(viadev, res)) {
#ifdef POINTER_DEBUG
printk(KERN_DEBUG "fail: idx = %i/%i, lastpos = 0x%x, "
"bufsize2 = 0x%x, offsize = 0x%x, size = 0x%x, "
"count = 0x%x\n", idx, viadev->tbl_entries, viadev->lastpos,
viadev->bufsize2, viadev->idx_table[idx].offset,
viadev->idx_table[idx].size, count);
#endif
if (count && size < count) {
snd_printd(KERN_ERR "invalid via82xx_cur_ptr, "
"using last valid pointer\n");
res = viadev->lastpos;
} else {
if (! count)
/* bogus count 0 on the DMA boundary? */
res = viadev->idx_table[idx].offset;
else
/* count register returns full size
* when end of buffer is reached
*/
res = viadev->idx_table[idx].offset + size;
if (check_invalid_pos(viadev, res)) {
snd_printd(KERN_ERR "invalid via82xx_cur_ptr (2), "
"using last valid pointer\n");
res = viadev->lastpos;
}
}
}
viadev->lastpos = res; /* remember the last position */
if (res >= viadev->bufsize)
res -= viadev->bufsize;
return res;
}
/*
* get the current pointer on via686
*/
static snd_pcm_uframes_t snd_via686_pcm_pointer(struct snd_pcm_substream *substream)
{
struct via82xx_modem *chip = snd_pcm_substream_chip(substream);
struct viadev *viadev = substream->runtime->private_data;
unsigned int idx, ptr, count, res;
if (snd_BUG_ON(!viadev->tbl_entries))
return 0;
if (!(inb(VIADEV_REG(viadev, OFFSET_STATUS)) & VIA_REG_STAT_ACTIVE))
return 0;
spin_lock(&chip->reg_lock);
count = inl(VIADEV_REG(viadev, OFFSET_CURR_COUNT)) & 0xffffff;
/* The via686a does not have the current index register,
* so we need to calculate the index from CURR_PTR.
*/
ptr = inl(VIADEV_REG(viadev, OFFSET_CURR_PTR));
if (ptr <= (unsigned int)viadev->table.addr)
idx = 0;
else /* CURR_PTR holds the address + 8 */
idx = ((ptr - (unsigned int)viadev->table.addr) / 8 - 1) %
viadev->tbl_entries;
res = calc_linear_pos(viadev, idx, count);
spin_unlock(&chip->reg_lock);
return bytes_to_frames(substream->runtime, res);
}
/*
* hw_params callback:
* allocate the buffer and build up the buffer description table
*/
static int snd_via82xx_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct via82xx_modem *chip = snd_pcm_substream_chip(substream);
struct viadev *viadev = substream->runtime->private_data;
int err;
err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
if (err < 0)
return err;
err = build_via_table(viadev, substream, chip->pci,
params_periods(hw_params),
params_period_bytes(hw_params));
if (err < 0)
return err;
snd_ac97_write(chip->ac97, AC97_LINE1_RATE, params_rate(hw_params));
snd_ac97_write(chip->ac97, AC97_LINE1_LEVEL, 0);
return 0;
}
/*
* hw_free callback:
* clean up the buffer description table and release the buffer
*/
static int snd_via82xx_hw_free(struct snd_pcm_substream *substream)
{
struct via82xx_modem *chip = snd_pcm_substream_chip(substream);
struct viadev *viadev = substream->runtime->private_data;
clean_via_table(viadev, substream, chip->pci);
snd_pcm_lib_free_pages(substream);
return 0;
}
/*
* set up the table pointer
*/
static void snd_via82xx_set_table_ptr(struct via82xx_modem *chip, struct viadev *viadev)
{
snd_via82xx_codec_ready(chip, chip->ac97_secondary);
outl((u32)viadev->table.addr, VIADEV_REG(viadev, OFFSET_TABLE_PTR));
udelay(20);
snd_via82xx_codec_ready(chip, chip->ac97_secondary);
}
/*
* prepare callback for playback and capture
*/
static int snd_via82xx_pcm_prepare(struct snd_pcm_substream *substream)
{
struct via82xx_modem *chip = snd_pcm_substream_chip(substream);
struct viadev *viadev = substream->runtime->private_data;
snd_via82xx_channel_reset(chip, viadev);
/* this must be set after channel_reset */
snd_via82xx_set_table_ptr(chip, viadev);
outb(VIA_REG_TYPE_AUTOSTART|VIA_REG_TYPE_INT_EOL|VIA_REG_TYPE_INT_FLAG,
VIADEV_REG(viadev, OFFSET_TYPE));
return 0;
}
/*
* pcm hardware definition, identical for both playback and capture
*/
static struct snd_pcm_hardware snd_via82xx_hw =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
/* SNDRV_PCM_INFO_RESUME | */
SNDRV_PCM_INFO_PAUSE),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_KNOT,
.rate_min = 8000,
.rate_max = 16000,
.channels_min = 1,
.channels_max = 1,
.buffer_bytes_max = 128 * 1024,
.period_bytes_min = 32,
.period_bytes_max = 128 * 1024,
.periods_min = 2,
.periods_max = VIA_TABLE_SIZE / 2,
.fifo_size = 0,
};
/*
* open callback skeleton
*/
static int snd_via82xx_modem_pcm_open(struct via82xx_modem *chip, struct viadev *viadev,
struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
static unsigned int rates[] = { 8000, 9600, 12000, 16000 };
static struct snd_pcm_hw_constraint_list hw_constraints_rates = {
.count = ARRAY_SIZE(rates),
.list = rates,
.mask = 0,
};
runtime->hw = snd_via82xx_hw;
if ((err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&hw_constraints_rates)) < 0)
return err;
/* we may remove following constaint when we modify table entries
in interrupt */
if ((err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS)) < 0)
return err;
runtime->private_data = viadev;
viadev->substream = substream;
return 0;
}
/*
* open callback for playback
*/
static int snd_via82xx_playback_open(struct snd_pcm_substream *substream)
{
struct via82xx_modem *chip = snd_pcm_substream_chip(substream);
struct viadev *viadev = &chip->devs[chip->playback_devno + substream->number];
return snd_via82xx_modem_pcm_open(chip, viadev, substream);
}
/*
* open callback for capture
*/
static int snd_via82xx_capture_open(struct snd_pcm_substream *substream)
{
struct via82xx_modem *chip = snd_pcm_substream_chip(substream);
struct viadev *viadev = &chip->devs[chip->capture_devno + substream->pcm->device];
return snd_via82xx_modem_pcm_open(chip, viadev, substream);
}
/*
* close callback
*/
static int snd_via82xx_pcm_close(struct snd_pcm_substream *substream)
{
struct viadev *viadev = substream->runtime->private_data;
viadev->substream = NULL;
return 0;
}
/* via686 playback callbacks */
static struct snd_pcm_ops snd_via686_playback_ops = {
.open = snd_via82xx_playback_open,
.close = snd_via82xx_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_via82xx_hw_params,
.hw_free = snd_via82xx_hw_free,
.prepare = snd_via82xx_pcm_prepare,
.trigger = snd_via82xx_pcm_trigger,
.pointer = snd_via686_pcm_pointer,
.page = snd_pcm_sgbuf_ops_page,
};
/* via686 capture callbacks */
static struct snd_pcm_ops snd_via686_capture_ops = {
.open = snd_via82xx_capture_open,
.close = snd_via82xx_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_via82xx_hw_params,
.hw_free = snd_via82xx_hw_free,
.prepare = snd_via82xx_pcm_prepare,
.trigger = snd_via82xx_pcm_trigger,
.pointer = snd_via686_pcm_pointer,
.page = snd_pcm_sgbuf_ops_page,
};
static void init_viadev(struct via82xx_modem *chip, int idx, unsigned int reg_offset,
int direction)
{
chip->devs[idx].reg_offset = reg_offset;
chip->devs[idx].direction = direction;
chip->devs[idx].port = chip->port + reg_offset;
}
/*
* create a pcm instance for via686a/b
*/
static int __devinit snd_via686_pcm_new(struct via82xx_modem *chip)
{
struct snd_pcm *pcm;
int err;
chip->playback_devno = 0;
chip->capture_devno = 1;
chip->num_devs = 2;
chip->intr_mask = 0x330000; /* FLAGS | EOL for MR, MW */
err = snd_pcm_new(chip->card, chip->card->shortname, 0, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_via686_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_via686_capture_ops);
pcm->dev_class = SNDRV_PCM_CLASS_MODEM;
pcm->private_data = chip;
strcpy(pcm->name, chip->card->shortname);
chip->pcms[0] = pcm;
init_viadev(chip, 0, VIA_REG_MO_STATUS, 0);
init_viadev(chip, 1, VIA_REG_MI_STATUS, 1);
if ((err = snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV_SG,
snd_dma_pci_data(chip->pci),
64*1024, 128*1024)) < 0)
return err;
return 0;
}
/*
* Mixer part
*/
static void snd_via82xx_mixer_free_ac97_bus(struct snd_ac97_bus *bus)
{
struct via82xx_modem *chip = bus->private_data;
chip->ac97_bus = NULL;
}
static void snd_via82xx_mixer_free_ac97(struct snd_ac97 *ac97)
{
struct via82xx_modem *chip = ac97->private_data;
chip->ac97 = NULL;
}
static int __devinit snd_via82xx_mixer_new(struct via82xx_modem *chip)
{
struct snd_ac97_template ac97;
int err;
static struct snd_ac97_bus_ops ops = {
.write = snd_via82xx_codec_write,
.read = snd_via82xx_codec_read,
.wait = snd_via82xx_codec_wait,
};
if ((err = snd_ac97_bus(chip->card, 0, &ops, chip, &chip->ac97_bus)) < 0)
return err;
chip->ac97_bus->private_free = snd_via82xx_mixer_free_ac97_bus;
chip->ac97_bus->clock = chip->ac97_clock;
memset(&ac97, 0, sizeof(ac97));
ac97.private_data = chip;
ac97.private_free = snd_via82xx_mixer_free_ac97;
ac97.pci = chip->pci;
ac97.scaps = AC97_SCAP_SKIP_AUDIO | AC97_SCAP_POWER_SAVE;
ac97.num = chip->ac97_secondary;
if ((err = snd_ac97_mixer(chip->ac97_bus, &ac97, &chip->ac97)) < 0)
return err;
return 0;
}
/*
* proc interface
*/
static void snd_via82xx_proc_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer)
{
struct via82xx_modem *chip = entry->private_data;
int i;
snd_iprintf(buffer, "%s\n\n", chip->card->longname);
for (i = 0; i < 0xa0; i += 4) {
snd_iprintf(buffer, "%02x: %08x\n", i, inl(chip->port + i));
}
}
static void __devinit snd_via82xx_proc_init(struct via82xx_modem *chip)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(chip->card, "via82xx", &entry))
snd_info_set_text_ops(entry, chip, snd_via82xx_proc_read);
}
/*
*
*/
static int snd_via82xx_chip_init(struct via82xx_modem *chip)
{
unsigned int val;
unsigned long end_time;
unsigned char pval;
pci_read_config_byte(chip->pci, VIA_MC97_CTRL, &pval);
if((pval & VIA_MC97_CTRL_INIT) != VIA_MC97_CTRL_INIT) {
pci_write_config_byte(chip->pci, 0x44, pval|VIA_MC97_CTRL_INIT);
udelay(100);
}
pci_read_config_byte(chip->pci, VIA_ACLINK_STAT, &pval);
if (! (pval & VIA_ACLINK_C00_READY)) { /* codec not ready? */
/* deassert ACLink reset, force SYNC */
pci_write_config_byte(chip->pci, VIA_ACLINK_CTRL,
VIA_ACLINK_CTRL_ENABLE |
VIA_ACLINK_CTRL_RESET |
VIA_ACLINK_CTRL_SYNC);
udelay(100);
#if 1 /* FIXME: should we do full reset here for all chip models? */
pci_write_config_byte(chip->pci, VIA_ACLINK_CTRL, 0x00);
udelay(100);
#else
/* deassert ACLink reset, force SYNC (warm AC'97 reset) */
pci_write_config_byte(chip->pci, VIA_ACLINK_CTRL,
VIA_ACLINK_CTRL_RESET|VIA_ACLINK_CTRL_SYNC);
udelay(2);
#endif
/* ACLink on, deassert ACLink reset, VSR, SGD data out */
pci_write_config_byte(chip->pci, VIA_ACLINK_CTRL, VIA_ACLINK_CTRL_INIT);
udelay(100);
}
pci_read_config_byte(chip->pci, VIA_ACLINK_CTRL, &pval);
if ((pval & VIA_ACLINK_CTRL_INIT) != VIA_ACLINK_CTRL_INIT) {
/* ACLink on, deassert ACLink reset, VSR, SGD data out */
pci_write_config_byte(chip->pci, VIA_ACLINK_CTRL, VIA_ACLINK_CTRL_INIT);
udelay(100);
}
/* wait until codec ready */
end_time = jiffies + msecs_to_jiffies(750);
do {
pci_read_config_byte(chip->pci, VIA_ACLINK_STAT, &pval);
if (pval & VIA_ACLINK_C00_READY) /* primary codec ready */
break;
schedule_timeout_uninterruptible(1);
} while (time_before(jiffies, end_time));
if ((val = snd_via82xx_codec_xread(chip)) & VIA_REG_AC97_BUSY)
snd_printk(KERN_ERR "AC'97 codec is not ready [0x%x]\n", val);
snd_via82xx_codec_xwrite(chip, VIA_REG_AC97_READ |
VIA_REG_AC97_SECONDARY_VALID |
(VIA_REG_AC97_CODEC_ID_SECONDARY << VIA_REG_AC97_CODEC_ID_SHIFT));
end_time = jiffies + msecs_to_jiffies(750);
snd_via82xx_codec_xwrite(chip, VIA_REG_AC97_READ |
VIA_REG_AC97_SECONDARY_VALID |
(VIA_REG_AC97_CODEC_ID_SECONDARY << VIA_REG_AC97_CODEC_ID_SHIFT));
do {
if ((val = snd_via82xx_codec_xread(chip)) & VIA_REG_AC97_SECONDARY_VALID) {
chip->ac97_secondary = 1;
goto __ac97_ok2;
}
schedule_timeout_uninterruptible(1);
} while (time_before(jiffies, end_time));
/* This is ok, the most of motherboards have only one codec */
__ac97_ok2:
/* route FM trap to IRQ, disable FM trap */
// pci_write_config_byte(chip->pci, VIA_FM_NMI_CTRL, 0);
/* disable all GPI interrupts */
outl(0, VIAREG(chip, GPI_INTR));
return 0;
}
#ifdef CONFIG_PM
/*
* power management
*/
static int snd_via82xx_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct via82xx_modem *chip = card->private_data;
int i;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
for (i = 0; i < 2; i++)
snd_pcm_suspend_all(chip->pcms[i]);
for (i = 0; i < chip->num_devs; i++)
snd_via82xx_channel_reset(chip, &chip->devs[i]);
synchronize_irq(chip->irq);
snd_ac97_suspend(chip->ac97);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
static int snd_via82xx_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct via82xx_modem *chip = card->private_data;
int i;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "via82xx-modem: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
snd_via82xx_chip_init(chip);
snd_ac97_resume(chip->ac97);
for (i = 0; i < chip->num_devs; i++)
snd_via82xx_channel_reset(chip, &chip->devs[i]);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
static int snd_via82xx_free(struct via82xx_modem *chip)
{
unsigned int i;
if (chip->irq < 0)
goto __end_hw;
/* disable interrupts */
for (i = 0; i < chip->num_devs; i++)
snd_via82xx_channel_reset(chip, &chip->devs[i]);
__end_hw:
if (chip->irq >= 0)
free_irq(chip->irq, chip);
pci_release_regions(chip->pci);
pci_disable_device(chip->pci);
kfree(chip);
return 0;
}
static int snd_via82xx_dev_free(struct snd_device *device)
{
struct via82xx_modem *chip = device->device_data;
return snd_via82xx_free(chip);
}
static int __devinit snd_via82xx_create(struct snd_card *card,
struct pci_dev *pci,
int chip_type,
int revision,
unsigned int ac97_clock,
struct via82xx_modem ** r_via)
{
struct via82xx_modem *chip;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_via82xx_dev_free,
};
if ((err = pci_enable_device(pci)) < 0)
return err;
if ((chip = kzalloc(sizeof(*chip), GFP_KERNEL)) == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
spin_lock_init(&chip->reg_lock);
chip->card = card;
chip->pci = pci;
chip->irq = -1;
if ((err = pci_request_regions(pci, card->driver)) < 0) {
kfree(chip);
pci_disable_device(pci);
return err;
}
chip->port = pci_resource_start(pci, 0);
if (request_irq(pci->irq, snd_via82xx_interrupt, IRQF_SHARED,
card->driver, chip)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_via82xx_free(chip);
return -EBUSY;
}
chip->irq = pci->irq;
if (ac97_clock >= 8000 && ac97_clock <= 48000)
chip->ac97_clock = ac97_clock;
synchronize_irq(chip->irq);
if ((err = snd_via82xx_chip_init(chip)) < 0) {
snd_via82xx_free(chip);
return err;
}
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
snd_via82xx_free(chip);
return err;
}
/* The 8233 ac97 controller does not implement the master bit
* in the pci command register. IMHO this is a violation of the PCI spec.
* We call pci_set_master here because it does not hurt. */
pci_set_master(pci);
snd_card_set_dev(card, &pci->dev);
*r_via = chip;
return 0;
}
static int __devinit snd_via82xx_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
struct snd_card *card;
struct via82xx_modem *chip;
int chip_type = 0, card_type;
unsigned int i;
int err;
err = snd_card_create(index, id, THIS_MODULE, 0, &card);
if (err < 0)
return err;
card_type = pci_id->driver_data;
switch (card_type) {
case TYPE_CARD_VIA82XX_MODEM:
strcpy(card->driver, "VIA82XX-MODEM");
sprintf(card->shortname, "VIA 82XX modem");
break;
default:
snd_printk(KERN_ERR "invalid card type %d\n", card_type);
err = -EINVAL;
goto __error;
}
if ((err = snd_via82xx_create(card, pci, chip_type, pci->revision,
ac97_clock, &chip)) < 0)
goto __error;
card->private_data = chip;
if ((err = snd_via82xx_mixer_new(chip)) < 0)
goto __error;
if ((err = snd_via686_pcm_new(chip)) < 0 )
goto __error;
/* disable interrupts */
for (i = 0; i < chip->num_devs; i++)
snd_via82xx_channel_reset(chip, &chip->devs[i]);
sprintf(card->longname, "%s at 0x%lx, irq %d",
card->shortname, chip->port, chip->irq);
snd_via82xx_proc_init(chip);
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
pci_set_drvdata(pci, card);
return 0;
__error:
snd_card_free(card);
return err;
}
static void __devexit snd_via82xx_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
static struct pci_driver driver = {
.name = "VIA 82xx Modem",
.id_table = snd_via82xx_modem_ids,
.probe = snd_via82xx_probe,
.remove = __devexit_p(snd_via82xx_remove),
#ifdef CONFIG_PM
.suspend = snd_via82xx_suspend,
.resume = snd_via82xx_resume,
#endif
};
static int __init alsa_card_via82xx_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_via82xx_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_via82xx_init)
module_exit(alsa_card_via82xx_exit)
| gpl-2.0 |
Entropy512/android_kernel_motorola_msm8226 | arch/arm/mach-bcmring/dma.c | 4869 | 42994 | /*****************************************************************************
* Copyright 2004 - 2008 Broadcom Corporation. All rights reserved.
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2, available at
* http://www.broadcom.com/licenses/GPLv2.php (the "GPL").
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a
* license other than the GPL, without Broadcom's express prior written
* consent.
*****************************************************************************/
/****************************************************************************/
/**
* @file dma.c
*
* @brief Implements the DMA interface.
*/
/****************************************************************************/
/* ---- Include Files ---------------------------------------------------- */
#include <linux/module.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/irqreturn.h>
#include <linux/proc_fs.h>
#include <linux/slab.h>
#include <mach/timer.h>
#include <linux/pfn.h>
#include <linux/atomic.h>
#include <mach/dma.h>
/* ---- Public Variables ------------------------------------------------- */
/* ---- Private Constants and Types -------------------------------------- */
#define MAKE_HANDLE(controllerIdx, channelIdx) (((controllerIdx) << 4) | (channelIdx))
#define CONTROLLER_FROM_HANDLE(handle) (((handle) >> 4) & 0x0f)
#define CHANNEL_FROM_HANDLE(handle) ((handle) & 0x0f)
/* ---- Private Variables ------------------------------------------------ */
static DMA_Global_t gDMA;
static struct proc_dir_entry *gDmaDir;
#include "dma_device.c"
/* ---- Private Function Prototypes -------------------------------------- */
/* ---- Functions ------------------------------------------------------- */
/****************************************************************************/
/**
* Displays information for /proc/dma/channels
*/
/****************************************************************************/
static int dma_proc_read_channels(char *buf, char **start, off_t offset,
int count, int *eof, void *data)
{
int controllerIdx;
int channelIdx;
int limit = count - 200;
int len = 0;
DMA_Channel_t *channel;
if (down_interruptible(&gDMA.lock) < 0) {
return -ERESTARTSYS;
}
for (controllerIdx = 0; controllerIdx < DMA_NUM_CONTROLLERS;
controllerIdx++) {
for (channelIdx = 0; channelIdx < DMA_NUM_CHANNELS;
channelIdx++) {
if (len >= limit) {
break;
}
channel =
&gDMA.controller[controllerIdx].channel[channelIdx];
len +=
sprintf(buf + len, "%d:%d ", controllerIdx,
channelIdx);
if ((channel->flags & DMA_CHANNEL_FLAG_IS_DEDICATED) !=
0) {
len +=
sprintf(buf + len, "Dedicated for %s ",
DMA_gDeviceAttribute[channel->
devType].name);
} else {
len += sprintf(buf + len, "Shared ");
}
if ((channel->flags & DMA_CHANNEL_FLAG_NO_ISR) != 0) {
len += sprintf(buf + len, "No ISR ");
}
if ((channel->flags & DMA_CHANNEL_FLAG_LARGE_FIFO) != 0) {
len += sprintf(buf + len, "Fifo: 128 ");
} else {
len += sprintf(buf + len, "Fifo: 64 ");
}
if ((channel->flags & DMA_CHANNEL_FLAG_IN_USE) != 0) {
len +=
sprintf(buf + len, "InUse by %s",
DMA_gDeviceAttribute[channel->
devType].name);
#if (DMA_DEBUG_TRACK_RESERVATION)
len +=
sprintf(buf + len, " (%s:%d)",
channel->fileName,
channel->lineNum);
#endif
} else {
len += sprintf(buf + len, "Avail ");
}
if (channel->lastDevType != DMA_DEVICE_NONE) {
len +=
sprintf(buf + len, "Last use: %s ",
DMA_gDeviceAttribute[channel->
lastDevType].
name);
}
len += sprintf(buf + len, "\n");
}
}
up(&gDMA.lock);
*eof = 1;
return len;
}
/****************************************************************************/
/**
* Displays information for /proc/dma/devices
*/
/****************************************************************************/
static int dma_proc_read_devices(char *buf, char **start, off_t offset,
int count, int *eof, void *data)
{
int limit = count - 200;
int len = 0;
int devIdx;
if (down_interruptible(&gDMA.lock) < 0) {
return -ERESTARTSYS;
}
for (devIdx = 0; devIdx < DMA_NUM_DEVICE_ENTRIES; devIdx++) {
DMA_DeviceAttribute_t *devAttr = &DMA_gDeviceAttribute[devIdx];
if (devAttr->name == NULL) {
continue;
}
if (len >= limit) {
break;
}
len += sprintf(buf + len, "%-12s ", devAttr->name);
if ((devAttr->flags & DMA_DEVICE_FLAG_IS_DEDICATED) != 0) {
len +=
sprintf(buf + len, "Dedicated %d:%d ",
devAttr->dedicatedController,
devAttr->dedicatedChannel);
} else {
len += sprintf(buf + len, "Shared DMA:");
if ((devAttr->flags & DMA_DEVICE_FLAG_ON_DMA0) != 0) {
len += sprintf(buf + len, "0");
}
if ((devAttr->flags & DMA_DEVICE_FLAG_ON_DMA1) != 0) {
len += sprintf(buf + len, "1");
}
len += sprintf(buf + len, " ");
}
if ((devAttr->flags & DMA_DEVICE_FLAG_NO_ISR) != 0) {
len += sprintf(buf + len, "NoISR ");
}
if ((devAttr->flags & DMA_DEVICE_FLAG_ALLOW_LARGE_FIFO) != 0) {
len += sprintf(buf + len, "Allow-128 ");
}
len +=
sprintf(buf + len,
"Xfer #: %Lu Ticks: %Lu Bytes: %Lu DescLen: %u\n",
devAttr->numTransfers, devAttr->transferTicks,
devAttr->transferBytes,
devAttr->ring.bytesAllocated);
}
up(&gDMA.lock);
*eof = 1;
return len;
}
/****************************************************************************/
/**
* Determines if a DMA_Device_t is "valid".
*
* @return
* TRUE - dma device is valid
* FALSE - dma device isn't valid
*/
/****************************************************************************/
static inline int IsDeviceValid(DMA_Device_t device)
{
return (device >= 0) && (device < DMA_NUM_DEVICE_ENTRIES);
}
/****************************************************************************/
/**
* Translates a DMA handle into a pointer to a channel.
*
* @return
* non-NULL - pointer to DMA_Channel_t
* NULL - DMA Handle was invalid
*/
/****************************************************************************/
static inline DMA_Channel_t *HandleToChannel(DMA_Handle_t handle)
{
int controllerIdx;
int channelIdx;
controllerIdx = CONTROLLER_FROM_HANDLE(handle);
channelIdx = CHANNEL_FROM_HANDLE(handle);
if ((controllerIdx > DMA_NUM_CONTROLLERS)
|| (channelIdx > DMA_NUM_CHANNELS)) {
return NULL;
}
return &gDMA.controller[controllerIdx].channel[channelIdx];
}
/****************************************************************************/
/**
* Interrupt handler which is called to process DMA interrupts.
*/
/****************************************************************************/
static irqreturn_t dma_interrupt_handler(int irq, void *dev_id)
{
DMA_Channel_t *channel;
DMA_DeviceAttribute_t *devAttr;
int irqStatus;
channel = (DMA_Channel_t *) dev_id;
/* Figure out why we were called, and knock down the interrupt */
irqStatus = dmacHw_getInterruptStatus(channel->dmacHwHandle);
dmacHw_clearInterrupt(channel->dmacHwHandle);
if ((channel->devType < 0)
|| (channel->devType > DMA_NUM_DEVICE_ENTRIES)) {
printk(KERN_ERR "dma_interrupt_handler: Invalid devType: %d\n",
channel->devType);
return IRQ_NONE;
}
devAttr = &DMA_gDeviceAttribute[channel->devType];
/* Update stats */
if ((irqStatus & dmacHw_INTERRUPT_STATUS_TRANS) != 0) {
devAttr->transferTicks +=
(timer_get_tick_count() - devAttr->transferStartTime);
}
if ((irqStatus & dmacHw_INTERRUPT_STATUS_ERROR) != 0) {
printk(KERN_ERR
"dma_interrupt_handler: devType :%d DMA error (%s)\n",
channel->devType, devAttr->name);
} else {
devAttr->numTransfers++;
devAttr->transferBytes += devAttr->numBytes;
}
/* Call any installed handler */
if (devAttr->devHandler != NULL) {
devAttr->devHandler(channel->devType, irqStatus,
devAttr->userData);
}
return IRQ_HANDLED;
}
/****************************************************************************/
/**
* Allocates memory to hold a descriptor ring. The descriptor ring then
* needs to be populated by making one or more calls to
* dna_add_descriptors.
*
* The returned descriptor ring will be automatically initialized.
*
* @return
* 0 Descriptor ring was allocated successfully
* -EINVAL Invalid parameters passed in
* -ENOMEM Unable to allocate memory for the desired number of descriptors.
*/
/****************************************************************************/
int dma_alloc_descriptor_ring(DMA_DescriptorRing_t *ring, /* Descriptor ring to populate */
int numDescriptors /* Number of descriptors that need to be allocated. */
) {
size_t bytesToAlloc = dmacHw_descriptorLen(numDescriptors);
if ((ring == NULL) || (numDescriptors <= 0)) {
return -EINVAL;
}
ring->physAddr = 0;
ring->descriptorsAllocated = 0;
ring->bytesAllocated = 0;
ring->virtAddr = dma_alloc_writecombine(NULL,
bytesToAlloc,
&ring->physAddr,
GFP_KERNEL);
if (ring->virtAddr == NULL) {
return -ENOMEM;
}
ring->bytesAllocated = bytesToAlloc;
ring->descriptorsAllocated = numDescriptors;
return dma_init_descriptor_ring(ring, numDescriptors);
}
EXPORT_SYMBOL(dma_alloc_descriptor_ring);
/****************************************************************************/
/**
* Releases the memory which was previously allocated for a descriptor ring.
*/
/****************************************************************************/
void dma_free_descriptor_ring(DMA_DescriptorRing_t *ring /* Descriptor to release */
) {
if (ring->virtAddr != NULL) {
dma_free_writecombine(NULL,
ring->bytesAllocated,
ring->virtAddr, ring->physAddr);
}
ring->bytesAllocated = 0;
ring->descriptorsAllocated = 0;
ring->virtAddr = NULL;
ring->physAddr = 0;
}
EXPORT_SYMBOL(dma_free_descriptor_ring);
/****************************************************************************/
/**
* Initializes a descriptor ring, so that descriptors can be added to it.
* Once a descriptor ring has been allocated, it may be reinitialized for
* use with additional/different regions of memory.
*
* Note that if 7 descriptors are allocated, it's perfectly acceptable to
* initialize the ring with a smaller number of descriptors. The amount
* of memory allocated for the descriptor ring will not be reduced, and
* the descriptor ring may be reinitialized later
*
* @return
* 0 Descriptor ring was initialized successfully
* -ENOMEM The descriptor which was passed in has insufficient space
* to hold the desired number of descriptors.
*/
/****************************************************************************/
int dma_init_descriptor_ring(DMA_DescriptorRing_t *ring, /* Descriptor ring to initialize */
int numDescriptors /* Number of descriptors to initialize. */
) {
if (ring->virtAddr == NULL) {
return -EINVAL;
}
if (dmacHw_initDescriptor(ring->virtAddr,
ring->physAddr,
ring->bytesAllocated, numDescriptors) < 0) {
printk(KERN_ERR
"dma_init_descriptor_ring: dmacHw_initDescriptor failed\n");
return -ENOMEM;
}
return 0;
}
EXPORT_SYMBOL(dma_init_descriptor_ring);
/****************************************************************************/
/**
* Determines the number of descriptors which would be required for a
* transfer of the indicated memory region.
*
* This function also needs to know which DMA device this transfer will
* be destined for, so that the appropriate DMA configuration can be retrieved.
* DMA parameters such as transfer width, and whether this is a memory-to-memory
* or memory-to-peripheral, etc can all affect the actual number of descriptors
* required.
*
* @return
* > 0 Returns the number of descriptors required for the indicated transfer
* -ENODEV - Device handed in is invalid.
* -EINVAL Invalid parameters
* -ENOMEM Memory exhausted
*/
/****************************************************************************/
int dma_calculate_descriptor_count(DMA_Device_t device, /* DMA Device that this will be associated with */
dma_addr_t srcData, /* Place to get data to write to device */
dma_addr_t dstData, /* Pointer to device data address */
size_t numBytes /* Number of bytes to transfer to the device */
) {
int numDescriptors;
DMA_DeviceAttribute_t *devAttr;
if (!IsDeviceValid(device)) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[device];
numDescriptors = dmacHw_calculateDescriptorCount(&devAttr->config,
(void *)srcData,
(void *)dstData,
numBytes);
if (numDescriptors < 0) {
printk(KERN_ERR
"dma_calculate_descriptor_count: dmacHw_calculateDescriptorCount failed\n");
return -EINVAL;
}
return numDescriptors;
}
EXPORT_SYMBOL(dma_calculate_descriptor_count);
/****************************************************************************/
/**
* Adds a region of memory to the descriptor ring. Note that it may take
* multiple descriptors for each region of memory. It is the callers
* responsibility to allocate a sufficiently large descriptor ring.
*
* @return
* 0 Descriptors were added successfully
* -ENODEV Device handed in is invalid.
* -EINVAL Invalid parameters
* -ENOMEM Memory exhausted
*/
/****************************************************************************/
int dma_add_descriptors(DMA_DescriptorRing_t *ring, /* Descriptor ring to add descriptors to */
DMA_Device_t device, /* DMA Device that descriptors are for */
dma_addr_t srcData, /* Place to get data (memory or device) */
dma_addr_t dstData, /* Place to put data (memory or device) */
size_t numBytes /* Number of bytes to transfer to the device */
) {
int rc;
DMA_DeviceAttribute_t *devAttr;
if (!IsDeviceValid(device)) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[device];
rc = dmacHw_setDataDescriptor(&devAttr->config,
ring->virtAddr,
(void *)srcData,
(void *)dstData, numBytes);
if (rc < 0) {
printk(KERN_ERR
"dma_add_descriptors: dmacHw_setDataDescriptor failed with code: %d\n",
rc);
return -ENOMEM;
}
return 0;
}
EXPORT_SYMBOL(dma_add_descriptors);
/****************************************************************************/
/**
* Sets the descriptor ring associated with a device.
*
* Once set, the descriptor ring will be associated with the device, even
* across channel request/free calls. Passing in a NULL descriptor ring
* will release any descriptor ring currently associated with the device.
*
* Note: If you call dma_transfer, or one of the other dma_alloc_ functions
* the descriptor ring may be released and reallocated.
*
* Note: This function will release the descriptor memory for any current
* descriptor ring associated with this device.
*
* @return
* 0 Descriptors were added successfully
* -ENODEV Device handed in is invalid.
*/
/****************************************************************************/
int dma_set_device_descriptor_ring(DMA_Device_t device, /* Device to update the descriptor ring for. */
DMA_DescriptorRing_t *ring /* Descriptor ring to add descriptors to */
) {
DMA_DeviceAttribute_t *devAttr;
if (!IsDeviceValid(device)) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[device];
/* Free the previously allocated descriptor ring */
dma_free_descriptor_ring(&devAttr->ring);
if (ring != NULL) {
/* Copy in the new one */
devAttr->ring = *ring;
}
/* Set things up so that if dma_transfer is called then this descriptor */
/* ring will get freed. */
devAttr->prevSrcData = 0;
devAttr->prevDstData = 0;
devAttr->prevNumBytes = 0;
return 0;
}
EXPORT_SYMBOL(dma_set_device_descriptor_ring);
/****************************************************************************/
/**
* Retrieves the descriptor ring associated with a device.
*
* @return
* 0 Descriptors were added successfully
* -ENODEV Device handed in is invalid.
*/
/****************************************************************************/
int dma_get_device_descriptor_ring(DMA_Device_t device, /* Device to retrieve the descriptor ring for. */
DMA_DescriptorRing_t *ring /* Place to store retrieved ring */
) {
DMA_DeviceAttribute_t *devAttr;
memset(ring, 0, sizeof(*ring));
if (!IsDeviceValid(device)) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[device];
*ring = devAttr->ring;
return 0;
}
EXPORT_SYMBOL(dma_get_device_descriptor_ring);
/****************************************************************************/
/**
* Configures a DMA channel.
*
* @return
* >= 0 - Initialization was successful.
*
* -EBUSY - Device is currently being used.
* -ENODEV - Device handed in is invalid.
*/
/****************************************************************************/
static int ConfigChannel(DMA_Handle_t handle)
{
DMA_Channel_t *channel;
DMA_DeviceAttribute_t *devAttr;
int controllerIdx;
channel = HandleToChannel(handle);
if (channel == NULL) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[channel->devType];
controllerIdx = CONTROLLER_FROM_HANDLE(handle);
if ((devAttr->flags & DMA_DEVICE_FLAG_PORT_PER_DMAC) != 0) {
if (devAttr->config.transferType ==
dmacHw_TRANSFER_TYPE_MEM_TO_PERIPHERAL) {
devAttr->config.dstPeripheralPort =
devAttr->dmacPort[controllerIdx];
} else if (devAttr->config.transferType ==
dmacHw_TRANSFER_TYPE_PERIPHERAL_TO_MEM) {
devAttr->config.srcPeripheralPort =
devAttr->dmacPort[controllerIdx];
}
}
if (dmacHw_configChannel(channel->dmacHwHandle, &devAttr->config) != 0) {
printk(KERN_ERR "ConfigChannel: dmacHw_configChannel failed\n");
return -EIO;
}
return 0;
}
/****************************************************************************/
/**
* Initializes all of the data structures associated with the DMA.
* @return
* >= 0 - Initialization was successful.
*
* -EBUSY - Device is currently being used.
* -ENODEV - Device handed in is invalid.
*/
/****************************************************************************/
int dma_init(void)
{
int rc = 0;
int controllerIdx;
int channelIdx;
DMA_Device_t devIdx;
DMA_Channel_t *channel;
DMA_Handle_t dedicatedHandle;
memset(&gDMA, 0, sizeof(gDMA));
sema_init(&gDMA.lock, 0);
init_waitqueue_head(&gDMA.freeChannelQ);
/* Initialize the Hardware */
dmacHw_initDma();
/* Start off by marking all of the DMA channels as shared. */
for (controllerIdx = 0; controllerIdx < DMA_NUM_CONTROLLERS;
controllerIdx++) {
for (channelIdx = 0; channelIdx < DMA_NUM_CHANNELS;
channelIdx++) {
channel =
&gDMA.controller[controllerIdx].channel[channelIdx];
channel->flags = 0;
channel->devType = DMA_DEVICE_NONE;
channel->lastDevType = DMA_DEVICE_NONE;
#if (DMA_DEBUG_TRACK_RESERVATION)
channel->fileName = "";
channel->lineNum = 0;
#endif
channel->dmacHwHandle =
dmacHw_getChannelHandle(dmacHw_MAKE_CHANNEL_ID
(controllerIdx,
channelIdx));
dmacHw_initChannel(channel->dmacHwHandle);
}
}
/* Record any special attributes that channels may have */
gDMA.controller[0].channel[0].flags |= DMA_CHANNEL_FLAG_LARGE_FIFO;
gDMA.controller[0].channel[1].flags |= DMA_CHANNEL_FLAG_LARGE_FIFO;
gDMA.controller[1].channel[0].flags |= DMA_CHANNEL_FLAG_LARGE_FIFO;
gDMA.controller[1].channel[1].flags |= DMA_CHANNEL_FLAG_LARGE_FIFO;
/* Now walk through and record the dedicated channels. */
for (devIdx = 0; devIdx < DMA_NUM_DEVICE_ENTRIES; devIdx++) {
DMA_DeviceAttribute_t *devAttr = &DMA_gDeviceAttribute[devIdx];
if (((devAttr->flags & DMA_DEVICE_FLAG_NO_ISR) != 0)
&& ((devAttr->flags & DMA_DEVICE_FLAG_IS_DEDICATED) == 0)) {
printk(KERN_ERR
"DMA Device: %s Can only request NO_ISR for dedicated devices\n",
devAttr->name);
rc = -EINVAL;
goto out;
}
if ((devAttr->flags & DMA_DEVICE_FLAG_IS_DEDICATED) != 0) {
/* This is a dedicated device. Mark the channel as being reserved. */
if (devAttr->dedicatedController >= DMA_NUM_CONTROLLERS) {
printk(KERN_ERR
"DMA Device: %s DMA Controller %d is out of range\n",
devAttr->name,
devAttr->dedicatedController);
rc = -EINVAL;
goto out;
}
if (devAttr->dedicatedChannel >= DMA_NUM_CHANNELS) {
printk(KERN_ERR
"DMA Device: %s DMA Channel %d is out of range\n",
devAttr->name,
devAttr->dedicatedChannel);
rc = -EINVAL;
goto out;
}
dedicatedHandle =
MAKE_HANDLE(devAttr->dedicatedController,
devAttr->dedicatedChannel);
channel = HandleToChannel(dedicatedHandle);
if ((channel->flags & DMA_CHANNEL_FLAG_IS_DEDICATED) !=
0) {
printk
("DMA Device: %s attempting to use same DMA Controller:Channel (%d:%d) as %s\n",
devAttr->name,
devAttr->dedicatedController,
devAttr->dedicatedChannel,
DMA_gDeviceAttribute[channel->devType].
name);
rc = -EBUSY;
goto out;
}
channel->flags |= DMA_CHANNEL_FLAG_IS_DEDICATED;
channel->devType = devIdx;
if (devAttr->flags & DMA_DEVICE_FLAG_NO_ISR) {
channel->flags |= DMA_CHANNEL_FLAG_NO_ISR;
}
/* For dedicated channels, we can go ahead and configure the DMA channel now */
/* as well. */
ConfigChannel(dedicatedHandle);
}
}
/* Go through and register the interrupt handlers */
for (controllerIdx = 0; controllerIdx < DMA_NUM_CONTROLLERS;
controllerIdx++) {
for (channelIdx = 0; channelIdx < DMA_NUM_CHANNELS;
channelIdx++) {
channel =
&gDMA.controller[controllerIdx].channel[channelIdx];
if ((channel->flags & DMA_CHANNEL_FLAG_NO_ISR) == 0) {
snprintf(channel->name, sizeof(channel->name),
"dma %d:%d %s", controllerIdx,
channelIdx,
channel->devType ==
DMA_DEVICE_NONE ? "" :
DMA_gDeviceAttribute[channel->devType].
name);
rc =
request_irq(IRQ_DMA0C0 +
(controllerIdx *
DMA_NUM_CHANNELS) +
channelIdx,
dma_interrupt_handler,
IRQF_DISABLED, channel->name,
channel);
if (rc != 0) {
printk(KERN_ERR
"request_irq for IRQ_DMA%dC%d failed\n",
controllerIdx, channelIdx);
}
}
}
}
/* Create /proc/dma/channels and /proc/dma/devices */
gDmaDir = proc_mkdir("dma", NULL);
if (gDmaDir == NULL) {
printk(KERN_ERR "Unable to create /proc/dma\n");
} else {
create_proc_read_entry("channels", 0, gDmaDir,
dma_proc_read_channels, NULL);
create_proc_read_entry("devices", 0, gDmaDir,
dma_proc_read_devices, NULL);
}
out:
up(&gDMA.lock);
return rc;
}
/****************************************************************************/
/**
* Reserves a channel for use with @a dev. If the device is setup to use
* a shared channel, then this function will block until a free channel
* becomes available.
*
* @return
* >= 0 - A valid DMA Handle.
* -EBUSY - Device is currently being used.
* -ENODEV - Device handed in is invalid.
*/
/****************************************************************************/
#if (DMA_DEBUG_TRACK_RESERVATION)
DMA_Handle_t dma_request_channel_dbg
(DMA_Device_t dev, const char *fileName, int lineNum)
#else
DMA_Handle_t dma_request_channel(DMA_Device_t dev)
#endif
{
DMA_Handle_t handle;
DMA_DeviceAttribute_t *devAttr;
DMA_Channel_t *channel;
int controllerIdx;
int controllerIdx2;
int channelIdx;
if (down_interruptible(&gDMA.lock) < 0) {
return -ERESTARTSYS;
}
if ((dev < 0) || (dev >= DMA_NUM_DEVICE_ENTRIES)) {
handle = -ENODEV;
goto out;
}
devAttr = &DMA_gDeviceAttribute[dev];
#if (DMA_DEBUG_TRACK_RESERVATION)
{
char *s;
s = strrchr(fileName, '/');
if (s != NULL) {
fileName = s + 1;
}
}
#endif
if ((devAttr->flags & DMA_DEVICE_FLAG_IN_USE) != 0) {
/* This device has already been requested and not been freed */
printk(KERN_ERR "%s: device %s is already requested\n",
__func__, devAttr->name);
handle = -EBUSY;
goto out;
}
if ((devAttr->flags & DMA_DEVICE_FLAG_IS_DEDICATED) != 0) {
/* This device has a dedicated channel. */
channel =
&gDMA.controller[devAttr->dedicatedController].
channel[devAttr->dedicatedChannel];
if ((channel->flags & DMA_CHANNEL_FLAG_IN_USE) != 0) {
handle = -EBUSY;
goto out;
}
channel->flags |= DMA_CHANNEL_FLAG_IN_USE;
devAttr->flags |= DMA_DEVICE_FLAG_IN_USE;
#if (DMA_DEBUG_TRACK_RESERVATION)
channel->fileName = fileName;
channel->lineNum = lineNum;
#endif
handle =
MAKE_HANDLE(devAttr->dedicatedController,
devAttr->dedicatedChannel);
goto out;
}
/* This device needs to use one of the shared channels. */
handle = DMA_INVALID_HANDLE;
while (handle == DMA_INVALID_HANDLE) {
/* Scan through the shared channels and see if one is available */
for (controllerIdx2 = 0; controllerIdx2 < DMA_NUM_CONTROLLERS;
controllerIdx2++) {
/* Check to see if we should try on controller 1 first. */
controllerIdx = controllerIdx2;
if ((devAttr->
flags & DMA_DEVICE_FLAG_ALLOC_DMA1_FIRST) != 0) {
controllerIdx = 1 - controllerIdx;
}
/* See if the device is available on the controller being tested */
if ((devAttr->
flags & (DMA_DEVICE_FLAG_ON_DMA0 << controllerIdx))
!= 0) {
for (channelIdx = 0;
channelIdx < DMA_NUM_CHANNELS;
channelIdx++) {
channel =
&gDMA.controller[controllerIdx].
channel[channelIdx];
if (((channel->
flags &
DMA_CHANNEL_FLAG_IS_DEDICATED) ==
0)
&&
((channel->
flags & DMA_CHANNEL_FLAG_IN_USE)
== 0)) {
if (((channel->
flags &
DMA_CHANNEL_FLAG_LARGE_FIFO)
!= 0)
&&
((devAttr->
flags &
DMA_DEVICE_FLAG_ALLOW_LARGE_FIFO)
== 0)) {
/* This channel is a large fifo - don't tie it up */
/* with devices that we don't want using it. */
continue;
}
channel->flags |=
DMA_CHANNEL_FLAG_IN_USE;
channel->devType = dev;
devAttr->flags |=
DMA_DEVICE_FLAG_IN_USE;
#if (DMA_DEBUG_TRACK_RESERVATION)
channel->fileName = fileName;
channel->lineNum = lineNum;
#endif
handle =
MAKE_HANDLE(controllerIdx,
channelIdx);
/* Now that we've reserved the channel - we can go ahead and configure it */
if (ConfigChannel(handle) != 0) {
handle = -EIO;
printk(KERN_ERR
"dma_request_channel: ConfigChannel failed\n");
}
goto out;
}
}
}
}
/* No channels are currently available. Let's wait for one to free up. */
{
DEFINE_WAIT(wait);
prepare_to_wait(&gDMA.freeChannelQ, &wait,
TASK_INTERRUPTIBLE);
up(&gDMA.lock);
schedule();
finish_wait(&gDMA.freeChannelQ, &wait);
if (signal_pending(current)) {
/* We don't currently hold gDMA.lock, so we return directly */
return -ERESTARTSYS;
}
}
if (down_interruptible(&gDMA.lock)) {
return -ERESTARTSYS;
}
}
out:
up(&gDMA.lock);
return handle;
}
/* Create both _dbg and non _dbg functions for modules. */
#if (DMA_DEBUG_TRACK_RESERVATION)
#undef dma_request_channel
DMA_Handle_t dma_request_channel(DMA_Device_t dev)
{
return dma_request_channel_dbg(dev, __FILE__, __LINE__);
}
EXPORT_SYMBOL(dma_request_channel_dbg);
#endif
EXPORT_SYMBOL(dma_request_channel);
/****************************************************************************/
/**
* Frees a previously allocated DMA Handle.
*/
/****************************************************************************/
int dma_free_channel(DMA_Handle_t handle /* DMA handle. */
) {
int rc = 0;
DMA_Channel_t *channel;
DMA_DeviceAttribute_t *devAttr;
if (down_interruptible(&gDMA.lock) < 0) {
return -ERESTARTSYS;
}
channel = HandleToChannel(handle);
if (channel == NULL) {
rc = -EINVAL;
goto out;
}
devAttr = &DMA_gDeviceAttribute[channel->devType];
if ((channel->flags & DMA_CHANNEL_FLAG_IS_DEDICATED) == 0) {
channel->lastDevType = channel->devType;
channel->devType = DMA_DEVICE_NONE;
}
channel->flags &= ~DMA_CHANNEL_FLAG_IN_USE;
devAttr->flags &= ~DMA_DEVICE_FLAG_IN_USE;
out:
up(&gDMA.lock);
wake_up_interruptible(&gDMA.freeChannelQ);
return rc;
}
EXPORT_SYMBOL(dma_free_channel);
/****************************************************************************/
/**
* Determines if a given device has been configured as using a shared
* channel.
*
* @return
* 0 Device uses a dedicated channel
* > zero Device uses a shared channel
* < zero Error code
*/
/****************************************************************************/
int dma_device_is_channel_shared(DMA_Device_t device /* Device to check. */
) {
DMA_DeviceAttribute_t *devAttr;
if (!IsDeviceValid(device)) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[device];
return ((devAttr->flags & DMA_DEVICE_FLAG_IS_DEDICATED) == 0);
}
EXPORT_SYMBOL(dma_device_is_channel_shared);
/****************************************************************************/
/**
* Allocates buffers for the descriptors. This is normally done automatically
* but needs to be done explicitly when initiating a dma from interrupt
* context.
*
* @return
* 0 Descriptors were allocated successfully
* -EINVAL Invalid device type for this kind of transfer
* (i.e. the device is _MEM_TO_DEV and not _DEV_TO_MEM)
* -ENOMEM Memory exhausted
*/
/****************************************************************************/
int dma_alloc_descriptors(DMA_Handle_t handle, /* DMA Handle */
dmacHw_TRANSFER_TYPE_e transferType, /* Type of transfer being performed */
dma_addr_t srcData, /* Place to get data to write to device */
dma_addr_t dstData, /* Pointer to device data address */
size_t numBytes /* Number of bytes to transfer to the device */
) {
DMA_Channel_t *channel;
DMA_DeviceAttribute_t *devAttr;
int numDescriptors;
size_t ringBytesRequired;
int rc = 0;
channel = HandleToChannel(handle);
if (channel == NULL) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[channel->devType];
if (devAttr->config.transferType != transferType) {
return -EINVAL;
}
/* Figure out how many descriptors we need. */
/* printk("srcData: 0x%08x dstData: 0x%08x, numBytes: %d\n", */
/* srcData, dstData, numBytes); */
numDescriptors = dmacHw_calculateDescriptorCount(&devAttr->config,
(void *)srcData,
(void *)dstData,
numBytes);
if (numDescriptors < 0) {
printk(KERN_ERR "%s: dmacHw_calculateDescriptorCount failed\n",
__func__);
return -EINVAL;
}
/* Check to see if we can reuse the existing descriptor ring, or if we need to allocate */
/* a new one. */
ringBytesRequired = dmacHw_descriptorLen(numDescriptors);
/* printk("ringBytesRequired: %d\n", ringBytesRequired); */
if (ringBytesRequired > devAttr->ring.bytesAllocated) {
/* Make sure that this code path is never taken from interrupt context. */
/* It's OK for an interrupt to initiate a DMA transfer, but the descriptor */
/* allocation needs to have already been done. */
might_sleep();
/* Free the old descriptor ring and allocate a new one. */
dma_free_descriptor_ring(&devAttr->ring);
/* And allocate a new one. */
rc =
dma_alloc_descriptor_ring(&devAttr->ring,
numDescriptors);
if (rc < 0) {
printk(KERN_ERR
"%s: dma_alloc_descriptor_ring(%d) failed\n",
__func__, numDescriptors);
return rc;
}
/* Setup the descriptor for this transfer */
if (dmacHw_initDescriptor(devAttr->ring.virtAddr,
devAttr->ring.physAddr,
devAttr->ring.bytesAllocated,
numDescriptors) < 0) {
printk(KERN_ERR "%s: dmacHw_initDescriptor failed\n",
__func__);
return -EINVAL;
}
} else {
/* We've already got enough ring buffer allocated. All we need to do is reset */
/* any control information, just in case the previous DMA was stopped. */
dmacHw_resetDescriptorControl(devAttr->ring.virtAddr);
}
/* dma_alloc/free both set the prevSrc/DstData to 0. If they happen to be the same */
/* as last time, then we don't need to call setDataDescriptor again. */
if (dmacHw_setDataDescriptor(&devAttr->config,
devAttr->ring.virtAddr,
(void *)srcData,
(void *)dstData, numBytes) < 0) {
printk(KERN_ERR "%s: dmacHw_setDataDescriptor failed\n",
__func__);
return -EINVAL;
}
/* Remember the critical information for this transfer so that we can eliminate */
/* another call to dma_alloc_descriptors if the caller reuses the same buffers */
devAttr->prevSrcData = srcData;
devAttr->prevDstData = dstData;
devAttr->prevNumBytes = numBytes;
return 0;
}
EXPORT_SYMBOL(dma_alloc_descriptors);
/****************************************************************************/
/**
* Allocates and sets up descriptors for a double buffered circular buffer.
*
* This is primarily intended to be used for things like the ingress samples
* from a microphone.
*
* @return
* > 0 Number of descriptors actually allocated.
* -EINVAL Invalid device type for this kind of transfer
* (i.e. the device is _MEM_TO_DEV and not _DEV_TO_MEM)
* -ENOMEM Memory exhausted
*/
/****************************************************************************/
int dma_alloc_double_dst_descriptors(DMA_Handle_t handle, /* DMA Handle */
dma_addr_t srcData, /* Physical address of source data */
dma_addr_t dstData1, /* Physical address of first destination buffer */
dma_addr_t dstData2, /* Physical address of second destination buffer */
size_t numBytes /* Number of bytes in each destination buffer */
) {
DMA_Channel_t *channel;
DMA_DeviceAttribute_t *devAttr;
int numDst1Descriptors;
int numDst2Descriptors;
int numDescriptors;
size_t ringBytesRequired;
int rc = 0;
channel = HandleToChannel(handle);
if (channel == NULL) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[channel->devType];
/* Figure out how many descriptors we need. */
/* printk("srcData: 0x%08x dstData: 0x%08x, numBytes: %d\n", */
/* srcData, dstData, numBytes); */
numDst1Descriptors =
dmacHw_calculateDescriptorCount(&devAttr->config, (void *)srcData,
(void *)dstData1, numBytes);
if (numDst1Descriptors < 0) {
return -EINVAL;
}
numDst2Descriptors =
dmacHw_calculateDescriptorCount(&devAttr->config, (void *)srcData,
(void *)dstData2, numBytes);
if (numDst2Descriptors < 0) {
return -EINVAL;
}
numDescriptors = numDst1Descriptors + numDst2Descriptors;
/* printk("numDescriptors: %d\n", numDescriptors); */
/* Check to see if we can reuse the existing descriptor ring, or if we need to allocate */
/* a new one. */
ringBytesRequired = dmacHw_descriptorLen(numDescriptors);
/* printk("ringBytesRequired: %d\n", ringBytesRequired); */
if (ringBytesRequired > devAttr->ring.bytesAllocated) {
/* Make sure that this code path is never taken from interrupt context. */
/* It's OK for an interrupt to initiate a DMA transfer, but the descriptor */
/* allocation needs to have already been done. */
might_sleep();
/* Free the old descriptor ring and allocate a new one. */
dma_free_descriptor_ring(&devAttr->ring);
/* And allocate a new one. */
rc =
dma_alloc_descriptor_ring(&devAttr->ring,
numDescriptors);
if (rc < 0) {
printk(KERN_ERR
"%s: dma_alloc_descriptor_ring(%d) failed\n",
__func__, ringBytesRequired);
return rc;
}
}
/* Setup the descriptor for this transfer. Since this function is used with */
/* CONTINUOUS DMA operations, we need to reinitialize every time, otherwise */
/* setDataDescriptor will keep trying to append onto the end. */
if (dmacHw_initDescriptor(devAttr->ring.virtAddr,
devAttr->ring.physAddr,
devAttr->ring.bytesAllocated,
numDescriptors) < 0) {
printk(KERN_ERR "%s: dmacHw_initDescriptor failed\n", __func__);
return -EINVAL;
}
/* dma_alloc/free both set the prevSrc/DstData to 0. If they happen to be the same */
/* as last time, then we don't need to call setDataDescriptor again. */
if (dmacHw_setDataDescriptor(&devAttr->config,
devAttr->ring.virtAddr,
(void *)srcData,
(void *)dstData1, numBytes) < 0) {
printk(KERN_ERR "%s: dmacHw_setDataDescriptor 1 failed\n",
__func__);
return -EINVAL;
}
if (dmacHw_setDataDescriptor(&devAttr->config,
devAttr->ring.virtAddr,
(void *)srcData,
(void *)dstData2, numBytes) < 0) {
printk(KERN_ERR "%s: dmacHw_setDataDescriptor 2 failed\n",
__func__);
return -EINVAL;
}
/* You should use dma_start_transfer rather than dma_transfer_xxx so we don't */
/* try to make the 'prev' variables right. */
devAttr->prevSrcData = 0;
devAttr->prevDstData = 0;
devAttr->prevNumBytes = 0;
return numDescriptors;
}
EXPORT_SYMBOL(dma_alloc_double_dst_descriptors);
/****************************************************************************/
/**
* Initiates a transfer when the descriptors have already been setup.
*
* This is a special case, and normally, the dma_transfer_xxx functions should
* be used.
*
* @return
* 0 Transfer was started successfully
* -ENODEV Invalid handle
*/
/****************************************************************************/
int dma_start_transfer(DMA_Handle_t handle)
{
DMA_Channel_t *channel;
DMA_DeviceAttribute_t *devAttr;
channel = HandleToChannel(handle);
if (channel == NULL) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[channel->devType];
dmacHw_initiateTransfer(channel->dmacHwHandle, &devAttr->config,
devAttr->ring.virtAddr);
/* Since we got this far, everything went successfully */
return 0;
}
EXPORT_SYMBOL(dma_start_transfer);
/****************************************************************************/
/**
* Stops a previously started DMA transfer.
*
* @return
* 0 Transfer was stopped successfully
* -ENODEV Invalid handle
*/
/****************************************************************************/
int dma_stop_transfer(DMA_Handle_t handle)
{
DMA_Channel_t *channel;
channel = HandleToChannel(handle);
if (channel == NULL) {
return -ENODEV;
}
dmacHw_stopTransfer(channel->dmacHwHandle);
return 0;
}
EXPORT_SYMBOL(dma_stop_transfer);
/****************************************************************************/
/**
* Waits for a DMA to complete by polling. This function is only intended
* to be used for testing. Interrupts should be used for most DMA operations.
*/
/****************************************************************************/
int dma_wait_transfer_done(DMA_Handle_t handle)
{
DMA_Channel_t *channel;
dmacHw_TRANSFER_STATUS_e status;
channel = HandleToChannel(handle);
if (channel == NULL) {
return -ENODEV;
}
while ((status =
dmacHw_transferCompleted(channel->dmacHwHandle)) ==
dmacHw_TRANSFER_STATUS_BUSY) {
;
}
if (status == dmacHw_TRANSFER_STATUS_ERROR) {
printk(KERN_ERR "%s: DMA transfer failed\n", __func__);
return -EIO;
}
return 0;
}
EXPORT_SYMBOL(dma_wait_transfer_done);
/****************************************************************************/
/**
* Initiates a DMA, allocating the descriptors as required.
*
* @return
* 0 Transfer was started successfully
* -EINVAL Invalid device type for this kind of transfer
* (i.e. the device is _DEV_TO_MEM and not _MEM_TO_DEV)
*/
/****************************************************************************/
int dma_transfer(DMA_Handle_t handle, /* DMA Handle */
dmacHw_TRANSFER_TYPE_e transferType, /* Type of transfer being performed */
dma_addr_t srcData, /* Place to get data to write to device */
dma_addr_t dstData, /* Pointer to device data address */
size_t numBytes /* Number of bytes to transfer to the device */
) {
DMA_Channel_t *channel;
DMA_DeviceAttribute_t *devAttr;
int rc = 0;
channel = HandleToChannel(handle);
if (channel == NULL) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[channel->devType];
if (devAttr->config.transferType != transferType) {
return -EINVAL;
}
/* We keep track of the information about the previous request for this */
/* device, and if the attributes match, then we can use the descriptors we setup */
/* the last time, and not have to reinitialize everything. */
{
rc =
dma_alloc_descriptors(handle, transferType, srcData,
dstData, numBytes);
if (rc != 0) {
return rc;
}
}
/* And kick off the transfer */
devAttr->numBytes = numBytes;
devAttr->transferStartTime = timer_get_tick_count();
dmacHw_initiateTransfer(channel->dmacHwHandle, &devAttr->config,
devAttr->ring.virtAddr);
/* Since we got this far, everything went successfully */
return 0;
}
EXPORT_SYMBOL(dma_transfer);
/****************************************************************************/
/**
* Set the callback function which will be called when a transfer completes.
* If a NULL callback function is set, then no callback will occur.
*
* @note @a devHandler will be called from IRQ context.
*
* @return
* 0 - Success
* -ENODEV - Device handed in is invalid.
*/
/****************************************************************************/
int dma_set_device_handler(DMA_Device_t dev, /* Device to set the callback for. */
DMA_DeviceHandler_t devHandler, /* Function to call when the DMA completes */
void *userData /* Pointer which will be passed to devHandler. */
) {
DMA_DeviceAttribute_t *devAttr;
unsigned long flags;
if (!IsDeviceValid(dev)) {
return -ENODEV;
}
devAttr = &DMA_gDeviceAttribute[dev];
local_irq_save(flags);
devAttr->userData = userData;
devAttr->devHandler = devHandler;
local_irq_restore(flags);
return 0;
}
EXPORT_SYMBOL(dma_set_device_handler);
| gpl-2.0 |
ali-filth/android_kernel_samsung_arubaslim | drivers/media/video/s5p-mfc/s5p_mfc_dec.c | 4869 | 29403 | /*
* linux/drivers/media/video/s5p-mfc/s5p_mfc_dec.c
*
* Copyright (C) 2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
* Kamil Debski, <k.debski@samsung.com>
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <linux/videodev2.h>
#include <linux/workqueue.h>
#include <media/v4l2-ctrls.h>
#include <media/videobuf2-core.h>
#include "regs-mfc.h"
#include "s5p_mfc_common.h"
#include "s5p_mfc_debug.h"
#include "s5p_mfc_dec.h"
#include "s5p_mfc_intr.h"
#include "s5p_mfc_opr.h"
#include "s5p_mfc_pm.h"
#include "s5p_mfc_shm.h"
static struct s5p_mfc_fmt formats[] = {
{
.name = "4:2:0 2 Planes 64x32 Tiles",
.fourcc = V4L2_PIX_FMT_NV12MT,
.codec_mode = S5P_FIMV_CODEC_NONE,
.type = MFC_FMT_RAW,
.num_planes = 2,
},
{
.name = "4:2:0 2 Planes",
.fourcc = V4L2_PIX_FMT_NV12M,
.codec_mode = S5P_FIMV_CODEC_NONE,
.type = MFC_FMT_RAW,
.num_planes = 2,
},
{
.name = "H264 Encoded Stream",
.fourcc = V4L2_PIX_FMT_H264,
.codec_mode = S5P_FIMV_CODEC_H264_DEC,
.type = MFC_FMT_DEC,
.num_planes = 1,
},
{
.name = "H263 Encoded Stream",
.fourcc = V4L2_PIX_FMT_H263,
.codec_mode = S5P_FIMV_CODEC_H263_DEC,
.type = MFC_FMT_DEC,
.num_planes = 1,
},
{
.name = "MPEG1 Encoded Stream",
.fourcc = V4L2_PIX_FMT_MPEG1,
.codec_mode = S5P_FIMV_CODEC_MPEG2_DEC,
.type = MFC_FMT_DEC,
.num_planes = 1,
},
{
.name = "MPEG2 Encoded Stream",
.fourcc = V4L2_PIX_FMT_MPEG2,
.codec_mode = S5P_FIMV_CODEC_MPEG2_DEC,
.type = MFC_FMT_DEC,
.num_planes = 1,
},
{
.name = "MPEG4 Encoded Stream",
.fourcc = V4L2_PIX_FMT_MPEG4,
.codec_mode = S5P_FIMV_CODEC_MPEG4_DEC,
.type = MFC_FMT_DEC,
.num_planes = 1,
},
{
.name = "XviD Encoded Stream",
.fourcc = V4L2_PIX_FMT_XVID,
.codec_mode = S5P_FIMV_CODEC_MPEG4_DEC,
.type = MFC_FMT_DEC,
.num_planes = 1,
},
{
.name = "VC1 Encoded Stream",
.fourcc = V4L2_PIX_FMT_VC1_ANNEX_G,
.codec_mode = S5P_FIMV_CODEC_VC1_DEC,
.type = MFC_FMT_DEC,
.num_planes = 1,
},
{
.name = "VC1 RCV Encoded Stream",
.fourcc = V4L2_PIX_FMT_VC1_ANNEX_L,
.codec_mode = S5P_FIMV_CODEC_VC1RCV_DEC,
.type = MFC_FMT_DEC,
.num_planes = 1,
},
};
#define NUM_FORMATS ARRAY_SIZE(formats)
/* Find selected format description */
static struct s5p_mfc_fmt *find_format(struct v4l2_format *f, unsigned int t)
{
unsigned int i;
for (i = 0; i < NUM_FORMATS; i++) {
if (formats[i].fourcc == f->fmt.pix_mp.pixelformat &&
formats[i].type == t)
return &formats[i];
}
return NULL;
}
static struct mfc_control controls[] = {
{
.id = V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "H264 Display Delay",
.minimum = 0,
.maximum = 16383,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY_ENABLE,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "H264 Display Delay Enable",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_MPEG_VIDEO_DECODER_MPEG4_DEBLOCK_FILTER,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Mpeg4 Loop Filter Enable",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_MPEG_VIDEO_DECODER_SLICE_INTERFACE,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Slice Interface Enable",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
{
.id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Minimum number of cap bufs",
.minimum = 1,
.maximum = 32,
.step = 1,
.default_value = 1,
.is_volatile = 1,
},
};
#define NUM_CTRLS ARRAY_SIZE(controls)
/* Check whether a context should be run on hardware */
static int s5p_mfc_ctx_ready(struct s5p_mfc_ctx *ctx)
{
/* Context is to parse header */
if (ctx->src_queue_cnt >= 1 && ctx->state == MFCINST_GOT_INST)
return 1;
/* Context is to decode a frame */
if (ctx->src_queue_cnt >= 1 &&
ctx->state == MFCINST_RUNNING &&
ctx->dst_queue_cnt >= ctx->dpb_count)
return 1;
/* Context is to return last frame */
if (ctx->state == MFCINST_FINISHING &&
ctx->dst_queue_cnt >= ctx->dpb_count)
return 1;
/* Context is to set buffers */
if (ctx->src_queue_cnt >= 1 &&
ctx->state == MFCINST_HEAD_PARSED &&
ctx->capture_state == QUEUE_BUFS_MMAPED)
return 1;
/* Resolution change */
if ((ctx->state == MFCINST_RES_CHANGE_INIT ||
ctx->state == MFCINST_RES_CHANGE_FLUSH) &&
ctx->dst_queue_cnt >= ctx->dpb_count)
return 1;
if (ctx->state == MFCINST_RES_CHANGE_END &&
ctx->src_queue_cnt >= 1)
return 1;
mfc_debug(2, "ctx is not ready\n");
return 0;
}
static struct s5p_mfc_codec_ops decoder_codec_ops = {
.pre_seq_start = NULL,
.post_seq_start = NULL,
.pre_frame_start = NULL,
.post_frame_start = NULL,
};
/* Query capabilities of the device */
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct s5p_mfc_dev *dev = video_drvdata(file);
strncpy(cap->driver, dev->plat_dev->name, sizeof(cap->driver) - 1);
strncpy(cap->card, dev->plat_dev->name, sizeof(cap->card) - 1);
cap->bus_info[0] = 0;
cap->version = KERNEL_VERSION(1, 0, 0);
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE_MPLANE |
V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_STREAMING;
return 0;
}
/* Enumerate format */
static int vidioc_enum_fmt(struct v4l2_fmtdesc *f, bool mplane, bool out)
{
struct s5p_mfc_fmt *fmt;
int i, j = 0;
for (i = 0; i < ARRAY_SIZE(formats); ++i) {
if (mplane && formats[i].num_planes == 1)
continue;
else if (!mplane && formats[i].num_planes > 1)
continue;
if (out && formats[i].type != MFC_FMT_DEC)
continue;
else if (!out && formats[i].type != MFC_FMT_RAW)
continue;
if (j == f->index)
break;
++j;
}
if (i == ARRAY_SIZE(formats))
return -EINVAL;
fmt = &formats[i];
strlcpy(f->description, fmt->name, sizeof(f->description));
f->pixelformat = fmt->fourcc;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *pirv,
struct v4l2_fmtdesc *f)
{
return vidioc_enum_fmt(f, false, false);
}
static int vidioc_enum_fmt_vid_cap_mplane(struct file *file, void *pirv,
struct v4l2_fmtdesc *f)
{
return vidioc_enum_fmt(f, true, false);
}
static int vidioc_enum_fmt_vid_out(struct file *file, void *prov,
struct v4l2_fmtdesc *f)
{
return vidioc_enum_fmt(f, false, true);
}
static int vidioc_enum_fmt_vid_out_mplane(struct file *file, void *prov,
struct v4l2_fmtdesc *f)
{
return vidioc_enum_fmt(f, true, true);
}
/* Get format */
static int vidioc_g_fmt(struct file *file, void *priv, struct v4l2_format *f)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
struct v4l2_pix_format_mplane *pix_mp;
mfc_debug_enter();
pix_mp = &f->fmt.pix_mp;
if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE &&
(ctx->state == MFCINST_GOT_INST || ctx->state ==
MFCINST_RES_CHANGE_END)) {
/* If the MFC is parsing the header,
* so wait until it is finished */
s5p_mfc_clean_ctx_int_flags(ctx);
s5p_mfc_wait_for_done_ctx(ctx, S5P_FIMV_R2H_CMD_SEQ_DONE_RET,
0);
}
if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE &&
ctx->state >= MFCINST_HEAD_PARSED &&
ctx->state < MFCINST_ABORT) {
/* This is run on CAPTURE (decode output) */
/* Width and height are set to the dimensions
of the movie, the buffer is bigger and
further processing stages should crop to this
rectangle. */
pix_mp->width = ctx->buf_width;
pix_mp->height = ctx->buf_height;
pix_mp->field = V4L2_FIELD_NONE;
pix_mp->num_planes = 2;
/* Set pixelformat to the format in which MFC
outputs the decoded frame */
pix_mp->pixelformat = V4L2_PIX_FMT_NV12MT;
pix_mp->plane_fmt[0].bytesperline = ctx->buf_width;
pix_mp->plane_fmt[0].sizeimage = ctx->luma_size;
pix_mp->plane_fmt[1].bytesperline = ctx->buf_width;
pix_mp->plane_fmt[1].sizeimage = ctx->chroma_size;
} else if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
/* This is run on OUTPUT
The buffer contains compressed image
so width and height have no meaning */
pix_mp->width = 0;
pix_mp->height = 0;
pix_mp->field = V4L2_FIELD_NONE;
pix_mp->plane_fmt[0].bytesperline = ctx->dec_src_buf_size;
pix_mp->plane_fmt[0].sizeimage = ctx->dec_src_buf_size;
pix_mp->pixelformat = ctx->src_fmt->fourcc;
pix_mp->num_planes = ctx->src_fmt->num_planes;
} else {
mfc_err("Format could not be read\n");
mfc_debug(2, "%s-- with error\n", __func__);
return -EINVAL;
}
mfc_debug_leave();
return 0;
}
/* Try format */
static int vidioc_try_fmt(struct file *file, void *priv, struct v4l2_format *f)
{
struct s5p_mfc_fmt *fmt;
if (f->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
mfc_err("This node supports decoding only\n");
return -EINVAL;
}
fmt = find_format(f, MFC_FMT_DEC);
if (!fmt) {
mfc_err("Unsupported format\n");
return -EINVAL;
}
if (fmt->type != MFC_FMT_DEC) {
mfc_err("\n");
return -EINVAL;
}
return 0;
}
/* Set format */
static int vidioc_s_fmt(struct file *file, void *priv, struct v4l2_format *f)
{
struct s5p_mfc_dev *dev = video_drvdata(file);
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
int ret = 0;
struct s5p_mfc_fmt *fmt;
struct v4l2_pix_format_mplane *pix_mp;
mfc_debug_enter();
ret = vidioc_try_fmt(file, priv, f);
pix_mp = &f->fmt.pix_mp;
if (ret)
return ret;
if (ctx->vq_src.streaming || ctx->vq_dst.streaming) {
v4l2_err(&dev->v4l2_dev, "%s queue busy\n", __func__);
ret = -EBUSY;
goto out;
}
fmt = find_format(f, MFC_FMT_DEC);
if (!fmt || fmt->codec_mode == S5P_FIMV_CODEC_NONE) {
mfc_err("Unknown codec\n");
ret = -EINVAL;
goto out;
}
if (fmt->type != MFC_FMT_DEC) {
mfc_err("Wrong format selected, you should choose "
"format for decoding\n");
ret = -EINVAL;
goto out;
}
ctx->src_fmt = fmt;
ctx->codec_mode = fmt->codec_mode;
mfc_debug(2, "The codec number is: %d\n", ctx->codec_mode);
pix_mp->height = 0;
pix_mp->width = 0;
if (pix_mp->plane_fmt[0].sizeimage)
ctx->dec_src_buf_size = pix_mp->plane_fmt[0].sizeimage;
else
pix_mp->plane_fmt[0].sizeimage = ctx->dec_src_buf_size =
DEF_CPB_SIZE;
pix_mp->plane_fmt[0].bytesperline = 0;
ctx->state = MFCINST_INIT;
out:
mfc_debug_leave();
return ret;
}
/* Reqeust buffers */
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *reqbufs)
{
struct s5p_mfc_dev *dev = video_drvdata(file);
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
int ret = 0;
unsigned long flags;
if (reqbufs->memory != V4L2_MEMORY_MMAP) {
mfc_err("Only V4L2_MEMORY_MAP is supported\n");
return -EINVAL;
}
if (reqbufs->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
/* Can only request buffers after an instance has been opened.*/
if (ctx->state == MFCINST_INIT) {
ctx->src_bufs_cnt = 0;
if (reqbufs->count == 0) {
mfc_debug(2, "Freeing buffers\n");
s5p_mfc_clock_on();
ret = vb2_reqbufs(&ctx->vq_src, reqbufs);
s5p_mfc_clock_off();
return ret;
}
/* Decoding */
if (ctx->output_state != QUEUE_FREE) {
mfc_err("Bufs have already been requested\n");
return -EINVAL;
}
s5p_mfc_clock_on();
ret = vb2_reqbufs(&ctx->vq_src, reqbufs);
s5p_mfc_clock_off();
if (ret) {
mfc_err("vb2_reqbufs on output failed\n");
return ret;
}
mfc_debug(2, "vb2_reqbufs: %d\n", ret);
ctx->output_state = QUEUE_BUFS_REQUESTED;
}
} else if (reqbufs->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
ctx->dst_bufs_cnt = 0;
if (reqbufs->count == 0) {
mfc_debug(2, "Freeing buffers\n");
s5p_mfc_clock_on();
ret = vb2_reqbufs(&ctx->vq_dst, reqbufs);
s5p_mfc_clock_off();
return ret;
}
if (ctx->capture_state != QUEUE_FREE) {
mfc_err("Bufs have already been requested\n");
return -EINVAL;
}
ctx->capture_state = QUEUE_BUFS_REQUESTED;
s5p_mfc_clock_on();
ret = vb2_reqbufs(&ctx->vq_dst, reqbufs);
s5p_mfc_clock_off();
if (ret) {
mfc_err("vb2_reqbufs on capture failed\n");
return ret;
}
if (reqbufs->count < ctx->dpb_count) {
mfc_err("Not enough buffers allocated\n");
reqbufs->count = 0;
s5p_mfc_clock_on();
ret = vb2_reqbufs(&ctx->vq_dst, reqbufs);
s5p_mfc_clock_off();
return -ENOMEM;
}
ctx->total_dpb_count = reqbufs->count;
ret = s5p_mfc_alloc_codec_buffers(ctx);
if (ret) {
mfc_err("Failed to allocate decoding buffers\n");
reqbufs->count = 0;
s5p_mfc_clock_on();
ret = vb2_reqbufs(&ctx->vq_dst, reqbufs);
s5p_mfc_clock_off();
return -ENOMEM;
}
if (ctx->dst_bufs_cnt == ctx->total_dpb_count) {
ctx->capture_state = QUEUE_BUFS_MMAPED;
} else {
mfc_err("Not all buffers passed to buf_init\n");
reqbufs->count = 0;
s5p_mfc_clock_on();
ret = vb2_reqbufs(&ctx->vq_dst, reqbufs);
s5p_mfc_release_codec_buffers(ctx);
s5p_mfc_clock_off();
return -ENOMEM;
}
if (s5p_mfc_ctx_ready(ctx)) {
spin_lock_irqsave(&dev->condlock, flags);
set_bit(ctx->num, &dev->ctx_work_bits);
spin_unlock_irqrestore(&dev->condlock, flags);
}
s5p_mfc_try_run(dev);
s5p_mfc_wait_for_done_ctx(ctx,
S5P_FIMV_R2H_CMD_INIT_BUFFERS_RET, 0);
}
return ret;
}
/* Query buffer */
static int vidioc_querybuf(struct file *file, void *priv,
struct v4l2_buffer *buf)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
int ret;
int i;
if (buf->memory != V4L2_MEMORY_MMAP) {
mfc_err("Only mmaped buffers can be used\n");
return -EINVAL;
}
mfc_debug(2, "State: %d, buf->type: %d\n", ctx->state, buf->type);
if (ctx->state == MFCINST_INIT &&
buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
ret = vb2_querybuf(&ctx->vq_src, buf);
} else if (ctx->state == MFCINST_RUNNING &&
buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
ret = vb2_querybuf(&ctx->vq_dst, buf);
for (i = 0; i < buf->length; i++)
buf->m.planes[i].m.mem_offset += DST_QUEUE_OFF_BASE;
} else {
mfc_err("vidioc_querybuf called in an inappropriate state\n");
ret = -EINVAL;
}
mfc_debug_leave();
return ret;
}
/* Queue a buffer */
static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *buf)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
if (ctx->state == MFCINST_ERROR) {
mfc_err("Call on QBUF after unrecoverable error\n");
return -EIO;
}
if (buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
return vb2_qbuf(&ctx->vq_src, buf);
else if (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
return vb2_qbuf(&ctx->vq_dst, buf);
return -EINVAL;
}
/* Dequeue a buffer */
static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *buf)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
if (ctx->state == MFCINST_ERROR) {
mfc_err("Call on DQBUF after unrecoverable error\n");
return -EIO;
}
if (buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
return vb2_dqbuf(&ctx->vq_src, buf, file->f_flags & O_NONBLOCK);
else if (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
return vb2_dqbuf(&ctx->vq_dst, buf, file->f_flags & O_NONBLOCK);
return -EINVAL;
}
/* Stream on */
static int vidioc_streamon(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
struct s5p_mfc_dev *dev = ctx->dev;
unsigned long flags;
int ret = -EINVAL;
mfc_debug_enter();
if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (ctx->state == MFCINST_INIT) {
ctx->dst_bufs_cnt = 0;
ctx->src_bufs_cnt = 0;
ctx->capture_state = QUEUE_FREE;
ctx->output_state = QUEUE_FREE;
s5p_mfc_alloc_instance_buffer(ctx);
s5p_mfc_alloc_dec_temp_buffers(ctx);
spin_lock_irqsave(&dev->condlock, flags);
set_bit(ctx->num, &dev->ctx_work_bits);
spin_unlock_irqrestore(&dev->condlock, flags);
s5p_mfc_clean_ctx_int_flags(ctx);
s5p_mfc_try_run(dev);
if (s5p_mfc_wait_for_done_ctx(ctx,
S5P_FIMV_R2H_CMD_OPEN_INSTANCE_RET, 0)) {
/* Error or timeout */
mfc_err("Error getting instance from hardware\n");
s5p_mfc_release_instance_buffer(ctx);
s5p_mfc_release_dec_desc_buffer(ctx);
return -EIO;
}
mfc_debug(2, "Got instance number: %d\n", ctx->inst_no);
}
ret = vb2_streamon(&ctx->vq_src, type);
}
else if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
ret = vb2_streamon(&ctx->vq_dst, type);
mfc_debug_leave();
return ret;
}
/* Stream off, which equals to a pause */
static int vidioc_streamoff(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
return vb2_streamoff(&ctx->vq_src, type);
else if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
return vb2_streamoff(&ctx->vq_dst, type);
return -EINVAL;
}
/* Set controls - v4l2 control framework */
static int s5p_mfc_dec_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct s5p_mfc_ctx *ctx = ctrl_to_ctx(ctrl);
switch (ctrl->id) {
case V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY:
ctx->loop_filter_mpeg4 = ctrl->val;
break;
case V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY_ENABLE:
ctx->display_delay_enable = ctrl->val;
break;
case V4L2_CID_MPEG_VIDEO_DECODER_MPEG4_DEBLOCK_FILTER:
ctx->display_delay = ctrl->val;
break;
case V4L2_CID_MPEG_VIDEO_DECODER_SLICE_INTERFACE:
ctx->slice_interface = ctrl->val;
break;
default:
mfc_err("Invalid control 0x%08x\n", ctrl->id);
return -EINVAL;
}
return 0;
}
static int s5p_mfc_dec_g_v_ctrl(struct v4l2_ctrl *ctrl)
{
struct s5p_mfc_ctx *ctx = ctrl_to_ctx(ctrl);
struct s5p_mfc_dev *dev = ctx->dev;
switch (ctrl->id) {
case V4L2_CID_MIN_BUFFERS_FOR_CAPTURE:
if (ctx->state >= MFCINST_HEAD_PARSED &&
ctx->state < MFCINST_ABORT) {
ctrl->val = ctx->dpb_count;
break;
} else if (ctx->state != MFCINST_INIT) {
v4l2_err(&dev->v4l2_dev, "Decoding not initialised\n");
return -EINVAL;
}
/* Should wait for the header to be parsed */
s5p_mfc_clean_ctx_int_flags(ctx);
s5p_mfc_wait_for_done_ctx(ctx,
S5P_FIMV_R2H_CMD_SEQ_DONE_RET, 0);
if (ctx->state >= MFCINST_HEAD_PARSED &&
ctx->state < MFCINST_ABORT) {
ctrl->val = ctx->dpb_count;
} else {
v4l2_err(&dev->v4l2_dev, "Decoding not initialised\n");
return -EINVAL;
}
break;
}
return 0;
}
static const struct v4l2_ctrl_ops s5p_mfc_dec_ctrl_ops = {
.s_ctrl = s5p_mfc_dec_s_ctrl,
.g_volatile_ctrl = s5p_mfc_dec_g_v_ctrl,
};
/* Get cropping information */
static int vidioc_g_crop(struct file *file, void *priv,
struct v4l2_crop *cr)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(priv);
u32 left, right, top, bottom;
if (ctx->state != MFCINST_HEAD_PARSED &&
ctx->state != MFCINST_RUNNING && ctx->state != MFCINST_FINISHING
&& ctx->state != MFCINST_FINISHED) {
mfc_err("Cannont set crop\n");
return -EINVAL;
}
if (ctx->src_fmt->fourcc == V4L2_PIX_FMT_H264) {
left = s5p_mfc_read_shm(ctx, CROP_INFO_H);
right = left >> S5P_FIMV_SHARED_CROP_RIGHT_SHIFT;
left = left & S5P_FIMV_SHARED_CROP_LEFT_MASK;
top = s5p_mfc_read_shm(ctx, CROP_INFO_V);
bottom = top >> S5P_FIMV_SHARED_CROP_BOTTOM_SHIFT;
top = top & S5P_FIMV_SHARED_CROP_TOP_MASK;
cr->c.left = left;
cr->c.top = top;
cr->c.width = ctx->img_width - left - right;
cr->c.height = ctx->img_height - top - bottom;
mfc_debug(2, "Cropping info [h264]: l=%d t=%d "
"w=%d h=%d (r=%d b=%d fw=%d fh=%d\n", left, top,
cr->c.width, cr->c.height, right, bottom,
ctx->buf_width, ctx->buf_height);
} else {
cr->c.left = 0;
cr->c.top = 0;
cr->c.width = ctx->img_width;
cr->c.height = ctx->img_height;
mfc_debug(2, "Cropping info: w=%d h=%d fw=%d "
"fh=%d\n", cr->c.width, cr->c.height, ctx->buf_width,
ctx->buf_height);
}
return 0;
}
/* v4l2_ioctl_ops */
static const struct v4l2_ioctl_ops s5p_mfc_dec_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_enum_fmt_vid_cap_mplane = vidioc_enum_fmt_vid_cap_mplane,
.vidioc_enum_fmt_vid_out = vidioc_enum_fmt_vid_out,
.vidioc_enum_fmt_vid_out_mplane = vidioc_enum_fmt_vid_out_mplane,
.vidioc_g_fmt_vid_cap_mplane = vidioc_g_fmt,
.vidioc_g_fmt_vid_out_mplane = vidioc_g_fmt,
.vidioc_try_fmt_vid_cap_mplane = vidioc_try_fmt,
.vidioc_try_fmt_vid_out_mplane = vidioc_try_fmt,
.vidioc_s_fmt_vid_cap_mplane = vidioc_s_fmt,
.vidioc_s_fmt_vid_out_mplane = vidioc_s_fmt,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_g_crop = vidioc_g_crop,
};
static int s5p_mfc_queue_setup(struct vb2_queue *vq,
const struct v4l2_format *fmt, unsigned int *buf_count,
unsigned int *plane_count, unsigned int psize[],
void *allocators[])
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(vq->drv_priv);
/* Video output for decoding (source)
* this can be set after getting an instance */
if (ctx->state == MFCINST_INIT &&
vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
/* A single plane is required for input */
*plane_count = 1;
if (*buf_count < 1)
*buf_count = 1;
if (*buf_count > MFC_MAX_BUFFERS)
*buf_count = MFC_MAX_BUFFERS;
/* Video capture for decoding (destination)
* this can be set after the header was parsed */
} else if (ctx->state == MFCINST_HEAD_PARSED &&
vq->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
/* Output plane count is 2 - one for Y and one for CbCr */
*plane_count = 2;
/* Setup buffer count */
if (*buf_count < ctx->dpb_count)
*buf_count = ctx->dpb_count;
if (*buf_count > ctx->dpb_count + MFC_MAX_EXTRA_DPB)
*buf_count = ctx->dpb_count + MFC_MAX_EXTRA_DPB;
if (*buf_count > MFC_MAX_BUFFERS)
*buf_count = MFC_MAX_BUFFERS;
} else {
mfc_err("State seems invalid. State = %d, vq->type = %d\n",
ctx->state, vq->type);
return -EINVAL;
}
mfc_debug(2, "Buffer count=%d, plane count=%d\n",
*buf_count, *plane_count);
if (ctx->state == MFCINST_HEAD_PARSED &&
vq->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
psize[0] = ctx->luma_size;
psize[1] = ctx->chroma_size;
allocators[0] = ctx->dev->alloc_ctx[MFC_BANK2_ALLOC_CTX];
allocators[1] = ctx->dev->alloc_ctx[MFC_BANK1_ALLOC_CTX];
} else if (vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE &&
ctx->state == MFCINST_INIT) {
psize[0] = ctx->dec_src_buf_size;
allocators[0] = ctx->dev->alloc_ctx[MFC_BANK1_ALLOC_CTX];
} else {
mfc_err("This video node is dedicated to decoding. Decoding not initalised\n");
return -EINVAL;
}
return 0;
}
static void s5p_mfc_unlock(struct vb2_queue *q)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(q->drv_priv);
struct s5p_mfc_dev *dev = ctx->dev;
mutex_unlock(&dev->mfc_mutex);
}
static void s5p_mfc_lock(struct vb2_queue *q)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(q->drv_priv);
struct s5p_mfc_dev *dev = ctx->dev;
mutex_lock(&dev->mfc_mutex);
}
static int s5p_mfc_buf_init(struct vb2_buffer *vb)
{
struct vb2_queue *vq = vb->vb2_queue;
struct s5p_mfc_ctx *ctx = fh_to_ctx(vq->drv_priv);
unsigned int i;
if (vq->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (ctx->capture_state == QUEUE_BUFS_MMAPED)
return 0;
for (i = 0; i <= ctx->src_fmt->num_planes ; i++) {
if (IS_ERR_OR_NULL(ERR_PTR(
vb2_dma_contig_plane_dma_addr(vb, i)))) {
mfc_err("Plane mem not allocated\n");
return -EINVAL;
}
}
if (vb2_plane_size(vb, 0) < ctx->luma_size ||
vb2_plane_size(vb, 1) < ctx->chroma_size) {
mfc_err("Plane buffer (CAPTURE) is too small\n");
return -EINVAL;
}
i = vb->v4l2_buf.index;
ctx->dst_bufs[i].b = vb;
ctx->dst_bufs[i].cookie.raw.luma =
vb2_dma_contig_plane_dma_addr(vb, 0);
ctx->dst_bufs[i].cookie.raw.chroma =
vb2_dma_contig_plane_dma_addr(vb, 1);
ctx->dst_bufs_cnt++;
} else if (vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (IS_ERR_OR_NULL(ERR_PTR(
vb2_dma_contig_plane_dma_addr(vb, 0)))) {
mfc_err("Plane memory not allocated\n");
return -EINVAL;
}
if (vb2_plane_size(vb, 0) < ctx->dec_src_buf_size) {
mfc_err("Plane buffer (OUTPUT) is too small\n");
return -EINVAL;
}
i = vb->v4l2_buf.index;
ctx->src_bufs[i].b = vb;
ctx->src_bufs[i].cookie.stream =
vb2_dma_contig_plane_dma_addr(vb, 0);
ctx->src_bufs_cnt++;
} else {
mfc_err("s5p_mfc_buf_init: unknown queue type\n");
return -EINVAL;
}
return 0;
}
static int s5p_mfc_start_streaming(struct vb2_queue *q, unsigned int count)
{
struct s5p_mfc_ctx *ctx = fh_to_ctx(q->drv_priv);
struct s5p_mfc_dev *dev = ctx->dev;
unsigned long flags;
v4l2_ctrl_handler_setup(&ctx->ctrl_handler);
if (ctx->state == MFCINST_FINISHING ||
ctx->state == MFCINST_FINISHED)
ctx->state = MFCINST_RUNNING;
/* If context is ready then dev = work->data;schedule it to run */
if (s5p_mfc_ctx_ready(ctx)) {
spin_lock_irqsave(&dev->condlock, flags);
set_bit(ctx->num, &dev->ctx_work_bits);
spin_unlock_irqrestore(&dev->condlock, flags);
}
s5p_mfc_try_run(dev);
return 0;
}
static int s5p_mfc_stop_streaming(struct vb2_queue *q)
{
unsigned long flags;
struct s5p_mfc_ctx *ctx = fh_to_ctx(q->drv_priv);
struct s5p_mfc_dev *dev = ctx->dev;
int aborted = 0;
if ((ctx->state == MFCINST_FINISHING ||
ctx->state == MFCINST_RUNNING) &&
dev->curr_ctx == ctx->num && dev->hw_lock) {
ctx->state = MFCINST_ABORT;
s5p_mfc_wait_for_done_ctx(ctx,
S5P_FIMV_R2H_CMD_FRAME_DONE_RET, 0);
aborted = 1;
}
spin_lock_irqsave(&dev->irqlock, flags);
if (q->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
s5p_mfc_cleanup_queue(&ctx->dst_queue, &ctx->vq_dst);
INIT_LIST_HEAD(&ctx->dst_queue);
ctx->dst_queue_cnt = 0;
ctx->dpb_flush_flag = 1;
ctx->dec_dst_flag = 0;
}
if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
s5p_mfc_cleanup_queue(&ctx->src_queue, &ctx->vq_src);
INIT_LIST_HEAD(&ctx->src_queue);
ctx->src_queue_cnt = 0;
}
if (aborted)
ctx->state = MFCINST_RUNNING;
spin_unlock_irqrestore(&dev->irqlock, flags);
return 0;
}
static void s5p_mfc_buf_queue(struct vb2_buffer *vb)
{
struct vb2_queue *vq = vb->vb2_queue;
struct s5p_mfc_ctx *ctx = fh_to_ctx(vq->drv_priv);
struct s5p_mfc_dev *dev = ctx->dev;
unsigned long flags;
struct s5p_mfc_buf *mfc_buf;
if (vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
mfc_buf = &ctx->src_bufs[vb->v4l2_buf.index];
mfc_buf->used = 0;
spin_lock_irqsave(&dev->irqlock, flags);
list_add_tail(&mfc_buf->list, &ctx->src_queue);
ctx->src_queue_cnt++;
spin_unlock_irqrestore(&dev->irqlock, flags);
} else if (vq->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
mfc_buf = &ctx->dst_bufs[vb->v4l2_buf.index];
mfc_buf->used = 0;
/* Mark destination as available for use by MFC */
spin_lock_irqsave(&dev->irqlock, flags);
set_bit(vb->v4l2_buf.index, &ctx->dec_dst_flag);
list_add_tail(&mfc_buf->list, &ctx->dst_queue);
ctx->dst_queue_cnt++;
spin_unlock_irqrestore(&dev->irqlock, flags);
} else {
mfc_err("Unsupported buffer type (%d)\n", vq->type);
}
if (s5p_mfc_ctx_ready(ctx)) {
spin_lock_irqsave(&dev->condlock, flags);
set_bit(ctx->num, &dev->ctx_work_bits);
spin_unlock_irqrestore(&dev->condlock, flags);
}
s5p_mfc_try_run(dev);
}
static struct vb2_ops s5p_mfc_dec_qops = {
.queue_setup = s5p_mfc_queue_setup,
.wait_prepare = s5p_mfc_unlock,
.wait_finish = s5p_mfc_lock,
.buf_init = s5p_mfc_buf_init,
.start_streaming = s5p_mfc_start_streaming,
.stop_streaming = s5p_mfc_stop_streaming,
.buf_queue = s5p_mfc_buf_queue,
};
struct s5p_mfc_codec_ops *get_dec_codec_ops(void)
{
return &decoder_codec_ops;
}
struct vb2_ops *get_dec_queue_ops(void)
{
return &s5p_mfc_dec_qops;
}
const struct v4l2_ioctl_ops *get_dec_v4l2_ioctl_ops(void)
{
return &s5p_mfc_dec_ioctl_ops;
}
#define IS_MFC51_PRIV(x) ((V4L2_CTRL_ID2CLASS(x) == V4L2_CTRL_CLASS_MPEG) \
&& V4L2_CTRL_DRIVER_PRIV(x))
int s5p_mfc_dec_ctrls_setup(struct s5p_mfc_ctx *ctx)
{
struct v4l2_ctrl_config cfg;
int i;
v4l2_ctrl_handler_init(&ctx->ctrl_handler, NUM_CTRLS);
if (ctx->ctrl_handler.error) {
mfc_err("v4l2_ctrl_handler_init failed\n");
return ctx->ctrl_handler.error;
}
for (i = 0; i < NUM_CTRLS; i++) {
if (IS_MFC51_PRIV(controls[i].id)) {
cfg.ops = &s5p_mfc_dec_ctrl_ops;
cfg.id = controls[i].id;
cfg.min = controls[i].minimum;
cfg.max = controls[i].maximum;
cfg.def = controls[i].default_value;
cfg.name = controls[i].name;
cfg.type = controls[i].type;
cfg.step = controls[i].step;
cfg.menu_skip_mask = 0;
ctx->ctrls[i] = v4l2_ctrl_new_custom(&ctx->ctrl_handler,
&cfg, NULL);
} else {
ctx->ctrls[i] = v4l2_ctrl_new_std(&ctx->ctrl_handler,
&s5p_mfc_dec_ctrl_ops,
controls[i].id, controls[i].minimum,
controls[i].maximum, controls[i].step,
controls[i].default_value);
}
if (ctx->ctrl_handler.error) {
mfc_err("Adding control (%d) failed\n", i);
return ctx->ctrl_handler.error;
}
if (controls[i].is_volatile && ctx->ctrls[i])
ctx->ctrls[i]->flags |= V4L2_CTRL_FLAG_VOLATILE;
}
return 0;
}
void s5p_mfc_dec_ctrls_delete(struct s5p_mfc_ctx *ctx)
{
int i;
v4l2_ctrl_handler_free(&ctx->ctrl_handler);
for (i = 0; i < NUM_CTRLS; i++)
ctx->ctrls[i] = NULL;
}
| gpl-2.0 |
ruslan250283/alcatel_6036 | tools/vm/slabinfo.c | 5125 | 34900 | /*
* Slabinfo: Tool to get reports about slabs
*
* (C) 2007 sgi, Christoph Lameter
* (C) 2011 Linux Foundation, Christoph Lameter
*
* Compile with:
*
* gcc -o slabinfo slabinfo.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <getopt.h>
#include <regex.h>
#include <errno.h>
#define MAX_SLABS 500
#define MAX_ALIASES 500
#define MAX_NODES 1024
struct slabinfo {
char *name;
int alias;
int refs;
int aliases, align, cache_dma, cpu_slabs, destroy_by_rcu;
int hwcache_align, object_size, objs_per_slab;
int sanity_checks, slab_size, store_user, trace;
int order, poison, reclaim_account, red_zone;
unsigned long partial, objects, slabs, objects_partial, objects_total;
unsigned long alloc_fastpath, alloc_slowpath;
unsigned long free_fastpath, free_slowpath;
unsigned long free_frozen, free_add_partial, free_remove_partial;
unsigned long alloc_from_partial, alloc_slab, free_slab, alloc_refill;
unsigned long cpuslab_flush, deactivate_full, deactivate_empty;
unsigned long deactivate_to_head, deactivate_to_tail;
unsigned long deactivate_remote_frees, order_fallback;
unsigned long cmpxchg_double_cpu_fail, cmpxchg_double_fail;
unsigned long alloc_node_mismatch, deactivate_bypass;
unsigned long cpu_partial_alloc, cpu_partial_free;
int numa[MAX_NODES];
int numa_partial[MAX_NODES];
} slabinfo[MAX_SLABS];
struct aliasinfo {
char *name;
char *ref;
struct slabinfo *slab;
} aliasinfo[MAX_ALIASES];
int slabs = 0;
int actual_slabs = 0;
int aliases = 0;
int alias_targets = 0;
int highest_node = 0;
char buffer[4096];
int show_empty = 0;
int show_report = 0;
int show_alias = 0;
int show_slab = 0;
int skip_zero = 1;
int show_numa = 0;
int show_track = 0;
int show_first_alias = 0;
int validate = 0;
int shrink = 0;
int show_inverted = 0;
int show_single_ref = 0;
int show_totals = 0;
int sort_size = 0;
int sort_active = 0;
int set_debug = 0;
int show_ops = 0;
int show_activity = 0;
/* Debug options */
int sanity = 0;
int redzone = 0;
int poison = 0;
int tracking = 0;
int tracing = 0;
int page_size;
regex_t pattern;
static void fatal(const char *x, ...)
{
va_list ap;
va_start(ap, x);
vfprintf(stderr, x, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
static void usage(void)
{
printf("slabinfo 4/15/2011. (c) 2007 sgi/(c) 2011 Linux Foundation.\n\n"
"slabinfo [-ahnpvtsz] [-d debugopts] [slab-regexp]\n"
"-a|--aliases Show aliases\n"
"-A|--activity Most active slabs first\n"
"-d<options>|--debug=<options> Set/Clear Debug options\n"
"-D|--display-active Switch line format to activity\n"
"-e|--empty Show empty slabs\n"
"-f|--first-alias Show first alias\n"
"-h|--help Show usage information\n"
"-i|--inverted Inverted list\n"
"-l|--slabs Show slabs\n"
"-n|--numa Show NUMA information\n"
"-o|--ops Show kmem_cache_ops\n"
"-s|--shrink Shrink slabs\n"
"-r|--report Detailed report on single slabs\n"
"-S|--Size Sort by size\n"
"-t|--tracking Show alloc/free information\n"
"-T|--Totals Show summary information\n"
"-v|--validate Validate slabs\n"
"-z|--zero Include empty slabs\n"
"-1|--1ref Single reference\n"
"\nValid debug options (FZPUT may be combined)\n"
"a / A Switch on all debug options (=FZUP)\n"
"- Switch off all debug options\n"
"f / F Sanity Checks (SLAB_DEBUG_FREE)\n"
"z / Z Redzoning\n"
"p / P Poisoning\n"
"u / U Tracking\n"
"t / T Tracing\n"
);
}
static unsigned long read_obj(const char *name)
{
FILE *f = fopen(name, "r");
if (!f)
buffer[0] = 0;
else {
if (!fgets(buffer, sizeof(buffer), f))
buffer[0] = 0;
fclose(f);
if (buffer[strlen(buffer)] == '\n')
buffer[strlen(buffer)] = 0;
}
return strlen(buffer);
}
/*
* Get the contents of an attribute
*/
static unsigned long get_obj(const char *name)
{
if (!read_obj(name))
return 0;
return atol(buffer);
}
static unsigned long get_obj_and_str(const char *name, char **x)
{
unsigned long result = 0;
char *p;
*x = NULL;
if (!read_obj(name)) {
x = NULL;
return 0;
}
result = strtoul(buffer, &p, 10);
while (*p == ' ')
p++;
if (*p)
*x = strdup(p);
return result;
}
static void set_obj(struct slabinfo *s, const char *name, int n)
{
char x[100];
FILE *f;
snprintf(x, 100, "%s/%s", s->name, name);
f = fopen(x, "w");
if (!f)
fatal("Cannot write to %s\n", x);
fprintf(f, "%d\n", n);
fclose(f);
}
static unsigned long read_slab_obj(struct slabinfo *s, const char *name)
{
char x[100];
FILE *f;
size_t l;
snprintf(x, 100, "%s/%s", s->name, name);
f = fopen(x, "r");
if (!f) {
buffer[0] = 0;
l = 0;
} else {
l = fread(buffer, 1, sizeof(buffer), f);
buffer[l] = 0;
fclose(f);
}
return l;
}
/*
* Put a size string together
*/
static int store_size(char *buffer, unsigned long value)
{
unsigned long divisor = 1;
char trailer = 0;
int n;
if (value > 1000000000UL) {
divisor = 100000000UL;
trailer = 'G';
} else if (value > 1000000UL) {
divisor = 100000UL;
trailer = 'M';
} else if (value > 1000UL) {
divisor = 100;
trailer = 'K';
}
value /= divisor;
n = sprintf(buffer, "%ld",value);
if (trailer) {
buffer[n] = trailer;
n++;
buffer[n] = 0;
}
if (divisor != 1) {
memmove(buffer + n - 2, buffer + n - 3, 4);
buffer[n-2] = '.';
n++;
}
return n;
}
static void decode_numa_list(int *numa, char *t)
{
int node;
int nr;
memset(numa, 0, MAX_NODES * sizeof(int));
if (!t)
return;
while (*t == 'N') {
t++;
node = strtoul(t, &t, 10);
if (*t == '=') {
t++;
nr = strtoul(t, &t, 10);
numa[node] = nr;
if (node > highest_node)
highest_node = node;
}
while (*t == ' ')
t++;
}
}
static void slab_validate(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
set_obj(s, "validate", 1);
}
static void slab_shrink(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
set_obj(s, "shrink", 1);
}
int line = 0;
static void first_line(void)
{
if (show_activity)
printf("Name Objects Alloc Free %%Fast Fallb O CmpX UL\n");
else
printf("Name Objects Objsize Space "
"Slabs/Part/Cpu O/S O %%Fr %%Ef Flg\n");
}
/*
* Find the shortest alias of a slab
*/
static struct aliasinfo *find_one_alias(struct slabinfo *find)
{
struct aliasinfo *a;
struct aliasinfo *best = NULL;
for(a = aliasinfo;a < aliasinfo + aliases; a++) {
if (a->slab == find &&
(!best || strlen(best->name) < strlen(a->name))) {
best = a;
if (strncmp(a->name,"kmall", 5) == 0)
return best;
}
}
return best;
}
static unsigned long slab_size(struct slabinfo *s)
{
return s->slabs * (page_size << s->order);
}
static unsigned long slab_activity(struct slabinfo *s)
{
return s->alloc_fastpath + s->free_fastpath +
s->alloc_slowpath + s->free_slowpath;
}
static void slab_numa(struct slabinfo *s, int mode)
{
int node;
if (strcmp(s->name, "*") == 0)
return;
if (!highest_node) {
printf("\n%s: No NUMA information available.\n", s->name);
return;
}
if (skip_zero && !s->slabs)
return;
if (!line) {
printf("\n%-21s:", mode ? "NUMA nodes" : "Slab");
for(node = 0; node <= highest_node; node++)
printf(" %4d", node);
printf("\n----------------------");
for(node = 0; node <= highest_node; node++)
printf("-----");
printf("\n");
}
printf("%-21s ", mode ? "All slabs" : s->name);
for(node = 0; node <= highest_node; node++) {
char b[20];
store_size(b, s->numa[node]);
printf(" %4s", b);
}
printf("\n");
if (mode) {
printf("%-21s ", "Partial slabs");
for(node = 0; node <= highest_node; node++) {
char b[20];
store_size(b, s->numa_partial[node]);
printf(" %4s", b);
}
printf("\n");
}
line++;
}
static void show_tracking(struct slabinfo *s)
{
printf("\n%s: Kernel object allocation\n", s->name);
printf("-----------------------------------------------------------------------\n");
if (read_slab_obj(s, "alloc_calls"))
printf("%s", buffer);
else
printf("No Data\n");
printf("\n%s: Kernel object freeing\n", s->name);
printf("------------------------------------------------------------------------\n");
if (read_slab_obj(s, "free_calls"))
printf("%s", buffer);
else
printf("No Data\n");
}
static void ops(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
if (read_slab_obj(s, "ops")) {
printf("\n%s: kmem_cache operations\n", s->name);
printf("--------------------------------------------\n");
printf("%s", buffer);
} else
printf("\n%s has no kmem_cache operations\n", s->name);
}
static const char *onoff(int x)
{
if (x)
return "On ";
return "Off";
}
static void slab_stats(struct slabinfo *s)
{
unsigned long total_alloc;
unsigned long total_free;
unsigned long total;
if (!s->alloc_slab)
return;
total_alloc = s->alloc_fastpath + s->alloc_slowpath;
total_free = s->free_fastpath + s->free_slowpath;
if (!total_alloc)
return;
printf("\n");
printf("Slab Perf Counter Alloc Free %%Al %%Fr\n");
printf("--------------------------------------------------\n");
printf("Fastpath %8lu %8lu %3lu %3lu\n",
s->alloc_fastpath, s->free_fastpath,
s->alloc_fastpath * 100 / total_alloc,
s->free_fastpath * 100 / total_free);
printf("Slowpath %8lu %8lu %3lu %3lu\n",
total_alloc - s->alloc_fastpath, s->free_slowpath,
(total_alloc - s->alloc_fastpath) * 100 / total_alloc,
s->free_slowpath * 100 / total_free);
printf("Page Alloc %8lu %8lu %3lu %3lu\n",
s->alloc_slab, s->free_slab,
s->alloc_slab * 100 / total_alloc,
s->free_slab * 100 / total_free);
printf("Add partial %8lu %8lu %3lu %3lu\n",
s->deactivate_to_head + s->deactivate_to_tail,
s->free_add_partial,
(s->deactivate_to_head + s->deactivate_to_tail) * 100 / total_alloc,
s->free_add_partial * 100 / total_free);
printf("Remove partial %8lu %8lu %3lu %3lu\n",
s->alloc_from_partial, s->free_remove_partial,
s->alloc_from_partial * 100 / total_alloc,
s->free_remove_partial * 100 / total_free);
printf("Cpu partial list %8lu %8lu %3lu %3lu\n",
s->cpu_partial_alloc, s->cpu_partial_free,
s->cpu_partial_alloc * 100 / total_alloc,
s->cpu_partial_free * 100 / total_free);
printf("RemoteObj/SlabFrozen %8lu %8lu %3lu %3lu\n",
s->deactivate_remote_frees, s->free_frozen,
s->deactivate_remote_frees * 100 / total_alloc,
s->free_frozen * 100 / total_free);
printf("Total %8lu %8lu\n\n", total_alloc, total_free);
if (s->cpuslab_flush)
printf("Flushes %8lu\n", s->cpuslab_flush);
total = s->deactivate_full + s->deactivate_empty +
s->deactivate_to_head + s->deactivate_to_tail + s->deactivate_bypass;
if (total) {
printf("\nSlab Deactivation Ocurrences %%\n");
printf("-------------------------------------------------\n");
printf("Slab full %7lu %3lu%%\n",
s->deactivate_full, (s->deactivate_full * 100) / total);
printf("Slab empty %7lu %3lu%%\n",
s->deactivate_empty, (s->deactivate_empty * 100) / total);
printf("Moved to head of partial list %7lu %3lu%%\n",
s->deactivate_to_head, (s->deactivate_to_head * 100) / total);
printf("Moved to tail of partial list %7lu %3lu%%\n",
s->deactivate_to_tail, (s->deactivate_to_tail * 100) / total);
printf("Deactivation bypass %7lu %3lu%%\n",
s->deactivate_bypass, (s->deactivate_bypass * 100) / total);
printf("Refilled from foreign frees %7lu %3lu%%\n",
s->alloc_refill, (s->alloc_refill * 100) / total);
printf("Node mismatch %7lu %3lu%%\n",
s->alloc_node_mismatch, (s->alloc_node_mismatch * 100) / total);
}
if (s->cmpxchg_double_fail || s->cmpxchg_double_cpu_fail)
printf("\nCmpxchg_double Looping\n------------------------\n");
printf("Locked Cmpxchg Double redos %lu\nUnlocked Cmpxchg Double redos %lu\n",
s->cmpxchg_double_fail, s->cmpxchg_double_cpu_fail);
}
static void report(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
printf("\nSlabcache: %-20s Aliases: %2d Order : %2d Objects: %lu\n",
s->name, s->aliases, s->order, s->objects);
if (s->hwcache_align)
printf("** Hardware cacheline aligned\n");
if (s->cache_dma)
printf("** Memory is allocated in a special DMA zone\n");
if (s->destroy_by_rcu)
printf("** Slabs are destroyed via RCU\n");
if (s->reclaim_account)
printf("** Reclaim accounting active\n");
printf("\nSizes (bytes) Slabs Debug Memory\n");
printf("------------------------------------------------------------------------\n");
printf("Object : %7d Total : %7ld Sanity Checks : %s Total: %7ld\n",
s->object_size, s->slabs, onoff(s->sanity_checks),
s->slabs * (page_size << s->order));
printf("SlabObj: %7d Full : %7ld Redzoning : %s Used : %7ld\n",
s->slab_size, s->slabs - s->partial - s->cpu_slabs,
onoff(s->red_zone), s->objects * s->object_size);
printf("SlabSiz: %7d Partial: %7ld Poisoning : %s Loss : %7ld\n",
page_size << s->order, s->partial, onoff(s->poison),
s->slabs * (page_size << s->order) - s->objects * s->object_size);
printf("Loss : %7d CpuSlab: %7d Tracking : %s Lalig: %7ld\n",
s->slab_size - s->object_size, s->cpu_slabs, onoff(s->store_user),
(s->slab_size - s->object_size) * s->objects);
printf("Align : %7d Objects: %7d Tracing : %s Lpadd: %7ld\n",
s->align, s->objs_per_slab, onoff(s->trace),
((page_size << s->order) - s->objs_per_slab * s->slab_size) *
s->slabs);
ops(s);
show_tracking(s);
slab_numa(s, 1);
slab_stats(s);
}
static void slabcache(struct slabinfo *s)
{
char size_str[20];
char dist_str[40];
char flags[20];
char *p = flags;
if (strcmp(s->name, "*") == 0)
return;
if (actual_slabs == 1) {
report(s);
return;
}
if (skip_zero && !show_empty && !s->slabs)
return;
if (show_empty && s->slabs)
return;
store_size(size_str, slab_size(s));
snprintf(dist_str, 40, "%lu/%lu/%d", s->slabs - s->cpu_slabs,
s->partial, s->cpu_slabs);
if (!line++)
first_line();
if (s->aliases)
*p++ = '*';
if (s->cache_dma)
*p++ = 'd';
if (s->hwcache_align)
*p++ = 'A';
if (s->poison)
*p++ = 'P';
if (s->reclaim_account)
*p++ = 'a';
if (s->red_zone)
*p++ = 'Z';
if (s->sanity_checks)
*p++ = 'F';
if (s->store_user)
*p++ = 'U';
if (s->trace)
*p++ = 'T';
*p = 0;
if (show_activity) {
unsigned long total_alloc;
unsigned long total_free;
total_alloc = s->alloc_fastpath + s->alloc_slowpath;
total_free = s->free_fastpath + s->free_slowpath;
printf("%-21s %8ld %10ld %10ld %3ld %3ld %5ld %1d %4ld %4ld\n",
s->name, s->objects,
total_alloc, total_free,
total_alloc ? (s->alloc_fastpath * 100 / total_alloc) : 0,
total_free ? (s->free_fastpath * 100 / total_free) : 0,
s->order_fallback, s->order, s->cmpxchg_double_fail,
s->cmpxchg_double_cpu_fail);
}
else
printf("%-21s %8ld %7d %8s %14s %4d %1d %3ld %3ld %s\n",
s->name, s->objects, s->object_size, size_str, dist_str,
s->objs_per_slab, s->order,
s->slabs ? (s->partial * 100) / s->slabs : 100,
s->slabs ? (s->objects * s->object_size * 100) /
(s->slabs * (page_size << s->order)) : 100,
flags);
}
/*
* Analyze debug options. Return false if something is amiss.
*/
static int debug_opt_scan(char *opt)
{
if (!opt || !opt[0] || strcmp(opt, "-") == 0)
return 1;
if (strcasecmp(opt, "a") == 0) {
sanity = 1;
poison = 1;
redzone = 1;
tracking = 1;
return 1;
}
for ( ; *opt; opt++)
switch (*opt) {
case 'F' : case 'f':
if (sanity)
return 0;
sanity = 1;
break;
case 'P' : case 'p':
if (poison)
return 0;
poison = 1;
break;
case 'Z' : case 'z':
if (redzone)
return 0;
redzone = 1;
break;
case 'U' : case 'u':
if (tracking)
return 0;
tracking = 1;
break;
case 'T' : case 't':
if (tracing)
return 0;
tracing = 1;
break;
default:
return 0;
}
return 1;
}
static int slab_empty(struct slabinfo *s)
{
if (s->objects > 0)
return 0;
/*
* We may still have slabs even if there are no objects. Shrinking will
* remove them.
*/
if (s->slabs != 0)
set_obj(s, "shrink", 1);
return 1;
}
static void slab_debug(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
if (sanity && !s->sanity_checks) {
set_obj(s, "sanity", 1);
}
if (!sanity && s->sanity_checks) {
if (slab_empty(s))
set_obj(s, "sanity", 0);
else
fprintf(stderr, "%s not empty cannot disable sanity checks\n", s->name);
}
if (redzone && !s->red_zone) {
if (slab_empty(s))
set_obj(s, "red_zone", 1);
else
fprintf(stderr, "%s not empty cannot enable redzoning\n", s->name);
}
if (!redzone && s->red_zone) {
if (slab_empty(s))
set_obj(s, "red_zone", 0);
else
fprintf(stderr, "%s not empty cannot disable redzoning\n", s->name);
}
if (poison && !s->poison) {
if (slab_empty(s))
set_obj(s, "poison", 1);
else
fprintf(stderr, "%s not empty cannot enable poisoning\n", s->name);
}
if (!poison && s->poison) {
if (slab_empty(s))
set_obj(s, "poison", 0);
else
fprintf(stderr, "%s not empty cannot disable poisoning\n", s->name);
}
if (tracking && !s->store_user) {
if (slab_empty(s))
set_obj(s, "store_user", 1);
else
fprintf(stderr, "%s not empty cannot enable tracking\n", s->name);
}
if (!tracking && s->store_user) {
if (slab_empty(s))
set_obj(s, "store_user", 0);
else
fprintf(stderr, "%s not empty cannot disable tracking\n", s->name);
}
if (tracing && !s->trace) {
if (slabs == 1)
set_obj(s, "trace", 1);
else
fprintf(stderr, "%s can only enable trace for one slab at a time\n", s->name);
}
if (!tracing && s->trace)
set_obj(s, "trace", 1);
}
static void totals(void)
{
struct slabinfo *s;
int used_slabs = 0;
char b1[20], b2[20], b3[20], b4[20];
unsigned long long max = 1ULL << 63;
/* Object size */
unsigned long long min_objsize = max, max_objsize = 0, avg_objsize;
/* Number of partial slabs in a slabcache */
unsigned long long min_partial = max, max_partial = 0,
avg_partial, total_partial = 0;
/* Number of slabs in a slab cache */
unsigned long long min_slabs = max, max_slabs = 0,
avg_slabs, total_slabs = 0;
/* Size of the whole slab */
unsigned long long min_size = max, max_size = 0,
avg_size, total_size = 0;
/* Bytes used for object storage in a slab */
unsigned long long min_used = max, max_used = 0,
avg_used, total_used = 0;
/* Waste: Bytes used for alignment and padding */
unsigned long long min_waste = max, max_waste = 0,
avg_waste, total_waste = 0;
/* Number of objects in a slab */
unsigned long long min_objects = max, max_objects = 0,
avg_objects, total_objects = 0;
/* Waste per object */
unsigned long long min_objwaste = max,
max_objwaste = 0, avg_objwaste,
total_objwaste = 0;
/* Memory per object */
unsigned long long min_memobj = max,
max_memobj = 0, avg_memobj,
total_objsize = 0;
/* Percentage of partial slabs per slab */
unsigned long min_ppart = 100, max_ppart = 0,
avg_ppart, total_ppart = 0;
/* Number of objects in partial slabs */
unsigned long min_partobj = max, max_partobj = 0,
avg_partobj, total_partobj = 0;
/* Percentage of partial objects of all objects in a slab */
unsigned long min_ppartobj = 100, max_ppartobj = 0,
avg_ppartobj, total_ppartobj = 0;
for (s = slabinfo; s < slabinfo + slabs; s++) {
unsigned long long size;
unsigned long used;
unsigned long long wasted;
unsigned long long objwaste;
unsigned long percentage_partial_slabs;
unsigned long percentage_partial_objs;
if (!s->slabs || !s->objects)
continue;
used_slabs++;
size = slab_size(s);
used = s->objects * s->object_size;
wasted = size - used;
objwaste = s->slab_size - s->object_size;
percentage_partial_slabs = s->partial * 100 / s->slabs;
if (percentage_partial_slabs > 100)
percentage_partial_slabs = 100;
percentage_partial_objs = s->objects_partial * 100
/ s->objects;
if (percentage_partial_objs > 100)
percentage_partial_objs = 100;
if (s->object_size < min_objsize)
min_objsize = s->object_size;
if (s->partial < min_partial)
min_partial = s->partial;
if (s->slabs < min_slabs)
min_slabs = s->slabs;
if (size < min_size)
min_size = size;
if (wasted < min_waste)
min_waste = wasted;
if (objwaste < min_objwaste)
min_objwaste = objwaste;
if (s->objects < min_objects)
min_objects = s->objects;
if (used < min_used)
min_used = used;
if (s->objects_partial < min_partobj)
min_partobj = s->objects_partial;
if (percentage_partial_slabs < min_ppart)
min_ppart = percentage_partial_slabs;
if (percentage_partial_objs < min_ppartobj)
min_ppartobj = percentage_partial_objs;
if (s->slab_size < min_memobj)
min_memobj = s->slab_size;
if (s->object_size > max_objsize)
max_objsize = s->object_size;
if (s->partial > max_partial)
max_partial = s->partial;
if (s->slabs > max_slabs)
max_slabs = s->slabs;
if (size > max_size)
max_size = size;
if (wasted > max_waste)
max_waste = wasted;
if (objwaste > max_objwaste)
max_objwaste = objwaste;
if (s->objects > max_objects)
max_objects = s->objects;
if (used > max_used)
max_used = used;
if (s->objects_partial > max_partobj)
max_partobj = s->objects_partial;
if (percentage_partial_slabs > max_ppart)
max_ppart = percentage_partial_slabs;
if (percentage_partial_objs > max_ppartobj)
max_ppartobj = percentage_partial_objs;
if (s->slab_size > max_memobj)
max_memobj = s->slab_size;
total_partial += s->partial;
total_slabs += s->slabs;
total_size += size;
total_waste += wasted;
total_objects += s->objects;
total_used += used;
total_partobj += s->objects_partial;
total_ppart += percentage_partial_slabs;
total_ppartobj += percentage_partial_objs;
total_objwaste += s->objects * objwaste;
total_objsize += s->objects * s->slab_size;
}
if (!total_objects) {
printf("No objects\n");
return;
}
if (!used_slabs) {
printf("No slabs\n");
return;
}
/* Per slab averages */
avg_partial = total_partial / used_slabs;
avg_slabs = total_slabs / used_slabs;
avg_size = total_size / used_slabs;
avg_waste = total_waste / used_slabs;
avg_objects = total_objects / used_slabs;
avg_used = total_used / used_slabs;
avg_partobj = total_partobj / used_slabs;
avg_ppart = total_ppart / used_slabs;
avg_ppartobj = total_ppartobj / used_slabs;
/* Per object object sizes */
avg_objsize = total_used / total_objects;
avg_objwaste = total_objwaste / total_objects;
avg_partobj = total_partobj * 100 / total_objects;
avg_memobj = total_objsize / total_objects;
printf("Slabcache Totals\n");
printf("----------------\n");
printf("Slabcaches : %3d Aliases : %3d->%-3d Active: %3d\n",
slabs, aliases, alias_targets, used_slabs);
store_size(b1, total_size);store_size(b2, total_waste);
store_size(b3, total_waste * 100 / total_used);
printf("Memory used: %6s # Loss : %6s MRatio:%6s%%\n", b1, b2, b3);
store_size(b1, total_objects);store_size(b2, total_partobj);
store_size(b3, total_partobj * 100 / total_objects);
printf("# Objects : %6s # PartObj: %6s ORatio:%6s%%\n", b1, b2, b3);
printf("\n");
printf("Per Cache Average Min Max Total\n");
printf("---------------------------------------------------------\n");
store_size(b1, avg_objects);store_size(b2, min_objects);
store_size(b3, max_objects);store_size(b4, total_objects);
printf("#Objects %10s %10s %10s %10s\n",
b1, b2, b3, b4);
store_size(b1, avg_slabs);store_size(b2, min_slabs);
store_size(b3, max_slabs);store_size(b4, total_slabs);
printf("#Slabs %10s %10s %10s %10s\n",
b1, b2, b3, b4);
store_size(b1, avg_partial);store_size(b2, min_partial);
store_size(b3, max_partial);store_size(b4, total_partial);
printf("#PartSlab %10s %10s %10s %10s\n",
b1, b2, b3, b4);
store_size(b1, avg_ppart);store_size(b2, min_ppart);
store_size(b3, max_ppart);
store_size(b4, total_partial * 100 / total_slabs);
printf("%%PartSlab%10s%% %10s%% %10s%% %10s%%\n",
b1, b2, b3, b4);
store_size(b1, avg_partobj);store_size(b2, min_partobj);
store_size(b3, max_partobj);
store_size(b4, total_partobj);
printf("PartObjs %10s %10s %10s %10s\n",
b1, b2, b3, b4);
store_size(b1, avg_ppartobj);store_size(b2, min_ppartobj);
store_size(b3, max_ppartobj);
store_size(b4, total_partobj * 100 / total_objects);
printf("%% PartObj%10s%% %10s%% %10s%% %10s%%\n",
b1, b2, b3, b4);
store_size(b1, avg_size);store_size(b2, min_size);
store_size(b3, max_size);store_size(b4, total_size);
printf("Memory %10s %10s %10s %10s\n",
b1, b2, b3, b4);
store_size(b1, avg_used);store_size(b2, min_used);
store_size(b3, max_used);store_size(b4, total_used);
printf("Used %10s %10s %10s %10s\n",
b1, b2, b3, b4);
store_size(b1, avg_waste);store_size(b2, min_waste);
store_size(b3, max_waste);store_size(b4, total_waste);
printf("Loss %10s %10s %10s %10s\n",
b1, b2, b3, b4);
printf("\n");
printf("Per Object Average Min Max\n");
printf("---------------------------------------------\n");
store_size(b1, avg_memobj);store_size(b2, min_memobj);
store_size(b3, max_memobj);
printf("Memory %10s %10s %10s\n",
b1, b2, b3);
store_size(b1, avg_objsize);store_size(b2, min_objsize);
store_size(b3, max_objsize);
printf("User %10s %10s %10s\n",
b1, b2, b3);
store_size(b1, avg_objwaste);store_size(b2, min_objwaste);
store_size(b3, max_objwaste);
printf("Loss %10s %10s %10s\n",
b1, b2, b3);
}
static void sort_slabs(void)
{
struct slabinfo *s1,*s2;
for (s1 = slabinfo; s1 < slabinfo + slabs; s1++) {
for (s2 = s1 + 1; s2 < slabinfo + slabs; s2++) {
int result;
if (sort_size)
result = slab_size(s1) < slab_size(s2);
else if (sort_active)
result = slab_activity(s1) < slab_activity(s2);
else
result = strcasecmp(s1->name, s2->name);
if (show_inverted)
result = -result;
if (result > 0) {
struct slabinfo t;
memcpy(&t, s1, sizeof(struct slabinfo));
memcpy(s1, s2, sizeof(struct slabinfo));
memcpy(s2, &t, sizeof(struct slabinfo));
}
}
}
}
static void sort_aliases(void)
{
struct aliasinfo *a1,*a2;
for (a1 = aliasinfo; a1 < aliasinfo + aliases; a1++) {
for (a2 = a1 + 1; a2 < aliasinfo + aliases; a2++) {
char *n1, *n2;
n1 = a1->name;
n2 = a2->name;
if (show_alias && !show_inverted) {
n1 = a1->ref;
n2 = a2->ref;
}
if (strcasecmp(n1, n2) > 0) {
struct aliasinfo t;
memcpy(&t, a1, sizeof(struct aliasinfo));
memcpy(a1, a2, sizeof(struct aliasinfo));
memcpy(a2, &t, sizeof(struct aliasinfo));
}
}
}
}
static void link_slabs(void)
{
struct aliasinfo *a;
struct slabinfo *s;
for (a = aliasinfo; a < aliasinfo + aliases; a++) {
for (s = slabinfo; s < slabinfo + slabs; s++)
if (strcmp(a->ref, s->name) == 0) {
a->slab = s;
s->refs++;
break;
}
if (s == slabinfo + slabs)
fatal("Unresolved alias %s\n", a->ref);
}
}
static void alias(void)
{
struct aliasinfo *a;
char *active = NULL;
sort_aliases();
link_slabs();
for(a = aliasinfo; a < aliasinfo + aliases; a++) {
if (!show_single_ref && a->slab->refs == 1)
continue;
if (!show_inverted) {
if (active) {
if (strcmp(a->slab->name, active) == 0) {
printf(" %s", a->name);
continue;
}
}
printf("\n%-12s <- %s", a->slab->name, a->name);
active = a->slab->name;
}
else
printf("%-20s -> %s\n", a->name, a->slab->name);
}
if (active)
printf("\n");
}
static void rename_slabs(void)
{
struct slabinfo *s;
struct aliasinfo *a;
for (s = slabinfo; s < slabinfo + slabs; s++) {
if (*s->name != ':')
continue;
if (s->refs > 1 && !show_first_alias)
continue;
a = find_one_alias(s);
if (a)
s->name = a->name;
else {
s->name = "*";
actual_slabs--;
}
}
}
static int slab_mismatch(char *slab)
{
return regexec(&pattern, slab, 0, NULL, 0);
}
static void read_slab_dir(void)
{
DIR *dir;
struct dirent *de;
struct slabinfo *slab = slabinfo;
struct aliasinfo *alias = aliasinfo;
char *p;
char *t;
int count;
if (chdir("/sys/kernel/slab") && chdir("/sys/slab"))
fatal("SYSFS support for SLUB not active\n");
dir = opendir(".");
while ((de = readdir(dir))) {
if (de->d_name[0] == '.' ||
(de->d_name[0] != ':' && slab_mismatch(de->d_name)))
continue;
switch (de->d_type) {
case DT_LNK:
alias->name = strdup(de->d_name);
count = readlink(de->d_name, buffer, sizeof(buffer)-1);
if (count < 0)
fatal("Cannot read symlink %s\n", de->d_name);
buffer[count] = 0;
p = buffer + count;
while (p > buffer && p[-1] != '/')
p--;
alias->ref = strdup(p);
alias++;
break;
case DT_DIR:
if (chdir(de->d_name))
fatal("Unable to access slab %s\n", slab->name);
slab->name = strdup(de->d_name);
slab->alias = 0;
slab->refs = 0;
slab->aliases = get_obj("aliases");
slab->align = get_obj("align");
slab->cache_dma = get_obj("cache_dma");
slab->cpu_slabs = get_obj("cpu_slabs");
slab->destroy_by_rcu = get_obj("destroy_by_rcu");
slab->hwcache_align = get_obj("hwcache_align");
slab->object_size = get_obj("object_size");
slab->objects = get_obj("objects");
slab->objects_partial = get_obj("objects_partial");
slab->objects_total = get_obj("objects_total");
slab->objs_per_slab = get_obj("objs_per_slab");
slab->order = get_obj("order");
slab->partial = get_obj("partial");
slab->partial = get_obj_and_str("partial", &t);
decode_numa_list(slab->numa_partial, t);
free(t);
slab->poison = get_obj("poison");
slab->reclaim_account = get_obj("reclaim_account");
slab->red_zone = get_obj("red_zone");
slab->sanity_checks = get_obj("sanity_checks");
slab->slab_size = get_obj("slab_size");
slab->slabs = get_obj_and_str("slabs", &t);
decode_numa_list(slab->numa, t);
free(t);
slab->store_user = get_obj("store_user");
slab->trace = get_obj("trace");
slab->alloc_fastpath = get_obj("alloc_fastpath");
slab->alloc_slowpath = get_obj("alloc_slowpath");
slab->free_fastpath = get_obj("free_fastpath");
slab->free_slowpath = get_obj("free_slowpath");
slab->free_frozen= get_obj("free_frozen");
slab->free_add_partial = get_obj("free_add_partial");
slab->free_remove_partial = get_obj("free_remove_partial");
slab->alloc_from_partial = get_obj("alloc_from_partial");
slab->alloc_slab = get_obj("alloc_slab");
slab->alloc_refill = get_obj("alloc_refill");
slab->free_slab = get_obj("free_slab");
slab->cpuslab_flush = get_obj("cpuslab_flush");
slab->deactivate_full = get_obj("deactivate_full");
slab->deactivate_empty = get_obj("deactivate_empty");
slab->deactivate_to_head = get_obj("deactivate_to_head");
slab->deactivate_to_tail = get_obj("deactivate_to_tail");
slab->deactivate_remote_frees = get_obj("deactivate_remote_frees");
slab->order_fallback = get_obj("order_fallback");
slab->cmpxchg_double_cpu_fail = get_obj("cmpxchg_double_cpu_fail");
slab->cmpxchg_double_fail = get_obj("cmpxchg_double_fail");
slab->cpu_partial_alloc = get_obj("cpu_partial_alloc");
slab->cpu_partial_free = get_obj("cpu_partial_free");
slab->alloc_node_mismatch = get_obj("alloc_node_mismatch");
slab->deactivate_bypass = get_obj("deactivate_bypass");
chdir("..");
if (slab->name[0] == ':')
alias_targets++;
slab++;
break;
default :
fatal("Unknown file type %lx\n", de->d_type);
}
}
closedir(dir);
slabs = slab - slabinfo;
actual_slabs = slabs;
aliases = alias - aliasinfo;
if (slabs > MAX_SLABS)
fatal("Too many slabs\n");
if (aliases > MAX_ALIASES)
fatal("Too many aliases\n");
}
static void output_slabs(void)
{
struct slabinfo *slab;
for (slab = slabinfo; slab < slabinfo + slabs; slab++) {
if (slab->alias)
continue;
if (show_numa)
slab_numa(slab, 0);
else if (show_track)
show_tracking(slab);
else if (validate)
slab_validate(slab);
else if (shrink)
slab_shrink(slab);
else if (set_debug)
slab_debug(slab);
else if (show_ops)
ops(slab);
else if (show_slab)
slabcache(slab);
else if (show_report)
report(slab);
}
}
struct option opts[] = {
{ "aliases", 0, NULL, 'a' },
{ "activity", 0, NULL, 'A' },
{ "debug", 2, NULL, 'd' },
{ "display-activity", 0, NULL, 'D' },
{ "empty", 0, NULL, 'e' },
{ "first-alias", 0, NULL, 'f' },
{ "help", 0, NULL, 'h' },
{ "inverted", 0, NULL, 'i'},
{ "numa", 0, NULL, 'n' },
{ "ops", 0, NULL, 'o' },
{ "report", 0, NULL, 'r' },
{ "shrink", 0, NULL, 's' },
{ "slabs", 0, NULL, 'l' },
{ "track", 0, NULL, 't'},
{ "validate", 0, NULL, 'v' },
{ "zero", 0, NULL, 'z' },
{ "1ref", 0, NULL, '1'},
{ NULL, 0, NULL, 0 }
};
int main(int argc, char *argv[])
{
int c;
int err;
char *pattern_source;
page_size = getpagesize();
while ((c = getopt_long(argc, argv, "aAd::Defhil1noprstvzTS",
opts, NULL)) != -1)
switch (c) {
case '1':
show_single_ref = 1;
break;
case 'a':
show_alias = 1;
break;
case 'A':
sort_active = 1;
break;
case 'd':
set_debug = 1;
if (!debug_opt_scan(optarg))
fatal("Invalid debug option '%s'\n", optarg);
break;
case 'D':
show_activity = 1;
break;
case 'e':
show_empty = 1;
break;
case 'f':
show_first_alias = 1;
break;
case 'h':
usage();
return 0;
case 'i':
show_inverted = 1;
break;
case 'n':
show_numa = 1;
break;
case 'o':
show_ops = 1;
break;
case 'r':
show_report = 1;
break;
case 's':
shrink = 1;
break;
case 'l':
show_slab = 1;
break;
case 't':
show_track = 1;
break;
case 'v':
validate = 1;
break;
case 'z':
skip_zero = 0;
break;
case 'T':
show_totals = 1;
break;
case 'S':
sort_size = 1;
break;
default:
fatal("%s: Invalid option '%c'\n", argv[0], optopt);
}
if (!show_slab && !show_alias && !show_track && !show_report
&& !validate && !shrink && !set_debug && !show_ops)
show_slab = 1;
if (argc > optind)
pattern_source = argv[optind];
else
pattern_source = ".*";
err = regcomp(&pattern, pattern_source, REG_ICASE|REG_NOSUB);
if (err)
fatal("%s: Invalid pattern '%s' code %d\n",
argv[0], pattern_source, err);
read_slab_dir();
if (show_alias)
alias();
else
if (show_totals)
totals();
else {
link_slabs();
rename_slabs();
sort_slabs();
output_slabs();
}
return 0;
}
| gpl-2.0 |
Jovy23/N930TUVU1APGC_Kernel | drivers/staging/rtl8712/rtl871x_eeprom.c | 11781 | 6525 | /******************************************************************************
* rtl871x_eeprom.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_EEPROM_C_
#include "osdep_service.h"
#include "drv_types.h"
static void up_clk(struct _adapter *padapter, u16 *x)
{
*x = *x | _EESK;
r8712_write8(padapter, EE_9346CR, (u8)*x);
udelay(CLOCK_RATE);
}
static void down_clk(struct _adapter *padapter, u16 *x)
{
*x = *x & ~_EESK;
r8712_write8(padapter, EE_9346CR, (u8)*x);
udelay(CLOCK_RATE);
}
static void shift_out_bits(struct _adapter *padapter, u16 data, u16 count)
{
u16 x, mask;
if (padapter->bSurpriseRemoved == true)
goto out;
mask = 0x01 << (count - 1);
x = r8712_read8(padapter, EE_9346CR);
x &= ~(_EEDO | _EEDI);
do {
x &= ~_EEDI;
if (data & mask)
x |= _EEDI;
if (padapter->bSurpriseRemoved == true)
goto out;
r8712_write8(padapter, EE_9346CR, (u8)x);
udelay(CLOCK_RATE);
up_clk(padapter, &x);
down_clk(padapter, &x);
mask = mask >> 1;
} while (mask);
if (padapter->bSurpriseRemoved == true)
goto out;
x &= ~_EEDI;
r8712_write8(padapter, EE_9346CR, (u8)x);
out:;
}
static u16 shift_in_bits(struct _adapter *padapter)
{
u16 x, d = 0, i;
if (padapter->bSurpriseRemoved == true)
goto out;
x = r8712_read8(padapter, EE_9346CR);
x &= ~(_EEDO | _EEDI);
d = 0;
for (i = 0; i < 16; i++) {
d = d << 1;
up_clk(padapter, &x);
if (padapter->bSurpriseRemoved == true)
goto out;
x = r8712_read8(padapter, EE_9346CR);
x &= ~(_EEDI);
if (x & _EEDO)
d |= 1;
down_clk(padapter, &x);
}
out:
return d;
}
static void standby(struct _adapter *padapter)
{
u8 x;
x = r8712_read8(padapter, EE_9346CR);
x &= ~(_EECS | _EESK);
r8712_write8(padapter, EE_9346CR, x);
udelay(CLOCK_RATE);
x |= _EECS;
r8712_write8(padapter, EE_9346CR, x);
udelay(CLOCK_RATE);
}
static u16 wait_eeprom_cmd_done(struct _adapter *padapter)
{
u8 x;
u16 i;
standby(padapter);
for (i = 0; i < 200; i++) {
x = r8712_read8(padapter, EE_9346CR);
if (x & _EEDO)
return true;
udelay(CLOCK_RATE);
}
return false;
}
static void eeprom_clean(struct _adapter *padapter)
{
u16 x;
if (padapter->bSurpriseRemoved == true)
return;
x = r8712_read8(padapter, EE_9346CR);
if (padapter->bSurpriseRemoved == true)
return;
x &= ~(_EECS | _EEDI);
r8712_write8(padapter, EE_9346CR, (u8)x);
if (padapter->bSurpriseRemoved == true)
return;
up_clk(padapter, &x);
if (padapter->bSurpriseRemoved == true)
return;
down_clk(padapter, &x);
}
void r8712_eeprom_write16(struct _adapter *padapter, u16 reg, u16 data)
{
u8 x;
u8 tmp8_ori, tmp8_new, tmp8_clk_ori, tmp8_clk_new;
tmp8_ori = r8712_read8(padapter, 0x102502f1);
tmp8_new = tmp8_ori & 0xf7;
if (tmp8_ori != tmp8_new)
r8712_write8(padapter, 0x102502f1, tmp8_new);
tmp8_clk_ori = r8712_read8(padapter, 0x10250003);
tmp8_clk_new = tmp8_clk_ori | 0x20;
if (tmp8_clk_new != tmp8_clk_ori)
r8712_write8(padapter, 0x10250003, tmp8_clk_new);
x = r8712_read8(padapter, EE_9346CR);
x &= ~(_EEDI | _EEDO | _EESK | _EEM0);
x |= _EEM1 | _EECS;
r8712_write8(padapter, EE_9346CR, x);
shift_out_bits(padapter, EEPROM_EWEN_OPCODE, 5);
if (padapter->EepromAddressSize == 8) /*CF+ and SDIO*/
shift_out_bits(padapter, 0, 6);
else /* USB */
shift_out_bits(padapter, 0, 4);
standby(padapter);
/* Erase this particular word. Write the erase opcode and register
* number in that order. The opcode is 3bits in length; reg is 6
* bits long.
*/
standby(padapter);
/* write the new word to the EEPROM
* send the write opcode the EEPORM
*/
shift_out_bits(padapter, EEPROM_WRITE_OPCODE, 3);
/* select which word in the EEPROM that we are writing to. */
shift_out_bits(padapter, reg, padapter->EepromAddressSize);
/* write the data to the selected EEPROM word. */
shift_out_bits(padapter, data, 16);
if (wait_eeprom_cmd_done(padapter)) {
standby(padapter);
shift_out_bits(padapter, EEPROM_EWDS_OPCODE, 5);
shift_out_bits(padapter, reg, 4);
eeprom_clean(padapter);
}
if (tmp8_clk_new != tmp8_clk_ori)
r8712_write8(padapter, 0x10250003, tmp8_clk_ori);
if (tmp8_new != tmp8_ori)
r8712_write8(padapter, 0x102502f1, tmp8_ori);
}
u16 r8712_eeprom_read16(struct _adapter *padapter, u16 reg) /*ReadEEprom*/
{
u16 x;
u16 data = 0;
u8 tmp8_ori, tmp8_new, tmp8_clk_ori, tmp8_clk_new;
tmp8_ori = r8712_read8(padapter, 0x102502f1);
tmp8_new = tmp8_ori & 0xf7;
if (tmp8_ori != tmp8_new)
r8712_write8(padapter, 0x102502f1, tmp8_new);
tmp8_clk_ori = r8712_read8(padapter, 0x10250003);
tmp8_clk_new = tmp8_clk_ori | 0x20;
if (tmp8_clk_new != tmp8_clk_ori)
r8712_write8(padapter, 0x10250003, tmp8_clk_new);
if (padapter->bSurpriseRemoved == true)
goto out;
/* select EEPROM, reset bits, set _EECS */
x = r8712_read8(padapter, EE_9346CR);
if (padapter->bSurpriseRemoved == true)
goto out;
x &= ~(_EEDI | _EEDO | _EESK | _EEM0);
x |= _EEM1 | _EECS;
r8712_write8(padapter, EE_9346CR, (unsigned char)x);
/* write the read opcode and register number in that order
* The opcode is 3bits in length, reg is 6 bits long
*/
shift_out_bits(padapter, EEPROM_READ_OPCODE, 3);
shift_out_bits(padapter, reg, padapter->EepromAddressSize);
/* Now read the data (16 bits) in from the selected EEPROM word */
data = shift_in_bits(padapter);
eeprom_clean(padapter);
out:
if (tmp8_clk_new != tmp8_clk_ori)
r8712_write8(padapter, 0x10250003, tmp8_clk_ori);
if (tmp8_new != tmp8_ori)
r8712_write8(padapter, 0x102502f1, tmp8_ori);
return data;
}
| gpl-2.0 |
nquest/kernel_dns_s4502m | drivers/video/syscopyarea.c | 12293 | 8960 | /*
* Generic Bit Block Transfer for frame buffers located in system RAM with
* packed pixels of any depth.
*
* Based almost entirely from cfbcopyarea.c (which is based almost entirely
* on Geert Uytterhoeven's copyarea routine)
*
* Copyright (C) 2007 Antonino Daplas <adaplas@pol.net>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/fb.h>
#include <asm/types.h>
#include <asm/io.h>
#include "fb_draw.h"
/*
* Generic bitwise copy algorithm
*/
static void
bitcpy(struct fb_info *p, unsigned long *dst, int dst_idx,
const unsigned long *src, int src_idx, int bits, unsigned n)
{
unsigned long first, last;
int const shift = dst_idx-src_idx;
int left, right;
first = FB_SHIFT_HIGH(p, ~0UL, dst_idx);
last = ~(FB_SHIFT_HIGH(p, ~0UL, (dst_idx+n) % bits));
if (!shift) {
/* Same alignment for source and dest */
if (dst_idx+n <= bits) {
/* Single word */
if (last)
first &= last;
*dst = comp(*src, *dst, first);
} else {
/* Multiple destination words */
/* Leading bits */
if (first != ~0UL) {
*dst = comp(*src, *dst, first);
dst++;
src++;
n -= bits - dst_idx;
}
/* Main chunk */
n /= bits;
while (n >= 8) {
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
n -= 8;
}
while (n--)
*dst++ = *src++;
/* Trailing bits */
if (last)
*dst = comp(*src, *dst, last);
}
} else {
unsigned long d0, d1;
int m;
/* Different alignment for source and dest */
right = shift & (bits - 1);
left = -shift & (bits - 1);
if (dst_idx+n <= bits) {
/* Single destination word */
if (last)
first &= last;
if (shift > 0) {
/* Single source word */
*dst = comp(*src >> right, *dst, first);
} else if (src_idx+n <= bits) {
/* Single source word */
*dst = comp(*src << left, *dst, first);
} else {
/* 2 source words */
d0 = *src++;
d1 = *src;
*dst = comp(d0 << left | d1 >> right, *dst,
first);
}
} else {
/* Multiple destination words */
/** We must always remember the last value read,
because in case SRC and DST overlap bitwise (e.g.
when moving just one pixel in 1bpp), we always
collect one full long for DST and that might
overlap with the current long from SRC. We store
this value in 'd0'. */
d0 = *src++;
/* Leading bits */
if (shift > 0) {
/* Single source word */
*dst = comp(d0 >> right, *dst, first);
dst++;
n -= bits - dst_idx;
} else {
/* 2 source words */
d1 = *src++;
*dst = comp(d0 << left | *dst >> right, *dst, first);
d0 = d1;
dst++;
n -= bits - dst_idx;
}
/* Main chunk */
m = n % bits;
n /= bits;
while (n >= 4) {
d1 = *src++;
*dst++ = d0 << left | d1 >> right;
d0 = d1;
d1 = *src++;
*dst++ = d0 << left | d1 >> right;
d0 = d1;
d1 = *src++;
*dst++ = d0 << left | d1 >> right;
d0 = d1;
d1 = *src++;
*dst++ = d0 << left | d1 >> right;
d0 = d1;
n -= 4;
}
while (n--) {
d1 = *src++;
*dst++ = d0 << left | d1 >> right;
d0 = d1;
}
/* Trailing bits */
if (last) {
if (m <= right) {
/* Single source word */
*dst = comp(d0 << left, *dst, last);
} else {
/* 2 source words */
d1 = *src;
*dst = comp(d0 << left | d1 >> right,
*dst, last);
}
}
}
}
}
/*
* Generic bitwise copy algorithm, operating backward
*/
static void
bitcpy_rev(struct fb_info *p, unsigned long *dst, int dst_idx,
const unsigned long *src, int src_idx, int bits, unsigned n)
{
unsigned long first, last;
int shift;
dst += (n-1)/bits;
src += (n-1)/bits;
if ((n-1) % bits) {
dst_idx += (n-1) % bits;
dst += dst_idx >> (ffs(bits) - 1);
dst_idx &= bits - 1;
src_idx += (n-1) % bits;
src += src_idx >> (ffs(bits) - 1);
src_idx &= bits - 1;
}
shift = dst_idx-src_idx;
first = FB_SHIFT_LOW(p, ~0UL, bits - 1 - dst_idx);
last = ~(FB_SHIFT_LOW(p, ~0UL, bits - 1 - ((dst_idx-n) % bits)));
if (!shift) {
/* Same alignment for source and dest */
if ((unsigned long)dst_idx+1 >= n) {
/* Single word */
if (last)
first &= last;
*dst = comp(*src, *dst, first);
} else {
/* Multiple destination words */
/* Leading bits */
if (first != ~0UL) {
*dst = comp(*src, *dst, first);
dst--;
src--;
n -= dst_idx+1;
}
/* Main chunk */
n /= bits;
while (n >= 8) {
*dst-- = *src--;
*dst-- = *src--;
*dst-- = *src--;
*dst-- = *src--;
*dst-- = *src--;
*dst-- = *src--;
*dst-- = *src--;
*dst-- = *src--;
n -= 8;
}
while (n--)
*dst-- = *src--;
/* Trailing bits */
if (last)
*dst = comp(*src, *dst, last);
}
} else {
/* Different alignment for source and dest */
int const left = -shift & (bits-1);
int const right = shift & (bits-1);
if ((unsigned long)dst_idx+1 >= n) {
/* Single destination word */
if (last)
first &= last;
if (shift < 0) {
/* Single source word */
*dst = comp(*src << left, *dst, first);
} else if (1+(unsigned long)src_idx >= n) {
/* Single source word */
*dst = comp(*src >> right, *dst, first);
} else {
/* 2 source words */
*dst = comp(*src >> right | *(src-1) << left,
*dst, first);
}
} else {
/* Multiple destination words */
/** We must always remember the last value read,
because in case SRC and DST overlap bitwise (e.g.
when moving just one pixel in 1bpp), we always
collect one full long for DST and that might
overlap with the current long from SRC. We store
this value in 'd0'. */
unsigned long d0, d1;
int m;
d0 = *src--;
/* Leading bits */
if (shift < 0) {
/* Single source word */
*dst = comp(d0 << left, *dst, first);
} else {
/* 2 source words */
d1 = *src--;
*dst = comp(d0 >> right | d1 << left, *dst,
first);
d0 = d1;
}
dst--;
n -= dst_idx+1;
/* Main chunk */
m = n % bits;
n /= bits;
while (n >= 4) {
d1 = *src--;
*dst-- = d0 >> right | d1 << left;
d0 = d1;
d1 = *src--;
*dst-- = d0 >> right | d1 << left;
d0 = d1;
d1 = *src--;
*dst-- = d0 >> right | d1 << left;
d0 = d1;
d1 = *src--;
*dst-- = d0 >> right | d1 << left;
d0 = d1;
n -= 4;
}
while (n--) {
d1 = *src--;
*dst-- = d0 >> right | d1 << left;
d0 = d1;
}
/* Trailing bits */
if (last) {
if (m <= left) {
/* Single source word */
*dst = comp(d0 >> right, *dst, last);
} else {
/* 2 source words */
d1 = *src;
*dst = comp(d0 >> right | d1 << left,
*dst, last);
}
}
}
}
}
void sys_copyarea(struct fb_info *p, const struct fb_copyarea *area)
{
u32 dx = area->dx, dy = area->dy, sx = area->sx, sy = area->sy;
u32 height = area->height, width = area->width;
unsigned long const bits_per_line = p->fix.line_length*8u;
unsigned long *dst = NULL, *src = NULL;
int bits = BITS_PER_LONG, bytes = bits >> 3;
int dst_idx = 0, src_idx = 0, rev_copy = 0;
if (p->state != FBINFO_STATE_RUNNING)
return;
/* if the beginning of the target area might overlap with the end of
the source area, be have to copy the area reverse. */
if ((dy == sy && dx > sx) || (dy > sy)) {
dy += height;
sy += height;
rev_copy = 1;
}
/* split the base of the framebuffer into a long-aligned address and
the index of the first bit */
dst = src = (unsigned long *)((unsigned long)p->screen_base &
~(bytes-1));
dst_idx = src_idx = 8*((unsigned long)p->screen_base & (bytes-1));
/* add offset of source and target area */
dst_idx += dy*bits_per_line + dx*p->var.bits_per_pixel;
src_idx += sy*bits_per_line + sx*p->var.bits_per_pixel;
if (p->fbops->fb_sync)
p->fbops->fb_sync(p);
if (rev_copy) {
while (height--) {
dst_idx -= bits_per_line;
src_idx -= bits_per_line;
dst += dst_idx >> (ffs(bits) - 1);
dst_idx &= (bytes - 1);
src += src_idx >> (ffs(bits) - 1);
src_idx &= (bytes - 1);
bitcpy_rev(p, dst, dst_idx, src, src_idx, bits,
width*p->var.bits_per_pixel);
}
} else {
while (height--) {
dst += dst_idx >> (ffs(bits) - 1);
dst_idx &= (bytes - 1);
src += src_idx >> (ffs(bits) - 1);
src_idx &= (bytes - 1);
bitcpy(p, dst, dst_idx, src, src_idx, bits,
width*p->var.bits_per_pixel);
dst_idx += bits_per_line;
src_idx += bits_per_line;
}
}
}
EXPORT_SYMBOL(sys_copyarea);
MODULE_AUTHOR("Antonino Daplas <adaplas@pol.net>");
MODULE_DESCRIPTION("Generic copyarea (sys-to-sys)");
MODULE_LICENSE("GPL");
| gpl-2.0 |
kgp700/Neok-GNexroid-Kernel-JB | arch/m68k/math-emu/fp_trig.c | 14853 | 2779 | /*
fp_trig.c: floating-point math routines for the Linux-m68k
floating point emulator.
Copyright (c) 1998-1999 David Huggins-Daines / Roman Zippel.
I hereby give permission, free of charge, to copy, modify, and
redistribute this software, in source or binary form, provided that
the above copyright notice and the following disclaimer are included
in all such copies.
THIS SOFTWARE IS PROVIDED "AS IS", WITH ABSOLUTELY NO WARRANTY, REAL
OR IMPLIED.
*/
#include "fp_emu.h"
#include "fp_trig.h"
struct fp_ext *
fp_fsin(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsin\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_fcos(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fcos\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_ftan(struct fp_ext *dest, struct fp_ext *src)
{
uprint("ftan\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_fasin(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fasin\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_facos(struct fp_ext *dest, struct fp_ext *src)
{
uprint("facos\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_fatan(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fatan\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_fsinh(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsinh\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_fcosh(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fcosh\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_ftanh(struct fp_ext *dest, struct fp_ext *src)
{
uprint("ftanh\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_fatanh(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fatanh\n");
fp_monadic_check(dest, src);
return dest;
}
struct fp_ext *
fp_fsincos0(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsincos0\n");
return dest;
}
struct fp_ext *
fp_fsincos1(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsincos1\n");
return dest;
}
struct fp_ext *
fp_fsincos2(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsincos2\n");
return dest;
}
struct fp_ext *
fp_fsincos3(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsincos3\n");
return dest;
}
struct fp_ext *
fp_fsincos4(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsincos4\n");
return dest;
}
struct fp_ext *
fp_fsincos5(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsincos5\n");
return dest;
}
struct fp_ext *
fp_fsincos6(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsincos6\n");
return dest;
}
struct fp_ext *
fp_fsincos7(struct fp_ext *dest, struct fp_ext *src)
{
uprint("fsincos7\n");
return dest;
}
| gpl-2.0 |
formorer/pkg-libnetfilter-conntrack | src/conntrack/filter.c | 6 | 3158 | /*
* (C) 2005-2011 by Pablo Neira Ayuso <pablo@netfilter.org>
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*/
#include "internal/internal.h"
static void filter_attr_l4proto(struct nfct_filter *filter, const void *value)
{
if (filter->l4proto_len >= __FILTER_L4PROTO_MAX)
return;
set_bit(*((int *) value), filter->l4proto_map);
filter->l4proto_len++;
}
static void
filter_attr_l4proto_state(struct nfct_filter *filter, const void *value)
{
const struct nfct_filter_proto *this = value;
set_bit_u16(this->state, &filter->l4proto_state[this->proto].map);
filter->l4proto_state[this->proto].len++;
}
static void filter_attr_src_ipv4(struct nfct_filter *filter, const void *value)
{
const struct nfct_filter_ipv4 *this = value;
if (filter->l3proto_elems[0] >= __FILTER_ADDR_MAX)
return;
filter->l3proto[0][filter->l3proto_elems[0]].addr = this->addr;
filter->l3proto[0][filter->l3proto_elems[0]].mask = this->mask;
filter->l3proto_elems[0]++;
}
static void filter_attr_dst_ipv4(struct nfct_filter *filter, const void *value)
{
const struct nfct_filter_ipv4 *this = value;
if (filter->l3proto_elems[1] >= __FILTER_ADDR_MAX)
return;
filter->l3proto[1][filter->l3proto_elems[1]].addr = this->addr;
filter->l3proto[1][filter->l3proto_elems[1]].mask = this->mask;
filter->l3proto_elems[1]++;
}
static void filter_attr_src_ipv6(struct nfct_filter *filter, const void *value)
{
const struct nfct_filter_ipv6 *this = value;
if (filter->l3proto_elems_ipv6[0] >= __FILTER_IPV6_MAX)
return;
memcpy(filter->l3proto_ipv6[0][filter->l3proto_elems_ipv6[0]].addr,
this->addr, sizeof(uint32_t)*4);
memcpy(filter->l3proto_ipv6[0][filter->l3proto_elems_ipv6[0]].mask,
this->mask, sizeof(uint32_t)*4);
filter->l3proto_elems_ipv6[0]++;
}
static void filter_attr_dst_ipv6(struct nfct_filter *filter, const void *value)
{
const struct nfct_filter_ipv6 *this = value;
if (filter->l3proto_elems_ipv6[1] >= __FILTER_IPV6_MAX)
return;
memcpy(filter->l3proto_ipv6[1][filter->l3proto_elems_ipv6[1]].addr,
this->addr, sizeof(uint32_t)*4);
memcpy(filter->l3proto_ipv6[1][filter->l3proto_elems_ipv6[1]].mask,
this->mask, sizeof(uint32_t)*4);
filter->l3proto_elems_ipv6[1]++;
}
static void filter_attr_mark(struct nfct_filter *filter, const void *value)
{
const struct nfct_filter_dump_mark *this = value;
if (filter->mark_elems >= __FILTER_MARK_MAX)
return;
filter->mark[filter->mark_elems].val = this->val;
filter->mark[filter->mark_elems].mask = this->mask;
filter->mark_elems++;
}
const filter_attr filter_attr_array[NFCT_FILTER_MAX] = {
[NFCT_FILTER_L4PROTO] = filter_attr_l4proto,
[NFCT_FILTER_L4PROTO_STATE] = filter_attr_l4proto_state,
[NFCT_FILTER_SRC_IPV4] = filter_attr_src_ipv4,
[NFCT_FILTER_DST_IPV4] = filter_attr_dst_ipv4,
[NFCT_FILTER_SRC_IPV6] = filter_attr_src_ipv6,
[NFCT_FILTER_DST_IPV6] = filter_attr_dst_ipv6,
[NFCT_FILTER_MARK] = filter_attr_mark,
};
| gpl-2.0 |
objectkuan/qemu_reverse | target-tricore/translate.c | 6 | 38581 | /*
* TriCore emulation for qemu: main translation routines.
*
* Copyright (c) 2013-2014 Bastian Koppelmann C-Lab/University Paderborn
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include "cpu.h"
#include "disas/disas.h"
#include "tcg-op.h"
#include "exec/cpu_ldst.h"
#include "exec/helper-proto.h"
#include "exec/helper-gen.h"
#include "tricore-opcodes.h"
/*
* TCG registers
*/
static TCGv cpu_PC;
static TCGv cpu_PCXI;
static TCGv cpu_PSW;
static TCGv cpu_ICR;
/* GPR registers */
static TCGv cpu_gpr_a[16];
static TCGv cpu_gpr_d[16];
/* PSW Flag cache */
static TCGv cpu_PSW_C;
static TCGv cpu_PSW_V;
static TCGv cpu_PSW_SV;
static TCGv cpu_PSW_AV;
static TCGv cpu_PSW_SAV;
/* CPU env */
static TCGv_ptr cpu_env;
#include "exec/gen-icount.h"
static const char *regnames_a[] = {
"a0" , "a1" , "a2" , "a3" , "a4" , "a5" ,
"a6" , "a7" , "a8" , "a9" , "sp" , "a11" ,
"a12" , "a13" , "a14" , "a15",
};
static const char *regnames_d[] = {
"d0" , "d1" , "d2" , "d3" , "d4" , "d5" ,
"d6" , "d7" , "d8" , "d9" , "d10" , "d11" ,
"d12" , "d13" , "d14" , "d15",
};
typedef struct DisasContext {
struct TranslationBlock *tb;
target_ulong pc, saved_pc, next_pc;
uint32_t opcode;
int singlestep_enabled;
/* Routine used to access memory */
int mem_idx;
uint32_t hflags, saved_hflags;
int bstate;
} DisasContext;
enum {
BS_NONE = 0,
BS_STOP = 1,
BS_BRANCH = 2,
BS_EXCP = 3,
};
void tricore_cpu_dump_state(CPUState *cs, FILE *f,
fprintf_function cpu_fprintf, int flags)
{
TriCoreCPU *cpu = TRICORE_CPU(cs);
CPUTriCoreState *env = &cpu->env;
int i;
cpu_fprintf(f, "PC=%08x\n", env->PC);
for (i = 0; i < 16; ++i) {
if ((i & 3) == 0) {
cpu_fprintf(f, "GPR A%02d:", i);
}
cpu_fprintf(f, " %s " TARGET_FMT_lx, regnames_a[i], env->gpr_a[i]);
}
for (i = 0; i < 16; ++i) {
if ((i & 3) == 0) {
cpu_fprintf(f, "GPR D%02d:", i);
}
cpu_fprintf(f, " %s " TARGET_FMT_lx, regnames_d[i], env->gpr_d[i]);
}
}
/*
* Functions to generate micro-ops
*/
/* Makros for generating helpers */
#define gen_helper_1arg(name, arg) do { \
TCGv_i32 helper_tmp = tcg_const_i32(arg); \
gen_helper_##name(cpu_env, helper_tmp); \
tcg_temp_free_i32(helper_tmp); \
} while (0)
/* Functions for load/save to/from memory */
static inline void gen_offset_ld(DisasContext *ctx, TCGv r1, TCGv r2,
int16_t con, TCGMemOp mop)
{
TCGv temp = tcg_temp_new();
tcg_gen_addi_tl(temp, r2, con);
tcg_gen_qemu_ld_tl(r1, temp, ctx->mem_idx, mop);
tcg_temp_free(temp);
}
static inline void gen_offset_st(DisasContext *ctx, TCGv r1, TCGv r2,
int16_t con, TCGMemOp mop)
{
TCGv temp = tcg_temp_new();
tcg_gen_addi_tl(temp, r2, con);
tcg_gen_qemu_st_tl(r1, temp, ctx->mem_idx, mop);
tcg_temp_free(temp);
}
/* Functions for arithmetic instructions */
static inline void gen_add_d(TCGv ret, TCGv r1, TCGv r2)
{
TCGv t0 = tcg_temp_new_i32();
TCGv result = tcg_temp_new_i32();
/* Addition and set V/SV bits */
tcg_gen_add_tl(result, r1, r2);
/* calc V bit */
tcg_gen_xor_tl(cpu_PSW_V, result, r1);
tcg_gen_xor_tl(t0, r1, r2);
tcg_gen_andc_tl(cpu_PSW_V, cpu_PSW_V, t0);
/* Calc SV bit */
tcg_gen_or_tl(cpu_PSW_SV, cpu_PSW_SV, cpu_PSW_V);
/* Calc AV/SAV bits */
tcg_gen_add_tl(cpu_PSW_AV, result, result);
tcg_gen_xor_tl(cpu_PSW_AV, result, cpu_PSW_AV);
/* calc SAV */
tcg_gen_or_tl(cpu_PSW_SAV, cpu_PSW_SAV, cpu_PSW_AV);
/* write back result */
tcg_gen_mov_tl(ret, result);
tcg_temp_free(result);
tcg_temp_free(t0);
}
static inline void gen_addi_d(TCGv ret, TCGv r1, target_ulong r2)
{
TCGv temp = tcg_const_i32(r2);
gen_add_d(ret, r1, temp);
tcg_temp_free(temp);
}
static inline void gen_cond_add(TCGCond cond, TCGv r1, TCGv r2, TCGv r3,
TCGv r4)
{
TCGv temp = tcg_temp_new();
TCGv temp2 = tcg_temp_new();
TCGv result = tcg_temp_new();
TCGv mask = tcg_temp_new();
TCGv t0 = tcg_const_i32(0);
/* create mask for sticky bits */
tcg_gen_setcond_tl(cond, mask, r4, t0);
tcg_gen_shli_tl(mask, mask, 31);
tcg_gen_add_tl(result, r1, r2);
/* Calc PSW_V */
tcg_gen_xor_tl(temp, result, r1);
tcg_gen_xor_tl(temp2, r1, r2);
tcg_gen_andc_tl(temp, temp, temp2);
tcg_gen_movcond_tl(cond, cpu_PSW_V, r4, t0, temp, cpu_PSW_V);
/* Set PSW_SV */
tcg_gen_and_tl(temp, temp, mask);
tcg_gen_or_tl(cpu_PSW_SV, temp, cpu_PSW_SV);
/* calc AV bit */
tcg_gen_add_tl(temp, result, result);
tcg_gen_xor_tl(temp, temp, result);
tcg_gen_movcond_tl(cond, cpu_PSW_AV, r4, t0, temp, cpu_PSW_AV);
/* calc SAV bit */
tcg_gen_and_tl(temp, temp, mask);
tcg_gen_or_tl(cpu_PSW_SAV, temp, cpu_PSW_SAV);
/* write back result */
tcg_gen_movcond_tl(cond, r3, r4, t0, result, r3);
tcg_temp_free(t0);
tcg_temp_free(temp);
tcg_temp_free(temp2);
tcg_temp_free(result);
tcg_temp_free(mask);
}
static inline void gen_condi_add(TCGCond cond, TCGv r1, int32_t r2,
TCGv r3, TCGv r4)
{
TCGv temp = tcg_const_i32(r2);
gen_cond_add(cond, r1, temp, r3, r4);
tcg_temp_free(temp);
}
static inline void gen_sub_d(TCGv ret, TCGv r1, TCGv r2)
{
TCGv temp = tcg_temp_new_i32();
TCGv result = tcg_temp_new_i32();
tcg_gen_sub_tl(result, r1, r2);
/* calc V bit */
tcg_gen_xor_tl(cpu_PSW_V, result, r1);
tcg_gen_xor_tl(temp, r1, r2);
tcg_gen_and_tl(cpu_PSW_V, cpu_PSW_V, temp);
/* calc SV bit */
tcg_gen_or_tl(cpu_PSW_SV, cpu_PSW_SV, cpu_PSW_V);
/* Calc AV bit */
tcg_gen_add_tl(cpu_PSW_AV, result, result);
tcg_gen_xor_tl(cpu_PSW_AV, result, cpu_PSW_AV);
/* calc SAV bit */
tcg_gen_or_tl(cpu_PSW_SAV, cpu_PSW_SAV, cpu_PSW_AV);
/* write back result */
tcg_gen_mov_tl(ret, result);
tcg_temp_free(temp);
tcg_temp_free(result);
}
static inline void gen_mul_i32s(TCGv ret, TCGv r1, TCGv r2)
{
TCGv high = tcg_temp_new();
TCGv low = tcg_temp_new();
tcg_gen_muls2_tl(low, high, r1, r2);
tcg_gen_mov_tl(ret, low);
/* calc V bit */
tcg_gen_sari_tl(low, low, 31);
tcg_gen_setcond_tl(TCG_COND_NE, cpu_PSW_V, high, low);
tcg_gen_shli_tl(cpu_PSW_V, cpu_PSW_V, 31);
/* calc SV bit */
tcg_gen_or_tl(cpu_PSW_SV, cpu_PSW_SV, cpu_PSW_V);
/* Calc AV bit */
tcg_gen_add_tl(cpu_PSW_AV, ret, ret);
tcg_gen_xor_tl(cpu_PSW_AV, ret, cpu_PSW_AV);
/* calc SAV bit */
tcg_gen_or_tl(cpu_PSW_SAV, cpu_PSW_SAV, cpu_PSW_AV);
tcg_temp_free(high);
tcg_temp_free(low);
}
static void gen_saturate(TCGv ret, TCGv arg, int32_t up, int32_t low)
{
TCGv sat_neg = tcg_const_i32(low);
TCGv temp = tcg_const_i32(up);
/* sat_neg = (arg < low ) ? low : arg; */
tcg_gen_movcond_tl(TCG_COND_LT, sat_neg, arg, sat_neg, sat_neg, arg);
/* ret = (sat_neg > up ) ? up : sat_neg; */
tcg_gen_movcond_tl(TCG_COND_GT, ret, sat_neg, temp, temp, sat_neg);
tcg_temp_free(sat_neg);
tcg_temp_free(temp);
}
static void gen_saturate_u(TCGv ret, TCGv arg, int32_t up)
{
TCGv temp = tcg_const_i32(up);
/* sat_neg = (arg > up ) ? up : arg; */
tcg_gen_movcond_tl(TCG_COND_GTU, ret, arg, temp, temp, arg);
tcg_temp_free(temp);
}
static void gen_shi(TCGv ret, TCGv r1, int32_t shift_count)
{
if (shift_count == -32) {
tcg_gen_movi_tl(ret, 0);
} else if (shift_count >= 0) {
tcg_gen_shli_tl(ret, r1, shift_count);
} else {
tcg_gen_shri_tl(ret, r1, -shift_count);
}
}
static void gen_shaci(TCGv ret, TCGv r1, int32_t shift_count)
{
uint32_t msk, msk_start;
TCGv temp = tcg_temp_new();
TCGv temp2 = tcg_temp_new();
TCGv t_0 = tcg_const_i32(0);
if (shift_count == 0) {
/* Clear PSW.C and PSW.V */
tcg_gen_movi_tl(cpu_PSW_C, 0);
tcg_gen_mov_tl(cpu_PSW_V, cpu_PSW_C);
tcg_gen_mov_tl(ret, r1);
} else if (shift_count == -32) {
/* set PSW.C */
tcg_gen_mov_tl(cpu_PSW_C, r1);
/* fill ret completly with sign bit */
tcg_gen_sari_tl(ret, r1, 31);
/* clear PSW.V */
tcg_gen_movi_tl(cpu_PSW_V, 0);
} else if (shift_count > 0) {
TCGv t_max = tcg_const_i32(0x7FFFFFFF >> shift_count);
TCGv t_min = tcg_const_i32(((int32_t) -0x80000000) >> shift_count);
/* calc carry */
msk_start = 32 - shift_count;
msk = ((1 << shift_count) - 1) << msk_start;
tcg_gen_andi_tl(cpu_PSW_C, r1, msk);
/* calc v/sv bits */
tcg_gen_setcond_tl(TCG_COND_GT, temp, r1, t_max);
tcg_gen_setcond_tl(TCG_COND_LT, temp2, r1, t_min);
tcg_gen_or_tl(cpu_PSW_V, temp, temp2);
tcg_gen_shli_tl(cpu_PSW_V, cpu_PSW_V, 31);
/* calc sv */
tcg_gen_or_tl(cpu_PSW_SV, cpu_PSW_V, cpu_PSW_SV);
/* do shift */
tcg_gen_shli_tl(ret, r1, shift_count);
tcg_temp_free(t_max);
tcg_temp_free(t_min);
} else {
/* clear PSW.V */
tcg_gen_movi_tl(cpu_PSW_V, 0);
/* calc carry */
msk = (1 << -shift_count) - 1;
tcg_gen_andi_tl(cpu_PSW_C, r1, msk);
/* do shift */
tcg_gen_sari_tl(ret, r1, -shift_count);
}
/* calc av overflow bit */
tcg_gen_add_tl(cpu_PSW_AV, ret, ret);
tcg_gen_xor_tl(cpu_PSW_AV, ret, cpu_PSW_AV);
/* calc sav overflow bit */
tcg_gen_or_tl(cpu_PSW_SAV, cpu_PSW_SAV, cpu_PSW_AV);
tcg_temp_free(temp);
tcg_temp_free(temp2);
tcg_temp_free(t_0);
}
static inline void gen_adds(TCGv ret, TCGv r1, TCGv r2)
{
gen_helper_add_ssov(ret, cpu_env, r1, r2);
}
static inline void gen_subs(TCGv ret, TCGv r1, TCGv r2)
{
gen_helper_sub_ssov(ret, cpu_env, r1, r2);
}
/* helpers for generating program flow micro-ops */
static inline void gen_save_pc(target_ulong pc)
{
tcg_gen_movi_tl(cpu_PC, pc);
}
static inline void gen_goto_tb(DisasContext *ctx, int n, target_ulong dest)
{
TranslationBlock *tb;
tb = ctx->tb;
if ((tb->pc & TARGET_PAGE_MASK) == (dest & TARGET_PAGE_MASK) &&
likely(!ctx->singlestep_enabled)) {
tcg_gen_goto_tb(n);
gen_save_pc(dest);
tcg_gen_exit_tb((uintptr_t)tb + n);
} else {
gen_save_pc(dest);
if (ctx->singlestep_enabled) {
/* raise exception debug */
}
tcg_gen_exit_tb(0);
}
}
static inline void gen_branch_cond(DisasContext *ctx, TCGCond cond, TCGv r1,
TCGv r2, int16_t address)
{
int jumpLabel;
jumpLabel = gen_new_label();
tcg_gen_brcond_tl(cond, r1, r2, jumpLabel);
gen_goto_tb(ctx, 1, ctx->next_pc);
gen_set_label(jumpLabel);
gen_goto_tb(ctx, 0, ctx->pc + address * 2);
}
static inline void gen_branch_condi(DisasContext *ctx, TCGCond cond, TCGv r1,
int r2, int16_t address)
{
TCGv temp = tcg_const_i32(r2);
gen_branch_cond(ctx, cond, r1, temp, address);
tcg_temp_free(temp);
}
static void gen_loop(DisasContext *ctx, int r1, int32_t offset)
{
int l1;
l1 = gen_new_label();
tcg_gen_subi_tl(cpu_gpr_a[r1], cpu_gpr_a[r1], 1);
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_gpr_a[r1], -1, l1);
gen_goto_tb(ctx, 1, ctx->pc + offset);
gen_set_label(l1);
gen_goto_tb(ctx, 0, ctx->next_pc);
}
static void gen_compute_branch(DisasContext *ctx, uint32_t opc, int r1,
int r2 , int32_t constant , int32_t offset)
{
TCGv temp;
switch (opc) {
/* SB-format jumps */
case OPC1_16_SB_J:
case OPC1_32_B_J:
gen_goto_tb(ctx, 0, ctx->pc + offset * 2);
break;
case OPC1_16_SB_CALL:
gen_helper_1arg(call, ctx->next_pc);
gen_goto_tb(ctx, 0, ctx->pc + offset * 2);
break;
case OPC1_16_SB_JZ:
gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[15], 0, offset);
break;
case OPC1_16_SB_JNZ:
gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[15], 0, offset);
break;
/* SBC-format jumps */
case OPC1_16_SBC_JEQ:
gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[15], constant, offset);
break;
case OPC1_16_SBC_JNE:
gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[15], constant, offset);
break;
/* SBRN-format jumps */
case OPC1_16_SBRN_JZ_T:
temp = tcg_temp_new();
tcg_gen_andi_tl(temp, cpu_gpr_d[15], 0x1u << constant);
gen_branch_condi(ctx, TCG_COND_EQ, temp, 0, offset);
tcg_temp_free(temp);
break;
case OPC1_16_SBRN_JNZ_T:
temp = tcg_temp_new();
tcg_gen_andi_tl(temp, cpu_gpr_d[15], 0x1u << constant);
gen_branch_condi(ctx, TCG_COND_NE, temp, 0, offset);
tcg_temp_free(temp);
break;
/* SBR-format jumps */
case OPC1_16_SBR_JEQ:
gen_branch_cond(ctx, TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[15],
offset);
break;
case OPC1_16_SBR_JNE:
gen_branch_cond(ctx, TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[15],
offset);
break;
case OPC1_16_SBR_JNZ:
gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[r1], 0, offset);
break;
case OPC1_16_SBR_JNZ_A:
gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_a[r1], 0, offset);
break;
case OPC1_16_SBR_JGEZ:
gen_branch_condi(ctx, TCG_COND_GE, cpu_gpr_d[r1], 0, offset);
break;
case OPC1_16_SBR_JGTZ:
gen_branch_condi(ctx, TCG_COND_GT, cpu_gpr_d[r1], 0, offset);
break;
case OPC1_16_SBR_JLEZ:
gen_branch_condi(ctx, TCG_COND_LE, cpu_gpr_d[r1], 0, offset);
break;
case OPC1_16_SBR_JLTZ:
gen_branch_condi(ctx, TCG_COND_LT, cpu_gpr_d[r1], 0, offset);
break;
case OPC1_16_SBR_JZ:
gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[r1], 0, offset);
break;
case OPC1_16_SBR_JZ_A:
gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_a[r1], 0, offset);
break;
case OPC1_16_SBR_LOOP:
gen_loop(ctx, r1, offset * 2 - 32);
break;
/* SR-format jumps */
case OPC1_16_SR_JI:
tcg_gen_andi_tl(cpu_PC, cpu_gpr_a[r1], 0xfffffffe);
tcg_gen_exit_tb(0);
break;
case OPC2_16_SR_RET:
gen_helper_ret(cpu_env);
tcg_gen_exit_tb(0);
break;
default:
printf("Branch Error at %x\n", ctx->pc);
}
ctx->bstate = BS_BRANCH;
}
/*
* Functions for decoding instructions
*/
static void decode_src_opc(DisasContext *ctx, int op1)
{
int r1;
int32_t const4;
TCGv temp, temp2;
r1 = MASK_OP_SRC_S1D(ctx->opcode);
const4 = MASK_OP_SRC_CONST4_SEXT(ctx->opcode);
switch (op1) {
case OPC1_16_SRC_ADD:
gen_addi_d(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);
break;
case OPC1_16_SRC_ADD_A15:
gen_addi_d(cpu_gpr_d[r1], cpu_gpr_d[15], const4);
break;
case OPC1_16_SRC_ADD_15A:
gen_addi_d(cpu_gpr_d[15], cpu_gpr_d[r1], const4);
break;
case OPC1_16_SRC_ADD_A:
tcg_gen_addi_tl(cpu_gpr_a[r1], cpu_gpr_a[r1], const4);
break;
case OPC1_16_SRC_CADD:
gen_condi_add(TCG_COND_NE, cpu_gpr_d[r1], const4, cpu_gpr_d[r1],
cpu_gpr_d[15]);
break;
case OPC1_16_SRC_CADDN:
gen_condi_add(TCG_COND_EQ, cpu_gpr_d[r1], const4, cpu_gpr_d[r1],
cpu_gpr_d[15]);
break;
case OPC1_16_SRC_CMOV:
temp = tcg_const_tl(0);
temp2 = tcg_const_tl(const4);
tcg_gen_movcond_tl(TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[15], temp,
temp2, cpu_gpr_d[r1]);
tcg_temp_free(temp);
tcg_temp_free(temp2);
break;
case OPC1_16_SRC_CMOVN:
temp = tcg_const_tl(0);
temp2 = tcg_const_tl(const4);
tcg_gen_movcond_tl(TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[15], temp,
temp2, cpu_gpr_d[r1]);
tcg_temp_free(temp);
tcg_temp_free(temp2);
break;
case OPC1_16_SRC_EQ:
tcg_gen_setcondi_tl(TCG_COND_EQ, cpu_gpr_d[15], cpu_gpr_d[r1],
const4);
break;
case OPC1_16_SRC_LT:
tcg_gen_setcondi_tl(TCG_COND_LT, cpu_gpr_d[15], cpu_gpr_d[r1],
const4);
break;
case OPC1_16_SRC_MOV:
tcg_gen_movi_tl(cpu_gpr_d[r1], const4);
break;
case OPC1_16_SRC_MOV_A:
const4 = MASK_OP_SRC_CONST4(ctx->opcode);
tcg_gen_movi_tl(cpu_gpr_a[r1], const4);
break;
case OPC1_16_SRC_SH:
gen_shi(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);
break;
case OPC1_16_SRC_SHA:
gen_shaci(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);
break;
}
}
static void decode_srr_opc(DisasContext *ctx, int op1)
{
int r1, r2;
TCGv temp;
r1 = MASK_OP_SRR_S1D(ctx->opcode);
r2 = MASK_OP_SRR_S2(ctx->opcode);
switch (op1) {
case OPC1_16_SRR_ADD:
gen_add_d(cpu_gpr_d[r1], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_ADD_A15:
gen_add_d(cpu_gpr_d[r1], cpu_gpr_d[15], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_ADD_15A:
gen_add_d(cpu_gpr_d[15], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_ADD_A:
tcg_gen_add_tl(cpu_gpr_a[r1], cpu_gpr_a[r1], cpu_gpr_a[r2]);
break;
case OPC1_16_SRR_ADDS:
gen_adds(cpu_gpr_d[r1], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_AND:
tcg_gen_and_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_CMOV:
temp = tcg_const_tl(0);
tcg_gen_movcond_tl(TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[15], temp,
cpu_gpr_d[r2], cpu_gpr_d[r1]);
tcg_temp_free(temp);
break;
case OPC1_16_SRR_CMOVN:
temp = tcg_const_tl(0);
tcg_gen_movcond_tl(TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[15], temp,
cpu_gpr_d[r2], cpu_gpr_d[r1]);
tcg_temp_free(temp);
break;
case OPC1_16_SRR_EQ:
tcg_gen_setcond_tl(TCG_COND_EQ, cpu_gpr_d[15], cpu_gpr_d[r1],
cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_LT:
tcg_gen_setcond_tl(TCG_COND_LT, cpu_gpr_d[15], cpu_gpr_d[r1],
cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_MOV:
tcg_gen_mov_tl(cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_MOV_A:
tcg_gen_mov_tl(cpu_gpr_a[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_MOV_AA:
tcg_gen_mov_tl(cpu_gpr_a[r1], cpu_gpr_a[r2]);
break;
case OPC1_16_SRR_MOV_D:
tcg_gen_mov_tl(cpu_gpr_d[r1], cpu_gpr_a[r2]);
break;
case OPC1_16_SRR_MUL:
gen_mul_i32s(cpu_gpr_d[r1], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_OR:
tcg_gen_or_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_SUB:
gen_sub_d(cpu_gpr_d[r1], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_SUB_A15B:
gen_sub_d(cpu_gpr_d[r1], cpu_gpr_d[15], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_SUB_15AB:
gen_sub_d(cpu_gpr_d[15], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_SUBS:
gen_subs(cpu_gpr_d[r1], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
case OPC1_16_SRR_XOR:
tcg_gen_xor_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], cpu_gpr_d[r2]);
break;
}
}
static void decode_ssr_opc(DisasContext *ctx, int op1)
{
int r1, r2;
r1 = MASK_OP_SSR_S1(ctx->opcode);
r2 = MASK_OP_SSR_S2(ctx->opcode);
switch (op1) {
case OPC1_16_SSR_ST_A:
tcg_gen_qemu_st_tl(cpu_gpr_a[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LEUL);
break;
case OPC1_16_SSR_ST_A_POSTINC:
tcg_gen_qemu_st_tl(cpu_gpr_a[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LEUL);
tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], 4);
break;
case OPC1_16_SSR_ST_B:
tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_UB);
break;
case OPC1_16_SSR_ST_B_POSTINC:
tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_UB);
tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], 1);
break;
case OPC1_16_SSR_ST_H:
tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LEUW);
break;
case OPC1_16_SSR_ST_H_POSTINC:
tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LEUW);
tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], 2);
break;
case OPC1_16_SSR_ST_W:
tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LEUL);
break;
case OPC1_16_SSR_ST_W_POSTINC:
tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LEUL);
tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], 4);
break;
}
}
static void decode_sc_opc(DisasContext *ctx, int op1)
{
int32_t const16;
const16 = MASK_OP_SC_CONST8(ctx->opcode);
switch (op1) {
case OPC1_16_SC_AND:
tcg_gen_andi_tl(cpu_gpr_d[15], cpu_gpr_d[15], const16);
break;
case OPC1_16_SC_BISR:
gen_helper_1arg(bisr, const16 & 0xff);
break;
case OPC1_16_SC_LD_A:
gen_offset_ld(ctx, cpu_gpr_a[15], cpu_gpr_a[10], const16 * 4, MO_LESL);
break;
case OPC1_16_SC_LD_W:
gen_offset_ld(ctx, cpu_gpr_d[15], cpu_gpr_a[10], const16 * 4, MO_LESL);
break;
case OPC1_16_SC_MOV:
tcg_gen_movi_tl(cpu_gpr_d[15], const16);
break;
case OPC1_16_SC_OR:
tcg_gen_ori_tl(cpu_gpr_d[15], cpu_gpr_d[15], const16);
break;
case OPC1_16_SC_ST_A:
gen_offset_st(ctx, cpu_gpr_a[15], cpu_gpr_a[10], const16 * 4, MO_LESL);
break;
case OPC1_16_SC_ST_W:
gen_offset_st(ctx, cpu_gpr_d[15], cpu_gpr_a[10], const16 * 4, MO_LESL);
break;
case OPC1_16_SC_SUB_A:
tcg_gen_subi_tl(cpu_gpr_a[10], cpu_gpr_a[10], const16);
break;
}
}
static void decode_slr_opc(DisasContext *ctx, int op1)
{
int r1, r2;
r1 = MASK_OP_SLR_D(ctx->opcode);
r2 = MASK_OP_SLR_S2(ctx->opcode);
switch (op1) {
/* SLR-format */
case OPC1_16_SLR_LD_A:
tcg_gen_qemu_ld_tl(cpu_gpr_a[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LESL);
break;
case OPC1_16_SLR_LD_A_POSTINC:
tcg_gen_qemu_ld_tl(cpu_gpr_a[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LESL);
tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], 4);
break;
case OPC1_16_SLR_LD_BU:
tcg_gen_qemu_ld_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_UB);
break;
case OPC1_16_SLR_LD_BU_POSTINC:
tcg_gen_qemu_ld_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_UB);
tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], 1);
break;
case OPC1_16_SLR_LD_H:
tcg_gen_qemu_ld_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LESW);
break;
case OPC1_16_SLR_LD_H_POSTINC:
tcg_gen_qemu_ld_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LESW);
tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], 2);
break;
case OPC1_16_SLR_LD_W:
tcg_gen_qemu_ld_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LESW);
break;
case OPC1_16_SLR_LD_W_POSTINC:
tcg_gen_qemu_ld_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx, MO_LESW);
tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], 4);
break;
}
}
static void decode_sro_opc(DisasContext *ctx, int op1)
{
int r2;
int32_t address;
r2 = MASK_OP_SRO_S2(ctx->opcode);
address = MASK_OP_SRO_OFF4(ctx->opcode);
/* SRO-format */
switch (op1) {
case OPC1_16_SRO_LD_A:
gen_offset_ld(ctx, cpu_gpr_a[15], cpu_gpr_a[r2], address * 4, MO_LESL);
break;
case OPC1_16_SRO_LD_BU:
gen_offset_ld(ctx, cpu_gpr_d[15], cpu_gpr_a[r2], address, MO_UB);
break;
case OPC1_16_SRO_LD_H:
gen_offset_ld(ctx, cpu_gpr_d[15], cpu_gpr_a[r2], address, MO_LESW);
break;
case OPC1_16_SRO_LD_W:
gen_offset_ld(ctx, cpu_gpr_d[15], cpu_gpr_a[r2], address * 4, MO_LESL);
break;
case OPC1_16_SRO_ST_A:
gen_offset_st(ctx, cpu_gpr_a[15], cpu_gpr_a[r2], address * 4, MO_LESL);
break;
case OPC1_16_SRO_ST_B:
gen_offset_st(ctx, cpu_gpr_d[15], cpu_gpr_a[r2], address, MO_UB);
break;
case OPC1_16_SRO_ST_H:
gen_offset_st(ctx, cpu_gpr_d[15], cpu_gpr_a[r2], address * 2, MO_LESW);
break;
case OPC1_16_SRO_ST_W:
gen_offset_st(ctx, cpu_gpr_d[15], cpu_gpr_a[r2], address * 4, MO_LESL);
break;
}
}
static void decode_sr_system(CPUTriCoreState *env, DisasContext *ctx)
{
uint32_t op2;
op2 = MASK_OP_SR_OP2(ctx->opcode);
switch (op2) {
case OPC2_16_SR_NOP:
break;
case OPC2_16_SR_RET:
gen_compute_branch(ctx, op2, 0, 0, 0, 0);
break;
case OPC2_16_SR_RFE:
gen_helper_rfe(cpu_env);
tcg_gen_exit_tb(0);
ctx->bstate = BS_BRANCH;
break;
case OPC2_16_SR_DEBUG:
/* raise EXCP_DEBUG */
break;
}
}
static void decode_sr_accu(CPUTriCoreState *env, DisasContext *ctx)
{
uint32_t op2;
uint32_t r1;
TCGv temp;
r1 = MASK_OP_SR_S1D(ctx->opcode);
op2 = MASK_OP_SR_OP2(ctx->opcode);
switch (op2) {
case OPC2_16_SR_RSUB:
/* overflow only if r1 = -0x80000000 */
temp = tcg_const_i32(-0x80000000);
/* calc V bit */
tcg_gen_setcond_tl(TCG_COND_EQ, cpu_PSW_V, cpu_gpr_d[r1], temp);
tcg_gen_shli_tl(cpu_PSW_V, cpu_PSW_V, 31);
/* calc SV bit */
tcg_gen_or_tl(cpu_PSW_SV, cpu_PSW_SV, cpu_PSW_V);
/* sub */
tcg_gen_neg_tl(cpu_gpr_d[r1], cpu_gpr_d[r1]);
/* calc av */
tcg_gen_add_tl(cpu_PSW_AV, cpu_gpr_d[r1], cpu_gpr_d[r1]);
tcg_gen_xor_tl(cpu_PSW_AV, cpu_gpr_d[r1], cpu_PSW_AV);
/* calc sav */
tcg_gen_or_tl(cpu_PSW_SAV, cpu_PSW_SAV, cpu_PSW_AV);
tcg_temp_free(temp);
break;
case OPC2_16_SR_SAT_B:
gen_saturate(cpu_gpr_d[r1], cpu_gpr_d[r1], 0x7f, -0x80);
break;
case OPC2_16_SR_SAT_BU:
gen_saturate_u(cpu_gpr_d[r1], cpu_gpr_d[r1], 0xff);
break;
case OPC2_16_SR_SAT_H:
gen_saturate(cpu_gpr_d[r1], cpu_gpr_d[r1], 0x7fff, -0x8000);
break;
case OPC2_16_SR_SAT_HU:
gen_saturate_u(cpu_gpr_d[r1], cpu_gpr_d[r1], 0xffff);
break;
}
}
static void decode_16Bit_opc(CPUTriCoreState *env, DisasContext *ctx)
{
int op1;
int r1, r2;
int32_t const16;
int32_t address;
TCGv temp;
op1 = MASK_OP_MAJOR(ctx->opcode);
/* handle ADDSC.A opcode only being 6 bit long */
if (unlikely((op1 & 0x3f) == OPC1_16_SRRS_ADDSC_A)) {
op1 = OPC1_16_SRRS_ADDSC_A;
}
switch (op1) {
case OPC1_16_SRC_ADD:
case OPC1_16_SRC_ADD_A15:
case OPC1_16_SRC_ADD_15A:
case OPC1_16_SRC_ADD_A:
case OPC1_16_SRC_CADD:
case OPC1_16_SRC_CADDN:
case OPC1_16_SRC_CMOV:
case OPC1_16_SRC_CMOVN:
case OPC1_16_SRC_EQ:
case OPC1_16_SRC_LT:
case OPC1_16_SRC_MOV:
case OPC1_16_SRC_MOV_A:
case OPC1_16_SRC_SH:
case OPC1_16_SRC_SHA:
decode_src_opc(ctx, op1);
break;
/* SRR-format */
case OPC1_16_SRR_ADD:
case OPC1_16_SRR_ADD_A15:
case OPC1_16_SRR_ADD_15A:
case OPC1_16_SRR_ADD_A:
case OPC1_16_SRR_ADDS:
case OPC1_16_SRR_AND:
case OPC1_16_SRR_CMOV:
case OPC1_16_SRR_CMOVN:
case OPC1_16_SRR_EQ:
case OPC1_16_SRR_LT:
case OPC1_16_SRR_MOV:
case OPC1_16_SRR_MOV_A:
case OPC1_16_SRR_MOV_AA:
case OPC1_16_SRR_MOV_D:
case OPC1_16_SRR_MUL:
case OPC1_16_SRR_OR:
case OPC1_16_SRR_SUB:
case OPC1_16_SRR_SUB_A15B:
case OPC1_16_SRR_SUB_15AB:
case OPC1_16_SRR_SUBS:
case OPC1_16_SRR_XOR:
decode_srr_opc(ctx, op1);
break;
/* SSR-format */
case OPC1_16_SSR_ST_A:
case OPC1_16_SSR_ST_A_POSTINC:
case OPC1_16_SSR_ST_B:
case OPC1_16_SSR_ST_B_POSTINC:
case OPC1_16_SSR_ST_H:
case OPC1_16_SSR_ST_H_POSTINC:
case OPC1_16_SSR_ST_W:
case OPC1_16_SSR_ST_W_POSTINC:
decode_ssr_opc(ctx, op1);
break;
/* SRRS-format */
case OPC1_16_SRRS_ADDSC_A:
r2 = MASK_OP_SRRS_S2(ctx->opcode);
r1 = MASK_OP_SRRS_S1D(ctx->opcode);
const16 = MASK_OP_SRRS_N(ctx->opcode);
temp = tcg_temp_new();
tcg_gen_shli_tl(temp, cpu_gpr_d[15], const16);
tcg_gen_add_tl(cpu_gpr_a[r1], cpu_gpr_a[r2], temp);
tcg_temp_free(temp);
break;
/* SLRO-format */
case OPC1_16_SLRO_LD_A:
r1 = MASK_OP_SLRO_D(ctx->opcode);
const16 = MASK_OP_SLRO_OFF4(ctx->opcode);
gen_offset_ld(ctx, cpu_gpr_a[r1], cpu_gpr_a[15], const16 * 4, MO_LESL);
break;
case OPC1_16_SLRO_LD_BU:
r1 = MASK_OP_SLRO_D(ctx->opcode);
const16 = MASK_OP_SLRO_OFF4(ctx->opcode);
gen_offset_ld(ctx, cpu_gpr_d[r1], cpu_gpr_a[15], const16, MO_UB);
break;
case OPC1_16_SLRO_LD_H:
r1 = MASK_OP_SLRO_D(ctx->opcode);
const16 = MASK_OP_SLRO_OFF4(ctx->opcode);
gen_offset_ld(ctx, cpu_gpr_d[r1], cpu_gpr_a[15], const16 * 2, MO_LESW);
break;
case OPC1_16_SLRO_LD_W:
r1 = MASK_OP_SLRO_D(ctx->opcode);
const16 = MASK_OP_SLRO_OFF4(ctx->opcode);
gen_offset_ld(ctx, cpu_gpr_d[r1], cpu_gpr_a[15], const16 * 4, MO_LESL);
break;
/* SB-format */
case OPC1_16_SB_CALL:
case OPC1_16_SB_J:
case OPC1_16_SB_JNZ:
case OPC1_16_SB_JZ:
address = MASK_OP_SB_DISP8_SEXT(ctx->opcode);
gen_compute_branch(ctx, op1, 0, 0, 0, address);
break;
/* SBC-format */
case OPC1_16_SBC_JEQ:
case OPC1_16_SBC_JNE:
address = MASK_OP_SBC_DISP4(ctx->opcode);
const16 = MASK_OP_SBC_CONST4_SEXT(ctx->opcode);
gen_compute_branch(ctx, op1, 0, 0, const16, address);
break;
/* SBRN-format */
case OPC1_16_SBRN_JNZ_T:
case OPC1_16_SBRN_JZ_T:
address = MASK_OP_SBRN_DISP4(ctx->opcode);
const16 = MASK_OP_SBRN_N(ctx->opcode);
gen_compute_branch(ctx, op1, 0, 0, const16, address);
break;
/* SBR-format */
case OPC1_16_SBR_JEQ:
case OPC1_16_SBR_JGEZ:
case OPC1_16_SBR_JGTZ:
case OPC1_16_SBR_JLEZ:
case OPC1_16_SBR_JLTZ:
case OPC1_16_SBR_JNE:
case OPC1_16_SBR_JNZ:
case OPC1_16_SBR_JNZ_A:
case OPC1_16_SBR_JZ:
case OPC1_16_SBR_JZ_A:
case OPC1_16_SBR_LOOP:
r1 = MASK_OP_SBR_S2(ctx->opcode);
address = MASK_OP_SBR_DISP4(ctx->opcode);
gen_compute_branch(ctx, op1, r1, 0, 0, address);
break;
/* SC-format */
case OPC1_16_SC_AND:
case OPC1_16_SC_BISR:
case OPC1_16_SC_LD_A:
case OPC1_16_SC_LD_W:
case OPC1_16_SC_MOV:
case OPC1_16_SC_OR:
case OPC1_16_SC_ST_A:
case OPC1_16_SC_ST_W:
case OPC1_16_SC_SUB_A:
decode_sc_opc(ctx, op1);
break;
/* SLR-format */
case OPC1_16_SLR_LD_A:
case OPC1_16_SLR_LD_A_POSTINC:
case OPC1_16_SLR_LD_BU:
case OPC1_16_SLR_LD_BU_POSTINC:
case OPC1_16_SLR_LD_H:
case OPC1_16_SLR_LD_H_POSTINC:
case OPC1_16_SLR_LD_W:
case OPC1_16_SLR_LD_W_POSTINC:
decode_slr_opc(ctx, op1);
break;
/* SRO-format */
case OPC1_16_SRO_LD_A:
case OPC1_16_SRO_LD_BU:
case OPC1_16_SRO_LD_H:
case OPC1_16_SRO_LD_W:
case OPC1_16_SRO_ST_A:
case OPC1_16_SRO_ST_B:
case OPC1_16_SRO_ST_H:
case OPC1_16_SRO_ST_W:
decode_sro_opc(ctx, op1);
break;
/* SSRO-format */
case OPC1_16_SSRO_ST_A:
r1 = MASK_OP_SSRO_S1(ctx->opcode);
const16 = MASK_OP_SSRO_OFF4(ctx->opcode);
gen_offset_st(ctx, cpu_gpr_a[r1], cpu_gpr_a[15], const16 * 4, MO_LESL);
break;
case OPC1_16_SSRO_ST_B:
r1 = MASK_OP_SSRO_S1(ctx->opcode);
const16 = MASK_OP_SSRO_OFF4(ctx->opcode);
gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[15], const16, MO_UB);
break;
case OPC1_16_SSRO_ST_H:
r1 = MASK_OP_SSRO_S1(ctx->opcode);
const16 = MASK_OP_SSRO_OFF4(ctx->opcode);
gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[15], const16 * 2, MO_LESW);
break;
case OPC1_16_SSRO_ST_W:
r1 = MASK_OP_SSRO_S1(ctx->opcode);
const16 = MASK_OP_SSRO_OFF4(ctx->opcode);
gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[15], const16 * 4, MO_LESL);
break;
/* SR-format */
case OPCM_16_SR_SYSTEM:
decode_sr_system(env, ctx);
break;
case OPCM_16_SR_ACCU:
decode_sr_accu(env, ctx);
break;
case OPC1_16_SR_JI:
r1 = MASK_OP_SR_S1D(ctx->opcode);
gen_compute_branch(ctx, op1, r1, 0, 0, 0);
break;
case OPC1_16_SR_NOT:
r1 = MASK_OP_SR_S1D(ctx->opcode);
tcg_gen_not_tl(cpu_gpr_d[r1], cpu_gpr_d[r1]);
break;
}
}
static void decode_32Bit_opc(CPUTriCoreState *env, DisasContext *ctx)
{
}
static void decode_opc(CPUTriCoreState *env, DisasContext *ctx, int *is_branch)
{
/* 16-Bit Instruction */
if ((ctx->opcode & 0x1) == 0) {
ctx->next_pc = ctx->pc + 2;
decode_16Bit_opc(env, ctx);
/* 32-Bit Instruction */
} else {
ctx->next_pc = ctx->pc + 4;
decode_32Bit_opc(env, ctx);
}
}
static inline void
gen_intermediate_code_internal(TriCoreCPU *cpu, struct TranslationBlock *tb,
int search_pc)
{
CPUState *cs = CPU(cpu);
CPUTriCoreState *env = &cpu->env;
DisasContext ctx;
target_ulong pc_start;
int num_insns;
uint16_t *gen_opc_end;
if (search_pc) {
qemu_log("search pc %d\n", search_pc);
}
num_insns = 0;
pc_start = tb->pc;
gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;
ctx.pc = pc_start;
ctx.saved_pc = -1;
ctx.tb = tb;
ctx.singlestep_enabled = cs->singlestep_enabled;
ctx.bstate = BS_NONE;
ctx.mem_idx = cpu_mmu_index(env);
tcg_clear_temp_count();
gen_tb_start();
while (ctx.bstate == BS_NONE) {
ctx.opcode = cpu_ldl_code(env, ctx.pc);
decode_opc(env, &ctx, 0);
num_insns++;
if (tcg_ctx.gen_opc_ptr >= gen_opc_end) {
gen_save_pc(ctx.next_pc);
tcg_gen_exit_tb(0);
break;
}
if (singlestep) {
gen_save_pc(ctx.next_pc);
tcg_gen_exit_tb(0);
break;
}
ctx.pc = ctx.next_pc;
}
gen_tb_end(tb, num_insns);
*tcg_ctx.gen_opc_ptr = INDEX_op_end;
if (search_pc) {
printf("done_generating search pc\n");
} else {
tb->size = ctx.pc - pc_start;
tb->icount = num_insns;
}
if (tcg_check_temp_count()) {
printf("LEAK at %08x\n", env->PC);
}
#ifdef DEBUG_DISAS
if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {
qemu_log("IN: %s\n", lookup_symbol(pc_start));
log_target_disas(env, pc_start, ctx.pc - pc_start, 0);
qemu_log("\n");
}
#endif
}
void
gen_intermediate_code(CPUTriCoreState *env, struct TranslationBlock *tb)
{
gen_intermediate_code_internal(tricore_env_get_cpu(env), tb, false);
}
void
gen_intermediate_code_pc(CPUTriCoreState *env, struct TranslationBlock *tb)
{
gen_intermediate_code_internal(tricore_env_get_cpu(env), tb, true);
}
void
restore_state_to_opc(CPUTriCoreState *env, TranslationBlock *tb, int pc_pos)
{
env->PC = tcg_ctx.gen_opc_pc[pc_pos];
}
/*
*
* Initialization
*
*/
void cpu_state_reset(CPUTriCoreState *env)
{
/* Reset Regs to Default Value */
env->PSW = 0xb80;
}
static void tricore_tcg_init_csfr(void)
{
cpu_PCXI = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, PCXI), "PCXI");
cpu_PSW = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, PSW), "PSW");
cpu_PC = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, PC), "PC");
cpu_ICR = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, ICR), "ICR");
}
void tricore_tcg_init(void)
{
int i;
static int inited;
if (inited) {
return;
}
cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");
/* reg init */
for (i = 0 ; i < 16 ; i++) {
cpu_gpr_a[i] = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, gpr_a[i]),
regnames_a[i]);
}
for (i = 0 ; i < 16 ; i++) {
cpu_gpr_d[i] = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, gpr_d[i]),
regnames_d[i]);
}
tricore_tcg_init_csfr();
/* init PSW flag cache */
cpu_PSW_C = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, PSW_USB_C),
"PSW_C");
cpu_PSW_V = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, PSW_USB_V),
"PSW_V");
cpu_PSW_SV = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, PSW_USB_SV),
"PSW_SV");
cpu_PSW_AV = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, PSW_USB_AV),
"PSW_AV");
cpu_PSW_SAV = tcg_global_mem_new(TCG_AREG0,
offsetof(CPUTriCoreState, PSW_USB_SAV),
"PSW_SAV");
}
| gpl-2.0 |
nslu2/linux-2.4.x | arch/niosnommu/kernel/traps.c | 6 | 2610 | /*FIXME - some unimplemented stuff to do */
/*
* arch/niosnommu/kernel/traps.c
*
* Copyright 2001 Vic Phillips
*
* hacked from:
*
* arch/sparcnommu/kernel/traps.c
*
* Copyright 1995 David S. Miller (davem@caip.rutgers.edu)
*/
#include <linux/sched.h> /* for jiffies */
#include <linux/kernel.h>
#include <linux/config.h>
#include <linux/signal.h>
#include <asm/delay.h>
#include <asm/system.h>
#include <asm/ptrace.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/unistd.h>
#include <asm/traps.h>
#include <asm/nios.h>
#include "hex.h"
/* #define TRAP_DEBUG */
static void puts(unsigned char *s) {
while(*s) {
while (!(nasys_printf_uart->np_uartstatus & np_uartstatus_trdy_mask));
nasys_printf_uart->np_uarttxdata = *s++;
}
while (!(nasys_printf_uart->np_uartstatus & np_uartstatus_trdy_mask));
nasys_printf_uart->np_uarttxdata = '\r';
while (!(nasys_printf_uart->np_uartstatus & np_uartstatus_trdy_mask));
nasys_printf_uart->np_uarttxdata = '\n';
}
#if 0
void dumpit(unsigned long l1, unsigned long l2)
{
outhex32(l1);
puts("l1");
outhex32(l2);
puts("l2");
while(1);
}
struct trap_trace_entry {
unsigned long pc;
unsigned long type;
};
int trap_curbuf = 0;
struct trap_trace_entry trapbuf[1024];
void syscall_trace_entry(struct pt_regs *regs)
{
printk("%s[%d]: ", current->comm, current->pid);
printk("scall<%d> (could be %d)\n", (int) regs->u_regs[UREG_G1],
(int) regs->u_regs[UREG_I0]);
}
void syscall_trace_exit(struct pt_regs *regs)
{
}
#endif
void die_if_kernel(char *str, struct pt_regs *pregs)
{
unsigned long pc;
pc = pregs->pc;
puts("");
outhex32(pc);
puts(" trapped to die_if_kernel");
show_regs(pregs);
#if 0
if(pregs->psr & PSR_SUPERVISOR)
do_exit(SIGKILL);
do_exit(SIGSEGV);
#endif
}
void do_hw_interrupt(unsigned long type, unsigned long psr, unsigned long pc)
{
if(type < 0x10) {
printk("Unimplemented Nios TRAP, type = %02lx\n", type);
die_if_kernel("Whee... Hello Mr. Penguin", current->thread.kregs);
}
#if 0
if(type == SP_TRAP_SBPT) {
send_sig(SIGTRAP, current, 1);
return;
}
current->thread.sig_desc = SUBSIG_BADTRAP(type - 0x80);
current->thread.sig_address = pc;
send_sig(SIGILL, current, 1);
#endif
}
#if 0
void handle_watchpoint(struct pt_regs *regs, unsigned long pc, unsigned long psr)
{
#ifdef TRAP_DEBUG
printk("Watchpoint detected at PC %08lx PSR %08lx\n", pc, psr);
#endif
if(psr & PSR_SUPERVISOR)
panic("Tell me what a watchpoint trap is, and I'll then deal "
"with such a beast...");
}
#endif
void trap_init(void)
{
#ifdef DEBUG
printk("trap_init reached\n");
#endif
}
| gpl-2.0 |
fqrouter/conntrack-tools | extensions/libct_proto_icmp.c | 6 | 2844 | /*
* (C) 2005-2007 by Pablo Neira Ayuso <pablo@netfilter.org>
* 2005 by Harald Welte <laforge@netfilter.org>
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
*/
#include "conntrack.h"
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <netinet/in.h> /* For htons */
#include <netinet/ip_icmp.h>
#include <libnetfilter_conntrack/libnetfilter_conntrack.h>
enum {
CT_ICMP_TYPE = (1 << 0),
CT_ICMP_CODE = (1 << 1),
CT_ICMP_ID = (1 << 2),
};
static struct option opts[] = {
{"icmp-type", 1, 0, '1'},
{"icmp-code", 1, 0, '2'},
{"icmp-id", 1, 0, '3'},
{0, 0, 0, 0}
};
#define ICMP_NUMBER_OF_OPT 4
static const char *icmp_optflags[ICMP_NUMBER_OF_OPT] = {
"icmp-type", "icmp-code", "icmp-id"
};
static char icmp_commands_v_options[NUMBER_OF_CMD][ICMP_NUMBER_OF_OPT] =
/* Well, it's better than "Re: Maradona vs Pele" */
{
/* 1 2 3 */
/*CT_LIST*/ {2,2,2},
/*CT_CREATE*/ {1,1,2},
/*CT_UPDATE*/ {2,2,2},
/*CT_DELETE*/ {2,2,2},
/*CT_GET*/ {1,1,2},
/*CT_FLUSH*/ {0,0,0},
/*CT_EVENT*/ {2,2,2},
/*CT_VERSION*/ {0,0,0},
/*CT_HELP*/ {0,0,0},
/*EXP_LIST*/ {0,0,0},
/*EXP_CREATE*/ {0,0,0},
/*EXP_DELETE*/ {0,0,0},
/*EXP_GET*/ {0,0,0},
/*EXP_FLUSH*/ {0,0,0},
/*EXP_EVENT*/ {0,0,0},
};
static void help(void)
{
fprintf(stdout, " --icmp-type\t\t\ticmp type\n");
fprintf(stdout, " --icmp-code\t\t\ticmp code\n");
fprintf(stdout, " --icmp-id\t\t\ticmp id\n");
}
static int parse(char c,
struct nf_conntrack *ct,
struct nf_conntrack *exptuple,
struct nf_conntrack *mask,
unsigned int *flags)
{
switch(c) {
u_int8_t tmp;
u_int16_t id;
case '1':
tmp = atoi(optarg);
nfct_set_attr_u8(ct, ATTR_ICMP_TYPE, tmp);
nfct_set_attr_u8(ct, ATTR_L4PROTO, IPPROTO_ICMP);
*flags |= CT_ICMP_TYPE;
break;
case '2':
tmp = atoi(optarg);
nfct_set_attr_u8(ct, ATTR_ICMP_CODE, tmp);
nfct_set_attr_u8(ct, ATTR_L4PROTO, IPPROTO_ICMP);
*flags |= CT_ICMP_CODE;
break;
case '3':
id = htons(atoi(optarg));
nfct_set_attr_u16(ct, ATTR_ICMP_ID, id);
nfct_set_attr_u8(ct, ATTR_L4PROTO, IPPROTO_ICMP);
*flags |= CT_ICMP_ID;
break;
}
return 1;
}
static void final_check(unsigned int flags,
unsigned int cmd,
struct nf_conntrack *ct)
{
generic_opt_check(flags,
ICMP_NUMBER_OF_OPT,
icmp_commands_v_options[cmd],
icmp_optflags, NULL, 0, NULL);
}
static struct ctproto_handler icmp = {
.name = "icmp",
.protonum = IPPROTO_ICMP,
.parse_opts = parse,
.final_check = final_check,
.help = help,
.opts = opts,
.version = VERSION,
};
void register_icmp(void)
{
register_proto(&icmp);
}
| gpl-2.0 |
xnox/systemd | src/basic/architecture.c | 6 | 7611 | /***
This file is part of systemd.
Copyright 2014 Lennart Poettering
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <sys/utsname.h>
#include "architecture.h"
#include "macro.h"
#include "string-table.h"
#include "string-util.h"
int uname_architecture(void) {
/* Return a sanitized enum identifying the architecture we are
* running on. This is based on uname(), and the user may
* hence control what this returns by using
* personality(). This puts the user in control on systems
* that can run binaries of multiple architectures.
*
* We do not translate the string returned by uname()
* 1:1. Instead we try to clean it up and break down the
* confusion on x86 and arm in particular.
*
* We do not try to distinguish CPUs not CPU features, but
* actual architectures, i.e. that have genuinely different
* code. */
static const struct {
const char *machine;
int arch;
} arch_map[] = {
#if defined(__x86_64__) || defined(__i386__)
{ "x86_64", ARCHITECTURE_X86_64 },
{ "i686", ARCHITECTURE_X86 },
{ "i586", ARCHITECTURE_X86 },
{ "i486", ARCHITECTURE_X86 },
{ "i386", ARCHITECTURE_X86 },
#elif defined(__powerpc__) || defined(__powerpc64__)
{ "ppc64", ARCHITECTURE_PPC64 },
{ "ppc64le", ARCHITECTURE_PPC64_LE },
{ "ppc", ARCHITECTURE_PPC },
{ "ppcle", ARCHITECTURE_PPC_LE },
#elif defined(__ia64__)
{ "ia64", ARCHITECTURE_IA64 },
#elif defined(__hppa__) || defined(__hppa64__)
{ "parisc64", ARCHITECTURE_PARISC64 },
{ "parisc", ARCHITECTURE_PARISC },
#elif defined(__s390__) || defined(__s390x__)
{ "s390x", ARCHITECTURE_S390X },
{ "s390", ARCHITECTURE_S390 },
#elif defined(__sparc__) || defined(__sparc64__)
{ "sparc64", ARCHITECTURE_SPARC64 },
{ "sparc", ARCHITECTURE_SPARC },
#elif defined(__mips__) || defined(__mips64__)
{ "mips64", ARCHITECTURE_MIPS64 },
{ "mips", ARCHITECTURE_MIPS },
#elif defined(__alpha__)
{ "alpha" , ARCHITECTURE_ALPHA },
#elif defined(__arm__) || defined(__aarch64__)
{ "aarch64", ARCHITECTURE_ARM64 },
{ "aarch64_be", ARCHITECTURE_ARM64_BE },
{ "armv4l", ARCHITECTURE_ARM },
{ "armv4b", ARCHITECTURE_ARM_BE },
{ "armv4tl", ARCHITECTURE_ARM },
{ "armv4tb", ARCHITECTURE_ARM_BE },
{ "armv5tl", ARCHITECTURE_ARM },
{ "armv5tb", ARCHITECTURE_ARM_BE },
{ "armv5tel", ARCHITECTURE_ARM },
{ "armv5teb" , ARCHITECTURE_ARM_BE },
{ "armv5tejl", ARCHITECTURE_ARM },
{ "armv5tejb", ARCHITECTURE_ARM_BE },
{ "armv6l", ARCHITECTURE_ARM },
{ "armv6b", ARCHITECTURE_ARM_BE },
{ "armv7l", ARCHITECTURE_ARM },
{ "armv7b", ARCHITECTURE_ARM_BE },
{ "armv7ml", ARCHITECTURE_ARM },
{ "armv7mb", ARCHITECTURE_ARM_BE },
{ "armv4l", ARCHITECTURE_ARM },
{ "armv4b", ARCHITECTURE_ARM_BE },
{ "armv4tl", ARCHITECTURE_ARM },
{ "armv4tb", ARCHITECTURE_ARM_BE },
{ "armv5tl", ARCHITECTURE_ARM },
{ "armv5tb", ARCHITECTURE_ARM_BE },
{ "armv5tel", ARCHITECTURE_ARM },
{ "armv5teb", ARCHITECTURE_ARM_BE },
{ "armv5tejl", ARCHITECTURE_ARM },
{ "armv5tejb", ARCHITECTURE_ARM_BE },
{ "armv6l", ARCHITECTURE_ARM },
{ "armv6b", ARCHITECTURE_ARM_BE },
{ "armv7l", ARCHITECTURE_ARM },
{ "armv7b", ARCHITECTURE_ARM_BE },
{ "armv7ml", ARCHITECTURE_ARM },
{ "armv7mb", ARCHITECTURE_ARM_BE },
{ "armv8l", ARCHITECTURE_ARM },
{ "armv8b", ARCHITECTURE_ARM_BE },
#elif defined(__sh__) || defined(__sh64__)
{ "sh5", ARCHITECTURE_SH64 },
{ "sh2", ARCHITECTURE_SH },
{ "sh2a", ARCHITECTURE_SH },
{ "sh3", ARCHITECTURE_SH },
{ "sh4", ARCHITECTURE_SH },
{ "sh4a", ARCHITECTURE_SH },
#elif defined(__m68k__)
{ "m68k", ARCHITECTURE_M68K },
#elif defined(__tilegx__)
{ "tilegx", ARCHITECTURE_TILEGX },
#elif defined(__cris__)
{ "crisv32", ARCHITECTURE_CRIS },
#else
#error "Please register your architecture here!"
#endif
};
static int cached = _ARCHITECTURE_INVALID;
struct utsname u;
unsigned i;
if (cached != _ARCHITECTURE_INVALID)
return cached;
assert_se(uname(&u) >= 0);
for (i = 0; i < ELEMENTSOF(arch_map); i++)
if (streq(arch_map[i].machine, u.machine))
return cached = arch_map[i].arch;
assert_not_reached("Couldn't identify architecture. You need to patch systemd.");
return _ARCHITECTURE_INVALID;
}
static const char *const architecture_table[_ARCHITECTURE_MAX] = {
[ARCHITECTURE_X86] = "x86",
[ARCHITECTURE_X86_64] = "x86-64",
[ARCHITECTURE_PPC] = "ppc",
[ARCHITECTURE_PPC_LE] = "ppc-le",
[ARCHITECTURE_PPC64] = "ppc64",
[ARCHITECTURE_PPC64_LE] = "ppc64-le",
[ARCHITECTURE_IA64] = "ia64",
[ARCHITECTURE_PARISC] = "parisc",
[ARCHITECTURE_PARISC64] = "parisc64",
[ARCHITECTURE_S390] = "s390",
[ARCHITECTURE_S390X] = "s390x",
[ARCHITECTURE_SPARC] = "sparc",
[ARCHITECTURE_SPARC64] = "sparc64",
[ARCHITECTURE_MIPS] = "mips",
[ARCHITECTURE_MIPS_LE] = "mips-le",
[ARCHITECTURE_MIPS64] = "mips64",
[ARCHITECTURE_MIPS64_LE] = "mips64-le",
[ARCHITECTURE_ALPHA] = "alpha",
[ARCHITECTURE_ARM] = "arm",
[ARCHITECTURE_ARM_BE] = "arm-be",
[ARCHITECTURE_ARM64] = "arm64",
[ARCHITECTURE_ARM64_BE] = "arm64-be",
[ARCHITECTURE_SH] = "sh",
[ARCHITECTURE_SH64] = "sh64",
[ARCHITECTURE_M68K] = "m68k",
[ARCHITECTURE_TILEGX] = "tilegx",
[ARCHITECTURE_CRIS] = "cris",
};
DEFINE_STRING_TABLE_LOOKUP(architecture, int);
| gpl-2.0 |
AOSPA-legacy/android_kernel_lge_msm8974 | fs/fat/inode.c | 6 | 44924 | /*
* linux/fs/fat/inode.c
*
* Written 1992,1993 by Werner Almesberger
* VFAT extensions by Gordon Chaffee, merged with msdos fs by Henrik Storner
* Rewritten for the constant inumbers support by Al Viro
*
* Fixes:
*
* Max Cohan: Fixed invalid FSINFO offset when info_sector is 0
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/pagemap.h>
#include <linux/mpage.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/mount.h>
#include <linux/vfs.h>
#include <linux/parser.h>
#include <linux/uio.h>
#include <linux/writeback.h>
#include <linux/log2.h>
#include <linux/hash.h>
#include <asm/unaligned.h>
#include "fat.h"
#ifndef CONFIG_FAT_DEFAULT_IOCHARSET
/* if user don't select VFAT, this is undefined. */
#define CONFIG_FAT_DEFAULT_IOCHARSET ""
#endif
static int fat_default_codepage = CONFIG_FAT_DEFAULT_CODEPAGE;
static char fat_default_iocharset[] = CONFIG_FAT_DEFAULT_IOCHARSET;
static int fat_add_cluster(struct inode *inode)
{
int err, cluster;
err = fat_alloc_clusters(inode, &cluster, 1);
if (err)
return err;
/* FIXME: this cluster should be added after data of this
* cluster is writed */
err = fat_chain_add(inode, cluster, 1);
if (err)
fat_free_clusters(inode, cluster);
return err;
}
static inline int __fat_get_block(struct inode *inode, sector_t iblock,
unsigned long *max_blocks,
struct buffer_head *bh_result, int create)
{
struct super_block *sb = inode->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
unsigned long mapped_blocks;
sector_t phys;
int err, offset;
err = fat_bmap(inode, iblock, &phys, &mapped_blocks, create);
if (err)
return err;
if (phys) {
map_bh(bh_result, sb, phys);
*max_blocks = min(mapped_blocks, *max_blocks);
return 0;
}
if (!create)
return 0;
if (iblock != MSDOS_I(inode)->mmu_private >> sb->s_blocksize_bits) {
fat_fs_error(sb, "corrupted file size (i_pos %lld, %lld)",
MSDOS_I(inode)->i_pos, MSDOS_I(inode)->mmu_private);
return -EIO;
}
offset = (unsigned long)iblock & (sbi->sec_per_clus - 1);
if (!offset) {
/* TODO: multiple cluster allocation would be desirable. */
err = fat_add_cluster(inode);
if (err)
return err;
}
/* available blocks on this cluster */
mapped_blocks = sbi->sec_per_clus - offset;
*max_blocks = min(mapped_blocks, *max_blocks);
MSDOS_I(inode)->mmu_private += *max_blocks << sb->s_blocksize_bits;
err = fat_bmap(inode, iblock, &phys, &mapped_blocks, create);
if (err)
return err;
BUG_ON(!phys);
BUG_ON(*max_blocks != mapped_blocks);
set_buffer_new(bh_result);
map_bh(bh_result, sb, phys);
return 0;
}
static int fat_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
struct super_block *sb = inode->i_sb;
unsigned long max_blocks = bh_result->b_size >> inode->i_blkbits;
int err;
err = __fat_get_block(inode, iblock, &max_blocks, bh_result, create);
if (err)
return err;
bh_result->b_size = max_blocks << sb->s_blocksize_bits;
return 0;
}
static int fat_writepage(struct page *page, struct writeback_control *wbc)
{
return block_write_full_page(page, fat_get_block, wbc);
}
static int fat_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
return mpage_writepages(mapping, wbc, fat_get_block);
}
static int fat_readpage(struct file *file, struct page *page)
{
return mpage_readpage(page, fat_get_block);
}
static int fat_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
return mpage_readpages(mapping, pages, nr_pages, fat_get_block);
}
static void fat_write_failed(struct address_space *mapping, loff_t to)
{
struct inode *inode = mapping->host;
if (to > inode->i_size) {
truncate_pagecache(inode, to, inode->i_size);
fat_truncate_blocks(inode, inode->i_size);
}
}
static int fat_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
int err;
*pagep = NULL;
err = cont_write_begin(file, mapping, pos, len, flags,
pagep, fsdata, fat_get_block,
&MSDOS_I(mapping->host)->mmu_private);
if (err < 0)
fat_write_failed(mapping, pos + len);
return err;
}
static int fat_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *pagep, void *fsdata)
{
struct inode *inode = mapping->host;
int err;
err = generic_write_end(file, mapping, pos, len, copied, pagep, fsdata);
if (err < len)
fat_write_failed(mapping, pos + len);
if (!(err < 0) && !(MSDOS_I(inode)->i_attrs & ATTR_ARCH)) {
inode->i_mtime = inode->i_ctime = CURRENT_TIME_SEC;
MSDOS_I(inode)->i_attrs |= ATTR_ARCH;
mark_inode_dirty(inode);
}
return err;
}
static ssize_t fat_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov,
loff_t offset, unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
ssize_t ret;
if (rw == WRITE) {
/*
* FIXME: blockdev_direct_IO() doesn't use ->write_begin(),
* so we need to update the ->mmu_private to block boundary.
*
* But we must fill the remaining area or hole by nul for
* updating ->mmu_private.
*
* Return 0, and fallback to normal buffered write.
*/
loff_t size = offset + iov_length(iov, nr_segs);
if (MSDOS_I(inode)->mmu_private < size)
return 0;
}
/*
* FAT need to use the DIO_LOCKING for avoiding the race
* condition of fat_get_block() and ->truncate().
*/
ret = blockdev_direct_IO(rw, iocb, inode, iov, offset, nr_segs,
fat_get_block);
if (ret < 0 && (rw & WRITE))
fat_write_failed(mapping, offset + iov_length(iov, nr_segs));
return ret;
}
static sector_t _fat_bmap(struct address_space *mapping, sector_t block)
{
sector_t blocknr;
/* fat_get_cluster() assumes the requested blocknr isn't truncated. */
down_read(&MSDOS_I(mapping->host)->truncate_lock);
blocknr = generic_block_bmap(mapping, block, fat_get_block);
up_read(&MSDOS_I(mapping->host)->truncate_lock);
return blocknr;
}
static const struct address_space_operations fat_aops = {
.readpage = fat_readpage,
.readpages = fat_readpages,
.writepage = fat_writepage,
.writepages = fat_writepages,
.write_begin = fat_write_begin,
.write_end = fat_write_end,
.direct_IO = fat_direct_IO,
.bmap = _fat_bmap
};
/*2013-05-02 Hyoungtaek-Lim[hyoungtaek.lim@lge.com)[g2/vmware/vzw,att]VMware Switch [START]*/
#ifdef CONFIG_LGE_B2B_VMWARE
int _fat_fallocate(struct inode *inode, loff_t len)
{
struct super_block *sb = inode->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
int err;
sector_t nblocks, iblock;
unsigned short offset;
if (!S_ISREG(inode->i_mode)) {
printk(KERN_ERR "_fat_fallocate: supported only for regular files\n");
return -EOPNOTSUPP;
}
if (IS_IMMUTABLE(inode)) {
return -EPERM;
}
mutex_lock(&inode->i_mutex);
/* file is already big enough */
if (len <= i_size_read(inode)) {
mutex_unlock(&inode->i_mutex);
return 0;
}
nblocks = (len + sb->s_blocksize - 1 ) >> sb->s_blocksize_bits;
iblock = (MSDOS_I(inode)->mmu_private + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
/* validate new size */
err = inode_newsize_ok(inode, len);
if (err) {
mutex_unlock(&inode->i_mutex);
return err;
}
/* check for available blocks on last cluster */
offset = (unsigned long)iblock & (sbi->sec_per_clus - 1);
if (offset) {
iblock += min((unsigned long) (sbi->sec_per_clus - offset),
(unsigned long) (nblocks - iblock));
}
/* now allocate new clusters */
while (iblock < nblocks) {
err = fat_add_cluster(inode);
if (err) {
break;
}
iblock += min((unsigned long) sbi->sec_per_clus,
(unsigned long) (nblocks - iblock));
}
/* update inode informations */
len = min(len, (loff_t)(iblock << sb->s_blocksize_bits));
i_size_write(inode, len);
MSDOS_I(inode)->mmu_private = len;
inode->i_mtime = inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
mutex_unlock(&inode->i_mutex);
return err;
}
#endif
/*2013-05-02 Hyoungtaek-Lim[hyoungtaek.lim@lge.com)[g2/vmware/vzw,att]VMware Switch [END]*/
/*
* New FAT inode stuff. We do the following:
* a) i_ino is constant and has nothing with on-disk location.
* b) FAT manages its own cache of directory entries.
* c) *This* cache is indexed by on-disk location.
* d) inode has an associated directory entry, all right, but
* it may be unhashed.
* e) currently entries are stored within struct inode. That should
* change.
* f) we deal with races in the following way:
* 1. readdir() and lookup() do FAT-dir-cache lookup.
* 2. rename() unhashes the F-d-c entry and rehashes it in
* a new place.
* 3. unlink() and rmdir() unhash F-d-c entry.
* 4. fat_write_inode() checks whether the thing is unhashed.
* If it is we silently return. If it isn't we do bread(),
* check if the location is still valid and retry if it
* isn't. Otherwise we do changes.
* 5. Spinlock is used to protect hash/unhash/location check/lookup
* 6. fat_evict_inode() unhashes the F-d-c entry.
* 7. lookup() and readdir() do igrab() if they find a F-d-c entry
* and consider negative result as cache miss.
*/
static void fat_hash_init(struct super_block *sb)
{
struct msdos_sb_info *sbi = MSDOS_SB(sb);
int i;
spin_lock_init(&sbi->inode_hash_lock);
for (i = 0; i < FAT_HASH_SIZE; i++)
INIT_HLIST_HEAD(&sbi->inode_hashtable[i]);
}
static inline unsigned long fat_hash(loff_t i_pos)
{
return hash_32(i_pos, FAT_HASH_BITS);
}
void fat_attach(struct inode *inode, loff_t i_pos)
{
struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
struct hlist_head *head = sbi->inode_hashtable + fat_hash(i_pos);
spin_lock(&sbi->inode_hash_lock);
MSDOS_I(inode)->i_pos = i_pos;
hlist_add_head(&MSDOS_I(inode)->i_fat_hash, head);
spin_unlock(&sbi->inode_hash_lock);
}
EXPORT_SYMBOL_GPL(fat_attach);
void fat_detach(struct inode *inode)
{
struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
spin_lock(&sbi->inode_hash_lock);
MSDOS_I(inode)->i_pos = 0;
hlist_del_init(&MSDOS_I(inode)->i_fat_hash);
spin_unlock(&sbi->inode_hash_lock);
}
EXPORT_SYMBOL_GPL(fat_detach);
struct inode *fat_iget(struct super_block *sb, loff_t i_pos)
{
struct msdos_sb_info *sbi = MSDOS_SB(sb);
struct hlist_head *head = sbi->inode_hashtable + fat_hash(i_pos);
struct hlist_node *_p;
struct msdos_inode_info *i;
struct inode *inode = NULL;
spin_lock(&sbi->inode_hash_lock);
hlist_for_each_entry(i, _p, head, i_fat_hash) {
BUG_ON(i->vfs_inode.i_sb != sb);
if (i->i_pos != i_pos)
continue;
inode = igrab(&i->vfs_inode);
if (inode)
break;
}
spin_unlock(&sbi->inode_hash_lock);
return inode;
}
static int is_exec(unsigned char *extension)
{
unsigned char *exe_extensions = "EXECOMBAT", *walk;
for (walk = exe_extensions; *walk; walk += 3)
if (!strncmp(extension, walk, 3))
return 1;
return 0;
}
static int fat_calc_dir_size(struct inode *inode)
{
struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
int ret, fclus, dclus;
inode->i_size = 0;
if (MSDOS_I(inode)->i_start == 0)
return 0;
ret = fat_get_cluster(inode, FAT_ENT_EOF, &fclus, &dclus);
if (ret < 0)
return ret;
inode->i_size = (fclus + 1) << sbi->cluster_bits;
return 0;
}
/* doesn't deal with root inode */
static int fat_fill_inode(struct inode *inode, struct msdos_dir_entry *de)
{
struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
int error;
MSDOS_I(inode)->i_pos = 0;
inode->i_uid = sbi->options.fs_uid;
inode->i_gid = sbi->options.fs_gid;
inode->i_version++;
inode->i_generation = get_seconds();
if ((de->attr & ATTR_DIR) && !IS_FREE(de->name)) {
inode->i_generation &= ~1;
inode->i_mode = fat_make_mode(sbi, de->attr, S_IRWXUGO);
inode->i_op = sbi->dir_ops;
inode->i_fop = &fat_dir_operations;
MSDOS_I(inode)->i_start = le16_to_cpu(de->start);
if (sbi->fat_bits == 32)
MSDOS_I(inode)->i_start |= (le16_to_cpu(de->starthi) << 16);
MSDOS_I(inode)->i_logstart = MSDOS_I(inode)->i_start;
error = fat_calc_dir_size(inode);
if (error < 0)
return error;
MSDOS_I(inode)->mmu_private = inode->i_size;
set_nlink(inode, fat_subdirs(inode));
} else { /* not a directory */
inode->i_generation |= 1;
inode->i_mode = fat_make_mode(sbi, de->attr,
((sbi->options.showexec && !is_exec(de->name + 8))
? S_IRUGO|S_IWUGO : S_IRWXUGO));
MSDOS_I(inode)->i_start = le16_to_cpu(de->start);
if (sbi->fat_bits == 32)
MSDOS_I(inode)->i_start |= (le16_to_cpu(de->starthi) << 16);
MSDOS_I(inode)->i_logstart = MSDOS_I(inode)->i_start;
inode->i_size = le32_to_cpu(de->size);
inode->i_op = &fat_file_inode_operations;
inode->i_fop = &fat_file_operations;
inode->i_mapping->a_ops = &fat_aops;
MSDOS_I(inode)->mmu_private = inode->i_size;
}
if (de->attr & ATTR_SYS) {
if (sbi->options.sys_immutable)
inode->i_flags |= S_IMMUTABLE;
}
fat_save_attrs(inode, de->attr);
inode->i_blocks = ((inode->i_size + (sbi->cluster_size - 1))
& ~((loff_t)sbi->cluster_size - 1)) >> 9;
fat_time_fat2unix(sbi, &inode->i_mtime, de->time, de->date, 0);
if (sbi->options.isvfat) {
fat_time_fat2unix(sbi, &inode->i_ctime, de->ctime,
de->cdate, de->ctime_cs);
fat_time_fat2unix(sbi, &inode->i_atime, 0, de->adate, 0);
} else
inode->i_ctime = inode->i_atime = inode->i_mtime;
return 0;
}
struct inode *fat_build_inode(struct super_block *sb,
struct msdos_dir_entry *de, loff_t i_pos)
{
struct inode *inode;
int err;
inode = fat_iget(sb, i_pos);
if (inode)
goto out;
inode = new_inode(sb);
if (!inode) {
inode = ERR_PTR(-ENOMEM);
goto out;
}
inode->i_ino = iunique(sb, MSDOS_ROOT_INO);
inode->i_version = 1;
err = fat_fill_inode(inode, de);
if (err) {
iput(inode);
inode = ERR_PTR(err);
goto out;
}
fat_attach(inode, i_pos);
insert_inode_hash(inode);
out:
return inode;
}
EXPORT_SYMBOL_GPL(fat_build_inode);
static void fat_evict_inode(struct inode *inode)
{
truncate_inode_pages(&inode->i_data, 0);
if (!inode->i_nlink) {
inode->i_size = 0;
fat_truncate_blocks(inode, 0);
}
invalidate_inode_buffers(inode);
end_writeback(inode);
fat_cache_inval_inode(inode);
fat_detach(inode);
}
static void fat_write_super(struct super_block *sb)
{
lock_super(sb);
sb->s_dirt = 0;
if (!(sb->s_flags & MS_RDONLY))
fat_clusters_flush(sb);
unlock_super(sb);
}
static int fat_sync_fs(struct super_block *sb, int wait)
{
int err = 0;
if (sb->s_dirt) {
lock_super(sb);
sb->s_dirt = 0;
err = fat_clusters_flush(sb);
unlock_super(sb);
}
return err;
}
static void fat_put_super(struct super_block *sb)
{
struct msdos_sb_info *sbi = MSDOS_SB(sb);
if (sb->s_dirt)
fat_write_super(sb);
iput(sbi->fat_inode);
unload_nls(sbi->nls_disk);
unload_nls(sbi->nls_io);
if (sbi->options.iocharset != fat_default_iocharset)
kfree(sbi->options.iocharset);
sb->s_fs_info = NULL;
kfree(sbi);
}
static struct kmem_cache *fat_inode_cachep;
static struct inode *fat_alloc_inode(struct super_block *sb)
{
struct msdos_inode_info *ei;
ei = kmem_cache_alloc(fat_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
init_rwsem(&ei->truncate_lock);
return &ei->vfs_inode;
}
static void fat_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(fat_inode_cachep, MSDOS_I(inode));
}
static void fat_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, fat_i_callback);
}
static void init_once(void *foo)
{
struct msdos_inode_info *ei = (struct msdos_inode_info *)foo;
spin_lock_init(&ei->cache_lru_lock);
ei->nr_caches = 0;
ei->cache_valid_id = FAT_CACHE_VALID + 1;
INIT_LIST_HEAD(&ei->cache_lru);
INIT_HLIST_NODE(&ei->i_fat_hash);
inode_init_once(&ei->vfs_inode);
}
static int __init fat_init_inodecache(void)
{
fat_inode_cachep = kmem_cache_create("fat_inode_cache",
sizeof(struct msdos_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
init_once);
if (fat_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void __exit fat_destroy_inodecache(void)
{
kmem_cache_destroy(fat_inode_cachep);
}
static int fat_remount(struct super_block *sb, int *flags, char *data)
{
struct msdos_sb_info *sbi = MSDOS_SB(sb);
*flags |= MS_NODIRATIME | (sbi->options.isvfat ? 0 : MS_NOATIME);
return 0;
}
static int fat_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
/* If the count of free cluster is still unknown, counts it here. */
if (sbi->free_clusters == -1 || !sbi->free_clus_valid) {
int err = fat_count_free_clusters(dentry->d_sb);
if (err)
return err;
}
buf->f_type = dentry->d_sb->s_magic;
buf->f_bsize = sbi->cluster_size;
buf->f_blocks = sbi->max_cluster - FAT_START_ENT;
buf->f_bfree = sbi->free_clusters;
buf->f_bavail = sbi->free_clusters;
buf->f_fsid.val[0] = (u32)id;
buf->f_fsid.val[1] = (u32)(id >> 32);
buf->f_namelen =
(sbi->options.isvfat ? FAT_LFN_LEN : 12) * NLS_MAX_CHARSET_SIZE;
return 0;
}
static inline loff_t fat_i_pos_read(struct msdos_sb_info *sbi,
struct inode *inode)
{
loff_t i_pos;
#if BITS_PER_LONG == 32
spin_lock(&sbi->inode_hash_lock);
#endif
i_pos = MSDOS_I(inode)->i_pos;
#if BITS_PER_LONG == 32
spin_unlock(&sbi->inode_hash_lock);
#endif
return i_pos;
}
static int __fat_write_inode(struct inode *inode, int wait)
{
struct super_block *sb = inode->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
struct buffer_head *bh;
struct msdos_dir_entry *raw_entry;
loff_t i_pos;
int err;
if (inode->i_ino == MSDOS_ROOT_INO)
return 0;
retry:
i_pos = fat_i_pos_read(sbi, inode);
if (!i_pos)
return 0;
bh = sb_bread(sb, i_pos >> sbi->dir_per_block_bits);
if (!bh) {
fat_msg(sb, KERN_ERR, "unable to read inode block "
"for updating (i_pos %lld)", i_pos);
return -EIO;
}
spin_lock(&sbi->inode_hash_lock);
if (i_pos != MSDOS_I(inode)->i_pos) {
spin_unlock(&sbi->inode_hash_lock);
brelse(bh);
goto retry;
}
raw_entry = &((struct msdos_dir_entry *) (bh->b_data))
[i_pos & (sbi->dir_per_block - 1)];
if (S_ISDIR(inode->i_mode))
raw_entry->size = 0;
else
raw_entry->size = cpu_to_le32(inode->i_size);
raw_entry->attr = fat_make_attrs(inode);
raw_entry->start = cpu_to_le16(MSDOS_I(inode)->i_logstart);
raw_entry->starthi = cpu_to_le16(MSDOS_I(inode)->i_logstart >> 16);
fat_time_unix2fat(sbi, &inode->i_mtime, &raw_entry->time,
&raw_entry->date, NULL);
if (sbi->options.isvfat) {
__le16 atime;
fat_time_unix2fat(sbi, &inode->i_ctime, &raw_entry->ctime,
&raw_entry->cdate, &raw_entry->ctime_cs);
fat_time_unix2fat(sbi, &inode->i_atime, &atime,
&raw_entry->adate, NULL);
}
spin_unlock(&sbi->inode_hash_lock);
mark_buffer_dirty(bh);
err = 0;
if (wait)
err = sync_dirty_buffer(bh);
brelse(bh);
return err;
}
static int fat_write_inode(struct inode *inode, struct writeback_control *wbc)
{
return __fat_write_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
}
int fat_sync_inode(struct inode *inode)
{
return __fat_write_inode(inode, 1);
}
EXPORT_SYMBOL_GPL(fat_sync_inode);
static int fat_show_options(struct seq_file *m, struct dentry *root);
static const struct super_operations fat_sops = {
.alloc_inode = fat_alloc_inode,
.destroy_inode = fat_destroy_inode,
.write_inode = fat_write_inode,
.evict_inode = fat_evict_inode,
.put_super = fat_put_super,
.write_super = fat_write_super,
.sync_fs = fat_sync_fs,
.statfs = fat_statfs,
.remount_fs = fat_remount,
.show_options = fat_show_options,
};
/*
* a FAT file handle with fhtype 3 is
* 0/ i_ino - for fast, reliable lookup if still in the cache
* 1/ i_generation - to see if i_ino is still valid
* bit 0 == 0 iff directory
* 2/ i_pos(8-39) - if ino has changed, but still in cache
* 3/ i_pos(4-7)|i_logstart - to semi-verify inode found at i_pos
* 4/ i_pos(0-3)|parent->i_logstart - maybe used to hunt for the file on disc
*
* Hack for NFSv2: Maximum FAT entry number is 28bits and maximum
* i_pos is 40bits (blocknr(32) + dir offset(8)), so two 4bits
* of i_logstart is used to store the directory entry offset.
*/
static struct dentry *fat_fh_to_dentry(struct super_block *sb,
struct fid *fid, int fh_len, int fh_type)
{
struct inode *inode = NULL;
u32 *fh = fid->raw;
if (fh_len < 5 || fh_type != 3)
return NULL;
inode = ilookup(sb, fh[0]);
if (!inode || inode->i_generation != fh[1]) {
if (inode)
iput(inode);
inode = NULL;
}
if (!inode) {
loff_t i_pos;
int i_logstart = fh[3] & 0x0fffffff;
i_pos = (loff_t)fh[2] << 8;
i_pos |= ((fh[3] >> 24) & 0xf0) | (fh[4] >> 28);
/* try 2 - see if i_pos is in F-d-c
* require i_logstart to be the same
* Will fail if you truncate and then re-write
*/
inode = fat_iget(sb, i_pos);
if (inode && MSDOS_I(inode)->i_logstart != i_logstart) {
iput(inode);
inode = NULL;
}
}
/*
* For now, do nothing if the inode is not found.
*
* What we could do is:
*
* - follow the file starting at fh[4], and record the ".." entry,
* and the name of the fh[2] entry.
* - then follow the ".." file finding the next step up.
*
* This way we build a path to the root of the tree. If this works, we
* lookup the path and so get this inode into the cache. Finally try
* the fat_iget lookup again. If that fails, then we are totally out
* of luck. But all that is for another day
*/
return d_obtain_alias(inode);
}
static int
fat_encode_fh(struct dentry *de, __u32 *fh, int *lenp, int connectable)
{
int len = *lenp;
struct inode *inode = de->d_inode;
u32 ipos_h, ipos_m, ipos_l;
if (len < 5) {
*lenp = 5;
return 255; /* no room */
}
ipos_h = MSDOS_I(inode)->i_pos >> 8;
ipos_m = (MSDOS_I(inode)->i_pos & 0xf0) << 24;
ipos_l = (MSDOS_I(inode)->i_pos & 0x0f) << 28;
*lenp = 5;
fh[0] = inode->i_ino;
fh[1] = inode->i_generation;
fh[2] = ipos_h;
fh[3] = ipos_m | MSDOS_I(inode)->i_logstart;
spin_lock(&de->d_lock);
fh[4] = ipos_l | MSDOS_I(de->d_parent->d_inode)->i_logstart;
spin_unlock(&de->d_lock);
return 3;
}
static struct dentry *fat_get_parent(struct dentry *child)
{
struct super_block *sb = child->d_sb;
struct buffer_head *bh;
struct msdos_dir_entry *de;
loff_t i_pos;
struct dentry *parent;
struct inode *inode;
int err;
lock_super(sb);
err = fat_get_dotdot_entry(child->d_inode, &bh, &de, &i_pos);
if (err) {
parent = ERR_PTR(err);
goto out;
}
inode = fat_build_inode(sb, de, i_pos);
brelse(bh);
parent = d_obtain_alias(inode);
out:
unlock_super(sb);
return parent;
}
static const struct export_operations fat_export_ops = {
.encode_fh = fat_encode_fh,
.fh_to_dentry = fat_fh_to_dentry,
.get_parent = fat_get_parent,
};
static int fat_show_options(struct seq_file *m, struct dentry *root)
{
struct msdos_sb_info *sbi = MSDOS_SB(root->d_sb);
struct fat_mount_options *opts = &sbi->options;
int isvfat = opts->isvfat;
if (opts->fs_uid != 0)
seq_printf(m, ",uid=%u", opts->fs_uid);
if (opts->fs_gid != 0)
seq_printf(m, ",gid=%u", opts->fs_gid);
seq_printf(m, ",fmask=%04o", opts->fs_fmask);
seq_printf(m, ",dmask=%04o", opts->fs_dmask);
if (opts->allow_utime)
seq_printf(m, ",allow_utime=%04o", opts->allow_utime);
if (sbi->nls_disk)
seq_printf(m, ",codepage=%s", sbi->nls_disk->charset);
if (isvfat) {
if (sbi->nls_io)
seq_printf(m, ",iocharset=%s", sbi->nls_io->charset);
switch (opts->shortname) {
case VFAT_SFN_DISPLAY_WIN95 | VFAT_SFN_CREATE_WIN95:
seq_puts(m, ",shortname=win95");
break;
case VFAT_SFN_DISPLAY_WINNT | VFAT_SFN_CREATE_WINNT:
seq_puts(m, ",shortname=winnt");
break;
case VFAT_SFN_DISPLAY_WINNT | VFAT_SFN_CREATE_WIN95:
seq_puts(m, ",shortname=mixed");
break;
case VFAT_SFN_DISPLAY_LOWER | VFAT_SFN_CREATE_WIN95:
seq_puts(m, ",shortname=lower");
break;
default:
seq_puts(m, ",shortname=unknown");
break;
}
}
if (opts->name_check != 'n')
seq_printf(m, ",check=%c", opts->name_check);
if (opts->usefree)
seq_puts(m, ",usefree");
if (opts->quiet)
seq_puts(m, ",quiet");
if (opts->showexec)
seq_puts(m, ",showexec");
if (opts->sys_immutable)
seq_puts(m, ",sys_immutable");
if (!isvfat) {
if (opts->dotsOK)
seq_puts(m, ",dotsOK=yes");
if (opts->nocase)
seq_puts(m, ",nocase");
} else {
if (opts->utf8)
seq_puts(m, ",utf8");
if (opts->unicode_xlate)
seq_puts(m, ",uni_xlate");
if (!opts->numtail)
seq_puts(m, ",nonumtail");
if (opts->rodir)
seq_puts(m, ",rodir");
}
if (opts->flush)
seq_puts(m, ",flush");
if (opts->tz_utc)
seq_puts(m, ",tz=UTC");
if (opts->errors == FAT_ERRORS_CONT)
seq_puts(m, ",errors=continue");
else if (opts->errors == FAT_ERRORS_PANIC)
seq_puts(m, ",errors=panic");
else
seq_puts(m, ",errors=remount-ro");
if (opts->discard)
seq_puts(m, ",discard");
return 0;
}
enum {
Opt_check_n, Opt_check_r, Opt_check_s, Opt_uid, Opt_gid,
Opt_umask, Opt_dmask, Opt_fmask, Opt_allow_utime, Opt_codepage,
Opt_usefree, Opt_nocase, Opt_quiet, Opt_showexec, Opt_debug,
Opt_immutable, Opt_dots, Opt_nodots,
Opt_charset, Opt_shortname_lower, Opt_shortname_win95,
Opt_shortname_winnt, Opt_shortname_mixed, Opt_utf8_no, Opt_utf8_yes,
Opt_uni_xl_no, Opt_uni_xl_yes, Opt_nonumtail_no, Opt_nonumtail_yes,
Opt_obsolete, Opt_flush, Opt_tz_utc, Opt_rodir, Opt_err_cont,
Opt_err_panic, Opt_err_ro, Opt_discard, Opt_err,
};
static const match_table_t fat_tokens = {
{Opt_check_r, "check=relaxed"},
{Opt_check_s, "check=strict"},
{Opt_check_n, "check=normal"},
{Opt_check_r, "check=r"},
{Opt_check_s, "check=s"},
{Opt_check_n, "check=n"},
{Opt_uid, "uid=%u"},
{Opt_gid, "gid=%u"},
{Opt_umask, "umask=%o"},
{Opt_dmask, "dmask=%o"},
{Opt_fmask, "fmask=%o"},
{Opt_allow_utime, "allow_utime=%o"},
{Opt_codepage, "codepage=%u"},
{Opt_usefree, "usefree"},
{Opt_nocase, "nocase"},
{Opt_quiet, "quiet"},
{Opt_showexec, "showexec"},
{Opt_debug, "debug"},
{Opt_immutable, "sys_immutable"},
{Opt_flush, "flush"},
{Opt_tz_utc, "tz=UTC"},
{Opt_err_cont, "errors=continue"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_discard, "discard"},
{Opt_obsolete, "conv=binary"},
{Opt_obsolete, "conv=text"},
{Opt_obsolete, "conv=auto"},
{Opt_obsolete, "conv=b"},
{Opt_obsolete, "conv=t"},
{Opt_obsolete, "conv=a"},
{Opt_obsolete, "fat=%u"},
{Opt_obsolete, "blocksize=%u"},
{Opt_obsolete, "cvf_format=%20s"},
{Opt_obsolete, "cvf_options=%100s"},
{Opt_obsolete, "posix"},
{Opt_err, NULL},
};
static const match_table_t msdos_tokens = {
{Opt_nodots, "nodots"},
{Opt_nodots, "dotsOK=no"},
{Opt_dots, "dots"},
{Opt_dots, "dotsOK=yes"},
{Opt_err, NULL}
};
static const match_table_t vfat_tokens = {
{Opt_charset, "iocharset=%s"},
{Opt_shortname_lower, "shortname=lower"},
{Opt_shortname_win95, "shortname=win95"},
{Opt_shortname_winnt, "shortname=winnt"},
{Opt_shortname_mixed, "shortname=mixed"},
{Opt_utf8_no, "utf8=0"}, /* 0 or no or false */
{Opt_utf8_no, "utf8=no"},
{Opt_utf8_no, "utf8=false"},
{Opt_utf8_yes, "utf8=1"}, /* empty or 1 or yes or true */
{Opt_utf8_yes, "utf8=yes"},
{Opt_utf8_yes, "utf8=true"},
{Opt_utf8_yes, "utf8"},
{Opt_uni_xl_no, "uni_xlate=0"}, /* 0 or no or false */
{Opt_uni_xl_no, "uni_xlate=no"},
{Opt_uni_xl_no, "uni_xlate=false"},
{Opt_uni_xl_yes, "uni_xlate=1"}, /* empty or 1 or yes or true */
{Opt_uni_xl_yes, "uni_xlate=yes"},
{Opt_uni_xl_yes, "uni_xlate=true"},
{Opt_uni_xl_yes, "uni_xlate"},
{Opt_nonumtail_no, "nonumtail=0"}, /* 0 or no or false */
{Opt_nonumtail_no, "nonumtail=no"},
{Opt_nonumtail_no, "nonumtail=false"},
{Opt_nonumtail_yes, "nonumtail=1"}, /* empty or 1 or yes or true */
{Opt_nonumtail_yes, "nonumtail=yes"},
{Opt_nonumtail_yes, "nonumtail=true"},
{Opt_nonumtail_yes, "nonumtail"},
{Opt_rodir, "rodir"},
{Opt_err, NULL}
};
static int parse_options(struct super_block *sb, char *options, int is_vfat,
int silent, int *debug, struct fat_mount_options *opts)
{
char *p;
substring_t args[MAX_OPT_ARGS];
int option;
char *iocharset;
opts->isvfat = is_vfat;
opts->fs_uid = current_uid();
opts->fs_gid = current_gid();
opts->fs_fmask = opts->fs_dmask = current_umask();
opts->allow_utime = -1;
opts->codepage = fat_default_codepage;
opts->iocharset = fat_default_iocharset;
if (is_vfat) {
opts->shortname = VFAT_SFN_DISPLAY_WINNT|VFAT_SFN_CREATE_WIN95;
opts->rodir = 0;
} else {
opts->shortname = 0;
opts->rodir = 1;
}
opts->name_check = 'n';
opts->quiet = opts->showexec = opts->sys_immutable = opts->dotsOK = 0;
opts->utf8 = opts->unicode_xlate = 0;
opts->numtail = 1;
opts->usefree = opts->nocase = 0;
opts->tz_utc = 0;
opts->errors = FAT_ERRORS_RO;
*debug = 0;
if (!options)
goto out;
while ((p = strsep(&options, ",")) != NULL) {
int token;
if (!*p)
continue;
token = match_token(p, fat_tokens, args);
if (token == Opt_err) {
if (is_vfat)
token = match_token(p, vfat_tokens, args);
else
token = match_token(p, msdos_tokens, args);
}
switch (token) {
case Opt_check_s:
opts->name_check = 's';
break;
case Opt_check_r:
opts->name_check = 'r';
break;
case Opt_check_n:
opts->name_check = 'n';
break;
case Opt_usefree:
opts->usefree = 1;
break;
case Opt_nocase:
if (!is_vfat)
opts->nocase = 1;
else {
/* for backward compatibility */
opts->shortname = VFAT_SFN_DISPLAY_WIN95
| VFAT_SFN_CREATE_WIN95;
}
break;
case Opt_quiet:
opts->quiet = 1;
break;
case Opt_showexec:
opts->showexec = 1;
break;
case Opt_debug:
*debug = 1;
break;
case Opt_immutable:
opts->sys_immutable = 1;
break;
case Opt_uid:
if (match_int(&args[0], &option))
return 0;
opts->fs_uid = option;
break;
case Opt_gid:
if (match_int(&args[0], &option))
return 0;
opts->fs_gid = option;
break;
case Opt_umask:
if (match_octal(&args[0], &option))
return 0;
opts->fs_fmask = opts->fs_dmask = option;
break;
case Opt_dmask:
if (match_octal(&args[0], &option))
return 0;
opts->fs_dmask = option;
break;
case Opt_fmask:
if (match_octal(&args[0], &option))
return 0;
opts->fs_fmask = option;
break;
case Opt_allow_utime:
if (match_octal(&args[0], &option))
return 0;
opts->allow_utime = option & (S_IWGRP | S_IWOTH);
break;
case Opt_codepage:
if (match_int(&args[0], &option))
return 0;
opts->codepage = option;
break;
case Opt_flush:
opts->flush = 1;
break;
case Opt_tz_utc:
opts->tz_utc = 1;
break;
case Opt_err_cont:
opts->errors = FAT_ERRORS_CONT;
break;
case Opt_err_panic:
opts->errors = FAT_ERRORS_PANIC;
break;
case Opt_err_ro:
opts->errors = FAT_ERRORS_RO;
break;
/* msdos specific */
case Opt_dots:
opts->dotsOK = 1;
break;
case Opt_nodots:
opts->dotsOK = 0;
break;
/* vfat specific */
case Opt_charset:
if (opts->iocharset != fat_default_iocharset)
kfree(opts->iocharset);
iocharset = match_strdup(&args[0]);
if (!iocharset)
return -ENOMEM;
opts->iocharset = iocharset;
break;
case Opt_shortname_lower:
opts->shortname = VFAT_SFN_DISPLAY_LOWER
| VFAT_SFN_CREATE_WIN95;
break;
case Opt_shortname_win95:
opts->shortname = VFAT_SFN_DISPLAY_WIN95
| VFAT_SFN_CREATE_WIN95;
break;
case Opt_shortname_winnt:
opts->shortname = VFAT_SFN_DISPLAY_WINNT
| VFAT_SFN_CREATE_WINNT;
break;
case Opt_shortname_mixed:
opts->shortname = VFAT_SFN_DISPLAY_WINNT
| VFAT_SFN_CREATE_WIN95;
break;
case Opt_utf8_no: /* 0 or no or false */
opts->utf8 = 0;
break;
case Opt_utf8_yes: /* empty or 1 or yes or true */
opts->utf8 = 1;
break;
case Opt_uni_xl_no: /* 0 or no or false */
opts->unicode_xlate = 0;
break;
case Opt_uni_xl_yes: /* empty or 1 or yes or true */
opts->unicode_xlate = 1;
break;
case Opt_nonumtail_no: /* 0 or no or false */
opts->numtail = 1; /* negated option */
break;
case Opt_nonumtail_yes: /* empty or 1 or yes or true */
opts->numtail = 0; /* negated option */
break;
case Opt_rodir:
opts->rodir = 1;
break;
case Opt_discard:
opts->discard = 1;
break;
/* obsolete mount options */
case Opt_obsolete:
fat_msg(sb, KERN_INFO, "\"%s\" option is obsolete, "
"not supported now", p);
break;
/* unknown option */
default:
if (!silent) {
fat_msg(sb, KERN_ERR,
"Unrecognized mount option \"%s\" "
"or missing value", p);
}
return -EINVAL;
}
}
out:
/* UTF-8 doesn't provide FAT semantics */
if (!strcmp(opts->iocharset, "utf8")) {
fat_msg(sb, KERN_WARNING, "utf8 is not a recommended IO charset"
" for FAT filesystems, filesystem will be "
"case sensitive!");
}
/* If user doesn't specify allow_utime, it's initialized from dmask. */
if (opts->allow_utime == (unsigned short)-1)
opts->allow_utime = ~opts->fs_dmask & (S_IWGRP | S_IWOTH);
if (opts->unicode_xlate)
opts->utf8 = 0;
return 0;
}
static int fat_read_root(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
int error;
MSDOS_I(inode)->i_pos = 0;
inode->i_uid = sbi->options.fs_uid;
inode->i_gid = sbi->options.fs_gid;
inode->i_version++;
inode->i_generation = 0;
inode->i_mode = fat_make_mode(sbi, ATTR_DIR, S_IRWXUGO);
inode->i_op = sbi->dir_ops;
inode->i_fop = &fat_dir_operations;
if (sbi->fat_bits == 32) {
MSDOS_I(inode)->i_start = sbi->root_cluster;
error = fat_calc_dir_size(inode);
if (error < 0)
return error;
} else {
MSDOS_I(inode)->i_start = 0;
inode->i_size = sbi->dir_entries * sizeof(struct msdos_dir_entry);
}
inode->i_blocks = ((inode->i_size + (sbi->cluster_size - 1))
& ~((loff_t)sbi->cluster_size - 1)) >> 9;
MSDOS_I(inode)->i_logstart = 0;
MSDOS_I(inode)->mmu_private = inode->i_size;
fat_save_attrs(inode, ATTR_DIR);
inode->i_mtime.tv_sec = inode->i_atime.tv_sec = inode->i_ctime.tv_sec = 0;
inode->i_mtime.tv_nsec = inode->i_atime.tv_nsec = inode->i_ctime.tv_nsec = 0;
set_nlink(inode, fat_subdirs(inode)+2);
return 0;
}
static unsigned long calc_fat_clusters(struct super_block *sb)
{
struct msdos_sb_info *sbi = MSDOS_SB(sb);
/* Divide first to avoid overflow */
if (sbi->fat_bits != 12) {
unsigned long ent_per_sec = sb->s_blocksize * 8 / sbi->fat_bits;
return ent_per_sec * sbi->fat_length;
}
return sbi->fat_length * sb->s_blocksize * 8 / sbi->fat_bits;
}
/*
* Read the super block of an MS-DOS FS.
*/
int fat_fill_super(struct super_block *sb, void *data, int silent, int isvfat,
void (*setup)(struct super_block *))
{
struct inode *root_inode = NULL, *fat_inode = NULL;
struct buffer_head *bh;
struct fat_boot_sector *b;
struct fat_boot_bsx *bsx;
struct msdos_sb_info *sbi;
u16 logical_sector_size;
u32 total_sectors, total_clusters, fat_clusters, rootdir_sectors;
int debug;
unsigned int media;
long error;
char buf[50];
/*
* GFP_KERNEL is ok here, because while we do hold the
* supeblock lock, memory pressure can't call back into
* the filesystem, since we're only just about to mount
* it and have no inodes etc active!
*/
sbi = kzalloc(sizeof(struct msdos_sb_info), GFP_KERNEL);
if (!sbi)
return -ENOMEM;
sb->s_fs_info = sbi;
sb->s_flags |= MS_NODIRATIME;
sb->s_magic = MSDOS_SUPER_MAGIC;
sb->s_op = &fat_sops;
sb->s_export_op = &fat_export_ops;
ratelimit_state_init(&sbi->ratelimit, DEFAULT_RATELIMIT_INTERVAL,
DEFAULT_RATELIMIT_BURST);
error = parse_options(sb, data, isvfat, silent, &debug, &sbi->options);
if (error)
goto out_fail;
setup(sb); /* flavour-specific stuff that needs options */
error = -EIO;
sb_min_blocksize(sb, 512);
bh = sb_bread(sb, 0);
if (bh == NULL) {
fat_msg(sb, KERN_ERR, "unable to read boot sector");
goto out_fail;
}
b = (struct fat_boot_sector *) bh->b_data;
if (!b->reserved) {
if (!silent)
fat_msg(sb, KERN_ERR, "bogus number of reserved sectors");
brelse(bh);
goto out_invalid;
}
if (!b->fats) {
if (!silent)
fat_msg(sb, KERN_ERR, "bogus number of FAT structure");
brelse(bh);
goto out_invalid;
}
/*
* Earlier we checked here that b->secs_track and b->head are nonzero,
* but it turns out valid FAT filesystems can have zero there.
*/
media = b->media;
if (!fat_valid_media(media)) {
if (!silent)
fat_msg(sb, KERN_ERR, "invalid media value (0x%02x)",
media);
brelse(bh);
goto out_invalid;
}
logical_sector_size = get_unaligned_le16(&b->sector_size);
if (!is_power_of_2(logical_sector_size)
|| (logical_sector_size < 512)
|| (logical_sector_size > 4096)) {
if (!silent)
fat_msg(sb, KERN_ERR, "bogus logical sector size %u",
logical_sector_size);
brelse(bh);
goto out_invalid;
}
sbi->sec_per_clus = b->sec_per_clus;
if (!is_power_of_2(sbi->sec_per_clus)) {
if (!silent)
fat_msg(sb, KERN_ERR, "bogus sectors per cluster %u",
sbi->sec_per_clus);
brelse(bh);
goto out_invalid;
}
if (logical_sector_size < sb->s_blocksize) {
fat_msg(sb, KERN_ERR, "logical sector size too small for device"
" (logical sector size = %u)", logical_sector_size);
brelse(bh);
goto out_fail;
}
if (logical_sector_size > sb->s_blocksize) {
brelse(bh);
if (!sb_set_blocksize(sb, logical_sector_size)) {
fat_msg(sb, KERN_ERR, "unable to set blocksize %u",
logical_sector_size);
goto out_fail;
}
bh = sb_bread(sb, 0);
if (bh == NULL) {
fat_msg(sb, KERN_ERR, "unable to read boot sector"
" (logical sector size = %lu)",
sb->s_blocksize);
goto out_fail;
}
b = (struct fat_boot_sector *) bh->b_data;
}
sbi->cluster_size = sb->s_blocksize * sbi->sec_per_clus;
sbi->cluster_bits = ffs(sbi->cluster_size) - 1;
sbi->fats = b->fats;
sbi->fat_bits = 0; /* Don't know yet */
sbi->fat_start = le16_to_cpu(b->reserved);
sbi->fat_length = le16_to_cpu(b->fat_length);
sbi->root_cluster = 0;
sbi->free_clusters = -1; /* Don't know yet */
sbi->free_clus_valid = 0;
sbi->prev_free = FAT_START_ENT;
sb->s_maxbytes = 0xffffffff;
if (!sbi->fat_length && b->fat32_length) {
struct fat_boot_fsinfo *fsinfo;
struct buffer_head *fsinfo_bh;
/* Must be FAT32 */
sbi->fat_bits = 32;
sbi->fat_length = le32_to_cpu(b->fat32_length);
sbi->root_cluster = le32_to_cpu(b->root_cluster);
/* MC - if info_sector is 0, don't multiply by 0 */
sbi->fsinfo_sector = le16_to_cpu(b->info_sector);
if (sbi->fsinfo_sector == 0)
sbi->fsinfo_sector = 1;
fsinfo_bh = sb_bread(sb, sbi->fsinfo_sector);
if (fsinfo_bh == NULL) {
fat_msg(sb, KERN_ERR, "bread failed, FSINFO block"
" (sector = %lu)", sbi->fsinfo_sector);
brelse(bh);
goto out_fail;
}
bsx = (struct fat_boot_bsx *)(bh->b_data + FAT32_BSX_OFFSET);
fsinfo = (struct fat_boot_fsinfo *)fsinfo_bh->b_data;
if (!IS_FSINFO(fsinfo)) {
fat_msg(sb, KERN_WARNING, "Invalid FSINFO signature: "
"0x%08x, 0x%08x (sector = %lu)",
le32_to_cpu(fsinfo->signature1),
le32_to_cpu(fsinfo->signature2),
sbi->fsinfo_sector);
} else {
if (sbi->options.usefree)
sbi->free_clus_valid = 1;
sbi->free_clusters = le32_to_cpu(fsinfo->free_clusters);
sbi->prev_free = le32_to_cpu(fsinfo->next_cluster);
}
brelse(fsinfo_bh);
} else {
bsx = (struct fat_boot_bsx *)(bh->b_data + FAT16_BSX_OFFSET);
}
/* interpret volume ID as a little endian 32 bit integer */
sbi->vol_id = (((u32)bsx->vol_id[0]) | ((u32)bsx->vol_id[1] << 8) |
((u32)bsx->vol_id[2] << 16) | ((u32)bsx->vol_id[3] << 24));
sbi->dir_per_block = sb->s_blocksize / sizeof(struct msdos_dir_entry);
sbi->dir_per_block_bits = ffs(sbi->dir_per_block) - 1;
sbi->dir_start = sbi->fat_start + sbi->fats * sbi->fat_length;
sbi->dir_entries = get_unaligned_le16(&b->dir_entries);
if (sbi->dir_entries & (sbi->dir_per_block - 1)) {
if (!silent)
fat_msg(sb, KERN_ERR, "bogus directroy-entries per block"
" (%u)", sbi->dir_entries);
brelse(bh);
goto out_invalid;
}
rootdir_sectors = sbi->dir_entries
* sizeof(struct msdos_dir_entry) / sb->s_blocksize;
sbi->data_start = sbi->dir_start + rootdir_sectors;
total_sectors = get_unaligned_le16(&b->sectors);
if (total_sectors == 0)
total_sectors = le32_to_cpu(b->total_sect);
total_clusters = (total_sectors - sbi->data_start) / sbi->sec_per_clus;
if (sbi->fat_bits != 32)
sbi->fat_bits = (total_clusters > MAX_FAT12) ? 16 : 12;
/* check that FAT table does not overflow */
fat_clusters = calc_fat_clusters(sb);
total_clusters = min(total_clusters, fat_clusters - FAT_START_ENT);
if (total_clusters > MAX_FAT(sb)) {
if (!silent)
fat_msg(sb, KERN_ERR, "count of clusters too big (%u)",
total_clusters);
brelse(bh);
goto out_invalid;
}
sbi->max_cluster = total_clusters + FAT_START_ENT;
/* check the free_clusters, it's not necessarily correct */
if (sbi->free_clusters != -1 && sbi->free_clusters > total_clusters)
sbi->free_clusters = -1;
/* check the prev_free, it's not necessarily correct */
sbi->prev_free %= sbi->max_cluster;
if (sbi->prev_free < FAT_START_ENT)
sbi->prev_free = FAT_START_ENT;
brelse(bh);
/* set up enough so that it can read an inode */
fat_hash_init(sb);
fat_ent_access_init(sb);
/*
* The low byte of FAT's first entry must have same value with
* media-field. But in real world, too many devices is
* writing wrong value. So, removed that validity check.
*
* if (FAT_FIRST_ENT(sb, media) != first)
*/
error = -EINVAL;
sprintf(buf, "cp%d", sbi->options.codepage);
sbi->nls_disk = load_nls(buf);
if (!sbi->nls_disk) {
fat_msg(sb, KERN_ERR, "codepage %s not found", buf);
goto out_fail;
}
/* FIXME: utf8 is using iocharset for upper/lower conversion */
if (sbi->options.isvfat) {
sbi->nls_io = load_nls(sbi->options.iocharset);
if (!sbi->nls_io) {
fat_msg(sb, KERN_ERR, "IO charset %s not found",
sbi->options.iocharset);
goto out_fail;
}
}
error = -ENOMEM;
fat_inode = new_inode(sb);
if (!fat_inode)
goto out_fail;
MSDOS_I(fat_inode)->i_pos = 0;
sbi->fat_inode = fat_inode;
root_inode = new_inode(sb);
if (!root_inode)
goto out_fail;
root_inode->i_ino = MSDOS_ROOT_INO;
root_inode->i_version = 1;
error = fat_read_root(root_inode);
if (error < 0) {
iput(root_inode);
goto out_fail;
}
error = -ENOMEM;
insert_inode_hash(root_inode);
sb->s_root = d_make_root(root_inode);
if (!sb->s_root) {
fat_msg(sb, KERN_ERR, "get root inode failed");
goto out_fail;
}
return 0;
out_invalid:
error = -EINVAL;
if (!silent)
fat_msg(sb, KERN_INFO, "Can't find a valid FAT filesystem");
out_fail:
if (fat_inode)
iput(fat_inode);
unload_nls(sbi->nls_io);
unload_nls(sbi->nls_disk);
if (sbi->options.iocharset != fat_default_iocharset)
kfree(sbi->options.iocharset);
sb->s_fs_info = NULL;
kfree(sbi);
return error;
}
EXPORT_SYMBOL_GPL(fat_fill_super);
/*
* helper function for fat_flush_inodes. This writes both the inode
* and the file data blocks, waiting for in flight data blocks before
* the start of the call. It does not wait for any io started
* during the call
*/
static int writeback_inode(struct inode *inode)
{
int ret;
struct address_space *mapping = inode->i_mapping;
struct writeback_control wbc = {
.sync_mode = WB_SYNC_NONE,
.nr_to_write = 0,
};
/* if we used WB_SYNC_ALL, sync_inode waits for the io for the
* inode to finish. So WB_SYNC_NONE is sent down to sync_inode
* and filemap_fdatawrite is used for the data blocks
*/
ret = sync_inode(inode, &wbc);
if (!ret)
ret = filemap_fdatawrite(mapping);
return ret;
}
/*
* write data and metadata corresponding to i1 and i2. The io is
* started but we do not wait for any of it to finish.
*
* filemap_flush is used for the block device, so if there is a dirty
* page for a block already in flight, we will not wait and start the
* io over again
*/
int fat_flush_inodes(struct super_block *sb, struct inode *i1, struct inode *i2)
{
int ret = 0;
if (!MSDOS_SB(sb)->options.flush)
return 0;
if (i1)
ret = writeback_inode(i1);
if (!ret && i2)
ret = writeback_inode(i2);
if (!ret) {
struct address_space *mapping = sb->s_bdev->bd_inode->i_mapping;
ret = filemap_flush(mapping);
}
return ret;
}
EXPORT_SYMBOL_GPL(fat_flush_inodes);
static int __init init_fat_fs(void)
{
int err;
err = fat_cache_init();
if (err)
return err;
err = fat_init_inodecache();
if (err)
goto failed;
return 0;
failed:
fat_cache_destroy();
return err;
}
static void __exit exit_fat_fs(void)
{
fat_cache_destroy();
fat_destroy_inodecache();
}
module_init(init_fat_fs)
module_exit(exit_fat_fs)
MODULE_LICENSE("GPL");
| gpl-2.0 |
mjbshaw/bluez | gobex/gobex-transfer.c | 6 | 16201 | /*
*
* OBEX library with GLib integration
*
* Copyright (C) 2011 Intel Corporation. All rights reserved.
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <string.h>
#include <errno.h>
#include "gobex.h"
#include "gobex-debug.h"
#define FIRST_PACKET_TIMEOUT 60
static GSList *transfers = NULL;
static void transfer_response(GObex *obex, GError *err, GObexPacket *rsp,
gpointer user_data);
struct transfer {
guint id;
guint8 opcode;
GObex *obex;
guint req_id;
guint put_id;
guint get_id;
guint abort_id;
GObexDataProducer data_producer;
GObexDataConsumer data_consumer;
GObexFunc complete_func;
gpointer user_data;
};
static void transfer_free(struct transfer *transfer)
{
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
transfers = g_slist_remove(transfers, transfer);
if (transfer->req_id > 0)
g_obex_cancel_req(transfer->obex, transfer->req_id, TRUE);
if (transfer->put_id > 0)
g_obex_remove_request_function(transfer->obex,
transfer->put_id);
if (transfer->get_id > 0)
g_obex_remove_request_function(transfer->obex,
transfer->get_id);
if (transfer->abort_id > 0)
g_obex_remove_request_function(transfer->obex,
transfer->abort_id);
g_obex_unref(transfer->obex);
g_free(transfer);
}
static struct transfer *find_transfer(guint id)
{
GSList *l;
for (l = transfers; l != NULL; l = g_slist_next(l)) {
struct transfer *t = l->data;
if (t->id == id)
return t;
}
return NULL;
}
static void transfer_complete(struct transfer *transfer, GError *err)
{
guint id = transfer->id;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", id);
transfer->complete_func(transfer->obex, err, transfer->user_data);
/* Check if the complete_func removed the transfer */
if (find_transfer(id) == NULL)
return;
transfer_free(transfer);
}
static void transfer_abort_response(GObex *obex, GError *err, GObexPacket *rsp,
gpointer user_data)
{
struct transfer *transfer = user_data;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
transfer->req_id = 0;
/* Intentionally override error */
err = g_error_new(G_OBEX_ERROR, G_OBEX_ERROR_CANCELLED,
"Operation was aborted");
g_obex_debug(G_OBEX_DEBUG_ERROR, "%s", err->message);
transfer_complete(transfer, err);
g_error_free(err);
}
static gssize put_get_data(void *buf, gsize len, gpointer user_data)
{
struct transfer *transfer = user_data;
GObexPacket *req;
GError *err = NULL;
gssize ret;
ret = transfer->data_producer(buf, len, transfer->user_data);
if (ret == 0 || ret == -EAGAIN)
return ret;
if (ret > 0) {
/* Check if SRM is active */
if (!g_obex_srm_active(transfer->obex))
return ret;
/* Generate next packet */
req = g_obex_packet_new(transfer->opcode, FALSE,
G_OBEX_HDR_INVALID);
g_obex_packet_add_body(req, put_get_data, transfer);
transfer->req_id = g_obex_send_req(transfer->obex, req, -1,
transfer_response, transfer,
&err);
goto done;
}
req = g_obex_packet_new(G_OBEX_OP_ABORT, TRUE, G_OBEX_HDR_INVALID);
transfer->req_id = g_obex_send_req(transfer->obex, req, -1,
transfer_abort_response,
transfer, &err);
done:
if (err != NULL) {
transfer_complete(transfer, err);
g_error_free(err);
}
return ret;
}
static gboolean handle_get_body(struct transfer *transfer, GObexPacket *rsp,
GError **err)
{
GObexHeader *body = g_obex_packet_get_body(rsp);
gboolean ret;
const guint8 *buf;
gsize len;
if (body == NULL)
return TRUE;
g_obex_header_get_bytes(body, &buf, &len);
if (len == 0)
return TRUE;
ret = transfer->data_consumer(buf, len, transfer->user_data);
if (ret == FALSE)
g_set_error(err, G_OBEX_ERROR, G_OBEX_ERROR_CANCELLED,
"Data consumer callback failed");
return ret;
}
static void transfer_response(GObex *obex, GError *err, GObexPacket *rsp,
gpointer user_data)
{
struct transfer *transfer = user_data;
GObexPacket *req;
gboolean rspcode, final;
guint id;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
id = transfer->req_id;
transfer->req_id = 0;
if (err != NULL) {
transfer_complete(transfer, err);
return;
}
rspcode = g_obex_packet_get_operation(rsp, &final);
if (rspcode != G_OBEX_RSP_SUCCESS && rspcode != G_OBEX_RSP_CONTINUE) {
err = g_error_new(G_OBEX_ERROR, rspcode, "%s",
g_obex_strerror(rspcode));
goto failed;
}
if (transfer->opcode == G_OBEX_OP_GET) {
handle_get_body(transfer, rsp, &err);
if (err != NULL)
goto failed;
}
if (rspcode == G_OBEX_RSP_SUCCESS) {
transfer_complete(transfer, NULL);
return;
}
if (transfer->opcode == G_OBEX_OP_PUT) {
req = g_obex_packet_new(transfer->opcode, FALSE,
G_OBEX_HDR_INVALID);
g_obex_packet_add_body(req, put_get_data, transfer);
} else if (!g_obex_srm_active(transfer->obex)) {
req = g_obex_packet_new(transfer->opcode, TRUE,
G_OBEX_HDR_INVALID);
} else {
/* Keep id since request still outstanting */
transfer->req_id = id;
return;
}
transfer->req_id = g_obex_send_req(obex, req, -1, transfer_response,
transfer, &err);
failed:
if (err != NULL) {
g_obex_debug(G_OBEX_DEBUG_ERROR, "%s", err->message);
transfer_complete(transfer, err);
g_error_free(err);
}
}
static struct transfer *transfer_new(GObex *obex, guint8 opcode,
GObexFunc complete_func, gpointer user_data)
{
static guint next_id = 1;
struct transfer *transfer;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "obex %p opcode %u", obex, opcode);
transfer = g_new0(struct transfer, 1);
transfer->id = next_id++;
transfer->opcode = opcode;
transfer->obex = g_obex_ref(obex);
transfer->complete_func = complete_func;
transfer->user_data = user_data;
transfers = g_slist_append(transfers, transfer);
return transfer;
}
guint g_obex_put_req_pkt(GObex *obex, GObexPacket *req,
GObexDataProducer data_func, GObexFunc complete_func,
gpointer user_data, GError **err)
{
struct transfer *transfer;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "obex %p", obex);
if (g_obex_packet_get_operation(req, NULL) != G_OBEX_OP_PUT)
return 0;
transfer = transfer_new(obex, G_OBEX_OP_PUT, complete_func, user_data);
transfer->data_producer = data_func;
g_obex_packet_add_body(req, put_get_data, transfer);
transfer->req_id = g_obex_send_req(obex, req, FIRST_PACKET_TIMEOUT,
transfer_response, transfer, err);
if (transfer->req_id == 0) {
transfer_free(transfer);
return 0;
}
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
return transfer->id;
}
guint g_obex_put_req(GObex *obex, GObexDataProducer data_func,
GObexFunc complete_func, gpointer user_data,
GError **err, guint8 first_hdr_id, ...)
{
GObexPacket *req;
va_list args;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "obex %p", obex);
va_start(args, first_hdr_id);
req = g_obex_packet_new_valist(G_OBEX_OP_PUT, FALSE,
first_hdr_id, args);
va_end(args);
return g_obex_put_req_pkt(obex, req, data_func, complete_func,
user_data, err);
}
static void transfer_abort_req(GObex *obex, GObexPacket *req, gpointer user_data)
{
struct transfer *transfer = user_data;
GObexPacket *rsp;
GError *err;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
err = g_error_new(G_OBEX_ERROR, G_OBEX_ERROR_CANCELLED,
"Request was aborted");
rsp = g_obex_packet_new(G_OBEX_RSP_SUCCESS, TRUE, G_OBEX_HDR_INVALID);
g_obex_send(obex, rsp, NULL);
transfer_complete(transfer, err);
g_error_free(err);
}
static guint8 put_get_bytes(struct transfer *transfer, GObexPacket *req)
{
GObexHeader *body;
gboolean final;
guint8 rsp;
const guint8 *buf;
gsize len;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
g_obex_packet_get_operation(req, &final);
if (final)
rsp = G_OBEX_RSP_SUCCESS;
else
rsp = G_OBEX_RSP_CONTINUE;
body = g_obex_packet_get_body(req);
if (body == NULL)
return rsp;
g_obex_header_get_bytes(body, &buf, &len);
if (len == 0)
return rsp;
if (transfer->data_consumer(buf, len, transfer->user_data) == FALSE)
rsp = G_OBEX_RSP_FORBIDDEN;
return rsp;
}
static void transfer_put_req_first(struct transfer *transfer, GObexPacket *req,
guint8 first_hdr_id, va_list args)
{
GError *err = NULL;
GObexPacket *rsp;
guint8 rspcode;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
rspcode = put_get_bytes(transfer, req);
rsp = g_obex_packet_new_valist(rspcode, TRUE, first_hdr_id, args);
if (!g_obex_send(transfer->obex, rsp, &err)) {
transfer_complete(transfer, err);
g_error_free(err);
}
if (rspcode != G_OBEX_RSP_CONTINUE)
transfer_complete(transfer, NULL);
}
static void transfer_put_req(GObex *obex, GObexPacket *req, gpointer user_data)
{
struct transfer *transfer = user_data;
GError *err = NULL;
GObexPacket *rsp;
guint8 rspcode;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
rspcode = put_get_bytes(transfer, req);
/* Don't send continue while SRM is active */
if (g_obex_srm_active(transfer->obex) &&
rspcode == G_OBEX_RSP_CONTINUE)
goto done;
rsp = g_obex_packet_new(rspcode, TRUE, G_OBEX_HDR_INVALID);
if (!g_obex_send(obex, rsp, &err)) {
transfer_complete(transfer, err);
g_error_free(err);
}
done:
if (rspcode != G_OBEX_RSP_CONTINUE)
transfer_complete(transfer, NULL);
}
guint g_obex_put_rsp(GObex *obex, GObexPacket *req,
GObexDataConsumer data_func, GObexFunc complete_func,
gpointer user_data, GError **err,
guint8 first_hdr_id, ...)
{
struct transfer *transfer;
va_list args;
guint id;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "obex %p", obex);
transfer = transfer_new(obex, G_OBEX_OP_PUT, complete_func, user_data);
transfer->data_consumer = data_func;
va_start(args, first_hdr_id);
transfer_put_req_first(transfer, req, first_hdr_id, args);
va_end(args);
if (!g_slist_find(transfers, transfer))
return 0;
id = g_obex_add_request_function(obex, G_OBEX_OP_PUT, transfer_put_req,
transfer);
transfer->put_id = id;
id = g_obex_add_request_function(obex, G_OBEX_OP_ABORT,
transfer_abort_req, transfer);
transfer->abort_id = id;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
return transfer->id;
}
guint g_obex_get_req_pkt(GObex *obex, GObexPacket *req,
GObexDataConsumer data_func, GObexFunc complete_func,
gpointer user_data, GError **err)
{
struct transfer *transfer;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "obex %p", obex);
if (g_obex_packet_get_operation(req, NULL) != G_OBEX_OP_GET)
return 0;
transfer = transfer_new(obex, G_OBEX_OP_GET, complete_func, user_data);
transfer->data_consumer = data_func;
transfer->req_id = g_obex_send_req(obex, req, FIRST_PACKET_TIMEOUT,
transfer_response, transfer, err);
if (transfer->req_id == 0) {
transfer_free(transfer);
return 0;
}
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
return transfer->id;
}
guint g_obex_get_req(GObex *obex, GObexDataConsumer data_func,
GObexFunc complete_func, gpointer user_data,
GError **err, guint8 first_hdr_id, ...)
{
struct transfer *transfer;
GObexPacket *req;
va_list args;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "obex %p", obex);
transfer = transfer_new(obex, G_OBEX_OP_GET, complete_func, user_data);
transfer->data_consumer = data_func;
va_start(args, first_hdr_id);
req = g_obex_packet_new_valist(G_OBEX_OP_GET, TRUE,
first_hdr_id, args);
va_end(args);
transfer->req_id = g_obex_send_req(obex, req, FIRST_PACKET_TIMEOUT,
transfer_response, transfer, err);
if (transfer->req_id == 0) {
transfer_free(transfer);
return 0;
}
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
return transfer->id;
}
static gssize get_get_data(void *buf, gsize len, gpointer user_data)
{
struct transfer *transfer = user_data;
GObexPacket *req, *rsp;
GError *err = NULL;
gssize ret;
guint8 op;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
ret = transfer->data_producer(buf, len, transfer->user_data);
if (ret > 0) {
if (!g_obex_srm_active(transfer->obex))
return ret;
/* Generate next response */
rsp = g_obex_packet_new(G_OBEX_RSP_CONTINUE, TRUE,
G_OBEX_HDR_INVALID);
g_obex_packet_add_body(rsp, get_get_data, transfer);
if (!g_obex_send(transfer->obex, rsp, &err)) {
transfer_complete(transfer, err);
g_error_free(err);
}
return ret;
}
if (ret == -EAGAIN)
return ret;
if (ret == 0) {
transfer_complete(transfer, NULL);
return ret;
}
op = g_obex_errno_to_rsp(ret);
req = g_obex_packet_new(op, TRUE, G_OBEX_HDR_INVALID);
g_obex_send(transfer->obex, req, NULL);
err = g_error_new(G_OBEX_ERROR, G_OBEX_ERROR_CANCELLED,
"Data producer function failed");
g_obex_debug(G_OBEX_DEBUG_ERROR, "%s", err->message);
transfer_complete(transfer, err);
g_error_free(err);
return ret;
}
static void transfer_get_req_first(struct transfer *transfer, GObexPacket *rsp)
{
GError *err = NULL;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
g_obex_packet_add_body(rsp, get_get_data, transfer);
if (!g_obex_send(transfer->obex, rsp, &err)) {
transfer_complete(transfer, err);
g_error_free(err);
}
}
static void transfer_get_req(GObex *obex, GObexPacket *req, gpointer user_data)
{
struct transfer *transfer = user_data;
GError *err = NULL;
GObexPacket *rsp;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
rsp = g_obex_packet_new(G_OBEX_RSP_CONTINUE, TRUE, G_OBEX_HDR_INVALID);
g_obex_packet_add_body(rsp, get_get_data, transfer);
if (!g_obex_send(obex, rsp, &err)) {
transfer_complete(transfer, err);
g_error_free(err);
}
}
guint g_obex_get_rsp_pkt(GObex *obex, GObexPacket *rsp,
GObexDataProducer data_func, GObexFunc complete_func,
gpointer user_data, GError **err)
{
struct transfer *transfer;
guint id;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "obex %p", obex);
transfer = transfer_new(obex, G_OBEX_OP_GET, complete_func, user_data);
transfer->data_producer = data_func;
transfer_get_req_first(transfer, rsp);
if (!g_slist_find(transfers, transfer))
return 0;
id = g_obex_add_request_function(obex, G_OBEX_OP_GET, transfer_get_req,
transfer);
transfer->get_id = id;
id = g_obex_add_request_function(obex, G_OBEX_OP_ABORT,
transfer_abort_req, transfer);
transfer->abort_id = id;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", transfer->id);
return transfer->id;
}
guint g_obex_get_rsp(GObex *obex, GObexDataProducer data_func,
GObexFunc complete_func, gpointer user_data,
GError **err, guint8 first_hdr_id, ...)
{
GObexPacket *rsp;
va_list args;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "obex %p", obex);
va_start(args, first_hdr_id);
rsp = g_obex_packet_new_valist(G_OBEX_RSP_CONTINUE, TRUE,
first_hdr_id, args);
va_end(args);
return g_obex_get_rsp_pkt(obex, rsp, data_func, complete_func,
user_data, err);
}
gboolean g_obex_cancel_transfer(guint id, GObexFunc complete_func,
gpointer user_data)
{
struct transfer *transfer = NULL;
gboolean ret = TRUE;
g_obex_debug(G_OBEX_DEBUG_TRANSFER, "transfer %u", id);
transfer = find_transfer(id);
if (transfer == NULL)
return FALSE;
if (complete_func == NULL)
goto done;
transfer->complete_func = complete_func;
transfer->user_data = user_data;
if (transfer->req_id == 0)
goto done;
ret = g_obex_cancel_req(transfer->obex, transfer->req_id, FALSE);
if (ret)
return TRUE;
done:
transfer_free(transfer);
return ret;
}
| gpl-2.0 |
fanfuqiang/iec_old | clang-3.2.src/test/CodeGen/builtins-x86.c | 6 | 22871 | // RUN: %clang_cc1 -DUSE_64 -triple x86_64-unknown-unknown -emit-llvm -o %t %s
// RUN: %clang_cc1 -DUSE_ALL -triple x86_64-unknown-unknown -fsyntax-only -o %t %s
#ifdef USE_ALL
#define USE_3DNOW
#define USE_64
#define USE_SSE4
#endif
// 64-bit
typedef char V8c __attribute__((vector_size(8 * sizeof(char))));
typedef signed short V4s __attribute__((vector_size(8)));
typedef signed int V2i __attribute__((vector_size(8)));
typedef signed long long V1LLi __attribute__((vector_size(8)));
typedef float V2f __attribute__((vector_size(8)));
// 128-bit
typedef char V16c __attribute__((vector_size(16)));
typedef signed short V8s __attribute__((vector_size(16)));
typedef signed int V4i __attribute__((vector_size(16)));
typedef signed long long V2LLi __attribute__((vector_size(16)));
typedef float V4f __attribute__((vector_size(16)));
typedef double V2d __attribute__((vector_size(16)));
// 256-bit
typedef char V32c __attribute__((vector_size(32)));
typedef signed int V8i __attribute__((vector_size(32)));
typedef signed long long V4LLi __attribute__((vector_size(32)));
typedef double V4d __attribute__((vector_size(32)));
typedef float V8f __attribute__((vector_size(32)));
void f0() {
signed char tmp_c;
// unsigned char tmp_Uc;
signed short tmp_s;
#ifdef USE_ALL
unsigned short tmp_Us;
#endif
signed int tmp_i;
unsigned int tmp_Ui;
signed long long tmp_LLi;
// unsigned long long tmp_ULLi;
float tmp_f;
double tmp_d;
void* tmp_vp;
const void* tmp_vCp;
char* tmp_cp;
const char* tmp_cCp;
int* tmp_ip;
float* tmp_fp;
const float* tmp_fCp;
double* tmp_dp;
const double* tmp_dCp;
#define imm_i 32
#define imm_i_0_2 0
#define imm_i_0_4 3
#define imm_i_0_8 7
#define imm_i_0_16 15
// Check this.
#define imm_i_0_256 0
V2i* tmp_V2ip;
V1LLi* tmp_V1LLip;
V2LLi* tmp_V2LLip;
// 64-bit
V8c tmp_V8c;
V4s tmp_V4s;
V2i tmp_V2i;
V1LLi tmp_V1LLi;
#ifdef USE_3DNOW
V2f tmp_V2f;
#endif
// 128-bit
V16c tmp_V16c;
V8s tmp_V8s;
V4i tmp_V4i;
V2LLi tmp_V2LLi;
V4f tmp_V4f;
V2d tmp_V2d;
V2d* tmp_V2dp;
V4f* tmp_V4fp;
const V2d* tmp_V2dCp;
const V4f* tmp_V4fCp;
// 256-bit
V32c tmp_V32c;
V4d tmp_V4d;
V8f tmp_V8f;
V4LLi tmp_V4LLi;
V8i tmp_V8i;
V4LLi* tmp_V4LLip;
V4d* tmp_V4dp;
V8f* tmp_V8fp;
const V4d* tmp_V4dCp;
const V8f* tmp_V8fCp;
tmp_i = __builtin_ia32_comieq(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_comilt(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_comile(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_comigt(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_comige(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_comineq(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_ucomieq(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_ucomilt(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_ucomile(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_ucomigt(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_ucomige(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_ucomineq(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_comisdeq(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_comisdlt(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_comisdle(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_comisdgt(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_comisdge(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_comisdneq(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_ucomisdeq(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_ucomisdlt(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_ucomisdle(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_ucomisdgt(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_ucomisdge(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_ucomisdneq(tmp_V2d, tmp_V2d);
tmp_V4f = __builtin_ia32_cmpps(tmp_V4f, tmp_V4f, 0);
tmp_V4f = __builtin_ia32_cmpps(tmp_V4f, tmp_V4f, 1);
tmp_V4f = __builtin_ia32_cmpps(tmp_V4f, tmp_V4f, 2);
tmp_V4f = __builtin_ia32_cmpps(tmp_V4f, tmp_V4f, 3);
tmp_V4f = __builtin_ia32_cmpps(tmp_V4f, tmp_V4f, 4);
tmp_V4f = __builtin_ia32_cmpps(tmp_V4f, tmp_V4f, 5);
tmp_V4f = __builtin_ia32_cmpps(tmp_V4f, tmp_V4f, 6);
tmp_V4f = __builtin_ia32_cmpps(tmp_V4f, tmp_V4f, 7);
tmp_V4f = __builtin_ia32_cmpss(tmp_V4f, tmp_V4f, 0);
tmp_V4f = __builtin_ia32_cmpss(tmp_V4f, tmp_V4f, 1);
tmp_V4f = __builtin_ia32_cmpss(tmp_V4f, tmp_V4f, 2);
tmp_V4f = __builtin_ia32_cmpss(tmp_V4f, tmp_V4f, 3);
tmp_V4f = __builtin_ia32_cmpss(tmp_V4f, tmp_V4f, 4);
tmp_V4f = __builtin_ia32_cmpss(tmp_V4f, tmp_V4f, 5);
tmp_V4f = __builtin_ia32_cmpss(tmp_V4f, tmp_V4f, 6);
tmp_V4f = __builtin_ia32_cmpss(tmp_V4f, tmp_V4f, 7);
tmp_V4f = __builtin_ia32_minps(tmp_V4f, tmp_V4f);
tmp_V4f = __builtin_ia32_maxps(tmp_V4f, tmp_V4f);
tmp_V4f = __builtin_ia32_minss(tmp_V4f, tmp_V4f);
tmp_V4f = __builtin_ia32_maxss(tmp_V4f, tmp_V4f);
tmp_V8c = __builtin_ia32_paddsb(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_paddsw(tmp_V4s, tmp_V4s);
tmp_V8c = __builtin_ia32_psubsb(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_psubsw(tmp_V4s, tmp_V4s);
tmp_V8c = __builtin_ia32_paddusb(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_paddusw(tmp_V4s, tmp_V4s);
tmp_V8c = __builtin_ia32_psubusb(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_psubusw(tmp_V4s, tmp_V4s);
tmp_V4s = __builtin_ia32_pmulhw(tmp_V4s, tmp_V4s);
tmp_V4s = __builtin_ia32_pmulhuw(tmp_V4s, tmp_V4s);
tmp_V8c = __builtin_ia32_pavgb(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_pavgw(tmp_V4s, tmp_V4s);
tmp_V8c = __builtin_ia32_pcmpeqb(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_pcmpeqw(tmp_V4s, tmp_V4s);
tmp_V2i = __builtin_ia32_pcmpeqd(tmp_V2i, tmp_V2i);
tmp_V8c = __builtin_ia32_pcmpgtb(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_pcmpgtw(tmp_V4s, tmp_V4s);
tmp_V2i = __builtin_ia32_pcmpgtd(tmp_V2i, tmp_V2i);
tmp_V8c = __builtin_ia32_pmaxub(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_pmaxsw(tmp_V4s, tmp_V4s);
tmp_V8c = __builtin_ia32_pminub(tmp_V8c, tmp_V8c);
tmp_V4s = __builtin_ia32_pminsw(tmp_V4s, tmp_V4s);
tmp_V2d = __builtin_ia32_cmppd(tmp_V2d, tmp_V2d, 0);
tmp_V2d = __builtin_ia32_cmppd(tmp_V2d, tmp_V2d, 1);
tmp_V2d = __builtin_ia32_cmppd(tmp_V2d, tmp_V2d, 2);
tmp_V2d = __builtin_ia32_cmppd(tmp_V2d, tmp_V2d, 3);
tmp_V2d = __builtin_ia32_cmppd(tmp_V2d, tmp_V2d, 4);
tmp_V2d = __builtin_ia32_cmppd(tmp_V2d, tmp_V2d, 5);
tmp_V2d = __builtin_ia32_cmppd(tmp_V2d, tmp_V2d, 6);
tmp_V2d = __builtin_ia32_cmppd(tmp_V2d, tmp_V2d, 7);
tmp_V2d = __builtin_ia32_cmpsd(tmp_V2d, tmp_V2d, 0);
tmp_V2d = __builtin_ia32_cmpsd(tmp_V2d, tmp_V2d, 1);
tmp_V2d = __builtin_ia32_cmpsd(tmp_V2d, tmp_V2d, 2);
tmp_V2d = __builtin_ia32_cmpsd(tmp_V2d, tmp_V2d, 3);
tmp_V2d = __builtin_ia32_cmpsd(tmp_V2d, tmp_V2d, 4);
tmp_V2d = __builtin_ia32_cmpsd(tmp_V2d, tmp_V2d, 5);
tmp_V2d = __builtin_ia32_cmpsd(tmp_V2d, tmp_V2d, 6);
tmp_V2d = __builtin_ia32_cmpsd(tmp_V2d, tmp_V2d, 7);
tmp_V2d = __builtin_ia32_minpd(tmp_V2d, tmp_V2d);
tmp_V2d = __builtin_ia32_maxpd(tmp_V2d, tmp_V2d);
tmp_V2d = __builtin_ia32_minsd(tmp_V2d, tmp_V2d);
tmp_V2d = __builtin_ia32_maxsd(tmp_V2d, tmp_V2d);
tmp_V16c = __builtin_ia32_paddsb128(tmp_V16c, tmp_V16c);
tmp_V8s = __builtin_ia32_paddsw128(tmp_V8s, tmp_V8s);
tmp_V16c = __builtin_ia32_psubsb128(tmp_V16c, tmp_V16c);
tmp_V8s = __builtin_ia32_psubsw128(tmp_V8s, tmp_V8s);
tmp_V16c = __builtin_ia32_paddusb128(tmp_V16c, tmp_V16c);
tmp_V8s = __builtin_ia32_paddusw128(tmp_V8s, tmp_V8s);
tmp_V16c = __builtin_ia32_psubusb128(tmp_V16c, tmp_V16c);
tmp_V8s = __builtin_ia32_psubusw128(tmp_V8s, tmp_V8s);
tmp_V8s = __builtin_ia32_pmulhw128(tmp_V8s, tmp_V8s);
tmp_V16c = __builtin_ia32_pavgb128(tmp_V16c, tmp_V16c);
tmp_V8s = __builtin_ia32_pavgw128(tmp_V8s, tmp_V8s);
tmp_V16c = __builtin_ia32_pmaxub128(tmp_V16c, tmp_V16c);
tmp_V8s = __builtin_ia32_pmaxsw128(tmp_V8s, tmp_V8s);
tmp_V16c = __builtin_ia32_pminub128(tmp_V16c, tmp_V16c);
tmp_V8s = __builtin_ia32_pminsw128(tmp_V8s, tmp_V8s);
tmp_V8s = __builtin_ia32_packsswb128(tmp_V8s, tmp_V8s);
tmp_V4i = __builtin_ia32_packssdw128(tmp_V4i, tmp_V4i);
tmp_V8s = __builtin_ia32_packuswb128(tmp_V8s, tmp_V8s);
tmp_V8s = __builtin_ia32_pmulhuw128(tmp_V8s, tmp_V8s);
tmp_V4f = __builtin_ia32_addsubps(tmp_V4f, tmp_V4f);
tmp_V2d = __builtin_ia32_addsubpd(tmp_V2d, tmp_V2d);
tmp_V4f = __builtin_ia32_haddps(tmp_V4f, tmp_V4f);
tmp_V2d = __builtin_ia32_haddpd(tmp_V2d, tmp_V2d);
tmp_V4f = __builtin_ia32_hsubps(tmp_V4f, tmp_V4f);
tmp_V2d = __builtin_ia32_hsubpd(tmp_V2d, tmp_V2d);
tmp_V8s = __builtin_ia32_phaddw128(tmp_V8s, tmp_V8s);
tmp_V4s = __builtin_ia32_phaddw(tmp_V4s, tmp_V4s);
tmp_V4i = __builtin_ia32_phaddd128(tmp_V4i, tmp_V4i);
tmp_V2i = __builtin_ia32_phaddd(tmp_V2i, tmp_V2i);
tmp_V8s = __builtin_ia32_phaddsw128(tmp_V8s, tmp_V8s);
tmp_V4s = __builtin_ia32_phaddsw(tmp_V4s, tmp_V4s);
tmp_V8s = __builtin_ia32_phsubw128(tmp_V8s, tmp_V8s);
tmp_V4s = __builtin_ia32_phsubw(tmp_V4s, tmp_V4s);
tmp_V4i = __builtin_ia32_phsubd128(tmp_V4i, tmp_V4i);
tmp_V2i = __builtin_ia32_phsubd(tmp_V2i, tmp_V2i);
tmp_V8s = __builtin_ia32_phsubsw128(tmp_V8s, tmp_V8s);
tmp_V4s = __builtin_ia32_phsubsw(tmp_V4s, tmp_V4s);
tmp_V16c = __builtin_ia32_pmaddubsw128(tmp_V16c, tmp_V16c);
tmp_V8c = __builtin_ia32_pmaddubsw(tmp_V8c, tmp_V8c);
tmp_V8s = __builtin_ia32_pmulhrsw128(tmp_V8s, tmp_V8s);
tmp_V4s = __builtin_ia32_pmulhrsw(tmp_V4s, tmp_V4s);
tmp_V16c = __builtin_ia32_pshufb128(tmp_V16c, tmp_V16c);
tmp_V8c = __builtin_ia32_pshufb(tmp_V8c, tmp_V8c);
tmp_V16c = __builtin_ia32_psignb128(tmp_V16c, tmp_V16c);
tmp_V8c = __builtin_ia32_psignb(tmp_V8c, tmp_V8c);
tmp_V8s = __builtin_ia32_psignw128(tmp_V8s, tmp_V8s);
tmp_V4s = __builtin_ia32_psignw(tmp_V4s, tmp_V4s);
tmp_V4i = __builtin_ia32_psignd128(tmp_V4i, tmp_V4i);
tmp_V2i = __builtin_ia32_psignd(tmp_V2i, tmp_V2i);
tmp_V16c = __builtin_ia32_pabsb128(tmp_V16c);
tmp_V8c = __builtin_ia32_pabsb(tmp_V8c);
tmp_V8s = __builtin_ia32_pabsw128(tmp_V8s);
tmp_V4s = __builtin_ia32_pabsw(tmp_V4s);
tmp_V4i = __builtin_ia32_pabsd128(tmp_V4i);
tmp_V2i = __builtin_ia32_pabsd(tmp_V2i);
tmp_V4s = __builtin_ia32_psllw(tmp_V4s, tmp_V1LLi);
tmp_V2i = __builtin_ia32_pslld(tmp_V2i, tmp_V1LLi);
tmp_V1LLi = __builtin_ia32_psllq(tmp_V1LLi, tmp_V1LLi);
tmp_V4s = __builtin_ia32_psrlw(tmp_V4s, tmp_V1LLi);
tmp_V2i = __builtin_ia32_psrld(tmp_V2i, tmp_V1LLi);
tmp_V1LLi = __builtin_ia32_psrlq(tmp_V1LLi, tmp_V1LLi);
tmp_V4s = __builtin_ia32_psraw(tmp_V4s, tmp_V1LLi);
tmp_V2i = __builtin_ia32_psrad(tmp_V2i, tmp_V1LLi);
tmp_V2i = __builtin_ia32_pmaddwd(tmp_V4s, tmp_V4s);
tmp_V8c = __builtin_ia32_packsswb(tmp_V4s, tmp_V4s);
tmp_V4s = __builtin_ia32_packssdw(tmp_V2i, tmp_V2i);
tmp_V8c = __builtin_ia32_packuswb(tmp_V4s, tmp_V4s);
tmp_i = __builtin_ia32_vec_ext_v2si(tmp_V2i, 0);
(void) __builtin_ia32_ldmxcsr(tmp_Ui);
tmp_Ui = __builtin_ia32_stmxcsr();
tmp_V4f = __builtin_ia32_cvtpi2ps(tmp_V4f, tmp_V2i);
tmp_V2i = __builtin_ia32_cvtps2pi(tmp_V4f);
tmp_i = __builtin_ia32_cvtss2si(tmp_V4f);
#ifdef USE_64
tmp_LLi = __builtin_ia32_cvtss2si64(tmp_V4f);
#endif
tmp_V2i = __builtin_ia32_cvttps2pi(tmp_V4f);
(void) __builtin_ia32_maskmovq(tmp_V8c, tmp_V8c, tmp_cp);
(void) __builtin_ia32_storeups(tmp_fp, tmp_V4f);
(void) __builtin_ia32_storehps(tmp_V2ip, tmp_V4f);
(void) __builtin_ia32_storelps(tmp_V2ip, tmp_V4f);
tmp_i = __builtin_ia32_movmskps(tmp_V4f);
tmp_i = __builtin_ia32_pmovmskb(tmp_V8c);
(void) __builtin_ia32_movntps(tmp_fp, tmp_V4f);
(void) __builtin_ia32_movntq(tmp_V1LLip, tmp_V1LLi);
(void) __builtin_ia32_sfence();
tmp_V4s = __builtin_ia32_psadbw(tmp_V8c, tmp_V8c);
tmp_V4f = __builtin_ia32_rcpps(tmp_V4f);
tmp_V4f = __builtin_ia32_rcpss(tmp_V4f);
tmp_V4f = __builtin_ia32_rsqrtps(tmp_V4f);
tmp_V4f = __builtin_ia32_rsqrtss(tmp_V4f);
tmp_V4f = __builtin_ia32_sqrtps(tmp_V4f);
tmp_V4f = __builtin_ia32_sqrtss(tmp_V4f);
(void) __builtin_ia32_maskmovdqu(tmp_V16c, tmp_V16c, tmp_cp);
(void) __builtin_ia32_storeupd(tmp_dp, tmp_V2d);
tmp_i = __builtin_ia32_movmskpd(tmp_V2d);
tmp_i = __builtin_ia32_pmovmskb128(tmp_V16c);
(void) __builtin_ia32_movnti(tmp_ip, tmp_i);
(void) __builtin_ia32_movntpd(tmp_dp, tmp_V2d);
(void) __builtin_ia32_movntdq(tmp_V2LLip, tmp_V2LLi);
tmp_V2LLi = __builtin_ia32_psadbw128(tmp_V16c, tmp_V16c);
tmp_V2d = __builtin_ia32_sqrtpd(tmp_V2d);
tmp_V2d = __builtin_ia32_sqrtsd(tmp_V2d);
tmp_V2d = __builtin_ia32_cvtdq2pd(tmp_V4i);
tmp_V4f = __builtin_ia32_cvtdq2ps(tmp_V4i);
tmp_V2LLi = __builtin_ia32_cvtpd2dq(tmp_V2d);
tmp_V2i = __builtin_ia32_cvtpd2pi(tmp_V2d);
tmp_V4f = __builtin_ia32_cvtpd2ps(tmp_V2d);
tmp_V4i = __builtin_ia32_cvttpd2dq(tmp_V2d);
tmp_V2i = __builtin_ia32_cvttpd2pi(tmp_V2d);
tmp_V2d = __builtin_ia32_cvtpi2pd(tmp_V2i);
tmp_i = __builtin_ia32_cvtsd2si(tmp_V2d);
#ifdef USE_64
tmp_LLi = __builtin_ia32_cvtsd2si64(tmp_V2d);
#endif
tmp_V4i = __builtin_ia32_cvtps2dq(tmp_V4f);
tmp_V2d = __builtin_ia32_cvtps2pd(tmp_V4f);
tmp_V4i = __builtin_ia32_cvttps2dq(tmp_V4f);
(void) __builtin_ia32_clflush(tmp_vCp);
(void) __builtin_ia32_lfence();
(void) __builtin_ia32_mfence();
(void) __builtin_ia32_storedqu(tmp_cp, tmp_V16c);
tmp_V4s = __builtin_ia32_psllwi(tmp_V4s, tmp_i);
tmp_V2i = __builtin_ia32_pslldi(tmp_V2i, tmp_i);
tmp_V1LLi = __builtin_ia32_psllqi(tmp_V1LLi, tmp_i);
tmp_V4s = __builtin_ia32_psrawi(tmp_V4s, tmp_i);
tmp_V2i = __builtin_ia32_psradi(tmp_V2i, tmp_i);
tmp_V4s = __builtin_ia32_psrlwi(tmp_V4s, tmp_i);
tmp_V2i = __builtin_ia32_psrldi(tmp_V2i, tmp_i);
tmp_V1LLi = __builtin_ia32_psrlqi(tmp_V1LLi, tmp_i);
tmp_V1LLi = __builtin_ia32_pmuludq(tmp_V2i, tmp_V2i);
tmp_V2LLi = __builtin_ia32_pmuludq128(tmp_V4i, tmp_V4i);
tmp_V8s = __builtin_ia32_psraw128(tmp_V8s, tmp_V8s);
tmp_V4i = __builtin_ia32_psrad128(tmp_V4i, tmp_V4i);
tmp_V8s = __builtin_ia32_psrlw128(tmp_V8s, tmp_V8s);
tmp_V4i = __builtin_ia32_psrld128(tmp_V4i, tmp_V4i);
tmp_V2LLi = __builtin_ia32_psrlq128(tmp_V2LLi, tmp_V2LLi);
tmp_V8s = __builtin_ia32_psllw128(tmp_V8s, tmp_V8s);
tmp_V4i = __builtin_ia32_pslld128(tmp_V4i, tmp_V4i);
tmp_V2LLi = __builtin_ia32_psllq128(tmp_V2LLi, tmp_V2LLi);
tmp_V8s = __builtin_ia32_psllwi128(tmp_V8s, tmp_i);
tmp_V4i = __builtin_ia32_pslldi128(tmp_V4i, tmp_i);
tmp_V2LLi = __builtin_ia32_psllqi128(tmp_V2LLi, tmp_i);
tmp_V8s = __builtin_ia32_psrlwi128(tmp_V8s, tmp_i);
tmp_V4i = __builtin_ia32_psrldi128(tmp_V4i, tmp_i);
tmp_V2LLi = __builtin_ia32_psrlqi128(tmp_V2LLi, tmp_i);
tmp_V8s = __builtin_ia32_psrawi128(tmp_V8s, tmp_i);
tmp_V4i = __builtin_ia32_psradi128(tmp_V4i, tmp_i);
tmp_V8s = __builtin_ia32_pmaddwd128(tmp_V8s, tmp_V8s);
(void) __builtin_ia32_monitor(tmp_vp, tmp_Ui, tmp_Ui);
(void) __builtin_ia32_mwait(tmp_Ui, tmp_Ui);
tmp_V16c = __builtin_ia32_lddqu(tmp_cCp);
tmp_V2LLi = __builtin_ia32_palignr128(tmp_V2LLi, tmp_V2LLi, imm_i);
tmp_V1LLi = __builtin_ia32_palignr(tmp_V1LLi, tmp_V1LLi, imm_i);
#ifdef USE_SSE4
tmp_V16c = __builtin_ia32_pblendvb128(tmp_V16c, tmp_V16c, tmp_V16c);
tmp_V8s = __builtin_ia32_pblendw128(tmp_V8s, tmp_V8s, imm_i_0_256);
tmp_V2d = __builtin_ia32_blendpd(tmp_V2d, tmp_V2d, imm_i_0_256);
tmp_V4f = __builtin_ia32_blendps(tmp_V4f, tmp_V4f, imm_i_0_256);
tmp_V2d = __builtin_ia32_blendvpd(tmp_V2d, tmp_V2d, tmp_V2d);
tmp_V4f = __builtin_ia32_blendvps(tmp_V4f, tmp_V4f, tmp_V4f);
tmp_V8s = __builtin_ia32_packusdw128(tmp_V4i, tmp_V4i);
tmp_V16c = __builtin_ia32_pmaxsb128(tmp_V16c, tmp_V16c);
tmp_V4i = __builtin_ia32_pmaxsd128(tmp_V4i, tmp_V4i);
tmp_V4i = __builtin_ia32_pmaxud128(tmp_V4i, tmp_V4i);
tmp_V8s = __builtin_ia32_pmaxuw128(tmp_V8s, tmp_V8s);
tmp_V16c = __builtin_ia32_pminsb128(tmp_V16c, tmp_V16c);
tmp_V4i = __builtin_ia32_pminsd128(tmp_V4i, tmp_V4i);
tmp_V4i = __builtin_ia32_pminud128(tmp_V4i, tmp_V4i);
tmp_V8s = __builtin_ia32_pminuw128(tmp_V8s, tmp_V8s);
tmp_V4i = __builtin_ia32_pmovsxbd128(tmp_V16c);
tmp_V2LLi = __builtin_ia32_pmovsxbq128(tmp_V16c);
tmp_V8s = __builtin_ia32_pmovsxbw128(tmp_V16c);
tmp_V2LLi = __builtin_ia32_pmovsxdq128(tmp_V4i);
tmp_V4i = __builtin_ia32_pmovsxwd128(tmp_V8s);
tmp_V2LLi = __builtin_ia32_pmovsxwq128(tmp_V8s);
tmp_V4i = __builtin_ia32_pmovzxbd128(tmp_V16c);
tmp_V2LLi = __builtin_ia32_pmovzxbq128(tmp_V16c);
tmp_V8s = __builtin_ia32_pmovzxbw128(tmp_V16c);
tmp_V2LLi = __builtin_ia32_pmovzxdq128(tmp_V4i);
tmp_V4i = __builtin_ia32_pmovzxwd128(tmp_V8s);
tmp_V2LLi = __builtin_ia32_pmovzxwq128(tmp_V8s);
tmp_V2LLi = __builtin_ia32_pmuldq128(tmp_V4i, tmp_V4i);
tmp_V4i = __builtin_ia32_pmulld128(tmp_V4i, tmp_V4i);
tmp_V4f = __builtin_ia32_roundps(tmp_V4f, imm_i_0_16);
tmp_V4f = __builtin_ia32_roundss(tmp_V4f, tmp_V4f, imm_i_0_16);
tmp_V2d = __builtin_ia32_roundsd(tmp_V2d, tmp_V2d, imm_i_0_16);
tmp_V2d = __builtin_ia32_roundpd(tmp_V2d, imm_i_0_16);
tmp_V4f = __builtin_ia32_insertps128(tmp_V4f, tmp_V4f, tmp_i);
#endif
tmp_V4d = __builtin_ia32_addsubpd256(tmp_V4d, tmp_V4d);
tmp_V8f = __builtin_ia32_addsubps256(tmp_V8f, tmp_V8f);
tmp_V4d = __builtin_ia32_haddpd256(tmp_V4d, tmp_V4d);
tmp_V8f = __builtin_ia32_hsubps256(tmp_V8f, tmp_V8f);
tmp_V4d = __builtin_ia32_hsubpd256(tmp_V4d, tmp_V4d);
tmp_V8f = __builtin_ia32_haddps256(tmp_V8f, tmp_V8f);
tmp_V4d = __builtin_ia32_maxpd256(tmp_V4d, tmp_V4d);
tmp_V8f = __builtin_ia32_maxps256(tmp_V8f, tmp_V8f);
tmp_V4d = __builtin_ia32_minpd256(tmp_V4d, tmp_V4d);
tmp_V8f = __builtin_ia32_minps256(tmp_V8f, tmp_V8f);
tmp_V2d = __builtin_ia32_vpermilvarpd(tmp_V2d, tmp_V2LLi);
tmp_V4f = __builtin_ia32_vpermilvarps(tmp_V4f, tmp_V4i);
tmp_V4d = __builtin_ia32_vpermilvarpd256(tmp_V4d, tmp_V4LLi);
tmp_V8f = __builtin_ia32_vpermilvarps256(tmp_V8f, tmp_V8i);
tmp_V4d = __builtin_ia32_blendpd256(tmp_V4d, tmp_V4d, 0x7);
tmp_V8f = __builtin_ia32_blendps256(tmp_V8f, tmp_V8f, 0x7);
tmp_V4d = __builtin_ia32_blendvpd256(tmp_V4d, tmp_V4d, tmp_V4d);
tmp_V8f = __builtin_ia32_blendvps256(tmp_V8f, tmp_V8f, tmp_V8f);
tmp_V8f = __builtin_ia32_dpps256(tmp_V8f, tmp_V8f, 0x7);
tmp_V4d = __builtin_ia32_cmppd256(tmp_V4d, tmp_V4d, 0);
tmp_V8f = __builtin_ia32_cmpps256(tmp_V8f, tmp_V8f, 0);
tmp_V2d = __builtin_ia32_vextractf128_pd256(tmp_V4d, 0x7);
tmp_V4f = __builtin_ia32_vextractf128_ps256(tmp_V8f, 0x7);
tmp_V4i = __builtin_ia32_vextractf128_si256(tmp_V8i, 0x7);
tmp_V4d = __builtin_ia32_cvtdq2pd256(tmp_V4i);
tmp_V8f = __builtin_ia32_cvtdq2ps256(tmp_V8i);
tmp_V4f = __builtin_ia32_cvtpd2ps256(tmp_V4d);
tmp_V8i = __builtin_ia32_cvtps2dq256(tmp_V8f);
tmp_V4d = __builtin_ia32_cvtps2pd256(tmp_V4f);
tmp_V4i = __builtin_ia32_cvttpd2dq256(tmp_V4d);
tmp_V4i = __builtin_ia32_cvtpd2dq256(tmp_V4d);
tmp_V8i = __builtin_ia32_cvttps2dq256(tmp_V8f);
tmp_V4d = __builtin_ia32_vperm2f128_pd256(tmp_V4d, tmp_V4d, 0x7);
tmp_V8f = __builtin_ia32_vperm2f128_ps256(tmp_V8f, tmp_V8f, 0x7);
tmp_V8i = __builtin_ia32_vperm2f128_si256(tmp_V8i, tmp_V8i, 0x7);
tmp_V4d = __builtin_ia32_vinsertf128_pd256(tmp_V4d, tmp_V2d, 0x7);
tmp_V8f = __builtin_ia32_vinsertf128_ps256(tmp_V8f, tmp_V4f, 0x7);
tmp_V8i = __builtin_ia32_vinsertf128_si256(tmp_V8i, tmp_V4i, 0x7);
tmp_V4d = __builtin_ia32_sqrtpd256(tmp_V4d);
tmp_V8f = __builtin_ia32_sqrtps256(tmp_V8f);
tmp_V8f = __builtin_ia32_rsqrtps256(tmp_V8f);
tmp_V8f = __builtin_ia32_rcpps256(tmp_V8f);
tmp_V4d = __builtin_ia32_roundpd256(tmp_V4d, 0x1);
tmp_V8f = __builtin_ia32_roundps256(tmp_V8f, 0x1);
tmp_i = __builtin_ia32_vtestzpd(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_vtestcpd(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_vtestnzcpd(tmp_V2d, tmp_V2d);
tmp_i = __builtin_ia32_vtestzps(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_vtestcps(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_vtestnzcps(tmp_V4f, tmp_V4f);
tmp_i = __builtin_ia32_vtestzpd256(tmp_V4d, tmp_V4d);
tmp_i = __builtin_ia32_vtestcpd256(tmp_V4d, tmp_V4d);
tmp_i = __builtin_ia32_vtestnzcpd256(tmp_V4d, tmp_V4d);
tmp_i = __builtin_ia32_vtestzps256(tmp_V8f, tmp_V8f);
tmp_i = __builtin_ia32_vtestcps256(tmp_V8f, tmp_V8f);
tmp_i = __builtin_ia32_vtestnzcps256(tmp_V8f, tmp_V8f);
tmp_i = __builtin_ia32_ptestz256(tmp_V4LLi, tmp_V4LLi);
tmp_i = __builtin_ia32_ptestc256(tmp_V4LLi, tmp_V4LLi);
tmp_i = __builtin_ia32_ptestnzc256(tmp_V4LLi, tmp_V4LLi);
tmp_i = __builtin_ia32_movmskpd256(tmp_V4d);
tmp_i = __builtin_ia32_movmskps256(tmp_V8f);
__builtin_ia32_vzeroall();
__builtin_ia32_vzeroupper();
tmp_V4f = __builtin_ia32_vbroadcastss(tmp_fCp);
tmp_V4d = __builtin_ia32_vbroadcastsd256(tmp_dCp);
tmp_V8f = __builtin_ia32_vbroadcastss256(tmp_fCp);
tmp_V4d = __builtin_ia32_vbroadcastf128_pd256(tmp_V2dCp);
tmp_V8f = __builtin_ia32_vbroadcastf128_ps256(tmp_V4fCp);
__builtin_ia32_storeupd256(tmp_dp, tmp_V4d);
__builtin_ia32_storeups256(tmp_fp, tmp_V8f);
__builtin_ia32_storedqu256(tmp_cp, tmp_V32c);
tmp_V32c = __builtin_ia32_lddqu256(tmp_cCp);
__builtin_ia32_movntdq256(tmp_V4LLip, tmp_V4LLi);
__builtin_ia32_movntpd256(tmp_dp, tmp_V4d);
__builtin_ia32_movntps256(tmp_fp, tmp_V8f);
tmp_V2d = __builtin_ia32_maskloadpd(tmp_V2dCp, tmp_V2d);
tmp_V4f = __builtin_ia32_maskloadps(tmp_V4fCp, tmp_V4f);
tmp_V4d = __builtin_ia32_maskloadpd256(tmp_V4dCp, tmp_V4d);
tmp_V8f = __builtin_ia32_maskloadps256(tmp_V8fCp, tmp_V8f);
__builtin_ia32_maskstorepd(tmp_V2dp, tmp_V2d, tmp_V2d);
__builtin_ia32_maskstoreps(tmp_V4fp, tmp_V4f, tmp_V4f);
__builtin_ia32_maskstorepd256(tmp_V4dp, tmp_V4d, tmp_V4d);
__builtin_ia32_maskstoreps256(tmp_V8fp, tmp_V8f, tmp_V8f);
#ifdef USE_3DNOW
tmp_V8c = __builtin_ia32_pavgusb(tmp_V8c, tmp_V8c);
tmp_V2i = __builtin_ia32_pf2id(tmp_V2f);
tmp_V2f = __builtin_ia32_pfacc(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfadd(tmp_V2f, tmp_V2f);
tmp_V2i = __builtin_ia32_pfcmpeq(tmp_V2f, tmp_V2f);
tmp_V2i = __builtin_ia32_pfcmpge(tmp_V2f, tmp_V2f);
tmp_V2i = __builtin_ia32_pfcmpgt(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfmax(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfmin(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfmul(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfrcp(tmp_V2f);
tmp_V2f = __builtin_ia32_pfrcpit1(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfrcpit2(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfrsqrt(tmp_V2f);
tmp_V2f = __builtin_ia32_pfrsqit1(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfsub(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfsubr(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pi2fd(tmp_V2i);
tmp_V4s = __builtin_ia32_pmulhrw(tmp_V4s, tmp_V4s);
tmp_V2i = __builtin_ia32_pf2iw(tmp_V2f);
tmp_V2f = __builtin_ia32_pfnacc(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pfpnacc(tmp_V2f, tmp_V2f);
tmp_V2f = __builtin_ia32_pi2fw(tmp_V2i);
tmp_V2f = __builtin_ia32_pswapdsf(tmp_V2f);
tmp_V2i = __builtin_ia32_pswapdsi(tmp_V2i);
#endif
}
| gpl-2.0 |
YouDiSN/OpenJDK-Research | jdk9/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp | 6 | 46638 | /*
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "c1/c1_Compilation.hpp"
#include "c1/c1_FrameMap.hpp"
#include "c1/c1_Instruction.hpp"
#include "c1/c1_LIRAssembler.hpp"
#include "c1/c1_LIRGenerator.hpp"
#include "c1/c1_Runtime1.hpp"
#include "c1/c1_ValueStack.hpp"
#include "ci/ciArray.hpp"
#include "ci/ciObjArrayKlass.hpp"
#include "ci/ciTypeArrayKlass.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/stubRoutines.hpp"
#include "vmreg_sparc.inline.hpp"
#ifdef ASSERT
#define __ gen()->lir(__FILE__, __LINE__)->
#else
#define __ gen()->lir()->
#endif
void LIRItem::load_byte_item() {
// byte loads use same registers as other loads
load_item();
}
void LIRItem::load_nonconstant() {
LIR_Opr r = value()->operand();
if (_gen->can_inline_as_constant(value())) {
if (!r->is_constant()) {
r = LIR_OprFact::value_type(value()->type());
}
_result = r;
} else {
load_item();
}
}
//--------------------------------------------------------------
// LIRGenerator
//--------------------------------------------------------------
LIR_Opr LIRGenerator::exceptionOopOpr() { return FrameMap::Oexception_opr; }
LIR_Opr LIRGenerator::exceptionPcOpr() { return FrameMap::Oissuing_pc_opr; }
LIR_Opr LIRGenerator::syncLockOpr() { return new_register(T_INT); }
LIR_Opr LIRGenerator::syncTempOpr() { return new_register(T_OBJECT); }
LIR_Opr LIRGenerator::getThreadTemp() { return rlock_callee_saved(NOT_LP64(T_INT) LP64_ONLY(T_LONG)); }
LIR_Opr LIRGenerator::result_register_for(ValueType* type, bool callee) {
LIR_Opr opr;
switch (type->tag()) {
case intTag: opr = callee ? FrameMap::I0_opr : FrameMap::O0_opr; break;
case objectTag: opr = callee ? FrameMap::I0_oop_opr : FrameMap::O0_oop_opr; break;
case longTag: opr = callee ? FrameMap::in_long_opr : FrameMap::out_long_opr; break;
case floatTag: opr = FrameMap::F0_opr; break;
case doubleTag: opr = FrameMap::F0_double_opr; break;
case addressTag:
default: ShouldNotReachHere(); return LIR_OprFact::illegalOpr;
}
assert(opr->type_field() == as_OprType(as_BasicType(type)), "type mismatch");
return opr;
}
LIR_Opr LIRGenerator::rlock_callee_saved(BasicType type) {
LIR_Opr reg = new_register(type);
set_vreg_flag(reg, callee_saved);
return reg;
}
LIR_Opr LIRGenerator::rlock_byte(BasicType type) {
return new_register(T_INT);
}
//--------- loading items into registers --------------------------------
// SPARC cannot inline all constants
bool LIRGenerator::can_store_as_constant(Value v, BasicType type) const {
if (v->type()->as_IntConstant() != NULL) {
return v->type()->as_IntConstant()->value() == 0;
} else if (v->type()->as_LongConstant() != NULL) {
return v->type()->as_LongConstant()->value() == 0L;
} else if (v->type()->as_ObjectConstant() != NULL) {
return v->type()->as_ObjectConstant()->value()->is_null_object();
} else {
return false;
}
}
// only simm13 constants can be inlined
bool LIRGenerator:: can_inline_as_constant(Value i) const {
if (i->type()->as_IntConstant() != NULL) {
return Assembler::is_simm13(i->type()->as_IntConstant()->value());
} else {
return can_store_as_constant(i, as_BasicType(i->type()));
}
}
bool LIRGenerator:: can_inline_as_constant(LIR_Const* c) const {
if (c->type() == T_INT) {
return Assembler::is_simm13(c->as_jint());
}
return false;
}
LIR_Opr LIRGenerator::safepoint_poll_register() {
return new_register(T_INT);
}
LIR_Address* LIRGenerator::generate_address(LIR_Opr base, LIR_Opr index,
int shift, int disp, BasicType type) {
assert(base->is_register(), "must be");
intx large_disp = disp;
// accumulate fixed displacements
if (index->is_constant()) {
large_disp += (intx)(index->as_constant_ptr()->as_jint()) << shift;
index = LIR_OprFact::illegalOpr;
}
if (index->is_register()) {
// apply the shift and accumulate the displacement
if (shift > 0) {
LIR_Opr tmp = new_pointer_register();
__ shift_left(index, shift, tmp);
index = tmp;
}
if (large_disp != 0) {
LIR_Opr tmp = new_pointer_register();
if (Assembler::is_simm13(large_disp)) {
__ add(tmp, LIR_OprFact::intptrConst(large_disp), tmp);
index = tmp;
} else {
__ move(LIR_OprFact::intptrConst(large_disp), tmp);
__ add(tmp, index, tmp);
index = tmp;
}
large_disp = 0;
}
} else if (large_disp != 0 && !Assembler::is_simm13(large_disp)) {
// index is illegal so replace it with the displacement loaded into a register
index = new_pointer_register();
__ move(LIR_OprFact::intptrConst(large_disp), index);
large_disp = 0;
}
// at this point we either have base + index or base + displacement
if (large_disp == 0) {
return new LIR_Address(base, index, type);
} else {
assert(Assembler::is_simm13(large_disp), "must be");
return new LIR_Address(base, large_disp, type);
}
}
LIR_Address* LIRGenerator::emit_array_address(LIR_Opr array_opr, LIR_Opr index_opr,
BasicType type, bool needs_card_mark) {
int elem_size = type2aelembytes(type);
int shift = exact_log2(elem_size);
LIR_Opr base_opr;
intx offset = arrayOopDesc::base_offset_in_bytes(type);
if (index_opr->is_constant()) {
intx i = index_opr->as_constant_ptr()->as_jint();
intx array_offset = i * elem_size;
if (Assembler::is_simm13(array_offset + offset)) {
base_opr = array_opr;
offset = array_offset + offset;
} else {
base_opr = new_pointer_register();
if (Assembler::is_simm13(array_offset)) {
__ add(array_opr, LIR_OprFact::intptrConst(array_offset), base_opr);
} else {
__ move(LIR_OprFact::intptrConst(array_offset), base_opr);
__ add(base_opr, array_opr, base_opr);
}
}
} else {
#ifdef _LP64
if (index_opr->type() == T_INT) {
LIR_Opr tmp = new_register(T_LONG);
__ convert(Bytecodes::_i2l, index_opr, tmp);
index_opr = tmp;
}
#endif
base_opr = new_pointer_register();
assert (index_opr->is_register(), "Must be register");
if (shift > 0) {
__ shift_left(index_opr, shift, base_opr);
__ add(base_opr, array_opr, base_opr);
} else {
__ add(index_opr, array_opr, base_opr);
}
}
if (needs_card_mark) {
LIR_Opr ptr = new_pointer_register();
__ add(base_opr, LIR_OprFact::intptrConst(offset), ptr);
return new LIR_Address(ptr, type);
} else {
return new LIR_Address(base_opr, offset, type);
}
}
LIR_Opr LIRGenerator::load_immediate(int x, BasicType type) {
LIR_Opr r;
if (type == T_LONG) {
r = LIR_OprFact::longConst(x);
} else if (type == T_INT) {
r = LIR_OprFact::intConst(x);
} else {
ShouldNotReachHere();
}
if (!Assembler::is_simm13(x)) {
LIR_Opr tmp = new_register(type);
__ move(r, tmp);
return tmp;
}
return r;
}
void LIRGenerator::increment_counter(address counter, BasicType type, int step) {
LIR_Opr pointer = new_pointer_register();
__ move(LIR_OprFact::intptrConst(counter), pointer);
LIR_Address* addr = new LIR_Address(pointer, type);
increment_counter(addr, step);
}
void LIRGenerator::increment_counter(LIR_Address* addr, int step) {
LIR_Opr temp = new_register(addr->type());
__ move(addr, temp);
__ add(temp, load_immediate(step, addr->type()), temp);
__ move(temp, addr);
}
void LIRGenerator::cmp_mem_int(LIR_Condition condition, LIR_Opr base, int disp, int c, CodeEmitInfo* info) {
LIR_Opr o7opr = FrameMap::O7_opr;
__ load(new LIR_Address(base, disp, T_INT), o7opr, info);
__ cmp(condition, o7opr, c);
}
void LIRGenerator::cmp_reg_mem(LIR_Condition condition, LIR_Opr reg, LIR_Opr base, int disp, BasicType type, CodeEmitInfo* info) {
LIR_Opr o7opr = FrameMap::O7_opr;
__ load(new LIR_Address(base, disp, type), o7opr, info);
__ cmp(condition, reg, o7opr);
}
void LIRGenerator::cmp_reg_mem(LIR_Condition condition, LIR_Opr reg, LIR_Opr base, LIR_Opr disp, BasicType type, CodeEmitInfo* info) {
LIR_Opr o7opr = FrameMap::O7_opr;
__ load(new LIR_Address(base, disp, type), o7opr, info);
__ cmp(condition, reg, o7opr);
}
bool LIRGenerator::strength_reduce_multiply(LIR_Opr left, int c, LIR_Opr result, LIR_Opr tmp) {
assert(left != result, "should be different registers");
if (is_power_of_2(c + 1)) {
__ shift_left(left, log2_intptr(c + 1), result);
__ sub(result, left, result);
return true;
} else if (is_power_of_2(c - 1)) {
__ shift_left(left, log2_intptr(c - 1), result);
__ add(result, left, result);
return true;
}
return false;
}
void LIRGenerator::store_stack_parameter (LIR_Opr item, ByteSize offset_from_sp) {
BasicType t = item->type();
LIR_Opr sp_opr = FrameMap::SP_opr;
if ((t == T_LONG || t == T_DOUBLE) &&
((in_bytes(offset_from_sp) - STACK_BIAS) % 8 != 0)) {
__ unaligned_move(item, new LIR_Address(sp_opr, in_bytes(offset_from_sp), t));
} else {
__ move(item, new LIR_Address(sp_opr, in_bytes(offset_from_sp), t));
}
}
//----------------------------------------------------------------------
// visitor functions
//----------------------------------------------------------------------
void LIRGenerator::do_StoreIndexed(StoreIndexed* x) {
assert(x->is_pinned(),"");
bool needs_range_check = x->compute_needs_range_check();
bool use_length = x->length() != NULL;
bool obj_store = x->elt_type() == T_ARRAY || x->elt_type() == T_OBJECT;
bool needs_store_check = obj_store && (x->value()->as_Constant() == NULL ||
!get_jobject_constant(x->value())->is_null_object() ||
x->should_profile());
LIRItem array(x->array(), this);
LIRItem index(x->index(), this);
LIRItem value(x->value(), this);
LIRItem length(this);
array.load_item();
index.load_nonconstant();
if (use_length && needs_range_check) {
length.set_instruction(x->length());
length.load_item();
}
if (needs_store_check || x->check_boolean()) {
value.load_item();
} else {
value.load_for_store(x->elt_type());
}
set_no_result(x);
// the CodeEmitInfo must be duplicated for each different
// LIR-instruction because spilling can occur anywhere between two
// instructions and so the debug information must be different
CodeEmitInfo* range_check_info = state_for(x);
CodeEmitInfo* null_check_info = NULL;
if (x->needs_null_check()) {
null_check_info = new CodeEmitInfo(range_check_info);
}
// emit array address setup early so it schedules better
LIR_Address* array_addr = emit_array_address(array.result(), index.result(), x->elt_type(), obj_store);
if (GenerateRangeChecks && needs_range_check) {
if (use_length) {
__ cmp(lir_cond_belowEqual, length.result(), index.result());
__ branch(lir_cond_belowEqual, T_INT, new RangeCheckStub(range_check_info, index.result()));
} else {
array_range_check(array.result(), index.result(), null_check_info, range_check_info);
// range_check also does the null check
null_check_info = NULL;
}
}
if (GenerateArrayStoreCheck && needs_store_check) {
LIR_Opr tmp1 = FrameMap::G1_opr;
LIR_Opr tmp2 = FrameMap::G3_opr;
LIR_Opr tmp3 = FrameMap::G5_opr;
CodeEmitInfo* store_check_info = new CodeEmitInfo(range_check_info);
__ store_check(value.result(), array.result(), tmp1, tmp2, tmp3, store_check_info, x->profiled_method(), x->profiled_bci());
}
if (obj_store) {
// Needs GC write barriers.
pre_barrier(LIR_OprFact::address(array_addr), LIR_OprFact::illegalOpr /* pre_val */,
true /* do_load */, false /* patch */, NULL);
}
LIR_Opr result = maybe_mask_boolean(x, array.result(), value.result(), null_check_info);
__ move(result, array_addr, null_check_info);
if (obj_store) {
// Precise card mark
post_barrier(LIR_OprFact::address(array_addr), value.result());
}
}
void LIRGenerator::do_MonitorEnter(MonitorEnter* x) {
assert(x->is_pinned(),"");
LIRItem obj(x->obj(), this);
obj.load_item();
set_no_result(x);
LIR_Opr lock = FrameMap::G1_opr;
LIR_Opr scratch = FrameMap::G3_opr;
LIR_Opr hdr = FrameMap::G4_opr;
CodeEmitInfo* info_for_exception = NULL;
if (x->needs_null_check()) {
info_for_exception = state_for(x);
}
// this CodeEmitInfo must not have the xhandlers because here the
// object is already locked (xhandlers expects object to be unlocked)
CodeEmitInfo* info = state_for(x, x->state(), true);
monitor_enter(obj.result(), lock, hdr, scratch, x->monitor_no(), info_for_exception, info);
}
void LIRGenerator::do_MonitorExit(MonitorExit* x) {
assert(x->is_pinned(),"");
LIRItem obj(x->obj(), this);
obj.dont_load_item();
set_no_result(x);
LIR_Opr lock = FrameMap::G1_opr;
LIR_Opr hdr = FrameMap::G3_opr;
LIR_Opr obj_temp = FrameMap::G4_opr;
monitor_exit(obj_temp, lock, hdr, LIR_OprFact::illegalOpr, x->monitor_no());
}
// _ineg, _lneg, _fneg, _dneg
void LIRGenerator::do_NegateOp(NegateOp* x) {
LIRItem value(x->x(), this);
value.load_item();
LIR_Opr reg = rlock_result(x);
__ negate(value.result(), reg);
}
// for _fadd, _fmul, _fsub, _fdiv, _frem
// _dadd, _dmul, _dsub, _ddiv, _drem
void LIRGenerator::do_ArithmeticOp_FPU(ArithmeticOp* x) {
switch (x->op()) {
case Bytecodes::_fadd:
case Bytecodes::_fmul:
case Bytecodes::_fsub:
case Bytecodes::_fdiv:
case Bytecodes::_dadd:
case Bytecodes::_dmul:
case Bytecodes::_dsub:
case Bytecodes::_ddiv: {
LIRItem left(x->x(), this);
LIRItem right(x->y(), this);
left.load_item();
right.load_item();
rlock_result(x);
arithmetic_op_fpu(x->op(), x->operand(), left.result(), right.result(), x->is_strictfp());
}
break;
case Bytecodes::_frem:
case Bytecodes::_drem: {
address entry;
switch (x->op()) {
case Bytecodes::_frem:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::frem);
break;
case Bytecodes::_drem:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::drem);
break;
default:
ShouldNotReachHere();
}
LIR_Opr result = call_runtime(x->x(), x->y(), entry, x->type(), NULL);
set_result(x, result);
}
break;
default: ShouldNotReachHere();
}
}
// for _ladd, _lmul, _lsub, _ldiv, _lrem
void LIRGenerator::do_ArithmeticOp_Long(ArithmeticOp* x) {
switch (x->op()) {
case Bytecodes::_lrem:
case Bytecodes::_lmul:
case Bytecodes::_ldiv: {
if (x->op() == Bytecodes::_ldiv || x->op() == Bytecodes::_lrem) {
LIRItem right(x->y(), this);
right.load_item();
CodeEmitInfo* info = state_for(x);
LIR_Opr item = right.result();
assert(item->is_register(), "must be");
__ cmp(lir_cond_equal, item, LIR_OprFact::longConst(0));
__ branch(lir_cond_equal, T_LONG, new DivByZeroStub(info));
}
address entry;
switch (x->op()) {
case Bytecodes::_lrem:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::lrem);
break; // check if dividend is 0 is done elsewhere
case Bytecodes::_ldiv:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::ldiv);
break; // check if dividend is 0 is done elsewhere
case Bytecodes::_lmul:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::lmul);
break;
default:
ShouldNotReachHere();
}
// order of arguments to runtime call is reversed.
LIR_Opr result = call_runtime(x->y(), x->x(), entry, x->type(), NULL);
set_result(x, result);
break;
}
case Bytecodes::_ladd:
case Bytecodes::_lsub: {
LIRItem left(x->x(), this);
LIRItem right(x->y(), this);
left.load_item();
right.load_item();
rlock_result(x);
arithmetic_op_long(x->op(), x->operand(), left.result(), right.result(), NULL);
break;
}
default: ShouldNotReachHere();
}
}
// Returns if item is an int constant that can be represented by a simm13
static bool is_simm13(LIR_Opr item) {
if (item->is_constant() && item->type() == T_INT) {
return Assembler::is_simm13(item->as_constant_ptr()->as_jint());
} else {
return false;
}
}
// for: _iadd, _imul, _isub, _idiv, _irem
void LIRGenerator::do_ArithmeticOp_Int(ArithmeticOp* x) {
bool is_div_rem = x->op() == Bytecodes::_idiv || x->op() == Bytecodes::_irem;
LIRItem left(x->x(), this);
LIRItem right(x->y(), this);
// missing test if instr is commutative and if we should swap
right.load_nonconstant();
assert(right.is_constant() || right.is_register(), "wrong state of right");
left.load_item();
rlock_result(x);
if (is_div_rem) {
CodeEmitInfo* info = state_for(x);
LIR_Opr tmp = FrameMap::G1_opr;
if (x->op() == Bytecodes::_irem) {
__ irem(left.result(), right.result(), x->operand(), tmp, info);
} else if (x->op() == Bytecodes::_idiv) {
__ idiv(left.result(), right.result(), x->operand(), tmp, info);
}
} else {
arithmetic_op_int(x->op(), x->operand(), left.result(), right.result(), FrameMap::G1_opr);
}
}
void LIRGenerator::do_ArithmeticOp(ArithmeticOp* x) {
ValueTag tag = x->type()->tag();
assert(x->x()->type()->tag() == tag && x->y()->type()->tag() == tag, "wrong parameters");
switch (tag) {
case floatTag:
case doubleTag: do_ArithmeticOp_FPU(x); return;
case longTag: do_ArithmeticOp_Long(x); return;
case intTag: do_ArithmeticOp_Int(x); return;
}
ShouldNotReachHere();
}
// _ishl, _lshl, _ishr, _lshr, _iushr, _lushr
void LIRGenerator::do_ShiftOp(ShiftOp* x) {
LIRItem value(x->x(), this);
LIRItem count(x->y(), this);
// Long shift destroys count register
if (value.type()->is_long()) {
count.set_destroys_register();
}
value.load_item();
// the old backend doesn't support this
if (count.is_constant() && count.type()->as_IntConstant() != NULL && value.type()->is_int()) {
jint c = count.get_jint_constant() & 0x1f;
assert(c >= 0 && c < 32, "should be small");
count.dont_load_item();
} else {
count.load_item();
}
LIR_Opr reg = rlock_result(x);
shift_op(x->op(), reg, value.result(), count.result(), LIR_OprFact::illegalOpr);
}
// _iand, _land, _ior, _lor, _ixor, _lxor
void LIRGenerator::do_LogicOp(LogicOp* x) {
LIRItem left(x->x(), this);
LIRItem right(x->y(), this);
left.load_item();
right.load_nonconstant();
LIR_Opr reg = rlock_result(x);
logic_op(x->op(), reg, left.result(), right.result());
}
// _lcmp, _fcmpl, _fcmpg, _dcmpl, _dcmpg
void LIRGenerator::do_CompareOp(CompareOp* x) {
LIRItem left(x->x(), this);
LIRItem right(x->y(), this);
left.load_item();
right.load_item();
LIR_Opr reg = rlock_result(x);
if (x->x()->type()->is_float_kind()) {
Bytecodes::Code code = x->op();
__ fcmp2int(left.result(), right.result(), reg, (code == Bytecodes::_fcmpl || code == Bytecodes::_dcmpl));
} else if (x->x()->type()->tag() == longTag) {
__ lcmp2int(left.result(), right.result(), reg);
} else {
Unimplemented();
}
}
void LIRGenerator::do_CompareAndSwap(Intrinsic* x, ValueType* type) {
assert(x->number_of_arguments() == 4, "wrong type");
LIRItem obj (x->argument_at(0), this); // object
LIRItem offset(x->argument_at(1), this); // offset of field
LIRItem cmp (x->argument_at(2), this); // value to compare with field
LIRItem val (x->argument_at(3), this); // replace field with val if matches cmp
// Use temps to avoid kills
LIR_Opr t1 = FrameMap::G1_opr;
LIR_Opr t2 = FrameMap::G3_opr;
LIR_Opr addr = new_pointer_register();
// get address of field
obj.load_item();
offset.load_item();
cmp.load_item();
val.load_item();
__ add(obj.result(), offset.result(), addr);
if (type == objectType) { // Write-barrier needed for Object fields.
pre_barrier(addr, LIR_OprFact::illegalOpr /* pre_val */,
true /* do_load */, false /* patch */, NULL);
}
if (type == objectType)
__ cas_obj(addr, cmp.result(), val.result(), t1, t2);
else if (type == intType)
__ cas_int(addr, cmp.result(), val.result(), t1, t2);
else if (type == longType)
__ cas_long(addr, cmp.result(), val.result(), t1, t2);
else {
ShouldNotReachHere();
}
// generate conditional move of boolean result
LIR_Opr result = rlock_result(x);
__ cmove(lir_cond_equal, LIR_OprFact::intConst(1), LIR_OprFact::intConst(0),
result, as_BasicType(type));
if (type == objectType) { // Write-barrier needed for Object fields.
// Precise card mark since could either be object or array
post_barrier(addr, val.result());
}
}
void LIRGenerator::do_MathIntrinsic(Intrinsic* x) {
switch (x->id()) {
case vmIntrinsics::_dabs:
case vmIntrinsics::_dsqrt: {
assert(x->number_of_arguments() == 1, "wrong type");
LIRItem value(x->argument_at(0), this);
value.load_item();
LIR_Opr dst = rlock_result(x);
switch (x->id()) {
case vmIntrinsics::_dsqrt: {
__ sqrt(value.result(), dst, LIR_OprFact::illegalOpr);
break;
}
case vmIntrinsics::_dabs: {
__ abs(value.result(), dst, LIR_OprFact::illegalOpr);
break;
}
}
break;
}
case vmIntrinsics::_dlog10: // fall through
case vmIntrinsics::_dlog: // fall through
case vmIntrinsics::_dsin: // fall through
case vmIntrinsics::_dtan: // fall through
case vmIntrinsics::_dcos: // fall through
case vmIntrinsics::_dexp: {
assert(x->number_of_arguments() == 1, "wrong type");
address runtime_entry = NULL;
switch (x->id()) {
case vmIntrinsics::_dsin:
runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dsin);
break;
case vmIntrinsics::_dcos:
runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dcos);
break;
case vmIntrinsics::_dtan:
runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dtan);
break;
case vmIntrinsics::_dlog:
runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dlog);
break;
case vmIntrinsics::_dlog10:
runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dlog10);
break;
case vmIntrinsics::_dexp:
runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dexp);
break;
default:
ShouldNotReachHere();
}
LIR_Opr result = call_runtime(x->argument_at(0), runtime_entry, x->type(), NULL);
set_result(x, result);
break;
}
case vmIntrinsics::_dpow: {
assert(x->number_of_arguments() == 2, "wrong type");
address runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
LIR_Opr result = call_runtime(x->argument_at(0), x->argument_at(1), runtime_entry, x->type(), NULL);
set_result(x, result);
break;
}
}
}
void LIRGenerator::do_ArrayCopy(Intrinsic* x) {
assert(x->number_of_arguments() == 5, "wrong type");
// Make all state_for calls early since they can emit code
CodeEmitInfo* info = state_for(x, x->state());
// Note: spill caller save before setting the item
LIRItem src (x->argument_at(0), this);
LIRItem src_pos (x->argument_at(1), this);
LIRItem dst (x->argument_at(2), this);
LIRItem dst_pos (x->argument_at(3), this);
LIRItem length (x->argument_at(4), this);
// load all values in callee_save_registers, as this makes the
// parameter passing to the fast case simpler
src.load_item_force (rlock_callee_saved(T_OBJECT));
src_pos.load_item_force (rlock_callee_saved(T_INT));
dst.load_item_force (rlock_callee_saved(T_OBJECT));
dst_pos.load_item_force (rlock_callee_saved(T_INT));
length.load_item_force (rlock_callee_saved(T_INT));
int flags;
ciArrayKlass* expected_type;
arraycopy_helper(x, &flags, &expected_type);
__ arraycopy(src.result(), src_pos.result(), dst.result(), dst_pos.result(),
length.result(), rlock_callee_saved(T_INT),
expected_type, flags, info);
set_no_result(x);
}
void LIRGenerator::do_update_CRC32(Intrinsic* x) {
// Make all state_for calls early since they can emit code
LIR_Opr result = rlock_result(x);
int flags = 0;
switch (x->id()) {
case vmIntrinsics::_updateCRC32: {
LIRItem crc(x->argument_at(0), this);
LIRItem val(x->argument_at(1), this);
// val is destroyed by update_crc32
val.set_destroys_register();
crc.load_item();
val.load_item();
__ update_crc32(crc.result(), val.result(), result);
break;
}
case vmIntrinsics::_updateBytesCRC32:
case vmIntrinsics::_updateByteBufferCRC32: {
bool is_updateBytes = (x->id() == vmIntrinsics::_updateBytesCRC32);
LIRItem crc(x->argument_at(0), this);
LIRItem buf(x->argument_at(1), this);
LIRItem off(x->argument_at(2), this);
LIRItem len(x->argument_at(3), this);
buf.load_item();
off.load_nonconstant();
LIR_Opr index = off.result();
int offset = is_updateBytes ? arrayOopDesc::base_offset_in_bytes(T_BYTE) : 0;
if(off.result()->is_constant()) {
index = LIR_OprFact::illegalOpr;
offset += off.result()->as_jint();
}
LIR_Opr base_op = buf.result();
if (index->is_valid()) {
LIR_Opr tmp = new_register(T_LONG);
__ convert(Bytecodes::_i2l, index, tmp);
index = tmp;
if (index->is_constant()) {
offset += index->as_constant_ptr()->as_jint();
index = LIR_OprFact::illegalOpr;
} else if (index->is_register()) {
LIR_Opr tmp2 = new_register(T_LONG);
LIR_Opr tmp3 = new_register(T_LONG);
__ move(base_op, tmp2);
__ move(index, tmp3);
__ add(tmp2, tmp3, tmp2);
base_op = tmp2;
} else {
ShouldNotReachHere();
}
}
LIR_Address* a = new LIR_Address(base_op, offset, T_BYTE);
BasicTypeList signature(3);
signature.append(T_INT);
signature.append(T_ADDRESS);
signature.append(T_INT);
CallingConvention* cc = frame_map()->c_calling_convention(&signature);
const LIR_Opr result_reg = result_register_for(x->type());
LIR_Opr addr = new_pointer_register();
__ leal(LIR_OprFact::address(a), addr);
crc.load_item_force(cc->at(0));
__ move(addr, cc->at(1));
len.load_item_force(cc->at(2));
__ call_runtime_leaf(StubRoutines::updateBytesCRC32(), getThreadTemp(), result_reg, cc->args());
__ move(result_reg, result);
break;
}
default: {
ShouldNotReachHere();
}
}
}
void LIRGenerator::do_update_CRC32C(Intrinsic* x) {
// Make all state_for calls early since they can emit code
LIR_Opr result = rlock_result(x);
int flags = 0;
switch (x->id()) {
case vmIntrinsics::_updateBytesCRC32C:
case vmIntrinsics::_updateDirectByteBufferCRC32C: {
bool is_updateBytes = (x->id() == vmIntrinsics::_updateBytesCRC32C);
int array_offset = is_updateBytes ? arrayOopDesc::base_offset_in_bytes(T_BYTE) : 0;
LIRItem crc(x->argument_at(0), this);
LIRItem buf(x->argument_at(1), this);
LIRItem off(x->argument_at(2), this);
LIRItem end(x->argument_at(3), this);
buf.load_item();
off.load_nonconstant();
end.load_nonconstant();
// len = end - off
LIR_Opr len = end.result();
LIR_Opr tmpA = new_register(T_INT);
LIR_Opr tmpB = new_register(T_INT);
__ move(end.result(), tmpA);
__ move(off.result(), tmpB);
__ sub(tmpA, tmpB, tmpA);
len = tmpA;
LIR_Opr index = off.result();
if(off.result()->is_constant()) {
index = LIR_OprFact::illegalOpr;
array_offset += off.result()->as_jint();
}
LIR_Opr base_op = buf.result();
if (index->is_valid()) {
LIR_Opr tmp = new_register(T_LONG);
__ convert(Bytecodes::_i2l, index, tmp);
index = tmp;
if (index->is_constant()) {
array_offset += index->as_constant_ptr()->as_jint();
index = LIR_OprFact::illegalOpr;
} else if (index->is_register()) {
LIR_Opr tmp2 = new_register(T_LONG);
LIR_Opr tmp3 = new_register(T_LONG);
__ move(base_op, tmp2);
__ move(index, tmp3);
__ add(tmp2, tmp3, tmp2);
base_op = tmp2;
} else {
ShouldNotReachHere();
}
}
LIR_Address* a = new LIR_Address(base_op, array_offset, T_BYTE);
BasicTypeList signature(3);
signature.append(T_INT);
signature.append(T_ADDRESS);
signature.append(T_INT);
CallingConvention* cc = frame_map()->c_calling_convention(&signature);
const LIR_Opr result_reg = result_register_for(x->type());
LIR_Opr addr = new_pointer_register();
__ leal(LIR_OprFact::address(a), addr);
crc.load_item_force(cc->at(0));
__ move(addr, cc->at(1));
__ move(len, cc->at(2));
__ call_runtime_leaf(StubRoutines::updateBytesCRC32C(), getThreadTemp(), result_reg, cc->args());
__ move(result_reg, result);
break;
}
default: {
ShouldNotReachHere();
}
}
}
void LIRGenerator::do_FmaIntrinsic(Intrinsic* x) {
fatal("FMA intrinsic is not implemented on this platform");
}
void LIRGenerator::do_vectorizedMismatch(Intrinsic* x) {
fatal("vectorizedMismatch intrinsic is not implemented on this platform");
}
// _i2l, _i2f, _i2d, _l2i, _l2f, _l2d, _f2i, _f2l, _f2d, _d2i, _d2l, _d2f
// _i2b, _i2c, _i2s
void LIRGenerator::do_Convert(Convert* x) {
switch (x->op()) {
case Bytecodes::_f2l:
case Bytecodes::_d2l:
case Bytecodes::_d2i:
case Bytecodes::_l2f:
case Bytecodes::_l2d: {
address entry;
switch (x->op()) {
case Bytecodes::_l2f:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::l2f);
break;
case Bytecodes::_l2d:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::l2d);
break;
case Bytecodes::_f2l:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::f2l);
break;
case Bytecodes::_d2l:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::d2l);
break;
case Bytecodes::_d2i:
entry = CAST_FROM_FN_PTR(address, SharedRuntime::d2i);
break;
default:
ShouldNotReachHere();
}
LIR_Opr result = call_runtime(x->value(), entry, x->type(), NULL);
set_result(x, result);
break;
}
case Bytecodes::_i2f:
case Bytecodes::_i2d: {
LIRItem value(x->value(), this);
LIR_Opr reg = rlock_result(x);
// To convert an int to double, we need to load the 32-bit int
// from memory into a single precision floating point register
// (even numbered). Then the sparc fitod instruction takes care
// of the conversion. This is a bit ugly, but is the best way to
// get the int value in a single precision floating point register
value.load_item();
LIR_Opr tmp = force_to_spill(value.result(), T_FLOAT);
__ convert(x->op(), tmp, reg);
break;
}
break;
case Bytecodes::_i2l:
case Bytecodes::_i2b:
case Bytecodes::_i2c:
case Bytecodes::_i2s:
case Bytecodes::_l2i:
case Bytecodes::_f2d:
case Bytecodes::_d2f: { // inline code
LIRItem value(x->value(), this);
value.load_item();
LIR_Opr reg = rlock_result(x);
__ convert(x->op(), value.result(), reg, false);
}
break;
case Bytecodes::_f2i: {
LIRItem value (x->value(), this);
value.set_destroys_register();
value.load_item();
LIR_Opr reg = rlock_result(x);
set_vreg_flag(reg, must_start_in_memory);
__ convert(x->op(), value.result(), reg, false);
}
break;
default: ShouldNotReachHere();
}
}
void LIRGenerator::do_NewInstance(NewInstance* x) {
print_if_not_loaded(x);
// This instruction can be deoptimized in the slow path : use
// O0 as result register.
const LIR_Opr reg = result_register_for(x->type());
CodeEmitInfo* info = state_for(x, x->state());
LIR_Opr tmp1 = FrameMap::G1_oop_opr;
LIR_Opr tmp2 = FrameMap::G3_oop_opr;
LIR_Opr tmp3 = FrameMap::G4_oop_opr;
LIR_Opr tmp4 = FrameMap::O1_oop_opr;
LIR_Opr klass_reg = FrameMap::G5_metadata_opr;
new_instance(reg, x->klass(), x->is_unresolved(), tmp1, tmp2, tmp3, tmp4, klass_reg, info);
LIR_Opr result = rlock_result(x);
__ move(reg, result);
}
void LIRGenerator::do_NewTypeArray(NewTypeArray* x) {
// Evaluate state_for early since it may emit code
CodeEmitInfo* info = state_for(x, x->state());
LIRItem length(x->length(), this);
length.load_item();
LIR_Opr reg = result_register_for(x->type());
LIR_Opr tmp1 = FrameMap::G1_oop_opr;
LIR_Opr tmp2 = FrameMap::G3_oop_opr;
LIR_Opr tmp3 = FrameMap::G4_oop_opr;
LIR_Opr tmp4 = FrameMap::O1_oop_opr;
LIR_Opr klass_reg = FrameMap::G5_metadata_opr;
LIR_Opr len = length.result();
BasicType elem_type = x->elt_type();
__ metadata2reg(ciTypeArrayKlass::make(elem_type)->constant_encoding(), klass_reg);
CodeStub* slow_path = new NewTypeArrayStub(klass_reg, len, reg, info);
__ allocate_array(reg, len, tmp1, tmp2, tmp3, tmp4, elem_type, klass_reg, slow_path);
LIR_Opr result = rlock_result(x);
__ move(reg, result);
}
void LIRGenerator::do_NewObjectArray(NewObjectArray* x) {
// Evaluate state_for early since it may emit code.
CodeEmitInfo* info = state_for(x, x->state());
// in case of patching (i.e., object class is not yet loaded), we need to reexecute the instruction
// and therefore provide the state before the parameters have been consumed
CodeEmitInfo* patching_info = NULL;
if (!x->klass()->is_loaded() || PatchALot) {
patching_info = state_for(x, x->state_before());
}
LIRItem length(x->length(), this);
length.load_item();
const LIR_Opr reg = result_register_for(x->type());
LIR_Opr tmp1 = FrameMap::G1_oop_opr;
LIR_Opr tmp2 = FrameMap::G3_oop_opr;
LIR_Opr tmp3 = FrameMap::G4_oop_opr;
LIR_Opr tmp4 = FrameMap::O1_oop_opr;
LIR_Opr klass_reg = FrameMap::G5_metadata_opr;
LIR_Opr len = length.result();
CodeStub* slow_path = new NewObjectArrayStub(klass_reg, len, reg, info);
ciMetadata* obj = ciObjArrayKlass::make(x->klass());
if (obj == ciEnv::unloaded_ciobjarrayklass()) {
BAILOUT("encountered unloaded_ciobjarrayklass due to out of memory error");
}
klass2reg_with_patching(klass_reg, obj, patching_info);
__ allocate_array(reg, len, tmp1, tmp2, tmp3, tmp4, T_OBJECT, klass_reg, slow_path);
LIR_Opr result = rlock_result(x);
__ move(reg, result);
}
void LIRGenerator::do_NewMultiArray(NewMultiArray* x) {
Values* dims = x->dims();
int i = dims->length();
LIRItemList* items = new LIRItemList(i, i, NULL);
while (i-- > 0) {
LIRItem* size = new LIRItem(dims->at(i), this);
items->at_put(i, size);
}
// Evaluate state_for early since it may emit code.
CodeEmitInfo* patching_info = NULL;
if (!x->klass()->is_loaded() || PatchALot) {
patching_info = state_for(x, x->state_before());
// Cannot re-use same xhandlers for multiple CodeEmitInfos, so
// clone all handlers (NOTE: Usually this is handled transparently
// by the CodeEmitInfo cloning logic in CodeStub constructors but
// is done explicitly here because a stub isn't being used).
x->set_exception_handlers(new XHandlers(x->exception_handlers()));
}
CodeEmitInfo* info = state_for(x, x->state());
i = dims->length();
while (i-- > 0) {
LIRItem* size = items->at(i);
size->load_item();
store_stack_parameter (size->result(),
in_ByteSize(STACK_BIAS +
frame::memory_parameter_word_sp_offset * wordSize +
i * sizeof(jint)));
}
// This instruction can be deoptimized in the slow path : use
// O0 as result register.
const LIR_Opr klass_reg = FrameMap::O0_metadata_opr;
klass2reg_with_patching(klass_reg, x->klass(), patching_info);
LIR_Opr rank = FrameMap::O1_opr;
__ move(LIR_OprFact::intConst(x->rank()), rank);
LIR_Opr varargs = FrameMap::as_pointer_opr(O2);
int offset_from_sp = (frame::memory_parameter_word_sp_offset * wordSize) + STACK_BIAS;
__ add(FrameMap::SP_opr,
LIR_OprFact::intptrConst(offset_from_sp),
varargs);
LIR_OprList* args = new LIR_OprList(3);
args->append(klass_reg);
args->append(rank);
args->append(varargs);
const LIR_Opr reg = result_register_for(x->type());
__ call_runtime(Runtime1::entry_for(Runtime1::new_multi_array_id),
LIR_OprFact::illegalOpr,
reg, args, info);
LIR_Opr result = rlock_result(x);
__ move(reg, result);
}
void LIRGenerator::do_BlockBegin(BlockBegin* x) {
}
void LIRGenerator::do_CheckCast(CheckCast* x) {
LIRItem obj(x->obj(), this);
CodeEmitInfo* patching_info = NULL;
if (!x->klass()->is_loaded() || (PatchALot && !x->is_incompatible_class_change_check())) {
// must do this before locking the destination register as an oop register,
// and before the obj is loaded (so x->obj()->item() is valid for creating a debug info location)
patching_info = state_for(x, x->state_before());
}
obj.load_item();
LIR_Opr out_reg = rlock_result(x);
CodeStub* stub;
CodeEmitInfo* info_for_exception =
(x->needs_exception_state() ? state_for(x) :
state_for(x, x->state_before(), true /*ignore_xhandler*/));
if (x->is_incompatible_class_change_check()) {
assert(patching_info == NULL, "can't patch this");
stub = new SimpleExceptionStub(Runtime1::throw_incompatible_class_change_error_id, LIR_OprFact::illegalOpr, info_for_exception);
} else if (x->is_invokespecial_receiver_check()) {
assert(patching_info == NULL, "can't patch this");
stub = new DeoptimizeStub(info_for_exception,
Deoptimization::Reason_class_check,
Deoptimization::Action_none);
} else {
stub = new SimpleExceptionStub(Runtime1::throw_class_cast_exception_id, obj.result(), info_for_exception);
}
LIR_Opr tmp1 = FrameMap::G1_oop_opr;
LIR_Opr tmp2 = FrameMap::G3_oop_opr;
LIR_Opr tmp3 = FrameMap::G4_oop_opr;
__ checkcast(out_reg, obj.result(), x->klass(), tmp1, tmp2, tmp3,
x->direct_compare(), info_for_exception, patching_info, stub,
x->profiled_method(), x->profiled_bci());
}
void LIRGenerator::do_InstanceOf(InstanceOf* x) {
LIRItem obj(x->obj(), this);
CodeEmitInfo* patching_info = NULL;
if (!x->klass()->is_loaded() || PatchALot) {
patching_info = state_for(x, x->state_before());
}
// ensure the result register is not the input register because the result is initialized before the patching safepoint
obj.load_item();
LIR_Opr out_reg = rlock_result(x);
LIR_Opr tmp1 = FrameMap::G1_oop_opr;
LIR_Opr tmp2 = FrameMap::G3_oop_opr;
LIR_Opr tmp3 = FrameMap::G4_oop_opr;
__ instanceof(out_reg, obj.result(), x->klass(), tmp1, tmp2, tmp3,
x->direct_compare(), patching_info,
x->profiled_method(), x->profiled_bci());
}
void LIRGenerator::do_If(If* x) {
assert(x->number_of_sux() == 2, "inconsistency");
ValueTag tag = x->x()->type()->tag();
LIRItem xitem(x->x(), this);
LIRItem yitem(x->y(), this);
LIRItem* xin = &xitem;
LIRItem* yin = &yitem;
If::Condition cond = x->cond();
if (tag == longTag) {
// for longs, only conditions "eql", "neq", "lss", "geq" are valid;
// mirror for other conditions
if (cond == If::gtr || cond == If::leq) {
// swap inputs
cond = Instruction::mirror(cond);
xin = &yitem;
yin = &xitem;
}
xin->set_destroys_register();
}
LIR_Opr left = LIR_OprFact::illegalOpr;
LIR_Opr right = LIR_OprFact::illegalOpr;
xin->load_item();
left = xin->result();
if (is_simm13(yin->result())) {
// inline int constants which are small enough to be immediate operands
right = LIR_OprFact::value_type(yin->value()->type());
} else if (tag == longTag && yin->is_constant() && yin->get_jlong_constant() == 0 &&
(cond == If::eql || cond == If::neq)) {
// inline long zero
right = LIR_OprFact::value_type(yin->value()->type());
} else if (tag == objectTag && yin->is_constant() && (yin->get_jobject_constant()->is_null_object())) {
right = LIR_OprFact::value_type(yin->value()->type());
} else {
yin->load_item();
right = yin->result();
}
set_no_result(x);
// add safepoint before generating condition code so it can be recomputed
if (x->is_safepoint()) {
// increment backedge counter if needed
increment_backedge_counter(state_for(x, x->state_before()), x->profiled_bci());
__ safepoint(new_register(T_INT), state_for(x, x->state_before()));
}
__ cmp(lir_cond(cond), left, right);
// Generate branch profiling. Profiling code doesn't kill flags.
profile_branch(x, cond);
move_to_phi(x->state());
if (x->x()->type()->is_float_kind()) {
__ branch(lir_cond(cond), right->type(), x->tsux(), x->usux());
} else {
__ branch(lir_cond(cond), right->type(), x->tsux());
}
assert(x->default_sux() == x->fsux(), "wrong destination above");
__ jump(x->default_sux());
}
LIR_Opr LIRGenerator::getThreadPointer() {
return FrameMap::as_pointer_opr(G2);
}
void LIRGenerator::trace_block_entry(BlockBegin* block) {
__ move(LIR_OprFact::intConst(block->block_id()), FrameMap::O0_opr);
LIR_OprList* args = new LIR_OprList(1);
args->append(FrameMap::O0_opr);
address func = CAST_FROM_FN_PTR(address, Runtime1::trace_block_entry);
__ call_runtime_leaf(func, rlock_callee_saved(T_INT), LIR_OprFact::illegalOpr, args);
}
void LIRGenerator::volatile_field_store(LIR_Opr value, LIR_Address* address,
CodeEmitInfo* info) {
#ifdef _LP64
__ store(value, address, info);
#else
__ volatile_store_mem_reg(value, address, info);
#endif
}
void LIRGenerator::volatile_field_load(LIR_Address* address, LIR_Opr result,
CodeEmitInfo* info) {
#ifdef _LP64
__ load(address, result, info);
#else
__ volatile_load_mem_reg(address, result, info);
#endif
}
void LIRGenerator::put_Object_unsafe(LIR_Opr src, LIR_Opr offset, LIR_Opr data,
BasicType type, bool is_volatile) {
LIR_Opr base_op = src;
LIR_Opr index_op = offset;
bool is_obj = (type == T_ARRAY || type == T_OBJECT);
#ifndef _LP64
if (is_volatile && type == T_LONG) {
__ volatile_store_unsafe_reg(data, src, offset, type, NULL, lir_patch_none);
} else
#endif
{
if (type == T_BOOLEAN) {
type = T_BYTE;
}
LIR_Address* addr;
if (type == T_ARRAY || type == T_OBJECT) {
LIR_Opr tmp = new_pointer_register();
__ add(base_op, index_op, tmp);
addr = new LIR_Address(tmp, type);
} else {
addr = new LIR_Address(base_op, index_op, type);
}
if (is_obj) {
pre_barrier(LIR_OprFact::address(addr), LIR_OprFact::illegalOpr /* pre_val */,
true /* do_load */, false /* patch */, NULL);
// _bs->c1_write_barrier_pre(this, LIR_OprFact::address(addr));
}
__ move(data, addr);
if (is_obj) {
// This address is precise
post_barrier(LIR_OprFact::address(addr), data);
}
}
}
void LIRGenerator::get_Object_unsafe(LIR_Opr dst, LIR_Opr src, LIR_Opr offset,
BasicType type, bool is_volatile) {
#ifndef _LP64
if (is_volatile && type == T_LONG) {
__ volatile_load_unsafe_reg(src, offset, dst, type, NULL, lir_patch_none);
} else
#endif
{
LIR_Address* addr = new LIR_Address(src, offset, type);
__ load(addr, dst);
}
}
void LIRGenerator::do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x) {
BasicType type = x->basic_type();
LIRItem src(x->object(), this);
LIRItem off(x->offset(), this);
LIRItem value(x->value(), this);
src.load_item();
value.load_item();
off.load_nonconstant();
LIR_Opr dst = rlock_result(x, type);
LIR_Opr data = value.result();
bool is_obj = (type == T_ARRAY || type == T_OBJECT);
LIR_Opr offset = off.result();
// Because we want a 2-arg form of xchg
__ move(data, dst);
assert (!x->is_add() && (type == T_INT || (is_obj LP64_ONLY(&& UseCompressedOops))), "unexpected type");
LIR_Address* addr;
if (offset->is_constant()) {
#ifdef _LP64
jlong l = offset->as_jlong();
assert((jlong)((jint)l) == l, "offset too large for constant");
jint c = (jint)l;
#else
jint c = offset->as_jint();
#endif
addr = new LIR_Address(src.result(), c, type);
} else {
addr = new LIR_Address(src.result(), offset, type);
}
LIR_Opr tmp = LIR_OprFact::illegalOpr;
LIR_Opr ptr = LIR_OprFact::illegalOpr;
if (is_obj) {
// Do the pre-write barrier, if any.
// barriers on sparc don't work with a base + index address
tmp = FrameMap::G3_opr;
ptr = new_pointer_register();
__ add(src.result(), off.result(), ptr);
pre_barrier(ptr, LIR_OprFact::illegalOpr /* pre_val */,
true /* do_load */, false /* patch */, NULL);
}
__ xchg(LIR_OprFact::address(addr), dst, dst, tmp);
if (is_obj) {
// Seems to be a precise address
post_barrier(ptr, data);
}
}
| gpl-2.0 |
Jetson-TX1-AndroidTV/android_kernel_jetson_tx1_hdmi_primary | drivers/gpu/nvgpu/gm20b/acr_gm20b.c | 6 | 44985 | /*
* Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*/
#include <linux/delay.h> /* for mdelay */
#include <linux/firmware.h>
#include <linux/clk.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include "../../../../arch/arm/mach-tegra/iomap.h"
#include <linux/platform/tegra/mc.h>
#include "gk20a/gk20a.h"
#include "gk20a/pmu_gk20a.h"
#include "gk20a/semaphore_gk20a.h"
#include "hw_pwr_gm20b.h"
/*Defines*/
#define gm20b_dbg_pmu(fmt, arg...) \
gk20a_dbg(gpu_dbg_pmu, fmt, ##arg)
typedef int (*get_ucode_details)(struct gk20a *g, struct flcn_ucode_img *udata);
/*Externs*/
/*Forwards*/
static int lsfm_discover_ucode_images(struct gk20a *g,
struct ls_flcn_mgr *plsfm);
static int lsfm_add_ucode_img(struct gk20a *g, struct ls_flcn_mgr *plsfm,
struct flcn_ucode_img *ucode_image, u32 falcon_id);
static void lsfm_free_ucode_img_res(struct flcn_ucode_img *p_img);
static void lsfm_free_nonpmu_ucode_img_res(struct flcn_ucode_img *p_img);
static int lsf_gen_wpr_requirements(struct gk20a *g, struct ls_flcn_mgr *plsfm);
static int lsfm_init_wpr_contents(struct gk20a *g, struct ls_flcn_mgr *plsfm,
void *nonwpr_addr);
static int acr_ucode_patch_sig(struct gk20a *g,
unsigned int *p_img,
unsigned int *p_prod_sig,
unsigned int *p_dbg_sig,
unsigned int *p_patch_loc,
unsigned int *p_patch_ind);
static void free_acr_resources(struct gk20a *g, struct ls_flcn_mgr *plsfm);
/*Globals*/
static get_ucode_details pmu_acr_supp_ucode_list[] = {
pmu_ucode_details,
fecs_ucode_details,
gpccs_ucode_details,
};
/*Once is LS mode, cpuctl_alias is only accessible*/
static void start_gm20b_pmu(struct gk20a *g)
{
/*disable irqs for hs falcon booting as we will poll for halt*/
mutex_lock(&g->pmu.isr_mutex);
pmu_enable_irq(&g->pmu, true);
g->pmu.isr_enabled = true;
mutex_unlock(&g->pmu.isr_mutex);
gk20a_writel(g, pwr_falcon_cpuctl_alias_r(),
pwr_falcon_cpuctl_startcpu_f(1));
}
void gm20b_init_secure_pmu(struct gpu_ops *gops)
{
gops->pmu.prepare_ucode = prepare_ucode_blob;
gops->pmu.pmu_setup_hw_and_bootstrap = gm20b_bootstrap_hs_flcn;
}
/* TODO - check if any free blob res needed*/
int pmu_ucode_details(struct gk20a *g, struct flcn_ucode_img *p_img)
{
const struct firmware *pmu_fw, *pmu_desc, *pmu_sig;
struct pmu_gk20a *pmu = &g->pmu;
struct lsf_ucode_desc *lsf_desc;
int err;
gm20b_dbg_pmu("requesting PMU ucode in GM20B\n");
pmu_fw = gk20a_request_firmware(g, GM20B_PMU_UCODE_IMAGE);
if (!pmu_fw) {
gk20a_err(dev_from_gk20a(g), "failed to load pmu ucode!!");
return -ENOENT;
}
g->acr.pmu_fw = pmu_fw;
gm20b_dbg_pmu("Loaded PMU ucode in for blob preparation");
gm20b_dbg_pmu("requesting PMU ucode desc in GM20B\n");
pmu_desc = gk20a_request_firmware(g, GM20B_PMU_UCODE_DESC);
if (!pmu_desc) {
gk20a_err(dev_from_gk20a(g), "failed to load pmu ucode desc!!");
err = -ENOENT;
goto release_img_fw;
}
pmu_sig = gk20a_request_firmware(g, GM20B_PMU_UCODE_SIG);
if (!pmu_sig) {
gk20a_err(dev_from_gk20a(g), "failed to load pmu sig!!");
err = -ENOENT;
goto release_desc;
}
pmu->desc = (struct pmu_ucode_desc *)pmu_desc->data;
pmu->ucode_image = (u32 *)pmu_fw->data;
g->acr.pmu_desc = pmu_desc;
err = gk20a_init_pmu(pmu);
if (err) {
gm20b_dbg_pmu("failed to set function pointers\n");
goto release_desc;
}
lsf_desc = kzalloc(sizeof(struct lsf_ucode_desc), GFP_KERNEL);
if (!lsf_desc) {
err = -ENOMEM;
goto release_sig;
}
memcpy(lsf_desc, (void *)pmu_sig->data, sizeof(struct lsf_ucode_desc));
lsf_desc->falcon_id = LSF_FALCON_ID_PMU;
p_img->desc = pmu->desc;
p_img->data = pmu->ucode_image;
p_img->data_size = pmu->desc->image_size;
p_img->fw_ver = NULL;
p_img->header = NULL;
p_img->lsf_desc = (struct lsf_ucode_desc *)lsf_desc;
gm20b_dbg_pmu("requesting PMU ucode in GM20B exit\n");
release_firmware(pmu_sig);
return 0;
release_sig:
release_firmware(pmu_sig);
release_desc:
release_firmware(pmu_desc);
release_img_fw:
release_firmware(pmu_fw);
return err;
}
int fecs_ucode_details(struct gk20a *g, struct flcn_ucode_img *p_img)
{
struct lsf_ucode_desc *lsf_desc;
const struct firmware *fecs_sig;
int err;
fecs_sig = gk20a_request_firmware(g, GM20B_FECS_UCODE_SIG);
if (!fecs_sig) {
gk20a_err(dev_from_gk20a(g), "failed to load fecs sig");
return -ENOENT;
}
lsf_desc = kzalloc(sizeof(struct lsf_ucode_desc), GFP_KERNEL);
if (!lsf_desc) {
err = -ENOMEM;
goto rel_sig;
}
memcpy(lsf_desc, (void *)fecs_sig->data, sizeof(struct lsf_ucode_desc));
lsf_desc->falcon_id = LSF_FALCON_ID_FECS;
p_img->desc = kzalloc(sizeof(struct pmu_ucode_desc), GFP_KERNEL);
if (p_img->desc == NULL) {
err = -ENOMEM;
goto free_lsf_desc;
}
p_img->desc->bootloader_start_offset =
g->ctxsw_ucode_info.fecs.boot.offset;
p_img->desc->bootloader_size =
ALIGN(g->ctxsw_ucode_info.fecs.boot.size, 256);
p_img->desc->bootloader_imem_offset =
g->ctxsw_ucode_info.fecs.boot_imem_offset;
p_img->desc->bootloader_entry_point =
g->ctxsw_ucode_info.fecs.boot_entry;
p_img->desc->image_size =
ALIGN(g->ctxsw_ucode_info.fecs.boot.size, 256) +
ALIGN(g->ctxsw_ucode_info.fecs.code.size, 256) +
ALIGN(g->ctxsw_ucode_info.fecs.data.size, 256);
p_img->desc->app_size = ALIGN(g->ctxsw_ucode_info.fecs.code.size, 256) +
ALIGN(g->ctxsw_ucode_info.fecs.data.size, 256);
p_img->desc->app_start_offset = g->ctxsw_ucode_info.fecs.code.offset;
p_img->desc->app_imem_offset = 0;
p_img->desc->app_imem_entry = 0;
p_img->desc->app_dmem_offset = 0;
p_img->desc->app_resident_code_offset = 0;
p_img->desc->app_resident_code_size =
g->ctxsw_ucode_info.fecs.code.size;
p_img->desc->app_resident_data_offset =
g->ctxsw_ucode_info.fecs.data.offset -
g->ctxsw_ucode_info.fecs.code.offset;
p_img->desc->app_resident_data_size =
g->ctxsw_ucode_info.fecs.data.size;
p_img->data = g->ctxsw_ucode_info.surface_desc.cpu_va;
p_img->data_size = p_img->desc->image_size;
p_img->fw_ver = NULL;
p_img->header = NULL;
p_img->lsf_desc = (struct lsf_ucode_desc *)lsf_desc;
gm20b_dbg_pmu("fecs fw loaded\n");
release_firmware(fecs_sig);
return 0;
free_lsf_desc:
kfree(lsf_desc);
rel_sig:
release_firmware(fecs_sig);
return err;
}
int gpccs_ucode_details(struct gk20a *g, struct flcn_ucode_img *p_img)
{
struct lsf_ucode_desc *lsf_desc;
const struct firmware *gpccs_sig;
int err;
if (g->ops.securegpccs == false)
return -ENOENT;
gpccs_sig = gk20a_request_firmware(g, GM20B_FECS_UCODE_SIG);
if (!gpccs_sig) {
gk20a_err(dev_from_gk20a(g), "failed to load gpccs sig");
return -ENOENT;
}
lsf_desc = kzalloc(sizeof(struct lsf_ucode_desc), GFP_KERNEL);
if (!lsf_desc) {
err = -ENOMEM;
goto rel_sig;
}
memcpy(lsf_desc, (void *)gpccs_sig->data,
sizeof(struct lsf_ucode_desc));
lsf_desc->falcon_id = LSF_FALCON_ID_GPCCS;
p_img->desc = kzalloc(sizeof(struct pmu_ucode_desc), GFP_KERNEL);
if (p_img->desc == NULL) {
err = -ENOMEM;
goto free_lsf_desc;
}
p_img->desc->bootloader_start_offset =
0;
p_img->desc->bootloader_size =
ALIGN(g->ctxsw_ucode_info.gpccs.boot.size, 256);
p_img->desc->bootloader_imem_offset =
g->ctxsw_ucode_info.gpccs.boot_imem_offset;
p_img->desc->bootloader_entry_point =
g->ctxsw_ucode_info.gpccs.boot_entry;
p_img->desc->image_size =
ALIGN(g->ctxsw_ucode_info.gpccs.boot.size, 256) +
ALIGN(g->ctxsw_ucode_info.gpccs.code.size, 256) +
ALIGN(g->ctxsw_ucode_info.gpccs.data.size, 256);
p_img->desc->app_size = ALIGN(g->ctxsw_ucode_info.gpccs.code.size, 256)
+ ALIGN(g->ctxsw_ucode_info.gpccs.data.size, 256);
p_img->desc->app_start_offset = p_img->desc->bootloader_size;
p_img->desc->app_imem_offset = 0;
p_img->desc->app_imem_entry = 0;
p_img->desc->app_dmem_offset = 0;
p_img->desc->app_resident_code_offset = 0;
p_img->desc->app_resident_code_size =
ALIGN(g->ctxsw_ucode_info.gpccs.code.size, 256);
p_img->desc->app_resident_data_offset =
ALIGN(g->ctxsw_ucode_info.gpccs.data.offset, 256) -
ALIGN(g->ctxsw_ucode_info.gpccs.code.offset, 256);
p_img->desc->app_resident_data_size =
ALIGN(g->ctxsw_ucode_info.gpccs.data.size, 256);
p_img->data = (u32 *)((u8 *)g->ctxsw_ucode_info.surface_desc.cpu_va +
g->ctxsw_ucode_info.gpccs.boot.offset);
p_img->data_size = ALIGN(p_img->desc->image_size, 256);
p_img->fw_ver = NULL;
p_img->header = NULL;
p_img->lsf_desc = (struct lsf_ucode_desc *)lsf_desc;
gm20b_dbg_pmu("gpccs fw loaded\n");
release_firmware(gpccs_sig);
return 0;
free_lsf_desc:
kfree(lsf_desc);
rel_sig:
release_firmware(gpccs_sig);
return err;
}
int prepare_ucode_blob(struct gk20a *g)
{
int err;
struct ls_flcn_mgr lsfm_l, *plsfm;
struct pmu_gk20a *pmu = &g->pmu;
phys_addr_t wpr_addr;
u32 wprsize;
struct mm_gk20a *mm = &g->mm;
struct vm_gk20a *vm = &mm->pmu.vm;
struct mc_carveout_info inf;
struct sg_table *sgt;
struct page *page;
if (g->acr.ucode_blob.cpu_va) {
/*Recovery case, we do not need to form
non WPR blob of ucodes*/
err = gk20a_init_pmu(pmu);
if (err) {
gm20b_dbg_pmu("failed to set function pointers\n");
return err;
}
return 0;
}
plsfm = &lsfm_l;
memset((void *)plsfm, 0, sizeof(struct ls_flcn_mgr));
gm20b_dbg_pmu("fetching GMMU regs\n");
gm20b_mm_mmu_vpr_info_fetch(g);
gr_gk20a_init_ctxsw_ucode(g);
mc_get_carveout_info(&inf, NULL, MC_SECURITY_CARVEOUT2);
gm20b_dbg_pmu("wpr carveout base:%llx\n", inf.base);
wpr_addr = (phys_addr_t)inf.base;
gm20b_dbg_pmu("wpr carveout size :%llx\n", inf.size);
wprsize = (u32)inf.size;
sgt = kzalloc(sizeof(*sgt), GFP_KERNEL);
if (!sgt) {
gk20a_err(dev_from_gk20a(g), "failed to allocate memory\n");
return -ENOMEM;
}
err = sg_alloc_table(sgt, 1, GFP_KERNEL);
if (err) {
gk20a_err(dev_from_gk20a(g), "failed to allocate sg_table\n");
goto free_sgt;
}
page = phys_to_page(wpr_addr);
sg_set_page(sgt->sgl, page, wprsize, 0);
/* This bypasses SMMU for WPR during gmmu_map. */
sg_dma_address(sgt->sgl) = 0;
g->pmu.wpr_buf.gpu_va = gk20a_gmmu_map(vm, &sgt, wprsize,
0, gk20a_mem_flag_none, false);
gm20b_dbg_pmu("wpr mapped gpu va :%llx\n", g->pmu.wpr_buf.gpu_va);
/* Discover all managed falcons*/
err = lsfm_discover_ucode_images(g, plsfm);
gm20b_dbg_pmu(" Managed Falcon cnt %d\n", plsfm->managed_flcn_cnt);
if (err)
goto free_sgt;
if (plsfm->managed_flcn_cnt && !g->acr.ucode_blob.cpu_va) {
/* Generate WPR requirements*/
err = lsf_gen_wpr_requirements(g, plsfm);
if (err)
goto free_sgt;
/*Alloc memory to hold ucode blob contents*/
err = gk20a_gmmu_alloc(g, plsfm->wpr_size, &g->acr.ucode_blob);
if (err)
goto free_sgt;
gm20b_dbg_pmu("managed LS falcon %d, WPR size %d bytes.\n",
plsfm->managed_flcn_cnt, plsfm->wpr_size);
lsfm_init_wpr_contents(g, plsfm, g->acr.ucode_blob.cpu_va);
} else {
gm20b_dbg_pmu("LSFM is managing no falcons.\n");
}
gm20b_dbg_pmu("prepare ucode blob return 0\n");
free_acr_resources(g, plsfm);
free_sgt:
gk20a_free_sgtable(&sgt);
return err;
}
static u8 lsfm_falcon_disabled(struct gk20a *g, struct ls_flcn_mgr *plsfm,
u32 falcon_id)
{
return (plsfm->disable_mask >> falcon_id) & 0x1;
}
/* Discover all managed falcon ucode images */
static int lsfm_discover_ucode_images(struct gk20a *g,
struct ls_flcn_mgr *plsfm)
{
struct pmu_gk20a *pmu = &g->pmu;
struct flcn_ucode_img ucode_img;
u32 falcon_id;
u32 i;
int status;
/* LSFM requires a secure PMU, discover it first.*/
/* Obtain the PMU ucode image and add it to the list if required*/
memset(&ucode_img, 0, sizeof(ucode_img));
status = pmu_ucode_details(g, &ucode_img);
if (status == 0) {
if (ucode_img.lsf_desc != NULL) {
/* The falon_id is formed by grabbing the static base
* falon_id from the image and adding the
* engine-designated falcon instance.*/
pmu->pmu_mode |= PMU_SECURE_MODE;
falcon_id = ucode_img.lsf_desc->falcon_id +
ucode_img.flcn_inst;
if (!lsfm_falcon_disabled(g, plsfm, falcon_id)) {
pmu->falcon_id = falcon_id;
if (lsfm_add_ucode_img(g, plsfm, &ucode_img,
pmu->falcon_id) == 0)
pmu->pmu_mode |= PMU_LSFM_MANAGED;
plsfm->managed_flcn_cnt++;
} else {
gm20b_dbg_pmu("id not managed %d\n",
ucode_img.lsf_desc->falcon_id);
}
}
/*Free any ucode image resources if not managing this falcon*/
if (!(pmu->pmu_mode & PMU_LSFM_MANAGED)) {
gm20b_dbg_pmu("pmu is not LSFM managed\n");
lsfm_free_ucode_img_res(&ucode_img);
}
}
/* Enumerate all constructed falcon objects,
as we need the ucode image info and total falcon count.*/
/*0th index is always PMU which is already handled in earlier
if condition*/
for (i = 1; i < (MAX_SUPPORTED_LSFM); i++) {
memset(&ucode_img, 0, sizeof(ucode_img));
if (pmu_acr_supp_ucode_list[i](g, &ucode_img) == 0) {
if (ucode_img.lsf_desc != NULL) {
/* We have engine sigs, ensure that this falcon
is aware of the secure mode expectations
(ACR status)*/
/* falon_id is formed by grabbing the static
base falonId from the image and adding the
engine-designated falcon instance. */
falcon_id = ucode_img.lsf_desc->falcon_id +
ucode_img.flcn_inst;
if (!lsfm_falcon_disabled(g, plsfm,
falcon_id)) {
/* Do not manage non-FB ucode*/
if (lsfm_add_ucode_img(g,
plsfm, &ucode_img, falcon_id)
== 0)
plsfm->managed_flcn_cnt++;
} else {
gm20b_dbg_pmu("not managed %d\n",
ucode_img.lsf_desc->falcon_id);
lsfm_free_nonpmu_ucode_img_res(
&ucode_img);
}
}
} else {
/* Consumed all available falcon objects */
gm20b_dbg_pmu("Done checking for ucodes %d\n", i);
break;
}
}
return 0;
}
static int pmu_populate_loader_cfg(struct gk20a *g,
struct lsfm_managed_ucode_img *lsfm,
union flcn_bl_generic_desc *p_bl_gen_desc, u32 *p_bl_gen_desc_size)
{
struct mc_carveout_info inf;
struct pmu_gk20a *pmu = &g->pmu;
struct flcn_ucode_img *p_img = &(lsfm->ucode_img);
struct loader_config *ldr_cfg =
(struct loader_config *)(&p_bl_gen_desc->loader_cfg);
u64 addr_base;
struct pmu_ucode_desc *desc;
u64 addr_code, addr_data;
u32 addr_args;
if (p_img->desc == NULL) /*This means its a header based ucode,
and so we do not fill BL gen desc structure*/
return -EINVAL;
desc = p_img->desc;
/*
Calculate physical and virtual addresses for various portions of
the PMU ucode image
Calculate the 32-bit addresses for the application code, application
data, and bootloader code. These values are all based on IM_BASE.
The 32-bit addresses will be the upper 32-bits of the virtual or
physical addresses of each respective segment.
*/
addr_base = lsfm->lsb_header.ucode_off;
mc_get_carveout_info(&inf, NULL, MC_SECURITY_CARVEOUT2);
addr_base += inf.base;
gm20b_dbg_pmu("pmu loader cfg u32 addrbase %x\n", (u32)addr_base);
/*From linux*/
addr_code = u64_lo32((addr_base +
desc->app_start_offset +
desc->app_resident_code_offset) >> 8);
gm20b_dbg_pmu("app start %d app res code off %d\n",
desc->app_start_offset, desc->app_resident_code_offset);
addr_data = u64_lo32((addr_base +
desc->app_start_offset +
desc->app_resident_data_offset) >> 8);
gm20b_dbg_pmu("app res data offset%d\n",
desc->app_resident_data_offset);
gm20b_dbg_pmu("bl start off %d\n", desc->bootloader_start_offset);
addr_args = ((pwr_falcon_hwcfg_dmem_size_v(
gk20a_readl(g, pwr_falcon_hwcfg_r())))
<< GK20A_PMU_DMEM_BLKSIZE2);
addr_args -= g->ops.pmu_ver.get_pmu_cmdline_args_size(pmu);
gm20b_dbg_pmu("addr_args %x\n", addr_args);
/* Populate the loader_config state*/
ldr_cfg->dma_idx = GK20A_PMU_DMAIDX_UCODE;
ldr_cfg->code_dma_base = addr_code;
ldr_cfg->code_size_total = desc->app_size;
ldr_cfg->code_size_to_load = desc->app_resident_code_size;
ldr_cfg->code_entry_point = desc->app_imem_entry;
ldr_cfg->data_dma_base = addr_data;
ldr_cfg->data_size = desc->app_resident_data_size;
ldr_cfg->overlay_dma_base = addr_code;
/* Update the argc/argv members*/
ldr_cfg->argc = 1;
ldr_cfg->argv = addr_args;
*p_bl_gen_desc_size = sizeof(p_bl_gen_desc->loader_cfg);
g->acr.pmu_args = addr_args;
return 0;
}
static int flcn_populate_bl_dmem_desc(struct gk20a *g,
struct lsfm_managed_ucode_img *lsfm,
union flcn_bl_generic_desc *p_bl_gen_desc, u32 *p_bl_gen_desc_size,
u32 falconid)
{
struct mc_carveout_info inf;
struct flcn_ucode_img *p_img = &(lsfm->ucode_img);
struct flcn_bl_dmem_desc *ldr_cfg =
(struct flcn_bl_dmem_desc *)(&p_bl_gen_desc->bl_dmem_desc);
u64 addr_base;
struct pmu_ucode_desc *desc;
u64 addr_code, addr_data;
if (p_img->desc == NULL) /*This means its a header based ucode,
and so we do not fill BL gen desc structure*/
return -EINVAL;
desc = p_img->desc;
/*
Calculate physical and virtual addresses for various portions of
the PMU ucode image
Calculate the 32-bit addresses for the application code, application
data, and bootloader code. These values are all based on IM_BASE.
The 32-bit addresses will be the upper 32-bits of the virtual or
physical addresses of each respective segment.
*/
addr_base = lsfm->lsb_header.ucode_off;
mc_get_carveout_info(&inf, NULL, MC_SECURITY_CARVEOUT2);
if (falconid == LSF_FALCON_ID_GPCCS)
addr_base += g->pmu.wpr_buf.gpu_va;
else
addr_base += inf.base;
gm20b_dbg_pmu("gen loader cfg %x u32 addrbase %x ID\n", (u32)addr_base,
lsfm->wpr_header.falcon_id);
addr_code = u64_lo32((addr_base +
desc->app_start_offset +
desc->app_resident_code_offset) >> 8);
addr_data = u64_lo32((addr_base +
desc->app_start_offset +
desc->app_resident_data_offset) >> 8);
gm20b_dbg_pmu("gen cfg %x u32 addrcode %x & data %x load offset %xID\n",
(u32)addr_code, (u32)addr_data, desc->bootloader_start_offset,
lsfm->wpr_header.falcon_id);
/* Populate the LOADER_CONFIG state */
memset((void *) ldr_cfg, 0, sizeof(struct flcn_bl_dmem_desc));
ldr_cfg->ctx_dma = GK20A_PMU_DMAIDX_UCODE;
ldr_cfg->code_dma_base = addr_code;
ldr_cfg->non_sec_code_size = desc->app_resident_code_size;
ldr_cfg->data_dma_base = addr_data;
ldr_cfg->data_size = desc->app_resident_data_size;
ldr_cfg->code_entry_point = desc->app_imem_entry;
*p_bl_gen_desc_size = sizeof(p_bl_gen_desc->bl_dmem_desc);
return 0;
}
/* Populate falcon boot loader generic desc.*/
static int lsfm_fill_flcn_bl_gen_desc(struct gk20a *g,
struct lsfm_managed_ucode_img *pnode)
{
struct pmu_gk20a *pmu = &g->pmu;
if (pnode->wpr_header.falcon_id != pmu->falcon_id) {
gm20b_dbg_pmu("non pmu. write flcn bl gen desc\n");
flcn_populate_bl_dmem_desc(g, pnode, &pnode->bl_gen_desc,
&pnode->bl_gen_desc_size,
pnode->wpr_header.falcon_id);
return 0;
}
if (pmu->pmu_mode & PMU_LSFM_MANAGED) {
gm20b_dbg_pmu("pmu write flcn bl gen desc\n");
if (pnode->wpr_header.falcon_id == pmu->falcon_id)
return pmu_populate_loader_cfg(g, pnode,
&pnode->bl_gen_desc, &pnode->bl_gen_desc_size);
}
/* Failed to find the falcon requested. */
return -ENOENT;
}
/* Initialize WPR contents */
static int lsfm_init_wpr_contents(struct gk20a *g, struct ls_flcn_mgr *plsfm,
void *nonwpr_addr)
{
int status = 0;
union flcn_bl_generic_desc *nonwpr_bl_gen_desc;
if (nonwpr_addr == NULL) {
status = -ENOMEM;
} else {
struct lsfm_managed_ucode_img *pnode = plsfm->ucode_img_list;
struct lsf_wpr_header *wpr_hdr;
struct lsf_lsb_header *lsb_hdr;
void *ucode_off;
u32 i;
/* The WPR array is at the base of the WPR */
wpr_hdr = (struct lsf_wpr_header *)nonwpr_addr;
pnode = plsfm->ucode_img_list;
i = 0;
/*
* Walk the managed falcons, flush WPR and LSB headers to FB.
* flush any bl args to the storage area relative to the
* ucode image (appended on the end as a DMEM area).
*/
while (pnode) {
/* Flush WPR header to memory*/
memcpy(&wpr_hdr[i], &pnode->wpr_header,
sizeof(struct lsf_wpr_header));
gm20b_dbg_pmu("wpr header as in memory and pnode\n");
gm20b_dbg_pmu("falconid :%d %d\n",
pnode->wpr_header.falcon_id,
wpr_hdr[i].falcon_id);
gm20b_dbg_pmu("lsb_offset :%x %x\n",
pnode->wpr_header.lsb_offset,
wpr_hdr[i].lsb_offset);
gm20b_dbg_pmu("bootstrap_owner :%d %d\n",
pnode->wpr_header.bootstrap_owner,
wpr_hdr[i].bootstrap_owner);
gm20b_dbg_pmu("lazy_bootstrap :%d %d\n",
pnode->wpr_header.lazy_bootstrap,
wpr_hdr[i].lazy_bootstrap);
gm20b_dbg_pmu("status :%d %d\n",
pnode->wpr_header.status, wpr_hdr[i].status);
/*Flush LSB header to memory*/
lsb_hdr = (struct lsf_lsb_header *)((u8 *)nonwpr_addr +
pnode->wpr_header.lsb_offset);
memcpy(lsb_hdr, &pnode->lsb_header,
sizeof(struct lsf_lsb_header));
gm20b_dbg_pmu("lsb header as in memory and pnode\n");
gm20b_dbg_pmu("ucode_off :%x %x\n",
pnode->lsb_header.ucode_off,
lsb_hdr->ucode_off);
gm20b_dbg_pmu("ucode_size :%x %x\n",
pnode->lsb_header.ucode_size,
lsb_hdr->ucode_size);
gm20b_dbg_pmu("data_size :%x %x\n",
pnode->lsb_header.data_size,
lsb_hdr->data_size);
gm20b_dbg_pmu("bl_code_size :%x %x\n",
pnode->lsb_header.bl_code_size,
lsb_hdr->bl_code_size);
gm20b_dbg_pmu("bl_imem_off :%x %x\n",
pnode->lsb_header.bl_imem_off,
lsb_hdr->bl_imem_off);
gm20b_dbg_pmu("bl_data_off :%x %x\n",
pnode->lsb_header.bl_data_off,
lsb_hdr->bl_data_off);
gm20b_dbg_pmu("bl_data_size :%x %x\n",
pnode->lsb_header.bl_data_size,
lsb_hdr->bl_data_size);
gm20b_dbg_pmu("app_code_off :%x %x\n",
pnode->lsb_header.app_code_off,
lsb_hdr->app_code_off);
gm20b_dbg_pmu("app_code_size :%x %x\n",
pnode->lsb_header.app_code_size,
lsb_hdr->app_code_size);
gm20b_dbg_pmu("app_data_off :%x %x\n",
pnode->lsb_header.app_data_off,
lsb_hdr->app_data_off);
gm20b_dbg_pmu("app_data_size :%x %x\n",
pnode->lsb_header.app_data_size,
lsb_hdr->app_data_size);
gm20b_dbg_pmu("flags :%x %x\n",
pnode->lsb_header.flags, lsb_hdr->flags);
/*If this falcon has a boot loader and related args,
* flush them.*/
if (!pnode->ucode_img.header) {
nonwpr_bl_gen_desc =
(union flcn_bl_generic_desc *)
((u8 *)nonwpr_addr +
pnode->lsb_header.bl_data_off);
/*Populate gen bl and flush to memory*/
lsfm_fill_flcn_bl_gen_desc(g, pnode);
memcpy(nonwpr_bl_gen_desc, &pnode->bl_gen_desc,
pnode->bl_gen_desc_size);
}
ucode_off = (void *)(pnode->lsb_header.ucode_off +
(u8 *)nonwpr_addr);
/*Copying of ucode*/
memcpy(ucode_off, pnode->ucode_img.data,
pnode->ucode_img.data_size);
pnode = pnode->next;
i++;
}
/* Tag the terminator WPR header with an invalid falcon ID. */
gk20a_mem_wr32(&wpr_hdr[plsfm->managed_flcn_cnt].falcon_id,
0, LSF_FALCON_ID_INVALID);
}
return status;
}
/*!
* lsfm_parse_no_loader_ucode: parses UCODE header of falcon
*
* @param[in] p_ucodehdr : UCODE header
* @param[out] lsb_hdr : updates values in LSB header
*
* @return 0
*/
static int lsfm_parse_no_loader_ucode(u32 *p_ucodehdr,
struct lsf_lsb_header *lsb_hdr)
{
u32 code_size = 0;
u32 data_size = 0;
u32 i = 0;
u32 total_apps = p_ucodehdr[FLCN_NL_UCODE_HDR_NUM_APPS_IND];
/* Lets calculate code size*/
code_size += p_ucodehdr[FLCN_NL_UCODE_HDR_OS_CODE_SIZE_IND];
for (i = 0; i < total_apps; i++) {
code_size += p_ucodehdr[FLCN_NL_UCODE_HDR_APP_CODE_SIZE_IND
(total_apps, i)];
}
code_size += p_ucodehdr[FLCN_NL_UCODE_HDR_OS_OVL_SIZE_IND(total_apps)];
/* Calculate data size*/
data_size += p_ucodehdr[FLCN_NL_UCODE_HDR_OS_DATA_SIZE_IND];
for (i = 0; i < total_apps; i++) {
data_size += p_ucodehdr[FLCN_NL_UCODE_HDR_APP_DATA_SIZE_IND
(total_apps, i)];
}
lsb_hdr->ucode_size = code_size;
lsb_hdr->data_size = data_size;
lsb_hdr->bl_code_size = p_ucodehdr[FLCN_NL_UCODE_HDR_OS_CODE_SIZE_IND];
lsb_hdr->bl_imem_off = 0;
lsb_hdr->bl_data_off = p_ucodehdr[FLCN_NL_UCODE_HDR_OS_DATA_OFF_IND];
lsb_hdr->bl_data_size = p_ucodehdr[FLCN_NL_UCODE_HDR_OS_DATA_SIZE_IND];
return 0;
}
/*!
* @brief lsfm_fill_static_lsb_hdr_info
* Populate static LSB header infomation using the provided ucode image
*/
static void lsfm_fill_static_lsb_hdr_info(struct gk20a *g,
u32 falcon_id, struct lsfm_managed_ucode_img *pnode)
{
struct pmu_gk20a *pmu = &g->pmu;
u32 full_app_size = 0;
u32 data = 0;
if (pnode->ucode_img.lsf_desc)
memcpy(&pnode->lsb_header.signature, pnode->ucode_img.lsf_desc,
sizeof(struct lsf_ucode_desc));
pnode->lsb_header.ucode_size = pnode->ucode_img.data_size;
/* The remainder of the LSB depends on the loader usage */
if (pnode->ucode_img.header) {
/* Does not use a loader */
pnode->lsb_header.data_size = 0;
pnode->lsb_header.bl_code_size = 0;
pnode->lsb_header.bl_data_off = 0;
pnode->lsb_header.bl_data_size = 0;
lsfm_parse_no_loader_ucode(pnode->ucode_img.header,
&(pnode->lsb_header));
/* Load the first 256 bytes of IMEM. */
/* Set LOAD_CODE_AT_0 and DMACTL_REQ_CTX.
True for all method based falcons */
data = NV_FLCN_ACR_LSF_FLAG_LOAD_CODE_AT_0_TRUE |
NV_FLCN_ACR_LSF_FLAG_DMACTL_REQ_CTX_TRUE;
pnode->lsb_header.flags = data;
} else {
/* Uses a loader. that is has a desc */
pnode->lsb_header.data_size = 0;
/* The loader code size is already aligned (padded) such that
the code following it is aligned, but the size in the image
desc is not, bloat it up to be on a 256 byte alignment. */
pnode->lsb_header.bl_code_size = ALIGN(
pnode->ucode_img.desc->bootloader_size,
LSF_BL_CODE_SIZE_ALIGNMENT);
full_app_size = ALIGN(pnode->ucode_img.desc->app_size,
LSF_BL_CODE_SIZE_ALIGNMENT) +
pnode->lsb_header.bl_code_size;
pnode->lsb_header.ucode_size = ALIGN(
pnode->ucode_img.desc->app_resident_data_offset,
LSF_BL_CODE_SIZE_ALIGNMENT) +
pnode->lsb_header.bl_code_size;
pnode->lsb_header.data_size = full_app_size -
pnode->lsb_header.ucode_size;
/* Though the BL is located at 0th offset of the image, the VA
is different to make sure that it doesnt collide the actual OS
VA range */
pnode->lsb_header.bl_imem_off =
pnode->ucode_img.desc->bootloader_imem_offset;
/* TODO: OBJFLCN should export properties using which the below
flags should be populated.*/
pnode->lsb_header.flags = 0;
if (falcon_id == pmu->falcon_id) {
data = NV_FLCN_ACR_LSF_FLAG_DMACTL_REQ_CTX_TRUE;
pnode->lsb_header.flags = data;
}
if (falcon_id == LSF_FALCON_ID_GPCCS) {
pnode->lsb_header.flags |=
NV_FLCN_ACR_LSF_FLAG_FORCE_PRIV_LOAD_FALSE;
}
}
}
/* Adds a ucode image to the list of managed ucode images managed. */
static int lsfm_add_ucode_img(struct gk20a *g, struct ls_flcn_mgr *plsfm,
struct flcn_ucode_img *ucode_image, u32 falcon_id)
{
struct lsfm_managed_ucode_img *pnode;
pnode = kzalloc(sizeof(struct lsfm_managed_ucode_img), GFP_KERNEL);
if (pnode == NULL)
return -ENOMEM;
/* Keep a copy of the ucode image info locally */
memcpy(&pnode->ucode_img, ucode_image, sizeof(struct flcn_ucode_img));
/* Fill in static WPR header info*/
pnode->wpr_header.falcon_id = falcon_id;
pnode->wpr_header.bootstrap_owner = LSF_BOOTSTRAP_OWNER_DEFAULT;
pnode->wpr_header.status = LSF_IMAGE_STATUS_COPY;
if (falcon_id == LSF_FALCON_ID_GPCCS)
pnode->wpr_header.lazy_bootstrap = 1;
/*TODO to check if PDB_PROP_FLCN_LAZY_BOOTSTRAP is to be supported by
Android */
/* Fill in static LSB header info elsewhere */
lsfm_fill_static_lsb_hdr_info(g, falcon_id, pnode);
pnode->next = plsfm->ucode_img_list;
plsfm->ucode_img_list = pnode;
return 0;
}
/* Free any ucode image structure resources*/
static void lsfm_free_ucode_img_res(struct flcn_ucode_img *p_img)
{
if (p_img->lsf_desc != NULL) {
kfree(p_img->lsf_desc);
p_img->lsf_desc = NULL;
}
}
/* Free any ucode image structure resources*/
static void lsfm_free_nonpmu_ucode_img_res(struct flcn_ucode_img *p_img)
{
if (p_img->lsf_desc != NULL) {
kfree(p_img->lsf_desc);
p_img->lsf_desc = NULL;
}
if (p_img->desc != NULL) {
kfree(p_img->desc);
p_img->desc = NULL;
}
}
static void free_acr_resources(struct gk20a *g, struct ls_flcn_mgr *plsfm)
{
u32 cnt = plsfm->managed_flcn_cnt;
struct lsfm_managed_ucode_img *mg_ucode_img;
while (cnt) {
mg_ucode_img = plsfm->ucode_img_list;
if (mg_ucode_img->ucode_img.lsf_desc->falcon_id ==
LSF_FALCON_ID_PMU)
lsfm_free_ucode_img_res(&mg_ucode_img->ucode_img);
else
lsfm_free_nonpmu_ucode_img_res(
&mg_ucode_img->ucode_img);
plsfm->ucode_img_list = mg_ucode_img->next;
kfree(mg_ucode_img);
cnt--;
}
}
/* Generate WPR requirements for ACR allocation request */
static int lsf_gen_wpr_requirements(struct gk20a *g, struct ls_flcn_mgr *plsfm)
{
struct lsfm_managed_ucode_img *pnode = plsfm->ucode_img_list;
u32 wpr_offset;
/* Calculate WPR size required */
/* Start with an array of WPR headers at the base of the WPR.
The expectation here is that the secure falcon will do a single DMA
read of this array and cache it internally so it's OK to pack these.
Also, we add 1 to the falcon count to indicate the end of the array.*/
wpr_offset = sizeof(struct lsf_wpr_header) *
(plsfm->managed_flcn_cnt+1);
/* Walk the managed falcons, accounting for the LSB structs
as well as the ucode images. */
while (pnode) {
/* Align, save off, and include an LSB header size */
wpr_offset = ALIGN(wpr_offset,
LSF_LSB_HEADER_ALIGNMENT);
pnode->wpr_header.lsb_offset = wpr_offset;
wpr_offset += sizeof(struct lsf_lsb_header);
/* Align, save off, and include the original (static)
ucode image size */
wpr_offset = ALIGN(wpr_offset,
LSF_UCODE_DATA_ALIGNMENT);
pnode->lsb_header.ucode_off = wpr_offset;
wpr_offset += pnode->ucode_img.data_size;
/* For falcons that use a boot loader (BL), we append a loader
desc structure on the end of the ucode image and consider this
the boot loader data. The host will then copy the loader desc
args to this space within the WPR region (before locking down)
and the HS bin will then copy them to DMEM 0 for the loader. */
if (!pnode->ucode_img.header) {
/* Track the size for LSB details filled in later
Note that at this point we don't know what kind of i
boot loader desc, so we just take the size of the
generic one, which is the largest it will will ever be.
*/
/* Align (size bloat) and save off generic
descriptor size*/
pnode->lsb_header.bl_data_size = ALIGN(
sizeof(pnode->bl_gen_desc),
LSF_BL_DATA_SIZE_ALIGNMENT);
/*Align, save off, and include the additional BL data*/
wpr_offset = ALIGN(wpr_offset,
LSF_BL_DATA_ALIGNMENT);
pnode->lsb_header.bl_data_off = wpr_offset;
wpr_offset += pnode->lsb_header.bl_data_size;
} else {
/* bl_data_off is already assigned in static
information. But that is from start of the image */
pnode->lsb_header.bl_data_off +=
(wpr_offset - pnode->ucode_img.data_size);
}
/* Finally, update ucode surface size to include updates */
pnode->full_ucode_size = wpr_offset -
pnode->lsb_header.ucode_off;
if (pnode->wpr_header.falcon_id != LSF_FALCON_ID_PMU) {
pnode->lsb_header.app_code_off =
pnode->lsb_header.bl_code_size;
pnode->lsb_header.app_code_size =
pnode->lsb_header.ucode_size -
pnode->lsb_header.bl_code_size;
pnode->lsb_header.app_data_off =
pnode->lsb_header.ucode_size;
pnode->lsb_header.app_data_size =
pnode->lsb_header.data_size;
}
pnode = pnode->next;
}
plsfm->wpr_size = wpr_offset;
return 0;
}
/*Loads ACR bin to FB mem and bootstraps PMU with bootloader code
* start and end are addresses of ucode blob in non-WPR region*/
int gm20b_bootstrap_hs_flcn(struct gk20a *g)
{
struct mm_gk20a *mm = &g->mm;
struct vm_gk20a *vm = &mm->pmu.vm;
int i, err = 0;
u64 *acr_dmem;
u32 img_size_in_bytes = 0;
u32 status, size;
u64 start;
struct acr_gm20b *acr = &g->acr;
const struct firmware *acr_fw = acr->acr_fw;
struct flcn_bl_dmem_desc *bl_dmem_desc = &acr->bl_dmem_desc;
u32 *acr_ucode_header_t210_load;
u32 *acr_ucode_data_t210_load;
start = g->ops.mm.get_iova_addr(g, acr->ucode_blob.sgt->sgl, 0);
size = acr->ucode_blob.size;
gm20b_dbg_pmu("");
if (!acr_fw) {
/*First time init case*/
acr_fw = gk20a_request_firmware(g, GM20B_HSBIN_PMU_UCODE_IMAGE);
if (!acr_fw) {
gk20a_err(dev_from_gk20a(g), "pmu ucode get fail");
return -ENOENT;
}
acr->acr_fw = acr_fw;
acr->hsbin_hdr = (struct bin_hdr *)acr_fw->data;
acr->fw_hdr = (struct acr_fw_header *)(acr_fw->data +
acr->hsbin_hdr->header_offset);
acr_ucode_data_t210_load = (u32 *)(acr_fw->data +
acr->hsbin_hdr->data_offset);
acr_ucode_header_t210_load = (u32 *)(acr_fw->data +
acr->fw_hdr->hdr_offset);
img_size_in_bytes = ALIGN((acr->hsbin_hdr->data_size), 256);
/* Lets patch the signatures first.. */
if (acr_ucode_patch_sig(g, acr_ucode_data_t210_load,
(u32 *)(acr_fw->data +
acr->fw_hdr->sig_prod_offset),
(u32 *)(acr_fw->data +
acr->fw_hdr->sig_dbg_offset),
(u32 *)(acr_fw->data +
acr->fw_hdr->patch_loc),
(u32 *)(acr_fw->data +
acr->fw_hdr->patch_sig)) < 0) {
gk20a_err(dev_from_gk20a(g), "patch signatures fail");
err = -1;
goto err_release_acr_fw;
}
err = gk20a_gmmu_alloc_map(vm, img_size_in_bytes,
&acr->acr_ucode);
if (err) {
err = -ENOMEM;
goto err_release_acr_fw;
}
acr_dmem = (u64 *)
&(((u8 *)acr_ucode_data_t210_load)[
acr_ucode_header_t210_load[2]]);
acr->acr_dmem_desc = (struct flcn_acr_desc *)((u8 *)(
acr->acr_ucode.cpu_va) + acr_ucode_header_t210_load[2]);
((struct flcn_acr_desc *)acr_dmem)->nonwpr_ucode_blob_start =
start;
((struct flcn_acr_desc *)acr_dmem)->nonwpr_ucode_blob_size =
size;
((struct flcn_acr_desc *)acr_dmem)->regions.no_regions = 2;
((struct flcn_acr_desc *)acr_dmem)->wpr_offset = 0;
for (i = 0; i < (img_size_in_bytes/4); i++) {
gk20a_mem_wr32(acr->acr_ucode.cpu_va, i,
acr_ucode_data_t210_load[i]);
}
/*
* In order to execute this binary, we will be using
* a bootloader which will load this image into PMU IMEM/DMEM.
* Fill up the bootloader descriptor for PMU HAL to use..
* TODO: Use standard descriptor which the generic bootloader is
* checked in.
*/
bl_dmem_desc->signature[0] = 0;
bl_dmem_desc->signature[1] = 0;
bl_dmem_desc->signature[2] = 0;
bl_dmem_desc->signature[3] = 0;
bl_dmem_desc->ctx_dma = GK20A_PMU_DMAIDX_VIRT;
bl_dmem_desc->code_dma_base =
(unsigned int)(((u64)acr->acr_ucode.gpu_va >> 8));
bl_dmem_desc->non_sec_code_off = acr_ucode_header_t210_load[0];
bl_dmem_desc->non_sec_code_size = acr_ucode_header_t210_load[1];
bl_dmem_desc->sec_code_off = acr_ucode_header_t210_load[5];
bl_dmem_desc->sec_code_size = acr_ucode_header_t210_load[6];
bl_dmem_desc->code_entry_point = 0; /* Start at 0th offset */
bl_dmem_desc->data_dma_base =
bl_dmem_desc->code_dma_base +
((acr_ucode_header_t210_load[2]) >> 8);
bl_dmem_desc->data_size = acr_ucode_header_t210_load[3];
} else
acr->acr_dmem_desc->nonwpr_ucode_blob_size = 0;
status = pmu_exec_gen_bl(g, bl_dmem_desc, 1);
if (status != 0) {
err = status;
goto err_free_ucode_map;
}
return 0;
err_free_ucode_map:
gk20a_gmmu_unmap_free(vm, &acr->acr_ucode);
err_release_acr_fw:
release_firmware(acr_fw);
acr->acr_fw = NULL;
return err;
}
static u8 pmu_is_debug_mode_en(struct gk20a *g)
{
u32 ctl_stat = gk20a_readl(g, pwr_pmu_scpctl_stat_r());
return pwr_pmu_scpctl_stat_debug_mode_v(ctl_stat);
}
/*
* @brief Patch signatures into ucode image
*/
static int
acr_ucode_patch_sig(struct gk20a *g,
unsigned int *p_img,
unsigned int *p_prod_sig,
unsigned int *p_dbg_sig,
unsigned int *p_patch_loc,
unsigned int *p_patch_ind)
{
int i, *p_sig;
gm20b_dbg_pmu("");
if (!pmu_is_debug_mode_en(g)) {
p_sig = p_prod_sig;
gm20b_dbg_pmu("PRODUCTION MODE\n");
} else {
p_sig = p_dbg_sig;
gm20b_dbg_pmu("DEBUG MODE\n");
}
/* Patching logic:*/
for (i = 0; i < sizeof(*p_patch_loc)>>2; i++) {
p_img[(p_patch_loc[i]>>2)] = p_sig[(p_patch_ind[i]<<2)];
p_img[(p_patch_loc[i]>>2)+1] = p_sig[(p_patch_ind[i]<<2)+1];
p_img[(p_patch_loc[i]>>2)+2] = p_sig[(p_patch_ind[i]<<2)+2];
p_img[(p_patch_loc[i]>>2)+3] = p_sig[(p_patch_ind[i]<<2)+3];
}
return 0;
}
static int bl_bootstrap(struct pmu_gk20a *pmu,
struct flcn_bl_dmem_desc *pbl_desc, u32 bl_sz)
{
struct gk20a *g = gk20a_from_pmu(pmu);
struct acr_gm20b *acr = &g->acr;
struct mm_gk20a *mm = &g->mm;
u32 imem_dst_blk = 0;
u32 virt_addr = 0;
u32 tag = 0;
u32 index = 0;
struct hsflcn_bl_desc *pmu_bl_gm10x_desc = g->acr.pmu_hsbl_desc;
u32 *bl_ucode;
gk20a_dbg_fn("");
gk20a_writel(g, pwr_falcon_itfen_r(),
gk20a_readl(g, pwr_falcon_itfen_r()) |
pwr_falcon_itfen_ctxen_enable_f());
gk20a_writel(g, pwr_pmu_new_instblk_r(),
pwr_pmu_new_instblk_ptr_f(
gk20a_mem_phys(&mm->pmu.inst_block) >> 12) |
pwr_pmu_new_instblk_valid_f(1) |
pwr_pmu_new_instblk_target_sys_coh_f());
/* TBD: load all other surfaces */
/*copy bootloader interface structure to dmem*/
gk20a_writel(g, pwr_falcon_dmemc_r(0),
pwr_falcon_dmemc_offs_f(0) |
pwr_falcon_dmemc_blk_f(0) |
pwr_falcon_dmemc_aincw_f(1));
pmu_copy_to_dmem(pmu, 0, (u8 *)pbl_desc,
sizeof(struct flcn_bl_dmem_desc), 0);
/*TODO This had to be copied to bl_desc_dmem_load_off, but since
* this is 0, so ok for now*/
/* Now copy bootloader to TOP of IMEM */
imem_dst_blk = (pwr_falcon_hwcfg_imem_size_v(
gk20a_readl(g, pwr_falcon_hwcfg_r()))) - bl_sz/256;
/* Set Auto-Increment on write */
gk20a_writel(g, pwr_falcon_imemc_r(0),
pwr_falcon_imemc_offs_f(0) |
pwr_falcon_imemc_blk_f(imem_dst_blk) |
pwr_falcon_imemc_aincw_f(1));
virt_addr = pmu_bl_gm10x_desc->bl_start_tag << 8;
tag = virt_addr >> 8; /* tag is always 256B aligned */
bl_ucode = (u32 *)(acr->hsbl_ucode.cpu_va);
for (index = 0; index < bl_sz/4; index++) {
if ((index % 64) == 0) {
gk20a_writel(g, pwr_falcon_imemt_r(0),
(tag & 0xffff) << 0);
tag++;
}
gk20a_writel(g, pwr_falcon_imemd_r(0),
bl_ucode[index] & 0xffffffff);
}
gk20a_writel(g, pwr_falcon_imemt_r(0), (0 & 0xffff) << 0);
gm20b_dbg_pmu("Before starting falcon with BL\n");
gk20a_writel(g, pwr_falcon_bootvec_r(),
pwr_falcon_bootvec_vec_f(virt_addr));
gk20a_writel(g, pwr_falcon_cpuctl_r(),
pwr_falcon_cpuctl_startcpu_f(1));
return 0;
}
static int gm20b_init_pmu_setup_hw1(struct gk20a *g,
struct flcn_bl_dmem_desc *desc, u32 bl_sz)
{
struct pmu_gk20a *pmu = &g->pmu;
int err;
struct gk20a_platform *platform = platform_get_drvdata(g->dev);
gk20a_dbg_fn("");
mutex_lock(&pmu->isr_mutex);
pmu_reset(pmu);
pmu->isr_enabled = true;
mutex_unlock(&pmu->isr_mutex);
/* setup apertures - virtual */
gk20a_writel(g, pwr_fbif_transcfg_r(GK20A_PMU_DMAIDX_UCODE),
pwr_fbif_transcfg_mem_type_physical_f() |
pwr_fbif_transcfg_target_local_fb_f());
gk20a_writel(g, pwr_fbif_transcfg_r(GK20A_PMU_DMAIDX_VIRT),
pwr_fbif_transcfg_mem_type_virtual_f());
/* setup apertures - physical */
gk20a_writel(g, pwr_fbif_transcfg_r(GK20A_PMU_DMAIDX_PHYS_VID),
pwr_fbif_transcfg_mem_type_physical_f() |
pwr_fbif_transcfg_target_local_fb_f());
gk20a_writel(g, pwr_fbif_transcfg_r(GK20A_PMU_DMAIDX_PHYS_SYS_COH),
pwr_fbif_transcfg_mem_type_physical_f() |
pwr_fbif_transcfg_target_coherent_sysmem_f());
gk20a_writel(g, pwr_fbif_transcfg_r(GK20A_PMU_DMAIDX_PHYS_SYS_NCOH),
pwr_fbif_transcfg_mem_type_physical_f() |
pwr_fbif_transcfg_target_noncoherent_sysmem_f());
/*Copying pmu cmdline args*/
g->ops.pmu_ver.set_pmu_cmdline_args_cpu_freq(pmu,
clk_get_rate(platform->clk[1]));
g->ops.pmu_ver.set_pmu_cmdline_args_secure_mode(pmu, 1);
g->ops.pmu_ver.set_pmu_cmdline_args_trace_size(
pmu, GK20A_PMU_TRACE_BUFSIZE);
g->ops.pmu_ver.set_pmu_cmdline_args_trace_dma_base(pmu);
g->ops.pmu_ver.set_pmu_cmdline_args_trace_dma_idx(
pmu, GK20A_PMU_DMAIDX_VIRT);
pmu_copy_to_dmem(pmu, g->acr.pmu_args,
(u8 *)(g->ops.pmu_ver.get_pmu_cmdline_args_ptr(pmu)),
g->ops.pmu_ver.get_pmu_cmdline_args_size(pmu), 0);
/*disable irqs for hs falcon booting as we will poll for halt*/
mutex_lock(&pmu->isr_mutex);
pmu_enable_irq(pmu, false);
pmu->isr_enabled = false;
mutex_unlock(&pmu->isr_mutex);
err = bl_bootstrap(pmu, desc, bl_sz);
if (err)
return err;
return 0;
}
/*
* Executes a generic bootloader and wait for PMU to halt.
* This BL will be used for those binaries that are loaded
* and executed at times other than RM PMU Binary execution.
*
* @param[in] g gk20a pointer
* @param[in] desc Bootloader descriptor
* @param[in] dma_idx DMA Index
* @param[in] b_wait_for_halt Wait for PMU to HALT
*/
int pmu_exec_gen_bl(struct gk20a *g, void *desc, u8 b_wait_for_halt)
{
struct mm_gk20a *mm = &g->mm;
struct vm_gk20a *vm = &mm->pmu.vm;
struct device *d = dev_from_gk20a(g);
int i, err = 0;
u32 bl_sz;
struct acr_gm20b *acr = &g->acr;
const struct firmware *hsbl_fw = acr->hsbl_fw;
struct hsflcn_bl_desc *pmu_bl_gm10x_desc;
u32 *pmu_bl_gm10x = NULL;
gm20b_dbg_pmu("");
if (!hsbl_fw) {
hsbl_fw = gk20a_request_firmware(g,
GM20B_HSBIN_PMU_BL_UCODE_IMAGE);
if (!hsbl_fw) {
gk20a_err(dev_from_gk20a(g), "pmu ucode load fail");
return -ENOENT;
}
acr->hsbl_fw = hsbl_fw;
acr->bl_bin_hdr = (struct bin_hdr *)hsbl_fw->data;
acr->pmu_hsbl_desc = (struct hsflcn_bl_desc *)(hsbl_fw->data +
acr->bl_bin_hdr->header_offset);
pmu_bl_gm10x_desc = acr->pmu_hsbl_desc;
pmu_bl_gm10x = (u32 *)(hsbl_fw->data +
acr->bl_bin_hdr->data_offset);
bl_sz = ALIGN(pmu_bl_gm10x_desc->bl_img_hdr.bl_code_size,
256);
acr->hsbl_ucode.size = bl_sz;
gm20b_dbg_pmu("Executing Generic Bootloader\n");
/*TODO in code verify that enable PMU is done,
scrubbing etc is done*/
/*TODO in code verify that gmmu vm init is done*/
err = gk20a_gmmu_alloc_attr(g,
DMA_ATTR_READ_ONLY, bl_sz, &acr->hsbl_ucode);
if (err) {
gk20a_err(d, "failed to allocate memory\n");
goto err_done;
}
acr->hsbl_ucode.gpu_va = gk20a_gmmu_map(vm, &acr->hsbl_ucode.sgt,
bl_sz,
0, /* flags */
gk20a_mem_flag_read_only, false);
if (!acr->hsbl_ucode.gpu_va) {
gk20a_err(d, "failed to map pmu ucode memory!!");
goto err_free_ucode;
}
for (i = 0; i < (bl_sz) >> 2; i++)
gk20a_mem_wr32(acr->hsbl_ucode.cpu_va, i, pmu_bl_gm10x[i]);
gm20b_dbg_pmu("Copied bl ucode to bl_cpuva\n");
}
/*
* Disable interrupts to avoid kernel hitting breakpoint due
* to PMU halt
*/
if (clear_halt_interrupt_status(g, gk20a_get_gr_idle_timeout(g)))
goto err_unmap_bl;
gm20b_dbg_pmu("phys sec reg %x\n", gk20a_readl(g,
pwr_falcon_mmu_phys_sec_r()));
gm20b_dbg_pmu("sctl reg %x\n", gk20a_readl(g, pwr_falcon_sctl_r()));
gm20b_init_pmu_setup_hw1(g, desc, acr->hsbl_ucode.size);
/* Poll for HALT */
if (b_wait_for_halt) {
err = pmu_wait_for_halt(g, gk20a_get_gr_idle_timeout(g));
if (err == 0) {
/* Clear the HALT interrupt */
if (clear_halt_interrupt_status(g, gk20a_get_gr_idle_timeout(g)))
goto err_unmap_bl;
}
else
goto err_unmap_bl;
}
gm20b_dbg_pmu("after waiting for halt, err %x\n", err);
gm20b_dbg_pmu("phys sec reg %x\n", gk20a_readl(g,
pwr_falcon_mmu_phys_sec_r()));
gm20b_dbg_pmu("sctl reg %x\n", gk20a_readl(g, pwr_falcon_sctl_r()));
start_gm20b_pmu(g);
return 0;
err_unmap_bl:
gk20a_gmmu_unmap(vm, acr->hsbl_ucode.gpu_va,
acr->hsbl_ucode.size, gk20a_mem_flag_none);
err_free_ucode:
gk20a_gmmu_free(g, &acr->hsbl_ucode);
err_done:
release_firmware(hsbl_fw);
return err;
}
/*!
* Wait for PMU to halt
* @param[in] g GPU object pointer
* @param[in] timeout_us Timeout in Us for PMU to halt
* @return '0' if PMU halts
*/
int pmu_wait_for_halt(struct gk20a *g, unsigned int timeout)
{
u32 data = 0;
while (timeout != 0) {
data = gk20a_readl(g, pwr_falcon_cpuctl_r());
if (data & pwr_falcon_cpuctl_halt_intr_m())
/*CPU is halted break*/
break;
timeout--;
udelay(1);
}
if (timeout == 0)
return -EBUSY;
data = gk20a_readl(g, pwr_falcon_mailbox0_r());
if (data) {
gk20a_err(dev_from_gk20a(g), "ACR boot failed, err %x", data);
return -EAGAIN;
}
return 0;
}
/*!
* Wait for PMU halt interrupt status to be cleared
* @param[in] g GPU object pointer
* @param[in] timeout_us Timeout in Us for PMU to halt
* @return '0' if PMU halt irq status is clear
*/
int clear_halt_interrupt_status(struct gk20a *g, unsigned int timeout)
{
u32 data = 0;
while (timeout != 0) {
gk20a_writel(g, pwr_falcon_irqsclr_r(),
gk20a_readl(g, pwr_falcon_irqsclr_r()) | (0x10));
data = gk20a_readl(g, (pwr_falcon_irqstat_r()));
if ((data & pwr_falcon_irqstat_halt_true_f()) !=
pwr_falcon_irqstat_halt_true_f())
/*halt irq is clear*/
break;
timeout--;
udelay(1);
}
if (timeout == 0)
return -EBUSY;
return 0;
}
| gpl-2.0 |
yxl/emscripten-calligra-mobile | sheets/tests/TestSelection.cpp | 6 | 16526 | /* This file is part of the KDE project
Copyright 2009 Stefan Nikolaus <stefan.nikolaus@kdemail.net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "TestSelection.h"
#include <qtest_kde.h>
#include "part/Canvas.h"
#include "Map.h"
#include "ui/Selection.h"
#include "Sheet.h"
using namespace Calligra::Sheets;
void TestSelection::initialize()
{
Map map;
Sheet* sheet1 = new Sheet(&map, "Sheet1");
map.addSheet(sheet1);
Sheet* sheet2 = new Sheet(&map, "Sheet2");
map.addSheet(sheet2);
Canvas canvas(0);
Selection selection(&canvas);
selection.setActiveSheet(sheet1);
QVERIFY(!selection.isEmpty());
QCOMPARE(selection.name(), QString("A1"));
// Clearing in normal selection mode, results in A1 as residuum.
selection.clear();
QVERIFY(!selection.isEmpty());
QCOMPARE(selection.name(), QString("Sheet1!A1"));
selection.initialize(QPoint(2, 4), sheet2);
QCOMPARE(selection.name(), QString("Sheet2!B4"));
selection.initialize(QRect(3, 5, 2, 3));
QCOMPARE(selection.name(), QString("Sheet1!C5:D7"));
Region region("A1:A4", &map, sheet2);
selection.initialize(region);
QCOMPARE(selection.name(), QString("Sheet2!A1:A4"));
region = Region("Sheet1!A2:A4", &map, sheet2);
selection.initialize(region);
QCOMPARE(selection.name(), QString("Sheet1!A2:A4"));
// reference mode:
selection.startReferenceSelection();
region = Region("Sheet1!A2:A4;B3;C5", &map, sheet2);
selection.initialize(region);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5"));
QCOMPARE(selection.activeSubRegionName(), QString("A2:A4;Sheet2!B3;Sheet2!C5"));
selection.setActiveSubRegion(1, 1);
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!B3"));
selection.initialize(QPoint(2, 2));
QCOMPARE(selection.name(), QString("A2:A4;B2;Sheet2!C5"));
QCOMPARE(selection.activeSubRegionName(), QString("B2"));
selection.setActiveSubRegion(1, 2, 2);
QCOMPARE(selection.activeSubRegionName(), QString("B2;Sheet2!C5"));
selection.initialize(QPoint(3, 3), sheet2);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!C3"));
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!C3"));
selection.setActiveSubRegion(1, 0, 2);
QCOMPARE(selection.activeSubRegionName(), QString());
selection.initialize(QPoint(4, 4), sheet2);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!D4;Sheet2!C3"));
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!D4"));
selection.setActiveSubRegion(1, 1, 2);
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!D4"));
selection.clearSubRegion();
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!C3"));
QCOMPARE(selection.activeSubRegionName(), QString());
// Two appendings.
selection.clear();
selection.setActiveSubRegion(0, 0, 0);
QCOMPARE(selection.activeSubRegionName(), QString());
selection.initialize(QPoint(1, 1), sheet1);
QCOMPARE(selection.activeSubRegionName(), QString("A1"));
selection.setActiveSubRegion(1, 0, 1);
QCOMPARE(selection.activeSubRegionName(), QString());
selection.initialize(QPoint(2, 2), sheet1);
QCOMPARE(selection.name(), QString("A1;B2"));
QCOMPARE(selection.activeSubRegionName(), QString("B2"));
}
void TestSelection::update()
{
Map map;
Sheet *sheet1 = new Sheet(&map, "Sheet1");
map.addSheet(sheet1);
Sheet *sheet2 = new Sheet(&map, "Sheet2");
map.addSheet(sheet2);
Canvas canvas(0);
Selection selection(&canvas);
selection.setActiveSheet(sheet1);
QVERIFY(!selection.isEmpty());
QCOMPARE(selection.name(), QString("A1"));
// Selection::update(const QPoint&) works always on the active sheet.
// normal mode:
// init with location
selection.initialize(QPoint(1, 6), sheet1);
QCOMPARE(selection.name(), QString("Sheet1!A6"));
// init with region
selection.initialize(Region("A3", &map, sheet1));
QCOMPARE(selection.name(), QString("Sheet1!A3"));
// init with location after init with region
selection.initialize(QPoint(1, 5), sheet1);
QCOMPARE(selection.name(), QString("Sheet1!A5"));
// TODO
// reference mode:
selection.startReferenceSelection();
Region region("Sheet1!A2:A4;B3;C5", &map, sheet2);
selection.initialize(region);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5"));
// Prepend new range.
selection.setActiveSubRegion(0, 0);
QCOMPARE(selection.activeSubRegionName(), QString());
selection.update(QPoint(1, 1));
QCOMPARE(selection.name(), QString("A1;A2:A4;Sheet2!B3;Sheet2!C5"));
// Insert new range on active sheet.
selection.setActiveSubRegion(2, 0);
QCOMPARE(selection.activeSubRegionName(), QString());
selection.update(QPoint(1, 1));
QCOMPARE(selection.name(), QString("A1;A2:A4;A1;Sheet2!B3;Sheet2!C5"));
// Append new range.
selection.setActiveSubRegion(5, 0);
QCOMPARE(selection.activeSubRegionName(), QString());
selection.update(QPoint(1, 1));
QCOMPARE(selection.name(), QString("A1;A2:A4;A1;Sheet2!B3;Sheet2!C5;A1"));
// Update range.
selection.setActiveSubRegion(2, 2);
QCOMPARE(selection.activeSubRegionName(), QString("A1;Sheet2!B3"));
selection.update(QPoint(2, 2));
QCOMPARE(selection.name(), QString("A1;A2:A4;A1:B2;Sheet2!B3;Sheet2!C5;A1"));
// Try to update range on non-active sheet. Inserts location on active sheet.
selection.setActiveSubRegion(2, 2, 3);
QCOMPARE(selection.activeSubRegionName(), QString("A1:B2;Sheet2!B3"));
selection.update(QPoint(2, 2));
QCOMPARE(selection.name(), QString("A1;A2:A4;A1:B2;Sheet2!B3;B2;Sheet2!C5;A1"));
}
void TestSelection::extend()
{
Map map;
Sheet *sheet1 = new Sheet(&map, "Sheet1");
map.addSheet(sheet1);
Sheet *sheet2 = new Sheet(&map, "Sheet2");
map.addSheet(sheet2);
Canvas canvas(0);
Selection selection(&canvas);
selection.setActiveSheet(sheet1);
QVERIFY(!selection.isEmpty());
QCOMPARE(selection.name(), QString("A1"));
// normal mode:
// TODO
// reference mode:
selection.startReferenceSelection();
Region region("Sheet1!A2:A4;B3;C5", &map, sheet2);
selection.initialize(region);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5"));
// Prepend new location.
selection.setActiveSubRegion(0, 0);
QCOMPARE(selection.activeSubRegionName(), QString());
selection.extend(QPoint(1, 1), sheet2);
QCOMPARE(selection.name(), QString("Sheet2!A1;A2:A4;Sheet2!B3;Sheet2!C5"));
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!A1"));
// Try to prepend new location. Prepending needs length = 0.
selection.setActiveSubRegion(0, 2); // results in: 0, 2, 0
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!A1;A2:A4"));
selection.extend(QPoint(1, 1), sheet1);
QCOMPARE(selection.name(), QString("Sheet2!A1;A1;A2:A4;Sheet2!B3;Sheet2!C5"));
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!A1;A1;A2:A4"));
// Prepend new range.
selection.setActiveSubRegion(0, 0);
QCOMPARE(selection.activeSubRegionName(), QString());
selection.extend(QRect(1, 1, 2, 2), sheet1);
QCOMPARE(selection.name(), QString("A1:B2;Sheet2!A1;A1;A2:A4;Sheet2!B3;Sheet2!C5"));
QCOMPARE(selection.activeSubRegionName(), QString("A1:B2"));
// Try to prepend new range. Prepending needs length = 0.
selection.setActiveSubRegion(0, 3); // results in: 0, 3, 0
QCOMPARE(selection.activeSubRegionName(), QString("A1:B2;Sheet2!A1;A1"));
selection.extend(QRect(1, 2, 2, 2), sheet2);
QCOMPARE(selection.name(), QString("A1:B2;Sheet2!A2:B3;Sheet2!A1;A1;A2:A4;Sheet2!B3;Sheet2!C5"));
QCOMPARE(selection.activeSubRegionName(), QString("A1:B2;Sheet2!A2:B3;Sheet2!A1;A1"));
selection.clear();
QVERIFY(selection.isEmpty());
selection.initialize(region);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5"));
// Append new location.
selection.setActiveSubRegion(1, 3, 3); // results in: 1, 2, 3
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!B3;Sheet2!C5"));
selection.extend(QPoint(1, 1), sheet2);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5;Sheet2!A1"));
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!B3;Sheet2!C5;Sheet2!A1"));
// Append new location.
selection.setActiveSubRegion(4, 1, 3); // results in: 4, 0, 4
QCOMPARE(selection.activeSubRegionName(), QString());
selection.extend(QPoint(1, 1), sheet1);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5;Sheet2!A1;A1"));
QCOMPARE(selection.activeSubRegionName(), QString("A1"));
// Append new range.
selection.setActiveSubRegion(5, 0); // results in: 5, 0, 5
QCOMPARE(selection.activeSubRegionName(), QString());
selection.extend(QRect(1, 1, 2, 2), sheet1);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5;Sheet2!A1;A1;A1:B2"));
QCOMPARE(selection.activeSubRegionName(), QString("A1:B2"));
// Append new range.
selection.setActiveSubRegion(5, 1, 6);
QCOMPARE(selection.activeSubRegionName(), QString("A1:B2"));
selection.extend(QRect(1, 2, 2, 2), sheet2);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5;Sheet2!A1;A1;A1:B2;Sheet2!A2:B3"));
QCOMPARE(selection.activeSubRegionName(), QString("A1:B2;Sheet2!A2:B3"));
selection.clear();
QVERIFY(selection.isEmpty());
selection.initialize(region);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!C5"));
// Insert new location.
selection.setActiveSubRegion(0, 3, 1);
QCOMPARE(selection.activeSubRegionName(), QString("A2:A4;Sheet2!B3;Sheet2!C5"));
selection.extend(QPoint(1, 1), sheet2);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!A1;Sheet2!C5"));
QCOMPARE(selection.activeSubRegionName(), QString("A2:A4;Sheet2!B3;Sheet2!A1;Sheet2!C5"));
// Insert new range.
selection.setActiveSubRegion(1, 3, 3);
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!B3;Sheet2!A1;Sheet2!C5"));
selection.extend(QRect(1, 1, 2, 2), sheet1);
QCOMPARE(selection.name(), QString("A2:A4;Sheet2!B3;Sheet2!A1;Sheet2!C5;A1:B2"));
QCOMPARE(selection.activeSubRegionName(), QString("Sheet2!B3;Sheet2!A1;Sheet2!C5;A1:B2"));
}
void TestSelection::activeElement()
{
Map map;
Sheet *sheet1 = new Sheet(&map, "Sheet1");
map.addSheet(sheet1);
Sheet *sheet2 = new Sheet(&map, "Sheet2");
map.addSheet(sheet2);
Canvas canvas(0);
Selection selection(&canvas);
selection.setActiveSheet(sheet1);
QVERIFY(!selection.isEmpty());
QCOMPARE(selection.name(), QString("A1"));
QVERIFY(!selection.activeElement());
// normal mode:
//BEGIN Leave the active element unset.
selection.startReferenceSelection();
QVERIFY(!selection.activeElement());
selection.initialize(Region("A3:A4;B2;C4:D5", &map, sheet1));
QCOMPARE(selection.name(sheet1), QString("A3:A4;B2;C4:D5"));
QVERIFY(!selection.activeElement());
selection.extend(QRect(1, 1, 4, 4), sheet1);
QCOMPARE(selection.name(sheet1), QString("A3:A4;B2;C4:D5;A1:D4"));
QVERIFY(!selection.activeElement());
selection.update(QPoint(5, 5));
QCOMPARE(selection.name(sheet1), QString("A3:A4;B2;C4:D5;A1:E5"));
QVERIFY(!selection.activeElement());
selection.initialize(QPoint(5, 6), sheet1);
QCOMPARE(selection.name(sheet1), QString("E6"));
QVERIFY(!selection.activeElement());
selection.initialize(QRect(1, 1, 2, 1), sheet1);
QCOMPARE(selection.name(sheet1), QString("A1:B1"));
QVERIFY(!selection.activeElement());
selection.extend(QPoint(1, 3), sheet1);
QCOMPARE(selection.name(sheet1), QString("A1:B1;A3"));
QVERIFY(!selection.activeElement());
//END Leave the active element unset.
}
void TestSelection::referenceSelectionMode()
{
Map map;
Sheet *sheet1 = new Sheet(&map, "Sheet1");
map.addSheet(sheet1);
Sheet *sheet2 = new Sheet(&map, "Sheet2");
map.addSheet(sheet2);
Canvas canvas(0);
Selection selection(&canvas);
selection.setActiveSheet(sheet1);
QVERIFY(!selection.isEmpty());
QCOMPARE(selection.name(), QString("A1"));
// reference mode:
selection.startReferenceSelection();
QVERIFY(selection.isEmpty());
selection.initialize(QPoint(2, 2), sheet2);
QCOMPARE(selection.name(), QString("Sheet2!B2"));
selection.extend(QPoint(1, 2));
QCOMPARE(selection.name(), QString("Sheet2!B2;A2"));
selection.setActiveSubRegion(1, 1, 1);
QCOMPARE(selection.activeSubRegionName(), QString("A2"));
selection.endReferenceSelection();
QCOMPARE(selection.name(), QString("A1"));
selection.initialize(QPoint(2, 2), sheet1);
QCOMPARE(selection.name(), QString("B2"));
// quit it again
selection.endReferenceSelection();
QCOMPARE(selection.name(), QString("B2"));
selection.initialize(QRect(2, 2, 2, 2));
QCOMPARE(selection.name(), QString("B2:C3"));
// start it again
selection.startReferenceSelection();
QVERIFY(selection.isEmpty());
selection.initialize(Region("A3", &map, sheet1));
QCOMPARE(selection.name(), QString("A3"));
// set the active sub-region beyond the last range
selection.setActiveSubRegion(1, 0, 1);
QCOMPARE(selection.activeSubRegionName(), QString());
// quit it again
selection.endReferenceSelection();
QCOMPARE(selection.name(), QString("B2:C3"));
}
void TestSelection::covering()
{
Map map;
Sheet *sheet1 = new Sheet(&map, "Sheet1");
map.addSheet(sheet1);
Sheet *sheet2 = new Sheet(&map, "Sheet2");
map.addSheet(sheet2);
Canvas canvas(0);
Selection selection(&canvas);
selection.setActiveSheet(sheet1);
QVERIFY(!selection.isEmpty());
QCOMPARE(selection.name(), QString("A1"));
// normal mode:
// convered ranges get removed
selection.initialize(Region("A3:A4;B2;C4:D5", &map, sheet1));
QCOMPARE(selection.name(sheet1), QString("A3:A4;B2;C4:D5"));
selection.extend(QRect(1, 1, 4, 4), sheet1);
QCOMPARE(selection.name(sheet1), QString("C4:D5;A1:D4"));
selection.update(QPoint(5, 5));
QCOMPARE(selection.name(sheet1), QString("A1:E5"));
// reference mode:
// covered ranges get ignored
selection.startReferenceSelection();
selection.initialize(Region("A3:A4;B2;C4:D5", &map, sheet1));
QCOMPARE(selection.name(), QString("A3:A4;B2;C4:D5"));
selection.extend(QRect(1, 1, 4, 4), sheet1);
QCOMPARE(selection.name(), QString("A3:A4;B2;C4:D5;A1:D4"));
selection.update(QPoint(5, 5));
QCOMPARE(selection.name(sheet1), QString("A3:A4;B2;C4:D5;A1:E5"));
}
void TestSelection::splitting()
{
Map map;
Sheet *sheet1 = new Sheet(&map, "Sheet1");
map.addSheet(sheet1);
Sheet *sheet2 = new Sheet(&map, "Sheet2");
map.addSheet(sheet2);
Canvas canvas(0);
Selection selection(&canvas);
selection.setActiveSheet(sheet1);
QVERIFY(!selection.isEmpty());
QCOMPARE(selection.name(), QString("A1"));
// normal mode:
// ranges get split
selection.initialize(Region("A1:D5", &map, sheet1));
QCOMPARE(selection.name(sheet1), QString("A1:D5"));
selection.extend(QPoint(2, 2), sheet1);
QCOMPARE(selection.name(sheet1), QString("A3:D5;C2:D2;A2;A1:D1"));
// reference mode:
// ranges are not affected
selection.startReferenceSelection();
selection.initialize(Region("A1:D5", &map, sheet1));
QCOMPARE(selection.name(), QString("A1:D5"));
selection.extend(QPoint(2, 2), sheet1);
QCOMPARE(selection.name(), QString("A1:D5;B2"));
}
QTEST_KDEMAIN(TestSelection, GUI)
#include "TestSelection.moc"
| gpl-2.0 |
sjurbren/modem-ipc | arch/arm/plat-s3c24xx/cpu.c | 6 | 5436 | /* linux/arch/arm/plat-s3c24xx/cpu.c
*
* Copyright (c) 2004-2005 Simtec Electronics
* http://www.simtec.co.uk/products/SWLINUX/
* Ben Dooks <ben@simtec.co.uk>
*
* S3C24XX CPU Support
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/cacheflush.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/system-reset.h>
#include <mach/regs-gpio.h>
#include <plat/regs-serial.h>
#include <plat/cpu.h>
#include <plat/devs.h>
#include <plat/clock.h>
#include <plat/s3c2410.h>
#include <plat/s3c2412.h>
#include <plat/s3c2416.h>
#include <plat/s3c244x.h>
#include <plat/s3c2443.h>
/* table of supported CPUs */
static const char name_s3c2410[] = "S3C2410";
static const char name_s3c2412[] = "S3C2412";
static const char name_s3c2416[] = "S3C2416/S3C2450";
static const char name_s3c2440[] = "S3C2440";
static const char name_s3c2442[] = "S3C2442";
static const char name_s3c2442b[] = "S3C2442B";
static const char name_s3c2443[] = "S3C2443";
static const char name_s3c2410a[] = "S3C2410A";
static const char name_s3c2440a[] = "S3C2440A";
static struct cpu_table cpu_ids[] __initdata = {
{
.idcode = 0x32410000,
.idmask = 0xffffffff,
.map_io = s3c2410_map_io,
.init_clocks = s3c2410_init_clocks,
.init_uarts = s3c2410_init_uarts,
.init = s3c2410_init,
.name = name_s3c2410
},
{
.idcode = 0x32410002,
.idmask = 0xffffffff,
.map_io = s3c2410_map_io,
.init_clocks = s3c2410_init_clocks,
.init_uarts = s3c2410_init_uarts,
.init = s3c2410a_init,
.name = name_s3c2410a
},
{
.idcode = 0x32440000,
.idmask = 0xffffffff,
.map_io = s3c2440_map_io,
.init_clocks = s3c244x_init_clocks,
.init_uarts = s3c244x_init_uarts,
.init = s3c2440_init,
.name = name_s3c2440
},
{
.idcode = 0x32440001,
.idmask = 0xffffffff,
.map_io = s3c2440_map_io,
.init_clocks = s3c244x_init_clocks,
.init_uarts = s3c244x_init_uarts,
.init = s3c2440_init,
.name = name_s3c2440a
},
{
.idcode = 0x32440aaa,
.idmask = 0xffffffff,
.map_io = s3c2442_map_io,
.init_clocks = s3c244x_init_clocks,
.init_uarts = s3c244x_init_uarts,
.init = s3c2442_init,
.name = name_s3c2442
},
{
.idcode = 0x32440aab,
.idmask = 0xffffffff,
.map_io = s3c2442_map_io,
.init_clocks = s3c244x_init_clocks,
.init_uarts = s3c244x_init_uarts,
.init = s3c2442_init,
.name = name_s3c2442b
},
{
.idcode = 0x32412001,
.idmask = 0xffffffff,
.map_io = s3c2412_map_io,
.init_clocks = s3c2412_init_clocks,
.init_uarts = s3c2412_init_uarts,
.init = s3c2412_init,
.name = name_s3c2412,
},
{ /* a newer version of the s3c2412 */
.idcode = 0x32412003,
.idmask = 0xffffffff,
.map_io = s3c2412_map_io,
.init_clocks = s3c2412_init_clocks,
.init_uarts = s3c2412_init_uarts,
.init = s3c2412_init,
.name = name_s3c2412,
},
{ /* a strange version of the s3c2416 */
.idcode = 0x32450003,
.idmask = 0xffffffff,
.map_io = s3c2416_map_io,
.init_clocks = s3c2416_init_clocks,
.init_uarts = s3c2416_init_uarts,
.init = s3c2416_init,
.name = name_s3c2416,
},
{
.idcode = 0x32443001,
.idmask = 0xffffffff,
.map_io = s3c2443_map_io,
.init_clocks = s3c2443_init_clocks,
.init_uarts = s3c2443_init_uarts,
.init = s3c2443_init,
.name = name_s3c2443,
},
};
/* minimal IO mapping */
static struct map_desc s3c_iodesc[] __initdata = {
IODESC_ENT(GPIO),
IODESC_ENT(IRQ),
IODESC_ENT(MEMCTRL),
IODESC_ENT(UART)
};
/* read cpu identificaiton code */
static unsigned long s3c24xx_read_idcode_v5(void)
{
#if defined(CONFIG_CPU_S3C2416)
/* s3c2416 is v5, with S3C24XX_GSTATUS1 instead of S3C2412_GSTATUS1 */
u32 gs = __raw_readl(S3C24XX_GSTATUS1);
/* test for s3c2416 or similar device */
if ((gs >> 16) == 0x3245)
return gs;
#endif
#if defined(CONFIG_CPU_S3C2412) || defined(CONFIG_CPU_S3C2413)
return __raw_readl(S3C2412_GSTATUS1);
#else
return 1UL; /* don't look like an 2400 */
#endif
}
static unsigned long s3c24xx_read_idcode_v4(void)
{
return __raw_readl(S3C2410_GSTATUS1);
}
void __init s3c24xx_init_io(struct map_desc *mach_desc, int size)
{
/* initialise the io descriptors we need for initialisation */
iotable_init(mach_desc, size);
iotable_init(s3c_iodesc, ARRAY_SIZE(s3c_iodesc));
if (cpu_architecture() >= CPU_ARCH_ARMv5) {
samsung_cpu_id = s3c24xx_read_idcode_v5();
} else {
samsung_cpu_id = s3c24xx_read_idcode_v4();
}
s3c24xx_init_cpu();
s3c_init_cpu(samsung_cpu_id, cpu_ids, ARRAY_SIZE(cpu_ids));
}
| gpl-2.0 |
371816210/kk44 | drivers/net/wireless/rkusbwifi/rtl8192cu/core/rtw_iol.c | 262 | 7368 | /******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
*
******************************************************************************/
#include<rtw_iol.h>
#ifdef CONFIG_IOL
struct xmit_frame *rtw_IOL_accquire_xmit_frame(ADAPTER *adapter)
{
struct xmit_frame *xmit_frame;
struct xmit_buf *xmitbuf;
struct pkt_attrib *pattrib;
struct xmit_priv *pxmitpriv = &(adapter->xmitpriv);
#if 1
if ((xmit_frame = rtw_alloc_xmitframe(pxmitpriv)) == NULL)
{
DBG_871X("%s rtw_alloc_xmitframe return null\n", __FUNCTION__);
goto exit;
}
if ((xmitbuf = rtw_alloc_xmitbuf(pxmitpriv)) == NULL)
{
DBG_871X("%s rtw_alloc_xmitbuf return null\n", __FUNCTION__);
rtw_free_xmitframe(pxmitpriv, xmit_frame);
xmit_frame=NULL;
goto exit;
}
xmit_frame->frame_tag = MGNT_FRAMETAG;
xmit_frame->pxmitbuf = xmitbuf;
xmit_frame->buf_addr = xmitbuf->pbuf;
xmitbuf->priv_data = xmit_frame;
pattrib = &xmit_frame->attrib;
update_mgntframe_attrib(adapter, pattrib);
pattrib->qsel = 0x10;
pattrib->pktlen = pattrib->last_txcmdsz = 0;
#else
if ((xmit_frame = alloc_mgtxmitframe(pxmitpriv)) == NULL)
{
DBG_871X("%s alloc_mgtxmitframe return null\n", __FUNCTION__);
}
else {
pattrib = &xmit_frame->attrib;
update_mgntframe_attrib(adapter, pattrib);
pattrib->qsel = 0x10;
pattrib->pktlen = pattrib->last_txcmdsz = 0;
}
#endif
exit:
return xmit_frame;
}
int rtw_IOL_append_cmds(struct xmit_frame *xmit_frame, u8 *IOL_cmds, u32 cmd_len)
{
struct pkt_attrib *pattrib = &xmit_frame->attrib;
u16 buf_offset;
u32 ori_len;
//Todo: bulkout without this offset
#ifdef CONFIG_USB_HCI
buf_offset = TXDESC_OFFSET;
#else
buf_offset = 0;
#endif
ori_len = buf_offset+pattrib->pktlen;
//check if the io_buf can accommodate new cmds
if(ori_len + cmd_len + 8 > MAX_XMITBUF_SZ) {
DBG_871X("%s %u is large than MAX_XMITBUF_SZ:%u, can't accommodate new cmds\n", __FUNCTION__
, ori_len + cmd_len + 8, MAX_XMITBUF_SZ);
return _FAIL;
}
_rtw_memcpy(xmit_frame->buf_addr + buf_offset + pattrib->pktlen, IOL_cmds, cmd_len);
pattrib->pktlen += cmd_len;
pattrib->last_txcmdsz += cmd_len;
//DBG_871X("%s ori:%u + cmd_len:%u = %u\n", __FUNCTION__, ori_len, cmd_len, buf_offset+pattrib->pktlen);
return _SUCCESS;
}
int rtw_IOL_append_LLT_cmd(struct xmit_frame *xmit_frame, u8 page_boundary)
{
IOL_CMD cmd = {0x0, IOL_CMD_LLT, 0x0, 0x0};
RTW_PUT_BE32((u8*)&cmd.value, (u32)page_boundary);
return rtw_IOL_append_cmds(xmit_frame, (u8*)&cmd, 8);
}
int _rtw_IOL_append_WB_cmd(struct xmit_frame *xmit_frame, u16 addr, u8 value)
{
IOL_CMD cmd = {0x0, IOL_CMD_WB_REG, 0x0, 0x0};
RTW_PUT_BE16((u8*)&cmd.address, (u16)addr);
RTW_PUT_BE32((u8*)&cmd.value, (u32)value);
return rtw_IOL_append_cmds(xmit_frame, (u8*)&cmd, 8);
}
int _rtw_IOL_append_WW_cmd(struct xmit_frame *xmit_frame, u16 addr, u16 value)
{
IOL_CMD cmd = {0x0, IOL_CMD_WW_REG, 0x0, 0x0};
RTW_PUT_BE16((u8*)&cmd.address, (u16)addr);
RTW_PUT_BE32((u8*)&cmd.value, (u32)value);
return rtw_IOL_append_cmds(xmit_frame, (u8*)&cmd, 8);
}
int _rtw_IOL_append_WD_cmd(struct xmit_frame *xmit_frame, u16 addr, u32 value)
{
IOL_CMD cmd = {0x0, IOL_CMD_WD_REG, 0x0, 0x0};
u8* pos = (u8 *)&cmd;
RTW_PUT_BE16((u8*)&cmd.address, (u16)addr);
RTW_PUT_BE32((u8*)&cmd.value, (u32)value);
return rtw_IOL_append_cmds(xmit_frame, (u8*)&cmd, 8);
}
#ifdef DBG_IO
int dbg_rtw_IOL_append_WB_cmd(struct xmit_frame *xmit_frame, u16 addr, u8 value, const char *caller, const int line)
{
if (match_write_sniff_ranges(addr, 1))
DBG_871X("DBG_IO %s:%d IOL_WB(0x%04x, 0x%02x)\n", caller, line, addr, value);
return _rtw_IOL_append_WB_cmd(xmit_frame, addr, value);
}
int dbg_rtw_IOL_append_WW_cmd(struct xmit_frame *xmit_frame, u16 addr, u16 value, const char *caller, const int line)
{
if (match_write_sniff_ranges(addr, 2))
DBG_871X("DBG_IO %s:%d IOL_WW(0x%04x, 0x%04x)\n", caller, line, addr, value);
return _rtw_IOL_append_WW_cmd(xmit_frame, addr, value);
}
int dbg_rtw_IOL_append_WD_cmd(struct xmit_frame *xmit_frame, u16 addr, u32 value, const char *caller, const int line)
{
if (match_write_sniff_ranges(addr, 4))
DBG_871X("DBG_IO %s:%d IOL_WD(0x%04x, 0x%08x)\n", caller, line, addr, value);
return _rtw_IOL_append_WD_cmd(xmit_frame, addr, value);
}
#endif
int rtw_IOL_append_DELAY_US_cmd(struct xmit_frame *xmit_frame, u16 us)
{
IOL_CMD cmd = {0x0, IOL_CMD_DELAY_US, 0x0, 0x0};
RTW_PUT_BE32((u8*)&cmd.value, (u32)us);
//DBG_871X("%s %u\n", __FUNCTION__, us);
return rtw_IOL_append_cmds(xmit_frame, (u8*)&cmd, 8);
}
int rtw_IOL_append_DELAY_MS_cmd(struct xmit_frame *xmit_frame, u16 ms)
{
IOL_CMD cmd = {0x0, IOL_CMD_DELAY_MS, 0x0, 0x0};
RTW_PUT_BE32((u8*)&cmd.value, (u32)ms);
//DBG_871X("%s %u\n", __FUNCTION__, ms);
return rtw_IOL_append_cmds(xmit_frame, (u8*)&cmd, 8);
}
int rtw_IOL_append_END_cmd(struct xmit_frame *xmit_frame)
{
struct pkt_attrib *pattrib = &xmit_frame->attrib;
u16 buf_offset;
u32 ori_len;
IOL_CMD end_cmd = {0x0, IOL_CMD_END, 0x0, 0x0};
//Todo: bulkout without this offset
#ifdef CONFIG_USB_HCI
buf_offset = TXDESC_OFFSET;
#else
buf_offset = 0;
#endif
ori_len = buf_offset+pattrib->pktlen;
//check if the io_buf can accommodate new cmds
if(ori_len + 8 > MAX_XMITBUF_SZ) {
DBG_871X("%s %u is large than MAX_XMITBUF_SZ:%u, can't accommodate end cmd\n", __FUNCTION__
, ori_len + 8, MAX_XMITBUF_SZ);
return _FAIL;
}
_rtw_memcpy(xmit_frame->buf_addr + buf_offset + pattrib->pktlen, (u8*)&end_cmd, 8);
pattrib->pktlen += 8;
pattrib->last_txcmdsz += 8;
//DBG_871X("%s ori:%u + 8 = %u\n", __FUNCTION__ , ori_len, buf_offset+pattrib->pktlen);
return _SUCCESS;
}
int rtw_IOL_exec_cmds_sync(ADAPTER *adapter, struct xmit_frame *xmit_frame, u32 max_wating_ms)
{
return rtw_hal_iol_cmd(adapter, xmit_frame, max_wating_ms);
}
int rtw_IOL_exec_cmd_array_sync(PADAPTER adapter, u8 *IOL_cmds, u32 cmd_num, u32 max_wating_ms)
{
struct xmit_frame *xmit_frame;
if((xmit_frame=rtw_IOL_accquire_xmit_frame(adapter)) == NULL)
return _FAIL;
if(rtw_IOL_append_cmds(xmit_frame, IOL_cmds, cmd_num<<3) == _FAIL)
return _FAIL;
return rtw_IOL_exec_cmds_sync(adapter, xmit_frame, max_wating_ms);
}
int rtw_IOL_exec_empty_cmds_sync(ADAPTER *adapter, u32 max_wating_ms)
{
IOL_CMD end_cmd = {0x0, IOL_CMD_END, 0x0, 0x0};
return rtw_IOL_exec_cmd_array_sync(adapter, (u8*)&end_cmd, 1, max_wating_ms);
}
bool rtw_IOL_applied(ADAPTER *adapter)
{
if(adapter->registrypriv.force_iol)
return _TRUE;
#ifdef CONFIG_USB_HCI
if(!adapter_to_dvobj(adapter)->ishighspeed)
return _TRUE;
#endif
return _FALSE;
}
#endif //CONFIG_IOL
| gpl-2.0 |
bergwolf/rhel6 | net/ipv4/fib_hash.c | 518 | 24011 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* IPv4 FIB: lookup engine and maintenance routines.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*
* 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; either version
* 2 of the License, or (at your option) any later version.
*/
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/bitops.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/errno.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/proc_fs.h>
#include <linux/skbuff.h>
#include <linux/netlink.h>
#include <linux/init.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/protocol.h>
#include <net/route.h>
#include <net/tcp.h>
#include <net/sock.h>
#include <net/ip_fib.h>
#include "fib_lookup.h"
static struct kmem_cache *fn_hash_kmem __read_mostly;
static struct kmem_cache *fn_alias_kmem __read_mostly;
struct fib_node {
struct hlist_node fn_hash;
struct list_head fn_alias;
__be32 fn_key;
struct fib_alias fn_embedded_alias;
};
struct fn_zone {
struct fn_zone *fz_next; /* Next not empty zone */
struct hlist_head *fz_hash; /* Hash table pointer */
int fz_nent; /* Number of entries */
int fz_divisor; /* Hash divisor */
u32 fz_hashmask; /* (fz_divisor - 1) */
#define FZ_HASHMASK(fz) ((fz)->fz_hashmask)
int fz_order; /* Zone order */
__be32 fz_mask;
#define FZ_MASK(fz) ((fz)->fz_mask)
};
/* NOTE. On fast computers evaluation of fz_hashmask and fz_mask
* can be cheaper than memory lookup, so that FZ_* macros are used.
*/
struct fn_hash {
struct fn_zone *fn_zones[33];
struct fn_zone *fn_zone_list;
};
static inline u32 fn_hash(__be32 key, struct fn_zone *fz)
{
u32 h = ntohl(key)>>(32 - fz->fz_order);
h ^= (h>>20);
h ^= (h>>10);
h ^= (h>>5);
h &= FZ_HASHMASK(fz);
return h;
}
static inline __be32 fz_key(__be32 dst, struct fn_zone *fz)
{
return dst & FZ_MASK(fz);
}
static DEFINE_RWLOCK(fib_hash_lock);
static unsigned int fib_hash_genid;
#define FZ_MAX_DIVISOR ((PAGE_SIZE<<MAX_ORDER) / sizeof(struct hlist_head))
static struct hlist_head *fz_hash_alloc(int divisor)
{
unsigned long size = divisor * sizeof(struct hlist_head);
if (size <= PAGE_SIZE) {
return kzalloc(size, GFP_KERNEL);
} else {
return (struct hlist_head *)
__get_free_pages(GFP_KERNEL | __GFP_ZERO, get_order(size));
}
}
/* The fib hash lock must be held when this is called. */
static inline void fn_rebuild_zone(struct fn_zone *fz,
struct hlist_head *old_ht,
int old_divisor)
{
int i;
for (i = 0; i < old_divisor; i++) {
struct hlist_node *node, *n;
struct fib_node *f;
hlist_for_each_entry_safe(f, node, n, &old_ht[i], fn_hash) {
struct hlist_head *new_head;
hlist_del(&f->fn_hash);
new_head = &fz->fz_hash[fn_hash(f->fn_key, fz)];
hlist_add_head(&f->fn_hash, new_head);
}
}
}
static void fz_hash_free(struct hlist_head *hash, int divisor)
{
unsigned long size = divisor * sizeof(struct hlist_head);
if (size <= PAGE_SIZE)
kfree(hash);
else
free_pages((unsigned long)hash, get_order(size));
}
static void fn_rehash_zone(struct fn_zone *fz)
{
struct hlist_head *ht, *old_ht;
int old_divisor, new_divisor;
u32 new_hashmask;
old_divisor = fz->fz_divisor;
switch (old_divisor) {
case 16:
new_divisor = 256;
break;
case 256:
new_divisor = 1024;
break;
default:
if ((old_divisor << 1) > FZ_MAX_DIVISOR) {
printk(KERN_CRIT "route.c: bad divisor %d!\n", old_divisor);
return;
}
new_divisor = (old_divisor << 1);
break;
}
new_hashmask = (new_divisor - 1);
#if RT_CACHE_DEBUG >= 2
printk(KERN_DEBUG "fn_rehash_zone: hash for zone %d grows from %d\n",
fz->fz_order, old_divisor);
#endif
ht = fz_hash_alloc(new_divisor);
if (ht) {
write_lock_bh(&fib_hash_lock);
old_ht = fz->fz_hash;
fz->fz_hash = ht;
fz->fz_hashmask = new_hashmask;
fz->fz_divisor = new_divisor;
fn_rebuild_zone(fz, old_ht, old_divisor);
fib_hash_genid++;
write_unlock_bh(&fib_hash_lock);
fz_hash_free(old_ht, old_divisor);
}
}
static inline void fn_free_node(struct fib_node * f)
{
kmem_cache_free(fn_hash_kmem, f);
}
static inline void fn_free_alias(struct fib_alias *fa, struct fib_node *f)
{
fib_release_info(fa->fa_info);
if (fa == &f->fn_embedded_alias)
fa->fa_info = NULL;
else
kmem_cache_free(fn_alias_kmem, fa);
}
static struct fn_zone *
fn_new_zone(struct fn_hash *table, int z)
{
int i;
struct fn_zone *fz = kzalloc(sizeof(struct fn_zone), GFP_KERNEL);
if (!fz)
return NULL;
if (z) {
fz->fz_divisor = 16;
} else {
fz->fz_divisor = 1;
}
fz->fz_hashmask = (fz->fz_divisor - 1);
fz->fz_hash = fz_hash_alloc(fz->fz_divisor);
if (!fz->fz_hash) {
kfree(fz);
return NULL;
}
fz->fz_order = z;
fz->fz_mask = inet_make_mask(z);
/* Find the first not empty zone with more specific mask */
for (i=z+1; i<=32; i++)
if (table->fn_zones[i])
break;
write_lock_bh(&fib_hash_lock);
if (i>32) {
/* No more specific masks, we are the first. */
fz->fz_next = table->fn_zone_list;
table->fn_zone_list = fz;
} else {
fz->fz_next = table->fn_zones[i]->fz_next;
table->fn_zones[i]->fz_next = fz;
}
table->fn_zones[z] = fz;
fib_hash_genid++;
write_unlock_bh(&fib_hash_lock);
return fz;
}
static int
fn_hash_lookup(struct fib_table *tb, const struct flowi *flp, struct fib_result *res)
{
int err;
struct fn_zone *fz;
struct fn_hash *t = (struct fn_hash *)tb->tb_data;
read_lock(&fib_hash_lock);
for (fz = t->fn_zone_list; fz; fz = fz->fz_next) {
struct hlist_head *head;
struct hlist_node *node;
struct fib_node *f;
__be32 k = fz_key(flp->fl4_dst, fz);
head = &fz->fz_hash[fn_hash(k, fz)];
hlist_for_each_entry(f, node, head, fn_hash) {
if (f->fn_key != k)
continue;
err = fib_semantic_match(&f->fn_alias,
flp, res,
fz->fz_order);
if (err <= 0)
goto out;
}
}
err = 1;
out:
read_unlock(&fib_hash_lock);
return err;
}
static void
fn_hash_select_default(struct fib_table *tb, const struct flowi *flp, struct fib_result *res)
{
int order, last_idx;
struct hlist_node *node;
struct fib_node *f;
struct fib_info *fi = NULL;
struct fib_info *last_resort;
struct fn_hash *t = (struct fn_hash *)tb->tb_data;
struct fn_zone *fz = t->fn_zones[0];
if (fz == NULL)
return;
last_idx = -1;
last_resort = NULL;
order = -1;
read_lock(&fib_hash_lock);
hlist_for_each_entry(f, node, &fz->fz_hash[0], fn_hash) {
struct fib_alias *fa;
list_for_each_entry(fa, &f->fn_alias, fa_list) {
struct fib_info *next_fi = fa->fa_info;
if (fa->fa_scope != res->scope ||
fa->fa_type != RTN_UNICAST)
continue;
if (next_fi->fib_priority > res->fi->fib_priority)
break;
if (!next_fi->fib_nh[0].nh_gw ||
next_fi->fib_nh[0].nh_scope != RT_SCOPE_LINK)
continue;
fa->fa_state |= FA_S_ACCESSED;
if (fi == NULL) {
if (next_fi != res->fi)
break;
} else if (!fib_detect_death(fi, order, &last_resort,
&last_idx, tb->tb_default)) {
fib_result_assign(res, fi);
tb->tb_default = order;
goto out;
}
fi = next_fi;
order++;
}
}
if (order <= 0 || fi == NULL) {
tb->tb_default = -1;
goto out;
}
if (!fib_detect_death(fi, order, &last_resort, &last_idx,
tb->tb_default)) {
fib_result_assign(res, fi);
tb->tb_default = order;
goto out;
}
if (last_idx >= 0)
fib_result_assign(res, last_resort);
tb->tb_default = last_idx;
out:
read_unlock(&fib_hash_lock);
}
/* Insert node F to FZ. */
static inline void fib_insert_node(struct fn_zone *fz, struct fib_node *f)
{
struct hlist_head *head = &fz->fz_hash[fn_hash(f->fn_key, fz)];
hlist_add_head(&f->fn_hash, head);
}
/* Return the node in FZ matching KEY. */
static struct fib_node *fib_find_node(struct fn_zone *fz, __be32 key)
{
struct hlist_head *head = &fz->fz_hash[fn_hash(key, fz)];
struct hlist_node *node;
struct fib_node *f;
hlist_for_each_entry(f, node, head, fn_hash) {
if (f->fn_key == key)
return f;
}
return NULL;
}
static int fn_hash_insert(struct fib_table *tb, struct fib_config *cfg)
{
struct fn_hash *table = (struct fn_hash *) tb->tb_data;
struct fib_node *new_f = NULL;
struct fib_node *f;
struct fib_alias *fa, *new_fa;
struct fn_zone *fz;
struct fib_info *fi;
u8 tos = cfg->fc_tos;
__be32 key;
int err;
if (cfg->fc_dst_len > 32)
return -EINVAL;
fz = table->fn_zones[cfg->fc_dst_len];
if (!fz && !(fz = fn_new_zone(table, cfg->fc_dst_len)))
return -ENOBUFS;
key = 0;
if (cfg->fc_dst) {
if (cfg->fc_dst & ~FZ_MASK(fz))
return -EINVAL;
key = fz_key(cfg->fc_dst, fz);
}
fi = fib_create_info(cfg);
if (IS_ERR(fi))
return PTR_ERR(fi);
if (fz->fz_nent > (fz->fz_divisor<<1) &&
fz->fz_divisor < FZ_MAX_DIVISOR &&
(cfg->fc_dst_len == 32 ||
(1 << cfg->fc_dst_len) > fz->fz_divisor))
fn_rehash_zone(fz);
f = fib_find_node(fz, key);
if (!f)
fa = NULL;
else
fa = fib_find_alias(&f->fn_alias, tos, fi->fib_priority);
/* Now fa, if non-NULL, points to the first fib alias
* with the same keys [prefix,tos,priority], if such key already
* exists or to the node before which we will insert new one.
*
* If fa is NULL, we will need to allocate a new one and
* insert to the head of f.
*
* If f is NULL, no fib node matched the destination key
* and we need to allocate a new one of those as well.
*/
if (fa && fa->fa_tos == tos &&
fa->fa_info->fib_priority == fi->fib_priority) {
struct fib_alias *fa_first, *fa_match;
err = -EEXIST;
if (cfg->fc_nlflags & NLM_F_EXCL)
goto out;
/* We have 2 goals:
* 1. Find exact match for type, scope, fib_info to avoid
* duplicate routes
* 2. Find next 'fa' (or head), NLM_F_APPEND inserts before it
*/
fa_match = NULL;
fa_first = fa;
fa = list_entry(fa->fa_list.prev, struct fib_alias, fa_list);
list_for_each_entry_continue(fa, &f->fn_alias, fa_list) {
if (fa->fa_tos != tos)
break;
if (fa->fa_info->fib_priority != fi->fib_priority)
break;
if (fa->fa_type == cfg->fc_type &&
fa->fa_scope == cfg->fc_scope &&
fa->fa_info == fi) {
fa_match = fa;
break;
}
}
if (cfg->fc_nlflags & NLM_F_REPLACE) {
struct fib_info *fi_drop;
u8 state;
fa = fa_first;
if (fa_match) {
if (fa == fa_match)
err = 0;
goto out;
}
write_lock_bh(&fib_hash_lock);
fi_drop = fa->fa_info;
fa->fa_info = fi;
fa->fa_type = cfg->fc_type;
fa->fa_scope = cfg->fc_scope;
state = fa->fa_state;
fa->fa_state &= ~FA_S_ACCESSED;
fib_hash_genid++;
write_unlock_bh(&fib_hash_lock);
fib_release_info(fi_drop);
if (state & FA_S_ACCESSED)
rt_cache_flush(cfg->fc_nlinfo.nl_net, -1);
rtmsg_fib(RTM_NEWROUTE, key, fa, cfg->fc_dst_len, tb->tb_id,
&cfg->fc_nlinfo, NLM_F_REPLACE);
return 0;
}
/* Error if we find a perfect match which
* uses the same scope, type, and nexthop
* information.
*/
if (fa_match)
goto out;
if (!(cfg->fc_nlflags & NLM_F_APPEND))
fa = fa_first;
}
err = -ENOENT;
if (!(cfg->fc_nlflags & NLM_F_CREATE))
goto out;
err = -ENOBUFS;
if (!f) {
new_f = kmem_cache_zalloc(fn_hash_kmem, GFP_KERNEL);
if (new_f == NULL)
goto out;
INIT_HLIST_NODE(&new_f->fn_hash);
INIT_LIST_HEAD(&new_f->fn_alias);
new_f->fn_key = key;
f = new_f;
}
new_fa = &f->fn_embedded_alias;
if (new_fa->fa_info != NULL) {
new_fa = kmem_cache_alloc(fn_alias_kmem, GFP_KERNEL);
if (new_fa == NULL)
goto out;
}
new_fa->fa_info = fi;
new_fa->fa_tos = tos;
new_fa->fa_type = cfg->fc_type;
new_fa->fa_scope = cfg->fc_scope;
new_fa->fa_state = 0;
/*
* Insert new entry to the list.
*/
write_lock_bh(&fib_hash_lock);
if (new_f)
fib_insert_node(fz, new_f);
list_add_tail(&new_fa->fa_list,
(fa ? &fa->fa_list : &f->fn_alias));
fib_hash_genid++;
write_unlock_bh(&fib_hash_lock);
if (new_f)
fz->fz_nent++;
rt_cache_flush(cfg->fc_nlinfo.nl_net, -1);
rtmsg_fib(RTM_NEWROUTE, key, new_fa, cfg->fc_dst_len, tb->tb_id,
&cfg->fc_nlinfo, 0);
return 0;
out:
if (new_f)
kmem_cache_free(fn_hash_kmem, new_f);
fib_release_info(fi);
return err;
}
static int fn_hash_delete(struct fib_table *tb, struct fib_config *cfg)
{
struct fn_hash *table = (struct fn_hash *)tb->tb_data;
struct fib_node *f;
struct fib_alias *fa, *fa_to_delete;
struct fn_zone *fz;
__be32 key;
if (cfg->fc_dst_len > 32)
return -EINVAL;
if ((fz = table->fn_zones[cfg->fc_dst_len]) == NULL)
return -ESRCH;
key = 0;
if (cfg->fc_dst) {
if (cfg->fc_dst & ~FZ_MASK(fz))
return -EINVAL;
key = fz_key(cfg->fc_dst, fz);
}
f = fib_find_node(fz, key);
if (!f)
fa = NULL;
else
fa = fib_find_alias(&f->fn_alias, cfg->fc_tos, 0);
if (!fa)
return -ESRCH;
fa_to_delete = NULL;
fa = list_entry(fa->fa_list.prev, struct fib_alias, fa_list);
list_for_each_entry_continue(fa, &f->fn_alias, fa_list) {
struct fib_info *fi = fa->fa_info;
if (fa->fa_tos != cfg->fc_tos)
break;
if ((!cfg->fc_type ||
fa->fa_type == cfg->fc_type) &&
(cfg->fc_scope == RT_SCOPE_NOWHERE ||
fa->fa_scope == cfg->fc_scope) &&
(!cfg->fc_protocol ||
fi->fib_protocol == cfg->fc_protocol) &&
fib_nh_match(cfg, fi) == 0) {
fa_to_delete = fa;
break;
}
}
if (fa_to_delete) {
int kill_fn;
fa = fa_to_delete;
rtmsg_fib(RTM_DELROUTE, key, fa, cfg->fc_dst_len,
tb->tb_id, &cfg->fc_nlinfo, 0);
kill_fn = 0;
write_lock_bh(&fib_hash_lock);
list_del(&fa->fa_list);
if (list_empty(&f->fn_alias)) {
hlist_del(&f->fn_hash);
kill_fn = 1;
}
fib_hash_genid++;
write_unlock_bh(&fib_hash_lock);
if (fa->fa_state & FA_S_ACCESSED)
rt_cache_flush(cfg->fc_nlinfo.nl_net, -1);
fn_free_alias(fa, f);
if (kill_fn) {
fn_free_node(f);
fz->fz_nent--;
}
return 0;
}
return -ESRCH;
}
static int fn_flush_list(struct fn_zone *fz, int idx)
{
struct hlist_head *head = &fz->fz_hash[idx];
struct hlist_node *node, *n;
struct fib_node *f;
int found = 0;
hlist_for_each_entry_safe(f, node, n, head, fn_hash) {
struct fib_alias *fa, *fa_node;
int kill_f;
kill_f = 0;
list_for_each_entry_safe(fa, fa_node, &f->fn_alias, fa_list) {
struct fib_info *fi = fa->fa_info;
if (fi && (fi->fib_flags&RTNH_F_DEAD)) {
write_lock_bh(&fib_hash_lock);
list_del(&fa->fa_list);
if (list_empty(&f->fn_alias)) {
hlist_del(&f->fn_hash);
kill_f = 1;
}
fib_hash_genid++;
write_unlock_bh(&fib_hash_lock);
fn_free_alias(fa, f);
found++;
}
}
if (kill_f) {
fn_free_node(f);
fz->fz_nent--;
}
}
return found;
}
static int fn_hash_flush(struct fib_table *tb)
{
struct fn_hash *table = (struct fn_hash *) tb->tb_data;
struct fn_zone *fz;
int found = 0;
for (fz = table->fn_zone_list; fz; fz = fz->fz_next) {
int i;
for (i = fz->fz_divisor - 1; i >= 0; i--)
found += fn_flush_list(fz, i);
}
return found;
}
static inline int
fn_hash_dump_bucket(struct sk_buff *skb, struct netlink_callback *cb,
struct fib_table *tb,
struct fn_zone *fz,
struct hlist_head *head)
{
struct hlist_node *node;
struct fib_node *f;
int i, s_i;
s_i = cb->args[4];
i = 0;
hlist_for_each_entry(f, node, head, fn_hash) {
struct fib_alias *fa;
list_for_each_entry(fa, &f->fn_alias, fa_list) {
if (i < s_i)
goto next;
if (fib_dump_info(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq,
RTM_NEWROUTE,
tb->tb_id,
fa->fa_type,
fa->fa_scope,
f->fn_key,
fz->fz_order,
fa->fa_tos,
fa->fa_info,
NLM_F_MULTI) < 0) {
cb->args[4] = i;
return -1;
}
next:
i++;
}
}
cb->args[4] = i;
return skb->len;
}
static inline int
fn_hash_dump_zone(struct sk_buff *skb, struct netlink_callback *cb,
struct fib_table *tb,
struct fn_zone *fz)
{
int h, s_h;
if (fz->fz_hash == NULL)
return skb->len;
s_h = cb->args[3];
for (h = s_h; h < fz->fz_divisor; h++) {
if (hlist_empty(&fz->fz_hash[h]))
continue;
if (fn_hash_dump_bucket(skb, cb, tb, fz, &fz->fz_hash[h]) < 0) {
cb->args[3] = h;
return -1;
}
memset(&cb->args[4], 0,
sizeof(cb->args) - 4*sizeof(cb->args[0]));
}
cb->args[3] = h;
return skb->len;
}
static int fn_hash_dump(struct fib_table *tb, struct sk_buff *skb, struct netlink_callback *cb)
{
int m, s_m;
struct fn_zone *fz;
struct fn_hash *table = (struct fn_hash *)tb->tb_data;
s_m = cb->args[2];
read_lock(&fib_hash_lock);
for (fz = table->fn_zone_list, m=0; fz; fz = fz->fz_next, m++) {
if (m < s_m) continue;
if (fn_hash_dump_zone(skb, cb, tb, fz) < 0) {
cb->args[2] = m;
read_unlock(&fib_hash_lock);
return -1;
}
memset(&cb->args[3], 0,
sizeof(cb->args) - 3*sizeof(cb->args[0]));
}
read_unlock(&fib_hash_lock);
cb->args[2] = m;
return skb->len;
}
void __init fib_hash_init(void)
{
fn_hash_kmem = kmem_cache_create("ip_fib_hash", sizeof(struct fib_node),
0, SLAB_PANIC, NULL);
fn_alias_kmem = kmem_cache_create("ip_fib_alias", sizeof(struct fib_alias),
0, SLAB_PANIC, NULL);
}
struct fib_table *fib_hash_table(u32 id)
{
struct fib_table *tb;
tb = kmalloc(sizeof(struct fib_table) + sizeof(struct fn_hash),
GFP_KERNEL);
if (tb == NULL)
return NULL;
tb->tb_id = id;
tb->tb_default = -1;
tb->tb_lookup = fn_hash_lookup;
tb->tb_insert = fn_hash_insert;
tb->tb_delete = fn_hash_delete;
tb->tb_flush = fn_hash_flush;
tb->tb_select_default = fn_hash_select_default;
tb->tb_dump = fn_hash_dump;
memset(tb->tb_data, 0, sizeof(struct fn_hash));
return tb;
}
/* ------------------------------------------------------------------------ */
#ifdef CONFIG_PROC_FS
struct fib_iter_state {
struct seq_net_private p;
struct fn_zone *zone;
int bucket;
struct hlist_head *hash_head;
struct fib_node *fn;
struct fib_alias *fa;
loff_t pos;
unsigned int genid;
int valid;
};
static struct fib_alias *fib_get_first(struct seq_file *seq)
{
struct fib_iter_state *iter = seq->private;
struct fib_table *main_table;
struct fn_hash *table;
main_table = fib_get_table(seq_file_net(seq), RT_TABLE_MAIN);
table = (struct fn_hash *)main_table->tb_data;
iter->bucket = 0;
iter->hash_head = NULL;
iter->fn = NULL;
iter->fa = NULL;
iter->pos = 0;
iter->genid = fib_hash_genid;
iter->valid = 1;
for (iter->zone = table->fn_zone_list; iter->zone;
iter->zone = iter->zone->fz_next) {
int maxslot;
if (!iter->zone->fz_nent)
continue;
iter->hash_head = iter->zone->fz_hash;
maxslot = iter->zone->fz_divisor;
for (iter->bucket = 0; iter->bucket < maxslot;
++iter->bucket, ++iter->hash_head) {
struct hlist_node *node;
struct fib_node *fn;
hlist_for_each_entry(fn, node, iter->hash_head, fn_hash) {
struct fib_alias *fa;
list_for_each_entry(fa, &fn->fn_alias, fa_list) {
iter->fn = fn;
iter->fa = fa;
goto out;
}
}
}
}
out:
return iter->fa;
}
static struct fib_alias *fib_get_next(struct seq_file *seq)
{
struct fib_iter_state *iter = seq->private;
struct fib_node *fn;
struct fib_alias *fa;
/* Advance FA, if any. */
fn = iter->fn;
fa = iter->fa;
if (fa) {
BUG_ON(!fn);
list_for_each_entry_continue(fa, &fn->fn_alias, fa_list) {
iter->fa = fa;
goto out;
}
}
fa = iter->fa = NULL;
/* Advance FN. */
if (fn) {
struct hlist_node *node = &fn->fn_hash;
hlist_for_each_entry_continue(fn, node, fn_hash) {
iter->fn = fn;
list_for_each_entry(fa, &fn->fn_alias, fa_list) {
iter->fa = fa;
goto out;
}
}
}
fn = iter->fn = NULL;
/* Advance hash chain. */
if (!iter->zone)
goto out;
for (;;) {
struct hlist_node *node;
int maxslot;
maxslot = iter->zone->fz_divisor;
while (++iter->bucket < maxslot) {
iter->hash_head++;
hlist_for_each_entry(fn, node, iter->hash_head, fn_hash) {
list_for_each_entry(fa, &fn->fn_alias, fa_list) {
iter->fn = fn;
iter->fa = fa;
goto out;
}
}
}
iter->zone = iter->zone->fz_next;
if (!iter->zone)
goto out;
iter->bucket = 0;
iter->hash_head = iter->zone->fz_hash;
hlist_for_each_entry(fn, node, iter->hash_head, fn_hash) {
list_for_each_entry(fa, &fn->fn_alias, fa_list) {
iter->fn = fn;
iter->fa = fa;
goto out;
}
}
}
out:
iter->pos++;
return fa;
}
static struct fib_alias *fib_get_idx(struct seq_file *seq, loff_t pos)
{
struct fib_iter_state *iter = seq->private;
struct fib_alias *fa;
if (iter->valid && pos >= iter->pos && iter->genid == fib_hash_genid) {
fa = iter->fa;
pos -= iter->pos;
} else
fa = fib_get_first(seq);
if (fa)
while (pos && (fa = fib_get_next(seq)))
--pos;
return pos ? NULL : fa;
}
static void *fib_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(fib_hash_lock)
{
void *v = NULL;
read_lock(&fib_hash_lock);
if (fib_get_table(seq_file_net(seq), RT_TABLE_MAIN))
v = *pos ? fib_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
return v;
}
static void *fib_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return v == SEQ_START_TOKEN ? fib_get_first(seq) : fib_get_next(seq);
}
static void fib_seq_stop(struct seq_file *seq, void *v)
__releases(fib_hash_lock)
{
read_unlock(&fib_hash_lock);
}
static unsigned fib_flag_trans(int type, __be32 mask, struct fib_info *fi)
{
static const unsigned type2flags[RTN_MAX + 1] = {
[7] = RTF_REJECT, [8] = RTF_REJECT,
};
unsigned flags = type2flags[type];
if (fi && fi->fib_nh->nh_gw)
flags |= RTF_GATEWAY;
if (mask == htonl(0xFFFFFFFF))
flags |= RTF_HOST;
flags |= RTF_UP;
return flags;
}
/*
* This outputs /proc/net/route.
*
* It always works in backward compatibility mode.
* The format of the file is not supposed to be changed.
*/
static int fib_seq_show(struct seq_file *seq, void *v)
{
struct fib_iter_state *iter;
int len;
__be32 prefix, mask;
unsigned flags;
struct fib_node *f;
struct fib_alias *fa;
struct fib_info *fi;
if (v == SEQ_START_TOKEN) {
seq_printf(seq, "%-127s\n", "Iface\tDestination\tGateway "
"\tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU"
"\tWindow\tIRTT");
goto out;
}
iter = seq->private;
f = iter->fn;
fa = iter->fa;
fi = fa->fa_info;
prefix = f->fn_key;
mask = FZ_MASK(iter->zone);
flags = fib_flag_trans(fa->fa_type, mask, fi);
if (fi)
seq_printf(seq,
"%s\t%08X\t%08X\t%04X\t%d\t%u\t%d\t%08X\t%d\t%u\t%u%n",
fi->fib_dev ? fi->fib_dev->name : "*", prefix,
fi->fib_nh->nh_gw, flags, 0, 0, fi->fib_priority,
mask, (fi->fib_advmss ? fi->fib_advmss + 40 : 0),
fi->fib_window,
fi->fib_rtt >> 3, &len);
else
seq_printf(seq,
"*\t%08X\t%08X\t%04X\t%d\t%u\t%d\t%08X\t%d\t%u\t%u%n",
prefix, 0, flags, 0, 0, 0, mask, 0, 0, 0, &len);
seq_printf(seq, "%*s\n", 127 - len, "");
out:
return 0;
}
static const struct seq_operations fib_seq_ops = {
.start = fib_seq_start,
.next = fib_seq_next,
.stop = fib_seq_stop,
.show = fib_seq_show,
};
static int fib_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &fib_seq_ops,
sizeof(struct fib_iter_state));
}
static const struct file_operations fib_seq_fops = {
.owner = THIS_MODULE,
.open = fib_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
int __net_init fib_proc_init(struct net *net)
{
if (!proc_net_fops_create(net, "route", S_IRUGO, &fib_seq_fops))
return -ENOMEM;
return 0;
}
void __net_exit fib_proc_exit(struct net *net)
{
proc_net_remove(net, "route");
}
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
pccr10001/Kernel-2.6.32.61-for-PDK-7105 | drivers/mtd/maps/ipaq-flash.c | 518 | 11582 | /*
* Flash memory access on iPAQ Handhelds (either SA1100 or PXA250 based)
*
* (C) 2000 Nicolas Pitre <nico@fluxnic.net>
* (C) 2002 Hewlett-Packard Company <jamey.hicks@hp.com>
* (C) 2003 Christian Pellegrin <chri@ascensit.com>, <chri@infis.univ.ts.it>: concatenation of multiple flashes
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <asm/page.h>
#include <asm/mach-types.h>
#include <asm/system.h>
#include <asm/errno.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#ifdef CONFIG_MTD_CONCAT
#include <linux/mtd/concat.h>
#endif
#include <mach/hardware.h>
#include <mach/h3600.h>
#include <asm/io.h>
#ifndef CONFIG_IPAQ_HANDHELD
#error This is for iPAQ Handhelds only
#endif
#ifdef CONFIG_SA1100_JORNADA56X
static void jornada56x_set_vpp(struct map_info *map, int vpp)
{
if (vpp)
GPSR = GPIO_GPIO26;
else
GPCR = GPIO_GPIO26;
GPDR |= GPIO_GPIO26;
}
#endif
#ifdef CONFIG_SA1100_JORNADA720
static void jornada720_set_vpp(struct map_info *map, int vpp)
{
if (vpp)
PPSR |= 0x80;
else
PPSR &= ~0x80;
PPDR |= 0x80;
}
#endif
#define MAX_IPAQ_CS 2 /* Number of CS we are going to test */
#define IPAQ_MAP_INIT(X) \
{ \
name: "IPAQ flash " X, \
}
static struct map_info ipaq_map[MAX_IPAQ_CS] = {
IPAQ_MAP_INIT("bank 1"),
IPAQ_MAP_INIT("bank 2")
};
static struct mtd_info *my_sub_mtd[MAX_IPAQ_CS] = {
NULL,
NULL
};
/*
* Here are partition information for all known IPAQ-based devices.
* See include/linux/mtd/partitions.h for definition of the mtd_partition
* structure.
*
* The *_max_flash_size is the maximum possible mapped flash size which
* is not necessarily the actual flash size. It must be no more than
* the value specified in the "struct map_desc *_io_desc" mapping
* definition for the corresponding machine.
*
* Please keep these in alphabetical order, and formatted as per existing
* entries. Thanks.
*/
#ifdef CONFIG_IPAQ_HANDHELD
static unsigned long h3xxx_max_flash_size = 0x04000000;
static struct mtd_partition h3xxx_partitions[] = {
{
name: "H3XXX boot firmware",
#ifndef CONFIG_LAB
size: 0x00040000,
#else
size: 0x00080000,
#endif
offset: 0,
#ifndef CONFIG_LAB
mask_flags: MTD_WRITEABLE, /* force read-only */
#endif
},
{
name: "H3XXX root jffs2",
#ifndef CONFIG_LAB
size: 0x2000000 - 2*0x40000, /* Warning, this is fixed later */
offset: 0x00040000,
#else
size: 0x2000000 - 0x40000 - 0x80000, /* Warning, this is fixed later */
offset: 0x00080000,
#endif
},
{
name: "asset",
size: 0x40000,
offset: 0x2000000 - 0x40000, /* Warning, this is fixed later */
mask_flags: MTD_WRITEABLE, /* force read-only */
}
};
#ifndef CONFIG_MTD_CONCAT
static struct mtd_partition h3xxx_partitions_bank2[] = {
/* this is used only on 2 CS machines when concat is not present */
{
name: "second H3XXX root jffs2",
size: 0x1000000 - 0x40000, /* Warning, this is fixed later */
offset: 0x00000000,
},
{
name: "second asset",
size: 0x40000,
offset: 0x1000000 - 0x40000, /* Warning, this is fixed later */
mask_flags: MTD_WRITEABLE, /* force read-only */
}
};
#endif
static DEFINE_SPINLOCK(ipaq_vpp_lock);
static void h3xxx_set_vpp(struct map_info *map, int vpp)
{
static int nest = 0;
spin_lock(&ipaq_vpp_lock);
if (vpp)
nest++;
else
nest--;
if (nest)
assign_h3600_egpio(IPAQ_EGPIO_VPP_ON, 1);
else
assign_h3600_egpio(IPAQ_EGPIO_VPP_ON, 0);
spin_unlock(&ipaq_vpp_lock);
}
#endif
#if defined(CONFIG_SA1100_JORNADA56X) || defined(CONFIG_SA1100_JORNADA720)
static unsigned long jornada_max_flash_size = 0x02000000;
static struct mtd_partition jornada_partitions[] = {
{
name: "Jornada boot firmware",
size: 0x00040000,
offset: 0,
mask_flags: MTD_WRITEABLE, /* force read-only */
}, {
name: "Jornada root jffs2",
size: MTDPART_SIZ_FULL,
offset: 0x00040000,
}
};
#endif
static struct mtd_partition *parsed_parts;
static struct mtd_info *mymtd;
static unsigned long cs_phys[] = {
#ifdef CONFIG_ARCH_SA1100
SA1100_CS0_PHYS,
SA1100_CS1_PHYS,
SA1100_CS2_PHYS,
SA1100_CS3_PHYS,
SA1100_CS4_PHYS,
SA1100_CS5_PHYS,
#else
PXA_CS0_PHYS,
PXA_CS1_PHYS,
PXA_CS2_PHYS,
PXA_CS3_PHYS,
PXA_CS4_PHYS,
PXA_CS5_PHYS,
#endif
};
static const char *part_probes[] = { "cmdlinepart", "RedBoot", NULL };
static int __init h1900_special_case(void);
static int __init ipaq_mtd_init(void)
{
struct mtd_partition *parts = NULL;
int nb_parts = 0;
int parsed_nr_parts = 0;
const char *part_type;
int i; /* used when we have >1 flash chips */
unsigned long tot_flashsize = 0; /* used when we have >1 flash chips */
/* Default flash bankwidth */
// ipaq_map.bankwidth = (MSC0 & MSC_RBW) ? 2 : 4;
if (machine_is_h1900())
{
/* For our intents, the h1900 is not a real iPAQ, so we special-case it. */
return h1900_special_case();
}
if (machine_is_h3100() || machine_is_h1900())
for(i=0; i<MAX_IPAQ_CS; i++)
ipaq_map[i].bankwidth = 2;
else
for(i=0; i<MAX_IPAQ_CS; i++)
ipaq_map[i].bankwidth = 4;
/*
* Static partition definition selection
*/
part_type = "static";
simple_map_init(&ipaq_map[0]);
simple_map_init(&ipaq_map[1]);
#ifdef CONFIG_IPAQ_HANDHELD
if (machine_is_ipaq()) {
parts = h3xxx_partitions;
nb_parts = ARRAY_SIZE(h3xxx_partitions);
for(i=0; i<MAX_IPAQ_CS; i++) {
ipaq_map[i].size = h3xxx_max_flash_size;
ipaq_map[i].set_vpp = h3xxx_set_vpp;
ipaq_map[i].phys = cs_phys[i];
ipaq_map[i].virt = ioremap(cs_phys[i], 0x04000000);
if (machine_is_h3100 () || machine_is_h1900())
ipaq_map[i].bankwidth = 2;
}
if (machine_is_h3600()) {
/* No asset partition here */
h3xxx_partitions[1].size += 0x40000;
nb_parts--;
}
}
#endif
#ifdef CONFIG_ARCH_H5400
if (machine_is_h5400()) {
ipaq_map[0].size = 0x02000000;
ipaq_map[1].size = 0x02000000;
ipaq_map[1].phys = 0x02000000;
ipaq_map[1].virt = ipaq_map[0].virt + 0x02000000;
}
#endif
#ifdef CONFIG_ARCH_H1900
if (machine_is_h1900()) {
ipaq_map[0].size = 0x00400000;
ipaq_map[1].size = 0x02000000;
ipaq_map[1].phys = 0x00080000;
ipaq_map[1].virt = ipaq_map[0].virt + 0x00080000;
}
#endif
#ifdef CONFIG_SA1100_JORNADA56X
if (machine_is_jornada56x()) {
parts = jornada_partitions;
nb_parts = ARRAY_SIZE(jornada_partitions);
ipaq_map[0].size = jornada_max_flash_size;
ipaq_map[0].set_vpp = jornada56x_set_vpp;
ipaq_map[0].virt = (__u32)ioremap(0x0, 0x04000000);
}
#endif
#ifdef CONFIG_SA1100_JORNADA720
if (machine_is_jornada720()) {
parts = jornada_partitions;
nb_parts = ARRAY_SIZE(jornada_partitions);
ipaq_map[0].size = jornada_max_flash_size;
ipaq_map[0].set_vpp = jornada720_set_vpp;
}
#endif
if (machine_is_ipaq()) { /* for iPAQs only */
for(i=0; i<MAX_IPAQ_CS; i++) {
printk(KERN_NOTICE "iPAQ flash: probing %d-bit flash bus, window=%lx with CFI.\n", ipaq_map[i].bankwidth*8, ipaq_map[i].virt);
my_sub_mtd[i] = do_map_probe("cfi_probe", &ipaq_map[i]);
if (!my_sub_mtd[i]) {
printk(KERN_NOTICE "iPAQ flash: probing %d-bit flash bus, window=%lx with JEDEC.\n", ipaq_map[i].bankwidth*8, ipaq_map[i].virt);
my_sub_mtd[i] = do_map_probe("jedec_probe", &ipaq_map[i]);
}
if (!my_sub_mtd[i]) {
printk(KERN_NOTICE "iPAQ flash: failed to find flash.\n");
if (i)
break;
else
return -ENXIO;
} else
printk(KERN_NOTICE "iPAQ flash: found %d bytes\n", my_sub_mtd[i]->size);
/* do we really need this debugging? --joshua 20030703 */
// printk("my_sub_mtd[%d]=%p\n", i, my_sub_mtd[i]);
my_sub_mtd[i]->owner = THIS_MODULE;
tot_flashsize += my_sub_mtd[i]->size;
}
#ifdef CONFIG_MTD_CONCAT
/* fix the asset location */
# ifdef CONFIG_LAB
h3xxx_partitions[1].size = tot_flashsize - 0x40000 - 0x80000 /* extra big boot block */;
# else
h3xxx_partitions[1].size = tot_flashsize - 2 * 0x40000;
# endif
h3xxx_partitions[2].offset = tot_flashsize - 0x40000;
/* and concat the devices */
mymtd = mtd_concat_create(&my_sub_mtd[0], i,
"ipaq");
if (!mymtd) {
printk("Cannot create iPAQ concat device\n");
return -ENXIO;
}
#else
mymtd = my_sub_mtd[0];
/*
*In the very near future, command line partition parsing
* will use the device name as 'mtd-id' instead of a value
* passed to the parse_cmdline_partitions() routine. Since
* the bootldr says 'ipaq', make sure it continues to work.
*/
mymtd->name = "ipaq";
if ((machine_is_h3600())) {
# ifdef CONFIG_LAB
h3xxx_partitions[1].size = my_sub_mtd[0]->size - 0x80000;
# else
h3xxx_partitions[1].size = my_sub_mtd[0]->size - 0x40000;
# endif
nb_parts = 2;
} else {
# ifdef CONFIG_LAB
h3xxx_partitions[1].size = my_sub_mtd[0]->size - 0x40000 - 0x80000; /* extra big boot block */
# else
h3xxx_partitions[1].size = my_sub_mtd[0]->size - 2*0x40000;
# endif
h3xxx_partitions[2].offset = my_sub_mtd[0]->size - 0x40000;
}
if (my_sub_mtd[1]) {
# ifdef CONFIG_LAB
h3xxx_partitions_bank2[0].size = my_sub_mtd[1]->size - 0x80000;
# else
h3xxx_partitions_bank2[0].size = my_sub_mtd[1]->size - 0x40000;
# endif
h3xxx_partitions_bank2[1].offset = my_sub_mtd[1]->size - 0x40000;
}
#endif
}
else {
/*
* Now let's probe for the actual flash. Do it here since
* specific machine settings might have been set above.
*/
printk(KERN_NOTICE "IPAQ flash: probing %d-bit flash bus, window=%lx\n", ipaq_map[0].bankwidth*8, ipaq_map[0].virt);
mymtd = do_map_probe("cfi_probe", &ipaq_map[0]);
if (!mymtd)
return -ENXIO;
mymtd->owner = THIS_MODULE;
}
/*
* Dynamic partition selection stuff (might override the static ones)
*/
i = parse_mtd_partitions(mymtd, part_probes, &parsed_parts, 0);
if (i > 0) {
nb_parts = parsed_nr_parts = i;
parts = parsed_parts;
part_type = "dynamic";
}
if (!parts) {
printk(KERN_NOTICE "IPAQ flash: no partition info available, registering whole flash at once\n");
add_mtd_device(mymtd);
#ifndef CONFIG_MTD_CONCAT
if (my_sub_mtd[1])
add_mtd_device(my_sub_mtd[1]);
#endif
} else {
printk(KERN_NOTICE "Using %s partition definition\n", part_type);
add_mtd_partitions(mymtd, parts, nb_parts);
#ifndef CONFIG_MTD_CONCAT
if (my_sub_mtd[1])
add_mtd_partitions(my_sub_mtd[1], h3xxx_partitions_bank2, ARRAY_SIZE(h3xxx_partitions_bank2));
#endif
}
return 0;
}
static void __exit ipaq_mtd_cleanup(void)
{
int i;
if (mymtd) {
del_mtd_partitions(mymtd);
#ifndef CONFIG_MTD_CONCAT
if (my_sub_mtd[1])
del_mtd_partitions(my_sub_mtd[1]);
#endif
map_destroy(mymtd);
#ifdef CONFIG_MTD_CONCAT
for(i=0; i<MAX_IPAQ_CS; i++)
#else
for(i=1; i<MAX_IPAQ_CS; i++)
#endif
{
if (my_sub_mtd[i])
map_destroy(my_sub_mtd[i]);
}
kfree(parsed_parts);
}
}
static int __init h1900_special_case(void)
{
/* The iPAQ h1900 is a special case - it has weird ROM. */
simple_map_init(&ipaq_map[0]);
ipaq_map[0].size = 0x80000;
ipaq_map[0].set_vpp = h3xxx_set_vpp;
ipaq_map[0].phys = 0x0;
ipaq_map[0].virt = ioremap(0x0, 0x04000000);
ipaq_map[0].bankwidth = 2;
printk(KERN_NOTICE "iPAQ flash: probing %d-bit flash bus, window=%lx with JEDEC.\n", ipaq_map[0].bankwidth*8, ipaq_map[0].virt);
mymtd = do_map_probe("jedec_probe", &ipaq_map[0]);
if (!mymtd)
return -ENODEV;
add_mtd_device(mymtd);
printk(KERN_NOTICE "iPAQ flash: registered h1910 flash\n");
return 0;
}
module_init(ipaq_mtd_init);
module_exit(ipaq_mtd_cleanup);
MODULE_AUTHOR("Jamey Hicks");
MODULE_DESCRIPTION("IPAQ CFI map driver");
MODULE_LICENSE("MIT");
| gpl-2.0 |
dwindsor/linux-next | drivers/watchdog/gef_wdt.c | 774 | 7672 | /*
* GE watchdog userspace interface
*
* Author: Martyn Welch <martyn.welch@ge.com>
*
* Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc.
*
* 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; either version 2 of the License, or (at your
* option) any later version.
*
* Based on: mv64x60_wdt.c (MV64X60 watchdog userspace interface)
* Author: James Chapman <jchapman@katalix.com>
*/
/* TODO:
* This driver does not provide support for the hardwares capability of sending
* an interrupt at a programmable threshold.
*
* This driver currently can only support 1 watchdog - there are 2 in the
* hardware that this driver supports. Thus one could be configured as a
* process-based watchdog (via /dev/watchdog), the second (using the interrupt
* capabilities) a kernel-based watchdog.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/compiler.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/fs.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <sysdev/fsl_soc.h>
/*
* The watchdog configuration register contains a pair of 2-bit fields,
* 1. a reload field, bits 27-26, which triggers a reload of
* the countdown register, and
* 2. an enable field, bits 25-24, which toggles between
* enabling and disabling the watchdog timer.
* Bit 31 is a read-only field which indicates whether the
* watchdog timer is currently enabled.
*
* The low 24 bits contain the timer reload value.
*/
#define GEF_WDC_ENABLE_SHIFT 24
#define GEF_WDC_SERVICE_SHIFT 26
#define GEF_WDC_ENABLED_SHIFT 31
#define GEF_WDC_ENABLED_TRUE 1
#define GEF_WDC_ENABLED_FALSE 0
/* Flags bits */
#define GEF_WDOG_FLAG_OPENED 0
static unsigned long wdt_flags;
static int wdt_status;
static void __iomem *gef_wdt_regs;
static int gef_wdt_timeout;
static int gef_wdt_count;
static unsigned int bus_clk;
static char expect_close;
static DEFINE_SPINLOCK(gef_wdt_spinlock);
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static int gef_wdt_toggle_wdc(int enabled_predicate, int field_shift)
{
u32 data;
u32 enabled;
int ret = 0;
spin_lock(&gef_wdt_spinlock);
data = ioread32be(gef_wdt_regs);
enabled = (data >> GEF_WDC_ENABLED_SHIFT) & 1;
/* only toggle the requested field if enabled state matches predicate */
if ((enabled ^ enabled_predicate) == 0) {
/* We write a 1, then a 2 -- to the appropriate field */
data = (1 << field_shift) | gef_wdt_count;
iowrite32be(data, gef_wdt_regs);
data = (2 << field_shift) | gef_wdt_count;
iowrite32be(data, gef_wdt_regs);
ret = 1;
}
spin_unlock(&gef_wdt_spinlock);
return ret;
}
static void gef_wdt_service(void)
{
gef_wdt_toggle_wdc(GEF_WDC_ENABLED_TRUE,
GEF_WDC_SERVICE_SHIFT);
}
static void gef_wdt_handler_enable(void)
{
if (gef_wdt_toggle_wdc(GEF_WDC_ENABLED_FALSE,
GEF_WDC_ENABLE_SHIFT)) {
gef_wdt_service();
pr_notice("watchdog activated\n");
}
}
static void gef_wdt_handler_disable(void)
{
if (gef_wdt_toggle_wdc(GEF_WDC_ENABLED_TRUE,
GEF_WDC_ENABLE_SHIFT))
pr_notice("watchdog deactivated\n");
}
static void gef_wdt_set_timeout(unsigned int timeout)
{
/* maximum bus cycle count is 0xFFFFFFFF */
if (timeout > 0xFFFFFFFF / bus_clk)
timeout = 0xFFFFFFFF / bus_clk;
/* Register only holds upper 24 bits, bit shifted into lower 24 */
gef_wdt_count = (timeout * bus_clk) >> 8;
gef_wdt_timeout = timeout;
}
static ssize_t gef_wdt_write(struct file *file, const char __user *data,
size_t len, loff_t *ppos)
{
if (len) {
if (!nowayout) {
size_t i;
expect_close = 0;
for (i = 0; i != len; i++) {
char c;
if (get_user(c, data + i))
return -EFAULT;
if (c == 'V')
expect_close = 42;
}
}
gef_wdt_service();
}
return len;
}
static long gef_wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int timeout;
int options;
void __user *argp = (void __user *)arg;
static const struct watchdog_info info = {
.options = WDIOF_SETTIMEOUT | WDIOF_MAGICCLOSE |
WDIOF_KEEPALIVEPING,
.firmware_version = 0,
.identity = "GE watchdog",
};
switch (cmd) {
case WDIOC_GETSUPPORT:
if (copy_to_user(argp, &info, sizeof(info)))
return -EFAULT;
break;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
if (put_user(wdt_status, (int __user *)argp))
return -EFAULT;
wdt_status &= ~WDIOF_KEEPALIVEPING;
break;
case WDIOC_SETOPTIONS:
if (get_user(options, (int __user *)argp))
return -EFAULT;
if (options & WDIOS_DISABLECARD)
gef_wdt_handler_disable();
if (options & WDIOS_ENABLECARD)
gef_wdt_handler_enable();
break;
case WDIOC_KEEPALIVE:
gef_wdt_service();
wdt_status |= WDIOF_KEEPALIVEPING;
break;
case WDIOC_SETTIMEOUT:
if (get_user(timeout, (int __user *)argp))
return -EFAULT;
gef_wdt_set_timeout(timeout);
/* Fall through */
case WDIOC_GETTIMEOUT:
if (put_user(gef_wdt_timeout, (int __user *)argp))
return -EFAULT;
break;
default:
return -ENOTTY;
}
return 0;
}
static int gef_wdt_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(GEF_WDOG_FLAG_OPENED, &wdt_flags))
return -EBUSY;
if (nowayout)
__module_get(THIS_MODULE);
gef_wdt_handler_enable();
return nonseekable_open(inode, file);
}
static int gef_wdt_release(struct inode *inode, struct file *file)
{
if (expect_close == 42)
gef_wdt_handler_disable();
else {
pr_crit("unexpected close, not stopping timer!\n");
gef_wdt_service();
}
expect_close = 0;
clear_bit(GEF_WDOG_FLAG_OPENED, &wdt_flags);
return 0;
}
static const struct file_operations gef_wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = gef_wdt_write,
.unlocked_ioctl = gef_wdt_ioctl,
.open = gef_wdt_open,
.release = gef_wdt_release,
};
static struct miscdevice gef_wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &gef_wdt_fops,
};
static int gef_wdt_probe(struct platform_device *dev)
{
int timeout = 10;
u32 freq;
bus_clk = 133; /* in MHz */
freq = fsl_get_sys_freq();
if (freq != -1)
bus_clk = freq;
/* Map devices registers into memory */
gef_wdt_regs = of_iomap(dev->dev.of_node, 0);
if (gef_wdt_regs == NULL)
return -ENOMEM;
gef_wdt_set_timeout(timeout);
gef_wdt_handler_disable(); /* in case timer was already running */
return misc_register(&gef_wdt_miscdev);
}
static int gef_wdt_remove(struct platform_device *dev)
{
misc_deregister(&gef_wdt_miscdev);
gef_wdt_handler_disable();
iounmap(gef_wdt_regs);
return 0;
}
static const struct of_device_id gef_wdt_ids[] = {
{
.compatible = "gef,fpga-wdt",
},
{},
};
MODULE_DEVICE_TABLE(of, gef_wdt_ids);
static struct platform_driver gef_wdt_driver = {
.driver = {
.name = "gef_wdt",
.of_match_table = gef_wdt_ids,
},
.probe = gef_wdt_probe,
.remove = gef_wdt_remove,
};
static int __init gef_wdt_init(void)
{
pr_info("GE watchdog driver\n");
return platform_driver_register(&gef_wdt_driver);
}
static void __exit gef_wdt_exit(void)
{
platform_driver_unregister(&gef_wdt_driver);
}
module_init(gef_wdt_init);
module_exit(gef_wdt_exit);
MODULE_AUTHOR("Martyn Welch <martyn.welch@ge.com>");
MODULE_DESCRIPTION("GE watchdog driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:gef_wdt");
| gpl-2.0 |
kissthink/aufs4-linux | arch/mips/loongson/common/machtype.c | 1542 | 1736 | /*
* Copyright (C) 2009 Lemote Inc.
* Author: Wu Zhangjin, wuzhangjin@gmail.com
*
* Copyright (c) 2009 Zhang Le <r0bertz@gentoo.org>
*
* 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; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/errno.h>
#include <asm/bootinfo.h>
#include <loongson.h>
#include <machine.h>
/* please ensure the length of the machtype string is less than 50 */
#define MACHTYPE_LEN 50
static const char *system_types[] = {
[MACH_LOONGSON_UNKNOWN] = "unknown loongson machine",
[MACH_LEMOTE_FL2E] = "lemote-fuloong-2e-box",
[MACH_LEMOTE_FL2F] = "lemote-fuloong-2f-box",
[MACH_LEMOTE_ML2F7] = "lemote-mengloong-2f-7inches",
[MACH_LEMOTE_YL2F89] = "lemote-yeeloong-2f-8.9inches",
[MACH_DEXXON_GDIUM2F10] = "dexxon-gdium-2f",
[MACH_LEMOTE_NAS] = "lemote-nas-2f",
[MACH_LEMOTE_LL2F] = "lemote-lynloong-2f",
[MACH_LOONGSON_GENERIC] = "generic-loongson-machine",
[MACH_LOONGSON_END] = NULL,
};
const char *get_system_type(void)
{
return system_types[mips_machtype];
}
void __weak __init mach_prom_init_machtype(void)
{
}
void __init prom_init_machtype(void)
{
char *p, str[MACHTYPE_LEN + 1];
int machtype = MACH_LEMOTE_FL2E;
mips_machtype = LOONGSON_MACHTYPE;
p = strstr(arcs_cmdline, "machtype=");
if (!p) {
mach_prom_init_machtype();
return;
}
p += strlen("machtype=");
strncpy(str, p, MACHTYPE_LEN);
str[MACHTYPE_LEN] = '\0';
p = strstr(str, " ");
if (p)
*p = '\0';
for (; system_types[machtype]; machtype++)
if (strstr(system_types[machtype], str)) {
mips_machtype = machtype;
break;
}
}
| gpl-2.0 |
Fusion-Devices/android_kernel_motorola_msm8916 | drivers/gpu/drm/nouveau/core/engine/disp/sornv94.c | 2310 | 3837 | /*
* Copyright 2012 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include <core/os.h>
#include <core/class.h>
#include <subdev/bios.h>
#include <subdev/bios/dcb.h>
#include <subdev/bios/dp.h>
#include <subdev/bios/init.h>
#include "nv50.h"
static inline u32
nv94_sor_soff(struct dcb_output *outp)
{
return (ffs(outp->or) - 1) * 0x800;
}
static inline u32
nv94_sor_loff(struct dcb_output *outp)
{
return nv94_sor_soff(outp) + !(outp->sorconf.link & 1) * 0x80;
}
static inline u32
nv94_sor_dp_lane_map(struct nv50_disp_priv *priv, u8 lane)
{
static const u8 nvaf[] = { 24, 16, 8, 0 }; /* thanks, apple.. */
static const u8 nv94[] = { 16, 8, 0, 24 };
if (nv_device(priv)->chipset == 0xaf)
return nvaf[lane];
return nv94[lane];
}
static int
nv94_sor_dp_pattern(struct nouveau_disp *disp, struct dcb_output *outp,
int head, int pattern)
{
struct nv50_disp_priv *priv = (void *)disp;
const u32 loff = nv94_sor_loff(outp);
nv_mask(priv, 0x61c10c + loff, 0x0f000000, pattern << 24);
return 0;
}
static int
nv94_sor_dp_lnk_ctl(struct nouveau_disp *disp, struct dcb_output *outp,
int head, int link_nr, int link_bw, bool enh_frame)
{
struct nv50_disp_priv *priv = (void *)disp;
const u32 soff = nv94_sor_soff(outp);
const u32 loff = nv94_sor_loff(outp);
u32 dpctrl = 0x00000000;
u32 clksor = 0x00000000;
u32 lane = 0;
int i;
dpctrl |= ((1 << link_nr) - 1) << 16;
if (enh_frame)
dpctrl |= 0x00004000;
if (link_bw > 0x06)
clksor |= 0x00040000;
for (i = 0; i < link_nr; i++)
lane |= 1 << (nv94_sor_dp_lane_map(priv, i) >> 3);
nv_mask(priv, 0x614300 + soff, 0x000c0000, clksor);
nv_mask(priv, 0x61c10c + loff, 0x001f4000, dpctrl);
nv_mask(priv, 0x61c130 + loff, 0x0000000f, lane);
return 0;
}
static int
nv94_sor_dp_drv_ctl(struct nouveau_disp *disp, struct dcb_output *outp,
int head, int lane, int swing, int preem)
{
struct nouveau_bios *bios = nouveau_bios(disp);
struct nv50_disp_priv *priv = (void *)disp;
const u32 loff = nv94_sor_loff(outp);
u32 addr, shift = nv94_sor_dp_lane_map(priv, lane);
u8 ver, hdr, cnt, len;
struct nvbios_dpout info;
struct nvbios_dpcfg ocfg;
addr = nvbios_dpout_match(bios, outp->hasht, outp->hashm,
&ver, &hdr, &cnt, &len, &info);
if (!addr)
return -ENODEV;
addr = nvbios_dpcfg_match(bios, addr, 0, swing, preem,
&ver, &hdr, &cnt, &len, &ocfg);
if (!addr)
return -EINVAL;
nv_mask(priv, 0x61c118 + loff, 0x000000ff << shift, ocfg.drv << shift);
nv_mask(priv, 0x61c120 + loff, 0x000000ff << shift, ocfg.pre << shift);
nv_mask(priv, 0x61c130 + loff, 0x0000ff00, ocfg.unk << 8);
return 0;
}
const struct nouveau_dp_func
nv94_sor_dp_func = {
.pattern = nv94_sor_dp_pattern,
.lnk_ctl = nv94_sor_dp_lnk_ctl,
.drv_ctl = nv94_sor_dp_drv_ctl,
};
| gpl-2.0 |
mtk00874/kernel-mediatek | drivers/net/wireless/rtlwifi/rtl8723ae/dm.c | 2566 | 31225 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
****************************************************************************
*/
#include "../wifi.h"
#include "../base.h"
#include "../pci.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "dm.h"
#include "fw.h"
#include "hal_btc.h"
static const u32 ofdmswing_table[OFDM_TABLE_SIZE] = {
0x7f8001fe,
0x788001e2,
0x71c001c7,
0x6b8001ae,
0x65400195,
0x5fc0017f,
0x5a400169,
0x55400155,
0x50800142,
0x4c000130,
0x47c0011f,
0x43c0010f,
0x40000100,
0x3c8000f2,
0x390000e4,
0x35c000d7,
0x32c000cb,
0x300000c0,
0x2d4000b5,
0x2ac000ab,
0x288000a2,
0x26000098,
0x24000090,
0x22000088,
0x20000080,
0x1e400079,
0x1c800072,
0x1b00006c,
0x19800066,
0x18000060,
0x16c0005b,
0x15800056,
0x14400051,
0x1300004c,
0x12000048,
0x11000044,
0x10000040,
};
static const u8 cckswing_table_ch1ch13[CCK_TABLE_SIZE][8] = {
{0x36, 0x35, 0x2e, 0x25, 0x1c, 0x12, 0x09, 0x04},
{0x33, 0x32, 0x2b, 0x23, 0x1a, 0x11, 0x08, 0x04},
{0x30, 0x2f, 0x29, 0x21, 0x19, 0x10, 0x08, 0x03},
{0x2d, 0x2d, 0x27, 0x1f, 0x18, 0x0f, 0x08, 0x03},
{0x2b, 0x2a, 0x25, 0x1e, 0x16, 0x0e, 0x07, 0x03},
{0x28, 0x28, 0x22, 0x1c, 0x15, 0x0d, 0x07, 0x03},
{0x26, 0x25, 0x21, 0x1b, 0x14, 0x0d, 0x06, 0x03},
{0x24, 0x23, 0x1f, 0x19, 0x13, 0x0c, 0x06, 0x03},
{0x22, 0x21, 0x1d, 0x18, 0x11, 0x0b, 0x06, 0x02},
{0x20, 0x20, 0x1b, 0x16, 0x11, 0x08, 0x05, 0x02},
{0x1f, 0x1e, 0x1a, 0x15, 0x10, 0x0a, 0x05, 0x02},
{0x1d, 0x1c, 0x18, 0x14, 0x0f, 0x0a, 0x05, 0x02},
{0x1b, 0x1a, 0x17, 0x13, 0x0e, 0x09, 0x04, 0x02},
{0x1a, 0x19, 0x16, 0x12, 0x0d, 0x09, 0x04, 0x02},
{0x18, 0x17, 0x15, 0x11, 0x0c, 0x08, 0x04, 0x02},
{0x17, 0x16, 0x13, 0x10, 0x0c, 0x08, 0x04, 0x02},
{0x16, 0x15, 0x12, 0x0f, 0x0b, 0x07, 0x04, 0x01},
{0x14, 0x14, 0x11, 0x0e, 0x0b, 0x07, 0x03, 0x02},
{0x13, 0x13, 0x10, 0x0d, 0x0a, 0x06, 0x03, 0x01},
{0x12, 0x12, 0x0f, 0x0c, 0x09, 0x06, 0x03, 0x01},
{0x11, 0x11, 0x0f, 0x0c, 0x09, 0x06, 0x03, 0x01},
{0x10, 0x10, 0x0e, 0x0b, 0x08, 0x05, 0x03, 0x01},
{0x0f, 0x0f, 0x0d, 0x0b, 0x08, 0x05, 0x03, 0x01},
{0x0e, 0x0e, 0x0c, 0x0a, 0x08, 0x05, 0x02, 0x01},
{0x0d, 0x0d, 0x0c, 0x0a, 0x07, 0x05, 0x02, 0x01},
{0x0d, 0x0c, 0x0b, 0x09, 0x07, 0x04, 0x02, 0x01},
{0x0c, 0x0c, 0x0a, 0x09, 0x06, 0x04, 0x02, 0x01},
{0x0b, 0x0b, 0x0a, 0x08, 0x06, 0x04, 0x02, 0x01},
{0x0b, 0x0a, 0x09, 0x08, 0x06, 0x04, 0x02, 0x01},
{0x0a, 0x0a, 0x09, 0x07, 0x05, 0x03, 0x02, 0x01},
{0x0a, 0x09, 0x08, 0x07, 0x05, 0x03, 0x02, 0x01},
{0x09, 0x09, 0x08, 0x06, 0x05, 0x03, 0x01, 0x01},
{0x09, 0x08, 0x07, 0x06, 0x04, 0x03, 0x01, 0x01}
};
static const u8 cckswing_table_ch14[CCK_TABLE_SIZE][8] = {
{0x36, 0x35, 0x2e, 0x1b, 0x00, 0x00, 0x00, 0x00},
{0x33, 0x32, 0x2b, 0x19, 0x00, 0x00, 0x00, 0x00},
{0x30, 0x2f, 0x29, 0x18, 0x00, 0x00, 0x00, 0x00},
{0x2d, 0x2d, 0x17, 0x17, 0x00, 0x00, 0x00, 0x00},
{0x2b, 0x2a, 0x25, 0x15, 0x00, 0x00, 0x00, 0x00},
{0x28, 0x28, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00},
{0x26, 0x25, 0x21, 0x13, 0x00, 0x00, 0x00, 0x00},
{0x24, 0x23, 0x1f, 0x12, 0x00, 0x00, 0x00, 0x00},
{0x22, 0x21, 0x1d, 0x11, 0x00, 0x00, 0x00, 0x00},
{0x20, 0x20, 0x1b, 0x10, 0x00, 0x00, 0x00, 0x00},
{0x1f, 0x1e, 0x1a, 0x0f, 0x00, 0x00, 0x00, 0x00},
{0x1d, 0x1c, 0x18, 0x0e, 0x00, 0x00, 0x00, 0x00},
{0x1b, 0x1a, 0x17, 0x0e, 0x00, 0x00, 0x00, 0x00},
{0x1a, 0x19, 0x16, 0x0d, 0x00, 0x00, 0x00, 0x00},
{0x18, 0x17, 0x15, 0x0c, 0x00, 0x00, 0x00, 0x00},
{0x17, 0x16, 0x13, 0x0b, 0x00, 0x00, 0x00, 0x00},
{0x16, 0x15, 0x12, 0x0b, 0x00, 0x00, 0x00, 0x00},
{0x14, 0x14, 0x11, 0x0a, 0x00, 0x00, 0x00, 0x00},
{0x13, 0x13, 0x10, 0x0a, 0x00, 0x00, 0x00, 0x00},
{0x12, 0x12, 0x0f, 0x09, 0x00, 0x00, 0x00, 0x00},
{0x11, 0x11, 0x0f, 0x09, 0x00, 0x00, 0x00, 0x00},
{0x10, 0x10, 0x0e, 0x08, 0x00, 0x00, 0x00, 0x00},
{0x0f, 0x0f, 0x0d, 0x08, 0x00, 0x00, 0x00, 0x00},
{0x0e, 0x0e, 0x0c, 0x07, 0x00, 0x00, 0x00, 0x00},
{0x0d, 0x0d, 0x0c, 0x07, 0x00, 0x00, 0x00, 0x00},
{0x0d, 0x0c, 0x0b, 0x06, 0x00, 0x00, 0x00, 0x00},
{0x0c, 0x0c, 0x0a, 0x06, 0x00, 0x00, 0x00, 0x00},
{0x0b, 0x0b, 0x0a, 0x06, 0x00, 0x00, 0x00, 0x00},
{0x0b, 0x0a, 0x09, 0x05, 0x00, 0x00, 0x00, 0x00},
{0x0a, 0x0a, 0x09, 0x05, 0x00, 0x00, 0x00, 0x00},
{0x0a, 0x09, 0x08, 0x05, 0x00, 0x00, 0x00, 0x00},
{0x09, 0x09, 0x08, 0x05, 0x00, 0x00, 0x00, 0x00},
{0x09, 0x08, 0x07, 0x04, 0x00, 0x00, 0x00, 0x00}
};
static void rtl8723ae_dm_diginit(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
dm_digtable->dig_enable_flag = true;
dm_digtable->dig_ext_port_stage = DIG_EXT_PORT_STAGE_MAX;
dm_digtable->cur_igvalue = 0x20;
dm_digtable->pre_igvalue = 0x0;
dm_digtable->cursta_cstate = DIG_STA_DISCONNECT;
dm_digtable->presta_cstate = DIG_STA_DISCONNECT;
dm_digtable->curmultista_cstate = DIG_MULTISTA_DISCONNECT;
dm_digtable->rssi_lowthresh = DM_DIG_THRESH_LOW;
dm_digtable->rssi_highthresh = DM_DIG_THRESH_HIGH;
dm_digtable->fa_lowthresh = DM_FALSEALARM_THRESH_LOW;
dm_digtable->fa_highthresh = DM_FALSEALARM_THRESH_HIGH;
dm_digtable->rx_gain_max = DM_DIG_MAX;
dm_digtable->rx_gain_min = DM_DIG_MIN;
dm_digtable->back_val = DM_DIG_BACKOFF_DEFAULT;
dm_digtable->back_range_max = DM_DIG_BACKOFF_MAX;
dm_digtable->back_range_min = DM_DIG_BACKOFF_MIN;
dm_digtable->pre_cck_pd_state = CCK_PD_STAGE_MAX;
dm_digtable->cur_cck_pd_state = CCK_PD_STAGE_MAX;
}
static u8 rtl_init_gain_min_pwdb(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
long rssi_val_min = 0;
if ((dm_digtable->curmultista_cstate == DIG_MULTISTA_CONNECT) &&
(dm_digtable->cursta_cstate == DIG_STA_CONNECT)) {
if (rtlpriv->dm.entry_min_undec_sm_pwdb != 0)
rssi_val_min =
(rtlpriv->dm.entry_min_undec_sm_pwdb >
rtlpriv->dm.undec_sm_pwdb) ?
rtlpriv->dm.undec_sm_pwdb :
rtlpriv->dm.entry_min_undec_sm_pwdb;
else
rssi_val_min = rtlpriv->dm.undec_sm_pwdb;
} else if (dm_digtable->cursta_cstate == DIG_STA_CONNECT ||
dm_digtable->cursta_cstate == DIG_STA_BEFORE_CONNECT) {
rssi_val_min = rtlpriv->dm.undec_sm_pwdb;
} else if (dm_digtable->curmultista_cstate == DIG_MULTISTA_CONNECT) {
rssi_val_min = rtlpriv->dm.entry_min_undec_sm_pwdb;
}
return (u8) rssi_val_min;
}
static void rtl8723ae_dm_false_alarm_counter_statistics(struct ieee80211_hw *hw)
{
u32 ret_value;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct false_alarm_statistics *falsealm_cnt = &(rtlpriv->falsealm_cnt);
ret_value = rtl_get_bbreg(hw, ROFDM_PHYCOUNTER1, MASKDWORD);
falsealm_cnt->cnt_parity_fail = ((ret_value & 0xffff0000) >> 16);
ret_value = rtl_get_bbreg(hw, ROFDM_PHYCOUNTER2, MASKDWORD);
falsealm_cnt->cnt_rate_illegal = (ret_value & 0xffff);
falsealm_cnt->cnt_crc8_fail = ((ret_value & 0xffff0000) >> 16);
ret_value = rtl_get_bbreg(hw, ROFDM_PHYCOUNTER3, MASKDWORD);
falsealm_cnt->cnt_mcs_fail = (ret_value & 0xffff);
falsealm_cnt->cnt_ofdm_fail = falsealm_cnt->cnt_parity_fail +
falsealm_cnt->cnt_rate_illegal +
falsealm_cnt->cnt_crc8_fail + falsealm_cnt->cnt_mcs_fail;
rtl_set_bbreg(hw, RCCK0_FALSEALARMREPORT, BIT(14), 1);
ret_value = rtl_get_bbreg(hw, RCCK0_FACOUNTERLOWER, MASKBYTE0);
falsealm_cnt->cnt_cck_fail = ret_value;
ret_value = rtl_get_bbreg(hw, RCCK0_FACOUNTERUPPER, MASKBYTE3);
falsealm_cnt->cnt_cck_fail += (ret_value & 0xff) << 8;
falsealm_cnt->cnt_all = (falsealm_cnt->cnt_parity_fail +
falsealm_cnt->cnt_rate_illegal +
falsealm_cnt->cnt_crc8_fail +
falsealm_cnt->cnt_mcs_fail +
falsealm_cnt->cnt_cck_fail);
rtl_set_bbreg(hw, ROFDM1_LSTF, 0x08000000, 1);
rtl_set_bbreg(hw, ROFDM1_LSTF, 0x08000000, 0);
rtl_set_bbreg(hw, RCCK0_FALSEALARMREPORT, 0x0000c000, 0);
rtl_set_bbreg(hw, RCCK0_FALSEALARMREPORT, 0x0000c000, 2);
RT_TRACE(rtlpriv, COMP_DIG, DBG_TRACE,
"cnt_parity_fail = %d, cnt_rate_illegal = %d, "
"cnt_crc8_fail = %d, cnt_mcs_fail = %d\n",
falsealm_cnt->cnt_parity_fail,
falsealm_cnt->cnt_rate_illegal,
falsealm_cnt->cnt_crc8_fail, falsealm_cnt->cnt_mcs_fail);
RT_TRACE(rtlpriv, COMP_DIG, DBG_TRACE,
"cnt_ofdm_fail = %x, cnt_cck_fail = %x, cnt_all = %x\n",
falsealm_cnt->cnt_ofdm_fail,
falsealm_cnt->cnt_cck_fail, falsealm_cnt->cnt_all);
}
static void rtl92c_dm_ctrl_initgain_by_fa(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
u8 value_igi = dm_digtable->cur_igvalue;
if (rtlpriv->falsealm_cnt.cnt_all < DM_DIG_FA_TH0)
value_igi--;
else if (rtlpriv->falsealm_cnt.cnt_all < DM_DIG_FA_TH1)
value_igi += 0;
else if (rtlpriv->falsealm_cnt.cnt_all < DM_DIG_FA_TH2)
value_igi++;
else
value_igi += 2;
value_igi = clamp(value_igi, (u8)DM_DIG_FA_LOWER, (u8)DM_DIG_FA_UPPER);
if (rtlpriv->falsealm_cnt.cnt_all > 10000)
value_igi = 0x32;
dm_digtable->cur_igvalue = value_igi;
rtl8723ae_dm_write_dig(hw);
}
static void rtl92c_dm_ctrl_initgain_by_rssi(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dgtbl = &rtlpriv->dm_digtable;
if (rtlpriv->falsealm_cnt.cnt_all > dgtbl->fa_highthresh) {
if ((dgtbl->back_val - 2) < dgtbl->back_range_min)
dgtbl->back_val = dgtbl->back_range_min;
else
dgtbl->back_val -= 2;
} else if (rtlpriv->falsealm_cnt.cnt_all < dgtbl->fa_lowthresh) {
if ((dgtbl->back_val + 2) > dgtbl->back_range_max)
dgtbl->back_val = dgtbl->back_range_max;
else
dgtbl->back_val += 2;
}
if ((dgtbl->rssi_val_min + 10 - dgtbl->back_val) >
dgtbl->rx_gain_max)
dgtbl->cur_igvalue = dgtbl->rx_gain_max;
else if ((dgtbl->rssi_val_min + 10 -
dgtbl->back_val) < dgtbl->rx_gain_min)
dgtbl->cur_igvalue = dgtbl->rx_gain_min;
else
dgtbl->cur_igvalue = dgtbl->rssi_val_min + 10 - dgtbl->back_val;
RT_TRACE(rtlpriv, COMP_DIG, DBG_TRACE,
"rssi_val_min = %x back_val %x\n",
dgtbl->rssi_val_min, dgtbl->back_val);
rtl8723ae_dm_write_dig(hw);
}
static void rtl8723ae_dm_initial_gain_multi_sta(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
long rssi_strength = rtlpriv->dm.entry_min_undec_sm_pwdb;
bool multi_sta = false;
if (mac->opmode == NL80211_IFTYPE_ADHOC)
multi_sta = true;
if ((!multi_sta) ||
(dm_digtable->cursta_cstate != DIG_STA_DISCONNECT)) {
rtlpriv->initialized = false;
dm_digtable->dig_ext_port_stage = DIG_EXT_PORT_STAGE_MAX;
return;
} else if (!rtlpriv->initialized) {
rtlpriv->initialized = true;
dm_digtable->dig_ext_port_stage = DIG_EXT_PORT_STAGE_0;
dm_digtable->cur_igvalue = 0x20;
rtl8723ae_dm_write_dig(hw);
}
if (dm_digtable->curmultista_cstate == DIG_MULTISTA_CONNECT) {
if ((rssi_strength < dm_digtable->rssi_lowthresh) &&
(dm_digtable->dig_ext_port_stage != DIG_EXT_PORT_STAGE_1)) {
if (dm_digtable->dig_ext_port_stage ==
DIG_EXT_PORT_STAGE_2) {
dm_digtable->cur_igvalue = 0x20;
rtl8723ae_dm_write_dig(hw);
}
dm_digtable->dig_ext_port_stage = DIG_EXT_PORT_STAGE_1;
} else if (rssi_strength > dm_digtable->rssi_highthresh) {
dm_digtable->dig_ext_port_stage = DIG_EXT_PORT_STAGE_2;
rtl92c_dm_ctrl_initgain_by_fa(hw);
}
} else if (dm_digtable->dig_ext_port_stage != DIG_EXT_PORT_STAGE_0) {
dm_digtable->dig_ext_port_stage = DIG_EXT_PORT_STAGE_0;
dm_digtable->cur_igvalue = 0x20;
rtl8723ae_dm_write_dig(hw);
}
RT_TRACE(rtlpriv, COMP_DIG, DBG_TRACE,
"curmultista_cstate = %x dig_ext_port_stage %x\n",
dm_digtable->curmultista_cstate,
dm_digtable->dig_ext_port_stage);
}
static void rtl8723ae_dm_initial_gain_sta(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
RT_TRACE(rtlpriv, COMP_DIG, DBG_TRACE,
"presta_cstate = %x, cursta_cstate = %x\n",
dm_digtable->presta_cstate,
dm_digtable->cursta_cstate);
if (dm_digtable->presta_cstate == dm_digtable->cursta_cstate ||
dm_digtable->cursta_cstate == DIG_STA_BEFORE_CONNECT ||
dm_digtable->cursta_cstate == DIG_STA_CONNECT) {
if (dm_digtable->cursta_cstate != DIG_STA_DISCONNECT) {
dm_digtable->rssi_val_min = rtl_init_gain_min_pwdb(hw);
rtl92c_dm_ctrl_initgain_by_rssi(hw);
}
} else {
dm_digtable->rssi_val_min = 0;
dm_digtable->dig_ext_port_stage = DIG_EXT_PORT_STAGE_MAX;
dm_digtable->back_val = DM_DIG_BACKOFF_DEFAULT;
dm_digtable->cur_igvalue = 0x20;
dm_digtable->pre_igvalue = 0;
rtl8723ae_dm_write_dig(hw);
}
}
static void rtl8723ae_dm_cck_packet_detection_thresh(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
if (dm_digtable->cursta_cstate == DIG_STA_CONNECT) {
dm_digtable->rssi_val_min = rtl_init_gain_min_pwdb(hw);
if (dm_digtable->pre_cck_pd_state == CCK_PD_STAGE_LowRssi) {
if (dm_digtable->rssi_val_min <= 25)
dm_digtable->cur_cck_pd_state =
CCK_PD_STAGE_LowRssi;
else
dm_digtable->cur_cck_pd_state =
CCK_PD_STAGE_HighRssi;
} else {
if (dm_digtable->rssi_val_min <= 20)
dm_digtable->cur_cck_pd_state =
CCK_PD_STAGE_LowRssi;
else
dm_digtable->cur_cck_pd_state =
CCK_PD_STAGE_HighRssi;
}
} else {
dm_digtable->cur_cck_pd_state = CCK_PD_STAGE_MAX;
}
if (dm_digtable->pre_cck_pd_state != dm_digtable->cur_cck_pd_state) {
if (dm_digtable->cur_cck_pd_state == CCK_PD_STAGE_LowRssi) {
if (rtlpriv->falsealm_cnt.cnt_cck_fail > 800)
dm_digtable->cur_cck_fa_state =
CCK_FA_STAGE_High;
else
dm_digtable->cur_cck_fa_state =
CCK_FA_STAGE_Low;
if (dm_digtable->pre_cck_fa_state !=
dm_digtable->cur_cck_fa_state) {
if (dm_digtable->cur_cck_fa_state ==
CCK_FA_STAGE_Low)
rtl_set_bbreg(hw, RCCK0_CCA, MASKBYTE2,
0x83);
else
rtl_set_bbreg(hw, RCCK0_CCA, MASKBYTE2,
0xcd);
dm_digtable->pre_cck_fa_state =
dm_digtable->cur_cck_fa_state;
}
rtl_set_bbreg(hw, RCCK0_SYSTEM, MASKBYTE1, 0x40);
} else {
rtl_set_bbreg(hw, RCCK0_CCA, MASKBYTE2, 0xcd);
rtl_set_bbreg(hw, RCCK0_SYSTEM, MASKBYTE1, 0x47);
}
dm_digtable->pre_cck_pd_state = dm_digtable->cur_cck_pd_state;
}
RT_TRACE(rtlpriv, COMP_DIG, DBG_TRACE,
"CCKPDStage=%x\n", dm_digtable->cur_cck_pd_state);
}
static void rtl8723ae_dm_ctrl_initgain_by_twoport(struct ieee80211_hw *hw)
{
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
if (mac->act_scanning == true)
return;
if (mac->link_state >= MAC80211_LINKED)
dm_digtable->cursta_cstate = DIG_STA_CONNECT;
else
dm_digtable->cursta_cstate = DIG_STA_DISCONNECT;
rtl8723ae_dm_initial_gain_sta(hw);
rtl8723ae_dm_initial_gain_multi_sta(hw);
rtl8723ae_dm_cck_packet_detection_thresh(hw);
dm_digtable->presta_cstate = dm_digtable->cursta_cstate;
}
static void rtl8723ae_dm_dig(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
if (rtlpriv->dm.dm_initialgain_enable == false)
return;
if (dm_digtable->dig_enable_flag == false)
return;
rtl8723ae_dm_ctrl_initgain_by_twoport(hw);
}
static void rtl8723ae_dm_init_dynamic_txpower(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->dm.dynamic_txpower_enable = false;
rtlpriv->dm.last_dtp_lvl = TXHIGHPWRLEVEL_NORMAL;
rtlpriv->dm.dynamic_txhighpower_lvl = TXHIGHPWRLEVEL_NORMAL;
}
static void rtl8723ae_dm_dynamic_txpower(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
long undec_sm_pwdb;
if (!rtlpriv->dm.dynamic_txpower_enable)
return;
if (rtlpriv->dm.dm_flag & HAL_DM_HIPWR_DISABLE) {
rtlpriv->dm.dynamic_txhighpower_lvl = TXHIGHPWRLEVEL_NORMAL;
return;
}
if ((mac->link_state < MAC80211_LINKED) &&
(rtlpriv->dm.entry_min_undec_sm_pwdb == 0)) {
RT_TRACE(rtlpriv, COMP_POWER, DBG_TRACE,
"Not connected\n");
rtlpriv->dm.dynamic_txhighpower_lvl = TXHIGHPWRLEVEL_NORMAL;
rtlpriv->dm.last_dtp_lvl = TXHIGHPWRLEVEL_NORMAL;
return;
}
if (mac->link_state >= MAC80211_LINKED) {
if (mac->opmode == NL80211_IFTYPE_ADHOC) {
undec_sm_pwdb = rtlpriv->dm.entry_min_undec_sm_pwdb;
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"AP Client PWDB = 0x%lx\n",
undec_sm_pwdb);
} else {
undec_sm_pwdb = rtlpriv->dm.undec_sm_pwdb;
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"STA Default Port PWDB = 0x%lx\n",
undec_sm_pwdb);
}
} else {
undec_sm_pwdb = rtlpriv->dm.entry_min_undec_sm_pwdb;
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"AP Ext Port PWDB = 0x%lx\n",
undec_sm_pwdb);
}
if (undec_sm_pwdb >= TX_POWER_NEAR_FIELD_THRESH_LVL2) {
rtlpriv->dm.dynamic_txhighpower_lvl = TXHIGHPWRLEVEL_LEVEL1;
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"TXHIGHPWRLEVEL_LEVEL1 (TxPwr=0x0)\n");
} else if ((undec_sm_pwdb < (TX_POWER_NEAR_FIELD_THRESH_LVL2 - 3)) &&
(undec_sm_pwdb >= TX_POWER_NEAR_FIELD_THRESH_LVL1)) {
rtlpriv->dm.dynamic_txhighpower_lvl = TXHIGHPWRLEVEL_LEVEL1;
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"TXHIGHPWRLEVEL_LEVEL1 (TxPwr=0x10)\n");
} else if (undec_sm_pwdb < (TX_POWER_NEAR_FIELD_THRESH_LVL1 - 5)) {
rtlpriv->dm.dynamic_txhighpower_lvl = TXHIGHPWRLEVEL_NORMAL;
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"TXHIGHPWRLEVEL_NORMAL\n");
}
if ((rtlpriv->dm.dynamic_txhighpower_lvl != rtlpriv->dm.last_dtp_lvl)) {
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"PHY_SetTxPowerLevel8192S() Channel = %d\n",
rtlphy->current_channel);
rtl8723ae_phy_set_txpower_level(hw, rtlphy->current_channel);
}
rtlpriv->dm.last_dtp_lvl = rtlpriv->dm.dynamic_txhighpower_lvl;
}
void rtl8723ae_dm_write_dig(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct dig_t *dm_digtable = &rtlpriv->dm_digtable;
RT_TRACE(rtlpriv, COMP_DIG, DBG_LOUD,
"cur_igvalue = 0x%x, "
"pre_igvalue = 0x%x, back_val = %d\n",
dm_digtable->cur_igvalue, dm_digtable->pre_igvalue,
dm_digtable->back_val);
if (dm_digtable->pre_igvalue != dm_digtable->cur_igvalue) {
rtl_set_bbreg(hw, ROFDM0_XAAGCCORE1, 0x7f,
dm_digtable->cur_igvalue);
rtl_set_bbreg(hw, ROFDM0_XBAGCCORE1, 0x7f,
dm_digtable->cur_igvalue);
dm_digtable->pre_igvalue = dm_digtable->cur_igvalue;
}
}
static void rtl8723ae_dm_pwdmonitor(struct ieee80211_hw *hw)
{
}
void rtl8723ae_dm_init_edca_turbo(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->dm.current_turbo_edca = false;
rtlpriv->dm.is_any_nonbepkts = false;
rtlpriv->dm.is_cur_rdlstate = false;
}
static void rtl8723ae_dm_check_edca_turbo(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *rtlpcipriv = rtl_pcipriv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u64 cur_txok_cnt = 0;
u64 cur_rxok_cnt = 0;
u32 edca_be_ul = 0x5ea42b;
u32 edca_be_dl = 0x5ea42b;
bool bt_change_edca = false;
if ((mac->last_bt_edca_ul != rtlpcipriv->bt_coexist.bt_edca_ul) ||
(mac->last_bt_edca_dl != rtlpcipriv->bt_coexist.bt_edca_dl)) {
rtlpriv->dm.current_turbo_edca = false;
mac->last_bt_edca_ul = rtlpcipriv->bt_coexist.bt_edca_ul;
mac->last_bt_edca_dl = rtlpcipriv->bt_coexist.bt_edca_dl;
}
if (rtlpcipriv->bt_coexist.bt_edca_ul != 0) {
edca_be_ul = rtlpcipriv->bt_coexist.bt_edca_ul;
bt_change_edca = true;
}
if (rtlpcipriv->bt_coexist.bt_edca_dl != 0) {
edca_be_ul = rtlpcipriv->bt_coexist.bt_edca_dl;
bt_change_edca = true;
}
if (mac->link_state != MAC80211_LINKED) {
rtlpriv->dm.current_turbo_edca = false;
return;
}
if ((!mac->ht_enable) && (!rtlpcipriv->bt_coexist.bt_coexistence)) {
if (!(edca_be_ul & 0xffff0000))
edca_be_ul |= 0x005e0000;
if (!(edca_be_dl & 0xffff0000))
edca_be_dl |= 0x005e0000;
}
if ((bt_change_edca) || ((!rtlpriv->dm.is_any_nonbepkts) &&
(!rtlpriv->dm.disable_framebursting))) {
cur_txok_cnt = rtlpriv->stats.txbytesunicast -
mac->last_txok_cnt;
cur_rxok_cnt = rtlpriv->stats.rxbytesunicast -
mac->last_rxok_cnt;
if (cur_rxok_cnt > 4 * cur_txok_cnt) {
if (!rtlpriv->dm.is_cur_rdlstate ||
!rtlpriv->dm.current_turbo_edca) {
rtl_write_dword(rtlpriv,
REG_EDCA_BE_PARAM,
edca_be_dl);
rtlpriv->dm.is_cur_rdlstate = true;
}
} else {
if (rtlpriv->dm.is_cur_rdlstate ||
!rtlpriv->dm.current_turbo_edca) {
rtl_write_dword(rtlpriv,
REG_EDCA_BE_PARAM,
edca_be_ul);
rtlpriv->dm.is_cur_rdlstate = false;
}
}
rtlpriv->dm.current_turbo_edca = true;
} else {
if (rtlpriv->dm.current_turbo_edca) {
u8 tmp = AC0_BE;
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_AC_PARAM,
(u8 *) (&tmp));
rtlpriv->dm.current_turbo_edca = false;
}
}
rtlpriv->dm.is_any_nonbepkts = false;
mac->last_txok_cnt = rtlpriv->stats.txbytesunicast;
mac->last_rxok_cnt = rtlpriv->stats.rxbytesunicast;
}
static void rtl8723ae_dm_initialize_txpower_tracking(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->dm.txpower_tracking = true;
rtlpriv->dm.txpower_trackinginit = false;
RT_TRACE(rtlpriv, COMP_POWER_TRACKING, DBG_LOUD,
"pMgntInfo->txpower_tracking = %d\n",
rtlpriv->dm.txpower_tracking);
}
void rtl8723ae_dm_init_rate_adaptive_mask(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rate_adaptive *p_ra = &(rtlpriv->ra);
p_ra->ratr_state = DM_RATR_STA_INIT;
p_ra->pre_ratr_state = DM_RATR_STA_INIT;
if (rtlpriv->dm.dm_type == DM_TYPE_BYDRIVER)
rtlpriv->dm.useramask = true;
else
rtlpriv->dm.useramask = false;
}
static void rtl8723ae_dm_refresh_rate_adaptive_mask(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rate_adaptive *p_ra = &(rtlpriv->ra);
u32 low_rssithresh_for_ra, high_rssithresh_for_ra;
struct ieee80211_sta *sta = NULL;
if (is_hal_stop(rtlhal)) {
RT_TRACE(rtlpriv, COMP_RATE, DBG_LOUD,
" driver is going to unload\n");
return;
}
if (!rtlpriv->dm.useramask) {
RT_TRACE(rtlpriv, COMP_RATE, DBG_LOUD,
" driver does not control rate adaptive mask\n");
return;
}
if (mac->link_state == MAC80211_LINKED &&
mac->opmode == NL80211_IFTYPE_STATION) {
switch (p_ra->pre_ratr_state) {
case DM_RATR_STA_HIGH:
high_rssithresh_for_ra = 50;
low_rssithresh_for_ra = 20;
break;
case DM_RATR_STA_MIDDLE:
high_rssithresh_for_ra = 55;
low_rssithresh_for_ra = 20;
break;
case DM_RATR_STA_LOW:
high_rssithresh_for_ra = 50;
low_rssithresh_for_ra = 25;
break;
default:
high_rssithresh_for_ra = 50;
low_rssithresh_for_ra = 20;
break;
}
if (rtlpriv->dm.undec_sm_pwdb > high_rssithresh_for_ra)
p_ra->ratr_state = DM_RATR_STA_HIGH;
else if (rtlpriv->dm.undec_sm_pwdb > low_rssithresh_for_ra)
p_ra->ratr_state = DM_RATR_STA_MIDDLE;
else
p_ra->ratr_state = DM_RATR_STA_LOW;
if (p_ra->pre_ratr_state != p_ra->ratr_state) {
RT_TRACE(rtlpriv, COMP_RATE, DBG_LOUD,
"RSSI = %ld\n",
rtlpriv->dm.undec_sm_pwdb);
RT_TRACE(rtlpriv, COMP_RATE, DBG_LOUD,
"RSSI_LEVEL = %d\n", p_ra->ratr_state);
RT_TRACE(rtlpriv, COMP_RATE, DBG_LOUD,
"PreState = %d, CurState = %d\n",
p_ra->pre_ratr_state, p_ra->ratr_state);
rcu_read_lock();
sta = rtl_find_sta(hw, mac->bssid);
if (sta)
rtlpriv->cfg->ops->update_rate_tbl(hw, sta,
p_ra->ratr_state);
rcu_read_unlock();
p_ra->pre_ratr_state = p_ra->ratr_state;
}
}
}
static void rtl8723ae_dm_init_dynamic_bpowersaving(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->dm_pstable.pre_ccastate = CCA_MAX;
rtlpriv->dm_pstable.cur_ccasate = CCA_MAX;
rtlpriv->dm_pstable.pre_rfstate = RF_MAX;
rtlpriv->dm_pstable.cur_rfstate = RF_MAX;
rtlpriv->dm_pstable.rssi_val_min = 0;
}
void rtl8723ae_dm_rf_saving(struct ieee80211_hw *hw, u8 force_in_normal)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct ps_t *dm_pstable = &rtlpriv->dm_pstable;
if (!rtlpriv->reg_init) {
rtlpriv->reg_874 = (rtl_get_bbreg(hw, RFPGA0_XCD_RFINTERFACESW,
MASKDWORD) & 0x1CC000) >> 14;
rtlpriv->reg_c70 = (rtl_get_bbreg(hw, ROFDM0_AGCPARAMETER1,
MASKDWORD) & BIT(3)) >> 3;
rtlpriv->reg_85c = (rtl_get_bbreg(hw, RFPGA0_XCD_SWITCHCONTROL,
MASKDWORD) & 0xFF000000) >> 24;
rtlpriv->reg_a74 = (rtl_get_bbreg(hw, 0xa74, MASKDWORD) &
0xF000) >> 12;
rtlpriv->reg_init = true;
}
if (!force_in_normal) {
if (dm_pstable->rssi_val_min != 0) {
if (dm_pstable->pre_rfstate == RF_NORMAL) {
if (dm_pstable->rssi_val_min >= 30)
dm_pstable->cur_rfstate = RF_SAVE;
else
dm_pstable->cur_rfstate = RF_NORMAL;
} else {
if (dm_pstable->rssi_val_min <= 25)
dm_pstable->cur_rfstate = RF_NORMAL;
else
dm_pstable->cur_rfstate = RF_SAVE;
}
} else {
dm_pstable->cur_rfstate = RF_MAX;
}
} else {
dm_pstable->cur_rfstate = RF_NORMAL;
}
if (dm_pstable->pre_rfstate != dm_pstable->cur_rfstate) {
if (dm_pstable->cur_rfstate == RF_SAVE) {
rtl_set_bbreg(hw, RFPGA0_XCD_RFINTERFACESW,
BIT(5), 0x1);
rtl_set_bbreg(hw, RFPGA0_XCD_RFINTERFACESW,
0x1C0000, 0x2);
rtl_set_bbreg(hw, ROFDM0_AGCPARAMETER1, BIT(3), 0);
rtl_set_bbreg(hw, RFPGA0_XCD_SWITCHCONTROL,
0xFF000000, 0x63);
rtl_set_bbreg(hw, RFPGA0_XCD_RFINTERFACESW,
0xC000, 0x2);
rtl_set_bbreg(hw, 0xa74, 0xF000, 0x3);
rtl_set_bbreg(hw, 0x818, BIT(28), 0x0);
rtl_set_bbreg(hw, 0x818, BIT(28), 0x1);
} else {
rtl_set_bbreg(hw, RFPGA0_XCD_RFINTERFACESW,
0x1CC000, rtlpriv->reg_874);
rtl_set_bbreg(hw, ROFDM0_AGCPARAMETER1, BIT(3),
rtlpriv->reg_c70);
rtl_set_bbreg(hw, RFPGA0_XCD_SWITCHCONTROL, 0xFF000000,
rtlpriv->reg_85c);
rtl_set_bbreg(hw, 0xa74, 0xF000, rtlpriv->reg_a74);
rtl_set_bbreg(hw, 0x818, BIT(28), 0x0);
rtl_set_bbreg(hw, RFPGA0_XCD_RFINTERFACESW,
BIT(5), 0x0);
}
dm_pstable->pre_rfstate = dm_pstable->cur_rfstate;
}
}
static void rtl8723ae_dm_dynamic_bpowersaving(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct ps_t *dm_pstable = &rtlpriv->dm_pstable;
if (((mac->link_state == MAC80211_NOLINK)) &&
(rtlpriv->dm.entry_min_undec_sm_pwdb == 0)) {
dm_pstable->rssi_val_min = 0;
RT_TRACE(rtlpriv, DBG_LOUD, DBG_LOUD,
"Not connected to any\n");
}
if (mac->link_state == MAC80211_LINKED) {
if (mac->opmode == NL80211_IFTYPE_ADHOC) {
dm_pstable->rssi_val_min =
rtlpriv->dm.entry_min_undec_sm_pwdb;
RT_TRACE(rtlpriv, DBG_LOUD, DBG_LOUD,
"AP Client PWDB = 0x%lx\n",
dm_pstable->rssi_val_min);
} else {
dm_pstable->rssi_val_min = rtlpriv->dm.undec_sm_pwdb;
RT_TRACE(rtlpriv, DBG_LOUD, DBG_LOUD,
"STA Default Port PWDB = 0x%lx\n",
dm_pstable->rssi_val_min);
}
} else {
dm_pstable->rssi_val_min = rtlpriv->dm.entry_min_undec_sm_pwdb;
RT_TRACE(rtlpriv, DBG_LOUD, DBG_LOUD,
"AP Ext Port PWDB = 0x%lx\n",
dm_pstable->rssi_val_min);
}
rtl8723ae_dm_rf_saving(hw, false);
}
void rtl8723ae_dm_init(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->dm.dm_type = DM_TYPE_BYDRIVER;
rtl8723ae_dm_diginit(hw);
rtl8723ae_dm_init_dynamic_txpower(hw);
rtl8723ae_dm_init_edca_turbo(hw);
rtl8723ae_dm_init_rate_adaptive_mask(hw);
rtl8723ae_dm_initialize_txpower_tracking(hw);
rtl8723ae_dm_init_dynamic_bpowersaving(hw);
}
void rtl8723ae_dm_watchdog(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_pci_priv *rtlpcipriv = rtl_pcipriv(hw);
bool fw_current_inpsmode = false;
bool fw_ps_awake = true;
rtlpriv->cfg->ops->get_hw_reg(hw, HW_VAR_FW_PSMODE_STATUS,
(u8 *) (&fw_current_inpsmode));
rtlpriv->cfg->ops->get_hw_reg(hw, HW_VAR_FWLPS_RF_ON,
(u8 *) (&fw_ps_awake));
if (ppsc->p2p_ps_info.p2p_ps_mode)
fw_ps_awake = false;
if ((ppsc->rfpwr_state == ERFON) &&
((!fw_current_inpsmode) && fw_ps_awake) &&
(!ppsc->rfchange_inprogress)) {
rtl8723ae_dm_pwdmonitor(hw);
rtl8723ae_dm_dig(hw);
rtl8723ae_dm_false_alarm_counter_statistics(hw);
rtl8723ae_dm_dynamic_bpowersaving(hw);
rtl8723ae_dm_dynamic_txpower(hw);
rtl8723ae_dm_refresh_rate_adaptive_mask(hw);
rtl8723ae_dm_bt_coexist(hw);
rtl8723ae_dm_check_edca_turbo(hw);
}
if (rtlpcipriv->bt_coexist.init_set)
rtl_write_byte(rtlpriv, 0x76e, 0xc);
}
static void rtl8723ae_dm_init_bt_coexist(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *rtlpcipriv = rtl_pcipriv(hw);
rtlpcipriv->bt_coexist.bt_rfreg_origin_1e
= rtl_get_rfreg(hw, (enum radio_path)0, RF_RCK1, 0xfffff);
rtlpcipriv->bt_coexist.bt_rfreg_origin_1f
= rtl_get_rfreg(hw, (enum radio_path)0, RF_RCK2, 0xf0);
rtlpcipriv->bt_coexist.cstate = 0;
rtlpcipriv->bt_coexist.previous_state = 0;
rtlpcipriv->bt_coexist.cstate_h = 0;
rtlpcipriv->bt_coexist.previous_state_h = 0;
rtlpcipriv->bt_coexist.lps_counter = 0;
/* Enable counter statistics */
rtl_write_byte(rtlpriv, 0x76e, 0x4);
rtl_write_byte(rtlpriv, 0x778, 0x3);
rtl_write_byte(rtlpriv, 0x40, 0x20);
rtlpcipriv->bt_coexist.init_set = true;
}
void rtl8723ae_dm_bt_coexist(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *rtlpcipriv = rtl_pcipriv(hw);
u8 tmp_byte = 0;
if (!rtlpcipriv->bt_coexist.bt_coexistence) {
RT_TRACE(rtlpriv, COMP_BT_COEXIST, DBG_LOUD,
"[DM]{BT], BT not exist!!\n");
return;
}
if (!rtlpcipriv->bt_coexist.init_set) {
RT_TRACE(rtlpriv, COMP_BT_COEXIST, DBG_LOUD,
"[DM][BT], rtl8723ae_dm_bt_coexist()\n");
rtl8723ae_dm_init_bt_coexist(hw);
}
tmp_byte = rtl_read_byte(rtlpriv, 0x40);
RT_TRACE(rtlpriv, COMP_BT_COEXIST, DBG_LOUD,
"[DM][BT], 0x40 is 0x%x", tmp_byte);
RT_TRACE(rtlpriv, COMP_BT_COEXIST, DBG_DMESG,
"[DM][BT], bt_dm_coexist start");
rtl8723ae_dm_bt_coexist_8723(hw);
}
| gpl-2.0 |
edoko/AirKernel_NS_JBN | sound/isa/azt2320.c | 3078 | 9968 | /*
card-azt2320.c - driver for Aztech Systems AZT2320 based soundcards.
Copyright (C) 1999-2000 by Massimo Piccioni <dafastidio@libero.it>
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; either version 2 of the License, or
(at your option) any later version.
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
*/
/*
This driver should provide support for most Aztech AZT2320 based cards.
Several AZT2316 chips are also supported/tested, but autoprobe doesn't
work: all module option have to be set.
No docs available for us at Aztech headquarters !!! Unbelievable ...
No other help obtained.
Thanks to Rainer Wiesner <rainer.wiesner@01019freenet.de> for the WSS
activation method (full-duplex audio!).
*/
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/pnp.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/wss.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#define PFX "azt2320: "
MODULE_AUTHOR("Massimo Piccioni <dafastidio@libero.it>");
MODULE_DESCRIPTION("Aztech Systems AZT2320");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Aztech Systems,PRO16V},"
"{Aztech Systems,AZT2320},"
"{Aztech Systems,AZT3300},"
"{Aztech Systems,AZT2320},"
"{Aztech Systems,AZT3000}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static long wss_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static long mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* Pnp setup */
static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* Pnp setup */
static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* PnP setup */
static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* PnP setup */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for azt2320 based soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for azt2320 based soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable azt2320 based soundcard.");
struct snd_card_azt2320 {
int dev_no;
struct pnp_dev *dev;
struct pnp_dev *devmpu;
struct snd_wss *chip;
};
static struct pnp_card_device_id snd_azt2320_pnpids[] = {
/* PRO16V */
{ .id = "AZT1008", .devs = { { "AZT1008" }, { "AZT2001" }, } },
/* Aztech Sound Galaxy 16 */
{ .id = "AZT2320", .devs = { { "AZT0001" }, { "AZT0002" }, } },
/* Packard Bell Sound III 336 AM/SP */
{ .id = "AZT3000", .devs = { { "AZT1003" }, { "AZT2001" }, } },
/* AT3300 */
{ .id = "AZT3002", .devs = { { "AZT1004" }, { "AZT2001" }, } },
/* --- */
{ .id = "AZT3005", .devs = { { "AZT1003" }, { "AZT2001" }, } },
/* --- */
{ .id = "AZT3011", .devs = { { "AZT1003" }, { "AZT2001" }, } },
{ .id = "" } /* end */
};
MODULE_DEVICE_TABLE(pnp_card, snd_azt2320_pnpids);
#define DRIVER_NAME "snd-card-azt2320"
static int __devinit snd_card_azt2320_pnp(int dev, struct snd_card_azt2320 *acard,
struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
struct pnp_dev *pdev;
int err;
acard->dev = pnp_request_card_device(card, id->devs[0].id, NULL);
if (acard->dev == NULL)
return -ENODEV;
acard->devmpu = pnp_request_card_device(card, id->devs[1].id, NULL);
pdev = acard->dev;
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR PFX "AUDIO pnp configure failure\n");
return err;
}
port[dev] = pnp_port_start(pdev, 0);
fm_port[dev] = pnp_port_start(pdev, 1);
wss_port[dev] = pnp_port_start(pdev, 2);
dma1[dev] = pnp_dma(pdev, 0);
dma2[dev] = pnp_dma(pdev, 1);
irq[dev] = pnp_irq(pdev, 0);
pdev = acard->devmpu;
if (pdev != NULL) {
err = pnp_activate_dev(pdev);
if (err < 0)
goto __mpu_error;
mpu_port[dev] = pnp_port_start(pdev, 0);
mpu_irq[dev] = pnp_irq(pdev, 0);
} else {
__mpu_error:
if (pdev) {
pnp_release_card_device(pdev);
snd_printk(KERN_ERR PFX "MPU401 pnp configure failure, skipping\n");
}
acard->devmpu = NULL;
mpu_port[dev] = -1;
}
return 0;
}
/* same of snd_sbdsp_command by Jaroslav Kysela */
static int __devinit snd_card_azt2320_command(unsigned long port, unsigned char val)
{
int i;
unsigned long limit;
limit = jiffies + HZ / 10;
for (i = 50000; i && time_after(limit, jiffies); i--)
if (!(inb(port + 0x0c) & 0x80)) {
outb(val, port + 0x0c);
return 0;
}
return -EBUSY;
}
static int __devinit snd_card_azt2320_enable_wss(unsigned long port)
{
int error;
if ((error = snd_card_azt2320_command(port, 0x09)))
return error;
if ((error = snd_card_azt2320_command(port, 0x00)))
return error;
mdelay(5);
return 0;
}
static int __devinit snd_card_azt2320_probe(int dev,
struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
int error;
struct snd_card *card;
struct snd_card_azt2320 *acard;
struct snd_wss *chip;
struct snd_opl3 *opl3;
error = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_card_azt2320), &card);
if (error < 0)
return error;
acard = card->private_data;
if ((error = snd_card_azt2320_pnp(dev, acard, pcard, pid))) {
snd_card_free(card);
return error;
}
snd_card_set_dev(card, &pcard->card->dev);
if ((error = snd_card_azt2320_enable_wss(port[dev]))) {
snd_card_free(card);
return error;
}
error = snd_wss_create(card, wss_port[dev], -1,
irq[dev],
dma1[dev], dma2[dev],
WSS_HW_DETECT, 0, &chip);
if (error < 0) {
snd_card_free(card);
return error;
}
strcpy(card->driver, "AZT2320");
strcpy(card->shortname, "Aztech AZT2320");
sprintf(card->longname, "%s, WSS at 0x%lx, irq %i, dma %i&%i",
card->shortname, chip->port, irq[dev], dma1[dev], dma2[dev]);
error = snd_wss_pcm(chip, 0, NULL);
if (error < 0) {
snd_card_free(card);
return error;
}
error = snd_wss_mixer(chip);
if (error < 0) {
snd_card_free(card);
return error;
}
error = snd_wss_timer(chip, 0, NULL);
if (error < 0) {
snd_card_free(card);
return error;
}
if (mpu_port[dev] > 0 && mpu_port[dev] != SNDRV_AUTO_PORT) {
if (snd_mpu401_uart_new(card, 0, MPU401_HW_AZT2320,
mpu_port[dev], 0,
mpu_irq[dev], IRQF_DISABLED,
NULL) < 0)
snd_printk(KERN_ERR PFX "no MPU-401 device at 0x%lx\n", mpu_port[dev]);
}
if (fm_port[dev] > 0 && fm_port[dev] != SNDRV_AUTO_PORT) {
if (snd_opl3_create(card,
fm_port[dev], fm_port[dev] + 2,
OPL3_HW_AUTO, 0, &opl3) < 0) {
snd_printk(KERN_ERR PFX "no OPL device at 0x%lx-0x%lx\n",
fm_port[dev], fm_port[dev] + 2);
} else {
if ((error = snd_opl3_timer_new(opl3, 1, 2)) < 0) {
snd_card_free(card);
return error;
}
if ((error = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) {
snd_card_free(card);
return error;
}
}
}
if ((error = snd_card_register(card)) < 0) {
snd_card_free(card);
return error;
}
pnp_set_card_drvdata(pcard, card);
return 0;
}
static unsigned int __devinitdata azt2320_devices;
static int __devinit snd_azt2320_pnp_detect(struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
static int dev;
int res;
for ( ; dev < SNDRV_CARDS; dev++) {
if (!enable[dev])
continue;
res = snd_card_azt2320_probe(dev, card, id);
if (res < 0)
return res;
dev++;
azt2320_devices++;
return 0;
}
return -ENODEV;
}
static void __devexit snd_azt2320_pnp_remove(struct pnp_card_link * pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
#ifdef CONFIG_PM
static int snd_azt2320_pnp_suspend(struct pnp_card_link *pcard, pm_message_t state)
{
struct snd_card *card = pnp_get_card_drvdata(pcard);
struct snd_card_azt2320 *acard = card->private_data;
struct snd_wss *chip = acard->chip;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
chip->suspend(chip);
return 0;
}
static int snd_azt2320_pnp_resume(struct pnp_card_link *pcard)
{
struct snd_card *card = pnp_get_card_drvdata(pcard);
struct snd_card_azt2320 *acard = card->private_data;
struct snd_wss *chip = acard->chip;
chip->resume(chip);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif
static struct pnp_card_driver azt2320_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = "azt2320",
.id_table = snd_azt2320_pnpids,
.probe = snd_azt2320_pnp_detect,
.remove = __devexit_p(snd_azt2320_pnp_remove),
#ifdef CONFIG_PM
.suspend = snd_azt2320_pnp_suspend,
.resume = snd_azt2320_pnp_resume,
#endif
};
static int __init alsa_card_azt2320_init(void)
{
int err;
err = pnp_register_card_driver(&azt2320_pnpc_driver);
if (err)
return err;
if (!azt2320_devices) {
pnp_unregister_card_driver(&azt2320_pnpc_driver);
#ifdef MODULE
snd_printk(KERN_ERR "no AZT2320 based soundcards found\n");
#endif
return -ENODEV;
}
return 0;
}
static void __exit alsa_card_azt2320_exit(void)
{
pnp_unregister_card_driver(&azt2320_pnpc_driver);
}
module_init(alsa_card_azt2320_init)
module_exit(alsa_card_azt2320_exit)
| gpl-2.0 |
syhost/android_kernel_kitkat | arch/powerpc/kvm/emulate.c | 3590 | 13160 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* 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, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright IBM Corp. 2007
* Copyright 2011 Freescale Semiconductor, Inc.
*
* Authors: Hollis Blanchard <hollisb@us.ibm.com>
*/
#include <linux/jiffies.h>
#include <linux/hrtimer.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kvm_host.h>
#include <asm/reg.h>
#include <asm/time.h>
#include <asm/byteorder.h>
#include <asm/kvm_ppc.h>
#include <asm/disassemble.h>
#include "timing.h"
#include "trace.h"
#define OP_TRAP 3
#define OP_TRAP_64 2
#define OP_31_XOP_LWZX 23
#define OP_31_XOP_LBZX 87
#define OP_31_XOP_STWX 151
#define OP_31_XOP_STBX 215
#define OP_31_XOP_LBZUX 119
#define OP_31_XOP_STBUX 247
#define OP_31_XOP_LHZX 279
#define OP_31_XOP_LHZUX 311
#define OP_31_XOP_MFSPR 339
#define OP_31_XOP_LHAX 343
#define OP_31_XOP_STHX 407
#define OP_31_XOP_STHUX 439
#define OP_31_XOP_MTSPR 467
#define OP_31_XOP_DCBI 470
#define OP_31_XOP_LWBRX 534
#define OP_31_XOP_TLBSYNC 566
#define OP_31_XOP_STWBRX 662
#define OP_31_XOP_LHBRX 790
#define OP_31_XOP_STHBRX 918
#define OP_LWZ 32
#define OP_LWZU 33
#define OP_LBZ 34
#define OP_LBZU 35
#define OP_STW 36
#define OP_STWU 37
#define OP_STB 38
#define OP_STBU 39
#define OP_LHZ 40
#define OP_LHZU 41
#define OP_LHA 42
#define OP_LHAU 43
#define OP_STH 44
#define OP_STHU 45
void kvmppc_emulate_dec(struct kvm_vcpu *vcpu)
{
unsigned long dec_nsec;
unsigned long long dec_time;
pr_debug("mtDEC: %x\n", vcpu->arch.dec);
hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
#ifdef CONFIG_PPC_BOOK3S
/* mtdec lowers the interrupt line when positive. */
kvmppc_core_dequeue_dec(vcpu);
/* POWER4+ triggers a dec interrupt if the value is < 0 */
if (vcpu->arch.dec & 0x80000000) {
kvmppc_core_queue_dec(vcpu);
return;
}
#endif
#ifdef CONFIG_BOOKE
/* On BOOKE, DEC = 0 is as good as decrementer not enabled */
if (vcpu->arch.dec == 0)
return;
#endif
/*
* The decrementer ticks at the same rate as the timebase, so
* that's how we convert the guest DEC value to the number of
* host ticks.
*/
dec_time = vcpu->arch.dec;
dec_time *= 1000;
do_div(dec_time, tb_ticks_per_usec);
dec_nsec = do_div(dec_time, NSEC_PER_SEC);
hrtimer_start(&vcpu->arch.dec_timer,
ktime_set(dec_time, dec_nsec), HRTIMER_MODE_REL);
vcpu->arch.dec_jiffies = get_tb();
}
u32 kvmppc_get_dec(struct kvm_vcpu *vcpu, u64 tb)
{
u64 jd = tb - vcpu->arch.dec_jiffies;
#ifdef CONFIG_BOOKE
if (vcpu->arch.dec < jd)
return 0;
#endif
return vcpu->arch.dec - jd;
}
/* XXX to do:
* lhax
* lhaux
* lswx
* lswi
* stswx
* stswi
* lha
* lhau
* lmw
* stmw
*
* XXX is_bigendian should depend on MMU mapping or MSR[LE]
*/
/* XXX Should probably auto-generate instruction decoding for a particular core
* from opcode tables in the future. */
int kvmppc_emulate_instruction(struct kvm_run *run, struct kvm_vcpu *vcpu)
{
u32 inst = kvmppc_get_last_inst(vcpu);
u32 ea;
int ra;
int rb;
int rs;
int rt;
int sprn;
enum emulation_result emulated = EMULATE_DONE;
int advance = 1;
/* this default type might be overwritten by subcategories */
kvmppc_set_exit_type(vcpu, EMULATED_INST_EXITS);
pr_debug("Emulating opcode %d / %d\n", get_op(inst), get_xop(inst));
switch (get_op(inst)) {
case OP_TRAP:
#ifdef CONFIG_PPC_BOOK3S
case OP_TRAP_64:
kvmppc_core_queue_program(vcpu, SRR1_PROGTRAP);
#else
kvmppc_core_queue_program(vcpu,
vcpu->arch.shared->esr | ESR_PTR);
#endif
advance = 0;
break;
case 31:
switch (get_xop(inst)) {
case OP_31_XOP_LWZX:
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 4, 1);
break;
case OP_31_XOP_LBZX:
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 1, 1);
break;
case OP_31_XOP_LBZUX:
rt = get_rt(inst);
ra = get_ra(inst);
rb = get_rb(inst);
ea = kvmppc_get_gpr(vcpu, rb);
if (ra)
ea += kvmppc_get_gpr(vcpu, ra);
emulated = kvmppc_handle_load(run, vcpu, rt, 1, 1);
kvmppc_set_gpr(vcpu, ra, ea);
break;
case OP_31_XOP_STWX:
rs = get_rs(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
4, 1);
break;
case OP_31_XOP_STBX:
rs = get_rs(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
1, 1);
break;
case OP_31_XOP_STBUX:
rs = get_rs(inst);
ra = get_ra(inst);
rb = get_rb(inst);
ea = kvmppc_get_gpr(vcpu, rb);
if (ra)
ea += kvmppc_get_gpr(vcpu, ra);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
1, 1);
kvmppc_set_gpr(vcpu, rs, ea);
break;
case OP_31_XOP_LHAX:
rt = get_rt(inst);
emulated = kvmppc_handle_loads(run, vcpu, rt, 2, 1);
break;
case OP_31_XOP_LHZX:
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 2, 1);
break;
case OP_31_XOP_LHZUX:
rt = get_rt(inst);
ra = get_ra(inst);
rb = get_rb(inst);
ea = kvmppc_get_gpr(vcpu, rb);
if (ra)
ea += kvmppc_get_gpr(vcpu, ra);
emulated = kvmppc_handle_load(run, vcpu, rt, 2, 1);
kvmppc_set_gpr(vcpu, ra, ea);
break;
case OP_31_XOP_MFSPR:
sprn = get_sprn(inst);
rt = get_rt(inst);
switch (sprn) {
case SPRN_SRR0:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->srr0);
break;
case SPRN_SRR1:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->srr1);
break;
case SPRN_PVR:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.pvr); break;
case SPRN_PIR:
kvmppc_set_gpr(vcpu, rt, vcpu->vcpu_id); break;
case SPRN_MSSSR0:
kvmppc_set_gpr(vcpu, rt, 0); break;
/* Note: mftb and TBRL/TBWL are user-accessible, so
* the guest can always access the real TB anyways.
* In fact, we probably will never see these traps. */
case SPRN_TBWL:
kvmppc_set_gpr(vcpu, rt, get_tb() >> 32); break;
case SPRN_TBWU:
kvmppc_set_gpr(vcpu, rt, get_tb()); break;
case SPRN_SPRG0:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->sprg0);
break;
case SPRN_SPRG1:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->sprg1);
break;
case SPRN_SPRG2:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->sprg2);
break;
case SPRN_SPRG3:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->sprg3);
break;
/* Note: SPRG4-7 are user-readable, so we don't get
* a trap. */
case SPRN_DEC:
{
kvmppc_set_gpr(vcpu, rt,
kvmppc_get_dec(vcpu, get_tb()));
break;
}
default:
emulated = kvmppc_core_emulate_mfspr(vcpu, sprn, rt);
if (emulated == EMULATE_FAIL) {
printk("mfspr: unknown spr %x\n", sprn);
kvmppc_set_gpr(vcpu, rt, 0);
}
break;
}
kvmppc_set_exit_type(vcpu, EMULATED_MFSPR_EXITS);
break;
case OP_31_XOP_STHX:
rs = get_rs(inst);
ra = get_ra(inst);
rb = get_rb(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
2, 1);
break;
case OP_31_XOP_STHUX:
rs = get_rs(inst);
ra = get_ra(inst);
rb = get_rb(inst);
ea = kvmppc_get_gpr(vcpu, rb);
if (ra)
ea += kvmppc_get_gpr(vcpu, ra);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
2, 1);
kvmppc_set_gpr(vcpu, ra, ea);
break;
case OP_31_XOP_MTSPR:
sprn = get_sprn(inst);
rs = get_rs(inst);
switch (sprn) {
case SPRN_SRR0:
vcpu->arch.shared->srr0 = kvmppc_get_gpr(vcpu, rs);
break;
case SPRN_SRR1:
vcpu->arch.shared->srr1 = kvmppc_get_gpr(vcpu, rs);
break;
/* XXX We need to context-switch the timebase for
* watchdog and FIT. */
case SPRN_TBWL: break;
case SPRN_TBWU: break;
case SPRN_MSSSR0: break;
case SPRN_DEC:
vcpu->arch.dec = kvmppc_get_gpr(vcpu, rs);
kvmppc_emulate_dec(vcpu);
break;
case SPRN_SPRG0:
vcpu->arch.shared->sprg0 = kvmppc_get_gpr(vcpu, rs);
break;
case SPRN_SPRG1:
vcpu->arch.shared->sprg1 = kvmppc_get_gpr(vcpu, rs);
break;
case SPRN_SPRG2:
vcpu->arch.shared->sprg2 = kvmppc_get_gpr(vcpu, rs);
break;
case SPRN_SPRG3:
vcpu->arch.shared->sprg3 = kvmppc_get_gpr(vcpu, rs);
break;
default:
emulated = kvmppc_core_emulate_mtspr(vcpu, sprn, rs);
if (emulated == EMULATE_FAIL)
printk("mtspr: unknown spr %x\n", sprn);
break;
}
kvmppc_set_exit_type(vcpu, EMULATED_MTSPR_EXITS);
break;
case OP_31_XOP_DCBI:
/* Do nothing. The guest is performing dcbi because
* hardware DMA is not snooped by the dcache, but
* emulated DMA either goes through the dcache as
* normal writes, or the host kernel has handled dcache
* coherence. */
break;
case OP_31_XOP_LWBRX:
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 4, 0);
break;
case OP_31_XOP_TLBSYNC:
break;
case OP_31_XOP_STWBRX:
rs = get_rs(inst);
ra = get_ra(inst);
rb = get_rb(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
4, 0);
break;
case OP_31_XOP_LHBRX:
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 2, 0);
break;
case OP_31_XOP_STHBRX:
rs = get_rs(inst);
ra = get_ra(inst);
rb = get_rb(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
2, 0);
break;
default:
/* Attempt core-specific emulation below. */
emulated = EMULATE_FAIL;
}
break;
case OP_LWZ:
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 4, 1);
break;
case OP_LWZU:
ra = get_ra(inst);
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 4, 1);
kvmppc_set_gpr(vcpu, ra, vcpu->arch.paddr_accessed);
break;
case OP_LBZ:
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 1, 1);
break;
case OP_LBZU:
ra = get_ra(inst);
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 1, 1);
kvmppc_set_gpr(vcpu, ra, vcpu->arch.paddr_accessed);
break;
case OP_STW:
rs = get_rs(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
4, 1);
break;
case OP_STWU:
ra = get_ra(inst);
rs = get_rs(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
4, 1);
kvmppc_set_gpr(vcpu, ra, vcpu->arch.paddr_accessed);
break;
case OP_STB:
rs = get_rs(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
1, 1);
break;
case OP_STBU:
ra = get_ra(inst);
rs = get_rs(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
1, 1);
kvmppc_set_gpr(vcpu, ra, vcpu->arch.paddr_accessed);
break;
case OP_LHZ:
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 2, 1);
break;
case OP_LHZU:
ra = get_ra(inst);
rt = get_rt(inst);
emulated = kvmppc_handle_load(run, vcpu, rt, 2, 1);
kvmppc_set_gpr(vcpu, ra, vcpu->arch.paddr_accessed);
break;
case OP_LHA:
rt = get_rt(inst);
emulated = kvmppc_handle_loads(run, vcpu, rt, 2, 1);
break;
case OP_LHAU:
ra = get_ra(inst);
rt = get_rt(inst);
emulated = kvmppc_handle_loads(run, vcpu, rt, 2, 1);
kvmppc_set_gpr(vcpu, ra, vcpu->arch.paddr_accessed);
break;
case OP_STH:
rs = get_rs(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
2, 1);
break;
case OP_STHU:
ra = get_ra(inst);
rs = get_rs(inst);
emulated = kvmppc_handle_store(run, vcpu,
kvmppc_get_gpr(vcpu, rs),
2, 1);
kvmppc_set_gpr(vcpu, ra, vcpu->arch.paddr_accessed);
break;
default:
emulated = EMULATE_FAIL;
}
if (emulated == EMULATE_FAIL) {
emulated = kvmppc_core_emulate_op(run, vcpu, inst, &advance);
if (emulated == EMULATE_AGAIN) {
advance = 0;
} else if (emulated == EMULATE_FAIL) {
advance = 0;
printk(KERN_ERR "Couldn't emulate instruction 0x%08x "
"(op %d xop %d)\n", inst, get_op(inst), get_xop(inst));
kvmppc_core_queue_program(vcpu, 0);
}
}
trace_kvm_ppc_instr(inst, kvmppc_get_pc(vcpu), emulated);
/* Advance past emulated instruction. */
if (advance)
kvmppc_set_pc(vcpu, kvmppc_get_pc(vcpu) + 4);
return emulated;
}
| gpl-2.0 |
XperianPro/android_kernel_xiaomi_aries-port | block/noop-iosched.c | 4614 | 2485 | /*
* elevator noop
*/
#include <linux/blkdev.h>
#include <linux/elevator.h>
#include <linux/bio.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
struct noop_data {
struct list_head queue;
};
static void noop_merged_requests(struct request_queue *q, struct request *rq,
struct request *next)
{
list_del_init(&next->queuelist);
}
static int noop_dispatch(struct request_queue *q, int force)
{
struct noop_data *nd = q->elevator->elevator_data;
if (!list_empty(&nd->queue)) {
struct request *rq;
rq = list_entry(nd->queue.next, struct request, queuelist);
list_del_init(&rq->queuelist);
elv_dispatch_sort(q, rq);
return 1;
}
return 0;
}
static void noop_add_request(struct request_queue *q, struct request *rq)
{
struct noop_data *nd = q->elevator->elevator_data;
list_add_tail(&rq->queuelist, &nd->queue);
}
static struct request *
noop_former_request(struct request_queue *q, struct request *rq)
{
struct noop_data *nd = q->elevator->elevator_data;
if (rq->queuelist.prev == &nd->queue)
return NULL;
return list_entry(rq->queuelist.prev, struct request, queuelist);
}
static struct request *
noop_latter_request(struct request_queue *q, struct request *rq)
{
struct noop_data *nd = q->elevator->elevator_data;
if (rq->queuelist.next == &nd->queue)
return NULL;
return list_entry(rq->queuelist.next, struct request, queuelist);
}
static void *noop_init_queue(struct request_queue *q)
{
struct noop_data *nd;
nd = kmalloc_node(sizeof(*nd), GFP_KERNEL, q->node);
if (!nd)
return NULL;
INIT_LIST_HEAD(&nd->queue);
return nd;
}
static void noop_exit_queue(struct elevator_queue *e)
{
struct noop_data *nd = e->elevator_data;
BUG_ON(!list_empty(&nd->queue));
kfree(nd);
}
static struct elevator_type elevator_noop = {
.ops = {
.elevator_merge_req_fn = noop_merged_requests,
.elevator_dispatch_fn = noop_dispatch,
.elevator_add_req_fn = noop_add_request,
.elevator_former_req_fn = noop_former_request,
.elevator_latter_req_fn = noop_latter_request,
.elevator_init_fn = noop_init_queue,
.elevator_exit_fn = noop_exit_queue,
},
.elevator_name = "noop",
.elevator_owner = THIS_MODULE,
};
static int __init noop_init(void)
{
return elv_register(&elevator_noop);
}
static void __exit noop_exit(void)
{
elv_unregister(&elevator_noop);
}
module_init(noop_init);
module_exit(noop_exit);
MODULE_AUTHOR("Jens Axboe");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("No-op IO scheduler");
| gpl-2.0 |
mbernasocchi/QGIS | src/app/qgslayertreeviewnocrsindicator.cpp | 7 | 3111 | /***************************************************************************
qgslayertreeviewnocrsindicator.h
--------------------------------------
Date : October 2019
Copyright : (C) 2019 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
***************************************************************************
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgslayertreeviewnocrsindicator.h"
#include "qgslayertreeview.h"
#include "qgslayertree.h"
#include "qgslayertreemodel.h"
#include "qgslayertreeutils.h"
#include "qgsvectorlayer.h"
#include "qgisapp.h"
#include "qgsprojectionselectiondialog.h"
#include "qgsannotationlayer.h"
QgsLayerTreeViewNoCrsIndicatorProvider::QgsLayerTreeViewNoCrsIndicatorProvider( QgsLayerTreeView *view )
: QgsLayerTreeViewIndicatorProvider( view )
{
}
void QgsLayerTreeViewNoCrsIndicatorProvider::onIndicatorClicked( const QModelIndex &index )
{
QgsLayerTreeNode *node = mLayerTreeView->index2node( index );
if ( !QgsLayerTree::isLayer( node ) )
return;
QgsMapLayer *layer = QgsLayerTree::toLayer( node )->layer();
if ( !layer )
return;
QgsProjectionSelectionDialog selector( QgisApp::instance() );
selector.showNoCrsForLayerMessage();
if ( selector.exec() )
{
QgsCoordinateReferenceSystem crs = selector.crs();
layer->setCrs( selector.crs() );
layer->triggerRepaint();
updateLayerIndicator( layer );
}
}
bool QgsLayerTreeViewNoCrsIndicatorProvider::acceptLayer( QgsMapLayer *layer )
{
return layer && layer->isValid() && layer->isSpatial() && !layer->crs().isValid() && !qobject_cast< QgsAnnotationLayer * >( layer );
}
QString QgsLayerTreeViewNoCrsIndicatorProvider::iconName( QgsMapLayer *layer )
{
Q_UNUSED( layer )
return QStringLiteral( "/mIndicatorNoCRS.svg" );
}
QString QgsLayerTreeViewNoCrsIndicatorProvider::tooltipText( QgsMapLayer *layer )
{
Q_UNUSED( layer )
return tr( "<b>Layer has no coordinate reference system set!</b><br>This layer is not georeferenced and has no geographic location available." );
}
void QgsLayerTreeViewNoCrsIndicatorProvider::connectSignals( QgsMapLayer *layer )
{
QgsLayerTreeViewIndicatorProvider::connectSignals( layer );
connect( layer, &QgsMapLayer::crsChanged, this, &QgsLayerTreeViewNoCrsIndicatorProvider::onLayerChanged );
}
void QgsLayerTreeViewNoCrsIndicatorProvider::disconnectSignals( QgsMapLayer *layer )
{
QgsLayerTreeViewIndicatorProvider::disconnectSignals( layer );
disconnect( layer, &QgsMapLayer::crsChanged, this, &QgsLayerTreeViewNoCrsIndicatorProvider::onLayerChanged );
}
| gpl-2.0 |
suhorng/vm14hw1 | roms/seabios/src/ata.c | 7 | 30070 | // Low level ATA disk access
//
// Copyright (C) 2008,2009 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2002 MandrakeSoft S.A.
//
// This file may be distributed under the terms of the GNU LGPLv3 license.
#include "types.h" // u8
#include "ioport.h" // inb
#include "util.h" // dprintf
#include "cmos.h" // inb_cmos
#include "pic.h" // enable_hwirq
#include "biosvar.h" // GET_EBDA
#include "pci.h" // foreachpci
#include "pci_ids.h" // PCI_CLASS_STORAGE_OTHER
#include "pci_regs.h" // PCI_INTERRUPT_LINE
#include "boot.h" // add_bcv_hd
#include "disk.h" // struct ata_s
#include "ata.h" // ATA_CB_STAT
#include "blockcmd.h" // CDB_CMD_READ_10
#define IDE_TIMEOUT 32000 //32 seconds max for IDE ops
/****************************************************************
* Helper functions
****************************************************************/
// Wait for the specified ide state
static inline int
await_ide(u8 mask, u8 flags, u16 base, u16 timeout)
{
u64 end = calc_future_tsc(timeout);
for (;;) {
u8 status = inb(base+ATA_CB_STAT);
if ((status & mask) == flags)
return status;
if (check_tsc(end)) {
warn_timeout();
return -1;
}
yield();
}
}
// Wait for the device to be not-busy.
static int
await_not_bsy(u16 base)
{
return await_ide(ATA_CB_STAT_BSY, 0, base, IDE_TIMEOUT);
}
// Wait for the device to be ready.
static int
await_rdy(u16 base)
{
return await_ide(ATA_CB_STAT_RDY, ATA_CB_STAT_RDY, base, IDE_TIMEOUT);
}
// Wait for ide state - pauses for one ata cycle first.
static inline int
pause_await_not_bsy(u16 iobase1, u16 iobase2)
{
// Wait one PIO transfer cycle.
inb(iobase2 + ATA_CB_ASTAT);
return await_not_bsy(iobase1);
}
// Wait for ide state - pause for 400ns first.
static inline int
ndelay_await_not_bsy(u16 iobase1)
{
ndelay(400);
return await_not_bsy(iobase1);
}
// Reset a drive
static void
ata_reset(struct atadrive_s *adrive_g)
{
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u8 slave = GET_GLOBAL(adrive_g->slave);
u16 iobase1 = GET_GLOBALFLAT(chan_gf->iobase1);
u16 iobase2 = GET_GLOBALFLAT(chan_gf->iobase2);
dprintf(6, "ata_reset drive=%p\n", &adrive_g->drive);
// Pulse SRST
outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN | ATA_CB_DC_SRST, iobase2+ATA_CB_DC);
udelay(5);
outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2+ATA_CB_DC);
msleep(2);
// wait for device to become not busy.
int status = await_not_bsy(iobase1);
if (status < 0)
goto done;
if (slave) {
// Change device.
u64 end = calc_future_tsc(IDE_TIMEOUT);
for (;;) {
outb(ATA_CB_DH_DEV1, iobase1 + ATA_CB_DH);
status = ndelay_await_not_bsy(iobase1);
if (status < 0)
goto done;
if (inb(iobase1 + ATA_CB_DH) == ATA_CB_DH_DEV1)
break;
// Change drive request failed to take effect - retry.
if (check_tsc(end)) {
warn_timeout();
goto done;
}
}
} else {
// QEMU doesn't reset dh on reset, so set it explicitly.
outb(ATA_CB_DH_DEV0, iobase1 + ATA_CB_DH);
}
// On a user-reset request, wait for RDY if it is an ATA device.
u8 type=GET_GLOBAL(adrive_g->drive.type);
if (type == DTYPE_ATA)
status = await_rdy(iobase1);
done:
// Enable interrupts
outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
dprintf(6, "ata_reset exit status=%x\n", status);
}
// Check for drive RDY for 16bit interface command.
static int
isready(struct atadrive_s *adrive_g)
{
// Read the status from controller
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u16 iobase1 = GET_GLOBALFLAT(chan_gf->iobase1);
u8 status = inb(iobase1 + ATA_CB_STAT);
if ((status & (ATA_CB_STAT_BSY|ATA_CB_STAT_RDY)) == ATA_CB_STAT_RDY)
return DISK_RET_SUCCESS;
return DISK_RET_ENOTREADY;
}
// Default 16bit command demuxer for ATA and ATAPI devices.
static int
process_ata_misc_op(struct disk_op_s *op)
{
if (!CONFIG_ATA)
return 0;
struct atadrive_s *adrive_g = container_of(
op->drive_g, struct atadrive_s, drive);
switch (op->command) {
case CMD_RESET:
ata_reset(adrive_g);
return DISK_RET_SUCCESS;
case CMD_ISREADY:
return isready(adrive_g);
case CMD_FORMAT:
case CMD_VERIFY:
case CMD_SEEK:
return DISK_RET_SUCCESS;
default:
op->count = 0;
return DISK_RET_EPARAM;
}
}
/****************************************************************
* ATA send command
****************************************************************/
struct ata_pio_command {
u8 feature;
u8 sector_count;
u8 lba_low;
u8 lba_mid;
u8 lba_high;
u8 device;
u8 command;
u8 feature2;
u8 sector_count2;
u8 lba_low2;
u8 lba_mid2;
u8 lba_high2;
};
// Send an ata command to the drive.
static int
send_cmd(struct atadrive_s *adrive_g, struct ata_pio_command *cmd)
{
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u8 slave = GET_GLOBAL(adrive_g->slave);
u16 iobase1 = GET_GLOBALFLAT(chan_gf->iobase1);
// Select device
int status = await_not_bsy(iobase1);
if (status < 0)
return status;
u8 newdh = ((cmd->device & ~ATA_CB_DH_DEV1)
| (slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0));
u8 olddh = inb(iobase1 + ATA_CB_DH);
outb(newdh, iobase1 + ATA_CB_DH);
if ((olddh ^ newdh) & (1<<4)) {
// Was a device change - wait for device to become not busy.
status = ndelay_await_not_bsy(iobase1);
if (status < 0)
return status;
}
// Check for ATA_CMD_(READ|WRITE)_(SECTORS|DMA)_EXT commands.
if ((cmd->command & ~0x11) == ATA_CMD_READ_SECTORS_EXT) {
outb(cmd->feature2, iobase1 + ATA_CB_FR);
outb(cmd->sector_count2, iobase1 + ATA_CB_SC);
outb(cmd->lba_low2, iobase1 + ATA_CB_SN);
outb(cmd->lba_mid2, iobase1 + ATA_CB_CL);
outb(cmd->lba_high2, iobase1 + ATA_CB_CH);
}
outb(cmd->feature, iobase1 + ATA_CB_FR);
outb(cmd->sector_count, iobase1 + ATA_CB_SC);
outb(cmd->lba_low, iobase1 + ATA_CB_SN);
outb(cmd->lba_mid, iobase1 + ATA_CB_CL);
outb(cmd->lba_high, iobase1 + ATA_CB_CH);
outb(cmd->command, iobase1 + ATA_CB_CMD);
return 0;
}
// Wait for data after calling 'send_cmd'.
static int
ata_wait_data(u16 iobase1)
{
int status = ndelay_await_not_bsy(iobase1);
if (status < 0)
return status;
if (status & ATA_CB_STAT_ERR) {
dprintf(6, "send_cmd : read error (status=%02x err=%02x)\n"
, status, inb(iobase1 + ATA_CB_ERR));
return -4;
}
if (!(status & ATA_CB_STAT_DRQ)) {
dprintf(6, "send_cmd : DRQ not set (status %02x)\n", status);
return -5;
}
return 0;
}
// Send an ata command that does not transfer any further data.
int
ata_cmd_nondata(struct atadrive_s *adrive_g, struct ata_pio_command *cmd)
{
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u16 iobase1 = GET_GLOBALFLAT(chan_gf->iobase1);
u16 iobase2 = GET_GLOBALFLAT(chan_gf->iobase2);
// Disable interrupts
outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
int ret = send_cmd(adrive_g, cmd);
if (ret)
goto fail;
ret = ndelay_await_not_bsy(iobase1);
if (ret < 0)
goto fail;
if (ret & ATA_CB_STAT_ERR) {
dprintf(6, "nondata cmd : read error (status=%02x err=%02x)\n"
, ret, inb(iobase1 + ATA_CB_ERR));
ret = -4;
goto fail;
}
if (ret & ATA_CB_STAT_DRQ) {
dprintf(6, "nondata cmd : DRQ set (status %02x)\n", ret);
ret = -5;
goto fail;
}
fail:
// Enable interrupts
outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
return ret;
}
/****************************************************************
* ATA PIO transfers
****************************************************************/
// Transfer 'op->count' blocks (of 'blocksize' bytes) to/from drive
// 'op->drive_g'.
static int
ata_pio_transfer(struct disk_op_s *op, int iswrite, int blocksize)
{
dprintf(16, "ata_pio_transfer id=%p write=%d count=%d bs=%d buf=%p\n"
, op->drive_g, iswrite, op->count, blocksize, op->buf_fl);
struct atadrive_s *adrive_g = container_of(
op->drive_g, struct atadrive_s, drive);
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u16 iobase1 = GET_GLOBALFLAT(chan_gf->iobase1);
u16 iobase2 = GET_GLOBALFLAT(chan_gf->iobase2);
int count = op->count;
void *buf_fl = op->buf_fl;
int status;
for (;;) {
if (iswrite) {
// Write data to controller
dprintf(16, "Write sector id=%p dest=%p\n", op->drive_g, buf_fl);
if (CONFIG_ATA_PIO32)
outsl_fl(iobase1, buf_fl, blocksize / 4);
else
outsw_fl(iobase1, buf_fl, blocksize / 2);
} else {
// Read data from controller
dprintf(16, "Read sector id=%p dest=%p\n", op->drive_g, buf_fl);
if (CONFIG_ATA_PIO32)
insl_fl(iobase1, buf_fl, blocksize / 4);
else
insw_fl(iobase1, buf_fl, blocksize / 2);
}
buf_fl += blocksize;
status = pause_await_not_bsy(iobase1, iobase2);
if (status < 0) {
// Error
op->count -= count;
return status;
}
count--;
if (!count)
break;
status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_DRQ | ATA_CB_STAT_ERR);
if (status != ATA_CB_STAT_DRQ) {
dprintf(6, "ata_pio_transfer : more sectors left (status %02x)\n"
, status);
op->count -= count;
return -6;
}
}
status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_DF | ATA_CB_STAT_DRQ
| ATA_CB_STAT_ERR);
if (!iswrite)
status &= ~ATA_CB_STAT_DF;
if (status != 0) {
dprintf(6, "ata_pio_transfer : no sectors left (status %02x)\n", status);
return -7;
}
return 0;
}
/****************************************************************
* ATA DMA transfers
****************************************************************/
#define BM_CMD 0
#define BM_CMD_MEMWRITE 0x08
#define BM_CMD_START 0x01
#define BM_STATUS 2
#define BM_STATUS_IRQ 0x04
#define BM_STATUS_ERROR 0x02
#define BM_STATUS_ACTIVE 0x01
#define BM_TABLE 4
struct sff_dma_prd {
u32 buf_fl;
u32 count;
};
// Check if DMA available and setup transfer if so.
static int
ata_try_dma(struct disk_op_s *op, int iswrite, int blocksize)
{
if (! CONFIG_ATA_DMA)
return -1;
u32 dest = (u32)op->buf_fl;
if (dest & 1)
// Need minimum alignment of 1.
return -1;
struct atadrive_s *adrive_g = container_of(
op->drive_g, struct atadrive_s, drive);
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u16 iomaster = GET_GLOBALFLAT(chan_gf->iomaster);
if (! iomaster)
return -1;
u32 bytes = op->count * blocksize;
if (! bytes)
return -1;
// Build PRD dma structure.
struct sff_dma_prd *dma = MAKE_FLATPTR(
get_ebda_seg()
, (void*)offsetof(struct extended_bios_data_area_s, extra_stack));
struct sff_dma_prd *origdma = dma;
while (bytes) {
if (dma >= &origdma[16])
// Too many descriptors..
return -1;
u32 count = bytes;
u32 max = 0x10000 - (dest & 0xffff);
if (count > max)
count = max;
SET_FLATPTR(dma->buf_fl, dest);
bytes -= count;
if (!bytes)
// Last descriptor.
count |= 1<<31;
dprintf(16, "dma@%p: %08x %08x\n", dma, dest, count);
dest += count;
SET_FLATPTR(dma->count, count);
dma++;
}
// Program bus-master controller.
outl((u32)origdma, iomaster + BM_TABLE);
u8 oldcmd = inb(iomaster + BM_CMD) & ~(BM_CMD_MEMWRITE|BM_CMD_START);
outb(oldcmd | (iswrite ? 0x00 : BM_CMD_MEMWRITE), iomaster + BM_CMD);
outb(BM_STATUS_ERROR|BM_STATUS_IRQ, iomaster + BM_STATUS);
return 0;
}
// Transfer data using DMA.
static int
ata_dma_transfer(struct disk_op_s *op)
{
if (! CONFIG_ATA_DMA)
return -1;
dprintf(16, "ata_dma_transfer id=%p buf=%p\n", op->drive_g, op->buf_fl);
struct atadrive_s *adrive_g = container_of(
op->drive_g, struct atadrive_s, drive);
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u16 iomaster = GET_GLOBALFLAT(chan_gf->iomaster);
// Start bus-master controller.
u8 oldcmd = inb(iomaster + BM_CMD);
outb(oldcmd | BM_CMD_START, iomaster + BM_CMD);
u64 end = calc_future_tsc(IDE_TIMEOUT);
u8 status;
for (;;) {
status = inb(iomaster + BM_STATUS);
if (status & BM_STATUS_IRQ)
break;
// Transfer in progress
if (check_tsc(end)) {
// Timeout.
warn_timeout();
break;
}
yield();
}
outb(oldcmd & ~BM_CMD_START, iomaster + BM_CMD);
u16 iobase1 = GET_GLOBALFLAT(chan_gf->iobase1);
u16 iobase2 = GET_GLOBALFLAT(chan_gf->iobase2);
int idestatus = pause_await_not_bsy(iobase1, iobase2);
if ((status & (BM_STATUS_IRQ|BM_STATUS_ACTIVE)) == BM_STATUS_IRQ
&& idestatus >= 0x00
&& (idestatus & (ATA_CB_STAT_BSY | ATA_CB_STAT_DF | ATA_CB_STAT_DRQ
| ATA_CB_STAT_ERR)) == 0x00)
// Success.
return 0;
dprintf(6, "IDE DMA error (dma=%x ide=%x/%x/%x)\n", status, idestatus
, inb(iobase2 + ATA_CB_ASTAT), inb(iobase1 + ATA_CB_ERR));
op->count = 0;
return -1;
}
/****************************************************************
* ATA hard drive functions
****************************************************************/
// Transfer data to harddrive using PIO protocol.
static int
ata_pio_cmd_data(struct disk_op_s *op, int iswrite, struct ata_pio_command *cmd)
{
struct atadrive_s *adrive_g = container_of(
op->drive_g, struct atadrive_s, drive);
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u16 iobase1 = GET_GLOBALFLAT(chan_gf->iobase1);
u16 iobase2 = GET_GLOBALFLAT(chan_gf->iobase2);
// Disable interrupts
outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
int ret = send_cmd(adrive_g, cmd);
if (ret)
goto fail;
ret = ata_wait_data(iobase1);
if (ret)
goto fail;
ret = ata_pio_transfer(op, iswrite, DISK_SECTOR_SIZE);
fail:
// Enable interrupts
outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
return ret;
}
// Transfer data to harddrive using DMA protocol.
static int
ata_dma_cmd_data(struct disk_op_s *op, struct ata_pio_command *cmd)
{
if (! CONFIG_ATA_DMA)
return -1;
struct atadrive_s *adrive_g = container_of(
op->drive_g, struct atadrive_s, drive);
int ret = send_cmd(adrive_g, cmd);
if (ret)
return ret;
return ata_dma_transfer(op);
}
// Read/write count blocks from a harddrive.
static int
ata_readwrite(struct disk_op_s *op, int iswrite)
{
u64 lba = op->lba;
int usepio = ata_try_dma(op, iswrite, DISK_SECTOR_SIZE);
struct ata_pio_command cmd;
memset(&cmd, 0, sizeof(cmd));
if (op->count >= (1<<8) || lba + op->count >= (1<<28)) {
cmd.sector_count2 = op->count >> 8;
cmd.lba_low2 = lba >> 24;
cmd.lba_mid2 = lba >> 32;
cmd.lba_high2 = lba >> 40;
lba &= 0xffffff;
if (usepio)
cmd.command = (iswrite ? ATA_CMD_WRITE_SECTORS_EXT
: ATA_CMD_READ_SECTORS_EXT);
else
cmd.command = (iswrite ? ATA_CMD_WRITE_DMA_EXT
: ATA_CMD_READ_DMA_EXT);
} else {
if (usepio)
cmd.command = (iswrite ? ATA_CMD_WRITE_SECTORS
: ATA_CMD_READ_SECTORS);
else
cmd.command = (iswrite ? ATA_CMD_WRITE_DMA
: ATA_CMD_READ_DMA);
}
cmd.sector_count = op->count;
cmd.lba_low = lba;
cmd.lba_mid = lba >> 8;
cmd.lba_high = lba >> 16;
cmd.device = ((lba >> 24) & 0xf) | ATA_CB_DH_LBA;
int ret;
if (usepio)
ret = ata_pio_cmd_data(op, iswrite, &cmd);
else
ret = ata_dma_cmd_data(op, &cmd);
if (ret)
return DISK_RET_EBADTRACK;
return DISK_RET_SUCCESS;
}
// 16bit command demuxer for ATA harddrives.
int
process_ata_op(struct disk_op_s *op)
{
if (!CONFIG_ATA)
return 0;
switch (op->command) {
case CMD_READ:
return ata_readwrite(op, 0);
case CMD_WRITE:
return ata_readwrite(op, 1);
default:
return process_ata_misc_op(op);
}
}
/****************************************************************
* ATAPI functions
****************************************************************/
#define CDROM_CDB_SIZE 12
// Low-level atapi command transmit function.
int
atapi_cmd_data(struct disk_op_s *op, void *cdbcmd, u16 blocksize)
{
struct atadrive_s *adrive_g = container_of(
op->drive_g, struct atadrive_s, drive);
struct ata_channel_s *chan_gf = GET_GLOBAL(adrive_g->chan_gf);
u16 iobase1 = GET_GLOBALFLAT(chan_gf->iobase1);
u16 iobase2 = GET_GLOBALFLAT(chan_gf->iobase2);
struct ata_pio_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.lba_mid = blocksize;
cmd.lba_high = blocksize >> 8;
cmd.command = ATA_CMD_PACKET;
// Disable interrupts
outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
int ret = send_cmd(adrive_g, &cmd);
if (ret)
goto fail;
ret = ata_wait_data(iobase1);
if (ret)
goto fail;
// Send command to device
outsw_fl(iobase1, MAKE_FLATPTR(GET_SEG(SS), cdbcmd), CDROM_CDB_SIZE / 2);
int status = pause_await_not_bsy(iobase1, iobase2);
if (status < 0) {
ret = status;
goto fail;
}
if (status & ATA_CB_STAT_ERR) {
u8 err = inb(iobase1 + ATA_CB_ERR);
// skip "Not Ready"
if (err != 0x20)
dprintf(6, "send_atapi_cmd : read error (status=%02x err=%02x)\n"
, status, err);
ret = -2;
goto fail;
}
if (!(status & ATA_CB_STAT_DRQ)) {
dprintf(6, "send_atapi_cmd : DRQ not set (status %02x)\n", status);
ret = -3;
goto fail;
}
ret = ata_pio_transfer(op, 0, blocksize);
fail:
// Enable interrupts
outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
if (ret)
return DISK_RET_EBADTRACK;
return DISK_RET_SUCCESS;
}
// 16bit command demuxer for ATAPI cdroms.
int
process_atapi_op(struct disk_op_s *op)
{
if (!CONFIG_ATA)
return 0;
switch (op->command) {
case CMD_READ:
return cdb_read(op);
case CMD_FORMAT:
case CMD_WRITE:
return DISK_RET_EWRITEPROTECT;
default:
return process_ata_misc_op(op);
}
}
/****************************************************************
* ATA detect and init
****************************************************************/
// Send an identify device or identify device packet command.
static int
send_ata_identity(struct atadrive_s *adrive_g, u16 *buffer, int command)
{
memset(buffer, 0, DISK_SECTOR_SIZE);
struct disk_op_s dop;
memset(&dop, 0, sizeof(dop));
dop.drive_g = &adrive_g->drive;
dop.count = 1;
dop.lba = 1;
dop.buf_fl = MAKE_FLATPTR(GET_SEG(SS), buffer);
struct ata_pio_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.command = command;
return ata_pio_cmd_data(&dop, 0, &cmd);
}
// Extract the ATA/ATAPI version info.
static int
extract_version(u16 *buffer)
{
// Extract ATA/ATAPI version.
u16 ataversion = buffer[80];
u8 version;
for (version=15; version>0; version--)
if (ataversion & (1<<version))
break;
return version;
}
#define MAXMODEL 40
// Extract the ATA/ATAPI model info.
static char *
extract_model(char *model, u16 *buffer)
{
// Read model name
int i;
for (i=0; i<MAXMODEL/2; i++)
*(u16*)&model[i*2] = ntohs(buffer[27+i]);
model[MAXMODEL] = 0x00;
// Trim trailing spaces from model name.
for (i=MAXMODEL-1; i>0 && model[i] == 0x20; i--)
model[i] = 0x00;
return model;
}
// Common init code between ata and atapi
static struct atadrive_s *
init_atadrive(struct atadrive_s *dummy, u16 *buffer)
{
char *desc = malloc_tmp(MAXDESCSIZE);
struct atadrive_s *adrive_g = malloc_fseg(sizeof(*adrive_g));
if (!adrive_g || !desc) {
warn_noalloc();
free(desc);
free(adrive_g);
return NULL;
}
memset(adrive_g, 0, sizeof(*adrive_g));
adrive_g->drive.desc = desc;
adrive_g->chan_gf = dummy->chan_gf;
adrive_g->slave = dummy->slave;
adrive_g->drive.cntl_id = adrive_g->chan_gf->chanid * 2 + dummy->slave;
adrive_g->drive.removable = (buffer[0] & 0x80) ? 1 : 0;
return adrive_g;
}
// Detect if the given drive is an atapi - initialize it if so.
static struct atadrive_s *
init_drive_atapi(struct atadrive_s *dummy, u16 *buffer)
{
// Send an IDENTIFY_DEVICE_PACKET command to device
int ret = send_ata_identity(dummy, buffer, ATA_CMD_IDENTIFY_PACKET_DEVICE);
if (ret)
return NULL;
// Success - setup as ATAPI.
struct atadrive_s *adrive_g = init_atadrive(dummy, buffer);
if (!adrive_g)
return NULL;
adrive_g->drive.type = DTYPE_ATAPI;
adrive_g->drive.blksize = CDROM_SECTOR_SIZE;
adrive_g->drive.sectors = (u64)-1;
u8 iscd = ((buffer[0] >> 8) & 0x1f) == 0x05;
char model[MAXMODEL+1];
snprintf(adrive_g->drive.desc, MAXDESCSIZE, "ata%d-%d: %s ATAPI-%d %s"
, adrive_g->chan_gf->chanid, adrive_g->slave
, extract_model(model, buffer), extract_version(buffer)
, (iscd ? "DVD/CD" : "Device"));
dprintf(1, "%s\n", adrive_g->drive.desc);
// fill cdidmap
if (iscd)
map_cd_drive(&adrive_g->drive);
return adrive_g;
}
// Detect if the given drive is a regular ata drive - initialize it if so.
static struct atadrive_s *
init_drive_ata(struct atadrive_s *dummy, u16 *buffer)
{
// Send an IDENTIFY_DEVICE command to device
int ret = send_ata_identity(dummy, buffer, ATA_CMD_IDENTIFY_DEVICE);
if (ret)
return NULL;
// Success - setup as ATA.
struct atadrive_s *adrive_g = init_atadrive(dummy, buffer);
if (!adrive_g)
return NULL;
adrive_g->drive.type = DTYPE_ATA;
adrive_g->drive.blksize = DISK_SECTOR_SIZE;
adrive_g->drive.pchs.cylinders = buffer[1];
adrive_g->drive.pchs.heads = buffer[3];
adrive_g->drive.pchs.spt = buffer[6];
u64 sectors;
if (buffer[83] & (1 << 10)) // word 83 - lba48 support
sectors = *(u64*)&buffer[100]; // word 100-103
else
sectors = *(u32*)&buffer[60]; // word 60 and word 61
adrive_g->drive.sectors = sectors;
u64 adjsize = sectors >> 11;
char adjprefix = 'M';
if (adjsize >= (1 << 16)) {
adjsize >>= 10;
adjprefix = 'G';
}
char model[MAXMODEL+1];
snprintf(adrive_g->drive.desc, MAXDESCSIZE
, "ata%d-%d: %s ATA-%d Hard-Disk (%u %ciBytes)"
, adrive_g->chan_gf->chanid, adrive_g->slave
, extract_model(model, buffer), extract_version(buffer)
, (u32)adjsize, adjprefix);
dprintf(1, "%s\n", adrive_g->drive.desc);
// Setup disk geometry translation.
setup_translation(&adrive_g->drive);
// Register with bcv system.
add_bcv_internal(&adrive_g->drive);
return adrive_g;
}
static u64 SpinupEnd;
// Wait for non-busy status and check for "floating bus" condition.
static int
powerup_await_non_bsy(u16 base)
{
u8 orstatus = 0;
u8 status;
for (;;) {
status = inb(base+ATA_CB_STAT);
if (!(status & ATA_CB_STAT_BSY))
break;
orstatus |= status;
if (orstatus == 0xff) {
dprintf(4, "powerup IDE floating\n");
return orstatus;
}
if (check_tsc(SpinupEnd)) {
warn_timeout();
return -1;
}
yield();
}
dprintf(6, "powerup iobase=%x st=%x\n", base, status);
return status;
}
// Detect any drives attached to a given controller.
static void
ata_detect(void *data)
{
struct ata_channel_s *chan_gf = data;
struct atadrive_s dummy;
memset(&dummy, 0, sizeof(dummy));
dummy.chan_gf = chan_gf;
// Device detection
int didreset = 0;
u8 slave;
for (slave=0; slave<=1; slave++) {
// Wait for not-bsy.
u16 iobase1 = chan_gf->iobase1;
int status = powerup_await_non_bsy(iobase1);
if (status < 0)
continue;
u8 newdh = slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0;
outb(newdh, iobase1+ATA_CB_DH);
ndelay(400);
status = powerup_await_non_bsy(iobase1);
if (status < 0)
continue;
// Check if ioport registers look valid.
outb(newdh, iobase1+ATA_CB_DH);
u8 dh = inb(iobase1+ATA_CB_DH);
outb(0x55, iobase1+ATA_CB_SC);
outb(0xaa, iobase1+ATA_CB_SN);
u8 sc = inb(iobase1+ATA_CB_SC);
u8 sn = inb(iobase1+ATA_CB_SN);
dprintf(6, "ata_detect ata%d-%d: sc=%x sn=%x dh=%x\n"
, chan_gf->chanid, slave, sc, sn, dh);
if (sc != 0x55 || sn != 0xaa || dh != newdh)
continue;
// Prepare new drive.
dummy.slave = slave;
// reset the channel
if (!didreset) {
ata_reset(&dummy);
didreset = 1;
}
// check for ATAPI
u16 buffer[256];
struct atadrive_s *adrive_g = init_drive_atapi(&dummy, buffer);
if (!adrive_g) {
// Didn't find an ATAPI drive - look for ATA drive.
u8 st = inb(iobase1+ATA_CB_STAT);
if (!st)
// Status not set - can't be a valid drive.
continue;
// Wait for RDY.
int ret = await_rdy(iobase1);
if (ret < 0)
continue;
// check for ATA.
adrive_g = init_drive_ata(&dummy, buffer);
if (!adrive_g)
// No ATA drive found
continue;
}
u16 resetresult = buffer[93];
dprintf(6, "ata_detect resetresult=%04x\n", resetresult);
if (!slave && (resetresult & 0xdf61) == 0x4041)
// resetresult looks valid and device 0 is responding to
// device 1 requests - device 1 must not be present - skip
// detection.
break;
}
}
// Initialize an ata controller and detect its drives.
static void
init_controller(int chanid, int bdf, int irq, u32 port1, u32 port2, u32 master)
{
struct ata_channel_s *chan_gf = malloc_fseg(sizeof(*chan_gf));
if (!chan_gf) {
warn_noalloc();
return;
}
chan_gf->chanid = chanid;
chan_gf->irq = irq;
chan_gf->pci_bdf = bdf;
chan_gf->iobase1 = port1;
chan_gf->iobase2 = port2;
chan_gf->iomaster = master;
dprintf(1, "ATA controller %d at %x/%x/%x (irq %d dev %x)\n"
, chanid, port1, port2, master, irq, bdf);
run_thread(ata_detect, chan_gf);
}
#define IRQ_ATA1 14
#define IRQ_ATA2 15
// Locate and init ata controllers.
static void
ata_init(void)
{
// Scan PCI bus for ATA adapters
int count=0, pcicount=0;
int bdf, max;
foreachpci(bdf, max) {
pcicount++;
if (pci_config_readw(bdf, PCI_CLASS_DEVICE) != PCI_CLASS_STORAGE_IDE)
continue;
u8 pciirq = pci_config_readb(bdf, PCI_INTERRUPT_LINE);
u8 prog_if = pci_config_readb(bdf, PCI_CLASS_PROG);
int master = 0;
if (CONFIG_ATA_DMA && prog_if & 0x80) {
// Check for bus-mastering.
u32 bar = pci_config_readl(bdf, PCI_BASE_ADDRESS_4);
if (bar & PCI_BASE_ADDRESS_SPACE_IO) {
master = bar & PCI_BASE_ADDRESS_IO_MASK;
pci_config_maskw(bdf, PCI_COMMAND, 0, PCI_COMMAND_MASTER);
}
}
u32 port1, port2, irq;
if (prog_if & 1) {
port1 = (pci_config_readl(bdf, PCI_BASE_ADDRESS_0)
& PCI_BASE_ADDRESS_IO_MASK);
port2 = (pci_config_readl(bdf, PCI_BASE_ADDRESS_1)
& PCI_BASE_ADDRESS_IO_MASK);
irq = pciirq;
} else {
port1 = PORT_ATA1_CMD_BASE;
port2 = PORT_ATA1_CTRL_BASE;
irq = IRQ_ATA1;
}
init_controller(count, bdf, irq, port1, port2, master);
count++;
if (prog_if & 4) {
port1 = (pci_config_readl(bdf, PCI_BASE_ADDRESS_2)
& PCI_BASE_ADDRESS_IO_MASK);
port2 = (pci_config_readl(bdf, PCI_BASE_ADDRESS_3)
& PCI_BASE_ADDRESS_IO_MASK);
irq = pciirq;
} else {
port1 = PORT_ATA2_CMD_BASE;
port2 = PORT_ATA2_CTRL_BASE;
irq = IRQ_ATA2;
}
init_controller(count, bdf, irq, port1, port2, master ? master + 8 : 0);
count++;
}
if (!CONFIG_COREBOOT && !pcicount) {
// No PCI devices found - probably a QEMU "-M isapc" machine.
// Try using ISA ports for ATA controllers.
init_controller(0, -1, IRQ_ATA1
, PORT_ATA1_CMD_BASE, PORT_ATA1_CTRL_BASE, 0);
init_controller(1, -1, IRQ_ATA2
, PORT_ATA2_CMD_BASE, PORT_ATA2_CTRL_BASE, 0);
}
}
void
ata_setup(void)
{
ASSERT32FLAT();
if (!CONFIG_ATA)
return;
dprintf(3, "init hard drives\n");
SpinupEnd = calc_future_tsc(IDE_TIMEOUT);
ata_init();
SET_BDA(disk_control_byte, 0xc0);
enable_hwirq(14, entry_76);
}
| gpl-2.0 |
Lachann/gst-plugins-bad | ext/gl/gstglcolorscale.c | 7 | 6781 | /*
* GStreamer
* Copyright (C) 2008 Julien Isorce <julien.isorce@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/**
* SECTION:element-glcolorscale
*
* video frame scaling and colorspace conversion.
*
* <refsect2>
* <title>Scaling and Color space conversion</title>
* <para>
* Equivalent to glupload ! gldownload.
* </para>
* </refsect2>
* <refsect2>
* <title>Examples</title>
* |[
* gst-launch -v videotestsrc ! "video/x-raw-yuv" ! glcolorscale ! ximagesink
* ]| A pipeline to test colorspace conversion.
* FBO is required.
|[
* gst-launch -v videotestsrc ! "video/x-raw-yuv, width=640, height=480, format=(fourcc)AYUV" ! glcolorscale ! \
* "video/x-raw-yuv, width=320, height=240, format=(fourcc)YV12" ! autovideosink
* ]| A pipeline to test hardware scaling and colorspace conversion.
* FBO and GLSL are required.
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstglcolorscale.h"
#define GST_CAT_DEFAULT gst_gl_colorscale_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
/* Properties */
enum
{
PROP_0
};
#define DEBUG_INIT \
GST_DEBUG_CATEGORY_INIT (gst_gl_colorscale_debug, "glcolorscale", 0, "glcolorscale element");
G_DEFINE_TYPE_WITH_CODE (GstGLColorscale, gst_gl_colorscale,
GST_TYPE_GL_FILTER, DEBUG_INIT);
static void gst_gl_colorscale_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_gl_colorscale_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
#if GST_GL_HAVE_GLES2
static gboolean gst_gl_colorscale_gen_gl_resources (GstGLFilter * filter);
static void gst_gl_colorscale_del_gl_resources (GstGLFilter * filter);
#endif
static gboolean gst_gl_colorscale_filter_texture (GstGLFilter * filter,
guint in_tex, guint out_tex);
#if GST_GL_HAVE_OPENGL
static void gst_gl_colorscale_callback (gint width, gint height,
guint texture, gpointer stuff);
#endif
static void
gst_gl_colorscale_class_init (GstGLColorscaleClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *element_class;
GstGLFilterClass *filter_class;
GstBaseTransformClass *basetransform_class = GST_BASE_TRANSFORM_CLASS (klass);
gobject_class = (GObjectClass *) klass;
element_class = GST_ELEMENT_CLASS (klass);
filter_class = GST_GL_FILTER_CLASS (klass);
gobject_class->set_property = gst_gl_colorscale_set_property;
gobject_class->get_property = gst_gl_colorscale_get_property;
gst_element_class_set_metadata (element_class, "OpenGL color scale",
"Filter/Effect/Video", "Colorspace converter and video scaler",
"Julien Isorce <julien.isorce@gmail.com>");
#if GST_GL_HAVE_GLES2
filter_class->onInitFBO =
GST_DEBUG_FUNCPTR (gst_gl_colorscale_gen_gl_resources);
filter_class->onStop = GST_DEBUG_FUNCPTR (gst_gl_colorscale_del_gl_resources);
#endif
filter_class->filter_texture = gst_gl_colorscale_filter_texture;
basetransform_class->passthrough_on_same_caps = TRUE;
}
static void
gst_gl_colorscale_init (GstGLColorscale * colorscale)
{
#if GST_GL_HAVE_GLES2
colorscale->shader = NULL;
#endif
}
static void
gst_gl_colorscale_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_gl_colorscale_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
#if GST_GL_HAVE_GLES2
static void
_compile_identity_shader (GstGLContext * context, GstGLColorscale * colorscale)
{
GstGLFilter *filter = GST_GL_FILTER (colorscale);
colorscale->shader = gst_gl_shader_new (context);
if (!gst_gl_shader_compile_with_default_vf_and_check (colorscale->shader,
&filter->draw_attr_position_loc, &filter->draw_attr_texture_loc)) {
gst_gl_context_clear_shader (context);
gst_object_unref (colorscale->shader);
colorscale->shader = NULL;
}
}
static gboolean
gst_gl_colorscale_gen_gl_resources (GstGLFilter * filter)
{
GstGLColorscale *colorscale = GST_GL_COLORSCALE (filter);
if (gst_gl_context_get_gl_api (filter->context) & GST_GL_API_GLES2) {
gst_gl_context_thread_add (filter->context,
(GstGLContextThreadFunc) _compile_identity_shader, colorscale);
if (!colorscale->shader) {
gst_gl_context_set_error (filter->context,
"Failed to initialize identity shader");
GST_ELEMENT_ERROR (colorscale, RESOURCE, NOT_FOUND, ("%s",
gst_gl_context_get_error ()), (NULL));
return FALSE;
}
}
return TRUE;
}
static void
gst_gl_colorscale_del_gl_resources (GstGLFilter * filter)
{
GstGLColorscale *colorscale = GST_GL_COLORSCALE (filter);
if (colorscale->shader) {
gst_gl_context_del_shader (filter->context, colorscale->shader);
colorscale->shader = NULL;
}
}
#endif
static gboolean
gst_gl_colorscale_filter_texture (GstGLFilter * filter, guint in_tex,
guint out_tex)
{
GstGLColorscale *colorscale;
colorscale = GST_GL_COLORSCALE (filter);
#if GST_GL_HAVE_GLES2
if (gst_gl_context_get_gl_api (filter->context) & GST_GL_API_GLES2)
gst_gl_filter_render_to_target_with_shader (filter, TRUE, in_tex, out_tex,
colorscale->shader);
#endif
#if GST_GL_HAVE_OPENGL
if (gst_gl_context_get_gl_api (filter->context) & GST_GL_API_OPENGL)
gst_gl_filter_render_to_target (filter, TRUE, in_tex, out_tex,
gst_gl_colorscale_callback, colorscale);
#endif
return TRUE;
}
#if GST_GL_HAVE_OPENGL
static void
gst_gl_colorscale_callback (gint width, gint height, guint texture,
gpointer stuff)
{
GstGLFilter *filter = GST_GL_FILTER (stuff);
if (gst_gl_context_get_gl_api (filter->context) & GST_GL_API_OPENGL) {
const GstGLFuncs *gl = filter->context->gl_vtable;
gl->MatrixMode (GL_PROJECTION);
gl->LoadIdentity ();
}
gst_gl_filter_draw_texture (filter, texture, width, height);
}
#endif
| gpl-2.0 |
infoburp/glibc | sysdeps/gnu/errlist.c | 7 | 40952 | /* This file is generated from errno.texi by errlist.awk. */
#include <errno.h>
#include <libintl.h>
#ifndef ERR_REMAP
# define ERR_REMAP(n) n
#endif
#if !defined EMIT_ERR_MAX && !defined ERRLIST_NO_COMPAT
# include <errlist-compat.h>
#endif
#ifdef ERR_MAX
# define ERRLIST_SIZE ERR_MAX + 1
#else
# define ERR_MAX 0
# define ERRLIST_SIZE
#endif
const char *const _sys_errlist_internal[ERRLIST_SIZE] =
{
[0] = N_("Success"),
#ifdef EPERM
/*
TRANS Operation not permitted; only the owner of the file (or other resource)
TRANS or processes with special privileges can perform the operation. */
[ERR_REMAP (EPERM)] = N_("Operation not permitted"),
# if EPERM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPERM
# endif
#endif
#ifdef ENOENT
/*
TRANS No such file or directory. This is a ``file doesn't exist'' error
TRANS for ordinary files that are referenced in contexts where they are
TRANS expected to already exist. */
[ERR_REMAP (ENOENT)] = N_("No such file or directory"),
# if ENOENT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOENT
# endif
#endif
#ifdef ESRCH
/*
TRANS No process matches the specified process ID. */
[ERR_REMAP (ESRCH)] = N_("No such process"),
# if ESRCH > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ESRCH
# endif
#endif
#ifdef EINTR
/*
TRANS Interrupted function call; an asynchronous signal occurred and prevented
TRANS completion of the call. When this happens, you should try the call
TRANS again.
TRANS
TRANS You can choose to have functions resume after a signal that is handled,
TRANS rather than failing with @code{EINTR}; see @ref{Interrupted
TRANS Primitives}. */
[ERR_REMAP (EINTR)] = N_("Interrupted system call"),
# if EINTR > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EINTR
# endif
#endif
#ifdef EIO
/*
TRANS Input/output error; usually used for physical read or write errors. */
[ERR_REMAP (EIO)] = N_("Input/output error"),
# if EIO > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EIO
# endif
#endif
#ifdef ENXIO
/*
TRANS No such device or address. The system tried to use the device
TRANS represented by a file you specified, and it couldn't find the device.
TRANS This can mean that the device file was installed incorrectly, or that
TRANS the physical device is missing or not correctly attached to the
TRANS computer. */
[ERR_REMAP (ENXIO)] = N_("No such device or address"),
# if ENXIO > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENXIO
# endif
#endif
#ifdef E2BIG
/*
TRANS Argument list too long; used when the arguments passed to a new program
TRANS being executed with one of the @code{exec} functions (@pxref{Executing a
TRANS File}) occupy too much memory space. This condition never arises on
TRANS @gnuhurdsystems{}. */
[ERR_REMAP (E2BIG)] = N_("Argument list too long"),
# if E2BIG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX E2BIG
# endif
#endif
#ifdef ENOEXEC
/*
TRANS Invalid executable file format. This condition is detected by the
TRANS @code{exec} functions; see @ref{Executing a File}. */
[ERR_REMAP (ENOEXEC)] = N_("Exec format error"),
# if ENOEXEC > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOEXEC
# endif
#endif
#ifdef EBADF
/*
TRANS Bad file descriptor; for example, I/O on a descriptor that has been
TRANS closed or reading from a descriptor open only for writing (or vice
TRANS versa). */
[ERR_REMAP (EBADF)] = N_("Bad file descriptor"),
# if EBADF > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBADF
# endif
#endif
#ifdef ECHILD
/*
TRANS There are no child processes. This error happens on operations that are
TRANS supposed to manipulate child processes, when there aren't any processes
TRANS to manipulate. */
[ERR_REMAP (ECHILD)] = N_("No child processes"),
# if ECHILD > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ECHILD
# endif
#endif
#ifdef EDEADLK
/*
TRANS Deadlock avoided; allocating a system resource would have resulted in a
TRANS deadlock situation. The system does not guarantee that it will notice
TRANS all such situations. This error means you got lucky and the system
TRANS noticed; it might just hang. @xref{File Locks}, for an example. */
[ERR_REMAP (EDEADLK)] = N_("Resource deadlock avoided"),
# if EDEADLK > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EDEADLK
# endif
#endif
#ifdef ENOMEM
/*
TRANS No memory available. The system cannot allocate more virtual memory
TRANS because its capacity is full. */
[ERR_REMAP (ENOMEM)] = N_("Cannot allocate memory"),
# if ENOMEM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOMEM
# endif
#endif
#ifdef EACCES
/*
TRANS Permission denied; the file permissions do not allow the attempted operation. */
[ERR_REMAP (EACCES)] = N_("Permission denied"),
# if EACCES > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EACCES
# endif
#endif
#ifdef EFAULT
/*
TRANS Bad address; an invalid pointer was detected.
TRANS On @gnuhurdsystems{}, this error never happens; you get a signal instead. */
[ERR_REMAP (EFAULT)] = N_("Bad address"),
# if EFAULT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EFAULT
# endif
#endif
#ifdef ENOTBLK
/*
TRANS A file that isn't a block special file was given in a situation that
TRANS requires one. For example, trying to mount an ordinary file as a file
TRANS system in Unix gives this error. */
[ERR_REMAP (ENOTBLK)] = N_("Block device required"),
# if ENOTBLK > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTBLK
# endif
#endif
#ifdef EBUSY
/*
TRANS Resource busy; a system resource that can't be shared is already in use.
TRANS For example, if you try to delete a file that is the root of a currently
TRANS mounted filesystem, you get this error. */
[ERR_REMAP (EBUSY)] = N_("Device or resource busy"),
# if EBUSY > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBUSY
# endif
#endif
#ifdef EEXIST
/*
TRANS File exists; an existing file was specified in a context where it only
TRANS makes sense to specify a new file. */
[ERR_REMAP (EEXIST)] = N_("File exists"),
# if EEXIST > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EEXIST
# endif
#endif
#ifdef EXDEV
/*
TRANS An attempt to make an improper link across file systems was detected.
TRANS This happens not only when you use @code{link} (@pxref{Hard Links}) but
TRANS also when you rename a file with @code{rename} (@pxref{Renaming Files}). */
[ERR_REMAP (EXDEV)] = N_("Invalid cross-device link"),
# if EXDEV > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EXDEV
# endif
#endif
#ifdef ENODEV
/*
TRANS The wrong type of device was given to a function that expects a
TRANS particular sort of device. */
[ERR_REMAP (ENODEV)] = N_("No such device"),
# if ENODEV > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENODEV
# endif
#endif
#ifdef ENOTDIR
/*
TRANS A file that isn't a directory was specified when a directory is required. */
[ERR_REMAP (ENOTDIR)] = N_("Not a directory"),
# if ENOTDIR > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTDIR
# endif
#endif
#ifdef EISDIR
/*
TRANS File is a directory; you cannot open a directory for writing,
TRANS or create or remove hard links to it. */
[ERR_REMAP (EISDIR)] = N_("Is a directory"),
# if EISDIR > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EISDIR
# endif
#endif
#ifdef EINVAL
/*
TRANS Invalid argument. This is used to indicate various kinds of problems
TRANS with passing the wrong argument to a library function. */
[ERR_REMAP (EINVAL)] = N_("Invalid argument"),
# if EINVAL > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EINVAL
# endif
#endif
#ifdef EMFILE
/*
TRANS The current process has too many files open and can't open any more.
TRANS Duplicate descriptors do count toward this limit.
TRANS
TRANS In BSD and GNU, the number of open files is controlled by a resource
TRANS limit that can usually be increased. If you get this error, you might
TRANS want to increase the @code{RLIMIT_NOFILE} limit or make it unlimited;
TRANS @pxref{Limits on Resources}. */
[ERR_REMAP (EMFILE)] = N_("Too many open files"),
# if EMFILE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EMFILE
# endif
#endif
#ifdef ENFILE
/*
TRANS There are too many distinct file openings in the entire system. Note
TRANS that any number of linked channels count as just one file opening; see
TRANS @ref{Linked Channels}. This error never occurs on @gnuhurdsystems{}. */
[ERR_REMAP (ENFILE)] = N_("Too many open files in system"),
# if ENFILE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENFILE
# endif
#endif
#ifdef ENOTTY
/*
TRANS Inappropriate I/O control operation, such as trying to set terminal
TRANS modes on an ordinary file. */
[ERR_REMAP (ENOTTY)] = N_("Inappropriate ioctl for device"),
# if ENOTTY > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTTY
# endif
#endif
#ifdef ETXTBSY
/*
TRANS An attempt to execute a file that is currently open for writing, or
TRANS write to a file that is currently being executed. Often using a
TRANS debugger to run a program is considered having it open for writing and
TRANS will cause this error. (The name stands for ``text file busy''.) This
TRANS is not an error on @gnuhurdsystems{}; the text is copied as necessary. */
[ERR_REMAP (ETXTBSY)] = N_("Text file busy"),
# if ETXTBSY > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ETXTBSY
# endif
#endif
#ifdef EFBIG
/*
TRANS File too big; the size of a file would be larger than allowed by the system. */
[ERR_REMAP (EFBIG)] = N_("File too large"),
# if EFBIG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EFBIG
# endif
#endif
#ifdef ENOSPC
/*
TRANS No space left on device; write operation on a file failed because the
TRANS disk is full. */
[ERR_REMAP (ENOSPC)] = N_("No space left on device"),
# if ENOSPC > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOSPC
# endif
#endif
#ifdef ESPIPE
/*
TRANS Invalid seek operation (such as on a pipe). */
[ERR_REMAP (ESPIPE)] = N_("Illegal seek"),
# if ESPIPE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ESPIPE
# endif
#endif
#ifdef EROFS
/*
TRANS An attempt was made to modify something on a read-only file system. */
[ERR_REMAP (EROFS)] = N_("Read-only file system"),
# if EROFS > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EROFS
# endif
#endif
#ifdef EMLINK
/*
TRANS Too many links; the link count of a single file would become too large.
TRANS @code{rename} can cause this error if the file being renamed already has
TRANS as many links as it can take (@pxref{Renaming Files}). */
[ERR_REMAP (EMLINK)] = N_("Too many links"),
# if EMLINK > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EMLINK
# endif
#endif
#ifdef EPIPE
/*
TRANS Broken pipe; there is no process reading from the other end of a pipe.
TRANS Every library function that returns this error code also generates a
TRANS @code{SIGPIPE} signal; this signal terminates the program if not handled
TRANS or blocked. Thus, your program will never actually see @code{EPIPE}
TRANS unless it has handled or blocked @code{SIGPIPE}. */
[ERR_REMAP (EPIPE)] = N_("Broken pipe"),
# if EPIPE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPIPE
# endif
#endif
#ifdef EDOM
/*
TRANS Domain error; used by mathematical functions when an argument value does
TRANS not fall into the domain over which the function is defined. */
[ERR_REMAP (EDOM)] = N_("Numerical argument out of domain"),
# if EDOM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EDOM
# endif
#endif
#ifdef ERANGE
/*
TRANS Range error; used by mathematical functions when the result value is
TRANS not representable because of overflow or underflow. */
[ERR_REMAP (ERANGE)] = N_("Numerical result out of range"),
# if ERANGE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ERANGE
# endif
#endif
#ifdef EAGAIN
/*
TRANS Resource temporarily unavailable; the call might work if you try again
TRANS later. The macro @code{EWOULDBLOCK} is another name for @code{EAGAIN};
TRANS they are always the same in @theglibc{}.
TRANS
TRANS This error can happen in a few different situations:
TRANS
TRANS @itemize @bullet
TRANS @item
TRANS An operation that would block was attempted on an object that has
TRANS non-blocking mode selected. Trying the same operation again will block
TRANS until some external condition makes it possible to read, write, or
TRANS connect (whatever the operation). You can use @code{select} to find out
TRANS when the operation will be possible; @pxref{Waiting for I/O}.
TRANS
TRANS @strong{Portability Note:} In many older Unix systems, this condition
TRANS was indicated by @code{EWOULDBLOCK}, which was a distinct error code
TRANS different from @code{EAGAIN}. To make your program portable, you should
TRANS check for both codes and treat them the same.
TRANS
TRANS @item
TRANS A temporary resource shortage made an operation impossible. @code{fork}
TRANS can return this error. It indicates that the shortage is expected to
TRANS pass, so your program can try the call again later and it may succeed.
TRANS It is probably a good idea to delay for a few seconds before trying it
TRANS again, to allow time for other processes to release scarce resources.
TRANS Such shortages are usually fairly serious and affect the whole system,
TRANS so usually an interactive program should report the error to the user
TRANS and return to its command loop.
TRANS @end itemize */
[ERR_REMAP (EAGAIN)] = N_("Resource temporarily unavailable"),
# if EAGAIN > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EAGAIN
# endif
#endif
#if defined (EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
/*
TRANS In @theglibc{}, this is another name for @code{EAGAIN} (above).
TRANS The values are always the same, on every operating system.
TRANS
TRANS C libraries in many older Unix systems have @code{EWOULDBLOCK} as a
TRANS separate error code. */
[ERR_REMAP (EWOULDBLOCK)] = N_("Operation would block"),
# if EWOULDBLOCK > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EWOULDBLOCK
# endif
#endif
#ifdef EINPROGRESS
/*
TRANS An operation that cannot complete immediately was initiated on an object
TRANS that has non-blocking mode selected. Some functions that must always
TRANS block (such as @code{connect}; @pxref{Connecting}) never return
TRANS @code{EAGAIN}. Instead, they return @code{EINPROGRESS} to indicate that
TRANS the operation has begun and will take some time. Attempts to manipulate
TRANS the object before the call completes return @code{EALREADY}. You can
TRANS use the @code{select} function to find out when the pending operation
TRANS has completed; @pxref{Waiting for I/O}. */
[ERR_REMAP (EINPROGRESS)] = N_("Operation now in progress"),
# if EINPROGRESS > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EINPROGRESS
# endif
#endif
#ifdef EALREADY
/*
TRANS An operation is already in progress on an object that has non-blocking
TRANS mode selected. */
[ERR_REMAP (EALREADY)] = N_("Operation already in progress"),
# if EALREADY > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EALREADY
# endif
#endif
#ifdef ENOTSOCK
/*
TRANS A file that isn't a socket was specified when a socket is required. */
[ERR_REMAP (ENOTSOCK)] = N_("Socket operation on non-socket"),
# if ENOTSOCK > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTSOCK
# endif
#endif
#ifdef EMSGSIZE
/*
TRANS The size of a message sent on a socket was larger than the supported
TRANS maximum size. */
[ERR_REMAP (EMSGSIZE)] = N_("Message too long"),
# if EMSGSIZE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EMSGSIZE
# endif
#endif
#ifdef EPROTOTYPE
/*
TRANS The socket type does not support the requested communications protocol. */
[ERR_REMAP (EPROTOTYPE)] = N_("Protocol wrong type for socket"),
# if EPROTOTYPE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPROTOTYPE
# endif
#endif
#ifdef ENOPROTOOPT
/*
TRANS You specified a socket option that doesn't make sense for the
TRANS particular protocol being used by the socket. @xref{Socket Options}. */
[ERR_REMAP (ENOPROTOOPT)] = N_("Protocol not available"),
# if ENOPROTOOPT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOPROTOOPT
# endif
#endif
#ifdef EPROTONOSUPPORT
/*
TRANS The socket domain does not support the requested communications protocol
TRANS (perhaps because the requested protocol is completely invalid).
TRANS @xref{Creating a Socket}. */
[ERR_REMAP (EPROTONOSUPPORT)] = N_("Protocol not supported"),
# if EPROTONOSUPPORT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPROTONOSUPPORT
# endif
#endif
#ifdef ESOCKTNOSUPPORT
/*
TRANS The socket type is not supported. */
[ERR_REMAP (ESOCKTNOSUPPORT)] = N_("Socket type not supported"),
# if ESOCKTNOSUPPORT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ESOCKTNOSUPPORT
# endif
#endif
#ifdef EOPNOTSUPP
/*
TRANS The operation you requested is not supported. Some socket functions
TRANS don't make sense for all types of sockets, and others may not be
TRANS implemented for all communications protocols. On @gnuhurdsystems{}, this
TRANS error can happen for many calls when the object does not support the
TRANS particular operation; it is a generic indication that the server knows
TRANS nothing to do for that call. */
[ERR_REMAP (EOPNOTSUPP)] = N_("Operation not supported"),
# if EOPNOTSUPP > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EOPNOTSUPP
# endif
#endif
#ifdef EPFNOSUPPORT
/*
TRANS The socket communications protocol family you requested is not supported. */
[ERR_REMAP (EPFNOSUPPORT)] = N_("Protocol family not supported"),
# if EPFNOSUPPORT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPFNOSUPPORT
# endif
#endif
#ifdef EAFNOSUPPORT
/*
TRANS The address family specified for a socket is not supported; it is
TRANS inconsistent with the protocol being used on the socket. @xref{Sockets}. */
[ERR_REMAP (EAFNOSUPPORT)] = N_("Address family not supported by protocol"),
# if EAFNOSUPPORT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EAFNOSUPPORT
# endif
#endif
#ifdef EADDRINUSE
/*
TRANS The requested socket address is already in use. @xref{Socket Addresses}. */
[ERR_REMAP (EADDRINUSE)] = N_("Address already in use"),
# if EADDRINUSE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EADDRINUSE
# endif
#endif
#ifdef EADDRNOTAVAIL
/*
TRANS The requested socket address is not available; for example, you tried
TRANS to give a socket a name that doesn't match the local host name.
TRANS @xref{Socket Addresses}. */
[ERR_REMAP (EADDRNOTAVAIL)] = N_("Cannot assign requested address"),
# if EADDRNOTAVAIL > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EADDRNOTAVAIL
# endif
#endif
#ifdef ENETDOWN
/*
TRANS A socket operation failed because the network was down. */
[ERR_REMAP (ENETDOWN)] = N_("Network is down"),
# if ENETDOWN > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENETDOWN
# endif
#endif
#ifdef ENETUNREACH
/*
TRANS A socket operation failed because the subnet containing the remote host
TRANS was unreachable. */
[ERR_REMAP (ENETUNREACH)] = N_("Network is unreachable"),
# if ENETUNREACH > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENETUNREACH
# endif
#endif
#ifdef ENETRESET
/*
TRANS A network connection was reset because the remote host crashed. */
[ERR_REMAP (ENETRESET)] = N_("Network dropped connection on reset"),
# if ENETRESET > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENETRESET
# endif
#endif
#ifdef ECONNABORTED
/*
TRANS A network connection was aborted locally. */
[ERR_REMAP (ECONNABORTED)] = N_("Software caused connection abort"),
# if ECONNABORTED > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ECONNABORTED
# endif
#endif
#ifdef ECONNRESET
/*
TRANS A network connection was closed for reasons outside the control of the
TRANS local host, such as by the remote machine rebooting or an unrecoverable
TRANS protocol violation. */
[ERR_REMAP (ECONNRESET)] = N_("Connection reset by peer"),
# if ECONNRESET > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ECONNRESET
# endif
#endif
#ifdef ENOBUFS
/*
TRANS The kernel's buffers for I/O operations are all in use. In GNU, this
TRANS error is always synonymous with @code{ENOMEM}; you may get one or the
TRANS other from network operations. */
[ERR_REMAP (ENOBUFS)] = N_("No buffer space available"),
# if ENOBUFS > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOBUFS
# endif
#endif
#ifdef EISCONN
/*
TRANS You tried to connect a socket that is already connected.
TRANS @xref{Connecting}. */
[ERR_REMAP (EISCONN)] = N_("Transport endpoint is already connected"),
# if EISCONN > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EISCONN
# endif
#endif
#ifdef ENOTCONN
/*
TRANS The socket is not connected to anything. You get this error when you
TRANS try to transmit data over a socket, without first specifying a
TRANS destination for the data. For a connectionless socket (for datagram
TRANS protocols, such as UDP), you get @code{EDESTADDRREQ} instead. */
[ERR_REMAP (ENOTCONN)] = N_("Transport endpoint is not connected"),
# if ENOTCONN > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTCONN
# endif
#endif
#ifdef EDESTADDRREQ
/*
TRANS No default destination address was set for the socket. You get this
TRANS error when you try to transmit data over a connectionless socket,
TRANS without first specifying a destination for the data with @code{connect}. */
[ERR_REMAP (EDESTADDRREQ)] = N_("Destination address required"),
# if EDESTADDRREQ > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EDESTADDRREQ
# endif
#endif
#ifdef ESHUTDOWN
/*
TRANS The socket has already been shut down. */
[ERR_REMAP (ESHUTDOWN)] = N_("Cannot send after transport endpoint shutdown"),
# if ESHUTDOWN > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ESHUTDOWN
# endif
#endif
#ifdef ETOOMANYREFS
/*
TRANS ??? */
[ERR_REMAP (ETOOMANYREFS)] = N_("Too many references: cannot splice"),
# if ETOOMANYREFS > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ETOOMANYREFS
# endif
#endif
#ifdef ETIMEDOUT
/*
TRANS A socket operation with a specified timeout received no response during
TRANS the timeout period. */
[ERR_REMAP (ETIMEDOUT)] = N_("Connection timed out"),
# if ETIMEDOUT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ETIMEDOUT
# endif
#endif
#ifdef ECONNREFUSED
/*
TRANS A remote host refused to allow the network connection (typically because
TRANS it is not running the requested service). */
[ERR_REMAP (ECONNREFUSED)] = N_("Connection refused"),
# if ECONNREFUSED > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ECONNREFUSED
# endif
#endif
#ifdef ELOOP
/*
TRANS Too many levels of symbolic links were encountered in looking up a file name.
TRANS This often indicates a cycle of symbolic links. */
[ERR_REMAP (ELOOP)] = N_("Too many levels of symbolic links"),
# if ELOOP > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ELOOP
# endif
#endif
#ifdef ENAMETOOLONG
/*
TRANS Filename too long (longer than @code{PATH_MAX}; @pxref{Limits for
TRANS Files}) or host name too long (in @code{gethostname} or
TRANS @code{sethostname}; @pxref{Host Identification}). */
[ERR_REMAP (ENAMETOOLONG)] = N_("File name too long"),
# if ENAMETOOLONG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENAMETOOLONG
# endif
#endif
#ifdef EHOSTDOWN
/*
TRANS The remote host for a requested network connection is down. */
[ERR_REMAP (EHOSTDOWN)] = N_("Host is down"),
# if EHOSTDOWN > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EHOSTDOWN
# endif
#endif
#ifdef EHOSTUNREACH
/*
TRANS The remote host for a requested network connection is not reachable. */
[ERR_REMAP (EHOSTUNREACH)] = N_("No route to host"),
# if EHOSTUNREACH > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EHOSTUNREACH
# endif
#endif
#ifdef ENOTEMPTY
/*
TRANS Directory not empty, where an empty directory was expected. Typically,
TRANS this error occurs when you are trying to delete a directory. */
[ERR_REMAP (ENOTEMPTY)] = N_("Directory not empty"),
# if ENOTEMPTY > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTEMPTY
# endif
#endif
#ifdef EPROCLIM
/*
TRANS This means that the per-user limit on new process would be exceeded by
TRANS an attempted @code{fork}. @xref{Limits on Resources}, for details on
TRANS the @code{RLIMIT_NPROC} limit. */
[ERR_REMAP (EPROCLIM)] = N_("Too many processes"),
# if EPROCLIM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPROCLIM
# endif
#endif
#ifdef EUSERS
/*
TRANS The file quota system is confused because there are too many users.
TRANS @c This can probably happen in a GNU system when using NFS. */
[ERR_REMAP (EUSERS)] = N_("Too many users"),
# if EUSERS > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EUSERS
# endif
#endif
#ifdef EDQUOT
/*
TRANS The user's disk quota was exceeded. */
[ERR_REMAP (EDQUOT)] = N_("Disk quota exceeded"),
# if EDQUOT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EDQUOT
# endif
#endif
#ifdef ESTALE
/*
TRANS Stale file handle. This indicates an internal confusion in the
TRANS file system which is due to file system rearrangements on the server host
TRANS for NFS file systems or corruption in other file systems.
TRANS Repairing this condition usually requires unmounting, possibly repairing
TRANS and remounting the file system. */
[ERR_REMAP (ESTALE)] = N_("Stale file handle"),
# if ESTALE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ESTALE
# endif
#endif
#ifdef EREMOTE
/*
TRANS An attempt was made to NFS-mount a remote file system with a file name that
TRANS already specifies an NFS-mounted file.
TRANS (This is an error on some operating systems, but we expect it to work
TRANS properly on @gnuhurdsystems{}, making this error code impossible.) */
[ERR_REMAP (EREMOTE)] = N_("Object is remote"),
# if EREMOTE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EREMOTE
# endif
#endif
#ifdef EBADRPC
/*
TRANS ??? */
[ERR_REMAP (EBADRPC)] = N_("RPC struct is bad"),
# if EBADRPC > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBADRPC
# endif
#endif
#ifdef ERPCMISMATCH
/*
TRANS ??? */
[ERR_REMAP (ERPCMISMATCH)] = N_("RPC version wrong"),
# if ERPCMISMATCH > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ERPCMISMATCH
# endif
#endif
#ifdef EPROGUNAVAIL
/*
TRANS ??? */
[ERR_REMAP (EPROGUNAVAIL)] = N_("RPC program not available"),
# if EPROGUNAVAIL > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPROGUNAVAIL
# endif
#endif
#ifdef EPROGMISMATCH
/*
TRANS ??? */
[ERR_REMAP (EPROGMISMATCH)] = N_("RPC program version wrong"),
# if EPROGMISMATCH > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPROGMISMATCH
# endif
#endif
#ifdef EPROCUNAVAIL
/*
TRANS ??? */
[ERR_REMAP (EPROCUNAVAIL)] = N_("RPC bad procedure for program"),
# if EPROCUNAVAIL > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPROCUNAVAIL
# endif
#endif
#ifdef ENOLCK
/*
TRANS No locks available. This is used by the file locking facilities; see
TRANS @ref{File Locks}. This error is never generated by @gnuhurdsystems{}, but
TRANS it can result from an operation to an NFS server running another
TRANS operating system. */
[ERR_REMAP (ENOLCK)] = N_("No locks available"),
# if ENOLCK > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOLCK
# endif
#endif
#ifdef EFTYPE
/*
TRANS Inappropriate file type or format. The file was the wrong type for the
TRANS operation, or a data file had the wrong format.
TRANS
TRANS On some systems @code{chmod} returns this error if you try to set the
TRANS sticky bit on a non-directory file; @pxref{Setting Permissions}. */
[ERR_REMAP (EFTYPE)] = N_("Inappropriate file type or format"),
# if EFTYPE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EFTYPE
# endif
#endif
#ifdef EAUTH
/*
TRANS ??? */
[ERR_REMAP (EAUTH)] = N_("Authentication error"),
# if EAUTH > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EAUTH
# endif
#endif
#ifdef ENEEDAUTH
/*
TRANS ??? */
[ERR_REMAP (ENEEDAUTH)] = N_("Need authenticator"),
# if ENEEDAUTH > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENEEDAUTH
# endif
#endif
#ifdef ENOSYS
/*
TRANS Function not implemented. This indicates that the function called is
TRANS not implemented at all, either in the C library itself or in the
TRANS operating system. When you get this error, you can be sure that this
TRANS particular function will always fail with @code{ENOSYS} unless you
TRANS install a new version of the C library or the operating system. */
[ERR_REMAP (ENOSYS)] = N_("Function not implemented"),
# if ENOSYS > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOSYS
# endif
#endif
#if defined (ENOTSUP) && ENOTSUP != EOPNOTSUPP
/*
TRANS Not supported. A function returns this error when certain parameter
TRANS values are valid, but the functionality they request is not available.
TRANS This can mean that the function does not implement a particular command
TRANS or option value or flag bit at all. For functions that operate on some
TRANS object given in a parameter, such as a file descriptor or a port, it
TRANS might instead mean that only @emph{that specific object} (file
TRANS descriptor, port, etc.) is unable to support the other parameters given;
TRANS different file descriptors might support different ranges of parameter
TRANS values.
TRANS
TRANS If the entire function is not available at all in the implementation,
TRANS it returns @code{ENOSYS} instead. */
[ERR_REMAP (ENOTSUP)] = N_("Not supported"),
# if ENOTSUP > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTSUP
# endif
#endif
#ifdef EILSEQ
/*
TRANS While decoding a multibyte character the function came along an invalid
TRANS or an incomplete sequence of bytes or the given wide character is invalid. */
[ERR_REMAP (EILSEQ)] = N_("Invalid or incomplete multibyte or wide character"),
# if EILSEQ > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EILSEQ
# endif
#endif
#ifdef EBACKGROUND
/*
TRANS On @gnuhurdsystems{}, servers supporting the @code{term} protocol return
TRANS this error for certain operations when the caller is not in the
TRANS foreground process group of the terminal. Users do not usually see this
TRANS error because functions such as @code{read} and @code{write} translate
TRANS it into a @code{SIGTTIN} or @code{SIGTTOU} signal. @xref{Job Control},
TRANS for information on process groups and these signals. */
[ERR_REMAP (EBACKGROUND)] = N_("Inappropriate operation for background process"),
# if EBACKGROUND > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBACKGROUND
# endif
#endif
#ifdef EDIED
/*
TRANS On @gnuhurdsystems{}, opening a file returns this error when the file is
TRANS translated by a program and the translator program dies while starting
TRANS up, before it has connected to the file. */
[ERR_REMAP (EDIED)] = N_("Translator died"),
# if EDIED > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EDIED
# endif
#endif
#ifdef ED
/*
TRANS The experienced user will know what is wrong.
TRANS @c This error code is a joke. Its perror text is part of the joke.
TRANS @c Don't change it. */
[ERR_REMAP (ED)] = N_("?"),
# if ED > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ED
# endif
#endif
#ifdef EGREGIOUS
/*
TRANS You did @strong{what}? */
[ERR_REMAP (EGREGIOUS)] = N_("You really blew it this time"),
# if EGREGIOUS > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EGREGIOUS
# endif
#endif
#ifdef EIEIO
/*
TRANS Go home and have a glass of warm, dairy-fresh milk. */
[ERR_REMAP (EIEIO)] = N_("Computer bought the farm"),
# if EIEIO > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EIEIO
# endif
#endif
#ifdef EGRATUITOUS
/*
TRANS This error code has no purpose. */
[ERR_REMAP (EGRATUITOUS)] = N_("Gratuitous error"),
# if EGRATUITOUS > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EGRATUITOUS
# endif
#endif
#ifdef EBADMSG
/* */
[ERR_REMAP (EBADMSG)] = N_("Bad message"),
# if EBADMSG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBADMSG
# endif
#endif
#ifdef EIDRM
/* */
[ERR_REMAP (EIDRM)] = N_("Identifier removed"),
# if EIDRM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EIDRM
# endif
#endif
#ifdef EMULTIHOP
/* */
[ERR_REMAP (EMULTIHOP)] = N_("Multihop attempted"),
# if EMULTIHOP > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EMULTIHOP
# endif
#endif
#ifdef ENODATA
/* */
[ERR_REMAP (ENODATA)] = N_("No data available"),
# if ENODATA > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENODATA
# endif
#endif
#ifdef ENOLINK
/* */
[ERR_REMAP (ENOLINK)] = N_("Link has been severed"),
# if ENOLINK > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOLINK
# endif
#endif
#ifdef ENOMSG
/* */
[ERR_REMAP (ENOMSG)] = N_("No message of desired type"),
# if ENOMSG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOMSG
# endif
#endif
#ifdef ENOSR
/* */
[ERR_REMAP (ENOSR)] = N_("Out of streams resources"),
# if ENOSR > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOSR
# endif
#endif
#ifdef ENOSTR
/* */
[ERR_REMAP (ENOSTR)] = N_("Device not a stream"),
# if ENOSTR > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOSTR
# endif
#endif
#ifdef EOVERFLOW
/* */
[ERR_REMAP (EOVERFLOW)] = N_("Value too large for defined data type"),
# if EOVERFLOW > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EOVERFLOW
# endif
#endif
#ifdef EPROTO
/* */
[ERR_REMAP (EPROTO)] = N_("Protocol error"),
# if EPROTO > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EPROTO
# endif
#endif
#ifdef ETIME
/* */
[ERR_REMAP (ETIME)] = N_("Timer expired"),
# if ETIME > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ETIME
# endif
#endif
#ifdef ECANCELED
/*
TRANS Operation canceled; an asynchronous operation was canceled before it
TRANS completed. @xref{Asynchronous I/O}. When you call @code{aio_cancel},
TRANS the normal result is for the operations affected to complete with this
TRANS error; @pxref{Cancel AIO Operations}. */
[ERR_REMAP (ECANCELED)] = N_("Operation canceled"),
# if ECANCELED > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ECANCELED
# endif
#endif
#ifdef ERESTART
/* */
[ERR_REMAP (ERESTART)] = N_("Interrupted system call should be restarted"),
# if ERESTART > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ERESTART
# endif
#endif
#ifdef ECHRNG
/* */
[ERR_REMAP (ECHRNG)] = N_("Channel number out of range"),
# if ECHRNG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ECHRNG
# endif
#endif
#ifdef EL2NSYNC
/* */
[ERR_REMAP (EL2NSYNC)] = N_("Level 2 not synchronized"),
# if EL2NSYNC > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EL2NSYNC
# endif
#endif
#ifdef EL3HLT
/* */
[ERR_REMAP (EL3HLT)] = N_("Level 3 halted"),
# if EL3HLT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EL3HLT
# endif
#endif
#ifdef EL3RST
/* */
[ERR_REMAP (EL3RST)] = N_("Level 3 reset"),
# if EL3RST > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EL3RST
# endif
#endif
#ifdef ELNRNG
/* */
[ERR_REMAP (ELNRNG)] = N_("Link number out of range"),
# if ELNRNG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ELNRNG
# endif
#endif
#ifdef EUNATCH
/* */
[ERR_REMAP (EUNATCH)] = N_("Protocol driver not attached"),
# if EUNATCH > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EUNATCH
# endif
#endif
#ifdef ENOCSI
/* */
[ERR_REMAP (ENOCSI)] = N_("No CSI structure available"),
# if ENOCSI > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOCSI
# endif
#endif
#ifdef EL2HLT
/* */
[ERR_REMAP (EL2HLT)] = N_("Level 2 halted"),
# if EL2HLT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EL2HLT
# endif
#endif
#ifdef EBADE
/* */
[ERR_REMAP (EBADE)] = N_("Invalid exchange"),
# if EBADE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBADE
# endif
#endif
#ifdef EBADR
/* */
[ERR_REMAP (EBADR)] = N_("Invalid request descriptor"),
# if EBADR > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBADR
# endif
#endif
#ifdef EXFULL
/* */
[ERR_REMAP (EXFULL)] = N_("Exchange full"),
# if EXFULL > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EXFULL
# endif
#endif
#ifdef ENOANO
/* */
[ERR_REMAP (ENOANO)] = N_("No anode"),
# if ENOANO > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOANO
# endif
#endif
#ifdef EBADRQC
/* */
[ERR_REMAP (EBADRQC)] = N_("Invalid request code"),
# if EBADRQC > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBADRQC
# endif
#endif
#ifdef EBADSLT
/* */
[ERR_REMAP (EBADSLT)] = N_("Invalid slot"),
# if EBADSLT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBADSLT
# endif
#endif
#if defined (EDEADLOCK) && EDEADLOCK != EDEADLK
/* */
[ERR_REMAP (EDEADLOCK)] = N_("File locking deadlock error"),
# if EDEADLOCK > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EDEADLOCK
# endif
#endif
#ifdef EBFONT
/* */
[ERR_REMAP (EBFONT)] = N_("Bad font file format"),
# if EBFONT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBFONT
# endif
#endif
#ifdef ENONET
/* */
[ERR_REMAP (ENONET)] = N_("Machine is not on the network"),
# if ENONET > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENONET
# endif
#endif
#ifdef ENOPKG
/* */
[ERR_REMAP (ENOPKG)] = N_("Package not installed"),
# if ENOPKG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOPKG
# endif
#endif
#ifdef EADV
/* */
[ERR_REMAP (EADV)] = N_("Advertise error"),
# if EADV > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EADV
# endif
#endif
#ifdef ESRMNT
/* */
[ERR_REMAP (ESRMNT)] = N_("Srmount error"),
# if ESRMNT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ESRMNT
# endif
#endif
#ifdef ECOMM
/* */
[ERR_REMAP (ECOMM)] = N_("Communication error on send"),
# if ECOMM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ECOMM
# endif
#endif
#ifdef EDOTDOT
/* */
[ERR_REMAP (EDOTDOT)] = N_("RFS specific error"),
# if EDOTDOT > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EDOTDOT
# endif
#endif
#ifdef ENOTUNIQ
/* */
[ERR_REMAP (ENOTUNIQ)] = N_("Name not unique on network"),
# if ENOTUNIQ > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTUNIQ
# endif
#endif
#ifdef EBADFD
/* */
[ERR_REMAP (EBADFD)] = N_("File descriptor in bad state"),
# if EBADFD > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EBADFD
# endif
#endif
#ifdef EREMCHG
/* */
[ERR_REMAP (EREMCHG)] = N_("Remote address changed"),
# if EREMCHG > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EREMCHG
# endif
#endif
#ifdef ELIBACC
/* */
[ERR_REMAP (ELIBACC)] = N_("Can not access a needed shared library"),
# if ELIBACC > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ELIBACC
# endif
#endif
#ifdef ELIBBAD
/* */
[ERR_REMAP (ELIBBAD)] = N_("Accessing a corrupted shared library"),
# if ELIBBAD > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ELIBBAD
# endif
#endif
#ifdef ELIBSCN
/* */
[ERR_REMAP (ELIBSCN)] = N_(".lib section in a.out corrupted"),
# if ELIBSCN > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ELIBSCN
# endif
#endif
#ifdef ELIBMAX
/* */
[ERR_REMAP (ELIBMAX)] = N_("Attempting to link in too many shared libraries"),
# if ELIBMAX > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ELIBMAX
# endif
#endif
#ifdef ELIBEXEC
/* */
[ERR_REMAP (ELIBEXEC)] = N_("Cannot exec a shared library directly"),
# if ELIBEXEC > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ELIBEXEC
# endif
#endif
#ifdef ESTRPIPE
/* */
[ERR_REMAP (ESTRPIPE)] = N_("Streams pipe error"),
# if ESTRPIPE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ESTRPIPE
# endif
#endif
#ifdef EUCLEAN
/* */
[ERR_REMAP (EUCLEAN)] = N_("Structure needs cleaning"),
# if EUCLEAN > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EUCLEAN
# endif
#endif
#ifdef ENOTNAM
/* */
[ERR_REMAP (ENOTNAM)] = N_("Not a XENIX named type file"),
# if ENOTNAM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTNAM
# endif
#endif
#ifdef ENAVAIL
/* */
[ERR_REMAP (ENAVAIL)] = N_("No XENIX semaphores available"),
# if ENAVAIL > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENAVAIL
# endif
#endif
#ifdef EISNAM
/* */
[ERR_REMAP (EISNAM)] = N_("Is a named type file"),
# if EISNAM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EISNAM
# endif
#endif
#ifdef EREMOTEIO
/* */
[ERR_REMAP (EREMOTEIO)] = N_("Remote I/O error"),
# if EREMOTEIO > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EREMOTEIO
# endif
#endif
#ifdef ENOMEDIUM
/* */
[ERR_REMAP (ENOMEDIUM)] = N_("No medium found"),
# if ENOMEDIUM > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOMEDIUM
# endif
#endif
#ifdef EMEDIUMTYPE
/* */
[ERR_REMAP (EMEDIUMTYPE)] = N_("Wrong medium type"),
# if EMEDIUMTYPE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EMEDIUMTYPE
# endif
#endif
#ifdef ENOKEY
/* */
[ERR_REMAP (ENOKEY)] = N_("Required key not available"),
# if ENOKEY > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOKEY
# endif
#endif
#ifdef EKEYEXPIRED
/* */
[ERR_REMAP (EKEYEXPIRED)] = N_("Key has expired"),
# if EKEYEXPIRED > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EKEYEXPIRED
# endif
#endif
#ifdef EKEYREVOKED
/* */
[ERR_REMAP (EKEYREVOKED)] = N_("Key has been revoked"),
# if EKEYREVOKED > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EKEYREVOKED
# endif
#endif
#ifdef EKEYREJECTED
/* */
[ERR_REMAP (EKEYREJECTED)] = N_("Key was rejected by service"),
# if EKEYREJECTED > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EKEYREJECTED
# endif
#endif
#ifdef EOWNERDEAD
/* */
[ERR_REMAP (EOWNERDEAD)] = N_("Owner died"),
# if EOWNERDEAD > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EOWNERDEAD
# endif
#endif
#ifdef ENOTRECOVERABLE
/* */
[ERR_REMAP (ENOTRECOVERABLE)] = N_("State not recoverable"),
# if ENOTRECOVERABLE > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ENOTRECOVERABLE
# endif
#endif
#ifdef ERFKILL
/* */
[ERR_REMAP (ERFKILL)] = N_("Operation not possible due to RF-kill"),
# if ERFKILL > ERR_MAX
# undef ERR_MAX
# define ERR_MAX ERFKILL
# endif
#endif
#ifdef EHWPOISON
/* */
[ERR_REMAP (EHWPOISON)] = N_("Memory page has hardware error"),
# if EHWPOISON > ERR_MAX
# undef ERR_MAX
# define ERR_MAX EHWPOISON
# endif
#endif
};
#define NERR \
(sizeof _sys_errlist_internal / sizeof _sys_errlist_internal [0])
const int _sys_nerr_internal = NERR;
#if !defined NOT_IN_libc && !defined ERRLIST_NO_COMPAT
# include <errlist-compat.c>
#endif
#ifdef EMIT_ERR_MAX
void dummy (void)
{ asm volatile (" @@@ %0 @@@ " : : "i" (ERR_REMAP (ERR_MAX))); }
#endif
| gpl-2.0 |
spinlockirqsave/linux_kernels | drivers/sound/opl3.c | 7 | 27717 | /*
* sound/opl3.c
*
* A low level driver for Yamaha YM3812 and OPL-3 -chips
*
*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*
*
* Changes
* Thomas Sailer ioctl code reworked (vmalloc/vfree removed)
* Alan Cox modularisation, fixed sound_mem allocs.
* Christoph Hellwig Adapted to module_init/module_exit
* Arnaldo C. de Melo get rid of check_region, use request_region for
* OPL4, release it on exit, some cleanups.
*
* Status
* Believed to work. Badly needs rewriting a bit to support multiple
* OPL3 devices.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/delay.h>
/*
* Major improvements to the FM handling 30AUG92 by Rob Hooft,
* hooft@chem.ruu.nl
*/
#include "sound_config.h"
#include "opl3.h"
#include "opl3_hw.h"
#define MAX_VOICE 18
#define OFFS_4OP 11
struct voice_info
{
unsigned char keyon_byte;
long bender;
long bender_range;
unsigned long orig_freq;
unsigned long current_freq;
int volume;
int mode;
int panning; /* 0xffff means not set */
};
typedef struct opl_devinfo
{
int base;
int left_io, right_io;
int nr_voice;
int lv_map[MAX_VOICE];
struct voice_info voc[MAX_VOICE];
struct voice_alloc_info *v_alloc;
struct channel_info *chn_info;
struct sbi_instrument i_map[SBFM_MAXINSTR];
struct sbi_instrument *act_i[MAX_VOICE];
struct synth_info fm_info;
int busy;
int model;
unsigned char cmask;
int is_opl4;
int *osp;
} opl_devinfo;
static struct opl_devinfo *devc = NULL;
static int detected_model;
static int store_instr(int instr_no, struct sbi_instrument *instr);
static void freq_to_fnum(int freq, int *block, int *fnum);
static void opl3_command(int io_addr, unsigned int addr, unsigned int val);
static int opl3_kill_note(int dev, int voice, int note, int velocity);
static void enter_4op_mode(void)
{
int i;
static int v4op[MAX_VOICE] = {
0, 1, 2, 9, 10, 11, 6, 7, 8, 15, 16, 17
};
devc->cmask = 0x3f; /* Connect all possible 4 OP voice operators */
opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, 0x3f);
for (i = 0; i < 3; i++)
pv_map[i].voice_mode = 4;
for (i = 3; i < 6; i++)
pv_map[i].voice_mode = 0;
for (i = 9; i < 12; i++)
pv_map[i].voice_mode = 4;
for (i = 12; i < 15; i++)
pv_map[i].voice_mode = 0;
for (i = 0; i < 12; i++)
devc->lv_map[i] = v4op[i];
devc->v_alloc->max_voice = devc->nr_voice = 12;
}
static int opl3_ioctl(int dev, unsigned int cmd, caddr_t arg)
{
struct sbi_instrument ins;
switch (cmd) {
case SNDCTL_FM_LOAD_INSTR:
printk(KERN_WARNING "Warning: Obsolete ioctl(SNDCTL_FM_LOAD_INSTR) used. Fix the program.\n");
if (copy_from_user(&ins, arg, sizeof(ins)))
return -EFAULT;
if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) {
printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel);
return -EINVAL;
}
return store_instr(ins.channel, &ins);
case SNDCTL_SYNTH_INFO:
devc->fm_info.nr_voices = (devc->nr_voice == 12) ? 6 : devc->nr_voice;
if (copy_to_user(arg, &devc->fm_info, sizeof(devc->fm_info)))
return -EFAULT;
return 0;
case SNDCTL_SYNTH_MEMAVL:
return 0x7fffffff;
case SNDCTL_FM_4OP_ENABLE:
if (devc->model == 2)
enter_4op_mode();
return 0;
default:
return -EINVAL;
}
}
int opl3_detect(int ioaddr, int *osp)
{
/*
* This function returns 1 if the FM chip is present at the given I/O port
* The detection algorithm plays with the timer built in the FM chip and
* looks for a change in the status register.
*
* Note! The timers of the FM chip are not connected to AdLib (and compatible)
* boards.
*
* Note2! The chip is initialized if detected.
*/
unsigned char stat1, signature;
int i;
if (devc != NULL)
{
printk(KERN_ERR "opl3: Only one OPL3 supported.\n");
return 0;
}
devc = (struct opl_devinfo *)kmalloc(sizeof(*devc), GFP_KERNEL);
if (devc == NULL)
{
printk(KERN_ERR "opl3: Can't allocate memory for the device control "
"structure \n ");
return 0;
}
memset(devc, 0, sizeof(*devc));
strcpy(devc->fm_info.name, "OPL2");
if (!request_region(ioaddr, 4, devc->fm_info.name)) {
printk(KERN_WARNING "opl3: I/O port 0x%x already in use\n", ioaddr);
goto cleanup_devc;
}
devc->osp = osp;
devc->base = ioaddr;
/* Reset timers 1 and 2 */
opl3_command(ioaddr, TIMER_CONTROL_REGISTER, TIMER1_MASK | TIMER2_MASK);
/* Reset the IRQ of the FM chip */
opl3_command(ioaddr, TIMER_CONTROL_REGISTER, IRQ_RESET);
signature = stat1 = inb(ioaddr); /* Status register */
if (signature != 0x00 && signature != 0x06 && signature != 0x02 &&
signature != 0x0f)
{
MDB(printk(KERN_INFO "OPL3 not detected %x\n", signature));
goto cleanup_region;
}
if (signature == 0x06) /* OPL2 */
{
detected_model = 2;
}
else if (signature == 0x00 || signature == 0x0f) /* OPL3 or OPL4 */
{
unsigned char tmp;
detected_model = 3;
/*
* Detect availability of OPL4 (_experimental_). Works probably
* only after a cold boot. In addition the OPL4 port
* of the chip may not be connected to the PC bus at all.
*/
opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, 0x00);
opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, OPL3_ENABLE | OPL4_ENABLE);
if ((tmp = inb(ioaddr)) == 0x02) /* Have a OPL4 */
{
detected_model = 4;
}
if (request_region(ioaddr - 8, 2, "OPL4")) /* OPL4 port was free */
{
int tmp;
outb((0x02), ioaddr - 8); /* Select OPL4 ID register */
udelay(10);
tmp = inb(ioaddr - 7); /* Read it */
udelay(10);
if (tmp == 0x20) /* OPL4 should return 0x20 here */
{
detected_model = 4;
outb((0xF8), ioaddr - 8); /* Select OPL4 FM mixer control */
udelay(10);
outb((0x1B), ioaddr - 7); /* Write value */
udelay(10);
}
else
{ /* release OPL4 port */
release_region(ioaddr - 8, 2);
detected_model = 3;
}
}
opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, 0);
}
for (i = 0; i < 9; i++)
opl3_command(ioaddr, KEYON_BLOCK + i, 0); /*
* Note off
*/
opl3_command(ioaddr, TEST_REGISTER, ENABLE_WAVE_SELECT);
opl3_command(ioaddr, PERCOSSION_REGISTER, 0x00); /*
* Melodic mode.
*/
return 1;
cleanup_region:
release_region(ioaddr, 4);
cleanup_devc:
kfree(devc);
devc = NULL;
return 0;
}
static int opl3_kill_note (int devno, int voice, int note, int velocity)
{
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return 0;
devc->v_alloc->map[voice] = 0;
map = &pv_map[devc->lv_map[voice]];
DEB(printk("Kill note %d\n", voice));
if (map->voice_mode == 0)
return 0;
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, devc->voc[voice].keyon_byte & ~0x20);
devc->voc[voice].keyon_byte = 0;
devc->voc[voice].bender = 0;
devc->voc[voice].volume = 64;
devc->voc[voice].panning = 0xffff; /* Not set */
devc->voc[voice].bender_range = 200;
devc->voc[voice].orig_freq = 0;
devc->voc[voice].current_freq = 0;
devc->voc[voice].mode = 0;
return 0;
}
#define HIHAT 0
#define CYMBAL 1
#define TOMTOM 2
#define SNARE 3
#define BDRUM 4
#define UNDEFINED TOMTOM
#define DEFAULT TOMTOM
static int store_instr(int instr_no, struct sbi_instrument *instr)
{
if (instr->key != FM_PATCH && (instr->key != OPL3_PATCH || devc->model != 2))
printk(KERN_WARNING "FM warning: Invalid patch format field (key) 0x%x\n", instr->key);
memcpy((char *) &(devc->i_map[instr_no]), (char *) instr, sizeof(*instr));
return 0;
}
static int opl3_set_instr (int dev, int voice, int instr_no)
{
if (voice < 0 || voice >= devc->nr_voice)
return 0;
if (instr_no < 0 || instr_no >= SBFM_MAXINSTR)
instr_no = 0; /* Acoustic piano (usually) */
devc->act_i[voice] = &devc->i_map[instr_no];
return 0;
}
/*
* The next table looks magical, but it certainly is not. Its values have
* been calculated as table[i]=8*log(i/64)/log(2) with an obvious exception
* for i=0. This log-table converts a linear volume-scaling (0..127) to a
* logarithmic scaling as present in the FM-synthesizer chips. so : Volume
* 64 = 0 db = relative volume 0 and: Volume 32 = -6 db = relative
* volume -8 it was implemented as a table because it is only 128 bytes and
* it saves a lot of log() calculations. (RH)
*/
static char fm_volume_table[128] =
{
-64, -48, -40, -35, -32, -29, -27, -26,
-24, -23, -21, -20, -19, -18, -18, -17,
-16, -15, -15, -14, -13, -13, -12, -12,
-11, -11, -10, -10, -10, -9, -9, -8,
-8, -8, -7, -7, -7, -6, -6, -6,
-5, -5, -5, -5, -4, -4, -4, -4,
-3, -3, -3, -3, -2, -2, -2, -2,
-2, -1, -1, -1, -1, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1,
1, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 4,
4, 4, 4, 4, 4, 4, 4, 5,
5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6,
6, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 8, 8, 8, 8, 8
};
static void calc_vol(unsigned char *regbyte, int volume, int main_vol)
{
int level = (~*regbyte & 0x3f);
if (main_vol > 127)
main_vol = 127;
volume = (volume * main_vol) / 127;
if (level)
level += fm_volume_table[volume];
if (level > 0x3f)
level = 0x3f;
if (level < 0)
level = 0;
*regbyte = (*regbyte & 0xc0) | (~level & 0x3f);
}
static void set_voice_volume(int voice, int volume, int main_vol)
{
unsigned char vol1, vol2, vol3, vol4;
struct sbi_instrument *instr;
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return;
map = &pv_map[devc->lv_map[voice]];
instr = devc->act_i[voice];
if (!instr)
instr = &devc->i_map[0];
if (instr->channel < 0)
return;
if (devc->voc[voice].mode == 0)
return;
if (devc->voc[voice].mode == 2)
{
vol1 = instr->operators[2];
vol2 = instr->operators[3];
if ((instr->operators[10] & 0x01))
{
calc_vol(&vol1, volume, main_vol);
calc_vol(&vol2, volume, main_vol);
}
else
{
calc_vol(&vol2, volume, main_vol);
}
opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], vol1);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], vol2);
}
else
{ /*
* 4 OP voice
*/
int connection;
vol1 = instr->operators[2];
vol2 = instr->operators[3];
vol3 = instr->operators[OFFS_4OP + 2];
vol4 = instr->operators[OFFS_4OP + 3];
/*
* The connection method for 4 OP devc->voc is defined by the rightmost
* bits at the offsets 10 and 10+OFFS_4OP
*/
connection = ((instr->operators[10] & 0x01) << 1) | (instr->operators[10 + OFFS_4OP] & 0x01);
switch (connection)
{
case 0:
calc_vol(&vol4, volume, main_vol);
break;
case 1:
calc_vol(&vol2, volume, main_vol);
calc_vol(&vol4, volume, main_vol);
break;
case 2:
calc_vol(&vol1, volume, main_vol);
calc_vol(&vol4, volume, main_vol);
break;
case 3:
calc_vol(&vol1, volume, main_vol);
calc_vol(&vol3, volume, main_vol);
calc_vol(&vol4, volume, main_vol);
break;
default:
;
}
opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], vol1);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], vol2);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[2], vol3);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[3], vol4);
}
}
static int opl3_start_note (int dev, int voice, int note, int volume)
{
unsigned char data, fpc;
int block, fnum, freq, voice_mode, pan;
struct sbi_instrument *instr;
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return 0;
map = &pv_map[devc->lv_map[voice]];
pan = devc->voc[voice].panning;
if (map->voice_mode == 0)
return 0;
if (note == 255) /*
* Just change the volume
*/
{
set_voice_volume(voice, volume, devc->voc[voice].volume);
return 0;
}
/*
* Kill previous note before playing
*/
opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], 0xff); /*
* Carrier
* volume to
* min
*/
opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], 0xff); /*
* Modulator
* volume to
*/
if (map->voice_mode == 4)
{
opl3_command(map->ioaddr, KSL_LEVEL + map->op[2], 0xff);
opl3_command(map->ioaddr, KSL_LEVEL + map->op[3], 0xff);
}
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, 0x00); /*
* Note
* off
*/
instr = devc->act_i[voice];
if (!instr)
instr = &devc->i_map[0];
if (instr->channel < 0)
{
printk(KERN_WARNING "opl3: Initializing voice %d with undefined instrument\n", voice);
return 0;
}
if (map->voice_mode == 2 && instr->key == OPL3_PATCH)
return 0; /*
* Cannot play
*/
voice_mode = map->voice_mode;
if (voice_mode == 4)
{
int voice_shift;
voice_shift = (map->ioaddr == devc->left_io) ? 0 : 3;
voice_shift += map->voice_num;
if (instr->key != OPL3_PATCH) /*
* Just 2 OP patch
*/
{
voice_mode = 2;
devc->cmask &= ~(1 << voice_shift);
}
else
{
devc->cmask |= (1 << voice_shift);
}
opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, devc->cmask);
}
/*
* Set Sound Characteristics
*/
opl3_command(map->ioaddr, AM_VIB + map->op[0], instr->operators[0]);
opl3_command(map->ioaddr, AM_VIB + map->op[1], instr->operators[1]);
/*
* Set Attack/Decay
*/
opl3_command(map->ioaddr, ATTACK_DECAY + map->op[0], instr->operators[4]);
opl3_command(map->ioaddr, ATTACK_DECAY + map->op[1], instr->operators[5]);
/*
* Set Sustain/Release
*/
opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[0], instr->operators[6]);
opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[1], instr->operators[7]);
/*
* Set Wave Select
*/
opl3_command(map->ioaddr, WAVE_SELECT + map->op[0], instr->operators[8]);
opl3_command(map->ioaddr, WAVE_SELECT + map->op[1], instr->operators[9]);
/*
* Set Feedback/Connection
*/
fpc = instr->operators[10];
if (pan != 0xffff)
{
fpc &= ~STEREO_BITS;
if (pan < -64)
fpc |= VOICE_TO_LEFT;
else
if (pan > 64)
fpc |= VOICE_TO_RIGHT;
else
fpc |= (VOICE_TO_LEFT | VOICE_TO_RIGHT);
}
if (!(fpc & 0x30))
fpc |= 0x30; /*
* Ensure that at least one chn is enabled
*/
opl3_command(map->ioaddr, FEEDBACK_CONNECTION + map->voice_num, fpc);
/*
* If the voice is a 4 OP one, initialize the operators 3 and 4 also
*/
if (voice_mode == 4)
{
/*
* Set Sound Characteristics
*/
opl3_command(map->ioaddr, AM_VIB + map->op[2], instr->operators[OFFS_4OP + 0]);
opl3_command(map->ioaddr, AM_VIB + map->op[3], instr->operators[OFFS_4OP + 1]);
/*
* Set Attack/Decay
*/
opl3_command(map->ioaddr, ATTACK_DECAY + map->op[2], instr->operators[OFFS_4OP + 4]);
opl3_command(map->ioaddr, ATTACK_DECAY + map->op[3], instr->operators[OFFS_4OP + 5]);
/*
* Set Sustain/Release
*/
opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[2], instr->operators[OFFS_4OP + 6]);
opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[3], instr->operators[OFFS_4OP + 7]);
/*
* Set Wave Select
*/
opl3_command(map->ioaddr, WAVE_SELECT + map->op[2], instr->operators[OFFS_4OP + 8]);
opl3_command(map->ioaddr, WAVE_SELECT + map->op[3], instr->operators[OFFS_4OP + 9]);
/*
* Set Feedback/Connection
*/
fpc = instr->operators[OFFS_4OP + 10];
if (!(fpc & 0x30))
fpc |= 0x30; /*
* Ensure that at least one chn is enabled
*/
opl3_command(map->ioaddr, FEEDBACK_CONNECTION + map->voice_num + 3, fpc);
}
devc->voc[voice].mode = voice_mode;
set_voice_volume(voice, volume, devc->voc[voice].volume);
freq = devc->voc[voice].orig_freq = note_to_freq(note) / 1000;
/*
* Since the pitch bender may have been set before playing the note, we
* have to calculate the bending now.
*/
freq = compute_finetune(devc->voc[voice].orig_freq, devc->voc[voice].bender, devc->voc[voice].bender_range, 0);
devc->voc[voice].current_freq = freq;
freq_to_fnum(freq, &block, &fnum);
/*
* Play note
*/
data = fnum & 0xff; /*
* Least significant bits of fnumber
*/
opl3_command(map->ioaddr, FNUM_LOW + map->voice_num, data);
data = 0x20 | ((block & 0x7) << 2) | ((fnum >> 8) & 0x3);
devc->voc[voice].keyon_byte = data;
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, data);
if (voice_mode == 4)
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num + 3, data);
return 0;
}
static void freq_to_fnum (int freq, int *block, int *fnum)
{
int f, octave;
/*
* Converts the note frequency to block and fnum values for the FM chip
*/
/*
* First try to compute the block -value (octave) where the note belongs
*/
f = freq;
octave = 5;
if (f == 0)
octave = 0;
else if (f < 261)
{
while (f < 261)
{
octave--;
f <<= 1;
}
}
else if (f > 493)
{
while (f > 493)
{
octave++;
f >>= 1;
}
}
if (octave > 7)
octave = 7;
*fnum = freq * (1 << (20 - octave)) / 49716;
*block = octave;
}
static void opl3_command (int io_addr, unsigned int addr, unsigned int val)
{
int i;
/*
* The original 2-OP synth requires a quite long delay after writing to a
* register. The OPL-3 survives with just two INBs
*/
outb(((unsigned char) (addr & 0xff)), io_addr);
if (devc->model != 2)
udelay(10);
else
for (i = 0; i < 2; i++)
inb(io_addr);
outb(((unsigned char) (val & 0xff)), io_addr + 1);
if (devc->model != 2)
udelay(30);
else
for (i = 0; i < 2; i++)
inb(io_addr);
}
static void opl3_reset(int devno)
{
int i;
for (i = 0; i < 18; i++)
devc->lv_map[i] = i;
for (i = 0; i < devc->nr_voice; i++)
{
opl3_command(pv_map[devc->lv_map[i]].ioaddr,
KSL_LEVEL + pv_map[devc->lv_map[i]].op[0], 0xff);
opl3_command(pv_map[devc->lv_map[i]].ioaddr,
KSL_LEVEL + pv_map[devc->lv_map[i]].op[1], 0xff);
if (pv_map[devc->lv_map[i]].voice_mode == 4)
{
opl3_command(pv_map[devc->lv_map[i]].ioaddr,
KSL_LEVEL + pv_map[devc->lv_map[i]].op[2], 0xff);
opl3_command(pv_map[devc->lv_map[i]].ioaddr,
KSL_LEVEL + pv_map[devc->lv_map[i]].op[3], 0xff);
}
opl3_kill_note(devno, i, 0, 64);
}
if (devc->model == 2)
{
devc->v_alloc->max_voice = devc->nr_voice = 18;
for (i = 0; i < 18; i++)
pv_map[i].voice_mode = 2;
}
}
static int opl3_open(int dev, int mode)
{
int i;
if (devc->busy)
return -EBUSY;
devc->busy = 1;
devc->v_alloc->max_voice = devc->nr_voice = (devc->model == 2) ? 18 : 9;
devc->v_alloc->timestamp = 0;
for (i = 0; i < 18; i++)
{
devc->v_alloc->map[i] = 0;
devc->v_alloc->alloc_times[i] = 0;
}
devc->cmask = 0x00; /*
* Just 2 OP mode
*/
if (devc->model == 2)
opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, devc->cmask);
return 0;
}
static void opl3_close(int dev)
{
devc->busy = 0;
devc->v_alloc->max_voice = devc->nr_voice = (devc->model == 2) ? 18 : 9;
devc->fm_info.nr_drums = 0;
devc->fm_info.perc_mode = 0;
opl3_reset(dev);
}
static void opl3_hw_control(int dev, unsigned char *event)
{
}
static int opl3_load_patch(int dev, int format, const char *addr,
int offs, int count, int pmgr_flag)
{
struct sbi_instrument ins;
if (count <sizeof(ins))
{
printk(KERN_WARNING "FM Error: Patch record too short\n");
return -EINVAL;
}
if(copy_from_user(&((char *) &ins)[offs], &(addr)[offs], sizeof(ins) - offs))
return -EFAULT;
if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR)
{
printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel);
return -EINVAL;
}
ins.key = format;
return store_instr(ins.channel, &ins);
}
static void opl3_panning(int dev, int voice, int value)
{
devc->voc[voice].panning = value;
}
static void opl3_volume_method(int dev, int mode)
{
}
#define SET_VIBRATO(cell) { \
tmp = instr->operators[(cell-1)+(((cell-1)/2)*OFFS_4OP)]; \
if (pressure > 110) \
tmp |= 0x40; /* Vibrato on */ \
opl3_command (map->ioaddr, AM_VIB + map->op[cell-1], tmp);}
static void opl3_aftertouch(int dev, int voice, int pressure)
{
int tmp;
struct sbi_instrument *instr;
struct physical_voice_info *map;
if (voice < 0 || voice >= devc->nr_voice)
return;
map = &pv_map[devc->lv_map[voice]];
DEB(printk("Aftertouch %d\n", voice));
if (map->voice_mode == 0)
return;
/*
* Adjust the amount of vibrato depending the pressure
*/
instr = devc->act_i[voice];
if (!instr)
instr = &devc->i_map[0];
if (devc->voc[voice].mode == 4)
{
int connection = ((instr->operators[10] & 0x01) << 1) | (instr->operators[10 + OFFS_4OP] & 0x01);
switch (connection)
{
case 0:
SET_VIBRATO(4);
break;
case 1:
SET_VIBRATO(2);
SET_VIBRATO(4);
break;
case 2:
SET_VIBRATO(1);
SET_VIBRATO(4);
break;
case 3:
SET_VIBRATO(1);
SET_VIBRATO(3);
SET_VIBRATO(4);
break;
}
/*
* Not implemented yet
*/
}
else
{
SET_VIBRATO(1);
if ((instr->operators[10] & 0x01)) /*
* Additive synthesis
*/
SET_VIBRATO(2);
}
}
#undef SET_VIBRATO
static void bend_pitch(int dev, int voice, int value)
{
unsigned char data;
int block, fnum, freq;
struct physical_voice_info *map;
map = &pv_map[devc->lv_map[voice]];
if (map->voice_mode == 0)
return;
devc->voc[voice].bender = value;
if (!value)
return;
if (!(devc->voc[voice].keyon_byte & 0x20))
return; /*
* Not keyed on
*/
freq = compute_finetune(devc->voc[voice].orig_freq, devc->voc[voice].bender, devc->voc[voice].bender_range, 0);
devc->voc[voice].current_freq = freq;
freq_to_fnum(freq, &block, &fnum);
data = fnum & 0xff; /*
* Least significant bits of fnumber
*/
opl3_command(map->ioaddr, FNUM_LOW + map->voice_num, data);
data = 0x20 | ((block & 0x7) << 2) | ((fnum >> 8) & 0x3);
devc->voc[voice].keyon_byte = data;
opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, data);
}
static void opl3_controller (int dev, int voice, int ctrl_num, int value)
{
if (voice < 0 || voice >= devc->nr_voice)
return;
switch (ctrl_num)
{
case CTRL_PITCH_BENDER:
bend_pitch(dev, voice, value);
break;
case CTRL_PITCH_BENDER_RANGE:
devc->voc[voice].bender_range = value;
break;
case CTL_MAIN_VOLUME:
devc->voc[voice].volume = value / 128;
break;
case CTL_PAN:
devc->voc[voice].panning = (value * 2) - 128;
break;
}
}
static void opl3_bender(int dev, int voice, int value)
{
if (voice < 0 || voice >= devc->nr_voice)
return;
bend_pitch(dev, voice, value - 8192);
}
static int opl3_alloc_voice(int dev, int chn, int note, struct voice_alloc_info *alloc)
{
int i, p, best, first, avail, best_time = 0x7fffffff;
struct sbi_instrument *instr;
int is4op;
int instr_no;
if (chn < 0 || chn > 15)
instr_no = 0;
else
instr_no = devc->chn_info[chn].pgm_num;
instr = &devc->i_map[instr_no];
if (instr->channel < 0 || /* Instrument not loaded */
devc->nr_voice != 12) /* Not in 4 OP mode */
is4op = 0;
else if (devc->nr_voice == 12) /* 4 OP mode */
is4op = (instr->key == OPL3_PATCH);
else
is4op = 0;
if (is4op)
{
first = p = 0;
avail = 6;
}
else
{
if (devc->nr_voice == 12) /* 4 OP mode. Use the '2 OP only' operators first */
first = p = 6;
else
first = p = 0;
avail = devc->nr_voice;
}
/*
* Now try to find a free voice
*/
best = first;
for (i = 0; i < avail; i++)
{
if (alloc->map[p] == 0)
{
return p;
}
if (alloc->alloc_times[p] < best_time) /* Find oldest playing note */
{
best_time = alloc->alloc_times[p];
best = p;
}
p = (p + 1) % avail;
}
/*
* Insert some kind of priority mechanism here.
*/
if (best < 0)
best = 0;
if (best > devc->nr_voice)
best -= devc->nr_voice;
return best; /* All devc->voc in use. Select the first one. */
}
static void opl3_setup_voice(int dev, int voice, int chn)
{
struct channel_info *info =
&synth_devs[dev]->chn_info[chn];
opl3_set_instr(dev, voice, info->pgm_num);
devc->voc[voice].bender = 0;
devc->voc[voice].bender_range = info->bender_range;
devc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME];
devc->voc[voice].panning = (info->controllers[CTL_PAN] * 2) - 128;
}
static struct synth_operations opl3_operations =
{
owner: THIS_MODULE,
id: "OPL",
info: NULL,
midi_dev: 0,
synth_type: SYNTH_TYPE_FM,
synth_subtype: FM_TYPE_ADLIB,
open: opl3_open,
close: opl3_close,
ioctl: opl3_ioctl,
kill_note: opl3_kill_note,
start_note: opl3_start_note,
set_instr: opl3_set_instr,
reset: opl3_reset,
hw_control: opl3_hw_control,
load_patch: opl3_load_patch,
aftertouch: opl3_aftertouch,
controller: opl3_controller,
panning: opl3_panning,
volume_method: opl3_volume_method,
bender: opl3_bender,
alloc_voice: opl3_alloc_voice,
setup_voice: opl3_setup_voice
};
int opl3_init(int ioaddr, int *osp, struct module *owner)
{
int i;
int me;
if (devc == NULL)
{
printk(KERN_ERR "opl3: Device control structure not initialized.\n");
return -1;
}
if ((me = sound_alloc_synthdev()) == -1)
{
printk(KERN_WARNING "opl3: Too many synthesizers\n");
return -1;
}
devc->nr_voice = 9;
devc->fm_info.device = 0;
devc->fm_info.synth_type = SYNTH_TYPE_FM;
devc->fm_info.synth_subtype = FM_TYPE_ADLIB;
devc->fm_info.perc_mode = 0;
devc->fm_info.nr_voices = 9;
devc->fm_info.nr_drums = 0;
devc->fm_info.instr_bank_size = SBFM_MAXINSTR;
devc->fm_info.capabilities = 0;
devc->left_io = ioaddr;
devc->right_io = ioaddr + 2;
if (detected_model <= 2)
devc->model = 1;
else
{
devc->model = 2;
if (detected_model == 4)
devc->is_opl4 = 1;
}
opl3_operations.info = &devc->fm_info;
synth_devs[me] = &opl3_operations;
if (owner)
synth_devs[me]->owner = owner;
sequencer_init();
devc->v_alloc = &opl3_operations.alloc;
devc->chn_info = &opl3_operations.chn_info[0];
if (devc->model == 2)
{
if (devc->is_opl4)
strcpy(devc->fm_info.name, "Yamaha OPL4/OPL3 FM");
else
strcpy(devc->fm_info.name, "Yamaha OPL3");
devc->v_alloc->max_voice = devc->nr_voice = 18;
devc->fm_info.nr_drums = 0;
devc->fm_info.synth_subtype = FM_TYPE_OPL3;
devc->fm_info.capabilities |= SYNTH_CAP_OPL3;
for (i = 0; i < 18; i++)
{
if (pv_map[i].ioaddr == USE_LEFT)
pv_map[i].ioaddr = devc->left_io;
else
pv_map[i].ioaddr = devc->right_io;
}
opl3_command(devc->right_io, OPL3_MODE_REGISTER, OPL3_ENABLE);
opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, 0x00);
}
else
{
strcpy(devc->fm_info.name, "Yamaha OPL2");
devc->v_alloc->max_voice = devc->nr_voice = 9;
devc->fm_info.nr_drums = 0;
for (i = 0; i < 18; i++)
pv_map[i].ioaddr = devc->left_io;
};
conf_printf2(devc->fm_info.name, ioaddr, 0, -1, -1);
for (i = 0; i < SBFM_MAXINSTR; i++)
devc->i_map[i].channel = -1;
return me;
}
EXPORT_SYMBOL(opl3_init);
EXPORT_SYMBOL(opl3_detect);
static int me;
static int io = -1;
MODULE_PARM(io, "i");
static int __init init_opl3 (void)
{
printk(KERN_INFO "YM3812 and OPL-3 driver Copyright (C) by Hannu Savolainen, Rob Hooft 1993-1996\n");
if (io != -1) /* User loading pure OPL3 module */
{
if (!opl3_detect(io, NULL))
{
return -ENODEV;
}
me = opl3_init(io, NULL, THIS_MODULE);
}
return 0;
}
static void __exit cleanup_opl3(void)
{
if (devc && io != -1)
{
if (devc->base) {
release_region(devc->base,4);
if (devc->is_opl4)
release_region(devc->base - 8, 2);
}
kfree(devc);
devc = NULL;
sound_unload_synthdev(me);
}
}
module_init(init_opl3);
module_exit(cleanup_opl3);
#ifndef MODULE
static int __init setup_opl3(char *str)
{
/* io */
int ints[2];
str = get_options(str, ARRAY_SIZE(ints), ints);
io = ints[1];
return 1;
}
__setup("opl3=", setup_opl3);
#endif
| gpl-2.0 |
opensourcerouting/frr | ospfd/ospf_errors.c | 7 | 8293 | /*
* OSPF-specific error messages.
* Copyright (C) 2018 Cumulus Networks, Inc.
* Chirag Shah
*
* 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; either version 2 of the License, or (at your option)
* any later version.
*
* 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; see the file COPYING; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <zebra.h>
#include "lib/ferr.h"
#include "ospf_errors.h"
/* clang-format off */
static struct log_ref ferr_ospf_warn[] = {
{
.code = EC_OSPF_SET_METRIC_PLUS,
.title = "OSPF does not support `set metric +rtt/-rtt`",
.description = "This implementation of OSPF does not currently support `set metric +rtt/-rtt`",
.suggestion = "Do not use this particular set command for an ospf route-map",
},
{
.code = EC_OSPF_MD5,
.title = "OSPF has noticed a MD5 issue",
.description = "Something has gone wrong with the calculation of the MD5 data",
.suggestion = "Ensure your key is correct, gather log data from this side as well as peer and open an Issue",
},
{
.code = EC_OSPF_PACKET,
.title = "OSPF has detected packet information mismatch",
.description = "OSPF has detected that packet information received is incorrect",
.suggestion = "Ensure interface configuration is correct, gather log files from here and the peer and open an Issue",
},
{
.code = EC_OSPF_LARGE_LSA,
.title = "OSPF has determined that a LSA packet will be too large",
.description = "OSPF has received data that is causing it to recalculate how large packets should be and has discovered that the packet size needed would be too large and we will need to fragment packets",
.suggestion = "Further divide up your network with areas",
},
{
.code = EC_OSPF_LSA_UNEXPECTED,
.title = "OSPF has received a LSA-type that it was not expecting",
.description = "OSPF has received a LSA-type that it was not expecting during processing",
.suggestion = "Gather log data from this machine and it's peer and open an Issue",
},
{
.code = EC_OSPF_LSA,
.title = "OSPF has discovered inconsistent internal state for a LSA",
.description = "During handling of a LSA, OSPF has discovered that the LSA's internal state is inconsistent",
.suggestion = "Gather log data and open an Issue",
},
{
.code = EC_OSPF_OPAQUE_REGISTRATION,
.title = "OSPF has failed to properly register Opaque Handler",
.description = "During initialization OSPF has detected a failure to install an opaque handler",
.suggestion = "Gather log data and open an Issue",
},
{
.code = EC_OSPF_TE_UNEXPECTED,
.title = "OSPF has received TE information that it was not expecting",
.description = "OSPF has received TE information that it was not expecting during normal processing of data",
.suggestion = "Gather log data from this machine and it's peer and open an Issue",
},
{
.code = EC_OSPF_LSA_INSTALL_FAILURE,
.title = "OSPF was unable to save the LSA into it's database",
.description = "During processing of a new lsa and attempting to save the lsa into the OSPF database, this process failed.",
.suggestion = "Gather log data from this machine and open an Issue",
},
{
.code = EC_OSPF_LSA_NULL,
.title = "OSPF has received a NULL lsa pointer",
.description = "When processing a LSA update we have found and noticed an internal error where we are passing around a NULL pointer",
.suggestion = "Gather data from this machine and it's peer and open an Issue",
},
{
.code = EC_OSPF_EXT_LSA_UNEXPECTED,
.title = "OSPF has received EXT information that leaves it in an unexpected state",
.description = "While processing EXT LSA information, OSPF has noticed that the internal state of OSPF has gotten inconsistent",
.suggestion = "Gather data from this machine and it's peer and open an Issue",
},
{
.code = EC_OSPF_LSA_MISSING,
.title = "OSPF attempted to look up a LSA and it was not found",
.description = "During processing of new LSA information, we attempted to look up an old LSA and it was not found",
.suggestion = "Gather data from this machine and open an Issue",
},
{
.code = EC_OSPF_PTP_NEIGHBOR,
.title = "OSPF has detected more than 1 neighbor on a P2P interface",
.description = "If you configure a ospf interface as P2P we should not detect more than one neighbor on the interface",
.suggestion = "Fix your config",
},
{
.code = EC_OSPF_LSA_SIZE,
.title = "OSPF has detected an invalid LSA size",
.description = "OSPF has detected a state where we are attempting to grow a LSA but the LSA has reached it's maximum size",
.suggestion = "Gather data and open an Issue",
},
{
.code = END_FERR,
}
};
static struct log_ref ferr_ospf_err[] = {
{
.code = EC_OSPF_PKT_PROCESS,
.title = "Failure to process a packet",
.description = "OSPF attempted to process a received packet but could not",
.suggestion = "Most likely a bug. If the problem persists, report the problem for troubleshooting"
},
{
.code = EC_OSPF_ROUTER_LSA_MISMATCH,
.title = "Failure to process Router LSA",
.description = "OSPF attempted to process a Router LSA but Advertising ID mismatch with link id",
.suggestion = "Check OSPF network config for any config issue, If the problem persists, report the problem for troubleshooting"
},
{
.code = EC_OSPF_DOMAIN_CORRUPT,
.title = "OSPF Domain Corruption",
.description = "OSPF attempted to process a Router LSA but Advertising ID mismatch with link id",
.suggestion = "Check OSPF network Database for corrupted LSA, If the problem persists, shutdown OSPF domain and report the problem for troubleshooting"
},
{
.code = EC_OSPF_INIT_FAIL,
.title = "OSPF Initialization failure",
.description = "OSPF failed to initialized OSPF default insance",
.suggestion = "Ensure there is adequate memory on the device. If the problem persists, report the problem for troubleshooting"
},
{
.code = EC_OSPF_SR_INVALID_DB,
.title = "OSPF SR Invalid DB",
.description = "OSPF Segment Routing Database is invalid",
.suggestion = "Most likely a bug. If the problem persists, report the problem for troubleshooting"
},
{
.code = EC_OSPF_SR_NODE_CREATE,
.title = "OSPF SR hash node creation failed",
.description = "OSPF Segment Routing node creation failed",
.suggestion = "Most likely a bug. If the problem persists, report the problem for troubleshooting"
},
{
.code = EC_OSPF_SR_INVALID_LSA_ID,
.title = "OSPF SR Invalid LSA ID",
.description = "OSPF Segment Routing invalid lsa id",
.suggestion = "Restart OSPF instance, If the problem persists, report the problem for troubleshooting"
},
{
.code = EC_OSPF_SR_SID_OVERFLOW,
.title = "OSPF SR Segment-ID overflow",
.description = "OSPF Segment Routing ID index or label exceed Global or Local Block Range",
.suggestion = "Restart OSPF instance, If the problem persists, report the problem for troubleshooting"
},
{
.code = EC_OSPF_INVALID_ALGORITHM,
.title = "OSPF SR Invalid Algorithm",
.description = "OSPF Segment Routing invalid Algorithm",
.suggestion = "Most likely a bug. If the problem persists, report the problem for troubleshooting"
},
{
.code = EC_OSPF_FSM_INVALID_STATE,
.title = "OSPF FSM invalid state detected",
.description = "OSPF has attempted to change states when it should not be able to",
.suggestion = "Gather log files and open an issue",
},
{
.code = EC_OSPF_LARGE_HELLO,
.title = "OSPF Encountered a Large Hello",
.description = "OSPF attempted to send a Hello larger than MTU but did not",
.suggestion = "Too many neighbors configured on a single interface. Suggestion is to decrease the number of neighbors on a single interface/subnet"
},
{
.code = END_FERR,
}
};
/* clang-format on */
void ospf_error_init(void)
{
log_ref_add(ferr_ospf_warn);
log_ref_add(ferr_ospf_err);
}
| gpl-2.0 |
hentel/openwrt | target/linux/ar71xx/files/drivers/mtd/wrt160nl_part.c | 7 | 5158 | /*
* Copyright (C) 2009 Christian Daniel <cd@maintech.de>
* Copyright (C) 2009 Gabor Juhos <juhosg@openwrt.org>
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* TRX flash partition table.
* Based on ar7 map by Felix Fietkau <nbd@openwrt.org>
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
struct cybertan_header {
char magic[4];
u8 res1[4];
char fw_date[3];
char fw_ver[3];
char id[4];
char hw_ver;
char unused;
u8 flags[2];
u8 res2[10];
};
#define TRX_PARTS 6
#define TRX_MAGIC 0x30524448
#define TRX_MAX_OFFSET 3
struct trx_header {
uint32_t magic; /* "HDR0" */
uint32_t len; /* Length of file including header */
uint32_t crc32; /* 32-bit CRC from flag_version to end of file */
uint32_t flag_version; /* 0:15 flags, 16:31 version */
uint32_t offsets[TRX_MAX_OFFSET]; /* Offsets of partitions from start of header */
};
#define IH_MAGIC 0x27051956 /* Image Magic Number */
#define IH_NMLEN 32 /* Image Name Length */
struct uimage_header {
uint32_t ih_magic; /* Image Header Magic Number */
uint32_t ih_hcrc; /* Image Header CRC Checksum */
uint32_t ih_time; /* Image Creation Timestamp */
uint32_t ih_size; /* Image Data Size */
uint32_t ih_load; /* Data» Load Address */
uint32_t ih_ep; /* Entry Point Address */
uint32_t ih_dcrc; /* Image Data CRC Checksum */
uint8_t ih_os; /* Operating System */
uint8_t ih_arch; /* CPU architecture */
uint8_t ih_type; /* Image Type */
uint8_t ih_comp; /* Compression Type */
uint8_t ih_name[IH_NMLEN]; /* Image Name */
};
struct wrt160nl_header {
struct cybertan_header cybertan;
struct trx_header trx;
struct uimage_header uimage;
} __attribute__ ((packed));
static struct mtd_partition trx_parts[TRX_PARTS];
static int wrt160nl_parse_partitions(struct mtd_info *master,
struct mtd_partition **pparts,
unsigned long origin)
{
struct wrt160nl_header *header;
struct trx_header *theader;
struct uimage_header *uheader;
size_t retlen;
unsigned int kernel_len;
int ret;
header = vmalloc(sizeof(*header));
if (!header) {
return -ENOMEM;
goto out;
}
ret = master->read(master, 4 * master->erasesize, sizeof(*header),
&retlen, (void *) header);
if (ret)
goto free_hdr;
if (retlen != sizeof(*header)) {
ret = -EIO;
goto free_hdr;
}
if (strncmp(header->cybertan.magic, "NL16", 4) != 0) {
printk(KERN_NOTICE "%s: no WRT160NL signature found\n",
master->name);
goto free_hdr;
}
theader = &header->trx;
if (le32_to_cpu(theader->magic) != TRX_MAGIC) {
printk(KERN_NOTICE "%s: no TRX header found\n", master->name);
goto free_hdr;
}
uheader = &header->uimage;
if (uheader->ih_magic != IH_MAGIC) {
printk(KERN_NOTICE "%s: no uImage found\n", master->name);
goto free_hdr;
}
kernel_len = uheader->ih_size / master->erasesize;
if (uheader->ih_size % master->erasesize)
kernel_len++;
kernel_len++;
kernel_len *= master->erasesize;
trx_parts[0].name = "u-boot";
trx_parts[0].offset = 0;
trx_parts[0].size = 4 * master->erasesize;
trx_parts[0].mask_flags = MTD_WRITEABLE;
trx_parts[1].name = "kernel";
trx_parts[1].offset = trx_parts[0].offset + trx_parts[0].size;
trx_parts[1].size = kernel_len;
trx_parts[1].mask_flags = 0;
trx_parts[2].name = "rootfs";
trx_parts[2].offset = trx_parts[1].offset + trx_parts[1].size;
trx_parts[2].size = master->size - 6 * master->erasesize - trx_parts[1].size;
trx_parts[2].mask_flags = 0;
trx_parts[3].name = "nvram";
trx_parts[3].offset = master->size - 2 * master->erasesize;
trx_parts[3].size = master->erasesize;
trx_parts[3].mask_flags = MTD_WRITEABLE;
trx_parts[4].name = "art";
trx_parts[4].offset = master->size - master->erasesize;
trx_parts[4].size = master->erasesize;
trx_parts[4].mask_flags = MTD_WRITEABLE;
trx_parts[5].name = "firmware";
trx_parts[5].offset = 4 * master->erasesize;
trx_parts[5].size = master->size - 6 * master->erasesize;
trx_parts[5].mask_flags = 0;
*pparts = trx_parts;
ret = TRX_PARTS;
free_hdr:
vfree(header);
out:
return ret;
}
static struct mtd_part_parser wrt160nl_parser = {
.owner = THIS_MODULE,
.parse_fn = wrt160nl_parse_partitions,
.name = "wrt160nl",
};
static int __init wrt160nl_parser_init(void)
{
return register_mtd_parser(&wrt160nl_parser);
}
module_init(wrt160nl_parser_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Christian Daniel <cd@maintech.de>");
| gpl-2.0 |
PeterPetrik/QGIS | src/app/devtools/querylogger/qgsqueryloggerpanelwidget.cpp | 7 | 6600 | /***************************************************************************
qgsqueryloggerpanelwidget.cpp
-------------------------
begin : October 2021
copyright : (C) 2021 by Nyall Dawson
email : nyall dot dawson at gmail dot com
***************************************************************************
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsapplication.h"
#include "qgsguiutils.h"
#include "qgsjsonutils.h"
#include "qgsqueryloggerpanelwidget.h"
#include "qgsdatabasequeryloggernode.h"
#include "qgsappquerylogger.h"
#include "qgssettings.h"
#include <QFileDialog>
#include <QFontDatabase>
#include <QMenu>
#include <QMessageBox>
#include <QScrollBar>
#include <QToolButton>
#include <QCheckBox>
#include <QTextStream>
#include <nlohmann/json.hpp>
//
// QgsDatabaseQueryLoggerTreeView
//
QgsDatabaseQueryLoggerTreeView::QgsDatabaseQueryLoggerTreeView( QgsAppQueryLogger *logger, QWidget *parent )
: QTreeView( parent )
, mLogger( logger )
{
connect( this, &QTreeView::expanded, this, &QgsDatabaseQueryLoggerTreeView::itemExpanded );
setFont( QFontDatabase::systemFont( QFontDatabase::FixedFont ) );
mProxyModel = new QgsDatabaseQueryLoggerProxyModel( mLogger, this );
setModel( mProxyModel );
setContextMenuPolicy( Qt::CustomContextMenu );
connect( this, &QgsDatabaseQueryLoggerTreeView::customContextMenuRequested, this, &QgsDatabaseQueryLoggerTreeView::contextMenu );
connect( verticalScrollBar(), &QAbstractSlider::sliderMoved, this, [this]( int value )
{
if ( value == verticalScrollBar()->maximum() )
mAutoScroll = true;
else
mAutoScroll = false;
} );
connect( mLogger, &QAbstractItemModel::rowsInserted, this, [ = ]
{
if ( mLogger->rowCount() > ( QgsAppQueryLogger::MAX_LOGGED_REQUESTS * 1.2 ) ) // 20 % more as buffer
{
// never trim expanded nodes
const int toTrim = mLogger->rowCount() - QgsAppQueryLogger::MAX_LOGGED_REQUESTS;
int trimmed = 0;
QList< int > rowsToTrim;
rowsToTrim.reserve( toTrim );
for ( int i = 0; i < mLogger->rowCount(); ++i )
{
const QModelIndex proxyIndex = mProxyModel->mapFromSource( mLogger->index( i, 0 ) );
if ( !proxyIndex.isValid() || !isExpanded( proxyIndex ) )
{
rowsToTrim << i;
trimmed++;
}
if ( trimmed == toTrim )
break;
}
mLogger->removeRequestRows( rowsToTrim );
}
if ( mAutoScroll )
scrollToBottom();
} );
mMenu = new QMenu( this );
}
void QgsDatabaseQueryLoggerTreeView::setFilterString( const QString &string )
{
mProxyModel->setFilterString( string );
}
void QgsDatabaseQueryLoggerTreeView::itemExpanded( const QModelIndex &index )
{
// if the item is a QgsNetworkLoggerRequestGroup item, open all children (show ALL info of it)
// we want to scroll to last request
// only expand all children on QgsNetworkLoggerRequestGroup nodes (which don't have a valid parent!)
if ( !index.parent().isValid() )
expandChildren( index );
// make ALL request information visible by scrolling view to it
scrollTo( index );
}
void QgsDatabaseQueryLoggerTreeView::contextMenu( QPoint point )
{
const QModelIndex viewModelIndex = indexAt( point );
const QModelIndex modelIndex = mProxyModel->mapToSource( viewModelIndex );
if ( modelIndex.isValid() )
{
mMenu->clear();
const QList< QAction * > actions = mLogger->actions( modelIndex, mMenu );
mMenu->addActions( actions );
if ( !mMenu->actions().empty() )
{
mMenu->exec( viewport()->mapToGlobal( point ) );
}
}
}
void QgsDatabaseQueryLoggerTreeView::expandChildren( const QModelIndex &index )
{
if ( !index.isValid() )
return;
const int count = model()->rowCount( index );
for ( int i = 0; i < count; ++i )
{
const QModelIndex childIndex = model()->index( i, 0, index );
expandChildren( childIndex );
}
if ( !isExpanded( index ) )
expand( index );
}
//
// QgsDatabaseQueryLoggerPanelWidget
//
QgsDatabaseQueryLoggerPanelWidget::QgsDatabaseQueryLoggerPanelWidget( QgsAppQueryLogger *logger, QWidget *parent )
: QgsDevToolWidget( parent )
, mLogger( logger )
{
setupUi( this );
mTreeView = new QgsDatabaseQueryLoggerTreeView( mLogger );
verticalLayout->addWidget( mTreeView );
mToolbar->setIconSize( QgsGuiUtils::iconSize( true ) );
mFilterLineEdit->setShowClearButton( true );
mFilterLineEdit->setShowSearchIcon( true );
mFilterLineEdit->setPlaceholderText( tr( "Filter queries" ) );
mActionRecord->setChecked( QgsApplication::databaseQueryLog()->enabled() );
connect( mFilterLineEdit, &QgsFilterLineEdit::textChanged, mTreeView, &QgsDatabaseQueryLoggerTreeView::setFilterString );
connect( mActionClear, &QAction::triggered, mLogger, &QgsAppQueryLogger::clear );
connect( mActionRecord, &QAction::toggled, this, [ = ]( bool enabled )
{
QgsSettings().setValue( QStringLiteral( "logDatabaseQueries" ), enabled, QgsSettings::App );
QgsApplication::databaseQueryLog()->setEnabled( enabled );
} );
connect( mActionSaveLog, &QAction::triggered, this, [ = ]()
{
if ( QMessageBox::warning( this, tr( "Save Database Query Log" ),
tr( "Security warning: query logs may contain sensitive data including usernames or passwords. Treat this log as confidential and be careful who you share it with. Continue?" ), QMessageBox::Yes | QMessageBox::No ) == QMessageBox::No )
return;
const QString saveFilePath = QFileDialog::getSaveFileName( this, tr( "Save Query Log" ), QDir::homePath(), tr( "Log files" ) + " (*.json)" );
if ( saveFilePath.isEmpty() )
{
return;
}
QFile exportFile( saveFilePath );
if ( !exportFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
{
return;
}
QTextStream fout( &exportFile );
const QVariant value = mLogger->rootGroup()->toVariant();
const QString json = QString::fromStdString( QgsJsonUtils::jsonFromVariant( value ).dump( 2 ) );
fout << json;
} );
}
| gpl-2.0 |
embecosm/binutils-gdb | gas/as.c | 7 | 36703 | /* as.c - GAS main program.
Copyright 1987-2014 Free Software Foundation, Inc.
This file is part of GAS, the GNU Assembler.
GAS 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; either version 3, or (at your option)
any later version.
GAS 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 GAS; see the file COPYING. If not, write to the Free
Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
02110-1301, USA. */
/* Main program for AS; a 32-bit assembler of GNU.
Understands command arguments.
Has a few routines that don't fit in other modules because they
are shared.
bugs
: initialisers
Since no-one else says they will support them in future: I
don't support them now. */
#define COMMON
#include "as.h"
#include "subsegs.h"
#include "output-file.h"
#include "sb.h"
#include "macro.h"
#include "dwarf2dbg.h"
#include "dw2gencfi.h"
#include "bfdver.h"
#ifdef HAVE_ITBL_CPU
#include "itbl-ops.h"
#else
#define itbl_init()
#endif
#ifdef HAVE_SBRK
#ifdef NEED_DECLARATION_SBRK
extern void *sbrk ();
#endif
#endif
#ifdef USING_CGEN
/* Perform any cgen specific initialisation for gas. */
extern void gas_cgen_begin (void);
#endif
/* We build a list of defsyms as we read the options, and then define
them after we have initialized everything. */
struct defsym_list
{
struct defsym_list *next;
char *name;
valueT value;
};
/* True if a listing is wanted. */
int listing;
/* Type of debugging to generate. */
enum debug_info_type debug_type = DEBUG_UNSPECIFIED;
int use_gnu_debug_info_extensions = 0;
#ifndef MD_DEBUG_FORMAT_SELECTOR
#define MD_DEBUG_FORMAT_SELECTOR NULL
#endif
static enum debug_info_type (*md_debug_format_selector) (int *) = MD_DEBUG_FORMAT_SELECTOR;
/* Maximum level of macro nesting. */
int max_macro_nest = 100;
/* argv[0] */
static char * myname;
/* The default obstack chunk size. If we set this to zero, the
obstack code will use whatever will fit in a 4096 byte block. */
int chunksize = 0;
/* To monitor memory allocation more effectively, make this non-zero.
Then the chunk sizes for gas and bfd will be reduced. */
int debug_memory = 0;
/* Enable verbose mode. */
int verbose = 0;
/* Keep the output file. */
int keep_it = 0;
segT reg_section;
segT expr_section;
segT text_section;
segT data_section;
segT bss_section;
/* Name of listing file. */
static char *listing_filename = NULL;
static struct defsym_list *defsyms;
#ifdef HAVE_ITBL_CPU
/* Keep a record of the itbl files we read in. */
struct itbl_file_list
{
struct itbl_file_list *next;
char *name;
};
static struct itbl_file_list *itbl_files;
#endif
static long start_time;
#ifdef HAVE_SBRK
char *start_sbrk;
#endif
static int flag_macro_alternate;
#ifdef USE_EMULATIONS
#define EMULATION_ENVIRON "AS_EMULATION"
extern struct emulation mipsbelf, mipslelf, mipself;
extern struct emulation i386coff, i386elf, i386aout;
extern struct emulation crisaout, criself;
static struct emulation *const emulations[] = { EMULATIONS };
static const int n_emulations = sizeof (emulations) / sizeof (emulations[0]);
static void
select_emulation_mode (int argc, char **argv)
{
int i;
char *p, *em = 0;
for (i = 1; i < argc; i++)
if (!strncmp ("--em", argv[i], 4))
break;
if (i == argc)
goto do_default;
p = strchr (argv[i], '=');
if (p)
p++;
else
p = argv[i + 1];
if (!p || !*p)
as_fatal (_("missing emulation mode name"));
em = p;
do_default:
if (em == 0)
em = getenv (EMULATION_ENVIRON);
if (em == 0)
em = DEFAULT_EMULATION;
if (em)
{
for (i = 0; i < n_emulations; i++)
if (!strcmp (emulations[i]->name, em))
break;
if (i == n_emulations)
as_fatal (_("unrecognized emulation name `%s'"), em);
this_emulation = emulations[i];
}
else
this_emulation = emulations[0];
this_emulation->init ();
}
const char *
default_emul_bfd_name (void)
{
abort ();
return NULL;
}
void
common_emul_init (void)
{
this_format = this_emulation->format;
if (this_emulation->leading_underscore == 2)
this_emulation->leading_underscore = this_format->dfl_leading_underscore;
if (this_emulation->default_endian != 2)
target_big_endian = this_emulation->default_endian;
if (this_emulation->fake_label_name == 0)
{
if (this_emulation->leading_underscore)
this_emulation->fake_label_name = "L0\001";
else
/* What other parameters should we test? */
this_emulation->fake_label_name = ".L0\001";
}
}
#endif
void
print_version_id (void)
{
static int printed;
if (printed)
return;
printed = 1;
fprintf (stderr, _("GNU assembler version %s (%s) using BFD version %s\n"),
VERSION, TARGET_ALIAS, BFD_VERSION_STRING);
}
static void
show_usage (FILE * stream)
{
fprintf (stream, _("Usage: %s [option...] [asmfile...]\n"), myname);
fprintf (stream, _("\
Options:\n\
-a[sub-option...] turn on listings\n\
Sub-options [default hls]:\n\
c omit false conditionals\n\
d omit debugging directives\n\
g include general info\n\
h include high-level source\n\
l include assembly\n\
m include macro expansions\n\
n omit forms processing\n\
s include symbols\n\
=FILE list to FILE (must be last sub-option)\n"));
fprintf (stream, _("\
--alternate initially turn on alternate macro syntax\n"));
#ifdef HAVE_ZLIB_H
fprintf (stream, _("\
--compress-debug-sections\n\
compress DWARF debug sections using zlib\n"));
fprintf (stream, _("\
--nocompress-debug-sections\n\
don't compress DWARF debug sections\n"));
#endif /* HAVE_ZLIB_H */
fprintf (stream, _("\
-D produce assembler debugging messages\n"));
fprintf (stream, _("\
--debug-prefix-map OLD=NEW\n\
map OLD to NEW in debug information\n"));
fprintf (stream, _("\
--defsym SYM=VAL define symbol SYM to given value\n"));
#ifdef USE_EMULATIONS
{
int i;
char *def_em;
fprintf (stream, "\
--em=[");
for (i = 0; i < n_emulations - 1; i++)
fprintf (stream, "%s | ", emulations[i]->name);
fprintf (stream, "%s]\n", emulations[i]->name);
def_em = getenv (EMULATION_ENVIRON);
if (!def_em)
def_em = DEFAULT_EMULATION;
fprintf (stream, _("\
emulate output (default %s)\n"), def_em);
}
#endif
#if defined OBJ_ELF || defined OBJ_MAYBE_ELF
fprintf (stream, _("\
--execstack require executable stack for this object\n"));
fprintf (stream, _("\
--noexecstack don't require executable stack for this object\n"));
fprintf (stream, _("\
--size-check=[error|warning]\n\
ELF .size directive check (default --size-check=error)\n"));
#endif
fprintf (stream, _("\
-f skip whitespace and comment preprocessing\n"));
fprintf (stream, _("\
-g --gen-debug generate debugging information\n"));
fprintf (stream, _("\
--gstabs generate STABS debugging information\n"));
fprintf (stream, _("\
--gstabs+ generate STABS debug info with GNU extensions\n"));
fprintf (stream, _("\
--gdwarf-2 generate DWARF2 debugging information\n"));
fprintf (stream, _("\
--gdwarf-sections generate per-function section names for DWARF line information\n"));
fprintf (stream, _("\
--hash-size=<value> set the hash table size close to <value>\n"));
fprintf (stream, _("\
--help show this message and exit\n"));
fprintf (stream, _("\
--target-help show target specific options\n"));
fprintf (stream, _("\
-I DIR add DIR to search list for .include directives\n"));
fprintf (stream, _("\
-J don't warn about signed overflow\n"));
fprintf (stream, _("\
-K warn when differences altered for long displacements\n"));
fprintf (stream, _("\
-L,--keep-locals keep local symbols (e.g. starting with `L')\n"));
fprintf (stream, _("\
-M,--mri assemble in MRI compatibility mode\n"));
fprintf (stream, _("\
--MD FILE write dependency information in FILE (default none)\n"));
fprintf (stream, _("\
-nocpp ignored\n"));
fprintf (stream, _("\
-o OBJFILE name the object-file output OBJFILE (default a.out)\n"));
fprintf (stream, _("\
-R fold data section into text section\n"));
fprintf (stream, _("\
--reduce-memory-overheads \n\
prefer smaller memory use at the cost of longer\n\
assembly times\n"));
fprintf (stream, _("\
--statistics print various measured statistics from execution\n"));
fprintf (stream, _("\
--strip-local-absolute strip local absolute symbols\n"));
fprintf (stream, _("\
--traditional-format Use same format as native assembler when possible\n"));
fprintf (stream, _("\
--version print assembler version number and exit\n"));
fprintf (stream, _("\
-W --no-warn suppress warnings\n"));
fprintf (stream, _("\
--warn don't suppress warnings\n"));
fprintf (stream, _("\
--fatal-warnings treat warnings as errors\n"));
#ifdef HAVE_ITBL_CPU
fprintf (stream, _("\
--itbl INSTTBL extend instruction set to include instructions\n\
matching the specifications defined in file INSTTBL\n"));
#endif
fprintf (stream, _("\
-w ignored\n"));
fprintf (stream, _("\
-X ignored\n"));
fprintf (stream, _("\
-Z generate object file even after errors\n"));
fprintf (stream, _("\
--listing-lhs-width set the width in words of the output data column of\n\
the listing\n"));
fprintf (stream, _("\
--listing-lhs-width2 set the width in words of the continuation lines\n\
of the output data column; ignored if smaller than\n\
the width of the first line\n"));
fprintf (stream, _("\
--listing-rhs-width set the max width in characters of the lines from\n\
the source file\n"));
fprintf (stream, _("\
--listing-cont-lines set the maximum number of continuation lines used\n\
for the output data column of the listing\n"));
fprintf (stream, _("\
@FILE read options from FILE\n"));
md_show_usage (stream);
fputc ('\n', stream);
if (REPORT_BUGS_TO[0] && stream == stdout)
fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
}
/* Since it is easy to do here we interpret the special arg "-"
to mean "use stdin" and we set that argv[] pointing to "".
After we have munged argv[], the only things left are source file
name(s) and ""(s) denoting stdin. These file names are used
(perhaps more than once) later.
check for new machine-dep cmdline options in
md_parse_option definitions in config/tc-*.c. */
static void
parse_args (int * pargc, char *** pargv)
{
int old_argc;
int new_argc;
char ** old_argv;
char ** new_argv;
/* Starting the short option string with '-' is for programs that
expect options and other ARGV-elements in any order and that care about
the ordering of the two. We describe each non-option ARGV-element
as if it were the argument of an option with character code 1. */
char *shortopts;
extern const char *md_shortopts;
static const char std_shortopts[] =
{
'-', 'J',
#ifndef WORKING_DOT_WORD
/* -K is not meaningful if .word is not being hacked. */
'K',
#endif
'L', 'M', 'R', 'W', 'Z', 'a', ':', ':', 'D', 'f', 'g', ':',':', 'I', ':', 'o', ':',
#ifndef VMS
/* -v takes an argument on VMS, so we don't make it a generic
option. */
'v',
#endif
'w', 'X',
#ifdef HAVE_ITBL_CPU
/* New option for extending instruction set (see also --itbl below). */
't', ':',
#endif
'\0'
};
struct option *longopts;
extern struct option md_longopts[];
extern size_t md_longopts_size;
/* Codes used for the long options with no short synonyms. */
enum option_values
{
OPTION_HELP = OPTION_STD_BASE,
OPTION_NOCPP,
OPTION_STATISTICS,
OPTION_VERSION,
OPTION_DUMPCONFIG,
OPTION_VERBOSE,
OPTION_EMULATION,
OPTION_DEBUG_PREFIX_MAP,
OPTION_DEFSYM,
OPTION_LISTING_LHS_WIDTH,
OPTION_LISTING_LHS_WIDTH2,
OPTION_LISTING_RHS_WIDTH,
OPTION_LISTING_CONT_LINES,
OPTION_DEPFILE,
OPTION_GSTABS,
OPTION_GSTABS_PLUS,
OPTION_GDWARF2,
OPTION_GDWARF_SECTIONS,
OPTION_STRIP_LOCAL_ABSOLUTE,
OPTION_TRADITIONAL_FORMAT,
OPTION_WARN,
OPTION_TARGET_HELP,
OPTION_EXECSTACK,
OPTION_NOEXECSTACK,
OPTION_SIZE_CHECK,
OPTION_ALTERNATE,
OPTION_AL,
OPTION_HASH_TABLE_SIZE,
OPTION_REDUCE_MEMORY_OVERHEADS,
OPTION_WARN_FATAL,
OPTION_COMPRESS_DEBUG,
OPTION_NOCOMPRESS_DEBUG
/* When you add options here, check that they do
not collide with OPTION_MD_BASE. See as.h. */
};
static const struct option std_longopts[] =
{
/* Note: commas are placed at the start of the line rather than
the end of the preceding line so that it is simpler to
selectively add and remove lines from this list. */
{"alternate", no_argument, NULL, OPTION_ALTERNATE}
/* The entry for "a" is here to prevent getopt_long_only() from
considering that -a is an abbreviation for --alternate. This is
necessary because -a=<FILE> is a valid switch but getopt would
normally reject it since --alternate does not take an argument. */
,{"a", optional_argument, NULL, 'a'}
/* Handle -al=<FILE>. */
,{"al", optional_argument, NULL, OPTION_AL}
,{"compress-debug-sections", no_argument, NULL, OPTION_COMPRESS_DEBUG}
,{"nocompress-debug-sections", no_argument, NULL, OPTION_NOCOMPRESS_DEBUG}
,{"debug-prefix-map", required_argument, NULL, OPTION_DEBUG_PREFIX_MAP}
,{"defsym", required_argument, NULL, OPTION_DEFSYM}
,{"dump-config", no_argument, NULL, OPTION_DUMPCONFIG}
,{"emulation", required_argument, NULL, OPTION_EMULATION}
#if defined OBJ_ELF || defined OBJ_MAYBE_ELF
,{"execstack", no_argument, NULL, OPTION_EXECSTACK}
,{"noexecstack", no_argument, NULL, OPTION_NOEXECSTACK}
,{"size-check", required_argument, NULL, OPTION_SIZE_CHECK}
#endif
,{"fatal-warnings", no_argument, NULL, OPTION_WARN_FATAL}
,{"gdwarf-2", no_argument, NULL, OPTION_GDWARF2}
/* GCC uses --gdwarf-2 but GAS uses to use --gdwarf2,
so we keep it here for backwards compatibility. */
,{"gdwarf2", no_argument, NULL, OPTION_GDWARF2}
,{"gdwarf-sections", no_argument, NULL, OPTION_GDWARF_SECTIONS}
,{"gen-debug", no_argument, NULL, 'g'}
,{"gstabs", no_argument, NULL, OPTION_GSTABS}
,{"gstabs+", no_argument, NULL, OPTION_GSTABS_PLUS}
,{"hash-size", required_argument, NULL, OPTION_HASH_TABLE_SIZE}
,{"help", no_argument, NULL, OPTION_HELP}
#ifdef HAVE_ITBL_CPU
/* New option for extending instruction set (see also -t above).
The "-t file" or "--itbl file" option extends the basic set of
valid instructions by reading "file", a text file containing a
list of instruction formats. The additional opcodes and their
formats are added to the built-in set of instructions, and
mnemonics for new registers may also be defined. */
,{"itbl", required_argument, NULL, 't'}
#endif
/* getopt allows abbreviations, so we do this to stop it from
treating -k as an abbreviation for --keep-locals. Some
ports use -k to enable PIC assembly. */
,{"keep-locals", no_argument, NULL, 'L'}
,{"keep-locals", no_argument, NULL, 'L'}
,{"listing-lhs-width", required_argument, NULL, OPTION_LISTING_LHS_WIDTH}
,{"listing-lhs-width2", required_argument, NULL, OPTION_LISTING_LHS_WIDTH2}
,{"listing-rhs-width", required_argument, NULL, OPTION_LISTING_RHS_WIDTH}
,{"listing-cont-lines", required_argument, NULL, OPTION_LISTING_CONT_LINES}
,{"MD", required_argument, NULL, OPTION_DEPFILE}
,{"mri", no_argument, NULL, 'M'}
,{"nocpp", no_argument, NULL, OPTION_NOCPP}
,{"no-warn", no_argument, NULL, 'W'}
,{"reduce-memory-overheads", no_argument, NULL, OPTION_REDUCE_MEMORY_OVERHEADS}
,{"statistics", no_argument, NULL, OPTION_STATISTICS}
,{"strip-local-absolute", no_argument, NULL, OPTION_STRIP_LOCAL_ABSOLUTE}
,{"version", no_argument, NULL, OPTION_VERSION}
,{"verbose", no_argument, NULL, OPTION_VERBOSE}
,{"target-help", no_argument, NULL, OPTION_TARGET_HELP}
,{"traditional-format", no_argument, NULL, OPTION_TRADITIONAL_FORMAT}
,{"warn", no_argument, NULL, OPTION_WARN}
};
/* Construct the option lists from the standard list and the target
dependent list. Include space for an extra NULL option and
always NULL terminate. */
shortopts = concat (std_shortopts, md_shortopts, (char *) NULL);
longopts = (struct option *) xmalloc (sizeof (std_longopts)
+ md_longopts_size + sizeof (struct option));
memcpy (longopts, std_longopts, sizeof (std_longopts));
memcpy (((char *) longopts) + sizeof (std_longopts), md_longopts, md_longopts_size);
memset (((char *) longopts) + sizeof (std_longopts) + md_longopts_size,
0, sizeof (struct option));
/* Make a local copy of the old argv. */
old_argc = *pargc;
old_argv = *pargv;
/* Initialize a new argv that contains no options. */
new_argv = (char **) xmalloc (sizeof (char *) * (old_argc + 1));
new_argv[0] = old_argv[0];
new_argc = 1;
new_argv[new_argc] = NULL;
while (1)
{
/* getopt_long_only is like getopt_long, but '-' as well as '--' can
indicate a long option. */
int longind;
int optc = getopt_long_only (old_argc, old_argv, shortopts, longopts,
&longind);
if (optc == -1)
break;
switch (optc)
{
default:
/* md_parse_option should return 1 if it recognizes optc,
0 if not. */
if (md_parse_option (optc, optarg) != 0)
break;
/* `-v' isn't included in the general short_opts list, so check for
it explicitly here before deciding we've gotten a bad argument. */
if (optc == 'v')
{
#ifdef VMS
/* Telling getopt to treat -v's value as optional can result
in it picking up a following filename argument here. The
VMS code in md_parse_option can return 0 in that case,
but it has no way of pushing the filename argument back. */
if (optarg && *optarg)
new_argv[new_argc++] = optarg, new_argv[new_argc] = NULL;
else
#else
case 'v':
#endif
case OPTION_VERBOSE:
print_version_id ();
verbose = 1;
break;
}
else
as_bad (_("unrecognized option -%c%s"), optc, optarg ? optarg : "");
/* Fall through. */
case '?':
exit (EXIT_FAILURE);
case 1: /* File name. */
if (!strcmp (optarg, "-"))
optarg = "";
new_argv[new_argc++] = optarg;
new_argv[new_argc] = NULL;
break;
case OPTION_TARGET_HELP:
md_show_usage (stdout);
exit (EXIT_SUCCESS);
case OPTION_HELP:
show_usage (stdout);
exit (EXIT_SUCCESS);
case OPTION_NOCPP:
break;
case OPTION_STATISTICS:
flag_print_statistics = 1;
break;
case OPTION_STRIP_LOCAL_ABSOLUTE:
flag_strip_local_absolute = 1;
break;
case OPTION_TRADITIONAL_FORMAT:
flag_traditional_format = 1;
break;
case OPTION_VERSION:
/* This output is intended to follow the GNU standards document. */
printf (_("GNU assembler %s\n"), BFD_VERSION_STRING);
printf (_("Copyright 2014 Free Software Foundation, Inc.\n"));
printf (_("\
This program is free software; you may redistribute it under the terms of\n\
the GNU General Public License version 3 or later.\n\
This program has absolutely no warranty.\n"));
printf (_("This assembler was configured for a target of `%s'.\n"),
TARGET_ALIAS);
exit (EXIT_SUCCESS);
case OPTION_EMULATION:
#ifdef USE_EMULATIONS
if (strcmp (optarg, this_emulation->name))
as_fatal (_("multiple emulation names specified"));
#else
as_fatal (_("emulations not handled in this configuration"));
#endif
break;
case OPTION_DUMPCONFIG:
fprintf (stderr, _("alias = %s\n"), TARGET_ALIAS);
fprintf (stderr, _("canonical = %s\n"), TARGET_CANONICAL);
fprintf (stderr, _("cpu-type = %s\n"), TARGET_CPU);
#ifdef TARGET_OBJ_FORMAT
fprintf (stderr, _("format = %s\n"), TARGET_OBJ_FORMAT);
#endif
#ifdef TARGET_FORMAT
fprintf (stderr, _("bfd-target = %s\n"), TARGET_FORMAT);
#endif
exit (EXIT_SUCCESS);
case OPTION_COMPRESS_DEBUG:
#ifdef HAVE_ZLIB_H
flag_compress_debug = 1;
#else
as_warn (_("cannot compress debug sections (zlib not installed)"));
#endif /* HAVE_ZLIB_H */
break;
case OPTION_NOCOMPRESS_DEBUG:
flag_compress_debug = 0;
break;
case OPTION_DEBUG_PREFIX_MAP:
add_debug_prefix_map (optarg);
break;
case OPTION_DEFSYM:
{
char *s;
valueT i;
struct defsym_list *n;
for (s = optarg; *s != '\0' && *s != '='; s++)
;
if (*s == '\0')
as_fatal (_("bad defsym; format is --defsym name=value"));
*s++ = '\0';
i = bfd_scan_vma (s, (const char **) NULL, 0);
n = (struct defsym_list *) xmalloc (sizeof *n);
n->next = defsyms;
n->name = optarg;
n->value = i;
defsyms = n;
}
break;
#ifdef HAVE_ITBL_CPU
case 't':
{
/* optarg is the name of the file containing the instruction
formats, opcodes, register names, etc. */
struct itbl_file_list *n;
if (optarg == NULL)
{
as_warn (_("no file name following -t option"));
break;
}
n = xmalloc (sizeof * n);
n->next = itbl_files;
n->name = optarg;
itbl_files = n;
/* Parse the file and add the new instructions to our internal
table. If multiple instruction tables are specified, the
information from this table gets appended onto the existing
internal table. */
itbl_files->name = xstrdup (optarg);
if (itbl_parse (itbl_files->name) != 0)
as_fatal (_("failed to read instruction table %s\n"),
itbl_files->name);
}
break;
#endif
case OPTION_DEPFILE:
start_dependencies (optarg);
break;
case 'g':
/* Some backends, eg Alpha and Mips, use the -g switch for their
own purposes. So we check here for an explicit -g and allow
the backend to decide if it wants to process it. */
if ( old_argv[optind - 1][1] == 'g'
&& md_parse_option (optc, optarg))
continue;
if (md_debug_format_selector)
debug_type = md_debug_format_selector (& use_gnu_debug_info_extensions);
else if (IS_ELF)
debug_type = DEBUG_DWARF2;
else
debug_type = DEBUG_STABS;
break;
case OPTION_GSTABS_PLUS:
use_gnu_debug_info_extensions = 1;
/* Fall through. */
case OPTION_GSTABS:
debug_type = DEBUG_STABS;
break;
case OPTION_GDWARF2:
debug_type = DEBUG_DWARF2;
break;
case OPTION_GDWARF_SECTIONS:
flag_dwarf_sections = TRUE;
break;
case 'J':
flag_signed_overflow_ok = 1;
break;
#ifndef WORKING_DOT_WORD
case 'K':
flag_warn_displacement = 1;
break;
#endif
case 'L':
flag_keep_locals = 1;
break;
case OPTION_LISTING_LHS_WIDTH:
listing_lhs_width = atoi (optarg);
if (listing_lhs_width_second < listing_lhs_width)
listing_lhs_width_second = listing_lhs_width;
break;
case OPTION_LISTING_LHS_WIDTH2:
{
int tmp = atoi (optarg);
if (tmp > listing_lhs_width)
listing_lhs_width_second = tmp;
}
break;
case OPTION_LISTING_RHS_WIDTH:
listing_rhs_width = atoi (optarg);
break;
case OPTION_LISTING_CONT_LINES:
listing_lhs_cont_lines = atoi (optarg);
break;
case 'M':
flag_mri = 1;
#ifdef TC_M68K
flag_m68k_mri = 1;
#endif
break;
case 'R':
flag_readonly_data_in_text = 1;
break;
case 'W':
flag_no_warnings = 1;
break;
case OPTION_WARN:
flag_no_warnings = 0;
flag_fatal_warnings = 0;
break;
case OPTION_WARN_FATAL:
flag_no_warnings = 0;
flag_fatal_warnings = 1;
break;
#if defined OBJ_ELF || defined OBJ_MAYBE_ELF
case OPTION_EXECSTACK:
flag_execstack = 1;
flag_noexecstack = 0;
break;
case OPTION_NOEXECSTACK:
flag_noexecstack = 1;
flag_execstack = 0;
break;
case OPTION_SIZE_CHECK:
if (strcasecmp (optarg, "error") == 0)
flag_size_check = size_check_error;
else if (strcasecmp (optarg, "warning") == 0)
flag_size_check = size_check_warning;
else
as_fatal (_("Invalid --size-check= option: `%s'"), optarg);
break;
#endif
case 'Z':
flag_always_generate_output = 1;
break;
case OPTION_AL:
listing |= LISTING_LISTING;
if (optarg)
listing_filename = xstrdup (optarg);
break;
case OPTION_ALTERNATE:
optarg = old_argv [optind - 1];
while (* optarg == '-')
optarg ++;
if (strcmp (optarg, "alternate") == 0)
{
flag_macro_alternate = 1;
break;
}
optarg ++;
/* Fall through. */
case 'a':
if (optarg)
{
if (optarg != old_argv[optind] && optarg[-1] == '=')
--optarg;
if (md_parse_option (optc, optarg) != 0)
break;
while (*optarg)
{
switch (*optarg)
{
case 'c':
listing |= LISTING_NOCOND;
break;
case 'd':
listing |= LISTING_NODEBUG;
break;
case 'g':
listing |= LISTING_GENERAL;
break;
case 'h':
listing |= LISTING_HLL;
break;
case 'l':
listing |= LISTING_LISTING;
break;
case 'm':
listing |= LISTING_MACEXP;
break;
case 'n':
listing |= LISTING_NOFORM;
break;
case 's':
listing |= LISTING_SYMBOLS;
break;
case '=':
listing_filename = xstrdup (optarg + 1);
optarg += strlen (listing_filename);
break;
default:
as_fatal (_("invalid listing option `%c'"), *optarg);
break;
}
optarg++;
}
}
if (!listing)
listing = LISTING_DEFAULT;
break;
case 'D':
/* DEBUG is implemented: it debugs different
things from other people's assemblers. */
flag_debug = 1;
break;
case 'f':
flag_no_comments = 1;
break;
case 'I':
{ /* Include file directory. */
char *temp = xstrdup (optarg);
add_include_dir (temp);
break;
}
case 'o':
out_file_name = xstrdup (optarg);
break;
case 'w':
break;
case 'X':
/* -X means treat warnings as errors. */
break;
case OPTION_REDUCE_MEMORY_OVERHEADS:
/* The only change we make at the moment is to reduce
the size of the hash tables that we use. */
set_gas_hash_table_size (4051);
break;
case OPTION_HASH_TABLE_SIZE:
{
unsigned long new_size;
new_size = strtoul (optarg, NULL, 0);
if (new_size)
set_gas_hash_table_size (new_size);
else
as_fatal (_("--hash-size needs a numeric argument"));
break;
}
}
}
free (shortopts);
free (longopts);
*pargc = new_argc;
*pargv = new_argv;
#ifdef md_after_parse_args
md_after_parse_args ();
#endif
}
static void
dump_statistics (void)
{
#ifdef HAVE_SBRK
char *lim = (char *) sbrk (0);
#endif
long run_time = get_run_time () - start_time;
fprintf (stderr, _("%s: total time in assembly: %ld.%06ld\n"),
myname, run_time / 1000000, run_time % 1000000);
#ifdef HAVE_SBRK
fprintf (stderr, _("%s: data size %ld\n"),
myname, (long) (lim - start_sbrk));
#endif
subsegs_print_statistics (stderr);
write_print_statistics (stderr);
symbol_print_statistics (stderr);
read_print_statistics (stderr);
#ifdef tc_print_statistics
tc_print_statistics (stderr);
#endif
#ifdef obj_print_statistics
obj_print_statistics (stderr);
#endif
}
static void
close_output_file (void)
{
output_file_close (out_file_name);
if (!keep_it)
unlink_if_ordinary (out_file_name);
}
/* The interface between the macro code and gas expression handling. */
static size_t
macro_expr (const char *emsg, size_t idx, sb *in, offsetT *val)
{
char *hold;
expressionS ex;
sb_terminate (in);
hold = input_line_pointer;
input_line_pointer = in->ptr + idx;
expression_and_evaluate (&ex);
idx = input_line_pointer - in->ptr;
input_line_pointer = hold;
if (ex.X_op != O_constant)
as_bad ("%s", emsg);
*val = ex.X_add_number;
return idx;
}
/* Here to attempt 1 pass over each input file.
We scan argv[*] looking for filenames or exactly "" which is
shorthand for stdin. Any argv that is NULL is not a file-name.
We set need_pass_2 TRUE if, after this, we still have unresolved
expressions of the form (unknown value)+-(unknown value).
Note the un*x semantics: there is only 1 logical input file, but it
may be a catenation of many 'physical' input files. */
static void
perform_an_assembly_pass (int argc, char ** argv)
{
int saw_a_file = 0;
#ifndef OBJ_MACH_O
flagword applicable;
#endif
need_pass_2 = 0;
#ifndef OBJ_MACH_O
/* Create the standard sections, and those the assembler uses
internally. */
text_section = subseg_new (TEXT_SECTION_NAME, 0);
data_section = subseg_new (DATA_SECTION_NAME, 0);
bss_section = subseg_new (BSS_SECTION_NAME, 0);
/* @@ FIXME -- we're setting the RELOC flag so that sections are assumed
to have relocs, otherwise we don't find out in time. */
applicable = bfd_applicable_section_flags (stdoutput);
bfd_set_section_flags (stdoutput, text_section,
applicable & (SEC_ALLOC | SEC_LOAD | SEC_RELOC
| SEC_CODE | SEC_READONLY));
bfd_set_section_flags (stdoutput, data_section,
applicable & (SEC_ALLOC | SEC_LOAD | SEC_RELOC
| SEC_DATA));
bfd_set_section_flags (stdoutput, bss_section, applicable & SEC_ALLOC);
seg_info (bss_section)->bss = 1;
#endif
subseg_new (BFD_ABS_SECTION_NAME, 0);
subseg_new (BFD_UND_SECTION_NAME, 0);
reg_section = subseg_new ("*GAS `reg' section*", 0);
expr_section = subseg_new ("*GAS `expr' section*", 0);
#ifndef OBJ_MACH_O
subseg_set (text_section, 0);
#endif
/* This may add symbol table entries, which requires having an open BFD,
and sections already created. */
md_begin ();
#ifdef USING_CGEN
gas_cgen_begin ();
#endif
#ifdef obj_begin
obj_begin ();
#endif
/* Skip argv[0]. */
argv++;
argc--;
while (argc--)
{
if (*argv)
{ /* Is it a file-name argument? */
PROGRESS (1);
saw_a_file++;
/* argv->"" if stdin desired, else->filename. */
read_a_source_file (*argv);
}
argv++; /* Completed that argv. */
}
if (!saw_a_file)
read_a_source_file ("");
}
#ifdef OBJ_ELF
static void
create_obj_attrs_section (void)
{
segT s;
char *p;
offsetT size;
const char *name;
size = bfd_elf_obj_attr_size (stdoutput);
if (size)
{
name = get_elf_backend_data (stdoutput)->obj_attrs_section;
if (!name)
name = ".gnu.attributes";
s = subseg_new (name, 0);
elf_section_type (s)
= get_elf_backend_data (stdoutput)->obj_attrs_section_type;
bfd_set_section_flags (stdoutput, s, SEC_READONLY | SEC_DATA);
frag_now_fix ();
p = frag_more (size);
bfd_elf_set_obj_attr_contents (stdoutput, (bfd_byte *)p, size);
}
}
#endif
int
main (int argc, char ** argv)
{
char ** argv_orig = argv;
int macro_strip_at;
start_time = get_run_time ();
#ifdef HAVE_SBRK
start_sbrk = (char *) sbrk (0);
#endif
#if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
setlocale (LC_MESSAGES, "");
#endif
#if defined (HAVE_SETLOCALE)
setlocale (LC_CTYPE, "");
#endif
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (debug_memory)
chunksize = 64;
#ifdef HOST_SPECIAL_INIT
HOST_SPECIAL_INIT (argc, argv);
#endif
myname = argv[0];
xmalloc_set_program_name (myname);
expandargv (&argc, &argv);
START_PROGRESS (myname, 0);
#ifndef OBJ_DEFAULT_OUTPUT_FILE_NAME
#define OBJ_DEFAULT_OUTPUT_FILE_NAME "a.out"
#endif
out_file_name = OBJ_DEFAULT_OUTPUT_FILE_NAME;
hex_init ();
bfd_init ();
bfd_set_error_program_name (myname);
#ifdef USE_EMULATIONS
select_emulation_mode (argc, argv);
#endif
PROGRESS (1);
/* Call parse_args before any of the init/begin functions
so that switches like --hash-size can be honored. */
parse_args (&argc, &argv);
symbol_begin ();
frag_init ();
subsegs_begin ();
read_begin ();
input_scrub_begin ();
expr_begin ();
/* It has to be called after dump_statistics (). */
xatexit (close_output_file);
if (flag_print_statistics)
xatexit (dump_statistics);
macro_strip_at = 0;
#ifdef TC_I960
macro_strip_at = flag_mri;
#endif
macro_init (flag_macro_alternate, flag_mri, macro_strip_at, macro_expr);
PROGRESS (1);
output_file_create (out_file_name);
gas_assert (stdoutput != 0);
dot_symbol_init ();
#ifdef tc_init_after_args
tc_init_after_args ();
#endif
itbl_init ();
dwarf2_init ();
local_symbol_make (".gasversion.", absolute_section,
BFD_VERSION / 10000UL, &predefined_address_frag);
/* Now that we have fully initialized, and have created the output
file, define any symbols requested by --defsym command line
arguments. */
while (defsyms != NULL)
{
symbolS *sym;
struct defsym_list *next;
sym = symbol_new (defsyms->name, absolute_section, defsyms->value,
&zero_address_frag);
/* Make symbols defined on the command line volatile, so that they
can be redefined inside a source file. This makes this assembler's
behaviour compatible with earlier versions, but it may not be
completely intuitive. */
S_SET_VOLATILE (sym);
symbol_table_insert (sym);
next = defsyms->next;
free (defsyms);
defsyms = next;
}
PROGRESS (1);
/* Assemble it. */
perform_an_assembly_pass (argc, argv);
cond_finish_check (-1);
#ifdef md_end
md_end ();
#endif
#ifdef OBJ_ELF
if (IS_ELF)
create_obj_attrs_section ();
#endif
#if defined OBJ_ELF || defined OBJ_MAYBE_ELF
if ((flag_execstack || flag_noexecstack)
&& OUTPUT_FLAVOR == bfd_target_elf_flavour)
{
segT gnustack;
gnustack = subseg_new (".note.GNU-stack", 0);
bfd_set_section_flags (stdoutput, gnustack,
SEC_READONLY | (flag_execstack ? SEC_CODE : 0));
}
#endif
/* If we've been collecting dwarf2 .debug_line info, either for
assembly debugging or on behalf of the compiler, emit it now. */
dwarf2_finish ();
/* If we constructed dwarf2 .eh_frame info, either via .cfi
directives from the user or by the backend, emit it now. */
cfi_finish ();
if (seen_at_least_1_file ()
&& (flag_always_generate_output || had_errors () == 0))
keep_it = 1;
else
keep_it = 0;
/* This used to be done at the start of write_object_file in
write.c, but that caused problems when doing listings when
keep_it was zero. This could probably be moved above md_end, but
I didn't want to risk the change. */
subsegs_finish ();
if (keep_it)
write_object_file ();
fflush (stderr);
#ifndef NO_LISTING
listing_print (listing_filename, argv_orig);
#endif
if (flag_fatal_warnings && had_warnings () > 0 && had_errors () == 0)
as_bad (_("%d warnings, treating warnings as errors"), had_warnings ());
if (had_errors () > 0 && ! flag_always_generate_output)
keep_it = 0;
input_scrub_end ();
END_PROGRESS (myname);
/* Use xexit instead of return, because under VMS environments they
may not place the same interpretation on the value given. */
if (had_errors () > 0)
xexit (EXIT_FAILURE);
/* Only generate dependency file if assembler was successful. */
print_dependencies ();
xexit (EXIT_SUCCESS);
}
| gpl-2.0 |
wujiku/superstar-kernel-shooter-2.3.4gb | drivers/usb/gadget/f_projector.c | 7 | 22316 | /*
* Projector function driver
*
* Copyright (C) 2010 HTC Corporation
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/delay.h>
#include <linux/wait.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/types.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <mach/msm_fb.h>
#include <linux/input.h>
#include <linux/usb/android_composite.h>
#include <linux/wakelock.h>
#ifdef DBG
#undef DBG
#endif
#if 1
#define DBG(x...) do {} while (0)
#else
#define DBG(x...) printk(KERN_INFO x)
#endif
/*16KB*/
#define TXN_MAX 16384
#define RXN_MAX 4096
/* number of rx and tx requests to allocate */
#define RX_REQ_MAX 4
#if defined(CONFIG_MACH_FLYER) || defined(CONFIG_MACH_EXPRESS)
#define TX_REQ_MAX 75 /*for resolution 1024*600*2 / 16k */
#else
#define TX_REQ_MAX 70 /*for 8k resolution 544*960*2 / 16k */
#endif
#define BITSPIXEL 16
#define PROJECTOR_FUNCTION_NAME "projector"
static struct wake_lock prj_idle_wake_lock;
static int keypad_code[] = {KEY_WAKEUP, 0, 0, 0, KEY_HOME, KEY_MENU, KEY_BACK};
static const char shortname[] = "android_projector";
struct projector_dev {
struct usb_function function;
struct usb_composite_dev *cdev;
spinlock_t lock;
struct usb_ep *ep_in;
struct usb_ep *ep_out;
int online;
int error;
struct list_head tx_idle;
struct list_head rx_idle;
int rx_done;
u32 bitsPixel;
u32 framesize;
u32 width;
u32 height;
u8 init_done;
u8 enabled;
u16 frame_count;
struct input_dev *keypad_input;
struct input_dev *touch_input;
char *fbaddr;
struct platform_device *pdev;
};
static struct usb_interface_descriptor projector_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 0,
.bNumEndpoints = 2,
.bInterfaceClass = 0xFF,
.bInterfaceSubClass = 0xFF,
.bInterfaceProtocol = 0xFF,
};
static struct usb_endpoint_descriptor projector_highspeed_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_endpoint_descriptor projector_highspeed_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_endpoint_descriptor projector_fullspeed_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor projector_fullspeed_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *fs_projector_descs[] = {
(struct usb_descriptor_header *) &projector_interface_desc,
(struct usb_descriptor_header *) &projector_fullspeed_in_desc,
(struct usb_descriptor_header *) &projector_fullspeed_out_desc,
NULL,
};
static struct usb_descriptor_header *hs_projector_descs[] = {
(struct usb_descriptor_header *) &projector_interface_desc,
(struct usb_descriptor_header *) &projector_highspeed_in_desc,
(struct usb_descriptor_header *) &projector_highspeed_out_desc,
NULL,
};
/* string descriptors: */
static struct usb_string projector_string_defs[] = {
[0].s = "HTC PROJECTOR",
{ } /* end of list */
};
static struct usb_gadget_strings projector_string_table = {
.language = 0x0409, /* en-us */
.strings = projector_string_defs,
};
static struct usb_gadget_strings *projector_strings[] = {
&projector_string_table,
NULL,
};
static struct projector_dev _projector_dev;
struct device prj_dev;
static inline struct projector_dev *func_to_dev(struct usb_function *f)
{
return container_of(f, struct projector_dev, function);
}
static struct usb_request *projector_request_new(struct usb_ep *ep, int buffer_size)
{
struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (!req)
return NULL;
/* now allocate buffers for the requests */
req->buf = kmalloc(buffer_size, GFP_KERNEL);
if (!req->buf) {
usb_ep_free_request(ep, req);
return NULL;
}
return req;
}
static void projector_request_free(struct usb_request *req, struct usb_ep *ep)
{
if (req) {
kfree(req->buf);
usb_ep_free_request(ep, req);
}
}
static inline int _lock(atomic_t *excl)
{
if (atomic_inc_return(excl) == 1) {
return 0;
} else {
atomic_dec(excl);
return -1;
}
}
static inline void _unlock(atomic_t *excl)
{
atomic_dec(excl);
}
/* add a request to the tail of a list */
static void req_put(struct projector_dev *dev, struct list_head *head,
struct usb_request *req)
{
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
list_add_tail(&req->list, head);
spin_unlock_irqrestore(&dev->lock, flags);
}
/* remove a request from the head of a list */
static struct usb_request *req_get(struct projector_dev *dev, struct list_head *head)
{
unsigned long flags;
struct usb_request *req;
spin_lock_irqsave(&dev->lock, flags);
if (list_empty(head)) {
req = 0;
} else {
req = list_first_entry(head, struct usb_request, list);
list_del(&req->list);
}
spin_unlock_irqrestore(&dev->lock, flags);
return req;
}
static void projector_queue_out(struct projector_dev *ctxt)
{
int ret;
struct usb_request *req;
/* if we have idle read requests, get them queued */
while ((req = req_get(ctxt, &ctxt->rx_idle))) {
req->length = RXN_MAX;
DBG("%s: queue %p\n", __func__, req);
ret = usb_ep_queue(ctxt->ep_out, req, GFP_ATOMIC);
if (ret < 0) {
DBG("projector: failed to queue out req (%d)\n", ret);
ctxt->error = 1;
req_put(ctxt, &ctxt->rx_idle, req);
break;
}
}
}
/* for mouse event type, 1 :move, 2:down, 3:up */
static void projector_send_touch_event(struct projector_dev *dev,
int iPenType, int iX, int iY)
{
struct input_dev *tdev = dev->touch_input;
static int b_prePenDown = false;
static int b_firstPenDown = true;
static int iCal_LastX;
static int iCal_LastY;
static int iReportCount;
if (iPenType != 3) {
if (b_firstPenDown) {
input_report_abs(tdev, ABS_X, iX);
input_report_abs(tdev, ABS_Y, iY);
input_report_abs(tdev, ABS_PRESSURE, 100);
input_report_abs(tdev, ABS_TOOL_WIDTH, 1);
input_report_key(tdev, BTN_TOUCH, 1);
input_report_key(tdev, BTN_2, 0);
input_sync(tdev);
b_firstPenDown = false;
b_prePenDown = true; /* For one pen-up only */
printk(KERN_INFO "projector: Pen down %d, %d\n", iX, iY);
} else {
/* don't report the same point */
if (iX != iCal_LastX || iY != iCal_LastY) {
input_report_abs(tdev, ABS_X, iX);
input_report_abs(tdev, ABS_Y, iY);
input_report_abs(tdev, ABS_PRESSURE, 100);
input_report_abs(tdev, ABS_TOOL_WIDTH, 1);
input_report_key(tdev, BTN_TOUCH, 1);
input_report_key(tdev, BTN_2, 0);
input_sync(tdev);
iReportCount++;
if (iReportCount < 10)
printk(KERN_INFO "projector: Pen move %d, %d\n", iX, iY);
}
}
} else if (b_prePenDown) {
input_report_abs(tdev, ABS_X, iX);
input_report_abs(tdev, ABS_Y, iY);
input_report_abs(tdev, ABS_PRESSURE, 0);
input_report_abs(tdev, ABS_TOOL_WIDTH, 0);
input_report_key(tdev, BTN_TOUCH, 0);
input_report_key(tdev, BTN_2, 0);
input_sync(tdev);
printk(KERN_INFO "projector: Pen up %d, %d\n", iX, iY);
b_prePenDown = false;
b_firstPenDown = true;
iReportCount = 0;
}
iCal_LastX = iX;
iCal_LastY = iY;
}
/* key code: 4 -> home, 5-> menu, 6 -> back, 0 -> system wake */
static void projector_send_Key_event(struct projector_dev *ctxt,
int iKeycode)
{
struct input_dev *kdev = ctxt->keypad_input;
printk(KERN_INFO "%s keycode %d\n", __func__, iKeycode);
input_report_key(kdev, keypad_code[iKeycode], 1);
input_sync(kdev);
input_report_key(kdev, keypad_code[iKeycode], 0);
input_sync(kdev);
}
static void send_fb(struct projector_dev *ctxt)
{
struct usb_request *req;
char *frame;
int xfer;
int count = ctxt->framesize;
if (msmfb_get_fb_area())
frame = (ctxt->fbaddr + ctxt->framesize);
else
frame = ctxt->fbaddr;
while (count > 0) {
req = req_get(ctxt, &ctxt->tx_idle);
if (req) {
xfer = count > TXN_MAX? TXN_MAX : count;
req->length = xfer;
memcpy(req->buf, frame, xfer);
if (usb_ep_queue(ctxt->ep_in, req, GFP_ATOMIC) < 0) {
req_put(ctxt, &ctxt->tx_idle, req);
printk(KERN_WARNING "%s: failed to queue req %p\n",
__func__, req);
break;
}
count -= xfer;
frame += xfer;
} else {
printk(KERN_ERR "send_fb: no req to send\n");
break;
}
}
}
static void send_info(struct projector_dev *ctxt)
{
struct usb_request *req;
req = req_get(ctxt, &ctxt->tx_idle);
if (req) {
req->length = 20;
memcpy(req->buf, "okay", 4);
memcpy(req->buf + 4, &ctxt->bitsPixel, 4);
#if defined(CONFIG_MACH_PARADISE)
if (machine_is_paradise()) {
ctxt->framesize = 320 * 480 * 2;
printk(KERN_INFO "send_info: framesize %d\n",
ctxt->framesize);
}
#endif
memcpy(req->buf + 8, &ctxt->framesize, 4);
memcpy(req->buf + 12, &ctxt->width, 4);
memcpy(req->buf + 16, &ctxt->height, 4);
if (usb_ep_queue(ctxt->ep_in, req, GFP_ATOMIC) < 0) {
req_put(ctxt, &ctxt->tx_idle, req);
printk(KERN_WARNING "%s: failed to queue req %p\n",
__func__, req);
}
} else
printk(KERN_INFO "%s: no req to send\n", __func__);
}
static void projector_get_msmfb(struct projector_dev *ctxt)
{
struct msm_fb_info fb_info;
msmfb_get_var(&fb_info);
ctxt->bitsPixel = BITSPIXEL;
ctxt->width = fb_info.xres;
ctxt->height = fb_info.yres;
ctxt->fbaddr = fb_info.fb_addr;
ctxt->framesize = (ctxt->width)*(ctxt->height)*2;
printk(KERN_INFO "projector: width %d, height %d %d\n",
fb_info.xres, fb_info.yres, ctxt->framesize);
}
static void projector_complete_in(struct usb_ep *ep, struct usb_request *req)
{
struct projector_dev *dev = &_projector_dev;
req_put(dev, &dev->tx_idle, req);
}
static void projector_complete_out(struct usb_ep *ep, struct usb_request *req)
{
struct projector_dev *ctxt = &_projector_dev;
unsigned char *data = req->buf;
int mouse_data[3];
int i;
DBG("%s: status %d, %d bytes\n", __func__,
req->status, req->actual);
if (req->status != 0) {
ctxt->error = 1;
req_put(ctxt, &ctxt->rx_idle, req);
return ;
}
/* for mouse event type, 1 :move, 2:down, 3:up */
mouse_data[0] = *((int *)(req->buf));
if (!strncmp("init", data, 4)) {
if (!ctxt->init_done) {
projector_get_msmfb(ctxt);
ctxt->init_done = 1;
}
send_info(ctxt);
/* system wake code */
projector_send_Key_event(ctxt, 0);
} else if (*data == ' ') {
send_fb(ctxt);
ctxt->frame_count++;
/* 30s send system wake code */
if (ctxt->frame_count == 30 * 30) {
projector_send_Key_event(ctxt, 0);
ctxt->frame_count = 0;
}
} else if (mouse_data[0] > 0) {
if (mouse_data[0] < 4) {
for (i = 0; i < 3; i++)
mouse_data[i] = *(((int *)(req->buf))+i);
projector_send_touch_event(ctxt,
mouse_data[0], mouse_data[1], mouse_data[2]);
} else {
projector_send_Key_event(ctxt, mouse_data[0]);
printk(KERN_INFO "projector: Key command data %02x, keycode %d\n",
*((char *)(req->buf)), mouse_data[0]);
}
} else if (mouse_data[0] != 0)
printk(KERN_ERR "projector: Unknow command data %02x, mouse %d,%d,%d\n",
*((char *)(req->buf)), mouse_data[0], mouse_data[1], mouse_data[2]);
req_put(ctxt, &ctxt->rx_idle, req);
projector_queue_out(ctxt);
wake_lock_timeout(&prj_idle_wake_lock, HZ / 2);
}
static int __init create_bulk_endpoints(struct projector_dev *dev,
struct usb_endpoint_descriptor *in_desc,
struct usb_endpoint_descriptor *out_desc)
{
struct usb_composite_dev *cdev = dev->cdev;
struct usb_request *req;
struct usb_ep *ep;
int i;
DBG("create_bulk_endpoints dev: %p\n", dev);
ep = usb_ep_autoconfig(cdev->gadget, in_desc);
if (!ep) {
DBG("usb_ep_autoconfig for ep_in failed\n");
return -ENODEV;
}
DBG("usb_ep_autoconfig for ep_in got %s\n", ep->name);
ep->driver_data = dev; /* claim the endpoint */
dev->ep_in = ep;
ep = usb_ep_autoconfig(cdev->gadget, out_desc);
if (!ep) {
DBG("usb_ep_autoconfig for ep_out failed\n");
return -ENODEV;
}
DBG("usb_ep_autoconfig for projector ep_out got %s\n", ep->name);
ep->driver_data = dev; /* claim the endpoint */
dev->ep_out = ep;
/* now allocate requests for our endpoints */
for (i = 0; i < RX_REQ_MAX; i++) {
req = projector_request_new(dev->ep_out, RXN_MAX);
if (!req)
goto fail;
req->complete = projector_complete_out;
req_put(dev, &dev->rx_idle, req);
}
for (i = 0; i < TX_REQ_MAX; i++) {
req = projector_request_new(dev->ep_in, TXN_MAX);
if (!req)
goto fail;
req->complete = projector_complete_in;
req_put(dev, &dev->tx_idle, req);
}
return 0;
fail:
while ((req = req_get(dev, &dev->tx_idle)))
projector_request_free(req, dev->ep_in);
while ((req = req_get(dev, &dev->rx_idle)))
projector_request_free(req, dev->ep_out);
printk(KERN_ERR "projector: could not allocate requests\n");
return -1;
}
static int
projector_function_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct projector_dev *dev = func_to_dev(f);
int id;
int ret;
dev->cdev = cdev;
DBG("projector_function_bind dev: %p\n", dev);
/* allocate interface ID(s) */
id = usb_interface_id(c, f);
if (id < 0)
return id;
projector_interface_desc.bInterfaceNumber = id;
/* allocate endpoints */
ret = create_bulk_endpoints(dev, &projector_fullspeed_in_desc,
&projector_fullspeed_out_desc);
if (ret)
return ret;
/* support high speed hardware */
if (gadget_is_dualspeed(c->cdev->gadget)) {
projector_highspeed_in_desc.bEndpointAddress =
projector_fullspeed_in_desc.bEndpointAddress;
projector_highspeed_out_desc.bEndpointAddress =
projector_fullspeed_out_desc.bEndpointAddress;
}
DBG("%s speed %s: IN/%s, OUT/%s\n",
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
f->name, dev->ep_in->name, dev->ep_out->name);
return 0;
}
static void
projector_function_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct projector_dev *dev = func_to_dev(f);
struct usb_request *req;
spin_lock_irq(&dev->lock);
while ((req = req_get(dev, &dev->tx_idle)))
projector_request_free(req, dev->ep_in);
while ((req = req_get(dev, &dev->rx_idle)))
projector_request_free(req, dev->ep_out);
dev->online = 0;
dev->error = 1;
spin_unlock_irq(&dev->lock);
}
static int projector_function_set_alt(struct usb_function *f,
unsigned intf, unsigned alt)
{
struct projector_dev *dev = func_to_dev(f);
struct usb_composite_dev *cdev = f->config->cdev;
int ret;
DBG("%s intf: %d alt: %d\n", __func__, intf, alt);
ret = usb_ep_enable(dev->ep_in,
ep_choose(cdev->gadget,
&projector_highspeed_in_desc,
&projector_fullspeed_in_desc));
if (ret)
return ret;
ret = usb_ep_enable(dev->ep_out,
ep_choose(cdev->gadget,
&projector_highspeed_out_desc,
&projector_fullspeed_out_desc));
if (ret) {
usb_ep_disable(dev->ep_in);
return ret;
}
dev->online = 1;
projector_queue_out(dev);
return 0;
}
static void projector_function_disable(struct usb_function *f)
{
struct projector_dev *dev = func_to_dev(f);
struct usb_composite_dev *cdev = dev->cdev;
DBG("projector_function_disable\n");
dev->online = 0;
dev->error = 1;
usb_ep_disable(dev->ep_in);
usb_ep_disable(dev->ep_out);
VDBG(cdev, "%s disabled\n", dev->function.name);
}
static int projector_touch_init(struct projector_dev *dev)
{
int x = dev->width;
int y = dev->height;
int ret = 0;
struct input_dev *tdev = dev->touch_input;
printk(KERN_INFO "%s: x=%d y=%d\n", __func__, x, y);
dev->touch_input = input_allocate_device();
if (dev->touch_input == NULL) {
printk(KERN_ERR "%s: Failed to allocate input device\n",
__func__);
return -1;
}
tdev = dev->touch_input;
tdev->name = "projector_input";
set_bit(EV_SYN, tdev->evbit);
set_bit(EV_KEY, tdev->evbit);
set_bit(BTN_TOUCH, tdev->keybit);
set_bit(BTN_2, tdev->keybit);
set_bit(EV_ABS, tdev->evbit);
if (x == 0) {
printk(KERN_ERR "%s: x=0\n", __func__);
#if defined(CONFIG_ARCH_QSD8X50)
x = 480;
#elif defined(CONFIG_MACH_PARADISE)
if (machine_is_paradise())
x = 240;
else
x = 320;
#else
x = 320;
#endif
}
if (y == 0) {
printk(KERN_ERR "%s: y=0\n", __func__);
#if defined(CONFIG_ARCH_QSD8X50)
y = 800;
#elif defined(CONFIG_MACH_PARADISE)
if (machine_is_paradise())
y = 400;
else
y = 480;
#else
y = 480;
#endif
}
/* Set input parameters boundary. */
input_set_abs_params(tdev, ABS_X, 0, x, 0, 0);
input_set_abs_params(tdev, ABS_Y, 0, y, 0, 0);
input_set_abs_params(tdev, ABS_PRESSURE, 0, 255, 0, 0);
input_set_abs_params(tdev, ABS_TOOL_WIDTH, 0, 15, 0, 0);
input_set_abs_params(tdev, ABS_HAT0X, 0, x, 0, 0);
input_set_abs_params(tdev, ABS_HAT0Y, 0, y, 0, 0);
ret = input_register_device(tdev);
if (ret) {
printk(KERN_ERR "%s: Unable to register %s input device\n",
__func__, tdev->name);
input_free_device(tdev);
return -1;
}
printk(KERN_INFO "%s OK \n", __func__);
return 0;
}
static int projector_keypad_init(struct projector_dev *dev)
{
struct input_dev *kdev;
/* Initialize input device info */
dev->keypad_input = input_allocate_device();
if (dev->keypad_input == NULL) {
printk(KERN_ERR "%s: Failed to allocate input device\n",
__func__);
return -1;
}
kdev = dev->keypad_input;
set_bit(EV_KEY, kdev->evbit);
set_bit(KEY_HOME, kdev->keybit);
set_bit(KEY_MENU, kdev->keybit);
set_bit(KEY_BACK, kdev->keybit);
set_bit(KEY_WAKEUP, kdev->keybit);
kdev->name = "projector-Keypad";
kdev->phys = "input2";
kdev->id.bustype = BUS_HOST;
kdev->id.vendor = 0x0123;
kdev->id.product = 0x5220 /*dummy value*/;
kdev->id.version = 0x0100;
kdev->keycodesize = sizeof(unsigned int);
/* Register linux input device */
if (input_register_device(kdev) < 0) {
printk(KERN_ERR "%s: Unable to register %s input device\n",
__func__, kdev->name);
input_free_device(kdev);
return -1;
}
printk(KERN_INFO "%s OK \n", __func__);
return 0;
}
static ssize_t store_enable(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int _enabled = simple_strtol(buf, NULL, 0);
printk(KERN_INFO "projector: %d\n", _enabled);
android_enable_function(&_projector_dev.function, _enabled);
_projector_dev.enabled = _enabled;
return count;
}
static ssize_t show_enable(struct device *dev, struct device_attribute *attr,
char *buf)
{
buf[0] = '0' + _projector_dev.enabled;
buf[1] = '\n';
return 2;
}
static DEVICE_ATTR(enable, 0664, show_enable, store_enable);
static void prj_dev_release(struct device *dev) {}
static int projector_bind_config(struct usb_configuration *c)
{
struct projector_dev *dev = &_projector_dev;
struct msm_fb_info fb_info;
int ret = 0;
printk(KERN_INFO "projector_bind_config\n");
ret = usb_string_id(c->cdev);
if (ret < 0)
return ret;
projector_string_defs[0].id = ret;
projector_interface_desc.iInterface = ret;
spin_lock_init(&dev->lock);
INIT_LIST_HEAD(&dev->rx_idle);
INIT_LIST_HEAD(&dev->tx_idle);
dev->cdev = c->cdev;
dev->function.name = "projector";
dev->function.strings = projector_strings;
dev->function.descriptors = fs_projector_descs;
dev->function.hs_descriptors = hs_projector_descs;
dev->function.bind = projector_function_bind;
dev->function.unbind = projector_function_unbind;
dev->function.set_alt = projector_function_set_alt;
dev->function.disable = projector_function_disable;
/* start disabled */
dev->function.hidden = 1;
msmfb_get_var(&fb_info);
dev->bitsPixel = BITSPIXEL;
dev->width = fb_info.xres;
dev->height = fb_info.yres;
dev->fbaddr = fb_info.fb_addr;
if (projector_touch_init(dev) < 0)
goto err;
if (projector_keypad_init(dev) < 0)
goto err;
if (!dev->pdev)
goto err;
prj_dev.release = prj_dev_release;
prj_dev.parent = &dev->pdev->dev;
dev_set_name(&prj_dev, "interface");
ret = device_register(&prj_dev);
if (ret != 0) {
DBG("projector failed to register device: %d\n", ret);
goto err;
}
ret = device_create_file(&prj_dev, &dev_attr_enable);
if (ret != 0) {
DBG("projector device_create_file failed: %d\n", ret);
goto err1;
}
ret = usb_add_function(c, &dev->function);
if (ret)
goto err2;
return 0;
err2:
device_remove_file(&prj_dev, &dev_attr_enable);
err1:
device_unregister(&prj_dev);
err:
printk(KERN_ERR "projector gadget driver failed to initialize\n");
return ret;
}
static struct android_usb_function projector_function = {
.name = "projector",
.bind_config = projector_bind_config,
};
static int pjr_probe(struct platform_device *pdev)
{
struct projector_dev *dev = &_projector_dev;
dev->pdev = pdev;
dev->init_done = 0;
dev->frame_count = 0;
wake_lock_init(&prj_idle_wake_lock, WAKE_LOCK_IDLE, "prj_idle_lock");
return 0;
}
static struct platform_driver pjr_driver = {
.probe = pjr_probe,
.driver = { .name = PROJECTOR_FUNCTION_NAME, },
};
static void pjr_release(struct device *dev) {}
static struct platform_device pjr_device = {
.name = PROJECTOR_FUNCTION_NAME,
.id = -1,
.dev = {
.release = pjr_release,
},
};
static int __init init(void)
{
int r;
printk(KERN_INFO "f_projector init\n");
r = platform_driver_register(&pjr_driver);
if (r < 0)
return r;
r = platform_device_register(&pjr_device);
if (r < 0) {
platform_driver_unregister(&pjr_driver);
return r;
}
android_register_function(&projector_function);
return 0;
}
module_init(init);
| gpl-2.0 |
qenter/vlc-android | vlc/modules/demux/image.c | 7 | 21428 | /*****************************************************************************
* image.c: Image demuxer
*****************************************************************************
* Copyright (C) 2010 Laurent Aimar
* $Id$
*
* Authors: Laurent Aimar <fenrir _AT_ videolan _DOT_ org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_demux.h>
#include <vlc_image.h>
#include "mxpeg_helper.h"
/*****************************************************************************
* Module descriptor
*****************************************************************************/
static int Open (vlc_object_t *);
static void Close(vlc_object_t *);
#define ID_TEXT N_("ES ID")
#define ID_LONGTEXT N_( \
"Set the ID of the elementary stream")
#define GROUP_TEXT N_("Group")
#define GROUP_LONGTEXT N_(\
"Set the group of the elementary stream")
#define DECODE_TEXT N_("Decode")
#define DECODE_LONGTEXT N_( \
"Decode at the demuxer stage")
#define CHROMA_TEXT N_("Forced chroma")
#define CHROMA_LONGTEXT N_( \
"If non empty and image-decode is true, the image will be " \
"converted to the specified chroma.")
#define DURATION_TEXT N_("Duration in seconds")
#define DURATION_LONGTEXT N_( \
"Duration in seconds before simulating an end of file. " \
"A negative value means an unlimited play time.")
#define FPS_TEXT N_("Frame rate")
#define FPS_LONGTEXT N_( \
"Frame rate of the elementary stream produced.")
#define RT_TEXT N_("Real-time")
#define RT_LONGTEXT N_( \
"Use real-time mode suitable for being used as a master input and " \
"real-time input slaves.")
vlc_module_begin()
set_description(N_("Image demuxer"))
set_shortname(N_("Image"))
set_category(CAT_INPUT)
set_subcategory(SUBCAT_INPUT_DEMUX)
add_integer("image-id", -1, ID_TEXT, ID_LONGTEXT, true)
change_safe()
add_integer("image-group", 0, GROUP_TEXT, GROUP_LONGTEXT, true)
change_safe()
add_bool("image-decode", true, DECODE_TEXT, DECODE_LONGTEXT, true)
change_safe()
add_string("image-chroma", "", CHROMA_TEXT, CHROMA_LONGTEXT, true)
change_safe()
add_float("image-duration", 10, DURATION_TEXT, DURATION_LONGTEXT, false)
change_safe()
add_string("image-fps", "10/1", FPS_TEXT, FPS_LONGTEXT, true)
change_safe()
add_bool("image-realtime", false, RT_TEXT, RT_LONGTEXT, true)
change_safe()
set_capability("demux", 10)
set_callbacks(Open, Close)
vlc_module_end()
/*****************************************************************************
* Local prototypes
*****************************************************************************/
struct demux_sys_t
{
block_t *data;
es_out_id_t *es;
mtime_t duration;
bool is_realtime;
mtime_t pts_origin;
mtime_t pts_next;
date_t pts;
};
static block_t *Load(demux_t *demux)
{
const unsigned max_size = 4096 * 4096 * 8;
uint64_t size;
if (vlc_stream_GetSize(demux->s, &size) == VLC_SUCCESS) {
if (size > max_size) {
msg_Err(demux, "image too large (%"PRIu64" > %u), rejected",
size, max_size);
return NULL;
}
} else
size = max_size;
block_t *block = block_Alloc(size);
if (block == NULL)
return NULL;
ssize_t val = vlc_stream_Read(demux->s, block->p_buffer, size);
if (val < 0) {
block_Release(block);
return NULL;
}
block->i_buffer = val;
return block;
}
static block_t *Decode(demux_t *demux,
video_format_t *fmt, vlc_fourcc_t chroma, block_t *data)
{
image_handler_t *handler = image_HandlerCreate(demux);
if (!handler) {
block_Release(data);
return NULL;
}
video_format_t decoded;
video_format_Init(&decoded, chroma);
picture_t *image = image_Read(handler, data, fmt, &decoded);
image_HandlerDelete(handler);
if (!image)
return NULL;
video_format_Clean(fmt);
*fmt = decoded;
size_t size = 0;
for (int i = 0; i < image->i_planes; i++)
size += image->p[i].i_pitch * image->p[i].i_lines;
data = block_Alloc(size);
if (!data) {
picture_Release(image);
return NULL;
}
size_t offset = 0;
for (int i = 0; i < image->i_planes; i++) {
const plane_t *src = &image->p[i];
for (int y = 0; y < src->i_visible_lines; y++) {
memcpy(&data->p_buffer[offset],
&src->p_pixels[y * src->i_pitch],
src->i_visible_pitch);
offset += src->i_visible_pitch;
}
}
picture_Release(image);
return data;
}
static int Demux(demux_t *demux)
{
demux_sys_t *sys = demux->p_sys;
if (!sys->data)
return 0;
mtime_t deadline;
const mtime_t pts_first = sys->pts_origin + date_Get(&sys->pts);
if (sys->pts_next > VLC_TS_INVALID) {
deadline = sys->pts_next;
} else if (sys->is_realtime) {
deadline = mdate();
const mtime_t max_wait = CLOCK_FREQ / 50;
if (deadline + max_wait < pts_first) {
es_out_Control(demux->out, ES_OUT_SET_PCR, deadline);
/* That's ugly, but not yet easily fixable */
mwait(deadline + max_wait);
return 1;
}
} else {
deadline = 1 + pts_first;
}
for (;;) {
const mtime_t pts = sys->pts_origin + date_Get(&sys->pts);
if (sys->duration >= 0 && pts >= sys->pts_origin + sys->duration)
return 0;
if (pts >= deadline)
return 1;
block_t *data = block_Duplicate(sys->data);
if (!data)
return -1;
data->i_dts =
data->i_pts = VLC_TS_0 + pts;
es_out_Control(demux->out, ES_OUT_SET_PCR, data->i_pts);
es_out_Send(demux->out, sys->es, data);
date_Increment(&sys->pts, 1);
}
}
static int Control(demux_t *demux, int query, va_list args)
{
demux_sys_t *sys = demux->p_sys;
switch (query) {
case DEMUX_CAN_SEEK:
*va_arg(args, bool *) = sys->duration >= 0 && !sys->is_realtime;
return VLC_SUCCESS;
case DEMUX_GET_POSITION: {
double *position = va_arg(args, double *);
if (sys->duration > 0)
*position = date_Get(&sys->pts) / (double)sys->duration;
else
*position = 0;
return VLC_SUCCESS;
}
case DEMUX_SET_POSITION: {
if (sys->duration < 0 || sys->is_realtime)
return VLC_EGENERIC;
double position = va_arg(args, double);
date_Set(&sys->pts, position * sys->duration);
return VLC_SUCCESS;
}
case DEMUX_GET_TIME: {
int64_t *time = va_arg(args, int64_t *);
*time = sys->pts_origin + date_Get(&sys->pts);
return VLC_SUCCESS;
}
case DEMUX_SET_TIME: {
if (sys->duration < 0 || sys->is_realtime)
return VLC_EGENERIC;
int64_t time = va_arg(args, int64_t);
date_Set(&sys->pts, VLC_CLIP(time - sys->pts_origin, 0, sys->duration));
return VLC_SUCCESS;
}
case DEMUX_SET_NEXT_DEMUX_TIME: {
int64_t pts_next = VLC_TS_0 + va_arg(args, int64_t);
if (sys->pts_next <= VLC_TS_INVALID)
sys->pts_origin = pts_next;
sys->pts_next = pts_next;
return VLC_SUCCESS;
}
case DEMUX_GET_LENGTH: {
int64_t *length = va_arg(args, int64_t *);
*length = __MAX(sys->duration, 0);
return VLC_SUCCESS;
}
case DEMUX_GET_FPS: {
double *fps = va_arg(args, double *);
*fps = (double)sys->pts.i_divider_num / sys->pts.i_divider_den;
return VLC_SUCCESS;
}
case DEMUX_GET_META:
case DEMUX_HAS_UNSUPPORTED_META:
case DEMUX_GET_ATTACHMENTS:
default:
return VLC_EGENERIC;
}
}
static bool IsBmp(stream_t *s)
{
const uint8_t *header;
if (vlc_stream_Peek(s, &header, 18) < 18)
return false;
if (memcmp(header, "BM", 2) &&
memcmp(header, "BA", 2) &&
memcmp(header, "CI", 2) &&
memcmp(header, "CP", 2) &&
memcmp(header, "IC", 2) &&
memcmp(header, "PT", 2))
return false;
uint32_t file_size = GetDWLE(&header[2]);
uint32_t data_offset = GetDWLE(&header[10]);
uint32_t header_size = GetDWLE(&header[14]);
if (file_size != 14 && file_size != 14 + header_size &&
file_size <= data_offset)
return false;
if (data_offset < header_size + 14)
return false;
if (header_size != 12 && header_size < 40)
return false;
return true;
}
static bool IsPcx(stream_t *s)
{
const uint8_t *header;
if (vlc_stream_Peek(s, &header, 66) < 66)
return false;
if (header[0] != 0x0A || /* marker */
(header[1] != 0x00 && header[1] != 0x02 &&
header[1] != 0x03 && header[1] != 0x05) || /* version */
(header[2] != 0 && header[2] != 1) || /* encoding */
(header[3] != 1 && header[3] != 2 &&
header[3] != 4 && header[3] != 8) || /* bits per pixel per plane */
header[64] != 0 || /* reserved */
header[65] == 0 || header[65] > 4) /* plane count */
return false;
if (GetWLE(&header[4]) > GetWLE(&header[8]) || /* xmin vs xmax */
GetWLE(&header[6]) > GetWLE(&header[10])) /* ymin vs ymax */
return false;
return true;
}
static bool IsLbm(stream_t *s)
{
const uint8_t *header;
if (vlc_stream_Peek(s, &header, 12) < 12)
return false;
if (memcmp(&header[0], "FORM", 4) ||
GetDWBE(&header[4]) <= 4 ||
(memcmp(&header[8], "ILBM", 4) && memcmp(&header[8], "PBM ", 4)))
return false;
return true;
}
static bool IsPnmBlank(uint8_t v)
{
return v == ' ' || v == '\t' || v == '\r' || v == '\n';
}
static bool IsPnm(stream_t *s)
{
const uint8_t *header;
int size = vlc_stream_Peek(s, &header, 256);
if (size < 3)
return false;
if (header[0] != 'P' ||
header[1] < '1' || header[1] > '6' ||
!IsPnmBlank(header[2]))
return false;
int number_count = 0;
for (int i = 3, parsing_number = 0; i < size && number_count < 2; i++) {
if (IsPnmBlank(header[i])) {
if (parsing_number) {
parsing_number = 0;
number_count++;
}
} else {
if (header[i] < '0' || header[i] > '9')
break;
parsing_number = 1;
}
}
if (number_count < 2)
return false;
return true;
}
static uint8_t FindJpegMarker(int *position, const uint8_t *data, int size)
{
for (int i = *position; i + 1 < size; i++) {
if (data[i + 0] != 0xff || data[i + 1] == 0x00)
return 0xff;
if (data[i + 1] != 0xff) {
*position = i + 2;
return data[i + 1];
}
}
return 0xff;
}
static bool IsJfif(stream_t *s)
{
const uint8_t *header;
int size = vlc_stream_Peek(s, &header, 256);
int position = 0;
if (FindJpegMarker(&position, header, size) != 0xd8)
return false;
if (FindJpegMarker(&position, header, size) != 0xe0)
return false;
position += 2; /* Skip size */
if (position + 5 > size)
return false;
if (memcmp(&header[position], "JFIF\0", 5))
return false;
return true;
}
static bool IsSpiff(stream_t *s)
{
const uint8_t *header;
if (vlc_stream_Peek(s, &header, 36) < 36) /* SPIFF header size */
return false;
if (header[0] != 0xff || header[1] != 0xd8 ||
header[2] != 0xff || header[3] != 0xe8)
return false;
if (memcmp(&header[6], "SPIFF\0", 6))
return false;
return true;
}
static bool IsExif(stream_t *s)
{
const uint8_t *header;
int size = vlc_stream_Peek(s, &header, 256);
int position = 0;
if (FindJpegMarker(&position, header, size) != 0xd8)
return false;
if (FindJpegMarker(&position, header, size) != 0xe1)
return false;
position += 2; /* Skip size */
if (position + 5 > size)
return false;
if (memcmp(&header[position], "Exif\0", 5))
return false;
return true;
}
static bool FindSVGmarker(int *position, const uint8_t *data, const int size, const char *marker)
{
for( int i = *position; i < size; i++)
{
if (memcmp(&data[i], marker, strlen(marker)) == 0)
{
*position = i;
return true;
}
}
return false;
}
static bool IsSVG(stream_t *s)
{
if (s->psz_url == NULL)
return false;
char *ext = strstr(s->psz_url, ".svg");
if (!ext) return false;
const uint8_t *header;
int size = vlc_stream_Peek(s, &header, 4096);
int position = 0;
const char xml[] = "<?xml version=\"";
if (!FindSVGmarker(&position, header, size, xml))
return false;
if (position != 0)
return false;
const char endxml[] = ">\0";
if (!FindSVGmarker(&position, header, size, endxml))
return false;
if (position <= 15)
return false;
const char svg[] = "<svg";
if (!FindSVGmarker(&position, header, size, svg))
return false;
if (position < 19)
return false;
/* SVG Scalable Vector Graphics image */
/* NOTE: some SVG images have the mimetype set in a meta data section
* and some do not */
return true;
}
static bool IsTarga(stream_t *s)
{
/* The header is not enough to ensure proper detection, we need
* to have a look at the footer. But doing so can be slow. So
* try to avoid it when possible */
const uint8_t *header;
if (vlc_stream_Peek(s, &header, 18) < 18) /* Targa fixed header */
return false;
if (header[1] > 1) /* Color Map Type */
return false;
if ((header[1] != 0 || header[3 + 4] != 0) &&
header[3 + 4] != 8 &&
header[3 + 4] != 15 && header[3 + 4] != 16 &&
header[3 + 4] != 24 && header[3 + 4] != 32)
return false;
if ((header[2] > 3 && header[2] < 9) || header[2] > 11) /* Image Type */
return false;
if (GetWLE(&header[8 + 4]) <= 0 || /* Width */
GetWLE(&header[8 + 6]) <= 0) /* Height */
return false;
if (header[8 + 8] != 8 &&
header[8 + 8] != 15 && header[8 + 8] != 16 &&
header[8 + 8] != 24 && header[8 + 8] != 32)
return false;
if (header[8 + 9] & 0xc0) /* Reserved bits */
return false;
const int64_t size = stream_Size(s);
if (size <= 18 + 26)
return false;
bool can_seek;
if (vlc_stream_Control(s, STREAM_CAN_SEEK, &can_seek) || !can_seek)
return false;
const int64_t position = vlc_stream_Tell(s);
if (vlc_stream_Seek(s, size - 26))
return false;
const uint8_t *footer;
bool is_targa = vlc_stream_Peek(s, &footer, 26) >= 26 &&
!memcmp(&footer[8], "TRUEVISION-XFILE.\x00", 18);
vlc_stream_Seek(s, position);
return is_targa;
}
typedef struct {
vlc_fourcc_t codec;
int marker_size;
const uint8_t marker[14];
bool (*detect)(stream_t *s);
} image_format_t;
#define VLC_CODEC_XCF VLC_FOURCC('X', 'C', 'F', ' ')
#define VLC_CODEC_LBM VLC_FOURCC('L', 'B', 'M', ' ')
static const image_format_t formats[] = {
{ .codec = VLC_CODEC_XCF,
.marker_size = 9 + 4 + 1,
.marker = { 'g', 'i', 'm', 'p', ' ', 'x', 'c', 'f', ' ',
'f', 'i', 'l', 'e', '\0' }
},
{ .codec = VLC_CODEC_XCF,
.marker_size = 9 + 4 + 1,
.marker = { 'g', 'i', 'm', 'p', ' ', 'x', 'c', 'f', ' ',
'v', '0', '0', '1', '\0' }
},
{ .codec = VLC_CODEC_XCF,
.marker_size = 9 + 4 + 1,
.marker = { 'g', 'i', 'm', 'p', ' ', 'x', 'c', 'f', ' ',
'v', '0', '0', '2', '\0' }
},
{ .codec = VLC_CODEC_PNG,
.marker_size = 8,
.marker = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }
},
{ .codec = VLC_CODEC_GIF,
.marker_size = 6,
.marker = { 'G', 'I', 'F', '8', '7', 'a' }
},
{ .codec = VLC_CODEC_GIF,
.marker_size = 6,
.marker = { 'G', 'I', 'F', '8', '9', 'a' }
},
/* XXX TIFF detection may be a bit weak */
{ .codec = VLC_CODEC_TIFF,
.marker_size = 4,
.marker = { 'I', 'I', 0x2a, 0x00 },
},
{ .codec = VLC_CODEC_TIFF,
.marker_size = 4,
.marker = { 'M', 'M', 0x00, 0x2a },
},
{ .codec = VLC_CODEC_BMP,
.detect = IsBmp,
},
{ .codec = VLC_CODEC_PCX,
.detect = IsPcx,
},
{ .codec = VLC_CODEC_LBM,
.detect = IsLbm,
},
{ .codec = VLC_CODEC_PNM,
.detect = IsPnm,
},
{ .codec = VLC_CODEC_MXPEG,
.detect = IsMxpeg,
},
{ .codec = VLC_CODEC_JPEG,
.detect = IsJfif,
},
{ .codec = VLC_CODEC_JPEG,
.detect = IsSpiff,
},
{ .codec = VLC_CODEC_JPEG,
.detect = IsExif,
},
{ .codec = VLC_CODEC_BPG,
.marker_size = 4,
.marker = { 'B', 'P', 'G', 0xFB },
},
{ .codec = VLC_CODEC_SVG,
.detect = IsSVG,
},
{ .codec = VLC_CODEC_TARGA,
.detect = IsTarga,
},
{ .codec = 0 }
};
static int Open(vlc_object_t *object)
{
demux_t *demux = (demux_t*)object;
/* Detect the image type */
const image_format_t *img;
const uint8_t *peek;
int peek_size = 0;
for (int i = 0; ; i++) {
img = &formats[i];
if (!img->codec)
return VLC_EGENERIC;
if (img->detect) {
if (img->detect(demux->s))
break;
} else {
if (peek_size < img->marker_size)
peek_size = vlc_stream_Peek(demux->s, &peek, img->marker_size);
if (peek_size >= img->marker_size &&
!memcmp(peek, img->marker, img->marker_size))
break;
}
}
msg_Dbg(demux, "Detected image: %s",
vlc_fourcc_GetDescription(VIDEO_ES, img->codec));
if( img->codec == VLC_CODEC_MXPEG )
{
return VLC_EGENERIC; //let avformat demux this file
}
/* Load and if selected decode */
es_format_t fmt;
es_format_Init(&fmt, VIDEO_ES, img->codec);
fmt.video.i_chroma = fmt.i_codec;
block_t *data = Load(demux);
if (data && var_InheritBool(demux, "image-decode")) {
char *string = var_InheritString(demux, "image-chroma");
vlc_fourcc_t chroma = vlc_fourcc_GetCodecFromString(VIDEO_ES, string);
free(string);
data = Decode(demux, &fmt.video, chroma, data);
fmt.i_codec = fmt.video.i_chroma;
}
fmt.i_id = var_InheritInteger(demux, "image-id");
fmt.i_group = var_InheritInteger(demux, "image-group");
if (var_InheritURational(demux,
&fmt.video.i_frame_rate,
&fmt.video.i_frame_rate_base,
"image-fps") ||
fmt.video.i_frame_rate <= 0 || fmt.video.i_frame_rate_base <= 0) {
msg_Err(demux, "Invalid frame rate, using 10/1 instead");
fmt.video.i_frame_rate = 10;
fmt.video.i_frame_rate_base = 1;
}
/* If loadind failed, we still continue to avoid mis-detection
* by other demuxers. */
if (!data)
msg_Err(demux, "Failed to load the image");
/* */
demux_sys_t *sys = malloc(sizeof(*sys));
if (!sys) {
if (data)
block_Release(data);
es_format_Clean(&fmt);
return VLC_ENOMEM;
}
sys->data = data;
sys->es = es_out_Add(demux->out, &fmt);
sys->duration = CLOCK_FREQ * var_InheritFloat(demux, "image-duration");
sys->is_realtime = var_InheritBool(demux, "image-realtime");
sys->pts_origin = sys->is_realtime ? mdate() : 0;
sys->pts_next = VLC_TS_INVALID;
date_Init(&sys->pts, fmt.video.i_frame_rate, fmt.video.i_frame_rate_base);
date_Set(&sys->pts, 0);
es_format_Clean(&fmt);
demux->pf_demux = Demux;
demux->pf_control = Control;
demux->p_sys = sys;
return VLC_SUCCESS;
}
static void Close(vlc_object_t *object)
{
demux_t *demux = (demux_t*)object;
demux_sys_t *sys = demux->p_sys;
if (sys->data)
block_Release(sys->data);
free(sys);
}
| gpl-2.0 |
android-armv7a-belalang-tempur/belalang-tempur | drivers/hid/hid-picolcd_cir.c | 263 | 4823 | /***************************************************************************
* Copyright (C) 2010-2012 by Bruno Prémont <bonbons@linux-vserver.org> *
* *
* Based on Logitech G13 driver (v0.4) *
* Copyright (C) 2009 by Rick L. Vinyard, Jr. <rvinyard@cs.nmsu.edu> *
* *
* 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 driver 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 software. If not see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include <linux/hid.h>
#include <linux/hid-debug.h>
#include <linux/input.h>
#include "hid-ids.h"
#include <linux/fb.h>
#include <linux/vmalloc.h>
#include <linux/backlight.h>
#include <linux/lcd.h>
#include <linux/leds.h>
#include <linux/seq_file.h>
#include <linux/debugfs.h>
#include <linux/completion.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include <media/rc-core.h>
#include "hid-picolcd.h"
int picolcd_raw_cir(struct picolcd_data *data,
struct hid_report *report, u8 *raw_data, int size)
{
unsigned long flags;
int i, w, sz;
DEFINE_IR_RAW_EVENT(rawir);
/* ignore if rc_dev is NULL or status is shunned */
spin_lock_irqsave(&data->lock, flags);
if (!data->rc_dev || (data->status & PICOLCD_CIR_SHUN)) {
spin_unlock_irqrestore(&data->lock, flags);
return 1;
}
spin_unlock_irqrestore(&data->lock, flags);
/* PicoLCD USB packets contain 16-bit intervals in network order,
* with value negated for pulse. Intervals are in microseconds.
*
* Note: some userspace LIRC code for PicoLCD says negated values
* for space - is it a matter of IR chip? (pulse for my TSOP2236)
*
* In addition, the first interval seems to be around 15000 + base
* interval for non-first report of IR data - thus the quirk below
* to get RC_CODE to understand Sony and JVC remotes I have at hand
*/
sz = size > 0 ? min((int)raw_data[0], size-1) : 0;
for (i = 0; i+1 < sz; i += 2) {
init_ir_raw_event(&rawir);
w = (raw_data[i] << 8) | (raw_data[i+1]);
rawir.pulse = !!(w & 0x8000);
rawir.duration = US_TO_NS(rawir.pulse ? (65536 - w) : w);
/* Quirk!! - see above */
if (i == 0 && rawir.duration > 15000000)
rawir.duration -= 15000000;
ir_raw_event_store(data->rc_dev, &rawir);
}
ir_raw_event_handle(data->rc_dev);
return 1;
}
static int picolcd_cir_open(struct rc_dev *dev)
{
struct picolcd_data *data = dev->priv;
unsigned long flags;
spin_lock_irqsave(&data->lock, flags);
data->status &= ~PICOLCD_CIR_SHUN;
spin_unlock_irqrestore(&data->lock, flags);
return 0;
}
static void picolcd_cir_close(struct rc_dev *dev)
{
struct picolcd_data *data = dev->priv;
unsigned long flags;
spin_lock_irqsave(&data->lock, flags);
data->status |= PICOLCD_CIR_SHUN;
spin_unlock_irqrestore(&data->lock, flags);
}
/* initialize CIR input device */
int picolcd_init_cir(struct picolcd_data *data, struct hid_report *report)
{
struct rc_dev *rdev;
int ret = 0;
rdev = rc_allocate_device();
if (!rdev)
return -ENOMEM;
rdev->priv = data;
rdev->driver_type = RC_DRIVER_IR_RAW;
rdev->allowed_protos = RC_BIT_ALL;
rdev->open = picolcd_cir_open;
rdev->close = picolcd_cir_close;
rdev->input_name = data->hdev->name;
rdev->input_phys = data->hdev->phys;
rdev->input_id.bustype = data->hdev->bus;
rdev->input_id.vendor = data->hdev->vendor;
rdev->input_id.product = data->hdev->product;
rdev->input_id.version = data->hdev->version;
rdev->dev.parent = &data->hdev->dev;
rdev->driver_name = PICOLCD_NAME;
rdev->map_name = RC_MAP_RC6_MCE;
rdev->timeout = MS_TO_NS(100);
rdev->rx_resolution = US_TO_NS(1);
ret = rc_register_device(rdev);
if (ret)
goto err;
data->rc_dev = rdev;
return 0;
err:
rc_free_device(rdev);
return ret;
}
void picolcd_exit_cir(struct picolcd_data *data)
{
struct rc_dev *rdev = data->rc_dev;
data->rc_dev = NULL;
rc_unregister_device(rdev);
}
| gpl-2.0 |
Cobaltum/kernel_u8110 | drivers/mtd/nand/s3c2410.c | 519 | 29317 | /* linux/drivers/mtd/nand/s3c2410.c
*
* Copyright © 2004-2008 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* Samsung S3C2410/S3C2440/S3C2412 NAND driver
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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
*/
#ifdef CONFIG_MTD_NAND_S3C2410_DEBUG
#define DEBUG
#endif
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/cpufreq.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <asm/io.h>
#include <plat/regs-nand.h>
#include <plat/nand.h>
#ifdef CONFIG_MTD_NAND_S3C2410_HWECC
static int hardware_ecc = 1;
#else
static int hardware_ecc = 0;
#endif
#ifdef CONFIG_MTD_NAND_S3C2410_CLKSTOP
static int clock_stop = 1;
#else
static const int clock_stop = 0;
#endif
/* new oob placement block for use with hardware ecc generation
*/
static struct nand_ecclayout nand_hw_eccoob = {
.eccbytes = 3,
.eccpos = {0, 1, 2},
.oobfree = {{8, 8}}
};
/* controller and mtd information */
struct s3c2410_nand_info;
/**
* struct s3c2410_nand_mtd - driver MTD structure
* @mtd: The MTD instance to pass to the MTD layer.
* @chip: The NAND chip information.
* @set: The platform information supplied for this set of NAND chips.
* @info: Link back to the hardware information.
* @scan_res: The result from calling nand_scan_ident().
*/
struct s3c2410_nand_mtd {
struct mtd_info mtd;
struct nand_chip chip;
struct s3c2410_nand_set *set;
struct s3c2410_nand_info *info;
int scan_res;
};
enum s3c_cpu_type {
TYPE_S3C2410,
TYPE_S3C2412,
TYPE_S3C2440,
};
/* overview of the s3c2410 nand state */
/**
* struct s3c2410_nand_info - NAND controller state.
* @mtds: An array of MTD instances on this controoler.
* @platform: The platform data for this board.
* @device: The platform device we bound to.
* @area: The IO area resource that came from request_mem_region().
* @clk: The clock resource for this controller.
* @regs: The area mapped for the hardware registers described by @area.
* @sel_reg: Pointer to the register controlling the NAND selection.
* @sel_bit: The bit in @sel_reg to select the NAND chip.
* @mtd_count: The number of MTDs created from this controller.
* @save_sel: The contents of @sel_reg to be saved over suspend.
* @clk_rate: The clock rate from @clk.
* @cpu_type: The exact type of this controller.
*/
struct s3c2410_nand_info {
/* mtd info */
struct nand_hw_control controller;
struct s3c2410_nand_mtd *mtds;
struct s3c2410_platform_nand *platform;
/* device info */
struct device *device;
struct resource *area;
struct clk *clk;
void __iomem *regs;
void __iomem *sel_reg;
int sel_bit;
int mtd_count;
unsigned long save_sel;
unsigned long clk_rate;
enum s3c_cpu_type cpu_type;
#ifdef CONFIG_CPU_FREQ
struct notifier_block freq_transition;
#endif
};
/* conversion functions */
static struct s3c2410_nand_mtd *s3c2410_nand_mtd_toours(struct mtd_info *mtd)
{
return container_of(mtd, struct s3c2410_nand_mtd, mtd);
}
static struct s3c2410_nand_info *s3c2410_nand_mtd_toinfo(struct mtd_info *mtd)
{
return s3c2410_nand_mtd_toours(mtd)->info;
}
static struct s3c2410_nand_info *to_nand_info(struct platform_device *dev)
{
return platform_get_drvdata(dev);
}
static struct s3c2410_platform_nand *to_nand_plat(struct platform_device *dev)
{
return dev->dev.platform_data;
}
static inline int allow_clk_stop(struct s3c2410_nand_info *info)
{
return clock_stop;
}
/* timing calculations */
#define NS_IN_KHZ 1000000
/**
* s3c_nand_calc_rate - calculate timing data.
* @wanted: The cycle time in nanoseconds.
* @clk: The clock rate in kHz.
* @max: The maximum divider value.
*
* Calculate the timing value from the given parameters.
*/
static int s3c_nand_calc_rate(int wanted, unsigned long clk, int max)
{
int result;
result = DIV_ROUND_UP((wanted * clk), NS_IN_KHZ);
pr_debug("result %d from %ld, %d\n", result, clk, wanted);
if (result > max) {
printk("%d ns is too big for current clock rate %ld\n", wanted, clk);
return -1;
}
if (result < 1)
result = 1;
return result;
}
#define to_ns(ticks,clk) (((ticks) * NS_IN_KHZ) / (unsigned int)(clk))
/* controller setup */
/**
* s3c2410_nand_setrate - setup controller timing information.
* @info: The controller instance.
*
* Given the information supplied by the platform, calculate and set
* the necessary timing registers in the hardware to generate the
* necessary timing cycles to the hardware.
*/
static int s3c2410_nand_setrate(struct s3c2410_nand_info *info)
{
struct s3c2410_platform_nand *plat = info->platform;
int tacls_max = (info->cpu_type == TYPE_S3C2412) ? 8 : 4;
int tacls, twrph0, twrph1;
unsigned long clkrate = clk_get_rate(info->clk);
unsigned long uninitialized_var(set), cfg, uninitialized_var(mask);
unsigned long flags;
/* calculate the timing information for the controller */
info->clk_rate = clkrate;
clkrate /= 1000; /* turn clock into kHz for ease of use */
if (plat != NULL) {
tacls = s3c_nand_calc_rate(plat->tacls, clkrate, tacls_max);
twrph0 = s3c_nand_calc_rate(plat->twrph0, clkrate, 8);
twrph1 = s3c_nand_calc_rate(plat->twrph1, clkrate, 8);
} else {
/* default timings */
tacls = tacls_max;
twrph0 = 8;
twrph1 = 8;
}
if (tacls < 0 || twrph0 < 0 || twrph1 < 0) {
dev_err(info->device, "cannot get suitable timings\n");
return -EINVAL;
}
dev_info(info->device, "Tacls=%d, %dns Twrph0=%d %dns, Twrph1=%d %dns\n",
tacls, to_ns(tacls, clkrate), twrph0, to_ns(twrph0, clkrate), twrph1, to_ns(twrph1, clkrate));
switch (info->cpu_type) {
case TYPE_S3C2410:
mask = (S3C2410_NFCONF_TACLS(3) |
S3C2410_NFCONF_TWRPH0(7) |
S3C2410_NFCONF_TWRPH1(7));
set = S3C2410_NFCONF_EN;
set |= S3C2410_NFCONF_TACLS(tacls - 1);
set |= S3C2410_NFCONF_TWRPH0(twrph0 - 1);
set |= S3C2410_NFCONF_TWRPH1(twrph1 - 1);
break;
case TYPE_S3C2440:
case TYPE_S3C2412:
mask = (S3C2440_NFCONF_TACLS(tacls_max - 1) |
S3C2440_NFCONF_TWRPH0(7) |
S3C2440_NFCONF_TWRPH1(7));
set = S3C2440_NFCONF_TACLS(tacls - 1);
set |= S3C2440_NFCONF_TWRPH0(twrph0 - 1);
set |= S3C2440_NFCONF_TWRPH1(twrph1 - 1);
break;
default:
BUG();
}
local_irq_save(flags);
cfg = readl(info->regs + S3C2410_NFCONF);
cfg &= ~mask;
cfg |= set;
writel(cfg, info->regs + S3C2410_NFCONF);
local_irq_restore(flags);
dev_dbg(info->device, "NF_CONF is 0x%lx\n", cfg);
return 0;
}
/**
* s3c2410_nand_inithw - basic hardware initialisation
* @info: The hardware state.
*
* Do the basic initialisation of the hardware, using s3c2410_nand_setrate()
* to setup the hardware access speeds and set the controller to be enabled.
*/
static int s3c2410_nand_inithw(struct s3c2410_nand_info *info)
{
int ret;
ret = s3c2410_nand_setrate(info);
if (ret < 0)
return ret;
switch (info->cpu_type) {
case TYPE_S3C2410:
default:
break;
case TYPE_S3C2440:
case TYPE_S3C2412:
/* enable the controller and de-assert nFCE */
writel(S3C2440_NFCONT_ENABLE, info->regs + S3C2440_NFCONT);
}
return 0;
}
/**
* s3c2410_nand_select_chip - select the given nand chip
* @mtd: The MTD instance for this chip.
* @chip: The chip number.
*
* This is called by the MTD layer to either select a given chip for the
* @mtd instance, or to indicate that the access has finished and the
* chip can be de-selected.
*
* The routine ensures that the nFCE line is correctly setup, and any
* platform specific selection code is called to route nFCE to the specific
* chip.
*/
static void s3c2410_nand_select_chip(struct mtd_info *mtd, int chip)
{
struct s3c2410_nand_info *info;
struct s3c2410_nand_mtd *nmtd;
struct nand_chip *this = mtd->priv;
unsigned long cur;
nmtd = this->priv;
info = nmtd->info;
if (chip != -1 && allow_clk_stop(info))
clk_enable(info->clk);
cur = readl(info->sel_reg);
if (chip == -1) {
cur |= info->sel_bit;
} else {
if (nmtd->set != NULL && chip > nmtd->set->nr_chips) {
dev_err(info->device, "invalid chip %d\n", chip);
return;
}
if (info->platform != NULL) {
if (info->platform->select_chip != NULL)
(info->platform->select_chip) (nmtd->set, chip);
}
cur &= ~info->sel_bit;
}
writel(cur, info->sel_reg);
if (chip == -1 && allow_clk_stop(info))
clk_disable(info->clk);
}
/* s3c2410_nand_hwcontrol
*
* Issue command and address cycles to the chip
*/
static void s3c2410_nand_hwcontrol(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
if (cmd == NAND_CMD_NONE)
return;
if (ctrl & NAND_CLE)
writeb(cmd, info->regs + S3C2410_NFCMD);
else
writeb(cmd, info->regs + S3C2410_NFADDR);
}
/* command and control functions */
static void s3c2440_nand_hwcontrol(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
if (cmd == NAND_CMD_NONE)
return;
if (ctrl & NAND_CLE)
writeb(cmd, info->regs + S3C2440_NFCMD);
else
writeb(cmd, info->regs + S3C2440_NFADDR);
}
/* s3c2410_nand_devready()
*
* returns 0 if the nand is busy, 1 if it is ready
*/
static int s3c2410_nand_devready(struct mtd_info *mtd)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
return readb(info->regs + S3C2410_NFSTAT) & S3C2410_NFSTAT_BUSY;
}
static int s3c2440_nand_devready(struct mtd_info *mtd)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
return readb(info->regs + S3C2440_NFSTAT) & S3C2440_NFSTAT_READY;
}
static int s3c2412_nand_devready(struct mtd_info *mtd)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
return readb(info->regs + S3C2412_NFSTAT) & S3C2412_NFSTAT_READY;
}
/* ECC handling functions */
static int s3c2410_nand_correct_data(struct mtd_info *mtd, u_char *dat,
u_char *read_ecc, u_char *calc_ecc)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned int diff0, diff1, diff2;
unsigned int bit, byte;
pr_debug("%s(%p,%p,%p,%p)\n", __func__, mtd, dat, read_ecc, calc_ecc);
diff0 = read_ecc[0] ^ calc_ecc[0];
diff1 = read_ecc[1] ^ calc_ecc[1];
diff2 = read_ecc[2] ^ calc_ecc[2];
pr_debug("%s: rd %02x%02x%02x calc %02x%02x%02x diff %02x%02x%02x\n",
__func__,
read_ecc[0], read_ecc[1], read_ecc[2],
calc_ecc[0], calc_ecc[1], calc_ecc[2],
diff0, diff1, diff2);
if (diff0 == 0 && diff1 == 0 && diff2 == 0)
return 0; /* ECC is ok */
/* sometimes people do not think about using the ECC, so check
* to see if we have an 0xff,0xff,0xff read ECC and then ignore
* the error, on the assumption that this is an un-eccd page.
*/
if (read_ecc[0] == 0xff && read_ecc[1] == 0xff && read_ecc[2] == 0xff
&& info->platform->ignore_unset_ecc)
return 0;
/* Can we correct this ECC (ie, one row and column change).
* Note, this is similar to the 256 error code on smartmedia */
if (((diff0 ^ (diff0 >> 1)) & 0x55) == 0x55 &&
((diff1 ^ (diff1 >> 1)) & 0x55) == 0x55 &&
((diff2 ^ (diff2 >> 1)) & 0x55) == 0x55) {
/* calculate the bit position of the error */
bit = ((diff2 >> 3) & 1) |
((diff2 >> 4) & 2) |
((diff2 >> 5) & 4);
/* calculate the byte position of the error */
byte = ((diff2 << 7) & 0x100) |
((diff1 << 0) & 0x80) |
((diff1 << 1) & 0x40) |
((diff1 << 2) & 0x20) |
((diff1 << 3) & 0x10) |
((diff0 >> 4) & 0x08) |
((diff0 >> 3) & 0x04) |
((diff0 >> 2) & 0x02) |
((diff0 >> 1) & 0x01);
dev_dbg(info->device, "correcting error bit %d, byte %d\n",
bit, byte);
dat[byte] ^= (1 << bit);
return 1;
}
/* if there is only one bit difference in the ECC, then
* one of only a row or column parity has changed, which
* means the error is most probably in the ECC itself */
diff0 |= (diff1 << 8);
diff0 |= (diff2 << 16);
if ((diff0 & ~(1<<fls(diff0))) == 0)
return 1;
return -1;
}
/* ECC functions
*
* These allow the s3c2410 and s3c2440 to use the controller's ECC
* generator block to ECC the data as it passes through]
*/
static void s3c2410_nand_enable_hwecc(struct mtd_info *mtd, int mode)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ctrl;
ctrl = readl(info->regs + S3C2410_NFCONF);
ctrl |= S3C2410_NFCONF_INITECC;
writel(ctrl, info->regs + S3C2410_NFCONF);
}
static void s3c2412_nand_enable_hwecc(struct mtd_info *mtd, int mode)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ctrl;
ctrl = readl(info->regs + S3C2440_NFCONT);
writel(ctrl | S3C2412_NFCONT_INIT_MAIN_ECC, info->regs + S3C2440_NFCONT);
}
static void s3c2440_nand_enable_hwecc(struct mtd_info *mtd, int mode)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ctrl;
ctrl = readl(info->regs + S3C2440_NFCONT);
writel(ctrl | S3C2440_NFCONT_INITECC, info->regs + S3C2440_NFCONT);
}
static int s3c2410_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
ecc_code[0] = readb(info->regs + S3C2410_NFECC + 0);
ecc_code[1] = readb(info->regs + S3C2410_NFECC + 1);
ecc_code[2] = readb(info->regs + S3C2410_NFECC + 2);
pr_debug("%s: returning ecc %02x%02x%02x\n", __func__,
ecc_code[0], ecc_code[1], ecc_code[2]);
return 0;
}
static int s3c2412_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ecc = readl(info->regs + S3C2412_NFMECC0);
ecc_code[0] = ecc;
ecc_code[1] = ecc >> 8;
ecc_code[2] = ecc >> 16;
pr_debug("calculate_ecc: returning ecc %02x,%02x,%02x\n", ecc_code[0], ecc_code[1], ecc_code[2]);
return 0;
}
static int s3c2440_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ecc = readl(info->regs + S3C2440_NFMECC0);
ecc_code[0] = ecc;
ecc_code[1] = ecc >> 8;
ecc_code[2] = ecc >> 16;
pr_debug("%s: returning ecc %06lx\n", __func__, ecc & 0xffffff);
return 0;
}
/* over-ride the standard functions for a little more speed. We can
* use read/write block to move the data buffers to/from the controller
*/
static void s3c2410_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
readsb(this->IO_ADDR_R, buf, len);
}
static void s3c2440_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
readsl(info->regs + S3C2440_NFDATA, buf, len >> 2);
/* cleanup if we've got less than a word to do */
if (len & 3) {
buf += len & ~3;
for (; len & 3; len--)
*buf++ = readb(info->regs + S3C2440_NFDATA);
}
}
static void s3c2410_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
writesb(this->IO_ADDR_W, buf, len);
}
static void s3c2440_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
writesl(info->regs + S3C2440_NFDATA, buf, len >> 2);
/* cleanup any fractional write */
if (len & 3) {
buf += len & ~3;
for (; len & 3; len--, buf++)
writeb(*buf, info->regs + S3C2440_NFDATA);
}
}
/* cpufreq driver support */
#ifdef CONFIG_CPU_FREQ
static int s3c2410_nand_cpufreq_transition(struct notifier_block *nb,
unsigned long val, void *data)
{
struct s3c2410_nand_info *info;
unsigned long newclk;
info = container_of(nb, struct s3c2410_nand_info, freq_transition);
newclk = clk_get_rate(info->clk);
if ((val == CPUFREQ_POSTCHANGE && newclk < info->clk_rate) ||
(val == CPUFREQ_PRECHANGE && newclk > info->clk_rate)) {
s3c2410_nand_setrate(info);
}
return 0;
}
static inline int s3c2410_nand_cpufreq_register(struct s3c2410_nand_info *info)
{
info->freq_transition.notifier_call = s3c2410_nand_cpufreq_transition;
return cpufreq_register_notifier(&info->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
}
static inline void s3c2410_nand_cpufreq_deregister(struct s3c2410_nand_info *info)
{
cpufreq_unregister_notifier(&info->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
}
#else
static inline int s3c2410_nand_cpufreq_register(struct s3c2410_nand_info *info)
{
return 0;
}
static inline void s3c2410_nand_cpufreq_deregister(struct s3c2410_nand_info *info)
{
}
#endif
/* device management functions */
static int s3c24xx_nand_remove(struct platform_device *pdev)
{
struct s3c2410_nand_info *info = to_nand_info(pdev);
platform_set_drvdata(pdev, NULL);
if (info == NULL)
return 0;
s3c2410_nand_cpufreq_deregister(info);
/* Release all our mtds and their partitions, then go through
* freeing the resources used
*/
if (info->mtds != NULL) {
struct s3c2410_nand_mtd *ptr = info->mtds;
int mtdno;
for (mtdno = 0; mtdno < info->mtd_count; mtdno++, ptr++) {
pr_debug("releasing mtd %d (%p)\n", mtdno, ptr);
nand_release(&ptr->mtd);
}
kfree(info->mtds);
}
/* free the common resources */
if (info->clk != NULL && !IS_ERR(info->clk)) {
if (!allow_clk_stop(info))
clk_disable(info->clk);
clk_put(info->clk);
}
if (info->regs != NULL) {
iounmap(info->regs);
info->regs = NULL;
}
if (info->area != NULL) {
release_resource(info->area);
kfree(info->area);
info->area = NULL;
}
kfree(info);
return 0;
}
#ifdef CONFIG_MTD_PARTITIONS
const char *part_probes[] = { "cmdlinepart", NULL };
static int s3c2410_nand_add_partition(struct s3c2410_nand_info *info,
struct s3c2410_nand_mtd *mtd,
struct s3c2410_nand_set *set)
{
struct mtd_partition *part_info;
int nr_part = 0;
if (set == NULL)
return add_mtd_device(&mtd->mtd);
if (set->nr_partitions == 0) {
mtd->mtd.name = set->name;
nr_part = parse_mtd_partitions(&mtd->mtd, part_probes,
&part_info, 0);
} else {
if (set->nr_partitions > 0 && set->partitions != NULL) {
nr_part = set->nr_partitions;
part_info = set->partitions;
}
}
if (nr_part > 0 && part_info)
return add_mtd_partitions(&mtd->mtd, part_info, nr_part);
return add_mtd_device(&mtd->mtd);
}
#else
static int s3c2410_nand_add_partition(struct s3c2410_nand_info *info,
struct s3c2410_nand_mtd *mtd,
struct s3c2410_nand_set *set)
{
return add_mtd_device(&mtd->mtd);
}
#endif
/**
* s3c2410_nand_init_chip - initialise a single instance of an chip
* @info: The base NAND controller the chip is on.
* @nmtd: The new controller MTD instance to fill in.
* @set: The information passed from the board specific platform data.
*
* Initialise the given @nmtd from the information in @info and @set. This
* readies the structure for use with the MTD layer functions by ensuring
* all pointers are setup and the necessary control routines selected.
*/
static void s3c2410_nand_init_chip(struct s3c2410_nand_info *info,
struct s3c2410_nand_mtd *nmtd,
struct s3c2410_nand_set *set)
{
struct nand_chip *chip = &nmtd->chip;
void __iomem *regs = info->regs;
chip->write_buf = s3c2410_nand_write_buf;
chip->read_buf = s3c2410_nand_read_buf;
chip->select_chip = s3c2410_nand_select_chip;
chip->chip_delay = 50;
chip->priv = nmtd;
chip->options = 0;
chip->controller = &info->controller;
switch (info->cpu_type) {
case TYPE_S3C2410:
chip->IO_ADDR_W = regs + S3C2410_NFDATA;
info->sel_reg = regs + S3C2410_NFCONF;
info->sel_bit = S3C2410_NFCONF_nFCE;
chip->cmd_ctrl = s3c2410_nand_hwcontrol;
chip->dev_ready = s3c2410_nand_devready;
break;
case TYPE_S3C2440:
chip->IO_ADDR_W = regs + S3C2440_NFDATA;
info->sel_reg = regs + S3C2440_NFCONT;
info->sel_bit = S3C2440_NFCONT_nFCE;
chip->cmd_ctrl = s3c2440_nand_hwcontrol;
chip->dev_ready = s3c2440_nand_devready;
chip->read_buf = s3c2440_nand_read_buf;
chip->write_buf = s3c2440_nand_write_buf;
break;
case TYPE_S3C2412:
chip->IO_ADDR_W = regs + S3C2440_NFDATA;
info->sel_reg = regs + S3C2440_NFCONT;
info->sel_bit = S3C2412_NFCONT_nFCE0;
chip->cmd_ctrl = s3c2440_nand_hwcontrol;
chip->dev_ready = s3c2412_nand_devready;
if (readl(regs + S3C2410_NFCONF) & S3C2412_NFCONF_NANDBOOT)
dev_info(info->device, "System booted from NAND\n");
break;
}
chip->IO_ADDR_R = chip->IO_ADDR_W;
nmtd->info = info;
nmtd->mtd.priv = chip;
nmtd->mtd.owner = THIS_MODULE;
nmtd->set = set;
if (hardware_ecc) {
chip->ecc.calculate = s3c2410_nand_calculate_ecc;
chip->ecc.correct = s3c2410_nand_correct_data;
chip->ecc.mode = NAND_ECC_HW;
switch (info->cpu_type) {
case TYPE_S3C2410:
chip->ecc.hwctl = s3c2410_nand_enable_hwecc;
chip->ecc.calculate = s3c2410_nand_calculate_ecc;
break;
case TYPE_S3C2412:
chip->ecc.hwctl = s3c2412_nand_enable_hwecc;
chip->ecc.calculate = s3c2412_nand_calculate_ecc;
break;
case TYPE_S3C2440:
chip->ecc.hwctl = s3c2440_nand_enable_hwecc;
chip->ecc.calculate = s3c2440_nand_calculate_ecc;
break;
}
} else {
chip->ecc.mode = NAND_ECC_SOFT;
}
if (set->ecc_layout != NULL)
chip->ecc.layout = set->ecc_layout;
if (set->disable_ecc)
chip->ecc.mode = NAND_ECC_NONE;
switch (chip->ecc.mode) {
case NAND_ECC_NONE:
dev_info(info->device, "NAND ECC disabled\n");
break;
case NAND_ECC_SOFT:
dev_info(info->device, "NAND soft ECC\n");
break;
case NAND_ECC_HW:
dev_info(info->device, "NAND hardware ECC\n");
break;
default:
dev_info(info->device, "NAND ECC UNKNOWN\n");
break;
}
/* If you use u-boot BBT creation code, specifying this flag will
* let the kernel fish out the BBT from the NAND, and also skip the
* full NAND scan that can take 1/2s or so. Little things... */
if (set->flash_bbt)
chip->options |= NAND_USE_FLASH_BBT | NAND_SKIP_BBTSCAN;
}
/**
* s3c2410_nand_update_chip - post probe update
* @info: The controller instance.
* @nmtd: The driver version of the MTD instance.
*
* This routine is called after the chip probe has succesfully completed
* and the relevant per-chip information updated. This call ensure that
* we update the internal state accordingly.
*
* The internal state is currently limited to the ECC state information.
*/
static void s3c2410_nand_update_chip(struct s3c2410_nand_info *info,
struct s3c2410_nand_mtd *nmtd)
{
struct nand_chip *chip = &nmtd->chip;
dev_dbg(info->device, "chip %p => page shift %d\n",
chip, chip->page_shift);
if (chip->ecc.mode != NAND_ECC_HW)
return;
/* change the behaviour depending on wether we are using
* the large or small page nand device */
if (chip->page_shift > 10) {
chip->ecc.size = 256;
chip->ecc.bytes = 3;
} else {
chip->ecc.size = 512;
chip->ecc.bytes = 3;
chip->ecc.layout = &nand_hw_eccoob;
}
}
/* s3c24xx_nand_probe
*
* called by device layer when it finds a device matching
* one our driver can handled. This code checks to see if
* it can allocate all necessary resources then calls the
* nand layer to look for devices
*/
static int s3c24xx_nand_probe(struct platform_device *pdev)
{
struct s3c2410_platform_nand *plat = to_nand_plat(pdev);
enum s3c_cpu_type cpu_type;
struct s3c2410_nand_info *info;
struct s3c2410_nand_mtd *nmtd;
struct s3c2410_nand_set *sets;
struct resource *res;
int err = 0;
int size;
int nr_sets;
int setno;
cpu_type = platform_get_device_id(pdev)->driver_data;
pr_debug("s3c2410_nand_probe(%p)\n", pdev);
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (info == NULL) {
dev_err(&pdev->dev, "no memory for flash info\n");
err = -ENOMEM;
goto exit_error;
}
memset(info, 0, sizeof(*info));
platform_set_drvdata(pdev, info);
spin_lock_init(&info->controller.lock);
init_waitqueue_head(&info->controller.wq);
/* get the clock source and enable it */
info->clk = clk_get(&pdev->dev, "nand");
if (IS_ERR(info->clk)) {
dev_err(&pdev->dev, "failed to get clock\n");
err = -ENOENT;
goto exit_error;
}
clk_enable(info->clk);
/* allocate and map the resource */
/* currently we assume we have the one resource */
res = pdev->resource;
size = res->end - res->start + 1;
info->area = request_mem_region(res->start, size, pdev->name);
if (info->area == NULL) {
dev_err(&pdev->dev, "cannot reserve register region\n");
err = -ENOENT;
goto exit_error;
}
info->device = &pdev->dev;
info->platform = plat;
info->regs = ioremap(res->start, size);
info->cpu_type = cpu_type;
if (info->regs == NULL) {
dev_err(&pdev->dev, "cannot reserve register region\n");
err = -EIO;
goto exit_error;
}
dev_dbg(&pdev->dev, "mapped registers at %p\n", info->regs);
/* initialise the hardware */
err = s3c2410_nand_inithw(info);
if (err != 0)
goto exit_error;
sets = (plat != NULL) ? plat->sets : NULL;
nr_sets = (plat != NULL) ? plat->nr_sets : 1;
info->mtd_count = nr_sets;
/* allocate our information */
size = nr_sets * sizeof(*info->mtds);
info->mtds = kmalloc(size, GFP_KERNEL);
if (info->mtds == NULL) {
dev_err(&pdev->dev, "failed to allocate mtd storage\n");
err = -ENOMEM;
goto exit_error;
}
memset(info->mtds, 0, size);
/* initialise all possible chips */
nmtd = info->mtds;
for (setno = 0; setno < nr_sets; setno++, nmtd++) {
pr_debug("initialising set %d (%p, info %p)\n", setno, nmtd, info);
s3c2410_nand_init_chip(info, nmtd, sets);
nmtd->scan_res = nand_scan_ident(&nmtd->mtd,
(sets) ? sets->nr_chips : 1);
if (nmtd->scan_res == 0) {
s3c2410_nand_update_chip(info, nmtd);
nand_scan_tail(&nmtd->mtd);
s3c2410_nand_add_partition(info, nmtd, sets);
}
if (sets != NULL)
sets++;
}
err = s3c2410_nand_cpufreq_register(info);
if (err < 0) {
dev_err(&pdev->dev, "failed to init cpufreq support\n");
goto exit_error;
}
if (allow_clk_stop(info)) {
dev_info(&pdev->dev, "clock idle support enabled\n");
clk_disable(info->clk);
}
pr_debug("initialised ok\n");
return 0;
exit_error:
s3c24xx_nand_remove(pdev);
if (err == 0)
err = -EINVAL;
return err;
}
/* PM Support */
#ifdef CONFIG_PM
static int s3c24xx_nand_suspend(struct platform_device *dev, pm_message_t pm)
{
struct s3c2410_nand_info *info = platform_get_drvdata(dev);
if (info) {
info->save_sel = readl(info->sel_reg);
/* For the moment, we must ensure nFCE is high during
* the time we are suspended. This really should be
* handled by suspending the MTDs we are using, but
* that is currently not the case. */
writel(info->save_sel | info->sel_bit, info->sel_reg);
if (!allow_clk_stop(info))
clk_disable(info->clk);
}
return 0;
}
static int s3c24xx_nand_resume(struct platform_device *dev)
{
struct s3c2410_nand_info *info = platform_get_drvdata(dev);
unsigned long sel;
if (info) {
clk_enable(info->clk);
s3c2410_nand_inithw(info);
/* Restore the state of the nFCE line. */
sel = readl(info->sel_reg);
sel &= ~info->sel_bit;
sel |= info->save_sel & info->sel_bit;
writel(sel, info->sel_reg);
if (allow_clk_stop(info))
clk_disable(info->clk);
}
return 0;
}
#else
#define s3c24xx_nand_suspend NULL
#define s3c24xx_nand_resume NULL
#endif
/* driver device registration */
static struct platform_device_id s3c24xx_driver_ids[] = {
{
.name = "s3c2410-nand",
.driver_data = TYPE_S3C2410,
}, {
.name = "s3c2440-nand",
.driver_data = TYPE_S3C2440,
}, {
.name = "s3c2412-nand",
.driver_data = TYPE_S3C2412,
}, {
.name = "s3c6400-nand",
.driver_data = TYPE_S3C2412, /* compatible with 2412 */
},
{ }
};
MODULE_DEVICE_TABLE(platform, s3c24xx_driver_ids);
static struct platform_driver s3c24xx_nand_driver = {
.probe = s3c24xx_nand_probe,
.remove = s3c24xx_nand_remove,
.suspend = s3c24xx_nand_suspend,
.resume = s3c24xx_nand_resume,
.id_table = s3c24xx_driver_ids,
.driver = {
.name = "s3c24xx-nand",
.owner = THIS_MODULE,
},
};
static int __init s3c2410_nand_init(void)
{
printk("S3C24XX NAND Driver, (c) 2004 Simtec Electronics\n");
return platform_driver_register(&s3c24xx_nand_driver);
}
static void __exit s3c2410_nand_exit(void)
{
platform_driver_unregister(&s3c24xx_nand_driver);
}
module_init(s3c2410_nand_init);
module_exit(s3c2410_nand_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("S3C24XX MTD NAND driver");
| gpl-2.0 |
faux123/private-pyramid | arch/arm/mach-omap2/cm4xxx.c | 775 | 1692 | /*
* OMAP4 CM module functions
*
* Copyright (C) 2009 Nokia Corporation
* Paul Walmsley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/io.h>
#include <asm/atomic.h>
#include <plat/common.h>
#include "cm.h"
#include "cm-regbits-44xx.h"
/**
* omap4_cm_wait_module_ready - wait for a module to be in 'func' state
* @clkctrl_reg: CLKCTRL module address
*
* Wait for the module IDLEST to be functional. If the idle state is in any
* the non functional state (trans, idle or disabled), module and thus the
* sysconfig cannot be accessed and will probably lead to an "imprecise
* external abort"
*
* Module idle state:
* 0x0 func: Module is fully functional, including OCP
* 0x1 trans: Module is performing transition: wakeup, or sleep, or sleep
* abortion
* 0x2 idle: Module is in Idle mode (only OCP part). It is functional if
* using separate functional clock
* 0x3 disabled: Module is disabled and cannot be accessed
*
* TODO: Need to handle module accessible in idle state
*/
int omap4_cm_wait_module_ready(void __iomem *clkctrl_reg)
{
int i = 0;
if (!clkctrl_reg)
return 0;
omap_test_timeout(((__raw_readl(clkctrl_reg) &
OMAP4430_IDLEST_MASK) == 0),
MAX_MODULE_READY_TIME, i);
return (i < MAX_MODULE_READY_TIME) ? 0 : -EBUSY;
}
| gpl-2.0 |
Sasho/Cataclysm | dep/src/zlib/example.c | 1031 | 16398 | /* example.c -- usage example of the zlib compression library
* Copyright (C) 1995-2004 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include <stdio.h>
#include "zlib.h"
#ifdef STDC
# include <string.h>
# include <stdlib.h>
#endif
#if defined(VMS) || defined(RISCOS)
# define TESTFILE "foo-gz"
#else
# define TESTFILE "foo.gz"
#endif
#define CHECK_ERR(err, msg) { \
if (err != Z_OK) { \
fprintf(stderr, "%s error: %d\n", msg, err); \
exit(1); \
} \
}
const char hello[] = "hello, hello!";
/* "hello world" would be more standard, but the repeated "hello"
* stresses the compression code better, sorry...
*/
const char dictionary[] = "hello";
uLong dictId; /* Adler32 value of the dictionary */
void test_compress OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_gzio OF((const char *fname,
Byte *uncompr, uLong uncomprLen));
void test_deflate OF((Byte *compr, uLong comprLen));
void test_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_large_deflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_large_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_flush OF((Byte *compr, uLong *comprLen));
void test_sync OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_dict_deflate OF((Byte *compr, uLong comprLen));
void test_dict_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
int main OF((int argc, char *argv[]));
/* ===========================================================================
* Test compress() and uncompress()
*/
void test_compress(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
uLong len = (uLong)strlen(hello)+1;
err = compress(compr, &comprLen, (const Bytef*)hello, len);
CHECK_ERR(err, "compress");
strcpy((char*)uncompr, "garbage");
err = uncompress(uncompr, &uncomprLen, compr, comprLen);
CHECK_ERR(err, "uncompress");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad uncompress\n");
exit(1);
} else {
printf("uncompress(): %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Test read/write of .gz files
*/
void test_gzio(fname, uncompr, uncomprLen)
const char *fname; /* compressed file name */
Byte *uncompr;
uLong uncomprLen;
{
#ifdef NO_GZCOMPRESS
fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n");
#else
int err;
int len = (int)strlen(hello)+1;
gzFile file;
z_off_t pos;
file = gzopen(fname, "wb");
if (file == NULL) {
fprintf(stderr, "gzopen error\n");
exit(1);
}
gzputc(file, 'h');
if (gzputs(file, "ello") != 4) {
fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err));
exit(1);
}
if (gzprintf(file, ", %s!", "hello") != 8) {
fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err));
exit(1);
}
gzseek(file, 1L, SEEK_CUR); /* add one zero byte */
gzclose(file);
file = gzopen(fname, "rb");
if (file == NULL) {
fprintf(stderr, "gzopen error\n");
exit(1);
}
strcpy((char*)uncompr, "garbage");
if (gzread(file, uncompr, (unsigned)uncomprLen) != len) {
fprintf(stderr, "gzread err: %s\n", gzerror(file, &err));
exit(1);
}
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad gzread: %s\n", (char*)uncompr);
exit(1);
} else {
printf("gzread(): %s\n", (char*)uncompr);
}
pos = gzseek(file, -8L, SEEK_CUR);
if (pos != 6 || gztell(file) != pos) {
fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n",
(long)pos, (long)gztell(file));
exit(1);
}
if (gzgetc(file) != ' ') {
fprintf(stderr, "gzgetc error\n");
exit(1);
}
if (gzungetc(' ', file) != ' ') {
fprintf(stderr, "gzungetc error\n");
exit(1);
}
gzgets(file, (char*)uncompr, (int)uncomprLen);
if (strlen((char*)uncompr) != 7) { /* " hello!" */
fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err));
exit(1);
}
if (strcmp((char*)uncompr, hello + 6)) {
fprintf(stderr, "bad gzgets after gzseek\n");
exit(1);
} else {
printf("gzgets() after gzseek: %s\n", (char*)uncompr);
}
gzclose(file);
#endif
}
/* ===========================================================================
* Test deflate() with small buffers
*/
void test_deflate(compr, comprLen)
Byte *compr;
uLong comprLen;
{
z_stream c_stream; /* compression stream */
int err;
uLong len = (uLong)strlen(hello)+1;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
CHECK_ERR(err, "deflateInit");
c_stream.next_in = (Bytef*)hello;
c_stream.next_out = compr;
while (c_stream.total_in != len && c_stream.total_out < comprLen) {
c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
}
/* Finish the stream, still forcing small buffers: */
for (;;) {
c_stream.avail_out = 1;
err = deflate(&c_stream, Z_FINISH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "deflate");
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with small buffers
*/
void test_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = 0;
d_stream.next_out = uncompr;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) {
d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "inflate");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad inflate\n");
exit(1);
} else {
printf("inflate(): %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Test deflate() with large buffers and dynamic change of compression level
*/
void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
z_stream c_stream; /* compression stream */
int err;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_BEST_SPEED);
CHECK_ERR(err, "deflateInit");
c_stream.next_out = compr;
c_stream.avail_out = (uInt)comprLen;
/* At this point, uncompr is still mostly zeroes, so it should compress
* very well:
*/
c_stream.next_in = uncompr;
c_stream.avail_in = (uInt)uncomprLen;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
if (c_stream.avail_in != 0) {
fprintf(stderr, "deflate not greedy\n");
exit(1);
}
/* Feed in already compressed data and switch to no compression: */
deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY);
c_stream.next_in = compr;
c_stream.avail_in = (uInt)comprLen/2;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
/* Switch back to compressing mode: */
deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED);
c_stream.next_in = uncompr;
c_stream.avail_in = (uInt)uncomprLen;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
fprintf(stderr, "deflate should report Z_STREAM_END\n");
exit(1);
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with large buffers
*/
void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = (uInt)comprLen;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
for (;;) {
d_stream.next_out = uncompr; /* discard the output */
d_stream.avail_out = (uInt)uncomprLen;
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "large inflate");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (d_stream.total_out != 2*uncomprLen + comprLen/2) {
fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out);
exit(1);
} else {
printf("large_inflate(): OK\n");
}
}
/* ===========================================================================
* Test deflate() with full flush
*/
void test_flush(compr, comprLen)
Byte *compr;
uLong *comprLen;
{
z_stream c_stream; /* compression stream */
int err;
uInt len = (uInt)strlen(hello)+1;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
CHECK_ERR(err, "deflateInit");
c_stream.next_in = (Bytef*)hello;
c_stream.next_out = compr;
c_stream.avail_in = 3;
c_stream.avail_out = (uInt)*comprLen;
err = deflate(&c_stream, Z_FULL_FLUSH);
CHECK_ERR(err, "deflate");
compr[3]++; /* force an error in first compressed block */
c_stream.avail_in = len - 3;
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
CHECK_ERR(err, "deflate");
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
*comprLen = c_stream.total_out;
}
/* ===========================================================================
* Test inflateSync()
*/
void test_sync(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = 2; /* just read the zlib header */
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
d_stream.next_out = uncompr;
d_stream.avail_out = (uInt)uncomprLen;
inflate(&d_stream, Z_NO_FLUSH);
CHECK_ERR(err, "inflate");
d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */
err = inflateSync(&d_stream); /* but skip the damaged part */
CHECK_ERR(err, "inflateSync");
err = inflate(&d_stream, Z_FINISH);
if (err != Z_DATA_ERROR) {
fprintf(stderr, "inflate should report DATA_ERROR\n");
/* Because of incorrect adler32 */
exit(1);
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
printf("after inflateSync(): hel%s\n", (char *)uncompr);
}
/* ===========================================================================
* Test deflate() with preset dictionary
*/
void test_dict_deflate(compr, comprLen)
Byte *compr;
uLong comprLen;
{
z_stream c_stream; /* compression stream */
int err;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_BEST_COMPRESSION);
CHECK_ERR(err, "deflateInit");
err = deflateSetDictionary(&c_stream,
(const Bytef*)dictionary, sizeof(dictionary));
CHECK_ERR(err, "deflateSetDictionary");
dictId = c_stream.adler;
c_stream.next_out = compr;
c_stream.avail_out = (uInt)comprLen;
c_stream.next_in = (Bytef*)hello;
c_stream.avail_in = (uInt)strlen(hello)+1;
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
fprintf(stderr, "deflate should report Z_STREAM_END\n");
exit(1);
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with a preset dictionary
*/
void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = (uInt)comprLen;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
d_stream.next_out = uncompr;
d_stream.avail_out = (uInt)uncomprLen;
for (;;) {
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
if (err == Z_NEED_DICT) {
if (d_stream.adler != dictId) {
fprintf(stderr, "unexpected dictionary");
exit(1);
}
err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
sizeof(dictionary));
}
CHECK_ERR(err, "inflate with dict");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad inflate with dict\n");
exit(1);
} else {
printf("inflate with dictionary: %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Usage: example [output.gz [input.gz]]
*/
int main(argc, argv)
int argc;
char *argv[];
{
Byte *compr, *uncompr;
uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */
uLong uncomprLen = comprLen;
static const char* myVersion = ZLIB_VERSION;
if (zlibVersion()[0] != myVersion[0]) {
fprintf(stderr, "incompatible zlib version\n");
exit(1);
} else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) {
fprintf(stderr, "warning: different zlib version\n");
}
printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n",
ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags());
compr = (Byte*)calloc((uInt)comprLen, 1);
uncompr = (Byte*)calloc((uInt)uncomprLen, 1);
/* compr and uncompr are cleared to avoid reading uninitialized
* data and to ensure that uncompr compresses well.
*/
if (compr == Z_NULL || uncompr == Z_NULL) {
printf("out of memory\n");
exit(1);
}
test_compress(compr, comprLen, uncompr, uncomprLen);
test_gzio((argc > 1 ? argv[1] : TESTFILE),
uncompr, uncomprLen);
test_deflate(compr, comprLen);
test_inflate(compr, comprLen, uncompr, uncomprLen);
test_large_deflate(compr, comprLen, uncompr, uncomprLen);
test_large_inflate(compr, comprLen, uncompr, uncomprLen);
test_flush(compr, &comprLen);
test_sync(compr, comprLen, uncompr, uncomprLen);
comprLen = uncomprLen;
test_dict_deflate(compr, comprLen);
test_dict_inflate(compr, comprLen, uncompr, uncomprLen);
free(compr);
free(uncompr);
return 0;
}
| gpl-2.0 |
genehuangtaiwan/common | arch/x86/boot/tools/build.c | 1287 | 11095 | /*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 1997 Martin Mares
* Copyright (C) 2007 H. Peter Anvin
*/
/*
* This file builds a disk-image from two different files:
*
* - setup: 8086 machine code, sets up system parm
* - system: 80386 code for actual system
*
* It does some checking that all files are of the correct type, and
* just writes the result to stdout, removing headers and padding to
* the right amount. It also writes some system data to stderr.
*/
/*
* Changes by tytso to allow root device specification
* High loaded stuff by Hans Lermen & Werner Almesberger, Feb. 1996
* Cross compiling fixes by Gertjan van Wingerde, July 1996
* Rewritten by Martin Mares, April 1997
* Substantially overhauled by H. Peter Anvin, April 2007
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <tools/le_byteshift.h>
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
#define DEFAULT_MAJOR_ROOT 0
#define DEFAULT_MINOR_ROOT 0
#define DEFAULT_ROOT_DEV (DEFAULT_MAJOR_ROOT << 8 | DEFAULT_MINOR_ROOT)
/* Minimal number of setup sectors */
#define SETUP_SECT_MIN 5
#define SETUP_SECT_MAX 64
/* This must be large enough to hold the entire setup */
u8 buf[SETUP_SECT_MAX*512];
int is_big_kernel;
#define PECOFF_RELOC_RESERVE 0x20
unsigned long efi_stub_entry;
unsigned long efi_pe_entry;
unsigned long startup_64;
/*----------------------------------------------------------------------*/
static const u32 crctab32[] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d
};
static u32 partial_crc32_one(u8 c, u32 crc)
{
return crctab32[(crc ^ c) & 0xff] ^ (crc >> 8);
}
static u32 partial_crc32(const u8 *s, int len, u32 crc)
{
while (len--)
crc = partial_crc32_one(*s++, crc);
return crc;
}
static void die(const char * str, ...)
{
va_list args;
va_start(args, str);
vfprintf(stderr, str, args);
fputc('\n', stderr);
exit(1);
}
static void usage(void)
{
die("Usage: build setup system [zoffset.h] [> image]");
}
#ifdef CONFIG_EFI_STUB
static void update_pecoff_section_header(char *section_name, u32 offset, u32 size)
{
unsigned int pe_header;
unsigned short num_sections;
u8 *section;
pe_header = get_unaligned_le32(&buf[0x3c]);
num_sections = get_unaligned_le16(&buf[pe_header + 6]);
#ifdef CONFIG_X86_32
section = &buf[pe_header + 0xa8];
#else
section = &buf[pe_header + 0xb8];
#endif
while (num_sections > 0) {
if (strncmp((char*)section, section_name, 8) == 0) {
/* section header size field */
put_unaligned_le32(size, section + 0x8);
/* section header vma field */
put_unaligned_le32(offset, section + 0xc);
/* section header 'size of initialised data' field */
put_unaligned_le32(size, section + 0x10);
/* section header 'file offset' field */
put_unaligned_le32(offset, section + 0x14);
break;
}
section += 0x28;
num_sections--;
}
}
static void update_pecoff_setup_and_reloc(unsigned int size)
{
u32 setup_offset = 0x200;
u32 reloc_offset = size - PECOFF_RELOC_RESERVE;
u32 setup_size = reloc_offset - setup_offset;
update_pecoff_section_header(".setup", setup_offset, setup_size);
update_pecoff_section_header(".reloc", reloc_offset, PECOFF_RELOC_RESERVE);
/*
* Modify .reloc section contents with a single entry. The
* relocation is applied to offset 10 of the relocation section.
*/
put_unaligned_le32(reloc_offset + 10, &buf[reloc_offset]);
put_unaligned_le32(10, &buf[reloc_offset + 4]);
}
static void update_pecoff_text(unsigned int text_start, unsigned int file_sz)
{
unsigned int pe_header;
unsigned int text_sz = file_sz - text_start;
pe_header = get_unaligned_le32(&buf[0x3c]);
/* Size of image */
put_unaligned_le32(file_sz, &buf[pe_header + 0x50]);
/*
* Size of code: Subtract the size of the first sector (512 bytes)
* which includes the header.
*/
put_unaligned_le32(file_sz - 512, &buf[pe_header + 0x1c]);
/*
* Address of entry point for PE/COFF executable
*/
put_unaligned_le32(text_start + efi_pe_entry, &buf[pe_header + 0x28]);
update_pecoff_section_header(".text", text_start, text_sz);
}
#endif /* CONFIG_EFI_STUB */
/*
* Parse zoffset.h and find the entry points. We could just #include zoffset.h
* but that would mean tools/build would have to be rebuilt every time. It's
* not as if parsing it is hard...
*/
#define PARSE_ZOFS(p, sym) do { \
if (!strncmp(p, "#define ZO_" #sym " ", 11+sizeof(#sym))) \
sym = strtoul(p + 11 + sizeof(#sym), NULL, 16); \
} while (0)
static void parse_zoffset(char *fname)
{
FILE *file;
char *p;
int c;
file = fopen(fname, "r");
if (!file)
die("Unable to open `%s': %m", fname);
c = fread(buf, 1, sizeof(buf) - 1, file);
if (ferror(file))
die("read-error on `zoffset.h'");
buf[c] = 0;
p = (char *)buf;
while (p && *p) {
PARSE_ZOFS(p, efi_stub_entry);
PARSE_ZOFS(p, efi_pe_entry);
PARSE_ZOFS(p, startup_64);
p = strchr(p, '\n');
while (p && (*p == '\r' || *p == '\n'))
p++;
}
}
int main(int argc, char ** argv)
{
unsigned int i, sz, setup_sectors;
int c;
u32 sys_size;
struct stat sb;
FILE *file;
int fd;
void *kernel;
u32 crc = 0xffffffffUL;
/* Defaults for old kernel */
#ifdef CONFIG_X86_32
efi_pe_entry = 0x10;
efi_stub_entry = 0x30;
#else
efi_pe_entry = 0x210;
efi_stub_entry = 0x230;
startup_64 = 0x200;
#endif
if (argc == 4)
parse_zoffset(argv[3]);
else if (argc != 3)
usage();
/* Copy the setup code */
file = fopen(argv[1], "r");
if (!file)
die("Unable to open `%s': %m", argv[1]);
c = fread(buf, 1, sizeof(buf), file);
if (ferror(file))
die("read-error on `setup'");
if (c < 1024)
die("The setup must be at least 1024 bytes");
if (get_unaligned_le16(&buf[510]) != 0xAA55)
die("Boot block hasn't got boot flag (0xAA55)");
fclose(file);
#ifdef CONFIG_EFI_STUB
/* Reserve 0x20 bytes for .reloc section */
memset(buf+c, 0, PECOFF_RELOC_RESERVE);
c += PECOFF_RELOC_RESERVE;
#endif
/* Pad unused space with zeros */
setup_sectors = (c + 511) / 512;
if (setup_sectors < SETUP_SECT_MIN)
setup_sectors = SETUP_SECT_MIN;
i = setup_sectors*512;
memset(buf+c, 0, i-c);
#ifdef CONFIG_EFI_STUB
update_pecoff_setup_and_reloc(i);
#endif
/* Set the default root device */
put_unaligned_le16(DEFAULT_ROOT_DEV, &buf[508]);
fprintf(stderr, "Setup is %d bytes (padded to %d bytes).\n", c, i);
/* Open and stat the kernel file */
fd = open(argv[2], O_RDONLY);
if (fd < 0)
die("Unable to open `%s': %m", argv[2]);
if (fstat(fd, &sb))
die("Unable to stat `%s': %m", argv[2]);
sz = sb.st_size;
fprintf (stderr, "System is %d kB\n", (sz+1023)/1024);
kernel = mmap(NULL, sz, PROT_READ, MAP_SHARED, fd, 0);
if (kernel == MAP_FAILED)
die("Unable to mmap '%s': %m", argv[2]);
/* Number of 16-byte paragraphs, including space for a 4-byte CRC */
sys_size = (sz + 15 + 4) / 16;
/* Patch the setup code with the appropriate size parameters */
buf[0x1f1] = setup_sectors-1;
put_unaligned_le32(sys_size, &buf[0x1f4]);
#ifdef CONFIG_EFI_STUB
update_pecoff_text(setup_sectors * 512, sz + i + ((sys_size * 16) - sz));
#ifdef CONFIG_X86_64 /* Yes, this is really how we defined it :( */
efi_stub_entry -= 0x200;
#endif
put_unaligned_le32(efi_stub_entry, &buf[0x264]);
#endif
crc = partial_crc32(buf, i, crc);
if (fwrite(buf, 1, i, stdout) != i)
die("Writing setup failed");
/* Copy the kernel code */
crc = partial_crc32(kernel, sz, crc);
if (fwrite(kernel, 1, sz, stdout) != sz)
die("Writing kernel failed");
/* Add padding leaving 4 bytes for the checksum */
while (sz++ < (sys_size*16) - 4) {
crc = partial_crc32_one('\0', crc);
if (fwrite("\0", 1, 1, stdout) != 1)
die("Writing padding failed");
}
/* Write the CRC */
fprintf(stderr, "CRC %x\n", crc);
put_unaligned_le32(crc, buf);
if (fwrite(buf, 1, 4, stdout) != 4)
die("Writing CRC failed");
close(fd);
/* Everything is OK */
return 0;
}
| gpl-2.0 |
TangxingZhou/linux | drivers/input/misc/sgi_btns.c | 1543 | 4106 | /*
* SGI Volume Button interface driver
*
* Copyright (C) 2008 Thomas Bogendoerfer <tsbogend@alpha.franken.de>
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/input-polldev.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#ifdef CONFIG_SGI_IP22
#include <asm/sgi/ioc.h>
static inline u8 button_status(void)
{
u8 status;
status = readb(&sgioc->panel) ^ 0xa0;
return ((status & 0x80) >> 6) | ((status & 0x20) >> 5);
}
#endif
#ifdef CONFIG_SGI_IP32
#include <asm/ip32/mace.h>
static inline u8 button_status(void)
{
u64 status;
status = readq(&mace->perif.audio.control);
writeq(status & ~(3U << 23), &mace->perif.audio.control);
return (status >> 23) & 3;
}
#endif
#define BUTTONS_POLL_INTERVAL 30 /* msec */
#define BUTTONS_COUNT_THRESHOLD 3
static const unsigned short sgi_map[] = {
KEY_VOLUMEDOWN,
KEY_VOLUMEUP
};
struct buttons_dev {
struct input_polled_dev *poll_dev;
unsigned short keymap[ARRAY_SIZE(sgi_map)];
int count[ARRAY_SIZE(sgi_map)];
};
static void handle_buttons(struct input_polled_dev *dev)
{
struct buttons_dev *bdev = dev->private;
struct input_dev *input = dev->input;
u8 status;
int i;
status = button_status();
for (i = 0; i < ARRAY_SIZE(bdev->keymap); i++) {
if (status & (1U << i)) {
if (++bdev->count[i] == BUTTONS_COUNT_THRESHOLD) {
input_event(input, EV_MSC, MSC_SCAN, i);
input_report_key(input, bdev->keymap[i], 1);
input_sync(input);
}
} else {
if (bdev->count[i] >= BUTTONS_COUNT_THRESHOLD) {
input_event(input, EV_MSC, MSC_SCAN, i);
input_report_key(input, bdev->keymap[i], 0);
input_sync(input);
}
bdev->count[i] = 0;
}
}
}
static int sgi_buttons_probe(struct platform_device *pdev)
{
struct buttons_dev *bdev;
struct input_polled_dev *poll_dev;
struct input_dev *input;
int error, i;
bdev = kzalloc(sizeof(struct buttons_dev), GFP_KERNEL);
poll_dev = input_allocate_polled_device();
if (!bdev || !poll_dev) {
error = -ENOMEM;
goto err_free_mem;
}
memcpy(bdev->keymap, sgi_map, sizeof(bdev->keymap));
poll_dev->private = bdev;
poll_dev->poll = handle_buttons;
poll_dev->poll_interval = BUTTONS_POLL_INTERVAL;
input = poll_dev->input;
input->name = "SGI buttons";
input->phys = "sgi/input0";
input->id.bustype = BUS_HOST;
input->dev.parent = &pdev->dev;
input->keycode = bdev->keymap;
input->keycodemax = ARRAY_SIZE(bdev->keymap);
input->keycodesize = sizeof(unsigned short);
input_set_capability(input, EV_MSC, MSC_SCAN);
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < ARRAY_SIZE(sgi_map); i++)
__set_bit(bdev->keymap[i], input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
bdev->poll_dev = poll_dev;
platform_set_drvdata(pdev, bdev);
error = input_register_polled_device(poll_dev);
if (error)
goto err_free_mem;
return 0;
err_free_mem:
input_free_polled_device(poll_dev);
kfree(bdev);
return error;
}
static int sgi_buttons_remove(struct platform_device *pdev)
{
struct buttons_dev *bdev = platform_get_drvdata(pdev);
input_unregister_polled_device(bdev->poll_dev);
input_free_polled_device(bdev->poll_dev);
kfree(bdev);
return 0;
}
static struct platform_driver sgi_buttons_driver = {
.probe = sgi_buttons_probe,
.remove = sgi_buttons_remove,
.driver = {
.name = "sgibtns",
},
};
module_platform_driver(sgi_buttons_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
13693100472/linux | drivers/leds/leds-versatile.c | 1799 | 2533 | /*
* Driver for the 8 user LEDs found on the RealViews and Versatiles
* Based on DaVinci's DM365 board code
*
* License terms: GNU General Public License (GPL) version 2
* Author: Linus Walleij <triad@df.lth.se>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/leds.h>
#include <linux/platform_device.h>
struct versatile_led {
void __iomem *base;
struct led_classdev cdev;
u8 mask;
};
/*
* The triggers lines up below will only be used if the
* LED triggers are compiled in.
*/
static const struct {
const char *name;
const char *trigger;
} versatile_leds[] = {
{ "versatile:0", "heartbeat", },
{ "versatile:1", "mmc0", },
{ "versatile:2", "cpu0" },
{ "versatile:3", "cpu1" },
{ "versatile:4", "cpu2" },
{ "versatile:5", "cpu3" },
{ "versatile:6", },
{ "versatile:7", },
};
static void versatile_led_set(struct led_classdev *cdev,
enum led_brightness b)
{
struct versatile_led *led = container_of(cdev,
struct versatile_led, cdev);
u32 reg = readl(led->base);
if (b != LED_OFF)
reg |= led->mask;
else
reg &= ~led->mask;
writel(reg, led->base);
}
static enum led_brightness versatile_led_get(struct led_classdev *cdev)
{
struct versatile_led *led = container_of(cdev,
struct versatile_led, cdev);
u32 reg = readl(led->base);
return (reg & led->mask) ? LED_FULL : LED_OFF;
}
static int versatile_leds_probe(struct platform_device *dev)
{
int i;
struct resource *res;
void __iomem *base;
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
base = devm_ioremap_resource(&dev->dev, res);
if (IS_ERR(base))
return PTR_ERR(base);
/* All off */
writel(0, base);
for (i = 0; i < ARRAY_SIZE(versatile_leds); i++) {
struct versatile_led *led;
led = kzalloc(sizeof(*led), GFP_KERNEL);
if (!led)
break;
led->base = base;
led->cdev.name = versatile_leds[i].name;
led->cdev.brightness_set = versatile_led_set;
led->cdev.brightness_get = versatile_led_get;
led->cdev.default_trigger = versatile_leds[i].trigger;
led->mask = BIT(i);
if (led_classdev_register(NULL, &led->cdev) < 0) {
kfree(led);
break;
}
}
return 0;
}
static struct platform_driver versatile_leds_driver = {
.driver = {
.name = "versatile-leds",
},
.probe = versatile_leds_probe,
};
module_platform_driver(versatile_leds_driver);
MODULE_AUTHOR("Linus Walleij <linus.walleij@linaro.org>");
MODULE_DESCRIPTION("ARM Versatile LED driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
rmbq/bubba_kernel_3.0 | security/tomoyo/domain.c | 2823 | 14925 | /*
* security/tomoyo/domain.c
*
* Domain transition functions for TOMOYO.
*
* Copyright (C) 2005-2010 NTT DATA CORPORATION
*/
#include "common.h"
#include <linux/binfmts.h>
#include <linux/slab.h>
/* Variables definitions.*/
/* The initial domain. */
struct tomoyo_domain_info tomoyo_kernel_domain;
/**
* tomoyo_update_policy - Update an entry for exception policy.
*
* @new_entry: Pointer to "struct tomoyo_acl_info".
* @size: Size of @new_entry in bytes.
* @is_delete: True if it is a delete request.
* @list: Pointer to "struct list_head".
* @check_duplicate: Callback function to find duplicated entry.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_update_policy(struct tomoyo_acl_head *new_entry, const int size,
bool is_delete, struct list_head *list,
bool (*check_duplicate) (const struct tomoyo_acl_head
*,
const struct tomoyo_acl_head
*))
{
int error = is_delete ? -ENOENT : -ENOMEM;
struct tomoyo_acl_head *entry;
if (mutex_lock_interruptible(&tomoyo_policy_lock))
return -ENOMEM;
list_for_each_entry_rcu(entry, list, list) {
if (!check_duplicate(entry, new_entry))
continue;
entry->is_deleted = is_delete;
error = 0;
break;
}
if (error && !is_delete) {
entry = tomoyo_commit_ok(new_entry, size);
if (entry) {
list_add_tail_rcu(&entry->list, list);
error = 0;
}
}
mutex_unlock(&tomoyo_policy_lock);
return error;
}
/**
* tomoyo_update_domain - Update an entry for domain policy.
*
* @new_entry: Pointer to "struct tomoyo_acl_info".
* @size: Size of @new_entry in bytes.
* @is_delete: True if it is a delete request.
* @domain: Pointer to "struct tomoyo_domain_info".
* @check_duplicate: Callback function to find duplicated entry.
* @merge_duplicate: Callback function to merge duplicated entry.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_update_domain(struct tomoyo_acl_info *new_entry, const int size,
bool is_delete, struct tomoyo_domain_info *domain,
bool (*check_duplicate) (const struct tomoyo_acl_info
*,
const struct tomoyo_acl_info
*),
bool (*merge_duplicate) (struct tomoyo_acl_info *,
struct tomoyo_acl_info *,
const bool))
{
int error = is_delete ? -ENOENT : -ENOMEM;
struct tomoyo_acl_info *entry;
if (mutex_lock_interruptible(&tomoyo_policy_lock))
return error;
list_for_each_entry_rcu(entry, &domain->acl_info_list, list) {
if (!check_duplicate(entry, new_entry))
continue;
if (merge_duplicate)
entry->is_deleted = merge_duplicate(entry, new_entry,
is_delete);
else
entry->is_deleted = is_delete;
error = 0;
break;
}
if (error && !is_delete) {
entry = tomoyo_commit_ok(new_entry, size);
if (entry) {
list_add_tail_rcu(&entry->list, &domain->acl_info_list);
error = 0;
}
}
mutex_unlock(&tomoyo_policy_lock);
return error;
}
void tomoyo_check_acl(struct tomoyo_request_info *r,
bool (*check_entry) (struct tomoyo_request_info *,
const struct tomoyo_acl_info *))
{
const struct tomoyo_domain_info *domain = r->domain;
struct tomoyo_acl_info *ptr;
list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
if (ptr->is_deleted || ptr->type != r->param_type)
continue;
if (check_entry(r, ptr)) {
r->granted = true;
return;
}
}
r->granted = false;
}
/* The list for "struct tomoyo_domain_info". */
LIST_HEAD(tomoyo_domain_list);
struct list_head tomoyo_policy_list[TOMOYO_MAX_POLICY];
struct list_head tomoyo_group_list[TOMOYO_MAX_GROUP];
/**
* tomoyo_last_word - Get last component of a domainname.
*
* @domainname: Domainname to check.
*
* Returns the last word of @domainname.
*/
static const char *tomoyo_last_word(const char *name)
{
const char *cp = strrchr(name, ' ');
if (cp)
return cp + 1;
return name;
}
static bool tomoyo_same_transition_control(const struct tomoyo_acl_head *a,
const struct tomoyo_acl_head *b)
{
const struct tomoyo_transition_control *p1 = container_of(a,
typeof(*p1),
head);
const struct tomoyo_transition_control *p2 = container_of(b,
typeof(*p2),
head);
return p1->type == p2->type && p1->is_last_name == p2->is_last_name
&& p1->domainname == p2->domainname
&& p1->program == p2->program;
}
/**
* tomoyo_update_transition_control_entry - Update "struct tomoyo_transition_control" list.
*
* @domainname: The name of domain. Maybe NULL.
* @program: The name of program. Maybe NULL.
* @type: Type of transition.
* @is_delete: True if it is a delete request.
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_update_transition_control_entry(const char *domainname,
const char *program,
const u8 type,
const bool is_delete)
{
struct tomoyo_transition_control e = { .type = type };
int error = is_delete ? -ENOENT : -ENOMEM;
if (program) {
if (!tomoyo_correct_path(program))
return -EINVAL;
e.program = tomoyo_get_name(program);
if (!e.program)
goto out;
}
if (domainname) {
if (!tomoyo_correct_domain(domainname)) {
if (!tomoyo_correct_path(domainname))
goto out;
e.is_last_name = true;
}
e.domainname = tomoyo_get_name(domainname);
if (!e.domainname)
goto out;
}
error = tomoyo_update_policy(&e.head, sizeof(e), is_delete,
&tomoyo_policy_list
[TOMOYO_ID_TRANSITION_CONTROL],
tomoyo_same_transition_control);
out:
tomoyo_put_name(e.domainname);
tomoyo_put_name(e.program);
return error;
}
/**
* tomoyo_write_transition_control - Write "struct tomoyo_transition_control" list.
*
* @data: String to parse.
* @is_delete: True if it is a delete request.
* @type: Type of this entry.
*
* Returns 0 on success, negative value otherwise.
*/
int tomoyo_write_transition_control(char *data, const bool is_delete,
const u8 type)
{
char *domainname = strstr(data, " from ");
if (domainname) {
*domainname = '\0';
domainname += 6;
} else if (type == TOMOYO_TRANSITION_CONTROL_NO_KEEP ||
type == TOMOYO_TRANSITION_CONTROL_KEEP) {
domainname = data;
data = NULL;
}
return tomoyo_update_transition_control_entry(domainname, data, type,
is_delete);
}
/**
* tomoyo_transition_type - Get domain transition type.
*
* @domainname: The name of domain.
* @program: The name of program.
*
* Returns TOMOYO_TRANSITION_CONTROL_INITIALIZE if executing @program
* reinitializes domain transition, TOMOYO_TRANSITION_CONTROL_KEEP if executing
* @program suppresses domain transition, others otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static u8 tomoyo_transition_type(const struct tomoyo_path_info *domainname,
const struct tomoyo_path_info *program)
{
const struct tomoyo_transition_control *ptr;
const char *last_name = tomoyo_last_word(domainname->name);
u8 type;
for (type = 0; type < TOMOYO_MAX_TRANSITION_TYPE; type++) {
next:
list_for_each_entry_rcu(ptr, &tomoyo_policy_list
[TOMOYO_ID_TRANSITION_CONTROL],
head.list) {
if (ptr->head.is_deleted || ptr->type != type)
continue;
if (ptr->domainname) {
if (!ptr->is_last_name) {
if (ptr->domainname != domainname)
continue;
} else {
/*
* Use direct strcmp() since this is
* unlikely used.
*/
if (strcmp(ptr->domainname->name,
last_name))
continue;
}
}
if (ptr->program &&
tomoyo_pathcmp(ptr->program, program))
continue;
if (type == TOMOYO_TRANSITION_CONTROL_NO_INITIALIZE) {
/*
* Do not check for initialize_domain if
* no_initialize_domain matched.
*/
type = TOMOYO_TRANSITION_CONTROL_NO_KEEP;
goto next;
}
goto done;
}
}
done:
return type;
}
static bool tomoyo_same_aggregator(const struct tomoyo_acl_head *a,
const struct tomoyo_acl_head *b)
{
const struct tomoyo_aggregator *p1 = container_of(a, typeof(*p1), head);
const struct tomoyo_aggregator *p2 = container_of(b, typeof(*p2), head);
return p1->original_name == p2->original_name &&
p1->aggregated_name == p2->aggregated_name;
}
/**
* tomoyo_update_aggregator_entry - Update "struct tomoyo_aggregator" list.
*
* @original_name: The original program's name.
* @aggregated_name: The program name to use.
* @is_delete: True if it is a delete request.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_update_aggregator_entry(const char *original_name,
const char *aggregated_name,
const bool is_delete)
{
struct tomoyo_aggregator e = { };
int error = is_delete ? -ENOENT : -ENOMEM;
if (!tomoyo_correct_path(original_name) ||
!tomoyo_correct_path(aggregated_name))
return -EINVAL;
e.original_name = tomoyo_get_name(original_name);
e.aggregated_name = tomoyo_get_name(aggregated_name);
if (!e.original_name || !e.aggregated_name ||
e.aggregated_name->is_patterned) /* No patterns allowed. */
goto out;
error = tomoyo_update_policy(&e.head, sizeof(e), is_delete,
&tomoyo_policy_list[TOMOYO_ID_AGGREGATOR],
tomoyo_same_aggregator);
out:
tomoyo_put_name(e.original_name);
tomoyo_put_name(e.aggregated_name);
return error;
}
/**
* tomoyo_write_aggregator - Write "struct tomoyo_aggregator" list.
*
* @data: String to parse.
* @is_delete: True if it is a delete request.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_write_aggregator(char *data, const bool is_delete)
{
char *cp = strchr(data, ' ');
if (!cp)
return -EINVAL;
*cp++ = '\0';
return tomoyo_update_aggregator_entry(data, cp, is_delete);
}
/**
* tomoyo_assign_domain - Create a domain.
*
* @domainname: The name of domain.
* @profile: Profile number to assign if the domain was newly created.
*
* Returns pointer to "struct tomoyo_domain_info" on success, NULL otherwise.
*
* Caller holds tomoyo_read_lock().
*/
struct tomoyo_domain_info *tomoyo_assign_domain(const char *domainname,
const u8 profile)
{
struct tomoyo_domain_info *entry;
struct tomoyo_domain_info *domain = NULL;
const struct tomoyo_path_info *saved_domainname;
bool found = false;
if (!tomoyo_correct_domain(domainname))
return NULL;
saved_domainname = tomoyo_get_name(domainname);
if (!saved_domainname)
return NULL;
entry = kzalloc(sizeof(*entry), GFP_NOFS);
if (mutex_lock_interruptible(&tomoyo_policy_lock))
goto out;
list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
if (domain->is_deleted ||
tomoyo_pathcmp(saved_domainname, domain->domainname))
continue;
found = true;
break;
}
if (!found && tomoyo_memory_ok(entry)) {
INIT_LIST_HEAD(&entry->acl_info_list);
entry->domainname = saved_domainname;
saved_domainname = NULL;
entry->profile = profile;
list_add_tail_rcu(&entry->list, &tomoyo_domain_list);
domain = entry;
entry = NULL;
found = true;
}
mutex_unlock(&tomoyo_policy_lock);
out:
tomoyo_put_name(saved_domainname);
kfree(entry);
return found ? domain : NULL;
}
/**
* tomoyo_find_next_domain - Find a domain.
*
* @bprm: Pointer to "struct linux_binprm".
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_find_next_domain(struct linux_binprm *bprm)
{
struct tomoyo_request_info r;
char *tmp = kzalloc(TOMOYO_EXEC_TMPSIZE, GFP_NOFS);
struct tomoyo_domain_info *old_domain = tomoyo_domain();
struct tomoyo_domain_info *domain = NULL;
const char *original_name = bprm->filename;
u8 mode;
bool is_enforce;
int retval = -ENOMEM;
bool need_kfree = false;
struct tomoyo_path_info rn = { }; /* real name */
mode = tomoyo_init_request_info(&r, NULL, TOMOYO_MAC_FILE_EXECUTE);
is_enforce = (mode == TOMOYO_CONFIG_ENFORCING);
if (!tmp)
goto out;
retry:
if (need_kfree) {
kfree(rn.name);
need_kfree = false;
}
/* Get symlink's pathname of program. */
retval = -ENOENT;
rn.name = tomoyo_realpath_nofollow(original_name);
if (!rn.name)
goto out;
tomoyo_fill_path_info(&rn);
need_kfree = true;
/* Check 'aggregator' directive. */
{
struct tomoyo_aggregator *ptr;
list_for_each_entry_rcu(ptr, &tomoyo_policy_list
[TOMOYO_ID_AGGREGATOR], head.list) {
if (ptr->head.is_deleted ||
!tomoyo_path_matches_pattern(&rn,
ptr->original_name))
continue;
kfree(rn.name);
need_kfree = false;
/* This is OK because it is read only. */
rn = *ptr->aggregated_name;
break;
}
}
/* Check execute permission. */
retval = tomoyo_path_permission(&r, TOMOYO_TYPE_EXECUTE, &rn);
if (retval == TOMOYO_RETRY_REQUEST)
goto retry;
if (retval < 0)
goto out;
/*
* To be able to specify domainnames with wildcards, use the
* pathname specified in the policy (which may contain
* wildcard) rather than the pathname passed to execve()
* (which never contains wildcard).
*/
if (r.param.path.matched_path) {
if (need_kfree)
kfree(rn.name);
need_kfree = false;
/* This is OK because it is read only. */
rn = *r.param.path.matched_path;
}
/* Calculate domain to transit to. */
switch (tomoyo_transition_type(old_domain->domainname, &rn)) {
case TOMOYO_TRANSITION_CONTROL_INITIALIZE:
/* Transit to the child of tomoyo_kernel_domain domain. */
snprintf(tmp, TOMOYO_EXEC_TMPSIZE - 1, TOMOYO_ROOT_NAME " "
"%s", rn.name);
break;
case TOMOYO_TRANSITION_CONTROL_KEEP:
/* Keep current domain. */
domain = old_domain;
break;
default:
if (old_domain == &tomoyo_kernel_domain &&
!tomoyo_policy_loaded) {
/*
* Needn't to transit from kernel domain before
* starting /sbin/init. But transit from kernel domain
* if executing initializers because they might start
* before /sbin/init.
*/
domain = old_domain;
} else {
/* Normal domain transition. */
snprintf(tmp, TOMOYO_EXEC_TMPSIZE - 1, "%s %s",
old_domain->domainname->name, rn.name);
}
break;
}
if (domain || strlen(tmp) >= TOMOYO_EXEC_TMPSIZE - 10)
goto done;
domain = tomoyo_find_domain(tmp);
if (domain)
goto done;
if (is_enforce) {
int error = tomoyo_supervisor(&r, "# wants to create domain\n"
"%s\n", tmp);
if (error == TOMOYO_RETRY_REQUEST)
goto retry;
if (error < 0)
goto done;
}
domain = tomoyo_assign_domain(tmp, old_domain->profile);
done:
if (domain)
goto out;
printk(KERN_WARNING "TOMOYO-ERROR: Domain '%s' not defined.\n", tmp);
if (is_enforce)
retval = -EPERM;
else
old_domain->transition_failed = true;
out:
if (!domain)
domain = old_domain;
/* Update reference count on "struct tomoyo_domain_info". */
atomic_inc(&domain->users);
bprm->cred->security = domain;
if (need_kfree)
kfree(rn.name);
kfree(tmp);
return retval;
}
| gpl-2.0 |
Snuzzo/max_od | sound/soc/codecs/wm8955.c | 3079 | 28698 | /*
* wm8955.c -- WM8955 ALSA SoC Audio driver
*
* Copyright 2009 Wolfson Microelectronics plc
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include <sound/wm8955.h>
#include "wm8955.h"
#define WM8955_NUM_SUPPLIES 4
static const char *wm8955_supply_names[WM8955_NUM_SUPPLIES] = {
"DCVDD",
"DBVDD",
"HPVDD",
"AVDD",
};
/* codec private data */
struct wm8955_priv {
enum snd_soc_control_type control_type;
unsigned int mclk_rate;
int deemph;
int fs;
struct regulator_bulk_data supplies[WM8955_NUM_SUPPLIES];
};
static const u16 wm8955_reg[WM8955_MAX_REGISTER + 1] = {
0x0000, /* R0 */
0x0000, /* R1 */
0x0079, /* R2 - LOUT1 volume */
0x0079, /* R3 - ROUT1 volume */
0x0000, /* R4 */
0x0008, /* R5 - DAC Control */
0x0000, /* R6 */
0x000A, /* R7 - Audio Interface */
0x0000, /* R8 - Sample Rate */
0x0000, /* R9 */
0x00FF, /* R10 - Left DAC volume */
0x00FF, /* R11 - Right DAC volume */
0x000F, /* R12 - Bass control */
0x000F, /* R13 - Treble control */
0x0000, /* R14 */
0x0000, /* R15 - Reset */
0x0000, /* R16 */
0x0000, /* R17 */
0x0000, /* R18 */
0x0000, /* R19 */
0x0000, /* R20 */
0x0000, /* R21 */
0x0000, /* R22 */
0x00C1, /* R23 - Additional control (1) */
0x0000, /* R24 - Additional control (2) */
0x0000, /* R25 - Power Management (1) */
0x0000, /* R26 - Power Management (2) */
0x0000, /* R27 - Additional Control (3) */
0x0000, /* R28 */
0x0000, /* R29 */
0x0000, /* R30 */
0x0000, /* R31 */
0x0000, /* R32 */
0x0000, /* R33 */
0x0050, /* R34 - Left out Mix (1) */
0x0050, /* R35 - Left out Mix (2) */
0x0050, /* R36 - Right out Mix (1) */
0x0050, /* R37 - Right Out Mix (2) */
0x0050, /* R38 - Mono out Mix (1) */
0x0050, /* R39 - Mono out Mix (2) */
0x0079, /* R40 - LOUT2 volume */
0x0079, /* R41 - ROUT2 volume */
0x0079, /* R42 - MONOOUT volume */
0x0000, /* R43 - Clocking / PLL */
0x0103, /* R44 - PLL Control 1 */
0x0024, /* R45 - PLL Control 2 */
0x01BA, /* R46 - PLL Control 3 */
0x0000, /* R47 */
0x0000, /* R48 */
0x0000, /* R49 */
0x0000, /* R50 */
0x0000, /* R51 */
0x0000, /* R52 */
0x0000, /* R53 */
0x0000, /* R54 */
0x0000, /* R55 */
0x0000, /* R56 */
0x0000, /* R57 */
0x0000, /* R58 */
0x0000, /* R59 - PLL Control 4 */
};
static int wm8955_reset(struct snd_soc_codec *codec)
{
return snd_soc_write(codec, WM8955_RESET, 0);
}
struct pll_factors {
int n;
int k;
int outdiv;
};
/* The size in bits of the FLL divide multiplied by 10
* to allow rounding later */
#define FIXED_FLL_SIZE ((1 << 22) * 10)
static int wm8995_pll_factors(struct device *dev,
int Fref, int Fout, struct pll_factors *pll)
{
u64 Kpart;
unsigned int K, Ndiv, Nmod, target;
dev_dbg(dev, "Fref=%u Fout=%u\n", Fref, Fout);
/* The oscilator should run at should be 90-100MHz, and
* there's a divide by 4 plus an optional divide by 2 in the
* output path to generate the system clock. The clock table
* is sortd so we should always generate a suitable target. */
target = Fout * 4;
if (target < 90000000) {
pll->outdiv = 1;
target *= 2;
} else {
pll->outdiv = 0;
}
WARN_ON(target < 90000000 || target > 100000000);
dev_dbg(dev, "Fvco=%dHz\n", target);
/* Now, calculate N.K */
Ndiv = target / Fref;
pll->n = Ndiv;
Nmod = target % Fref;
dev_dbg(dev, "Nmod=%d\n", Nmod);
/* Calculate fractional part - scale up so we can round. */
Kpart = FIXED_FLL_SIZE * (long long)Nmod;
do_div(Kpart, Fref);
K = Kpart & 0xFFFFFFFF;
if ((K % 10) >= 5)
K += 5;
/* Move down to proper range now rounding is done */
pll->k = K / 10;
dev_dbg(dev, "N=%x K=%x OUTDIV=%x\n", pll->n, pll->k, pll->outdiv);
return 0;
}
/* Lookup table specifying SRATE (table 25 in datasheet); some of the
* output frequencies have been rounded to the standard frequencies
* they are intended to match where the error is slight. */
static struct {
int mclk;
int fs;
int usb;
int sr;
} clock_cfgs[] = {
{ 18432000, 8000, 0, 3, },
{ 18432000, 12000, 0, 9, },
{ 18432000, 16000, 0, 11, },
{ 18432000, 24000, 0, 29, },
{ 18432000, 32000, 0, 13, },
{ 18432000, 48000, 0, 1, },
{ 18432000, 96000, 0, 15, },
{ 16934400, 8018, 0, 19, },
{ 16934400, 11025, 0, 25, },
{ 16934400, 22050, 0, 27, },
{ 16934400, 44100, 0, 17, },
{ 16934400, 88200, 0, 31, },
{ 12000000, 8000, 1, 2, },
{ 12000000, 11025, 1, 25, },
{ 12000000, 12000, 1, 8, },
{ 12000000, 16000, 1, 10, },
{ 12000000, 22050, 1, 27, },
{ 12000000, 24000, 1, 28, },
{ 12000000, 32000, 1, 12, },
{ 12000000, 44100, 1, 17, },
{ 12000000, 48000, 1, 0, },
{ 12000000, 88200, 1, 31, },
{ 12000000, 96000, 1, 14, },
{ 12288000, 8000, 0, 2, },
{ 12288000, 12000, 0, 8, },
{ 12288000, 16000, 0, 10, },
{ 12288000, 24000, 0, 28, },
{ 12288000, 32000, 0, 12, },
{ 12288000, 48000, 0, 0, },
{ 12288000, 96000, 0, 14, },
{ 12289600, 8018, 0, 18, },
{ 12289600, 11025, 0, 24, },
{ 12289600, 22050, 0, 26, },
{ 11289600, 44100, 0, 16, },
{ 11289600, 88200, 0, 31, },
};
static int wm8955_configure_clocking(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int i, ret, val;
int clocking = 0;
int srate = 0;
int sr = -1;
struct pll_factors pll;
/* If we're not running a sample rate currently just pick one */
if (wm8955->fs == 0)
wm8955->fs = 8000;
/* Can we generate an exact output? */
for (i = 0; i < ARRAY_SIZE(clock_cfgs); i++) {
if (wm8955->fs != clock_cfgs[i].fs)
continue;
sr = i;
if (wm8955->mclk_rate == clock_cfgs[i].mclk)
break;
}
/* We should never get here with an unsupported sample rate */
if (sr == -1) {
dev_err(codec->dev, "Sample rate %dHz unsupported\n",
wm8955->fs);
WARN_ON(sr == -1);
return -EINVAL;
}
if (i == ARRAY_SIZE(clock_cfgs)) {
/* If we can't generate the right clock from MCLK then
* we should configure the PLL to supply us with an
* appropriate clock.
*/
clocking |= WM8955_MCLKSEL;
/* Use the last divider configuration we saw for the
* sample rate. */
ret = wm8995_pll_factors(codec->dev, wm8955->mclk_rate,
clock_cfgs[sr].mclk, &pll);
if (ret != 0) {
dev_err(codec->dev,
"Unable to generate %dHz from %dHz MCLK\n",
wm8955->fs, wm8955->mclk_rate);
return -EINVAL;
}
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_1,
WM8955_N_MASK | WM8955_K_21_18_MASK,
(pll.n << WM8955_N_SHIFT) |
pll.k >> 18);
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_2,
WM8955_K_17_9_MASK,
(pll.k >> 9) & WM8955_K_17_9_MASK);
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_2,
WM8955_K_8_0_MASK,
pll.k & WM8955_K_8_0_MASK);
if (pll.k)
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_4,
WM8955_KEN, WM8955_KEN);
else
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_4,
WM8955_KEN, 0);
if (pll.outdiv)
val = WM8955_PLL_RB | WM8955_PLLOUTDIV2;
else
val = WM8955_PLL_RB;
/* Now start the PLL running */
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_PLL_RB | WM8955_PLLOUTDIV2, val);
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_PLLEN, WM8955_PLLEN);
}
srate = clock_cfgs[sr].usb | (clock_cfgs[sr].sr << WM8955_SR_SHIFT);
snd_soc_update_bits(codec, WM8955_SAMPLE_RATE,
WM8955_USB | WM8955_SR_MASK, srate);
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_MCLKSEL, clocking);
return 0;
}
static int wm8955_sysclk(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int ret = 0;
/* Always disable the clocks - if we're doing reconfiguration this
* avoids misclocking.
*/
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_DIGENB, 0);
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_PLL_RB | WM8955_PLLEN, 0);
switch (event) {
case SND_SOC_DAPM_POST_PMD:
break;
case SND_SOC_DAPM_PRE_PMU:
ret = wm8955_configure_clocking(codec);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int deemph_settings[] = { 0, 32000, 44100, 48000 };
static int wm8955_set_deemph(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int val, i, best;
/* If we're using deemphasis select the nearest available sample
* rate.
*/
if (wm8955->deemph) {
best = 1;
for (i = 2; i < ARRAY_SIZE(deemph_settings); i++) {
if (abs(deemph_settings[i] - wm8955->fs) <
abs(deemph_settings[best] - wm8955->fs))
best = i;
}
val = best << WM8955_DEEMPH_SHIFT;
} else {
val = 0;
}
dev_dbg(codec->dev, "Set deemphasis %d\n", val);
return snd_soc_update_bits(codec, WM8955_DAC_CONTROL,
WM8955_DEEMPH_MASK, val);
}
static int wm8955_get_deemph(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
ucontrol->value.enumerated.item[0] = wm8955->deemph;
return 0;
}
static int wm8955_put_deemph(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int deemph = ucontrol->value.enumerated.item[0];
if (deemph > 1)
return -EINVAL;
wm8955->deemph = deemph;
return wm8955_set_deemph(codec);
}
static const char *bass_mode_text[] = {
"Linear", "Adaptive",
};
static const struct soc_enum bass_mode =
SOC_ENUM_SINGLE(WM8955_BASS_CONTROL, 7, 2, bass_mode_text);
static const char *bass_cutoff_text[] = {
"Low", "High"
};
static const struct soc_enum bass_cutoff =
SOC_ENUM_SINGLE(WM8955_BASS_CONTROL, 6, 2, bass_cutoff_text);
static const char *treble_cutoff_text[] = {
"High", "Low"
};
static const struct soc_enum treble_cutoff =
SOC_ENUM_SINGLE(WM8955_TREBLE_CONTROL, 6, 2, treble_cutoff_text);
static const DECLARE_TLV_DB_SCALE(digital_tlv, -12750, 50, 1);
static const DECLARE_TLV_DB_SCALE(atten_tlv, -600, 600, 0);
static const DECLARE_TLV_DB_SCALE(bypass_tlv, -1500, 300, 0);
static const DECLARE_TLV_DB_SCALE(mono_tlv, -2100, 300, 0);
static const DECLARE_TLV_DB_SCALE(out_tlv, -12100, 100, 1);
static const DECLARE_TLV_DB_SCALE(treble_tlv, -1200, 150, 1);
static const struct snd_kcontrol_new wm8955_snd_controls[] = {
SOC_DOUBLE_R_TLV("Digital Playback Volume", WM8955_LEFT_DAC_VOLUME,
WM8955_RIGHT_DAC_VOLUME, 0, 255, 0, digital_tlv),
SOC_SINGLE_TLV("Playback Attenuation Volume", WM8955_DAC_CONTROL, 7, 1, 1,
atten_tlv),
SOC_SINGLE_BOOL_EXT("DAC Deemphasis Switch", 0,
wm8955_get_deemph, wm8955_put_deemph),
SOC_ENUM("Bass Mode", bass_mode),
SOC_ENUM("Bass Cutoff", bass_cutoff),
SOC_SINGLE("Bass Volume", WM8955_BASS_CONTROL, 0, 15, 1),
SOC_ENUM("Treble Cutoff", treble_cutoff),
SOC_SINGLE_TLV("Treble Volume", WM8955_TREBLE_CONTROL, 0, 14, 1, treble_tlv),
SOC_SINGLE_TLV("Left Bypass Volume", WM8955_LEFT_OUT_MIX_1, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Left Mono Volume", WM8955_LEFT_OUT_MIX_2, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Right Mono Volume", WM8955_RIGHT_OUT_MIX_1, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Right Bypass Volume", WM8955_RIGHT_OUT_MIX_2, 4, 7, 1,
bypass_tlv),
/* Not a stereo pair so they line up with the DAPM switches */
SOC_SINGLE_TLV("Mono Left Bypass Volume", WM8955_MONO_OUT_MIX_1, 4, 7, 1,
mono_tlv),
SOC_SINGLE_TLV("Mono Right Bypass Volume", WM8955_MONO_OUT_MIX_2, 4, 7, 1,
mono_tlv),
SOC_DOUBLE_R_TLV("Headphone Volume", WM8955_LOUT1_VOLUME,
WM8955_ROUT1_VOLUME, 0, 127, 0, out_tlv),
SOC_DOUBLE_R("Headphone ZC Switch", WM8955_LOUT1_VOLUME,
WM8955_ROUT1_VOLUME, 7, 1, 0),
SOC_DOUBLE_R_TLV("Speaker Volume", WM8955_LOUT2_VOLUME,
WM8955_ROUT2_VOLUME, 0, 127, 0, out_tlv),
SOC_DOUBLE_R("Speaker ZC Switch", WM8955_LOUT2_VOLUME,
WM8955_ROUT2_VOLUME, 7, 1, 0),
SOC_SINGLE_TLV("Mono Volume", WM8955_MONOOUT_VOLUME, 0, 127, 0, out_tlv),
SOC_SINGLE("Mono ZC Switch", WM8955_MONOOUT_VOLUME, 7, 1, 0),
};
static const struct snd_kcontrol_new lmixer[] = {
SOC_DAPM_SINGLE("Playback Switch", WM8955_LEFT_OUT_MIX_1, 8, 1, 0),
SOC_DAPM_SINGLE("Bypass Switch", WM8955_LEFT_OUT_MIX_1, 7, 1, 0),
SOC_DAPM_SINGLE("Right Playback Switch", WM8955_LEFT_OUT_MIX_2, 8, 1, 0),
SOC_DAPM_SINGLE("Mono Switch", WM8955_LEFT_OUT_MIX_2, 7, 1, 0),
};
static const struct snd_kcontrol_new rmixer[] = {
SOC_DAPM_SINGLE("Left Playback Switch", WM8955_RIGHT_OUT_MIX_1, 8, 1, 0),
SOC_DAPM_SINGLE("Mono Switch", WM8955_RIGHT_OUT_MIX_1, 7, 1, 0),
SOC_DAPM_SINGLE("Playback Switch", WM8955_RIGHT_OUT_MIX_2, 8, 1, 0),
SOC_DAPM_SINGLE("Bypass Switch", WM8955_RIGHT_OUT_MIX_2, 7, 1, 0),
};
static const struct snd_kcontrol_new mmixer[] = {
SOC_DAPM_SINGLE("Left Playback Switch", WM8955_MONO_OUT_MIX_1, 8, 1, 0),
SOC_DAPM_SINGLE("Left Bypass Switch", WM8955_MONO_OUT_MIX_1, 7, 1, 0),
SOC_DAPM_SINGLE("Right Playback Switch", WM8955_MONO_OUT_MIX_2, 8, 1, 0),
SOC_DAPM_SINGLE("Right Bypass Switch", WM8955_MONO_OUT_MIX_2, 7, 1, 0),
};
static const struct snd_soc_dapm_widget wm8955_dapm_widgets[] = {
SND_SOC_DAPM_INPUT("MONOIN-"),
SND_SOC_DAPM_INPUT("MONOIN+"),
SND_SOC_DAPM_INPUT("LINEINR"),
SND_SOC_DAPM_INPUT("LINEINL"),
SND_SOC_DAPM_PGA("Mono Input", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("SYSCLK", WM8955_POWER_MANAGEMENT_1, 0, 1, wm8955_sysclk,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("TSDEN", WM8955_ADDITIONAL_CONTROL_1, 8, 0, NULL, 0),
SND_SOC_DAPM_DAC("DACL", "Playback", WM8955_POWER_MANAGEMENT_2, 8, 0),
SND_SOC_DAPM_DAC("DACR", "Playback", WM8955_POWER_MANAGEMENT_2, 7, 0),
SND_SOC_DAPM_PGA("LOUT1 PGA", WM8955_POWER_MANAGEMENT_2, 6, 0, NULL, 0),
SND_SOC_DAPM_PGA("ROUT1 PGA", WM8955_POWER_MANAGEMENT_2, 5, 0, NULL, 0),
SND_SOC_DAPM_PGA("LOUT2 PGA", WM8955_POWER_MANAGEMENT_2, 4, 0, NULL, 0),
SND_SOC_DAPM_PGA("ROUT2 PGA", WM8955_POWER_MANAGEMENT_2, 3, 0, NULL, 0),
SND_SOC_DAPM_PGA("MOUT PGA", WM8955_POWER_MANAGEMENT_2, 2, 0, NULL, 0),
SND_SOC_DAPM_PGA("OUT3 PGA", WM8955_POWER_MANAGEMENT_2, 1, 0, NULL, 0),
/* The names are chosen to make the control names nice */
SND_SOC_DAPM_MIXER("Left", SND_SOC_NOPM, 0, 0,
lmixer, ARRAY_SIZE(lmixer)),
SND_SOC_DAPM_MIXER("Right", SND_SOC_NOPM, 0, 0,
rmixer, ARRAY_SIZE(rmixer)),
SND_SOC_DAPM_MIXER("Mono", SND_SOC_NOPM, 0, 0,
mmixer, ARRAY_SIZE(mmixer)),
SND_SOC_DAPM_OUTPUT("LOUT1"),
SND_SOC_DAPM_OUTPUT("ROUT1"),
SND_SOC_DAPM_OUTPUT("LOUT2"),
SND_SOC_DAPM_OUTPUT("ROUT2"),
SND_SOC_DAPM_OUTPUT("MONOOUT"),
SND_SOC_DAPM_OUTPUT("OUT3"),
};
static const struct snd_soc_dapm_route wm8955_intercon[] = {
{ "DACL", NULL, "SYSCLK" },
{ "DACR", NULL, "SYSCLK" },
{ "Mono Input", NULL, "MONOIN-" },
{ "Mono Input", NULL, "MONOIN+" },
{ "Left", "Playback Switch", "DACL" },
{ "Left", "Right Playback Switch", "DACR" },
{ "Left", "Bypass Switch", "LINEINL" },
{ "Left", "Mono Switch", "Mono Input" },
{ "Right", "Playback Switch", "DACR" },
{ "Right", "Left Playback Switch", "DACL" },
{ "Right", "Bypass Switch", "LINEINR" },
{ "Right", "Mono Switch", "Mono Input" },
{ "Mono", "Left Playback Switch", "DACL" },
{ "Mono", "Right Playback Switch", "DACR" },
{ "Mono", "Left Bypass Switch", "LINEINL" },
{ "Mono", "Right Bypass Switch", "LINEINR" },
{ "LOUT1 PGA", NULL, "Left" },
{ "LOUT1", NULL, "TSDEN" },
{ "LOUT1", NULL, "LOUT1 PGA" },
{ "ROUT1 PGA", NULL, "Right" },
{ "ROUT1", NULL, "TSDEN" },
{ "ROUT1", NULL, "ROUT1 PGA" },
{ "LOUT2 PGA", NULL, "Left" },
{ "LOUT2", NULL, "TSDEN" },
{ "LOUT2", NULL, "LOUT2 PGA" },
{ "ROUT2 PGA", NULL, "Right" },
{ "ROUT2", NULL, "TSDEN" },
{ "ROUT2", NULL, "ROUT2 PGA" },
{ "MOUT PGA", NULL, "Mono" },
{ "MONOOUT", NULL, "MOUT PGA" },
/* OUT3 not currently implemented */
{ "OUT3", NULL, "OUT3 PGA" },
};
static int wm8955_add_widgets(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_add_controls(codec, wm8955_snd_controls,
ARRAY_SIZE(wm8955_snd_controls));
snd_soc_dapm_new_controls(dapm, wm8955_dapm_widgets,
ARRAY_SIZE(wm8955_dapm_widgets));
snd_soc_dapm_add_routes(dapm, wm8955_intercon,
ARRAY_SIZE(wm8955_intercon));
return 0;
}
static int wm8955_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int ret;
int wl;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
wl = 0;
break;
case SNDRV_PCM_FORMAT_S20_3LE:
wl = 0x4;
break;
case SNDRV_PCM_FORMAT_S24_LE:
wl = 0x8;
break;
case SNDRV_PCM_FORMAT_S32_LE:
wl = 0xc;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, WM8955_AUDIO_INTERFACE,
WM8955_WL_MASK, wl);
wm8955->fs = params_rate(params);
wm8955_set_deemph(codec);
/* If the chip is clocked then disable the clocks and force a
* reconfiguration, otherwise DAPM will power up the
* clocks for us later. */
ret = snd_soc_read(codec, WM8955_POWER_MANAGEMENT_1);
if (ret < 0)
return ret;
if (ret & WM8955_DIGENB) {
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_DIGENB, 0);
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_PLL_RB | WM8955_PLLEN, 0);
wm8955_configure_clocking(codec);
}
return 0;
}
static int wm8955_set_sysclk(struct snd_soc_dai *dai, int clk_id,
unsigned int freq, int dir)
{
struct snd_soc_codec *codec = dai->codec;
struct wm8955_priv *priv = snd_soc_codec_get_drvdata(codec);
int div;
switch (clk_id) {
case WM8955_CLK_MCLK:
if (freq > 15000000) {
priv->mclk_rate = freq /= 2;
div = WM8955_MCLKDIV2;
} else {
priv->mclk_rate = freq;
div = 0;
}
snd_soc_update_bits(codec, WM8955_SAMPLE_RATE,
WM8955_MCLKDIV2, div);
break;
default:
return -EINVAL;
}
dev_dbg(dai->dev, "Clock source is %d at %uHz\n", clk_id, freq);
return 0;
}
static int wm8955_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct snd_soc_codec *codec = dai->codec;
u16 aif = 0;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
break;
case SND_SOC_DAIFMT_CBM_CFM:
aif |= WM8955_MS;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_DSP_B:
aif |= WM8955_LRP;
case SND_SOC_DAIFMT_DSP_A:
aif |= 0x3;
break;
case SND_SOC_DAIFMT_I2S:
aif |= 0x2;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
aif |= 0x1;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_DSP_A:
case SND_SOC_DAIFMT_DSP_B:
/* frame inversion not valid for DSP modes */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_NF:
aif |= WM8955_BCLKINV;
break;
default:
return -EINVAL;
}
break;
case SND_SOC_DAIFMT_I2S:
case SND_SOC_DAIFMT_RIGHT_J:
case SND_SOC_DAIFMT_LEFT_J:
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
aif |= WM8955_BCLKINV | WM8955_LRP;
break;
case SND_SOC_DAIFMT_IB_NF:
aif |= WM8955_BCLKINV;
break;
case SND_SOC_DAIFMT_NB_IF:
aif |= WM8955_LRP;
break;
default:
return -EINVAL;
}
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, WM8955_AUDIO_INTERFACE,
WM8955_MS | WM8955_FORMAT_MASK | WM8955_BCLKINV |
WM8955_LRP, aif);
return 0;
}
static int wm8955_digital_mute(struct snd_soc_dai *codec_dai, int mute)
{
struct snd_soc_codec *codec = codec_dai->codec;
int val;
if (mute)
val = WM8955_DACMU;
else
val = 0;
snd_soc_update_bits(codec, WM8955_DAC_CONTROL, WM8955_DACMU, val);
return 0;
}
static int wm8955_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
u16 *reg_cache = codec->reg_cache;
int ret, i;
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
/* VMID resistance 2*50k */
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_VMIDSEL_MASK,
0x1 << WM8955_VMIDSEL_SHIFT);
/* Default bias current */
snd_soc_update_bits(codec, WM8955_ADDITIONAL_CONTROL_1,
WM8955_VSEL_MASK,
0x2 << WM8955_VSEL_SHIFT);
break;
case SND_SOC_BIAS_STANDBY:
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) {
ret = regulator_bulk_enable(ARRAY_SIZE(wm8955->supplies),
wm8955->supplies);
if (ret != 0) {
dev_err(codec->dev,
"Failed to enable supplies: %d\n",
ret);
return ret;
}
/* Sync back cached values if they're
* different from the hardware default.
*/
for (i = 0; i < codec->driver->reg_cache_size; i++) {
if (i == WM8955_RESET)
continue;
if (reg_cache[i] == wm8955_reg[i])
continue;
snd_soc_write(codec, i, reg_cache[i]);
}
/* Enable VREF and VMID */
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_VREF |
WM8955_VMIDSEL_MASK,
WM8955_VREF |
0x3 << WM8955_VREF_SHIFT);
/* Let VMID ramp */
msleep(500);
/* High resistance VROI to maintain outputs */
snd_soc_update_bits(codec,
WM8955_ADDITIONAL_CONTROL_3,
WM8955_VROI, WM8955_VROI);
}
/* Maintain VMID with 2*250k */
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_VMIDSEL_MASK,
0x2 << WM8955_VMIDSEL_SHIFT);
/* Minimum bias current */
snd_soc_update_bits(codec, WM8955_ADDITIONAL_CONTROL_1,
WM8955_VSEL_MASK, 0);
break;
case SND_SOC_BIAS_OFF:
/* Low resistance VROI to help discharge */
snd_soc_update_bits(codec,
WM8955_ADDITIONAL_CONTROL_3,
WM8955_VROI, 0);
/* Turn off VMID and VREF */
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_VREF |
WM8955_VMIDSEL_MASK, 0);
regulator_bulk_disable(ARRAY_SIZE(wm8955->supplies),
wm8955->supplies);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define WM8955_RATES SNDRV_PCM_RATE_8000_96000
#define WM8955_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE)
static struct snd_soc_dai_ops wm8955_dai_ops = {
.set_sysclk = wm8955_set_sysclk,
.set_fmt = wm8955_set_fmt,
.hw_params = wm8955_hw_params,
.digital_mute = wm8955_digital_mute,
};
static struct snd_soc_dai_driver wm8955_dai = {
.name = "wm8955-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = WM8955_RATES,
.formats = WM8955_FORMATS,
},
.ops = &wm8955_dai_ops,
};
#ifdef CONFIG_PM
static int wm8955_suspend(struct snd_soc_codec *codec, pm_message_t state)
{
wm8955_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int wm8955_resume(struct snd_soc_codec *codec)
{
wm8955_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
#else
#define wm8955_suspend NULL
#define wm8955_resume NULL
#endif
static int wm8955_probe(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
struct wm8955_pdata *pdata = dev_get_platdata(codec->dev);
u16 *reg_cache = codec->reg_cache;
int ret, i;
ret = snd_soc_codec_set_cache_io(codec, 7, 9, wm8955->control_type);
if (ret != 0) {
dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret);
return ret;
}
for (i = 0; i < ARRAY_SIZE(wm8955->supplies); i++)
wm8955->supplies[i].supply = wm8955_supply_names[i];
ret = regulator_bulk_get(codec->dev, ARRAY_SIZE(wm8955->supplies),
wm8955->supplies);
if (ret != 0) {
dev_err(codec->dev, "Failed to request supplies: %d\n", ret);
return ret;
}
ret = regulator_bulk_enable(ARRAY_SIZE(wm8955->supplies),
wm8955->supplies);
if (ret != 0) {
dev_err(codec->dev, "Failed to enable supplies: %d\n", ret);
goto err_get;
}
ret = wm8955_reset(codec);
if (ret < 0) {
dev_err(codec->dev, "Failed to issue reset: %d\n", ret);
goto err_enable;
}
/* Change some default settings - latch VU and enable ZC */
snd_soc_update_bits(codec, WM8955_LEFT_DAC_VOLUME,
WM8955_LDVU, WM8955_LDVU);
snd_soc_update_bits(codec, WM8955_RIGHT_DAC_VOLUME,
WM8955_RDVU, WM8955_RDVU);
snd_soc_update_bits(codec, WM8955_LOUT1_VOLUME,
WM8955_LO1VU | WM8955_LO1ZC,
WM8955_LO1VU | WM8955_LO1ZC);
snd_soc_update_bits(codec, WM8955_ROUT1_VOLUME,
WM8955_RO1VU | WM8955_RO1ZC,
WM8955_RO1VU | WM8955_RO1ZC);
snd_soc_update_bits(codec, WM8955_LOUT2_VOLUME,
WM8955_LO2VU | WM8955_LO2ZC,
WM8955_LO2VU | WM8955_LO2ZC);
snd_soc_update_bits(codec, WM8955_ROUT2_VOLUME,
WM8955_RO2VU | WM8955_RO2ZC,
WM8955_RO2VU | WM8955_RO2ZC);
snd_soc_update_bits(codec, WM8955_MONOOUT_VOLUME,
WM8955_MOZC, WM8955_MOZC);
/* Also enable adaptive bass boost by default */
snd_soc_update_bits(codec, WM8955_BASS_CONTROL, WM8955_BB, WM8955_BB);
/* Set platform data values */
if (pdata) {
if (pdata->out2_speaker)
reg_cache[WM8955_ADDITIONAL_CONTROL_2]
|= WM8955_ROUT2INV;
if (pdata->monoin_diff)
reg_cache[WM8955_MONO_OUT_MIX_1]
|= WM8955_DMEN;
}
wm8955_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
/* Bias level configuration will have done an extra enable */
regulator_bulk_disable(ARRAY_SIZE(wm8955->supplies), wm8955->supplies);
wm8955_add_widgets(codec);
return 0;
err_enable:
regulator_bulk_disable(ARRAY_SIZE(wm8955->supplies), wm8955->supplies);
err_get:
regulator_bulk_free(ARRAY_SIZE(wm8955->supplies), wm8955->supplies);
return ret;
}
static int wm8955_remove(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
wm8955_set_bias_level(codec, SND_SOC_BIAS_OFF);
regulator_bulk_free(ARRAY_SIZE(wm8955->supplies), wm8955->supplies);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_wm8955 = {
.probe = wm8955_probe,
.remove = wm8955_remove,
.suspend = wm8955_suspend,
.resume = wm8955_resume,
.set_bias_level = wm8955_set_bias_level,
.reg_cache_size = ARRAY_SIZE(wm8955_reg),
.reg_word_size = sizeof(u16),
.reg_cache_default = wm8955_reg,
};
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static __devinit int wm8955_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8955_priv *wm8955;
int ret;
wm8955 = kzalloc(sizeof(struct wm8955_priv), GFP_KERNEL);
if (wm8955 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, wm8955);
wm8955->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8955, &wm8955_dai, 1);
if (ret < 0)
kfree(wm8955);
return ret;
}
static __devexit int wm8955_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
kfree(i2c_get_clientdata(client));
return 0;
}
static const struct i2c_device_id wm8955_i2c_id[] = {
{ "wm8955", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8955_i2c_id);
static struct i2c_driver wm8955_i2c_driver = {
.driver = {
.name = "wm8955-codec",
.owner = THIS_MODULE,
},
.probe = wm8955_i2c_probe,
.remove = __devexit_p(wm8955_i2c_remove),
.id_table = wm8955_i2c_id,
};
#endif
static int __init wm8955_modinit(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&wm8955_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8955 I2C driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(wm8955_modinit);
static void __exit wm8955_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&wm8955_i2c_driver);
#endif
}
module_exit(wm8955_exit);
MODULE_DESCRIPTION("ASoC WM8955 driver");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
nitrogen-os-devices/nitrogen_kernel_lge_hammerhead | arch/arm/kernel/sys_arm.c | 3847 | 3470 | /*
* linux/arch/arm/kernel/sys_arm.c
*
* Copyright (C) People who wrote linux/arch/i386/kernel/sys_i386.c
* Copyright (C) 1995, 1996 Russell King.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This file contains various random system calls that
* have a non-standard calling sequence on the Linux/arm
* platform.
*/
#include <linux/export.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/stat.h>
#include <linux/syscalls.h>
#include <linux/mman.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/ipc.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
/* Fork a new task - this creates a new program thread.
* This is called indirectly via a small wrapper
*/
asmlinkage int sys_fork(struct pt_regs *regs)
{
#ifdef CONFIG_MMU
return do_fork(SIGCHLD, regs->ARM_sp, regs, 0, NULL, NULL);
#else
/* can not support in nommu mode */
return(-EINVAL);
#endif
}
/* Clone a task - this clones the calling program thread.
* This is called indirectly via a small wrapper
*/
asmlinkage int sys_clone(unsigned long clone_flags, unsigned long newsp,
int __user *parent_tidptr, int tls_val,
int __user *child_tidptr, struct pt_regs *regs)
{
if (!newsp)
newsp = regs->ARM_sp;
return do_fork(clone_flags, newsp, regs, 0, parent_tidptr, child_tidptr);
}
asmlinkage int sys_vfork(struct pt_regs *regs)
{
return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs->ARM_sp, regs, 0, NULL, NULL);
}
/* sys_execve() executes a new program.
* This is called indirectly via a small wrapper
*/
asmlinkage int sys_execve(const char __user *filenamei,
const char __user *const __user *argv,
const char __user *const __user *envp, struct pt_regs *regs)
{
int error;
char * filename;
filename = getname(filenamei);
error = PTR_ERR(filename);
if (IS_ERR(filename))
goto out;
error = do_execve(filename, argv, envp, regs);
putname(filename);
out:
return error;
}
int kernel_execve(const char *filename,
const char *const argv[],
const char *const envp[])
{
struct pt_regs regs;
int ret;
memset(®s, 0, sizeof(struct pt_regs));
ret = do_execve(filename,
(const char __user *const __user *)argv,
(const char __user *const __user *)envp, ®s);
if (ret < 0)
goto out;
/*
* Save argc to the register structure for userspace.
*/
regs.ARM_r0 = ret;
/*
* We were successful. We won't be returning to our caller, but
* instead to user space by manipulating the kernel stack.
*/
asm( "add r0, %0, %1\n\t"
"mov r1, %2\n\t"
"mov r2, %3\n\t"
"bl memmove\n\t" /* copy regs to top of stack */
"mov r8, #0\n\t" /* not a syscall */
"mov r9, %0\n\t" /* thread structure */
"mov sp, r0\n\t" /* reposition stack pointer */
"b ret_to_user"
:
: "r" (current_thread_info()),
"Ir" (THREAD_START_SP - sizeof(regs)),
"r" (®s),
"Ir" (sizeof(regs))
: "r0", "r1", "r2", "r3", "r8", "r9", "ip", "lr", "memory");
out:
return ret;
}
EXPORT_SYMBOL(kernel_execve);
/*
* Since loff_t is a 64 bit type we avoid a lot of ABI hassle
* with a different argument ordering.
*/
asmlinkage long sys_arm_fadvise64_64(int fd, int advice,
loff_t offset, loff_t len)
{
return sys_fadvise64_64(fd, offset, len, advice);
}
| gpl-2.0 |
agrabren/android_kernel_htc_shooter_u | drivers/video/cirrusfb.c | 4103 | 77633 | /*
* drivers/video/cirrusfb.c - driver for Cirrus Logic chipsets
*
* Copyright 1999-2001 Jeff Garzik <jgarzik@pobox.com>
*
* Contributors (thanks, all!)
*
* David Eger:
* Overhaul for Linux 2.6
*
* Jeff Rugen:
* Major contributions; Motorola PowerStack (PPC and PCI) support,
* GD54xx, 1280x1024 mode support, change MCLK based on VCLK.
*
* Geert Uytterhoeven:
* Excellent code review.
*
* Lars Hecking:
* Amiga updates and testing.
*
* Original cirrusfb author: Frank Neumann
*
* Based on retz3fb.c and cirrusfb.c:
* Copyright (C) 1997 Jes Sorensen
* Copyright (C) 1996 Frank Neumann
*
***************************************************************
*
* Format this code with GNU indent '-kr -i8 -pcs' options.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <asm/pgtable.h>
#ifdef CONFIG_ZORRO
#include <linux/zorro.h>
#endif
#ifdef CONFIG_PCI
#include <linux/pci.h>
#endif
#ifdef CONFIG_AMIGA
#include <asm/amigahw.h>
#endif
#ifdef CONFIG_PPC_PREP
#include <asm/machdep.h>
#define isPReP machine_is(prep)
#else
#define isPReP 0
#endif
#include <video/vga.h>
#include <video/cirrus.h>
/*****************************************************************
*
* debugging and utility macros
*
*/
/* disable runtime assertions? */
/* #define CIRRUSFB_NDEBUG */
/* debugging assertions */
#ifndef CIRRUSFB_NDEBUG
#define assert(expr) \
if (!(expr)) { \
printk("Assertion failed! %s,%s,%s,line=%d\n", \
#expr, __FILE__, __func__, __LINE__); \
}
#else
#define assert(expr)
#endif
#define MB_ (1024 * 1024)
/*****************************************************************
*
* chipset information
*
*/
/* board types */
enum cirrus_board {
BT_NONE = 0,
BT_SD64, /* GD5434 */
BT_PICCOLO, /* GD5426 */
BT_PICASSO, /* GD5426 or GD5428 */
BT_SPECTRUM, /* GD5426 or GD5428 */
BT_PICASSO4, /* GD5446 */
BT_ALPINE, /* GD543x/4x */
BT_GD5480,
BT_LAGUNA, /* GD5462/64 */
BT_LAGUNAB, /* GD5465 */
};
/*
* per-board-type information, used for enumerating and abstracting
* chip-specific information
* NOTE: MUST be in the same order as enum cirrus_board in order to
* use direct indexing on this array
* NOTE: '__initdata' cannot be used as some of this info
* is required at runtime. Maybe separate into an init-only and
* a run-time table?
*/
static const struct cirrusfb_board_info_rec {
char *name; /* ASCII name of chipset */
long maxclock[5]; /* maximum video clock */
/* for 1/4bpp, 8bpp 15/16bpp, 24bpp, 32bpp - numbers from xorg code */
bool init_sr07 : 1; /* init SR07 during init_vgachip() */
bool init_sr1f : 1; /* write SR1F during init_vgachip() */
/* construct bit 19 of screen start address */
bool scrn_start_bit19 : 1;
/* initial SR07 value, then for each mode */
unsigned char sr07;
unsigned char sr07_1bpp;
unsigned char sr07_1bpp_mux;
unsigned char sr07_8bpp;
unsigned char sr07_8bpp_mux;
unsigned char sr1f; /* SR1F VGA initial register value */
} cirrusfb_board_info[] = {
[BT_SD64] = {
.name = "CL SD64",
.maxclock = {
/* guess */
/* the SD64/P4 have a higher max. videoclock */
135100, 135100, 85500, 85500, 0
},
.init_sr07 = true,
.init_sr1f = true,
.scrn_start_bit19 = true,
.sr07 = 0xF0,
.sr07_1bpp = 0xF0,
.sr07_1bpp_mux = 0xF6,
.sr07_8bpp = 0xF1,
.sr07_8bpp_mux = 0xF7,
.sr1f = 0x1E
},
[BT_PICCOLO] = {
.name = "CL Piccolo",
.maxclock = {
/* guess */
90000, 90000, 90000, 90000, 90000
},
.init_sr07 = true,
.init_sr1f = true,
.scrn_start_bit19 = false,
.sr07 = 0x80,
.sr07_1bpp = 0x80,
.sr07_8bpp = 0x81,
.sr1f = 0x22
},
[BT_PICASSO] = {
.name = "CL Picasso",
.maxclock = {
/* guess */
90000, 90000, 90000, 90000, 90000
},
.init_sr07 = true,
.init_sr1f = true,
.scrn_start_bit19 = false,
.sr07 = 0x20,
.sr07_1bpp = 0x20,
.sr07_8bpp = 0x21,
.sr1f = 0x22
},
[BT_SPECTRUM] = {
.name = "CL Spectrum",
.maxclock = {
/* guess */
90000, 90000, 90000, 90000, 90000
},
.init_sr07 = true,
.init_sr1f = true,
.scrn_start_bit19 = false,
.sr07 = 0x80,
.sr07_1bpp = 0x80,
.sr07_8bpp = 0x81,
.sr1f = 0x22
},
[BT_PICASSO4] = {
.name = "CL Picasso4",
.maxclock = {
135100, 135100, 85500, 85500, 0
},
.init_sr07 = true,
.init_sr1f = false,
.scrn_start_bit19 = true,
.sr07 = 0xA0,
.sr07_1bpp = 0xA0,
.sr07_1bpp_mux = 0xA6,
.sr07_8bpp = 0xA1,
.sr07_8bpp_mux = 0xA7,
.sr1f = 0
},
[BT_ALPINE] = {
.name = "CL Alpine",
.maxclock = {
/* for the GD5430. GD5446 can do more... */
85500, 85500, 50000, 28500, 0
},
.init_sr07 = true,
.init_sr1f = true,
.scrn_start_bit19 = true,
.sr07 = 0xA0,
.sr07_1bpp = 0xA0,
.sr07_1bpp_mux = 0xA6,
.sr07_8bpp = 0xA1,
.sr07_8bpp_mux = 0xA7,
.sr1f = 0x1C
},
[BT_GD5480] = {
.name = "CL GD5480",
.maxclock = {
135100, 200000, 200000, 135100, 135100
},
.init_sr07 = true,
.init_sr1f = true,
.scrn_start_bit19 = true,
.sr07 = 0x10,
.sr07_1bpp = 0x11,
.sr07_8bpp = 0x11,
.sr1f = 0x1C
},
[BT_LAGUNA] = {
.name = "CL Laguna",
.maxclock = {
/* taken from X11 code */
170000, 170000, 170000, 170000, 135100,
},
.init_sr07 = false,
.init_sr1f = false,
.scrn_start_bit19 = true,
},
[BT_LAGUNAB] = {
.name = "CL Laguna AGP",
.maxclock = {
/* taken from X11 code */
170000, 250000, 170000, 170000, 135100,
},
.init_sr07 = false,
.init_sr1f = false,
.scrn_start_bit19 = true,
}
};
#ifdef CONFIG_PCI
#define CHIP(id, btype) \
{ PCI_VENDOR_ID_CIRRUS, id, PCI_ANY_ID, PCI_ANY_ID, 0, 0, (btype) }
static struct pci_device_id cirrusfb_pci_table[] = {
CHIP(PCI_DEVICE_ID_CIRRUS_5436, BT_ALPINE),
CHIP(PCI_DEVICE_ID_CIRRUS_5434_8, BT_SD64),
CHIP(PCI_DEVICE_ID_CIRRUS_5434_4, BT_SD64),
CHIP(PCI_DEVICE_ID_CIRRUS_5430, BT_ALPINE), /* GD-5440 is same id */
CHIP(PCI_DEVICE_ID_CIRRUS_7543, BT_ALPINE),
CHIP(PCI_DEVICE_ID_CIRRUS_7548, BT_ALPINE),
CHIP(PCI_DEVICE_ID_CIRRUS_5480, BT_GD5480), /* MacPicasso likely */
CHIP(PCI_DEVICE_ID_CIRRUS_5446, BT_PICASSO4), /* Picasso 4 is 5446 */
CHIP(PCI_DEVICE_ID_CIRRUS_5462, BT_LAGUNA), /* CL Laguna */
CHIP(PCI_DEVICE_ID_CIRRUS_5464, BT_LAGUNA), /* CL Laguna 3D */
CHIP(PCI_DEVICE_ID_CIRRUS_5465, BT_LAGUNAB), /* CL Laguna 3DA*/
{ 0, }
};
MODULE_DEVICE_TABLE(pci, cirrusfb_pci_table);
#undef CHIP
#endif /* CONFIG_PCI */
#ifdef CONFIG_ZORRO
static const struct zorro_device_id cirrusfb_zorro_table[] = {
{
.id = ZORRO_PROD_HELFRICH_SD64_RAM,
.driver_data = BT_SD64,
}, {
.id = ZORRO_PROD_HELFRICH_PICCOLO_RAM,
.driver_data = BT_PICCOLO,
}, {
.id = ZORRO_PROD_VILLAGE_TRONIC_PICASSO_II_II_PLUS_RAM,
.driver_data = BT_PICASSO,
}, {
.id = ZORRO_PROD_GVP_EGS_28_24_SPECTRUM_RAM,
.driver_data = BT_SPECTRUM,
}, {
.id = ZORRO_PROD_VILLAGE_TRONIC_PICASSO_IV_Z3,
.driver_data = BT_PICASSO4,
},
{ 0 }
};
MODULE_DEVICE_TABLE(zorro, cirrusfb_zorro_table);
static const struct {
zorro_id id2;
unsigned long size;
} cirrusfb_zorro_table2[] = {
[BT_SD64] = {
.id2 = ZORRO_PROD_HELFRICH_SD64_REG,
.size = 0x400000
},
[BT_PICCOLO] = {
.id2 = ZORRO_PROD_HELFRICH_PICCOLO_REG,
.size = 0x200000
},
[BT_PICASSO] = {
.id2 = ZORRO_PROD_VILLAGE_TRONIC_PICASSO_II_II_PLUS_REG,
.size = 0x200000
},
[BT_SPECTRUM] = {
.id2 = ZORRO_PROD_GVP_EGS_28_24_SPECTRUM_REG,
.size = 0x200000
},
[BT_PICASSO4] = {
.id2 = 0,
.size = 0x400000
}
};
#endif /* CONFIG_ZORRO */
#ifdef CIRRUSFB_DEBUG
enum cirrusfb_dbg_reg_class {
CRT,
SEQ
};
#endif /* CIRRUSFB_DEBUG */
/* info about board */
struct cirrusfb_info {
u8 __iomem *regbase;
u8 __iomem *laguna_mmio;
enum cirrus_board btype;
unsigned char SFR; /* Shadow of special function register */
int multiplexing;
int doubleVCLK;
int blank_mode;
u32 pseudo_palette[16];
void (*unmap)(struct fb_info *info);
};
static int noaccel __devinitdata;
static char *mode_option __devinitdata = "640x480@60";
/****************************************************************************/
/**** BEGIN PROTOTYPES ******************************************************/
/*--- Interface used by the world ------------------------------------------*/
static int cirrusfb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info);
/*--- Internal routines ----------------------------------------------------*/
static void init_vgachip(struct fb_info *info);
static void switch_monitor(struct cirrusfb_info *cinfo, int on);
static void WGen(const struct cirrusfb_info *cinfo,
int regnum, unsigned char val);
static unsigned char RGen(const struct cirrusfb_info *cinfo, int regnum);
static void AttrOn(const struct cirrusfb_info *cinfo);
static void WHDR(const struct cirrusfb_info *cinfo, unsigned char val);
static void WSFR(struct cirrusfb_info *cinfo, unsigned char val);
static void WSFR2(struct cirrusfb_info *cinfo, unsigned char val);
static void WClut(struct cirrusfb_info *cinfo, unsigned char regnum,
unsigned char red, unsigned char green, unsigned char blue);
#if 0
static void RClut(struct cirrusfb_info *cinfo, unsigned char regnum,
unsigned char *red, unsigned char *green,
unsigned char *blue);
#endif
static void cirrusfb_WaitBLT(u8 __iomem *regbase);
static void cirrusfb_BitBLT(u8 __iomem *regbase, int bits_per_pixel,
u_short curx, u_short cury,
u_short destx, u_short desty,
u_short width, u_short height,
u_short line_length);
static void cirrusfb_RectFill(u8 __iomem *regbase, int bits_per_pixel,
u_short x, u_short y,
u_short width, u_short height,
u32 fg_color, u32 bg_color,
u_short line_length, u_char blitmode);
static void bestclock(long freq, int *nom, int *den, int *div);
#ifdef CIRRUSFB_DEBUG
static void cirrusfb_dbg_reg_dump(struct fb_info *info, caddr_t regbase);
static void cirrusfb_dbg_print_regs(struct fb_info *info,
caddr_t regbase,
enum cirrusfb_dbg_reg_class reg_class, ...);
#endif /* CIRRUSFB_DEBUG */
/*** END PROTOTYPES ********************************************************/
/*****************************************************************************/
/*** BEGIN Interface Used by the World ***************************************/
static inline int is_laguna(const struct cirrusfb_info *cinfo)
{
return cinfo->btype == BT_LAGUNA || cinfo->btype == BT_LAGUNAB;
}
static int opencount;
/*--- Open /dev/fbx ---------------------------------------------------------*/
static int cirrusfb_open(struct fb_info *info, int user)
{
if (opencount++ == 0)
switch_monitor(info->par, 1);
return 0;
}
/*--- Close /dev/fbx --------------------------------------------------------*/
static int cirrusfb_release(struct fb_info *info, int user)
{
if (--opencount == 0)
switch_monitor(info->par, 0);
return 0;
}
/**** END Interface used by the World *************************************/
/****************************************************************************/
/**** BEGIN Hardware specific Routines **************************************/
/* Check if the MCLK is not a better clock source */
static int cirrusfb_check_mclk(struct fb_info *info, long freq)
{
struct cirrusfb_info *cinfo = info->par;
long mclk = vga_rseq(cinfo->regbase, CL_SEQR1F) & 0x3f;
/* Read MCLK value */
mclk = (14318 * mclk) >> 3;
dev_dbg(info->device, "Read MCLK of %ld kHz\n", mclk);
/* Determine if we should use MCLK instead of VCLK, and if so, what we
* should divide it by to get VCLK
*/
if (abs(freq - mclk) < 250) {
dev_dbg(info->device, "Using VCLK = MCLK\n");
return 1;
} else if (abs(freq - (mclk / 2)) < 250) {
dev_dbg(info->device, "Using VCLK = MCLK/2\n");
return 2;
}
return 0;
}
static int cirrusfb_check_pixclock(const struct fb_var_screeninfo *var,
struct fb_info *info)
{
long freq;
long maxclock;
struct cirrusfb_info *cinfo = info->par;
unsigned maxclockidx = var->bits_per_pixel >> 3;
/* convert from ps to kHz */
freq = PICOS2KHZ(var->pixclock);
dev_dbg(info->device, "desired pixclock: %ld kHz\n", freq);
maxclock = cirrusfb_board_info[cinfo->btype].maxclock[maxclockidx];
cinfo->multiplexing = 0;
/* If the frequency is greater than we can support, we might be able
* to use multiplexing for the video mode */
if (freq > maxclock) {
dev_err(info->device,
"Frequency greater than maxclock (%ld kHz)\n",
maxclock);
return -EINVAL;
}
/*
* Additional constraint: 8bpp uses DAC clock doubling to allow maximum
* pixel clock
*/
if (var->bits_per_pixel == 8) {
switch (cinfo->btype) {
case BT_ALPINE:
case BT_SD64:
case BT_PICASSO4:
if (freq > 85500)
cinfo->multiplexing = 1;
break;
case BT_GD5480:
if (freq > 135100)
cinfo->multiplexing = 1;
break;
default:
break;
}
}
/* If we have a 1MB 5434, we need to put ourselves in a mode where
* the VCLK is double the pixel clock. */
cinfo->doubleVCLK = 0;
if (cinfo->btype == BT_SD64 && info->fix.smem_len <= MB_ &&
var->bits_per_pixel == 16) {
cinfo->doubleVCLK = 1;
}
return 0;
}
static int cirrusfb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
int yres;
/* memory size in pixels */
unsigned pixels = info->screen_size * 8 / var->bits_per_pixel;
struct cirrusfb_info *cinfo = info->par;
switch (var->bits_per_pixel) {
case 1:
var->red.offset = 0;
var->red.length = 1;
var->green = var->red;
var->blue = var->red;
break;
case 8:
var->red.offset = 0;
var->red.length = 8;
var->green = var->red;
var->blue = var->red;
break;
case 16:
if (isPReP) {
var->red.offset = 2;
var->green.offset = -3;
var->blue.offset = 8;
} else {
var->red.offset = 11;
var->green.offset = 5;
var->blue.offset = 0;
}
var->red.length = 5;
var->green.length = 6;
var->blue.length = 5;
break;
case 24:
if (isPReP) {
var->red.offset = 0;
var->green.offset = 8;
var->blue.offset = 16;
} else {
var->red.offset = 16;
var->green.offset = 8;
var->blue.offset = 0;
}
var->red.length = 8;
var->green.length = 8;
var->blue.length = 8;
break;
default:
dev_dbg(info->device,
"Unsupported bpp size: %d\n", var->bits_per_pixel);
return -EINVAL;
}
if (var->xres_virtual < var->xres)
var->xres_virtual = var->xres;
/* use highest possible virtual resolution */
if (var->yres_virtual == -1) {
var->yres_virtual = pixels / var->xres_virtual;
dev_info(info->device,
"virtual resolution set to maximum of %dx%d\n",
var->xres_virtual, var->yres_virtual);
}
if (var->yres_virtual < var->yres)
var->yres_virtual = var->yres;
if (var->xres_virtual * var->yres_virtual > pixels) {
dev_err(info->device, "mode %dx%dx%d rejected... "
"virtual resolution too high to fit into video memory!\n",
var->xres_virtual, var->yres_virtual,
var->bits_per_pixel);
return -EINVAL;
}
if (var->xoffset < 0)
var->xoffset = 0;
if (var->yoffset < 0)
var->yoffset = 0;
/* truncate xoffset and yoffset to maximum if too high */
if (var->xoffset > var->xres_virtual - var->xres)
var->xoffset = var->xres_virtual - var->xres - 1;
if (var->yoffset > var->yres_virtual - var->yres)
var->yoffset = var->yres_virtual - var->yres - 1;
var->red.msb_right =
var->green.msb_right =
var->blue.msb_right =
var->transp.offset =
var->transp.length =
var->transp.msb_right = 0;
yres = var->yres;
if (var->vmode & FB_VMODE_DOUBLE)
yres *= 2;
else if (var->vmode & FB_VMODE_INTERLACED)
yres = (yres + 1) / 2;
if (yres >= 1280) {
dev_err(info->device, "ERROR: VerticalTotal >= 1280; "
"special treatment required! (TODO)\n");
return -EINVAL;
}
if (cirrusfb_check_pixclock(var, info))
return -EINVAL;
if (!is_laguna(cinfo))
var->accel_flags = FB_ACCELF_TEXT;
return 0;
}
static void cirrusfb_set_mclk_as_source(const struct fb_info *info, int div)
{
struct cirrusfb_info *cinfo = info->par;
unsigned char old1f, old1e;
assert(cinfo != NULL);
old1f = vga_rseq(cinfo->regbase, CL_SEQR1F) & ~0x40;
if (div) {
dev_dbg(info->device, "Set %s as pixclock source.\n",
(div == 2) ? "MCLK/2" : "MCLK");
old1f |= 0x40;
old1e = vga_rseq(cinfo->regbase, CL_SEQR1E) & ~0x1;
if (div == 2)
old1e |= 1;
vga_wseq(cinfo->regbase, CL_SEQR1E, old1e);
}
vga_wseq(cinfo->regbase, CL_SEQR1F, old1f);
}
/*************************************************************************
cirrusfb_set_par_foo()
actually writes the values for a new video mode into the hardware,
**************************************************************************/
static int cirrusfb_set_par_foo(struct fb_info *info)
{
struct cirrusfb_info *cinfo = info->par;
struct fb_var_screeninfo *var = &info->var;
u8 __iomem *regbase = cinfo->regbase;
unsigned char tmp;
int pitch;
const struct cirrusfb_board_info_rec *bi;
int hdispend, hsyncstart, hsyncend, htotal;
int yres, vdispend, vsyncstart, vsyncend, vtotal;
long freq;
int nom, den, div;
unsigned int control = 0, format = 0, threshold = 0;
dev_dbg(info->device, "Requested mode: %dx%dx%d\n",
var->xres, var->yres, var->bits_per_pixel);
switch (var->bits_per_pixel) {
case 1:
info->fix.line_length = var->xres_virtual / 8;
info->fix.visual = FB_VISUAL_MONO10;
break;
case 8:
info->fix.line_length = var->xres_virtual;
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
break;
case 16:
case 24:
info->fix.line_length = var->xres_virtual *
var->bits_per_pixel >> 3;
info->fix.visual = FB_VISUAL_TRUECOLOR;
break;
}
info->fix.type = FB_TYPE_PACKED_PIXELS;
init_vgachip(info);
bi = &cirrusfb_board_info[cinfo->btype];
hsyncstart = var->xres + var->right_margin;
hsyncend = hsyncstart + var->hsync_len;
htotal = (hsyncend + var->left_margin) / 8;
hdispend = var->xres / 8;
hsyncstart = hsyncstart / 8;
hsyncend = hsyncend / 8;
vdispend = var->yres;
vsyncstart = vdispend + var->lower_margin;
vsyncend = vsyncstart + var->vsync_len;
vtotal = vsyncend + var->upper_margin;
if (var->vmode & FB_VMODE_DOUBLE) {
vdispend *= 2;
vsyncstart *= 2;
vsyncend *= 2;
vtotal *= 2;
} else if (var->vmode & FB_VMODE_INTERLACED) {
vdispend = (vdispend + 1) / 2;
vsyncstart = (vsyncstart + 1) / 2;
vsyncend = (vsyncend + 1) / 2;
vtotal = (vtotal + 1) / 2;
}
yres = vdispend;
if (yres >= 1024) {
vtotal /= 2;
vsyncstart /= 2;
vsyncend /= 2;
vdispend /= 2;
}
vdispend -= 1;
vsyncstart -= 1;
vsyncend -= 1;
vtotal -= 2;
if (cinfo->multiplexing) {
htotal /= 2;
hsyncstart /= 2;
hsyncend /= 2;
hdispend /= 2;
}
htotal -= 5;
hdispend -= 1;
hsyncstart += 1;
hsyncend += 1;
/* unlock register VGA_CRTC_H_TOTAL..CRT7 */
vga_wcrt(regbase, VGA_CRTC_V_SYNC_END, 0x20); /* previously: 0x00) */
/* if debugging is enabled, all parameters get output before writing */
dev_dbg(info->device, "CRT0: %d\n", htotal);
vga_wcrt(regbase, VGA_CRTC_H_TOTAL, htotal);
dev_dbg(info->device, "CRT1: %d\n", hdispend);
vga_wcrt(regbase, VGA_CRTC_H_DISP, hdispend);
dev_dbg(info->device, "CRT2: %d\n", var->xres / 8);
vga_wcrt(regbase, VGA_CRTC_H_BLANK_START, var->xres / 8);
/* + 128: Compatible read */
dev_dbg(info->device, "CRT3: 128+%d\n", (htotal + 5) % 32);
vga_wcrt(regbase, VGA_CRTC_H_BLANK_END,
128 + ((htotal + 5) % 32));
dev_dbg(info->device, "CRT4: %d\n", hsyncstart);
vga_wcrt(regbase, VGA_CRTC_H_SYNC_START, hsyncstart);
tmp = hsyncend % 32;
if ((htotal + 5) & 32)
tmp += 128;
dev_dbg(info->device, "CRT5: %d\n", tmp);
vga_wcrt(regbase, VGA_CRTC_H_SYNC_END, tmp);
dev_dbg(info->device, "CRT6: %d\n", vtotal & 0xff);
vga_wcrt(regbase, VGA_CRTC_V_TOTAL, vtotal & 0xff);
tmp = 16; /* LineCompare bit #9 */
if (vtotal & 256)
tmp |= 1;
if (vdispend & 256)
tmp |= 2;
if (vsyncstart & 256)
tmp |= 4;
if ((vdispend + 1) & 256)
tmp |= 8;
if (vtotal & 512)
tmp |= 32;
if (vdispend & 512)
tmp |= 64;
if (vsyncstart & 512)
tmp |= 128;
dev_dbg(info->device, "CRT7: %d\n", tmp);
vga_wcrt(regbase, VGA_CRTC_OVERFLOW, tmp);
tmp = 0x40; /* LineCompare bit #8 */
if ((vdispend + 1) & 512)
tmp |= 0x20;
if (var->vmode & FB_VMODE_DOUBLE)
tmp |= 0x80;
dev_dbg(info->device, "CRT9: %d\n", tmp);
vga_wcrt(regbase, VGA_CRTC_MAX_SCAN, tmp);
dev_dbg(info->device, "CRT10: %d\n", vsyncstart & 0xff);
vga_wcrt(regbase, VGA_CRTC_V_SYNC_START, vsyncstart & 0xff);
dev_dbg(info->device, "CRT11: 64+32+%d\n", vsyncend % 16);
vga_wcrt(regbase, VGA_CRTC_V_SYNC_END, vsyncend % 16 + 64 + 32);
dev_dbg(info->device, "CRT12: %d\n", vdispend & 0xff);
vga_wcrt(regbase, VGA_CRTC_V_DISP_END, vdispend & 0xff);
dev_dbg(info->device, "CRT15: %d\n", (vdispend + 1) & 0xff);
vga_wcrt(regbase, VGA_CRTC_V_BLANK_START, (vdispend + 1) & 0xff);
dev_dbg(info->device, "CRT16: %d\n", vtotal & 0xff);
vga_wcrt(regbase, VGA_CRTC_V_BLANK_END, vtotal & 0xff);
dev_dbg(info->device, "CRT18: 0xff\n");
vga_wcrt(regbase, VGA_CRTC_LINE_COMPARE, 0xff);
tmp = 0;
if (var->vmode & FB_VMODE_INTERLACED)
tmp |= 1;
if ((htotal + 5) & 64)
tmp |= 16;
if ((htotal + 5) & 128)
tmp |= 32;
if (vtotal & 256)
tmp |= 64;
if (vtotal & 512)
tmp |= 128;
dev_dbg(info->device, "CRT1a: %d\n", tmp);
vga_wcrt(regbase, CL_CRT1A, tmp);
freq = PICOS2KHZ(var->pixclock);
if (var->bits_per_pixel == 24)
if (cinfo->btype == BT_ALPINE || cinfo->btype == BT_SD64)
freq *= 3;
if (cinfo->multiplexing)
freq /= 2;
if (cinfo->doubleVCLK)
freq *= 2;
bestclock(freq, &nom, &den, &div);
dev_dbg(info->device, "VCLK freq: %ld kHz nom: %d den: %d div: %d\n",
freq, nom, den, div);
/* set VCLK0 */
/* hardware RefClock: 14.31818 MHz */
/* formula: VClk = (OSC * N) / (D * (1+P)) */
/* Example: VClk = (14.31818 * 91) / (23 * (1+1)) = 28.325 MHz */
if (cinfo->btype == BT_ALPINE || cinfo->btype == BT_PICASSO4 ||
cinfo->btype == BT_SD64) {
/* if freq is close to mclk or mclk/2 select mclk
* as clock source
*/
int divMCLK = cirrusfb_check_mclk(info, freq);
if (divMCLK)
nom = 0;
cirrusfb_set_mclk_as_source(info, divMCLK);
}
if (is_laguna(cinfo)) {
long pcifc = fb_readl(cinfo->laguna_mmio + 0x3fc);
unsigned char tile = fb_readb(cinfo->laguna_mmio + 0x407);
unsigned short tile_control;
if (cinfo->btype == BT_LAGUNAB) {
tile_control = fb_readw(cinfo->laguna_mmio + 0x2c4);
tile_control &= ~0x80;
fb_writew(tile_control, cinfo->laguna_mmio + 0x2c4);
}
fb_writel(pcifc | 0x10000000l, cinfo->laguna_mmio + 0x3fc);
fb_writeb(tile & 0x3f, cinfo->laguna_mmio + 0x407);
control = fb_readw(cinfo->laguna_mmio + 0x402);
threshold = fb_readw(cinfo->laguna_mmio + 0xea);
control &= ~0x6800;
format = 0;
threshold &= 0xffc0 & 0x3fbf;
}
if (nom) {
tmp = den << 1;
if (div != 0)
tmp |= 1;
/* 6 bit denom; ONLY 5434!!! (bugged me 10 days) */
if ((cinfo->btype == BT_SD64) ||
(cinfo->btype == BT_ALPINE) ||
(cinfo->btype == BT_GD5480))
tmp |= 0x80;
/* Laguna chipset has reversed clock registers */
if (is_laguna(cinfo)) {
vga_wseq(regbase, CL_SEQRE, tmp);
vga_wseq(regbase, CL_SEQR1E, nom);
} else {
vga_wseq(regbase, CL_SEQRE, nom);
vga_wseq(regbase, CL_SEQR1E, tmp);
}
}
if (yres >= 1024)
/* 1280x1024 */
vga_wcrt(regbase, VGA_CRTC_MODE, 0xc7);
else
/* mode control: VGA_CRTC_START_HI enable, ROTATE(?), 16bit
* address wrap, no compat. */
vga_wcrt(regbase, VGA_CRTC_MODE, 0xc3);
/* don't know if it would hurt to also program this if no interlaced */
/* mode is used, but I feel better this way.. :-) */
if (var->vmode & FB_VMODE_INTERLACED)
vga_wcrt(regbase, VGA_CRTC_REGS, htotal / 2);
else
vga_wcrt(regbase, VGA_CRTC_REGS, 0x00); /* interlace control */
/* adjust horizontal/vertical sync type (low/high), use VCLK3 */
/* enable display memory & CRTC I/O address for color mode */
tmp = 0x03 | 0xc;
if (var->sync & FB_SYNC_HOR_HIGH_ACT)
tmp |= 0x40;
if (var->sync & FB_SYNC_VERT_HIGH_ACT)
tmp |= 0x80;
WGen(cinfo, VGA_MIS_W, tmp);
/* text cursor on and start line */
vga_wcrt(regbase, VGA_CRTC_CURSOR_START, 0);
/* text cursor end line */
vga_wcrt(regbase, VGA_CRTC_CURSOR_END, 31);
/******************************************************
*
* 1 bpp
*
*/
/* programming for different color depths */
if (var->bits_per_pixel == 1) {
dev_dbg(info->device, "preparing for 1 bit deep display\n");
vga_wgfx(regbase, VGA_GFX_MODE, 0); /* mode register */
/* SR07 */
switch (cinfo->btype) {
case BT_SD64:
case BT_PICCOLO:
case BT_PICASSO:
case BT_SPECTRUM:
case BT_PICASSO4:
case BT_ALPINE:
case BT_GD5480:
vga_wseq(regbase, CL_SEQR7,
cinfo->multiplexing ?
bi->sr07_1bpp_mux : bi->sr07_1bpp);
break;
case BT_LAGUNA:
case BT_LAGUNAB:
vga_wseq(regbase, CL_SEQR7,
vga_rseq(regbase, CL_SEQR7) & ~0x01);
break;
default:
dev_warn(info->device, "unknown Board\n");
break;
}
/* Extended Sequencer Mode */
switch (cinfo->btype) {
case BT_PICCOLO:
case BT_SPECTRUM:
/* evtl d0 bei 1 bit? avoid FIFO underruns..? */
vga_wseq(regbase, CL_SEQRF, 0xb0);
break;
case BT_PICASSO:
/* ## vorher d0 avoid FIFO underruns..? */
vga_wseq(regbase, CL_SEQRF, 0xd0);
break;
case BT_SD64:
case BT_PICASSO4:
case BT_ALPINE:
case BT_GD5480:
case BT_LAGUNA:
case BT_LAGUNAB:
/* do nothing */
break;
default:
dev_warn(info->device, "unknown Board\n");
break;
}
/* pixel mask: pass-through for first plane */
WGen(cinfo, VGA_PEL_MSK, 0x01);
if (cinfo->multiplexing)
/* hidden dac reg: 1280x1024 */
WHDR(cinfo, 0x4a);
else
/* hidden dac: nothing */
WHDR(cinfo, 0);
/* memory mode: odd/even, ext. memory */
vga_wseq(regbase, VGA_SEQ_MEMORY_MODE, 0x06);
/* plane mask: only write to first plane */
vga_wseq(regbase, VGA_SEQ_PLANE_WRITE, 0x01);
}
/******************************************************
*
* 8 bpp
*
*/
else if (var->bits_per_pixel == 8) {
dev_dbg(info->device, "preparing for 8 bit deep display\n");
switch (cinfo->btype) {
case BT_SD64:
case BT_PICCOLO:
case BT_PICASSO:
case BT_SPECTRUM:
case BT_PICASSO4:
case BT_ALPINE:
case BT_GD5480:
vga_wseq(regbase, CL_SEQR7,
cinfo->multiplexing ?
bi->sr07_8bpp_mux : bi->sr07_8bpp);
break;
case BT_LAGUNA:
case BT_LAGUNAB:
vga_wseq(regbase, CL_SEQR7,
vga_rseq(regbase, CL_SEQR7) | 0x01);
threshold |= 0x10;
break;
default:
dev_warn(info->device, "unknown Board\n");
break;
}
switch (cinfo->btype) {
case BT_PICCOLO:
case BT_PICASSO:
case BT_SPECTRUM:
/* Fast Page-Mode writes */
vga_wseq(regbase, CL_SEQRF, 0xb0);
break;
case BT_PICASSO4:
#ifdef CONFIG_ZORRO
/* ### INCOMPLETE!! */
vga_wseq(regbase, CL_SEQRF, 0xb8);
#endif
case BT_ALPINE:
case BT_SD64:
case BT_GD5480:
case BT_LAGUNA:
case BT_LAGUNAB:
/* do nothing */
break;
default:
dev_warn(info->device, "unknown board\n");
break;
}
/* mode register: 256 color mode */
vga_wgfx(regbase, VGA_GFX_MODE, 64);
if (cinfo->multiplexing)
/* hidden dac reg: 1280x1024 */
WHDR(cinfo, 0x4a);
else
/* hidden dac: nothing */
WHDR(cinfo, 0);
}
/******************************************************
*
* 16 bpp
*
*/
else if (var->bits_per_pixel == 16) {
dev_dbg(info->device, "preparing for 16 bit deep display\n");
switch (cinfo->btype) {
case BT_PICCOLO:
case BT_SPECTRUM:
vga_wseq(regbase, CL_SEQR7, 0x87);
/* Fast Page-Mode writes */
vga_wseq(regbase, CL_SEQRF, 0xb0);
break;
case BT_PICASSO:
vga_wseq(regbase, CL_SEQR7, 0x27);
/* Fast Page-Mode writes */
vga_wseq(regbase, CL_SEQRF, 0xb0);
break;
case BT_SD64:
case BT_PICASSO4:
case BT_ALPINE:
/* Extended Sequencer Mode: 256c col. mode */
vga_wseq(regbase, CL_SEQR7,
cinfo->doubleVCLK ? 0xa3 : 0xa7);
break;
case BT_GD5480:
vga_wseq(regbase, CL_SEQR7, 0x17);
/* We already set SRF and SR1F */
break;
case BT_LAGUNA:
case BT_LAGUNAB:
vga_wseq(regbase, CL_SEQR7,
vga_rseq(regbase, CL_SEQR7) & ~0x01);
control |= 0x2000;
format |= 0x1400;
threshold |= 0x10;
break;
default:
dev_warn(info->device, "unknown Board\n");
break;
}
/* mode register: 256 color mode */
vga_wgfx(regbase, VGA_GFX_MODE, 64);
#ifdef CONFIG_PCI
WHDR(cinfo, cinfo->doubleVCLK ? 0xe1 : 0xc1);
#elif defined(CONFIG_ZORRO)
/* FIXME: CONFIG_PCI and CONFIG_ZORRO may be defined both */
WHDR(cinfo, 0xa0); /* hidden dac reg: nothing special */
#endif
}
/******************************************************
*
* 24 bpp
*
*/
else if (var->bits_per_pixel == 24) {
dev_dbg(info->device, "preparing for 24 bit deep display\n");
switch (cinfo->btype) {
case BT_PICCOLO:
case BT_SPECTRUM:
vga_wseq(regbase, CL_SEQR7, 0x85);
/* Fast Page-Mode writes */
vga_wseq(regbase, CL_SEQRF, 0xb0);
break;
case BT_PICASSO:
vga_wseq(regbase, CL_SEQR7, 0x25);
/* Fast Page-Mode writes */
vga_wseq(regbase, CL_SEQRF, 0xb0);
break;
case BT_SD64:
case BT_PICASSO4:
case BT_ALPINE:
/* Extended Sequencer Mode: 256c col. mode */
vga_wseq(regbase, CL_SEQR7, 0xa5);
break;
case BT_GD5480:
vga_wseq(regbase, CL_SEQR7, 0x15);
/* We already set SRF and SR1F */
break;
case BT_LAGUNA:
case BT_LAGUNAB:
vga_wseq(regbase, CL_SEQR7,
vga_rseq(regbase, CL_SEQR7) & ~0x01);
control |= 0x4000;
format |= 0x2400;
threshold |= 0x20;
break;
default:
dev_warn(info->device, "unknown Board\n");
break;
}
/* mode register: 256 color mode */
vga_wgfx(regbase, VGA_GFX_MODE, 64);
/* hidden dac reg: 8-8-8 mode (24 or 32) */
WHDR(cinfo, 0xc5);
}
/******************************************************
*
* unknown/unsupported bpp
*
*/
else
dev_err(info->device,
"What's this? requested color depth == %d.\n",
var->bits_per_pixel);
pitch = info->fix.line_length >> 3;
vga_wcrt(regbase, VGA_CRTC_OFFSET, pitch & 0xff);
tmp = 0x22;
if (pitch & 0x100)
tmp |= 0x10; /* offset overflow bit */
/* screen start addr #16-18, fastpagemode cycles */
vga_wcrt(regbase, CL_CRT1B, tmp);
/* screen start address bit 19 */
if (cirrusfb_board_info[cinfo->btype].scrn_start_bit19)
vga_wcrt(regbase, CL_CRT1D, (pitch >> 9) & 1);
if (is_laguna(cinfo)) {
tmp = 0;
if ((htotal + 5) & 256)
tmp |= 128;
if (hdispend & 256)
tmp |= 64;
if (hsyncstart & 256)
tmp |= 48;
if (vtotal & 1024)
tmp |= 8;
if (vdispend & 1024)
tmp |= 4;
if (vsyncstart & 1024)
tmp |= 3;
vga_wcrt(regbase, CL_CRT1E, tmp);
dev_dbg(info->device, "CRT1e: %d\n", tmp);
}
/* pixel panning */
vga_wattr(regbase, CL_AR33, 0);
/* [ EGS: SetOffset(); ] */
/* From SetOffset(): Turn on VideoEnable bit in Attribute controller */
AttrOn(cinfo);
if (is_laguna(cinfo)) {
/* no tiles */
fb_writew(control | 0x1000, cinfo->laguna_mmio + 0x402);
fb_writew(format, cinfo->laguna_mmio + 0xc0);
fb_writew(threshold, cinfo->laguna_mmio + 0xea);
}
/* finally, turn on everything - turn off "FullBandwidth" bit */
/* also, set "DotClock%2" bit where requested */
tmp = 0x01;
/*** FB_VMODE_CLOCK_HALVE in linux/fb.h not defined anymore ?
if (var->vmode & FB_VMODE_CLOCK_HALVE)
tmp |= 0x08;
*/
vga_wseq(regbase, VGA_SEQ_CLOCK_MODE, tmp);
dev_dbg(info->device, "CL_SEQR1: %d\n", tmp);
#ifdef CIRRUSFB_DEBUG
cirrusfb_dbg_reg_dump(info, NULL);
#endif
return 0;
}
/* for some reason incomprehensible to me, cirrusfb requires that you write
* the registers twice for the settings to take..grr. -dte */
static int cirrusfb_set_par(struct fb_info *info)
{
cirrusfb_set_par_foo(info);
return cirrusfb_set_par_foo(info);
}
static int cirrusfb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
struct cirrusfb_info *cinfo = info->par;
if (regno > 255)
return -EINVAL;
if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 v;
red >>= (16 - info->var.red.length);
green >>= (16 - info->var.green.length);
blue >>= (16 - info->var.blue.length);
if (regno >= 16)
return 1;
v = (red << info->var.red.offset) |
(green << info->var.green.offset) |
(blue << info->var.blue.offset);
cinfo->pseudo_palette[regno] = v;
return 0;
}
if (info->var.bits_per_pixel == 8)
WClut(cinfo, regno, red >> 10, green >> 10, blue >> 10);
return 0;
}
/*************************************************************************
cirrusfb_pan_display()
performs display panning - provided hardware permits this
**************************************************************************/
static int cirrusfb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
int xoffset;
unsigned long base;
unsigned char tmp, xpix;
struct cirrusfb_info *cinfo = info->par;
/* no range checks for xoffset and yoffset, */
/* as fb_pan_display has already done this */
if (var->vmode & FB_VMODE_YWRAP)
return -EINVAL;
xoffset = var->xoffset * info->var.bits_per_pixel / 8;
base = var->yoffset * info->fix.line_length + xoffset;
if (info->var.bits_per_pixel == 1) {
/* base is already correct */
xpix = (unsigned char) (var->xoffset % 8);
} else {
base /= 4;
xpix = (unsigned char) ((xoffset % 4) * 2);
}
if (!is_laguna(cinfo))
cirrusfb_WaitBLT(cinfo->regbase);
/* lower 8 + 8 bits of screen start address */
vga_wcrt(cinfo->regbase, VGA_CRTC_START_LO, base & 0xff);
vga_wcrt(cinfo->regbase, VGA_CRTC_START_HI, (base >> 8) & 0xff);
/* 0xf2 is %11110010, exclude tmp bits */
tmp = vga_rcrt(cinfo->regbase, CL_CRT1B) & 0xf2;
/* construct bits 16, 17 and 18 of screen start address */
if (base & 0x10000)
tmp |= 0x01;
if (base & 0x20000)
tmp |= 0x04;
if (base & 0x40000)
tmp |= 0x08;
vga_wcrt(cinfo->regbase, CL_CRT1B, tmp);
/* construct bit 19 of screen start address */
if (cirrusfb_board_info[cinfo->btype].scrn_start_bit19) {
tmp = vga_rcrt(cinfo->regbase, CL_CRT1D);
if (is_laguna(cinfo))
tmp = (tmp & ~0x18) | ((base >> 16) & 0x18);
else
tmp = (tmp & ~0x80) | ((base >> 12) & 0x80);
vga_wcrt(cinfo->regbase, CL_CRT1D, tmp);
}
/* write pixel panning value to AR33; this does not quite work in 8bpp
*
* ### Piccolo..? Will this work?
*/
if (info->var.bits_per_pixel == 1)
vga_wattr(cinfo->regbase, CL_AR33, xpix);
return 0;
}
static int cirrusfb_blank(int blank_mode, struct fb_info *info)
{
/*
* Blank the screen if blank_mode != 0, else unblank. If blank == NULL
* then the caller blanks by setting the CLUT (Color Look Up Table)
* to all black. Return 0 if blanking succeeded, != 0 if un-/blanking
* failed due to e.g. a video mode which doesn't support it.
* Implements VESA suspend and powerdown modes on hardware that
* supports disabling hsync/vsync:
* blank_mode == 2: suspend vsync
* blank_mode == 3: suspend hsync
* blank_mode == 4: powerdown
*/
unsigned char val;
struct cirrusfb_info *cinfo = info->par;
int current_mode = cinfo->blank_mode;
dev_dbg(info->device, "ENTER, blank mode = %d\n", blank_mode);
if (info->state != FBINFO_STATE_RUNNING ||
current_mode == blank_mode) {
dev_dbg(info->device, "EXIT, returning 0\n");
return 0;
}
/* Undo current */
if (current_mode == FB_BLANK_NORMAL ||
current_mode == FB_BLANK_UNBLANK)
/* clear "FullBandwidth" bit */
val = 0;
else
/* set "FullBandwidth" bit */
val = 0x20;
val |= vga_rseq(cinfo->regbase, VGA_SEQ_CLOCK_MODE) & 0xdf;
vga_wseq(cinfo->regbase, VGA_SEQ_CLOCK_MODE, val);
switch (blank_mode) {
case FB_BLANK_UNBLANK:
case FB_BLANK_NORMAL:
val = 0x00;
break;
case FB_BLANK_VSYNC_SUSPEND:
val = 0x04;
break;
case FB_BLANK_HSYNC_SUSPEND:
val = 0x02;
break;
case FB_BLANK_POWERDOWN:
val = 0x06;
break;
default:
dev_dbg(info->device, "EXIT, returning 1\n");
return 1;
}
vga_wgfx(cinfo->regbase, CL_GRE, val);
cinfo->blank_mode = blank_mode;
dev_dbg(info->device, "EXIT, returning 0\n");
/* Let fbcon do a soft blank for us */
return (blank_mode == FB_BLANK_NORMAL) ? 1 : 0;
}
/**** END Hardware specific Routines **************************************/
/****************************************************************************/
/**** BEGIN Internal Routines ***********************************************/
static void init_vgachip(struct fb_info *info)
{
struct cirrusfb_info *cinfo = info->par;
const struct cirrusfb_board_info_rec *bi;
assert(cinfo != NULL);
bi = &cirrusfb_board_info[cinfo->btype];
/* reset board globally */
switch (cinfo->btype) {
case BT_PICCOLO:
WSFR(cinfo, 0x01);
udelay(500);
WSFR(cinfo, 0x51);
udelay(500);
break;
case BT_PICASSO:
WSFR2(cinfo, 0xff);
udelay(500);
break;
case BT_SD64:
case BT_SPECTRUM:
WSFR(cinfo, 0x1f);
udelay(500);
WSFR(cinfo, 0x4f);
udelay(500);
break;
case BT_PICASSO4:
/* disable flickerfixer */
vga_wcrt(cinfo->regbase, CL_CRT51, 0x00);
mdelay(100);
/* mode */
vga_wgfx(cinfo->regbase, CL_GR31, 0x00);
case BT_GD5480: /* fall through */
/* from Klaus' NetBSD driver: */
vga_wgfx(cinfo->regbase, CL_GR2F, 0x00);
case BT_ALPINE: /* fall through */
/* put blitter into 542x compat */
vga_wgfx(cinfo->regbase, CL_GR33, 0x00);
break;
case BT_LAGUNA:
case BT_LAGUNAB:
/* Nothing to do to reset the board. */
break;
default:
dev_err(info->device, "Warning: Unknown board type\n");
break;
}
/* make sure RAM size set by this point */
assert(info->screen_size > 0);
/* the P4 is not fully initialized here; I rely on it having been */
/* inited under AmigaOS already, which seems to work just fine */
/* (Klaus advised to do it this way) */
if (cinfo->btype != BT_PICASSO4) {
WGen(cinfo, CL_VSSM, 0x10); /* EGS: 0x16 */
WGen(cinfo, CL_POS102, 0x01);
WGen(cinfo, CL_VSSM, 0x08); /* EGS: 0x0e */
if (cinfo->btype != BT_SD64)
WGen(cinfo, CL_VSSM2, 0x01);
/* reset sequencer logic */
vga_wseq(cinfo->regbase, VGA_SEQ_RESET, 0x03);
/* FullBandwidth (video off) and 8/9 dot clock */
vga_wseq(cinfo->regbase, VGA_SEQ_CLOCK_MODE, 0x21);
/* "magic cookie" - doesn't make any sense to me.. */
/* vga_wgfx(cinfo->regbase, CL_GRA, 0xce); */
/* unlock all extension registers */
vga_wseq(cinfo->regbase, CL_SEQR6, 0x12);
switch (cinfo->btype) {
case BT_GD5480:
vga_wseq(cinfo->regbase, CL_SEQRF, 0x98);
break;
case BT_ALPINE:
case BT_LAGUNA:
case BT_LAGUNAB:
break;
case BT_SD64:
#ifdef CONFIG_ZORRO
vga_wseq(cinfo->regbase, CL_SEQRF, 0xb8);
#endif
break;
default:
vga_wseq(cinfo->regbase, CL_SEQR16, 0x0f);
vga_wseq(cinfo->regbase, CL_SEQRF, 0xb0);
break;
}
}
/* plane mask: nothing */
vga_wseq(cinfo->regbase, VGA_SEQ_PLANE_WRITE, 0xff);
/* character map select: doesn't even matter in gx mode */
vga_wseq(cinfo->regbase, VGA_SEQ_CHARACTER_MAP, 0x00);
/* memory mode: chain4, ext. memory */
vga_wseq(cinfo->regbase, VGA_SEQ_MEMORY_MODE, 0x0a);
/* controller-internal base address of video memory */
if (bi->init_sr07)
vga_wseq(cinfo->regbase, CL_SEQR7, bi->sr07);
/* vga_wseq(cinfo->regbase, CL_SEQR8, 0x00); */
/* EEPROM control: shouldn't be necessary to write to this at all.. */
/* graphics cursor X position (incomplete; position gives rem. 3 bits */
vga_wseq(cinfo->regbase, CL_SEQR10, 0x00);
/* graphics cursor Y position (..."... ) */
vga_wseq(cinfo->regbase, CL_SEQR11, 0x00);
/* graphics cursor attributes */
vga_wseq(cinfo->regbase, CL_SEQR12, 0x00);
/* graphics cursor pattern address */
vga_wseq(cinfo->regbase, CL_SEQR13, 0x00);
/* writing these on a P4 might give problems.. */
if (cinfo->btype != BT_PICASSO4) {
/* configuration readback and ext. color */
vga_wseq(cinfo->regbase, CL_SEQR17, 0x00);
/* signature generator */
vga_wseq(cinfo->regbase, CL_SEQR18, 0x02);
}
/* Screen A preset row scan: none */
vga_wcrt(cinfo->regbase, VGA_CRTC_PRESET_ROW, 0x00);
/* Text cursor start: disable text cursor */
vga_wcrt(cinfo->regbase, VGA_CRTC_CURSOR_START, 0x20);
/* Text cursor end: - */
vga_wcrt(cinfo->regbase, VGA_CRTC_CURSOR_END, 0x00);
/* text cursor location high: 0 */
vga_wcrt(cinfo->regbase, VGA_CRTC_CURSOR_HI, 0x00);
/* text cursor location low: 0 */
vga_wcrt(cinfo->regbase, VGA_CRTC_CURSOR_LO, 0x00);
/* Underline Row scanline: - */
vga_wcrt(cinfo->regbase, VGA_CRTC_UNDERLINE, 0x00);
/* ### add 0x40 for text modes with > 30 MHz pixclock */
/* ext. display controls: ext.adr. wrap */
vga_wcrt(cinfo->regbase, CL_CRT1B, 0x02);
/* Set/Reset registes: - */
vga_wgfx(cinfo->regbase, VGA_GFX_SR_VALUE, 0x00);
/* Set/Reset enable: - */
vga_wgfx(cinfo->regbase, VGA_GFX_SR_ENABLE, 0x00);
/* Color Compare: - */
vga_wgfx(cinfo->regbase, VGA_GFX_COMPARE_VALUE, 0x00);
/* Data Rotate: - */
vga_wgfx(cinfo->regbase, VGA_GFX_DATA_ROTATE, 0x00);
/* Read Map Select: - */
vga_wgfx(cinfo->regbase, VGA_GFX_PLANE_READ, 0x00);
/* Mode: conf. for 16/4/2 color mode, no odd/even, read/write mode 0 */
vga_wgfx(cinfo->regbase, VGA_GFX_MODE, 0x00);
/* Miscellaneous: memory map base address, graphics mode */
vga_wgfx(cinfo->regbase, VGA_GFX_MISC, 0x01);
/* Color Don't care: involve all planes */
vga_wgfx(cinfo->regbase, VGA_GFX_COMPARE_MASK, 0x0f);
/* Bit Mask: no mask at all */
vga_wgfx(cinfo->regbase, VGA_GFX_BIT_MASK, 0xff);
if (cinfo->btype == BT_ALPINE || cinfo->btype == BT_SD64 ||
is_laguna(cinfo))
/* (5434 can't have bit 3 set for bitblt) */
vga_wgfx(cinfo->regbase, CL_GRB, 0x20);
else
/* Graphics controller mode extensions: finer granularity,
* 8byte data latches
*/
vga_wgfx(cinfo->regbase, CL_GRB, 0x28);
vga_wgfx(cinfo->regbase, CL_GRC, 0xff); /* Color Key compare: - */
vga_wgfx(cinfo->regbase, CL_GRD, 0x00); /* Color Key compare mask: - */
vga_wgfx(cinfo->regbase, CL_GRE, 0x00); /* Miscellaneous control: - */
/* Background color byte 1: - */
/* vga_wgfx (cinfo->regbase, CL_GR10, 0x00); */
/* vga_wgfx (cinfo->regbase, CL_GR11, 0x00); */
/* Attribute Controller palette registers: "identity mapping" */
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE0, 0x00);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE1, 0x01);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE2, 0x02);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE3, 0x03);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE4, 0x04);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE5, 0x05);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE6, 0x06);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE7, 0x07);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE8, 0x08);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTE9, 0x09);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTEA, 0x0a);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTEB, 0x0b);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTEC, 0x0c);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTED, 0x0d);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTEE, 0x0e);
vga_wattr(cinfo->regbase, VGA_ATC_PALETTEF, 0x0f);
/* Attribute Controller mode: graphics mode */
vga_wattr(cinfo->regbase, VGA_ATC_MODE, 0x01);
/* Overscan color reg.: reg. 0 */
vga_wattr(cinfo->regbase, VGA_ATC_OVERSCAN, 0x00);
/* Color Plane enable: Enable all 4 planes */
vga_wattr(cinfo->regbase, VGA_ATC_PLANE_ENABLE, 0x0f);
/* Color Select: - */
vga_wattr(cinfo->regbase, VGA_ATC_COLOR_PAGE, 0x00);
WGen(cinfo, VGA_PEL_MSK, 0xff); /* Pixel mask: no mask */
/* BLT Start/status: Blitter reset */
vga_wgfx(cinfo->regbase, CL_GR31, 0x04);
/* - " - : "end-of-reset" */
vga_wgfx(cinfo->regbase, CL_GR31, 0x00);
/* misc... */
WHDR(cinfo, 0); /* Hidden DAC register: - */
return;
}
static void switch_monitor(struct cirrusfb_info *cinfo, int on)
{
#ifdef CONFIG_ZORRO /* only works on Zorro boards */
static int IsOn = 0; /* XXX not ok for multiple boards */
if (cinfo->btype == BT_PICASSO4)
return; /* nothing to switch */
if (cinfo->btype == BT_ALPINE)
return; /* nothing to switch */
if (cinfo->btype == BT_GD5480)
return; /* nothing to switch */
if (cinfo->btype == BT_PICASSO) {
if ((on && !IsOn) || (!on && IsOn))
WSFR(cinfo, 0xff);
return;
}
if (on) {
switch (cinfo->btype) {
case BT_SD64:
WSFR(cinfo, cinfo->SFR | 0x21);
break;
case BT_PICCOLO:
WSFR(cinfo, cinfo->SFR | 0x28);
break;
case BT_SPECTRUM:
WSFR(cinfo, 0x6f);
break;
default: /* do nothing */ break;
}
} else {
switch (cinfo->btype) {
case BT_SD64:
WSFR(cinfo, cinfo->SFR & 0xde);
break;
case BT_PICCOLO:
WSFR(cinfo, cinfo->SFR & 0xd7);
break;
case BT_SPECTRUM:
WSFR(cinfo, 0x4f);
break;
default: /* do nothing */
break;
}
}
#endif /* CONFIG_ZORRO */
}
/******************************************/
/* Linux 2.6-style accelerated functions */
/******************************************/
static int cirrusfb_sync(struct fb_info *info)
{
struct cirrusfb_info *cinfo = info->par;
if (!is_laguna(cinfo)) {
while (vga_rgfx(cinfo->regbase, CL_GR31) & 0x03)
cpu_relax();
}
return 0;
}
static void cirrusfb_fillrect(struct fb_info *info,
const struct fb_fillrect *region)
{
struct fb_fillrect modded;
int vxres, vyres;
struct cirrusfb_info *cinfo = info->par;
int m = info->var.bits_per_pixel;
u32 color = (info->fix.visual == FB_VISUAL_TRUECOLOR) ?
cinfo->pseudo_palette[region->color] : region->color;
if (info->state != FBINFO_STATE_RUNNING)
return;
if (info->flags & FBINFO_HWACCEL_DISABLED) {
cfb_fillrect(info, region);
return;
}
vxres = info->var.xres_virtual;
vyres = info->var.yres_virtual;
memcpy(&modded, region, sizeof(struct fb_fillrect));
if (!modded.width || !modded.height ||
modded.dx >= vxres || modded.dy >= vyres)
return;
if (modded.dx + modded.width > vxres)
modded.width = vxres - modded.dx;
if (modded.dy + modded.height > vyres)
modded.height = vyres - modded.dy;
cirrusfb_RectFill(cinfo->regbase,
info->var.bits_per_pixel,
(region->dx * m) / 8, region->dy,
(region->width * m) / 8, region->height,
color, color,
info->fix.line_length, 0x40);
}
static void cirrusfb_copyarea(struct fb_info *info,
const struct fb_copyarea *area)
{
struct fb_copyarea modded;
u32 vxres, vyres;
struct cirrusfb_info *cinfo = info->par;
int m = info->var.bits_per_pixel;
if (info->state != FBINFO_STATE_RUNNING)
return;
if (info->flags & FBINFO_HWACCEL_DISABLED) {
cfb_copyarea(info, area);
return;
}
vxres = info->var.xres_virtual;
vyres = info->var.yres_virtual;
memcpy(&modded, area, sizeof(struct fb_copyarea));
if (!modded.width || !modded.height ||
modded.sx >= vxres || modded.sy >= vyres ||
modded.dx >= vxres || modded.dy >= vyres)
return;
if (modded.sx + modded.width > vxres)
modded.width = vxres - modded.sx;
if (modded.dx + modded.width > vxres)
modded.width = vxres - modded.dx;
if (modded.sy + modded.height > vyres)
modded.height = vyres - modded.sy;
if (modded.dy + modded.height > vyres)
modded.height = vyres - modded.dy;
cirrusfb_BitBLT(cinfo->regbase, info->var.bits_per_pixel,
(area->sx * m) / 8, area->sy,
(area->dx * m) / 8, area->dy,
(area->width * m) / 8, area->height,
info->fix.line_length);
}
static void cirrusfb_imageblit(struct fb_info *info,
const struct fb_image *image)
{
struct cirrusfb_info *cinfo = info->par;
unsigned char op = (info->var.bits_per_pixel == 24) ? 0xc : 0x4;
if (info->state != FBINFO_STATE_RUNNING)
return;
/* Alpine/SD64 does not work at 24bpp ??? */
if (info->flags & FBINFO_HWACCEL_DISABLED || image->depth != 1)
cfb_imageblit(info, image);
else if ((cinfo->btype == BT_ALPINE || cinfo->btype == BT_SD64) &&
op == 0xc)
cfb_imageblit(info, image);
else {
unsigned size = ((image->width + 7) >> 3) * image->height;
int m = info->var.bits_per_pixel;
u32 fg, bg;
if (info->var.bits_per_pixel == 8) {
fg = image->fg_color;
bg = image->bg_color;
} else {
fg = ((u32 *)(info->pseudo_palette))[image->fg_color];
bg = ((u32 *)(info->pseudo_palette))[image->bg_color];
}
if (info->var.bits_per_pixel == 24) {
/* clear background first */
cirrusfb_RectFill(cinfo->regbase,
info->var.bits_per_pixel,
(image->dx * m) / 8, image->dy,
(image->width * m) / 8,
image->height,
bg, bg,
info->fix.line_length, 0x40);
}
cirrusfb_RectFill(cinfo->regbase,
info->var.bits_per_pixel,
(image->dx * m) / 8, image->dy,
(image->width * m) / 8, image->height,
fg, bg,
info->fix.line_length, op);
memcpy(info->screen_base, image->data, size);
}
}
#ifdef CONFIG_PPC_PREP
#define PREP_VIDEO_BASE ((volatile unsigned long) 0xC0000000)
#define PREP_IO_BASE ((volatile unsigned char *) 0x80000000)
static void get_prep_addrs(unsigned long *display, unsigned long *registers)
{
*display = PREP_VIDEO_BASE;
*registers = (unsigned long) PREP_IO_BASE;
}
#endif /* CONFIG_PPC_PREP */
#ifdef CONFIG_PCI
static int release_io_ports;
/* Pulled the logic from XFree86 Cirrus driver to get the memory size,
* based on the DRAM bandwidth bit and DRAM bank switching bit. This
* works with 1MB, 2MB and 4MB configurations (which the Motorola boards
* seem to have. */
static unsigned int __devinit cirrusfb_get_memsize(struct fb_info *info,
u8 __iomem *regbase)
{
unsigned long mem;
struct cirrusfb_info *cinfo = info->par;
if (is_laguna(cinfo)) {
unsigned char SR14 = vga_rseq(regbase, CL_SEQR14);
mem = ((SR14 & 7) + 1) << 20;
} else {
unsigned char SRF = vga_rseq(regbase, CL_SEQRF);
switch ((SRF & 0x18)) {
case 0x08:
mem = 512 * 1024;
break;
case 0x10:
mem = 1024 * 1024;
break;
/* 64-bit DRAM data bus width; assume 2MB.
* Also indicates 2MB memory on the 5430.
*/
case 0x18:
mem = 2048 * 1024;
break;
default:
dev_warn(info->device, "Unknown memory size!\n");
mem = 1024 * 1024;
}
/* If DRAM bank switching is enabled, there must be
* twice as much memory installed. (4MB on the 5434)
*/
if (cinfo->btype != BT_ALPINE && (SRF & 0x80) != 0)
mem *= 2;
}
/* TODO: Handling of GD5446/5480 (see XF86 sources ...) */
return mem;
}
static void get_pci_addrs(const struct pci_dev *pdev,
unsigned long *display, unsigned long *registers)
{
assert(pdev != NULL);
assert(display != NULL);
assert(registers != NULL);
*display = 0;
*registers = 0;
/* This is a best-guess for now */
if (pci_resource_flags(pdev, 0) & IORESOURCE_IO) {
*display = pci_resource_start(pdev, 1);
*registers = pci_resource_start(pdev, 0);
} else {
*display = pci_resource_start(pdev, 0);
*registers = pci_resource_start(pdev, 1);
}
assert(*display != 0);
}
static void cirrusfb_pci_unmap(struct fb_info *info)
{
struct pci_dev *pdev = to_pci_dev(info->device);
struct cirrusfb_info *cinfo = info->par;
if (cinfo->laguna_mmio == NULL)
iounmap(cinfo->laguna_mmio);
iounmap(info->screen_base);
#if 0 /* if system didn't claim this region, we would... */
release_mem_region(0xA0000, 65535);
#endif
if (release_io_ports)
release_region(0x3C0, 32);
pci_release_regions(pdev);
}
#endif /* CONFIG_PCI */
#ifdef CONFIG_ZORRO
static void cirrusfb_zorro_unmap(struct fb_info *info)
{
struct cirrusfb_info *cinfo = info->par;
struct zorro_dev *zdev = to_zorro_dev(info->device);
zorro_release_device(zdev);
if (cinfo->btype == BT_PICASSO4) {
cinfo->regbase -= 0x600000;
iounmap((void *)cinfo->regbase);
iounmap(info->screen_base);
} else {
if (zorro_resource_start(zdev) > 0x01000000)
iounmap(info->screen_base);
}
}
#endif /* CONFIG_ZORRO */
/* function table of the above functions */
static struct fb_ops cirrusfb_ops = {
.owner = THIS_MODULE,
.fb_open = cirrusfb_open,
.fb_release = cirrusfb_release,
.fb_setcolreg = cirrusfb_setcolreg,
.fb_check_var = cirrusfb_check_var,
.fb_set_par = cirrusfb_set_par,
.fb_pan_display = cirrusfb_pan_display,
.fb_blank = cirrusfb_blank,
.fb_fillrect = cirrusfb_fillrect,
.fb_copyarea = cirrusfb_copyarea,
.fb_sync = cirrusfb_sync,
.fb_imageblit = cirrusfb_imageblit,
};
static int __devinit cirrusfb_set_fbinfo(struct fb_info *info)
{
struct cirrusfb_info *cinfo = info->par;
struct fb_var_screeninfo *var = &info->var;
info->pseudo_palette = cinfo->pseudo_palette;
info->flags = FBINFO_DEFAULT
| FBINFO_HWACCEL_XPAN
| FBINFO_HWACCEL_YPAN
| FBINFO_HWACCEL_FILLRECT
| FBINFO_HWACCEL_IMAGEBLIT
| FBINFO_HWACCEL_COPYAREA;
if (noaccel || is_laguna(cinfo)) {
info->flags |= FBINFO_HWACCEL_DISABLED;
info->fix.accel = FB_ACCEL_NONE;
} else
info->fix.accel = FB_ACCEL_CIRRUS_ALPINE;
info->fbops = &cirrusfb_ops;
if (cinfo->btype == BT_GD5480) {
if (var->bits_per_pixel == 16)
info->screen_base += 1 * MB_;
if (var->bits_per_pixel == 32)
info->screen_base += 2 * MB_;
}
/* Fill fix common fields */
strlcpy(info->fix.id, cirrusfb_board_info[cinfo->btype].name,
sizeof(info->fix.id));
/* monochrome: only 1 memory plane */
/* 8 bit and above: Use whole memory area */
info->fix.smem_len = info->screen_size;
if (var->bits_per_pixel == 1)
info->fix.smem_len /= 4;
info->fix.type_aux = 0;
info->fix.xpanstep = 1;
info->fix.ypanstep = 1;
info->fix.ywrapstep = 0;
/* FIXME: map region at 0xB8000 if available, fill in here */
info->fix.mmio_len = 0;
fb_alloc_cmap(&info->cmap, 256, 0);
return 0;
}
static int __devinit cirrusfb_register(struct fb_info *info)
{
struct cirrusfb_info *cinfo = info->par;
int err;
/* sanity checks */
assert(cinfo->btype != BT_NONE);
/* set all the vital stuff */
cirrusfb_set_fbinfo(info);
dev_dbg(info->device, "(RAM start set to: 0x%p)\n", info->screen_base);
err = fb_find_mode(&info->var, info, mode_option, NULL, 0, NULL, 8);
if (!err) {
dev_dbg(info->device, "wrong initial video mode\n");
err = -EINVAL;
goto err_dealloc_cmap;
}
info->var.activate = FB_ACTIVATE_NOW;
err = cirrusfb_check_var(&info->var, info);
if (err < 0) {
/* should never happen */
dev_dbg(info->device,
"choking on default var... umm, no good.\n");
goto err_dealloc_cmap;
}
err = register_framebuffer(info);
if (err < 0) {
dev_err(info->device,
"could not register fb device; err = %d!\n", err);
goto err_dealloc_cmap;
}
return 0;
err_dealloc_cmap:
fb_dealloc_cmap(&info->cmap);
return err;
}
static void __devexit cirrusfb_cleanup(struct fb_info *info)
{
struct cirrusfb_info *cinfo = info->par;
switch_monitor(cinfo, 0);
unregister_framebuffer(info);
fb_dealloc_cmap(&info->cmap);
dev_dbg(info->device, "Framebuffer unregistered\n");
cinfo->unmap(info);
framebuffer_release(info);
}
#ifdef CONFIG_PCI
static int __devinit cirrusfb_pci_register(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct cirrusfb_info *cinfo;
struct fb_info *info;
unsigned long board_addr, board_size;
int ret;
ret = pci_enable_device(pdev);
if (ret < 0) {
printk(KERN_ERR "cirrusfb: Cannot enable PCI device\n");
goto err_out;
}
info = framebuffer_alloc(sizeof(struct cirrusfb_info), &pdev->dev);
if (!info) {
printk(KERN_ERR "cirrusfb: could not allocate memory\n");
ret = -ENOMEM;
goto err_out;
}
cinfo = info->par;
cinfo->btype = (enum cirrus_board) ent->driver_data;
dev_dbg(info->device,
" Found PCI device, base address 0 is 0x%Lx, btype set to %d\n",
(unsigned long long)pdev->resource[0].start, cinfo->btype);
dev_dbg(info->device, " base address 1 is 0x%Lx\n",
(unsigned long long)pdev->resource[1].start);
if (isPReP) {
pci_write_config_dword(pdev, PCI_BASE_ADDRESS_0, 0x00000000);
#ifdef CONFIG_PPC_PREP
get_prep_addrs(&board_addr, &info->fix.mmio_start);
#endif
/* PReP dies if we ioremap the IO registers, but it works w/out... */
cinfo->regbase = (char __iomem *) info->fix.mmio_start;
} else {
dev_dbg(info->device,
"Attempt to get PCI info for Cirrus Graphics Card\n");
get_pci_addrs(pdev, &board_addr, &info->fix.mmio_start);
/* FIXME: this forces VGA. alternatives? */
cinfo->regbase = NULL;
cinfo->laguna_mmio = ioremap(info->fix.mmio_start, 0x1000);
}
dev_dbg(info->device, "Board address: 0x%lx, register address: 0x%lx\n",
board_addr, info->fix.mmio_start);
board_size = (cinfo->btype == BT_GD5480) ?
32 * MB_ : cirrusfb_get_memsize(info, cinfo->regbase);
ret = pci_request_regions(pdev, "cirrusfb");
if (ret < 0) {
dev_err(info->device, "cannot reserve region 0x%lx, abort\n",
board_addr);
goto err_release_fb;
}
#if 0 /* if the system didn't claim this region, we would... */
if (!request_mem_region(0xA0000, 65535, "cirrusfb")) {
dev_err(info->device, "cannot reserve region 0x%lx, abort\n",
0xA0000L);
ret = -EBUSY;
goto err_release_regions;
}
#endif
if (request_region(0x3C0, 32, "cirrusfb"))
release_io_ports = 1;
info->screen_base = ioremap(board_addr, board_size);
if (!info->screen_base) {
ret = -EIO;
goto err_release_legacy;
}
info->fix.smem_start = board_addr;
info->screen_size = board_size;
cinfo->unmap = cirrusfb_pci_unmap;
dev_info(info->device,
"Cirrus Logic chipset on PCI bus, RAM (%lu kB) at 0x%lx\n",
info->screen_size >> 10, board_addr);
pci_set_drvdata(pdev, info);
ret = cirrusfb_register(info);
if (!ret)
return 0;
pci_set_drvdata(pdev, NULL);
iounmap(info->screen_base);
err_release_legacy:
if (release_io_ports)
release_region(0x3C0, 32);
#if 0
release_mem_region(0xA0000, 65535);
err_release_regions:
#endif
pci_release_regions(pdev);
err_release_fb:
if (cinfo->laguna_mmio != NULL)
iounmap(cinfo->laguna_mmio);
framebuffer_release(info);
err_out:
return ret;
}
static void __devexit cirrusfb_pci_unregister(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
cirrusfb_cleanup(info);
}
static struct pci_driver cirrusfb_pci_driver = {
.name = "cirrusfb",
.id_table = cirrusfb_pci_table,
.probe = cirrusfb_pci_register,
.remove = __devexit_p(cirrusfb_pci_unregister),
#ifdef CONFIG_PM
#if 0
.suspend = cirrusfb_pci_suspend,
.resume = cirrusfb_pci_resume,
#endif
#endif
};
#endif /* CONFIG_PCI */
#ifdef CONFIG_ZORRO
static int __devinit cirrusfb_zorro_register(struct zorro_dev *z,
const struct zorro_device_id *ent)
{
struct cirrusfb_info *cinfo;
struct fb_info *info;
enum cirrus_board btype;
struct zorro_dev *z2 = NULL;
unsigned long board_addr, board_size, size;
int ret;
btype = ent->driver_data;
if (cirrusfb_zorro_table2[btype].id2)
z2 = zorro_find_device(cirrusfb_zorro_table2[btype].id2, NULL);
size = cirrusfb_zorro_table2[btype].size;
info = framebuffer_alloc(sizeof(struct cirrusfb_info), &z->dev);
if (!info) {
printk(KERN_ERR "cirrusfb: could not allocate memory\n");
ret = -ENOMEM;
goto err_out;
}
dev_info(info->device, "%s board detected\n",
cirrusfb_board_info[btype].name);
cinfo = info->par;
cinfo->btype = btype;
assert(z);
assert(btype != BT_NONE);
board_addr = zorro_resource_start(z);
board_size = zorro_resource_len(z);
info->screen_size = size;
if (!zorro_request_device(z, "cirrusfb")) {
dev_err(info->device, "cannot reserve region 0x%lx, abort\n",
board_addr);
ret = -EBUSY;
goto err_release_fb;
}
ret = -EIO;
if (btype == BT_PICASSO4) {
dev_info(info->device, " REG at $%lx\n", board_addr + 0x600000);
/* To be precise, for the P4 this is not the */
/* begin of the board, but the begin of RAM. */
/* for P4, map in its address space in 2 chunks (### TEST! ) */
/* (note the ugly hardcoded 16M number) */
cinfo->regbase = ioremap(board_addr, 16777216);
if (!cinfo->regbase)
goto err_release_region;
dev_dbg(info->device, "Virtual address for board set to: $%p\n",
cinfo->regbase);
cinfo->regbase += 0x600000;
info->fix.mmio_start = board_addr + 0x600000;
info->fix.smem_start = board_addr + 16777216;
info->screen_base = ioremap(info->fix.smem_start, 16777216);
if (!info->screen_base)
goto err_unmap_regbase;
} else {
dev_info(info->device, " REG at $%lx\n",
(unsigned long) z2->resource.start);
info->fix.smem_start = board_addr;
if (board_addr > 0x01000000)
info->screen_base = ioremap(board_addr, board_size);
else
info->screen_base = (caddr_t) ZTWO_VADDR(board_addr);
if (!info->screen_base)
goto err_release_region;
/* set address for REG area of board */
cinfo->regbase = (caddr_t) ZTWO_VADDR(z2->resource.start);
info->fix.mmio_start = z2->resource.start;
dev_dbg(info->device, "Virtual address for board set to: $%p\n",
cinfo->regbase);
}
cinfo->unmap = cirrusfb_zorro_unmap;
dev_info(info->device,
"Cirrus Logic chipset on Zorro bus, RAM (%lu MB) at $%lx\n",
board_size / MB_, board_addr);
zorro_set_drvdata(z, info);
/* MCLK select etc. */
if (cirrusfb_board_info[btype].init_sr1f)
vga_wseq(cinfo->regbase, CL_SEQR1F,
cirrusfb_board_info[btype].sr1f);
ret = cirrusfb_register(info);
if (!ret)
return 0;
if (btype == BT_PICASSO4 || board_addr > 0x01000000)
iounmap(info->screen_base);
err_unmap_regbase:
if (btype == BT_PICASSO4)
iounmap(cinfo->regbase - 0x600000);
err_release_region:
release_region(board_addr, board_size);
err_release_fb:
framebuffer_release(info);
err_out:
return ret;
}
void __devexit cirrusfb_zorro_unregister(struct zorro_dev *z)
{
struct fb_info *info = zorro_get_drvdata(z);
cirrusfb_cleanup(info);
}
static struct zorro_driver cirrusfb_zorro_driver = {
.name = "cirrusfb",
.id_table = cirrusfb_zorro_table,
.probe = cirrusfb_zorro_register,
.remove = __devexit_p(cirrusfb_zorro_unregister),
};
#endif /* CONFIG_ZORRO */
#ifndef MODULE
static int __init cirrusfb_setup(char *options)
{
char *this_opt;
if (!options || !*options)
return 0;
while ((this_opt = strsep(&options, ",")) != NULL) {
if (!*this_opt)
continue;
if (!strcmp(this_opt, "noaccel"))
noaccel = 1;
else if (!strncmp(this_opt, "mode:", 5))
mode_option = this_opt + 5;
else
mode_option = this_opt;
}
return 0;
}
#endif
/*
* Modularization
*/
MODULE_AUTHOR("Copyright 1999,2000 Jeff Garzik <jgarzik@pobox.com>");
MODULE_DESCRIPTION("Accelerated FBDev driver for Cirrus Logic chips");
MODULE_LICENSE("GPL");
static int __init cirrusfb_init(void)
{
int error = 0;
#ifndef MODULE
char *option = NULL;
if (fb_get_options("cirrusfb", &option))
return -ENODEV;
cirrusfb_setup(option);
#endif
#ifdef CONFIG_ZORRO
error |= zorro_register_driver(&cirrusfb_zorro_driver);
#endif
#ifdef CONFIG_PCI
error |= pci_register_driver(&cirrusfb_pci_driver);
#endif
return error;
}
static void __exit cirrusfb_exit(void)
{
#ifdef CONFIG_PCI
pci_unregister_driver(&cirrusfb_pci_driver);
#endif
#ifdef CONFIG_ZORRO
zorro_unregister_driver(&cirrusfb_zorro_driver);
#endif
}
module_init(cirrusfb_init);
module_param(mode_option, charp, 0);
MODULE_PARM_DESC(mode_option, "Initial video mode e.g. '648x480-8@60'");
module_param(noaccel, bool, 0);
MODULE_PARM_DESC(noaccel, "Disable acceleration");
#ifdef MODULE
module_exit(cirrusfb_exit);
#endif
/**********************************************************************/
/* about the following functions - I have used the same names for the */
/* functions as Markus Wild did in his Retina driver for NetBSD as */
/* they just made sense for this purpose. Apart from that, I wrote */
/* these functions myself. */
/**********************************************************************/
/*** WGen() - write into one of the external/general registers ***/
static void WGen(const struct cirrusfb_info *cinfo,
int regnum, unsigned char val)
{
unsigned long regofs = 0;
if (cinfo->btype == BT_PICASSO) {
/* Picasso II specific hack */
/* if (regnum == VGA_PEL_IR || regnum == VGA_PEL_D ||
regnum == CL_VSSM2) */
if (regnum == VGA_PEL_IR || regnum == VGA_PEL_D)
regofs = 0xfff;
}
vga_w(cinfo->regbase, regofs + regnum, val);
}
/*** RGen() - read out one of the external/general registers ***/
static unsigned char RGen(const struct cirrusfb_info *cinfo, int regnum)
{
unsigned long regofs = 0;
if (cinfo->btype == BT_PICASSO) {
/* Picasso II specific hack */
/* if (regnum == VGA_PEL_IR || regnum == VGA_PEL_D ||
regnum == CL_VSSM2) */
if (regnum == VGA_PEL_IR || regnum == VGA_PEL_D)
regofs = 0xfff;
}
return vga_r(cinfo->regbase, regofs + regnum);
}
/*** AttrOn() - turn on VideoEnable for Attribute controller ***/
static void AttrOn(const struct cirrusfb_info *cinfo)
{
assert(cinfo != NULL);
if (vga_rcrt(cinfo->regbase, CL_CRT24) & 0x80) {
/* if we're just in "write value" mode, write back the */
/* same value as before to not modify anything */
vga_w(cinfo->regbase, VGA_ATT_IW,
vga_r(cinfo->regbase, VGA_ATT_R));
}
/* turn on video bit */
/* vga_w(cinfo->regbase, VGA_ATT_IW, 0x20); */
vga_w(cinfo->regbase, VGA_ATT_IW, 0x33);
/* dummy write on Reg0 to be on "write index" mode next time */
vga_w(cinfo->regbase, VGA_ATT_IW, 0x00);
}
/*** WHDR() - write into the Hidden DAC register ***/
/* as the HDR is the only extension register that requires special treatment
* (the other extension registers are accessible just like the "ordinary"
* registers of their functional group) here is a specialized routine for
* accessing the HDR
*/
static void WHDR(const struct cirrusfb_info *cinfo, unsigned char val)
{
unsigned char dummy;
if (is_laguna(cinfo))
return;
if (cinfo->btype == BT_PICASSO) {
/* Klaus' hint for correct access to HDR on some boards */
/* first write 0 to pixel mask (3c6) */
WGen(cinfo, VGA_PEL_MSK, 0x00);
udelay(200);
/* next read dummy from pixel address (3c8) */
dummy = RGen(cinfo, VGA_PEL_IW);
udelay(200);
}
/* now do the usual stuff to access the HDR */
dummy = RGen(cinfo, VGA_PEL_MSK);
udelay(200);
dummy = RGen(cinfo, VGA_PEL_MSK);
udelay(200);
dummy = RGen(cinfo, VGA_PEL_MSK);
udelay(200);
dummy = RGen(cinfo, VGA_PEL_MSK);
udelay(200);
WGen(cinfo, VGA_PEL_MSK, val);
udelay(200);
if (cinfo->btype == BT_PICASSO) {
/* now first reset HDR access counter */
dummy = RGen(cinfo, VGA_PEL_IW);
udelay(200);
/* and at the end, restore the mask value */
/* ## is this mask always 0xff? */
WGen(cinfo, VGA_PEL_MSK, 0xff);
udelay(200);
}
}
/*** WSFR() - write to the "special function register" (SFR) ***/
static void WSFR(struct cirrusfb_info *cinfo, unsigned char val)
{
#ifdef CONFIG_ZORRO
assert(cinfo->regbase != NULL);
cinfo->SFR = val;
z_writeb(val, cinfo->regbase + 0x8000);
#endif
}
/* The Picasso has a second register for switching the monitor bit */
static void WSFR2(struct cirrusfb_info *cinfo, unsigned char val)
{
#ifdef CONFIG_ZORRO
/* writing an arbitrary value to this one causes the monitor switcher */
/* to flip to Amiga display */
assert(cinfo->regbase != NULL);
cinfo->SFR = val;
z_writeb(val, cinfo->regbase + 0x9000);
#endif
}
/*** WClut - set CLUT entry (range: 0..63) ***/
static void WClut(struct cirrusfb_info *cinfo, unsigned char regnum, unsigned char red,
unsigned char green, unsigned char blue)
{
unsigned int data = VGA_PEL_D;
/* address write mode register is not translated.. */
vga_w(cinfo->regbase, VGA_PEL_IW, regnum);
if (cinfo->btype == BT_PICASSO || cinfo->btype == BT_PICASSO4 ||
cinfo->btype == BT_ALPINE || cinfo->btype == BT_GD5480 ||
cinfo->btype == BT_SD64 || is_laguna(cinfo)) {
/* but DAC data register IS, at least for Picasso II */
if (cinfo->btype == BT_PICASSO)
data += 0xfff;
vga_w(cinfo->regbase, data, red);
vga_w(cinfo->regbase, data, green);
vga_w(cinfo->regbase, data, blue);
} else {
vga_w(cinfo->regbase, data, blue);
vga_w(cinfo->regbase, data, green);
vga_w(cinfo->regbase, data, red);
}
}
#if 0
/*** RClut - read CLUT entry (range 0..63) ***/
static void RClut(struct cirrusfb_info *cinfo, unsigned char regnum, unsigned char *red,
unsigned char *green, unsigned char *blue)
{
unsigned int data = VGA_PEL_D;
vga_w(cinfo->regbase, VGA_PEL_IR, regnum);
if (cinfo->btype == BT_PICASSO || cinfo->btype == BT_PICASSO4 ||
cinfo->btype == BT_ALPINE || cinfo->btype == BT_GD5480) {
if (cinfo->btype == BT_PICASSO)
data += 0xfff;
*red = vga_r(cinfo->regbase, data);
*green = vga_r(cinfo->regbase, data);
*blue = vga_r(cinfo->regbase, data);
} else {
*blue = vga_r(cinfo->regbase, data);
*green = vga_r(cinfo->regbase, data);
*red = vga_r(cinfo->regbase, data);
}
}
#endif
/*******************************************************************
cirrusfb_WaitBLT()
Wait for the BitBLT engine to complete a possible earlier job
*********************************************************************/
/* FIXME: use interrupts instead */
static void cirrusfb_WaitBLT(u8 __iomem *regbase)
{
while (vga_rgfx(regbase, CL_GR31) & 0x08)
cpu_relax();
}
/*******************************************************************
cirrusfb_BitBLT()
perform accelerated "scrolling"
********************************************************************/
static void cirrusfb_set_blitter(u8 __iomem *regbase,
u_short nwidth, u_short nheight,
u_long nsrc, u_long ndest,
u_short bltmode, u_short line_length)
{
/* pitch: set to line_length */
/* dest pitch low */
vga_wgfx(regbase, CL_GR24, line_length & 0xff);
/* dest pitch hi */
vga_wgfx(regbase, CL_GR25, line_length >> 8);
/* source pitch low */
vga_wgfx(regbase, CL_GR26, line_length & 0xff);
/* source pitch hi */
vga_wgfx(regbase, CL_GR27, line_length >> 8);
/* BLT width: actual number of pixels - 1 */
/* BLT width low */
vga_wgfx(regbase, CL_GR20, nwidth & 0xff);
/* BLT width hi */
vga_wgfx(regbase, CL_GR21, nwidth >> 8);
/* BLT height: actual number of lines -1 */
/* BLT height low */
vga_wgfx(regbase, CL_GR22, nheight & 0xff);
/* BLT width hi */
vga_wgfx(regbase, CL_GR23, nheight >> 8);
/* BLT destination */
/* BLT dest low */
vga_wgfx(regbase, CL_GR28, (u_char) (ndest & 0xff));
/* BLT dest mid */
vga_wgfx(regbase, CL_GR29, (u_char) (ndest >> 8));
/* BLT dest hi */
vga_wgfx(regbase, CL_GR2A, (u_char) (ndest >> 16));
/* BLT source */
/* BLT src low */
vga_wgfx(regbase, CL_GR2C, (u_char) (nsrc & 0xff));
/* BLT src mid */
vga_wgfx(regbase, CL_GR2D, (u_char) (nsrc >> 8));
/* BLT src hi */
vga_wgfx(regbase, CL_GR2E, (u_char) (nsrc >> 16));
/* BLT mode */
vga_wgfx(regbase, CL_GR30, bltmode); /* BLT mode */
/* BLT ROP: SrcCopy */
vga_wgfx(regbase, CL_GR32, 0x0d); /* BLT ROP */
/* and finally: GO! */
vga_wgfx(regbase, CL_GR31, 0x02); /* BLT Start/status */
}
/*******************************************************************
cirrusfb_BitBLT()
perform accelerated "scrolling"
********************************************************************/
static void cirrusfb_BitBLT(u8 __iomem *regbase, int bits_per_pixel,
u_short curx, u_short cury,
u_short destx, u_short desty,
u_short width, u_short height,
u_short line_length)
{
u_short nwidth = width - 1;
u_short nheight = height - 1;
u_long nsrc, ndest;
u_char bltmode;
bltmode = 0x00;
/* if source adr < dest addr, do the Blt backwards */
if (cury <= desty) {
if (cury == desty) {
/* if src and dest are on the same line, check x */
if (curx < destx)
bltmode |= 0x01;
} else
bltmode |= 0x01;
}
/* standard case: forward blitting */
nsrc = (cury * line_length) + curx;
ndest = (desty * line_length) + destx;
if (bltmode) {
/* this means start addresses are at the end,
* counting backwards
*/
nsrc += nheight * line_length + nwidth;
ndest += nheight * line_length + nwidth;
}
cirrusfb_WaitBLT(regbase);
cirrusfb_set_blitter(regbase, nwidth, nheight,
nsrc, ndest, bltmode, line_length);
}
/*******************************************************************
cirrusfb_RectFill()
perform accelerated rectangle fill
********************************************************************/
static void cirrusfb_RectFill(u8 __iomem *regbase, int bits_per_pixel,
u_short x, u_short y, u_short width, u_short height,
u32 fg_color, u32 bg_color, u_short line_length,
u_char blitmode)
{
u_long ndest = (y * line_length) + x;
u_char op;
cirrusfb_WaitBLT(regbase);
/* This is a ColorExpand Blt, using the */
/* same color for foreground and background */
vga_wgfx(regbase, VGA_GFX_SR_VALUE, bg_color);
vga_wgfx(regbase, VGA_GFX_SR_ENABLE, fg_color);
op = 0x80;
if (bits_per_pixel >= 16) {
vga_wgfx(regbase, CL_GR10, bg_color >> 8);
vga_wgfx(regbase, CL_GR11, fg_color >> 8);
op = 0x90;
}
if (bits_per_pixel >= 24) {
vga_wgfx(regbase, CL_GR12, bg_color >> 16);
vga_wgfx(regbase, CL_GR13, fg_color >> 16);
op = 0xa0;
}
if (bits_per_pixel == 32) {
vga_wgfx(regbase, CL_GR14, bg_color >> 24);
vga_wgfx(regbase, CL_GR15, fg_color >> 24);
op = 0xb0;
}
cirrusfb_set_blitter(regbase, width - 1, height - 1,
0, ndest, op | blitmode, line_length);
}
/**************************************************************************
* bestclock() - determine closest possible clock lower(?) than the
* desired pixel clock
**************************************************************************/
static void bestclock(long freq, int *nom, int *den, int *div)
{
int n, d;
long h, diff;
assert(nom != NULL);
assert(den != NULL);
assert(div != NULL);
*nom = 0;
*den = 0;
*div = 0;
if (freq < 8000)
freq = 8000;
diff = freq;
for (n = 32; n < 128; n++) {
int s = 0;
d = (14318 * n) / freq;
if ((d >= 7) && (d <= 63)) {
int temp = d;
if (temp > 31) {
s = 1;
temp >>= 1;
}
h = ((14318 * n) / temp) >> s;
h = h > freq ? h - freq : freq - h;
if (h < diff) {
diff = h;
*nom = n;
*den = temp;
*div = s;
}
}
d++;
if ((d >= 7) && (d <= 63)) {
if (d > 31) {
s = 1;
d >>= 1;
}
h = ((14318 * n) / d) >> s;
h = h > freq ? h - freq : freq - h;
if (h < diff) {
diff = h;
*nom = n;
*den = d;
*div = s;
}
}
}
}
/* -------------------------------------------------------------------------
*
* debugging functions
*
* -------------------------------------------------------------------------
*/
#ifdef CIRRUSFB_DEBUG
/**
* cirrusfb_dbg_print_regs
* @base: If using newmmio, the newmmio base address, otherwise %NULL
* @reg_class: type of registers to read: %CRT, or %SEQ
*
* DESCRIPTION:
* Dumps the given list of VGA CRTC registers. If @base is %NULL,
* old-style I/O ports are queried for information, otherwise MMIO is
* used at the given @base address to query the information.
*/
static void cirrusfb_dbg_print_regs(struct fb_info *info,
caddr_t regbase,
enum cirrusfb_dbg_reg_class reg_class, ...)
{
va_list list;
unsigned char val = 0;
unsigned reg;
char *name;
va_start(list, reg_class);
name = va_arg(list, char *);
while (name != NULL) {
reg = va_arg(list, int);
switch (reg_class) {
case CRT:
val = vga_rcrt(regbase, (unsigned char) reg);
break;
case SEQ:
val = vga_rseq(regbase, (unsigned char) reg);
break;
default:
/* should never occur */
assert(false);
break;
}
dev_dbg(info->device, "%8s = 0x%02X\n", name, val);
name = va_arg(list, char *);
}
va_end(list);
}
/**
* cirrusfb_dbg_reg_dump
* @base: If using newmmio, the newmmio base address, otherwise %NULL
*
* DESCRIPTION:
* Dumps a list of interesting VGA and CIRRUSFB registers. If @base is %NULL,
* old-style I/O ports are queried for information, otherwise MMIO is
* used at the given @base address to query the information.
*/
static void cirrusfb_dbg_reg_dump(struct fb_info *info, caddr_t regbase)
{
dev_dbg(info->device, "VGA CRTC register dump:\n");
cirrusfb_dbg_print_regs(info, regbase, CRT,
"CR00", 0x00,
"CR01", 0x01,
"CR02", 0x02,
"CR03", 0x03,
"CR04", 0x04,
"CR05", 0x05,
"CR06", 0x06,
"CR07", 0x07,
"CR08", 0x08,
"CR09", 0x09,
"CR0A", 0x0A,
"CR0B", 0x0B,
"CR0C", 0x0C,
"CR0D", 0x0D,
"CR0E", 0x0E,
"CR0F", 0x0F,
"CR10", 0x10,
"CR11", 0x11,
"CR12", 0x12,
"CR13", 0x13,
"CR14", 0x14,
"CR15", 0x15,
"CR16", 0x16,
"CR17", 0x17,
"CR18", 0x18,
"CR22", 0x22,
"CR24", 0x24,
"CR26", 0x26,
"CR2D", 0x2D,
"CR2E", 0x2E,
"CR2F", 0x2F,
"CR30", 0x30,
"CR31", 0x31,
"CR32", 0x32,
"CR33", 0x33,
"CR34", 0x34,
"CR35", 0x35,
"CR36", 0x36,
"CR37", 0x37,
"CR38", 0x38,
"CR39", 0x39,
"CR3A", 0x3A,
"CR3B", 0x3B,
"CR3C", 0x3C,
"CR3D", 0x3D,
"CR3E", 0x3E,
"CR3F", 0x3F,
NULL);
dev_dbg(info->device, "\n");
dev_dbg(info->device, "VGA SEQ register dump:\n");
cirrusfb_dbg_print_regs(info, regbase, SEQ,
"SR00", 0x00,
"SR01", 0x01,
"SR02", 0x02,
"SR03", 0x03,
"SR04", 0x04,
"SR08", 0x08,
"SR09", 0x09,
"SR0A", 0x0A,
"SR0B", 0x0B,
"SR0D", 0x0D,
"SR10", 0x10,
"SR11", 0x11,
"SR12", 0x12,
"SR13", 0x13,
"SR14", 0x14,
"SR15", 0x15,
"SR16", 0x16,
"SR17", 0x17,
"SR18", 0x18,
"SR19", 0x19,
"SR1A", 0x1A,
"SR1B", 0x1B,
"SR1C", 0x1C,
"SR1D", 0x1D,
"SR1E", 0x1E,
"SR1F", 0x1F,
NULL);
dev_dbg(info->device, "\n");
}
#endif /* CIRRUSFB_DEBUG */
| gpl-2.0 |
blueskycoco/sq-linux | fs/afs/server.c | 8199 | 8083 | /* AFS server record management
*
* Copyright (C) 2002, 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* 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; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include "internal.h"
static unsigned afs_server_timeout = 10; /* server timeout in seconds */
static void afs_reap_server(struct work_struct *);
/* tree of all the servers, indexed by IP address */
static struct rb_root afs_servers = RB_ROOT;
static DEFINE_RWLOCK(afs_servers_lock);
/* LRU list of all the servers not currently in use */
static LIST_HEAD(afs_server_graveyard);
static DEFINE_SPINLOCK(afs_server_graveyard_lock);
static DECLARE_DELAYED_WORK(afs_server_reaper, afs_reap_server);
/*
* install a server record in the master tree
*/
static int afs_install_server(struct afs_server *server)
{
struct afs_server *xserver;
struct rb_node **pp, *p;
int ret;
_enter("%p", server);
write_lock(&afs_servers_lock);
ret = -EEXIST;
pp = &afs_servers.rb_node;
p = NULL;
while (*pp) {
p = *pp;
_debug("- consider %p", p);
xserver = rb_entry(p, struct afs_server, master_rb);
if (server->addr.s_addr < xserver->addr.s_addr)
pp = &(*pp)->rb_left;
else if (server->addr.s_addr > xserver->addr.s_addr)
pp = &(*pp)->rb_right;
else
goto error;
}
rb_link_node(&server->master_rb, p, pp);
rb_insert_color(&server->master_rb, &afs_servers);
ret = 0;
error:
write_unlock(&afs_servers_lock);
return ret;
}
/*
* allocate a new server record
*/
static struct afs_server *afs_alloc_server(struct afs_cell *cell,
const struct in_addr *addr)
{
struct afs_server *server;
_enter("");
server = kzalloc(sizeof(struct afs_server), GFP_KERNEL);
if (server) {
atomic_set(&server->usage, 1);
server->cell = cell;
INIT_LIST_HEAD(&server->link);
INIT_LIST_HEAD(&server->grave);
init_rwsem(&server->sem);
spin_lock_init(&server->fs_lock);
server->fs_vnodes = RB_ROOT;
server->cb_promises = RB_ROOT;
spin_lock_init(&server->cb_lock);
init_waitqueue_head(&server->cb_break_waitq);
INIT_DELAYED_WORK(&server->cb_break_work,
afs_dispatch_give_up_callbacks);
memcpy(&server->addr, addr, sizeof(struct in_addr));
server->addr.s_addr = addr->s_addr;
_leave(" = %p{%d}", server, atomic_read(&server->usage));
} else {
_leave(" = NULL [nomem]");
}
return server;
}
/*
* get an FS-server record for a cell
*/
struct afs_server *afs_lookup_server(struct afs_cell *cell,
const struct in_addr *addr)
{
struct afs_server *server, *candidate;
_enter("%p,%pI4", cell, &addr->s_addr);
/* quick scan of the list to see if we already have the server */
read_lock(&cell->servers_lock);
list_for_each_entry(server, &cell->servers, link) {
if (server->addr.s_addr == addr->s_addr)
goto found_server_quickly;
}
read_unlock(&cell->servers_lock);
candidate = afs_alloc_server(cell, addr);
if (!candidate) {
_leave(" = -ENOMEM");
return ERR_PTR(-ENOMEM);
}
write_lock(&cell->servers_lock);
/* check the cell's server list again */
list_for_each_entry(server, &cell->servers, link) {
if (server->addr.s_addr == addr->s_addr)
goto found_server;
}
_debug("new");
server = candidate;
if (afs_install_server(server) < 0)
goto server_in_two_cells;
afs_get_cell(cell);
list_add_tail(&server->link, &cell->servers);
write_unlock(&cell->servers_lock);
_leave(" = %p{%d}", server, atomic_read(&server->usage));
return server;
/* found a matching server quickly */
found_server_quickly:
_debug("found quickly");
afs_get_server(server);
read_unlock(&cell->servers_lock);
no_longer_unused:
if (!list_empty(&server->grave)) {
spin_lock(&afs_server_graveyard_lock);
list_del_init(&server->grave);
spin_unlock(&afs_server_graveyard_lock);
}
_leave(" = %p{%d}", server, atomic_read(&server->usage));
return server;
/* found a matching server on the second pass */
found_server:
_debug("found");
afs_get_server(server);
write_unlock(&cell->servers_lock);
kfree(candidate);
goto no_longer_unused;
/* found a server that seems to be in two cells */
server_in_two_cells:
write_unlock(&cell->servers_lock);
kfree(candidate);
printk(KERN_NOTICE "kAFS: Server %pI4 appears to be in two cells\n",
addr);
_leave(" = -EEXIST");
return ERR_PTR(-EEXIST);
}
/*
* look up a server by its IP address
*/
struct afs_server *afs_find_server(const struct in_addr *_addr)
{
struct afs_server *server = NULL;
struct rb_node *p;
struct in_addr addr = *_addr;
_enter("%pI4", &addr.s_addr);
read_lock(&afs_servers_lock);
p = afs_servers.rb_node;
while (p) {
server = rb_entry(p, struct afs_server, master_rb);
_debug("- consider %p", p);
if (addr.s_addr < server->addr.s_addr) {
p = p->rb_left;
} else if (addr.s_addr > server->addr.s_addr) {
p = p->rb_right;
} else {
afs_get_server(server);
goto found;
}
}
server = NULL;
found:
read_unlock(&afs_servers_lock);
ASSERTIFCMP(server, server->addr.s_addr, ==, addr.s_addr);
_leave(" = %p", server);
return server;
}
/*
* destroy a server record
* - removes from the cell list
*/
void afs_put_server(struct afs_server *server)
{
if (!server)
return;
_enter("%p{%d}", server, atomic_read(&server->usage));
_debug("PUT SERVER %d", atomic_read(&server->usage));
ASSERTCMP(atomic_read(&server->usage), >, 0);
if (likely(!atomic_dec_and_test(&server->usage))) {
_leave("");
return;
}
afs_flush_callback_breaks(server);
spin_lock(&afs_server_graveyard_lock);
if (atomic_read(&server->usage) == 0) {
list_move_tail(&server->grave, &afs_server_graveyard);
server->time_of_death = get_seconds();
queue_delayed_work(afs_wq, &afs_server_reaper,
afs_server_timeout * HZ);
}
spin_unlock(&afs_server_graveyard_lock);
_leave(" [dead]");
}
/*
* destroy a dead server
*/
static void afs_destroy_server(struct afs_server *server)
{
_enter("%p", server);
ASSERTIF(server->cb_break_head != server->cb_break_tail,
delayed_work_pending(&server->cb_break_work));
ASSERTCMP(server->fs_vnodes.rb_node, ==, NULL);
ASSERTCMP(server->cb_promises.rb_node, ==, NULL);
ASSERTCMP(server->cb_break_head, ==, server->cb_break_tail);
ASSERTCMP(atomic_read(&server->cb_break_n), ==, 0);
afs_put_cell(server->cell);
kfree(server);
}
/*
* reap dead server records
*/
static void afs_reap_server(struct work_struct *work)
{
LIST_HEAD(corpses);
struct afs_server *server;
unsigned long delay, expiry;
time_t now;
now = get_seconds();
spin_lock(&afs_server_graveyard_lock);
while (!list_empty(&afs_server_graveyard)) {
server = list_entry(afs_server_graveyard.next,
struct afs_server, grave);
/* the queue is ordered most dead first */
expiry = server->time_of_death + afs_server_timeout;
if (expiry > now) {
delay = (expiry - now) * HZ;
if (!queue_delayed_work(afs_wq, &afs_server_reaper,
delay)) {
cancel_delayed_work(&afs_server_reaper);
queue_delayed_work(afs_wq, &afs_server_reaper,
delay);
}
break;
}
write_lock(&server->cell->servers_lock);
write_lock(&afs_servers_lock);
if (atomic_read(&server->usage) > 0) {
list_del_init(&server->grave);
} else {
list_move_tail(&server->grave, &corpses);
list_del_init(&server->link);
rb_erase(&server->master_rb, &afs_servers);
}
write_unlock(&afs_servers_lock);
write_unlock(&server->cell->servers_lock);
}
spin_unlock(&afs_server_graveyard_lock);
/* now reap the corpses we've extracted */
while (!list_empty(&corpses)) {
server = list_entry(corpses.next, struct afs_server, grave);
list_del(&server->grave);
afs_destroy_server(server);
}
}
/*
* discard all the server records for rmmod
*/
void __exit afs_purge_servers(void)
{
afs_server_timeout = 0;
cancel_delayed_work(&afs_server_reaper);
queue_delayed_work(afs_wq, &afs_server_reaper, 0);
}
| gpl-2.0 |
mpokwsths/flo_kernel | drivers/uio/uio_sercos3.c | 8455 | 6526 | /* sercos3: UIO driver for the Automata Sercos III PCI card
Copyright (C) 2008 Linutronix GmbH
Author: John Ogness <john.ogness@linutronix.de>
This is a straight-forward UIO driver, where interrupts are disabled
by the interrupt handler and re-enabled via a write to the UIO device
by the userspace-part.
The only part that may seem odd is the use of a logical OR when
storing and restoring enabled interrupts. This is done because the
userspace-part could directly modify the Interrupt Enable Register
at any time. To reduce possible conflicts, the kernel driver uses
a logical OR to make more controlled changes (rather than blindly
overwriting previous values).
Race conditions exist if the userspace-part directly modifies the
Interrupt Enable Register while in operation. The consequences are
that certain interrupts would fail to be enabled or disabled. For
this reason, the userspace-part should only directly modify the
Interrupt Enable Register at the beginning (to get things going).
The userspace-part can safely disable interrupts at any time using
a write to the UIO device.
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/uio_driver.h>
#include <linux/io.h>
#include <linux/slab.h>
/* ID's for SERCOS III PCI card (PLX 9030) */
#define SERCOS_SUB_VENDOR_ID 0x1971
#define SERCOS_SUB_SYSID_3530 0x3530
#define SERCOS_SUB_SYSID_3535 0x3535
#define SERCOS_SUB_SYSID_3780 0x3780
/* Interrupt Enable Register */
#define IER0_OFFSET 0x08
/* Interrupt Status Register */
#define ISR0_OFFSET 0x18
struct sercos3_priv {
u32 ier0_cache;
spinlock_t ier0_cache_lock;
};
/* this function assumes ier0_cache_lock is locked! */
static void sercos3_disable_interrupts(struct uio_info *info,
struct sercos3_priv *priv)
{
void __iomem *ier0 = info->mem[3].internal_addr + IER0_OFFSET;
/* add enabled interrupts to cache */
priv->ier0_cache |= ioread32(ier0);
/* disable interrupts */
iowrite32(0, ier0);
}
/* this function assumes ier0_cache_lock is locked! */
static void sercos3_enable_interrupts(struct uio_info *info,
struct sercos3_priv *priv)
{
void __iomem *ier0 = info->mem[3].internal_addr + IER0_OFFSET;
/* restore previously enabled interrupts */
iowrite32(ioread32(ier0) | priv->ier0_cache, ier0);
priv->ier0_cache = 0;
}
static irqreturn_t sercos3_handler(int irq, struct uio_info *info)
{
struct sercos3_priv *priv = info->priv;
void __iomem *isr0 = info->mem[3].internal_addr + ISR0_OFFSET;
void __iomem *ier0 = info->mem[3].internal_addr + IER0_OFFSET;
if (!(ioread32(isr0) & ioread32(ier0)))
return IRQ_NONE;
spin_lock(&priv->ier0_cache_lock);
sercos3_disable_interrupts(info, priv);
spin_unlock(&priv->ier0_cache_lock);
return IRQ_HANDLED;
}
static int sercos3_irqcontrol(struct uio_info *info, s32 irq_on)
{
struct sercos3_priv *priv = info->priv;
spin_lock_irq(&priv->ier0_cache_lock);
if (irq_on)
sercos3_enable_interrupts(info, priv);
else
sercos3_disable_interrupts(info, priv);
spin_unlock_irq(&priv->ier0_cache_lock);
return 0;
}
static int sercos3_setup_iomem(struct pci_dev *dev, struct uio_info *info,
int n, int pci_bar)
{
info->mem[n].addr = pci_resource_start(dev, pci_bar);
if (!info->mem[n].addr)
return -1;
info->mem[n].internal_addr = ioremap(pci_resource_start(dev, pci_bar),
pci_resource_len(dev, pci_bar));
if (!info->mem[n].internal_addr)
return -1;
info->mem[n].size = pci_resource_len(dev, pci_bar);
info->mem[n].memtype = UIO_MEM_PHYS;
return 0;
}
static int __devinit sercos3_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
struct uio_info *info;
struct sercos3_priv *priv;
int i;
info = kzalloc(sizeof(struct uio_info), GFP_KERNEL);
if (!info)
return -ENOMEM;
priv = kzalloc(sizeof(struct sercos3_priv), GFP_KERNEL);
if (!priv)
goto out_free;
if (pci_enable_device(dev))
goto out_free_priv;
if (pci_request_regions(dev, "sercos3"))
goto out_disable;
/* we only need PCI BAR's 0, 2, 3, 4, 5 */
if (sercos3_setup_iomem(dev, info, 0, 0))
goto out_unmap;
if (sercos3_setup_iomem(dev, info, 1, 2))
goto out_unmap;
if (sercos3_setup_iomem(dev, info, 2, 3))
goto out_unmap;
if (sercos3_setup_iomem(dev, info, 3, 4))
goto out_unmap;
if (sercos3_setup_iomem(dev, info, 4, 5))
goto out_unmap;
spin_lock_init(&priv->ier0_cache_lock);
info->priv = priv;
info->name = "Sercos_III_PCI";
info->version = "0.0.1";
info->irq = dev->irq;
info->irq_flags = IRQF_SHARED;
info->handler = sercos3_handler;
info->irqcontrol = sercos3_irqcontrol;
pci_set_drvdata(dev, info);
if (uio_register_device(&dev->dev, info))
goto out_unmap;
return 0;
out_unmap:
for (i = 0; i < 5; i++) {
if (info->mem[i].internal_addr)
iounmap(info->mem[i].internal_addr);
}
pci_release_regions(dev);
out_disable:
pci_disable_device(dev);
out_free_priv:
kfree(priv);
out_free:
kfree(info);
return -ENODEV;
}
static void sercos3_pci_remove(struct pci_dev *dev)
{
struct uio_info *info = pci_get_drvdata(dev);
int i;
uio_unregister_device(info);
pci_release_regions(dev);
pci_disable_device(dev);
pci_set_drvdata(dev, NULL);
for (i = 0; i < 5; i++) {
if (info->mem[i].internal_addr)
iounmap(info->mem[i].internal_addr);
}
kfree(info->priv);
kfree(info);
}
static struct pci_device_id sercos3_pci_ids[] __devinitdata = {
{
.vendor = PCI_VENDOR_ID_PLX,
.device = PCI_DEVICE_ID_PLX_9030,
.subvendor = SERCOS_SUB_VENDOR_ID,
.subdevice = SERCOS_SUB_SYSID_3530,
},
{
.vendor = PCI_VENDOR_ID_PLX,
.device = PCI_DEVICE_ID_PLX_9030,
.subvendor = SERCOS_SUB_VENDOR_ID,
.subdevice = SERCOS_SUB_SYSID_3535,
},
{
.vendor = PCI_VENDOR_ID_PLX,
.device = PCI_DEVICE_ID_PLX_9030,
.subvendor = SERCOS_SUB_VENDOR_ID,
.subdevice = SERCOS_SUB_SYSID_3780,
},
{ 0, }
};
static struct pci_driver sercos3_pci_driver = {
.name = "sercos3",
.id_table = sercos3_pci_ids,
.probe = sercos3_pci_probe,
.remove = sercos3_pci_remove,
};
static int __init sercos3_init_module(void)
{
return pci_register_driver(&sercos3_pci_driver);
}
static void __exit sercos3_exit_module(void)
{
pci_unregister_driver(&sercos3_pci_driver);
}
module_init(sercos3_init_module);
module_exit(sercos3_exit_module);
MODULE_DESCRIPTION("UIO driver for the Automata Sercos III PCI card");
MODULE_AUTHOR("John Ogness <john.ogness@linutronix.de>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
omnirom/android_kernel_acer_t30 | tools/power/cpupower/lib/cpufreq.c | 9991 | 3890 | /*
* (C) 2004-2009 Dominik Brodowski <linux@dominikbrodowski.de>
*
* Licensed under the terms of the GNU GPL License version 2.
*/
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "cpufreq.h"
#include "sysfs.h"
int cpufreq_cpu_exists(unsigned int cpu)
{
return sysfs_cpu_exists(cpu);
}
unsigned long cpufreq_get_freq_kernel(unsigned int cpu)
{
return sysfs_get_freq_kernel(cpu);
}
unsigned long cpufreq_get_freq_hardware(unsigned int cpu)
{
return sysfs_get_freq_hardware(cpu);
}
unsigned long cpufreq_get_transition_latency(unsigned int cpu)
{
return sysfs_get_freq_transition_latency(cpu);
}
int cpufreq_get_hardware_limits(unsigned int cpu,
unsigned long *min,
unsigned long *max)
{
if ((!min) || (!max))
return -EINVAL;
return sysfs_get_freq_hardware_limits(cpu, min, max);
}
char *cpufreq_get_driver(unsigned int cpu)
{
return sysfs_get_freq_driver(cpu);
}
void cpufreq_put_driver(char *ptr)
{
if (!ptr)
return;
free(ptr);
}
struct cpufreq_policy *cpufreq_get_policy(unsigned int cpu)
{
return sysfs_get_freq_policy(cpu);
}
void cpufreq_put_policy(struct cpufreq_policy *policy)
{
if ((!policy) || (!policy->governor))
return;
free(policy->governor);
policy->governor = NULL;
free(policy);
}
struct cpufreq_available_governors *cpufreq_get_available_governors(unsigned
int cpu)
{
return sysfs_get_freq_available_governors(cpu);
}
void cpufreq_put_available_governors(struct cpufreq_available_governors *any)
{
struct cpufreq_available_governors *tmp, *next;
if (!any)
return;
tmp = any->first;
while (tmp) {
next = tmp->next;
if (tmp->governor)
free(tmp->governor);
free(tmp);
tmp = next;
}
}
struct cpufreq_available_frequencies
*cpufreq_get_available_frequencies(unsigned int cpu)
{
return sysfs_get_available_frequencies(cpu);
}
void cpufreq_put_available_frequencies(struct cpufreq_available_frequencies
*any) {
struct cpufreq_available_frequencies *tmp, *next;
if (!any)
return;
tmp = any->first;
while (tmp) {
next = tmp->next;
free(tmp);
tmp = next;
}
}
struct cpufreq_affected_cpus *cpufreq_get_affected_cpus(unsigned int cpu)
{
return sysfs_get_freq_affected_cpus(cpu);
}
void cpufreq_put_affected_cpus(struct cpufreq_affected_cpus *any)
{
struct cpufreq_affected_cpus *tmp, *next;
if (!any)
return;
tmp = any->first;
while (tmp) {
next = tmp->next;
free(tmp);
tmp = next;
}
}
struct cpufreq_affected_cpus *cpufreq_get_related_cpus(unsigned int cpu)
{
return sysfs_get_freq_related_cpus(cpu);
}
void cpufreq_put_related_cpus(struct cpufreq_affected_cpus *any)
{
cpufreq_put_affected_cpus(any);
}
int cpufreq_set_policy(unsigned int cpu, struct cpufreq_policy *policy)
{
if (!policy || !(policy->governor))
return -EINVAL;
return sysfs_set_freq_policy(cpu, policy);
}
int cpufreq_modify_policy_min(unsigned int cpu, unsigned long min_freq)
{
return sysfs_modify_freq_policy_min(cpu, min_freq);
}
int cpufreq_modify_policy_max(unsigned int cpu, unsigned long max_freq)
{
return sysfs_modify_freq_policy_max(cpu, max_freq);
}
int cpufreq_modify_policy_governor(unsigned int cpu, char *governor)
{
if ((!governor) || (strlen(governor) > 19))
return -EINVAL;
return sysfs_modify_freq_policy_governor(cpu, governor);
}
int cpufreq_set_frequency(unsigned int cpu, unsigned long target_frequency)
{
return sysfs_set_frequency(cpu, target_frequency);
}
struct cpufreq_stats *cpufreq_get_stats(unsigned int cpu,
unsigned long long *total_time)
{
return sysfs_get_freq_stats(cpu, total_time);
}
void cpufreq_put_stats(struct cpufreq_stats *any)
{
struct cpufreq_stats *tmp, *next;
if (!any)
return;
tmp = any->first;
while (tmp) {
next = tmp->next;
free(tmp);
tmp = next;
}
}
unsigned long cpufreq_get_transitions(unsigned int cpu)
{
return sysfs_get_freq_transitions(cpu);
}
| gpl-2.0 |
AICP/android_kernel_asus_tf201 | drivers/rtc/rtc-starfire.c | 10247 | 1745 | /* rtc-starfire.c: Starfire platform RTC driver.
*
* Copyright (C) 2008 David S. Miller <davem@davemloft.net>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/rtc.h>
#include <linux/platform_device.h>
#include <asm/oplib.h>
MODULE_AUTHOR("David S. Miller <davem@davemloft.net>");
MODULE_DESCRIPTION("Starfire RTC driver");
MODULE_LICENSE("GPL");
static u32 starfire_get_time(void)
{
static char obp_gettod[32];
static u32 unix_tod;
sprintf(obp_gettod, "h# %08x unix-gettod",
(unsigned int) (long) &unix_tod);
prom_feval(obp_gettod);
return unix_tod;
}
static int starfire_read_time(struct device *dev, struct rtc_time *tm)
{
rtc_time_to_tm(starfire_get_time(), tm);
return rtc_valid_tm(tm);
}
static const struct rtc_class_ops starfire_rtc_ops = {
.read_time = starfire_read_time,
};
static int __init starfire_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtc = rtc_device_register("starfire", &pdev->dev,
&starfire_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
platform_set_drvdata(pdev, rtc);
return 0;
}
static int __exit starfire_rtc_remove(struct platform_device *pdev)
{
struct rtc_device *rtc = platform_get_drvdata(pdev);
rtc_device_unregister(rtc);
return 0;
}
static struct platform_driver starfire_rtc_driver = {
.driver = {
.name = "rtc-starfire",
.owner = THIS_MODULE,
},
.remove = __exit_p(starfire_rtc_remove),
};
static int __init starfire_rtc_init(void)
{
return platform_driver_probe(&starfire_rtc_driver, starfire_rtc_probe);
}
static void __exit starfire_rtc_exit(void)
{
platform_driver_unregister(&starfire_rtc_driver);
}
module_init(starfire_rtc_init);
module_exit(starfire_rtc_exit);
| gpl-2.0 |
thanhphat11/Kernel-Stock-A900-SLK | drivers/input/misc/gpio_switch.c | 8 | 11146 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* 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.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/gpio_event.h>
#include <linux/switch.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/hrtimer.h>
#include <asm/mach-types.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <mach/gpio.h>
#include <linux/gpio_switch.h>
#include "linux/spi/fpc1080.h"
#define DBG_ENABLE
#ifdef DBG_ENABLE
#define dbg(fmt, args...) pr_debug("[gpio_switch] " fmt, ##args)
#else
#define dbg(fmt, args...)
#endif
#define dbg_func_in() dbg("[+] %s\n", __func__)
#define dbg_func_out() dbg("[-] %s\n", __func__)
#define dbg_line() dbg("[LINE] %d(%s)\n", __LINE__, __func__)
struct gpio_switch_data *head = NULL;
struct gpio_switch_data *tail = NULL;
void register_notify_func(int mode , const char* name , void (*noti_func)(const int)){
struct gpio_switch_data *p = head;
while(p){
if(strcmp(name , p->name)==0){
if(mode == EMERGENCY_MODE){
p->emergency_notify = noti_func;
pr_info("%s added emergency_notify func with mode : %d\n" , name , mode);
}
else if(mode == NORMAL_MODE){
p->notify = noti_func;
pr_info("%s added normal_notify func with mode : %d\n" , name , mode);
}
break;
}
p = p->next;
}
}
EXPORT_SYMBOL(register_notify_func);
static void gpio_switch_work(struct work_struct *work){
struct gpio_switch_data *p = container_of(work, struct gpio_switch_data, work);
if(p->current_state == p->last_state){
dbg("current_state is last_state, so framework does not need it\n");
}
else{
if(p->event_mode == PAN_INPUTEVENT){
input_report_switch(p->input_dev , SW_LID , p->current_state);
input_sync(p->input_dev);
}
else if(p->event_mode == PAN_UEVENT){
switch_set_state(&p->sdev , p->current_state);
wake_lock_timeout(&p->wakelock,msecs_to_jiffies(GPIO_SWITCH_WAKE_LOCK_TIMEOUT));
}
p->last_state = p->current_state;
dbg("data(%d) is sent by %s\n" , p->current_state , p->name);
if(p->notify){
p->notify(p->current_state);
dbg("%s->notify call! sent data(%d)\n" , p->name , p->current_state);
}
else{
dbg("%s->notify did not register!\n" , p->name);
}
}
}
static irqreturn_t gpio_switch_irq_handler(int irq, void *dev){
struct gpio_switch_data *p = head;
while(p){
if(p->irq == irq) break;
p = p->next;
}
if(p->emergency_notify){
p->current_state = gpio_get_value(p->gpio) ^ p->flag;
p->emergency_notify(p->current_state);
dbg("%s->emergency_notify call! sent data(%d)\n" , p->name , p->current_state);
}
else
dbg("%s->emergency_notify did not register!\n" , p->name);
if(p->debounce & DEBOUNCE_WAIT_IRQ){
if(p->debounce_count++ == 0){
p->debounce = DEBOUNCE_UNSTABLE;
dbg("hrtimer in ISR\n");
hrtimer_start(&p->timer , p->debounce_time , HRTIMER_MODE_REL);
}
}
return IRQ_HANDLED;
}
static enum hrtimer_restart gpio_switch_timer_func(struct hrtimer *timer){
struct gpio_switch_data *p = container_of(timer , struct gpio_switch_data, timer);
bool pressed;
if(p->debounce & DEBOUNCE_UNSTABLE){
dbg("STATE DEBOUNCE_UNSTABLE\n");
p->debounce = DEBOUNCE_UNKNOWN;
}
p->current_state = gpio_get_value(p->gpio) ^ p->flag;
pressed = (p->current_state == 1) ? false : true;
if(pressed && (p->debounce & DEBOUNCE_NOTPRESSED)){
dbg("STATE DEBOUNCE_PRESSED\n");
p->debounce = DEBOUNCE_PRESSED;
goto check_again;
}
if(!pressed && (p->debounce & DEBOUNCE_PRESSED)){
dbg("STATE DEBOUNCE_NOTPRESSED\n");
p->debounce = DEBOUNCE_NOTPRESSED;
goto check_again;
}
p->debounce_count--;
p->debounce |= DEBOUNCE_WAIT_IRQ;
schedule_work(&p->work);
check_again:
if(p->debounce_count){
hrtimer_start(&p->timer , p->debounce_time , HRTIMER_MODE_REL);
}
return HRTIMER_NORESTART;
}
static ssize_t gpio_switch_print_state(struct switch_dev *sdev, char *buf){
struct gpio_switch_data *p = container_of(sdev , struct gpio_switch_data , sdev);
const char *state;
const char *high_state;
const char *low_state;
if(strcmp(p->name , "touch_pen_detection") == 0){
high_state = (p->flag == 0) ? "ON" : "OFF";
low_state = (p->flag == 0) ? "OFF" : "ON";
}
else{
high_state = (p->flag == 0) ? "OFF" : "ON";
low_state = (p->flag == 0) ? "ON" : "OFF";
}
if (switch_get_state(sdev))
state = high_state;
else
state = low_state;
if (state)
return sprintf(buf, "%s\n", state);
return -1;
}
static int init_gpios(void){
int ret;
struct gpio_switch_data *p = head;
while(p){
ret = gpio_tlmm_config(GPIO_CFG(p->gpio, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
if (ret){
pr_err("Could not configure gpio %d\n", p->gpio);
return -EINVAL;
}
gpio_request(p->gpio , p->name);
if(p->event_mode == PAN_INPUTEVENT){
p->input_dev = input_allocate_device();
if(p->input_dev == NULL){
pr_err("switch_gpio failed to allocate input device\n");
return -ENOMEM;
}
p->input_dev->name = p->name;
set_bit(EV_SW, p->input_dev->evbit);
set_bit(SW_LID, p->input_dev->swbit);
ret = input_register_device(p->input_dev);
if(ret){
pr_err("switch_gpio unable to register %s input device\n", p->input_dev->name);
return -EINVAL;
}
}
else if(p->event_mode == PAN_UEVENT){
p->sdev.print_state = gpio_switch_print_state;
p->sdev.name = p->name;
ret = switch_dev_register(&p->sdev);
if(ret < 0){
pr_err("%s Switch dev register is failed\n" , p->sdev.name);
return -EINVAL;
}
}
else{
pr_err("event_mode : %d does not exist\n" , p->event_mode);
return -EINVAL;
}
p->current_state = gpio_get_value(p->gpio) ^ p->flag;
if(p->event_mode == PAN_INPUTEVENT){
dbg("INPUTEVENT %s sent event : %d\n" , p->name , p->current_state);
input_report_switch(p->input_dev , SW_LID , p->current_state);
input_sync(p->input_dev);
}
else if(p->event_mode == PAN_UEVENT){
dbg("UEVENT %s sent event : %d\n" , p->name , p->current_state);
switch_set_state(&p->sdev , p->current_state);
}
p->last_state = p->current_state;
ret = request_threaded_irq(p->irq , NULL , gpio_switch_irq_handler , IRQF_TRIGGER_FALLING|IRQF_TRIGGER_RISING , p->name , p);
if(ret){
pr_err("%s request_irq is failed reason : %d\n" , p->name , ret);
return -EINVAL;
}
hrtimer_init(&p->timer , CLOCK_MONOTONIC , HRTIMER_MODE_REL);
p->timer.function = gpio_switch_timer_func;
p->debounce = DEBOUNCE_UNKNOWN | DEBOUNCE_WAIT_IRQ;
p->debounce_count = 0;
p->notify = NULL;
p->emergency_notify = NULL;
INIT_WORK(&p->work , gpio_switch_work);
wake_lock_init(&p->wakelock, WAKE_LOCK_SUSPEND, p->name);
enable_irq_wake(p->irq);
p = p->next;
}
return 0;
}
static int __devinit gpio_switch_probe(struct platform_device *pdev){
struct device *dev = &pdev->dev;
struct device_node *node , *pp = NULL;
struct gpio_switch_data *sdata;
u32 reg;
int ret;
dbg("switch_gpio probe!\n");
node = dev->of_node;
if(node == NULL){
pr_err("node is null\n");
return -ENODEV;
}
while( (pp=of_get_next_child(node,pp))){
sdata = kzalloc(sizeof(struct gpio_switch_data) , GFP_KERNEL);
if(!sdata){
pr_err("sdata memory alloc is failed\n");
return -ENOMEM;
}
if(!of_find_property(pp , "gpios" , NULL)){
continue;
}
sdata->name = of_get_property(pp,"label",NULL);
ret = of_property_read_u32(pp , "event_mode" , ®);
if(ret < 0 )
return -EINVAL;
sdata->event_mode = reg;
ret = of_property_read_u32(pp , "flag" , ®);
if(ret < 0 )
return -EINVAL;
sdata->flag = reg;
ret = of_property_read_u32(pp , "gpios" , ®);
if(ret < 0 )
return -EINVAL;
sdata->gpio = reg;
sdata->irq = gpio_to_irq(reg);
ret = of_property_read_u32(pp , "debounce_time" , ®);
if(ret < 0)
return -EINVAL;
sdata->debounce_time = ktime_set(0, reg * 1000000);
pr_info("label : %s , gpios : %d , irq : %d , event_mode : %d , flag = %d\n" , sdata->name , sdata->gpio , sdata->irq , sdata->event_mode , sdata->flag);
sdata->next = NULL;
if(head == NULL){
head = sdata;
tail = sdata;
}else{
tail->next = sdata;
tail = sdata;
}
}
ret = init_gpios();
if(ret < 0){
pr_err("init gpios is failed with error : %d\n" , ret);
return ret;
}
dbg("switch_gpio probe end!\n");
return 0;
}
static struct of_device_id gpio_switch_of_match[] = {
{ .compatible = GPIO_SWITCH_NAME ,},
{ },
};
static struct platform_driver gpio_switch_driver = {
.probe = gpio_switch_probe,
.driver = {
.name = GPIO_SWITCH_NAME,
.owner = THIS_MODULE,
.of_match_table = gpio_switch_of_match,
},
};
static int __init gpio_switch_init(void){
pr_info("gpio_switch_init\n");
return platform_driver_register(&gpio_switch_driver);
}
static void __exit gpio_switch_exit(void){
struct gpio_switch_data *p = head;
pr_info("gpio_switch_exit\n");
platform_driver_unregister(&gpio_switch_driver);
while(p){
switch_dev_unregister(&p->sdev);
hrtimer_cancel(&p->timer);
cancel_work_sync(&p->work);
wake_lock_destroy(&p->wakelock);
p = p->next;
}
}
rootfs_initcall(gpio_switch_init);
module_exit(gpio_switch_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("HALL IC drivers");
| gpl-2.0 |
mcfi/MCFI | compiler/llvm-3.5.0.src/tools/clang/test/Sema/nonnull.c | 8 | 2625 | // RUN: %clang_cc1 -fsyntax-only -verify %s
// rdar://9584012
typedef struct {
char *str;
} Class;
typedef union {
Class *object;
} Instance __attribute__((transparent_union));
__attribute__((nonnull(1))) void Class_init(Instance this, char *str) {
this.object->str = str;
}
int main(void) {
Class *obj;
Class_init(0, "Hello World"); // expected-warning {{null passed to a callee which requires a non-null argument}}
Class_init(obj, "Hello World");
}
void foo(const char *str) __attribute__((nonnull("foo"))); // expected-error{{'nonnull' attribute requires parameter 1 to be an integer constant}}
void bar(int i) __attribute__((nonnull(1))); // expected-warning {{'nonnull' attribute only applies to pointer arguments}} expected-warning {{'nonnull' attribute applied to function with no pointer arguments}}
void baz(__attribute__((nonnull)) const char *str);
void baz2(__attribute__((nonnull(1))) const char *str); // expected-warning {{'nonnull' attribute when used on parameters takes no arguments}}
void baz3(__attribute__((nonnull)) int x); // expected-warning {{'nonnull' attribute only applies to pointer arguments}}
void test_baz() {
baz(0); // expected-warning {{null passed to a callee which requires a non-null argument}}
baz2(0); // no-warning
baz3(0); // no-warning
}
void test_void_returns_nonnull(void) __attribute__((returns_nonnull)); // expected-warning {{'returns_nonnull' attribute only applies to return values that are pointers}}
int test_int_returns_nonnull(void) __attribute__((returns_nonnull)); // expected-warning {{'returns_nonnull' attribute only applies to return values that are pointers}}
void *test_ptr_returns_nonnull(void) __attribute__((returns_nonnull)); // no-warning
int i __attribute__((nonnull)); // expected-warning {{'nonnull' attribute only applies to functions, methods, and parameters}}
int j __attribute__((returns_nonnull)); // expected-warning {{'returns_nonnull' attribute only applies to functions and methods}}
void *test_no_fn_proto() __attribute__((returns_nonnull)); // no-warning
void *test_with_fn_proto(void) __attribute__((returns_nonnull)); // no-warning
__attribute__((returns_nonnull))
void *test_bad_returns_null(void) {
return 0; // expected-warning {{null returned from function that requires a non-null return value}}
}
void PR18795(int (*g)(const char *h, ...) __attribute__((nonnull(1))) __attribute__((nonnull))) {
g(0); // expected-warning{{null passed to a callee which requires a non-null argument}}
}
void PR18795_helper() {
PR18795(0); // expected-warning{{null passed to a callee which requires a non-null argument}}
}
| gpl-2.0 |
toastcfh/android_kernel_lge_d851 | arch/arm/mach-ixp23xx/espresso.c | 8 | 2109 | /*
* arch/arm/mach-ixp23xx/espresso.c
*
* Double Espresso-specific routines
*
* Author: Lennert Buytenhek <buytenh@wantstofly.org>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/serial.h>
#include <linux/tty.h>
#include <linux/bitops.h>
#include <linux/ioport.h>
#include <linux/serial_8250.h>
#include <linux/serial_core.h>
#include <linux/device.h>
#include <linux/mm.h>
#include <linux/pci.h>
#include <linux/mtd/physmap.h>
#include <asm/types.h>
#include <asm/setup.h>
#include <asm/memory.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/tlbflush.h>
#include <asm/pgtable.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/pci.h>
static int __init espresso_pci_init(void)
{
if (machine_is_espresso())
ixp23xx_pci_slave_init();
return 0;
};
subsys_initcall(espresso_pci_init);
static struct physmap_flash_data espresso_flash_data = {
.width = 2,
};
static struct resource espresso_flash_resource = {
.start = 0x90000000,
.end = 0x91ffffff,
.flags = IORESOURCE_MEM,
};
static struct platform_device espresso_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &espresso_flash_data,
},
.num_resources = 1,
.resource = &espresso_flash_resource,
};
static void __init espresso_init(void)
{
platform_device_register(&espresso_flash);
/*
*/
IXP23XX_EXP_CS0[0] |= IXP23XX_FLASH_WRITABLE;
IXP23XX_EXP_CS0[1] |= IXP23XX_FLASH_WRITABLE;
ixp23xx_sys_init();
}
MACHINE_START(ESPRESSO, "IP Fabrics Double Espresso")
/* */
.map_io = ixp23xx_map_io,
.init_irq = ixp23xx_init_irq,
.timer = &ixp23xx_timer,
.atag_offset = 0x100,
.init_machine = espresso_init,
.restart = ixp23xx_restart,
MACHINE_END
| gpl-2.0 |
gamerlulea/linux-2.6-5 | arch/mips/kernel/perf_event_mipsxx.c | 8 | 28109 | #if defined(CONFIG_CPU_MIPS32) || defined(CONFIG_CPU_MIPS64) || \
defined(CONFIG_CPU_R10000) || defined(CONFIG_CPU_SB1)
#define M_CONFIG1_PC (1 << 4)
#define M_PERFCTL_EXL (1UL << 0)
#define M_PERFCTL_KERNEL (1UL << 1)
#define M_PERFCTL_SUPERVISOR (1UL << 2)
#define M_PERFCTL_USER (1UL << 3)
#define M_PERFCTL_INTERRUPT_ENABLE (1UL << 4)
#define M_PERFCTL_EVENT(event) (((event) & 0x3ff) << 5)
#define M_PERFCTL_VPEID(vpe) ((vpe) << 16)
#define M_PERFCTL_MT_EN(filter) ((filter) << 20)
#define M_TC_EN_ALL M_PERFCTL_MT_EN(0)
#define M_TC_EN_VPE M_PERFCTL_MT_EN(1)
#define M_TC_EN_TC M_PERFCTL_MT_EN(2)
#define M_PERFCTL_TCID(tcid) ((tcid) << 22)
#define M_PERFCTL_WIDE (1UL << 30)
#define M_PERFCTL_MORE (1UL << 31)
#define M_PERFCTL_COUNT_EVENT_WHENEVER (M_PERFCTL_EXL | \
M_PERFCTL_KERNEL | \
M_PERFCTL_USER | \
M_PERFCTL_SUPERVISOR | \
M_PERFCTL_INTERRUPT_ENABLE)
#ifdef CONFIG_MIPS_MT_SMP
#define M_PERFCTL_CONFIG_MASK 0x3fff801f
#else
#define M_PERFCTL_CONFIG_MASK 0x1f
#endif
#define M_PERFCTL_EVENT_MASK 0xfe0
#define M_COUNTER_OVERFLOW (1UL << 31)
#ifdef CONFIG_MIPS_MT_SMP
static int cpu_has_mipsmt_pertccounters;
/*
* FIXME: For VSMP, vpe_id() is redefined for Perf-events, because
* cpu_data[cpuid].vpe_id reports 0 for _both_ CPUs.
*/
#if defined(CONFIG_HW_PERF_EVENTS)
#define vpe_id() (cpu_has_mipsmt_pertccounters ? \
0 : smp_processor_id())
#else
#define vpe_id() (cpu_has_mipsmt_pertccounters ? \
0 : cpu_data[smp_processor_id()].vpe_id)
#endif
/* Copied from op_model_mipsxx.c */
static inline unsigned int vpe_shift(void)
{
if (num_possible_cpus() > 1)
return 1;
return 0;
}
#else /* !CONFIG_MIPS_MT_SMP */
#define vpe_id() 0
static inline unsigned int vpe_shift(void)
{
return 0;
}
#endif /* CONFIG_MIPS_MT_SMP */
static inline unsigned int
counters_total_to_per_cpu(unsigned int counters)
{
return counters >> vpe_shift();
}
static inline unsigned int
counters_per_cpu_to_total(unsigned int counters)
{
return counters << vpe_shift();
}
#define __define_perf_accessors(r, n, np) \
\
static inline unsigned int r_c0_ ## r ## n(void) \
{ \
unsigned int cpu = vpe_id(); \
\
switch (cpu) { \
case 0: \
return read_c0_ ## r ## n(); \
case 1: \
return read_c0_ ## r ## np(); \
default: \
BUG(); \
} \
return 0; \
} \
\
static inline void w_c0_ ## r ## n(unsigned int value) \
{ \
unsigned int cpu = vpe_id(); \
\
switch (cpu) { \
case 0: \
write_c0_ ## r ## n(value); \
return; \
case 1: \
write_c0_ ## r ## np(value); \
return; \
default: \
BUG(); \
} \
return; \
} \
__define_perf_accessors(perfcntr, 0, 2)
__define_perf_accessors(perfcntr, 1, 3)
__define_perf_accessors(perfcntr, 2, 0)
__define_perf_accessors(perfcntr, 3, 1)
__define_perf_accessors(perfctrl, 0, 2)
__define_perf_accessors(perfctrl, 1, 3)
__define_perf_accessors(perfctrl, 2, 0)
__define_perf_accessors(perfctrl, 3, 1)
static inline int __n_counters(void)
{
if (!(read_c0_config1() & M_CONFIG1_PC))
return 0;
if (!(read_c0_perfctrl0() & M_PERFCTL_MORE))
return 1;
if (!(read_c0_perfctrl1() & M_PERFCTL_MORE))
return 2;
if (!(read_c0_perfctrl2() & M_PERFCTL_MORE))
return 3;
return 4;
}
static inline int n_counters(void)
{
int counters;
switch (current_cpu_type()) {
case CPU_R10000:
counters = 2;
break;
case CPU_R12000:
case CPU_R14000:
counters = 4;
break;
default:
counters = __n_counters();
}
return counters;
}
static void reset_counters(void *arg)
{
int counters = (int)(long)arg;
switch (counters) {
case 4:
w_c0_perfctrl3(0);
w_c0_perfcntr3(0);
case 3:
w_c0_perfctrl2(0);
w_c0_perfcntr2(0);
case 2:
w_c0_perfctrl1(0);
w_c0_perfcntr1(0);
case 1:
w_c0_perfctrl0(0);
w_c0_perfcntr0(0);
}
}
static inline u64
mipsxx_pmu_read_counter(unsigned int idx)
{
switch (idx) {
case 0:
return r_c0_perfcntr0();
case 1:
return r_c0_perfcntr1();
case 2:
return r_c0_perfcntr2();
case 3:
return r_c0_perfcntr3();
default:
WARN_ONCE(1, "Invalid performance counter number (%d)\n", idx);
return 0;
}
}
static inline void
mipsxx_pmu_write_counter(unsigned int idx, u64 val)
{
switch (idx) {
case 0:
w_c0_perfcntr0(val);
return;
case 1:
w_c0_perfcntr1(val);
return;
case 2:
w_c0_perfcntr2(val);
return;
case 3:
w_c0_perfcntr3(val);
return;
}
}
static inline unsigned int
mipsxx_pmu_read_control(unsigned int idx)
{
switch (idx) {
case 0:
return r_c0_perfctrl0();
case 1:
return r_c0_perfctrl1();
case 2:
return r_c0_perfctrl2();
case 3:
return r_c0_perfctrl3();
default:
WARN_ONCE(1, "Invalid performance counter number (%d)\n", idx);
return 0;
}
}
static inline void
mipsxx_pmu_write_control(unsigned int idx, unsigned int val)
{
switch (idx) {
case 0:
w_c0_perfctrl0(val);
return;
case 1:
w_c0_perfctrl1(val);
return;
case 2:
w_c0_perfctrl2(val);
return;
case 3:
w_c0_perfctrl3(val);
return;
}
}
#ifdef CONFIG_MIPS_MT_SMP
static DEFINE_RWLOCK(pmuint_rwlock);
#endif
/* 24K/34K/1004K cores can share the same event map. */
static const struct mips_perf_event mipsxxcore_event_map
[PERF_COUNT_HW_MAX] = {
[PERF_COUNT_HW_CPU_CYCLES] = { 0x00, CNTR_EVEN | CNTR_ODD, P },
[PERF_COUNT_HW_INSTRUCTIONS] = { 0x01, CNTR_EVEN | CNTR_ODD, T },
[PERF_COUNT_HW_CACHE_REFERENCES] = { UNSUPPORTED_PERF_EVENT_ID },
[PERF_COUNT_HW_CACHE_MISSES] = { UNSUPPORTED_PERF_EVENT_ID },
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = { 0x02, CNTR_EVEN, T },
[PERF_COUNT_HW_BRANCH_MISSES] = { 0x02, CNTR_ODD, T },
[PERF_COUNT_HW_BUS_CYCLES] = { UNSUPPORTED_PERF_EVENT_ID },
};
/* 74K core has different branch event code. */
static const struct mips_perf_event mipsxx74Kcore_event_map
[PERF_COUNT_HW_MAX] = {
[PERF_COUNT_HW_CPU_CYCLES] = { 0x00, CNTR_EVEN | CNTR_ODD, P },
[PERF_COUNT_HW_INSTRUCTIONS] = { 0x01, CNTR_EVEN | CNTR_ODD, T },
[PERF_COUNT_HW_CACHE_REFERENCES] = { UNSUPPORTED_PERF_EVENT_ID },
[PERF_COUNT_HW_CACHE_MISSES] = { UNSUPPORTED_PERF_EVENT_ID },
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = { 0x27, CNTR_EVEN, T },
[PERF_COUNT_HW_BRANCH_MISSES] = { 0x27, CNTR_ODD, T },
[PERF_COUNT_HW_BUS_CYCLES] = { UNSUPPORTED_PERF_EVENT_ID },
};
/* 24K/34K/1004K cores can share the same cache event map. */
static const struct mips_perf_event mipsxxcore_cache_map
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] = {
[C(L1D)] = {
/*
* Like some other architectures (e.g. ARM), the performance
* counters don't differentiate between read and write
* accesses/misses, so this isn't strictly correct, but it's the
* best we can do. Writes and reads get combined.
*/
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x0a, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x0b, CNTR_EVEN | CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0a, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x0b, CNTR_EVEN | CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x09, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x09, CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x09, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x09, CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { 0x14, CNTR_EVEN, T },
/*
* Note that MIPS has only "hit" events countable for
* the prefetch operation.
*/
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x15, CNTR_ODD, P },
[C(RESULT_MISS)] = { 0x16, CNTR_EVEN, P },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x15, CNTR_ODD, P },
[C(RESULT_MISS)] = { 0x16, CNTR_EVEN, P },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x06, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x06, CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x06, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x06, CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x05, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x05, CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x05, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x05, CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(BPU)] = {
/* Using the same code for *HW_BRANCH* */
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x02, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x02, CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x02, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x02, CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
};
/* 74K core has completely different cache event map. */
static const struct mips_perf_event mipsxx74Kcore_cache_map
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] = {
[C(L1D)] = {
/*
* Like some other architectures (e.g. ARM), the performance
* counters don't differentiate between read and write
* accesses/misses, so this isn't strictly correct, but it's the
* best we can do. Writes and reads get combined.
*/
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x17, CNTR_ODD, T },
[C(RESULT_MISS)] = { 0x18, CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x17, CNTR_ODD, T },
[C(RESULT_MISS)] = { 0x18, CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x06, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x06, CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x06, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x06, CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { 0x34, CNTR_EVEN, T },
/*
* Note that MIPS has only "hit" events countable for
* the prefetch operation.
*/
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x1c, CNTR_ODD, P },
[C(RESULT_MISS)] = { 0x1d, CNTR_EVEN | CNTR_ODD, P },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x1c, CNTR_ODD, P },
[C(RESULT_MISS)] = { 0x1d, CNTR_EVEN | CNTR_ODD, P },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(DTLB)] = {
/* 74K core does not have specific DTLB events. */
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x04, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x04, CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x04, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x04, CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
[C(BPU)] = {
/* Using the same code for *HW_BRANCH* */
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x27, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x27, CNTR_ODD, T },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x27, CNTR_EVEN, T },
[C(RESULT_MISS)] = { 0x27, CNTR_ODD, T },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { UNSUPPORTED_PERF_EVENT_ID },
[C(RESULT_MISS)] = { UNSUPPORTED_PERF_EVENT_ID },
},
},
};
#ifdef CONFIG_MIPS_MT_SMP
static void
check_and_calc_range(struct perf_event *event,
const struct mips_perf_event *pev)
{
struct hw_perf_event *hwc = &event->hw;
if (event->cpu >= 0) {
if (pev->range > V) {
/*
* The user selected an event that is processor
* wide, while expecting it to be VPE wide.
*/
hwc->config_base |= M_TC_EN_ALL;
} else {
/*
* FIXME: cpu_data[event->cpu].vpe_id reports 0
* for both CPUs.
*/
hwc->config_base |= M_PERFCTL_VPEID(event->cpu);
hwc->config_base |= M_TC_EN_VPE;
}
} else
hwc->config_base |= M_TC_EN_ALL;
}
#else
static void
check_and_calc_range(struct perf_event *event,
const struct mips_perf_event *pev)
{
}
#endif
static int __hw_perf_event_init(struct perf_event *event)
{
struct perf_event_attr *attr = &event->attr;
struct hw_perf_event *hwc = &event->hw;
const struct mips_perf_event *pev;
int err;
/* Returning MIPS event descriptor for generic perf event. */
if (PERF_TYPE_HARDWARE == event->attr.type) {
if (event->attr.config >= PERF_COUNT_HW_MAX)
return -EINVAL;
pev = mipspmu_map_general_event(event->attr.config);
} else if (PERF_TYPE_HW_CACHE == event->attr.type) {
pev = mipspmu_map_cache_event(event->attr.config);
} else if (PERF_TYPE_RAW == event->attr.type) {
/* We are working on the global raw event. */
mutex_lock(&raw_event_mutex);
pev = mipspmu->map_raw_event(event->attr.config);
} else {
/* The event type is not (yet) supported. */
return -EOPNOTSUPP;
}
if (IS_ERR(pev)) {
if (PERF_TYPE_RAW == event->attr.type)
mutex_unlock(&raw_event_mutex);
return PTR_ERR(pev);
}
/*
* We allow max flexibility on how each individual counter shared
* by the single CPU operates (the mode exclusion and the range).
*/
hwc->config_base = M_PERFCTL_INTERRUPT_ENABLE;
/* Calculate range bits and validate it. */
if (num_possible_cpus() > 1)
check_and_calc_range(event, pev);
hwc->event_base = mipspmu_perf_event_encode(pev);
if (PERF_TYPE_RAW == event->attr.type)
mutex_unlock(&raw_event_mutex);
if (!attr->exclude_user)
hwc->config_base |= M_PERFCTL_USER;
if (!attr->exclude_kernel) {
hwc->config_base |= M_PERFCTL_KERNEL;
/* MIPS kernel mode: KSU == 00b || EXL == 1 || ERL == 1 */
hwc->config_base |= M_PERFCTL_EXL;
}
if (!attr->exclude_hv)
hwc->config_base |= M_PERFCTL_SUPERVISOR;
hwc->config_base &= M_PERFCTL_CONFIG_MASK;
/*
* The event can belong to another cpu. We do not assign a local
* counter for it for now.
*/
hwc->idx = -1;
hwc->config = 0;
if (!hwc->sample_period) {
hwc->sample_period = MAX_PERIOD;
hwc->last_period = hwc->sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
}
err = 0;
if (event->group_leader != event) {
err = validate_group(event);
if (err)
return -EINVAL;
}
event->destroy = hw_perf_event_destroy;
return err;
}
static void pause_local_counters(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int counters = mipspmu->num_counters;
unsigned long flags;
local_irq_save(flags);
switch (counters) {
case 4:
cpuc->saved_ctrl[3] = r_c0_perfctrl3();
w_c0_perfctrl3(cpuc->saved_ctrl[3] &
~M_PERFCTL_COUNT_EVENT_WHENEVER);
case 3:
cpuc->saved_ctrl[2] = r_c0_perfctrl2();
w_c0_perfctrl2(cpuc->saved_ctrl[2] &
~M_PERFCTL_COUNT_EVENT_WHENEVER);
case 2:
cpuc->saved_ctrl[1] = r_c0_perfctrl1();
w_c0_perfctrl1(cpuc->saved_ctrl[1] &
~M_PERFCTL_COUNT_EVENT_WHENEVER);
case 1:
cpuc->saved_ctrl[0] = r_c0_perfctrl0();
w_c0_perfctrl0(cpuc->saved_ctrl[0] &
~M_PERFCTL_COUNT_EVENT_WHENEVER);
}
local_irq_restore(flags);
}
static void resume_local_counters(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int counters = mipspmu->num_counters;
unsigned long flags;
local_irq_save(flags);
switch (counters) {
case 4:
w_c0_perfctrl3(cpuc->saved_ctrl[3]);
case 3:
w_c0_perfctrl2(cpuc->saved_ctrl[2]);
case 2:
w_c0_perfctrl1(cpuc->saved_ctrl[1]);
case 1:
w_c0_perfctrl0(cpuc->saved_ctrl[0]);
}
local_irq_restore(flags);
}
static int mipsxx_pmu_handle_shared_irq(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct perf_sample_data data;
unsigned int counters = mipspmu->num_counters;
unsigned int counter;
int handled = IRQ_NONE;
struct pt_regs *regs;
if (cpu_has_mips_r2 && !(read_c0_cause() & (1 << 26)))
return handled;
/*
* First we pause the local counters, so that when we are locked
* here, the counters are all paused. When it gets locked due to
* perf_disable(), the timer interrupt handler will be delayed.
*
* See also mipsxx_pmu_start().
*/
pause_local_counters();
#ifdef CONFIG_MIPS_MT_SMP
read_lock(&pmuint_rwlock);
#endif
regs = get_irq_regs();
perf_sample_data_init(&data, 0);
switch (counters) {
#define HANDLE_COUNTER(n) \
case n + 1: \
if (test_bit(n, cpuc->used_mask)) { \
counter = r_c0_perfcntr ## n(); \
if (counter & M_COUNTER_OVERFLOW) { \
w_c0_perfcntr ## n(counter & \
VALID_COUNT); \
if (test_and_change_bit(n, cpuc->msbs)) \
handle_associated_event(cpuc, \
n, &data, regs); \
handled = IRQ_HANDLED; \
} \
}
HANDLE_COUNTER(3)
HANDLE_COUNTER(2)
HANDLE_COUNTER(1)
HANDLE_COUNTER(0)
}
/*
* Do all the work for the pending perf events. We can do this
* in here because the performance counter interrupt is a regular
* interrupt, not NMI.
*/
if (handled == IRQ_HANDLED)
perf_event_do_pending();
#ifdef CONFIG_MIPS_MT_SMP
read_unlock(&pmuint_rwlock);
#endif
resume_local_counters();
return handled;
}
static irqreturn_t
mipsxx_pmu_handle_irq(int irq, void *dev)
{
return mipsxx_pmu_handle_shared_irq();
}
static void mipsxx_pmu_start(void)
{
#ifdef CONFIG_MIPS_MT_SMP
write_unlock(&pmuint_rwlock);
#endif
resume_local_counters();
}
/*
* MIPS performance counters can be per-TC. The control registers can
* not be directly accessed accross CPUs. Hence if we want to do global
* control, we need cross CPU calls. on_each_cpu() can help us, but we
* can not make sure this function is called with interrupts enabled. So
* here we pause local counters and then grab a rwlock and leave the
* counters on other CPUs alone. If any counter interrupt raises while
* we own the write lock, simply pause local counters on that CPU and
* spin in the handler. Also we know we won't be switched to another
* CPU after pausing local counters and before grabbing the lock.
*/
static void mipsxx_pmu_stop(void)
{
pause_local_counters();
#ifdef CONFIG_MIPS_MT_SMP
write_lock(&pmuint_rwlock);
#endif
}
static int
mipsxx_pmu_alloc_counter(struct cpu_hw_events *cpuc,
struct hw_perf_event *hwc)
{
int i;
/*
* We only need to care the counter mask. The range has been
* checked definitely.
*/
unsigned long cntr_mask = (hwc->event_base >> 8) & 0xffff;
for (i = mipspmu->num_counters - 1; i >= 0; i--) {
/*
* Note that some MIPS perf events can be counted by both
* even and odd counters, wheresas many other are only by
* even _or_ odd counters. This introduces an issue that
* when the former kind of event takes the counter the
* latter kind of event wants to use, then the "counter
* allocation" for the latter event will fail. In fact if
* they can be dynamically swapped, they both feel happy.
* But here we leave this issue alone for now.
*/
if (test_bit(i, &cntr_mask) &&
!test_and_set_bit(i, cpuc->used_mask))
return i;
}
return -EAGAIN;
}
static void
mipsxx_pmu_enable_event(struct hw_perf_event *evt, int idx)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
unsigned long flags;
WARN_ON(idx < 0 || idx >= mipspmu->num_counters);
local_irq_save(flags);
cpuc->saved_ctrl[idx] = M_PERFCTL_EVENT(evt->event_base & 0xff) |
(evt->config_base & M_PERFCTL_CONFIG_MASK) |
/* Make sure interrupt enabled. */
M_PERFCTL_INTERRUPT_ENABLE;
/*
* We do not actually let the counter run. Leave it until start().
*/
local_irq_restore(flags);
}
static void
mipsxx_pmu_disable_event(int idx)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
unsigned long flags;
WARN_ON(idx < 0 || idx >= mipspmu->num_counters);
local_irq_save(flags);
cpuc->saved_ctrl[idx] = mipsxx_pmu_read_control(idx) &
~M_PERFCTL_COUNT_EVENT_WHENEVER;
mipsxx_pmu_write_control(idx, cpuc->saved_ctrl[idx]);
local_irq_restore(flags);
}
/* 24K */
#define IS_UNSUPPORTED_24K_EVENT(r, b) \
((b) == 12 || (r) == 151 || (r) == 152 || (b) == 26 || \
(b) == 27 || (r) == 28 || (r) == 158 || (b) == 31 || \
(b) == 32 || (b) == 34 || (b) == 36 || (r) == 168 || \
(r) == 172 || (b) == 47 || ((b) >= 56 && (b) <= 63) || \
((b) >= 68 && (b) <= 127))
#define IS_BOTH_COUNTERS_24K_EVENT(b) \
((b) == 0 || (b) == 1 || (b) == 11)
/* 34K */
#define IS_UNSUPPORTED_34K_EVENT(r, b) \
((b) == 12 || (r) == 27 || (r) == 158 || (b) == 36 || \
(b) == 38 || (r) == 175 || ((b) >= 56 && (b) <= 63) || \
((b) >= 68 && (b) <= 127))
#define IS_BOTH_COUNTERS_34K_EVENT(b) \
((b) == 0 || (b) == 1 || (b) == 11)
#ifdef CONFIG_MIPS_MT_SMP
#define IS_RANGE_P_34K_EVENT(r, b) \
((b) == 0 || (r) == 18 || (b) == 21 || (b) == 22 || \
(b) == 25 || (b) == 39 || (r) == 44 || (r) == 174 || \
(r) == 176 || ((b) >= 50 && (b) <= 55) || \
((b) >= 64 && (b) <= 67))
#define IS_RANGE_V_34K_EVENT(r) ((r) == 47)
#endif
/* 74K */
#define IS_UNSUPPORTED_74K_EVENT(r, b) \
((r) == 5 || ((r) >= 135 && (r) <= 137) || \
((b) >= 10 && (b) <= 12) || (b) == 22 || (b) == 27 || \
(b) == 33 || (b) == 34 || ((b) >= 47 && (b) <= 49) || \
(r) == 178 || (b) == 55 || (b) == 57 || (b) == 60 || \
(b) == 61 || (r) == 62 || (r) == 191 || \
((b) >= 64 && (b) <= 127))
#define IS_BOTH_COUNTERS_74K_EVENT(b) \
((b) == 0 || (b) == 1)
/* 1004K */
#define IS_UNSUPPORTED_1004K_EVENT(r, b) \
((b) == 12 || (r) == 27 || (r) == 158 || (b) == 38 || \
(r) == 175 || (b) == 63 || ((b) >= 68 && (b) <= 127))
#define IS_BOTH_COUNTERS_1004K_EVENT(b) \
((b) == 0 || (b) == 1 || (b) == 11)
#ifdef CONFIG_MIPS_MT_SMP
#define IS_RANGE_P_1004K_EVENT(r, b) \
((b) == 0 || (r) == 18 || (b) == 21 || (b) == 22 || \
(b) == 25 || (b) == 36 || (b) == 39 || (r) == 44 || \
(r) == 174 || (r) == 176 || ((b) >= 50 && (b) <= 59) || \
(r) == 188 || (b) == 61 || (b) == 62 || \
((b) >= 64 && (b) <= 67))
#define IS_RANGE_V_1004K_EVENT(r) ((r) == 47)
#endif
/*
* User can use 0-255 raw events, where 0-127 for the events of even
* counters, and 128-255 for odd counters. Note that bit 7 is used to
* indicate the parity. So, for example, when user wants to take the
* Event Num of 15 for odd counters (by referring to the user manual),
* then 128 needs to be added to 15 as the input for the event config,
* i.e., 143 (0x8F) to be used.
*/
static const struct mips_perf_event *
mipsxx_pmu_map_raw_event(u64 config)
{
unsigned int raw_id = config & 0xff;
unsigned int base_id = raw_id & 0x7f;
switch (current_cpu_type()) {
case CPU_24K:
if (IS_UNSUPPORTED_24K_EVENT(raw_id, base_id))
return ERR_PTR(-EOPNOTSUPP);
raw_event.event_id = base_id;
if (IS_BOTH_COUNTERS_24K_EVENT(base_id))
raw_event.cntr_mask = CNTR_EVEN | CNTR_ODD;
else
raw_event.cntr_mask =
raw_id > 127 ? CNTR_ODD : CNTR_EVEN;
#ifdef CONFIG_MIPS_MT_SMP
/*
* This is actually doing nothing. Non-multithreading
* CPUs will not check and calculate the range.
*/
raw_event.range = P;
#endif
break;
case CPU_34K:
if (IS_UNSUPPORTED_34K_EVENT(raw_id, base_id))
return ERR_PTR(-EOPNOTSUPP);
raw_event.event_id = base_id;
if (IS_BOTH_COUNTERS_34K_EVENT(base_id))
raw_event.cntr_mask = CNTR_EVEN | CNTR_ODD;
else
raw_event.cntr_mask =
raw_id > 127 ? CNTR_ODD : CNTR_EVEN;
#ifdef CONFIG_MIPS_MT_SMP
if (IS_RANGE_P_34K_EVENT(raw_id, base_id))
raw_event.range = P;
else if (unlikely(IS_RANGE_V_34K_EVENT(raw_id)))
raw_event.range = V;
else
raw_event.range = T;
#endif
break;
case CPU_74K:
if (IS_UNSUPPORTED_74K_EVENT(raw_id, base_id))
return ERR_PTR(-EOPNOTSUPP);
raw_event.event_id = base_id;
if (IS_BOTH_COUNTERS_74K_EVENT(base_id))
raw_event.cntr_mask = CNTR_EVEN | CNTR_ODD;
else
raw_event.cntr_mask =
raw_id > 127 ? CNTR_ODD : CNTR_EVEN;
#ifdef CONFIG_MIPS_MT_SMP
raw_event.range = P;
#endif
break;
case CPU_1004K:
if (IS_UNSUPPORTED_1004K_EVENT(raw_id, base_id))
return ERR_PTR(-EOPNOTSUPP);
raw_event.event_id = base_id;
if (IS_BOTH_COUNTERS_1004K_EVENT(base_id))
raw_event.cntr_mask = CNTR_EVEN | CNTR_ODD;
else
raw_event.cntr_mask =
raw_id > 127 ? CNTR_ODD : CNTR_EVEN;
#ifdef CONFIG_MIPS_MT_SMP
if (IS_RANGE_P_1004K_EVENT(raw_id, base_id))
raw_event.range = P;
else if (unlikely(IS_RANGE_V_1004K_EVENT(raw_id)))
raw_event.range = V;
else
raw_event.range = T;
#endif
break;
}
return &raw_event;
}
static struct mips_pmu mipsxxcore_pmu = {
.handle_irq = mipsxx_pmu_handle_irq,
.handle_shared_irq = mipsxx_pmu_handle_shared_irq,
.start = mipsxx_pmu_start,
.stop = mipsxx_pmu_stop,
.alloc_counter = mipsxx_pmu_alloc_counter,
.read_counter = mipsxx_pmu_read_counter,
.write_counter = mipsxx_pmu_write_counter,
.enable_event = mipsxx_pmu_enable_event,
.disable_event = mipsxx_pmu_disable_event,
.map_raw_event = mipsxx_pmu_map_raw_event,
.general_event_map = &mipsxxcore_event_map,
.cache_event_map = &mipsxxcore_cache_map,
};
static struct mips_pmu mipsxx74Kcore_pmu = {
.handle_irq = mipsxx_pmu_handle_irq,
.handle_shared_irq = mipsxx_pmu_handle_shared_irq,
.start = mipsxx_pmu_start,
.stop = mipsxx_pmu_stop,
.alloc_counter = mipsxx_pmu_alloc_counter,
.read_counter = mipsxx_pmu_read_counter,
.write_counter = mipsxx_pmu_write_counter,
.enable_event = mipsxx_pmu_enable_event,
.disable_event = mipsxx_pmu_disable_event,
.map_raw_event = mipsxx_pmu_map_raw_event,
.general_event_map = &mipsxx74Kcore_event_map,
.cache_event_map = &mipsxx74Kcore_cache_map,
};
static int __init
init_hw_perf_events(void)
{
int counters, irq;
pr_info("Performance counters: ");
counters = n_counters();
if (counters == 0) {
pr_cont("No available PMU.\n");
return -ENODEV;
}
#ifdef CONFIG_MIPS_MT_SMP
cpu_has_mipsmt_pertccounters = read_c0_config7() & (1<<19);
if (!cpu_has_mipsmt_pertccounters)
counters = counters_total_to_per_cpu(counters);
#endif
#ifdef MSC01E_INT_BASE
if (cpu_has_veic) {
/*
* Using platform specific interrupt controller defines.
*/
irq = MSC01E_INT_BASE + MSC01E_INT_PERFCTR;
} else {
#endif
if (cp0_perfcount_irq >= 0)
irq = MIPS_CPU_IRQ_BASE + cp0_perfcount_irq;
else
irq = -1;
#ifdef MSC01E_INT_BASE
}
#endif
on_each_cpu(reset_counters, (void *)(long)counters, 1);
switch (current_cpu_type()) {
case CPU_24K:
mipsxxcore_pmu.name = "mips/24K";
mipsxxcore_pmu.num_counters = counters;
mipsxxcore_pmu.irq = irq;
mipspmu = &mipsxxcore_pmu;
break;
case CPU_34K:
mipsxxcore_pmu.name = "mips/34K";
mipsxxcore_pmu.num_counters = counters;
mipsxxcore_pmu.irq = irq;
mipspmu = &mipsxxcore_pmu;
break;
case CPU_74K:
mipsxx74Kcore_pmu.name = "mips/74K";
mipsxx74Kcore_pmu.num_counters = counters;
mipsxx74Kcore_pmu.irq = irq;
mipspmu = &mipsxx74Kcore_pmu;
break;
case CPU_1004K:
mipsxxcore_pmu.name = "mips/1004K";
mipsxxcore_pmu.num_counters = counters;
mipsxxcore_pmu.irq = irq;
mipspmu = &mipsxxcore_pmu;
break;
default:
pr_cont("Either hardware does not support performance "
"counters, or not yet implemented.\n");
return -ENODEV;
}
if (mipspmu)
pr_cont("%s PMU enabled, %d counters available to each "
"CPU, irq %d%s\n", mipspmu->name, counters, irq,
irq < 0 ? " (share with timer interrupt)" : "");
return 0;
}
early_initcall(init_hw_perf_events);
#endif /* defined(CONFIG_CPU_MIPS32)... */
| gpl-2.0 |
Motorhead1991/acer-kernel_project | drivers/infiniband/hw/mlx4/main.c | 8 | 71852 | /*
* Copyright (c) 2006, 2007 Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2007, 2008 Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/inetdevice.h>
#include <linux/rtnetlink.h>
#include <linux/if_vlan.h>
#include <net/ipv6.h>
#include <net/addrconf.h>
#include <rdma/ib_smi.h>
#include <rdma/ib_user_verbs.h>
#include <rdma/ib_addr.h>
#include <linux/mlx4/driver.h>
#include <linux/mlx4/cmd.h>
#include <linux/mlx4/qp.h>
#include "mlx4_ib.h"
#include "user.h"
#define DRV_NAME MLX4_IB_DRV_NAME
#define DRV_VERSION "2.2-1"
#define DRV_RELDATE "Feb 2014"
#define MLX4_IB_FLOW_MAX_PRIO 0xFFF
#define MLX4_IB_FLOW_QPN_MASK 0xFFFFFF
#define MLX4_IB_CARD_REV_A0 0xA0
MODULE_AUTHOR("Roland Dreier");
MODULE_DESCRIPTION("Mellanox ConnectX HCA InfiniBand driver");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_VERSION(DRV_VERSION);
int mlx4_ib_sm_guid_assign = 1;
module_param_named(sm_guid_assign, mlx4_ib_sm_guid_assign, int, 0444);
MODULE_PARM_DESC(sm_guid_assign, "Enable SM alias_GUID assignment if sm_guid_assign > 0 (Default: 1)");
static const char mlx4_ib_version[] =
DRV_NAME ": Mellanox ConnectX InfiniBand driver v"
DRV_VERSION " (" DRV_RELDATE ")\n";
struct update_gid_work {
struct work_struct work;
union ib_gid gids[128];
struct mlx4_ib_dev *dev;
int port;
};
static void do_slave_init(struct mlx4_ib_dev *ibdev, int slave, int do_init);
static struct workqueue_struct *wq;
static void init_query_mad(struct ib_smp *mad)
{
mad->base_version = 1;
mad->mgmt_class = IB_MGMT_CLASS_SUBN_LID_ROUTED;
mad->class_version = 1;
mad->method = IB_MGMT_METHOD_GET;
}
static union ib_gid zgid;
static int check_flow_steering_support(struct mlx4_dev *dev)
{
int eth_num_ports = 0;
int ib_num_ports = 0;
int dmfs = dev->caps.steering_mode == MLX4_STEERING_MODE_DEVICE_MANAGED;
if (dmfs) {
int i;
mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_ETH)
eth_num_ports++;
mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_IB)
ib_num_ports++;
dmfs &= (!ib_num_ports ||
(dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_DMFS_IPOIB)) &&
(!eth_num_ports ||
(dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_FS_EN));
if (ib_num_ports && mlx4_is_mfunc(dev)) {
pr_warn("Device managed flow steering is unavailable for IB port in multifunction env.\n");
dmfs = 0;
}
}
return dmfs;
}
static int num_ib_ports(struct mlx4_dev *dev)
{
int ib_ports = 0;
int i;
mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_IB)
ib_ports++;
return ib_ports;
}
static int mlx4_ib_query_device(struct ib_device *ibdev,
struct ib_device_attr *props)
{
struct mlx4_ib_dev *dev = to_mdev(ibdev);
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
int have_ib_ports;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_NODE_INFO;
err = mlx4_MAD_IFC(to_mdev(ibdev), MLX4_MAD_IFC_IGNORE_KEYS,
1, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memset(props, 0, sizeof *props);
have_ib_ports = num_ib_ports(dev->dev);
props->fw_ver = dev->dev->caps.fw_ver;
props->device_cap_flags = IB_DEVICE_CHANGE_PHY_PORT |
IB_DEVICE_PORT_ACTIVE_EVENT |
IB_DEVICE_SYS_IMAGE_GUID |
IB_DEVICE_RC_RNR_NAK_GEN |
IB_DEVICE_BLOCK_MULTICAST_LOOPBACK;
if (dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_BAD_PKEY_CNTR)
props->device_cap_flags |= IB_DEVICE_BAD_PKEY_CNTR;
if (dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_BAD_QKEY_CNTR)
props->device_cap_flags |= IB_DEVICE_BAD_QKEY_CNTR;
if (dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_APM && have_ib_ports)
props->device_cap_flags |= IB_DEVICE_AUTO_PATH_MIG;
if (dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_UD_AV_PORT)
props->device_cap_flags |= IB_DEVICE_UD_AV_PORT_ENFORCE;
if (dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_IPOIB_CSUM)
props->device_cap_flags |= IB_DEVICE_UD_IP_CSUM;
if (dev->dev->caps.max_gso_sz &&
(dev->dev->rev_id != MLX4_IB_CARD_REV_A0) &&
(dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_BLH))
props->device_cap_flags |= IB_DEVICE_UD_TSO;
if (dev->dev->caps.bmme_flags & MLX4_BMME_FLAG_RESERVED_LKEY)
props->device_cap_flags |= IB_DEVICE_LOCAL_DMA_LKEY;
if ((dev->dev->caps.bmme_flags & MLX4_BMME_FLAG_LOCAL_INV) &&
(dev->dev->caps.bmme_flags & MLX4_BMME_FLAG_REMOTE_INV) &&
(dev->dev->caps.bmme_flags & MLX4_BMME_FLAG_FAST_REG_WR))
props->device_cap_flags |= IB_DEVICE_MEM_MGT_EXTENSIONS;
if (dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_XRC)
props->device_cap_flags |= IB_DEVICE_XRC;
if (dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_MEM_WINDOW)
props->device_cap_flags |= IB_DEVICE_MEM_WINDOW;
if (dev->dev->caps.bmme_flags & MLX4_BMME_FLAG_TYPE_2_WIN) {
if (dev->dev->caps.bmme_flags & MLX4_BMME_FLAG_WIN_TYPE_2B)
props->device_cap_flags |= IB_DEVICE_MEM_WINDOW_TYPE_2B;
else
props->device_cap_flags |= IB_DEVICE_MEM_WINDOW_TYPE_2A;
if (dev->steering_support == MLX4_STEERING_MODE_DEVICE_MANAGED)
props->device_cap_flags |= IB_DEVICE_MANAGED_FLOW_STEERING;
}
props->vendor_id = be32_to_cpup((__be32 *) (out_mad->data + 36)) &
0xffffff;
props->vendor_part_id = dev->dev->pdev->device;
props->hw_ver = be32_to_cpup((__be32 *) (out_mad->data + 32));
memcpy(&props->sys_image_guid, out_mad->data + 4, 8);
props->max_mr_size = ~0ull;
props->page_size_cap = dev->dev->caps.page_size_cap;
props->max_qp = dev->dev->quotas.qp;
props->max_qp_wr = dev->dev->caps.max_wqes - MLX4_IB_SQ_MAX_SPARE;
props->max_sge = min(dev->dev->caps.max_sq_sg,
dev->dev->caps.max_rq_sg);
props->max_cq = dev->dev->quotas.cq;
props->max_cqe = dev->dev->caps.max_cqes;
props->max_mr = dev->dev->quotas.mpt;
props->max_pd = dev->dev->caps.num_pds - dev->dev->caps.reserved_pds;
props->max_qp_rd_atom = dev->dev->caps.max_qp_dest_rdma;
props->max_qp_init_rd_atom = dev->dev->caps.max_qp_init_rdma;
props->max_res_rd_atom = props->max_qp_rd_atom * props->max_qp;
props->max_srq = dev->dev->quotas.srq;
props->max_srq_wr = dev->dev->caps.max_srq_wqes - 1;
props->max_srq_sge = dev->dev->caps.max_srq_sge;
props->max_fast_reg_page_list_len = MLX4_MAX_FAST_REG_PAGES;
props->local_ca_ack_delay = dev->dev->caps.local_ca_ack_delay;
props->atomic_cap = dev->dev->caps.flags & MLX4_DEV_CAP_FLAG_ATOMIC ?
IB_ATOMIC_HCA : IB_ATOMIC_NONE;
props->masked_atomic_cap = props->atomic_cap;
props->max_pkeys = dev->dev->caps.pkey_table_len[1];
props->max_mcast_grp = dev->dev->caps.num_mgms + dev->dev->caps.num_amgms;
props->max_mcast_qp_attach = dev->dev->caps.num_qp_per_mgm;
props->max_total_mcast_qp_attach = props->max_mcast_qp_attach *
props->max_mcast_grp;
props->max_map_per_fmr = dev->dev->caps.max_fmr_maps;
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
static enum rdma_link_layer
mlx4_ib_port_link_layer(struct ib_device *device, u8 port_num)
{
struct mlx4_dev *dev = to_mdev(device)->dev;
return dev->caps.port_mask[port_num] == MLX4_PORT_TYPE_IB ?
IB_LINK_LAYER_INFINIBAND : IB_LINK_LAYER_ETHERNET;
}
static int ib_link_query_port(struct ib_device *ibdev, u8 port,
struct ib_port_attr *props, int netw_view)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int ext_active_speed;
int mad_ifc_flags = MLX4_MAD_IFC_IGNORE_KEYS;
int err = -ENOMEM;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
if (mlx4_is_mfunc(to_mdev(ibdev)->dev) && netw_view)
mad_ifc_flags |= MLX4_MAD_IFC_NET_VIEW;
err = mlx4_MAD_IFC(to_mdev(ibdev), mad_ifc_flags, port, NULL, NULL,
in_mad, out_mad);
if (err)
goto out;
props->lid = be16_to_cpup((__be16 *) (out_mad->data + 16));
props->lmc = out_mad->data[34] & 0x7;
props->sm_lid = be16_to_cpup((__be16 *) (out_mad->data + 18));
props->sm_sl = out_mad->data[36] & 0xf;
props->state = out_mad->data[32] & 0xf;
props->phys_state = out_mad->data[33] >> 4;
props->port_cap_flags = be32_to_cpup((__be32 *) (out_mad->data + 20));
if (netw_view)
props->gid_tbl_len = out_mad->data[50];
else
props->gid_tbl_len = to_mdev(ibdev)->dev->caps.gid_table_len[port];
props->max_msg_sz = to_mdev(ibdev)->dev->caps.max_msg_sz;
props->pkey_tbl_len = to_mdev(ibdev)->dev->caps.pkey_table_len[port];
props->bad_pkey_cntr = be16_to_cpup((__be16 *) (out_mad->data + 46));
props->qkey_viol_cntr = be16_to_cpup((__be16 *) (out_mad->data + 48));
props->active_width = out_mad->data[31] & 0xf;
props->active_speed = out_mad->data[35] >> 4;
props->max_mtu = out_mad->data[41] & 0xf;
props->active_mtu = out_mad->data[36] >> 4;
props->subnet_timeout = out_mad->data[51] & 0x1f;
props->max_vl_num = out_mad->data[37] >> 4;
props->init_type_reply = out_mad->data[41] >> 4;
/* Check if extended speeds (EDR/FDR/...) are supported */
if (props->port_cap_flags & IB_PORT_EXTENDED_SPEEDS_SUP) {
ext_active_speed = out_mad->data[62] >> 4;
switch (ext_active_speed) {
case 1:
props->active_speed = IB_SPEED_FDR;
break;
case 2:
props->active_speed = IB_SPEED_EDR;
break;
}
}
/* If reported active speed is QDR, check if is FDR-10 */
if (props->active_speed == IB_SPEED_QDR) {
init_query_mad(in_mad);
in_mad->attr_id = MLX4_ATTR_EXTENDED_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
err = mlx4_MAD_IFC(to_mdev(ibdev), mad_ifc_flags, port,
NULL, NULL, in_mad, out_mad);
if (err)
goto out;
/* Checking LinkSpeedActive for FDR-10 */
if (out_mad->data[15] & 0x1)
props->active_speed = IB_SPEED_FDR10;
}
/* Avoid wrong speed value returned by FW if the IB link is down. */
if (props->state == IB_PORT_DOWN)
props->active_speed = IB_SPEED_SDR;
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
static u8 state_to_phys_state(enum ib_port_state state)
{
return state == IB_PORT_ACTIVE ? 5 : 3;
}
static int eth_link_query_port(struct ib_device *ibdev, u8 port,
struct ib_port_attr *props, int netw_view)
{
struct mlx4_ib_dev *mdev = to_mdev(ibdev);
struct mlx4_ib_iboe *iboe = &mdev->iboe;
struct net_device *ndev;
enum ib_mtu tmp;
struct mlx4_cmd_mailbox *mailbox;
int err = 0;
mailbox = mlx4_alloc_cmd_mailbox(mdev->dev);
if (IS_ERR(mailbox))
return PTR_ERR(mailbox);
err = mlx4_cmd_box(mdev->dev, 0, mailbox->dma, port, 0,
MLX4_CMD_QUERY_PORT, MLX4_CMD_TIME_CLASS_B,
MLX4_CMD_WRAPPED);
if (err)
goto out;
props->active_width = (((u8 *)mailbox->buf)[5] == 0x40) ?
IB_WIDTH_4X : IB_WIDTH_1X;
props->active_speed = IB_SPEED_QDR;
props->port_cap_flags = IB_PORT_CM_SUP | IB_PORT_IP_BASED_GIDS;
props->gid_tbl_len = mdev->dev->caps.gid_table_len[port];
props->max_msg_sz = mdev->dev->caps.max_msg_sz;
props->pkey_tbl_len = 1;
props->max_mtu = IB_MTU_4096;
props->max_vl_num = 2;
props->state = IB_PORT_DOWN;
props->phys_state = state_to_phys_state(props->state);
props->active_mtu = IB_MTU_256;
spin_lock_bh(&iboe->lock);
ndev = iboe->netdevs[port - 1];
if (!ndev)
goto out_unlock;
tmp = iboe_get_mtu(ndev->mtu);
props->active_mtu = tmp ? min(props->max_mtu, tmp) : IB_MTU_256;
props->state = (netif_running(ndev) && netif_carrier_ok(ndev)) ?
IB_PORT_ACTIVE : IB_PORT_DOWN;
props->phys_state = state_to_phys_state(props->state);
out_unlock:
spin_unlock_bh(&iboe->lock);
out:
mlx4_free_cmd_mailbox(mdev->dev, mailbox);
return err;
}
int __mlx4_ib_query_port(struct ib_device *ibdev, u8 port,
struct ib_port_attr *props, int netw_view)
{
int err;
memset(props, 0, sizeof *props);
err = mlx4_ib_port_link_layer(ibdev, port) == IB_LINK_LAYER_INFINIBAND ?
ib_link_query_port(ibdev, port, props, netw_view) :
eth_link_query_port(ibdev, port, props, netw_view);
return err;
}
static int mlx4_ib_query_port(struct ib_device *ibdev, u8 port,
struct ib_port_attr *props)
{
/* returns host view */
return __mlx4_ib_query_port(ibdev, port, props, 0);
}
int __mlx4_ib_query_gid(struct ib_device *ibdev, u8 port, int index,
union ib_gid *gid, int netw_view)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
struct mlx4_ib_dev *dev = to_mdev(ibdev);
int clear = 0;
int mad_ifc_flags = MLX4_MAD_IFC_IGNORE_KEYS;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
if (mlx4_is_mfunc(dev->dev) && netw_view)
mad_ifc_flags |= MLX4_MAD_IFC_NET_VIEW;
err = mlx4_MAD_IFC(dev, mad_ifc_flags, port, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memcpy(gid->raw, out_mad->data + 8, 8);
if (mlx4_is_mfunc(dev->dev) && !netw_view) {
if (index) {
/* For any index > 0, return the null guid */
err = 0;
clear = 1;
goto out;
}
}
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_GUID_INFO;
in_mad->attr_mod = cpu_to_be32(index / 8);
err = mlx4_MAD_IFC(dev, mad_ifc_flags, port,
NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memcpy(gid->raw + 8, out_mad->data + (index % 8) * 8, 8);
out:
if (clear)
memset(gid->raw + 8, 0, 8);
kfree(in_mad);
kfree(out_mad);
return err;
}
static int iboe_query_gid(struct ib_device *ibdev, u8 port, int index,
union ib_gid *gid)
{
struct mlx4_ib_dev *dev = to_mdev(ibdev);
*gid = dev->iboe.gid_table[port - 1][index];
return 0;
}
static int mlx4_ib_query_gid(struct ib_device *ibdev, u8 port, int index,
union ib_gid *gid)
{
if (rdma_port_get_link_layer(ibdev, port) == IB_LINK_LAYER_INFINIBAND)
return __mlx4_ib_query_gid(ibdev, port, index, gid, 0);
else
return iboe_query_gid(ibdev, port, index, gid);
}
int __mlx4_ib_query_pkey(struct ib_device *ibdev, u8 port, u16 index,
u16 *pkey, int netw_view)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int mad_ifc_flags = MLX4_MAD_IFC_IGNORE_KEYS;
int err = -ENOMEM;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PKEY_TABLE;
in_mad->attr_mod = cpu_to_be32(index / 32);
if (mlx4_is_mfunc(to_mdev(ibdev)->dev) && netw_view)
mad_ifc_flags |= MLX4_MAD_IFC_NET_VIEW;
err = mlx4_MAD_IFC(to_mdev(ibdev), mad_ifc_flags, port, NULL, NULL,
in_mad, out_mad);
if (err)
goto out;
*pkey = be16_to_cpu(((__be16 *) out_mad->data)[index % 32]);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
static int mlx4_ib_query_pkey(struct ib_device *ibdev, u8 port, u16 index, u16 *pkey)
{
return __mlx4_ib_query_pkey(ibdev, port, index, pkey, 0);
}
static int mlx4_ib_modify_device(struct ib_device *ibdev, int mask,
struct ib_device_modify *props)
{
struct mlx4_cmd_mailbox *mailbox;
unsigned long flags;
if (mask & ~IB_DEVICE_MODIFY_NODE_DESC)
return -EOPNOTSUPP;
if (!(mask & IB_DEVICE_MODIFY_NODE_DESC))
return 0;
if (mlx4_is_slave(to_mdev(ibdev)->dev))
return -EOPNOTSUPP;
spin_lock_irqsave(&to_mdev(ibdev)->sm_lock, flags);
memcpy(ibdev->node_desc, props->node_desc, 64);
spin_unlock_irqrestore(&to_mdev(ibdev)->sm_lock, flags);
/*
* If possible, pass node desc to FW, so it can generate
* a 144 trap. If cmd fails, just ignore.
*/
mailbox = mlx4_alloc_cmd_mailbox(to_mdev(ibdev)->dev);
if (IS_ERR(mailbox))
return 0;
memcpy(mailbox->buf, props->node_desc, 64);
mlx4_cmd(to_mdev(ibdev)->dev, mailbox->dma, 1, 0,
MLX4_CMD_SET_NODE, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE);
mlx4_free_cmd_mailbox(to_mdev(ibdev)->dev, mailbox);
return 0;
}
static int mlx4_ib_SET_PORT(struct mlx4_ib_dev *dev, u8 port, int reset_qkey_viols,
u32 cap_mask)
{
struct mlx4_cmd_mailbox *mailbox;
int err;
mailbox = mlx4_alloc_cmd_mailbox(dev->dev);
if (IS_ERR(mailbox))
return PTR_ERR(mailbox);
if (dev->dev->flags & MLX4_FLAG_OLD_PORT_CMDS) {
*(u8 *) mailbox->buf = !!reset_qkey_viols << 6;
((__be32 *) mailbox->buf)[2] = cpu_to_be32(cap_mask);
} else {
((u8 *) mailbox->buf)[3] = !!reset_qkey_viols;
((__be32 *) mailbox->buf)[1] = cpu_to_be32(cap_mask);
}
err = mlx4_cmd(dev->dev, mailbox->dma, port, 0, MLX4_CMD_SET_PORT,
MLX4_CMD_TIME_CLASS_B, MLX4_CMD_WRAPPED);
mlx4_free_cmd_mailbox(dev->dev, mailbox);
return err;
}
static int mlx4_ib_modify_port(struct ib_device *ibdev, u8 port, int mask,
struct ib_port_modify *props)
{
struct mlx4_ib_dev *mdev = to_mdev(ibdev);
u8 is_eth = mdev->dev->caps.port_type[port] == MLX4_PORT_TYPE_ETH;
struct ib_port_attr attr;
u32 cap_mask;
int err;
/* return OK if this is RoCE. CM calls ib_modify_port() regardless
* of whether port link layer is ETH or IB. For ETH ports, qkey
* violations and port capabilities are not meaningful.
*/
if (is_eth)
return 0;
mutex_lock(&mdev->cap_mask_mutex);
err = mlx4_ib_query_port(ibdev, port, &attr);
if (err)
goto out;
cap_mask = (attr.port_cap_flags | props->set_port_cap_mask) &
~props->clr_port_cap_mask;
err = mlx4_ib_SET_PORT(mdev, port,
!!(mask & IB_PORT_RESET_QKEY_CNTR),
cap_mask);
out:
mutex_unlock(&to_mdev(ibdev)->cap_mask_mutex);
return err;
}
static struct ib_ucontext *mlx4_ib_alloc_ucontext(struct ib_device *ibdev,
struct ib_udata *udata)
{
struct mlx4_ib_dev *dev = to_mdev(ibdev);
struct mlx4_ib_ucontext *context;
struct mlx4_ib_alloc_ucontext_resp_v3 resp_v3;
struct mlx4_ib_alloc_ucontext_resp resp;
int err;
if (!dev->ib_active)
return ERR_PTR(-EAGAIN);
if (ibdev->uverbs_abi_ver == MLX4_IB_UVERBS_NO_DEV_CAPS_ABI_VERSION) {
resp_v3.qp_tab_size = dev->dev->caps.num_qps;
resp_v3.bf_reg_size = dev->dev->caps.bf_reg_size;
resp_v3.bf_regs_per_page = dev->dev->caps.bf_regs_per_page;
} else {
resp.dev_caps = dev->dev->caps.userspace_caps;
resp.qp_tab_size = dev->dev->caps.num_qps;
resp.bf_reg_size = dev->dev->caps.bf_reg_size;
resp.bf_regs_per_page = dev->dev->caps.bf_regs_per_page;
resp.cqe_size = dev->dev->caps.cqe_size;
}
context = kmalloc(sizeof *context, GFP_KERNEL);
if (!context)
return ERR_PTR(-ENOMEM);
err = mlx4_uar_alloc(to_mdev(ibdev)->dev, &context->uar);
if (err) {
kfree(context);
return ERR_PTR(err);
}
INIT_LIST_HEAD(&context->db_page_list);
mutex_init(&context->db_page_mutex);
if (ibdev->uverbs_abi_ver == MLX4_IB_UVERBS_NO_DEV_CAPS_ABI_VERSION)
err = ib_copy_to_udata(udata, &resp_v3, sizeof(resp_v3));
else
err = ib_copy_to_udata(udata, &resp, sizeof(resp));
if (err) {
mlx4_uar_free(to_mdev(ibdev)->dev, &context->uar);
kfree(context);
return ERR_PTR(-EFAULT);
}
return &context->ibucontext;
}
static int mlx4_ib_dealloc_ucontext(struct ib_ucontext *ibcontext)
{
struct mlx4_ib_ucontext *context = to_mucontext(ibcontext);
mlx4_uar_free(to_mdev(ibcontext->device)->dev, &context->uar);
kfree(context);
return 0;
}
static int mlx4_ib_mmap(struct ib_ucontext *context, struct vm_area_struct *vma)
{
struct mlx4_ib_dev *dev = to_mdev(context->device);
if (vma->vm_end - vma->vm_start != PAGE_SIZE)
return -EINVAL;
if (vma->vm_pgoff == 0) {
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
if (io_remap_pfn_range(vma, vma->vm_start,
to_mucontext(context)->uar.pfn,
PAGE_SIZE, vma->vm_page_prot))
return -EAGAIN;
} else if (vma->vm_pgoff == 1 && dev->dev->caps.bf_reg_size != 0) {
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
if (io_remap_pfn_range(vma, vma->vm_start,
to_mucontext(context)->uar.pfn +
dev->dev->caps.num_uars,
PAGE_SIZE, vma->vm_page_prot))
return -EAGAIN;
} else
return -EINVAL;
return 0;
}
static struct ib_pd *mlx4_ib_alloc_pd(struct ib_device *ibdev,
struct ib_ucontext *context,
struct ib_udata *udata)
{
struct mlx4_ib_pd *pd;
int err;
pd = kmalloc(sizeof *pd, GFP_KERNEL);
if (!pd)
return ERR_PTR(-ENOMEM);
err = mlx4_pd_alloc(to_mdev(ibdev)->dev, &pd->pdn);
if (err) {
kfree(pd);
return ERR_PTR(err);
}
if (context)
if (ib_copy_to_udata(udata, &pd->pdn, sizeof (__u32))) {
mlx4_pd_free(to_mdev(ibdev)->dev, pd->pdn);
kfree(pd);
return ERR_PTR(-EFAULT);
}
return &pd->ibpd;
}
static int mlx4_ib_dealloc_pd(struct ib_pd *pd)
{
mlx4_pd_free(to_mdev(pd->device)->dev, to_mpd(pd)->pdn);
kfree(pd);
return 0;
}
static struct ib_xrcd *mlx4_ib_alloc_xrcd(struct ib_device *ibdev,
struct ib_ucontext *context,
struct ib_udata *udata)
{
struct mlx4_ib_xrcd *xrcd;
int err;
if (!(to_mdev(ibdev)->dev->caps.flags & MLX4_DEV_CAP_FLAG_XRC))
return ERR_PTR(-ENOSYS);
xrcd = kmalloc(sizeof *xrcd, GFP_KERNEL);
if (!xrcd)
return ERR_PTR(-ENOMEM);
err = mlx4_xrcd_alloc(to_mdev(ibdev)->dev, &xrcd->xrcdn);
if (err)
goto err1;
xrcd->pd = ib_alloc_pd(ibdev);
if (IS_ERR(xrcd->pd)) {
err = PTR_ERR(xrcd->pd);
goto err2;
}
xrcd->cq = ib_create_cq(ibdev, NULL, NULL, xrcd, 1, 0);
if (IS_ERR(xrcd->cq)) {
err = PTR_ERR(xrcd->cq);
goto err3;
}
return &xrcd->ibxrcd;
err3:
ib_dealloc_pd(xrcd->pd);
err2:
mlx4_xrcd_free(to_mdev(ibdev)->dev, xrcd->xrcdn);
err1:
kfree(xrcd);
return ERR_PTR(err);
}
static int mlx4_ib_dealloc_xrcd(struct ib_xrcd *xrcd)
{
ib_destroy_cq(to_mxrcd(xrcd)->cq);
ib_dealloc_pd(to_mxrcd(xrcd)->pd);
mlx4_xrcd_free(to_mdev(xrcd->device)->dev, to_mxrcd(xrcd)->xrcdn);
kfree(xrcd);
return 0;
}
static int add_gid_entry(struct ib_qp *ibqp, union ib_gid *gid)
{
struct mlx4_ib_qp *mqp = to_mqp(ibqp);
struct mlx4_ib_dev *mdev = to_mdev(ibqp->device);
struct mlx4_ib_gid_entry *ge;
ge = kzalloc(sizeof *ge, GFP_KERNEL);
if (!ge)
return -ENOMEM;
ge->gid = *gid;
if (mlx4_ib_add_mc(mdev, mqp, gid)) {
ge->port = mqp->port;
ge->added = 1;
}
mutex_lock(&mqp->mutex);
list_add_tail(&ge->list, &mqp->gid_list);
mutex_unlock(&mqp->mutex);
return 0;
}
int mlx4_ib_add_mc(struct mlx4_ib_dev *mdev, struct mlx4_ib_qp *mqp,
union ib_gid *gid)
{
struct net_device *ndev;
int ret = 0;
if (!mqp->port)
return 0;
spin_lock_bh(&mdev->iboe.lock);
ndev = mdev->iboe.netdevs[mqp->port - 1];
if (ndev)
dev_hold(ndev);
spin_unlock_bh(&mdev->iboe.lock);
if (ndev) {
ret = 1;
dev_put(ndev);
}
return ret;
}
struct mlx4_ib_steering {
struct list_head list;
u64 reg_id;
union ib_gid gid;
};
static int parse_flow_attr(struct mlx4_dev *dev,
u32 qp_num,
union ib_flow_spec *ib_spec,
struct _rule_hw *mlx4_spec)
{
enum mlx4_net_trans_rule_id type;
switch (ib_spec->type) {
case IB_FLOW_SPEC_ETH:
type = MLX4_NET_TRANS_RULE_ID_ETH;
memcpy(mlx4_spec->eth.dst_mac, ib_spec->eth.val.dst_mac,
ETH_ALEN);
memcpy(mlx4_spec->eth.dst_mac_msk, ib_spec->eth.mask.dst_mac,
ETH_ALEN);
mlx4_spec->eth.vlan_tag = ib_spec->eth.val.vlan_tag;
mlx4_spec->eth.vlan_tag_msk = ib_spec->eth.mask.vlan_tag;
break;
case IB_FLOW_SPEC_IB:
type = MLX4_NET_TRANS_RULE_ID_IB;
mlx4_spec->ib.l3_qpn =
cpu_to_be32(qp_num);
mlx4_spec->ib.qpn_mask =
cpu_to_be32(MLX4_IB_FLOW_QPN_MASK);
break;
case IB_FLOW_SPEC_IPV4:
type = MLX4_NET_TRANS_RULE_ID_IPV4;
mlx4_spec->ipv4.src_ip = ib_spec->ipv4.val.src_ip;
mlx4_spec->ipv4.src_ip_msk = ib_spec->ipv4.mask.src_ip;
mlx4_spec->ipv4.dst_ip = ib_spec->ipv4.val.dst_ip;
mlx4_spec->ipv4.dst_ip_msk = ib_spec->ipv4.mask.dst_ip;
break;
case IB_FLOW_SPEC_TCP:
case IB_FLOW_SPEC_UDP:
type = ib_spec->type == IB_FLOW_SPEC_TCP ?
MLX4_NET_TRANS_RULE_ID_TCP :
MLX4_NET_TRANS_RULE_ID_UDP;
mlx4_spec->tcp_udp.dst_port = ib_spec->tcp_udp.val.dst_port;
mlx4_spec->tcp_udp.dst_port_msk = ib_spec->tcp_udp.mask.dst_port;
mlx4_spec->tcp_udp.src_port = ib_spec->tcp_udp.val.src_port;
mlx4_spec->tcp_udp.src_port_msk = ib_spec->tcp_udp.mask.src_port;
break;
default:
return -EINVAL;
}
if (mlx4_map_sw_to_hw_steering_id(dev, type) < 0 ||
mlx4_hw_rule_sz(dev, type) < 0)
return -EINVAL;
mlx4_spec->id = cpu_to_be16(mlx4_map_sw_to_hw_steering_id(dev, type));
mlx4_spec->size = mlx4_hw_rule_sz(dev, type) >> 2;
return mlx4_hw_rule_sz(dev, type);
}
struct default_rules {
__u32 mandatory_fields[IB_FLOW_SPEC_SUPPORT_LAYERS];
__u32 mandatory_not_fields[IB_FLOW_SPEC_SUPPORT_LAYERS];
__u32 rules_create_list[IB_FLOW_SPEC_SUPPORT_LAYERS];
__u8 link_layer;
};
static const struct default_rules default_table[] = {
{
.mandatory_fields = {IB_FLOW_SPEC_IPV4},
.mandatory_not_fields = {IB_FLOW_SPEC_ETH},
.rules_create_list = {IB_FLOW_SPEC_IB},
.link_layer = IB_LINK_LAYER_INFINIBAND
}
};
static int __mlx4_ib_default_rules_match(struct ib_qp *qp,
struct ib_flow_attr *flow_attr)
{
int i, j, k;
void *ib_flow;
const struct default_rules *pdefault_rules = default_table;
u8 link_layer = rdma_port_get_link_layer(qp->device, flow_attr->port);
for (i = 0; i < ARRAY_SIZE(default_table); i++, pdefault_rules++) {
__u32 field_types[IB_FLOW_SPEC_SUPPORT_LAYERS];
memset(&field_types, 0, sizeof(field_types));
if (link_layer != pdefault_rules->link_layer)
continue;
ib_flow = flow_attr + 1;
/* we assume the specs are sorted */
for (j = 0, k = 0; k < IB_FLOW_SPEC_SUPPORT_LAYERS &&
j < flow_attr->num_of_specs; k++) {
union ib_flow_spec *current_flow =
(union ib_flow_spec *)ib_flow;
/* same layer but different type */
if (((current_flow->type & IB_FLOW_SPEC_LAYER_MASK) ==
(pdefault_rules->mandatory_fields[k] &
IB_FLOW_SPEC_LAYER_MASK)) &&
(current_flow->type !=
pdefault_rules->mandatory_fields[k]))
goto out;
/* same layer, try match next one */
if (current_flow->type ==
pdefault_rules->mandatory_fields[k]) {
j++;
ib_flow +=
((union ib_flow_spec *)ib_flow)->size;
}
}
ib_flow = flow_attr + 1;
for (j = 0; j < flow_attr->num_of_specs;
j++, ib_flow += ((union ib_flow_spec *)ib_flow)->size)
for (k = 0; k < IB_FLOW_SPEC_SUPPORT_LAYERS; k++)
/* same layer and same type */
if (((union ib_flow_spec *)ib_flow)->type ==
pdefault_rules->mandatory_not_fields[k])
goto out;
return i;
}
out:
return -1;
}
static int __mlx4_ib_create_default_rules(
struct mlx4_ib_dev *mdev,
struct ib_qp *qp,
const struct default_rules *pdefault_rules,
struct _rule_hw *mlx4_spec) {
int size = 0;
int i;
for (i = 0; i < ARRAY_SIZE(pdefault_rules->rules_create_list); i++) {
int ret;
union ib_flow_spec ib_spec;
switch (pdefault_rules->rules_create_list[i]) {
case 0:
/* no rule */
continue;
case IB_FLOW_SPEC_IB:
ib_spec.type = IB_FLOW_SPEC_IB;
ib_spec.size = sizeof(struct ib_flow_spec_ib);
break;
default:
/* invalid rule */
return -EINVAL;
}
/* We must put empty rule, qpn is being ignored */
ret = parse_flow_attr(mdev->dev, 0, &ib_spec,
mlx4_spec);
if (ret < 0) {
pr_info("invalid parsing\n");
return -EINVAL;
}
mlx4_spec = (void *)mlx4_spec + ret;
size += ret;
}
return size;
}
static int __mlx4_ib_create_flow(struct ib_qp *qp, struct ib_flow_attr *flow_attr,
int domain,
enum mlx4_net_trans_promisc_mode flow_type,
u64 *reg_id)
{
int ret, i;
int size = 0;
void *ib_flow;
struct mlx4_ib_dev *mdev = to_mdev(qp->device);
struct mlx4_cmd_mailbox *mailbox;
struct mlx4_net_trans_rule_hw_ctrl *ctrl;
int default_flow;
static const u16 __mlx4_domain[] = {
[IB_FLOW_DOMAIN_USER] = MLX4_DOMAIN_UVERBS,
[IB_FLOW_DOMAIN_ETHTOOL] = MLX4_DOMAIN_ETHTOOL,
[IB_FLOW_DOMAIN_RFS] = MLX4_DOMAIN_RFS,
[IB_FLOW_DOMAIN_NIC] = MLX4_DOMAIN_NIC,
};
if (flow_attr->priority > MLX4_IB_FLOW_MAX_PRIO) {
pr_err("Invalid priority value %d\n", flow_attr->priority);
return -EINVAL;
}
if (domain >= IB_FLOW_DOMAIN_NUM) {
pr_err("Invalid domain value %d\n", domain);
return -EINVAL;
}
if (mlx4_map_sw_to_hw_steering_mode(mdev->dev, flow_type) < 0)
return -EINVAL;
mailbox = mlx4_alloc_cmd_mailbox(mdev->dev);
if (IS_ERR(mailbox))
return PTR_ERR(mailbox);
ctrl = mailbox->buf;
ctrl->prio = cpu_to_be16(__mlx4_domain[domain] |
flow_attr->priority);
ctrl->type = mlx4_map_sw_to_hw_steering_mode(mdev->dev, flow_type);
ctrl->port = flow_attr->port;
ctrl->qpn = cpu_to_be32(qp->qp_num);
ib_flow = flow_attr + 1;
size += sizeof(struct mlx4_net_trans_rule_hw_ctrl);
/* Add default flows */
default_flow = __mlx4_ib_default_rules_match(qp, flow_attr);
if (default_flow >= 0) {
ret = __mlx4_ib_create_default_rules(
mdev, qp, default_table + default_flow,
mailbox->buf + size);
if (ret < 0) {
mlx4_free_cmd_mailbox(mdev->dev, mailbox);
return -EINVAL;
}
size += ret;
}
for (i = 0; i < flow_attr->num_of_specs; i++) {
ret = parse_flow_attr(mdev->dev, qp->qp_num, ib_flow,
mailbox->buf + size);
if (ret < 0) {
mlx4_free_cmd_mailbox(mdev->dev, mailbox);
return -EINVAL;
}
ib_flow += ((union ib_flow_spec *) ib_flow)->size;
size += ret;
}
ret = mlx4_cmd_imm(mdev->dev, mailbox->dma, reg_id, size >> 2, 0,
MLX4_QP_FLOW_STEERING_ATTACH, MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (ret == -ENOMEM)
pr_err("mcg table is full. Fail to register network rule.\n");
else if (ret == -ENXIO)
pr_err("Device managed flow steering is disabled. Fail to register network rule.\n");
else if (ret)
pr_err("Invalid argumant. Fail to register network rule.\n");
mlx4_free_cmd_mailbox(mdev->dev, mailbox);
return ret;
}
static int __mlx4_ib_destroy_flow(struct mlx4_dev *dev, u64 reg_id)
{
int err;
err = mlx4_cmd(dev, reg_id, 0, 0,
MLX4_QP_FLOW_STEERING_DETACH, MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (err)
pr_err("Fail to detach network rule. registration id = 0x%llx\n",
reg_id);
return err;
}
static int mlx4_ib_tunnel_steer_add(struct ib_qp *qp, struct ib_flow_attr *flow_attr,
u64 *reg_id)
{
void *ib_flow;
union ib_flow_spec *ib_spec;
struct mlx4_dev *dev = to_mdev(qp->device)->dev;
int err = 0;
if (dev->caps.tunnel_offload_mode != MLX4_TUNNEL_OFFLOAD_MODE_VXLAN ||
dev->caps.dmfs_high_steer_mode == MLX4_STEERING_DMFS_A0_STATIC)
return 0; /* do nothing */
ib_flow = flow_attr + 1;
ib_spec = (union ib_flow_spec *)ib_flow;
if (ib_spec->type != IB_FLOW_SPEC_ETH || flow_attr->num_of_specs != 1)
return 0; /* do nothing */
err = mlx4_tunnel_steer_add(to_mdev(qp->device)->dev, ib_spec->eth.val.dst_mac,
flow_attr->port, qp->qp_num,
MLX4_DOMAIN_UVERBS | (flow_attr->priority & 0xff),
reg_id);
return err;
}
static struct ib_flow *mlx4_ib_create_flow(struct ib_qp *qp,
struct ib_flow_attr *flow_attr,
int domain)
{
int err = 0, i = 0;
struct mlx4_ib_flow *mflow;
enum mlx4_net_trans_promisc_mode type[2];
memset(type, 0, sizeof(type));
mflow = kzalloc(sizeof(*mflow), GFP_KERNEL);
if (!mflow) {
err = -ENOMEM;
goto err_free;
}
switch (flow_attr->type) {
case IB_FLOW_ATTR_NORMAL:
type[0] = MLX4_FS_REGULAR;
break;
case IB_FLOW_ATTR_ALL_DEFAULT:
type[0] = MLX4_FS_ALL_DEFAULT;
break;
case IB_FLOW_ATTR_MC_DEFAULT:
type[0] = MLX4_FS_MC_DEFAULT;
break;
case IB_FLOW_ATTR_SNIFFER:
type[0] = MLX4_FS_UC_SNIFFER;
type[1] = MLX4_FS_MC_SNIFFER;
break;
default:
err = -EINVAL;
goto err_free;
}
while (i < ARRAY_SIZE(type) && type[i]) {
err = __mlx4_ib_create_flow(qp, flow_attr, domain, type[i],
&mflow->reg_id[i]);
if (err)
goto err_create_flow;
i++;
}
if (i < ARRAY_SIZE(type) && flow_attr->type == IB_FLOW_ATTR_NORMAL) {
err = mlx4_ib_tunnel_steer_add(qp, flow_attr, &mflow->reg_id[i]);
if (err)
goto err_create_flow;
i++;
}
return &mflow->ibflow;
err_create_flow:
while (i) {
(void)__mlx4_ib_destroy_flow(to_mdev(qp->device)->dev, mflow->reg_id[i]);
i--;
}
err_free:
kfree(mflow);
return ERR_PTR(err);
}
static int mlx4_ib_destroy_flow(struct ib_flow *flow_id)
{
int err, ret = 0;
int i = 0;
struct mlx4_ib_dev *mdev = to_mdev(flow_id->qp->device);
struct mlx4_ib_flow *mflow = to_mflow(flow_id);
while (i < ARRAY_SIZE(mflow->reg_id) && mflow->reg_id[i]) {
err = __mlx4_ib_destroy_flow(mdev->dev, mflow->reg_id[i]);
if (err)
ret = err;
i++;
}
kfree(mflow);
return ret;
}
static int mlx4_ib_mcg_attach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
{
int err;
struct mlx4_ib_dev *mdev = to_mdev(ibqp->device);
struct mlx4_ib_qp *mqp = to_mqp(ibqp);
u64 reg_id;
struct mlx4_ib_steering *ib_steering = NULL;
enum mlx4_protocol prot = MLX4_PROT_IB_IPV6;
if (mdev->dev->caps.steering_mode ==
MLX4_STEERING_MODE_DEVICE_MANAGED) {
ib_steering = kmalloc(sizeof(*ib_steering), GFP_KERNEL);
if (!ib_steering)
return -ENOMEM;
}
err = mlx4_multicast_attach(mdev->dev, &mqp->mqp, gid->raw, mqp->port,
!!(mqp->flags &
MLX4_IB_QP_BLOCK_MULTICAST_LOOPBACK),
prot, ®_id);
if (err) {
pr_err("multicast attach op failed, err %d\n", err);
goto err_malloc;
}
err = add_gid_entry(ibqp, gid);
if (err)
goto err_add;
if (ib_steering) {
memcpy(ib_steering->gid.raw, gid->raw, 16);
ib_steering->reg_id = reg_id;
mutex_lock(&mqp->mutex);
list_add(&ib_steering->list, &mqp->steering_rules);
mutex_unlock(&mqp->mutex);
}
return 0;
err_add:
mlx4_multicast_detach(mdev->dev, &mqp->mqp, gid->raw,
prot, reg_id);
err_malloc:
kfree(ib_steering);
return err;
}
static struct mlx4_ib_gid_entry *find_gid_entry(struct mlx4_ib_qp *qp, u8 *raw)
{
struct mlx4_ib_gid_entry *ge;
struct mlx4_ib_gid_entry *tmp;
struct mlx4_ib_gid_entry *ret = NULL;
list_for_each_entry_safe(ge, tmp, &qp->gid_list, list) {
if (!memcmp(raw, ge->gid.raw, 16)) {
ret = ge;
break;
}
}
return ret;
}
static int mlx4_ib_mcg_detach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
{
int err;
struct mlx4_ib_dev *mdev = to_mdev(ibqp->device);
struct mlx4_ib_qp *mqp = to_mqp(ibqp);
struct net_device *ndev;
struct mlx4_ib_gid_entry *ge;
u64 reg_id = 0;
enum mlx4_protocol prot = MLX4_PROT_IB_IPV6;
if (mdev->dev->caps.steering_mode ==
MLX4_STEERING_MODE_DEVICE_MANAGED) {
struct mlx4_ib_steering *ib_steering;
mutex_lock(&mqp->mutex);
list_for_each_entry(ib_steering, &mqp->steering_rules, list) {
if (!memcmp(ib_steering->gid.raw, gid->raw, 16)) {
list_del(&ib_steering->list);
break;
}
}
mutex_unlock(&mqp->mutex);
if (&ib_steering->list == &mqp->steering_rules) {
pr_err("Couldn't find reg_id for mgid. Steering rule is left attached\n");
return -EINVAL;
}
reg_id = ib_steering->reg_id;
kfree(ib_steering);
}
err = mlx4_multicast_detach(mdev->dev, &mqp->mqp, gid->raw,
prot, reg_id);
if (err)
return err;
mutex_lock(&mqp->mutex);
ge = find_gid_entry(mqp, gid->raw);
if (ge) {
spin_lock_bh(&mdev->iboe.lock);
ndev = ge->added ? mdev->iboe.netdevs[ge->port - 1] : NULL;
if (ndev)
dev_hold(ndev);
spin_unlock_bh(&mdev->iboe.lock);
if (ndev)
dev_put(ndev);
list_del(&ge->list);
kfree(ge);
} else
pr_warn("could not find mgid entry\n");
mutex_unlock(&mqp->mutex);
return 0;
}
static int init_node_data(struct mlx4_ib_dev *dev)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int mad_ifc_flags = MLX4_MAD_IFC_IGNORE_KEYS;
int err = -ENOMEM;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_NODE_DESC;
if (mlx4_is_master(dev->dev))
mad_ifc_flags |= MLX4_MAD_IFC_NET_VIEW;
err = mlx4_MAD_IFC(dev, mad_ifc_flags, 1, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memcpy(dev->ib_dev.node_desc, out_mad->data, 64);
in_mad->attr_id = IB_SMP_ATTR_NODE_INFO;
err = mlx4_MAD_IFC(dev, mad_ifc_flags, 1, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
dev->dev->rev_id = be32_to_cpup((__be32 *) (out_mad->data + 32));
memcpy(&dev->ib_dev.node_guid, out_mad->data + 12, 8);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
static ssize_t show_hca(struct device *device, struct device_attribute *attr,
char *buf)
{
struct mlx4_ib_dev *dev =
container_of(device, struct mlx4_ib_dev, ib_dev.dev);
return sprintf(buf, "MT%d\n", dev->dev->pdev->device);
}
static ssize_t show_fw_ver(struct device *device, struct device_attribute *attr,
char *buf)
{
struct mlx4_ib_dev *dev =
container_of(device, struct mlx4_ib_dev, ib_dev.dev);
return sprintf(buf, "%d.%d.%d\n", (int) (dev->dev->caps.fw_ver >> 32),
(int) (dev->dev->caps.fw_ver >> 16) & 0xffff,
(int) dev->dev->caps.fw_ver & 0xffff);
}
static ssize_t show_rev(struct device *device, struct device_attribute *attr,
char *buf)
{
struct mlx4_ib_dev *dev =
container_of(device, struct mlx4_ib_dev, ib_dev.dev);
return sprintf(buf, "%x\n", dev->dev->rev_id);
}
static ssize_t show_board(struct device *device, struct device_attribute *attr,
char *buf)
{
struct mlx4_ib_dev *dev =
container_of(device, struct mlx4_ib_dev, ib_dev.dev);
return sprintf(buf, "%.*s\n", MLX4_BOARD_ID_LEN,
dev->dev->board_id);
}
static DEVICE_ATTR(hw_rev, S_IRUGO, show_rev, NULL);
static DEVICE_ATTR(fw_ver, S_IRUGO, show_fw_ver, NULL);
static DEVICE_ATTR(hca_type, S_IRUGO, show_hca, NULL);
static DEVICE_ATTR(board_id, S_IRUGO, show_board, NULL);
static struct device_attribute *mlx4_class_attributes[] = {
&dev_attr_hw_rev,
&dev_attr_fw_ver,
&dev_attr_hca_type,
&dev_attr_board_id
};
static void mlx4_addrconf_ifid_eui48(u8 *eui, u16 vlan_id,
struct net_device *dev)
{
memcpy(eui, dev->dev_addr, 3);
memcpy(eui + 5, dev->dev_addr + 3, 3);
if (vlan_id < 0x1000) {
eui[3] = vlan_id >> 8;
eui[4] = vlan_id & 0xff;
} else {
eui[3] = 0xff;
eui[4] = 0xfe;
}
eui[0] ^= 2;
}
static void update_gids_task(struct work_struct *work)
{
struct update_gid_work *gw = container_of(work, struct update_gid_work, work);
struct mlx4_cmd_mailbox *mailbox;
union ib_gid *gids;
int err;
struct mlx4_dev *dev = gw->dev->dev;
if (!gw->dev->ib_active)
return;
mailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(mailbox)) {
pr_warn("update gid table failed %ld\n", PTR_ERR(mailbox));
return;
}
gids = mailbox->buf;
memcpy(gids, gw->gids, sizeof gw->gids);
err = mlx4_cmd(dev, mailbox->dma, MLX4_SET_PORT_GID_TABLE << 8 | gw->port,
1, MLX4_CMD_SET_PORT, MLX4_CMD_TIME_CLASS_B,
MLX4_CMD_WRAPPED);
if (err)
pr_warn("set port command failed\n");
else
mlx4_ib_dispatch_event(gw->dev, gw->port, IB_EVENT_GID_CHANGE);
mlx4_free_cmd_mailbox(dev, mailbox);
kfree(gw);
}
static void reset_gids_task(struct work_struct *work)
{
struct update_gid_work *gw =
container_of(work, struct update_gid_work, work);
struct mlx4_cmd_mailbox *mailbox;
union ib_gid *gids;
int err;
struct mlx4_dev *dev = gw->dev->dev;
if (!gw->dev->ib_active)
return;
mailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(mailbox)) {
pr_warn("reset gid table failed\n");
goto free;
}
gids = mailbox->buf;
memcpy(gids, gw->gids, sizeof(gw->gids));
if (mlx4_ib_port_link_layer(&gw->dev->ib_dev, gw->port) ==
IB_LINK_LAYER_ETHERNET) {
err = mlx4_cmd(dev, mailbox->dma,
MLX4_SET_PORT_GID_TABLE << 8 | gw->port,
1, MLX4_CMD_SET_PORT,
MLX4_CMD_TIME_CLASS_B,
MLX4_CMD_WRAPPED);
if (err)
pr_warn(KERN_WARNING
"set port %d command failed\n", gw->port);
}
mlx4_free_cmd_mailbox(dev, mailbox);
free:
kfree(gw);
}
static int update_gid_table(struct mlx4_ib_dev *dev, int port,
union ib_gid *gid, int clear,
int default_gid)
{
struct update_gid_work *work;
int i;
int need_update = 0;
int free = -1;
int found = -1;
int max_gids;
if (default_gid) {
free = 0;
} else {
max_gids = dev->dev->caps.gid_table_len[port];
for (i = 1; i < max_gids; ++i) {
if (!memcmp(&dev->iboe.gid_table[port - 1][i], gid,
sizeof(*gid)))
found = i;
if (clear) {
if (found >= 0) {
need_update = 1;
dev->iboe.gid_table[port - 1][found] =
zgid;
break;
}
} else {
if (found >= 0)
break;
if (free < 0 &&
!memcmp(&dev->iboe.gid_table[port - 1][i],
&zgid, sizeof(*gid)))
free = i;
}
}
}
if (found == -1 && !clear && free >= 0) {
dev->iboe.gid_table[port - 1][free] = *gid;
need_update = 1;
}
if (!need_update)
return 0;
work = kzalloc(sizeof(*work), GFP_ATOMIC);
if (!work)
return -ENOMEM;
memcpy(work->gids, dev->iboe.gid_table[port - 1], sizeof(work->gids));
INIT_WORK(&work->work, update_gids_task);
work->port = port;
work->dev = dev;
queue_work(wq, &work->work);
return 0;
}
static void mlx4_make_default_gid(struct net_device *dev, union ib_gid *gid)
{
gid->global.subnet_prefix = cpu_to_be64(0xfe80000000000000LL);
mlx4_addrconf_ifid_eui48(&gid->raw[8], 0xffff, dev);
}
static int reset_gid_table(struct mlx4_ib_dev *dev, u8 port)
{
struct update_gid_work *work;
work = kzalloc(sizeof(*work), GFP_ATOMIC);
if (!work)
return -ENOMEM;
memset(dev->iboe.gid_table[port - 1], 0, sizeof(work->gids));
memset(work->gids, 0, sizeof(work->gids));
INIT_WORK(&work->work, reset_gids_task);
work->dev = dev;
work->port = port;
queue_work(wq, &work->work);
return 0;
}
static int mlx4_ib_addr_event(int event, struct net_device *event_netdev,
struct mlx4_ib_dev *ibdev, union ib_gid *gid)
{
struct mlx4_ib_iboe *iboe;
int port = 0;
struct net_device *real_dev = rdma_vlan_dev_real_dev(event_netdev) ?
rdma_vlan_dev_real_dev(event_netdev) :
event_netdev;
union ib_gid default_gid;
mlx4_make_default_gid(real_dev, &default_gid);
if (!memcmp(gid, &default_gid, sizeof(*gid)))
return 0;
if (event != NETDEV_DOWN && event != NETDEV_UP)
return 0;
if ((real_dev != event_netdev) &&
(event == NETDEV_DOWN) &&
rdma_link_local_addr((struct in6_addr *)gid))
return 0;
iboe = &ibdev->iboe;
spin_lock_bh(&iboe->lock);
for (port = 1; port <= ibdev->dev->caps.num_ports; ++port)
if ((netif_is_bond_master(real_dev) &&
(real_dev == iboe->masters[port - 1])) ||
(!netif_is_bond_master(real_dev) &&
(real_dev == iboe->netdevs[port - 1])))
update_gid_table(ibdev, port, gid,
event == NETDEV_DOWN, 0);
spin_unlock_bh(&iboe->lock);
return 0;
}
static u8 mlx4_ib_get_dev_port(struct net_device *dev,
struct mlx4_ib_dev *ibdev)
{
u8 port = 0;
struct mlx4_ib_iboe *iboe;
struct net_device *real_dev = rdma_vlan_dev_real_dev(dev) ?
rdma_vlan_dev_real_dev(dev) : dev;
iboe = &ibdev->iboe;
for (port = 1; port <= ibdev->dev->caps.num_ports; ++port)
if ((netif_is_bond_master(real_dev) &&
(real_dev == iboe->masters[port - 1])) ||
(!netif_is_bond_master(real_dev) &&
(real_dev == iboe->netdevs[port - 1])))
break;
if ((port == 0) || (port > ibdev->dev->caps.num_ports))
return 0;
else
return port;
}
static int mlx4_ib_inet_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct mlx4_ib_dev *ibdev;
struct in_ifaddr *ifa = ptr;
union ib_gid gid;
struct net_device *event_netdev = ifa->ifa_dev->dev;
ipv6_addr_set_v4mapped(ifa->ifa_address, (struct in6_addr *)&gid);
ibdev = container_of(this, struct mlx4_ib_dev, iboe.nb_inet);
mlx4_ib_addr_event(event, event_netdev, ibdev, &gid);
return NOTIFY_DONE;
}
#if IS_ENABLED(CONFIG_IPV6)
static int mlx4_ib_inet6_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct mlx4_ib_dev *ibdev;
struct inet6_ifaddr *ifa = ptr;
union ib_gid *gid = (union ib_gid *)&ifa->addr;
struct net_device *event_netdev = ifa->idev->dev;
ibdev = container_of(this, struct mlx4_ib_dev, iboe.nb_inet6);
mlx4_ib_addr_event(event, event_netdev, ibdev, gid);
return NOTIFY_DONE;
}
#endif
#define MLX4_IB_INVALID_MAC ((u64)-1)
static void mlx4_ib_update_qps(struct mlx4_ib_dev *ibdev,
struct net_device *dev,
int port)
{
u64 new_smac = 0;
u64 release_mac = MLX4_IB_INVALID_MAC;
struct mlx4_ib_qp *qp;
read_lock(&dev_base_lock);
new_smac = mlx4_mac_to_u64(dev->dev_addr);
read_unlock(&dev_base_lock);
atomic64_set(&ibdev->iboe.mac[port - 1], new_smac);
/* no need for update QP1 and mac registration in non-SRIOV */
if (!mlx4_is_mfunc(ibdev->dev))
return;
mutex_lock(&ibdev->qp1_proxy_lock[port - 1]);
qp = ibdev->qp1_proxy[port - 1];
if (qp) {
int new_smac_index;
u64 old_smac;
struct mlx4_update_qp_params update_params;
mutex_lock(&qp->mutex);
old_smac = qp->pri.smac;
if (new_smac == old_smac)
goto unlock;
new_smac_index = mlx4_register_mac(ibdev->dev, port, new_smac);
if (new_smac_index < 0)
goto unlock;
update_params.smac_index = new_smac_index;
if (mlx4_update_qp(ibdev->dev, qp->mqp.qpn, MLX4_UPDATE_QP_SMAC,
&update_params)) {
release_mac = new_smac;
goto unlock;
}
/* if old port was zero, no mac was yet registered for this QP */
if (qp->pri.smac_port)
release_mac = old_smac;
qp->pri.smac = new_smac;
qp->pri.smac_port = port;
qp->pri.smac_index = new_smac_index;
}
unlock:
if (release_mac != MLX4_IB_INVALID_MAC)
mlx4_unregister_mac(ibdev->dev, port, release_mac);
if (qp)
mutex_unlock(&qp->mutex);
mutex_unlock(&ibdev->qp1_proxy_lock[port - 1]);
}
static void mlx4_ib_get_dev_addr(struct net_device *dev,
struct mlx4_ib_dev *ibdev, u8 port)
{
struct in_device *in_dev;
#if IS_ENABLED(CONFIG_IPV6)
struct inet6_dev *in6_dev;
union ib_gid *pgid;
struct inet6_ifaddr *ifp;
union ib_gid default_gid;
#endif
union ib_gid gid;
if ((port == 0) || (port > ibdev->dev->caps.num_ports))
return;
/* IPv4 gids */
in_dev = in_dev_get(dev);
if (in_dev) {
for_ifa(in_dev) {
/*ifa->ifa_address;*/
ipv6_addr_set_v4mapped(ifa->ifa_address,
(struct in6_addr *)&gid);
update_gid_table(ibdev, port, &gid, 0, 0);
}
endfor_ifa(in_dev);
in_dev_put(in_dev);
}
#if IS_ENABLED(CONFIG_IPV6)
mlx4_make_default_gid(dev, &default_gid);
/* IPv6 gids */
in6_dev = in6_dev_get(dev);
if (in6_dev) {
read_lock_bh(&in6_dev->lock);
list_for_each_entry(ifp, &in6_dev->addr_list, if_list) {
pgid = (union ib_gid *)&ifp->addr;
if (!memcmp(pgid, &default_gid, sizeof(*pgid)))
continue;
update_gid_table(ibdev, port, pgid, 0, 0);
}
read_unlock_bh(&in6_dev->lock);
in6_dev_put(in6_dev);
}
#endif
}
static void mlx4_ib_set_default_gid(struct mlx4_ib_dev *ibdev,
struct net_device *dev, u8 port)
{
union ib_gid gid;
mlx4_make_default_gid(dev, &gid);
update_gid_table(ibdev, port, &gid, 0, 1);
}
static int mlx4_ib_init_gid_table(struct mlx4_ib_dev *ibdev)
{
struct net_device *dev;
struct mlx4_ib_iboe *iboe = &ibdev->iboe;
int i;
int err = 0;
for (i = 1; i <= ibdev->num_ports; ++i) {
if (rdma_port_get_link_layer(&ibdev->ib_dev, i) ==
IB_LINK_LAYER_ETHERNET) {
err = reset_gid_table(ibdev, i);
if (err)
goto out;
}
}
read_lock(&dev_base_lock);
spin_lock_bh(&iboe->lock);
for_each_netdev(&init_net, dev) {
u8 port = mlx4_ib_get_dev_port(dev, ibdev);
/* port will be non-zero only for ETH ports */
if (port) {
mlx4_ib_set_default_gid(ibdev, dev, port);
mlx4_ib_get_dev_addr(dev, ibdev, port);
}
}
spin_unlock_bh(&iboe->lock);
read_unlock(&dev_base_lock);
out:
return err;
}
static void mlx4_ib_scan_netdevs(struct mlx4_ib_dev *ibdev,
struct net_device *dev,
unsigned long event)
{
struct mlx4_ib_iboe *iboe;
int update_qps_port = -1;
int port;
iboe = &ibdev->iboe;
spin_lock_bh(&iboe->lock);
mlx4_foreach_ib_transport_port(port, ibdev->dev) {
enum ib_port_state port_state = IB_PORT_NOP;
struct net_device *old_master = iboe->masters[port - 1];
struct net_device *curr_netdev;
struct net_device *curr_master;
iboe->netdevs[port - 1] =
mlx4_get_protocol_dev(ibdev->dev, MLX4_PROT_ETH, port);
if (iboe->netdevs[port - 1])
mlx4_ib_set_default_gid(ibdev,
iboe->netdevs[port - 1], port);
curr_netdev = iboe->netdevs[port - 1];
if (iboe->netdevs[port - 1] &&
netif_is_bond_slave(iboe->netdevs[port - 1])) {
iboe->masters[port - 1] = netdev_master_upper_dev_get(
iboe->netdevs[port - 1]);
} else {
iboe->masters[port - 1] = NULL;
}
curr_master = iboe->masters[port - 1];
if (dev == iboe->netdevs[port - 1] &&
(event == NETDEV_CHANGEADDR || event == NETDEV_REGISTER ||
event == NETDEV_UP || event == NETDEV_CHANGE))
update_qps_port = port;
if (curr_netdev) {
port_state = (netif_running(curr_netdev) && netif_carrier_ok(curr_netdev)) ?
IB_PORT_ACTIVE : IB_PORT_DOWN;
mlx4_ib_set_default_gid(ibdev, curr_netdev, port);
if (curr_master) {
/* if using bonding/team and a slave port is down, we
* don't want the bond IP based gids in the table since
* flows that select port by gid may get the down port.
*/
if (port_state == IB_PORT_DOWN) {
reset_gid_table(ibdev, port);
mlx4_ib_set_default_gid(ibdev,
curr_netdev,
port);
} else {
/* gids from the upper dev (bond/team)
* should appear in port's gid table
*/
mlx4_ib_get_dev_addr(curr_master,
ibdev, port);
}
}
/* if bonding is used it is possible that we add it to
* masters only after IP address is assigned to the
* net bonding interface.
*/
if (curr_master && (old_master != curr_master)) {
reset_gid_table(ibdev, port);
mlx4_ib_set_default_gid(ibdev,
curr_netdev, port);
mlx4_ib_get_dev_addr(curr_master, ibdev, port);
}
if (!curr_master && (old_master != curr_master)) {
reset_gid_table(ibdev, port);
mlx4_ib_set_default_gid(ibdev,
curr_netdev, port);
mlx4_ib_get_dev_addr(curr_netdev, ibdev, port);
}
} else {
reset_gid_table(ibdev, port);
}
}
spin_unlock_bh(&iboe->lock);
if (update_qps_port > 0)
mlx4_ib_update_qps(ibdev, dev, update_qps_port);
}
static int mlx4_ib_netdev_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct mlx4_ib_dev *ibdev;
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
ibdev = container_of(this, struct mlx4_ib_dev, iboe.nb);
mlx4_ib_scan_netdevs(ibdev, dev, event);
return NOTIFY_DONE;
}
static void init_pkeys(struct mlx4_ib_dev *ibdev)
{
int port;
int slave;
int i;
if (mlx4_is_master(ibdev->dev)) {
for (slave = 0; slave <= ibdev->dev->num_vfs; ++slave) {
for (port = 1; port <= ibdev->dev->caps.num_ports; ++port) {
for (i = 0;
i < ibdev->dev->phys_caps.pkey_phys_table_len[port];
++i) {
ibdev->pkeys.virt2phys_pkey[slave][port - 1][i] =
/* master has the identity virt2phys pkey mapping */
(slave == mlx4_master_func_num(ibdev->dev) || !i) ? i :
ibdev->dev->phys_caps.pkey_phys_table_len[port] - 1;
mlx4_sync_pkey_table(ibdev->dev, slave, port, i,
ibdev->pkeys.virt2phys_pkey[slave][port - 1][i]);
}
}
}
/* initialize pkey cache */
for (port = 1; port <= ibdev->dev->caps.num_ports; ++port) {
for (i = 0;
i < ibdev->dev->phys_caps.pkey_phys_table_len[port];
++i)
ibdev->pkeys.phys_pkey_cache[port-1][i] =
(i) ? 0 : 0xFFFF;
}
}
}
static void mlx4_ib_alloc_eqs(struct mlx4_dev *dev, struct mlx4_ib_dev *ibdev)
{
char name[80];
int eq_per_port = 0;
int added_eqs = 0;
int total_eqs = 0;
int i, j, eq;
/* Legacy mode or comp_pool is not large enough */
if (dev->caps.comp_pool == 0 ||
dev->caps.num_ports > dev->caps.comp_pool)
return;
eq_per_port = dev->caps.comp_pool / dev->caps.num_ports;
/* Init eq table */
added_eqs = 0;
mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_IB)
added_eqs += eq_per_port;
total_eqs = dev->caps.num_comp_vectors + added_eqs;
ibdev->eq_table = kzalloc(total_eqs * sizeof(int), GFP_KERNEL);
if (!ibdev->eq_table)
return;
ibdev->eq_added = added_eqs;
eq = 0;
mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_IB) {
for (j = 0; j < eq_per_port; j++) {
snprintf(name, sizeof(name), "mlx4-ib-%d-%d@%s",
i, j, dev->pdev->bus->name);
/* Set IRQ for specific name (per ring) */
if (mlx4_assign_eq(dev, name, NULL,
&ibdev->eq_table[eq])) {
/* Use legacy (same as mlx4_en driver) */
pr_warn("Can't allocate EQ %d; reverting to legacy\n", eq);
ibdev->eq_table[eq] =
(eq % dev->caps.num_comp_vectors);
}
eq++;
}
}
/* Fill the reset of the vector with legacy EQ */
for (i = 0, eq = added_eqs; i < dev->caps.num_comp_vectors; i++)
ibdev->eq_table[eq++] = i;
/* Advertise the new number of EQs to clients */
ibdev->ib_dev.num_comp_vectors = total_eqs;
}
static void mlx4_ib_free_eqs(struct mlx4_dev *dev, struct mlx4_ib_dev *ibdev)
{
int i;
/* no additional eqs were added */
if (!ibdev->eq_table)
return;
/* Reset the advertised EQ number */
ibdev->ib_dev.num_comp_vectors = dev->caps.num_comp_vectors;
/* Free only the added eqs */
for (i = 0; i < ibdev->eq_added; i++) {
/* Don't free legacy eqs if used */
if (ibdev->eq_table[i] <= dev->caps.num_comp_vectors)
continue;
mlx4_release_eq(dev, ibdev->eq_table[i]);
}
kfree(ibdev->eq_table);
}
static void *mlx4_ib_add(struct mlx4_dev *dev)
{
struct mlx4_ib_dev *ibdev;
int num_ports = 0;
int i, j;
int err;
struct mlx4_ib_iboe *iboe;
int ib_num_ports = 0;
pr_info_once("%s", mlx4_ib_version);
num_ports = 0;
mlx4_foreach_ib_transport_port(i, dev)
num_ports++;
/* No point in registering a device with no ports... */
if (num_ports == 0)
return NULL;
ibdev = (struct mlx4_ib_dev *) ib_alloc_device(sizeof *ibdev);
if (!ibdev) {
dev_err(&dev->pdev->dev, "Device struct alloc failed\n");
return NULL;
}
iboe = &ibdev->iboe;
if (mlx4_pd_alloc(dev, &ibdev->priv_pdn))
goto err_dealloc;
if (mlx4_uar_alloc(dev, &ibdev->priv_uar))
goto err_pd;
ibdev->uar_map = ioremap((phys_addr_t) ibdev->priv_uar.pfn << PAGE_SHIFT,
PAGE_SIZE);
if (!ibdev->uar_map)
goto err_uar;
MLX4_INIT_DOORBELL_LOCK(&ibdev->uar_lock);
ibdev->dev = dev;
strlcpy(ibdev->ib_dev.name, "mlx4_%d", IB_DEVICE_NAME_MAX);
ibdev->ib_dev.owner = THIS_MODULE;
ibdev->ib_dev.node_type = RDMA_NODE_IB_CA;
ibdev->ib_dev.local_dma_lkey = dev->caps.reserved_lkey;
ibdev->num_ports = num_ports;
ibdev->ib_dev.phys_port_cnt = ibdev->num_ports;
ibdev->ib_dev.num_comp_vectors = dev->caps.num_comp_vectors;
ibdev->ib_dev.dma_device = &dev->pdev->dev;
if (dev->caps.userspace_caps)
ibdev->ib_dev.uverbs_abi_ver = MLX4_IB_UVERBS_ABI_VERSION;
else
ibdev->ib_dev.uverbs_abi_ver = MLX4_IB_UVERBS_NO_DEV_CAPS_ABI_VERSION;
ibdev->ib_dev.uverbs_cmd_mask =
(1ull << IB_USER_VERBS_CMD_GET_CONTEXT) |
(1ull << IB_USER_VERBS_CMD_QUERY_DEVICE) |
(1ull << IB_USER_VERBS_CMD_QUERY_PORT) |
(1ull << IB_USER_VERBS_CMD_ALLOC_PD) |
(1ull << IB_USER_VERBS_CMD_DEALLOC_PD) |
(1ull << IB_USER_VERBS_CMD_REG_MR) |
(1ull << IB_USER_VERBS_CMD_REREG_MR) |
(1ull << IB_USER_VERBS_CMD_DEREG_MR) |
(1ull << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) |
(1ull << IB_USER_VERBS_CMD_CREATE_CQ) |
(1ull << IB_USER_VERBS_CMD_RESIZE_CQ) |
(1ull << IB_USER_VERBS_CMD_DESTROY_CQ) |
(1ull << IB_USER_VERBS_CMD_CREATE_QP) |
(1ull << IB_USER_VERBS_CMD_MODIFY_QP) |
(1ull << IB_USER_VERBS_CMD_QUERY_QP) |
(1ull << IB_USER_VERBS_CMD_DESTROY_QP) |
(1ull << IB_USER_VERBS_CMD_ATTACH_MCAST) |
(1ull << IB_USER_VERBS_CMD_DETACH_MCAST) |
(1ull << IB_USER_VERBS_CMD_CREATE_SRQ) |
(1ull << IB_USER_VERBS_CMD_MODIFY_SRQ) |
(1ull << IB_USER_VERBS_CMD_QUERY_SRQ) |
(1ull << IB_USER_VERBS_CMD_DESTROY_SRQ) |
(1ull << IB_USER_VERBS_CMD_CREATE_XSRQ) |
(1ull << IB_USER_VERBS_CMD_OPEN_QP);
ibdev->ib_dev.query_device = mlx4_ib_query_device;
ibdev->ib_dev.query_port = mlx4_ib_query_port;
ibdev->ib_dev.get_link_layer = mlx4_ib_port_link_layer;
ibdev->ib_dev.query_gid = mlx4_ib_query_gid;
ibdev->ib_dev.query_pkey = mlx4_ib_query_pkey;
ibdev->ib_dev.modify_device = mlx4_ib_modify_device;
ibdev->ib_dev.modify_port = mlx4_ib_modify_port;
ibdev->ib_dev.alloc_ucontext = mlx4_ib_alloc_ucontext;
ibdev->ib_dev.dealloc_ucontext = mlx4_ib_dealloc_ucontext;
ibdev->ib_dev.mmap = mlx4_ib_mmap;
ibdev->ib_dev.alloc_pd = mlx4_ib_alloc_pd;
ibdev->ib_dev.dealloc_pd = mlx4_ib_dealloc_pd;
ibdev->ib_dev.create_ah = mlx4_ib_create_ah;
ibdev->ib_dev.query_ah = mlx4_ib_query_ah;
ibdev->ib_dev.destroy_ah = mlx4_ib_destroy_ah;
ibdev->ib_dev.create_srq = mlx4_ib_create_srq;
ibdev->ib_dev.modify_srq = mlx4_ib_modify_srq;
ibdev->ib_dev.query_srq = mlx4_ib_query_srq;
ibdev->ib_dev.destroy_srq = mlx4_ib_destroy_srq;
ibdev->ib_dev.post_srq_recv = mlx4_ib_post_srq_recv;
ibdev->ib_dev.create_qp = mlx4_ib_create_qp;
ibdev->ib_dev.modify_qp = mlx4_ib_modify_qp;
ibdev->ib_dev.query_qp = mlx4_ib_query_qp;
ibdev->ib_dev.destroy_qp = mlx4_ib_destroy_qp;
ibdev->ib_dev.post_send = mlx4_ib_post_send;
ibdev->ib_dev.post_recv = mlx4_ib_post_recv;
ibdev->ib_dev.create_cq = mlx4_ib_create_cq;
ibdev->ib_dev.modify_cq = mlx4_ib_modify_cq;
ibdev->ib_dev.resize_cq = mlx4_ib_resize_cq;
ibdev->ib_dev.destroy_cq = mlx4_ib_destroy_cq;
ibdev->ib_dev.poll_cq = mlx4_ib_poll_cq;
ibdev->ib_dev.req_notify_cq = mlx4_ib_arm_cq;
ibdev->ib_dev.get_dma_mr = mlx4_ib_get_dma_mr;
ibdev->ib_dev.reg_user_mr = mlx4_ib_reg_user_mr;
ibdev->ib_dev.rereg_user_mr = mlx4_ib_rereg_user_mr;
ibdev->ib_dev.dereg_mr = mlx4_ib_dereg_mr;
ibdev->ib_dev.alloc_fast_reg_mr = mlx4_ib_alloc_fast_reg_mr;
ibdev->ib_dev.alloc_fast_reg_page_list = mlx4_ib_alloc_fast_reg_page_list;
ibdev->ib_dev.free_fast_reg_page_list = mlx4_ib_free_fast_reg_page_list;
ibdev->ib_dev.attach_mcast = mlx4_ib_mcg_attach;
ibdev->ib_dev.detach_mcast = mlx4_ib_mcg_detach;
ibdev->ib_dev.process_mad = mlx4_ib_process_mad;
if (!mlx4_is_slave(ibdev->dev)) {
ibdev->ib_dev.alloc_fmr = mlx4_ib_fmr_alloc;
ibdev->ib_dev.map_phys_fmr = mlx4_ib_map_phys_fmr;
ibdev->ib_dev.unmap_fmr = mlx4_ib_unmap_fmr;
ibdev->ib_dev.dealloc_fmr = mlx4_ib_fmr_dealloc;
}
if (dev->caps.flags & MLX4_DEV_CAP_FLAG_MEM_WINDOW ||
dev->caps.bmme_flags & MLX4_BMME_FLAG_TYPE_2_WIN) {
ibdev->ib_dev.alloc_mw = mlx4_ib_alloc_mw;
ibdev->ib_dev.bind_mw = mlx4_ib_bind_mw;
ibdev->ib_dev.dealloc_mw = mlx4_ib_dealloc_mw;
ibdev->ib_dev.uverbs_cmd_mask |=
(1ull << IB_USER_VERBS_CMD_ALLOC_MW) |
(1ull << IB_USER_VERBS_CMD_DEALLOC_MW);
}
if (dev->caps.flags & MLX4_DEV_CAP_FLAG_XRC) {
ibdev->ib_dev.alloc_xrcd = mlx4_ib_alloc_xrcd;
ibdev->ib_dev.dealloc_xrcd = mlx4_ib_dealloc_xrcd;
ibdev->ib_dev.uverbs_cmd_mask |=
(1ull << IB_USER_VERBS_CMD_OPEN_XRCD) |
(1ull << IB_USER_VERBS_CMD_CLOSE_XRCD);
}
if (check_flow_steering_support(dev)) {
ibdev->steering_support = MLX4_STEERING_MODE_DEVICE_MANAGED;
ibdev->ib_dev.create_flow = mlx4_ib_create_flow;
ibdev->ib_dev.destroy_flow = mlx4_ib_destroy_flow;
ibdev->ib_dev.uverbs_ex_cmd_mask |=
(1ull << IB_USER_VERBS_EX_CMD_CREATE_FLOW) |
(1ull << IB_USER_VERBS_EX_CMD_DESTROY_FLOW);
}
mlx4_ib_alloc_eqs(dev, ibdev);
spin_lock_init(&iboe->lock);
if (init_node_data(ibdev))
goto err_map;
for (i = 0; i < ibdev->num_ports; ++i) {
mutex_init(&ibdev->qp1_proxy_lock[i]);
if (mlx4_ib_port_link_layer(&ibdev->ib_dev, i + 1) ==
IB_LINK_LAYER_ETHERNET) {
err = mlx4_counter_alloc(ibdev->dev, &ibdev->counters[i]);
if (err)
ibdev->counters[i] = -1;
} else {
ibdev->counters[i] = -1;
}
}
mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_IB)
ib_num_ports++;
spin_lock_init(&ibdev->sm_lock);
mutex_init(&ibdev->cap_mask_mutex);
if (ibdev->steering_support == MLX4_STEERING_MODE_DEVICE_MANAGED &&
ib_num_ports) {
ibdev->steer_qpn_count = MLX4_IB_UC_MAX_NUM_QPS;
err = mlx4_qp_reserve_range(dev, ibdev->steer_qpn_count,
MLX4_IB_UC_STEER_QPN_ALIGN,
&ibdev->steer_qpn_base, 0);
if (err)
goto err_counter;
ibdev->ib_uc_qpns_bitmap =
kmalloc(BITS_TO_LONGS(ibdev->steer_qpn_count) *
sizeof(long),
GFP_KERNEL);
if (!ibdev->ib_uc_qpns_bitmap) {
dev_err(&dev->pdev->dev, "bit map alloc failed\n");
goto err_steer_qp_release;
}
bitmap_zero(ibdev->ib_uc_qpns_bitmap, ibdev->steer_qpn_count);
err = mlx4_FLOW_STEERING_IB_UC_QP_RANGE(
dev, ibdev->steer_qpn_base,
ibdev->steer_qpn_base +
ibdev->steer_qpn_count - 1);
if (err)
goto err_steer_free_bitmap;
}
for (j = 1; j <= ibdev->dev->caps.num_ports; j++)
atomic64_set(&iboe->mac[j - 1], ibdev->dev->caps.def_mac[j]);
if (ib_register_device(&ibdev->ib_dev, NULL))
goto err_steer_free_bitmap;
if (mlx4_ib_mad_init(ibdev))
goto err_reg;
if (mlx4_ib_init_sriov(ibdev))
goto err_mad;
if (dev->caps.flags & MLX4_DEV_CAP_FLAG_IBOE) {
if (!iboe->nb.notifier_call) {
iboe->nb.notifier_call = mlx4_ib_netdev_event;
err = register_netdevice_notifier(&iboe->nb);
if (err) {
iboe->nb.notifier_call = NULL;
goto err_notif;
}
}
if (!iboe->nb_inet.notifier_call) {
iboe->nb_inet.notifier_call = mlx4_ib_inet_event;
err = register_inetaddr_notifier(&iboe->nb_inet);
if (err) {
iboe->nb_inet.notifier_call = NULL;
goto err_notif;
}
}
#if IS_ENABLED(CONFIG_IPV6)
if (!iboe->nb_inet6.notifier_call) {
iboe->nb_inet6.notifier_call = mlx4_ib_inet6_event;
err = register_inet6addr_notifier(&iboe->nb_inet6);
if (err) {
iboe->nb_inet6.notifier_call = NULL;
goto err_notif;
}
}
#endif
if (mlx4_ib_init_gid_table(ibdev))
goto err_notif;
}
for (j = 0; j < ARRAY_SIZE(mlx4_class_attributes); ++j) {
if (device_create_file(&ibdev->ib_dev.dev,
mlx4_class_attributes[j]))
goto err_notif;
}
ibdev->ib_active = true;
if (mlx4_is_mfunc(ibdev->dev))
init_pkeys(ibdev);
/* create paravirt contexts for any VFs which are active */
if (mlx4_is_master(ibdev->dev)) {
for (j = 0; j < MLX4_MFUNC_MAX; j++) {
if (j == mlx4_master_func_num(ibdev->dev))
continue;
if (mlx4_is_slave_active(ibdev->dev, j))
do_slave_init(ibdev, j, 1);
}
}
return ibdev;
err_notif:
if (ibdev->iboe.nb.notifier_call) {
if (unregister_netdevice_notifier(&ibdev->iboe.nb))
pr_warn("failure unregistering notifier\n");
ibdev->iboe.nb.notifier_call = NULL;
}
if (ibdev->iboe.nb_inet.notifier_call) {
if (unregister_inetaddr_notifier(&ibdev->iboe.nb_inet))
pr_warn("failure unregistering notifier\n");
ibdev->iboe.nb_inet.notifier_call = NULL;
}
#if IS_ENABLED(CONFIG_IPV6)
if (ibdev->iboe.nb_inet6.notifier_call) {
if (unregister_inet6addr_notifier(&ibdev->iboe.nb_inet6))
pr_warn("failure unregistering notifier\n");
ibdev->iboe.nb_inet6.notifier_call = NULL;
}
#endif
flush_workqueue(wq);
mlx4_ib_close_sriov(ibdev);
err_mad:
mlx4_ib_mad_cleanup(ibdev);
err_reg:
ib_unregister_device(&ibdev->ib_dev);
err_steer_free_bitmap:
kfree(ibdev->ib_uc_qpns_bitmap);
err_steer_qp_release:
if (ibdev->steering_support == MLX4_STEERING_MODE_DEVICE_MANAGED)
mlx4_qp_release_range(dev, ibdev->steer_qpn_base,
ibdev->steer_qpn_count);
err_counter:
for (; i; --i)
if (ibdev->counters[i - 1] != -1)
mlx4_counter_free(ibdev->dev, ibdev->counters[i - 1]);
err_map:
iounmap(ibdev->uar_map);
err_uar:
mlx4_uar_free(dev, &ibdev->priv_uar);
err_pd:
mlx4_pd_free(dev, ibdev->priv_pdn);
err_dealloc:
ib_dealloc_device(&ibdev->ib_dev);
return NULL;
}
int mlx4_ib_steer_qp_alloc(struct mlx4_ib_dev *dev, int count, int *qpn)
{
int offset;
WARN_ON(!dev->ib_uc_qpns_bitmap);
offset = bitmap_find_free_region(dev->ib_uc_qpns_bitmap,
dev->steer_qpn_count,
get_count_order(count));
if (offset < 0)
return offset;
*qpn = dev->steer_qpn_base + offset;
return 0;
}
void mlx4_ib_steer_qp_free(struct mlx4_ib_dev *dev, u32 qpn, int count)
{
if (!qpn ||
dev->steering_support != MLX4_STEERING_MODE_DEVICE_MANAGED)
return;
BUG_ON(qpn < dev->steer_qpn_base);
bitmap_release_region(dev->ib_uc_qpns_bitmap,
qpn - dev->steer_qpn_base,
get_count_order(count));
}
int mlx4_ib_steer_qp_reg(struct mlx4_ib_dev *mdev, struct mlx4_ib_qp *mqp,
int is_attach)
{
int err;
size_t flow_size;
struct ib_flow_attr *flow = NULL;
struct ib_flow_spec_ib *ib_spec;
if (is_attach) {
flow_size = sizeof(struct ib_flow_attr) +
sizeof(struct ib_flow_spec_ib);
flow = kzalloc(flow_size, GFP_KERNEL);
if (!flow)
return -ENOMEM;
flow->port = mqp->port;
flow->num_of_specs = 1;
flow->size = flow_size;
ib_spec = (struct ib_flow_spec_ib *)(flow + 1);
ib_spec->type = IB_FLOW_SPEC_IB;
ib_spec->size = sizeof(struct ib_flow_spec_ib);
/* Add an empty rule for IB L2 */
memset(&ib_spec->mask, 0, sizeof(ib_spec->mask));
err = __mlx4_ib_create_flow(&mqp->ibqp, flow,
IB_FLOW_DOMAIN_NIC,
MLX4_FS_REGULAR,
&mqp->reg_id);
} else {
err = __mlx4_ib_destroy_flow(mdev->dev, mqp->reg_id);
}
kfree(flow);
return err;
}
static void mlx4_ib_remove(struct mlx4_dev *dev, void *ibdev_ptr)
{
struct mlx4_ib_dev *ibdev = ibdev_ptr;
int p;
ibdev->ib_active = false;
flush_workqueue(wq);
mlx4_ib_close_sriov(ibdev);
mlx4_ib_mad_cleanup(ibdev);
ib_unregister_device(&ibdev->ib_dev);
if (ibdev->iboe.nb.notifier_call) {
if (unregister_netdevice_notifier(&ibdev->iboe.nb))
pr_warn("failure unregistering notifier\n");
ibdev->iboe.nb.notifier_call = NULL;
}
if (ibdev->steering_support == MLX4_STEERING_MODE_DEVICE_MANAGED) {
mlx4_qp_release_range(dev, ibdev->steer_qpn_base,
ibdev->steer_qpn_count);
kfree(ibdev->ib_uc_qpns_bitmap);
}
if (ibdev->iboe.nb_inet.notifier_call) {
if (unregister_inetaddr_notifier(&ibdev->iboe.nb_inet))
pr_warn("failure unregistering notifier\n");
ibdev->iboe.nb_inet.notifier_call = NULL;
}
#if IS_ENABLED(CONFIG_IPV6)
if (ibdev->iboe.nb_inet6.notifier_call) {
if (unregister_inet6addr_notifier(&ibdev->iboe.nb_inet6))
pr_warn("failure unregistering notifier\n");
ibdev->iboe.nb_inet6.notifier_call = NULL;
}
#endif
iounmap(ibdev->uar_map);
for (p = 0; p < ibdev->num_ports; ++p)
if (ibdev->counters[p] != -1)
mlx4_counter_free(ibdev->dev, ibdev->counters[p]);
mlx4_foreach_port(p, dev, MLX4_PORT_TYPE_IB)
mlx4_CLOSE_PORT(dev, p);
mlx4_ib_free_eqs(dev, ibdev);
mlx4_uar_free(dev, &ibdev->priv_uar);
mlx4_pd_free(dev, ibdev->priv_pdn);
ib_dealloc_device(&ibdev->ib_dev);
}
static void do_slave_init(struct mlx4_ib_dev *ibdev, int slave, int do_init)
{
struct mlx4_ib_demux_work **dm = NULL;
struct mlx4_dev *dev = ibdev->dev;
int i;
unsigned long flags;
struct mlx4_active_ports actv_ports;
unsigned int ports;
unsigned int first_port;
if (!mlx4_is_master(dev))
return;
actv_ports = mlx4_get_active_ports(dev, slave);
ports = bitmap_weight(actv_ports.ports, dev->caps.num_ports);
first_port = find_first_bit(actv_ports.ports, dev->caps.num_ports);
dm = kcalloc(ports, sizeof(*dm), GFP_ATOMIC);
if (!dm) {
pr_err("failed to allocate memory for tunneling qp update\n");
goto out;
}
for (i = 0; i < ports; i++) {
dm[i] = kmalloc(sizeof (struct mlx4_ib_demux_work), GFP_ATOMIC);
if (!dm[i]) {
pr_err("failed to allocate memory for tunneling qp update work struct\n");
for (i = 0; i < dev->caps.num_ports; i++) {
if (dm[i])
kfree(dm[i]);
}
goto out;
}
}
/* initialize or tear down tunnel QPs for the slave */
for (i = 0; i < ports; i++) {
INIT_WORK(&dm[i]->work, mlx4_ib_tunnels_update_work);
dm[i]->port = first_port + i + 1;
dm[i]->slave = slave;
dm[i]->do_init = do_init;
dm[i]->dev = ibdev;
spin_lock_irqsave(&ibdev->sriov.going_down_lock, flags);
if (!ibdev->sriov.is_going_down)
queue_work(ibdev->sriov.demux[i].ud_wq, &dm[i]->work);
spin_unlock_irqrestore(&ibdev->sriov.going_down_lock, flags);
}
out:
kfree(dm);
return;
}
static void mlx4_ib_event(struct mlx4_dev *dev, void *ibdev_ptr,
enum mlx4_dev_event event, unsigned long param)
{
struct ib_event ibev;
struct mlx4_ib_dev *ibdev = to_mdev((struct ib_device *) ibdev_ptr);
struct mlx4_eqe *eqe = NULL;
struct ib_event_work *ew;
int p = 0;
if (event == MLX4_DEV_EVENT_PORT_MGMT_CHANGE)
eqe = (struct mlx4_eqe *)param;
else
p = (int) param;
switch (event) {
case MLX4_DEV_EVENT_PORT_UP:
if (p > ibdev->num_ports)
return;
if (mlx4_is_master(dev) &&
rdma_port_get_link_layer(&ibdev->ib_dev, p) ==
IB_LINK_LAYER_INFINIBAND) {
mlx4_ib_invalidate_all_guid_record(ibdev, p);
}
ibev.event = IB_EVENT_PORT_ACTIVE;
break;
case MLX4_DEV_EVENT_PORT_DOWN:
if (p > ibdev->num_ports)
return;
ibev.event = IB_EVENT_PORT_ERR;
break;
case MLX4_DEV_EVENT_CATASTROPHIC_ERROR:
ibdev->ib_active = false;
ibev.event = IB_EVENT_DEVICE_FATAL;
break;
case MLX4_DEV_EVENT_PORT_MGMT_CHANGE:
ew = kmalloc(sizeof *ew, GFP_ATOMIC);
if (!ew) {
pr_err("failed to allocate memory for events work\n");
break;
}
INIT_WORK(&ew->work, handle_port_mgmt_change_event);
memcpy(&ew->ib_eqe, eqe, sizeof *eqe);
ew->ib_dev = ibdev;
/* need to queue only for port owner, which uses GEN_EQE */
if (mlx4_is_master(dev))
queue_work(wq, &ew->work);
else
handle_port_mgmt_change_event(&ew->work);
return;
case MLX4_DEV_EVENT_SLAVE_INIT:
/* here, p is the slave id */
do_slave_init(ibdev, p, 1);
return;
case MLX4_DEV_EVENT_SLAVE_SHUTDOWN:
/* here, p is the slave id */
do_slave_init(ibdev, p, 0);
return;
default:
return;
}
ibev.device = ibdev_ptr;
ibev.element.port_num = (u8) p;
ib_dispatch_event(&ibev);
}
static struct mlx4_interface mlx4_ib_interface = {
.add = mlx4_ib_add,
.remove = mlx4_ib_remove,
.event = mlx4_ib_event,
.protocol = MLX4_PROT_IB_IPV6
};
static int __init mlx4_ib_init(void)
{
int err;
wq = create_singlethread_workqueue("mlx4_ib");
if (!wq)
return -ENOMEM;
err = mlx4_ib_mcg_init();
if (err)
goto clean_wq;
err = mlx4_register_interface(&mlx4_ib_interface);
if (err)
goto clean_mcg;
return 0;
clean_mcg:
mlx4_ib_mcg_destroy();
clean_wq:
destroy_workqueue(wq);
return err;
}
static void __exit mlx4_ib_cleanup(void)
{
mlx4_unregister_interface(&mlx4_ib_interface);
mlx4_ib_mcg_destroy();
destroy_workqueue(wq);
}
module_init(mlx4_ib_init);
module_exit(mlx4_ib_cleanup);
| gpl-2.0 |
bright-pan/smartlock2 | bsp/xplorer4330/libraries/lpc_ip/ssp_001.c | 8 | 5071 | /*
* @brief SSP Registers and control functions
*
* @note
* Copyright(C) NXP Semiconductors, 2012
* All rights reserved.
*
* @par
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* LPC products. This software is supplied "AS IS" without any warranties of
* any kind, and NXP Semiconductors and its licensor disclaim any and
* all warranties, express or implied, including all implied warranties of
* merchantability, fitness for a particular purpose and non-infringement of
* intellectual property rights. NXP Semiconductors assumes no responsibility
* or liability for the use of the software, conveys no license or rights under any
* patent, copyright, mask work right, or any other intellectual property rights in
* or to any products. NXP Semiconductors reserves the right to make changes
* in the software without notification. NXP Semiconductors also makes no
* representation or warranty that such application will be suitable for the
* specified use without further testing or modification.
*
* @par
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, under NXP Semiconductors' and its
* licensor's relevant copyrights in the software, without fee, provided that it
* is used in conjunction with NXP Semiconductors microcontrollers. This
* copyright, permission, and disclaimer notice must appear in all copies of
* this code.
*/
#include "ssp_001.h"
/*****************************************************************************
* Private types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Public types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Private functions
****************************************************************************/
/*****************************************************************************
* Public functions
****************************************************************************/
/*Set up output clocks per bit for SSP bus*/
void IP_SSP_Set_ClockRate(IP_SSP_001_Type *pSSP, uint32_t clk_rate, uint32_t prescale)
{
pSSP->CR0 &= ~(SSP_CR0_SCR(0xFF));
pSSP->CR0 |= SSP_CR0_SCR(clk_rate);
pSSP->CPSR = prescale;
}
/* Set up the SSP frame format */
void IP_SSP_Set_Format(IP_SSP_001_Type *pSSP, uint32_t bits, uint32_t frameFormat, uint32_t clockFormat)
{
pSSP->CR0 = (pSSP->CR0 & ~0xFF) | bits | frameFormat | clockFormat;
}
/* Set the SSP working as master or slave mode */
void IP_SSP_Set_Mode(IP_SSP_001_Type *pSSP, uint32_t mode)
{
pSSP->CR1 = (pSSP->CR1 & ~(1 << 2)) | mode;
}
/* Disable SSP operation */
void IP_SSP_DeInit(IP_SSP_001_Type *pSSP)
{
pSSP->CR1 &= (~SSP_CR1_SSP_EN) & SSP_CR1_BITMASK;
}
/* Enable/Disable SSP operation */
void IP_SSP_Cmd(IP_SSP_001_Type *pSSP, FunctionalState NewState)
{
if (NewState == ENABLE) {
pSSP->CR1 |= SSP_CR1_SSP_EN;
}
else {
pSSP->CR1 &= (~SSP_CR1_SSP_EN) & SSP_CR1_BITMASK;
}
}
/* Send SSP 16-bit data */
void IP_SSP_SendFrame(IP_SSP_001_Type *pSSP, uint16_t tx_data)
{
pSSP->DR = SSP_DR_BITMASK(tx_data);
}
/* Get received SSP data */
uint16_t IP_SSP_ReceiveFrame(IP_SSP_001_Type *pSSP)
{
return (uint16_t) (SSP_DR_BITMASK(pSSP->DR));
}
/* Enable/Disable loopback mode */
void IP_SSP_LoopBackCmd(IP_SSP_001_Type *pSSP, FunctionalState NewState)
{
if (NewState == ENABLE) {
pSSP->CR1 |= SSP_CR1_LBM_EN;
}
else {
pSSP->CR1 &= (~SSP_CR1_LBM_EN) & SSP_CR1_BITMASK;
}
}
/* Get the raw interrupt status */
IntStatus IP_SSP_GetRawIntStatus(IP_SSP_001_Type *pSSP, SSP_Raw_Int_Status_Type RawInt)
{
return (pSSP->RIS & RawInt) ? SET : RESET;
}
/* Get the masked interrupt status */
uint32_t IP_SSP_GetIntStatus(IP_SSP_001_Type *pSSP)
{
return pSSP->MIS;
}
/* Clear the corresponding interrupt condition(s) in the SSP controller */
void IP_SSP_ClearIntPending(IP_SSP_001_Type *pSSP, SSP_Int_Clear_Type IntClear)
{
pSSP->ICR = IntClear;
}
/* Get the current status of SSP controller */
FlagStatus IP_SSP_GetStatus(IP_SSP_001_Type *pSSP, SSP_Status_Type Stat)
{
return (pSSP->SR & Stat) ? SET : RESET;
}
/* Get the number of bits transferred in each frame */
uint8_t IP_SSP_GetDataSize(IP_SSP_001_Type *pSSP)
{
return SSP_CR0_DSS(pSSP->CR0);
}
/* Enable/Disable interrupt for the SSP */
void IP_SSP_Int_Enable(IP_SSP_001_Type *pSSP, SSP_Int_Mask_Type IntType, FunctionalState NewState)
{
if (NewState == ENABLE) {
pSSP->IMSC |= IntType;
}
else {
pSSP->IMSC &= (~IntType);
}
}
/* Enable/Disable DMA for SSP */
void IP_SSP_DMA_Cmd(IP_SSP_001_Type *pSSP, SSP_DMA_Type ssp_dma_t, FunctionalState NewState)
{
#if !defined(CHIP_LPC111X_CXX) && !defined(CHIP_LPC11UXX)
if (NewState == ENABLE) {
pSSP->DMACR |= ssp_dma_t;
}
else {
pSSP->DMACR &= (~ssp_dma_t);
}
#endif
}
| gpl-2.0 |
qiyao/gdb | gdb/nios2-tdep.c | 8 | 47833 | /* Target-machine dependent code for Nios II, for GDB.
Copyright (C) 2012-2014 Free Software Foundation, Inc.
Contributed by Peter Brookes (pbrookes@altera.com)
and Andrew Draper (adraper@altera.com).
Contributed by Mentor Graphics, Inc.
This file is part of GDB.
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; either version 3 of the License, or
(at your option) any later version.
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, see <http://www.gnu.org/licenses/>. */
#include "defs.h"
#include "frame.h"
#include "frame-unwind.h"
#include "frame-base.h"
#include "trad-frame.h"
#include "dwarf2-frame.h"
#include "symtab.h"
#include "inferior.h"
#include "gdbtypes.h"
#include "gdbcore.h"
#include "gdbcmd.h"
#include "osabi.h"
#include "target.h"
#include "dis-asm.h"
#include "regcache.h"
#include "value.h"
#include "symfile.h"
#include "arch-utils.h"
#include "floatformat.h"
#include "gdb_assert.h"
#include "infcall.h"
#include "regset.h"
#include "target-descriptions.h"
/* To get entry_point_address. */
#include "objfiles.h"
/* Nios II ISA specific encodings and macros. */
#include "opcode/nios2.h"
/* Nios II specific header. */
#include "nios2-tdep.h"
#include "features/nios2.c"
/* Control debugging information emitted in this file. */
static int nios2_debug = 0;
/* The following structures are used in the cache for prologue
analysis; see the reg_value and reg_saved tables in
struct nios2_unwind_cache, respectively. */
/* struct reg_value is used to record that a register has the same value
as reg at the given offset from the start of a function. */
struct reg_value
{
int reg;
unsigned int offset;
};
/* struct reg_saved is used to record that a register value has been saved at
basereg + addr, for basereg >= 0. If basereg < 0, that indicates
that the register is not known to have been saved. Note that when
basereg == NIOS2_Z_REGNUM (that is, r0, which holds value 0),
addr is an absolute address. */
struct reg_saved
{
int basereg;
CORE_ADDR addr;
};
struct nios2_unwind_cache
{
/* The frame's base, optionally used by the high-level debug info. */
CORE_ADDR base;
/* The previous frame's inner most stack address. Used as this
frame ID's stack_addr. */
CORE_ADDR cfa;
/* The address of the first instruction in this function. */
CORE_ADDR pc;
/* Which register holds the return address for the frame. */
int return_regnum;
/* Table indicating what changes have been made to each register. */
struct reg_value reg_value[NIOS2_NUM_REGS];
/* Table indicating where each register has been saved. */
struct reg_saved reg_saved[NIOS2_NUM_REGS];
};
/* This array is a mapping from Dwarf-2 register numbering to GDB's. */
static int nios2_dwarf2gdb_regno_map[] =
{
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15,
16, 17, 18, 19,
20, 21, 22, 23,
24, 25,
NIOS2_GP_REGNUM, /* 26 */
NIOS2_SP_REGNUM, /* 27 */
NIOS2_FP_REGNUM, /* 28 */
NIOS2_EA_REGNUM, /* 29 */
NIOS2_BA_REGNUM, /* 30 */
NIOS2_RA_REGNUM, /* 31 */
NIOS2_PC_REGNUM, /* 32 */
NIOS2_STATUS_REGNUM, /* 33 */
NIOS2_ESTATUS_REGNUM, /* 34 */
NIOS2_BSTATUS_REGNUM, /* 35 */
NIOS2_IENABLE_REGNUM, /* 36 */
NIOS2_IPENDING_REGNUM, /* 37 */
NIOS2_CPUID_REGNUM, /* 38 */
39, /* CTL6 */ /* 39 */
NIOS2_EXCEPTION_REGNUM, /* 40 */
NIOS2_PTEADDR_REGNUM, /* 41 */
NIOS2_TLBACC_REGNUM, /* 42 */
NIOS2_TLBMISC_REGNUM, /* 43 */
NIOS2_ECCINJ_REGNUM, /* 44 */
NIOS2_BADADDR_REGNUM, /* 45 */
NIOS2_CONFIG_REGNUM, /* 46 */
NIOS2_MPUBASE_REGNUM, /* 47 */
NIOS2_MPUACC_REGNUM /* 48 */
};
/* Implement the dwarf2_reg_to_regnum gdbarch method. */
static int
nios2_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int dw_reg)
{
if (dw_reg < 0 || dw_reg > NIOS2_NUM_REGS)
{
warning (_("Dwarf-2 uses unmapped register #%d"), dw_reg);
return dw_reg;
}
return nios2_dwarf2gdb_regno_map[dw_reg];
}
/* Canonical names for the 49 registers. */
static const char *const nios2_reg_names[NIOS2_NUM_REGS] =
{
"zero", "at", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
"et", "bt", "gp", "sp", "fp", "ea", "sstatus", "ra",
"pc",
"status", "estatus", "bstatus", "ienable",
"ipending", "cpuid", "ctl6", "exception",
"pteaddr", "tlbacc", "tlbmisc", "eccinj",
"badaddr", "config", "mpubase", "mpuacc"
};
/* Implement the register_name gdbarch method. */
static const char *
nios2_register_name (struct gdbarch *gdbarch, int regno)
{
/* Use mnemonic aliases for GPRs. */
if (regno >= 0 && regno < NIOS2_NUM_REGS)
return nios2_reg_names[regno];
else
return tdesc_register_name (gdbarch, regno);
}
/* Implement the register_type gdbarch method. */
static struct type *
nios2_register_type (struct gdbarch *gdbarch, int regno)
{
/* If the XML description has register information, use that to
determine the register type. */
if (tdesc_has_registers (gdbarch_target_desc (gdbarch)))
return tdesc_register_type (gdbarch, regno);
if (regno == NIOS2_PC_REGNUM)
return builtin_type (gdbarch)->builtin_func_ptr;
else if (regno == NIOS2_SP_REGNUM)
return builtin_type (gdbarch)->builtin_data_ptr;
else
return builtin_type (gdbarch)->builtin_uint32;
}
/* Given a return value in REGCACHE with a type VALTYPE,
extract and copy its value into VALBUF. */
static void
nios2_extract_return_value (struct gdbarch *gdbarch, struct type *valtype,
struct regcache *regcache, gdb_byte *valbuf)
{
int len = TYPE_LENGTH (valtype);
/* Return values of up to 8 bytes are returned in $r2 $r3. */
if (len <= register_size (gdbarch, NIOS2_R2_REGNUM))
regcache_cooked_read (regcache, NIOS2_R2_REGNUM, valbuf);
else
{
gdb_assert (len <= (register_size (gdbarch, NIOS2_R2_REGNUM)
+ register_size (gdbarch, NIOS2_R3_REGNUM)));
regcache_cooked_read (regcache, NIOS2_R2_REGNUM, valbuf);
regcache_cooked_read (regcache, NIOS2_R3_REGNUM, valbuf + 4);
}
}
/* Write into appropriate registers a function return value
of type TYPE, given in virtual format. */
static void
nios2_store_return_value (struct gdbarch *gdbarch, struct type *valtype,
struct regcache *regcache, const gdb_byte *valbuf)
{
int len = TYPE_LENGTH (valtype);
/* Return values of up to 8 bytes are returned in $r2 $r3. */
if (len <= register_size (gdbarch, NIOS2_R2_REGNUM))
regcache_cooked_write (regcache, NIOS2_R2_REGNUM, valbuf);
else
{
gdb_assert (len <= (register_size (gdbarch, NIOS2_R2_REGNUM)
+ register_size (gdbarch, NIOS2_R3_REGNUM)));
regcache_cooked_write (regcache, NIOS2_R2_REGNUM, valbuf);
regcache_cooked_write (regcache, NIOS2_R3_REGNUM, valbuf + 4);
}
}
/* Set up the default values of the registers. */
static void
nios2_setup_default (struct nios2_unwind_cache *cache)
{
int i;
for (i = 0; i < NIOS2_NUM_REGS; i++)
{
/* All registers start off holding their previous values. */
cache->reg_value[i].reg = i;
cache->reg_value[i].offset = 0;
/* All registers start off not saved. */
cache->reg_saved[i].basereg = -1;
cache->reg_saved[i].addr = 0;
}
}
/* Initialize the unwind cache. */
static void
nios2_init_cache (struct nios2_unwind_cache *cache, CORE_ADDR pc)
{
cache->base = 0;
cache->cfa = 0;
cache->pc = pc;
cache->return_regnum = NIOS2_RA_REGNUM;
nios2_setup_default (cache);
}
/* Helper function to identify when we're in a function epilogue;
that is, the part of the function from the point at which the
stack adjustment is made, to the return or sibcall. On Nios II,
we want to check that the CURRENT_PC is a return-type instruction
and that the previous instruction is a stack adjustment.
START_PC is the beginning of the function in question. */
static int
nios2_in_epilogue_p (struct gdbarch *gdbarch,
CORE_ADDR current_pc,
CORE_ADDR start_pc)
{
enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
/* There has to be a previous instruction in the function. */
if (current_pc > start_pc)
{
/* Check whether the previous instruction was a stack
adjustment. */
unsigned int insn
= read_memory_unsigned_integer (current_pc - NIOS2_OPCODE_SIZE,
NIOS2_OPCODE_SIZE, byte_order);
if ((insn & 0xffc0003c) == 0xdec00004 /* ADDI sp, sp, */
|| (insn & 0xffc1ffff) == 0xdec1883a /* ADD sp, sp, */
|| (insn & 0xffc0003f) == 0xdec00017) /* LDW sp, constant(sp) */
{
/* Then check if it's followed by a return or a tail
call. */
insn = read_memory_unsigned_integer (current_pc, NIOS2_OPCODE_SIZE,
byte_order);
if (insn == 0xf800283a /* RET */
|| insn == 0xe800083a /* ERET */
|| (insn & 0x07ffffff) == 0x0000683a /* JMP */
|| (insn & 0xffc0003f) == 6) /* BR */
return 1;
}
}
return 0;
}
/* Implement the in_function_epilogue_p gdbarch method. */
static int
nios2_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
{
CORE_ADDR func_addr;
if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
return nios2_in_epilogue_p (gdbarch, pc, func_addr);
return 0;
}
/* Define some instruction patterns supporting wildcard bits via a
mask. */
typedef struct
{
unsigned int insn;
unsigned int mask;
} wild_insn;
static const wild_insn profiler_insn[] =
{
{ 0x0010e03a, 0x00000000 }, /* nextpc r8 */
{ 0xf813883a, 0x00000000 }, /* mov r9,ra */
{ 0x02800034, 0x003fffc0 }, /* movhi r10,257 */
{ 0x52800004, 0x003fffc0 }, /* addi r10,r10,-31992 */
{ 0x00000000, 0xffffffc0 }, /* call <mcount> */
{ 0x483f883a, 0x00000000 } /* mov ra,r9 */
};
static const wild_insn irqentry_insn[] =
{
{ 0x0031307a, 0x00000000 }, /* rdctl et,estatus */
{ 0xc600004c, 0x00000000 }, /* andi et,et,1 */
{ 0xc0000026, 0x003fffc0 }, /* beq et,zero, <software_exception> */
{ 0x0031313a, 0x00000000 }, /* rdctl et,ipending */
{ 0xc0000026, 0x003fffc0 } /* beq et,zero, <software_exception> */
};
/* Attempt to match SEQUENCE, which is COUNT insns long, at START_PC. */
static int
nios2_match_sequence (struct gdbarch *gdbarch, CORE_ADDR start_pc,
const wild_insn *sequence, int count)
{
CORE_ADDR pc = start_pc;
int i;
unsigned int insn;
enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
for (i = 0 ; i < count ; i++)
{
insn = read_memory_unsigned_integer (pc, NIOS2_OPCODE_SIZE, byte_order);
if ((insn & ~sequence[i].mask) != sequence[i].insn)
return 0;
pc += NIOS2_OPCODE_SIZE;
}
return 1;
}
/* Do prologue analysis, returning the PC of the first instruction
after the function prologue. Assumes CACHE has already been
initialized. THIS_FRAME can be null, in which case we are only
interested in skipping the prologue. Otherwise CACHE is filled in
from the frame information.
The prologue will consist of the following parts:
1) Optional profiling instrumentation. The old version uses six
instructions. We step over this if there is an exact match.
nextpc r8
mov r9, ra
movhi r10, %hiadj(.LP2)
addi r10, r10, %lo(.LP2)
call mcount
mov ra, r9
The new version uses two or three instructions (the last of
these might get merged in with the STW which saves RA to the
stack). We interpret these.
mov r8, ra
call mcount
mov ra, r8
2) Optional interrupt entry decision. Again, we step over
this if there is an exact match.
rdctl et,estatus
andi et,et,1
beq et,zero, <software_exception>
rdctl et,ipending
beq et,zero, <software_exception>
3) A stack adjustment or stack which, which will be one of:
addi sp, sp, -constant
or:
movi r8, constant
sub sp, sp, r8
or
movhi r8, constant
addi r8, r8, constant
sub sp, sp, r8
or
movhi rx, %hiadj(newstack)
addhi rx, rx, %lo(newstack)
stw sp, constant(rx)
mov sp, rx
4) An optional stack check, which can take either of these forms:
bgeu sp, rx, +8
break 3
or
bltu sp, rx, .Lstack_overflow
...
.Lstack_overflow:
break 3
5) Saving any registers which need to be saved. These will
normally just be stored onto the stack:
stw rx, constant(sp)
but in the large frame case will use r8 as an offset back
to the cfa:
add r8, r8, sp
stw rx, -constant(r8)
Saving control registers looks slightly different:
rdctl rx, ctlN
stw rx, constant(sp)
6) An optional FP setup, either if the user has requested a
frame pointer or if the function calls alloca.
This is always:
mov fp, sp
The prologue instructions may be interleaved, and the register
saves and FP setup can occur in either order.
To cope with all this variability we decode all the instructions
from the start of the prologue until we hit a branch, call or
return. For each of the instructions mentioned in 3, 4 and 5 we
handle the limited cases of stores to the stack and operations
on constant values. */
static CORE_ADDR
nios2_analyze_prologue (struct gdbarch *gdbarch, const CORE_ADDR start_pc,
const CORE_ADDR current_pc,
struct nios2_unwind_cache *cache,
struct frame_info *this_frame)
{
/* Maximum lines of prologue to check.
Note that this number should not be too large, else we can
potentially end up iterating through unmapped memory. */
CORE_ADDR limit_pc = start_pc + 200;
int regno;
enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
/* Does the frame set up the FP register? */
int base_reg = 0;
struct reg_value *value = cache->reg_value;
struct reg_value temp_value[NIOS2_NUM_REGS];
int i;
/* Save the starting PC so we can correct the pc after running
through the prolog, using symbol info. */
CORE_ADDR pc = start_pc;
/* Is this an exception handler? */
int exception_handler = 0;
/* What was the original value of SP (or fake original value for
functions which switch stacks? */
CORE_ADDR frame_high;
/* Is this the end of the prologue? */
int within_prologue = 1;
CORE_ADDR prologue_end;
/* Is this the innermost function? */
int innermost = (this_frame ? (frame_relative_level (this_frame) == 0) : 1);
if (nios2_debug)
fprintf_unfiltered (gdb_stdlog,
"{ nios2_analyze_prologue start=%s, current=%s ",
paddress (gdbarch, start_pc),
paddress (gdbarch, current_pc));
/* Set up the default values of the registers. */
nios2_setup_default (cache);
/* If the first few instructions are the profile entry, then skip
over them. Newer versions of the compiler use more efficient
profiling code. */
if (nios2_match_sequence (gdbarch, pc, profiler_insn,
ARRAY_SIZE (profiler_insn)))
pc += ARRAY_SIZE (profiler_insn) * NIOS2_OPCODE_SIZE;
/* If the first few instructions are an interrupt entry, then skip
over them too. */
if (nios2_match_sequence (gdbarch, pc, irqentry_insn,
ARRAY_SIZE (irqentry_insn)))
{
pc += ARRAY_SIZE (irqentry_insn) * NIOS2_OPCODE_SIZE;
exception_handler = 1;
}
prologue_end = start_pc;
/* Find the prologue instructions. */
while (pc < limit_pc && within_prologue)
{
/* Present instruction. */
uint32_t insn;
int prologue_insn = 0;
if (pc == current_pc)
{
/* When we reach the current PC we must save the current
register state (for the backtrace) but keep analysing
because there might be more to find out (eg. is this an
exception handler). */
memcpy (temp_value, value, sizeof (temp_value));
value = temp_value;
if (nios2_debug)
fprintf_unfiltered (gdb_stdlog, "*");
}
insn = read_memory_unsigned_integer (pc, NIOS2_OPCODE_SIZE, byte_order);
pc += NIOS2_OPCODE_SIZE;
if (nios2_debug)
fprintf_unfiltered (gdb_stdlog, "[%08X]", insn);
/* The following instructions can appear in the prologue. */
if ((insn & 0x0001ffff) == 0x0001883a)
{
/* ADD rc, ra, rb (also used for MOV) */
int ra = GET_IW_A (insn);
int rb = GET_IW_B (insn);
int rc = GET_IW_C (insn);
if (rc == NIOS2_SP_REGNUM
&& rb == 0
&& value[ra].reg == cache->reg_saved[NIOS2_SP_REGNUM].basereg)
{
/* If the previous value of SP is available somewhere
near the new stack pointer value then this is a
stack switch. */
/* If any registers were saved on the stack before then
we can't backtrace into them now. */
for (i = 0 ; i < NIOS2_NUM_REGS ; i++)
{
if (cache->reg_saved[i].basereg == NIOS2_SP_REGNUM)
cache->reg_saved[i].basereg = -1;
if (value[i].reg == NIOS2_SP_REGNUM)
value[i].reg = -1;
}
/* Create a fake "high water mark" 4 bytes above where SP
was stored and fake up the registers to be consistent
with that. */
value[NIOS2_SP_REGNUM].reg = NIOS2_SP_REGNUM;
value[NIOS2_SP_REGNUM].offset
= (value[ra].offset
- cache->reg_saved[NIOS2_SP_REGNUM].addr
- 4);
cache->reg_saved[NIOS2_SP_REGNUM].basereg = NIOS2_SP_REGNUM;
cache->reg_saved[NIOS2_SP_REGNUM].addr = -4;
}
else if (rc != 0)
{
if (value[rb].reg == 0)
value[rc].reg = value[ra].reg;
else if (value[ra].reg == 0)
value[rc].reg = value[rb].reg;
else
value[rc].reg = -1;
value[rc].offset = value[ra].offset + value[rb].offset;
}
prologue_insn = 1;
}
else if ((insn & 0x0001ffff) == 0x0001983a)
{
/* SUB rc, ra, rb */
int ra = GET_IW_A (insn);
int rb = GET_IW_B (insn);
int rc = GET_IW_C (insn);
if (rc != 0)
{
if (value[rb].reg == 0)
value[rc].reg = value[ra].reg;
else
value[rc].reg = -1;
value[rc].offset = value[ra].offset - value[rb].offset;
}
}
else if ((insn & 0x0000003f) == 0x00000004)
{
/* ADDI rb, ra, immed (also used for MOVI) */
short immed = GET_IW_IMM16 (insn);
int ra = GET_IW_A (insn);
int rb = GET_IW_B (insn);
/* The first stack adjustment is part of the prologue.
Any subsequent stack adjustments are either down to
alloca or the epilogue so stop analysing when we hit
them. */
if (rb == NIOS2_SP_REGNUM
&& (value[rb].offset != 0 || value[ra].reg != NIOS2_SP_REGNUM))
break;
if (rb != 0)
{
value[rb].reg = value[ra].reg;
value[rb].offset = value[ra].offset + immed;
}
prologue_insn = 1;
}
else if ((insn & 0x0000003f) == 0x00000034)
{
/* ORHI rb, ra, immed (also used for MOVHI) */
unsigned int immed = GET_IW_IMM16 (insn);
int ra = GET_IW_A (insn);
int rb = GET_IW_B (insn);
if (rb != 0)
{
value[rb].reg = (value[ra].reg == 0) ? 0 : -1;
value[rb].offset = value[ra].offset | (immed << 16);
}
}
else if ((insn & IW_OP_MASK) == OP_STW
|| (insn & IW_OP_MASK) == OP_STWIO)
{
/* STW rb, immediate(ra) */
short immed16 = GET_IW_IMM16 (insn);
int ra = GET_IW_A (insn);
int rb = GET_IW_B (insn);
/* Are we storing the original value of a register?
For exception handlers the value of EA-4 (return
address from interrupts etc) is sometimes stored. */
int orig = value[rb].reg;
if (orig > 0
&& (value[rb].offset == 0
|| (orig == NIOS2_EA_REGNUM && value[rb].offset == -4)))
{
/* We are most interested in stores to the stack, but
also take note of stores to other places as they
might be useful later. */
if ((value[ra].reg == NIOS2_SP_REGNUM
&& cache->reg_saved[orig].basereg != NIOS2_SP_REGNUM)
|| cache->reg_saved[orig].basereg == -1)
{
if (pc < current_pc)
{
/* Save off callee saved registers. */
cache->reg_saved[orig].basereg = value[ra].reg;
cache->reg_saved[orig].addr
= value[ra].offset + GET_IW_IMM16 (insn);
}
prologue_insn = 1;
if (orig == NIOS2_EA_REGNUM || orig == NIOS2_ESTATUS_REGNUM)
exception_handler = 1;
}
}
else
/* Non-stack memory writes are not part of the
prologue. */
within_prologue = 0;
}
else if ((insn & 0xffc1f83f) == 0x0001303a)
{
/* RDCTL rC, ctlN */
int rc = GET_IW_C (insn);
int n = GET_IW_CONTROL_REGNUM (insn);
if (rc != 0)
{
value[rc].reg = NIOS2_STATUS_REGNUM + n;
value[rc].offset = 0;
}
prologue_insn = 1;
}
else if ((insn & 0x0000003f) == 0
&& value[8].reg == NIOS2_RA_REGNUM
&& value[8].offset == 0
&& value[NIOS2_SP_REGNUM].reg == NIOS2_SP_REGNUM
&& value[NIOS2_SP_REGNUM].offset == 0)
{
/* A CALL instruction. This is treated as a call to mcount
if ra has been stored into r8 beforehand and if it's
before the stack adjust.
Note mcount corrupts r2-r3, r9-r15 & ra. */
for (i = 2 ; i <= 3 ; i++)
value[i].reg = -1;
for (i = 9 ; i <= 15 ; i++)
value[i].reg = -1;
value[NIOS2_RA_REGNUM].reg = -1;
prologue_insn = 1;
}
else if ((insn & 0xf83fffff) == 0xd800012e)
{
/* BGEU sp, rx, +8
BREAK 3
This instruction sequence is used in stack checking;
we can ignore it. */
unsigned int next_insn
= read_memory_unsigned_integer (pc, NIOS2_OPCODE_SIZE, byte_order);
if (next_insn != 0x003da0fa)
within_prologue = 0;
else
pc += NIOS2_OPCODE_SIZE;
}
else if ((insn & 0xf800003f) == 0xd8000036)
{
/* BLTU sp, rx, .Lstackoverflow
If the location branched to holds a BREAK 3 instruction
then this is also stack overflow detection. We can
ignore it. */
CORE_ADDR target_pc = pc + ((insn & 0x3fffc0) >> 6);
unsigned int target_insn
= read_memory_unsigned_integer (target_pc, NIOS2_OPCODE_SIZE,
byte_order);
if (target_insn != 0x003da0fa)
within_prologue = 0;
}
/* Any other instructions are allowed to be moved up into the
prologue. If we reach a branch, call or return then the
prologue is considered over. We also consider a second stack
adjustment as terminating the prologue (see above). */
else
{
switch (GET_IW_OP (insn))
{
case OP_BEQ:
case OP_BGE:
case OP_BGEU:
case OP_BLT:
case OP_BLTU:
case OP_BNE:
case OP_BR:
case OP_CALL:
within_prologue = 0;
break;
case OP_OPX:
if (GET_IW_OPX (insn) == OPX_RET
|| GET_IW_OPX (insn) == OPX_ERET
|| GET_IW_OPX (insn) == OPX_BRET
|| GET_IW_OPX (insn) == OPX_CALLR
|| GET_IW_OPX (insn) == OPX_JMP)
within_prologue = 0;
break;
default:
break;
}
}
if (prologue_insn)
prologue_end = pc;
}
/* If THIS_FRAME is NULL, we are being called from skip_prologue
and are only interested in the PROLOGUE_END value, so just
return that now and skip over the cache updates, which depend
on having frame information. */
if (this_frame == NULL)
return prologue_end;
/* If we are in the function epilogue and have already popped
registers off the stack in preparation for returning, then we
want to go back to the original register values. */
if (innermost && nios2_in_epilogue_p (gdbarch, current_pc, start_pc))
nios2_setup_default (cache);
/* Exception handlers use a different return address register. */
if (exception_handler)
cache->return_regnum = NIOS2_EA_REGNUM;
if (nios2_debug)
fprintf_unfiltered (gdb_stdlog, "\n-> retreg=%d, ", cache->return_regnum);
if (cache->reg_value[NIOS2_FP_REGNUM].reg == NIOS2_SP_REGNUM)
/* If the FP now holds an offset from the CFA then this is a
normal frame which uses the frame pointer. */
base_reg = NIOS2_FP_REGNUM;
else if (cache->reg_value[NIOS2_SP_REGNUM].reg == NIOS2_SP_REGNUM)
/* FP doesn't hold an offset from the CFA. If SP still holds an
offset from the CFA then we might be in a function which omits
the frame pointer, or we might be partway through the prologue.
In both cases we can find the CFA using SP. */
base_reg = NIOS2_SP_REGNUM;
else
{
/* Somehow the stack pointer has been corrupted.
We can't return. */
if (nios2_debug)
fprintf_unfiltered (gdb_stdlog, "<can't reach cfa> }\n");
return 0;
}
if (cache->reg_value[base_reg].offset == 0
|| cache->reg_saved[NIOS2_RA_REGNUM].basereg != NIOS2_SP_REGNUM
|| cache->reg_saved[cache->return_regnum].basereg != NIOS2_SP_REGNUM)
{
/* If the frame didn't adjust the stack, didn't save RA or
didn't save EA in an exception handler then it must either
be a leaf function (doesn't call any other functions) or it
can't return. If it has called another function then it
can't be a leaf, so set base == 0 to indicate that we can't
backtrace past it. */
if (!innermost)
{
/* If it isn't the innermost function then it can't be a
leaf, unless it was interrupted. Check whether RA for
this frame is the same as PC. If so then it probably
wasn't interrupted. */
CORE_ADDR ra
= get_frame_register_unsigned (this_frame, NIOS2_RA_REGNUM);
if (ra == current_pc)
{
if (nios2_debug)
fprintf_unfiltered
(gdb_stdlog,
"<noreturn ADJUST %s, r31@r%d+?>, r%d@r%d+?> }\n",
paddress (gdbarch, cache->reg_value[base_reg].offset),
cache->reg_saved[NIOS2_RA_REGNUM].basereg,
cache->return_regnum,
cache->reg_saved[cache->return_regnum].basereg);
return 0;
}
}
}
/* Get the value of whichever register we are using for the
base. */
cache->base = get_frame_register_unsigned (this_frame, base_reg);
/* What was the value of SP at the start of this function (or just
after the stack switch). */
frame_high = cache->base - cache->reg_value[base_reg].offset;
/* Adjust all the saved registers such that they contain addresses
instead of offsets. */
for (i = 0; i < NIOS2_NUM_REGS; i++)
if (cache->reg_saved[i].basereg == NIOS2_SP_REGNUM)
{
cache->reg_saved[i].basereg = NIOS2_Z_REGNUM;
cache->reg_saved[i].addr += frame_high;
}
for (i = 0; i < NIOS2_NUM_REGS; i++)
if (cache->reg_saved[i].basereg == NIOS2_GP_REGNUM)
{
CORE_ADDR gp = get_frame_register_unsigned (this_frame,
NIOS2_GP_REGNUM);
for ( ; i < NIOS2_NUM_REGS; i++)
if (cache->reg_saved[i].basereg == NIOS2_GP_REGNUM)
{
cache->reg_saved[i].basereg = NIOS2_Z_REGNUM;
cache->reg_saved[i].addr += gp;
}
}
/* Work out what the value of SP was on the first instruction of
this function. If we didn't switch stacks then this can be
trivially computed from the base address. */
if (cache->reg_saved[NIOS2_SP_REGNUM].basereg == NIOS2_Z_REGNUM)
cache->cfa
= read_memory_unsigned_integer (cache->reg_saved[NIOS2_SP_REGNUM].addr,
4, byte_order);
else
cache->cfa = frame_high;
/* Exception handlers restore ESTATUS into STATUS. */
if (exception_handler)
{
cache->reg_saved[NIOS2_STATUS_REGNUM]
= cache->reg_saved[NIOS2_ESTATUS_REGNUM];
cache->reg_saved[NIOS2_ESTATUS_REGNUM].basereg = -1;
}
if (nios2_debug)
fprintf_unfiltered (gdb_stdlog, "cfa=%s }\n",
paddress (gdbarch, cache->cfa));
return prologue_end;
}
/* Implement the skip_prologue gdbarch hook. */
static CORE_ADDR
nios2_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR start_pc)
{
CORE_ADDR limit_pc;
CORE_ADDR func_addr;
struct nios2_unwind_cache cache;
/* See if we can determine the end of the prologue via the symbol
table. If so, then return either PC, or the PC after the
prologue, whichever is greater. */
if (find_pc_partial_function (start_pc, NULL, &func_addr, NULL))
{
CORE_ADDR post_prologue_pc
= skip_prologue_using_sal (gdbarch, func_addr);
if (post_prologue_pc != 0)
return max (start_pc, post_prologue_pc);
}
/* Prologue analysis does the rest.... */
nios2_init_cache (&cache, start_pc);
return nios2_analyze_prologue (gdbarch, start_pc, start_pc, &cache, NULL);
}
/* Implement the breakpoint_from_pc gdbarch hook. */
static const gdb_byte*
nios2_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *bp_addr,
int *bp_size)
{
/* break encoding: 31->27 26->22 21->17 16->11 10->6 5->0 */
/* 00000 00000 0x1d 0x2d 11111 0x3a */
/* 00000 00000 11101 101101 11111 111010 */
/* In bytes: 00000000 00111011 01101111 11111010 */
/* 0x0 0x3b 0x6f 0xfa */
static const gdb_byte breakpoint_le[] = {0xfa, 0x6f, 0x3b, 0x0};
static const gdb_byte breakpoint_be[] = {0x0, 0x3b, 0x6f, 0xfa};
enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
*bp_size = 4;
if (gdbarch_byte_order_for_code (gdbarch) == BFD_ENDIAN_BIG)
return breakpoint_be;
else
return breakpoint_le;
}
/* Implement the print_insn gdbarch method. */
static int
nios2_print_insn (bfd_vma memaddr, disassemble_info *info)
{
if (info->endian == BFD_ENDIAN_BIG)
return print_insn_big_nios2 (memaddr, info);
else
return print_insn_little_nios2 (memaddr, info);
}
/* Implement the frame_align gdbarch method. */
static CORE_ADDR
nios2_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
{
return align_down (addr, 4);
}
/* Implement the return_value gdbarch method. */
static enum return_value_convention
nios2_return_value (struct gdbarch *gdbarch, struct value *function,
struct type *type, struct regcache *regcache,
gdb_byte *readbuf, const gdb_byte *writebuf)
{
if (TYPE_LENGTH (type) > 8)
return RETURN_VALUE_STRUCT_CONVENTION;
if (readbuf)
nios2_extract_return_value (gdbarch, type, regcache, readbuf);
if (writebuf)
nios2_store_return_value (gdbarch, type, regcache, writebuf);
return RETURN_VALUE_REGISTER_CONVENTION;
}
/* Implement the dummy_id gdbarch method. */
static struct frame_id
nios2_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
{
return frame_id_build
(get_frame_register_unsigned (this_frame, NIOS2_SP_REGNUM),
get_frame_pc (this_frame));
}
/* Implement the push_dummy_call gdbarch method. */
static CORE_ADDR
nios2_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
struct regcache *regcache, CORE_ADDR bp_addr,
int nargs, struct value **args, CORE_ADDR sp,
int struct_return, CORE_ADDR struct_addr)
{
int argreg;
int float_argreg;
int argnum;
int len = 0;
int stack_offset = 0;
CORE_ADDR func_addr = find_function_addr (function, NULL);
enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
/* Set the return address register to point to the entry point of
the program, where a breakpoint lies in wait. */
regcache_cooked_write_signed (regcache, NIOS2_RA_REGNUM, bp_addr);
/* Now make space on the stack for the args. */
for (argnum = 0; argnum < nargs; argnum++)
len += align_up (TYPE_LENGTH (value_type (args[argnum])), 4);
sp -= len;
/* Initialize the register pointer. */
argreg = NIOS2_FIRST_ARGREG;
/* The struct_return pointer occupies the first parameter-passing
register. */
if (struct_return)
regcache_cooked_write_unsigned (regcache, argreg++, struct_addr);
/* Now load as many as possible of the first arguments into
registers, and push the rest onto the stack. Loop through args
from first to last. */
for (argnum = 0; argnum < nargs; argnum++)
{
const gdb_byte *val;
gdb_byte valbuf[MAX_REGISTER_SIZE];
struct value *arg = args[argnum];
struct type *arg_type = check_typedef (value_type (arg));
int len = TYPE_LENGTH (arg_type);
enum type_code typecode = TYPE_CODE (arg_type);
val = value_contents (arg);
/* Copy the argument to general registers or the stack in
register-sized pieces. Large arguments are split between
registers and stack. */
while (len > 0)
{
int partial_len = (len < 4 ? len : 4);
if (argreg <= NIOS2_LAST_ARGREG)
{
/* The argument is being passed in a register. */
CORE_ADDR regval = extract_unsigned_integer (val, partial_len,
byte_order);
regcache_cooked_write_unsigned (regcache, argreg, regval);
argreg++;
}
else
{
/* The argument is being passed on the stack. */
CORE_ADDR addr = sp + stack_offset;
write_memory (addr, val, partial_len);
stack_offset += align_up (partial_len, 4);
}
len -= partial_len;
val += partial_len;
}
}
regcache_cooked_write_signed (regcache, NIOS2_SP_REGNUM, sp);
/* Return adjusted stack pointer. */
return sp;
}
/* Implement the unwind_pc gdbarch method. */
static CORE_ADDR
nios2_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
{
gdb_byte buf[4];
frame_unwind_register (next_frame, NIOS2_PC_REGNUM, buf);
return extract_typed_address (buf, builtin_type (gdbarch)->builtin_func_ptr);
}
/* Implement the unwind_sp gdbarch method. */
static CORE_ADDR
nios2_unwind_sp (struct gdbarch *gdbarch, struct frame_info *this_frame)
{
return frame_unwind_register_unsigned (this_frame, NIOS2_SP_REGNUM);
}
/* Use prologue analysis to fill in the register cache
*THIS_PROLOGUE_CACHE for THIS_FRAME. This function initializes
*THIS_PROLOGUE_CACHE first. */
static struct nios2_unwind_cache *
nios2_frame_unwind_cache (struct frame_info *this_frame,
void **this_prologue_cache)
{
struct gdbarch *gdbarch = get_frame_arch (this_frame);
CORE_ADDR current_pc;
struct nios2_unwind_cache *cache;
int i;
if (*this_prologue_cache)
return *this_prologue_cache;
cache = FRAME_OBSTACK_ZALLOC (struct nios2_unwind_cache);
*this_prologue_cache = cache;
/* Zero all fields. */
nios2_init_cache (cache, get_frame_func (this_frame));
/* Prologue analysis does the rest... */
current_pc = get_frame_pc (this_frame);
if (cache->pc != 0)
nios2_analyze_prologue (gdbarch, cache->pc, current_pc, cache, this_frame);
return cache;
}
/* Implement the this_id function for the normal unwinder. */
static void
nios2_frame_this_id (struct frame_info *this_frame, void **this_cache,
struct frame_id *this_id)
{
struct nios2_unwind_cache *cache =
nios2_frame_unwind_cache (this_frame, this_cache);
/* This marks the outermost frame. */
if (cache->base == 0)
return;
*this_id = frame_id_build (cache->cfa, cache->pc);
}
/* Implement the prev_register function for the normal unwinder. */
static struct value *
nios2_frame_prev_register (struct frame_info *this_frame, void **this_cache,
int regnum)
{
struct nios2_unwind_cache *cache =
nios2_frame_unwind_cache (this_frame, this_cache);
gdb_assert (regnum >= 0 && regnum < NIOS2_NUM_REGS);
/* The PC of the previous frame is stored in the RA register of
the current frame. Frob regnum so that we pull the value from
the correct place. */
if (regnum == NIOS2_PC_REGNUM)
regnum = cache->return_regnum;
if (regnum == NIOS2_SP_REGNUM && cache->cfa)
return frame_unwind_got_constant (this_frame, regnum, cache->cfa);
/* If we've worked out where a register is stored then load it from
there. */
if (cache->reg_saved[regnum].basereg == NIOS2_Z_REGNUM)
return frame_unwind_got_memory (this_frame, regnum,
cache->reg_saved[regnum].addr);
return frame_unwind_got_register (this_frame, regnum, regnum);
}
/* Implement the this_base, this_locals, and this_args hooks
for the normal unwinder. */
static CORE_ADDR
nios2_frame_base_address (struct frame_info *this_frame, void **this_cache)
{
struct nios2_unwind_cache *info
= nios2_frame_unwind_cache (this_frame, this_cache);
return info->base;
}
/* Data structures for the normal prologue-analysis-based
unwinder. */
static const struct frame_unwind nios2_frame_unwind =
{
NORMAL_FRAME,
default_frame_unwind_stop_reason,
nios2_frame_this_id,
nios2_frame_prev_register,
NULL,
default_frame_sniffer
};
static const struct frame_base nios2_frame_base =
{
&nios2_frame_unwind,
nios2_frame_base_address,
nios2_frame_base_address,
nios2_frame_base_address
};
/* Fill in the register cache *THIS_CACHE for THIS_FRAME for use
in the stub unwinder. */
static struct trad_frame_cache *
nios2_stub_frame_cache (struct frame_info *this_frame, void **this_cache)
{
CORE_ADDR pc;
CORE_ADDR start_addr;
CORE_ADDR stack_addr;
struct trad_frame_cache *this_trad_cache;
struct gdbarch *gdbarch = get_frame_arch (this_frame);
int num_regs = gdbarch_num_regs (gdbarch);
if (*this_cache != NULL)
return *this_cache;
this_trad_cache = trad_frame_cache_zalloc (this_frame);
*this_cache = this_trad_cache;
/* The return address is in the link register. */
trad_frame_set_reg_realreg (this_trad_cache,
gdbarch_pc_regnum (gdbarch),
NIOS2_RA_REGNUM);
/* Frame ID, since it's a frameless / stackless function, no stack
space is allocated and SP on entry is the current SP. */
pc = get_frame_pc (this_frame);
find_pc_partial_function (pc, NULL, &start_addr, NULL);
stack_addr = get_frame_register_unsigned (this_frame, NIOS2_SP_REGNUM);
trad_frame_set_id (this_trad_cache, frame_id_build (start_addr, stack_addr));
/* Assume that the frame's base is the same as the stack pointer. */
trad_frame_set_this_base (this_trad_cache, stack_addr);
return this_trad_cache;
}
/* Implement the this_id function for the stub unwinder. */
static void
nios2_stub_frame_this_id (struct frame_info *this_frame, void **this_cache,
struct frame_id *this_id)
{
struct trad_frame_cache *this_trad_cache
= nios2_stub_frame_cache (this_frame, this_cache);
trad_frame_get_id (this_trad_cache, this_id);
}
/* Implement the prev_register function for the stub unwinder. */
static struct value *
nios2_stub_frame_prev_register (struct frame_info *this_frame,
void **this_cache, int regnum)
{
struct trad_frame_cache *this_trad_cache
= nios2_stub_frame_cache (this_frame, this_cache);
return trad_frame_get_register (this_trad_cache, this_frame, regnum);
}
/* Implement the sniffer function for the stub unwinder.
This unwinder is used for cases where the normal
prologue-analysis-based unwinder can't work,
such as PLT stubs. */
static int
nios2_stub_frame_sniffer (const struct frame_unwind *self,
struct frame_info *this_frame, void **cache)
{
gdb_byte dummy[4];
struct obj_section *s;
CORE_ADDR pc = get_frame_address_in_block (this_frame);
/* Use the stub unwinder for unreadable code. */
if (target_read_memory (get_frame_pc (this_frame), dummy, 4) != 0)
return 1;
if (in_plt_section (pc))
return 1;
return 0;
}
/* Implement the this_base, this_locals, and this_args hooks
for the stub unwinder. */
static CORE_ADDR
nios2_stub_frame_base_address (struct frame_info *this_frame, void **this_cache)
{
struct trad_frame_cache *this_trad_cache
= nios2_stub_frame_cache (this_frame, this_cache);
return trad_frame_get_this_base (this_trad_cache);
}
/* Define the data structures for the stub unwinder. */
static const struct frame_unwind nios2_stub_frame_unwind =
{
NORMAL_FRAME,
default_frame_unwind_stop_reason,
nios2_stub_frame_this_id,
nios2_stub_frame_prev_register,
NULL,
nios2_stub_frame_sniffer
};
static const struct frame_base nios2_stub_frame_base =
{
&nios2_stub_frame_unwind,
nios2_stub_frame_base_address,
nios2_stub_frame_base_address,
nios2_stub_frame_base_address
};
/* Helper function to read an instruction at PC. */
static unsigned long
nios2_fetch_instruction (struct gdbarch *gdbarch, CORE_ADDR pc)
{
enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
return read_memory_unsigned_integer (pc, NIOS2_OPCODE_SIZE, byte_order);
}
/* Determine where to set a single step breakpoint while considering
branch prediction. */
static CORE_ADDR
nios2_get_next_pc (struct frame_info *frame, CORE_ADDR pc)
{
struct gdbarch *gdbarch = get_frame_arch (frame);
struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
unsigned long inst;
int op;
int imm16;
int ra;
int rb;
int ras;
int rbs;
unsigned int rau;
unsigned int rbu;
inst = nios2_fetch_instruction (gdbarch, pc);
pc += NIOS2_OPCODE_SIZE;
imm16 = (short) GET_IW_IMM16 (inst);
ra = GET_IW_A (inst);
rb = GET_IW_B (inst);
ras = get_frame_register_signed (frame, ra);
rbs = get_frame_register_signed (frame, rb);
rau = get_frame_register_unsigned (frame, ra);
rbu = get_frame_register_unsigned (frame, rb);
switch (GET_IW_OP (inst))
{
case OP_BEQ:
if (ras == rbs)
pc += imm16;
break;
case OP_BGE:
if (ras >= rbs)
pc += imm16;
break;
case OP_BGEU:
if (rau >= rbu)
pc += imm16;
break;
case OP_BLT:
if (ras < rbs)
pc += imm16;
break;
case OP_BLTU:
if (rau < rbu)
pc += imm16;
break;
case OP_BNE:
if (ras != rbs)
pc += imm16;
break;
case OP_BR:
pc += imm16;
break;
case OP_JMPI:
case OP_CALL:
pc = (pc & 0xf0000000) | (GET_IW_IMM26 (inst) << 2);
break;
case OP_OPX:
switch (GET_IW_OPX (inst))
{
case OPX_JMP:
case OPX_CALLR:
case OPX_RET:
pc = ras;
break;
case OPX_TRAP:
if (tdep->syscall_next_pc != NULL)
return tdep->syscall_next_pc (frame);
default:
break;
}
break;
default:
break;
}
return pc;
}
/* Implement the software_single_step gdbarch method. */
static int
nios2_software_single_step (struct frame_info *frame)
{
struct gdbarch *gdbarch = get_frame_arch (frame);
struct address_space *aspace = get_frame_address_space (frame);
CORE_ADDR next_pc = nios2_get_next_pc (frame, get_frame_pc (frame));
insert_single_step_breakpoint (gdbarch, aspace, next_pc);
return 1;
}
/* Implement the get_longjump_target gdbarch method. */
static int
nios2_get_longjmp_target (struct frame_info *frame, CORE_ADDR *pc)
{
struct gdbarch *gdbarch = get_frame_arch (frame);
struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
CORE_ADDR jb_addr = get_frame_register_unsigned (frame, NIOS2_R4_REGNUM);
gdb_byte buf[4];
if (target_read_memory (jb_addr + (tdep->jb_pc * 4), buf, 4))
return 0;
*pc = extract_unsigned_integer (buf, 4, byte_order);
return 1;
}
/* Initialize the Nios II gdbarch. */
static struct gdbarch *
nios2_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
{
struct gdbarch *gdbarch;
struct gdbarch_tdep *tdep;
int register_bytes, i;
struct tdesc_arch_data *tdesc_data = NULL;
const struct target_desc *tdesc = info.target_desc;
if (!tdesc_has_registers (tdesc))
/* Pick a default target description. */
tdesc = tdesc_nios2;
/* Check any target description for validity. */
if (tdesc_has_registers (tdesc))
{
const struct tdesc_feature *feature;
int valid_p;
feature = tdesc_find_feature (tdesc, "org.gnu.gdb.nios2.cpu");
if (feature == NULL)
return NULL;
tdesc_data = tdesc_data_alloc ();
valid_p = 1;
for (i = 0; i < NIOS2_NUM_REGS; i++)
valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
nios2_reg_names[i]);
if (!valid_p)
{
tdesc_data_cleanup (tdesc_data);
return NULL;
}
}
/* Find a candidate among the list of pre-declared architectures. */
arches = gdbarch_list_lookup_by_info (arches, &info);
if (arches != NULL)
return arches->gdbarch;
/* None found, create a new architecture from the information
provided. */
tdep = xcalloc (1, sizeof (struct gdbarch_tdep));
gdbarch = gdbarch_alloc (&info, tdep);
/* longjmp support not enabled by default. */
tdep->jb_pc = -1;
/* Data type sizes. */
set_gdbarch_ptr_bit (gdbarch, 32);
set_gdbarch_addr_bit (gdbarch, 32);
set_gdbarch_short_bit (gdbarch, 16);
set_gdbarch_int_bit (gdbarch, 32);
set_gdbarch_long_bit (gdbarch, 32);
set_gdbarch_long_long_bit (gdbarch, 64);
set_gdbarch_float_bit (gdbarch, 32);
set_gdbarch_double_bit (gdbarch, 64);
set_gdbarch_float_format (gdbarch, floatformats_ieee_single);
set_gdbarch_double_format (gdbarch, floatformats_ieee_double);
/* The register set. */
set_gdbarch_num_regs (gdbarch, NIOS2_NUM_REGS);
set_gdbarch_sp_regnum (gdbarch, NIOS2_SP_REGNUM);
set_gdbarch_pc_regnum (gdbarch, NIOS2_PC_REGNUM); /* Pseudo register PC */
set_gdbarch_register_name (gdbarch, nios2_register_name);
set_gdbarch_register_type (gdbarch, nios2_register_type);
/* Provide register mappings for stabs and dwarf2. */
set_gdbarch_stab_reg_to_regnum (gdbarch, nios2_dwarf_reg_to_regnum);
set_gdbarch_dwarf2_reg_to_regnum (gdbarch, nios2_dwarf_reg_to_regnum);
set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
/* Call dummy code. */
set_gdbarch_frame_align (gdbarch, nios2_frame_align);
set_gdbarch_return_value (gdbarch, nios2_return_value);
set_gdbarch_skip_prologue (gdbarch, nios2_skip_prologue);
set_gdbarch_in_function_epilogue_p (gdbarch, nios2_in_function_epilogue_p);
set_gdbarch_breakpoint_from_pc (gdbarch, nios2_breakpoint_from_pc);
set_gdbarch_dummy_id (gdbarch, nios2_dummy_id);
set_gdbarch_unwind_pc (gdbarch, nios2_unwind_pc);
set_gdbarch_unwind_sp (gdbarch, nios2_unwind_sp);
/* The dwarf2 unwinder will normally produce the best results if
the debug information is available, so register it first. */
dwarf2_append_unwinders (gdbarch);
frame_unwind_append_unwinder (gdbarch, &nios2_stub_frame_unwind);
frame_unwind_append_unwinder (gdbarch, &nios2_frame_unwind);
/* Single stepping. */
set_gdbarch_software_single_step (gdbarch, nios2_software_single_step);
/* Hook in ABI-specific overrides, if they have been registered. */
gdbarch_init_osabi (info, gdbarch);
if (tdep->jb_pc >= 0)
set_gdbarch_get_longjmp_target (gdbarch, nios2_get_longjmp_target);
frame_base_set_default (gdbarch, &nios2_frame_base);
set_gdbarch_print_insn (gdbarch, nios2_print_insn);
/* Enable inferior call support. */
set_gdbarch_push_dummy_call (gdbarch, nios2_push_dummy_call);
if (tdesc_data)
tdesc_use_registers (gdbarch, tdesc, tdesc_data);
return gdbarch;
}
extern initialize_file_ftype _initialize_nios2_tdep; /* -Wmissing-prototypes */
void
_initialize_nios2_tdep (void)
{
gdbarch_register (bfd_arch_nios2, nios2_gdbarch_init, NULL);
initialize_tdesc_nios2 ();
/* Allow debugging this file's internals. */
add_setshow_boolean_cmd ("nios2", class_maintenance, &nios2_debug,
_("Set Nios II debugging."),
_("Show Nios II debugging."),
_("When on, Nios II specific debugging is enabled."),
NULL,
NULL,
&setdebuglist, &showdebuglist);
}
| gpl-2.0 |
omnirom/android_kernel_motorola_msm8226 | drivers/net/wireless/prima/CORE/SME/src/csr/csrNeighborRoam.c | 8 | 217158 | /*
* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/** ------------------------------------------------------------------------- *
------------------------------------------------------------------------- *
\file csrNeighborRoam.c
Implementation for the simple roaming algorithm for 802.11r Fast transitions and Legacy roaming for Android platform.
Copyright (C) 2010 Qualcomm, Incorporated
========================================================================== */
/*===========================================================================
EDIT HISTORY FOR FILE
This section contains comments describing changes made to the module.
Notice that changes are listed in reverse chronological order.
when who what, where, why
---------- --- --------------------------------------------------------
08/01/10 Murali Created
===========================================================================*/
#ifdef WLAN_FEATURE_NEIGHBOR_ROAMING
#include "wlan_qct_wda.h"
#include "palApi.h"
#include "csrInsideApi.h"
#include "smsDebug.h"
#include "logDump.h"
#include "smeQosInternal.h"
#include "wlan_qct_tl.h"
#include "smeInside.h"
#include "vos_diag_core_event.h"
#include "vos_diag_core_log.h"
#include "csrApi.h"
#include "wlan_qct_tl.h"
#include "sme_Api.h"
#include "csrNeighborRoam.h"
#if defined(FEATURE_WLAN_CCX) && !defined(FEATURE_WLAN_CCX_UPLOAD)
#include "csrCcx.h"
#endif
#define WLAN_FEATURE_NEIGHBOR_ROAMING_DEBUG 1
#ifdef WLAN_FEATURE_NEIGHBOR_ROAMING_DEBUG
#define NEIGHBOR_ROAM_DEBUG smsLog
#else
#define NEIGHBOR_ROAM_DEBUG(x...)
#endif
static void csrNeighborRoamResetChannelInfo(tpCsrNeighborRoamChannelInfo rChInfo);
static void csrNeighborRoamResetCfgListChanScanControlInfo(tpAniSirGlobal pMac);
static void csrNeighborRoamResetPreauthControlInfo(tpAniSirGlobal pMac);
static void csrNeighborRoamDeregAllRssiIndication(tpAniSirGlobal pMac);
VOS_STATUS csrNeighborRoamNeighborLookupUPCallback (v_PVOID_t pAdapter, v_U8_t rssiNotification,
v_PVOID_t pUserCtxt,
v_S7_t avgRssi);
VOS_STATUS csrNeighborRoamNeighborLookupDOWNCallback (v_PVOID_t pAdapter, v_U8_t rssiNotification,
v_PVOID_t pUserCtxt,
v_S7_t avgRssi);
void csrNeighborRoamRRMNeighborReportResult(void *context, VOS_STATUS vosStatus);
eHalStatus csrRoamCopyConnectedProfile(tpAniSirGlobal pMac, tANI_U32 sessionId, tCsrRoamProfile *pDstProfile );
#ifdef WLAN_FEATURE_VOWIFI_11R
static eHalStatus csrNeighborRoamIssuePreauthReq(tpAniSirGlobal pMac);
VOS_STATUS csrNeighborRoamIssueNeighborRptRequest(tpAniSirGlobal pMac);
#endif
#define ROAM_STATE_RETURN_STRING( str )\
case ( ( str ) ): return( #str )
v_U8_t *csrNeighborRoamStateToString(v_U8_t state)
{
switch(state)
{
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_CLOSED );
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_INIT );
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_CONNECTED );
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN );
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_REASSOCIATING );
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_REPORT_QUERY );
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN );
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_PREAUTHENTICATING );
ROAM_STATE_RETURN_STRING( eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE );
default:
return "eCSR_NEIGHBOR_ROAM_STATE_UNKNOWN";
}
}
/* State Transition macro */
#define CSR_NEIGHBOR_ROAM_STATE_TRANSITION(newState)\
{\
pMac->roam.neighborRoamInfo.prevNeighborRoamState = pMac->roam.neighborRoamInfo.neighborRoamState;\
pMac->roam.neighborRoamInfo.neighborRoamState = newState;\
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, \
FL("Neighbor Roam Transition from state %s ==> %s"), \
csrNeighborRoamStateToString (pMac->roam.neighborRoamInfo.prevNeighborRoamState), \
csrNeighborRoamStateToString (newState));\
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamFreeNeighborRoamBSSNode
\brief This function frees all the internal pointers CSR NeighborRoam BSS Info
and also frees the node itself
\param pMac - The handle returned by macOpen.
neighborRoamBSSNode - Neighbor Roam BSS Node to be freed
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamFreeNeighborRoamBSSNode(tpAniSirGlobal pMac, tpCsrNeighborRoamBSSInfo neighborRoamBSSNode)
{
if (neighborRoamBSSNode)
{
if (neighborRoamBSSNode->pBssDescription)
{
vos_mem_free(neighborRoamBSSNode->pBssDescription);
neighborRoamBSSNode->pBssDescription = NULL;
}
vos_mem_free(neighborRoamBSSNode);
neighborRoamBSSNode = NULL;
}
return;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamRemoveRoamableAPListEntry
\brief This function removes a given entry from the given list
\param pMac - The handle returned by macOpen.
pList - The list from which the entry should be removed
pNeighborEntry - Neighbor Roam BSS Node to be removed
\return TRUE if successfully removed, else FALSE
---------------------------------------------------------------------------*/
tANI_BOOLEAN csrNeighborRoamRemoveRoamableAPListEntry(tpAniSirGlobal pMac,
tDblLinkList *pList, tpCsrNeighborRoamBSSInfo pNeighborEntry)
{
if(pList)
{
return csrLLRemoveEntry(pList, &pNeighborEntry->List, LL_ACCESS_LOCK);
}
smsLog(pMac, LOGE, FL("Removing neighbor BSS node from list failed. Current count = %d"), csrLLCount(pList));
return eANI_BOOLEAN_FALSE;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamGetRoamableAPListNextEntry
\brief Gets the entry next to passed entry. If NULL is passed, return the entry in the head of the list
\param pMac - The handle returned by macOpen.
pList - The list from which the entry should be returned
pNeighborEntry - Neighbor Roam BSS Node whose next entry should be returned
\return Neighbor Roam BSS Node to be returned
---------------------------------------------------------------------------*/
tpCsrNeighborRoamBSSInfo csrNeighborRoamGetRoamableAPListNextEntry(tpAniSirGlobal pMac,
tDblLinkList *pList, tpCsrNeighborRoamBSSInfo pNeighborEntry)
{
tListElem *pEntry = NULL;
tpCsrNeighborRoamBSSInfo pResult = NULL;
if(pList)
{
if(NULL == pNeighborEntry)
{
pEntry = csrLLPeekHead(pList, LL_ACCESS_LOCK);
}
else
{
pEntry = csrLLNext(pList, &pNeighborEntry->List, LL_ACCESS_LOCK);
}
if(pEntry)
{
pResult = GET_BASE_ADDR(pEntry, tCsrNeighborRoamBSSInfo, List);
}
}
return pResult;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamFreeRoamableBSSList
\brief Empties and frees all the nodes in the roamable AP list
\param pMac - The handle returned by macOpen.
pList - Neighbor Roam BSS List to be emptied
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamFreeRoamableBSSList(tpAniSirGlobal pMac, tDblLinkList *pList)
{
tpCsrNeighborRoamBSSInfo pResult = NULL;
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Emptying the BSS list. Current count = %d"), csrLLCount(pList));
/* Pick up the head, remove and free the node till the list becomes empty */
while ((pResult = csrNeighborRoamGetRoamableAPListNextEntry(pMac, pList, NULL)) != NULL)
{
csrNeighborRoamRemoveRoamableAPListEntry(pMac, pList, pResult);
csrNeighborRoamFreeNeighborRoamBSSNode(pMac, pResult);
}
return;
}
static void csrNeighborRoamTriggerHandoff(tpAniSirGlobal pMac,
tpCsrNeighborRoamControlInfo pNeighborRoamInfo)
{
#ifdef WLAN_FEATURE_VOWIFI_11R
if ((pNeighborRoamInfo->is11rAssoc)
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
&& !csrRoamIsRoamOffloadScanEnabled(pMac)
#endif
)
{
if ((eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN == pNeighborRoamInfo->neighborRoamState) ||
(eSME_ROAM_TRIGGER_FAST_ROAM == pNeighborRoamInfo->cfgRoamEn))
{
csrNeighborRoamIssuePreauthReq(pMac);
pNeighborRoamInfo->cfgRoamEn = eSME_ROAM_TRIGGER_NONE;
vos_mem_set(&pNeighborRoamInfo->cfgRoambssId[0],
sizeof(pNeighborRoamInfo->cfgRoambssId),
0xFF);
}
else
{
smsLog(pMac, LOGE, FL("11R Reassoc indication received in unexpected state %d"), pNeighborRoamInfo->neighborRoamState);
VOS_ASSERT(0);
}
}
else
#endif
#ifdef FEATURE_WLAN_CCX
if ((pNeighborRoamInfo->isCCXAssoc)
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
&& !csrRoamIsRoamOffloadScanEnabled(pMac)
#endif
)
{
if (eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN == pNeighborRoamInfo->neighborRoamState)
{
csrNeighborRoamIssuePreauthReq(pMac);
}
else
{
smsLog(pMac, LOGE, FL("CCX Reassoc indication received in unexpected state %d"), pNeighborRoamInfo->neighborRoamState);
VOS_ASSERT(0);
}
}
else
#endif
#ifdef FEATURE_WLAN_LFR
if (csrRoamIsFastRoamEnabled(pMac, CSR_SESSION_ID_INVALID))
{
if ((eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN == pNeighborRoamInfo->neighborRoamState)
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
|| csrRoamIsRoamOffloadScanEnabled(pMac) ||
(eSME_ROAM_TRIGGER_FAST_ROAM == pNeighborRoamInfo->cfgRoamEn)
#endif
)
{
csrNeighborRoamIssuePreauthReq(pMac);
pNeighborRoamInfo->cfgRoamEn = eSME_ROAM_TRIGGER_NONE;
vos_mem_set(&pNeighborRoamInfo->cfgRoambssId[0],
sizeof(pNeighborRoamInfo->cfgRoambssId),
0xFF);
}
else
{
smsLog(pMac, LOGE, FL("LFR Reassoc indication received in unexpected state %d"), pNeighborRoamInfo->neighborRoamState);
VOS_ASSERT(0);
}
}
else
#endif
{
if (eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN == pNeighborRoamInfo->neighborRoamState)
{
csrNeighborRoamRequestHandoff(pMac);
}
else
{
smsLog(pMac, LOGE, FL("Non-11R Reassoc indication received in unexpected state %d"
" or Roaming is disabled"), pNeighborRoamInfo->neighborRoamState);
}
}
}
VOS_STATUS csrNeighborRoamUpdateFastRoamingEnabled(tpAniSirGlobal pMac, const v_BOOL_t fastRoamEnabled)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
if (eCSR_NEIGHBOR_ROAM_STATE_CONNECTED == pNeighborRoamInfo->neighborRoamState)
{
if (VOS_TRUE == fastRoamEnabled)
{
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (pMac->roam.configParam.isRoamOffloadScanEnabled)
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_START, REASON_CONNECT);
} else {
#endif
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Registering neighbor lookup DOWN event with TL, RSSI = %d"),
pNeighborRoamInfo->currentNeighborLookupThreshold);
/* Register Neighbor Lookup threshold callback with TL for DOWN event only */
vosStatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext, (v_S7_t)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamNeighborLookupDOWNCallback,
VOS_MODULE_ID_SME, pMac);
if (!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGE, FL(" Couldn't register csrNeighborRoamNeighborLookupDOWNCallback with TL: Status = %d"), vosStatus);
vosStatus = VOS_STATUS_E_FAILURE;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
}
else if (VOS_FALSE == fastRoamEnabled)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Currently in CONNECTED state, so deregister all events"));
/* De-register existing lookup UP/DOWN, Rssi indications */
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (pMac->roam.configParam.isRoamOffloadScanEnabled)
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_STOP, REASON_DISCONNECTED);
} else {
#endif
csrNeighborRoamDeregAllRssiIndication(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
}
}
else if (eCSR_NEIGHBOR_ROAM_STATE_INIT == pNeighborRoamInfo->neighborRoamState)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Currently in INIT state, Nothing to do"));
}
else
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Unexpected state %d, returning failure"), pNeighborRoamInfo->neighborRoamState);
vosStatus = VOS_STATUS_E_FAILURE;
}
return vosStatus;
}
#ifdef FEATURE_WLAN_CCX
VOS_STATUS csrNeighborRoamUpdateCcxModeEnabled(tpAniSirGlobal pMac, const v_BOOL_t ccxMode)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
if (eCSR_NEIGHBOR_ROAM_STATE_CONNECTED == pNeighborRoamInfo->neighborRoamState)
{
if (VOS_TRUE == ccxMode)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Registering neighbor lookup DOWN event with TL, RSSI = %d"),
pNeighborRoamInfo->currentNeighborLookupThreshold);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (pMac->roam.configParam.isRoamOffloadScanEnabled)
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_START, REASON_CONNECT);
} else {
#endif
/* Register Neighbor Lookup threshold callback with TL for DOWN event only */
vosStatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext, (v_S7_t)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamNeighborLookupDOWNCallback,
VOS_MODULE_ID_SME, pMac);
if (!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGE, FL(" Couldn't register csrNeighborRoamNeighborLookupDOWNCallback with TL: Status = %d"), vosStatus);
vosStatus = VOS_STATUS_E_FAILURE;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
}
else if (VOS_FALSE == ccxMode)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Currently in CONNECTED state, so deregister all events"));
/* De-register existing lookup UP/DOWN, Rssi indications */
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (pMac->roam.configParam.isRoamOffloadScanEnabled)
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_STOP, REASON_DISCONNECTED);
} else {
#endif
csrNeighborRoamDeregAllRssiIndication(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
}
}
else if (eCSR_NEIGHBOR_ROAM_STATE_INIT == pNeighborRoamInfo->neighborRoamState)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Currently in INIT state, Nothing to do"));
}
else
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Unexpected state %d, returning failure"), pNeighborRoamInfo->neighborRoamState);
vosStatus = VOS_STATUS_E_FAILURE;
}
return vosStatus;
}
#endif
VOS_STATUS csrNeighborRoamSetLookupRssiThreshold(tpAniSirGlobal pMac, v_U8_t neighborLookupRssiThreshold)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
if (eCSR_NEIGHBOR_ROAM_STATE_CONNECTED == pNeighborRoamInfo->neighborRoamState)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Currently in CONNECTED state, so deregister all and re-register for DOWN event again"));
pMac->roam.neighborRoamInfo.cfgParams.neighborLookupThreshold = neighborLookupRssiThreshold;
pNeighborRoamInfo->currentNeighborLookupThreshold = pMac->roam.neighborRoamInfo.cfgParams.neighborLookupThreshold;
/* De-register existing lookup UP/DOWN, Rssi indications */
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (pMac->roam.configParam.isRoamOffloadScanEnabled)
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_LOOKUP_THRESH_CHANGED);
}
else
{
#endif
csrNeighborRoamDeregAllRssiIndication(pMac);
NEIGHBOR_ROAM_DEBUG(pMac, LOG2,
FL("Registering neighbor lookup DOWN event with TL, RSSI = %d"),
pNeighborRoamInfo->currentNeighborLookupThreshold);
/* Register Neighbor Lookup threshold callback with TL for DOWN event only */
vosStatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamNeighborLookupDOWNCallback,
VOS_MODULE_ID_SME, pMac);
if (!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGE, FL(" Couldn't register csrNeighborRoamNeighborLookupDOWNCallback with TL: Status = %d"), vosStatus);
vosStatus = VOS_STATUS_E_FAILURE;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
}
else if (eCSR_NEIGHBOR_ROAM_STATE_INIT == pNeighborRoamInfo->neighborRoamState)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Currently in INIT state, safe to set lookupRssi threshold"));
pMac->roam.neighborRoamInfo.cfgParams.neighborLookupThreshold = neighborLookupRssiThreshold;
pNeighborRoamInfo->currentNeighborLookupThreshold = pMac->roam.neighborRoamInfo.cfgParams.neighborLookupThreshold;
}
else
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Unexpected state %d, returning failure"), pNeighborRoamInfo->neighborRoamState);
vosStatus = VOS_STATUS_E_FAILURE;
}
return vosStatus;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamReassocIndCallback
\brief Reassoc callback invoked by TL on crossing the registered re-assoc threshold.
Directly triggere HO in case of non-11r association
In case of 11R association, triggers a pre-auth eventually followed by actual HO
\param pAdapter - VOS Context
trafficStatus - UP/DOWN indication from TL
pUserCtxt - Parameter for callback registered during callback registration. Should be pMac
\return VOID
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamReassocIndCallback(v_PVOID_t pAdapter,
v_U8_t trafficStatus,
v_PVOID_t pUserCtxt,
v_S7_t avgRssi)
{
tpAniSirGlobal pMac = PMAC_STRUCT( pUserCtxt );
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
if (eSME_ROAM_TRIGGER_FAST_ROAM != pNeighborRoamInfo->cfgRoamEn)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Deregistering DOWN event reassoc callback with TL. Threshold RSSI = %d Reported RSSI = %d"),
pNeighborRoamInfo->cfgParams.neighborReassocThreshold * (-1),
avgRssi);
vosStatus = WLANTL_DeregRSSIIndicationCB(pMac->roam.gVosContext, (v_S7_t)pNeighborRoamInfo->cfgParams.neighborReassocThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamReassocIndCallback,
VOS_MODULE_ID_SME);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGW, FL(" Couldn't deregister csrNeighborRoamReassocIndCallback with TL: Status = %d"), vosStatus);
}
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Rcvd reassoc notification-deregister UP indication. Threshold RSSI = %d Reported RSSI = %d"),
NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1), avgRssi);
vosStatus = WLANTL_DeregRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1),
WLANTL_HO_THRESHOLD_UP,
csrNeighborRoamNeighborLookupUPCallback,
VOS_MODULE_ID_SME);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGW, FL(" Couldn't deregister csrNeighborRoamNeighborLookupUPCallback with TL: Status = %d"), vosStatus);
}
}
/* We dont need to run this timer any more. */
vos_timer_stop(&pNeighborRoamInfo->neighborResultsRefreshTimer);
vos_timer_stop(&pNeighborRoamInfo->emptyScanRefreshTimer);
csrNeighborRoamTriggerHandoff(pMac, pNeighborRoamInfo);
return VOS_STATUS_SUCCESS;
}
/*CleanUP Routines*/
static void csrNeighborRoamResetChannelInfo(tpCsrNeighborRoamChannelInfo rChInfo)
{
if ((rChInfo->IAPPNeighborListReceived == FALSE) &&
(rChInfo->currentChannelListInfo.numOfChannels))
{
rChInfo->currentChanIndex = CSR_NEIGHBOR_ROAM_INVALID_CHANNEL_INDEX;
rChInfo->currentChannelListInfo.numOfChannels = 0;
if (rChInfo->currentChannelListInfo.ChannelList)
vos_mem_free(rChInfo->currentChannelListInfo.ChannelList);
rChInfo->currentChannelListInfo.ChannelList = NULL;
rChInfo->chanListScanInProgress = eANI_BOOLEAN_FALSE;
}
else
{
rChInfo->currentChanIndex = 0;
rChInfo->chanListScanInProgress = eANI_BOOLEAN_TRUE;
}
}
static void csrNeighborRoamResetCfgListChanScanControlInfo(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
/* Stop neighbor scan timer */
vos_timer_stop(&pNeighborRoamInfo->neighborScanTimer);
/* Stop neighbor scan results refresh timer */
vos_timer_stop(&pNeighborRoamInfo->neighborResultsRefreshTimer);
/* Stop empty scan results refresh timer */
vos_timer_stop(&pNeighborRoamInfo->emptyScanRefreshTimer);
/* Abort any ongoing scan */
if (eANI_BOOLEAN_TRUE == pNeighborRoamInfo->scanRspPending)
{
csrScanAbortMacScan(pMac, eCSR_SCAN_ABORT_DEFAULT);
}
pNeighborRoamInfo->scanRspPending = eANI_BOOLEAN_FALSE;
/* Reset roam channel list information */
csrNeighborRoamResetChannelInfo(&pNeighborRoamInfo->roamChannelInfo);
}
static void csrNeighborRoamResetPreauthControlInfo(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
#if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
pNeighborRoamInfo->is11rAssoc = eANI_BOOLEAN_FALSE;
/* Purge pre-auth fail list */
csrNeighborRoamPurgePreauthFailedList(pMac);
#endif
pNeighborRoamInfo->FTRoamInfo.preauthRspPending = eANI_BOOLEAN_FALSE;
pNeighborRoamInfo->FTRoamInfo.numPreAuthRetries = 0;
#ifdef WLAN_FEATURE_VOWIFI_11R
/* Do not free up the preauth done list here */
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum = 0;
pNeighborRoamInfo->FTRoamInfo.neighborRptPending = eANI_BOOLEAN_FALSE;
pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport = 0;
vos_mem_zero(pNeighborRoamInfo->FTRoamInfo.neighboReportBssInfo, sizeof(tCsrNeighborReportBssInfo) * MAX_BSS_IN_NEIGHBOR_RPT);
#endif
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
pNeighborRoamInfo->uOsRequestedHandoff = 0;
vos_mem_zero(&pNeighborRoamInfo->handoffReqInfo, sizeof(tCsrHandoffRequest));
#endif
}
static void csrNeighborRoamDeregAllRssiIndication(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
NEIGHBOR_ROAM_DEBUG(pMac, LOG2,
FL("Deregister neighbor lookup UP callback with TL. RSSI = %d"),
NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1));
/* Deregister reassoc callback. Ignore return status */
vosStatus = WLANTL_DeregRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1),
WLANTL_HO_THRESHOLD_UP,
csrNeighborRoamNeighborLookupUPCallback,
VOS_MODULE_ID_SME);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
smsLog(pMac, LOGW,
FL("Couldn't deregister csrNeighborRoamNeighborLookupUPCallback "
"with TL: Status = %d"), vosStatus);
}
NEIGHBOR_ROAM_DEBUG(pMac, LOG2,
FL("Deregistering reassoc DOWN callback with TL. RSSI = %d"),
pNeighborRoamInfo->cfgParams.neighborReassocThreshold * (-1));
/* Deregister reassoc callback. Ignore return status */
vosStatus = WLANTL_DeregRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)pNeighborRoamInfo->cfgParams.neighborReassocThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamReassocIndCallback,
VOS_MODULE_ID_SME);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
smsLog(pMac, LOGW,
FL(" Couldn't deregister csrNeighborRoamReassocIndCallback with "
"TL: Status = %d"), vosStatus);
}
NEIGHBOR_ROAM_DEBUG(pMac, LOG2,
FL("Deregistering neighborLookup DOWN callback with TL. RSSI = %d"),
pNeighborRoamInfo->currentNeighborLookupThreshold * (-1));
/* Deregister neighbor lookup callback. Ignore return status */
vosStatus = WLANTL_DeregRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamNeighborLookupDOWNCallback,
VOS_MODULE_ID_SME);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
smsLog(pMac, LOGW,
FL(" Couldn't deregister csrNeighborRoamNeighborLookupDOWNCallback "
"with TL: Status = %d"), vosStatus);
}
/* Reset thresholds only after deregistering DOWN event from TL */
pNeighborRoamInfo->currentNeighborLookupThreshold =
pNeighborRoamInfo->cfgParams.neighborLookupThreshold;
#ifdef FEATURE_WLAN_LFR
pNeighborRoamInfo->uEmptyScanCount = 0;
pNeighborRoamInfo->lookupDOWNRssi = 0;
pNeighborRoamInfo->uScanMode = DEFAULT_SCAN;
#endif
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamResetConnectedStateControlInfo
\brief This function will reset the neighbor roam control info data structures.
This function should be invoked whenever we move to CONNECTED state from
any state other than INIT state
\param pMac - The handle returned by macOpen.
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamResetConnectedStateControlInfo(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
csrNeighborRoamResetChannelInfo(&pNeighborRoamInfo->roamChannelInfo);
csrNeighborRoamFreeRoamableBSSList(pMac, &pNeighborRoamInfo->roamableAPList);
/* We dont need to run this timer any more. */
vos_timer_stop(&pNeighborRoamInfo->neighborResultsRefreshTimer);
vos_timer_stop(&pNeighborRoamInfo->emptyScanRefreshTimer);
#ifdef WLAN_FEATURE_VOWIFI_11R
/* Do not free up the preauth done list here */
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum = 0;
pNeighborRoamInfo->FTRoamInfo.neighborRptPending = eANI_BOOLEAN_FALSE;
pNeighborRoamInfo->FTRoamInfo.numPreAuthRetries = 0;
pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport = 0;
pNeighborRoamInfo->FTRoamInfo.preauthRspPending = 0;
vos_mem_zero(pNeighborRoamInfo->FTRoamInfo.neighboReportBssInfo, sizeof(tCsrNeighborReportBssInfo) * MAX_BSS_IN_NEIGHBOR_RPT);
#endif
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
pNeighborRoamInfo->uOsRequestedHandoff = 0;
vos_mem_zero(&pNeighborRoamInfo->handoffReqInfo, sizeof(tCsrHandoffRequest));
#endif
}
void csrNeighborRoamResetReportScanStateControlInfo(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
pNeighborRoamInfo->csrSessionId = CSR_SESSION_ID_INVALID;
vos_mem_set(pNeighborRoamInfo->currAPbssid, sizeof(tCsrBssid), 0);
pNeighborRoamInfo->neighborScanTimerInfo.pMac = pMac;
pNeighborRoamInfo->neighborScanTimerInfo.sessionId = CSR_SESSION_ID_INVALID;
#ifdef FEATURE_WLAN_CCX
pNeighborRoamInfo->isCCXAssoc = eANI_BOOLEAN_FALSE;
pNeighborRoamInfo->isVOAdmitted = eANI_BOOLEAN_FALSE;
pNeighborRoamInfo->MinQBssLoadRequired = 0;
#endif
/* Stop scan refresh timer */
vos_timer_stop(&pNeighborRoamInfo->neighborResultsRefreshTimer);
/* Stop empty scan results refresh timer */
vos_timer_stop(&pNeighborRoamInfo->emptyScanRefreshTimer);
/* Purge roamable AP list */
csrNeighborRoamFreeRoamableBSSList(pMac, &pNeighborRoamInfo->roamableAPList);
return;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamResetInitStateControlInfo
\brief This function will reset the neighbor roam control info data structures.
This function should be invoked whenever we move to CONNECTED state from
INIT state
\param pMac - The handle returned by macOpen.
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamResetInitStateControlInfo(tpAniSirGlobal pMac)
{
csrNeighborRoamResetConnectedStateControlInfo(pMac);
/* In addition to the above resets, we should clear off the curAPBssId/Session ID in the timers */
csrNeighborRoamResetReportScanStateControlInfo(pMac);
}
#ifdef WLAN_FEATURE_VOWIFI_11R
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamBssIdScanFilter
\brief This API is used to prepare a filter to obtain scan results when
we complete the scan in the REPORT_SCAN state after receiving a
valid neighbor report from AP. This filter includes BSSIDs received from
the neighbor report from the AP in addition to the other filter parameters
created from connected profile
\param pMac - The handle returned by macOpen.
pScanFilter - Scan filter to be filled and returned
\return eHAL_STATUS_SUCCESS on succesful filter creation, corresponding error
code otherwise
---------------------------------------------------------------------------*/
static eHalStatus csrNeighborRoamBssIdScanFilter(tpAniSirGlobal pMac, tCsrScanResultFilter *pScanFilter)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tANI_U8 i = 0;
VOS_ASSERT(pScanFilter != NULL);
if (pScanFilter == NULL)
return eHAL_STATUS_FAILURE;
vos_mem_zero(pScanFilter, sizeof(tCsrScanResultFilter));
pScanFilter->BSSIDs.numOfBSSIDs = pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport;
pScanFilter->BSSIDs.bssid = vos_mem_malloc(sizeof(tSirMacAddr) * pScanFilter->BSSIDs.numOfBSSIDs);
if (NULL == pScanFilter->BSSIDs.bssid)
{
smsLog(pMac, LOGE, FL("Scan Filter BSSID mem alloc failed"));
return eHAL_STATUS_FAILED_ALLOC;
}
vos_mem_zero(pScanFilter->BSSIDs.bssid, sizeof(tSirMacAddr) * pScanFilter->BSSIDs.numOfBSSIDs);
/* Populate the BSSID from Neighbor BSS info received from neighbor report */
for (i = 0; i < pScanFilter->BSSIDs.numOfBSSIDs; i++)
{
vos_mem_copy(&pScanFilter->BSSIDs.bssid[i],
pNeighborRoamInfo->FTRoamInfo.neighboReportBssInfo[i].neighborBssId, sizeof(tSirMacAddr));
}
/* Fill other general scan filter params */
return csrNeighborRoamPrepareScanProfileFilter(pMac, pScanFilter);
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamPurgePreauthFailList
\brief This function empties the preauth fail list
\param pMac - The handle returned by macOpen.
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamPurgePreauthFailList(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Purging the preauth fail list"));
while (pNeighborRoamInfo->FTRoamInfo.preAuthFailList.numMACAddress)
{
vos_mem_zero(pNeighborRoamInfo->FTRoamInfo.preAuthFailList.macAddress[pNeighborRoamInfo->FTRoamInfo.preAuthFailList.numMACAddress-1],
sizeof(tSirMacAddr));
pNeighborRoamInfo->FTRoamInfo.preAuthFailList.numMACAddress--;
}
return;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamAddBssIdToPreauthFailList
\brief This function adds the given BSSID to the Preauth fail list
\param pMac - The handle returned by macOpen.
bssId - BSSID to be added to the preauth fail list
\return eHAL_STATUS_SUCCESS on success, eHAL_STATUS_FAILURE otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamAddBssIdToPreauthFailList(tpAniSirGlobal pMac, tSirMacAddr bssId)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL(" Added BSSID "MAC_ADDRESS_STR" to Preauth failed list"),
MAC_ADDR_ARRAY(bssId));
if ((pNeighborRoamInfo->FTRoamInfo.preAuthFailList.numMACAddress + 1) >
MAX_NUM_PREAUTH_FAIL_LIST_ADDRESS)
{
smsLog(pMac, LOGE, FL("Preauth fail list already full.. Cannot add new one"));
return eHAL_STATUS_FAILURE;
}
vos_mem_copy(pNeighborRoamInfo->FTRoamInfo.preAuthFailList.macAddress[pNeighborRoamInfo->FTRoamInfo.preAuthFailList.numMACAddress],
bssId, sizeof(tSirMacAddr));
pNeighborRoamInfo->FTRoamInfo.preAuthFailList.numMACAddress++;
return eHAL_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamIsPreauthCandidate
\brief This function checks whether the given MAC address is already
present in the preauth fail list and returns TRUE/FALSE accordingly
\param pMac - The handle returned by macOpen.
\return eANI_BOOLEAN_TRUE if preauth candidate, eANI_BOOLEAN_FALSE otherwise
---------------------------------------------------------------------------*/
tANI_BOOLEAN csrNeighborRoamIsPreauthCandidate(tpAniSirGlobal pMac, tSirMacAddr bssId)
{
tANI_U8 i = 0;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (csrRoamIsRoamOffloadScanEnabled(pMac))
{
return eANI_BOOLEAN_TRUE;
}
#endif
if (0 == pNeighborRoamInfo->FTRoamInfo.preAuthFailList.numMACAddress)
return eANI_BOOLEAN_TRUE;
for (i = 0; i < pNeighborRoamInfo->FTRoamInfo.preAuthFailList.numMACAddress; i++)
{
if (VOS_TRUE == vos_mem_compare(pNeighborRoamInfo->FTRoamInfo.preAuthFailList.macAddress[i],
bssId, sizeof(tSirMacAddr)))
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("BSSID "MAC_ADDRESS_STR" already present in preauth fail list"),
MAC_ADDR_ARRAY(bssId));
return eANI_BOOLEAN_FALSE;
}
}
return eANI_BOOLEAN_TRUE;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamIssuePreauthReq
\brief This function issues preauth request to PE with the 1st AP entry in the
roamable AP list
\param pMac - The handle returned by macOpen.
\return eHAL_STATUS_SUCCESS on success, eHAL_STATUS_FAILURE otherwise
---------------------------------------------------------------------------*/
static eHalStatus csrNeighborRoamIssuePreauthReq(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
tpCsrNeighborRoamBSSInfo pNeighborBssNode;
/* This must not be true here */
VOS_ASSERT(pNeighborRoamInfo->FTRoamInfo.preauthRspPending == eANI_BOOLEAN_FALSE);
/* Issue Preauth request to PE here */
/* Need to issue the preauth request with the BSSID that is there in the head of the roamable AP list */
/* Parameters that should be passed are BSSID, Channel number and the neighborScanPeriod(probably) */
/* If roamableAPList gets empty, should transition to REPORT_SCAN state */
pNeighborBssNode = csrNeighborRoamGetRoamableAPListNextEntry(pMac, &pNeighborRoamInfo->roamableAPList, NULL);
if (NULL == pNeighborBssNode)
{
smsLog(pMac, LOGW, FL("Roamable AP list is empty.. "));
return eHAL_STATUS_FAILURE;
}
else
{
status = csrRoamEnqueuePreauth(pMac, pNeighborRoamInfo->csrSessionId, pNeighborBssNode->pBssDescription,
eCsrPerformPreauth, eANI_BOOLEAN_TRUE);
smsLog(pMac, LOG1, FL("Before Pre-Auth: BSSID "MAC_ADDRESS_STR", Ch:%d"),
MAC_ADDR_ARRAY(pNeighborBssNode->pBssDescription->bssId),
(int)pNeighborBssNode->pBssDescription->channelId);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("Send Preauth request to PE failed with status %d"), status);
return status;
}
}
pNeighborRoamInfo->FTRoamInfo.preauthRspPending = eANI_BOOLEAN_TRUE;
/* Increment the preauth retry count */
pNeighborRoamInfo->FTRoamInfo.numPreAuthRetries++;
/* Transition the state to preauthenticating */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_PREAUTHENTICATING)
return status;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamPreauthRspHandler
\brief This function handle the Preauth response from PE
Every preauth is allowed max 3 tries if it fails. If a bssid failed
for more than MAX_TRIES, we will remove it from the list and try
with the next node in the roamable AP list and add the BSSID to pre-auth failed
list. If no more entries present in
roamable AP list, transition to REPORT_SCAN state
\param pMac - The handle returned by macOpen.
limStatus - eSIR_SUCCESS/eSIR_FAILURE/eSIR_LIM_MAX_STA_REACHED_ERROR/
eSIT_LIM_AUTH_RSP_TIMEOUT status from PE
\return eHAL_STATUS_SUCCESS on success (i.e. pre-auth processed),
eHAL_STATUS_FAILURE otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamPreauthRspHandler(tpAniSirGlobal pMac, tSirRetStatus limStatus)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
eHalStatus preauthProcessed = eHAL_STATUS_SUCCESS;
tpCsrNeighborRoamBSSInfo pPreauthRspNode = NULL;
if (eANI_BOOLEAN_FALSE == pNeighborRoamInfo->FTRoamInfo.preauthRspPending)
{
/* This can happen when we disconnect immediately
* after sending a pre-auth request. During processing
* of the disconnect command, we would have reset
* preauthRspPending and transitioned to INIT state.
*/
NEIGHBOR_ROAM_DEBUG(pMac, LOGW,
FL("Unexpected pre-auth response in state %d"),
pNeighborRoamInfo->neighborRoamState);
preauthProcessed = eHAL_STATUS_FAILURE;
goto DEQ_PREAUTH;
}
// We can receive it in these 2 states.
if ((pNeighborRoamInfo->neighborRoamState != eCSR_NEIGHBOR_ROAM_STATE_PREAUTHENTICATING) &&
(pNeighborRoamInfo->neighborRoamState != eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN))
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("Preauth response received in state %d"),
pNeighborRoamInfo->neighborRoamState);
preauthProcessed = eHAL_STATUS_FAILURE;
goto DEQ_PREAUTH;
}
pNeighborRoamInfo->FTRoamInfo.preauthRspPending = eANI_BOOLEAN_FALSE;
if (eSIR_SUCCESS == limStatus)
{
pPreauthRspNode = csrNeighborRoamGetRoamableAPListNextEntry(pMac, &pNeighborRoamInfo->roamableAPList, NULL);
}
if ((eSIR_SUCCESS == limStatus) && (NULL != pPreauthRspNode))
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Preauth completed successfully after %d tries"), pNeighborRoamInfo->FTRoamInfo.numPreAuthRetries);
smsLog(pMac, LOG1, FL("After Pre-Auth: BSSID "MAC_ADDRESS_STR", Ch:%d"),
MAC_ADDR_ARRAY(pPreauthRspNode->pBssDescription->bssId),
(int)pPreauthRspNode->pBssDescription->channelId);
/* Preauth competer successfully. Insert the preauthenticated node to tail of preAuthDoneList */
csrNeighborRoamRemoveRoamableAPListEntry(pMac, &pNeighborRoamInfo->roamableAPList, pPreauthRspNode);
csrLLInsertTail(&pNeighborRoamInfo->FTRoamInfo.preAuthDoneList, &pPreauthRspNode->List, LL_ACCESS_LOCK);
/* Pre-auth completed successfully. Transition to PREAUTH Done state */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE)
pNeighborRoamInfo->FTRoamInfo.numPreAuthRetries = 0;
/* The caller of this function would start a timer and by the time it expires, supplicant should
have provided the updated FTIEs to SME. So, when it expires, handoff will be triggered then */
}
else
{
tpCsrNeighborRoamBSSInfo pNeighborBssNode = NULL;
tListElem *pEntry;
smsLog(pMac, LOGE, FL("Preauth failed retry number %d, status = 0x%x"),
pNeighborRoamInfo->FTRoamInfo.numPreAuthRetries, limStatus);
/* Preauth failed. Add the bssId to the preAuth failed list MAC Address. Also remove the AP from roamable AP list */
if ((pNeighborRoamInfo->FTRoamInfo.numPreAuthRetries >=
CSR_NEIGHBOR_ROAM_MAX_NUM_PREAUTH_RETRIES) ||
(eSIR_LIM_MAX_STA_REACHED_ERROR == limStatus))
{
/* We are going to remove the node as it fails for more than MAX tries. Reset this count to 0 */
pNeighborRoamInfo->FTRoamInfo.numPreAuthRetries = 0;
/* The one in the head of the list should be one with which we issued pre-auth and failed */
pEntry = csrLLRemoveHead(&pNeighborRoamInfo->roamableAPList, LL_ACCESS_LOCK);
if(pEntry)
{
pNeighborBssNode = GET_BASE_ADDR(pEntry, tCsrNeighborRoamBSSInfo, List);
/* Add the BSSID to pre-auth fail list if it is not requested by HDD */
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if(!pNeighborRoamInfo->uOsRequestedHandoff)
#endif
{
status = csrNeighborRoamAddBssIdToPreauthFailList(pMac, pNeighborBssNode->pBssDescription->bssId);
}
/* Now we can free this node */
csrNeighborRoamFreeNeighborRoamBSSNode(pMac, pNeighborBssNode);
}
}
/* Issue preauth request for the same/next entry */
if (eHAL_STATUS_SUCCESS == csrNeighborRoamIssuePreauthReq(pMac))
goto DEQ_PREAUTH;
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (csrRoamIsRoamOffloadScanEnabled(pMac))
{
if(pNeighborRoamInfo->uOsRequestedHandoff)
{
pNeighborRoamInfo->uOsRequestedHandoff = 0;
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_START, REASON_PREAUTH_FAILED_FOR_ALL);
}
else
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_RESTART, REASON_PREAUTH_FAILED_FOR_ALL);
}
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_CONNECTED);
} else
{
#endif
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN);
/* Register Neighbor Lookup threshold callback with TL for UP event now */
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("No more pre-auth candidates-"
"register UP indication with TL. RSSI = %d,"), NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1));
vosStatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1),
WLANTL_HO_THRESHOLD_UP,
csrNeighborRoamNeighborLookupUPCallback,
VOS_MODULE_ID_SME, pMac);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGE, FL(" Couldn't register csrNeighborRoamNeighborLookupCallback UP event with TL: Status = %d"), status);
}
/* Start the neighbor results refresh timer and transition to REPORT_SCAN state to perform scan again */
status = vos_timer_start(&pNeighborRoamInfo->neighborResultsRefreshTimer,
pNeighborRoamInfo->cfgParams.neighborResultsRefreshPeriod);
if ( status != eHAL_STATUS_SUCCESS )
{
smsLog(pMac, LOGE, FL("Neighbor results refresh timer start failed with status %d"), status);
}
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
DEQ_PREAUTH:
csrRoamDequeuePreauth(pMac);
return preauthProcessed;
}
#endif /* WLAN_FEATURE_NEIGHBOR_ROAMING */
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamPrepareScanProfileFilter
\brief This function creates a scan filter based on the currently connected profile.
Based on this filter, scan results are obtained
\param pMac - The handle returned by macOpen.
pScanFilter - Populated scan filter based on the connected profile
\return eHAL_STATUS_SUCCESS on success, eHAL_STATUS_FAILURE otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamPrepareScanProfileFilter(tpAniSirGlobal pMac, tCsrScanResultFilter *pScanFilter)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tANI_U8 sessionId = (tANI_U8)pNeighborRoamInfo->csrSessionId;
tCsrRoamConnectedProfile *pCurProfile = &pMac->roam.roamSession[sessionId].connectedProfile;
tANI_U8 i = 0;
VOS_ASSERT(pScanFilter != NULL);
if (pScanFilter == NULL)
return eHAL_STATUS_FAILURE;
vos_mem_zero(pScanFilter, sizeof(tCsrScanResultFilter));
/* We dont want to set BSSID based Filter */
pScanFilter->BSSIDs.numOfBSSIDs = 0;
//only for HDD requested handoff fill in the BSSID in the filter
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (pNeighborRoamInfo->uOsRequestedHandoff)
{
pScanFilter->BSSIDs.numOfBSSIDs = 1;
pScanFilter->BSSIDs.bssid = vos_mem_malloc(sizeof(tSirMacAddr) * pScanFilter->BSSIDs.numOfBSSIDs);
if (NULL == pScanFilter->BSSIDs.bssid)
{
smsLog(pMac, LOGE, FL("Scan Filter BSSID mem alloc failed"));
return eHAL_STATUS_FAILED_ALLOC;
}
vos_mem_zero(pScanFilter->BSSIDs.bssid, sizeof(tSirMacAddr) * pScanFilter->BSSIDs.numOfBSSIDs);
/* Populate the BSSID from handoff info received from HDD */
for (i = 0; i < pScanFilter->BSSIDs.numOfBSSIDs; i++)
{
vos_mem_copy(&pScanFilter->BSSIDs.bssid[i],
pNeighborRoamInfo->handoffReqInfo.bssid, sizeof(tSirMacAddr));
}
}
#endif
/* Populate all the information from the connected profile */
pScanFilter->SSIDs.numOfSSIDs = 1;
pScanFilter->SSIDs.SSIDList = vos_mem_malloc(sizeof(tCsrSSIDInfo));
if (NULL == pScanFilter->SSIDs.SSIDList)
{
smsLog(pMac, LOGE, FL("Scan Filter SSID mem alloc failed"));
return eHAL_STATUS_FAILED_ALLOC;
}
pScanFilter->SSIDs.SSIDList->handoffPermitted = 1;
pScanFilter->SSIDs.SSIDList->ssidHidden = 0;
pScanFilter->SSIDs.SSIDList->SSID.length = pCurProfile->SSID.length;
vos_mem_copy((void *)pScanFilter->SSIDs.SSIDList->SSID.ssId, (void *)pCurProfile->SSID.ssId, pCurProfile->SSID.length);
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Filtering for SSID %.*s from scan results,"
"length of SSID = %u"),
pScanFilter->SSIDs.SSIDList->SSID.length,
pScanFilter->SSIDs.SSIDList->SSID.ssId,
pScanFilter->SSIDs.SSIDList->SSID.length);
pScanFilter->authType.numEntries = 1;
pScanFilter->authType.authType[0] = pCurProfile->AuthType;
pScanFilter->EncryptionType.numEntries = 1; //This must be 1
pScanFilter->EncryptionType.encryptionType[0] = pCurProfile->EncryptionType;
pScanFilter->mcEncryptionType.numEntries = 1;
pScanFilter->mcEncryptionType.encryptionType[0] = pCurProfile->mcEncryptionType;
pScanFilter->BSSType = pCurProfile->BSSType;
/* We are intrested only in the scan results on channels that we scanned */
pScanFilter->ChannelInfo.numOfChannels = pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels;
pScanFilter->ChannelInfo.ChannelList = vos_mem_malloc(pScanFilter->ChannelInfo.numOfChannels * sizeof(tANI_U8));
if (NULL == pScanFilter->ChannelInfo.ChannelList)
{
smsLog(pMac, LOGE, FL("Scan Filter Channel list mem alloc failed"));
vos_mem_free(pScanFilter->SSIDs.SSIDList);
pScanFilter->SSIDs.SSIDList = NULL;
return eHAL_STATUS_FAILED_ALLOC;
}
for (i = 0; i < pScanFilter->ChannelInfo.numOfChannels; i++)
{
pScanFilter->ChannelInfo.ChannelList[i] = pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList[i];
}
#ifdef WLAN_FEATURE_VOWIFI_11R
if (pNeighborRoamInfo->is11rAssoc)
{
/* MDIE should be added as a part of profile. This should be added as a part of filter as well */
pScanFilter->MDID.mdiePresent = pCurProfile->MDID.mdiePresent;
pScanFilter->MDID.mobilityDomain = pCurProfile->MDID.mobilityDomain;
}
#endif
return eHAL_STATUS_SUCCESS;
}
tANI_U32 csrGetCurrentAPRssi(tpAniSirGlobal pMac, tScanResultHandle *pScanResultList)
{
tCsrScanResultInfo *pScanResult;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
#ifdef FEATURE_WLAN_LFR
tANI_U32 CurrAPRssi = pNeighborRoamInfo->lookupDOWNRssi;
#else
/* We are setting this as default value to make sure we return this value,
when we do not see this AP in the scan result for some reason.However,it is
less likely that we are associated to an AP and do not see it in the scan list */
tANI_U32 CurrAPRssi = -125;
#endif
while (NULL != (pScanResult = csrScanResultGetNext(pMac, *pScanResultList)))
{
if (VOS_TRUE == vos_mem_compare(pScanResult->BssDescriptor.bssId,
pNeighborRoamInfo->currAPbssid, sizeof(tSirMacAddr)))
{
/* We got a match with the currently associated AP.
* Capture the RSSI value and complete the while loop.
* The while loop is completed in order to make the current entry go back to NULL,
* and in the next while loop, it properly starts searching from the head of the list.
* TODO: Can also try setting the current entry directly to NULL as soon as we find the new AP*/
CurrAPRssi = (int)pScanResult->BssDescriptor.rssi * (-1) ;
} else {
continue;
}
}
return CurrAPRssi;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamProcessScanResults
\brief This function extracts scan results, sorts on the basis of neighbor score(todo).
Assumed that the results are already sorted by RSSI by csrScanGetResult
\param pMac - The handle returned by macOpen.
pScanResultList - Scan result result obtained from csrScanGetResult()
\return tANI_BOOLEAN - return TRUE if we have a candidate we can immediately
roam to. Otherwise, return FALSE.
---------------------------------------------------------------------------*/
static tANI_BOOLEAN csrNeighborRoamProcessScanResults(tpAniSirGlobal pMac,
tScanResultHandle *pScanResultList)
{
tCsrScanResultInfo *pScanResult;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tpCsrNeighborRoamBSSInfo pBssInfo;
tANI_U32 CurrAPRssi;
tANI_U8 RoamRssiDiff = pMac->roam.configParam.RoamRssiDiff;
#if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
tANI_U8 immediateRoamRssiDiff = pMac->roam.configParam.nImmediateRoamRssiDiff;
#endif
tANI_BOOLEAN roamNow = eANI_BOOLEAN_FALSE;
/***************************************************************
* Find out the Current AP RSSI and keep it handy to check if
* it is better than the RSSI of the AP which we are
* going to roam.If so, we are going to continue with the
* current AP.
***************************************************************/
CurrAPRssi = csrGetCurrentAPRssi(pMac, pScanResultList);
/* Expecting the scan result already to be in the sorted order based on the RSSI */
/* Based on the previous state we need to check whether the list should be sorted again taking neighbor score into consideration */
/* If previous state is CFG_CHAN_LIST_SCAN, there should not be any neighbor score associated with any of the BSS.
If the previous state is REPORT_QUERY, then there will be neighbor score for each of the APs */
/* For now, let us take the top of the list provided as it is by the CSR Scan result API. This means it is assumed that neighbor score
and rssi score are in the same order. This will be taken care later */
while (NULL != (pScanResult = csrScanResultGetNext(pMac, *pScanResultList)))
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG,
FL("Scan result: BSSID "MAC_ADDRESS_STR" (Rssi %ld, Ch:%d)"),
MAC_ADDR_ARRAY(pScanResult->BssDescriptor.bssId),
abs(pScanResult->BssDescriptor.rssi),
pScanResult->BssDescriptor.channelId);
if ((VOS_TRUE == vos_mem_compare(pScanResult->BssDescriptor.bssId,
pNeighborRoamInfo->currAPbssid, sizeof(tSirMacAddr))) ||
((eSME_ROAM_TRIGGER_SCAN == pNeighborRoamInfo->cfgRoamEn) &&
(VOS_TRUE != vos_mem_compare(pScanResult->BssDescriptor.bssId,
pNeighborRoamInfo->cfgRoambssId, sizeof(tSirMacAddr)))))
{
/* currently associated AP. Do not have this in the roamable AP list */
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"SKIP-currently associated AP");
continue;
}
#ifdef FEATURE_WLAN_LFR
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
/* In case of reassoc requested by upper layer, look for exact match of bssid & channel;
csr cache might have duplicates*/
if ((pNeighborRoamInfo->uOsRequestedHandoff) &&
((VOS_FALSE == vos_mem_compare(pScanResult->BssDescriptor.bssId,
pNeighborRoamInfo->handoffReqInfo.bssid,
sizeof(tSirMacAddr)))||
(pScanResult->BssDescriptor.channelId != pNeighborRoamInfo->handoffReqInfo.channel)))
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"SKIP-not a candidate AP for OS requested roam");
continue;
}
#endif
#endif
/* This condition is to ensure to roam to an AP with better RSSI. if the value of RoamRssiDiff is Zero, this feature
* is disabled and we continue to roam without any check*/
if ((RoamRssiDiff > 0)
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
&& !csrRoamIsRoamOffloadScanEnabled(pMac)
#endif
&& ((eSME_ROAM_TRIGGER_SCAN != pNeighborRoamInfo->cfgRoamEn) ||
(eSME_ROAM_TRIGGER_FAST_ROAM != pNeighborRoamInfo->cfgRoamEn)))
{
/*
* If RSSI is lower than the lookup threshold, then continue.
*/
if (abs(pScanResult->BssDescriptor.rssi) >
pNeighborRoamInfo->currentNeighborLookupThreshold)
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG] new ap rssi (%d) lower than lookup threshold (%d)",
__func__, (int)pScanResult->BssDescriptor.rssi * (-1),
(int)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1));
continue;
}
if (abs(CurrAPRssi) < abs(pScanResult->BssDescriptor.rssi))
{
/*Do not roam to an AP with worse RSSI than the current*/
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG]Current AP rssi=%d new ap rssi worse=%d", __func__,
CurrAPRssi,
(int)pScanResult->BssDescriptor.rssi * (-1) );
continue;
} else {
/*Do not roam to an AP which is having better RSSI than the current AP, but still less than the
* margin that is provided by user from the ini file (RoamRssiDiff)*/
if (abs(abs(CurrAPRssi) - abs(pScanResult->BssDescriptor.rssi)) < RoamRssiDiff)
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG]Current AP rssi=%d new ap rssi=%d not good enough, roamRssiDiff=%d", __func__,
CurrAPRssi,
(int)pScanResult->BssDescriptor.rssi * (-1),
RoamRssiDiff);
continue;
}
else {
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG]Current AP rssi=%d new ap rssi better=%d", __func__,
CurrAPRssi,
(int)pScanResult->BssDescriptor.rssi * (-1) );
}
}
}
#ifdef WLAN_FEATURE_VOWIFI_11R
if (pNeighborRoamInfo->is11rAssoc)
{
if (!csrNeighborRoamIsPreauthCandidate(pMac, pScanResult->BssDescriptor.bssId))
{
smsLog(pMac, LOGE, FL("BSSID present in pre-auth fail list.. Ignoring"));
continue;
}
}
#endif /* WLAN_FEATURE_VOWIFI_11R */
#ifdef FEATURE_WLAN_CCX
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (!csrRoamIsRoamOffloadScanEnabled(pMac))
{
#endif
if (pNeighborRoamInfo->isCCXAssoc)
{
if (!csrNeighborRoamIsPreauthCandidate(pMac, pScanResult->BssDescriptor.bssId))
{
smsLog(pMac, LOGE, FL("BSSID present in pre-auth fail list.. Ignoring"));
continue;
}
}
if ((pScanResult->BssDescriptor.QBSSLoad_present) &&
(pScanResult->BssDescriptor.QBSSLoad_avail))
{
if (pNeighborRoamInfo->isVOAdmitted)
{
smsLog(pMac, LOG1, FL("New AP has %x BW available"), (unsigned int)pScanResult->BssDescriptor.QBSSLoad_avail);
smsLog(pMac, LOG1, FL("We need %x BW available"),(unsigned int)pNeighborRoamInfo->MinQBssLoadRequired);
if (pScanResult->BssDescriptor.QBSSLoad_avail < pNeighborRoamInfo->MinQBssLoadRequired)
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"[INFOLOG]BSSID : "MAC_ADDRESS_STR" has no bandwidth ignoring..not adding to roam list",
MAC_ADDR_ARRAY(pScanResult->BssDescriptor.bssId));
continue;
}
}
}
else
{
smsLog(pMac, LOGE, FL("No QBss %x %x"), (unsigned int)pScanResult->BssDescriptor.QBSSLoad_avail, (unsigned int)pScanResult->BssDescriptor.QBSSLoad_present);
if (pNeighborRoamInfo->isVOAdmitted)
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"[INFOLOG]BSSID : "MAC_ADDRESS_STR" has no QBSSLoad IE, ignoring..not adding to roam list",
MAC_ADDR_ARRAY(pScanResult->BssDescriptor.bssId));
continue;
}
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
#endif /* FEATURE_WLAN_CCX */
#ifdef FEATURE_WLAN_LFR
// If we are supporting legacy roaming, and
// if the candidate is on the "pre-auth failed" list, ignore it.
if (csrRoamIsFastRoamEnabled(pMac, CSR_SESSION_ID_INVALID))
{
if (!csrNeighborRoamIsPreauthCandidate(pMac, pScanResult->BssDescriptor.bssId))
{
smsLog(pMac, LOGE, FL("BSSID present in pre-auth fail list.. Ignoring"));
continue;
}
}
#endif /* FEATURE_WLAN_LFR */
/* If the received timestamp in BSS description is earlier than the scan request timestamp, skip
* this result */
if ((pNeighborRoamInfo->scanRequestTimeStamp >= pScanResult->BssDescriptor.nReceivedTime)
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
&& !csrRoamIsRoamOffloadScanEnabled(pMac)
#endif
)
{
smsLog(pMac, LOGE, FL("Ignoring BSS as it is older than the scan request timestamp"));
continue;
}
pBssInfo = vos_mem_malloc(sizeof(tCsrNeighborRoamBSSInfo));
if (NULL == pBssInfo)
{
smsLog(pMac, LOGE, FL("Memory allocation for Neighbor Roam BSS Info failed.. Just ignoring"));
continue;
}
pBssInfo->pBssDescription = vos_mem_malloc(pScanResult->BssDescriptor.length + sizeof(pScanResult->BssDescriptor.length));
if (pBssInfo->pBssDescription != NULL)
{
vos_mem_copy(pBssInfo->pBssDescription, &pScanResult->BssDescriptor,
pScanResult->BssDescriptor.length + sizeof(pScanResult->BssDescriptor.length));
}
else
{
smsLog(pMac, LOGE, FL("Memory allocation for Neighbor Roam BSS Descriptor failed.. Just ignoring"));
vos_mem_free(pBssInfo);
continue;
}
pBssInfo->apPreferenceVal = 10; //some value for now. Need to calculate the actual score based on RSSI and neighbor AP score
/* Just add to the end of the list as it is already sorted by RSSI */
csrLLInsertTail(&pNeighborRoamInfo->roamableAPList, &pBssInfo->List, LL_ACCESS_LOCK);
#if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
if ((eSME_ROAM_TRIGGER_SCAN == pNeighborRoamInfo->cfgRoamEn) ||
(eSME_ROAM_TRIGGER_FAST_ROAM == pNeighborRoamInfo->cfgRoamEn))
{
roamNow = eANI_BOOLEAN_FALSE;
}
else if ((abs(abs(CurrAPRssi) - abs(pScanResult->BssDescriptor.rssi)) >= immediateRoamRssiDiff)
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
&& !csrRoamIsRoamOffloadScanEnabled(pMac)
#endif
)
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG] potential candidate to roam immediately (diff=%d, expected=%d)",
__func__, abs(abs(CurrAPRssi) - abs(pScanResult->BssDescriptor.rssi)),
immediateRoamRssiDiff);
roamNow = eANI_BOOLEAN_TRUE;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
/* If we are here means, FW already found candidates to roam, so we are
good to go with pre-auth */
if(csrRoamIsRoamOffloadScanEnabled(pMac))
{
roamNow = eANI_BOOLEAN_TRUE;
}
#endif
#endif
}
/* Now we have all the scan results in our local list. Good time to free up the the list we got as a part of csrGetScanResult */
csrScanResultPurge(pMac, *pScanResultList);
return roamNow;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamHandleEmptyScanResult
\brief This function will be invoked in CFG_CHAN_LIST_SCAN state when
there are no valid APs in the scan result for roaming. This means
our AP is the best and no other AP is around. No point in scanning
again and again. Performing the following here.
1. Stop the neighbor scan timer.
2a. If this is the first time we encountered empty scan, then
re-register with TL with modified lookup threshold.
2b. Else if this is the second time we encountered empty scan,
then start neighbor scan results refresh timer (20s).
2c. Else, nothing more to do.
NOTE: In LFR, channels selected for scanning is dervied from
the occuped channel list. Scan cycle following one which
yielded empty results is split into two halves: (i) scan on
channels in the occupied list, and (ii) scan on channels not
in the occupied list. This helps converging faster (while
looking for candidates in the occupied list first), and also,
adds channels to the occupied channel list upon finding candidates
matching SSID profile of interest.
uEmptyScanCount Comments
eFirstEmptyScan Previous scan was done on channels in the
occupied list and yielded potential candidates.
This scan cycle was likely triggered through
receipt of lookup DOWN notification event.
eSecondEmptyScan Previous scan was done on channels in the
occupied list and yielded no candidates. This scan
cycle was triggered through RSSI notification
with modified lookup threshold.
eThirdEmptyScan Previous scan was done on channels NOT in
the occupied list and yielded no candidates. This
scan cycle was triggered immediately after scanning
channels in the occupied list and no candidates
were found.
eFourthEmptyScan Previous scan was done on channels in the
occupied list and yielded no candidates. This scan
cycle was triggered upon expiry of
neighborScanResultsRefreshPeriod (=20s).
eFifthEmptyScan Previous scan was done on channels NOT in
the occupied list and yielded no candidates. This
scan cycle was triggered immediately after scanning
channels in the occupied list and no candidates
were found.
[1], [2,3] and [4,5] together form one discrete set of scan cycle.
\param pMac - The handle returned by macOpen.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
static VOS_STATUS csrNeighborRoamHandleEmptyScanResult(tpAniSirGlobal pMac)
{
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
#ifdef FEATURE_WLAN_LFR
tANI_BOOLEAN performPeriodicScan =
(pNeighborRoamInfo->cfgParams.emptyScanRefreshPeriod) ? TRUE : FALSE;
#endif
/* Stop neighbor scan timer */
vos_timer_stop(&pNeighborRoamInfo->neighborScanTimer);
/*
* Increase the neighbor lookup threshold by 3 dB
* after every scan cycle. NOTE: uEmptyScanCount
* would be either 1, 3 or 5 at the end of every
* scan cycle.
*/
#ifdef FEATURE_WLAN_LFR
if ((++pNeighborRoamInfo->uEmptyScanCount) > eFifthEmptyScan)
{
pNeighborRoamInfo->uEmptyScanCount = eFifthEmptyScan;
}
if (((0 != pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels) ||
(abs(pNeighborRoamInfo->lookupDOWNRssi) >
abs(pNeighborRoamInfo->cfgParams.neighborReassocThreshold))) &&
((pNeighborRoamInfo->uEmptyScanCount == eSecondEmptyScan) ||
(pNeighborRoamInfo->uEmptyScanCount == eFourthEmptyScan)))
{
/*
* If the scan was triggered due to lookupDOWNRssi > reassoc threshold,
* then it would be a contiguous scan on all valid non-DFS channels.
* If channels are configured in INI, then only those channels need
* to be scanned.
* In either of these modes, there is no need to trigger an immediate
* scan upon empty scan results for the second and fourth time (which
* would be equivalent to scanning on channels in non-occupied list).
* Incrementing uEmptyScanCount will correspond to skipping this step.
* NOTE: double increment of uEmptyScanCount corresponds to completion
* of scans on all valid channels.
*/
++pNeighborRoamInfo->uEmptyScanCount;
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, "Extra increment of empty scan count (=%d)"
" in contiguous scan mode", pNeighborRoamInfo->uEmptyScanCount);
}
#endif
if (((pNeighborRoamInfo->currentNeighborLookupThreshold+3) <
pNeighborRoamInfo->cfgParams.neighborReassocThreshold)
#ifdef FEATURE_WLAN_LFR
&& ((pNeighborRoamInfo->uEmptyScanCount % 2) == 1)
#endif
)
{
pNeighborRoamInfo->currentNeighborLookupThreshold += 3;
}
#ifdef WLAN_FEATURE_VOWIFI_11R
/* Clear off the old neighbor report details */
vos_mem_zero(&pNeighborRoamInfo->FTRoamInfo.neighboReportBssInfo, sizeof(tCsrNeighborReportBssInfo) * MAX_BSS_IN_NEIGHBOR_RPT);
#endif
/* Transition to CONNECTED state */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_CONNECTED);
/* Reset all the necessary variables before transitioning to the CONNECTED state */
csrNeighborRoamResetConnectedStateControlInfo(pMac);
#ifdef FEATURE_WLAN_LFR
if (pNeighborRoamInfo->uEmptyScanCount == eFirstEmptyScan)
{
#endif
/* Empty scan results for the first time */
/* Re-register neighbor lookup DOWN threshold callback with TL */
NEIGHBOR_ROAM_DEBUG(pMac, LOGE,
FL("Registering DOWN event neighbor lookup callback with TL for RSSI = %d"),
pNeighborRoamInfo->currentNeighborLookupThreshold * (-1));
vosStatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamNeighborLookupDOWNCallback,
VOS_MODULE_ID_SME, pMac);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
smsLog(pMac, LOGW,
FL("Couldn't re-register csrNeighborRoamNeighborLookupDOWNCallback"
" with TL: Status = %d"), status);
}
#ifdef FEATURE_WLAN_LFR
pNeighborRoamInfo->lookupDOWNRssi = 0;
}
else if ((pNeighborRoamInfo->uEmptyScanCount == eSecondEmptyScan) ||
(pNeighborRoamInfo->uEmptyScanCount == eFourthEmptyScan))
{
/* Empty scan results for the second or fourth time */
/* Immediately scan on channels in non-occupied list */
csrNeighborRoamTransitToCFGChanScan(pMac);
}
else if (pNeighborRoamInfo->uEmptyScanCount >= eThirdEmptyScan)
{
/* Empty scan results for the third time */
if (performPeriodicScan)
{
smsLog(pMac, LOGE, FL("Performing periodic scan, uEmptyScanCount=%d"),
pNeighborRoamInfo->uEmptyScanCount);
/*
* Set uEmptyScanCount to MAX so that we always enter this
* condition on subsequent empty scan results
*/
pNeighborRoamInfo->uEmptyScanCount = eMaxEmptyScan;
/* From here on, ONLY scan on channels in the occupied list */
pNeighborRoamInfo->uScanMode = SPLIT_SCAN_OCCUPIED_LIST;
/* Start empty scan refresh timer */
if (VOS_STATUS_SUCCESS !=
vos_timer_start(&pNeighborRoamInfo->emptyScanRefreshTimer,
pNeighborRoamInfo->cfgParams.emptyScanRefreshPeriod))
{
smsLog(pMac, LOGE, FL("Empty scan refresh timer failed to start (%d)"),
status);
vos_mem_free(pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList);
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = 0;
vosStatus = VOS_STATUS_E_FAILURE;
}
else
{
smsLog(pMac, LOGE, FL("Empty scan refresh timer started (%ld ms)"),
(pNeighborRoamInfo->cfgParams.emptyScanRefreshPeriod));
}
}
else if (eThirdEmptyScan == pNeighborRoamInfo->uEmptyScanCount)
{
/* Start neighbor scan results refresh timer */
if (VOS_STATUS_SUCCESS !=
vos_timer_start(&pNeighborRoamInfo->neighborResultsRefreshTimer,
pNeighborRoamInfo->cfgParams.neighborResultsRefreshPeriod))
{
smsLog(pMac, LOGE, FL("Neighbor results refresh timer failed to start (%d)"),
status);
vos_mem_free(pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList);
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = 0;
vosStatus = VOS_STATUS_E_FAILURE;
}
else
{
smsLog(pMac, LOG2, FL("Neighbor results refresh timer started (%ld ms)"),
(pNeighborRoamInfo->cfgParams.neighborResultsRefreshPeriod * PAL_TIMER_TO_MS_UNIT));
}
}
}
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, "Neighbor roam empty scan count=%d scan mode=%d",
pNeighborRoamInfo->uEmptyScanCount, pNeighborRoamInfo->uScanMode);
#endif
return vosStatus;
}
static eHalStatus csrNeighborRoamProcessScanComplete (tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tCsrScanResultFilter scanFilter;
tScanResultHandle scanResult;
tANI_U32 tempVal = 0;
tANI_BOOLEAN roamNow = eANI_BOOLEAN_FALSE;
eHalStatus hstatus;
#if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
/* If the state is REPORT_SCAN, then this must be the scan after the REPORT_QUERY state. So, we
should use the BSSID filter made out of neighbor reports */
if ((eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN == pNeighborRoamInfo->neighborRoamState)
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
&& (!csrRoamIsRoamOffloadScanEnabled(pMac))
#endif
)
{
hstatus = csrNeighborRoamBssIdScanFilter(pMac, &scanFilter);
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("11R or CCX Association: Prepare scan filter status with neighbor AP = %d"), hstatus);
tempVal = 1;
}
else
#endif
{
hstatus = csrNeighborRoamPrepareScanProfileFilter(pMac, &scanFilter);
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("11R/CCX/Other Association: Prepare scan to find neighbor AP filter status = %d"), hstatus);
}
if (eHAL_STATUS_SUCCESS != hstatus)
{
smsLog(pMac, LOGE, FL("Scan Filter preparation failed for Assoc type %d.. Bailing out.."), tempVal);
return eHAL_STATUS_FAILURE;
}
hstatus = csrScanGetResult(pMac, &scanFilter, &scanResult);
if (hstatus != eHAL_STATUS_SUCCESS)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Get Scan Result status code %d"), hstatus);
}
/* Process the scan results and update roamable AP list */
roamNow = csrNeighborRoamProcessScanResults(pMac, &scanResult);
/* Free the scan filter */
csrFreeScanFilter(pMac, &scanFilter);
tempVal = csrLLCount(&pNeighborRoamInfo->roamableAPList);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if(!csrRoamIsRoamOffloadScanEnabled(pMac))
{
#endif
switch(pNeighborRoamInfo->neighborRoamState)
{
case eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN:
if (tempVal)
{
#ifdef FEATURE_WLAN_LFR
/*
* Since there are non-zero candidates found
* after the scan, reset empty scan count.
*/
pNeighborRoamInfo->uEmptyScanCount = 0;
pNeighborRoamInfo->uScanMode = DEFAULT_SCAN;
#endif
#ifdef WLAN_FEATURE_VOWIFI_11R
/* If this is a non-11r association, then we can register the reassoc callback here as we have some
APs in the roamable AP list */
if (pNeighborRoamInfo->is11rAssoc)
{
/* Valid APs are found after scan. Now we can initiate pre-authentication */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN)
}
else
#endif
#ifdef FEATURE_WLAN_CCX
/* If this is a non-11r association, then we can register the reassoc callback here as we have some
APs in the roamable AP list */
if (pNeighborRoamInfo->isCCXAssoc)
{
/* Valid APs are found after scan. Now we can initiate pre-authentication */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN)
}
else
#endif
#ifdef FEATURE_WLAN_LFR
/* If LFR is enabled, then we can register the reassoc callback here as we have some
APs in the roamable AP list */
if (csrRoamIsFastRoamEnabled(pMac, CSR_SESSION_ID_INVALID))
{
/* Valid APs are found after scan. Now we can initiate pre-authentication */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN)
}
else
#endif
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Completed scanning of CFG CHAN LIST in non-11r association. Registering reassoc callback"));
/* Nothing much to do now. Will continue to remain in this state in case of non-11r association */
/* Stop the timer. But how long the roamable AP list will be valid in here. At some point of time, we
need to restart the CFG CHAN list scan procedure if reassoc callback is not invoked from TL
within certain duration */
// vos_timer_stop(&pNeighborRoamInfo->neighborScanTimer);
}
}
else
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("No candidate found after scanning in state %d.. "), pNeighborRoamInfo->neighborRoamState);
/* Handle it appropriately */
csrNeighborRoamHandleEmptyScanResult(pMac);
}
break;
#ifdef WLAN_FEATURE_VOWIFI_11R
case eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN:
if (!tempVal)
{
smsLog(pMac, LOGE, FL("No candidate found after scanning in state %d.. "), pNeighborRoamInfo->neighborRoamState);
/* Stop the timer here as the same timer will be started again in CFG_CHAN_SCAN_STATE */
csrNeighborRoamTransitToCFGChanScan(pMac);
}
break;
#endif /* WLAN_FEATURE_VOWIFI_11R */
default:
// Can come only in INIT state. Where in we are associated, we sent scan and user
// in the meantime decides to disassoc, we will be in init state and still received call
// back issued. Should not come here in any other state, printing just in case
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG] State %d", __func__, (pNeighborRoamInfo->neighborRoamState));
// Lets just exit out silently.
return eHAL_STATUS_SUCCESS;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
if (tempVal)
{
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
if (roamNow)
{
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if(!csrRoamIsRoamOffloadScanEnabled(pMac))
{
#endif
NEIGHBOR_ROAM_DEBUG(pMac, LOG2,
FL("Immediate roam-deregister UP indication. RSSI = %d"),
NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1));
vosStatus = WLANTL_DeregRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1),
WLANTL_HO_THRESHOLD_UP,
csrNeighborRoamNeighborLookupUPCallback,
VOS_MODULE_ID_SME);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
smsLog(pMac, LOGW,
FL("Couldn't deregister lookup UP callback with TL: Status = %d"), vosStatus);
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
csrNeighborRoamTriggerHandoff(pMac, pNeighborRoamInfo);
return eHAL_STATUS_SUCCESS;
}
hstatus = vos_timer_start(&pNeighborRoamInfo->neighborResultsRefreshTimer,
pNeighborRoamInfo->cfgParams.neighborResultsRefreshPeriod);
/* This timer should be started before registering the Reassoc callback with TL. This is because, it is very likely
* that the callback getting called immediately and the timer would never be stopped when pre-auth is in progress */
if( hstatus != eHAL_STATUS_SUCCESS)
{
smsLog(pMac, LOGE, FL("Neighbor results refresh timer failed to start, status = %d"), hstatus);
vos_mem_free(pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList);
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = 0;
return eHAL_STATUS_FAILURE;
}
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Registering DOWN event Reassoc callback with TL. RSSI = %d"), pNeighborRoamInfo->cfgParams.neighborReassocThreshold * (-1));
/* Register a reassoc Indication callback */
vosStatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext, (v_S7_t)pNeighborRoamInfo->cfgParams.neighborReassocThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamReassocIndCallback,
VOS_MODULE_ID_SME, pMac);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGW, FL(" Couldn't register csrNeighborRoamReassocIndCallback with TL: Status = %d"), vosStatus);
}
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (csrRoamIsRoamOffloadScanEnabled(pMac))
{
if (!tempVal || !roamNow)
{
if (pNeighborRoamInfo->uOsRequestedHandoff)
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_START, REASON_NO_CAND_FOUND_OR_NOT_ROAMING_NOW);
pNeighborRoamInfo->uOsRequestedHandoff = 0;
}
else
{
/* There is no candidate or We are not roaming Now.
* Inform the FW to restart Roam Offload Scan */
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_RESTART, REASON_NO_CAND_FOUND_OR_NOT_ROAMING_NOW);
}
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_CONNECTED);
}
}
#endif
return eHAL_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamScanRequestCallback
\brief This function is the callback function registered in csrScanRequest() to
indicate the completion of scan. If scan is completed for all the channels in
the channel list, this function gets the scan result and starts the refresh results
timer to avoid having stale results. If scan is not completed on all the channels,
it restarts the neighbor scan timer which on expiry issues scan on the next
channel
\param halHandle - The handle returned by macOpen.
pContext - not used
scanId - not used
status - not used
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
static eHalStatus csrNeighborRoamScanRequestCallback(tHalHandle halHandle, void *pContext,
tANI_U32 scanId, eCsrScanStatus status)
{
tpAniSirGlobal pMac = (tpAniSirGlobal) halHandle;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tANI_U8 currentChanIndex;
eHalStatus hstatus;
#ifdef FEATURE_WLAN_LFR
tANI_U32 sessionId = CSR_SESSION_ID_INVALID;
if (NULL != pContext)
{
sessionId = *((tANI_U32*)pContext);
if (!csrRoamIsStaMode(pMac, sessionId))
{
smsLog(pMac, LOGE, FL("%s: Ignoring scan request callback on non-infra session %d in state %d"),
__FUNCTION__, sessionId, pNeighborRoamInfo->neighborRoamState);
vos_mem_free(pContext);
return eHAL_STATUS_SUCCESS;
}
if (!csrRoamIsFastRoamEnabled(pMac,sessionId))
{
smsLog(pMac, LOGE, FL("Received when fast roam is disabled. Ignore it"));
vos_mem_free(pContext);
return eHAL_STATUS_SUCCESS;
}
}
#endif
pMac->roam.neighborRoamInfo.scanRspPending = eANI_BOOLEAN_FALSE;
/* This can happen when we receive a UP event from TL in any of the scan states. Silently ignore it */
if (eCSR_NEIGHBOR_ROAM_STATE_CONNECTED == pNeighborRoamInfo->neighborRoamState)
{
smsLog(pMac, LOGE, FL("Received in CONNECTED state. Must be because a UP event from TL after issuing scan request. Ignore it"));
if (NULL != pContext)
vos_mem_free(pContext);
return eHAL_STATUS_SUCCESS;
}
/* -1 is done because the chanIndex would have got incremented after issuing a successful scan request */
currentChanIndex = (pMac->roam.neighborRoamInfo.roamChannelInfo.currentChanIndex) ? (pMac->roam.neighborRoamInfo.roamChannelInfo.currentChanIndex - 1) : 0;
/* Validate inputs */
if (pMac->roam.neighborRoamInfo.roamChannelInfo.currentChannelListInfo.ChannelList) {
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("csrNeighborRoamScanRequestCallback received for Channel = %d, ChanIndex = %d"),
pMac->roam.neighborRoamInfo.roamChannelInfo.currentChannelListInfo.ChannelList[currentChanIndex], currentChanIndex);
}
else
{
smsLog(pMac, LOG1, FL("Received during clean-up. Silently ignore scan completion event."));
if (NULL != pContext)
vos_mem_free(pContext);
return eHAL_STATUS_SUCCESS;
}
if (eANI_BOOLEAN_FALSE == pNeighborRoamInfo->roamChannelInfo.chanListScanInProgress)
{
/* Scan is completed in the CFG_CHAN_SCAN state. We can transition to REPORT_SCAN state
just to get the results and perform PREAUTH */
/* Now we have completed scanning the channel list. We have get the result by applying appropriate filter
sort the results based on neighborScore and RSSI and select the best candidate out of the list */
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("Channel list scan completed. Current chan index = %d"), currentChanIndex);
VOS_ASSERT(pNeighborRoamInfo->roamChannelInfo.currentChanIndex == 0);
hstatus = csrNeighborRoamProcessScanComplete(pMac);
if (eHAL_STATUS_SUCCESS != hstatus)
{
smsLog(pMac, LOGE, FL("Neighbor scan process complete failed with status %d"), hstatus);
if (NULL != pContext)
vos_mem_free(pContext);
return eHAL_STATUS_FAILURE;
}
}
else
{
/* Restart the timer for the next scan sequence as scanning is not over */
hstatus = vos_timer_start(&pNeighborRoamInfo->neighborScanTimer,
pNeighborRoamInfo->cfgParams.neighborScanPeriod);
if (eHAL_STATUS_SUCCESS != hstatus)
{
/* Timer start failed.. Should we ASSERT here??? */
smsLog(pMac, LOGE, FL("Neighbor scan PAL Timer start failed, status = %d, Ignoring state transition"), status);
vos_mem_free(pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList);
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = 0;
if (NULL != pContext)
vos_mem_free(pContext);
return eHAL_STATUS_FAILURE;
}
}
if (NULL != pContext)
vos_mem_free(pContext);
return eHAL_STATUS_SUCCESS;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamScanResultRequestCallback
\brief This function is the callback function registered in csrScanRequestLfrResult() to
indicate the completion of scan. If scan is completed for all the channels in
the channel list, this function gets the scan result and treats them as candidates
\param halHandle - The handle returned by macOpen.
pContext - not used
scanId - not used
status - not used
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
static eHalStatus csrNeighborRoamScanResultRequestCallback(tHalHandle halHandle, void *pContext,
tANI_U32 scanId, eCsrScanStatus status)
{
tpAniSirGlobal pMac = (tpAniSirGlobal) halHandle;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus hstatus;
smsLog(pMac, LOG2, FL("called "));
pMac->roam.neighborRoamInfo.scanRspPending = eANI_BOOLEAN_FALSE;
/* we must be in connected state, if not ignore it */
if (eCSR_NEIGHBOR_ROAM_STATE_CONNECTED != pNeighborRoamInfo->neighborRoamState)
{
smsLog(pMac, LOGW, FL("Received in not CONNECTED state. Ignore it"));
return eHAL_STATUS_SUCCESS;
}
/* Now we have completed scanning the channel list. We have get the result by applying appropriate filter
sort the results based on neighborScore and RSSI and select the best candidate out of the list */
hstatus = csrNeighborRoamProcessScanComplete(pMac);
if (eHAL_STATUS_SUCCESS != hstatus)
{
smsLog(pMac, LOGE, FL("Neighbor scan process complete failed with status %d"), hstatus);
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
#endif //WLAN_FEATURE_ROAM_SCAN_OFFLOAD
#ifdef FEATURE_WLAN_LFR
static eHalStatus csrNeighborRoamContiguousScanRequestCallback(tHalHandle halHandle,
void *pContext, tANI_U32 scanId, eCsrScanStatus status)
{
tpAniSirGlobal pMac = (tpAniSirGlobal) halHandle;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus hstatus = eHAL_STATUS_SUCCESS;
tANI_U32 sessionId = CSR_SESSION_ID_INVALID;
if (NULL != pContext)
{
sessionId = *((tANI_U32*)pContext);
if (!csrRoamIsFastRoamEnabled(pMac,sessionId))
{
smsLog(pMac, LOGE, FL("Received when fast roam is disabled. Ignore it"));
vos_mem_free(pContext);
return eHAL_STATUS_SUCCESS;
}
}
pMac->roam.neighborRoamInfo.scanRspPending = eANI_BOOLEAN_FALSE;
/* This can happen when we receive a UP event from TL in any of the scan states. Silently ignore it */
if (eCSR_NEIGHBOR_ROAM_STATE_CONNECTED == pNeighborRoamInfo->neighborRoamState)
{
smsLog(pMac, LOGE, FL("Received in CONNECTED state. Must be because a UP event from TL after issuing scan request. Ignore it"));
if (NULL != pContext)
vos_mem_free(pContext);
return eHAL_STATUS_SUCCESS;
}
if (eCSR_NEIGHBOR_ROAM_STATE_INIT == pNeighborRoamInfo->neighborRoamState)
{
smsLog(pMac, LOGE, FL("Received in INIT state. Must have disconnected. Ignore it"));
if (NULL != pContext)
vos_mem_free(pContext);
return eHAL_STATUS_SUCCESS;
}
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, "%s: process scan results", __func__);
hstatus = csrNeighborRoamProcessScanComplete(pMac);
if (eHAL_STATUS_SUCCESS != hstatus)
{
smsLog(pMac, LOGE, FL("Neighbor scan process complete failed with status %d"), hstatus);
}
if (NULL != pContext)
vos_mem_free(pContext);
return hstatus;
}
#endif
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamIssueBgScanRequest
\brief This function issues CSR scan request after populating all the BG scan params
passed
\param pMac - The handle returned by macOpen.
pBgScanParams - Params that need to be populated into csr Scan request
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamIssueBgScanRequest(tpAniSirGlobal pMac,
tCsrBGScanRequest *pBgScanParams,
tANI_U32 sessionId,
csrScanCompleteCallback callbackfn)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tANI_U32 scanId;
tCsrScanRequest scanReq;
tANI_U8 channel;
void * userData = NULL;
if (1 == pBgScanParams->ChannelInfo.numOfChannels)
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("Channel = %d, ChanIndex = %d"),
pBgScanParams->ChannelInfo.ChannelList[0],
pMac->roam.neighborRoamInfo.roamChannelInfo.currentChanIndex);
//send down the scan req for 1 channel on the associated SSID
palZeroMemory(pMac->hHdd, &scanReq, sizeof(tCsrScanRequest));
/* Fill in the SSID Info */
scanReq.SSIDs.numOfSSIDs = 1;
scanReq.SSIDs.SSIDList = vos_mem_malloc(sizeof(tCsrSSIDInfo) * scanReq.SSIDs.numOfSSIDs);
if(NULL == scanReq.SSIDs.SSIDList)
{
//err msg
smsLog(pMac, LOGE, FL("Couldn't allocate memory for the SSID..Freeing memory allocated for Channel List"));
return eHAL_STATUS_FAILURE;
}
vos_mem_zero(scanReq.SSIDs.SSIDList, sizeof(tCsrSSIDInfo) * scanReq.SSIDs.numOfSSIDs);
scanReq.SSIDs.SSIDList[0].handoffPermitted = eANI_BOOLEAN_TRUE;
scanReq.SSIDs.SSIDList[0].ssidHidden = eANI_BOOLEAN_TRUE;
vos_mem_copy((void *)&scanReq.SSIDs.SSIDList[0].SSID, (void *)&pBgScanParams->SSID, sizeof(pBgScanParams->SSID));
scanReq.ChannelInfo.numOfChannels = pBgScanParams->ChannelInfo.numOfChannels;
if (1 == pBgScanParams->ChannelInfo.numOfChannels)
{
channel = pBgScanParams->ChannelInfo.ChannelList[0];
scanReq.ChannelInfo.ChannelList = &channel;
}
else
{
scanReq.ChannelInfo.ChannelList = pBgScanParams->ChannelInfo.ChannelList;
}
scanReq.BSSType = eCSR_BSS_TYPE_INFRASTRUCTURE;
scanReq.scanType = eSIR_ACTIVE_SCAN;
scanReq.requestType = eCSR_SCAN_HO_BG_SCAN;
scanReq.maxChnTime = pBgScanParams->maxChnTime;
scanReq.minChnTime = pBgScanParams->minChnTime;
userData = vos_mem_malloc(sizeof(tANI_U32));
if (NULL == userData)
{
smsLog(pMac, LOGE, FL("Failed to allocate memory for scan request"));
vos_mem_free(scanReq.SSIDs.SSIDList);
return eHAL_STATUS_FAILURE;
}
*((tANI_U32*)userData) = sessionId;
status = csrScanRequest(pMac, CSR_SESSION_ID_INVALID, &scanReq,
&scanId, callbackfn, (void *) userData);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("CSR Scan Request failed with status %d"), status);
vos_mem_free(scanReq.SSIDs.SSIDList);
vos_mem_free(userData);
return status;
}
pMac->roam.neighborRoamInfo.scanRspPending = eANI_BOOLEAN_TRUE;
vos_mem_free(scanReq.SSIDs.SSIDList);
if (1 == pBgScanParams->ChannelInfo.numOfChannels)
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Channel List Address = %08x, Actual index = %d"),
&pMac->roam.neighborRoamInfo.roamChannelInfo.currentChannelListInfo.ChannelList[0],
pMac->roam.neighborRoamInfo.roamChannelInfo.currentChanIndex);
return status;
}
static void csrNeighborRoamFillNonChannelBgScanParams (tpAniSirGlobal pMac,
tpCsrBGScanRequest bgScanParams)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tANI_U8 broadcastBssid[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
vos_mem_copy(bgScanParams->bssid, broadcastBssid, sizeof(tCsrBssid));
bgScanParams->SSID.length = pMac->roam.roamSession[pNeighborRoamInfo->csrSessionId].connectedProfile.SSID.length;
vos_mem_copy(bgScanParams->SSID.ssId,
pMac->roam.roamSession[pNeighborRoamInfo->csrSessionId].connectedProfile.SSID.ssId,
pMac->roam.roamSession[pNeighborRoamInfo->csrSessionId].connectedProfile.SSID.length);
bgScanParams->minChnTime = pNeighborRoamInfo->cfgParams.minChannelScanTime;
bgScanParams->maxChnTime = pNeighborRoamInfo->cfgParams.maxChannelScanTime;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamPerformBgScan
\brief This function is invoked on every expiry of neighborScanTimer till all
the channels in the channel list are scanned. It populates necessary
parameters for BG scan and calls appropriate AP to invoke the CSR scan
request
\param pMac - The handle returned by macOpen.
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamPerformBgScan(tpAniSirGlobal pMac, tANI_U32 sessionId)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tCsrBGScanRequest bgScanParams;
tANI_U8 channel = 0;
if (pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Channel List Address = %08x"), &pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList[0]);
}
else
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Channel List Empty"));
// Go back and restart. Mostly timer start failure has occurred.
// When timer start is declared a failure, then we delete the list.
// Should not happen now as we stop and then only start the scan timer.
// still handle the unlikely case.
csrNeighborRoamHandleEmptyScanResult(pMac);
return status;
}
/* Validate the currentChanIndex value before using it to index the ChannelList array */
if ( pNeighborRoamInfo->roamChannelInfo.currentChanIndex
> pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Invalid channel index: %d"), pNeighborRoamInfo->roamChannelInfo.currentChanIndex);
// Go back and restart.
csrNeighborRoamHandleEmptyScanResult(pMac);
return status;
}
/* Need to perform scan here before getting the list */
palZeroMemory(pMac->hHdd, &bgScanParams, sizeof(tCsrBGScanRequest));
channel = pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList[pNeighborRoamInfo->roamChannelInfo.currentChanIndex];
bgScanParams.ChannelInfo.numOfChannels = 1;
bgScanParams.ChannelInfo.ChannelList = &channel;
csrNeighborRoamFillNonChannelBgScanParams(pMac, &bgScanParams);
status = csrNeighborRoamIssueBgScanRequest(pMac, &bgScanParams,
sessionId, csrNeighborRoamScanRequestCallback);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("Issue of BG Scan request failed: Status = %d"), status);
}
pNeighborRoamInfo->roamChannelInfo.currentChanIndex++;
if (pNeighborRoamInfo->roamChannelInfo.currentChanIndex >=
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Completed scanning channels in Channel List: CurrChanIndex = %d, Num Channels = %d"),
pNeighborRoamInfo->roamChannelInfo.currentChanIndex,
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels);
/* We have completed scanning all the channels */
pNeighborRoamInfo->roamChannelInfo.currentChanIndex = 0;
/* We are no longer scanning the channel list. Next timer firing should be used to get the scan results
and select the best AP in the list */
if (eANI_BOOLEAN_TRUE == pNeighborRoamInfo->roamChannelInfo.chanListScanInProgress)
{
pNeighborRoamInfo->roamChannelInfo.chanListScanInProgress = eANI_BOOLEAN_FALSE;
}
}
if (eHAL_STATUS_SUCCESS != status)
{
/*
* If the status is not success, we need to call the callback
* routine so that the state machine does not get stuck.
*/
csrNeighborRoamScanRequestCallback(pMac, NULL, 0, eCSR_SCAN_FAILURE);
}
return status;
}
#ifdef FEATURE_WLAN_LFR
eHalStatus csrNeighborRoamPerformContiguousBgScan(tpAniSirGlobal pMac, tANI_U32 sessionId)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tCsrBGScanRequest bgScanParams;
tANI_U8 numOfChannels = 0, i = 0;
tANI_U8 *channelList = NULL;
tANI_U8 *pInChannelList = NULL;
tANI_U8 tmpChannelList[WNI_CFG_VALID_CHANNEL_LIST_LEN];
palZeroMemory(pMac->hHdd, &bgScanParams, sizeof(tCsrBGScanRequest));
/* Contiguously scan all channels from valid list */
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, "%s: get valid channel list", __func__);
numOfChannels = sizeof(pMac->roam.validChannelList);
if(!HAL_STATUS_SUCCESS(csrGetCfgValidChannels(pMac,
(tANI_U8 *)pMac->roam.validChannelList,
(tANI_U32 *) &numOfChannels)))
{
smsLog(pMac, LOGE, FL("Could not get valid channel list"));
return eHAL_STATUS_FAILURE;
}
pInChannelList = pMac->roam.validChannelList;
if (CSR_IS_ROAM_INTRA_BAND_ENABLED(pMac))
{
csrNeighborRoamChannelsFilterByCurrentBand(
pMac,
pInChannelList,
numOfChannels,
tmpChannelList,
&numOfChannels);
pInChannelList = tmpChannelList;
}
channelList = vos_mem_malloc( numOfChannels );
if( NULL == channelList )
{
smsLog(pMac, LOGE, FL("could not allocate memory for channelList"));
return eHAL_STATUS_FAILURE;
}
vos_mem_copy(channelList, (tANI_U8 *)pInChannelList,
numOfChannels * sizeof(tANI_U8));
bgScanParams.ChannelInfo.numOfChannels = numOfChannels;
bgScanParams.ChannelInfo.ChannelList = channelList;
for (i = 0; i < numOfChannels; i++)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, "%s: valid channel list = %d",
__func__, bgScanParams.ChannelInfo.ChannelList[i]);
}
csrNeighborRoamFillNonChannelBgScanParams(pMac, &bgScanParams);
status = csrNeighborRoamIssueBgScanRequest(pMac, &bgScanParams,
sessionId, csrNeighborRoamContiguousScanRequestCallback);
vos_mem_free( channelList );
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("Issue of BG Scan request failed: Status = %d"), status);
}
return status;
}
#endif
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamNeighborScanTimerCallback
\brief This function is the neighbor scan timer callback function. It invokes
the BG scan request based on the current and previous states
\param pv - CSR timer context info which includes pMac and session ID
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamNeighborScanTimerCallback(void *pv)
{
tCsrTimerInfo *pInfo = (tCsrTimerInfo *)pv;
tpAniSirGlobal pMac = pInfo->pMac;
tANI_U32 sessionId = pInfo->sessionId;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
// check if bg scan is on going, no need to send down the new params if true
if(eANI_BOOLEAN_TRUE == pNeighborRoamInfo->scanRspPending)
{
//msg
smsLog(pMac, LOGW, FL("Already BgScanRsp is Pending"));
return;
}
VOS_ASSERT(sessionId == pNeighborRoamInfo->csrSessionId);
switch (pNeighborRoamInfo->neighborRoamState)
{
#ifdef WLAN_FEATURE_VOWIFI_11R
case eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN:
switch(pNeighborRoamInfo->prevNeighborRoamState)
{
case eCSR_NEIGHBOR_ROAM_STATE_REPORT_QUERY:
csrNeighborRoamPerformBgScan(pMac, sessionId);
break;
default:
smsLog(pMac, LOGE, FL("Neighbor scan callback received in state %d, prev state = %d"),
pNeighborRoamInfo->neighborRoamState, pNeighborRoamInfo->prevNeighborRoamState);
break;
}
break;
#endif /* WLAN_FEATURE_VOWIFI_11R */
case eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN:
csrNeighborRoamPerformBgScan(pMac, sessionId);
break;
default:
break;
}
return;
}
void csrNeighborRoamEmptyScanRefreshTimerCallback(void *context)
{
tCsrTimerInfo *pInfo = (tCsrTimerInfo *)context;
tpAniSirGlobal pMac = pInfo->pMac;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
/* Reset all the variables just as no scan had happened before */
csrNeighborRoamResetConnectedStateControlInfo(pMac);
#if defined WLAN_FEATURE_VOWIFI_11R && defined WLAN_FEATURE_VOWIFI
if ((pNeighborRoamInfo->is11rAssoc) && (pMac->rrm.rrmSmeContext.rrmConfig.rrmEnabled))
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("11R Association:Neighbor Lookup Down event received in CONNECTED state"));
vosStatus = csrNeighborRoamIssueNeighborRptRequest(pMac);
if (VOS_STATUS_SUCCESS != vosStatus)
{
smsLog(pMac, LOGE, FL("Neighbor report request failed. status = %d"), vosStatus);
return;
}
/* Increment the neighbor report retry count after sending the neighbor request successfully */
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum++;
pNeighborRoamInfo->FTRoamInfo.neighborRptPending = eANI_BOOLEAN_TRUE;
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REPORT_QUERY)
}
else
#endif
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Non 11R or CCX Association:empty scan refresh timer expired"));
vosStatus = csrNeighborRoamTransitToCFGChanScan(pMac);
if (VOS_STATUS_SUCCESS != vosStatus)
{
return;
}
}
return;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamResultsRefreshTimerCallback
\brief This function is the timer callback function for results refresh timer.
When this is invoked, it is as good as down event received from TL. So,
clear off the roamable AP list and start the scan procedure based on 11R
or non-11R association
\param context - CSR timer context info which includes pMac and session ID
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamResultsRefreshTimerCallback(void *context)
{
tCsrTimerInfo *pInfo = (tCsrTimerInfo *)context;
tpAniSirGlobal pMac = pInfo->pMac;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Deregistering DOWN event reassoc callback with TL. RSSI = %d"), pNeighborRoamInfo->cfgParams.neighborReassocThreshold * (-1));
/* Deregister reassoc callback. Ignore return status */
vosStatus = WLANTL_DeregRSSIIndicationCB(pMac->roam.gVosContext, (v_S7_t)pNeighborRoamInfo->cfgParams.neighborReassocThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamReassocIndCallback,
VOS_MODULE_ID_SME);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGW, FL(" Couldn't deregister csrNeighborRoamReassocIndCallback with TL: Status = %d"), vosStatus);
}
/* Reset all the variables just as no scan had happened before */
csrNeighborRoamResetConnectedStateControlInfo(pMac);
#if defined WLAN_FEATURE_VOWIFI_11R && defined WLAN_FEATURE_VOWIFI
if ((pNeighborRoamInfo->is11rAssoc) && (pMac->rrm.rrmSmeContext.rrmConfig.rrmEnabled))
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("11R Association:Neighbor Lookup Down event received in CONNECTED state"));
vosStatus = csrNeighborRoamIssueNeighborRptRequest(pMac);
if (VOS_STATUS_SUCCESS != vosStatus)
{
smsLog(pMac, LOGE, FL("Neighbor report request failed. status = %d"), vosStatus);
return;
}
/* Increment the neighbor report retry count after sending the neighbor request successfully */
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum++;
pNeighborRoamInfo->FTRoamInfo.neighborRptPending = eANI_BOOLEAN_TRUE;
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REPORT_QUERY)
}
else
#endif
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Non 11R or CCX Association:results refresh timer expired"));
vosStatus = csrNeighborRoamTransitToCFGChanScan(pMac);
if (VOS_STATUS_SUCCESS != vosStatus)
{
return;
}
}
return;
}
#if defined WLAN_FEATURE_VOWIFI_11R && defined WLAN_FEATURE_VOWIFI
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamIssueNeighborRptRequest
\brief This function is invoked when TL issues a down event and the current assoc
is a 11R association. It invokes SME RRM API to issue the neighbor request to
the currently associated AP with the current SSID
\param pMac - The handle returned by macOpen.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamIssueNeighborRptRequest(tpAniSirGlobal pMac)
{
tRrmNeighborRspCallbackInfo callbackInfo;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tRrmNeighborReq neighborReq;
neighborReq.no_ssid = 0;
/* Fill in the SSID */
neighborReq.ssid.length = pMac->roam.roamSession[pNeighborRoamInfo->csrSessionId].connectedProfile.SSID.length;
vos_mem_copy(neighborReq.ssid.ssId, pMac->roam.roamSession[pNeighborRoamInfo->csrSessionId].connectedProfile.SSID.ssId,
pMac->roam.roamSession[pNeighborRoamInfo->csrSessionId].connectedProfile.SSID.length);
callbackInfo.neighborRspCallback = csrNeighborRoamRRMNeighborReportResult;
callbackInfo.neighborRspCallbackContext = pMac;
callbackInfo.timeout = pNeighborRoamInfo->FTRoamInfo.neighborReportTimeout;
return sme_NeighborReportRequest(pMac,(tANI_U8) pNeighborRoamInfo->csrSessionId, &neighborReq, &callbackInfo);
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamChannelsFilterByCurrentBand
\brief This function is used to filter out the channels
based on the currently associated AP channel
\param pMac - The handle returned by macOpen.
\param pInputChannelList - The input channel list
\param inputNumOfChannels - The number of channels in input channel list
\param pOutputChannelList - The output channel list
\param outputNumOfChannels - The number of channels in output channel list
\param pMergedOutputNumOfChannels - The final number of channels in the output channel list.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamChannelsFilterByCurrentBand(
tpAniSirGlobal pMac,
tANI_U8* pInputChannelList,
tANI_U8 inputNumOfChannels,
tANI_U8* pOutputChannelList,
tANI_U8* pMergedOutputNumOfChannels
)
{
tANI_U8 i = 0;
tANI_U8 numChannels = 0;
tANI_U8 currAPoperationChannel = pMac->roam.neighborRoamInfo.currAPoperationChannel;
// Check for NULL pointer
if (!pInputChannelList) return VOS_STATUS_E_INVAL;
// Check for NULL pointer
if (!pOutputChannelList) return VOS_STATUS_E_INVAL;
if (inputNumOfChannels > WNI_CFG_VALID_CHANNEL_LIST_LEN)
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR,
"%s: Wrong Number of Input Channels %d",
__func__, inputNumOfChannels);
return VOS_STATUS_E_INVAL;
}
for (i = 0; i < inputNumOfChannels; i++)
{
if (GetRFBand(currAPoperationChannel) == GetRFBand(pInputChannelList[i]))
{
pOutputChannelList[numChannels] = pInputChannelList[i];
numChannels++;
}
}
// Return final number of channels
*pMergedOutputNumOfChannels = numChannels;
return VOS_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamMergeChannelLists
\brief This function is used to merge two channel list.
NB: If called with outputNumOfChannels == 0, this routines
simply copies the input channel list to the output channel list.
\param pMac - The handle returned by macOpen.
\param pInputChannelList - The addtional channels to merge in to the "merged" channels list.
\param inputNumOfChannels - The number of additional channels.
\param pOutputChannelList - The place to put the "merged" channel list.
\param outputNumOfChannels - The original number of channels in the "merged" channels list.
\param pMergedOutputNumOfChannels - The final number of channels in the "merged" channel list.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamMergeChannelLists(
tpAniSirGlobal pMac,
tANI_U8 *pInputChannelList,
tANI_U8 inputNumOfChannels,
tANI_U8 *pOutputChannelList,
tANI_U8 outputNumOfChannels,
tANI_U8 *pMergedOutputNumOfChannels
)
{
tANI_U8 i = 0;
tANI_U8 j = 0;
tANI_U8 numChannels = outputNumOfChannels;
// Check for NULL pointer
if (!pInputChannelList) return VOS_STATUS_E_INVAL;
// Check for NULL pointer
if (!pOutputChannelList) return VOS_STATUS_E_INVAL;
if (inputNumOfChannels > WNI_CFG_VALID_CHANNEL_LIST_LEN)
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR,
"%s: Wrong Number of Input Channels %d",
__func__, inputNumOfChannels);
return VOS_STATUS_E_INVAL;
}
// Add the "new" channels in the input list to the end of the output list.
for (i = 0; i < inputNumOfChannels; i++)
{
for (j = 0; j < outputNumOfChannels; j++)
{
if (pInputChannelList[i] == pOutputChannelList[j])
break;
}
if (j == outputNumOfChannels)
{
if (pInputChannelList[i])
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG] Adding extra %d to Neighbor channel list", __func__,
pInputChannelList[i]);
pOutputChannelList[numChannels] = pInputChannelList[i];
numChannels++;
}
}
}
// Return final number of channels
*pMergedOutputNumOfChannels = numChannels;
return VOS_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamCreateChanListFromNeighborReport
\brief This function is invoked when neighbor report is received for the
neighbor request. Based on the channels present in the neighbor report,
it generates channel list which will be used in REPORT_SCAN state to
scan for these neighbor APs
\param pMac - The handle returned by macOpen.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamCreateChanListFromNeighborReport(tpAniSirGlobal pMac)
{
tpRrmNeighborReportDesc pNeighborBssDesc;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tANI_U8 numChannels = 0, i = 0;
tANI_U8 channelList[MAX_BSS_IN_NEIGHBOR_RPT];
tANI_U8 mergedOutputNumOfChannels = 0;
#if 0
eHalStatus status = eHAL_STATUS_SUCCESS;
#endif
/* This should always start from 0 whenever we create a channel list out of neighbor AP list */
pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport = 0;
pNeighborBssDesc = smeRrmGetFirstBssEntryFromNeighborCache(pMac);
while (pNeighborBssDesc)
{
if (pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport >= MAX_BSS_IN_NEIGHBOR_RPT) break;
/* Update the neighbor BSS Info in the 11r FT Roam Info */
pNeighborRoamInfo->FTRoamInfo.neighboReportBssInfo[pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport].channelNum =
pNeighborBssDesc->pNeighborBssDescription->channel;
pNeighborRoamInfo->FTRoamInfo.neighboReportBssInfo[pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport].neighborScore =
(tANI_U8)pNeighborBssDesc->roamScore;
vos_mem_copy(pNeighborRoamInfo->FTRoamInfo.neighboReportBssInfo[pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport].neighborBssId,
pNeighborBssDesc->pNeighborBssDescription->bssId, sizeof(tSirMacAddr));
pNeighborRoamInfo->FTRoamInfo.numBssFromNeighborReport++;
/* Saving the channel list non-redundantly */
if (numChannels > 0)
{
for (i = 0; i < numChannels; i++)
{
if (pNeighborBssDesc->pNeighborBssDescription->channel == channelList[i])
break;
}
}
if (i == numChannels)
{
if (pNeighborBssDesc->pNeighborBssDescription->channel)
{
if (CSR_IS_ROAM_INTRA_BAND_ENABLED(pMac))
{
// Make sure to add only if its the same band
if (GetRFBand(pNeighborRoamInfo->currAPoperationChannel) ==
GetRFBand(pNeighborBssDesc->pNeighborBssDescription->channel))
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG] Adding %d to Neighbor channel list (Same band)\n", __func__,
pNeighborBssDesc->pNeighborBssDescription->channel);
channelList[numChannels] = pNeighborBssDesc->pNeighborBssDescription->channel;
numChannels++;
}
}
else
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
"%s: [INFOLOG] Adding %d to Neighbor channel list\n", __func__,
pNeighborBssDesc->pNeighborBssDescription->channel);
channelList[numChannels] = pNeighborBssDesc->pNeighborBssDescription->channel;
numChannels++;
}
}
}
pNeighborBssDesc = smeRrmGetNextBssEntryFromNeighborCache(pMac, pNeighborBssDesc);
}
if (pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList)
{
#if 0
// Before we free the existing channel list for a safety net make sure
// we have a union of the IAPP and the already existing list.
status = csrNeighborRoamMergeChannelLists(
pMac,
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList,
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels,
channelList,
numChannels,
&numChannels );
#endif
vos_mem_free(pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList);
}
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = 0;
/* Store the obtained channel list to the Neighbor Control data structure */
if (numChannels)
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = vos_mem_malloc((numChannels) * sizeof(tANI_U8));
if (NULL == pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList)
{
smsLog(pMac, LOGE, FL("Memory allocation for Channel list failed.. TL event ignored"));
return VOS_STATUS_E_RESOURCES;
}
vos_mem_copy(pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList,
channelList, (numChannels) * sizeof(tANI_U8));
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = numChannels;
/*
* Create a Union of occupied channel list learnt by the DUT along with the Neighbor
* report Channels. This increases the chances of the DUT to get a candidate AP while
* roaming even if the Neighbor Report is not able to provide sufficient information.
* */
if (pMac->scan.occupiedChannels.numChannels)
{
csrNeighborRoamMergeChannelLists(pMac,
&pMac->scan.occupiedChannels.channelList[0],
pMac->scan.occupiedChannels.numChannels,
&pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList[0],
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels,
&mergedOutputNumOfChannels);
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels =
mergedOutputNumOfChannels;
}
/*Indicate the firmware about the update only if any new channels are added.
* Otherwise, the firmware would already be knowing the non-IAPPneighborlist
* channels. There is no need to update.*/
if (numChannels)
{
smsLog(pMac, LOG1, FL("IAPP Neighbor list callback received as expected in state %d."),
pNeighborRoamInfo->neighborRoamState);
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_TRUE;
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (csrRoamIsRoamOffloadScanEnabled(pMac))
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_CHANNEL_LIST_CHANGED);
}
#endif
}
pNeighborRoamInfo->roamChannelInfo.currentChanIndex = 0;
pNeighborRoamInfo->roamChannelInfo.chanListScanInProgress = eANI_BOOLEAN_TRUE;
return VOS_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamRRMNeighborReportResult
\brief This function is the neighbor report callback that will be invoked by
SME RRM on receiving a neighbor report or of neighbor report is not
received after timeout. On receiving a valid report, it generates a
channel list from the neighbor report and starts the
neighbor scan timer
\param context - The handle returned by macOpen.
vosStatus - Status of the callback(SUCCESS/FAILURE)
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamRRMNeighborReportResult(void *context, VOS_STATUS vosStatus)
{
tpAniSirGlobal pMac = PMAC_STRUCT(context);
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
smsLog(pMac, LOG1, FL("Neighbor report result callback with status = %d"), vosStatus);
switch (pNeighborRoamInfo->neighborRoamState)
{
case eCSR_NEIGHBOR_ROAM_STATE_REPORT_QUERY:
/* Reset the report pending variable */
pNeighborRoamInfo->FTRoamInfo.neighborRptPending = eANI_BOOLEAN_FALSE;
if (VOS_STATUS_SUCCESS == vosStatus)
{
/* Need to create channel list based on the neighbor AP list and transition to REPORT_SCAN state */
vosStatus = csrNeighborRoamCreateChanListFromNeighborReport(pMac);
if (VOS_STATUS_SUCCESS == vosStatus)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("Channel List created from Neighbor report, Transitioning to NEIGHBOR_SCAN state"));
}
/* We are gonna scan now. Remember the time stamp to filter out results only after this timestamp */
pNeighborRoamInfo->scanRequestTimeStamp = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd);
/* Now ready for neighbor scan based on the channel list created */
/* Start Neighbor scan timer now. Multiplication by PAL_TIMER_TO_MS_UNIT is to convert ms to us which is
what palTimerStart expects */
status = vos_timer_start(&pNeighborRoamInfo->neighborScanTimer,
pNeighborRoamInfo->cfgParams.neighborScanPeriod);
if (eHAL_STATUS_SUCCESS != status)
{
/* Timer start failed.. Should we ASSERT here??? */
smsLog(pMac, LOGE, FL("PAL Timer start for neighbor scan timer failed, status = %d, Ignoring state transition"), status);
vos_mem_free(pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList);
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = 0;
return;
}
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum = 0;
/* Neighbor scan timer started. Transition to REPORT_SCAN state */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN)
}
else
{
/* Neighbor report timeout happened in SME RRM. We can try sending more neighbor requests until we
reach the maxNeighborRetries or receiving a successful neighbor response */
smsLog(pMac, LOGE, FL("Neighbor report result failed after %d retries, MAX RETRIES = %d"),
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum, pNeighborRoamInfo->cfgParams.maxNeighborRetries);
if (pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum >=
pNeighborRoamInfo->cfgParams.maxNeighborRetries)
{
smsLog(pMac, LOGE, FL("Bailing out to CFG Channel list scan.. "));
vosStatus = csrNeighborRoamTransitToCFGChanScan(pMac);
if (VOS_STATUS_SUCCESS != vosStatus)
{
smsLog(pMac, LOGE, FL("Transit to CFG Channel list scan state failed with status %d "), vosStatus);
return;
}
/* We transitioned to different state now. Reset the Neighbor report retry count */
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum = 0;
}
else
{
vosStatus = csrNeighborRoamIssueNeighborRptRequest(pMac);
if (VOS_STATUS_SUCCESS != vosStatus)
{
smsLog(pMac, LOGE, FL("Neighbor report request failed. status = %d"), vosStatus);
return;
}
pNeighborRoamInfo->FTRoamInfo.neighborRptPending = eANI_BOOLEAN_TRUE;
/* Increment the neighbor report retry count after sending the neighbor request successfully */
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum++;
}
}
break;
default:
smsLog(pMac, LOGE, FL("Neighbor result callback not expected in state %d, Ignoring.."), pNeighborRoamInfo->neighborRoamState);
break;
}
return;
}
#endif /* WLAN_FEATURE_VOWIFI_11R */
#ifdef FEATURE_WLAN_LFR
tANI_BOOLEAN csrNeighborRoamIsSsidAndSecurityMatch(
tpAniSirGlobal pMac,
tCsrRoamConnectedProfile *pCurProfile,
tSirBssDescription *pBssDesc,
tDot11fBeaconIEs *pIes)
{
tCsrAuthList authType;
tCsrEncryptionList uCEncryptionType;
tCsrEncryptionList mCEncryptionType;
tANI_BOOLEAN fMatch = FALSE;
authType.numEntries = 1;
authType.authType[0] = pCurProfile->AuthType;
uCEncryptionType.numEntries = 1;
uCEncryptionType.encryptionType[0] = pCurProfile->EncryptionType;
mCEncryptionType.numEntries = 1;
mCEncryptionType.encryptionType[0] = pCurProfile->mcEncryptionType;
if( pIes )
{
if(pIes->SSID.present)
{
fMatch = csrIsSsidMatch( pMac,
(void *)pCurProfile->SSID.ssId, pCurProfile->SSID.length,
pIes->SSID.ssid, pIes->SSID.num_ssid,
eANI_BOOLEAN_TRUE );
if(TRUE == fMatch)
{
fMatch = csrIsSecurityMatch( pMac, &authType, &uCEncryptionType,
&mCEncryptionType, pBssDesc, pIes, NULL, NULL, NULL );
return (fMatch);
}
else
{
return (fMatch);
}
}
else
{
return FALSE; // Treat a missing SSID as a non-match.
}
}
else
{
return FALSE; // Again, treat missing pIes as a non-match.
}
}
tANI_BOOLEAN csrNeighborRoamIsNewConnectedProfile(
tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tANI_U8 sessionId = (tANI_U8)pNeighborRoamInfo->csrSessionId;
tCsrRoamConnectedProfile *pCurrProfile = NULL;
tCsrRoamConnectedProfile *pPrevProfile = NULL;
tDot11fBeaconIEs *pIes = NULL;
tSirBssDescription *pBssDesc = NULL;
tANI_BOOLEAN fNew = TRUE;
if(!(pMac->roam.roamSession && CSR_IS_SESSION_VALID(pMac, sessionId)))
{
return (fNew);
}
pCurrProfile = &pMac->roam.roamSession[sessionId].connectedProfile;
if( !pCurrProfile )
{
return (fNew);
}
pPrevProfile = &pNeighborRoamInfo->prevConnProfile;
if( !pPrevProfile )
{
return (fNew);
}
pBssDesc = pPrevProfile->pBssDesc;
if (pBssDesc)
{
if (HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac,
pBssDesc, &pIes)) &&
csrNeighborRoamIsSsidAndSecurityMatch(pMac, pCurrProfile, pBssDesc, pIes))
{
fNew = FALSE;
}
if (pIes) {
palFreeMemory(pMac->hHdd, pIes);
}
}
if (fNew)
{
smsLog(pMac, LOG1, FL("Prev roam profile did not match current"));
}
else
{
smsLog(pMac, LOG1, FL("Prev roam profile matches current"));
}
return (fNew);
}
tANI_BOOLEAN csrNeighborRoamConnectedProfileMatch(
tpAniSirGlobal pMac,
tCsrScanResult *pResult,
tDot11fBeaconIEs *pIes)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tANI_U8 sessionId = (tANI_U8)pNeighborRoamInfo->csrSessionId;
tCsrRoamConnectedProfile *pCurProfile = NULL;
tSirBssDescription *pBssDesc = &pResult->Result.BssDescriptor;
if( !(pMac->roam.roamSession
&& CSR_IS_SESSION_VALID(pMac, sessionId)))
{
return FALSE;
}
pCurProfile = &pMac->roam.roamSession[sessionId].connectedProfile;
if( !pCurProfile)
{
return FALSE;
}
return csrNeighborRoamIsSsidAndSecurityMatch(pMac, pCurProfile, pBssDesc, pIes);
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamPrepareNonOccupiedChannelList
\brief This function is used to prepare a channel list that is derived from
the list of valid channels and does not include those in the occupied
list.
\param pMac - The handle returned by macOpen.
\param pInputChannelList - The default channels list.
\param numOfChannels - The number of channels in the default channels list.
\param pOutputChannelList - The place to put the non-occupied channel list.
\param pOutputNumOfChannels - The number of channels in the non-occupied channel list.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamPrepareNonOccupiedChannelList(
tpAniSirGlobal pMac,
tANI_U8 *pInputChannelList,
tANI_U8 numOfChannels,
tANI_U8 *pOutputChannelList,
tANI_U8 *pOutputNumOfChannels
)
{
tANI_U8 i = 0;
tANI_U8 outputNumOfChannels = 0; // Clear the output number of channels
tANI_U8 numOccupiedChannels = pMac->scan.occupiedChannels.numChannels;
tANI_U8 *pOccupiedChannelList = pMac->scan.occupiedChannels.channelList;
for (i = 0; i < numOfChannels; i++)
{
if (!csrIsChannelPresentInList(pOccupiedChannelList, numOccupiedChannels,
pInputChannelList[i]))
{
pOutputChannelList[outputNumOfChannels++] = pInputChannelList[i];
}
}
smsLog(pMac, LOG2, FL("Number of channels in the valid channel list=%d; "
"Number of channels in the non-occupied list list=%d"),
numOfChannels, outputNumOfChannels);
// Return the number of channels
*pOutputNumOfChannels = outputNumOfChannels;
return eHAL_STATUS_SUCCESS;
}
#endif /* FEATURE_WLAN_LFR */
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamTransitToCFGChanScan
\brief This function is called whenever there is a transition to CFG chan scan
state from any state. It frees up the current channel list and allocates
a new memory for the channels received from CFG item. It then starts the
neighbor scan timer to perform the scan on each channel one by one
\param pMac - The handle returned by macOpen.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamTransitToCFGChanScan(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
int i = 0;
tANI_U8 numOfChannels = 0;
tANI_U8 channelList[WNI_CFG_VALID_CHANNEL_LIST_LEN];
tpCsrChannelInfo currChannelListInfo;
#ifdef FEATURE_WLAN_LFR
tANI_U32 sessionId = pNeighborRoamInfo->csrSessionId;
#endif
currChannelListInfo = &pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo;
if (
#ifdef FEATURE_WLAN_CCX
((pNeighborRoamInfo->isCCXAssoc) &&
(pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived == eANI_BOOLEAN_FALSE)) ||
(pNeighborRoamInfo->isCCXAssoc == eANI_BOOLEAN_FALSE) ||
#endif // CCX
currChannelListInfo->numOfChannels == 0)
{
smsLog(pMac, LOGW, FL("Building channel list to scan"));
/* Free up the channel list and allocate a new memory. This is because we dont know how much
was allocated last time. If we directly copy more number of bytes than allocated earlier, this might
result in memory corruption */
if (NULL != currChannelListInfo->ChannelList)
{
vos_mem_free(currChannelListInfo->ChannelList);
currChannelListInfo->ChannelList = NULL;
currChannelListInfo->numOfChannels = 0;
}
// Now obtain the contents for "channelList" (the "default valid channel list") from EITHER
// the gNeighborScanChannelList in "cfg.ini", OR the actual "valid channel list" information formed by CSR.
if (0 != pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels)
{
// Copy the "default valid channel list" (channelList) from the gNeighborScanChannelList in "cfg.ini".
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, "Using the channel list from cfg.ini");
status = csrNeighborRoamMergeChannelLists(
pMac,
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList,
pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels,
channelList,
0, //NB: If 0, simply copy the input channel list to the output list.
&numOfChannels );
if (CSR_IS_ROAM_INTRA_BAND_ENABLED(pMac))
{
csrNeighborRoamChannelsFilterByCurrentBand(
pMac,
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList,
pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels,
channelList,
&numOfChannels);
}
if(numOfChannels > WNI_CFG_VALID_CHANNEL_LIST_LEN)
{
smsLog(pMac, LOGE, FL("Received wrong number of Channel list"));
return VOS_STATUS_E_INVAL;
}
currChannelListInfo->ChannelList =
vos_mem_malloc(numOfChannels*sizeof(tANI_U8));
if (NULL == currChannelListInfo->ChannelList)
{
smsLog(pMac, LOGE, FL("Memory allocation for Channel list failed"));
return VOS_STATUS_E_RESOURCES;
}
vos_mem_copy(currChannelListInfo->ChannelList,
channelList, numOfChannels * sizeof(tANI_U8));
}
#ifdef FEATURE_WLAN_LFR
else if ((pNeighborRoamInfo->uScanMode == DEFAULT_SCAN) &&
(abs(pNeighborRoamInfo->lookupDOWNRssi) >
abs(pNeighborRoamInfo->cfgParams.neighborReassocThreshold)))
{
/*
* Trigger a contiguous scan on all channels when the
* RSSI in the lookup DOWN notification is below reassoc
* threshold. This will help us find the best available
* candidate and also update the channel cache.
*/
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, "Triggering contiguous scan "
"(lookupDOWNRssi=%d,reassocThreshold=%d)",
pNeighborRoamInfo->lookupDOWNRssi,
pNeighborRoamInfo->cfgParams.neighborReassocThreshold*(-1));
pNeighborRoamInfo->scanRequestTimeStamp = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd);
vos_timer_stop(&pNeighborRoamInfo->neighborScanTimer);
/* We are about to start a fresh scan cycle,
* purge non-P2P results from the past */
csrScanFlushSelectiveResult(pMac, VOS_FALSE);
csrNeighborRoamPerformContiguousBgScan(pMac, sessionId);
/* Transition to CFG_CHAN_LIST_SCAN */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN);
return VOS_STATUS_SUCCESS;
}
#endif
else
{
numOfChannels = pMac->scan.occupiedChannels.numChannels;
if (numOfChannels > WNI_CFG_VALID_CHANNEL_LIST_LEN)
{
numOfChannels = WNI_CFG_VALID_CHANNEL_LIST_LEN;
}
if (numOfChannels
#ifdef FEATURE_WLAN_LFR
&& ((pNeighborRoamInfo->uScanMode == SPLIT_SCAN_OCCUPIED_LIST) ||
(pNeighborRoamInfo->uEmptyScanCount == 0) ||
((pNeighborRoamInfo->uEmptyScanCount % 2) == 1))
#endif
)
{
/*
* Always scan channels in the occupied channel list
* before scanning on the non-occupied list.
*/
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, "Switching to occupied channel list"
#ifdef FEATURE_WLAN_LFR
"-uScanMode=%d, uEmptyScanCount=%d",
pNeighborRoamInfo->uScanMode,
pNeighborRoamInfo->uEmptyScanCount
#endif
);
if (CSR_IS_ROAM_INTRA_BAND_ENABLED(pMac))
{
csrNeighborRoamChannelsFilterByCurrentBand(
pMac,
pMac->scan.occupiedChannels.channelList,
numOfChannels,
channelList,
&numOfChannels);
}
else
{
vos_mem_copy(channelList,
pMac->scan.occupiedChannels.channelList,
numOfChannels * sizeof(tANI_U8));
}
VOS_ASSERT(currChannelListInfo->ChannelList == NULL);
currChannelListInfo->ChannelList = vos_mem_malloc(numOfChannels * sizeof(tANI_U8));
if (NULL == currChannelListInfo->ChannelList)
{
smsLog(pMac, LOGE, FL("Memory allocation for Channel list failed"));
return VOS_STATUS_E_RESOURCES;
}
vos_mem_copy(currChannelListInfo->ChannelList,
channelList,
numOfChannels * sizeof(tANI_U8));
}
else
{
/* Scan all channels from non-occupied list */
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, "Get valid channel list");
numOfChannels = sizeof(pMac->roam.validChannelList);
if(HAL_STATUS_SUCCESS(csrGetCfgValidChannels(pMac,
(tANI_U8 *)pMac->roam.validChannelList,
(tANI_U32 *) &numOfChannels)))
{
#ifdef FEATURE_WLAN_LFR
/*
* Prepare non-occupied channel list (channelList)
* from the actual "valid channel list" information
* formed by CSR.
*/
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, "Switching to non-occupied channel list");
status = csrNeighborRoamPrepareNonOccupiedChannelList(pMac,
(tANI_U8 *)pMac->roam.validChannelList,
numOfChannels,
channelList,
&numOfChannels);
#else
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, "Merging channel list");
status = csrNeighborRoamMergeChannelLists(
pMac,
(tANI_U8 *)pMac->roam.validChannelList,
numOfChannels, // The number of channels in the validChannelList
channelList,
0, //NB: If 0, simply copy the input channel list to the output list.
&numOfChannels ); // The final number of channels in the output list. Will be numOfChannels
#endif
}
else
{
smsLog(pMac, LOGE, FL("Could not get valid channel list"));
return VOS_STATUS_E_FAILURE;
}
if (CSR_IS_ROAM_INTRA_BAND_ENABLED(pMac))
{
csrNeighborRoamChannelsFilterByCurrentBand(
pMac,
(tANI_U8 *)pMac->roam.validChannelList,
numOfChannels,
channelList,
&numOfChannels);
}
currChannelListInfo->ChannelList =
vos_mem_malloc(numOfChannels*sizeof(tANI_U8));
if (NULL == currChannelListInfo->ChannelList)
{
smsLog(pMac, LOGE, FL("Memory allocation for Channel list failed"));
return VOS_STATUS_E_RESOURCES;
}
#ifdef FEATURE_WLAN_LFR
vos_mem_copy(currChannelListInfo->ChannelList,
channelList, numOfChannels * sizeof(tANI_U8));
#else
if (numOfChannels > WNI_CFG_VALID_CHANNEL_LIST_LEN)
{
numOfChannels = WNI_CFG_VALID_CHANNEL_LIST_LEN;
}
vos_mem_copy(currChannelListInfo->ChannelList,
(tANI_U8 *)pMac->roam.validChannelList,
numOfChannels * sizeof(tANI_U8));
#endif
}
}
/* Adjust for the actual number that are used */
currChannelListInfo->numOfChannels = numOfChannels;
NEIGHBOR_ROAM_DEBUG(pMac, LOGW,
"Number of channels from CFG (or) (non-)occupied list=%d",
currChannelListInfo->numOfChannels);
for (i = 0; i < currChannelListInfo->numOfChannels; i++)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, "Channel List from CFG (or) (non-)occupied list"
"= %d", currChannelListInfo->ChannelList[i]);
}
}
/* We are gonna scan now. Remember the time stamp to filter out results only after this timestamp */
pNeighborRoamInfo->scanRequestTimeStamp = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd);
vos_timer_stop(&pNeighborRoamInfo->neighborScanTimer);
/* Start Neighbor scan timer now. Multiplication by PAL_TIMER_TO_MS_UNIT is to convert ms to us which is
what palTimerStart expects */
status = vos_timer_start(&pNeighborRoamInfo->neighborScanTimer,
pNeighborRoamInfo->cfgParams.neighborScanPeriod);
if (eHAL_STATUS_SUCCESS != status)
{
/* Timer start failed.. */
smsLog(pMac, LOGE, FL("Neighbor scan PAL Timer start failed, status = %d, Ignoring state transition"), status);
vos_mem_free(currChannelListInfo->ChannelList);
currChannelListInfo->ChannelList = NULL;
currChannelListInfo->numOfChannels = 0;
return VOS_STATUS_E_FAILURE;
}
pNeighborRoamInfo->roamChannelInfo.currentChanIndex = 0;
pNeighborRoamInfo->roamChannelInfo.chanListScanInProgress = eANI_BOOLEAN_TRUE;
/* We are about to start a fresh scan cycle,
* purge non-P2P results from the past */
csrScanFlushSelectiveResult(pMac, VOS_FALSE);
/* We are about to start a fresh scan cycle,
* purge failed pre-auth results from the past */
csrNeighborRoamPurgePreauthFailedList(pMac);
/* Transition to CFG_CHAN_LIST_SCAN_STATE */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN)
return VOS_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamNeighborLookupUpEvent
\brief This function is called as soon as TL indicates that the current AP's
RSSI is better than the neighbor lookup threshold. Here, we transition to
CONNECTED state and reset all the scan parameters
\param pMac - The handle returned by macOpen.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamNeighborLookupUpEvent(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus;
csrNeighborRoamDeregAllRssiIndication(pMac);
/* Recheck whether the below check is needed. */
if (pNeighborRoamInfo->neighborRoamState != eCSR_NEIGHBOR_ROAM_STATE_CONNECTED)
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_CONNECTED)
#ifdef FEATURE_WLAN_LFR
if (!csrRoamIsFastRoamEnabled(pMac,pMac->roam.neighborRoamInfo.csrSessionId))
{
smsLog(pMac, LOGE, FL("Received when fast roam is disabled. Ignore it"));
return eHAL_STATUS_SUCCESS;
}
#endif
/* Reset all the neighbor roam info control variables. Free all the allocated memory. It is like we are just associated now */
csrNeighborRoamResetConnectedStateControlInfo(pMac);
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Registering DOWN event neighbor lookup callback with TL. RSSI = %d,"), pNeighborRoamInfo->currentNeighborLookupThreshold * (-1));
/* Register Neighbor Lookup threshold callback with TL for DOWN event now */
vosStatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext, (v_S7_t)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamNeighborLookupDOWNCallback,
VOS_MODULE_ID_SME, pMac);
#ifdef FEATURE_WLAN_LFR
pNeighborRoamInfo->lookupDOWNRssi = 0;
#endif
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGW, FL(" Couldn't register csrNeighborRoamNeighborLookupCallback DOWN event with TL: Status = %d"), vosStatus);
}
return vosStatus;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamNeighborLookupDownEvent
\brief This function is called as soon as TL indicates that the current AP's
RSSI falls below the current eighbor lookup threshold. Here, we transition to
REPORT_QUERY for 11r association and CFG_CHAN_LIST_SCAN state if the assoc is
a non-11R association.
\param pMac - The handle returned by macOpen.
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamNeighborLookupDownEvent(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
eHalStatus status = eHAL_STATUS_SUCCESS;
switch (pNeighborRoamInfo->neighborRoamState)
{
case eCSR_NEIGHBOR_ROAM_STATE_CONNECTED:
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Deregistering DOWN event neighbor lookup callback with TL. RSSI = %d,"),
pNeighborRoamInfo->currentNeighborLookupThreshold * (-1));
/* De-register Neighbor Lookup threshold callback with TL */
vosStatus = WLANTL_DeregRSSIIndicationCB(pMac->roam.gVosContext, (v_S7_t)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamNeighborLookupDOWNCallback,
VOS_MODULE_ID_SME);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGW, FL(" Couldn't Deregister csrNeighborRoamNeighborLookupCallback DOWN event from TL: Status = %d"), vosStatus);
}
#ifdef FEATURE_WLAN_LFR
if (!csrRoamIsFastRoamEnabled(pMac,pMac->roam.neighborRoamInfo.csrSessionId))
{
smsLog(pMac, LOGE, FL("Received when fast roam is disabled. Ignore it"));
return eHAL_STATUS_SUCCESS;
}
#endif
#if defined WLAN_FEATURE_VOWIFI_11R && defined WLAN_FEATURE_VOWIFI
if ((pNeighborRoamInfo->is11rAssoc) && (pMac->rrm.rrmSmeContext.rrmConfig.rrmEnabled))
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("11R Association:Neighbor Lookup Down event received in CONNECTED state"));
vosStatus = csrNeighborRoamIssueNeighborRptRequest(pMac);
if (VOS_STATUS_SUCCESS != vosStatus)
{
smsLog(pMac, LOGE, FL("Neighbor report request failed. status = %d"), vosStatus);
return vosStatus;
}
/* Increment the neighbor report retry count after sending the neighbor request successfully */
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum++;
pNeighborRoamInfo->FTRoamInfo.neighborRptPending = eANI_BOOLEAN_TRUE;
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REPORT_QUERY)
}
else
#endif
{
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Non 11R or CCX Association:Neighbor Lookup Down event received in CONNECTED state"));
vosStatus = csrNeighborRoamTransitToCFGChanScan(pMac);
if (VOS_STATUS_SUCCESS != vosStatus)
{
NEIGHBOR_ROAM_DEBUG(pMac, LOGE, FL("csrNeighborRoamTransitToCFGChanScan failed"
" with status=%d"), vosStatus);
return vosStatus;
}
}
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Registering UP event neighbor lookup callback with TL. RSSI = %d,"), NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1));
/* Register Neighbor Lookup threshold callback with TL for UP event now */
vosStatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext,
(v_S7_t)NEIGHBOR_ROAM_LOOKUP_UP_THRESHOLD * (-1),
WLANTL_HO_THRESHOLD_UP,
csrNeighborRoamNeighborLookupUPCallback,
VOS_MODULE_ID_SME, pMac);
if(!VOS_IS_STATUS_SUCCESS(vosStatus))
{
//err msg
smsLog(pMac, LOGE, FL(" Couldn't register csrNeighborRoamNeighborLookupCallback UP event with TL: Status = %d"), status);
}
break;
default:
smsLog(pMac, LOGE, FL("DOWN event received in invalid state %d..Ignoring..."), pNeighborRoamInfo->neighborRoamState);
break;
}
return vosStatus;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamNeighborLookupUPCallback
\brief This function is registered with TL to indicate whenever the RSSI
gets better than the neighborLookup RSSI Threshold
\param pAdapter - VOS Context
trafficStatus - UP/DOWN indication from TL
pUserCtxt - Parameter for callback registered during callback registration. Should be pMac
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamNeighborLookupUPCallback (v_PVOID_t pAdapter, v_U8_t rssiNotification,
v_PVOID_t pUserCtxt,
v_S7_t avgRssi)
{
tpAniSirGlobal pMac = PMAC_STRUCT( pUserCtxt );
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus = eHAL_STATUS_SUCCESS;
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("Neighbor Lookup UP indication callback called with notification %d Reported RSSI = %d"),
rssiNotification,
avgRssi);
if(!csrIsConnStateConnectedInfra(pMac, pNeighborRoamInfo->csrSessionId))
{
smsLog(pMac, LOGW, "Ignoring the indication as we are not connected");
return VOS_STATUS_SUCCESS;
}
VOS_ASSERT(WLANTL_HO_THRESHOLD_UP == rssiNotification);
vosStatus = csrNeighborRoamNeighborLookupUpEvent(pMac);
return vosStatus;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamNeighborLookupDOWNCallback
\brief This function is registered with TL to indicate whenever the RSSI
falls below the current neighborLookup RSSI Threshold
\param pAdapter - VOS Context
trafficStatus - UP/DOWN indication from TL
pUserCtxt - Parameter for callback registered during callback registration. Should be pMac
\return VOS_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
VOS_STATUS csrNeighborRoamNeighborLookupDOWNCallback (v_PVOID_t pAdapter, v_U8_t rssiNotification,
v_PVOID_t pUserCtxt,
v_S7_t avgRssi)
{
tpAniSirGlobal pMac = PMAC_STRUCT( pUserCtxt );
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
VOS_STATUS vosStatus = eHAL_STATUS_SUCCESS;
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("Neighbor Lookup DOWN indication callback called with notification %d Reported RSSI = %d"),
rssiNotification,
avgRssi);
#ifdef FEATURE_WLAN_LFR
pNeighborRoamInfo->lookupDOWNRssi = avgRssi;
#endif
if(!csrIsConnStateConnectedInfra(pMac, pNeighborRoamInfo->csrSessionId))
{
smsLog(pMac, LOGW, "Ignoring the indication as we are not connected");
return VOS_STATUS_SUCCESS;
}
VOS_ASSERT(WLANTL_HO_THRESHOLD_DOWN == rssiNotification);
vosStatus = csrNeighborRoamNeighborLookupDownEvent(pMac);
return vosStatus;
}
#ifdef RSSI_HACK
extern int dumpCmdRSSI;
#endif
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamIndicateDisconnect
\brief This function is called by CSR as soon as the station disconnects from
the AP. This function does the necessary cleanup of neighbor roam data
structures. Neighbor roam state transitions to INIT state whenever this
function is called except if the current state is REASSOCIATING
\param pMac - The handle returned by macOpen.
sessionId - CSR session id that got disconnected
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamIndicateDisconnect(tpAniSirGlobal pMac, tANI_U8 sessionId)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
#ifdef FEATURE_WLAN_LFR
tCsrRoamConnectedProfile *pPrevProfile = &pNeighborRoamInfo->prevConnProfile;
#endif
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId);
VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO,
FL("Disconnect indication on session %d in state %d from BSSID : "
MAC_ADDRESS_STR), sessionId, pNeighborRoamInfo->neighborRoamState,
MAC_ADDR_ARRAY(pSession->connectedProfile.bssid));
#ifdef FEATURE_WLAN_LFR
/*Free the current previous profile and move the current profile to prev profile.*/
csrRoamFreeConnectProfile(pMac, pPrevProfile);
csrRoamCopyConnectProfile(pMac, sessionId, pPrevProfile);
#endif
if (NULL != pSession)
{
if (NULL != pSession->pCurRoamProfile)
{
if (VOS_STA_MODE != pMac->roam.roamSession[sessionId].pCurRoamProfile->csrPersona)
{
smsLog(pMac, LOGE, FL("Ignoring Disconnect indication received from a non STA persona."
"sessionId: %d, csrPersonna %d"), sessionId,
(int)pMac->roam.roamSession[sessionId].pCurRoamProfile->csrPersona);
return eHAL_STATUS_SUCCESS;
}
}
#ifdef FEATURE_WLAN_CCX
if (pSession->connectedProfile.isCCXAssoc)
{
vos_mem_copy(&pSession->prevApSSID, &pSession->connectedProfile.SSID,
sizeof(tSirMacSSid));
vos_mem_copy(pSession->prevApBssid, pSession->connectedProfile.bssid,
sizeof(tSirMacAddr));
pSession->prevOpChannel = pSession->connectedProfile.operationChannel;
pSession->isPrevApInfoValid = TRUE;
pSession->roamTS1 = vos_timer_get_system_time();
}
#endif
} //if (NULL != pSession)
#ifdef RSSI_HACK
dumpCmdRSSI = -40;
#endif
switch (pNeighborRoamInfo->neighborRoamState)
{
case eCSR_NEIGHBOR_ROAM_STATE_REASSOCIATING:
// Stop scan and neighbor refresh timers.
// These are indeed not required when we are in reassociating
// state.
vos_timer_stop(&pNeighborRoamInfo->neighborScanTimer);
vos_timer_stop(&pNeighborRoamInfo->neighborResultsRefreshTimer);
vos_timer_stop(&pNeighborRoamInfo->emptyScanRefreshTimer);
if (!CSR_IS_ROAM_SUBSTATE_DISASSOC_HO( pMac, sessionId )) {
/*
* Disconnect indication during Disassoc Handoff sub-state
* is received when we are trying to disconnect with the old
* AP during roam. BUT, if receive a disconnect indication
* outside of Disassoc Handoff sub-state, then it means that
* this is a genuine disconnect and we need to clean up.
* Otherwise, we will be stuck in reassoc state which will
* in-turn block scans (see csrIsScanAllowed).
*/
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_INIT);
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
}
break;
case eCSR_NEIGHBOR_ROAM_STATE_INIT:
csrNeighborRoamResetInitStateControlInfo(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (!csrRoamIsRoamOffloadScanEnabled(pMac))
{
#endif
csrNeighborRoamDeregAllRssiIndication(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
break;
case eCSR_NEIGHBOR_ROAM_STATE_CONNECTED:
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_INIT)
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
csrNeighborRoamResetConnectedStateControlInfo(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (!csrRoamIsRoamOffloadScanEnabled(pMac))
{
#endif
csrNeighborRoamDeregAllRssiIndication(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
break;
case eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN:
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_INIT);
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
csrNeighborRoamResetCfgListChanScanControlInfo(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (!csrRoamIsRoamOffloadScanEnabled(pMac))
{
#endif
csrNeighborRoamDeregAllRssiIndication(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
break;
case eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE:
/* Stop pre-auth to reassoc interval timer */
vos_timer_stop(&pMac->ft.ftSmeContext.preAuthReassocIntvlTimer);
case eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN:
case eCSR_NEIGHBOR_ROAM_STATE_PREAUTHENTICATING:
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_INIT)
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
csrNeighborRoamResetPreauthControlInfo(pMac);
csrNeighborRoamResetReportScanStateControlInfo(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (!csrRoamIsRoamOffloadScanEnabled(pMac))
{
#endif
csrNeighborRoamDeregAllRssiIndication(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
break;
default:
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("Received disconnect event in state %d"), pNeighborRoamInfo->neighborRoamState);
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, FL("Transitioning to INIT state"));
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_INIT)
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
break;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
/*Inform the Firmware to STOP Scanning as the host has a disconnect.*/
if (csrRoamIsStaMode(pMac, sessionId))
{
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_STOP, REASON_DISCONNECTED);
}
#endif
return eHAL_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamIndicateConnect
\brief This function is called by CSR as soon as the station connects to an AP.
This initializes all the necessary data structures related to the
associated AP and transitions the state to CONNECTED state
\param pMac - The handle returned by macOpen.
sessionId - CSR session id that got connected
vosStatus - connect status SUCCESS/FAILURE
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamIndicateConnect(tpAniSirGlobal pMac, tANI_U8 sessionId, VOS_STATUS vosStatus)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
VOS_STATUS vstatus;
#if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
int init_ft_flag = FALSE;
#endif
// if session id invalid then we need return failure
if (NULL == pNeighborRoamInfo || !CSR_IS_SESSION_VALID(pMac, sessionId) ||
(NULL == pMac->roam.roamSession[sessionId].pCurRoamProfile))
{
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOG2, FL("Connect indication received with session id %d in state %d"), sessionId, pNeighborRoamInfo->neighborRoamState);
// Bail out if this is NOT a STA persona
if (pMac->roam.roamSession[sessionId].pCurRoamProfile->csrPersona != VOS_STA_MODE)
{
smsLog(pMac, LOGE, FL("Ignoring Connect indication received from a non STA persona."
"sessionId: %d, csrPersonna %d"),
sessionId,
(int)pMac->roam.roamSession[sessionId].pCurRoamProfile->csrPersona);
return eHAL_STATUS_SUCCESS;
}
// if a concurrent session is running
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (eANI_BOOLEAN_FALSE == CSR_IS_FASTROAM_IN_CONCURRENCY_INI_FEATURE_ENABLED(pMac))
{
#endif
if (csrIsConcurrentSessionRunning(pMac))
{
smsLog(pMac, LOGE, FL("Ignoring Connect indication received in multisession %d"),
csrIsConcurrentSessionRunning(pMac));
return eHAL_STATUS_SUCCESS;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif
switch (pNeighborRoamInfo->neighborRoamState)
{
case eCSR_NEIGHBOR_ROAM_STATE_REASSOCIATING:
if (VOS_STATUS_SUCCESS != vosStatus)
{
/* Just transition the state to INIT state. Rest of the clean up happens when we get next connect indication */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_INIT)
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
break;
}
/* Fall through if the status is SUCCESS */
case eCSR_NEIGHBOR_ROAM_STATE_INIT:
/* Reset all the data structures here */
csrNeighborRoamResetInitStateControlInfo(pMac);
pNeighborRoamInfo->csrSessionId = sessionId;
#ifdef FEATURE_WLAN_LFR
/*
* Initialize the occupied list ONLY if we are
* transitioning from INIT state to CONNECTED state.
*/
if (eCSR_NEIGHBOR_ROAM_STATE_INIT == pNeighborRoamInfo->neighborRoamState)
csrInitOccupiedChannelsList(pMac);
#endif
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_CONNECTED);
vos_mem_copy(pNeighborRoamInfo->currAPbssid,
pMac->roam.roamSession[sessionId].connectedProfile.bssid, sizeof(tCsrBssid));
pNeighborRoamInfo->currAPoperationChannel = pMac->roam.roamSession[sessionId].connectedProfile.operationChannel;
pNeighborRoamInfo->neighborScanTimerInfo.pMac = pMac;
pNeighborRoamInfo->neighborScanTimerInfo.sessionId = sessionId;
pNeighborRoamInfo->currentNeighborLookupThreshold =
pNeighborRoamInfo->cfgParams.neighborLookupThreshold;
#ifdef FEATURE_WLAN_LFR
pNeighborRoamInfo->uEmptyScanCount = 0;
pNeighborRoamInfo->lookupDOWNRssi = 0;
pNeighborRoamInfo->uScanMode = DEFAULT_SCAN;
#endif
#if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
/* Now we can clear the preauthDone that was saved as we are connected afresh */
csrNeighborRoamFreeRoamableBSSList(pMac, &pMac->roam.neighborRoamInfo.FTRoamInfo.preAuthDoneList);
#endif
#ifdef WLAN_FEATURE_VOWIFI_11R
// Based on the auth scheme tell if we are 11r
if ( csrIsAuthType11r( pMac->roam.roamSession[sessionId].connectedProfile.AuthType,
pMac->roam.roamSession[sessionId].connectedProfile.MDID.mdiePresent))
{
if (pMac->roam.configParam.isFastTransitionEnabled)
init_ft_flag = TRUE;
pNeighborRoamInfo->is11rAssoc = eANI_BOOLEAN_TRUE;
}
else
pNeighborRoamInfo->is11rAssoc = eANI_BOOLEAN_FALSE;
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("11rAssoc is = %d"), pNeighborRoamInfo->is11rAssoc);
#endif
#ifdef FEATURE_WLAN_CCX
// Based on the auth scheme tell if we are 11r
if (pMac->roam.roamSession[sessionId].connectedProfile.isCCXAssoc)
{
if (pMac->roam.configParam.isFastTransitionEnabled)
init_ft_flag = TRUE;
pNeighborRoamInfo->isCCXAssoc = eANI_BOOLEAN_TRUE;
}
else
pNeighborRoamInfo->isCCXAssoc = eANI_BOOLEAN_FALSE;
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("isCCXAssoc is = %d ft = %d"),
pNeighborRoamInfo->isCCXAssoc, init_ft_flag);
#endif
#ifdef FEATURE_WLAN_LFR
// If "Legacy Fast Roaming" is enabled
if (csrRoamIsFastRoamEnabled(pMac, sessionId))
{
init_ft_flag = TRUE;
}
#endif
#if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
if ( init_ft_flag == TRUE )
{
/* Initialize all the data structures needed for the 11r FT Preauth */
pNeighborRoamInfo->FTRoamInfo.currentNeighborRptRetryNum = 0;
csrNeighborRoamPurgePreauthFailedList(pMac);
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
if (csrRoamIsRoamOffloadScanEnabled(pMac))
{
/*If this is not a INFRA type BSS, then do not send the command
* down to firmware.Do not send the START command for other session
* connections.*/
if(csrRoamIsStaMode(pMac, sessionId))
{
pNeighborRoamInfo->uOsRequestedHandoff = 0;
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_START, REASON_CONNECT);
}
} else {
#endif
NEIGHBOR_ROAM_DEBUG(pMac, LOG2, FL("Registering neighbor lookup DOWN event with TL, RSSI = %d"), pNeighborRoamInfo->currentNeighborLookupThreshold);
/* Register Neighbor Lookup threshold callback with TL for DOWN event only */
vstatus = WLANTL_RegRSSIIndicationCB(pMac->roam.gVosContext, (v_S7_t)pNeighborRoamInfo->currentNeighborLookupThreshold * (-1),
WLANTL_HO_THRESHOLD_DOWN,
csrNeighborRoamNeighborLookupDOWNCallback,
VOS_MODULE_ID_SME, pMac);
#ifdef FEATURE_WLAN_LFR
pNeighborRoamInfo->lookupDOWNRssi = 0;
#endif
if(!VOS_IS_STATUS_SUCCESS(vstatus))
{
//err msg
smsLog(pMac, LOGW, FL(" Couldn't register csrNeighborRoamNeighborLookupDOWNCallback with TL: Status = %d"), vstatus);
status = eHAL_STATUS_FAILURE;
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
}
#endif /* WLAN_FEATURE_ROAM_SCAN_OFFLOAD */
}
#endif
break;
default:
smsLog(pMac, LOGE, FL("Connect event received in invalid state %d..Ignoring..."), pNeighborRoamInfo->neighborRoamState);
break;
}
return status;
}
#ifdef WLAN_FEATURE_VOWIFI_11R
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamPurgePreauthFailedList
\brief This function purges all the MAC addresses in the pre-auth fail list
\param pMac - The handle returned by macOpen.
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamPurgePreauthFailedList(tpAniSirGlobal pMac)
{
tANI_U8 i;
for (i = 0; i < pMac->roam.neighborRoamInfo.FTRoamInfo.preAuthFailList.numMACAddress; i++)
{
vos_mem_zero(pMac->roam.neighborRoamInfo.FTRoamInfo.preAuthFailList.macAddress[i], sizeof(tSirMacAddr));
}
pMac->roam.neighborRoamInfo.FTRoamInfo.preAuthFailList.numMACAddress = 0;
return;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamInit11rAssocInfo
\brief This function initializes 11r related neighbor roam data structures
\param pMac - The handle returned by macOpen.
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamInit11rAssocInfo(tpAniSirGlobal pMac)
{
eHalStatus status;
tpCsr11rAssocNeighborInfo pFTRoamInfo = &pMac->roam.neighborRoamInfo.FTRoamInfo;
pMac->roam.neighborRoamInfo.is11rAssoc = eANI_BOOLEAN_FALSE;
pMac->roam.neighborRoamInfo.cfgParams.maxNeighborRetries = pMac->roam.configParam.neighborRoamConfig.nMaxNeighborRetries;
pFTRoamInfo->neighborReportTimeout = CSR_NEIGHBOR_ROAM_REPORT_QUERY_TIMEOUT;
pFTRoamInfo->PEPreauthRespTimeout = CSR_NEIGHBOR_ROAM_PREAUTH_RSP_WAIT_MULTIPLIER * pMac->roam.neighborRoamInfo.cfgParams.neighborScanPeriod;
pFTRoamInfo->neighborRptPending = eANI_BOOLEAN_FALSE;
pFTRoamInfo->preauthRspPending = eANI_BOOLEAN_FALSE;
pMac->roam.neighborRoamInfo.FTRoamInfo.currentNeighborRptRetryNum = 0;
pMac->roam.neighborRoamInfo.FTRoamInfo.numBssFromNeighborReport = 0;
vos_mem_zero(pMac->roam.neighborRoamInfo.FTRoamInfo.neighboReportBssInfo,
sizeof(tCsrNeighborReportBssInfo) * MAX_BSS_IN_NEIGHBOR_RPT);
status = csrLLOpen(pMac->hHdd, &pFTRoamInfo->preAuthDoneList);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("LL Open of preauth done AP List failed"));
return eHAL_STATUS_RESOURCES;
}
return status;
}
#endif /* WLAN_FEATURE_VOWIFI_11R */
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamInit
\brief This function initializes neighbor roam data structures
\param pMac - The handle returned by macOpen.
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamInit(tpAniSirGlobal pMac)
{
eHalStatus status;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
pNeighborRoamInfo->neighborRoamState = eCSR_NEIGHBOR_ROAM_STATE_CLOSED;
pNeighborRoamInfo->prevNeighborRoamState = eCSR_NEIGHBOR_ROAM_STATE_CLOSED;
pNeighborRoamInfo->csrSessionId = CSR_SESSION_ID_INVALID;
pNeighborRoamInfo->cfgParams.maxChannelScanTime = pMac->roam.configParam.neighborRoamConfig.nNeighborScanMaxChanTime;
pNeighborRoamInfo->cfgParams.minChannelScanTime = pMac->roam.configParam.neighborRoamConfig.nNeighborScanMinChanTime;
pNeighborRoamInfo->cfgParams.maxNeighborRetries = 0;
pNeighborRoamInfo->cfgParams.neighborLookupThreshold = pMac->roam.configParam.neighborRoamConfig.nNeighborLookupRssiThreshold;
pNeighborRoamInfo->cfgParams.neighborReassocThreshold = pMac->roam.configParam.neighborRoamConfig.nNeighborReassocRssiThreshold;
pNeighborRoamInfo->cfgParams.neighborScanPeriod = pMac->roam.configParam.neighborRoamConfig.nNeighborScanTimerPeriod;
pNeighborRoamInfo->cfgParams.neighborResultsRefreshPeriod = pMac->roam.configParam.neighborRoamConfig.nNeighborResultsRefreshPeriod;
pNeighborRoamInfo->cfgParams.emptyScanRefreshPeriod = pMac->roam.configParam.neighborRoamConfig.nEmptyScanRefreshPeriod;
pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels =
pMac->roam.configParam.neighborRoamConfig.neighborScanChanList.numChannels;
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList =
vos_mem_malloc(pMac->roam.configParam.neighborRoamConfig.neighborScanChanList.numChannels);
if (NULL == pNeighborRoamInfo->cfgParams.channelInfo.ChannelList)
{
smsLog(pMac, LOGE, FL("Memory Allocation for CFG Channel List failed"));
return eHAL_STATUS_RESOURCES;
}
/* Update the roam global structure from CFG */
palCopyMemory(pMac->hHdd, pNeighborRoamInfo->cfgParams.channelInfo.ChannelList,
pMac->roam.configParam.neighborRoamConfig.neighborScanChanList.channelList,
pMac->roam.configParam.neighborRoamConfig.neighborScanChanList.numChannels);
vos_mem_set(pNeighborRoamInfo->currAPbssid, sizeof(tCsrBssid), 0);
pNeighborRoamInfo->currentNeighborLookupThreshold = pMac->roam.neighborRoamInfo.cfgParams.neighborLookupThreshold;
#ifdef FEATURE_WLAN_LFR
pNeighborRoamInfo->lookupDOWNRssi = 0;
pNeighborRoamInfo->uEmptyScanCount = 0;
pNeighborRoamInfo->uScanMode = DEFAULT_SCAN;
palZeroMemory(pMac->hHdd, &pNeighborRoamInfo->prevConnProfile,
sizeof(tCsrRoamConnectedProfile));
#endif
pNeighborRoamInfo->scanRspPending = eANI_BOOLEAN_FALSE;
pNeighborRoamInfo->neighborScanTimerInfo.pMac = pMac;
pNeighborRoamInfo->neighborScanTimerInfo.sessionId = CSR_SESSION_ID_INVALID;
status = vos_timer_init(&pNeighborRoamInfo->neighborScanTimer, VOS_TIMER_TYPE_SW,
csrNeighborRoamNeighborScanTimerCallback, (void *)&pNeighborRoamInfo->neighborScanTimerInfo);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("Neighbor scan timer allocation failed"));
vos_mem_free(pNeighborRoamInfo->cfgParams.channelInfo.ChannelList);
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList = NULL;
return eHAL_STATUS_RESOURCES;
}
status = vos_timer_init(&pNeighborRoamInfo->neighborResultsRefreshTimer, VOS_TIMER_TYPE_SW,
csrNeighborRoamResultsRefreshTimerCallback, (void *)&pNeighborRoamInfo->neighborScanTimerInfo);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("Neighbor results refresh timer allocation failed"));
vos_mem_free(pNeighborRoamInfo->cfgParams.channelInfo.ChannelList);
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList = NULL;
vos_timer_destroy(&pNeighborRoamInfo->neighborScanTimer);
return eHAL_STATUS_RESOURCES;
}
status = vos_timer_init(&pNeighborRoamInfo->emptyScanRefreshTimer, VOS_TIMER_TYPE_SW,
csrNeighborRoamEmptyScanRefreshTimerCallback,
(void *)&pNeighborRoamInfo->neighborScanTimerInfo);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("Empty scan refresh timer allocation failed"));
vos_mem_free(pNeighborRoamInfo->cfgParams.channelInfo.ChannelList);
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList = NULL;
vos_timer_destroy(&pNeighborRoamInfo->neighborScanTimer);
vos_timer_destroy(&pNeighborRoamInfo->neighborResultsRefreshTimer);
return eHAL_STATUS_RESOURCES;
}
status = csrLLOpen(pMac->hHdd, &pNeighborRoamInfo->roamableAPList);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("LL Open of roamable AP List failed"));
vos_mem_free(pNeighborRoamInfo->cfgParams.channelInfo.ChannelList);
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList = NULL;
vos_timer_destroy(&pNeighborRoamInfo->neighborScanTimer);
vos_timer_destroy(&pNeighborRoamInfo->neighborResultsRefreshTimer);
vos_timer_destroy(&pNeighborRoamInfo->emptyScanRefreshTimer);
return eHAL_STATUS_RESOURCES;
}
pNeighborRoamInfo->roamChannelInfo.currentChanIndex = CSR_NEIGHBOR_ROAM_INVALID_CHANNEL_INDEX;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = 0;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.chanListScanInProgress = eANI_BOOLEAN_FALSE;
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
#ifdef WLAN_FEATURE_VOWIFI_11R
status = csrNeighborRoamInit11rAssocInfo(pMac);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("LL Open of roamable AP List failed"));
vos_mem_free(pNeighborRoamInfo->cfgParams.channelInfo.ChannelList);
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList = NULL;
vos_timer_destroy(&pNeighborRoamInfo->neighborScanTimer);
vos_timer_destroy(&pNeighborRoamInfo->neighborResultsRefreshTimer);
vos_timer_destroy(&pNeighborRoamInfo->emptyScanRefreshTimer);
csrLLClose(&pNeighborRoamInfo->roamableAPList);
return eHAL_STATUS_RESOURCES;
}
#endif
/* Initialize this with the current tick count */
pNeighborRoamInfo->scanRequestTimeStamp = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd);
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_INIT)
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
return eHAL_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamClose
\brief This function closes/frees all the neighbor roam data structures
\param pMac - The handle returned by macOpen.
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamClose(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
if (eCSR_NEIGHBOR_ROAM_STATE_CLOSED == pNeighborRoamInfo->neighborRoamState)
{
smsLog(pMac, LOGW, FL("Neighbor Roam Algorithm Already Closed"));
return;
}
if (pNeighborRoamInfo->cfgParams.channelInfo.ChannelList)
vos_mem_free(pNeighborRoamInfo->cfgParams.channelInfo.ChannelList);
pNeighborRoamInfo->cfgParams.channelInfo.ChannelList = NULL;
pNeighborRoamInfo->neighborScanTimerInfo.pMac = NULL;
pNeighborRoamInfo->neighborScanTimerInfo.sessionId = CSR_SESSION_ID_INVALID;
vos_timer_destroy(&pNeighborRoamInfo->neighborScanTimer);
vos_timer_destroy(&pNeighborRoamInfo->neighborResultsRefreshTimer);
vos_timer_destroy(&pNeighborRoamInfo->emptyScanRefreshTimer);
/* Should free up the nodes in the list before closing the double Linked list */
csrNeighborRoamFreeRoamableBSSList(pMac, &pNeighborRoamInfo->roamableAPList);
csrLLClose(&pNeighborRoamInfo->roamableAPList);
if (pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList)
{
vos_mem_free(pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList);
}
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.currentChanIndex = CSR_NEIGHBOR_ROAM_INVALID_CHANNEL_INDEX;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.numOfChannels = 0;
pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo.ChannelList = NULL;
pNeighborRoamInfo->roamChannelInfo.chanListScanInProgress = eANI_BOOLEAN_FALSE;
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
/* Free the profile.. */
csrReleaseProfile(pMac, &pNeighborRoamInfo->csrNeighborRoamProfile);
#ifdef FEATURE_WLAN_LFR
csrRoamFreeConnectProfile(pMac, &pNeighborRoamInfo->prevConnProfile);
#endif
#ifdef WLAN_FEATURE_VOWIFI_11R
pMac->roam.neighborRoamInfo.FTRoamInfo.currentNeighborRptRetryNum = 0;
pMac->roam.neighborRoamInfo.FTRoamInfo.numBssFromNeighborReport = 0;
vos_mem_zero(pMac->roam.neighborRoamInfo.FTRoamInfo.neighboReportBssInfo,
sizeof(tCsrNeighborReportBssInfo) * MAX_BSS_IN_NEIGHBOR_RPT);
csrNeighborRoamFreeRoamableBSSList(pMac, &pMac->roam.neighborRoamInfo.FTRoamInfo.preAuthDoneList);
csrLLClose(&pMac->roam.neighborRoamInfo.FTRoamInfo.preAuthDoneList);
#endif /* WLAN_FEATURE_VOWIFI_11R */
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_CLOSED)
return;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamRequestHandoff
\brief This function triggers actual switching from one AP to the new AP.
It issues disassociate with reason code as Handoff and CSR as a part of
handling disassoc rsp, issues reassociate to the new AP
\param pMac - The handle returned by macOpen.
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamRequestHandoff(tpAniSirGlobal pMac)
{
tCsrRoamInfo roamInfo;
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tANI_U32 sessionId = pNeighborRoamInfo->csrSessionId;
tCsrNeighborRoamBSSInfo handoffNode;
extern void csrRoamRoamingStateDisassocRspProcessor( tpAniSirGlobal pMac, tSirSmeDisassocRsp *pSmeDisassocRsp );
tANI_U32 roamId = 0;
eHalStatus status;
if (pMac->roam.neighborRoamInfo.neighborRoamState != eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE)
{
smsLog(pMac, LOGE, FL("Roam requested when Neighbor roam is in %d state"),
pMac->roam.neighborRoamInfo.neighborRoamState);
return;
}
vos_mem_zero(&roamInfo, sizeof(tCsrRoamInfo));
csrRoamCallCallback(pMac, pNeighborRoamInfo->csrSessionId, &roamInfo, roamId, eCSR_ROAM_FT_START,
eSIR_SME_SUCCESS);
vos_mem_zero(&roamInfo, sizeof(tCsrRoamInfo));
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_REASSOCIATING)
csrNeighborRoamGetHandoffAPInfo(pMac, &handoffNode);
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG,
FL("HANDOFF CANDIDATE BSSID "MAC_ADDRESS_STR),
MAC_ADDR_ARRAY(handoffNode.pBssDescription->bssId));
/* Free the profile.. Just to make sure we dont leak memory here */
csrReleaseProfile(pMac, &pNeighborRoamInfo->csrNeighborRoamProfile);
/* Create the Handoff AP profile. Copy the currently connected profile and update only the BSSID and channel number
This should happen before issuing disconnect */
status = csrRoamCopyConnectedProfile(pMac,
pNeighborRoamInfo->csrSessionId,
&pNeighborRoamInfo->csrNeighborRoamProfile);
if(eHAL_STATUS_SUCCESS != status)
{
VOS_TRACE (VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR,
FL("csrRoamCopyConnectedProfile returned failed %d"), status);
return;
}
vos_mem_copy(pNeighborRoamInfo->csrNeighborRoamProfile.BSSIDs.bssid, handoffNode.pBssDescription->bssId, sizeof(tSirMacAddr));
pNeighborRoamInfo->csrNeighborRoamProfile.ChannelInfo.ChannelList[0] = handoffNode.pBssDescription->channelId;
NEIGHBOR_ROAM_DEBUG(pMac, LOGW, " csrRoamHandoffRequested: disassociating with current AP");
if(!HAL_STATUS_SUCCESS(csrRoamIssueDisassociateCmd(pMac, sessionId, eCSR_DISCONNECT_REASON_HANDOFF)))
{
smsLog(pMac, LOGW, "csrRoamHandoffRequested: fail to issue disassociate");
return;
}
//notify HDD for handoff, providing the BSSID too
roamInfo.reasonCode = eCsrRoamReasonBetterAP;
vos_mem_copy(roamInfo.bssid,
handoffNode.pBssDescription->bssId,
sizeof( tCsrBssid ));
csrRoamCallCallback(pMac, sessionId, &roamInfo, 0, eCSR_ROAM_ROAMING_START, eCSR_ROAM_RESULT_NONE);
return;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamIsHandoffInProgress
\brief This function returns whether handoff is in progress or not based on
the current neighbor roam state
\param pMac - The handle returned by macOpen.
is11rReassoc - Return whether reassoc is of type 802.11r reassoc
\return eANI_BOOLEAN_TRUE if reassoc in progress, eANI_BOOLEAN_FALSE otherwise
---------------------------------------------------------------------------*/
tANI_BOOLEAN csrNeighborRoamIsHandoffInProgress(tpAniSirGlobal pMac)
{
if (eCSR_NEIGHBOR_ROAM_STATE_REASSOCIATING == pMac->roam.neighborRoamInfo.neighborRoamState)
return eANI_BOOLEAN_TRUE;
return eANI_BOOLEAN_FALSE;
}
#if defined(WLAN_FEATURE_VOWIFI_11R) || defined(WLAN_FEATURE_NEIGHBOR_ROAMING)
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamIs11rAssoc
\brief This function returns whether the current association is a 11r assoc or not
\param pMac - The handle returned by macOpen.
\return eANI_BOOLEAN_TRUE if current assoc is 11r, eANI_BOOLEAN_FALSE otherwise
---------------------------------------------------------------------------*/
tANI_BOOLEAN csrNeighborRoamIs11rAssoc(tpAniSirGlobal pMac)
{
return pMac->roam.neighborRoamInfo.is11rAssoc;
}
#endif /* WLAN_FEATURE_VOWIFI_11R */
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamGetHandoffAPInfo
\brief This function returns the best possible AP for handoff. For 11R case, it
returns the 1st entry from pre-auth done list. For non-11r case, it returns
the 1st entry from roamable AP list
\param pMac - The handle returned by macOpen.
pHandoffNode - AP node that is the handoff candidate returned
\return VOID
---------------------------------------------------------------------------*/
void csrNeighborRoamGetHandoffAPInfo(tpAniSirGlobal pMac, tpCsrNeighborRoamBSSInfo pHandoffNode)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tpCsrNeighborRoamBSSInfo pBssNode;
VOS_ASSERT(NULL != pHandoffNode);
#ifdef WLAN_FEATURE_VOWIFI_11R
if (pNeighborRoamInfo->is11rAssoc)
{
/* Always the BSS info in the head is the handoff candidate */
pBssNode = csrNeighborRoamGetRoamableAPListNextEntry(pMac, &pNeighborRoamInfo->FTRoamInfo.preAuthDoneList, NULL);
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Number of Handoff candidates = %d"), csrLLCount(&pNeighborRoamInfo->FTRoamInfo.preAuthDoneList));
}
else
#endif
#ifdef FEATURE_WLAN_CCX
if (pNeighborRoamInfo->isCCXAssoc)
{
/* Always the BSS info in the head is the handoff candidate */
pBssNode = csrNeighborRoamGetRoamableAPListNextEntry(pMac, &pNeighborRoamInfo->FTRoamInfo.preAuthDoneList, NULL);
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Number of Handoff candidates = %d"), csrLLCount(&pNeighborRoamInfo->FTRoamInfo.preAuthDoneList));
}
else
#endif
#ifdef FEATURE_WLAN_LFR
if (csrRoamIsFastRoamEnabled(pMac, CSR_SESSION_ID_INVALID))
{
/* Always the BSS info in the head is the handoff candidate */
pBssNode = csrNeighborRoamGetRoamableAPListNextEntry(pMac, &pNeighborRoamInfo->FTRoamInfo.preAuthDoneList, NULL);
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Number of Handoff candidates = %d"), csrLLCount(&pNeighborRoamInfo->FTRoamInfo.preAuthDoneList));
}
else
#endif
{
pBssNode = csrNeighborRoamGetRoamableAPListNextEntry(pMac, &pNeighborRoamInfo->roamableAPList, NULL);
NEIGHBOR_ROAM_DEBUG(pMac, LOG1, FL("Number of Handoff candidates = %d"), csrLLCount(&pNeighborRoamInfo->roamableAPList));
}
vos_mem_copy(pHandoffNode, pBssNode, sizeof(tCsrNeighborRoamBSSInfo));
return;
}
/* ---------------------------------------------------------------------------
\brief This function returns TRUE if preauth is completed
\param pMac - The handle returned by macOpen.
\return boolean
---------------------------------------------------------------------------*/
tANI_BOOLEAN csrNeighborRoamStatePreauthDone(tpAniSirGlobal pMac)
{
return (pMac->roam.neighborRoamInfo.neighborRoamState ==
eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE);
}
/* ---------------------------------------------------------------------------
\brief In the event that we are associated with AP1 and we have
completed pre auth with AP2. Then we receive a deauth/disassoc from
AP1.
At this point neighbor roam is in pre auth done state, pre auth timer
is running. We now handle this case by stopping timer and clearing
the pre-auth state. We basically clear up and just go to disconnected
state.
\param pMac - The handle returned by macOpen.
\return boolean
---------------------------------------------------------------------------*/
void csrNeighborRoamTranistionPreauthDoneToDisconnected(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
if (pMac->roam.neighborRoamInfo.neighborRoamState !=
eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE) return;
// Stop timer
vos_timer_stop(&pMac->ft.ftSmeContext.preAuthReassocIntvlTimer);
// Transition to init state
CSR_NEIGHBOR_ROAM_STATE_TRANSITION(eCSR_NEIGHBOR_ROAM_STATE_INIT)
pNeighborRoamInfo->roamChannelInfo.IAPPNeighborListReceived = eANI_BOOLEAN_FALSE;
}
/* ---------------------------------------------------------------------------
\brief This function returns TRUE if background scan triggered by
LFR is in progress.
\param halHandle - The handle from HDD context.
\return boolean
---------------------------------------------------------------------------*/
tANI_BOOLEAN csrNeighborRoamScanRspPending (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
return (pMac->roam.neighborRoamInfo.scanRspPending);
}
/* ---------------------------------------------------------------------------
\brief This function returns TRUE if STA is in the middle of roaming states
\param halHandle - The handle from HDD context.
\return boolean
---------------------------------------------------------------------------*/
tANI_BOOLEAN csrNeighborMiddleOfRoaming (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
tANI_BOOLEAN val = (eCSR_NEIGHBOR_ROAM_STATE_REASSOCIATING == pMac->roam.neighborRoamInfo.neighborRoamState) ||
(eCSR_NEIGHBOR_ROAM_STATE_PREAUTHENTICATING == pMac->roam.neighborRoamInfo.neighborRoamState) ||
(eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE == pMac->roam.neighborRoamInfo.neighborRoamState) ||
(eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN == pMac->roam.neighborRoamInfo.neighborRoamState) ||
(eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN == pMac->roam.neighborRoamInfo.neighborRoamState);
return (val);
}
#ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamCandidateFoundIndHdlr
\brief This function is called by CSR as soon as TL posts the candidate
found indication to SME via MC thread
\param pMac - The handle returned by macOpen.
pMsg - Msg sent by PE
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamCandidateFoundIndHdlr(tpAniSirGlobal pMac, void* pMsg)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
/* we must be in connected state, if not ignore it */
if ((eCSR_NEIGHBOR_ROAM_STATE_CONNECTED != pNeighborRoamInfo->neighborRoamState)
|| (pNeighborRoamInfo->uOsRequestedHandoff))
{
smsLog(pMac, LOGE, FL("Received in not CONNECTED state OR uOsRequestedHandoff is set. Ignore it"));
status = eHAL_STATUS_FAILURE;
}
else
{
/* We are about to start a fresh scan cycle,
* purge non-P2P results from the past */
csrScanFlushSelectiveResult(pMac, VOS_FALSE);
/* Once it gets the candidates found indication from PE, will issue a scan
- req to PE with freshScan in scanreq structure set as follows:
0x42 - Return & purge LFR scan results
*/
status = csrScanRequestLfrResult(pMac, pNeighborRoamInfo->csrSessionId,
csrNeighborRoamScanResultRequestCallback, pMac);
}
return status;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamProcessHandoffReq
\brief This function is called start with the handoff process. First do a
SSID scan for the BSSID provided
\param pMac - The handle returned by macOpen.
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamProcessHandoffReq(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
tANI_U32 roamId;
tCsrRoamProfile *pProfile = NULL;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, pNeighborRoamInfo->csrSessionId );
tANI_U8 i = 0;
do
{
roamId = GET_NEXT_ROAM_ID(&pMac->roam);
status = palAllocateMemory(pMac->hHdd, (void **)&pProfile, sizeof(tCsrRoamProfile));
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGE, FL("Memory alloc failed"));
break;
}
palZeroMemory(pMac->hHdd, pProfile, sizeof(tCsrRoamProfile));
status = csrRoamCopyProfile(pMac, pProfile, pSession->pCurRoamProfile);
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGE, FL("Profile copy failed"));
break;
}
//Add the BSSID & Channel
pProfile->BSSIDs.numOfBSSIDs = 1;
pProfile->BSSIDs.bssid = vos_mem_malloc(sizeof(tSirMacAddr) * pProfile->BSSIDs.numOfBSSIDs);
if (NULL == pProfile->BSSIDs.bssid)
{
smsLog(pMac, LOGE, FL("mem alloc failed for BSSID"));
status = eHAL_STATUS_FAILURE;
break;
}
vos_mem_zero(pProfile->BSSIDs.bssid, sizeof(tSirMacAddr) * pProfile->BSSIDs.numOfBSSIDs);
/* Populate the BSSID from handoff info received from HDD */
for (i = 0; i < pProfile->BSSIDs.numOfBSSIDs; i++)
{
vos_mem_copy(&pProfile->BSSIDs.bssid[i],
pNeighborRoamInfo->handoffReqInfo.bssid, sizeof(tSirMacAddr));
}
pProfile->ChannelInfo.numOfChannels = 1;
pProfile->ChannelInfo.ChannelList =
vos_mem_malloc(sizeof(*pProfile->ChannelInfo.ChannelList) *
pProfile->ChannelInfo.numOfChannels);
if (NULL == pProfile->ChannelInfo.ChannelList)
{
smsLog(pMac, LOGE, FL("mem alloc failed for ChannelList"));
status = eHAL_STATUS_FAILURE;
break;
}
pProfile->ChannelInfo.ChannelList[0] = pNeighborRoamInfo->handoffReqInfo.channel;
//clean up csr cache first
//csrScanFlushSelectiveResult(pMac, VOS_FALSE);
//do a SSID scan
status = csrScanForSSID(pMac, pNeighborRoamInfo->csrSessionId, pProfile, roamId, FALSE);
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGE, FL("SSID scan failed"));
}
}while(0);
if(NULL != pProfile)
{
csrReleaseProfile(pMac, pProfile);
palFreeMemory(pMac->hHdd, pProfile);
}
return status;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamSssidScanDone
\brief This function is called once SSID scan is done. If SSID scan failed
to find our candidate add an entry to csr scan cache ourself before starting
the handoff process
\param pMac - The handle returned by macOpen.
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamSssidScanDone(tpAniSirGlobal pMac, eHalStatus status)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus hstatus;
smsLog(pMac, LOGE, FL("called "));
/* we must be in connected state, if not ignore it */
if (eCSR_NEIGHBOR_ROAM_STATE_CONNECTED != pNeighborRoamInfo->neighborRoamState)
{
smsLog(pMac, LOGE, FL("Received in not CONNECTED state. Ignore it"));
return eHAL_STATUS_FAILURE;
}
//if SSID scan failed to find our candidate add an entry to csr scan cache ourself
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGE, FL("Add an entry to csr scan cache"));
hstatus = csrScanCreateEntryInScanCache(pMac, pNeighborRoamInfo->csrSessionId,
pNeighborRoamInfo->handoffReqInfo.bssid,
pNeighborRoamInfo->handoffReqInfo.channel);
if (eHAL_STATUS_SUCCESS != hstatus)
{
smsLog(pMac, LOGE, FL("csrScanCreateEntryInScanCache failed with status %d"), hstatus);
return eHAL_STATUS_FAILURE;
}
}
/* Now we have completed scanning for the candidate provided by HDD. Let move on to HO*/
hstatus = csrNeighborRoamProcessScanComplete(pMac);
if (eHAL_STATUS_SUCCESS != hstatus)
{
smsLog(pMac, LOGE, FL("Neighbor scan process complete failed with status %d"), hstatus);
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamHandoffReqHdlr
\brief This function is called by CSR as soon as it gets a handoff request
to SME via MC thread
\param pMac - The handle returned by macOpen.
pMsg - Msg sent by HDD
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamHandoffReqHdlr(tpAniSirGlobal pMac, void* pMsg)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
tAniHandoffReq *pHandoffReqInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
/* we must be in connected state, if not ignore it */
if (eCSR_NEIGHBOR_ROAM_STATE_CONNECTED != pNeighborRoamInfo->neighborRoamState)
{
smsLog(pMac, LOGE, FL("Received in not CONNECTED state. Ignore it"));
status = eHAL_STATUS_FAILURE;
}
else
{
//save the handoff info came from HDD as part of the reassoc req
pHandoffReqInfo = (tAniHandoffReq *)pMsg;
if (NULL != pHandoffReqInfo)
{
//sanity check
if (VOS_FALSE == vos_mem_compare(pHandoffReqInfo->bssid,
pNeighborRoamInfo->currAPbssid,
sizeof(tSirMacAddr)))
{
pNeighborRoamInfo->handoffReqInfo.channel = pHandoffReqInfo->channel;
vos_mem_copy(pNeighborRoamInfo->handoffReqInfo.bssid,
pHandoffReqInfo->bssid,
6);
pNeighborRoamInfo->uOsRequestedHandoff = 1;
status = csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_STOP,
REASON_OS_REQUESTED_ROAMING_NOW);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, FL("csrRoamOffloadScan failed"));
pNeighborRoamInfo->uOsRequestedHandoff = 0;
}
}
else
{
smsLog(pMac, LOGE, FL("Received req has same BSSID as current AP!!"));
status = eHAL_STATUS_FAILURE;
}
}
else
{
smsLog(pMac, LOGE, FL("Received msg is NULL"));
status = eHAL_STATUS_FAILURE;
}
}
return status;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamProceedWithHandoffReq
\brief This function is called by CSR as soon as it gets rsp back for
ROAM_SCAN_OFFLOAD_STOP with reason REASON_OS_REQUESTED_ROAMING_NOW
\param pMac - The handle returned by macOpen.
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamProceedWithHandoffReq(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
eHalStatus status = eHAL_STATUS_SUCCESS;
/* we must be in connected state, if not ignore it */
if ((eCSR_NEIGHBOR_ROAM_STATE_CONNECTED != pNeighborRoamInfo->neighborRoamState)
|| (!pNeighborRoamInfo->uOsRequestedHandoff))
{
smsLog(pMac, LOGE, FL("Received in not CONNECTED state or uOsRequestedHandoff is not set. Ignore it"));
status = eHAL_STATUS_FAILURE;
}
else
{
//Let's go ahead with handoff
status = csrNeighborRoamProcessHandoffReq(pMac);
}
if(!HAL_STATUS_SUCCESS(status))
{
pNeighborRoamInfo->uOsRequestedHandoff = 0;
}
return status;
}
/* ---------------------------------------------------------------------------
\fn csrNeighborRoamStartLfrScan
\brief This function is called if HDD requested handoff failed for some
reason. start the LFR logic at that point.By the time, this function is
called, a STOP command has already been issued.
\param pMac - The handle returned by macOpen.
\return eHAL_STATUS_SUCCESS on success, corresponding error code otherwise
---------------------------------------------------------------------------*/
eHalStatus csrNeighborRoamStartLfrScan(tpAniSirGlobal pMac)
{
tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo;
pNeighborRoamInfo->uOsRequestedHandoff = 0;
/* There is no candidate or We are not roaming Now.
* Inform the FW to restart Roam Offload Scan */
csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_START, REASON_NO_CAND_FOUND_OR_NOT_ROAMING_NOW);
return eHAL_STATUS_SUCCESS;
}
#endif //WLAN_FEATURE_ROAM_SCAN_OFFLOAD
#endif /* WLAN_FEATURE_NEIGHBOR_ROAMING */
| gpl-2.0 |
rispo/almas | dep/acelite/ace/OS_NS_stdlib.cpp | 264 | 30547 | // $Id: OS_NS_stdlib.cpp 96017 2012-08-08 22:18:09Z mitza $
#include "ace/OS_NS_stdlib.h"
#include "ace/Default_Constants.h"
#if !defined (ACE_HAS_INLINED_OSCALLS)
# include "ace/OS_NS_stdlib.inl"
#endif /* ACE_HAS_INLINED_OSCALLS */
#include "ace/OS_Memory.h"
#include "ace/OS_NS_unistd.h"
#include "ace/OS_NS_ctype.h"
#if defined (ACE_LACKS_MKTEMP) \
|| defined (ACE_LACKS_MKSTEMP) \
|| defined (ACE_LACKS_REALPATH)
# include "ace/OS_NS_stdio.h"
# include "ace/OS_NS_sys_stat.h"
#endif /* ACE_LACKS_MKTEMP || ACE_LACKS_MKSTEMP || ACE_LACKS_REALPATH */
#if defined (ACE_LACKS_MKSTEMP)
# include "ace/OS_NS_fcntl.h"
# include "ace/OS_NS_ctype.h"
# include "ace/OS_NS_sys_time.h"
# include "ace/OS_NS_Thread.h"
# include "ace/Numeric_Limits.h"
#endif /* ACE_LACKS_MKSTEMP */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_EXIT_HOOK ACE_OS::exit_hook_ = 0;
void *
ACE_OS::calloc (size_t elements, size_t sizeof_elements)
{
#if !defined (ACE_HAS_WINCE)
return ACE_CALLOC_FUNC (elements, sizeof_elements);
#else
// @@ This will probably not work since it doesn't consider
// alignment properly.
return ACE_MALLOC_FUNC (elements * sizeof_elements);
#endif /* ACE_HAS_WINCE */
}
void
ACE_OS::exit (int status)
{
ACE_OS_TRACE ("ACE_OS::exit");
#if defined (ACE_HAS_NONSTATIC_OBJECT_MANAGER) && !defined (ACE_HAS_WINCE) && !defined (ACE_DOESNT_INSTANTIATE_NONSTATIC_OBJECT_MANAGER)
// Shut down the ACE_Object_Manager, if it had registered its exit_hook.
// With ACE_HAS_NONSTATIC_OBJECT_MANAGER, the ACE_Object_Manager is
// instantiated on the main's stack. ::exit () doesn't destroy it.
if (exit_hook_)
(*exit_hook_) ();
#endif /* ACE_HAS_NONSTATIC_OBJECT_MANAGER && !ACE_HAS_WINCE && !ACE_DOESNT_INSTANTIATE_NONSTATIC_OBJECT_MANAGER */
#if defined (ACE_WIN32)
::ExitProcess ((UINT) status);
#else
::exit (status);
#endif /* ACE_WIN32 */
}
void
ACE_OS::free (void *ptr)
{
ACE_FREE_FUNC (ACE_MALLOC_T (ptr));
}
// You may be asking yourself, why are we doing this? Well, in winbase.h,
// MS didn't follow their normal Api_FunctionA and Api_FunctionW style,
// so we have to #undef their define to get access to the unicode version.
// And because we don't want to #undef this for the users code, we keep
// this method in the .cpp file.
#if defined (ACE_WIN32) && defined (UNICODE) && !defined (ACE_USES_TCHAR)
#undef GetEnvironmentStrings
#endif /* ACE_WIN32 && UNICODE !ACE_USES_TCHAR */
ACE_TCHAR *
ACE_OS::getenvstrings (void)
{
#if defined (ACE_LACKS_GETENVSTRINGS)
ACE_NOTSUP_RETURN (0);
#elif defined (ACE_WIN32)
# if defined (ACE_USES_WCHAR)
return ::GetEnvironmentStringsW ();
# else /* ACE_USES_WCHAR */
return ::GetEnvironmentStrings ();
# endif /* ACE_USES_WCHAR */
#else /* ACE_WIN32 */
ACE_NOTSUP_RETURN (0);
#endif /* ACE_WIN32 */
}
// Return a dynamically allocated duplicate of <str>, substituting the
// environment variables of form $VAR_NAME. Note that the pointer is
// allocated with <ACE_OS::malloc> and must be freed by
// <ACE_OS::free>.
ACE_TCHAR *
ACE_OS::strenvdup (const ACE_TCHAR *str)
{
#if defined (ACE_HAS_WINCE)
// WinCE doesn't have environment variables so we just skip it.
return ACE_OS::strdup (str);
#elif defined (ACE_LACKS_STRENVDUP)
ACE_UNUSED_ARG (str);
ACE_NOTSUP_RETURN (0);
#else
const ACE_TCHAR * start = 0;
if ((start = ACE_OS::strchr (str, ACE_TEXT ('$'))) != 0)
{
ACE_TCHAR buf[ACE_DEFAULT_ARGV_BUFSIZ];
size_t var_len = ACE_OS::strcspn (&start[1],
ACE_TEXT ("$~!#%^&*()-+=\\|/?,.;:'\"`[]{} \t\n\r"));
ACE_OS::strncpy (buf, &start[1], var_len);
buf[var_len++] = ACE_TEXT ('\0');
# if defined (ACE_WIN32)
// Always use the ACE_TCHAR for Windows.
ACE_TCHAR *temp = ACE_OS::getenv (buf);
# else
// Use char * for environment on non-Windows.
char *temp = ACE_OS::getenv (ACE_TEXT_ALWAYS_CHAR (buf));
# endif /* ACE_WIN32 */
size_t buf_len = ACE_OS::strlen (str) + 1;
if (temp != 0)
buf_len += ACE_OS::strlen (temp) - var_len;
ACE_TCHAR * buf_p = buf;
if (buf_len > ACE_DEFAULT_ARGV_BUFSIZ)
{
buf_p =
(ACE_TCHAR *) ACE_OS::malloc (buf_len * sizeof (ACE_TCHAR));
if (buf_p == 0)
{
errno = ENOMEM;
return 0;
}
}
ACE_TCHAR * p = buf_p;
size_t len = start - str;
ACE_OS::strncpy (p, str, len);
p += len;
if (temp != 0)
{
# if defined (ACE_WIN32)
p = ACE_OS::strecpy (p, temp) - 1;
# else
p = ACE_OS::strecpy (p, ACE_TEXT_CHAR_TO_TCHAR (temp)) - 1;
# endif /* ACE_WIN32 */
}
else
{
ACE_OS::strncpy (p, start, var_len);
p += var_len;
*p = ACE_TEXT ('\0');
}
ACE_OS::strcpy (p, &start[var_len]);
return (buf_p == buf) ? ACE_OS::strdup (buf) : buf_p;
}
else
return ACE_OS::strdup (str);
#endif /* ACE_HAS_WINCE */
}
#if !defined (ACE_HAS_ITOA)
char *
ACE_OS::itoa_emulation (int value, char *string, int radix)
{
char *e = string;
char *b = string;
// Short circuit if 0
if (value == 0)
{
string[0] = '0';
string[1] = 0;
return string;
}
// If negative and base 10, print a - and then do the
// number.
if (value < 0 && radix == 10)
{
string[0] = '-';
++b;
++e; // Don't overwrite the negative sign.
value = -value; // Drop negative sign so character selection is correct.
}
// Convert to base <radix>, but in reverse order
while (value != 0)
{
int mod = value % radix;
value = value / radix;
*e++ = (mod < 10) ? '0' + mod : 'a' + mod - 10;
}
*e-- = 0;
// Now reverse the string to get the correct result
while (e > b)
{
char temp = *e;
*e = *b;
*b = temp;
++b;
--e;
}
return string;
}
#endif /* !ACE_HAS_ITOA */
#if defined (ACE_HAS_WCHAR) && defined (ACE_LACKS_ITOW)
wchar_t *
ACE_OS::itow_emulation (int value, wchar_t *string, int radix)
{
wchar_t *e = string;
wchar_t *b = string;
// Short circuit if 0
if (value == 0)
{
string[0] = '0';
string[1] = 0;
return string;
}
// If negative and base 10, print a - and then do the
// number.
if (value < 0 && radix == 10)
{
string[0] = '-';
b++;
}
// Convert to base <radix>, but in reverse order
while (value != 0)
{
int mod = value % radix;
value = value / radix;
*e++ = (mod < 10) ? '0' + mod : 'a' + mod - 10;
}
*e-- = 0;
// Now reverse the string to get the correct result
while (e > b)
{
wchar_t temp = *e;
*e = *b;
*b = temp;
++b;
--e;
}
return string;
}
#endif /* ACE_HAS_WCHAR && ACE_LACKS_ITOW */
void *
ACE_OS::malloc (size_t nbytes)
{
return ACE_MALLOC_FUNC (nbytes);
}
#if defined (ACE_LACKS_MKTEMP)
ACE_TCHAR *
ACE_OS::mktemp (ACE_TCHAR *s)
{
ACE_OS_TRACE ("ACE_OS::mktemp");
if (s == 0)
// check for null template string failed!
return 0;
else
{
ACE_TCHAR *xxxxxx = ACE_OS::strstr (s, ACE_TEXT ("XXXXXX"));
if (xxxxxx == 0)
// the template string doesn't contain "XXXXXX"!
return s;
else
{
ACE_TCHAR unique_letter = ACE_TEXT ('a');
ACE_stat sb;
// Find an unused filename for this process. It is assumed
// that the user will open the file immediately after
// getting this filename back (so, yes, there is a race
// condition if multiple threads in a process use the same
// template). This appears to match the behavior of the
// SunOS 5.5 mktemp().
ACE_OS::sprintf (xxxxxx,
ACE_TEXT ("%05d%c"),
ACE_OS::getpid (),
unique_letter);
while (ACE_OS::stat (s, &sb) >= 0)
{
if (++unique_letter <= ACE_TEXT ('z'))
ACE_OS::sprintf (xxxxxx,
ACE_TEXT ("%05d%c"),
ACE_OS::getpid (),
unique_letter);
else
{
// maximum of 26 unique files per template, per process
ACE_OS::sprintf (xxxxxx, ACE_TEXT ("%s"), ACE_TEXT (""));
return s;
}
}
}
return s;
}
}
#endif /* ACE_LACKS_MKTEMP */
void *
ACE_OS::realloc (void *ptr, size_t nbytes)
{
return ACE_REALLOC_FUNC (ACE_MALLOC_T (ptr), nbytes);
}
#if defined (ACE_LACKS_REALPATH)
char *
ACE_OS::realpath (const char *file_name,
char *resolved_name)
{
ACE_OS_TRACE ("ACE_OS::realpath");
if (file_name == 0)
{
// Single Unix Specification V3:
// Return an error if parameter is a null pointer.
errno = EINVAL;
return 0;
}
if (*file_name == '\0')
{
// Single Unix Specification V3:
// Return an error if the file_name argument points
// to an empty string.
errno = ENOENT;
return 0;
}
char* rpath;
if (resolved_name == 0)
{
// Single Unix Specification V3:
// Return an error if parameter is a null pointer.
//
// To match glibc realpath() and Win32 _fullpath() behavior,
// allocate room for the return value if resolved_name is
// a null pointer.
rpath = static_cast<char*>(ACE_OS::malloc (PATH_MAX));
if (rpath == 0)
{
errno = ENOMEM;
return 0;
}
}
else
{
rpath = resolved_name;
}
char* dest;
if (*file_name != '/')
{
// file_name is relative path so CWD needs to be added
if (ACE_OS::getcwd (rpath, PATH_MAX) == 0)
{
if (resolved_name == 0)
ACE_OS::free (rpath);
return 0;
}
dest = ACE_OS::strchr (rpath, '\0');
}
else
{
dest = rpath;
}
#if !defined (ACE_LACKS_SYMLINKS)
char expand_buf[PATH_MAX]; // Extra buffer needed to expand symbolic links
int nlinks = 0;
#endif
while (*file_name)
{
*dest++ = '/';
// Skip multiple separators
while (*file_name == '/')
++file_name;
char* start = dest;
// Process one path component
while (*file_name && *file_name != '/')
{
*dest++ = *file_name++;
if (dest - rpath > PATH_MAX)
{
errno = ENAMETOOLONG;
if (resolved_name == 0)
ACE_OS::free (rpath);
return 0;
}
}
if (start == dest) // Are we done?
{
if (dest - rpath > 1)
--dest; // Remove trailing separator if not at root
break;
}
else if (dest - start == 1 && *start == '.')
{
dest -= 2; // Remove "./"
}
else if (dest - start == 2 && *start == '.' && *(start +1) == '.')
{
dest -= 3; // Remove "../"
if (dest > rpath) // Remove the last path component if not at root
while (*--dest != '/')
;
}
# if !defined (ACE_LACKS_SYMLINKS)
else
{
ACE_stat st;
*dest = '\0';
if (ACE_OS::lstat(rpath, &st) < 0)
{
if (resolved_name == 0)
ACE_OS::free (rpath);
return 0;
}
// Check if current path is a link
if (S_ISLNK (st.st_mode))
{
if (++nlinks > MAXSYMLINKS)
{
errno = ELOOP;
if (resolved_name == 0)
ACE_OS::free (rpath);
return 0;
}
char link_buf[PATH_MAX];
ssize_t link_len = ACE_OS::readlink (rpath, link_buf, PATH_MAX);
int tail_len = ACE_OS::strlen (file_name) + 1;
// Check if there is room to expand link?
if (link_len + tail_len > PATH_MAX)
{
errno = ENAMETOOLONG;
if (resolved_name == 0)
ACE_OS::free (rpath);
return 0;
}
// Move tail and prefix it with expanded link
ACE_OS::memmove (expand_buf + link_len, file_name, tail_len);
ACE_OS::memcpy (expand_buf, link_buf, link_len);
if (*link_buf == '/') // Absolute link?
{
dest = rpath;
}
else // Relative link, remove expanded link component
{
--dest;
while (*--dest != '/')
;
}
file_name = expand_buf; // Source path is now in expand_buf
}
}
# endif /* ACE_LACKS_SYMLINKS */
}
*dest = '\0';
return rpath;
}
#endif /* ACE_LACKS_REALPATH */
#if defined (ACE_LACKS_STRTOL)
long
ACE_OS::strtol_emulation (const char *nptr, char **endptr, int base)
{
register const char *s = nptr;
register unsigned long acc;
register int c;
register unsigned long cutoff;
register int neg = 0, any, cutlim;
/*
* Skip white space and pick up leading +/- sign if any.
* If base is 0, allow 0x for hex and 0 for octal, else
* assume decimal; if base is already 16, allow 0x.
*/
do {
c = *s++;
} while (ACE_OS::ace_isspace(c));
if (c == '-') {
neg = 1;
c = *s++;
} else if (c == '+')
c = *s++;
if ((base == 0 || base == 16) &&
c == '0' && (*s == 'x' || *s == 'X')) {
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == '0' ? 8 : 10;
/*
* Compute the cutoff value between legal numbers and illegal
* numbers. That is the largest legal value, divided by the
* base. An input number that is greater than this value, if
* followed by a legal input character, is too big. One that
* is equal to this value may be valid or not; the limit
* between valid and invalid numbers is then based on the last
* digit. For instance, if the range for longs is
* [-2147483648..2147483647] and the input base is 10,
* cutoff will be set to 214748364 and cutlim to either
* 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
* a value > 214748364, or equal but the next digit is > 7 (or 8),
* the number is too big, and we will return a range error.
*
* Set any if any `digits' consumed; make it negative to indicate
* overflow.
*/
cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
cutlim = cutoff % (unsigned long)base;
cutoff /= (unsigned long)base;
for (acc = 0, any = 0;; c = *s++) {
if (ACE_OS::ace_isdigit(c))
c -= '0';
else if (ACE_OS::ace_isalpha(c))
c -= ACE_OS::ace_isupper(c) ? 'A' - 10 : 'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
any = -1;
else {
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0) {
acc = neg ? LONG_MIN : LONG_MAX;
errno = ERANGE;
} else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = any ? (char *)s - 1 : (char *)nptr;
return (acc);
}
#endif /* ACE_LACKS_STRTOL */
#if defined (ACE_HAS_WCHAR) && defined (ACE_LACKS_WCSTOL)
long
ACE_OS::wcstol_emulation (const wchar_t *nptr,
wchar_t **endptr,
int base)
{
register const wchar_t *s = nptr;
register unsigned long acc;
register int c;
register unsigned long cutoff;
register int neg = 0, any, cutlim;
/*
* Skip white space and pick up leading +/- sign if any.
* If base is 0, allow 0x for hex and 0 for octal, else
* assume decimal; if base is already 16, allow 0x.
*/
do {
c = *s++;
} while (ACE_OS::ace_isspace(c));
if (c == L'-') {
neg = 1;
c = *s++;
} else if (c == L'+')
c = *s++;
if ((base == 0 || base == 16) &&
c == '0' && (*s == L'x' || *s == L'X')) {
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == L'0' ? 8 : 10;
/*
* See strtol for comments as to the logic used.
*/
cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
cutlim = cutoff % (unsigned long)base;
cutoff /= (unsigned long)base;
for (acc = 0, any = 0;; c = *s++) {
if (ACE_OS::ace_isdigit(c))
c -= L'0';
else if (ACE_OS::ace_isalpha(c))
c -= ACE_OS::ace_isupper(c) ? L'A' - 10 : L'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
any = -1;
else {
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0) {
acc = neg ? LONG_MIN : LONG_MAX;
errno = ERANGE;
} else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = any ? (wchar_t *)s - 1 : (wchar_t *)nptr;
return (acc);
}
#endif /* ACE_HAS_WCHAR && ACE_LACKS_WCSTOL */
#if defined (ACE_LACKS_STRTOUL)
unsigned long
ACE_OS::strtoul_emulation (const char *nptr,
char **endptr,
register int base)
{
register const char *s = nptr;
register unsigned long acc;
register int c;
register unsigned long cutoff;
register int neg = 0, any, cutlim;
/*
* See strtol for comments as to the logic used.
*/
do
c = *s++;
while (ACE_OS::ace_isspace(c));
if (c == '-')
{
neg = 1;
c = *s++;
}
else if (c == '+')
c = *s++;
if ((base == 0 || base == 16) &&
c == '0' && (*s == 'x' || *s == 'X'))
{
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == '0' ? 8 : 10;
cutoff = (unsigned long) ULONG_MAX / (unsigned long) base;
cutlim = (unsigned long) ULONG_MAX % (unsigned long) base;
for (acc = 0, any = 0;; c = *s++)
{
if (ACE_OS::ace_isdigit(c))
c -= '0';
else if (ACE_OS::ace_isalpha(c))
c -= ACE_OS::ace_isupper(c) ? 'A' - 10 : 'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
any = -1;
else
{
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0)
{
acc = ULONG_MAX;
errno = ERANGE;
}
else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = any ? (char *) s - 1 : (char *) nptr;
return (acc);
}
#endif /* ACE_LACKS_STRTOUL */
#if defined (ACE_HAS_WCHAR) && defined (ACE_LACKS_WCSTOUL)
unsigned long
ACE_OS::wcstoul_emulation (const wchar_t *nptr,
wchar_t **endptr,
int base)
{
register const wchar_t *s = nptr;
register unsigned long acc;
register int c;
register unsigned long cutoff;
register int neg = 0, any, cutlim;
/*
* See strtol for comments as to the logic used.
*/
do
c = *s++;
while (ACE_OS::ace_isspace(c));
if (c == L'-')
{
neg = 1;
c = *s++;
}
else if (c == L'+')
c = *s++;
if ((base == 0 || base == 16) &&
c == L'0' && (*s == L'x' || *s == L'X'))
{
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == L'0' ? 8 : 10;
cutoff = (unsigned long) ULONG_MAX / (unsigned long) base;
cutlim = (unsigned long) ULONG_MAX % (unsigned long) base;
for (acc = 0, any = 0;; c = *s++)
{
if (ACE_OS::ace_isdigit(c))
c -= L'0';
else if (ACE_OS::ace_isalpha(c))
c -= ACE_OS::ace_isupper(c) ? L'A' - 10 : L'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
any = -1;
else
{
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0)
{
acc = ULONG_MAX;
errno = ERANGE;
}
else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = any ? (wchar_t *) s - 1 : (wchar_t *) nptr;
return (acc);
}
#endif /* ACE_HAS_WCHAR && ACE_LACKS_WCSTOUL */
#if defined (ACE_LACKS_STRTOLL)
ACE_INT64
ACE_OS::strtoll_emulation (const char *nptr,
char **endptr,
register int base)
{
register const char *s = nptr;
register ACE_UINT64 acc;
register int c;
register ACE_UINT64 cutoff;
register int neg = 0, any, cutlim;
/*
* Skip white space and pick up leading +/- sign if any.
* If base is 0, allow 0x for hex and 0 for octal, else
* assume decimal; if base is already 16, allow 0x.
*/
do {
c = *s++;
} while (ACE_OS::ace_isspace(c));
if (c == '-') {
neg = 1;
c = *s++;
} else if (c == '+')
c = *s++;
if ((base == 0 || base == 16) &&
c == '0' && (*s == 'x' || *s == 'X')) {
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == '0' ? 8 : 10;
/*
* See strtol for comments as to the logic used.
*/
cutoff = neg ? -(ACE_UINT64)ACE_INT64_MIN : ACE_INT64_MAX;
cutlim = cutoff % (ACE_UINT64)base;
cutoff /= (ACE_UINT64)base;
for (acc = 0, any = 0;; c = *s++) {
if (ACE_OS::ace_isdigit(c))
c -= '0';
else if (ACE_OS::ace_isalpha(c))
c -= ACE_OS::ace_isupper(c) ? 'A' - 10 : 'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
any = -1;
else {
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0) {
acc = neg ? ACE_INT64_MIN : ACE_INT64_MAX;
errno = ERANGE;
} else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = any ? (char *)s - 1 : (char *)nptr;
return (acc);
}
#endif /* ACE_LACKS_STRTOLL */
#if defined (ACE_HAS_WCHAR) && defined (ACE_LACKS_WCSTOLL)
ACE_INT64
ACE_OS::wcstoll_emulation (const wchar_t *nptr,
wchar_t **endptr,
int base)
{
register const wchar_t *s = nptr;
register ACE_UINT64 acc;
register int c;
register ACE_UINT64 cutoff;
register int neg = 0, any, cutlim;
/*
* Skip white space and pick up leading +/- sign if any.
* If base is 0, allow 0x for hex and 0 for octal, else
* assume decimal; if base is already 16, allow 0x.
*/
do {
c = *s++;
} while (ACE_OS::ace_isspace(c));
if (c == L'-') {
neg = 1;
c = *s++;
} else if (c == L'+')
c = *s++;
if ((base == 0 || base == 16) &&
c == L'0' && (*s == L'x' || *s == L'X')) {
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == L'0' ? 8 : 10;
/*
* See strtol for comments as to the logic used.
*/
cutoff = neg ? -(ACE_UINT64)ACE_INT64_MIN : ACE_INT64_MAX;
cutlim = cutoff % (ACE_UINT64)base;
cutoff /= (ACE_UINT64)base;
for (acc = 0, any = 0;; c = *s++) {
if (ACE_OS::ace_isdigit(c))
c -= L'0';
else if (ACE_OS::ace_isalpha(c))
c -= ACE_OS::ace_isupper(c) ? L'A' - 10 : L'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
any = -1;
else {
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0) {
acc = neg ? ACE_INT64_MIN : ACE_INT64_MAX;
errno = ERANGE;
} else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = any ? (wchar_t *)s - 1 : (wchar_t *)nptr;
return (acc);
}
#endif /* ACE_HAS_WCHAR && ACE_LACKS_WCSTOLL */
#if defined (ACE_LACKS_STRTOULL)
ACE_UINT64
ACE_OS::strtoull_emulation (const char *nptr,
char **endptr,
register int base)
{
register const char *s = nptr;
register ACE_UINT64 acc;
register int c;
register ACE_UINT64 cutoff;
register int neg = 0, any, cutlim;
/*
* See strtol for comments as to the logic used.
*/
do
c = *s++;
while (ACE_OS::ace_isspace(c));
if (c == '-')
{
neg = 1;
c = *s++;
}
else if (c == '+')
c = *s++;
if ((base == 0 || base == 16) &&
c == '0' && (*s == 'x' || *s == 'X'))
{
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == '0' ? 8 : 10;
cutoff = (ACE_UINT64) ACE_UINT64_MAX / (ACE_UINT64) base;
cutlim = (ACE_UINT64) ACE_UINT64_MAX % (ACE_UINT64) base;
for (acc = 0, any = 0;; c = *s++)
{
if (ACE_OS::ace_isdigit(c))
c -= '0';
else if (ACE_OS::ace_isalpha(c))
c -= ACE_OS::ace_isupper(c) ? 'A' - 10 : 'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
any = -1;
else
{
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0)
{
acc = ACE_UINT64_MAX;
errno = ERANGE;
}
else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = any ? (char *) s - 1 : (char *) nptr;
return (acc);
}
#endif /* ACE_LACKS_STRTOULL */
#if defined (ACE_HAS_WCHAR) && defined (ACE_LACKS_WCSTOULL)
ACE_UINT64
ACE_OS::wcstoull_emulation (const wchar_t *nptr,
wchar_t **endptr,
int base)
{
register const wchar_t *s = nptr;
register ACE_UINT64 acc;
register int c;
register ACE_UINT64 cutoff;
register int neg = 0, any, cutlim;
/*
* See strtol for comments as to the logic used.
*/
do
c = *s++;
while (ACE_OS::ace_isspace(c));
if (c == L'-')
{
neg = 1;
c = *s++;
}
else if (c == L'+')
c = *s++;
if ((base == 0 || base == 16) &&
c == L'0' && (*s == L'x' || *s == L'X'))
{
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == L'0' ? 8 : 10;
cutoff = (ACE_UINT64) ACE_UINT64_MAX / (ACE_UINT64) base;
cutlim = (ACE_UINT64) ACE_UINT64_MAX % (ACE_UINT64) base;
for (acc = 0, any = 0;; c = *s++)
{
if (ACE_OS::ace_isdigit(c))
c -= L'0';
else if (ACE_OS::ace_isalpha(c))
c -= ACE_OS::ace_isupper(c) ? L'A' - 10 : L'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
any = -1;
else
{
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0)
{
acc = ACE_UINT64_MAX;
errno = ERANGE;
}
else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = any ? (wchar_t *) s - 1 : (wchar_t *) nptr;
return (acc);
}
#endif /* ACE_HAS_WCHAR && ACE_LACKS_WCSTOULL */
#if defined (ACE_LACKS_MKSTEMP)
ACE_HANDLE
ACE_OS::mkstemp_emulation (ACE_TCHAR * s)
{
if (s == 0)
{
errno = EINVAL;
return ACE_INVALID_HANDLE;
}
// The "XXXXXX" template to be filled in.
ACE_TCHAR * const t = ACE_OS::strstr (s, ACE_TEXT ("XXXXXX"));
if (t == 0)
{
errno = EINVAL;
return ACE_INVALID_HANDLE;
}
static unsigned int const NUM_RETRIES = 50;
static unsigned int const NUM_CHARS = 6; // Do not change!
// Use ACE_Time_Value::msec(ACE_UINT64&) as opposed to
// ACE_Time_Value::msec(void) to avoid truncation.
ACE_UINT64 msec;
// Use a const ACE_Time_Value to resolve ambiguity between
// ACE_Time_Value::msec (long) and ACE_Time_Value::msec(ACE_UINT64&) const.
ACE_Time_Value const now = ACE_OS::gettimeofday();
now.msec (msec);
// Add the process and thread ids to ensure uniqueness.
msec += ACE_OS::getpid();
msec += (size_t) ACE_OS::thr_self();
// ACE_thread_t may be a char* (returned by ACE_OS::thr_self()) so
// we need to use a C-style cast as a catch-all in order to use a
// static_cast<> to an integral type.
unsigned int seed = static_cast<unsigned int> (msec);
// We only care about UTF-8 / ASCII characters in generated
// filenames. A UTF-16 or UTF-32 character could potentially cause
// a very large space to be searched in the below do/while() loop,
// greatly slowing down this mkstemp() implementation. It is more
// practical to limit the search space to UTF-8 / ASCII characters
// (i.e. 127 characters).
//
// Note that we can't make this constant static since the compiler
// may not inline the return value of ACE_Numeric_Limits::max(),
// meaning multiple threads could potentially initialize this value
// in parallel.
float const MAX_VAL =
static_cast<float> (ACE_Numeric_Limits<char>::max ());
// Use high-order bits rather than low-order ones (e.g. rand() %
// MAX_VAL). See Numerical Recipes in C: The Art of Scientific
// Computing (William H. Press, Brian P. Flannery, Saul
// A. Teukolsky, William T. Vetterling; New York: Cambridge
// University Press, 1992 (2nd ed., p. 277).
//
// e.g.: MAX_VAL * rand() / (RAND_MAX + 1.0)
// Factor out the constant coefficient.
float const coefficient =
static_cast<float> (MAX_VAL / (RAND_MAX + 1.0f));
// @@ These nested loops may be ineffecient. Improvements are
// welcome.
for (unsigned int i = 0; i < NUM_RETRIES; ++i)
{
for (unsigned int n = 0; n < NUM_CHARS; ++n)
{
ACE_TCHAR r;
// This do/while() loop allows this alphanumeric character
// selection to work for EBCDIC, as well.
do
{
r = static_cast<ACE_TCHAR> (coefficient * ACE_OS::rand_r (&seed));
}
while (!ACE_OS::ace_isalnum (r));
t[n] = r;
}
static int const perms =
#if defined (ACE_WIN32)
0; /* Do not share while open. */
#else
0600; /* S_IRUSR | S_IWUSR */
#endif /* ACE_WIN32 */
// Create the file with the O_EXCL bit set to ensure that we're
// not subject to a symbolic link attack.
//
// Note that O_EXCL is subject to a race condition over NFS
// filesystems.
ACE_HANDLE const handle = ACE_OS::open (s,
O_RDWR | O_CREAT | O_EXCL,
perms);
if (handle != ACE_INVALID_HANDLE)
return handle;
}
errno = EEXIST; // Couldn't create a unique temporary file.
return ACE_INVALID_HANDLE;
}
#endif /* ACE_LACKS_MKSTEMP */
#if !defined (ACE_HAS_GETPROGNAME) && !defined (ACE_HAS_SETPROGNAME)
static const char *__progname = "";
#endif /* !ACE_HAS_GETPROGNAME && !ACE_HAS_SETPROGNAME */
#if !defined (ACE_HAS_GETPROGNAME)
const char*
ACE_OS::getprogname_emulation ()
{
return __progname;
}
#endif /* !ACE_HAS_GETPROGNAME */
#if !defined (ACE_HAS_SETPROGNAME)
void
ACE_OS::setprogname_emulation (const char* progname)
{
const char *p = ACE_OS::strrchr (progname, '/');
if (p != 0)
__progname = p + 1;
else
__progname = progname;
}
#endif /* !ACE_HAS_SETPROGNAME */
ACE_END_VERSIONED_NAMESPACE_DECL
| gpl-2.0 |
francescodiotalevi/linux-zynq-stable | drivers/ata/ahci_xgene.c | 520 | 24912 | /*
* AppliedMicro X-Gene SoC SATA Host Controller Driver
*
* Copyright (c) 2014, Applied Micro Circuits Corporation
* Author: Loc Ho <lho@apm.com>
* Tuan Phan <tphan@apm.com>
* Suman Tripathi <stripathi@apm.com>
*
* 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; either version 2 of the License, or (at your
* option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
* NOTE: PM support is not currently available.
*
*/
#include <linux/acpi.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/ahci_platform.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#include <linux/of_irq.h>
#include <linux/phy/phy.h>
#include "ahci.h"
#define DRV_NAME "xgene-ahci"
/* Max # of disk per a controller */
#define MAX_AHCI_CHN_PERCTR 2
/* MUX CSR */
#define SATA_ENET_CONFIG_REG 0x00000000
#define CFG_SATA_ENET_SELECT_MASK 0x00000001
/* SATA core host controller CSR */
#define SLVRDERRATTRIBUTES 0x00000000
#define SLVWRERRATTRIBUTES 0x00000004
#define MSTRDERRATTRIBUTES 0x00000008
#define MSTWRERRATTRIBUTES 0x0000000c
#define BUSCTLREG 0x00000014
#define IOFMSTRWAUX 0x00000018
#define INTSTATUSMASK 0x0000002c
#define ERRINTSTATUS 0x00000030
#define ERRINTSTATUSMASK 0x00000034
/* SATA host AHCI CSR */
#define PORTCFG 0x000000a4
#define PORTADDR_SET(dst, src) \
(((dst) & ~0x0000003f) | (((u32)(src)) & 0x0000003f))
#define PORTPHY1CFG 0x000000a8
#define PORTPHY1CFG_FRCPHYRDY_SET(dst, src) \
(((dst) & ~0x00100000) | (((u32)(src) << 0x14) & 0x00100000))
#define PORTPHY2CFG 0x000000ac
#define PORTPHY3CFG 0x000000b0
#define PORTPHY4CFG 0x000000b4
#define PORTPHY5CFG 0x000000b8
#define SCTL0 0x0000012C
#define PORTPHY5CFG_RTCHG_SET(dst, src) \
(((dst) & ~0xfff00000) | (((u32)(src) << 0x14) & 0xfff00000))
#define PORTAXICFG_EN_CONTEXT_SET(dst, src) \
(((dst) & ~0x01000000) | (((u32)(src) << 0x18) & 0x01000000))
#define PORTAXICFG 0x000000bc
#define PORTAXICFG_OUTTRANS_SET(dst, src) \
(((dst) & ~0x00f00000) | (((u32)(src) << 0x14) & 0x00f00000))
#define PORTRANSCFG 0x000000c8
#define PORTRANSCFG_RXWM_SET(dst, src) \
(((dst) & ~0x0000007f) | (((u32)(src)) & 0x0000007f))
/* SATA host controller AXI CSR */
#define INT_SLV_TMOMASK 0x00000010
/* SATA diagnostic CSR */
#define CFG_MEM_RAM_SHUTDOWN 0x00000070
#define BLOCK_MEM_RDY 0x00000074
/* Max retry for link down */
#define MAX_LINK_DOWN_RETRY 3
enum xgene_ahci_version {
XGENE_AHCI_V1 = 1,
XGENE_AHCI_V2,
};
struct xgene_ahci_context {
struct ahci_host_priv *hpriv;
struct device *dev;
u8 last_cmd[MAX_AHCI_CHN_PERCTR]; /* tracking the last command issued*/
u32 class[MAX_AHCI_CHN_PERCTR]; /* tracking the class of device */
void __iomem *csr_core; /* Core CSR address of IP */
void __iomem *csr_diag; /* Diag CSR address of IP */
void __iomem *csr_axi; /* AXI CSR address of IP */
void __iomem *csr_mux; /* MUX CSR address of IP */
};
static int xgene_ahci_init_memram(struct xgene_ahci_context *ctx)
{
dev_dbg(ctx->dev, "Release memory from shutdown\n");
writel(0x0, ctx->csr_diag + CFG_MEM_RAM_SHUTDOWN);
readl(ctx->csr_diag + CFG_MEM_RAM_SHUTDOWN); /* Force a barrier */
msleep(1); /* reset may take up to 1ms */
if (readl(ctx->csr_diag + BLOCK_MEM_RDY) != 0xFFFFFFFF) {
dev_err(ctx->dev, "failed to release memory from shutdown\n");
return -ENODEV;
}
return 0;
}
/**
* xgene_ahci_poll_reg_val- Poll a register on a specific value.
* @ap : ATA port of interest.
* @reg : Register of interest.
* @val : Value to be attained.
* @interval : waiting interval for polling.
* @timeout : timeout for achieving the value.
*/
static int xgene_ahci_poll_reg_val(struct ata_port *ap,
void __iomem *reg, unsigned
int val, unsigned long interval,
unsigned long timeout)
{
unsigned long deadline;
unsigned int tmp;
tmp = ioread32(reg);
deadline = ata_deadline(jiffies, timeout);
while (tmp != val && time_before(jiffies, deadline)) {
ata_msleep(ap, interval);
tmp = ioread32(reg);
}
return tmp;
}
/**
* xgene_ahci_restart_engine - Restart the dma engine.
* @ap : ATA port of interest
*
* Waits for completion of multiple commands and restarts
* the DMA engine inside the controller.
*/
static int xgene_ahci_restart_engine(struct ata_port *ap)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
struct ahci_port_priv *pp = ap->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
u32 fbs;
/*
* In case of PMP multiple IDENTIFY DEVICE commands can be
* issued inside PxCI. So need to poll PxCI for the
* completion of outstanding IDENTIFY DEVICE commands before
* we restart the DMA engine.
*/
if (xgene_ahci_poll_reg_val(ap, port_mmio +
PORT_CMD_ISSUE, 0x0, 1, 100))
return -EBUSY;
ahci_stop_engine(ap);
ahci_start_fis_rx(ap);
/*
* Enable the PxFBS.FBS_EN bit as it
* gets cleared due to stopping the engine.
*/
if (pp->fbs_supported) {
fbs = readl(port_mmio + PORT_FBS);
writel(fbs | PORT_FBS_EN, port_mmio + PORT_FBS);
fbs = readl(port_mmio + PORT_FBS);
}
hpriv->start_engine(ap);
return 0;
}
/**
* xgene_ahci_qc_issue - Issue commands to the device
* @qc: Command to issue
*
* Due to Hardware errata for IDENTIFY DEVICE command, the controller cannot
* clear the BSY bit after receiving the PIO setup FIS. This results in the dma
* state machine goes into the CMFatalErrorUpdate state and locks up. By
* restarting the dma engine, it removes the controller out of lock up state.
*
* Due to H/W errata, the controller is unable to save the PMP
* field fetched from command header before sending the H2D FIS.
* When the device returns the PMP port field in the D2H FIS, there is
* a mismatch and results in command completion failure. The
* workaround is to write the pmp value to PxFBS.DEV field before issuing
* any command to PMP.
*/
static unsigned int xgene_ahci_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ahci_host_priv *hpriv = ap->host->private_data;
struct xgene_ahci_context *ctx = hpriv->plat_data;
int rc = 0;
u32 port_fbs;
void *port_mmio = ahci_port_base(ap);
/*
* Write the pmp value to PxFBS.DEV
* for case of Port Mulitplier.
*/
if (ctx->class[ap->port_no] == ATA_DEV_PMP) {
port_fbs = readl(port_mmio + PORT_FBS);
port_fbs &= ~PORT_FBS_DEV_MASK;
port_fbs |= qc->dev->link->pmp << PORT_FBS_DEV_OFFSET;
writel(port_fbs, port_mmio + PORT_FBS);
}
if (unlikely((ctx->last_cmd[ap->port_no] == ATA_CMD_ID_ATA) ||
(ctx->last_cmd[ap->port_no] == ATA_CMD_PACKET) ||
(ctx->last_cmd[ap->port_no] == ATA_CMD_SMART)))
xgene_ahci_restart_engine(ap);
rc = ahci_qc_issue(qc);
/* Save the last command issued */
ctx->last_cmd[ap->port_no] = qc->tf.command;
return rc;
}
static bool xgene_ahci_is_memram_inited(struct xgene_ahci_context *ctx)
{
void __iomem *diagcsr = ctx->csr_diag;
return (readl(diagcsr + CFG_MEM_RAM_SHUTDOWN) == 0 &&
readl(diagcsr + BLOCK_MEM_RDY) == 0xFFFFFFFF);
}
/**
* xgene_ahci_read_id - Read ID data from the specified device
* @dev: device
* @tf: proposed taskfile
* @id: data buffer
*
* This custom read ID function is required due to the fact that the HW
* does not support DEVSLP.
*/
static unsigned int xgene_ahci_read_id(struct ata_device *dev,
struct ata_taskfile *tf, u16 *id)
{
u32 err_mask;
err_mask = ata_do_dev_read_id(dev, tf, id);
if (err_mask)
return err_mask;
/*
* Mask reserved area. Word78 spec of Link Power Management
* bit15-8: reserved
* bit7: NCQ autosence
* bit6: Software settings preservation supported
* bit5: reserved
* bit4: In-order sata delivery supported
* bit3: DIPM requests supported
* bit2: DMA Setup FIS Auto-Activate optimization supported
* bit1: DMA Setup FIX non-Zero buffer offsets supported
* bit0: Reserved
*
* Clear reserved bit 8 (DEVSLP bit) as we don't support DEVSLP
*/
id[ATA_ID_FEATURE_SUPP] &= cpu_to_le16(~(1 << 8));
return 0;
}
static void xgene_ahci_set_phy_cfg(struct xgene_ahci_context *ctx, int channel)
{
void __iomem *mmio = ctx->hpriv->mmio;
u32 val;
dev_dbg(ctx->dev, "port configure mmio 0x%p channel %d\n",
mmio, channel);
val = readl(mmio + PORTCFG);
val = PORTADDR_SET(val, channel == 0 ? 2 : 3);
writel(val, mmio + PORTCFG);
readl(mmio + PORTCFG); /* Force a barrier */
/* Disable fix rate */
writel(0x0001fffe, mmio + PORTPHY1CFG);
readl(mmio + PORTPHY1CFG); /* Force a barrier */
writel(0x28183219, mmio + PORTPHY2CFG);
readl(mmio + PORTPHY2CFG); /* Force a barrier */
writel(0x13081008, mmio + PORTPHY3CFG);
readl(mmio + PORTPHY3CFG); /* Force a barrier */
writel(0x00480815, mmio + PORTPHY4CFG);
readl(mmio + PORTPHY4CFG); /* Force a barrier */
/* Set window negotiation */
val = readl(mmio + PORTPHY5CFG);
val = PORTPHY5CFG_RTCHG_SET(val, 0x300);
writel(val, mmio + PORTPHY5CFG);
readl(mmio + PORTPHY5CFG); /* Force a barrier */
val = readl(mmio + PORTAXICFG);
val = PORTAXICFG_EN_CONTEXT_SET(val, 0x1); /* Enable context mgmt */
val = PORTAXICFG_OUTTRANS_SET(val, 0xe); /* Set outstanding */
writel(val, mmio + PORTAXICFG);
readl(mmio + PORTAXICFG); /* Force a barrier */
/* Set the watermark threshold of the receive FIFO */
val = readl(mmio + PORTRANSCFG);
val = PORTRANSCFG_RXWM_SET(val, 0x30);
writel(val, mmio + PORTRANSCFG);
}
/**
* xgene_ahci_do_hardreset - Issue the actual COMRESET
* @link: link to reset
* @deadline: deadline jiffies for the operation
* @online: Return value to indicate if device online
*
* Due to the limitation of the hardware PHY, a difference set of setting is
* required for each supported disk speed - Gen3 (6.0Gbps), Gen2 (3.0Gbps),
* and Gen1 (1.5Gbps). Otherwise during long IO stress test, the PHY will
* report disparity error and etc. In addition, during COMRESET, there can
* be error reported in the register PORT_SCR_ERR. For SERR_DISPARITY and
* SERR_10B_8B_ERR, the PHY receiver line must be reseted. Also during long
* reboot cycle regression, sometimes the PHY reports link down even if the
* device is present because of speed negotiation failure. so need to retry
* the COMRESET to get the link up. The following algorithm is followed to
* proper configure the hardware PHY during COMRESET:
*
* Alg Part 1:
* 1. Start the PHY at Gen3 speed (default setting)
* 2. Issue the COMRESET
* 3. If no link, go to Alg Part 3
* 4. If link up, determine if the negotiated speed matches the PHY
* configured speed
* 5. If they matched, go to Alg Part 2
* 6. If they do not matched and first time, configure the PHY for the linked
* up disk speed and repeat step 2
* 7. Go to Alg Part 2
*
* Alg Part 2:
* 1. On link up, if there are any SERR_DISPARITY and SERR_10B_8B_ERR error
* reported in the register PORT_SCR_ERR, then reset the PHY receiver line
* 2. Go to Alg Part 4
*
* Alg Part 3:
* 1. Check the PORT_SCR_STAT to see whether device presence detected but PHY
* communication establishment failed and maximum link down attempts are
* less than Max attempts 3 then goto Alg Part 1.
* 2. Go to Alg Part 4.
*
* Alg Part 4:
* 1. Clear any pending from register PORT_SCR_ERR.
*
* NOTE: For the initial version, we will NOT support Gen1/Gen2. In addition
* and until the underlying PHY supports an method to reset the receiver
* line, on detection of SERR_DISPARITY or SERR_10B_8B_ERR errors,
* an warning message will be printed.
*/
static int xgene_ahci_do_hardreset(struct ata_link *link,
unsigned long deadline, bool *online)
{
const unsigned long *timing = sata_ehc_deb_timing(&link->eh_context);
struct ata_port *ap = link->ap;
struct ahci_host_priv *hpriv = ap->host->private_data;
struct xgene_ahci_context *ctx = hpriv->plat_data;
struct ahci_port_priv *pp = ap->private_data;
u8 *d2h_fis = pp->rx_fis + RX_FIS_D2H_REG;
void __iomem *port_mmio = ahci_port_base(ap);
struct ata_taskfile tf;
int link_down_retry = 0;
int rc;
u32 val, sstatus;
do {
/* clear D2H reception area to properly wait for D2H FIS */
ata_tf_init(link->device, &tf);
tf.command = ATA_BUSY;
ata_tf_to_fis(&tf, 0, 0, d2h_fis);
rc = sata_link_hardreset(link, timing, deadline, online,
ahci_check_ready);
if (*online) {
val = readl(port_mmio + PORT_SCR_ERR);
if (val & (SERR_DISPARITY | SERR_10B_8B_ERR))
dev_warn(ctx->dev, "link has error\n");
break;
}
sata_scr_read(link, SCR_STATUS, &sstatus);
} while (link_down_retry++ < MAX_LINK_DOWN_RETRY &&
(sstatus & 0xff) == 0x1);
/* clear all errors if any pending */
val = readl(port_mmio + PORT_SCR_ERR);
writel(val, port_mmio + PORT_SCR_ERR);
return rc;
}
static int xgene_ahci_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
struct ahci_host_priv *hpriv = ap->host->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
bool online;
int rc;
u32 portcmd_saved;
u32 portclb_saved;
u32 portclbhi_saved;
u32 portrxfis_saved;
u32 portrxfishi_saved;
/* As hardreset resets these CSR, save it to restore later */
portcmd_saved = readl(port_mmio + PORT_CMD);
portclb_saved = readl(port_mmio + PORT_LST_ADDR);
portclbhi_saved = readl(port_mmio + PORT_LST_ADDR_HI);
portrxfis_saved = readl(port_mmio + PORT_FIS_ADDR);
portrxfishi_saved = readl(port_mmio + PORT_FIS_ADDR_HI);
ahci_stop_engine(ap);
rc = xgene_ahci_do_hardreset(link, deadline, &online);
/* As controller hardreset clears them, restore them */
writel(portcmd_saved, port_mmio + PORT_CMD);
writel(portclb_saved, port_mmio + PORT_LST_ADDR);
writel(portclbhi_saved, port_mmio + PORT_LST_ADDR_HI);
writel(portrxfis_saved, port_mmio + PORT_FIS_ADDR);
writel(portrxfishi_saved, port_mmio + PORT_FIS_ADDR_HI);
hpriv->start_engine(ap);
if (online)
*class = ahci_dev_classify(ap);
return rc;
}
static void xgene_ahci_host_stop(struct ata_host *host)
{
struct ahci_host_priv *hpriv = host->private_data;
ahci_platform_disable_resources(hpriv);
}
/**
* xgene_ahci_pmp_softreset - Issue the softreset to the drives connected
* to Port Multiplier.
* @link: link to reset
* @class: Return value to indicate class of device
* @deadline: deadline jiffies for the operation
*
* Due to H/W errata, the controller is unable to save the PMP
* field fetched from command header before sending the H2D FIS.
* When the device returns the PMP port field in the D2H FIS, there is
* a mismatch and results in command completion failure. The workaround
* is to write the pmp value to PxFBS.DEV field before issuing any command
* to PMP.
*/
static int xgene_ahci_pmp_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
int pmp = sata_srst_pmp(link);
struct ata_port *ap = link->ap;
u32 rc;
void *port_mmio = ahci_port_base(ap);
u32 port_fbs;
/*
* Set PxFBS.DEV field with pmp
* value.
*/
port_fbs = readl(port_mmio + PORT_FBS);
port_fbs &= ~PORT_FBS_DEV_MASK;
port_fbs |= pmp << PORT_FBS_DEV_OFFSET;
writel(port_fbs, port_mmio + PORT_FBS);
rc = ahci_do_softreset(link, class, pmp, deadline, ahci_check_ready);
return rc;
}
/**
* xgene_ahci_softreset - Issue the softreset to the drive.
* @link: link to reset
* @class: Return value to indicate class of device
* @deadline: deadline jiffies for the operation
*
* Due to H/W errata, the controller is unable to save the PMP
* field fetched from command header before sending the H2D FIS.
* When the device returns the PMP port field in the D2H FIS, there is
* a mismatch and results in command completion failure. The workaround
* is to write the pmp value to PxFBS.DEV field before issuing any command
* to PMP. Here is the algorithm to detect PMP :
*
* 1. Save the PxFBS value
* 2. Program PxFBS.DEV with pmp value send by framework. Framework sends
* 0xF for both PMP/NON-PMP initially
* 3. Issue softreset
* 4. If signature class is PMP goto 6
* 5. restore the original PxFBS and goto 3
* 6. return
*/
static int xgene_ahci_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
int pmp = sata_srst_pmp(link);
struct ata_port *ap = link->ap;
struct ahci_host_priv *hpriv = ap->host->private_data;
struct xgene_ahci_context *ctx = hpriv->plat_data;
void *port_mmio = ahci_port_base(ap);
u32 port_fbs;
u32 port_fbs_save;
u32 retry = 1;
u32 rc;
port_fbs_save = readl(port_mmio + PORT_FBS);
/*
* Set PxFBS.DEV field with pmp
* value.
*/
port_fbs = readl(port_mmio + PORT_FBS);
port_fbs &= ~PORT_FBS_DEV_MASK;
port_fbs |= pmp << PORT_FBS_DEV_OFFSET;
writel(port_fbs, port_mmio + PORT_FBS);
softreset_retry:
rc = ahci_do_softreset(link, class, pmp,
deadline, ahci_check_ready);
ctx->class[ap->port_no] = *class;
if (*class != ATA_DEV_PMP) {
/*
* Retry for normal drives without
* setting PxFBS.DEV field with pmp value.
*/
if (retry--) {
writel(port_fbs_save, port_mmio + PORT_FBS);
goto softreset_retry;
}
}
return rc;
}
static struct ata_port_operations xgene_ahci_v1_ops = {
.inherits = &ahci_ops,
.host_stop = xgene_ahci_host_stop,
.hardreset = xgene_ahci_hardreset,
.read_id = xgene_ahci_read_id,
.qc_issue = xgene_ahci_qc_issue,
.softreset = xgene_ahci_softreset,
.pmp_softreset = xgene_ahci_pmp_softreset
};
static const struct ata_port_info xgene_ahci_v1_port_info = {
.flags = AHCI_FLAG_COMMON | ATA_FLAG_PMP,
.pio_mask = ATA_PIO4,
.udma_mask = ATA_UDMA6,
.port_ops = &xgene_ahci_v1_ops,
};
static struct ata_port_operations xgene_ahci_v2_ops = {
.inherits = &ahci_ops,
.host_stop = xgene_ahci_host_stop,
.hardreset = xgene_ahci_hardreset,
.read_id = xgene_ahci_read_id,
};
static const struct ata_port_info xgene_ahci_v2_port_info = {
.flags = AHCI_FLAG_COMMON | ATA_FLAG_PMP,
.pio_mask = ATA_PIO4,
.udma_mask = ATA_UDMA6,
.port_ops = &xgene_ahci_v2_ops,
};
static int xgene_ahci_hw_init(struct ahci_host_priv *hpriv)
{
struct xgene_ahci_context *ctx = hpriv->plat_data;
int i;
int rc;
u32 val;
/* Remove IP RAM out of shutdown */
rc = xgene_ahci_init_memram(ctx);
if (rc)
return rc;
for (i = 0; i < MAX_AHCI_CHN_PERCTR; i++)
xgene_ahci_set_phy_cfg(ctx, i);
/* AXI disable Mask */
writel(0xffffffff, hpriv->mmio + HOST_IRQ_STAT);
readl(hpriv->mmio + HOST_IRQ_STAT); /* Force a barrier */
writel(0, ctx->csr_core + INTSTATUSMASK);
val = readl(ctx->csr_core + INTSTATUSMASK); /* Force a barrier */
dev_dbg(ctx->dev, "top level interrupt mask 0x%X value 0x%08X\n",
INTSTATUSMASK, val);
writel(0x0, ctx->csr_core + ERRINTSTATUSMASK);
readl(ctx->csr_core + ERRINTSTATUSMASK); /* Force a barrier */
writel(0x0, ctx->csr_axi + INT_SLV_TMOMASK);
readl(ctx->csr_axi + INT_SLV_TMOMASK);
/* Enable AXI Interrupt */
writel(0xffffffff, ctx->csr_core + SLVRDERRATTRIBUTES);
writel(0xffffffff, ctx->csr_core + SLVWRERRATTRIBUTES);
writel(0xffffffff, ctx->csr_core + MSTRDERRATTRIBUTES);
writel(0xffffffff, ctx->csr_core + MSTWRERRATTRIBUTES);
/* Enable coherency */
val = readl(ctx->csr_core + BUSCTLREG);
val &= ~0x00000002; /* Enable write coherency */
val &= ~0x00000001; /* Enable read coherency */
writel(val, ctx->csr_core + BUSCTLREG);
val = readl(ctx->csr_core + IOFMSTRWAUX);
val |= (1 << 3); /* Enable read coherency */
val |= (1 << 9); /* Enable write coherency */
writel(val, ctx->csr_core + IOFMSTRWAUX);
val = readl(ctx->csr_core + IOFMSTRWAUX);
dev_dbg(ctx->dev, "coherency 0x%X value 0x%08X\n",
IOFMSTRWAUX, val);
return rc;
}
static int xgene_ahci_mux_select(struct xgene_ahci_context *ctx)
{
u32 val;
/* Check for optional MUX resource */
if (!ctx->csr_mux)
return 0;
val = readl(ctx->csr_mux + SATA_ENET_CONFIG_REG);
val &= ~CFG_SATA_ENET_SELECT_MASK;
writel(val, ctx->csr_mux + SATA_ENET_CONFIG_REG);
val = readl(ctx->csr_mux + SATA_ENET_CONFIG_REG);
return val & CFG_SATA_ENET_SELECT_MASK ? -1 : 0;
}
static struct scsi_host_template ahci_platform_sht = {
AHCI_SHT(DRV_NAME),
};
#ifdef CONFIG_ACPI
static const struct acpi_device_id xgene_ahci_acpi_match[] = {
{ "APMC0D0D", XGENE_AHCI_V1},
{ "APMC0D32", XGENE_AHCI_V2},
{},
};
MODULE_DEVICE_TABLE(acpi, xgene_ahci_acpi_match);
#endif
static const struct of_device_id xgene_ahci_of_match[] = {
{.compatible = "apm,xgene-ahci", .data = (void *) XGENE_AHCI_V1},
{.compatible = "apm,xgene-ahci-v2", .data = (void *) XGENE_AHCI_V2},
{},
};
MODULE_DEVICE_TABLE(of, xgene_ahci_of_match);
static int xgene_ahci_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct ahci_host_priv *hpriv;
struct xgene_ahci_context *ctx;
struct resource *res;
const struct of_device_id *of_devid;
enum xgene_ahci_version version = XGENE_AHCI_V1;
const struct ata_port_info *ppi[] = { &xgene_ahci_v1_port_info,
&xgene_ahci_v2_port_info };
int rc;
hpriv = ahci_platform_get_resources(pdev);
if (IS_ERR(hpriv))
return PTR_ERR(hpriv);
ctx = devm_kzalloc(dev, sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
hpriv->plat_data = ctx;
ctx->hpriv = hpriv;
ctx->dev = dev;
/* Retrieve the IP core resource */
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
ctx->csr_core = devm_ioremap_resource(dev, res);
if (IS_ERR(ctx->csr_core))
return PTR_ERR(ctx->csr_core);
/* Retrieve the IP diagnostic resource */
res = platform_get_resource(pdev, IORESOURCE_MEM, 2);
ctx->csr_diag = devm_ioremap_resource(dev, res);
if (IS_ERR(ctx->csr_diag))
return PTR_ERR(ctx->csr_diag);
/* Retrieve the IP AXI resource */
res = platform_get_resource(pdev, IORESOURCE_MEM, 3);
ctx->csr_axi = devm_ioremap_resource(dev, res);
if (IS_ERR(ctx->csr_axi))
return PTR_ERR(ctx->csr_axi);
/* Retrieve the optional IP mux resource */
res = platform_get_resource(pdev, IORESOURCE_MEM, 4);
if (res) {
void __iomem *csr = devm_ioremap_resource(dev, res);
if (IS_ERR(csr))
return PTR_ERR(csr);
ctx->csr_mux = csr;
}
of_devid = of_match_device(xgene_ahci_of_match, dev);
if (of_devid) {
if (of_devid->data)
version = (enum xgene_ahci_version) of_devid->data;
}
#ifdef CONFIG_ACPI
else {
const struct acpi_device_id *acpi_id;
struct acpi_device_info *info;
acpi_status status;
acpi_id = acpi_match_device(xgene_ahci_acpi_match, &pdev->dev);
if (!acpi_id) {
dev_warn(&pdev->dev, "No node entry in ACPI table. Assume version1\n");
version = XGENE_AHCI_V1;
} else if (acpi_id->driver_data) {
version = (enum xgene_ahci_version) acpi_id->driver_data;
status = acpi_get_object_info(ACPI_HANDLE(&pdev->dev), &info);
if (ACPI_FAILURE(status)) {
dev_warn(&pdev->dev, "%s: Error reading device info. Assume version1\n",
__func__);
version = XGENE_AHCI_V1;
}
if (info->valid & ACPI_VALID_CID)
version = XGENE_AHCI_V2;
}
}
#endif
dev_dbg(dev, "VAddr 0x%p Mmio VAddr 0x%p\n", ctx->csr_core,
hpriv->mmio);
/* Select ATA */
if ((rc = xgene_ahci_mux_select(ctx))) {
dev_err(dev, "SATA mux selection failed error %d\n", rc);
return -ENODEV;
}
if (xgene_ahci_is_memram_inited(ctx)) {
dev_info(dev, "skip clock and PHY initialization\n");
goto skip_clk_phy;
}
/* Due to errata, HW requires full toggle transition */
rc = ahci_platform_enable_clks(hpriv);
if (rc)
goto disable_resources;
ahci_platform_disable_clks(hpriv);
rc = ahci_platform_enable_resources(hpriv);
if (rc)
goto disable_resources;
/* Configure the host controller */
xgene_ahci_hw_init(hpriv);
skip_clk_phy:
switch (version) {
case XGENE_AHCI_V1:
hpriv->flags = AHCI_HFLAG_NO_NCQ;
break;
case XGENE_AHCI_V2:
hpriv->flags |= AHCI_HFLAG_YES_FBS | AHCI_HFLAG_EDGE_IRQ;
break;
default:
break;
}
rc = ahci_platform_init_host(pdev, hpriv, ppi[version - 1],
&ahci_platform_sht);
if (rc)
goto disable_resources;
dev_dbg(dev, "X-Gene SATA host controller initialized\n");
return 0;
disable_resources:
ahci_platform_disable_resources(hpriv);
return rc;
}
static struct platform_driver xgene_ahci_driver = {
.probe = xgene_ahci_probe,
.remove = ata_platform_remove_one,
.driver = {
.name = DRV_NAME,
.of_match_table = xgene_ahci_of_match,
.acpi_match_table = ACPI_PTR(xgene_ahci_acpi_match),
},
};
module_platform_driver(xgene_ahci_driver);
MODULE_DESCRIPTION("APM X-Gene AHCI SATA driver");
MODULE_AUTHOR("Loc Ho <lho@apm.com>");
MODULE_LICENSE("GPL");
MODULE_VERSION("0.4");
| gpl-2.0 |
project-voodoo-vibrant/linux_sgh-t959v | fs/ocfs2/namei.c | 520 | 56123 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* namei.c
*
* Create and rename file, directory, symlinks
*
* Copyright (C) 2002, 2004 Oracle. All rights reserved.
*
* Portions of this code from linux/fs/ext3/dir.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/dir.c
*
* Copyright (C) 1991, 1992 Linux Torvalds
*
* 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; either
* version 2 of the License, or (at your option) any later version.
*
* 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 021110-1307, USA.
*/
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/highmem.h>
#include <linux/quotaops.h>
#define MLOG_MASK_PREFIX ML_NAMEI
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "dcache.h"
#include "dir.h"
#include "dlmglue.h"
#include "extent_map.h"
#include "file.h"
#include "inode.h"
#include "journal.h"
#include "namei.h"
#include "suballoc.h"
#include "super.h"
#include "symlink.h"
#include "sysfile.h"
#include "uptodate.h"
#include "xattr.h"
#include "acl.h"
#include "buffer_head_io.h"
static int ocfs2_mknod_locked(struct ocfs2_super *osb,
struct inode *dir,
struct inode *inode,
dev_t dev,
struct buffer_head **new_fe_bh,
struct buffer_head *parent_fe_bh,
handle_t *handle,
struct ocfs2_alloc_context *inode_ac);
static int ocfs2_prepare_orphan_dir(struct ocfs2_super *osb,
struct inode **ret_orphan_dir,
u64 blkno,
char *name,
struct ocfs2_dir_lookup_result *lookup);
static int ocfs2_orphan_add(struct ocfs2_super *osb,
handle_t *handle,
struct inode *inode,
struct ocfs2_dinode *fe,
char *name,
struct ocfs2_dir_lookup_result *lookup,
struct inode *orphan_dir_inode);
static int ocfs2_create_symlink_data(struct ocfs2_super *osb,
handle_t *handle,
struct inode *inode,
const char *symname);
/* An orphan dir name is an 8 byte value, printed as a hex string */
#define OCFS2_ORPHAN_NAMELEN ((int)(2 * sizeof(u64)))
static struct dentry *ocfs2_lookup(struct inode *dir, struct dentry *dentry,
struct nameidata *nd)
{
int status;
u64 blkno;
struct inode *inode = NULL;
struct dentry *ret;
struct ocfs2_inode_info *oi;
mlog_entry("(0x%p, 0x%p, '%.*s')\n", dir, dentry,
dentry->d_name.len, dentry->d_name.name);
if (dentry->d_name.len > OCFS2_MAX_FILENAME_LEN) {
ret = ERR_PTR(-ENAMETOOLONG);
goto bail;
}
mlog(0, "find name %.*s in directory %llu\n", dentry->d_name.len,
dentry->d_name.name, (unsigned long long)OCFS2_I(dir)->ip_blkno);
status = ocfs2_inode_lock_nested(dir, NULL, 0, OI_LS_PARENT);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
ret = ERR_PTR(status);
goto bail;
}
status = ocfs2_lookup_ino_from_name(dir, dentry->d_name.name,
dentry->d_name.len, &blkno);
if (status < 0)
goto bail_add;
inode = ocfs2_iget(OCFS2_SB(dir->i_sb), blkno, 0, 0);
if (IS_ERR(inode)) {
ret = ERR_PTR(-EACCES);
goto bail_unlock;
}
oi = OCFS2_I(inode);
/* Clear any orphaned state... If we were able to look up the
* inode from a directory, it certainly can't be orphaned. We
* might have the bad state from a node which intended to
* orphan this inode but crashed before it could commit the
* unlink. */
spin_lock(&oi->ip_lock);
oi->ip_flags &= ~OCFS2_INODE_MAYBE_ORPHANED;
spin_unlock(&oi->ip_lock);
bail_add:
dentry->d_op = &ocfs2_dentry_ops;
ret = d_splice_alias(inode, dentry);
if (inode) {
/*
* If d_splice_alias() finds a DCACHE_DISCONNECTED
* dentry, it will d_move() it on top of ourse. The
* return value will indicate this however, so in
* those cases, we switch them around for the locking
* code.
*
* NOTE: This dentry already has ->d_op set from
* ocfs2_get_parent() and ocfs2_get_dentry()
*/
if (ret)
dentry = ret;
status = ocfs2_dentry_attach_lock(dentry, inode,
OCFS2_I(dir)->ip_blkno);
if (status) {
mlog_errno(status);
ret = ERR_PTR(status);
goto bail_unlock;
}
}
bail_unlock:
/* Don't drop the cluster lock until *after* the d_add --
* unlink on another node will message us to remove that
* dentry under this lock so otherwise we can race this with
* the downconvert thread and have a stale dentry. */
ocfs2_inode_unlock(dir, 0);
bail:
mlog_exit_ptr(ret);
return ret;
}
static struct inode *ocfs2_get_init_inode(struct inode *dir, int mode)
{
struct inode *inode;
inode = new_inode(dir->i_sb);
if (!inode) {
mlog(ML_ERROR, "new_inode failed!\n");
return NULL;
}
/* populate as many fields early on as possible - many of
* these are used by the support functions here and in
* callers. */
if (S_ISDIR(mode))
inode->i_nlink = 2;
else
inode->i_nlink = 1;
inode->i_uid = current_fsuid();
if (dir->i_mode & S_ISGID) {
inode->i_gid = dir->i_gid;
if (S_ISDIR(mode))
mode |= S_ISGID;
} else
inode->i_gid = current_fsgid();
inode->i_mode = mode;
vfs_dq_init(inode);
return inode;
}
static int ocfs2_mknod(struct inode *dir,
struct dentry *dentry,
int mode,
dev_t dev)
{
int status = 0;
struct buffer_head *parent_fe_bh = NULL;
handle_t *handle = NULL;
struct ocfs2_super *osb;
struct ocfs2_dinode *dirfe;
struct buffer_head *new_fe_bh = NULL;
struct inode *inode = NULL;
struct ocfs2_alloc_context *inode_ac = NULL;
struct ocfs2_alloc_context *data_ac = NULL;
struct ocfs2_alloc_context *meta_ac = NULL;
int want_clusters = 0;
int want_meta = 0;
int xattr_credits = 0;
struct ocfs2_security_xattr_info si = {
.enable = 1,
};
int did_quota_inode = 0;
struct ocfs2_dir_lookup_result lookup = { NULL, };
mlog_entry("(0x%p, 0x%p, %d, %lu, '%.*s')\n", dir, dentry, mode,
(unsigned long)dev, dentry->d_name.len,
dentry->d_name.name);
/* get our super block */
osb = OCFS2_SB(dir->i_sb);
status = ocfs2_inode_lock(dir, &parent_fe_bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
return status;
}
if (S_ISDIR(mode) && (dir->i_nlink >= ocfs2_link_max(osb))) {
status = -EMLINK;
goto leave;
}
dirfe = (struct ocfs2_dinode *) parent_fe_bh->b_data;
if (!ocfs2_read_links_count(dirfe)) {
/* can't make a file in a deleted directory. */
status = -ENOENT;
goto leave;
}
status = ocfs2_check_dir_for_entry(dir, dentry->d_name.name,
dentry->d_name.len);
if (status)
goto leave;
/* get a spot inside the dir. */
status = ocfs2_prepare_dir_for_insert(osb, dir, parent_fe_bh,
dentry->d_name.name,
dentry->d_name.len, &lookup);
if (status < 0) {
mlog_errno(status);
goto leave;
}
/* reserve an inode spot */
status = ocfs2_reserve_new_inode(osb, &inode_ac);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
goto leave;
}
inode = ocfs2_get_init_inode(dir, mode);
if (!inode) {
status = -ENOMEM;
mlog_errno(status);
goto leave;
}
/* get security xattr */
status = ocfs2_init_security_get(inode, dir, &si);
if (status) {
if (status == -EOPNOTSUPP)
si.enable = 0;
else {
mlog_errno(status);
goto leave;
}
}
/* calculate meta data/clusters for setting security and acl xattr */
status = ocfs2_calc_xattr_init(dir, parent_fe_bh, mode,
&si, &want_clusters,
&xattr_credits, &want_meta);
if (status < 0) {
mlog_errno(status);
goto leave;
}
/* Reserve a cluster if creating an extent based directory. */
if (S_ISDIR(mode) && !ocfs2_supports_inline_data(osb)) {
want_clusters += 1;
/* Dir indexing requires extra space as well */
if (ocfs2_supports_indexed_dirs(osb))
want_meta++;
}
status = ocfs2_reserve_new_metadata_blocks(osb, want_meta, &meta_ac);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
goto leave;
}
status = ocfs2_reserve_clusters(osb, want_clusters, &data_ac);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
goto leave;
}
handle = ocfs2_start_trans(osb, ocfs2_mknod_credits(osb->sb,
S_ISDIR(mode),
xattr_credits));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
handle = NULL;
mlog_errno(status);
goto leave;
}
/* We don't use standard VFS wrapper because we don't want vfs_dq_init
* to be called. */
if (sb_any_quota_active(osb->sb) &&
osb->sb->dq_op->alloc_inode(inode, 1) == NO_QUOTA) {
status = -EDQUOT;
goto leave;
}
did_quota_inode = 1;
mlog_entry("(0x%p, 0x%p, %d, %lu, '%.*s')\n", dir, dentry,
inode->i_mode, (unsigned long)dev, dentry->d_name.len,
dentry->d_name.name);
/* do the real work now. */
status = ocfs2_mknod_locked(osb, dir, inode, dev,
&new_fe_bh, parent_fe_bh, handle,
inode_ac);
if (status < 0) {
mlog_errno(status);
goto leave;
}
if (S_ISDIR(mode)) {
status = ocfs2_fill_new_dir(osb, handle, dir, inode,
new_fe_bh, data_ac, meta_ac);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_journal_access_di(handle, INODE_CACHE(dir),
parent_fe_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto leave;
}
ocfs2_add_links_count(dirfe, 1);
status = ocfs2_journal_dirty(handle, parent_fe_bh);
if (status < 0) {
mlog_errno(status);
goto leave;
}
inc_nlink(dir);
}
status = ocfs2_init_acl(handle, inode, dir, new_fe_bh, parent_fe_bh,
meta_ac, data_ac);
if (status < 0) {
mlog_errno(status);
goto leave;
}
if (si.enable) {
status = ocfs2_init_security_set(handle, inode, new_fe_bh, &si,
meta_ac, data_ac);
if (status < 0) {
mlog_errno(status);
goto leave;
}
}
status = ocfs2_add_entry(handle, dentry, inode,
OCFS2_I(inode)->ip_blkno, parent_fe_bh,
&lookup);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_dentry_attach_lock(dentry, inode,
OCFS2_I(dir)->ip_blkno);
if (status) {
mlog_errno(status);
goto leave;
}
insert_inode_hash(inode);
dentry->d_op = &ocfs2_dentry_ops;
d_instantiate(dentry, inode);
status = 0;
leave:
if (status < 0 && did_quota_inode)
vfs_dq_free_inode(inode);
if (handle)
ocfs2_commit_trans(osb, handle);
ocfs2_inode_unlock(dir, 1);
if (status == -ENOSPC)
mlog(0, "Disk is full\n");
brelse(new_fe_bh);
brelse(parent_fe_bh);
kfree(si.name);
kfree(si.value);
ocfs2_free_dir_lookup_result(&lookup);
if ((status < 0) && inode) {
clear_nlink(inode);
iput(inode);
}
if (inode_ac)
ocfs2_free_alloc_context(inode_ac);
if (data_ac)
ocfs2_free_alloc_context(data_ac);
if (meta_ac)
ocfs2_free_alloc_context(meta_ac);
mlog_exit(status);
return status;
}
static int ocfs2_mknod_locked(struct ocfs2_super *osb,
struct inode *dir,
struct inode *inode,
dev_t dev,
struct buffer_head **new_fe_bh,
struct buffer_head *parent_fe_bh,
handle_t *handle,
struct ocfs2_alloc_context *inode_ac)
{
int status = 0;
struct ocfs2_dinode *fe = NULL;
struct ocfs2_extent_list *fel;
u64 fe_blkno = 0;
u16 suballoc_bit;
u16 feat;
*new_fe_bh = NULL;
status = ocfs2_claim_new_inode(osb, handle, dir, parent_fe_bh,
inode_ac, &suballoc_bit, &fe_blkno);
if (status < 0) {
mlog_errno(status);
goto leave;
}
/* populate as many fields early on as possible - many of
* these are used by the support functions here and in
* callers. */
inode->i_ino = ino_from_blkno(osb->sb, fe_blkno);
OCFS2_I(inode)->ip_blkno = fe_blkno;
spin_lock(&osb->osb_lock);
inode->i_generation = osb->s_next_generation++;
spin_unlock(&osb->osb_lock);
*new_fe_bh = sb_getblk(osb->sb, fe_blkno);
if (!*new_fe_bh) {
status = -EIO;
mlog_errno(status);
goto leave;
}
ocfs2_set_new_buffer_uptodate(INODE_CACHE(inode), *new_fe_bh);
status = ocfs2_journal_access_di(handle, INODE_CACHE(inode),
*new_fe_bh,
OCFS2_JOURNAL_ACCESS_CREATE);
if (status < 0) {
mlog_errno(status);
goto leave;
}
fe = (struct ocfs2_dinode *) (*new_fe_bh)->b_data;
memset(fe, 0, osb->sb->s_blocksize);
fe->i_generation = cpu_to_le32(inode->i_generation);
fe->i_fs_generation = cpu_to_le32(osb->fs_generation);
fe->i_blkno = cpu_to_le64(fe_blkno);
fe->i_suballoc_bit = cpu_to_le16(suballoc_bit);
fe->i_suballoc_slot = cpu_to_le16(inode_ac->ac_alloc_slot);
fe->i_uid = cpu_to_le32(inode->i_uid);
fe->i_gid = cpu_to_le32(inode->i_gid);
fe->i_mode = cpu_to_le16(inode->i_mode);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
fe->id1.dev1.i_rdev = cpu_to_le64(huge_encode_dev(dev));
ocfs2_set_links_count(fe, inode->i_nlink);
fe->i_last_eb_blk = 0;
strcpy(fe->i_signature, OCFS2_INODE_SIGNATURE);
le32_add_cpu(&fe->i_flags, OCFS2_VALID_FL);
fe->i_atime = fe->i_ctime = fe->i_mtime =
cpu_to_le64(CURRENT_TIME.tv_sec);
fe->i_mtime_nsec = fe->i_ctime_nsec = fe->i_atime_nsec =
cpu_to_le32(CURRENT_TIME.tv_nsec);
fe->i_dtime = 0;
/*
* If supported, directories start with inline data. If inline
* isn't supported, but indexing is, we start them as indexed.
*/
feat = le16_to_cpu(fe->i_dyn_features);
if (S_ISDIR(inode->i_mode) && ocfs2_supports_inline_data(osb)) {
fe->i_dyn_features = cpu_to_le16(feat | OCFS2_INLINE_DATA_FL);
fe->id2.i_data.id_count = cpu_to_le16(
ocfs2_max_inline_data_with_xattr(osb->sb, fe));
} else {
fel = &fe->id2.i_list;
fel->l_tree_depth = 0;
fel->l_next_free_rec = 0;
fel->l_count = cpu_to_le16(ocfs2_extent_recs_per_inode(osb->sb));
}
status = ocfs2_journal_dirty(handle, *new_fe_bh);
if (status < 0) {
mlog_errno(status);
goto leave;
}
ocfs2_populate_inode(inode, fe, 1);
ocfs2_ci_set_new(osb, INODE_CACHE(inode));
if (!ocfs2_mount_local(osb)) {
status = ocfs2_create_new_inode_locks(inode);
if (status < 0)
mlog_errno(status);
}
status = 0; /* error in ocfs2_create_new_inode_locks is not
* critical */
leave:
if (status < 0) {
if (*new_fe_bh) {
brelse(*new_fe_bh);
*new_fe_bh = NULL;
}
}
mlog_exit(status);
return status;
}
static int ocfs2_mkdir(struct inode *dir,
struct dentry *dentry,
int mode)
{
int ret;
mlog_entry("(0x%p, 0x%p, %d, '%.*s')\n", dir, dentry, mode,
dentry->d_name.len, dentry->d_name.name);
ret = ocfs2_mknod(dir, dentry, mode | S_IFDIR, 0);
mlog_exit(ret);
return ret;
}
static int ocfs2_create(struct inode *dir,
struct dentry *dentry,
int mode,
struct nameidata *nd)
{
int ret;
mlog_entry("(0x%p, 0x%p, %d, '%.*s')\n", dir, dentry, mode,
dentry->d_name.len, dentry->d_name.name);
ret = ocfs2_mknod(dir, dentry, mode | S_IFREG, 0);
mlog_exit(ret);
return ret;
}
static int ocfs2_link(struct dentry *old_dentry,
struct inode *dir,
struct dentry *dentry)
{
handle_t *handle;
struct inode *inode = old_dentry->d_inode;
int err;
struct buffer_head *fe_bh = NULL;
struct buffer_head *parent_fe_bh = NULL;
struct ocfs2_dinode *fe = NULL;
struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
struct ocfs2_dir_lookup_result lookup = { NULL, };
mlog_entry("(inode=%lu, old='%.*s' new='%.*s')\n", inode->i_ino,
old_dentry->d_name.len, old_dentry->d_name.name,
dentry->d_name.len, dentry->d_name.name);
if (S_ISDIR(inode->i_mode))
return -EPERM;
err = ocfs2_inode_lock_nested(dir, &parent_fe_bh, 1, OI_LS_PARENT);
if (err < 0) {
if (err != -ENOENT)
mlog_errno(err);
return err;
}
if (!dir->i_nlink) {
err = -ENOENT;
goto out;
}
err = ocfs2_check_dir_for_entry(dir, dentry->d_name.name,
dentry->d_name.len);
if (err)
goto out;
err = ocfs2_prepare_dir_for_insert(osb, dir, parent_fe_bh,
dentry->d_name.name,
dentry->d_name.len, &lookup);
if (err < 0) {
mlog_errno(err);
goto out;
}
err = ocfs2_inode_lock(inode, &fe_bh, 1);
if (err < 0) {
if (err != -ENOENT)
mlog_errno(err);
goto out;
}
fe = (struct ocfs2_dinode *) fe_bh->b_data;
if (ocfs2_read_links_count(fe) >= ocfs2_link_max(osb)) {
err = -EMLINK;
goto out_unlock_inode;
}
handle = ocfs2_start_trans(osb, ocfs2_link_credits(osb->sb));
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
handle = NULL;
mlog_errno(err);
goto out_unlock_inode;
}
err = ocfs2_journal_access_di(handle, INODE_CACHE(inode), fe_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (err < 0) {
mlog_errno(err);
goto out_commit;
}
inc_nlink(inode);
inode->i_ctime = CURRENT_TIME;
ocfs2_set_links_count(fe, inode->i_nlink);
fe->i_ctime = cpu_to_le64(inode->i_ctime.tv_sec);
fe->i_ctime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
err = ocfs2_journal_dirty(handle, fe_bh);
if (err < 0) {
ocfs2_add_links_count(fe, -1);
drop_nlink(inode);
mlog_errno(err);
goto out_commit;
}
err = ocfs2_add_entry(handle, dentry, inode,
OCFS2_I(inode)->ip_blkno,
parent_fe_bh, &lookup);
if (err) {
ocfs2_add_links_count(fe, -1);
drop_nlink(inode);
mlog_errno(err);
goto out_commit;
}
err = ocfs2_dentry_attach_lock(dentry, inode, OCFS2_I(dir)->ip_blkno);
if (err) {
mlog_errno(err);
goto out_commit;
}
atomic_inc(&inode->i_count);
dentry->d_op = &ocfs2_dentry_ops;
d_instantiate(dentry, inode);
out_commit:
ocfs2_commit_trans(osb, handle);
out_unlock_inode:
ocfs2_inode_unlock(inode, 1);
out:
ocfs2_inode_unlock(dir, 1);
brelse(fe_bh);
brelse(parent_fe_bh);
ocfs2_free_dir_lookup_result(&lookup);
mlog_exit(err);
return err;
}
/*
* Takes and drops an exclusive lock on the given dentry. This will
* force other nodes to drop it.
*/
static int ocfs2_remote_dentry_delete(struct dentry *dentry)
{
int ret;
ret = ocfs2_dentry_lock(dentry, 1);
if (ret)
mlog_errno(ret);
else
ocfs2_dentry_unlock(dentry, 1);
return ret;
}
static inline int inode_is_unlinkable(struct inode *inode)
{
if (S_ISDIR(inode->i_mode)) {
if (inode->i_nlink == 2)
return 1;
return 0;
}
if (inode->i_nlink == 1)
return 1;
return 0;
}
static int ocfs2_unlink(struct inode *dir,
struct dentry *dentry)
{
int status;
int child_locked = 0;
struct inode *inode = dentry->d_inode;
struct inode *orphan_dir = NULL;
struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
u64 blkno;
struct ocfs2_dinode *fe = NULL;
struct buffer_head *fe_bh = NULL;
struct buffer_head *parent_node_bh = NULL;
handle_t *handle = NULL;
char orphan_name[OCFS2_ORPHAN_NAMELEN + 1];
struct ocfs2_dir_lookup_result lookup = { NULL, };
struct ocfs2_dir_lookup_result orphan_insert = { NULL, };
mlog_entry("(0x%p, 0x%p, '%.*s')\n", dir, dentry,
dentry->d_name.len, dentry->d_name.name);
BUG_ON(dentry->d_parent->d_inode != dir);
mlog(0, "ino = %llu\n", (unsigned long long)OCFS2_I(inode)->ip_blkno);
if (inode == osb->root_inode) {
mlog(0, "Cannot delete the root directory\n");
return -EPERM;
}
status = ocfs2_inode_lock_nested(dir, &parent_node_bh, 1,
OI_LS_PARENT);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
return status;
}
status = ocfs2_find_files_on_disk(dentry->d_name.name,
dentry->d_name.len, &blkno, dir,
&lookup);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
goto leave;
}
if (OCFS2_I(inode)->ip_blkno != blkno) {
status = -ENOENT;
mlog(0, "ip_blkno %llu != dirent blkno %llu ip_flags = %x\n",
(unsigned long long)OCFS2_I(inode)->ip_blkno,
(unsigned long long)blkno, OCFS2_I(inode)->ip_flags);
goto leave;
}
status = ocfs2_inode_lock(inode, &fe_bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
goto leave;
}
child_locked = 1;
if (S_ISDIR(inode->i_mode)) {
if (inode->i_nlink != 2 || !ocfs2_empty_dir(inode)) {
status = -ENOTEMPTY;
goto leave;
}
}
status = ocfs2_remote_dentry_delete(dentry);
if (status < 0) {
/* This remote delete should succeed under all normal
* circumstances. */
mlog_errno(status);
goto leave;
}
if (inode_is_unlinkable(inode)) {
status = ocfs2_prepare_orphan_dir(osb, &orphan_dir,
OCFS2_I(inode)->ip_blkno,
orphan_name, &orphan_insert);
if (status < 0) {
mlog_errno(status);
goto leave;
}
}
handle = ocfs2_start_trans(osb, ocfs2_unlink_credits(osb->sb));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
handle = NULL;
mlog_errno(status);
goto leave;
}
status = ocfs2_journal_access_di(handle, INODE_CACHE(inode), fe_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto leave;
}
fe = (struct ocfs2_dinode *) fe_bh->b_data;
if (inode_is_unlinkable(inode)) {
status = ocfs2_orphan_add(osb, handle, inode, fe, orphan_name,
&orphan_insert, orphan_dir);
if (status < 0) {
mlog_errno(status);
goto leave;
}
}
/* delete the name from the parent dir */
status = ocfs2_delete_entry(handle, dir, &lookup);
if (status < 0) {
mlog_errno(status);
goto leave;
}
if (S_ISDIR(inode->i_mode))
drop_nlink(inode);
drop_nlink(inode);
ocfs2_set_links_count(fe, inode->i_nlink);
status = ocfs2_journal_dirty(handle, fe_bh);
if (status < 0) {
mlog_errno(status);
goto leave;
}
dir->i_ctime = dir->i_mtime = CURRENT_TIME;
if (S_ISDIR(inode->i_mode))
drop_nlink(dir);
status = ocfs2_mark_inode_dirty(handle, dir, parent_node_bh);
if (status < 0) {
mlog_errno(status);
if (S_ISDIR(inode->i_mode))
inc_nlink(dir);
}
leave:
if (handle)
ocfs2_commit_trans(osb, handle);
if (child_locked)
ocfs2_inode_unlock(inode, 1);
ocfs2_inode_unlock(dir, 1);
if (orphan_dir) {
/* This was locked for us in ocfs2_prepare_orphan_dir() */
ocfs2_inode_unlock(orphan_dir, 1);
mutex_unlock(&orphan_dir->i_mutex);
iput(orphan_dir);
}
brelse(fe_bh);
brelse(parent_node_bh);
ocfs2_free_dir_lookup_result(&orphan_insert);
ocfs2_free_dir_lookup_result(&lookup);
mlog_exit(status);
return status;
}
/*
* The only place this should be used is rename!
* if they have the same id, then the 1st one is the only one locked.
*/
static int ocfs2_double_lock(struct ocfs2_super *osb,
struct buffer_head **bh1,
struct inode *inode1,
struct buffer_head **bh2,
struct inode *inode2)
{
int status;
struct ocfs2_inode_info *oi1 = OCFS2_I(inode1);
struct ocfs2_inode_info *oi2 = OCFS2_I(inode2);
struct buffer_head **tmpbh;
struct inode *tmpinode;
mlog_entry("(inode1 = %llu, inode2 = %llu)\n",
(unsigned long long)oi1->ip_blkno,
(unsigned long long)oi2->ip_blkno);
if (*bh1)
*bh1 = NULL;
if (*bh2)
*bh2 = NULL;
/* we always want to lock the one with the lower lockid first. */
if (oi1->ip_blkno != oi2->ip_blkno) {
if (oi1->ip_blkno < oi2->ip_blkno) {
/* switch id1 and id2 around */
mlog(0, "switching them around...\n");
tmpbh = bh2;
bh2 = bh1;
bh1 = tmpbh;
tmpinode = inode2;
inode2 = inode1;
inode1 = tmpinode;
}
/* lock id2 */
status = ocfs2_inode_lock_nested(inode2, bh2, 1,
OI_LS_RENAME1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
goto bail;
}
}
/* lock id1 */
status = ocfs2_inode_lock_nested(inode1, bh1, 1, OI_LS_RENAME2);
if (status < 0) {
/*
* An error return must mean that no cluster locks
* were held on function exit.
*/
if (oi1->ip_blkno != oi2->ip_blkno)
ocfs2_inode_unlock(inode2, 1);
if (status != -ENOENT)
mlog_errno(status);
}
bail:
mlog_exit(status);
return status;
}
static void ocfs2_double_unlock(struct inode *inode1, struct inode *inode2)
{
ocfs2_inode_unlock(inode1, 1);
if (inode1 != inode2)
ocfs2_inode_unlock(inode2, 1);
}
static int ocfs2_rename(struct inode *old_dir,
struct dentry *old_dentry,
struct inode *new_dir,
struct dentry *new_dentry)
{
int status = 0, rename_lock = 0, parents_locked = 0, target_exists = 0;
int old_child_locked = 0, new_child_locked = 0, update_dot_dot = 0;
struct inode *old_inode = old_dentry->d_inode;
struct inode *new_inode = new_dentry->d_inode;
struct inode *orphan_dir = NULL;
struct ocfs2_dinode *newfe = NULL;
char orphan_name[OCFS2_ORPHAN_NAMELEN + 1];
struct buffer_head *newfe_bh = NULL;
struct buffer_head *old_inode_bh = NULL;
struct ocfs2_super *osb = NULL;
u64 newfe_blkno, old_de_ino;
handle_t *handle = NULL;
struct buffer_head *old_dir_bh = NULL;
struct buffer_head *new_dir_bh = NULL;
nlink_t old_dir_nlink = old_dir->i_nlink;
struct ocfs2_dinode *old_di;
struct ocfs2_dir_lookup_result old_inode_dot_dot_res = { NULL, };
struct ocfs2_dir_lookup_result target_lookup_res = { NULL, };
struct ocfs2_dir_lookup_result old_entry_lookup = { NULL, };
struct ocfs2_dir_lookup_result orphan_insert = { NULL, };
struct ocfs2_dir_lookup_result target_insert = { NULL, };
/* At some point it might be nice to break this function up a
* bit. */
mlog_entry("(0x%p, 0x%p, 0x%p, 0x%p, from='%.*s' to='%.*s')\n",
old_dir, old_dentry, new_dir, new_dentry,
old_dentry->d_name.len, old_dentry->d_name.name,
new_dentry->d_name.len, new_dentry->d_name.name);
osb = OCFS2_SB(old_dir->i_sb);
if (new_inode) {
if (!igrab(new_inode))
BUG();
}
/* Assume a directory hierarchy thusly:
* a/b/c
* a/d
* a,b,c, and d are all directories.
*
* from cwd of 'a' on both nodes:
* node1: mv b/c d
* node2: mv d b/c
*
* And that's why, just like the VFS, we need a file system
* rename lock. */
if (old_dir != new_dir && S_ISDIR(old_inode->i_mode)) {
status = ocfs2_rename_lock(osb);
if (status < 0) {
mlog_errno(status);
goto bail;
}
rename_lock = 1;
}
/* if old and new are the same, this'll just do one lock. */
status = ocfs2_double_lock(osb, &old_dir_bh, old_dir,
&new_dir_bh, new_dir);
if (status < 0) {
mlog_errno(status);
goto bail;
}
parents_locked = 1;
/* make sure both dirs have bhs
* get an extra ref on old_dir_bh if old==new */
if (!new_dir_bh) {
if (old_dir_bh) {
new_dir_bh = old_dir_bh;
get_bh(new_dir_bh);
} else {
mlog(ML_ERROR, "no old_dir_bh!\n");
status = -EIO;
goto bail;
}
}
/*
* Aside from allowing a meta data update, the locking here
* also ensures that the downconvert thread on other nodes
* won't have to concurrently downconvert the inode and the
* dentry locks.
*/
status = ocfs2_inode_lock_nested(old_inode, &old_inode_bh, 1,
OI_LS_PARENT);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
goto bail;
}
old_child_locked = 1;
status = ocfs2_remote_dentry_delete(old_dentry);
if (status < 0) {
mlog_errno(status);
goto bail;
}
if (S_ISDIR(old_inode->i_mode)) {
u64 old_inode_parent;
update_dot_dot = 1;
status = ocfs2_find_files_on_disk("..", 2, &old_inode_parent,
old_inode,
&old_inode_dot_dot_res);
if (status) {
status = -EIO;
goto bail;
}
if (old_inode_parent != OCFS2_I(old_dir)->ip_blkno) {
status = -EIO;
goto bail;
}
if (!new_inode && new_dir != old_dir &&
new_dir->i_nlink >= ocfs2_link_max(osb)) {
status = -EMLINK;
goto bail;
}
}
status = ocfs2_lookup_ino_from_name(old_dir, old_dentry->d_name.name,
old_dentry->d_name.len,
&old_de_ino);
if (status) {
status = -ENOENT;
goto bail;
}
/*
* Check for inode number is _not_ due to possible IO errors.
* We might rmdir the source, keep it as pwd of some process
* and merrily kill the link to whatever was created under the
* same name. Goodbye sticky bit ;-<
*/
if (old_de_ino != OCFS2_I(old_inode)->ip_blkno) {
status = -ENOENT;
goto bail;
}
/* check if the target already exists (in which case we need
* to delete it */
status = ocfs2_find_files_on_disk(new_dentry->d_name.name,
new_dentry->d_name.len,
&newfe_blkno, new_dir,
&target_lookup_res);
/* The only error we allow here is -ENOENT because the new
* file not existing is perfectly valid. */
if ((status < 0) && (status != -ENOENT)) {
/* If we cannot find the file specified we should just */
/* return the error... */
mlog_errno(status);
goto bail;
}
if (status == 0)
target_exists = 1;
if (!target_exists && new_inode) {
/*
* Target was unlinked by another node while we were
* waiting to get to ocfs2_rename(). There isn't
* anything we can do here to help the situation, so
* bubble up the appropriate error.
*/
status = -ENOENT;
goto bail;
}
/* In case we need to overwrite an existing file, we blow it
* away first */
if (target_exists) {
/* VFS didn't think there existed an inode here, but
* someone else in the cluster must have raced our
* rename to create one. Today we error cleanly, in
* the future we should consider calling iget to build
* a new struct inode for this entry. */
if (!new_inode) {
status = -EACCES;
mlog(0, "We found an inode for name %.*s but VFS "
"didn't give us one.\n", new_dentry->d_name.len,
new_dentry->d_name.name);
goto bail;
}
if (OCFS2_I(new_inode)->ip_blkno != newfe_blkno) {
status = -EACCES;
mlog(0, "Inode %llu and dir %llu disagree. flags = %x\n",
(unsigned long long)OCFS2_I(new_inode)->ip_blkno,
(unsigned long long)newfe_blkno,
OCFS2_I(new_inode)->ip_flags);
goto bail;
}
status = ocfs2_inode_lock(new_inode, &newfe_bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
goto bail;
}
new_child_locked = 1;
status = ocfs2_remote_dentry_delete(new_dentry);
if (status < 0) {
mlog_errno(status);
goto bail;
}
newfe = (struct ocfs2_dinode *) newfe_bh->b_data;
mlog(0, "aha rename over existing... new_blkno=%llu "
"newfebh=%p bhblocknr=%llu\n",
(unsigned long long)newfe_blkno, newfe_bh, newfe_bh ?
(unsigned long long)newfe_bh->b_blocknr : 0ULL);
if (S_ISDIR(new_inode->i_mode) || (new_inode->i_nlink == 1)) {
status = ocfs2_prepare_orphan_dir(osb, &orphan_dir,
OCFS2_I(new_inode)->ip_blkno,
orphan_name, &orphan_insert);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
} else {
BUG_ON(new_dentry->d_parent->d_inode != new_dir);
status = ocfs2_check_dir_for_entry(new_dir,
new_dentry->d_name.name,
new_dentry->d_name.len);
if (status)
goto bail;
status = ocfs2_prepare_dir_for_insert(osb, new_dir, new_dir_bh,
new_dentry->d_name.name,
new_dentry->d_name.len,
&target_insert);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
handle = ocfs2_start_trans(osb, ocfs2_rename_credits(osb->sb));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
handle = NULL;
mlog_errno(status);
goto bail;
}
if (target_exists) {
if (S_ISDIR(new_inode->i_mode)) {
if (new_inode->i_nlink != 2 ||
!ocfs2_empty_dir(new_inode)) {
status = -ENOTEMPTY;
goto bail;
}
}
status = ocfs2_journal_access_di(handle, INODE_CACHE(new_inode),
newfe_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
if (S_ISDIR(new_inode->i_mode) ||
(ocfs2_read_links_count(newfe) == 1)) {
status = ocfs2_orphan_add(osb, handle, new_inode,
newfe, orphan_name,
&orphan_insert, orphan_dir);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
/* change the dirent to point to the correct inode */
status = ocfs2_update_entry(new_dir, handle, &target_lookup_res,
old_inode);
if (status < 0) {
mlog_errno(status);
goto bail;
}
new_dir->i_version++;
if (S_ISDIR(new_inode->i_mode))
ocfs2_set_links_count(newfe, 0);
else
ocfs2_add_links_count(newfe, -1);
status = ocfs2_journal_dirty(handle, newfe_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
} else {
/* if the name was not found in new_dir, add it now */
status = ocfs2_add_entry(handle, new_dentry, old_inode,
OCFS2_I(old_inode)->ip_blkno,
new_dir_bh, &target_insert);
}
old_inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(old_inode);
status = ocfs2_journal_access_di(handle, INODE_CACHE(old_inode),
old_inode_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status >= 0) {
old_di = (struct ocfs2_dinode *) old_inode_bh->b_data;
old_di->i_ctime = cpu_to_le64(old_inode->i_ctime.tv_sec);
old_di->i_ctime_nsec = cpu_to_le32(old_inode->i_ctime.tv_nsec);
status = ocfs2_journal_dirty(handle, old_inode_bh);
if (status < 0)
mlog_errno(status);
} else
mlog_errno(status);
/*
* Now that the name has been added to new_dir, remove the old name.
*
* We don't keep any directory entry context around until now
* because the insert might have changed the type of directory
* we're dealing with.
*/
status = ocfs2_find_entry(old_dentry->d_name.name,
old_dentry->d_name.len, old_dir,
&old_entry_lookup);
if (status)
goto bail;
status = ocfs2_delete_entry(handle, old_dir, &old_entry_lookup);
if (status < 0) {
mlog_errno(status);
goto bail;
}
if (new_inode) {
new_inode->i_nlink--;
new_inode->i_ctime = CURRENT_TIME;
}
old_dir->i_ctime = old_dir->i_mtime = CURRENT_TIME;
if (update_dot_dot) {
status = ocfs2_update_entry(old_inode, handle,
&old_inode_dot_dot_res, new_dir);
old_dir->i_nlink--;
if (new_inode) {
new_inode->i_nlink--;
} else {
inc_nlink(new_dir);
mark_inode_dirty(new_dir);
}
}
mark_inode_dirty(old_dir);
ocfs2_mark_inode_dirty(handle, old_dir, old_dir_bh);
if (new_inode) {
mark_inode_dirty(new_inode);
ocfs2_mark_inode_dirty(handle, new_inode, newfe_bh);
}
if (old_dir != new_dir) {
/* Keep the same times on both directories.*/
new_dir->i_ctime = new_dir->i_mtime = old_dir->i_ctime;
/*
* This will also pick up the i_nlink change from the
* block above.
*/
ocfs2_mark_inode_dirty(handle, new_dir, new_dir_bh);
}
if (old_dir_nlink != old_dir->i_nlink) {
if (!old_dir_bh) {
mlog(ML_ERROR, "need to change nlink for old dir "
"%llu from %d to %d but bh is NULL!\n",
(unsigned long long)OCFS2_I(old_dir)->ip_blkno,
(int)old_dir_nlink, old_dir->i_nlink);
} else {
struct ocfs2_dinode *fe;
status = ocfs2_journal_access_di(handle,
INODE_CACHE(old_dir),
old_dir_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
fe = (struct ocfs2_dinode *) old_dir_bh->b_data;
ocfs2_set_links_count(fe, old_dir->i_nlink);
status = ocfs2_journal_dirty(handle, old_dir_bh);
}
}
ocfs2_dentry_move(old_dentry, new_dentry, old_dir, new_dir);
status = 0;
bail:
if (rename_lock)
ocfs2_rename_unlock(osb);
if (handle)
ocfs2_commit_trans(osb, handle);
if (parents_locked)
ocfs2_double_unlock(old_dir, new_dir);
if (old_child_locked)
ocfs2_inode_unlock(old_inode, 1);
if (new_child_locked)
ocfs2_inode_unlock(new_inode, 1);
if (orphan_dir) {
/* This was locked for us in ocfs2_prepare_orphan_dir() */
ocfs2_inode_unlock(orphan_dir, 1);
mutex_unlock(&orphan_dir->i_mutex);
iput(orphan_dir);
}
if (new_inode)
sync_mapping_buffers(old_inode->i_mapping);
if (new_inode)
iput(new_inode);
ocfs2_free_dir_lookup_result(&target_lookup_res);
ocfs2_free_dir_lookup_result(&old_entry_lookup);
ocfs2_free_dir_lookup_result(&old_inode_dot_dot_res);
ocfs2_free_dir_lookup_result(&orphan_insert);
ocfs2_free_dir_lookup_result(&target_insert);
brelse(newfe_bh);
brelse(old_inode_bh);
brelse(old_dir_bh);
brelse(new_dir_bh);
mlog_exit(status);
return status;
}
/*
* we expect i_size = strlen(symname). Copy symname into the file
* data, including the null terminator.
*/
static int ocfs2_create_symlink_data(struct ocfs2_super *osb,
handle_t *handle,
struct inode *inode,
const char *symname)
{
struct buffer_head **bhs = NULL;
const char *c;
struct super_block *sb = osb->sb;
u64 p_blkno, p_blocks;
int virtual, blocks, status, i, bytes_left;
bytes_left = i_size_read(inode) + 1;
/* we can't trust i_blocks because we're actually going to
* write i_size + 1 bytes. */
blocks = (bytes_left + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
mlog_entry("i_blocks = %llu, i_size = %llu, blocks = %d\n",
(unsigned long long)inode->i_blocks,
i_size_read(inode), blocks);
/* Sanity check -- make sure we're going to fit. */
if (bytes_left >
ocfs2_clusters_to_bytes(sb, OCFS2_I(inode)->ip_clusters)) {
status = -EIO;
mlog_errno(status);
goto bail;
}
bhs = kcalloc(blocks, sizeof(struct buffer_head *), GFP_KERNEL);
if (!bhs) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
status = ocfs2_extent_map_get_blocks(inode, 0, &p_blkno, &p_blocks,
NULL);
if (status < 0) {
mlog_errno(status);
goto bail;
}
/* links can never be larger than one cluster so we know this
* is all going to be contiguous, but do a sanity check
* anyway. */
if ((p_blocks << sb->s_blocksize_bits) < bytes_left) {
status = -EIO;
mlog_errno(status);
goto bail;
}
virtual = 0;
while(bytes_left > 0) {
c = &symname[virtual * sb->s_blocksize];
bhs[virtual] = sb_getblk(sb, p_blkno);
if (!bhs[virtual]) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
ocfs2_set_new_buffer_uptodate(INODE_CACHE(inode),
bhs[virtual]);
status = ocfs2_journal_access(handle, INODE_CACHE(inode),
bhs[virtual],
OCFS2_JOURNAL_ACCESS_CREATE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
memset(bhs[virtual]->b_data, 0, sb->s_blocksize);
memcpy(bhs[virtual]->b_data, c,
(bytes_left > sb->s_blocksize) ? sb->s_blocksize :
bytes_left);
status = ocfs2_journal_dirty(handle, bhs[virtual]);
if (status < 0) {
mlog_errno(status);
goto bail;
}
virtual++;
p_blkno++;
bytes_left -= sb->s_blocksize;
}
status = 0;
bail:
if (bhs) {
for(i = 0; i < blocks; i++)
brelse(bhs[i]);
kfree(bhs);
}
mlog_exit(status);
return status;
}
static int ocfs2_symlink(struct inode *dir,
struct dentry *dentry,
const char *symname)
{
int status, l, credits;
u64 newsize;
struct ocfs2_super *osb = NULL;
struct inode *inode = NULL;
struct super_block *sb;
struct buffer_head *new_fe_bh = NULL;
struct buffer_head *parent_fe_bh = NULL;
struct ocfs2_dinode *fe = NULL;
struct ocfs2_dinode *dirfe;
handle_t *handle = NULL;
struct ocfs2_alloc_context *inode_ac = NULL;
struct ocfs2_alloc_context *data_ac = NULL;
struct ocfs2_alloc_context *xattr_ac = NULL;
int want_clusters = 0;
int xattr_credits = 0;
struct ocfs2_security_xattr_info si = {
.enable = 1,
};
int did_quota = 0, did_quota_inode = 0;
struct ocfs2_dir_lookup_result lookup = { NULL, };
mlog_entry("(0x%p, 0x%p, symname='%s' actual='%.*s')\n", dir,
dentry, symname, dentry->d_name.len, dentry->d_name.name);
sb = dir->i_sb;
osb = OCFS2_SB(sb);
l = strlen(symname) + 1;
credits = ocfs2_calc_symlink_credits(sb);
/* lock the parent directory */
status = ocfs2_inode_lock(dir, &parent_fe_bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
return status;
}
dirfe = (struct ocfs2_dinode *) parent_fe_bh->b_data;
if (!ocfs2_read_links_count(dirfe)) {
/* can't make a file in a deleted directory. */
status = -ENOENT;
goto bail;
}
status = ocfs2_check_dir_for_entry(dir, dentry->d_name.name,
dentry->d_name.len);
if (status)
goto bail;
status = ocfs2_prepare_dir_for_insert(osb, dir, parent_fe_bh,
dentry->d_name.name,
dentry->d_name.len, &lookup);
if (status < 0) {
mlog_errno(status);
goto bail;
}
status = ocfs2_reserve_new_inode(osb, &inode_ac);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
goto bail;
}
inode = ocfs2_get_init_inode(dir, S_IFLNK | S_IRWXUGO);
if (!inode) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
/* get security xattr */
status = ocfs2_init_security_get(inode, dir, &si);
if (status) {
if (status == -EOPNOTSUPP)
si.enable = 0;
else {
mlog_errno(status);
goto bail;
}
}
/* calculate meta data/clusters for setting security xattr */
if (si.enable) {
status = ocfs2_calc_security_init(dir, &si, &want_clusters,
&xattr_credits, &xattr_ac);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
/* don't reserve bitmap space for fast symlinks. */
if (l > ocfs2_fast_symlink_chars(sb))
want_clusters += 1;
status = ocfs2_reserve_clusters(osb, want_clusters, &data_ac);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
goto bail;
}
handle = ocfs2_start_trans(osb, credits + xattr_credits);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
handle = NULL;
mlog_errno(status);
goto bail;
}
/* We don't use standard VFS wrapper because we don't want vfs_dq_init
* to be called. */
if (sb_any_quota_active(osb->sb) &&
osb->sb->dq_op->alloc_inode(inode, 1) == NO_QUOTA) {
status = -EDQUOT;
goto bail;
}
did_quota_inode = 1;
mlog_entry("(0x%p, 0x%p, %d, '%.*s')\n", dir, dentry,
inode->i_mode, dentry->d_name.len,
dentry->d_name.name);
status = ocfs2_mknod_locked(osb, dir, inode,
0, &new_fe_bh, parent_fe_bh, handle,
inode_ac);
if (status < 0) {
mlog_errno(status);
goto bail;
}
fe = (struct ocfs2_dinode *) new_fe_bh->b_data;
inode->i_rdev = 0;
newsize = l - 1;
if (l > ocfs2_fast_symlink_chars(sb)) {
u32 offset = 0;
inode->i_op = &ocfs2_symlink_inode_operations;
if (vfs_dq_alloc_space_nodirty(inode,
ocfs2_clusters_to_bytes(osb->sb, 1))) {
status = -EDQUOT;
goto bail;
}
did_quota = 1;
status = ocfs2_add_inode_data(osb, inode, &offset, 1, 0,
new_fe_bh,
handle, data_ac, NULL,
NULL);
if (status < 0) {
if (status != -ENOSPC && status != -EINTR) {
mlog(ML_ERROR,
"Failed to extend file to %llu\n",
(unsigned long long)newsize);
mlog_errno(status);
status = -ENOSPC;
}
goto bail;
}
i_size_write(inode, newsize);
inode->i_blocks = ocfs2_inode_sector_count(inode);
} else {
inode->i_op = &ocfs2_fast_symlink_inode_operations;
memcpy((char *) fe->id2.i_symlink, symname, l);
i_size_write(inode, newsize);
inode->i_blocks = 0;
}
status = ocfs2_mark_inode_dirty(handle, inode, new_fe_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
if (!ocfs2_inode_is_fast_symlink(inode)) {
status = ocfs2_create_symlink_data(osb, handle, inode,
symname);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
if (si.enable) {
status = ocfs2_init_security_set(handle, inode, new_fe_bh, &si,
xattr_ac, data_ac);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
status = ocfs2_add_entry(handle, dentry, inode,
le64_to_cpu(fe->i_blkno), parent_fe_bh,
&lookup);
if (status < 0) {
mlog_errno(status);
goto bail;
}
status = ocfs2_dentry_attach_lock(dentry, inode, OCFS2_I(dir)->ip_blkno);
if (status) {
mlog_errno(status);
goto bail;
}
insert_inode_hash(inode);
dentry->d_op = &ocfs2_dentry_ops;
d_instantiate(dentry, inode);
bail:
if (status < 0 && did_quota)
vfs_dq_free_space_nodirty(inode,
ocfs2_clusters_to_bytes(osb->sb, 1));
if (status < 0 && did_quota_inode)
vfs_dq_free_inode(inode);
if (handle)
ocfs2_commit_trans(osb, handle);
ocfs2_inode_unlock(dir, 1);
brelse(new_fe_bh);
brelse(parent_fe_bh);
kfree(si.name);
kfree(si.value);
ocfs2_free_dir_lookup_result(&lookup);
if (inode_ac)
ocfs2_free_alloc_context(inode_ac);
if (data_ac)
ocfs2_free_alloc_context(data_ac);
if (xattr_ac)
ocfs2_free_alloc_context(xattr_ac);
if ((status < 0) && inode) {
clear_nlink(inode);
iput(inode);
}
mlog_exit(status);
return status;
}
static int ocfs2_blkno_stringify(u64 blkno, char *name)
{
int status, namelen;
mlog_entry_void();
namelen = snprintf(name, OCFS2_ORPHAN_NAMELEN + 1, "%016llx",
(long long)blkno);
if (namelen <= 0) {
if (namelen)
status = namelen;
else
status = -EINVAL;
mlog_errno(status);
goto bail;
}
if (namelen != OCFS2_ORPHAN_NAMELEN) {
status = -EINVAL;
mlog_errno(status);
goto bail;
}
mlog(0, "built filename '%s' for orphan dir (len=%d)\n", name,
namelen);
status = 0;
bail:
mlog_exit(status);
return status;
}
static int ocfs2_prepare_orphan_dir(struct ocfs2_super *osb,
struct inode **ret_orphan_dir,
u64 blkno,
char *name,
struct ocfs2_dir_lookup_result *lookup)
{
struct inode *orphan_dir_inode;
struct buffer_head *orphan_dir_bh = NULL;
int status = 0;
status = ocfs2_blkno_stringify(blkno, name);
if (status < 0) {
mlog_errno(status);
return status;
}
orphan_dir_inode = ocfs2_get_system_file_inode(osb,
ORPHAN_DIR_SYSTEM_INODE,
osb->slot_num);
if (!orphan_dir_inode) {
status = -ENOENT;
mlog_errno(status);
return status;
}
mutex_lock(&orphan_dir_inode->i_mutex);
status = ocfs2_inode_lock(orphan_dir_inode, &orphan_dir_bh, 1);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_prepare_dir_for_insert(osb, orphan_dir_inode,
orphan_dir_bh, name,
OCFS2_ORPHAN_NAMELEN, lookup);
if (status < 0) {
ocfs2_inode_unlock(orphan_dir_inode, 1);
mlog_errno(status);
goto leave;
}
*ret_orphan_dir = orphan_dir_inode;
leave:
if (status) {
mutex_unlock(&orphan_dir_inode->i_mutex);
iput(orphan_dir_inode);
}
brelse(orphan_dir_bh);
mlog_exit(status);
return status;
}
static int ocfs2_orphan_add(struct ocfs2_super *osb,
handle_t *handle,
struct inode *inode,
struct ocfs2_dinode *fe,
char *name,
struct ocfs2_dir_lookup_result *lookup,
struct inode *orphan_dir_inode)
{
struct buffer_head *orphan_dir_bh = NULL;
int status = 0;
struct ocfs2_dinode *orphan_fe;
mlog_entry("(inode->i_ino = %lu)\n", inode->i_ino);
status = ocfs2_read_inode_block(orphan_dir_inode, &orphan_dir_bh);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_journal_access_di(handle,
INODE_CACHE(orphan_dir_inode),
orphan_dir_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto leave;
}
/* we're a cluster, and nlink can change on disk from
* underneath us... */
orphan_fe = (struct ocfs2_dinode *) orphan_dir_bh->b_data;
if (S_ISDIR(inode->i_mode))
ocfs2_add_links_count(orphan_fe, 1);
orphan_dir_inode->i_nlink = ocfs2_read_links_count(orphan_fe);
status = ocfs2_journal_dirty(handle, orphan_dir_bh);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = __ocfs2_add_entry(handle, orphan_dir_inode, name,
OCFS2_ORPHAN_NAMELEN, inode,
OCFS2_I(inode)->ip_blkno,
orphan_dir_bh, lookup);
if (status < 0) {
mlog_errno(status);
goto leave;
}
le32_add_cpu(&fe->i_flags, OCFS2_ORPHANED_FL);
/* Record which orphan dir our inode now resides
* in. delete_inode will use this to determine which orphan
* dir to lock. */
fe->i_orphaned_slot = cpu_to_le16(osb->slot_num);
mlog(0, "Inode %llu orphaned in slot %d\n",
(unsigned long long)OCFS2_I(inode)->ip_blkno, osb->slot_num);
leave:
brelse(orphan_dir_bh);
mlog_exit(status);
return status;
}
/* unlike orphan_add, we expect the orphan dir to already be locked here. */
int ocfs2_orphan_del(struct ocfs2_super *osb,
handle_t *handle,
struct inode *orphan_dir_inode,
struct inode *inode,
struct buffer_head *orphan_dir_bh)
{
char name[OCFS2_ORPHAN_NAMELEN + 1];
struct ocfs2_dinode *orphan_fe;
int status = 0;
struct ocfs2_dir_lookup_result lookup = { NULL, };
mlog_entry_void();
status = ocfs2_blkno_stringify(OCFS2_I(inode)->ip_blkno, name);
if (status < 0) {
mlog_errno(status);
goto leave;
}
mlog(0, "removing '%s' from orphan dir %llu (namelen=%d)\n",
name, (unsigned long long)OCFS2_I(orphan_dir_inode)->ip_blkno,
OCFS2_ORPHAN_NAMELEN);
/* find it's spot in the orphan directory */
status = ocfs2_find_entry(name, OCFS2_ORPHAN_NAMELEN, orphan_dir_inode,
&lookup);
if (status) {
mlog_errno(status);
goto leave;
}
/* remove it from the orphan directory */
status = ocfs2_delete_entry(handle, orphan_dir_inode, &lookup);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_journal_access_di(handle,
INODE_CACHE(orphan_dir_inode),
orphan_dir_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto leave;
}
/* do the i_nlink dance! :) */
orphan_fe = (struct ocfs2_dinode *) orphan_dir_bh->b_data;
if (S_ISDIR(inode->i_mode))
ocfs2_add_links_count(orphan_fe, -1);
orphan_dir_inode->i_nlink = ocfs2_read_links_count(orphan_fe);
status = ocfs2_journal_dirty(handle, orphan_dir_bh);
if (status < 0) {
mlog_errno(status);
goto leave;
}
leave:
ocfs2_free_dir_lookup_result(&lookup);
mlog_exit(status);
return status;
}
int ocfs2_create_inode_in_orphan(struct inode *dir,
int mode,
struct inode **new_inode)
{
int status, did_quota_inode = 0;
struct inode *inode = NULL;
struct inode *orphan_dir = NULL;
struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
struct ocfs2_dinode *di = NULL;
handle_t *handle = NULL;
char orphan_name[OCFS2_ORPHAN_NAMELEN + 1];
struct buffer_head *parent_di_bh = NULL;
struct buffer_head *new_di_bh = NULL;
struct ocfs2_alloc_context *inode_ac = NULL;
struct ocfs2_dir_lookup_result orphan_insert = { NULL, };
status = ocfs2_inode_lock(dir, &parent_di_bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
return status;
}
/*
* We give the orphan dir the root blkno to fake an orphan name,
* and allocate enough space for our insertion.
*/
status = ocfs2_prepare_orphan_dir(osb, &orphan_dir,
osb->root_blkno,
orphan_name, &orphan_insert);
if (status < 0) {
mlog_errno(status);
goto leave;
}
/* reserve an inode spot */
status = ocfs2_reserve_new_inode(osb, &inode_ac);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
goto leave;
}
inode = ocfs2_get_init_inode(dir, mode);
if (!inode) {
status = -ENOMEM;
mlog_errno(status);
goto leave;
}
handle = ocfs2_start_trans(osb, ocfs2_mknod_credits(osb->sb, 0, 0));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
handle = NULL;
mlog_errno(status);
goto leave;
}
/* We don't use standard VFS wrapper because we don't want vfs_dq_init
* to be called. */
if (sb_any_quota_active(osb->sb) &&
osb->sb->dq_op->alloc_inode(inode, 1) == NO_QUOTA) {
status = -EDQUOT;
goto leave;
}
did_quota_inode = 1;
/* do the real work now. */
status = ocfs2_mknod_locked(osb, dir, inode,
0, &new_di_bh, parent_di_bh, handle,
inode_ac);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_blkno_stringify(OCFS2_I(inode)->ip_blkno, orphan_name);
if (status < 0) {
mlog_errno(status);
goto leave;
}
di = (struct ocfs2_dinode *)new_di_bh->b_data;
status = ocfs2_orphan_add(osb, handle, inode, di, orphan_name,
&orphan_insert, orphan_dir);
if (status < 0) {
mlog_errno(status);
goto leave;
}
/* get open lock so that only nodes can't remove it from orphan dir. */
status = ocfs2_open_lock(inode);
if (status < 0)
mlog_errno(status);
leave:
if (status < 0 && did_quota_inode)
vfs_dq_free_inode(inode);
if (handle)
ocfs2_commit_trans(osb, handle);
if (orphan_dir) {
/* This was locked for us in ocfs2_prepare_orphan_dir() */
ocfs2_inode_unlock(orphan_dir, 1);
mutex_unlock(&orphan_dir->i_mutex);
iput(orphan_dir);
}
if (status == -ENOSPC)
mlog(0, "Disk is full\n");
if ((status < 0) && inode) {
clear_nlink(inode);
iput(inode);
}
if (inode_ac)
ocfs2_free_alloc_context(inode_ac);
brelse(new_di_bh);
if (!status)
*new_inode = inode;
ocfs2_free_dir_lookup_result(&orphan_insert);
ocfs2_inode_unlock(dir, 1);
brelse(parent_di_bh);
return status;
}
int ocfs2_mv_orphaned_inode_to_new(struct inode *dir,
struct inode *inode,
struct dentry *dentry)
{
int status = 0;
struct buffer_head *parent_di_bh = NULL;
handle_t *handle = NULL;
struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
struct ocfs2_dinode *dir_di, *di;
struct inode *orphan_dir_inode = NULL;
struct buffer_head *orphan_dir_bh = NULL;
struct buffer_head *di_bh = NULL;
struct ocfs2_dir_lookup_result lookup = { NULL, };
mlog_entry("(0x%p, 0x%p, %.*s')\n", dir, dentry,
dentry->d_name.len, dentry->d_name.name);
status = ocfs2_inode_lock(dir, &parent_di_bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
return status;
}
dir_di = (struct ocfs2_dinode *) parent_di_bh->b_data;
if (!dir_di->i_links_count) {
/* can't make a file in a deleted directory. */
status = -ENOENT;
goto leave;
}
status = ocfs2_check_dir_for_entry(dir, dentry->d_name.name,
dentry->d_name.len);
if (status)
goto leave;
/* get a spot inside the dir. */
status = ocfs2_prepare_dir_for_insert(osb, dir, parent_di_bh,
dentry->d_name.name,
dentry->d_name.len, &lookup);
if (status < 0) {
mlog_errno(status);
goto leave;
}
orphan_dir_inode = ocfs2_get_system_file_inode(osb,
ORPHAN_DIR_SYSTEM_INODE,
osb->slot_num);
if (!orphan_dir_inode) {
status = -EEXIST;
mlog_errno(status);
goto leave;
}
mutex_lock(&orphan_dir_inode->i_mutex);
status = ocfs2_inode_lock(orphan_dir_inode, &orphan_dir_bh, 1);
if (status < 0) {
mlog_errno(status);
mutex_unlock(&orphan_dir_inode->i_mutex);
iput(orphan_dir_inode);
goto leave;
}
status = ocfs2_read_inode_block(inode, &di_bh);
if (status < 0) {
mlog_errno(status);
goto orphan_unlock;
}
handle = ocfs2_start_trans(osb, ocfs2_rename_credits(osb->sb));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
handle = NULL;
mlog_errno(status);
goto orphan_unlock;
}
status = ocfs2_journal_access_di(handle, INODE_CACHE(inode),
di_bh, OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto out_commit;
}
status = ocfs2_orphan_del(osb, handle, orphan_dir_inode, inode,
orphan_dir_bh);
if (status < 0) {
mlog_errno(status);
goto out_commit;
}
di = (struct ocfs2_dinode *)di_bh->b_data;
le32_add_cpu(&di->i_flags, -OCFS2_ORPHANED_FL);
di->i_orphaned_slot = 0;
ocfs2_journal_dirty(handle, di_bh);
status = ocfs2_add_entry(handle, dentry, inode,
OCFS2_I(inode)->ip_blkno, parent_di_bh,
&lookup);
if (status < 0) {
mlog_errno(status);
goto out_commit;
}
status = ocfs2_dentry_attach_lock(dentry, inode,
OCFS2_I(dir)->ip_blkno);
if (status) {
mlog_errno(status);
goto out_commit;
}
insert_inode_hash(inode);
dentry->d_op = &ocfs2_dentry_ops;
d_instantiate(dentry, inode);
status = 0;
out_commit:
ocfs2_commit_trans(osb, handle);
orphan_unlock:
ocfs2_inode_unlock(orphan_dir_inode, 1);
mutex_unlock(&orphan_dir_inode->i_mutex);
iput(orphan_dir_inode);
leave:
ocfs2_inode_unlock(dir, 1);
brelse(di_bh);
brelse(parent_di_bh);
brelse(orphan_dir_bh);
ocfs2_free_dir_lookup_result(&lookup);
mlog_exit(status);
return status;
}
const struct inode_operations ocfs2_dir_iops = {
.create = ocfs2_create,
.lookup = ocfs2_lookup,
.link = ocfs2_link,
.unlink = ocfs2_unlink,
.rmdir = ocfs2_unlink,
.symlink = ocfs2_symlink,
.mkdir = ocfs2_mkdir,
.mknod = ocfs2_mknod,
.rename = ocfs2_rename,
.setattr = ocfs2_setattr,
.getattr = ocfs2_getattr,
.permission = ocfs2_permission,
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ocfs2_listxattr,
.removexattr = generic_removexattr,
};
| gpl-2.0 |
kevin0100/android_kernel_qcom_msm8916 | drivers/input/misc/arizona-haptics.c | 776 | 6282 | /*
* Arizona haptics driver
*
* Copyright 2012 Wolfson Microelectronics plc
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <linux/mfd/arizona/core.h>
#include <linux/mfd/arizona/pdata.h>
#include <linux/mfd/arizona/registers.h>
struct arizona_haptics {
struct arizona *arizona;
struct input_dev *input_dev;
struct work_struct work;
struct mutex mutex;
u8 intensity;
};
static void arizona_haptics_work(struct work_struct *work)
{
struct arizona_haptics *haptics = container_of(work,
struct arizona_haptics,
work);
struct arizona *arizona = haptics->arizona;
struct mutex *dapm_mutex = &arizona->dapm->card->dapm_mutex;
int ret;
if (!haptics->arizona->dapm) {
dev_err(arizona->dev, "No DAPM context\n");
return;
}
if (haptics->intensity) {
ret = regmap_update_bits(arizona->regmap,
ARIZONA_HAPTICS_PHASE_2_INTENSITY,
ARIZONA_PHASE2_INTENSITY_MASK,
haptics->intensity);
if (ret != 0) {
dev_err(arizona->dev, "Failed to set intensity: %d\n",
ret);
return;
}
/* This enable sequence will be a noop if already enabled */
ret = regmap_update_bits(arizona->regmap,
ARIZONA_HAPTICS_CONTROL_1,
ARIZONA_HAP_CTRL_MASK,
1 << ARIZONA_HAP_CTRL_SHIFT);
if (ret != 0) {
dev_err(arizona->dev, "Failed to start haptics: %d\n",
ret);
return;
}
mutex_lock_nested(dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME);
ret = snd_soc_dapm_enable_pin(arizona->dapm, "HAPTICS");
if (ret != 0) {
dev_err(arizona->dev, "Failed to start HAPTICS: %d\n",
ret);
mutex_unlock(dapm_mutex);
return;
}
ret = snd_soc_dapm_sync(arizona->dapm);
if (ret != 0) {
dev_err(arizona->dev, "Failed to sync DAPM: %d\n",
ret);
mutex_unlock(dapm_mutex);
return;
}
mutex_unlock(dapm_mutex);
} else {
/* This disable sequence will be a noop if already enabled */
mutex_lock_nested(dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME);
ret = snd_soc_dapm_disable_pin(arizona->dapm, "HAPTICS");
if (ret != 0) {
dev_err(arizona->dev, "Failed to disable HAPTICS: %d\n",
ret);
mutex_unlock(dapm_mutex);
return;
}
ret = snd_soc_dapm_sync(arizona->dapm);
if (ret != 0) {
dev_err(arizona->dev, "Failed to sync DAPM: %d\n",
ret);
mutex_unlock(dapm_mutex);
return;
}
mutex_unlock(dapm_mutex);
ret = regmap_update_bits(arizona->regmap,
ARIZONA_HAPTICS_CONTROL_1,
ARIZONA_HAP_CTRL_MASK,
1 << ARIZONA_HAP_CTRL_SHIFT);
if (ret != 0) {
dev_err(arizona->dev, "Failed to stop haptics: %d\n",
ret);
return;
}
}
}
static int arizona_haptics_play(struct input_dev *input, void *data,
struct ff_effect *effect)
{
struct arizona_haptics *haptics = input_get_drvdata(input);
struct arizona *arizona = haptics->arizona;
if (!arizona->dapm) {
dev_err(arizona->dev, "No DAPM context\n");
return -EBUSY;
}
if (effect->u.rumble.strong_magnitude) {
/* Scale the magnitude into the range the device supports */
if (arizona->pdata.hap_act) {
haptics->intensity =
effect->u.rumble.strong_magnitude >> 9;
if (effect->direction < 0x8000)
haptics->intensity += 0x7f;
} else {
haptics->intensity =
effect->u.rumble.strong_magnitude >> 8;
}
} else {
haptics->intensity = 0;
}
schedule_work(&haptics->work);
return 0;
}
static void arizona_haptics_close(struct input_dev *input)
{
struct arizona_haptics *haptics = input_get_drvdata(input);
struct mutex *dapm_mutex = &haptics->arizona->dapm->card->dapm_mutex;
cancel_work_sync(&haptics->work);
mutex_lock_nested(dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME);
if (haptics->arizona->dapm)
snd_soc_dapm_disable_pin(haptics->arizona->dapm, "HAPTICS");
mutex_unlock(dapm_mutex);
}
static int arizona_haptics_probe(struct platform_device *pdev)
{
struct arizona *arizona = dev_get_drvdata(pdev->dev.parent);
struct arizona_haptics *haptics;
int ret;
haptics = devm_kzalloc(&pdev->dev, sizeof(*haptics), GFP_KERNEL);
if (!haptics)
return -ENOMEM;
haptics->arizona = arizona;
ret = regmap_update_bits(arizona->regmap, ARIZONA_HAPTICS_CONTROL_1,
ARIZONA_HAP_ACT, arizona->pdata.hap_act);
if (ret != 0) {
dev_err(arizona->dev, "Failed to set haptics actuator: %d\n",
ret);
return ret;
}
INIT_WORK(&haptics->work, arizona_haptics_work);
haptics->input_dev = input_allocate_device();
if (haptics->input_dev == NULL) {
dev_err(arizona->dev, "Failed to allocate input device\n");
return -ENOMEM;
}
input_set_drvdata(haptics->input_dev, haptics);
haptics->input_dev->name = "arizona:haptics";
haptics->input_dev->dev.parent = pdev->dev.parent;
haptics->input_dev->close = arizona_haptics_close;
__set_bit(FF_RUMBLE, haptics->input_dev->ffbit);
ret = input_ff_create_memless(haptics->input_dev, NULL,
arizona_haptics_play);
if (ret < 0) {
dev_err(arizona->dev, "input_ff_create_memless() failed: %d\n",
ret);
goto err_ialloc;
}
ret = input_register_device(haptics->input_dev);
if (ret < 0) {
dev_err(arizona->dev, "couldn't register input device: %d\n",
ret);
goto err_iff;
}
platform_set_drvdata(pdev, haptics);
return 0;
err_iff:
if (haptics->input_dev)
input_ff_destroy(haptics->input_dev);
err_ialloc:
input_free_device(haptics->input_dev);
return ret;
}
static int arizona_haptics_remove(struct platform_device *pdev)
{
struct arizona_haptics *haptics = platform_get_drvdata(pdev);
input_unregister_device(haptics->input_dev);
return 0;
}
static struct platform_driver arizona_haptics_driver = {
.probe = arizona_haptics_probe,
.remove = arizona_haptics_remove,
.driver = {
.name = "arizona-haptics",
.owner = THIS_MODULE,
},
};
module_platform_driver(arizona_haptics_driver);
MODULE_ALIAS("platform:arizona-haptics");
MODULE_DESCRIPTION("Arizona haptics driver");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
| gpl-2.0 |
tmc/openwrt-go | package/network/services/ead/src/tinysrp/srvtest.c | 776 | 3730 | /*
* Copyright (c) 1997-1999 The Stanford SRP Authentication Project
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL STANFORD BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
* THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* In addition, the following conditions apply:
*
* 1. Any software that incorporates the SRP authentication technology
* must display the following acknowlegment:
* "This product uses the 'Secure Remote Password' cryptographic
* authentication system developed by Tom Wu (tjw@CS.Stanford.EDU)."
*
* 2. Any software that incorporates all or part of the SRP distribution
* itself must also display the following acknowledgment:
* "This product includes software developed by Tom Wu and Eugene
* Jhong for the SRP Distribution (http://srp.stanford.edu/srp/)."
*
* 3. Redistributions in source or binary form must retain an intact copy
* of this copyright notice and list of conditions.
*/
#include <stdio.h>
#include "t_defines.h"
#include "t_pwd.h"
#include "t_server.h"
int
main(argc, argv)
int argc;
char * argv[];
{
struct t_server * ts;
struct t_pw * tpw;
struct t_conf * tcnf;
struct t_num * B;
char username[MAXUSERLEN];
char hexbuf[MAXHEXPARAMLEN];
char buf[MAXPARAMLEN];
struct t_num A;
unsigned char * skey;
unsigned char cbuf[20];
FILE * fp;
FILE * fp2;
char confname[256];
printf("Enter username: ");
fgets(username, sizeof(username), stdin);
username[strlen(username) - 1] = '\0';
ts = t_serveropen(username);
if(ts == NULL) {
fprintf(stderr, "User %s not found\n", username);
exit(1);
}
#if 0
printf("n: %s\n", t_tob64(hexbuf, ts->n.data, ts->n.len));
printf("g: %s\n", t_tob64(hexbuf, ts->g.data, ts->g.len));
#endif
printf("index (to client): %d\n", ts->index);
printf("salt (to client): %s\n", t_tob64(hexbuf, ts->s.data, ts->s.len));
B = t_servergenexp(ts);
printf("Enter A (from client): ");
fgets(hexbuf, sizeof(hexbuf), stdin);
A.data = buf;
A.len = t_fromb64(A.data, hexbuf);
printf("B (to client): %s\n", t_tob64(hexbuf, B->data, B->len));
skey = t_servergetkey(ts, &A);
printf("Session key: %s\n", t_tohex(hexbuf, skey, 40));
/* printf("[Expected response: %s]\n", t_tohex(hexbuf, cbuf, 16)); */
printf("Enter response (from client): ");
fgets(hexbuf, sizeof(hexbuf), stdin);
hexbuf[strlen(hexbuf) - 1] = '\0';
t_fromhex(cbuf, hexbuf);
if(t_serververify(ts, cbuf) == 0) {
printf("Authentication successful.\n");
printf("Response (to client): %s\n",
t_tohex(hexbuf, t_serverresponse(ts), RESPONSE_LEN));
} else
printf("Authentication failed.\n");
t_serverclose(ts);
return 0;
}
| gpl-2.0 |
sev3n85/samsung_s3ve3g_EUR | arch/arm/mach-msm/sec_getlog.c | 776 | 4119 | /*
* sec_getlog.c
*
*/
#include <linux/module.h>
#include <linux/errno.h>
static struct {
u32 special_mark_1;
u32 special_mark_2;
u32 special_mark_3;
u32 special_mark_4;
void *p_fb; /* it must be physical address */
u32 xres;
u32 yres;
u32 bpp; /* color depth : 16 or 24 */
u32 frames; /* frame buffer count : 2 */
} frame_buf_mark = {
.special_mark_1 = (('*' << 24) | ('^' << 16) | ('^' << 8) | ('*' << 0)),
.special_mark_2 = (('I' << 24) | ('n' << 16) | ('f' << 8) | ('o' << 0)),
.special_mark_3 = (('H' << 24) | ('e' << 16) | ('r' << 8) | ('e' << 0)),
.special_mark_4 = (('f' << 24) | ('b' << 16) | ('u' << 8) | ('f' << 0)),
};
void sec_getlog_supply_fbinfo(void *p_fb, u32 xres, u32 yres, u32 bpp,
u32 frames)
{
if (p_fb) {
pr_info("%s: 0x %p %d %d %d %d\n", __func__, p_fb, xres, yres,
bpp, frames);
frame_buf_mark.p_fb = p_fb;
frame_buf_mark.xres = xres;
frame_buf_mark.yres = yres;
frame_buf_mark.bpp = bpp;
frame_buf_mark.frames = frames;
}
}
EXPORT_SYMBOL(sec_getlog_supply_fbinfo);
static struct {
u32 special_mark_1;
u32 special_mark_2;
u32 special_mark_3;
u32 special_mark_4;
u32 log_mark_version;
u32 framebuffer_mark_version;
void *this; /* this is used for addressing
log buffer in 2 dump files */
struct {
u32 size; /* memory block's size */
u32 addr; /* memory block'sPhysical address */
} mem[2];
} marks_ver_mark = {
.special_mark_1 = (('*' << 24) | ('^' << 16) | ('^' << 8) | ('*' << 0)),
.special_mark_2 = (('I' << 24) | ('n' << 16) | ('f' << 8) | ('o' << 0)),
.special_mark_3 = (('H' << 24) | ('e' << 16) | ('r' << 8) | ('e' << 0)),
.special_mark_4 = (('v' << 24) | ('e' << 16) | ('r' << 8) | ('s' << 0)),
.log_mark_version = 1,
.framebuffer_mark_version = 1,
.this = &marks_ver_mark,
};
void sec_getlog_supply_meminfo(u32 size0, u32 addr0, u32 size1, u32 addr1)
{
pr_info("%s: %x %x %x %x\n", __func__, size0, addr0, size1, addr1);
marks_ver_mark.mem[0].size = size0;
marks_ver_mark.mem[0].addr = addr0;
marks_ver_mark.mem[1].size = size1;
marks_ver_mark.mem[1].addr = addr1;
}
EXPORT_SYMBOL(sec_getlog_supply_meminfo);
/* mark for GetLog extraction */
static struct {
u32 special_mark_1;
u32 special_mark_2;
u32 special_mark_3;
u32 special_mark_4;
void *p_main;
void *p_radio;
void *p_events;
void *p_system;
} plat_log_mark = {
.special_mark_1 = (('*' << 24) | ('^' << 16) | ('^' << 8) | ('*' << 0)),
.special_mark_2 = (('I' << 24) | ('n' << 16) | ('f' << 8) | ('o' << 0)),
.special_mark_3 = (('H' << 24) | ('e' << 16) | ('r' << 8) | ('e' << 0)),
.special_mark_4 = (('p' << 24) | ('l' << 16) | ('o' << 8) | ('g' << 0)),
};
static void sec_getlog_trim(unsigned int *val)
{
*val = (*val) & 0x0FFFFFFF;
}
void sec_getlog_supply_loggerinfo(void *p_main,
void *p_radio, void *p_events, void *p_system)
{
pr_info("%s: 0x%p 0x%p 0x%p 0x%p\n", __func__, p_main, p_radio,
p_events, p_system);
plat_log_mark.p_main = p_main + CONFIG_PHYS_OFFSET;
sec_getlog_trim((unsigned int *)&plat_log_mark.p_main);
plat_log_mark.p_radio = p_radio + CONFIG_PHYS_OFFSET;
sec_getlog_trim((unsigned int *)&plat_log_mark.p_radio);
plat_log_mark.p_events = p_events + CONFIG_PHYS_OFFSET;
sec_getlog_trim((unsigned int *)&plat_log_mark.p_events);
plat_log_mark.p_system = p_system + CONFIG_PHYS_OFFSET;
sec_getlog_trim((unsigned int *)&plat_log_mark.p_system);
}
EXPORT_SYMBOL(sec_getlog_supply_loggerinfo);
static struct {
u32 special_mark_1;
u32 special_mark_2;
u32 special_mark_3;
u32 special_mark_4;
void *klog_buf;
} kernel_log_mark = {
.special_mark_1 = (('*' << 24) | ('^' << 16) | ('^' << 8) | ('*' << 0)),
.special_mark_2 = (('I' << 24) | ('n' << 16) | ('f' << 8) | ('o' << 0)),
.special_mark_3 = (('H' << 24) | ('e' << 16) | ('r' << 8) | ('e' << 0)),
.special_mark_4 = (('k' << 24) | ('l' << 16) | ('o' << 8) | ('g' << 0)),
};
void sec_getlog_supply_kloginfo(void *klog_buf)
{
pr_info("%s: 0x%p\n", __func__, klog_buf);
kernel_log_mark.klog_buf = klog_buf + CONFIG_PHYS_OFFSET;
sec_getlog_trim((unsigned int *)&kernel_log_mark.klog_buf);
}
EXPORT_SYMBOL(sec_getlog_supply_kloginfo);
| gpl-2.0 |
baberthal/linux | drivers/media/platform/omap3isp/isph3a_af.c | 1032 | 11078 | /*
* isph3a_af.c
*
* TI OMAP3 ISP - H3A AF module
*
* Copyright (C) 2010 Nokia Corporation
* Copyright (C) 2009 Texas Instruments, Inc.
*
* Contacts: David Cohen <dacohen@gmail.com>
* Laurent Pinchart <laurent.pinchart@ideasonboard.com>
* Sakari Ailus <sakari.ailus@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Linux specific include files */
#include <linux/device.h>
#include <linux/slab.h>
#include "isp.h"
#include "isph3a.h"
#include "ispstat.h"
#define IS_OUT_OF_BOUNDS(value, min, max) \
(((value) < (min)) || ((value) > (max)))
static void h3a_af_setup_regs(struct ispstat *af, void *priv)
{
struct omap3isp_h3a_af_config *conf = priv;
u32 pcr;
u32 pax1;
u32 pax2;
u32 paxstart;
u32 coef;
u32 base_coef_set0;
u32 base_coef_set1;
int index;
if (af->state == ISPSTAT_DISABLED)
return;
isp_reg_writel(af->isp, af->active_buf->dma_addr, OMAP3_ISP_IOMEM_H3A,
ISPH3A_AFBUFST);
if (!af->update)
return;
/* Configure Hardware Registers */
pax1 = ((conf->paxel.width >> 1) - 1) << AF_PAXW_SHIFT;
/* Set height in AFPAX1 */
pax1 |= (conf->paxel.height >> 1) - 1;
isp_reg_writel(af->isp, pax1, OMAP3_ISP_IOMEM_H3A, ISPH3A_AFPAX1);
/* Configure AFPAX2 Register */
/* Set Line Increment in AFPAX2 Register */
pax2 = ((conf->paxel.line_inc >> 1) - 1) << AF_LINE_INCR_SHIFT;
/* Set Vertical Count */
pax2 |= (conf->paxel.v_cnt - 1) << AF_VT_COUNT_SHIFT;
/* Set Horizontal Count */
pax2 |= (conf->paxel.h_cnt - 1);
isp_reg_writel(af->isp, pax2, OMAP3_ISP_IOMEM_H3A, ISPH3A_AFPAX2);
/* Configure PAXSTART Register */
/*Configure Horizontal Start */
paxstart = conf->paxel.h_start << AF_HZ_START_SHIFT;
/* Configure Vertical Start */
paxstart |= conf->paxel.v_start;
isp_reg_writel(af->isp, paxstart, OMAP3_ISP_IOMEM_H3A,
ISPH3A_AFPAXSTART);
/*SetIIRSH Register */
isp_reg_writel(af->isp, conf->iir.h_start,
OMAP3_ISP_IOMEM_H3A, ISPH3A_AFIIRSH);
base_coef_set0 = ISPH3A_AFCOEF010;
base_coef_set1 = ISPH3A_AFCOEF110;
for (index = 0; index <= 8; index += 2) {
/*Set IIR Filter0 Coefficients */
coef = 0;
coef |= conf->iir.coeff_set0[index];
coef |= conf->iir.coeff_set0[index + 1] <<
AF_COEF_SHIFT;
isp_reg_writel(af->isp, coef, OMAP3_ISP_IOMEM_H3A,
base_coef_set0);
base_coef_set0 += AFCOEF_OFFSET;
/*Set IIR Filter1 Coefficients */
coef = 0;
coef |= conf->iir.coeff_set1[index];
coef |= conf->iir.coeff_set1[index + 1] <<
AF_COEF_SHIFT;
isp_reg_writel(af->isp, coef, OMAP3_ISP_IOMEM_H3A,
base_coef_set1);
base_coef_set1 += AFCOEF_OFFSET;
}
/* set AFCOEF0010 Register */
isp_reg_writel(af->isp, conf->iir.coeff_set0[10],
OMAP3_ISP_IOMEM_H3A, ISPH3A_AFCOEF0010);
/* set AFCOEF1010 Register */
isp_reg_writel(af->isp, conf->iir.coeff_set1[10],
OMAP3_ISP_IOMEM_H3A, ISPH3A_AFCOEF1010);
/* PCR Register */
/* Set RGB Position */
pcr = conf->rgb_pos << AF_RGBPOS_SHIFT;
/* Set Accumulator Mode */
if (conf->fvmode == OMAP3ISP_AF_MODE_PEAK)
pcr |= AF_FVMODE;
/* Set A-law */
if (conf->alaw_enable)
pcr |= AF_ALAW_EN;
/* HMF Configurations */
if (conf->hmf.enable) {
/* Enable HMF */
pcr |= AF_MED_EN;
/* Set Median Threshold */
pcr |= conf->hmf.threshold << AF_MED_TH_SHIFT;
}
/* Set PCR Register */
isp_reg_clr_set(af->isp, OMAP3_ISP_IOMEM_H3A, ISPH3A_PCR,
AF_PCR_MASK, pcr);
af->update = 0;
af->config_counter += af->inc_config;
af->inc_config = 0;
af->buf_size = conf->buf_size;
}
static void h3a_af_enable(struct ispstat *af, int enable)
{
if (enable) {
isp_reg_set(af->isp, OMAP3_ISP_IOMEM_H3A, ISPH3A_PCR,
ISPH3A_PCR_AF_EN);
omap3isp_subclk_enable(af->isp, OMAP3_ISP_SUBCLK_AF);
} else {
isp_reg_clr(af->isp, OMAP3_ISP_IOMEM_H3A, ISPH3A_PCR,
ISPH3A_PCR_AF_EN);
omap3isp_subclk_disable(af->isp, OMAP3_ISP_SUBCLK_AF);
}
}
static int h3a_af_busy(struct ispstat *af)
{
return isp_reg_readl(af->isp, OMAP3_ISP_IOMEM_H3A, ISPH3A_PCR)
& ISPH3A_PCR_BUSYAF;
}
static u32 h3a_af_get_buf_size(struct omap3isp_h3a_af_config *conf)
{
return conf->paxel.h_cnt * conf->paxel.v_cnt * OMAP3ISP_AF_PAXEL_SIZE;
}
/* Function to check paxel parameters */
static int h3a_af_validate_params(struct ispstat *af, void *new_conf)
{
struct omap3isp_h3a_af_config *user_cfg = new_conf;
struct omap3isp_h3a_af_paxel *paxel_cfg = &user_cfg->paxel;
struct omap3isp_h3a_af_iir *iir_cfg = &user_cfg->iir;
int index;
u32 buf_size;
/* Check horizontal Count */
if (IS_OUT_OF_BOUNDS(paxel_cfg->h_cnt,
OMAP3ISP_AF_PAXEL_HORIZONTAL_COUNT_MIN,
OMAP3ISP_AF_PAXEL_HORIZONTAL_COUNT_MAX))
return -EINVAL;
/* Check Vertical Count */
if (IS_OUT_OF_BOUNDS(paxel_cfg->v_cnt,
OMAP3ISP_AF_PAXEL_VERTICAL_COUNT_MIN,
OMAP3ISP_AF_PAXEL_VERTICAL_COUNT_MAX))
return -EINVAL;
if (IS_OUT_OF_BOUNDS(paxel_cfg->height, OMAP3ISP_AF_PAXEL_HEIGHT_MIN,
OMAP3ISP_AF_PAXEL_HEIGHT_MAX) ||
paxel_cfg->height % 2)
return -EINVAL;
/* Check width */
if (IS_OUT_OF_BOUNDS(paxel_cfg->width, OMAP3ISP_AF_PAXEL_WIDTH_MIN,
OMAP3ISP_AF_PAXEL_WIDTH_MAX) ||
paxel_cfg->width % 2)
return -EINVAL;
/* Check Line Increment */
if (IS_OUT_OF_BOUNDS(paxel_cfg->line_inc,
OMAP3ISP_AF_PAXEL_INCREMENT_MIN,
OMAP3ISP_AF_PAXEL_INCREMENT_MAX) ||
paxel_cfg->line_inc % 2)
return -EINVAL;
/* Check Horizontal Start */
if ((paxel_cfg->h_start < iir_cfg->h_start) ||
IS_OUT_OF_BOUNDS(paxel_cfg->h_start,
OMAP3ISP_AF_PAXEL_HZSTART_MIN,
OMAP3ISP_AF_PAXEL_HZSTART_MAX))
return -EINVAL;
/* Check IIR */
for (index = 0; index < OMAP3ISP_AF_NUM_COEF; index++) {
if ((iir_cfg->coeff_set0[index]) > OMAP3ISP_AF_COEF_MAX)
return -EINVAL;
if ((iir_cfg->coeff_set1[index]) > OMAP3ISP_AF_COEF_MAX)
return -EINVAL;
}
if (IS_OUT_OF_BOUNDS(iir_cfg->h_start, OMAP3ISP_AF_IIRSH_MIN,
OMAP3ISP_AF_IIRSH_MAX))
return -EINVAL;
/* Hack: If paxel size is 12, the 10th AF window may be corrupted */
if ((paxel_cfg->h_cnt * paxel_cfg->v_cnt > 9) &&
(paxel_cfg->width * paxel_cfg->height == 12))
return -EINVAL;
buf_size = h3a_af_get_buf_size(user_cfg);
if (buf_size > user_cfg->buf_size)
/* User buf_size request wasn't enough */
user_cfg->buf_size = buf_size;
else if (user_cfg->buf_size > OMAP3ISP_AF_MAX_BUF_SIZE)
user_cfg->buf_size = OMAP3ISP_AF_MAX_BUF_SIZE;
return 0;
}
/* Update local parameters */
static void h3a_af_set_params(struct ispstat *af, void *new_conf)
{
struct omap3isp_h3a_af_config *user_cfg = new_conf;
struct omap3isp_h3a_af_config *cur_cfg = af->priv;
int update = 0;
int index;
/* alaw */
if (cur_cfg->alaw_enable != user_cfg->alaw_enable) {
update = 1;
goto out;
}
/* hmf */
if (cur_cfg->hmf.enable != user_cfg->hmf.enable) {
update = 1;
goto out;
}
if (cur_cfg->hmf.threshold != user_cfg->hmf.threshold) {
update = 1;
goto out;
}
/* rgbpos */
if (cur_cfg->rgb_pos != user_cfg->rgb_pos) {
update = 1;
goto out;
}
/* iir */
if (cur_cfg->iir.h_start != user_cfg->iir.h_start) {
update = 1;
goto out;
}
for (index = 0; index < OMAP3ISP_AF_NUM_COEF; index++) {
if (cur_cfg->iir.coeff_set0[index] !=
user_cfg->iir.coeff_set0[index]) {
update = 1;
goto out;
}
if (cur_cfg->iir.coeff_set1[index] !=
user_cfg->iir.coeff_set1[index]) {
update = 1;
goto out;
}
}
/* paxel */
if ((cur_cfg->paxel.width != user_cfg->paxel.width) ||
(cur_cfg->paxel.height != user_cfg->paxel.height) ||
(cur_cfg->paxel.h_start != user_cfg->paxel.h_start) ||
(cur_cfg->paxel.v_start != user_cfg->paxel.v_start) ||
(cur_cfg->paxel.h_cnt != user_cfg->paxel.h_cnt) ||
(cur_cfg->paxel.v_cnt != user_cfg->paxel.v_cnt) ||
(cur_cfg->paxel.line_inc != user_cfg->paxel.line_inc)) {
update = 1;
goto out;
}
/* af_mode */
if (cur_cfg->fvmode != user_cfg->fvmode)
update = 1;
out:
if (update || !af->configured) {
memcpy(cur_cfg, user_cfg, sizeof(*cur_cfg));
af->inc_config++;
af->update = 1;
/*
* User might be asked for a bigger buffer than necessary for
* this configuration. In order to return the right amount of
* data during buffer request, let's calculate the size here
* instead of stick with user_cfg->buf_size.
*/
cur_cfg->buf_size = h3a_af_get_buf_size(cur_cfg);
}
}
static long h3a_af_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
struct ispstat *stat = v4l2_get_subdevdata(sd);
switch (cmd) {
case VIDIOC_OMAP3ISP_AF_CFG:
return omap3isp_stat_config(stat, arg);
case VIDIOC_OMAP3ISP_STAT_REQ:
return omap3isp_stat_request_statistics(stat, arg);
case VIDIOC_OMAP3ISP_STAT_EN: {
int *en = arg;
return omap3isp_stat_enable(stat, !!*en);
}
}
return -ENOIOCTLCMD;
}
static const struct ispstat_ops h3a_af_ops = {
.validate_params = h3a_af_validate_params,
.set_params = h3a_af_set_params,
.setup_regs = h3a_af_setup_regs,
.enable = h3a_af_enable,
.busy = h3a_af_busy,
};
static const struct v4l2_subdev_core_ops h3a_af_subdev_core_ops = {
.ioctl = h3a_af_ioctl,
.subscribe_event = omap3isp_stat_subscribe_event,
.unsubscribe_event = omap3isp_stat_unsubscribe_event,
};
static const struct v4l2_subdev_video_ops h3a_af_subdev_video_ops = {
.s_stream = omap3isp_stat_s_stream,
};
static const struct v4l2_subdev_ops h3a_af_subdev_ops = {
.core = &h3a_af_subdev_core_ops,
.video = &h3a_af_subdev_video_ops,
};
/* Function to register the AF character device driver. */
int omap3isp_h3a_af_init(struct isp_device *isp)
{
struct ispstat *af = &isp->isp_af;
struct omap3isp_h3a_af_config *af_cfg;
struct omap3isp_h3a_af_config *af_recover_cfg;
af_cfg = devm_kzalloc(isp->dev, sizeof(*af_cfg), GFP_KERNEL);
if (af_cfg == NULL)
return -ENOMEM;
af->ops = &h3a_af_ops;
af->priv = af_cfg;
af->event_type = V4L2_EVENT_OMAP3ISP_AF;
af->isp = isp;
/* Set recover state configuration */
af_recover_cfg = devm_kzalloc(isp->dev, sizeof(*af_recover_cfg),
GFP_KERNEL);
if (!af_recover_cfg) {
dev_err(af->isp->dev, "AF: cannot allocate memory for recover "
"configuration.\n");
return -ENOMEM;
}
af_recover_cfg->paxel.h_start = OMAP3ISP_AF_PAXEL_HZSTART_MIN;
af_recover_cfg->paxel.width = OMAP3ISP_AF_PAXEL_WIDTH_MIN;
af_recover_cfg->paxel.height = OMAP3ISP_AF_PAXEL_HEIGHT_MIN;
af_recover_cfg->paxel.h_cnt = OMAP3ISP_AF_PAXEL_HORIZONTAL_COUNT_MIN;
af_recover_cfg->paxel.v_cnt = OMAP3ISP_AF_PAXEL_VERTICAL_COUNT_MIN;
af_recover_cfg->paxel.line_inc = OMAP3ISP_AF_PAXEL_INCREMENT_MIN;
if (h3a_af_validate_params(af, af_recover_cfg)) {
dev_err(af->isp->dev, "AF: recover configuration is "
"invalid.\n");
return -EINVAL;
}
af_recover_cfg->buf_size = h3a_af_get_buf_size(af_recover_cfg);
af->recover_priv = af_recover_cfg;
return omap3isp_stat_init(af, "AF", &h3a_af_subdev_ops);
}
void omap3isp_h3a_af_cleanup(struct isp_device *isp)
{
omap3isp_stat_cleanup(&isp->isp_af);
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.