repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
varigit/VAR-SOM-AM33-Kernel-3-14 | arch/m68k/sun3/sun3ints.c | 4603 | 2142 | /*
* linux/arch/m68k/sun3/sun3ints.c -- Sun-3(x) Linux interrupt handling code
*
* 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/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/kernel_stat.h>
#include <linux/interrupt.h>
#include <asm/segment.h>
#include <asm/intersil.h>
#include <asm/oplib.h>
#include <asm/sun3ints.h>
#include <asm/irq_regs.h>
#include <linux/seq_file.h>
extern void sun3_leds (unsigned char);
void sun3_disable_interrupts(void)
{
sun3_disable_irq(0);
}
void sun3_enable_interrupts(void)
{
sun3_enable_irq(0);
}
static int led_pattern[8] = {
~(0x80), ~(0x01),
~(0x40), ~(0x02),
~(0x20), ~(0x04),
~(0x10), ~(0x08)
};
volatile unsigned char* sun3_intreg;
void sun3_enable_irq(unsigned int irq)
{
*sun3_intreg |= (1 << irq);
}
void sun3_disable_irq(unsigned int irq)
{
*sun3_intreg &= ~(1 << irq);
}
static irqreturn_t sun3_int7(int irq, void *dev_id)
{
unsigned int cnt;
cnt = kstat_irqs_cpu(irq, 0);
if (!(cnt % 2000))
sun3_leds(led_pattern[cnt % 16000 / 2000]);
return IRQ_HANDLED;
}
static irqreturn_t sun3_int5(int irq, void *dev_id)
{
unsigned int cnt;
#ifdef CONFIG_SUN3
intersil_clear();
#endif
sun3_disable_irq(5);
sun3_enable_irq(5);
#ifdef CONFIG_SUN3
intersil_clear();
#endif
xtime_update(1);
update_process_times(user_mode(get_irq_regs()));
cnt = kstat_irqs_cpu(irq, 0);
if (!(cnt % 20))
sun3_leds(led_pattern[cnt % 160 / 20]);
return IRQ_HANDLED;
}
static irqreturn_t sun3_vec255(int irq, void *dev_id)
{
return IRQ_HANDLED;
}
void __init sun3_init_IRQ(void)
{
*sun3_intreg = 1;
m68k_setup_user_interrupt(VEC_USER, 128);
if (request_irq(IRQ_AUTO_5, sun3_int5, 0, "clock", NULL))
pr_err("Couldn't register %s interrupt\n", "int5");
if (request_irq(IRQ_AUTO_7, sun3_int7, 0, "nmi", NULL))
pr_err("Couldn't register %s interrupt\n", "int7");
if (request_irq(IRQ_USER+127, sun3_vec255, 0, "vec255", NULL))
pr_err("Couldn't register %s interrupt\n", "vec255");
}
| gpl-2.0 |
mtb3000gt/Deathly_Kernel_D2 | drivers/net/ethernet/intel/ixgbevf/vf.c | 4859 | 12780 | /*******************************************************************************
Intel 82599 Virtual Function driver
Copyright(c) 1999 - 2012 Intel Corporation.
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.
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.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include "vf.h"
#include "ixgbevf.h"
/**
* ixgbevf_start_hw_vf - Prepare hardware for Tx/Rx
* @hw: pointer to hardware structure
*
* Starts the hardware by filling the bus info structure and media type, clears
* all on chip counters, initializes receive address registers, multicast
* table, VLAN filter table, calls routine to set up link and flow control
* settings, and leaves transmit and receive units disabled and uninitialized
**/
static s32 ixgbevf_start_hw_vf(struct ixgbe_hw *hw)
{
/* Clear adapter stopped flag */
hw->adapter_stopped = false;
return 0;
}
/**
* ixgbevf_init_hw_vf - virtual function hardware initialization
* @hw: pointer to hardware structure
*
* Initialize the hardware by resetting the hardware and then starting
* the hardware
**/
static s32 ixgbevf_init_hw_vf(struct ixgbe_hw *hw)
{
s32 status = hw->mac.ops.start_hw(hw);
hw->mac.ops.get_mac_addr(hw, hw->mac.addr);
return status;
}
/**
* ixgbevf_reset_hw_vf - Performs hardware reset
* @hw: pointer to hardware structure
*
* Resets the hardware by reseting the transmit and receive units, masks and
* clears all interrupts.
**/
static s32 ixgbevf_reset_hw_vf(struct ixgbe_hw *hw)
{
struct ixgbe_mbx_info *mbx = &hw->mbx;
u32 timeout = IXGBE_VF_INIT_TIMEOUT;
s32 ret_val = IXGBE_ERR_INVALID_MAC_ADDR;
u32 msgbuf[IXGBE_VF_PERMADDR_MSG_LEN];
u8 *addr = (u8 *)(&msgbuf[1]);
/* Call adapter stop to disable tx/rx and clear interrupts */
hw->mac.ops.stop_adapter(hw);
IXGBE_WRITE_REG(hw, IXGBE_VFCTRL, IXGBE_CTRL_RST);
IXGBE_WRITE_FLUSH(hw);
/* we cannot reset while the RSTI / RSTD bits are asserted */
while (!mbx->ops.check_for_rst(hw) && timeout) {
timeout--;
udelay(5);
}
if (!timeout)
return IXGBE_ERR_RESET_FAILED;
/* mailbox timeout can now become active */
mbx->timeout = IXGBE_VF_MBX_INIT_TIMEOUT;
msgbuf[0] = IXGBE_VF_RESET;
mbx->ops.write_posted(hw, msgbuf, 1);
msleep(10);
/* set our "perm_addr" based on info provided by PF */
/* also set up the mc_filter_type which is piggy backed
* on the mac address in word 3 */
ret_val = mbx->ops.read_posted(hw, msgbuf, IXGBE_VF_PERMADDR_MSG_LEN);
if (ret_val)
return ret_val;
if (msgbuf[0] != (IXGBE_VF_RESET | IXGBE_VT_MSGTYPE_ACK))
return IXGBE_ERR_INVALID_MAC_ADDR;
memcpy(hw->mac.perm_addr, addr, ETH_ALEN);
hw->mac.mc_filter_type = msgbuf[IXGBE_VF_MC_TYPE_WORD];
return 0;
}
/**
* ixgbevf_stop_hw_vf - Generic stop Tx/Rx units
* @hw: pointer to hardware structure
*
* Sets the adapter_stopped flag within ixgbe_hw struct. Clears interrupts,
* disables transmit and receive units. The adapter_stopped flag is used by
* the shared code and drivers to determine if the adapter is in a stopped
* state and should not touch the hardware.
**/
static s32 ixgbevf_stop_hw_vf(struct ixgbe_hw *hw)
{
u32 number_of_queues;
u32 reg_val;
u16 i;
/*
* Set the adapter_stopped flag so other driver functions stop touching
* the hardware
*/
hw->adapter_stopped = true;
/* Disable the receive unit by stopped each queue */
number_of_queues = hw->mac.max_rx_queues;
for (i = 0; i < number_of_queues; i++) {
reg_val = IXGBE_READ_REG(hw, IXGBE_VFRXDCTL(i));
if (reg_val & IXGBE_RXDCTL_ENABLE) {
reg_val &= ~IXGBE_RXDCTL_ENABLE;
IXGBE_WRITE_REG(hw, IXGBE_VFRXDCTL(i), reg_val);
}
}
IXGBE_WRITE_FLUSH(hw);
/* Clear interrupt mask to stop from interrupts being generated */
IXGBE_WRITE_REG(hw, IXGBE_VTEIMC, IXGBE_VF_IRQ_CLEAR_MASK);
/* Clear any pending interrupts */
IXGBE_READ_REG(hw, IXGBE_VTEICR);
/* Disable the transmit unit. Each queue must be disabled. */
number_of_queues = hw->mac.max_tx_queues;
for (i = 0; i < number_of_queues; i++) {
reg_val = IXGBE_READ_REG(hw, IXGBE_VFTXDCTL(i));
if (reg_val & IXGBE_TXDCTL_ENABLE) {
reg_val &= ~IXGBE_TXDCTL_ENABLE;
IXGBE_WRITE_REG(hw, IXGBE_VFTXDCTL(i), reg_val);
}
}
return 0;
}
/**
* ixgbevf_mta_vector - Determines bit-vector in multicast table to set
* @hw: pointer to hardware structure
* @mc_addr: the multicast address
*
* Extracts the 12 bits, from a multicast address, to determine which
* bit-vector to set in the multicast table. The hardware uses 12 bits, from
* incoming rx multicast addresses, to determine the bit-vector to check in
* the MTA. Which of the 4 combination, of 12-bits, the hardware uses is set
* by the MO field of the MCSTCTRL. The MO field is set during initialization
* to mc_filter_type.
**/
static s32 ixgbevf_mta_vector(struct ixgbe_hw *hw, u8 *mc_addr)
{
u32 vector = 0;
switch (hw->mac.mc_filter_type) {
case 0: /* use bits [47:36] of the address */
vector = ((mc_addr[4] >> 4) | (((u16)mc_addr[5]) << 4));
break;
case 1: /* use bits [46:35] of the address */
vector = ((mc_addr[4] >> 3) | (((u16)mc_addr[5]) << 5));
break;
case 2: /* use bits [45:34] of the address */
vector = ((mc_addr[4] >> 2) | (((u16)mc_addr[5]) << 6));
break;
case 3: /* use bits [43:32] of the address */
vector = ((mc_addr[4]) | (((u16)mc_addr[5]) << 8));
break;
default: /* Invalid mc_filter_type */
break;
}
/* vector can only be 12-bits or boundary will be exceeded */
vector &= 0xFFF;
return vector;
}
/**
* ixgbevf_get_mac_addr_vf - Read device MAC address
* @hw: pointer to the HW structure
* @mac_addr: pointer to storage for retrieved MAC address
**/
static s32 ixgbevf_get_mac_addr_vf(struct ixgbe_hw *hw, u8 *mac_addr)
{
memcpy(mac_addr, hw->mac.perm_addr, ETH_ALEN);
return 0;
}
static s32 ixgbevf_set_uc_addr_vf(struct ixgbe_hw *hw, u32 index, u8 *addr)
{
struct ixgbe_mbx_info *mbx = &hw->mbx;
u32 msgbuf[3];
u8 *msg_addr = (u8 *)(&msgbuf[1]);
s32 ret_val;
memset(msgbuf, 0, sizeof(msgbuf));
/*
* If index is one then this is the start of a new list and needs
* indication to the PF so it can do it's own list management.
* If it is zero then that tells the PF to just clear all of
* this VF's macvlans and there is no new list.
*/
msgbuf[0] |= index << IXGBE_VT_MSGINFO_SHIFT;
msgbuf[0] |= IXGBE_VF_SET_MACVLAN;
if (addr)
memcpy(msg_addr, addr, 6);
ret_val = mbx->ops.write_posted(hw, msgbuf, 3);
if (!ret_val)
ret_val = mbx->ops.read_posted(hw, msgbuf, 3);
msgbuf[0] &= ~IXGBE_VT_MSGTYPE_CTS;
if (!ret_val)
if (msgbuf[0] ==
(IXGBE_VF_SET_MACVLAN | IXGBE_VT_MSGTYPE_NACK))
ret_val = -ENOMEM;
return ret_val;
}
/**
* ixgbevf_set_rar_vf - set device MAC address
* @hw: pointer to hardware structure
* @index: Receive address register to write
* @addr: Address to put into receive address register
* @vmdq: Unused in this implementation
**/
static s32 ixgbevf_set_rar_vf(struct ixgbe_hw *hw, u32 index, u8 *addr,
u32 vmdq)
{
struct ixgbe_mbx_info *mbx = &hw->mbx;
u32 msgbuf[3];
u8 *msg_addr = (u8 *)(&msgbuf[1]);
s32 ret_val;
memset(msgbuf, 0, sizeof(msgbuf));
msgbuf[0] = IXGBE_VF_SET_MAC_ADDR;
memcpy(msg_addr, addr, 6);
ret_val = mbx->ops.write_posted(hw, msgbuf, 3);
if (!ret_val)
ret_val = mbx->ops.read_posted(hw, msgbuf, 3);
msgbuf[0] &= ~IXGBE_VT_MSGTYPE_CTS;
/* if nacked the address was rejected, use "perm_addr" */
if (!ret_val &&
(msgbuf[0] == (IXGBE_VF_SET_MAC_ADDR | IXGBE_VT_MSGTYPE_NACK)))
ixgbevf_get_mac_addr_vf(hw, hw->mac.addr);
return ret_val;
}
static void ixgbevf_write_msg_read_ack(struct ixgbe_hw *hw,
u32 *msg, u16 size)
{
struct ixgbe_mbx_info *mbx = &hw->mbx;
u32 retmsg[IXGBE_VFMAILBOX_SIZE];
s32 retval = mbx->ops.write_posted(hw, msg, size);
if (!retval)
mbx->ops.read_posted(hw, retmsg, size);
}
/**
* ixgbevf_update_mc_addr_list_vf - Update Multicast addresses
* @hw: pointer to the HW structure
* @netdev: pointer to net device structure
*
* Updates the Multicast Table Array.
**/
static s32 ixgbevf_update_mc_addr_list_vf(struct ixgbe_hw *hw,
struct net_device *netdev)
{
struct netdev_hw_addr *ha;
u32 msgbuf[IXGBE_VFMAILBOX_SIZE];
u16 *vector_list = (u16 *)&msgbuf[1];
u32 cnt, i;
/* Each entry in the list uses 1 16 bit word. We have 30
* 16 bit words available in our HW msg buffer (minus 1 for the
* msg type). That's 30 hash values if we pack 'em right. If
* there are more than 30 MC addresses to add then punt the
* extras for now and then add code to handle more than 30 later.
* It would be unusual for a server to request that many multi-cast
* addresses except for in large enterprise network environments.
*/
cnt = netdev_mc_count(netdev);
if (cnt > 30)
cnt = 30;
msgbuf[0] = IXGBE_VF_SET_MULTICAST;
msgbuf[0] |= cnt << IXGBE_VT_MSGINFO_SHIFT;
i = 0;
netdev_for_each_mc_addr(ha, netdev) {
if (i == cnt)
break;
vector_list[i++] = ixgbevf_mta_vector(hw, ha->addr);
}
ixgbevf_write_msg_read_ack(hw, msgbuf, IXGBE_VFMAILBOX_SIZE);
return 0;
}
/**
* ixgbevf_set_vfta_vf - Set/Unset vlan filter table address
* @hw: pointer to the HW structure
* @vlan: 12 bit VLAN ID
* @vind: unused by VF drivers
* @vlan_on: if true then set bit, else clear bit
**/
static s32 ixgbevf_set_vfta_vf(struct ixgbe_hw *hw, u32 vlan, u32 vind,
bool vlan_on)
{
u32 msgbuf[2];
msgbuf[0] = IXGBE_VF_SET_VLAN;
msgbuf[1] = vlan;
/* Setting the 8 bit field MSG INFO to TRUE indicates "add" */
msgbuf[0] |= vlan_on << IXGBE_VT_MSGINFO_SHIFT;
ixgbevf_write_msg_read_ack(hw, msgbuf, 2);
return 0;
}
/**
* ixgbevf_setup_mac_link_vf - Setup MAC link settings
* @hw: pointer to hardware structure
* @speed: Unused in this implementation
* @autoneg: Unused in this implementation
* @autoneg_wait_to_complete: Unused in this implementation
*
* Do nothing and return success. VF drivers are not allowed to change
* global settings. Maintained for driver compatibility.
**/
static s32 ixgbevf_setup_mac_link_vf(struct ixgbe_hw *hw,
ixgbe_link_speed speed, bool autoneg,
bool autoneg_wait_to_complete)
{
return 0;
}
/**
* ixgbevf_check_mac_link_vf - Get link/speed status
* @hw: pointer to hardware structure
* @speed: pointer to link speed
* @link_up: true is link is up, false otherwise
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Reads the links register to determine if link is up and the current speed
**/
static s32 ixgbevf_check_mac_link_vf(struct ixgbe_hw *hw,
ixgbe_link_speed *speed,
bool *link_up,
bool autoneg_wait_to_complete)
{
u32 links_reg;
if (!(hw->mbx.ops.check_for_rst(hw))) {
*link_up = false;
*speed = 0;
return -1;
}
links_reg = IXGBE_READ_REG(hw, IXGBE_VFLINKS);
if (links_reg & IXGBE_LINKS_UP)
*link_up = true;
else
*link_up = false;
if ((links_reg & IXGBE_LINKS_SPEED_82599) ==
IXGBE_LINKS_SPEED_10G_82599)
*speed = IXGBE_LINK_SPEED_10GB_FULL;
else
*speed = IXGBE_LINK_SPEED_1GB_FULL;
return 0;
}
static const struct ixgbe_mac_operations ixgbevf_mac_ops = {
.init_hw = ixgbevf_init_hw_vf,
.reset_hw = ixgbevf_reset_hw_vf,
.start_hw = ixgbevf_start_hw_vf,
.get_mac_addr = ixgbevf_get_mac_addr_vf,
.stop_adapter = ixgbevf_stop_hw_vf,
.setup_link = ixgbevf_setup_mac_link_vf,
.check_link = ixgbevf_check_mac_link_vf,
.set_rar = ixgbevf_set_rar_vf,
.update_mc_addr_list = ixgbevf_update_mc_addr_list_vf,
.set_uc_addr = ixgbevf_set_uc_addr_vf,
.set_vfta = ixgbevf_set_vfta_vf,
};
const struct ixgbevf_info ixgbevf_82599_vf_info = {
.mac = ixgbe_mac_82599_vf,
.mac_ops = &ixgbevf_mac_ops,
};
const struct ixgbevf_info ixgbevf_X540_vf_info = {
.mac = ixgbe_mac_X540_vf,
.mac_ops = &ixgbevf_mac_ops,
};
| gpl-2.0 |
munjeni/stock_jb_kexec_kernel_for_locked_bootloader | net/ipv6/inet6_hashtables.c | 6651 | 8251 | /*
* 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.
*
* Generic INET6 transport hashtables
*
* Authors: Lotsa people, from code originally in tcp, generalised here
* by Arnaldo Carvalho de Melo <acme@mandriva.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/module.h>
#include <linux/random.h>
#include <net/inet_connection_sock.h>
#include <net/inet_hashtables.h>
#include <net/inet6_hashtables.h>
#include <net/secure_seq.h>
#include <net/ip.h>
int __inet6_hash(struct sock *sk, struct inet_timewait_sock *tw)
{
struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
int twrefcnt = 0;
WARN_ON(!sk_unhashed(sk));
if (sk->sk_state == TCP_LISTEN) {
struct inet_listen_hashbucket *ilb;
ilb = &hashinfo->listening_hash[inet_sk_listen_hashfn(sk)];
spin_lock(&ilb->lock);
__sk_nulls_add_node_rcu(sk, &ilb->head);
spin_unlock(&ilb->lock);
} else {
unsigned int hash;
struct hlist_nulls_head *list;
spinlock_t *lock;
sk->sk_hash = hash = inet6_sk_ehashfn(sk);
list = &inet_ehash_bucket(hashinfo, hash)->chain;
lock = inet_ehash_lockp(hashinfo, hash);
spin_lock(lock);
__sk_nulls_add_node_rcu(sk, list);
if (tw) {
WARN_ON(sk->sk_hash != tw->tw_hash);
twrefcnt = inet_twsk_unhash(tw);
}
spin_unlock(lock);
}
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
return twrefcnt;
}
EXPORT_SYMBOL(__inet6_hash);
/*
* Sockets in TCP_CLOSE state are _always_ taken out of the hash, so
* we need not check it for TCP lookups anymore, thanks Alexey. -DaveM
*
* The sockhash lock must be held as a reader here.
*/
struct sock *__inet6_lookup_established(struct net *net,
struct inet_hashinfo *hashinfo,
const struct in6_addr *saddr,
const __be16 sport,
const struct in6_addr *daddr,
const u16 hnum,
const int dif)
{
struct sock *sk;
const struct hlist_nulls_node *node;
const __portpair ports = INET_COMBINED_PORTS(sport, hnum);
/* Optimize here for direct hit, only listening connections can
* have wildcards anyways.
*/
unsigned int hash = inet6_ehashfn(net, daddr, hnum, saddr, sport);
unsigned int slot = hash & hashinfo->ehash_mask;
struct inet_ehash_bucket *head = &hashinfo->ehash[slot];
rcu_read_lock();
begin:
sk_nulls_for_each_rcu(sk, node, &head->chain) {
/* For IPV6 do the cheaper port and family tests first. */
if (INET6_MATCH(sk, net, hash, saddr, daddr, ports, dif)) {
if (unlikely(!atomic_inc_not_zero(&sk->sk_refcnt)))
goto begintw;
if (!INET6_MATCH(sk, net, hash, saddr, daddr, ports, dif)) {
sock_put(sk);
goto begin;
}
goto out;
}
}
if (get_nulls_value(node) != slot)
goto begin;
begintw:
/* Must check for a TIME_WAIT'er before going to listener hash. */
sk_nulls_for_each_rcu(sk, node, &head->twchain) {
if (INET6_TW_MATCH(sk, net, hash, saddr, daddr, ports, dif)) {
if (unlikely(!atomic_inc_not_zero(&sk->sk_refcnt))) {
sk = NULL;
goto out;
}
if (!INET6_TW_MATCH(sk, net, hash, saddr, daddr, ports, dif)) {
sock_put(sk);
goto begintw;
}
goto out;
}
}
if (get_nulls_value(node) != slot)
goto begintw;
sk = NULL;
out:
rcu_read_unlock();
return sk;
}
EXPORT_SYMBOL(__inet6_lookup_established);
static inline int compute_score(struct sock *sk, struct net *net,
const unsigned short hnum,
const struct in6_addr *daddr,
const int dif)
{
int score = -1;
if (net_eq(sock_net(sk), net) && inet_sk(sk)->inet_num == hnum &&
sk->sk_family == PF_INET6) {
const struct ipv6_pinfo *np = inet6_sk(sk);
score = 1;
if (!ipv6_addr_any(&np->rcv_saddr)) {
if (!ipv6_addr_equal(&np->rcv_saddr, daddr))
return -1;
score++;
}
if (sk->sk_bound_dev_if) {
if (sk->sk_bound_dev_if != dif)
return -1;
score++;
}
}
return score;
}
struct sock *inet6_lookup_listener(struct net *net,
struct inet_hashinfo *hashinfo, const struct in6_addr *daddr,
const unsigned short hnum, const int dif)
{
struct sock *sk;
const struct hlist_nulls_node *node;
struct sock *result;
int score, hiscore;
unsigned int hash = inet_lhashfn(net, hnum);
struct inet_listen_hashbucket *ilb = &hashinfo->listening_hash[hash];
rcu_read_lock();
begin:
result = NULL;
hiscore = -1;
sk_nulls_for_each(sk, node, &ilb->head) {
score = compute_score(sk, net, hnum, daddr, dif);
if (score > hiscore) {
hiscore = score;
result = sk;
}
}
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (get_nulls_value(node) != hash + LISTENING_NULLS_BASE)
goto begin;
if (result) {
if (unlikely(!atomic_inc_not_zero(&result->sk_refcnt)))
result = NULL;
else if (unlikely(compute_score(result, net, hnum, daddr,
dif) < hiscore)) {
sock_put(result);
goto begin;
}
}
rcu_read_unlock();
return result;
}
EXPORT_SYMBOL_GPL(inet6_lookup_listener);
struct sock *inet6_lookup(struct net *net, struct inet_hashinfo *hashinfo,
const struct in6_addr *saddr, const __be16 sport,
const struct in6_addr *daddr, const __be16 dport,
const int dif)
{
struct sock *sk;
local_bh_disable();
sk = __inet6_lookup(net, hashinfo, saddr, sport, daddr, ntohs(dport), dif);
local_bh_enable();
return sk;
}
EXPORT_SYMBOL_GPL(inet6_lookup);
static int __inet6_check_established(struct inet_timewait_death_row *death_row,
struct sock *sk, const __u16 lport,
struct inet_timewait_sock **twp)
{
struct inet_hashinfo *hinfo = death_row->hashinfo;
struct inet_sock *inet = inet_sk(sk);
const struct ipv6_pinfo *np = inet6_sk(sk);
const struct in6_addr *daddr = &np->rcv_saddr;
const struct in6_addr *saddr = &np->daddr;
const int dif = sk->sk_bound_dev_if;
const __portpair ports = INET_COMBINED_PORTS(inet->inet_dport, lport);
struct net *net = sock_net(sk);
const unsigned int hash = inet6_ehashfn(net, daddr, lport, saddr,
inet->inet_dport);
struct inet_ehash_bucket *head = inet_ehash_bucket(hinfo, hash);
spinlock_t *lock = inet_ehash_lockp(hinfo, hash);
struct sock *sk2;
const struct hlist_nulls_node *node;
struct inet_timewait_sock *tw;
int twrefcnt = 0;
spin_lock(lock);
/* Check TIME-WAIT sockets first. */
sk_nulls_for_each(sk2, node, &head->twchain) {
tw = inet_twsk(sk2);
if (INET6_TW_MATCH(sk2, net, hash, saddr, daddr, ports, dif)) {
if (twsk_unique(sk, sk2, twp))
goto unique;
else
goto not_unique;
}
}
tw = NULL;
/* And established part... */
sk_nulls_for_each(sk2, node, &head->chain) {
if (INET6_MATCH(sk2, net, hash, saddr, daddr, ports, dif))
goto not_unique;
}
unique:
/* Must record num and sport now. Otherwise we will see
* in hash table socket with a funny identity. */
inet->inet_num = lport;
inet->inet_sport = htons(lport);
sk->sk_hash = hash;
WARN_ON(!sk_unhashed(sk));
__sk_nulls_add_node_rcu(sk, &head->chain);
if (tw) {
twrefcnt = inet_twsk_unhash(tw);
NET_INC_STATS_BH(net, LINUX_MIB_TIMEWAITRECYCLED);
}
spin_unlock(lock);
if (twrefcnt)
inet_twsk_put(tw);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
if (twp) {
*twp = tw;
} else if (tw) {
/* Silly. Should hash-dance instead... */
inet_twsk_deschedule(tw, death_row);
inet_twsk_put(tw);
}
return 0;
not_unique:
spin_unlock(lock);
return -EADDRNOTAVAIL;
}
static inline u32 inet6_sk_port_offset(const struct sock *sk)
{
const struct inet_sock *inet = inet_sk(sk);
const struct ipv6_pinfo *np = inet6_sk(sk);
return secure_ipv6_port_ephemeral(np->rcv_saddr.s6_addr32,
np->daddr.s6_addr32,
inet->inet_dport);
}
int inet6_hash_connect(struct inet_timewait_death_row *death_row,
struct sock *sk)
{
return __inet_hash_connect(death_row, sk, inet6_sk_port_offset(sk),
__inet6_check_established, __inet6_hash);
}
EXPORT_SYMBOL_GPL(inet6_hash_connect);
| gpl-2.0 |
sinflood/w4118_hw2 | sound/pci/ac97/ac97_patch.c | 7931 | 129899 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Universal interface for Audio Codec '97
*
* For more details look to AC '97 component specification revision 2.2
* by Intel Corporation (http://developer.intel.com) and to datasheets
* for specific codecs.
*
*
* 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 "ac97_local.h"
#include "ac97_patch.h"
/*
* Forward declarations
*/
static struct snd_kcontrol *snd_ac97_find_mixer_ctl(struct snd_ac97 *ac97,
const char *name);
static int snd_ac97_add_vmaster(struct snd_ac97 *ac97, char *name,
const unsigned int *tlv, const char **slaves);
/*
* Chip specific initialization
*/
static int patch_build_controls(struct snd_ac97 * ac97, const struct snd_kcontrol_new *controls, int count)
{
int idx, err;
for (idx = 0; idx < count; idx++)
if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&controls[idx], ac97))) < 0)
return err;
return 0;
}
/* replace with a new TLV */
static void reset_tlv(struct snd_ac97 *ac97, const char *name,
const unsigned int *tlv)
{
struct snd_ctl_elem_id sid;
struct snd_kcontrol *kctl;
memset(&sid, 0, sizeof(sid));
strcpy(sid.name, name);
sid.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
kctl = snd_ctl_find_id(ac97->bus->card, &sid);
if (kctl && kctl->tlv.p)
kctl->tlv.p = tlv;
}
/* set to the page, update bits and restore the page */
static int ac97_update_bits_page(struct snd_ac97 *ac97, unsigned short reg, unsigned short mask, unsigned short value, unsigned short page)
{
unsigned short page_save;
int ret;
mutex_lock(&ac97->page_mutex);
page_save = snd_ac97_read(ac97, AC97_INT_PAGING) & AC97_PAGE_MASK;
snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, page);
ret = snd_ac97_update_bits(ac97, reg, mask, value);
snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, page_save);
mutex_unlock(&ac97->page_mutex); /* unlock paging */
return ret;
}
/*
* shared line-in/mic controls
*/
static int ac97_enum_text_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo,
const char **texts, unsigned int nums)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = nums;
if (uinfo->value.enumerated.item > nums - 1)
uinfo->value.enumerated.item = nums - 1;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int ac97_surround_jack_mode_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static const char *texts[] = { "Shared", "Independent" };
return ac97_enum_text_info(kcontrol, uinfo, texts, 2);
}
static int ac97_surround_jack_mode_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
ucontrol->value.enumerated.item[0] = ac97->indep_surround;
return 0;
}
static int ac97_surround_jack_mode_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned char indep = !!ucontrol->value.enumerated.item[0];
if (indep != ac97->indep_surround) {
ac97->indep_surround = indep;
if (ac97->build_ops->update_jacks)
ac97->build_ops->update_jacks(ac97);
return 1;
}
return 0;
}
static int ac97_channel_mode_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static const char *texts[] = { "2ch", "4ch", "6ch", "8ch" };
return ac97_enum_text_info(kcontrol, uinfo, texts,
kcontrol->private_value);
}
static int ac97_channel_mode_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
ucontrol->value.enumerated.item[0] = ac97->channel_mode;
return 0;
}
static int ac97_channel_mode_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned char mode = ucontrol->value.enumerated.item[0];
if (mode >= kcontrol->private_value)
return -EINVAL;
if (mode != ac97->channel_mode) {
ac97->channel_mode = mode;
if (ac97->build_ops->update_jacks)
ac97->build_ops->update_jacks(ac97);
return 1;
}
return 0;
}
#define AC97_SURROUND_JACK_MODE_CTL \
{ \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = "Surround Jack Mode", \
.info = ac97_surround_jack_mode_info, \
.get = ac97_surround_jack_mode_get, \
.put = ac97_surround_jack_mode_put, \
}
/* 6ch */
#define AC97_CHANNEL_MODE_CTL \
{ \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = "Channel Mode", \
.info = ac97_channel_mode_info, \
.get = ac97_channel_mode_get, \
.put = ac97_channel_mode_put, \
.private_value = 3, \
}
/* 4ch */
#define AC97_CHANNEL_MODE_4CH_CTL \
{ \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = "Channel Mode", \
.info = ac97_channel_mode_info, \
.get = ac97_channel_mode_get, \
.put = ac97_channel_mode_put, \
.private_value = 2, \
}
/* 8ch */
#define AC97_CHANNEL_MODE_8CH_CTL \
{ \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = "Channel Mode", \
.info = ac97_channel_mode_info, \
.get = ac97_channel_mode_get, \
.put = ac97_channel_mode_put, \
.private_value = 4, \
}
static inline int is_surround_on(struct snd_ac97 *ac97)
{
return ac97->channel_mode >= 1;
}
static inline int is_clfe_on(struct snd_ac97 *ac97)
{
return ac97->channel_mode >= 2;
}
/* system has shared jacks with surround out enabled */
static inline int is_shared_surrout(struct snd_ac97 *ac97)
{
return !ac97->indep_surround && is_surround_on(ac97);
}
/* system has shared jacks with center/lfe out enabled */
static inline int is_shared_clfeout(struct snd_ac97 *ac97)
{
return !ac97->indep_surround && is_clfe_on(ac97);
}
/* system has shared jacks with line in enabled */
static inline int is_shared_linein(struct snd_ac97 *ac97)
{
return !ac97->indep_surround && !is_surround_on(ac97);
}
/* system has shared jacks with mic in enabled */
static inline int is_shared_micin(struct snd_ac97 *ac97)
{
return !ac97->indep_surround && !is_clfe_on(ac97);
}
static inline int alc850_is_aux_back_surround(struct snd_ac97 *ac97)
{
return is_surround_on(ac97);
}
/* The following snd_ac97_ymf753_... items added by David Shust (dshust@shustring.com) */
/* Modified for YMF743 by Keita Maehara <maehara@debian.org> */
/* It is possible to indicate to the Yamaha YMF7x3 the type of
speakers being used. */
static int snd_ac97_ymf7x3_info_speaker(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static char *texts[3] = {
"Standard", "Small", "Smaller"
};
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 3;
if (uinfo->value.enumerated.item > 2)
uinfo->value.enumerated.item = 2;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_ymf7x3_get_speaker(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_YMF7X3_3D_MODE_SEL];
val = (val >> 10) & 3;
if (val > 0) /* 0 = invalid */
val--;
ucontrol->value.enumerated.item[0] = val;
return 0;
}
static int snd_ac97_ymf7x3_put_speaker(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
if (ucontrol->value.enumerated.item[0] > 2)
return -EINVAL;
val = (ucontrol->value.enumerated.item[0] + 1) << 10;
return snd_ac97_update(ac97, AC97_YMF7X3_3D_MODE_SEL, val);
}
static const struct snd_kcontrol_new snd_ac97_ymf7x3_controls_speaker =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "3D Control - Speaker",
.info = snd_ac97_ymf7x3_info_speaker,
.get = snd_ac97_ymf7x3_get_speaker,
.put = snd_ac97_ymf7x3_put_speaker,
};
/* It is possible to indicate to the Yamaha YMF7x3 the source to
direct to the S/PDIF output. */
static int snd_ac97_ymf7x3_spdif_source_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static char *texts[2] = { "AC-Link", "A/D Converter" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item > 1)
uinfo->value.enumerated.item = 1;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_ymf7x3_spdif_source_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_YMF7X3_DIT_CTRL];
ucontrol->value.enumerated.item[0] = (val >> 1) & 1;
return 0;
}
static int snd_ac97_ymf7x3_spdif_source_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
if (ucontrol->value.enumerated.item[0] > 1)
return -EINVAL;
val = ucontrol->value.enumerated.item[0] << 1;
return snd_ac97_update_bits(ac97, AC97_YMF7X3_DIT_CTRL, 0x0002, val);
}
static int patch_yamaha_ymf7x3_3d(struct snd_ac97 *ac97)
{
struct snd_kcontrol *kctl;
int err;
kctl = snd_ac97_cnew(&snd_ac97_controls_3d[0], ac97);
err = snd_ctl_add(ac97->bus->card, kctl);
if (err < 0)
return err;
strcpy(kctl->id.name, "3D Control - Wide");
kctl->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 9, 7, 0);
snd_ac97_write_cache(ac97, AC97_3D_CONTROL, 0x0000);
err = snd_ctl_add(ac97->bus->card,
snd_ac97_cnew(&snd_ac97_ymf7x3_controls_speaker,
ac97));
if (err < 0)
return err;
snd_ac97_write_cache(ac97, AC97_YMF7X3_3D_MODE_SEL, 0x0c00);
return 0;
}
static const struct snd_kcontrol_new snd_ac97_yamaha_ymf743_controls_spdif[3] =
{
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("", PLAYBACK, SWITCH),
AC97_YMF7X3_DIT_CTRL, 0, 1, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, NONE) "Source",
.info = snd_ac97_ymf7x3_spdif_source_info,
.get = snd_ac97_ymf7x3_spdif_source_get,
.put = snd_ac97_ymf7x3_spdif_source_put,
},
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("", NONE, NONE) "Mute",
AC97_YMF7X3_DIT_CTRL, 2, 1, 1)
};
static int patch_yamaha_ymf743_build_spdif(struct snd_ac97 *ac97)
{
int err;
err = patch_build_controls(ac97, &snd_ac97_controls_spdif[0], 3);
if (err < 0)
return err;
err = patch_build_controls(ac97,
snd_ac97_yamaha_ymf743_controls_spdif, 3);
if (err < 0)
return err;
/* set default PCM S/PDIF params */
/* PCM audio,no copyright,no preemphasis,PCM coder,original */
snd_ac97_write_cache(ac97, AC97_YMF7X3_DIT_CTRL, 0xa201);
return 0;
}
static const struct snd_ac97_build_ops patch_yamaha_ymf743_ops = {
.build_spdif = patch_yamaha_ymf743_build_spdif,
.build_3d = patch_yamaha_ymf7x3_3d,
};
static int patch_yamaha_ymf743(struct snd_ac97 *ac97)
{
ac97->build_ops = &patch_yamaha_ymf743_ops;
ac97->caps |= AC97_BC_BASS_TREBLE;
ac97->caps |= 0x04 << 10; /* Yamaha 3D enhancement */
ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */
ac97->ext_id |= AC97_EI_SPDIF; /* force the detection of spdif */
return 0;
}
/* The AC'97 spec states that the S/PDIF signal is to be output at pin 48.
The YMF753 will output the S/PDIF signal to pin 43, 47 (EAPD), or 48.
By default, no output pin is selected, and the S/PDIF signal is not output.
There is also a bit to mute S/PDIF output in a vendor-specific register. */
static int snd_ac97_ymf753_spdif_output_pin_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[3] = { "Disabled", "Pin 43", "Pin 48" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 3;
if (uinfo->value.enumerated.item > 2)
uinfo->value.enumerated.item = 2;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_ymf753_spdif_output_pin_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_YMF7X3_DIT_CTRL];
ucontrol->value.enumerated.item[0] = (val & 0x0008) ? 2 : (val & 0x0020) ? 1 : 0;
return 0;
}
static int snd_ac97_ymf753_spdif_output_pin_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
if (ucontrol->value.enumerated.item[0] > 2)
return -EINVAL;
val = (ucontrol->value.enumerated.item[0] == 2) ? 0x0008 :
(ucontrol->value.enumerated.item[0] == 1) ? 0x0020 : 0;
return snd_ac97_update_bits(ac97, AC97_YMF7X3_DIT_CTRL, 0x0028, val);
/* The following can be used to direct S/PDIF output to pin 47 (EAPD).
snd_ac97_write_cache(ac97, 0x62, snd_ac97_read(ac97, 0x62) | 0x0008); */
}
static const struct snd_kcontrol_new snd_ac97_ymf753_controls_spdif[3] = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
.info = snd_ac97_ymf7x3_spdif_source_info,
.get = snd_ac97_ymf7x3_spdif_source_get,
.put = snd_ac97_ymf7x3_spdif_source_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Output Pin",
.info = snd_ac97_ymf753_spdif_output_pin_info,
.get = snd_ac97_ymf753_spdif_output_pin_get,
.put = snd_ac97_ymf753_spdif_output_pin_put,
},
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("", NONE, NONE) "Mute",
AC97_YMF7X3_DIT_CTRL, 2, 1, 1)
};
static int patch_yamaha_ymf753_post_spdif(struct snd_ac97 * ac97)
{
int err;
if ((err = patch_build_controls(ac97, snd_ac97_ymf753_controls_spdif, ARRAY_SIZE(snd_ac97_ymf753_controls_spdif))) < 0)
return err;
return 0;
}
static const struct snd_ac97_build_ops patch_yamaha_ymf753_ops = {
.build_3d = patch_yamaha_ymf7x3_3d,
.build_post_spdif = patch_yamaha_ymf753_post_spdif
};
static int patch_yamaha_ymf753(struct snd_ac97 * ac97)
{
/* Patch for Yamaha YMF753, Copyright (c) by David Shust, dshust@shustring.com.
This chip has nonstandard and extended behaviour with regard to its S/PDIF output.
The AC'97 spec states that the S/PDIF signal is to be output at pin 48.
The YMF753 will ouput the S/PDIF signal to pin 43, 47 (EAPD), or 48.
By default, no output pin is selected, and the S/PDIF signal is not output.
There is also a bit to mute S/PDIF output in a vendor-specific register.
*/
ac97->build_ops = &patch_yamaha_ymf753_ops;
ac97->caps |= AC97_BC_BASS_TREBLE;
ac97->caps |= 0x04 << 10; /* Yamaha 3D enhancement */
return 0;
}
/*
* May 2, 2003 Liam Girdwood <lrg@slimlogic.co.uk>
* removed broken wolfson00 patch.
* added support for WM9705,WM9708,WM9709,WM9710,WM9711,WM9712 and WM9717.
*/
static const struct snd_kcontrol_new wm97xx_snd_ac97_controls[] = {
AC97_DOUBLE("Front Playback Volume", AC97_WM97XX_FMIXER_VOL, 8, 0, 31, 1),
AC97_SINGLE("Front Playback Switch", AC97_WM97XX_FMIXER_VOL, 15, 1, 1),
};
static int patch_wolfson_wm9703_specific(struct snd_ac97 * ac97)
{
/* This is known to work for the ViewSonic ViewPad 1000
* Randolph Bentson <bentson@holmsjoen.com>
* WM9703/9707/9708/9717
*/
int err, i;
for (i = 0; i < ARRAY_SIZE(wm97xx_snd_ac97_controls); i++) {
if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm97xx_snd_ac97_controls[i], ac97))) < 0)
return err;
}
snd_ac97_write_cache(ac97, AC97_WM97XX_FMIXER_VOL, 0x0808);
return 0;
}
static const struct snd_ac97_build_ops patch_wolfson_wm9703_ops = {
.build_specific = patch_wolfson_wm9703_specific,
};
static int patch_wolfson03(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_wolfson_wm9703_ops;
return 0;
}
static const struct snd_kcontrol_new wm9704_snd_ac97_controls[] = {
AC97_DOUBLE("Front Playback Volume", AC97_WM97XX_FMIXER_VOL, 8, 0, 31, 1),
AC97_SINGLE("Front Playback Switch", AC97_WM97XX_FMIXER_VOL, 15, 1, 1),
AC97_DOUBLE("Rear Playback Volume", AC97_WM9704_RMIXER_VOL, 8, 0, 31, 1),
AC97_SINGLE("Rear Playback Switch", AC97_WM9704_RMIXER_VOL, 15, 1, 1),
AC97_DOUBLE("Rear DAC Volume", AC97_WM9704_RPCM_VOL, 8, 0, 31, 1),
AC97_DOUBLE("Surround Volume", AC97_SURROUND_MASTER, 8, 0, 31, 1),
};
static int patch_wolfson_wm9704_specific(struct snd_ac97 * ac97)
{
int err, i;
for (i = 0; i < ARRAY_SIZE(wm9704_snd_ac97_controls); i++) {
if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm9704_snd_ac97_controls[i], ac97))) < 0)
return err;
}
/* patch for DVD noise */
snd_ac97_write_cache(ac97, AC97_WM9704_TEST, 0x0200);
return 0;
}
static const struct snd_ac97_build_ops patch_wolfson_wm9704_ops = {
.build_specific = patch_wolfson_wm9704_specific,
};
static int patch_wolfson04(struct snd_ac97 * ac97)
{
/* WM9704M/9704Q */
ac97->build_ops = &patch_wolfson_wm9704_ops;
return 0;
}
static int patch_wolfson05(struct snd_ac97 * ac97)
{
/* WM9705, WM9710 */
ac97->build_ops = &patch_wolfson_wm9703_ops;
#ifdef CONFIG_TOUCHSCREEN_WM9705
/* WM9705 touchscreen uses AUX and VIDEO for touch */
ac97->flags |= AC97_HAS_NO_VIDEO | AC97_HAS_NO_AUX;
#endif
return 0;
}
static const char* wm9711_alc_select[] = {"None", "Left", "Right", "Stereo"};
static const char* wm9711_alc_mix[] = {"Stereo", "Right", "Left", "None"};
static const char* wm9711_out3_src[] = {"Left", "VREF", "Left + Right", "Mono"};
static const char* wm9711_out3_lrsrc[] = {"Master Mix", "Headphone Mix"};
static const char* wm9711_rec_adc[] = {"Stereo", "Left", "Right", "Mute"};
static const char* wm9711_base[] = {"Linear Control", "Adaptive Boost"};
static const char* wm9711_rec_gain[] = {"+1.5dB Steps", "+0.75dB Steps"};
static const char* wm9711_mic[] = {"Mic 1", "Differential", "Mic 2", "Stereo"};
static const char* wm9711_rec_sel[] =
{"Mic 1", "NC", "NC", "Master Mix", "Line", "Headphone Mix", "Phone Mix", "Phone"};
static const char* wm9711_ng_type[] = {"Constant Gain", "Mute"};
static const struct ac97_enum wm9711_enum[] = {
AC97_ENUM_SINGLE(AC97_PCI_SVID, 14, 4, wm9711_alc_select),
AC97_ENUM_SINGLE(AC97_VIDEO, 10, 4, wm9711_alc_mix),
AC97_ENUM_SINGLE(AC97_AUX, 9, 4, wm9711_out3_src),
AC97_ENUM_SINGLE(AC97_AUX, 8, 2, wm9711_out3_lrsrc),
AC97_ENUM_SINGLE(AC97_REC_SEL, 12, 4, wm9711_rec_adc),
AC97_ENUM_SINGLE(AC97_MASTER_TONE, 15, 2, wm9711_base),
AC97_ENUM_DOUBLE(AC97_REC_GAIN, 14, 6, 2, wm9711_rec_gain),
AC97_ENUM_SINGLE(AC97_MIC, 5, 4, wm9711_mic),
AC97_ENUM_DOUBLE(AC97_REC_SEL, 8, 0, 8, wm9711_rec_sel),
AC97_ENUM_SINGLE(AC97_PCI_SVID, 5, 2, wm9711_ng_type),
};
static const struct snd_kcontrol_new wm9711_snd_ac97_controls[] = {
AC97_SINGLE("ALC Target Volume", AC97_CODEC_CLASS_REV, 12, 15, 0),
AC97_SINGLE("ALC Hold Time", AC97_CODEC_CLASS_REV, 8, 15, 0),
AC97_SINGLE("ALC Decay Time", AC97_CODEC_CLASS_REV, 4, 15, 0),
AC97_SINGLE("ALC Attack Time", AC97_CODEC_CLASS_REV, 0, 15, 0),
AC97_ENUM("ALC Function", wm9711_enum[0]),
AC97_SINGLE("ALC Max Volume", AC97_PCI_SVID, 11, 7, 1),
AC97_SINGLE("ALC ZC Timeout", AC97_PCI_SVID, 9, 3, 1),
AC97_SINGLE("ALC ZC Switch", AC97_PCI_SVID, 8, 1, 0),
AC97_SINGLE("ALC NG Switch", AC97_PCI_SVID, 7, 1, 0),
AC97_ENUM("ALC NG Type", wm9711_enum[9]),
AC97_SINGLE("ALC NG Threshold", AC97_PCI_SVID, 0, 31, 1),
AC97_SINGLE("Side Tone Switch", AC97_VIDEO, 15, 1, 1),
AC97_SINGLE("Side Tone Volume", AC97_VIDEO, 12, 7, 1),
AC97_ENUM("ALC Headphone Mux", wm9711_enum[1]),
AC97_SINGLE("ALC Headphone Volume", AC97_VIDEO, 7, 7, 1),
AC97_SINGLE("Out3 Switch", AC97_AUX, 15, 1, 1),
AC97_SINGLE("Out3 ZC Switch", AC97_AUX, 7, 1, 0),
AC97_ENUM("Out3 Mux", wm9711_enum[2]),
AC97_ENUM("Out3 LR Mux", wm9711_enum[3]),
AC97_SINGLE("Out3 Volume", AC97_AUX, 0, 31, 1),
AC97_SINGLE("Beep to Headphone Switch", AC97_PC_BEEP, 15, 1, 1),
AC97_SINGLE("Beep to Headphone Volume", AC97_PC_BEEP, 12, 7, 1),
AC97_SINGLE("Beep to Side Tone Switch", AC97_PC_BEEP, 11, 1, 1),
AC97_SINGLE("Beep to Side Tone Volume", AC97_PC_BEEP, 8, 7, 1),
AC97_SINGLE("Beep to Phone Switch", AC97_PC_BEEP, 7, 1, 1),
AC97_SINGLE("Beep to Phone Volume", AC97_PC_BEEP, 4, 7, 1),
AC97_SINGLE("Aux to Headphone Switch", AC97_CD, 15, 1, 1),
AC97_SINGLE("Aux to Headphone Volume", AC97_CD, 12, 7, 1),
AC97_SINGLE("Aux to Side Tone Switch", AC97_CD, 11, 1, 1),
AC97_SINGLE("Aux to Side Tone Volume", AC97_CD, 8, 7, 1),
AC97_SINGLE("Aux to Phone Switch", AC97_CD, 7, 1, 1),
AC97_SINGLE("Aux to Phone Volume", AC97_CD, 4, 7, 1),
AC97_SINGLE("Phone to Headphone Switch", AC97_PHONE, 15, 1, 1),
AC97_SINGLE("Phone to Master Switch", AC97_PHONE, 14, 1, 1),
AC97_SINGLE("Line to Headphone Switch", AC97_LINE, 15, 1, 1),
AC97_SINGLE("Line to Master Switch", AC97_LINE, 14, 1, 1),
AC97_SINGLE("Line to Phone Switch", AC97_LINE, 13, 1, 1),
AC97_SINGLE("PCM Playback to Headphone Switch", AC97_PCM, 15, 1, 1),
AC97_SINGLE("PCM Playback to Master Switch", AC97_PCM, 14, 1, 1),
AC97_SINGLE("PCM Playback to Phone Switch", AC97_PCM, 13, 1, 1),
AC97_SINGLE("Capture 20dB Boost Switch", AC97_REC_SEL, 14, 1, 0),
AC97_ENUM("Capture to Phone Mux", wm9711_enum[4]),
AC97_SINGLE("Capture to Phone 20dB Boost Switch", AC97_REC_SEL, 11, 1, 1),
AC97_ENUM("Capture Select", wm9711_enum[8]),
AC97_SINGLE("3D Upper Cut-off Switch", AC97_3D_CONTROL, 5, 1, 1),
AC97_SINGLE("3D Lower Cut-off Switch", AC97_3D_CONTROL, 4, 1, 1),
AC97_ENUM("Bass Control", wm9711_enum[5]),
AC97_SINGLE("Bass Cut-off Switch", AC97_MASTER_TONE, 12, 1, 1),
AC97_SINGLE("Tone Cut-off Switch", AC97_MASTER_TONE, 4, 1, 1),
AC97_SINGLE("Playback Attenuate (-6dB) Switch", AC97_MASTER_TONE, 6, 1, 0),
AC97_SINGLE("ADC Switch", AC97_REC_GAIN, 15, 1, 1),
AC97_ENUM("Capture Volume Steps", wm9711_enum[6]),
AC97_DOUBLE("Capture Volume", AC97_REC_GAIN, 8, 0, 63, 1),
AC97_SINGLE("Capture ZC Switch", AC97_REC_GAIN, 7, 1, 0),
AC97_SINGLE("Mic 1 to Phone Switch", AC97_MIC, 14, 1, 1),
AC97_SINGLE("Mic 2 to Phone Switch", AC97_MIC, 13, 1, 1),
AC97_ENUM("Mic Select Source", wm9711_enum[7]),
AC97_SINGLE("Mic 1 Volume", AC97_MIC, 8, 31, 1),
AC97_SINGLE("Mic 2 Volume", AC97_MIC, 0, 31, 1),
AC97_SINGLE("Mic 20dB Boost Switch", AC97_MIC, 7, 1, 0),
AC97_SINGLE("Master Left Inv Switch", AC97_MASTER, 6, 1, 0),
AC97_SINGLE("Master ZC Switch", AC97_MASTER, 7, 1, 0),
AC97_SINGLE("Headphone ZC Switch", AC97_HEADPHONE, 7, 1, 0),
AC97_SINGLE("Mono ZC Switch", AC97_MASTER_MONO, 7, 1, 0),
};
static int patch_wolfson_wm9711_specific(struct snd_ac97 * ac97)
{
int err, i;
for (i = 0; i < ARRAY_SIZE(wm9711_snd_ac97_controls); i++) {
if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm9711_snd_ac97_controls[i], ac97))) < 0)
return err;
}
snd_ac97_write_cache(ac97, AC97_CODEC_CLASS_REV, 0x0808);
snd_ac97_write_cache(ac97, AC97_PCI_SVID, 0x0808);
snd_ac97_write_cache(ac97, AC97_VIDEO, 0x0808);
snd_ac97_write_cache(ac97, AC97_AUX, 0x0808);
snd_ac97_write_cache(ac97, AC97_PC_BEEP, 0x0808);
snd_ac97_write_cache(ac97, AC97_CD, 0x0000);
return 0;
}
static const struct snd_ac97_build_ops patch_wolfson_wm9711_ops = {
.build_specific = patch_wolfson_wm9711_specific,
};
static int patch_wolfson11(struct snd_ac97 * ac97)
{
/* WM9711, WM9712 */
ac97->build_ops = &patch_wolfson_wm9711_ops;
ac97->flags |= AC97_HAS_NO_REC_GAIN | AC97_STEREO_MUTES | AC97_HAS_NO_MIC |
AC97_HAS_NO_PC_BEEP | AC97_HAS_NO_VIDEO | AC97_HAS_NO_CD;
return 0;
}
static const char* wm9713_mic_mixer[] = {"Stereo", "Mic 1", "Mic 2", "Mute"};
static const char* wm9713_rec_mux[] = {"Stereo", "Left", "Right", "Mute"};
static const char* wm9713_rec_src[] =
{"Mic 1", "Mic 2", "Line", "Mono In", "Headphone Mix", "Master Mix",
"Mono Mix", "Zh"};
static const char* wm9713_rec_gain[] = {"+1.5dB Steps", "+0.75dB Steps"};
static const char* wm9713_alc_select[] = {"None", "Left", "Right", "Stereo"};
static const char* wm9713_mono_pga[] = {"Vmid", "Zh", "Mono Mix", "Inv 1"};
static const char* wm9713_spk_pga[] =
{"Vmid", "Zh", "Headphone Mix", "Master Mix", "Inv", "NC", "NC", "NC"};
static const char* wm9713_hp_pga[] = {"Vmid", "Zh", "Headphone Mix", "NC"};
static const char* wm9713_out3_pga[] = {"Vmid", "Zh", "Inv 1", "NC"};
static const char* wm9713_out4_pga[] = {"Vmid", "Zh", "Inv 2", "NC"};
static const char* wm9713_dac_inv[] =
{"Off", "Mono Mix", "Master Mix", "Headphone Mix L", "Headphone Mix R",
"Headphone Mix Mono", "NC", "Vmid"};
static const char* wm9713_base[] = {"Linear Control", "Adaptive Boost"};
static const char* wm9713_ng_type[] = {"Constant Gain", "Mute"};
static const struct ac97_enum wm9713_enum[] = {
AC97_ENUM_SINGLE(AC97_LINE, 3, 4, wm9713_mic_mixer),
AC97_ENUM_SINGLE(AC97_VIDEO, 14, 4, wm9713_rec_mux),
AC97_ENUM_SINGLE(AC97_VIDEO, 9, 4, wm9713_rec_mux),
AC97_ENUM_DOUBLE(AC97_VIDEO, 3, 0, 8, wm9713_rec_src),
AC97_ENUM_DOUBLE(AC97_CD, 14, 6, 2, wm9713_rec_gain),
AC97_ENUM_SINGLE(AC97_PCI_SVID, 14, 4, wm9713_alc_select),
AC97_ENUM_SINGLE(AC97_REC_GAIN, 14, 4, wm9713_mono_pga),
AC97_ENUM_DOUBLE(AC97_REC_GAIN, 11, 8, 8, wm9713_spk_pga),
AC97_ENUM_DOUBLE(AC97_REC_GAIN, 6, 4, 4, wm9713_hp_pga),
AC97_ENUM_SINGLE(AC97_REC_GAIN, 2, 4, wm9713_out3_pga),
AC97_ENUM_SINGLE(AC97_REC_GAIN, 0, 4, wm9713_out4_pga),
AC97_ENUM_DOUBLE(AC97_REC_GAIN_MIC, 13, 10, 8, wm9713_dac_inv),
AC97_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 15, 2, wm9713_base),
AC97_ENUM_SINGLE(AC97_PCI_SVID, 5, 2, wm9713_ng_type),
};
static const struct snd_kcontrol_new wm13_snd_ac97_controls[] = {
AC97_DOUBLE("Line In Volume", AC97_PC_BEEP, 8, 0, 31, 1),
AC97_SINGLE("Line In to Headphone Switch", AC97_PC_BEEP, 15, 1, 1),
AC97_SINGLE("Line In to Master Switch", AC97_PC_BEEP, 14, 1, 1),
AC97_SINGLE("Line In to Mono Switch", AC97_PC_BEEP, 13, 1, 1),
AC97_DOUBLE("PCM Playback Volume", AC97_PHONE, 8, 0, 31, 1),
AC97_SINGLE("PCM Playback to Headphone Switch", AC97_PHONE, 15, 1, 1),
AC97_SINGLE("PCM Playback to Master Switch", AC97_PHONE, 14, 1, 1),
AC97_SINGLE("PCM Playback to Mono Switch", AC97_PHONE, 13, 1, 1),
AC97_SINGLE("Mic 1 Volume", AC97_MIC, 8, 31, 1),
AC97_SINGLE("Mic 2 Volume", AC97_MIC, 0, 31, 1),
AC97_SINGLE("Mic 1 to Mono Switch", AC97_LINE, 7, 1, 1),
AC97_SINGLE("Mic 2 to Mono Switch", AC97_LINE, 6, 1, 1),
AC97_SINGLE("Mic Boost (+20dB) Switch", AC97_LINE, 5, 1, 0),
AC97_ENUM("Mic to Headphone Mux", wm9713_enum[0]),
AC97_SINGLE("Mic Headphone Mixer Volume", AC97_LINE, 0, 7, 1),
AC97_SINGLE("Capture Switch", AC97_CD, 15, 1, 1),
AC97_ENUM("Capture Volume Steps", wm9713_enum[4]),
AC97_DOUBLE("Capture Volume", AC97_CD, 8, 0, 15, 0),
AC97_SINGLE("Capture ZC Switch", AC97_CD, 7, 1, 0),
AC97_ENUM("Capture to Headphone Mux", wm9713_enum[1]),
AC97_SINGLE("Capture to Headphone Volume", AC97_VIDEO, 11, 7, 1),
AC97_ENUM("Capture to Mono Mux", wm9713_enum[2]),
AC97_SINGLE("Capture to Mono Boost (+20dB) Switch", AC97_VIDEO, 8, 1, 0),
AC97_SINGLE("Capture ADC Boost (+20dB) Switch", AC97_VIDEO, 6, 1, 0),
AC97_ENUM("Capture Select", wm9713_enum[3]),
AC97_SINGLE("ALC Target Volume", AC97_CODEC_CLASS_REV, 12, 15, 0),
AC97_SINGLE("ALC Hold Time", AC97_CODEC_CLASS_REV, 8, 15, 0),
AC97_SINGLE("ALC Decay Time ", AC97_CODEC_CLASS_REV, 4, 15, 0),
AC97_SINGLE("ALC Attack Time", AC97_CODEC_CLASS_REV, 0, 15, 0),
AC97_ENUM("ALC Function", wm9713_enum[5]),
AC97_SINGLE("ALC Max Volume", AC97_PCI_SVID, 11, 7, 0),
AC97_SINGLE("ALC ZC Timeout", AC97_PCI_SVID, 9, 3, 0),
AC97_SINGLE("ALC ZC Switch", AC97_PCI_SVID, 8, 1, 0),
AC97_SINGLE("ALC NG Switch", AC97_PCI_SVID, 7, 1, 0),
AC97_ENUM("ALC NG Type", wm9713_enum[13]),
AC97_SINGLE("ALC NG Threshold", AC97_PCI_SVID, 0, 31, 0),
AC97_DOUBLE("Master ZC Switch", AC97_MASTER, 14, 6, 1, 0),
AC97_DOUBLE("Headphone ZC Switch", AC97_HEADPHONE, 14, 6, 1, 0),
AC97_DOUBLE("Out3/4 ZC Switch", AC97_MASTER_MONO, 14, 6, 1, 0),
AC97_SINGLE("Master Right Switch", AC97_MASTER, 7, 1, 1),
AC97_SINGLE("Headphone Right Switch", AC97_HEADPHONE, 7, 1, 1),
AC97_SINGLE("Out3/4 Right Switch", AC97_MASTER_MONO, 7, 1, 1),
AC97_SINGLE("Mono In to Headphone Switch", AC97_MASTER_TONE, 15, 1, 1),
AC97_SINGLE("Mono In to Master Switch", AC97_MASTER_TONE, 14, 1, 1),
AC97_SINGLE("Mono In Volume", AC97_MASTER_TONE, 8, 31, 1),
AC97_SINGLE("Mono Switch", AC97_MASTER_TONE, 7, 1, 1),
AC97_SINGLE("Mono ZC Switch", AC97_MASTER_TONE, 6, 1, 0),
AC97_SINGLE("Mono Volume", AC97_MASTER_TONE, 0, 31, 1),
AC97_SINGLE("Beep to Headphone Switch", AC97_AUX, 15, 1, 1),
AC97_SINGLE("Beep to Headphone Volume", AC97_AUX, 12, 7, 1),
AC97_SINGLE("Beep to Master Switch", AC97_AUX, 11, 1, 1),
AC97_SINGLE("Beep to Master Volume", AC97_AUX, 8, 7, 1),
AC97_SINGLE("Beep to Mono Switch", AC97_AUX, 7, 1, 1),
AC97_SINGLE("Beep to Mono Volume", AC97_AUX, 4, 7, 1),
AC97_SINGLE("Voice to Headphone Switch", AC97_PCM, 15, 1, 1),
AC97_SINGLE("Voice to Headphone Volume", AC97_PCM, 12, 7, 1),
AC97_SINGLE("Voice to Master Switch", AC97_PCM, 11, 1, 1),
AC97_SINGLE("Voice to Master Volume", AC97_PCM, 8, 7, 1),
AC97_SINGLE("Voice to Mono Switch", AC97_PCM, 7, 1, 1),
AC97_SINGLE("Voice to Mono Volume", AC97_PCM, 4, 7, 1),
AC97_SINGLE("Aux to Headphone Switch", AC97_REC_SEL, 15, 1, 1),
AC97_SINGLE("Aux to Headphone Volume", AC97_REC_SEL, 12, 7, 1),
AC97_SINGLE("Aux to Master Switch", AC97_REC_SEL, 11, 1, 1),
AC97_SINGLE("Aux to Master Volume", AC97_REC_SEL, 8, 7, 1),
AC97_SINGLE("Aux to Mono Switch", AC97_REC_SEL, 7, 1, 1),
AC97_SINGLE("Aux to Mono Volume", AC97_REC_SEL, 4, 7, 1),
AC97_ENUM("Mono Input Mux", wm9713_enum[6]),
AC97_ENUM("Master Input Mux", wm9713_enum[7]),
AC97_ENUM("Headphone Input Mux", wm9713_enum[8]),
AC97_ENUM("Out 3 Input Mux", wm9713_enum[9]),
AC97_ENUM("Out 4 Input Mux", wm9713_enum[10]),
AC97_ENUM("Bass Control", wm9713_enum[12]),
AC97_SINGLE("Bass Cut-off Switch", AC97_GENERAL_PURPOSE, 12, 1, 1),
AC97_SINGLE("Tone Cut-off Switch", AC97_GENERAL_PURPOSE, 4, 1, 1),
AC97_SINGLE("Playback Attenuate (-6dB) Switch", AC97_GENERAL_PURPOSE, 6, 1, 0),
AC97_SINGLE("Bass Volume", AC97_GENERAL_PURPOSE, 8, 15, 1),
AC97_SINGLE("Tone Volume", AC97_GENERAL_PURPOSE, 0, 15, 1),
};
static const struct snd_kcontrol_new wm13_snd_ac97_controls_3d[] = {
AC97_ENUM("Inv Input Mux", wm9713_enum[11]),
AC97_SINGLE("3D Upper Cut-off Switch", AC97_REC_GAIN_MIC, 5, 1, 0),
AC97_SINGLE("3D Lower Cut-off Switch", AC97_REC_GAIN_MIC, 4, 1, 0),
AC97_SINGLE("3D Depth", AC97_REC_GAIN_MIC, 0, 15, 1),
};
static int patch_wolfson_wm9713_3d (struct snd_ac97 * ac97)
{
int err, i;
for (i = 0; i < ARRAY_SIZE(wm13_snd_ac97_controls_3d); i++) {
if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm13_snd_ac97_controls_3d[i], ac97))) < 0)
return err;
}
return 0;
}
static int patch_wolfson_wm9713_specific(struct snd_ac97 * ac97)
{
int err, i;
for (i = 0; i < ARRAY_SIZE(wm13_snd_ac97_controls); i++) {
if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm13_snd_ac97_controls[i], ac97))) < 0)
return err;
}
snd_ac97_write_cache(ac97, AC97_PC_BEEP, 0x0808);
snd_ac97_write_cache(ac97, AC97_PHONE, 0x0808);
snd_ac97_write_cache(ac97, AC97_MIC, 0x0808);
snd_ac97_write_cache(ac97, AC97_LINE, 0x00da);
snd_ac97_write_cache(ac97, AC97_CD, 0x0808);
snd_ac97_write_cache(ac97, AC97_VIDEO, 0xd612);
snd_ac97_write_cache(ac97, AC97_REC_GAIN, 0x1ba0);
return 0;
}
#ifdef CONFIG_PM
static void patch_wolfson_wm9713_suspend (struct snd_ac97 * ac97)
{
snd_ac97_write_cache(ac97, AC97_EXTENDED_MID, 0xfeff);
snd_ac97_write_cache(ac97, AC97_EXTENDED_MSTATUS, 0xffff);
}
static void patch_wolfson_wm9713_resume (struct snd_ac97 * ac97)
{
snd_ac97_write_cache(ac97, AC97_EXTENDED_MID, 0xda00);
snd_ac97_write_cache(ac97, AC97_EXTENDED_MSTATUS, 0x3810);
snd_ac97_write_cache(ac97, AC97_POWERDOWN, 0x0);
}
#endif
static const struct snd_ac97_build_ops patch_wolfson_wm9713_ops = {
.build_specific = patch_wolfson_wm9713_specific,
.build_3d = patch_wolfson_wm9713_3d,
#ifdef CONFIG_PM
.suspend = patch_wolfson_wm9713_suspend,
.resume = patch_wolfson_wm9713_resume
#endif
};
static int patch_wolfson13(struct snd_ac97 * ac97)
{
/* WM9713, WM9714 */
ac97->build_ops = &patch_wolfson_wm9713_ops;
ac97->flags |= AC97_HAS_NO_REC_GAIN | AC97_STEREO_MUTES | AC97_HAS_NO_PHONE |
AC97_HAS_NO_PC_BEEP | AC97_HAS_NO_VIDEO | AC97_HAS_NO_CD | AC97_HAS_NO_TONE |
AC97_HAS_NO_STD_PCM;
ac97->scaps &= ~AC97_SCAP_MODEM;
snd_ac97_write_cache(ac97, AC97_EXTENDED_MID, 0xda00);
snd_ac97_write_cache(ac97, AC97_EXTENDED_MSTATUS, 0x3810);
snd_ac97_write_cache(ac97, AC97_POWERDOWN, 0x0);
return 0;
}
/*
* Tritech codec
*/
static int patch_tritech_tr28028(struct snd_ac97 * ac97)
{
snd_ac97_write_cache(ac97, 0x26, 0x0300);
snd_ac97_write_cache(ac97, 0x26, 0x0000);
snd_ac97_write_cache(ac97, AC97_SURROUND_MASTER, 0x0000);
snd_ac97_write_cache(ac97, AC97_SPDIF, 0x0000);
return 0;
}
/*
* Sigmatel STAC97xx codecs
*/
static int patch_sigmatel_stac9700_3d(struct snd_ac97 * ac97)
{
struct snd_kcontrol *kctl;
int err;
if ((err = snd_ctl_add(ac97->bus->card, kctl = snd_ac97_cnew(&snd_ac97_controls_3d[0], ac97))) < 0)
return err;
strcpy(kctl->id.name, "3D Control Sigmatel - Depth");
kctl->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 2, 3, 0);
snd_ac97_write_cache(ac97, AC97_3D_CONTROL, 0x0000);
return 0;
}
static int patch_sigmatel_stac9708_3d(struct snd_ac97 * ac97)
{
struct snd_kcontrol *kctl;
int err;
if ((err = snd_ctl_add(ac97->bus->card, kctl = snd_ac97_cnew(&snd_ac97_controls_3d[0], ac97))) < 0)
return err;
strcpy(kctl->id.name, "3D Control Sigmatel - Depth");
kctl->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 0, 3, 0);
if ((err = snd_ctl_add(ac97->bus->card, kctl = snd_ac97_cnew(&snd_ac97_controls_3d[0], ac97))) < 0)
return err;
strcpy(kctl->id.name, "3D Control Sigmatel - Rear Depth");
kctl->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 2, 3, 0);
snd_ac97_write_cache(ac97, AC97_3D_CONTROL, 0x0000);
return 0;
}
static const struct snd_kcontrol_new snd_ac97_sigmatel_4speaker =
AC97_SINGLE("Sigmatel 4-Speaker Stereo Playback Switch",
AC97_SIGMATEL_DAC2INVERT, 2, 1, 0);
/* "Sigmatel " removed due to excessive name length: */
static const struct snd_kcontrol_new snd_ac97_sigmatel_phaseinvert =
AC97_SINGLE("Surround Phase Inversion Playback Switch",
AC97_SIGMATEL_DAC2INVERT, 3, 1, 0);
static const struct snd_kcontrol_new snd_ac97_sigmatel_controls[] = {
AC97_SINGLE("Sigmatel DAC 6dB Attenuate", AC97_SIGMATEL_ANALOG, 1, 1, 0),
AC97_SINGLE("Sigmatel ADC 6dB Attenuate", AC97_SIGMATEL_ANALOG, 0, 1, 0)
};
static int patch_sigmatel_stac97xx_specific(struct snd_ac97 * ac97)
{
int err;
snd_ac97_write_cache(ac97, AC97_SIGMATEL_ANALOG, snd_ac97_read(ac97, AC97_SIGMATEL_ANALOG) & ~0x0003);
if (snd_ac97_try_bit(ac97, AC97_SIGMATEL_ANALOG, 1))
if ((err = patch_build_controls(ac97, &snd_ac97_sigmatel_controls[0], 1)) < 0)
return err;
if (snd_ac97_try_bit(ac97, AC97_SIGMATEL_ANALOG, 0))
if ((err = patch_build_controls(ac97, &snd_ac97_sigmatel_controls[1], 1)) < 0)
return err;
if (snd_ac97_try_bit(ac97, AC97_SIGMATEL_DAC2INVERT, 2))
if ((err = patch_build_controls(ac97, &snd_ac97_sigmatel_4speaker, 1)) < 0)
return err;
if (snd_ac97_try_bit(ac97, AC97_SIGMATEL_DAC2INVERT, 3))
if ((err = patch_build_controls(ac97, &snd_ac97_sigmatel_phaseinvert, 1)) < 0)
return err;
return 0;
}
static const struct snd_ac97_build_ops patch_sigmatel_stac9700_ops = {
.build_3d = patch_sigmatel_stac9700_3d,
.build_specific = patch_sigmatel_stac97xx_specific
};
static int patch_sigmatel_stac9700(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_sigmatel_stac9700_ops;
return 0;
}
static int snd_ac97_stac9708_put_bias(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
int err;
mutex_lock(&ac97->page_mutex);
snd_ac97_write(ac97, AC97_SIGMATEL_BIAS1, 0xabba);
err = snd_ac97_update_bits(ac97, AC97_SIGMATEL_BIAS2, 0x0010,
(ucontrol->value.integer.value[0] & 1) << 4);
snd_ac97_write(ac97, AC97_SIGMATEL_BIAS1, 0);
mutex_unlock(&ac97->page_mutex);
return err;
}
static const struct snd_kcontrol_new snd_ac97_stac9708_bias_control = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Sigmatel Output Bias Switch",
.info = snd_ac97_info_volsw,
.get = snd_ac97_get_volsw,
.put = snd_ac97_stac9708_put_bias,
.private_value = AC97_SINGLE_VALUE(AC97_SIGMATEL_BIAS2, 4, 1, 0),
};
static int patch_sigmatel_stac9708_specific(struct snd_ac97 *ac97)
{
int err;
/* the register bit is writable, but the function is not implemented: */
snd_ac97_remove_ctl(ac97, "PCM Out Path & Mute", NULL);
snd_ac97_rename_vol_ctl(ac97, "Headphone Playback", "Sigmatel Surround Playback");
if ((err = patch_build_controls(ac97, &snd_ac97_stac9708_bias_control, 1)) < 0)
return err;
return patch_sigmatel_stac97xx_specific(ac97);
}
static const struct snd_ac97_build_ops patch_sigmatel_stac9708_ops = {
.build_3d = patch_sigmatel_stac9708_3d,
.build_specific = patch_sigmatel_stac9708_specific
};
static int patch_sigmatel_stac9708(struct snd_ac97 * ac97)
{
unsigned int codec72, codec6c;
ac97->build_ops = &patch_sigmatel_stac9708_ops;
ac97->caps |= 0x10; /* HP (sigmatel surround) support */
codec72 = snd_ac97_read(ac97, AC97_SIGMATEL_BIAS2) & 0x8000;
codec6c = snd_ac97_read(ac97, AC97_SIGMATEL_ANALOG);
if ((codec72==0) && (codec6c==0)) {
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x1000);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS2, 0x0007);
} else if ((codec72==0x8000) && (codec6c==0)) {
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x1001);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_DAC2INVERT, 0x0008);
} else if ((codec72==0x8000) && (codec6c==0x0080)) {
/* nothing */
}
snd_ac97_write_cache(ac97, AC97_SIGMATEL_MULTICHN, 0x0000);
return 0;
}
static int patch_sigmatel_stac9721(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_sigmatel_stac9700_ops;
if (snd_ac97_read(ac97, AC97_SIGMATEL_ANALOG) == 0) {
// patch for SigmaTel
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x4000);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS2, 0x0002);
}
snd_ac97_write_cache(ac97, AC97_SIGMATEL_MULTICHN, 0x0000);
return 0;
}
static int patch_sigmatel_stac9744(struct snd_ac97 * ac97)
{
// patch for SigmaTel
ac97->build_ops = &patch_sigmatel_stac9700_ops;
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x0000); /* is this correct? --jk */
snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS2, 0x0002);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_MULTICHN, 0x0000);
return 0;
}
static int patch_sigmatel_stac9756(struct snd_ac97 * ac97)
{
// patch for SigmaTel
ac97->build_ops = &patch_sigmatel_stac9700_ops;
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x0000); /* is this correct? --jk */
snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS1, 0xabba);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS2, 0x0002);
snd_ac97_write_cache(ac97, AC97_SIGMATEL_MULTICHN, 0x0000);
return 0;
}
static int snd_ac97_stac9758_output_jack_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[5] = { "Input/Disabled", "Front Output",
"Rear Output", "Center/LFE Output", "Mixer Output" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 5;
if (uinfo->value.enumerated.item > 4)
uinfo->value.enumerated.item = 4;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_stac9758_output_jack_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
int shift = kcontrol->private_value;
unsigned short val;
val = ac97->regs[AC97_SIGMATEL_OUTSEL] >> shift;
if (!(val & 4))
ucontrol->value.enumerated.item[0] = 0;
else
ucontrol->value.enumerated.item[0] = 1 + (val & 3);
return 0;
}
static int snd_ac97_stac9758_output_jack_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
int shift = kcontrol->private_value;
unsigned short val;
if (ucontrol->value.enumerated.item[0] > 4)
return -EINVAL;
if (ucontrol->value.enumerated.item[0] == 0)
val = 0;
else
val = 4 | (ucontrol->value.enumerated.item[0] - 1);
return ac97_update_bits_page(ac97, AC97_SIGMATEL_OUTSEL,
7 << shift, val << shift, 0);
}
static int snd_ac97_stac9758_input_jack_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[7] = { "Mic2 Jack", "Mic1 Jack", "Line In Jack",
"Front Jack", "Rear Jack", "Center/LFE Jack", "Mute" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 7;
if (uinfo->value.enumerated.item > 6)
uinfo->value.enumerated.item = 6;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_stac9758_input_jack_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
int shift = kcontrol->private_value;
unsigned short val;
val = ac97->regs[AC97_SIGMATEL_INSEL];
ucontrol->value.enumerated.item[0] = (val >> shift) & 7;
return 0;
}
static int snd_ac97_stac9758_input_jack_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
int shift = kcontrol->private_value;
return ac97_update_bits_page(ac97, AC97_SIGMATEL_INSEL, 7 << shift,
ucontrol->value.enumerated.item[0] << shift, 0);
}
static int snd_ac97_stac9758_phonesel_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[3] = { "None", "Front Jack", "Rear Jack" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 3;
if (uinfo->value.enumerated.item > 2)
uinfo->value.enumerated.item = 2;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_stac9758_phonesel_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
ucontrol->value.enumerated.item[0] = ac97->regs[AC97_SIGMATEL_IOMISC] & 3;
return 0;
}
static int snd_ac97_stac9758_phonesel_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
return ac97_update_bits_page(ac97, AC97_SIGMATEL_IOMISC, 3,
ucontrol->value.enumerated.item[0], 0);
}
#define STAC9758_OUTPUT_JACK(xname, shift) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_ac97_stac9758_output_jack_info, \
.get = snd_ac97_stac9758_output_jack_get, \
.put = snd_ac97_stac9758_output_jack_put, \
.private_value = shift }
#define STAC9758_INPUT_JACK(xname, shift) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_ac97_stac9758_input_jack_info, \
.get = snd_ac97_stac9758_input_jack_get, \
.put = snd_ac97_stac9758_input_jack_put, \
.private_value = shift }
static const struct snd_kcontrol_new snd_ac97_sigmatel_stac9758_controls[] = {
STAC9758_OUTPUT_JACK("Mic1 Jack", 1),
STAC9758_OUTPUT_JACK("LineIn Jack", 4),
STAC9758_OUTPUT_JACK("Front Jack", 7),
STAC9758_OUTPUT_JACK("Rear Jack", 10),
STAC9758_OUTPUT_JACK("Center/LFE Jack", 13),
STAC9758_INPUT_JACK("Mic Input Source", 0),
STAC9758_INPUT_JACK("Line Input Source", 8),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Headphone Amp",
.info = snd_ac97_stac9758_phonesel_info,
.get = snd_ac97_stac9758_phonesel_get,
.put = snd_ac97_stac9758_phonesel_put
},
AC97_SINGLE("Exchange Center/LFE", AC97_SIGMATEL_IOMISC, 4, 1, 0),
AC97_SINGLE("Headphone +3dB Boost", AC97_SIGMATEL_IOMISC, 8, 1, 0)
};
static int patch_sigmatel_stac9758_specific(struct snd_ac97 *ac97)
{
int err;
err = patch_sigmatel_stac97xx_specific(ac97);
if (err < 0)
return err;
err = patch_build_controls(ac97, snd_ac97_sigmatel_stac9758_controls,
ARRAY_SIZE(snd_ac97_sigmatel_stac9758_controls));
if (err < 0)
return err;
/* DAC-A direct */
snd_ac97_rename_vol_ctl(ac97, "Headphone Playback", "Front Playback");
/* DAC-A to Mix = PCM */
/* DAC-B direct = Surround */
/* DAC-B to Mix */
snd_ac97_rename_vol_ctl(ac97, "Video Playback", "Surround Mix Playback");
/* DAC-C direct = Center/LFE */
return 0;
}
static const struct snd_ac97_build_ops patch_sigmatel_stac9758_ops = {
.build_3d = patch_sigmatel_stac9700_3d,
.build_specific = patch_sigmatel_stac9758_specific
};
static int patch_sigmatel_stac9758(struct snd_ac97 * ac97)
{
static unsigned short regs[4] = {
AC97_SIGMATEL_OUTSEL,
AC97_SIGMATEL_IOMISC,
AC97_SIGMATEL_INSEL,
AC97_SIGMATEL_VARIOUS
};
static unsigned short def_regs[4] = {
/* OUTSEL */ 0xd794, /* CL:CL, SR:SR, LO:MX, LI:DS, MI:DS */
/* IOMISC */ 0x2001,
/* INSEL */ 0x0201, /* LI:LI, MI:M1 */
/* VARIOUS */ 0x0040
};
static unsigned short m675_regs[4] = {
/* OUTSEL */ 0xfc70, /* CL:MX, SR:MX, LO:DS, LI:MX, MI:DS */
/* IOMISC */ 0x2102, /* HP amp on */
/* INSEL */ 0x0203, /* LI:LI, MI:FR */
/* VARIOUS */ 0x0041 /* stereo mic */
};
unsigned short *pregs = def_regs;
int i;
/* Gateway M675 notebook */
if (ac97->pci &&
ac97->subsystem_vendor == 0x107b &&
ac97->subsystem_device == 0x0601)
pregs = m675_regs;
// patch for SigmaTel
ac97->build_ops = &patch_sigmatel_stac9758_ops;
/* FIXME: assume only page 0 for writing cache */
snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, AC97_PAGE_VENDOR);
for (i = 0; i < 4; i++)
snd_ac97_write_cache(ac97, regs[i], pregs[i]);
ac97->flags |= AC97_STEREO_MUTES;
return 0;
}
/*
* Cirrus Logic CS42xx codecs
*/
static const struct snd_kcontrol_new snd_ac97_cirrus_controls_spdif[2] = {
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH), AC97_CSR_SPDIF, 15, 1, 0),
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "AC97-SPSA", AC97_CSR_ACMODE, 0, 3, 0)
};
static int patch_cirrus_build_spdif(struct snd_ac97 * ac97)
{
int err;
/* con mask, pro mask, default */
if ((err = patch_build_controls(ac97, &snd_ac97_controls_spdif[0], 3)) < 0)
return err;
/* switch, spsa */
if ((err = patch_build_controls(ac97, &snd_ac97_cirrus_controls_spdif[0], 1)) < 0)
return err;
switch (ac97->id & AC97_ID_CS_MASK) {
case AC97_ID_CS4205:
if ((err = patch_build_controls(ac97, &snd_ac97_cirrus_controls_spdif[1], 1)) < 0)
return err;
break;
}
/* set default PCM S/PDIF params */
/* consumer,PCM audio,no copyright,no preemphasis,PCM coder,original,48000Hz */
snd_ac97_write_cache(ac97, AC97_CSR_SPDIF, 0x0a20);
return 0;
}
static const struct snd_ac97_build_ops patch_cirrus_ops = {
.build_spdif = patch_cirrus_build_spdif
};
static int patch_cirrus_spdif(struct snd_ac97 * ac97)
{
/* Basically, the cs4201/cs4205/cs4297a has non-standard sp/dif registers.
WHY CAN'T ANYONE FOLLOW THE BLOODY SPEC? *sigh*
- sp/dif EA ID is not set, but sp/dif is always present.
- enable/disable is spdif register bit 15.
- sp/dif control register is 0x68. differs from AC97:
- valid is bit 14 (vs 15)
- no DRS
- only 44.1/48k [00 = 48, 01=44,1] (AC97 is 00=44.1, 10=48)
- sp/dif ssource select is in 0x5e bits 0,1.
*/
ac97->build_ops = &patch_cirrus_ops;
ac97->flags |= AC97_CS_SPDIF;
ac97->rates[AC97_RATES_SPDIF] &= ~SNDRV_PCM_RATE_32000;
ac97->ext_id |= AC97_EI_SPDIF; /* force the detection of spdif */
snd_ac97_write_cache(ac97, AC97_CSR_ACMODE, 0x0080);
return 0;
}
static int patch_cirrus_cs4299(struct snd_ac97 * ac97)
{
/* force the detection of PC Beep */
ac97->flags |= AC97_HAS_PC_BEEP;
return patch_cirrus_spdif(ac97);
}
/*
* Conexant codecs
*/
static const struct snd_kcontrol_new snd_ac97_conexant_controls_spdif[1] = {
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH), AC97_CXR_AUDIO_MISC, 3, 1, 0),
};
static int patch_conexant_build_spdif(struct snd_ac97 * ac97)
{
int err;
/* con mask, pro mask, default */
if ((err = patch_build_controls(ac97, &snd_ac97_controls_spdif[0], 3)) < 0)
return err;
/* switch */
if ((err = patch_build_controls(ac97, &snd_ac97_conexant_controls_spdif[0], 1)) < 0)
return err;
/* set default PCM S/PDIF params */
/* consumer,PCM audio,no copyright,no preemphasis,PCM coder,original,48000Hz */
snd_ac97_write_cache(ac97, AC97_CXR_AUDIO_MISC,
snd_ac97_read(ac97, AC97_CXR_AUDIO_MISC) & ~(AC97_CXR_SPDIFEN|AC97_CXR_COPYRGT|AC97_CXR_SPDIF_MASK));
return 0;
}
static const struct snd_ac97_build_ops patch_conexant_ops = {
.build_spdif = patch_conexant_build_spdif
};
static int patch_conexant(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_conexant_ops;
ac97->flags |= AC97_CX_SPDIF;
ac97->ext_id |= AC97_EI_SPDIF; /* force the detection of spdif */
ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */
return 0;
}
static int patch_cx20551(struct snd_ac97 *ac97)
{
snd_ac97_update_bits(ac97, 0x5c, 0x01, 0x01);
return 0;
}
/*
* Analog Device AD18xx, AD19xx codecs
*/
#ifdef CONFIG_PM
static void ad18xx_resume(struct snd_ac97 *ac97)
{
static unsigned short setup_regs[] = {
AC97_AD_MISC, AC97_AD_SERIAL_CFG, AC97_AD_JACK_SPDIF,
};
int i, codec;
for (i = 0; i < (int)ARRAY_SIZE(setup_regs); i++) {
unsigned short reg = setup_regs[i];
if (test_bit(reg, ac97->reg_accessed)) {
snd_ac97_write(ac97, reg, ac97->regs[reg]);
snd_ac97_read(ac97, reg);
}
}
if (! (ac97->flags & AC97_AD_MULTI))
/* normal restore */
snd_ac97_restore_status(ac97);
else {
/* restore the AD18xx codec configurations */
for (codec = 0; codec < 3; codec++) {
if (! ac97->spec.ad18xx.id[codec])
continue;
/* select single codec */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000,
ac97->spec.ad18xx.unchained[codec] | ac97->spec.ad18xx.chained[codec]);
ac97->bus->ops->write(ac97, AC97_AD_CODEC_CFG, ac97->spec.ad18xx.codec_cfg[codec]);
}
/* select all codecs */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, 0x7000);
/* restore status */
for (i = 2; i < 0x7c ; i += 2) {
if (i == AC97_POWERDOWN || i == AC97_EXTENDED_ID)
continue;
if (test_bit(i, ac97->reg_accessed)) {
/* handle multi codecs for AD18xx */
if (i == AC97_PCM) {
for (codec = 0; codec < 3; codec++) {
if (! ac97->spec.ad18xx.id[codec])
continue;
/* select single codec */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000,
ac97->spec.ad18xx.unchained[codec] | ac97->spec.ad18xx.chained[codec]);
/* update PCM bits */
ac97->bus->ops->write(ac97, AC97_PCM, ac97->spec.ad18xx.pcmreg[codec]);
}
/* select all codecs */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, 0x7000);
continue;
} else if (i == AC97_AD_TEST ||
i == AC97_AD_CODEC_CFG ||
i == AC97_AD_SERIAL_CFG)
continue; /* ignore */
}
snd_ac97_write(ac97, i, ac97->regs[i]);
snd_ac97_read(ac97, i);
}
}
snd_ac97_restore_iec958(ac97);
}
static void ad1888_resume(struct snd_ac97 *ac97)
{
ad18xx_resume(ac97);
snd_ac97_write_cache(ac97, AC97_CODEC_CLASS_REV, 0x8080);
}
#endif
static const struct snd_ac97_res_table ad1819_restbl[] = {
{ AC97_PHONE, 0x9f1f },
{ AC97_MIC, 0x9f1f },
{ AC97_LINE, 0x9f1f },
{ AC97_CD, 0x9f1f },
{ AC97_VIDEO, 0x9f1f },
{ AC97_AUX, 0x9f1f },
{ AC97_PCM, 0x9f1f },
{ } /* terminator */
};
static int patch_ad1819(struct snd_ac97 * ac97)
{
unsigned short scfg;
// patch for Analog Devices
scfg = snd_ac97_read(ac97, AC97_AD_SERIAL_CFG);
snd_ac97_write_cache(ac97, AC97_AD_SERIAL_CFG, scfg | 0x7000); /* select all codecs */
ac97->res_table = ad1819_restbl;
return 0;
}
static unsigned short patch_ad1881_unchained(struct snd_ac97 * ac97, int idx, unsigned short mask)
{
unsigned short val;
// test for unchained codec
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, mask);
snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, 0x0000); /* ID0C, ID1C, SDIE = off */
val = snd_ac97_read(ac97, AC97_VENDOR_ID2);
if ((val & 0xff40) != 0x5340)
return 0;
ac97->spec.ad18xx.unchained[idx] = mask;
ac97->spec.ad18xx.id[idx] = val;
ac97->spec.ad18xx.codec_cfg[idx] = 0x0000;
return mask;
}
static int patch_ad1881_chained1(struct snd_ac97 * ac97, int idx, unsigned short codec_bits)
{
static int cfg_bits[3] = { 1<<12, 1<<14, 1<<13 };
unsigned short val;
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, cfg_bits[idx]);
snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, 0x0004); // SDIE
val = snd_ac97_read(ac97, AC97_VENDOR_ID2);
if ((val & 0xff40) != 0x5340)
return 0;
if (codec_bits)
snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, codec_bits);
ac97->spec.ad18xx.chained[idx] = cfg_bits[idx];
ac97->spec.ad18xx.id[idx] = val;
ac97->spec.ad18xx.codec_cfg[idx] = codec_bits ? codec_bits : 0x0004;
return 1;
}
static void patch_ad1881_chained(struct snd_ac97 * ac97, int unchained_idx, int cidx1, int cidx2)
{
// already detected?
if (ac97->spec.ad18xx.unchained[cidx1] || ac97->spec.ad18xx.chained[cidx1])
cidx1 = -1;
if (ac97->spec.ad18xx.unchained[cidx2] || ac97->spec.ad18xx.chained[cidx2])
cidx2 = -1;
if (cidx1 < 0 && cidx2 < 0)
return;
// test for chained codecs
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000,
ac97->spec.ad18xx.unchained[unchained_idx]);
snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, 0x0002); // ID1C
ac97->spec.ad18xx.codec_cfg[unchained_idx] = 0x0002;
if (cidx1 >= 0) {
if (cidx2 < 0)
patch_ad1881_chained1(ac97, cidx1, 0);
else if (patch_ad1881_chained1(ac97, cidx1, 0x0006)) // SDIE | ID1C
patch_ad1881_chained1(ac97, cidx2, 0);
else if (patch_ad1881_chained1(ac97, cidx2, 0x0006)) // SDIE | ID1C
patch_ad1881_chained1(ac97, cidx1, 0);
} else if (cidx2 >= 0) {
patch_ad1881_chained1(ac97, cidx2, 0);
}
}
static const struct snd_ac97_build_ops patch_ad1881_build_ops = {
#ifdef CONFIG_PM
.resume = ad18xx_resume
#endif
};
static int patch_ad1881(struct snd_ac97 * ac97)
{
static const char cfg_idxs[3][2] = {
{2, 1},
{0, 2},
{0, 1}
};
// patch for Analog Devices
unsigned short codecs[3];
unsigned short val;
int idx, num;
val = snd_ac97_read(ac97, AC97_AD_SERIAL_CFG);
snd_ac97_write_cache(ac97, AC97_AD_SERIAL_CFG, val);
codecs[0] = patch_ad1881_unchained(ac97, 0, (1<<12));
codecs[1] = patch_ad1881_unchained(ac97, 1, (1<<14));
codecs[2] = patch_ad1881_unchained(ac97, 2, (1<<13));
if (! (codecs[0] || codecs[1] || codecs[2]))
goto __end;
for (idx = 0; idx < 3; idx++)
if (ac97->spec.ad18xx.unchained[idx])
patch_ad1881_chained(ac97, idx, cfg_idxs[idx][0], cfg_idxs[idx][1]);
if (ac97->spec.ad18xx.id[1]) {
ac97->flags |= AC97_AD_MULTI;
ac97->scaps |= AC97_SCAP_SURROUND_DAC;
}
if (ac97->spec.ad18xx.id[2]) {
ac97->flags |= AC97_AD_MULTI;
ac97->scaps |= AC97_SCAP_CENTER_LFE_DAC;
}
__end:
/* select all codecs */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, 0x7000);
/* check if only one codec is present */
for (idx = num = 0; idx < 3; idx++)
if (ac97->spec.ad18xx.id[idx])
num++;
if (num == 1) {
/* ok, deselect all ID bits */
snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, 0x0000);
ac97->spec.ad18xx.codec_cfg[0] =
ac97->spec.ad18xx.codec_cfg[1] =
ac97->spec.ad18xx.codec_cfg[2] = 0x0000;
}
/* required for AD1886/AD1885 combination */
ac97->ext_id = snd_ac97_read(ac97, AC97_EXTENDED_ID);
if (ac97->spec.ad18xx.id[0]) {
ac97->id &= 0xffff0000;
ac97->id |= ac97->spec.ad18xx.id[0];
}
ac97->build_ops = &patch_ad1881_build_ops;
return 0;
}
static const struct snd_kcontrol_new snd_ac97_controls_ad1885[] = {
AC97_SINGLE("Digital Mono Direct", AC97_AD_MISC, 11, 1, 0),
/* AC97_SINGLE("Digital Audio Mode", AC97_AD_MISC, 12, 1, 0), */ /* seems problematic */
AC97_SINGLE("Low Power Mixer", AC97_AD_MISC, 14, 1, 0),
AC97_SINGLE("Zero Fill DAC", AC97_AD_MISC, 15, 1, 0),
AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 9, 1, 1), /* inverted */
AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 8, 1, 1), /* inverted */
};
static const DECLARE_TLV_DB_SCALE(db_scale_6bit_6db_max, -8850, 150, 0);
static int patch_ad1885_specific(struct snd_ac97 * ac97)
{
int err;
if ((err = patch_build_controls(ac97, snd_ac97_controls_ad1885, ARRAY_SIZE(snd_ac97_controls_ad1885))) < 0)
return err;
reset_tlv(ac97, "Headphone Playback Volume",
db_scale_6bit_6db_max);
return 0;
}
static const struct snd_ac97_build_ops patch_ad1885_build_ops = {
.build_specific = &patch_ad1885_specific,
#ifdef CONFIG_PM
.resume = ad18xx_resume
#endif
};
static int patch_ad1885(struct snd_ac97 * ac97)
{
patch_ad1881(ac97);
/* This is required to deal with the Intel D815EEAL2 */
/* i.e. Line out is actually headphone out from codec */
/* set default */
snd_ac97_write_cache(ac97, AC97_AD_MISC, 0x0404);
ac97->build_ops = &patch_ad1885_build_ops;
return 0;
}
static int patch_ad1886_specific(struct snd_ac97 * ac97)
{
reset_tlv(ac97, "Headphone Playback Volume",
db_scale_6bit_6db_max);
return 0;
}
static const struct snd_ac97_build_ops patch_ad1886_build_ops = {
.build_specific = &patch_ad1886_specific,
#ifdef CONFIG_PM
.resume = ad18xx_resume
#endif
};
static int patch_ad1886(struct snd_ac97 * ac97)
{
patch_ad1881(ac97);
/* Presario700 workaround */
/* for Jack Sense/SPDIF Register misetting causing */
snd_ac97_write_cache(ac97, AC97_AD_JACK_SPDIF, 0x0010);
ac97->build_ops = &patch_ad1886_build_ops;
return 0;
}
/* MISC bits (AD1888/AD1980/AD1985 register 0x76) */
#define AC97_AD198X_MBC 0x0003 /* mic boost */
#define AC97_AD198X_MBC_20 0x0000 /* +20dB */
#define AC97_AD198X_MBC_10 0x0001 /* +10dB */
#define AC97_AD198X_MBC_30 0x0002 /* +30dB */
#define AC97_AD198X_VREFD 0x0004 /* VREF high-Z */
#define AC97_AD198X_VREFH 0x0008 /* 0=2.25V, 1=3.7V */
#define AC97_AD198X_VREF_0 0x000c /* 0V (AD1985 only) */
#define AC97_AD198X_VREF_MASK (AC97_AD198X_VREFH | AC97_AD198X_VREFD)
#define AC97_AD198X_VREF_SHIFT 2
#define AC97_AD198X_SRU 0x0010 /* sample rate unlock */
#define AC97_AD198X_LOSEL 0x0020 /* LINE_OUT amplifiers input select */
#define AC97_AD198X_2MIC 0x0040 /* 2-channel mic select */
#define AC97_AD198X_SPRD 0x0080 /* SPREAD enable */
#define AC97_AD198X_DMIX0 0x0100 /* downmix mode: */
/* 0 = 6-to-4, 1 = 6-to-2 downmix */
#define AC97_AD198X_DMIX1 0x0200 /* downmix mode: 1 = enabled */
#define AC97_AD198X_HPSEL 0x0400 /* headphone amplifier input select */
#define AC97_AD198X_CLDIS 0x0800 /* center/lfe disable */
#define AC97_AD198X_LODIS 0x1000 /* LINE_OUT disable */
#define AC97_AD198X_MSPLT 0x2000 /* mute split */
#define AC97_AD198X_AC97NC 0x4000 /* AC97 no compatible mode */
#define AC97_AD198X_DACZ 0x8000 /* DAC zero-fill mode */
/* MISC 1 bits (AD1986 register 0x76) */
#define AC97_AD1986_MBC 0x0003 /* mic boost */
#define AC97_AD1986_MBC_20 0x0000 /* +20dB */
#define AC97_AD1986_MBC_10 0x0001 /* +10dB */
#define AC97_AD1986_MBC_30 0x0002 /* +30dB */
#define AC97_AD1986_LISEL0 0x0004 /* LINE_IN select bit 0 */
#define AC97_AD1986_LISEL1 0x0008 /* LINE_IN select bit 1 */
#define AC97_AD1986_LISEL_MASK (AC97_AD1986_LISEL1 | AC97_AD1986_LISEL0)
#define AC97_AD1986_LISEL_LI 0x0000 /* LINE_IN pins as LINE_IN source */
#define AC97_AD1986_LISEL_SURR 0x0004 /* SURROUND pins as LINE_IN source */
#define AC97_AD1986_LISEL_MIC 0x0008 /* MIC_1/2 pins as LINE_IN source */
#define AC97_AD1986_SRU 0x0010 /* sample rate unlock */
#define AC97_AD1986_SOSEL 0x0020 /* SURROUND_OUT amplifiers input sel */
#define AC97_AD1986_2MIC 0x0040 /* 2-channel mic select */
#define AC97_AD1986_SPRD 0x0080 /* SPREAD enable */
#define AC97_AD1986_DMIX0 0x0100 /* downmix mode: */
/* 0 = 6-to-4, 1 = 6-to-2 downmix */
#define AC97_AD1986_DMIX1 0x0200 /* downmix mode: 1 = enabled */
#define AC97_AD1986_CLDIS 0x0800 /* center/lfe disable */
#define AC97_AD1986_SODIS 0x1000 /* SURROUND_OUT disable */
#define AC97_AD1986_MSPLT 0x2000 /* mute split (read only 1) */
#define AC97_AD1986_AC97NC 0x4000 /* AC97 no compatible mode (r/o 1) */
#define AC97_AD1986_DACZ 0x8000 /* DAC zero-fill mode */
/* MISC 2 bits (AD1986 register 0x70) */
#define AC97_AD_MISC2 0x70 /* Misc Control Bits 2 (AD1986) */
#define AC97_AD1986_CVREF0 0x0004 /* C/LFE VREF_OUT 2.25V */
#define AC97_AD1986_CVREF1 0x0008 /* C/LFE VREF_OUT 0V */
#define AC97_AD1986_CVREF2 0x0010 /* C/LFE VREF_OUT 3.7V */
#define AC97_AD1986_CVREF_MASK \
(AC97_AD1986_CVREF2 | AC97_AD1986_CVREF1 | AC97_AD1986_CVREF0)
#define AC97_AD1986_JSMAP 0x0020 /* Jack Sense Mapping 1 = alternate */
#define AC97_AD1986_MMDIS 0x0080 /* Mono Mute Disable */
#define AC97_AD1986_MVREF0 0x0400 /* MIC VREF_OUT 2.25V */
#define AC97_AD1986_MVREF1 0x0800 /* MIC VREF_OUT 0V */
#define AC97_AD1986_MVREF2 0x1000 /* MIC VREF_OUT 3.7V */
#define AC97_AD1986_MVREF_MASK \
(AC97_AD1986_MVREF2 | AC97_AD1986_MVREF1 | AC97_AD1986_MVREF0)
/* MISC 3 bits (AD1986 register 0x7a) */
#define AC97_AD_MISC3 0x7a /* Misc Control Bits 3 (AD1986) */
#define AC97_AD1986_MMIX 0x0004 /* Mic Mix, left/right */
#define AC97_AD1986_GPO 0x0008 /* General Purpose Out */
#define AC97_AD1986_LOHPEN 0x0010 /* LINE_OUT headphone drive */
#define AC97_AD1986_LVREF0 0x0100 /* LINE_OUT VREF_OUT 2.25V */
#define AC97_AD1986_LVREF1 0x0200 /* LINE_OUT VREF_OUT 0V */
#define AC97_AD1986_LVREF2 0x0400 /* LINE_OUT VREF_OUT 3.7V */
#define AC97_AD1986_LVREF_MASK \
(AC97_AD1986_LVREF2 | AC97_AD1986_LVREF1 | AC97_AD1986_LVREF0)
#define AC97_AD1986_JSINVA 0x0800 /* Jack Sense Invert SENSE_A */
#define AC97_AD1986_LOSEL 0x1000 /* LINE_OUT amplifiers input select */
#define AC97_AD1986_HPSEL0 0x2000 /* Headphone amplifiers */
/* input select Surround DACs */
#define AC97_AD1986_HPSEL1 0x4000 /* Headphone amplifiers input */
/* select C/LFE DACs */
#define AC97_AD1986_JSINVB 0x8000 /* Jack Sense Invert SENSE_B */
/* Serial Config bits (AD1986 register 0x74) (incomplete) */
#define AC97_AD1986_OMS0 0x0100 /* Optional Mic Selector bit 0 */
#define AC97_AD1986_OMS1 0x0200 /* Optional Mic Selector bit 1 */
#define AC97_AD1986_OMS2 0x0400 /* Optional Mic Selector bit 2 */
#define AC97_AD1986_OMS_MASK \
(AC97_AD1986_OMS2 | AC97_AD1986_OMS1 | AC97_AD1986_OMS0)
#define AC97_AD1986_OMS_M 0x0000 /* MIC_1/2 pins are MIC sources */
#define AC97_AD1986_OMS_L 0x0100 /* LINE_IN pins are MIC sources */
#define AC97_AD1986_OMS_C 0x0200 /* Center/LFE pins are MCI sources */
#define AC97_AD1986_OMS_MC 0x0400 /* Mix of MIC and C/LFE pins */
/* are MIC sources */
#define AC97_AD1986_OMS_ML 0x0500 /* MIX of MIC and LINE_IN pins */
/* are MIC sources */
#define AC97_AD1986_OMS_LC 0x0600 /* MIX of LINE_IN and C/LFE pins */
/* are MIC sources */
#define AC97_AD1986_OMS_MLC 0x0700 /* MIX of MIC, LINE_IN, C/LFE pins */
/* are MIC sources */
static int snd_ac97_ad198x_spdif_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[2] = { "AC-Link", "A/D Converter" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item > 1)
uinfo->value.enumerated.item = 1;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_ad198x_spdif_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_AD_SERIAL_CFG];
ucontrol->value.enumerated.item[0] = (val >> 2) & 1;
return 0;
}
static int snd_ac97_ad198x_spdif_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
if (ucontrol->value.enumerated.item[0] > 1)
return -EINVAL;
val = ucontrol->value.enumerated.item[0] << 2;
return snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x0004, val);
}
static const struct snd_kcontrol_new snd_ac97_ad198x_spdif_source = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
.info = snd_ac97_ad198x_spdif_source_info,
.get = snd_ac97_ad198x_spdif_source_get,
.put = snd_ac97_ad198x_spdif_source_put,
};
static int patch_ad198x_post_spdif(struct snd_ac97 * ac97)
{
return patch_build_controls(ac97, &snd_ac97_ad198x_spdif_source, 1);
}
static const struct snd_kcontrol_new snd_ac97_ad1981x_jack_sense[] = {
AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 11, 1, 0),
AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 12, 1, 0),
};
/* black list to avoid HP/Line jack-sense controls
* (SS vendor << 16 | device)
*/
static unsigned int ad1981_jacks_blacklist[] = {
0x10140523, /* Thinkpad R40 */
0x10140534, /* Thinkpad X31 */
0x10140537, /* Thinkpad T41p */
0x1014053e, /* Thinkpad R40e */
0x10140554, /* Thinkpad T42p/R50p */
0x10140567, /* Thinkpad T43p 2668-G7U */
0x10140581, /* Thinkpad X41-2527 */
0x10280160, /* Dell Dimension 2400 */
0x104380b0, /* Asus A7V8X-MX */
0x11790241, /* Toshiba Satellite A-15 S127 */
0x1179ff10, /* Toshiba P500 */
0x144dc01a, /* Samsung NP-X20C004/SEG */
0 /* end */
};
static int check_list(struct snd_ac97 *ac97, const unsigned int *list)
{
u32 subid = ((u32)ac97->subsystem_vendor << 16) | ac97->subsystem_device;
for (; *list; list++)
if (*list == subid)
return 1;
return 0;
}
static int patch_ad1981a_specific(struct snd_ac97 * ac97)
{
if (check_list(ac97, ad1981_jacks_blacklist))
return 0;
return patch_build_controls(ac97, snd_ac97_ad1981x_jack_sense,
ARRAY_SIZE(snd_ac97_ad1981x_jack_sense));
}
static const struct snd_ac97_build_ops patch_ad1981a_build_ops = {
.build_post_spdif = patch_ad198x_post_spdif,
.build_specific = patch_ad1981a_specific,
#ifdef CONFIG_PM
.resume = ad18xx_resume
#endif
};
/* white list to enable HP jack-sense bits
* (SS vendor << 16 | device)
*/
static unsigned int ad1981_jacks_whitelist[] = {
0x0e11005a, /* HP nc4000/4010 */
0x103c0890, /* HP nc6000 */
0x103c0938, /* HP nc4220 */
0x103c099c, /* HP nx6110 */
0x103c0944, /* HP nc6220 */
0x103c0934, /* HP nc8220 */
0x103c006d, /* HP nx9105 */
0x103c300d, /* HP Compaq dc5100 SFF(PT003AW) */
0x17340088, /* FSC Scenic-W */
0 /* end */
};
static void check_ad1981_hp_jack_sense(struct snd_ac97 *ac97)
{
if (check_list(ac97, ad1981_jacks_whitelist))
/* enable headphone jack sense */
snd_ac97_update_bits(ac97, AC97_AD_JACK_SPDIF, 1<<11, 1<<11);
}
static int patch_ad1981a(struct snd_ac97 *ac97)
{
patch_ad1881(ac97);
ac97->build_ops = &patch_ad1981a_build_ops;
snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD198X_MSPLT, AC97_AD198X_MSPLT);
ac97->flags |= AC97_STEREO_MUTES;
check_ad1981_hp_jack_sense(ac97);
return 0;
}
static const struct snd_kcontrol_new snd_ac97_ad198x_2cmic =
AC97_SINGLE("Stereo Mic", AC97_AD_MISC, 6, 1, 0);
static int patch_ad1981b_specific(struct snd_ac97 *ac97)
{
int err;
if ((err = patch_build_controls(ac97, &snd_ac97_ad198x_2cmic, 1)) < 0)
return err;
if (check_list(ac97, ad1981_jacks_blacklist))
return 0;
return patch_build_controls(ac97, snd_ac97_ad1981x_jack_sense,
ARRAY_SIZE(snd_ac97_ad1981x_jack_sense));
}
static const struct snd_ac97_build_ops patch_ad1981b_build_ops = {
.build_post_spdif = patch_ad198x_post_spdif,
.build_specific = patch_ad1981b_specific,
#ifdef CONFIG_PM
.resume = ad18xx_resume
#endif
};
static int patch_ad1981b(struct snd_ac97 *ac97)
{
patch_ad1881(ac97);
ac97->build_ops = &patch_ad1981b_build_ops;
snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD198X_MSPLT, AC97_AD198X_MSPLT);
ac97->flags |= AC97_STEREO_MUTES;
check_ad1981_hp_jack_sense(ac97);
return 0;
}
#define snd_ac97_ad1888_lohpsel_info snd_ctl_boolean_mono_info
static int snd_ac97_ad1888_lohpsel_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_AD_MISC];
ucontrol->value.integer.value[0] = !(val & AC97_AD198X_LOSEL);
if (ac97->spec.ad18xx.lo_as_master)
ucontrol->value.integer.value[0] =
!ucontrol->value.integer.value[0];
return 0;
}
static int snd_ac97_ad1888_lohpsel_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = !ucontrol->value.integer.value[0];
if (ac97->spec.ad18xx.lo_as_master)
val = !val;
val = val ? (AC97_AD198X_LOSEL | AC97_AD198X_HPSEL) : 0;
return snd_ac97_update_bits(ac97, AC97_AD_MISC,
AC97_AD198X_LOSEL | AC97_AD198X_HPSEL, val);
}
static int snd_ac97_ad1888_downmix_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[3] = {"Off", "6 -> 4", "6 -> 2"};
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 3;
if (uinfo->value.enumerated.item > 2)
uinfo->value.enumerated.item = 2;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_ad1888_downmix_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_AD_MISC];
if (!(val & AC97_AD198X_DMIX1))
ucontrol->value.enumerated.item[0] = 0;
else
ucontrol->value.enumerated.item[0] = 1 + ((val >> 8) & 1);
return 0;
}
static int snd_ac97_ad1888_downmix_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
if (ucontrol->value.enumerated.item[0] > 2)
return -EINVAL;
if (ucontrol->value.enumerated.item[0] == 0)
val = 0;
else
val = AC97_AD198X_DMIX1 |
((ucontrol->value.enumerated.item[0] - 1) << 8);
return snd_ac97_update_bits(ac97, AC97_AD_MISC,
AC97_AD198X_DMIX0 | AC97_AD198X_DMIX1, val);
}
static void ad1888_update_jacks(struct snd_ac97 *ac97)
{
unsigned short val = 0;
/* clear LODIS if shared jack is to be used for Surround out */
if (!ac97->spec.ad18xx.lo_as_master && is_shared_linein(ac97))
val |= (1 << 12);
/* clear CLDIS if shared jack is to be used for C/LFE out */
if (is_shared_micin(ac97))
val |= (1 << 11);
/* shared Line-In */
snd_ac97_update_bits(ac97, AC97_AD_MISC, (1 << 11) | (1 << 12), val);
}
static const struct snd_kcontrol_new snd_ac97_ad1888_controls[] = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Exchange Front/Surround",
.info = snd_ac97_ad1888_lohpsel_info,
.get = snd_ac97_ad1888_lohpsel_get,
.put = snd_ac97_ad1888_lohpsel_put
},
AC97_SINGLE("V_REFOUT Enable", AC97_AD_MISC, AC97_AD_VREFD_SHIFT, 1, 1),
AC97_SINGLE("High Pass Filter Enable", AC97_AD_TEST2,
AC97_AD_HPFD_SHIFT, 1, 1),
AC97_SINGLE("Spread Front to Surround and Center/LFE", AC97_AD_MISC, 7, 1, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Downmix",
.info = snd_ac97_ad1888_downmix_info,
.get = snd_ac97_ad1888_downmix_get,
.put = snd_ac97_ad1888_downmix_put
},
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_CTL,
AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 10, 1, 0),
AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 12, 1, 0),
};
static int patch_ad1888_specific(struct snd_ac97 *ac97)
{
if (!ac97->spec.ad18xx.lo_as_master) {
/* rename 0x04 as "Master" and 0x02 as "Master Surround" */
snd_ac97_rename_vol_ctl(ac97, "Master Playback",
"Master Surround Playback");
snd_ac97_rename_vol_ctl(ac97, "Headphone Playback",
"Master Playback");
}
return patch_build_controls(ac97, snd_ac97_ad1888_controls, ARRAY_SIZE(snd_ac97_ad1888_controls));
}
static const struct snd_ac97_build_ops patch_ad1888_build_ops = {
.build_post_spdif = patch_ad198x_post_spdif,
.build_specific = patch_ad1888_specific,
#ifdef CONFIG_PM
.resume = ad1888_resume,
#endif
.update_jacks = ad1888_update_jacks,
};
static int patch_ad1888(struct snd_ac97 * ac97)
{
unsigned short misc;
patch_ad1881(ac97);
ac97->build_ops = &patch_ad1888_build_ops;
/*
* LO can be used as a real line-out on some devices,
* and we need to revert the front/surround mixer switches
*/
if (ac97->subsystem_vendor == 0x1043 &&
ac97->subsystem_device == 0x1193) /* ASUS A9T laptop */
ac97->spec.ad18xx.lo_as_master = 1;
misc = snd_ac97_read(ac97, AC97_AD_MISC);
/* AD-compatible mode */
/* Stereo mutes enabled */
misc |= AC97_AD198X_MSPLT | AC97_AD198X_AC97NC;
if (!ac97->spec.ad18xx.lo_as_master)
/* Switch FRONT/SURROUND LINE-OUT/HP-OUT default connection */
/* it seems that most vendors connect line-out connector to
* headphone out of AC'97
*/
misc |= AC97_AD198X_LOSEL | AC97_AD198X_HPSEL;
snd_ac97_write_cache(ac97, AC97_AD_MISC, misc);
ac97->flags |= AC97_STEREO_MUTES;
return 0;
}
static int patch_ad1980_specific(struct snd_ac97 *ac97)
{
int err;
if ((err = patch_ad1888_specific(ac97)) < 0)
return err;
return patch_build_controls(ac97, &snd_ac97_ad198x_2cmic, 1);
}
static const struct snd_ac97_build_ops patch_ad1980_build_ops = {
.build_post_spdif = patch_ad198x_post_spdif,
.build_specific = patch_ad1980_specific,
#ifdef CONFIG_PM
.resume = ad18xx_resume,
#endif
.update_jacks = ad1888_update_jacks,
};
static int patch_ad1980(struct snd_ac97 * ac97)
{
patch_ad1888(ac97);
ac97->build_ops = &patch_ad1980_build_ops;
return 0;
}
static int snd_ac97_ad1985_vrefout_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static char *texts[4] = {"High-Z", "3.7 V", "2.25 V", "0 V"};
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 4;
if (uinfo->value.enumerated.item > 3)
uinfo->value.enumerated.item = 3;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_ad1985_vrefout_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
static const int reg2ctrl[4] = {2, 0, 1, 3};
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = (ac97->regs[AC97_AD_MISC] & AC97_AD198X_VREF_MASK)
>> AC97_AD198X_VREF_SHIFT;
ucontrol->value.enumerated.item[0] = reg2ctrl[val];
return 0;
}
static int snd_ac97_ad1985_vrefout_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
static const int ctrl2reg[4] = {1, 2, 0, 3};
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
if (ucontrol->value.enumerated.item[0] > 3)
return -EINVAL;
val = ctrl2reg[ucontrol->value.enumerated.item[0]]
<< AC97_AD198X_VREF_SHIFT;
return snd_ac97_update_bits(ac97, AC97_AD_MISC,
AC97_AD198X_VREF_MASK, val);
}
static const struct snd_kcontrol_new snd_ac97_ad1985_controls[] = {
AC97_SINGLE("Exchange Center/LFE", AC97_AD_SERIAL_CFG, 3, 1, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Exchange Front/Surround",
.info = snd_ac97_ad1888_lohpsel_info,
.get = snd_ac97_ad1888_lohpsel_get,
.put = snd_ac97_ad1888_lohpsel_put
},
AC97_SINGLE("High Pass Filter Enable", AC97_AD_TEST2, 12, 1, 1),
AC97_SINGLE("Spread Front to Surround and Center/LFE",
AC97_AD_MISC, 7, 1, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Downmix",
.info = snd_ac97_ad1888_downmix_info,
.get = snd_ac97_ad1888_downmix_get,
.put = snd_ac97_ad1888_downmix_put
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "V_REFOUT",
.info = snd_ac97_ad1985_vrefout_info,
.get = snd_ac97_ad1985_vrefout_get,
.put = snd_ac97_ad1985_vrefout_put
},
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_CTL,
AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 10, 1, 0),
AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 12, 1, 0),
};
static void ad1985_update_jacks(struct snd_ac97 *ac97)
{
ad1888_update_jacks(ac97);
/* clear OMS if shared jack is to be used for C/LFE out */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 1 << 9,
is_shared_micin(ac97) ? 1 << 9 : 0);
}
static int patch_ad1985_specific(struct snd_ac97 *ac97)
{
int err;
/* rename 0x04 as "Master" and 0x02 as "Master Surround" */
snd_ac97_rename_vol_ctl(ac97, "Master Playback",
"Master Surround Playback");
snd_ac97_rename_vol_ctl(ac97, "Headphone Playback", "Master Playback");
if ((err = patch_build_controls(ac97, &snd_ac97_ad198x_2cmic, 1)) < 0)
return err;
return patch_build_controls(ac97, snd_ac97_ad1985_controls,
ARRAY_SIZE(snd_ac97_ad1985_controls));
}
static const struct snd_ac97_build_ops patch_ad1985_build_ops = {
.build_post_spdif = patch_ad198x_post_spdif,
.build_specific = patch_ad1985_specific,
#ifdef CONFIG_PM
.resume = ad18xx_resume,
#endif
.update_jacks = ad1985_update_jacks,
};
static int patch_ad1985(struct snd_ac97 * ac97)
{
unsigned short misc;
patch_ad1881(ac97);
ac97->build_ops = &patch_ad1985_build_ops;
misc = snd_ac97_read(ac97, AC97_AD_MISC);
/* switch front/surround line-out/hp-out */
/* AD-compatible mode */
/* Stereo mutes enabled */
snd_ac97_write_cache(ac97, AC97_AD_MISC, misc |
AC97_AD198X_LOSEL |
AC97_AD198X_HPSEL |
AC97_AD198X_MSPLT |
AC97_AD198X_AC97NC);
ac97->flags |= AC97_STEREO_MUTES;
/* update current jack configuration */
ad1985_update_jacks(ac97);
/* on AD1985 rev. 3, AC'97 revision bits are zero */
ac97->ext_id = (ac97->ext_id & ~AC97_EI_REV_MASK) | AC97_EI_REV_23;
return 0;
}
#define snd_ac97_ad1986_bool_info snd_ctl_boolean_mono_info
static int snd_ac97_ad1986_lososel_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_AD_MISC3];
ucontrol->value.integer.value[0] = (val & AC97_AD1986_LOSEL) != 0;
return 0;
}
static int snd_ac97_ad1986_lososel_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
int ret0;
int ret1;
int sprd = (ac97->regs[AC97_AD_MISC] & AC97_AD1986_SPRD) != 0;
ret0 = snd_ac97_update_bits(ac97, AC97_AD_MISC3, AC97_AD1986_LOSEL,
ucontrol->value.integer.value[0] != 0
? AC97_AD1986_LOSEL : 0);
if (ret0 < 0)
return ret0;
/* SOSEL is set to values of "Spread" or "Exchange F/S" controls */
ret1 = snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD1986_SOSEL,
(ucontrol->value.integer.value[0] != 0
|| sprd)
? AC97_AD1986_SOSEL : 0);
if (ret1 < 0)
return ret1;
return (ret0 > 0 || ret1 > 0) ? 1 : 0;
}
static int snd_ac97_ad1986_spread_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_AD_MISC];
ucontrol->value.integer.value[0] = (val & AC97_AD1986_SPRD) != 0;
return 0;
}
static int snd_ac97_ad1986_spread_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
int ret0;
int ret1;
int sprd = (ac97->regs[AC97_AD_MISC3] & AC97_AD1986_LOSEL) != 0;
ret0 = snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD1986_SPRD,
ucontrol->value.integer.value[0] != 0
? AC97_AD1986_SPRD : 0);
if (ret0 < 0)
return ret0;
/* SOSEL is set to values of "Spread" or "Exchange F/S" controls */
ret1 = snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD1986_SOSEL,
(ucontrol->value.integer.value[0] != 0
|| sprd)
? AC97_AD1986_SOSEL : 0);
if (ret1 < 0)
return ret1;
return (ret0 > 0 || ret1 > 0) ? 1 : 0;
}
static int snd_ac97_ad1986_miclisel_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = ac97->spec.ad18xx.swap_mic_linein;
return 0;
}
static int snd_ac97_ad1986_miclisel_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned char swap = ucontrol->value.integer.value[0] != 0;
if (swap != ac97->spec.ad18xx.swap_mic_linein) {
ac97->spec.ad18xx.swap_mic_linein = swap;
if (ac97->build_ops->update_jacks)
ac97->build_ops->update_jacks(ac97);
return 1;
}
return 0;
}
static int snd_ac97_ad1986_vrefout_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
/* Use MIC_1/2 V_REFOUT as the "get" value */
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
unsigned short reg = ac97->regs[AC97_AD_MISC2];
if ((reg & AC97_AD1986_MVREF0) != 0)
val = 2;
else if ((reg & AC97_AD1986_MVREF1) != 0)
val = 3;
else if ((reg & AC97_AD1986_MVREF2) != 0)
val = 1;
else
val = 0;
ucontrol->value.enumerated.item[0] = val;
return 0;
}
static int snd_ac97_ad1986_vrefout_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short cval;
unsigned short lval;
unsigned short mval;
int cret;
int lret;
int mret;
switch (ucontrol->value.enumerated.item[0])
{
case 0: /* High-Z */
cval = 0;
lval = 0;
mval = 0;
break;
case 1: /* 3.7 V */
cval = AC97_AD1986_CVREF2;
lval = AC97_AD1986_LVREF2;
mval = AC97_AD1986_MVREF2;
break;
case 2: /* 2.25 V */
cval = AC97_AD1986_CVREF0;
lval = AC97_AD1986_LVREF0;
mval = AC97_AD1986_MVREF0;
break;
case 3: /* 0 V */
cval = AC97_AD1986_CVREF1;
lval = AC97_AD1986_LVREF1;
mval = AC97_AD1986_MVREF1;
break;
default:
return -EINVAL;
}
cret = snd_ac97_update_bits(ac97, AC97_AD_MISC2,
AC97_AD1986_CVREF_MASK, cval);
if (cret < 0)
return cret;
lret = snd_ac97_update_bits(ac97, AC97_AD_MISC3,
AC97_AD1986_LVREF_MASK, lval);
if (lret < 0)
return lret;
mret = snd_ac97_update_bits(ac97, AC97_AD_MISC2,
AC97_AD1986_MVREF_MASK, mval);
if (mret < 0)
return mret;
return (cret > 0 || lret > 0 || mret > 0) ? 1 : 0;
}
static const struct snd_kcontrol_new snd_ac97_ad1986_controls[] = {
AC97_SINGLE("Exchange Center/LFE", AC97_AD_SERIAL_CFG, 3, 1, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Exchange Front/Surround",
.info = snd_ac97_ad1986_bool_info,
.get = snd_ac97_ad1986_lososel_get,
.put = snd_ac97_ad1986_lososel_put
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Exchange Mic/Line In",
.info = snd_ac97_ad1986_bool_info,
.get = snd_ac97_ad1986_miclisel_get,
.put = snd_ac97_ad1986_miclisel_put
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Spread Front to Surround and Center/LFE",
.info = snd_ac97_ad1986_bool_info,
.get = snd_ac97_ad1986_spread_get,
.put = snd_ac97_ad1986_spread_put
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Downmix",
.info = snd_ac97_ad1888_downmix_info,
.get = snd_ac97_ad1888_downmix_get,
.put = snd_ac97_ad1888_downmix_put
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "V_REFOUT",
.info = snd_ac97_ad1985_vrefout_info,
.get = snd_ac97_ad1986_vrefout_get,
.put = snd_ac97_ad1986_vrefout_put
},
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_CTL,
AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 10, 1, 0),
AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 12, 1, 0)
};
static void ad1986_update_jacks(struct snd_ac97 *ac97)
{
unsigned short misc_val = 0;
unsigned short ser_val;
/* disable SURROUND and CENTER/LFE if not surround mode */
if (!is_surround_on(ac97))
misc_val |= AC97_AD1986_SODIS;
if (!is_clfe_on(ac97))
misc_val |= AC97_AD1986_CLDIS;
/* select line input (default=LINE_IN, SURROUND or MIC_1/2) */
if (is_shared_linein(ac97))
misc_val |= AC97_AD1986_LISEL_SURR;
else if (ac97->spec.ad18xx.swap_mic_linein != 0)
misc_val |= AC97_AD1986_LISEL_MIC;
snd_ac97_update_bits(ac97, AC97_AD_MISC,
AC97_AD1986_SODIS | AC97_AD1986_CLDIS |
AC97_AD1986_LISEL_MASK,
misc_val);
/* select microphone input (MIC_1/2, Center/LFE or LINE_IN) */
if (is_shared_micin(ac97))
ser_val = AC97_AD1986_OMS_C;
else if (ac97->spec.ad18xx.swap_mic_linein != 0)
ser_val = AC97_AD1986_OMS_L;
else
ser_val = AC97_AD1986_OMS_M;
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG,
AC97_AD1986_OMS_MASK,
ser_val);
}
static int patch_ad1986_specific(struct snd_ac97 *ac97)
{
int err;
if ((err = patch_build_controls(ac97, &snd_ac97_ad198x_2cmic, 1)) < 0)
return err;
return patch_build_controls(ac97, snd_ac97_ad1986_controls,
ARRAY_SIZE(snd_ac97_ad1985_controls));
}
static const struct snd_ac97_build_ops patch_ad1986_build_ops = {
.build_post_spdif = patch_ad198x_post_spdif,
.build_specific = patch_ad1986_specific,
#ifdef CONFIG_PM
.resume = ad18xx_resume,
#endif
.update_jacks = ad1986_update_jacks,
};
static int patch_ad1986(struct snd_ac97 * ac97)
{
patch_ad1881(ac97);
ac97->build_ops = &patch_ad1986_build_ops;
ac97->flags |= AC97_STEREO_MUTES;
/* update current jack configuration */
ad1986_update_jacks(ac97);
return 0;
}
/*
* realtek ALC203: use mono-out for pin 37
*/
static int patch_alc203(struct snd_ac97 *ac97)
{
snd_ac97_update_bits(ac97, 0x7a, 0x400, 0x400);
return 0;
}
/*
* realtek ALC65x/850 codecs
*/
static void alc650_update_jacks(struct snd_ac97 *ac97)
{
int shared;
/* shared Line-In / Surround Out */
shared = is_shared_surrout(ac97);
snd_ac97_update_bits(ac97, AC97_ALC650_MULTICH, 1 << 9,
shared ? (1 << 9) : 0);
/* update shared Mic In / Center/LFE Out */
shared = is_shared_clfeout(ac97);
/* disable/enable vref */
snd_ac97_update_bits(ac97, AC97_ALC650_CLOCK, 1 << 12,
shared ? (1 << 12) : 0);
/* turn on/off center-on-mic */
snd_ac97_update_bits(ac97, AC97_ALC650_MULTICH, 1 << 10,
shared ? (1 << 10) : 0);
/* GPIO0 high for mic */
snd_ac97_update_bits(ac97, AC97_ALC650_GPIO_STATUS, 0x100,
shared ? 0 : 0x100);
}
static const struct snd_kcontrol_new snd_ac97_controls_alc650[] = {
AC97_SINGLE("Duplicate Front", AC97_ALC650_MULTICH, 0, 1, 0),
AC97_SINGLE("Surround Down Mix", AC97_ALC650_MULTICH, 1, 1, 0),
AC97_SINGLE("Center/LFE Down Mix", AC97_ALC650_MULTICH, 2, 1, 0),
AC97_SINGLE("Exchange Center/LFE", AC97_ALC650_MULTICH, 3, 1, 0),
/* 4: Analog Input To Surround */
/* 5: Analog Input To Center/LFE */
/* 6: Independent Master Volume Right */
/* 7: Independent Master Volume Left */
/* 8: reserved */
/* 9: Line-In/Surround share */
/* 10: Mic/CLFE share */
/* 11-13: in IEC958 controls */
AC97_SINGLE("Swap Surround Slot", AC97_ALC650_MULTICH, 14, 1, 0),
#if 0 /* always set in patch_alc650 */
AC97_SINGLE("IEC958 Input Clock Enable", AC97_ALC650_CLOCK, 0, 1, 0),
AC97_SINGLE("IEC958 Input Pin Enable", AC97_ALC650_CLOCK, 1, 1, 0),
AC97_SINGLE("Surround DAC Switch", AC97_ALC650_SURR_DAC_VOL, 15, 1, 1),
AC97_DOUBLE("Surround DAC Volume", AC97_ALC650_SURR_DAC_VOL, 8, 0, 31, 1),
AC97_SINGLE("Center/LFE DAC Switch", AC97_ALC650_LFE_DAC_VOL, 15, 1, 1),
AC97_DOUBLE("Center/LFE DAC Volume", AC97_ALC650_LFE_DAC_VOL, 8, 0, 31, 1),
#endif
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_CTL,
};
static const struct snd_kcontrol_new snd_ac97_spdif_controls_alc650[] = {
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), AC97_ALC650_MULTICH, 11, 1, 0),
AC97_SINGLE("Analog to IEC958 Output", AC97_ALC650_MULTICH, 12, 1, 0),
/* disable this controls since it doesn't work as expected */
/* AC97_SINGLE("IEC958 Input Monitor", AC97_ALC650_MULTICH, 13, 1, 0), */
};
static const DECLARE_TLV_DB_SCALE(db_scale_5bit_3db_max, -4350, 150, 0);
static int patch_alc650_specific(struct snd_ac97 * ac97)
{
int err;
if ((err = patch_build_controls(ac97, snd_ac97_controls_alc650, ARRAY_SIZE(snd_ac97_controls_alc650))) < 0)
return err;
if (ac97->ext_id & AC97_EI_SPDIF) {
if ((err = patch_build_controls(ac97, snd_ac97_spdif_controls_alc650, ARRAY_SIZE(snd_ac97_spdif_controls_alc650))) < 0)
return err;
}
if (ac97->id != AC97_ID_ALC650F)
reset_tlv(ac97, "Master Playback Volume",
db_scale_5bit_3db_max);
return 0;
}
static const struct snd_ac97_build_ops patch_alc650_ops = {
.build_specific = patch_alc650_specific,
.update_jacks = alc650_update_jacks
};
static int patch_alc650(struct snd_ac97 * ac97)
{
unsigned short val;
ac97->build_ops = &patch_alc650_ops;
/* determine the revision */
val = snd_ac97_read(ac97, AC97_ALC650_REVISION) & 0x3f;
if (val < 3)
ac97->id = 0x414c4720; /* Old version */
else if (val < 0x10)
ac97->id = 0x414c4721; /* D version */
else if (val < 0x20)
ac97->id = 0x414c4722; /* E version */
else if (val < 0x30)
ac97->id = 0x414c4723; /* F version */
/* revision E or F */
/* FIXME: what about revision D ? */
ac97->spec.dev_flags = (ac97->id == 0x414c4722 ||
ac97->id == 0x414c4723);
/* enable AC97_ALC650_GPIO_SETUP, AC97_ALC650_CLOCK for R/W */
snd_ac97_write_cache(ac97, AC97_ALC650_GPIO_STATUS,
snd_ac97_read(ac97, AC97_ALC650_GPIO_STATUS) | 0x8000);
/* Enable SPDIF-IN only on Rev.E and above */
val = snd_ac97_read(ac97, AC97_ALC650_CLOCK);
/* SPDIF IN with pin 47 */
if (ac97->spec.dev_flags &&
/* ASUS A6KM requires EAPD */
! (ac97->subsystem_vendor == 0x1043 &&
ac97->subsystem_device == 0x1103))
val |= 0x03; /* enable */
else
val &= ~0x03; /* disable */
snd_ac97_write_cache(ac97, AC97_ALC650_CLOCK, val);
/* set default: slot 3,4,7,8,6,9
spdif-in monitor off, analog-spdif off, spdif-in off
center on mic off, surround on line-in off
downmix off, duplicate front off
*/
snd_ac97_write_cache(ac97, AC97_ALC650_MULTICH, 0);
/* set GPIO0 for mic bias */
/* GPIO0 pin output, no interrupt, high */
snd_ac97_write_cache(ac97, AC97_ALC650_GPIO_SETUP,
snd_ac97_read(ac97, AC97_ALC650_GPIO_SETUP) | 0x01);
snd_ac97_write_cache(ac97, AC97_ALC650_GPIO_STATUS,
(snd_ac97_read(ac97, AC97_ALC650_GPIO_STATUS) | 0x100) & ~0x10);
/* full DAC volume */
snd_ac97_write_cache(ac97, AC97_ALC650_SURR_DAC_VOL, 0x0808);
snd_ac97_write_cache(ac97, AC97_ALC650_LFE_DAC_VOL, 0x0808);
return 0;
}
static void alc655_update_jacks(struct snd_ac97 *ac97)
{
int shared;
/* shared Line-In / Surround Out */
shared = is_shared_surrout(ac97);
ac97_update_bits_page(ac97, AC97_ALC650_MULTICH, 1 << 9,
shared ? (1 << 9) : 0, 0);
/* update shared Mic In / Center/LFE Out */
shared = is_shared_clfeout(ac97);
/* misc control; vrefout disable */
snd_ac97_update_bits(ac97, AC97_ALC650_CLOCK, 1 << 12,
shared ? (1 << 12) : 0);
ac97_update_bits_page(ac97, AC97_ALC650_MULTICH, 1 << 10,
shared ? (1 << 10) : 0, 0);
}
static const struct snd_kcontrol_new snd_ac97_controls_alc655[] = {
AC97_PAGE_SINGLE("Duplicate Front", AC97_ALC650_MULTICH, 0, 1, 0, 0),
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_CTL,
};
static int alc655_iec958_route_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts_655[3] = { "PCM", "Analog In", "IEC958 In" };
static char *texts_658[4] = { "PCM", "Analog1 In", "Analog2 In", "IEC958 In" };
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = ac97->spec.dev_flags ? 4 : 3;
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
uinfo->value.enumerated.item = uinfo->value.enumerated.items - 1;
strcpy(uinfo->value.enumerated.name,
ac97->spec.dev_flags ?
texts_658[uinfo->value.enumerated.item] :
texts_655[uinfo->value.enumerated.item]);
return 0;
}
static int alc655_iec958_route_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_ALC650_MULTICH];
val = (val >> 12) & 3;
if (ac97->spec.dev_flags && val == 3)
val = 0;
ucontrol->value.enumerated.item[0] = val;
return 0;
}
static int alc655_iec958_route_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
return ac97_update_bits_page(ac97, AC97_ALC650_MULTICH, 3 << 12,
(unsigned short)ucontrol->value.enumerated.item[0] << 12,
0);
}
static const struct snd_kcontrol_new snd_ac97_spdif_controls_alc655[] = {
AC97_PAGE_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), AC97_ALC650_MULTICH, 11, 1, 0, 0),
/* disable this controls since it doesn't work as expected */
/* AC97_PAGE_SINGLE("IEC958 Input Monitor", AC97_ALC650_MULTICH, 14, 1, 0, 0), */
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
.info = alc655_iec958_route_info,
.get = alc655_iec958_route_get,
.put = alc655_iec958_route_put,
},
};
static int patch_alc655_specific(struct snd_ac97 * ac97)
{
int err;
if ((err = patch_build_controls(ac97, snd_ac97_controls_alc655, ARRAY_SIZE(snd_ac97_controls_alc655))) < 0)
return err;
if (ac97->ext_id & AC97_EI_SPDIF) {
if ((err = patch_build_controls(ac97, snd_ac97_spdif_controls_alc655, ARRAY_SIZE(snd_ac97_spdif_controls_alc655))) < 0)
return err;
}
return 0;
}
static const struct snd_ac97_build_ops patch_alc655_ops = {
.build_specific = patch_alc655_specific,
.update_jacks = alc655_update_jacks
};
static int patch_alc655(struct snd_ac97 * ac97)
{
unsigned int val;
if (ac97->id == AC97_ID_ALC658) {
ac97->spec.dev_flags = 1; /* ALC658 */
if ((snd_ac97_read(ac97, AC97_ALC650_REVISION) & 0x3f) == 2) {
ac97->id = AC97_ID_ALC658D;
ac97->spec.dev_flags = 2;
}
}
ac97->build_ops = &patch_alc655_ops;
/* assume only page 0 for writing cache */
snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, AC97_PAGE_VENDOR);
/* adjust default values */
val = snd_ac97_read(ac97, 0x7a); /* misc control */
if (ac97->spec.dev_flags) /* ALC658 */
val &= ~(1 << 1); /* Pin 47 is spdif input pin */
else { /* ALC655 */
if (ac97->subsystem_vendor == 0x1462 &&
(ac97->subsystem_device == 0x0131 || /* MSI S270 laptop */
ac97->subsystem_device == 0x0161 || /* LG K1 Express */
ac97->subsystem_device == 0x0351 || /* MSI L725 laptop */
ac97->subsystem_device == 0x0471 || /* MSI L720 laptop */
ac97->subsystem_device == 0x0061)) /* MSI S250 laptop */
val &= ~(1 << 1); /* Pin 47 is EAPD (for internal speaker) */
else
val |= (1 << 1); /* Pin 47 is spdif input pin */
/* this seems missing on some hardwares */
ac97->ext_id |= AC97_EI_SPDIF;
}
val &= ~(1 << 12); /* vref enable */
snd_ac97_write_cache(ac97, 0x7a, val);
/* set default: spdif-in enabled,
spdif-in monitor off, spdif-in PCM off
center on mic off, surround on line-in off
duplicate front off
*/
snd_ac97_write_cache(ac97, AC97_ALC650_MULTICH, 1<<15);
/* full DAC volume */
snd_ac97_write_cache(ac97, AC97_ALC650_SURR_DAC_VOL, 0x0808);
snd_ac97_write_cache(ac97, AC97_ALC650_LFE_DAC_VOL, 0x0808);
/* update undocumented bit... */
if (ac97->id == AC97_ID_ALC658D)
snd_ac97_update_bits(ac97, 0x74, 0x0800, 0x0800);
return 0;
}
#define AC97_ALC850_JACK_SELECT 0x76
#define AC97_ALC850_MISC1 0x7a
#define AC97_ALC850_MULTICH 0x6a
static void alc850_update_jacks(struct snd_ac97 *ac97)
{
int shared;
int aux_is_back_surround;
/* shared Line-In / Surround Out */
shared = is_shared_surrout(ac97);
/* SURR 1kOhm (bit4), Amp (bit5) */
snd_ac97_update_bits(ac97, AC97_ALC850_MISC1, (1<<4)|(1<<5),
shared ? (1<<5) : (1<<4));
/* LINE-IN = 0, SURROUND = 2 */
snd_ac97_update_bits(ac97, AC97_ALC850_JACK_SELECT, 7 << 12,
shared ? (2<<12) : (0<<12));
/* update shared Mic In / Center/LFE Out */
shared = is_shared_clfeout(ac97);
/* Vref disable (bit12), 1kOhm (bit13) */
snd_ac97_update_bits(ac97, AC97_ALC850_MISC1, (1<<12)|(1<<13),
shared ? (1<<12) : (1<<13));
/* MIC-IN = 1, CENTER-LFE = 5 */
snd_ac97_update_bits(ac97, AC97_ALC850_JACK_SELECT, 7 << 4,
shared ? (5<<4) : (1<<4));
aux_is_back_surround = alc850_is_aux_back_surround(ac97);
/* Aux is Back Surround */
snd_ac97_update_bits(ac97, AC97_ALC850_MULTICH, 1 << 10,
aux_is_back_surround ? (1<<10) : (0<<10));
}
static const struct snd_kcontrol_new snd_ac97_controls_alc850[] = {
AC97_PAGE_SINGLE("Duplicate Front", AC97_ALC650_MULTICH, 0, 1, 0, 0),
AC97_SINGLE("Mic Front Input Switch", AC97_ALC850_JACK_SELECT, 15, 1, 1),
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_8CH_CTL,
};
static int patch_alc850_specific(struct snd_ac97 *ac97)
{
int err;
if ((err = patch_build_controls(ac97, snd_ac97_controls_alc850, ARRAY_SIZE(snd_ac97_controls_alc850))) < 0)
return err;
if (ac97->ext_id & AC97_EI_SPDIF) {
if ((err = patch_build_controls(ac97, snd_ac97_spdif_controls_alc655, ARRAY_SIZE(snd_ac97_spdif_controls_alc655))) < 0)
return err;
}
return 0;
}
static const struct snd_ac97_build_ops patch_alc850_ops = {
.build_specific = patch_alc850_specific,
.update_jacks = alc850_update_jacks
};
static int patch_alc850(struct snd_ac97 *ac97)
{
ac97->build_ops = &patch_alc850_ops;
ac97->spec.dev_flags = 0; /* for IEC958 playback route - ALC655 compatible */
ac97->flags |= AC97_HAS_8CH;
/* assume only page 0 for writing cache */
snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, AC97_PAGE_VENDOR);
/* adjust default values */
/* set default: spdif-in enabled,
spdif-in monitor off, spdif-in PCM off
center on mic off, surround on line-in off
duplicate front off
NB default bit 10=0 = Aux is Capture, not Back Surround
*/
snd_ac97_write_cache(ac97, AC97_ALC650_MULTICH, 1<<15);
/* SURR_OUT: on, Surr 1kOhm: on, Surr Amp: off, Front 1kOhm: off
* Front Amp: on, Vref: enable, Center 1kOhm: on, Mix: on
*/
snd_ac97_write_cache(ac97, 0x7a, (1<<1)|(1<<4)|(0<<5)|(1<<6)|
(1<<7)|(0<<12)|(1<<13)|(0<<14));
/* detection UIO2,3: all path floating, UIO3: MIC, Vref2: disable,
* UIO1: FRONT, Vref3: disable, UIO3: LINE, Front-Mic: mute
*/
snd_ac97_write_cache(ac97, 0x76, (0<<0)|(0<<2)|(1<<4)|(1<<7)|(2<<8)|
(1<<11)|(0<<12)|(1<<15));
/* full DAC volume */
snd_ac97_write_cache(ac97, AC97_ALC650_SURR_DAC_VOL, 0x0808);
snd_ac97_write_cache(ac97, AC97_ALC650_LFE_DAC_VOL, 0x0808);
return 0;
}
static int patch_aztech_azf3328_specific(struct snd_ac97 *ac97)
{
struct snd_kcontrol *kctl_3d_center =
snd_ac97_find_mixer_ctl(ac97, "3D Control - Center");
struct snd_kcontrol *kctl_3d_depth =
snd_ac97_find_mixer_ctl(ac97, "3D Control - Depth");
/*
* 3D register is different from AC97 standard layout
* (also do some renaming, to resemble Windows driver naming)
*/
if (kctl_3d_center) {
kctl_3d_center->private_value =
AC97_SINGLE_VALUE(AC97_3D_CONTROL, 1, 0x07, 0);
snd_ac97_rename_vol_ctl(ac97,
"3D Control - Center", "3D Control - Width"
);
}
if (kctl_3d_depth)
kctl_3d_depth->private_value =
AC97_SINGLE_VALUE(AC97_3D_CONTROL, 8, 0x03, 0);
/* Aztech Windows driver calls the
equivalent control "Modem Playback", thus rename it: */
snd_ac97_rename_vol_ctl(ac97,
"Master Mono Playback", "Modem Playback"
);
snd_ac97_rename_vol_ctl(ac97,
"Headphone Playback", "FM Synth Playback"
);
return 0;
}
static const struct snd_ac97_build_ops patch_aztech_azf3328_ops = {
.build_specific = patch_aztech_azf3328_specific
};
static int patch_aztech_azf3328(struct snd_ac97 *ac97)
{
ac97->build_ops = &patch_aztech_azf3328_ops;
return 0;
}
/*
* C-Media CM97xx codecs
*/
static void cm9738_update_jacks(struct snd_ac97 *ac97)
{
/* shared Line-In / Surround Out */
snd_ac97_update_bits(ac97, AC97_CM9738_VENDOR_CTRL, 1 << 10,
is_shared_surrout(ac97) ? (1 << 10) : 0);
}
static const struct snd_kcontrol_new snd_ac97_cm9738_controls[] = {
AC97_SINGLE("Duplicate Front", AC97_CM9738_VENDOR_CTRL, 13, 1, 0),
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_4CH_CTL,
};
static int patch_cm9738_specific(struct snd_ac97 * ac97)
{
return patch_build_controls(ac97, snd_ac97_cm9738_controls, ARRAY_SIZE(snd_ac97_cm9738_controls));
}
static const struct snd_ac97_build_ops patch_cm9738_ops = {
.build_specific = patch_cm9738_specific,
.update_jacks = cm9738_update_jacks
};
static int patch_cm9738(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_cm9738_ops;
/* FIXME: can anyone confirm below? */
/* CM9738 has no PCM volume although the register reacts */
ac97->flags |= AC97_HAS_NO_PCM_VOL;
snd_ac97_write_cache(ac97, AC97_PCM, 0x8000);
return 0;
}
static int snd_ac97_cmedia_spdif_playback_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[] = { "Analog", "Digital" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item > 1)
uinfo->value.enumerated.item = 1;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int snd_ac97_cmedia_spdif_playback_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
unsigned short val;
val = ac97->regs[AC97_CM9739_SPDIF_CTRL];
ucontrol->value.enumerated.item[0] = (val >> 1) & 0x01;
return 0;
}
static int snd_ac97_cmedia_spdif_playback_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
return snd_ac97_update_bits(ac97, AC97_CM9739_SPDIF_CTRL,
0x01 << 1,
(ucontrol->value.enumerated.item[0] & 0x01) << 1);
}
static const struct snd_kcontrol_new snd_ac97_cm9739_controls_spdif[] = {
/* BIT 0: SPDI_EN - always true */
{ /* BIT 1: SPDIFS */
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
.info = snd_ac97_cmedia_spdif_playback_source_info,
.get = snd_ac97_cmedia_spdif_playback_source_get,
.put = snd_ac97_cmedia_spdif_playback_source_put,
},
/* BIT 2: IG_SPIV */
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,NONE) "Valid Switch", AC97_CM9739_SPDIF_CTRL, 2, 1, 0),
/* BIT 3: SPI2F */
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,NONE) "Monitor", AC97_CM9739_SPDIF_CTRL, 3, 1, 0),
/* BIT 4: SPI2SDI */
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), AC97_CM9739_SPDIF_CTRL, 4, 1, 0),
/* BIT 8: SPD32 - 32bit SPDIF - not supported yet */
};
static void cm9739_update_jacks(struct snd_ac97 *ac97)
{
/* shared Line-In / Surround Out */
snd_ac97_update_bits(ac97, AC97_CM9739_MULTI_CHAN, 1 << 10,
is_shared_surrout(ac97) ? (1 << 10) : 0);
/* shared Mic In / Center/LFE Out **/
snd_ac97_update_bits(ac97, AC97_CM9739_MULTI_CHAN, 0x3000,
is_shared_clfeout(ac97) ? 0x1000 : 0x2000);
}
static const struct snd_kcontrol_new snd_ac97_cm9739_controls[] = {
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_CTL,
};
static int patch_cm9739_specific(struct snd_ac97 * ac97)
{
return patch_build_controls(ac97, snd_ac97_cm9739_controls, ARRAY_SIZE(snd_ac97_cm9739_controls));
}
static int patch_cm9739_post_spdif(struct snd_ac97 * ac97)
{
return patch_build_controls(ac97, snd_ac97_cm9739_controls_spdif, ARRAY_SIZE(snd_ac97_cm9739_controls_spdif));
}
static const struct snd_ac97_build_ops patch_cm9739_ops = {
.build_specific = patch_cm9739_specific,
.build_post_spdif = patch_cm9739_post_spdif,
.update_jacks = cm9739_update_jacks
};
static int patch_cm9739(struct snd_ac97 * ac97)
{
unsigned short val;
ac97->build_ops = &patch_cm9739_ops;
/* CM9739/A has no Master and PCM volume although the register reacts */
ac97->flags |= AC97_HAS_NO_MASTER_VOL | AC97_HAS_NO_PCM_VOL;
snd_ac97_write_cache(ac97, AC97_MASTER, 0x8000);
snd_ac97_write_cache(ac97, AC97_PCM, 0x8000);
/* check spdif */
val = snd_ac97_read(ac97, AC97_EXTENDED_STATUS);
if (val & AC97_EA_SPCV) {
/* enable spdif in */
snd_ac97_write_cache(ac97, AC97_CM9739_SPDIF_CTRL,
snd_ac97_read(ac97, AC97_CM9739_SPDIF_CTRL) | 0x01);
ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */
} else {
ac97->ext_id &= ~AC97_EI_SPDIF; /* disable extended-id */
ac97->rates[AC97_RATES_SPDIF] = 0;
}
/* set-up multi channel */
/* bit 14: 0 = SPDIF, 1 = EAPD */
/* bit 13: enable internal vref output for mic */
/* bit 12: disable center/lfe (swithable) */
/* bit 10: disable surround/line (switchable) */
/* bit 9: mix 2 surround off */
/* bit 4: undocumented; 0 mutes the CM9739A, which defaults to 1 */
/* bit 3: undocumented; surround? */
/* bit 0: dB */
val = snd_ac97_read(ac97, AC97_CM9739_MULTI_CHAN) & (1 << 4);
val |= (1 << 3);
val |= (1 << 13);
if (! (ac97->ext_id & AC97_EI_SPDIF))
val |= (1 << 14);
snd_ac97_write_cache(ac97, AC97_CM9739_MULTI_CHAN, val);
/* FIXME: set up GPIO */
snd_ac97_write_cache(ac97, 0x70, 0x0100);
snd_ac97_write_cache(ac97, 0x72, 0x0020);
/* Special exception for ASUS W1000/CMI9739. It does not have an SPDIF in. */
if (ac97->pci &&
ac97->subsystem_vendor == 0x1043 &&
ac97->subsystem_device == 0x1843) {
snd_ac97_write_cache(ac97, AC97_CM9739_SPDIF_CTRL,
snd_ac97_read(ac97, AC97_CM9739_SPDIF_CTRL) & ~0x01);
snd_ac97_write_cache(ac97, AC97_CM9739_MULTI_CHAN,
snd_ac97_read(ac97, AC97_CM9739_MULTI_CHAN) | (1 << 14));
}
return 0;
}
#define AC97_CM9761_MULTI_CHAN 0x64
#define AC97_CM9761_FUNC 0x66
#define AC97_CM9761_SPDIF_CTRL 0x6c
static void cm9761_update_jacks(struct snd_ac97 *ac97)
{
/* FIXME: check the bits for each model
* model 83 is confirmed to work
*/
static unsigned short surr_on[3][2] = {
{ 0x0008, 0x0000 }, /* 9761-78 & 82 */
{ 0x0000, 0x0008 }, /* 9761-82 rev.B */
{ 0x0000, 0x0008 }, /* 9761-83 */
};
static unsigned short clfe_on[3][2] = {
{ 0x0000, 0x1000 }, /* 9761-78 & 82 */
{ 0x1000, 0x0000 }, /* 9761-82 rev.B */
{ 0x0000, 0x1000 }, /* 9761-83 */
};
static unsigned short surr_shared[3][2] = {
{ 0x0000, 0x0400 }, /* 9761-78 & 82 */
{ 0x0000, 0x0400 }, /* 9761-82 rev.B */
{ 0x0000, 0x0400 }, /* 9761-83 */
};
static unsigned short clfe_shared[3][2] = {
{ 0x2000, 0x0880 }, /* 9761-78 & 82 */
{ 0x0000, 0x2880 }, /* 9761-82 rev.B */
{ 0x2000, 0x0800 }, /* 9761-83 */
};
unsigned short val = 0;
val |= surr_on[ac97->spec.dev_flags][is_surround_on(ac97)];
val |= clfe_on[ac97->spec.dev_flags][is_clfe_on(ac97)];
val |= surr_shared[ac97->spec.dev_flags][is_shared_surrout(ac97)];
val |= clfe_shared[ac97->spec.dev_flags][is_shared_clfeout(ac97)];
snd_ac97_update_bits(ac97, AC97_CM9761_MULTI_CHAN, 0x3c88, val);
}
static const struct snd_kcontrol_new snd_ac97_cm9761_controls[] = {
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_CTL,
};
static int cm9761_spdif_out_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[] = { "AC-Link", "ADC", "SPDIF-In" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 3;
if (uinfo->value.enumerated.item > 2)
uinfo->value.enumerated.item = 2;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int cm9761_spdif_out_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
if (ac97->regs[AC97_CM9761_FUNC] & 0x1)
ucontrol->value.enumerated.item[0] = 2; /* SPDIF-loopback */
else if (ac97->regs[AC97_CM9761_SPDIF_CTRL] & 0x2)
ucontrol->value.enumerated.item[0] = 1; /* ADC loopback */
else
ucontrol->value.enumerated.item[0] = 0; /* AC-link */
return 0;
}
static int cm9761_spdif_out_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol);
if (ucontrol->value.enumerated.item[0] == 2)
return snd_ac97_update_bits(ac97, AC97_CM9761_FUNC, 0x1, 0x1);
snd_ac97_update_bits(ac97, AC97_CM9761_FUNC, 0x1, 0);
return snd_ac97_update_bits(ac97, AC97_CM9761_SPDIF_CTRL, 0x2,
ucontrol->value.enumerated.item[0] == 1 ? 0x2 : 0);
}
static const char *cm9761_dac_clock[] = { "AC-Link", "SPDIF-In", "Both" };
static const struct ac97_enum cm9761_dac_clock_enum =
AC97_ENUM_SINGLE(AC97_CM9761_SPDIF_CTRL, 9, 3, cm9761_dac_clock);
static const struct snd_kcontrol_new snd_ac97_cm9761_controls_spdif[] = {
{ /* BIT 1: SPDIFS */
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
.info = cm9761_spdif_out_source_info,
.get = cm9761_spdif_out_source_get,
.put = cm9761_spdif_out_source_put,
},
/* BIT 2: IG_SPIV */
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,NONE) "Valid Switch", AC97_CM9761_SPDIF_CTRL, 2, 1, 0),
/* BIT 3: SPI2F */
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,NONE) "Monitor", AC97_CM9761_SPDIF_CTRL, 3, 1, 0),
/* BIT 4: SPI2SDI */
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), AC97_CM9761_SPDIF_CTRL, 4, 1, 0),
/* BIT 9-10: DAC_CTL */
AC97_ENUM("DAC Clock Source", cm9761_dac_clock_enum),
};
static int patch_cm9761_post_spdif(struct snd_ac97 * ac97)
{
return patch_build_controls(ac97, snd_ac97_cm9761_controls_spdif, ARRAY_SIZE(snd_ac97_cm9761_controls_spdif));
}
static int patch_cm9761_specific(struct snd_ac97 * ac97)
{
return patch_build_controls(ac97, snd_ac97_cm9761_controls, ARRAY_SIZE(snd_ac97_cm9761_controls));
}
static const struct snd_ac97_build_ops patch_cm9761_ops = {
.build_specific = patch_cm9761_specific,
.build_post_spdif = patch_cm9761_post_spdif,
.update_jacks = cm9761_update_jacks
};
static int patch_cm9761(struct snd_ac97 *ac97)
{
unsigned short val;
/* CM9761 has no PCM volume although the register reacts */
/* Master volume seems to have _some_ influence on the analog
* input sounds
*/
ac97->flags |= /*AC97_HAS_NO_MASTER_VOL |*/ AC97_HAS_NO_PCM_VOL;
snd_ac97_write_cache(ac97, AC97_MASTER, 0x8808);
snd_ac97_write_cache(ac97, AC97_PCM, 0x8808);
ac97->spec.dev_flags = 0; /* 1 = model 82 revision B, 2 = model 83 */
if (ac97->id == AC97_ID_CM9761_82) {
unsigned short tmp;
/* check page 1, reg 0x60 */
val = snd_ac97_read(ac97, AC97_INT_PAGING);
snd_ac97_write_cache(ac97, AC97_INT_PAGING, (val & ~0x0f) | 0x01);
tmp = snd_ac97_read(ac97, 0x60);
ac97->spec.dev_flags = tmp & 1; /* revision B? */
snd_ac97_write_cache(ac97, AC97_INT_PAGING, val);
} else if (ac97->id == AC97_ID_CM9761_83)
ac97->spec.dev_flags = 2;
ac97->build_ops = &patch_cm9761_ops;
/* enable spdif */
/* force the SPDIF bit in ext_id - codec doesn't set this bit! */
ac97->ext_id |= AC97_EI_SPDIF;
/* to be sure: we overwrite the ext status bits */
snd_ac97_write_cache(ac97, AC97_EXTENDED_STATUS, 0x05c0);
/* Don't set 0x0200 here. This results in the silent analog output */
snd_ac97_write_cache(ac97, AC97_CM9761_SPDIF_CTRL, 0x0001); /* enable spdif-in */
ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */
/* set-up multi channel */
/* bit 15: pc master beep off
* bit 14: pin47 = EAPD/SPDIF
* bit 13: vref ctl [= cm9739]
* bit 12: CLFE control (reverted on rev B)
* bit 11: Mic/center share (reverted on rev B)
* bit 10: suddound/line share
* bit 9: Analog-in mix -> surround
* bit 8: Analog-in mix -> CLFE
* bit 7: Mic/LFE share (mic/center/lfe)
* bit 5: vref select (9761A)
* bit 4: front control
* bit 3: surround control (revereted with rev B)
* bit 2: front mic
* bit 1: stereo mic
* bit 0: mic boost level (0=20dB, 1=30dB)
*/
#if 0
if (ac97->spec.dev_flags)
val = 0x0214;
else
val = 0x321c;
#endif
val = snd_ac97_read(ac97, AC97_CM9761_MULTI_CHAN);
val |= (1 << 4); /* front on */
snd_ac97_write_cache(ac97, AC97_CM9761_MULTI_CHAN, val);
/* FIXME: set up GPIO */
snd_ac97_write_cache(ac97, 0x70, 0x0100);
snd_ac97_write_cache(ac97, 0x72, 0x0020);
return 0;
}
#define AC97_CM9780_SIDE 0x60
#define AC97_CM9780_JACK 0x62
#define AC97_CM9780_MIXER 0x64
#define AC97_CM9780_MULTI_CHAN 0x66
#define AC97_CM9780_SPDIF 0x6c
static const char *cm9780_ch_select[] = { "Front", "Side", "Center/LFE", "Rear" };
static const struct ac97_enum cm9780_ch_select_enum =
AC97_ENUM_SINGLE(AC97_CM9780_MULTI_CHAN, 6, 4, cm9780_ch_select);
static const struct snd_kcontrol_new cm9780_controls[] = {
AC97_DOUBLE("Side Playback Switch", AC97_CM9780_SIDE, 15, 7, 1, 1),
AC97_DOUBLE("Side Playback Volume", AC97_CM9780_SIDE, 8, 0, 31, 0),
AC97_ENUM("Side Playback Route", cm9780_ch_select_enum),
};
static int patch_cm9780_specific(struct snd_ac97 *ac97)
{
return patch_build_controls(ac97, cm9780_controls, ARRAY_SIZE(cm9780_controls));
}
static const struct snd_ac97_build_ops patch_cm9780_ops = {
.build_specific = patch_cm9780_specific,
.build_post_spdif = patch_cm9761_post_spdif /* identical with CM9761 */
};
static int patch_cm9780(struct snd_ac97 *ac97)
{
unsigned short val;
ac97->build_ops = &patch_cm9780_ops;
/* enable spdif */
if (ac97->ext_id & AC97_EI_SPDIF) {
ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */
val = snd_ac97_read(ac97, AC97_CM9780_SPDIF);
val |= 0x1; /* SPDI_EN */
snd_ac97_write_cache(ac97, AC97_CM9780_SPDIF, val);
}
return 0;
}
/*
* VIA VT1616 codec
*/
static const struct snd_kcontrol_new snd_ac97_controls_vt1616[] = {
AC97_SINGLE("DC Offset removal", 0x5a, 10, 1, 0),
AC97_SINGLE("Alternate Level to Surround Out", 0x5a, 15, 1, 0),
AC97_SINGLE("Downmix LFE and Center to Front", 0x5a, 12, 1, 0),
AC97_SINGLE("Downmix Surround to Front", 0x5a, 11, 1, 0),
};
static const char *slave_vols_vt1616[] = {
"Front Playback Volume",
"Surround Playback Volume",
"Center Playback Volume",
"LFE Playback Volume",
NULL
};
static const char *slave_sws_vt1616[] = {
"Front Playback Switch",
"Surround Playback Switch",
"Center Playback Switch",
"LFE Playback Switch",
NULL
};
/* find a mixer control element with the given name */
static struct snd_kcontrol *snd_ac97_find_mixer_ctl(struct snd_ac97 *ac97,
const char *name)
{
struct snd_ctl_elem_id id;
memset(&id, 0, sizeof(id));
id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
strcpy(id.name, name);
return snd_ctl_find_id(ac97->bus->card, &id);
}
/* create a virtual master control and add slaves */
static int snd_ac97_add_vmaster(struct snd_ac97 *ac97, char *name,
const unsigned int *tlv, const char **slaves)
{
struct snd_kcontrol *kctl;
const char **s;
int err;
kctl = snd_ctl_make_virtual_master(name, tlv);
if (!kctl)
return -ENOMEM;
err = snd_ctl_add(ac97->bus->card, kctl);
if (err < 0)
return err;
for (s = slaves; *s; s++) {
struct snd_kcontrol *sctl;
sctl = snd_ac97_find_mixer_ctl(ac97, *s);
if (!sctl) {
snd_printdd("Cannot find slave %s, skipped\n", *s);
continue;
}
err = snd_ctl_add_slave(kctl, sctl);
if (err < 0)
return err;
}
return 0;
}
static int patch_vt1616_specific(struct snd_ac97 * ac97)
{
struct snd_kcontrol *kctl;
int err;
if (snd_ac97_try_bit(ac97, 0x5a, 9))
if ((err = patch_build_controls(ac97, &snd_ac97_controls_vt1616[0], 1)) < 0)
return err;
if ((err = patch_build_controls(ac97, &snd_ac97_controls_vt1616[1], ARRAY_SIZE(snd_ac97_controls_vt1616) - 1)) < 0)
return err;
/* There is already a misnamed master switch. Rename it. */
kctl = snd_ac97_find_mixer_ctl(ac97, "Master Playback Volume");
if (!kctl)
return -EINVAL;
snd_ac97_rename_vol_ctl(ac97, "Master Playback", "Front Playback");
err = snd_ac97_add_vmaster(ac97, "Master Playback Volume",
kctl->tlv.p, slave_vols_vt1616);
if (err < 0)
return err;
err = snd_ac97_add_vmaster(ac97, "Master Playback Switch",
NULL, slave_sws_vt1616);
if (err < 0)
return err;
return 0;
}
static const struct snd_ac97_build_ops patch_vt1616_ops = {
.build_specific = patch_vt1616_specific
};
static int patch_vt1616(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_vt1616_ops;
return 0;
}
/*
* VT1617A codec
*/
/*
* unfortunately, the vt1617a stashes the twiddlers required for
* noodling the i/o jacks on 2 different regs. that means that we can't
* use the easy way provided by AC97_ENUM_DOUBLE() we have to write
* are own funcs.
*
* NB: this is absolutely and utterly different from the vt1618. dunno
* about the 1616.
*/
/* copied from ac97_surround_jack_mode_info() */
static int snd_ac97_vt1617a_smart51_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
/* ordering in this list reflects vt1617a docs for Reg 20 and
* 7a and Table 6 that lays out the matrix NB WRT Table6: SM51
* is SM51EN *AND* it's Bit14, not Bit15 so the table is very
* counter-intuitive */
static const char* texts[] = { "LineIn Mic1", "LineIn Mic1 Mic3",
"Surr LFE/C Mic3", "LineIn LFE/C Mic3",
"LineIn Mic2", "LineIn Mic2 Mic1",
"Surr LFE Mic1", "Surr LFE Mic1 Mic2"};
return ac97_enum_text_info(kcontrol, uinfo, texts, 8);
}
static int snd_ac97_vt1617a_smart51_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ushort usSM51, usMS;
struct snd_ac97 *pac97;
pac97 = snd_kcontrol_chip(kcontrol); /* grab codec handle */
/* grab our desired bits, then mash them together in a manner
* consistent with Table 6 on page 17 in the 1617a docs */
usSM51 = snd_ac97_read(pac97, 0x7a) >> 14;
usMS = snd_ac97_read(pac97, 0x20) >> 8;
ucontrol->value.enumerated.item[0] = (usSM51 << 1) + usMS;
return 0;
}
static int snd_ac97_vt1617a_smart51_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ushort usSM51, usMS, usReg;
struct snd_ac97 *pac97;
pac97 = snd_kcontrol_chip(kcontrol); /* grab codec handle */
usSM51 = ucontrol->value.enumerated.item[0] >> 1;
usMS = ucontrol->value.enumerated.item[0] & 1;
/* push our values into the register - consider that things will be left
* in a funky state if the write fails */
usReg = snd_ac97_read(pac97, 0x7a);
snd_ac97_write_cache(pac97, 0x7a, (usReg & 0x3FFF) + (usSM51 << 14));
usReg = snd_ac97_read(pac97, 0x20);
snd_ac97_write_cache(pac97, 0x20, (usReg & 0xFEFF) + (usMS << 8));
return 0;
}
static const struct snd_kcontrol_new snd_ac97_controls_vt1617a[] = {
AC97_SINGLE("Center/LFE Exchange", 0x5a, 8, 1, 0),
/*
* These are used to enable/disable surround sound on motherboards
* that have 3 bidirectional analog jacks
*/
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Smart 5.1 Select",
.info = snd_ac97_vt1617a_smart51_info,
.get = snd_ac97_vt1617a_smart51_get,
.put = snd_ac97_vt1617a_smart51_put,
},
};
static int patch_vt1617a(struct snd_ac97 * ac97)
{
int err = 0;
int val;
/* we choose to not fail out at this point, but we tell the
caller when we return */
err = patch_build_controls(ac97, &snd_ac97_controls_vt1617a[0],
ARRAY_SIZE(snd_ac97_controls_vt1617a));
/* bring analog power consumption to normal by turning off the
* headphone amplifier, like WinXP driver for EPIA SP
*/
/* We need to check the bit before writing it.
* On some (many?) hardwares, setting bit actually clears it!
*/
val = snd_ac97_read(ac97, 0x5c);
if (!(val & 0x20))
snd_ac97_write_cache(ac97, 0x5c, 0x20);
ac97->ext_id |= AC97_EI_SPDIF; /* force the detection of spdif */
ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000;
ac97->build_ops = &patch_vt1616_ops;
return err;
}
/* VIA VT1618 8 CHANNEL AC97 CODEC
*
* VIA implements 'Smart 5.1' completely differently on the 1618 than
* it does on the 1617a. awesome! They seem to have sourced this
* particular revision of the technology from somebody else, it's
* called Universal Audio Jack and it shows up on some other folk's chips
* as well.
*
* ordering in this list reflects vt1618 docs for Reg 60h and
* the block diagram, DACs are as follows:
*
* OUT_O -> Front,
* OUT_1 -> Surround,
* OUT_2 -> C/LFE
*
* Unlike the 1617a, each OUT has a consistent set of mappings
* for all bitpatterns other than 00:
*
* 01 Unmixed Output
* 10 Line In
* 11 Mic In
*
* Special Case of 00:
*
* OUT_0 Mixed Output
* OUT_1 Reserved
* OUT_2 Reserved
*
* I have no idea what the hell Reserved does, but on an MSI
* CN700T, i have to set it to get 5.1 output - YMMV, bad
* shit may happen.
*
* If other chips use Universal Audio Jack, then this code might be applicable
* to them.
*/
struct vt1618_uaj_item {
unsigned short mask;
unsigned short shift;
const char *items[4];
};
/* This list reflects the vt1618 docs for Vendor Defined Register 0x60. */
static struct vt1618_uaj_item vt1618_uaj[3] = {
{
/* speaker jack */
.mask = 0x03,
.shift = 0,
.items = {
"Speaker Out", "DAC Unmixed Out", "Line In", "Mic In"
}
},
{
/* line jack */
.mask = 0x0c,
.shift = 2,
.items = {
"Surround Out", "DAC Unmixed Out", "Line In", "Mic In"
}
},
{
/* mic jack */
.mask = 0x30,
.shift = 4,
.items = {
"Center LFE Out", "DAC Unmixed Out", "Line In", "Mic In"
},
},
};
static int snd_ac97_vt1618_UAJ_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
return ac97_enum_text_info(kcontrol, uinfo,
vt1618_uaj[kcontrol->private_value].items,
4);
}
/* All of the vt1618 Universal Audio Jack twiddlers are on
* Vendor Defined Register 0x60, page 0. The bits, and thus
* the mask, are the only thing that changes
*/
static int snd_ac97_vt1618_UAJ_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
unsigned short datpag, uaj;
struct snd_ac97 *pac97 = snd_kcontrol_chip(kcontrol);
mutex_lock(&pac97->page_mutex);
datpag = snd_ac97_read(pac97, AC97_INT_PAGING) & AC97_PAGE_MASK;
snd_ac97_update_bits(pac97, AC97_INT_PAGING, AC97_PAGE_MASK, 0);
uaj = snd_ac97_read(pac97, 0x60) &
vt1618_uaj[kcontrol->private_value].mask;
snd_ac97_update_bits(pac97, AC97_INT_PAGING, AC97_PAGE_MASK, datpag);
mutex_unlock(&pac97->page_mutex);
ucontrol->value.enumerated.item[0] = uaj >>
vt1618_uaj[kcontrol->private_value].shift;
return 0;
}
static int snd_ac97_vt1618_UAJ_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
return ac97_update_bits_page(snd_kcontrol_chip(kcontrol), 0x60,
vt1618_uaj[kcontrol->private_value].mask,
ucontrol->value.enumerated.item[0]<<
vt1618_uaj[kcontrol->private_value].shift,
0);
}
/* config aux in jack - not found on 3 jack motherboards or soundcards */
static int snd_ac97_vt1618_aux_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char *txt_aux[] = {"Aux In", "Back Surr Out"};
return ac97_enum_text_info(kcontrol, uinfo, txt_aux, 2);
}
static int snd_ac97_vt1618_aux_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.enumerated.item[0] =
(snd_ac97_read(snd_kcontrol_chip(kcontrol), 0x5c) & 0x0008)>>3;
return 0;
}
static int snd_ac97_vt1618_aux_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
/* toggle surround rear dac power */
snd_ac97_update_bits(snd_kcontrol_chip(kcontrol), 0x5c, 0x0008,
ucontrol->value.enumerated.item[0] << 3);
/* toggle aux in surround rear out jack */
return snd_ac97_update_bits(snd_kcontrol_chip(kcontrol), 0x76, 0x0008,
ucontrol->value.enumerated.item[0] << 3);
}
static const struct snd_kcontrol_new snd_ac97_controls_vt1618[] = {
AC97_SINGLE("Exchange Center/LFE", 0x5a, 8, 1, 0),
AC97_SINGLE("DC Offset", 0x5a, 10, 1, 0),
AC97_SINGLE("Soft Mute", 0x5c, 0, 1, 1),
AC97_SINGLE("Headphone Amp", 0x5c, 5, 1, 1),
AC97_DOUBLE("Back Surr Volume", 0x5e, 8, 0, 31, 1),
AC97_SINGLE("Back Surr Switch", 0x5e, 15, 1, 1),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Speaker Jack Mode",
.info = snd_ac97_vt1618_UAJ_info,
.get = snd_ac97_vt1618_UAJ_get,
.put = snd_ac97_vt1618_UAJ_put,
.private_value = 0
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Line Jack Mode",
.info = snd_ac97_vt1618_UAJ_info,
.get = snd_ac97_vt1618_UAJ_get,
.put = snd_ac97_vt1618_UAJ_put,
.private_value = 1
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Mic Jack Mode",
.info = snd_ac97_vt1618_UAJ_info,
.get = snd_ac97_vt1618_UAJ_get,
.put = snd_ac97_vt1618_UAJ_put,
.private_value = 2
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Aux Jack Mode",
.info = snd_ac97_vt1618_aux_info,
.get = snd_ac97_vt1618_aux_get,
.put = snd_ac97_vt1618_aux_put,
}
};
static int patch_vt1618(struct snd_ac97 *ac97)
{
return patch_build_controls(ac97, snd_ac97_controls_vt1618,
ARRAY_SIZE(snd_ac97_controls_vt1618));
}
/*
*/
static void it2646_update_jacks(struct snd_ac97 *ac97)
{
/* shared Line-In / Surround Out */
snd_ac97_update_bits(ac97, 0x76, 1 << 9,
is_shared_surrout(ac97) ? (1<<9) : 0);
/* shared Mic / Center/LFE Out */
snd_ac97_update_bits(ac97, 0x76, 1 << 10,
is_shared_clfeout(ac97) ? (1<<10) : 0);
}
static const struct snd_kcontrol_new snd_ac97_controls_it2646[] = {
AC97_SURROUND_JACK_MODE_CTL,
AC97_CHANNEL_MODE_CTL,
};
static const struct snd_kcontrol_new snd_ac97_spdif_controls_it2646[] = {
AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), 0x76, 11, 1, 0),
AC97_SINGLE("Analog to IEC958 Output", 0x76, 12, 1, 0),
AC97_SINGLE("IEC958 Input Monitor", 0x76, 13, 1, 0),
};
static int patch_it2646_specific(struct snd_ac97 * ac97)
{
int err;
if ((err = patch_build_controls(ac97, snd_ac97_controls_it2646, ARRAY_SIZE(snd_ac97_controls_it2646))) < 0)
return err;
if ((err = patch_build_controls(ac97, snd_ac97_spdif_controls_it2646, ARRAY_SIZE(snd_ac97_spdif_controls_it2646))) < 0)
return err;
return 0;
}
static const struct snd_ac97_build_ops patch_it2646_ops = {
.build_specific = patch_it2646_specific,
.update_jacks = it2646_update_jacks
};
static int patch_it2646(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_it2646_ops;
/* full DAC volume */
snd_ac97_write_cache(ac97, 0x5E, 0x0808);
snd_ac97_write_cache(ac97, 0x7A, 0x0808);
return 0;
}
/*
* Si3036 codec
*/
#define AC97_SI3036_CHIP_ID 0x5a
#define AC97_SI3036_LINE_CFG 0x5c
static const struct snd_kcontrol_new snd_ac97_controls_si3036[] = {
AC97_DOUBLE("Modem Speaker Volume", 0x5c, 14, 12, 3, 1)
};
static int patch_si3036_specific(struct snd_ac97 * ac97)
{
int idx, err;
for (idx = 0; idx < ARRAY_SIZE(snd_ac97_controls_si3036); idx++)
if ((err = snd_ctl_add(ac97->bus->card, snd_ctl_new1(&snd_ac97_controls_si3036[idx], ac97))) < 0)
return err;
return 0;
}
static const struct snd_ac97_build_ops patch_si3036_ops = {
.build_specific = patch_si3036_specific,
};
static int mpatch_si3036(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_si3036_ops;
snd_ac97_write_cache(ac97, 0x5c, 0xf210 );
snd_ac97_write_cache(ac97, 0x68, 0);
return 0;
}
/*
* LM 4550 Codec
*
* We use a static resolution table since LM4550 codec cannot be
* properly autoprobed to determine the resolution via
* check_volume_resolution().
*/
static struct snd_ac97_res_table lm4550_restbl[] = {
{ AC97_MASTER, 0x1f1f },
{ AC97_HEADPHONE, 0x1f1f },
{ AC97_MASTER_MONO, 0x001f },
{ AC97_PC_BEEP, 0x001f }, /* LSB is ignored */
{ AC97_PHONE, 0x001f },
{ AC97_MIC, 0x001f },
{ AC97_LINE, 0x1f1f },
{ AC97_CD, 0x1f1f },
{ AC97_VIDEO, 0x1f1f },
{ AC97_AUX, 0x1f1f },
{ AC97_PCM, 0x1f1f },
{ AC97_REC_GAIN, 0x0f0f },
{ } /* terminator */
};
static int patch_lm4550(struct snd_ac97 *ac97)
{
ac97->res_table = lm4550_restbl;
return 0;
}
/*
* UCB1400 codec (http://www.semiconductors.philips.com/acrobat_download/datasheets/UCB1400-02.pdf)
*/
static const struct snd_kcontrol_new snd_ac97_controls_ucb1400[] = {
/* enable/disable headphone driver which allows direct connection to
stereo headphone without the use of external DC blocking
capacitors */
AC97_SINGLE("Headphone Driver", 0x6a, 6, 1, 0),
/* Filter used to compensate the DC offset is added in the ADC to remove idle
tones from the audio band. */
AC97_SINGLE("DC Filter", 0x6a, 4, 1, 0),
/* Control smart-low-power mode feature. Allows automatic power down
of unused blocks in the ADC analog front end and the PLL. */
AC97_SINGLE("Smart Low Power Mode", 0x6c, 4, 3, 0),
};
static int patch_ucb1400_specific(struct snd_ac97 * ac97)
{
int idx, err;
for (idx = 0; idx < ARRAY_SIZE(snd_ac97_controls_ucb1400); idx++)
if ((err = snd_ctl_add(ac97->bus->card, snd_ctl_new1(&snd_ac97_controls_ucb1400[idx], ac97))) < 0)
return err;
return 0;
}
static const struct snd_ac97_build_ops patch_ucb1400_ops = {
.build_specific = patch_ucb1400_specific,
};
static int patch_ucb1400(struct snd_ac97 * ac97)
{
ac97->build_ops = &patch_ucb1400_ops;
/* enable headphone driver and smart low power mode by default */
snd_ac97_write_cache(ac97, 0x6a, 0x0050);
snd_ac97_write_cache(ac97, 0x6c, 0x0030);
return 0;
}
| gpl-2.0 |
Split-Screen/android_kernel_motorola_msm8610 | drivers/ide/ide-pio-blacklist.c | 12539 | 2347 | /*
* PIO blacklist. Some drives incorrectly report their maximal PIO mode,
* at least in respect to CMD640. Here we keep info on some known drives.
*
* Changes to the ide_pio_blacklist[] should be made with EXTREME CAUTION
* to avoid breaking the fragile cmd640.c support.
*/
#include <linux/string.h>
static struct ide_pio_info {
const char *name;
int pio;
} ide_pio_blacklist [] = {
{ "Conner Peripherals 540MB - CFS540A", 3 },
{ "WDC AC2700", 3 },
{ "WDC AC2540", 3 },
{ "WDC AC2420", 3 },
{ "WDC AC2340", 3 },
{ "WDC AC2250", 0 },
{ "WDC AC2200", 0 },
{ "WDC AC21200", 4 },
{ "WDC AC2120", 0 },
{ "WDC AC2850", 3 },
{ "WDC AC1270", 3 },
{ "WDC AC1170", 1 },
{ "WDC AC1210", 1 },
{ "WDC AC280", 0 },
{ "WDC AC31000", 3 },
{ "WDC AC31200", 3 },
{ "Maxtor 7131 AT", 1 },
{ "Maxtor 7171 AT", 1 },
{ "Maxtor 7213 AT", 1 },
{ "Maxtor 7245 AT", 1 },
{ "Maxtor 7345 AT", 1 },
{ "Maxtor 7546 AT", 3 },
{ "Maxtor 7540 AV", 3 },
{ "SAMSUNG SHD-3121A", 1 },
{ "SAMSUNG SHD-3122A", 1 },
{ "SAMSUNG SHD-3172A", 1 },
{ "ST5660A", 3 },
{ "ST3660A", 3 },
{ "ST3630A", 3 },
{ "ST3655A", 3 },
{ "ST3391A", 3 },
{ "ST3390A", 1 },
{ "ST3600A", 1 },
{ "ST3290A", 0 },
{ "ST3144A", 0 },
{ "ST3491A", 1 }, /* reports 3, should be 1 or 2 (depending on drive)
according to Seagate's FIND-ATA program */
{ "QUANTUM ELS127A", 0 },
{ "QUANTUM ELS170A", 0 },
{ "QUANTUM LPS240A", 0 },
{ "QUANTUM LPS210A", 3 },
{ "QUANTUM LPS270A", 3 },
{ "QUANTUM LPS365A", 3 },
{ "QUANTUM LPS540A", 3 },
{ "QUANTUM LIGHTNING 540A", 3 },
{ "QUANTUM LIGHTNING 730A", 3 },
{ "QUANTUM FIREBALL_540", 3 }, /* Older Quantum Fireballs don't work */
{ "QUANTUM FIREBALL_640", 3 },
{ "QUANTUM FIREBALL_1080", 3 },
{ "QUANTUM FIREBALL_1280", 3 },
{ NULL, 0 }
};
/**
* ide_scan_pio_blacklist - check for a blacklisted drive
* @model: Drive model string
*
* This routine searches the ide_pio_blacklist for an entry
* matching the start/whole of the supplied model name.
*
* Returns -1 if no match found.
* Otherwise returns the recommended PIO mode from ide_pio_blacklist[].
*/
int ide_scan_pio_blacklist(char *model)
{
struct ide_pio_info *p;
for (p = ide_pio_blacklist; p->name != NULL; p++) {
if (strncmp(p->name, model, strlen(p->name)) == 0)
return p->pio;
}
return -1;
}
| gpl-2.0 |
denseye73/mykernel | drivers/zorro/gen-devlist.c | 14843 | 2134 | /*
* Generate devlist.h from the Zorro ID file.
*
* (c) 2000 Geert Uytterhoeven <geert@linux-m68k.org>
*
* Based on the PCI version:
*
* (c) 1999--2000 Martin Mares <mj@ucw.cz>
*/
#include <stdio.h>
#include <string.h>
#define MAX_NAME_SIZE 63
static void
pq(FILE *f, const char *c)
{
while (*c) {
if (*c == '"')
fprintf(f, "\\\"");
else
fputc(*c, f);
c++;
}
}
int
main(void)
{
char line[1024], *c, *bra, manuf[8];
int manufs = 0;
int mode = 0;
int lino = 0;
int manuf_len = 0;
FILE *devf;
devf = fopen("devlist.h", "w");
if (!devf) {
fprintf(stderr, "Cannot create output file!\n");
return 1;
}
while (fgets(line, sizeof(line)-1, stdin)) {
lino++;
if ((c = strchr(line, '\n')))
*c = 0;
if (!line[0] || line[0] == '#')
continue;
if (line[0] == '\t') {
switch (mode) {
case 1:
if (strlen(line) > 5 && line[5] == ' ') {
c = line + 5;
while (*c == ' ')
*c++ = 0;
if (manuf_len + strlen(c) + 1 > MAX_NAME_SIZE) {
/* Too long, try cutting off long description */
bra = strchr(c, '[');
if (bra && bra > c && bra[-1] == ' ')
bra[-1] = 0;
if (manuf_len + strlen(c) + 1 > MAX_NAME_SIZE) {
fprintf(stderr, "Line %d: Product name too long\n", lino);
return 1;
}
}
fprintf(devf, "\tPRODUCT(%s,%s,\"", manuf, line+1);
pq(devf, c);
fputs("\")\n", devf);
} else goto err;
break;
default:
goto err;
}
} else if (strlen(line) > 4 && line[4] == ' ') {
c = line + 4;
while (*c == ' ')
*c++ = 0;
if (manufs)
fputs("ENDMANUF()\n\n", devf);
manufs++;
strcpy(manuf, line);
manuf_len = strlen(c);
if (manuf_len + 24 > MAX_NAME_SIZE) {
fprintf(stderr, "Line %d: manufacturer name too long\n", lino);
return 1;
}
fprintf(devf, "MANUF(%s,\"", manuf);
pq(devf, c);
fputs("\")\n", devf);
mode = 1;
} else {
err:
fprintf(stderr, "Line %d: Syntax error in mode %d: %s\n", lino, mode, line);
return 1;
}
}
fputs("ENDMANUF()\n\
\n\
#undef MANUF\n\
#undef PRODUCT\n\
#undef ENDMANUF\n", devf);
fclose(devf);
return 0;
}
| gpl-2.0 |
pjrobertson/Telegram-1 | TMessagesProj/jni/opus/silk/fixed/vector_ops_FIX.c | 252 | 4548 | /***********************************************************************
Copyright (c) 2006-2011, Skype Limited. All rights reserved.
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.
- Neither the name of Internet Society, IETF or IETF Trust, nor the
names of specific contributors, may be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "SigProc_FIX.h"
/* Copy and multiply a vector by a constant */
void silk_scale_copy_vector16(
opus_int16 *data_out,
const opus_int16 *data_in,
opus_int32 gain_Q16, /* I Gain in Q16 */
const opus_int dataSize /* I Length */
)
{
opus_int i;
opus_int32 tmp32;
for( i = 0; i < dataSize; i++ ) {
tmp32 = silk_SMULWB( gain_Q16, data_in[ i ] );
data_out[ i ] = (opus_int16)silk_CHECK_FIT16( tmp32 );
}
}
/* Multiply a vector by a constant */
void silk_scale_vector32_Q26_lshift_18(
opus_int32 *data1, /* I/O Q0/Q18 */
opus_int32 gain_Q26, /* I Q26 */
opus_int dataSize /* I length */
)
{
opus_int i;
for( i = 0; i < dataSize; i++ ) {
data1[ i ] = (opus_int32)silk_CHECK_FIT32( silk_RSHIFT64( silk_SMULL( data1[ i ], gain_Q26 ), 8 ) ); /* OUTPUT: Q18 */
}
}
/* sum = for(i=0;i<len;i++)inVec1[i]*inVec2[i]; --- inner product */
/* Note for ARM asm: */
/* * inVec1 and inVec2 should be at least 2 byte aligned. */
/* * len should be positive 16bit integer. */
/* * only when len>6, memory access can be reduced by half. */
opus_int32 silk_inner_prod_aligned(
const opus_int16 *const inVec1, /* I input vector 1 */
const opus_int16 *const inVec2, /* I input vector 2 */
const opus_int len /* I vector lengths */
)
{
opus_int i;
opus_int32 sum = 0;
for( i = 0; i < len; i++ ) {
sum = silk_SMLABB( sum, inVec1[ i ], inVec2[ i ] );
}
return sum;
}
opus_int64 silk_inner_prod16_aligned_64(
const opus_int16 *inVec1, /* I input vector 1 */
const opus_int16 *inVec2, /* I input vector 2 */
const opus_int len /* I vector lengths */
)
{
opus_int i;
opus_int64 sum = 0;
for( i = 0; i < len; i++ ) {
sum = silk_SMLALBB( sum, inVec1[ i ], inVec2[ i ] );
}
return sum;
}
| gpl-2.0 |
qnhoang81/Moment_kernel | arch/arm/mach-pxa/irq.c | 508 | 4302 | /*
* linux/arch/arm/mach-pxa/irq.c
*
* Generic PXA IRQ handling
*
* Author: Nicolas Pitre
* Created: Jun 15, 2001
* Copyright: 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/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/sysdev.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach/irq.h>
#include <mach/gpio.h>
#include <mach/regs-intc.h>
#include "generic.h"
#define MAX_INTERNAL_IRQS 128
#define IRQ_BIT(n) (((n) - PXA_IRQ(0)) & 0x1f)
#define _ICMR(n) (*((((n) - PXA_IRQ(0)) & ~0x1f) ? &ICMR2 : &ICMR))
#define _ICLR(n) (*((((n) - PXA_IRQ(0)) & ~0x1f) ? &ICLR2 : &ICLR))
/*
* This is for peripheral IRQs internal to the PXA chip.
*/
static int pxa_internal_irq_nr;
static void pxa_mask_irq(unsigned int irq)
{
_ICMR(irq) &= ~(1 << IRQ_BIT(irq));
}
static void pxa_unmask_irq(unsigned int irq)
{
_ICMR(irq) |= 1 << IRQ_BIT(irq);
}
static struct irq_chip pxa_internal_irq_chip = {
.name = "SC",
.ack = pxa_mask_irq,
.mask = pxa_mask_irq,
.unmask = pxa_unmask_irq,
};
/*
* GPIO IRQs for GPIO 0 and 1
*/
static int pxa_set_low_gpio_type(unsigned int irq, unsigned int type)
{
int gpio = irq - IRQ_GPIO0;
if (__gpio_is_occupied(gpio)) {
pr_err("%s failed: GPIO is configured\n", __func__);
return -EINVAL;
}
if (type & IRQ_TYPE_EDGE_RISING)
GRER0 |= GPIO_bit(gpio);
else
GRER0 &= ~GPIO_bit(gpio);
if (type & IRQ_TYPE_EDGE_FALLING)
GFER0 |= GPIO_bit(gpio);
else
GFER0 &= ~GPIO_bit(gpio);
return 0;
}
static void pxa_ack_low_gpio(unsigned int irq)
{
GEDR0 = (1 << (irq - IRQ_GPIO0));
}
static void pxa_mask_low_gpio(unsigned int irq)
{
ICMR &= ~(1 << (irq - PXA_IRQ(0)));
}
static void pxa_unmask_low_gpio(unsigned int irq)
{
ICMR |= 1 << (irq - PXA_IRQ(0));
}
static struct irq_chip pxa_low_gpio_chip = {
.name = "GPIO-l",
.ack = pxa_ack_low_gpio,
.mask = pxa_mask_low_gpio,
.unmask = pxa_unmask_low_gpio,
.set_type = pxa_set_low_gpio_type,
};
static void __init pxa_init_low_gpio_irq(set_wake_t fn)
{
int irq;
/* clear edge detection on GPIO 0 and 1 */
GFER0 &= ~0x3;
GRER0 &= ~0x3;
GEDR0 = 0x3;
for (irq = IRQ_GPIO0; irq <= IRQ_GPIO1; irq++) {
set_irq_chip(irq, &pxa_low_gpio_chip);
set_irq_handler(irq, handle_edge_irq);
set_irq_flags(irq, IRQF_VALID);
}
pxa_low_gpio_chip.set_wake = fn;
}
void __init pxa_init_irq(int irq_nr, set_wake_t fn)
{
int irq, i;
BUG_ON(irq_nr > MAX_INTERNAL_IRQS);
pxa_internal_irq_nr = irq_nr;
for (irq = PXA_IRQ(0); irq < PXA_IRQ(irq_nr); irq += 32) {
_ICMR(irq) = 0; /* disable all IRQs */
_ICLR(irq) = 0; /* all IRQs are IRQ, not FIQ */
}
/* initialize interrupt priority */
if (cpu_is_pxa27x() || cpu_is_pxa3xx()) {
for (i = 0; i < irq_nr; i++)
IPR(i) = i | (1 << 31);
}
/* only unmasked interrupts kick us out of idle */
ICCR = 1;
for (irq = PXA_IRQ(0); irq < PXA_IRQ(irq_nr); irq++) {
set_irq_chip(irq, &pxa_internal_irq_chip);
set_irq_handler(irq, handle_level_irq);
set_irq_flags(irq, IRQF_VALID);
}
pxa_internal_irq_chip.set_wake = fn;
pxa_init_low_gpio_irq(fn);
}
#ifdef CONFIG_PM
static unsigned long saved_icmr[MAX_INTERNAL_IRQS/32];
static unsigned long saved_ipr[MAX_INTERNAL_IRQS];
static int pxa_irq_suspend(struct sys_device *dev, pm_message_t state)
{
int i, irq = PXA_IRQ(0);
for (i = 0; irq < PXA_IRQ(pxa_internal_irq_nr); i++, irq += 32) {
saved_icmr[i] = _ICMR(irq);
_ICMR(irq) = 0;
}
for (i = 0; i < pxa_internal_irq_nr; i++)
saved_ipr[i] = IPR(i);
return 0;
}
static int pxa_irq_resume(struct sys_device *dev)
{
int i, irq = PXA_IRQ(0);
for (i = 0; irq < PXA_IRQ(pxa_internal_irq_nr); i++, irq += 32) {
_ICMR(irq) = saved_icmr[i];
_ICLR(irq) = 0;
}
for (i = 0; i < pxa_internal_irq_nr; i++)
IPR(i) = saved_ipr[i];
ICCR = 1;
return 0;
}
#else
#define pxa_irq_suspend NULL
#define pxa_irq_resume NULL
#endif
struct sysdev_class pxa_irq_sysclass = {
.name = "irq",
.suspend = pxa_irq_suspend,
.resume = pxa_irq_resume,
};
static int __init pxa_irq_init(void)
{
return sysdev_class_register(&pxa_irq_sysclass);
}
core_initcall(pxa_irq_init);
| gpl-2.0 |
kingklick/kk-evo-kernel | drivers/i2c/busses/i2c-sh_mobile.c | 508 | 19274 | /*
* SuperH Mobile I2C Controller
*
* Copyright (C) 2008 Magnus Damm
*
* Portions of the code based on out-of-tree driver i2c-sh7343.c
* Copyright (c) 2006 Carlos Munoz <carlos@kenati.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
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/pm_runtime.h>
#include <linux/clk.h>
#include <linux/io.h>
/* Transmit operation: */
/* */
/* 0 byte transmit */
/* BUS: S A8 ACK P */
/* IRQ: DTE WAIT */
/* ICIC: */
/* ICCR: 0x94 0x90 */
/* ICDR: A8 */
/* */
/* 1 byte transmit */
/* BUS: S A8 ACK D8(1) ACK P */
/* IRQ: DTE WAIT WAIT */
/* ICIC: -DTE */
/* ICCR: 0x94 0x90 */
/* ICDR: A8 D8(1) */
/* */
/* 2 byte transmit */
/* BUS: S A8 ACK D8(1) ACK D8(2) ACK P */
/* IRQ: DTE WAIT WAIT WAIT */
/* ICIC: -DTE */
/* ICCR: 0x94 0x90 */
/* ICDR: A8 D8(1) D8(2) */
/* */
/* 3 bytes or more, +---------+ gets repeated */
/* */
/* */
/* Receive operation: */
/* */
/* 0 byte receive - not supported since slave may hold SDA low */
/* */
/* 1 byte receive [TX] | [RX] */
/* BUS: S A8 ACK | D8(1) ACK P */
/* IRQ: DTE WAIT | WAIT DTE */
/* ICIC: -DTE | +DTE */
/* ICCR: 0x94 0x81 | 0xc0 */
/* ICDR: A8 | D8(1) */
/* */
/* 2 byte receive [TX]| [RX] */
/* BUS: S A8 ACK | D8(1) ACK D8(2) ACK P */
/* IRQ: DTE WAIT | WAIT WAIT DTE */
/* ICIC: -DTE | +DTE */
/* ICCR: 0x94 0x81 | 0xc0 */
/* ICDR: A8 | D8(1) D8(2) */
/* */
/* 3 byte receive [TX] | [RX] */
/* BUS: S A8 ACK | D8(1) ACK D8(2) ACK D8(3) ACK P */
/* IRQ: DTE WAIT | WAIT WAIT WAIT DTE */
/* ICIC: -DTE | +DTE */
/* ICCR: 0x94 0x81 | 0xc0 */
/* ICDR: A8 | D8(1) D8(2) D8(3) */
/* */
/* 4 bytes or more, this part is repeated +---------+ */
/* */
/* */
/* Interrupt order and BUSY flag */
/* ___ _ */
/* SDA ___\___XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXAAAAAAAAA___/ */
/* SCL \_/1\_/2\_/3\_/4\_/5\_/6\_/7\_/8\___/9\_____/ */
/* */
/* S D7 D6 D5 D4 D3 D2 D1 D0 P */
/* ___ */
/* WAIT IRQ ________________________________/ \___________ */
/* TACK IRQ ____________________________________/ \_______ */
/* DTE IRQ __________________________________________/ \_ */
/* AL IRQ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */
/* _______________________________________________ */
/* BUSY __/ \_ */
/* */
enum sh_mobile_i2c_op {
OP_START = 0,
OP_TX_FIRST,
OP_TX,
OP_TX_STOP,
OP_TX_TO_RX,
OP_RX,
OP_RX_STOP,
OP_RX_STOP_DATA,
};
struct sh_mobile_i2c_data {
struct device *dev;
void __iomem *reg;
struct i2c_adapter adap;
struct clk *clk;
u_int8_t iccl;
u_int8_t icch;
spinlock_t lock;
wait_queue_head_t wait;
struct i2c_msg *msg;
int pos;
int sr;
};
#define NORMAL_SPEED 100000 /* FAST_SPEED 400000 */
/* Register offsets */
#define ICDR(pd) (pd->reg + 0x00)
#define ICCR(pd) (pd->reg + 0x04)
#define ICSR(pd) (pd->reg + 0x08)
#define ICIC(pd) (pd->reg + 0x0c)
#define ICCL(pd) (pd->reg + 0x10)
#define ICCH(pd) (pd->reg + 0x14)
/* Register bits */
#define ICCR_ICE 0x80
#define ICCR_RACK 0x40
#define ICCR_TRS 0x10
#define ICCR_BBSY 0x04
#define ICCR_SCP 0x01
#define ICSR_SCLM 0x80
#define ICSR_SDAM 0x40
#define SW_DONE 0x20
#define ICSR_BUSY 0x10
#define ICSR_AL 0x08
#define ICSR_TACK 0x04
#define ICSR_WAIT 0x02
#define ICSR_DTE 0x01
#define ICIC_ALE 0x08
#define ICIC_TACKE 0x04
#define ICIC_WAITE 0x02
#define ICIC_DTEE 0x01
static void activate_ch(struct sh_mobile_i2c_data *pd)
{
unsigned long i2c_clk;
u_int32_t num;
u_int32_t denom;
u_int32_t tmp;
/* Wake up device and enable clock */
pm_runtime_get_sync(pd->dev);
clk_enable(pd->clk);
/* Get clock rate after clock is enabled */
i2c_clk = clk_get_rate(pd->clk);
/* Calculate the value for iccl. From the data sheet:
* iccl = (p clock / transfer rate) * (L / (L + H))
* where L and H are the SCL low/high ratio (5/4 in this case).
* We also round off the result.
*/
num = i2c_clk * 5;
denom = NORMAL_SPEED * 9;
tmp = num * 10 / denom;
if (tmp % 10 >= 5)
pd->iccl = (u_int8_t)((num/denom) + 1);
else
pd->iccl = (u_int8_t)(num/denom);
/* Calculate the value for icch. From the data sheet:
icch = (p clock / transfer rate) * (H / (L + H)) */
num = i2c_clk * 4;
tmp = num * 10 / denom;
if (tmp % 10 >= 5)
pd->icch = (u_int8_t)((num/denom) + 1);
else
pd->icch = (u_int8_t)(num/denom);
/* Enable channel and configure rx ack */
iowrite8(ioread8(ICCR(pd)) | ICCR_ICE, ICCR(pd));
/* Mask all interrupts */
iowrite8(0, ICIC(pd));
/* Set the clock */
iowrite8(pd->iccl, ICCL(pd));
iowrite8(pd->icch, ICCH(pd));
}
static void deactivate_ch(struct sh_mobile_i2c_data *pd)
{
/* Clear/disable interrupts */
iowrite8(0, ICSR(pd));
iowrite8(0, ICIC(pd));
/* Disable channel */
iowrite8(ioread8(ICCR(pd)) & ~ICCR_ICE, ICCR(pd));
/* Disable clock and mark device as idle */
clk_disable(pd->clk);
pm_runtime_put_sync(pd->dev);
}
static unsigned char i2c_op(struct sh_mobile_i2c_data *pd,
enum sh_mobile_i2c_op op, unsigned char data)
{
unsigned char ret = 0;
unsigned long flags;
dev_dbg(pd->dev, "op %d, data in 0x%02x\n", op, data);
spin_lock_irqsave(&pd->lock, flags);
switch (op) {
case OP_START: /* issue start and trigger DTE interrupt */
iowrite8(0x94, ICCR(pd));
break;
case OP_TX_FIRST: /* disable DTE interrupt and write data */
iowrite8(ICIC_WAITE | ICIC_ALE | ICIC_TACKE, ICIC(pd));
iowrite8(data, ICDR(pd));
break;
case OP_TX: /* write data */
iowrite8(data, ICDR(pd));
break;
case OP_TX_STOP: /* write data and issue a stop afterwards */
iowrite8(data, ICDR(pd));
iowrite8(0x90, ICCR(pd));
break;
case OP_TX_TO_RX: /* select read mode */
iowrite8(0x81, ICCR(pd));
break;
case OP_RX: /* just read data */
ret = ioread8(ICDR(pd));
break;
case OP_RX_STOP: /* enable DTE interrupt, issue stop */
iowrite8(ICIC_DTEE | ICIC_WAITE | ICIC_ALE | ICIC_TACKE,
ICIC(pd));
iowrite8(0xc0, ICCR(pd));
break;
case OP_RX_STOP_DATA: /* enable DTE interrupt, read data, issue stop */
iowrite8(ICIC_DTEE | ICIC_WAITE | ICIC_ALE | ICIC_TACKE,
ICIC(pd));
ret = ioread8(ICDR(pd));
iowrite8(0xc0, ICCR(pd));
break;
}
spin_unlock_irqrestore(&pd->lock, flags);
dev_dbg(pd->dev, "op %d, data out 0x%02x\n", op, ret);
return ret;
}
static int sh_mobile_i2c_is_first_byte(struct sh_mobile_i2c_data *pd)
{
if (pd->pos == -1)
return 1;
return 0;
}
static int sh_mobile_i2c_is_last_byte(struct sh_mobile_i2c_data *pd)
{
if (pd->pos == (pd->msg->len - 1))
return 1;
return 0;
}
static void sh_mobile_i2c_get_data(struct sh_mobile_i2c_data *pd,
unsigned char *buf)
{
switch (pd->pos) {
case -1:
*buf = (pd->msg->addr & 0x7f) << 1;
*buf |= (pd->msg->flags & I2C_M_RD) ? 1 : 0;
break;
default:
*buf = pd->msg->buf[pd->pos];
}
}
static int sh_mobile_i2c_isr_tx(struct sh_mobile_i2c_data *pd)
{
unsigned char data;
if (pd->pos == pd->msg->len)
return 1;
sh_mobile_i2c_get_data(pd, &data);
if (sh_mobile_i2c_is_last_byte(pd))
i2c_op(pd, OP_TX_STOP, data);
else if (sh_mobile_i2c_is_first_byte(pd))
i2c_op(pd, OP_TX_FIRST, data);
else
i2c_op(pd, OP_TX, data);
pd->pos++;
return 0;
}
static int sh_mobile_i2c_isr_rx(struct sh_mobile_i2c_data *pd)
{
unsigned char data;
int real_pos;
do {
if (pd->pos <= -1) {
sh_mobile_i2c_get_data(pd, &data);
if (sh_mobile_i2c_is_first_byte(pd))
i2c_op(pd, OP_TX_FIRST, data);
else
i2c_op(pd, OP_TX, data);
break;
}
if (pd->pos == 0) {
i2c_op(pd, OP_TX_TO_RX, 0);
break;
}
real_pos = pd->pos - 2;
if (pd->pos == pd->msg->len) {
if (real_pos < 0) {
i2c_op(pd, OP_RX_STOP, 0);
break;
}
data = i2c_op(pd, OP_RX_STOP_DATA, 0);
} else
data = i2c_op(pd, OP_RX, 0);
if (real_pos >= 0)
pd->msg->buf[real_pos] = data;
} while (0);
pd->pos++;
return pd->pos == (pd->msg->len + 2);
}
static irqreturn_t sh_mobile_i2c_isr(int irq, void *dev_id)
{
struct platform_device *dev = dev_id;
struct sh_mobile_i2c_data *pd = platform_get_drvdata(dev);
unsigned char sr;
int wakeup;
sr = ioread8(ICSR(pd));
pd->sr |= sr; /* remember state */
dev_dbg(pd->dev, "i2c_isr 0x%02x 0x%02x %s %d %d!\n", sr, pd->sr,
(pd->msg->flags & I2C_M_RD) ? "read" : "write",
pd->pos, pd->msg->len);
if (sr & (ICSR_AL | ICSR_TACK)) {
/* don't interrupt transaction - continue to issue stop */
iowrite8(sr & ~(ICSR_AL | ICSR_TACK), ICSR(pd));
wakeup = 0;
} else if (pd->msg->flags & I2C_M_RD)
wakeup = sh_mobile_i2c_isr_rx(pd);
else
wakeup = sh_mobile_i2c_isr_tx(pd);
if (sr & ICSR_WAIT) /* TODO: add delay here to support slow acks */
iowrite8(sr & ~ICSR_WAIT, ICSR(pd));
if (wakeup) {
pd->sr |= SW_DONE;
wake_up(&pd->wait);
}
return IRQ_HANDLED;
}
static int start_ch(struct sh_mobile_i2c_data *pd, struct i2c_msg *usr_msg)
{
if (usr_msg->len == 0 && (usr_msg->flags & I2C_M_RD)) {
dev_err(pd->dev, "Unsupported zero length i2c read\n");
return -EIO;
}
/* Initialize channel registers */
iowrite8(ioread8(ICCR(pd)) & ~ICCR_ICE, ICCR(pd));
/* Enable channel and configure rx ack */
iowrite8(ioread8(ICCR(pd)) | ICCR_ICE, ICCR(pd));
/* Set the clock */
iowrite8(pd->iccl, ICCL(pd));
iowrite8(pd->icch, ICCH(pd));
pd->msg = usr_msg;
pd->pos = -1;
pd->sr = 0;
/* Enable all interrupts to begin with */
iowrite8(ICIC_WAITE | ICIC_ALE | ICIC_TACKE | ICIC_DTEE, ICIC(pd));
return 0;
}
static int sh_mobile_i2c_xfer(struct i2c_adapter *adapter,
struct i2c_msg *msgs,
int num)
{
struct sh_mobile_i2c_data *pd = i2c_get_adapdata(adapter);
struct i2c_msg *msg;
int err = 0;
u_int8_t val;
int i, k, retry_count;
activate_ch(pd);
/* Process all messages */
for (i = 0; i < num; i++) {
msg = &msgs[i];
err = start_ch(pd, msg);
if (err)
break;
i2c_op(pd, OP_START, 0);
/* The interrupt handler takes care of the rest... */
k = wait_event_timeout(pd->wait,
pd->sr & (ICSR_TACK | SW_DONE),
5 * HZ);
if (!k)
dev_err(pd->dev, "Transfer request timed out\n");
retry_count = 1000;
again:
val = ioread8(ICSR(pd));
dev_dbg(pd->dev, "val 0x%02x pd->sr 0x%02x\n", val, pd->sr);
/* the interrupt handler may wake us up before the
* transfer is finished, so poll the hardware
* until we're done.
*/
if (val & ICSR_BUSY) {
udelay(10);
if (retry_count--)
goto again;
err = -EIO;
dev_err(pd->dev, "Polling timed out\n");
break;
}
/* handle missing acknowledge and arbitration lost */
if ((val | pd->sr) & (ICSR_TACK | ICSR_AL)) {
err = -EIO;
break;
}
}
deactivate_ch(pd);
if (!err)
err = num;
return err;
}
static u32 sh_mobile_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static struct i2c_algorithm sh_mobile_i2c_algorithm = {
.functionality = sh_mobile_i2c_func,
.master_xfer = sh_mobile_i2c_xfer,
};
static int sh_mobile_i2c_hook_irqs(struct platform_device *dev, int hook)
{
struct resource *res;
int ret = -ENXIO;
int q, m;
int k = 0;
int n = 0;
while ((res = platform_get_resource(dev, IORESOURCE_IRQ, k))) {
for (n = res->start; hook && n <= res->end; n++) {
if (request_irq(n, sh_mobile_i2c_isr, IRQF_DISABLED,
dev_name(&dev->dev), dev))
goto rollback;
}
k++;
}
if (hook)
return k > 0 ? 0 : -ENOENT;
k--;
ret = 0;
rollback:
for (q = k; k >= 0; k--) {
for (m = n; m >= res->start; m--)
free_irq(m, dev);
res = platform_get_resource(dev, IORESOURCE_IRQ, k - 1);
m = res->end;
}
return ret;
}
static int sh_mobile_i2c_probe(struct platform_device *dev)
{
struct sh_mobile_i2c_data *pd;
struct i2c_adapter *adap;
struct resource *res;
char clk_name[8];
int size;
int ret;
pd = kzalloc(sizeof(struct sh_mobile_i2c_data), GFP_KERNEL);
if (pd == NULL) {
dev_err(&dev->dev, "cannot allocate private data\n");
return -ENOMEM;
}
snprintf(clk_name, sizeof(clk_name), "i2c%d", dev->id);
pd->clk = clk_get(&dev->dev, clk_name);
if (IS_ERR(pd->clk)) {
dev_err(&dev->dev, "cannot get clock \"%s\"\n", clk_name);
ret = PTR_ERR(pd->clk);
goto err;
}
ret = sh_mobile_i2c_hook_irqs(dev, 1);
if (ret) {
dev_err(&dev->dev, "cannot request IRQ\n");
goto err_clk;
}
pd->dev = &dev->dev;
platform_set_drvdata(dev, pd);
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&dev->dev, "cannot find IO resource\n");
ret = -ENOENT;
goto err_irq;
}
size = resource_size(res);
pd->reg = ioremap(res->start, size);
if (pd->reg == NULL) {
dev_err(&dev->dev, "cannot map IO\n");
ret = -ENXIO;
goto err_irq;
}
/* Enable Runtime PM for this device.
*
* Also tell the Runtime PM core to ignore children
* for this device since it is valid for us to suspend
* this I2C master driver even though the slave devices
* on the I2C bus may not be suspended.
*
* The state of the I2C hardware bus is unaffected by
* the Runtime PM state.
*/
pm_suspend_ignore_children(&dev->dev, true);
pm_runtime_enable(&dev->dev);
/* setup the private data */
adap = &pd->adap;
i2c_set_adapdata(adap, pd);
adap->owner = THIS_MODULE;
adap->algo = &sh_mobile_i2c_algorithm;
adap->dev.parent = &dev->dev;
adap->retries = 5;
adap->nr = dev->id;
strlcpy(adap->name, dev->name, sizeof(adap->name));
spin_lock_init(&pd->lock);
init_waitqueue_head(&pd->wait);
ret = i2c_add_numbered_adapter(adap);
if (ret < 0) {
dev_err(&dev->dev, "cannot add numbered adapter\n");
goto err_all;
}
return 0;
err_all:
iounmap(pd->reg);
err_irq:
sh_mobile_i2c_hook_irqs(dev, 0);
err_clk:
clk_put(pd->clk);
err:
kfree(pd);
return ret;
}
static int sh_mobile_i2c_remove(struct platform_device *dev)
{
struct sh_mobile_i2c_data *pd = platform_get_drvdata(dev);
i2c_del_adapter(&pd->adap);
iounmap(pd->reg);
sh_mobile_i2c_hook_irqs(dev, 0);
clk_put(pd->clk);
pm_runtime_disable(&dev->dev);
kfree(pd);
return 0;
}
static int sh_mobile_i2c_runtime_nop(struct device *dev)
{
/* Runtime PM callback shared between ->runtime_suspend()
* and ->runtime_resume(). Simply returns success.
*
* This driver re-initializes all registers after
* pm_runtime_get_sync() anyway so there is no need
* to save and restore registers here.
*/
return 0;
}
static struct dev_pm_ops sh_mobile_i2c_dev_pm_ops = {
.runtime_suspend = sh_mobile_i2c_runtime_nop,
.runtime_resume = sh_mobile_i2c_runtime_nop,
};
static struct platform_driver sh_mobile_i2c_driver = {
.driver = {
.name = "i2c-sh_mobile",
.owner = THIS_MODULE,
.pm = &sh_mobile_i2c_dev_pm_ops,
},
.probe = sh_mobile_i2c_probe,
.remove = sh_mobile_i2c_remove,
};
static int __init sh_mobile_i2c_adap_init(void)
{
return platform_driver_register(&sh_mobile_i2c_driver);
}
static void __exit sh_mobile_i2c_adap_exit(void)
{
platform_driver_unregister(&sh_mobile_i2c_driver);
}
subsys_initcall(sh_mobile_i2c_adap_init);
module_exit(sh_mobile_i2c_adap_exit);
MODULE_DESCRIPTION("SuperH Mobile I2C Bus Controller driver");
MODULE_AUTHOR("Magnus Damm");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
delaemon/linux | arch/avr32/kernel/time.c | 764 | 4075 | /*
* Copyright (C) 2004-2007 Atmel Corporation
*
* 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/clk.h>
#include <linux/clockchips.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/time.h>
#include <linux/cpu.h>
#include <asm/sysreg.h>
#include <mach/pm.h>
static bool disable_cpu_idle_poll;
static cycle_t read_cycle_count(struct clocksource *cs)
{
return (cycle_t)sysreg_read(COUNT);
}
/*
* The architectural cycle count registers are a fine clocksource unless
* the system idle loop use sleep states like "idle": the CPU cycles
* measured by COUNT (and COMPARE) don't happen during sleep states.
* Their duration also changes if cpufreq changes the CPU clock rate.
* So we rate the clocksource using COUNT as very low quality.
*/
static struct clocksource counter = {
.name = "avr32_counter",
.rating = 50,
.read = read_cycle_count,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
static irqreturn_t timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *evdev = dev_id;
if (unlikely(!(intc_get_pending(0) & 1)))
return IRQ_NONE;
/*
* Disable the interrupt until the clockevent subsystem
* reprograms it.
*/
sysreg_write(COMPARE, 0);
evdev->event_handler(evdev);
return IRQ_HANDLED;
}
static struct irqaction timer_irqaction = {
.handler = timer_interrupt,
/* Oprofile uses the same irq as the timer, so allow it to be shared */
.flags = IRQF_TIMER | IRQF_SHARED,
.name = "avr32_comparator",
};
static int comparator_next_event(unsigned long delta,
struct clock_event_device *evdev)
{
unsigned long flags;
raw_local_irq_save(flags);
/* The time to read COUNT then update COMPARE must be less
* than the min_delta_ns value for this clockevent source.
*/
sysreg_write(COMPARE, (sysreg_read(COUNT) + delta) ? : 1);
raw_local_irq_restore(flags);
return 0;
}
static int comparator_shutdown(struct clock_event_device *evdev)
{
pr_debug("%s: %s\n", __func__, evdev->name);
sysreg_write(COMPARE, 0);
if (disable_cpu_idle_poll) {
disable_cpu_idle_poll = false;
/*
* Only disable idle poll if we have forced that
* in a previous call.
*/
cpu_idle_poll_ctrl(false);
}
return 0;
}
static int comparator_set_oneshot(struct clock_event_device *evdev)
{
pr_debug("%s: %s\n", __func__, evdev->name);
disable_cpu_idle_poll = true;
/*
* If we're using the COUNT and COMPARE registers we
* need to force idle poll.
*/
cpu_idle_poll_ctrl(true);
return 0;
}
static struct clock_event_device comparator = {
.name = "avr32_comparator",
.features = CLOCK_EVT_FEAT_ONESHOT,
.shift = 16,
.rating = 50,
.set_next_event = comparator_next_event,
.set_state_shutdown = comparator_shutdown,
.set_state_oneshot = comparator_set_oneshot,
.tick_resume = comparator_set_oneshot,
};
void read_persistent_clock(struct timespec *ts)
{
ts->tv_sec = mktime(2007, 1, 1, 0, 0, 0);
ts->tv_nsec = 0;
}
void __init time_init(void)
{
unsigned long counter_hz;
int ret;
/* figure rate for counter */
counter_hz = clk_get_rate(boot_cpu_data.clk);
ret = clocksource_register_hz(&counter, counter_hz);
if (ret)
pr_debug("timer: could not register clocksource: %d\n", ret);
/* setup COMPARE clockevent */
comparator.mult = div_sc(counter_hz, NSEC_PER_SEC, comparator.shift);
comparator.max_delta_ns = clockevent_delta2ns((u32)~0, &comparator);
comparator.min_delta_ns = clockevent_delta2ns(50, &comparator) + 1;
comparator.cpumask = cpumask_of(0);
sysreg_write(COMPARE, 0);
timer_irqaction.dev_id = &comparator;
ret = setup_irq(0, &timer_irqaction);
if (ret)
pr_debug("timer: could not request IRQ 0: %d\n", ret);
else {
clockevents_register_device(&comparator);
pr_info("%s: irq 0, %lu.%03lu MHz\n", comparator.name,
((counter_hz + 500) / 1000) / 1000,
((counter_hz + 500) / 1000) % 1000);
}
}
| gpl-2.0 |
cattleprod/XCeLL-XV | kernel/trace/trace_kprobe.c | 764 | 40288 | /*
* Kprobes-based tracing events
*
* Created by Masami Hiramatsu <mhiramat@redhat.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.
*
* 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/module.h>
#include <linux/uaccess.h>
#include <linux/kprobes.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/smp.h>
#include <linux/debugfs.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/ptrace.h>
#include <linux/perf_event.h>
#include <linux/stringify.h>
#include <asm/bitsperlong.h>
#include "trace.h"
#include "trace_output.h"
#define MAX_TRACE_ARGS 128
#define MAX_ARGSTR_LEN 63
#define MAX_EVENT_NAME_LEN 64
#define KPROBE_EVENT_SYSTEM "kprobes"
/* Reserved field names */
#define FIELD_STRING_IP "__probe_ip"
#define FIELD_STRING_RETIP "__probe_ret_ip"
#define FIELD_STRING_FUNC "__probe_func"
const char *reserved_field_names[] = {
"common_type",
"common_flags",
"common_preempt_count",
"common_pid",
"common_tgid",
"common_lock_depth",
FIELD_STRING_IP,
FIELD_STRING_RETIP,
FIELD_STRING_FUNC,
};
/* Printing function type */
typedef int (*print_type_func_t)(struct trace_seq *, const char *, void *);
#define PRINT_TYPE_FUNC_NAME(type) print_type_##type
#define PRINT_TYPE_FMT_NAME(type) print_type_format_##type
/* Printing in basic type function template */
#define DEFINE_BASIC_PRINT_TYPE_FUNC(type, fmt, cast) \
static __kprobes int PRINT_TYPE_FUNC_NAME(type)(struct trace_seq *s, \
const char *name, void *data)\
{ \
return trace_seq_printf(s, " %s=" fmt, name, (cast)*(type *)data);\
} \
static const char PRINT_TYPE_FMT_NAME(type)[] = fmt;
DEFINE_BASIC_PRINT_TYPE_FUNC(u8, "%x", unsigned int)
DEFINE_BASIC_PRINT_TYPE_FUNC(u16, "%x", unsigned int)
DEFINE_BASIC_PRINT_TYPE_FUNC(u32, "%lx", unsigned long)
DEFINE_BASIC_PRINT_TYPE_FUNC(u64, "%llx", unsigned long long)
DEFINE_BASIC_PRINT_TYPE_FUNC(s8, "%d", int)
DEFINE_BASIC_PRINT_TYPE_FUNC(s16, "%d", int)
DEFINE_BASIC_PRINT_TYPE_FUNC(s32, "%ld", long)
DEFINE_BASIC_PRINT_TYPE_FUNC(s64, "%lld", long long)
/* Data fetch function type */
typedef void (*fetch_func_t)(struct pt_regs *, void *, void *);
struct fetch_param {
fetch_func_t fn;
void *data;
};
static __kprobes void call_fetch(struct fetch_param *fprm,
struct pt_regs *regs, void *dest)
{
return fprm->fn(regs, fprm->data, dest);
}
#define FETCH_FUNC_NAME(kind, type) fetch_##kind##_##type
/*
* Define macro for basic types - we don't need to define s* types, because
* we have to care only about bitwidth at recording time.
*/
#define DEFINE_BASIC_FETCH_FUNCS(kind) \
DEFINE_FETCH_##kind(u8) \
DEFINE_FETCH_##kind(u16) \
DEFINE_FETCH_##kind(u32) \
DEFINE_FETCH_##kind(u64)
#define CHECK_BASIC_FETCH_FUNCS(kind, fn) \
((FETCH_FUNC_NAME(kind, u8) == fn) || \
(FETCH_FUNC_NAME(kind, u16) == fn) || \
(FETCH_FUNC_NAME(kind, u32) == fn) || \
(FETCH_FUNC_NAME(kind, u64) == fn))
/* Data fetch function templates */
#define DEFINE_FETCH_reg(type) \
static __kprobes void FETCH_FUNC_NAME(reg, type)(struct pt_regs *regs, \
void *offset, void *dest) \
{ \
*(type *)dest = (type)regs_get_register(regs, \
(unsigned int)((unsigned long)offset)); \
}
DEFINE_BASIC_FETCH_FUNCS(reg)
#define DEFINE_FETCH_stack(type) \
static __kprobes void FETCH_FUNC_NAME(stack, type)(struct pt_regs *regs,\
void *offset, void *dest) \
{ \
*(type *)dest = (type)regs_get_kernel_stack_nth(regs, \
(unsigned int)((unsigned long)offset)); \
}
DEFINE_BASIC_FETCH_FUNCS(stack)
#define DEFINE_FETCH_retval(type) \
static __kprobes void FETCH_FUNC_NAME(retval, type)(struct pt_regs *regs,\
void *dummy, void *dest) \
{ \
*(type *)dest = (type)regs_return_value(regs); \
}
DEFINE_BASIC_FETCH_FUNCS(retval)
#define DEFINE_FETCH_memory(type) \
static __kprobes void FETCH_FUNC_NAME(memory, type)(struct pt_regs *regs,\
void *addr, void *dest) \
{ \
type retval; \
if (probe_kernel_address(addr, retval)) \
*(type *)dest = 0; \
else \
*(type *)dest = retval; \
}
DEFINE_BASIC_FETCH_FUNCS(memory)
/* Memory fetching by symbol */
struct symbol_cache {
char *symbol;
long offset;
unsigned long addr;
};
static unsigned long update_symbol_cache(struct symbol_cache *sc)
{
sc->addr = (unsigned long)kallsyms_lookup_name(sc->symbol);
if (sc->addr)
sc->addr += sc->offset;
return sc->addr;
}
static void free_symbol_cache(struct symbol_cache *sc)
{
kfree(sc->symbol);
kfree(sc);
}
static struct symbol_cache *alloc_symbol_cache(const char *sym, long offset)
{
struct symbol_cache *sc;
if (!sym || strlen(sym) == 0)
return NULL;
sc = kzalloc(sizeof(struct symbol_cache), GFP_KERNEL);
if (!sc)
return NULL;
sc->symbol = kstrdup(sym, GFP_KERNEL);
if (!sc->symbol) {
kfree(sc);
return NULL;
}
sc->offset = offset;
update_symbol_cache(sc);
return sc;
}
#define DEFINE_FETCH_symbol(type) \
static __kprobes void FETCH_FUNC_NAME(symbol, type)(struct pt_regs *regs,\
void *data, void *dest) \
{ \
struct symbol_cache *sc = data; \
if (sc->addr) \
fetch_memory_##type(regs, (void *)sc->addr, dest); \
else \
*(type *)dest = 0; \
}
DEFINE_BASIC_FETCH_FUNCS(symbol)
/* Dereference memory access function */
struct deref_fetch_param {
struct fetch_param orig;
long offset;
};
#define DEFINE_FETCH_deref(type) \
static __kprobes void FETCH_FUNC_NAME(deref, type)(struct pt_regs *regs,\
void *data, void *dest) \
{ \
struct deref_fetch_param *dprm = data; \
unsigned long addr; \
call_fetch(&dprm->orig, regs, &addr); \
if (addr) { \
addr += dprm->offset; \
fetch_memory_##type(regs, (void *)addr, dest); \
} else \
*(type *)dest = 0; \
}
DEFINE_BASIC_FETCH_FUNCS(deref)
static __kprobes void free_deref_fetch_param(struct deref_fetch_param *data)
{
if (CHECK_BASIC_FETCH_FUNCS(deref, data->orig.fn))
free_deref_fetch_param(data->orig.data);
else if (CHECK_BASIC_FETCH_FUNCS(symbol, data->orig.fn))
free_symbol_cache(data->orig.data);
kfree(data);
}
/* Default (unsigned long) fetch type */
#define __DEFAULT_FETCH_TYPE(t) u##t
#define _DEFAULT_FETCH_TYPE(t) __DEFAULT_FETCH_TYPE(t)
#define DEFAULT_FETCH_TYPE _DEFAULT_FETCH_TYPE(BITS_PER_LONG)
#define DEFAULT_FETCH_TYPE_STR __stringify(DEFAULT_FETCH_TYPE)
#define ASSIGN_FETCH_FUNC(kind, type) \
.kind = FETCH_FUNC_NAME(kind, type)
#define ASSIGN_FETCH_TYPE(ptype, ftype, sign) \
{.name = #ptype, \
.size = sizeof(ftype), \
.is_signed = sign, \
.print = PRINT_TYPE_FUNC_NAME(ptype), \
.fmt = PRINT_TYPE_FMT_NAME(ptype), \
ASSIGN_FETCH_FUNC(reg, ftype), \
ASSIGN_FETCH_FUNC(stack, ftype), \
ASSIGN_FETCH_FUNC(retval, ftype), \
ASSIGN_FETCH_FUNC(memory, ftype), \
ASSIGN_FETCH_FUNC(symbol, ftype), \
ASSIGN_FETCH_FUNC(deref, ftype), \
}
/* Fetch type information table */
static const struct fetch_type {
const char *name; /* Name of type */
size_t size; /* Byte size of type */
int is_signed; /* Signed flag */
print_type_func_t print; /* Print functions */
const char *fmt; /* Fromat string */
/* Fetch functions */
fetch_func_t reg;
fetch_func_t stack;
fetch_func_t retval;
fetch_func_t memory;
fetch_func_t symbol;
fetch_func_t deref;
} fetch_type_table[] = {
ASSIGN_FETCH_TYPE(u8, u8, 0),
ASSIGN_FETCH_TYPE(u16, u16, 0),
ASSIGN_FETCH_TYPE(u32, u32, 0),
ASSIGN_FETCH_TYPE(u64, u64, 0),
ASSIGN_FETCH_TYPE(s8, u8, 1),
ASSIGN_FETCH_TYPE(s16, u16, 1),
ASSIGN_FETCH_TYPE(s32, u32, 1),
ASSIGN_FETCH_TYPE(s64, u64, 1),
};
static const struct fetch_type *find_fetch_type(const char *type)
{
int i;
if (!type)
type = DEFAULT_FETCH_TYPE_STR;
for (i = 0; i < ARRAY_SIZE(fetch_type_table); i++)
if (strcmp(type, fetch_type_table[i].name) == 0)
return &fetch_type_table[i];
return NULL;
}
/* Special function : only accept unsigned long */
static __kprobes void fetch_stack_address(struct pt_regs *regs,
void *dummy, void *dest)
{
*(unsigned long *)dest = kernel_stack_pointer(regs);
}
/**
* Kprobe event core functions
*/
struct probe_arg {
struct fetch_param fetch;
unsigned int offset; /* Offset from argument entry */
const char *name; /* Name of this argument */
const char *comm; /* Command of this argument */
const struct fetch_type *type; /* Type of this argument */
};
/* Flags for trace_probe */
#define TP_FLAG_TRACE 1
#define TP_FLAG_PROFILE 2
struct trace_probe {
struct list_head list;
struct kretprobe rp; /* Use rp.kp for kprobe use */
unsigned long nhit;
unsigned int flags; /* For TP_FLAG_* */
const char *symbol; /* symbol name */
struct ftrace_event_class class;
struct ftrace_event_call call;
ssize_t size; /* trace entry size */
unsigned int nr_args;
struct probe_arg args[];
};
#define SIZEOF_TRACE_PROBE(n) \
(offsetof(struct trace_probe, args) + \
(sizeof(struct probe_arg) * (n)))
static __kprobes int probe_is_return(struct trace_probe *tp)
{
return tp->rp.handler != NULL;
}
static __kprobes const char *probe_symbol(struct trace_probe *tp)
{
return tp->symbol ? tp->symbol : "unknown";
}
static int register_probe_event(struct trace_probe *tp);
static void unregister_probe_event(struct trace_probe *tp);
static DEFINE_MUTEX(probe_lock);
static LIST_HEAD(probe_list);
static int kprobe_dispatcher(struct kprobe *kp, struct pt_regs *regs);
static int kretprobe_dispatcher(struct kretprobe_instance *ri,
struct pt_regs *regs);
/* Check the name is good for event/group */
static int check_event_name(const char *name)
{
if (!isalpha(*name) && *name != '_')
return 0;
while (*++name != '\0') {
if (!isalpha(*name) && !isdigit(*name) && *name != '_')
return 0;
}
return 1;
}
/*
* Allocate new trace_probe and initialize it (including kprobes).
*/
static struct trace_probe *alloc_trace_probe(const char *group,
const char *event,
void *addr,
const char *symbol,
unsigned long offs,
int nargs, int is_return)
{
struct trace_probe *tp;
int ret = -ENOMEM;
tp = kzalloc(SIZEOF_TRACE_PROBE(nargs), GFP_KERNEL);
if (!tp)
return ERR_PTR(ret);
if (symbol) {
tp->symbol = kstrdup(symbol, GFP_KERNEL);
if (!tp->symbol)
goto error;
tp->rp.kp.symbol_name = tp->symbol;
tp->rp.kp.offset = offs;
} else
tp->rp.kp.addr = addr;
if (is_return)
tp->rp.handler = kretprobe_dispatcher;
else
tp->rp.kp.pre_handler = kprobe_dispatcher;
if (!event || !check_event_name(event)) {
ret = -EINVAL;
goto error;
}
tp->call.class = &tp->class;
tp->call.name = kstrdup(event, GFP_KERNEL);
if (!tp->call.name)
goto error;
if (!group || !check_event_name(group)) {
ret = -EINVAL;
goto error;
}
tp->class.system = kstrdup(group, GFP_KERNEL);
if (!tp->class.system)
goto error;
INIT_LIST_HEAD(&tp->list);
return tp;
error:
kfree(tp->call.name);
kfree(tp->symbol);
kfree(tp);
return ERR_PTR(ret);
}
static void free_probe_arg(struct probe_arg *arg)
{
if (CHECK_BASIC_FETCH_FUNCS(deref, arg->fetch.fn))
free_deref_fetch_param(arg->fetch.data);
else if (CHECK_BASIC_FETCH_FUNCS(symbol, arg->fetch.fn))
free_symbol_cache(arg->fetch.data);
kfree(arg->name);
kfree(arg->comm);
}
static void free_trace_probe(struct trace_probe *tp)
{
int i;
for (i = 0; i < tp->nr_args; i++)
free_probe_arg(&tp->args[i]);
kfree(tp->call.class->system);
kfree(tp->call.name);
kfree(tp->symbol);
kfree(tp);
}
static struct trace_probe *find_probe_event(const char *event,
const char *group)
{
struct trace_probe *tp;
list_for_each_entry(tp, &probe_list, list)
if (strcmp(tp->call.name, event) == 0 &&
strcmp(tp->call.class->system, group) == 0)
return tp;
return NULL;
}
/* Unregister a trace_probe and probe_event: call with locking probe_lock */
static void unregister_trace_probe(struct trace_probe *tp)
{
if (probe_is_return(tp))
unregister_kretprobe(&tp->rp);
else
unregister_kprobe(&tp->rp.kp);
list_del(&tp->list);
unregister_probe_event(tp);
}
/* Register a trace_probe and probe_event */
static int register_trace_probe(struct trace_probe *tp)
{
struct trace_probe *old_tp;
int ret;
mutex_lock(&probe_lock);
/* register as an event */
old_tp = find_probe_event(tp->call.name, tp->call.class->system);
if (old_tp) {
/* delete old event */
unregister_trace_probe(old_tp);
free_trace_probe(old_tp);
}
ret = register_probe_event(tp);
if (ret) {
pr_warning("Faild to register probe event(%d)\n", ret);
goto end;
}
tp->rp.kp.flags |= KPROBE_FLAG_DISABLED;
if (probe_is_return(tp))
ret = register_kretprobe(&tp->rp);
else
ret = register_kprobe(&tp->rp.kp);
if (ret) {
pr_warning("Could not insert probe(%d)\n", ret);
if (ret == -EILSEQ) {
pr_warning("Probing address(0x%p) is not an "
"instruction boundary.\n",
tp->rp.kp.addr);
ret = -EINVAL;
}
unregister_probe_event(tp);
} else
list_add_tail(&tp->list, &probe_list);
end:
mutex_unlock(&probe_lock);
return ret;
}
/* Split symbol and offset. */
static int split_symbol_offset(char *symbol, unsigned long *offset)
{
char *tmp;
int ret;
if (!offset)
return -EINVAL;
tmp = strchr(symbol, '+');
if (tmp) {
/* skip sign because strict_strtol doesn't accept '+' */
ret = strict_strtoul(tmp + 1, 0, offset);
if (ret)
return ret;
*tmp = '\0';
} else
*offset = 0;
return 0;
}
#define PARAM_MAX_ARGS 16
#define PARAM_MAX_STACK (THREAD_SIZE / sizeof(unsigned long))
static int parse_probe_vars(char *arg, const struct fetch_type *t,
struct fetch_param *f, int is_return)
{
int ret = 0;
unsigned long param;
if (strcmp(arg, "retval") == 0) {
if (is_return)
f->fn = t->retval;
else
ret = -EINVAL;
} else if (strncmp(arg, "stack", 5) == 0) {
if (arg[5] == '\0') {
if (strcmp(t->name, DEFAULT_FETCH_TYPE_STR) == 0)
f->fn = fetch_stack_address;
else
ret = -EINVAL;
} else if (isdigit(arg[5])) {
ret = strict_strtoul(arg + 5, 10, ¶m);
if (ret || param > PARAM_MAX_STACK)
ret = -EINVAL;
else {
f->fn = t->stack;
f->data = (void *)param;
}
} else
ret = -EINVAL;
} else
ret = -EINVAL;
return ret;
}
/* Recursive argument parser */
static int __parse_probe_arg(char *arg, const struct fetch_type *t,
struct fetch_param *f, int is_return)
{
int ret = 0;
unsigned long param;
long offset;
char *tmp;
switch (arg[0]) {
case '$':
ret = parse_probe_vars(arg + 1, t, f, is_return);
break;
case '%': /* named register */
ret = regs_query_register_offset(arg + 1);
if (ret >= 0) {
f->fn = t->reg;
f->data = (void *)(unsigned long)ret;
ret = 0;
}
break;
case '@': /* memory or symbol */
if (isdigit(arg[1])) {
ret = strict_strtoul(arg + 1, 0, ¶m);
if (ret)
break;
f->fn = t->memory;
f->data = (void *)param;
} else {
ret = split_symbol_offset(arg + 1, &offset);
if (ret)
break;
f->data = alloc_symbol_cache(arg + 1, offset);
if (f->data)
f->fn = t->symbol;
}
break;
case '+': /* deref memory */
case '-':
tmp = strchr(arg, '(');
if (!tmp)
break;
*tmp = '\0';
ret = strict_strtol(arg + 1, 0, &offset);
if (ret)
break;
if (arg[0] == '-')
offset = -offset;
arg = tmp + 1;
tmp = strrchr(arg, ')');
if (tmp) {
struct deref_fetch_param *dprm;
const struct fetch_type *t2 = find_fetch_type(NULL);
*tmp = '\0';
dprm = kzalloc(sizeof(struct deref_fetch_param),
GFP_KERNEL);
if (!dprm)
return -ENOMEM;
dprm->offset = offset;
ret = __parse_probe_arg(arg, t2, &dprm->orig,
is_return);
if (ret)
kfree(dprm);
else {
f->fn = t->deref;
f->data = (void *)dprm;
}
}
break;
}
if (!ret && !f->fn)
ret = -EINVAL;
return ret;
}
/* String length checking wrapper */
static int parse_probe_arg(char *arg, struct trace_probe *tp,
struct probe_arg *parg, int is_return)
{
const char *t;
if (strlen(arg) > MAX_ARGSTR_LEN) {
pr_info("Argument is too long.: %s\n", arg);
return -ENOSPC;
}
parg->comm = kstrdup(arg, GFP_KERNEL);
if (!parg->comm) {
pr_info("Failed to allocate memory for command '%s'.\n", arg);
return -ENOMEM;
}
t = strchr(parg->comm, ':');
if (t) {
arg[t - parg->comm] = '\0';
t++;
}
parg->type = find_fetch_type(t);
if (!parg->type) {
pr_info("Unsupported type: %s\n", t);
return -EINVAL;
}
parg->offset = tp->size;
tp->size += parg->type->size;
return __parse_probe_arg(arg, parg->type, &parg->fetch, is_return);
}
/* Return 1 if name is reserved or already used by another argument */
static int conflict_field_name(const char *name,
struct probe_arg *args, int narg)
{
int i;
for (i = 0; i < ARRAY_SIZE(reserved_field_names); i++)
if (strcmp(reserved_field_names[i], name) == 0)
return 1;
for (i = 0; i < narg; i++)
if (strcmp(args[i].name, name) == 0)
return 1;
return 0;
}
static int create_trace_probe(int argc, char **argv)
{
/*
* Argument syntax:
* - Add kprobe: p[:[GRP/]EVENT] KSYM[+OFFS]|KADDR [FETCHARGS]
* - Add kretprobe: r[:[GRP/]EVENT] KSYM[+0] [FETCHARGS]
* Fetch args:
* $retval : fetch return value
* $stack : fetch stack address
* $stackN : fetch Nth of stack (N:0-)
* @ADDR : fetch memory at ADDR (ADDR should be in kernel)
* @SYM[+|-offs] : fetch memory at SYM +|- offs (SYM is a data symbol)
* %REG : fetch register REG
* Dereferencing memory fetch:
* +|-offs(ARG) : fetch memory at ARG +|- offs address.
* Alias name of args:
* NAME=FETCHARG : set NAME as alias of FETCHARG.
* Type of args:
* FETCHARG:TYPE : use TYPE instead of unsigned long.
*/
struct trace_probe *tp;
int i, ret = 0;
int is_return = 0, is_delete = 0;
char *symbol = NULL, *event = NULL, *group = NULL;
char *arg, *tmp;
unsigned long offset = 0;
void *addr = NULL;
char buf[MAX_EVENT_NAME_LEN];
/* argc must be >= 1 */
if (argv[0][0] == 'p')
is_return = 0;
else if (argv[0][0] == 'r')
is_return = 1;
else if (argv[0][0] == '-')
is_delete = 1;
else {
pr_info("Probe definition must be started with 'p', 'r' or"
" '-'.\n");
return -EINVAL;
}
if (argv[0][1] == ':') {
event = &argv[0][2];
if (strchr(event, '/')) {
group = event;
event = strchr(group, '/') + 1;
event[-1] = '\0';
if (strlen(group) == 0) {
pr_info("Group name is not specified\n");
return -EINVAL;
}
}
if (strlen(event) == 0) {
pr_info("Event name is not specified\n");
return -EINVAL;
}
}
if (!group)
group = KPROBE_EVENT_SYSTEM;
if (is_delete) {
if (!event) {
pr_info("Delete command needs an event name.\n");
return -EINVAL;
}
tp = find_probe_event(event, group);
if (!tp) {
pr_info("Event %s/%s doesn't exist.\n", group, event);
return -ENOENT;
}
/* delete an event */
unregister_trace_probe(tp);
free_trace_probe(tp);
return 0;
}
if (argc < 2) {
pr_info("Probe point is not specified.\n");
return -EINVAL;
}
if (isdigit(argv[1][0])) {
if (is_return) {
pr_info("Return probe point must be a symbol.\n");
return -EINVAL;
}
/* an address specified */
ret = strict_strtoul(&argv[1][0], 0, (unsigned long *)&addr);
if (ret) {
pr_info("Failed to parse address.\n");
return ret;
}
} else {
/* a symbol specified */
symbol = argv[1];
/* TODO: support .init module functions */
ret = split_symbol_offset(symbol, &offset);
if (ret) {
pr_info("Failed to parse symbol.\n");
return ret;
}
if (offset && is_return) {
pr_info("Return probe must be used without offset.\n");
return -EINVAL;
}
}
argc -= 2; argv += 2;
/* setup a probe */
if (!event) {
/* Make a new event name */
if (symbol)
snprintf(buf, MAX_EVENT_NAME_LEN, "%c_%s_%ld",
is_return ? 'r' : 'p', symbol, offset);
else
snprintf(buf, MAX_EVENT_NAME_LEN, "%c_0x%p",
is_return ? 'r' : 'p', addr);
event = buf;
}
tp = alloc_trace_probe(group, event, addr, symbol, offset, argc,
is_return);
if (IS_ERR(tp)) {
pr_info("Failed to allocate trace_probe.(%d)\n",
(int)PTR_ERR(tp));
return PTR_ERR(tp);
}
/* parse arguments */
ret = 0;
for (i = 0; i < argc && i < MAX_TRACE_ARGS; i++) {
/* Parse argument name */
arg = strchr(argv[i], '=');
if (arg)
*arg++ = '\0';
else
arg = argv[i];
tp->args[i].name = kstrdup(argv[i], GFP_KERNEL);
if (!tp->args[i].name) {
pr_info("Failed to allocate argument%d name '%s'.\n",
i, argv[i]);
ret = -ENOMEM;
goto error;
}
tmp = strchr(tp->args[i].name, ':');
if (tmp)
*tmp = '_'; /* convert : to _ */
if (conflict_field_name(tp->args[i].name, tp->args, i)) {
pr_info("Argument%d name '%s' conflicts with "
"another field.\n", i, argv[i]);
ret = -EINVAL;
goto error;
}
/* Parse fetch argument */
ret = parse_probe_arg(arg, tp, &tp->args[i], is_return);
if (ret) {
pr_info("Parse error at argument%d. (%d)\n", i, ret);
kfree(tp->args[i].name);
goto error;
}
tp->nr_args++;
}
ret = register_trace_probe(tp);
if (ret)
goto error;
return 0;
error:
free_trace_probe(tp);
return ret;
}
static void cleanup_all_probes(void)
{
struct trace_probe *tp;
mutex_lock(&probe_lock);
/* TODO: Use batch unregistration */
while (!list_empty(&probe_list)) {
tp = list_entry(probe_list.next, struct trace_probe, list);
unregister_trace_probe(tp);
free_trace_probe(tp);
}
mutex_unlock(&probe_lock);
}
/* Probes listing interfaces */
static void *probes_seq_start(struct seq_file *m, loff_t *pos)
{
mutex_lock(&probe_lock);
return seq_list_start(&probe_list, *pos);
}
static void *probes_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
return seq_list_next(v, &probe_list, pos);
}
static void probes_seq_stop(struct seq_file *m, void *v)
{
mutex_unlock(&probe_lock);
}
static int probes_seq_show(struct seq_file *m, void *v)
{
struct trace_probe *tp = v;
int i;
seq_printf(m, "%c", probe_is_return(tp) ? 'r' : 'p');
seq_printf(m, ":%s/%s", tp->call.class->system, tp->call.name);
if (!tp->symbol)
seq_printf(m, " 0x%p", tp->rp.kp.addr);
else if (tp->rp.kp.offset)
seq_printf(m, " %s+%u", probe_symbol(tp), tp->rp.kp.offset);
else
seq_printf(m, " %s", probe_symbol(tp));
for (i = 0; i < tp->nr_args; i++)
seq_printf(m, " %s=%s", tp->args[i].name, tp->args[i].comm);
seq_printf(m, "\n");
return 0;
}
static const struct seq_operations probes_seq_op = {
.start = probes_seq_start,
.next = probes_seq_next,
.stop = probes_seq_stop,
.show = probes_seq_show
};
static int probes_open(struct inode *inode, struct file *file)
{
if ((file->f_mode & FMODE_WRITE) &&
(file->f_flags & O_TRUNC))
cleanup_all_probes();
return seq_open(file, &probes_seq_op);
}
static int command_trace_probe(const char *buf)
{
char **argv;
int argc = 0, ret = 0;
argv = argv_split(GFP_KERNEL, buf, &argc);
if (!argv)
return -ENOMEM;
if (argc)
ret = create_trace_probe(argc, argv);
argv_free(argv);
return ret;
}
#define WRITE_BUFSIZE 128
static ssize_t probes_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
char *kbuf, *tmp;
int ret;
size_t done;
size_t size;
kbuf = kmalloc(WRITE_BUFSIZE, GFP_KERNEL);
if (!kbuf)
return -ENOMEM;
ret = done = 0;
while (done < count) {
size = count - done;
if (size >= WRITE_BUFSIZE)
size = WRITE_BUFSIZE - 1;
if (copy_from_user(kbuf, buffer + done, size)) {
ret = -EFAULT;
goto out;
}
kbuf[size] = '\0';
tmp = strchr(kbuf, '\n');
if (tmp) {
*tmp = '\0';
size = tmp - kbuf + 1;
} else if (done + size < count) {
pr_warning("Line length is too long: "
"Should be less than %d.", WRITE_BUFSIZE);
ret = -EINVAL;
goto out;
}
done += size;
/* Remove comments */
tmp = strchr(kbuf, '#');
if (tmp)
*tmp = '\0';
ret = command_trace_probe(kbuf);
if (ret)
goto out;
}
ret = done;
out:
kfree(kbuf);
return ret;
}
static const struct file_operations kprobe_events_ops = {
.owner = THIS_MODULE,
.open = probes_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
.write = probes_write,
};
/* Probes profiling interfaces */
static int probes_profile_seq_show(struct seq_file *m, void *v)
{
struct trace_probe *tp = v;
seq_printf(m, " %-44s %15lu %15lu\n", tp->call.name, tp->nhit,
tp->rp.kp.nmissed);
return 0;
}
static const struct seq_operations profile_seq_op = {
.start = probes_seq_start,
.next = probes_seq_next,
.stop = probes_seq_stop,
.show = probes_profile_seq_show
};
static int profile_open(struct inode *inode, struct file *file)
{
return seq_open(file, &profile_seq_op);
}
static const struct file_operations kprobe_profile_ops = {
.owner = THIS_MODULE,
.open = profile_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
/* Kprobe handler */
static __kprobes void kprobe_trace_func(struct kprobe *kp, struct pt_regs *regs)
{
struct trace_probe *tp = container_of(kp, struct trace_probe, rp.kp);
struct kprobe_trace_entry_head *entry;
struct ring_buffer_event *event;
struct ring_buffer *buffer;
u8 *data;
int size, i, pc;
unsigned long irq_flags;
struct ftrace_event_call *call = &tp->call;
tp->nhit++;
local_save_flags(irq_flags);
pc = preempt_count();
size = sizeof(*entry) + tp->size;
event = trace_current_buffer_lock_reserve(&buffer, call->event.type,
size, irq_flags, pc);
if (!event)
return;
entry = ring_buffer_event_data(event);
entry->ip = (unsigned long)kp->addr;
data = (u8 *)&entry[1];
for (i = 0; i < tp->nr_args; i++)
call_fetch(&tp->args[i].fetch, regs, data + tp->args[i].offset);
if (!filter_current_check_discard(buffer, call, entry, event))
trace_nowake_buffer_unlock_commit(buffer, event, irq_flags, pc);
}
/* Kretprobe handler */
static __kprobes void kretprobe_trace_func(struct kretprobe_instance *ri,
struct pt_regs *regs)
{
struct trace_probe *tp = container_of(ri->rp, struct trace_probe, rp);
struct kretprobe_trace_entry_head *entry;
struct ring_buffer_event *event;
struct ring_buffer *buffer;
u8 *data;
int size, i, pc;
unsigned long irq_flags;
struct ftrace_event_call *call = &tp->call;
local_save_flags(irq_flags);
pc = preempt_count();
size = sizeof(*entry) + tp->size;
event = trace_current_buffer_lock_reserve(&buffer, call->event.type,
size, irq_flags, pc);
if (!event)
return;
entry = ring_buffer_event_data(event);
entry->func = (unsigned long)tp->rp.kp.addr;
entry->ret_ip = (unsigned long)ri->ret_addr;
data = (u8 *)&entry[1];
for (i = 0; i < tp->nr_args; i++)
call_fetch(&tp->args[i].fetch, regs, data + tp->args[i].offset);
if (!filter_current_check_discard(buffer, call, entry, event))
trace_nowake_buffer_unlock_commit(buffer, event, irq_flags, pc);
}
/* Event entry printers */
enum print_line_t
print_kprobe_event(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct kprobe_trace_entry_head *field;
struct trace_seq *s = &iter->seq;
struct trace_probe *tp;
u8 *data;
int i;
field = (struct kprobe_trace_entry_head *)iter->ent;
tp = container_of(event, struct trace_probe, call.event);
if (!trace_seq_printf(s, "%s: (", tp->call.name))
goto partial;
if (!seq_print_ip_sym(s, field->ip, flags | TRACE_ITER_SYM_OFFSET))
goto partial;
if (!trace_seq_puts(s, ")"))
goto partial;
data = (u8 *)&field[1];
for (i = 0; i < tp->nr_args; i++)
if (!tp->args[i].type->print(s, tp->args[i].name,
data + tp->args[i].offset))
goto partial;
if (!trace_seq_puts(s, "\n"))
goto partial;
return TRACE_TYPE_HANDLED;
partial:
return TRACE_TYPE_PARTIAL_LINE;
}
enum print_line_t
print_kretprobe_event(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct kretprobe_trace_entry_head *field;
struct trace_seq *s = &iter->seq;
struct trace_probe *tp;
u8 *data;
int i;
field = (struct kretprobe_trace_entry_head *)iter->ent;
tp = container_of(event, struct trace_probe, call.event);
if (!trace_seq_printf(s, "%s: (", tp->call.name))
goto partial;
if (!seq_print_ip_sym(s, field->ret_ip, flags | TRACE_ITER_SYM_OFFSET))
goto partial;
if (!trace_seq_puts(s, " <- "))
goto partial;
if (!seq_print_ip_sym(s, field->func, flags & ~TRACE_ITER_SYM_OFFSET))
goto partial;
if (!trace_seq_puts(s, ")"))
goto partial;
data = (u8 *)&field[1];
for (i = 0; i < tp->nr_args; i++)
if (!tp->args[i].type->print(s, tp->args[i].name,
data + tp->args[i].offset))
goto partial;
if (!trace_seq_puts(s, "\n"))
goto partial;
return TRACE_TYPE_HANDLED;
partial:
return TRACE_TYPE_PARTIAL_LINE;
}
static int probe_event_enable(struct ftrace_event_call *call)
{
struct trace_probe *tp = (struct trace_probe *)call->data;
tp->flags |= TP_FLAG_TRACE;
if (probe_is_return(tp))
return enable_kretprobe(&tp->rp);
else
return enable_kprobe(&tp->rp.kp);
}
static void probe_event_disable(struct ftrace_event_call *call)
{
struct trace_probe *tp = (struct trace_probe *)call->data;
tp->flags &= ~TP_FLAG_TRACE;
if (!(tp->flags & (TP_FLAG_TRACE | TP_FLAG_PROFILE))) {
if (probe_is_return(tp))
disable_kretprobe(&tp->rp);
else
disable_kprobe(&tp->rp.kp);
}
}
static int probe_event_raw_init(struct ftrace_event_call *event_call)
{
return 0;
}
#undef DEFINE_FIELD
#define DEFINE_FIELD(type, item, name, is_signed) \
do { \
ret = trace_define_field(event_call, #type, name, \
offsetof(typeof(field), item), \
sizeof(field.item), is_signed, \
FILTER_OTHER); \
if (ret) \
return ret; \
} while (0)
static int kprobe_event_define_fields(struct ftrace_event_call *event_call)
{
int ret, i;
struct kprobe_trace_entry_head field;
struct trace_probe *tp = (struct trace_probe *)event_call->data;
DEFINE_FIELD(unsigned long, ip, FIELD_STRING_IP, 0);
/* Set argument names as fields */
for (i = 0; i < tp->nr_args; i++) {
ret = trace_define_field(event_call, tp->args[i].type->name,
tp->args[i].name,
sizeof(field) + tp->args[i].offset,
tp->args[i].type->size,
tp->args[i].type->is_signed,
FILTER_OTHER);
if (ret)
return ret;
}
return 0;
}
static int kretprobe_event_define_fields(struct ftrace_event_call *event_call)
{
int ret, i;
struct kretprobe_trace_entry_head field;
struct trace_probe *tp = (struct trace_probe *)event_call->data;
DEFINE_FIELD(unsigned long, func, FIELD_STRING_FUNC, 0);
DEFINE_FIELD(unsigned long, ret_ip, FIELD_STRING_RETIP, 0);
/* Set argument names as fields */
for (i = 0; i < tp->nr_args; i++) {
ret = trace_define_field(event_call, tp->args[i].type->name,
tp->args[i].name,
sizeof(field) + tp->args[i].offset,
tp->args[i].type->size,
tp->args[i].type->is_signed,
FILTER_OTHER);
if (ret)
return ret;
}
return 0;
}
static int __set_print_fmt(struct trace_probe *tp, char *buf, int len)
{
int i;
int pos = 0;
const char *fmt, *arg;
if (!probe_is_return(tp)) {
fmt = "(%lx)";
arg = "REC->" FIELD_STRING_IP;
} else {
fmt = "(%lx <- %lx)";
arg = "REC->" FIELD_STRING_FUNC ", REC->" FIELD_STRING_RETIP;
}
/* When len=0, we just calculate the needed length */
#define LEN_OR_ZERO (len ? len - pos : 0)
pos += snprintf(buf + pos, LEN_OR_ZERO, "\"%s", fmt);
for (i = 0; i < tp->nr_args; i++) {
pos += snprintf(buf + pos, LEN_OR_ZERO, " %s=%s",
tp->args[i].name, tp->args[i].type->fmt);
}
pos += snprintf(buf + pos, LEN_OR_ZERO, "\", %s", arg);
for (i = 0; i < tp->nr_args; i++) {
pos += snprintf(buf + pos, LEN_OR_ZERO, ", REC->%s",
tp->args[i].name);
}
#undef LEN_OR_ZERO
/* return the length of print_fmt */
return pos;
}
static int set_print_fmt(struct trace_probe *tp)
{
int len;
char *print_fmt;
/* First: called with 0 length to calculate the needed length */
len = __set_print_fmt(tp, NULL, 0);
print_fmt = kmalloc(len + 1, GFP_KERNEL);
if (!print_fmt)
return -ENOMEM;
/* Second: actually write the @print_fmt */
__set_print_fmt(tp, print_fmt, len + 1);
tp->call.print_fmt = print_fmt;
return 0;
}
#ifdef CONFIG_PERF_EVENTS
/* Kprobe profile handler */
static __kprobes void kprobe_perf_func(struct kprobe *kp,
struct pt_regs *regs)
{
struct trace_probe *tp = container_of(kp, struct trace_probe, rp.kp);
struct ftrace_event_call *call = &tp->call;
struct kprobe_trace_entry_head *entry;
struct hlist_head *head;
u8 *data;
int size, __size, i;
int rctx;
__size = sizeof(*entry) + tp->size;
size = ALIGN(__size + sizeof(u32), sizeof(u64));
size -= sizeof(u32);
if (WARN_ONCE(size > PERF_MAX_TRACE_SIZE,
"profile buffer not large enough"))
return;
entry = perf_trace_buf_prepare(size, call->event.type, regs, &rctx);
if (!entry)
return;
entry->ip = (unsigned long)kp->addr;
data = (u8 *)&entry[1];
for (i = 0; i < tp->nr_args; i++)
call_fetch(&tp->args[i].fetch, regs, data + tp->args[i].offset);
head = this_cpu_ptr(call->perf_events);
perf_trace_buf_submit(entry, size, rctx, entry->ip, 1, regs, head);
}
/* Kretprobe profile handler */
static __kprobes void kretprobe_perf_func(struct kretprobe_instance *ri,
struct pt_regs *regs)
{
struct trace_probe *tp = container_of(ri->rp, struct trace_probe, rp);
struct ftrace_event_call *call = &tp->call;
struct kretprobe_trace_entry_head *entry;
struct hlist_head *head;
u8 *data;
int size, __size, i;
int rctx;
__size = sizeof(*entry) + tp->size;
size = ALIGN(__size + sizeof(u32), sizeof(u64));
size -= sizeof(u32);
if (WARN_ONCE(size > PERF_MAX_TRACE_SIZE,
"profile buffer not large enough"))
return;
entry = perf_trace_buf_prepare(size, call->event.type, regs, &rctx);
if (!entry)
return;
entry->func = (unsigned long)tp->rp.kp.addr;
entry->ret_ip = (unsigned long)ri->ret_addr;
data = (u8 *)&entry[1];
for (i = 0; i < tp->nr_args; i++)
call_fetch(&tp->args[i].fetch, regs, data + tp->args[i].offset);
head = this_cpu_ptr(call->perf_events);
perf_trace_buf_submit(entry, size, rctx, entry->ret_ip, 1, regs, head);
}
static int probe_perf_enable(struct ftrace_event_call *call)
{
struct trace_probe *tp = (struct trace_probe *)call->data;
tp->flags |= TP_FLAG_PROFILE;
if (probe_is_return(tp))
return enable_kretprobe(&tp->rp);
else
return enable_kprobe(&tp->rp.kp);
}
static void probe_perf_disable(struct ftrace_event_call *call)
{
struct trace_probe *tp = (struct trace_probe *)call->data;
tp->flags &= ~TP_FLAG_PROFILE;
if (!(tp->flags & TP_FLAG_TRACE)) {
if (probe_is_return(tp))
disable_kretprobe(&tp->rp);
else
disable_kprobe(&tp->rp.kp);
}
}
#endif /* CONFIG_PERF_EVENTS */
static __kprobes
int kprobe_register(struct ftrace_event_call *event, enum trace_reg type)
{
switch (type) {
case TRACE_REG_REGISTER:
return probe_event_enable(event);
case TRACE_REG_UNREGISTER:
probe_event_disable(event);
return 0;
#ifdef CONFIG_PERF_EVENTS
case TRACE_REG_PERF_REGISTER:
return probe_perf_enable(event);
case TRACE_REG_PERF_UNREGISTER:
probe_perf_disable(event);
return 0;
#endif
}
return 0;
}
static __kprobes
int kprobe_dispatcher(struct kprobe *kp, struct pt_regs *regs)
{
struct trace_probe *tp = container_of(kp, struct trace_probe, rp.kp);
if (tp->flags & TP_FLAG_TRACE)
kprobe_trace_func(kp, regs);
#ifdef CONFIG_PERF_EVENTS
if (tp->flags & TP_FLAG_PROFILE)
kprobe_perf_func(kp, regs);
#endif
return 0; /* We don't tweek kernel, so just return 0 */
}
static __kprobes
int kretprobe_dispatcher(struct kretprobe_instance *ri, struct pt_regs *regs)
{
struct trace_probe *tp = container_of(ri->rp, struct trace_probe, rp);
if (tp->flags & TP_FLAG_TRACE)
kretprobe_trace_func(ri, regs);
#ifdef CONFIG_PERF_EVENTS
if (tp->flags & TP_FLAG_PROFILE)
kretprobe_perf_func(ri, regs);
#endif
return 0; /* We don't tweek kernel, so just return 0 */
}
static struct trace_event_functions kretprobe_funcs = {
.trace = print_kretprobe_event
};
static struct trace_event_functions kprobe_funcs = {
.trace = print_kprobe_event
};
static int register_probe_event(struct trace_probe *tp)
{
struct ftrace_event_call *call = &tp->call;
int ret;
/* Initialize ftrace_event_call */
if (probe_is_return(tp)) {
INIT_LIST_HEAD(&call->class->fields);
call->event.funcs = &kretprobe_funcs;
call->class->raw_init = probe_event_raw_init;
call->class->define_fields = kretprobe_event_define_fields;
} else {
INIT_LIST_HEAD(&call->class->fields);
call->event.funcs = &kprobe_funcs;
call->class->raw_init = probe_event_raw_init;
call->class->define_fields = kprobe_event_define_fields;
}
if (set_print_fmt(tp) < 0)
return -ENOMEM;
ret = register_ftrace_event(&call->event);
if (!ret) {
kfree(call->print_fmt);
return -ENODEV;
}
call->flags = 0;
call->class->reg = kprobe_register;
call->data = tp;
ret = trace_add_event_call(call);
if (ret) {
pr_info("Failed to register kprobe event: %s\n", call->name);
kfree(call->print_fmt);
unregister_ftrace_event(&call->event);
}
return ret;
}
static void unregister_probe_event(struct trace_probe *tp)
{
/* tp->event is unregistered in trace_remove_event_call() */
trace_remove_event_call(&tp->call);
kfree(tp->call.print_fmt);
}
/* Make a debugfs interface for controling probe points */
static __init int init_kprobe_trace(void)
{
struct dentry *d_tracer;
struct dentry *entry;
d_tracer = tracing_init_dentry();
if (!d_tracer)
return 0;
entry = debugfs_create_file("kprobe_events", 0644, d_tracer,
NULL, &kprobe_events_ops);
/* Event list interface */
if (!entry)
pr_warning("Could not create debugfs "
"'kprobe_events' entry\n");
/* Profile interface */
entry = debugfs_create_file("kprobe_profile", 0444, d_tracer,
NULL, &kprobe_profile_ops);
if (!entry)
pr_warning("Could not create debugfs "
"'kprobe_profile' entry\n");
return 0;
}
fs_initcall(init_kprobe_trace);
#ifdef CONFIG_FTRACE_STARTUP_TEST
static int kprobe_trace_selftest_target(int a1, int a2, int a3,
int a4, int a5, int a6)
{
return a1 + a2 + a3 + a4 + a5 + a6;
}
static __init int kprobe_trace_self_tests_init(void)
{
int ret, warn = 0;
int (*target)(int, int, int, int, int, int);
struct trace_probe *tp;
target = kprobe_trace_selftest_target;
pr_info("Testing kprobe tracing: ");
ret = command_trace_probe("p:testprobe kprobe_trace_selftest_target "
"$stack $stack0 +0($stack)");
if (WARN_ON_ONCE(ret)) {
pr_warning("error on probing function entry.\n");
warn++;
} else {
/* Enable trace point */
tp = find_probe_event("testprobe", KPROBE_EVENT_SYSTEM);
if (WARN_ON_ONCE(tp == NULL)) {
pr_warning("error on getting new probe.\n");
warn++;
} else
probe_event_enable(&tp->call);
}
ret = command_trace_probe("r:testprobe2 kprobe_trace_selftest_target "
"$retval");
if (WARN_ON_ONCE(ret)) {
pr_warning("error on probing function return.\n");
warn++;
} else {
/* Enable trace point */
tp = find_probe_event("testprobe2", KPROBE_EVENT_SYSTEM);
if (WARN_ON_ONCE(tp == NULL)) {
pr_warning("error on getting new probe.\n");
warn++;
} else
probe_event_enable(&tp->call);
}
if (warn)
goto end;
ret = target(1, 2, 3, 4, 5, 6);
ret = command_trace_probe("-:testprobe");
if (WARN_ON_ONCE(ret)) {
pr_warning("error on deleting a probe.\n");
warn++;
}
ret = command_trace_probe("-:testprobe2");
if (WARN_ON_ONCE(ret)) {
pr_warning("error on deleting a probe.\n");
warn++;
}
end:
cleanup_all_probes();
if (warn)
pr_cont("NG: Some tests are failed. Please check them.\n");
else
pr_cont("OK\n");
return 0;
}
late_initcall(kprobe_trace_self_tests_init);
#endif
| gpl-2.0 |
Krabappel2548/u8500_kernel_sources | .fr-dbVriS/kernel/arch/microblaze/pci/indirect_pci.c | 1020 | 4263 | /*
* Support for indirect PCI bridges.
*
* Copyright (C) 1998 Gabriel Paubert.
*
* 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/kernel.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/init.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
static int
indirect_read_config(struct pci_bus *bus, unsigned int devfn, int offset,
int len, u32 *val)
{
struct pci_controller *hose = pci_bus_to_host(bus);
volatile void __iomem *cfg_data;
u8 cfg_type = 0;
u32 bus_no, reg;
if (hose->indirect_type & INDIRECT_TYPE_NO_PCIE_LINK) {
if (bus->number != hose->first_busno)
return PCIBIOS_DEVICE_NOT_FOUND;
if (devfn != 0)
return PCIBIOS_DEVICE_NOT_FOUND;
}
if (hose->indirect_type & INDIRECT_TYPE_SET_CFG_TYPE)
if (bus->number != hose->first_busno)
cfg_type = 1;
bus_no = (bus->number == hose->first_busno) ?
hose->self_busno : bus->number;
if (hose->indirect_type & INDIRECT_TYPE_EXT_REG)
reg = ((offset & 0xf00) << 16) | (offset & 0xfc);
else
reg = offset & 0xfc; /* Only 3 bits for function */
if (hose->indirect_type & INDIRECT_TYPE_BIG_ENDIAN)
out_be32(hose->cfg_addr, (0x80000000 | (bus_no << 16) |
(devfn << 8) | reg | cfg_type));
else
out_le32(hose->cfg_addr, (0x80000000 | (bus_no << 16) |
(devfn << 8) | reg | cfg_type));
/*
* Note: the caller has already checked that offset is
* suitably aligned and that len is 1, 2 or 4.
*/
cfg_data = hose->cfg_data + (offset & 3); /* Only 3 bits for function */
switch (len) {
case 1:
*val = in_8(cfg_data);
break;
case 2:
*val = in_le16(cfg_data);
break;
default:
*val = in_le32(cfg_data);
break;
}
return PCIBIOS_SUCCESSFUL;
}
static int
indirect_write_config(struct pci_bus *bus, unsigned int devfn, int offset,
int len, u32 val)
{
struct pci_controller *hose = pci_bus_to_host(bus);
volatile void __iomem *cfg_data;
u8 cfg_type = 0;
u32 bus_no, reg;
if (hose->indirect_type & INDIRECT_TYPE_NO_PCIE_LINK) {
if (bus->number != hose->first_busno)
return PCIBIOS_DEVICE_NOT_FOUND;
if (devfn != 0)
return PCIBIOS_DEVICE_NOT_FOUND;
}
if (hose->indirect_type & INDIRECT_TYPE_SET_CFG_TYPE)
if (bus->number != hose->first_busno)
cfg_type = 1;
bus_no = (bus->number == hose->first_busno) ?
hose->self_busno : bus->number;
if (hose->indirect_type & INDIRECT_TYPE_EXT_REG)
reg = ((offset & 0xf00) << 16) | (offset & 0xfc);
else
reg = offset & 0xfc;
if (hose->indirect_type & INDIRECT_TYPE_BIG_ENDIAN)
out_be32(hose->cfg_addr, (0x80000000 | (bus_no << 16) |
(devfn << 8) | reg | cfg_type));
else
out_le32(hose->cfg_addr, (0x80000000 | (bus_no << 16) |
(devfn << 8) | reg | cfg_type));
/* surpress setting of PCI_PRIMARY_BUS */
if (hose->indirect_type & INDIRECT_TYPE_SURPRESS_PRIMARY_BUS)
if ((offset == PCI_PRIMARY_BUS) &&
(bus->number == hose->first_busno))
val &= 0xffffff00;
/* Workaround for PCI_28 Errata in 440EPx/GRx */
if ((hose->indirect_type & INDIRECT_TYPE_BROKEN_MRM) &&
offset == PCI_CACHE_LINE_SIZE) {
val = 0;
}
/*
* Note: the caller has already checked that offset is
* suitably aligned and that len is 1, 2 or 4.
*/
cfg_data = hose->cfg_data + (offset & 3);
switch (len) {
case 1:
out_8(cfg_data, val);
break;
case 2:
out_le16(cfg_data, val);
break;
default:
out_le32(cfg_data, val);
break;
}
return PCIBIOS_SUCCESSFUL;
}
static struct pci_ops indirect_pci_ops = {
.read = indirect_read_config,
.write = indirect_write_config,
};
void __init
setup_indirect_pci(struct pci_controller *hose,
resource_size_t cfg_addr,
resource_size_t cfg_data, u32 flags)
{
resource_size_t base = cfg_addr & PAGE_MASK;
void __iomem *mbase;
mbase = ioremap(base, PAGE_SIZE);
hose->cfg_addr = mbase + (cfg_addr & ~PAGE_MASK);
if ((cfg_data & PAGE_MASK) != base)
mbase = ioremap(cfg_data & PAGE_MASK, PAGE_SIZE);
hose->cfg_data = mbase + (cfg_data & ~PAGE_MASK);
hose->ops = &indirect_pci_ops;
hose->indirect_type = flags;
}
| gpl-2.0 |
floft/rpi-linux | drivers/input/touchscreen/cyttsp_core.c | 1020 | 14351 | /*
* Core Source for:
* Cypress TrueTouch(TM) Standard Product (TTSP) touchscreen drivers.
* For use with Cypress Txx3xx parts.
* Supported parts include:
* CY8CTST341
* CY8CTMA340
*
* Copyright (C) 2009, 2010, 2011 Cypress Semiconductor, Inc.
* Copyright (C) 2012 Javier Martinez Canillas <javier@dowhile0.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, 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.
*
* 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.
*
* Contact Cypress Semiconductor at www.cypress.com <kev@cypress.com>
*
*/
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include "cyttsp_core.h"
/* Bootloader number of command keys */
#define CY_NUM_BL_KEYS 8
/* helpers */
#define GET_NUM_TOUCHES(x) ((x) & 0x0F)
#define IS_LARGE_AREA(x) (((x) & 0x10) >> 4)
#define IS_BAD_PKT(x) ((x) & 0x20)
#define IS_VALID_APP(x) ((x) & 0x01)
#define IS_OPERATIONAL_ERR(x) ((x) & 0x3F)
#define GET_HSTMODE(reg) (((reg) & 0x70) >> 4)
#define GET_BOOTLOADERMODE(reg) (((reg) & 0x10) >> 4)
#define CY_REG_BASE 0x00
#define CY_REG_ACT_DIST 0x1E
#define CY_REG_ACT_INTRVL 0x1D
#define CY_REG_TCH_TMOUT (CY_REG_ACT_INTRVL + 1)
#define CY_REG_LP_INTRVL (CY_REG_TCH_TMOUT + 1)
#define CY_MAXZ 255
#define CY_DELAY_DFLT 20 /* ms */
#define CY_DELAY_MAX 500
#define CY_ACT_DIST_DFLT 0xF8
#define CY_HNDSHK_BIT 0x80
/* device mode bits */
#define CY_OPERATE_MODE 0x00
#define CY_SYSINFO_MODE 0x10
/* power mode select bits */
#define CY_SOFT_RESET_MODE 0x01 /* return to Bootloader mode */
#define CY_DEEP_SLEEP_MODE 0x02
#define CY_LOW_POWER_MODE 0x04
/* Slots management */
#define CY_MAX_FINGER 4
#define CY_MAX_ID 16
static const u8 bl_command[] = {
0x00, /* file offset */
0xFF, /* command */
0xA5, /* exit bootloader command */
0, 1, 2, 3, 4, 5, 6, 7 /* default keys */
};
static int ttsp_read_block_data(struct cyttsp *ts, u8 command,
u8 length, void *buf)
{
int error;
int tries;
for (tries = 0; tries < CY_NUM_RETRY; tries++) {
error = ts->bus_ops->read(ts->dev, ts->xfer_buf, command,
length, buf);
if (!error)
return 0;
msleep(CY_DELAY_DFLT);
}
return -EIO;
}
static int ttsp_write_block_data(struct cyttsp *ts, u8 command,
u8 length, void *buf)
{
int error;
int tries;
for (tries = 0; tries < CY_NUM_RETRY; tries++) {
error = ts->bus_ops->write(ts->dev, ts->xfer_buf, command,
length, buf);
if (!error)
return 0;
msleep(CY_DELAY_DFLT);
}
return -EIO;
}
static int ttsp_send_command(struct cyttsp *ts, u8 cmd)
{
return ttsp_write_block_data(ts, CY_REG_BASE, sizeof(cmd), &cmd);
}
static int cyttsp_handshake(struct cyttsp *ts)
{
if (ts->pdata->use_hndshk)
return ttsp_send_command(ts,
ts->xy_data.hst_mode ^ CY_HNDSHK_BIT);
return 0;
}
static int cyttsp_load_bl_regs(struct cyttsp *ts)
{
memset(&ts->bl_data, 0, sizeof(ts->bl_data));
ts->bl_data.bl_status = 0x10;
return ttsp_read_block_data(ts, CY_REG_BASE,
sizeof(ts->bl_data), &ts->bl_data);
}
static int cyttsp_exit_bl_mode(struct cyttsp *ts)
{
int error;
u8 bl_cmd[sizeof(bl_command)];
memcpy(bl_cmd, bl_command, sizeof(bl_command));
if (ts->pdata->bl_keys)
memcpy(&bl_cmd[sizeof(bl_command) - CY_NUM_BL_KEYS],
ts->pdata->bl_keys, CY_NUM_BL_KEYS);
error = ttsp_write_block_data(ts, CY_REG_BASE,
sizeof(bl_cmd), bl_cmd);
if (error)
return error;
/* wait for TTSP Device to complete the operation */
msleep(CY_DELAY_DFLT);
error = cyttsp_load_bl_regs(ts);
if (error)
return error;
if (GET_BOOTLOADERMODE(ts->bl_data.bl_status))
return -EIO;
return 0;
}
static int cyttsp_set_operational_mode(struct cyttsp *ts)
{
int error;
error = ttsp_send_command(ts, CY_OPERATE_MODE);
if (error)
return error;
/* wait for TTSP Device to complete switch to Operational mode */
error = ttsp_read_block_data(ts, CY_REG_BASE,
sizeof(ts->xy_data), &ts->xy_data);
if (error)
return error;
error = cyttsp_handshake(ts);
if (error)
return error;
return ts->xy_data.act_dist == CY_ACT_DIST_DFLT ? -EIO : 0;
}
static int cyttsp_set_sysinfo_mode(struct cyttsp *ts)
{
int error;
memset(&ts->sysinfo_data, 0, sizeof(ts->sysinfo_data));
/* switch to sysinfo mode */
error = ttsp_send_command(ts, CY_SYSINFO_MODE);
if (error)
return error;
/* read sysinfo registers */
msleep(CY_DELAY_DFLT);
error = ttsp_read_block_data(ts, CY_REG_BASE, sizeof(ts->sysinfo_data),
&ts->sysinfo_data);
if (error)
return error;
error = cyttsp_handshake(ts);
if (error)
return error;
if (!ts->sysinfo_data.tts_verh && !ts->sysinfo_data.tts_verl)
return -EIO;
return 0;
}
static int cyttsp_set_sysinfo_regs(struct cyttsp *ts)
{
int retval = 0;
if (ts->pdata->act_intrvl != CY_ACT_INTRVL_DFLT ||
ts->pdata->tch_tmout != CY_TCH_TMOUT_DFLT ||
ts->pdata->lp_intrvl != CY_LP_INTRVL_DFLT) {
u8 intrvl_ray[] = {
ts->pdata->act_intrvl,
ts->pdata->tch_tmout,
ts->pdata->lp_intrvl
};
/* set intrvl registers */
retval = ttsp_write_block_data(ts, CY_REG_ACT_INTRVL,
sizeof(intrvl_ray), intrvl_ray);
msleep(CY_DELAY_DFLT);
}
return retval;
}
static int cyttsp_soft_reset(struct cyttsp *ts)
{
unsigned long timeout;
int retval;
/* wait for interrupt to set ready completion */
reinit_completion(&ts->bl_ready);
ts->state = CY_BL_STATE;
enable_irq(ts->irq);
retval = ttsp_send_command(ts, CY_SOFT_RESET_MODE);
if (retval)
goto out;
timeout = wait_for_completion_timeout(&ts->bl_ready,
msecs_to_jiffies(CY_DELAY_DFLT * CY_DELAY_MAX));
retval = timeout ? 0 : -EIO;
out:
ts->state = CY_IDLE_STATE;
disable_irq(ts->irq);
return retval;
}
static int cyttsp_act_dist_setup(struct cyttsp *ts)
{
u8 act_dist_setup = ts->pdata->act_dist;
/* Init gesture; active distance setup */
return ttsp_write_block_data(ts, CY_REG_ACT_DIST,
sizeof(act_dist_setup), &act_dist_setup);
}
static void cyttsp_extract_track_ids(struct cyttsp_xydata *xy_data, int *ids)
{
ids[0] = xy_data->touch12_id >> 4;
ids[1] = xy_data->touch12_id & 0xF;
ids[2] = xy_data->touch34_id >> 4;
ids[3] = xy_data->touch34_id & 0xF;
}
static const struct cyttsp_tch *cyttsp_get_tch(struct cyttsp_xydata *xy_data,
int idx)
{
switch (idx) {
case 0:
return &xy_data->tch1;
case 1:
return &xy_data->tch2;
case 2:
return &xy_data->tch3;
case 3:
return &xy_data->tch4;
default:
return NULL;
}
}
static void cyttsp_report_tchdata(struct cyttsp *ts)
{
struct cyttsp_xydata *xy_data = &ts->xy_data;
struct input_dev *input = ts->input;
int num_tch = GET_NUM_TOUCHES(xy_data->tt_stat);
const struct cyttsp_tch *tch;
int ids[CY_MAX_ID];
int i;
DECLARE_BITMAP(used, CY_MAX_ID);
if (IS_LARGE_AREA(xy_data->tt_stat) == 1) {
/* terminate all active tracks */
num_tch = 0;
dev_dbg(ts->dev, "%s: Large area detected\n", __func__);
} else if (num_tch > CY_MAX_FINGER) {
/* terminate all active tracks */
num_tch = 0;
dev_dbg(ts->dev, "%s: Num touch error detected\n", __func__);
} else if (IS_BAD_PKT(xy_data->tt_mode)) {
/* terminate all active tracks */
num_tch = 0;
dev_dbg(ts->dev, "%s: Invalid buffer detected\n", __func__);
}
cyttsp_extract_track_ids(xy_data, ids);
bitmap_zero(used, CY_MAX_ID);
for (i = 0; i < num_tch; i++) {
tch = cyttsp_get_tch(xy_data, i);
input_mt_slot(input, ids[i]);
input_mt_report_slot_state(input, MT_TOOL_FINGER, true);
input_report_abs(input, ABS_MT_POSITION_X, be16_to_cpu(tch->x));
input_report_abs(input, ABS_MT_POSITION_Y, be16_to_cpu(tch->y));
input_report_abs(input, ABS_MT_TOUCH_MAJOR, tch->z);
__set_bit(ids[i], used);
}
for (i = 0; i < CY_MAX_ID; i++) {
if (test_bit(i, used))
continue;
input_mt_slot(input, i);
input_mt_report_slot_state(input, MT_TOOL_FINGER, false);
}
input_sync(input);
}
static irqreturn_t cyttsp_irq(int irq, void *handle)
{
struct cyttsp *ts = handle;
int error;
if (unlikely(ts->state == CY_BL_STATE)) {
complete(&ts->bl_ready);
goto out;
}
/* Get touch data from CYTTSP device */
error = ttsp_read_block_data(ts, CY_REG_BASE,
sizeof(struct cyttsp_xydata), &ts->xy_data);
if (error)
goto out;
/* provide flow control handshake */
error = cyttsp_handshake(ts);
if (error)
goto out;
if (unlikely(ts->state == CY_IDLE_STATE))
goto out;
if (GET_BOOTLOADERMODE(ts->xy_data.tt_mode)) {
/*
* TTSP device has reset back to bootloader mode.
* Restore to operational mode.
*/
error = cyttsp_exit_bl_mode(ts);
if (error) {
dev_err(ts->dev,
"Could not return to operational mode, err: %d\n",
error);
ts->state = CY_IDLE_STATE;
}
} else {
cyttsp_report_tchdata(ts);
}
out:
return IRQ_HANDLED;
}
static int cyttsp_power_on(struct cyttsp *ts)
{
int error;
error = cyttsp_soft_reset(ts);
if (error)
return error;
error = cyttsp_load_bl_regs(ts);
if (error)
return error;
if (GET_BOOTLOADERMODE(ts->bl_data.bl_status) &&
IS_VALID_APP(ts->bl_data.bl_status)) {
error = cyttsp_exit_bl_mode(ts);
if (error)
return error;
}
if (GET_HSTMODE(ts->bl_data.bl_file) != CY_OPERATE_MODE ||
IS_OPERATIONAL_ERR(ts->bl_data.bl_status)) {
return -ENODEV;
}
error = cyttsp_set_sysinfo_mode(ts);
if (error)
return error;
error = cyttsp_set_sysinfo_regs(ts);
if (error)
return error;
error = cyttsp_set_operational_mode(ts);
if (error)
return error;
/* init active distance */
error = cyttsp_act_dist_setup(ts);
if (error)
return error;
ts->state = CY_ACTIVE_STATE;
return 0;
}
static int cyttsp_enable(struct cyttsp *ts)
{
int error;
/*
* The device firmware can wake on an I2C or SPI memory slave
* address match. So just reading a register is sufficient to
* wake up the device. The first read attempt will fail but it
* will wake it up making the second read attempt successful.
*/
error = ttsp_read_block_data(ts, CY_REG_BASE,
sizeof(ts->xy_data), &ts->xy_data);
if (error)
return error;
if (GET_HSTMODE(ts->xy_data.hst_mode))
return -EIO;
enable_irq(ts->irq);
return 0;
}
static int cyttsp_disable(struct cyttsp *ts)
{
int error;
error = ttsp_send_command(ts, CY_LOW_POWER_MODE);
if (error)
return error;
disable_irq(ts->irq);
return 0;
}
static int __maybe_unused cyttsp_suspend(struct device *dev)
{
struct cyttsp *ts = dev_get_drvdata(dev);
int retval = 0;
mutex_lock(&ts->input->mutex);
if (ts->input->users) {
retval = cyttsp_disable(ts);
if (retval == 0)
ts->suspended = true;
}
mutex_unlock(&ts->input->mutex);
return retval;
}
static int __maybe_unused cyttsp_resume(struct device *dev)
{
struct cyttsp *ts = dev_get_drvdata(dev);
mutex_lock(&ts->input->mutex);
if (ts->input->users)
cyttsp_enable(ts);
ts->suspended = false;
mutex_unlock(&ts->input->mutex);
return 0;
}
SIMPLE_DEV_PM_OPS(cyttsp_pm_ops, cyttsp_suspend, cyttsp_resume);
EXPORT_SYMBOL_GPL(cyttsp_pm_ops);
static int cyttsp_open(struct input_dev *dev)
{
struct cyttsp *ts = input_get_drvdata(dev);
int retval = 0;
if (!ts->suspended)
retval = cyttsp_enable(ts);
return retval;
}
static void cyttsp_close(struct input_dev *dev)
{
struct cyttsp *ts = input_get_drvdata(dev);
if (!ts->suspended)
cyttsp_disable(ts);
}
struct cyttsp *cyttsp_probe(const struct cyttsp_bus_ops *bus_ops,
struct device *dev, int irq, size_t xfer_buf_size)
{
const struct cyttsp_platform_data *pdata = dev_get_platdata(dev);
struct cyttsp *ts;
struct input_dev *input_dev;
int error;
if (!pdata || !pdata->name || irq <= 0) {
error = -EINVAL;
goto err_out;
}
ts = kzalloc(sizeof(*ts) + xfer_buf_size, GFP_KERNEL);
input_dev = input_allocate_device();
if (!ts || !input_dev) {
error = -ENOMEM;
goto err_free_mem;
}
ts->dev = dev;
ts->input = input_dev;
ts->pdata = dev_get_platdata(dev);
ts->bus_ops = bus_ops;
ts->irq = irq;
init_completion(&ts->bl_ready);
snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(dev));
if (pdata->init) {
error = pdata->init();
if (error) {
dev_err(ts->dev, "platform init failed, err: %d\n",
error);
goto err_free_mem;
}
}
input_dev->name = pdata->name;
input_dev->phys = ts->phys;
input_dev->id.bustype = bus_ops->bustype;
input_dev->dev.parent = ts->dev;
input_dev->open = cyttsp_open;
input_dev->close = cyttsp_close;
input_set_drvdata(input_dev, ts);
__set_bit(EV_ABS, input_dev->evbit);
input_set_abs_params(input_dev, ABS_MT_POSITION_X,
0, pdata->maxx, 0, 0);
input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
0, pdata->maxy, 0, 0);
input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR,
0, CY_MAXZ, 0, 0);
input_mt_init_slots(input_dev, CY_MAX_ID, 0);
error = request_threaded_irq(ts->irq, NULL, cyttsp_irq,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
pdata->name, ts);
if (error) {
dev_err(ts->dev, "failed to request IRQ %d, err: %d\n",
ts->irq, error);
goto err_platform_exit;
}
disable_irq(ts->irq);
error = cyttsp_power_on(ts);
if (error)
goto err_free_irq;
error = input_register_device(input_dev);
if (error) {
dev_err(ts->dev, "failed to register input device: %d\n",
error);
goto err_free_irq;
}
return ts;
err_free_irq:
free_irq(ts->irq, ts);
err_platform_exit:
if (pdata->exit)
pdata->exit();
err_free_mem:
input_free_device(input_dev);
kfree(ts);
err_out:
return ERR_PTR(error);
}
EXPORT_SYMBOL_GPL(cyttsp_probe);
void cyttsp_remove(struct cyttsp *ts)
{
free_irq(ts->irq, ts);
input_unregister_device(ts->input);
if (ts->pdata->exit)
ts->pdata->exit();
kfree(ts);
}
EXPORT_SYMBOL_GPL(cyttsp_remove);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard touchscreen driver core");
MODULE_AUTHOR("Cypress");
| gpl-2.0 |
telf/error_state_capture_improvement | arch/arm/mach-omap2/mux.c | 1020 | 26547 | /*
* linux/arch/arm/mach-omap2/mux.c
*
* OMAP2, OMAP3 and OMAP4 pin multiplexing configurations
*
* Copyright (C) 2004 - 2010 Texas Instruments Inc.
* Copyright (C) 2003 - 2008 Nokia Corporation
*
* Written by Tony Lindgren
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/ctype.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include "omap_hwmod.h"
#include "soc.h"
#include "control.h"
#include "mux.h"
#include "prm.h"
#include "common.h"
#define OMAP_MUX_BASE_OFFSET 0x30 /* Offset from CTRL_BASE */
#define OMAP_MUX_BASE_SZ 0x5ca
struct omap_mux_entry {
struct omap_mux mux;
struct list_head node;
};
static LIST_HEAD(mux_partitions);
static DEFINE_MUTEX(muxmode_mutex);
struct omap_mux_partition *omap_mux_get(const char *name)
{
struct omap_mux_partition *partition;
list_for_each_entry(partition, &mux_partitions, node) {
if (!strcmp(name, partition->name))
return partition;
}
return NULL;
}
u16 omap_mux_read(struct omap_mux_partition *partition, u16 reg)
{
if (partition->flags & OMAP_MUX_REG_8BIT)
return readb_relaxed(partition->base + reg);
else
return readw_relaxed(partition->base + reg);
}
void omap_mux_write(struct omap_mux_partition *partition, u16 val,
u16 reg)
{
if (partition->flags & OMAP_MUX_REG_8BIT)
writeb_relaxed(val, partition->base + reg);
else
writew_relaxed(val, partition->base + reg);
}
void omap_mux_write_array(struct omap_mux_partition *partition,
struct omap_board_mux *board_mux)
{
if (!board_mux)
return;
while (board_mux->reg_offset != OMAP_MUX_TERMINATOR) {
omap_mux_write(partition, board_mux->value,
board_mux->reg_offset);
board_mux++;
}
}
#ifdef CONFIG_OMAP_MUX
static char *omap_mux_options;
static int __init _omap_mux_init_gpio(struct omap_mux_partition *partition,
int gpio, int val)
{
struct omap_mux_entry *e;
struct omap_mux *gpio_mux = NULL;
u16 old_mode;
u16 mux_mode;
int found = 0;
struct list_head *muxmodes = &partition->muxmodes;
if (!gpio)
return -EINVAL;
list_for_each_entry(e, muxmodes, node) {
struct omap_mux *m = &e->mux;
if (gpio == m->gpio) {
gpio_mux = m;
found++;
}
}
if (found == 0) {
pr_err("%s: Could not set gpio%i\n", __func__, gpio);
return -ENODEV;
}
if (found > 1) {
pr_info("%s: Multiple gpio paths (%d) for gpio%i\n", __func__,
found, gpio);
return -EINVAL;
}
old_mode = omap_mux_read(partition, gpio_mux->reg_offset);
mux_mode = val & ~(OMAP_MUX_NR_MODES - 1);
mux_mode |= partition->gpio;
pr_debug("%s: Setting signal %s.gpio%i 0x%04x -> 0x%04x\n", __func__,
gpio_mux->muxnames[0], gpio, old_mode, mux_mode);
omap_mux_write(partition, mux_mode, gpio_mux->reg_offset);
return 0;
}
int __init omap_mux_init_gpio(int gpio, int val)
{
struct omap_mux_partition *partition;
int ret;
list_for_each_entry(partition, &mux_partitions, node) {
ret = _omap_mux_init_gpio(partition, gpio, val);
if (!ret)
return ret;
}
return -ENODEV;
}
static int __init _omap_mux_get_by_name(struct omap_mux_partition *partition,
const char *muxname,
struct omap_mux **found_mux)
{
struct omap_mux *mux = NULL;
struct omap_mux_entry *e;
const char *mode_name;
int found = 0, found_mode = 0, mode0_len = 0;
struct list_head *muxmodes = &partition->muxmodes;
mode_name = strchr(muxname, '.');
if (mode_name) {
mode0_len = strlen(muxname) - strlen(mode_name);
mode_name++;
} else {
mode_name = muxname;
}
list_for_each_entry(e, muxmodes, node) {
char *m0_entry;
int i;
mux = &e->mux;
m0_entry = mux->muxnames[0];
/* First check for full name in mode0.muxmode format */
if (mode0_len)
if (strncmp(muxname, m0_entry, mode0_len) ||
(strlen(m0_entry) != mode0_len))
continue;
/* Then check for muxmode only */
for (i = 0; i < OMAP_MUX_NR_MODES; i++) {
char *mode_cur = mux->muxnames[i];
if (!mode_cur)
continue;
if (!strcmp(mode_name, mode_cur)) {
*found_mux = mux;
found++;
found_mode = i;
}
}
}
if (found == 1) {
return found_mode;
}
if (found > 1) {
pr_err("%s: Multiple signal paths (%i) for %s\n", __func__,
found, muxname);
return -EINVAL;
}
return -ENODEV;
}
int __init omap_mux_get_by_name(const char *muxname,
struct omap_mux_partition **found_partition,
struct omap_mux **found_mux)
{
struct omap_mux_partition *partition;
list_for_each_entry(partition, &mux_partitions, node) {
struct omap_mux *mux = NULL;
int mux_mode = _omap_mux_get_by_name(partition, muxname, &mux);
if (mux_mode < 0)
continue;
*found_partition = partition;
*found_mux = mux;
return mux_mode;
}
pr_err("%s: Could not find signal %s\n", __func__, muxname);
return -ENODEV;
}
int __init omap_mux_init_signal(const char *muxname, int val)
{
struct omap_mux_partition *partition = NULL;
struct omap_mux *mux = NULL;
u16 old_mode;
int mux_mode;
mux_mode = omap_mux_get_by_name(muxname, &partition, &mux);
if (mux_mode < 0 || !mux)
return mux_mode;
old_mode = omap_mux_read(partition, mux->reg_offset);
mux_mode |= val;
pr_debug("%s: Setting signal %s 0x%04x -> 0x%04x\n",
__func__, muxname, old_mode, mux_mode);
omap_mux_write(partition, mux_mode, mux->reg_offset);
return 0;
}
struct omap_hwmod_mux_info * __init
omap_hwmod_mux_init(struct omap_device_pad *bpads, int nr_pads)
{
struct omap_hwmod_mux_info *hmux;
int i, nr_pads_dynamic = 0;
if (!bpads || nr_pads < 1)
return NULL;
hmux = kzalloc(sizeof(struct omap_hwmod_mux_info), GFP_KERNEL);
if (!hmux)
goto err1;
hmux->nr_pads = nr_pads;
hmux->pads = kzalloc(sizeof(struct omap_device_pad) *
nr_pads, GFP_KERNEL);
if (!hmux->pads)
goto err2;
for (i = 0; i < hmux->nr_pads; i++) {
struct omap_mux_partition *partition;
struct omap_device_pad *bpad = &bpads[i], *pad = &hmux->pads[i];
struct omap_mux *mux;
int mux_mode;
mux_mode = omap_mux_get_by_name(bpad->name, &partition, &mux);
if (mux_mode < 0)
goto err3;
if (!pad->partition)
pad->partition = partition;
if (!pad->mux)
pad->mux = mux;
pad->name = kzalloc(strlen(bpad->name) + 1, GFP_KERNEL);
if (!pad->name) {
int j;
for (j = i - 1; j >= 0; j--)
kfree(hmux->pads[j].name);
goto err3;
}
strcpy(pad->name, bpad->name);
pad->flags = bpad->flags;
pad->enable = bpad->enable;
pad->idle = bpad->idle;
pad->off = bpad->off;
if (pad->flags &
(OMAP_DEVICE_PAD_REMUX | OMAP_DEVICE_PAD_WAKEUP))
nr_pads_dynamic++;
pr_debug("%s: Initialized %s\n", __func__, pad->name);
}
if (!nr_pads_dynamic)
return hmux;
/*
* Add pads that need dynamic muxing into a separate list
*/
hmux->nr_pads_dynamic = nr_pads_dynamic;
hmux->pads_dynamic = kzalloc(sizeof(struct omap_device_pad *) *
nr_pads_dynamic, GFP_KERNEL);
if (!hmux->pads_dynamic) {
pr_err("%s: Could not allocate dynamic pads\n", __func__);
return hmux;
}
nr_pads_dynamic = 0;
for (i = 0; i < hmux->nr_pads; i++) {
struct omap_device_pad *pad = &hmux->pads[i];
if (pad->flags &
(OMAP_DEVICE_PAD_REMUX | OMAP_DEVICE_PAD_WAKEUP)) {
pr_debug("%s: pad %s tagged dynamic\n",
__func__, pad->name);
hmux->pads_dynamic[nr_pads_dynamic] = pad;
nr_pads_dynamic++;
}
}
return hmux;
err3:
kfree(hmux->pads);
err2:
kfree(hmux);
err1:
pr_err("%s: Could not allocate device mux entry\n", __func__);
return NULL;
}
/**
* omap_hwmod_mux_scan_wakeups - omap hwmod scan wakeup pads
* @hmux: Pads for a hwmod
* @mpu_irqs: MPU irq array for a hwmod
*
* Scans the wakeup status of pads for a single hwmod. If an irq
* array is defined for this mux, the parser will call the registered
* ISRs for corresponding pads, otherwise the parser will stop at the
* first wakeup active pad and return. Returns true if there is a
* pending and non-served wakeup event for the mux, otherwise false.
*/
static bool omap_hwmod_mux_scan_wakeups(struct omap_hwmod_mux_info *hmux,
struct omap_hwmod_irq_info *mpu_irqs)
{
int i, irq;
unsigned int val;
u32 handled_irqs = 0;
for (i = 0; i < hmux->nr_pads_dynamic; i++) {
struct omap_device_pad *pad = hmux->pads_dynamic[i];
if (!(pad->flags & OMAP_DEVICE_PAD_WAKEUP) ||
!(pad->idle & OMAP_WAKEUP_EN))
continue;
val = omap_mux_read(pad->partition, pad->mux->reg_offset);
if (!(val & OMAP_WAKEUP_EVENT))
continue;
if (!hmux->irqs)
return true;
irq = hmux->irqs[i];
/* make sure we only handle each irq once */
if (handled_irqs & 1 << irq)
continue;
handled_irqs |= 1 << irq;
generic_handle_irq(mpu_irqs[irq].irq);
}
return false;
}
/**
* _omap_hwmod_mux_handle_irq - Process wakeup events for a single hwmod
*
* Checks a single hwmod for every wakeup capable pad to see if there is an
* active wakeup event. If this is the case, call the corresponding ISR.
*/
static int _omap_hwmod_mux_handle_irq(struct omap_hwmod *oh, void *data)
{
if (!oh->mux || !oh->mux->enabled)
return 0;
if (omap_hwmod_mux_scan_wakeups(oh->mux, oh->mpu_irqs))
generic_handle_irq(oh->mpu_irqs[0].irq);
return 0;
}
/**
* omap_hwmod_mux_handle_irq - Process pad wakeup irqs.
*
* Calls a function for each registered omap_hwmod to check
* pad wakeup statuses.
*/
static irqreturn_t omap_hwmod_mux_handle_irq(int irq, void *unused)
{
omap_hwmod_for_each(_omap_hwmod_mux_handle_irq, NULL);
return IRQ_HANDLED;
}
/* Assumes the calling function takes care of locking */
void omap_hwmod_mux(struct omap_hwmod_mux_info *hmux, u8 state)
{
int i;
/* Runtime idling of dynamic pads */
if (state == _HWMOD_STATE_IDLE && hmux->enabled) {
for (i = 0; i < hmux->nr_pads_dynamic; i++) {
struct omap_device_pad *pad = hmux->pads_dynamic[i];
int val = -EINVAL;
val = pad->idle;
omap_mux_write(pad->partition, val,
pad->mux->reg_offset);
}
return;
}
/* Runtime enabling of dynamic pads */
if ((state == _HWMOD_STATE_ENABLED) && hmux->pads_dynamic
&& hmux->enabled) {
for (i = 0; i < hmux->nr_pads_dynamic; i++) {
struct omap_device_pad *pad = hmux->pads_dynamic[i];
int val = -EINVAL;
val = pad->enable;
omap_mux_write(pad->partition, val,
pad->mux->reg_offset);
}
return;
}
/* Enabling or disabling of all pads */
for (i = 0; i < hmux->nr_pads; i++) {
struct omap_device_pad *pad = &hmux->pads[i];
int flags, val = -EINVAL;
flags = pad->flags;
switch (state) {
case _HWMOD_STATE_ENABLED:
val = pad->enable;
pr_debug("%s: Enabling %s %x\n", __func__,
pad->name, val);
break;
case _HWMOD_STATE_DISABLED:
/* Use safe mode unless OMAP_DEVICE_PAD_REMUX */
if (flags & OMAP_DEVICE_PAD_REMUX)
val = pad->off;
else
val = OMAP_MUX_MODE7;
pr_debug("%s: Disabling %s %x\n", __func__,
pad->name, val);
break;
default:
/* Nothing to be done */
break;
}
if (val >= 0) {
omap_mux_write(pad->partition, val,
pad->mux->reg_offset);
pad->flags = flags;
}
}
if (state == _HWMOD_STATE_ENABLED)
hmux->enabled = true;
else
hmux->enabled = false;
}
#ifdef CONFIG_DEBUG_FS
#define OMAP_MUX_MAX_NR_FLAGS 10
#define OMAP_MUX_TEST_FLAG(val, mask) \
if (((val) & (mask)) == (mask)) { \
i++; \
flags[i] = #mask; \
}
/* REVISIT: Add checking for non-optimal mux settings */
static inline void omap_mux_decode(struct seq_file *s, u16 val)
{
char *flags[OMAP_MUX_MAX_NR_FLAGS];
char mode[sizeof("OMAP_MUX_MODE") + 1];
int i = -1;
sprintf(mode, "OMAP_MUX_MODE%d", val & 0x7);
i++;
flags[i] = mode;
OMAP_MUX_TEST_FLAG(val, OMAP_PIN_OFF_WAKEUPENABLE);
if (val & OMAP_OFF_EN) {
if (!(val & OMAP_OFFOUT_EN)) {
if (!(val & OMAP_OFF_PULL_UP)) {
OMAP_MUX_TEST_FLAG(val,
OMAP_PIN_OFF_INPUT_PULLDOWN);
} else {
OMAP_MUX_TEST_FLAG(val,
OMAP_PIN_OFF_INPUT_PULLUP);
}
} else {
if (!(val & OMAP_OFFOUT_VAL)) {
OMAP_MUX_TEST_FLAG(val,
OMAP_PIN_OFF_OUTPUT_LOW);
} else {
OMAP_MUX_TEST_FLAG(val,
OMAP_PIN_OFF_OUTPUT_HIGH);
}
}
}
if (val & OMAP_INPUT_EN) {
if (val & OMAP_PULL_ENA) {
if (!(val & OMAP_PULL_UP)) {
OMAP_MUX_TEST_FLAG(val,
OMAP_PIN_INPUT_PULLDOWN);
} else {
OMAP_MUX_TEST_FLAG(val, OMAP_PIN_INPUT_PULLUP);
}
} else {
OMAP_MUX_TEST_FLAG(val, OMAP_PIN_INPUT);
}
} else {
i++;
flags[i] = "OMAP_PIN_OUTPUT";
}
do {
seq_printf(s, "%s", flags[i]);
if (i > 0)
seq_printf(s, " | ");
} while (i-- > 0);
}
#define OMAP_MUX_DEFNAME_LEN 32
static int omap_mux_dbg_board_show(struct seq_file *s, void *unused)
{
struct omap_mux_partition *partition = s->private;
struct omap_mux_entry *e;
u8 omap_gen = omap_rev() >> 28;
list_for_each_entry(e, &partition->muxmodes, node) {
struct omap_mux *m = &e->mux;
char m0_def[OMAP_MUX_DEFNAME_LEN];
char *m0_name = m->muxnames[0];
u16 val;
int i, mode;
if (!m0_name)
continue;
/* REVISIT: Needs to be updated if mode0 names get longer */
for (i = 0; i < OMAP_MUX_DEFNAME_LEN; i++) {
if (m0_name[i] == '\0') {
m0_def[i] = m0_name[i];
break;
}
m0_def[i] = toupper(m0_name[i]);
}
val = omap_mux_read(partition, m->reg_offset);
mode = val & OMAP_MUX_MODE7;
if (mode != 0)
seq_printf(s, "/* %s */\n", m->muxnames[mode]);
/*
* XXX: Might be revisited to support differences across
* same OMAP generation.
*/
seq_printf(s, "OMAP%d_MUX(%s, ", omap_gen, m0_def);
omap_mux_decode(s, val);
seq_printf(s, "),\n");
}
return 0;
}
static int omap_mux_dbg_board_open(struct inode *inode, struct file *file)
{
return single_open(file, omap_mux_dbg_board_show, inode->i_private);
}
static const struct file_operations omap_mux_dbg_board_fops = {
.open = omap_mux_dbg_board_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static struct omap_mux_partition *omap_mux_get_partition(struct omap_mux *mux)
{
struct omap_mux_partition *partition;
list_for_each_entry(partition, &mux_partitions, node) {
struct list_head *muxmodes = &partition->muxmodes;
struct omap_mux_entry *e;
list_for_each_entry(e, muxmodes, node) {
struct omap_mux *m = &e->mux;
if (m == mux)
return partition;
}
}
return NULL;
}
static int omap_mux_dbg_signal_show(struct seq_file *s, void *unused)
{
struct omap_mux *m = s->private;
struct omap_mux_partition *partition;
const char *none = "NA";
u16 val;
int mode;
partition = omap_mux_get_partition(m);
if (!partition)
return 0;
val = omap_mux_read(partition, m->reg_offset);
mode = val & OMAP_MUX_MODE7;
seq_printf(s, "name: %s.%s (0x%08x/0x%03x = 0x%04x), b %s, t %s\n",
m->muxnames[0], m->muxnames[mode],
partition->phys + m->reg_offset, m->reg_offset, val,
m->balls[0] ? m->balls[0] : none,
m->balls[1] ? m->balls[1] : none);
seq_printf(s, "mode: ");
omap_mux_decode(s, val);
seq_printf(s, "\n");
seq_printf(s, "signals: %s | %s | %s | %s | %s | %s | %s | %s\n",
m->muxnames[0] ? m->muxnames[0] : none,
m->muxnames[1] ? m->muxnames[1] : none,
m->muxnames[2] ? m->muxnames[2] : none,
m->muxnames[3] ? m->muxnames[3] : none,
m->muxnames[4] ? m->muxnames[4] : none,
m->muxnames[5] ? m->muxnames[5] : none,
m->muxnames[6] ? m->muxnames[6] : none,
m->muxnames[7] ? m->muxnames[7] : none);
return 0;
}
#define OMAP_MUX_MAX_ARG_CHAR 7
static ssize_t omap_mux_dbg_signal_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct seq_file *seqf;
struct omap_mux *m;
u16 val;
int ret;
struct omap_mux_partition *partition;
if (count > OMAP_MUX_MAX_ARG_CHAR)
return -EINVAL;
ret = kstrtou16_from_user(user_buf, count, 0x10, &val);
if (ret < 0)
return ret;
seqf = file->private_data;
m = seqf->private;
partition = omap_mux_get_partition(m);
if (!partition)
return -ENODEV;
omap_mux_write(partition, val, m->reg_offset);
*ppos += count;
return count;
}
static int omap_mux_dbg_signal_open(struct inode *inode, struct file *file)
{
return single_open(file, omap_mux_dbg_signal_show, inode->i_private);
}
static const struct file_operations omap_mux_dbg_signal_fops = {
.open = omap_mux_dbg_signal_open,
.read = seq_read,
.write = omap_mux_dbg_signal_write,
.llseek = seq_lseek,
.release = single_release,
};
static struct dentry *mux_dbg_dir;
static void __init omap_mux_dbg_create_entry(
struct omap_mux_partition *partition,
struct dentry *mux_dbg_dir)
{
struct omap_mux_entry *e;
list_for_each_entry(e, &partition->muxmodes, node) {
struct omap_mux *m = &e->mux;
(void)debugfs_create_file(m->muxnames[0], S_IWUSR | S_IRUGO,
mux_dbg_dir, m,
&omap_mux_dbg_signal_fops);
}
}
static void __init omap_mux_dbg_init(void)
{
struct omap_mux_partition *partition;
static struct dentry *mux_dbg_board_dir;
mux_dbg_dir = debugfs_create_dir("omap_mux", NULL);
if (!mux_dbg_dir)
return;
mux_dbg_board_dir = debugfs_create_dir("board", mux_dbg_dir);
if (!mux_dbg_board_dir)
return;
list_for_each_entry(partition, &mux_partitions, node) {
omap_mux_dbg_create_entry(partition, mux_dbg_dir);
(void)debugfs_create_file(partition->name, S_IRUGO,
mux_dbg_board_dir, partition,
&omap_mux_dbg_board_fops);
}
}
#else
static inline void omap_mux_dbg_init(void)
{
}
#endif /* CONFIG_DEBUG_FS */
static void __init omap_mux_free_names(struct omap_mux *m)
{
int i;
for (i = 0; i < OMAP_MUX_NR_MODES; i++)
kfree(m->muxnames[i]);
#ifdef CONFIG_DEBUG_FS
for (i = 0; i < OMAP_MUX_NR_SIDES; i++)
kfree(m->balls[i]);
#endif
}
/* Free all data except for GPIO pins unless CONFIG_DEBUG_FS is set */
int __init omap_mux_late_init(void)
{
struct omap_mux_partition *partition;
int ret;
list_for_each_entry(partition, &mux_partitions, node) {
struct omap_mux_entry *e, *tmp;
list_for_each_entry_safe(e, tmp, &partition->muxmodes, node) {
struct omap_mux *m = &e->mux;
u16 mode = omap_mux_read(partition, m->reg_offset);
if (OMAP_MODE_GPIO(partition, mode))
continue;
#ifndef CONFIG_DEBUG_FS
mutex_lock(&muxmode_mutex);
list_del(&e->node);
mutex_unlock(&muxmode_mutex);
omap_mux_free_names(m);
kfree(m);
#endif
}
}
omap_mux_dbg_init();
/* see pinctrl-single-omap for the wake-up interrupt handling */
if (of_have_populated_dt())
return 0;
ret = request_irq(omap_prcm_event_to_irq("io"),
omap_hwmod_mux_handle_irq, IRQF_SHARED | IRQF_NO_SUSPEND,
"hwmod_io", omap_mux_late_init);
if (ret)
pr_warn("mux: Failed to setup hwmod io irq %d\n", ret);
return 0;
}
static void __init omap_mux_package_fixup(struct omap_mux *p,
struct omap_mux *superset)
{
while (p->reg_offset != OMAP_MUX_TERMINATOR) {
struct omap_mux *s = superset;
int found = 0;
while (s->reg_offset != OMAP_MUX_TERMINATOR) {
if (s->reg_offset == p->reg_offset) {
*s = *p;
found++;
break;
}
s++;
}
if (!found)
pr_err("%s: Unknown entry offset 0x%x\n", __func__,
p->reg_offset);
p++;
}
}
#ifdef CONFIG_DEBUG_FS
static void __init omap_mux_package_init_balls(struct omap_ball *b,
struct omap_mux *superset)
{
while (b->reg_offset != OMAP_MUX_TERMINATOR) {
struct omap_mux *s = superset;
int found = 0;
while (s->reg_offset != OMAP_MUX_TERMINATOR) {
if (s->reg_offset == b->reg_offset) {
s->balls[0] = b->balls[0];
s->balls[1] = b->balls[1];
found++;
break;
}
s++;
}
if (!found)
pr_err("%s: Unknown ball offset 0x%x\n", __func__,
b->reg_offset);
b++;
}
}
#else /* CONFIG_DEBUG_FS */
static inline void omap_mux_package_init_balls(struct omap_ball *b,
struct omap_mux *superset)
{
}
#endif /* CONFIG_DEBUG_FS */
static int __init omap_mux_setup(char *options)
{
if (!options)
return 0;
omap_mux_options = options;
return 1;
}
__setup("omap_mux=", omap_mux_setup);
/*
* Note that the omap_mux=some.signal1=0x1234,some.signal2=0x1234
* cmdline options only override the bootloader values.
* During development, please enable CONFIG_DEBUG_FS, and use the
* signal specific entries under debugfs.
*/
static void __init omap_mux_set_cmdline_signals(void)
{
char *options, *next_opt, *token;
if (!omap_mux_options)
return;
options = kstrdup(omap_mux_options, GFP_KERNEL);
if (!options)
return;
next_opt = options;
while ((token = strsep(&next_opt, ",")) != NULL) {
char *keyval, *name;
u16 val;
keyval = token;
name = strsep(&keyval, "=");
if (name) {
int res;
res = kstrtou16(keyval, 0x10, &val);
if (res < 0)
continue;
omap_mux_init_signal(name, (u16)val);
}
}
kfree(options);
}
static int __init omap_mux_copy_names(struct omap_mux *src,
struct omap_mux *dst)
{
int i;
for (i = 0; i < OMAP_MUX_NR_MODES; i++) {
if (src->muxnames[i]) {
dst->muxnames[i] = kstrdup(src->muxnames[i],
GFP_KERNEL);
if (!dst->muxnames[i])
goto free;
}
}
#ifdef CONFIG_DEBUG_FS
for (i = 0; i < OMAP_MUX_NR_SIDES; i++) {
if (src->balls[i]) {
dst->balls[i] = kstrdup(src->balls[i], GFP_KERNEL);
if (!dst->balls[i])
goto free;
}
}
#endif
return 0;
free:
omap_mux_free_names(dst);
return -ENOMEM;
}
#endif /* CONFIG_OMAP_MUX */
static struct omap_mux *omap_mux_get_by_gpio(
struct omap_mux_partition *partition,
int gpio)
{
struct omap_mux_entry *e;
struct omap_mux *ret = NULL;
list_for_each_entry(e, &partition->muxmodes, node) {
struct omap_mux *m = &e->mux;
if (m->gpio == gpio) {
ret = m;
break;
}
}
return ret;
}
/* Needed for dynamic muxing of GPIO pins for off-idle */
u16 omap_mux_get_gpio(int gpio)
{
struct omap_mux_partition *partition;
struct omap_mux *m = NULL;
list_for_each_entry(partition, &mux_partitions, node) {
m = omap_mux_get_by_gpio(partition, gpio);
if (m)
return omap_mux_read(partition, m->reg_offset);
}
if (!m || m->reg_offset == OMAP_MUX_TERMINATOR)
pr_err("%s: Could not get gpio%i\n", __func__, gpio);
return OMAP_MUX_TERMINATOR;
}
/* Needed for dynamic muxing of GPIO pins for off-idle */
void omap_mux_set_gpio(u16 val, int gpio)
{
struct omap_mux_partition *partition;
struct omap_mux *m = NULL;
list_for_each_entry(partition, &mux_partitions, node) {
m = omap_mux_get_by_gpio(partition, gpio);
if (m) {
omap_mux_write(partition, val, m->reg_offset);
return;
}
}
if (!m || m->reg_offset == OMAP_MUX_TERMINATOR)
pr_err("%s: Could not set gpio%i\n", __func__, gpio);
}
static struct omap_mux * __init omap_mux_list_add(
struct omap_mux_partition *partition,
struct omap_mux *src)
{
struct omap_mux_entry *entry;
struct omap_mux *m;
entry = kzalloc(sizeof(struct omap_mux_entry), GFP_KERNEL);
if (!entry)
return NULL;
m = &entry->mux;
entry->mux = *src;
#ifdef CONFIG_OMAP_MUX
if (omap_mux_copy_names(src, m)) {
kfree(entry);
return NULL;
}
#endif
mutex_lock(&muxmode_mutex);
list_add_tail(&entry->node, &partition->muxmodes);
mutex_unlock(&muxmode_mutex);
return m;
}
/*
* Note if CONFIG_OMAP_MUX is not selected, we will only initialize
* the GPIO to mux offset mapping that is needed for dynamic muxing
* of GPIO pins for off-idle.
*/
static void __init omap_mux_init_list(struct omap_mux_partition *partition,
struct omap_mux *superset)
{
while (superset->reg_offset != OMAP_MUX_TERMINATOR) {
struct omap_mux *entry;
#ifdef CONFIG_OMAP_MUX
if (!superset->muxnames[0]) {
superset++;
continue;
}
#else
/* Skip pins that are not muxed as GPIO by bootloader */
if (!OMAP_MODE_GPIO(partition, omap_mux_read(partition,
superset->reg_offset))) {
superset++;
continue;
}
#endif
entry = omap_mux_list_add(partition, superset);
if (!entry) {
pr_err("%s: Could not add entry\n", __func__);
return;
}
superset++;
}
}
#ifdef CONFIG_OMAP_MUX
static void omap_mux_init_package(struct omap_mux *superset,
struct omap_mux *package_subset,
struct omap_ball *package_balls)
{
if (package_subset)
omap_mux_package_fixup(package_subset, superset);
if (package_balls)
omap_mux_package_init_balls(package_balls, superset);
}
static void __init omap_mux_init_signals(struct omap_mux_partition *partition,
struct omap_board_mux *board_mux)
{
omap_mux_set_cmdline_signals();
omap_mux_write_array(partition, board_mux);
}
#else
static void omap_mux_init_package(struct omap_mux *superset,
struct omap_mux *package_subset,
struct omap_ball *package_balls)
{
}
static void __init omap_mux_init_signals(struct omap_mux_partition *partition,
struct omap_board_mux *board_mux)
{
}
#endif
static u32 mux_partitions_cnt;
int __init omap_mux_init(const char *name, u32 flags,
u32 mux_pbase, u32 mux_size,
struct omap_mux *superset,
struct omap_mux *package_subset,
struct omap_board_mux *board_mux,
struct omap_ball *package_balls)
{
struct omap_mux_partition *partition;
partition = kzalloc(sizeof(struct omap_mux_partition), GFP_KERNEL);
if (!partition)
return -ENOMEM;
partition->name = name;
partition->flags = flags;
partition->gpio = flags & OMAP_MUX_MODE7;
partition->size = mux_size;
partition->phys = mux_pbase;
partition->base = ioremap(mux_pbase, mux_size);
if (!partition->base) {
pr_err("%s: Could not ioremap mux partition at 0x%08x\n",
__func__, partition->phys);
kfree(partition);
return -ENODEV;
}
INIT_LIST_HEAD(&partition->muxmodes);
list_add_tail(&partition->node, &mux_partitions);
mux_partitions_cnt++;
pr_info("%s: Add partition: #%d: %s, flags: %x\n", __func__,
mux_partitions_cnt, partition->name, partition->flags);
omap_mux_init_package(superset, package_subset, package_balls);
omap_mux_init_list(partition, superset);
omap_mux_init_signals(partition, board_mux);
return 0;
}
| gpl-2.0 |
deadman96385/android_kernel_leeco_msm8996 | drivers/gpu/drm/msm/msm_rd.c | 1532 | 8194 | /*
* Copyright (C) 2013 Red Hat
* Author: Rob Clark <robdclark@gmail.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.
*
* 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/>.
*/
/* For debugging crashes, userspace can:
*
* tail -f /sys/kernel/debug/dri/<minor>/rd > logfile.rd
*
* To log the cmdstream in a format that is understood by freedreno/cffdump
* utility. By comparing the last successfully completed fence #, to the
* cmdstream for the next fence, you can narrow down which process and submit
* caused the gpu crash/lockup.
*
* This bypasses drm_debugfs_create_files() mainly because we need to use
* our own fops for a bit more control. In particular, we don't want to
* do anything if userspace doesn't have the debugfs file open.
*/
#ifdef CONFIG_DEBUG_FS
#include <linux/kfifo.h>
#include <linux/debugfs.h>
#include <linux/circ_buf.h>
#include <linux/wait.h>
#include "msm_drv.h"
#include "msm_gpu.h"
#include "msm_gem.h"
enum rd_sect_type {
RD_NONE,
RD_TEST, /* ascii text */
RD_CMD, /* ascii text */
RD_GPUADDR, /* u32 gpuaddr, u32 size */
RD_CONTEXT, /* raw dump */
RD_CMDSTREAM, /* raw dump */
RD_CMDSTREAM_ADDR, /* gpu addr of cmdstream */
RD_PARAM, /* u32 param_type, u32 param_val, u32 bitlen */
RD_FLUSH, /* empty, clear previous params */
RD_PROGRAM, /* shader program, raw dump */
RD_VERT_SHADER,
RD_FRAG_SHADER,
RD_BUFFER_CONTENTS,
RD_GPU_ID,
};
#define BUF_SZ 512 /* should be power of 2 */
/* space used: */
#define circ_count(circ) \
(CIRC_CNT((circ)->head, (circ)->tail, BUF_SZ))
#define circ_count_to_end(circ) \
(CIRC_CNT_TO_END((circ)->head, (circ)->tail, BUF_SZ))
/* space available: */
#define circ_space(circ) \
(CIRC_SPACE((circ)->head, (circ)->tail, BUF_SZ))
#define circ_space_to_end(circ) \
(CIRC_SPACE_TO_END((circ)->head, (circ)->tail, BUF_SZ))
struct msm_rd_state {
struct drm_device *dev;
bool open;
struct dentry *ent;
struct drm_info_node *node;
/* current submit to read out: */
struct msm_gem_submit *submit;
/* fifo access is synchronized on the producer side by
* struct_mutex held by submit code (otherwise we could
* end up w/ cmds logged in different order than they
* were executed). And read_lock synchronizes the reads
*/
struct mutex read_lock;
wait_queue_head_t fifo_event;
struct circ_buf fifo;
char buf[BUF_SZ];
};
static void rd_write(struct msm_rd_state *rd, const void *buf, int sz)
{
struct circ_buf *fifo = &rd->fifo;
const char *ptr = buf;
while (sz > 0) {
char *fptr = &fifo->buf[fifo->head];
int n;
wait_event(rd->fifo_event, circ_space(&rd->fifo) > 0);
n = min(sz, circ_space_to_end(&rd->fifo));
memcpy(fptr, ptr, n);
fifo->head = (fifo->head + n) & (BUF_SZ - 1);
sz -= n;
ptr += n;
wake_up_all(&rd->fifo_event);
}
}
static void rd_write_section(struct msm_rd_state *rd,
enum rd_sect_type type, const void *buf, int sz)
{
rd_write(rd, &type, 4);
rd_write(rd, &sz, 4);
rd_write(rd, buf, sz);
}
static ssize_t rd_read(struct file *file, char __user *buf,
size_t sz, loff_t *ppos)
{
struct msm_rd_state *rd = file->private_data;
struct circ_buf *fifo = &rd->fifo;
const char *fptr = &fifo->buf[fifo->tail];
int n = 0, ret = 0;
mutex_lock(&rd->read_lock);
ret = wait_event_interruptible(rd->fifo_event,
circ_count(&rd->fifo) > 0);
if (ret)
goto out;
n = min_t(int, sz, circ_count_to_end(&rd->fifo));
ret = copy_to_user(buf, fptr, n);
if (ret)
goto out;
fifo->tail = (fifo->tail + n) & (BUF_SZ - 1);
*ppos += n;
wake_up_all(&rd->fifo_event);
out:
mutex_unlock(&rd->read_lock);
if (ret)
return ret;
return n;
}
static int rd_open(struct inode *inode, struct file *file)
{
struct msm_rd_state *rd = inode->i_private;
struct drm_device *dev = rd->dev;
struct msm_drm_private *priv = dev->dev_private;
struct msm_gpu *gpu = priv->gpu;
uint64_t val;
uint32_t gpu_id;
int ret = 0;
mutex_lock(&dev->struct_mutex);
if (rd->open || !gpu) {
ret = -EBUSY;
goto out;
}
file->private_data = rd;
rd->open = true;
/* the parsing tools need to know gpu-id to know which
* register database to load.
*/
gpu->funcs->get_param(gpu, MSM_PARAM_GPU_ID, &val);
gpu_id = val;
rd_write_section(rd, RD_GPU_ID, &gpu_id, sizeof(gpu_id));
out:
mutex_unlock(&dev->struct_mutex);
return ret;
}
static int rd_release(struct inode *inode, struct file *file)
{
struct msm_rd_state *rd = inode->i_private;
rd->open = false;
return 0;
}
static const struct file_operations rd_debugfs_fops = {
.owner = THIS_MODULE,
.open = rd_open,
.read = rd_read,
.llseek = no_llseek,
.release = rd_release,
};
int msm_rd_debugfs_init(struct drm_minor *minor)
{
struct msm_drm_private *priv = minor->dev->dev_private;
struct msm_rd_state *rd;
/* only create on first minor: */
if (priv->rd)
return 0;
rd = kzalloc(sizeof(*rd), GFP_KERNEL);
if (!rd)
return -ENOMEM;
rd->dev = minor->dev;
rd->fifo.buf = rd->buf;
mutex_init(&rd->read_lock);
priv->rd = rd;
init_waitqueue_head(&rd->fifo_event);
rd->node = kzalloc(sizeof(*rd->node), GFP_KERNEL);
if (!rd->node)
goto fail;
rd->ent = debugfs_create_file("rd", S_IFREG | S_IRUGO,
minor->debugfs_root, rd, &rd_debugfs_fops);
if (!rd->ent) {
DRM_ERROR("Cannot create /sys/kernel/debug/dri/%s/rd\n",
minor->debugfs_root->d_name.name);
goto fail;
}
rd->node->minor = minor;
rd->node->dent = rd->ent;
rd->node->info_ent = NULL;
mutex_lock(&minor->debugfs_lock);
list_add(&rd->node->list, &minor->debugfs_list);
mutex_unlock(&minor->debugfs_lock);
return 0;
fail:
msm_rd_debugfs_cleanup(minor);
return -1;
}
void msm_rd_debugfs_cleanup(struct drm_minor *minor)
{
struct msm_drm_private *priv = minor->dev->dev_private;
struct msm_rd_state *rd = priv->rd;
if (!rd)
return;
priv->rd = NULL;
debugfs_remove(rd->ent);
if (rd->node) {
mutex_lock(&minor->debugfs_lock);
list_del(&rd->node->list);
mutex_unlock(&minor->debugfs_lock);
kfree(rd->node);
}
mutex_destroy(&rd->read_lock);
kfree(rd);
}
/* called under struct_mutex */
void msm_rd_dump_submit(struct msm_gem_submit *submit)
{
struct drm_device *dev = submit->dev;
struct msm_drm_private *priv = dev->dev_private;
struct msm_rd_state *rd = priv->rd;
char msg[128];
int i, n;
if (!rd->open)
return;
/* writing into fifo is serialized by caller, and
* rd->read_lock is used to serialize the reads
*/
WARN_ON(!mutex_is_locked(&dev->struct_mutex));
n = snprintf(msg, sizeof(msg), "%.*s/%d: fence=%u",
TASK_COMM_LEN, current->comm, task_pid_nr(current),
submit->fence);
rd_write_section(rd, RD_CMD, msg, ALIGN(n, 4));
/* could be nice to have an option (module-param?) to snapshot
* all the bo's associated with the submit. Handy to see vtx
* buffers, etc. For now just the cmdstream bo's is enough.
*/
for (i = 0; i < submit->nr_cmds; i++) {
uint32_t idx = submit->cmd[i].idx;
uint32_t iova = submit->cmd[i].iova;
uint32_t szd = submit->cmd[i].size; /* in dwords */
struct msm_gem_object *obj = submit->bos[idx].obj;
const char *buf = msm_gem_vaddr_locked(&obj->base);
buf += iova - submit->bos[idx].iova;
rd_write_section(rd, RD_GPUADDR,
(uint32_t[2]){ iova, szd * 4 }, 8);
rd_write_section(rd, RD_BUFFER_CONTENTS,
buf, szd * 4);
switch (submit->cmd[i].type) {
case MSM_SUBMIT_CMD_IB_TARGET_BUF:
/* ignore IB-targets, we've logged the buffer, the
* parser tool will follow the IB based on the logged
* buffer/gpuaddr, so nothing more to do.
*/
break;
case MSM_SUBMIT_CMD_CTX_RESTORE_BUF:
case MSM_SUBMIT_CMD_BUF:
rd_write_section(rd, RD_CMDSTREAM_ADDR,
(uint32_t[2]){ iova, szd }, 8);
break;
}
}
}
#endif
| gpl-2.0 |
emceethemouth/kernel_androidone | arch/arm/mach-shmobile/board-ap4evb.c | 2044 | 31063 | /*
* AP4EVB board support
*
* Copyright (C) 2010 Magnus Damm
* Copyright (C) 2008 Yoshihiro Shimoda
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/clk.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/mfd/tmio.h>
#include <linux/mmc/host.h>
#include <linux/mmc/sh_mobile_sdhi.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/mmc/sh_mmcif.h>
#include <linux/i2c.h>
#include <linux/i2c/tsc2007.h>
#include <linux/io.h>
#include <linux/pinctrl/machine.h>
#include <linux/regulator/fixed.h>
#include <linux/regulator/machine.h>
#include <linux/smsc911x.h>
#include <linux/sh_intc.h>
#include <linux/sh_clk.h>
#include <linux/gpio.h>
#include <linux/input.h>
#include <linux/leds.h>
#include <linux/input/sh_keysc.h>
#include <linux/usb/r8a66597.h>
#include <linux/pm_clock.h>
#include <linux/dma-mapping.h>
#include <media/sh_mobile_ceu.h>
#include <media/sh_mobile_csi2.h>
#include <media/soc_camera.h>
#include <sound/sh_fsi.h>
#include <sound/simple_card.h>
#include <video/sh_mobile_hdmi.h>
#include <video/sh_mobile_lcdc.h>
#include <video/sh_mipi_dsi.h>
#include <mach/common.h>
#include <mach/irqs.h>
#include <mach/sh7372.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/setup.h>
#include "sh-gpio.h"
/*
* Address Interface BusWidth note
* ------------------------------------------------------------------
* 0x0000_0000 NOR Flash ROM (MCP) 16bit SW7 : bit1 = ON
* 0x0800_0000 user area -
* 0x1000_0000 NOR Flash ROM (MCP) 16bit SW7 : bit1 = OFF
* 0x1400_0000 Ether (LAN9220) 16bit
* 0x1600_0000 user area - cannot use with NAND
* 0x1800_0000 user area -
* 0x1A00_0000 -
* 0x4000_0000 LPDDR2-SDRAM (POP) 32bit
*/
/*
* NOR Flash ROM
*
* SW1 | SW2 | SW7 | NOR Flash ROM
* bit1 | bit1 bit2 | bit1 | Memory allocation
* ------+------------+------+------------------
* OFF | ON OFF | ON | Area 0
* OFF | ON OFF | OFF | Area 4
*/
/*
* NAND Flash ROM
*
* SW1 | SW2 | SW7 | NAND Flash ROM
* bit1 | bit1 bit2 | bit2 | Memory allocation
* ------+------------+------+------------------
* OFF | ON OFF | ON | FCE 0
* OFF | ON OFF | OFF | FCE 1
*/
/*
* SMSC 9220
*
* SW1 SMSC 9220
* -----------------------
* ON access disable
* OFF access enable
*/
/*
* LCD / IRQ / KEYSC / IrDA
*
* IRQ = IRQ26 (TS), IRQ27 (VIO), IRQ28 (QHD-TouchScreen)
* LCD = 2nd LCDC (WVGA)
*
* | SW43 |
* SW3 | ON | OFF |
* -------------+-----------------------+---------------+
* ON | KEY / IrDA | LCD |
* OFF | KEY / IrDA / IRQ | IRQ |
*
*
* QHD / WVGA display
*
* You can choice display type on menuconfig.
* Then, check above dip-switch.
*/
/*
* USB
*
* J7 : 1-2 MAX3355E VBUS
* 2-3 DC 5.0V
*
* S39: bit2: off
*/
/*
* FSI/FSMI
*
* SW41 : ON : SH-Mobile AP4 Audio Mode
* : OFF : Bluetooth Audio Mode
*
* it needs amixer settings for playing
*
* amixer set "Headphone Enable" on
*/
/*
* MMC0/SDHI1 (CN7)
*
* J22 : select card voltage
* 1-2 pin : 1.8v
* 2-3 pin : 3.3v
*
* SW1 | SW33
* | bit1 | bit2 | bit3 | bit4
* ------------+------+------+------+-------
* MMC0 OFF | OFF | ON | ON | X
* SDHI1 OFF | ON | X | OFF | ON
*
* voltage lebel
* CN7 : 1.8v
* CN12: 3.3v
*/
/* Dummy supplies, where voltage doesn't matter */
static struct regulator_consumer_supply fixed1v8_power_consumers[] =
{
/* J22 default position: 1.8V */
REGULATOR_SUPPLY("vmmc", "sh_mobile_sdhi.1"),
REGULATOR_SUPPLY("vqmmc", "sh_mobile_sdhi.1"),
REGULATOR_SUPPLY("vmmc", "sh_mmcif.0"),
REGULATOR_SUPPLY("vqmmc", "sh_mmcif.0"),
};
static struct regulator_consumer_supply fixed3v3_power_consumers[] =
{
REGULATOR_SUPPLY("vmmc", "sh_mobile_sdhi.0"),
REGULATOR_SUPPLY("vqmmc", "sh_mobile_sdhi.0"),
};
static struct regulator_consumer_supply dummy_supplies[] = {
REGULATOR_SUPPLY("vddvario", "smsc911x"),
REGULATOR_SUPPLY("vdd33a", "smsc911x"),
};
/* MTD */
static struct mtd_partition nor_flash_partitions[] = {
{
.name = "loader",
.offset = 0x00000000,
.size = 512 * 1024,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "bootenv",
.offset = MTDPART_OFS_APPEND,
.size = 512 * 1024,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "kernel_ro",
.offset = MTDPART_OFS_APPEND,
.size = 8 * 1024 * 1024,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = 8 * 1024 * 1024,
},
{
.name = "data",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct physmap_flash_data nor_flash_data = {
.width = 2,
.parts = nor_flash_partitions,
.nr_parts = ARRAY_SIZE(nor_flash_partitions),
};
static struct resource nor_flash_resources[] = {
[0] = {
.start = 0x20000000, /* CS0 shadow instead of regular CS0 */
.end = 0x28000000 - 1, /* needed by USB MASK ROM boot */
.flags = IORESOURCE_MEM,
}
};
static struct platform_device nor_flash_device = {
.name = "physmap-flash",
.dev = {
.platform_data = &nor_flash_data,
},
.num_resources = ARRAY_SIZE(nor_flash_resources),
.resource = nor_flash_resources,
};
/* SMSC 9220 */
static struct resource smc911x_resources[] = {
{
.start = 0x14000000,
.end = 0x16000000 - 1,
.flags = IORESOURCE_MEM,
}, {
.start = evt2irq(0x02c0) /* IRQ6A */,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWLEVEL,
},
};
static struct smsc911x_platform_config smsc911x_info = {
.flags = SMSC911X_USE_16BIT | SMSC911X_SAVE_MAC_ADDRESS,
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_PUSH_PULL,
};
static struct platform_device smc911x_device = {
.name = "smsc911x",
.id = -1,
.num_resources = ARRAY_SIZE(smc911x_resources),
.resource = smc911x_resources,
.dev = {
.platform_data = &smsc911x_info,
},
};
/*
* The card detect pin of the top SD/MMC slot (CN7) is active low and is
* connected to GPIO A22 of SH7372 (GPIO 41).
*/
static int slot_cn7_get_cd(struct platform_device *pdev)
{
return !gpio_get_value(41);
}
/* MERAM */
static struct sh_mobile_meram_info meram_info = {
.addr_mode = SH_MOBILE_MERAM_MODE1,
};
static struct resource meram_resources[] = {
[0] = {
.name = "regs",
.start = 0xe8000000,
.end = 0xe807ffff,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "meram",
.start = 0xe8080000,
.end = 0xe81fffff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device meram_device = {
.name = "sh_mobile_meram",
.id = 0,
.num_resources = ARRAY_SIZE(meram_resources),
.resource = meram_resources,
.dev = {
.platform_data = &meram_info,
},
};
/* SH_MMCIF */
static struct resource sh_mmcif_resources[] = {
[0] = {
.name = "MMCIF",
.start = 0xE6BD0000,
.end = 0xE6BD00FF,
.flags = IORESOURCE_MEM,
},
[1] = {
/* MMC ERR */
.start = evt2irq(0x1ac0),
.flags = IORESOURCE_IRQ,
},
[2] = {
/* MMC NOR */
.start = evt2irq(0x1ae0),
.flags = IORESOURCE_IRQ,
},
};
static struct sh_mmcif_plat_data sh_mmcif_plat = {
.sup_pclk = 0,
.ocr = MMC_VDD_165_195 | MMC_VDD_32_33 | MMC_VDD_33_34,
.caps = MMC_CAP_4_BIT_DATA |
MMC_CAP_8_BIT_DATA |
MMC_CAP_NEEDS_POLL,
.get_cd = slot_cn7_get_cd,
.slave_id_tx = SHDMA_SLAVE_MMCIF_TX,
.slave_id_rx = SHDMA_SLAVE_MMCIF_RX,
};
static struct platform_device sh_mmcif_device = {
.name = "sh_mmcif",
.id = 0,
.dev = {
.dma_mask = NULL,
.coherent_dma_mask = 0xffffffff,
.platform_data = &sh_mmcif_plat,
},
.num_resources = ARRAY_SIZE(sh_mmcif_resources),
.resource = sh_mmcif_resources,
};
/* SDHI0 */
static struct sh_mobile_sdhi_info sdhi0_info = {
.dma_slave_tx = SHDMA_SLAVE_SDHI0_TX,
.dma_slave_rx = SHDMA_SLAVE_SDHI0_RX,
.tmio_caps = MMC_CAP_SDIO_IRQ,
};
static struct resource sdhi0_resources[] = {
[0] = {
.name = "SDHI0",
.start = 0xe6850000,
.end = 0xe68500ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x0e00) /* SDHI0_SDHI0I0 */,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = evt2irq(0x0e20) /* SDHI0_SDHI0I1 */,
.flags = IORESOURCE_IRQ,
},
[3] = {
.start = evt2irq(0x0e40) /* SDHI0_SDHI0I2 */,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device sdhi0_device = {
.name = "sh_mobile_sdhi",
.num_resources = ARRAY_SIZE(sdhi0_resources),
.resource = sdhi0_resources,
.id = 0,
.dev = {
.platform_data = &sdhi0_info,
},
};
/* SDHI1 */
static struct sh_mobile_sdhi_info sdhi1_info = {
.dma_slave_tx = SHDMA_SLAVE_SDHI1_TX,
.dma_slave_rx = SHDMA_SLAVE_SDHI1_RX,
.tmio_ocr_mask = MMC_VDD_165_195,
.tmio_flags = TMIO_MMC_WRPROTECT_DISABLE,
.tmio_caps = MMC_CAP_NEEDS_POLL | MMC_CAP_SDIO_IRQ,
.get_cd = slot_cn7_get_cd,
};
static struct resource sdhi1_resources[] = {
[0] = {
.name = "SDHI1",
.start = 0xe6860000,
.end = 0xe68600ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x0e80), /* SDHI1_SDHI1I0 */
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = evt2irq(0x0ea0), /* SDHI1_SDHI1I1 */
.flags = IORESOURCE_IRQ,
},
[3] = {
.start = evt2irq(0x0ec0), /* SDHI1_SDHI1I2 */
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device sdhi1_device = {
.name = "sh_mobile_sdhi",
.num_resources = ARRAY_SIZE(sdhi1_resources),
.resource = sdhi1_resources,
.id = 1,
.dev = {
.platform_data = &sdhi1_info,
},
};
/* USB1 */
static void usb1_host_port_power(int port, int power)
{
if (!power) /* only power-on supported for now */
return;
/* set VBOUT/PWEN and EXTLP1 in DVSTCTR */
__raw_writew(__raw_readw(IOMEM(0xE68B0008)) | 0x600, IOMEM(0xE68B0008));
}
static struct r8a66597_platdata usb1_host_data = {
.on_chip = 1,
.port_power = usb1_host_port_power,
};
static struct resource usb1_host_resources[] = {
[0] = {
.name = "USBHS",
.start = 0xE68B0000,
.end = 0xE68B00E6 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x1ce0) /* USB1_USB1I0 */,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device usb1_host_device = {
.name = "r8a66597_hcd",
.id = 1,
.dev = {
.dma_mask = NULL, /* not use dma */
.coherent_dma_mask = 0xffffffff,
.platform_data = &usb1_host_data,
},
.num_resources = ARRAY_SIZE(usb1_host_resources),
.resource = usb1_host_resources,
};
/*
* QHD display
*/
#ifdef CONFIG_AP4EVB_QHD
/* KEYSC (Needs SW43 set to ON) */
static struct sh_keysc_info keysc_info = {
.mode = SH_KEYSC_MODE_1,
.scan_timing = 3,
.delay = 2500,
.keycodes = {
KEY_0, KEY_1, KEY_2, KEY_3, KEY_4,
KEY_5, KEY_6, KEY_7, KEY_8, KEY_9,
KEY_A, KEY_B, KEY_C, KEY_D, KEY_E,
KEY_F, KEY_G, KEY_H, KEY_I, KEY_J,
KEY_K, KEY_L, KEY_M, KEY_N, KEY_O,
},
};
static struct resource keysc_resources[] = {
[0] = {
.name = "KEYSC",
.start = 0xe61b0000,
.end = 0xe61b0063,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x0be0), /* KEYSC_KEY */
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device keysc_device = {
.name = "sh_keysc",
.id = 0, /* "keysc0" clock */
.num_resources = ARRAY_SIZE(keysc_resources),
.resource = keysc_resources,
.dev = {
.platform_data = &keysc_info,
},
};
/* MIPI-DSI */
static int sh_mipi_set_dot_clock(struct platform_device *pdev,
void __iomem *base,
int enable)
{
struct clk *pck = clk_get(&pdev->dev, "dsip_clk");
if (IS_ERR(pck))
return PTR_ERR(pck);
if (enable) {
/*
* DSIPCLK = 24MHz
* D-PHY = DSIPCLK * ((0x6*2)+1) = 312MHz (see .phyctrl)
* HsByteCLK = D-PHY/8 = 39MHz
*
* X * Y * FPS =
* (544+72+600+16) * (961+8+8+2) * 30 = 36.1MHz
*/
clk_set_rate(pck, clk_round_rate(pck, 24000000));
clk_enable(pck);
} else {
clk_disable(pck);
}
clk_put(pck);
return 0;
}
static struct resource mipidsi0_resources[] = {
[0] = {
.start = 0xffc60000,
.end = 0xffc63073,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 0xffc68000,
.end = 0xffc680ef,
.flags = IORESOURCE_MEM,
},
};
static struct sh_mipi_dsi_info mipidsi0_info = {
.data_format = MIPI_RGB888,
.channel = LCDC_CHAN_MAINLCD,
.lane = 2,
.vsynw_offset = 17,
.phyctrl = 0x6 << 8,
.flags = SH_MIPI_DSI_SYNC_PULSES_MODE |
SH_MIPI_DSI_HSbyteCLK,
.set_dot_clock = sh_mipi_set_dot_clock,
};
static struct platform_device mipidsi0_device = {
.name = "sh-mipi-dsi",
.num_resources = ARRAY_SIZE(mipidsi0_resources),
.resource = mipidsi0_resources,
.id = 0,
.dev = {
.platform_data = &mipidsi0_info,
},
};
static struct platform_device *qhd_devices[] __initdata = {
&mipidsi0_device,
&keysc_device,
};
#endif /* CONFIG_AP4EVB_QHD */
/* LCDC0 */
static const struct fb_videomode ap4evb_lcdc_modes[] = {
{
#ifdef CONFIG_AP4EVB_QHD
.name = "R63302(QHD)",
.xres = 544,
.yres = 961,
.left_margin = 72,
.right_margin = 600,
.hsync_len = 16,
.upper_margin = 8,
.lower_margin = 8,
.vsync_len = 2,
.sync = FB_SYNC_VERT_HIGH_ACT | FB_SYNC_HOR_HIGH_ACT,
#else
.name = "WVGA Panel",
.xres = 800,
.yres = 480,
.left_margin = 220,
.right_margin = 110,
.hsync_len = 70,
.upper_margin = 20,
.lower_margin = 5,
.vsync_len = 5,
.sync = 0,
#endif
},
};
static const struct sh_mobile_meram_cfg lcd_meram_cfg = {
.icb[0] = {
.meram_size = 0x40,
},
.icb[1] = {
.meram_size = 0x40,
},
};
static struct sh_mobile_lcdc_info lcdc_info = {
.meram_dev = &meram_info,
.ch[0] = {
.chan = LCDC_CHAN_MAINLCD,
.fourcc = V4L2_PIX_FMT_RGB565,
.lcd_modes = ap4evb_lcdc_modes,
.num_modes = ARRAY_SIZE(ap4evb_lcdc_modes),
.meram_cfg = &lcd_meram_cfg,
#ifdef CONFIG_AP4EVB_QHD
.tx_dev = &mipidsi0_device,
#endif
}
};
static struct resource lcdc_resources[] = {
[0] = {
.name = "LCDC",
.start = 0xfe940000, /* P4-only space */
.end = 0xfe943fff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = intcs_evt2irq(0x580),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device lcdc_device = {
.name = "sh_mobile_lcdc_fb",
.num_resources = ARRAY_SIZE(lcdc_resources),
.resource = lcdc_resources,
.dev = {
.platform_data = &lcdc_info,
.coherent_dma_mask = ~0,
},
};
/* FSI */
#define IRQ_FSI evt2irq(0x1840)
static struct sh_fsi_platform_info fsi_info = {
.port_b = {
.flags = SH_FSI_CLK_CPG |
SH_FSI_FMT_SPDIF,
},
};
static struct resource fsi_resources[] = {
[0] = {
.name = "FSI",
.start = 0xFE3C0000,
.end = 0xFE3C0400 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_FSI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device fsi_device = {
.name = "sh_fsi2",
.id = -1,
.num_resources = ARRAY_SIZE(fsi_resources),
.resource = fsi_resources,
.dev = {
.platform_data = &fsi_info,
},
};
static struct asoc_simple_card_info fsi2_ak4643_info = {
.name = "AK4643",
.card = "FSI2A-AK4643",
.codec = "ak4642-codec.0-0013",
.platform = "sh_fsi2",
.daifmt = SND_SOC_DAIFMT_LEFT_J,
.cpu_dai = {
.name = "fsia-dai",
.fmt = SND_SOC_DAIFMT_CBS_CFS,
},
.codec_dai = {
.name = "ak4642-hifi",
.fmt = SND_SOC_DAIFMT_CBM_CFM,
.sysclk = 11289600,
},
};
static struct platform_device fsi_ak4643_device = {
.name = "asoc-simple-card",
.dev = {
.platform_data = &fsi2_ak4643_info,
},
};
/* LCDC1 */
static long ap4evb_clk_optimize(unsigned long target, unsigned long *best_freq,
unsigned long *parent_freq);
static struct sh_mobile_hdmi_info hdmi_info = {
.flags = HDMI_SND_SRC_SPDIF,
.clk_optimize_parent = ap4evb_clk_optimize,
};
static struct resource hdmi_resources[] = {
[0] = {
.name = "HDMI",
.start = 0xe6be0000,
.end = 0xe6be00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
/* There's also an HDMI interrupt on INTCS @ 0x18e0 */
.start = evt2irq(0x17e0),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device hdmi_device = {
.name = "sh-mobile-hdmi",
.num_resources = ARRAY_SIZE(hdmi_resources),
.resource = hdmi_resources,
.id = -1,
.dev = {
.platform_data = &hdmi_info,
},
};
static long ap4evb_clk_optimize(unsigned long target, unsigned long *best_freq,
unsigned long *parent_freq)
{
struct clk *hdmi_ick = clk_get(&hdmi_device.dev, "ick");
long error;
if (IS_ERR(hdmi_ick)) {
int ret = PTR_ERR(hdmi_ick);
pr_err("Cannot get HDMI ICK: %d\n", ret);
return ret;
}
error = clk_round_parent(hdmi_ick, target, best_freq, parent_freq, 1, 64);
clk_put(hdmi_ick);
return error;
}
static const struct sh_mobile_meram_cfg hdmi_meram_cfg = {
.icb[0] = {
.meram_size = 0x100,
},
.icb[1] = {
.meram_size = 0x100,
},
};
static struct sh_mobile_lcdc_info sh_mobile_lcdc1_info = {
.clock_source = LCDC_CLK_EXTERNAL,
.meram_dev = &meram_info,
.ch[0] = {
.chan = LCDC_CHAN_MAINLCD,
.fourcc = V4L2_PIX_FMT_RGB565,
.interface_type = RGB24,
.clock_divider = 1,
.flags = LCDC_FLAGS_DWPOL,
.meram_cfg = &hdmi_meram_cfg,
.tx_dev = &hdmi_device,
}
};
static struct resource lcdc1_resources[] = {
[0] = {
.name = "LCDC1",
.start = 0xfe944000,
.end = 0xfe947fff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = intcs_evt2irq(0x1780),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device lcdc1_device = {
.name = "sh_mobile_lcdc_fb",
.num_resources = ARRAY_SIZE(lcdc1_resources),
.resource = lcdc1_resources,
.id = 1,
.dev = {
.platform_data = &sh_mobile_lcdc1_info,
.coherent_dma_mask = ~0,
},
};
static struct asoc_simple_card_info fsi2_hdmi_info = {
.name = "HDMI",
.card = "FSI2B-HDMI",
.codec = "sh-mobile-hdmi",
.platform = "sh_fsi2",
.cpu_dai = {
.name = "fsib-dai",
.fmt = SND_SOC_DAIFMT_CBM_CFM | SND_SOC_DAIFMT_IB_NF,
},
.codec_dai = {
.name = "sh_mobile_hdmi-hifi",
},
};
static struct platform_device fsi_hdmi_device = {
.name = "asoc-simple-card",
.id = 1,
.dev = {
.platform_data = &fsi2_hdmi_info,
},
};
static struct gpio_led ap4evb_leds[] = {
{
.name = "led4",
.gpio = 185,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "led2",
.gpio = 186,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "led3",
.gpio = 187,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "led1",
.gpio = 188,
.default_state = LEDS_GPIO_DEFSTATE_ON,
}
};
static struct gpio_led_platform_data ap4evb_leds_pdata = {
.num_leds = ARRAY_SIZE(ap4evb_leds),
.leds = ap4evb_leds,
};
static struct platform_device leds_device = {
.name = "leds-gpio",
.id = 0,
.dev = {
.platform_data = &ap4evb_leds_pdata,
},
};
static struct i2c_board_info imx074_info = {
I2C_BOARD_INFO("imx074", 0x1a),
};
static struct soc_camera_link imx074_link = {
.bus_id = 0,
.board_info = &imx074_info,
.i2c_adapter_id = 0,
.module_name = "imx074",
};
static struct platform_device ap4evb_camera = {
.name = "soc-camera-pdrv",
.id = 0,
.dev = {
.platform_data = &imx074_link,
},
};
static struct sh_csi2_client_config csi2_clients[] = {
{
.phy = SH_CSI2_PHY_MAIN,
.lanes = 0, /* default: 2 lanes */
.channel = 0,
.pdev = &ap4evb_camera,
},
};
static struct sh_csi2_pdata csi2_info = {
.type = SH_CSI2C,
.clients = csi2_clients,
.num_clients = ARRAY_SIZE(csi2_clients),
.flags = SH_CSI2_ECC | SH_CSI2_CRC,
};
static struct resource csi2_resources[] = {
[0] = {
.name = "CSI2",
.start = 0xffc90000,
.end = 0xffc90fff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = intcs_evt2irq(0x17a0),
.flags = IORESOURCE_IRQ,
},
};
static struct sh_mobile_ceu_companion csi2 = {
.id = 0,
.num_resources = ARRAY_SIZE(csi2_resources),
.resource = csi2_resources,
.platform_data = &csi2_info,
};
static struct sh_mobile_ceu_info sh_mobile_ceu_info = {
.flags = SH_CEU_FLAG_USE_8BIT_BUS,
.max_width = 8188,
.max_height = 8188,
.csi2 = &csi2,
};
static struct resource ceu_resources[] = {
[0] = {
.name = "CEU",
.start = 0xfe910000,
.end = 0xfe91009f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = intcs_evt2irq(0x880),
.flags = IORESOURCE_IRQ,
},
[2] = {
/* place holder for contiguous memory */
},
};
static struct platform_device ceu_device = {
.name = "sh_mobile_ceu",
.id = 0, /* "ceu0" clock */
.num_resources = ARRAY_SIZE(ceu_resources),
.resource = ceu_resources,
.dev = {
.platform_data = &sh_mobile_ceu_info,
.coherent_dma_mask = 0xffffffff,
},
};
static struct platform_device *ap4evb_devices[] __initdata = {
&leds_device,
&nor_flash_device,
&smc911x_device,
&sdhi0_device,
&sdhi1_device,
&usb1_host_device,
&fsi_device,
&fsi_ak4643_device,
&fsi_hdmi_device,
&sh_mmcif_device,
&hdmi_device,
&lcdc_device,
&lcdc1_device,
&ceu_device,
&ap4evb_camera,
&meram_device,
};
static void __init hdmi_init_pm_clock(void)
{
struct clk *hdmi_ick = clk_get(&hdmi_device.dev, "ick");
int ret;
long rate;
if (IS_ERR(hdmi_ick)) {
ret = PTR_ERR(hdmi_ick);
pr_err("Cannot get HDMI ICK: %d\n", ret);
goto out;
}
ret = clk_set_parent(&sh7372_pllc2_clk, &sh7372_dv_clki_div2_clk);
if (ret < 0) {
pr_err("Cannot set PLLC2 parent: %d, %d users\n", ret, sh7372_pllc2_clk.usecount);
goto out;
}
pr_debug("PLLC2 initial frequency %lu\n", clk_get_rate(&sh7372_pllc2_clk));
rate = clk_round_rate(&sh7372_pllc2_clk, 594000000);
if (rate < 0) {
pr_err("Cannot get suitable rate: %ld\n", rate);
ret = rate;
goto out;
}
ret = clk_set_rate(&sh7372_pllc2_clk, rate);
if (ret < 0) {
pr_err("Cannot set rate %ld: %d\n", rate, ret);
goto out;
}
pr_debug("PLLC2 set frequency %lu\n", rate);
ret = clk_set_parent(hdmi_ick, &sh7372_pllc2_clk);
if (ret < 0)
pr_err("Cannot set HDMI parent: %d\n", ret);
out:
if (!IS_ERR(hdmi_ick))
clk_put(hdmi_ick);
}
/* TouchScreen */
#ifdef CONFIG_AP4EVB_QHD
# define GPIO_TSC_IRQ GPIO_FN_IRQ28_123
# define GPIO_TSC_PORT 123
#else /* WVGA */
# define GPIO_TSC_IRQ GPIO_FN_IRQ7_40
# define GPIO_TSC_PORT 40
#endif
#define IRQ28 evt2irq(0x3380) /* IRQ28A */
#define IRQ7 evt2irq(0x02e0) /* IRQ7A */
static int ts_get_pendown_state(void)
{
int val;
gpio_free(GPIO_TSC_IRQ);
gpio_request_one(GPIO_TSC_PORT, GPIOF_IN, NULL);
val = gpio_get_value(GPIO_TSC_PORT);
gpio_request(GPIO_TSC_IRQ, NULL);
return !val;
}
static int ts_init(void)
{
gpio_request(GPIO_TSC_IRQ, NULL);
return 0;
}
static struct tsc2007_platform_data tsc2007_info = {
.model = 2007,
.x_plate_ohms = 180,
.get_pendown_state = ts_get_pendown_state,
.init_platform_hw = ts_init,
};
static struct i2c_board_info tsc_device = {
I2C_BOARD_INFO("tsc2007", 0x48),
.type = "tsc2007",
.platform_data = &tsc2007_info,
/*.irq is selected on ap4evb_init */
};
/* I2C */
static struct i2c_board_info i2c0_devices[] = {
{
I2C_BOARD_INFO("ak4643", 0x13),
},
};
static struct i2c_board_info i2c1_devices[] = {
{
I2C_BOARD_INFO("r2025sd", 0x32),
},
};
static const struct pinctrl_map ap4evb_pinctrl_map[] = {
/* MMCIF */
PIN_MAP_MUX_GROUP_DEFAULT("sh_mmcif.0", "pfc-sh7372",
"mmc0_data8_0", "mmc0"),
PIN_MAP_MUX_GROUP_DEFAULT("sh_mmcif.0", "pfc-sh7372",
"mmc0_ctrl_0", "mmc0"),
/* SDHI0 */
PIN_MAP_MUX_GROUP_DEFAULT("sh_mobile_sdhi.0", "pfc-sh7372",
"sdhi0_data4", "sdhi0"),
PIN_MAP_MUX_GROUP_DEFAULT("sh_mobile_sdhi.0", "pfc-sh7372",
"sdhi0_ctrl", "sdhi0"),
PIN_MAP_MUX_GROUP_DEFAULT("sh_mobile_sdhi.0", "pfc-sh7372",
"sdhi0_cd", "sdhi0"),
PIN_MAP_MUX_GROUP_DEFAULT("sh_mobile_sdhi.0", "pfc-sh7372",
"sdhi0_wp", "sdhi0"),
/* SDHI1 */
PIN_MAP_MUX_GROUP_DEFAULT("sh_mobile_sdhi.1", "pfc-sh7372",
"sdhi1_data4", "sdhi1"),
PIN_MAP_MUX_GROUP_DEFAULT("sh_mobile_sdhi.1", "pfc-sh7372",
"sdhi1_ctrl", "sdhi1"),
};
#define GPIO_PORT9CR IOMEM(0xE6051009)
#define GPIO_PORT10CR IOMEM(0xE605100A)
#define USCCR1 IOMEM(0xE6058144)
static void __init ap4evb_init(void)
{
struct pm_domain_device domain_devices[] = {
{ "A4LC", &lcdc1_device, },
{ "A4LC", &lcdc_device, },
{ "A4MP", &fsi_device, },
{ "A3SP", &sh_mmcif_device, },
{ "A3SP", &sdhi0_device, },
{ "A3SP", &sdhi1_device, },
{ "A4R", &ceu_device, },
};
u32 srcr4;
struct clk *clk;
regulator_register_always_on(0, "fixed-1.8V", fixed1v8_power_consumers,
ARRAY_SIZE(fixed1v8_power_consumers), 1800000);
regulator_register_always_on(1, "fixed-3.3V", fixed3v3_power_consumers,
ARRAY_SIZE(fixed3v3_power_consumers), 3300000);
regulator_register_fixed(2, dummy_supplies, ARRAY_SIZE(dummy_supplies));
/* External clock source */
clk_set_rate(&sh7372_dv_clki_clk, 27000000);
pinctrl_register_mappings(ap4evb_pinctrl_map,
ARRAY_SIZE(ap4evb_pinctrl_map));
sh7372_pinmux_init();
/* enable SCIFA0 */
gpio_request(GPIO_FN_SCIFA0_TXD, NULL);
gpio_request(GPIO_FN_SCIFA0_RXD, NULL);
/* enable SMSC911X */
gpio_request(GPIO_FN_CS5A, NULL);
gpio_request(GPIO_FN_IRQ6_39, NULL);
/* enable Debug switch (S6) */
gpio_request_one(32, GPIOF_IN | GPIOF_EXPORT, NULL);
gpio_request_one(33, GPIOF_IN | GPIOF_EXPORT, NULL);
gpio_request_one(34, GPIOF_IN | GPIOF_EXPORT, NULL);
gpio_request_one(35, GPIOF_IN | GPIOF_EXPORT, NULL);
/* USB enable */
gpio_request(GPIO_FN_VBUS0_1, NULL);
gpio_request(GPIO_FN_IDIN_1_18, NULL);
gpio_request(GPIO_FN_PWEN_1_115, NULL);
gpio_request(GPIO_FN_OVCN_1_114, NULL);
gpio_request(GPIO_FN_EXTLP_1, NULL);
gpio_request(GPIO_FN_OVCN2_1, NULL);
/* setup USB phy */
__raw_writew(0x8a0a, IOMEM(0xE6058130)); /* USBCR4 */
/* enable FSI2 port A (ak4643) */
gpio_request(GPIO_FN_FSIAIBT, NULL);
gpio_request(GPIO_FN_FSIAILR, NULL);
gpio_request(GPIO_FN_FSIAISLD, NULL);
gpio_request(GPIO_FN_FSIAOSLD, NULL);
gpio_request_one(161, GPIOF_OUT_INIT_LOW, NULL); /* slave */
gpio_request(9, NULL);
gpio_request(10, NULL);
gpio_direction_none(GPIO_PORT9CR); /* FSIAOBT needs no direction */
gpio_direction_none(GPIO_PORT10CR); /* FSIAOLR needs no direction */
/* card detect pin for MMC slot (CN7) */
gpio_request_one(41, GPIOF_IN, NULL);
/* setup FSI2 port B (HDMI) */
gpio_request(GPIO_FN_FSIBCK, NULL);
__raw_writew(__raw_readw(USCCR1) & ~(1 << 6), USCCR1); /* use SPDIF */
/* set SPU2 clock to 119.6 MHz */
clk = clk_get(NULL, "spu_clk");
if (!IS_ERR(clk)) {
clk_set_rate(clk, clk_round_rate(clk, 119600000));
clk_put(clk);
}
/*
* set irq priority, to avoid sound chopping
* when NFS rootfs is used
* FSI(3) > SMSC911X(2)
*/
intc_set_priority(IRQ_FSI, 3);
i2c_register_board_info(0, i2c0_devices,
ARRAY_SIZE(i2c0_devices));
i2c_register_board_info(1, i2c1_devices,
ARRAY_SIZE(i2c1_devices));
#ifdef CONFIG_AP4EVB_QHD
/*
* For QHD Panel (MIPI-DSI, CONFIG_AP4EVB_QHD=y) and
* IRQ28 for Touch Panel, set dip switches S3, S43 as OFF, ON.
*/
/* enable KEYSC */
gpio_request(GPIO_FN_KEYOUT0, NULL);
gpio_request(GPIO_FN_KEYOUT1, NULL);
gpio_request(GPIO_FN_KEYOUT2, NULL);
gpio_request(GPIO_FN_KEYOUT3, NULL);
gpio_request(GPIO_FN_KEYOUT4, NULL);
gpio_request(GPIO_FN_KEYIN0_136, NULL);
gpio_request(GPIO_FN_KEYIN1_135, NULL);
gpio_request(GPIO_FN_KEYIN2_134, NULL);
gpio_request(GPIO_FN_KEYIN3_133, NULL);
gpio_request(GPIO_FN_KEYIN4, NULL);
/* enable TouchScreen */
irq_set_irq_type(IRQ28, IRQ_TYPE_LEVEL_LOW);
tsc_device.irq = IRQ28;
i2c_register_board_info(1, &tsc_device, 1);
/* LCDC0 */
lcdc_info.clock_source = LCDC_CLK_PERIPHERAL;
lcdc_info.ch[0].interface_type = RGB24;
lcdc_info.ch[0].clock_divider = 1;
lcdc_info.ch[0].flags = LCDC_FLAGS_DWPOL;
lcdc_info.ch[0].panel_cfg.width = 44;
lcdc_info.ch[0].panel_cfg.height = 79;
platform_add_devices(qhd_devices, ARRAY_SIZE(qhd_devices));
#else
/*
* For WVGA Panel (18-bit RGB, CONFIG_AP4EVB_WVGA=y) and
* IRQ7 for Touch Panel, set dip switches S3, S43 to ON, OFF.
*/
gpio_request(GPIO_FN_LCDD17, NULL);
gpio_request(GPIO_FN_LCDD16, NULL);
gpio_request(GPIO_FN_LCDD15, NULL);
gpio_request(GPIO_FN_LCDD14, NULL);
gpio_request(GPIO_FN_LCDD13, NULL);
gpio_request(GPIO_FN_LCDD12, NULL);
gpio_request(GPIO_FN_LCDD11, NULL);
gpio_request(GPIO_FN_LCDD10, NULL);
gpio_request(GPIO_FN_LCDD9, NULL);
gpio_request(GPIO_FN_LCDD8, NULL);
gpio_request(GPIO_FN_LCDD7, NULL);
gpio_request(GPIO_FN_LCDD6, NULL);
gpio_request(GPIO_FN_LCDD5, NULL);
gpio_request(GPIO_FN_LCDD4, NULL);
gpio_request(GPIO_FN_LCDD3, NULL);
gpio_request(GPIO_FN_LCDD2, NULL);
gpio_request(GPIO_FN_LCDD1, NULL);
gpio_request(GPIO_FN_LCDD0, NULL);
gpio_request(GPIO_FN_LCDDISP, NULL);
gpio_request(GPIO_FN_LCDDCK, NULL);
gpio_request_one(189, GPIOF_OUT_INIT_HIGH, NULL); /* backlight */
gpio_request_one(151, GPIOF_OUT_INIT_HIGH, NULL); /* LCDDON */
lcdc_info.clock_source = LCDC_CLK_BUS;
lcdc_info.ch[0].interface_type = RGB18;
lcdc_info.ch[0].clock_divider = 3;
lcdc_info.ch[0].flags = 0;
lcdc_info.ch[0].panel_cfg.width = 152;
lcdc_info.ch[0].panel_cfg.height = 91;
/* enable TouchScreen */
irq_set_irq_type(IRQ7, IRQ_TYPE_LEVEL_LOW);
tsc_device.irq = IRQ7;
i2c_register_board_info(0, &tsc_device, 1);
#endif /* CONFIG_AP4EVB_QHD */
/* CEU */
/*
* TODO: reserve memory for V4L2 DMA buffers, when a suitable API
* becomes available
*/
/* MIPI-CSI stuff */
gpio_request(GPIO_FN_VIO_CKO, NULL);
clk = clk_get(NULL, "vck1_clk");
if (!IS_ERR(clk)) {
clk_set_rate(clk, clk_round_rate(clk, 13000000));
clk_enable(clk);
clk_put(clk);
}
sh7372_add_standard_devices();
/* HDMI */
gpio_request(GPIO_FN_HDMI_HPD, NULL);
gpio_request(GPIO_FN_HDMI_CEC, NULL);
/* Reset HDMI, must be held at least one EXTALR (32768Hz) period */
#define SRCR4 IOMEM(0xe61580bc)
srcr4 = __raw_readl(SRCR4);
__raw_writel(srcr4 | (1 << 13), SRCR4);
udelay(50);
__raw_writel(srcr4 & ~(1 << 13), SRCR4);
platform_add_devices(ap4evb_devices, ARRAY_SIZE(ap4evb_devices));
rmobile_add_devices_to_domains(domain_devices,
ARRAY_SIZE(domain_devices));
hdmi_init_pm_clock();
sh7372_pm_init();
pm_clk_add(&fsi_device.dev, "spu2");
pm_clk_add(&lcdc1_device.dev, "hdmi");
}
MACHINE_START(AP4EVB, "ap4evb")
.map_io = sh7372_map_io,
.init_early = sh7372_add_early_devices,
.init_irq = sh7372_init_irq,
.handle_irq = shmobile_handle_irq_intc,
.init_machine = ap4evb_init,
.init_late = sh7372_pm_init_late,
.init_time = sh7372_earlytimer_init,
MACHINE_END
| gpl-2.0 |
SudaMod-devices/boeffla-kernel-cm-bacon | drivers/staging/android/switch/switch_class.c | 2300 | 4371 | /*
* switch_class.c
*
* Copyright (C) 2008 Google, Inc.
* Author: Mike Lockwood <lockwood@android.com>
*
* 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/types.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/err.h>
#include "switch.h"
struct class *switch_class;
static atomic_t device_count;
static ssize_t state_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_state) {
int ret = sdev->print_state(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%d\n", sdev->state);
}
static ssize_t name_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_name) {
int ret = sdev->print_name(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%s\n", sdev->name);
}
static DEVICE_ATTR(state, S_IRUGO | S_IWUSR, state_show, NULL);
static DEVICE_ATTR(name, S_IRUGO | S_IWUSR, name_show, NULL);
void switch_set_state(struct switch_dev *sdev, int state)
{
char name_buf[120];
char state_buf[120];
char *prop_buf;
char *envp[3];
int env_offset = 0;
int length;
if (sdev->state != state) {
sdev->state = state;
prop_buf = (char *)get_zeroed_page(GFP_KERNEL);
if (prop_buf) {
length = name_show(sdev->dev, NULL, prop_buf);
if (length > 0) {
if (prop_buf[length - 1] == '\n')
prop_buf[length - 1] = 0;
snprintf(name_buf, sizeof(name_buf),
"SWITCH_NAME=%s", prop_buf);
envp[env_offset++] = name_buf;
}
length = state_show(sdev->dev, NULL, prop_buf);
if (length > 0) {
if (prop_buf[length - 1] == '\n')
prop_buf[length - 1] = 0;
snprintf(state_buf, sizeof(state_buf),
"SWITCH_STATE=%s", prop_buf);
envp[env_offset++] = state_buf;
}
envp[env_offset] = NULL;
kobject_uevent_env(&sdev->dev->kobj, KOBJ_CHANGE, envp);
free_page((unsigned long)prop_buf);
} else {
printk(KERN_ERR "out of memory in switch_set_state\n");
kobject_uevent(&sdev->dev->kobj, KOBJ_CHANGE);
}
}
}
EXPORT_SYMBOL_GPL(switch_set_state);
static int create_switch_class(void)
{
if (!switch_class) {
switch_class = class_create(THIS_MODULE, "switch");
if (IS_ERR(switch_class))
return PTR_ERR(switch_class);
atomic_set(&device_count, 0);
}
return 0;
}
int switch_dev_register(struct switch_dev *sdev)
{
int ret;
if (!switch_class) {
ret = create_switch_class();
if (ret < 0)
return ret;
}
sdev->index = atomic_inc_return(&device_count);
sdev->dev = device_create(switch_class, NULL,
MKDEV(0, sdev->index), NULL, sdev->name);
if (IS_ERR(sdev->dev))
return PTR_ERR(sdev->dev);
ret = device_create_file(sdev->dev, &dev_attr_state);
if (ret < 0)
goto err_create_file_1;
ret = device_create_file(sdev->dev, &dev_attr_name);
if (ret < 0)
goto err_create_file_2;
dev_set_drvdata(sdev->dev, sdev);
sdev->state = 0;
return 0;
err_create_file_2:
device_remove_file(sdev->dev, &dev_attr_state);
err_create_file_1:
device_destroy(switch_class, MKDEV(0, sdev->index));
printk(KERN_ERR "switch: Failed to register driver %s\n", sdev->name);
return ret;
}
EXPORT_SYMBOL_GPL(switch_dev_register);
void switch_dev_unregister(struct switch_dev *sdev)
{
device_remove_file(sdev->dev, &dev_attr_name);
device_remove_file(sdev->dev, &dev_attr_state);
dev_set_drvdata(sdev->dev, NULL);
device_destroy(switch_class, MKDEV(0, sdev->index));
}
EXPORT_SYMBOL_GPL(switch_dev_unregister);
static int __init switch_class_init(void)
{
return create_switch_class();
}
static void __exit switch_class_exit(void)
{
class_destroy(switch_class);
}
module_init(switch_class_init);
module_exit(switch_class_exit);
MODULE_AUTHOR("Mike Lockwood <lockwood@android.com>");
MODULE_DESCRIPTION("Switch class driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Arakmar/android_kernel_sony_msm8660 | drivers/staging/line6/pcm.c | 3068 | 12775 | /*
* Line6 Linux USB driver - 0.9.1beta
*
* Copyright (C) 2004-2010 Markus Grabner (grabner@icg.tugraz.at)
*
* 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.
*
*/
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "audio.h"
#include "capture.h"
#include "driver.h"
#include "playback.h"
#include "pod.h"
#ifdef CONFIG_LINE6_USB_IMPULSE_RESPONSE
static struct snd_line6_pcm *dev2pcm(struct device *dev)
{
struct usb_interface *interface = to_usb_interface(dev);
struct usb_line6 *line6 = usb_get_intfdata(interface);
struct snd_line6_pcm *line6pcm = line6->line6pcm;
return line6pcm;
}
/*
"read" request on "impulse_volume" special file.
*/
static ssize_t pcm_get_impulse_volume(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", dev2pcm(dev)->impulse_volume);
}
/*
"write" request on "impulse_volume" special file.
*/
static ssize_t pcm_set_impulse_volume(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct snd_line6_pcm *line6pcm = dev2pcm(dev);
int value = simple_strtoul(buf, NULL, 10);
line6pcm->impulse_volume = value;
if (value > 0)
line6_pcm_start(line6pcm, MASK_PCM_IMPULSE);
else
line6_pcm_stop(line6pcm, MASK_PCM_IMPULSE);
return count;
}
/*
"read" request on "impulse_period" special file.
*/
static ssize_t pcm_get_impulse_period(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", dev2pcm(dev)->impulse_period);
}
/*
"write" request on "impulse_period" special file.
*/
static ssize_t pcm_set_impulse_period(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
dev2pcm(dev)->impulse_period = simple_strtoul(buf, NULL, 10);
return count;
}
static DEVICE_ATTR(impulse_volume, S_IWUSR | S_IRUGO, pcm_get_impulse_volume,
pcm_set_impulse_volume);
static DEVICE_ATTR(impulse_period, S_IWUSR | S_IRUGO, pcm_get_impulse_period,
pcm_set_impulse_period);
#endif
int line6_pcm_start(struct snd_line6_pcm *line6pcm, int channels)
{
unsigned long flags_old =
__sync_fetch_and_or(&line6pcm->flags, channels);
unsigned long flags_new = flags_old | channels;
int err = 0;
#if LINE6_BACKUP_MONITOR_SIGNAL
if (!(line6pcm->line6->properties->capabilities & LINE6_BIT_HWMON)) {
line6pcm->prev_fbuf =
kmalloc(LINE6_ISO_PACKETS * line6pcm->max_packet_size,
GFP_KERNEL);
if (!line6pcm->prev_fbuf) {
dev_err(line6pcm->line6->ifcdev,
"cannot malloc monitor buffer\n");
return -ENOMEM;
}
}
#else
line6pcm->prev_fbuf = NULL;
#endif
if (((flags_old & MASK_CAPTURE) == 0) &&
((flags_new & MASK_CAPTURE) != 0)) {
/*
Waiting for completion of active URBs in the stop handler is
a bug, we therefore report an error if capturing is restarted
too soon.
*/
if (line6pcm->active_urb_in | line6pcm->unlink_urb_in)
return -EBUSY;
line6pcm->buffer_in =
kmalloc(LINE6_ISO_BUFFERS * LINE6_ISO_PACKETS *
line6pcm->max_packet_size, GFP_KERNEL);
if (!line6pcm->buffer_in) {
dev_err(line6pcm->line6->ifcdev,
"cannot malloc capture buffer\n");
return -ENOMEM;
}
line6pcm->count_in = 0;
line6pcm->prev_fsize = 0;
err = line6_submit_audio_in_all_urbs(line6pcm);
if (err < 0) {
__sync_fetch_and_and(&line6pcm->flags, ~channels);
return err;
}
}
if (((flags_old & MASK_PLAYBACK) == 0) &&
((flags_new & MASK_PLAYBACK) != 0)) {
/*
See comment above regarding PCM restart.
*/
if (line6pcm->active_urb_out | line6pcm->unlink_urb_out)
return -EBUSY;
line6pcm->buffer_out =
kmalloc(LINE6_ISO_BUFFERS * LINE6_ISO_PACKETS *
line6pcm->max_packet_size, GFP_KERNEL);
if (!line6pcm->buffer_out) {
dev_err(line6pcm->line6->ifcdev,
"cannot malloc playback buffer\n");
return -ENOMEM;
}
line6pcm->count_out = 0;
err = line6_submit_audio_out_all_urbs(line6pcm);
if (err < 0) {
__sync_fetch_and_and(&line6pcm->flags, ~channels);
return err;
}
}
return 0;
}
int line6_pcm_stop(struct snd_line6_pcm *line6pcm, int channels)
{
unsigned long flags_old =
__sync_fetch_and_and(&line6pcm->flags, ~channels);
unsigned long flags_new = flags_old & ~channels;
if (((flags_old & MASK_CAPTURE) != 0) &&
((flags_new & MASK_CAPTURE) == 0)) {
line6_unlink_audio_in_urbs(line6pcm);
kfree(line6pcm->buffer_in);
line6pcm->buffer_in = NULL;
}
if (((flags_old & MASK_PLAYBACK) != 0) &&
((flags_new & MASK_PLAYBACK) == 0)) {
line6_unlink_audio_out_urbs(line6pcm);
kfree(line6pcm->buffer_out);
line6pcm->buffer_out = NULL;
}
#if LINE6_BACKUP_MONITOR_SIGNAL
kfree(line6pcm->prev_fbuf);
#endif
return 0;
}
/* trigger callback */
int snd_line6_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_line6_pcm *line6pcm = snd_pcm_substream_chip(substream);
struct snd_pcm_substream *s;
int err;
unsigned long flags;
spin_lock_irqsave(&line6pcm->lock_trigger, flags);
clear_bit(BIT_PREPARED, &line6pcm->flags);
snd_pcm_group_for_each_entry(s, substream) {
switch (s->stream) {
case SNDRV_PCM_STREAM_PLAYBACK:
err = snd_line6_playback_trigger(line6pcm, cmd);
if (err < 0) {
spin_unlock_irqrestore(&line6pcm->lock_trigger,
flags);
return err;
}
break;
case SNDRV_PCM_STREAM_CAPTURE:
err = snd_line6_capture_trigger(line6pcm, cmd);
if (err < 0) {
spin_unlock_irqrestore(&line6pcm->lock_trigger,
flags);
return err;
}
break;
default:
dev_err(line6pcm->line6->ifcdev,
"Unknown stream direction %d\n", s->stream);
}
}
spin_unlock_irqrestore(&line6pcm->lock_trigger, flags);
return 0;
}
/* control info callback */
static int snd_line6_control_playback_info(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 = 256;
return 0;
}
/* control get callback */
static int snd_line6_control_playback_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int i;
struct snd_line6_pcm *line6pcm = snd_kcontrol_chip(kcontrol);
for (i = 2; i--;)
ucontrol->value.integer.value[i] = line6pcm->volume_playback[i];
return 0;
}
/* control put callback */
static int snd_line6_control_playback_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int i, changed = 0;
struct snd_line6_pcm *line6pcm = snd_kcontrol_chip(kcontrol);
for (i = 2; i--;)
if (line6pcm->volume_playback[i] !=
ucontrol->value.integer.value[i]) {
line6pcm->volume_playback[i] =
ucontrol->value.integer.value[i];
changed = 1;
}
return changed;
}
/* control definition */
static struct snd_kcontrol_new line6_control_playback = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Volume",
.index = 0,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_line6_control_playback_info,
.get = snd_line6_control_playback_get,
.put = snd_line6_control_playback_put
};
/*
Cleanup the PCM device.
*/
static void line6_cleanup_pcm(struct snd_pcm *pcm)
{
int i;
struct snd_line6_pcm *line6pcm = snd_pcm_chip(pcm);
#ifdef CONFIG_LINE6_USB_IMPULSE_RESPONSE
device_remove_file(line6pcm->line6->ifcdev, &dev_attr_impulse_volume);
device_remove_file(line6pcm->line6->ifcdev, &dev_attr_impulse_period);
#endif
for (i = LINE6_ISO_BUFFERS; i--;) {
if (line6pcm->urb_audio_out[i]) {
usb_kill_urb(line6pcm->urb_audio_out[i]);
usb_free_urb(line6pcm->urb_audio_out[i]);
}
if (line6pcm->urb_audio_in[i]) {
usb_kill_urb(line6pcm->urb_audio_in[i]);
usb_free_urb(line6pcm->urb_audio_in[i]);
}
}
}
/* create a PCM device */
static int snd_line6_new_pcm(struct snd_line6_pcm *line6pcm)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(line6pcm->line6->card,
(char *)line6pcm->line6->properties->name,
0, 1, 1, &pcm);
if (err < 0)
return err;
pcm->private_data = line6pcm;
pcm->private_free = line6_cleanup_pcm;
line6pcm->pcm = pcm;
strcpy(pcm->name, line6pcm->line6->properties->name);
/* set operators */
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
&snd_line6_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_line6_capture_ops);
/* pre-allocation of buffers */
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
snd_dma_continuous_data
(GFP_KERNEL), 64 * 1024,
128 * 1024);
return 0;
}
/* PCM device destructor */
static int snd_line6_pcm_free(struct snd_device *device)
{
return 0;
}
/*
Stop substream if still running.
*/
static void pcm_disconnect_substream(struct snd_pcm_substream *substream)
{
if (substream->runtime && snd_pcm_running(substream))
snd_pcm_stop(substream, SNDRV_PCM_STATE_DISCONNECTED);
}
/*
Stop PCM stream.
*/
void line6_pcm_disconnect(struct snd_line6_pcm *line6pcm)
{
pcm_disconnect_substream(get_substream
(line6pcm, SNDRV_PCM_STREAM_CAPTURE));
pcm_disconnect_substream(get_substream
(line6pcm, SNDRV_PCM_STREAM_PLAYBACK));
line6_unlink_wait_clear_audio_out_urbs(line6pcm);
line6_unlink_wait_clear_audio_in_urbs(line6pcm);
}
/*
Create and register the PCM device and mixer entries.
Create URBs for playback and capture.
*/
int line6_init_pcm(struct usb_line6 *line6,
struct line6_pcm_properties *properties)
{
static struct snd_device_ops pcm_ops = {
.dev_free = snd_line6_pcm_free,
};
int err;
int ep_read = 0, ep_write = 0;
struct snd_line6_pcm *line6pcm;
if (!(line6->properties->capabilities & LINE6_BIT_PCM))
return 0; /* skip PCM initialization and report success */
/* initialize PCM subsystem based on product id: */
switch (line6->product) {
case LINE6_DEVID_BASSPODXT:
case LINE6_DEVID_BASSPODXTLIVE:
case LINE6_DEVID_BASSPODXTPRO:
case LINE6_DEVID_PODXT:
case LINE6_DEVID_PODXTLIVE:
case LINE6_DEVID_PODXTPRO:
ep_read = 0x82;
ep_write = 0x01;
break;
case LINE6_DEVID_PODX3:
case LINE6_DEVID_PODX3LIVE:
ep_read = 0x86;
ep_write = 0x02;
break;
case LINE6_DEVID_POCKETPOD:
ep_read = 0x82;
ep_write = 0x02;
break;
case LINE6_DEVID_GUITARPORT:
case LINE6_DEVID_PODSTUDIO_GX:
case LINE6_DEVID_PODSTUDIO_UX1:
case LINE6_DEVID_PODSTUDIO_UX2:
case LINE6_DEVID_TONEPORT_GX:
case LINE6_DEVID_TONEPORT_UX1:
case LINE6_DEVID_TONEPORT_UX2:
ep_read = 0x82;
ep_write = 0x01;
break;
/* this is for interface_number == 1:
case LINE6_DEVID_TONEPORT_UX2:
case LINE6_DEVID_PODSTUDIO_UX2:
ep_read = 0x87;
ep_write = 0x00;
break;
*/
default:
MISSING_CASE;
}
line6pcm = kzalloc(sizeof(struct snd_line6_pcm), GFP_KERNEL);
if (line6pcm == NULL)
return -ENOMEM;
line6pcm->volume_playback[0] = line6pcm->volume_playback[1] = 255;
line6pcm->volume_monitor = 255;
line6pcm->line6 = line6;
line6pcm->ep_audio_read = ep_read;
line6pcm->ep_audio_write = ep_write;
line6pcm->max_packet_size = usb_maxpacket(line6->usbdev,
usb_rcvintpipe(line6->usbdev,
ep_read), 0);
line6pcm->properties = properties;
line6->line6pcm = line6pcm;
/* PCM device: */
err = snd_device_new(line6->card, SNDRV_DEV_PCM, line6, &pcm_ops);
if (err < 0)
return err;
snd_card_set_dev(line6->card, line6->ifcdev);
err = snd_line6_new_pcm(line6pcm);
if (err < 0)
return err;
spin_lock_init(&line6pcm->lock_audio_out);
spin_lock_init(&line6pcm->lock_audio_in);
spin_lock_init(&line6pcm->lock_trigger);
err = line6_create_audio_out_urbs(line6pcm);
if (err < 0)
return err;
err = line6_create_audio_in_urbs(line6pcm);
if (err < 0)
return err;
/* mixer: */
err =
snd_ctl_add(line6->card,
snd_ctl_new1(&line6_control_playback, line6pcm));
if (err < 0)
return err;
#ifdef CONFIG_LINE6_USB_IMPULSE_RESPONSE
/* impulse response test: */
err = device_create_file(line6->ifcdev, &dev_attr_impulse_volume);
if (err < 0)
return err;
err = device_create_file(line6->ifcdev, &dev_attr_impulse_period);
if (err < 0)
return err;
line6pcm->impulse_period = LINE6_IMPULSE_DEFAULT_PERIOD;
#endif
return 0;
}
/* prepare pcm callback */
int snd_line6_prepare(struct snd_pcm_substream *substream)
{
struct snd_line6_pcm *line6pcm = snd_pcm_substream_chip(substream);
if (!test_and_set_bit(BIT_PREPARED, &line6pcm->flags)) {
line6pcm->count_out = 0;
line6pcm->pos_out = 0;
line6pcm->pos_out_done = 0;
line6pcm->bytes_out = 0;
line6pcm->count_in = 0;
line6pcm->pos_in_done = 0;
line6pcm->bytes_in = 0;
}
return 0;
}
| gpl-2.0 |
MWisBest/android_kernel_samsung_tuna | crypto/crc32c.c | 3324 | 8197 | /*
* Cryptographic API.
*
* CRC32C chksum
*
*@Article{castagnoli-crc,
* author = { Guy Castagnoli and Stefan Braeuer and Martin Herrman},
* title = {{Optimization of Cyclic Redundancy-Check Codes with 24
* and 32 Parity Bits}},
* journal = IEEE Transactions on Communication,
* year = {1993},
* volume = {41},
* number = {6},
* pages = {},
* month = {June},
*}
* Used by the iSCSI driver, possibly others, and derived from the
* the iscsi-crc.c module of the linux-iscsi driver at
* http://linux-iscsi.sourceforge.net.
*
* Following the example of lib/crc32, this function is intended to be
* flexible and useful for all users. Modules that currently have their
* own crc32c, but hopefully may be able to use this one are:
* net/sctp (please add all your doco to here if you change to
* use this one!)
* <endoflist>
*
* Copyright (c) 2004 Cisco Systems, Inc.
* Copyright (c) 2008 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/internal/hash.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/kernel.h>
#define CHKSUM_BLOCK_SIZE 1
#define CHKSUM_DIGEST_SIZE 4
struct chksum_ctx {
u32 key;
};
struct chksum_desc_ctx {
u32 crc;
};
/*
* This is the CRC-32C table
* Generated with:
* width = 32 bits
* poly = 0x1EDC6F41
* reflect input bytes = true
* reflect output bytes = true
*/
static const u32 crc32c_table[256] = {
0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L,
0xC79A971FL, 0x35F1141CL, 0x26A1E7E8L, 0xD4CA64EBL,
0x8AD958CFL, 0x78B2DBCCL, 0x6BE22838L, 0x9989AB3BL,
0x4D43CFD0L, 0xBF284CD3L, 0xAC78BF27L, 0x5E133C24L,
0x105EC76FL, 0xE235446CL, 0xF165B798L, 0x030E349BL,
0xD7C45070L, 0x25AFD373L, 0x36FF2087L, 0xC494A384L,
0x9A879FA0L, 0x68EC1CA3L, 0x7BBCEF57L, 0x89D76C54L,
0x5D1D08BFL, 0xAF768BBCL, 0xBC267848L, 0x4E4DFB4BL,
0x20BD8EDEL, 0xD2D60DDDL, 0xC186FE29L, 0x33ED7D2AL,
0xE72719C1L, 0x154C9AC2L, 0x061C6936L, 0xF477EA35L,
0xAA64D611L, 0x580F5512L, 0x4B5FA6E6L, 0xB93425E5L,
0x6DFE410EL, 0x9F95C20DL, 0x8CC531F9L, 0x7EAEB2FAL,
0x30E349B1L, 0xC288CAB2L, 0xD1D83946L, 0x23B3BA45L,
0xF779DEAEL, 0x05125DADL, 0x1642AE59L, 0xE4292D5AL,
0xBA3A117EL, 0x4851927DL, 0x5B016189L, 0xA96AE28AL,
0x7DA08661L, 0x8FCB0562L, 0x9C9BF696L, 0x6EF07595L,
0x417B1DBCL, 0xB3109EBFL, 0xA0406D4BL, 0x522BEE48L,
0x86E18AA3L, 0x748A09A0L, 0x67DAFA54L, 0x95B17957L,
0xCBA24573L, 0x39C9C670L, 0x2A993584L, 0xD8F2B687L,
0x0C38D26CL, 0xFE53516FL, 0xED03A29BL, 0x1F682198L,
0x5125DAD3L, 0xA34E59D0L, 0xB01EAA24L, 0x42752927L,
0x96BF4DCCL, 0x64D4CECFL, 0x77843D3BL, 0x85EFBE38L,
0xDBFC821CL, 0x2997011FL, 0x3AC7F2EBL, 0xC8AC71E8L,
0x1C661503L, 0xEE0D9600L, 0xFD5D65F4L, 0x0F36E6F7L,
0x61C69362L, 0x93AD1061L, 0x80FDE395L, 0x72966096L,
0xA65C047DL, 0x5437877EL, 0x4767748AL, 0xB50CF789L,
0xEB1FCBADL, 0x197448AEL, 0x0A24BB5AL, 0xF84F3859L,
0x2C855CB2L, 0xDEEEDFB1L, 0xCDBE2C45L, 0x3FD5AF46L,
0x7198540DL, 0x83F3D70EL, 0x90A324FAL, 0x62C8A7F9L,
0xB602C312L, 0x44694011L, 0x5739B3E5L, 0xA55230E6L,
0xFB410CC2L, 0x092A8FC1L, 0x1A7A7C35L, 0xE811FF36L,
0x3CDB9BDDL, 0xCEB018DEL, 0xDDE0EB2AL, 0x2F8B6829L,
0x82F63B78L, 0x709DB87BL, 0x63CD4B8FL, 0x91A6C88CL,
0x456CAC67L, 0xB7072F64L, 0xA457DC90L, 0x563C5F93L,
0x082F63B7L, 0xFA44E0B4L, 0xE9141340L, 0x1B7F9043L,
0xCFB5F4A8L, 0x3DDE77ABL, 0x2E8E845FL, 0xDCE5075CL,
0x92A8FC17L, 0x60C37F14L, 0x73938CE0L, 0x81F80FE3L,
0x55326B08L, 0xA759E80BL, 0xB4091BFFL, 0x466298FCL,
0x1871A4D8L, 0xEA1A27DBL, 0xF94AD42FL, 0x0B21572CL,
0xDFEB33C7L, 0x2D80B0C4L, 0x3ED04330L, 0xCCBBC033L,
0xA24BB5A6L, 0x502036A5L, 0x4370C551L, 0xB11B4652L,
0x65D122B9L, 0x97BAA1BAL, 0x84EA524EL, 0x7681D14DL,
0x2892ED69L, 0xDAF96E6AL, 0xC9A99D9EL, 0x3BC21E9DL,
0xEF087A76L, 0x1D63F975L, 0x0E330A81L, 0xFC588982L,
0xB21572C9L, 0x407EF1CAL, 0x532E023EL, 0xA145813DL,
0x758FE5D6L, 0x87E466D5L, 0x94B49521L, 0x66DF1622L,
0x38CC2A06L, 0xCAA7A905L, 0xD9F75AF1L, 0x2B9CD9F2L,
0xFF56BD19L, 0x0D3D3E1AL, 0x1E6DCDEEL, 0xEC064EEDL,
0xC38D26C4L, 0x31E6A5C7L, 0x22B65633L, 0xD0DDD530L,
0x0417B1DBL, 0xF67C32D8L, 0xE52CC12CL, 0x1747422FL,
0x49547E0BL, 0xBB3FFD08L, 0xA86F0EFCL, 0x5A048DFFL,
0x8ECEE914L, 0x7CA56A17L, 0x6FF599E3L, 0x9D9E1AE0L,
0xD3D3E1ABL, 0x21B862A8L, 0x32E8915CL, 0xC083125FL,
0x144976B4L, 0xE622F5B7L, 0xF5720643L, 0x07198540L,
0x590AB964L, 0xAB613A67L, 0xB831C993L, 0x4A5A4A90L,
0x9E902E7BL, 0x6CFBAD78L, 0x7FAB5E8CL, 0x8DC0DD8FL,
0xE330A81AL, 0x115B2B19L, 0x020BD8EDL, 0xF0605BEEL,
0x24AA3F05L, 0xD6C1BC06L, 0xC5914FF2L, 0x37FACCF1L,
0x69E9F0D5L, 0x9B8273D6L, 0x88D28022L, 0x7AB90321L,
0xAE7367CAL, 0x5C18E4C9L, 0x4F48173DL, 0xBD23943EL,
0xF36E6F75L, 0x0105EC76L, 0x12551F82L, 0xE03E9C81L,
0x34F4F86AL, 0xC69F7B69L, 0xD5CF889DL, 0x27A40B9EL,
0x79B737BAL, 0x8BDCB4B9L, 0x988C474DL, 0x6AE7C44EL,
0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, 0xAD7D5351L
};
/*
* Steps through buffer one byte at at time, calculates reflected
* crc using table.
*/
static u32 crc32c(u32 crc, const u8 *data, unsigned int length)
{
while (length--)
crc = crc32c_table[(crc ^ *data++) & 0xFFL] ^ (crc >> 8);
return crc;
}
/*
* Steps through buffer one byte at at time, calculates reflected
* crc using table.
*/
static int chksum_init(struct shash_desc *desc)
{
struct chksum_ctx *mctx = crypto_shash_ctx(desc->tfm);
struct chksum_desc_ctx *ctx = shash_desc_ctx(desc);
ctx->crc = mctx->key;
return 0;
}
/*
* Setting the seed allows arbitrary accumulators and flexible XOR policy
* If your algorithm starts with ~0, then XOR with ~0 before you set
* the seed.
*/
static int chksum_setkey(struct crypto_shash *tfm, const u8 *key,
unsigned int keylen)
{
struct chksum_ctx *mctx = crypto_shash_ctx(tfm);
if (keylen != sizeof(mctx->key)) {
crypto_shash_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
mctx->key = le32_to_cpu(*(__le32 *)key);
return 0;
}
static int chksum_update(struct shash_desc *desc, const u8 *data,
unsigned int length)
{
struct chksum_desc_ctx *ctx = shash_desc_ctx(desc);
ctx->crc = crc32c(ctx->crc, data, length);
return 0;
}
static int chksum_final(struct shash_desc *desc, u8 *out)
{
struct chksum_desc_ctx *ctx = shash_desc_ctx(desc);
*(__le32 *)out = ~cpu_to_le32p(&ctx->crc);
return 0;
}
static int __chksum_finup(u32 *crcp, const u8 *data, unsigned int len, u8 *out)
{
*(__le32 *)out = ~cpu_to_le32(crc32c(*crcp, data, len));
return 0;
}
static int chksum_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
struct chksum_desc_ctx *ctx = shash_desc_ctx(desc);
return __chksum_finup(&ctx->crc, data, len, out);
}
static int chksum_digest(struct shash_desc *desc, const u8 *data,
unsigned int length, u8 *out)
{
struct chksum_ctx *mctx = crypto_shash_ctx(desc->tfm);
return __chksum_finup(&mctx->key, data, length, out);
}
static int crc32c_cra_init(struct crypto_tfm *tfm)
{
struct chksum_ctx *mctx = crypto_tfm_ctx(tfm);
mctx->key = ~0;
return 0;
}
static struct shash_alg alg = {
.digestsize = CHKSUM_DIGEST_SIZE,
.setkey = chksum_setkey,
.init = chksum_init,
.update = chksum_update,
.final = chksum_final,
.finup = chksum_finup,
.digest = chksum_digest,
.descsize = sizeof(struct chksum_desc_ctx),
.base = {
.cra_name = "crc32c",
.cra_driver_name = "crc32c-generic",
.cra_priority = 100,
.cra_blocksize = CHKSUM_BLOCK_SIZE,
.cra_alignmask = 3,
.cra_ctxsize = sizeof(struct chksum_ctx),
.cra_module = THIS_MODULE,
.cra_init = crc32c_cra_init,
}
};
static int __init crc32c_mod_init(void)
{
return crypto_register_shash(&alg);
}
static void __exit crc32c_mod_fini(void)
{
crypto_unregister_shash(&alg);
}
module_init(crc32c_mod_init);
module_exit(crc32c_mod_fini);
MODULE_AUTHOR("Clay Haapala <chaapala@cisco.com>");
MODULE_DESCRIPTION("CRC32c (Castagnoli) calculations wrapper for lib/crc32c");
MODULE_LICENSE("GPL");
| gpl-2.0 |
AICP/kernel_htc_m7 | drivers/net/ethernet/faraday/ftgmac100.c | 4860 | 35713 | /*
* Faraday FTGMAC100 Gigabit Ethernet
*
* (C) Copyright 2009-2011 Faraday Technology
* Po-Yu Chuang <ratbert@faraday-tech.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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/dma-mapping.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/phy.h>
#include <linux/platform_device.h>
#include <net/ip.h>
#include "ftgmac100.h"
#define DRV_NAME "ftgmac100"
#define DRV_VERSION "0.7"
#define RX_QUEUE_ENTRIES 256 /* must be power of 2 */
#define TX_QUEUE_ENTRIES 512 /* must be power of 2 */
#define MAX_PKT_SIZE 1518
#define RX_BUF_SIZE PAGE_SIZE /* must be smaller than 0x3fff */
/******************************************************************************
* private data
*****************************************************************************/
struct ftgmac100_descs {
struct ftgmac100_rxdes rxdes[RX_QUEUE_ENTRIES];
struct ftgmac100_txdes txdes[TX_QUEUE_ENTRIES];
};
struct ftgmac100 {
struct resource *res;
void __iomem *base;
int irq;
struct ftgmac100_descs *descs;
dma_addr_t descs_dma_addr;
unsigned int rx_pointer;
unsigned int tx_clean_pointer;
unsigned int tx_pointer;
unsigned int tx_pending;
spinlock_t tx_lock;
struct net_device *netdev;
struct device *dev;
struct napi_struct napi;
struct mii_bus *mii_bus;
int phy_irq[PHY_MAX_ADDR];
struct phy_device *phydev;
int old_speed;
};
static int ftgmac100_alloc_rx_page(struct ftgmac100 *priv,
struct ftgmac100_rxdes *rxdes, gfp_t gfp);
/******************************************************************************
* internal functions (hardware register access)
*****************************************************************************/
#define INT_MASK_ALL_ENABLED (FTGMAC100_INT_RPKT_LOST | \
FTGMAC100_INT_XPKT_ETH | \
FTGMAC100_INT_XPKT_LOST | \
FTGMAC100_INT_AHB_ERR | \
FTGMAC100_INT_PHYSTS_CHG | \
FTGMAC100_INT_RPKT_BUF | \
FTGMAC100_INT_NO_RXBUF)
static void ftgmac100_set_rx_ring_base(struct ftgmac100 *priv, dma_addr_t addr)
{
iowrite32(addr, priv->base + FTGMAC100_OFFSET_RXR_BADR);
}
static void ftgmac100_set_rx_buffer_size(struct ftgmac100 *priv,
unsigned int size)
{
size = FTGMAC100_RBSR_SIZE(size);
iowrite32(size, priv->base + FTGMAC100_OFFSET_RBSR);
}
static void ftgmac100_set_normal_prio_tx_ring_base(struct ftgmac100 *priv,
dma_addr_t addr)
{
iowrite32(addr, priv->base + FTGMAC100_OFFSET_NPTXR_BADR);
}
static void ftgmac100_txdma_normal_prio_start_polling(struct ftgmac100 *priv)
{
iowrite32(1, priv->base + FTGMAC100_OFFSET_NPTXPD);
}
static int ftgmac100_reset_hw(struct ftgmac100 *priv)
{
struct net_device *netdev = priv->netdev;
int i;
/* NOTE: reset clears all registers */
iowrite32(FTGMAC100_MACCR_SW_RST, priv->base + FTGMAC100_OFFSET_MACCR);
for (i = 0; i < 5; i++) {
unsigned int maccr;
maccr = ioread32(priv->base + FTGMAC100_OFFSET_MACCR);
if (!(maccr & FTGMAC100_MACCR_SW_RST))
return 0;
udelay(1000);
}
netdev_err(netdev, "software reset failed\n");
return -EIO;
}
static void ftgmac100_set_mac(struct ftgmac100 *priv, const unsigned char *mac)
{
unsigned int maddr = mac[0] << 8 | mac[1];
unsigned int laddr = mac[2] << 24 | mac[3] << 16 | mac[4] << 8 | mac[5];
iowrite32(maddr, priv->base + FTGMAC100_OFFSET_MAC_MADR);
iowrite32(laddr, priv->base + FTGMAC100_OFFSET_MAC_LADR);
}
static void ftgmac100_init_hw(struct ftgmac100 *priv)
{
/* setup ring buffer base registers */
ftgmac100_set_rx_ring_base(priv,
priv->descs_dma_addr +
offsetof(struct ftgmac100_descs, rxdes));
ftgmac100_set_normal_prio_tx_ring_base(priv,
priv->descs_dma_addr +
offsetof(struct ftgmac100_descs, txdes));
ftgmac100_set_rx_buffer_size(priv, RX_BUF_SIZE);
iowrite32(FTGMAC100_APTC_RXPOLL_CNT(1), priv->base + FTGMAC100_OFFSET_APTC);
ftgmac100_set_mac(priv, priv->netdev->dev_addr);
}
#define MACCR_ENABLE_ALL (FTGMAC100_MACCR_TXDMA_EN | \
FTGMAC100_MACCR_RXDMA_EN | \
FTGMAC100_MACCR_TXMAC_EN | \
FTGMAC100_MACCR_RXMAC_EN | \
FTGMAC100_MACCR_FULLDUP | \
FTGMAC100_MACCR_CRC_APD | \
FTGMAC100_MACCR_RX_RUNT | \
FTGMAC100_MACCR_RX_BROADPKT)
static void ftgmac100_start_hw(struct ftgmac100 *priv, int speed)
{
int maccr = MACCR_ENABLE_ALL;
switch (speed) {
default:
case 10:
break;
case 100:
maccr |= FTGMAC100_MACCR_FAST_MODE;
break;
case 1000:
maccr |= FTGMAC100_MACCR_GIGA_MODE;
break;
}
iowrite32(maccr, priv->base + FTGMAC100_OFFSET_MACCR);
}
static void ftgmac100_stop_hw(struct ftgmac100 *priv)
{
iowrite32(0, priv->base + FTGMAC100_OFFSET_MACCR);
}
/******************************************************************************
* internal functions (receive descriptor)
*****************************************************************************/
static bool ftgmac100_rxdes_first_segment(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_FRS);
}
static bool ftgmac100_rxdes_last_segment(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_LRS);
}
static bool ftgmac100_rxdes_packet_ready(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_RXPKT_RDY);
}
static void ftgmac100_rxdes_set_dma_own(struct ftgmac100_rxdes *rxdes)
{
/* clear status bits */
rxdes->rxdes0 &= cpu_to_le32(FTGMAC100_RXDES0_EDORR);
}
static bool ftgmac100_rxdes_rx_error(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_RX_ERR);
}
static bool ftgmac100_rxdes_crc_error(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_CRC_ERR);
}
static bool ftgmac100_rxdes_frame_too_long(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_FTL);
}
static bool ftgmac100_rxdes_runt(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_RUNT);
}
static bool ftgmac100_rxdes_odd_nibble(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_RX_ODD_NB);
}
static unsigned int ftgmac100_rxdes_data_length(struct ftgmac100_rxdes *rxdes)
{
return le32_to_cpu(rxdes->rxdes0) & FTGMAC100_RXDES0_VDBC;
}
static bool ftgmac100_rxdes_multicast(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes0 & cpu_to_le32(FTGMAC100_RXDES0_MULTICAST);
}
static void ftgmac100_rxdes_set_end_of_ring(struct ftgmac100_rxdes *rxdes)
{
rxdes->rxdes0 |= cpu_to_le32(FTGMAC100_RXDES0_EDORR);
}
static void ftgmac100_rxdes_set_dma_addr(struct ftgmac100_rxdes *rxdes,
dma_addr_t addr)
{
rxdes->rxdes3 = cpu_to_le32(addr);
}
static dma_addr_t ftgmac100_rxdes_get_dma_addr(struct ftgmac100_rxdes *rxdes)
{
return le32_to_cpu(rxdes->rxdes3);
}
static bool ftgmac100_rxdes_is_tcp(struct ftgmac100_rxdes *rxdes)
{
return (rxdes->rxdes1 & cpu_to_le32(FTGMAC100_RXDES1_PROT_MASK)) ==
cpu_to_le32(FTGMAC100_RXDES1_PROT_TCPIP);
}
static bool ftgmac100_rxdes_is_udp(struct ftgmac100_rxdes *rxdes)
{
return (rxdes->rxdes1 & cpu_to_le32(FTGMAC100_RXDES1_PROT_MASK)) ==
cpu_to_le32(FTGMAC100_RXDES1_PROT_UDPIP);
}
static bool ftgmac100_rxdes_tcpcs_err(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes1 & cpu_to_le32(FTGMAC100_RXDES1_TCP_CHKSUM_ERR);
}
static bool ftgmac100_rxdes_udpcs_err(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes1 & cpu_to_le32(FTGMAC100_RXDES1_UDP_CHKSUM_ERR);
}
static bool ftgmac100_rxdes_ipcs_err(struct ftgmac100_rxdes *rxdes)
{
return rxdes->rxdes1 & cpu_to_le32(FTGMAC100_RXDES1_IP_CHKSUM_ERR);
}
/*
* rxdes2 is not used by hardware. We use it to keep track of page.
* Since hardware does not touch it, we can skip cpu_to_le32()/le32_to_cpu().
*/
static void ftgmac100_rxdes_set_page(struct ftgmac100_rxdes *rxdes, struct page *page)
{
rxdes->rxdes2 = (unsigned int)page;
}
static struct page *ftgmac100_rxdes_get_page(struct ftgmac100_rxdes *rxdes)
{
return (struct page *)rxdes->rxdes2;
}
/******************************************************************************
* internal functions (receive)
*****************************************************************************/
static int ftgmac100_next_rx_pointer(int pointer)
{
return (pointer + 1) & (RX_QUEUE_ENTRIES - 1);
}
static void ftgmac100_rx_pointer_advance(struct ftgmac100 *priv)
{
priv->rx_pointer = ftgmac100_next_rx_pointer(priv->rx_pointer);
}
static struct ftgmac100_rxdes *ftgmac100_current_rxdes(struct ftgmac100 *priv)
{
return &priv->descs->rxdes[priv->rx_pointer];
}
static struct ftgmac100_rxdes *
ftgmac100_rx_locate_first_segment(struct ftgmac100 *priv)
{
struct ftgmac100_rxdes *rxdes = ftgmac100_current_rxdes(priv);
while (ftgmac100_rxdes_packet_ready(rxdes)) {
if (ftgmac100_rxdes_first_segment(rxdes))
return rxdes;
ftgmac100_rxdes_set_dma_own(rxdes);
ftgmac100_rx_pointer_advance(priv);
rxdes = ftgmac100_current_rxdes(priv);
}
return NULL;
}
static bool ftgmac100_rx_packet_error(struct ftgmac100 *priv,
struct ftgmac100_rxdes *rxdes)
{
struct net_device *netdev = priv->netdev;
bool error = false;
if (unlikely(ftgmac100_rxdes_rx_error(rxdes))) {
if (net_ratelimit())
netdev_info(netdev, "rx err\n");
netdev->stats.rx_errors++;
error = true;
}
if (unlikely(ftgmac100_rxdes_crc_error(rxdes))) {
if (net_ratelimit())
netdev_info(netdev, "rx crc err\n");
netdev->stats.rx_crc_errors++;
error = true;
} else if (unlikely(ftgmac100_rxdes_ipcs_err(rxdes))) {
if (net_ratelimit())
netdev_info(netdev, "rx IP checksum err\n");
error = true;
}
if (unlikely(ftgmac100_rxdes_frame_too_long(rxdes))) {
if (net_ratelimit())
netdev_info(netdev, "rx frame too long\n");
netdev->stats.rx_length_errors++;
error = true;
} else if (unlikely(ftgmac100_rxdes_runt(rxdes))) {
if (net_ratelimit())
netdev_info(netdev, "rx runt\n");
netdev->stats.rx_length_errors++;
error = true;
} else if (unlikely(ftgmac100_rxdes_odd_nibble(rxdes))) {
if (net_ratelimit())
netdev_info(netdev, "rx odd nibble\n");
netdev->stats.rx_length_errors++;
error = true;
}
return error;
}
static void ftgmac100_rx_drop_packet(struct ftgmac100 *priv)
{
struct net_device *netdev = priv->netdev;
struct ftgmac100_rxdes *rxdes = ftgmac100_current_rxdes(priv);
bool done = false;
if (net_ratelimit())
netdev_dbg(netdev, "drop packet %p\n", rxdes);
do {
if (ftgmac100_rxdes_last_segment(rxdes))
done = true;
ftgmac100_rxdes_set_dma_own(rxdes);
ftgmac100_rx_pointer_advance(priv);
rxdes = ftgmac100_current_rxdes(priv);
} while (!done && ftgmac100_rxdes_packet_ready(rxdes));
netdev->stats.rx_dropped++;
}
static bool ftgmac100_rx_packet(struct ftgmac100 *priv, int *processed)
{
struct net_device *netdev = priv->netdev;
struct ftgmac100_rxdes *rxdes;
struct sk_buff *skb;
bool done = false;
rxdes = ftgmac100_rx_locate_first_segment(priv);
if (!rxdes)
return false;
if (unlikely(ftgmac100_rx_packet_error(priv, rxdes))) {
ftgmac100_rx_drop_packet(priv);
return true;
}
/* start processing */
skb = netdev_alloc_skb_ip_align(netdev, 128);
if (unlikely(!skb)) {
if (net_ratelimit())
netdev_err(netdev, "rx skb alloc failed\n");
ftgmac100_rx_drop_packet(priv);
return true;
}
if (unlikely(ftgmac100_rxdes_multicast(rxdes)))
netdev->stats.multicast++;
/*
* It seems that HW does checksum incorrectly with fragmented packets,
* so we are conservative here - if HW checksum error, let software do
* the checksum again.
*/
if ((ftgmac100_rxdes_is_tcp(rxdes) && !ftgmac100_rxdes_tcpcs_err(rxdes)) ||
(ftgmac100_rxdes_is_udp(rxdes) && !ftgmac100_rxdes_udpcs_err(rxdes)))
skb->ip_summed = CHECKSUM_UNNECESSARY;
do {
dma_addr_t map = ftgmac100_rxdes_get_dma_addr(rxdes);
struct page *page = ftgmac100_rxdes_get_page(rxdes);
unsigned int size;
dma_unmap_page(priv->dev, map, RX_BUF_SIZE, DMA_FROM_DEVICE);
size = ftgmac100_rxdes_data_length(rxdes);
skb_fill_page_desc(skb, skb_shinfo(skb)->nr_frags, page, 0, size);
skb->len += size;
skb->data_len += size;
skb->truesize += PAGE_SIZE;
if (ftgmac100_rxdes_last_segment(rxdes))
done = true;
ftgmac100_alloc_rx_page(priv, rxdes, GFP_ATOMIC);
ftgmac100_rx_pointer_advance(priv);
rxdes = ftgmac100_current_rxdes(priv);
} while (!done);
if (skb->len <= 64)
skb->truesize -= PAGE_SIZE;
__pskb_pull_tail(skb, min(skb->len, 64U));
skb->protocol = eth_type_trans(skb, netdev);
netdev->stats.rx_packets++;
netdev->stats.rx_bytes += skb->len;
/* push packet to protocol stack */
napi_gro_receive(&priv->napi, skb);
(*processed)++;
return true;
}
/******************************************************************************
* internal functions (transmit descriptor)
*****************************************************************************/
static void ftgmac100_txdes_reset(struct ftgmac100_txdes *txdes)
{
/* clear all except end of ring bit */
txdes->txdes0 &= cpu_to_le32(FTGMAC100_TXDES0_EDOTR);
txdes->txdes1 = 0;
txdes->txdes2 = 0;
txdes->txdes3 = 0;
}
static bool ftgmac100_txdes_owned_by_dma(struct ftgmac100_txdes *txdes)
{
return txdes->txdes0 & cpu_to_le32(FTGMAC100_TXDES0_TXDMA_OWN);
}
static void ftgmac100_txdes_set_dma_own(struct ftgmac100_txdes *txdes)
{
/*
* Make sure dma own bit will not be set before any other
* descriptor fields.
*/
wmb();
txdes->txdes0 |= cpu_to_le32(FTGMAC100_TXDES0_TXDMA_OWN);
}
static void ftgmac100_txdes_set_end_of_ring(struct ftgmac100_txdes *txdes)
{
txdes->txdes0 |= cpu_to_le32(FTGMAC100_TXDES0_EDOTR);
}
static void ftgmac100_txdes_set_first_segment(struct ftgmac100_txdes *txdes)
{
txdes->txdes0 |= cpu_to_le32(FTGMAC100_TXDES0_FTS);
}
static void ftgmac100_txdes_set_last_segment(struct ftgmac100_txdes *txdes)
{
txdes->txdes0 |= cpu_to_le32(FTGMAC100_TXDES0_LTS);
}
static void ftgmac100_txdes_set_buffer_size(struct ftgmac100_txdes *txdes,
unsigned int len)
{
txdes->txdes0 |= cpu_to_le32(FTGMAC100_TXDES0_TXBUF_SIZE(len));
}
static void ftgmac100_txdes_set_txint(struct ftgmac100_txdes *txdes)
{
txdes->txdes1 |= cpu_to_le32(FTGMAC100_TXDES1_TXIC);
}
static void ftgmac100_txdes_set_tcpcs(struct ftgmac100_txdes *txdes)
{
txdes->txdes1 |= cpu_to_le32(FTGMAC100_TXDES1_TCP_CHKSUM);
}
static void ftgmac100_txdes_set_udpcs(struct ftgmac100_txdes *txdes)
{
txdes->txdes1 |= cpu_to_le32(FTGMAC100_TXDES1_UDP_CHKSUM);
}
static void ftgmac100_txdes_set_ipcs(struct ftgmac100_txdes *txdes)
{
txdes->txdes1 |= cpu_to_le32(FTGMAC100_TXDES1_IP_CHKSUM);
}
static void ftgmac100_txdes_set_dma_addr(struct ftgmac100_txdes *txdes,
dma_addr_t addr)
{
txdes->txdes3 = cpu_to_le32(addr);
}
static dma_addr_t ftgmac100_txdes_get_dma_addr(struct ftgmac100_txdes *txdes)
{
return le32_to_cpu(txdes->txdes3);
}
/*
* txdes2 is not used by hardware. We use it to keep track of socket buffer.
* Since hardware does not touch it, we can skip cpu_to_le32()/le32_to_cpu().
*/
static void ftgmac100_txdes_set_skb(struct ftgmac100_txdes *txdes,
struct sk_buff *skb)
{
txdes->txdes2 = (unsigned int)skb;
}
static struct sk_buff *ftgmac100_txdes_get_skb(struct ftgmac100_txdes *txdes)
{
return (struct sk_buff *)txdes->txdes2;
}
/******************************************************************************
* internal functions (transmit)
*****************************************************************************/
static int ftgmac100_next_tx_pointer(int pointer)
{
return (pointer + 1) & (TX_QUEUE_ENTRIES - 1);
}
static void ftgmac100_tx_pointer_advance(struct ftgmac100 *priv)
{
priv->tx_pointer = ftgmac100_next_tx_pointer(priv->tx_pointer);
}
static void ftgmac100_tx_clean_pointer_advance(struct ftgmac100 *priv)
{
priv->tx_clean_pointer = ftgmac100_next_tx_pointer(priv->tx_clean_pointer);
}
static struct ftgmac100_txdes *ftgmac100_current_txdes(struct ftgmac100 *priv)
{
return &priv->descs->txdes[priv->tx_pointer];
}
static struct ftgmac100_txdes *
ftgmac100_current_clean_txdes(struct ftgmac100 *priv)
{
return &priv->descs->txdes[priv->tx_clean_pointer];
}
static bool ftgmac100_tx_complete_packet(struct ftgmac100 *priv)
{
struct net_device *netdev = priv->netdev;
struct ftgmac100_txdes *txdes;
struct sk_buff *skb;
dma_addr_t map;
if (priv->tx_pending == 0)
return false;
txdes = ftgmac100_current_clean_txdes(priv);
if (ftgmac100_txdes_owned_by_dma(txdes))
return false;
skb = ftgmac100_txdes_get_skb(txdes);
map = ftgmac100_txdes_get_dma_addr(txdes);
netdev->stats.tx_packets++;
netdev->stats.tx_bytes += skb->len;
dma_unmap_single(priv->dev, map, skb_headlen(skb), DMA_TO_DEVICE);
dev_kfree_skb(skb);
ftgmac100_txdes_reset(txdes);
ftgmac100_tx_clean_pointer_advance(priv);
spin_lock(&priv->tx_lock);
priv->tx_pending--;
spin_unlock(&priv->tx_lock);
netif_wake_queue(netdev);
return true;
}
static void ftgmac100_tx_complete(struct ftgmac100 *priv)
{
while (ftgmac100_tx_complete_packet(priv))
;
}
static int ftgmac100_xmit(struct ftgmac100 *priv, struct sk_buff *skb,
dma_addr_t map)
{
struct net_device *netdev = priv->netdev;
struct ftgmac100_txdes *txdes;
unsigned int len = (skb->len < ETH_ZLEN) ? ETH_ZLEN : skb->len;
txdes = ftgmac100_current_txdes(priv);
ftgmac100_tx_pointer_advance(priv);
/* setup TX descriptor */
ftgmac100_txdes_set_skb(txdes, skb);
ftgmac100_txdes_set_dma_addr(txdes, map);
ftgmac100_txdes_set_buffer_size(txdes, len);
ftgmac100_txdes_set_first_segment(txdes);
ftgmac100_txdes_set_last_segment(txdes);
ftgmac100_txdes_set_txint(txdes);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
__be16 protocol = skb->protocol;
if (protocol == cpu_to_be16(ETH_P_IP)) {
u8 ip_proto = ip_hdr(skb)->protocol;
ftgmac100_txdes_set_ipcs(txdes);
if (ip_proto == IPPROTO_TCP)
ftgmac100_txdes_set_tcpcs(txdes);
else if (ip_proto == IPPROTO_UDP)
ftgmac100_txdes_set_udpcs(txdes);
}
}
spin_lock(&priv->tx_lock);
priv->tx_pending++;
if (priv->tx_pending == TX_QUEUE_ENTRIES)
netif_stop_queue(netdev);
/* start transmit */
ftgmac100_txdes_set_dma_own(txdes);
spin_unlock(&priv->tx_lock);
ftgmac100_txdma_normal_prio_start_polling(priv);
return NETDEV_TX_OK;
}
/******************************************************************************
* internal functions (buffer)
*****************************************************************************/
static int ftgmac100_alloc_rx_page(struct ftgmac100 *priv,
struct ftgmac100_rxdes *rxdes, gfp_t gfp)
{
struct net_device *netdev = priv->netdev;
struct page *page;
dma_addr_t map;
page = alloc_page(gfp);
if (!page) {
if (net_ratelimit())
netdev_err(netdev, "failed to allocate rx page\n");
return -ENOMEM;
}
map = dma_map_page(priv->dev, page, 0, RX_BUF_SIZE, DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(priv->dev, map))) {
if (net_ratelimit())
netdev_err(netdev, "failed to map rx page\n");
__free_page(page);
return -ENOMEM;
}
ftgmac100_rxdes_set_page(rxdes, page);
ftgmac100_rxdes_set_dma_addr(rxdes, map);
ftgmac100_rxdes_set_dma_own(rxdes);
return 0;
}
static void ftgmac100_free_buffers(struct ftgmac100 *priv)
{
int i;
for (i = 0; i < RX_QUEUE_ENTRIES; i++) {
struct ftgmac100_rxdes *rxdes = &priv->descs->rxdes[i];
struct page *page = ftgmac100_rxdes_get_page(rxdes);
dma_addr_t map = ftgmac100_rxdes_get_dma_addr(rxdes);
if (!page)
continue;
dma_unmap_page(priv->dev, map, RX_BUF_SIZE, DMA_FROM_DEVICE);
__free_page(page);
}
for (i = 0; i < TX_QUEUE_ENTRIES; i++) {
struct ftgmac100_txdes *txdes = &priv->descs->txdes[i];
struct sk_buff *skb = ftgmac100_txdes_get_skb(txdes);
dma_addr_t map = ftgmac100_txdes_get_dma_addr(txdes);
if (!skb)
continue;
dma_unmap_single(priv->dev, map, skb_headlen(skb), DMA_TO_DEVICE);
dev_kfree_skb(skb);
}
dma_free_coherent(priv->dev, sizeof(struct ftgmac100_descs),
priv->descs, priv->descs_dma_addr);
}
static int ftgmac100_alloc_buffers(struct ftgmac100 *priv)
{
int i;
priv->descs = dma_alloc_coherent(priv->dev,
sizeof(struct ftgmac100_descs),
&priv->descs_dma_addr, GFP_KERNEL);
if (!priv->descs)
return -ENOMEM;
memset(priv->descs, 0, sizeof(struct ftgmac100_descs));
/* initialize RX ring */
ftgmac100_rxdes_set_end_of_ring(&priv->descs->rxdes[RX_QUEUE_ENTRIES - 1]);
for (i = 0; i < RX_QUEUE_ENTRIES; i++) {
struct ftgmac100_rxdes *rxdes = &priv->descs->rxdes[i];
if (ftgmac100_alloc_rx_page(priv, rxdes, GFP_KERNEL))
goto err;
}
/* initialize TX ring */
ftgmac100_txdes_set_end_of_ring(&priv->descs->txdes[TX_QUEUE_ENTRIES - 1]);
return 0;
err:
ftgmac100_free_buffers(priv);
return -ENOMEM;
}
/******************************************************************************
* internal functions (mdio)
*****************************************************************************/
static void ftgmac100_adjust_link(struct net_device *netdev)
{
struct ftgmac100 *priv = netdev_priv(netdev);
struct phy_device *phydev = priv->phydev;
int ier;
if (phydev->speed == priv->old_speed)
return;
priv->old_speed = phydev->speed;
ier = ioread32(priv->base + FTGMAC100_OFFSET_IER);
/* disable all interrupts */
iowrite32(0, priv->base + FTGMAC100_OFFSET_IER);
netif_stop_queue(netdev);
ftgmac100_stop_hw(priv);
netif_start_queue(netdev);
ftgmac100_init_hw(priv);
ftgmac100_start_hw(priv, phydev->speed);
/* re-enable interrupts */
iowrite32(ier, priv->base + FTGMAC100_OFFSET_IER);
}
static int ftgmac100_mii_probe(struct ftgmac100 *priv)
{
struct net_device *netdev = priv->netdev;
struct phy_device *phydev = NULL;
int i;
/* search for connect PHY device */
for (i = 0; i < PHY_MAX_ADDR; i++) {
struct phy_device *tmp = priv->mii_bus->phy_map[i];
if (tmp) {
phydev = tmp;
break;
}
}
/* now we are supposed to have a proper phydev, to attach to... */
if (!phydev) {
netdev_info(netdev, "%s: no PHY found\n", netdev->name);
return -ENODEV;
}
phydev = phy_connect(netdev, dev_name(&phydev->dev),
&ftgmac100_adjust_link, 0,
PHY_INTERFACE_MODE_GMII);
if (IS_ERR(phydev)) {
netdev_err(netdev, "%s: Could not attach to PHY\n", netdev->name);
return PTR_ERR(phydev);
}
priv->phydev = phydev;
return 0;
}
/******************************************************************************
* struct mii_bus functions
*****************************************************************************/
static int ftgmac100_mdiobus_read(struct mii_bus *bus, int phy_addr, int regnum)
{
struct net_device *netdev = bus->priv;
struct ftgmac100 *priv = netdev_priv(netdev);
unsigned int phycr;
int i;
phycr = ioread32(priv->base + FTGMAC100_OFFSET_PHYCR);
/* preserve MDC cycle threshold */
phycr &= FTGMAC100_PHYCR_MDC_CYCTHR_MASK;
phycr |= FTGMAC100_PHYCR_PHYAD(phy_addr) |
FTGMAC100_PHYCR_REGAD(regnum) |
FTGMAC100_PHYCR_MIIRD;
iowrite32(phycr, priv->base + FTGMAC100_OFFSET_PHYCR);
for (i = 0; i < 10; i++) {
phycr = ioread32(priv->base + FTGMAC100_OFFSET_PHYCR);
if ((phycr & FTGMAC100_PHYCR_MIIRD) == 0) {
int data;
data = ioread32(priv->base + FTGMAC100_OFFSET_PHYDATA);
return FTGMAC100_PHYDATA_MIIRDATA(data);
}
udelay(100);
}
netdev_err(netdev, "mdio read timed out\n");
return -EIO;
}
static int ftgmac100_mdiobus_write(struct mii_bus *bus, int phy_addr,
int regnum, u16 value)
{
struct net_device *netdev = bus->priv;
struct ftgmac100 *priv = netdev_priv(netdev);
unsigned int phycr;
int data;
int i;
phycr = ioread32(priv->base + FTGMAC100_OFFSET_PHYCR);
/* preserve MDC cycle threshold */
phycr &= FTGMAC100_PHYCR_MDC_CYCTHR_MASK;
phycr |= FTGMAC100_PHYCR_PHYAD(phy_addr) |
FTGMAC100_PHYCR_REGAD(regnum) |
FTGMAC100_PHYCR_MIIWR;
data = FTGMAC100_PHYDATA_MIIWDATA(value);
iowrite32(data, priv->base + FTGMAC100_OFFSET_PHYDATA);
iowrite32(phycr, priv->base + FTGMAC100_OFFSET_PHYCR);
for (i = 0; i < 10; i++) {
phycr = ioread32(priv->base + FTGMAC100_OFFSET_PHYCR);
if ((phycr & FTGMAC100_PHYCR_MIIWR) == 0)
return 0;
udelay(100);
}
netdev_err(netdev, "mdio write timed out\n");
return -EIO;
}
static int ftgmac100_mdiobus_reset(struct mii_bus *bus)
{
return 0;
}
/******************************************************************************
* struct ethtool_ops functions
*****************************************************************************/
static void ftgmac100_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *info)
{
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->bus_info, dev_name(&netdev->dev));
}
static int ftgmac100_get_settings(struct net_device *netdev,
struct ethtool_cmd *cmd)
{
struct ftgmac100 *priv = netdev_priv(netdev);
return phy_ethtool_gset(priv->phydev, cmd);
}
static int ftgmac100_set_settings(struct net_device *netdev,
struct ethtool_cmd *cmd)
{
struct ftgmac100 *priv = netdev_priv(netdev);
return phy_ethtool_sset(priv->phydev, cmd);
}
static const struct ethtool_ops ftgmac100_ethtool_ops = {
.set_settings = ftgmac100_set_settings,
.get_settings = ftgmac100_get_settings,
.get_drvinfo = ftgmac100_get_drvinfo,
.get_link = ethtool_op_get_link,
};
/******************************************************************************
* interrupt handler
*****************************************************************************/
static irqreturn_t ftgmac100_interrupt(int irq, void *dev_id)
{
struct net_device *netdev = dev_id;
struct ftgmac100 *priv = netdev_priv(netdev);
if (likely(netif_running(netdev))) {
/* Disable interrupts for polling */
iowrite32(0, priv->base + FTGMAC100_OFFSET_IER);
napi_schedule(&priv->napi);
}
return IRQ_HANDLED;
}
/******************************************************************************
* struct napi_struct functions
*****************************************************************************/
static int ftgmac100_poll(struct napi_struct *napi, int budget)
{
struct ftgmac100 *priv = container_of(napi, struct ftgmac100, napi);
struct net_device *netdev = priv->netdev;
unsigned int status;
bool completed = true;
int rx = 0;
status = ioread32(priv->base + FTGMAC100_OFFSET_ISR);
iowrite32(status, priv->base + FTGMAC100_OFFSET_ISR);
if (status & (FTGMAC100_INT_RPKT_BUF | FTGMAC100_INT_NO_RXBUF)) {
/*
* FTGMAC100_INT_RPKT_BUF:
* RX DMA has received packets into RX buffer successfully
*
* FTGMAC100_INT_NO_RXBUF:
* RX buffer unavailable
*/
bool retry;
do {
retry = ftgmac100_rx_packet(priv, &rx);
} while (retry && rx < budget);
if (retry && rx == budget)
completed = false;
}
if (status & (FTGMAC100_INT_XPKT_ETH | FTGMAC100_INT_XPKT_LOST)) {
/*
* FTGMAC100_INT_XPKT_ETH:
* packet transmitted to ethernet successfully
*
* FTGMAC100_INT_XPKT_LOST:
* packet transmitted to ethernet lost due to late
* collision or excessive collision
*/
ftgmac100_tx_complete(priv);
}
if (status & (FTGMAC100_INT_NO_RXBUF | FTGMAC100_INT_RPKT_LOST |
FTGMAC100_INT_AHB_ERR | FTGMAC100_INT_PHYSTS_CHG)) {
if (net_ratelimit())
netdev_info(netdev, "[ISR] = 0x%x: %s%s%s%s\n", status,
status & FTGMAC100_INT_NO_RXBUF ? "NO_RXBUF " : "",
status & FTGMAC100_INT_RPKT_LOST ? "RPKT_LOST " : "",
status & FTGMAC100_INT_AHB_ERR ? "AHB_ERR " : "",
status & FTGMAC100_INT_PHYSTS_CHG ? "PHYSTS_CHG" : "");
if (status & FTGMAC100_INT_NO_RXBUF) {
/* RX buffer unavailable */
netdev->stats.rx_over_errors++;
}
if (status & FTGMAC100_INT_RPKT_LOST) {
/* received packet lost due to RX FIFO full */
netdev->stats.rx_fifo_errors++;
}
}
if (completed) {
napi_complete(napi);
/* enable all interrupts */
iowrite32(INT_MASK_ALL_ENABLED, priv->base + FTGMAC100_OFFSET_IER);
}
return rx;
}
/******************************************************************************
* struct net_device_ops functions
*****************************************************************************/
static int ftgmac100_open(struct net_device *netdev)
{
struct ftgmac100 *priv = netdev_priv(netdev);
int err;
err = ftgmac100_alloc_buffers(priv);
if (err) {
netdev_err(netdev, "failed to allocate buffers\n");
goto err_alloc;
}
err = request_irq(priv->irq, ftgmac100_interrupt, 0, netdev->name, netdev);
if (err) {
netdev_err(netdev, "failed to request irq %d\n", priv->irq);
goto err_irq;
}
priv->rx_pointer = 0;
priv->tx_clean_pointer = 0;
priv->tx_pointer = 0;
priv->tx_pending = 0;
err = ftgmac100_reset_hw(priv);
if (err)
goto err_hw;
ftgmac100_init_hw(priv);
ftgmac100_start_hw(priv, 10);
phy_start(priv->phydev);
napi_enable(&priv->napi);
netif_start_queue(netdev);
/* enable all interrupts */
iowrite32(INT_MASK_ALL_ENABLED, priv->base + FTGMAC100_OFFSET_IER);
return 0;
err_hw:
free_irq(priv->irq, netdev);
err_irq:
ftgmac100_free_buffers(priv);
err_alloc:
return err;
}
static int ftgmac100_stop(struct net_device *netdev)
{
struct ftgmac100 *priv = netdev_priv(netdev);
/* disable all interrupts */
iowrite32(0, priv->base + FTGMAC100_OFFSET_IER);
netif_stop_queue(netdev);
napi_disable(&priv->napi);
phy_stop(priv->phydev);
ftgmac100_stop_hw(priv);
free_irq(priv->irq, netdev);
ftgmac100_free_buffers(priv);
return 0;
}
static int ftgmac100_hard_start_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
struct ftgmac100 *priv = netdev_priv(netdev);
dma_addr_t map;
if (unlikely(skb->len > MAX_PKT_SIZE)) {
if (net_ratelimit())
netdev_dbg(netdev, "tx packet too big\n");
netdev->stats.tx_dropped++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
map = dma_map_single(priv->dev, skb->data, skb_headlen(skb), DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(priv->dev, map))) {
/* drop packet */
if (net_ratelimit())
netdev_err(netdev, "map socket buffer failed\n");
netdev->stats.tx_dropped++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
return ftgmac100_xmit(priv, skb, map);
}
/* optional */
static int ftgmac100_do_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct ftgmac100 *priv = netdev_priv(netdev);
return phy_mii_ioctl(priv->phydev, ifr, cmd);
}
static const struct net_device_ops ftgmac100_netdev_ops = {
.ndo_open = ftgmac100_open,
.ndo_stop = ftgmac100_stop,
.ndo_start_xmit = ftgmac100_hard_start_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_do_ioctl = ftgmac100_do_ioctl,
};
/******************************************************************************
* struct platform_driver functions
*****************************************************************************/
static int ftgmac100_probe(struct platform_device *pdev)
{
struct resource *res;
int irq;
struct net_device *netdev;
struct ftgmac100 *priv;
int err;
int i;
if (!pdev)
return -ENODEV;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENXIO;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
/* setup net_device */
netdev = alloc_etherdev(sizeof(*priv));
if (!netdev) {
err = -ENOMEM;
goto err_alloc_etherdev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
SET_ETHTOOL_OPS(netdev, &ftgmac100_ethtool_ops);
netdev->netdev_ops = &ftgmac100_netdev_ops;
netdev->features = NETIF_F_IP_CSUM | NETIF_F_GRO;
platform_set_drvdata(pdev, netdev);
/* setup private data */
priv = netdev_priv(netdev);
priv->netdev = netdev;
priv->dev = &pdev->dev;
spin_lock_init(&priv->tx_lock);
/* initialize NAPI */
netif_napi_add(netdev, &priv->napi, ftgmac100_poll, 64);
/* map io memory */
priv->res = request_mem_region(res->start, resource_size(res),
dev_name(&pdev->dev));
if (!priv->res) {
dev_err(&pdev->dev, "Could not reserve memory region\n");
err = -ENOMEM;
goto err_req_mem;
}
priv->base = ioremap(res->start, resource_size(res));
if (!priv->base) {
dev_err(&pdev->dev, "Failed to ioremap ethernet registers\n");
err = -EIO;
goto err_ioremap;
}
priv->irq = irq;
/* initialize mdio bus */
priv->mii_bus = mdiobus_alloc();
if (!priv->mii_bus) {
err = -EIO;
goto err_alloc_mdiobus;
}
priv->mii_bus->name = "ftgmac100_mdio";
snprintf(priv->mii_bus->id, MII_BUS_ID_SIZE, "ftgmac100_mii");
priv->mii_bus->priv = netdev;
priv->mii_bus->read = ftgmac100_mdiobus_read;
priv->mii_bus->write = ftgmac100_mdiobus_write;
priv->mii_bus->reset = ftgmac100_mdiobus_reset;
priv->mii_bus->irq = priv->phy_irq;
for (i = 0; i < PHY_MAX_ADDR; i++)
priv->mii_bus->irq[i] = PHY_POLL;
err = mdiobus_register(priv->mii_bus);
if (err) {
dev_err(&pdev->dev, "Cannot register MDIO bus!\n");
goto err_register_mdiobus;
}
err = ftgmac100_mii_probe(priv);
if (err) {
dev_err(&pdev->dev, "MII Probe failed!\n");
goto err_mii_probe;
}
/* register network device */
err = register_netdev(netdev);
if (err) {
dev_err(&pdev->dev, "Failed to register netdev\n");
goto err_register_netdev;
}
netdev_info(netdev, "irq %d, mapped at %p\n", priv->irq, priv->base);
if (!is_valid_ether_addr(netdev->dev_addr)) {
eth_hw_addr_random(netdev);
netdev_info(netdev, "generated random MAC address %pM\n",
netdev->dev_addr);
}
return 0;
err_register_netdev:
phy_disconnect(priv->phydev);
err_mii_probe:
mdiobus_unregister(priv->mii_bus);
err_register_mdiobus:
mdiobus_free(priv->mii_bus);
err_alloc_mdiobus:
iounmap(priv->base);
err_ioremap:
release_resource(priv->res);
err_req_mem:
netif_napi_del(&priv->napi);
platform_set_drvdata(pdev, NULL);
free_netdev(netdev);
err_alloc_etherdev:
return err;
}
static int __exit ftgmac100_remove(struct platform_device *pdev)
{
struct net_device *netdev;
struct ftgmac100 *priv;
netdev = platform_get_drvdata(pdev);
priv = netdev_priv(netdev);
unregister_netdev(netdev);
phy_disconnect(priv->phydev);
mdiobus_unregister(priv->mii_bus);
mdiobus_free(priv->mii_bus);
iounmap(priv->base);
release_resource(priv->res);
netif_napi_del(&priv->napi);
platform_set_drvdata(pdev, NULL);
free_netdev(netdev);
return 0;
}
static struct platform_driver ftgmac100_driver = {
.probe = ftgmac100_probe,
.remove = __exit_p(ftgmac100_remove),
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
};
/******************************************************************************
* initialization / finalization
*****************************************************************************/
static int __init ftgmac100_init(void)
{
pr_info("Loading version " DRV_VERSION " ...\n");
return platform_driver_register(&ftgmac100_driver);
}
static void __exit ftgmac100_exit(void)
{
platform_driver_unregister(&ftgmac100_driver);
}
module_init(ftgmac100_init);
module_exit(ftgmac100_exit);
MODULE_AUTHOR("Po-Yu Chuang <ratbert@faraday-tech.com>");
MODULE_DESCRIPTION("FTGMAC100 driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
pressy4pie/kernel_lge_f6mt | arch/arm/mach-omap2/clock2xxx.c | 4860 | 1567 | /*
* clock2xxx.c - OMAP2xxx-specific clock integration code
*
* Copyright (C) 2005-2008 Texas Instruments, Inc.
* Copyright (C) 2004-2010 Nokia Corporation
*
* Contacts:
* Richard Woodruff <r-woodruff2@ti.com>
* Paul Walmsley
*
* Based on earlier work by Tuukka Tikkanen, Tony Lindgren,
* Gordon McNutt and RidgeRun, 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/cpu.h>
#include <plat/clock.h>
#include "clock.h"
#include "clock2xxx.h"
#include "cm.h"
#include "cm-regbits-24xx.h"
struct clk *vclk, *sclk, *dclk;
/*
* Omap24xx specific clock functions
*/
/*
* Set clocks for bypass mode for reboot to work.
*/
void omap2xxx_clk_prepare_for_reboot(void)
{
u32 rate;
if (vclk == NULL || sclk == NULL)
return;
rate = clk_get_rate(sclk);
clk_set_rate(vclk, rate);
}
/*
* Switch the MPU rate if specified on cmdline. We cannot do this
* early until cmdline is parsed. XXX This should be removed from the
* clock code and handled by the OPP layer code in the near future.
*/
static int __init omap2xxx_clk_arch_init(void)
{
int ret;
if (!cpu_is_omap24xx())
return 0;
ret = omap2_clk_switch_mpurate_at_boot("virt_prcm_set");
if (!ret)
omap2_clk_print_new_rates("sys_ck", "dpll_ck", "mpu_ck");
return ret;
}
arch_initcall(omap2xxx_clk_arch_init);
| gpl-2.0 |
DooMLoRD/android_kernel_sony_msm8960t_aosp | drivers/net/ethernet/mellanox/mlx4/en_ethtool.c | 4860 | 17310 | /*
* Copyright (c) 2007 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/kernel.h>
#include <linux/ethtool.h>
#include <linux/netdevice.h>
#include "mlx4_en.h"
#include "en_port.h"
static void
mlx4_en_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *drvinfo)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
struct mlx4_en_dev *mdev = priv->mdev;
strlcpy(drvinfo->driver, DRV_NAME, sizeof(drvinfo->driver));
strlcpy(drvinfo->version, DRV_VERSION " (" DRV_RELDATE ")",
sizeof(drvinfo->version));
snprintf(drvinfo->fw_version, sizeof(drvinfo->fw_version),
"%d.%d.%d",
(u16) (mdev->dev->caps.fw_ver >> 32),
(u16) ((mdev->dev->caps.fw_ver >> 16) & 0xffff),
(u16) (mdev->dev->caps.fw_ver & 0xffff));
strlcpy(drvinfo->bus_info, pci_name(mdev->dev->pdev),
sizeof(drvinfo->bus_info));
drvinfo->n_stats = 0;
drvinfo->regdump_len = 0;
drvinfo->eedump_len = 0;
}
static const char main_strings[][ETH_GSTRING_LEN] = {
"rx_packets", "tx_packets", "rx_bytes", "tx_bytes", "rx_errors",
"tx_errors", "rx_dropped", "tx_dropped", "multicast", "collisions",
"rx_length_errors", "rx_over_errors", "rx_crc_errors",
"rx_frame_errors", "rx_fifo_errors", "rx_missed_errors",
"tx_aborted_errors", "tx_carrier_errors", "tx_fifo_errors",
"tx_heartbeat_errors", "tx_window_errors",
/* port statistics */
"tso_packets",
"queue_stopped", "wake_queue", "tx_timeout", "rx_alloc_failed",
"rx_csum_good", "rx_csum_none", "tx_chksum_offload",
/* packet statistics */
"broadcast", "rx_prio_0", "rx_prio_1", "rx_prio_2", "rx_prio_3",
"rx_prio_4", "rx_prio_5", "rx_prio_6", "rx_prio_7", "tx_prio_0",
"tx_prio_1", "tx_prio_2", "tx_prio_3", "tx_prio_4", "tx_prio_5",
"tx_prio_6", "tx_prio_7",
};
#define NUM_MAIN_STATS 21
#define NUM_ALL_STATS (NUM_MAIN_STATS + NUM_PORT_STATS + NUM_PKT_STATS + NUM_PERF_STATS)
static const char mlx4_en_test_names[][ETH_GSTRING_LEN]= {
"Interupt Test",
"Link Test",
"Speed Test",
"Register Test",
"Loopback Test",
};
static u32 mlx4_en_get_msglevel(struct net_device *dev)
{
return ((struct mlx4_en_priv *) netdev_priv(dev))->msg_enable;
}
static void mlx4_en_set_msglevel(struct net_device *dev, u32 val)
{
((struct mlx4_en_priv *) netdev_priv(dev))->msg_enable = val;
}
static void mlx4_en_get_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
struct mlx4_en_priv *priv = netdev_priv(netdev);
int err = 0;
u64 config = 0;
u64 mask;
if ((priv->port < 1) || (priv->port > 2)) {
en_err(priv, "Failed to get WoL information\n");
return;
}
mask = (priv->port == 1) ? MLX4_DEV_CAP_FLAG_WOL_PORT1 :
MLX4_DEV_CAP_FLAG_WOL_PORT2;
if (!(priv->mdev->dev->caps.flags & mask)) {
wol->supported = 0;
wol->wolopts = 0;
return;
}
err = mlx4_wol_read(priv->mdev->dev, &config, priv->port);
if (err) {
en_err(priv, "Failed to get WoL information\n");
return;
}
if (config & MLX4_EN_WOL_MAGIC)
wol->supported = WAKE_MAGIC;
else
wol->supported = 0;
if (config & MLX4_EN_WOL_ENABLED)
wol->wolopts = WAKE_MAGIC;
else
wol->wolopts = 0;
}
static int mlx4_en_set_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
struct mlx4_en_priv *priv = netdev_priv(netdev);
u64 config = 0;
int err = 0;
u64 mask;
if ((priv->port < 1) || (priv->port > 2))
return -EOPNOTSUPP;
mask = (priv->port == 1) ? MLX4_DEV_CAP_FLAG_WOL_PORT1 :
MLX4_DEV_CAP_FLAG_WOL_PORT2;
if (!(priv->mdev->dev->caps.flags & mask))
return -EOPNOTSUPP;
if (wol->supported & ~WAKE_MAGIC)
return -EINVAL;
err = mlx4_wol_read(priv->mdev->dev, &config, priv->port);
if (err) {
en_err(priv, "Failed to get WoL info, unable to modify\n");
return err;
}
if (wol->wolopts & WAKE_MAGIC) {
config |= MLX4_EN_WOL_DO_MODIFY | MLX4_EN_WOL_ENABLED |
MLX4_EN_WOL_MAGIC;
} else {
config &= ~(MLX4_EN_WOL_ENABLED | MLX4_EN_WOL_MAGIC);
config |= MLX4_EN_WOL_DO_MODIFY;
}
err = mlx4_wol_write(priv->mdev->dev, config, priv->port);
if (err)
en_err(priv, "Failed to set WoL information\n");
return err;
}
static int mlx4_en_get_sset_count(struct net_device *dev, int sset)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
int bit_count = hweight64(priv->stats_bitmap);
switch (sset) {
case ETH_SS_STATS:
return (priv->stats_bitmap ? bit_count : NUM_ALL_STATS) +
(priv->tx_ring_num + priv->rx_ring_num) * 2;
case ETH_SS_TEST:
return MLX4_EN_NUM_SELF_TEST - !(priv->mdev->dev->caps.flags
& MLX4_DEV_CAP_FLAG_UC_LOOPBACK) * 2;
default:
return -EOPNOTSUPP;
}
}
static void mlx4_en_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, uint64_t *data)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
int index = 0;
int i, j = 0;
spin_lock_bh(&priv->stats_lock);
if (!(priv->stats_bitmap)) {
for (i = 0; i < NUM_MAIN_STATS; i++)
data[index++] =
((unsigned long *) &priv->stats)[i];
for (i = 0; i < NUM_PORT_STATS; i++)
data[index++] =
((unsigned long *) &priv->port_stats)[i];
for (i = 0; i < NUM_PKT_STATS; i++)
data[index++] =
((unsigned long *) &priv->pkstats)[i];
} else {
for (i = 0; i < NUM_MAIN_STATS; i++) {
if ((priv->stats_bitmap >> j) & 1)
data[index++] =
((unsigned long *) &priv->stats)[i];
j++;
}
for (i = 0; i < NUM_PORT_STATS; i++) {
if ((priv->stats_bitmap >> j) & 1)
data[index++] =
((unsigned long *) &priv->port_stats)[i];
j++;
}
}
for (i = 0; i < priv->tx_ring_num; i++) {
data[index++] = priv->tx_ring[i].packets;
data[index++] = priv->tx_ring[i].bytes;
}
for (i = 0; i < priv->rx_ring_num; i++) {
data[index++] = priv->rx_ring[i].packets;
data[index++] = priv->rx_ring[i].bytes;
}
spin_unlock_bh(&priv->stats_lock);
}
static void mlx4_en_self_test(struct net_device *dev,
struct ethtool_test *etest, u64 *buf)
{
mlx4_en_ex_selftest(dev, &etest->flags, buf);
}
static void mlx4_en_get_strings(struct net_device *dev,
uint32_t stringset, uint8_t *data)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
int index = 0;
int i;
switch (stringset) {
case ETH_SS_TEST:
for (i = 0; i < MLX4_EN_NUM_SELF_TEST - 2; i++)
strcpy(data + i * ETH_GSTRING_LEN, mlx4_en_test_names[i]);
if (priv->mdev->dev->caps.flags & MLX4_DEV_CAP_FLAG_UC_LOOPBACK)
for (; i < MLX4_EN_NUM_SELF_TEST; i++)
strcpy(data + i * ETH_GSTRING_LEN, mlx4_en_test_names[i]);
break;
case ETH_SS_STATS:
/* Add main counters */
if (!priv->stats_bitmap) {
for (i = 0; i < NUM_MAIN_STATS; i++)
strcpy(data + (index++) * ETH_GSTRING_LEN,
main_strings[i]);
for (i = 0; i < NUM_PORT_STATS; i++)
strcpy(data + (index++) * ETH_GSTRING_LEN,
main_strings[i +
NUM_MAIN_STATS]);
for (i = 0; i < NUM_PKT_STATS; i++)
strcpy(data + (index++) * ETH_GSTRING_LEN,
main_strings[i +
NUM_MAIN_STATS +
NUM_PORT_STATS]);
} else
for (i = 0; i < NUM_MAIN_STATS + NUM_PORT_STATS; i++) {
if ((priv->stats_bitmap >> i) & 1) {
strcpy(data +
(index++) * ETH_GSTRING_LEN,
main_strings[i]);
}
if (!(priv->stats_bitmap >> i))
break;
}
for (i = 0; i < priv->tx_ring_num; i++) {
sprintf(data + (index++) * ETH_GSTRING_LEN,
"tx%d_packets", i);
sprintf(data + (index++) * ETH_GSTRING_LEN,
"tx%d_bytes", i);
}
for (i = 0; i < priv->rx_ring_num; i++) {
sprintf(data + (index++) * ETH_GSTRING_LEN,
"rx%d_packets", i);
sprintf(data + (index++) * ETH_GSTRING_LEN,
"rx%d_bytes", i);
}
break;
}
}
static int mlx4_en_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
int trans_type;
cmd->autoneg = AUTONEG_DISABLE;
cmd->supported = SUPPORTED_10000baseT_Full;
cmd->advertising = ADVERTISED_10000baseT_Full;
if (mlx4_en_QUERY_PORT(priv->mdev, priv->port))
return -ENOMEM;
trans_type = priv->port_state.transciver;
if (netif_carrier_ok(dev)) {
ethtool_cmd_speed_set(cmd, priv->port_state.link_speed);
cmd->duplex = DUPLEX_FULL;
} else {
ethtool_cmd_speed_set(cmd, -1);
cmd->duplex = -1;
}
if (trans_type > 0 && trans_type <= 0xC) {
cmd->port = PORT_FIBRE;
cmd->transceiver = XCVR_EXTERNAL;
cmd->supported |= SUPPORTED_FIBRE;
cmd->advertising |= ADVERTISED_FIBRE;
} else if (trans_type == 0x80 || trans_type == 0) {
cmd->port = PORT_TP;
cmd->transceiver = XCVR_INTERNAL;
cmd->supported |= SUPPORTED_TP;
cmd->advertising |= ADVERTISED_TP;
} else {
cmd->port = -1;
cmd->transceiver = -1;
}
return 0;
}
static int mlx4_en_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
if ((cmd->autoneg == AUTONEG_ENABLE) ||
(ethtool_cmd_speed(cmd) != SPEED_10000) ||
(cmd->duplex != DUPLEX_FULL))
return -EINVAL;
/* Nothing to change */
return 0;
}
static int mlx4_en_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *coal)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
coal->tx_coalesce_usecs = 0;
coal->tx_max_coalesced_frames = 0;
coal->rx_coalesce_usecs = priv->rx_usecs;
coal->rx_max_coalesced_frames = priv->rx_frames;
coal->pkt_rate_low = priv->pkt_rate_low;
coal->rx_coalesce_usecs_low = priv->rx_usecs_low;
coal->pkt_rate_high = priv->pkt_rate_high;
coal->rx_coalesce_usecs_high = priv->rx_usecs_high;
coal->rate_sample_interval = priv->sample_interval;
coal->use_adaptive_rx_coalesce = priv->adaptive_rx_coal;
return 0;
}
static int mlx4_en_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *coal)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
int err, i;
priv->rx_frames = (coal->rx_max_coalesced_frames ==
MLX4_EN_AUTO_CONF) ?
MLX4_EN_RX_COAL_TARGET :
coal->rx_max_coalesced_frames;
priv->rx_usecs = (coal->rx_coalesce_usecs ==
MLX4_EN_AUTO_CONF) ?
MLX4_EN_RX_COAL_TIME :
coal->rx_coalesce_usecs;
/* Set adaptive coalescing params */
priv->pkt_rate_low = coal->pkt_rate_low;
priv->rx_usecs_low = coal->rx_coalesce_usecs_low;
priv->pkt_rate_high = coal->pkt_rate_high;
priv->rx_usecs_high = coal->rx_coalesce_usecs_high;
priv->sample_interval = coal->rate_sample_interval;
priv->adaptive_rx_coal = coal->use_adaptive_rx_coalesce;
if (priv->adaptive_rx_coal)
return 0;
for (i = 0; i < priv->rx_ring_num; i++) {
priv->rx_cq[i].moder_cnt = priv->rx_frames;
priv->rx_cq[i].moder_time = priv->rx_usecs;
priv->last_moder_time[i] = MLX4_EN_AUTO_CONF;
err = mlx4_en_set_cq_moder(priv, &priv->rx_cq[i]);
if (err)
return err;
}
return 0;
}
static int mlx4_en_set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *pause)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
struct mlx4_en_dev *mdev = priv->mdev;
int err;
priv->prof->tx_pause = pause->tx_pause != 0;
priv->prof->rx_pause = pause->rx_pause != 0;
err = mlx4_SET_PORT_general(mdev->dev, priv->port,
priv->rx_skb_size + ETH_FCS_LEN,
priv->prof->tx_pause,
priv->prof->tx_ppp,
priv->prof->rx_pause,
priv->prof->rx_ppp);
if (err)
en_err(priv, "Failed setting pause params\n");
return err;
}
static void mlx4_en_get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *pause)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
pause->tx_pause = priv->prof->tx_pause;
pause->rx_pause = priv->prof->rx_pause;
}
static int mlx4_en_set_ringparam(struct net_device *dev,
struct ethtool_ringparam *param)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
struct mlx4_en_dev *mdev = priv->mdev;
u32 rx_size, tx_size;
int port_up = 0;
int err = 0;
int i;
if (param->rx_jumbo_pending || param->rx_mini_pending)
return -EINVAL;
rx_size = roundup_pow_of_two(param->rx_pending);
rx_size = max_t(u32, rx_size, MLX4_EN_MIN_RX_SIZE);
rx_size = min_t(u32, rx_size, MLX4_EN_MAX_RX_SIZE);
tx_size = roundup_pow_of_two(param->tx_pending);
tx_size = max_t(u32, tx_size, MLX4_EN_MIN_TX_SIZE);
tx_size = min_t(u32, tx_size, MLX4_EN_MAX_TX_SIZE);
if (rx_size == (priv->port_up ? priv->rx_ring[0].actual_size :
priv->rx_ring[0].size) &&
tx_size == priv->tx_ring[0].size)
return 0;
mutex_lock(&mdev->state_lock);
if (priv->port_up) {
port_up = 1;
mlx4_en_stop_port(dev);
}
mlx4_en_free_resources(priv);
priv->prof->tx_ring_size = tx_size;
priv->prof->rx_ring_size = rx_size;
err = mlx4_en_alloc_resources(priv);
if (err) {
en_err(priv, "Failed reallocating port resources\n");
goto out;
}
if (port_up) {
err = mlx4_en_start_port(dev);
if (err)
en_err(priv, "Failed starting port\n");
}
for (i = 0; i < priv->rx_ring_num; i++) {
priv->rx_cq[i].moder_cnt = priv->rx_frames;
priv->rx_cq[i].moder_time = priv->rx_usecs;
priv->last_moder_time[i] = MLX4_EN_AUTO_CONF;
err = mlx4_en_set_cq_moder(priv, &priv->rx_cq[i]);
if (err)
goto out;
}
out:
mutex_unlock(&mdev->state_lock);
return err;
}
static void mlx4_en_get_ringparam(struct net_device *dev,
struct ethtool_ringparam *param)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
memset(param, 0, sizeof(*param));
param->rx_max_pending = MLX4_EN_MAX_RX_SIZE;
param->tx_max_pending = MLX4_EN_MAX_TX_SIZE;
param->rx_pending = priv->port_up ?
priv->rx_ring[0].actual_size : priv->rx_ring[0].size;
param->tx_pending = priv->tx_ring[0].size;
}
static u32 mlx4_en_get_rxfh_indir_size(struct net_device *dev)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
return priv->rx_ring_num;
}
static int mlx4_en_get_rxfh_indir(struct net_device *dev, u32 *ring_index)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
struct mlx4_en_rss_map *rss_map = &priv->rss_map;
int rss_rings;
size_t n = priv->rx_ring_num;
int err = 0;
rss_rings = priv->prof->rss_rings ?: priv->rx_ring_num;
while (n--) {
ring_index[n] = rss_map->qps[n % rss_rings].qpn -
rss_map->base_qpn;
}
return err;
}
static int mlx4_en_set_rxfh_indir(struct net_device *dev,
const u32 *ring_index)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
struct mlx4_en_dev *mdev = priv->mdev;
int port_up = 0;
int err = 0;
int i;
int rss_rings = 0;
/* Calculate RSS table size and make sure flows are spread evenly
* between rings
*/
for (i = 0; i < priv->rx_ring_num; i++) {
if (i > 0 && !ring_index[i] && !rss_rings)
rss_rings = i;
if (ring_index[i] != (i % (rss_rings ?: priv->rx_ring_num)))
return -EINVAL;
}
if (!rss_rings)
rss_rings = priv->rx_ring_num;
/* RSS table size must be an order of 2 */
if (!is_power_of_2(rss_rings))
return -EINVAL;
mutex_lock(&mdev->state_lock);
if (priv->port_up) {
port_up = 1;
mlx4_en_stop_port(dev);
}
priv->prof->rss_rings = rss_rings;
if (port_up) {
err = mlx4_en_start_port(dev);
if (err)
en_err(priv, "Failed starting port\n");
}
mutex_unlock(&mdev->state_lock);
return err;
}
static int mlx4_en_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *cmd,
u32 *rule_locs)
{
struct mlx4_en_priv *priv = netdev_priv(dev);
int err = 0;
switch (cmd->cmd) {
case ETHTOOL_GRXRINGS:
cmd->data = priv->rx_ring_num;
break;
default:
err = -EOPNOTSUPP;
break;
}
return err;
}
const struct ethtool_ops mlx4_en_ethtool_ops = {
.get_drvinfo = mlx4_en_get_drvinfo,
.get_settings = mlx4_en_get_settings,
.set_settings = mlx4_en_set_settings,
.get_link = ethtool_op_get_link,
.get_strings = mlx4_en_get_strings,
.get_sset_count = mlx4_en_get_sset_count,
.get_ethtool_stats = mlx4_en_get_ethtool_stats,
.self_test = mlx4_en_self_test,
.get_wol = mlx4_en_get_wol,
.set_wol = mlx4_en_set_wol,
.get_msglevel = mlx4_en_get_msglevel,
.set_msglevel = mlx4_en_set_msglevel,
.get_coalesce = mlx4_en_get_coalesce,
.set_coalesce = mlx4_en_set_coalesce,
.get_pauseparam = mlx4_en_get_pauseparam,
.set_pauseparam = mlx4_en_set_pauseparam,
.get_ringparam = mlx4_en_get_ringparam,
.set_ringparam = mlx4_en_set_ringparam,
.get_rxnfc = mlx4_en_get_rxnfc,
.get_rxfh_indir_size = mlx4_en_get_rxfh_indir_size,
.get_rxfh_indir = mlx4_en_get_rxfh_indir,
.set_rxfh_indir = mlx4_en_set_rxfh_indir,
};
| gpl-2.0 |
MoKee/android_kernel_lge_hammerheadcaf | drivers/input/mouse/synaptics_usb.c | 4860 | 14807 | /*
* USB Synaptics device driver
*
* Copyright (c) 2002 Rob Miller (rob@inpharmatica . co . uk)
* Copyright (c) 2003 Ron Lee (ron@debian.org)
* cPad driver for kernel 2.4
*
* Copyright (c) 2004 Jan Steinhoff (cpad@jan-steinhoff . de)
* Copyright (c) 2004 Ron Lee (ron@debian.org)
* rewritten for kernel 2.6
*
* cPad display character device part is not included. It can be found at
* http://jan-steinhoff.de/linux/synaptics-usb.html
*
* Bases on: usb_skeleton.c v2.2 by Greg Kroah-Hartman
* drivers/hid/usbhid/usbmouse.c by Vojtech Pavlik
* drivers/input/mouse/synaptics.c by Peter Osterlund
*
* 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.
*
* Trademarks are the property of their respective owners.
*/
/*
* There are three different types of Synaptics USB devices: Touchpads,
* touchsticks (or trackpoints), and touchscreens. Touchpads are well supported
* by this driver, touchstick support has not been tested much yet, and
* touchscreens have not been tested at all.
*
* Up to three alternate settings are possible:
* setting 0: one int endpoint for relative movement (used by usbhid.ko)
* setting 1: one int endpoint for absolute finger position
* setting 2 (cPad only): one int endpoint for absolute finger position and
* two bulk endpoints for the display (in/out)
* This driver uses setting 1.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/usb.h>
#include <linux/input.h>
#include <linux/usb/input.h>
#define USB_VENDOR_ID_SYNAPTICS 0x06cb
#define USB_DEVICE_ID_SYNAPTICS_TP 0x0001 /* Synaptics USB TouchPad */
#define USB_DEVICE_ID_SYNAPTICS_INT_TP 0x0002 /* Integrated USB TouchPad */
#define USB_DEVICE_ID_SYNAPTICS_CPAD 0x0003 /* Synaptics cPad */
#define USB_DEVICE_ID_SYNAPTICS_TS 0x0006 /* Synaptics TouchScreen */
#define USB_DEVICE_ID_SYNAPTICS_STICK 0x0007 /* Synaptics USB Styk */
#define USB_DEVICE_ID_SYNAPTICS_WP 0x0008 /* Synaptics USB WheelPad */
#define USB_DEVICE_ID_SYNAPTICS_COMP_TP 0x0009 /* Composite USB TouchPad */
#define USB_DEVICE_ID_SYNAPTICS_WTP 0x0010 /* Wireless TouchPad */
#define USB_DEVICE_ID_SYNAPTICS_DPAD 0x0013 /* DisplayPad */
#define SYNUSB_TOUCHPAD (1 << 0)
#define SYNUSB_STICK (1 << 1)
#define SYNUSB_TOUCHSCREEN (1 << 2)
#define SYNUSB_AUXDISPLAY (1 << 3) /* For cPad */
#define SYNUSB_COMBO (1 << 4) /* Composite device (TP + stick) */
#define SYNUSB_IO_ALWAYS (1 << 5)
#define USB_DEVICE_SYNAPTICS(prod, kind) \
USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, \
USB_DEVICE_ID_SYNAPTICS_##prod), \
.driver_info = (kind),
#define SYNUSB_RECV_SIZE 8
#define XMIN_NOMINAL 1472
#define XMAX_NOMINAL 5472
#define YMIN_NOMINAL 1408
#define YMAX_NOMINAL 4448
struct synusb {
struct usb_device *udev;
struct usb_interface *intf;
struct urb *urb;
unsigned char *data;
/* input device related data structures */
struct input_dev *input;
char name[128];
char phys[64];
/* characteristics of the device */
unsigned long flags;
};
static void synusb_report_buttons(struct synusb *synusb)
{
struct input_dev *input_dev = synusb->input;
input_report_key(input_dev, BTN_LEFT, synusb->data[1] & 0x04);
input_report_key(input_dev, BTN_RIGHT, synusb->data[1] & 0x01);
input_report_key(input_dev, BTN_MIDDLE, synusb->data[1] & 0x02);
}
static void synusb_report_stick(struct synusb *synusb)
{
struct input_dev *input_dev = synusb->input;
int x, y;
unsigned int pressure;
pressure = synusb->data[6];
x = (s16)(be16_to_cpup((__be16 *)&synusb->data[2]) << 3) >> 7;
y = (s16)(be16_to_cpup((__be16 *)&synusb->data[4]) << 3) >> 7;
if (pressure > 0) {
input_report_rel(input_dev, REL_X, x);
input_report_rel(input_dev, REL_Y, -y);
}
input_report_abs(input_dev, ABS_PRESSURE, pressure);
synusb_report_buttons(synusb);
input_sync(input_dev);
}
static void synusb_report_touchpad(struct synusb *synusb)
{
struct input_dev *input_dev = synusb->input;
unsigned int num_fingers, tool_width;
unsigned int x, y;
unsigned int pressure, w;
pressure = synusb->data[6];
x = be16_to_cpup((__be16 *)&synusb->data[2]);
y = be16_to_cpup((__be16 *)&synusb->data[4]);
w = synusb->data[0] & 0x0f;
if (pressure > 0) {
num_fingers = 1;
tool_width = 5;
switch (w) {
case 0 ... 1:
num_fingers = 2 + w;
break;
case 2: /* pen, pretend its a finger */
break;
case 4 ... 15:
tool_width = w;
break;
}
} else {
num_fingers = 0;
tool_width = 0;
}
/*
* Post events
* BTN_TOUCH has to be first as mousedev relies on it when doing
* absolute -> relative conversion
*/
if (pressure > 30)
input_report_key(input_dev, BTN_TOUCH, 1);
if (pressure < 25)
input_report_key(input_dev, BTN_TOUCH, 0);
if (num_fingers > 0) {
input_report_abs(input_dev, ABS_X, x);
input_report_abs(input_dev, ABS_Y,
YMAX_NOMINAL + YMIN_NOMINAL - y);
}
input_report_abs(input_dev, ABS_PRESSURE, pressure);
input_report_abs(input_dev, ABS_TOOL_WIDTH, tool_width);
input_report_key(input_dev, BTN_TOOL_FINGER, num_fingers == 1);
input_report_key(input_dev, BTN_TOOL_DOUBLETAP, num_fingers == 2);
input_report_key(input_dev, BTN_TOOL_TRIPLETAP, num_fingers == 3);
synusb_report_buttons(synusb);
if (synusb->flags & SYNUSB_AUXDISPLAY)
input_report_key(input_dev, BTN_MIDDLE, synusb->data[1] & 0x08);
input_sync(input_dev);
}
static void synusb_irq(struct urb *urb)
{
struct synusb *synusb = urb->context;
int error;
/* Check our status in case we need to bail out early. */
switch (urb->status) {
case 0:
usb_mark_last_busy(synusb->udev);
break;
/* Device went away so don't keep trying to read from it. */
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
return;
default:
goto resubmit;
break;
}
if (synusb->flags & SYNUSB_STICK)
synusb_report_stick(synusb);
else
synusb_report_touchpad(synusb);
resubmit:
error = usb_submit_urb(urb, GFP_ATOMIC);
if (error && error != -EPERM)
dev_err(&synusb->intf->dev,
"%s - usb_submit_urb failed with result: %d",
__func__, error);
}
static struct usb_endpoint_descriptor *
synusb_get_in_endpoint(struct usb_host_interface *iface)
{
struct usb_endpoint_descriptor *endpoint;
int i;
for (i = 0; i < iface->desc.bNumEndpoints; ++i) {
endpoint = &iface->endpoint[i].desc;
if (usb_endpoint_is_int_in(endpoint)) {
/* we found our interrupt in endpoint */
return endpoint;
}
}
return NULL;
}
static int synusb_open(struct input_dev *dev)
{
struct synusb *synusb = input_get_drvdata(dev);
int retval;
retval = usb_autopm_get_interface(synusb->intf);
if (retval) {
dev_err(&synusb->intf->dev,
"%s - usb_autopm_get_interface failed, error: %d\n",
__func__, retval);
return retval;
}
retval = usb_submit_urb(synusb->urb, GFP_KERNEL);
if (retval) {
dev_err(&synusb->intf->dev,
"%s - usb_submit_urb failed, error: %d\n",
__func__, retval);
retval = -EIO;
goto out;
}
synusb->intf->needs_remote_wakeup = 1;
out:
usb_autopm_put_interface(synusb->intf);
return retval;
}
static void synusb_close(struct input_dev *dev)
{
struct synusb *synusb = input_get_drvdata(dev);
int autopm_error;
autopm_error = usb_autopm_get_interface(synusb->intf);
usb_kill_urb(synusb->urb);
synusb->intf->needs_remote_wakeup = 0;
if (!autopm_error)
usb_autopm_put_interface(synusb->intf);
}
static int synusb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_endpoint_descriptor *ep;
struct synusb *synusb;
struct input_dev *input_dev;
unsigned int intf_num = intf->cur_altsetting->desc.bInterfaceNumber;
unsigned int altsetting = min(intf->num_altsetting, 1U);
int error;
error = usb_set_interface(udev, intf_num, altsetting);
if (error) {
dev_err(&udev->dev,
"Can not set alternate setting to %i, error: %i",
altsetting, error);
return error;
}
ep = synusb_get_in_endpoint(intf->cur_altsetting);
if (!ep)
return -ENODEV;
synusb = kzalloc(sizeof(*synusb), GFP_KERNEL);
input_dev = input_allocate_device();
if (!synusb || !input_dev) {
error = -ENOMEM;
goto err_free_mem;
}
synusb->udev = udev;
synusb->intf = intf;
synusb->input = input_dev;
synusb->flags = id->driver_info;
if (synusb->flags & SYNUSB_COMBO) {
/*
* This is a combo device, we need to set proper
* capability, depending on the interface.
*/
synusb->flags |= intf_num == 1 ?
SYNUSB_STICK : SYNUSB_TOUCHPAD;
}
synusb->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!synusb->urb) {
error = -ENOMEM;
goto err_free_mem;
}
synusb->data = usb_alloc_coherent(udev, SYNUSB_RECV_SIZE, GFP_KERNEL,
&synusb->urb->transfer_dma);
if (!synusb->data) {
error = -ENOMEM;
goto err_free_urb;
}
usb_fill_int_urb(synusb->urb, udev,
usb_rcvintpipe(udev, ep->bEndpointAddress),
synusb->data, SYNUSB_RECV_SIZE,
synusb_irq, synusb,
ep->bInterval);
synusb->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
if (udev->manufacturer)
strlcpy(synusb->name, udev->manufacturer,
sizeof(synusb->name));
if (udev->product) {
if (udev->manufacturer)
strlcat(synusb->name, " ", sizeof(synusb->name));
strlcat(synusb->name, udev->product, sizeof(synusb->name));
}
if (!strlen(synusb->name))
snprintf(synusb->name, sizeof(synusb->name),
"USB Synaptics Device %04x:%04x",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct));
if (synusb->flags & SYNUSB_STICK)
strlcat(synusb->name, " (Stick) ", sizeof(synusb->name));
usb_make_path(udev, synusb->phys, sizeof(synusb->phys));
strlcat(synusb->phys, "/input0", sizeof(synusb->phys));
input_dev->name = synusb->name;
input_dev->phys = synusb->phys;
usb_to_input_id(udev, &input_dev->id);
input_dev->dev.parent = &synusb->intf->dev;
if (!(synusb->flags & SYNUSB_IO_ALWAYS)) {
input_dev->open = synusb_open;
input_dev->close = synusb_close;
}
input_set_drvdata(input_dev, synusb);
__set_bit(EV_ABS, input_dev->evbit);
__set_bit(EV_KEY, input_dev->evbit);
if (synusb->flags & SYNUSB_STICK) {
__set_bit(EV_REL, input_dev->evbit);
__set_bit(REL_X, input_dev->relbit);
__set_bit(REL_Y, input_dev->relbit);
input_set_abs_params(input_dev, ABS_PRESSURE, 0, 127, 0, 0);
} else {
input_set_abs_params(input_dev, ABS_X,
XMIN_NOMINAL, XMAX_NOMINAL, 0, 0);
input_set_abs_params(input_dev, ABS_Y,
YMIN_NOMINAL, YMAX_NOMINAL, 0, 0);
input_set_abs_params(input_dev, ABS_PRESSURE, 0, 255, 0, 0);
input_set_abs_params(input_dev, ABS_TOOL_WIDTH, 0, 15, 0, 0);
__set_bit(BTN_TOUCH, input_dev->keybit);
__set_bit(BTN_TOOL_FINGER, input_dev->keybit);
__set_bit(BTN_TOOL_DOUBLETAP, input_dev->keybit);
__set_bit(BTN_TOOL_TRIPLETAP, input_dev->keybit);
}
__set_bit(BTN_LEFT, input_dev->keybit);
__set_bit(BTN_RIGHT, input_dev->keybit);
__set_bit(BTN_MIDDLE, input_dev->keybit);
usb_set_intfdata(intf, synusb);
if (synusb->flags & SYNUSB_IO_ALWAYS) {
error = synusb_open(input_dev);
if (error)
goto err_free_dma;
}
error = input_register_device(input_dev);
if (error) {
dev_err(&udev->dev,
"Failed to register input device, error %d\n",
error);
goto err_stop_io;
}
return 0;
err_stop_io:
if (synusb->flags & SYNUSB_IO_ALWAYS)
synusb_close(synusb->input);
err_free_dma:
usb_free_coherent(udev, SYNUSB_RECV_SIZE, synusb->data,
synusb->urb->transfer_dma);
err_free_urb:
usb_free_urb(synusb->urb);
err_free_mem:
input_free_device(input_dev);
kfree(synusb);
usb_set_intfdata(intf, NULL);
return error;
}
static void synusb_disconnect(struct usb_interface *intf)
{
struct synusb *synusb = usb_get_intfdata(intf);
struct usb_device *udev = interface_to_usbdev(intf);
if (synusb->flags & SYNUSB_IO_ALWAYS)
synusb_close(synusb->input);
input_unregister_device(synusb->input);
usb_free_coherent(udev, SYNUSB_RECV_SIZE, synusb->data,
synusb->urb->transfer_dma);
usb_free_urb(synusb->urb);
kfree(synusb);
usb_set_intfdata(intf, NULL);
}
static int synusb_suspend(struct usb_interface *intf, pm_message_t message)
{
struct synusb *synusb = usb_get_intfdata(intf);
struct input_dev *input_dev = synusb->input;
mutex_lock(&input_dev->mutex);
usb_kill_urb(synusb->urb);
mutex_unlock(&input_dev->mutex);
return 0;
}
static int synusb_resume(struct usb_interface *intf)
{
struct synusb *synusb = usb_get_intfdata(intf);
struct input_dev *input_dev = synusb->input;
int retval = 0;
mutex_lock(&input_dev->mutex);
if ((input_dev->users || (synusb->flags & SYNUSB_IO_ALWAYS)) &&
usb_submit_urb(synusb->urb, GFP_NOIO) < 0) {
retval = -EIO;
}
mutex_unlock(&input_dev->mutex);
return retval;
}
static int synusb_pre_reset(struct usb_interface *intf)
{
struct synusb *synusb = usb_get_intfdata(intf);
struct input_dev *input_dev = synusb->input;
mutex_lock(&input_dev->mutex);
usb_kill_urb(synusb->urb);
return 0;
}
static int synusb_post_reset(struct usb_interface *intf)
{
struct synusb *synusb = usb_get_intfdata(intf);
struct input_dev *input_dev = synusb->input;
int retval = 0;
if ((input_dev->users || (synusb->flags & SYNUSB_IO_ALWAYS)) &&
usb_submit_urb(synusb->urb, GFP_NOIO) < 0) {
retval = -EIO;
}
mutex_unlock(&input_dev->mutex);
return retval;
}
static int synusb_reset_resume(struct usb_interface *intf)
{
return synusb_resume(intf);
}
static struct usb_device_id synusb_idtable[] = {
{ USB_DEVICE_SYNAPTICS(TP, SYNUSB_TOUCHPAD) },
{ USB_DEVICE_SYNAPTICS(INT_TP, SYNUSB_TOUCHPAD) },
{ USB_DEVICE_SYNAPTICS(CPAD,
SYNUSB_TOUCHPAD | SYNUSB_AUXDISPLAY | SYNUSB_IO_ALWAYS) },
{ USB_DEVICE_SYNAPTICS(TS, SYNUSB_TOUCHSCREEN) },
{ USB_DEVICE_SYNAPTICS(STICK, SYNUSB_STICK) },
{ USB_DEVICE_SYNAPTICS(WP, SYNUSB_TOUCHPAD) },
{ USB_DEVICE_SYNAPTICS(COMP_TP, SYNUSB_COMBO) },
{ USB_DEVICE_SYNAPTICS(WTP, SYNUSB_TOUCHPAD) },
{ USB_DEVICE_SYNAPTICS(DPAD, SYNUSB_TOUCHPAD) },
{ }
};
MODULE_DEVICE_TABLE(usb, synusb_idtable);
static struct usb_driver synusb_driver = {
.name = "synaptics_usb",
.probe = synusb_probe,
.disconnect = synusb_disconnect,
.id_table = synusb_idtable,
.suspend = synusb_suspend,
.resume = synusb_resume,
.pre_reset = synusb_pre_reset,
.post_reset = synusb_post_reset,
.reset_resume = synusb_reset_resume,
.supports_autosuspend = 1,
};
module_usb_driver(synusb_driver);
MODULE_AUTHOR("Rob Miller <rob@inpharmatica.co.uk>, "
"Ron Lee <ron@debian.org>, "
"Jan Steinhoff <cpad@jan-steinhoff.de>");
MODULE_DESCRIPTION("Synaptics USB device driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ShinySide/HispAsian_Kernel | drivers/pci/hotplug/cpci_hotplug_pci.c | 4860 | 7832 | /*
* CompactPCI Hot Plug Driver PCI functions
*
* Copyright (C) 2002,2005 by SOMA Networks, Inc.
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. 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.
*
* Send feedback to <scottm@somanetworks.com>
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include <linux/proc_fs.h>
#include "../pci.h"
#include "cpci_hotplug.h"
#define MY_NAME "cpci_hotplug"
extern int cpci_debug;
#define dbg(format, arg...) \
do { \
if (cpci_debug) \
printk (KERN_DEBUG "%s: " format "\n", \
MY_NAME , ## arg); \
} while (0)
#define err(format, arg...) printk(KERN_ERR "%s: " format "\n", MY_NAME , ## arg)
#define info(format, arg...) printk(KERN_INFO "%s: " format "\n", MY_NAME , ## arg)
#define warn(format, arg...) printk(KERN_WARNING "%s: " format "\n", MY_NAME , ## arg)
u8 cpci_get_attention_status(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0;
return hs_csr & 0x0008 ? 1 : 0;
}
int cpci_set_attention_status(struct slot* slot, int status)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0;
if (status)
hs_csr |= HS_CSR_LOO;
else
hs_csr &= ~HS_CSR_LOO;
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr))
return 0;
return 1;
}
u16 cpci_get_hs_csr(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0xFFFF;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0xFFFF;
return hs_csr;
}
int cpci_check_and_clear_ins(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
int ins = 0;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0;
if (hs_csr & HS_CSR_INS) {
/* Clear INS (by setting it) */
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr))
ins = 0;
else
ins = 1;
}
return ins;
}
int cpci_check_ext(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
int ext = 0;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0;
if (hs_csr & HS_CSR_EXT)
ext = 1;
return ext;
}
int cpci_clear_ext(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return -ENODEV;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return -ENODEV;
if (hs_csr & HS_CSR_EXT) {
/* Clear EXT (by setting it) */
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr))
return -ENODEV;
}
return 0;
}
int cpci_led_on(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return -ENODEV;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return -ENODEV;
if ((hs_csr & HS_CSR_LOO) != HS_CSR_LOO) {
hs_csr |= HS_CSR_LOO;
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr)) {
err("Could not set LOO for slot %s",
hotplug_slot_name(slot->hotplug_slot));
return -ENODEV;
}
}
return 0;
}
int cpci_led_off(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return -ENODEV;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return -ENODEV;
if (hs_csr & HS_CSR_LOO) {
hs_csr &= ~HS_CSR_LOO;
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr)) {
err("Could not clear LOO for slot %s",
hotplug_slot_name(slot->hotplug_slot));
return -ENODEV;
}
}
return 0;
}
/*
* Device configuration functions
*/
int __ref cpci_configure_slot(struct slot *slot)
{
struct pci_bus *parent;
int fn;
dbg("%s - enter", __func__);
if (slot->dev == NULL) {
dbg("pci_dev null, finding %02x:%02x:%x",
slot->bus->number, PCI_SLOT(slot->devfn), PCI_FUNC(slot->devfn));
slot->dev = pci_get_slot(slot->bus, slot->devfn);
}
/* Still NULL? Well then scan for it! */
if (slot->dev == NULL) {
int n;
dbg("pci_dev still null");
/*
* This will generate pci_dev structures for all functions, but
* we will only call this case when lookup fails.
*/
n = pci_scan_slot(slot->bus, slot->devfn);
dbg("%s: pci_scan_slot returned %d", __func__, n);
slot->dev = pci_get_slot(slot->bus, slot->devfn);
if (slot->dev == NULL) {
err("Could not find PCI device for slot %02x", slot->number);
return -ENODEV;
}
}
parent = slot->dev->bus;
for (fn = 0; fn < 8; fn++) {
struct pci_dev *dev;
dev = pci_get_slot(parent, PCI_DEVFN(PCI_SLOT(slot->devfn), fn));
if (!dev)
continue;
if ((dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) ||
(dev->hdr_type == PCI_HEADER_TYPE_CARDBUS)) {
/* Find an unused bus number for the new bridge */
struct pci_bus *child;
unsigned char busnr, start = parent->secondary;
unsigned char end = parent->subordinate;
for (busnr = start; busnr <= end; busnr++) {
if (!pci_find_bus(pci_domain_nr(parent),
busnr))
break;
}
if (busnr >= end) {
err("No free bus for hot-added bridge\n");
pci_dev_put(dev);
continue;
}
child = pci_add_new_bus(parent, dev, busnr);
if (!child) {
err("Cannot add new bus for %s\n",
pci_name(dev));
pci_dev_put(dev);
continue;
}
child->subordinate = pci_do_scan_bus(child);
pci_bus_size_bridges(child);
}
pci_dev_put(dev);
}
pci_bus_assign_resources(parent);
pci_bus_add_devices(parent);
pci_enable_bridges(parent);
dbg("%s - exit", __func__);
return 0;
}
int cpci_unconfigure_slot(struct slot* slot)
{
int i;
struct pci_dev *dev;
dbg("%s - enter", __func__);
if (!slot->dev) {
err("No device for slot %02x\n", slot->number);
return -ENODEV;
}
for (i = 0; i < 8; i++) {
dev = pci_get_slot(slot->bus,
PCI_DEVFN(PCI_SLOT(slot->devfn), i));
if (dev) {
pci_stop_and_remove_bus_device(dev);
pci_dev_put(dev);
}
}
pci_dev_put(slot->dev);
slot->dev = NULL;
dbg("%s - exit", __func__);
return 0;
}
| gpl-2.0 |
moscowdesire/Sony | drivers/pci/hotplug/cpci_hotplug_pci.c | 4860 | 7832 | /*
* CompactPCI Hot Plug Driver PCI functions
*
* Copyright (C) 2002,2005 by SOMA Networks, Inc.
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. 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.
*
* Send feedback to <scottm@somanetworks.com>
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include <linux/proc_fs.h>
#include "../pci.h"
#include "cpci_hotplug.h"
#define MY_NAME "cpci_hotplug"
extern int cpci_debug;
#define dbg(format, arg...) \
do { \
if (cpci_debug) \
printk (KERN_DEBUG "%s: " format "\n", \
MY_NAME , ## arg); \
} while (0)
#define err(format, arg...) printk(KERN_ERR "%s: " format "\n", MY_NAME , ## arg)
#define info(format, arg...) printk(KERN_INFO "%s: " format "\n", MY_NAME , ## arg)
#define warn(format, arg...) printk(KERN_WARNING "%s: " format "\n", MY_NAME , ## arg)
u8 cpci_get_attention_status(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0;
return hs_csr & 0x0008 ? 1 : 0;
}
int cpci_set_attention_status(struct slot* slot, int status)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0;
if (status)
hs_csr |= HS_CSR_LOO;
else
hs_csr &= ~HS_CSR_LOO;
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr))
return 0;
return 1;
}
u16 cpci_get_hs_csr(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0xFFFF;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0xFFFF;
return hs_csr;
}
int cpci_check_and_clear_ins(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
int ins = 0;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0;
if (hs_csr & HS_CSR_INS) {
/* Clear INS (by setting it) */
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr))
ins = 0;
else
ins = 1;
}
return ins;
}
int cpci_check_ext(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
int ext = 0;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return 0;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return 0;
if (hs_csr & HS_CSR_EXT)
ext = 1;
return ext;
}
int cpci_clear_ext(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return -ENODEV;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return -ENODEV;
if (hs_csr & HS_CSR_EXT) {
/* Clear EXT (by setting it) */
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr))
return -ENODEV;
}
return 0;
}
int cpci_led_on(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return -ENODEV;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return -ENODEV;
if ((hs_csr & HS_CSR_LOO) != HS_CSR_LOO) {
hs_csr |= HS_CSR_LOO;
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr)) {
err("Could not set LOO for slot %s",
hotplug_slot_name(slot->hotplug_slot));
return -ENODEV;
}
}
return 0;
}
int cpci_led_off(struct slot* slot)
{
int hs_cap;
u16 hs_csr;
hs_cap = pci_bus_find_capability(slot->bus,
slot->devfn,
PCI_CAP_ID_CHSWP);
if (!hs_cap)
return -ENODEV;
if (pci_bus_read_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
&hs_csr))
return -ENODEV;
if (hs_csr & HS_CSR_LOO) {
hs_csr &= ~HS_CSR_LOO;
if (pci_bus_write_config_word(slot->bus,
slot->devfn,
hs_cap + 2,
hs_csr)) {
err("Could not clear LOO for slot %s",
hotplug_slot_name(slot->hotplug_slot));
return -ENODEV;
}
}
return 0;
}
/*
* Device configuration functions
*/
int __ref cpci_configure_slot(struct slot *slot)
{
struct pci_bus *parent;
int fn;
dbg("%s - enter", __func__);
if (slot->dev == NULL) {
dbg("pci_dev null, finding %02x:%02x:%x",
slot->bus->number, PCI_SLOT(slot->devfn), PCI_FUNC(slot->devfn));
slot->dev = pci_get_slot(slot->bus, slot->devfn);
}
/* Still NULL? Well then scan for it! */
if (slot->dev == NULL) {
int n;
dbg("pci_dev still null");
/*
* This will generate pci_dev structures for all functions, but
* we will only call this case when lookup fails.
*/
n = pci_scan_slot(slot->bus, slot->devfn);
dbg("%s: pci_scan_slot returned %d", __func__, n);
slot->dev = pci_get_slot(slot->bus, slot->devfn);
if (slot->dev == NULL) {
err("Could not find PCI device for slot %02x", slot->number);
return -ENODEV;
}
}
parent = slot->dev->bus;
for (fn = 0; fn < 8; fn++) {
struct pci_dev *dev;
dev = pci_get_slot(parent, PCI_DEVFN(PCI_SLOT(slot->devfn), fn));
if (!dev)
continue;
if ((dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) ||
(dev->hdr_type == PCI_HEADER_TYPE_CARDBUS)) {
/* Find an unused bus number for the new bridge */
struct pci_bus *child;
unsigned char busnr, start = parent->secondary;
unsigned char end = parent->subordinate;
for (busnr = start; busnr <= end; busnr++) {
if (!pci_find_bus(pci_domain_nr(parent),
busnr))
break;
}
if (busnr >= end) {
err("No free bus for hot-added bridge\n");
pci_dev_put(dev);
continue;
}
child = pci_add_new_bus(parent, dev, busnr);
if (!child) {
err("Cannot add new bus for %s\n",
pci_name(dev));
pci_dev_put(dev);
continue;
}
child->subordinate = pci_do_scan_bus(child);
pci_bus_size_bridges(child);
}
pci_dev_put(dev);
}
pci_bus_assign_resources(parent);
pci_bus_add_devices(parent);
pci_enable_bridges(parent);
dbg("%s - exit", __func__);
return 0;
}
int cpci_unconfigure_slot(struct slot* slot)
{
int i;
struct pci_dev *dev;
dbg("%s - enter", __func__);
if (!slot->dev) {
err("No device for slot %02x\n", slot->number);
return -ENODEV;
}
for (i = 0; i < 8; i++) {
dev = pci_get_slot(slot->bus,
PCI_DEVFN(PCI_SLOT(slot->devfn), i));
if (dev) {
pci_stop_and_remove_bus_device(dev);
pci_dev_put(dev);
}
}
pci_dev_put(slot->dev);
slot->dev = NULL;
dbg("%s - exit", __func__);
return 0;
}
| gpl-2.0 |
SerenityS/Solid_Kernel-Stock-KK | drivers/staging/vme/boards/vme_vmivme7805.c | 5628 | 2963 | /*
* Support for the VMIVME-7805 board access to the Universe II bridge.
*
* Author: Arthur Benilov <arthur.benilov@iba-group.com>
* Copyright 2010 Ion Beam Application, 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.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/pci.h>
#include <linux/poll.h>
#include <linux/io.h>
#include "vme_vmivme7805.h"
static int __init vmic_init(void);
static int vmic_probe(struct pci_dev *, const struct pci_device_id *);
static void vmic_remove(struct pci_dev *);
static void __exit vmic_exit(void);
/** Base address to access FPGA register */
static void *vmic_base;
static const char driver_name[] = "vmivme_7805";
static DEFINE_PCI_DEVICE_TABLE(vmic_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_VMIC, PCI_DEVICE_ID_VTIMR) },
{ },
};
static struct pci_driver vmic_driver = {
.name = driver_name,
.id_table = vmic_ids,
.probe = vmic_probe,
.remove = vmic_remove,
};
static int __init vmic_init(void)
{
return pci_register_driver(&vmic_driver);
}
static int vmic_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
int retval;
u32 data;
/* Enable the device */
retval = pci_enable_device(pdev);
if (retval) {
dev_err(&pdev->dev, "Unable to enable device\n");
goto err;
}
/* Map Registers */
retval = pci_request_regions(pdev, driver_name);
if (retval) {
dev_err(&pdev->dev, "Unable to reserve resources\n");
goto err_resource;
}
/* Map registers in BAR 0 */
vmic_base = ioremap_nocache(pci_resource_start(pdev, 0), 16);
if (!vmic_base) {
dev_err(&pdev->dev, "Unable to remap CRG region\n");
retval = -EIO;
goto err_remap;
}
/* Clear the FPGA VME IF contents */
iowrite32(0, vmic_base + VME_CONTROL);
/* Clear any initial BERR */
data = ioread32(vmic_base + VME_CONTROL) & 0x00000FFF;
data |= BM_VME_CONTROL_BERRST;
iowrite32(data, vmic_base + VME_CONTROL);
/* Enable the vme interface and byte swapping */
data = ioread32(vmic_base + VME_CONTROL) & 0x00000FFF;
data = data | BM_VME_CONTROL_MASTER_ENDIAN |
BM_VME_CONTROL_SLAVE_ENDIAN |
BM_VME_CONTROL_ABLE |
BM_VME_CONTROL_BERRI |
BM_VME_CONTROL_BPENA |
BM_VME_CONTROL_VBENA;
iowrite32(data, vmic_base + VME_CONTROL);
return 0;
err_remap:
pci_release_regions(pdev);
err_resource:
pci_disable_device(pdev);
err:
return retval;
}
static void vmic_remove(struct pci_dev *pdev)
{
iounmap(vmic_base);
pci_release_regions(pdev);
pci_disable_device(pdev);
}
static void __exit vmic_exit(void)
{
pci_unregister_driver(&vmic_driver);
}
MODULE_DESCRIPTION("VMIVME-7805 board support driver");
MODULE_AUTHOR("Arthur Benilov <arthur.benilov@iba-group.com>");
MODULE_LICENSE("GPL");
module_init(vmic_init);
module_exit(vmic_exit);
| gpl-2.0 |
CyanogenMod/android_kernel_google_msm | fs/yaffs2/yaffs_tagscompat.c | 7932 | 10448 | /*
* YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
*
* Copyright (C) 2002-2010 Aleph One Ltd.
* for Toby Churchill Ltd and Brightstar Engineering
*
* Created by Charles Manning <charles@aleph1.co.uk>
*
* 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 "yaffs_guts.h"
#include "yaffs_tagscompat.h"
#include "yaffs_ecc.h"
#include "yaffs_getblockinfo.h"
#include "yaffs_trace.h"
static void yaffs_handle_rd_data_error(struct yaffs_dev *dev, int nand_chunk);
/********** Tags ECC calculations *********/
void yaffs_calc_ecc(const u8 * data, struct yaffs_spare *spare)
{
yaffs_ecc_cacl(data, spare->ecc1);
yaffs_ecc_cacl(&data[256], spare->ecc2);
}
void yaffs_calc_tags_ecc(struct yaffs_tags *tags)
{
/* Calculate an ecc */
unsigned char *b = ((union yaffs_tags_union *)tags)->as_bytes;
unsigned i, j;
unsigned ecc = 0;
unsigned bit = 0;
tags->ecc = 0;
for (i = 0; i < 8; i++) {
for (j = 1; j & 0xff; j <<= 1) {
bit++;
if (b[i] & j)
ecc ^= bit;
}
}
tags->ecc = ecc;
}
int yaffs_check_tags_ecc(struct yaffs_tags *tags)
{
unsigned ecc = tags->ecc;
yaffs_calc_tags_ecc(tags);
ecc ^= tags->ecc;
if (ecc && ecc <= 64) {
/* TODO: Handle the failure better. Retire? */
unsigned char *b = ((union yaffs_tags_union *)tags)->as_bytes;
ecc--;
b[ecc / 8] ^= (1 << (ecc & 7));
/* Now recvalc the ecc */
yaffs_calc_tags_ecc(tags);
return 1; /* recovered error */
} else if (ecc) {
/* Wierd ecc failure value */
/* TODO Need to do somethiong here */
return -1; /* unrecovered error */
}
return 0;
}
/********** Tags **********/
static void yaffs_load_tags_to_spare(struct yaffs_spare *spare_ptr,
struct yaffs_tags *tags_ptr)
{
union yaffs_tags_union *tu = (union yaffs_tags_union *)tags_ptr;
yaffs_calc_tags_ecc(tags_ptr);
spare_ptr->tb0 = tu->as_bytes[0];
spare_ptr->tb1 = tu->as_bytes[1];
spare_ptr->tb2 = tu->as_bytes[2];
spare_ptr->tb3 = tu->as_bytes[3];
spare_ptr->tb4 = tu->as_bytes[4];
spare_ptr->tb5 = tu->as_bytes[5];
spare_ptr->tb6 = tu->as_bytes[6];
spare_ptr->tb7 = tu->as_bytes[7];
}
static void yaffs_get_tags_from_spare(struct yaffs_dev *dev,
struct yaffs_spare *spare_ptr,
struct yaffs_tags *tags_ptr)
{
union yaffs_tags_union *tu = (union yaffs_tags_union *)tags_ptr;
int result;
tu->as_bytes[0] = spare_ptr->tb0;
tu->as_bytes[1] = spare_ptr->tb1;
tu->as_bytes[2] = spare_ptr->tb2;
tu->as_bytes[3] = spare_ptr->tb3;
tu->as_bytes[4] = spare_ptr->tb4;
tu->as_bytes[5] = spare_ptr->tb5;
tu->as_bytes[6] = spare_ptr->tb6;
tu->as_bytes[7] = spare_ptr->tb7;
result = yaffs_check_tags_ecc(tags_ptr);
if (result > 0)
dev->n_tags_ecc_fixed++;
else if (result < 0)
dev->n_tags_ecc_unfixed++;
}
static void yaffs_spare_init(struct yaffs_spare *spare)
{
memset(spare, 0xFF, sizeof(struct yaffs_spare));
}
static int yaffs_wr_nand(struct yaffs_dev *dev,
int nand_chunk, const u8 * data,
struct yaffs_spare *spare)
{
if (nand_chunk < dev->param.start_block * dev->param.chunks_per_block) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>> yaffs chunk %d is not valid",
nand_chunk);
return YAFFS_FAIL;
}
return dev->param.write_chunk_fn(dev, nand_chunk, data, spare);
}
static int yaffs_rd_chunk_nand(struct yaffs_dev *dev,
int nand_chunk,
u8 * data,
struct yaffs_spare *spare,
enum yaffs_ecc_result *ecc_result,
int correct_errors)
{
int ret_val;
struct yaffs_spare local_spare;
if (!spare && data) {
/* If we don't have a real spare, then we use a local one. */
/* Need this for the calculation of the ecc */
spare = &local_spare;
}
if (!dev->param.use_nand_ecc) {
ret_val =
dev->param.read_chunk_fn(dev, nand_chunk, data, spare);
if (data && correct_errors) {
/* Do ECC correction */
/* Todo handle any errors */
int ecc_result1, ecc_result2;
u8 calc_ecc[3];
yaffs_ecc_cacl(data, calc_ecc);
ecc_result1 =
yaffs_ecc_correct(data, spare->ecc1, calc_ecc);
yaffs_ecc_cacl(&data[256], calc_ecc);
ecc_result2 =
yaffs_ecc_correct(&data[256], spare->ecc2,
calc_ecc);
if (ecc_result1 > 0) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>>yaffs ecc error fix performed on chunk %d:0",
nand_chunk);
dev->n_ecc_fixed++;
} else if (ecc_result1 < 0) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>>yaffs ecc error unfixed on chunk %d:0",
nand_chunk);
dev->n_ecc_unfixed++;
}
if (ecc_result2 > 0) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>>yaffs ecc error fix performed on chunk %d:1",
nand_chunk);
dev->n_ecc_fixed++;
} else if (ecc_result2 < 0) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>>yaffs ecc error unfixed on chunk %d:1",
nand_chunk);
dev->n_ecc_unfixed++;
}
if (ecc_result1 || ecc_result2) {
/* We had a data problem on this page */
yaffs_handle_rd_data_error(dev, nand_chunk);
}
if (ecc_result1 < 0 || ecc_result2 < 0)
*ecc_result = YAFFS_ECC_RESULT_UNFIXED;
else if (ecc_result1 > 0 || ecc_result2 > 0)
*ecc_result = YAFFS_ECC_RESULT_FIXED;
else
*ecc_result = YAFFS_ECC_RESULT_NO_ERROR;
}
} else {
/* Must allocate enough memory for spare+2*sizeof(int) */
/* for ecc results from device. */
struct yaffs_nand_spare nspare;
memset(&nspare, 0, sizeof(nspare));
ret_val = dev->param.read_chunk_fn(dev, nand_chunk, data,
(struct yaffs_spare *)
&nspare);
memcpy(spare, &nspare, sizeof(struct yaffs_spare));
if (data && correct_errors) {
if (nspare.eccres1 > 0) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>>mtd ecc error fix performed on chunk %d:0",
nand_chunk);
} else if (nspare.eccres1 < 0) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>>mtd ecc error unfixed on chunk %d:0",
nand_chunk);
}
if (nspare.eccres2 > 0) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>>mtd ecc error fix performed on chunk %d:1",
nand_chunk);
} else if (nspare.eccres2 < 0) {
yaffs_trace(YAFFS_TRACE_ERROR,
"**>>mtd ecc error unfixed on chunk %d:1",
nand_chunk);
}
if (nspare.eccres1 || nspare.eccres2) {
/* We had a data problem on this page */
yaffs_handle_rd_data_error(dev, nand_chunk);
}
if (nspare.eccres1 < 0 || nspare.eccres2 < 0)
*ecc_result = YAFFS_ECC_RESULT_UNFIXED;
else if (nspare.eccres1 > 0 || nspare.eccres2 > 0)
*ecc_result = YAFFS_ECC_RESULT_FIXED;
else
*ecc_result = YAFFS_ECC_RESULT_NO_ERROR;
}
}
return ret_val;
}
/*
* Functions for robustisizing
*/
static void yaffs_handle_rd_data_error(struct yaffs_dev *dev, int nand_chunk)
{
int flash_block = nand_chunk / dev->param.chunks_per_block;
/* Mark the block for retirement */
yaffs_get_block_info(dev,
flash_block + dev->block_offset)->needs_retiring =
1;
yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
"**>>Block %d marked for retirement",
flash_block);
/* TODO:
* Just do a garbage collection on the affected block
* then retire the block
* NB recursion
*/
}
int yaffs_tags_compat_wr(struct yaffs_dev *dev,
int nand_chunk,
const u8 * data, const struct yaffs_ext_tags *ext_tags)
{
struct yaffs_spare spare;
struct yaffs_tags tags;
yaffs_spare_init(&spare);
if (ext_tags->is_deleted)
spare.page_status = 0;
else {
tags.obj_id = ext_tags->obj_id;
tags.chunk_id = ext_tags->chunk_id;
tags.n_bytes_lsb = ext_tags->n_bytes & 0x3ff;
if (dev->data_bytes_per_chunk >= 1024)
tags.n_bytes_msb = (ext_tags->n_bytes >> 10) & 3;
else
tags.n_bytes_msb = 3;
tags.serial_number = ext_tags->serial_number;
if (!dev->param.use_nand_ecc && data)
yaffs_calc_ecc(data, &spare);
yaffs_load_tags_to_spare(&spare, &tags);
}
return yaffs_wr_nand(dev, nand_chunk, data, &spare);
}
int yaffs_tags_compat_rd(struct yaffs_dev *dev,
int nand_chunk,
u8 * data, struct yaffs_ext_tags *ext_tags)
{
struct yaffs_spare spare;
struct yaffs_tags tags;
enum yaffs_ecc_result ecc_result = YAFFS_ECC_RESULT_UNKNOWN;
static struct yaffs_spare spare_ff;
static int init;
if (!init) {
memset(&spare_ff, 0xFF, sizeof(spare_ff));
init = 1;
}
if (yaffs_rd_chunk_nand(dev, nand_chunk, data, &spare, &ecc_result, 1)) {
/* ext_tags may be NULL */
if (ext_tags) {
int deleted =
(hweight8(spare.page_status) < 7) ? 1 : 0;
ext_tags->is_deleted = deleted;
ext_tags->ecc_result = ecc_result;
ext_tags->block_bad = 0; /* We're reading it */
/* therefore it is not a bad block */
ext_tags->chunk_used =
(memcmp(&spare_ff, &spare, sizeof(spare_ff)) !=
0) ? 1 : 0;
if (ext_tags->chunk_used) {
yaffs_get_tags_from_spare(dev, &spare, &tags);
ext_tags->obj_id = tags.obj_id;
ext_tags->chunk_id = tags.chunk_id;
ext_tags->n_bytes = tags.n_bytes_lsb;
if (dev->data_bytes_per_chunk >= 1024)
ext_tags->n_bytes |=
(((unsigned)tags.
n_bytes_msb) << 10);
ext_tags->serial_number = tags.serial_number;
}
}
return YAFFS_OK;
} else {
return YAFFS_FAIL;
}
}
int yaffs_tags_compat_mark_bad(struct yaffs_dev *dev, int flash_block)
{
struct yaffs_spare spare;
memset(&spare, 0xff, sizeof(struct yaffs_spare));
spare.block_status = 'Y';
yaffs_wr_nand(dev, flash_block * dev->param.chunks_per_block, NULL,
&spare);
yaffs_wr_nand(dev, flash_block * dev->param.chunks_per_block + 1,
NULL, &spare);
return YAFFS_OK;
}
int yaffs_tags_compat_query_block(struct yaffs_dev *dev,
int block_no,
enum yaffs_block_state *state,
u32 * seq_number)
{
struct yaffs_spare spare0, spare1;
static struct yaffs_spare spare_ff;
static int init;
enum yaffs_ecc_result dummy;
if (!init) {
memset(&spare_ff, 0xFF, sizeof(spare_ff));
init = 1;
}
*seq_number = 0;
yaffs_rd_chunk_nand(dev, block_no * dev->param.chunks_per_block, NULL,
&spare0, &dummy, 1);
yaffs_rd_chunk_nand(dev, block_no * dev->param.chunks_per_block + 1,
NULL, &spare1, &dummy, 1);
if (hweight8(spare0.block_status & spare1.block_status) < 7)
*state = YAFFS_BLOCK_STATE_DEAD;
else if (memcmp(&spare_ff, &spare0, sizeof(spare_ff)) == 0)
*state = YAFFS_BLOCK_STATE_EMPTY;
else
*state = YAFFS_BLOCK_STATE_NEEDS_SCANNING;
return YAFFS_OK;
}
| gpl-2.0 |
rutvik95/android_kernel_samsung_universal-5260 | drivers/mtd/maps/mbx860.c | 8188 | 2439 | /*
* Handle mapping of the flash on MBX860 boards
*
* Author: Anton Todorov
* Copyright: (C) 2001 Emness Technology
*
* 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/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#define WINDOW_ADDR 0xfe000000
#define WINDOW_SIZE 0x00200000
/* Flash / Partition sizing */
#define MAX_SIZE_KiB 8192
#define BOOT_PARTITION_SIZE_KiB 512
#define KERNEL_PARTITION_SIZE_KiB 5632
#define APP_PARTITION_SIZE_KiB 2048
#define NUM_PARTITIONS 3
/* partition_info gives details on the logical partitions that the split the
* single flash device into. If the size if zero we use up to the end of the
* device. */
static struct mtd_partition partition_info[]={
{ .name = "MBX flash BOOT partition",
.offset = 0,
.size = BOOT_PARTITION_SIZE_KiB*1024 },
{ .name = "MBX flash DATA partition",
.offset = BOOT_PARTITION_SIZE_KiB*1024,
.size = (KERNEL_PARTITION_SIZE_KiB)*1024 },
{ .name = "MBX flash APPLICATION partition",
.offset = (BOOT_PARTITION_SIZE_KiB+KERNEL_PARTITION_SIZE_KiB)*1024 }
};
static struct mtd_info *mymtd;
struct map_info mbx_map = {
.name = "MBX flash",
.size = WINDOW_SIZE,
.phys = WINDOW_ADDR,
.bankwidth = 4,
};
static int __init init_mbx(void)
{
printk(KERN_NOTICE "Motorola MBX flash device: 0x%x at 0x%x\n", WINDOW_SIZE*4, WINDOW_ADDR);
mbx_map.virt = ioremap(WINDOW_ADDR, WINDOW_SIZE * 4);
if (!mbx_map.virt) {
printk("Failed to ioremap\n");
return -EIO;
}
simple_map_init(&mbx_map);
mymtd = do_map_probe("jedec_probe", &mbx_map);
if (mymtd) {
mymtd->owner = THIS_MODULE;
mtd_device_register(mymtd, NULL, 0);
mtd_device_register(mymtd, partition_info, NUM_PARTITIONS);
return 0;
}
iounmap((void *)mbx_map.virt);
return -ENXIO;
}
static void __exit cleanup_mbx(void)
{
if (mymtd) {
mtd_device_unregister(mymtd);
map_destroy(mymtd);
}
if (mbx_map.virt) {
iounmap((void *)mbx_map.virt);
mbx_map.virt = 0;
}
}
module_init(init_mbx);
module_exit(cleanup_mbx);
MODULE_AUTHOR("Anton Todorov <a.todorov@emness.com>");
MODULE_DESCRIPTION("MTD map driver for Motorola MBX860 board");
MODULE_LICENSE("GPL");
| gpl-2.0 |
coliby/terasic_MTL | drivers/macintosh/via-pmu-backlight.c | 11004 | 4671 | /*
* Backlight code for via-pmu
*
* Copyright (C) 1998 Paul Mackerras and Fabio Riccardi.
* Copyright (C) 2001-2002 Benjamin Herrenschmidt
* Copyright (C) 2006 Michael Hanselmann <linux-kernel@hansmi.ch>
*
*/
#include <asm/ptrace.h>
#include <linux/adb.h>
#include <linux/pmu.h>
#include <asm/backlight.h>
#include <asm/prom.h>
#define MAX_PMU_LEVEL 0xFF
static const struct backlight_ops pmu_backlight_data;
static DEFINE_SPINLOCK(pmu_backlight_lock);
static int sleeping, uses_pmu_bl;
static u8 bl_curve[FB_BACKLIGHT_LEVELS];
static void pmu_backlight_init_curve(u8 off, u8 min, u8 max)
{
int i, flat, count, range = (max - min);
bl_curve[0] = off;
for (flat = 1; flat < (FB_BACKLIGHT_LEVELS / 16); ++flat)
bl_curve[flat] = min;
count = FB_BACKLIGHT_LEVELS * 15 / 16;
for (i = 0; i < count; ++i)
bl_curve[flat + i] = min + (range * (i + 1) / count);
}
static int pmu_backlight_curve_lookup(int value)
{
int level = (FB_BACKLIGHT_LEVELS - 1);
int i, max = 0;
/* Look for biggest value */
for (i = 0; i < FB_BACKLIGHT_LEVELS; i++)
max = max((int)bl_curve[i], max);
/* Look for nearest value */
for (i = 0; i < FB_BACKLIGHT_LEVELS; i++) {
int diff = abs(bl_curve[i] - value);
if (diff < max) {
max = diff;
level = i;
}
}
return level;
}
static int pmu_backlight_get_level_brightness(int level)
{
int pmulevel;
/* Get and convert the value */
pmulevel = bl_curve[level] * FB_BACKLIGHT_MAX / MAX_PMU_LEVEL;
if (pmulevel < 0)
pmulevel = 0;
else if (pmulevel > MAX_PMU_LEVEL)
pmulevel = MAX_PMU_LEVEL;
return pmulevel;
}
static int __pmu_backlight_update_status(struct backlight_device *bd)
{
struct adb_request req;
int level = bd->props.brightness;
if (bd->props.power != FB_BLANK_UNBLANK ||
bd->props.fb_blank != FB_BLANK_UNBLANK)
level = 0;
if (level > 0) {
int pmulevel = pmu_backlight_get_level_brightness(level);
pmu_request(&req, NULL, 2, PMU_BACKLIGHT_BRIGHT, pmulevel);
pmu_wait_complete(&req);
pmu_request(&req, NULL, 2, PMU_POWER_CTRL,
PMU_POW_BACKLIGHT | PMU_POW_ON);
pmu_wait_complete(&req);
} else {
pmu_request(&req, NULL, 2, PMU_POWER_CTRL,
PMU_POW_BACKLIGHT | PMU_POW_OFF);
pmu_wait_complete(&req);
}
return 0;
}
static int pmu_backlight_update_status(struct backlight_device *bd)
{
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&pmu_backlight_lock, flags);
/* Don't update brightness when sleeping */
if (!sleeping)
rc = __pmu_backlight_update_status(bd);
spin_unlock_irqrestore(&pmu_backlight_lock, flags);
return rc;
}
static int pmu_backlight_get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static const struct backlight_ops pmu_backlight_data = {
.get_brightness = pmu_backlight_get_brightness,
.update_status = pmu_backlight_update_status,
};
#ifdef CONFIG_PM
void pmu_backlight_set_sleep(int sleep)
{
unsigned long flags;
spin_lock_irqsave(&pmu_backlight_lock, flags);
sleeping = sleep;
if (pmac_backlight && uses_pmu_bl) {
if (sleep) {
struct adb_request req;
pmu_request(&req, NULL, 2, PMU_POWER_CTRL,
PMU_POW_BACKLIGHT | PMU_POW_OFF);
pmu_wait_complete(&req);
} else
__pmu_backlight_update_status(pmac_backlight);
}
spin_unlock_irqrestore(&pmu_backlight_lock, flags);
}
#endif /* CONFIG_PM */
void __init pmu_backlight_init()
{
struct backlight_properties props;
struct backlight_device *bd;
char name[10];
int level, autosave;
/* Special case for the old PowerBook since I can't test on it */
autosave =
of_machine_is_compatible("AAPL,3400/2400") ||
of_machine_is_compatible("AAPL,3500");
if (!autosave &&
!pmac_has_backlight_type("pmu") &&
!of_machine_is_compatible("AAPL,PowerBook1998") &&
!of_machine_is_compatible("PowerBook1,1"))
return;
snprintf(name, sizeof(name), "pmubl");
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = FB_BACKLIGHT_LEVELS - 1;
bd = backlight_device_register(name, NULL, NULL, &pmu_backlight_data,
&props);
if (IS_ERR(bd)) {
printk(KERN_ERR "PMU Backlight registration failed\n");
return;
}
uses_pmu_bl = 1;
pmu_backlight_init_curve(0x7F, 0x46, 0x0E);
level = bd->props.max_brightness;
if (autosave) {
/* read autosaved value if available */
struct adb_request req;
pmu_request(&req, NULL, 2, 0xd9, 0);
pmu_wait_complete(&req);
level = pmu_backlight_curve_lookup(
(req.reply[0] >> 4) *
bd->props.max_brightness / 15);
}
bd->props.brightness = level;
bd->props.power = FB_BLANK_UNBLANK;
backlight_update_status(bd);
printk(KERN_INFO "PMU Backlight initialized (%s)\n", name);
}
| gpl-2.0 |
alexpotter1/QuantumKernel_msm8974_d802 | drivers/media/video/cx18/cx18-irq.c | 13820 | 2326 | /*
* cx18 interrupt handling
*
* Copyright (C) 2007 Hans Verkuil <hverkuil@xs4all.nl>
* Copyright (C) 2008 Andy Walls <awalls@md.metrocast.net>
*
* 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 "cx18-driver.h"
#include "cx18-io.h"
#include "cx18-irq.h"
#include "cx18-mailbox.h"
#include "cx18-scb.h"
static void xpu_ack(struct cx18 *cx, u32 sw2)
{
if (sw2 & IRQ_CPU_TO_EPU_ACK)
wake_up(&cx->mb_cpu_waitq);
if (sw2 & IRQ_APU_TO_EPU_ACK)
wake_up(&cx->mb_apu_waitq);
}
static void epu_cmd(struct cx18 *cx, u32 sw1)
{
if (sw1 & IRQ_CPU_TO_EPU)
cx18_api_epu_cmd_irq(cx, CPU);
if (sw1 & IRQ_APU_TO_EPU)
cx18_api_epu_cmd_irq(cx, APU);
}
irqreturn_t cx18_irq_handler(int irq, void *dev_id)
{
struct cx18 *cx = (struct cx18 *)dev_id;
u32 sw1, sw2, hw2;
sw1 = cx18_read_reg(cx, SW1_INT_STATUS) & cx->sw1_irq_mask;
sw2 = cx18_read_reg(cx, SW2_INT_STATUS) & cx->sw2_irq_mask;
hw2 = cx18_read_reg(cx, HW2_INT_CLR_STATUS) & cx->hw2_irq_mask;
if (sw1)
cx18_write_reg_expect(cx, sw1, SW1_INT_STATUS, ~sw1, sw1);
if (sw2)
cx18_write_reg_expect(cx, sw2, SW2_INT_STATUS, ~sw2, sw2);
if (hw2)
cx18_write_reg_expect(cx, hw2, HW2_INT_CLR_STATUS, ~hw2, hw2);
if (sw1 || sw2 || hw2)
CX18_DEBUG_HI_IRQ("received interrupts "
"SW1: %x SW2: %x HW2: %x\n", sw1, sw2, hw2);
/*
* SW1 responses have to happen first. The sending XPU times out the
* incoming mailboxes on us rather rapidly.
*/
if (sw1)
epu_cmd(cx, sw1);
/* To do: interrupt-based I2C handling
if (hw2 & (HW2_I2C1_INT|HW2_I2C2_INT)) {
}
*/
if (sw2)
xpu_ack(cx, sw2);
return (sw1 || sw2 || hw2) ? IRQ_HANDLED : IRQ_NONE;
}
| gpl-2.0 |
primiano/udoo_kernel_imx | drivers/media/video/cx18/cx18-irq.c | 13820 | 2326 | /*
* cx18 interrupt handling
*
* Copyright (C) 2007 Hans Verkuil <hverkuil@xs4all.nl>
* Copyright (C) 2008 Andy Walls <awalls@md.metrocast.net>
*
* 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 "cx18-driver.h"
#include "cx18-io.h"
#include "cx18-irq.h"
#include "cx18-mailbox.h"
#include "cx18-scb.h"
static void xpu_ack(struct cx18 *cx, u32 sw2)
{
if (sw2 & IRQ_CPU_TO_EPU_ACK)
wake_up(&cx->mb_cpu_waitq);
if (sw2 & IRQ_APU_TO_EPU_ACK)
wake_up(&cx->mb_apu_waitq);
}
static void epu_cmd(struct cx18 *cx, u32 sw1)
{
if (sw1 & IRQ_CPU_TO_EPU)
cx18_api_epu_cmd_irq(cx, CPU);
if (sw1 & IRQ_APU_TO_EPU)
cx18_api_epu_cmd_irq(cx, APU);
}
irqreturn_t cx18_irq_handler(int irq, void *dev_id)
{
struct cx18 *cx = (struct cx18 *)dev_id;
u32 sw1, sw2, hw2;
sw1 = cx18_read_reg(cx, SW1_INT_STATUS) & cx->sw1_irq_mask;
sw2 = cx18_read_reg(cx, SW2_INT_STATUS) & cx->sw2_irq_mask;
hw2 = cx18_read_reg(cx, HW2_INT_CLR_STATUS) & cx->hw2_irq_mask;
if (sw1)
cx18_write_reg_expect(cx, sw1, SW1_INT_STATUS, ~sw1, sw1);
if (sw2)
cx18_write_reg_expect(cx, sw2, SW2_INT_STATUS, ~sw2, sw2);
if (hw2)
cx18_write_reg_expect(cx, hw2, HW2_INT_CLR_STATUS, ~hw2, hw2);
if (sw1 || sw2 || hw2)
CX18_DEBUG_HI_IRQ("received interrupts "
"SW1: %x SW2: %x HW2: %x\n", sw1, sw2, hw2);
/*
* SW1 responses have to happen first. The sending XPU times out the
* incoming mailboxes on us rather rapidly.
*/
if (sw1)
epu_cmd(cx, sw1);
/* To do: interrupt-based I2C handling
if (hw2 & (HW2_I2C1_INT|HW2_I2C2_INT)) {
}
*/
if (sw2)
xpu_ack(cx, sw2);
return (sw1 || sw2 || hw2) ? IRQ_HANDLED : IRQ_NONE;
}
| gpl-2.0 |
erasmux/pyramid-gb-kernel | drivers/input/keyboard/gpio_keys.c | 509 | 16048 | /*
* Driver for keys on GPIO lines capable of generating interrupts.
*
* Copyright 2005 Phil Blundell
*
* 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/init.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/sched.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <linux/workqueue.h>
#include <linux/gpio.h>
struct gpio_button_data {
struct gpio_keys_button *button;
struct input_dev *input;
struct timer_list timer;
struct work_struct work;
bool disabled;
};
struct gpio_keys_drvdata {
struct input_dev *input;
struct mutex disable_lock;
unsigned int n_buttons;
struct gpio_button_data data[0];
};
/*
* SYSFS interface for enabling/disabling keys and switches:
*
* There are 4 attributes under /sys/devices/platform/gpio-keys/
* keys [ro] - bitmap of keys (EV_KEY) which can be
* disabled
* switches [ro] - bitmap of switches (EV_SW) which can be
* disabled
* disabled_keys [rw] - bitmap of keys currently disabled
* disabled_switches [rw] - bitmap of switches currently disabled
*
* Userland can change these values and hence disable event generation
* for each key (or switch). Disabling a key means its interrupt line
* is disabled.
*
* For example, if we have following switches set up as gpio-keys:
* SW_DOCK = 5
* SW_CAMERA_LENS_COVER = 9
* SW_KEYPAD_SLIDE = 10
* SW_FRONT_PROXIMITY = 11
* This is read from switches:
* 11-9,5
* Next we want to disable proximity (11) and dock (5), we write:
* 11,5
* to file disabled_switches. Now proximity and dock IRQs are disabled.
* This can be verified by reading the file disabled_switches:
* 11,5
* If we now want to enable proximity (11) switch we write:
* 5
* to disabled_switches.
*
* We can disable only those keys which don't allow sharing the irq.
*/
/**
* get_n_events_by_type() - returns maximum number of events per @type
* @type: type of button (%EV_KEY, %EV_SW)
*
* Return value of this function can be used to allocate bitmap
* large enough to hold all bits for given type.
*/
static inline int get_n_events_by_type(int type)
{
BUG_ON(type != EV_SW && type != EV_KEY);
return (type == EV_KEY) ? KEY_CNT : SW_CNT;
}
/**
* gpio_keys_disable_button() - disables given GPIO button
* @bdata: button data for button to be disabled
*
* Disables button pointed by @bdata. This is done by masking
* IRQ line. After this function is called, button won't generate
* input events anymore. Note that one can only disable buttons
* that don't share IRQs.
*
* Make sure that @bdata->disable_lock is locked when entering
* this function to avoid races when concurrent threads are
* disabling buttons at the same time.
*/
static void gpio_keys_disable_button(struct gpio_button_data *bdata)
{
if (!bdata->disabled) {
/*
* Disable IRQ and possible debouncing timer.
*/
disable_irq(gpio_to_irq(bdata->button->gpio));
if (bdata->button->debounce_interval)
del_timer_sync(&bdata->timer);
bdata->disabled = true;
}
}
/**
* gpio_keys_enable_button() - enables given GPIO button
* @bdata: button data for button to be disabled
*
* Enables given button pointed by @bdata.
*
* Make sure that @bdata->disable_lock is locked when entering
* this function to avoid races with concurrent threads trying
* to enable the same button at the same time.
*/
static void gpio_keys_enable_button(struct gpio_button_data *bdata)
{
if (bdata->disabled) {
enable_irq(gpio_to_irq(bdata->button->gpio));
bdata->disabled = false;
}
}
/**
* gpio_keys_attr_show_helper() - fill in stringified bitmap of buttons
* @ddata: pointer to drvdata
* @buf: buffer where stringified bitmap is written
* @type: button type (%EV_KEY, %EV_SW)
* @only_disabled: does caller want only those buttons that are
* currently disabled or all buttons that can be
* disabled
*
* This function writes buttons that can be disabled to @buf. If
* @only_disabled is true, then @buf contains only those buttons
* that are currently disabled. Returns 0 on success or negative
* errno on failure.
*/
static ssize_t gpio_keys_attr_show_helper(struct gpio_keys_drvdata *ddata,
char *buf, unsigned int type,
bool only_disabled)
{
int n_events = get_n_events_by_type(type);
unsigned long *bits;
ssize_t ret;
int i;
bits = kcalloc(BITS_TO_LONGS(n_events), sizeof(*bits), GFP_KERNEL);
if (!bits)
return -ENOMEM;
for (i = 0; i < ddata->n_buttons; i++) {
struct gpio_button_data *bdata = &ddata->data[i];
if (bdata->button->type != type)
continue;
if (only_disabled && !bdata->disabled)
continue;
__set_bit(bdata->button->code, bits);
}
ret = bitmap_scnlistprintf(buf, PAGE_SIZE - 2, bits, n_events);
buf[ret++] = '\n';
buf[ret] = '\0';
kfree(bits);
return ret;
}
/**
* gpio_keys_attr_store_helper() - enable/disable buttons based on given bitmap
* @ddata: pointer to drvdata
* @buf: buffer from userspace that contains stringified bitmap
* @type: button type (%EV_KEY, %EV_SW)
*
* This function parses stringified bitmap from @buf and disables/enables
* GPIO buttons accordinly. Returns 0 on success and negative error
* on failure.
*/
static ssize_t gpio_keys_attr_store_helper(struct gpio_keys_drvdata *ddata,
const char *buf, unsigned int type)
{
int n_events = get_n_events_by_type(type);
unsigned long *bits;
ssize_t error;
int i;
bits = kcalloc(BITS_TO_LONGS(n_events), sizeof(*bits), GFP_KERNEL);
if (!bits)
return -ENOMEM;
error = bitmap_parselist(buf, bits, n_events);
if (error)
goto out;
/* First validate */
for (i = 0; i < ddata->n_buttons; i++) {
struct gpio_button_data *bdata = &ddata->data[i];
if (bdata->button->type != type)
continue;
if (test_bit(bdata->button->code, bits) &&
!bdata->button->can_disable) {
error = -EINVAL;
goto out;
}
}
mutex_lock(&ddata->disable_lock);
for (i = 0; i < ddata->n_buttons; i++) {
struct gpio_button_data *bdata = &ddata->data[i];
if (bdata->button->type != type)
continue;
if (test_bit(bdata->button->code, bits))
gpio_keys_disable_button(bdata);
else
gpio_keys_enable_button(bdata);
}
mutex_unlock(&ddata->disable_lock);
out:
kfree(bits);
return error;
}
#define ATTR_SHOW_FN(name, type, only_disabled) \
static ssize_t gpio_keys_show_##name(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct platform_device *pdev = to_platform_device(dev); \
struct gpio_keys_drvdata *ddata = platform_get_drvdata(pdev); \
\
return gpio_keys_attr_show_helper(ddata, buf, \
type, only_disabled); \
}
ATTR_SHOW_FN(keys, EV_KEY, false);
ATTR_SHOW_FN(switches, EV_SW, false);
ATTR_SHOW_FN(disabled_keys, EV_KEY, true);
ATTR_SHOW_FN(disabled_switches, EV_SW, true);
/*
* ATTRIBUTES:
*
* /sys/devices/platform/gpio-keys/keys [ro]
* /sys/devices/platform/gpio-keys/switches [ro]
*/
static DEVICE_ATTR(keys, S_IRUGO, gpio_keys_show_keys, NULL);
static DEVICE_ATTR(switches, S_IRUGO, gpio_keys_show_switches, NULL);
#define ATTR_STORE_FN(name, type) \
static ssize_t gpio_keys_store_##name(struct device *dev, \
struct device_attribute *attr, \
const char *buf, \
size_t count) \
{ \
struct platform_device *pdev = to_platform_device(dev); \
struct gpio_keys_drvdata *ddata = platform_get_drvdata(pdev); \
ssize_t error; \
\
error = gpio_keys_attr_store_helper(ddata, buf, type); \
if (error) \
return error; \
\
return count; \
}
ATTR_STORE_FN(disabled_keys, EV_KEY);
ATTR_STORE_FN(disabled_switches, EV_SW);
/*
* ATTRIBUTES:
*
* /sys/devices/platform/gpio-keys/disabled_keys [rw]
* /sys/devices/platform/gpio-keys/disables_switches [rw]
*/
static DEVICE_ATTR(disabled_keys, S_IWUSR | S_IRUGO,
gpio_keys_show_disabled_keys,
gpio_keys_store_disabled_keys);
static DEVICE_ATTR(disabled_switches, S_IWUSR | S_IRUGO,
gpio_keys_show_disabled_switches,
gpio_keys_store_disabled_switches);
static struct attribute *gpio_keys_attrs[] = {
&dev_attr_keys.attr,
&dev_attr_switches.attr,
&dev_attr_disabled_keys.attr,
&dev_attr_disabled_switches.attr,
NULL,
};
static struct attribute_group gpio_keys_attr_group = {
.attrs = gpio_keys_attrs,
};
static void gpio_keys_report_event(struct gpio_button_data *bdata)
{
struct gpio_keys_button *button = bdata->button;
struct input_dev *input = bdata->input;
unsigned int type = button->type ?: EV_KEY;
int state = (gpio_get_value(button->gpio) ? 1 : 0) ^ button->active_low;
input_event(input, type, button->code, !!state);
input_sync(input);
}
static void gpio_keys_work_func(struct work_struct *work)
{
struct gpio_button_data *bdata =
container_of(work, struct gpio_button_data, work);
gpio_keys_report_event(bdata);
}
static void gpio_keys_timer(unsigned long _data)
{
struct gpio_button_data *data = (struct gpio_button_data *)_data;
schedule_work(&data->work);
}
static irqreturn_t gpio_keys_isr(int irq, void *dev_id)
{
struct gpio_button_data *bdata = dev_id;
struct gpio_keys_button *button = bdata->button;
BUG_ON(irq != gpio_to_irq(button->gpio));
if (button->debounce_interval)
mod_timer(&bdata->timer,
jiffies + msecs_to_jiffies(button->debounce_interval));
else
schedule_work(&bdata->work);
return IRQ_HANDLED;
}
static int __devinit gpio_keys_setup_key(struct platform_device *pdev,
struct gpio_button_data *bdata,
struct gpio_keys_button *button)
{
char *desc = button->desc ? button->desc : "gpio_keys";
struct device *dev = &pdev->dev;
unsigned long irqflags;
int irq, error;
setup_timer(&bdata->timer, gpio_keys_timer, (unsigned long)bdata);
INIT_WORK(&bdata->work, gpio_keys_work_func);
error = gpio_request(button->gpio, desc);
if (error < 0) {
dev_err(dev, "failed to request GPIO %d, error %d\n",
button->gpio, error);
goto fail2;
}
error = gpio_direction_input(button->gpio);
if (error < 0) {
dev_err(dev, "failed to configure"
" direction for GPIO %d, error %d\n",
button->gpio, error);
goto fail3;
}
irq = gpio_to_irq(button->gpio);
if (irq < 0) {
error = irq;
dev_err(dev, "Unable to get irq number for GPIO %d, error %d\n",
button->gpio, error);
goto fail3;
}
irqflags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
/*
* If platform has specified that the button can be disabled,
* we don't want it to share the interrupt line.
*/
if (!button->can_disable)
irqflags |= IRQF_SHARED;
error = request_irq(irq, gpio_keys_isr, irqflags, desc, bdata);
if (error) {
dev_err(dev, "Unable to claim irq %d; error %d\n",
irq, error);
goto fail3;
}
return 0;
fail3:
gpio_free(button->gpio);
fail2:
return error;
}
static int __devinit gpio_keys_probe(struct platform_device *pdev)
{
struct gpio_keys_platform_data *pdata = pdev->dev.platform_data;
struct gpio_keys_drvdata *ddata;
struct device *dev = &pdev->dev;
struct input_dev *input;
int i, error;
int wakeup = 0;
ddata = kzalloc(sizeof(struct gpio_keys_drvdata) +
pdata->nbuttons * sizeof(struct gpio_button_data),
GFP_KERNEL);
input = input_allocate_device();
if (!ddata || !input) {
dev_err(dev, "failed to allocate state\n");
error = -ENOMEM;
goto fail1;
}
ddata->input = input;
ddata->n_buttons = pdata->nbuttons;
mutex_init(&ddata->disable_lock);
platform_set_drvdata(pdev, ddata);
input->name = pdev->name;
input->phys = "gpio-keys/input0";
input->dev.parent = &pdev->dev;
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
/* Enable auto repeat feature of Linux input subsystem */
if (pdata->rep)
__set_bit(EV_REP, input->evbit);
for (i = 0; i < pdata->nbuttons; i++) {
struct gpio_keys_button *button = &pdata->buttons[i];
struct gpio_button_data *bdata = &ddata->data[i];
unsigned int type = button->type ?: EV_KEY;
bdata->input = input;
bdata->button = button;
error = gpio_keys_setup_key(pdev, bdata, button);
if (error)
goto fail2;
if (button->wakeup)
wakeup = 1;
input_set_capability(input, type, button->code);
}
error = sysfs_create_group(&pdev->dev.kobj, &gpio_keys_attr_group);
if (error) {
dev_err(dev, "Unable to export keys/switches, error: %d\n",
error);
goto fail2;
}
error = input_register_device(input);
if (error) {
dev_err(dev, "Unable to register input device, error: %d\n",
error);
goto fail3;
}
/* get current state of buttons */
for (i = 0; i < pdata->nbuttons; i++)
gpio_keys_report_event(&ddata->data[i]);
input_sync(input);
device_init_wakeup(&pdev->dev, wakeup);
return 0;
fail3:
sysfs_remove_group(&pdev->dev.kobj, &gpio_keys_attr_group);
fail2:
while (--i >= 0) {
free_irq(gpio_to_irq(pdata->buttons[i].gpio), &ddata->data[i]);
if (pdata->buttons[i].debounce_interval)
del_timer_sync(&ddata->data[i].timer);
cancel_work_sync(&ddata->data[i].work);
gpio_free(pdata->buttons[i].gpio);
}
platform_set_drvdata(pdev, NULL);
fail1:
input_free_device(input);
kfree(ddata);
return error;
}
static int __devexit gpio_keys_remove(struct platform_device *pdev)
{
struct gpio_keys_platform_data *pdata = pdev->dev.platform_data;
struct gpio_keys_drvdata *ddata = platform_get_drvdata(pdev);
struct input_dev *input = ddata->input;
int i;
sysfs_remove_group(&pdev->dev.kobj, &gpio_keys_attr_group);
device_init_wakeup(&pdev->dev, 0);
for (i = 0; i < pdata->nbuttons; i++) {
int irq = gpio_to_irq(pdata->buttons[i].gpio);
free_irq(irq, &ddata->data[i]);
if (pdata->buttons[i].debounce_interval)
del_timer_sync(&ddata->data[i].timer);
cancel_work_sync(&ddata->data[i].work);
gpio_free(pdata->buttons[i].gpio);
}
input_unregister_device(input);
return 0;
}
#ifdef CONFIG_PM
static int gpio_keys_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct gpio_keys_platform_data *pdata = pdev->dev.platform_data;
int i;
if (device_may_wakeup(&pdev->dev)) {
for (i = 0; i < pdata->nbuttons; i++) {
struct gpio_keys_button *button = &pdata->buttons[i];
if (button->wakeup) {
int irq = gpio_to_irq(button->gpio);
enable_irq_wake(irq);
}
}
}
return 0;
}
static int gpio_keys_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct gpio_keys_drvdata *ddata = platform_get_drvdata(pdev);
struct gpio_keys_platform_data *pdata = pdev->dev.platform_data;
int i;
for (i = 0; i < pdata->nbuttons; i++) {
struct gpio_keys_button *button = &pdata->buttons[i];
if (button->wakeup && device_may_wakeup(&pdev->dev)) {
int irq = gpio_to_irq(button->gpio);
disable_irq_wake(irq);
}
gpio_keys_report_event(&ddata->data[i]);
}
input_sync(ddata->input);
return 0;
}
static const struct dev_pm_ops gpio_keys_pm_ops = {
.suspend = gpio_keys_suspend,
.resume = gpio_keys_resume,
};
#endif
static struct platform_driver gpio_keys_device_driver = {
.probe = gpio_keys_probe,
.remove = __devexit_p(gpio_keys_remove),
.driver = {
.name = "gpio-keys",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &gpio_keys_pm_ops,
#endif
}
};
static int __init gpio_keys_init(void)
{
return platform_driver_register(&gpio_keys_device_driver);
}
static void __exit gpio_keys_exit(void)
{
platform_driver_unregister(&gpio_keys_device_driver);
}
module_init(gpio_keys_init);
module_exit(gpio_keys_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Phil Blundell <pb@handhelds.org>");
MODULE_DESCRIPTION("Keyboard driver for CPU GPIOs");
MODULE_ALIAS("platform:gpio-keys");
| gpl-2.0 |
ISTweak/android_kernel_sharp_is03 | drivers/gpu/drm/radeon/r600_blit_shaders.c | 509 | 14039 |
#include <linux/types.h>
#include <linux/kernel.h>
const u32 r6xx_default_state[] =
{
0xc0002400,
0x00000000,
0xc0012800,
0x80000000,
0x80000000,
0xc0004600,
0x00000016,
0xc0016800,
0x00000010,
0x00028000,
0xc0016800,
0x00000010,
0x00008000,
0xc0016800,
0x00000542,
0x07000003,
0xc0016800,
0x000005c5,
0x00000000,
0xc0016800,
0x00000363,
0x00000000,
0xc0016800,
0x0000060c,
0x82000000,
0xc0016800,
0x0000060e,
0x01020204,
0xc0016f00,
0x00000000,
0x00000000,
0xc0016f00,
0x00000001,
0x00000000,
0xc0096900,
0x0000022a,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0016900,
0x00000004,
0x00000000,
0xc0016900,
0x0000000a,
0x00000000,
0xc0016900,
0x0000000b,
0x00000000,
0xc0016900,
0x0000010c,
0x00000000,
0xc0016900,
0x0000010d,
0x00000000,
0xc0016900,
0x00000200,
0x00000000,
0xc0016900,
0x00000343,
0x00000060,
0xc0016900,
0x00000344,
0x00000040,
0xc0016900,
0x00000351,
0x0000aa00,
0xc0016900,
0x00000104,
0x00000000,
0xc0016900,
0x0000010e,
0x00000000,
0xc0046900,
0x00000105,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0036900,
0x00000109,
0x00000000,
0x00000000,
0x00000000,
0xc0046900,
0x0000030c,
0x01000000,
0x00000000,
0x00000000,
0x00000000,
0xc0046900,
0x00000048,
0x3f800000,
0x00000000,
0x3f800000,
0x3f800000,
0xc0016900,
0x0000008e,
0x0000000f,
0xc0016900,
0x00000080,
0x00000000,
0xc0016900,
0x00000083,
0x0000ffff,
0xc0016900,
0x00000084,
0x00000000,
0xc0016900,
0x00000085,
0x20002000,
0xc0016900,
0x00000086,
0x00000000,
0xc0016900,
0x00000087,
0x20002000,
0xc0016900,
0x00000088,
0x00000000,
0xc0016900,
0x00000089,
0x20002000,
0xc0016900,
0x0000008a,
0x00000000,
0xc0016900,
0x0000008b,
0x20002000,
0xc0016900,
0x0000008c,
0x00000000,
0xc0016900,
0x00000094,
0x80000000,
0xc0016900,
0x00000095,
0x20002000,
0xc0026900,
0x000000b4,
0x00000000,
0x3f800000,
0xc0016900,
0x00000096,
0x80000000,
0xc0016900,
0x00000097,
0x20002000,
0xc0026900,
0x000000b6,
0x00000000,
0x3f800000,
0xc0016900,
0x00000098,
0x80000000,
0xc0016900,
0x00000099,
0x20002000,
0xc0026900,
0x000000b8,
0x00000000,
0x3f800000,
0xc0016900,
0x0000009a,
0x80000000,
0xc0016900,
0x0000009b,
0x20002000,
0xc0026900,
0x000000ba,
0x00000000,
0x3f800000,
0xc0016900,
0x0000009c,
0x80000000,
0xc0016900,
0x0000009d,
0x20002000,
0xc0026900,
0x000000bc,
0x00000000,
0x3f800000,
0xc0016900,
0x0000009e,
0x80000000,
0xc0016900,
0x0000009f,
0x20002000,
0xc0026900,
0x000000be,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a0,
0x80000000,
0xc0016900,
0x000000a1,
0x20002000,
0xc0026900,
0x000000c0,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a2,
0x80000000,
0xc0016900,
0x000000a3,
0x20002000,
0xc0026900,
0x000000c2,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a4,
0x80000000,
0xc0016900,
0x000000a5,
0x20002000,
0xc0026900,
0x000000c4,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a6,
0x80000000,
0xc0016900,
0x000000a7,
0x20002000,
0xc0026900,
0x000000c6,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a8,
0x80000000,
0xc0016900,
0x000000a9,
0x20002000,
0xc0026900,
0x000000c8,
0x00000000,
0x3f800000,
0xc0016900,
0x000000aa,
0x80000000,
0xc0016900,
0x000000ab,
0x20002000,
0xc0026900,
0x000000ca,
0x00000000,
0x3f800000,
0xc0016900,
0x000000ac,
0x80000000,
0xc0016900,
0x000000ad,
0x20002000,
0xc0026900,
0x000000cc,
0x00000000,
0x3f800000,
0xc0016900,
0x000000ae,
0x80000000,
0xc0016900,
0x000000af,
0x20002000,
0xc0026900,
0x000000ce,
0x00000000,
0x3f800000,
0xc0016900,
0x000000b0,
0x80000000,
0xc0016900,
0x000000b1,
0x20002000,
0xc0026900,
0x000000d0,
0x00000000,
0x3f800000,
0xc0016900,
0x000000b2,
0x80000000,
0xc0016900,
0x000000b3,
0x20002000,
0xc0026900,
0x000000d2,
0x00000000,
0x3f800000,
0xc0016900,
0x00000293,
0x00004010,
0xc0016900,
0x00000300,
0x00000000,
0xc0016900,
0x00000301,
0x00000000,
0xc0016900,
0x00000312,
0xffffffff,
0xc0016900,
0x00000307,
0x00000000,
0xc0016900,
0x00000308,
0x00000000,
0xc0016900,
0x00000283,
0x00000000,
0xc0016900,
0x00000292,
0x00000000,
0xc0066900,
0x0000010f,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0016900,
0x00000206,
0x00000000,
0xc0016900,
0x00000207,
0x00000000,
0xc0016900,
0x00000208,
0x00000000,
0xc0046900,
0x00000303,
0x3f800000,
0x3f800000,
0x3f800000,
0x3f800000,
0xc0016900,
0x00000205,
0x00000004,
0xc0016900,
0x00000280,
0x00000000,
0xc0016900,
0x00000281,
0x00000000,
0xc0016900,
0x0000037e,
0x00000000,
0xc0016900,
0x00000382,
0x00000000,
0xc0016900,
0x00000380,
0x00000000,
0xc0016900,
0x00000383,
0x00000000,
0xc0016900,
0x00000381,
0x00000000,
0xc0016900,
0x00000282,
0x00000008,
0xc0016900,
0x00000302,
0x0000002d,
0xc0016900,
0x0000037f,
0x00000000,
0xc0016900,
0x000001b2,
0x00000000,
0xc0016900,
0x000001b6,
0x00000000,
0xc0016900,
0x000001b7,
0x00000000,
0xc0016900,
0x000001b8,
0x00000000,
0xc0016900,
0x000001b9,
0x00000000,
0xc0016900,
0x00000225,
0x00000000,
0xc0016900,
0x00000229,
0x00000000,
0xc0016900,
0x00000237,
0x00000000,
0xc0016900,
0x00000100,
0x00000800,
0xc0016900,
0x00000101,
0x00000000,
0xc0016900,
0x00000102,
0x00000000,
0xc0016900,
0x000002a8,
0x00000000,
0xc0016900,
0x000002a9,
0x00000000,
0xc0016900,
0x00000103,
0x00000000,
0xc0016900,
0x00000284,
0x00000000,
0xc0016900,
0x00000290,
0x00000000,
0xc0016900,
0x00000285,
0x00000000,
0xc0016900,
0x00000286,
0x00000000,
0xc0016900,
0x00000287,
0x00000000,
0xc0016900,
0x00000288,
0x00000000,
0xc0016900,
0x00000289,
0x00000000,
0xc0016900,
0x0000028a,
0x00000000,
0xc0016900,
0x0000028b,
0x00000000,
0xc0016900,
0x0000028c,
0x00000000,
0xc0016900,
0x0000028d,
0x00000000,
0xc0016900,
0x0000028e,
0x00000000,
0xc0016900,
0x0000028f,
0x00000000,
0xc0016900,
0x000002a1,
0x00000000,
0xc0016900,
0x000002a5,
0x00000000,
0xc0016900,
0x000002ac,
0x00000000,
0xc0016900,
0x000002ad,
0x00000000,
0xc0016900,
0x000002ae,
0x00000000,
0xc0016900,
0x000002c8,
0x00000000,
0xc0016900,
0x00000206,
0x00000100,
0xc0016900,
0x00000204,
0x00010000,
0xc0036e00,
0x00000000,
0x00000012,
0x00000000,
0x00000000,
0xc0016900,
0x0000008f,
0x0000000f,
0xc0016900,
0x000001e8,
0x00000001,
0xc0016900,
0x00000202,
0x00cc0000,
0xc0016900,
0x00000205,
0x00000244,
0xc0016900,
0x00000203,
0x00000210,
0xc0016900,
0x000001b1,
0x00000000,
0xc0016900,
0x00000185,
0x00000000,
0xc0016900,
0x000001b3,
0x00000001,
0xc0016900,
0x000001b4,
0x00000000,
0xc0016900,
0x00000191,
0x00000b00,
0xc0016900,
0x000001b5,
0x00000000,
};
const u32 r7xx_default_state[] =
{
0xc0012800,
0x80000000,
0x80000000,
0xc0004600,
0x00000016,
0xc0016800,
0x00000010,
0x00028000,
0xc0016800,
0x00000010,
0x00008000,
0xc0016800,
0x00000542,
0x07000002,
0xc0016800,
0x000005c5,
0x00000000,
0xc0016800,
0x00000363,
0x00004000,
0xc0016800,
0x0000060c,
0x00000000,
0xc0016800,
0x0000060e,
0x00420204,
0xc0016f00,
0x00000000,
0x00000000,
0xc0016f00,
0x00000001,
0x00000000,
0xc0096900,
0x0000022a,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0016900,
0x00000004,
0x00000000,
0xc0016900,
0x0000000a,
0x00000000,
0xc0016900,
0x0000000b,
0x00000000,
0xc0016900,
0x0000010c,
0x00000000,
0xc0016900,
0x0000010d,
0x00000000,
0xc0016900,
0x00000200,
0x00000000,
0xc0016900,
0x00000343,
0x00000060,
0xc0016900,
0x00000344,
0x00000000,
0xc0016900,
0x00000351,
0x0000aa00,
0xc0016900,
0x00000104,
0x00000000,
0xc0016900,
0x0000010e,
0x00000000,
0xc0046900,
0x00000105,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0046900,
0x0000030c,
0x01000000,
0x00000000,
0x00000000,
0x00000000,
0xc0016900,
0x0000008e,
0x0000000f,
0xc0016900,
0x00000080,
0x00000000,
0xc0016900,
0x00000083,
0x0000ffff,
0xc0016900,
0x00000084,
0x00000000,
0xc0016900,
0x00000085,
0x20002000,
0xc0016900,
0x00000086,
0x00000000,
0xc0016900,
0x00000087,
0x20002000,
0xc0016900,
0x00000088,
0x00000000,
0xc0016900,
0x00000089,
0x20002000,
0xc0016900,
0x0000008a,
0x00000000,
0xc0016900,
0x0000008b,
0x20002000,
0xc0016900,
0x0000008c,
0xaaaaaaaa,
0xc0016900,
0x00000094,
0x80000000,
0xc0016900,
0x00000095,
0x20002000,
0xc0026900,
0x000000b4,
0x00000000,
0x3f800000,
0xc0016900,
0x00000096,
0x80000000,
0xc0016900,
0x00000097,
0x20002000,
0xc0026900,
0x000000b6,
0x00000000,
0x3f800000,
0xc0016900,
0x00000098,
0x80000000,
0xc0016900,
0x00000099,
0x20002000,
0xc0026900,
0x000000b8,
0x00000000,
0x3f800000,
0xc0016900,
0x0000009a,
0x80000000,
0xc0016900,
0x0000009b,
0x20002000,
0xc0026900,
0x000000ba,
0x00000000,
0x3f800000,
0xc0016900,
0x0000009c,
0x80000000,
0xc0016900,
0x0000009d,
0x20002000,
0xc0026900,
0x000000bc,
0x00000000,
0x3f800000,
0xc0016900,
0x0000009e,
0x80000000,
0xc0016900,
0x0000009f,
0x20002000,
0xc0026900,
0x000000be,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a0,
0x80000000,
0xc0016900,
0x000000a1,
0x20002000,
0xc0026900,
0x000000c0,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a2,
0x80000000,
0xc0016900,
0x000000a3,
0x20002000,
0xc0026900,
0x000000c2,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a4,
0x80000000,
0xc0016900,
0x000000a5,
0x20002000,
0xc0026900,
0x000000c4,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a6,
0x80000000,
0xc0016900,
0x000000a7,
0x20002000,
0xc0026900,
0x000000c6,
0x00000000,
0x3f800000,
0xc0016900,
0x000000a8,
0x80000000,
0xc0016900,
0x000000a9,
0x20002000,
0xc0026900,
0x000000c8,
0x00000000,
0x3f800000,
0xc0016900,
0x000000aa,
0x80000000,
0xc0016900,
0x000000ab,
0x20002000,
0xc0026900,
0x000000ca,
0x00000000,
0x3f800000,
0xc0016900,
0x000000ac,
0x80000000,
0xc0016900,
0x000000ad,
0x20002000,
0xc0026900,
0x000000cc,
0x00000000,
0x3f800000,
0xc0016900,
0x000000ae,
0x80000000,
0xc0016900,
0x000000af,
0x20002000,
0xc0026900,
0x000000ce,
0x00000000,
0x3f800000,
0xc0016900,
0x000000b0,
0x80000000,
0xc0016900,
0x000000b1,
0x20002000,
0xc0026900,
0x000000d0,
0x00000000,
0x3f800000,
0xc0016900,
0x000000b2,
0x80000000,
0xc0016900,
0x000000b3,
0x20002000,
0xc0026900,
0x000000d2,
0x00000000,
0x3f800000,
0xc0016900,
0x00000293,
0x00514000,
0xc0016900,
0x00000300,
0x00000000,
0xc0016900,
0x00000301,
0x00000000,
0xc0016900,
0x00000312,
0xffffffff,
0xc0016900,
0x00000307,
0x00000000,
0xc0016900,
0x00000308,
0x00000000,
0xc0016900,
0x00000283,
0x00000000,
0xc0016900,
0x00000292,
0x00000000,
0xc0066900,
0x0000010f,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0016900,
0x00000206,
0x00000000,
0xc0016900,
0x00000207,
0x00000000,
0xc0016900,
0x00000208,
0x00000000,
0xc0046900,
0x00000303,
0x3f800000,
0x3f800000,
0x3f800000,
0x3f800000,
0xc0016900,
0x00000205,
0x00000004,
0xc0016900,
0x00000280,
0x00000000,
0xc0016900,
0x00000281,
0x00000000,
0xc0016900,
0x0000037e,
0x00000000,
0xc0016900,
0x00000382,
0x00000000,
0xc0016900,
0x00000380,
0x00000000,
0xc0016900,
0x00000383,
0x00000000,
0xc0016900,
0x00000381,
0x00000000,
0xc0016900,
0x00000282,
0x00000008,
0xc0016900,
0x00000302,
0x0000002d,
0xc0016900,
0x0000037f,
0x00000000,
0xc0016900,
0x000001b2,
0x00000001,
0xc0016900,
0x000001b6,
0x00000000,
0xc0016900,
0x000001b7,
0x00000000,
0xc0016900,
0x000001b8,
0x00000000,
0xc0016900,
0x000001b9,
0x00000000,
0xc0016900,
0x00000225,
0x00000000,
0xc0016900,
0x00000229,
0x00000000,
0xc0016900,
0x00000237,
0x00000000,
0xc0016900,
0x00000100,
0x00000800,
0xc0016900,
0x00000101,
0x00000000,
0xc0016900,
0x00000102,
0x00000000,
0xc0016900,
0x000002a8,
0x00000000,
0xc0016900,
0x000002a9,
0x00000000,
0xc0016900,
0x00000103,
0x00000000,
0xc0016900,
0x00000284,
0x00000000,
0xc0016900,
0x00000290,
0x00000000,
0xc0016900,
0x00000285,
0x00000000,
0xc0016900,
0x00000286,
0x00000000,
0xc0016900,
0x00000287,
0x00000000,
0xc0016900,
0x00000288,
0x00000000,
0xc0016900,
0x00000289,
0x00000000,
0xc0016900,
0x0000028a,
0x00000000,
0xc0016900,
0x0000028b,
0x00000000,
0xc0016900,
0x0000028c,
0x00000000,
0xc0016900,
0x0000028d,
0x00000000,
0xc0016900,
0x0000028e,
0x00000000,
0xc0016900,
0x0000028f,
0x00000000,
0xc0016900,
0x000002a1,
0x00000000,
0xc0016900,
0x000002a5,
0x00000000,
0xc0016900,
0x000002ac,
0x00000000,
0xc0016900,
0x000002ad,
0x00000000,
0xc0016900,
0x000002ae,
0x00000000,
0xc0016900,
0x000002c8,
0x00000000,
0xc0016900,
0x00000206,
0x00000100,
0xc0016900,
0x00000204,
0x00010000,
0xc0036e00,
0x00000000,
0x00000012,
0x00000000,
0x00000000,
0xc0016900,
0x0000008f,
0x0000000f,
0xc0016900,
0x000001e8,
0x00000001,
0xc0016900,
0x00000202,
0x00cc0000,
0xc0016900,
0x00000205,
0x00000244,
0xc0016900,
0x00000203,
0x00000210,
0xc0016900,
0x000001b1,
0x00000000,
0xc0016900,
0x00000185,
0x00000000,
0xc0016900,
0x000001b3,
0x00000001,
0xc0016900,
0x000001b4,
0x00000000,
0xc0016900,
0x00000191,
0x00000b00,
0xc0016900,
0x000001b5,
0x00000000,
};
/* same for r6xx/r7xx */
const u32 r6xx_vs[] =
{
0x00000004,
0x81000000,
0x0000203c,
0x94000b08,
0x00004000,
0x14200b1a,
0x00000000,
0x00000000,
0x3c000000,
0x68cd1000,
0x00080000,
0x00000000,
};
const u32 r6xx_ps[] =
{
0x00000002,
0x80800000,
0x00000000,
0x94200688,
0x00000010,
0x000d1000,
0xb0800000,
0x00000000,
};
const u32 r6xx_ps_size = ARRAY_SIZE(r6xx_ps);
const u32 r6xx_vs_size = ARRAY_SIZE(r6xx_vs);
const u32 r6xx_default_size = ARRAY_SIZE(r6xx_default_state);
const u32 r7xx_default_size = ARRAY_SIZE(r7xx_default_state);
| gpl-2.0 |
SiennaStellar/linux-3.10.20_kelleni | drivers/hwmon/max6650.c | 2301 | 19847 | /*
* max6650.c - Part of lm_sensors, Linux kernel modules for hardware
* monitoring.
*
* (C) 2007 by Hans J. Koch <hjk@hansjkoch.de>
*
* based on code written by John Morris <john.morris@spirentcom.com>
* Copyright (c) 2003 Spirent Communications
* and Claus Gindhart <claus.gindhart@kontron.com>
*
* This module has only been tested with the MAX6650 chip. It should
* also work with the MAX6651. It does not distinguish max6650 and max6651
* chips.
*
* The datasheet was last seen at:
*
* http://pdfserv.maxim-ic.com/en/ds/MAX6650-MAX6651.pdf
*
* 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 <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
/*
* Insmod parameters
*/
/* fan_voltage: 5=5V fan, 12=12V fan, 0=don't change */
static int fan_voltage;
/* prescaler: Possible values are 1, 2, 4, 8, 16 or 0 for don't change */
static int prescaler;
/* clock: The clock frequency of the chip the driver should assume */
static int clock = 254000;
module_param(fan_voltage, int, S_IRUGO);
module_param(prescaler, int, S_IRUGO);
module_param(clock, int, S_IRUGO);
/*
* MAX 6650/6651 registers
*/
#define MAX6650_REG_SPEED 0x00
#define MAX6650_REG_CONFIG 0x02
#define MAX6650_REG_GPIO_DEF 0x04
#define MAX6650_REG_DAC 0x06
#define MAX6650_REG_ALARM_EN 0x08
#define MAX6650_REG_ALARM 0x0A
#define MAX6650_REG_TACH0 0x0C
#define MAX6650_REG_TACH1 0x0E
#define MAX6650_REG_TACH2 0x10
#define MAX6650_REG_TACH3 0x12
#define MAX6650_REG_GPIO_STAT 0x14
#define MAX6650_REG_COUNT 0x16
/*
* Config register bits
*/
#define MAX6650_CFG_V12 0x08
#define MAX6650_CFG_PRESCALER_MASK 0x07
#define MAX6650_CFG_PRESCALER_2 0x01
#define MAX6650_CFG_PRESCALER_4 0x02
#define MAX6650_CFG_PRESCALER_8 0x03
#define MAX6650_CFG_PRESCALER_16 0x04
#define MAX6650_CFG_MODE_MASK 0x30
#define MAX6650_CFG_MODE_ON 0x00
#define MAX6650_CFG_MODE_OFF 0x10
#define MAX6650_CFG_MODE_CLOSED_LOOP 0x20
#define MAX6650_CFG_MODE_OPEN_LOOP 0x30
#define MAX6650_COUNT_MASK 0x03
/*
* Alarm status register bits
*/
#define MAX6650_ALRM_MAX 0x01
#define MAX6650_ALRM_MIN 0x02
#define MAX6650_ALRM_TACH 0x04
#define MAX6650_ALRM_GPIO1 0x08
#define MAX6650_ALRM_GPIO2 0x10
/* Minimum and maximum values of the FAN-RPM */
#define FAN_RPM_MIN 240
#define FAN_RPM_MAX 30000
#define DIV_FROM_REG(reg) (1 << (reg & 7))
static int max6650_probe(struct i2c_client *client,
const struct i2c_device_id *id);
static int max6650_init_client(struct i2c_client *client);
static int max6650_remove(struct i2c_client *client);
static struct max6650_data *max6650_update_device(struct device *dev);
/*
* Driver data (common to all clients)
*/
static const struct i2c_device_id max6650_id[] = {
{ "max6650", 1 },
{ "max6651", 4 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max6650_id);
static struct i2c_driver max6650_driver = {
.driver = {
.name = "max6650",
},
.probe = max6650_probe,
.remove = max6650_remove,
.id_table = max6650_id,
};
/*
* Client data (each client gets its own)
*/
struct max6650_data {
struct device *hwmon_dev;
struct mutex update_lock;
int nr_fans;
char valid; /* zero until following fields are valid */
unsigned long last_updated; /* in jiffies */
/* register values */
u8 speed;
u8 config;
u8 tach[4];
u8 count;
u8 dac;
u8 alarm;
};
static ssize_t get_fan(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct max6650_data *data = max6650_update_device(dev);
int rpm;
/*
* Calculation details:
*
* Each tachometer counts over an interval given by the "count"
* register (0.25, 0.5, 1 or 2 seconds). This module assumes
* that the fans produce two pulses per revolution (this seems
* to be the most common).
*/
rpm = ((data->tach[attr->index] * 120) / DIV_FROM_REG(data->count));
return sprintf(buf, "%d\n", rpm);
}
/*
* Set the fan speed to the specified RPM (or read back the RPM setting).
* This works in closed loop mode only. Use pwm1 for open loop speed setting.
*
* The MAX6650/1 will automatically control fan speed when in closed loop
* mode.
*
* Assumptions:
*
* 1) The MAX6650/1 internal 254kHz clock frequency is set correctly. Use
* the clock module parameter if you need to fine tune this.
*
* 2) The prescaler (low three bits of the config register) has already
* been set to an appropriate value. Use the prescaler module parameter
* if your BIOS doesn't initialize the chip properly.
*
* The relevant equations are given on pages 21 and 22 of the datasheet.
*
* From the datasheet, the relevant equation when in regulation is:
*
* [fCLK / (128 x (KTACH + 1))] = 2 x FanSpeed / KSCALE
*
* where:
*
* fCLK is the oscillator frequency (either the 254kHz internal
* oscillator or the externally applied clock)
*
* KTACH is the value in the speed register
*
* FanSpeed is the speed of the fan in rps
*
* KSCALE is the prescaler value (1, 2, 4, 8, or 16)
*
* When reading, we need to solve for FanSpeed. When writing, we need to
* solve for KTACH.
*
* Note: this tachometer is completely separate from the tachometers
* used to measure the fan speeds. Only one fan's speed (fan1) is
* controlled.
*/
static ssize_t get_target(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct max6650_data *data = max6650_update_device(dev);
int kscale, ktach, rpm;
/*
* Use the datasheet equation:
*
* FanSpeed = KSCALE x fCLK / [256 x (KTACH + 1)]
*
* then multiply by 60 to give rpm.
*/
kscale = DIV_FROM_REG(data->config);
ktach = data->speed;
rpm = 60 * kscale * clock / (256 * (ktach + 1));
return sprintf(buf, "%d\n", rpm);
}
static ssize_t set_target(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct max6650_data *data = i2c_get_clientdata(client);
int kscale, ktach;
unsigned long rpm;
int err;
err = kstrtoul(buf, 10, &rpm);
if (err)
return err;
rpm = clamp_val(rpm, FAN_RPM_MIN, FAN_RPM_MAX);
/*
* Divide the required speed by 60 to get from rpm to rps, then
* use the datasheet equation:
*
* KTACH = [(fCLK x KSCALE) / (256 x FanSpeed)] - 1
*/
mutex_lock(&data->update_lock);
kscale = DIV_FROM_REG(data->config);
ktach = ((clock * kscale) / (256 * rpm / 60)) - 1;
if (ktach < 0)
ktach = 0;
if (ktach > 255)
ktach = 255;
data->speed = ktach;
i2c_smbus_write_byte_data(client, MAX6650_REG_SPEED, data->speed);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Get/set the fan speed in open loop mode using pwm1 sysfs file.
* Speed is given as a relative value from 0 to 255, where 255 is maximum
* speed. Note that this is done by writing directly to the chip's DAC,
* it won't change the closed loop speed set by fan1_target.
* Also note that due to rounding errors it is possible that you don't read
* back exactly the value you have set.
*/
static ssize_t get_pwm(struct device *dev, struct device_attribute *devattr,
char *buf)
{
int pwm;
struct max6650_data *data = max6650_update_device(dev);
/*
* Useful range for dac is 0-180 for 12V fans and 0-76 for 5V fans.
* Lower DAC values mean higher speeds.
*/
if (data->config & MAX6650_CFG_V12)
pwm = 255 - (255 * (int)data->dac)/180;
else
pwm = 255 - (255 * (int)data->dac)/76;
if (pwm < 0)
pwm = 0;
return sprintf(buf, "%d\n", pwm);
}
static ssize_t set_pwm(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct max6650_data *data = i2c_get_clientdata(client);
unsigned long pwm;
int err;
err = kstrtoul(buf, 10, &pwm);
if (err)
return err;
pwm = clamp_val(pwm, 0, 255);
mutex_lock(&data->update_lock);
if (data->config & MAX6650_CFG_V12)
data->dac = 180 - (180 * pwm)/255;
else
data->dac = 76 - (76 * pwm)/255;
i2c_smbus_write_byte_data(client, MAX6650_REG_DAC, data->dac);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Get/Set controller mode:
* Possible values:
* 0 = Fan always on
* 1 = Open loop, Voltage is set according to speed, not regulated.
* 2 = Closed loop, RPM for all fans regulated by fan1 tachometer
*/
static ssize_t get_enable(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct max6650_data *data = max6650_update_device(dev);
int mode = (data->config & MAX6650_CFG_MODE_MASK) >> 4;
int sysfs_modes[4] = {0, 1, 2, 1};
return sprintf(buf, "%d\n", sysfs_modes[mode]);
}
static ssize_t set_enable(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct max6650_data *data = i2c_get_clientdata(client);
int max6650_modes[3] = {0, 3, 2};
unsigned long mode;
int err;
err = kstrtoul(buf, 10, &mode);
if (err)
return err;
if (mode > 2)
return -EINVAL;
mutex_lock(&data->update_lock);
data->config = i2c_smbus_read_byte_data(client, MAX6650_REG_CONFIG);
data->config = (data->config & ~MAX6650_CFG_MODE_MASK)
| (max6650_modes[mode] << 4);
i2c_smbus_write_byte_data(client, MAX6650_REG_CONFIG, data->config);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Read/write functions for fan1_div sysfs file. The MAX6650 has no such
* divider. We handle this by converting between divider and counttime:
*
* (counttime == k) <==> (divider == 2^k), k = 0, 1, 2, or 3
*
* Lower values of k allow to connect a faster fan without the risk of
* counter overflow. The price is lower resolution. You can also set counttime
* using the module parameter. Note that the module parameter "prescaler" also
* influences the behaviour. Unfortunately, there's no sysfs attribute
* defined for that. See the data sheet for details.
*/
static ssize_t get_div(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct max6650_data *data = max6650_update_device(dev);
return sprintf(buf, "%d\n", DIV_FROM_REG(data->count));
}
static ssize_t set_div(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct max6650_data *data = i2c_get_clientdata(client);
unsigned long div;
int err;
err = kstrtoul(buf, 10, &div);
if (err)
return err;
mutex_lock(&data->update_lock);
switch (div) {
case 1:
data->count = 0;
break;
case 2:
data->count = 1;
break;
case 4:
data->count = 2;
break;
case 8:
data->count = 3;
break;
default:
mutex_unlock(&data->update_lock);
return -EINVAL;
}
i2c_smbus_write_byte_data(client, MAX6650_REG_COUNT, data->count);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Get alarm stati:
* Possible values:
* 0 = no alarm
* 1 = alarm
*/
static ssize_t get_alarm(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct max6650_data *data = max6650_update_device(dev);
struct i2c_client *client = to_i2c_client(dev);
int alarm = 0;
if (data->alarm & attr->index) {
mutex_lock(&data->update_lock);
alarm = 1;
data->alarm &= ~attr->index;
data->alarm |= i2c_smbus_read_byte_data(client,
MAX6650_REG_ALARM);
mutex_unlock(&data->update_lock);
}
return sprintf(buf, "%d\n", alarm);
}
static SENSOR_DEVICE_ATTR(fan1_input, S_IRUGO, get_fan, NULL, 0);
static SENSOR_DEVICE_ATTR(fan2_input, S_IRUGO, get_fan, NULL, 1);
static SENSOR_DEVICE_ATTR(fan3_input, S_IRUGO, get_fan, NULL, 2);
static SENSOR_DEVICE_ATTR(fan4_input, S_IRUGO, get_fan, NULL, 3);
static DEVICE_ATTR(fan1_target, S_IWUSR | S_IRUGO, get_target, set_target);
static DEVICE_ATTR(fan1_div, S_IWUSR | S_IRUGO, get_div, set_div);
static DEVICE_ATTR(pwm1_enable, S_IWUSR | S_IRUGO, get_enable, set_enable);
static DEVICE_ATTR(pwm1, S_IWUSR | S_IRUGO, get_pwm, set_pwm);
static SENSOR_DEVICE_ATTR(fan1_max_alarm, S_IRUGO, get_alarm, NULL,
MAX6650_ALRM_MAX);
static SENSOR_DEVICE_ATTR(fan1_min_alarm, S_IRUGO, get_alarm, NULL,
MAX6650_ALRM_MIN);
static SENSOR_DEVICE_ATTR(fan1_fault, S_IRUGO, get_alarm, NULL,
MAX6650_ALRM_TACH);
static SENSOR_DEVICE_ATTR(gpio1_alarm, S_IRUGO, get_alarm, NULL,
MAX6650_ALRM_GPIO1);
static SENSOR_DEVICE_ATTR(gpio2_alarm, S_IRUGO, get_alarm, NULL,
MAX6650_ALRM_GPIO2);
static umode_t max6650_attrs_visible(struct kobject *kobj, struct attribute *a,
int n)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct i2c_client *client = to_i2c_client(dev);
u8 alarm_en = i2c_smbus_read_byte_data(client, MAX6650_REG_ALARM_EN);
struct device_attribute *devattr;
/*
* Hide the alarms that have not been enabled by the firmware
*/
devattr = container_of(a, struct device_attribute, attr);
if (devattr == &sensor_dev_attr_fan1_max_alarm.dev_attr
|| devattr == &sensor_dev_attr_fan1_min_alarm.dev_attr
|| devattr == &sensor_dev_attr_fan1_fault.dev_attr
|| devattr == &sensor_dev_attr_gpio1_alarm.dev_attr
|| devattr == &sensor_dev_attr_gpio2_alarm.dev_attr) {
if (!(alarm_en & to_sensor_dev_attr(devattr)->index))
return 0;
}
return a->mode;
}
static struct attribute *max6650_attrs[] = {
&sensor_dev_attr_fan1_input.dev_attr.attr,
&dev_attr_fan1_target.attr,
&dev_attr_fan1_div.attr,
&dev_attr_pwm1_enable.attr,
&dev_attr_pwm1.attr,
&sensor_dev_attr_fan1_max_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_min_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_fault.dev_attr.attr,
&sensor_dev_attr_gpio1_alarm.dev_attr.attr,
&sensor_dev_attr_gpio2_alarm.dev_attr.attr,
NULL
};
static struct attribute_group max6650_attr_grp = {
.attrs = max6650_attrs,
.is_visible = max6650_attrs_visible,
};
static struct attribute *max6651_attrs[] = {
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan3_input.dev_attr.attr,
&sensor_dev_attr_fan4_input.dev_attr.attr,
NULL
};
static const struct attribute_group max6651_attr_grp = {
.attrs = max6651_attrs,
};
/*
* Real code
*/
static int max6650_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct max6650_data *data;
int err;
data = devm_kzalloc(&client->dev, sizeof(struct max6650_data),
GFP_KERNEL);
if (!data) {
dev_err(&client->dev, "out of memory.\n");
return -ENOMEM;
}
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
data->nr_fans = id->driver_data;
/*
* Initialize the max6650 chip
*/
err = max6650_init_client(client);
if (err)
return err;
err = sysfs_create_group(&client->dev.kobj, &max6650_attr_grp);
if (err)
return err;
/* 3 additional fan inputs for the MAX6651 */
if (data->nr_fans == 4) {
err = sysfs_create_group(&client->dev.kobj, &max6651_attr_grp);
if (err)
goto err_remove;
}
data->hwmon_dev = hwmon_device_register(&client->dev);
if (!IS_ERR(data->hwmon_dev))
return 0;
err = PTR_ERR(data->hwmon_dev);
dev_err(&client->dev, "error registering hwmon device.\n");
if (data->nr_fans == 4)
sysfs_remove_group(&client->dev.kobj, &max6651_attr_grp);
err_remove:
sysfs_remove_group(&client->dev.kobj, &max6650_attr_grp);
return err;
}
static int max6650_remove(struct i2c_client *client)
{
struct max6650_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
if (data->nr_fans == 4)
sysfs_remove_group(&client->dev.kobj, &max6651_attr_grp);
sysfs_remove_group(&client->dev.kobj, &max6650_attr_grp);
return 0;
}
static int max6650_init_client(struct i2c_client *client)
{
struct max6650_data *data = i2c_get_clientdata(client);
int config;
int err = -EIO;
config = i2c_smbus_read_byte_data(client, MAX6650_REG_CONFIG);
if (config < 0) {
dev_err(&client->dev, "Error reading config, aborting.\n");
return err;
}
switch (fan_voltage) {
case 0:
break;
case 5:
config &= ~MAX6650_CFG_V12;
break;
case 12:
config |= MAX6650_CFG_V12;
break;
default:
dev_err(&client->dev, "illegal value for fan_voltage (%d)\n",
fan_voltage);
}
dev_info(&client->dev, "Fan voltage is set to %dV.\n",
(config & MAX6650_CFG_V12) ? 12 : 5);
switch (prescaler) {
case 0:
break;
case 1:
config &= ~MAX6650_CFG_PRESCALER_MASK;
break;
case 2:
config = (config & ~MAX6650_CFG_PRESCALER_MASK)
| MAX6650_CFG_PRESCALER_2;
break;
case 4:
config = (config & ~MAX6650_CFG_PRESCALER_MASK)
| MAX6650_CFG_PRESCALER_4;
break;
case 8:
config = (config & ~MAX6650_CFG_PRESCALER_MASK)
| MAX6650_CFG_PRESCALER_8;
break;
case 16:
config = (config & ~MAX6650_CFG_PRESCALER_MASK)
| MAX6650_CFG_PRESCALER_16;
break;
default:
dev_err(&client->dev, "illegal value for prescaler (%d)\n",
prescaler);
}
dev_info(&client->dev, "Prescaler is set to %d.\n",
1 << (config & MAX6650_CFG_PRESCALER_MASK));
/*
* If mode is set to "full off", we change it to "open loop" and
* set DAC to 255, which has the same effect. We do this because
* there's no "full off" mode defined in hwmon specifcations.
*/
if ((config & MAX6650_CFG_MODE_MASK) == MAX6650_CFG_MODE_OFF) {
dev_dbg(&client->dev, "Change mode to open loop, full off.\n");
config = (config & ~MAX6650_CFG_MODE_MASK)
| MAX6650_CFG_MODE_OPEN_LOOP;
if (i2c_smbus_write_byte_data(client, MAX6650_REG_DAC, 255)) {
dev_err(&client->dev, "DAC write error, aborting.\n");
return err;
}
}
if (i2c_smbus_write_byte_data(client, MAX6650_REG_CONFIG, config)) {
dev_err(&client->dev, "Config write error, aborting.\n");
return err;
}
data->config = config;
data->count = i2c_smbus_read_byte_data(client, MAX6650_REG_COUNT);
return 0;
}
static const u8 tach_reg[] = {
MAX6650_REG_TACH0,
MAX6650_REG_TACH1,
MAX6650_REG_TACH2,
MAX6650_REG_TACH3,
};
static struct max6650_data *max6650_update_device(struct device *dev)
{
int i;
struct i2c_client *client = to_i2c_client(dev);
struct max6650_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
data->speed = i2c_smbus_read_byte_data(client,
MAX6650_REG_SPEED);
data->config = i2c_smbus_read_byte_data(client,
MAX6650_REG_CONFIG);
for (i = 0; i < data->nr_fans; i++) {
data->tach[i] = i2c_smbus_read_byte_data(client,
tach_reg[i]);
}
data->count = i2c_smbus_read_byte_data(client,
MAX6650_REG_COUNT);
data->dac = i2c_smbus_read_byte_data(client, MAX6650_REG_DAC);
/*
* Alarms are cleared on read in case the condition that
* caused the alarm is removed. Keep the value latched here
* for providing the register through different alarm files.
*/
data->alarm |= i2c_smbus_read_byte_data(client,
MAX6650_REG_ALARM);
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
module_i2c_driver(max6650_driver);
MODULE_AUTHOR("Hans J. Koch");
MODULE_DESCRIPTION("MAX6650 sensor driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
wanam/Adam-Kernel-GS3 | fs/xfs/quota/xfs_trans_dquot.c | 2557 | 22413 | /*
* Copyright (c) 2000-2002 Silicon Graphics, Inc.
* 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.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_alloc.h"
#include "xfs_quota.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_inode.h"
#include "xfs_itable.h"
#include "xfs_bmap.h"
#include "xfs_rtalloc.h"
#include "xfs_error.h"
#include "xfs_attr.h"
#include "xfs_buf_item.h"
#include "xfs_trans_priv.h"
#include "xfs_qm.h"
STATIC void xfs_trans_alloc_dqinfo(xfs_trans_t *);
/*
* Add the locked dquot to the transaction.
* The dquot must be locked, and it cannot be associated with any
* transaction.
*/
void
xfs_trans_dqjoin(
xfs_trans_t *tp,
xfs_dquot_t *dqp)
{
ASSERT(dqp->q_transp != tp);
ASSERT(XFS_DQ_IS_LOCKED(dqp));
ASSERT(dqp->q_logitem.qli_dquot == dqp);
/*
* Get a log_item_desc to point at the new item.
*/
xfs_trans_add_item(tp, &dqp->q_logitem.qli_item);
/*
* Initialize i_transp so we can later determine if this dquot is
* associated with this transaction.
*/
dqp->q_transp = tp;
}
/*
* This is called to mark the dquot as needing
* to be logged when the transaction is committed. The dquot must
* already be associated with the given transaction.
* Note that it marks the entire transaction as dirty. In the ordinary
* case, this gets called via xfs_trans_commit, after the transaction
* is already dirty. However, there's nothing stop this from getting
* called directly, as done by xfs_qm_scall_setqlim. Hence, the TRANS_DIRTY
* flag.
*/
void
xfs_trans_log_dquot(
xfs_trans_t *tp,
xfs_dquot_t *dqp)
{
ASSERT(dqp->q_transp == tp);
ASSERT(XFS_DQ_IS_LOCKED(dqp));
tp->t_flags |= XFS_TRANS_DIRTY;
dqp->q_logitem.qli_item.li_desc->lid_flags |= XFS_LID_DIRTY;
}
/*
* Carry forward whatever is left of the quota blk reservation to
* the spanky new transaction
*/
void
xfs_trans_dup_dqinfo(
xfs_trans_t *otp,
xfs_trans_t *ntp)
{
xfs_dqtrx_t *oq, *nq;
int i,j;
xfs_dqtrx_t *oqa, *nqa;
if (!otp->t_dqinfo)
return;
xfs_trans_alloc_dqinfo(ntp);
oqa = otp->t_dqinfo->dqa_usrdquots;
nqa = ntp->t_dqinfo->dqa_usrdquots;
/*
* Because the quota blk reservation is carried forward,
* it is also necessary to carry forward the DQ_DIRTY flag.
*/
if(otp->t_flags & XFS_TRANS_DQ_DIRTY)
ntp->t_flags |= XFS_TRANS_DQ_DIRTY;
for (j = 0; j < 2; j++) {
for (i = 0; i < XFS_QM_TRANS_MAXDQS; i++) {
if (oqa[i].qt_dquot == NULL)
break;
oq = &oqa[i];
nq = &nqa[i];
nq->qt_dquot = oq->qt_dquot;
nq->qt_bcount_delta = nq->qt_icount_delta = 0;
nq->qt_rtbcount_delta = 0;
/*
* Transfer whatever is left of the reservations.
*/
nq->qt_blk_res = oq->qt_blk_res - oq->qt_blk_res_used;
oq->qt_blk_res = oq->qt_blk_res_used;
nq->qt_rtblk_res = oq->qt_rtblk_res -
oq->qt_rtblk_res_used;
oq->qt_rtblk_res = oq->qt_rtblk_res_used;
nq->qt_ino_res = oq->qt_ino_res - oq->qt_ino_res_used;
oq->qt_ino_res = oq->qt_ino_res_used;
}
oqa = otp->t_dqinfo->dqa_grpdquots;
nqa = ntp->t_dqinfo->dqa_grpdquots;
}
}
/*
* Wrap around mod_dquot to account for both user and group quotas.
*/
void
xfs_trans_mod_dquot_byino(
xfs_trans_t *tp,
xfs_inode_t *ip,
uint field,
long delta)
{
xfs_mount_t *mp = tp->t_mountp;
if (!XFS_IS_QUOTA_RUNNING(mp) ||
!XFS_IS_QUOTA_ON(mp) ||
ip->i_ino == mp->m_sb.sb_uquotino ||
ip->i_ino == mp->m_sb.sb_gquotino)
return;
if (tp->t_dqinfo == NULL)
xfs_trans_alloc_dqinfo(tp);
if (XFS_IS_UQUOTA_ON(mp) && ip->i_udquot)
(void) xfs_trans_mod_dquot(tp, ip->i_udquot, field, delta);
if (XFS_IS_OQUOTA_ON(mp) && ip->i_gdquot)
(void) xfs_trans_mod_dquot(tp, ip->i_gdquot, field, delta);
}
STATIC xfs_dqtrx_t *
xfs_trans_get_dqtrx(
xfs_trans_t *tp,
xfs_dquot_t *dqp)
{
int i;
xfs_dqtrx_t *qa;
qa = XFS_QM_ISUDQ(dqp) ?
tp->t_dqinfo->dqa_usrdquots : tp->t_dqinfo->dqa_grpdquots;
for (i = 0; i < XFS_QM_TRANS_MAXDQS; i++) {
if (qa[i].qt_dquot == NULL ||
qa[i].qt_dquot == dqp)
return &qa[i];
}
return NULL;
}
/*
* Make the changes in the transaction structure.
* The moral equivalent to xfs_trans_mod_sb().
* We don't touch any fields in the dquot, so we don't care
* if it's locked or not (most of the time it won't be).
*/
void
xfs_trans_mod_dquot(
xfs_trans_t *tp,
xfs_dquot_t *dqp,
uint field,
long delta)
{
xfs_dqtrx_t *qtrx;
ASSERT(tp);
ASSERT(XFS_IS_QUOTA_RUNNING(tp->t_mountp));
qtrx = NULL;
if (tp->t_dqinfo == NULL)
xfs_trans_alloc_dqinfo(tp);
/*
* Find either the first free slot or the slot that belongs
* to this dquot.
*/
qtrx = xfs_trans_get_dqtrx(tp, dqp);
ASSERT(qtrx);
if (qtrx->qt_dquot == NULL)
qtrx->qt_dquot = dqp;
switch (field) {
/*
* regular disk blk reservation
*/
case XFS_TRANS_DQ_RES_BLKS:
qtrx->qt_blk_res += (ulong)delta;
break;
/*
* inode reservation
*/
case XFS_TRANS_DQ_RES_INOS:
qtrx->qt_ino_res += (ulong)delta;
break;
/*
* disk blocks used.
*/
case XFS_TRANS_DQ_BCOUNT:
if (qtrx->qt_blk_res && delta > 0) {
qtrx->qt_blk_res_used += (ulong)delta;
ASSERT(qtrx->qt_blk_res >= qtrx->qt_blk_res_used);
}
qtrx->qt_bcount_delta += delta;
break;
case XFS_TRANS_DQ_DELBCOUNT:
qtrx->qt_delbcnt_delta += delta;
break;
/*
* Inode Count
*/
case XFS_TRANS_DQ_ICOUNT:
if (qtrx->qt_ino_res && delta > 0) {
qtrx->qt_ino_res_used += (ulong)delta;
ASSERT(qtrx->qt_ino_res >= qtrx->qt_ino_res_used);
}
qtrx->qt_icount_delta += delta;
break;
/*
* rtblk reservation
*/
case XFS_TRANS_DQ_RES_RTBLKS:
qtrx->qt_rtblk_res += (ulong)delta;
break;
/*
* rtblk count
*/
case XFS_TRANS_DQ_RTBCOUNT:
if (qtrx->qt_rtblk_res && delta > 0) {
qtrx->qt_rtblk_res_used += (ulong)delta;
ASSERT(qtrx->qt_rtblk_res >= qtrx->qt_rtblk_res_used);
}
qtrx->qt_rtbcount_delta += delta;
break;
case XFS_TRANS_DQ_DELRTBCOUNT:
qtrx->qt_delrtb_delta += delta;
break;
default:
ASSERT(0);
}
tp->t_flags |= XFS_TRANS_DQ_DIRTY;
}
/*
* Given an array of dqtrx structures, lock all the dquots associated
* and join them to the transaction, provided they have been modified.
* We know that the highest number of dquots (of one type - usr OR grp),
* involved in a transaction is 2 and that both usr and grp combined - 3.
* So, we don't attempt to make this very generic.
*/
STATIC void
xfs_trans_dqlockedjoin(
xfs_trans_t *tp,
xfs_dqtrx_t *q)
{
ASSERT(q[0].qt_dquot != NULL);
if (q[1].qt_dquot == NULL) {
xfs_dqlock(q[0].qt_dquot);
xfs_trans_dqjoin(tp, q[0].qt_dquot);
} else {
ASSERT(XFS_QM_TRANS_MAXDQS == 2);
xfs_dqlock2(q[0].qt_dquot, q[1].qt_dquot);
xfs_trans_dqjoin(tp, q[0].qt_dquot);
xfs_trans_dqjoin(tp, q[1].qt_dquot);
}
}
/*
* Called by xfs_trans_commit() and similar in spirit to
* xfs_trans_apply_sb_deltas().
* Go thru all the dquots belonging to this transaction and modify the
* INCORE dquot to reflect the actual usages.
* Unreserve just the reservations done by this transaction.
* dquot is still left locked at exit.
*/
void
xfs_trans_apply_dquot_deltas(
xfs_trans_t *tp)
{
int i, j;
xfs_dquot_t *dqp;
xfs_dqtrx_t *qtrx, *qa;
xfs_disk_dquot_t *d;
long totalbdelta;
long totalrtbdelta;
if (!(tp->t_flags & XFS_TRANS_DQ_DIRTY))
return;
ASSERT(tp->t_dqinfo);
qa = tp->t_dqinfo->dqa_usrdquots;
for (j = 0; j < 2; j++) {
if (qa[0].qt_dquot == NULL) {
qa = tp->t_dqinfo->dqa_grpdquots;
continue;
}
/*
* Lock all of the dquots and join them to the transaction.
*/
xfs_trans_dqlockedjoin(tp, qa);
for (i = 0; i < XFS_QM_TRANS_MAXDQS; i++) {
qtrx = &qa[i];
/*
* The array of dquots is filled
* sequentially, not sparsely.
*/
if ((dqp = qtrx->qt_dquot) == NULL)
break;
ASSERT(XFS_DQ_IS_LOCKED(dqp));
ASSERT(dqp->q_transp == tp);
/*
* adjust the actual number of blocks used
*/
d = &dqp->q_core;
/*
* The issue here is - sometimes we don't make a blkquota
* reservation intentionally to be fair to users
* (when the amount is small). On the other hand,
* delayed allocs do make reservations, but that's
* outside of a transaction, so we have no
* idea how much was really reserved.
* So, here we've accumulated delayed allocation blks and
* non-delay blks. The assumption is that the
* delayed ones are always reserved (outside of a
* transaction), and the others may or may not have
* quota reservations.
*/
totalbdelta = qtrx->qt_bcount_delta +
qtrx->qt_delbcnt_delta;
totalrtbdelta = qtrx->qt_rtbcount_delta +
qtrx->qt_delrtb_delta;
#ifdef QUOTADEBUG
if (totalbdelta < 0)
ASSERT(be64_to_cpu(d->d_bcount) >=
(xfs_qcnt_t) -totalbdelta);
if (totalrtbdelta < 0)
ASSERT(be64_to_cpu(d->d_rtbcount) >=
(xfs_qcnt_t) -totalrtbdelta);
if (qtrx->qt_icount_delta < 0)
ASSERT(be64_to_cpu(d->d_icount) >=
(xfs_qcnt_t) -qtrx->qt_icount_delta);
#endif
if (totalbdelta)
be64_add_cpu(&d->d_bcount, (xfs_qcnt_t)totalbdelta);
if (qtrx->qt_icount_delta)
be64_add_cpu(&d->d_icount, (xfs_qcnt_t)qtrx->qt_icount_delta);
if (totalrtbdelta)
be64_add_cpu(&d->d_rtbcount, (xfs_qcnt_t)totalrtbdelta);
/*
* Get any default limits in use.
* Start/reset the timer(s) if needed.
*/
if (d->d_id) {
xfs_qm_adjust_dqlimits(tp->t_mountp, d);
xfs_qm_adjust_dqtimers(tp->t_mountp, d);
}
dqp->dq_flags |= XFS_DQ_DIRTY;
/*
* add this to the list of items to get logged
*/
xfs_trans_log_dquot(tp, dqp);
/*
* Take off what's left of the original reservation.
* In case of delayed allocations, there's no
* reservation that a transaction structure knows of.
*/
if (qtrx->qt_blk_res != 0) {
if (qtrx->qt_blk_res != qtrx->qt_blk_res_used) {
if (qtrx->qt_blk_res >
qtrx->qt_blk_res_used)
dqp->q_res_bcount -= (xfs_qcnt_t)
(qtrx->qt_blk_res -
qtrx->qt_blk_res_used);
else
dqp->q_res_bcount -= (xfs_qcnt_t)
(qtrx->qt_blk_res_used -
qtrx->qt_blk_res);
}
} else {
/*
* These blks were never reserved, either inside
* a transaction or outside one (in a delayed
* allocation). Also, this isn't always a
* negative number since we sometimes
* deliberately skip quota reservations.
*/
if (qtrx->qt_bcount_delta) {
dqp->q_res_bcount +=
(xfs_qcnt_t)qtrx->qt_bcount_delta;
}
}
/*
* Adjust the RT reservation.
*/
if (qtrx->qt_rtblk_res != 0) {
if (qtrx->qt_rtblk_res != qtrx->qt_rtblk_res_used) {
if (qtrx->qt_rtblk_res >
qtrx->qt_rtblk_res_used)
dqp->q_res_rtbcount -= (xfs_qcnt_t)
(qtrx->qt_rtblk_res -
qtrx->qt_rtblk_res_used);
else
dqp->q_res_rtbcount -= (xfs_qcnt_t)
(qtrx->qt_rtblk_res_used -
qtrx->qt_rtblk_res);
}
} else {
if (qtrx->qt_rtbcount_delta)
dqp->q_res_rtbcount +=
(xfs_qcnt_t)qtrx->qt_rtbcount_delta;
}
/*
* Adjust the inode reservation.
*/
if (qtrx->qt_ino_res != 0) {
ASSERT(qtrx->qt_ino_res >=
qtrx->qt_ino_res_used);
if (qtrx->qt_ino_res > qtrx->qt_ino_res_used)
dqp->q_res_icount -= (xfs_qcnt_t)
(qtrx->qt_ino_res -
qtrx->qt_ino_res_used);
} else {
if (qtrx->qt_icount_delta)
dqp->q_res_icount +=
(xfs_qcnt_t)qtrx->qt_icount_delta;
}
ASSERT(dqp->q_res_bcount >=
be64_to_cpu(dqp->q_core.d_bcount));
ASSERT(dqp->q_res_icount >=
be64_to_cpu(dqp->q_core.d_icount));
ASSERT(dqp->q_res_rtbcount >=
be64_to_cpu(dqp->q_core.d_rtbcount));
}
/*
* Do the group quotas next
*/
qa = tp->t_dqinfo->dqa_grpdquots;
}
}
/*
* Release the reservations, and adjust the dquots accordingly.
* This is called only when the transaction is being aborted. If by
* any chance we have done dquot modifications incore (ie. deltas) already,
* we simply throw those away, since that's the expected behavior
* when a transaction is curtailed without a commit.
*/
void
xfs_trans_unreserve_and_mod_dquots(
xfs_trans_t *tp)
{
int i, j;
xfs_dquot_t *dqp;
xfs_dqtrx_t *qtrx, *qa;
boolean_t locked;
if (!tp->t_dqinfo || !(tp->t_flags & XFS_TRANS_DQ_DIRTY))
return;
qa = tp->t_dqinfo->dqa_usrdquots;
for (j = 0; j < 2; j++) {
for (i = 0; i < XFS_QM_TRANS_MAXDQS; i++) {
qtrx = &qa[i];
/*
* We assume that the array of dquots is filled
* sequentially, not sparsely.
*/
if ((dqp = qtrx->qt_dquot) == NULL)
break;
/*
* Unreserve the original reservation. We don't care
* about the number of blocks used field, or deltas.
* Also we don't bother to zero the fields.
*/
locked = B_FALSE;
if (qtrx->qt_blk_res) {
xfs_dqlock(dqp);
locked = B_TRUE;
dqp->q_res_bcount -=
(xfs_qcnt_t)qtrx->qt_blk_res;
}
if (qtrx->qt_ino_res) {
if (!locked) {
xfs_dqlock(dqp);
locked = B_TRUE;
}
dqp->q_res_icount -=
(xfs_qcnt_t)qtrx->qt_ino_res;
}
if (qtrx->qt_rtblk_res) {
if (!locked) {
xfs_dqlock(dqp);
locked = B_TRUE;
}
dqp->q_res_rtbcount -=
(xfs_qcnt_t)qtrx->qt_rtblk_res;
}
if (locked)
xfs_dqunlock(dqp);
}
qa = tp->t_dqinfo->dqa_grpdquots;
}
}
STATIC void
xfs_quota_warn(
struct xfs_mount *mp,
struct xfs_dquot *dqp,
int type)
{
/* no warnings for project quotas - we just return ENOSPC later */
if (dqp->dq_flags & XFS_DQ_PROJ)
return;
quota_send_warning((dqp->dq_flags & XFS_DQ_USER) ? USRQUOTA : GRPQUOTA,
be32_to_cpu(dqp->q_core.d_id), mp->m_super->s_dev,
type);
}
/*
* This reserves disk blocks and inodes against a dquot.
* Flags indicate if the dquot is to be locked here and also
* if the blk reservation is for RT or regular blocks.
* Sending in XFS_QMOPT_FORCE_RES flag skips the quota check.
*/
STATIC int
xfs_trans_dqresv(
xfs_trans_t *tp,
xfs_mount_t *mp,
xfs_dquot_t *dqp,
long nblks,
long ninos,
uint flags)
{
xfs_qcnt_t hardlimit;
xfs_qcnt_t softlimit;
time_t timer;
xfs_qwarncnt_t warns;
xfs_qwarncnt_t warnlimit;
xfs_qcnt_t count;
xfs_qcnt_t *resbcountp;
xfs_quotainfo_t *q = mp->m_quotainfo;
xfs_dqlock(dqp);
if (flags & XFS_TRANS_DQ_RES_BLKS) {
hardlimit = be64_to_cpu(dqp->q_core.d_blk_hardlimit);
if (!hardlimit)
hardlimit = q->qi_bhardlimit;
softlimit = be64_to_cpu(dqp->q_core.d_blk_softlimit);
if (!softlimit)
softlimit = q->qi_bsoftlimit;
timer = be32_to_cpu(dqp->q_core.d_btimer);
warns = be16_to_cpu(dqp->q_core.d_bwarns);
warnlimit = dqp->q_mount->m_quotainfo->qi_bwarnlimit;
resbcountp = &dqp->q_res_bcount;
} else {
ASSERT(flags & XFS_TRANS_DQ_RES_RTBLKS);
hardlimit = be64_to_cpu(dqp->q_core.d_rtb_hardlimit);
if (!hardlimit)
hardlimit = q->qi_rtbhardlimit;
softlimit = be64_to_cpu(dqp->q_core.d_rtb_softlimit);
if (!softlimit)
softlimit = q->qi_rtbsoftlimit;
timer = be32_to_cpu(dqp->q_core.d_rtbtimer);
warns = be16_to_cpu(dqp->q_core.d_rtbwarns);
warnlimit = dqp->q_mount->m_quotainfo->qi_rtbwarnlimit;
resbcountp = &dqp->q_res_rtbcount;
}
if ((flags & XFS_QMOPT_FORCE_RES) == 0 &&
dqp->q_core.d_id &&
((XFS_IS_UQUOTA_ENFORCED(dqp->q_mount) && XFS_QM_ISUDQ(dqp)) ||
(XFS_IS_OQUOTA_ENFORCED(dqp->q_mount) &&
(XFS_QM_ISPDQ(dqp) || XFS_QM_ISGDQ(dqp))))) {
#ifdef QUOTADEBUG
xfs_debug(mp,
"BLK Res: nblks=%ld + resbcount=%Ld > hardlimit=%Ld?",
nblks, *resbcountp, hardlimit);
#endif
if (nblks > 0) {
/*
* dquot is locked already. See if we'd go over the
* hardlimit or exceed the timelimit if we allocate
* nblks.
*/
if (hardlimit > 0ULL &&
hardlimit <= nblks + *resbcountp) {
xfs_quota_warn(mp, dqp, QUOTA_NL_BHARDWARN);
goto error_return;
}
if (softlimit > 0ULL &&
softlimit <= nblks + *resbcountp) {
if ((timer != 0 && get_seconds() > timer) ||
(warns != 0 && warns >= warnlimit)) {
xfs_quota_warn(mp, dqp,
QUOTA_NL_BSOFTLONGWARN);
goto error_return;
}
xfs_quota_warn(mp, dqp, QUOTA_NL_BSOFTWARN);
}
}
if (ninos > 0) {
count = be64_to_cpu(dqp->q_core.d_icount);
timer = be32_to_cpu(dqp->q_core.d_itimer);
warns = be16_to_cpu(dqp->q_core.d_iwarns);
warnlimit = dqp->q_mount->m_quotainfo->qi_iwarnlimit;
hardlimit = be64_to_cpu(dqp->q_core.d_ino_hardlimit);
if (!hardlimit)
hardlimit = q->qi_ihardlimit;
softlimit = be64_to_cpu(dqp->q_core.d_ino_softlimit);
if (!softlimit)
softlimit = q->qi_isoftlimit;
if (hardlimit > 0ULL && count >= hardlimit) {
xfs_quota_warn(mp, dqp, QUOTA_NL_IHARDWARN);
goto error_return;
}
if (softlimit > 0ULL && count >= softlimit) {
if ((timer != 0 && get_seconds() > timer) ||
(warns != 0 && warns >= warnlimit)) {
xfs_quota_warn(mp, dqp,
QUOTA_NL_ISOFTLONGWARN);
goto error_return;
}
xfs_quota_warn(mp, dqp, QUOTA_NL_ISOFTWARN);
}
}
}
/*
* Change the reservation, but not the actual usage.
* Note that q_res_bcount = q_core.d_bcount + resv
*/
(*resbcountp) += (xfs_qcnt_t)nblks;
if (ninos != 0)
dqp->q_res_icount += (xfs_qcnt_t)ninos;
/*
* note the reservation amt in the trans struct too,
* so that the transaction knows how much was reserved by
* it against this particular dquot.
* We don't do this when we are reserving for a delayed allocation,
* because we don't have the luxury of a transaction envelope then.
*/
if (tp) {
ASSERT(tp->t_dqinfo);
ASSERT(flags & XFS_QMOPT_RESBLK_MASK);
if (nblks != 0)
xfs_trans_mod_dquot(tp, dqp,
flags & XFS_QMOPT_RESBLK_MASK,
nblks);
if (ninos != 0)
xfs_trans_mod_dquot(tp, dqp,
XFS_TRANS_DQ_RES_INOS,
ninos);
}
ASSERT(dqp->q_res_bcount >= be64_to_cpu(dqp->q_core.d_bcount));
ASSERT(dqp->q_res_rtbcount >= be64_to_cpu(dqp->q_core.d_rtbcount));
ASSERT(dqp->q_res_icount >= be64_to_cpu(dqp->q_core.d_icount));
xfs_dqunlock(dqp);
return 0;
error_return:
xfs_dqunlock(dqp);
if (flags & XFS_QMOPT_ENOSPC)
return ENOSPC;
return EDQUOT;
}
/*
* Given dquot(s), make disk block and/or inode reservations against them.
* The fact that this does the reservation against both the usr and
* grp/prj quotas is important, because this follows a both-or-nothing
* approach.
*
* flags = XFS_QMOPT_FORCE_RES evades limit enforcement. Used by chown.
* XFS_QMOPT_ENOSPC returns ENOSPC not EDQUOT. Used by pquota.
* XFS_TRANS_DQ_RES_BLKS reserves regular disk blocks
* XFS_TRANS_DQ_RES_RTBLKS reserves realtime disk blocks
* dquots are unlocked on return, if they were not locked by caller.
*/
int
xfs_trans_reserve_quota_bydquots(
xfs_trans_t *tp,
xfs_mount_t *mp,
xfs_dquot_t *udqp,
xfs_dquot_t *gdqp,
long nblks,
long ninos,
uint flags)
{
int resvd = 0, error;
if (!XFS_IS_QUOTA_RUNNING(mp) || !XFS_IS_QUOTA_ON(mp))
return 0;
if (tp && tp->t_dqinfo == NULL)
xfs_trans_alloc_dqinfo(tp);
ASSERT(flags & XFS_QMOPT_RESBLK_MASK);
if (udqp) {
error = xfs_trans_dqresv(tp, mp, udqp, nblks, ninos,
(flags & ~XFS_QMOPT_ENOSPC));
if (error)
return error;
resvd = 1;
}
if (gdqp) {
error = xfs_trans_dqresv(tp, mp, gdqp, nblks, ninos, flags);
if (error) {
/*
* can't do it, so backout previous reservation
*/
if (resvd) {
flags |= XFS_QMOPT_FORCE_RES;
xfs_trans_dqresv(tp, mp, udqp,
-nblks, -ninos, flags);
}
return error;
}
}
/*
* Didn't change anything critical, so, no need to log
*/
return 0;
}
/*
* Lock the dquot and change the reservation if we can.
* This doesn't change the actual usage, just the reservation.
* The inode sent in is locked.
*/
int
xfs_trans_reserve_quota_nblks(
struct xfs_trans *tp,
struct xfs_inode *ip,
long nblks,
long ninos,
uint flags)
{
struct xfs_mount *mp = ip->i_mount;
if (!XFS_IS_QUOTA_RUNNING(mp) || !XFS_IS_QUOTA_ON(mp))
return 0;
if (XFS_IS_PQUOTA_ON(mp))
flags |= XFS_QMOPT_ENOSPC;
ASSERT(ip->i_ino != mp->m_sb.sb_uquotino);
ASSERT(ip->i_ino != mp->m_sb.sb_gquotino);
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
ASSERT((flags & ~(XFS_QMOPT_FORCE_RES | XFS_QMOPT_ENOSPC)) ==
XFS_TRANS_DQ_RES_RTBLKS ||
(flags & ~(XFS_QMOPT_FORCE_RES | XFS_QMOPT_ENOSPC)) ==
XFS_TRANS_DQ_RES_BLKS);
/*
* Reserve nblks against these dquots, with trans as the mediator.
*/
return xfs_trans_reserve_quota_bydquots(tp, mp,
ip->i_udquot, ip->i_gdquot,
nblks, ninos, flags);
}
/*
* This routine is called to allocate a quotaoff log item.
*/
xfs_qoff_logitem_t *
xfs_trans_get_qoff_item(
xfs_trans_t *tp,
xfs_qoff_logitem_t *startqoff,
uint flags)
{
xfs_qoff_logitem_t *q;
ASSERT(tp != NULL);
q = xfs_qm_qoff_logitem_init(tp->t_mountp, startqoff, flags);
ASSERT(q != NULL);
/*
* Get a log_item_desc to point at the new item.
*/
xfs_trans_add_item(tp, &q->qql_item);
return q;
}
/*
* This is called to mark the quotaoff logitem as needing
* to be logged when the transaction is committed. The logitem must
* already be associated with the given transaction.
*/
void
xfs_trans_log_quotaoff_item(
xfs_trans_t *tp,
xfs_qoff_logitem_t *qlp)
{
tp->t_flags |= XFS_TRANS_DIRTY;
qlp->qql_item.li_desc->lid_flags |= XFS_LID_DIRTY;
}
STATIC void
xfs_trans_alloc_dqinfo(
xfs_trans_t *tp)
{
tp->t_dqinfo = kmem_zone_zalloc(xfs_Gqm->qm_dqtrxzone, KM_SLEEP);
}
void
xfs_trans_free_dqinfo(
xfs_trans_t *tp)
{
if (!tp->t_dqinfo)
return;
kmem_zone_free(xfs_Gqm->qm_dqtrxzone, tp->t_dqinfo);
tp->t_dqinfo = NULL;
}
| gpl-2.0 |
smac0628/htc_gpe_51 | sound/usb/caiaq/device.c | 3325 | 14721 | /*
* caiaq.c: ALSA driver for caiaq/NativeInstruments devices
*
* Copyright (c) 2007 Daniel Mack <daniel@caiaq.de>
* Karsten Wiese <fzu@wemgehoertderstaat.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
*/
#include <linux/moduleparam.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/gfp.h>
#include <linux/usb.h>
#include <sound/initval.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include "device.h"
#include "audio.h"
#include "midi.h"
#include "control.h"
#include "input.h"
MODULE_AUTHOR("Daniel Mack <daniel@caiaq.de>");
MODULE_DESCRIPTION("caiaq USB audio");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Native Instruments, RigKontrol2},"
"{Native Instruments, RigKontrol3},"
"{Native Instruments, Kore Controller},"
"{Native Instruments, Kore Controller 2},"
"{Native Instruments, Audio Kontrol 1},"
"{Native Instruments, Audio 2 DJ},"
"{Native Instruments, Audio 4 DJ},"
"{Native Instruments, Audio 8 DJ},"
"{Native Instruments, Traktor Audio 2},"
"{Native Instruments, Session I/O},"
"{Native Instruments, GuitarRig mobile}"
"{Native Instruments, Traktor Kontrol X1}"
"{Native Instruments, Traktor Kontrol S4}"
"{Native Instruments, Maschine Controller}");
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_PNP; /* Enable this card */
static int snd_card_used[SNDRV_CARDS];
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for the caiaq sound device");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for the caiaq soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable the caiaq soundcard.");
enum {
SAMPLERATE_44100 = 0,
SAMPLERATE_48000 = 1,
SAMPLERATE_96000 = 2,
SAMPLERATE_192000 = 3,
SAMPLERATE_88200 = 4,
SAMPLERATE_INVALID = 0xff
};
enum {
DEPTH_NONE = 0,
DEPTH_16 = 1,
DEPTH_24 = 2,
DEPTH_32 = 3
};
static struct usb_device_id snd_usb_id_table[] = {
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_RIGKONTROL2
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_RIGKONTROL3
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_KORECONTROLLER
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_KORECONTROLLER2
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_AK1
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_AUDIO8DJ
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_SESSIONIO
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_GUITARRIGMOBILE
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_AUDIO4DJ
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_AUDIO2DJ
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_TRAKTORKONTROLX1
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_TRAKTORKONTROLS4
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_TRAKTORAUDIO2
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = USB_VID_NATIVEINSTRUMENTS,
.idProduct = USB_PID_MASCHINECONTROLLER
},
{ /* terminator */ }
};
static void usb_ep1_command_reply_dispatch (struct urb* urb)
{
int ret;
struct snd_usb_caiaqdev *dev = urb->context;
unsigned char *buf = urb->transfer_buffer;
if (urb->status || !dev) {
log("received EP1 urb->status = %i\n", urb->status);
return;
}
switch(buf[0]) {
case EP1_CMD_GET_DEVICE_INFO:
memcpy(&dev->spec, buf+1, sizeof(struct caiaq_device_spec));
dev->spec.fw_version = le16_to_cpu(dev->spec.fw_version);
debug("device spec (firmware %d): audio: %d in, %d out, "
"MIDI: %d in, %d out, data alignment %d\n",
dev->spec.fw_version,
dev->spec.num_analog_audio_in,
dev->spec.num_analog_audio_out,
dev->spec.num_midi_in,
dev->spec.num_midi_out,
dev->spec.data_alignment);
dev->spec_received++;
wake_up(&dev->ep1_wait_queue);
break;
case EP1_CMD_AUDIO_PARAMS:
dev->audio_parm_answer = buf[1];
wake_up(&dev->ep1_wait_queue);
break;
case EP1_CMD_MIDI_READ:
snd_usb_caiaq_midi_handle_input(dev, buf[1], buf + 3, buf[2]);
break;
case EP1_CMD_READ_IO:
if (dev->chip.usb_id ==
USB_ID(USB_VID_NATIVEINSTRUMENTS, USB_PID_AUDIO8DJ)) {
if (urb->actual_length > sizeof(dev->control_state))
urb->actual_length = sizeof(dev->control_state);
memcpy(dev->control_state, buf + 1, urb->actual_length);
wake_up(&dev->ep1_wait_queue);
break;
}
#ifdef CONFIG_SND_USB_CAIAQ_INPUT
case EP1_CMD_READ_ERP:
case EP1_CMD_READ_ANALOG:
snd_usb_caiaq_input_dispatch(dev, buf, urb->actual_length);
#endif
break;
}
dev->ep1_in_urb.actual_length = 0;
ret = usb_submit_urb(&dev->ep1_in_urb, GFP_ATOMIC);
if (ret < 0)
log("unable to submit urb. OOM!?\n");
}
int snd_usb_caiaq_send_command(struct snd_usb_caiaqdev *dev,
unsigned char command,
const unsigned char *buffer,
int len)
{
int actual_len;
struct usb_device *usb_dev = dev->chip.dev;
if (!usb_dev)
return -EIO;
if (len > EP1_BUFSIZE - 1)
len = EP1_BUFSIZE - 1;
if (buffer && len > 0)
memcpy(dev->ep1_out_buf+1, buffer, len);
dev->ep1_out_buf[0] = command;
return usb_bulk_msg(usb_dev, usb_sndbulkpipe(usb_dev, 1),
dev->ep1_out_buf, len+1, &actual_len, 200);
}
int snd_usb_caiaq_set_audio_params (struct snd_usb_caiaqdev *dev,
int rate, int depth, int bpp)
{
int ret;
char tmp[5];
switch (rate) {
case 44100: tmp[0] = SAMPLERATE_44100; break;
case 48000: tmp[0] = SAMPLERATE_48000; break;
case 88200: tmp[0] = SAMPLERATE_88200; break;
case 96000: tmp[0] = SAMPLERATE_96000; break;
case 192000: tmp[0] = SAMPLERATE_192000; break;
default: return -EINVAL;
}
switch (depth) {
case 16: tmp[1] = DEPTH_16; break;
case 24: tmp[1] = DEPTH_24; break;
default: return -EINVAL;
}
tmp[2] = bpp & 0xff;
tmp[3] = bpp >> 8;
tmp[4] = 1; /* packets per microframe */
debug("setting audio params: %d Hz, %d bits, %d bpp\n",
rate, depth, bpp);
dev->audio_parm_answer = -1;
ret = snd_usb_caiaq_send_command(dev, EP1_CMD_AUDIO_PARAMS,
tmp, sizeof(tmp));
if (ret)
return ret;
if (!wait_event_timeout(dev->ep1_wait_queue,
dev->audio_parm_answer >= 0, HZ))
return -EPIPE;
if (dev->audio_parm_answer != 1)
debug("unable to set the device's audio params\n");
else
dev->bpp = bpp;
return dev->audio_parm_answer == 1 ? 0 : -EINVAL;
}
int snd_usb_caiaq_set_auto_msg(struct snd_usb_caiaqdev *dev,
int digital, int analog, int erp)
{
char tmp[3] = { digital, analog, erp };
return snd_usb_caiaq_send_command(dev, EP1_CMD_AUTO_MSG,
tmp, sizeof(tmp));
}
static void __devinit setup_card(struct snd_usb_caiaqdev *dev)
{
int ret;
char val[4];
/* device-specific startup specials */
switch (dev->chip.usb_id) {
case USB_ID(USB_VID_NATIVEINSTRUMENTS, USB_PID_RIGKONTROL2):
/* RigKontrol2 - display centered dash ('-') */
val[0] = 0x00;
val[1] = 0x00;
val[2] = 0x01;
snd_usb_caiaq_send_command(dev, EP1_CMD_WRITE_IO, val, 3);
break;
case USB_ID(USB_VID_NATIVEINSTRUMENTS, USB_PID_RIGKONTROL3):
/* RigKontrol2 - display two centered dashes ('--') */
val[0] = 0x00;
val[1] = 0x40;
val[2] = 0x40;
val[3] = 0x00;
snd_usb_caiaq_send_command(dev, EP1_CMD_WRITE_IO, val, 4);
break;
case USB_ID(USB_VID_NATIVEINSTRUMENTS, USB_PID_AK1):
/* Audio Kontrol 1 - make USB-LED stop blinking */
val[0] = 0x00;
snd_usb_caiaq_send_command(dev, EP1_CMD_WRITE_IO, val, 1);
break;
case USB_ID(USB_VID_NATIVEINSTRUMENTS, USB_PID_AUDIO8DJ):
/* Audio 8 DJ - trigger read of current settings */
dev->control_state[0] = 0xff;
snd_usb_caiaq_set_auto_msg(dev, 1, 0, 0);
snd_usb_caiaq_send_command(dev, EP1_CMD_READ_IO, NULL, 0);
if (!wait_event_timeout(dev->ep1_wait_queue,
dev->control_state[0] != 0xff, HZ))
return;
/* fix up some defaults */
if ((dev->control_state[1] != 2) ||
(dev->control_state[2] != 3) ||
(dev->control_state[4] != 2)) {
dev->control_state[1] = 2;
dev->control_state[2] = 3;
dev->control_state[4] = 2;
snd_usb_caiaq_send_command(dev,
EP1_CMD_WRITE_IO, dev->control_state, 6);
}
break;
}
if (dev->spec.num_analog_audio_out +
dev->spec.num_analog_audio_in +
dev->spec.num_digital_audio_out +
dev->spec.num_digital_audio_in > 0) {
ret = snd_usb_caiaq_audio_init(dev);
if (ret < 0)
log("Unable to set up audio system (ret=%d)\n", ret);
}
if (dev->spec.num_midi_in +
dev->spec.num_midi_out > 0) {
ret = snd_usb_caiaq_midi_init(dev);
if (ret < 0)
log("Unable to set up MIDI system (ret=%d)\n", ret);
}
#ifdef CONFIG_SND_USB_CAIAQ_INPUT
ret = snd_usb_caiaq_input_init(dev);
if (ret < 0)
log("Unable to set up input system (ret=%d)\n", ret);
#endif
/* finally, register the card and all its sub-instances */
ret = snd_card_register(dev->chip.card);
if (ret < 0) {
log("snd_card_register() returned %d\n", ret);
snd_card_free(dev->chip.card);
}
ret = snd_usb_caiaq_control_init(dev);
if (ret < 0)
log("Unable to set up control system (ret=%d)\n", ret);
}
static int create_card(struct usb_device *usb_dev,
struct usb_interface *intf,
struct snd_card **cardp)
{
int devnum;
int err;
struct snd_card *card;
struct snd_usb_caiaqdev *dev;
for (devnum = 0; devnum < SNDRV_CARDS; devnum++)
if (enable[devnum] && !snd_card_used[devnum])
break;
if (devnum >= SNDRV_CARDS)
return -ENODEV;
err = snd_card_create(index[devnum], id[devnum], THIS_MODULE,
sizeof(struct snd_usb_caiaqdev), &card);
if (err < 0)
return err;
dev = caiaqdev(card);
dev->chip.dev = usb_dev;
dev->chip.card = card;
dev->chip.usb_id = USB_ID(le16_to_cpu(usb_dev->descriptor.idVendor),
le16_to_cpu(usb_dev->descriptor.idProduct));
spin_lock_init(&dev->spinlock);
snd_card_set_dev(card, &intf->dev);
*cardp = card;
return 0;
}
static int __devinit init_card(struct snd_usb_caiaqdev *dev)
{
char *c, usbpath[32];
struct usb_device *usb_dev = dev->chip.dev;
struct snd_card *card = dev->chip.card;
int err, len;
if (usb_set_interface(usb_dev, 0, 1) != 0) {
log("can't set alt interface.\n");
return -EIO;
}
usb_init_urb(&dev->ep1_in_urb);
usb_init_urb(&dev->midi_out_urb);
usb_fill_bulk_urb(&dev->ep1_in_urb, usb_dev,
usb_rcvbulkpipe(usb_dev, 0x1),
dev->ep1_in_buf, EP1_BUFSIZE,
usb_ep1_command_reply_dispatch, dev);
usb_fill_bulk_urb(&dev->midi_out_urb, usb_dev,
usb_sndbulkpipe(usb_dev, 0x1),
dev->midi_out_buf, EP1_BUFSIZE,
snd_usb_caiaq_midi_output_done, dev);
init_waitqueue_head(&dev->ep1_wait_queue);
init_waitqueue_head(&dev->prepare_wait_queue);
if (usb_submit_urb(&dev->ep1_in_urb, GFP_KERNEL) != 0)
return -EIO;
err = snd_usb_caiaq_send_command(dev, EP1_CMD_GET_DEVICE_INFO, NULL, 0);
if (err)
return err;
if (!wait_event_timeout(dev->ep1_wait_queue, dev->spec_received, HZ))
return -ENODEV;
usb_string(usb_dev, usb_dev->descriptor.iManufacturer,
dev->vendor_name, CAIAQ_USB_STR_LEN);
usb_string(usb_dev, usb_dev->descriptor.iProduct,
dev->product_name, CAIAQ_USB_STR_LEN);
strlcpy(card->driver, MODNAME, sizeof(card->driver));
strlcpy(card->shortname, dev->product_name, sizeof(card->shortname));
strlcpy(card->mixername, dev->product_name, sizeof(card->mixername));
/* if the id was not passed as module option, fill it with a shortened
* version of the product string which does not contain any
* whitespaces */
if (*card->id == '\0') {
char id[sizeof(card->id)];
memset(id, 0, sizeof(id));
for (c = card->shortname, len = 0;
*c && len < sizeof(card->id); c++)
if (*c != ' ')
id[len++] = *c;
snd_card_set_id(card, id);
}
usb_make_path(usb_dev, usbpath, sizeof(usbpath));
snprintf(card->longname, sizeof(card->longname),
"%s %s (%s)",
dev->vendor_name, dev->product_name, usbpath);
setup_card(dev);
return 0;
}
static int __devinit snd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
int ret;
struct snd_card *card;
struct usb_device *device = interface_to_usbdev(intf);
ret = create_card(device, intf, &card);
if (ret < 0)
return ret;
usb_set_intfdata(intf, card);
ret = init_card(caiaqdev(card));
if (ret < 0) {
log("unable to init card! (ret=%d)\n", ret);
snd_card_free(card);
return ret;
}
return 0;
}
static void snd_disconnect(struct usb_interface *intf)
{
struct snd_usb_caiaqdev *dev;
struct snd_card *card = usb_get_intfdata(intf);
debug("%s(%p)\n", __func__, intf);
if (!card)
return;
dev = caiaqdev(card);
snd_card_disconnect(card);
#ifdef CONFIG_SND_USB_CAIAQ_INPUT
snd_usb_caiaq_input_free(dev);
#endif
snd_usb_caiaq_audio_free(dev);
usb_kill_urb(&dev->ep1_in_urb);
usb_kill_urb(&dev->midi_out_urb);
snd_card_free(card);
usb_reset_device(interface_to_usbdev(intf));
}
MODULE_DEVICE_TABLE(usb, snd_usb_id_table);
static struct usb_driver snd_usb_driver = {
.name = MODNAME,
.probe = snd_probe,
.disconnect = snd_disconnect,
.id_table = snd_usb_id_table,
};
module_usb_driver(snd_usb_driver);
| gpl-2.0 |
SlimRoms/kernel_htc_flounder | sound/isa/wavefront/wavefront_midi.c | 3325 | 15526 | /*
* Copyright (C) by Paul Barton-Davis 1998-1999
*
* This file is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this
* software for more info.
*/
/* The low level driver for the WaveFront ICS2115 MIDI interface(s)
*
* Note that there is also an MPU-401 emulation (actually, a UART-401
* emulation) on the CS4232 on the Tropez and Tropez Plus. This code
* has nothing to do with that interface at all.
*
* The interface is essentially just a UART-401, but is has the
* interesting property of supporting what Turtle Beach called
* "Virtual MIDI" mode. In this mode, there are effectively *two*
* MIDI buses accessible via the interface, one that is routed
* solely to/from the external WaveFront synthesizer and the other
* corresponding to the pin/socket connector used to link external
* MIDI devices to the board.
*
* This driver fully supports this mode, allowing two distinct MIDI
* busses to be used completely independently, giving 32 channels of
* MIDI routing, 16 to the WaveFront synth and 16 to the external MIDI
* bus. The devices are named /dev/snd/midiCnD0 and /dev/snd/midiCnD1,
* where `n' is the card number. Note that the device numbers may be
* something other than 0 and 1 if the CS4232 UART/MPU-401 interface
* is enabled.
*
* Switching between the two is accomplished externally by the driver
* using the two otherwise unused MIDI bytes. See the code for more details.
*
* NOTE: VIRTUAL MIDI MODE IS ON BY DEFAULT (see lowlevel/isa/wavefront.c)
*
* The main reason to turn off Virtual MIDI mode is when you want to
* tightly couple the WaveFront synth with an external MIDI
* device. You won't be able to distinguish the source of any MIDI
* data except via SysEx ID, but thats probably OK, since for the most
* part, the WaveFront won't be sending any MIDI data at all.
*
* The main reason to turn on Virtual MIDI Mode is to provide two
* completely independent 16-channel MIDI buses, one to the
* WaveFront and one to any external MIDI devices. Given the 32
* voice nature of the WaveFront, its pretty easy to find a use
* for all 16 channels driving just that synth.
*
*/
#include <asm/io.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <sound/core.h>
#include <sound/snd_wavefront.h>
static inline int
wf_mpu_status (snd_wavefront_midi_t *midi)
{
return inb (midi->mpu_status_port);
}
static inline int
input_avail (snd_wavefront_midi_t *midi)
{
return !(wf_mpu_status(midi) & INPUT_AVAIL);
}
static inline int
output_ready (snd_wavefront_midi_t *midi)
{
return !(wf_mpu_status(midi) & OUTPUT_READY);
}
static inline int
read_data (snd_wavefront_midi_t *midi)
{
return inb (midi->mpu_data_port);
}
static inline void
write_data (snd_wavefront_midi_t *midi, unsigned char byte)
{
outb (byte, midi->mpu_data_port);
}
static snd_wavefront_midi_t *
get_wavefront_midi (struct snd_rawmidi_substream *substream)
{
struct snd_card *card;
snd_wavefront_card_t *acard;
if (substream == NULL || substream->rmidi == NULL)
return NULL;
card = substream->rmidi->card;
if (card == NULL)
return NULL;
if (card->private_data == NULL)
return NULL;
acard = card->private_data;
return &acard->wavefront.midi;
}
static void snd_wavefront_midi_output_write(snd_wavefront_card_t *card)
{
snd_wavefront_midi_t *midi = &card->wavefront.midi;
snd_wavefront_mpu_id mpu;
unsigned long flags;
unsigned char midi_byte;
int max = 256, mask = 1;
int timeout;
/* Its not OK to try to change the status of "virtuality" of
the MIDI interface while we're outputting stuff. See
snd_wavefront_midi_{enable,disable}_virtual () for the
other half of this.
The first loop attempts to flush any data from the
current output device, and then the second
emits the switch byte (if necessary), and starts
outputting data for the output device currently in use.
*/
if (midi->substream_output[midi->output_mpu] == NULL) {
goto __second;
}
while (max > 0) {
/* XXX fix me - no hard timing loops allowed! */
for (timeout = 30000; timeout > 0; timeout--) {
if (output_ready (midi))
break;
}
spin_lock_irqsave (&midi->virtual, flags);
if ((midi->mode[midi->output_mpu] & MPU401_MODE_OUTPUT) == 0) {
spin_unlock_irqrestore (&midi->virtual, flags);
goto __second;
}
if (output_ready (midi)) {
if (snd_rawmidi_transmit(midi->substream_output[midi->output_mpu], &midi_byte, 1) == 1) {
if (!midi->isvirtual ||
(midi_byte != WF_INTERNAL_SWITCH &&
midi_byte != WF_EXTERNAL_SWITCH))
write_data(midi, midi_byte);
max--;
} else {
if (midi->istimer) {
if (--midi->istimer <= 0)
del_timer(&midi->timer);
}
midi->mode[midi->output_mpu] &= ~MPU401_MODE_OUTPUT_TRIGGER;
spin_unlock_irqrestore (&midi->virtual, flags);
goto __second;
}
} else {
spin_unlock_irqrestore (&midi->virtual, flags);
return;
}
spin_unlock_irqrestore (&midi->virtual, flags);
}
__second:
if (midi->substream_output[!midi->output_mpu] == NULL) {
return;
}
while (max > 0) {
/* XXX fix me - no hard timing loops allowed! */
for (timeout = 30000; timeout > 0; timeout--) {
if (output_ready (midi))
break;
}
spin_lock_irqsave (&midi->virtual, flags);
if (!midi->isvirtual)
mask = 0;
mpu = midi->output_mpu ^ mask;
mask = 0; /* don't invert the value from now */
if ((midi->mode[mpu] & MPU401_MODE_OUTPUT) == 0) {
spin_unlock_irqrestore (&midi->virtual, flags);
return;
}
if (snd_rawmidi_transmit_empty(midi->substream_output[mpu]))
goto __timer;
if (output_ready (midi)) {
if (mpu != midi->output_mpu) {
write_data(midi, mpu == internal_mpu ?
WF_INTERNAL_SWITCH :
WF_EXTERNAL_SWITCH);
midi->output_mpu = mpu;
} else if (snd_rawmidi_transmit(midi->substream_output[mpu], &midi_byte, 1) == 1) {
if (!midi->isvirtual ||
(midi_byte != WF_INTERNAL_SWITCH &&
midi_byte != WF_EXTERNAL_SWITCH))
write_data(midi, midi_byte);
max--;
} else {
__timer:
if (midi->istimer) {
if (--midi->istimer <= 0)
del_timer(&midi->timer);
}
midi->mode[mpu] &= ~MPU401_MODE_OUTPUT_TRIGGER;
spin_unlock_irqrestore (&midi->virtual, flags);
return;
}
} else {
spin_unlock_irqrestore (&midi->virtual, flags);
return;
}
spin_unlock_irqrestore (&midi->virtual, flags);
}
}
static int snd_wavefront_midi_input_open(struct snd_rawmidi_substream *substream)
{
unsigned long flags;
snd_wavefront_midi_t *midi;
snd_wavefront_mpu_id mpu;
if (snd_BUG_ON(!substream || !substream->rmidi))
return -ENXIO;
if (snd_BUG_ON(!substream->rmidi->private_data))
return -ENXIO;
mpu = *((snd_wavefront_mpu_id *) substream->rmidi->private_data);
if ((midi = get_wavefront_midi (substream)) == NULL)
return -EIO;
spin_lock_irqsave (&midi->open, flags);
midi->mode[mpu] |= MPU401_MODE_INPUT;
midi->substream_input[mpu] = substream;
spin_unlock_irqrestore (&midi->open, flags);
return 0;
}
static int snd_wavefront_midi_output_open(struct snd_rawmidi_substream *substream)
{
unsigned long flags;
snd_wavefront_midi_t *midi;
snd_wavefront_mpu_id mpu;
if (snd_BUG_ON(!substream || !substream->rmidi))
return -ENXIO;
if (snd_BUG_ON(!substream->rmidi->private_data))
return -ENXIO;
mpu = *((snd_wavefront_mpu_id *) substream->rmidi->private_data);
if ((midi = get_wavefront_midi (substream)) == NULL)
return -EIO;
spin_lock_irqsave (&midi->open, flags);
midi->mode[mpu] |= MPU401_MODE_OUTPUT;
midi->substream_output[mpu] = substream;
spin_unlock_irqrestore (&midi->open, flags);
return 0;
}
static int snd_wavefront_midi_input_close(struct snd_rawmidi_substream *substream)
{
unsigned long flags;
snd_wavefront_midi_t *midi;
snd_wavefront_mpu_id mpu;
if (snd_BUG_ON(!substream || !substream->rmidi))
return -ENXIO;
if (snd_BUG_ON(!substream->rmidi->private_data))
return -ENXIO;
mpu = *((snd_wavefront_mpu_id *) substream->rmidi->private_data);
if ((midi = get_wavefront_midi (substream)) == NULL)
return -EIO;
spin_lock_irqsave (&midi->open, flags);
midi->mode[mpu] &= ~MPU401_MODE_INPUT;
spin_unlock_irqrestore (&midi->open, flags);
return 0;
}
static int snd_wavefront_midi_output_close(struct snd_rawmidi_substream *substream)
{
unsigned long flags;
snd_wavefront_midi_t *midi;
snd_wavefront_mpu_id mpu;
if (snd_BUG_ON(!substream || !substream->rmidi))
return -ENXIO;
if (snd_BUG_ON(!substream->rmidi->private_data))
return -ENXIO;
mpu = *((snd_wavefront_mpu_id *) substream->rmidi->private_data);
if ((midi = get_wavefront_midi (substream)) == NULL)
return -EIO;
spin_lock_irqsave (&midi->open, flags);
midi->mode[mpu] &= ~MPU401_MODE_OUTPUT;
spin_unlock_irqrestore (&midi->open, flags);
return 0;
}
static void snd_wavefront_midi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
unsigned long flags;
snd_wavefront_midi_t *midi;
snd_wavefront_mpu_id mpu;
if (substream == NULL || substream->rmidi == NULL)
return;
if (substream->rmidi->private_data == NULL)
return;
mpu = *((snd_wavefront_mpu_id *) substream->rmidi->private_data);
if ((midi = get_wavefront_midi (substream)) == NULL) {
return;
}
spin_lock_irqsave (&midi->virtual, flags);
if (up) {
midi->mode[mpu] |= MPU401_MODE_INPUT_TRIGGER;
} else {
midi->mode[mpu] &= ~MPU401_MODE_INPUT_TRIGGER;
}
spin_unlock_irqrestore (&midi->virtual, flags);
}
static void snd_wavefront_midi_output_timer(unsigned long data)
{
snd_wavefront_card_t *card = (snd_wavefront_card_t *)data;
snd_wavefront_midi_t *midi = &card->wavefront.midi;
unsigned long flags;
spin_lock_irqsave (&midi->virtual, flags);
midi->timer.expires = 1 + jiffies;
add_timer(&midi->timer);
spin_unlock_irqrestore (&midi->virtual, flags);
snd_wavefront_midi_output_write(card);
}
static void snd_wavefront_midi_output_trigger(struct snd_rawmidi_substream *substream, int up)
{
unsigned long flags;
snd_wavefront_midi_t *midi;
snd_wavefront_mpu_id mpu;
if (substream == NULL || substream->rmidi == NULL)
return;
if (substream->rmidi->private_data == NULL)
return;
mpu = *((snd_wavefront_mpu_id *) substream->rmidi->private_data);
if ((midi = get_wavefront_midi (substream)) == NULL) {
return;
}
spin_lock_irqsave (&midi->virtual, flags);
if (up) {
if ((midi->mode[mpu] & MPU401_MODE_OUTPUT_TRIGGER) == 0) {
if (!midi->istimer) {
init_timer(&midi->timer);
midi->timer.function = snd_wavefront_midi_output_timer;
midi->timer.data = (unsigned long) substream->rmidi->card->private_data;
midi->timer.expires = 1 + jiffies;
add_timer(&midi->timer);
}
midi->istimer++;
midi->mode[mpu] |= MPU401_MODE_OUTPUT_TRIGGER;
}
} else {
midi->mode[mpu] &= ~MPU401_MODE_OUTPUT_TRIGGER;
}
spin_unlock_irqrestore (&midi->virtual, flags);
if (up)
snd_wavefront_midi_output_write((snd_wavefront_card_t *)substream->rmidi->card->private_data);
}
void
snd_wavefront_midi_interrupt (snd_wavefront_card_t *card)
{
unsigned long flags;
snd_wavefront_midi_t *midi;
static struct snd_rawmidi_substream *substream = NULL;
static int mpu = external_mpu;
int max = 128;
unsigned char byte;
midi = &card->wavefront.midi;
if (!input_avail (midi)) { /* not for us */
snd_wavefront_midi_output_write(card);
return;
}
spin_lock_irqsave (&midi->virtual, flags);
while (--max) {
if (input_avail (midi)) {
byte = read_data (midi);
if (midi->isvirtual) {
if (byte == WF_EXTERNAL_SWITCH) {
substream = midi->substream_input[external_mpu];
mpu = external_mpu;
} else if (byte == WF_INTERNAL_SWITCH) {
substream = midi->substream_output[internal_mpu];
mpu = internal_mpu;
} /* else just leave it as it is */
} else {
substream = midi->substream_input[internal_mpu];
mpu = internal_mpu;
}
if (substream == NULL) {
continue;
}
if (midi->mode[mpu] & MPU401_MODE_INPUT_TRIGGER) {
snd_rawmidi_receive(substream, &byte, 1);
}
} else {
break;
}
}
spin_unlock_irqrestore (&midi->virtual, flags);
snd_wavefront_midi_output_write(card);
}
void
snd_wavefront_midi_enable_virtual (snd_wavefront_card_t *card)
{
unsigned long flags;
spin_lock_irqsave (&card->wavefront.midi.virtual, flags);
card->wavefront.midi.isvirtual = 1;
card->wavefront.midi.output_mpu = internal_mpu;
card->wavefront.midi.input_mpu = internal_mpu;
spin_unlock_irqrestore (&card->wavefront.midi.virtual, flags);
}
void
snd_wavefront_midi_disable_virtual (snd_wavefront_card_t *card)
{
unsigned long flags;
spin_lock_irqsave (&card->wavefront.midi.virtual, flags);
// snd_wavefront_midi_input_close (card->ics2115_external_rmidi);
// snd_wavefront_midi_output_close (card->ics2115_external_rmidi);
card->wavefront.midi.isvirtual = 0;
spin_unlock_irqrestore (&card->wavefront.midi.virtual, flags);
}
int
snd_wavefront_midi_start (snd_wavefront_card_t *card)
{
int ok, i;
unsigned char rbuf[4], wbuf[4];
snd_wavefront_t *dev;
snd_wavefront_midi_t *midi;
dev = &card->wavefront;
midi = &dev->midi;
/* The ICS2115 MPU-401 interface doesn't do anything
until its set into UART mode.
*/
/* XXX fix me - no hard timing loops allowed! */
for (i = 0; i < 30000 && !output_ready (midi); i++);
if (!output_ready (midi)) {
snd_printk ("MIDI interface not ready for command\n");
return -1;
}
/* Any interrupts received from now on
are owned by the MIDI side of things.
*/
dev->interrupts_are_midi = 1;
outb (UART_MODE_ON, midi->mpu_command_port);
for (ok = 0, i = 50000; i > 0 && !ok; i--) {
if (input_avail (midi)) {
if (read_data (midi) == MPU_ACK) {
ok = 1;
break;
}
}
}
if (!ok) {
snd_printk ("cannot set UART mode for MIDI interface");
dev->interrupts_are_midi = 0;
return -1;
}
/* Route external MIDI to WaveFront synth (by default) */
if (snd_wavefront_cmd (dev, WFC_MISYNTH_ON, rbuf, wbuf)) {
snd_printk ("can't enable MIDI-IN-2-synth routing.\n");
/* XXX error ? */
}
/* Turn on Virtual MIDI, but first *always* turn it off,
since otherwise consecutive reloads of the driver will
never cause the hardware to generate the initial "internal" or
"external" source bytes in the MIDI data stream. This
is pretty important, since the internal hardware generally will
be used to generate none or very little MIDI output, and
thus the only source of MIDI data is actually external. Without
the switch bytes, the driver will think it all comes from
the internal interface. Duh.
*/
if (snd_wavefront_cmd (dev, WFC_VMIDI_OFF, rbuf, wbuf)) {
snd_printk ("virtual MIDI mode not disabled\n");
return 0; /* We're OK, but missing the external MIDI dev */
}
snd_wavefront_midi_enable_virtual (card);
if (snd_wavefront_cmd (dev, WFC_VMIDI_ON, rbuf, wbuf)) {
snd_printk ("cannot enable virtual MIDI mode.\n");
snd_wavefront_midi_disable_virtual (card);
}
return 0;
}
struct snd_rawmidi_ops snd_wavefront_midi_output =
{
.open = snd_wavefront_midi_output_open,
.close = snd_wavefront_midi_output_close,
.trigger = snd_wavefront_midi_output_trigger,
};
struct snd_rawmidi_ops snd_wavefront_midi_input =
{
.open = snd_wavefront_midi_input_open,
.close = snd_wavefront_midi_input_close,
.trigger = snd_wavefront_midi_input_trigger,
};
| gpl-2.0 |
luckasfb/kernel_lenovo_a3000 | net/netfilter/xt_NFQUEUE.c | 4605 | 4143 | /* iptables module for using new netfilter netlink queue
*
* (C) 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 version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/jhash.h>
#include <linux/netfilter.h>
#include <linux/netfilter_arp.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_NFQUEUE.h>
MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
MODULE_DESCRIPTION("Xtables: packet forwarding to netlink");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_NFQUEUE");
MODULE_ALIAS("ip6t_NFQUEUE");
MODULE_ALIAS("arpt_NFQUEUE");
static u32 jhash_initval __read_mostly;
static bool rnd_inited __read_mostly;
static unsigned int
nfqueue_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_NFQ_info *tinfo = par->targinfo;
return NF_QUEUE_NR(tinfo->queuenum);
}
static u32 hash_v4(const struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
__be32 ipaddr;
/* packets in either direction go into same queue */
ipaddr = iph->saddr ^ iph->daddr;
return jhash_2words((__force u32)ipaddr, iph->protocol, jhash_initval);
}
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
static u32 hash_v6(const struct sk_buff *skb)
{
const struct ipv6hdr *ip6h = ipv6_hdr(skb);
__be32 addr[4];
addr[0] = ip6h->saddr.s6_addr32[0] ^ ip6h->daddr.s6_addr32[0];
addr[1] = ip6h->saddr.s6_addr32[1] ^ ip6h->daddr.s6_addr32[1];
addr[2] = ip6h->saddr.s6_addr32[2] ^ ip6h->daddr.s6_addr32[2];
addr[3] = ip6h->saddr.s6_addr32[3] ^ ip6h->daddr.s6_addr32[3];
return jhash2((__force u32 *)addr, ARRAY_SIZE(addr), jhash_initval);
}
#endif
static unsigned int
nfqueue_tg_v1(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_NFQ_info_v1 *info = par->targinfo;
u32 queue = info->queuenum;
if (info->queues_total > 1) {
if (par->family == NFPROTO_IPV4)
queue = (((u64) hash_v4(skb) * info->queues_total) >>
32) + queue;
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
else if (par->family == NFPROTO_IPV6)
queue = (((u64) hash_v6(skb) * info->queues_total) >>
32) + queue;
#endif
}
return NF_QUEUE_NR(queue);
}
static unsigned int
nfqueue_tg_v2(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_NFQ_info_v2 *info = par->targinfo;
unsigned int ret = nfqueue_tg_v1(skb, par);
if (info->bypass)
ret |= NF_VERDICT_FLAG_QUEUE_BYPASS;
return ret;
}
static int nfqueue_tg_check(const struct xt_tgchk_param *par)
{
const struct xt_NFQ_info_v2 *info = par->targinfo;
u32 maxid;
if (unlikely(!rnd_inited)) {
get_random_bytes(&jhash_initval, sizeof(jhash_initval));
rnd_inited = true;
}
if (info->queues_total == 0) {
pr_err("NFQUEUE: number of total queues is 0\n");
return -EINVAL;
}
maxid = info->queues_total - 1 + info->queuenum;
if (maxid > 0xffff) {
pr_err("NFQUEUE: number of queues (%u) out of range (got %u)\n",
info->queues_total, maxid);
return -ERANGE;
}
if (par->target->revision == 2 && info->bypass > 1)
return -EINVAL;
return 0;
}
static struct xt_target nfqueue_tg_reg[] __read_mostly = {
{
.name = "NFQUEUE",
.family = NFPROTO_UNSPEC,
.target = nfqueue_tg,
.targetsize = sizeof(struct xt_NFQ_info),
.me = THIS_MODULE,
},
{
.name = "NFQUEUE",
.revision = 1,
.family = NFPROTO_UNSPEC,
.checkentry = nfqueue_tg_check,
.target = nfqueue_tg_v1,
.targetsize = sizeof(struct xt_NFQ_info_v1),
.me = THIS_MODULE,
},
{
.name = "NFQUEUE",
.revision = 2,
.family = NFPROTO_UNSPEC,
.checkentry = nfqueue_tg_check,
.target = nfqueue_tg_v2,
.targetsize = sizeof(struct xt_NFQ_info_v2),
.me = THIS_MODULE,
},
};
static int __init nfqueue_tg_init(void)
{
return xt_register_targets(nfqueue_tg_reg, ARRAY_SIZE(nfqueue_tg_reg));
}
static void __exit nfqueue_tg_exit(void)
{
xt_unregister_targets(nfqueue_tg_reg, ARRAY_SIZE(nfqueue_tg_reg));
}
module_init(nfqueue_tg_init);
module_exit(nfqueue_tg_exit);
| gpl-2.0 |
fefifofum/android_kernel_bq_maxwell2qc | arch/m68k/apollo/dn_ints.c | 4605 | 1049 | #include <linux/interrupt.h>
#include <asm/irq.h>
#include <asm/traps.h>
#include <asm/apollohw.h>
void dn_process_int(unsigned int irq, struct pt_regs *fp)
{
__m68k_handle_int(irq, fp);
*(volatile unsigned char *)(pica)=0x20;
*(volatile unsigned char *)(picb)=0x20;
}
int apollo_irq_startup(unsigned int irq)
{
if (irq < 8)
*(volatile unsigned char *)(pica+1) &= ~(1 << irq);
else
*(volatile unsigned char *)(picb+1) &= ~(1 << (irq - 8));
return 0;
}
void apollo_irq_shutdown(unsigned int irq)
{
if (irq < 8)
*(volatile unsigned char *)(pica+1) |= (1 << irq);
else
*(volatile unsigned char *)(picb+1) |= (1 << (irq - 8));
}
static struct irq_controller apollo_irq_controller = {
.name = "apollo",
.lock = __SPIN_LOCK_UNLOCKED(apollo_irq_controller.lock),
.startup = apollo_irq_startup,
.shutdown = apollo_irq_shutdown,
};
void __init dn_init_IRQ(void)
{
m68k_setup_user_interrupt(VEC_USER + 96, 16, dn_process_int);
m68k_setup_irq_controller(&apollo_irq_controller, IRQ_APOLLO, 16);
}
| gpl-2.0 |
zeroblade1984/LG_MSM8974 | sound/soc/codecs/wm8776.c | 4861 | 13766 | /*
* wm8776.c -- WM8776 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.
*
* TODO: Input ALC/limiter support
*/
#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/of_device.h>
#include <linux/spi/spi.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 "wm8776.h"
enum wm8776_chip_type {
WM8775 = 1,
WM8776,
};
/* codec private data */
struct wm8776_priv {
enum snd_soc_control_type control_type;
int sysclk[2];
};
static const u16 wm8776_reg[WM8776_CACHEREGNUM] = {
0x79, 0x79, 0x79, 0xff, 0xff, /* 4 */
0xff, 0x00, 0x90, 0x00, 0x00, /* 9 */
0x22, 0x22, 0x22, 0x08, 0xcf, /* 14 */
0xcf, 0x7b, 0x00, 0x32, 0x00, /* 19 */
0xa6, 0x01, 0x01
};
static int wm8776_reset(struct snd_soc_codec *codec)
{
return snd_soc_write(codec, WM8776_RESET, 0);
}
static const DECLARE_TLV_DB_SCALE(hp_tlv, -12100, 100, 1);
static const DECLARE_TLV_DB_SCALE(dac_tlv, -12750, 50, 1);
static const DECLARE_TLV_DB_SCALE(adc_tlv, -10350, 50, 1);
static const struct snd_kcontrol_new wm8776_snd_controls[] = {
SOC_DOUBLE_R_TLV("Headphone Playback Volume", WM8776_HPLVOL, WM8776_HPRVOL,
0, 127, 0, hp_tlv),
SOC_DOUBLE_R_TLV("Digital Playback Volume", WM8776_DACLVOL, WM8776_DACRVOL,
0, 255, 0, dac_tlv),
SOC_SINGLE("Digital Playback ZC Switch", WM8776_DACCTRL1, 0, 1, 0),
SOC_SINGLE("Deemphasis Switch", WM8776_DACCTRL2, 0, 1, 0),
SOC_DOUBLE_R_TLV("Capture Volume", WM8776_ADCLVOL, WM8776_ADCRVOL,
0, 255, 0, adc_tlv),
SOC_DOUBLE("Capture Switch", WM8776_ADCMUX, 7, 6, 1, 1),
SOC_DOUBLE_R("Capture ZC Switch", WM8776_ADCLVOL, WM8776_ADCRVOL, 8, 1, 0),
SOC_SINGLE("Capture HPF Switch", WM8776_ADCIFCTRL, 8, 1, 1),
};
static const struct snd_kcontrol_new inmix_controls[] = {
SOC_DAPM_SINGLE("AIN1 Switch", WM8776_ADCMUX, 0, 1, 0),
SOC_DAPM_SINGLE("AIN2 Switch", WM8776_ADCMUX, 1, 1, 0),
SOC_DAPM_SINGLE("AIN3 Switch", WM8776_ADCMUX, 2, 1, 0),
SOC_DAPM_SINGLE("AIN4 Switch", WM8776_ADCMUX, 3, 1, 0),
SOC_DAPM_SINGLE("AIN5 Switch", WM8776_ADCMUX, 4, 1, 0),
};
static const struct snd_kcontrol_new outmix_controls[] = {
SOC_DAPM_SINGLE("DAC Switch", WM8776_OUTMUX, 0, 1, 0),
SOC_DAPM_SINGLE("AUX Switch", WM8776_OUTMUX, 1, 1, 0),
SOC_DAPM_SINGLE("Bypass Switch", WM8776_OUTMUX, 2, 1, 0),
};
static const struct snd_soc_dapm_widget wm8776_dapm_widgets[] = {
SND_SOC_DAPM_INPUT("AUX"),
SND_SOC_DAPM_INPUT("AIN1"),
SND_SOC_DAPM_INPUT("AIN2"),
SND_SOC_DAPM_INPUT("AIN3"),
SND_SOC_DAPM_INPUT("AIN4"),
SND_SOC_DAPM_INPUT("AIN5"),
SND_SOC_DAPM_MIXER("Input Mixer", WM8776_PWRDOWN, 6, 1,
inmix_controls, ARRAY_SIZE(inmix_controls)),
SND_SOC_DAPM_ADC("ADC", "Capture", WM8776_PWRDOWN, 1, 1),
SND_SOC_DAPM_DAC("DAC", "Playback", WM8776_PWRDOWN, 2, 1),
SND_SOC_DAPM_MIXER("Output Mixer", SND_SOC_NOPM, 0, 0,
outmix_controls, ARRAY_SIZE(outmix_controls)),
SND_SOC_DAPM_PGA("Headphone PGA", WM8776_PWRDOWN, 3, 1, NULL, 0),
SND_SOC_DAPM_OUTPUT("VOUT"),
SND_SOC_DAPM_OUTPUT("HPOUTL"),
SND_SOC_DAPM_OUTPUT("HPOUTR"),
};
static const struct snd_soc_dapm_route routes[] = {
{ "Input Mixer", "AIN1 Switch", "AIN1" },
{ "Input Mixer", "AIN2 Switch", "AIN2" },
{ "Input Mixer", "AIN3 Switch", "AIN3" },
{ "Input Mixer", "AIN4 Switch", "AIN4" },
{ "Input Mixer", "AIN5 Switch", "AIN5" },
{ "ADC", NULL, "Input Mixer" },
{ "Output Mixer", "DAC Switch", "DAC" },
{ "Output Mixer", "AUX Switch", "AUX" },
{ "Output Mixer", "Bypass Switch", "Input Mixer" },
{ "VOUT", NULL, "Output Mixer" },
{ "Headphone PGA", NULL, "Output Mixer" },
{ "HPOUTL", NULL, "Headphone PGA" },
{ "HPOUTR", NULL, "Headphone PGA" },
};
static int wm8776_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct snd_soc_codec *codec = dai->codec;
int reg, iface, master;
switch (dai->driver->id) {
case WM8776_DAI_DAC:
reg = WM8776_DACIFCTRL;
master = 0x80;
break;
case WM8776_DAI_ADC:
reg = WM8776_ADCIFCTRL;
master = 0x100;
break;
default:
return -EINVAL;
}
iface = 0;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
break;
case SND_SOC_DAIFMT_CBS_CFS:
master = 0;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface |= 0x0002;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
iface |= 0x0001;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
iface |= 0x00c;
break;
case SND_SOC_DAIFMT_IB_NF:
iface |= 0x008;
break;
case SND_SOC_DAIFMT_NB_IF:
iface |= 0x004;
break;
default:
return -EINVAL;
}
/* Finally, write out the values */
snd_soc_update_bits(codec, reg, 0xf, iface);
snd_soc_update_bits(codec, WM8776_MSTRCTRL, 0x180, master);
return 0;
}
static int mclk_ratios[] = {
128,
192,
256,
384,
512,
768,
};
static int wm8776_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 wm8776_priv *wm8776 = snd_soc_codec_get_drvdata(codec);
int iface_reg, iface;
int ratio_shift, master;
int i;
switch (dai->driver->id) {
case WM8776_DAI_DAC:
iface_reg = WM8776_DACIFCTRL;
master = 0x80;
ratio_shift = 4;
break;
case WM8776_DAI_ADC:
iface_reg = WM8776_ADCIFCTRL;
master = 0x100;
ratio_shift = 0;
break;
default:
return -EINVAL;
}
/* Set word length */
switch (snd_pcm_format_width(params_format(params))) {
case 16:
iface = 0;
break;
case 20:
iface = 0x10;
break;
case 24:
iface = 0x20;
break;
case 32:
iface = 0x30;
break;
default:
dev_err(codec->dev, "Unsupported sample size: %i\n",
snd_pcm_format_width(params_format(params)));
return -EINVAL;
}
/* Only need to set MCLK/LRCLK ratio if we're master */
if (snd_soc_read(codec, WM8776_MSTRCTRL) & master) {
for (i = 0; i < ARRAY_SIZE(mclk_ratios); i++) {
if (wm8776->sysclk[dai->driver->id] / params_rate(params)
== mclk_ratios[i])
break;
}
if (i == ARRAY_SIZE(mclk_ratios)) {
dev_err(codec->dev,
"Unable to configure MCLK ratio %d/%d\n",
wm8776->sysclk[dai->driver->id], params_rate(params));
return -EINVAL;
}
dev_dbg(codec->dev, "MCLK is %dfs\n", mclk_ratios[i]);
snd_soc_update_bits(codec, WM8776_MSTRCTRL,
0x7 << ratio_shift, i << ratio_shift);
} else {
dev_dbg(codec->dev, "DAI in slave mode\n");
}
snd_soc_update_bits(codec, iface_reg, 0x30, iface);
return 0;
}
static int wm8776_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
return snd_soc_write(codec, WM8776_DACMUTE, !!mute);
}
static int wm8776_set_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = dai->codec;
struct wm8776_priv *wm8776 = snd_soc_codec_get_drvdata(codec);
BUG_ON(dai->driver->id >= ARRAY_SIZE(wm8776->sysclk));
wm8776->sysclk[dai->driver->id] = freq;
return 0;
}
static int wm8776_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) {
snd_soc_cache_sync(codec);
/* Disable the global powerdown; DAPM does the rest */
snd_soc_update_bits(codec, WM8776_PWRDOWN, 1, 0);
}
break;
case SND_SOC_BIAS_OFF:
snd_soc_update_bits(codec, WM8776_PWRDOWN, 1, 1);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define WM8776_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE)
static const struct snd_soc_dai_ops wm8776_dac_ops = {
.digital_mute = wm8776_mute,
.hw_params = wm8776_hw_params,
.set_fmt = wm8776_set_fmt,
.set_sysclk = wm8776_set_sysclk,
};
static const struct snd_soc_dai_ops wm8776_adc_ops = {
.hw_params = wm8776_hw_params,
.set_fmt = wm8776_set_fmt,
.set_sysclk = wm8776_set_sysclk,
};
static struct snd_soc_dai_driver wm8776_dai[] = {
{
.name = "wm8776-hifi-playback",
.id = WM8776_DAI_DAC,
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_CONTINUOUS,
.rate_min = 32000,
.rate_max = 192000,
.formats = WM8776_FORMATS,
},
.ops = &wm8776_dac_ops,
},
{
.name = "wm8776-hifi-capture",
.id = WM8776_DAI_ADC,
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_CONTINUOUS,
.rate_min = 32000,
.rate_max = 96000,
.formats = WM8776_FORMATS,
},
.ops = &wm8776_adc_ops,
},
};
#ifdef CONFIG_PM
static int wm8776_suspend(struct snd_soc_codec *codec)
{
wm8776_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int wm8776_resume(struct snd_soc_codec *codec)
{
wm8776_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
#else
#define wm8776_suspend NULL
#define wm8776_resume NULL
#endif
static int wm8776_probe(struct snd_soc_codec *codec)
{
struct wm8776_priv *wm8776 = snd_soc_codec_get_drvdata(codec);
int ret = 0;
ret = snd_soc_codec_set_cache_io(codec, 7, 9, wm8776->control_type);
if (ret < 0) {
dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret);
return ret;
}
ret = wm8776_reset(codec);
if (ret < 0) {
dev_err(codec->dev, "Failed to issue reset: %d\n", ret);
return ret;
}
wm8776_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
/* Latch the update bits; right channel only since we always
* update both. */
snd_soc_update_bits(codec, WM8776_HPRVOL, 0x100, 0x100);
snd_soc_update_bits(codec, WM8776_DACRVOL, 0x100, 0x100);
return ret;
}
/* power down chip */
static int wm8776_remove(struct snd_soc_codec *codec)
{
wm8776_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_wm8776 = {
.probe = wm8776_probe,
.remove = wm8776_remove,
.suspend = wm8776_suspend,
.resume = wm8776_resume,
.set_bias_level = wm8776_set_bias_level,
.reg_cache_size = ARRAY_SIZE(wm8776_reg),
.reg_word_size = sizeof(u16),
.reg_cache_default = wm8776_reg,
.controls = wm8776_snd_controls,
.num_controls = ARRAY_SIZE(wm8776_snd_controls),
.dapm_widgets = wm8776_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(wm8776_dapm_widgets),
.dapm_routes = routes,
.num_dapm_routes = ARRAY_SIZE(routes),
};
static const struct of_device_id wm8776_of_match[] = {
{ .compatible = "wlf,wm8776", },
{ }
};
MODULE_DEVICE_TABLE(of, wm8776_of_match);
#if defined(CONFIG_SPI_MASTER)
static int __devinit wm8776_spi_probe(struct spi_device *spi)
{
struct wm8776_priv *wm8776;
int ret;
wm8776 = devm_kzalloc(&spi->dev, sizeof(struct wm8776_priv),
GFP_KERNEL);
if (wm8776 == NULL)
return -ENOMEM;
wm8776->control_type = SND_SOC_SPI;
spi_set_drvdata(spi, wm8776);
ret = snd_soc_register_codec(&spi->dev,
&soc_codec_dev_wm8776, wm8776_dai, ARRAY_SIZE(wm8776_dai));
return ret;
}
static int __devexit wm8776_spi_remove(struct spi_device *spi)
{
snd_soc_unregister_codec(&spi->dev);
return 0;
}
static struct spi_driver wm8776_spi_driver = {
.driver = {
.name = "wm8776",
.owner = THIS_MODULE,
.of_match_table = wm8776_of_match,
},
.probe = wm8776_spi_probe,
.remove = __devexit_p(wm8776_spi_remove),
};
#endif /* CONFIG_SPI_MASTER */
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static __devinit int wm8776_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8776_priv *wm8776;
int ret;
wm8776 = devm_kzalloc(&i2c->dev, sizeof(struct wm8776_priv),
GFP_KERNEL);
if (wm8776 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, wm8776);
wm8776->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8776, wm8776_dai, ARRAY_SIZE(wm8776_dai));
return ret;
}
static __devexit int wm8776_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static const struct i2c_device_id wm8776_i2c_id[] = {
{ "wm8775", WM8775 },
{ "wm8776", WM8776 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8776_i2c_id);
static struct i2c_driver wm8776_i2c_driver = {
.driver = {
.name = "wm8776",
.owner = THIS_MODULE,
.of_match_table = wm8776_of_match,
},
.probe = wm8776_i2c_probe,
.remove = __devexit_p(wm8776_i2c_remove),
.id_table = wm8776_i2c_id,
};
#endif
static int __init wm8776_modinit(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&wm8776_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register wm8776 I2C driver: %d\n",
ret);
}
#endif
#if defined(CONFIG_SPI_MASTER)
ret = spi_register_driver(&wm8776_spi_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register wm8776 SPI driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(wm8776_modinit);
static void __exit wm8776_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&wm8776_i2c_driver);
#endif
#if defined(CONFIG_SPI_MASTER)
spi_unregister_driver(&wm8776_spi_driver);
#endif
}
module_exit(wm8776_exit);
MODULE_DESCRIPTION("ASoC WM8776 driver");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
widz4rd/WIDzard-A860L | tools/perf/bench/mem-memset.c | 4861 | 6606 | /*
* mem-memset.c
*
* memset: Simple memory set in various ways
*
* Trivial clone of mem-memcpy.c.
*/
#include "../perf.h"
#include "../util/util.h"
#include "../util/parse-options.h"
#include "../util/header.h"
#include "bench.h"
#include "mem-memset-arch.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <errno.h>
#define K 1024
static const char *length_str = "1MB";
static const char *routine = "default";
static int iterations = 1;
static bool use_clock;
static int clock_fd;
static bool only_prefault;
static bool no_prefault;
static const struct option options[] = {
OPT_STRING('l', "length", &length_str, "1MB",
"Specify length of memory to copy. "
"available unit: B, MB, GB (upper and lower)"),
OPT_STRING('r', "routine", &routine, "default",
"Specify routine to copy"),
OPT_INTEGER('i', "iterations", &iterations,
"repeat memset() invocation this number of times"),
OPT_BOOLEAN('c', "clock", &use_clock,
"Use CPU clock for measuring"),
OPT_BOOLEAN('o', "only-prefault", &only_prefault,
"Show only the result with page faults before memset()"),
OPT_BOOLEAN('n', "no-prefault", &no_prefault,
"Show only the result without page faults before memset()"),
OPT_END()
};
typedef void *(*memset_t)(void *, int, size_t);
struct routine {
const char *name;
const char *desc;
memset_t fn;
};
static const struct routine routines[] = {
{ "default",
"Default memset() provided by glibc",
memset },
#ifdef ARCH_X86_64
#define MEMSET_FN(fn, name, desc) { name, desc, fn },
#include "mem-memset-x86-64-asm-def.h"
#undef MEMSET_FN
#endif
{ NULL,
NULL,
NULL }
};
static const char * const bench_mem_memset_usage[] = {
"perf bench mem memset <options>",
NULL
};
static struct perf_event_attr clock_attr = {
.type = PERF_TYPE_HARDWARE,
.config = PERF_COUNT_HW_CPU_CYCLES
};
static void init_clock(void)
{
clock_fd = sys_perf_event_open(&clock_attr, getpid(), -1, -1, 0);
if (clock_fd < 0 && errno == ENOSYS)
die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
else
BUG_ON(clock_fd < 0);
}
static u64 get_clock(void)
{
int ret;
u64 clk;
ret = read(clock_fd, &clk, sizeof(u64));
BUG_ON(ret != sizeof(u64));
return clk;
}
static double timeval2double(struct timeval *ts)
{
return (double)ts->tv_sec +
(double)ts->tv_usec / (double)1000000;
}
static void alloc_mem(void **dst, size_t length)
{
*dst = zalloc(length);
if (!dst)
die("memory allocation failed - maybe length is too large?\n");
}
static u64 do_memset_clock(memset_t fn, size_t len, bool prefault)
{
u64 clock_start = 0ULL, clock_end = 0ULL;
void *dst = NULL;
int i;
alloc_mem(&dst, len);
if (prefault)
fn(dst, -1, len);
clock_start = get_clock();
for (i = 0; i < iterations; ++i)
fn(dst, i, len);
clock_end = get_clock();
free(dst);
return clock_end - clock_start;
}
static double do_memset_gettimeofday(memset_t fn, size_t len, bool prefault)
{
struct timeval tv_start, tv_end, tv_diff;
void *dst = NULL;
int i;
alloc_mem(&dst, len);
if (prefault)
fn(dst, -1, len);
BUG_ON(gettimeofday(&tv_start, NULL));
for (i = 0; i < iterations; ++i)
fn(dst, i, len);
BUG_ON(gettimeofday(&tv_end, NULL));
timersub(&tv_end, &tv_start, &tv_diff);
free(dst);
return (double)((double)len / timeval2double(&tv_diff));
}
#define pf (no_prefault ? 0 : 1)
#define print_bps(x) do { \
if (x < K) \
printf(" %14lf B/Sec", x); \
else if (x < K * K) \
printf(" %14lfd KB/Sec", x / K); \
else if (x < K * K * K) \
printf(" %14lf MB/Sec", x / K / K); \
else \
printf(" %14lf GB/Sec", x / K / K / K); \
} while (0)
int bench_mem_memset(int argc, const char **argv,
const char *prefix __used)
{
int i;
size_t len;
double result_bps[2];
u64 result_clock[2];
argc = parse_options(argc, argv, options,
bench_mem_memset_usage, 0);
if (use_clock)
init_clock();
len = (size_t)perf_atoll((char *)length_str);
result_clock[0] = result_clock[1] = 0ULL;
result_bps[0] = result_bps[1] = 0.0;
if ((s64)len <= 0) {
fprintf(stderr, "Invalid length:%s\n", length_str);
return 1;
}
/* same to without specifying either of prefault and no-prefault */
if (only_prefault && no_prefault)
only_prefault = no_prefault = false;
for (i = 0; routines[i].name; i++) {
if (!strcmp(routines[i].name, routine))
break;
}
if (!routines[i].name) {
printf("Unknown routine:%s\n", routine);
printf("Available routines...\n");
for (i = 0; routines[i].name; i++) {
printf("\t%s ... %s\n",
routines[i].name, routines[i].desc);
}
return 1;
}
if (bench_format == BENCH_FORMAT_DEFAULT)
printf("# Copying %s Bytes ...\n\n", length_str);
if (!only_prefault && !no_prefault) {
/* show both of results */
if (use_clock) {
result_clock[0] =
do_memset_clock(routines[i].fn, len, false);
result_clock[1] =
do_memset_clock(routines[i].fn, len, true);
} else {
result_bps[0] =
do_memset_gettimeofday(routines[i].fn,
len, false);
result_bps[1] =
do_memset_gettimeofday(routines[i].fn,
len, true);
}
} else {
if (use_clock) {
result_clock[pf] =
do_memset_clock(routines[i].fn,
len, only_prefault);
} else {
result_bps[pf] =
do_memset_gettimeofday(routines[i].fn,
len, only_prefault);
}
}
switch (bench_format) {
case BENCH_FORMAT_DEFAULT:
if (!only_prefault && !no_prefault) {
if (use_clock) {
printf(" %14lf Clock/Byte\n",
(double)result_clock[0]
/ (double)len);
printf(" %14lf Clock/Byte (with prefault)\n ",
(double)result_clock[1]
/ (double)len);
} else {
print_bps(result_bps[0]);
printf("\n");
print_bps(result_bps[1]);
printf(" (with prefault)\n");
}
} else {
if (use_clock) {
printf(" %14lf Clock/Byte",
(double)result_clock[pf]
/ (double)len);
} else
print_bps(result_bps[pf]);
printf("%s\n", only_prefault ? " (with prefault)" : "");
}
break;
case BENCH_FORMAT_SIMPLE:
if (!only_prefault && !no_prefault) {
if (use_clock) {
printf("%lf %lf\n",
(double)result_clock[0] / (double)len,
(double)result_clock[1] / (double)len);
} else {
printf("%lf %lf\n",
result_bps[0], result_bps[1]);
}
} else {
if (use_clock) {
printf("%lf\n", (double)result_clock[pf]
/ (double)len);
} else
printf("%lf\n", result_bps[pf]);
}
break;
default:
/* reaching this means there's some disaster: */
die("unknown format: %d\n", bench_format);
break;
}
return 0;
}
| gpl-2.0 |
kostoulhs/android_kernel_samsung_expressltexx | drivers/staging/rtl8187se/ieee80211/ieee80211_module.c | 5629 | 5468 | /*******************************************************************************
Copyright(c) 2004 Intel Corporation. All rights reserved.
Portions of this file are based on the WEP enablement code provided by the
Host AP project hostap-drivers v0.1.3
Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
<jkmaline@cc.hut.fi>
Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
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., 59
Temple Place - Suite 330, Boston, MA 02111-1307, USA.
The full GNU General Public License is included in this distribution in the
file called LICENSE.
Contact Information:
James P. Ketrenos <ipw2100-admin@linux.intel.com>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/compiler.h>
//#include <linux/config.h>
#include <linux/errno.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/pci.h>
#include <linux/proc_fs.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/tcp.h>
#include <linux/types.h>
#include <linux/wireless.h>
#include <linux/etherdevice.h>
#include <asm/uaccess.h>
#include <net/arp.h>
#include <net/net_namespace.h>
#include "ieee80211.h"
MODULE_DESCRIPTION("802.11 data/management/control stack");
MODULE_AUTHOR("Copyright (C) 2004 Intel Corporation <jketreno@linux.intel.com>");
MODULE_LICENSE("GPL");
#define DRV_NAME "ieee80211"
static inline int ieee80211_networks_allocate(struct ieee80211_device *ieee)
{
if (ieee->networks)
return 0;
ieee->networks = kcalloc(
MAX_NETWORK_COUNT, sizeof(struct ieee80211_network),
GFP_KERNEL);
if (!ieee->networks) {
printk(KERN_WARNING "%s: Out of memory allocating beacons\n",
ieee->dev->name);
return -ENOMEM;
}
return 0;
}
static inline void ieee80211_networks_free(struct ieee80211_device *ieee)
{
if (!ieee->networks)
return;
kfree(ieee->networks);
ieee->networks = NULL;
}
static inline void ieee80211_networks_initialize(struct ieee80211_device *ieee)
{
int i;
INIT_LIST_HEAD(&ieee->network_free_list);
INIT_LIST_HEAD(&ieee->network_list);
for (i = 0; i < MAX_NETWORK_COUNT; i++)
list_add_tail(&ieee->networks[i].list, &ieee->network_free_list);
}
struct net_device *alloc_ieee80211(int sizeof_priv)
{
struct ieee80211_device *ieee;
struct net_device *dev;
int i,err;
IEEE80211_DEBUG_INFO("Initializing...\n");
dev = alloc_etherdev(sizeof(struct ieee80211_device) + sizeof_priv);
if (!dev) {
IEEE80211_ERROR("Unable to network device.\n");
goto failed;
}
ieee = netdev_priv(dev);
ieee->dev = dev;
err = ieee80211_networks_allocate(ieee);
if (err) {
IEEE80211_ERROR("Unable to allocate beacon storage: %d\n",
err);
goto failed;
}
ieee80211_networks_initialize(ieee);
/* Default fragmentation threshold is maximum payload size */
ieee->fts = DEFAULT_FTS;
ieee->scan_age = DEFAULT_MAX_SCAN_AGE;
ieee->open_wep = 1;
/* Default to enabling full open WEP with host based encrypt/decrypt */
ieee->host_encrypt = 1;
ieee->host_decrypt = 1;
ieee->ieee802_1x = 1; /* Default to supporting 802.1x */
INIT_LIST_HEAD(&ieee->crypt_deinit_list);
init_timer(&ieee->crypt_deinit_timer);
ieee->crypt_deinit_timer.data = (unsigned long)ieee;
ieee->crypt_deinit_timer.function = ieee80211_crypt_deinit_handler;
spin_lock_init(&ieee->lock);
spin_lock_init(&ieee->wpax_suitlist_lock);
ieee->wpax_type_set = 0;
ieee->wpa_enabled = 0;
ieee->tkip_countermeasures = 0;
ieee->drop_unencrypted = 0;
ieee->privacy_invoked = 0;
ieee->ieee802_1x = 1;
ieee->raw_tx = 0;
ieee80211_softmac_init(ieee);
for (i = 0; i < IEEE_IBSS_MAC_HASH_SIZE; i++)
INIT_LIST_HEAD(&ieee->ibss_mac_hash[i]);
for (i = 0; i < 17; i++) {
ieee->last_rxseq_num[i] = -1;
ieee->last_rxfrag_num[i] = -1;
ieee->last_packet_time[i] = 0;
}
//These function were added to load crypte module autoly
ieee80211_tkip_null();
ieee80211_wep_null();
ieee80211_ccmp_null();
return dev;
failed:
if (dev)
free_netdev(dev);
return NULL;
}
void free_ieee80211(struct net_device *dev)
{
struct ieee80211_device *ieee = netdev_priv(dev);
int i;
struct list_head *p, *q;
ieee80211_softmac_free(ieee);
del_timer_sync(&ieee->crypt_deinit_timer);
ieee80211_crypt_deinit_entries(ieee, 1);
for (i = 0; i < WEP_KEYS; i++) {
struct ieee80211_crypt_data *crypt = ieee->crypt[i];
if (crypt) {
if (crypt->ops)
crypt->ops->deinit(crypt->priv);
kfree(crypt);
ieee->crypt[i] = NULL;
}
}
ieee80211_networks_free(ieee);
for (i = 0; i < IEEE_IBSS_MAC_HASH_SIZE; i++) {
list_for_each_safe(p, q, &ieee->ibss_mac_hash[i]) {
kfree(list_entry(p, struct ieee_ibss_seq, list));
list_del(p);
}
}
free_netdev(dev);
}
| gpl-2.0 |
mykernel/kernel | arch/sh/kernel/cpu/sh2a/fpu.c | 8957 | 13898 | /*
* Save/restore floating point context for signal handlers.
*
* Copyright (C) 1999, 2000 Kaz Kojima & Niibe Yutaka
*
* 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.
*
* FIXME! These routines can be optimized in big endian case.
*/
#include <linux/sched.h>
#include <linux/signal.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/fpu.h>
#include <asm/traps.h>
/* The PR (precision) bit in the FP Status Register must be clear when
* an frchg instruction is executed, otherwise the instruction is undefined.
* Executing frchg with PR set causes a trap on some SH4 implementations.
*/
#define FPSCR_RCHG 0x00000000
/*
* Save FPU registers onto task structure.
*/
void save_fpu(struct task_struct *tsk)
{
unsigned long dummy;
enable_fpu();
asm volatile("sts.l fpul, @-%0\n\t"
"sts.l fpscr, @-%0\n\t"
"fmov.s fr15, @-%0\n\t"
"fmov.s fr14, @-%0\n\t"
"fmov.s fr13, @-%0\n\t"
"fmov.s fr12, @-%0\n\t"
"fmov.s fr11, @-%0\n\t"
"fmov.s fr10, @-%0\n\t"
"fmov.s fr9, @-%0\n\t"
"fmov.s fr8, @-%0\n\t"
"fmov.s fr7, @-%0\n\t"
"fmov.s fr6, @-%0\n\t"
"fmov.s fr5, @-%0\n\t"
"fmov.s fr4, @-%0\n\t"
"fmov.s fr3, @-%0\n\t"
"fmov.s fr2, @-%0\n\t"
"fmov.s fr1, @-%0\n\t"
"fmov.s fr0, @-%0\n\t"
"lds %3, fpscr\n\t"
: "=r" (dummy)
: "0" ((char *)(&tsk->thread.xstate->hardfpu.status)),
"r" (FPSCR_RCHG),
"r" (FPSCR_INIT)
: "memory");
disable_fpu();
}
void restore_fpu(struct task_struct *tsk)
{
unsigned long dummy;
enable_fpu();
asm volatile("fmov.s @%0+, fr0\n\t"
"fmov.s @%0+, fr1\n\t"
"fmov.s @%0+, fr2\n\t"
"fmov.s @%0+, fr3\n\t"
"fmov.s @%0+, fr4\n\t"
"fmov.s @%0+, fr5\n\t"
"fmov.s @%0+, fr6\n\t"
"fmov.s @%0+, fr7\n\t"
"fmov.s @%0+, fr8\n\t"
"fmov.s @%0+, fr9\n\t"
"fmov.s @%0+, fr10\n\t"
"fmov.s @%0+, fr11\n\t"
"fmov.s @%0+, fr12\n\t"
"fmov.s @%0+, fr13\n\t"
"fmov.s @%0+, fr14\n\t"
"fmov.s @%0+, fr15\n\t"
"lds.l @%0+, fpscr\n\t"
"lds.l @%0+, fpul\n\t"
: "=r" (dummy)
: "0" (tsk->thread.xstate), "r" (FPSCR_RCHG)
: "memory");
disable_fpu();
}
/*
* Emulate arithmetic ops on denormalized number for some FPU insns.
*/
/* denormalized float * float */
static int denormal_mulf(int hx, int hy)
{
unsigned int ix, iy;
unsigned long long m, n;
int exp, w;
ix = hx & 0x7fffffff;
iy = hy & 0x7fffffff;
if (iy < 0x00800000 || ix == 0)
return ((hx ^ hy) & 0x80000000);
exp = (iy & 0x7f800000) >> 23;
ix &= 0x007fffff;
iy = (iy & 0x007fffff) | 0x00800000;
m = (unsigned long long)ix * iy;
n = m;
w = -1;
while (n) { n >>= 1; w++; }
/* FIXME: use guard bits */
exp += w - 126 - 46;
if (exp > 0)
ix = ((int) (m >> (w - 23)) & 0x007fffff) | (exp << 23);
else if (exp + 22 >= 0)
ix = (int) (m >> (w - 22 - exp)) & 0x007fffff;
else
ix = 0;
ix |= (hx ^ hy) & 0x80000000;
return ix;
}
/* denormalized double * double */
static void mult64(unsigned long long x, unsigned long long y,
unsigned long long *highp, unsigned long long *lowp)
{
unsigned long long sub0, sub1, sub2, sub3;
unsigned long long high, low;
sub0 = (x >> 32) * (unsigned long) (y >> 32);
sub1 = (x & 0xffffffffLL) * (unsigned long) (y >> 32);
sub2 = (x >> 32) * (unsigned long) (y & 0xffffffffLL);
sub3 = (x & 0xffffffffLL) * (unsigned long) (y & 0xffffffffLL);
low = sub3;
high = 0LL;
sub3 += (sub1 << 32);
if (low > sub3)
high++;
low = sub3;
sub3 += (sub2 << 32);
if (low > sub3)
high++;
low = sub3;
high += (sub1 >> 32) + (sub2 >> 32);
high += sub0;
*lowp = low;
*highp = high;
}
static inline long long rshift64(unsigned long long mh,
unsigned long long ml, int n)
{
if (n >= 64)
return mh >> (n - 64);
return (mh << (64 - n)) | (ml >> n);
}
static long long denormal_muld(long long hx, long long hy)
{
unsigned long long ix, iy;
unsigned long long mh, ml, nh, nl;
int exp, w;
ix = hx & 0x7fffffffffffffffLL;
iy = hy & 0x7fffffffffffffffLL;
if (iy < 0x0010000000000000LL || ix == 0)
return ((hx ^ hy) & 0x8000000000000000LL);
exp = (iy & 0x7ff0000000000000LL) >> 52;
ix &= 0x000fffffffffffffLL;
iy = (iy & 0x000fffffffffffffLL) | 0x0010000000000000LL;
mult64(ix, iy, &mh, &ml);
nh = mh;
nl = ml;
w = -1;
if (nh) {
while (nh) { nh >>= 1; w++;}
w += 64;
} else
while (nl) { nl >>= 1; w++;}
/* FIXME: use guard bits */
exp += w - 1022 - 52 * 2;
if (exp > 0)
ix = (rshift64(mh, ml, w - 52) & 0x000fffffffffffffLL)
| ((long long)exp << 52);
else if (exp + 51 >= 0)
ix = rshift64(mh, ml, w - 51 - exp) & 0x000fffffffffffffLL;
else
ix = 0;
ix |= (hx ^ hy) & 0x8000000000000000LL;
return ix;
}
/* ix - iy where iy: denormal and ix, iy >= 0 */
static int denormal_subf1(unsigned int ix, unsigned int iy)
{
int frac;
int exp;
if (ix < 0x00800000)
return ix - iy;
exp = (ix & 0x7f800000) >> 23;
if (exp - 1 > 31)
return ix;
iy >>= exp - 1;
if (iy == 0)
return ix;
frac = (ix & 0x007fffff) | 0x00800000;
frac -= iy;
while (frac < 0x00800000) {
if (--exp == 0)
return frac;
frac <<= 1;
}
return (exp << 23) | (frac & 0x007fffff);
}
/* ix + iy where iy: denormal and ix, iy >= 0 */
static int denormal_addf1(unsigned int ix, unsigned int iy)
{
int frac;
int exp;
if (ix < 0x00800000)
return ix + iy;
exp = (ix & 0x7f800000) >> 23;
if (exp - 1 > 31)
return ix;
iy >>= exp - 1;
if (iy == 0)
return ix;
frac = (ix & 0x007fffff) | 0x00800000;
frac += iy;
if (frac >= 0x01000000) {
frac >>= 1;
++exp;
}
return (exp << 23) | (frac & 0x007fffff);
}
static int denormal_addf(int hx, int hy)
{
unsigned int ix, iy;
int sign;
if ((hx ^ hy) & 0x80000000) {
sign = hx & 0x80000000;
ix = hx & 0x7fffffff;
iy = hy & 0x7fffffff;
if (iy < 0x00800000) {
ix = denormal_subf1(ix, iy);
if ((int) ix < 0) {
ix = -ix;
sign ^= 0x80000000;
}
} else {
ix = denormal_subf1(iy, ix);
sign ^= 0x80000000;
}
} else {
sign = hx & 0x80000000;
ix = hx & 0x7fffffff;
iy = hy & 0x7fffffff;
if (iy < 0x00800000)
ix = denormal_addf1(ix, iy);
else
ix = denormal_addf1(iy, ix);
}
return sign | ix;
}
/* ix - iy where iy: denormal and ix, iy >= 0 */
static long long denormal_subd1(unsigned long long ix, unsigned long long iy)
{
long long frac;
int exp;
if (ix < 0x0010000000000000LL)
return ix - iy;
exp = (ix & 0x7ff0000000000000LL) >> 52;
if (exp - 1 > 63)
return ix;
iy >>= exp - 1;
if (iy == 0)
return ix;
frac = (ix & 0x000fffffffffffffLL) | 0x0010000000000000LL;
frac -= iy;
while (frac < 0x0010000000000000LL) {
if (--exp == 0)
return frac;
frac <<= 1;
}
return ((long long)exp << 52) | (frac & 0x000fffffffffffffLL);
}
/* ix + iy where iy: denormal and ix, iy >= 0 */
static long long denormal_addd1(unsigned long long ix, unsigned long long iy)
{
long long frac;
long long exp;
if (ix < 0x0010000000000000LL)
return ix + iy;
exp = (ix & 0x7ff0000000000000LL) >> 52;
if (exp - 1 > 63)
return ix;
iy >>= exp - 1;
if (iy == 0)
return ix;
frac = (ix & 0x000fffffffffffffLL) | 0x0010000000000000LL;
frac += iy;
if (frac >= 0x0020000000000000LL) {
frac >>= 1;
++exp;
}
return (exp << 52) | (frac & 0x000fffffffffffffLL);
}
static long long denormal_addd(long long hx, long long hy)
{
unsigned long long ix, iy;
long long sign;
if ((hx ^ hy) & 0x8000000000000000LL) {
sign = hx & 0x8000000000000000LL;
ix = hx & 0x7fffffffffffffffLL;
iy = hy & 0x7fffffffffffffffLL;
if (iy < 0x0010000000000000LL) {
ix = denormal_subd1(ix, iy);
if ((int) ix < 0) {
ix = -ix;
sign ^= 0x8000000000000000LL;
}
} else {
ix = denormal_subd1(iy, ix);
sign ^= 0x8000000000000000LL;
}
} else {
sign = hx & 0x8000000000000000LL;
ix = hx & 0x7fffffffffffffffLL;
iy = hy & 0x7fffffffffffffffLL;
if (iy < 0x0010000000000000LL)
ix = denormal_addd1(ix, iy);
else
ix = denormal_addd1(iy, ix);
}
return sign | ix;
}
/**
* denormal_to_double - Given denormalized float number,
* store double float
*
* @fpu: Pointer to sh_fpu_hard structure
* @n: Index to FP register
*/
static void
denormal_to_double (struct sh_fpu_hard_struct *fpu, int n)
{
unsigned long du, dl;
unsigned long x = fpu->fpul;
int exp = 1023 - 126;
if (x != 0 && (x & 0x7f800000) == 0) {
du = (x & 0x80000000);
while ((x & 0x00800000) == 0) {
x <<= 1;
exp--;
}
x &= 0x007fffff;
du |= (exp << 20) | (x >> 3);
dl = x << 29;
fpu->fp_regs[n] = du;
fpu->fp_regs[n+1] = dl;
}
}
/**
* ieee_fpe_handler - Handle denormalized number exception
*
* @regs: Pointer to register structure
*
* Returns 1 when it's handled (should not cause exception).
*/
static int
ieee_fpe_handler (struct pt_regs *regs)
{
unsigned short insn = *(unsigned short *) regs->pc;
unsigned short finsn;
unsigned long nextpc;
int nib[4] = {
(insn >> 12) & 0xf,
(insn >> 8) & 0xf,
(insn >> 4) & 0xf,
insn & 0xf};
if (nib[0] == 0xb ||
(nib[0] == 0x4 && nib[2] == 0x0 && nib[3] == 0xb)) /* bsr & jsr */
regs->pr = regs->pc + 4;
if (nib[0] == 0xa || nib[0] == 0xb) { /* bra & bsr */
nextpc = regs->pc + 4 + ((short) ((insn & 0xfff) << 4) >> 3);
finsn = *(unsigned short *) (regs->pc + 2);
} else if (nib[0] == 0x8 && nib[1] == 0xd) { /* bt/s */
if (regs->sr & 1)
nextpc = regs->pc + 4 + ((char) (insn & 0xff) << 1);
else
nextpc = regs->pc + 4;
finsn = *(unsigned short *) (regs->pc + 2);
} else if (nib[0] == 0x8 && nib[1] == 0xf) { /* bf/s */
if (regs->sr & 1)
nextpc = regs->pc + 4;
else
nextpc = regs->pc + 4 + ((char) (insn & 0xff) << 1);
finsn = *(unsigned short *) (regs->pc + 2);
} else if (nib[0] == 0x4 && nib[3] == 0xb &&
(nib[2] == 0x0 || nib[2] == 0x2)) { /* jmp & jsr */
nextpc = regs->regs[nib[1]];
finsn = *(unsigned short *) (regs->pc + 2);
} else if (nib[0] == 0x0 && nib[3] == 0x3 &&
(nib[2] == 0x0 || nib[2] == 0x2)) { /* braf & bsrf */
nextpc = regs->pc + 4 + regs->regs[nib[1]];
finsn = *(unsigned short *) (regs->pc + 2);
} else if (insn == 0x000b) { /* rts */
nextpc = regs->pr;
finsn = *(unsigned short *) (regs->pc + 2);
} else {
nextpc = regs->pc + 2;
finsn = insn;
}
#define FPSCR_FPU_ERROR (1 << 17)
if ((finsn & 0xf1ff) == 0xf0ad) { /* fcnvsd */
struct task_struct *tsk = current;
if ((tsk->thread.xstate->hardfpu.fpscr & FPSCR_FPU_ERROR)) {
/* FPU error */
denormal_to_double (&tsk->thread.xstate->hardfpu,
(finsn >> 8) & 0xf);
} else
return 0;
regs->pc = nextpc;
return 1;
} else if ((finsn & 0xf00f) == 0xf002) { /* fmul */
struct task_struct *tsk = current;
int fpscr;
int n, m, prec;
unsigned int hx, hy;
n = (finsn >> 8) & 0xf;
m = (finsn >> 4) & 0xf;
hx = tsk->thread.xstate->hardfpu.fp_regs[n];
hy = tsk->thread.xstate->hardfpu.fp_regs[m];
fpscr = tsk->thread.xstate->hardfpu.fpscr;
prec = fpscr & (1 << 19);
if ((fpscr & FPSCR_FPU_ERROR)
&& (prec && ((hx & 0x7fffffff) < 0x00100000
|| (hy & 0x7fffffff) < 0x00100000))) {
long long llx, lly;
/* FPU error because of denormal */
llx = ((long long) hx << 32)
| tsk->thread.xstate->hardfpu.fp_regs[n+1];
lly = ((long long) hy << 32)
| tsk->thread.xstate->hardfpu.fp_regs[m+1];
if ((hx & 0x7fffffff) >= 0x00100000)
llx = denormal_muld(lly, llx);
else
llx = denormal_muld(llx, lly);
tsk->thread.xstate->hardfpu.fp_regs[n] = llx >> 32;
tsk->thread.xstate->hardfpu.fp_regs[n+1] = llx & 0xffffffff;
} else if ((fpscr & FPSCR_FPU_ERROR)
&& (!prec && ((hx & 0x7fffffff) < 0x00800000
|| (hy & 0x7fffffff) < 0x00800000))) {
/* FPU error because of denormal */
if ((hx & 0x7fffffff) >= 0x00800000)
hx = denormal_mulf(hy, hx);
else
hx = denormal_mulf(hx, hy);
tsk->thread.xstate->hardfpu.fp_regs[n] = hx;
} else
return 0;
regs->pc = nextpc;
return 1;
} else if ((finsn & 0xf00e) == 0xf000) { /* fadd, fsub */
struct task_struct *tsk = current;
int fpscr;
int n, m, prec;
unsigned int hx, hy;
n = (finsn >> 8) & 0xf;
m = (finsn >> 4) & 0xf;
hx = tsk->thread.xstate->hardfpu.fp_regs[n];
hy = tsk->thread.xstate->hardfpu.fp_regs[m];
fpscr = tsk->thread.xstate->hardfpu.fpscr;
prec = fpscr & (1 << 19);
if ((fpscr & FPSCR_FPU_ERROR)
&& (prec && ((hx & 0x7fffffff) < 0x00100000
|| (hy & 0x7fffffff) < 0x00100000))) {
long long llx, lly;
/* FPU error because of denormal */
llx = ((long long) hx << 32)
| tsk->thread.xstate->hardfpu.fp_regs[n+1];
lly = ((long long) hy << 32)
| tsk->thread.xstate->hardfpu.fp_regs[m+1];
if ((finsn & 0xf00f) == 0xf000)
llx = denormal_addd(llx, lly);
else
llx = denormal_addd(llx, lly ^ (1LL << 63));
tsk->thread.xstate->hardfpu.fp_regs[n] = llx >> 32;
tsk->thread.xstate->hardfpu.fp_regs[n+1] = llx & 0xffffffff;
} else if ((fpscr & FPSCR_FPU_ERROR)
&& (!prec && ((hx & 0x7fffffff) < 0x00800000
|| (hy & 0x7fffffff) < 0x00800000))) {
/* FPU error because of denormal */
if ((finsn & 0xf00f) == 0xf000)
hx = denormal_addf(hx, hy);
else
hx = denormal_addf(hx, hy ^ 0x80000000);
tsk->thread.xstate->hardfpu.fp_regs[n] = hx;
} else
return 0;
regs->pc = nextpc;
return 1;
}
return 0;
}
BUILD_TRAP_HANDLER(fpu_error)
{
struct task_struct *tsk = current;
TRAP_HANDLER_DECL;
__unlazy_fpu(tsk, regs);
if (ieee_fpe_handler(regs)) {
tsk->thread.xstate->hardfpu.fpscr &=
~(FPSCR_CAUSE_MASK | FPSCR_FLAG_MASK);
grab_fpu(regs);
restore_fpu(tsk);
task_thread_info(tsk)->status |= TS_USEDFPU;
return;
}
force_sig(SIGFPE, tsk);
}
| gpl-2.0 |
michaelspeed/EntityMobile_Nexus5_kernel_AOSP | drivers/mca/mca-device.c | 9981 | 6771 | /* -*- mode: c; c-basic-offset: 8 -*- */
/*
* MCA device support functions
*
* These functions support the ongoing device access API.
*
* (C) 2002 James Bottomley <James.Bottomley@HansenPartnership.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, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
**-----------------------------------------------------------------------------
*/
#include <linux/module.h>
#include <linux/device.h>
#include <linux/mca.h>
#include <linux/string.h>
/**
* mca_device_read_stored_pos - read POS register from stored data
* @mca_dev: device to read from
* @reg: register to read from
*
* Fetch a POS value that was stored at boot time by the kernel
* when it scanned the MCA space. The register value is returned.
* Missing or invalid registers report 0.
*/
unsigned char mca_device_read_stored_pos(struct mca_device *mca_dev, int reg)
{
if(reg < 0 || reg >= 8)
return 0;
return mca_dev->pos[reg];
}
EXPORT_SYMBOL(mca_device_read_stored_pos);
/**
* mca_device_read_pos - read POS register from card
* @mca_dev: device to read from
* @reg: register to read from
*
* Fetch a POS value directly from the hardware to obtain the
* current value. This is much slower than
* mca_device_read_stored_pos and may not be invoked from
* interrupt context. It handles the deep magic required for
* onboard devices transparently.
*/
unsigned char mca_device_read_pos(struct mca_device *mca_dev, int reg)
{
struct mca_bus *mca_bus = to_mca_bus(mca_dev->dev.parent);
return mca_bus->f.mca_read_pos(mca_dev, reg);
return mca_dev->pos[reg];
}
EXPORT_SYMBOL(mca_device_read_pos);
/**
* mca_device_write_pos - read POS register from card
* @mca_dev: device to write pos register to
* @reg: register to write to
* @byte: byte to write to the POS registers
*
* Store a POS value directly to the hardware. You should not
* normally need to use this function and should have a very good
* knowledge of MCA bus before you do so. Doing this wrongly can
* damage the hardware.
*
* This function may not be used from interrupt context.
*
*/
void mca_device_write_pos(struct mca_device *mca_dev, int reg,
unsigned char byte)
{
struct mca_bus *mca_bus = to_mca_bus(mca_dev->dev.parent);
mca_bus->f.mca_write_pos(mca_dev, reg, byte);
}
EXPORT_SYMBOL(mca_device_write_pos);
/**
* mca_device_transform_irq - transform the ADF obtained IRQ
* @mca_device: device whose irq needs transforming
* @irq: input irq from ADF
*
* MCA Adapter Definition Files (ADF) contain irq, ioport, memory
* etc. definitions. In systems with more than one bus, these need
* to be transformed through bus mapping functions to get the real
* system global quantities.
*
* This function transforms the interrupt number and returns the
* transformed system global interrupt
*/
int mca_device_transform_irq(struct mca_device *mca_dev, int irq)
{
struct mca_bus *mca_bus = to_mca_bus(mca_dev->dev.parent);
return mca_bus->f.mca_transform_irq(mca_dev, irq);
}
EXPORT_SYMBOL(mca_device_transform_irq);
/**
* mca_device_transform_ioport - transform the ADF obtained I/O port
* @mca_device: device whose port needs transforming
* @ioport: input I/O port from ADF
*
* MCA Adapter Definition Files (ADF) contain irq, ioport, memory
* etc. definitions. In systems with more than one bus, these need
* to be transformed through bus mapping functions to get the real
* system global quantities.
*
* This function transforms the I/O port number and returns the
* transformed system global port number.
*
* This transformation can be assumed to be linear for port ranges.
*/
int mca_device_transform_ioport(struct mca_device *mca_dev, int port)
{
struct mca_bus *mca_bus = to_mca_bus(mca_dev->dev.parent);
return mca_bus->f.mca_transform_ioport(mca_dev, port);
}
EXPORT_SYMBOL(mca_device_transform_ioport);
/**
* mca_device_transform_memory - transform the ADF obtained memory
* @mca_device: device whose memory region needs transforming
* @mem: memory region start from ADF
*
* MCA Adapter Definition Files (ADF) contain irq, ioport, memory
* etc. definitions. In systems with more than one bus, these need
* to be transformed through bus mapping functions to get the real
* system global quantities.
*
* This function transforms the memory region start and returns the
* transformed system global memory region (physical).
*
* This transformation can be assumed to be linear for region ranges.
*/
void *mca_device_transform_memory(struct mca_device *mca_dev, void *mem)
{
struct mca_bus *mca_bus = to_mca_bus(mca_dev->dev.parent);
return mca_bus->f.mca_transform_memory(mca_dev, mem);
}
EXPORT_SYMBOL(mca_device_transform_memory);
/**
* mca_device_claimed - check if claimed by driver
* @mca_dev: device to check
*
* Returns 1 if the slot has been claimed by a driver
*/
int mca_device_claimed(struct mca_device *mca_dev)
{
return mca_dev->driver_loaded;
}
EXPORT_SYMBOL(mca_device_claimed);
/**
* mca_device_set_claim - set the claim value of the driver
* @mca_dev: device to set value for
* @val: claim value to set (1 claimed, 0 unclaimed)
*/
void mca_device_set_claim(struct mca_device *mca_dev, int val)
{
mca_dev->driver_loaded = val;
}
EXPORT_SYMBOL(mca_device_set_claim);
/**
* mca_device_status - get the status of the device
* @mca_device: device to get
*
* returns an enumeration of the device status:
*
* MCA_ADAPTER_NORMAL adapter is OK.
* MCA_ADAPTER_NONE no adapter at device (should never happen).
* MCA_ADAPTER_DISABLED adapter is disabled.
* MCA_ADAPTER_ERROR adapter cannot be initialised.
*/
enum MCA_AdapterStatus mca_device_status(struct mca_device *mca_dev)
{
return mca_dev->status;
}
EXPORT_SYMBOL(mca_device_status);
/**
* mca_device_set_name - set the name of the device
* @mca_device: device to set the name of
* @name: name to set
*/
void mca_device_set_name(struct mca_device *mca_dev, const char *name)
{
if(!mca_dev)
return;
strlcpy(mca_dev->name, name, sizeof(mca_dev->name));
}
EXPORT_SYMBOL(mca_device_set_name);
| gpl-2.0 |
Shkerzy/alcatelOT990-kernel-msm7x27 | drivers/mmc/host/at91_mci.c | 254 | 31262 | /*
* linux/drivers/mmc/host/at91_mci.c - ATMEL AT91 MCI Driver
*
* Copyright (C) 2005 Cougar Creek Computing Devices Ltd, All Rights Reserved
*
* Copyright (C) 2006 Malcolm Noyes
*
* 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 is the AT91 MCI driver that has been tested with both MMC cards
and SD-cards. Boards that support write protect are now supported.
The CCAT91SBC001 board does not support SD cards.
The three entry points are at91_mci_request, at91_mci_set_ios
and at91_mci_get_ro.
SET IOS
This configures the device to put it into the correct mode and clock speed
required.
MCI REQUEST
MCI request processes the commands sent in the mmc_request structure. This
can consist of a processing command and a stop command in the case of
multiple block transfers.
There are three main types of request, commands, reads and writes.
Commands are straight forward. The command is submitted to the controller and
the request function returns. When the controller generates an interrupt to indicate
the command is finished, the response to the command are read and the mmc_request_done
function called to end the request.
Reads and writes work in a similar manner to normal commands but involve the PDC (DMA)
controller to manage the transfers.
A read is done from the controller directly to the scatterlist passed in from the request.
Due to a bug in the AT91RM9200 controller, when a read is completed, all the words are byte
swapped in the scatterlist buffers. AT91SAM926x are not affected by this bug.
The sequence of read interrupts is: ENDRX, RXBUFF, CMDRDY
A write is slightly different in that the bytes to write are read from the scatterlist
into a dma memory buffer (this is in case the source buffer should be read only). The
entire write buffer is then done from this single dma memory buffer.
The sequence of write interrupts is: ENDTX, TXBUFE, NOTBUSY, CMDRDY
GET RO
Gets the status of the write protect pin, if available.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/dma-mapping.h>
#include <linux/clk.h>
#include <linux/atmel_pdc.h>
#include <linux/gfp.h>
#include <linux/mmc/host.h>
#include <linux/mmc/sdio.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/gpio.h>
#include <mach/board.h>
#include <mach/cpu.h>
#include <mach/at91_mci.h>
#define DRIVER_NAME "at91_mci"
static inline int at91mci_is_mci1rev2xx(void)
{
return ( cpu_is_at91sam9260()
|| cpu_is_at91sam9263()
|| cpu_is_at91cap9()
|| cpu_is_at91sam9rl()
|| cpu_is_at91sam9g10()
|| cpu_is_at91sam9g20()
);
}
#define FL_SENT_COMMAND (1 << 0)
#define FL_SENT_STOP (1 << 1)
#define AT91_MCI_ERRORS (AT91_MCI_RINDE | AT91_MCI_RDIRE | AT91_MCI_RCRCE \
| AT91_MCI_RENDE | AT91_MCI_RTOE | AT91_MCI_DCRCE \
| AT91_MCI_DTOE | AT91_MCI_OVRE | AT91_MCI_UNRE)
#define at91_mci_read(host, reg) __raw_readl((host)->baseaddr + (reg))
#define at91_mci_write(host, reg, val) __raw_writel((val), (host)->baseaddr + (reg))
#define MCI_BLKSIZE 512
#define MCI_MAXBLKSIZE 4095
#define MCI_BLKATONCE 256
#define MCI_BUFSIZE (MCI_BLKSIZE * MCI_BLKATONCE)
/*
* Low level type for this driver
*/
struct at91mci_host
{
struct mmc_host *mmc;
struct mmc_command *cmd;
struct mmc_request *request;
void __iomem *baseaddr;
int irq;
struct at91_mmc_data *board;
int present;
struct clk *mci_clk;
/*
* Flag indicating when the command has been sent. This is used to
* work out whether or not to send the stop
*/
unsigned int flags;
/* flag for current bus settings */
u32 bus_mode;
/* DMA buffer used for transmitting */
unsigned int* buffer;
dma_addr_t physical_address;
unsigned int total_length;
/* Latest in the scatterlist that has been enabled for transfer, but not freed */
int in_use_index;
/* Latest in the scatterlist that has been enabled for transfer */
int transfer_index;
/* Timer for timeouts */
struct timer_list timer;
};
/*
* Reset the controller and restore most of the state
*/
static void at91_reset_host(struct at91mci_host *host)
{
unsigned long flags;
u32 mr;
u32 sdcr;
u32 dtor;
u32 imr;
local_irq_save(flags);
imr = at91_mci_read(host, AT91_MCI_IMR);
at91_mci_write(host, AT91_MCI_IDR, 0xffffffff);
/* save current state */
mr = at91_mci_read(host, AT91_MCI_MR) & 0x7fff;
sdcr = at91_mci_read(host, AT91_MCI_SDCR);
dtor = at91_mci_read(host, AT91_MCI_DTOR);
/* reset the controller */
at91_mci_write(host, AT91_MCI_CR, AT91_MCI_MCIDIS | AT91_MCI_SWRST);
/* restore state */
at91_mci_write(host, AT91_MCI_CR, AT91_MCI_MCIEN);
at91_mci_write(host, AT91_MCI_MR, mr);
at91_mci_write(host, AT91_MCI_SDCR, sdcr);
at91_mci_write(host, AT91_MCI_DTOR, dtor);
at91_mci_write(host, AT91_MCI_IER, imr);
/* make sure sdio interrupts will fire */
at91_mci_read(host, AT91_MCI_SR);
local_irq_restore(flags);
}
static void at91_timeout_timer(unsigned long data)
{
struct at91mci_host *host;
host = (struct at91mci_host *)data;
if (host->request) {
dev_err(host->mmc->parent, "Timeout waiting end of packet\n");
if (host->cmd && host->cmd->data) {
host->cmd->data->error = -ETIMEDOUT;
} else {
if (host->cmd)
host->cmd->error = -ETIMEDOUT;
else
host->request->cmd->error = -ETIMEDOUT;
}
at91_reset_host(host);
mmc_request_done(host->mmc, host->request);
}
}
/*
* Copy from sg to a dma block - used for transfers
*/
static inline void at91_mci_sg_to_dma(struct at91mci_host *host, struct mmc_data *data)
{
unsigned int len, i, size;
unsigned *dmabuf = host->buffer;
size = data->blksz * data->blocks;
len = data->sg_len;
/* MCI1 rev2xx Data Write Operation and number of bytes erratum */
if (at91mci_is_mci1rev2xx())
if (host->total_length == 12)
memset(dmabuf, 0, 12);
/*
* Just loop through all entries. Size might not
* be the entire list though so make sure that
* we do not transfer too much.
*/
for (i = 0; i < len; i++) {
struct scatterlist *sg;
int amount;
unsigned int *sgbuffer;
sg = &data->sg[i];
sgbuffer = kmap_atomic(sg_page(sg), KM_BIO_SRC_IRQ) + sg->offset;
amount = min(size, sg->length);
size -= amount;
if (cpu_is_at91rm9200()) { /* AT91RM9200 errata */
int index;
for (index = 0; index < (amount / 4); index++)
*dmabuf++ = swab32(sgbuffer[index]);
} else {
char *tmpv = (char *)dmabuf;
memcpy(tmpv, sgbuffer, amount);
tmpv += amount;
dmabuf = (unsigned *)tmpv;
}
kunmap_atomic(sgbuffer, KM_BIO_SRC_IRQ);
if (size == 0)
break;
}
/*
* Check that we didn't get a request to transfer
* more data than can fit into the SG list.
*/
BUG_ON(size != 0);
}
/*
* Handle after a dma read
*/
static void at91_mci_post_dma_read(struct at91mci_host *host)
{
struct mmc_command *cmd;
struct mmc_data *data;
unsigned int len, i, size;
unsigned *dmabuf = host->buffer;
pr_debug("post dma read\n");
cmd = host->cmd;
if (!cmd) {
pr_debug("no command\n");
return;
}
data = cmd->data;
if (!data) {
pr_debug("no data\n");
return;
}
size = data->blksz * data->blocks;
len = data->sg_len;
at91_mci_write(host, AT91_MCI_IDR, AT91_MCI_ENDRX);
at91_mci_write(host, AT91_MCI_IER, AT91_MCI_RXBUFF);
for (i = 0; i < len; i++) {
struct scatterlist *sg;
int amount;
unsigned int *sgbuffer;
sg = &data->sg[i];
sgbuffer = kmap_atomic(sg_page(sg), KM_BIO_SRC_IRQ) + sg->offset;
amount = min(size, sg->length);
size -= amount;
if (cpu_is_at91rm9200()) { /* AT91RM9200 errata */
int index;
for (index = 0; index < (amount / 4); index++)
sgbuffer[index] = swab32(*dmabuf++);
} else {
char *tmpv = (char *)dmabuf;
memcpy(sgbuffer, tmpv, amount);
tmpv += amount;
dmabuf = (unsigned *)tmpv;
}
flush_kernel_dcache_page(sg_page(sg));
kunmap_atomic(sgbuffer, KM_BIO_SRC_IRQ);
data->bytes_xfered += amount;
if (size == 0)
break;
}
pr_debug("post dma read done\n");
}
/*
* Handle transmitted data
*/
static void at91_mci_handle_transmitted(struct at91mci_host *host)
{
struct mmc_command *cmd;
struct mmc_data *data;
pr_debug("Handling the transmit\n");
/* Disable the transfer */
at91_mci_write(host, ATMEL_PDC_PTCR, ATMEL_PDC_RXTDIS | ATMEL_PDC_TXTDIS);
/* Now wait for cmd ready */
at91_mci_write(host, AT91_MCI_IDR, AT91_MCI_TXBUFE);
cmd = host->cmd;
if (!cmd) return;
data = cmd->data;
if (!data) return;
if (cmd->data->blocks > 1) {
pr_debug("multiple write : wait for BLKE...\n");
at91_mci_write(host, AT91_MCI_IER, AT91_MCI_BLKE);
} else
at91_mci_write(host, AT91_MCI_IER, AT91_MCI_NOTBUSY);
}
/*
* Update bytes tranfered count during a write operation
*/
static void at91_mci_update_bytes_xfered(struct at91mci_host *host)
{
struct mmc_data *data;
/* always deal with the effective request (and not the current cmd) */
if (host->request->cmd && host->request->cmd->error != 0)
return;
if (host->request->data) {
data = host->request->data;
if (data->flags & MMC_DATA_WRITE) {
/* card is in IDLE mode now */
pr_debug("-> bytes_xfered %d, total_length = %d\n",
data->bytes_xfered, host->total_length);
data->bytes_xfered = data->blksz * data->blocks;
}
}
}
/*Handle after command sent ready*/
static int at91_mci_handle_cmdrdy(struct at91mci_host *host)
{
if (!host->cmd)
return 1;
else if (!host->cmd->data) {
if (host->flags & FL_SENT_STOP) {
/*After multi block write, we must wait for NOTBUSY*/
at91_mci_write(host, AT91_MCI_IER, AT91_MCI_NOTBUSY);
} else return 1;
} else if (host->cmd->data->flags & MMC_DATA_WRITE) {
/*After sendding multi-block-write command, start DMA transfer*/
at91_mci_write(host, AT91_MCI_IER, AT91_MCI_TXBUFE | AT91_MCI_BLKE);
at91_mci_write(host, ATMEL_PDC_PTCR, ATMEL_PDC_TXTEN);
}
/* command not completed, have to wait */
return 0;
}
/*
* Enable the controller
*/
static void at91_mci_enable(struct at91mci_host *host)
{
unsigned int mr;
at91_mci_write(host, AT91_MCI_CR, AT91_MCI_MCIEN);
at91_mci_write(host, AT91_MCI_IDR, 0xffffffff);
at91_mci_write(host, AT91_MCI_DTOR, AT91_MCI_DTOMUL_1M | AT91_MCI_DTOCYC);
mr = AT91_MCI_PDCMODE | 0x34a;
if (at91mci_is_mci1rev2xx())
mr |= AT91_MCI_RDPROOF | AT91_MCI_WRPROOF;
at91_mci_write(host, AT91_MCI_MR, mr);
/* use Slot A or B (only one at same time) */
at91_mci_write(host, AT91_MCI_SDCR, host->board->slot_b);
}
/*
* Disable the controller
*/
static void at91_mci_disable(struct at91mci_host *host)
{
at91_mci_write(host, AT91_MCI_CR, AT91_MCI_MCIDIS | AT91_MCI_SWRST);
}
/*
* Send a command
*/
static void at91_mci_send_command(struct at91mci_host *host, struct mmc_command *cmd)
{
unsigned int cmdr, mr;
unsigned int block_length;
struct mmc_data *data = cmd->data;
unsigned int blocks;
unsigned int ier = 0;
host->cmd = cmd;
/* Needed for leaving busy state before CMD1 */
if ((at91_mci_read(host, AT91_MCI_SR) & AT91_MCI_RTOE) && (cmd->opcode == 1)) {
pr_debug("Clearing timeout\n");
at91_mci_write(host, AT91_MCI_ARGR, 0);
at91_mci_write(host, AT91_MCI_CMDR, AT91_MCI_OPDCMD);
while (!(at91_mci_read(host, AT91_MCI_SR) & AT91_MCI_CMDRDY)) {
/* spin */
pr_debug("Clearing: SR = %08X\n", at91_mci_read(host, AT91_MCI_SR));
}
}
cmdr = cmd->opcode;
if (mmc_resp_type(cmd) == MMC_RSP_NONE)
cmdr |= AT91_MCI_RSPTYP_NONE;
else {
/* if a response is expected then allow maximum response latancy */
cmdr |= AT91_MCI_MAXLAT;
/* set 136 bit response for R2, 48 bit response otherwise */
if (mmc_resp_type(cmd) == MMC_RSP_R2)
cmdr |= AT91_MCI_RSPTYP_136;
else
cmdr |= AT91_MCI_RSPTYP_48;
}
if (data) {
if (cpu_is_at91rm9200() || cpu_is_at91sam9261()) {
if (data->blksz & 0x3) {
pr_debug("Unsupported block size\n");
cmd->error = -EINVAL;
mmc_request_done(host->mmc, host->request);
return;
}
if (data->flags & MMC_DATA_STREAM) {
pr_debug("Stream commands not supported\n");
cmd->error = -EINVAL;
mmc_request_done(host->mmc, host->request);
return;
}
}
block_length = data->blksz;
blocks = data->blocks;
/* always set data start - also set direction flag for read */
if (data->flags & MMC_DATA_READ)
cmdr |= (AT91_MCI_TRDIR | AT91_MCI_TRCMD_START);
else if (data->flags & MMC_DATA_WRITE)
cmdr |= AT91_MCI_TRCMD_START;
if (cmd->opcode == SD_IO_RW_EXTENDED) {
cmdr |= AT91_MCI_TRTYP_SDIO_BLOCK;
} else {
if (data->flags & MMC_DATA_STREAM)
cmdr |= AT91_MCI_TRTYP_STREAM;
if (data->blocks > 1)
cmdr |= AT91_MCI_TRTYP_MULTIPLE;
}
}
else {
block_length = 0;
blocks = 0;
}
if (host->flags & FL_SENT_STOP)
cmdr |= AT91_MCI_TRCMD_STOP;
if (host->bus_mode == MMC_BUSMODE_OPENDRAIN)
cmdr |= AT91_MCI_OPDCMD;
/*
* Set the arguments and send the command
*/
pr_debug("Sending command %d as %08X, arg = %08X, blocks = %d, length = %d (MR = %08X)\n",
cmd->opcode, cmdr, cmd->arg, blocks, block_length, at91_mci_read(host, AT91_MCI_MR));
if (!data) {
at91_mci_write(host, ATMEL_PDC_PTCR, ATMEL_PDC_TXTDIS | ATMEL_PDC_RXTDIS);
at91_mci_write(host, ATMEL_PDC_RPR, 0);
at91_mci_write(host, ATMEL_PDC_RCR, 0);
at91_mci_write(host, ATMEL_PDC_RNPR, 0);
at91_mci_write(host, ATMEL_PDC_RNCR, 0);
at91_mci_write(host, ATMEL_PDC_TPR, 0);
at91_mci_write(host, ATMEL_PDC_TCR, 0);
at91_mci_write(host, ATMEL_PDC_TNPR, 0);
at91_mci_write(host, ATMEL_PDC_TNCR, 0);
ier = AT91_MCI_CMDRDY;
} else {
/* zero block length and PDC mode */
mr = at91_mci_read(host, AT91_MCI_MR) & 0x5fff;
mr |= (data->blksz & 0x3) ? AT91_MCI_PDCFBYTE : 0;
mr |= (block_length << 16);
mr |= AT91_MCI_PDCMODE;
at91_mci_write(host, AT91_MCI_MR, mr);
if (!(cpu_is_at91rm9200() || cpu_is_at91sam9261()))
at91_mci_write(host, AT91_MCI_BLKR,
AT91_MCI_BLKR_BCNT(blocks) |
AT91_MCI_BLKR_BLKLEN(block_length));
/*
* Disable the PDC controller
*/
at91_mci_write(host, ATMEL_PDC_PTCR, ATMEL_PDC_RXTDIS | ATMEL_PDC_TXTDIS);
if (cmdr & AT91_MCI_TRCMD_START) {
data->bytes_xfered = 0;
host->transfer_index = 0;
host->in_use_index = 0;
if (cmdr & AT91_MCI_TRDIR) {
/*
* Handle a read
*/
host->total_length = 0;
at91_mci_write(host, ATMEL_PDC_RPR, host->physical_address);
at91_mci_write(host, ATMEL_PDC_RCR, (data->blksz & 0x3) ?
(blocks * block_length) : (blocks * block_length) / 4);
at91_mci_write(host, ATMEL_PDC_RNPR, 0);
at91_mci_write(host, ATMEL_PDC_RNCR, 0);
ier = AT91_MCI_ENDRX /* | AT91_MCI_RXBUFF */;
}
else {
/*
* Handle a write
*/
host->total_length = block_length * blocks;
/*
* MCI1 rev2xx Data Write Operation and
* number of bytes erratum
*/
if (at91mci_is_mci1rev2xx())
if (host->total_length < 12)
host->total_length = 12;
at91_mci_sg_to_dma(host, data);
pr_debug("Transmitting %d bytes\n", host->total_length);
at91_mci_write(host, ATMEL_PDC_TPR, host->physical_address);
at91_mci_write(host, ATMEL_PDC_TCR, (data->blksz & 0x3) ?
host->total_length : host->total_length / 4);
ier = AT91_MCI_CMDRDY;
}
}
}
/*
* Send the command and then enable the PDC - not the other way round as
* the data sheet says
*/
at91_mci_write(host, AT91_MCI_ARGR, cmd->arg);
at91_mci_write(host, AT91_MCI_CMDR, cmdr);
if (cmdr & AT91_MCI_TRCMD_START) {
if (cmdr & AT91_MCI_TRDIR)
at91_mci_write(host, ATMEL_PDC_PTCR, ATMEL_PDC_RXTEN);
}
/* Enable selected interrupts */
at91_mci_write(host, AT91_MCI_IER, AT91_MCI_ERRORS | ier);
}
/*
* Process the next step in the request
*/
static void at91_mci_process_next(struct at91mci_host *host)
{
if (!(host->flags & FL_SENT_COMMAND)) {
host->flags |= FL_SENT_COMMAND;
at91_mci_send_command(host, host->request->cmd);
}
else if ((!(host->flags & FL_SENT_STOP)) && host->request->stop) {
host->flags |= FL_SENT_STOP;
at91_mci_send_command(host, host->request->stop);
} else {
del_timer(&host->timer);
/* the at91rm9200 mci controller hangs after some transfers,
* and the workaround is to reset it after each transfer.
*/
if (cpu_is_at91rm9200())
at91_reset_host(host);
mmc_request_done(host->mmc, host->request);
}
}
/*
* Handle a command that has been completed
*/
static void at91_mci_completed_command(struct at91mci_host *host, unsigned int status)
{
struct mmc_command *cmd = host->cmd;
struct mmc_data *data = cmd->data;
at91_mci_write(host, AT91_MCI_IDR, 0xffffffff & ~(AT91_MCI_SDIOIRQA | AT91_MCI_SDIOIRQB));
cmd->resp[0] = at91_mci_read(host, AT91_MCI_RSPR(0));
cmd->resp[1] = at91_mci_read(host, AT91_MCI_RSPR(1));
cmd->resp[2] = at91_mci_read(host, AT91_MCI_RSPR(2));
cmd->resp[3] = at91_mci_read(host, AT91_MCI_RSPR(3));
pr_debug("Status = %08X/%08x [%08X %08X %08X %08X]\n",
status, at91_mci_read(host, AT91_MCI_SR),
cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]);
if (status & AT91_MCI_ERRORS) {
if ((status & AT91_MCI_RCRCE) && !(mmc_resp_type(cmd) & MMC_RSP_CRC)) {
cmd->error = 0;
}
else {
if (status & (AT91_MCI_DTOE | AT91_MCI_DCRCE)) {
if (data) {
if (status & AT91_MCI_DTOE)
data->error = -ETIMEDOUT;
else if (status & AT91_MCI_DCRCE)
data->error = -EILSEQ;
}
} else {
if (status & AT91_MCI_RTOE)
cmd->error = -ETIMEDOUT;
else if (status & AT91_MCI_RCRCE)
cmd->error = -EILSEQ;
else
cmd->error = -EIO;
}
pr_debug("Error detected and set to %d/%d (cmd = %d, retries = %d)\n",
cmd->error, data ? data->error : 0,
cmd->opcode, cmd->retries);
}
}
else
cmd->error = 0;
at91_mci_process_next(host);
}
/*
* Handle an MMC request
*/
static void at91_mci_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct at91mci_host *host = mmc_priv(mmc);
host->request = mrq;
host->flags = 0;
/* more than 1s timeout needed with slow SD cards */
mod_timer(&host->timer, jiffies + msecs_to_jiffies(2000));
at91_mci_process_next(host);
}
/*
* Set the IOS
*/
static void at91_mci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
int clkdiv;
struct at91mci_host *host = mmc_priv(mmc);
unsigned long at91_master_clock = clk_get_rate(host->mci_clk);
host->bus_mode = ios->bus_mode;
if (ios->clock == 0) {
/* Disable the MCI controller */
at91_mci_write(host, AT91_MCI_CR, AT91_MCI_MCIDIS);
clkdiv = 0;
}
else {
/* Enable the MCI controller */
at91_mci_write(host, AT91_MCI_CR, AT91_MCI_MCIEN);
if ((at91_master_clock % (ios->clock * 2)) == 0)
clkdiv = ((at91_master_clock / ios->clock) / 2) - 1;
else
clkdiv = (at91_master_clock / ios->clock) / 2;
pr_debug("clkdiv = %d. mcck = %ld\n", clkdiv,
at91_master_clock / (2 * (clkdiv + 1)));
}
if (ios->bus_width == MMC_BUS_WIDTH_4 && host->board->wire4) {
pr_debug("MMC: Setting controller bus width to 4\n");
at91_mci_write(host, AT91_MCI_SDCR, at91_mci_read(host, AT91_MCI_SDCR) | AT91_MCI_SDCBUS);
}
else {
pr_debug("MMC: Setting controller bus width to 1\n");
at91_mci_write(host, AT91_MCI_SDCR, at91_mci_read(host, AT91_MCI_SDCR) & ~AT91_MCI_SDCBUS);
}
/* Set the clock divider */
at91_mci_write(host, AT91_MCI_MR, (at91_mci_read(host, AT91_MCI_MR) & ~AT91_MCI_CLKDIV) | clkdiv);
/* maybe switch power to the card */
if (host->board->vcc_pin) {
switch (ios->power_mode) {
case MMC_POWER_OFF:
gpio_set_value(host->board->vcc_pin, 0);
break;
case MMC_POWER_UP:
gpio_set_value(host->board->vcc_pin, 1);
break;
case MMC_POWER_ON:
break;
default:
WARN_ON(1);
}
}
}
/*
* Handle an interrupt
*/
static irqreturn_t at91_mci_irq(int irq, void *devid)
{
struct at91mci_host *host = devid;
int completed = 0;
unsigned int int_status, int_mask;
int_status = at91_mci_read(host, AT91_MCI_SR);
int_mask = at91_mci_read(host, AT91_MCI_IMR);
pr_debug("MCI irq: status = %08X, %08X, %08X\n", int_status, int_mask,
int_status & int_mask);
int_status = int_status & int_mask;
if (int_status & AT91_MCI_ERRORS) {
completed = 1;
if (int_status & AT91_MCI_UNRE)
pr_debug("MMC: Underrun error\n");
if (int_status & AT91_MCI_OVRE)
pr_debug("MMC: Overrun error\n");
if (int_status & AT91_MCI_DTOE)
pr_debug("MMC: Data timeout\n");
if (int_status & AT91_MCI_DCRCE)
pr_debug("MMC: CRC error in data\n");
if (int_status & AT91_MCI_RTOE)
pr_debug("MMC: Response timeout\n");
if (int_status & AT91_MCI_RENDE)
pr_debug("MMC: Response end bit error\n");
if (int_status & AT91_MCI_RCRCE)
pr_debug("MMC: Response CRC error\n");
if (int_status & AT91_MCI_RDIRE)
pr_debug("MMC: Response direction error\n");
if (int_status & AT91_MCI_RINDE)
pr_debug("MMC: Response index error\n");
} else {
/* Only continue processing if no errors */
if (int_status & AT91_MCI_TXBUFE) {
pr_debug("TX buffer empty\n");
at91_mci_handle_transmitted(host);
}
if (int_status & AT91_MCI_ENDRX) {
pr_debug("ENDRX\n");
at91_mci_post_dma_read(host);
}
if (int_status & AT91_MCI_RXBUFF) {
pr_debug("RX buffer full\n");
at91_mci_write(host, ATMEL_PDC_PTCR, ATMEL_PDC_RXTDIS | ATMEL_PDC_TXTDIS);
at91_mci_write(host, AT91_MCI_IDR, AT91_MCI_RXBUFF | AT91_MCI_ENDRX);
completed = 1;
}
if (int_status & AT91_MCI_ENDTX)
pr_debug("Transmit has ended\n");
if (int_status & AT91_MCI_NOTBUSY) {
pr_debug("Card is ready\n");
at91_mci_update_bytes_xfered(host);
completed = 1;
}
if (int_status & AT91_MCI_DTIP)
pr_debug("Data transfer in progress\n");
if (int_status & AT91_MCI_BLKE) {
pr_debug("Block transfer has ended\n");
if (host->request->data && host->request->data->blocks > 1) {
/* multi block write : complete multi write
* command and send stop */
completed = 1;
} else {
at91_mci_write(host, AT91_MCI_IER, AT91_MCI_NOTBUSY);
}
}
if (int_status & AT91_MCI_SDIOIRQA)
mmc_signal_sdio_irq(host->mmc);
if (int_status & AT91_MCI_SDIOIRQB)
mmc_signal_sdio_irq(host->mmc);
if (int_status & AT91_MCI_TXRDY)
pr_debug("Ready to transmit\n");
if (int_status & AT91_MCI_RXRDY)
pr_debug("Ready to receive\n");
if (int_status & AT91_MCI_CMDRDY) {
pr_debug("Command ready\n");
completed = at91_mci_handle_cmdrdy(host);
}
}
if (completed) {
pr_debug("Completed command\n");
at91_mci_write(host, AT91_MCI_IDR, 0xffffffff & ~(AT91_MCI_SDIOIRQA | AT91_MCI_SDIOIRQB));
at91_mci_completed_command(host, int_status);
} else
at91_mci_write(host, AT91_MCI_IDR, int_status & ~(AT91_MCI_SDIOIRQA | AT91_MCI_SDIOIRQB));
return IRQ_HANDLED;
}
static irqreturn_t at91_mmc_det_irq(int irq, void *_host)
{
struct at91mci_host *host = _host;
int present = !gpio_get_value(irq_to_gpio(irq));
/*
* we expect this irq on both insert and remove,
* and use a short delay to debounce.
*/
if (present != host->present) {
host->present = present;
pr_debug("%s: card %s\n", mmc_hostname(host->mmc),
present ? "insert" : "remove");
if (!present) {
pr_debug("****** Resetting SD-card bus width ******\n");
at91_mci_write(host, AT91_MCI_SDCR, at91_mci_read(host, AT91_MCI_SDCR) & ~AT91_MCI_SDCBUS);
}
/* 0.5s needed because of early card detect switch firing */
mmc_detect_change(host->mmc, msecs_to_jiffies(500));
}
return IRQ_HANDLED;
}
static int at91_mci_get_ro(struct mmc_host *mmc)
{
struct at91mci_host *host = mmc_priv(mmc);
if (host->board->wp_pin)
return !!gpio_get_value(host->board->wp_pin);
/*
* Board doesn't support read only detection; let the mmc core
* decide what to do.
*/
return -ENOSYS;
}
static void at91_mci_enable_sdio_irq(struct mmc_host *mmc, int enable)
{
struct at91mci_host *host = mmc_priv(mmc);
pr_debug("%s: sdio_irq %c : %s\n", mmc_hostname(host->mmc),
host->board->slot_b ? 'B':'A', enable ? "enable" : "disable");
at91_mci_write(host, enable ? AT91_MCI_IER : AT91_MCI_IDR,
host->board->slot_b ? AT91_MCI_SDIOIRQB : AT91_MCI_SDIOIRQA);
}
static const struct mmc_host_ops at91_mci_ops = {
.request = at91_mci_request,
.set_ios = at91_mci_set_ios,
.get_ro = at91_mci_get_ro,
.enable_sdio_irq = at91_mci_enable_sdio_irq,
};
/*
* Probe for the device
*/
static int __init at91_mci_probe(struct platform_device *pdev)
{
struct mmc_host *mmc;
struct at91mci_host *host;
struct resource *res;
int ret;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENXIO;
if (!request_mem_region(res->start, res->end - res->start + 1, DRIVER_NAME))
return -EBUSY;
mmc = mmc_alloc_host(sizeof(struct at91mci_host), &pdev->dev);
if (!mmc) {
ret = -ENOMEM;
dev_dbg(&pdev->dev, "couldn't allocate mmc host\n");
goto fail6;
}
mmc->ops = &at91_mci_ops;
mmc->f_min = 375000;
mmc->f_max = 25000000;
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
mmc->caps = 0;
mmc->max_blk_size = MCI_MAXBLKSIZE;
mmc->max_blk_count = MCI_BLKATONCE;
mmc->max_req_size = MCI_BUFSIZE;
mmc->max_phys_segs = MCI_BLKATONCE;
mmc->max_hw_segs = MCI_BLKATONCE;
mmc->max_seg_size = MCI_BUFSIZE;
host = mmc_priv(mmc);
host->mmc = mmc;
host->bus_mode = 0;
host->board = pdev->dev.platform_data;
if (host->board->wire4) {
if (at91mci_is_mci1rev2xx())
mmc->caps |= MMC_CAP_4_BIT_DATA;
else
dev_warn(&pdev->dev, "4 wire bus mode not supported"
" - using 1 wire\n");
}
host->buffer = dma_alloc_coherent(&pdev->dev, MCI_BUFSIZE,
&host->physical_address, GFP_KERNEL);
if (!host->buffer) {
ret = -ENOMEM;
dev_err(&pdev->dev, "Can't allocate transmit buffer\n");
goto fail5;
}
/* Add SDIO capability when available */
if (at91mci_is_mci1rev2xx()) {
/* at91mci MCI1 rev2xx sdio interrupt erratum */
if (host->board->wire4 || !host->board->slot_b)
mmc->caps |= MMC_CAP_SDIO_IRQ;
}
/*
* Reserve GPIOs ... board init code makes sure these pins are set
* up as GPIOs with the right direction (input, except for vcc)
*/
if (host->board->det_pin) {
ret = gpio_request(host->board->det_pin, "mmc_detect");
if (ret < 0) {
dev_dbg(&pdev->dev, "couldn't claim card detect pin\n");
goto fail4b;
}
}
if (host->board->wp_pin) {
ret = gpio_request(host->board->wp_pin, "mmc_wp");
if (ret < 0) {
dev_dbg(&pdev->dev, "couldn't claim wp sense pin\n");
goto fail4;
}
}
if (host->board->vcc_pin) {
ret = gpio_request(host->board->vcc_pin, "mmc_vcc");
if (ret < 0) {
dev_dbg(&pdev->dev, "couldn't claim vcc switch pin\n");
goto fail3;
}
}
/*
* Get Clock
*/
host->mci_clk = clk_get(&pdev->dev, "mci_clk");
if (IS_ERR(host->mci_clk)) {
ret = -ENODEV;
dev_dbg(&pdev->dev, "no mci_clk?\n");
goto fail2;
}
/*
* Map I/O region
*/
host->baseaddr = ioremap(res->start, res->end - res->start + 1);
if (!host->baseaddr) {
ret = -ENOMEM;
goto fail1;
}
/*
* Reset hardware
*/
clk_enable(host->mci_clk); /* Enable the peripheral clock */
at91_mci_disable(host);
at91_mci_enable(host);
/*
* Allocate the MCI interrupt
*/
host->irq = platform_get_irq(pdev, 0);
ret = request_irq(host->irq, at91_mci_irq, IRQF_SHARED,
mmc_hostname(mmc), host);
if (ret) {
dev_dbg(&pdev->dev, "request MCI interrupt failed\n");
goto fail0;
}
setup_timer(&host->timer, at91_timeout_timer, (unsigned long)host);
platform_set_drvdata(pdev, mmc);
/*
* Add host to MMC layer
*/
if (host->board->det_pin) {
host->present = !gpio_get_value(host->board->det_pin);
}
else
host->present = -1;
mmc_add_host(mmc);
/*
* monitor card insertion/removal if we can
*/
if (host->board->det_pin) {
ret = request_irq(gpio_to_irq(host->board->det_pin),
at91_mmc_det_irq, 0, mmc_hostname(mmc), host);
if (ret)
dev_warn(&pdev->dev, "request MMC detect irq failed\n");
else
device_init_wakeup(&pdev->dev, 1);
}
pr_debug("Added MCI driver\n");
return 0;
fail0:
clk_disable(host->mci_clk);
iounmap(host->baseaddr);
fail1:
clk_put(host->mci_clk);
fail2:
if (host->board->vcc_pin)
gpio_free(host->board->vcc_pin);
fail3:
if (host->board->wp_pin)
gpio_free(host->board->wp_pin);
fail4:
if (host->board->det_pin)
gpio_free(host->board->det_pin);
fail4b:
if (host->buffer)
dma_free_coherent(&pdev->dev, MCI_BUFSIZE,
host->buffer, host->physical_address);
fail5:
mmc_free_host(mmc);
fail6:
release_mem_region(res->start, res->end - res->start + 1);
dev_err(&pdev->dev, "probe failed, err %d\n", ret);
return ret;
}
/*
* Remove a device
*/
static int __exit at91_mci_remove(struct platform_device *pdev)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
struct at91mci_host *host;
struct resource *res;
if (!mmc)
return -1;
host = mmc_priv(mmc);
if (host->buffer)
dma_free_coherent(&pdev->dev, MCI_BUFSIZE,
host->buffer, host->physical_address);
if (host->board->det_pin) {
if (device_can_wakeup(&pdev->dev))
free_irq(gpio_to_irq(host->board->det_pin), host);
device_init_wakeup(&pdev->dev, 0);
gpio_free(host->board->det_pin);
}
at91_mci_disable(host);
del_timer_sync(&host->timer);
mmc_remove_host(mmc);
free_irq(host->irq, host);
clk_disable(host->mci_clk); /* Disable the peripheral clock */
clk_put(host->mci_clk);
if (host->board->vcc_pin)
gpio_free(host->board->vcc_pin);
if (host->board->wp_pin)
gpio_free(host->board->wp_pin);
iounmap(host->baseaddr);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, res->end - res->start + 1);
mmc_free_host(mmc);
platform_set_drvdata(pdev, NULL);
pr_debug("MCI Removed\n");
return 0;
}
#ifdef CONFIG_PM
static int at91_mci_suspend(struct platform_device *pdev, pm_message_t state)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
struct at91mci_host *host = mmc_priv(mmc);
int ret = 0;
if (host->board->det_pin && device_may_wakeup(&pdev->dev))
enable_irq_wake(host->board->det_pin);
if (mmc)
ret = mmc_suspend_host(mmc);
return ret;
}
static int at91_mci_resume(struct platform_device *pdev)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
struct at91mci_host *host = mmc_priv(mmc);
int ret = 0;
if (host->board->det_pin && device_may_wakeup(&pdev->dev))
disable_irq_wake(host->board->det_pin);
if (mmc)
ret = mmc_resume_host(mmc);
return ret;
}
#else
#define at91_mci_suspend NULL
#define at91_mci_resume NULL
#endif
static struct platform_driver at91_mci_driver = {
.remove = __exit_p(at91_mci_remove),
.suspend = at91_mci_suspend,
.resume = at91_mci_resume,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
static int __init at91_mci_init(void)
{
return platform_driver_probe(&at91_mci_driver, at91_mci_probe);
}
static void __exit at91_mci_exit(void)
{
platform_driver_unregister(&at91_mci_driver);
}
module_init(at91_mci_init);
module_exit(at91_mci_exit);
MODULE_DESCRIPTION("AT91 Multimedia Card Interface driver");
MODULE_AUTHOR("Nick Randell");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:at91_mci");
| gpl-2.0 |
romracer/atrix-kernel | drivers/staging/vt6656/rxtx.c | 510 | 128870 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* File: rxtx.c
*
* Purpose: handle WMAC/802.3/802.11 rx & tx functions
*
* Author: Lyndon Chen
*
* Date: May 20, 2003
*
* Functions:
* s_vGenerateTxParameter - Generate tx dma requried parameter.
* s_vGenerateMACHeader - Translate 802.3 to 802.11 header
* csBeacon_xmit - beacon tx function
* csMgmt_xmit - management tx function
* s_uGetDataDuration - get tx data required duration
* s_uFillDataHead- fulfill tx data duration header
* s_uGetRTSCTSDuration- get rtx/cts requried duration
* s_uGetRTSCTSRsvTime- get rts/cts reserved time
* s_uGetTxRsvTime- get frame reserved time
* s_vFillCTSHead- fulfill CTS ctl header
* s_vFillFragParameter- Set fragement ctl parameter.
* s_vFillRTSHead- fulfill RTS ctl header
* s_vFillTxKey- fulfill tx encrypt key
* s_vSWencryption- Software encrypt header
* vDMA0_tx_80211- tx 802.11 frame via dma0
* vGenerateFIFOHeader- Generate tx FIFO ctl header
*
* Revision History:
*
*/
#include "device.h"
#include "rxtx.h"
#include "tether.h"
#include "card.h"
#include "bssdb.h"
#include "mac.h"
#include "baseband.h"
#include "michael.h"
#include "tkip.h"
#include "tcrc.h"
#include "wctl.h"
#include "hostap.h"
#include "rf.h"
#include "datarate.h"
#include "usbpipe.h"
#ifdef WPA_SM_Transtatus
#include "iocmd.h"
#endif
/*--------------------- Static Definitions -------------------------*/
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
//static int msglevel =MSG_LEVEL_DEBUG;
static int msglevel =MSG_LEVEL_INFO;
/*--------------------- Static Functions --------------------------*/
/*--------------------- Static Definitions -------------------------*/
#define CRITICAL_PACKET_LEN 256 // if packet size < 256 -> in-direct send
// packet size >= 256 -> direct send
const WORD wTimeStampOff[2][MAX_RATE] = {
{384, 288, 226, 209, 54, 43, 37, 31, 28, 25, 24, 23}, // Long Preamble
{384, 192, 130, 113, 54, 43, 37, 31, 28, 25, 24, 23}, // Short Preamble
};
const WORD wFB_Opt0[2][5] = {
{RATE_12M, RATE_18M, RATE_24M, RATE_36M, RATE_48M}, // fallback_rate0
{RATE_12M, RATE_12M, RATE_18M, RATE_24M, RATE_36M}, // fallback_rate1
};
const WORD wFB_Opt1[2][5] = {
{RATE_12M, RATE_18M, RATE_24M, RATE_24M, RATE_36M}, // fallback_rate0
{RATE_6M , RATE_6M, RATE_12M, RATE_12M, RATE_18M}, // fallback_rate1
};
#define RTSDUR_BB 0
#define RTSDUR_BA 1
#define RTSDUR_AA 2
#define CTSDUR_BA 3
#define RTSDUR_BA_F0 4
#define RTSDUR_AA_F0 5
#define RTSDUR_BA_F1 6
#define RTSDUR_AA_F1 7
#define CTSDUR_BA_F0 8
#define CTSDUR_BA_F1 9
#define DATADUR_B 10
#define DATADUR_A 11
#define DATADUR_A_F0 12
#define DATADUR_A_F1 13
/*--------------------- Static Functions --------------------------*/
static
VOID
s_vSaveTxPktInfo(
IN PSDevice pDevice,
IN BYTE byPktNum,
IN PBYTE pbyDestAddr,
IN WORD wPktLength,
IN WORD wFIFOCtl
);
static
PVOID
s_vGetFreeContext(
PSDevice pDevice
);
static
VOID
s_vGenerateTxParameter(
IN PSDevice pDevice,
IN BYTE byPktType,
IN WORD wCurrentRate,
IN PVOID pTxBufHead,
IN PVOID pvRrvTime,
IN PVOID pvRTS,
IN PVOID pvCTS,
IN UINT cbFrameSize,
IN BOOL bNeedACK,
IN UINT uDMAIdx,
IN PSEthernetHeader psEthHeader
);
static
UINT
s_uFillDataHead (
IN PSDevice pDevice,
IN BYTE byPktType,
IN WORD wCurrentRate,
IN PVOID pTxDataHead,
IN UINT cbFrameLength,
IN UINT uDMAIdx,
IN BOOL bNeedAck,
IN UINT uFragIdx,
IN UINT cbLastFragmentSize,
IN UINT uMACfragNum,
IN BYTE byFBOption
);
static
VOID
s_vGenerateMACHeader (
IN PSDevice pDevice,
IN PBYTE pbyBufferAddr,
IN WORD wDuration,
IN PSEthernetHeader psEthHeader,
IN BOOL bNeedEncrypt,
IN WORD wFragType,
IN UINT uDMAIdx,
IN UINT uFragIdx
);
static
VOID
s_vFillTxKey(
IN PSDevice pDevice,
IN PBYTE pbyBuf,
IN PBYTE pbyIVHead,
IN PSKeyItem pTransmitKey,
IN PBYTE pbyHdrBuf,
IN WORD wPayloadLen,
OUT PBYTE pMICHDR
);
static
VOID
s_vSWencryption (
IN PSDevice pDevice,
IN PSKeyItem pTransmitKey,
IN PBYTE pbyPayloadHead,
IN WORD wPayloadSize
);
static
UINT
s_uGetTxRsvTime (
IN PSDevice pDevice,
IN BYTE byPktType,
IN UINT cbFrameLength,
IN WORD wRate,
IN BOOL bNeedAck
);
static
UINT
s_uGetRTSCTSRsvTime (
IN PSDevice pDevice,
IN BYTE byRTSRsvType,
IN BYTE byPktType,
IN UINT cbFrameLength,
IN WORD wCurrentRate
);
static
VOID
s_vFillCTSHead (
IN PSDevice pDevice,
IN UINT uDMAIdx,
IN BYTE byPktType,
IN PVOID pvCTS,
IN UINT cbFrameLength,
IN BOOL bNeedAck,
IN BOOL bDisCRC,
IN WORD wCurrentRate,
IN BYTE byFBOption
);
static
VOID
s_vFillRTSHead(
IN PSDevice pDevice,
IN BYTE byPktType,
IN PVOID pvRTS,
IN UINT cbFrameLength,
IN BOOL bNeedAck,
IN BOOL bDisCRC,
IN PSEthernetHeader psEthHeader,
IN WORD wCurrentRate,
IN BYTE byFBOption
);
static
UINT
s_uGetDataDuration (
IN PSDevice pDevice,
IN BYTE byDurType,
IN UINT cbFrameLength,
IN BYTE byPktType,
IN WORD wRate,
IN BOOL bNeedAck,
IN UINT uFragIdx,
IN UINT cbLastFragmentSize,
IN UINT uMACfragNum,
IN BYTE byFBOption
);
static
UINT
s_uGetRTSCTSDuration (
IN PSDevice pDevice,
IN BYTE byDurType,
IN UINT cbFrameLength,
IN BYTE byPktType,
IN WORD wRate,
IN BOOL bNeedAck,
IN BYTE byFBOption
);
/*--------------------- Export Variables --------------------------*/
static
PVOID
s_vGetFreeContext(
PSDevice pDevice
)
{
PUSB_SEND_CONTEXT pContext = NULL;
PUSB_SEND_CONTEXT pReturnContext = NULL;
UINT ii;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"GetFreeContext()\n");
for (ii = 0; ii < pDevice->cbTD; ii++) {
pContext = pDevice->apTD[ii];
if (pContext->bBoolInUse == FALSE) {
pContext->bBoolInUse = TRUE;
pReturnContext = pContext;
break;
}
}
if ( ii == pDevice->cbTD ) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"No Free Tx Context\n");
}
return ((PVOID) pReturnContext);
}
static
VOID
s_vSaveTxPktInfo(PSDevice pDevice, BYTE byPktNum, PBYTE pbyDestAddr, WORD wPktLength, WORD wFIFOCtl)
{
PSStatCounter pStatistic=&(pDevice->scStatistic);
if (IS_BROADCAST_ADDRESS(pbyDestAddr))
pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni = TX_PKT_BROAD;
else if (IS_MULTICAST_ADDRESS(pbyDestAddr))
pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni = TX_PKT_MULTI;
else
pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni = TX_PKT_UNI;
pStatistic->abyTxPktInfo[byPktNum].wLength = wPktLength;
pStatistic->abyTxPktInfo[byPktNum].wFIFOCtl = wFIFOCtl;
memcpy(pStatistic->abyTxPktInfo[byPktNum].abyDestAddr, pbyDestAddr, U_ETHER_ADDR_LEN);
}
static
VOID
s_vFillTxKey (
IN PSDevice pDevice,
IN PBYTE pbyBuf,
IN PBYTE pbyIVHead,
IN PSKeyItem pTransmitKey,
IN PBYTE pbyHdrBuf,
IN WORD wPayloadLen,
OUT PBYTE pMICHDR
)
{
PDWORD pdwIV = (PDWORD) pbyIVHead;
PDWORD pdwExtIV = (PDWORD) ((PBYTE)pbyIVHead+4);
WORD wValue;
PS802_11Header pMACHeader = (PS802_11Header)pbyHdrBuf;
DWORD dwRevIVCounter;
//Fill TXKEY
if (pTransmitKey == NULL)
return;
dwRevIVCounter = cpu_to_le32(pDevice->dwIVCounter);
*pdwIV = pDevice->dwIVCounter;
pDevice->byKeyIndex = pTransmitKey->dwKeyIndex & 0xf;
if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) {
if (pTransmitKey->uKeyLength == WLAN_WEP232_KEYLEN ){
memcpy(pDevice->abyPRNG, (PBYTE)&(dwRevIVCounter), 3);
memcpy(pDevice->abyPRNG+3, pTransmitKey->abyKey, pTransmitKey->uKeyLength);
} else {
memcpy(pbyBuf, (PBYTE)&(dwRevIVCounter), 3);
memcpy(pbyBuf+3, pTransmitKey->abyKey, pTransmitKey->uKeyLength);
if(pTransmitKey->uKeyLength == WLAN_WEP40_KEYLEN) {
memcpy(pbyBuf+8, (PBYTE)&(dwRevIVCounter), 3);
memcpy(pbyBuf+11, pTransmitKey->abyKey, pTransmitKey->uKeyLength);
}
memcpy(pDevice->abyPRNG, pbyBuf, 16);
}
// Append IV after Mac Header
*pdwIV &= WEP_IV_MASK;//00000000 11111111 11111111 11111111
*pdwIV |= (pDevice->byKeyIndex << 30);
*pdwIV = cpu_to_le32(*pdwIV);
pDevice->dwIVCounter++;
if (pDevice->dwIVCounter > WEP_IV_MASK) {
pDevice->dwIVCounter = 0;
}
} else if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
pTransmitKey->wTSC15_0++;
if (pTransmitKey->wTSC15_0 == 0) {
pTransmitKey->dwTSC47_16++;
}
TKIPvMixKey(pTransmitKey->abyKey, pDevice->abyCurrentNetAddr,
pTransmitKey->wTSC15_0, pTransmitKey->dwTSC47_16, pDevice->abyPRNG);
memcpy(pbyBuf, pDevice->abyPRNG, 16);
// Make IV
memcpy(pdwIV, pDevice->abyPRNG, 3);
*(pbyIVHead+3) = (BYTE)(((pDevice->byKeyIndex << 6) & 0xc0) | 0x20); // 0x20 is ExtIV
// Append IV&ExtIV after Mac Header
*pdwExtIV = cpu_to_le32(pTransmitKey->dwTSC47_16);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"vFillTxKey()---- pdwExtIV: %lx\n", *pdwExtIV);
} else if (pTransmitKey->byCipherSuite == KEY_CTL_CCMP) {
pTransmitKey->wTSC15_0++;
if (pTransmitKey->wTSC15_0 == 0) {
pTransmitKey->dwTSC47_16++;
}
memcpy(pbyBuf, pTransmitKey->abyKey, 16);
// Make IV
*pdwIV = 0;
*(pbyIVHead+3) = (BYTE)(((pDevice->byKeyIndex << 6) & 0xc0) | 0x20); // 0x20 is ExtIV
*pdwIV |= cpu_to_le16((WORD)(pTransmitKey->wTSC15_0));
//Append IV&ExtIV after Mac Header
*pdwExtIV = cpu_to_le32(pTransmitKey->dwTSC47_16);
//Fill MICHDR0
*pMICHDR = 0x59;
*((PBYTE)(pMICHDR+1)) = 0; // TxPriority
memcpy(pMICHDR+2, &(pMACHeader->abyAddr2[0]), 6);
*((PBYTE)(pMICHDR+8)) = HIBYTE(HIWORD(pTransmitKey->dwTSC47_16));
*((PBYTE)(pMICHDR+9)) = LOBYTE(HIWORD(pTransmitKey->dwTSC47_16));
*((PBYTE)(pMICHDR+10)) = HIBYTE(LOWORD(pTransmitKey->dwTSC47_16));
*((PBYTE)(pMICHDR+11)) = LOBYTE(LOWORD(pTransmitKey->dwTSC47_16));
*((PBYTE)(pMICHDR+12)) = HIBYTE(pTransmitKey->wTSC15_0);
*((PBYTE)(pMICHDR+13)) = LOBYTE(pTransmitKey->wTSC15_0);
*((PBYTE)(pMICHDR+14)) = HIBYTE(wPayloadLen);
*((PBYTE)(pMICHDR+15)) = LOBYTE(wPayloadLen);
//Fill MICHDR1
*((PBYTE)(pMICHDR+16)) = 0; // HLEN[15:8]
if (pDevice->bLongHeader) {
*((PBYTE)(pMICHDR+17)) = 28; // HLEN[7:0]
} else {
*((PBYTE)(pMICHDR+17)) = 22; // HLEN[7:0]
}
wValue = cpu_to_le16(pMACHeader->wFrameCtl & 0xC78F);
memcpy(pMICHDR+18, (PBYTE)&wValue, 2); // MSKFRACTL
memcpy(pMICHDR+20, &(pMACHeader->abyAddr1[0]), 6);
memcpy(pMICHDR+26, &(pMACHeader->abyAddr2[0]), 6);
//Fill MICHDR2
memcpy(pMICHDR+32, &(pMACHeader->abyAddr3[0]), 6);
wValue = pMACHeader->wSeqCtl;
wValue &= 0x000F;
wValue = cpu_to_le16(wValue);
memcpy(pMICHDR+38, (PBYTE)&wValue, 2); // MSKSEQCTL
if (pDevice->bLongHeader) {
memcpy(pMICHDR+40, &(pMACHeader->abyAddr4[0]), 6);
}
}
}
static
VOID
s_vSWencryption (
IN PSDevice pDevice,
IN PSKeyItem pTransmitKey,
IN PBYTE pbyPayloadHead,
IN WORD wPayloadSize
)
{
UINT cbICVlen = 4;
DWORD dwICV = 0xFFFFFFFFL;
PDWORD pdwICV;
if (pTransmitKey == NULL)
return;
if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) {
//=======================================================================
// Append ICV after payload
dwICV = CRCdwGetCrc32Ex(pbyPayloadHead, wPayloadSize, dwICV);//ICV(Payload)
pdwICV = (PDWORD)(pbyPayloadHead + wPayloadSize);
// finally, we must invert dwCRC to get the correct answer
*pdwICV = cpu_to_le32(~dwICV);
// RC4 encryption
rc4_init(&pDevice->SBox, pDevice->abyPRNG, pTransmitKey->uKeyLength + 3);
rc4_encrypt(&pDevice->SBox, pbyPayloadHead, pbyPayloadHead, wPayloadSize+cbICVlen);
//=======================================================================
} else if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
//=======================================================================
//Append ICV after payload
dwICV = CRCdwGetCrc32Ex(pbyPayloadHead, wPayloadSize, dwICV);//ICV(Payload)
pdwICV = (PDWORD)(pbyPayloadHead + wPayloadSize);
// finally, we must invert dwCRC to get the correct answer
*pdwICV = cpu_to_le32(~dwICV);
// RC4 encryption
rc4_init(&pDevice->SBox, pDevice->abyPRNG, TKIP_KEY_LEN);
rc4_encrypt(&pDevice->SBox, pbyPayloadHead, pbyPayloadHead, wPayloadSize+cbICVlen);
//=======================================================================
}
}
/*byPktType : PK_TYPE_11A 0
PK_TYPE_11B 1
PK_TYPE_11GB 2
PK_TYPE_11GA 3
*/
static
UINT
s_uGetTxRsvTime (
IN PSDevice pDevice,
IN BYTE byPktType,
IN UINT cbFrameLength,
IN WORD wRate,
IN BOOL bNeedAck
)
{
UINT uDataTime, uAckTime;
uDataTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, cbFrameLength, wRate);
if (byPktType == PK_TYPE_11B) {//llb,CCK mode
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, (WORD)pDevice->byTopCCKBasicRate);
} else {//11g 2.4G OFDM mode & 11a 5G OFDM mode
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, (WORD)pDevice->byTopOFDMBasicRate);
}
if (bNeedAck) {
return (uDataTime + pDevice->uSIFS + uAckTime);
}
else {
return uDataTime;
}
}
//byFreqType: 0=>5GHZ 1=>2.4GHZ
static
UINT
s_uGetRTSCTSRsvTime (
IN PSDevice pDevice,
IN BYTE byRTSRsvType,
IN BYTE byPktType,
IN UINT cbFrameLength,
IN WORD wCurrentRate
)
{
UINT uRrvTime , uRTSTime, uCTSTime, uAckTime, uDataTime;
uRrvTime = uRTSTime = uCTSTime = uAckTime = uDataTime = 0;
uDataTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, cbFrameLength, wCurrentRate);
if (byRTSRsvType == 0) { //RTSTxRrvTime_bb
uRTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 20, pDevice->byTopCCKBasicRate);
uCTSTime = uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
}
else if (byRTSRsvType == 1){ //RTSTxRrvTime_ba, only in 2.4GHZ
uRTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 20, pDevice->byTopCCKBasicRate);
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
}
else if (byRTSRsvType == 2) { //RTSTxRrvTime_aa
uRTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 20, pDevice->byTopOFDMBasicRate);
uCTSTime = uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
}
else if (byRTSRsvType == 3) { //CTSTxRrvTime_ba, only in 2.4GHZ
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
uRrvTime = uCTSTime + uAckTime + uDataTime + 2*pDevice->uSIFS;
return uRrvTime;
}
//RTSRrvTime
uRrvTime = uRTSTime + uCTSTime + uAckTime + uDataTime + 3*pDevice->uSIFS;
return uRrvTime;
}
//byFreqType 0: 5GHz, 1:2.4Ghz
static
UINT
s_uGetDataDuration (
IN PSDevice pDevice,
IN BYTE byDurType,
IN UINT cbFrameLength,
IN BYTE byPktType,
IN WORD wRate,
IN BOOL bNeedAck,
IN UINT uFragIdx,
IN UINT cbLastFragmentSize,
IN UINT uMACfragNum,
IN BYTE byFBOption
)
{
BOOL bLastFrag = 0;
UINT uAckTime =0, uNextPktTime = 0;
if (uFragIdx == (uMACfragNum-1)) {
bLastFrag = 1;
}
switch (byDurType) {
case DATADUR_B: //DATADUR_B
if (((uMACfragNum == 1)) || (bLastFrag == 1)) {//Non Frag or Last Frag
if (bNeedAck) {
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
return (pDevice->uSIFS + uAckTime);
} else {
return 0;
}
}
else {//First Frag or Mid Frag
if (uFragIdx == (uMACfragNum-2)) {
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wRate, bNeedAck);
} else {
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
}
if (bNeedAck) {
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
return (pDevice->uSIFS + uAckTime + uNextPktTime);
} else {
return (pDevice->uSIFS + uNextPktTime);
}
}
break;
case DATADUR_A: //DATADUR_A
if (((uMACfragNum==1)) || (bLastFrag==1)) {//Non Frag or Last Frag
if(bNeedAck){
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
return (pDevice->uSIFS + uAckTime);
} else {
return 0;
}
}
else {//First Frag or Mid Frag
if(uFragIdx == (uMACfragNum-2)){
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wRate, bNeedAck);
} else {
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
}
if(bNeedAck){
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
return (pDevice->uSIFS + uAckTime + uNextPktTime);
} else {
return (pDevice->uSIFS + uNextPktTime);
}
}
break;
case DATADUR_A_F0: //DATADUR_A_F0
if (((uMACfragNum==1)) || (bLastFrag==1)) {//Non Frag or Last Frag
if(bNeedAck){
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
return (pDevice->uSIFS + uAckTime);
} else {
return 0;
}
}
else { //First Frag or Mid Frag
if (byFBOption == AUTO_FB_0) {
if (wRate < RATE_18M)
wRate = RATE_18M;
else if (wRate > RATE_54M)
wRate = RATE_54M;
if(uFragIdx == (uMACfragNum-2)){
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
} else {
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
}
} else { // (byFBOption == AUTO_FB_1)
if (wRate < RATE_18M)
wRate = RATE_18M;
else if (wRate > RATE_54M)
wRate = RATE_54M;
if(uFragIdx == (uMACfragNum-2)){
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
} else {
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
}
}
if(bNeedAck){
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
return (pDevice->uSIFS + uAckTime + uNextPktTime);
} else {
return (pDevice->uSIFS + uNextPktTime);
}
}
break;
case DATADUR_A_F1: //DATADUR_A_F1
if (((uMACfragNum==1)) || (bLastFrag==1)) {//Non Frag or Last Frag
if(bNeedAck){
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
return (pDevice->uSIFS + uAckTime);
} else {
return 0;
}
}
else { //First Frag or Mid Frag
if (byFBOption == AUTO_FB_0) {
if (wRate < RATE_18M)
wRate = RATE_18M;
else if (wRate > RATE_54M)
wRate = RATE_54M;
if(uFragIdx == (uMACfragNum-2)){
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
} else {
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
}
} else { // (byFBOption == AUTO_FB_1)
if (wRate < RATE_18M)
wRate = RATE_18M;
else if (wRate > RATE_54M)
wRate = RATE_54M;
if(uFragIdx == (uMACfragNum-2)){
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
} else {
uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
}
}
if(bNeedAck){
uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
return (pDevice->uSIFS + uAckTime + uNextPktTime);
} else {
return (pDevice->uSIFS + uNextPktTime);
}
}
break;
default:
break;
}
ASSERT(FALSE);
return 0;
}
//byFreqType: 0=>5GHZ 1=>2.4GHZ
static
UINT
s_uGetRTSCTSDuration (
IN PSDevice pDevice,
IN BYTE byDurType,
IN UINT cbFrameLength,
IN BYTE byPktType,
IN WORD wRate,
IN BOOL bNeedAck,
IN BYTE byFBOption
)
{
UINT uCTSTime = 0, uDurTime = 0;
switch (byDurType) {
case RTSDUR_BB: //RTSDuration_bb
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
break;
case RTSDUR_BA: //RTSDuration_ba
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
break;
case RTSDUR_AA: //RTSDuration_aa
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
break;
case CTSDUR_BA: //CTSDuration_ba
uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
break;
case RTSDUR_BA_F0: //RTSDuration_ba_f0
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
} else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
}
break;
case RTSDUR_AA_F0: //RTSDuration_aa_f0
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
} else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
}
break;
case RTSDUR_BA_F1: //RTSDuration_ba_f1
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
} else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
}
break;
case RTSDUR_AA_F1: //RTSDuration_aa_f1
uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
} else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
}
break;
case CTSDUR_BA_F0: //CTSDuration_ba_f0
if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
} else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
}
break;
case CTSDUR_BA_F1: //CTSDuration_ba_f1
if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
} else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
}
break;
default:
break;
}
return uDurTime;
}
static
UINT
s_uFillDataHead (
IN PSDevice pDevice,
IN BYTE byPktType,
IN WORD wCurrentRate,
IN PVOID pTxDataHead,
IN UINT cbFrameLength,
IN UINT uDMAIdx,
IN BOOL bNeedAck,
IN UINT uFragIdx,
IN UINT cbLastFragmentSize,
IN UINT uMACfragNum,
IN BYTE byFBOption
)
{
if (pTxDataHead == NULL) {
return 0;
}
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {
if((uDMAIdx==TYPE_ATIMDMA)||(uDMAIdx==TYPE_BEACONDMA)) {
PSTxDataHead_ab pBuf = (PSTxDataHead_ab)pTxDataHead;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktType,
(PWORD)&(pBuf->wTransmitLength), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
);
//Get Duration and TimeStampOff
pBuf->wDuration = (WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx,
cbLastFragmentSize, uMACfragNum,
byFBOption); //1: 2.4GHz
if(uDMAIdx!=TYPE_ATIMDMA) {
pBuf->wTimeStampOff = wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE];
}
return (pBuf->wDuration);
}
else { // DATA & MANAGE Frame
if (byFBOption == AUTO_FB_NONE) {
PSTxDataHead_g pBuf = (PSTxDataHead_g)pTxDataHead;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktType,
(PWORD)&(pBuf->wTransmitLength_a), (PBYTE)&(pBuf->byServiceField_a), (PBYTE)&(pBuf->bySignalField_a)
);
BBvCaculateParameter(pDevice, cbFrameLength, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
(PWORD)&(pBuf->wTransmitLength_b), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
);
//Get Duration and TimeStamp
pBuf->wDuration_a = (WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength,
byPktType, wCurrentRate, bNeedAck, uFragIdx,
cbLastFragmentSize, uMACfragNum,
byFBOption); //1: 2.4GHz
pBuf->wDuration_b = (WORD)s_uGetDataDuration(pDevice, DATADUR_B, cbFrameLength,
PK_TYPE_11B, pDevice->byTopCCKBasicRate,
bNeedAck, uFragIdx, cbLastFragmentSize,
uMACfragNum, byFBOption); //1: 2.4GHz
pBuf->wTimeStampOff_a = wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE];
pBuf->wTimeStampOff_b = wTimeStampOff[pDevice->byPreambleType%2][pDevice->byTopCCKBasicRate%MAX_RATE];
return (pBuf->wDuration_a);
} else {
// Auto Fallback
PSTxDataHead_g_FB pBuf = (PSTxDataHead_g_FB)pTxDataHead;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktType,
(PWORD)&(pBuf->wTransmitLength_a), (PBYTE)&(pBuf->byServiceField_a), (PBYTE)&(pBuf->bySignalField_a)
);
BBvCaculateParameter(pDevice, cbFrameLength, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
(PWORD)&(pBuf->wTransmitLength_b), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
);
//Get Duration and TimeStamp
pBuf->wDuration_a = (WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption); //1: 2.4GHz
pBuf->wDuration_b = (WORD)s_uGetDataDuration(pDevice, DATADUR_B, cbFrameLength, PK_TYPE_11B,
pDevice->byTopCCKBasicRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption); //1: 2.4GHz
pBuf->wDuration_a_f0 = (WORD)s_uGetDataDuration(pDevice, DATADUR_A_F0, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption); //1: 2.4GHz
pBuf->wDuration_a_f1 = (WORD)s_uGetDataDuration(pDevice, DATADUR_A_F1, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption); //1: 2.4GHz
pBuf->wTimeStampOff_a = wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE];
pBuf->wTimeStampOff_b = wTimeStampOff[pDevice->byPreambleType%2][pDevice->byTopCCKBasicRate%MAX_RATE];
return (pBuf->wDuration_a);
} //if (byFBOption == AUTO_FB_NONE)
}
}
else if (byPktType == PK_TYPE_11A) {
if ((byFBOption != AUTO_FB_NONE) && (uDMAIdx != TYPE_ATIMDMA) && (uDMAIdx != TYPE_BEACONDMA)) {
// Auto Fallback
PSTxDataHead_a_FB pBuf = (PSTxDataHead_a_FB)pTxDataHead;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktType,
(PWORD)&(pBuf->wTransmitLength), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
);
//Get Duration and TimeStampOff
pBuf->wDuration = (WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption); //0: 5GHz
pBuf->wDuration_f0 = (WORD)s_uGetDataDuration(pDevice, DATADUR_A_F0, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption); //0: 5GHz
pBuf->wDuration_f1 = (WORD)s_uGetDataDuration(pDevice, DATADUR_A_F1, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption); //0: 5GHz
if(uDMAIdx!=TYPE_ATIMDMA) {
pBuf->wTimeStampOff = wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE];
}
return (pBuf->wDuration);
} else {
PSTxDataHead_ab pBuf = (PSTxDataHead_ab)pTxDataHead;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktType,
(PWORD)&(pBuf->wTransmitLength), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
);
//Get Duration and TimeStampOff
pBuf->wDuration = (WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx,
cbLastFragmentSize, uMACfragNum,
byFBOption);
if(uDMAIdx!=TYPE_ATIMDMA) {
pBuf->wTimeStampOff = wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE];
}
return (pBuf->wDuration);
}
}
else if (byPktType == PK_TYPE_11B) {
PSTxDataHead_ab pBuf = (PSTxDataHead_ab)pTxDataHead;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktType,
(PWORD)&(pBuf->wTransmitLength), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
);
//Get Duration and TimeStampOff
pBuf->wDuration = (WORD)s_uGetDataDuration(pDevice, DATADUR_B, cbFrameLength, byPktType,
wCurrentRate, bNeedAck, uFragIdx,
cbLastFragmentSize, uMACfragNum,
byFBOption);
if (uDMAIdx != TYPE_ATIMDMA) {
pBuf->wTimeStampOff = wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE];
}
return (pBuf->wDuration);
}
return 0;
}
static
VOID
s_vFillRTSHead (
IN PSDevice pDevice,
IN BYTE byPktType,
IN PVOID pvRTS,
IN UINT cbFrameLength,
IN BOOL bNeedAck,
IN BOOL bDisCRC,
IN PSEthernetHeader psEthHeader,
IN WORD wCurrentRate,
IN BYTE byFBOption
)
{
UINT uRTSFrameLen = 20;
WORD wLen = 0x0000;
if (pvRTS == NULL)
return;
if (bDisCRC) {
// When CRCDIS bit is on, H/W forgot to generate FCS for RTS frame,
// in this case we need to decrease its length by 4.
uRTSFrameLen -= 4;
}
// Note: So far RTSHead dosen't appear in ATIM & Beacom DMA, so we don't need to take them into account.
// Otherwise, we need to modified codes for them.
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {
if (byFBOption == AUTO_FB_NONE) {
PSRTS_g pBuf = (PSRTS_g)pvRTS;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
);
pBuf->wTransmitLength_b = cpu_to_le16(wLen);
BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopOFDMBasicRate, byPktType,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_a), (PBYTE)&(pBuf->bySignalField_a)
);
pBuf->wTransmitLength_a = cpu_to_le16(wLen);
//Get Duration
pBuf->wDuration_bb = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BB, cbFrameLength, PK_TYPE_11B, pDevice->byTopCCKBasicRate, bNeedAck, byFBOption)); //0:RTSDuration_bb, 1:2.4G, 1:CCKData
pBuf->wDuration_aa = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //2:RTSDuration_aa, 1:2.4G, 2,3: 2.4G OFDMData
pBuf->wDuration_ba = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BA, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //1:RTSDuration_ba, 1:2.4G, 2,3:2.4G OFDM Data
pBuf->Data.wDurationID = pBuf->wDuration_aa;
//Get RTS Frame body
pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
(pDevice->eOPMode == OP_MODE_AP)) {
memcpy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
if (pDevice->eOPMode == OP_MODE_AP) {
memcpy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
}
}
else {
PSRTS_g_FB pBuf = (PSRTS_g_FB)pvRTS;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
);
pBuf->wTransmitLength_b = cpu_to_le16(wLen);
BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopOFDMBasicRate, byPktType,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_a), (PBYTE)&(pBuf->bySignalField_a)
);
pBuf->wTransmitLength_a = cpu_to_le16(wLen);
//Get Duration
pBuf->wDuration_bb = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BB, cbFrameLength, PK_TYPE_11B, pDevice->byTopCCKBasicRate, bNeedAck, byFBOption)); //0:RTSDuration_bb, 1:2.4G, 1:CCKData
pBuf->wDuration_aa = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //2:RTSDuration_aa, 1:2.4G, 2,3:2.4G OFDMData
pBuf->wDuration_ba = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BA, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //1:RTSDuration_ba, 1:2.4G, 2,3:2.4G OFDMData
pBuf->wRTSDuration_ba_f0 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BA_F0, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //4:wRTSDuration_ba_f0, 1:2.4G, 1:CCKData
pBuf->wRTSDuration_aa_f0 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA_F0, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //5:wRTSDuration_aa_f0, 1:2.4G, 1:CCKData
pBuf->wRTSDuration_ba_f1 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BA_F1, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //6:wRTSDuration_ba_f1, 1:2.4G, 1:CCKData
pBuf->wRTSDuration_aa_f1 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA_F1, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //7:wRTSDuration_aa_f1, 1:2.4G, 1:CCKData
pBuf->Data.wDurationID = pBuf->wDuration_aa;
//Get RTS Frame body
pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
(pDevice->eOPMode == OP_MODE_AP)) {
memcpy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
if (pDevice->eOPMode == OP_MODE_AP) {
memcpy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
}
} // if (byFBOption == AUTO_FB_NONE)
}
else if (byPktType == PK_TYPE_11A) {
if (byFBOption == AUTO_FB_NONE) {
PSRTS_ab pBuf = (PSRTS_ab)pvRTS;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopOFDMBasicRate, byPktType,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
);
pBuf->wTransmitLength = cpu_to_le16(wLen);
//Get Duration
pBuf->wDuration = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //0:RTSDuration_aa, 0:5G, 0: 5G OFDMData
pBuf->Data.wDurationID = pBuf->wDuration;
//Get RTS Frame body
pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
(pDevice->eOPMode == OP_MODE_AP)) {
memcpy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
if (pDevice->eOPMode == OP_MODE_AP) {
memcpy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
}
}
else {
PSRTS_a_FB pBuf = (PSRTS_a_FB)pvRTS;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopOFDMBasicRate, byPktType,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
);
pBuf->wTransmitLength = cpu_to_le16(wLen);
//Get Duration
pBuf->wDuration = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //0:RTSDuration_aa, 0:5G, 0: 5G OFDMData
pBuf->wRTSDuration_f0 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA_F0, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //5:RTSDuration_aa_f0, 0:5G, 0: 5G OFDMData
pBuf->wRTSDuration_f1 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA_F1, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //7:RTSDuration_aa_f1, 0:5G, 0:
pBuf->Data.wDurationID = pBuf->wDuration;
//Get RTS Frame body
pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
(pDevice->eOPMode == OP_MODE_AP)) {
memcpy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
if (pDevice->eOPMode == OP_MODE_AP) {
memcpy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
}
}
}
else if (byPktType == PK_TYPE_11B) {
PSRTS_ab pBuf = (PSRTS_ab)pvRTS;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
);
pBuf->wTransmitLength = cpu_to_le16(wLen);
//Get Duration
pBuf->wDuration = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BB, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //0:RTSDuration_bb, 1:2.4G, 1:CCKData
pBuf->Data.wDurationID = pBuf->wDuration;
//Get RTS Frame body
pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
(pDevice->eOPMode == OP_MODE_AP)) {
memcpy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
if (pDevice->eOPMode == OP_MODE_AP) {
memcpy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
}
}
}
static
VOID
s_vFillCTSHead (
IN PSDevice pDevice,
IN UINT uDMAIdx,
IN BYTE byPktType,
IN PVOID pvCTS,
IN UINT cbFrameLength,
IN BOOL bNeedAck,
IN BOOL bDisCRC,
IN WORD wCurrentRate,
IN BYTE byFBOption
)
{
UINT uCTSFrameLen = 14;
WORD wLen = 0x0000;
if (pvCTS == NULL) {
return;
}
if (bDisCRC) {
// When CRCDIS bit is on, H/W forgot to generate FCS for CTS frame,
// in this case we need to decrease its length by 4.
uCTSFrameLen -= 4;
}
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {
if (byFBOption != AUTO_FB_NONE && uDMAIdx != TYPE_ATIMDMA && uDMAIdx != TYPE_BEACONDMA) {
// Auto Fall back
PSCTS_FB pBuf = (PSCTS_FB)pvCTS;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, uCTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
);
pBuf->wTransmitLength_b = cpu_to_le16(wLen);
pBuf->wDuration_ba = (WORD)s_uGetRTSCTSDuration(pDevice, CTSDUR_BA, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption); //3:CTSDuration_ba, 1:2.4G, 2,3:2.4G OFDM Data
pBuf->wDuration_ba += pDevice->wCTSDuration;
pBuf->wDuration_ba = cpu_to_le16(pBuf->wDuration_ba);
//Get CTSDuration_ba_f0
pBuf->wCTSDuration_ba_f0 = (WORD)s_uGetRTSCTSDuration(pDevice, CTSDUR_BA_F0, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption); //8:CTSDuration_ba_f0, 1:2.4G, 2,3:2.4G OFDM Data
pBuf->wCTSDuration_ba_f0 += pDevice->wCTSDuration;
pBuf->wCTSDuration_ba_f0 = cpu_to_le16(pBuf->wCTSDuration_ba_f0);
//Get CTSDuration_ba_f1
pBuf->wCTSDuration_ba_f1 = (WORD)s_uGetRTSCTSDuration(pDevice, CTSDUR_BA_F1, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption); //9:CTSDuration_ba_f1, 1:2.4G, 2,3:2.4G OFDM Data
pBuf->wCTSDuration_ba_f1 += pDevice->wCTSDuration;
pBuf->wCTSDuration_ba_f1 = cpu_to_le16(pBuf->wCTSDuration_ba_f1);
//Get CTS Frame body
pBuf->Data.wDurationID = pBuf->wDuration_ba;
pBuf->Data.wFrameControl = TYPE_CTL_CTS;//0x00C4
pBuf->Data.wReserved = 0x0000;
memcpy(&(pBuf->Data.abyRA[0]), &(pDevice->abyCurrentNetAddr[0]), U_ETHER_ADDR_LEN);
} else { //if (byFBOption != AUTO_FB_NONE && uDMAIdx != TYPE_ATIMDMA && uDMAIdx != TYPE_BEACONDMA)
PSCTS pBuf = (PSCTS)pvCTS;
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, uCTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
(PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
);
pBuf->wTransmitLength_b = cpu_to_le16(wLen);
//Get CTSDuration_ba
pBuf->wDuration_ba = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, CTSDUR_BA, cbFrameLength, byPktType, wCurrentRate, bNeedAck, byFBOption)); //3:CTSDuration_ba, 1:2.4G, 2,3:2.4G OFDM Data
pBuf->wDuration_ba += pDevice->wCTSDuration;
pBuf->wDuration_ba = cpu_to_le16(pBuf->wDuration_ba);
//Get CTS Frame body
pBuf->Data.wDurationID = pBuf->wDuration_ba;
pBuf->Data.wFrameControl = TYPE_CTL_CTS;//0x00C4
pBuf->Data.wReserved = 0x0000;
memcpy(&(pBuf->Data.abyRA[0]), &(pDevice->abyCurrentNetAddr[0]), U_ETHER_ADDR_LEN);
}
}
}
/*+
*
* Description:
* Generate FIFO control for MAC & Baseband controller
*
* Parameters:
* In:
* pDevice - Pointer to adpater
* pTxDataHead - Transmit Data Buffer
* pTxBufHead - pTxBufHead
* pvRrvTime - pvRrvTime
* pvRTS - RTS Buffer
* pCTS - CTS Buffer
* cbFrameSize - Transmit Data Length (Hdr+Payload+FCS)
* bNeedACK - If need ACK
* uDMAIdx - DMA Index
* Out:
* none
*
* Return Value: none
*
-*/
// UINT cbFrameSize,//Hdr+Payload+FCS
static
VOID
s_vGenerateTxParameter (
IN PSDevice pDevice,
IN BYTE byPktType,
IN WORD wCurrentRate,
IN PVOID pTxBufHead,
IN PVOID pvRrvTime,
IN PVOID pvRTS,
IN PVOID pvCTS,
IN UINT cbFrameSize,
IN BOOL bNeedACK,
IN UINT uDMAIdx,
IN PSEthernetHeader psEthHeader
)
{
UINT cbMACHdLen = WLAN_HDR_ADDR3_LEN; //24
WORD wFifoCtl;
BOOL bDisCRC = FALSE;
BYTE byFBOption = AUTO_FB_NONE;
// WORD wCurrentRate = pDevice->wCurrentRate;
//DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"s_vGenerateTxParameter...\n");
PSTxBufHead pFifoHead = (PSTxBufHead)pTxBufHead;
pFifoHead->wReserved = wCurrentRate;
wFifoCtl = pFifoHead->wFIFOCtl;
if (wFifoCtl & FIFOCTL_CRCDIS) {
bDisCRC = TRUE;
}
if (wFifoCtl & FIFOCTL_AUTO_FB_0) {
byFBOption = AUTO_FB_0;
}
else if (wFifoCtl & FIFOCTL_AUTO_FB_1) {
byFBOption = AUTO_FB_1;
}
if (pDevice->bLongHeader)
cbMACHdLen = WLAN_HDR_ADDR3_LEN + 6;
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {
if (pvRTS != NULL) { //RTS_need
//Fill RsvTime
if (pvRrvTime) {
PSRrvTime_gRTS pBuf = (PSRrvTime_gRTS)pvRrvTime;
pBuf->wRTSTxRrvTime_aa = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 2, byPktType, cbFrameSize, wCurrentRate));//2:RTSTxRrvTime_aa, 1:2.4GHz
pBuf->wRTSTxRrvTime_ba = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 1, byPktType, cbFrameSize, wCurrentRate));//1:RTSTxRrvTime_ba, 1:2.4GHz
pBuf->wRTSTxRrvTime_bb = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 0, byPktType, cbFrameSize, wCurrentRate));//0:RTSTxRrvTime_bb, 1:2.4GHz
pBuf->wTxRrvTime_a = cpu_to_le16((WORD) s_uGetTxRsvTime(pDevice, byPktType, cbFrameSize, wCurrentRate, bNeedACK));//2.4G OFDM
pBuf->wTxRrvTime_b = cpu_to_le16((WORD) s_uGetTxRsvTime(pDevice, PK_TYPE_11B, cbFrameSize, pDevice->byTopCCKBasicRate, bNeedACK));//1:CCK
}
//Fill RTS
s_vFillRTSHead(pDevice, byPktType, pvRTS, cbFrameSize, bNeedACK, bDisCRC, psEthHeader, wCurrentRate, byFBOption);
}
else {//RTS_needless, PCF mode
//Fill RsvTime
if (pvRrvTime) {
PSRrvTime_gCTS pBuf = (PSRrvTime_gCTS)pvRrvTime;
pBuf->wTxRrvTime_a = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, byPktType, cbFrameSize, wCurrentRate, bNeedACK));//2.4G OFDM
pBuf->wTxRrvTime_b = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, PK_TYPE_11B, cbFrameSize, pDevice->byTopCCKBasicRate, bNeedACK));//1:CCK
pBuf->wCTSTxRrvTime_ba = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 3, byPktType, cbFrameSize, wCurrentRate));//3:CTSTxRrvTime_Ba, 1:2.4GHz
}
//Fill CTS
s_vFillCTSHead(pDevice, uDMAIdx, byPktType, pvCTS, cbFrameSize, bNeedACK, bDisCRC, wCurrentRate, byFBOption);
}
}
else if (byPktType == PK_TYPE_11A) {
if (pvRTS != NULL) {//RTS_need, non PCF mode
//Fill RsvTime
if (pvRrvTime) {
PSRrvTime_ab pBuf = (PSRrvTime_ab)pvRrvTime;
pBuf->wRTSTxRrvTime = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 2, byPktType, cbFrameSize, wCurrentRate));//2:RTSTxRrvTime_aa, 0:5GHz
pBuf->wTxRrvTime = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, byPktType, cbFrameSize, wCurrentRate, bNeedACK));//0:OFDM
}
//Fill RTS
s_vFillRTSHead(pDevice, byPktType, pvRTS, cbFrameSize, bNeedACK, bDisCRC, psEthHeader, wCurrentRate, byFBOption);
}
else if (pvRTS == NULL) {//RTS_needless, non PCF mode
//Fill RsvTime
if (pvRrvTime) {
PSRrvTime_ab pBuf = (PSRrvTime_ab)pvRrvTime;
pBuf->wTxRrvTime = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, PK_TYPE_11A, cbFrameSize, wCurrentRate, bNeedACK)); //0:OFDM
}
}
}
else if (byPktType == PK_TYPE_11B) {
if ((pvRTS != NULL)) {//RTS_need, non PCF mode
//Fill RsvTime
if (pvRrvTime) {
PSRrvTime_ab pBuf = (PSRrvTime_ab)pvRrvTime;
pBuf->wRTSTxRrvTime = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 0, byPktType, cbFrameSize, wCurrentRate));//0:RTSTxRrvTime_bb, 1:2.4GHz
pBuf->wTxRrvTime = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, PK_TYPE_11B, cbFrameSize, wCurrentRate, bNeedACK));//1:CCK
}
//Fill RTS
s_vFillRTSHead(pDevice, byPktType, pvRTS, cbFrameSize, bNeedACK, bDisCRC, psEthHeader, wCurrentRate, byFBOption);
}
else { //RTS_needless, non PCF mode
//Fill RsvTime
if (pvRrvTime) {
PSRrvTime_ab pBuf = (PSRrvTime_ab)pvRrvTime;
pBuf->wTxRrvTime = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, PK_TYPE_11B, cbFrameSize, wCurrentRate, bNeedACK)); //1:CCK
}
}
}
//DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"s_vGenerateTxParameter END.\n");
}
/*
PBYTE pbyBuffer,//point to pTxBufHead
WORD wFragType,//00:Non-Frag, 01:Start, 02:Mid, 03:Last
UINT cbFragmentSize,//Hdr+payoad+FCS
*/
BOOL
s_bPacketToWirelessUsb(
IN PSDevice pDevice,
IN BYTE byPktType,
IN PBYTE usbPacketBuf,
IN BOOL bNeedEncryption,
IN UINT uSkbPacketLen,
IN UINT uDMAIdx,
IN PSEthernetHeader psEthHeader,
IN PBYTE pPacket,
IN PSKeyItem pTransmitKey,
IN UINT uNodeIndex,
IN WORD wCurrentRate,
OUT UINT *pcbHeaderLen,
OUT UINT *pcbTotalLen
)
{
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
UINT cbFrameSize,cbFrameBodySize;
PTX_BUFFER pTxBufHead;
UINT cb802_1_H_len;
UINT cbIVlen=0,cbICVlen=0,cbMIClen=0,cbMACHdLen=0,cbFCSlen=4;
UINT cbMICHDR = 0;
BOOL bNeedACK,bRTS;
PBYTE pbyType,pbyMacHdr,pbyIVHead,pbyPayloadHead,pbyTxBufferAddr;
BYTE abySNAP_RFC1042[6] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
BYTE abySNAP_Bridgetunnel[6] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0xF8};
UINT uDuration;
UINT cbHeaderLength= 0,uPadding = 0;
PVOID pvRrvTime;
PSMICHDRHead pMICHDR;
PVOID pvRTS;
PVOID pvCTS;
PVOID pvTxDataHd;
BYTE byFBOption = AUTO_FB_NONE,byFragType;
WORD wTxBufSize;
DWORD dwMICKey0,dwMICKey1,dwMIC_Priority,dwCRC;
PDWORD pdwMIC_L,pdwMIC_R;
BOOL bSoftWEP = FALSE;
pvRrvTime = pMICHDR = pvRTS = pvCTS = pvTxDataHd = NULL;
if ((bNeedEncryption) && (pTransmitKey != NULL)) {
if (((PSKeyTable) (pTransmitKey->pvKeyTable))->bSoftWEP == TRUE) {
// WEP 256
bSoftWEP = TRUE;
}
}
pTxBufHead = (PTX_BUFFER) usbPacketBuf;
memset(pTxBufHead, 0, sizeof(TX_BUFFER));
// Get pkt type
if (ntohs(psEthHeader->wType) > MAX_DATA_LEN) {
if (pDevice->dwDiagRefCount == 0) {
cb802_1_H_len = 8;
} else {
cb802_1_H_len = 2;
}
} else {
cb802_1_H_len = 0;
}
cbFrameBodySize = uSkbPacketLen - U_HEADER_LEN + cb802_1_H_len;
//Set packet type
pTxBufHead->wFIFOCtl |= (WORD)(byPktType<<8);
if (pDevice->dwDiagRefCount != 0) {
bNeedACK = FALSE;
pTxBufHead->wFIFOCtl = pTxBufHead->wFIFOCtl & (~FIFOCTL_NEEDACK);
} else { //if (pDevice->dwDiagRefCount != 0) {
if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
(pDevice->eOPMode == OP_MODE_AP)) {
if (IS_MULTICAST_ADDRESS(&(psEthHeader->abyDstAddr[0])) ||
IS_BROADCAST_ADDRESS(&(psEthHeader->abyDstAddr[0]))) {
bNeedACK = FALSE;
pTxBufHead->wFIFOCtl = pTxBufHead->wFIFOCtl & (~FIFOCTL_NEEDACK);
}
else {
bNeedACK = TRUE;
pTxBufHead->wFIFOCtl |= FIFOCTL_NEEDACK;
}
}
else {
// MSDUs in Infra mode always need ACK
bNeedACK = TRUE;
pTxBufHead->wFIFOCtl |= FIFOCTL_NEEDACK;
}
} //if (pDevice->dwDiagRefCount != 0) {
pTxBufHead->wTimeStamp = DEFAULT_MSDU_LIFETIME_RES_64us;
//Set FIFOCTL_LHEAD
if (pDevice->bLongHeader)
pTxBufHead->wFIFOCtl |= FIFOCTL_LHEAD;
if (pDevice->bSoftwareGenCrcErr) {
pTxBufHead->wFIFOCtl |= FIFOCTL_CRCDIS; // set tx descriptors to NO hardware CRC
}
//Set FRAGCTL_MACHDCNT
if (pDevice->bLongHeader) {
cbMACHdLen = WLAN_HDR_ADDR3_LEN + 6;
} else {
cbMACHdLen = WLAN_HDR_ADDR3_LEN;
}
pTxBufHead->wFragCtl |= (WORD)(cbMACHdLen << 10);
//Set FIFOCTL_GrpAckPolicy
if (pDevice->bGrpAckPolicy == TRUE) {//0000 0100 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_GRPACK;
}
//Set Auto Fallback Ctl
if (wCurrentRate >= RATE_18M) {
if (pDevice->byAutoFBCtrl == AUTO_FB_0) {
pTxBufHead->wFIFOCtl |= FIFOCTL_AUTO_FB_0;
byFBOption = AUTO_FB_0;
} else if (pDevice->byAutoFBCtrl == AUTO_FB_1) {
pTxBufHead->wFIFOCtl |= FIFOCTL_AUTO_FB_1;
byFBOption = AUTO_FB_1;
}
}
if (bSoftWEP != TRUE) {
if ((bNeedEncryption) && (pTransmitKey != NULL)) { //WEP enabled
if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) { //WEP40 or WEP104
pTxBufHead->wFragCtl |= FRAGCTL_LEGACY;
}
if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Tx Set wFragCtl == FRAGCTL_TKIP\n");
pTxBufHead->wFragCtl |= FRAGCTL_TKIP;
}
else if (pTransmitKey->byCipherSuite == KEY_CTL_CCMP) { //CCMP
pTxBufHead->wFragCtl |= FRAGCTL_AES;
}
}
}
if ((bNeedEncryption) && (pTransmitKey != NULL)) {
if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) {
cbIVlen = 4;
cbICVlen = 4;
}
else if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
cbIVlen = 8;//IV+ExtIV
cbMIClen = 8;
cbICVlen = 4;
}
if (pTransmitKey->byCipherSuite == KEY_CTL_CCMP) {
cbIVlen = 8;//RSN Header
cbICVlen = 8;//MIC
cbMICHDR = sizeof(SMICHDRHead);
}
if (bSoftWEP == FALSE) {
//MAC Header should be padding 0 to DW alignment.
uPadding = 4 - (cbMACHdLen%4);
uPadding %= 4;
}
}
cbFrameSize = cbMACHdLen + cbIVlen + (cbFrameBodySize + cbMIClen) + cbICVlen + cbFCSlen;
if ( (bNeedACK == FALSE) ||(cbFrameSize < pDevice->wRTSThreshold) ) {
bRTS = FALSE;
} else {
bRTS = TRUE;
pTxBufHead->wFIFOCtl |= (FIFOCTL_RTS | FIFOCTL_LRETRY);
}
pbyTxBufferAddr = (PBYTE) &(pTxBufHead->adwTxKey[0]);
wTxBufSize = sizeof(STxBufHead);
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {//802.11g packet
if (byFBOption == AUTO_FB_NONE) {
if (bRTS == TRUE) {//RTS_need
pvRrvTime = (PSRrvTime_gRTS) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS));
pvRTS = (PSRTS_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR);
pvCTS = NULL;
pvTxDataHd = (PSTxDataHead_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR + sizeof(SRTS_g));
cbHeaderLength = wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR + sizeof(SRTS_g) + sizeof(STxDataHead_g);
}
else { //RTS_needless
pvRrvTime = (PSRrvTime_gCTS) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS));
pvRTS = NULL;
pvCTS = (PSCTS) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR);
pvTxDataHd = (PSTxDataHead_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS));
cbHeaderLength = wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS) + sizeof(STxDataHead_g);
}
} else {
// Auto Fall Back
if (bRTS == TRUE) {//RTS_need
pvRrvTime = (PSRrvTime_gRTS) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS));
pvRTS = (PSRTS_g_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR);
pvCTS = NULL;
pvTxDataHd = (PSTxDataHead_g_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR + sizeof(SRTS_g_FB));
cbHeaderLength = wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR + sizeof(SRTS_g_FB) + sizeof(STxDataHead_g_FB);
}
else if (bRTS == FALSE) { //RTS_needless
pvRrvTime = (PSRrvTime_gCTS) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS));
pvRTS = NULL;
pvCTS = (PSCTS_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR);
pvTxDataHd = (PSTxDataHead_g_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS_FB));
cbHeaderLength = wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS_FB) + sizeof(STxDataHead_g_FB);
}
} // Auto Fall Back
}
else {//802.11a/b packet
if (byFBOption == AUTO_FB_NONE) {
if (bRTS == TRUE) {//RTS_need
pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
pvRTS = (PSRTS_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
pvCTS = NULL;
pvTxDataHd = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR + sizeof(SRTS_ab));
cbHeaderLength = wTxBufSize + sizeof(PSRrvTime_ab) + cbMICHDR + sizeof(SRTS_ab) + sizeof(STxDataHead_ab);
}
else if (bRTS == FALSE) { //RTS_needless, no MICHDR
pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
pvRTS = NULL;
pvCTS = NULL;
pvTxDataHd = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
cbHeaderLength = wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR + sizeof(STxDataHead_ab);
}
} else {
// Auto Fall Back
if (bRTS == TRUE) {//RTS_need
pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
pvRTS = (PSRTS_a_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
pvCTS = NULL;
pvTxDataHd = (PSTxDataHead_a_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR + sizeof(SRTS_a_FB));
cbHeaderLength = wTxBufSize + sizeof(PSRrvTime_ab) + cbMICHDR + sizeof(SRTS_a_FB) + sizeof(STxDataHead_a_FB);
}
else if (bRTS == FALSE) { //RTS_needless
pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
pvRTS = NULL;
pvCTS = NULL;
pvTxDataHd = (PSTxDataHead_a_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
cbHeaderLength = wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR + sizeof(STxDataHead_a_FB);
}
} // Auto Fall Back
}
pbyMacHdr = (PBYTE)(pbyTxBufferAddr + cbHeaderLength);
pbyIVHead = (PBYTE)(pbyMacHdr + cbMACHdLen + uPadding);
pbyPayloadHead = (PBYTE)(pbyMacHdr + cbMACHdLen + uPadding + cbIVlen);
//=========================
// No Fragmentation
//=========================
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"No Fragmentation...\n");
byFragType = FRAGCTL_NONFRAG;
//uDMAIdx = TYPE_AC0DMA;
//pTxBufHead = (PSTxBufHead) &(pTxBufHead->adwTxKey[0]);
//Fill FIFO,RrvTime,RTS,and CTS
s_vGenerateTxParameter(pDevice, byPktType, wCurrentRate, (PVOID)pbyTxBufferAddr, pvRrvTime, pvRTS, pvCTS,
cbFrameSize, bNeedACK, uDMAIdx, psEthHeader);
//Fill DataHead
uDuration = s_uFillDataHead(pDevice, byPktType, wCurrentRate, pvTxDataHd, cbFrameSize, uDMAIdx, bNeedACK,
0, 0, 1/*uMACfragNum*/, byFBOption);
// Generate TX MAC Header
s_vGenerateMACHeader(pDevice, pbyMacHdr, (WORD)uDuration, psEthHeader, bNeedEncryption,
byFragType, uDMAIdx, 0);
if (bNeedEncryption == TRUE) {
//Fill TXKEY
s_vFillTxKey(pDevice, (PBYTE)(pTxBufHead->adwTxKey), pbyIVHead, pTransmitKey,
pbyMacHdr, (WORD)cbFrameBodySize, (PBYTE)pMICHDR);
if (pDevice->bEnableHostWEP) {
pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16 = pTransmitKey->dwTSC47_16;
pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0 = pTransmitKey->wTSC15_0;
}
}
// 802.1H
if (ntohs(psEthHeader->wType) > MAX_DATA_LEN) {
if (pDevice->dwDiagRefCount == 0) {
if ( (psEthHeader->wType == TYPE_PKT_IPX) ||
(psEthHeader->wType == cpu_to_le16(0xF380))) {
memcpy((PBYTE) (pbyPayloadHead), &abySNAP_Bridgetunnel[0], 6);
} else {
memcpy((PBYTE) (pbyPayloadHead), &abySNAP_RFC1042[0], 6);
}
pbyType = (PBYTE) (pbyPayloadHead + 6);
memcpy(pbyType, &(psEthHeader->wType), sizeof(WORD));
} else {
memcpy((PBYTE) (pbyPayloadHead), &(psEthHeader->wType), sizeof(WORD));
}
}
if (pPacket != NULL) {
// Copy the Packet into a tx Buffer
memcpy((pbyPayloadHead + cb802_1_H_len),
(pPacket + U_HEADER_LEN),
uSkbPacketLen - U_HEADER_LEN
);
} else {
// while bRelayPacketSend psEthHeader is point to header+payload
memcpy((pbyPayloadHead + cb802_1_H_len), ((PBYTE)psEthHeader)+U_HEADER_LEN, uSkbPacketLen - U_HEADER_LEN);
}
ASSERT(uLength == cbNdisBodySize);
if ((bNeedEncryption == TRUE) && (pTransmitKey != NULL) && (pTransmitKey->byCipherSuite == KEY_CTL_TKIP)) {
///////////////////////////////////////////////////////////////////
if (pDevice->sMgmtObj.eAuthenMode == WMAC_AUTH_WPANONE) {
dwMICKey0 = *(PDWORD)(&pTransmitKey->abyKey[16]);
dwMICKey1 = *(PDWORD)(&pTransmitKey->abyKey[20]);
}
else if ((pTransmitKey->dwKeyIndex & AUTHENTICATOR_KEY) != 0) {
dwMICKey0 = *(PDWORD)(&pTransmitKey->abyKey[16]);
dwMICKey1 = *(PDWORD)(&pTransmitKey->abyKey[20]);
}
else {
dwMICKey0 = *(PDWORD)(&pTransmitKey->abyKey[24]);
dwMICKey1 = *(PDWORD)(&pTransmitKey->abyKey[28]);
}
// DO Software Michael
MIC_vInit(dwMICKey0, dwMICKey1);
MIC_vAppend((PBYTE)&(psEthHeader->abyDstAddr[0]), 12);
dwMIC_Priority = 0;
MIC_vAppend((PBYTE)&dwMIC_Priority, 4);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIC KEY: %lX, %lX\n", dwMICKey0, dwMICKey1);
///////////////////////////////////////////////////////////////////
//DBG_PRN_GRP12(("Length:%d, %d\n", cbFrameBodySize, uFromHDtoPLDLength));
//for (ii = 0; ii < cbFrameBodySize; ii++) {
// DBG_PRN_GRP12(("%02x ", *((PBYTE)((pbyPayloadHead + cb802_1_H_len) + ii))));
//}
//DBG_PRN_GRP12(("\n\n\n"));
MIC_vAppend(pbyPayloadHead, cbFrameBodySize);
pdwMIC_L = (PDWORD)(pbyPayloadHead + cbFrameBodySize);
pdwMIC_R = (PDWORD)(pbyPayloadHead + cbFrameBodySize + 4);
MIC_vGetMIC(pdwMIC_L, pdwMIC_R);
MIC_vUnInit();
if (pDevice->bTxMICFail == TRUE) {
*pdwMIC_L = 0;
*pdwMIC_R = 0;
pDevice->bTxMICFail = FALSE;
}
//DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"uLength: %d, %d\n", uLength, cbFrameBodySize);
//DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"cbReqCount:%d, %d, %d, %d\n", cbReqCount, cbHeaderLength, uPadding, cbIVlen);
//DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIC:%lX, %lX\n", *pdwMIC_L, *pdwMIC_R);
}
if (bSoftWEP == TRUE) {
s_vSWencryption(pDevice, pTransmitKey, (pbyPayloadHead), (WORD)(cbFrameBodySize + cbMIClen));
} else if ( ((pDevice->eEncryptionStatus == Ndis802_11Encryption1Enabled) && (bNeedEncryption == TRUE)) ||
((pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) && (bNeedEncryption == TRUE)) ||
((pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) && (bNeedEncryption == TRUE)) ) {
cbFrameSize -= cbICVlen;
}
if (pDevice->bSoftwareGenCrcErr == TRUE) {
UINT cbLen;
PDWORD pdwCRC;
dwCRC = 0xFFFFFFFFL;
cbLen = cbFrameSize - cbFCSlen;
// calculate CRC, and wrtie CRC value to end of TD
dwCRC = CRCdwGetCrc32Ex(pbyMacHdr, cbLen, dwCRC);
pdwCRC = (PDWORD)(pbyMacHdr + cbLen);
// finally, we must invert dwCRC to get the correct answer
*pdwCRC = ~dwCRC;
// Force Error
*pdwCRC -= 1;
} else {
cbFrameSize -= cbFCSlen;
}
*pcbHeaderLen = cbHeaderLength;
*pcbTotalLen = cbHeaderLength + cbFrameSize ;
//Set FragCtl in TxBufferHead
pTxBufHead->wFragCtl |= (WORD)byFragType;
return TRUE;
}
/*+
*
* Description:
* Translate 802.3 to 802.11 header
*
* Parameters:
* In:
* pDevice - Pointer to adpater
* dwTxBufferAddr - Transmit Buffer
* pPacket - Packet from upper layer
* cbPacketSize - Transmit Data Length
* Out:
* pcbHeadSize - Header size of MAC&Baseband control and 802.11 Header
* pcbAppendPayload - size of append payload for 802.1H translation
*
* Return Value: none
*
-*/
VOID
s_vGenerateMACHeader (
IN PSDevice pDevice,
IN PBYTE pbyBufferAddr,
IN WORD wDuration,
IN PSEthernetHeader psEthHeader,
IN BOOL bNeedEncrypt,
IN WORD wFragType,
IN UINT uDMAIdx,
IN UINT uFragIdx
)
{
PS802_11Header pMACHeader = (PS802_11Header)pbyBufferAddr;
memset(pMACHeader, 0, (sizeof(S802_11Header))); //- sizeof(pMACHeader->dwIV)));
if (uDMAIdx == TYPE_ATIMDMA) {
pMACHeader->wFrameCtl = TYPE_802_11_ATIM;
} else {
pMACHeader->wFrameCtl = TYPE_802_11_DATA;
}
if (pDevice->eOPMode == OP_MODE_AP) {
memcpy(&(pMACHeader->abyAddr1[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
memcpy(&(pMACHeader->abyAddr2[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
memcpy(&(pMACHeader->abyAddr3[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
pMACHeader->wFrameCtl |= FC_FROMDS;
}
else {
if (pDevice->eOPMode == OP_MODE_ADHOC) {
memcpy(&(pMACHeader->abyAddr1[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
memcpy(&(pMACHeader->abyAddr2[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
memcpy(&(pMACHeader->abyAddr3[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
}
else {
memcpy(&(pMACHeader->abyAddr3[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
memcpy(&(pMACHeader->abyAddr2[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
memcpy(&(pMACHeader->abyAddr1[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
pMACHeader->wFrameCtl |= FC_TODS;
}
}
if (bNeedEncrypt)
pMACHeader->wFrameCtl |= cpu_to_le16((WORD)WLAN_SET_FC_ISWEP(1));
pMACHeader->wDurationID = cpu_to_le16(wDuration);
if (pDevice->bLongHeader) {
PWLAN_80211HDR_A4 pMACA4Header = (PWLAN_80211HDR_A4) pbyBufferAddr;
pMACHeader->wFrameCtl |= (FC_TODS | FC_FROMDS);
memcpy(pMACA4Header->abyAddr4, pDevice->abyBSSID, WLAN_ADDR_LEN);
}
pMACHeader->wSeqCtl = cpu_to_le16(pDevice->wSeqCounter << 4);
//Set FragNumber in Sequence Control
pMACHeader->wSeqCtl |= cpu_to_le16((WORD)uFragIdx);
if ((wFragType == FRAGCTL_ENDFRAG) || (wFragType == FRAGCTL_NONFRAG)) {
pDevice->wSeqCounter++;
if (pDevice->wSeqCounter > 0x0fff)
pDevice->wSeqCounter = 0;
}
if ((wFragType == FRAGCTL_STAFRAG) || (wFragType == FRAGCTL_MIDFRAG)) { //StartFrag or MidFrag
pMACHeader->wFrameCtl |= FC_MOREFRAG;
}
}
/*+
*
* Description:
* Request instructs a MAC to transmit a 802.11 management packet through
* the adapter onto the medium.
*
* Parameters:
* In:
* hDeviceContext - Pointer to the adapter
* pPacket - A pointer to a descriptor for the packet to transmit
* Out:
* none
*
* Return Value: CMD_STATUS_PENDING if MAC Tx resource avaliable; otherwise FALSE
*
-*/
CMD_STATUS csMgmt_xmit(
IN PSDevice pDevice,
IN PSTxMgmtPacket pPacket
)
{
BYTE byPktType;
PBYTE pbyTxBufferAddr;
PVOID pvRTS;
PSCTS pCTS;
PVOID pvTxDataHd;
UINT uDuration;
UINT cbReqCount;
PS802_11Header pMACHeader;
UINT cbHeaderSize;
UINT cbFrameBodySize;
BOOL bNeedACK;
BOOL bIsPSPOLL = FALSE;
PSTxBufHead pTxBufHead;
UINT cbFrameSize;
UINT cbIVlen = 0;
UINT cbICVlen = 0;
UINT cbMIClen = 0;
UINT cbFCSlen = 4;
UINT uPadding = 0;
WORD wTxBufSize;
UINT cbMacHdLen;
SEthernetHeader sEthHeader;
PVOID pvRrvTime;
PVOID pMICHDR;
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
WORD wCurrentRate = RATE_1M;
PTX_BUFFER pTX_Buffer;
PUSB_SEND_CONTEXT pContext;
pContext = (PUSB_SEND_CONTEXT)s_vGetFreeContext(pDevice);
if (NULL == pContext) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ManagementSend TX...NO CONTEXT!\n");
return CMD_STATUS_RESOURCES;
}
pTX_Buffer = (PTX_BUFFER) (&pContext->Data[0]);
pbyTxBufferAddr = (PBYTE)&(pTX_Buffer->adwTxKey[0]);
cbFrameBodySize = pPacket->cbPayloadLen;
pTxBufHead = (PSTxBufHead) pbyTxBufferAddr;
wTxBufSize = sizeof(STxBufHead);
memset(pTxBufHead, 0, wTxBufSize);
if (pDevice->byBBType == BB_TYPE_11A) {
wCurrentRate = RATE_6M;
byPktType = PK_TYPE_11A;
} else {
wCurrentRate = RATE_1M;
byPktType = PK_TYPE_11B;
}
// SetPower will cause error power TX state for OFDM Date packet in TX buffer.
// 2004.11.11 Kyle -- Using OFDM power to tx MngPkt will decrease the connection capability.
// And cmd timer will wait data pkt TX finish before scanning so it's OK
// to set power here.
if (pMgmt->eScanState != WMAC_NO_SCANNING) {
RFbSetPower(pDevice, wCurrentRate, pDevice->byCurrentCh);
} else {
RFbSetPower(pDevice, wCurrentRate, pMgmt->uCurrChannel);
}
pDevice->wCurrentRate = wCurrentRate;
//Set packet type
if (byPktType == PK_TYPE_11A) {//0000 0000 0000 0000
pTxBufHead->wFIFOCtl = 0;
}
else if (byPktType == PK_TYPE_11B) {//0000 0001 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_11B;
}
else if (byPktType == PK_TYPE_11GB) {//0000 0010 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_11GB;
}
else if (byPktType == PK_TYPE_11GA) {//0000 0011 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_11GA;
}
pTxBufHead->wFIFOCtl |= FIFOCTL_TMOEN;
pTxBufHead->wTimeStamp = cpu_to_le16(DEFAULT_MGN_LIFETIME_RES_64us);
if (IS_MULTICAST_ADDRESS(&(pPacket->p80211Header->sA3.abyAddr1[0])) ||
IS_BROADCAST_ADDRESS(&(pPacket->p80211Header->sA3.abyAddr1[0]))) {
bNeedACK = FALSE;
}
else {
bNeedACK = TRUE;
pTxBufHead->wFIFOCtl |= FIFOCTL_NEEDACK;
};
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) ||
(pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) ) {
pTxBufHead->wFIFOCtl |= FIFOCTL_LRETRY;
//Set Preamble type always long
//pDevice->byPreambleType = PREAMBLE_LONG;
// probe-response don't retry
//if ((pPacket->p80211Header->sA4.wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_MGMT_PROBE_RSP) {
// bNeedACK = FALSE;
// pTxBufHead->wFIFOCtl &= (~FIFOCTL_NEEDACK);
//}
}
pTxBufHead->wFIFOCtl |= (FIFOCTL_GENINT | FIFOCTL_ISDMA0);
if ((pPacket->p80211Header->sA4.wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_CTL_PSPOLL) {
bIsPSPOLL = TRUE;
cbMacHdLen = WLAN_HDR_ADDR2_LEN;
} else {
cbMacHdLen = WLAN_HDR_ADDR3_LEN;
}
//Set FRAGCTL_MACHDCNT
pTxBufHead->wFragCtl |= cpu_to_le16((WORD)(cbMacHdLen << 10));
// Notes:
// Although spec says MMPDU can be fragmented; In most case,
// no one will send a MMPDU under fragmentation. With RTS may occur.
pDevice->bAES = FALSE; //Set FRAGCTL_WEPTYP
if (WLAN_GET_FC_ISWEP(pPacket->p80211Header->sA4.wFrameCtl) != 0) {
if (pDevice->eEncryptionStatus == Ndis802_11Encryption1Enabled) {
cbIVlen = 4;
cbICVlen = 4;
pTxBufHead->wFragCtl |= FRAGCTL_LEGACY;
}
else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
cbIVlen = 8;//IV+ExtIV
cbMIClen = 8;
cbICVlen = 4;
pTxBufHead->wFragCtl |= FRAGCTL_TKIP;
//We need to get seed here for filling TxKey entry.
//TKIPvMixKey(pTransmitKey->abyKey, pDevice->abyCurrentNetAddr,
// pTransmitKey->wTSC15_0, pTransmitKey->dwTSC47_16, pDevice->abyPRNG);
}
else if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
cbIVlen = 8;//RSN Header
cbICVlen = 8;//MIC
pTxBufHead->wFragCtl |= FRAGCTL_AES;
pDevice->bAES = TRUE;
}
//MAC Header should be padding 0 to DW alignment.
uPadding = 4 - (cbMacHdLen%4);
uPadding %= 4;
}
cbFrameSize = cbMacHdLen + cbFrameBodySize + cbIVlen + cbMIClen + cbICVlen + cbFCSlen;
//Set FIFOCTL_GrpAckPolicy
if (pDevice->bGrpAckPolicy == TRUE) {//0000 0100 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_GRPACK;
}
//the rest of pTxBufHead->wFragCtl:FragTyp will be set later in s_vFillFragParameter()
//Set RrvTime/RTS/CTS Buffer
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {//802.11g packet
pvRrvTime = (PSRrvTime_gCTS) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = NULL;
pvRTS = NULL;
pCTS = (PSCTS) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS));
pvTxDataHd = (PSTxDataHead_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + sizeof(SCTS));
cbHeaderSize = wTxBufSize + sizeof(SRrvTime_gCTS) + sizeof(SCTS) + sizeof(STxDataHead_g);
}
else { // 802.11a/b packet
pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = NULL;
pvRTS = NULL;
pCTS = NULL;
pvTxDataHd = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
cbHeaderSize = wTxBufSize + sizeof(SRrvTime_ab) + sizeof(STxDataHead_ab);
}
memset((PVOID)(pbyTxBufferAddr + wTxBufSize), 0, (cbHeaderSize - wTxBufSize));
memcpy(&(sEthHeader.abyDstAddr[0]), &(pPacket->p80211Header->sA3.abyAddr1[0]), U_ETHER_ADDR_LEN);
memcpy(&(sEthHeader.abySrcAddr[0]), &(pPacket->p80211Header->sA3.abyAddr2[0]), U_ETHER_ADDR_LEN);
//=========================
// No Fragmentation
//=========================
pTxBufHead->wFragCtl |= (WORD)FRAGCTL_NONFRAG;
//Fill FIFO,RrvTime,RTS,and CTS
s_vGenerateTxParameter(pDevice, byPktType, wCurrentRate, pbyTxBufferAddr, pvRrvTime, pvRTS, pCTS,
cbFrameSize, bNeedACK, TYPE_TXDMA0, &sEthHeader);
//Fill DataHead
uDuration = s_uFillDataHead(pDevice, byPktType, wCurrentRate, pvTxDataHd, cbFrameSize, TYPE_TXDMA0, bNeedACK,
0, 0, 1, AUTO_FB_NONE);
pMACHeader = (PS802_11Header) (pbyTxBufferAddr + cbHeaderSize);
cbReqCount = cbHeaderSize + cbMacHdLen + uPadding + cbIVlen + cbFrameBodySize;
if (WLAN_GET_FC_ISWEP(pPacket->p80211Header->sA4.wFrameCtl) != 0) {
PBYTE pbyIVHead;
PBYTE pbyPayloadHead;
PBYTE pbyBSSID;
PSKeyItem pTransmitKey = NULL;
pbyIVHead = (PBYTE)(pbyTxBufferAddr + cbHeaderSize + cbMacHdLen + uPadding);
pbyPayloadHead = (PBYTE)(pbyTxBufferAddr + cbHeaderSize + cbMacHdLen + uPadding + cbIVlen);
do {
if ((pDevice->eOPMode == OP_MODE_INFRASTRUCTURE) &&
(pDevice->bLinkPass == TRUE)) {
pbyBSSID = pDevice->abyBSSID;
// get pairwise key
if (KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, PAIRWISE_KEY, &pTransmitKey) == FALSE) {
// get group key
if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == TRUE) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Get GTK.\n");
break;
}
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Get PTK.\n");
break;
}
}
// get group key
pbyBSSID = pDevice->abyBroadcastAddr;
if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == FALSE) {
pTransmitKey = NULL;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KEY is NULL. OP Mode[%d]\n", pDevice->eOPMode);
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Get GTK.\n");
}
} while(FALSE);
//Fill TXKEY
s_vFillTxKey(pDevice, (PBYTE)(pTxBufHead->adwTxKey), pbyIVHead, pTransmitKey,
(PBYTE)pMACHeader, (WORD)cbFrameBodySize, NULL);
memcpy(pMACHeader, pPacket->p80211Header, cbMacHdLen);
memcpy(pbyPayloadHead, ((PBYTE)(pPacket->p80211Header) + cbMacHdLen),
cbFrameBodySize);
}
else {
// Copy the Packet into a tx Buffer
memcpy(pMACHeader, pPacket->p80211Header, pPacket->cbMPDULen);
}
pMACHeader->wSeqCtl = cpu_to_le16(pDevice->wSeqCounter << 4);
pDevice->wSeqCounter++ ;
if (pDevice->wSeqCounter > 0x0fff)
pDevice->wSeqCounter = 0;
if (bIsPSPOLL) {
// The MAC will automatically replace the Duration-field of MAC header by Duration-field
// of FIFO control header.
// This will cause AID-field of PS-POLL packet be incorrect (Because PS-POLL's AID field is
// in the same place of other packet's Duration-field).
// And it will cause Cisco-AP to issue Disassociation-packet
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {
((PSTxDataHead_g)pvTxDataHd)->wDuration_a = cpu_to_le16(pPacket->p80211Header->sA2.wDurationID);
((PSTxDataHead_g)pvTxDataHd)->wDuration_b = cpu_to_le16(pPacket->p80211Header->sA2.wDurationID);
} else {
((PSTxDataHead_ab)pvTxDataHd)->wDuration = cpu_to_le16(pPacket->p80211Header->sA2.wDurationID);
}
}
pTX_Buffer->wTxByteCount = cpu_to_le16((WORD)(cbReqCount));
pTX_Buffer->byPKTNO = (BYTE) (((wCurrentRate<<4) &0x00F0) | ((pDevice->wSeqCounter - 1) & 0x000F));
pTX_Buffer->byType = 0x00;
pContext->pPacket = NULL;
pContext->Type = CONTEXT_MGMT_PACKET;
pContext->uBufLen = (WORD)cbReqCount + 4; //USB header
if (WLAN_GET_FC_TODS(pMACHeader->wFrameCtl) == 0) {
s_vSaveTxPktInfo(pDevice, (BYTE) (pTX_Buffer->byPKTNO & 0x0F), &(pMACHeader->abyAddr1[0]),(WORD)cbFrameSize,pTX_Buffer->wFIFOCtl);
}
else {
s_vSaveTxPktInfo(pDevice, (BYTE) (pTX_Buffer->byPKTNO & 0x0F), &(pMACHeader->abyAddr3[0]),(WORD)cbFrameSize,pTX_Buffer->wFIFOCtl);
}
PIPEnsSendBulkOut(pDevice,pContext);
return CMD_STATUS_PENDING;
}
CMD_STATUS
csBeacon_xmit(
IN PSDevice pDevice,
IN PSTxMgmtPacket pPacket
)
{
UINT cbFrameSize = pPacket->cbMPDULen + WLAN_FCS_LEN;
UINT cbHeaderSize = 0;
WORD wTxBufSize = sizeof(STxShortBufHead);
PSTxShortBufHead pTxBufHead;
PS802_11Header pMACHeader;
PSTxDataHead_ab pTxDataHead;
WORD wCurrentRate;
UINT cbFrameBodySize;
UINT cbReqCount;
PBEACON_BUFFER pTX_Buffer;
PBYTE pbyTxBufferAddr;
PUSB_SEND_CONTEXT pContext;
CMD_STATUS status;
pContext = (PUSB_SEND_CONTEXT)s_vGetFreeContext(pDevice);
if (NULL == pContext) {
status = CMD_STATUS_RESOURCES;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ManagementSend TX...NO CONTEXT!\n");
return status ;
}
pTX_Buffer = (PBEACON_BUFFER) (&pContext->Data[0]);
pbyTxBufferAddr = (PBYTE)&(pTX_Buffer->wFIFOCtl);
cbFrameBodySize = pPacket->cbPayloadLen;
pTxBufHead = (PSTxShortBufHead) pbyTxBufferAddr;
wTxBufSize = sizeof(STxShortBufHead);
memset(pTxBufHead, 0, wTxBufSize);
if (pDevice->byBBType == BB_TYPE_11A) {
wCurrentRate = RATE_6M;
pTxDataHead = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize);
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, cbFrameSize, wCurrentRate, PK_TYPE_11A,
(PWORD)&(pTxDataHead->wTransmitLength), (PBYTE)&(pTxDataHead->byServiceField), (PBYTE)&(pTxDataHead->bySignalField)
);
//Get Duration and TimeStampOff
pTxDataHead->wDuration = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameSize, PK_TYPE_11A,
wCurrentRate, FALSE, 0, 0, 1, AUTO_FB_NONE));
pTxDataHead->wTimeStampOff = wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE];
cbHeaderSize = wTxBufSize + sizeof(STxDataHead_ab);
} else {
wCurrentRate = RATE_1M;
pTxBufHead->wFIFOCtl |= FIFOCTL_11B;
pTxDataHead = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize);
//Get SignalField,ServiceField,Length
BBvCaculateParameter(pDevice, cbFrameSize, wCurrentRate, PK_TYPE_11B,
(PWORD)&(pTxDataHead->wTransmitLength), (PBYTE)&(pTxDataHead->byServiceField), (PBYTE)&(pTxDataHead->bySignalField)
);
//Get Duration and TimeStampOff
pTxDataHead->wDuration = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_B, cbFrameSize, PK_TYPE_11B,
wCurrentRate, FALSE, 0, 0, 1, AUTO_FB_NONE));
pTxDataHead->wTimeStampOff = wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE];
cbHeaderSize = wTxBufSize + sizeof(STxDataHead_ab);
}
//Generate Beacon Header
pMACHeader = (PS802_11Header)(pbyTxBufferAddr + cbHeaderSize);
memcpy(pMACHeader, pPacket->p80211Header, pPacket->cbMPDULen);
pMACHeader->wDurationID = 0;
pMACHeader->wSeqCtl = cpu_to_le16(pDevice->wSeqCounter << 4);
pDevice->wSeqCounter++ ;
if (pDevice->wSeqCounter > 0x0fff)
pDevice->wSeqCounter = 0;
cbReqCount = cbHeaderSize + WLAN_HDR_ADDR3_LEN + cbFrameBodySize;
pTX_Buffer->wTxByteCount = (WORD)cbReqCount;
pTX_Buffer->byPKTNO = (BYTE) (((wCurrentRate<<4) &0x00F0) | ((pDevice->wSeqCounter - 1) & 0x000F));
pTX_Buffer->byType = 0x01;
pContext->pPacket = NULL;
pContext->Type = CONTEXT_MGMT_PACKET;
pContext->uBufLen = (WORD)cbReqCount + 4; //USB header
PIPEnsSendBulkOut(pDevice,pContext);
return CMD_STATUS_PENDING;
}
VOID
vDMA0_tx_80211(PSDevice pDevice, struct sk_buff *skb) {
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
BYTE byPktType;
PBYTE pbyTxBufferAddr;
PVOID pvRTS;
PVOID pvCTS;
PVOID pvTxDataHd;
UINT uDuration;
UINT cbReqCount;
PS802_11Header pMACHeader;
UINT cbHeaderSize;
UINT cbFrameBodySize;
BOOL bNeedACK;
BOOL bIsPSPOLL = FALSE;
PSTxBufHead pTxBufHead;
UINT cbFrameSize;
UINT cbIVlen = 0;
UINT cbICVlen = 0;
UINT cbMIClen = 0;
UINT cbFCSlen = 4;
UINT uPadding = 0;
UINT cbMICHDR = 0;
UINT uLength = 0;
DWORD dwMICKey0, dwMICKey1;
DWORD dwMIC_Priority;
PDWORD pdwMIC_L;
PDWORD pdwMIC_R;
WORD wTxBufSize;
UINT cbMacHdLen;
SEthernetHeader sEthHeader;
PVOID pvRrvTime;
PVOID pMICHDR;
WORD wCurrentRate = RATE_1M;
PUWLAN_80211HDR p80211Header;
UINT uNodeIndex = 0;
BOOL bNodeExist = FALSE;
SKeyItem STempKey;
PSKeyItem pTransmitKey = NULL;
PBYTE pbyIVHead;
PBYTE pbyPayloadHead;
PBYTE pbyMacHdr;
UINT cbExtSuppRate = 0;
PTX_BUFFER pTX_Buffer;
PUSB_SEND_CONTEXT pContext;
// PWLAN_IE pItem;
pvRrvTime = pMICHDR = pvRTS = pvCTS = pvTxDataHd = NULL;
if(skb->len <= WLAN_HDR_ADDR3_LEN) {
cbFrameBodySize = 0;
}
else {
cbFrameBodySize = skb->len - WLAN_HDR_ADDR3_LEN;
}
p80211Header = (PUWLAN_80211HDR)skb->data;
pContext = (PUSB_SEND_CONTEXT)s_vGetFreeContext(pDevice);
if (NULL == pContext) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"DMA0 TX...NO CONTEXT!\n");
dev_kfree_skb_irq(skb);
return ;
}
pTX_Buffer = (PTX_BUFFER)(&pContext->Data[0]);
pbyTxBufferAddr = (PBYTE)(&pTX_Buffer->adwTxKey[0]);
pTxBufHead = (PSTxBufHead) pbyTxBufferAddr;
wTxBufSize = sizeof(STxBufHead);
memset(pTxBufHead, 0, wTxBufSize);
if (pDevice->byBBType == BB_TYPE_11A) {
wCurrentRate = RATE_6M;
byPktType = PK_TYPE_11A;
} else {
wCurrentRate = RATE_1M;
byPktType = PK_TYPE_11B;
}
// SetPower will cause error power TX state for OFDM Date packet in TX buffer.
// 2004.11.11 Kyle -- Using OFDM power to tx MngPkt will decrease the connection capability.
// And cmd timer will wait data pkt TX finish before scanning so it's OK
// to set power here.
if (pMgmt->eScanState != WMAC_NO_SCANNING) {
RFbSetPower(pDevice, wCurrentRate, pDevice->byCurrentCh);
} else {
RFbSetPower(pDevice, wCurrentRate, pMgmt->uCurrChannel);
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"vDMA0_tx_80211: p80211Header->sA3.wFrameCtl = %x \n", p80211Header->sA3.wFrameCtl);
//Set packet type
if (byPktType == PK_TYPE_11A) {//0000 0000 0000 0000
pTxBufHead->wFIFOCtl = 0;
}
else if (byPktType == PK_TYPE_11B) {//0000 0001 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_11B;
}
else if (byPktType == PK_TYPE_11GB) {//0000 0010 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_11GB;
}
else if (byPktType == PK_TYPE_11GA) {//0000 0011 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_11GA;
}
pTxBufHead->wFIFOCtl |= FIFOCTL_TMOEN;
pTxBufHead->wTimeStamp = cpu_to_le16(DEFAULT_MGN_LIFETIME_RES_64us);
if (IS_MULTICAST_ADDRESS(&(p80211Header->sA3.abyAddr1[0])) ||
IS_BROADCAST_ADDRESS(&(p80211Header->sA3.abyAddr1[0]))) {
bNeedACK = FALSE;
if (pDevice->bEnableHostWEP) {
uNodeIndex = 0;
bNodeExist = TRUE;
};
}
else {
if (pDevice->bEnableHostWEP) {
if (BSSbIsSTAInNodeDB(pDevice, (PBYTE)(p80211Header->sA3.abyAddr1), &uNodeIndex))
bNodeExist = TRUE;
};
bNeedACK = TRUE;
pTxBufHead->wFIFOCtl |= FIFOCTL_NEEDACK;
};
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) ||
(pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) ) {
pTxBufHead->wFIFOCtl |= FIFOCTL_LRETRY;
//Set Preamble type always long
//pDevice->byPreambleType = PREAMBLE_LONG;
// probe-response don't retry
//if ((p80211Header->sA4.wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_MGMT_PROBE_RSP) {
// bNeedACK = FALSE;
// pTxBufHead->wFIFOCtl &= (~FIFOCTL_NEEDACK);
//}
}
pTxBufHead->wFIFOCtl |= (FIFOCTL_GENINT | FIFOCTL_ISDMA0);
if ((p80211Header->sA4.wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_CTL_PSPOLL) {
bIsPSPOLL = TRUE;
cbMacHdLen = WLAN_HDR_ADDR2_LEN;
} else {
cbMacHdLen = WLAN_HDR_ADDR3_LEN;
}
// hostapd deamon ext support rate patch
if (WLAN_GET_FC_FSTYPE(p80211Header->sA4.wFrameCtl) == WLAN_FSTYPE_ASSOCRESP) {
if (((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len != 0) {
cbExtSuppRate += ((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len + WLAN_IEHDR_LEN;
}
if (((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates)->len != 0) {
cbExtSuppRate += ((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates)->len + WLAN_IEHDR_LEN;
}
if (cbExtSuppRate >0) {
cbFrameBodySize = WLAN_ASSOCRESP_OFF_SUPP_RATES;
}
}
//Set FRAGCTL_MACHDCNT
pTxBufHead->wFragCtl |= cpu_to_le16((WORD)cbMacHdLen << 10);
// Notes:
// Although spec says MMPDU can be fragmented; In most case,
// no one will send a MMPDU under fragmentation. With RTS may occur.
pDevice->bAES = FALSE; //Set FRAGCTL_WEPTYP
if (WLAN_GET_FC_ISWEP(p80211Header->sA4.wFrameCtl) != 0) {
if (pDevice->eEncryptionStatus == Ndis802_11Encryption1Enabled) {
cbIVlen = 4;
cbICVlen = 4;
pTxBufHead->wFragCtl |= FRAGCTL_LEGACY;
}
else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
cbIVlen = 8;//IV+ExtIV
cbMIClen = 8;
cbICVlen = 4;
pTxBufHead->wFragCtl |= FRAGCTL_TKIP;
//We need to get seed here for filling TxKey entry.
//TKIPvMixKey(pTransmitKey->abyKey, pDevice->abyCurrentNetAddr,
// pTransmitKey->wTSC15_0, pTransmitKey->dwTSC47_16, pDevice->abyPRNG);
}
else if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
cbIVlen = 8;//RSN Header
cbICVlen = 8;//MIC
cbMICHDR = sizeof(SMICHDRHead);
pTxBufHead->wFragCtl |= FRAGCTL_AES;
pDevice->bAES = TRUE;
}
//MAC Header should be padding 0 to DW alignment.
uPadding = 4 - (cbMacHdLen%4);
uPadding %= 4;
}
cbFrameSize = cbMacHdLen + cbFrameBodySize + cbIVlen + cbMIClen + cbICVlen + cbFCSlen + cbExtSuppRate;
//Set FIFOCTL_GrpAckPolicy
if (pDevice->bGrpAckPolicy == TRUE) {//0000 0100 0000 0000
pTxBufHead->wFIFOCtl |= FIFOCTL_GRPACK;
}
//the rest of pTxBufHead->wFragCtl:FragTyp will be set later in s_vFillFragParameter()
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {//802.11g packet
pvRrvTime = (PSRrvTime_gCTS) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS));
pvRTS = NULL;
pvCTS = (PSCTS) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR);
pvTxDataHd = (PSTxDataHead_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS));
cbHeaderSize = wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS) + sizeof(STxDataHead_g);
}
else {//802.11a/b packet
pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
pvRTS = NULL;
pvCTS = NULL;
pvTxDataHd = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
cbHeaderSize = wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR + sizeof(STxDataHead_ab);
}
memset((PVOID)(pbyTxBufferAddr + wTxBufSize), 0, (cbHeaderSize - wTxBufSize));
memcpy(&(sEthHeader.abyDstAddr[0]), &(p80211Header->sA3.abyAddr1[0]), U_ETHER_ADDR_LEN);
memcpy(&(sEthHeader.abySrcAddr[0]), &(p80211Header->sA3.abyAddr2[0]), U_ETHER_ADDR_LEN);
//=========================
// No Fragmentation
//=========================
pTxBufHead->wFragCtl |= (WORD)FRAGCTL_NONFRAG;
//Fill FIFO,RrvTime,RTS,and CTS
s_vGenerateTxParameter(pDevice, byPktType, wCurrentRate, pbyTxBufferAddr, pvRrvTime, pvRTS, pvCTS,
cbFrameSize, bNeedACK, TYPE_TXDMA0, &sEthHeader);
//Fill DataHead
uDuration = s_uFillDataHead(pDevice, byPktType, wCurrentRate, pvTxDataHd, cbFrameSize, TYPE_TXDMA0, bNeedACK,
0, 0, 1, AUTO_FB_NONE);
pMACHeader = (PS802_11Header) (pbyTxBufferAddr + cbHeaderSize);
cbReqCount = cbHeaderSize + cbMacHdLen + uPadding + cbIVlen + (cbFrameBodySize + cbMIClen) + cbExtSuppRate;
pbyMacHdr = (PBYTE)(pbyTxBufferAddr + cbHeaderSize);
pbyPayloadHead = (PBYTE)(pbyMacHdr + cbMacHdLen + uPadding + cbIVlen);
pbyIVHead = (PBYTE)(pbyMacHdr + cbMacHdLen + uPadding);
// Copy the Packet into a tx Buffer
memcpy(pbyMacHdr, skb->data, cbMacHdLen);
// version set to 0, patch for hostapd deamon
pMACHeader->wFrameCtl &= cpu_to_le16(0xfffc);
memcpy(pbyPayloadHead, (skb->data + cbMacHdLen), cbFrameBodySize);
// replace support rate, patch for hostapd deamon( only support 11M)
if (WLAN_GET_FC_FSTYPE(p80211Header->sA4.wFrameCtl) == WLAN_FSTYPE_ASSOCRESP) {
if (cbExtSuppRate != 0) {
if (((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len != 0)
memcpy((pbyPayloadHead + cbFrameBodySize),
pMgmt->abyCurrSuppRates,
((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len + WLAN_IEHDR_LEN
);
if (((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates)->len != 0)
memcpy((pbyPayloadHead + cbFrameBodySize) + ((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len + WLAN_IEHDR_LEN,
pMgmt->abyCurrExtSuppRates,
((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates)->len + WLAN_IEHDR_LEN
);
}
}
// Set wep
if (WLAN_GET_FC_ISWEP(p80211Header->sA4.wFrameCtl) != 0) {
if (pDevice->bEnableHostWEP) {
pTransmitKey = &STempKey;
pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
memcpy(pTransmitKey->abyKey,
&pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
pTransmitKey->uKeyLength
);
}
if ((pTransmitKey != NULL) && (pTransmitKey->byCipherSuite == KEY_CTL_TKIP)) {
dwMICKey0 = *(PDWORD)(&pTransmitKey->abyKey[16]);
dwMICKey1 = *(PDWORD)(&pTransmitKey->abyKey[20]);
// DO Software Michael
MIC_vInit(dwMICKey0, dwMICKey1);
MIC_vAppend((PBYTE)&(sEthHeader.abyDstAddr[0]), 12);
dwMIC_Priority = 0;
MIC_vAppend((PBYTE)&dwMIC_Priority, 4);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"DMA0_tx_8021:MIC KEY: %lX, %lX\n", dwMICKey0, dwMICKey1);
uLength = cbHeaderSize + cbMacHdLen + uPadding + cbIVlen;
MIC_vAppend((pbyTxBufferAddr + uLength), cbFrameBodySize);
pdwMIC_L = (PDWORD)(pbyTxBufferAddr + uLength + cbFrameBodySize);
pdwMIC_R = (PDWORD)(pbyTxBufferAddr + uLength + cbFrameBodySize + 4);
MIC_vGetMIC(pdwMIC_L, pdwMIC_R);
MIC_vUnInit();
if (pDevice->bTxMICFail == TRUE) {
*pdwMIC_L = 0;
*pdwMIC_R = 0;
pDevice->bTxMICFail = FALSE;
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"uLength: %d, %d\n", uLength, cbFrameBodySize);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"cbReqCount:%d, %d, %d, %d\n", cbReqCount, cbHeaderSize, uPadding, cbIVlen);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIC:%lx, %lx\n", *pdwMIC_L, *pdwMIC_R);
}
s_vFillTxKey(pDevice, (PBYTE)(pTxBufHead->adwTxKey), pbyIVHead, pTransmitKey,
pbyMacHdr, (WORD)cbFrameBodySize, (PBYTE)pMICHDR);
if (pDevice->bEnableHostWEP) {
pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16 = pTransmitKey->dwTSC47_16;
pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0 = pTransmitKey->wTSC15_0;
}
if ((pDevice->byLocalID <= REV_ID_VT3253_A1)) {
s_vSWencryption(pDevice, pTransmitKey, pbyPayloadHead, (WORD)(cbFrameBodySize + cbMIClen));
}
}
pMACHeader->wSeqCtl = cpu_to_le16(pDevice->wSeqCounter << 4);
pDevice->wSeqCounter++ ;
if (pDevice->wSeqCounter > 0x0fff)
pDevice->wSeqCounter = 0;
if (bIsPSPOLL) {
// The MAC will automatically replace the Duration-field of MAC header by Duration-field
// of FIFO control header.
// This will cause AID-field of PS-POLL packet be incorrect (Because PS-POLL's AID field is
// in the same place of other packet's Duration-field).
// And it will cause Cisco-AP to issue Disassociation-packet
if (byPktType == PK_TYPE_11GB || byPktType == PK_TYPE_11GA) {
((PSTxDataHead_g)pvTxDataHd)->wDuration_a = cpu_to_le16(p80211Header->sA2.wDurationID);
((PSTxDataHead_g)pvTxDataHd)->wDuration_b = cpu_to_le16(p80211Header->sA2.wDurationID);
} else {
((PSTxDataHead_ab)pvTxDataHd)->wDuration = cpu_to_le16(p80211Header->sA2.wDurationID);
}
}
pTX_Buffer->wTxByteCount = cpu_to_le16((WORD)(cbReqCount));
pTX_Buffer->byPKTNO = (BYTE) (((wCurrentRate<<4) &0x00F0) | ((pDevice->wSeqCounter - 1) & 0x000F));
pTX_Buffer->byType = 0x00;
pContext->pPacket = skb;
pContext->Type = CONTEXT_MGMT_PACKET;
pContext->uBufLen = (WORD)cbReqCount + 4; //USB header
if (WLAN_GET_FC_TODS(pMACHeader->wFrameCtl) == 0) {
s_vSaveTxPktInfo(pDevice, (BYTE) (pTX_Buffer->byPKTNO & 0x0F), &(pMACHeader->abyAddr1[0]),(WORD)cbFrameSize,pTX_Buffer->wFIFOCtl);
}
else {
s_vSaveTxPktInfo(pDevice, (BYTE) (pTX_Buffer->byPKTNO & 0x0F), &(pMACHeader->abyAddr3[0]),(WORD)cbFrameSize,pTX_Buffer->wFIFOCtl);
}
PIPEnsSendBulkOut(pDevice,pContext);
return ;
}
//TYPE_AC0DMA data tx
/*
* Description:
* Tx packet via AC0DMA(DMA1)
*
* Parameters:
* In:
* pDevice - Pointer to the adapter
* skb - Pointer to tx skb packet
* Out:
* void
*
* Return Value: NULL
*/
NTSTATUS
nsDMA_tx_packet(
IN PSDevice pDevice,
IN UINT uDMAIdx,
IN struct sk_buff *skb
)
{
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
UINT BytesToWrite =0,uHeaderLen = 0;
UINT uNodeIndex = 0;
BYTE byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
WORD wAID;
BYTE byPktType;
BOOL bNeedEncryption = FALSE;
PSKeyItem pTransmitKey = NULL;
SKeyItem STempKey;
UINT ii;
BOOL bTKIP_UseGTK = FALSE;
BOOL bNeedDeAuth = FALSE;
PBYTE pbyBSSID;
BOOL bNodeExist = FALSE;
PUSB_SEND_CONTEXT pContext;
BOOL fConvertedPacket;
PTX_BUFFER pTX_Buffer;
UINT status;
WORD wKeepRate = pDevice->wCurrentRate;
struct net_device_stats* pStats = &pDevice->stats;
//#ifdef WPA_SM_Transtatus
// extern SWPAResult wpa_Result;
//#endif
BOOL bTxeapol_key = FALSE;
if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
if (pDevice->uAssocCount == 0) {
dev_kfree_skb_irq(skb);
return 0;
}
if (IS_MULTICAST_ADDRESS((PBYTE)(skb->data))) {
uNodeIndex = 0;
bNodeExist = TRUE;
if (pMgmt->sNodeDBTable[0].bPSEnable) {
skb_queue_tail(&(pMgmt->sNodeDBTable[0].sTxPSQueue), skb);
pMgmt->sNodeDBTable[0].wEnQueueCnt++;
// set tx map
pMgmt->abyPSTxMap[0] |= byMask[0];
return 0;
}
// muticast/broadcast data rate
if (pDevice->byBBType != BB_TYPE_11A)
pDevice->wCurrentRate = RATE_2M;
else
pDevice->wCurrentRate = RATE_24M;
// long preamble type
pDevice->byPreambleType = PREAMBLE_SHORT;
}else {
if (BSSbIsSTAInNodeDB(pDevice, (PBYTE)(skb->data), &uNodeIndex)) {
if (pMgmt->sNodeDBTable[uNodeIndex].bPSEnable) {
skb_queue_tail(&pMgmt->sNodeDBTable[uNodeIndex].sTxPSQueue, skb);
pMgmt->sNodeDBTable[uNodeIndex].wEnQueueCnt++;
// set tx map
wAID = pMgmt->sNodeDBTable[uNodeIndex].wAID;
pMgmt->abyPSTxMap[wAID >> 3] |= byMask[wAID & 7];
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set:pMgmt->abyPSTxMap[%d]= %d\n",
(wAID >> 3), pMgmt->abyPSTxMap[wAID >> 3]);
return 0;
}
// AP rate decided from node
pDevice->wCurrentRate = pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate;
// tx preamble decided from node
if (pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble) {
pDevice->byPreambleType = pDevice->byShortPreamble;
}else {
pDevice->byPreambleType = PREAMBLE_LONG;
}
bNodeExist = TRUE;
}
}
if (bNodeExist == FALSE) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Unknown STA not found in node DB \n");
dev_kfree_skb_irq(skb);
return 0;
}
}
pContext = (PUSB_SEND_CONTEXT)s_vGetFreeContext(pDevice);
if (pContext == NULL) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG" pContext == NULL\n");
dev_kfree_skb_irq(skb);
return STATUS_RESOURCES;
}
memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)(skb->data), U_HEADER_LEN);
//mike add:station mode check eapol-key challenge--->
{
BYTE Protocol_Version; //802.1x Authentication
BYTE Packet_Type; //802.1x Authentication
BYTE Descriptor_type;
WORD Key_info;
Protocol_Version = skb->data[U_HEADER_LEN];
Packet_Type = skb->data[U_HEADER_LEN+1];
Descriptor_type = skb->data[U_HEADER_LEN+1+1+2];
Key_info = (skb->data[U_HEADER_LEN+1+1+2+1] << 8)|(skb->data[U_HEADER_LEN+1+1+2+2]);
if (pDevice->sTxEthHeader.wType == TYPE_PKT_802_1x) {
if(((Protocol_Version==1) ||(Protocol_Version==2)) &&
(Packet_Type==3)) { //802.1x OR eapol-key challenge frame transfer
bTxeapol_key = TRUE;
if(!(Key_info & BIT3) && //WPA or RSN group-key challenge
(Key_info & BIT8) && (Key_info & BIT9)) { //send 2/2 key
if(Descriptor_type==254) {
pDevice->fWPA_Authened = TRUE;
PRINT_K("WPA ");
}
else {
pDevice->fWPA_Authened = TRUE;
PRINT_K("WPA2(re-keying) ");
}
PRINT_K("Authentication completed!!\n");
}
else if((Key_info & BIT3) && (Descriptor_type==2) && //RSN pairse-key challenge
(Key_info & BIT8) && (Key_info & BIT9)) {
pDevice->fWPA_Authened = TRUE;
PRINT_K("WPA2 Authentication completed!!\n");
}
}
}
}
//mike add:station mode check eapol-key challenge<---
if (pDevice->bEncryptionEnable == TRUE) {
bNeedEncryption = TRUE;
// get Transmit key
do {
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
(pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
pbyBSSID = pDevice->abyBSSID;
// get pairwise key
if (KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, PAIRWISE_KEY, &pTransmitKey) == FALSE) {
// get group key
if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == TRUE) {
bTKIP_UseGTK = TRUE;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get GTK.\n");
break;
}
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get PTK.\n");
break;
}
}else if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
pbyBSSID = pDevice->sTxEthHeader.abyDstAddr; //TO_DS = 0 and FROM_DS = 0 --> 802.11 MAC Address1
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"IBSS Serach Key: \n");
for (ii = 0; ii< 6; ii++)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"%x \n", *(pbyBSSID+ii));
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"\n");
// get pairwise key
if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, PAIRWISE_KEY, &pTransmitKey) == TRUE)
break;
}
// get group key
pbyBSSID = pDevice->abyBroadcastAddr;
if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == FALSE) {
pTransmitKey = NULL;
if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"IBSS and KEY is NULL. [%d]\n", pMgmt->eCurrMode);
}
else
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"NOT IBSS and KEY is NULL. [%d]\n", pMgmt->eCurrMode);
} else {
bTKIP_UseGTK = TRUE;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get GTK.\n");
}
} while(FALSE);
}
if (pDevice->bEnableHostWEP) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"acdma0: STA index %d\n", uNodeIndex);
if (pDevice->bEncryptionEnable == TRUE) {
pTransmitKey = &STempKey;
pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
memcpy(pTransmitKey->abyKey,
&pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
pTransmitKey->uKeyLength
);
}
}
byPktType = (BYTE)pDevice->byPacketType;
if (pDevice->bFixRate) {
if (pDevice->byBBType == BB_TYPE_11B) {
if (pDevice->uConnectionRate >= RATE_11M) {
pDevice->wCurrentRate = RATE_11M;
} else {
pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
}
} else {
if ((pDevice->byBBType == BB_TYPE_11A) &&
(pDevice->uConnectionRate <= RATE_6M)) {
pDevice->wCurrentRate = RATE_6M;
} else {
if (pDevice->uConnectionRate >= RATE_54M)
pDevice->wCurrentRate = RATE_54M;
else
pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
}
}
}
else {
if (pDevice->eOPMode == OP_MODE_ADHOC) {
// Adhoc Tx rate decided from node DB
if (IS_MULTICAST_ADDRESS(&(pDevice->sTxEthHeader.abyDstAddr[0]))) {
// Multicast use highest data rate
pDevice->wCurrentRate = pMgmt->sNodeDBTable[0].wTxDataRate;
// preamble type
pDevice->byPreambleType = pDevice->byShortPreamble;
}
else {
if(BSSbIsSTAInNodeDB(pDevice, &(pDevice->sTxEthHeader.abyDstAddr[0]), &uNodeIndex)) {
pDevice->wCurrentRate = pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate;
if (pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble) {
pDevice->byPreambleType = pDevice->byShortPreamble;
}
else {
pDevice->byPreambleType = PREAMBLE_LONG;
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Found Node Index is [%d] Tx Data Rate:[%d]\n",uNodeIndex, pDevice->wCurrentRate);
}
else {
if (pDevice->byBBType != BB_TYPE_11A)
pDevice->wCurrentRate = RATE_2M;
else
pDevice->wCurrentRate = RATE_24M; // refer to vMgrCreateOwnIBSS()'s
// abyCurrExtSuppRates[]
pDevice->byPreambleType = PREAMBLE_SHORT;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Not Found Node use highest basic Rate.....\n");
}
}
}
if (pDevice->eOPMode == OP_MODE_INFRASTRUCTURE) {
// Infra STA rate decided from AP Node, index = 0
pDevice->wCurrentRate = pMgmt->sNodeDBTable[0].wTxDataRate;
}
}
if (pDevice->sTxEthHeader.wType == TYPE_PKT_802_1x) {
if (pDevice->byBBType != BB_TYPE_11A) {
pDevice->wCurrentRate = RATE_1M;
pDevice->byACKRate = RATE_1M;
pDevice->byTopCCKBasicRate = RATE_1M;
pDevice->byTopOFDMBasicRate = RATE_6M;
} else {
pDevice->wCurrentRate = RATE_6M;
pDevice->byACKRate = RATE_6M;
pDevice->byTopCCKBasicRate = RATE_1M;
pDevice->byTopOFDMBasicRate = RATE_6M;
}
}
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dma_tx: pDevice->wCurrentRate = %d \n", pDevice->wCurrentRate);
if (wKeepRate != pDevice->wCurrentRate) {
bScheduleCommand((HANDLE)pDevice, WLAN_CMD_SETPOWER, NULL);
}
if (pDevice->wCurrentRate <= RATE_11M) {
byPktType = PK_TYPE_11B;
}
if (bNeedEncryption == TRUE) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ntohs Pkt Type=%04x\n", ntohs(pDevice->sTxEthHeader.wType));
if ((pDevice->sTxEthHeader.wType) == TYPE_PKT_802_1x) {
bNeedEncryption = FALSE;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Pkt Type=%04x\n", (pDevice->sTxEthHeader.wType));
if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) && (pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
if (pTransmitKey == NULL) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Don't Find TX KEY\n");
}
else {
if (bTKIP_UseGTK == TRUE) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"error: KEY is GTK!!~~\n");
}
else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Find PTK [%lX]\n", pTransmitKey->dwKeyIndex);
bNeedEncryption = TRUE;
}
}
}
if (pDevice->byCntMeasure == 2) {
bNeedDeAuth = TRUE;
pDevice->s802_11Counter.TKIPCounterMeasuresInvoked++;
}
if (pDevice->bEnableHostWEP) {
if ((uNodeIndex != 0) &&
(pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex & PAIRWISE_KEY)) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Find PTK [%lX]\n", pTransmitKey->dwKeyIndex);
bNeedEncryption = TRUE;
}
}
}
else {
#if 0
if((pDevice->fWPA_Authened == FALSE) &&
((pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK)||(pMgmt->eAuthenMode = WMAC_AUTH_WPA2PSK))){
dev_kfree_skb_irq(skb);
pStats->tx_dropped++;
return STATUS_FAILURE;
}
else if (pTransmitKey == NULL) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"return no tx key\n");
dev_kfree_skb_irq(skb);
pStats->tx_dropped++;
return STATUS_FAILURE;
}
#else
if (pTransmitKey == NULL) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"return no tx key\n");
dev_kfree_skb_irq(skb);
pStats->tx_dropped++;
return STATUS_FAILURE;
}
#endif
}
}
fConvertedPacket = s_bPacketToWirelessUsb(pDevice, byPktType,
(PBYTE)(&pContext->Data[0]), bNeedEncryption,
skb->len, uDMAIdx, &pDevice->sTxEthHeader,
(PBYTE)skb->data, pTransmitKey, uNodeIndex,
pDevice->wCurrentRate,
&uHeaderLen, &BytesToWrite
);
if (fConvertedPacket == FALSE) {
pContext->bBoolInUse = FALSE;
dev_kfree_skb_irq(skb);
return STATUS_FAILURE;
}
if ( pDevice->bEnablePSMode == TRUE ) {
if ( !pDevice->bPSModeTxBurst ) {
bScheduleCommand((HANDLE) pDevice, WLAN_CMD_MAC_DISPOWERSAVING, NULL);
pDevice->bPSModeTxBurst = TRUE;
}
}
pTX_Buffer = (PTX_BUFFER)&(pContext->Data[0]);
pTX_Buffer->byPKTNO = (BYTE) (((pDevice->wCurrentRate<<4) &0x00F0) | ((pDevice->wSeqCounter - 1) & 0x000F));
pTX_Buffer->wTxByteCount = (WORD)BytesToWrite;
pContext->pPacket = skb;
pContext->Type = CONTEXT_DATA_PACKET;
pContext->uBufLen = (WORD)BytesToWrite + 4 ; //USB header
s_vSaveTxPktInfo(pDevice, (BYTE) (pTX_Buffer->byPKTNO & 0x0F), &(pContext->sEthHeader.abyDstAddr[0]),(WORD) (BytesToWrite-uHeaderLen),pTX_Buffer->wFIFOCtl);
status = PIPEnsSendBulkOut(pDevice,pContext);
if (bNeedDeAuth == TRUE) {
WORD wReason = WLAN_MGMT_REASON_MIC_FAILURE;
bScheduleCommand((HANDLE) pDevice, WLAN_CMD_DEAUTH, (PBYTE)&wReason);
}
if(status!=STATUS_PENDING) {
pContext->bBoolInUse = FALSE;
dev_kfree_skb_irq(skb);
return STATUS_FAILURE;
}
else
return 0;
}
/*
* Description:
* Relay packet send (AC1DMA) from rx dpc.
*
* Parameters:
* In:
* pDevice - Pointer to the adapter
* pPacket - Pointer to rx packet
* cbPacketSize - rx ethernet frame size
* Out:
* TURE, FALSE
*
* Return Value: Return TRUE if packet is copy to dma1; otherwise FALSE
*/
BOOL
bRelayPacketSend (
IN PSDevice pDevice,
IN PBYTE pbySkbData,
IN UINT uDataLen,
IN UINT uNodeIndex
)
{
PSMgmtObject pMgmt = &(pDevice->sMgmtObj);
UINT BytesToWrite =0,uHeaderLen = 0;
BYTE byPktType = PK_TYPE_11B;
BOOL bNeedEncryption = FALSE;
SKeyItem STempKey;
PSKeyItem pTransmitKey = NULL;
PBYTE pbyBSSID;
PUSB_SEND_CONTEXT pContext;
BYTE byPktTyp;
BOOL fConvertedPacket;
PTX_BUFFER pTX_Buffer;
UINT status;
WORD wKeepRate = pDevice->wCurrentRate;
pContext = (PUSB_SEND_CONTEXT)s_vGetFreeContext(pDevice);
if (NULL == pContext) {
return FALSE;
}
memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)pbySkbData, U_HEADER_LEN);
if (pDevice->bEncryptionEnable == TRUE) {
bNeedEncryption = TRUE;
// get group key
pbyBSSID = pDevice->abyBroadcastAddr;
if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == FALSE) {
pTransmitKey = NULL;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"KEY is NULL. [%d]\n", pMgmt->eCurrMode);
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get GTK.\n");
}
}
if (pDevice->bEnableHostWEP) {
if (uNodeIndex >= 0) {
pTransmitKey = &STempKey;
pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
memcpy(pTransmitKey->abyKey,
&pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
pTransmitKey->uKeyLength
);
}
}
if ( bNeedEncryption && (pTransmitKey == NULL) ) {
pContext->bBoolInUse = FALSE;
return FALSE;
}
byPktTyp = (BYTE)pDevice->byPacketType;
if (pDevice->bFixRate) {
if (pDevice->byBBType == BB_TYPE_11B) {
if (pDevice->uConnectionRate >= RATE_11M) {
pDevice->wCurrentRate = RATE_11M;
} else {
pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
}
} else {
if ((pDevice->byBBType == BB_TYPE_11A) &&
(pDevice->uConnectionRate <= RATE_6M)) {
pDevice->wCurrentRate = RATE_6M;
} else {
if (pDevice->uConnectionRate >= RATE_54M)
pDevice->wCurrentRate = RATE_54M;
else
pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
}
}
}
else {
pDevice->wCurrentRate = pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate;
}
if (wKeepRate != pDevice->wCurrentRate) {
bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SETPOWER, NULL);
}
if (pDevice->wCurrentRate <= RATE_11M)
byPktType = PK_TYPE_11B;
BytesToWrite = uDataLen + U_CRC_LEN;
// Convert the packet to an usb frame and copy into our buffer
// and send the irp.
fConvertedPacket = s_bPacketToWirelessUsb(pDevice, byPktType,
(PBYTE)(&pContext->Data[0]), bNeedEncryption,
uDataLen, TYPE_AC0DMA, &pDevice->sTxEthHeader,
pbySkbData, pTransmitKey, uNodeIndex,
pDevice->wCurrentRate,
&uHeaderLen, &BytesToWrite
);
if (fConvertedPacket == FALSE) {
pContext->bBoolInUse = FALSE;
return FALSE;
}
pTX_Buffer = (PTX_BUFFER)&(pContext->Data[0]);
pTX_Buffer->byPKTNO = (BYTE) (((pDevice->wCurrentRate<<4) &0x00F0) | ((pDevice->wSeqCounter - 1) & 0x000F));
pTX_Buffer->wTxByteCount = (WORD)BytesToWrite;
pContext->pPacket = NULL;
pContext->Type = CONTEXT_DATA_PACKET;
pContext->uBufLen = (WORD)BytesToWrite + 4 ; //USB header
s_vSaveTxPktInfo(pDevice, (BYTE) (pTX_Buffer->byPKTNO & 0x0F), &(pContext->sEthHeader.abyDstAddr[0]),(WORD) (BytesToWrite-uHeaderLen),pTX_Buffer->wFIFOCtl);
status = PIPEnsSendBulkOut(pDevice,pContext);
return TRUE;
}
| gpl-2.0 |
karandpr/Doppler3ICS | drivers/staging/rar/rar_driver.c | 510 | 11631 | #include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/kdev_t.h>
#include <linux/semaphore.h>
#include <linux/mm.h>
#include <linux/poll.h>
#include <linux/wait.h>
#include <linux/ioctl.h>
#include <linux/ioport.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/pagemap.h>
#include <linux/pci.h>
#include <linux/firmware.h>
#include <linux/sched.h>
#include "rar_driver.h"
/* The following defines are for the IPC process to retrieve RAR in */
/* === Lincroft Message Bus Interface === */
/* Message Control Register */
#define LNC_MCR_OFFSET 0xD0
/* Message Data Register */
#define LNC_MDR_OFFSET 0xD4
/* Message Opcodes */
#define LNC_MESSAGE_READ_OPCODE 0xD0
#define LNC_MESSAGE_WRITE_OPCODE 0xE0
/* Message Write Byte Enables */
#define LNC_MESSAGE_BYTE_WRITE_ENABLES 0xF
/* B-unit Port */
#define LNC_BUNIT_PORT 0x3
/* === Lincroft B-Unit Registers - Programmed by IA32 firmware === */
#define LNC_BRAR0L 0x10
#define LNC_BRAR0H 0x11
#define LNC_BRAR1L 0x12
#define LNC_BRAR1H 0x13
/* Reserved for SeP */
#define LNC_BRAR2L 0x14
#define LNC_BRAR2H 0x15
/* This structure is only used during module initialization. */
struct RAR_offsets {
int low; /* Register offset for low RAR physical address. */
int high; /* Register offset for high RAR physical address. */
};
struct pci_dev *rar_dev;
static uint32_t registered;
/* Moorestown supports three restricted access regions. */
#define MRST_NUM_RAR 3
struct RAR_address_struct rar_addr[MRST_NUM_RAR];
/* prototype for init */
static int __init rar_init_handler(void);
static void __exit rar_exit_handler(void);
/*
function that is activated on the succesfull probe of the RAR device
*/
static int __devinit rar_probe(struct pci_dev *pdev, const struct pci_device_id *ent);
static struct pci_device_id rar_pci_id_tbl[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x4110) },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, rar_pci_id_tbl);
/* field for registering driver to PCI device */
static struct pci_driver rar_pci_driver = {
.name = "rar_driver",
.id_table = rar_pci_id_tbl,
.probe = rar_probe
};
/* This function is used to retrieved RAR info using the IPC message
bus interface */
static int memrar_get_rar_addr(struct pci_dev* pdev,
int offset,
u32 *addr)
{
/*
* ======== The Lincroft Message Bus Interface ========
* Lincroft registers may be obtained from the PCI
* (the Host Bridge) using the Lincroft Message Bus
* Interface. That message bus interface is generally
* comprised of two registers: a control register (MCR, 0xDO)
* and a data register (MDR, 0xD4).
*
* The MCR (message control register) format is the following:
* 1. [31:24]: Opcode
* 2. [23:16]: Port
* 3. [15:8]: Register Offset
* 4. [7:4]: Byte Enables (use 0xF to set all of these bits
* to 1)
* 5. [3:0]: reserved
*
* Read (0xD0) and write (0xE0) opcodes are written to the
* control register when reading and writing to Lincroft
* registers, respectively.
*
* We're interested in registers found in the Lincroft
* B-unit. The B-unit port is 0x3.
*
* The six B-unit RAR register offsets we use are listed
* earlier in this file.
*
* Lastly writing to the MCR register requires the "Byte
* enables" bits to be set to 1. This may be achieved by
* writing 0xF at bit 4.
*
* The MDR (message data register) format is the following:
* 1. [31:0]: Read/Write Data
*
* Data being read from this register is only available after
* writing the appropriate control message to the MCR
* register.
*
* Data being written to this register must be written before
* writing the appropriate control message to the MCR
* register.
*/
int result = 0; /* result */
/* Construct control message */
u32 const message =
(LNC_MESSAGE_READ_OPCODE << 24)
| (LNC_BUNIT_PORT << 16)
| (offset << 8)
| (LNC_MESSAGE_BYTE_WRITE_ENABLES << 4);
printk(KERN_WARNING "rar- offset to LNC MSG is %x\n",offset);
if (addr == 0)
return -EINVAL;
/* Send the control message */
result = pci_write_config_dword(pdev,
LNC_MCR_OFFSET,
message);
printk(KERN_WARNING "rar- result from send ctl register is %x\n"
,result);
if (!result)
result = pci_read_config_dword(pdev,
LNC_MDR_OFFSET,
addr);
printk(KERN_WARNING "rar- result from read data register is %x\n",
result);
printk(KERN_WARNING "rar- value read from data register is %x\n",
*addr);
if (result)
return -1;
else
return 0;
}
static int memrar_set_rar_addr(struct pci_dev* pdev,
int offset,
u32 addr)
{
/*
* ======== The Lincroft Message Bus Interface ========
* Lincroft registers may be obtained from the PCI
* (the Host Bridge) using the Lincroft Message Bus
* Interface. That message bus interface is generally
* comprised of two registers: a control register (MCR, 0xDO)
* and a data register (MDR, 0xD4).
*
* The MCR (message control register) format is the following:
* 1. [31:24]: Opcode
* 2. [23:16]: Port
* 3. [15:8]: Register Offset
* 4. [7:4]: Byte Enables (use 0xF to set all of these bits
* to 1)
* 5. [3:0]: reserved
*
* Read (0xD0) and write (0xE0) opcodes are written to the
* control register when reading and writing to Lincroft
* registers, respectively.
*
* We're interested in registers found in the Lincroft
* B-unit. The B-unit port is 0x3.
*
* The six B-unit RAR register offsets we use are listed
* earlier in this file.
*
* Lastly writing to the MCR register requires the "Byte
* enables" bits to be set to 1. This may be achieved by
* writing 0xF at bit 4.
*
* The MDR (message data register) format is the following:
* 1. [31:0]: Read/Write Data
*
* Data being read from this register is only available after
* writing the appropriate control message to the MCR
* register.
*
* Data being written to this register must be written before
* writing the appropriate control message to the MCR
* register.
*/
int result = 0; /* result */
/* Construct control message */
u32 const message =
(LNC_MESSAGE_WRITE_OPCODE << 24)
| (LNC_BUNIT_PORT << 16)
| (offset << 8)
| (LNC_MESSAGE_BYTE_WRITE_ENABLES << 4);
printk(KERN_WARNING "rar- offset to LNC MSG is %x\n",offset);
if (addr == 0)
return -EINVAL;
/* Send the control message */
result = pci_write_config_dword(pdev,
LNC_MDR_OFFSET,
addr);
printk(KERN_WARNING "rar- result from send ctl register is %x\n"
,result);
if (!result)
result = pci_write_config_dword(pdev,
LNC_MCR_OFFSET,
message);
printk(KERN_WARNING "rar- result from write data register is %x\n",
result);
printk(KERN_WARNING "rar- value read to data register is %x\n",
addr);
if (result)
return -1;
else
return 0;
}
/*
* Initialize RAR parameters, such as physical addresses, etc.
*/
static int memrar_init_rar_params(struct pci_dev *pdev)
{
struct RAR_offsets const offsets[] = {
{ LNC_BRAR0L, LNC_BRAR0H },
{ LNC_BRAR1L, LNC_BRAR1H },
{ LNC_BRAR2L, LNC_BRAR2H }
};
size_t const num_offsets = sizeof(offsets) / sizeof(offsets[0]);
struct RAR_offsets const *end = offsets + num_offsets;
struct RAR_offsets const *i;
unsigned int n = 0;
int result = 0;
/* Retrieve RAR start and end physical addresses. */
/*
* Access the RAR registers through the Lincroft Message Bus
* Interface on PCI device: 00:00.0 Host bridge.
*/
/* struct pci_dev *pdev = pci_get_bus_and_slot(0, PCI_DEVFN(0,0)); */
if (pdev == NULL)
return -ENODEV;
for (i = offsets; i != end; ++i, ++n) {
if (memrar_get_rar_addr (pdev,
(*i).low,
&(rar_addr[n].low)) != 0
|| memrar_get_rar_addr (pdev,
(*i).high,
&(rar_addr[n].high)) != 0) {
result = -1;
break;
}
}
/* Done accessing the device. */
/* pci_dev_put(pdev); */
if (result == 0) {
if(1) {
size_t z;
for (z = 0; z != MRST_NUM_RAR; ++z) {
printk(KERN_WARNING "rar - BRAR[%Zd] physical address low\n"
"\tlow: 0x%08x\n"
"\thigh: 0x%08x\n",
z,
rar_addr[z].low,
rar_addr[z].high);
}
}
}
return result;
}
/*
function that is activaed on the succesfull probe of the RAR device
*/
static int __devinit rar_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
/* error */
int error;
/*------------------------
CODE
---------------------------*/
DEBUG_PRINT_0(RAR_DEBUG_LEVEL_EXTENDED,
"Rar pci probe starting\n");
error = 0;
/* enable the device */
error = pci_enable_device(pdev);
if (error) {
DEBUG_PRINT_0(RAR_DEBUG_LEVEL_EXTENDED,
"error enabling pci device\n");
goto end_function;
}
rar_dev = pdev;
registered = 1;
/* Initialize the RAR parameters, which have to be retrieved */
/* via the message bus service */
error=memrar_init_rar_params(rar_dev);
if (error) {
DEBUG_PRINT_0(RAR_DEBUG_LEVEL_EXTENDED,
"error getting RAR addresses device\n");
registered = 0;
goto end_function;
}
end_function:
return error;
}
/*
this function registers th driver to
the device subsystem( either PCI, USB, etc)
*/
static int __init rar_init_handler(void)
{
return pci_register_driver(&rar_pci_driver);
}
static void __exit rar_exit_handler(void)
{
pci_unregister_driver(&rar_pci_driver);
}
module_init(rar_init_handler);
module_exit(rar_exit_handler);
MODULE_LICENSE("GPL");
/* The get_rar_address function is used by other device drivers
* to obtain RAR address information on a RAR. It takes two
* parameter:
*
* int rar_index
* The rar_index is an index to the rar for which you wish to retrieve
* the address information.
* Values can be 0,1, or 2.
*
* struct RAR_address_struct is a pointer to a place to which the function
* can return the address structure for the RAR.
*
* The function returns a 0 upon success or a -1 if there is no RAR
* facility on this system.
*/
int get_rar_address(int rar_index,struct RAR_address_struct *addresses)
{
if (registered && (rar_index < 3) && (rar_index >= 0)) {
*addresses=rar_addr[rar_index];
/* strip off lock bit information */
addresses->low = addresses->low & 0xfffffff0;
addresses->high = addresses->high & 0xfffffff0;
return 0;
}
else {
return -ENODEV;
}
}
EXPORT_SYMBOL(get_rar_address);
/* The lock_rar function is ued by other device drivers to lock an RAR.
* once an RAR is locked, it stays locked until the next system reboot.
* The function takes one parameter:
*
* int rar_index
* The rar_index is an index to the rar that you want to lock.
* Values can be 0,1, or 2.
*
* The function returns a 0 upon success or a -1 if there is no RAR
* facility on this system.
*/
int lock_rar(int rar_index)
{
u32 working_addr;
int result;
if (registered && (rar_index < 3) && (rar_index >= 0)) {
/* first make sure that lock bits are clear (this does lock) */
working_addr=rar_addr[rar_index].low & 0xfffffff0;
/* now send that value to the register using the IPC */
result=memrar_set_rar_addr(rar_dev,rar_index,working_addr);
return result;
}
else {
return -ENODEV;
}
}
| gpl-2.0 |
nik124seleznev/ZC500TG | drivers/input/keyboard/spear-keyboard.c | 766 | 9533 | /*
* SPEAr Keyboard Driver
* Based on omap-keypad driver
*
* Copyright (C) 2010 ST Microelectronics
* Rajeev Kumar<rajeev-dlh.kumar@st.com>
*
* 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/clk.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/pm_wakeup.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/platform_data/keyboard-spear.h>
/* Keyboard Registers */
#define MODE_CTL_REG 0x00
#define STATUS_REG 0x0C
#define DATA_REG 0x10
#define INTR_MASK 0x54
/* Register Values */
#define NUM_ROWS 16
#define NUM_COLS 16
#define MODE_CTL_PCLK_FREQ_SHIFT 9
#define MODE_CTL_PCLK_FREQ_MSK 0x7F
#define MODE_CTL_KEYBOARD (0x2 << 0)
#define MODE_CTL_SCAN_RATE_10 (0x0 << 2)
#define MODE_CTL_SCAN_RATE_20 (0x1 << 2)
#define MODE_CTL_SCAN_RATE_40 (0x2 << 2)
#define MODE_CTL_SCAN_RATE_80 (0x3 << 2)
#define MODE_CTL_KEYNUM_SHIFT 6
#define MODE_CTL_START_SCAN (0x1 << 8)
#define STATUS_DATA_AVAIL (0x1 << 1)
#define DATA_ROW_MASK 0xF0
#define DATA_COLUMN_MASK 0x0F
#define ROW_SHIFT 4
struct spear_kbd {
struct input_dev *input;
void __iomem *io_base;
struct clk *clk;
unsigned int irq;
unsigned int mode;
unsigned int suspended_rate;
unsigned short last_key;
unsigned short keycodes[NUM_ROWS * NUM_COLS];
bool rep;
bool irq_wake_enabled;
u32 mode_ctl_reg;
};
static irqreturn_t spear_kbd_interrupt(int irq, void *dev_id)
{
struct spear_kbd *kbd = dev_id;
struct input_dev *input = kbd->input;
unsigned int key;
u32 sts, val;
sts = readl_relaxed(kbd->io_base + STATUS_REG);
if (!(sts & STATUS_DATA_AVAIL))
return IRQ_NONE;
if (kbd->last_key != KEY_RESERVED) {
input_report_key(input, kbd->last_key, 0);
kbd->last_key = KEY_RESERVED;
}
/* following reads active (row, col) pair */
val = readl_relaxed(kbd->io_base + DATA_REG) &
(DATA_ROW_MASK | DATA_COLUMN_MASK);
key = kbd->keycodes[val];
input_event(input, EV_MSC, MSC_SCAN, val);
input_report_key(input, key, 1);
input_sync(input);
kbd->last_key = key;
/* clear interrupt */
writel_relaxed(0, kbd->io_base + STATUS_REG);
return IRQ_HANDLED;
}
static int spear_kbd_open(struct input_dev *dev)
{
struct spear_kbd *kbd = input_get_drvdata(dev);
int error;
u32 val;
kbd->last_key = KEY_RESERVED;
error = clk_enable(kbd->clk);
if (error)
return error;
/* keyboard rate to be programmed is input clock (in MHz) - 1 */
val = clk_get_rate(kbd->clk) / 1000000 - 1;
val = (val & MODE_CTL_PCLK_FREQ_MSK) << MODE_CTL_PCLK_FREQ_SHIFT;
/* program keyboard */
val = MODE_CTL_SCAN_RATE_80 | MODE_CTL_KEYBOARD | val |
(kbd->mode << MODE_CTL_KEYNUM_SHIFT);
writel_relaxed(val, kbd->io_base + MODE_CTL_REG);
writel_relaxed(1, kbd->io_base + STATUS_REG);
/* start key scan */
val = readl_relaxed(kbd->io_base + MODE_CTL_REG);
val |= MODE_CTL_START_SCAN;
writel_relaxed(val, kbd->io_base + MODE_CTL_REG);
return 0;
}
static void spear_kbd_close(struct input_dev *dev)
{
struct spear_kbd *kbd = input_get_drvdata(dev);
u32 val;
/* stop key scan */
val = readl_relaxed(kbd->io_base + MODE_CTL_REG);
val &= ~MODE_CTL_START_SCAN;
writel_relaxed(val, kbd->io_base + MODE_CTL_REG);
clk_disable(kbd->clk);
kbd->last_key = KEY_RESERVED;
}
#ifdef CONFIG_OF
static int spear_kbd_parse_dt(struct platform_device *pdev,
struct spear_kbd *kbd)
{
struct device_node *np = pdev->dev.of_node;
int error;
u32 val, suspended_rate;
if (!np) {
dev_err(&pdev->dev, "Missing DT data\n");
return -EINVAL;
}
if (of_property_read_bool(np, "autorepeat"))
kbd->rep = true;
if (of_property_read_u32(np, "suspended_rate", &suspended_rate))
kbd->suspended_rate = suspended_rate;
error = of_property_read_u32(np, "st,mode", &val);
if (error) {
dev_err(&pdev->dev, "DT: Invalid or missing mode\n");
return error;
}
kbd->mode = val;
return 0;
}
#else
static inline int spear_kbd_parse_dt(struct platform_device *pdev,
struct spear_kbd *kbd)
{
return -ENOSYS;
}
#endif
static int spear_kbd_probe(struct platform_device *pdev)
{
struct kbd_platform_data *pdata = dev_get_platdata(&pdev->dev);
const struct matrix_keymap_data *keymap = pdata ? pdata->keymap : NULL;
struct spear_kbd *kbd;
struct input_dev *input_dev;
struct resource *res;
int irq;
int error;
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(&pdev->dev, "not able to get irq for the device\n");
return irq;
}
kbd = devm_kzalloc(&pdev->dev, sizeof(*kbd), GFP_KERNEL);
if (!kbd) {
dev_err(&pdev->dev, "not enough memory for driver data\n");
return -ENOMEM;
}
input_dev = devm_input_allocate_device(&pdev->dev);
if (!input_dev) {
dev_err(&pdev->dev, "unable to allocate input device\n");
return -ENOMEM;
}
kbd->input = input_dev;
kbd->irq = irq;
if (!pdata) {
error = spear_kbd_parse_dt(pdev, kbd);
if (error)
return error;
} else {
kbd->mode = pdata->mode;
kbd->rep = pdata->rep;
kbd->suspended_rate = pdata->suspended_rate;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
kbd->io_base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(kbd->io_base))
return PTR_ERR(kbd->io_base);
kbd->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(kbd->clk))
return PTR_ERR(kbd->clk);
input_dev->name = "Spear Keyboard";
input_dev->phys = "keyboard/input0";
input_dev->id.bustype = BUS_HOST;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->open = spear_kbd_open;
input_dev->close = spear_kbd_close;
error = matrix_keypad_build_keymap(keymap, NULL, NUM_ROWS, NUM_COLS,
kbd->keycodes, input_dev);
if (error) {
dev_err(&pdev->dev, "Failed to build keymap\n");
return error;
}
if (kbd->rep)
__set_bit(EV_REP, input_dev->evbit);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
input_set_drvdata(input_dev, kbd);
error = devm_request_irq(&pdev->dev, irq, spear_kbd_interrupt, 0,
"keyboard", kbd);
if (error) {
dev_err(&pdev->dev, "request_irq failed\n");
return error;
}
error = clk_prepare(kbd->clk);
if (error)
return error;
error = input_register_device(input_dev);
if (error) {
dev_err(&pdev->dev, "Unable to register keyboard device\n");
clk_unprepare(kbd->clk);
return error;
}
device_init_wakeup(&pdev->dev, 1);
platform_set_drvdata(pdev, kbd);
return 0;
}
static int spear_kbd_remove(struct platform_device *pdev)
{
struct spear_kbd *kbd = platform_get_drvdata(pdev);
input_unregister_device(kbd->input);
clk_unprepare(kbd->clk);
device_init_wakeup(&pdev->dev, 0);
return 0;
}
#ifdef CONFIG_PM
static int spear_kbd_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct spear_kbd *kbd = platform_get_drvdata(pdev);
struct input_dev *input_dev = kbd->input;
unsigned int rate = 0, mode_ctl_reg, val;
mutex_lock(&input_dev->mutex);
/* explicitly enable clock as we may program device */
clk_enable(kbd->clk);
mode_ctl_reg = readl_relaxed(kbd->io_base + MODE_CTL_REG);
if (device_may_wakeup(&pdev->dev)) {
if (!enable_irq_wake(kbd->irq))
kbd->irq_wake_enabled = true;
/*
* reprogram the keyboard operating frequency as on some
* platform it may change during system suspended
*/
if (kbd->suspended_rate)
rate = kbd->suspended_rate / 1000000 - 1;
else
rate = clk_get_rate(kbd->clk) / 1000000 - 1;
val = mode_ctl_reg &
~(MODE_CTL_PCLK_FREQ_MSK << MODE_CTL_PCLK_FREQ_SHIFT);
val |= (rate & MODE_CTL_PCLK_FREQ_MSK)
<< MODE_CTL_PCLK_FREQ_SHIFT;
writel_relaxed(val, kbd->io_base + MODE_CTL_REG);
} else {
if (input_dev->users) {
writel_relaxed(mode_ctl_reg & ~MODE_CTL_START_SCAN,
kbd->io_base + MODE_CTL_REG);
clk_disable(kbd->clk);
}
}
/* store current configuration */
if (input_dev->users)
kbd->mode_ctl_reg = mode_ctl_reg;
/* restore previous clk state */
clk_disable(kbd->clk);
mutex_unlock(&input_dev->mutex);
return 0;
}
static int spear_kbd_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct spear_kbd *kbd = platform_get_drvdata(pdev);
struct input_dev *input_dev = kbd->input;
mutex_lock(&input_dev->mutex);
if (device_may_wakeup(&pdev->dev)) {
if (kbd->irq_wake_enabled) {
kbd->irq_wake_enabled = false;
disable_irq_wake(kbd->irq);
}
} else {
if (input_dev->users)
clk_enable(kbd->clk);
}
/* restore current configuration */
if (input_dev->users)
writel_relaxed(kbd->mode_ctl_reg, kbd->io_base + MODE_CTL_REG);
mutex_unlock(&input_dev->mutex);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(spear_kbd_pm_ops, spear_kbd_suspend, spear_kbd_resume);
#ifdef CONFIG_OF
static const struct of_device_id spear_kbd_id_table[] = {
{ .compatible = "st,spear300-kbd" },
{}
};
MODULE_DEVICE_TABLE(of, spear_kbd_id_table);
#endif
static struct platform_driver spear_kbd_driver = {
.probe = spear_kbd_probe,
.remove = spear_kbd_remove,
.driver = {
.name = "keyboard",
.owner = THIS_MODULE,
.pm = &spear_kbd_pm_ops,
.of_match_table = of_match_ptr(spear_kbd_id_table),
},
};
module_platform_driver(spear_kbd_driver);
MODULE_AUTHOR("Rajeev Kumar");
MODULE_DESCRIPTION("SPEAr Keyboard Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Tommy-Geenexus/android_kernel_sony_msm8994_suzuran_6.0.x | drivers/mfd/wm5102-tables.c | 1534 | 86658 | /*
* wm5102-tables.c -- WM5102 data tables
*
* 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/device.h>
#include <linux/module.h>
#include <linux/mfd/arizona/core.h>
#include <linux/mfd/arizona/registers.h>
#include "arizona.h"
#define WM5102_NUM_AOD_ISR 2
#define WM5102_NUM_ISR 5
static const struct reg_default wm5102_reva_patch[] = {
{ 0x80, 0x0003 },
{ 0x221, 0x0090 },
{ 0x211, 0x0014 },
{ 0x212, 0x0000 },
{ 0x214, 0x000C },
{ 0x171, 0x0002 },
{ 0x171, 0x0000 },
{ 0x461, 0x8000 },
{ 0x463, 0x50F0 },
{ 0x465, 0x4820 },
{ 0x467, 0x4040 },
{ 0x469, 0x3940 },
{ 0x46B, 0x3310 },
{ 0x46D, 0x2D80 },
{ 0x46F, 0x2890 },
{ 0x471, 0x1990 },
{ 0x473, 0x1450 },
{ 0x475, 0x1020 },
{ 0x477, 0x0CD0 },
{ 0x479, 0x0A30 },
{ 0x47B, 0x0810 },
{ 0x47D, 0x0510 },
{ 0x4D1, 0x017F },
{ 0x500, 0x000D },
{ 0x507, 0x1820 },
{ 0x508, 0x1820 },
{ 0x540, 0x000D },
{ 0x547, 0x1820 },
{ 0x548, 0x1820 },
{ 0x580, 0x000D },
{ 0x587, 0x1820 },
{ 0x588, 0x1820 },
{ 0x80, 0x0000 },
};
static const struct reg_default wm5102_revb_patch[] = {
{ 0x19, 0x0001 },
{ 0x80, 0x0003 },
{ 0x081, 0xE022 },
{ 0x410, 0x6080 },
{ 0x418, 0xa080 },
{ 0x420, 0xa080 },
{ 0x428, 0xe000 },
{ 0x443, 0xDC1A },
{ 0x4B0, 0x0066 },
{ 0x458, 0x000b },
{ 0x212, 0x0000 },
{ 0x171, 0x0000 },
{ 0x35E, 0x000C },
{ 0x2D4, 0x0000 },
{ 0x80, 0x0000 },
};
/* We use a function so we can use ARRAY_SIZE() */
int wm5102_patch(struct arizona *arizona)
{
const struct reg_default *wm5102_patch;
int ret = 0;
int i, patch_size;
switch (arizona->rev) {
case 0:
wm5102_patch = wm5102_reva_patch;
patch_size = ARRAY_SIZE(wm5102_reva_patch);
default:
wm5102_patch = wm5102_revb_patch;
patch_size = ARRAY_SIZE(wm5102_revb_patch);
}
regcache_cache_bypass(arizona->regmap, true);
for (i = 0; i < patch_size; i++) {
ret = regmap_write(arizona->regmap, wm5102_patch[i].reg,
wm5102_patch[i].def);
if (ret != 0) {
dev_err(arizona->dev, "Failed to write %x = %x: %d\n",
wm5102_patch[i].reg, wm5102_patch[i].def, ret);
goto out;
}
}
out:
regcache_cache_bypass(arizona->regmap, false);
return ret;
}
static const struct regmap_irq wm5102_aod_irqs[ARIZONA_NUM_IRQ] = {
[ARIZONA_IRQ_MICD_CLAMP_FALL] = {
.mask = ARIZONA_MICD_CLAMP_FALL_EINT1
},
[ARIZONA_IRQ_MICD_CLAMP_RISE] = {
.mask = ARIZONA_MICD_CLAMP_RISE_EINT1
},
[ARIZONA_IRQ_GP5_FALL] = { .mask = ARIZONA_GP5_FALL_EINT1 },
[ARIZONA_IRQ_GP5_RISE] = { .mask = ARIZONA_GP5_RISE_EINT1 },
[ARIZONA_IRQ_JD_FALL] = { .mask = ARIZONA_JD1_FALL_EINT1 },
[ARIZONA_IRQ_JD_RISE] = { .mask = ARIZONA_JD1_RISE_EINT1 },
};
const struct regmap_irq_chip wm5102_aod = {
.name = "wm5102 AOD",
.status_base = ARIZONA_AOD_IRQ1,
.mask_base = ARIZONA_AOD_IRQ_MASK_IRQ1,
.ack_base = ARIZONA_AOD_IRQ1,
.wake_base = ARIZONA_WAKE_CONTROL,
.wake_invert = 1,
.num_regs = 1,
.irqs = wm5102_aod_irqs,
.num_irqs = ARRAY_SIZE(wm5102_aod_irqs),
};
static const struct regmap_irq wm5102_irqs[ARIZONA_NUM_IRQ] = {
[ARIZONA_IRQ_GP4] = { .reg_offset = 0, .mask = ARIZONA_GP4_EINT1 },
[ARIZONA_IRQ_GP3] = { .reg_offset = 0, .mask = ARIZONA_GP3_EINT1 },
[ARIZONA_IRQ_GP2] = { .reg_offset = 0, .mask = ARIZONA_GP2_EINT1 },
[ARIZONA_IRQ_GP1] = { .reg_offset = 0, .mask = ARIZONA_GP1_EINT1 },
[ARIZONA_IRQ_DSP1_RAM_RDY] = {
.reg_offset = 1, .mask = ARIZONA_DSP1_RAM_RDY_EINT1
},
[ARIZONA_IRQ_DSP_IRQ2] = {
.reg_offset = 1, .mask = ARIZONA_DSP_IRQ2_EINT1
},
[ARIZONA_IRQ_DSP_IRQ1] = {
.reg_offset = 1, .mask = ARIZONA_DSP_IRQ1_EINT1
},
[ARIZONA_IRQ_SPK_SHUTDOWN_WARN] = {
.reg_offset = 2, .mask = ARIZONA_SPK_SHUTDOWN_WARN_EINT1
},
[ARIZONA_IRQ_SPK_SHUTDOWN] = {
.reg_offset = 2, .mask = ARIZONA_SPK_SHUTDOWN_EINT1
},
[ARIZONA_IRQ_HPDET] = {
.reg_offset = 2, .mask = ARIZONA_HPDET_EINT1
},
[ARIZONA_IRQ_MICDET] = {
.reg_offset = 2, .mask = ARIZONA_MICDET_EINT1
},
[ARIZONA_IRQ_WSEQ_DONE] = {
.reg_offset = 2, .mask = ARIZONA_WSEQ_DONE_EINT1
},
[ARIZONA_IRQ_DRC2_SIG_DET] = {
.reg_offset = 2, .mask = ARIZONA_DRC2_SIG_DET_EINT1
},
[ARIZONA_IRQ_DRC1_SIG_DET] = {
.reg_offset = 2, .mask = ARIZONA_DRC1_SIG_DET_EINT1
},
[ARIZONA_IRQ_ASRC2_LOCK] = {
.reg_offset = 2, .mask = ARIZONA_ASRC2_LOCK_EINT1
},
[ARIZONA_IRQ_ASRC1_LOCK] = {
.reg_offset = 2, .mask = ARIZONA_ASRC1_LOCK_EINT1
},
[ARIZONA_IRQ_UNDERCLOCKED] = {
.reg_offset = 2, .mask = ARIZONA_UNDERCLOCKED_EINT1
},
[ARIZONA_IRQ_OVERCLOCKED] = {
.reg_offset = 2, .mask = ARIZONA_OVERCLOCKED_EINT1
},
[ARIZONA_IRQ_FLL2_LOCK] = {
.reg_offset = 2, .mask = ARIZONA_FLL2_LOCK_EINT1
},
[ARIZONA_IRQ_FLL1_LOCK] = {
.reg_offset = 2, .mask = ARIZONA_FLL1_LOCK_EINT1
},
[ARIZONA_IRQ_CLKGEN_ERR] = {
.reg_offset = 2, .mask = ARIZONA_CLKGEN_ERR_EINT1
},
[ARIZONA_IRQ_CLKGEN_ERR_ASYNC] = {
.reg_offset = 2, .mask = ARIZONA_CLKGEN_ERR_ASYNC_EINT1
},
[ARIZONA_IRQ_ASRC_CFG_ERR] = {
.reg_offset = 3, .mask = ARIZONA_ASRC_CFG_ERR_EINT1
},
[ARIZONA_IRQ_AIF3_ERR] = {
.reg_offset = 3, .mask = ARIZONA_AIF3_ERR_EINT1
},
[ARIZONA_IRQ_AIF2_ERR] = {
.reg_offset = 3, .mask = ARIZONA_AIF2_ERR_EINT1
},
[ARIZONA_IRQ_AIF1_ERR] = {
.reg_offset = 3, .mask = ARIZONA_AIF1_ERR_EINT1
},
[ARIZONA_IRQ_CTRLIF_ERR] = {
.reg_offset = 3, .mask = ARIZONA_CTRLIF_ERR_EINT1
},
[ARIZONA_IRQ_MIXER_DROPPED_SAMPLES] = {
.reg_offset = 3, .mask = ARIZONA_MIXER_DROPPED_SAMPLE_EINT1
},
[ARIZONA_IRQ_ASYNC_CLK_ENA_LOW] = {
.reg_offset = 3, .mask = ARIZONA_ASYNC_CLK_ENA_LOW_EINT1
},
[ARIZONA_IRQ_SYSCLK_ENA_LOW] = {
.reg_offset = 3, .mask = ARIZONA_SYSCLK_ENA_LOW_EINT1
},
[ARIZONA_IRQ_ISRC1_CFG_ERR] = {
.reg_offset = 3, .mask = ARIZONA_ISRC1_CFG_ERR_EINT1
},
[ARIZONA_IRQ_ISRC2_CFG_ERR] = {
.reg_offset = 3, .mask = ARIZONA_ISRC2_CFG_ERR_EINT1
},
[ARIZONA_IRQ_BOOT_DONE] = {
.reg_offset = 4, .mask = ARIZONA_BOOT_DONE_EINT1
},
[ARIZONA_IRQ_DCS_DAC_DONE] = {
.reg_offset = 4, .mask = ARIZONA_DCS_DAC_DONE_EINT1
},
[ARIZONA_IRQ_DCS_HP_DONE] = {
.reg_offset = 4, .mask = ARIZONA_DCS_HP_DONE_EINT1
},
[ARIZONA_IRQ_FLL2_CLOCK_OK] = {
.reg_offset = 4, .mask = ARIZONA_FLL2_CLOCK_OK_EINT1
},
[ARIZONA_IRQ_FLL1_CLOCK_OK] = {
.reg_offset = 4, .mask = ARIZONA_FLL1_CLOCK_OK_EINT1
},
};
const struct regmap_irq_chip wm5102_irq = {
.name = "wm5102 IRQ",
.status_base = ARIZONA_INTERRUPT_STATUS_1,
.mask_base = ARIZONA_INTERRUPT_STATUS_1_MASK,
.ack_base = ARIZONA_INTERRUPT_STATUS_1,
.num_regs = 5,
.irqs = wm5102_irqs,
.num_irqs = ARRAY_SIZE(wm5102_irqs),
};
static const struct reg_default wm5102_reg_default[] = {
{ 0x00000008, 0x0019 }, /* R8 - Ctrl IF SPI CFG 1 */
{ 0x00000009, 0x0001 }, /* R9 - Ctrl IF I2C1 CFG 1 */
{ 0x00000016, 0x0000 }, /* R22 - Write Sequencer Ctrl 0 */
{ 0x00000017, 0x0000 }, /* R23 - Write Sequencer Ctrl 1 */
{ 0x00000018, 0x0000 }, /* R24 - Write Sequencer Ctrl 2 */
{ 0x00000020, 0x0000 }, /* R32 - Tone Generator 1 */
{ 0x00000021, 0x1000 }, /* R33 - Tone Generator 2 */
{ 0x00000022, 0x0000 }, /* R34 - Tone Generator 3 */
{ 0x00000023, 0x1000 }, /* R35 - Tone Generator 4 */
{ 0x00000024, 0x0000 }, /* R36 - Tone Generator 5 */
{ 0x00000030, 0x0000 }, /* R48 - PWM Drive 1 */
{ 0x00000031, 0x0100 }, /* R49 - PWM Drive 2 */
{ 0x00000032, 0x0100 }, /* R50 - PWM Drive 3 */
{ 0x00000040, 0x0000 }, /* R64 - Wake control */
{ 0x00000041, 0x0000 }, /* R65 - Sequence control */
{ 0x00000061, 0x01FF }, /* R97 - Sample Rate Sequence Select 1 */
{ 0x00000062, 0x01FF }, /* R98 - Sample Rate Sequence Select 2 */
{ 0x00000063, 0x01FF }, /* R99 - Sample Rate Sequence Select 3 */
{ 0x00000064, 0x01FF }, /* R100 - Sample Rate Sequence Select 4 */
{ 0x00000066, 0x01FF }, /* R102 - Always On Triggers Sequence Select 1 */
{ 0x00000067, 0x01FF }, /* R103 - Always On Triggers Sequence Select 2 */
{ 0x00000068, 0x01FF }, /* R104 - Always On Triggers Sequence Select 3 */
{ 0x00000069, 0x01FF }, /* R105 - Always On Triggers Sequence Select 4 */
{ 0x0000006A, 0x01FF }, /* R106 - Always On Triggers Sequence Select 5 */
{ 0x0000006B, 0x01FF }, /* R107 - Always On Triggers Sequence Select 6 */
{ 0x0000006E, 0x01FF }, /* R110 - Trigger Sequence Select 32 */
{ 0x0000006F, 0x01FF }, /* R111 - Trigger Sequence Select 33 */
{ 0x00000070, 0x0000 }, /* R112 - Comfort Noise Generator */
{ 0x00000090, 0x0000 }, /* R144 - Haptics Control 1 */
{ 0x00000091, 0x7FFF }, /* R145 - Haptics Control 2 */
{ 0x00000092, 0x0000 }, /* R146 - Haptics phase 1 intensity */
{ 0x00000093, 0x0000 }, /* R147 - Haptics phase 1 duration */
{ 0x00000094, 0x0000 }, /* R148 - Haptics phase 2 intensity */
{ 0x00000095, 0x0000 }, /* R149 - Haptics phase 2 duration */
{ 0x00000096, 0x0000 }, /* R150 - Haptics phase 3 intensity */
{ 0x00000097, 0x0000 }, /* R151 - Haptics phase 3 duration */
{ 0x00000100, 0x0002 }, /* R256 - Clock 32k 1 */
{ 0x00000101, 0x0304 }, /* R257 - System Clock 1 */
{ 0x00000102, 0x0011 }, /* R258 - Sample rate 1 */
{ 0x00000103, 0x0011 }, /* R259 - Sample rate 2 */
{ 0x00000104, 0x0011 }, /* R260 - Sample rate 3 */
{ 0x00000112, 0x0305 }, /* R274 - Async clock 1 */
{ 0x00000113, 0x0011 }, /* R275 - Async sample rate 1 */
{ 0x00000114, 0x0011 }, /* R276 - Async sample rate 2 */
{ 0x00000149, 0x0000 }, /* R329 - Output system clock */
{ 0x0000014A, 0x0000 }, /* R330 - Output async clock */
{ 0x00000152, 0x0000 }, /* R338 - Rate Estimator 1 */
{ 0x00000153, 0x0000 }, /* R339 - Rate Estimator 2 */
{ 0x00000154, 0x0000 }, /* R340 - Rate Estimator 3 */
{ 0x00000155, 0x0000 }, /* R341 - Rate Estimator 4 */
{ 0x00000156, 0x0000 }, /* R342 - Rate Estimator 5 */
{ 0x00000161, 0x0000 }, /* R353 - Dynamic Frequency Scaling 1 */
{ 0x00000171, 0x0000 }, /* R369 - FLL1 Control 1 */
{ 0x00000172, 0x0008 }, /* R370 - FLL1 Control 2 */
{ 0x00000173, 0x0018 }, /* R371 - FLL1 Control 3 */
{ 0x00000174, 0x007D }, /* R372 - FLL1 Control 4 */
{ 0x00000175, 0x0004 }, /* R373 - FLL1 Control 5 */
{ 0x00000176, 0x0000 }, /* R374 - FLL1 Control 6 */
{ 0x00000177, 0x0181 }, /* R375 - FLL1 Loop Filter Test 1 */
{ 0x00000178, 0x0000 }, /* R376 - FLL1 NCO Test 0 */
{ 0x00000179, 0x0000 }, /* R377 - FLL1 Control 7 */
{ 0x00000181, 0x0000 }, /* R385 - FLL1 Synchroniser 1 */
{ 0x00000182, 0x0000 }, /* R386 - FLL1 Synchroniser 2 */
{ 0x00000183, 0x0000 }, /* R387 - FLL1 Synchroniser 3 */
{ 0x00000184, 0x0000 }, /* R388 - FLL1 Synchroniser 4 */
{ 0x00000185, 0x0000 }, /* R389 - FLL1 Synchroniser 5 */
{ 0x00000186, 0x0000 }, /* R390 - FLL1 Synchroniser 6 */
{ 0x00000187, 0x0001 }, /* R391 - FLL1 Synchroniser 7 */
{ 0x00000189, 0x0000 }, /* R393 - FLL1 Spread Spectrum */
{ 0x0000018A, 0x0004 }, /* R394 - FLL1 GPIO Clock */
{ 0x00000191, 0x0000 }, /* R401 - FLL2 Control 1 */
{ 0x00000192, 0x0008 }, /* R402 - FLL2 Control 2 */
{ 0x00000193, 0x0018 }, /* R403 - FLL2 Control 3 */
{ 0x00000194, 0x007D }, /* R404 - FLL2 Control 4 */
{ 0x00000195, 0x0004 }, /* R405 - FLL2 Control 5 */
{ 0x00000196, 0x0000 }, /* R406 - FLL2 Control 6 */
{ 0x00000197, 0x0000 }, /* R407 - FLL2 Loop Filter Test 1 */
{ 0x00000198, 0x0000 }, /* R408 - FLL2 NCO Test 0 */
{ 0x00000199, 0x0000 }, /* R409 - FLL2 Control 7 */
{ 0x000001A1, 0x0000 }, /* R417 - FLL2 Synchroniser 1 */
{ 0x000001A2, 0x0000 }, /* R418 - FLL2 Synchroniser 2 */
{ 0x000001A3, 0x0000 }, /* R419 - FLL2 Synchroniser 3 */
{ 0x000001A4, 0x0000 }, /* R420 - FLL2 Synchroniser 4 */
{ 0x000001A5, 0x0000 }, /* R421 - FLL2 Synchroniser 5 */
{ 0x000001A6, 0x0000 }, /* R422 - FLL2 Synchroniser 6 */
{ 0x000001A7, 0x0001 }, /* R423 - FLL2 Synchroniser 7 */
{ 0x000001A9, 0x0000 }, /* R425 - FLL2 Spread Spectrum */
{ 0x000001AA, 0x0004 }, /* R426 - FLL2 GPIO Clock */
{ 0x00000200, 0x0006 }, /* R512 - Mic Charge Pump 1 */
{ 0x00000210, 0x00D4 }, /* R528 - LDO1 Control 1 */
{ 0x00000212, 0x0001 }, /* R530 - LDO1 Control 2 */
{ 0x00000213, 0x0344 }, /* R531 - LDO2 Control 1 */
{ 0x00000218, 0x01A6 }, /* R536 - Mic Bias Ctrl 1 */
{ 0x00000219, 0x01A6 }, /* R537 - Mic Bias Ctrl 2 */
{ 0x0000021A, 0x01A6 }, /* R538 - Mic Bias Ctrl 3 */
{ 0x00000225, 0x0400 }, /* R549 - HP Ctrl 1L */
{ 0x00000226, 0x0400 }, /* R550 - HP Ctrl 1R */
{ 0x00000293, 0x0000 }, /* R659 - Accessory Detect Mode 1 */
{ 0x0000029B, 0x0020 }, /* R667 - Headphone Detect 1 */
{ 0x0000029C, 0x0000 }, /* R668 - Headphone Detect 2 */
{ 0x0000029F, 0x0000 }, /* R671 - Headphone Detect Test */
{ 0x000002A2, 0x0000 }, /* R674 - Micd clamp control */
{ 0x000002A3, 0x1102 }, /* R675 - Mic Detect 1 */
{ 0x000002A4, 0x009F }, /* R676 - Mic Detect 2 */
{ 0x000002A5, 0x0000 }, /* R677 - Mic Detect 3 */
{ 0x000002A6, 0x3737 }, /* R678 - Mic Detect Level 1 */
{ 0x000002A7, 0x372C }, /* R679 - Mic Detect Level 2 */
{ 0x000002A8, 0x1422 }, /* R680 - Mic Detect Level 3 */
{ 0x000002A9, 0x030A }, /* R681 - Mic Detect Level 4 */
{ 0x000002C3, 0x0000 }, /* R707 - Mic noise mix control 1 */
{ 0x000002CB, 0x0000 }, /* R715 - Isolation control */
{ 0x000002D3, 0x0000 }, /* R723 - Jack detect analogue */
{ 0x00000300, 0x0000 }, /* R768 - Input Enables */
{ 0x00000308, 0x0000 }, /* R776 - Input Rate */
{ 0x00000309, 0x0022 }, /* R777 - Input Volume Ramp */
{ 0x00000310, 0x2080 }, /* R784 - IN1L Control */
{ 0x00000311, 0x0180 }, /* R785 - ADC Digital Volume 1L */
{ 0x00000312, 0x0000 }, /* R786 - DMIC1L Control */
{ 0x00000314, 0x0080 }, /* R788 - IN1R Control */
{ 0x00000315, 0x0180 }, /* R789 - ADC Digital Volume 1R */
{ 0x00000316, 0x0000 }, /* R790 - DMIC1R Control */
{ 0x00000318, 0x2080 }, /* R792 - IN2L Control */
{ 0x00000319, 0x0180 }, /* R793 - ADC Digital Volume 2L */
{ 0x0000031A, 0x0000 }, /* R794 - DMIC2L Control */
{ 0x0000031C, 0x0080 }, /* R796 - IN2R Control */
{ 0x0000031D, 0x0180 }, /* R797 - ADC Digital Volume 2R */
{ 0x0000031E, 0x0000 }, /* R798 - DMIC2R Control */
{ 0x00000320, 0x2080 }, /* R800 - IN3L Control */
{ 0x00000321, 0x0180 }, /* R801 - ADC Digital Volume 3L */
{ 0x00000322, 0x0000 }, /* R802 - DMIC3L Control */
{ 0x00000324, 0x0080 }, /* R804 - IN3R Control */
{ 0x00000325, 0x0180 }, /* R805 - ADC Digital Volume 3R */
{ 0x00000326, 0x0000 }, /* R806 - DMIC3R Control */
{ 0x00000400, 0x0000 }, /* R1024 - Output Enables 1 */
{ 0x00000408, 0x0000 }, /* R1032 - Output Rate 1 */
{ 0x00000409, 0x0022 }, /* R1033 - Output Volume Ramp */
{ 0x00000410, 0x6080 }, /* R1040 - Output Path Config 1L */
{ 0x00000411, 0x0180 }, /* R1041 - DAC Digital Volume 1L */
{ 0x00000412, 0x0081 }, /* R1042 - DAC Volume Limit 1L */
{ 0x00000413, 0x0001 }, /* R1043 - Noise Gate Select 1L */
{ 0x00000414, 0x0080 }, /* R1044 - Output Path Config 1R */
{ 0x00000415, 0x0180 }, /* R1045 - DAC Digital Volume 1R */
{ 0x00000416, 0x0081 }, /* R1046 - DAC Volume Limit 1R */
{ 0x00000417, 0x0002 }, /* R1047 - Noise Gate Select 1R */
{ 0x00000418, 0xA080 }, /* R1048 - Output Path Config 2L */
{ 0x00000419, 0x0180 }, /* R1049 - DAC Digital Volume 2L */
{ 0x0000041A, 0x0081 }, /* R1050 - DAC Volume Limit 2L */
{ 0x0000041B, 0x0004 }, /* R1051 - Noise Gate Select 2L */
{ 0x0000041C, 0x0080 }, /* R1052 - Output Path Config 2R */
{ 0x0000041D, 0x0180 }, /* R1053 - DAC Digital Volume 2R */
{ 0x0000041E, 0x0081 }, /* R1054 - DAC Volume Limit 2R */
{ 0x0000041F, 0x0008 }, /* R1055 - Noise Gate Select 2R */
{ 0x00000420, 0xA080 }, /* R1056 - Output Path Config 3L */
{ 0x00000421, 0x0180 }, /* R1057 - DAC Digital Volume 3L */
{ 0x00000422, 0x0081 }, /* R1058 - DAC Volume Limit 3L */
{ 0x00000423, 0x0010 }, /* R1059 - Noise Gate Select 3L */
{ 0x00000428, 0xE000 }, /* R1064 - Output Path Config 4L */
{ 0x00000429, 0x0180 }, /* R1065 - DAC Digital Volume 4L */
{ 0x0000042A, 0x0081 }, /* R1066 - Out Volume 4L */
{ 0x0000042B, 0x0040 }, /* R1067 - Noise Gate Select 4L */
{ 0x0000042D, 0x0180 }, /* R1069 - DAC Digital Volume 4R */
{ 0x0000042E, 0x0081 }, /* R1070 - Out Volume 4R */
{ 0x0000042F, 0x0080 }, /* R1071 - Noise Gate Select 4R */
{ 0x00000430, 0x0000 }, /* R1072 - Output Path Config 5L */
{ 0x00000431, 0x0180 }, /* R1073 - DAC Digital Volume 5L */
{ 0x00000432, 0x0081 }, /* R1074 - DAC Volume Limit 5L */
{ 0x00000433, 0x0100 }, /* R1075 - Noise Gate Select 5L */
{ 0x00000435, 0x0180 }, /* R1077 - DAC Digital Volume 5R */
{ 0x00000436, 0x0081 }, /* R1078 - DAC Volume Limit 5R */
{ 0x00000437, 0x0200 }, /* R1079 - Noise Gate Select 5R */
{ 0x00000450, 0x0000 }, /* R1104 - DAC AEC Control 1 */
{ 0x00000458, 0x000B }, /* R1112 - Noise Gate Control */
{ 0x00000490, 0x0069 }, /* R1168 - PDM SPK1 CTRL 1 */
{ 0x00000491, 0x0000 }, /* R1169 - PDM SPK1 CTRL 2 */
{ 0x00000500, 0x000C }, /* R1280 - AIF1 BCLK Ctrl */
{ 0x00000501, 0x0008 }, /* R1281 - AIF1 Tx Pin Ctrl */
{ 0x00000502, 0x0000 }, /* R1282 - AIF1 Rx Pin Ctrl */
{ 0x00000503, 0x0000 }, /* R1283 - AIF1 Rate Ctrl */
{ 0x00000504, 0x0000 }, /* R1284 - AIF1 Format */
{ 0x00000505, 0x0040 }, /* R1285 - AIF1 Tx BCLK Rate */
{ 0x00000506, 0x0040 }, /* R1286 - AIF1 Rx BCLK Rate */
{ 0x00000507, 0x1818 }, /* R1287 - AIF1 Frame Ctrl 1 */
{ 0x00000508, 0x1818 }, /* R1288 - AIF1 Frame Ctrl 2 */
{ 0x00000509, 0x0000 }, /* R1289 - AIF1 Frame Ctrl 3 */
{ 0x0000050A, 0x0001 }, /* R1290 - AIF1 Frame Ctrl 4 */
{ 0x0000050B, 0x0002 }, /* R1291 - AIF1 Frame Ctrl 5 */
{ 0x0000050C, 0x0003 }, /* R1292 - AIF1 Frame Ctrl 6 */
{ 0x0000050D, 0x0004 }, /* R1293 - AIF1 Frame Ctrl 7 */
{ 0x0000050E, 0x0005 }, /* R1294 - AIF1 Frame Ctrl 8 */
{ 0x0000050F, 0x0006 }, /* R1295 - AIF1 Frame Ctrl 9 */
{ 0x00000510, 0x0007 }, /* R1296 - AIF1 Frame Ctrl 10 */
{ 0x00000511, 0x0000 }, /* R1297 - AIF1 Frame Ctrl 11 */
{ 0x00000512, 0x0001 }, /* R1298 - AIF1 Frame Ctrl 12 */
{ 0x00000513, 0x0002 }, /* R1299 - AIF1 Frame Ctrl 13 */
{ 0x00000514, 0x0003 }, /* R1300 - AIF1 Frame Ctrl 14 */
{ 0x00000515, 0x0004 }, /* R1301 - AIF1 Frame Ctrl 15 */
{ 0x00000516, 0x0005 }, /* R1302 - AIF1 Frame Ctrl 16 */
{ 0x00000517, 0x0006 }, /* R1303 - AIF1 Frame Ctrl 17 */
{ 0x00000518, 0x0007 }, /* R1304 - AIF1 Frame Ctrl 18 */
{ 0x00000519, 0x0000 }, /* R1305 - AIF1 Tx Enables */
{ 0x0000051A, 0x0000 }, /* R1306 - AIF1 Rx Enables */
{ 0x00000540, 0x000C }, /* R1344 - AIF2 BCLK Ctrl */
{ 0x00000541, 0x0008 }, /* R1345 - AIF2 Tx Pin Ctrl */
{ 0x00000542, 0x0000 }, /* R1346 - AIF2 Rx Pin Ctrl */
{ 0x00000543, 0x0000 }, /* R1347 - AIF2 Rate Ctrl */
{ 0x00000544, 0x0000 }, /* R1348 - AIF2 Format */
{ 0x00000545, 0x0040 }, /* R1349 - AIF2 Tx BCLK Rate */
{ 0x00000546, 0x0040 }, /* R1350 - AIF2 Rx BCLK Rate */
{ 0x00000547, 0x1818 }, /* R1351 - AIF2 Frame Ctrl 1 */
{ 0x00000548, 0x1818 }, /* R1352 - AIF2 Frame Ctrl 2 */
{ 0x00000549, 0x0000 }, /* R1353 - AIF2 Frame Ctrl 3 */
{ 0x0000054A, 0x0001 }, /* R1354 - AIF2 Frame Ctrl 4 */
{ 0x00000551, 0x0000 }, /* R1361 - AIF2 Frame Ctrl 11 */
{ 0x00000552, 0x0001 }, /* R1362 - AIF2 Frame Ctrl 12 */
{ 0x00000559, 0x0000 }, /* R1369 - AIF2 Tx Enables */
{ 0x0000055A, 0x0000 }, /* R1370 - AIF2 Rx Enables */
{ 0x00000580, 0x000C }, /* R1408 - AIF3 BCLK Ctrl */
{ 0x00000581, 0x0008 }, /* R1409 - AIF3 Tx Pin Ctrl */
{ 0x00000582, 0x0000 }, /* R1410 - AIF3 Rx Pin Ctrl */
{ 0x00000583, 0x0000 }, /* R1411 - AIF3 Rate Ctrl */
{ 0x00000584, 0x0000 }, /* R1412 - AIF3 Format */
{ 0x00000585, 0x0040 }, /* R1413 - AIF3 Tx BCLK Rate */
{ 0x00000586, 0x0040 }, /* R1414 - AIF3 Rx BCLK Rate */
{ 0x00000587, 0x1818 }, /* R1415 - AIF3 Frame Ctrl 1 */
{ 0x00000588, 0x1818 }, /* R1416 - AIF3 Frame Ctrl 2 */
{ 0x00000589, 0x0000 }, /* R1417 - AIF3 Frame Ctrl 3 */
{ 0x0000058A, 0x0001 }, /* R1418 - AIF3 Frame Ctrl 4 */
{ 0x00000591, 0x0000 }, /* R1425 - AIF3 Frame Ctrl 11 */
{ 0x00000592, 0x0001 }, /* R1426 - AIF3 Frame Ctrl 12 */
{ 0x00000599, 0x0000 }, /* R1433 - AIF3 Tx Enables */
{ 0x0000059A, 0x0000 }, /* R1434 - AIF3 Rx Enables */
{ 0x000005E3, 0x0004 }, /* R1507 - SLIMbus Framer Ref Gear */
{ 0x000005E5, 0x0000 }, /* R1509 - SLIMbus Rates 1 */
{ 0x000005E6, 0x0000 }, /* R1510 - SLIMbus Rates 2 */
{ 0x000005E7, 0x0000 }, /* R1511 - SLIMbus Rates 3 */
{ 0x000005E8, 0x0000 }, /* R1512 - SLIMbus Rates 4 */
{ 0x000005E9, 0x0000 }, /* R1513 - SLIMbus Rates 5 */
{ 0x000005EA, 0x0000 }, /* R1514 - SLIMbus Rates 6 */
{ 0x000005EB, 0x0000 }, /* R1515 - SLIMbus Rates 7 */
{ 0x000005EC, 0x0000 }, /* R1516 - SLIMbus Rates 8 */
{ 0x000005F5, 0x0000 }, /* R1525 - SLIMbus RX Channel Enable */
{ 0x000005F6, 0x0000 }, /* R1526 - SLIMbus TX Channel Enable */
{ 0x00000640, 0x0000 }, /* R1600 - PWM1MIX Input 1 Source */
{ 0x00000641, 0x0080 }, /* R1601 - PWM1MIX Input 1 Volume */
{ 0x00000642, 0x0000 }, /* R1602 - PWM1MIX Input 2 Source */
{ 0x00000643, 0x0080 }, /* R1603 - PWM1MIX Input 2 Volume */
{ 0x00000644, 0x0000 }, /* R1604 - PWM1MIX Input 3 Source */
{ 0x00000645, 0x0080 }, /* R1605 - PWM1MIX Input 3 Volume */
{ 0x00000646, 0x0000 }, /* R1606 - PWM1MIX Input 4 Source */
{ 0x00000647, 0x0080 }, /* R1607 - PWM1MIX Input 4 Volume */
{ 0x00000648, 0x0000 }, /* R1608 - PWM2MIX Input 1 Source */
{ 0x00000649, 0x0080 }, /* R1609 - PWM2MIX Input 1 Volume */
{ 0x0000064A, 0x0000 }, /* R1610 - PWM2MIX Input 2 Source */
{ 0x0000064B, 0x0080 }, /* R1611 - PWM2MIX Input 2 Volume */
{ 0x0000064C, 0x0000 }, /* R1612 - PWM2MIX Input 3 Source */
{ 0x0000064D, 0x0080 }, /* R1613 - PWM2MIX Input 3 Volume */
{ 0x0000064E, 0x0000 }, /* R1614 - PWM2MIX Input 4 Source */
{ 0x0000064F, 0x0080 }, /* R1615 - PWM2MIX Input 4 Volume */
{ 0x00000660, 0x0000 }, /* R1632 - MICMIX Input 1 Source */
{ 0x00000661, 0x0080 }, /* R1633 - MICMIX Input 1 Volume */
{ 0x00000662, 0x0000 }, /* R1634 - MICMIX Input 2 Source */
{ 0x00000663, 0x0080 }, /* R1635 - MICMIX Input 2 Volume */
{ 0x00000664, 0x0000 }, /* R1636 - MICMIX Input 3 Source */
{ 0x00000665, 0x0080 }, /* R1637 - MICMIX Input 3 Volume */
{ 0x00000666, 0x0000 }, /* R1638 - MICMIX Input 4 Source */
{ 0x00000667, 0x0080 }, /* R1639 - MICMIX Input 4 Volume */
{ 0x00000668, 0x0000 }, /* R1640 - NOISEMIX Input 1 Source */
{ 0x00000669, 0x0080 }, /* R1641 - NOISEMIX Input 1 Volume */
{ 0x0000066A, 0x0000 }, /* R1642 - NOISEMIX Input 2 Source */
{ 0x0000066B, 0x0080 }, /* R1643 - NOISEMIX Input 2 Volume */
{ 0x0000066C, 0x0000 }, /* R1644 - NOISEMIX Input 3 Source */
{ 0x0000066D, 0x0080 }, /* R1645 - NOISEMIX Input 3 Volume */
{ 0x0000066E, 0x0000 }, /* R1646 - NOISEMIX Input 4 Source */
{ 0x0000066F, 0x0080 }, /* R1647 - NOISEMIX Input 4 Volume */
{ 0x00000680, 0x0000 }, /* R1664 - OUT1LMIX Input 1 Source */
{ 0x00000681, 0x0080 }, /* R1665 - OUT1LMIX Input 1 Volume */
{ 0x00000682, 0x0000 }, /* R1666 - OUT1LMIX Input 2 Source */
{ 0x00000683, 0x0080 }, /* R1667 - OUT1LMIX Input 2 Volume */
{ 0x00000684, 0x0000 }, /* R1668 - OUT1LMIX Input 3 Source */
{ 0x00000685, 0x0080 }, /* R1669 - OUT1LMIX Input 3 Volume */
{ 0x00000686, 0x0000 }, /* R1670 - OUT1LMIX Input 4 Source */
{ 0x00000687, 0x0080 }, /* R1671 - OUT1LMIX Input 4 Volume */
{ 0x00000688, 0x0000 }, /* R1672 - OUT1RMIX Input 1 Source */
{ 0x00000689, 0x0080 }, /* R1673 - OUT1RMIX Input 1 Volume */
{ 0x0000068A, 0x0000 }, /* R1674 - OUT1RMIX Input 2 Source */
{ 0x0000068B, 0x0080 }, /* R1675 - OUT1RMIX Input 2 Volume */
{ 0x0000068C, 0x0000 }, /* R1676 - OUT1RMIX Input 3 Source */
{ 0x0000068D, 0x0080 }, /* R1677 - OUT1RMIX Input 3 Volume */
{ 0x0000068E, 0x0000 }, /* R1678 - OUT1RMIX Input 4 Source */
{ 0x0000068F, 0x0080 }, /* R1679 - OUT1RMIX Input 4 Volume */
{ 0x00000690, 0x0000 }, /* R1680 - OUT2LMIX Input 1 Source */
{ 0x00000691, 0x0080 }, /* R1681 - OUT2LMIX Input 1 Volume */
{ 0x00000692, 0x0000 }, /* R1682 - OUT2LMIX Input 2 Source */
{ 0x00000693, 0x0080 }, /* R1683 - OUT2LMIX Input 2 Volume */
{ 0x00000694, 0x0000 }, /* R1684 - OUT2LMIX Input 3 Source */
{ 0x00000695, 0x0080 }, /* R1685 - OUT2LMIX Input 3 Volume */
{ 0x00000696, 0x0000 }, /* R1686 - OUT2LMIX Input 4 Source */
{ 0x00000697, 0x0080 }, /* R1687 - OUT2LMIX Input 4 Volume */
{ 0x00000698, 0x0000 }, /* R1688 - OUT2RMIX Input 1 Source */
{ 0x00000699, 0x0080 }, /* R1689 - OUT2RMIX Input 1 Volume */
{ 0x0000069A, 0x0000 }, /* R1690 - OUT2RMIX Input 2 Source */
{ 0x0000069B, 0x0080 }, /* R1691 - OUT2RMIX Input 2 Volume */
{ 0x0000069C, 0x0000 }, /* R1692 - OUT2RMIX Input 3 Source */
{ 0x0000069D, 0x0080 }, /* R1693 - OUT2RMIX Input 3 Volume */
{ 0x0000069E, 0x0000 }, /* R1694 - OUT2RMIX Input 4 Source */
{ 0x0000069F, 0x0080 }, /* R1695 - OUT2RMIX Input 4 Volume */
{ 0x000006A0, 0x0000 }, /* R1696 - OUT3LMIX Input 1 Source */
{ 0x000006A1, 0x0080 }, /* R1697 - OUT3LMIX Input 1 Volume */
{ 0x000006A2, 0x0000 }, /* R1698 - OUT3LMIX Input 2 Source */
{ 0x000006A3, 0x0080 }, /* R1699 - OUT3LMIX Input 2 Volume */
{ 0x000006A4, 0x0000 }, /* R1700 - OUT3LMIX Input 3 Source */
{ 0x000006A5, 0x0080 }, /* R1701 - OUT3LMIX Input 3 Volume */
{ 0x000006A6, 0x0000 }, /* R1702 - OUT3LMIX Input 4 Source */
{ 0x000006A7, 0x0080 }, /* R1703 - OUT3LMIX Input 4 Volume */
{ 0x000006B0, 0x0000 }, /* R1712 - OUT4LMIX Input 1 Source */
{ 0x000006B1, 0x0080 }, /* R1713 - OUT4LMIX Input 1 Volume */
{ 0x000006B2, 0x0000 }, /* R1714 - OUT4LMIX Input 2 Source */
{ 0x000006B3, 0x0080 }, /* R1715 - OUT4LMIX Input 2 Volume */
{ 0x000006B4, 0x0000 }, /* R1716 - OUT4LMIX Input 3 Source */
{ 0x000006B5, 0x0080 }, /* R1717 - OUT4LMIX Input 3 Volume */
{ 0x000006B6, 0x0000 }, /* R1718 - OUT4LMIX Input 4 Source */
{ 0x000006B7, 0x0080 }, /* R1719 - OUT4LMIX Input 4 Volume */
{ 0x000006B8, 0x0000 }, /* R1720 - OUT4RMIX Input 1 Source */
{ 0x000006B9, 0x0080 }, /* R1721 - OUT4RMIX Input 1 Volume */
{ 0x000006BA, 0x0000 }, /* R1722 - OUT4RMIX Input 2 Source */
{ 0x000006BB, 0x0080 }, /* R1723 - OUT4RMIX Input 2 Volume */
{ 0x000006BC, 0x0000 }, /* R1724 - OUT4RMIX Input 3 Source */
{ 0x000006BD, 0x0080 }, /* R1725 - OUT4RMIX Input 3 Volume */
{ 0x000006BE, 0x0000 }, /* R1726 - OUT4RMIX Input 4 Source */
{ 0x000006BF, 0x0080 }, /* R1727 - OUT4RMIX Input 4 Volume */
{ 0x000006C0, 0x0000 }, /* R1728 - OUT5LMIX Input 1 Source */
{ 0x000006C1, 0x0080 }, /* R1729 - OUT5LMIX Input 1 Volume */
{ 0x000006C2, 0x0000 }, /* R1730 - OUT5LMIX Input 2 Source */
{ 0x000006C3, 0x0080 }, /* R1731 - OUT5LMIX Input 2 Volume */
{ 0x000006C4, 0x0000 }, /* R1732 - OUT5LMIX Input 3 Source */
{ 0x000006C5, 0x0080 }, /* R1733 - OUT5LMIX Input 3 Volume */
{ 0x000006C6, 0x0000 }, /* R1734 - OUT5LMIX Input 4 Source */
{ 0x000006C7, 0x0080 }, /* R1735 - OUT5LMIX Input 4 Volume */
{ 0x000006C8, 0x0000 }, /* R1736 - OUT5RMIX Input 1 Source */
{ 0x000006C9, 0x0080 }, /* R1737 - OUT5RMIX Input 1 Volume */
{ 0x000006CA, 0x0000 }, /* R1738 - OUT5RMIX Input 2 Source */
{ 0x000006CB, 0x0080 }, /* R1739 - OUT5RMIX Input 2 Volume */
{ 0x000006CC, 0x0000 }, /* R1740 - OUT5RMIX Input 3 Source */
{ 0x000006CD, 0x0080 }, /* R1741 - OUT5RMIX Input 3 Volume */
{ 0x000006CE, 0x0000 }, /* R1742 - OUT5RMIX Input 4 Source */
{ 0x000006CF, 0x0080 }, /* R1743 - OUT5RMIX Input 4 Volume */
{ 0x00000700, 0x0000 }, /* R1792 - AIF1TX1MIX Input 1 Source */
{ 0x00000701, 0x0080 }, /* R1793 - AIF1TX1MIX Input 1 Volume */
{ 0x00000702, 0x0000 }, /* R1794 - AIF1TX1MIX Input 2 Source */
{ 0x00000703, 0x0080 }, /* R1795 - AIF1TX1MIX Input 2 Volume */
{ 0x00000704, 0x0000 }, /* R1796 - AIF1TX1MIX Input 3 Source */
{ 0x00000705, 0x0080 }, /* R1797 - AIF1TX1MIX Input 3 Volume */
{ 0x00000706, 0x0000 }, /* R1798 - AIF1TX1MIX Input 4 Source */
{ 0x00000707, 0x0080 }, /* R1799 - AIF1TX1MIX Input 4 Volume */
{ 0x00000708, 0x0000 }, /* R1800 - AIF1TX2MIX Input 1 Source */
{ 0x00000709, 0x0080 }, /* R1801 - AIF1TX2MIX Input 1 Volume */
{ 0x0000070A, 0x0000 }, /* R1802 - AIF1TX2MIX Input 2 Source */
{ 0x0000070B, 0x0080 }, /* R1803 - AIF1TX2MIX Input 2 Volume */
{ 0x0000070C, 0x0000 }, /* R1804 - AIF1TX2MIX Input 3 Source */
{ 0x0000070D, 0x0080 }, /* R1805 - AIF1TX2MIX Input 3 Volume */
{ 0x0000070E, 0x0000 }, /* R1806 - AIF1TX2MIX Input 4 Source */
{ 0x0000070F, 0x0080 }, /* R1807 - AIF1TX2MIX Input 4 Volume */
{ 0x00000710, 0x0000 }, /* R1808 - AIF1TX3MIX Input 1 Source */
{ 0x00000711, 0x0080 }, /* R1809 - AIF1TX3MIX Input 1 Volume */
{ 0x00000712, 0x0000 }, /* R1810 - AIF1TX3MIX Input 2 Source */
{ 0x00000713, 0x0080 }, /* R1811 - AIF1TX3MIX Input 2 Volume */
{ 0x00000714, 0x0000 }, /* R1812 - AIF1TX3MIX Input 3 Source */
{ 0x00000715, 0x0080 }, /* R1813 - AIF1TX3MIX Input 3 Volume */
{ 0x00000716, 0x0000 }, /* R1814 - AIF1TX3MIX Input 4 Source */
{ 0x00000717, 0x0080 }, /* R1815 - AIF1TX3MIX Input 4 Volume */
{ 0x00000718, 0x0000 }, /* R1816 - AIF1TX4MIX Input 1 Source */
{ 0x00000719, 0x0080 }, /* R1817 - AIF1TX4MIX Input 1 Volume */
{ 0x0000071A, 0x0000 }, /* R1818 - AIF1TX4MIX Input 2 Source */
{ 0x0000071B, 0x0080 }, /* R1819 - AIF1TX4MIX Input 2 Volume */
{ 0x0000071C, 0x0000 }, /* R1820 - AIF1TX4MIX Input 3 Source */
{ 0x0000071D, 0x0080 }, /* R1821 - AIF1TX4MIX Input 3 Volume */
{ 0x0000071E, 0x0000 }, /* R1822 - AIF1TX4MIX Input 4 Source */
{ 0x0000071F, 0x0080 }, /* R1823 - AIF1TX4MIX Input 4 Volume */
{ 0x00000720, 0x0000 }, /* R1824 - AIF1TX5MIX Input 1 Source */
{ 0x00000721, 0x0080 }, /* R1825 - AIF1TX5MIX Input 1 Volume */
{ 0x00000722, 0x0000 }, /* R1826 - AIF1TX5MIX Input 2 Source */
{ 0x00000723, 0x0080 }, /* R1827 - AIF1TX5MIX Input 2 Volume */
{ 0x00000724, 0x0000 }, /* R1828 - AIF1TX5MIX Input 3 Source */
{ 0x00000725, 0x0080 }, /* R1829 - AIF1TX5MIX Input 3 Volume */
{ 0x00000726, 0x0000 }, /* R1830 - AIF1TX5MIX Input 4 Source */
{ 0x00000727, 0x0080 }, /* R1831 - AIF1TX5MIX Input 4 Volume */
{ 0x00000728, 0x0000 }, /* R1832 - AIF1TX6MIX Input 1 Source */
{ 0x00000729, 0x0080 }, /* R1833 - AIF1TX6MIX Input 1 Volume */
{ 0x0000072A, 0x0000 }, /* R1834 - AIF1TX6MIX Input 2 Source */
{ 0x0000072B, 0x0080 }, /* R1835 - AIF1TX6MIX Input 2 Volume */
{ 0x0000072C, 0x0000 }, /* R1836 - AIF1TX6MIX Input 3 Source */
{ 0x0000072D, 0x0080 }, /* R1837 - AIF1TX6MIX Input 3 Volume */
{ 0x0000072E, 0x0000 }, /* R1838 - AIF1TX6MIX Input 4 Source */
{ 0x0000072F, 0x0080 }, /* R1839 - AIF1TX6MIX Input 4 Volume */
{ 0x00000730, 0x0000 }, /* R1840 - AIF1TX7MIX Input 1 Source */
{ 0x00000731, 0x0080 }, /* R1841 - AIF1TX7MIX Input 1 Volume */
{ 0x00000732, 0x0000 }, /* R1842 - AIF1TX7MIX Input 2 Source */
{ 0x00000733, 0x0080 }, /* R1843 - AIF1TX7MIX Input 2 Volume */
{ 0x00000734, 0x0000 }, /* R1844 - AIF1TX7MIX Input 3 Source */
{ 0x00000735, 0x0080 }, /* R1845 - AIF1TX7MIX Input 3 Volume */
{ 0x00000736, 0x0000 }, /* R1846 - AIF1TX7MIX Input 4 Source */
{ 0x00000737, 0x0080 }, /* R1847 - AIF1TX7MIX Input 4 Volume */
{ 0x00000738, 0x0000 }, /* R1848 - AIF1TX8MIX Input 1 Source */
{ 0x00000739, 0x0080 }, /* R1849 - AIF1TX8MIX Input 1 Volume */
{ 0x0000073A, 0x0000 }, /* R1850 - AIF1TX8MIX Input 2 Source */
{ 0x0000073B, 0x0080 }, /* R1851 - AIF1TX8MIX Input 2 Volume */
{ 0x0000073C, 0x0000 }, /* R1852 - AIF1TX8MIX Input 3 Source */
{ 0x0000073D, 0x0080 }, /* R1853 - AIF1TX8MIX Input 3 Volume */
{ 0x0000073E, 0x0000 }, /* R1854 - AIF1TX8MIX Input 4 Source */
{ 0x0000073F, 0x0080 }, /* R1855 - AIF1TX8MIX Input 4 Volume */
{ 0x00000740, 0x0000 }, /* R1856 - AIF2TX1MIX Input 1 Source */
{ 0x00000741, 0x0080 }, /* R1857 - AIF2TX1MIX Input 1 Volume */
{ 0x00000742, 0x0000 }, /* R1858 - AIF2TX1MIX Input 2 Source */
{ 0x00000743, 0x0080 }, /* R1859 - AIF2TX1MIX Input 2 Volume */
{ 0x00000744, 0x0000 }, /* R1860 - AIF2TX1MIX Input 3 Source */
{ 0x00000745, 0x0080 }, /* R1861 - AIF2TX1MIX Input 3 Volume */
{ 0x00000746, 0x0000 }, /* R1862 - AIF2TX1MIX Input 4 Source */
{ 0x00000747, 0x0080 }, /* R1863 - AIF2TX1MIX Input 4 Volume */
{ 0x00000748, 0x0000 }, /* R1864 - AIF2TX2MIX Input 1 Source */
{ 0x00000749, 0x0080 }, /* R1865 - AIF2TX2MIX Input 1 Volume */
{ 0x0000074A, 0x0000 }, /* R1866 - AIF2TX2MIX Input 2 Source */
{ 0x0000074B, 0x0080 }, /* R1867 - AIF2TX2MIX Input 2 Volume */
{ 0x0000074C, 0x0000 }, /* R1868 - AIF2TX2MIX Input 3 Source */
{ 0x0000074D, 0x0080 }, /* R1869 - AIF2TX2MIX Input 3 Volume */
{ 0x0000074E, 0x0000 }, /* R1870 - AIF2TX2MIX Input 4 Source */
{ 0x0000074F, 0x0080 }, /* R1871 - AIF2TX2MIX Input 4 Volume */
{ 0x00000780, 0x0000 }, /* R1920 - AIF3TX1MIX Input 1 Source */
{ 0x00000781, 0x0080 }, /* R1921 - AIF3TX1MIX Input 1 Volume */
{ 0x00000782, 0x0000 }, /* R1922 - AIF3TX1MIX Input 2 Source */
{ 0x00000783, 0x0080 }, /* R1923 - AIF3TX1MIX Input 2 Volume */
{ 0x00000784, 0x0000 }, /* R1924 - AIF3TX1MIX Input 3 Source */
{ 0x00000785, 0x0080 }, /* R1925 - AIF3TX1MIX Input 3 Volume */
{ 0x00000786, 0x0000 }, /* R1926 - AIF3TX1MIX Input 4 Source */
{ 0x00000787, 0x0080 }, /* R1927 - AIF3TX1MIX Input 4 Volume */
{ 0x00000788, 0x0000 }, /* R1928 - AIF3TX2MIX Input 1 Source */
{ 0x00000789, 0x0080 }, /* R1929 - AIF3TX2MIX Input 1 Volume */
{ 0x0000078A, 0x0000 }, /* R1930 - AIF3TX2MIX Input 2 Source */
{ 0x0000078B, 0x0080 }, /* R1931 - AIF3TX2MIX Input 2 Volume */
{ 0x0000078C, 0x0000 }, /* R1932 - AIF3TX2MIX Input 3 Source */
{ 0x0000078D, 0x0080 }, /* R1933 - AIF3TX2MIX Input 3 Volume */
{ 0x0000078E, 0x0000 }, /* R1934 - AIF3TX2MIX Input 4 Source */
{ 0x0000078F, 0x0080 }, /* R1935 - AIF3TX2MIX Input 4 Volume */
{ 0x000007C0, 0x0000 }, /* R1984 - SLIMTX1MIX Input 1 Source */
{ 0x000007C1, 0x0080 }, /* R1985 - SLIMTX1MIX Input 1 Volume */
{ 0x000007C2, 0x0000 }, /* R1986 - SLIMTX1MIX Input 2 Source */
{ 0x000007C3, 0x0080 }, /* R1987 - SLIMTX1MIX Input 2 Volume */
{ 0x000007C4, 0x0000 }, /* R1988 - SLIMTX1MIX Input 3 Source */
{ 0x000007C5, 0x0080 }, /* R1989 - SLIMTX1MIX Input 3 Volume */
{ 0x000007C6, 0x0000 }, /* R1990 - SLIMTX1MIX Input 4 Source */
{ 0x000007C7, 0x0080 }, /* R1991 - SLIMTX1MIX Input 4 Volume */
{ 0x000007C8, 0x0000 }, /* R1992 - SLIMTX2MIX Input 1 Source */
{ 0x000007C9, 0x0080 }, /* R1993 - SLIMTX2MIX Input 1 Volume */
{ 0x000007CA, 0x0000 }, /* R1994 - SLIMTX2MIX Input 2 Source */
{ 0x000007CB, 0x0080 }, /* R1995 - SLIMTX2MIX Input 2 Volume */
{ 0x000007CC, 0x0000 }, /* R1996 - SLIMTX2MIX Input 3 Source */
{ 0x000007CD, 0x0080 }, /* R1997 - SLIMTX2MIX Input 3 Volume */
{ 0x000007CE, 0x0000 }, /* R1998 - SLIMTX2MIX Input 4 Source */
{ 0x000007CF, 0x0080 }, /* R1999 - SLIMTX2MIX Input 4 Volume */
{ 0x000007D0, 0x0000 }, /* R2000 - SLIMTX3MIX Input 1 Source */
{ 0x000007D1, 0x0080 }, /* R2001 - SLIMTX3MIX Input 1 Volume */
{ 0x000007D2, 0x0000 }, /* R2002 - SLIMTX3MIX Input 2 Source */
{ 0x000007D3, 0x0080 }, /* R2003 - SLIMTX3MIX Input 2 Volume */
{ 0x000007D4, 0x0000 }, /* R2004 - SLIMTX3MIX Input 3 Source */
{ 0x000007D5, 0x0080 }, /* R2005 - SLIMTX3MIX Input 3 Volume */
{ 0x000007D6, 0x0000 }, /* R2006 - SLIMTX3MIX Input 4 Source */
{ 0x000007D7, 0x0080 }, /* R2007 - SLIMTX3MIX Input 4 Volume */
{ 0x000007D8, 0x0000 }, /* R2008 - SLIMTX4MIX Input 1 Source */
{ 0x000007D9, 0x0080 }, /* R2009 - SLIMTX4MIX Input 1 Volume */
{ 0x000007DA, 0x0000 }, /* R2010 - SLIMTX4MIX Input 2 Source */
{ 0x000007DB, 0x0080 }, /* R2011 - SLIMTX4MIX Input 2 Volume */
{ 0x000007DC, 0x0000 }, /* R2012 - SLIMTX4MIX Input 3 Source */
{ 0x000007DD, 0x0080 }, /* R2013 - SLIMTX4MIX Input 3 Volume */
{ 0x000007DE, 0x0000 }, /* R2014 - SLIMTX4MIX Input 4 Source */
{ 0x000007DF, 0x0080 }, /* R2015 - SLIMTX4MIX Input 4 Volume */
{ 0x000007E0, 0x0000 }, /* R2016 - SLIMTX5MIX Input 1 Source */
{ 0x000007E1, 0x0080 }, /* R2017 - SLIMTX5MIX Input 1 Volume */
{ 0x000007E2, 0x0000 }, /* R2018 - SLIMTX5MIX Input 2 Source */
{ 0x000007E3, 0x0080 }, /* R2019 - SLIMTX5MIX Input 2 Volume */
{ 0x000007E4, 0x0000 }, /* R2020 - SLIMTX5MIX Input 3 Source */
{ 0x000007E5, 0x0080 }, /* R2021 - SLIMTX5MIX Input 3 Volume */
{ 0x000007E6, 0x0000 }, /* R2022 - SLIMTX5MIX Input 4 Source */
{ 0x000007E7, 0x0080 }, /* R2023 - SLIMTX5MIX Input 4 Volume */
{ 0x000007E8, 0x0000 }, /* R2024 - SLIMTX6MIX Input 1 Source */
{ 0x000007E9, 0x0080 }, /* R2025 - SLIMTX6MIX Input 1 Volume */
{ 0x000007EA, 0x0000 }, /* R2026 - SLIMTX6MIX Input 2 Source */
{ 0x000007EB, 0x0080 }, /* R2027 - SLIMTX6MIX Input 2 Volume */
{ 0x000007EC, 0x0000 }, /* R2028 - SLIMTX6MIX Input 3 Source */
{ 0x000007ED, 0x0080 }, /* R2029 - SLIMTX6MIX Input 3 Volume */
{ 0x000007EE, 0x0000 }, /* R2030 - SLIMTX6MIX Input 4 Source */
{ 0x000007EF, 0x0080 }, /* R2031 - SLIMTX6MIX Input 4 Volume */
{ 0x000007F0, 0x0000 }, /* R2032 - SLIMTX7MIX Input 1 Source */
{ 0x000007F1, 0x0080 }, /* R2033 - SLIMTX7MIX Input 1 Volume */
{ 0x000007F2, 0x0000 }, /* R2034 - SLIMTX7MIX Input 2 Source */
{ 0x000007F3, 0x0080 }, /* R2035 - SLIMTX7MIX Input 2 Volume */
{ 0x000007F4, 0x0000 }, /* R2036 - SLIMTX7MIX Input 3 Source */
{ 0x000007F5, 0x0080 }, /* R2037 - SLIMTX7MIX Input 3 Volume */
{ 0x000007F6, 0x0000 }, /* R2038 - SLIMTX7MIX Input 4 Source */
{ 0x000007F7, 0x0080 }, /* R2039 - SLIMTX7MIX Input 4 Volume */
{ 0x000007F8, 0x0000 }, /* R2040 - SLIMTX8MIX Input 1 Source */
{ 0x000007F9, 0x0080 }, /* R2041 - SLIMTX8MIX Input 1 Volume */
{ 0x000007FA, 0x0000 }, /* R2042 - SLIMTX8MIX Input 2 Source */
{ 0x000007FB, 0x0080 }, /* R2043 - SLIMTX8MIX Input 2 Volume */
{ 0x000007FC, 0x0000 }, /* R2044 - SLIMTX8MIX Input 3 Source */
{ 0x000007FD, 0x0080 }, /* R2045 - SLIMTX8MIX Input 3 Volume */
{ 0x000007FE, 0x0000 }, /* R2046 - SLIMTX8MIX Input 4 Source */
{ 0x000007FF, 0x0080 }, /* R2047 - SLIMTX8MIX Input 4 Volume */
{ 0x00000880, 0x0000 }, /* R2176 - EQ1MIX Input 1 Source */
{ 0x00000881, 0x0080 }, /* R2177 - EQ1MIX Input 1 Volume */
{ 0x00000882, 0x0000 }, /* R2178 - EQ1MIX Input 2 Source */
{ 0x00000883, 0x0080 }, /* R2179 - EQ1MIX Input 2 Volume */
{ 0x00000884, 0x0000 }, /* R2180 - EQ1MIX Input 3 Source */
{ 0x00000885, 0x0080 }, /* R2181 - EQ1MIX Input 3 Volume */
{ 0x00000886, 0x0000 }, /* R2182 - EQ1MIX Input 4 Source */
{ 0x00000887, 0x0080 }, /* R2183 - EQ1MIX Input 4 Volume */
{ 0x00000888, 0x0000 }, /* R2184 - EQ2MIX Input 1 Source */
{ 0x00000889, 0x0080 }, /* R2185 - EQ2MIX Input 1 Volume */
{ 0x0000088A, 0x0000 }, /* R2186 - EQ2MIX Input 2 Source */
{ 0x0000088B, 0x0080 }, /* R2187 - EQ2MIX Input 2 Volume */
{ 0x0000088C, 0x0000 }, /* R2188 - EQ2MIX Input 3 Source */
{ 0x0000088D, 0x0080 }, /* R2189 - EQ2MIX Input 3 Volume */
{ 0x0000088E, 0x0000 }, /* R2190 - EQ2MIX Input 4 Source */
{ 0x0000088F, 0x0080 }, /* R2191 - EQ2MIX Input 4 Volume */
{ 0x00000890, 0x0000 }, /* R2192 - EQ3MIX Input 1 Source */
{ 0x00000891, 0x0080 }, /* R2193 - EQ3MIX Input 1 Volume */
{ 0x00000892, 0x0000 }, /* R2194 - EQ3MIX Input 2 Source */
{ 0x00000893, 0x0080 }, /* R2195 - EQ3MIX Input 2 Volume */
{ 0x00000894, 0x0000 }, /* R2196 - EQ3MIX Input 3 Source */
{ 0x00000895, 0x0080 }, /* R2197 - EQ3MIX Input 3 Volume */
{ 0x00000896, 0x0000 }, /* R2198 - EQ3MIX Input 4 Source */
{ 0x00000897, 0x0080 }, /* R2199 - EQ3MIX Input 4 Volume */
{ 0x00000898, 0x0000 }, /* R2200 - EQ4MIX Input 1 Source */
{ 0x00000899, 0x0080 }, /* R2201 - EQ4MIX Input 1 Volume */
{ 0x0000089A, 0x0000 }, /* R2202 - EQ4MIX Input 2 Source */
{ 0x0000089B, 0x0080 }, /* R2203 - EQ4MIX Input 2 Volume */
{ 0x0000089C, 0x0000 }, /* R2204 - EQ4MIX Input 3 Source */
{ 0x0000089D, 0x0080 }, /* R2205 - EQ4MIX Input 3 Volume */
{ 0x0000089E, 0x0000 }, /* R2206 - EQ4MIX Input 4 Source */
{ 0x0000089F, 0x0080 }, /* R2207 - EQ4MIX Input 4 Volume */
{ 0x000008C0, 0x0000 }, /* R2240 - DRC1LMIX Input 1 Source */
{ 0x000008C1, 0x0080 }, /* R2241 - DRC1LMIX Input 1 Volume */
{ 0x000008C2, 0x0000 }, /* R2242 - DRC1LMIX Input 2 Source */
{ 0x000008C3, 0x0080 }, /* R2243 - DRC1LMIX Input 2 Volume */
{ 0x000008C4, 0x0000 }, /* R2244 - DRC1LMIX Input 3 Source */
{ 0x000008C5, 0x0080 }, /* R2245 - DRC1LMIX Input 3 Volume */
{ 0x000008C6, 0x0000 }, /* R2246 - DRC1LMIX Input 4 Source */
{ 0x000008C7, 0x0080 }, /* R2247 - DRC1LMIX Input 4 Volume */
{ 0x000008C8, 0x0000 }, /* R2248 - DRC1RMIX Input 1 Source */
{ 0x000008C9, 0x0080 }, /* R2249 - DRC1RMIX Input 1 Volume */
{ 0x000008CA, 0x0000 }, /* R2250 - DRC1RMIX Input 2 Source */
{ 0x000008CB, 0x0080 }, /* R2251 - DRC1RMIX Input 2 Volume */
{ 0x000008CC, 0x0000 }, /* R2252 - DRC1RMIX Input 3 Source */
{ 0x000008CD, 0x0080 }, /* R2253 - DRC1RMIX Input 3 Volume */
{ 0x000008CE, 0x0000 }, /* R2254 - DRC1RMIX Input 4 Source */
{ 0x000008CF, 0x0080 }, /* R2255 - DRC1RMIX Input 4 Volume */
{ 0x00000900, 0x0000 }, /* R2304 - HPLP1MIX Input 1 Source */
{ 0x00000901, 0x0080 }, /* R2305 - HPLP1MIX Input 1 Volume */
{ 0x00000902, 0x0000 }, /* R2306 - HPLP1MIX Input 2 Source */
{ 0x00000903, 0x0080 }, /* R2307 - HPLP1MIX Input 2 Volume */
{ 0x00000904, 0x0000 }, /* R2308 - HPLP1MIX Input 3 Source */
{ 0x00000905, 0x0080 }, /* R2309 - HPLP1MIX Input 3 Volume */
{ 0x00000906, 0x0000 }, /* R2310 - HPLP1MIX Input 4 Source */
{ 0x00000907, 0x0080 }, /* R2311 - HPLP1MIX Input 4 Volume */
{ 0x00000908, 0x0000 }, /* R2312 - HPLP2MIX Input 1 Source */
{ 0x00000909, 0x0080 }, /* R2313 - HPLP2MIX Input 1 Volume */
{ 0x0000090A, 0x0000 }, /* R2314 - HPLP2MIX Input 2 Source */
{ 0x0000090B, 0x0080 }, /* R2315 - HPLP2MIX Input 2 Volume */
{ 0x0000090C, 0x0000 }, /* R2316 - HPLP2MIX Input 3 Source */
{ 0x0000090D, 0x0080 }, /* R2317 - HPLP2MIX Input 3 Volume */
{ 0x0000090E, 0x0000 }, /* R2318 - HPLP2MIX Input 4 Source */
{ 0x0000090F, 0x0080 }, /* R2319 - HPLP2MIX Input 4 Volume */
{ 0x00000910, 0x0000 }, /* R2320 - HPLP3MIX Input 1 Source */
{ 0x00000911, 0x0080 }, /* R2321 - HPLP3MIX Input 1 Volume */
{ 0x00000912, 0x0000 }, /* R2322 - HPLP3MIX Input 2 Source */
{ 0x00000913, 0x0080 }, /* R2323 - HPLP3MIX Input 2 Volume */
{ 0x00000914, 0x0000 }, /* R2324 - HPLP3MIX Input 3 Source */
{ 0x00000915, 0x0080 }, /* R2325 - HPLP3MIX Input 3 Volume */
{ 0x00000916, 0x0000 }, /* R2326 - HPLP3MIX Input 4 Source */
{ 0x00000917, 0x0080 }, /* R2327 - HPLP3MIX Input 4 Volume */
{ 0x00000918, 0x0000 }, /* R2328 - HPLP4MIX Input 1 Source */
{ 0x00000919, 0x0080 }, /* R2329 - HPLP4MIX Input 1 Volume */
{ 0x0000091A, 0x0000 }, /* R2330 - HPLP4MIX Input 2 Source */
{ 0x0000091B, 0x0080 }, /* R2331 - HPLP4MIX Input 2 Volume */
{ 0x0000091C, 0x0000 }, /* R2332 - HPLP4MIX Input 3 Source */
{ 0x0000091D, 0x0080 }, /* R2333 - HPLP4MIX Input 3 Volume */
{ 0x0000091E, 0x0000 }, /* R2334 - HPLP4MIX Input 4 Source */
{ 0x0000091F, 0x0080 }, /* R2335 - HPLP4MIX Input 4 Volume */
{ 0x00000940, 0x0000 }, /* R2368 - DSP1LMIX Input 1 Source */
{ 0x00000941, 0x0080 }, /* R2369 - DSP1LMIX Input 1 Volume */
{ 0x00000942, 0x0000 }, /* R2370 - DSP1LMIX Input 2 Source */
{ 0x00000943, 0x0080 }, /* R2371 - DSP1LMIX Input 2 Volume */
{ 0x00000944, 0x0000 }, /* R2372 - DSP1LMIX Input 3 Source */
{ 0x00000945, 0x0080 }, /* R2373 - DSP1LMIX Input 3 Volume */
{ 0x00000946, 0x0000 }, /* R2374 - DSP1LMIX Input 4 Source */
{ 0x00000947, 0x0080 }, /* R2375 - DSP1LMIX Input 4 Volume */
{ 0x00000948, 0x0000 }, /* R2376 - DSP1RMIX Input 1 Source */
{ 0x00000949, 0x0080 }, /* R2377 - DSP1RMIX Input 1 Volume */
{ 0x0000094A, 0x0000 }, /* R2378 - DSP1RMIX Input 2 Source */
{ 0x0000094B, 0x0080 }, /* R2379 - DSP1RMIX Input 2 Volume */
{ 0x0000094C, 0x0000 }, /* R2380 - DSP1RMIX Input 3 Source */
{ 0x0000094D, 0x0080 }, /* R2381 - DSP1RMIX Input 3 Volume */
{ 0x0000094E, 0x0000 }, /* R2382 - DSP1RMIX Input 4 Source */
{ 0x0000094F, 0x0080 }, /* R2383 - DSP1RMIX Input 4 Volume */
{ 0x00000950, 0x0000 }, /* R2384 - DSP1AUX1MIX Input 1 Source */
{ 0x00000958, 0x0000 }, /* R2392 - DSP1AUX2MIX Input 1 Source */
{ 0x00000960, 0x0000 }, /* R2400 - DSP1AUX3MIX Input 1 Source */
{ 0x00000968, 0x0000 }, /* R2408 - DSP1AUX4MIX Input 1 Source */
{ 0x00000970, 0x0000 }, /* R2416 - DSP1AUX5MIX Input 1 Source */
{ 0x00000978, 0x0000 }, /* R2424 - DSP1AUX6MIX Input 1 Source */
{ 0x00000A80, 0x0000 }, /* R2688 - ASRC1LMIX Input 1 Source */
{ 0x00000A88, 0x0000 }, /* R2696 - ASRC1RMIX Input 1 Source */
{ 0x00000A90, 0x0000 }, /* R2704 - ASRC2LMIX Input 1 Source */
{ 0x00000A98, 0x0000 }, /* R2712 - ASRC2RMIX Input 1 Source */
{ 0x00000B00, 0x0000 }, /* R2816 - ISRC1DEC1MIX Input 1 Source */
{ 0x00000B08, 0x0000 }, /* R2824 - ISRC1DEC2MIX Input 1 Source */
{ 0x00000B20, 0x0000 }, /* R2848 - ISRC1INT1MIX Input 1 Source */
{ 0x00000B28, 0x0000 }, /* R2856 - ISRC1INT2MIX Input 1 Source */
{ 0x00000B40, 0x0000 }, /* R2880 - ISRC2DEC1MIX Input 1 Source */
{ 0x00000B48, 0x0000 }, /* R2888 - ISRC2DEC2MIX Input 1 Source */
{ 0x00000B60, 0x0000 }, /* R2912 - ISRC2INT1MIX Input 1 Source */
{ 0x00000B68, 0x0000 }, /* R2920 - ISRC2INT2MIX Input 1 Source */
{ 0x00000C00, 0xA101 }, /* R3072 - GPIO1 CTRL */
{ 0x00000C01, 0xA101 }, /* R3073 - GPIO2 CTRL */
{ 0x00000C02, 0xA101 }, /* R3074 - GPIO3 CTRL */
{ 0x00000C03, 0xA101 }, /* R3075 - GPIO4 CTRL */
{ 0x00000C04, 0xA101 }, /* R3076 - GPIO5 CTRL */
{ 0x00000C0F, 0x0400 }, /* R3087 - IRQ CTRL 1 */
{ 0x00000C10, 0x1000 }, /* R3088 - GPIO Debounce Config */
{ 0x00000C20, 0x8002 }, /* R3104 - Misc Pad Ctrl 1 */
{ 0x00000C21, 0x8001 }, /* R3105 - Misc Pad Ctrl 2 */
{ 0x00000C22, 0x0000 }, /* R3106 - Misc Pad Ctrl 3 */
{ 0x00000C23, 0x0000 }, /* R3107 - Misc Pad Ctrl 4 */
{ 0x00000C24, 0x0000 }, /* R3108 - Misc Pad Ctrl 5 */
{ 0x00000C25, 0x0000 }, /* R3109 - Misc Pad Ctrl 6 */
{ 0x00000D08, 0xFFFF }, /* R3336 - Interrupt Status 1 Mask */
{ 0x00000D09, 0xFFFF }, /* R3337 - Interrupt Status 2 Mask */
{ 0x00000D0A, 0xFFFF }, /* R3338 - Interrupt Status 3 Mask */
{ 0x00000D0B, 0xFFFF }, /* R3339 - Interrupt Status 4 Mask */
{ 0x00000D0C, 0xFEFF }, /* R3340 - Interrupt Status 5 Mask */
{ 0x00000D0F, 0x0000 }, /* R3343 - Interrupt Control */
{ 0x00000D18, 0xFFFF }, /* R3352 - IRQ2 Status 1 Mask */
{ 0x00000D19, 0xFFFF }, /* R3353 - IRQ2 Status 2 Mask */
{ 0x00000D1A, 0xFFFF }, /* R3354 - IRQ2 Status 3 Mask */
{ 0x00000D1B, 0xFFFF }, /* R3355 - IRQ2 Status 4 Mask */
{ 0x00000D1C, 0xFFFF }, /* R3356 - IRQ2 Status 5 Mask */
{ 0x00000D1F, 0x0000 }, /* R3359 - IRQ2 Control */
{ 0x00000D50, 0x0000 }, /* R3408 - AOD wkup and trig */
{ 0x00000D53, 0xFFFF }, /* R3411 - AOD IRQ Mask IRQ1 */
{ 0x00000D54, 0xFFFF }, /* R3412 - AOD IRQ Mask IRQ2 */
{ 0x00000D56, 0x0000 }, /* R3414 - Jack detect debounce */
{ 0x00000E00, 0x0000 }, /* R3584 - FX_Ctrl1 */
{ 0x00000E01, 0x0000 }, /* R3585 - FX_Ctrl2 */
{ 0x00000E10, 0x6318 }, /* R3600 - EQ1_1 */
{ 0x00000E11, 0x6300 }, /* R3601 - EQ1_2 */
{ 0x00000E12, 0x0FC8 }, /* R3602 - EQ1_3 */
{ 0x00000E13, 0x03FE }, /* R3603 - EQ1_4 */
{ 0x00000E14, 0x00E0 }, /* R3604 - EQ1_5 */
{ 0x00000E15, 0x1EC4 }, /* R3605 - EQ1_6 */
{ 0x00000E16, 0xF136 }, /* R3606 - EQ1_7 */
{ 0x00000E17, 0x0409 }, /* R3607 - EQ1_8 */
{ 0x00000E18, 0x04CC }, /* R3608 - EQ1_9 */
{ 0x00000E19, 0x1C9B }, /* R3609 - EQ1_10 */
{ 0x00000E1A, 0xF337 }, /* R3610 - EQ1_11 */
{ 0x00000E1B, 0x040B }, /* R3611 - EQ1_12 */
{ 0x00000E1C, 0x0CBB }, /* R3612 - EQ1_13 */
{ 0x00000E1D, 0x16F8 }, /* R3613 - EQ1_14 */
{ 0x00000E1E, 0xF7D9 }, /* R3614 - EQ1_15 */
{ 0x00000E1F, 0x040A }, /* R3615 - EQ1_16 */
{ 0x00000E20, 0x1F14 }, /* R3616 - EQ1_17 */
{ 0x00000E21, 0x058C }, /* R3617 - EQ1_18 */
{ 0x00000E22, 0x0563 }, /* R3618 - EQ1_19 */
{ 0x00000E23, 0x4000 }, /* R3619 - EQ1_20 */
{ 0x00000E24, 0x0B75 }, /* R3620 - EQ1_21 */
{ 0x00000E26, 0x6318 }, /* R3622 - EQ2_1 */
{ 0x00000E27, 0x6300 }, /* R3623 - EQ2_2 */
{ 0x00000E28, 0x0FC8 }, /* R3624 - EQ2_3 */
{ 0x00000E29, 0x03FE }, /* R3625 - EQ2_4 */
{ 0x00000E2A, 0x00E0 }, /* R3626 - EQ2_5 */
{ 0x00000E2B, 0x1EC4 }, /* R3627 - EQ2_6 */
{ 0x00000E2C, 0xF136 }, /* R3628 - EQ2_7 */
{ 0x00000E2D, 0x0409 }, /* R3629 - EQ2_8 */
{ 0x00000E2E, 0x04CC }, /* R3630 - EQ2_9 */
{ 0x00000E2F, 0x1C9B }, /* R3631 - EQ2_10 */
{ 0x00000E30, 0xF337 }, /* R3632 - EQ2_11 */
{ 0x00000E31, 0x040B }, /* R3633 - EQ2_12 */
{ 0x00000E32, 0x0CBB }, /* R3634 - EQ2_13 */
{ 0x00000E33, 0x16F8 }, /* R3635 - EQ2_14 */
{ 0x00000E34, 0xF7D9 }, /* R3636 - EQ2_15 */
{ 0x00000E35, 0x040A }, /* R3637 - EQ2_16 */
{ 0x00000E36, 0x1F14 }, /* R3638 - EQ2_17 */
{ 0x00000E37, 0x058C }, /* R3639 - EQ2_18 */
{ 0x00000E38, 0x0563 }, /* R3640 - EQ2_19 */
{ 0x00000E39, 0x4000 }, /* R3641 - EQ2_20 */
{ 0x00000E3A, 0x0B75 }, /* R3642 - EQ2_21 */
{ 0x00000E3C, 0x6318 }, /* R3644 - EQ3_1 */
{ 0x00000E3D, 0x6300 }, /* R3645 - EQ3_2 */
{ 0x00000E3E, 0x0FC8 }, /* R3646 - EQ3_3 */
{ 0x00000E3F, 0x03FE }, /* R3647 - EQ3_4 */
{ 0x00000E40, 0x00E0 }, /* R3648 - EQ3_5 */
{ 0x00000E41, 0x1EC4 }, /* R3649 - EQ3_6 */
{ 0x00000E42, 0xF136 }, /* R3650 - EQ3_7 */
{ 0x00000E43, 0x0409 }, /* R3651 - EQ3_8 */
{ 0x00000E44, 0x04CC }, /* R3652 - EQ3_9 */
{ 0x00000E45, 0x1C9B }, /* R3653 - EQ3_10 */
{ 0x00000E46, 0xF337 }, /* R3654 - EQ3_11 */
{ 0x00000E47, 0x040B }, /* R3655 - EQ3_12 */
{ 0x00000E48, 0x0CBB }, /* R3656 - EQ3_13 */
{ 0x00000E49, 0x16F8 }, /* R3657 - EQ3_14 */
{ 0x00000E4A, 0xF7D9 }, /* R3658 - EQ3_15 */
{ 0x00000E4B, 0x040A }, /* R3659 - EQ3_16 */
{ 0x00000E4C, 0x1F14 }, /* R3660 - EQ3_17 */
{ 0x00000E4D, 0x058C }, /* R3661 - EQ3_18 */
{ 0x00000E4E, 0x0563 }, /* R3662 - EQ3_19 */
{ 0x00000E4F, 0x4000 }, /* R3663 - EQ3_20 */
{ 0x00000E50, 0x0B75 }, /* R3664 - EQ3_21 */
{ 0x00000E52, 0x6318 }, /* R3666 - EQ4_1 */
{ 0x00000E53, 0x6300 }, /* R3667 - EQ4_2 */
{ 0x00000E54, 0x0FC8 }, /* R3668 - EQ4_3 */
{ 0x00000E55, 0x03FE }, /* R3669 - EQ4_4 */
{ 0x00000E56, 0x00E0 }, /* R3670 - EQ4_5 */
{ 0x00000E57, 0x1EC4 }, /* R3671 - EQ4_6 */
{ 0x00000E58, 0xF136 }, /* R3672 - EQ4_7 */
{ 0x00000E59, 0x0409 }, /* R3673 - EQ4_8 */
{ 0x00000E5A, 0x04CC }, /* R3674 - EQ4_9 */
{ 0x00000E5B, 0x1C9B }, /* R3675 - EQ4_10 */
{ 0x00000E5C, 0xF337 }, /* R3676 - EQ4_11 */
{ 0x00000E5D, 0x040B }, /* R3677 - EQ4_12 */
{ 0x00000E5E, 0x0CBB }, /* R3678 - EQ4_13 */
{ 0x00000E5F, 0x16F8 }, /* R3679 - EQ4_14 */
{ 0x00000E60, 0xF7D9 }, /* R3680 - EQ4_15 */
{ 0x00000E61, 0x040A }, /* R3681 - EQ4_16 */
{ 0x00000E62, 0x1F14 }, /* R3682 - EQ4_17 */
{ 0x00000E63, 0x058C }, /* R3683 - EQ4_18 */
{ 0x00000E64, 0x0563 }, /* R3684 - EQ4_19 */
{ 0x00000E65, 0x4000 }, /* R3685 - EQ4_20 */
{ 0x00000E66, 0x0B75 }, /* R3686 - EQ4_21 */
{ 0x00000E80, 0x0018 }, /* R3712 - DRC1 ctrl1 */
{ 0x00000E81, 0x0933 }, /* R3713 - DRC1 ctrl2 */
{ 0x00000E82, 0x0018 }, /* R3714 - DRC1 ctrl3 */
{ 0x00000E83, 0x0000 }, /* R3715 - DRC1 ctrl4 */
{ 0x00000E84, 0x0000 }, /* R3716 - DRC1 ctrl5 */
{ 0x00000EC0, 0x0000 }, /* R3776 - HPLPF1_1 */
{ 0x00000EC1, 0x0000 }, /* R3777 - HPLPF1_2 */
{ 0x00000EC4, 0x0000 }, /* R3780 - HPLPF2_1 */
{ 0x00000EC5, 0x0000 }, /* R3781 - HPLPF2_2 */
{ 0x00000EC8, 0x0000 }, /* R3784 - HPLPF3_1 */
{ 0x00000EC9, 0x0000 }, /* R3785 - HPLPF3_2 */
{ 0x00000ECC, 0x0000 }, /* R3788 - HPLPF4_1 */
{ 0x00000ECD, 0x0000 }, /* R3789 - HPLPF4_2 */
{ 0x00000EE0, 0x0000 }, /* R3808 - ASRC_ENABLE */
{ 0x00000EE2, 0x0000 }, /* R3810 - ASRC_RATE1 */
{ 0x00000EF0, 0x0000 }, /* R3824 - ISRC 1 CTRL 1 */
{ 0x00000EF1, 0x0000 }, /* R3825 - ISRC 1 CTRL 2 */
{ 0x00000EF2, 0x0000 }, /* R3826 - ISRC 1 CTRL 3 */
{ 0x00000EF3, 0x0000 }, /* R3827 - ISRC 2 CTRL 1 */
{ 0x00000EF4, 0x0000 }, /* R3828 - ISRC 2 CTRL 2 */
{ 0x00000EF5, 0x0000 }, /* R3829 - ISRC 2 CTRL 3 */
{ 0x00001100, 0x0010 }, /* R4352 - DSP1 Control 1 */
{ 0x00001101, 0x0000 }, /* R4353 - DSP1 Clocking 1 */
};
static bool wm5102_readable_register(struct device *dev, unsigned int reg)
{
switch (reg) {
case ARIZONA_SOFTWARE_RESET:
case ARIZONA_DEVICE_REVISION:
case ARIZONA_CTRL_IF_SPI_CFG_1:
case ARIZONA_CTRL_IF_I2C1_CFG_1:
case ARIZONA_CTRL_IF_STATUS_1:
case ARIZONA_WRITE_SEQUENCER_CTRL_0:
case ARIZONA_WRITE_SEQUENCER_CTRL_1:
case ARIZONA_WRITE_SEQUENCER_CTRL_2:
case ARIZONA_WRITE_SEQUENCER_PROM:
case ARIZONA_TONE_GENERATOR_1:
case ARIZONA_TONE_GENERATOR_2:
case ARIZONA_TONE_GENERATOR_3:
case ARIZONA_TONE_GENERATOR_4:
case ARIZONA_TONE_GENERATOR_5:
case ARIZONA_PWM_DRIVE_1:
case ARIZONA_PWM_DRIVE_2:
case ARIZONA_PWM_DRIVE_3:
case ARIZONA_WAKE_CONTROL:
case ARIZONA_SEQUENCE_CONTROL:
case ARIZONA_SAMPLE_RATE_SEQUENCE_SELECT_1:
case ARIZONA_SAMPLE_RATE_SEQUENCE_SELECT_2:
case ARIZONA_SAMPLE_RATE_SEQUENCE_SELECT_3:
case ARIZONA_SAMPLE_RATE_SEQUENCE_SELECT_4:
case ARIZONA_ALWAYS_ON_TRIGGERS_SEQUENCE_SELECT_1:
case ARIZONA_ALWAYS_ON_TRIGGERS_SEQUENCE_SELECT_2:
case ARIZONA_ALWAYS_ON_TRIGGERS_SEQUENCE_SELECT_3:
case ARIZONA_ALWAYS_ON_TRIGGERS_SEQUENCE_SELECT_4:
case ARIZONA_ALWAYS_ON_TRIGGERS_SEQUENCE_SELECT_5:
case ARIZONA_ALWAYS_ON_TRIGGERS_SEQUENCE_SELECT_6:
case ARIZONA_COMFORT_NOISE_GENERATOR:
case ARIZONA_HAPTICS_CONTROL_1:
case ARIZONA_HAPTICS_CONTROL_2:
case ARIZONA_HAPTICS_PHASE_1_INTENSITY:
case ARIZONA_HAPTICS_PHASE_1_DURATION:
case ARIZONA_HAPTICS_PHASE_2_INTENSITY:
case ARIZONA_HAPTICS_PHASE_2_DURATION:
case ARIZONA_HAPTICS_PHASE_3_INTENSITY:
case ARIZONA_HAPTICS_PHASE_3_DURATION:
case ARIZONA_HAPTICS_STATUS:
case ARIZONA_CLOCK_32K_1:
case ARIZONA_SYSTEM_CLOCK_1:
case ARIZONA_SAMPLE_RATE_1:
case ARIZONA_SAMPLE_RATE_2:
case ARIZONA_SAMPLE_RATE_3:
case ARIZONA_SAMPLE_RATE_1_STATUS:
case ARIZONA_SAMPLE_RATE_2_STATUS:
case ARIZONA_SAMPLE_RATE_3_STATUS:
case ARIZONA_ASYNC_CLOCK_1:
case ARIZONA_ASYNC_SAMPLE_RATE_1:
case ARIZONA_ASYNC_SAMPLE_RATE_1_STATUS:
case ARIZONA_OUTPUT_SYSTEM_CLOCK:
case ARIZONA_OUTPUT_ASYNC_CLOCK:
case ARIZONA_RATE_ESTIMATOR_1:
case ARIZONA_RATE_ESTIMATOR_2:
case ARIZONA_RATE_ESTIMATOR_3:
case ARIZONA_RATE_ESTIMATOR_4:
case ARIZONA_RATE_ESTIMATOR_5:
case ARIZONA_DYNAMIC_FREQUENCY_SCALING_1:
case ARIZONA_FLL1_CONTROL_1:
case ARIZONA_FLL1_CONTROL_2:
case ARIZONA_FLL1_CONTROL_3:
case ARIZONA_FLL1_CONTROL_4:
case ARIZONA_FLL1_CONTROL_5:
case ARIZONA_FLL1_CONTROL_6:
case ARIZONA_FLL1_LOOP_FILTER_TEST_1:
case ARIZONA_FLL1_NCO_TEST_0:
case ARIZONA_FLL1_CONTROL_7:
case ARIZONA_FLL1_SYNCHRONISER_1:
case ARIZONA_FLL1_SYNCHRONISER_2:
case ARIZONA_FLL1_SYNCHRONISER_3:
case ARIZONA_FLL1_SYNCHRONISER_4:
case ARIZONA_FLL1_SYNCHRONISER_5:
case ARIZONA_FLL1_SYNCHRONISER_6:
case ARIZONA_FLL1_SYNCHRONISER_7:
case ARIZONA_FLL1_SPREAD_SPECTRUM:
case ARIZONA_FLL1_GPIO_CLOCK:
case ARIZONA_FLL2_CONTROL_1:
case ARIZONA_FLL2_CONTROL_2:
case ARIZONA_FLL2_CONTROL_3:
case ARIZONA_FLL2_CONTROL_4:
case ARIZONA_FLL2_CONTROL_5:
case ARIZONA_FLL2_CONTROL_6:
case ARIZONA_FLL2_LOOP_FILTER_TEST_1:
case ARIZONA_FLL2_NCO_TEST_0:
case ARIZONA_FLL2_CONTROL_7:
case ARIZONA_FLL2_SYNCHRONISER_1:
case ARIZONA_FLL2_SYNCHRONISER_2:
case ARIZONA_FLL2_SYNCHRONISER_3:
case ARIZONA_FLL2_SYNCHRONISER_4:
case ARIZONA_FLL2_SYNCHRONISER_5:
case ARIZONA_FLL2_SYNCHRONISER_6:
case ARIZONA_FLL2_SYNCHRONISER_7:
case ARIZONA_FLL2_SPREAD_SPECTRUM:
case ARIZONA_FLL2_GPIO_CLOCK:
case ARIZONA_MIC_CHARGE_PUMP_1:
case ARIZONA_LDO1_CONTROL_1:
case ARIZONA_LDO1_CONTROL_2:
case ARIZONA_LDO2_CONTROL_1:
case ARIZONA_MIC_BIAS_CTRL_1:
case ARIZONA_MIC_BIAS_CTRL_2:
case ARIZONA_MIC_BIAS_CTRL_3:
case ARIZONA_ACCESSORY_DETECT_MODE_1:
case ARIZONA_HEADPHONE_DETECT_1:
case ARIZONA_HEADPHONE_DETECT_2:
case ARIZONA_HP_DACVAL:
case ARIZONA_MICD_CLAMP_CONTROL:
case ARIZONA_MIC_DETECT_1:
case ARIZONA_MIC_DETECT_2:
case ARIZONA_MIC_DETECT_3:
case ARIZONA_MIC_DETECT_LEVEL_1:
case ARIZONA_MIC_DETECT_LEVEL_2:
case ARIZONA_MIC_DETECT_LEVEL_3:
case ARIZONA_MIC_DETECT_LEVEL_4:
case ARIZONA_MIC_NOISE_MIX_CONTROL_1:
case ARIZONA_ISOLATION_CONTROL:
case ARIZONA_JACK_DETECT_ANALOGUE:
case ARIZONA_INPUT_ENABLES:
case ARIZONA_INPUT_RATE:
case ARIZONA_INPUT_VOLUME_RAMP:
case ARIZONA_IN1L_CONTROL:
case ARIZONA_ADC_DIGITAL_VOLUME_1L:
case ARIZONA_DMIC1L_CONTROL:
case ARIZONA_IN1R_CONTROL:
case ARIZONA_ADC_DIGITAL_VOLUME_1R:
case ARIZONA_DMIC1R_CONTROL:
case ARIZONA_IN2L_CONTROL:
case ARIZONA_ADC_DIGITAL_VOLUME_2L:
case ARIZONA_DMIC2L_CONTROL:
case ARIZONA_IN2R_CONTROL:
case ARIZONA_ADC_DIGITAL_VOLUME_2R:
case ARIZONA_DMIC2R_CONTROL:
case ARIZONA_IN3L_CONTROL:
case ARIZONA_ADC_DIGITAL_VOLUME_3L:
case ARIZONA_DMIC3L_CONTROL:
case ARIZONA_IN3R_CONTROL:
case ARIZONA_ADC_DIGITAL_VOLUME_3R:
case ARIZONA_DMIC3R_CONTROL:
case ARIZONA_OUTPUT_ENABLES_1:
case ARIZONA_OUTPUT_STATUS_1:
case ARIZONA_OUTPUT_RATE_1:
case ARIZONA_OUTPUT_VOLUME_RAMP:
case ARIZONA_OUTPUT_PATH_CONFIG_1L:
case ARIZONA_DAC_DIGITAL_VOLUME_1L:
case ARIZONA_DAC_VOLUME_LIMIT_1L:
case ARIZONA_NOISE_GATE_SELECT_1L:
case ARIZONA_OUTPUT_PATH_CONFIG_1R:
case ARIZONA_DAC_DIGITAL_VOLUME_1R:
case ARIZONA_DAC_VOLUME_LIMIT_1R:
case ARIZONA_NOISE_GATE_SELECT_1R:
case ARIZONA_OUTPUT_PATH_CONFIG_2L:
case ARIZONA_DAC_DIGITAL_VOLUME_2L:
case ARIZONA_DAC_VOLUME_LIMIT_2L:
case ARIZONA_NOISE_GATE_SELECT_2L:
case ARIZONA_OUTPUT_PATH_CONFIG_2R:
case ARIZONA_DAC_DIGITAL_VOLUME_2R:
case ARIZONA_DAC_VOLUME_LIMIT_2R:
case ARIZONA_NOISE_GATE_SELECT_2R:
case ARIZONA_OUTPUT_PATH_CONFIG_3L:
case ARIZONA_DAC_DIGITAL_VOLUME_3L:
case ARIZONA_DAC_VOLUME_LIMIT_3L:
case ARIZONA_NOISE_GATE_SELECT_3L:
case ARIZONA_OUTPUT_PATH_CONFIG_3R:
case ARIZONA_DAC_DIGITAL_VOLUME_3R:
case ARIZONA_DAC_VOLUME_LIMIT_3R:
case ARIZONA_OUTPUT_PATH_CONFIG_4L:
case ARIZONA_DAC_DIGITAL_VOLUME_4L:
case ARIZONA_OUT_VOLUME_4L:
case ARIZONA_NOISE_GATE_SELECT_4L:
case ARIZONA_OUTPUT_PATH_CONFIG_4R:
case ARIZONA_DAC_DIGITAL_VOLUME_4R:
case ARIZONA_OUT_VOLUME_4R:
case ARIZONA_NOISE_GATE_SELECT_4R:
case ARIZONA_OUTPUT_PATH_CONFIG_5L:
case ARIZONA_DAC_DIGITAL_VOLUME_5L:
case ARIZONA_DAC_VOLUME_LIMIT_5L:
case ARIZONA_NOISE_GATE_SELECT_5L:
case ARIZONA_OUTPUT_PATH_CONFIG_5R:
case ARIZONA_DAC_DIGITAL_VOLUME_5R:
case ARIZONA_DAC_VOLUME_LIMIT_5R:
case ARIZONA_NOISE_GATE_SELECT_5R:
case ARIZONA_DAC_AEC_CONTROL_1:
case ARIZONA_NOISE_GATE_CONTROL:
case ARIZONA_PDM_SPK1_CTRL_1:
case ARIZONA_PDM_SPK1_CTRL_2:
case ARIZONA_SPK_CTRL_2:
case ARIZONA_SPK_CTRL_3:
case ARIZONA_DAC_COMP_1:
case ARIZONA_DAC_COMP_2:
case ARIZONA_DAC_COMP_3:
case ARIZONA_DAC_COMP_4:
case ARIZONA_AIF1_BCLK_CTRL:
case ARIZONA_AIF1_TX_PIN_CTRL:
case ARIZONA_AIF1_RX_PIN_CTRL:
case ARIZONA_AIF1_RATE_CTRL:
case ARIZONA_AIF1_FORMAT:
case ARIZONA_AIF1_TX_BCLK_RATE:
case ARIZONA_AIF1_RX_BCLK_RATE:
case ARIZONA_AIF1_FRAME_CTRL_1:
case ARIZONA_AIF1_FRAME_CTRL_2:
case ARIZONA_AIF1_FRAME_CTRL_3:
case ARIZONA_AIF1_FRAME_CTRL_4:
case ARIZONA_AIF1_FRAME_CTRL_5:
case ARIZONA_AIF1_FRAME_CTRL_6:
case ARIZONA_AIF1_FRAME_CTRL_7:
case ARIZONA_AIF1_FRAME_CTRL_8:
case ARIZONA_AIF1_FRAME_CTRL_9:
case ARIZONA_AIF1_FRAME_CTRL_10:
case ARIZONA_AIF1_FRAME_CTRL_11:
case ARIZONA_AIF1_FRAME_CTRL_12:
case ARIZONA_AIF1_FRAME_CTRL_13:
case ARIZONA_AIF1_FRAME_CTRL_14:
case ARIZONA_AIF1_FRAME_CTRL_15:
case ARIZONA_AIF1_FRAME_CTRL_16:
case ARIZONA_AIF1_FRAME_CTRL_17:
case ARIZONA_AIF1_FRAME_CTRL_18:
case ARIZONA_AIF1_TX_ENABLES:
case ARIZONA_AIF1_RX_ENABLES:
case ARIZONA_AIF1_FORCE_WRITE:
case ARIZONA_AIF2_BCLK_CTRL:
case ARIZONA_AIF2_TX_PIN_CTRL:
case ARIZONA_AIF2_RX_PIN_CTRL:
case ARIZONA_AIF2_RATE_CTRL:
case ARIZONA_AIF2_FORMAT:
case ARIZONA_AIF2_TX_BCLK_RATE:
case ARIZONA_AIF2_RX_BCLK_RATE:
case ARIZONA_AIF2_FRAME_CTRL_1:
case ARIZONA_AIF2_FRAME_CTRL_2:
case ARIZONA_AIF2_FRAME_CTRL_3:
case ARIZONA_AIF2_FRAME_CTRL_4:
case ARIZONA_AIF2_FRAME_CTRL_11:
case ARIZONA_AIF2_FRAME_CTRL_12:
case ARIZONA_AIF2_TX_ENABLES:
case ARIZONA_AIF2_RX_ENABLES:
case ARIZONA_AIF2_FORCE_WRITE:
case ARIZONA_AIF3_BCLK_CTRL:
case ARIZONA_AIF3_TX_PIN_CTRL:
case ARIZONA_AIF3_RX_PIN_CTRL:
case ARIZONA_AIF3_RATE_CTRL:
case ARIZONA_AIF3_FORMAT:
case ARIZONA_AIF3_TX_BCLK_RATE:
case ARIZONA_AIF3_RX_BCLK_RATE:
case ARIZONA_AIF3_FRAME_CTRL_1:
case ARIZONA_AIF3_FRAME_CTRL_2:
case ARIZONA_AIF3_FRAME_CTRL_3:
case ARIZONA_AIF3_FRAME_CTRL_4:
case ARIZONA_AIF3_FRAME_CTRL_11:
case ARIZONA_AIF3_FRAME_CTRL_12:
case ARIZONA_AIF3_TX_ENABLES:
case ARIZONA_AIF3_RX_ENABLES:
case ARIZONA_AIF3_FORCE_WRITE:
case ARIZONA_SLIMBUS_FRAMER_REF_GEAR:
case ARIZONA_SLIMBUS_RATES_1:
case ARIZONA_SLIMBUS_RATES_2:
case ARIZONA_SLIMBUS_RATES_3:
case ARIZONA_SLIMBUS_RATES_4:
case ARIZONA_SLIMBUS_RATES_5:
case ARIZONA_SLIMBUS_RATES_6:
case ARIZONA_SLIMBUS_RATES_7:
case ARIZONA_SLIMBUS_RATES_8:
case ARIZONA_SLIMBUS_RX_CHANNEL_ENABLE:
case ARIZONA_SLIMBUS_TX_CHANNEL_ENABLE:
case ARIZONA_SLIMBUS_RX_PORT_STATUS:
case ARIZONA_SLIMBUS_TX_PORT_STATUS:
case ARIZONA_PWM1MIX_INPUT_1_SOURCE:
case ARIZONA_PWM1MIX_INPUT_1_VOLUME:
case ARIZONA_PWM1MIX_INPUT_2_SOURCE:
case ARIZONA_PWM1MIX_INPUT_2_VOLUME:
case ARIZONA_PWM1MIX_INPUT_3_SOURCE:
case ARIZONA_PWM1MIX_INPUT_3_VOLUME:
case ARIZONA_PWM1MIX_INPUT_4_SOURCE:
case ARIZONA_PWM1MIX_INPUT_4_VOLUME:
case ARIZONA_PWM2MIX_INPUT_1_SOURCE:
case ARIZONA_PWM2MIX_INPUT_1_VOLUME:
case ARIZONA_PWM2MIX_INPUT_2_SOURCE:
case ARIZONA_PWM2MIX_INPUT_2_VOLUME:
case ARIZONA_PWM2MIX_INPUT_3_SOURCE:
case ARIZONA_PWM2MIX_INPUT_3_VOLUME:
case ARIZONA_PWM2MIX_INPUT_4_SOURCE:
case ARIZONA_PWM2MIX_INPUT_4_VOLUME:
case ARIZONA_MICMIX_INPUT_1_SOURCE:
case ARIZONA_MICMIX_INPUT_1_VOLUME:
case ARIZONA_MICMIX_INPUT_2_SOURCE:
case ARIZONA_MICMIX_INPUT_2_VOLUME:
case ARIZONA_MICMIX_INPUT_3_SOURCE:
case ARIZONA_MICMIX_INPUT_3_VOLUME:
case ARIZONA_MICMIX_INPUT_4_SOURCE:
case ARIZONA_MICMIX_INPUT_4_VOLUME:
case ARIZONA_NOISEMIX_INPUT_1_SOURCE:
case ARIZONA_NOISEMIX_INPUT_1_VOLUME:
case ARIZONA_NOISEMIX_INPUT_2_SOURCE:
case ARIZONA_NOISEMIX_INPUT_2_VOLUME:
case ARIZONA_NOISEMIX_INPUT_3_SOURCE:
case ARIZONA_NOISEMIX_INPUT_3_VOLUME:
case ARIZONA_NOISEMIX_INPUT_4_SOURCE:
case ARIZONA_NOISEMIX_INPUT_4_VOLUME:
case ARIZONA_OUT1LMIX_INPUT_1_SOURCE:
case ARIZONA_OUT1LMIX_INPUT_1_VOLUME:
case ARIZONA_OUT1LMIX_INPUT_2_SOURCE:
case ARIZONA_OUT1LMIX_INPUT_2_VOLUME:
case ARIZONA_OUT1LMIX_INPUT_3_SOURCE:
case ARIZONA_OUT1LMIX_INPUT_3_VOLUME:
case ARIZONA_OUT1LMIX_INPUT_4_SOURCE:
case ARIZONA_OUT1LMIX_INPUT_4_VOLUME:
case ARIZONA_OUT1RMIX_INPUT_1_SOURCE:
case ARIZONA_OUT1RMIX_INPUT_1_VOLUME:
case ARIZONA_OUT1RMIX_INPUT_2_SOURCE:
case ARIZONA_OUT1RMIX_INPUT_2_VOLUME:
case ARIZONA_OUT1RMIX_INPUT_3_SOURCE:
case ARIZONA_OUT1RMIX_INPUT_3_VOLUME:
case ARIZONA_OUT1RMIX_INPUT_4_SOURCE:
case ARIZONA_OUT1RMIX_INPUT_4_VOLUME:
case ARIZONA_OUT2LMIX_INPUT_1_SOURCE:
case ARIZONA_OUT2LMIX_INPUT_1_VOLUME:
case ARIZONA_OUT2LMIX_INPUT_2_SOURCE:
case ARIZONA_OUT2LMIX_INPUT_2_VOLUME:
case ARIZONA_OUT2LMIX_INPUT_3_SOURCE:
case ARIZONA_OUT2LMIX_INPUT_3_VOLUME:
case ARIZONA_OUT2LMIX_INPUT_4_SOURCE:
case ARIZONA_OUT2LMIX_INPUT_4_VOLUME:
case ARIZONA_OUT2RMIX_INPUT_1_SOURCE:
case ARIZONA_OUT2RMIX_INPUT_1_VOLUME:
case ARIZONA_OUT2RMIX_INPUT_2_SOURCE:
case ARIZONA_OUT2RMIX_INPUT_2_VOLUME:
case ARIZONA_OUT2RMIX_INPUT_3_SOURCE:
case ARIZONA_OUT2RMIX_INPUT_3_VOLUME:
case ARIZONA_OUT2RMIX_INPUT_4_SOURCE:
case ARIZONA_OUT2RMIX_INPUT_4_VOLUME:
case ARIZONA_OUT3LMIX_INPUT_1_SOURCE:
case ARIZONA_OUT3LMIX_INPUT_1_VOLUME:
case ARIZONA_OUT3LMIX_INPUT_2_SOURCE:
case ARIZONA_OUT3LMIX_INPUT_2_VOLUME:
case ARIZONA_OUT3LMIX_INPUT_3_SOURCE:
case ARIZONA_OUT3LMIX_INPUT_3_VOLUME:
case ARIZONA_OUT3LMIX_INPUT_4_SOURCE:
case ARIZONA_OUT3LMIX_INPUT_4_VOLUME:
case ARIZONA_OUT4LMIX_INPUT_1_SOURCE:
case ARIZONA_OUT4LMIX_INPUT_1_VOLUME:
case ARIZONA_OUT4LMIX_INPUT_2_SOURCE:
case ARIZONA_OUT4LMIX_INPUT_2_VOLUME:
case ARIZONA_OUT4LMIX_INPUT_3_SOURCE:
case ARIZONA_OUT4LMIX_INPUT_3_VOLUME:
case ARIZONA_OUT4LMIX_INPUT_4_SOURCE:
case ARIZONA_OUT4LMIX_INPUT_4_VOLUME:
case ARIZONA_OUT4RMIX_INPUT_1_SOURCE:
case ARIZONA_OUT4RMIX_INPUT_1_VOLUME:
case ARIZONA_OUT4RMIX_INPUT_2_SOURCE:
case ARIZONA_OUT4RMIX_INPUT_2_VOLUME:
case ARIZONA_OUT4RMIX_INPUT_3_SOURCE:
case ARIZONA_OUT4RMIX_INPUT_3_VOLUME:
case ARIZONA_OUT4RMIX_INPUT_4_SOURCE:
case ARIZONA_OUT4RMIX_INPUT_4_VOLUME:
case ARIZONA_OUT5LMIX_INPUT_1_SOURCE:
case ARIZONA_OUT5LMIX_INPUT_1_VOLUME:
case ARIZONA_OUT5LMIX_INPUT_2_SOURCE:
case ARIZONA_OUT5LMIX_INPUT_2_VOLUME:
case ARIZONA_OUT5LMIX_INPUT_3_SOURCE:
case ARIZONA_OUT5LMIX_INPUT_3_VOLUME:
case ARIZONA_OUT5LMIX_INPUT_4_SOURCE:
case ARIZONA_OUT5LMIX_INPUT_4_VOLUME:
case ARIZONA_OUT5RMIX_INPUT_1_SOURCE:
case ARIZONA_OUT5RMIX_INPUT_1_VOLUME:
case ARIZONA_OUT5RMIX_INPUT_2_SOURCE:
case ARIZONA_OUT5RMIX_INPUT_2_VOLUME:
case ARIZONA_OUT5RMIX_INPUT_3_SOURCE:
case ARIZONA_OUT5RMIX_INPUT_3_VOLUME:
case ARIZONA_OUT5RMIX_INPUT_4_SOURCE:
case ARIZONA_OUT5RMIX_INPUT_4_VOLUME:
case ARIZONA_AIF1TX1MIX_INPUT_1_SOURCE:
case ARIZONA_AIF1TX1MIX_INPUT_1_VOLUME:
case ARIZONA_AIF1TX1MIX_INPUT_2_SOURCE:
case ARIZONA_AIF1TX1MIX_INPUT_2_VOLUME:
case ARIZONA_AIF1TX1MIX_INPUT_3_SOURCE:
case ARIZONA_AIF1TX1MIX_INPUT_3_VOLUME:
case ARIZONA_AIF1TX1MIX_INPUT_4_SOURCE:
case ARIZONA_AIF1TX1MIX_INPUT_4_VOLUME:
case ARIZONA_AIF1TX2MIX_INPUT_1_SOURCE:
case ARIZONA_AIF1TX2MIX_INPUT_1_VOLUME:
case ARIZONA_AIF1TX2MIX_INPUT_2_SOURCE:
case ARIZONA_AIF1TX2MIX_INPUT_2_VOLUME:
case ARIZONA_AIF1TX2MIX_INPUT_3_SOURCE:
case ARIZONA_AIF1TX2MIX_INPUT_3_VOLUME:
case ARIZONA_AIF1TX2MIX_INPUT_4_SOURCE:
case ARIZONA_AIF1TX2MIX_INPUT_4_VOLUME:
case ARIZONA_AIF1TX3MIX_INPUT_1_SOURCE:
case ARIZONA_AIF1TX3MIX_INPUT_1_VOLUME:
case ARIZONA_AIF1TX3MIX_INPUT_2_SOURCE:
case ARIZONA_AIF1TX3MIX_INPUT_2_VOLUME:
case ARIZONA_AIF1TX3MIX_INPUT_3_SOURCE:
case ARIZONA_AIF1TX3MIX_INPUT_3_VOLUME:
case ARIZONA_AIF1TX3MIX_INPUT_4_SOURCE:
case ARIZONA_AIF1TX3MIX_INPUT_4_VOLUME:
case ARIZONA_AIF1TX4MIX_INPUT_1_SOURCE:
case ARIZONA_AIF1TX4MIX_INPUT_1_VOLUME:
case ARIZONA_AIF1TX4MIX_INPUT_2_SOURCE:
case ARIZONA_AIF1TX4MIX_INPUT_2_VOLUME:
case ARIZONA_AIF1TX4MIX_INPUT_3_SOURCE:
case ARIZONA_AIF1TX4MIX_INPUT_3_VOLUME:
case ARIZONA_AIF1TX4MIX_INPUT_4_SOURCE:
case ARIZONA_AIF1TX4MIX_INPUT_4_VOLUME:
case ARIZONA_AIF1TX5MIX_INPUT_1_SOURCE:
case ARIZONA_AIF1TX5MIX_INPUT_1_VOLUME:
case ARIZONA_AIF1TX5MIX_INPUT_2_SOURCE:
case ARIZONA_AIF1TX5MIX_INPUT_2_VOLUME:
case ARIZONA_AIF1TX5MIX_INPUT_3_SOURCE:
case ARIZONA_AIF1TX5MIX_INPUT_3_VOLUME:
case ARIZONA_AIF1TX5MIX_INPUT_4_SOURCE:
case ARIZONA_AIF1TX5MIX_INPUT_4_VOLUME:
case ARIZONA_AIF1TX6MIX_INPUT_1_SOURCE:
case ARIZONA_AIF1TX6MIX_INPUT_1_VOLUME:
case ARIZONA_AIF1TX6MIX_INPUT_2_SOURCE:
case ARIZONA_AIF1TX6MIX_INPUT_2_VOLUME:
case ARIZONA_AIF1TX6MIX_INPUT_3_SOURCE:
case ARIZONA_AIF1TX6MIX_INPUT_3_VOLUME:
case ARIZONA_AIF1TX6MIX_INPUT_4_SOURCE:
case ARIZONA_AIF1TX6MIX_INPUT_4_VOLUME:
case ARIZONA_AIF1TX7MIX_INPUT_1_SOURCE:
case ARIZONA_AIF1TX7MIX_INPUT_1_VOLUME:
case ARIZONA_AIF1TX7MIX_INPUT_2_SOURCE:
case ARIZONA_AIF1TX7MIX_INPUT_2_VOLUME:
case ARIZONA_AIF1TX7MIX_INPUT_3_SOURCE:
case ARIZONA_AIF1TX7MIX_INPUT_3_VOLUME:
case ARIZONA_AIF1TX7MIX_INPUT_4_SOURCE:
case ARIZONA_AIF1TX7MIX_INPUT_4_VOLUME:
case ARIZONA_AIF1TX8MIX_INPUT_1_SOURCE:
case ARIZONA_AIF1TX8MIX_INPUT_1_VOLUME:
case ARIZONA_AIF1TX8MIX_INPUT_2_SOURCE:
case ARIZONA_AIF1TX8MIX_INPUT_2_VOLUME:
case ARIZONA_AIF1TX8MIX_INPUT_3_SOURCE:
case ARIZONA_AIF1TX8MIX_INPUT_3_VOLUME:
case ARIZONA_AIF1TX8MIX_INPUT_4_SOURCE:
case ARIZONA_AIF1TX8MIX_INPUT_4_VOLUME:
case ARIZONA_AIF2TX1MIX_INPUT_1_SOURCE:
case ARIZONA_AIF2TX1MIX_INPUT_1_VOLUME:
case ARIZONA_AIF2TX1MIX_INPUT_2_SOURCE:
case ARIZONA_AIF2TX1MIX_INPUT_2_VOLUME:
case ARIZONA_AIF2TX1MIX_INPUT_3_SOURCE:
case ARIZONA_AIF2TX1MIX_INPUT_3_VOLUME:
case ARIZONA_AIF2TX1MIX_INPUT_4_SOURCE:
case ARIZONA_AIF2TX1MIX_INPUT_4_VOLUME:
case ARIZONA_AIF2TX2MIX_INPUT_1_SOURCE:
case ARIZONA_AIF2TX2MIX_INPUT_1_VOLUME:
case ARIZONA_AIF2TX2MIX_INPUT_2_SOURCE:
case ARIZONA_AIF2TX2MIX_INPUT_2_VOLUME:
case ARIZONA_AIF2TX2MIX_INPUT_3_SOURCE:
case ARIZONA_AIF2TX2MIX_INPUT_3_VOLUME:
case ARIZONA_AIF2TX2MIX_INPUT_4_SOURCE:
case ARIZONA_AIF2TX2MIX_INPUT_4_VOLUME:
case ARIZONA_AIF3TX1MIX_INPUT_1_SOURCE:
case ARIZONA_AIF3TX1MIX_INPUT_1_VOLUME:
case ARIZONA_AIF3TX1MIX_INPUT_2_SOURCE:
case ARIZONA_AIF3TX1MIX_INPUT_2_VOLUME:
case ARIZONA_AIF3TX1MIX_INPUT_3_SOURCE:
case ARIZONA_AIF3TX1MIX_INPUT_3_VOLUME:
case ARIZONA_AIF3TX1MIX_INPUT_4_SOURCE:
case ARIZONA_AIF3TX1MIX_INPUT_4_VOLUME:
case ARIZONA_AIF3TX2MIX_INPUT_1_SOURCE:
case ARIZONA_AIF3TX2MIX_INPUT_1_VOLUME:
case ARIZONA_AIF3TX2MIX_INPUT_2_SOURCE:
case ARIZONA_AIF3TX2MIX_INPUT_2_VOLUME:
case ARIZONA_AIF3TX2MIX_INPUT_3_SOURCE:
case ARIZONA_AIF3TX2MIX_INPUT_3_VOLUME:
case ARIZONA_AIF3TX2MIX_INPUT_4_SOURCE:
case ARIZONA_AIF3TX2MIX_INPUT_4_VOLUME:
case ARIZONA_SLIMTX1MIX_INPUT_1_SOURCE:
case ARIZONA_SLIMTX1MIX_INPUT_1_VOLUME:
case ARIZONA_SLIMTX1MIX_INPUT_2_SOURCE:
case ARIZONA_SLIMTX1MIX_INPUT_2_VOLUME:
case ARIZONA_SLIMTX1MIX_INPUT_3_SOURCE:
case ARIZONA_SLIMTX1MIX_INPUT_3_VOLUME:
case ARIZONA_SLIMTX1MIX_INPUT_4_SOURCE:
case ARIZONA_SLIMTX1MIX_INPUT_4_VOLUME:
case ARIZONA_SLIMTX2MIX_INPUT_1_SOURCE:
case ARIZONA_SLIMTX2MIX_INPUT_1_VOLUME:
case ARIZONA_SLIMTX2MIX_INPUT_2_SOURCE:
case ARIZONA_SLIMTX2MIX_INPUT_2_VOLUME:
case ARIZONA_SLIMTX2MIX_INPUT_3_SOURCE:
case ARIZONA_SLIMTX2MIX_INPUT_3_VOLUME:
case ARIZONA_SLIMTX2MIX_INPUT_4_SOURCE:
case ARIZONA_SLIMTX2MIX_INPUT_4_VOLUME:
case ARIZONA_SLIMTX3MIX_INPUT_1_SOURCE:
case ARIZONA_SLIMTX3MIX_INPUT_1_VOLUME:
case ARIZONA_SLIMTX3MIX_INPUT_2_SOURCE:
case ARIZONA_SLIMTX3MIX_INPUT_2_VOLUME:
case ARIZONA_SLIMTX3MIX_INPUT_3_SOURCE:
case ARIZONA_SLIMTX3MIX_INPUT_3_VOLUME:
case ARIZONA_SLIMTX3MIX_INPUT_4_SOURCE:
case ARIZONA_SLIMTX3MIX_INPUT_4_VOLUME:
case ARIZONA_SLIMTX4MIX_INPUT_1_SOURCE:
case ARIZONA_SLIMTX4MIX_INPUT_1_VOLUME:
case ARIZONA_SLIMTX4MIX_INPUT_2_SOURCE:
case ARIZONA_SLIMTX4MIX_INPUT_2_VOLUME:
case ARIZONA_SLIMTX4MIX_INPUT_3_SOURCE:
case ARIZONA_SLIMTX4MIX_INPUT_3_VOLUME:
case ARIZONA_SLIMTX4MIX_INPUT_4_SOURCE:
case ARIZONA_SLIMTX4MIX_INPUT_4_VOLUME:
case ARIZONA_SLIMTX5MIX_INPUT_1_SOURCE:
case ARIZONA_SLIMTX5MIX_INPUT_1_VOLUME:
case ARIZONA_SLIMTX5MIX_INPUT_2_SOURCE:
case ARIZONA_SLIMTX5MIX_INPUT_2_VOLUME:
case ARIZONA_SLIMTX5MIX_INPUT_3_SOURCE:
case ARIZONA_SLIMTX5MIX_INPUT_3_VOLUME:
case ARIZONA_SLIMTX5MIX_INPUT_4_SOURCE:
case ARIZONA_SLIMTX5MIX_INPUT_4_VOLUME:
case ARIZONA_SLIMTX6MIX_INPUT_1_SOURCE:
case ARIZONA_SLIMTX6MIX_INPUT_1_VOLUME:
case ARIZONA_SLIMTX6MIX_INPUT_2_SOURCE:
case ARIZONA_SLIMTX6MIX_INPUT_2_VOLUME:
case ARIZONA_SLIMTX6MIX_INPUT_3_SOURCE:
case ARIZONA_SLIMTX6MIX_INPUT_3_VOLUME:
case ARIZONA_SLIMTX6MIX_INPUT_4_SOURCE:
case ARIZONA_SLIMTX6MIX_INPUT_4_VOLUME:
case ARIZONA_SLIMTX7MIX_INPUT_1_SOURCE:
case ARIZONA_SLIMTX7MIX_INPUT_1_VOLUME:
case ARIZONA_SLIMTX7MIX_INPUT_2_SOURCE:
case ARIZONA_SLIMTX7MIX_INPUT_2_VOLUME:
case ARIZONA_SLIMTX7MIX_INPUT_3_SOURCE:
case ARIZONA_SLIMTX7MIX_INPUT_3_VOLUME:
case ARIZONA_SLIMTX7MIX_INPUT_4_SOURCE:
case ARIZONA_SLIMTX7MIX_INPUT_4_VOLUME:
case ARIZONA_SLIMTX8MIX_INPUT_1_SOURCE:
case ARIZONA_SLIMTX8MIX_INPUT_1_VOLUME:
case ARIZONA_SLIMTX8MIX_INPUT_2_SOURCE:
case ARIZONA_SLIMTX8MIX_INPUT_2_VOLUME:
case ARIZONA_SLIMTX8MIX_INPUT_3_SOURCE:
case ARIZONA_SLIMTX8MIX_INPUT_3_VOLUME:
case ARIZONA_SLIMTX8MIX_INPUT_4_SOURCE:
case ARIZONA_SLIMTX8MIX_INPUT_4_VOLUME:
case ARIZONA_EQ1MIX_INPUT_1_SOURCE:
case ARIZONA_EQ1MIX_INPUT_1_VOLUME:
case ARIZONA_EQ1MIX_INPUT_2_SOURCE:
case ARIZONA_EQ1MIX_INPUT_2_VOLUME:
case ARIZONA_EQ1MIX_INPUT_3_SOURCE:
case ARIZONA_EQ1MIX_INPUT_3_VOLUME:
case ARIZONA_EQ1MIX_INPUT_4_SOURCE:
case ARIZONA_EQ1MIX_INPUT_4_VOLUME:
case ARIZONA_EQ2MIX_INPUT_1_SOURCE:
case ARIZONA_EQ2MIX_INPUT_1_VOLUME:
case ARIZONA_EQ2MIX_INPUT_2_SOURCE:
case ARIZONA_EQ2MIX_INPUT_2_VOLUME:
case ARIZONA_EQ2MIX_INPUT_3_SOURCE:
case ARIZONA_EQ2MIX_INPUT_3_VOLUME:
case ARIZONA_EQ2MIX_INPUT_4_SOURCE:
case ARIZONA_EQ2MIX_INPUT_4_VOLUME:
case ARIZONA_EQ3MIX_INPUT_1_SOURCE:
case ARIZONA_EQ3MIX_INPUT_1_VOLUME:
case ARIZONA_EQ3MIX_INPUT_2_SOURCE:
case ARIZONA_EQ3MIX_INPUT_2_VOLUME:
case ARIZONA_EQ3MIX_INPUT_3_SOURCE:
case ARIZONA_EQ3MIX_INPUT_3_VOLUME:
case ARIZONA_EQ3MIX_INPUT_4_SOURCE:
case ARIZONA_EQ3MIX_INPUT_4_VOLUME:
case ARIZONA_EQ4MIX_INPUT_1_SOURCE:
case ARIZONA_EQ4MIX_INPUT_1_VOLUME:
case ARIZONA_EQ4MIX_INPUT_2_SOURCE:
case ARIZONA_EQ4MIX_INPUT_2_VOLUME:
case ARIZONA_EQ4MIX_INPUT_3_SOURCE:
case ARIZONA_EQ4MIX_INPUT_3_VOLUME:
case ARIZONA_EQ4MIX_INPUT_4_SOURCE:
case ARIZONA_EQ4MIX_INPUT_4_VOLUME:
case ARIZONA_DRC1LMIX_INPUT_1_SOURCE:
case ARIZONA_DRC1LMIX_INPUT_1_VOLUME:
case ARIZONA_DRC1LMIX_INPUT_2_SOURCE:
case ARIZONA_DRC1LMIX_INPUT_2_VOLUME:
case ARIZONA_DRC1LMIX_INPUT_3_SOURCE:
case ARIZONA_DRC1LMIX_INPUT_3_VOLUME:
case ARIZONA_DRC1LMIX_INPUT_4_SOURCE:
case ARIZONA_DRC1LMIX_INPUT_4_VOLUME:
case ARIZONA_DRC1RMIX_INPUT_1_SOURCE:
case ARIZONA_DRC1RMIX_INPUT_1_VOLUME:
case ARIZONA_DRC1RMIX_INPUT_2_SOURCE:
case ARIZONA_DRC1RMIX_INPUT_2_VOLUME:
case ARIZONA_DRC1RMIX_INPUT_3_SOURCE:
case ARIZONA_DRC1RMIX_INPUT_3_VOLUME:
case ARIZONA_DRC1RMIX_INPUT_4_SOURCE:
case ARIZONA_DRC1RMIX_INPUT_4_VOLUME:
case ARIZONA_DRC2LMIX_INPUT_1_SOURCE:
case ARIZONA_DRC2LMIX_INPUT_1_VOLUME:
case ARIZONA_DRC2LMIX_INPUT_2_SOURCE:
case ARIZONA_DRC2LMIX_INPUT_2_VOLUME:
case ARIZONA_DRC2LMIX_INPUT_3_SOURCE:
case ARIZONA_DRC2LMIX_INPUT_3_VOLUME:
case ARIZONA_DRC2LMIX_INPUT_4_SOURCE:
case ARIZONA_DRC2LMIX_INPUT_4_VOLUME:
case ARIZONA_DRC2RMIX_INPUT_1_SOURCE:
case ARIZONA_DRC2RMIX_INPUT_1_VOLUME:
case ARIZONA_DRC2RMIX_INPUT_2_SOURCE:
case ARIZONA_DRC2RMIX_INPUT_2_VOLUME:
case ARIZONA_DRC2RMIX_INPUT_3_SOURCE:
case ARIZONA_DRC2RMIX_INPUT_3_VOLUME:
case ARIZONA_DRC2RMIX_INPUT_4_SOURCE:
case ARIZONA_DRC2RMIX_INPUT_4_VOLUME:
case ARIZONA_HPLP1MIX_INPUT_1_SOURCE:
case ARIZONA_HPLP1MIX_INPUT_1_VOLUME:
case ARIZONA_HPLP1MIX_INPUT_2_SOURCE:
case ARIZONA_HPLP1MIX_INPUT_2_VOLUME:
case ARIZONA_HPLP1MIX_INPUT_3_SOURCE:
case ARIZONA_HPLP1MIX_INPUT_3_VOLUME:
case ARIZONA_HPLP1MIX_INPUT_4_SOURCE:
case ARIZONA_HPLP1MIX_INPUT_4_VOLUME:
case ARIZONA_HPLP2MIX_INPUT_1_SOURCE:
case ARIZONA_HPLP2MIX_INPUT_1_VOLUME:
case ARIZONA_HPLP2MIX_INPUT_2_SOURCE:
case ARIZONA_HPLP2MIX_INPUT_2_VOLUME:
case ARIZONA_HPLP2MIX_INPUT_3_SOURCE:
case ARIZONA_HPLP2MIX_INPUT_3_VOLUME:
case ARIZONA_HPLP2MIX_INPUT_4_SOURCE:
case ARIZONA_HPLP2MIX_INPUT_4_VOLUME:
case ARIZONA_HPLP3MIX_INPUT_1_SOURCE:
case ARIZONA_HPLP3MIX_INPUT_1_VOLUME:
case ARIZONA_HPLP3MIX_INPUT_2_SOURCE:
case ARIZONA_HPLP3MIX_INPUT_2_VOLUME:
case ARIZONA_HPLP3MIX_INPUT_3_SOURCE:
case ARIZONA_HPLP3MIX_INPUT_3_VOLUME:
case ARIZONA_HPLP3MIX_INPUT_4_SOURCE:
case ARIZONA_HPLP3MIX_INPUT_4_VOLUME:
case ARIZONA_HPLP4MIX_INPUT_1_SOURCE:
case ARIZONA_HPLP4MIX_INPUT_1_VOLUME:
case ARIZONA_HPLP4MIX_INPUT_2_SOURCE:
case ARIZONA_HPLP4MIX_INPUT_2_VOLUME:
case ARIZONA_HPLP4MIX_INPUT_3_SOURCE:
case ARIZONA_HPLP4MIX_INPUT_3_VOLUME:
case ARIZONA_HPLP4MIX_INPUT_4_SOURCE:
case ARIZONA_HPLP4MIX_INPUT_4_VOLUME:
case ARIZONA_DSP1LMIX_INPUT_1_SOURCE:
case ARIZONA_DSP1LMIX_INPUT_1_VOLUME:
case ARIZONA_DSP1LMIX_INPUT_2_SOURCE:
case ARIZONA_DSP1LMIX_INPUT_2_VOLUME:
case ARIZONA_DSP1LMIX_INPUT_3_SOURCE:
case ARIZONA_DSP1LMIX_INPUT_3_VOLUME:
case ARIZONA_DSP1LMIX_INPUT_4_SOURCE:
case ARIZONA_DSP1LMIX_INPUT_4_VOLUME:
case ARIZONA_DSP1RMIX_INPUT_1_SOURCE:
case ARIZONA_DSP1RMIX_INPUT_1_VOLUME:
case ARIZONA_DSP1RMIX_INPUT_2_SOURCE:
case ARIZONA_DSP1RMIX_INPUT_2_VOLUME:
case ARIZONA_DSP1RMIX_INPUT_3_SOURCE:
case ARIZONA_DSP1RMIX_INPUT_3_VOLUME:
case ARIZONA_DSP1RMIX_INPUT_4_SOURCE:
case ARIZONA_DSP1RMIX_INPUT_4_VOLUME:
case ARIZONA_DSP1AUX1MIX_INPUT_1_SOURCE:
case ARIZONA_DSP1AUX2MIX_INPUT_1_SOURCE:
case ARIZONA_DSP1AUX3MIX_INPUT_1_SOURCE:
case ARIZONA_DSP1AUX4MIX_INPUT_1_SOURCE:
case ARIZONA_DSP1AUX5MIX_INPUT_1_SOURCE:
case ARIZONA_DSP1AUX6MIX_INPUT_1_SOURCE:
case ARIZONA_ASRC1LMIX_INPUT_1_SOURCE:
case ARIZONA_ASRC1RMIX_INPUT_1_SOURCE:
case ARIZONA_ASRC2LMIX_INPUT_1_SOURCE:
case ARIZONA_ASRC2RMIX_INPUT_1_SOURCE:
case ARIZONA_ISRC1DEC1MIX_INPUT_1_SOURCE:
case ARIZONA_ISRC1DEC2MIX_INPUT_1_SOURCE:
case ARIZONA_ISRC1INT1MIX_INPUT_1_SOURCE:
case ARIZONA_ISRC1INT2MIX_INPUT_1_SOURCE:
case ARIZONA_ISRC2DEC1MIX_INPUT_1_SOURCE:
case ARIZONA_ISRC2DEC2MIX_INPUT_1_SOURCE:
case ARIZONA_ISRC2INT1MIX_INPUT_1_SOURCE:
case ARIZONA_ISRC2INT2MIX_INPUT_1_SOURCE:
case ARIZONA_GPIO1_CTRL:
case ARIZONA_GPIO2_CTRL:
case ARIZONA_GPIO3_CTRL:
case ARIZONA_GPIO4_CTRL:
case ARIZONA_GPIO5_CTRL:
case ARIZONA_IRQ_CTRL_1:
case ARIZONA_GPIO_DEBOUNCE_CONFIG:
case ARIZONA_MISC_PAD_CTRL_1:
case ARIZONA_MISC_PAD_CTRL_2:
case ARIZONA_MISC_PAD_CTRL_3:
case ARIZONA_MISC_PAD_CTRL_4:
case ARIZONA_MISC_PAD_CTRL_5:
case ARIZONA_MISC_PAD_CTRL_6:
case ARIZONA_INTERRUPT_STATUS_1:
case ARIZONA_INTERRUPT_STATUS_2:
case ARIZONA_INTERRUPT_STATUS_3:
case ARIZONA_INTERRUPT_STATUS_4:
case ARIZONA_INTERRUPT_STATUS_5:
case ARIZONA_INTERRUPT_STATUS_1_MASK:
case ARIZONA_INTERRUPT_STATUS_2_MASK:
case ARIZONA_INTERRUPT_STATUS_3_MASK:
case ARIZONA_INTERRUPT_STATUS_4_MASK:
case ARIZONA_INTERRUPT_STATUS_5_MASK:
case ARIZONA_INTERRUPT_CONTROL:
case ARIZONA_IRQ2_STATUS_1:
case ARIZONA_IRQ2_STATUS_2:
case ARIZONA_IRQ2_STATUS_3:
case ARIZONA_IRQ2_STATUS_4:
case ARIZONA_IRQ2_STATUS_5:
case ARIZONA_IRQ2_STATUS_1_MASK:
case ARIZONA_IRQ2_STATUS_2_MASK:
case ARIZONA_IRQ2_STATUS_3_MASK:
case ARIZONA_IRQ2_STATUS_4_MASK:
case ARIZONA_IRQ2_STATUS_5_MASK:
case ARIZONA_IRQ2_CONTROL:
case ARIZONA_INTERRUPT_RAW_STATUS_2:
case ARIZONA_INTERRUPT_RAW_STATUS_3:
case ARIZONA_INTERRUPT_RAW_STATUS_4:
case ARIZONA_INTERRUPT_RAW_STATUS_5:
case ARIZONA_INTERRUPT_RAW_STATUS_6:
case ARIZONA_INTERRUPT_RAW_STATUS_7:
case ARIZONA_INTERRUPT_RAW_STATUS_8:
case ARIZONA_IRQ_PIN_STATUS:
case ARIZONA_ADSP2_IRQ0:
case ARIZONA_AOD_WKUP_AND_TRIG:
case ARIZONA_AOD_IRQ1:
case ARIZONA_AOD_IRQ2:
case ARIZONA_AOD_IRQ_MASK_IRQ1:
case ARIZONA_AOD_IRQ_MASK_IRQ2:
case ARIZONA_AOD_IRQ_RAW_STATUS:
case ARIZONA_JACK_DETECT_DEBOUNCE:
case ARIZONA_FX_CTRL1:
case ARIZONA_FX_CTRL2:
case ARIZONA_EQ1_1:
case ARIZONA_EQ1_2:
case ARIZONA_EQ1_3:
case ARIZONA_EQ1_4:
case ARIZONA_EQ1_5:
case ARIZONA_EQ1_6:
case ARIZONA_EQ1_7:
case ARIZONA_EQ1_8:
case ARIZONA_EQ1_9:
case ARIZONA_EQ1_10:
case ARIZONA_EQ1_11:
case ARIZONA_EQ1_12:
case ARIZONA_EQ1_13:
case ARIZONA_EQ1_14:
case ARIZONA_EQ1_15:
case ARIZONA_EQ1_16:
case ARIZONA_EQ1_17:
case ARIZONA_EQ1_18:
case ARIZONA_EQ1_19:
case ARIZONA_EQ1_20:
case ARIZONA_EQ1_21:
case ARIZONA_EQ2_1:
case ARIZONA_EQ2_2:
case ARIZONA_EQ2_3:
case ARIZONA_EQ2_4:
case ARIZONA_EQ2_5:
case ARIZONA_EQ2_6:
case ARIZONA_EQ2_7:
case ARIZONA_EQ2_8:
case ARIZONA_EQ2_9:
case ARIZONA_EQ2_10:
case ARIZONA_EQ2_11:
case ARIZONA_EQ2_12:
case ARIZONA_EQ2_13:
case ARIZONA_EQ2_14:
case ARIZONA_EQ2_15:
case ARIZONA_EQ2_16:
case ARIZONA_EQ2_17:
case ARIZONA_EQ2_18:
case ARIZONA_EQ2_19:
case ARIZONA_EQ2_20:
case ARIZONA_EQ2_21:
case ARIZONA_EQ3_1:
case ARIZONA_EQ3_2:
case ARIZONA_EQ3_3:
case ARIZONA_EQ3_4:
case ARIZONA_EQ3_5:
case ARIZONA_EQ3_6:
case ARIZONA_EQ3_7:
case ARIZONA_EQ3_8:
case ARIZONA_EQ3_9:
case ARIZONA_EQ3_10:
case ARIZONA_EQ3_11:
case ARIZONA_EQ3_12:
case ARIZONA_EQ3_13:
case ARIZONA_EQ3_14:
case ARIZONA_EQ3_15:
case ARIZONA_EQ3_16:
case ARIZONA_EQ3_17:
case ARIZONA_EQ3_18:
case ARIZONA_EQ3_19:
case ARIZONA_EQ3_20:
case ARIZONA_EQ3_21:
case ARIZONA_EQ4_1:
case ARIZONA_EQ4_2:
case ARIZONA_EQ4_3:
case ARIZONA_EQ4_4:
case ARIZONA_EQ4_5:
case ARIZONA_EQ4_6:
case ARIZONA_EQ4_7:
case ARIZONA_EQ4_8:
case ARIZONA_EQ4_9:
case ARIZONA_EQ4_10:
case ARIZONA_EQ4_11:
case ARIZONA_EQ4_12:
case ARIZONA_EQ4_13:
case ARIZONA_EQ4_14:
case ARIZONA_EQ4_15:
case ARIZONA_EQ4_16:
case ARIZONA_EQ4_17:
case ARIZONA_EQ4_18:
case ARIZONA_EQ4_19:
case ARIZONA_EQ4_20:
case ARIZONA_EQ4_21:
case ARIZONA_DRC1_CTRL1:
case ARIZONA_DRC1_CTRL2:
case ARIZONA_DRC1_CTRL3:
case ARIZONA_DRC1_CTRL4:
case ARIZONA_DRC1_CTRL5:
case ARIZONA_DRC2_CTRL1:
case ARIZONA_DRC2_CTRL2:
case ARIZONA_DRC2_CTRL3:
case ARIZONA_DRC2_CTRL4:
case ARIZONA_DRC2_CTRL5:
case ARIZONA_HPLPF1_1:
case ARIZONA_HPLPF1_2:
case ARIZONA_HPLPF2_1:
case ARIZONA_HPLPF2_2:
case ARIZONA_HPLPF3_1:
case ARIZONA_HPLPF3_2:
case ARIZONA_HPLPF4_1:
case ARIZONA_HPLPF4_2:
case ARIZONA_ASRC_ENABLE:
case ARIZONA_ASRC_RATE1:
case ARIZONA_ASRC_RATE2:
case ARIZONA_ISRC_1_CTRL_1:
case ARIZONA_ISRC_1_CTRL_2:
case ARIZONA_ISRC_1_CTRL_3:
case ARIZONA_ISRC_2_CTRL_1:
case ARIZONA_ISRC_2_CTRL_2:
case ARIZONA_ISRC_2_CTRL_3:
case ARIZONA_ISRC_3_CTRL_1:
case ARIZONA_ISRC_3_CTRL_2:
case ARIZONA_ISRC_3_CTRL_3:
case ARIZONA_DSP1_CONTROL_1:
case ARIZONA_DSP1_CLOCKING_1:
case ARIZONA_DSP1_STATUS_1:
case ARIZONA_DSP1_STATUS_2:
case ARIZONA_DSP1_STATUS_3:
case ARIZONA_DSP1_SCRATCH_0:
case ARIZONA_DSP1_SCRATCH_1:
case ARIZONA_DSP1_SCRATCH_2:
case ARIZONA_DSP1_SCRATCH_3:
return true;
default:
if ((reg >= 0x100000 && reg < 0x106000) ||
(reg >= 0x180000 && reg < 0x180800) ||
(reg >= 0x190000 && reg < 0x194800) ||
(reg >= 0x1a8000 && reg < 0x1a9800))
return true;
else
return false;
}
}
static bool wm5102_volatile_register(struct device *dev, unsigned int reg)
{
switch (reg) {
case ARIZONA_SOFTWARE_RESET:
case ARIZONA_DEVICE_REVISION:
case ARIZONA_OUTPUT_STATUS_1:
case ARIZONA_RAW_OUTPUT_STATUS_1:
case ARIZONA_SLIMBUS_RX_PORT_STATUS:
case ARIZONA_SLIMBUS_TX_PORT_STATUS:
case ARIZONA_SAMPLE_RATE_1_STATUS:
case ARIZONA_SAMPLE_RATE_2_STATUS:
case ARIZONA_SAMPLE_RATE_3_STATUS:
case ARIZONA_HAPTICS_STATUS:
case ARIZONA_ASYNC_SAMPLE_RATE_1_STATUS:
case ARIZONA_FLL1_NCO_TEST_0:
case ARIZONA_FLL2_NCO_TEST_0:
case ARIZONA_FX_CTRL2:
case ARIZONA_INTERRUPT_STATUS_1:
case ARIZONA_INTERRUPT_STATUS_2:
case ARIZONA_INTERRUPT_STATUS_3:
case ARIZONA_INTERRUPT_STATUS_4:
case ARIZONA_INTERRUPT_STATUS_5:
case ARIZONA_IRQ2_STATUS_1:
case ARIZONA_IRQ2_STATUS_2:
case ARIZONA_IRQ2_STATUS_3:
case ARIZONA_IRQ2_STATUS_4:
case ARIZONA_IRQ2_STATUS_5:
case ARIZONA_INTERRUPT_RAW_STATUS_2:
case ARIZONA_INTERRUPT_RAW_STATUS_3:
case ARIZONA_INTERRUPT_RAW_STATUS_4:
case ARIZONA_INTERRUPT_RAW_STATUS_5:
case ARIZONA_INTERRUPT_RAW_STATUS_6:
case ARIZONA_INTERRUPT_RAW_STATUS_7:
case ARIZONA_INTERRUPT_RAW_STATUS_8:
case ARIZONA_IRQ_PIN_STATUS:
case ARIZONA_AOD_WKUP_AND_TRIG:
case ARIZONA_AOD_IRQ1:
case ARIZONA_AOD_IRQ2:
case ARIZONA_AOD_IRQ_RAW_STATUS:
case ARIZONA_DSP1_STATUS_1:
case ARIZONA_DSP1_STATUS_2:
case ARIZONA_DSP1_STATUS_3:
case ARIZONA_DSP1_SCRATCH_0:
case ARIZONA_DSP1_SCRATCH_1:
case ARIZONA_DSP1_SCRATCH_2:
case ARIZONA_DSP1_SCRATCH_3:
case ARIZONA_HEADPHONE_DETECT_2:
case ARIZONA_HP_DACVAL:
case ARIZONA_MIC_DETECT_3:
return true;
default:
if ((reg >= 0x100000 && reg < 0x106000) ||
(reg >= 0x180000 && reg < 0x180800) ||
(reg >= 0x190000 && reg < 0x194800) ||
(reg >= 0x1a8000 && reg < 0x1a9800))
return true;
else
return false;
}
}
#define WM5102_MAX_REGISTER 0x1a9800
const struct regmap_config wm5102_spi_regmap = {
.reg_bits = 32,
.pad_bits = 16,
.val_bits = 16,
.max_register = WM5102_MAX_REGISTER,
.readable_reg = wm5102_readable_register,
.volatile_reg = wm5102_volatile_register,
.cache_type = REGCACHE_RBTREE,
.reg_defaults = wm5102_reg_default,
.num_reg_defaults = ARRAY_SIZE(wm5102_reg_default),
};
EXPORT_SYMBOL_GPL(wm5102_spi_regmap);
const struct regmap_config wm5102_i2c_regmap = {
.reg_bits = 32,
.val_bits = 16,
.max_register = WM5102_MAX_REGISTER,
.readable_reg = wm5102_readable_register,
.volatile_reg = wm5102_volatile_register,
.cache_type = REGCACHE_RBTREE,
.reg_defaults = wm5102_reg_default,
.num_reg_defaults = ARRAY_SIZE(wm5102_reg_default),
};
EXPORT_SYMBOL_GPL(wm5102_i2c_regmap);
| gpl-2.0 |
SiddheshK15/android_kernel_cyanogen_msm8916 | arch/arm/mach-omap2/pm44xx.c | 2046 | 6065 | /*
* OMAP4 Power Management Routines
*
* Copyright (C) 2010-2011 Texas Instruments, Inc.
* Rajendra Nayak <rnayak@ti.com>
* Santosh Shilimkar <santosh.shilimkar@ti.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/pm.h>
#include <linux/suspend.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <asm/system_misc.h>
#include "soc.h"
#include "common.h"
#include "clockdomain.h"
#include "powerdomain.h"
#include "pm.h"
struct power_state {
struct powerdomain *pwrdm;
u32 next_state;
#ifdef CONFIG_SUSPEND
u32 saved_state;
u32 saved_logic_state;
#endif
struct list_head node;
};
static LIST_HEAD(pwrst_list);
#ifdef CONFIG_SUSPEND
static int omap4_pm_suspend(void)
{
struct power_state *pwrst;
int state, ret = 0;
u32 cpu_id = smp_processor_id();
/* Save current powerdomain state */
list_for_each_entry(pwrst, &pwrst_list, node) {
pwrst->saved_state = pwrdm_read_next_pwrst(pwrst->pwrdm);
pwrst->saved_logic_state = pwrdm_read_logic_retst(pwrst->pwrdm);
}
/* Set targeted power domain states by suspend */
list_for_each_entry(pwrst, &pwrst_list, node) {
omap_set_pwrdm_state(pwrst->pwrdm, pwrst->next_state);
pwrdm_set_logic_retst(pwrst->pwrdm, PWRDM_POWER_OFF);
}
/*
* For MPUSS to hit power domain retention(CSWR or OSWR),
* CPU0 and CPU1 power domains need to be in OFF or DORMANT state,
* since CPU power domain CSWR is not supported by hardware
* Only master CPU follows suspend path. All other CPUs follow
* CPU hotplug path in system wide suspend. On OMAP4, CPU power
* domain CSWR is not supported by hardware.
* More details can be found in OMAP4430 TRM section 4.3.4.2.
*/
omap4_enter_lowpower(cpu_id, PWRDM_POWER_OFF);
/* Restore next powerdomain state */
list_for_each_entry(pwrst, &pwrst_list, node) {
state = pwrdm_read_prev_pwrst(pwrst->pwrdm);
if (state > pwrst->next_state) {
pr_info("Powerdomain (%s) didn't enter target state %d\n",
pwrst->pwrdm->name, pwrst->next_state);
ret = -1;
}
omap_set_pwrdm_state(pwrst->pwrdm, pwrst->saved_state);
pwrdm_set_logic_retst(pwrst->pwrdm, pwrst->saved_logic_state);
}
if (ret) {
pr_crit("Could not enter target state in pm_suspend\n");
/*
* OMAP4 chip PM currently works only with certain (newer)
* versions of bootloaders. This is due to missing code in the
* kernel to properly reset and initialize some devices.
* Warn the user about the bootloader version being one of the
* possible causes.
* http://www.spinics.net/lists/arm-kernel/msg218641.html
*/
pr_warn("A possible cause could be an old bootloader - try u-boot >= v2012.07\n");
} else {
pr_info("Successfully put all powerdomains to target state\n");
}
return 0;
}
#endif /* CONFIG_SUSPEND */
static int __init pwrdms_setup(struct powerdomain *pwrdm, void *unused)
{
struct power_state *pwrst;
if (!pwrdm->pwrsts)
return 0;
/*
* Skip CPU0 and CPU1 power domains. CPU1 is programmed
* through hotplug path and CPU0 explicitly programmed
* further down in the code path
*/
if (!strncmp(pwrdm->name, "cpu", 3))
return 0;
pwrst = kmalloc(sizeof(struct power_state), GFP_ATOMIC);
if (!pwrst)
return -ENOMEM;
pwrst->pwrdm = pwrdm;
pwrst->next_state = PWRDM_POWER_RET;
list_add(&pwrst->node, &pwrst_list);
return omap_set_pwrdm_state(pwrst->pwrdm, pwrst->next_state);
}
/**
* omap_default_idle - OMAP4 default ilde routine.'
*
* Implements OMAP4 memory, IO ordering requirements which can't be addressed
* with default cpu_do_idle() hook. Used by all CPUs with !CONFIG_CPU_IDLE and
* by secondary CPU with CONFIG_CPU_IDLE.
*/
static void omap_default_idle(void)
{
omap_do_wfi();
}
/**
* omap4_pm_init - Init routine for OMAP4 PM
*
* Initializes all powerdomain and clockdomain target states
* and all PRCM settings.
*/
int __init omap4_pm_init(void)
{
int ret;
struct clockdomain *emif_clkdm, *mpuss_clkdm, *l3_1_clkdm;
struct clockdomain *ducati_clkdm, *l3_2_clkdm;
if (omap_rev() == OMAP4430_REV_ES1_0) {
WARN(1, "Power Management not supported on OMAP4430 ES1.0\n");
return -ENODEV;
}
pr_err("Power Management for TI OMAP4.\n");
/*
* OMAP4 chip PM currently works only with certain (newer)
* versions of bootloaders. This is due to missing code in the
* kernel to properly reset and initialize some devices.
* http://www.spinics.net/lists/arm-kernel/msg218641.html
*/
pr_warn("OMAP4 PM: u-boot >= v2012.07 is required for full PM support\n");
ret = pwrdm_for_each(pwrdms_setup, NULL);
if (ret) {
pr_err("Failed to setup powerdomains\n");
goto err2;
}
/*
* The dynamic dependency between MPUSS -> MEMIF and
* MPUSS -> L4_PER/L3_* and DUCATI -> L3_* doesn't work as
* expected. The hardware recommendation is to enable static
* dependencies for these to avoid system lock ups or random crashes.
*/
mpuss_clkdm = clkdm_lookup("mpuss_clkdm");
emif_clkdm = clkdm_lookup("l3_emif_clkdm");
l3_1_clkdm = clkdm_lookup("l3_1_clkdm");
l3_2_clkdm = clkdm_lookup("l3_2_clkdm");
ducati_clkdm = clkdm_lookup("ducati_clkdm");
if ((!mpuss_clkdm) || (!emif_clkdm) || (!l3_1_clkdm) ||
(!l3_2_clkdm) || (!ducati_clkdm))
goto err2;
ret = clkdm_add_wkdep(mpuss_clkdm, emif_clkdm);
ret |= clkdm_add_wkdep(mpuss_clkdm, l3_1_clkdm);
ret |= clkdm_add_wkdep(mpuss_clkdm, l3_2_clkdm);
ret |= clkdm_add_wkdep(ducati_clkdm, l3_1_clkdm);
ret |= clkdm_add_wkdep(ducati_clkdm, l3_2_clkdm);
if (ret) {
pr_err("Failed to add MPUSS -> L3/EMIF/L4PER, DUCATI -> L3 wakeup dependency\n");
goto err2;
}
ret = omap4_mpuss_init();
if (ret) {
pr_err("Failed to initialise OMAP4 MPUSS\n");
goto err2;
}
(void) clkdm_for_each(omap_pm_clkdms_setup, NULL);
#ifdef CONFIG_SUSPEND
omap_pm_suspend = omap4_pm_suspend;
#endif
/* Overwrite the default cpu_do_idle() */
arm_pm_idle = omap_default_idle;
omap4_idle_init();
err2:
return ret;
}
| gpl-2.0 |
TeamWin/android_kernel_oneplus_msm8974 | net/ceph/mon_client.c | 3326 | 25343 | #include <linux/ceph/ceph_debug.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/random.h>
#include <linux/sched.h>
#include <linux/ceph/mon_client.h>
#include <linux/ceph/libceph.h>
#include <linux/ceph/debugfs.h>
#include <linux/ceph/decode.h>
#include <linux/ceph/auth.h>
/*
* Interact with Ceph monitor cluster. Handle requests for new map
* versions, and periodically resend as needed. Also implement
* statfs() and umount().
*
* A small cluster of Ceph "monitors" are responsible for managing critical
* cluster configuration and state information. An odd number (e.g., 3, 5)
* of cmon daemons use a modified version of the Paxos part-time parliament
* algorithm to manage the MDS map (mds cluster membership), OSD map, and
* list of clients who have mounted the file system.
*
* We maintain an open, active session with a monitor at all times in order to
* receive timely MDSMap updates. We periodically send a keepalive byte on the
* TCP socket to ensure we detect a failure. If the connection does break, we
* randomly hunt for a new monitor. Once the connection is reestablished, we
* resend any outstanding requests.
*/
static const struct ceph_connection_operations mon_con_ops;
static int __validate_auth(struct ceph_mon_client *monc);
/*
* Decode a monmap blob (e.g., during mount).
*/
struct ceph_monmap *ceph_monmap_decode(void *p, void *end)
{
struct ceph_monmap *m = NULL;
int i, err = -EINVAL;
struct ceph_fsid fsid;
u32 epoch, num_mon;
u16 version;
u32 len;
ceph_decode_32_safe(&p, end, len, bad);
ceph_decode_need(&p, end, len, bad);
dout("monmap_decode %p %p len %d\n", p, end, (int)(end-p));
ceph_decode_16_safe(&p, end, version, bad);
ceph_decode_need(&p, end, sizeof(fsid) + 2*sizeof(u32), bad);
ceph_decode_copy(&p, &fsid, sizeof(fsid));
epoch = ceph_decode_32(&p);
num_mon = ceph_decode_32(&p);
ceph_decode_need(&p, end, num_mon*sizeof(m->mon_inst[0]), bad);
if (num_mon >= CEPH_MAX_MON)
goto bad;
m = kmalloc(sizeof(*m) + sizeof(m->mon_inst[0])*num_mon, GFP_NOFS);
if (m == NULL)
return ERR_PTR(-ENOMEM);
m->fsid = fsid;
m->epoch = epoch;
m->num_mon = num_mon;
ceph_decode_copy(&p, m->mon_inst, num_mon*sizeof(m->mon_inst[0]));
for (i = 0; i < num_mon; i++)
ceph_decode_addr(&m->mon_inst[i].addr);
dout("monmap_decode epoch %d, num_mon %d\n", m->epoch,
m->num_mon);
for (i = 0; i < m->num_mon; i++)
dout("monmap_decode mon%d is %s\n", i,
ceph_pr_addr(&m->mon_inst[i].addr.in_addr));
return m;
bad:
dout("monmap_decode failed with %d\n", err);
kfree(m);
return ERR_PTR(err);
}
/*
* return true if *addr is included in the monmap.
*/
int ceph_monmap_contains(struct ceph_monmap *m, struct ceph_entity_addr *addr)
{
int i;
for (i = 0; i < m->num_mon; i++)
if (memcmp(addr, &m->mon_inst[i].addr, sizeof(*addr)) == 0)
return 1;
return 0;
}
/*
* Send an auth request.
*/
static void __send_prepared_auth_request(struct ceph_mon_client *monc, int len)
{
monc->pending_auth = 1;
monc->m_auth->front.iov_len = len;
monc->m_auth->hdr.front_len = cpu_to_le32(len);
ceph_con_revoke(monc->con, monc->m_auth);
ceph_msg_get(monc->m_auth); /* keep our ref */
ceph_con_send(monc->con, monc->m_auth);
}
/*
* Close monitor session, if any.
*/
static void __close_session(struct ceph_mon_client *monc)
{
dout("__close_session closing mon%d\n", monc->cur_mon);
ceph_con_revoke(monc->con, monc->m_auth);
ceph_con_close(monc->con);
monc->cur_mon = -1;
monc->pending_auth = 0;
ceph_auth_reset(monc->auth);
}
/*
* Open a session with a (new) monitor.
*/
static int __open_session(struct ceph_mon_client *monc)
{
char r;
int ret;
if (monc->cur_mon < 0) {
get_random_bytes(&r, 1);
monc->cur_mon = r % monc->monmap->num_mon;
dout("open_session num=%d r=%d -> mon%d\n",
monc->monmap->num_mon, r, monc->cur_mon);
monc->sub_sent = 0;
monc->sub_renew_after = jiffies; /* i.e., expired */
monc->want_next_osdmap = !!monc->want_next_osdmap;
dout("open_session mon%d opening\n", monc->cur_mon);
monc->con->peer_name.type = CEPH_ENTITY_TYPE_MON;
monc->con->peer_name.num = cpu_to_le64(monc->cur_mon);
ceph_con_open(monc->con,
&monc->monmap->mon_inst[monc->cur_mon].addr);
/* initiatiate authentication handshake */
ret = ceph_auth_build_hello(monc->auth,
monc->m_auth->front.iov_base,
monc->m_auth->front_max);
__send_prepared_auth_request(monc, ret);
} else {
dout("open_session mon%d already open\n", monc->cur_mon);
}
return 0;
}
static bool __sub_expired(struct ceph_mon_client *monc)
{
return time_after_eq(jiffies, monc->sub_renew_after);
}
/*
* Reschedule delayed work timer.
*/
static void __schedule_delayed(struct ceph_mon_client *monc)
{
unsigned delay;
if (monc->cur_mon < 0 || __sub_expired(monc))
delay = 10 * HZ;
else
delay = 20 * HZ;
dout("__schedule_delayed after %u\n", delay);
schedule_delayed_work(&monc->delayed_work, delay);
}
/*
* Send subscribe request for mdsmap and/or osdmap.
*/
static void __send_subscribe(struct ceph_mon_client *monc)
{
dout("__send_subscribe sub_sent=%u exp=%u want_osd=%d\n",
(unsigned)monc->sub_sent, __sub_expired(monc),
monc->want_next_osdmap);
if ((__sub_expired(monc) && !monc->sub_sent) ||
monc->want_next_osdmap == 1) {
struct ceph_msg *msg = monc->m_subscribe;
struct ceph_mon_subscribe_item *i;
void *p, *end;
int num;
p = msg->front.iov_base;
end = p + msg->front_max;
num = 1 + !!monc->want_next_osdmap + !!monc->want_mdsmap;
ceph_encode_32(&p, num);
if (monc->want_next_osdmap) {
dout("__send_subscribe to 'osdmap' %u\n",
(unsigned)monc->have_osdmap);
ceph_encode_string(&p, end, "osdmap", 6);
i = p;
i->have = cpu_to_le64(monc->have_osdmap);
i->onetime = 1;
p += sizeof(*i);
monc->want_next_osdmap = 2; /* requested */
}
if (monc->want_mdsmap) {
dout("__send_subscribe to 'mdsmap' %u+\n",
(unsigned)monc->have_mdsmap);
ceph_encode_string(&p, end, "mdsmap", 6);
i = p;
i->have = cpu_to_le64(monc->have_mdsmap);
i->onetime = 0;
p += sizeof(*i);
}
ceph_encode_string(&p, end, "monmap", 6);
i = p;
i->have = 0;
i->onetime = 0;
p += sizeof(*i);
msg->front.iov_len = p - msg->front.iov_base;
msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
ceph_con_revoke(monc->con, msg);
ceph_con_send(monc->con, ceph_msg_get(msg));
monc->sub_sent = jiffies | 1; /* never 0 */
}
}
static void handle_subscribe_ack(struct ceph_mon_client *monc,
struct ceph_msg *msg)
{
unsigned seconds;
struct ceph_mon_subscribe_ack *h = msg->front.iov_base;
if (msg->front.iov_len < sizeof(*h))
goto bad;
seconds = le32_to_cpu(h->duration);
mutex_lock(&monc->mutex);
if (monc->hunting) {
pr_info("mon%d %s session established\n",
monc->cur_mon,
ceph_pr_addr(&monc->con->peer_addr.in_addr));
monc->hunting = false;
}
dout("handle_subscribe_ack after %d seconds\n", seconds);
monc->sub_renew_after = monc->sub_sent + (seconds >> 1)*HZ - 1;
monc->sub_sent = 0;
mutex_unlock(&monc->mutex);
return;
bad:
pr_err("got corrupt subscribe-ack msg\n");
ceph_msg_dump(msg);
}
/*
* Keep track of which maps we have
*/
int ceph_monc_got_mdsmap(struct ceph_mon_client *monc, u32 got)
{
mutex_lock(&monc->mutex);
monc->have_mdsmap = got;
mutex_unlock(&monc->mutex);
return 0;
}
EXPORT_SYMBOL(ceph_monc_got_mdsmap);
int ceph_monc_got_osdmap(struct ceph_mon_client *monc, u32 got)
{
mutex_lock(&monc->mutex);
monc->have_osdmap = got;
monc->want_next_osdmap = 0;
mutex_unlock(&monc->mutex);
return 0;
}
/*
* Register interest in the next osdmap
*/
void ceph_monc_request_next_osdmap(struct ceph_mon_client *monc)
{
dout("request_next_osdmap have %u\n", monc->have_osdmap);
mutex_lock(&monc->mutex);
if (!monc->want_next_osdmap)
monc->want_next_osdmap = 1;
if (monc->want_next_osdmap < 2)
__send_subscribe(monc);
mutex_unlock(&monc->mutex);
}
/*
*
*/
int ceph_monc_open_session(struct ceph_mon_client *monc)
{
mutex_lock(&monc->mutex);
__open_session(monc);
__schedule_delayed(monc);
mutex_unlock(&monc->mutex);
return 0;
}
EXPORT_SYMBOL(ceph_monc_open_session);
/*
* The monitor responds with mount ack indicate mount success. The
* included client ticket allows the client to talk to MDSs and OSDs.
*/
static void ceph_monc_handle_map(struct ceph_mon_client *monc,
struct ceph_msg *msg)
{
struct ceph_client *client = monc->client;
struct ceph_monmap *monmap = NULL, *old = monc->monmap;
void *p, *end;
mutex_lock(&monc->mutex);
dout("handle_monmap\n");
p = msg->front.iov_base;
end = p + msg->front.iov_len;
monmap = ceph_monmap_decode(p, end);
if (IS_ERR(monmap)) {
pr_err("problem decoding monmap, %d\n",
(int)PTR_ERR(monmap));
goto out;
}
if (ceph_check_fsid(monc->client, &monmap->fsid) < 0) {
kfree(monmap);
goto out;
}
client->monc.monmap = monmap;
kfree(old);
if (!client->have_fsid) {
client->have_fsid = true;
mutex_unlock(&monc->mutex);
/*
* do debugfs initialization without mutex to avoid
* creating a locking dependency
*/
ceph_debugfs_client_init(client);
goto out_unlocked;
}
out:
mutex_unlock(&monc->mutex);
out_unlocked:
wake_up_all(&client->auth_wq);
}
/*
* generic requests (e.g., statfs, poolop)
*/
static struct ceph_mon_generic_request *__lookup_generic_req(
struct ceph_mon_client *monc, u64 tid)
{
struct ceph_mon_generic_request *req;
struct rb_node *n = monc->generic_request_tree.rb_node;
while (n) {
req = rb_entry(n, struct ceph_mon_generic_request, node);
if (tid < req->tid)
n = n->rb_left;
else if (tid > req->tid)
n = n->rb_right;
else
return req;
}
return NULL;
}
static void __insert_generic_request(struct ceph_mon_client *monc,
struct ceph_mon_generic_request *new)
{
struct rb_node **p = &monc->generic_request_tree.rb_node;
struct rb_node *parent = NULL;
struct ceph_mon_generic_request *req = NULL;
while (*p) {
parent = *p;
req = rb_entry(parent, struct ceph_mon_generic_request, node);
if (new->tid < req->tid)
p = &(*p)->rb_left;
else if (new->tid > req->tid)
p = &(*p)->rb_right;
else
BUG();
}
rb_link_node(&new->node, parent, p);
rb_insert_color(&new->node, &monc->generic_request_tree);
}
static void release_generic_request(struct kref *kref)
{
struct ceph_mon_generic_request *req =
container_of(kref, struct ceph_mon_generic_request, kref);
if (req->reply)
ceph_msg_put(req->reply);
if (req->request)
ceph_msg_put(req->request);
kfree(req);
}
static void put_generic_request(struct ceph_mon_generic_request *req)
{
kref_put(&req->kref, release_generic_request);
}
static void get_generic_request(struct ceph_mon_generic_request *req)
{
kref_get(&req->kref);
}
static struct ceph_msg *get_generic_reply(struct ceph_connection *con,
struct ceph_msg_header *hdr,
int *skip)
{
struct ceph_mon_client *monc = con->private;
struct ceph_mon_generic_request *req;
u64 tid = le64_to_cpu(hdr->tid);
struct ceph_msg *m;
mutex_lock(&monc->mutex);
req = __lookup_generic_req(monc, tid);
if (!req) {
dout("get_generic_reply %lld dne\n", tid);
*skip = 1;
m = NULL;
} else {
dout("get_generic_reply %lld got %p\n", tid, req->reply);
m = ceph_msg_get(req->reply);
/*
* we don't need to track the connection reading into
* this reply because we only have one open connection
* at a time, ever.
*/
}
mutex_unlock(&monc->mutex);
return m;
}
static int do_generic_request(struct ceph_mon_client *monc,
struct ceph_mon_generic_request *req)
{
int err;
/* register request */
mutex_lock(&monc->mutex);
req->tid = ++monc->last_tid;
req->request->hdr.tid = cpu_to_le64(req->tid);
__insert_generic_request(monc, req);
monc->num_generic_requests++;
ceph_con_send(monc->con, ceph_msg_get(req->request));
mutex_unlock(&monc->mutex);
err = wait_for_completion_interruptible(&req->completion);
mutex_lock(&monc->mutex);
rb_erase(&req->node, &monc->generic_request_tree);
monc->num_generic_requests--;
mutex_unlock(&monc->mutex);
if (!err)
err = req->result;
return err;
}
/*
* statfs
*/
static void handle_statfs_reply(struct ceph_mon_client *monc,
struct ceph_msg *msg)
{
struct ceph_mon_generic_request *req;
struct ceph_mon_statfs_reply *reply = msg->front.iov_base;
u64 tid = le64_to_cpu(msg->hdr.tid);
if (msg->front.iov_len != sizeof(*reply))
goto bad;
dout("handle_statfs_reply %p tid %llu\n", msg, tid);
mutex_lock(&monc->mutex);
req = __lookup_generic_req(monc, tid);
if (req) {
*(struct ceph_statfs *)req->buf = reply->st;
req->result = 0;
get_generic_request(req);
}
mutex_unlock(&monc->mutex);
if (req) {
complete_all(&req->completion);
put_generic_request(req);
}
return;
bad:
pr_err("corrupt generic reply, tid %llu\n", tid);
ceph_msg_dump(msg);
}
/*
* Do a synchronous statfs().
*/
int ceph_monc_do_statfs(struct ceph_mon_client *monc, struct ceph_statfs *buf)
{
struct ceph_mon_generic_request *req;
struct ceph_mon_statfs *h;
int err;
req = kzalloc(sizeof(*req), GFP_NOFS);
if (!req)
return -ENOMEM;
kref_init(&req->kref);
req->buf = buf;
req->buf_len = sizeof(*buf);
init_completion(&req->completion);
err = -ENOMEM;
req->request = ceph_msg_new(CEPH_MSG_STATFS, sizeof(*h), GFP_NOFS,
true);
if (!req->request)
goto out;
req->reply = ceph_msg_new(CEPH_MSG_STATFS_REPLY, 1024, GFP_NOFS,
true);
if (!req->reply)
goto out;
/* fill out request */
h = req->request->front.iov_base;
h->monhdr.have_version = 0;
h->monhdr.session_mon = cpu_to_le16(-1);
h->monhdr.session_mon_tid = 0;
h->fsid = monc->monmap->fsid;
err = do_generic_request(monc, req);
out:
kref_put(&req->kref, release_generic_request);
return err;
}
EXPORT_SYMBOL(ceph_monc_do_statfs);
/*
* pool ops
*/
static int get_poolop_reply_buf(const char *src, size_t src_len,
char *dst, size_t dst_len)
{
u32 buf_len;
if (src_len != sizeof(u32) + dst_len)
return -EINVAL;
buf_len = le32_to_cpu(*(u32 *)src);
if (buf_len != dst_len)
return -EINVAL;
memcpy(dst, src + sizeof(u32), dst_len);
return 0;
}
static void handle_poolop_reply(struct ceph_mon_client *monc,
struct ceph_msg *msg)
{
struct ceph_mon_generic_request *req;
struct ceph_mon_poolop_reply *reply = msg->front.iov_base;
u64 tid = le64_to_cpu(msg->hdr.tid);
if (msg->front.iov_len < sizeof(*reply))
goto bad;
dout("handle_poolop_reply %p tid %llu\n", msg, tid);
mutex_lock(&monc->mutex);
req = __lookup_generic_req(monc, tid);
if (req) {
if (req->buf_len &&
get_poolop_reply_buf(msg->front.iov_base + sizeof(*reply),
msg->front.iov_len - sizeof(*reply),
req->buf, req->buf_len) < 0) {
mutex_unlock(&monc->mutex);
goto bad;
}
req->result = le32_to_cpu(reply->reply_code);
get_generic_request(req);
}
mutex_unlock(&monc->mutex);
if (req) {
complete(&req->completion);
put_generic_request(req);
}
return;
bad:
pr_err("corrupt generic reply, tid %llu\n", tid);
ceph_msg_dump(msg);
}
/*
* Do a synchronous pool op.
*/
int ceph_monc_do_poolop(struct ceph_mon_client *monc, u32 op,
u32 pool, u64 snapid,
char *buf, int len)
{
struct ceph_mon_generic_request *req;
struct ceph_mon_poolop *h;
int err;
req = kzalloc(sizeof(*req), GFP_NOFS);
if (!req)
return -ENOMEM;
kref_init(&req->kref);
req->buf = buf;
req->buf_len = len;
init_completion(&req->completion);
err = -ENOMEM;
req->request = ceph_msg_new(CEPH_MSG_POOLOP, sizeof(*h), GFP_NOFS,
true);
if (!req->request)
goto out;
req->reply = ceph_msg_new(CEPH_MSG_POOLOP_REPLY, 1024, GFP_NOFS,
true);
if (!req->reply)
goto out;
/* fill out request */
req->request->hdr.version = cpu_to_le16(2);
h = req->request->front.iov_base;
h->monhdr.have_version = 0;
h->monhdr.session_mon = cpu_to_le16(-1);
h->monhdr.session_mon_tid = 0;
h->fsid = monc->monmap->fsid;
h->pool = cpu_to_le32(pool);
h->op = cpu_to_le32(op);
h->auid = 0;
h->snapid = cpu_to_le64(snapid);
h->name_len = 0;
err = do_generic_request(monc, req);
out:
kref_put(&req->kref, release_generic_request);
return err;
}
int ceph_monc_create_snapid(struct ceph_mon_client *monc,
u32 pool, u64 *snapid)
{
return ceph_monc_do_poolop(monc, POOL_OP_CREATE_UNMANAGED_SNAP,
pool, 0, (char *)snapid, sizeof(*snapid));
}
EXPORT_SYMBOL(ceph_monc_create_snapid);
int ceph_monc_delete_snapid(struct ceph_mon_client *monc,
u32 pool, u64 snapid)
{
return ceph_monc_do_poolop(monc, POOL_OP_CREATE_UNMANAGED_SNAP,
pool, snapid, 0, 0);
}
/*
* Resend pending generic requests.
*/
static void __resend_generic_request(struct ceph_mon_client *monc)
{
struct ceph_mon_generic_request *req;
struct rb_node *p;
for (p = rb_first(&monc->generic_request_tree); p; p = rb_next(p)) {
req = rb_entry(p, struct ceph_mon_generic_request, node);
ceph_con_revoke(monc->con, req->request);
ceph_con_send(monc->con, ceph_msg_get(req->request));
}
}
/*
* Delayed work. If we haven't mounted yet, retry. Otherwise,
* renew/retry subscription as needed (in case it is timing out, or we
* got an ENOMEM). And keep the monitor connection alive.
*/
static void delayed_work(struct work_struct *work)
{
struct ceph_mon_client *monc =
container_of(work, struct ceph_mon_client, delayed_work.work);
dout("monc delayed_work\n");
mutex_lock(&monc->mutex);
if (monc->hunting) {
__close_session(monc);
__open_session(monc); /* continue hunting */
} else {
ceph_con_keepalive(monc->con);
__validate_auth(monc);
if (monc->auth->ops->is_authenticated(monc->auth))
__send_subscribe(monc);
}
__schedule_delayed(monc);
mutex_unlock(&monc->mutex);
}
/*
* On startup, we build a temporary monmap populated with the IPs
* provided by mount(2).
*/
static int build_initial_monmap(struct ceph_mon_client *monc)
{
struct ceph_options *opt = monc->client->options;
struct ceph_entity_addr *mon_addr = opt->mon_addr;
int num_mon = opt->num_mon;
int i;
/* build initial monmap */
monc->monmap = kzalloc(sizeof(*monc->monmap) +
num_mon*sizeof(monc->monmap->mon_inst[0]),
GFP_KERNEL);
if (!monc->monmap)
return -ENOMEM;
for (i = 0; i < num_mon; i++) {
monc->monmap->mon_inst[i].addr = mon_addr[i];
monc->monmap->mon_inst[i].addr.nonce = 0;
monc->monmap->mon_inst[i].name.type =
CEPH_ENTITY_TYPE_MON;
monc->monmap->mon_inst[i].name.num = cpu_to_le64(i);
}
monc->monmap->num_mon = num_mon;
monc->have_fsid = false;
return 0;
}
int ceph_monc_init(struct ceph_mon_client *monc, struct ceph_client *cl)
{
int err = 0;
dout("init\n");
memset(monc, 0, sizeof(*monc));
monc->client = cl;
monc->monmap = NULL;
mutex_init(&monc->mutex);
err = build_initial_monmap(monc);
if (err)
goto out;
/* connection */
monc->con = kmalloc(sizeof(*monc->con), GFP_KERNEL);
if (!monc->con)
goto out_monmap;
ceph_con_init(monc->client->msgr, monc->con);
monc->con->private = monc;
monc->con->ops = &mon_con_ops;
/* authentication */
monc->auth = ceph_auth_init(cl->options->name,
cl->options->key);
if (IS_ERR(monc->auth)) {
err = PTR_ERR(monc->auth);
goto out_con;
}
monc->auth->want_keys =
CEPH_ENTITY_TYPE_AUTH | CEPH_ENTITY_TYPE_MON |
CEPH_ENTITY_TYPE_OSD | CEPH_ENTITY_TYPE_MDS;
/* msgs */
err = -ENOMEM;
monc->m_subscribe_ack = ceph_msg_new(CEPH_MSG_MON_SUBSCRIBE_ACK,
sizeof(struct ceph_mon_subscribe_ack),
GFP_NOFS, true);
if (!monc->m_subscribe_ack)
goto out_auth;
monc->m_subscribe = ceph_msg_new(CEPH_MSG_MON_SUBSCRIBE, 96, GFP_NOFS,
true);
if (!monc->m_subscribe)
goto out_subscribe_ack;
monc->m_auth_reply = ceph_msg_new(CEPH_MSG_AUTH_REPLY, 4096, GFP_NOFS,
true);
if (!monc->m_auth_reply)
goto out_subscribe;
monc->m_auth = ceph_msg_new(CEPH_MSG_AUTH, 4096, GFP_NOFS, true);
monc->pending_auth = 0;
if (!monc->m_auth)
goto out_auth_reply;
monc->cur_mon = -1;
monc->hunting = true;
monc->sub_renew_after = jiffies;
monc->sub_sent = 0;
INIT_DELAYED_WORK(&monc->delayed_work, delayed_work);
monc->generic_request_tree = RB_ROOT;
monc->num_generic_requests = 0;
monc->last_tid = 0;
monc->have_mdsmap = 0;
monc->have_osdmap = 0;
monc->want_next_osdmap = 1;
return 0;
out_auth_reply:
ceph_msg_put(monc->m_auth_reply);
out_subscribe:
ceph_msg_put(monc->m_subscribe);
out_subscribe_ack:
ceph_msg_put(monc->m_subscribe_ack);
out_auth:
ceph_auth_destroy(monc->auth);
out_con:
monc->con->ops->put(monc->con);
out_monmap:
kfree(monc->monmap);
out:
return err;
}
EXPORT_SYMBOL(ceph_monc_init);
void ceph_monc_stop(struct ceph_mon_client *monc)
{
dout("stop\n");
cancel_delayed_work_sync(&monc->delayed_work);
mutex_lock(&monc->mutex);
__close_session(monc);
monc->con->private = NULL;
monc->con->ops->put(monc->con);
monc->con = NULL;
mutex_unlock(&monc->mutex);
ceph_auth_destroy(monc->auth);
ceph_msg_put(monc->m_auth);
ceph_msg_put(monc->m_auth_reply);
ceph_msg_put(monc->m_subscribe);
ceph_msg_put(monc->m_subscribe_ack);
kfree(monc->monmap);
}
EXPORT_SYMBOL(ceph_monc_stop);
static void handle_auth_reply(struct ceph_mon_client *monc,
struct ceph_msg *msg)
{
int ret;
int was_auth = 0;
mutex_lock(&monc->mutex);
if (monc->auth->ops)
was_auth = monc->auth->ops->is_authenticated(monc->auth);
monc->pending_auth = 0;
ret = ceph_handle_auth_reply(monc->auth, msg->front.iov_base,
msg->front.iov_len,
monc->m_auth->front.iov_base,
monc->m_auth->front_max);
if (ret < 0) {
monc->client->auth_err = ret;
wake_up_all(&monc->client->auth_wq);
} else if (ret > 0) {
__send_prepared_auth_request(monc, ret);
} else if (!was_auth && monc->auth->ops->is_authenticated(monc->auth)) {
dout("authenticated, starting session\n");
monc->client->msgr->inst.name.type = CEPH_ENTITY_TYPE_CLIENT;
monc->client->msgr->inst.name.num =
cpu_to_le64(monc->auth->global_id);
__send_subscribe(monc);
__resend_generic_request(monc);
}
mutex_unlock(&monc->mutex);
}
static int __validate_auth(struct ceph_mon_client *monc)
{
int ret;
if (monc->pending_auth)
return 0;
ret = ceph_build_auth(monc->auth, monc->m_auth->front.iov_base,
monc->m_auth->front_max);
if (ret <= 0)
return ret; /* either an error, or no need to authenticate */
__send_prepared_auth_request(monc, ret);
return 0;
}
int ceph_monc_validate_auth(struct ceph_mon_client *monc)
{
int ret;
mutex_lock(&monc->mutex);
ret = __validate_auth(monc);
mutex_unlock(&monc->mutex);
return ret;
}
EXPORT_SYMBOL(ceph_monc_validate_auth);
/*
* handle incoming message
*/
static void dispatch(struct ceph_connection *con, struct ceph_msg *msg)
{
struct ceph_mon_client *monc = con->private;
int type = le16_to_cpu(msg->hdr.type);
if (!monc)
return;
switch (type) {
case CEPH_MSG_AUTH_REPLY:
handle_auth_reply(monc, msg);
break;
case CEPH_MSG_MON_SUBSCRIBE_ACK:
handle_subscribe_ack(monc, msg);
break;
case CEPH_MSG_STATFS_REPLY:
handle_statfs_reply(monc, msg);
break;
case CEPH_MSG_POOLOP_REPLY:
handle_poolop_reply(monc, msg);
break;
case CEPH_MSG_MON_MAP:
ceph_monc_handle_map(monc, msg);
break;
case CEPH_MSG_OSD_MAP:
ceph_osdc_handle_map(&monc->client->osdc, msg);
break;
default:
/* can the chained handler handle it? */
if (monc->client->extra_mon_dispatch &&
monc->client->extra_mon_dispatch(monc->client, msg) == 0)
break;
pr_err("received unknown message type %d %s\n", type,
ceph_msg_type_name(type));
}
ceph_msg_put(msg);
}
/*
* Allocate memory for incoming message
*/
static struct ceph_msg *mon_alloc_msg(struct ceph_connection *con,
struct ceph_msg_header *hdr,
int *skip)
{
struct ceph_mon_client *monc = con->private;
int type = le16_to_cpu(hdr->type);
int front_len = le32_to_cpu(hdr->front_len);
struct ceph_msg *m = NULL;
*skip = 0;
switch (type) {
case CEPH_MSG_MON_SUBSCRIBE_ACK:
m = ceph_msg_get(monc->m_subscribe_ack);
break;
case CEPH_MSG_POOLOP_REPLY:
case CEPH_MSG_STATFS_REPLY:
return get_generic_reply(con, hdr, skip);
case CEPH_MSG_AUTH_REPLY:
m = ceph_msg_get(monc->m_auth_reply);
break;
case CEPH_MSG_MON_MAP:
case CEPH_MSG_MDS_MAP:
case CEPH_MSG_OSD_MAP:
m = ceph_msg_new(type, front_len, GFP_NOFS, false);
break;
}
if (!m) {
pr_info("alloc_msg unknown type %d\n", type);
*skip = 1;
}
return m;
}
/*
* If the monitor connection resets, pick a new monitor and resubmit
* any pending requests.
*/
static void mon_fault(struct ceph_connection *con)
{
struct ceph_mon_client *monc = con->private;
if (!monc)
return;
dout("mon_fault\n");
mutex_lock(&monc->mutex);
if (!con->private)
goto out;
if (!monc->hunting)
pr_info("mon%d %s session lost, "
"hunting for new mon\n", monc->cur_mon,
ceph_pr_addr(&monc->con->peer_addr.in_addr));
__close_session(monc);
if (!monc->hunting) {
/* start hunting */
monc->hunting = true;
__open_session(monc);
} else {
/* already hunting, let's wait a bit */
__schedule_delayed(monc);
}
out:
mutex_unlock(&monc->mutex);
}
static const struct ceph_connection_operations mon_con_ops = {
.get = ceph_con_get,
.put = ceph_con_put,
.dispatch = dispatch,
.fault = mon_fault,
.alloc_msg = mon_alloc_msg,
};
| gpl-2.0 |
fjtrujy/barrier-breaker-openwrt | target/linux/adm5120/image/lzma-loader/src/LzmaDecode.c | 3326 | 15775 | /*
LzmaDecode.c
LZMA Decoder (optimized for Speed version)
LZMA SDK 4.40 Copyright (c) 1999-2006 Igor Pavlov (2006-05-01)
http://www.7-zip.org/
LZMA SDK is licensed under two licenses:
1) GNU Lesser General Public License (GNU LGPL)
2) Common Public License (CPL)
It means that you can select one of these two licenses and
follow rules of that license.
SPECIAL EXCEPTION:
Igor Pavlov, as the author of this Code, expressly permits you to
statically or dynamically link your Code (or bind by name) to the
interfaces of this file without subjecting your linked Code to the
terms of the CPL or GNU LGPL. Any modifications or additions
to this file, however, are subject to the LGPL or CPL terms.
*/
#include "LzmaDecode.h"
#define kNumTopBits 24
#define kTopValue ((UInt32)1 << kNumTopBits)
#define kNumBitModelTotalBits 11
#define kBitModelTotal (1 << kNumBitModelTotalBits)
#define kNumMoveBits 5
#define RC_READ_BYTE (*Buffer++)
#define RC_INIT2 Code = 0; Range = 0xFFFFFFFF; \
{ int i; for(i = 0; i < 5; i++) { RC_TEST; Code = (Code << 8) | RC_READ_BYTE; }}
#ifdef _LZMA_IN_CB
#define RC_TEST { if (Buffer == BufferLim) \
{ SizeT size; int result = InCallback->Read(InCallback, &Buffer, &size); if (result != LZMA_RESULT_OK) return result; \
BufferLim = Buffer + size; if (size == 0) return LZMA_RESULT_DATA_ERROR; }}
#define RC_INIT Buffer = BufferLim = 0; RC_INIT2
#else
#define RC_TEST { if (Buffer == BufferLim) return LZMA_RESULT_DATA_ERROR; }
#define RC_INIT(buffer, bufferSize) Buffer = buffer; BufferLim = buffer + bufferSize; RC_INIT2
#endif
#define RC_NORMALIZE if (Range < kTopValue) { RC_TEST; Range <<= 8; Code = (Code << 8) | RC_READ_BYTE; }
#define IfBit0(p) RC_NORMALIZE; bound = (Range >> kNumBitModelTotalBits) * *(p); if (Code < bound)
#define UpdateBit0(p) Range = bound; *(p) += (kBitModelTotal - *(p)) >> kNumMoveBits;
#define UpdateBit1(p) Range -= bound; Code -= bound; *(p) -= (*(p)) >> kNumMoveBits;
#define RC_GET_BIT2(p, mi, A0, A1) IfBit0(p) \
{ UpdateBit0(p); mi <<= 1; A0; } else \
{ UpdateBit1(p); mi = (mi + mi) + 1; A1; }
#define RC_GET_BIT(p, mi) RC_GET_BIT2(p, mi, ; , ;)
#define RangeDecoderBitTreeDecode(probs, numLevels, res) \
{ int i = numLevels; res = 1; \
do { CProb *p = probs + res; RC_GET_BIT(p, res) } while(--i != 0); \
res -= (1 << numLevels); }
#define kNumPosBitsMax 4
#define kNumPosStatesMax (1 << kNumPosBitsMax)
#define kLenNumLowBits 3
#define kLenNumLowSymbols (1 << kLenNumLowBits)
#define kLenNumMidBits 3
#define kLenNumMidSymbols (1 << kLenNumMidBits)
#define kLenNumHighBits 8
#define kLenNumHighSymbols (1 << kLenNumHighBits)
#define LenChoice 0
#define LenChoice2 (LenChoice + 1)
#define LenLow (LenChoice2 + 1)
#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
#define kNumStates 12
#define kNumLitStates 7
#define kStartPosModelIndex 4
#define kEndPosModelIndex 14
#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
#define kNumPosSlotBits 6
#define kNumLenToPosStates 4
#define kNumAlignBits 4
#define kAlignTableSize (1 << kNumAlignBits)
#define kMatchMinLen 2
#define IsMatch 0
#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
#define IsRepG0 (IsRep + kNumStates)
#define IsRepG1 (IsRepG0 + kNumStates)
#define IsRepG2 (IsRepG1 + kNumStates)
#define IsRep0Long (IsRepG2 + kNumStates)
#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
#define LenCoder (Align + kAlignTableSize)
#define RepLenCoder (LenCoder + kNumLenProbs)
#define Literal (RepLenCoder + kNumLenProbs)
#if Literal != LZMA_BASE_SIZE
StopCompilingDueBUG
#endif
int LzmaDecodeProperties(CLzmaProperties *propsRes, const unsigned char *propsData, int size)
{
unsigned char prop0;
if (size < LZMA_PROPERTIES_SIZE)
return LZMA_RESULT_DATA_ERROR;
prop0 = propsData[0];
if (prop0 >= (9 * 5 * 5))
return LZMA_RESULT_DATA_ERROR;
{
for (propsRes->pb = 0; prop0 >= (9 * 5); propsRes->pb++, prop0 -= (9 * 5));
for (propsRes->lp = 0; prop0 >= 9; propsRes->lp++, prop0 -= 9);
propsRes->lc = prop0;
/*
unsigned char remainder = (unsigned char)(prop0 / 9);
propsRes->lc = prop0 % 9;
propsRes->pb = remainder / 5;
propsRes->lp = remainder % 5;
*/
}
#ifdef _LZMA_OUT_READ
{
int i;
propsRes->DictionarySize = 0;
for (i = 0; i < 4; i++)
propsRes->DictionarySize += (UInt32)(propsData[1 + i]) << (i * 8);
if (propsRes->DictionarySize == 0)
propsRes->DictionarySize = 1;
}
#endif
return LZMA_RESULT_OK;
}
#define kLzmaStreamWasFinishedId (-1)
int LzmaDecode(CLzmaDecoderState *vs,
#ifdef _LZMA_IN_CB
ILzmaInCallback *InCallback,
#else
const unsigned char *inStream, SizeT inSize, SizeT *inSizeProcessed,
#endif
unsigned char *outStream, SizeT outSize, SizeT *outSizeProcessed)
{
CProb *p = vs->Probs;
SizeT nowPos = 0;
Byte previousByte = 0;
UInt32 posStateMask = (1 << (vs->Properties.pb)) - 1;
UInt32 literalPosMask = (1 << (vs->Properties.lp)) - 1;
int lc = vs->Properties.lc;
#ifdef _LZMA_OUT_READ
UInt32 Range = vs->Range;
UInt32 Code = vs->Code;
#ifdef _LZMA_IN_CB
const Byte *Buffer = vs->Buffer;
const Byte *BufferLim = vs->BufferLim;
#else
const Byte *Buffer = inStream;
const Byte *BufferLim = inStream + inSize;
#endif
int state = vs->State;
UInt32 rep0 = vs->Reps[0], rep1 = vs->Reps[1], rep2 = vs->Reps[2], rep3 = vs->Reps[3];
int len = vs->RemainLen;
UInt32 globalPos = vs->GlobalPos;
UInt32 distanceLimit = vs->DistanceLimit;
Byte *dictionary = vs->Dictionary;
UInt32 dictionarySize = vs->Properties.DictionarySize;
UInt32 dictionaryPos = vs->DictionaryPos;
Byte tempDictionary[4];
#ifndef _LZMA_IN_CB
*inSizeProcessed = 0;
#endif
*outSizeProcessed = 0;
if (len == kLzmaStreamWasFinishedId)
return LZMA_RESULT_OK;
if (dictionarySize == 0)
{
dictionary = tempDictionary;
dictionarySize = 1;
tempDictionary[0] = vs->TempDictionary[0];
}
if (len == kLzmaNeedInitId)
{
{
UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (lc + vs->Properties.lp));
UInt32 i;
for (i = 0; i < numProbs; i++)
p[i] = kBitModelTotal >> 1;
rep0 = rep1 = rep2 = rep3 = 1;
state = 0;
globalPos = 0;
distanceLimit = 0;
dictionaryPos = 0;
dictionary[dictionarySize - 1] = 0;
#ifdef _LZMA_IN_CB
RC_INIT;
#else
RC_INIT(inStream, inSize);
#endif
}
len = 0;
}
while(len != 0 && nowPos < outSize)
{
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
outStream[nowPos++] = dictionary[dictionaryPos] = dictionary[pos];
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
len--;
}
if (dictionaryPos == 0)
previousByte = dictionary[dictionarySize - 1];
else
previousByte = dictionary[dictionaryPos - 1];
#else /* if !_LZMA_OUT_READ */
int state = 0;
UInt32 rep0 = 1, rep1 = 1, rep2 = 1, rep3 = 1;
int len = 0;
const Byte *Buffer;
const Byte *BufferLim;
UInt32 Range;
UInt32 Code;
#ifndef _LZMA_IN_CB
*inSizeProcessed = 0;
#endif
*outSizeProcessed = 0;
{
UInt32 i;
UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (lc + vs->Properties.lp));
for (i = 0; i < numProbs; i++)
p[i] = kBitModelTotal >> 1;
}
#ifdef _LZMA_IN_CB
RC_INIT;
#else
RC_INIT(inStream, inSize);
#endif
#endif /* _LZMA_OUT_READ */
while(nowPos < outSize)
{
CProb *prob;
UInt32 bound;
int posState = (int)(
(nowPos
#ifdef _LZMA_OUT_READ
+ globalPos
#endif
)
& posStateMask);
prob = p + IsMatch + (state << kNumPosBitsMax) + posState;
IfBit0(prob)
{
int symbol = 1;
UpdateBit0(prob)
prob = p + Literal + (LZMA_LIT_SIZE *
(((
(nowPos
#ifdef _LZMA_OUT_READ
+ globalPos
#endif
)
& literalPosMask) << lc) + (previousByte >> (8 - lc))));
if (state >= kNumLitStates)
{
int matchByte;
#ifdef _LZMA_OUT_READ
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
matchByte = dictionary[pos];
#else
matchByte = outStream[nowPos - rep0];
#endif
do
{
int bit;
CProb *probLit;
matchByte <<= 1;
bit = (matchByte & 0x100);
probLit = prob + 0x100 + bit + symbol;
RC_GET_BIT2(probLit, symbol, if (bit != 0) break, if (bit == 0) break)
}
while (symbol < 0x100);
}
while (symbol < 0x100)
{
CProb *probLit = prob + symbol;
RC_GET_BIT(probLit, symbol)
}
previousByte = (Byte)symbol;
outStream[nowPos++] = previousByte;
#ifdef _LZMA_OUT_READ
if (distanceLimit < dictionarySize)
distanceLimit++;
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
#endif
if (state < 4) state = 0;
else if (state < 10) state -= 3;
else state -= 6;
}
else
{
UpdateBit1(prob);
prob = p + IsRep + state;
IfBit0(prob)
{
UpdateBit0(prob);
rep3 = rep2;
rep2 = rep1;
rep1 = rep0;
state = state < kNumLitStates ? 0 : 3;
prob = p + LenCoder;
}
else
{
UpdateBit1(prob);
prob = p + IsRepG0 + state;
IfBit0(prob)
{
UpdateBit0(prob);
prob = p + IsRep0Long + (state << kNumPosBitsMax) + posState;
IfBit0(prob)
{
#ifdef _LZMA_OUT_READ
UInt32 pos;
#endif
UpdateBit0(prob);
#ifdef _LZMA_OUT_READ
if (distanceLimit == 0)
#else
if (nowPos == 0)
#endif
return LZMA_RESULT_DATA_ERROR;
state = state < kNumLitStates ? 9 : 11;
#ifdef _LZMA_OUT_READ
pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
previousByte = dictionary[pos];
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
#else
previousByte = outStream[nowPos - rep0];
#endif
outStream[nowPos++] = previousByte;
#ifdef _LZMA_OUT_READ
if (distanceLimit < dictionarySize)
distanceLimit++;
#endif
continue;
}
else
{
UpdateBit1(prob);
}
}
else
{
UInt32 distance;
UpdateBit1(prob);
prob = p + IsRepG1 + state;
IfBit0(prob)
{
UpdateBit0(prob);
distance = rep1;
}
else
{
UpdateBit1(prob);
prob = p + IsRepG2 + state;
IfBit0(prob)
{
UpdateBit0(prob);
distance = rep2;
}
else
{
UpdateBit1(prob);
distance = rep3;
rep3 = rep2;
}
rep2 = rep1;
}
rep1 = rep0;
rep0 = distance;
}
state = state < kNumLitStates ? 8 : 11;
prob = p + RepLenCoder;
}
{
int numBits, offset;
CProb *probLen = prob + LenChoice;
IfBit0(probLen)
{
UpdateBit0(probLen);
probLen = prob + LenLow + (posState << kLenNumLowBits);
offset = 0;
numBits = kLenNumLowBits;
}
else
{
UpdateBit1(probLen);
probLen = prob + LenChoice2;
IfBit0(probLen)
{
UpdateBit0(probLen);
probLen = prob + LenMid + (posState << kLenNumMidBits);
offset = kLenNumLowSymbols;
numBits = kLenNumMidBits;
}
else
{
UpdateBit1(probLen);
probLen = prob + LenHigh;
offset = kLenNumLowSymbols + kLenNumMidSymbols;
numBits = kLenNumHighBits;
}
}
RangeDecoderBitTreeDecode(probLen, numBits, len);
len += offset;
}
if (state < 4)
{
int posSlot;
state += kNumLitStates;
prob = p + PosSlot +
((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) <<
kNumPosSlotBits);
RangeDecoderBitTreeDecode(prob, kNumPosSlotBits, posSlot);
if (posSlot >= kStartPosModelIndex)
{
int numDirectBits = ((posSlot >> 1) - 1);
rep0 = (2 | ((UInt32)posSlot & 1));
if (posSlot < kEndPosModelIndex)
{
rep0 <<= numDirectBits;
prob = p + SpecPos + rep0 - posSlot - 1;
}
else
{
numDirectBits -= kNumAlignBits;
do
{
RC_NORMALIZE
Range >>= 1;
rep0 <<= 1;
if (Code >= Range)
{
Code -= Range;
rep0 |= 1;
}
}
while (--numDirectBits != 0);
prob = p + Align;
rep0 <<= kNumAlignBits;
numDirectBits = kNumAlignBits;
}
{
int i = 1;
int mi = 1;
do
{
CProb *prob3 = prob + mi;
RC_GET_BIT2(prob3, mi, ; , rep0 |= i);
i <<= 1;
}
while(--numDirectBits != 0);
}
}
else
rep0 = posSlot;
if (++rep0 == (UInt32)(0))
{
/* it's for stream version */
len = kLzmaStreamWasFinishedId;
break;
}
}
len += kMatchMinLen;
#ifdef _LZMA_OUT_READ
if (rep0 > distanceLimit)
#else
if (rep0 > nowPos)
#endif
return LZMA_RESULT_DATA_ERROR;
#ifdef _LZMA_OUT_READ
if (dictionarySize - distanceLimit > (UInt32)len)
distanceLimit += len;
else
distanceLimit = dictionarySize;
#endif
do
{
#ifdef _LZMA_OUT_READ
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
previousByte = dictionary[pos];
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
#else
previousByte = outStream[nowPos - rep0];
#endif
len--;
outStream[nowPos++] = previousByte;
}
while(len != 0 && nowPos < outSize);
}
}
RC_NORMALIZE;
#ifdef _LZMA_OUT_READ
vs->Range = Range;
vs->Code = Code;
vs->DictionaryPos = dictionaryPos;
vs->GlobalPos = globalPos + (UInt32)nowPos;
vs->DistanceLimit = distanceLimit;
vs->Reps[0] = rep0;
vs->Reps[1] = rep1;
vs->Reps[2] = rep2;
vs->Reps[3] = rep3;
vs->State = state;
vs->RemainLen = len;
vs->TempDictionary[0] = tempDictionary[0];
#endif
#ifdef _LZMA_IN_CB
vs->Buffer = Buffer;
vs->BufferLim = BufferLim;
#else
*inSizeProcessed = (SizeT)(Buffer - inStream);
#endif
*outSizeProcessed = nowPos;
return LZMA_RESULT_OK;
}
| gpl-2.0 |
knightkill3r/FalcoKernel | drivers/scsi/scsi_transport_spi.c | 3582 | 43947 | /*
* Parallel SCSI (SPI) transport specific attributes exported to sysfs.
*
* Copyright (c) 2003 Silicon Graphics, Inc. All rights reserved.
* Copyright (c) 2004, 2005 James Bottomley <James.Bottomley@SteelEye.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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/ctype.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/workqueue.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
#include <linux/slab.h>
#include <scsi/scsi.h>
#include "scsi_priv.h"
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_transport.h>
#include <scsi/scsi_transport_spi.h>
#define SPI_NUM_ATTRS 14 /* increase this if you add attributes */
#define SPI_OTHER_ATTRS 1 /* Increase this if you add "always
* on" attributes */
#define SPI_HOST_ATTRS 1
#define SPI_MAX_ECHO_BUFFER_SIZE 4096
#define DV_LOOPS 3
#define DV_TIMEOUT (10*HZ)
#define DV_RETRIES 3 /* should only need at most
* two cc/ua clears */
/* Our blacklist flags */
enum {
SPI_BLIST_NOIUS = 0x1,
};
/* blacklist table, modelled on scsi_devinfo.c */
static struct {
char *vendor;
char *model;
unsigned flags;
} spi_static_device_list[] __initdata = {
{"HP", "Ultrium 3-SCSI", SPI_BLIST_NOIUS },
{"IBM", "ULTRIUM-TD3", SPI_BLIST_NOIUS },
{NULL, NULL, 0}
};
/* Private data accessors (keep these out of the header file) */
#define spi_dv_in_progress(x) (((struct spi_transport_attrs *)&(x)->starget_data)->dv_in_progress)
#define spi_dv_mutex(x) (((struct spi_transport_attrs *)&(x)->starget_data)->dv_mutex)
struct spi_internal {
struct scsi_transport_template t;
struct spi_function_template *f;
};
#define to_spi_internal(tmpl) container_of(tmpl, struct spi_internal, t)
static const int ppr_to_ps[] = {
/* The PPR values 0-6 are reserved, fill them in when
* the committee defines them */
-1, /* 0x00 */
-1, /* 0x01 */
-1, /* 0x02 */
-1, /* 0x03 */
-1, /* 0x04 */
-1, /* 0x05 */
-1, /* 0x06 */
3125, /* 0x07 */
6250, /* 0x08 */
12500, /* 0x09 */
25000, /* 0x0a */
30300, /* 0x0b */
50000, /* 0x0c */
};
/* The PPR values at which you calculate the period in ns by multiplying
* by 4 */
#define SPI_STATIC_PPR 0x0c
static int sprint_frac(char *dest, int value, int denom)
{
int frac = value % denom;
int result = sprintf(dest, "%d", value / denom);
if (frac == 0)
return result;
dest[result++] = '.';
do {
denom /= 10;
sprintf(dest + result, "%d", frac / denom);
result++;
frac %= denom;
} while (frac);
dest[result++] = '\0';
return result;
}
static int spi_execute(struct scsi_device *sdev, const void *cmd,
enum dma_data_direction dir,
void *buffer, unsigned bufflen,
struct scsi_sense_hdr *sshdr)
{
int i, result;
unsigned char sense[SCSI_SENSE_BUFFERSIZE];
for(i = 0; i < DV_RETRIES; i++) {
result = scsi_execute(sdev, cmd, dir, buffer, bufflen,
sense, DV_TIMEOUT, /* retries */ 1,
REQ_FAILFAST_DEV |
REQ_FAILFAST_TRANSPORT |
REQ_FAILFAST_DRIVER,
NULL);
if (driver_byte(result) & DRIVER_SENSE) {
struct scsi_sense_hdr sshdr_tmp;
if (!sshdr)
sshdr = &sshdr_tmp;
if (scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE,
sshdr)
&& sshdr->sense_key == UNIT_ATTENTION)
continue;
}
break;
}
return result;
}
static struct {
enum spi_signal_type value;
char *name;
} signal_types[] = {
{ SPI_SIGNAL_UNKNOWN, "unknown" },
{ SPI_SIGNAL_SE, "SE" },
{ SPI_SIGNAL_LVD, "LVD" },
{ SPI_SIGNAL_HVD, "HVD" },
};
static inline const char *spi_signal_to_string(enum spi_signal_type type)
{
int i;
for (i = 0; i < ARRAY_SIZE(signal_types); i++) {
if (type == signal_types[i].value)
return signal_types[i].name;
}
return NULL;
}
static inline enum spi_signal_type spi_signal_to_value(const char *name)
{
int i, len;
for (i = 0; i < ARRAY_SIZE(signal_types); i++) {
len = strlen(signal_types[i].name);
if (strncmp(name, signal_types[i].name, len) == 0 &&
(name[len] == '\n' || name[len] == '\0'))
return signal_types[i].value;
}
return SPI_SIGNAL_UNKNOWN;
}
static int spi_host_setup(struct transport_container *tc, struct device *dev,
struct device *cdev)
{
struct Scsi_Host *shost = dev_to_shost(dev);
spi_signalling(shost) = SPI_SIGNAL_UNKNOWN;
return 0;
}
static int spi_host_configure(struct transport_container *tc,
struct device *dev,
struct device *cdev);
static DECLARE_TRANSPORT_CLASS(spi_host_class,
"spi_host",
spi_host_setup,
NULL,
spi_host_configure);
static int spi_host_match(struct attribute_container *cont,
struct device *dev)
{
struct Scsi_Host *shost;
if (!scsi_is_host_device(dev))
return 0;
shost = dev_to_shost(dev);
if (!shost->transportt || shost->transportt->host_attrs.ac.class
!= &spi_host_class.class)
return 0;
return &shost->transportt->host_attrs.ac == cont;
}
static int spi_target_configure(struct transport_container *tc,
struct device *dev,
struct device *cdev);
static int spi_device_configure(struct transport_container *tc,
struct device *dev,
struct device *cdev)
{
struct scsi_device *sdev = to_scsi_device(dev);
struct scsi_target *starget = sdev->sdev_target;
unsigned bflags = scsi_get_device_flags_keyed(sdev, &sdev->inquiry[8],
&sdev->inquiry[16],
SCSI_DEVINFO_SPI);
/* Populate the target capability fields with the values
* gleaned from the device inquiry */
spi_support_sync(starget) = scsi_device_sync(sdev);
spi_support_wide(starget) = scsi_device_wide(sdev);
spi_support_dt(starget) = scsi_device_dt(sdev);
spi_support_dt_only(starget) = scsi_device_dt_only(sdev);
spi_support_ius(starget) = scsi_device_ius(sdev);
if (bflags & SPI_BLIST_NOIUS) {
dev_info(dev, "Information Units disabled by blacklist\n");
spi_support_ius(starget) = 0;
}
spi_support_qas(starget) = scsi_device_qas(sdev);
return 0;
}
static int spi_setup_transport_attrs(struct transport_container *tc,
struct device *dev,
struct device *cdev)
{
struct scsi_target *starget = to_scsi_target(dev);
spi_period(starget) = -1; /* illegal value */
spi_min_period(starget) = 0;
spi_offset(starget) = 0; /* async */
spi_max_offset(starget) = 255;
spi_width(starget) = 0; /* narrow */
spi_max_width(starget) = 1;
spi_iu(starget) = 0; /* no IU */
spi_max_iu(starget) = 1;
spi_dt(starget) = 0; /* ST */
spi_qas(starget) = 0;
spi_max_qas(starget) = 1;
spi_wr_flow(starget) = 0;
spi_rd_strm(starget) = 0;
spi_rti(starget) = 0;
spi_pcomp_en(starget) = 0;
spi_hold_mcs(starget) = 0;
spi_dv_pending(starget) = 0;
spi_dv_in_progress(starget) = 0;
spi_initial_dv(starget) = 0;
mutex_init(&spi_dv_mutex(starget));
return 0;
}
#define spi_transport_show_simple(field, format_string) \
\
static ssize_t \
show_spi_transport_##field(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct scsi_target *starget = transport_class_to_starget(dev); \
struct spi_transport_attrs *tp; \
\
tp = (struct spi_transport_attrs *)&starget->starget_data; \
return snprintf(buf, 20, format_string, tp->field); \
}
#define spi_transport_store_simple(field, format_string) \
\
static ssize_t \
store_spi_transport_##field(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
int val; \
struct scsi_target *starget = transport_class_to_starget(dev); \
struct spi_transport_attrs *tp; \
\
tp = (struct spi_transport_attrs *)&starget->starget_data; \
val = simple_strtoul(buf, NULL, 0); \
tp->field = val; \
return count; \
}
#define spi_transport_show_function(field, format_string) \
\
static ssize_t \
show_spi_transport_##field(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct scsi_target *starget = transport_class_to_starget(dev); \
struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); \
struct spi_transport_attrs *tp; \
struct spi_internal *i = to_spi_internal(shost->transportt); \
tp = (struct spi_transport_attrs *)&starget->starget_data; \
if (i->f->get_##field) \
i->f->get_##field(starget); \
return snprintf(buf, 20, format_string, tp->field); \
}
#define spi_transport_store_function(field, format_string) \
static ssize_t \
store_spi_transport_##field(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
int val; \
struct scsi_target *starget = transport_class_to_starget(dev); \
struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); \
struct spi_internal *i = to_spi_internal(shost->transportt); \
\
if (!i->f->set_##field) \
return -EINVAL; \
val = simple_strtoul(buf, NULL, 0); \
i->f->set_##field(starget, val); \
return count; \
}
#define spi_transport_store_max(field, format_string) \
static ssize_t \
store_spi_transport_##field(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
int val; \
struct scsi_target *starget = transport_class_to_starget(dev); \
struct Scsi_Host *shost = dev_to_shost(starget->dev.parent); \
struct spi_internal *i = to_spi_internal(shost->transportt); \
struct spi_transport_attrs *tp \
= (struct spi_transport_attrs *)&starget->starget_data; \
\
if (i->f->set_##field) \
return -EINVAL; \
val = simple_strtoul(buf, NULL, 0); \
if (val > tp->max_##field) \
val = tp->max_##field; \
i->f->set_##field(starget, val); \
return count; \
}
#define spi_transport_rd_attr(field, format_string) \
spi_transport_show_function(field, format_string) \
spi_transport_store_function(field, format_string) \
static DEVICE_ATTR(field, S_IRUGO, \
show_spi_transport_##field, \
store_spi_transport_##field);
#define spi_transport_simple_attr(field, format_string) \
spi_transport_show_simple(field, format_string) \
spi_transport_store_simple(field, format_string) \
static DEVICE_ATTR(field, S_IRUGO, \
show_spi_transport_##field, \
store_spi_transport_##field);
#define spi_transport_max_attr(field, format_string) \
spi_transport_show_function(field, format_string) \
spi_transport_store_max(field, format_string) \
spi_transport_simple_attr(max_##field, format_string) \
static DEVICE_ATTR(field, S_IRUGO, \
show_spi_transport_##field, \
store_spi_transport_##field);
/* The Parallel SCSI Tranport Attributes: */
spi_transport_max_attr(offset, "%d\n");
spi_transport_max_attr(width, "%d\n");
spi_transport_max_attr(iu, "%d\n");
spi_transport_rd_attr(dt, "%d\n");
spi_transport_max_attr(qas, "%d\n");
spi_transport_rd_attr(wr_flow, "%d\n");
spi_transport_rd_attr(rd_strm, "%d\n");
spi_transport_rd_attr(rti, "%d\n");
spi_transport_rd_attr(pcomp_en, "%d\n");
spi_transport_rd_attr(hold_mcs, "%d\n");
/* we only care about the first child device that's a real SCSI device
* so we return 1 to terminate the iteration when we find it */
static int child_iter(struct device *dev, void *data)
{
if (!scsi_is_sdev_device(dev))
return 0;
spi_dv_device(to_scsi_device(dev));
return 1;
}
static ssize_t
store_spi_revalidate(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct scsi_target *starget = transport_class_to_starget(dev);
device_for_each_child(&starget->dev, NULL, child_iter);
return count;
}
static DEVICE_ATTR(revalidate, S_IWUSR, NULL, store_spi_revalidate);
/* Translate the period into ns according to the current spec
* for SDTR/PPR messages */
static int period_to_str(char *buf, int period)
{
int len, picosec;
if (period < 0 || period > 0xff) {
picosec = -1;
} else if (period <= SPI_STATIC_PPR) {
picosec = ppr_to_ps[period];
} else {
picosec = period * 4000;
}
if (picosec == -1) {
len = sprintf(buf, "reserved");
} else {
len = sprint_frac(buf, picosec, 1000);
}
return len;
}
static ssize_t
show_spi_transport_period_helper(char *buf, int period)
{
int len = period_to_str(buf, period);
buf[len++] = '\n';
buf[len] = '\0';
return len;
}
static ssize_t
store_spi_transport_period_helper(struct device *dev, const char *buf,
size_t count, int *periodp)
{
int j, picosec, period = -1;
char *endp;
picosec = simple_strtoul(buf, &endp, 10) * 1000;
if (*endp == '.') {
int mult = 100;
do {
endp++;
if (!isdigit(*endp))
break;
picosec += (*endp - '0') * mult;
mult /= 10;
} while (mult > 0);
}
for (j = 0; j <= SPI_STATIC_PPR; j++) {
if (ppr_to_ps[j] < picosec)
continue;
period = j;
break;
}
if (period == -1)
period = picosec / 4000;
if (period > 0xff)
period = 0xff;
*periodp = period;
return count;
}
static ssize_t
show_spi_transport_period(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct scsi_target *starget = transport_class_to_starget(dev);
struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
struct spi_internal *i = to_spi_internal(shost->transportt);
struct spi_transport_attrs *tp =
(struct spi_transport_attrs *)&starget->starget_data;
if (i->f->get_period)
i->f->get_period(starget);
return show_spi_transport_period_helper(buf, tp->period);
}
static ssize_t
store_spi_transport_period(struct device *cdev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct scsi_target *starget = transport_class_to_starget(cdev);
struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
struct spi_internal *i = to_spi_internal(shost->transportt);
struct spi_transport_attrs *tp =
(struct spi_transport_attrs *)&starget->starget_data;
int period, retval;
if (!i->f->set_period)
return -EINVAL;
retval = store_spi_transport_period_helper(cdev, buf, count, &period);
if (period < tp->min_period)
period = tp->min_period;
i->f->set_period(starget, period);
return retval;
}
static DEVICE_ATTR(period, S_IRUGO,
show_spi_transport_period,
store_spi_transport_period);
static ssize_t
show_spi_transport_min_period(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct scsi_target *starget = transport_class_to_starget(cdev);
struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
struct spi_internal *i = to_spi_internal(shost->transportt);
struct spi_transport_attrs *tp =
(struct spi_transport_attrs *)&starget->starget_data;
if (!i->f->set_period)
return -EINVAL;
return show_spi_transport_period_helper(buf, tp->min_period);
}
static ssize_t
store_spi_transport_min_period(struct device *cdev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct scsi_target *starget = transport_class_to_starget(cdev);
struct spi_transport_attrs *tp =
(struct spi_transport_attrs *)&starget->starget_data;
return store_spi_transport_period_helper(cdev, buf, count,
&tp->min_period);
}
static DEVICE_ATTR(min_period, S_IRUGO,
show_spi_transport_min_period,
store_spi_transport_min_period);
static ssize_t show_spi_host_signalling(struct device *cdev,
struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = transport_class_to_shost(cdev);
struct spi_internal *i = to_spi_internal(shost->transportt);
if (i->f->get_signalling)
i->f->get_signalling(shost);
return sprintf(buf, "%s\n", spi_signal_to_string(spi_signalling(shost)));
}
static ssize_t store_spi_host_signalling(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct Scsi_Host *shost = transport_class_to_shost(dev);
struct spi_internal *i = to_spi_internal(shost->transportt);
enum spi_signal_type type = spi_signal_to_value(buf);
if (!i->f->set_signalling)
return -EINVAL;
if (type != SPI_SIGNAL_UNKNOWN)
i->f->set_signalling(shost, type);
return count;
}
static DEVICE_ATTR(signalling, S_IRUGO,
show_spi_host_signalling,
store_spi_host_signalling);
#define DV_SET(x, y) \
if(i->f->set_##x) \
i->f->set_##x(sdev->sdev_target, y)
enum spi_compare_returns {
SPI_COMPARE_SUCCESS,
SPI_COMPARE_FAILURE,
SPI_COMPARE_SKIP_TEST,
};
/* This is for read/write Domain Validation: If the device supports
* an echo buffer, we do read/write tests to it */
static enum spi_compare_returns
spi_dv_device_echo_buffer(struct scsi_device *sdev, u8 *buffer,
u8 *ptr, const int retries)
{
int len = ptr - buffer;
int j, k, r, result;
unsigned int pattern = 0x0000ffff;
struct scsi_sense_hdr sshdr;
const char spi_write_buffer[] = {
WRITE_BUFFER, 0x0a, 0, 0, 0, 0, 0, len >> 8, len & 0xff, 0
};
const char spi_read_buffer[] = {
READ_BUFFER, 0x0a, 0, 0, 0, 0, 0, len >> 8, len & 0xff, 0
};
/* set up the pattern buffer. Doesn't matter if we spill
* slightly beyond since that's where the read buffer is */
for (j = 0; j < len; ) {
/* fill the buffer with counting (test a) */
for ( ; j < min(len, 32); j++)
buffer[j] = j;
k = j;
/* fill the buffer with alternating words of 0x0 and
* 0xffff (test b) */
for ( ; j < min(len, k + 32); j += 2) {
u16 *word = (u16 *)&buffer[j];
*word = (j & 0x02) ? 0x0000 : 0xffff;
}
k = j;
/* fill with crosstalk (alternating 0x5555 0xaaa)
* (test c) */
for ( ; j < min(len, k + 32); j += 2) {
u16 *word = (u16 *)&buffer[j];
*word = (j & 0x02) ? 0x5555 : 0xaaaa;
}
k = j;
/* fill with shifting bits (test d) */
for ( ; j < min(len, k + 32); j += 4) {
u32 *word = (unsigned int *)&buffer[j];
u32 roll = (pattern & 0x80000000) ? 1 : 0;
*word = pattern;
pattern = (pattern << 1) | roll;
}
/* don't bother with random data (test e) */
}
for (r = 0; r < retries; r++) {
result = spi_execute(sdev, spi_write_buffer, DMA_TO_DEVICE,
buffer, len, &sshdr);
if(result || !scsi_device_online(sdev)) {
scsi_device_set_state(sdev, SDEV_QUIESCE);
if (scsi_sense_valid(&sshdr)
&& sshdr.sense_key == ILLEGAL_REQUEST
/* INVALID FIELD IN CDB */
&& sshdr.asc == 0x24 && sshdr.ascq == 0x00)
/* This would mean that the drive lied
* to us about supporting an echo
* buffer (unfortunately some Western
* Digital drives do precisely this)
*/
return SPI_COMPARE_SKIP_TEST;
sdev_printk(KERN_ERR, sdev, "Write Buffer failure %x\n", result);
return SPI_COMPARE_FAILURE;
}
memset(ptr, 0, len);
spi_execute(sdev, spi_read_buffer, DMA_FROM_DEVICE,
ptr, len, NULL);
scsi_device_set_state(sdev, SDEV_QUIESCE);
if (memcmp(buffer, ptr, len) != 0)
return SPI_COMPARE_FAILURE;
}
return SPI_COMPARE_SUCCESS;
}
/* This is for the simplest form of Domain Validation: a read test
* on the inquiry data from the device */
static enum spi_compare_returns
spi_dv_device_compare_inquiry(struct scsi_device *sdev, u8 *buffer,
u8 *ptr, const int retries)
{
int r, result;
const int len = sdev->inquiry_len;
const char spi_inquiry[] = {
INQUIRY, 0, 0, 0, len, 0
};
for (r = 0; r < retries; r++) {
memset(ptr, 0, len);
result = spi_execute(sdev, spi_inquiry, DMA_FROM_DEVICE,
ptr, len, NULL);
if(result || !scsi_device_online(sdev)) {
scsi_device_set_state(sdev, SDEV_QUIESCE);
return SPI_COMPARE_FAILURE;
}
/* If we don't have the inquiry data already, the
* first read gets it */
if (ptr == buffer) {
ptr += len;
--r;
continue;
}
if (memcmp(buffer, ptr, len) != 0)
/* failure */
return SPI_COMPARE_FAILURE;
}
return SPI_COMPARE_SUCCESS;
}
static enum spi_compare_returns
spi_dv_retrain(struct scsi_device *sdev, u8 *buffer, u8 *ptr,
enum spi_compare_returns
(*compare_fn)(struct scsi_device *, u8 *, u8 *, int))
{
struct spi_internal *i = to_spi_internal(sdev->host->transportt);
struct scsi_target *starget = sdev->sdev_target;
int period = 0, prevperiod = 0;
enum spi_compare_returns retval;
for (;;) {
int newperiod;
retval = compare_fn(sdev, buffer, ptr, DV_LOOPS);
if (retval == SPI_COMPARE_SUCCESS
|| retval == SPI_COMPARE_SKIP_TEST)
break;
/* OK, retrain, fallback */
if (i->f->get_iu)
i->f->get_iu(starget);
if (i->f->get_qas)
i->f->get_qas(starget);
if (i->f->get_period)
i->f->get_period(sdev->sdev_target);
/* Here's the fallback sequence; first try turning off
* IU, then QAS (if we can control them), then finally
* fall down the periods */
if (i->f->set_iu && spi_iu(starget)) {
starget_printk(KERN_ERR, starget, "Domain Validation Disabing Information Units\n");
DV_SET(iu, 0);
} else if (i->f->set_qas && spi_qas(starget)) {
starget_printk(KERN_ERR, starget, "Domain Validation Disabing Quick Arbitration and Selection\n");
DV_SET(qas, 0);
} else {
newperiod = spi_period(starget);
period = newperiod > period ? newperiod : period;
if (period < 0x0d)
period++;
else
period += period >> 1;
if (unlikely(period > 0xff || period == prevperiod)) {
/* Total failure; set to async and return */
starget_printk(KERN_ERR, starget, "Domain Validation Failure, dropping back to Asynchronous\n");
DV_SET(offset, 0);
return SPI_COMPARE_FAILURE;
}
starget_printk(KERN_ERR, starget, "Domain Validation detected failure, dropping back\n");
DV_SET(period, period);
prevperiod = period;
}
}
return retval;
}
static int
spi_dv_device_get_echo_buffer(struct scsi_device *sdev, u8 *buffer)
{
int l, result;
/* first off do a test unit ready. This can error out
* because of reservations or some other reason. If it
* fails, the device won't let us write to the echo buffer
* so just return failure */
const char spi_test_unit_ready[] = {
TEST_UNIT_READY, 0, 0, 0, 0, 0
};
const char spi_read_buffer_descriptor[] = {
READ_BUFFER, 0x0b, 0, 0, 0, 0, 0, 0, 4, 0
};
/* We send a set of three TURs to clear any outstanding
* unit attention conditions if they exist (Otherwise the
* buffer tests won't be happy). If the TUR still fails
* (reservation conflict, device not ready, etc) just
* skip the write tests */
for (l = 0; ; l++) {
result = spi_execute(sdev, spi_test_unit_ready, DMA_NONE,
NULL, 0, NULL);
if(result) {
if(l >= 3)
return 0;
} else {
/* TUR succeeded */
break;
}
}
result = spi_execute(sdev, spi_read_buffer_descriptor,
DMA_FROM_DEVICE, buffer, 4, NULL);
if (result)
/* Device has no echo buffer */
return 0;
return buffer[3] + ((buffer[2] & 0x1f) << 8);
}
static void
spi_dv_device_internal(struct scsi_device *sdev, u8 *buffer)
{
struct spi_internal *i = to_spi_internal(sdev->host->transportt);
struct scsi_target *starget = sdev->sdev_target;
struct Scsi_Host *shost = sdev->host;
int len = sdev->inquiry_len;
int min_period = spi_min_period(starget);
int max_width = spi_max_width(starget);
/* first set us up for narrow async */
DV_SET(offset, 0);
DV_SET(width, 0);
if (spi_dv_device_compare_inquiry(sdev, buffer, buffer, DV_LOOPS)
!= SPI_COMPARE_SUCCESS) {
starget_printk(KERN_ERR, starget, "Domain Validation Initial Inquiry Failed\n");
/* FIXME: should probably offline the device here? */
return;
}
if (!spi_support_wide(starget)) {
spi_max_width(starget) = 0;
max_width = 0;
}
/* test width */
if (i->f->set_width && max_width) {
i->f->set_width(starget, 1);
if (spi_dv_device_compare_inquiry(sdev, buffer,
buffer + len,
DV_LOOPS)
!= SPI_COMPARE_SUCCESS) {
starget_printk(KERN_ERR, starget, "Wide Transfers Fail\n");
i->f->set_width(starget, 0);
/* Make sure we don't force wide back on by asking
* for a transfer period that requires it */
max_width = 0;
if (min_period < 10)
min_period = 10;
}
}
if (!i->f->set_period)
return;
/* device can't handle synchronous */
if (!spi_support_sync(starget) && !spi_support_dt(starget))
return;
/* len == -1 is the signal that we need to ascertain the
* presence of an echo buffer before trying to use it. len ==
* 0 means we don't have an echo buffer */
len = -1;
retry:
/* now set up to the maximum */
DV_SET(offset, spi_max_offset(starget));
DV_SET(period, min_period);
/* try QAS requests; this should be harmless to set if the
* target supports it */
if (spi_support_qas(starget) && spi_max_qas(starget)) {
DV_SET(qas, 1);
} else {
DV_SET(qas, 0);
}
if (spi_support_ius(starget) && spi_max_iu(starget) &&
min_period < 9) {
/* This u320 (or u640). Set IU transfers */
DV_SET(iu, 1);
/* Then set the optional parameters */
DV_SET(rd_strm, 1);
DV_SET(wr_flow, 1);
DV_SET(rti, 1);
if (min_period == 8)
DV_SET(pcomp_en, 1);
} else {
DV_SET(iu, 0);
}
/* now that we've done all this, actually check the bus
* signal type (if known). Some devices are stupid on
* a SE bus and still claim they can try LVD only settings */
if (i->f->get_signalling)
i->f->get_signalling(shost);
if (spi_signalling(shost) == SPI_SIGNAL_SE ||
spi_signalling(shost) == SPI_SIGNAL_HVD ||
!spi_support_dt(starget)) {
DV_SET(dt, 0);
} else {
DV_SET(dt, 1);
}
/* set width last because it will pull all the other
* parameters down to required values */
DV_SET(width, max_width);
/* Do the read only INQUIRY tests */
spi_dv_retrain(sdev, buffer, buffer + sdev->inquiry_len,
spi_dv_device_compare_inquiry);
/* See if we actually managed to negotiate and sustain DT */
if (i->f->get_dt)
i->f->get_dt(starget);
/* see if the device has an echo buffer. If it does we can do
* the SPI pattern write tests. Because of some broken
* devices, we *only* try this on a device that has actually
* negotiated DT */
if (len == -1 && spi_dt(starget))
len = spi_dv_device_get_echo_buffer(sdev, buffer);
if (len <= 0) {
starget_printk(KERN_INFO, starget, "Domain Validation skipping write tests\n");
return;
}
if (len > SPI_MAX_ECHO_BUFFER_SIZE) {
starget_printk(KERN_WARNING, starget, "Echo buffer size %d is too big, trimming to %d\n", len, SPI_MAX_ECHO_BUFFER_SIZE);
len = SPI_MAX_ECHO_BUFFER_SIZE;
}
if (spi_dv_retrain(sdev, buffer, buffer + len,
spi_dv_device_echo_buffer)
== SPI_COMPARE_SKIP_TEST) {
/* OK, the stupid drive can't do a write echo buffer
* test after all, fall back to the read tests */
len = 0;
goto retry;
}
}
/** spi_dv_device - Do Domain Validation on the device
* @sdev: scsi device to validate
*
* Performs the domain validation on the given device in the
* current execution thread. Since DV operations may sleep,
* the current thread must have user context. Also no SCSI
* related locks that would deadlock I/O issued by the DV may
* be held.
*/
void
spi_dv_device(struct scsi_device *sdev)
{
struct scsi_target *starget = sdev->sdev_target;
u8 *buffer;
const int len = SPI_MAX_ECHO_BUFFER_SIZE*2;
if (unlikely(scsi_device_get(sdev)))
return;
if (unlikely(spi_dv_in_progress(starget)))
return;
spi_dv_in_progress(starget) = 1;
buffer = kzalloc(len, GFP_KERNEL);
if (unlikely(!buffer))
goto out_put;
/* We need to verify that the actual device will quiesce; the
* later target quiesce is just a nice to have */
if (unlikely(scsi_device_quiesce(sdev)))
goto out_free;
scsi_target_quiesce(starget);
spi_dv_pending(starget) = 1;
mutex_lock(&spi_dv_mutex(starget));
starget_printk(KERN_INFO, starget, "Beginning Domain Validation\n");
spi_dv_device_internal(sdev, buffer);
starget_printk(KERN_INFO, starget, "Ending Domain Validation\n");
mutex_unlock(&spi_dv_mutex(starget));
spi_dv_pending(starget) = 0;
scsi_target_resume(starget);
spi_initial_dv(starget) = 1;
out_free:
kfree(buffer);
out_put:
spi_dv_in_progress(starget) = 0;
scsi_device_put(sdev);
}
EXPORT_SYMBOL(spi_dv_device);
struct work_queue_wrapper {
struct work_struct work;
struct scsi_device *sdev;
};
static void
spi_dv_device_work_wrapper(struct work_struct *work)
{
struct work_queue_wrapper *wqw =
container_of(work, struct work_queue_wrapper, work);
struct scsi_device *sdev = wqw->sdev;
kfree(wqw);
spi_dv_device(sdev);
spi_dv_pending(sdev->sdev_target) = 0;
scsi_device_put(sdev);
}
/**
* spi_schedule_dv_device - schedule domain validation to occur on the device
* @sdev: The device to validate
*
* Identical to spi_dv_device() above, except that the DV will be
* scheduled to occur in a workqueue later. All memory allocations
* are atomic, so may be called from any context including those holding
* SCSI locks.
*/
void
spi_schedule_dv_device(struct scsi_device *sdev)
{
struct work_queue_wrapper *wqw =
kmalloc(sizeof(struct work_queue_wrapper), GFP_ATOMIC);
if (unlikely(!wqw))
return;
if (unlikely(spi_dv_pending(sdev->sdev_target))) {
kfree(wqw);
return;
}
/* Set pending early (dv_device doesn't check it, only sets it) */
spi_dv_pending(sdev->sdev_target) = 1;
if (unlikely(scsi_device_get(sdev))) {
kfree(wqw);
spi_dv_pending(sdev->sdev_target) = 0;
return;
}
INIT_WORK(&wqw->work, spi_dv_device_work_wrapper);
wqw->sdev = sdev;
schedule_work(&wqw->work);
}
EXPORT_SYMBOL(spi_schedule_dv_device);
/**
* spi_display_xfer_agreement - Print the current target transfer agreement
* @starget: The target for which to display the agreement
*
* Each SPI port is required to maintain a transfer agreement for each
* other port on the bus. This function prints a one-line summary of
* the current agreement; more detailed information is available in sysfs.
*/
void spi_display_xfer_agreement(struct scsi_target *starget)
{
struct spi_transport_attrs *tp;
tp = (struct spi_transport_attrs *)&starget->starget_data;
if (tp->offset > 0 && tp->period > 0) {
unsigned int picosec, kb100;
char *scsi = "FAST-?";
char tmp[8];
if (tp->period <= SPI_STATIC_PPR) {
picosec = ppr_to_ps[tp->period];
switch (tp->period) {
case 7: scsi = "FAST-320"; break;
case 8: scsi = "FAST-160"; break;
case 9: scsi = "FAST-80"; break;
case 10:
case 11: scsi = "FAST-40"; break;
case 12: scsi = "FAST-20"; break;
}
} else {
picosec = tp->period * 4000;
if (tp->period < 25)
scsi = "FAST-20";
else if (tp->period < 50)
scsi = "FAST-10";
else
scsi = "FAST-5";
}
kb100 = (10000000 + picosec / 2) / picosec;
if (tp->width)
kb100 *= 2;
sprint_frac(tmp, picosec, 1000);
dev_info(&starget->dev,
"%s %sSCSI %d.%d MB/s %s%s%s%s%s%s%s%s (%s ns, offset %d)\n",
scsi, tp->width ? "WIDE " : "", kb100/10, kb100 % 10,
tp->dt ? "DT" : "ST",
tp->iu ? " IU" : "",
tp->qas ? " QAS" : "",
tp->rd_strm ? " RDSTRM" : "",
tp->rti ? " RTI" : "",
tp->wr_flow ? " WRFLOW" : "",
tp->pcomp_en ? " PCOMP" : "",
tp->hold_mcs ? " HMCS" : "",
tmp, tp->offset);
} else {
dev_info(&starget->dev, "%sasynchronous\n",
tp->width ? "wide " : "");
}
}
EXPORT_SYMBOL(spi_display_xfer_agreement);
int spi_populate_width_msg(unsigned char *msg, int width)
{
msg[0] = EXTENDED_MESSAGE;
msg[1] = 2;
msg[2] = EXTENDED_WDTR;
msg[3] = width;
return 4;
}
EXPORT_SYMBOL_GPL(spi_populate_width_msg);
int spi_populate_sync_msg(unsigned char *msg, int period, int offset)
{
msg[0] = EXTENDED_MESSAGE;
msg[1] = 3;
msg[2] = EXTENDED_SDTR;
msg[3] = period;
msg[4] = offset;
return 5;
}
EXPORT_SYMBOL_GPL(spi_populate_sync_msg);
int spi_populate_ppr_msg(unsigned char *msg, int period, int offset,
int width, int options)
{
msg[0] = EXTENDED_MESSAGE;
msg[1] = 6;
msg[2] = EXTENDED_PPR;
msg[3] = period;
msg[4] = 0;
msg[5] = offset;
msg[6] = width;
msg[7] = options;
return 8;
}
EXPORT_SYMBOL_GPL(spi_populate_ppr_msg);
#ifdef CONFIG_SCSI_CONSTANTS
static const char * const one_byte_msgs[] = {
/* 0x00 */ "Task Complete", NULL /* Extended Message */, "Save Pointers",
/* 0x03 */ "Restore Pointers", "Disconnect", "Initiator Error",
/* 0x06 */ "Abort Task Set", "Message Reject", "Nop", "Message Parity Error",
/* 0x0a */ "Linked Command Complete", "Linked Command Complete w/flag",
/* 0x0c */ "Target Reset", "Abort Task", "Clear Task Set",
/* 0x0f */ "Initiate Recovery", "Release Recovery",
/* 0x11 */ "Terminate Process", "Continue Task", "Target Transfer Disable",
/* 0x14 */ NULL, NULL, "Clear ACA", "LUN Reset"
};
static const char * const two_byte_msgs[] = {
/* 0x20 */ "Simple Queue Tag", "Head of Queue Tag", "Ordered Queue Tag",
/* 0x23 */ "Ignore Wide Residue", "ACA"
};
static const char * const extended_msgs[] = {
/* 0x00 */ "Modify Data Pointer", "Synchronous Data Transfer Request",
/* 0x02 */ "SCSI-I Extended Identify", "Wide Data Transfer Request",
/* 0x04 */ "Parallel Protocol Request", "Modify Bidirectional Data Pointer"
};
static void print_nego(const unsigned char *msg, int per, int off, int width)
{
if (per) {
char buf[20];
period_to_str(buf, msg[per]);
printk("period = %s ns ", buf);
}
if (off)
printk("offset = %d ", msg[off]);
if (width)
printk("width = %d ", 8 << msg[width]);
}
static void print_ptr(const unsigned char *msg, int msb, const char *desc)
{
int ptr = (msg[msb] << 24) | (msg[msb+1] << 16) | (msg[msb+2] << 8) |
msg[msb+3];
printk("%s = %d ", desc, ptr);
}
int spi_print_msg(const unsigned char *msg)
{
int len = 1, i;
if (msg[0] == EXTENDED_MESSAGE) {
len = 2 + msg[1];
if (len == 2)
len += 256;
if (msg[2] < ARRAY_SIZE(extended_msgs))
printk ("%s ", extended_msgs[msg[2]]);
else
printk ("Extended Message, reserved code (0x%02x) ",
(int) msg[2]);
switch (msg[2]) {
case EXTENDED_MODIFY_DATA_POINTER:
print_ptr(msg, 3, "pointer");
break;
case EXTENDED_SDTR:
print_nego(msg, 3, 4, 0);
break;
case EXTENDED_WDTR:
print_nego(msg, 0, 0, 3);
break;
case EXTENDED_PPR:
print_nego(msg, 3, 5, 6);
break;
case EXTENDED_MODIFY_BIDI_DATA_PTR:
print_ptr(msg, 3, "out");
print_ptr(msg, 7, "in");
break;
default:
for (i = 2; i < len; ++i)
printk("%02x ", msg[i]);
}
/* Identify */
} else if (msg[0] & 0x80) {
printk("Identify disconnect %sallowed %s %d ",
(msg[0] & 0x40) ? "" : "not ",
(msg[0] & 0x20) ? "target routine" : "lun",
msg[0] & 0x7);
/* Normal One byte */
} else if (msg[0] < 0x1f) {
if (msg[0] < ARRAY_SIZE(one_byte_msgs) && one_byte_msgs[msg[0]])
printk("%s ", one_byte_msgs[msg[0]]);
else
printk("reserved (%02x) ", msg[0]);
} else if (msg[0] == 0x55) {
printk("QAS Request ");
/* Two byte */
} else if (msg[0] <= 0x2f) {
if ((msg[0] - 0x20) < ARRAY_SIZE(two_byte_msgs))
printk("%s %02x ", two_byte_msgs[msg[0] - 0x20],
msg[1]);
else
printk("reserved two byte (%02x %02x) ",
msg[0], msg[1]);
len = 2;
} else
printk("reserved ");
return len;
}
EXPORT_SYMBOL(spi_print_msg);
#else /* ifndef CONFIG_SCSI_CONSTANTS */
int spi_print_msg(const unsigned char *msg)
{
int len = 1, i;
if (msg[0] == EXTENDED_MESSAGE) {
len = 2 + msg[1];
if (len == 2)
len += 256;
for (i = 0; i < len; ++i)
printk("%02x ", msg[i]);
/* Identify */
} else if (msg[0] & 0x80) {
printk("%02x ", msg[0]);
/* Normal One byte */
} else if ((msg[0] < 0x1f) || (msg[0] == 0x55)) {
printk("%02x ", msg[0]);
/* Two byte */
} else if (msg[0] <= 0x2f) {
printk("%02x %02x", msg[0], msg[1]);
len = 2;
} else
printk("%02x ", msg[0]);
return len;
}
EXPORT_SYMBOL(spi_print_msg);
#endif /* ! CONFIG_SCSI_CONSTANTS */
static int spi_device_match(struct attribute_container *cont,
struct device *dev)
{
struct scsi_device *sdev;
struct Scsi_Host *shost;
struct spi_internal *i;
if (!scsi_is_sdev_device(dev))
return 0;
sdev = to_scsi_device(dev);
shost = sdev->host;
if (!shost->transportt || shost->transportt->host_attrs.ac.class
!= &spi_host_class.class)
return 0;
/* Note: this class has no device attributes, so it has
* no per-HBA allocation and thus we don't need to distinguish
* the attribute containers for the device */
i = to_spi_internal(shost->transportt);
if (i->f->deny_binding && i->f->deny_binding(sdev->sdev_target))
return 0;
return 1;
}
static int spi_target_match(struct attribute_container *cont,
struct device *dev)
{
struct Scsi_Host *shost;
struct scsi_target *starget;
struct spi_internal *i;
if (!scsi_is_target_device(dev))
return 0;
shost = dev_to_shost(dev->parent);
if (!shost->transportt || shost->transportt->host_attrs.ac.class
!= &spi_host_class.class)
return 0;
i = to_spi_internal(shost->transportt);
starget = to_scsi_target(dev);
if (i->f->deny_binding && i->f->deny_binding(starget))
return 0;
return &i->t.target_attrs.ac == cont;
}
static DECLARE_TRANSPORT_CLASS(spi_transport_class,
"spi_transport",
spi_setup_transport_attrs,
NULL,
spi_target_configure);
static DECLARE_ANON_TRANSPORT_CLASS(spi_device_class,
spi_device_match,
spi_device_configure);
static struct attribute *host_attributes[] = {
&dev_attr_signalling.attr,
NULL
};
static struct attribute_group host_attribute_group = {
.attrs = host_attributes,
};
static int spi_host_configure(struct transport_container *tc,
struct device *dev,
struct device *cdev)
{
struct kobject *kobj = &cdev->kobj;
struct Scsi_Host *shost = transport_class_to_shost(cdev);
struct spi_internal *si = to_spi_internal(shost->transportt);
struct attribute *attr = &dev_attr_signalling.attr;
int rc = 0;
if (si->f->set_signalling)
rc = sysfs_chmod_file(kobj, attr, attr->mode | S_IWUSR);
return rc;
}
/* returns true if we should be showing the variable. Also
* overloads the return by setting 1<<1 if the attribute should
* be writeable */
#define TARGET_ATTRIBUTE_HELPER(name) \
(si->f->show_##name ? S_IRUGO : 0) | \
(si->f->set_##name ? S_IWUSR : 0)
static mode_t target_attribute_is_visible(struct kobject *kobj,
struct attribute *attr, int i)
{
struct device *cdev = container_of(kobj, struct device, kobj);
struct scsi_target *starget = transport_class_to_starget(cdev);
struct Scsi_Host *shost = transport_class_to_shost(cdev);
struct spi_internal *si = to_spi_internal(shost->transportt);
if (attr == &dev_attr_period.attr &&
spi_support_sync(starget))
return TARGET_ATTRIBUTE_HELPER(period);
else if (attr == &dev_attr_min_period.attr &&
spi_support_sync(starget))
return TARGET_ATTRIBUTE_HELPER(period);
else if (attr == &dev_attr_offset.attr &&
spi_support_sync(starget))
return TARGET_ATTRIBUTE_HELPER(offset);
else if (attr == &dev_attr_max_offset.attr &&
spi_support_sync(starget))
return TARGET_ATTRIBUTE_HELPER(offset);
else if (attr == &dev_attr_width.attr &&
spi_support_wide(starget))
return TARGET_ATTRIBUTE_HELPER(width);
else if (attr == &dev_attr_max_width.attr &&
spi_support_wide(starget))
return TARGET_ATTRIBUTE_HELPER(width);
else if (attr == &dev_attr_iu.attr &&
spi_support_ius(starget))
return TARGET_ATTRIBUTE_HELPER(iu);
else if (attr == &dev_attr_max_iu.attr &&
spi_support_ius(starget))
return TARGET_ATTRIBUTE_HELPER(iu);
else if (attr == &dev_attr_dt.attr &&
spi_support_dt(starget))
return TARGET_ATTRIBUTE_HELPER(dt);
else if (attr == &dev_attr_qas.attr &&
spi_support_qas(starget))
return TARGET_ATTRIBUTE_HELPER(qas);
else if (attr == &dev_attr_max_qas.attr &&
spi_support_qas(starget))
return TARGET_ATTRIBUTE_HELPER(qas);
else if (attr == &dev_attr_wr_flow.attr &&
spi_support_ius(starget))
return TARGET_ATTRIBUTE_HELPER(wr_flow);
else if (attr == &dev_attr_rd_strm.attr &&
spi_support_ius(starget))
return TARGET_ATTRIBUTE_HELPER(rd_strm);
else if (attr == &dev_attr_rti.attr &&
spi_support_ius(starget))
return TARGET_ATTRIBUTE_HELPER(rti);
else if (attr == &dev_attr_pcomp_en.attr &&
spi_support_ius(starget))
return TARGET_ATTRIBUTE_HELPER(pcomp_en);
else if (attr == &dev_attr_hold_mcs.attr &&
spi_support_ius(starget))
return TARGET_ATTRIBUTE_HELPER(hold_mcs);
else if (attr == &dev_attr_revalidate.attr)
return S_IWUSR;
return 0;
}
static struct attribute *target_attributes[] = {
&dev_attr_period.attr,
&dev_attr_min_period.attr,
&dev_attr_offset.attr,
&dev_attr_max_offset.attr,
&dev_attr_width.attr,
&dev_attr_max_width.attr,
&dev_attr_iu.attr,
&dev_attr_max_iu.attr,
&dev_attr_dt.attr,
&dev_attr_qas.attr,
&dev_attr_max_qas.attr,
&dev_attr_wr_flow.attr,
&dev_attr_rd_strm.attr,
&dev_attr_rti.attr,
&dev_attr_pcomp_en.attr,
&dev_attr_hold_mcs.attr,
&dev_attr_revalidate.attr,
NULL
};
static struct attribute_group target_attribute_group = {
.attrs = target_attributes,
.is_visible = target_attribute_is_visible,
};
static int spi_target_configure(struct transport_container *tc,
struct device *dev,
struct device *cdev)
{
struct kobject *kobj = &cdev->kobj;
/* force an update based on parameters read from the device */
sysfs_update_group(kobj, &target_attribute_group);
return 0;
}
struct scsi_transport_template *
spi_attach_transport(struct spi_function_template *ft)
{
struct spi_internal *i = kzalloc(sizeof(struct spi_internal),
GFP_KERNEL);
if (unlikely(!i))
return NULL;
i->t.target_attrs.ac.class = &spi_transport_class.class;
i->t.target_attrs.ac.grp = &target_attribute_group;
i->t.target_attrs.ac.match = spi_target_match;
transport_container_register(&i->t.target_attrs);
i->t.target_size = sizeof(struct spi_transport_attrs);
i->t.host_attrs.ac.class = &spi_host_class.class;
i->t.host_attrs.ac.grp = &host_attribute_group;
i->t.host_attrs.ac.match = spi_host_match;
transport_container_register(&i->t.host_attrs);
i->t.host_size = sizeof(struct spi_host_attrs);
i->f = ft;
return &i->t;
}
EXPORT_SYMBOL(spi_attach_transport);
void spi_release_transport(struct scsi_transport_template *t)
{
struct spi_internal *i = to_spi_internal(t);
transport_container_unregister(&i->t.target_attrs);
transport_container_unregister(&i->t.host_attrs);
kfree(i);
}
EXPORT_SYMBOL(spi_release_transport);
static __init int spi_transport_init(void)
{
int error = scsi_dev_info_add_list(SCSI_DEVINFO_SPI,
"SCSI Parallel Transport Class");
if (!error) {
int i;
for (i = 0; spi_static_device_list[i].vendor; i++)
scsi_dev_info_list_add_keyed(1, /* compatible */
spi_static_device_list[i].vendor,
spi_static_device_list[i].model,
NULL,
spi_static_device_list[i].flags,
SCSI_DEVINFO_SPI);
}
error = transport_class_register(&spi_transport_class);
if (error)
return error;
error = anon_transport_class_register(&spi_device_class);
return transport_class_register(&spi_host_class);
}
static void __exit spi_transport_exit(void)
{
transport_class_unregister(&spi_transport_class);
anon_transport_class_unregister(&spi_device_class);
transport_class_unregister(&spi_host_class);
scsi_dev_info_remove_list(SCSI_DEVINFO_SPI);
}
MODULE_AUTHOR("Martin Hicks");
MODULE_DESCRIPTION("SPI Transport Attributes");
MODULE_LICENSE("GPL");
module_init(spi_transport_init);
module_exit(spi_transport_exit);
| gpl-2.0 |
mi3-dev/android_kernel_xiaomi_msm8x74pro | scripts/dtc/treesource.c | 4862 | 6105 | /*
* (C) Copyright David Gibson <dwg@au1.ibm.com>, IBM Corporation. 2005.
*
*
* 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 "dtc.h"
#include "srcpos.h"
extern FILE *yyin;
extern int yyparse(void);
extern YYLTYPE yylloc;
struct boot_info *the_boot_info;
int treesource_error;
struct boot_info *dt_from_source(const char *fname)
{
the_boot_info = NULL;
treesource_error = 0;
srcfile_push(fname);
yyin = current_srcfile->f;
yylloc.file = current_srcfile;
if (yyparse() != 0)
die("Unable to parse input tree\n");
if (treesource_error)
die("Syntax error parsing input tree\n");
return the_boot_info;
}
static void write_prefix(FILE *f, int level)
{
int i;
for (i = 0; i < level; i++)
fputc('\t', f);
}
static int isstring(char c)
{
return (isprint(c)
|| (c == '\0')
|| strchr("\a\b\t\n\v\f\r", c));
}
static void write_propval_string(FILE *f, struct data val)
{
const char *str = val.val;
int i;
struct marker *m = val.markers;
assert(str[val.len-1] == '\0');
while (m && (m->offset == 0)) {
if (m->type == LABEL)
fprintf(f, "%s: ", m->ref);
m = m->next;
}
fprintf(f, "\"");
for (i = 0; i < (val.len-1); i++) {
char c = str[i];
switch (c) {
case '\a':
fprintf(f, "\\a");
break;
case '\b':
fprintf(f, "\\b");
break;
case '\t':
fprintf(f, "\\t");
break;
case '\n':
fprintf(f, "\\n");
break;
case '\v':
fprintf(f, "\\v");
break;
case '\f':
fprintf(f, "\\f");
break;
case '\r':
fprintf(f, "\\r");
break;
case '\\':
fprintf(f, "\\\\");
break;
case '\"':
fprintf(f, "\\\"");
break;
case '\0':
fprintf(f, "\", ");
while (m && (m->offset < i)) {
if (m->type == LABEL) {
assert(m->offset == (i+1));
fprintf(f, "%s: ", m->ref);
}
m = m->next;
}
fprintf(f, "\"");
break;
default:
if (isprint(c))
fprintf(f, "%c", c);
else
fprintf(f, "\\x%02hhx", c);
}
}
fprintf(f, "\"");
/* Wrap up any labels at the end of the value */
for_each_marker_of_type(m, LABEL) {
assert (m->offset == val.len);
fprintf(f, " %s:", m->ref);
}
}
static void write_propval_cells(FILE *f, struct data val)
{
void *propend = val.val + val.len;
cell_t *cp = (cell_t *)val.val;
struct marker *m = val.markers;
fprintf(f, "<");
for (;;) {
while (m && (m->offset <= ((char *)cp - val.val))) {
if (m->type == LABEL) {
assert(m->offset == ((char *)cp - val.val));
fprintf(f, "%s: ", m->ref);
}
m = m->next;
}
fprintf(f, "0x%x", fdt32_to_cpu(*cp++));
if ((void *)cp >= propend)
break;
fprintf(f, " ");
}
/* Wrap up any labels at the end of the value */
for_each_marker_of_type(m, LABEL) {
assert (m->offset == val.len);
fprintf(f, " %s:", m->ref);
}
fprintf(f, ">");
}
static void write_propval_bytes(FILE *f, struct data val)
{
void *propend = val.val + val.len;
const char *bp = val.val;
struct marker *m = val.markers;
fprintf(f, "[");
for (;;) {
while (m && (m->offset == (bp-val.val))) {
if (m->type == LABEL)
fprintf(f, "%s: ", m->ref);
m = m->next;
}
fprintf(f, "%02hhx", *bp++);
if ((const void *)bp >= propend)
break;
fprintf(f, " ");
}
/* Wrap up any labels at the end of the value */
for_each_marker_of_type(m, LABEL) {
assert (m->offset == val.len);
fprintf(f, " %s:", m->ref);
}
fprintf(f, "]");
}
static void write_propval(FILE *f, struct property *prop)
{
int len = prop->val.len;
const char *p = prop->val.val;
struct marker *m = prop->val.markers;
int nnotstring = 0, nnul = 0;
int nnotstringlbl = 0, nnotcelllbl = 0;
int i;
if (len == 0) {
fprintf(f, ";\n");
return;
}
for (i = 0; i < len; i++) {
if (! isstring(p[i]))
nnotstring++;
if (p[i] == '\0')
nnul++;
}
for_each_marker_of_type(m, LABEL) {
if ((m->offset > 0) && (prop->val.val[m->offset - 1] != '\0'))
nnotstringlbl++;
if ((m->offset % sizeof(cell_t)) != 0)
nnotcelllbl++;
}
fprintf(f, " = ");
if ((p[len-1] == '\0') && (nnotstring == 0) && (nnul < (len-nnul))
&& (nnotstringlbl == 0)) {
write_propval_string(f, prop->val);
} else if (((len % sizeof(cell_t)) == 0) && (nnotcelllbl == 0)) {
write_propval_cells(f, prop->val);
} else {
write_propval_bytes(f, prop->val);
}
fprintf(f, ";\n");
}
static void write_tree_source_node(FILE *f, struct node *tree, int level)
{
struct property *prop;
struct node *child;
struct label *l;
write_prefix(f, level);
for_each_label(tree->labels, l)
fprintf(f, "%s: ", l->label);
if (tree->name && (*tree->name))
fprintf(f, "%s {\n", tree->name);
else
fprintf(f, "/ {\n");
for_each_property(tree, prop) {
write_prefix(f, level+1);
for_each_label(prop->labels, l)
fprintf(f, "%s: ", l->label);
fprintf(f, "%s", prop->name);
write_propval(f, prop);
}
for_each_child(tree, child) {
fprintf(f, "\n");
write_tree_source_node(f, child, level+1);
}
write_prefix(f, level);
fprintf(f, "};\n");
}
void dt_to_source(FILE *f, struct boot_info *bi)
{
struct reserve_info *re;
fprintf(f, "/dts-v1/;\n\n");
for (re = bi->reservelist; re; re = re->next) {
struct label *l;
for_each_label(re->labels, l)
fprintf(f, "%s: ", l->label);
fprintf(f, "/memreserve/\t0x%016llx 0x%016llx;\n",
(unsigned long long)re->re.address,
(unsigned long long)re->re.size);
}
write_tree_source_node(f, bi->dt, 0);
}
| gpl-2.0 |
emansih/d855_CM_kernel | drivers/leds/leds-pca9633.c | 4862 | 4777 | /*
* Copyright 2011 bct electronic GmbH
*
* Author: Peter Meerwald <p.meerwald@bct-electronic.com>
*
* Based on leds-pca955x.c
*
* This file is subject to the terms and conditions of version 2 of
* the GNU General Public License. See the file COPYING in the main
* directory of this archive for more details.
*
* LED driver for the PCA9633 I2C LED driver (7-bit slave address 0x62)
*
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/leds.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
/* LED select registers determine the source that drives LED outputs */
#define PCA9633_LED_OFF 0x0 /* LED driver off */
#define PCA9633_LED_ON 0x1 /* LED driver on */
#define PCA9633_LED_PWM 0x2 /* Controlled through PWM */
#define PCA9633_LED_GRP_PWM 0x3 /* Controlled through PWM/GRPPWM */
#define PCA9633_MODE1 0x00
#define PCA9633_MODE2 0x01
#define PCA9633_PWM_BASE 0x02
#define PCA9633_LEDOUT 0x08
static const struct i2c_device_id pca9633_id[] = {
{ "pca9633", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pca9633_id);
struct pca9633_led {
struct i2c_client *client;
struct work_struct work;
enum led_brightness brightness;
struct led_classdev led_cdev;
int led_num; /* 0 .. 3 potentially */
char name[32];
};
static void pca9633_led_work(struct work_struct *work)
{
struct pca9633_led *pca9633 = container_of(work,
struct pca9633_led, work);
u8 ledout = i2c_smbus_read_byte_data(pca9633->client, PCA9633_LEDOUT);
int shift = 2 * pca9633->led_num;
u8 mask = 0x3 << shift;
switch (pca9633->brightness) {
case LED_FULL:
i2c_smbus_write_byte_data(pca9633->client, PCA9633_LEDOUT,
(ledout & ~mask) | (PCA9633_LED_ON << shift));
break;
case LED_OFF:
i2c_smbus_write_byte_data(pca9633->client, PCA9633_LEDOUT,
ledout & ~mask);
break;
default:
i2c_smbus_write_byte_data(pca9633->client,
PCA9633_PWM_BASE + pca9633->led_num,
pca9633->brightness);
i2c_smbus_write_byte_data(pca9633->client, PCA9633_LEDOUT,
(ledout & ~mask) | (PCA9633_LED_PWM << shift));
break;
}
}
static void pca9633_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct pca9633_led *pca9633;
pca9633 = container_of(led_cdev, struct pca9633_led, led_cdev);
pca9633->brightness = value;
/*
* Must use workqueue for the actual I/O since I2C operations
* can sleep.
*/
schedule_work(&pca9633->work);
}
static int __devinit pca9633_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pca9633_led *pca9633;
struct led_platform_data *pdata;
int i, err;
pdata = client->dev.platform_data;
if (pdata) {
if (pdata->num_leds <= 0 || pdata->num_leds > 4) {
dev_err(&client->dev, "board info must claim at most 4 LEDs");
return -EINVAL;
}
}
pca9633 = kcalloc(4, sizeof(*pca9633), GFP_KERNEL);
if (!pca9633)
return -ENOMEM;
i2c_set_clientdata(client, pca9633);
for (i = 0; i < 4; i++) {
pca9633[i].client = client;
pca9633[i].led_num = i;
/* Platform data can specify LED names and default triggers */
if (pdata && i < pdata->num_leds) {
if (pdata->leds[i].name)
snprintf(pca9633[i].name,
sizeof(pca9633[i].name), "pca9633:%s",
pdata->leds[i].name);
if (pdata->leds[i].default_trigger)
pca9633[i].led_cdev.default_trigger =
pdata->leds[i].default_trigger;
} else {
snprintf(pca9633[i].name, sizeof(pca9633[i].name),
"pca9633:%d", i);
}
pca9633[i].led_cdev.name = pca9633[i].name;
pca9633[i].led_cdev.brightness_set = pca9633_led_set;
INIT_WORK(&pca9633[i].work, pca9633_led_work);
err = led_classdev_register(&client->dev, &pca9633[i].led_cdev);
if (err < 0)
goto exit;
}
/* Disable LED all-call address and set normal mode */
i2c_smbus_write_byte_data(client, PCA9633_MODE1, 0x00);
/* Turn off LEDs */
i2c_smbus_write_byte_data(client, PCA9633_LEDOUT, 0x00);
return 0;
exit:
while (i--) {
led_classdev_unregister(&pca9633[i].led_cdev);
cancel_work_sync(&pca9633[i].work);
}
kfree(pca9633);
return err;
}
static int __devexit pca9633_remove(struct i2c_client *client)
{
struct pca9633_led *pca9633 = i2c_get_clientdata(client);
int i;
for (i = 0; i < 4; i++) {
led_classdev_unregister(&pca9633[i].led_cdev);
cancel_work_sync(&pca9633[i].work);
}
kfree(pca9633);
return 0;
}
static struct i2c_driver pca9633_driver = {
.driver = {
.name = "leds-pca9633",
.owner = THIS_MODULE,
},
.probe = pca9633_probe,
.remove = __devexit_p(pca9633_remove),
.id_table = pca9633_id,
};
module_i2c_driver(pca9633_driver);
MODULE_AUTHOR("Peter Meerwald <p.meerwald@bct-electronic.com>");
MODULE_DESCRIPTION("PCA9633 LED driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Freack-v/android_kernel_eagle | drivers/leds/leds-pca9633.c | 4862 | 4777 | /*
* Copyright 2011 bct electronic GmbH
*
* Author: Peter Meerwald <p.meerwald@bct-electronic.com>
*
* Based on leds-pca955x.c
*
* This file is subject to the terms and conditions of version 2 of
* the GNU General Public License. See the file COPYING in the main
* directory of this archive for more details.
*
* LED driver for the PCA9633 I2C LED driver (7-bit slave address 0x62)
*
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/leds.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
/* LED select registers determine the source that drives LED outputs */
#define PCA9633_LED_OFF 0x0 /* LED driver off */
#define PCA9633_LED_ON 0x1 /* LED driver on */
#define PCA9633_LED_PWM 0x2 /* Controlled through PWM */
#define PCA9633_LED_GRP_PWM 0x3 /* Controlled through PWM/GRPPWM */
#define PCA9633_MODE1 0x00
#define PCA9633_MODE2 0x01
#define PCA9633_PWM_BASE 0x02
#define PCA9633_LEDOUT 0x08
static const struct i2c_device_id pca9633_id[] = {
{ "pca9633", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pca9633_id);
struct pca9633_led {
struct i2c_client *client;
struct work_struct work;
enum led_brightness brightness;
struct led_classdev led_cdev;
int led_num; /* 0 .. 3 potentially */
char name[32];
};
static void pca9633_led_work(struct work_struct *work)
{
struct pca9633_led *pca9633 = container_of(work,
struct pca9633_led, work);
u8 ledout = i2c_smbus_read_byte_data(pca9633->client, PCA9633_LEDOUT);
int shift = 2 * pca9633->led_num;
u8 mask = 0x3 << shift;
switch (pca9633->brightness) {
case LED_FULL:
i2c_smbus_write_byte_data(pca9633->client, PCA9633_LEDOUT,
(ledout & ~mask) | (PCA9633_LED_ON << shift));
break;
case LED_OFF:
i2c_smbus_write_byte_data(pca9633->client, PCA9633_LEDOUT,
ledout & ~mask);
break;
default:
i2c_smbus_write_byte_data(pca9633->client,
PCA9633_PWM_BASE + pca9633->led_num,
pca9633->brightness);
i2c_smbus_write_byte_data(pca9633->client, PCA9633_LEDOUT,
(ledout & ~mask) | (PCA9633_LED_PWM << shift));
break;
}
}
static void pca9633_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct pca9633_led *pca9633;
pca9633 = container_of(led_cdev, struct pca9633_led, led_cdev);
pca9633->brightness = value;
/*
* Must use workqueue for the actual I/O since I2C operations
* can sleep.
*/
schedule_work(&pca9633->work);
}
static int __devinit pca9633_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pca9633_led *pca9633;
struct led_platform_data *pdata;
int i, err;
pdata = client->dev.platform_data;
if (pdata) {
if (pdata->num_leds <= 0 || pdata->num_leds > 4) {
dev_err(&client->dev, "board info must claim at most 4 LEDs");
return -EINVAL;
}
}
pca9633 = kcalloc(4, sizeof(*pca9633), GFP_KERNEL);
if (!pca9633)
return -ENOMEM;
i2c_set_clientdata(client, pca9633);
for (i = 0; i < 4; i++) {
pca9633[i].client = client;
pca9633[i].led_num = i;
/* Platform data can specify LED names and default triggers */
if (pdata && i < pdata->num_leds) {
if (pdata->leds[i].name)
snprintf(pca9633[i].name,
sizeof(pca9633[i].name), "pca9633:%s",
pdata->leds[i].name);
if (pdata->leds[i].default_trigger)
pca9633[i].led_cdev.default_trigger =
pdata->leds[i].default_trigger;
} else {
snprintf(pca9633[i].name, sizeof(pca9633[i].name),
"pca9633:%d", i);
}
pca9633[i].led_cdev.name = pca9633[i].name;
pca9633[i].led_cdev.brightness_set = pca9633_led_set;
INIT_WORK(&pca9633[i].work, pca9633_led_work);
err = led_classdev_register(&client->dev, &pca9633[i].led_cdev);
if (err < 0)
goto exit;
}
/* Disable LED all-call address and set normal mode */
i2c_smbus_write_byte_data(client, PCA9633_MODE1, 0x00);
/* Turn off LEDs */
i2c_smbus_write_byte_data(client, PCA9633_LEDOUT, 0x00);
return 0;
exit:
while (i--) {
led_classdev_unregister(&pca9633[i].led_cdev);
cancel_work_sync(&pca9633[i].work);
}
kfree(pca9633);
return err;
}
static int __devexit pca9633_remove(struct i2c_client *client)
{
struct pca9633_led *pca9633 = i2c_get_clientdata(client);
int i;
for (i = 0; i < 4; i++) {
led_classdev_unregister(&pca9633[i].led_cdev);
cancel_work_sync(&pca9633[i].work);
}
kfree(pca9633);
return 0;
}
static struct i2c_driver pca9633_driver = {
.driver = {
.name = "leds-pca9633",
.owner = THIS_MODULE,
},
.probe = pca9633_probe,
.remove = __devexit_p(pca9633_remove),
.id_table = pca9633_id,
};
module_i2c_driver(pca9633_driver);
MODULE_AUTHOR("Peter Meerwald <p.meerwald@bct-electronic.com>");
MODULE_DESCRIPTION("PCA9633 LED driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
htc-first/android_kernel_htc_msm8930aa | drivers/dca/dca-sysfs.c | 5374 | 2749 | /*
* Copyright(c) 2007 - 2009 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., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The full GNU General Public License is included in this distribution in the
* file called COPYING.
*/
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/device.h>
#include <linux/idr.h>
#include <linux/kdev_t.h>
#include <linux/err.h>
#include <linux/dca.h>
#include <linux/gfp.h>
#include <linux/export.h>
static struct class *dca_class;
static struct idr dca_idr;
static spinlock_t dca_idr_lock;
int dca_sysfs_add_req(struct dca_provider *dca, struct device *dev, int slot)
{
struct device *cd;
static int req_count;
cd = device_create(dca_class, dca->cd, MKDEV(0, slot + 1), NULL,
"requester%d", req_count++);
if (IS_ERR(cd))
return PTR_ERR(cd);
return 0;
}
void dca_sysfs_remove_req(struct dca_provider *dca, int slot)
{
device_destroy(dca_class, MKDEV(0, slot + 1));
}
int dca_sysfs_add_provider(struct dca_provider *dca, struct device *dev)
{
struct device *cd;
int err = 0;
idr_try_again:
if (!idr_pre_get(&dca_idr, GFP_KERNEL))
return -ENOMEM;
spin_lock(&dca_idr_lock);
err = idr_get_new(&dca_idr, dca, &dca->id);
spin_unlock(&dca_idr_lock);
switch (err) {
case 0:
break;
case -EAGAIN:
goto idr_try_again;
default:
return err;
}
cd = device_create(dca_class, dev, MKDEV(0, 0), NULL, "dca%d", dca->id);
if (IS_ERR(cd)) {
spin_lock(&dca_idr_lock);
idr_remove(&dca_idr, dca->id);
spin_unlock(&dca_idr_lock);
return PTR_ERR(cd);
}
dca->cd = cd;
return 0;
}
void dca_sysfs_remove_provider(struct dca_provider *dca)
{
device_unregister(dca->cd);
dca->cd = NULL;
spin_lock(&dca_idr_lock);
idr_remove(&dca_idr, dca->id);
spin_unlock(&dca_idr_lock);
}
int __init dca_sysfs_init(void)
{
idr_init(&dca_idr);
spin_lock_init(&dca_idr_lock);
dca_class = class_create(THIS_MODULE, "dca");
if (IS_ERR(dca_class)) {
idr_destroy(&dca_idr);
return PTR_ERR(dca_class);
}
return 0;
}
void __exit dca_sysfs_exit(void)
{
class_destroy(dca_class);
idr_destroy(&dca_idr);
}
| gpl-2.0 |
daivietpda/M7WLJ-5.0.2 | arch/mips/math-emu/sp_mul.c | 7678 | 4799 | /* IEEE754 floating point arithmetic
* single precision
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* ########################################################################
*
* This program is free software; you can distribute 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 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 "ieee754sp.h"
ieee754sp ieee754sp_mul(ieee754sp x, ieee754sp y)
{
COMPXSP;
COMPYSP;
EXPLODEXSP;
EXPLODEYSP;
CLEARCX;
FLUSHXSP;
FLUSHYSP;
switch (CLPAIR(xc, yc)) {
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_INF):
SETCX(IEEE754_INVALID_OPERATION);
return ieee754sp_nanxcpt(ieee754sp_indef(), "mul", x, y);
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_QNAN):
return y;
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_INF):
return x;
/* Infinity handling */
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_INF):
SETCX(IEEE754_INVALID_OPERATION);
return ieee754sp_xcpt(ieee754sp_indef(), "mul", x, y);
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_INF):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_INF):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_INF):
return ieee754sp_inf(xs ^ ys);
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_ZERO):
return ieee754sp_zero(xs ^ ys);
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_DNORM):
SPDNORMX;
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_DNORM):
SPDNORMY;
break;
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_NORM):
SPDNORMX;
break;
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_NORM):
break;
}
/* rm = xm * ym, re = xe+ye basically */
assert(xm & SP_HIDDEN_BIT);
assert(ym & SP_HIDDEN_BIT);
{
int re = xe + ye;
int rs = xs ^ ys;
unsigned rm;
/* shunt to top of word */
xm <<= 32 - (SP_MBITS + 1);
ym <<= 32 - (SP_MBITS + 1);
/* multiply 32bits xm,ym to give high 32bits rm with stickness
*/
{
unsigned short lxm = xm & 0xffff;
unsigned short hxm = xm >> 16;
unsigned short lym = ym & 0xffff;
unsigned short hym = ym >> 16;
unsigned lrm;
unsigned hrm;
lrm = lxm * lym; /* 16 * 16 => 32 */
hrm = hxm * hym; /* 16 * 16 => 32 */
{
unsigned t = lxm * hym; /* 16 * 16 => 32 */
{
unsigned at = lrm + (t << 16);
hrm += at < lrm;
lrm = at;
}
hrm = hrm + (t >> 16);
}
{
unsigned t = hxm * lym; /* 16 * 16 => 32 */
{
unsigned at = lrm + (t << 16);
hrm += at < lrm;
lrm = at;
}
hrm = hrm + (t >> 16);
}
rm = hrm | (lrm != 0);
}
/*
* sticky shift down to normal rounding precision
*/
if ((int) rm < 0) {
rm = (rm >> (32 - (SP_MBITS + 1 + 3))) |
((rm << (SP_MBITS + 1 + 3)) != 0);
re++;
} else {
rm = (rm >> (32 - (SP_MBITS + 1 + 3 + 1))) |
((rm << (SP_MBITS + 1 + 3 + 1)) != 0);
}
assert(rm & (SP_HIDDEN_BIT << 3));
SPNORMRET2(rs, re, rm, "mul", x, y);
}
}
| gpl-2.0 |
Senthil360/android_kernel_samsung_trlte | arch/arm/mach-msm/timer.c | 255 | 31280 | /*
* Copyright (C) 2007 Google, Inc.
* Copyright (c) 2009-2014, The Linux Foundation. All rights reserved.
*
* 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/clocksource.h>
#include <linux/clockchips.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/percpu.h>
#include <linux/mm.h>
#include <asm/localtimer.h>
#include <asm/mach/time.h>
#include <asm/sched_clock.h>
#include <asm/smp_plat.h>
#include <asm/user_accessible_timer.h>
#include <mach/msm_iomap.h>
#include <mach/irqs.h>
#include <soc/qcom/socinfo.h>
#include <soc/qcom/smem.h>
#if defined(CONFIG_MSM_SMD)
#include <mach/msm_smsm.h>
#endif
#include "timer.h"
enum {
MSM_TIMER_DEBUG_SYNC = 1U << 0,
};
static int msm_timer_debug_mask;
module_param_named(debug_mask, msm_timer_debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
#ifdef CONFIG_MSM7X00A_USE_GP_TIMER
#define DG_TIMER_RATING 100
#else
#define DG_TIMER_RATING 300
#endif
#ifndef MSM_TMR0_BASE
#define MSM_TMR0_BASE MSM_TMR_BASE
#endif
#define MSM_DGT_SHIFT (5)
#define TIMER_MATCH_VAL 0x0000
#define TIMER_COUNT_VAL 0x0004
#define TIMER_ENABLE 0x0008
#define TIMER_CLEAR 0x000C
#define DGT_CLK_CTL 0x0034
enum {
DGT_CLK_CTL_DIV_1 = 0,
DGT_CLK_CTL_DIV_2 = 1,
DGT_CLK_CTL_DIV_3 = 2,
DGT_CLK_CTL_DIV_4 = 3,
};
#define TIMER_STATUS 0x0088
#define TIMER_ENABLE_EN 1
#define TIMER_ENABLE_CLR_ON_MATCH_EN 2
#define LOCAL_TIMER 0
#define GLOBAL_TIMER 1
/*
* global_timer_offset is added to the regbase of a timer to force the memory
* access to come from the CPU0 region.
*/
static int global_timer_offset;
static int msm_global_timer;
#define NR_TIMERS ARRAY_SIZE(msm_clocks)
unsigned int gpt_hz = 32768;
unsigned int sclk_hz = 32768;
static struct msm_clock *clockevent_to_clock(struct clock_event_device *evt);
static irqreturn_t msm_timer_interrupt(int irq, void *dev_id);
static cycle_t msm_gpt_read(struct clocksource *cs);
static cycle_t msm_dgt_read(struct clocksource *cs);
static void msm_timer_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt);
static int msm_timer_set_next_event(unsigned long cycles,
struct clock_event_device *evt);
enum {
MSM_CLOCK_FLAGS_UNSTABLE_COUNT = 1U << 0,
MSM_CLOCK_FLAGS_ODD_MATCH_WRITE = 1U << 1,
MSM_CLOCK_FLAGS_DELAYED_WRITE_POST = 1U << 2,
};
struct msm_clock {
struct clock_event_device clockevent;
struct clocksource clocksource;
unsigned int irq;
void __iomem *regbase;
uint32_t freq;
uint32_t shift;
uint32_t flags;
uint32_t write_delay;
uint32_t rollover_offset;
uint32_t index;
void __iomem *global_counter;
void __iomem *local_counter;
uint32_t status_mask;
union {
struct clock_event_device *evt;
struct clock_event_device __percpu **percpu_evt;
};
};
enum {
MSM_CLOCK_GPT,
MSM_CLOCK_DGT,
};
struct msm_clock_percpu_data {
uint32_t last_set;
uint32_t sleep_offset;
uint32_t alarm_vtime;
uint32_t alarm;
uint32_t non_sleep_offset;
uint32_t in_sync;
cycle_t stopped_tick;
int stopped;
uint32_t last_sync_gpt;
u64 last_sync_jiffies;
};
struct msm_timer_sync_data_t {
struct msm_clock *clock;
uint32_t timeout;
int exit_sleep;
};
static struct msm_clock msm_clocks[] = {
[MSM_CLOCK_GPT] = {
.clockevent = {
.name = "gp_timer",
.features = CLOCK_EVT_FEAT_ONESHOT,
.shift = 32,
.rating = 200,
.set_next_event = msm_timer_set_next_event,
.set_mode = msm_timer_set_mode,
},
.clocksource = {
.name = "gp_timer",
.rating = 200,
.read = msm_gpt_read,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
},
.irq = INT_GP_TIMER_EXP,
.regbase = MSM_TMR_BASE + 0x4,
.freq = 32768,
.index = MSM_CLOCK_GPT,
.write_delay = 9,
},
[MSM_CLOCK_DGT] = {
.clockevent = {
.name = "dg_timer",
.features = CLOCK_EVT_FEAT_ONESHOT,
.shift = 32,
.rating = DG_TIMER_RATING,
.set_next_event = msm_timer_set_next_event,
.set_mode = msm_timer_set_mode,
},
.clocksource = {
.name = "dg_timer",
.rating = DG_TIMER_RATING,
.read = msm_dgt_read,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
},
.irq = INT_DEBUG_TIMER_EXP,
.regbase = MSM_TMR_BASE + 0x24,
.index = MSM_CLOCK_DGT,
.write_delay = 9,
}
};
static DEFINE_PER_CPU(struct msm_clock_percpu_data[NR_TIMERS],
msm_clocks_percpu);
static DEFINE_PER_CPU(struct msm_clock *, msm_active_clock);
static irqreturn_t msm_timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *evt = *(struct clock_event_device **)dev_id;
if (evt->event_handler == NULL)
return IRQ_HANDLED;
evt->event_handler(evt);
return IRQ_HANDLED;
}
static uint32_t msm_read_timer_count(struct msm_clock *clock, int global)
{
uint32_t t1, t2, t3;
int loop_count = 0;
void __iomem *addr = clock->regbase + TIMER_COUNT_VAL +
global*global_timer_offset;
if (!(clock->flags & MSM_CLOCK_FLAGS_UNSTABLE_COUNT))
return __raw_readl_no_log(addr);
t1 = __raw_readl_no_log(addr);
t2 = __raw_readl_no_log(addr);
if ((t2-t1) <= 1)
return t2;
while (1) {
t1 = __raw_readl_no_log(addr);
t2 = __raw_readl_no_log(addr);
t3 = __raw_readl_no_log(addr);
cpu_relax();
if ((t3-t2) <= 1)
return t3;
if ((t2-t1) <= 1)
return t2;
if ((t2 >= t1) && (t3 >= t2))
return t2;
if (++loop_count == 5) {
pr_err("msm_read_timer_count timer %s did not "
"stabilize: %u -> %u -> %u\n",
clock->clockevent.name, t1, t2, t3);
return t3;
}
}
}
static cycle_t msm_gpt_read(struct clocksource *cs)
{
struct msm_clock *clock = &msm_clocks[MSM_CLOCK_GPT];
struct msm_clock_percpu_data *clock_state =
&per_cpu(msm_clocks_percpu, 0)[MSM_CLOCK_GPT];
if (clock_state->stopped)
return clock_state->stopped_tick;
return msm_read_timer_count(clock, GLOBAL_TIMER) +
clock_state->sleep_offset;
}
static cycle_t msm_dgt_read(struct clocksource *cs)
{
struct msm_clock *clock = &msm_clocks[MSM_CLOCK_DGT];
struct msm_clock_percpu_data *clock_state =
&per_cpu(msm_clocks_percpu, 0)[MSM_CLOCK_DGT];
if (clock_state->stopped)
return clock_state->stopped_tick >> clock->shift;
return (msm_read_timer_count(clock, GLOBAL_TIMER) +
clock_state->sleep_offset) >> clock->shift;
}
static struct msm_clock *clockevent_to_clock(struct clock_event_device *evt)
{
int i;
if (!is_smp())
return container_of(evt, struct msm_clock, clockevent);
for (i = 0; i < NR_TIMERS; i++)
if (evt == &(msm_clocks[i].clockevent))
return &msm_clocks[i];
return &msm_clocks[msm_global_timer];
}
static int msm_timer_set_next_event(unsigned long cycles,
struct clock_event_device *evt)
{
int i;
struct msm_clock *clock;
struct msm_clock_percpu_data *clock_state;
uint32_t now;
uint32_t alarm;
int late;
clock = clockevent_to_clock(evt);
clock_state = &__get_cpu_var(msm_clocks_percpu)[clock->index];
now = msm_read_timer_count(clock, LOCAL_TIMER);
alarm = now + (cycles << clock->shift);
if (clock->flags & MSM_CLOCK_FLAGS_ODD_MATCH_WRITE)
while (now == clock_state->last_set)
now = msm_read_timer_count(clock, LOCAL_TIMER);
clock_state->alarm = alarm;
__raw_writel(alarm, clock->regbase + TIMER_MATCH_VAL);
if (clock->flags & MSM_CLOCK_FLAGS_DELAYED_WRITE_POST) {
/* read the counter four extra times to make sure write posts
before reading the time */
for (i = 0; i < 4; i++)
__raw_readl_no_log(clock->regbase + TIMER_COUNT_VAL);
}
now = msm_read_timer_count(clock, LOCAL_TIMER);
clock_state->last_set = now;
clock_state->alarm_vtime = alarm + clock_state->sleep_offset;
late = now - alarm;
if (late >= (int)(-clock->write_delay << clock->shift) &&
late < clock->freq*5)
return -ETIME;
return 0;
}
static void msm_timer_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
struct msm_clock *clock;
struct msm_clock **cur_clock;
struct msm_clock_percpu_data *clock_state, *gpt_state;
unsigned long irq_flags;
struct irq_chip *chip;
clock = clockevent_to_clock(evt);
clock_state = &__get_cpu_var(msm_clocks_percpu)[clock->index];
gpt_state = &__get_cpu_var(msm_clocks_percpu)[MSM_CLOCK_GPT];
local_irq_save(irq_flags);
switch (mode) {
case CLOCK_EVT_MODE_RESUME:
case CLOCK_EVT_MODE_PERIODIC:
break;
case CLOCK_EVT_MODE_ONESHOT:
clock_state->stopped = 0;
clock_state->sleep_offset =
-msm_read_timer_count(clock, LOCAL_TIMER) +
clock_state->stopped_tick;
get_cpu_var(msm_active_clock) = clock;
put_cpu_var(msm_active_clock);
__raw_writel(TIMER_ENABLE_EN, clock->regbase + TIMER_ENABLE);
chip = irq_get_chip(clock->irq);
if (chip && chip->irq_unmask)
chip->irq_unmask(irq_get_irq_data(clock->irq));
if (clock != &msm_clocks[MSM_CLOCK_GPT])
__raw_writel(TIMER_ENABLE_EN,
msm_clocks[MSM_CLOCK_GPT].regbase +
TIMER_ENABLE);
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
cur_clock = &get_cpu_var(msm_active_clock);
if (*cur_clock == clock)
*cur_clock = NULL;
put_cpu_var(msm_active_clock);
clock_state->in_sync = 0;
clock_state->stopped = 1;
clock_state->stopped_tick =
msm_read_timer_count(clock, LOCAL_TIMER) +
clock_state->sleep_offset;
__raw_writel(0, clock->regbase + TIMER_MATCH_VAL);
chip = irq_get_chip(clock->irq);
if (chip && chip->irq_mask)
chip->irq_mask(irq_get_irq_data(clock->irq));
if (!is_smp() || clock != &msm_clocks[MSM_CLOCK_DGT]
|| smp_processor_id())
__raw_writel(0, clock->regbase + TIMER_ENABLE);
if (msm_global_timer == MSM_CLOCK_DGT &&
clock != &msm_clocks[MSM_CLOCK_GPT]) {
gpt_state->in_sync = 0;
__raw_writel(0, msm_clocks[MSM_CLOCK_GPT].regbase +
TIMER_ENABLE);
}
break;
}
wmb();
local_irq_restore(irq_flags);
}
void __iomem *msm_timer_get_timer0_base(void)
{
return MSM_TMR_BASE + global_timer_offset;
}
#define MPM_SCLK_COUNT_VAL 0x0024
#ifdef CONFIG_PM
/*
* Retrieve the cycle count from sclk and optionally synchronize local clock
* with the sclk value.
*
* time_start and time_expired are callbacks that must be specified. The
* protocol uses them to detect timeout. The update callback is optional.
* If not NULL, update will be called so that it can update local clock.
*
* The function does not use the argument data directly; it passes data to
* the callbacks.
*
* Return value:
* 0: the operation failed
* >0: the slow clock value after time-sync
*/
static void (*msm_timer_sync_timeout)(void);
#if defined(CONFIG_MSM_DIRECT_SCLK_ACCESS)
uint32_t msm_timer_get_sclk_ticks(void)
{
uint32_t t1, t2;
int loop_count = 10;
int loop_zero_count = 3;
int tmp = USEC_PER_SEC;
do_div(tmp, sclk_hz);
tmp /= (loop_zero_count-1);
while (loop_zero_count--) {
t1 = __raw_readl_no_log(MSM_RPM_MPM_BASE + MPM_SCLK_COUNT_VAL);
do {
udelay(1);
t2 = t1;
t1 = __raw_readl_no_log(
MSM_RPM_MPM_BASE + MPM_SCLK_COUNT_VAL);
} while ((t2 != t1) && --loop_count);
if (!loop_count) {
printk(KERN_EMERG "SCLK did not stabilize\n");
return 0;
}
if (t1)
break;
udelay(tmp);
}
if (!loop_zero_count) {
printk(KERN_EMERG "SCLK reads zero\n");
return 0;
}
return t1;
}
static uint32_t msm_timer_do_sync_to_sclk(
void (*time_start)(struct msm_timer_sync_data_t *data),
bool (*time_expired)(struct msm_timer_sync_data_t *data),
void (*update)(struct msm_timer_sync_data_t *, uint32_t, uint32_t),
struct msm_timer_sync_data_t *data)
{
unsigned t1 = msm_timer_get_sclk_ticks();
if (t1 && update != NULL)
update(data, t1, sclk_hz);
return t1;
}
#else
/* Time Master State Bits */
#define MASTER_BITS_PER_CPU 1
#define MASTER_TIME_PENDING \
(0x01UL << (MASTER_BITS_PER_CPU * SMSM_APPS_STATE))
/* Time Slave State Bits */
#define SLAVE_TIME_REQUEST 0x0400
#define SLAVE_TIME_POLL 0x0800
#define SLAVE_TIME_INIT 0x1000
static uint32_t msm_timer_do_sync_to_sclk(
void (*time_start)(struct msm_timer_sync_data_t *data),
bool (*time_expired)(struct msm_timer_sync_data_t *data),
void (*update)(struct msm_timer_sync_data_t *, uint32_t, uint32_t),
struct msm_timer_sync_data_t *data)
{
uint32_t *smem_clock;
uint32_t smem_clock_val;
uint32_t state;
smem_clock = smem_find(SMEM_SMEM_SLOW_CLOCK_VALUE,
sizeof(uint32_t), 0, SMEM_ANY_HOST_FLAG);
if (smem_clock == NULL) {
printk(KERN_ERR "no smem clock\n");
return 0;
}
state = smsm_get_state(SMSM_MODEM_STATE);
if ((state & SMSM_INIT) == 0) {
printk(KERN_ERR "smsm not initialized\n");
return 0;
}
time_start(data);
while ((state = smsm_get_state(SMSM_TIME_MASTER_DEM)) &
MASTER_TIME_PENDING) {
if (time_expired(data)) {
printk(KERN_EMERG "get_smem_clock: timeout 1 still "
"invalid state %x\n", state);
msm_timer_sync_timeout();
}
}
smsm_change_state(SMSM_APPS_DEM, SLAVE_TIME_POLL | SLAVE_TIME_INIT,
SLAVE_TIME_REQUEST);
time_start(data);
while (!((state = smsm_get_state(SMSM_TIME_MASTER_DEM)) &
MASTER_TIME_PENDING)) {
if (time_expired(data)) {
printk(KERN_EMERG "get_smem_clock: timeout 2 still "
"invalid state %x\n", state);
msm_timer_sync_timeout();
}
}
smsm_change_state(SMSM_APPS_DEM, SLAVE_TIME_REQUEST, SLAVE_TIME_POLL);
time_start(data);
do {
smem_clock_val = *smem_clock;
} while (smem_clock_val == 0 && !time_expired(data));
state = smsm_get_state(SMSM_TIME_MASTER_DEM);
if (smem_clock_val) {
if (update != NULL)
update(data, smem_clock_val, sclk_hz);
if (msm_timer_debug_mask & MSM_TIMER_DEBUG_SYNC)
printk(KERN_INFO
"get_smem_clock: state %x clock %u\n",
state, smem_clock_val);
} else {
printk(KERN_EMERG
"get_smem_clock: timeout state %x clock %u\n",
state, smem_clock_val);
msm_timer_sync_timeout();
}
smsm_change_state(SMSM_APPS_DEM, SLAVE_TIME_REQUEST | SLAVE_TIME_POLL,
SLAVE_TIME_INIT);
return smem_clock_val;
}
#endif /* CONFIG_MSM_DIRECT_SCLK_ACCESS */
/*
* Callback function that initializes the timeout value.
*/
static void msm_timer_sync_to_sclk_time_start(
struct msm_timer_sync_data_t *data)
{
/* approx 2 seconds */
uint32_t delta = data->clock->freq << data->clock->shift << 1;
data->timeout = msm_read_timer_count(data->clock, LOCAL_TIMER) + delta;
}
/*
* Callback function that checks the timeout.
*/
static bool msm_timer_sync_to_sclk_time_expired(
struct msm_timer_sync_data_t *data)
{
uint32_t delta = msm_read_timer_count(data->clock, LOCAL_TIMER) -
data->timeout;
return ((int32_t) delta) > 0;
}
/*
* Callback function that updates local clock from the specified source clock
* value and frequency.
*/
static void msm_timer_sync_update(struct msm_timer_sync_data_t *data,
uint32_t src_clk_val, uint32_t src_clk_freq)
{
struct msm_clock *dst_clk = data->clock;
struct msm_clock_percpu_data *dst_clk_state =
&__get_cpu_var(msm_clocks_percpu)[dst_clk->index];
uint32_t dst_clk_val = msm_read_timer_count(dst_clk, LOCAL_TIMER);
uint32_t new_offset;
if ((dst_clk->freq << dst_clk->shift) == src_clk_freq) {
new_offset = src_clk_val - dst_clk_val;
} else {
uint64_t temp;
/* separate multiplication and division steps to reduce
rounding error */
temp = src_clk_val;
temp *= dst_clk->freq << dst_clk->shift;
do_div(temp, src_clk_freq);
new_offset = (uint32_t)(temp) - dst_clk_val;
}
if (dst_clk_state->sleep_offset + dst_clk_state->non_sleep_offset !=
new_offset) {
if (data->exit_sleep)
dst_clk_state->sleep_offset =
new_offset - dst_clk_state->non_sleep_offset;
else
dst_clk_state->non_sleep_offset =
new_offset - dst_clk_state->sleep_offset;
if (msm_timer_debug_mask & MSM_TIMER_DEBUG_SYNC)
printk(KERN_INFO "sync clock %s: "
"src %u, new offset %u + %u\n",
dst_clk->clocksource.name, src_clk_val,
dst_clk_state->sleep_offset,
dst_clk_state->non_sleep_offset);
}
}
/*
* Synchronize GPT clock with sclk.
*/
static void msm_timer_sync_gpt_to_sclk(int exit_sleep)
{
struct msm_clock *gpt_clk = &msm_clocks[MSM_CLOCK_GPT];
struct msm_clock_percpu_data *gpt_clk_state =
&__get_cpu_var(msm_clocks_percpu)[MSM_CLOCK_GPT];
struct msm_timer_sync_data_t data;
uint32_t ret;
if (gpt_clk_state->in_sync)
return;
data.clock = gpt_clk;
data.timeout = 0;
data.exit_sleep = exit_sleep;
ret = msm_timer_do_sync_to_sclk(
msm_timer_sync_to_sclk_time_start,
msm_timer_sync_to_sclk_time_expired,
msm_timer_sync_update,
&data);
if (ret)
gpt_clk_state->in_sync = 1;
}
/*
* Synchronize clock with GPT clock.
*/
static void msm_timer_sync_to_gpt(struct msm_clock *clock, int exit_sleep)
{
struct msm_clock *gpt_clk = &msm_clocks[MSM_CLOCK_GPT];
struct msm_clock_percpu_data *gpt_clk_state =
&__get_cpu_var(msm_clocks_percpu)[MSM_CLOCK_GPT];
struct msm_clock_percpu_data *clock_state =
&__get_cpu_var(msm_clocks_percpu)[clock->index];
struct msm_timer_sync_data_t data;
uint32_t gpt_clk_val;
u64 gpt_period = (1ULL << 32) * HZ;
u64 now = get_jiffies_64();
do_div(gpt_period, gpt_hz);
BUG_ON(clock == gpt_clk);
if (clock_state->in_sync &&
(now - clock_state->last_sync_jiffies < (gpt_period >> 1)))
return;
gpt_clk_val = msm_read_timer_count(gpt_clk, LOCAL_TIMER)
+ gpt_clk_state->sleep_offset + gpt_clk_state->non_sleep_offset;
if (exit_sleep && gpt_clk_val < clock_state->last_sync_gpt)
clock_state->non_sleep_offset -= clock->rollover_offset;
data.clock = clock;
data.timeout = 0;
data.exit_sleep = exit_sleep;
msm_timer_sync_update(&data, gpt_clk_val, gpt_hz);
clock_state->in_sync = 1;
clock_state->last_sync_gpt = gpt_clk_val;
clock_state->last_sync_jiffies = now;
}
static void msm_timer_reactivate_alarm(struct msm_clock *clock)
{
struct msm_clock_percpu_data *clock_state =
&__get_cpu_var(msm_clocks_percpu)[clock->index];
long alarm_delta = clock_state->alarm_vtime -
clock_state->sleep_offset -
msm_read_timer_count(clock, LOCAL_TIMER);
alarm_delta >>= clock->shift;
if (alarm_delta < (long)clock->write_delay + 4)
alarm_delta = clock->write_delay + 4;
while (msm_timer_set_next_event(alarm_delta, &clock->clockevent))
;
}
int64_t msm_timer_enter_idle(void)
{
struct msm_clock *gpt_clk = &msm_clocks[MSM_CLOCK_GPT];
struct msm_clock *clock = __get_cpu_var(msm_active_clock);
struct msm_clock_percpu_data *clock_state =
&__get_cpu_var(msm_clocks_percpu)[clock->index];
uint32_t alarm;
uint32_t count;
int32_t delta;
BUG_ON(clock != &msm_clocks[MSM_CLOCK_GPT] &&
clock != &msm_clocks[MSM_CLOCK_DGT]);
msm_timer_sync_gpt_to_sclk(0);
if (clock != gpt_clk)
msm_timer_sync_to_gpt(clock, 0);
count = msm_read_timer_count(clock, LOCAL_TIMER);
if (clock_state->stopped++ == 0)
clock_state->stopped_tick = count + clock_state->sleep_offset;
alarm = clock_state->alarm;
delta = alarm - count;
if (delta <= -(int32_t)((clock->freq << clock->shift) >> 10)) {
/* timer should have triggered 1ms ago */
printk(KERN_ERR "msm_timer_enter_idle: timer late %d, "
"reprogram it\n", delta);
msm_timer_reactivate_alarm(clock);
}
if (delta <= 0)
return 0;
return clocksource_cyc2ns((alarm - count) >> clock->shift,
clock->clocksource.mult,
clock->clocksource.shift);
}
void msm_timer_exit_idle(int low_power)
{
struct msm_clock *gpt_clk = &msm_clocks[MSM_CLOCK_GPT];
struct msm_clock *clock = __get_cpu_var(msm_active_clock);
struct msm_clock_percpu_data *gpt_clk_state =
&__get_cpu_var(msm_clocks_percpu)[MSM_CLOCK_GPT];
struct msm_clock_percpu_data *clock_state =
&__get_cpu_var(msm_clocks_percpu)[clock->index];
uint32_t enabled;
BUG_ON(clock != &msm_clocks[MSM_CLOCK_GPT] &&
clock != &msm_clocks[MSM_CLOCK_DGT]);
if (!low_power)
goto exit_idle_exit;
enabled = __raw_readl(gpt_clk->regbase + TIMER_ENABLE) &
TIMER_ENABLE_EN;
if (!enabled)
__raw_writel(TIMER_ENABLE_EN, gpt_clk->regbase + TIMER_ENABLE);
#if defined(CONFIG_ARCH_MSM_SCORPION) || defined(CONFIG_ARCH_MSM_KRAIT)
gpt_clk_state->in_sync = 0;
#else
gpt_clk_state->in_sync = gpt_clk_state->in_sync && enabled;
#endif
/* Make sure timer is actually enabled before we sync it */
wmb();
msm_timer_sync_gpt_to_sclk(1);
if (clock == gpt_clk)
goto exit_idle_alarm;
enabled = __raw_readl(clock->regbase + TIMER_ENABLE) & TIMER_ENABLE_EN;
if (!enabled)
__raw_writel(TIMER_ENABLE_EN, clock->regbase + TIMER_ENABLE);
#if defined(CONFIG_ARCH_MSM_SCORPION) || defined(CONFIG_ARCH_MSM_KRAIT)
clock_state->in_sync = 0;
#else
clock_state->in_sync = clock_state->in_sync && enabled;
#endif
/* Make sure timer is actually enabled before we sync it */
wmb();
msm_timer_sync_to_gpt(clock, 1);
exit_idle_alarm:
msm_timer_reactivate_alarm(clock);
exit_idle_exit:
clock_state->stopped--;
}
/*
* Callback function that initializes the timeout value.
*/
static void msm_timer_get_sclk_time_start(
struct msm_timer_sync_data_t *data)
{
data->timeout = 200000;
}
/*
* Callback function that checks the timeout.
*/
static bool msm_timer_get_sclk_time_expired(
struct msm_timer_sync_data_t *data)
{
udelay(10);
return --data->timeout <= 0;
}
/*
* Retrieve the cycle count from the sclk and convert it into
* nanoseconds.
*
* On exit, if period is not NULL, it contains the period of the
* sclk in nanoseconds, i.e. how long the cycle count wraps around.
*
* Return value:
* 0: the operation failed; period is not set either
* >0: time in nanoseconds
*/
int64_t msm_timer_get_sclk_time(int64_t *period)
{
struct msm_timer_sync_data_t data;
uint32_t clock_value;
int64_t tmp;
memset(&data, 0, sizeof(data));
clock_value = msm_timer_do_sync_to_sclk(
msm_timer_get_sclk_time_start,
msm_timer_get_sclk_time_expired,
NULL,
&data);
if (!clock_value)
return 0;
if (period) {
tmp = 1LL << 32;
tmp *= NSEC_PER_SEC;
do_div(tmp, sclk_hz);
*period = tmp;
}
tmp = (int64_t)clock_value;
tmp *= NSEC_PER_SEC;
do_div(tmp, sclk_hz);
return tmp;
}
int __init msm_timer_init_time_sync(void (*timeout)(void))
{
#if !defined(CONFIG_MSM_DIRECT_SCLK_ACCESS)
int ret = smsm_change_intr_mask(SMSM_TIME_MASTER_DEM, 0xFFFFFFFF, 0);
if (ret) {
printk(KERN_ERR "%s: failed to clear interrupt mask, %d\n",
__func__, ret);
return ret;
}
smsm_change_state(SMSM_APPS_DEM,
SLAVE_TIME_REQUEST | SLAVE_TIME_POLL, SLAVE_TIME_INIT);
#endif
BUG_ON(timeout == NULL);
msm_timer_sync_timeout = timeout;
return 0;
}
#endif
static u32 notrace msm_read_sched_clock(void)
{
struct msm_clock *clock = &msm_clocks[msm_global_timer];
struct clocksource *cs = &clock->clocksource;
return cs->read(NULL);
}
static struct delay_timer msm_delay_timer;
static unsigned long msm_read_current_timer(void)
{
struct msm_clock *dgt = &msm_clocks[MSM_CLOCK_DGT];
return msm_read_timer_count(dgt, GLOBAL_TIMER);
}
static void __init msm_sched_clock_init(void)
{
struct msm_clock *clock = &msm_clocks[msm_global_timer];
setup_sched_clock(msm_read_sched_clock, 32 - clock->shift, clock->freq);
}
#ifdef CONFIG_LOCAL_TIMERS
int __cpuinit local_timer_setup(struct clock_event_device *evt)
{
static DEFINE_PER_CPU(bool, first_boot) = true;
struct msm_clock *clock = &msm_clocks[msm_global_timer];
/* Use existing clock_event for cpu 0 */
if (!smp_processor_id())
return 0;
if (cpu_is_msm8x60() || soc_class_is_msm8960() ||
soc_class_is_apq8064() || soc_class_is_msm8930())
__raw_writel(DGT_CLK_CTL_DIV_4, MSM_TMR_BASE + DGT_CLK_CTL);
if (__get_cpu_var(first_boot)) {
__raw_writel(0, clock->regbase + TIMER_ENABLE);
__raw_writel(0, clock->regbase + TIMER_CLEAR);
__raw_writel(~0, clock->regbase + TIMER_MATCH_VAL);
__get_cpu_var(first_boot) = false;
if (clock->status_mask)
while (__raw_readl(MSM_TMR_BASE + TIMER_STATUS) &
clock->status_mask)
;
}
evt->irq = clock->irq;
evt->name = "local_timer";
evt->features = CLOCK_EVT_FEAT_ONESHOT;
evt->rating = clock->clockevent.rating;
evt->set_mode = msm_timer_set_mode;
evt->set_next_event = msm_timer_set_next_event;
*__this_cpu_ptr(clock->percpu_evt) = evt;
clockevents_config_and_register(evt, gpt_hz, 4, 0xf0000000);
enable_percpu_irq(evt->irq, IRQ_TYPE_EDGE_RISING);
return 0;
}
void local_timer_stop(struct clock_event_device *evt)
{
evt->set_mode(CLOCK_EVT_MODE_UNUSED, evt);
disable_percpu_irq(evt->irq);
}
static struct local_timer_ops msm_lt_ops = {
local_timer_setup,
local_timer_stop,
};
#endif /* CONFIG_LOCAL_TIMERS */
#ifdef CONFIG_ARCH_MSM8625
static void fixup_msm8625_timer(void)
{
struct msm_clock *dgt = &msm_clocks[MSM_CLOCK_DGT];
struct msm_clock *gpt = &msm_clocks[MSM_CLOCK_GPT];
dgt->irq = MSM8625_INT_DEBUG_TIMER_EXP;
gpt->irq = MSM8625_INT_GP_TIMER_EXP;
global_timer_offset = MSM_TMR0_BASE - MSM_TMR_BASE;
}
#else
static inline void fixup_msm8625_timer(void) { };
#endif
void __init msm_timer_init(void)
{
int i;
int res;
struct irq_chip *chip;
struct msm_clock *dgt = &msm_clocks[MSM_CLOCK_DGT];
struct msm_clock *gpt = &msm_clocks[MSM_CLOCK_GPT];
if (cpu_is_msm7x01() || cpu_is_msm7x25() || cpu_is_msm7x27() ||
cpu_is_msm7x25a() || cpu_is_msm7x27a() || cpu_is_msm7x25aa() ||
cpu_is_msm7x27aa() || cpu_is_msm8625() || cpu_is_msm7x25ab() ||
cpu_is_msm8625q()) {
dgt->shift = MSM_DGT_SHIFT;
dgt->freq = 19200000 >> MSM_DGT_SHIFT;
dgt->clockevent.shift = 32 + MSM_DGT_SHIFT;
dgt->clocksource.mask = CLOCKSOURCE_MASK(32 - MSM_DGT_SHIFT);
gpt->regbase = MSM_TMR_BASE;
dgt->regbase = MSM_TMR_BASE + 0x10;
gpt->flags |= MSM_CLOCK_FLAGS_UNSTABLE_COUNT
| MSM_CLOCK_FLAGS_ODD_MATCH_WRITE
| MSM_CLOCK_FLAGS_DELAYED_WRITE_POST;
if (cpu_is_msm8625() || cpu_is_msm8625q())
fixup_msm8625_timer();
} else if (cpu_is_qsd8x50()) {
dgt->freq = 4800000;
gpt->regbase = MSM_TMR_BASE;
dgt->regbase = MSM_TMR_BASE + 0x10;
} else if (cpu_is_fsm9xxx())
dgt->freq = 4800000;
else if (cpu_is_msm7x30() || cpu_is_msm8x55()) {
gpt->status_mask = BIT(10);
dgt->status_mask = BIT(2);
dgt->freq = 6144000;
} else if (cpu_is_msm8x60()) {
global_timer_offset = MSM_TMR0_BASE - MSM_TMR_BASE;
gpt->status_mask = BIT(10);
dgt->status_mask = BIT(2);
dgt->freq = 6750000;
__raw_writel(DGT_CLK_CTL_DIV_4, MSM_TMR_BASE + DGT_CLK_CTL);
} else if (cpu_is_msm9615()) {
dgt->freq = 6750000;
__raw_writel(DGT_CLK_CTL_DIV_4, MSM_TMR_BASE + DGT_CLK_CTL);
gpt->status_mask = BIT(10);
dgt->status_mask = BIT(2);
gpt->freq = 32765;
gpt_hz = 32765;
sclk_hz = 32765;
gpt->flags |= MSM_CLOCK_FLAGS_UNSTABLE_COUNT;
dgt->flags |= MSM_CLOCK_FLAGS_UNSTABLE_COUNT;
} else if (soc_class_is_msm8960() || soc_class_is_apq8064() ||
soc_class_is_msm8930()) {
global_timer_offset = MSM_TMR0_BASE - MSM_TMR_BASE;
dgt->freq = 6750000;
__raw_writel(DGT_CLK_CTL_DIV_4, MSM_TMR_BASE + DGT_CLK_CTL);
gpt->status_mask = BIT(10);
dgt->status_mask = BIT(2);
if (!soc_class_is_apq8064()) {
gpt->freq = 32765;
gpt_hz = 32765;
sclk_hz = 32765;
}
if (!soc_class_is_msm8930() && !cpu_is_msm8960ab()) {
gpt->flags |= MSM_CLOCK_FLAGS_UNSTABLE_COUNT;
dgt->flags |= MSM_CLOCK_FLAGS_UNSTABLE_COUNT;
}
} else {
WARN(1, "Timer running on unknown hardware. Configure this! "
"Assuming default configuration.\n");
dgt->freq = 6750000;
}
if (msm_clocks[MSM_CLOCK_GPT].clocksource.rating > DG_TIMER_RATING)
msm_global_timer = MSM_CLOCK_GPT;
else
msm_global_timer = MSM_CLOCK_DGT;
for (i = 0; i < ARRAY_SIZE(msm_clocks); i++) {
struct msm_clock *clock = &msm_clocks[i];
struct clock_event_device *ce = &clock->clockevent;
struct clocksource *cs = &clock->clocksource;
__raw_writel(0, clock->regbase + TIMER_ENABLE);
__raw_writel(0, clock->regbase + TIMER_CLEAR);
__raw_writel(~0, clock->regbase + TIMER_MATCH_VAL);
if ((clock->freq << clock->shift) == gpt_hz) {
clock->rollover_offset = 0;
} else {
uint64_t temp;
temp = clock->freq << clock->shift;
temp <<= 32;
do_div(temp, gpt_hz);
clock->rollover_offset = (uint32_t) temp;
}
ce->mult = div_sc(clock->freq, NSEC_PER_SEC, ce->shift);
/* allow at least 10 seconds to notice that the timer wrapped */
ce->max_delta_ns =
clockevent_delta2ns(0xf0000000 >> clock->shift, ce);
/* ticks gets rounded down by one */
ce->min_delta_ns =
clockevent_delta2ns(clock->write_delay + 4, ce);
ce->cpumask = cpumask_of(0);
res = clocksource_register_hz(cs, clock->freq);
if (res)
printk(KERN_ERR "msm_timer_init: clocksource_register "
"failed for %s\n", cs->name);
ce->irq = clock->irq;
if (cpu_is_msm8x60() || cpu_is_msm9615() || cpu_is_msm8625() ||
cpu_is_msm8625q() || soc_class_is_msm8960() ||
soc_class_is_apq8064() || soc_class_is_msm8930()) {
clock->percpu_evt = alloc_percpu(struct clock_event_device *);
if (!clock->percpu_evt) {
pr_err("msm_timer_init: memory allocation "
"failed for %s\n", ce->name);
continue;
}
*__this_cpu_ptr(clock->percpu_evt) = ce;
res = request_percpu_irq(ce->irq, msm_timer_interrupt,
ce->name, clock->percpu_evt);
if (!res)
enable_percpu_irq(ce->irq,
IRQ_TYPE_EDGE_RISING);
} else {
clock->evt = ce;
res = request_irq(ce->irq, msm_timer_interrupt,
IRQF_TIMER | IRQF_NOBALANCING | IRQF_TRIGGER_RISING,
ce->name, &clock->evt);
}
if (res)
pr_err("msm_timer_init: request_irq failed for %s\n",
ce->name);
chip = irq_get_chip(clock->irq);
if (chip && chip->irq_mask)
chip->irq_mask(irq_get_irq_data(clock->irq));
if (clock->status_mask)
while (__raw_readl(MSM_TMR_BASE + TIMER_STATUS) &
clock->status_mask)
;
clockevents_register_device(ce);
}
msm_sched_clock_init();
if (use_user_accessible_timers()) {
if (cpu_is_msm8960() || cpu_is_msm8930() || cpu_is_apq8064()) {
struct msm_clock *gtclock = &msm_clocks[MSM_CLOCK_GPT];
void __iomem *addr = gtclock->regbase +
TIMER_COUNT_VAL + global_timer_offset;
setup_user_timer_offset(virt_to_phys(addr)&0xfff);
set_user_accessible_timer_flag(true);
}
}
if (is_smp()) {
__raw_writel(1,
msm_clocks[MSM_CLOCK_DGT].regbase + TIMER_ENABLE);
msm_delay_timer.freq = dgt->freq;
msm_delay_timer.read_current_timer = &msm_read_current_timer;
register_current_timer_delay(&msm_delay_timer);
}
#ifdef CONFIG_LOCAL_TIMERS
local_timer_register(&msm_lt_ops);
#endif
}
| gpl-2.0 |
tohenk/android_kernel_samsung_smdk4x12 | drivers/usb/gadget/f_audio_source.c | 255 | 21897 | /*
* Gadget Function Driver for USB audio source device
*
* Copyright (C) 2012 Google, Inc.
*
* 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/device.h>
#include <linux/usb/audio.h>
#include <linux/wait.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/pcm.h>
#define SAMPLE_RATE 44100
#define FRAMES_PER_MSEC (SAMPLE_RATE / 1000)
#define IN_EP_MAX_PACKET_SIZE 384
/* Number of requests to allocate */
#define IN_EP_REQ_COUNT 4
#define AUDIO_AC_INTERFACE 0
#define AUDIO_AS_INTERFACE 1
#define AUDIO_NUM_INTERFACES 2
/* B.3.1 Standard AC Interface Descriptor */
static struct usb_interface_descriptor ac_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL,
};
DECLARE_UAC_AC_HEADER_DESCRIPTOR(2);
#define UAC_DT_AC_HEADER_LENGTH UAC_DT_AC_HEADER_SIZE(AUDIO_NUM_INTERFACES)
/* 1 input terminal, 1 output terminal and 1 feature unit */
#define UAC_DT_TOTAL_LENGTH (UAC_DT_AC_HEADER_LENGTH \
+ UAC_DT_INPUT_TERMINAL_SIZE + UAC_DT_OUTPUT_TERMINAL_SIZE \
+ UAC_DT_FEATURE_UNIT_SIZE(0))
/* B.3.2 Class-Specific AC Interface Descriptor */
static struct uac1_ac_header_descriptor_2 ac_header_desc = {
.bLength = UAC_DT_AC_HEADER_LENGTH,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_HEADER,
.bcdADC = __constant_cpu_to_le16(0x0100),
.wTotalLength = __constant_cpu_to_le16(UAC_DT_TOTAL_LENGTH),
.bInCollection = AUDIO_NUM_INTERFACES,
.baInterfaceNr = {
[0] = AUDIO_AC_INTERFACE,
[1] = AUDIO_AS_INTERFACE,
}
};
#define INPUT_TERMINAL_ID 1
static struct uac_input_terminal_descriptor input_terminal_desc = {
.bLength = UAC_DT_INPUT_TERMINAL_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_INPUT_TERMINAL,
.bTerminalID = INPUT_TERMINAL_ID,
.wTerminalType = UAC_INPUT_TERMINAL_MICROPHONE,
.bAssocTerminal = 0,
.wChannelConfig = 0x3,
};
DECLARE_UAC_FEATURE_UNIT_DESCRIPTOR(0);
#define FEATURE_UNIT_ID 2
static struct uac_feature_unit_descriptor_0 feature_unit_desc = {
.bLength = UAC_DT_FEATURE_UNIT_SIZE(0),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_FEATURE_UNIT,
.bUnitID = FEATURE_UNIT_ID,
.bSourceID = INPUT_TERMINAL_ID,
.bControlSize = 2,
};
#define OUTPUT_TERMINAL_ID 3
static struct uac1_output_terminal_descriptor output_terminal_desc = {
.bLength = UAC_DT_OUTPUT_TERMINAL_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_OUTPUT_TERMINAL,
.bTerminalID = OUTPUT_TERMINAL_ID,
.wTerminalType = UAC_TERMINAL_STREAMING,
.bAssocTerminal = FEATURE_UNIT_ID,
.bSourceID = FEATURE_UNIT_ID,
};
/* B.4.1 Standard AS Interface Descriptor */
static struct usb_interface_descriptor as_interface_alt_0_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bAlternateSetting = 0,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
};
static struct usb_interface_descriptor as_interface_alt_1_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bAlternateSetting = 1,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
};
/* B.4.2 Class-Specific AS Interface Descriptor */
static struct uac1_as_header_descriptor as_header_desc = {
.bLength = UAC_DT_AS_HEADER_SIZE,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_AS_GENERAL,
.bTerminalLink = INPUT_TERMINAL_ID,
.bDelay = 1,
.wFormatTag = UAC_FORMAT_TYPE_I_PCM,
};
DECLARE_UAC_FORMAT_TYPE_I_DISCRETE_DESC(1);
static struct uac_format_type_i_discrete_descriptor_1 as_type_i_desc = {
.bLength = UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubtype = UAC_FORMAT_TYPE,
.bFormatType = UAC_FORMAT_TYPE_I,
.bSubframeSize = 2,
.bBitResolution = 16,
.bSamFreqType = 1,
};
/* Standard ISO IN Endpoint Descriptor for highspeed */
static struct usb_endpoint_descriptor hs_as_in_ep_desc = {
.bLength = USB_DT_ENDPOINT_AUDIO_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_SYNC_SYNC
| USB_ENDPOINT_XFER_ISOC,
.wMaxPacketSize = __constant_cpu_to_le16(IN_EP_MAX_PACKET_SIZE),
.bInterval = 4, /* poll 1 per millisecond */
};
/* Standard ISO IN Endpoint Descriptor for highspeed */
static struct usb_endpoint_descriptor fs_as_in_ep_desc = {
.bLength = USB_DT_ENDPOINT_AUDIO_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_SYNC_SYNC
| USB_ENDPOINT_XFER_ISOC,
.wMaxPacketSize = __constant_cpu_to_le16(IN_EP_MAX_PACKET_SIZE),
.bInterval = 1, /* poll 1 per millisecond */
};
/* Class-specific AS ISO OUT Endpoint Descriptor */
static struct uac_iso_endpoint_descriptor as_iso_in_desc = {
.bLength = UAC_ISO_ENDPOINT_DESC_SIZE,
.bDescriptorType = USB_DT_CS_ENDPOINT,
.bDescriptorSubtype = UAC_EP_GENERAL,
.bmAttributes = 1,
.bLockDelayUnits = 1,
.wLockDelay = __constant_cpu_to_le16(1),
};
static struct usb_descriptor_header *hs_audio_desc[] = {
(struct usb_descriptor_header *)&ac_interface_desc,
(struct usb_descriptor_header *)&ac_header_desc,
(struct usb_descriptor_header *)&input_terminal_desc,
(struct usb_descriptor_header *)&output_terminal_desc,
(struct usb_descriptor_header *)&feature_unit_desc,
(struct usb_descriptor_header *)&as_interface_alt_0_desc,
(struct usb_descriptor_header *)&as_interface_alt_1_desc,
(struct usb_descriptor_header *)&as_header_desc,
(struct usb_descriptor_header *)&as_type_i_desc,
(struct usb_descriptor_header *)&hs_as_in_ep_desc,
(struct usb_descriptor_header *)&as_iso_in_desc,
NULL,
};
static struct usb_descriptor_header *fs_audio_desc[] = {
(struct usb_descriptor_header *)&ac_interface_desc,
(struct usb_descriptor_header *)&ac_header_desc,
(struct usb_descriptor_header *)&input_terminal_desc,
(struct usb_descriptor_header *)&output_terminal_desc,
(struct usb_descriptor_header *)&feature_unit_desc,
(struct usb_descriptor_header *)&as_interface_alt_0_desc,
(struct usb_descriptor_header *)&as_interface_alt_1_desc,
(struct usb_descriptor_header *)&as_header_desc,
(struct usb_descriptor_header *)&as_type_i_desc,
(struct usb_descriptor_header *)&fs_as_in_ep_desc,
(struct usb_descriptor_header *)&as_iso_in_desc,
NULL,
};
static struct snd_pcm_hardware audio_hw_info = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BATCH |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 2,
.channels_max = 2,
.rate_min = SAMPLE_RATE,
.rate_max = SAMPLE_RATE,
.buffer_bytes_max = 1024 * 1024,
.period_bytes_min = 64,
.period_bytes_max = 512 * 1024,
.periods_min = 2,
.periods_max = 1024,
};
/*-------------------------------------------------------------------------*/
struct audio_source_config {
int card;
int device;
};
struct audio_dev {
struct usb_function func;
struct snd_card *card;
struct snd_pcm *pcm;
struct snd_pcm_substream *substream;
struct list_head idle_reqs;
struct usb_ep *in_ep;
struct usb_endpoint_descriptor *in_desc;
spinlock_t lock;
/* beginning, end and current position in our buffer */
void *buffer_start;
void *buffer_end;
void *buffer_pos;
/* byte size of a "period" */
unsigned int period;
/* bytes sent since last call to snd_pcm_period_elapsed */
unsigned int period_offset;
/* time we started playing */
ktime_t start_time;
/* number of frames sent since start_time */
s64 frames_sent;
};
static inline struct audio_dev *func_to_audio(struct usb_function *f)
{
return container_of(f, struct audio_dev, func);
}
/*-------------------------------------------------------------------------*/
static struct usb_request *audio_request_new(struct usb_ep *ep, int buffer_size)
{
struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (!req)
return NULL;
req->buf = kmalloc(buffer_size, GFP_KERNEL);
if (!req->buf) {
usb_ep_free_request(ep, req);
return NULL;
}
req->length = buffer_size;
return req;
}
static void audio_request_free(struct usb_request *req, struct usb_ep *ep)
{
if (req) {
kfree(req->buf);
usb_ep_free_request(ep, req);
}
}
static void audio_req_put(struct audio_dev *audio, struct usb_request *req)
{
unsigned long flags;
spin_lock_irqsave(&audio->lock, flags);
list_add_tail(&req->list, &audio->idle_reqs);
spin_unlock_irqrestore(&audio->lock, flags);
}
static struct usb_request *audio_req_get(struct audio_dev *audio)
{
unsigned long flags;
struct usb_request *req;
spin_lock_irqsave(&audio->lock, flags);
if (list_empty(&audio->idle_reqs)) {
req = 0;
} else {
req = list_first_entry(&audio->idle_reqs, struct usb_request,
list);
list_del(&req->list);
}
spin_unlock_irqrestore(&audio->lock, flags);
return req;
}
/* send the appropriate number of packets to match our bitrate */
static void audio_send(struct audio_dev *audio)
{
struct snd_pcm_runtime *runtime;
struct usb_request *req;
int length, length1, length2, ret;
s64 msecs;
s64 frames;
ktime_t now;
/* audio->substream will be null if we have been closed */
if (!audio->substream)
return;
/* audio->buffer_pos will be null if we have been stopped */
if (!audio->buffer_pos)
return;
runtime = audio->substream->runtime;
/* compute number of frames to send */
now = ktime_get();
msecs = ktime_to_ns(now) - ktime_to_ns(audio->start_time);
do_div(msecs, 1000000);
frames = msecs * SAMPLE_RATE;
do_div(frames, 1000);
/* Readjust our frames_sent if we fall too far behind.
* If we get too far behind it is better to drop some frames than
* to keep sending data too fast in an attempt to catch up.
*/
if (frames - audio->frames_sent > 10 * FRAMES_PER_MSEC)
audio->frames_sent = frames - FRAMES_PER_MSEC;
frames -= audio->frames_sent;
/* We need to send something to keep the pipeline going */
if (frames <= 0)
frames = FRAMES_PER_MSEC;
while (frames > 0) {
req = audio_req_get(audio);
if (!req)
break;
length = frames_to_bytes(runtime, frames);
if (length > IN_EP_MAX_PACKET_SIZE)
length = IN_EP_MAX_PACKET_SIZE;
if (audio->buffer_pos + length > audio->buffer_end)
length1 = audio->buffer_end - audio->buffer_pos;
else
length1 = length;
memcpy(req->buf, audio->buffer_pos, length1);
if (length1 < length) {
/* Wrap around and copy remaining length
* at beginning of buffer.
*/
length2 = length - length1;
memcpy(req->buf + length1, audio->buffer_start,
length2);
audio->buffer_pos = audio->buffer_start + length2;
} else {
audio->buffer_pos += length1;
if (audio->buffer_pos >= audio->buffer_end)
audio->buffer_pos = audio->buffer_start;
}
req->length = length;
ret = usb_ep_queue(audio->in_ep, req, GFP_ATOMIC);
if (ret < 0) {
pr_err("usb_ep_queue failed ret: %d\n", ret);
audio_req_put(audio, req);
break;
}
frames -= bytes_to_frames(runtime, length);
audio->frames_sent += bytes_to_frames(runtime, length);
}
}
static void audio_control_complete(struct usb_ep *ep, struct usb_request *req)
{
/* nothing to do here */
}
static void audio_data_complete(struct usb_ep *ep, struct usb_request *req)
{
struct audio_dev *audio = req->context;
pr_debug("audio_data_complete req->status %d req->actual %d\n",
req->status, req->actual);
audio_req_put(audio, req);
if (!audio->buffer_start || req->status)
return;
audio->period_offset += req->actual;
if (audio->period_offset >= audio->period) {
snd_pcm_period_elapsed(audio->substream);
audio->period_offset = 0;
}
audio_send(audio);
}
static int audio_set_endpoint_req(struct usb_function *f,
const struct usb_ctrlrequest *ctrl)
{
int value = -EOPNOTSUPP;
u16 ep = le16_to_cpu(ctrl->wIndex);
u16 len = le16_to_cpu(ctrl->wLength);
u16 w_value = le16_to_cpu(ctrl->wValue);
pr_debug("bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
ctrl->bRequest, w_value, len, ep);
switch (ctrl->bRequest) {
case UAC_SET_CUR:
case UAC_SET_MIN:
case UAC_SET_MAX:
case UAC_SET_RES:
value = len;
break;
default:
break;
}
return value;
}
static int audio_get_endpoint_req(struct usb_function *f,
const struct usb_ctrlrequest *ctrl)
{
struct usb_composite_dev *cdev = f->config->cdev;
int value = -EOPNOTSUPP;
u8 ep = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
u16 len = le16_to_cpu(ctrl->wLength);
u16 w_value = le16_to_cpu(ctrl->wValue);
u8 *buf = cdev->req->buf;
pr_debug("bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
ctrl->bRequest, w_value, len, ep);
if (w_value == UAC_EP_CS_ATTR_SAMPLE_RATE << 8) {
switch (ctrl->bRequest) {
case UAC_GET_CUR:
case UAC_GET_MIN:
case UAC_GET_MAX:
case UAC_GET_RES:
/* return our sample rate */
buf[0] = (u8)SAMPLE_RATE;
buf[1] = (u8)(SAMPLE_RATE >> 8);
buf[2] = (u8)(SAMPLE_RATE >> 16);
value = 3;
break;
default:
break;
}
}
return value;
}
static int
audio_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
/* composite driver infrastructure handles everything; interface
* activation uses set_alt().
*/
switch (ctrl->bRequestType) {
case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
value = audio_set_endpoint_req(f, ctrl);
break;
case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
value = audio_get_endpoint_req(f, ctrl);
break;
}
/* respond with data transfer or status phase? */
if (value >= 0) {
pr_debug("audio req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->zero = 0;
req->length = value;
req->complete = audio_control_complete;
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
pr_err("audio response on err %d\n", value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
static int audio_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct audio_dev *audio = func_to_audio(f);
pr_debug("audio_set_alt intf %d, alt %d\n", intf, alt);
usb_ep_enable(audio->in_ep, audio->in_desc);
return 0;
}
static void audio_disable(struct usb_function *f)
{
struct audio_dev *audio = func_to_audio(f);
pr_debug("audio_disable\n");
usb_ep_disable(audio->in_ep);
}
/*-------------------------------------------------------------------------*/
static void audio_build_desc(struct audio_dev *audio)
{
u8 *sam_freq;
int rate;
/* Set channel numbers */
input_terminal_desc.bNrChannels = 2;
as_type_i_desc.bNrChannels = 2;
/* Set sample rates */
rate = SAMPLE_RATE;
sam_freq = as_type_i_desc.tSamFreq[0];
memcpy(sam_freq, &rate, 3);
}
/* audio function driver setup/binding */
static int
audio_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct audio_dev *audio = func_to_audio(f);
int status;
struct usb_ep *ep;
struct usb_request *req;
int i;
audio_build_desc(audio);
/* allocate instance-specific interface IDs, and patch descriptors */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
ac_interface_desc.bInterfaceNumber = status;
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
as_interface_alt_0_desc.bInterfaceNumber = status;
as_interface_alt_1_desc.bInterfaceNumber = status;
status = -ENODEV;
/* allocate our endpoint */
ep = usb_ep_autoconfig(cdev->gadget, &fs_as_in_ep_desc);
if (!ep)
goto fail;
audio->in_ep = ep;
ep->driver_data = audio; /* claim */
if (gadget_is_dualspeed(c->cdev->gadget))
hs_as_in_ep_desc.bEndpointAddress =
fs_as_in_ep_desc.bEndpointAddress;
f->descriptors = fs_audio_desc;
f->hs_descriptors = hs_audio_desc;
for (i = 0, status = 0; i < IN_EP_REQ_COUNT && status == 0; i++) {
req = audio_request_new(ep, IN_EP_MAX_PACKET_SIZE);
if (req) {
req->context = audio;
req->complete = audio_data_complete;
audio_req_put(audio, req);
} else
status = -ENOMEM;
}
fail:
return status;
}
static void
audio_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct audio_dev *audio = func_to_audio(f);
struct usb_request *req;
while ((req = audio_req_get(audio)))
audio_request_free(req, audio->in_ep);
snd_card_free_when_closed(audio->card);
audio->card = NULL;
audio->pcm = NULL;
audio->substream = NULL;
audio->in_ep = NULL;
}
static void audio_pcm_playback_start(struct audio_dev *audio)
{
audio->start_time = ktime_get();
audio->frames_sent = 0;
audio_send(audio);
}
static void audio_pcm_playback_stop(struct audio_dev *audio)
{
unsigned long flags;
spin_lock_irqsave(&audio->lock, flags);
audio->buffer_start = 0;
audio->buffer_end = 0;
audio->buffer_pos = 0;
spin_unlock_irqrestore(&audio->lock, flags);
}
static int audio_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct audio_dev *audio = substream->private_data;
runtime->private_data = audio;
runtime->hw = audio_hw_info;
snd_pcm_limit_hw_rates(runtime);
runtime->hw.channels_max = 2;
audio->substream = substream;
return 0;
}
static int audio_pcm_close(struct snd_pcm_substream *substream)
{
struct audio_dev *audio = substream->private_data;
unsigned long flags;
spin_lock_irqsave(&audio->lock, flags);
audio->substream = NULL;
spin_unlock_irqrestore(&audio->lock, flags);
return 0;
}
static int audio_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
unsigned int channels = params_channels(params);
unsigned int rate = params_rate(params);
if (rate != SAMPLE_RATE)
return -EINVAL;
if (channels != 2)
return -EINVAL;
return snd_pcm_lib_alloc_vmalloc_buffer(substream,
params_buffer_bytes(params));
}
static int audio_pcm_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_vmalloc_buffer(substream);
}
static int audio_pcm_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct audio_dev *audio = runtime->private_data;
audio->period = snd_pcm_lib_period_bytes(substream);
audio->period_offset = 0;
audio->buffer_start = runtime->dma_area;
audio->buffer_end = audio->buffer_start
+ snd_pcm_lib_buffer_bytes(substream);
audio->buffer_pos = audio->buffer_start;
return 0;
}
static snd_pcm_uframes_t audio_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct audio_dev *audio = runtime->private_data;
ssize_t bytes = audio->buffer_pos - audio->buffer_start;
/* return offset of next frame to fill in our buffer */
return bytes_to_frames(runtime, bytes);
}
static int audio_pcm_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct audio_dev *audio = substream->runtime->private_data;
int ret = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
audio_pcm_playback_start(audio);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
audio_pcm_playback_stop(audio);
break;
default:
ret = -EINVAL;
}
return ret;
}
static struct audio_dev _audio_dev = {
.func = {
.name = "audio_source",
.bind = audio_bind,
.unbind = audio_unbind,
.set_alt = audio_set_alt,
.setup = audio_setup,
.disable = audio_disable,
},
.in_desc = &fs_as_in_ep_desc,
.lock = __SPIN_LOCK_UNLOCKED(_audio_dev.lock),
.idle_reqs = LIST_HEAD_INIT(_audio_dev.idle_reqs),
};
static struct snd_pcm_ops audio_playback_ops = {
.open = audio_pcm_open,
.close = audio_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = audio_pcm_hw_params,
.hw_free = audio_pcm_hw_free,
.prepare = audio_pcm_prepare,
.trigger = audio_pcm_playback_trigger,
.pointer = audio_pcm_pointer,
};
int audio_source_bind_config(struct usb_configuration *c,
struct audio_source_config *config)
{
struct audio_dev *audio;
struct snd_card *card;
struct snd_pcm *pcm;
int err;
config->card = -1;
config->device = -1;
audio = &_audio_dev;
err = snd_card_create(SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1,
THIS_MODULE, 0, &card);
if (err)
return err;
snd_card_set_dev(card, &c->cdev->gadget->dev);
err = snd_pcm_new(card, "USB audio source", 0, 1, 0, &pcm);
if (err)
goto pcm_fail;
pcm->private_data = audio;
pcm->info_flags = 0;
audio->pcm = pcm;
strlcpy(pcm->name, "USB gadget audio", sizeof(pcm->name));
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &audio_playback_ops);
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
NULL, 0, 64 * 1024);
strlcpy(card->driver, "audio_source", sizeof(card->driver));
strlcpy(card->shortname, card->driver, sizeof(card->shortname));
strlcpy(card->longname, "USB accessory audio source",
sizeof(card->longname));
err = snd_card_register(card);
if (err)
goto register_fail;
err = usb_add_function(c, &audio->func);
if (err)
goto add_fail;
config->card = pcm->card->number;
config->device = pcm->device;
audio->card = card;
return 0;
add_fail:
register_fail:
pcm_fail:
snd_card_free(audio->card);
return err;
}
| gpl-2.0 |
bcnice20/speedy-2.6.32.21 | arch/parisc/kernel/sys_parisc.c | 511 | 7188 |
/*
* PARISC specific syscalls
*
* Copyright (C) 1999-2003 Matthew Wilcox <willy at parisc-linux.org>
* Copyright (C) 2000-2003 Paul Bame <bame at parisc-linux.org>
* Copyright (C) 2001 Thomas Bogendoerfer <tsbogend at parisc-linux.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
*/
#include <asm/uaccess.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/linkage.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/shm.h>
#include <linux/syscalls.h>
#include <linux/utsname.h>
#include <linux/personality.h>
static unsigned long get_unshared_area(unsigned long addr, unsigned long len)
{
struct vm_area_struct *vma;
addr = PAGE_ALIGN(addr);
for (vma = find_vma(current->mm, addr); ; vma = vma->vm_next) {
/* At this point: (!vma || addr < vma->vm_end). */
if (TASK_SIZE - len < addr)
return -ENOMEM;
if (!vma || addr + len <= vma->vm_start)
return addr;
addr = vma->vm_end;
}
}
#define DCACHE_ALIGN(addr) (((addr) + (SHMLBA - 1)) &~ (SHMLBA - 1))
/*
* We need to know the offset to use. Old scheme was to look for
* existing mapping and use the same offset. New scheme is to use the
* address of the kernel data structure as the seed for the offset.
* We'll see how that works...
*
* The mapping is cacheline aligned, so there's no information in the bottom
* few bits of the address. We're looking for 10 bits (4MB / 4k), so let's
* drop the bottom 8 bits and use bits 8-17.
*/
static int get_offset(struct address_space *mapping)
{
int offset = (unsigned long) mapping << (PAGE_SHIFT - 8);
return offset & 0x3FF000;
}
static unsigned long get_shared_area(struct address_space *mapping,
unsigned long addr, unsigned long len, unsigned long pgoff)
{
struct vm_area_struct *vma;
int offset = mapping ? get_offset(mapping) : 0;
addr = DCACHE_ALIGN(addr - offset) + offset;
for (vma = find_vma(current->mm, addr); ; vma = vma->vm_next) {
/* At this point: (!vma || addr < vma->vm_end). */
if (TASK_SIZE - len < addr)
return -ENOMEM;
if (!vma || addr + len <= vma->vm_start)
return addr;
addr = DCACHE_ALIGN(vma->vm_end - offset) + offset;
if (addr < vma->vm_end) /* handle wraparound */
return -ENOMEM;
}
}
unsigned long arch_get_unmapped_area(struct file *filp, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
if (len > TASK_SIZE)
return -ENOMEM;
/* Might want to check for cache aliasing issues for MAP_FIXED case
* like ARM or MIPS ??? --BenH.
*/
if (flags & MAP_FIXED)
return addr;
if (!addr)
addr = TASK_UNMAPPED_BASE;
if (filp) {
addr = get_shared_area(filp->f_mapping, addr, len, pgoff);
} else if(flags & MAP_SHARED) {
addr = get_shared_area(NULL, addr, len, pgoff);
} else {
addr = get_unshared_area(addr, len);
}
return addr;
}
asmlinkage unsigned long sys_mmap2(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags, unsigned long fd,
unsigned long pgoff)
{
/* Make sure the shift for mmap2 is constant (12), no matter what PAGE_SIZE
we have. */
return sys_mmap_pgoff(addr, len, prot, flags, fd,
pgoff >> (PAGE_SHIFT - 12));
}
asmlinkage unsigned long sys_mmap(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags, unsigned long fd,
unsigned long offset)
{
if (!(offset & ~PAGE_MASK)) {
return sys_mmap_pgoff(addr, len, prot, flags, fd,
offset >> PAGE_SHIFT);
} else {
return -EINVAL;
}
}
/* Fucking broken ABI */
#ifdef CONFIG_64BIT
asmlinkage long parisc_truncate64(const char __user * path,
unsigned int high, unsigned int low)
{
return sys_truncate(path, (long)high << 32 | low);
}
asmlinkage long parisc_ftruncate64(unsigned int fd,
unsigned int high, unsigned int low)
{
return sys_ftruncate(fd, (long)high << 32 | low);
}
/* stubs for the benefit of the syscall_table since truncate64 and truncate
* are identical on LP64 */
asmlinkage long sys_truncate64(const char __user * path, unsigned long length)
{
return sys_truncate(path, length);
}
asmlinkage long sys_ftruncate64(unsigned int fd, unsigned long length)
{
return sys_ftruncate(fd, length);
}
asmlinkage long sys_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg)
{
return sys_fcntl(fd, cmd, arg);
}
#else
asmlinkage long parisc_truncate64(const char __user * path,
unsigned int high, unsigned int low)
{
return sys_truncate64(path, (loff_t)high << 32 | low);
}
asmlinkage long parisc_ftruncate64(unsigned int fd,
unsigned int high, unsigned int low)
{
return sys_ftruncate64(fd, (loff_t)high << 32 | low);
}
#endif
asmlinkage ssize_t parisc_pread64(unsigned int fd, char __user *buf, size_t count,
unsigned int high, unsigned int low)
{
return sys_pread64(fd, buf, count, (loff_t)high << 32 | low);
}
asmlinkage ssize_t parisc_pwrite64(unsigned int fd, const char __user *buf,
size_t count, unsigned int high, unsigned int low)
{
return sys_pwrite64(fd, buf, count, (loff_t)high << 32 | low);
}
asmlinkage ssize_t parisc_readahead(int fd, unsigned int high, unsigned int low,
size_t count)
{
return sys_readahead(fd, (loff_t)high << 32 | low, count);
}
asmlinkage long parisc_fadvise64_64(int fd,
unsigned int high_off, unsigned int low_off,
unsigned int high_len, unsigned int low_len, int advice)
{
return sys_fadvise64_64(fd, (loff_t)high_off << 32 | low_off,
(loff_t)high_len << 32 | low_len, advice);
}
asmlinkage long parisc_sync_file_range(int fd,
u32 hi_off, u32 lo_off, u32 hi_nbytes, u32 lo_nbytes,
unsigned int flags)
{
return sys_sync_file_range(fd, (loff_t)hi_off << 32 | lo_off,
(loff_t)hi_nbytes << 32 | lo_nbytes, flags);
}
asmlinkage unsigned long sys_alloc_hugepages(int key, unsigned long addr, unsigned long len, int prot, int flag)
{
return -ENOMEM;
}
asmlinkage int sys_free_hugepages(unsigned long addr)
{
return -EINVAL;
}
long parisc_personality(unsigned long personality)
{
long err;
if (personality(current->personality) == PER_LINUX32
&& personality == PER_LINUX)
personality = PER_LINUX32;
err = sys_personality(personality);
if (err == PER_LINUX32)
err = PER_LINUX;
return err;
}
long parisc_newuname(struct new_utsname __user *name)
{
int err = sys_newuname(name);
#ifdef CONFIG_COMPAT
if (!err && personality(current->personality) == PER_LINUX32) {
if (__put_user(0, name->machine + 6) ||
__put_user(0, name->machine + 7))
err = -EFAULT;
}
#endif
return err;
}
| gpl-2.0 |
RobBrownNZ/android_kernel_zuk_z2_plus | drivers/scsi/a3000.c | 767 | 7153 | #include <linux/types.h>
#include <linux/mm.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/amigaints.h>
#include <asm/amigahw.h>
#include "scsi.h"
#include "wd33c93.h"
#include "a3000.h"
struct a3000_hostdata {
struct WD33C93_hostdata wh;
struct a3000_scsiregs *regs;
};
static irqreturn_t a3000_intr(int irq, void *data)
{
struct Scsi_Host *instance = data;
struct a3000_hostdata *hdata = shost_priv(instance);
unsigned int status = hdata->regs->ISTR;
unsigned long flags;
if (!(status & ISTR_INT_P))
return IRQ_NONE;
if (status & ISTR_INTS) {
spin_lock_irqsave(instance->host_lock, flags);
wd33c93_intr(instance);
spin_unlock_irqrestore(instance->host_lock, flags);
return IRQ_HANDLED;
}
pr_warning("Non-serviced A3000 SCSI-interrupt? ISTR = %02x\n", status);
return IRQ_NONE;
}
static int dma_setup(struct scsi_cmnd *cmd, int dir_in)
{
struct Scsi_Host *instance = cmd->device->host;
struct a3000_hostdata *hdata = shost_priv(instance);
struct WD33C93_hostdata *wh = &hdata->wh;
struct a3000_scsiregs *regs = hdata->regs;
unsigned short cntr = CNTR_PDMD | CNTR_INTEN;
unsigned long addr = virt_to_bus(cmd->SCp.ptr);
/*
* if the physical address has the wrong alignment, or if
* physical address is bad, or if it is a write and at the
* end of a physical memory chunk, then allocate a bounce
* buffer
*/
if (addr & A3000_XFER_MASK) {
wh->dma_bounce_len = (cmd->SCp.this_residual + 511) & ~0x1ff;
wh->dma_bounce_buffer = kmalloc(wh->dma_bounce_len,
GFP_KERNEL);
/* can't allocate memory; use PIO */
if (!wh->dma_bounce_buffer) {
wh->dma_bounce_len = 0;
return 1;
}
if (!dir_in) {
/* copy to bounce buffer for a write */
memcpy(wh->dma_bounce_buffer, cmd->SCp.ptr,
cmd->SCp.this_residual);
}
addr = virt_to_bus(wh->dma_bounce_buffer);
}
/* setup dma direction */
if (!dir_in)
cntr |= CNTR_DDIR;
/* remember direction */
wh->dma_dir = dir_in;
regs->CNTR = cntr;
/* setup DMA *physical* address */
regs->ACR = addr;
if (dir_in) {
/* invalidate any cache */
cache_clear(addr, cmd->SCp.this_residual);
} else {
/* push any dirty cache */
cache_push(addr, cmd->SCp.this_residual);
}
/* start DMA */
mb(); /* make sure setup is completed */
regs->ST_DMA = 1;
mb(); /* make sure DMA has started before next IO */
/* return success */
return 0;
}
static void dma_stop(struct Scsi_Host *instance, struct scsi_cmnd *SCpnt,
int status)
{
struct a3000_hostdata *hdata = shost_priv(instance);
struct WD33C93_hostdata *wh = &hdata->wh;
struct a3000_scsiregs *regs = hdata->regs;
/* disable SCSI interrupts */
unsigned short cntr = CNTR_PDMD;
if (!wh->dma_dir)
cntr |= CNTR_DDIR;
regs->CNTR = cntr;
mb(); /* make sure CNTR is updated before next IO */
/* flush if we were reading */
if (wh->dma_dir) {
regs->FLUSH = 1;
mb(); /* don't allow prefetch */
while (!(regs->ISTR & ISTR_FE_FLG))
barrier();
mb(); /* no IO until FLUSH is done */
}
/* clear a possible interrupt */
/* I think that this CINT is only necessary if you are
* using the terminal count features. HM 7 Mar 1994
*/
regs->CINT = 1;
/* stop DMA */
regs->SP_DMA = 1;
mb(); /* make sure DMA is stopped before next IO */
/* restore the CONTROL bits (minus the direction flag) */
regs->CNTR = CNTR_PDMD | CNTR_INTEN;
mb(); /* make sure CNTR is updated before next IO */
/* copy from a bounce buffer, if necessary */
if (status && wh->dma_bounce_buffer) {
if (SCpnt) {
if (wh->dma_dir && SCpnt)
memcpy(SCpnt->SCp.ptr, wh->dma_bounce_buffer,
SCpnt->SCp.this_residual);
kfree(wh->dma_bounce_buffer);
wh->dma_bounce_buffer = NULL;
wh->dma_bounce_len = 0;
} else {
kfree(wh->dma_bounce_buffer);
wh->dma_bounce_buffer = NULL;
wh->dma_bounce_len = 0;
}
}
}
static int a3000_bus_reset(struct scsi_cmnd *cmd)
{
struct Scsi_Host *instance = cmd->device->host;
/* FIXME perform bus-specific reset */
/* FIXME 2: kill this entire function, which should
cause mid-layer to call wd33c93_host_reset anyway? */
spin_lock_irq(instance->host_lock);
wd33c93_host_reset(cmd);
spin_unlock_irq(instance->host_lock);
return SUCCESS;
}
static struct scsi_host_template amiga_a3000_scsi_template = {
.module = THIS_MODULE,
.name = "Amiga 3000 built-in SCSI",
.show_info = wd33c93_show_info,
.write_info = wd33c93_write_info,
.proc_name = "A3000",
.queuecommand = wd33c93_queuecommand,
.eh_abort_handler = wd33c93_abort,
.eh_bus_reset_handler = a3000_bus_reset,
.eh_host_reset_handler = wd33c93_host_reset,
.can_queue = CAN_QUEUE,
.this_id = 7,
.sg_tablesize = SG_ALL,
.cmd_per_lun = CMD_PER_LUN,
.use_clustering = ENABLE_CLUSTERING
};
static int __init amiga_a3000_scsi_probe(struct platform_device *pdev)
{
struct resource *res;
struct Scsi_Host *instance;
int error;
struct a3000_scsiregs *regs;
wd33c93_regs wdregs;
struct a3000_hostdata *hdata;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
if (!request_mem_region(res->start, resource_size(res), "wd33c93"))
return -EBUSY;
instance = scsi_host_alloc(&amiga_a3000_scsi_template,
sizeof(struct a3000_hostdata));
if (!instance) {
error = -ENOMEM;
goto fail_alloc;
}
instance->irq = IRQ_AMIGA_PORTS;
regs = ZTWO_VADDR(res->start);
regs->DAWR = DAWR_A3000;
wdregs.SASR = ®s->SASR;
wdregs.SCMD = ®s->SCMD;
hdata = shost_priv(instance);
hdata->wh.no_sync = 0xff;
hdata->wh.fast = 0;
hdata->wh.dma_mode = CTRL_DMA;
hdata->regs = regs;
wd33c93_init(instance, wdregs, dma_setup, dma_stop, WD33C93_FS_12_15);
error = request_irq(IRQ_AMIGA_PORTS, a3000_intr, IRQF_SHARED,
"A3000 SCSI", instance);
if (error)
goto fail_irq;
regs->CNTR = CNTR_PDMD | CNTR_INTEN;
error = scsi_add_host(instance, NULL);
if (error)
goto fail_host;
platform_set_drvdata(pdev, instance);
scsi_scan_host(instance);
return 0;
fail_host:
free_irq(IRQ_AMIGA_PORTS, instance);
fail_irq:
scsi_host_put(instance);
fail_alloc:
release_mem_region(res->start, resource_size(res));
return error;
}
static int __exit amiga_a3000_scsi_remove(struct platform_device *pdev)
{
struct Scsi_Host *instance = platform_get_drvdata(pdev);
struct a3000_hostdata *hdata = shost_priv(instance);
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
hdata->regs->CNTR = 0;
scsi_remove_host(instance);
free_irq(IRQ_AMIGA_PORTS, instance);
scsi_host_put(instance);
release_mem_region(res->start, resource_size(res));
return 0;
}
static struct platform_driver amiga_a3000_scsi_driver = {
.remove = __exit_p(amiga_a3000_scsi_remove),
.driver = {
.name = "amiga-a3000-scsi",
.owner = THIS_MODULE,
},
};
module_platform_driver_probe(amiga_a3000_scsi_driver, amiga_a3000_scsi_probe);
MODULE_DESCRIPTION("Amiga 3000 built-in SCSI");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:amiga-a3000-scsi");
| gpl-2.0 |
meimz/linux | fs/efs/dir.c | 1535 | 2393 | /*
* dir.c
*
* Copyright (c) 1999 Al Smith
*/
#include <linux/buffer_head.h>
#include "efs.h"
static int efs_readdir(struct file *, struct dir_context *);
const struct file_operations efs_dir_operations = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.iterate = efs_readdir,
};
const struct inode_operations efs_dir_inode_operations = {
.lookup = efs_lookup,
};
static int efs_readdir(struct file *file, struct dir_context *ctx)
{
struct inode *inode = file_inode(file);
efs_block_t block;
int slot;
if (inode->i_size & (EFS_DIRBSIZE-1))
pr_warn("%s(): directory size not a multiple of EFS_DIRBSIZE\n",
__func__);
/* work out where this entry can be found */
block = ctx->pos >> EFS_DIRBSIZE_BITS;
/* each block contains at most 256 slots */
slot = ctx->pos & 0xff;
/* look at all blocks */
while (block < inode->i_blocks) {
struct efs_dir *dirblock;
struct buffer_head *bh;
/* read the dir block */
bh = sb_bread(inode->i_sb, efs_bmap(inode, block));
if (!bh) {
pr_err("%s(): failed to read dir block %d\n",
__func__, block);
break;
}
dirblock = (struct efs_dir *) bh->b_data;
if (be16_to_cpu(dirblock->magic) != EFS_DIRBLK_MAGIC) {
pr_err("%s(): invalid directory block\n", __func__);
brelse(bh);
break;
}
for (; slot < dirblock->slots; slot++) {
struct efs_dentry *dirslot;
efs_ino_t inodenum;
const char *nameptr;
int namelen;
if (dirblock->space[slot] == 0)
continue;
dirslot = (struct efs_dentry *) (((char *) bh->b_data) + EFS_SLOTAT(dirblock, slot));
inodenum = be32_to_cpu(dirslot->inode);
namelen = dirslot->namelen;
nameptr = dirslot->name;
pr_debug("%s(): block %d slot %d/%d: inode %u, name \"%s\", namelen %u\n",
__func__, block, slot, dirblock->slots-1,
inodenum, nameptr, namelen);
if (!namelen)
continue;
/* found the next entry */
ctx->pos = (block << EFS_DIRBSIZE_BITS) | slot;
/* sanity check */
if (nameptr - (char *) dirblock + namelen > EFS_DIRBSIZE) {
pr_warn("directory entry %d exceeds directory block\n",
slot);
continue;
}
/* copy filename and data in dirslot */
if (!dir_emit(ctx, nameptr, namelen, inodenum, DT_UNKNOWN)) {
brelse(bh);
return 0;
}
}
brelse(bh);
slot = 0;
block++;
}
ctx->pos = (block << EFS_DIRBSIZE_BITS) | slot;
return 0;
}
| gpl-2.0 |
SVoxel/R9000 | git_home/linux.git/fs/gfs2/file.c | 2047 | 27002 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/pagemap.h>
#include <linux/uio.h>
#include <linux/blkdev.h>
#include <linux/mm.h>
#include <linux/mount.h>
#include <linux/fs.h>
#include <linux/gfs2_ondisk.h>
#include <linux/falloc.h>
#include <linux/swap.h>
#include <linux/crc32.h>
#include <linux/writeback.h>
#include <asm/uaccess.h>
#include <linux/dlm.h>
#include <linux/dlm_plock.h>
#include <linux/aio.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "dir.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "log.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
/**
* gfs2_llseek - seek to a location in a file
* @file: the file
* @offset: the offset
* @whence: Where to seek from (SEEK_SET, SEEK_CUR, or SEEK_END)
*
* SEEK_END requires the glock for the file because it references the
* file's size.
*
* Returns: The new offset, or errno
*/
static loff_t gfs2_llseek(struct file *file, loff_t offset, int whence)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
struct gfs2_holder i_gh;
loff_t error;
switch (whence) {
case SEEK_END: /* These reference inode->i_size */
case SEEK_DATA:
case SEEK_HOLE:
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (!error) {
error = generic_file_llseek(file, offset, whence);
gfs2_glock_dq_uninit(&i_gh);
}
break;
case SEEK_CUR:
case SEEK_SET:
error = generic_file_llseek(file, offset, whence);
break;
default:
error = -EINVAL;
}
return error;
}
/**
* gfs2_readdir - Read directory entries from a directory
* @file: The directory to read from
* @dirent: Buffer for dirents
* @filldir: Function used to do the copying
*
* Returns: errno
*/
static int gfs2_readdir(struct file *file, void *dirent, filldir_t filldir)
{
struct inode *dir = file->f_mapping->host;
struct gfs2_inode *dip = GFS2_I(dir);
struct gfs2_holder d_gh;
u64 offset = file->f_pos;
int error;
gfs2_holder_init(dip->i_gl, LM_ST_SHARED, 0, &d_gh);
error = gfs2_glock_nq(&d_gh);
if (error) {
gfs2_holder_uninit(&d_gh);
return error;
}
error = gfs2_dir_read(dir, &offset, dirent, filldir, &file->f_ra);
gfs2_glock_dq_uninit(&d_gh);
file->f_pos = offset;
return error;
}
/**
* fsflags_cvt
* @table: A table of 32 u32 flags
* @val: a 32 bit value to convert
*
* This function can be used to convert between fsflags values and
* GFS2's own flags values.
*
* Returns: the converted flags
*/
static u32 fsflags_cvt(const u32 *table, u32 val)
{
u32 res = 0;
while(val) {
if (val & 1)
res |= *table;
table++;
val >>= 1;
}
return res;
}
static const u32 fsflags_to_gfs2[32] = {
[3] = GFS2_DIF_SYNC,
[4] = GFS2_DIF_IMMUTABLE,
[5] = GFS2_DIF_APPENDONLY,
[7] = GFS2_DIF_NOATIME,
[12] = GFS2_DIF_EXHASH,
[14] = GFS2_DIF_INHERIT_JDATA,
[17] = GFS2_DIF_TOPDIR,
};
static const u32 gfs2_to_fsflags[32] = {
[gfs2fl_Sync] = FS_SYNC_FL,
[gfs2fl_Immutable] = FS_IMMUTABLE_FL,
[gfs2fl_AppendOnly] = FS_APPEND_FL,
[gfs2fl_NoAtime] = FS_NOATIME_FL,
[gfs2fl_ExHash] = FS_INDEX_FL,
[gfs2fl_TopLevel] = FS_TOPDIR_FL,
[gfs2fl_InheritJdata] = FS_JOURNAL_DATA_FL,
};
static int gfs2_get_flags(struct file *filp, u32 __user *ptr)
{
struct inode *inode = file_inode(filp);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int error;
u32 fsflags;
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
error = gfs2_glock_nq(&gh);
if (error)
return error;
fsflags = fsflags_cvt(gfs2_to_fsflags, ip->i_diskflags);
if (!S_ISDIR(inode->i_mode) && ip->i_diskflags & GFS2_DIF_JDATA)
fsflags |= FS_JOURNAL_DATA_FL;
if (put_user(fsflags, ptr))
error = -EFAULT;
gfs2_glock_dq(&gh);
gfs2_holder_uninit(&gh);
return error;
}
void gfs2_set_inode_flags(struct inode *inode)
{
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int flags = inode->i_flags;
flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_NOSEC);
if ((ip->i_eattr == 0) && !is_sxid(inode->i_mode))
inode->i_flags |= S_NOSEC;
if (ip->i_diskflags & GFS2_DIF_IMMUTABLE)
flags |= S_IMMUTABLE;
if (ip->i_diskflags & GFS2_DIF_APPENDONLY)
flags |= S_APPEND;
if (ip->i_diskflags & GFS2_DIF_NOATIME)
flags |= S_NOATIME;
if (ip->i_diskflags & GFS2_DIF_SYNC)
flags |= S_SYNC;
inode->i_flags = flags;
}
/* Flags that can be set by user space */
#define GFS2_FLAGS_USER_SET (GFS2_DIF_JDATA| \
GFS2_DIF_IMMUTABLE| \
GFS2_DIF_APPENDONLY| \
GFS2_DIF_NOATIME| \
GFS2_DIF_SYNC| \
GFS2_DIF_SYSTEM| \
GFS2_DIF_TOPDIR| \
GFS2_DIF_INHERIT_JDATA)
/**
* gfs2_set_flags - set flags on an inode
* @inode: The inode
* @flags: The flags to set
* @mask: Indicates which flags are valid
*
*/
static int do_gfs2_set_flags(struct file *filp, u32 reqflags, u32 mask)
{
struct inode *inode = file_inode(filp);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *bh;
struct gfs2_holder gh;
int error;
u32 new_flags, flags;
error = mnt_want_write_file(filp);
if (error)
return error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
if (error)
goto out_drop_write;
error = -EACCES;
if (!inode_owner_or_capable(inode))
goto out;
error = 0;
flags = ip->i_diskflags;
new_flags = (flags & ~mask) | (reqflags & mask);
if ((new_flags ^ flags) == 0)
goto out;
error = -EINVAL;
if ((new_flags ^ flags) & ~GFS2_FLAGS_USER_SET)
goto out;
error = -EPERM;
if (IS_IMMUTABLE(inode) && (new_flags & GFS2_DIF_IMMUTABLE))
goto out;
if (IS_APPEND(inode) && (new_flags & GFS2_DIF_APPENDONLY))
goto out;
if (((new_flags ^ flags) & GFS2_DIF_IMMUTABLE) &&
!capable(CAP_LINUX_IMMUTABLE))
goto out;
if (!IS_IMMUTABLE(inode)) {
error = gfs2_permission(inode, MAY_WRITE);
if (error)
goto out;
}
if ((flags ^ new_flags) & GFS2_DIF_JDATA) {
if (flags & GFS2_DIF_JDATA)
gfs2_log_flush(sdp, ip->i_gl);
error = filemap_fdatawrite(inode->i_mapping);
if (error)
goto out;
error = filemap_fdatawait(inode->i_mapping);
if (error)
goto out;
}
error = gfs2_trans_begin(sdp, RES_DINODE, 0);
if (error)
goto out;
error = gfs2_meta_inode_buffer(ip, &bh);
if (error)
goto out_trans_end;
gfs2_trans_add_meta(ip->i_gl, bh);
ip->i_diskflags = new_flags;
gfs2_dinode_out(ip, bh->b_data);
brelse(bh);
gfs2_set_inode_flags(inode);
gfs2_set_aops(inode);
out_trans_end:
gfs2_trans_end(sdp);
out:
gfs2_glock_dq_uninit(&gh);
out_drop_write:
mnt_drop_write_file(filp);
return error;
}
static int gfs2_set_flags(struct file *filp, u32 __user *ptr)
{
struct inode *inode = file_inode(filp);
u32 fsflags, gfsflags;
if (get_user(fsflags, ptr))
return -EFAULT;
gfsflags = fsflags_cvt(fsflags_to_gfs2, fsflags);
if (!S_ISDIR(inode->i_mode)) {
gfsflags &= ~GFS2_DIF_TOPDIR;
if (gfsflags & GFS2_DIF_INHERIT_JDATA)
gfsflags ^= (GFS2_DIF_JDATA | GFS2_DIF_INHERIT_JDATA);
return do_gfs2_set_flags(filp, gfsflags, ~0);
}
return do_gfs2_set_flags(filp, gfsflags, ~GFS2_DIF_JDATA);
}
static long gfs2_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
switch(cmd) {
case FS_IOC_GETFLAGS:
return gfs2_get_flags(filp, (u32 __user *)arg);
case FS_IOC_SETFLAGS:
return gfs2_set_flags(filp, (u32 __user *)arg);
case FITRIM:
return gfs2_fitrim(filp, (void __user *)arg);
}
return -ENOTTY;
}
/**
* gfs2_size_hint - Give a hint to the size of a write request
* @file: The struct file
* @offset: The file offset of the write
* @size: The length of the write
*
* When we are about to do a write, this function records the total
* write size in order to provide a suitable hint to the lower layers
* about how many blocks will be required.
*
*/
static void gfs2_size_hint(struct file *filep, loff_t offset, size_t size)
{
struct inode *inode = file_inode(filep);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *ip = GFS2_I(inode);
size_t blks = (size + sdp->sd_sb.sb_bsize - 1) >> sdp->sd_sb.sb_bsize_shift;
int hint = min_t(size_t, INT_MAX, blks);
atomic_set(&ip->i_res->rs_sizehint, hint);
}
/**
* gfs2_allocate_page_backing - Use bmap to allocate blocks
* @page: The (locked) page to allocate backing for
*
* We try to allocate all the blocks required for the page in
* one go. This might fail for various reasons, so we keep
* trying until all the blocks to back this page are allocated.
* If some of the blocks are already allocated, thats ok too.
*/
static int gfs2_allocate_page_backing(struct page *page)
{
struct inode *inode = page->mapping->host;
struct buffer_head bh;
unsigned long size = PAGE_CACHE_SIZE;
u64 lblock = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
do {
bh.b_state = 0;
bh.b_size = size;
gfs2_block_map(inode, lblock, &bh, 1);
if (!buffer_mapped(&bh))
return -EIO;
size -= bh.b_size;
lblock += (bh.b_size >> inode->i_blkbits);
} while(size > 0);
return 0;
}
/**
* gfs2_page_mkwrite - Make a shared, mmap()ed, page writable
* @vma: The virtual memory area
* @page: The page which is about to become writable
*
* When the page becomes writable, we need to ensure that we have
* blocks allocated on disk to back that page.
*/
static int gfs2_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page = vmf->page;
struct inode *inode = file_inode(vma->vm_file);
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
unsigned long last_index;
u64 pos = page->index << PAGE_CACHE_SHIFT;
unsigned int data_blocks, ind_blocks, rblocks;
struct gfs2_holder gh;
loff_t size;
int ret;
sb_start_pagefault(inode->i_sb);
/* Update file times before taking page lock */
file_update_time(vma->vm_file);
ret = get_write_access(inode);
if (ret)
goto out;
ret = gfs2_rs_alloc(ip);
if (ret)
goto out_write_access;
gfs2_size_hint(vma->vm_file, pos, PAGE_CACHE_SIZE);
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
ret = gfs2_glock_nq(&gh);
if (ret)
goto out_uninit;
set_bit(GLF_DIRTY, &ip->i_gl->gl_flags);
set_bit(GIF_SW_PAGED, &ip->i_flags);
if (!gfs2_write_alloc_required(ip, pos, PAGE_CACHE_SIZE)) {
lock_page(page);
if (!PageUptodate(page) || page->mapping != inode->i_mapping) {
ret = -EAGAIN;
unlock_page(page);
}
goto out_unlock;
}
ret = gfs2_rindex_update(sdp);
if (ret)
goto out_unlock;
ret = gfs2_quota_lock_check(ip);
if (ret)
goto out_unlock;
gfs2_write_calc_reserv(ip, PAGE_CACHE_SIZE, &data_blocks, &ind_blocks);
ret = gfs2_inplace_reserve(ip, data_blocks + ind_blocks, 0);
if (ret)
goto out_quota_unlock;
rblocks = RES_DINODE + ind_blocks;
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
if (ind_blocks || data_blocks) {
rblocks += RES_STATFS + RES_QUOTA;
rblocks += gfs2_rg_blocks(ip, data_blocks + ind_blocks);
}
ret = gfs2_trans_begin(sdp, rblocks, 0);
if (ret)
goto out_trans_fail;
lock_page(page);
ret = -EINVAL;
size = i_size_read(inode);
last_index = (size - 1) >> PAGE_CACHE_SHIFT;
/* Check page index against inode size */
if (size == 0 || (page->index > last_index))
goto out_trans_end;
ret = -EAGAIN;
/* If truncated, we must retry the operation, we may have raced
* with the glock demotion code.
*/
if (!PageUptodate(page) || page->mapping != inode->i_mapping)
goto out_trans_end;
/* Unstuff, if required, and allocate backing blocks for page */
ret = 0;
if (gfs2_is_stuffed(ip))
ret = gfs2_unstuff_dinode(ip, page);
if (ret == 0)
ret = gfs2_allocate_page_backing(page);
out_trans_end:
if (ret)
unlock_page(page);
gfs2_trans_end(sdp);
out_trans_fail:
gfs2_inplace_release(ip);
out_quota_unlock:
gfs2_quota_unlock(ip);
out_unlock:
gfs2_glock_dq(&gh);
out_uninit:
gfs2_holder_uninit(&gh);
if (ret == 0) {
set_page_dirty(page);
wait_for_stable_page(page);
}
out_write_access:
put_write_access(inode);
out:
sb_end_pagefault(inode->i_sb);
return block_page_mkwrite_return(ret);
}
static const struct vm_operations_struct gfs2_vm_ops = {
.fault = filemap_fault,
.page_mkwrite = gfs2_page_mkwrite,
.remap_pages = generic_file_remap_pages,
};
/**
* gfs2_mmap -
* @file: The file to map
* @vma: The VMA which described the mapping
*
* There is no need to get a lock here unless we should be updating
* atime. We ignore any locking errors since the only consequence is
* a missed atime update (which will just be deferred until later).
*
* Returns: 0
*/
static int gfs2_mmap(struct file *file, struct vm_area_struct *vma)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
if (!(file->f_flags & O_NOATIME) &&
!IS_NOATIME(&ip->i_inode)) {
struct gfs2_holder i_gh;
int error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (error)
return error;
/* grab lock to update inode */
gfs2_glock_dq_uninit(&i_gh);
file_accessed(file);
}
vma->vm_ops = &gfs2_vm_ops;
return 0;
}
/**
* gfs2_open - open a file
* @inode: the inode to open
* @file: the struct file for this opening
*
* Returns: errno
*/
static int gfs2_open(struct inode *inode, struct file *file)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder i_gh;
struct gfs2_file *fp;
int error;
fp = kzalloc(sizeof(struct gfs2_file), GFP_KERNEL);
if (!fp)
return -ENOMEM;
mutex_init(&fp->f_fl_mutex);
gfs2_assert_warn(GFS2_SB(inode), !file->private_data);
file->private_data = fp;
if (S_ISREG(ip->i_inode.i_mode)) {
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (error)
goto fail;
if (!(file->f_flags & O_LARGEFILE) &&
i_size_read(inode) > MAX_NON_LFS) {
error = -EOVERFLOW;
goto fail_gunlock;
}
gfs2_glock_dq_uninit(&i_gh);
}
return 0;
fail_gunlock:
gfs2_glock_dq_uninit(&i_gh);
fail:
file->private_data = NULL;
kfree(fp);
return error;
}
/**
* gfs2_release - called to close a struct file
* @inode: the inode the struct file belongs to
* @file: the struct file being closed
*
* Returns: errno
*/
static int gfs2_release(struct inode *inode, struct file *file)
{
struct gfs2_inode *ip = GFS2_I(inode);
kfree(file->private_data);
file->private_data = NULL;
if (!(file->f_mode & FMODE_WRITE))
return 0;
gfs2_rs_delete(ip);
return 0;
}
/**
* gfs2_fsync - sync the dirty data for a file (across the cluster)
* @file: the file that points to the dentry
* @start: the start position in the file to sync
* @end: the end position in the file to sync
* @datasync: set if we can ignore timestamp changes
*
* We split the data flushing here so that we don't wait for the data
* until after we've also sent the metadata to disk. Note that for
* data=ordered, we will write & wait for the data at the log flush
* stage anyway, so this is unlikely to make much of a difference
* except in the data=writeback case.
*
* If the fdatawrite fails due to any reason except -EIO, we will
* continue the remainder of the fsync, although we'll still report
* the error at the end. This is to match filemap_write_and_wait_range()
* behaviour.
*
* Returns: errno
*/
static int gfs2_fsync(struct file *file, loff_t start, loff_t end,
int datasync)
{
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
int sync_state = inode->i_state & (I_DIRTY_SYNC|I_DIRTY_DATASYNC);
struct gfs2_inode *ip = GFS2_I(inode);
int ret = 0, ret1 = 0;
if (mapping->nrpages) {
ret1 = filemap_fdatawrite_range(mapping, start, end);
if (ret1 == -EIO)
return ret1;
}
if (datasync)
sync_state &= ~I_DIRTY_SYNC;
if (sync_state) {
ret = sync_inode_metadata(inode, 1);
if (ret)
return ret;
if (gfs2_is_jdata(ip))
filemap_write_and_wait(mapping);
gfs2_ail_flush(ip->i_gl, 1);
}
if (mapping->nrpages)
ret = filemap_fdatawait_range(mapping, start, end);
return ret ? ret : ret1;
}
/**
* gfs2_file_aio_write - Perform a write to a file
* @iocb: The io context
* @iov: The data to write
* @nr_segs: Number of @iov segments
* @pos: The file position
*
* We have to do a lock/unlock here to refresh the inode size for
* O_APPEND writes, otherwise we can land up writing at the wrong
* offset. There is still a race, but provided the app is using its
* own file locking, this will make O_APPEND work as expected.
*
*/
static ssize_t gfs2_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct file *file = iocb->ki_filp;
size_t writesize = iov_length(iov, nr_segs);
struct gfs2_inode *ip = GFS2_I(file_inode(file));
int ret;
ret = gfs2_rs_alloc(ip);
if (ret)
return ret;
gfs2_size_hint(file, pos, writesize);
if (file->f_flags & O_APPEND) {
struct gfs2_holder gh;
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
if (ret)
return ret;
gfs2_glock_dq_uninit(&gh);
}
return generic_file_aio_write(iocb, iov, nr_segs, pos);
}
static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len,
int mode)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct buffer_head *dibh;
int error;
loff_t size = len;
unsigned int nr_blks;
sector_t lblock = offset >> inode->i_blkbits;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (unlikely(error))
return error;
gfs2_trans_add_meta(ip->i_gl, dibh);
if (gfs2_is_stuffed(ip)) {
error = gfs2_unstuff_dinode(ip, NULL);
if (unlikely(error))
goto out;
}
while (len) {
struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 };
bh_map.b_size = len;
set_buffer_zeronew(&bh_map);
error = gfs2_block_map(inode, lblock, &bh_map, 1);
if (unlikely(error))
goto out;
len -= bh_map.b_size;
nr_blks = bh_map.b_size >> inode->i_blkbits;
lblock += nr_blks;
if (!buffer_new(&bh_map))
continue;
if (unlikely(!buffer_zeronew(&bh_map))) {
error = -EIO;
goto out;
}
}
if (offset + size > inode->i_size && !(mode & FALLOC_FL_KEEP_SIZE))
i_size_write(inode, offset + size);
mark_inode_dirty(inode);
out:
brelse(dibh);
return error;
}
static void calc_max_reserv(struct gfs2_inode *ip, loff_t max, loff_t *len,
unsigned int *data_blocks, unsigned int *ind_blocks)
{
const struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
unsigned int max_blocks = ip->i_rgd->rd_free_clone;
unsigned int tmp, max_data = max_blocks - 3 * (sdp->sd_max_height - 1);
for (tmp = max_data; tmp > sdp->sd_diptrs;) {
tmp = DIV_ROUND_UP(tmp, sdp->sd_inptrs);
max_data -= tmp;
}
/* This calculation isn't the exact reverse of gfs2_write_calc_reserve,
so it might end up with fewer data blocks */
if (max_data <= *data_blocks)
return;
*data_blocks = max_data;
*ind_blocks = max_blocks - max_data;
*len = ((loff_t)max_data - 3) << sdp->sd_sb.sb_bsize_shift;
if (*len > max) {
*len = max;
gfs2_write_calc_reserv(ip, max, data_blocks, ind_blocks);
}
}
static long gfs2_fallocate(struct file *file, int mode, loff_t offset,
loff_t len)
{
struct inode *inode = file_inode(file);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int data_blocks = 0, ind_blocks = 0, rblocks;
loff_t bytes, max_bytes;
int error;
const loff_t pos = offset;
const loff_t count = len;
loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1);
loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift;
loff_t max_chunk_size = UINT_MAX & bsize_mask;
next = (next + 1) << sdp->sd_sb.sb_bsize_shift;
/* We only support the FALLOC_FL_KEEP_SIZE mode */
if (mode & ~FALLOC_FL_KEEP_SIZE)
return -EOPNOTSUPP;
offset &= bsize_mask;
len = next - offset;
bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2;
if (!bytes)
bytes = UINT_MAX;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
error = gfs2_rs_alloc(ip);
if (error)
return error;
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh);
error = gfs2_glock_nq(&ip->i_gh);
if (unlikely(error))
goto out_uninit;
gfs2_size_hint(file, offset, len);
while (len > 0) {
if (len < bytes)
bytes = len;
if (!gfs2_write_alloc_required(ip, offset, bytes)) {
len -= bytes;
offset += bytes;
continue;
}
error = gfs2_quota_lock_check(ip);
if (error)
goto out_unlock;
retry:
gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks);
error = gfs2_inplace_reserve(ip, data_blocks + ind_blocks, 0);
if (error) {
if (error == -ENOSPC && bytes > sdp->sd_sb.sb_bsize) {
bytes >>= 1;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
goto retry;
}
goto out_qunlock;
}
max_bytes = bytes;
calc_max_reserv(ip, (len > max_chunk_size)? max_chunk_size: len,
&max_bytes, &data_blocks, &ind_blocks);
rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA +
RES_RG_HDR + gfs2_rg_blocks(ip, data_blocks + ind_blocks);
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
error = gfs2_trans_begin(sdp, rblocks,
PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize);
if (error)
goto out_trans_fail;
error = fallocate_chunk(inode, offset, max_bytes, mode);
gfs2_trans_end(sdp);
if (error)
goto out_trans_fail;
len -= max_bytes;
offset += max_bytes;
gfs2_inplace_release(ip);
gfs2_quota_unlock(ip);
}
if (error == 0)
error = generic_write_sync(file, pos, count);
goto out_unlock;
out_trans_fail:
gfs2_inplace_release(ip);
out_qunlock:
gfs2_quota_unlock(ip);
out_unlock:
gfs2_glock_dq(&ip->i_gh);
out_uninit:
gfs2_holder_uninit(&ip->i_gh);
return error;
}
#ifdef CONFIG_GFS2_FS_LOCKING_DLM
/**
* gfs2_setlease - acquire/release a file lease
* @file: the file pointer
* @arg: lease type
* @fl: file lock
*
* We don't currently have a way to enforce a lease across the whole
* cluster; until we do, disable leases (by just returning -EINVAL),
* unless the administrator has requested purely local locking.
*
* Locking: called under lock_flocks
*
* Returns: errno
*/
static int gfs2_setlease(struct file *file, long arg, struct file_lock **fl)
{
return -EINVAL;
}
/**
* gfs2_lock - acquire/release a posix lock on a file
* @file: the file pointer
* @cmd: either modify or retrieve lock state, possibly wait
* @fl: type and range of lock
*
* Returns: errno
*/
static int gfs2_lock(struct file *file, int cmd, struct file_lock *fl)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
struct gfs2_sbd *sdp = GFS2_SB(file->f_mapping->host);
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (!(fl->fl_flags & FL_POSIX))
return -ENOLCK;
if (__mandatory_lock(&ip->i_inode) && fl->fl_type != F_UNLCK)
return -ENOLCK;
if (cmd == F_CANCELLK) {
/* Hack: */
cmd = F_SETLK;
fl->fl_type = F_UNLCK;
}
if (unlikely(test_bit(SDF_SHUTDOWN, &sdp->sd_flags))) {
if (fl->fl_type == F_UNLCK)
posix_lock_file_wait(file, fl);
return -EIO;
}
if (IS_GETLK(cmd))
return dlm_posix_get(ls->ls_dlm, ip->i_no_addr, file, fl);
else if (fl->fl_type == F_UNLCK)
return dlm_posix_unlock(ls->ls_dlm, ip->i_no_addr, file, fl);
else
return dlm_posix_lock(ls->ls_dlm, ip->i_no_addr, file, cmd, fl);
}
static int do_flock(struct file *file, int cmd, struct file_lock *fl)
{
struct gfs2_file *fp = file->private_data;
struct gfs2_holder *fl_gh = &fp->f_fl_gh;
struct gfs2_inode *ip = GFS2_I(file_inode(file));
struct gfs2_glock *gl;
unsigned int state;
int flags;
int error = 0;
state = (fl->fl_type == F_WRLCK) ? LM_ST_EXCLUSIVE : LM_ST_SHARED;
flags = (IS_SETLKW(cmd) ? 0 : LM_FLAG_TRY) | GL_EXACT | GL_NOCACHE;
mutex_lock(&fp->f_fl_mutex);
gl = fl_gh->gh_gl;
if (gl) {
if (fl_gh->gh_state == state)
goto out;
flock_lock_file_wait(file,
&(struct file_lock){.fl_type = F_UNLCK});
gfs2_glock_dq_wait(fl_gh);
gfs2_holder_reinit(state, flags, fl_gh);
} else {
error = gfs2_glock_get(GFS2_SB(&ip->i_inode), ip->i_no_addr,
&gfs2_flock_glops, CREATE, &gl);
if (error)
goto out;
gfs2_holder_init(gl, state, flags, fl_gh);
gfs2_glock_put(gl);
}
error = gfs2_glock_nq(fl_gh);
if (error) {
gfs2_holder_uninit(fl_gh);
if (error == GLR_TRYFAILED)
error = -EAGAIN;
} else {
error = flock_lock_file_wait(file, fl);
gfs2_assert_warn(GFS2_SB(&ip->i_inode), !error);
}
out:
mutex_unlock(&fp->f_fl_mutex);
return error;
}
static void do_unflock(struct file *file, struct file_lock *fl)
{
struct gfs2_file *fp = file->private_data;
struct gfs2_holder *fl_gh = &fp->f_fl_gh;
mutex_lock(&fp->f_fl_mutex);
flock_lock_file_wait(file, fl);
if (fl_gh->gh_gl) {
gfs2_glock_dq_wait(fl_gh);
gfs2_holder_uninit(fl_gh);
}
mutex_unlock(&fp->f_fl_mutex);
}
/**
* gfs2_flock - acquire/release a flock lock on a file
* @file: the file pointer
* @cmd: either modify or retrieve lock state, possibly wait
* @fl: type and range of lock
*
* Returns: errno
*/
static int gfs2_flock(struct file *file, int cmd, struct file_lock *fl)
{
if (!(fl->fl_flags & FL_FLOCK))
return -ENOLCK;
if (fl->fl_type & LOCK_MAND)
return -EOPNOTSUPP;
if (fl->fl_type == F_UNLCK) {
do_unflock(file, fl);
return 0;
} else {
return do_flock(file, cmd, fl);
}
}
const struct file_operations gfs2_file_fops = {
.llseek = gfs2_llseek,
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.write = do_sync_write,
.aio_write = gfs2_file_aio_write,
.unlocked_ioctl = gfs2_ioctl,
.mmap = gfs2_mmap,
.open = gfs2_open,
.release = gfs2_release,
.fsync = gfs2_fsync,
.lock = gfs2_lock,
.flock = gfs2_flock,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.setlease = gfs2_setlease,
.fallocate = gfs2_fallocate,
};
const struct file_operations gfs2_dir_fops = {
.readdir = gfs2_readdir,
.unlocked_ioctl = gfs2_ioctl,
.open = gfs2_open,
.release = gfs2_release,
.fsync = gfs2_fsync,
.lock = gfs2_lock,
.flock = gfs2_flock,
.llseek = default_llseek,
};
#endif /* CONFIG_GFS2_FS_LOCKING_DLM */
const struct file_operations gfs2_file_fops_nolock = {
.llseek = gfs2_llseek,
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.write = do_sync_write,
.aio_write = gfs2_file_aio_write,
.unlocked_ioctl = gfs2_ioctl,
.mmap = gfs2_mmap,
.open = gfs2_open,
.release = gfs2_release,
.fsync = gfs2_fsync,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.setlease = generic_setlease,
.fallocate = gfs2_fallocate,
};
const struct file_operations gfs2_dir_fops_nolock = {
.readdir = gfs2_readdir,
.unlocked_ioctl = gfs2_ioctl,
.open = gfs2_open,
.release = gfs2_release,
.fsync = gfs2_fsync,
.llseek = default_llseek,
};
| gpl-2.0 |
XileForce/Vindicator-S6-Uni-Old | arch/arm/mach-spear/spear310.c | 2047 | 5848 | /*
* arch/arm/mach-spear3xx/spear310.c
*
* SPEAr310 machine source file
*
* Copyright (C) 2009-2012 ST Microelectronics
* Viresh Kumar <viresh.linux@gmail.com>
*
* 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.
*/
#define pr_fmt(fmt) "SPEAr310: " fmt
#include <linux/amba/pl08x.h>
#include <linux/amba/serial.h>
#include <linux/irqchip.h>
#include <linux/of_platform.h>
#include <asm/mach/arch.h>
#include "generic.h"
#include <mach/spear.h>
#define SPEAR310_UART1_BASE UL(0xB2000000)
#define SPEAR310_UART2_BASE UL(0xB2080000)
#define SPEAR310_UART3_BASE UL(0xB2100000)
#define SPEAR310_UART4_BASE UL(0xB2180000)
#define SPEAR310_UART5_BASE UL(0xB2200000)
/* DMAC platform data's slave info */
struct pl08x_channel_data spear310_dma_info[] = {
{
.bus_id = "uart0_rx",
.min_signal = 2,
.max_signal = 2,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart0_tx",
.min_signal = 3,
.max_signal = 3,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "ssp0_rx",
.min_signal = 8,
.max_signal = 8,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "ssp0_tx",
.min_signal = 9,
.max_signal = 9,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "i2c_rx",
.min_signal = 10,
.max_signal = 10,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "i2c_tx",
.min_signal = 11,
.max_signal = 11,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "irda",
.min_signal = 12,
.max_signal = 12,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "adc",
.min_signal = 13,
.max_signal = 13,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "to_jpeg",
.min_signal = 14,
.max_signal = 14,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "from_jpeg",
.min_signal = 15,
.max_signal = 15,
.muxval = 0,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart1_rx",
.min_signal = 0,
.max_signal = 0,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart1_tx",
.min_signal = 1,
.max_signal = 1,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart2_rx",
.min_signal = 2,
.max_signal = 2,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart2_tx",
.min_signal = 3,
.max_signal = 3,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart3_rx",
.min_signal = 4,
.max_signal = 4,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart3_tx",
.min_signal = 5,
.max_signal = 5,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart4_rx",
.min_signal = 6,
.max_signal = 6,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart4_tx",
.min_signal = 7,
.max_signal = 7,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart5_rx",
.min_signal = 8,
.max_signal = 8,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "uart5_tx",
.min_signal = 9,
.max_signal = 9,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "ras5_rx",
.min_signal = 10,
.max_signal = 10,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "ras5_tx",
.min_signal = 11,
.max_signal = 11,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "ras6_rx",
.min_signal = 12,
.max_signal = 12,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "ras6_tx",
.min_signal = 13,
.max_signal = 13,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "ras7_rx",
.min_signal = 14,
.max_signal = 14,
.muxval = 1,
.periph_buses = PL08X_AHB1,
}, {
.bus_id = "ras7_tx",
.min_signal = 15,
.max_signal = 15,
.muxval = 1,
.periph_buses = PL08X_AHB1,
},
};
/* uart devices plat data */
static struct amba_pl011_data spear310_uart_data[] = {
{
.dma_filter = pl08x_filter_id,
.dma_tx_param = "uart1_tx",
.dma_rx_param = "uart1_rx",
}, {
.dma_filter = pl08x_filter_id,
.dma_tx_param = "uart2_tx",
.dma_rx_param = "uart2_rx",
}, {
.dma_filter = pl08x_filter_id,
.dma_tx_param = "uart3_tx",
.dma_rx_param = "uart3_rx",
}, {
.dma_filter = pl08x_filter_id,
.dma_tx_param = "uart4_tx",
.dma_rx_param = "uart4_rx",
}, {
.dma_filter = pl08x_filter_id,
.dma_tx_param = "uart5_tx",
.dma_rx_param = "uart5_rx",
},
};
/* Add SPEAr310 auxdata to pass platform data */
static struct of_dev_auxdata spear310_auxdata_lookup[] __initdata = {
OF_DEV_AUXDATA("arm,pl022", SPEAR3XX_ICM1_SSP_BASE, NULL,
&pl022_plat_data),
OF_DEV_AUXDATA("arm,pl080", SPEAR_ICM3_DMA_BASE, NULL,
&pl080_plat_data),
OF_DEV_AUXDATA("arm,pl011", SPEAR310_UART1_BASE, NULL,
&spear310_uart_data[0]),
OF_DEV_AUXDATA("arm,pl011", SPEAR310_UART2_BASE, NULL,
&spear310_uart_data[1]),
OF_DEV_AUXDATA("arm,pl011", SPEAR310_UART3_BASE, NULL,
&spear310_uart_data[2]),
OF_DEV_AUXDATA("arm,pl011", SPEAR310_UART4_BASE, NULL,
&spear310_uart_data[3]),
OF_DEV_AUXDATA("arm,pl011", SPEAR310_UART5_BASE, NULL,
&spear310_uart_data[4]),
{}
};
static void __init spear310_dt_init(void)
{
pl080_plat_data.slave_channels = spear310_dma_info;
pl080_plat_data.num_slave_channels = ARRAY_SIZE(spear310_dma_info);
of_platform_populate(NULL, of_default_bus_match_table,
spear310_auxdata_lookup, NULL);
}
static const char * const spear310_dt_board_compat[] = {
"st,spear310",
"st,spear310-evb",
NULL,
};
static void __init spear310_map_io(void)
{
spear3xx_map_io();
}
DT_MACHINE_START(SPEAR310_DT, "ST SPEAr310 SoC with Flattened Device Tree")
.map_io = spear310_map_io,
.init_irq = irqchip_init,
.init_time = spear3xx_timer_init,
.init_machine = spear310_dt_init,
.restart = spear_restart,
.dt_compat = spear310_dt_board_compat,
MACHINE_END
| gpl-2.0 |
losfair/MiracleKernel | fs/btrfs/lzo.c | 3327 | 10075 | /*
* Copyright (C) 2008 Oracle. 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 v2 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., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/sched.h>
#include <linux/pagemap.h>
#include <linux/bio.h>
#include <linux/lzo.h>
#include "compression.h"
#define LZO_LEN 4
struct workspace {
void *mem;
void *buf; /* where compressed data goes */
void *cbuf; /* where decompressed data goes */
struct list_head list;
};
static void lzo_free_workspace(struct list_head *ws)
{
struct workspace *workspace = list_entry(ws, struct workspace, list);
vfree(workspace->buf);
vfree(workspace->cbuf);
vfree(workspace->mem);
kfree(workspace);
}
static struct list_head *lzo_alloc_workspace(void)
{
struct workspace *workspace;
workspace = kzalloc(sizeof(*workspace), GFP_NOFS);
if (!workspace)
return ERR_PTR(-ENOMEM);
workspace->mem = vmalloc(LZO1X_MEM_COMPRESS);
workspace->buf = vmalloc(lzo1x_worst_compress(PAGE_CACHE_SIZE));
workspace->cbuf = vmalloc(lzo1x_worst_compress(PAGE_CACHE_SIZE));
if (!workspace->mem || !workspace->buf || !workspace->cbuf)
goto fail;
INIT_LIST_HEAD(&workspace->list);
return &workspace->list;
fail:
lzo_free_workspace(&workspace->list);
return ERR_PTR(-ENOMEM);
}
static inline void write_compress_length(char *buf, size_t len)
{
__le32 dlen;
dlen = cpu_to_le32(len);
memcpy(buf, &dlen, LZO_LEN);
}
static inline size_t read_compress_length(char *buf)
{
__le32 dlen;
memcpy(&dlen, buf, LZO_LEN);
return le32_to_cpu(dlen);
}
static int lzo_compress_pages(struct list_head *ws,
struct address_space *mapping,
u64 start, unsigned long len,
struct page **pages,
unsigned long nr_dest_pages,
unsigned long *out_pages,
unsigned long *total_in,
unsigned long *total_out,
unsigned long max_out)
{
struct workspace *workspace = list_entry(ws, struct workspace, list);
int ret = 0;
char *data_in;
char *cpage_out;
int nr_pages = 0;
struct page *in_page = NULL;
struct page *out_page = NULL;
unsigned long bytes_left;
size_t in_len;
size_t out_len;
char *buf;
unsigned long tot_in = 0;
unsigned long tot_out = 0;
unsigned long pg_bytes_left;
unsigned long out_offset;
unsigned long bytes;
*out_pages = 0;
*total_out = 0;
*total_in = 0;
in_page = find_get_page(mapping, start >> PAGE_CACHE_SHIFT);
data_in = kmap(in_page);
/*
* store the size of all chunks of compressed data in
* the first 4 bytes
*/
out_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
if (out_page == NULL) {
ret = -ENOMEM;
goto out;
}
cpage_out = kmap(out_page);
out_offset = LZO_LEN;
tot_out = LZO_LEN;
pages[0] = out_page;
nr_pages = 1;
pg_bytes_left = PAGE_CACHE_SIZE - LZO_LEN;
/* compress at most one page of data each time */
in_len = min(len, PAGE_CACHE_SIZE);
while (tot_in < len) {
ret = lzo1x_1_compress(data_in, in_len, workspace->cbuf,
&out_len, workspace->mem);
if (ret != LZO_E_OK) {
printk(KERN_DEBUG "btrfs deflate in loop returned %d\n",
ret);
ret = -1;
goto out;
}
/* store the size of this chunk of compressed data */
write_compress_length(cpage_out + out_offset, out_len);
tot_out += LZO_LEN;
out_offset += LZO_LEN;
pg_bytes_left -= LZO_LEN;
tot_in += in_len;
tot_out += out_len;
/* copy bytes from the working buffer into the pages */
buf = workspace->cbuf;
while (out_len) {
bytes = min_t(unsigned long, pg_bytes_left, out_len);
memcpy(cpage_out + out_offset, buf, bytes);
out_len -= bytes;
pg_bytes_left -= bytes;
buf += bytes;
out_offset += bytes;
/*
* we need another page for writing out.
*
* Note if there's less than 4 bytes left, we just
* skip to a new page.
*/
if ((out_len == 0 && pg_bytes_left < LZO_LEN) ||
pg_bytes_left == 0) {
if (pg_bytes_left) {
memset(cpage_out + out_offset, 0,
pg_bytes_left);
tot_out += pg_bytes_left;
}
/* we're done, don't allocate new page */
if (out_len == 0 && tot_in >= len)
break;
kunmap(out_page);
if (nr_pages == nr_dest_pages) {
out_page = NULL;
ret = -1;
goto out;
}
out_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
if (out_page == NULL) {
ret = -ENOMEM;
goto out;
}
cpage_out = kmap(out_page);
pages[nr_pages++] = out_page;
pg_bytes_left = PAGE_CACHE_SIZE;
out_offset = 0;
}
}
/* we're making it bigger, give up */
if (tot_in > 8192 && tot_in < tot_out)
goto out;
/* we're all done */
if (tot_in >= len)
break;
if (tot_out > max_out)
break;
bytes_left = len - tot_in;
kunmap(in_page);
page_cache_release(in_page);
start += PAGE_CACHE_SIZE;
in_page = find_get_page(mapping, start >> PAGE_CACHE_SHIFT);
data_in = kmap(in_page);
in_len = min(bytes_left, PAGE_CACHE_SIZE);
}
if (tot_out > tot_in)
goto out;
/* store the size of all chunks of compressed data */
cpage_out = kmap(pages[0]);
write_compress_length(cpage_out, tot_out);
kunmap(pages[0]);
ret = 0;
*total_out = tot_out;
*total_in = tot_in;
out:
*out_pages = nr_pages;
if (out_page)
kunmap(out_page);
if (in_page) {
kunmap(in_page);
page_cache_release(in_page);
}
return ret;
}
static int lzo_decompress_biovec(struct list_head *ws,
struct page **pages_in,
u64 disk_start,
struct bio_vec *bvec,
int vcnt,
size_t srclen)
{
struct workspace *workspace = list_entry(ws, struct workspace, list);
int ret = 0, ret2;
char *data_in;
unsigned long page_in_index = 0;
unsigned long page_out_index = 0;
unsigned long total_pages_in = (srclen + PAGE_CACHE_SIZE - 1) /
PAGE_CACHE_SIZE;
unsigned long buf_start;
unsigned long buf_offset = 0;
unsigned long bytes;
unsigned long working_bytes;
unsigned long pg_offset;
size_t in_len;
size_t out_len;
unsigned long in_offset;
unsigned long in_page_bytes_left;
unsigned long tot_in;
unsigned long tot_out;
unsigned long tot_len;
char *buf;
bool may_late_unmap, need_unmap;
data_in = kmap(pages_in[0]);
tot_len = read_compress_length(data_in);
tot_in = LZO_LEN;
in_offset = LZO_LEN;
tot_len = min_t(size_t, srclen, tot_len);
in_page_bytes_left = PAGE_CACHE_SIZE - LZO_LEN;
tot_out = 0;
pg_offset = 0;
while (tot_in < tot_len) {
in_len = read_compress_length(data_in + in_offset);
in_page_bytes_left -= LZO_LEN;
in_offset += LZO_LEN;
tot_in += LZO_LEN;
tot_in += in_len;
working_bytes = in_len;
may_late_unmap = need_unmap = false;
/* fast path: avoid using the working buffer */
if (in_page_bytes_left >= in_len) {
buf = data_in + in_offset;
bytes = in_len;
may_late_unmap = true;
goto cont;
}
/* copy bytes from the pages into the working buffer */
buf = workspace->cbuf;
buf_offset = 0;
while (working_bytes) {
bytes = min(working_bytes, in_page_bytes_left);
memcpy(buf + buf_offset, data_in + in_offset, bytes);
buf_offset += bytes;
cont:
working_bytes -= bytes;
in_page_bytes_left -= bytes;
in_offset += bytes;
/* check if we need to pick another page */
if ((working_bytes == 0 && in_page_bytes_left < LZO_LEN)
|| in_page_bytes_left == 0) {
tot_in += in_page_bytes_left;
if (working_bytes == 0 && tot_in >= tot_len)
break;
if (page_in_index + 1 >= total_pages_in) {
ret = -1;
goto done;
}
if (may_late_unmap)
need_unmap = true;
else
kunmap(pages_in[page_in_index]);
data_in = kmap(pages_in[++page_in_index]);
in_page_bytes_left = PAGE_CACHE_SIZE;
in_offset = 0;
}
}
out_len = lzo1x_worst_compress(PAGE_CACHE_SIZE);
ret = lzo1x_decompress_safe(buf, in_len, workspace->buf,
&out_len);
if (need_unmap)
kunmap(pages_in[page_in_index - 1]);
if (ret != LZO_E_OK) {
printk(KERN_WARNING "btrfs decompress failed\n");
ret = -1;
break;
}
buf_start = tot_out;
tot_out += out_len;
ret2 = btrfs_decompress_buf2page(workspace->buf, buf_start,
tot_out, disk_start,
bvec, vcnt,
&page_out_index, &pg_offset);
if (ret2 == 0)
break;
}
done:
kunmap(pages_in[page_in_index]);
return ret;
}
static int lzo_decompress(struct list_head *ws, unsigned char *data_in,
struct page *dest_page,
unsigned long start_byte,
size_t srclen, size_t destlen)
{
struct workspace *workspace = list_entry(ws, struct workspace, list);
size_t in_len;
size_t out_len;
size_t tot_len;
int ret = 0;
char *kaddr;
unsigned long bytes;
BUG_ON(srclen < LZO_LEN);
tot_len = read_compress_length(data_in);
data_in += LZO_LEN;
in_len = read_compress_length(data_in);
data_in += LZO_LEN;
out_len = PAGE_CACHE_SIZE;
ret = lzo1x_decompress_safe(data_in, in_len, workspace->buf, &out_len);
if (ret != LZO_E_OK) {
printk(KERN_WARNING "btrfs decompress failed!\n");
ret = -1;
goto out;
}
if (out_len < start_byte) {
ret = -1;
goto out;
}
bytes = min_t(unsigned long, destlen, out_len - start_byte);
kaddr = kmap_atomic(dest_page, KM_USER0);
memcpy(kaddr, workspace->buf + start_byte, bytes);
kunmap_atomic(kaddr, KM_USER0);
out:
return ret;
}
struct btrfs_compress_op btrfs_lzo_compress = {
.alloc_workspace = lzo_alloc_workspace,
.free_workspace = lzo_free_workspace,
.compress_pages = lzo_compress_pages,
.decompress_biovec = lzo_decompress_biovec,
.decompress = lzo_decompress,
};
| gpl-2.0 |
go2ev-devteam/linux-tk1 | drivers/scsi/aacraid/dpcsup.c | 3583 | 11730 | /*
* Adaptec AAC series RAID controller driver
* (c) Copyright 2001 Red Hat Inc.
*
* based on the old aacraid driver that is..
* Adaptec aacraid device driver for Linux.
*
* Copyright (c) 2000-2010 Adaptec, Inc.
* 2010 PMC-Sierra, Inc. (aacraid@pmc-sierra.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, 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, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Module Name:
* dpcsup.c
*
* Abstract: All DPC processing routines for the cyclone board occur here.
*
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/completion.h>
#include <linux/blkdev.h>
#include <linux/semaphore.h>
#include "aacraid.h"
/**
* aac_response_normal - Handle command replies
* @q: Queue to read from
*
* This DPC routine will be run when the adapter interrupts us to let us
* know there is a response on our normal priority queue. We will pull off
* all QE there are and wake up all the waiters before exiting. We will
* take a spinlock out on the queue before operating on it.
*/
unsigned int aac_response_normal(struct aac_queue * q)
{
struct aac_dev * dev = q->dev;
struct aac_entry *entry;
struct hw_fib * hwfib;
struct fib * fib;
int consumed = 0;
unsigned long flags, mflags;
spin_lock_irqsave(q->lock, flags);
/*
* Keep pulling response QEs off the response queue and waking
* up the waiters until there are no more QEs. We then return
* back to the system. If no response was requesed we just
* deallocate the Fib here and continue.
*/
while(aac_consumer_get(dev, q, &entry))
{
int fast;
u32 index = le32_to_cpu(entry->addr);
fast = index & 0x01;
fib = &dev->fibs[index >> 2];
hwfib = fib->hw_fib_va;
aac_consumer_free(dev, q, HostNormRespQueue);
/*
* Remove this fib from the Outstanding I/O queue.
* But only if it has not already been timed out.
*
* If the fib has been timed out already, then just
* continue. The caller has already been notified that
* the fib timed out.
*/
dev->queues->queue[AdapNormCmdQueue].numpending--;
if (unlikely(fib->flags & FIB_CONTEXT_FLAG_TIMED_OUT)) {
spin_unlock_irqrestore(q->lock, flags);
aac_fib_complete(fib);
aac_fib_free(fib);
spin_lock_irqsave(q->lock, flags);
continue;
}
spin_unlock_irqrestore(q->lock, flags);
if (fast) {
/*
* Doctor the fib
*/
*(__le32 *)hwfib->data = cpu_to_le32(ST_OK);
hwfib->header.XferState |= cpu_to_le32(AdapterProcessed);
fib->flags |= FIB_CONTEXT_FLAG_FASTRESP;
}
FIB_COUNTER_INCREMENT(aac_config.FibRecved);
if (hwfib->header.Command == cpu_to_le16(NuFileSystem))
{
__le32 *pstatus = (__le32 *)hwfib->data;
if (*pstatus & cpu_to_le32(0xffff0000))
*pstatus = cpu_to_le32(ST_OK);
}
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected | Async))
{
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected))
FIB_COUNTER_INCREMENT(aac_config.NoResponseRecved);
else
FIB_COUNTER_INCREMENT(aac_config.AsyncRecved);
/*
* NOTE: we cannot touch the fib after this
* call, because it may have been deallocated.
*/
fib->flags &= FIB_CONTEXT_FLAG_FASTRESP;
fib->callback(fib->callback_data, fib);
} else {
unsigned long flagv;
spin_lock_irqsave(&fib->event_lock, flagv);
if (!fib->done) {
fib->done = 1;
up(&fib->event_wait);
}
spin_unlock_irqrestore(&fib->event_lock, flagv);
spin_lock_irqsave(&dev->manage_lock, mflags);
dev->management_fib_count--;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
FIB_COUNTER_INCREMENT(aac_config.NormalRecved);
if (fib->done == 2) {
spin_lock_irqsave(&fib->event_lock, flagv);
fib->done = 0;
spin_unlock_irqrestore(&fib->event_lock, flagv);
aac_fib_complete(fib);
aac_fib_free(fib);
}
}
consumed++;
spin_lock_irqsave(q->lock, flags);
}
if (consumed > aac_config.peak_fibs)
aac_config.peak_fibs = consumed;
if (consumed == 0)
aac_config.zero_fibs++;
spin_unlock_irqrestore(q->lock, flags);
return 0;
}
/**
* aac_command_normal - handle commands
* @q: queue to process
*
* This DPC routine will be queued when the adapter interrupts us to
* let us know there is a command on our normal priority queue. We will
* pull off all QE there are and wake up all the waiters before exiting.
* We will take a spinlock out on the queue before operating on it.
*/
unsigned int aac_command_normal(struct aac_queue *q)
{
struct aac_dev * dev = q->dev;
struct aac_entry *entry;
unsigned long flags;
spin_lock_irqsave(q->lock, flags);
/*
* Keep pulling response QEs off the response queue and waking
* up the waiters until there are no more QEs. We then return
* back to the system.
*/
while(aac_consumer_get(dev, q, &entry))
{
struct fib fibctx;
struct hw_fib * hw_fib;
u32 index;
struct fib *fib = &fibctx;
index = le32_to_cpu(entry->addr) / sizeof(struct hw_fib);
hw_fib = &dev->aif_base_va[index];
/*
* Allocate a FIB at all costs. For non queued stuff
* we can just use the stack so we are happy. We need
* a fib object in order to manage the linked lists
*/
if (dev->aif_thread)
if((fib = kmalloc(sizeof(struct fib), GFP_ATOMIC)) == NULL)
fib = &fibctx;
memset(fib, 0, sizeof(struct fib));
INIT_LIST_HEAD(&fib->fiblink);
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof(struct fib);
fib->hw_fib_va = hw_fib;
fib->data = hw_fib->data;
fib->dev = dev;
if (dev->aif_thread && fib != &fibctx) {
list_add_tail(&fib->fiblink, &q->cmdq);
aac_consumer_free(dev, q, HostNormCmdQueue);
wake_up_interruptible(&q->cmdready);
} else {
aac_consumer_free(dev, q, HostNormCmdQueue);
spin_unlock_irqrestore(q->lock, flags);
/*
* Set the status of this FIB
*/
*(__le32 *)hw_fib->data = cpu_to_le32(ST_OK);
aac_fib_adapter_complete(fib, sizeof(u32));
spin_lock_irqsave(q->lock, flags);
}
}
spin_unlock_irqrestore(q->lock, flags);
return 0;
}
/*
*
* aac_aif_callback
* @context: the context set in the fib - here it is scsi cmd
* @fibptr: pointer to the fib
*
* Handles the AIFs - new method (SRC)
*
*/
static void aac_aif_callback(void *context, struct fib * fibptr)
{
struct fib *fibctx;
struct aac_dev *dev;
struct aac_aifcmd *cmd;
int status;
fibctx = (struct fib *)context;
BUG_ON(fibptr == NULL);
dev = fibptr->dev;
if (fibptr->hw_fib_va->header.XferState &
cpu_to_le32(NoMoreAifDataAvailable)) {
aac_fib_complete(fibptr);
aac_fib_free(fibptr);
return;
}
aac_intr_normal(dev, 0, 1, 0, fibptr->hw_fib_va);
aac_fib_init(fibctx);
cmd = (struct aac_aifcmd *) fib_data(fibctx);
cmd->command = cpu_to_le32(AifReqEvent);
status = aac_fib_send(AifRequest,
fibctx,
sizeof(struct hw_fib)-sizeof(struct aac_fibhdr),
FsaNormal,
0, 1,
(fib_callback)aac_aif_callback, fibctx);
}
/**
* aac_intr_normal - Handle command replies
* @dev: Device
* @index: completion reference
*
* This DPC routine will be run when the adapter interrupts us to let us
* know there is a response on our normal priority queue. We will pull off
* all QE there are and wake up all the waiters before exiting.
*/
unsigned int aac_intr_normal(struct aac_dev *dev, u32 index,
int isAif, int isFastResponse, struct hw_fib *aif_fib)
{
unsigned long mflags;
dprintk((KERN_INFO "aac_intr_normal(%p,%x)\n", dev, index));
if (isAif == 1) { /* AIF - common */
struct hw_fib * hw_fib;
struct fib * fib;
struct aac_queue *q = &dev->queues->queue[HostNormCmdQueue];
unsigned long flags;
/*
* Allocate a FIB. For non queued stuff we can just use
* the stack so we are happy. We need a fib object in order to
* manage the linked lists.
*/
if ((!dev->aif_thread)
|| (!(fib = kzalloc(sizeof(struct fib),GFP_ATOMIC))))
return 1;
if (!(hw_fib = kzalloc(sizeof(struct hw_fib),GFP_ATOMIC))) {
kfree (fib);
return 1;
}
if (aif_fib != NULL) {
memcpy(hw_fib, aif_fib, sizeof(struct hw_fib));
} else {
memcpy(hw_fib,
(struct hw_fib *)(((uintptr_t)(dev->regs.sa)) +
index), sizeof(struct hw_fib));
}
INIT_LIST_HEAD(&fib->fiblink);
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof(struct fib);
fib->hw_fib_va = hw_fib;
fib->data = hw_fib->data;
fib->dev = dev;
spin_lock_irqsave(q->lock, flags);
list_add_tail(&fib->fiblink, &q->cmdq);
wake_up_interruptible(&q->cmdready);
spin_unlock_irqrestore(q->lock, flags);
return 1;
} else if (isAif == 2) { /* AIF - new (SRC) */
struct fib *fibctx;
struct aac_aifcmd *cmd;
fibctx = aac_fib_alloc(dev);
if (!fibctx)
return 1;
aac_fib_init(fibctx);
cmd = (struct aac_aifcmd *) fib_data(fibctx);
cmd->command = cpu_to_le32(AifReqEvent);
return aac_fib_send(AifRequest,
fibctx,
sizeof(struct hw_fib)-sizeof(struct aac_fibhdr),
FsaNormal,
0, 1,
(fib_callback)aac_aif_callback, fibctx);
} else {
struct fib *fib = &dev->fibs[index];
struct hw_fib * hwfib = fib->hw_fib_va;
/*
* Remove this fib from the Outstanding I/O queue.
* But only if it has not already been timed out.
*
* If the fib has been timed out already, then just
* continue. The caller has already been notified that
* the fib timed out.
*/
dev->queues->queue[AdapNormCmdQueue].numpending--;
if (unlikely(fib->flags & FIB_CONTEXT_FLAG_TIMED_OUT)) {
aac_fib_complete(fib);
aac_fib_free(fib);
return 0;
}
if (isFastResponse) {
/*
* Doctor the fib
*/
*(__le32 *)hwfib->data = cpu_to_le32(ST_OK);
hwfib->header.XferState |= cpu_to_le32(AdapterProcessed);
fib->flags |= FIB_CONTEXT_FLAG_FASTRESP;
}
FIB_COUNTER_INCREMENT(aac_config.FibRecved);
if (hwfib->header.Command == cpu_to_le16(NuFileSystem))
{
__le32 *pstatus = (__le32 *)hwfib->data;
if (*pstatus & cpu_to_le32(0xffff0000))
*pstatus = cpu_to_le32(ST_OK);
}
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected | Async))
{
if (hwfib->header.XferState & cpu_to_le32(NoResponseExpected))
FIB_COUNTER_INCREMENT(aac_config.NoResponseRecved);
else
FIB_COUNTER_INCREMENT(aac_config.AsyncRecved);
/*
* NOTE: we cannot touch the fib after this
* call, because it may have been deallocated.
*/
fib->flags &= FIB_CONTEXT_FLAG_FASTRESP;
fib->callback(fib->callback_data, fib);
} else {
unsigned long flagv;
dprintk((KERN_INFO "event_wait up\n"));
spin_lock_irqsave(&fib->event_lock, flagv);
if (!fib->done) {
fib->done = 1;
up(&fib->event_wait);
}
spin_unlock_irqrestore(&fib->event_lock, flagv);
spin_lock_irqsave(&dev->manage_lock, mflags);
dev->management_fib_count--;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
FIB_COUNTER_INCREMENT(aac_config.NormalRecved);
if (fib->done == 2) {
spin_lock_irqsave(&fib->event_lock, flagv);
fib->done = 0;
spin_unlock_irqrestore(&fib->event_lock, flagv);
aac_fib_complete(fib);
aac_fib_free(fib);
}
}
return 0;
}
}
| gpl-2.0 |
tepelmann/linux-perf | net/rds/page.c | 4351 | 5912 | /*
* 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/highmem.h>
#include <linux/gfp.h>
#include <linux/cpu.h>
#include <linux/export.h>
#include "rds.h"
struct rds_page_remainder {
struct page *r_page;
unsigned long r_offset;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct rds_page_remainder,
rds_page_remainders);
/*
* returns 0 on success or -errno on failure.
*
* We don't have to worry about flush_dcache_page() as this only works
* with private pages. If, say, we were to do directed receive to pinned
* user pages we'd have to worry more about cache coherence. (Though
* the flush_dcache_page() in get_user_pages() would probably be enough).
*/
int rds_page_copy_user(struct page *page, unsigned long offset,
void __user *ptr, unsigned long bytes,
int to_user)
{
unsigned long ret;
void *addr;
addr = kmap(page);
if (to_user) {
rds_stats_add(s_copy_to_user, bytes);
ret = copy_to_user(ptr, addr + offset, bytes);
} else {
rds_stats_add(s_copy_from_user, bytes);
ret = copy_from_user(addr + offset, ptr, bytes);
}
kunmap(page);
return ret ? -EFAULT : 0;
}
EXPORT_SYMBOL_GPL(rds_page_copy_user);
/**
* rds_page_remainder_alloc - build up regions of a message.
*
* @scat: Scatter list for message
* @bytes: the number of bytes needed.
* @gfp: the waiting behaviour of the allocation
*
* @gfp is always ored with __GFP_HIGHMEM. Callers must be prepared to
* kmap the pages, etc.
*
* If @bytes is at least a full page then this just returns a page from
* alloc_page().
*
* If @bytes is a partial page then this stores the unused region of the
* page in a per-cpu structure. Future partial-page allocations may be
* satisfied from that cached region. This lets us waste less memory on
* small allocations with minimal complexity. It works because the transmit
* path passes read-only page regions down to devices. They hold a page
* reference until they are done with the region.
*/
int rds_page_remainder_alloc(struct scatterlist *scat, unsigned long bytes,
gfp_t gfp)
{
struct rds_page_remainder *rem;
unsigned long flags;
struct page *page;
int ret;
gfp |= __GFP_HIGHMEM;
/* jump straight to allocation if we're trying for a huge page */
if (bytes >= PAGE_SIZE) {
page = alloc_page(gfp);
if (!page) {
ret = -ENOMEM;
} else {
sg_set_page(scat, page, PAGE_SIZE, 0);
ret = 0;
}
goto out;
}
rem = &per_cpu(rds_page_remainders, get_cpu());
local_irq_save(flags);
while (1) {
/* avoid a tiny region getting stuck by tossing it */
if (rem->r_page && bytes > (PAGE_SIZE - rem->r_offset)) {
rds_stats_inc(s_page_remainder_miss);
__free_page(rem->r_page);
rem->r_page = NULL;
}
/* hand out a fragment from the cached page */
if (rem->r_page && bytes <= (PAGE_SIZE - rem->r_offset)) {
sg_set_page(scat, rem->r_page, bytes, rem->r_offset);
get_page(sg_page(scat));
if (rem->r_offset != 0)
rds_stats_inc(s_page_remainder_hit);
rem->r_offset += bytes;
if (rem->r_offset == PAGE_SIZE) {
__free_page(rem->r_page);
rem->r_page = NULL;
}
ret = 0;
break;
}
/* alloc if there is nothing for us to use */
local_irq_restore(flags);
put_cpu();
page = alloc_page(gfp);
rem = &per_cpu(rds_page_remainders, get_cpu());
local_irq_save(flags);
if (!page) {
ret = -ENOMEM;
break;
}
/* did someone race to fill the remainder before us? */
if (rem->r_page) {
__free_page(page);
continue;
}
/* otherwise install our page and loop around to alloc */
rem->r_page = page;
rem->r_offset = 0;
}
local_irq_restore(flags);
put_cpu();
out:
rdsdebug("bytes %lu ret %d %p %u %u\n", bytes, ret,
ret ? NULL : sg_page(scat), ret ? 0 : scat->offset,
ret ? 0 : scat->length);
return ret;
}
EXPORT_SYMBOL_GPL(rds_page_remainder_alloc);
static int rds_page_remainder_cpu_notify(struct notifier_block *self,
unsigned long action, void *hcpu)
{
struct rds_page_remainder *rem;
long cpu = (long)hcpu;
rem = &per_cpu(rds_page_remainders, cpu);
rdsdebug("cpu %ld action 0x%lx\n", cpu, action);
switch (action) {
case CPU_DEAD:
if (rem->r_page)
__free_page(rem->r_page);
rem->r_page = NULL;
break;
}
return 0;
}
static struct notifier_block rds_page_remainder_nb = {
.notifier_call = rds_page_remainder_cpu_notify,
};
void rds_page_exit(void)
{
int i;
for_each_possible_cpu(i)
rds_page_remainder_cpu_notify(&rds_page_remainder_nb,
(unsigned long)CPU_DEAD,
(void *)(long)i);
}
| gpl-2.0 |
fat-tire/android_kernel_qcom_kfire-hdx-common | drivers/media/video/mt9v022.c | 4863 | 23613 | /*
* Driver for MT9V022 CMOS Image Sensor from Micron
*
* Copyright (C) 2008, Guennadi Liakhovetski <kernel@pengutronix.de>
*
* 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/videodev2.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/delay.h>
#include <linux/log2.h>
#include <linux/module.h>
#include <media/soc_camera.h>
#include <media/soc_mediabus.h>
#include <media/v4l2-subdev.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-ctrls.h>
/*
* mt9v022 i2c address 0x48, 0x4c, 0x58, 0x5c
* The platform has to define ctruct i2c_board_info objects and link to them
* from struct soc_camera_link
*/
static char *sensor_type;
module_param(sensor_type, charp, S_IRUGO);
MODULE_PARM_DESC(sensor_type, "Sensor type: \"colour\" or \"monochrome\"");
/* mt9v022 selected register addresses */
#define MT9V022_CHIP_VERSION 0x00
#define MT9V022_COLUMN_START 0x01
#define MT9V022_ROW_START 0x02
#define MT9V022_WINDOW_HEIGHT 0x03
#define MT9V022_WINDOW_WIDTH 0x04
#define MT9V022_HORIZONTAL_BLANKING 0x05
#define MT9V022_VERTICAL_BLANKING 0x06
#define MT9V022_CHIP_CONTROL 0x07
#define MT9V022_SHUTTER_WIDTH1 0x08
#define MT9V022_SHUTTER_WIDTH2 0x09
#define MT9V022_SHUTTER_WIDTH_CTRL 0x0a
#define MT9V022_TOTAL_SHUTTER_WIDTH 0x0b
#define MT9V022_RESET 0x0c
#define MT9V022_READ_MODE 0x0d
#define MT9V022_MONITOR_MODE 0x0e
#define MT9V022_PIXEL_OPERATION_MODE 0x0f
#define MT9V022_LED_OUT_CONTROL 0x1b
#define MT9V022_ADC_MODE_CONTROL 0x1c
#define MT9V022_ANALOG_GAIN 0x35
#define MT9V022_BLACK_LEVEL_CALIB_CTRL 0x47
#define MT9V022_PIXCLK_FV_LV 0x74
#define MT9V022_DIGITAL_TEST_PATTERN 0x7f
#define MT9V022_AEC_AGC_ENABLE 0xAF
#define MT9V022_MAX_TOTAL_SHUTTER_WIDTH 0xBD
/* Progressive scan, master, defaults */
#define MT9V022_CHIP_CONTROL_DEFAULT 0x188
#define MT9V022_MAX_WIDTH 752
#define MT9V022_MAX_HEIGHT 480
#define MT9V022_MIN_WIDTH 48
#define MT9V022_MIN_HEIGHT 32
#define MT9V022_COLUMN_SKIP 1
#define MT9V022_ROW_SKIP 4
/* MT9V022 has only one fixed colorspace per pixelcode */
struct mt9v022_datafmt {
enum v4l2_mbus_pixelcode code;
enum v4l2_colorspace colorspace;
};
/* Find a data format by a pixel code in an array */
static const struct mt9v022_datafmt *mt9v022_find_datafmt(
enum v4l2_mbus_pixelcode code, const struct mt9v022_datafmt *fmt,
int n)
{
int i;
for (i = 0; i < n; i++)
if (fmt[i].code == code)
return fmt + i;
return NULL;
}
static const struct mt9v022_datafmt mt9v022_colour_fmts[] = {
/*
* Order important: first natively supported,
* second supported with a GPIO extender
*/
{V4L2_MBUS_FMT_SBGGR10_1X10, V4L2_COLORSPACE_SRGB},
{V4L2_MBUS_FMT_SBGGR8_1X8, V4L2_COLORSPACE_SRGB},
};
static const struct mt9v022_datafmt mt9v022_monochrome_fmts[] = {
/* Order important - see above */
{V4L2_MBUS_FMT_Y10_1X10, V4L2_COLORSPACE_JPEG},
{V4L2_MBUS_FMT_Y8_1X8, V4L2_COLORSPACE_JPEG},
};
struct mt9v022 {
struct v4l2_subdev subdev;
struct v4l2_ctrl_handler hdl;
struct {
/* exposure/auto-exposure cluster */
struct v4l2_ctrl *autoexposure;
struct v4l2_ctrl *exposure;
};
struct {
/* gain/auto-gain cluster */
struct v4l2_ctrl *autogain;
struct v4l2_ctrl *gain;
};
struct v4l2_rect rect; /* Sensor window */
const struct mt9v022_datafmt *fmt;
const struct mt9v022_datafmt *fmts;
int num_fmts;
int model; /* V4L2_IDENT_MT9V022* codes from v4l2-chip-ident.h */
u16 chip_control;
unsigned short y_skip_top; /* Lines to skip at the top */
};
static struct mt9v022 *to_mt9v022(const struct i2c_client *client)
{
return container_of(i2c_get_clientdata(client), struct mt9v022, subdev);
}
static int reg_read(struct i2c_client *client, const u8 reg)
{
return i2c_smbus_read_word_swapped(client, reg);
}
static int reg_write(struct i2c_client *client, const u8 reg,
const u16 data)
{
return i2c_smbus_write_word_swapped(client, reg, data);
}
static int reg_set(struct i2c_client *client, const u8 reg,
const u16 data)
{
int ret;
ret = reg_read(client, reg);
if (ret < 0)
return ret;
return reg_write(client, reg, ret | data);
}
static int reg_clear(struct i2c_client *client, const u8 reg,
const u16 data)
{
int ret;
ret = reg_read(client, reg);
if (ret < 0)
return ret;
return reg_write(client, reg, ret & ~data);
}
static int mt9v022_init(struct i2c_client *client)
{
struct mt9v022 *mt9v022 = to_mt9v022(client);
int ret;
/*
* Almost the default mode: master, parallel, simultaneous, and an
* undocumented bit 0x200, which is present in table 7, but not in 8,
* plus snapshot mode to disable scan for now
*/
mt9v022->chip_control |= 0x10;
ret = reg_write(client, MT9V022_CHIP_CONTROL, mt9v022->chip_control);
if (!ret)
ret = reg_write(client, MT9V022_READ_MODE, 0x300);
/* All defaults */
if (!ret)
/* AEC, AGC on */
ret = reg_set(client, MT9V022_AEC_AGC_ENABLE, 0x3);
if (!ret)
ret = reg_write(client, MT9V022_ANALOG_GAIN, 16);
if (!ret)
ret = reg_write(client, MT9V022_TOTAL_SHUTTER_WIDTH, 480);
if (!ret)
ret = reg_write(client, MT9V022_MAX_TOTAL_SHUTTER_WIDTH, 480);
if (!ret)
/* default - auto */
ret = reg_clear(client, MT9V022_BLACK_LEVEL_CALIB_CTRL, 1);
if (!ret)
ret = reg_write(client, MT9V022_DIGITAL_TEST_PATTERN, 0);
if (!ret)
return v4l2_ctrl_handler_setup(&mt9v022->hdl);
return ret;
}
static int mt9v022_s_stream(struct v4l2_subdev *sd, int enable)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
if (enable)
/* Switch to master "normal" mode */
mt9v022->chip_control &= ~0x10;
else
/* Switch to snapshot mode */
mt9v022->chip_control |= 0x10;
if (reg_write(client, MT9V022_CHIP_CONTROL, mt9v022->chip_control) < 0)
return -EIO;
return 0;
}
static int mt9v022_s_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
struct v4l2_rect rect = a->c;
int ret;
/* Bayer format - even size lengths */
if (mt9v022->fmts == mt9v022_colour_fmts) {
rect.width = ALIGN(rect.width, 2);
rect.height = ALIGN(rect.height, 2);
/* Let the user play with the starting pixel */
}
soc_camera_limit_side(&rect.left, &rect.width,
MT9V022_COLUMN_SKIP, MT9V022_MIN_WIDTH, MT9V022_MAX_WIDTH);
soc_camera_limit_side(&rect.top, &rect.height,
MT9V022_ROW_SKIP, MT9V022_MIN_HEIGHT, MT9V022_MAX_HEIGHT);
/* Like in example app. Contradicts the datasheet though */
ret = reg_read(client, MT9V022_AEC_AGC_ENABLE);
if (ret >= 0) {
if (ret & 1) /* Autoexposure */
ret = reg_write(client, MT9V022_MAX_TOTAL_SHUTTER_WIDTH,
rect.height + mt9v022->y_skip_top + 43);
else
ret = reg_write(client, MT9V022_TOTAL_SHUTTER_WIDTH,
rect.height + mt9v022->y_skip_top + 43);
}
/* Setup frame format: defaults apart from width and height */
if (!ret)
ret = reg_write(client, MT9V022_COLUMN_START, rect.left);
if (!ret)
ret = reg_write(client, MT9V022_ROW_START, rect.top);
if (!ret)
/*
* Default 94, Phytec driver says:
* "width + horizontal blank >= 660"
*/
ret = reg_write(client, MT9V022_HORIZONTAL_BLANKING,
rect.width > 660 - 43 ? 43 :
660 - rect.width);
if (!ret)
ret = reg_write(client, MT9V022_VERTICAL_BLANKING, 45);
if (!ret)
ret = reg_write(client, MT9V022_WINDOW_WIDTH, rect.width);
if (!ret)
ret = reg_write(client, MT9V022_WINDOW_HEIGHT,
rect.height + mt9v022->y_skip_top);
if (ret < 0)
return ret;
dev_dbg(&client->dev, "Frame %dx%d pixel\n", rect.width, rect.height);
mt9v022->rect = rect;
return 0;
}
static int mt9v022_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
a->c = mt9v022->rect;
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
return 0;
}
static int mt9v022_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a)
{
a->bounds.left = MT9V022_COLUMN_SKIP;
a->bounds.top = MT9V022_ROW_SKIP;
a->bounds.width = MT9V022_MAX_WIDTH;
a->bounds.height = MT9V022_MAX_HEIGHT;
a->defrect = a->bounds;
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
a->pixelaspect.numerator = 1;
a->pixelaspect.denominator = 1;
return 0;
}
static int mt9v022_g_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
mf->width = mt9v022->rect.width;
mf->height = mt9v022->rect.height;
mf->code = mt9v022->fmt->code;
mf->colorspace = mt9v022->fmt->colorspace;
mf->field = V4L2_FIELD_NONE;
return 0;
}
static int mt9v022_s_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
struct v4l2_crop a = {
.c = {
.left = mt9v022->rect.left,
.top = mt9v022->rect.top,
.width = mf->width,
.height = mf->height,
},
};
int ret;
/*
* The caller provides a supported format, as verified per call to
* .try_mbus_fmt(), datawidth is from our supported format list
*/
switch (mf->code) {
case V4L2_MBUS_FMT_Y8_1X8:
case V4L2_MBUS_FMT_Y10_1X10:
if (mt9v022->model != V4L2_IDENT_MT9V022IX7ATM)
return -EINVAL;
break;
case V4L2_MBUS_FMT_SBGGR8_1X8:
case V4L2_MBUS_FMT_SBGGR10_1X10:
if (mt9v022->model != V4L2_IDENT_MT9V022IX7ATC)
return -EINVAL;
break;
default:
return -EINVAL;
}
/* No support for scaling on this camera, just crop. */
ret = mt9v022_s_crop(sd, &a);
if (!ret) {
mf->width = mt9v022->rect.width;
mf->height = mt9v022->rect.height;
mt9v022->fmt = mt9v022_find_datafmt(mf->code,
mt9v022->fmts, mt9v022->num_fmts);
mf->colorspace = mt9v022->fmt->colorspace;
}
return ret;
}
static int mt9v022_try_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
const struct mt9v022_datafmt *fmt;
int align = mf->code == V4L2_MBUS_FMT_SBGGR8_1X8 ||
mf->code == V4L2_MBUS_FMT_SBGGR10_1X10;
v4l_bound_align_image(&mf->width, MT9V022_MIN_WIDTH,
MT9V022_MAX_WIDTH, align,
&mf->height, MT9V022_MIN_HEIGHT + mt9v022->y_skip_top,
MT9V022_MAX_HEIGHT + mt9v022->y_skip_top, align, 0);
fmt = mt9v022_find_datafmt(mf->code, mt9v022->fmts,
mt9v022->num_fmts);
if (!fmt) {
fmt = mt9v022->fmt;
mf->code = fmt->code;
}
mf->colorspace = fmt->colorspace;
return 0;
}
static int mt9v022_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *id)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
if (id->match.type != V4L2_CHIP_MATCH_I2C_ADDR)
return -EINVAL;
if (id->match.addr != client->addr)
return -ENODEV;
id->ident = mt9v022->model;
id->revision = 0;
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int mt9v022_g_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (reg->match.type != V4L2_CHIP_MATCH_I2C_ADDR || reg->reg > 0xff)
return -EINVAL;
if (reg->match.addr != client->addr)
return -ENODEV;
reg->size = 2;
reg->val = reg_read(client, reg->reg);
if (reg->val > 0xffff)
return -EIO;
return 0;
}
static int mt9v022_s_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (reg->match.type != V4L2_CHIP_MATCH_I2C_ADDR || reg->reg > 0xff)
return -EINVAL;
if (reg->match.addr != client->addr)
return -ENODEV;
if (reg_write(client, reg->reg, reg->val) < 0)
return -EIO;
return 0;
}
#endif
static int mt9v022_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
{
struct mt9v022 *mt9v022 = container_of(ctrl->handler,
struct mt9v022, hdl);
struct v4l2_subdev *sd = &mt9v022->subdev;
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct v4l2_ctrl *gain = mt9v022->gain;
struct v4l2_ctrl *exp = mt9v022->exposure;
unsigned long range;
int data;
switch (ctrl->id) {
case V4L2_CID_AUTOGAIN:
data = reg_read(client, MT9V022_ANALOG_GAIN);
if (data < 0)
return -EIO;
range = gain->maximum - gain->minimum;
gain->val = ((data - 16) * range + 24) / 48 + gain->minimum;
return 0;
case V4L2_CID_EXPOSURE_AUTO:
data = reg_read(client, MT9V022_TOTAL_SHUTTER_WIDTH);
if (data < 0)
return -EIO;
range = exp->maximum - exp->minimum;
exp->val = ((data - 1) * range + 239) / 479 + exp->minimum;
return 0;
}
return -EINVAL;
}
static int mt9v022_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct mt9v022 *mt9v022 = container_of(ctrl->handler,
struct mt9v022, hdl);
struct v4l2_subdev *sd = &mt9v022->subdev;
struct i2c_client *client = v4l2_get_subdevdata(sd);
int data;
switch (ctrl->id) {
case V4L2_CID_VFLIP:
if (ctrl->val)
data = reg_set(client, MT9V022_READ_MODE, 0x10);
else
data = reg_clear(client, MT9V022_READ_MODE, 0x10);
if (data < 0)
return -EIO;
return 0;
case V4L2_CID_HFLIP:
if (ctrl->val)
data = reg_set(client, MT9V022_READ_MODE, 0x20);
else
data = reg_clear(client, MT9V022_READ_MODE, 0x20);
if (data < 0)
return -EIO;
return 0;
case V4L2_CID_AUTOGAIN:
if (ctrl->val) {
if (reg_set(client, MT9V022_AEC_AGC_ENABLE, 0x2) < 0)
return -EIO;
} else {
struct v4l2_ctrl *gain = mt9v022->gain;
/* mt9v022 has minimum == default */
unsigned long range = gain->maximum - gain->minimum;
/* Valid values 16 to 64, 32 to 64 must be even. */
unsigned long gain_val = ((gain->val - gain->minimum) *
48 + range / 2) / range + 16;
if (gain_val >= 32)
gain_val &= ~1;
/*
* The user wants to set gain manually, hope, she
* knows, what she's doing... Switch AGC off.
*/
if (reg_clear(client, MT9V022_AEC_AGC_ENABLE, 0x2) < 0)
return -EIO;
dev_dbg(&client->dev, "Setting gain from %d to %lu\n",
reg_read(client, MT9V022_ANALOG_GAIN), gain_val);
if (reg_write(client, MT9V022_ANALOG_GAIN, gain_val) < 0)
return -EIO;
}
return 0;
case V4L2_CID_EXPOSURE_AUTO:
if (ctrl->val == V4L2_EXPOSURE_AUTO) {
data = reg_set(client, MT9V022_AEC_AGC_ENABLE, 0x1);
} else {
struct v4l2_ctrl *exp = mt9v022->exposure;
unsigned long range = exp->maximum - exp->minimum;
unsigned long shutter = ((exp->val - exp->minimum) *
479 + range / 2) / range + 1;
/*
* The user wants to set shutter width manually, hope,
* she knows, what she's doing... Switch AEC off.
*/
data = reg_clear(client, MT9V022_AEC_AGC_ENABLE, 0x1);
if (data < 0)
return -EIO;
dev_dbg(&client->dev, "Shutter width from %d to %lu\n",
reg_read(client, MT9V022_TOTAL_SHUTTER_WIDTH),
shutter);
if (reg_write(client, MT9V022_TOTAL_SHUTTER_WIDTH,
shutter) < 0)
return -EIO;
}
return 0;
}
return -EINVAL;
}
/*
* Interface active, can use i2c. If it fails, it can indeed mean, that
* this wasn't our capture interface, so, we wait for the right one
*/
static int mt9v022_video_probe(struct i2c_client *client)
{
struct mt9v022 *mt9v022 = to_mt9v022(client);
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
s32 data;
int ret;
unsigned long flags;
/* Read out the chip version register */
data = reg_read(client, MT9V022_CHIP_VERSION);
/* must be 0x1311 or 0x1313 */
if (data != 0x1311 && data != 0x1313) {
ret = -ENODEV;
dev_info(&client->dev, "No MT9V022 found, ID register 0x%x\n",
data);
goto ei2c;
}
/* Soft reset */
ret = reg_write(client, MT9V022_RESET, 1);
if (ret < 0)
goto ei2c;
/* 15 clock cycles */
udelay(200);
if (reg_read(client, MT9V022_RESET)) {
dev_err(&client->dev, "Resetting MT9V022 failed!\n");
if (ret > 0)
ret = -EIO;
goto ei2c;
}
/* Set monochrome or colour sensor type */
if (sensor_type && (!strcmp("colour", sensor_type) ||
!strcmp("color", sensor_type))) {
ret = reg_write(client, MT9V022_PIXEL_OPERATION_MODE, 4 | 0x11);
mt9v022->model = V4L2_IDENT_MT9V022IX7ATC;
mt9v022->fmts = mt9v022_colour_fmts;
} else {
ret = reg_write(client, MT9V022_PIXEL_OPERATION_MODE, 0x11);
mt9v022->model = V4L2_IDENT_MT9V022IX7ATM;
mt9v022->fmts = mt9v022_monochrome_fmts;
}
if (ret < 0)
goto ei2c;
mt9v022->num_fmts = 0;
/*
* This is a 10bit sensor, so by default we only allow 10bit.
* The platform may support different bus widths due to
* different routing of the data lines.
*/
if (icl->query_bus_param)
flags = icl->query_bus_param(icl);
else
flags = SOCAM_DATAWIDTH_10;
if (flags & SOCAM_DATAWIDTH_10)
mt9v022->num_fmts++;
else
mt9v022->fmts++;
if (flags & SOCAM_DATAWIDTH_8)
mt9v022->num_fmts++;
mt9v022->fmt = &mt9v022->fmts[0];
dev_info(&client->dev, "Detected a MT9V022 chip ID %x, %s sensor\n",
data, mt9v022->model == V4L2_IDENT_MT9V022IX7ATM ?
"monochrome" : "colour");
ret = mt9v022_init(client);
if (ret < 0)
dev_err(&client->dev, "Failed to initialise the camera\n");
ei2c:
return ret;
}
static int mt9v022_g_skip_top_lines(struct v4l2_subdev *sd, u32 *lines)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
*lines = mt9v022->y_skip_top;
return 0;
}
static const struct v4l2_ctrl_ops mt9v022_ctrl_ops = {
.g_volatile_ctrl = mt9v022_g_volatile_ctrl,
.s_ctrl = mt9v022_s_ctrl,
};
static struct v4l2_subdev_core_ops mt9v022_subdev_core_ops = {
.g_chip_ident = mt9v022_g_chip_ident,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.g_register = mt9v022_g_register,
.s_register = mt9v022_s_register,
#endif
};
static int mt9v022_enum_fmt(struct v4l2_subdev *sd, unsigned int index,
enum v4l2_mbus_pixelcode *code)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct mt9v022 *mt9v022 = to_mt9v022(client);
if (index >= mt9v022->num_fmts)
return -EINVAL;
*code = mt9v022->fmts[index].code;
return 0;
}
static int mt9v022_g_mbus_config(struct v4l2_subdev *sd,
struct v4l2_mbus_config *cfg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
cfg->flags = V4L2_MBUS_MASTER | V4L2_MBUS_SLAVE |
V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_PCLK_SAMPLE_FALLING |
V4L2_MBUS_HSYNC_ACTIVE_HIGH | V4L2_MBUS_HSYNC_ACTIVE_LOW |
V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_VSYNC_ACTIVE_LOW |
V4L2_MBUS_DATA_ACTIVE_HIGH;
cfg->type = V4L2_MBUS_PARALLEL;
cfg->flags = soc_camera_apply_board_flags(icl, cfg);
return 0;
}
static int mt9v022_s_mbus_config(struct v4l2_subdev *sd,
const struct v4l2_mbus_config *cfg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
struct mt9v022 *mt9v022 = to_mt9v022(client);
unsigned long flags = soc_camera_apply_board_flags(icl, cfg);
unsigned int bps = soc_mbus_get_fmtdesc(mt9v022->fmt->code)->bits_per_sample;
int ret;
u16 pixclk = 0;
if (icl->set_bus_param) {
ret = icl->set_bus_param(icl, 1 << (bps - 1));
if (ret)
return ret;
} else if (bps != 10) {
/*
* Without board specific bus width settings we only support the
* sensors native bus width
*/
return -EINVAL;
}
if (flags & V4L2_MBUS_PCLK_SAMPLE_FALLING)
pixclk |= 0x10;
if (!(flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH))
pixclk |= 0x1;
if (!(flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH))
pixclk |= 0x2;
ret = reg_write(client, MT9V022_PIXCLK_FV_LV, pixclk);
if (ret < 0)
return ret;
if (!(flags & V4L2_MBUS_MASTER))
mt9v022->chip_control &= ~0x8;
ret = reg_write(client, MT9V022_CHIP_CONTROL, mt9v022->chip_control);
if (ret < 0)
return ret;
dev_dbg(&client->dev, "Calculated pixclk 0x%x, chip control 0x%x\n",
pixclk, mt9v022->chip_control);
return 0;
}
static struct v4l2_subdev_video_ops mt9v022_subdev_video_ops = {
.s_stream = mt9v022_s_stream,
.s_mbus_fmt = mt9v022_s_fmt,
.g_mbus_fmt = mt9v022_g_fmt,
.try_mbus_fmt = mt9v022_try_fmt,
.s_crop = mt9v022_s_crop,
.g_crop = mt9v022_g_crop,
.cropcap = mt9v022_cropcap,
.enum_mbus_fmt = mt9v022_enum_fmt,
.g_mbus_config = mt9v022_g_mbus_config,
.s_mbus_config = mt9v022_s_mbus_config,
};
static struct v4l2_subdev_sensor_ops mt9v022_subdev_sensor_ops = {
.g_skip_top_lines = mt9v022_g_skip_top_lines,
};
static struct v4l2_subdev_ops mt9v022_subdev_ops = {
.core = &mt9v022_subdev_core_ops,
.video = &mt9v022_subdev_video_ops,
.sensor = &mt9v022_subdev_sensor_ops,
};
static int mt9v022_probe(struct i2c_client *client,
const struct i2c_device_id *did)
{
struct mt9v022 *mt9v022;
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
int ret;
if (!icl) {
dev_err(&client->dev, "MT9V022 driver needs platform data\n");
return -EINVAL;
}
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA)) {
dev_warn(&adapter->dev,
"I2C-Adapter doesn't support I2C_FUNC_SMBUS_WORD\n");
return -EIO;
}
mt9v022 = kzalloc(sizeof(struct mt9v022), GFP_KERNEL);
if (!mt9v022)
return -ENOMEM;
v4l2_i2c_subdev_init(&mt9v022->subdev, client, &mt9v022_subdev_ops);
v4l2_ctrl_handler_init(&mt9v022->hdl, 6);
v4l2_ctrl_new_std(&mt9v022->hdl, &mt9v022_ctrl_ops,
V4L2_CID_VFLIP, 0, 1, 1, 0);
v4l2_ctrl_new_std(&mt9v022->hdl, &mt9v022_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
mt9v022->autogain = v4l2_ctrl_new_std(&mt9v022->hdl, &mt9v022_ctrl_ops,
V4L2_CID_AUTOGAIN, 0, 1, 1, 1);
mt9v022->gain = v4l2_ctrl_new_std(&mt9v022->hdl, &mt9v022_ctrl_ops,
V4L2_CID_GAIN, 0, 127, 1, 64);
/*
* Simulated autoexposure. If enabled, we calculate shutter width
* ourselves in the driver based on vertical blanking and frame width
*/
mt9v022->autoexposure = v4l2_ctrl_new_std_menu(&mt9v022->hdl,
&mt9v022_ctrl_ops, V4L2_CID_EXPOSURE_AUTO, 1, 0,
V4L2_EXPOSURE_AUTO);
mt9v022->exposure = v4l2_ctrl_new_std(&mt9v022->hdl, &mt9v022_ctrl_ops,
V4L2_CID_EXPOSURE, 1, 255, 1, 255);
mt9v022->subdev.ctrl_handler = &mt9v022->hdl;
if (mt9v022->hdl.error) {
int err = mt9v022->hdl.error;
kfree(mt9v022);
return err;
}
v4l2_ctrl_auto_cluster(2, &mt9v022->autoexposure,
V4L2_EXPOSURE_MANUAL, true);
v4l2_ctrl_auto_cluster(2, &mt9v022->autogain, 0, true);
mt9v022->chip_control = MT9V022_CHIP_CONTROL_DEFAULT;
/*
* MT9V022 _really_ corrupts the first read out line.
* TODO: verify on i.MX31
*/
mt9v022->y_skip_top = 1;
mt9v022->rect.left = MT9V022_COLUMN_SKIP;
mt9v022->rect.top = MT9V022_ROW_SKIP;
mt9v022->rect.width = MT9V022_MAX_WIDTH;
mt9v022->rect.height = MT9V022_MAX_HEIGHT;
ret = mt9v022_video_probe(client);
if (ret) {
v4l2_ctrl_handler_free(&mt9v022->hdl);
kfree(mt9v022);
}
return ret;
}
static int mt9v022_remove(struct i2c_client *client)
{
struct mt9v022 *mt9v022 = to_mt9v022(client);
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
v4l2_device_unregister_subdev(&mt9v022->subdev);
if (icl->free_bus)
icl->free_bus(icl);
v4l2_ctrl_handler_free(&mt9v022->hdl);
kfree(mt9v022);
return 0;
}
static const struct i2c_device_id mt9v022_id[] = {
{ "mt9v022", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, mt9v022_id);
static struct i2c_driver mt9v022_i2c_driver = {
.driver = {
.name = "mt9v022",
},
.probe = mt9v022_probe,
.remove = mt9v022_remove,
.id_table = mt9v022_id,
};
module_i2c_driver(mt9v022_i2c_driver);
MODULE_DESCRIPTION("Micron MT9V022 Camera driver");
MODULE_AUTHOR("Guennadi Liakhovetski <kernel@pengutronix.de>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
miuihu/android_kernel_xiaomi_redmi2 | crypto/af_alg.c | 6399 | 9492 | /*
* af_alg: User-space algorithm interface
*
* This file provides the user-space API for algorithms.
*
* 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 <linux/atomic.h>
#include <crypto/if_alg.h>
#include <linux/crypto.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/net.h>
#include <linux/rwsem.h>
struct alg_type_list {
const struct af_alg_type *type;
struct list_head list;
};
static atomic_long_t alg_memory_allocated;
static struct proto alg_proto = {
.name = "ALG",
.owner = THIS_MODULE,
.memory_allocated = &alg_memory_allocated,
.obj_size = sizeof(struct alg_sock),
};
static LIST_HEAD(alg_types);
static DECLARE_RWSEM(alg_types_sem);
static const struct af_alg_type *alg_get_type(const char *name)
{
const struct af_alg_type *type = ERR_PTR(-ENOENT);
struct alg_type_list *node;
down_read(&alg_types_sem);
list_for_each_entry(node, &alg_types, list) {
if (strcmp(node->type->name, name))
continue;
if (try_module_get(node->type->owner))
type = node->type;
break;
}
up_read(&alg_types_sem);
return type;
}
int af_alg_register_type(const struct af_alg_type *type)
{
struct alg_type_list *node;
int err = -EEXIST;
down_write(&alg_types_sem);
list_for_each_entry(node, &alg_types, list) {
if (!strcmp(node->type->name, type->name))
goto unlock;
}
node = kmalloc(sizeof(*node), GFP_KERNEL);
err = -ENOMEM;
if (!node)
goto unlock;
type->ops->owner = THIS_MODULE;
node->type = type;
list_add(&node->list, &alg_types);
err = 0;
unlock:
up_write(&alg_types_sem);
return err;
}
EXPORT_SYMBOL_GPL(af_alg_register_type);
int af_alg_unregister_type(const struct af_alg_type *type)
{
struct alg_type_list *node;
int err = -ENOENT;
down_write(&alg_types_sem);
list_for_each_entry(node, &alg_types, list) {
if (strcmp(node->type->name, type->name))
continue;
list_del(&node->list);
kfree(node);
err = 0;
break;
}
up_write(&alg_types_sem);
return err;
}
EXPORT_SYMBOL_GPL(af_alg_unregister_type);
static void alg_do_release(const struct af_alg_type *type, void *private)
{
if (!type)
return;
type->release(private);
module_put(type->owner);
}
int af_alg_release(struct socket *sock)
{
if (sock->sk)
sock_put(sock->sk);
return 0;
}
EXPORT_SYMBOL_GPL(af_alg_release);
static int alg_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct sockaddr_alg *sa = (void *)uaddr;
const struct af_alg_type *type;
void *private;
if (sock->state == SS_CONNECTED)
return -EINVAL;
if (addr_len != sizeof(*sa))
return -EINVAL;
sa->salg_type[sizeof(sa->salg_type) - 1] = 0;
sa->salg_name[sizeof(sa->salg_name) - 1] = 0;
type = alg_get_type(sa->salg_type);
if (IS_ERR(type) && PTR_ERR(type) == -ENOENT) {
request_module("algif-%s", sa->salg_type);
type = alg_get_type(sa->salg_type);
}
if (IS_ERR(type))
return PTR_ERR(type);
private = type->bind(sa->salg_name, sa->salg_feat, sa->salg_mask);
if (IS_ERR(private)) {
module_put(type->owner);
return PTR_ERR(private);
}
lock_sock(sk);
swap(ask->type, type);
swap(ask->private, private);
release_sock(sk);
alg_do_release(type, private);
return 0;
}
static int alg_setkey(struct sock *sk, char __user *ukey,
unsigned int keylen)
{
struct alg_sock *ask = alg_sk(sk);
const struct af_alg_type *type = ask->type;
u8 *key;
int err;
key = sock_kmalloc(sk, keylen, GFP_KERNEL);
if (!key)
return -ENOMEM;
err = -EFAULT;
if (copy_from_user(key, ukey, keylen))
goto out;
err = type->setkey(ask->private, key, keylen);
out:
sock_kfree_s(sk, key, keylen);
return err;
}
static int alg_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
const struct af_alg_type *type;
int err = -ENOPROTOOPT;
lock_sock(sk);
type = ask->type;
if (level != SOL_ALG || !type)
goto unlock;
switch (optname) {
case ALG_SET_KEY:
if (sock->state == SS_CONNECTED)
goto unlock;
if (!type->setkey)
goto unlock;
err = alg_setkey(sk, optval, optlen);
}
unlock:
release_sock(sk);
return err;
}
int af_alg_accept(struct sock *sk, struct socket *newsock)
{
struct alg_sock *ask = alg_sk(sk);
const struct af_alg_type *type;
struct sock *sk2;
int err;
lock_sock(sk);
type = ask->type;
err = -EINVAL;
if (!type)
goto unlock;
sk2 = sk_alloc(sock_net(sk), PF_ALG, GFP_KERNEL, &alg_proto);
err = -ENOMEM;
if (!sk2)
goto unlock;
sock_init_data(newsock, sk2);
sock_graft(sk2, newsock);
err = type->accept(ask->private, sk2);
if (err) {
sk_free(sk2);
goto unlock;
}
sk2->sk_family = PF_ALG;
sock_hold(sk);
alg_sk(sk2)->parent = sk;
alg_sk(sk2)->type = type;
newsock->ops = type->ops;
newsock->state = SS_CONNECTED;
err = 0;
unlock:
release_sock(sk);
return err;
}
EXPORT_SYMBOL_GPL(af_alg_accept);
static int alg_accept(struct socket *sock, struct socket *newsock, int flags)
{
return af_alg_accept(sock->sk, newsock);
}
static const struct proto_ops alg_proto_ops = {
.family = PF_ALG,
.owner = THIS_MODULE,
.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,
.sendpage = sock_no_sendpage,
.sendmsg = sock_no_sendmsg,
.recvmsg = sock_no_recvmsg,
.poll = sock_no_poll,
.bind = alg_bind,
.release = af_alg_release,
.setsockopt = alg_setsockopt,
.accept = alg_accept,
};
static void alg_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
alg_do_release(ask->type, ask->private);
}
static int alg_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
int err;
if (sock->type != SOCK_SEQPACKET)
return -ESOCKTNOSUPPORT;
if (protocol != 0)
return -EPROTONOSUPPORT;
err = -ENOMEM;
sk = sk_alloc(net, PF_ALG, GFP_KERNEL, &alg_proto);
if (!sk)
goto out;
sock->ops = &alg_proto_ops;
sock_init_data(sock, sk);
sk->sk_family = PF_ALG;
sk->sk_destruct = alg_sock_destruct;
return 0;
out:
return err;
}
static const struct net_proto_family alg_family = {
.family = PF_ALG,
.create = alg_create,
.owner = THIS_MODULE,
};
int af_alg_make_sg(struct af_alg_sgl *sgl, void __user *addr, int len,
int write)
{
unsigned long from = (unsigned long)addr;
unsigned long npages;
unsigned off;
int err;
int i;
err = -EFAULT;
if (!access_ok(write ? VERIFY_READ : VERIFY_WRITE, addr, len))
goto out;
off = from & ~PAGE_MASK;
npages = (off + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
if (npages > ALG_MAX_PAGES)
npages = ALG_MAX_PAGES;
err = get_user_pages_fast(from, npages, write, sgl->pages);
if (err < 0)
goto out;
npages = err;
err = -EINVAL;
if (WARN_ON(npages == 0))
goto out;
err = 0;
sg_init_table(sgl->sg, npages);
for (i = 0; i < npages; i++) {
int plen = min_t(int, len, PAGE_SIZE - off);
sg_set_page(sgl->sg + i, sgl->pages[i], plen, off);
off = 0;
len -= plen;
err += plen;
}
out:
return err;
}
EXPORT_SYMBOL_GPL(af_alg_make_sg);
void af_alg_free_sg(struct af_alg_sgl *sgl)
{
int i;
i = 0;
do {
put_page(sgl->pages[i]);
} while (!sg_is_last(sgl->sg + (i++)));
}
EXPORT_SYMBOL_GPL(af_alg_free_sg);
int af_alg_cmsg_send(struct msghdr *msg, struct af_alg_control *con)
{
struct cmsghdr *cmsg;
for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
if (!CMSG_OK(msg, cmsg))
return -EINVAL;
if (cmsg->cmsg_level != SOL_ALG)
continue;
switch(cmsg->cmsg_type) {
case ALG_SET_IV:
if (cmsg->cmsg_len < CMSG_LEN(sizeof(*con->iv)))
return -EINVAL;
con->iv = (void *)CMSG_DATA(cmsg);
if (cmsg->cmsg_len < CMSG_LEN(con->iv->ivlen +
sizeof(*con->iv)))
return -EINVAL;
break;
case ALG_SET_OP:
if (cmsg->cmsg_len < CMSG_LEN(sizeof(u32)))
return -EINVAL;
con->op = *(u32 *)CMSG_DATA(cmsg);
break;
default:
return -EINVAL;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(af_alg_cmsg_send);
int af_alg_wait_for_completion(int err, struct af_alg_completion *completion)
{
switch (err) {
case -EINPROGRESS:
case -EBUSY:
wait_for_completion(&completion->completion);
INIT_COMPLETION(completion->completion);
err = completion->err;
break;
};
return err;
}
EXPORT_SYMBOL_GPL(af_alg_wait_for_completion);
void af_alg_complete(struct crypto_async_request *req, int err)
{
struct af_alg_completion *completion = req->data;
completion->err = err;
complete(&completion->completion);
}
EXPORT_SYMBOL_GPL(af_alg_complete);
static int __init af_alg_init(void)
{
int err = proto_register(&alg_proto, 0);
if (err)
goto out;
err = sock_register(&alg_family);
if (err != 0)
goto out_unregister_proto;
out:
return err;
out_unregister_proto:
proto_unregister(&alg_proto);
goto out;
}
static void __exit af_alg_exit(void)
{
sock_unregister(PF_ALG);
proto_unregister(&alg_proto);
}
module_init(af_alg_init);
module_exit(af_alg_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(AF_ALG);
| gpl-2.0 |
TeamExodus/kernel_xiaomi_cancro | crypto/af_alg.c | 6399 | 9492 | /*
* af_alg: User-space algorithm interface
*
* This file provides the user-space API for algorithms.
*
* 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 <linux/atomic.h>
#include <crypto/if_alg.h>
#include <linux/crypto.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/net.h>
#include <linux/rwsem.h>
struct alg_type_list {
const struct af_alg_type *type;
struct list_head list;
};
static atomic_long_t alg_memory_allocated;
static struct proto alg_proto = {
.name = "ALG",
.owner = THIS_MODULE,
.memory_allocated = &alg_memory_allocated,
.obj_size = sizeof(struct alg_sock),
};
static LIST_HEAD(alg_types);
static DECLARE_RWSEM(alg_types_sem);
static const struct af_alg_type *alg_get_type(const char *name)
{
const struct af_alg_type *type = ERR_PTR(-ENOENT);
struct alg_type_list *node;
down_read(&alg_types_sem);
list_for_each_entry(node, &alg_types, list) {
if (strcmp(node->type->name, name))
continue;
if (try_module_get(node->type->owner))
type = node->type;
break;
}
up_read(&alg_types_sem);
return type;
}
int af_alg_register_type(const struct af_alg_type *type)
{
struct alg_type_list *node;
int err = -EEXIST;
down_write(&alg_types_sem);
list_for_each_entry(node, &alg_types, list) {
if (!strcmp(node->type->name, type->name))
goto unlock;
}
node = kmalloc(sizeof(*node), GFP_KERNEL);
err = -ENOMEM;
if (!node)
goto unlock;
type->ops->owner = THIS_MODULE;
node->type = type;
list_add(&node->list, &alg_types);
err = 0;
unlock:
up_write(&alg_types_sem);
return err;
}
EXPORT_SYMBOL_GPL(af_alg_register_type);
int af_alg_unregister_type(const struct af_alg_type *type)
{
struct alg_type_list *node;
int err = -ENOENT;
down_write(&alg_types_sem);
list_for_each_entry(node, &alg_types, list) {
if (strcmp(node->type->name, type->name))
continue;
list_del(&node->list);
kfree(node);
err = 0;
break;
}
up_write(&alg_types_sem);
return err;
}
EXPORT_SYMBOL_GPL(af_alg_unregister_type);
static void alg_do_release(const struct af_alg_type *type, void *private)
{
if (!type)
return;
type->release(private);
module_put(type->owner);
}
int af_alg_release(struct socket *sock)
{
if (sock->sk)
sock_put(sock->sk);
return 0;
}
EXPORT_SYMBOL_GPL(af_alg_release);
static int alg_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct sockaddr_alg *sa = (void *)uaddr;
const struct af_alg_type *type;
void *private;
if (sock->state == SS_CONNECTED)
return -EINVAL;
if (addr_len != sizeof(*sa))
return -EINVAL;
sa->salg_type[sizeof(sa->salg_type) - 1] = 0;
sa->salg_name[sizeof(sa->salg_name) - 1] = 0;
type = alg_get_type(sa->salg_type);
if (IS_ERR(type) && PTR_ERR(type) == -ENOENT) {
request_module("algif-%s", sa->salg_type);
type = alg_get_type(sa->salg_type);
}
if (IS_ERR(type))
return PTR_ERR(type);
private = type->bind(sa->salg_name, sa->salg_feat, sa->salg_mask);
if (IS_ERR(private)) {
module_put(type->owner);
return PTR_ERR(private);
}
lock_sock(sk);
swap(ask->type, type);
swap(ask->private, private);
release_sock(sk);
alg_do_release(type, private);
return 0;
}
static int alg_setkey(struct sock *sk, char __user *ukey,
unsigned int keylen)
{
struct alg_sock *ask = alg_sk(sk);
const struct af_alg_type *type = ask->type;
u8 *key;
int err;
key = sock_kmalloc(sk, keylen, GFP_KERNEL);
if (!key)
return -ENOMEM;
err = -EFAULT;
if (copy_from_user(key, ukey, keylen))
goto out;
err = type->setkey(ask->private, key, keylen);
out:
sock_kfree_s(sk, key, keylen);
return err;
}
static int alg_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
const struct af_alg_type *type;
int err = -ENOPROTOOPT;
lock_sock(sk);
type = ask->type;
if (level != SOL_ALG || !type)
goto unlock;
switch (optname) {
case ALG_SET_KEY:
if (sock->state == SS_CONNECTED)
goto unlock;
if (!type->setkey)
goto unlock;
err = alg_setkey(sk, optval, optlen);
}
unlock:
release_sock(sk);
return err;
}
int af_alg_accept(struct sock *sk, struct socket *newsock)
{
struct alg_sock *ask = alg_sk(sk);
const struct af_alg_type *type;
struct sock *sk2;
int err;
lock_sock(sk);
type = ask->type;
err = -EINVAL;
if (!type)
goto unlock;
sk2 = sk_alloc(sock_net(sk), PF_ALG, GFP_KERNEL, &alg_proto);
err = -ENOMEM;
if (!sk2)
goto unlock;
sock_init_data(newsock, sk2);
sock_graft(sk2, newsock);
err = type->accept(ask->private, sk2);
if (err) {
sk_free(sk2);
goto unlock;
}
sk2->sk_family = PF_ALG;
sock_hold(sk);
alg_sk(sk2)->parent = sk;
alg_sk(sk2)->type = type;
newsock->ops = type->ops;
newsock->state = SS_CONNECTED;
err = 0;
unlock:
release_sock(sk);
return err;
}
EXPORT_SYMBOL_GPL(af_alg_accept);
static int alg_accept(struct socket *sock, struct socket *newsock, int flags)
{
return af_alg_accept(sock->sk, newsock);
}
static const struct proto_ops alg_proto_ops = {
.family = PF_ALG,
.owner = THIS_MODULE,
.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,
.sendpage = sock_no_sendpage,
.sendmsg = sock_no_sendmsg,
.recvmsg = sock_no_recvmsg,
.poll = sock_no_poll,
.bind = alg_bind,
.release = af_alg_release,
.setsockopt = alg_setsockopt,
.accept = alg_accept,
};
static void alg_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
alg_do_release(ask->type, ask->private);
}
static int alg_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
int err;
if (sock->type != SOCK_SEQPACKET)
return -ESOCKTNOSUPPORT;
if (protocol != 0)
return -EPROTONOSUPPORT;
err = -ENOMEM;
sk = sk_alloc(net, PF_ALG, GFP_KERNEL, &alg_proto);
if (!sk)
goto out;
sock->ops = &alg_proto_ops;
sock_init_data(sock, sk);
sk->sk_family = PF_ALG;
sk->sk_destruct = alg_sock_destruct;
return 0;
out:
return err;
}
static const struct net_proto_family alg_family = {
.family = PF_ALG,
.create = alg_create,
.owner = THIS_MODULE,
};
int af_alg_make_sg(struct af_alg_sgl *sgl, void __user *addr, int len,
int write)
{
unsigned long from = (unsigned long)addr;
unsigned long npages;
unsigned off;
int err;
int i;
err = -EFAULT;
if (!access_ok(write ? VERIFY_READ : VERIFY_WRITE, addr, len))
goto out;
off = from & ~PAGE_MASK;
npages = (off + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
if (npages > ALG_MAX_PAGES)
npages = ALG_MAX_PAGES;
err = get_user_pages_fast(from, npages, write, sgl->pages);
if (err < 0)
goto out;
npages = err;
err = -EINVAL;
if (WARN_ON(npages == 0))
goto out;
err = 0;
sg_init_table(sgl->sg, npages);
for (i = 0; i < npages; i++) {
int plen = min_t(int, len, PAGE_SIZE - off);
sg_set_page(sgl->sg + i, sgl->pages[i], plen, off);
off = 0;
len -= plen;
err += plen;
}
out:
return err;
}
EXPORT_SYMBOL_GPL(af_alg_make_sg);
void af_alg_free_sg(struct af_alg_sgl *sgl)
{
int i;
i = 0;
do {
put_page(sgl->pages[i]);
} while (!sg_is_last(sgl->sg + (i++)));
}
EXPORT_SYMBOL_GPL(af_alg_free_sg);
int af_alg_cmsg_send(struct msghdr *msg, struct af_alg_control *con)
{
struct cmsghdr *cmsg;
for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
if (!CMSG_OK(msg, cmsg))
return -EINVAL;
if (cmsg->cmsg_level != SOL_ALG)
continue;
switch(cmsg->cmsg_type) {
case ALG_SET_IV:
if (cmsg->cmsg_len < CMSG_LEN(sizeof(*con->iv)))
return -EINVAL;
con->iv = (void *)CMSG_DATA(cmsg);
if (cmsg->cmsg_len < CMSG_LEN(con->iv->ivlen +
sizeof(*con->iv)))
return -EINVAL;
break;
case ALG_SET_OP:
if (cmsg->cmsg_len < CMSG_LEN(sizeof(u32)))
return -EINVAL;
con->op = *(u32 *)CMSG_DATA(cmsg);
break;
default:
return -EINVAL;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(af_alg_cmsg_send);
int af_alg_wait_for_completion(int err, struct af_alg_completion *completion)
{
switch (err) {
case -EINPROGRESS:
case -EBUSY:
wait_for_completion(&completion->completion);
INIT_COMPLETION(completion->completion);
err = completion->err;
break;
};
return err;
}
EXPORT_SYMBOL_GPL(af_alg_wait_for_completion);
void af_alg_complete(struct crypto_async_request *req, int err)
{
struct af_alg_completion *completion = req->data;
completion->err = err;
complete(&completion->completion);
}
EXPORT_SYMBOL_GPL(af_alg_complete);
static int __init af_alg_init(void)
{
int err = proto_register(&alg_proto, 0);
if (err)
goto out;
err = sock_register(&alg_family);
if (err != 0)
goto out_unregister_proto;
out:
return err;
out_unregister_proto:
proto_unregister(&alg_proto);
goto out;
}
static void __exit af_alg_exit(void)
{
sock_unregister(PF_ALG);
proto_unregister(&alg_proto);
}
module_init(af_alg_init);
module_exit(af_alg_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(AF_ALG);
| gpl-2.0 |
mdmower/android_kernel_htc_msm8960 | drivers/video/modedb.c | 7167 | 33300 | /*
* linux/drivers/video/modedb.c -- Standard video mode database management
*
* Copyright (C) 1999 Geert Uytterhoeven
*
* 2001 - Documented with DocBook
* - Brad Douglas <brad@neruo.com>
*
* 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/slab.h>
#include <linux/fb.h>
#include <linux/kernel.h>
#undef DEBUG
#define name_matches(v, s, l) \
((v).name && !strncmp((s), (v).name, (l)) && strlen((v).name) == (l))
#define res_matches(v, x, y) \
((v).xres == (x) && (v).yres == (y))
#ifdef DEBUG
#define DPRINTK(fmt, args...) printk("modedb %s: " fmt, __func__ , ## args)
#else
#define DPRINTK(fmt, args...)
#endif
const char *fb_mode_option;
EXPORT_SYMBOL_GPL(fb_mode_option);
/*
* Standard video mode definitions (taken from XFree86)
*/
static const struct fb_videomode modedb[] = {
/* 640x400 @ 70 Hz, 31.5 kHz hsync */
{ NULL, 70, 640, 400, 39721, 40, 24, 39, 9, 96, 2, 0,
FB_VMODE_NONINTERLACED },
/* 640x480 @ 60 Hz, 31.5 kHz hsync */
{ NULL, 60, 640, 480, 39721, 40, 24, 32, 11, 96, 2, 0,
FB_VMODE_NONINTERLACED },
/* 800x600 @ 56 Hz, 35.15 kHz hsync */
{ NULL, 56, 800, 600, 27777, 128, 24, 22, 1, 72, 2, 0,
FB_VMODE_NONINTERLACED },
/* 1024x768 @ 87 Hz interlaced, 35.5 kHz hsync */
{ NULL, 87, 1024, 768, 22271, 56, 24, 33, 8, 160, 8, 0,
FB_VMODE_INTERLACED },
/* 640x400 @ 85 Hz, 37.86 kHz hsync */
{ NULL, 85, 640, 400, 31746, 96, 32, 41, 1, 64, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED },
/* 640x480 @ 72 Hz, 36.5 kHz hsync */
{ NULL, 72, 640, 480, 31746, 144, 40, 30, 8, 40, 3, 0,
FB_VMODE_NONINTERLACED },
/* 640x480 @ 75 Hz, 37.50 kHz hsync */
{ NULL, 75, 640, 480, 31746, 120, 16, 16, 1, 64, 3, 0,
FB_VMODE_NONINTERLACED },
/* 800x600 @ 60 Hz, 37.8 kHz hsync */
{ NULL, 60, 800, 600, 25000, 88, 40, 23, 1, 128, 4,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 640x480 @ 85 Hz, 43.27 kHz hsync */
{ NULL, 85, 640, 480, 27777, 80, 56, 25, 1, 56, 3, 0,
FB_VMODE_NONINTERLACED },
/* 1152x864 @ 89 Hz interlaced, 44 kHz hsync */
{ NULL, 89, 1152, 864, 15384, 96, 16, 110, 1, 216, 10, 0,
FB_VMODE_INTERLACED },
/* 800x600 @ 72 Hz, 48.0 kHz hsync */
{ NULL, 72, 800, 600, 20000, 64, 56, 23, 37, 120, 6,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1024x768 @ 60 Hz, 48.4 kHz hsync */
{ NULL, 60, 1024, 768, 15384, 168, 8, 29, 3, 144, 6, 0,
FB_VMODE_NONINTERLACED },
/* 640x480 @ 100 Hz, 53.01 kHz hsync */
{ NULL, 100, 640, 480, 21834, 96, 32, 36, 8, 96, 6, 0,
FB_VMODE_NONINTERLACED },
/* 1152x864 @ 60 Hz, 53.5 kHz hsync */
{ NULL, 60, 1152, 864, 11123, 208, 64, 16, 4, 256, 8, 0,
FB_VMODE_NONINTERLACED },
/* 800x600 @ 85 Hz, 55.84 kHz hsync */
{ NULL, 85, 800, 600, 16460, 160, 64, 36, 16, 64, 5, 0,
FB_VMODE_NONINTERLACED },
/* 1024x768 @ 70 Hz, 56.5 kHz hsync */
{ NULL, 70, 1024, 768, 13333, 144, 24, 29, 3, 136, 6, 0,
FB_VMODE_NONINTERLACED },
/* 1280x1024 @ 87 Hz interlaced, 51 kHz hsync */
{ NULL, 87, 1280, 1024, 12500, 56, 16, 128, 1, 216, 12, 0,
FB_VMODE_INTERLACED },
/* 800x600 @ 100 Hz, 64.02 kHz hsync */
{ NULL, 100, 800, 600, 14357, 160, 64, 30, 4, 64, 6, 0,
FB_VMODE_NONINTERLACED },
/* 1024x768 @ 76 Hz, 62.5 kHz hsync */
{ NULL, 76, 1024, 768, 11764, 208, 8, 36, 16, 120, 3, 0,
FB_VMODE_NONINTERLACED },
/* 1152x864 @ 70 Hz, 62.4 kHz hsync */
{ NULL, 70, 1152, 864, 10869, 106, 56, 20, 1, 160, 10, 0,
FB_VMODE_NONINTERLACED },
/* 1280x1024 @ 61 Hz, 64.2 kHz hsync */
{ NULL, 61, 1280, 1024, 9090, 200, 48, 26, 1, 184, 3, 0,
FB_VMODE_NONINTERLACED },
/* 1400x1050 @ 60Hz, 63.9 kHz hsync */
{ NULL, 60, 1400, 1050, 9259, 136, 40, 13, 1, 112, 3, 0,
FB_VMODE_NONINTERLACED },
/* 1400x1050 @ 75,107 Hz, 82,392 kHz +hsync +vsync*/
{ NULL, 75, 1400, 1050, 7190, 120, 56, 23, 10, 112, 13,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1400x1050 @ 60 Hz, ? kHz +hsync +vsync*/
{ NULL, 60, 1400, 1050, 9259, 128, 40, 12, 0, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1024x768 @ 85 Hz, 70.24 kHz hsync */
{ NULL, 85, 1024, 768, 10111, 192, 32, 34, 14, 160, 6, 0,
FB_VMODE_NONINTERLACED },
/* 1152x864 @ 78 Hz, 70.8 kHz hsync */
{ NULL, 78, 1152, 864, 9090, 228, 88, 32, 0, 84, 12, 0,
FB_VMODE_NONINTERLACED },
/* 1280x1024 @ 70 Hz, 74.59 kHz hsync */
{ NULL, 70, 1280, 1024, 7905, 224, 32, 28, 8, 160, 8, 0,
FB_VMODE_NONINTERLACED },
/* 1600x1200 @ 60Hz, 75.00 kHz hsync */
{ NULL, 60, 1600, 1200, 6172, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1152x864 @ 84 Hz, 76.0 kHz hsync */
{ NULL, 84, 1152, 864, 7407, 184, 312, 32, 0, 128, 12, 0,
FB_VMODE_NONINTERLACED },
/* 1280x1024 @ 74 Hz, 78.85 kHz hsync */
{ NULL, 74, 1280, 1024, 7407, 256, 32, 34, 3, 144, 3, 0,
FB_VMODE_NONINTERLACED },
/* 1024x768 @ 100Hz, 80.21 kHz hsync */
{ NULL, 100, 1024, 768, 8658, 192, 32, 21, 3, 192, 10, 0,
FB_VMODE_NONINTERLACED },
/* 1280x1024 @ 76 Hz, 81.13 kHz hsync */
{ NULL, 76, 1280, 1024, 7407, 248, 32, 34, 3, 104, 3, 0,
FB_VMODE_NONINTERLACED },
/* 1600x1200 @ 70 Hz, 87.50 kHz hsync */
{ NULL, 70, 1600, 1200, 5291, 304, 64, 46, 1, 192, 3, 0,
FB_VMODE_NONINTERLACED },
/* 1152x864 @ 100 Hz, 89.62 kHz hsync */
{ NULL, 100, 1152, 864, 7264, 224, 32, 17, 2, 128, 19, 0,
FB_VMODE_NONINTERLACED },
/* 1280x1024 @ 85 Hz, 91.15 kHz hsync */
{ NULL, 85, 1280, 1024, 6349, 224, 64, 44, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1600x1200 @ 75 Hz, 93.75 kHz hsync */
{ NULL, 75, 1600, 1200, 4938, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1680x1050 @ 60 Hz, 65.191 kHz hsync */
{ NULL, 60, 1680, 1050, 6848, 280, 104, 30, 3, 176, 6,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1600x1200 @ 85 Hz, 105.77 kHz hsync */
{ NULL, 85, 1600, 1200, 4545, 272, 16, 37, 4, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1280x1024 @ 100 Hz, 107.16 kHz hsync */
{ NULL, 100, 1280, 1024, 5502, 256, 32, 26, 7, 128, 15, 0,
FB_VMODE_NONINTERLACED },
/* 1800x1440 @ 64Hz, 96.15 kHz hsync */
{ NULL, 64, 1800, 1440, 4347, 304, 96, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1800x1440 @ 70Hz, 104.52 kHz hsync */
{ NULL, 70, 1800, 1440, 4000, 304, 96, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 512x384 @ 78 Hz, 31.50 kHz hsync */
{ NULL, 78, 512, 384, 49603, 48, 16, 16, 1, 64, 3, 0,
FB_VMODE_NONINTERLACED },
/* 512x384 @ 85 Hz, 34.38 kHz hsync */
{ NULL, 85, 512, 384, 45454, 48, 16, 16, 1, 64, 3, 0,
FB_VMODE_NONINTERLACED },
/* 320x200 @ 70 Hz, 31.5 kHz hsync, 8:5 aspect ratio */
{ NULL, 70, 320, 200, 79440, 16, 16, 20, 4, 48, 1, 0,
FB_VMODE_DOUBLE },
/* 320x240 @ 60 Hz, 31.5 kHz hsync, 4:3 aspect ratio */
{ NULL, 60, 320, 240, 79440, 16, 16, 16, 5, 48, 1, 0,
FB_VMODE_DOUBLE },
/* 320x240 @ 72 Hz, 36.5 kHz hsync */
{ NULL, 72, 320, 240, 63492, 16, 16, 16, 4, 48, 2, 0,
FB_VMODE_DOUBLE },
/* 400x300 @ 56 Hz, 35.2 kHz hsync, 4:3 aspect ratio */
{ NULL, 56, 400, 300, 55555, 64, 16, 10, 1, 32, 1, 0,
FB_VMODE_DOUBLE },
/* 400x300 @ 60 Hz, 37.8 kHz hsync */
{ NULL, 60, 400, 300, 50000, 48, 16, 11, 1, 64, 2, 0,
FB_VMODE_DOUBLE },
/* 400x300 @ 72 Hz, 48.0 kHz hsync */
{ NULL, 72, 400, 300, 40000, 32, 24, 11, 19, 64, 3, 0,
FB_VMODE_DOUBLE },
/* 480x300 @ 56 Hz, 35.2 kHz hsync, 8:5 aspect ratio */
{ NULL, 56, 480, 300, 46176, 80, 16, 10, 1, 40, 1, 0,
FB_VMODE_DOUBLE },
/* 480x300 @ 60 Hz, 37.8 kHz hsync */
{ NULL, 60, 480, 300, 41858, 56, 16, 11, 1, 80, 2, 0,
FB_VMODE_DOUBLE },
/* 480x300 @ 63 Hz, 39.6 kHz hsync */
{ NULL, 63, 480, 300, 40000, 56, 16, 11, 1, 80, 2, 0,
FB_VMODE_DOUBLE },
/* 480x300 @ 72 Hz, 48.0 kHz hsync */
{ NULL, 72, 480, 300, 33386, 40, 24, 11, 19, 80, 3, 0,
FB_VMODE_DOUBLE },
/* 1920x1200 @ 60 Hz, 74.5 Khz hsync */
{ NULL, 60, 1920, 1200, 5177, 128, 336, 1, 38, 208, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1152x768, 60 Hz, PowerBook G4 Titanium I and II */
{ NULL, 60, 1152, 768, 14047, 158, 26, 29, 3, 136, 6,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED },
/* 1366x768, 60 Hz, 47.403 kHz hsync, WXGA 16:9 aspect ratio */
{ NULL, 60, 1366, 768, 13806, 120, 10, 14, 3, 32, 5, 0,
FB_VMODE_NONINTERLACED },
/* 1280x800, 60 Hz, 47.403 kHz hsync, WXGA 16:10 aspect ratio */
{ NULL, 60, 1280, 800, 12048, 200, 64, 24, 1, 136, 3, 0,
FB_VMODE_NONINTERLACED },
/* 720x576i @ 50 Hz, 15.625 kHz hsync (PAL RGB) */
{ NULL, 50, 720, 576, 74074, 64, 16, 39, 5, 64, 5, 0,
FB_VMODE_INTERLACED },
/* 800x520i @ 50 Hz, 15.625 kHz hsync (PAL RGB) */
{ NULL, 50, 800, 520, 58823, 144, 64, 72, 28, 80, 5, 0,
FB_VMODE_INTERLACED },
/* 864x480 @ 60 Hz, 35.15 kHz hsync */
{ NULL, 60, 864, 480, 27777, 1, 1, 1, 1, 0, 0,
0, FB_VMODE_NONINTERLACED },
};
#ifdef CONFIG_FB_MODE_HELPERS
const struct fb_videomode cea_modes[64] = {
/* #1: 640x480p@59.94/60Hz */
[1] = {
NULL, 60, 640, 480, 39722, 48, 16, 33, 10, 96, 2, 0,
FB_VMODE_NONINTERLACED, 0,
},
/* #3: 720x480p@59.94/60Hz */
[3] = {
NULL, 60, 720, 480, 37037, 60, 16, 30, 9, 62, 6, 0,
FB_VMODE_NONINTERLACED, 0,
},
/* #5: 1920x1080i@59.94/60Hz */
[5] = {
NULL, 60, 1920, 1080, 13763, 148, 88, 15, 2, 44, 5,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_INTERLACED, 0,
},
/* #7: 720(1440)x480iH@59.94/60Hz */
[7] = {
NULL, 60, 1440, 480, 18554/*37108*/, 114, 38, 15, 4, 124, 3, 0,
FB_VMODE_INTERLACED, 0,
},
/* #9: 720(1440)x240pH@59.94/60Hz */
[9] = {
NULL, 60, 1440, 240, 18554, 114, 38, 16, 4, 124, 3, 0,
FB_VMODE_NONINTERLACED, 0,
},
/* #18: 720x576pH@50Hz */
[18] = {
NULL, 50, 720, 576, 37037, 68, 12, 39, 5, 64, 5, 0,
FB_VMODE_NONINTERLACED, 0,
},
/* #19: 1280x720p@50Hz */
[19] = {
NULL, 50, 1280, 720, 13468, 220, 440, 20, 5, 40, 5,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, 0,
},
/* #20: 1920x1080i@50Hz */
[20] = {
NULL, 50, 1920, 1080, 13480, 148, 528, 15, 5, 528, 5,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_INTERLACED, 0,
},
/* #32: 1920x1080p@23.98/24Hz */
[32] = {
NULL, 24, 1920, 1080, 13468, 148, 638, 36, 4, 44, 5,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, 0,
},
/* #35: (2880)x480p4x@59.94/60Hz */
[35] = {
NULL, 60, 2880, 480, 9250, 240, 64, 30, 9, 248, 6, 0,
FB_VMODE_NONINTERLACED, 0,
},
};
const struct fb_videomode vesa_modes[] = {
/* 0 640x350-85 VESA */
{ NULL, 85, 640, 350, 31746, 96, 32, 60, 32, 64, 3,
FB_SYNC_HOR_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA},
/* 1 640x400-85 VESA */
{ NULL, 85, 640, 400, 31746, 96, 32, 41, 01, 64, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 2 720x400-85 VESA */
{ NULL, 85, 721, 400, 28169, 108, 36, 42, 01, 72, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 3 640x480-60 VESA */
{ NULL, 60, 640, 480, 39682, 48, 16, 33, 10, 96, 2,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 4 640x480-72 VESA */
{ NULL, 72, 640, 480, 31746, 128, 24, 29, 9, 40, 2,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 5 640x480-75 VESA */
{ NULL, 75, 640, 480, 31746, 120, 16, 16, 01, 64, 3,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 6 640x480-85 VESA */
{ NULL, 85, 640, 480, 27777, 80, 56, 25, 01, 56, 3,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 7 800x600-56 VESA */
{ NULL, 56, 800, 600, 27777, 128, 24, 22, 01, 72, 2,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 8 800x600-60 VESA */
{ NULL, 60, 800, 600, 25000, 88, 40, 23, 01, 128, 4,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 9 800x600-72 VESA */
{ NULL, 72, 800, 600, 20000, 64, 56, 23, 37, 120, 6,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 10 800x600-75 VESA */
{ NULL, 75, 800, 600, 20202, 160, 16, 21, 01, 80, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 11 800x600-85 VESA */
{ NULL, 85, 800, 600, 17761, 152, 32, 27, 01, 64, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 12 1024x768i-43 VESA */
{ NULL, 43, 1024, 768, 22271, 56, 8, 41, 0, 176, 8,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_INTERLACED, FB_MODE_IS_VESA },
/* 13 1024x768-60 VESA */
{ NULL, 60, 1024, 768, 15384, 160, 24, 29, 3, 136, 6,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 14 1024x768-70 VESA */
{ NULL, 70, 1024, 768, 13333, 144, 24, 29, 3, 136, 6,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 15 1024x768-75 VESA */
{ NULL, 75, 1024, 768, 12690, 176, 16, 28, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 16 1024x768-85 VESA */
{ NULL, 85, 1024, 768, 10582, 208, 48, 36, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 17 1152x864-75 VESA */
{ NULL, 75, 1152, 864, 9259, 256, 64, 32, 1, 128, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 18 1280x960-60 VESA */
{ NULL, 60, 1280, 960, 9259, 312, 96, 36, 1, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 19 1280x960-85 VESA */
{ NULL, 85, 1280, 960, 6734, 224, 64, 47, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 20 1280x1024-60 VESA */
{ NULL, 60, 1280, 1024, 9259, 248, 48, 38, 1, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 21 1280x1024-75 VESA */
{ NULL, 75, 1280, 1024, 7407, 248, 16, 38, 1, 144, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 22 1280x1024-85 VESA */
{ NULL, 85, 1280, 1024, 6349, 224, 64, 44, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 23 1600x1200-60 VESA */
{ NULL, 60, 1600, 1200, 6172, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 24 1600x1200-65 VESA */
{ NULL, 65, 1600, 1200, 5698, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 25 1600x1200-70 VESA */
{ NULL, 70, 1600, 1200, 5291, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 26 1600x1200-75 VESA */
{ NULL, 75, 1600, 1200, 4938, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 27 1600x1200-85 VESA */
{ NULL, 85, 1600, 1200, 4357, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 28 1792x1344-60 VESA */
{ NULL, 60, 1792, 1344, 4882, 328, 128, 46, 1, 200, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 29 1792x1344-75 VESA */
{ NULL, 75, 1792, 1344, 3831, 352, 96, 69, 1, 216, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 30 1856x1392-60 VESA */
{ NULL, 60, 1856, 1392, 4580, 352, 96, 43, 1, 224, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 31 1856x1392-75 VESA */
{ NULL, 75, 1856, 1392, 3472, 352, 128, 104, 1, 224, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 32 1920x1440-60 VESA */
{ NULL, 60, 1920, 1440, 4273, 344, 128, 56, 1, 200, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 33 1920x1440-75 VESA */
{ NULL, 75, 1920, 1440, 3367, 352, 144, 56, 1, 224, 3,
FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
};
EXPORT_SYMBOL(vesa_modes);
#endif /* CONFIG_FB_MODE_HELPERS */
/**
* fb_try_mode - test a video mode
* @var: frame buffer user defined part of display
* @info: frame buffer info structure
* @mode: frame buffer video mode structure
* @bpp: color depth in bits per pixel
*
* Tries a video mode to test it's validity for device @info.
*
* Returns 1 on success.
*
*/
static int fb_try_mode(struct fb_var_screeninfo *var, struct fb_info *info,
const struct fb_videomode *mode, unsigned int bpp)
{
int err = 0;
DPRINTK("Trying mode %s %dx%d-%d@%d\n",
mode->name ? mode->name : "noname",
mode->xres, mode->yres, bpp, mode->refresh);
var->xres = mode->xres;
var->yres = mode->yres;
var->xres_virtual = mode->xres;
var->yres_virtual = mode->yres;
var->xoffset = 0;
var->yoffset = 0;
var->bits_per_pixel = bpp;
var->activate |= FB_ACTIVATE_TEST;
var->pixclock = mode->pixclock;
var->left_margin = mode->left_margin;
var->right_margin = mode->right_margin;
var->upper_margin = mode->upper_margin;
var->lower_margin = mode->lower_margin;
var->hsync_len = mode->hsync_len;
var->vsync_len = mode->vsync_len;
var->sync = mode->sync;
var->vmode = mode->vmode;
if (info->fbops->fb_check_var)
err = info->fbops->fb_check_var(var, info);
var->activate &= ~FB_ACTIVATE_TEST;
return err;
}
/**
* fb_find_mode - finds a valid video mode
* @var: frame buffer user defined part of display
* @info: frame buffer info structure
* @mode_option: string video mode to find
* @db: video mode database
* @dbsize: size of @db
* @default_mode: default video mode to fall back to
* @default_bpp: default color depth in bits per pixel
*
* Finds a suitable video mode, starting with the specified mode
* in @mode_option with fallback to @default_mode. If
* @default_mode fails, all modes in the video mode database will
* be tried.
*
* Valid mode specifiers for @mode_option:
*
* <xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m] or
* <name>[-<bpp>][@<refresh>]
*
* with <xres>, <yres>, <bpp> and <refresh> decimal numbers and
* <name> a string.
*
* If 'M' is present after yres (and before refresh/bpp if present),
* the function will compute the timings using VESA(tm) Coordinated
* Video Timings (CVT). If 'R' is present after 'M', will compute with
* reduced blanking (for flatpanels). If 'i' is present, compute
* interlaced mode. If 'm' is present, add margins equal to 1.8%
* of xres rounded down to 8 pixels, and 1.8% of yres. The char
* 'i' and 'm' must be after 'M' and 'R'. Example:
*
* 1024x768MR-8@60m - Reduced blank with margins at 60Hz.
*
* NOTE: The passed struct @var is _not_ cleared! This allows you
* to supply values for e.g. the grayscale and accel_flags fields.
*
* Returns zero for failure, 1 if using specified @mode_option,
* 2 if using specified @mode_option with an ignored refresh rate,
* 3 if default mode is used, 4 if fall back to any valid mode.
*
*/
int fb_find_mode(struct fb_var_screeninfo *var,
struct fb_info *info, const char *mode_option,
const struct fb_videomode *db, unsigned int dbsize,
const struct fb_videomode *default_mode,
unsigned int default_bpp)
{
int i;
/* Set up defaults */
if (!db) {
db = modedb;
dbsize = ARRAY_SIZE(modedb);
}
if (!default_mode)
default_mode = &db[0];
if (!default_bpp)
default_bpp = 8;
/* Did the user specify a video mode? */
if (!mode_option)
mode_option = fb_mode_option;
if (mode_option) {
const char *name = mode_option;
unsigned int namelen = strlen(name);
int res_specified = 0, bpp_specified = 0, refresh_specified = 0;
unsigned int xres = 0, yres = 0, bpp = default_bpp, refresh = 0;
int yres_specified = 0, cvt = 0, rb = 0, interlace = 0;
int margins = 0;
u32 best, diff, tdiff;
for (i = namelen-1; i >= 0; i--) {
switch (name[i]) {
case '@':
namelen = i;
if (!refresh_specified && !bpp_specified &&
!yres_specified) {
refresh = simple_strtol(&name[i+1], NULL,
10);
refresh_specified = 1;
if (cvt || rb)
cvt = 0;
} else
goto done;
break;
case '-':
namelen = i;
if (!bpp_specified && !yres_specified) {
bpp = simple_strtol(&name[i+1], NULL,
10);
bpp_specified = 1;
if (cvt || rb)
cvt = 0;
} else
goto done;
break;
case 'x':
if (!yres_specified) {
yres = simple_strtol(&name[i+1], NULL,
10);
yres_specified = 1;
} else
goto done;
break;
case '0' ... '9':
break;
case 'M':
if (!yres_specified)
cvt = 1;
break;
case 'R':
if (!cvt)
rb = 1;
break;
case 'm':
if (!cvt)
margins = 1;
break;
case 'i':
if (!cvt)
interlace = 1;
break;
default:
goto done;
}
}
if (i < 0 && yres_specified) {
xres = simple_strtol(name, NULL, 10);
res_specified = 1;
}
done:
if (cvt) {
struct fb_videomode cvt_mode;
int ret;
DPRINTK("CVT mode %dx%d@%dHz%s%s%s\n", xres, yres,
(refresh) ? refresh : 60,
(rb) ? " reduced blanking" : "",
(margins) ? " with margins" : "",
(interlace) ? " interlaced" : "");
memset(&cvt_mode, 0, sizeof(cvt_mode));
cvt_mode.xres = xres;
cvt_mode.yres = yres;
cvt_mode.refresh = (refresh) ? refresh : 60;
if (interlace)
cvt_mode.vmode |= FB_VMODE_INTERLACED;
else
cvt_mode.vmode &= ~FB_VMODE_INTERLACED;
ret = fb_find_mode_cvt(&cvt_mode, margins, rb);
if (!ret && !fb_try_mode(var, info, &cvt_mode, bpp)) {
DPRINTK("modedb CVT: CVT mode ok\n");
return 1;
}
DPRINTK("CVT mode invalid, getting mode from database\n");
}
DPRINTK("Trying specified video mode%s %ix%i\n",
refresh_specified ? "" : " (ignoring refresh rate)",
xres, yres);
if (!refresh_specified) {
/*
* If the caller has provided a custom mode database and
* a valid monspecs structure, we look for the mode with
* the highest refresh rate. Otherwise we play it safe
* it and try to find a mode with a refresh rate closest
* to the standard 60 Hz.
*/
if (db != modedb &&
info->monspecs.vfmin && info->monspecs.vfmax &&
info->monspecs.hfmin && info->monspecs.hfmax &&
info->monspecs.dclkmax) {
refresh = 1000;
} else {
refresh = 60;
}
}
diff = -1;
best = -1;
for (i = 0; i < dbsize; i++) {
if ((name_matches(db[i], name, namelen) ||
(res_specified && res_matches(db[i], xres, yres))) &&
!fb_try_mode(var, info, &db[i], bpp)) {
if (refresh_specified && db[i].refresh == refresh)
return 1;
if (abs(db[i].refresh - refresh) < diff) {
diff = abs(db[i].refresh - refresh);
best = i;
}
}
}
if (best != -1) {
fb_try_mode(var, info, &db[best], bpp);
return (refresh_specified) ? 2 : 1;
}
diff = 2 * (xres + yres);
best = -1;
DPRINTK("Trying best-fit modes\n");
for (i = 0; i < dbsize; i++) {
DPRINTK("Trying %ix%i\n", db[i].xres, db[i].yres);
if (!fb_try_mode(var, info, &db[i], bpp)) {
tdiff = abs(db[i].xres - xres) +
abs(db[i].yres - yres);
/*
* Penalize modes with resolutions smaller
* than requested.
*/
if (xres > db[i].xres || yres > db[i].yres)
tdiff += xres + yres;
if (diff > tdiff) {
diff = tdiff;
best = i;
}
}
}
if (best != -1) {
fb_try_mode(var, info, &db[best], bpp);
return 5;
}
}
DPRINTK("Trying default video mode\n");
if (!fb_try_mode(var, info, default_mode, default_bpp))
return 3;
DPRINTK("Trying all modes\n");
for (i = 0; i < dbsize; i++)
if (!fb_try_mode(var, info, &db[i], default_bpp))
return 4;
DPRINTK("No valid mode found\n");
return 0;
}
/**
* fb_var_to_videomode - convert fb_var_screeninfo to fb_videomode
* @mode: pointer to struct fb_videomode
* @var: pointer to struct fb_var_screeninfo
*/
void fb_var_to_videomode(struct fb_videomode *mode,
const struct fb_var_screeninfo *var)
{
u32 pixclock, hfreq, htotal, vtotal;
mode->name = NULL;
mode->xres = var->xres;
mode->yres = var->yres;
mode->pixclock = var->pixclock;
mode->hsync_len = var->hsync_len;
mode->vsync_len = var->vsync_len;
mode->left_margin = var->left_margin;
mode->right_margin = var->right_margin;
mode->upper_margin = var->upper_margin;
mode->lower_margin = var->lower_margin;
mode->sync = var->sync;
mode->vmode = var->vmode & FB_VMODE_MASK;
mode->flag = FB_MODE_IS_FROM_VAR;
mode->refresh = 0;
if (!var->pixclock)
return;
pixclock = PICOS2KHZ(var->pixclock) * 1000;
htotal = var->xres + var->right_margin + var->hsync_len +
var->left_margin;
vtotal = var->yres + var->lower_margin + var->vsync_len +
var->upper_margin;
if (var->vmode & FB_VMODE_INTERLACED)
vtotal /= 2;
if (var->vmode & FB_VMODE_DOUBLE)
vtotal *= 2;
hfreq = pixclock/htotal;
mode->refresh = hfreq/vtotal;
}
/**
* fb_videomode_to_var - convert fb_videomode to fb_var_screeninfo
* @var: pointer to struct fb_var_screeninfo
* @mode: pointer to struct fb_videomode
*/
void fb_videomode_to_var(struct fb_var_screeninfo *var,
const struct fb_videomode *mode)
{
var->xres = mode->xres;
var->yres = mode->yres;
var->xres_virtual = mode->xres;
var->yres_virtual = mode->yres;
var->xoffset = 0;
var->yoffset = 0;
var->pixclock = mode->pixclock;
var->left_margin = mode->left_margin;
var->right_margin = mode->right_margin;
var->upper_margin = mode->upper_margin;
var->lower_margin = mode->lower_margin;
var->hsync_len = mode->hsync_len;
var->vsync_len = mode->vsync_len;
var->sync = mode->sync;
var->vmode = mode->vmode & FB_VMODE_MASK;
}
/**
* fb_mode_is_equal - compare 2 videomodes
* @mode1: first videomode
* @mode2: second videomode
*
* RETURNS:
* 1 if equal, 0 if not
*/
int fb_mode_is_equal(const struct fb_videomode *mode1,
const struct fb_videomode *mode2)
{
return (mode1->xres == mode2->xres &&
mode1->yres == mode2->yres &&
mode1->pixclock == mode2->pixclock &&
mode1->hsync_len == mode2->hsync_len &&
mode1->vsync_len == mode2->vsync_len &&
mode1->left_margin == mode2->left_margin &&
mode1->right_margin == mode2->right_margin &&
mode1->upper_margin == mode2->upper_margin &&
mode1->lower_margin == mode2->lower_margin &&
mode1->sync == mode2->sync &&
mode1->vmode == mode2->vmode);
}
/**
* fb_find_best_mode - find best matching videomode
* @var: pointer to struct fb_var_screeninfo
* @head: pointer to struct list_head of modelist
*
* RETURNS:
* struct fb_videomode, NULL if none found
*
* IMPORTANT:
* This function assumes that all modelist entries in
* info->modelist are valid.
*
* NOTES:
* Finds best matching videomode which has an equal or greater dimension than
* var->xres and var->yres. If more than 1 videomode is found, will return
* the videomode with the highest refresh rate
*/
const struct fb_videomode *fb_find_best_mode(const struct fb_var_screeninfo *var,
struct list_head *head)
{
struct list_head *pos;
struct fb_modelist *modelist;
struct fb_videomode *mode, *best = NULL;
u32 diff = -1;
list_for_each(pos, head) {
u32 d;
modelist = list_entry(pos, struct fb_modelist, list);
mode = &modelist->mode;
if (mode->xres >= var->xres && mode->yres >= var->yres) {
d = (mode->xres - var->xres) +
(mode->yres - var->yres);
if (diff > d) {
diff = d;
best = mode;
} else if (diff == d && best &&
mode->refresh > best->refresh)
best = mode;
}
}
return best;
}
/**
* fb_find_nearest_mode - find closest videomode
*
* @mode: pointer to struct fb_videomode
* @head: pointer to modelist
*
* Finds best matching videomode, smaller or greater in dimension.
* If more than 1 videomode is found, will return the videomode with
* the closest refresh rate.
*/
const struct fb_videomode *fb_find_nearest_mode(const struct fb_videomode *mode,
struct list_head *head)
{
struct list_head *pos;
struct fb_modelist *modelist;
struct fb_videomode *cmode, *best = NULL;
u32 diff = -1, diff_refresh = -1;
list_for_each(pos, head) {
u32 d;
modelist = list_entry(pos, struct fb_modelist, list);
cmode = &modelist->mode;
d = abs(cmode->xres - mode->xres) +
abs(cmode->yres - mode->yres);
if (diff > d) {
diff = d;
diff_refresh = abs(cmode->refresh - mode->refresh);
best = cmode;
} else if (diff == d) {
d = abs(cmode->refresh - mode->refresh);
if (diff_refresh > d) {
diff_refresh = d;
best = cmode;
}
}
}
return best;
}
/**
* fb_match_mode - find a videomode which exactly matches the timings in var
* @var: pointer to struct fb_var_screeninfo
* @head: pointer to struct list_head of modelist
*
* RETURNS:
* struct fb_videomode, NULL if none found
*/
const struct fb_videomode *fb_match_mode(const struct fb_var_screeninfo *var,
struct list_head *head)
{
struct list_head *pos;
struct fb_modelist *modelist;
struct fb_videomode *m, mode;
fb_var_to_videomode(&mode, var);
list_for_each(pos, head) {
modelist = list_entry(pos, struct fb_modelist, list);
m = &modelist->mode;
if (fb_mode_is_equal(m, &mode))
return m;
}
return NULL;
}
/**
* fb_add_videomode - adds videomode entry to modelist
* @mode: videomode to add
* @head: struct list_head of modelist
*
* NOTES:
* Will only add unmatched mode entries
*/
int fb_add_videomode(const struct fb_videomode *mode, struct list_head *head)
{
struct list_head *pos;
struct fb_modelist *modelist;
struct fb_videomode *m;
int found = 0;
list_for_each(pos, head) {
modelist = list_entry(pos, struct fb_modelist, list);
m = &modelist->mode;
if (fb_mode_is_equal(m, mode)) {
found = 1;
break;
}
}
if (!found) {
modelist = kmalloc(sizeof(struct fb_modelist),
GFP_KERNEL);
if (!modelist)
return -ENOMEM;
modelist->mode = *mode;
list_add(&modelist->list, head);
}
return 0;
}
/**
* fb_delete_videomode - removed videomode entry from modelist
* @mode: videomode to remove
* @head: struct list_head of modelist
*
* NOTES:
* Will remove all matching mode entries
*/
void fb_delete_videomode(const struct fb_videomode *mode,
struct list_head *head)
{
struct list_head *pos, *n;
struct fb_modelist *modelist;
struct fb_videomode *m;
list_for_each_safe(pos, n, head) {
modelist = list_entry(pos, struct fb_modelist, list);
m = &modelist->mode;
if (fb_mode_is_equal(m, mode)) {
list_del(pos);
kfree(pos);
}
}
}
/**
* fb_destroy_modelist - destroy modelist
* @head: struct list_head of modelist
*/
void fb_destroy_modelist(struct list_head *head)
{
struct list_head *pos, *n;
list_for_each_safe(pos, n, head) {
list_del(pos);
kfree(pos);
}
}
EXPORT_SYMBOL_GPL(fb_destroy_modelist);
/**
* fb_videomode_to_modelist - convert mode array to mode list
* @modedb: array of struct fb_videomode
* @num: number of entries in array
* @head: struct list_head of modelist
*/
void fb_videomode_to_modelist(const struct fb_videomode *modedb, int num,
struct list_head *head)
{
int i;
INIT_LIST_HEAD(head);
for (i = 0; i < num; i++) {
if (fb_add_videomode(&modedb[i], head))
return;
}
}
const struct fb_videomode *fb_find_best_display(const struct fb_monspecs *specs,
struct list_head *head)
{
struct list_head *pos;
struct fb_modelist *modelist;
const struct fb_videomode *m, *m1 = NULL, *md = NULL, *best = NULL;
int first = 0;
if (!head->prev || !head->next || list_empty(head))
goto finished;
/* get the first detailed mode and the very first mode */
list_for_each(pos, head) {
modelist = list_entry(pos, struct fb_modelist, list);
m = &modelist->mode;
if (!first) {
m1 = m;
first = 1;
}
if (m->flag & FB_MODE_IS_FIRST) {
md = m;
break;
}
}
/* first detailed timing is preferred */
if (specs->misc & FB_MISC_1ST_DETAIL) {
best = md;
goto finished;
}
/* find best mode based on display width and height */
if (specs->max_x && specs->max_y) {
struct fb_var_screeninfo var;
memset(&var, 0, sizeof(struct fb_var_screeninfo));
var.xres = (specs->max_x * 7200)/254;
var.yres = (specs->max_y * 7200)/254;
m = fb_find_best_mode(&var, head);
if (m) {
best = m;
goto finished;
}
}
/* use first detailed mode */
if (md) {
best = md;
goto finished;
}
/* last resort, use the very first mode */
best = m1;
finished:
return best;
}
EXPORT_SYMBOL(fb_find_best_display);
EXPORT_SYMBOL(fb_videomode_to_var);
EXPORT_SYMBOL(fb_var_to_videomode);
EXPORT_SYMBOL(fb_mode_is_equal);
EXPORT_SYMBOL(fb_add_videomode);
EXPORT_SYMBOL(fb_match_mode);
EXPORT_SYMBOL(fb_find_best_mode);
EXPORT_SYMBOL(fb_find_nearest_mode);
EXPORT_SYMBOL(fb_videomode_to_modelist);
EXPORT_SYMBOL(fb_find_mode);
EXPORT_SYMBOL(fb_find_mode_cvt);
| gpl-2.0 |
davidmueller13/Vindicator-flo-aosp | arch/arm/mach-pxa/generic.c | 7679 | 2347 | /*
* linux/arch/arm/mach-pxa/generic.c
*
* Author: Nicolas Pitre
* Created: Jun 15, 2001
* Copyright: MontaVista Software Inc.
*
* Code common to all PXA machines.
*
* 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.
*
* Since this file should be linked before any other machine specific file,
* the __initcall() here will be executed first. This serves as default
* initialization stuff for PXA machines which can be overridden later if
* need be.
*/
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <mach/hardware.h>
#include <asm/mach/map.h>
#include <asm/mach-types.h>
#include <mach/reset.h>
#include <mach/smemc.h>
#include <mach/pxa3xx-regs.h>
#include "generic.h"
void clear_reset_status(unsigned int mask)
{
if (cpu_is_pxa2xx())
pxa2xx_clear_reset_status(mask);
else {
/* RESET_STATUS_* has a 1:1 mapping with ARSR */
ARSR = mask;
}
}
unsigned long get_clock_tick_rate(void)
{
unsigned long clock_tick_rate;
if (cpu_is_pxa25x())
clock_tick_rate = 3686400;
else if (machine_is_mainstone())
clock_tick_rate = 3249600;
else
clock_tick_rate = 3250000;
return clock_tick_rate;
}
EXPORT_SYMBOL(get_clock_tick_rate);
/*
* Get the clock frequency as reflected by CCCR and the turbo flag.
* We assume these values have been applied via a fcs.
* If info is not 0 we also display the current settings.
*/
unsigned int get_clk_frequency_khz(int info)
{
if (cpu_is_pxa25x())
return pxa25x_get_clk_frequency_khz(info);
else if (cpu_is_pxa27x())
return pxa27x_get_clk_frequency_khz(info);
return 0;
}
EXPORT_SYMBOL(get_clk_frequency_khz);
/*
* Intel PXA2xx internal register mapping.
*
* Note: virtual 0xfffe0000-0xffffffff is reserved for the vector table
* and cache flush area.
*/
static struct map_desc common_io_desc[] __initdata = {
{ /* Devs */
.virtual = 0xf2000000,
.pfn = __phys_to_pfn(0x40000000),
.length = 0x02000000,
.type = MT_DEVICE
}, { /* UNCACHED_PHYS_0 */
.virtual = 0xff000000,
.pfn = __phys_to_pfn(0x00000000),
.length = 0x00100000,
.type = MT_DEVICE
}
};
void __init pxa_map_io(void)
{
iotable_init(ARRAY_AND_SIZE(common_io_desc));
}
| gpl-2.0 |
Split-Screen/android_kernel_htc_msm8974 | arch/xtensa/mm/cache.c | 8703 | 6487 | /*
* arch/xtensa/mm/cache.c
*
* 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.
*
* Copyright (C) 2001-2006 Tensilica Inc.
*
* Chris Zankel <chris@zankel.net>
* Joe Taylor
* Marc Gauthier
*
*/
#include <linux/init.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/ptrace.h>
#include <linux/bootmem.h>
#include <linux/swap.h>
#include <linux/pagemap.h>
#include <asm/bootparam.h>
#include <asm/mmu_context.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
//#define printd(x...) printk(x)
#define printd(x...) do { } while(0)
/*
* Note:
* The kernel provides one architecture bit PG_arch_1 in the page flags that
* can be used for cache coherency.
*
* I$-D$ coherency.
*
* The Xtensa architecture doesn't keep the instruction cache coherent with
* the data cache. We use the architecture bit to indicate if the caches
* are coherent. The kernel clears this bit whenever a page is added to the
* page cache. At that time, the caches might not be in sync. We, therefore,
* define this flag as 'clean' if set.
*
* D-cache aliasing.
*
* With cache aliasing, we have to always flush the cache when pages are
* unmapped (see tlb_start_vma(). So, we use this flag to indicate a dirty
* page.
*
*
*
*/
#if (DCACHE_WAY_SIZE > PAGE_SIZE) && XCHAL_DCACHE_IS_WRITEBACK
/*
* Any time the kernel writes to a user page cache page, or it is about to
* read from a page cache page this routine is called.
*
*/
void flush_dcache_page(struct page *page)
{
struct address_space *mapping = page_mapping(page);
/*
* If we have a mapping but the page is not mapped to user-space
* yet, we simply mark this page dirty and defer flushing the
* caches until update_mmu().
*/
if (mapping && !mapping_mapped(mapping)) {
if (!test_bit(PG_arch_1, &page->flags))
set_bit(PG_arch_1, &page->flags);
return;
} else {
unsigned long phys = page_to_phys(page);
unsigned long temp = page->index << PAGE_SHIFT;
unsigned long alias = !(DCACHE_ALIAS_EQ(temp, phys));
unsigned long virt;
/*
* Flush the page in kernel space and user space.
* Note that we can omit that step if aliasing is not
* an issue, but we do have to synchronize I$ and D$
* if we have a mapping.
*/
if (!alias && !mapping)
return;
__flush_invalidate_dcache_page((long)page_address(page));
virt = TLBTEMP_BASE_1 + (temp & DCACHE_ALIAS_MASK);
if (alias)
__flush_invalidate_dcache_page_alias(virt, phys);
if (mapping)
__invalidate_icache_page_alias(virt, phys);
}
/* There shouldn't be an entry in the cache for this page anymore. */
}
/*
* For now, flush the whole cache. FIXME??
*/
void flush_cache_range(struct vm_area_struct* vma,
unsigned long start, unsigned long end)
{
__flush_invalidate_dcache_all();
__invalidate_icache_all();
}
/*
* Remove any entry in the cache for this page.
*
* Note that this function is only called for user pages, so use the
* alias versions of the cache flush functions.
*/
void flush_cache_page(struct vm_area_struct* vma, unsigned long address,
unsigned long pfn)
{
/* Note that we have to use the 'alias' address to avoid multi-hit */
unsigned long phys = page_to_phys(pfn_to_page(pfn));
unsigned long virt = TLBTEMP_BASE_1 + (address & DCACHE_ALIAS_MASK);
__flush_invalidate_dcache_page_alias(virt, phys);
__invalidate_icache_page_alias(virt, phys);
}
#endif
void
update_mmu_cache(struct vm_area_struct * vma, unsigned long addr, pte_t *ptep)
{
unsigned long pfn = pte_pfn(*ptep);
struct page *page;
if (!pfn_valid(pfn))
return;
page = pfn_to_page(pfn);
/* Invalidate old entry in TLBs */
invalidate_itlb_mapping(addr);
invalidate_dtlb_mapping(addr);
#if (DCACHE_WAY_SIZE > PAGE_SIZE) && XCHAL_DCACHE_IS_WRITEBACK
if (!PageReserved(page) && test_bit(PG_arch_1, &page->flags)) {
unsigned long vaddr = TLBTEMP_BASE_1 + (addr & DCACHE_ALIAS_MASK);
unsigned long paddr = (unsigned long) page_address(page);
unsigned long phys = page_to_phys(page);
__flush_invalidate_dcache_page(paddr);
__flush_invalidate_dcache_page_alias(vaddr, phys);
__invalidate_icache_page_alias(vaddr, phys);
clear_bit(PG_arch_1, &page->flags);
}
#else
if (!PageReserved(page) && !test_bit(PG_arch_1, &page->flags)
&& (vma->vm_flags & VM_EXEC) != 0) {
unsigned long paddr = (unsigned long) page_address(page);
__flush_dcache_page(paddr);
__invalidate_icache_page(paddr);
set_bit(PG_arch_1, &page->flags);
}
#endif
}
/*
* access_process_vm() has called get_user_pages(), which has done a
* flush_dcache_page() on the page.
*/
#if (DCACHE_WAY_SIZE > PAGE_SIZE) && XCHAL_DCACHE_IS_WRITEBACK
void copy_to_user_page(struct vm_area_struct *vma, struct page *page,
unsigned long vaddr, void *dst, const void *src,
unsigned long len)
{
unsigned long phys = page_to_phys(page);
unsigned long alias = !(DCACHE_ALIAS_EQ(vaddr, phys));
/* Flush and invalidate user page if aliased. */
if (alias) {
unsigned long temp = TLBTEMP_BASE_1 + (vaddr & DCACHE_ALIAS_MASK);
__flush_invalidate_dcache_page_alias(temp, phys);
}
/* Copy data */
memcpy(dst, src, len);
/*
* Flush and invalidate kernel page if aliased and synchronize
* data and instruction caches for executable pages.
*/
if (alias) {
unsigned long temp = TLBTEMP_BASE_1 + (vaddr & DCACHE_ALIAS_MASK);
__flush_invalidate_dcache_range((unsigned long) dst, len);
if ((vma->vm_flags & VM_EXEC) != 0) {
__invalidate_icache_page_alias(temp, phys);
}
} else if ((vma->vm_flags & VM_EXEC) != 0) {
__flush_dcache_range((unsigned long)dst,len);
__invalidate_icache_range((unsigned long) dst, len);
}
}
extern void copy_from_user_page(struct vm_area_struct *vma, struct page *page,
unsigned long vaddr, void *dst, const void *src,
unsigned long len)
{
unsigned long phys = page_to_phys(page);
unsigned long alias = !(DCACHE_ALIAS_EQ(vaddr, phys));
/*
* Flush user page if aliased.
* (Note: a simply flush would be sufficient)
*/
if (alias) {
unsigned long temp = TLBTEMP_BASE_1 + (vaddr & DCACHE_ALIAS_MASK);
__flush_invalidate_dcache_page_alias(temp, phys);
}
memcpy(dst, src, len);
}
#endif
| gpl-2.0 |
flar2/jewel-ElementalX | arch/xtensa/mm/cache.c | 8703 | 6487 | /*
* arch/xtensa/mm/cache.c
*
* 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.
*
* Copyright (C) 2001-2006 Tensilica Inc.
*
* Chris Zankel <chris@zankel.net>
* Joe Taylor
* Marc Gauthier
*
*/
#include <linux/init.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/ptrace.h>
#include <linux/bootmem.h>
#include <linux/swap.h>
#include <linux/pagemap.h>
#include <asm/bootparam.h>
#include <asm/mmu_context.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
//#define printd(x...) printk(x)
#define printd(x...) do { } while(0)
/*
* Note:
* The kernel provides one architecture bit PG_arch_1 in the page flags that
* can be used for cache coherency.
*
* I$-D$ coherency.
*
* The Xtensa architecture doesn't keep the instruction cache coherent with
* the data cache. We use the architecture bit to indicate if the caches
* are coherent. The kernel clears this bit whenever a page is added to the
* page cache. At that time, the caches might not be in sync. We, therefore,
* define this flag as 'clean' if set.
*
* D-cache aliasing.
*
* With cache aliasing, we have to always flush the cache when pages are
* unmapped (see tlb_start_vma(). So, we use this flag to indicate a dirty
* page.
*
*
*
*/
#if (DCACHE_WAY_SIZE > PAGE_SIZE) && XCHAL_DCACHE_IS_WRITEBACK
/*
* Any time the kernel writes to a user page cache page, or it is about to
* read from a page cache page this routine is called.
*
*/
void flush_dcache_page(struct page *page)
{
struct address_space *mapping = page_mapping(page);
/*
* If we have a mapping but the page is not mapped to user-space
* yet, we simply mark this page dirty and defer flushing the
* caches until update_mmu().
*/
if (mapping && !mapping_mapped(mapping)) {
if (!test_bit(PG_arch_1, &page->flags))
set_bit(PG_arch_1, &page->flags);
return;
} else {
unsigned long phys = page_to_phys(page);
unsigned long temp = page->index << PAGE_SHIFT;
unsigned long alias = !(DCACHE_ALIAS_EQ(temp, phys));
unsigned long virt;
/*
* Flush the page in kernel space and user space.
* Note that we can omit that step if aliasing is not
* an issue, but we do have to synchronize I$ and D$
* if we have a mapping.
*/
if (!alias && !mapping)
return;
__flush_invalidate_dcache_page((long)page_address(page));
virt = TLBTEMP_BASE_1 + (temp & DCACHE_ALIAS_MASK);
if (alias)
__flush_invalidate_dcache_page_alias(virt, phys);
if (mapping)
__invalidate_icache_page_alias(virt, phys);
}
/* There shouldn't be an entry in the cache for this page anymore. */
}
/*
* For now, flush the whole cache. FIXME??
*/
void flush_cache_range(struct vm_area_struct* vma,
unsigned long start, unsigned long end)
{
__flush_invalidate_dcache_all();
__invalidate_icache_all();
}
/*
* Remove any entry in the cache for this page.
*
* Note that this function is only called for user pages, so use the
* alias versions of the cache flush functions.
*/
void flush_cache_page(struct vm_area_struct* vma, unsigned long address,
unsigned long pfn)
{
/* Note that we have to use the 'alias' address to avoid multi-hit */
unsigned long phys = page_to_phys(pfn_to_page(pfn));
unsigned long virt = TLBTEMP_BASE_1 + (address & DCACHE_ALIAS_MASK);
__flush_invalidate_dcache_page_alias(virt, phys);
__invalidate_icache_page_alias(virt, phys);
}
#endif
void
update_mmu_cache(struct vm_area_struct * vma, unsigned long addr, pte_t *ptep)
{
unsigned long pfn = pte_pfn(*ptep);
struct page *page;
if (!pfn_valid(pfn))
return;
page = pfn_to_page(pfn);
/* Invalidate old entry in TLBs */
invalidate_itlb_mapping(addr);
invalidate_dtlb_mapping(addr);
#if (DCACHE_WAY_SIZE > PAGE_SIZE) && XCHAL_DCACHE_IS_WRITEBACK
if (!PageReserved(page) && test_bit(PG_arch_1, &page->flags)) {
unsigned long vaddr = TLBTEMP_BASE_1 + (addr & DCACHE_ALIAS_MASK);
unsigned long paddr = (unsigned long) page_address(page);
unsigned long phys = page_to_phys(page);
__flush_invalidate_dcache_page(paddr);
__flush_invalidate_dcache_page_alias(vaddr, phys);
__invalidate_icache_page_alias(vaddr, phys);
clear_bit(PG_arch_1, &page->flags);
}
#else
if (!PageReserved(page) && !test_bit(PG_arch_1, &page->flags)
&& (vma->vm_flags & VM_EXEC) != 0) {
unsigned long paddr = (unsigned long) page_address(page);
__flush_dcache_page(paddr);
__invalidate_icache_page(paddr);
set_bit(PG_arch_1, &page->flags);
}
#endif
}
/*
* access_process_vm() has called get_user_pages(), which has done a
* flush_dcache_page() on the page.
*/
#if (DCACHE_WAY_SIZE > PAGE_SIZE) && XCHAL_DCACHE_IS_WRITEBACK
void copy_to_user_page(struct vm_area_struct *vma, struct page *page,
unsigned long vaddr, void *dst, const void *src,
unsigned long len)
{
unsigned long phys = page_to_phys(page);
unsigned long alias = !(DCACHE_ALIAS_EQ(vaddr, phys));
/* Flush and invalidate user page if aliased. */
if (alias) {
unsigned long temp = TLBTEMP_BASE_1 + (vaddr & DCACHE_ALIAS_MASK);
__flush_invalidate_dcache_page_alias(temp, phys);
}
/* Copy data */
memcpy(dst, src, len);
/*
* Flush and invalidate kernel page if aliased and synchronize
* data and instruction caches for executable pages.
*/
if (alias) {
unsigned long temp = TLBTEMP_BASE_1 + (vaddr & DCACHE_ALIAS_MASK);
__flush_invalidate_dcache_range((unsigned long) dst, len);
if ((vma->vm_flags & VM_EXEC) != 0) {
__invalidate_icache_page_alias(temp, phys);
}
} else if ((vma->vm_flags & VM_EXEC) != 0) {
__flush_dcache_range((unsigned long)dst,len);
__invalidate_icache_range((unsigned long) dst, len);
}
}
extern void copy_from_user_page(struct vm_area_struct *vma, struct page *page,
unsigned long vaddr, void *dst, const void *src,
unsigned long len)
{
unsigned long phys = page_to_phys(page);
unsigned long alias = !(DCACHE_ALIAS_EQ(vaddr, phys));
/*
* Flush user page if aliased.
* (Note: a simply flush would be sufficient)
*/
if (alias) {
unsigned long temp = TLBTEMP_BASE_1 + (vaddr & DCACHE_ALIAS_MASK);
__flush_invalidate_dcache_page_alias(temp, phys);
}
memcpy(dst, src, len);
}
#endif
| gpl-2.0 |
ebshimizu/Lumiverse | Lumiverse/source/LumiverseShowControl/Keyframe.cpp | 1 | 2008 | #include "Keyframe.h"
namespace Lumiverse {
namespace ShowControl {
Keyframe::Keyframe(JSONNode node) {
auto jt = node.find("t");
if (jt == node.end()) {
Logger::log(ERR, "Keyframe has no assigned time. Defaulting to 0.");
t = 0;
}
else {
t = jt->as_int();
}
auto v = node.find("val");
if (v == node.end()) {
val = nullptr;
}
else {
val = shared_ptr<LumiverseType>(LumiverseTypeUtils::loadFromJSON(*v));
}
auto ucs = node.find("useCurrentState");
if (ucs == node.end()) {
useCurrentState = false;
}
else {
useCurrentState = ucs->as_bool();
}
auto tid = node.find("timelineID");
if (tid == node.end()) {
timelineID = "";
}
else {
timelineID = tid->as_string();
}
auto to = node.find("timelineOffset");
if (to == node.end()) {
timelineOffset = 0;
}
else {
timelineOffset = to->as_int();
}
}
JSONNode Keyframe::toJSON() {
JSONNode keyframe;
keyframe.push_back(JSONNode("t", (unsigned long) t));
if (val != nullptr) {
keyframe.push_back(val->toJSON("val"));
}
keyframe.push_back(JSONNode("useCurrentState", useCurrentState));
if (timelineID != "") {
keyframe.push_back(JSONNode("timelineID", timelineID));
keyframe.push_back(JSONNode("timelineOffset", (unsigned long)timelineOffset));
}
return keyframe;
}
Event::Event(function<void()> cb, string id) : _id(id) {
_callback = cb;
}
Event::Event(JSONNode node) {
_id = node.name();
_callback = [](){ Logger::log(WARN, "Event loaded from JSON node has no callback. Update this in code."); };
}
Event::~Event() {
// destructor if necessary
}
void Event::execute() {
_callback();
}
void Event::reset() {
// nothing for the base class.
}
void Event::setCallback(function<void()> cb) {
_callback = cb;
}
JSONNode Event::toJSON() {
// this is equivalent to saying "something happened here but I have no idea what it is"
JSONNode e;
e.set_name(_id);
e.push_back(JSONNode("type", getType()));
return e;
}
}
} | gpl-3.0 |
mtyka/pd | src/mmlib/library/rotamer_dunbrack.cpp | 1 | 13949 | // PD is a free, modular C++ library for biomolecular simulation with a
// flexible and scriptable Python interface.
// Copyright (C) 2003-2013 Mike Tyka and Jon Rea
//
// 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 "global.h"
#include <deque>
#include "tools/vector.h"
#include "library/rotamer_dunbrack.h"
namespace Library
{
RotLibConvert_Dunbrack_BBInd::RotLibConvert_Dunbrack_BBInd()
: RotLibConvertBase()
{
}
void RotLibConvert_Dunbrack_BBInd::readDefinition( StringBuilder& sb, RotamerLibrary& _RotLib ) const
{
ASSERT( sb.size() >= 67, ParseException, "String too short to parse!!");
StringBuilder resname(3);
resname.setTo( sb, 0, 3 );
sb.TruncateLeftBy(18);
int pdbCount = sb.parseInt(0,7);
if( pdbCount == 0 )
return;
double probability = sb.parseDouble(7,8);
sb.TruncateLeftBy(37);
std::vector<double> importChis;
std::vector<std::string> parts = sb.tokenise();
ASSERT( (parts.size() % 2 == 0), ParseException, "Unexpected element count");
for( size_t i = 0; i < parts.size(); i+=2 )
{
double chi;
ASSERT( 0 == str2double( parts[i], chi ), ParseException, "Error parsing chi def");
importChis.push_back(Maths::DegToRad(chi));
}
ASSERT( importChis.size() != 0, ParseException, "No chis found!!");
_RotLib.addRotamer( resname.toString(), importChis, ConstantProbability( probability ) );
}
void RotLibConvert_Dunbrack_BBInd::readLib( const std::string& _LibraryFilename, RotamerLibrary& _RotLib )
{
StringBuilder sb;
std::ifstream* p_torsionFile;
try
{
if( _RotLib.isFinalised() )
throw ProcedureException("readLib() is not allowed, the rotamer library has been finalised, no further import can occur");
// Mappings for things like HIS -> HIE HID HIP
_RotLib.addIonisationAliasWorkingDefaults();
// Make sure Alanine and Glycine are defined non-rotamer residues (the library itself ignores them)
_RotLib.addAsBlankRotamer("ALA");
_RotLib.addAsBlankRotamer("GLY");
p_torsionFile = new std::ifstream(_LibraryFilename.c_str(), std::ifstream::in);
std::ifstream& torsionFile = *p_torsionFile;
if( !torsionFile.is_open() ) throw(IOException( "Dunbrack BB-independent torsional definition file not found: '" + _LibraryFilename + "'!" ));
sb << torsionFile;
ASSERT( sb.size() >= 36 && sb.compare("Backbone-independent rotamer library",0,36,0,false),
ParseException,
"The input coordinate file does not appear to be in Dunbrack BB-independent format");
const char* initLine = "Res Rotamer n(r1) n(r1234) p(r1234) sig p(r234|r1) sig chi1 sig chi2 sig chi3 sig chi4 sig";
int initLineLength = strlen(initLine);
bool begun = false;
while( sb << torsionFile )
{
if( sb.size() >= initLineLength &&
sb.compare( initLine, 0, initLineLength, 0 ) )
{
begun = true;
break;
}
}
ASSERT(begun,ParseException,"Unexpected EOF whilst parsing the Dunbrack BB-independent format library");
sb << torsionFile; // Two blanking lines are present here
sb << torsionFile; // So eradicate them - mwa ha ha ha!
while( sb << torsionFile )
{
sb.Trim();
if( sb.size() == 0 ) continue;
readDefinition( sb, _RotLib );
}
// Ensure file-handle cleanup
p_torsionFile->close();
delete p_torsionFile;
}
catch( ExceptionBase ex )
{
// Ensure file-handle cleanup
p_torsionFile->close();
delete p_torsionFile;
throw ex;
}
}
RotLibConvert_Dunbrack_BBDep::RotLibConvert_Dunbrack_BBDep()
: RotLibConvertBase(), switchImportMode(false)
{
}
struct ParseData
{
ParseData();
bool parse( StringBuilder& sb );
StringBuilder rotID;
short phi;
short psi;
float probability;
std::vector<double> chis;
};
typedef std::vector<ParseData> ContainerType;
ParseData::ParseData()
: rotID(7)
{
chis.reserve(4);
}
bool ParseData::parse(StringBuilder& sb)
{
if( sb.size() < 107 )
return false;
phi = (short)sb.parseInt(5,4);
psi = (short)sb.parseInt(10,4);
ASSERT(
180 >= phi &&
-180 <= phi &&
180 >= psi &&
-180 <= psi,
ParseException, "Phi/Psi range error");
rotID.setTo(sb, 24, 7 );
rotID.removeAll(' ');
ASSERT(rotID.size() == 4, ParseException, "RotID is bad");
probability = (float)sb.parseDouble(33, 8);
float chi;
chis.clear();
chi = (float)sb.parseDouble( 42, 7 );
if( chi != 0.0 ) // As a coder, this line makes me vomit, but unfortunatly their library is written this way. Eugh!
chis.push_back(chi);
chi = (float)sb.parseDouble( 50, 7 );
if( chi != 0.0 ) // Why could they not have a gap, or at least use NULL or something ?!?
chis.push_back(chi);
chi = (float)sb.parseDouble( 58, 7 );
if( chi != 0.0 )
chis.push_back(chi);
chi = (float)sb.parseDouble( 66, 7 );
if( chi != 0.0 )
chis.push_back(chi);
return true;
}
inline bool removeParseData( const ParseData& pd )
{
return pd.phi == 180.0 || pd.psi == 180.0;
}
inline bool removeLowPropensity( const ParseData& pd )
{
return Maths::SigFigEquality(0.0,(double)pd.probability,6);
}
void processData( const std::string& resName, ContainerType& data, RotamerLibrary& _RotLib, double tollerance )
{
std::vector<double> averagedChis = data[0].chis;
if( averagedChis[0] < 0.0 )
averagedChis[0] += 360.0;
for( size_t j = 1; j < data.size(); j++ )
{
while( data[0].chis.size() > data[j].chis.size() )
{
// Chi count disagreement: Unfortunatly some, due to being 0.0 are not read in. Just pad it...
data[j].chis.push_back(0.0);
}
for( size_t k = 0; k < data[0].chis.size(); k++ )
{
double d1 = data[0].chis[k];
double d2 = data[j].chis[k];
double delta = d1 - d2;
if( delta < 0.0 )
delta = -delta;
if( delta > 180.0 )
delta = 360.0 - delta;
if( delta != 0.0 )
{
// We have to allow a +-tollerance wobble, as some are *a little* different depending on the exact phi/psi!
ASSERT( tollerance > delta, ParseException, "Internal data correlation mismatch (Chi)");
}
if( d2 < 0.0 ) d2 += 360.0; // assure all are +ve
averagedChis[k] += d2;
}
}
for( size_t i = 0; i < averagedChis.size(); i++ )
{
averagedChis[i] = averagedChis[i] / (double)data.size();
averagedChis[i] = torsionalRangeDegrees( averagedChis[i] );
averagedChis[i] = Maths::DegToRad(averagedChis[i]);
}
ProbabilityByPhiPsiMap map( 36 ); // 10 degree
for( size_t j = 0; j < data.size(); j++ )
{
map.assignFrom(
Maths::DegToRad(data[j].phi),
Maths::DegToRad(data[j].psi),
Maths::DegToRad(data[j].probability)
);
}
_RotLib.addRotamer( resName, averagedChis, map );
return;
}
inline bool sortPhi( const ParseData& _a, const ParseData& _b )
{
return _a.phi < _b.phi;
}
inline bool sortPsi( const ParseData& _a, const ParseData& _b )
{
return _a.psi < _b.psi;
}
inline bool sortRotID( const ParseData& _a, const ParseData& _b )
{
return _a.rotID.compareValue(_b.rotID,0,4,0) >= 0;
}
inline double ensure( const std::vector<double>& d, size_t i )
{
if( d.size() > i ) return d[i];
return 0.0;
}
inline bool sortChi1( const ParseData& _a, const ParseData& _b )
{
return ensure(_a.chis,0) < ensure(_b.chis,0);
}
inline bool sortChi2( const ParseData& _a, const ParseData& _b )
{
return ensure(_a.chis,1) < ensure(_b.chis,1);
}
inline bool sortChi3( const ParseData& _a, const ParseData& _b )
{
return ensure(_a.chis,2) < ensure(_b.chis,2);
}
inline bool sortChi4( const ParseData& _a, const ParseData& _b )
{
return ensure(_a.chis,3) < ensure(_b.chis,3);
}
bool equalChis( ParseData& _a, ParseData& _b, double tollerance )
{
for( size_t i = 0; i < _a.chis.size(); i++ )
{
double a = _a.chis[i];
double b = _b.chis[i];
double delta = fabs(a - b);
if( delta > 180.0 )
delta = 360.0 - delta;
if( delta >= tollerance )
return false;
}
return true;
}
void processResData_ByChis( const std::string& resName, ContainerType& data, RotamerLibrary& _RotLib )
{
const double tollerance = 12.0;
// Ensure full chi arrays
size_t largestSoFar = data[0].chis.size();
for( size_t i = 1; i < data.size(); i++ )
{
if( data[i].chis.size() > largestSoFar )
{
largestSoFar = data[i].chis.size();
i = 0; // reset
}
while( data[i].chis.size() < largestSoFar )
{
data[i].chis.push_back(0.0);
}
}
size_t done = 0;
std::vector<bool> taken(data.size());
while( data.size() > done )
{
ContainerType subdata;
bool on = false;
for( int i = (int)data.size()-1; i >= 0; i-- )
{
if( taken[i] != true && (!on || equalChis( subdata[0], data[i], tollerance ) ) )
{
subdata.push_back( data[i] );
taken[i] = true;
on = true;
done++;
}
}
processData( resName, subdata, _RotLib, tollerance );
subdata.clear();
}
data.clear();
}
void processResData_ByRotID( const std::string& resName, ContainerType& data, RotamerLibrary& _RotLib )
{
// Sort the data to increase efficiency below
std::stable_sort( data.begin(), data.end(), sortPsi);
std::stable_sort( data.begin(), data.end(), sortPhi);
std::stable_sort( data.begin(), data.end(), sortRotID);
ContainerType subdata;
while( true )
{
if( data.size() > 0 && (subdata.size() == 0 || subdata[0].rotID.compare( data.back().rotID,0,4,0 )) )
{
subdata.push_back( data.back() );
data.erase(data.end()-1); // rob the end, not the start (ContainerType<> perfomance reasons!)
}
else
{
ASSERT( data.size() == (36*36), ParseException, "Assumption error!");
ASSERT( data[0].phi == -180.0 && data[0].psi == -180.0, ParseException, "Wrong phi/psi");
for( size_t j = 1; j < data.size(); j++ )
{
ASSERT( data[j].phi == (-180.0+(j/36)*10) && data[j].psi == (-180.0+(j%36)*10), ParseException, "Wrong phi/psi");
}
processData( resName, subdata, _RotLib, 40.0 ); // 40 degree tollerance delta from data[0]
subdata.clear();
if( data.size() == 0 )
{
return;
}
}
}
}
// This function is given an entire block of the same residue. The rotamerIDs will of course be different.
void processResData( const std::string& resName, ContainerType& data, RotamerLibrary& _RotLib, bool switchImportMode )
{
// Either there is something fundamental I don't understand, or ...
// The dunbrack library has this really annoying thing whereby the 180 and -180 phi/psi torsions,
// which are by definition the same thing, are both defined!
// We only want one, as both represent the same 10 degree bin!
data.erase(std::remove_if(data.begin(),data.end(),removeParseData),data.end());
if( switchImportMode )
{
processResData_ByRotID(resName,data,_RotLib);
}
else
{
data.erase(std::remove_if(data.begin(),data.end(),removeLowPropensity),data.end());
processResData_ByChis(resName,data,_RotLib);
}
}
void RotLibConvert_Dunbrack_BBDep::readLib( const std::string& _LibraryFilename, RotamerLibrary& _RotLib )
{
StringBuilder sb;
std::ifstream* p_torsionFile;
try
{
if( _RotLib.isFinalised() )
throw ProcedureException("readLib() is not allowed, the rotamer library has been finalised, no further import can occur");
// Mappings for things like HIS -> HIE HID HIP
_RotLib.addIonisationAliasWorkingDefaults();
// Make sure Alanine and Glycine are defined non-rotamer residues (the library itself ignores them)
_RotLib.addAsBlankRotamer("ALA");
_RotLib.addAsBlankRotamer("GLY");
p_torsionFile = new std::ifstream(_LibraryFilename.c_str(), std::ifstream::in);
std::ifstream& torsionFile = *p_torsionFile;
if( !torsionFile.is_open() )
throw(IOException( "Dunbrack BB-independent torsional definition file not found: '" + _LibraryFilename + "'!" ));
ParseData pd;
ContainerType data;
StringBuilder prevResName(3);
StringBuilder currResName(4);
StringBuilder cacheLine;
while( true )
{
if( cacheLine.size() > 0 )
{
sb.setTo(cacheLine);
cacheLine.clear();
}
else if( !(sb << torsionFile) )
{
break;
}
sb.Trim();
if( sb.size() == 0 )
continue; // blank line
currResName.setTo(sb,0,3);
if( prevResName.size() == 0 )
{
prevResName.setTo( currResName );
ASSERT( pd.parse( sb ), ParseException, "Malformed line");
data.push_back( pd );
}
else if( prevResName.compare( currResName, 0, 3, 0 ) )
{
// Woooo - we found one :-D
ASSERT( pd.parse( sb ), ParseException, "Malformed line");
data.push_back( pd );
}
else
{
if( data.size() > 0 )
{
processResData( prevResName.toString(), data, _RotLib, switchImportMode );
ASSERT( data.size() == 0, CodeException, "CodeFail");
}
prevResName.setTo( currResName );
cacheLine.setTo( sb ); // we havent actually processed the current line! Store it.
}
}
if( data.size() > 0 )
{
processResData( prevResName.toString(), data, _RotLib, switchImportMode );
ASSERT( data.size() == 0, CodeException, "CodeFail");
}
// Ensure file-handle cleanup
p_torsionFile->close();
delete p_torsionFile;
}
catch( ExceptionBase ex )
{
// Ensure file-handle cleanup
p_torsionFile->close();
delete p_torsionFile;
throw ex;
}
}
}
| gpl-3.0 |
dongkc/crtmpserver | sources/common/src/platform/linux/linuxplatform.cpp | 1 | 12467 | /*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver 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.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef LINUX
#include "platform/linux/linuxplatform.h"
#include "common.h"
string alowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
static map<int, SignalFnc> _signalHandlers;
LinuxPlatform::LinuxPlatform() {
}
LinuxPlatform::~LinuxPlatform() {
}
string format(string fmt, ...) {
string result = "";
va_list arguments;
va_start(arguments, fmt);
result = vFormat(fmt, arguments);
va_end(arguments);
return result;
}
string vFormat(string fmt, va_list args) {
char *pBuffer = NULL;
if (vasprintf(&pBuffer, STR(fmt), args) == -1) {
o_assert(false);
return "";
}
string result = pBuffer;
free(pBuffer);
return result;
}
void replace(string &target, string search, string replacement) {
if (search == replacement)
return;
if (search == "")
return;
string::size_type i = string::npos;
string::size_type lastPos = 0;
while ((i = target.find(search, lastPos)) != string::npos) {
target.replace(i, search.length(), replacement);
lastPos = i + replacement.length();
}
}
bool fileExists(string path) {
struct stat fileInfo;
if (stat(STR(path), &fileInfo) == 0) {
return true;
} else {
return false;
}
}
string lowerCase(string value) {
return changeCase(value, true);
}
string upperCase(string value) {
return changeCase(value, false);
}
string changeCase(string &value, bool lowerCase) {
string result = "";
for (string::size_type i = 0; i < value.length(); i++) {
if (lowerCase)
result += tolower(value[i]);
else
result += toupper(value[i]);
}
return result;
}
string tagToString(uint64_t tag) {
string result;
for (uint32_t i = 0; i < 8; i++) {
uint8_t v = (tag >> ((7 - i)*8)&0xff);
if (v == 0)
break;
result += (char) v;
}
return result;
}
bool setFdNonBlock(SOCKET fd) {
int32_t arg;
if ((arg = fcntl(fd, F_GETFL, NULL)) < 0) {
int err = errno;
FATAL("Unable to get fd flags: (%d) %s", err, strerror(err));
return false;
}
arg |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, arg) < 0) {
int err = errno;
FATAL("Unable to set fd flags: (%d) %s", err, strerror(err));
return false;
}
return true;
}
bool setFdNoSIGPIPE(SOCKET fd) {
//This is not needed because we use MSG_NOSIGNAL when using
//send/write functions
return true;
}
bool setFdKeepAlive(SOCKET fd, bool isUdp) {
if (isUdp)
return true;
int32_t one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
(const char*) & one, sizeof (one)) != 0) {
FATAL("Unable to set SO_NOSIGPIPE");
return false;
}
return true;
}
bool setFdNoNagle(SOCKET fd, bool isUdp) {
if (isUdp)
return true;
int32_t one = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) & one, sizeof (one)) != 0) {
return false;
}
return true;
}
bool setFdReuseAddress(SOCKET fd) {
int32_t one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) & one, sizeof (one)) != 0) {
FATAL("Unable to reuse address");
return false;
}
#ifdef SO_REUSEPORT
if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char *) & one, sizeof (one)) != 0) {
FATAL("Unable to reuse port");
return false;
}
#endif /* SO_REUSEPORT */
return true;
}
bool setFdTTL(SOCKET fd, uint8_t ttl) {
int temp = ttl;
if (setsockopt(fd, IPPROTO_IP, IP_TTL, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_TTL: %"PRIu8"; error was (%d) %s", ttl, err, strerror(err));
}
return true;
}
bool setFdMulticastTTL(SOCKET fd, uint8_t ttl) {
int temp = ttl;
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_MULTICAST_TTL: %"PRIu8"; error was (%d) %s", ttl, err, strerror(err));
}
return true;
}
bool setFdTOS(SOCKET fd, uint8_t tos) {
int temp = tos;
if (setsockopt(fd, IPPROTO_IP, IP_TOS, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_TOS: %"PRIu8"; error was (%d) %s", tos, err, strerror(err));
}
return true;
}
bool setFdOptions(SOCKET fd, bool isUdp) {
if (!setFdNonBlock(fd)) {
FATAL("Unable to set non block");
return false;
}
if (!setFdNoSIGPIPE(fd)) {
FATAL("Unable to set no SIGPIPE");
return false;
}
if (!setFdKeepAlive(fd, isUdp)) {
FATAL("Unable to set keep alive");
return false;
}
if (!setFdNoNagle(fd, isUdp)) {
WARN("Unable to disable Nagle algorithm");
}
if (!setFdReuseAddress(fd)) {
FATAL("Unable to enable reuse address");
return false;
}
return true;
}
bool deleteFile(string path) {
if (remove(STR(path)) != 0) {
FATAL("Unable to delete file `%s`", STR(path));
return false;
}
return true;
}
bool deleteFolder(string path, bool force) {
if (!force) {
return deleteFile(path);
} else {
string command = format("rm -rf %s", STR(path));
if (system(STR(command)) != 0) {
FATAL("Unable to delete folder %s", STR(path));
return false;
}
return true;
}
}
bool createFolder(string path, bool recursive) {
string command = format("mkdir %s %s",
recursive ? "-p" : "",
STR(path));
if (system(STR(command)) != 0) {
FATAL("Unable to create folder %s", STR(path));
return false;
}
return true;
}
string getHostByName(string name) {
struct hostent *pHostEnt = gethostbyname(STR(name));
if (pHostEnt == NULL)
return "";
if (pHostEnt->h_length <= 0)
return "";
string result = format("%hhu.%hhu.%hhu.%hhu",
(uint8_t) pHostEnt->h_addr_list[0][0],
(uint8_t) pHostEnt->h_addr_list[0][1],
(uint8_t) pHostEnt->h_addr_list[0][2],
(uint8_t) pHostEnt->h_addr_list[0][3]);
return result;
}
bool isNumeric(string value) {
return value == format("%d", atoi(STR(value)));
}
void split(string str, string separator, vector<string> &result) {
result.clear();
string::size_type position = str.find(separator);
string::size_type lastPosition = 0;
uint32_t separatorLength = separator.length();
while (position != str.npos) {
ADD_VECTOR_END(result, str.substr(lastPosition, position - lastPosition));
lastPosition = position + separatorLength;
position = str.find(separator, lastPosition);
}
ADD_VECTOR_END(result, str.substr(lastPosition, string::npos));
}
uint64_t getTagMask(uint64_t tag) {
uint64_t result = 0xffffffffffffffffLL;
for (int8_t i = 56; i >= 0; i -= 8) {
if (((tag >> i)&0xff) == 0)
break;
result = result >> 8;
}
return ~result;
}
string generateRandomString(uint32_t length) {
string result = "";
for (uint32_t i = 0; i < length; i++)
result += alowedCharacters[rand() % alowedCharacters.length()];
return result;
}
void lTrim(string &value) {
string::size_type i = 0;
for (i = 0; i < value.length(); i++) {
if (value[i] != ' ' &&
value[i] != '\t' &&
value[i] != '\n' &&
value[i] != '\r')
break;
}
value = value.substr(i);
}
void rTrim(string &value) {
int32_t i = 0;
for (i = (int32_t) value.length() - 1; i >= 0; i--) {
if (value[i] != ' ' &&
value[i] != '\t' &&
value[i] != '\n' &&
value[i] != '\r')
break;
}
value = value.substr(0, i + 1);
}
void trim(string &value) {
lTrim(value);
rTrim(value);
}
int8_t getCPUCount() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
map<string, string> mapping(string str, string separator1, string separator2, bool trimStrings) {
map<string, string> result;
vector<string> pairs;
split(str, separator1, pairs);
FOR_VECTOR_ITERATOR(string, pairs, i) {
if (VECTOR_VAL(i) != "") {
if (VECTOR_VAL(i).find(separator2) != string::npos) {
string key = VECTOR_VAL(i).substr(0, VECTOR_VAL(i).find(separator2));
string value = VECTOR_VAL(i).substr(VECTOR_VAL(i).find(separator2) + 1);
if (trimStrings) {
trim(key);
trim(value);
}
result[key] = value;
} else {
if (trimStrings) {
trim(VECTOR_VAL(i));
}
result[VECTOR_VAL(i)] = "";
}
}
}
return result;
}
void splitFileName(string fileName, string &name, string & extension, char separator) {
size_t dotPosition = fileName.find_last_of(separator);
if (dotPosition == string::npos) {
name = fileName;
extension = "";
return;
}
name = fileName.substr(0, dotPosition);
extension = fileName.substr(dotPosition + 1);
}
double getFileModificationDate(string path) {
struct stat s;
if (stat(STR(path), &s) != 0) {
FATAL("Unable to stat file %s", STR(path));
return 0;
}
return (double) s.st_mtime;
}
string normalizePath(string base, string file) {
char dummy1[PATH_MAX];
char dummy2[PATH_MAX];
char *pBase = realpath(STR(base), dummy1);
char *pFile = realpath(STR(base + file), dummy2);
if (pBase != NULL) {
base = pBase;
} else {
base = "";
}
if (pFile != NULL) {
file = pFile;
} else {
file = "";
}
if (file == "" || base == "") {
return "";
}
if (file.find(base) != 0) {
return "";
} else {
if (!fileExists(file)) {
return "";
} else {
return file;
}
}
}
bool listFolder(string path, vector<string> &result, bool normalizeAllPaths,
bool includeFolders, bool recursive) {
if (path == "")
path = ".";
if (path[path.size() - 1] != PATH_SEPARATOR)
path += PATH_SEPARATOR;
DIR *pDir = NULL;
pDir = opendir(STR(path));
if (pDir == NULL) {
int err = errno;
FATAL("Unable to open folder: %s (%d) %s", STR(path), err, strerror(err));
return false;
}
struct dirent *pDirent = NULL;
while ((pDirent = readdir(pDir)) != NULL) {
string entry = pDirent->d_name;
if ((entry == ".")
|| (entry == "..")) {
continue;
}
if (normalizeAllPaths) {
entry = normalizePath(path, entry);
} else {
entry = path + entry;
}
if (entry == "")
continue;
if (pDirent->d_type == DT_DIR) {
if (includeFolders) {
ADD_VECTOR_END(result, entry);
}
if (recursive) {
if (!listFolder(entry, result, normalizeAllPaths, includeFolders, recursive)) {
FATAL("Unable to list folder");
closedir(pDir);
return false;
}
}
} else {
ADD_VECTOR_END(result, entry);
}
}
closedir(pDir);
return true;
}
bool moveFile(string src, string dst) {
if (rename(STR(src), STR(dst)) != 0) {
FATAL("Unable to move file from `%s` to `%s`",
STR(src), STR(dst));
return false;
}
return true;
}
void signalHandler(int sig) {
if (!MAP_HAS1(_signalHandlers, sig))
return;
_signalHandlers[sig]();
}
void installSignal(int sig, SignalFnc pSignalFnc) {
_signalHandlers[sig] = pSignalFnc;
struct sigaction action;
action.sa_handler = signalHandler;
action.sa_flags = 0;
if (sigemptyset(&action.sa_mask) != 0) {
ASSERT("Unable to install the quit signal");
return;
}
if (sigaction(sig, &action, NULL) != 0) {
ASSERT("Unable to install the quit signal");
return;
}
}
void installQuitSignal(SignalFnc pQuitSignalFnc) {
installSignal(SIGTERM, pQuitSignalFnc);
}
void installConfRereadSignal(SignalFnc pConfRereadSignalFnc) {
installSignal(SIGHUP, pConfRereadSignalFnc);
}
static time_t _gUTCOffset = -1;
void computeGMTTimeOffset() {
time_t now = time(NULL);
struct tm *pTemp = localtime(&now);
_gUTCOffset = pTemp->tm_gmtoff;
}
time_t getlocaltime() {
if (_gUTCOffset == -1)
computeGMTTimeOffset();
return getutctime() + _gUTCOffset;
}
time_t gettimeoffset() {
if (_gUTCOffset == -1)
computeGMTTimeOffset();
return _gUTCOffset;
}
#endif /* LINUX */
| gpl-3.0 |
estei-master/segment_SOL | PJ/uboot_kernel/u-boot-sunxi/common/cmd_nvedit.c | 1 | 29153 | /*
* (C) Copyright 2000-2013
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Andreas Heppel <aheppel@sysgo.de>
*
* Copyright 2011 Freescale Semiconductor, Inc.
*
* SPDX-License-Identifier: GPL-2.0+
*/
/*
* Support for persistent environment data
*
* The "environment" is stored on external storage as a list of '\0'
* terminated "name=value" strings. The end of the list is marked by
* a double '\0'. The environment is preceeded by a 32 bit CRC over
* the data part and, in case of redundant environment, a byte of
* flags.
*
* This linearized representation will also be used before
* relocation, i. e. as long as we don't have a full C runtime
* environment. After that, we use a hash table.
*/
#include <common.h>
#include <command.h>
#include <environment.h>
#include <search.h>
#include <errno.h>
#include <malloc.h>
#include <watchdog.h>
#include <linux/stddef.h>
#include <asm/byteorder.h>
DECLARE_GLOBAL_DATA_PTR;
#if !defined(CONFIG_ENV_IS_IN_EEPROM) && \
!defined(CONFIG_ENV_IS_IN_FLASH) && \
!defined(CONFIG_ENV_IS_IN_DATAFLASH) && \
!defined(CONFIG_ENV_IS_IN_MMC) && \
!defined(CONFIG_ENV_IS_IN_FAT) && \
!defined(CONFIG_ENV_IS_IN_NAND) && \
!defined(CONFIG_ENV_IS_IN_NVRAM) && \
!defined(CONFIG_ENV_IS_IN_ONENAND) && \
!defined(CONFIG_ENV_IS_IN_SPI_FLASH) && \
!defined(CONFIG_ENV_IS_IN_REMOTE) && \
!defined(CONFIG_ENV_IS_IN_UBI) && \
!defined(CONFIG_ENV_IS_NOWHERE)
# error Define one of CONFIG_ENV_IS_IN_{EEPROM|FLASH|DATAFLASH|ONENAND|\
SPI_FLASH|NVRAM|MMC|FAT|REMOTE|UBI} or CONFIG_ENV_IS_NOWHERE
#endif
/*
* Maximum expected input data size for import command
*/
#define MAX_ENV_SIZE (1 << 20) /* 1 MiB */
/*
* This variable is incremented on each do_env_set(), so it can
* be used via get_env_id() as an indication, if the environment
* has changed or not. So it is possible to reread an environment
* variable only if the environment was changed ... done so for
* example in NetInitLoop()
*/
static int env_id = 1;
int get_env_id(void)
{
return env_id;
}
#ifndef CONFIG_SPL_BUILD
/*
* Command interface: print one or all environment variables
*
* Returns 0 in case of error, or length of printed string
*/
static int env_print(char *name, int flag)
{
char *res = NULL;
ssize_t len;
if (name) { /* print a single name */
ENTRY e, *ep;
e.key = name;
e.data = NULL;
hsearch_r(e, FIND, &ep, &env_htab, flag);
if (ep == NULL)
return 0;
len = printf("%s=%s\n", ep->key, ep->data);
return len;
}
/* print whole list */
len = hexport_r(&env_htab, '\n', flag, &res, 0, 0, NULL);
if (len > 0) {
puts(res);
free(res);
return len;
}
/* should never happen */
printf("## Error: cannot export environment\n");
return 0;
}
static int do_env_print(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[])
{
int i;
int rcode = 0;
int env_flag = H_HIDE_DOT;
if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'a') {
argc--;
argv++;
env_flag &= ~H_HIDE_DOT;
}
if (argc == 1) {
/* print all env vars */
rcode = env_print(NULL, env_flag);
if (!rcode)
return 1;
printf("\nEnvironment size: %d/%ld bytes\n",
rcode, (ulong)ENV_SIZE);
return 0;
}
/* print selected env vars */
env_flag &= ~H_HIDE_DOT;
for (i = 1; i < argc; ++i) {
int rc = env_print(argv[i], env_flag);
if (!rc) {
printf("## Error: \"%s\" not defined\n", argv[i]);
++rcode;
}
}
return rcode;
}
#ifdef CONFIG_CMD_GREPENV
static int do_env_grep(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
char *res = NULL;
int len, grep_how, grep_what;
if (argc < 2)
return CMD_RET_USAGE;
grep_how = H_MATCH_SUBSTR; /* default: substring search */
grep_what = H_MATCH_BOTH; /* default: grep names and values */
while (argc > 1 && **(argv + 1) == '-') {
char *arg = *++argv;
--argc;
while (*++arg) {
switch (*arg) {
#ifdef CONFIG_REGEX
case 'e': /* use regex matching */
grep_how = H_MATCH_REGEX;
break;
#endif
case 'n': /* grep for name */
grep_what = H_MATCH_KEY;
break;
case 'v': /* grep for value */
grep_what = H_MATCH_DATA;
break;
case 'b': /* grep for both */
grep_what = H_MATCH_BOTH;
break;
case '-':
goto DONE;
default:
return CMD_RET_USAGE;
}
}
}
DONE:
len = hexport_r(&env_htab, '\n',
flag | grep_what | grep_how,
&res, 0, argc, argv);
if (len > 0) {
puts(res);
free(res);
}
if (len < 2)
return 1;
return 0;
}
#endif
#endif /* CONFIG_SPL_BUILD */
/*
* Set a new environment variable,
* or replace or delete an existing one.
*/
static int _do_env_set(int flag, int argc, char * const argv[])
{
int i, len;
char *name, *value, *s;
ENTRY e, *ep;
int env_flag = H_INTERACTIVE;
debug("Initial value for argc=%d\n", argc);
while (argc > 1 && **(argv + 1) == '-') {
char *arg = *++argv;
--argc;
while (*++arg) {
switch (*arg) {
case 'f': /* force */
env_flag |= H_FORCE;
break;
default:
return CMD_RET_USAGE;
}
}
}
debug("Final value for argc=%d\n", argc);
name = argv[1];
value = argv[2];
if (strchr(name, '=')) {
printf("## Error: illegal character '='"
"in variable name \"%s\"\n", name);
return 1;
}
env_id++;
/* Delete only ? */
if (argc < 3 || argv[2] == NULL) {
int rc = hdelete_r(name, &env_htab, env_flag);
return !rc;
}
/*
* Insert / replace new value
*/
for (i = 2, len = 0; i < argc; ++i)
len += strlen(argv[i]) + 1;
value = malloc(len);
if (value == NULL) {
printf("## Can't malloc %d bytes\n", len);
return 1;
}
for (i = 2, s = value; i < argc; ++i) {
char *v = argv[i];
while ((*s++ = *v++) != '\0')
;
*(s - 1) = ' ';
}
if (s != value)
*--s = '\0';
e.key = name;
e.data = value;
hsearch_r(e, ENTER, &ep, &env_htab, env_flag);
free(value);
if (!ep) {
printf("## Error inserting \"%s\" variable, errno=%d\n",
name, errno);
return 1;
}
return 0;
}
int setenv(const char *varname, const char *varvalue)
{
const char * const argv[4] = { "setenv", varname, varvalue, NULL };
/* before import into hashtable */
if (!(gd->flags & GD_FLG_ENV_READY))
return 1;
if (varvalue == NULL || varvalue[0] == '\0')
return _do_env_set(0, 2, (char * const *)argv);
else
return _do_env_set(0, 3, (char * const *)argv);
}
/**
* Set an environment variable to an integer value
*
* @param varname Environment variable to set
* @param value Value to set it to
* @return 0 if ok, 1 on error
*/
int setenv_ulong(const char *varname, ulong value)
{
/* TODO: this should be unsigned */
char *str = simple_itoa(value);
return setenv(varname, str);
}
/**
* Set an environment variable to an value in hex
*
* @param varname Environment variable to set
* @param value Value to set it to
* @return 0 if ok, 1 on error
*/
int setenv_hex(const char *varname, ulong value)
{
char str[17];
sprintf(str, "%lx", value);
return setenv(varname, str);
}
ulong getenv_hex(const char *varname, ulong default_val)
{
const char *s;
ulong value;
char *endp;
s = getenv(varname);
if (s)
value = simple_strtoul(s, &endp, 16);
if (!s || endp == s)
return default_val;
return value;
}
#ifndef CONFIG_SPL_BUILD
static int do_env_set(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if (argc < 2)
return CMD_RET_USAGE;
return _do_env_set(flag, argc, argv);
}
/*
* Prompt for environment variable
*/
#if defined(CONFIG_CMD_ASKENV)
int do_env_ask(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char message[CONFIG_SYS_CBSIZE];
int i, len, pos, size;
char *local_args[4];
char *endptr;
local_args[0] = argv[0];
local_args[1] = argv[1];
local_args[2] = NULL;
local_args[3] = NULL;
/*
* Check the syntax:
*
* env_ask envname [message1 ...] [size]
*/
if (argc == 1)
return CMD_RET_USAGE;
/*
* We test the last argument if it can be converted
* into a decimal number. If yes, we assume it's
* the size. Otherwise we echo it as part of the
* message.
*/
i = simple_strtoul(argv[argc - 1], &endptr, 10);
if (*endptr != '\0') { /* no size */
size = CONFIG_SYS_CBSIZE - 1;
} else { /* size given */
size = i;
--argc;
}
if (argc <= 2) {
sprintf(message, "Please enter '%s': ", argv[1]);
} else {
/* env_ask envname message1 ... messagen [size] */
for (i = 2, pos = 0; i < argc; i++) {
if (pos)
message[pos++] = ' ';
strcpy(message + pos, argv[i]);
pos += strlen(argv[i]);
}
message[pos++] = ' ';
message[pos] = '\0';
}
if (size >= CONFIG_SYS_CBSIZE)
size = CONFIG_SYS_CBSIZE - 1;
if (size <= 0)
return 1;
/* prompt for input */
len = readline(message);
if (size < len)
console_buffer[size] = '\0';
len = 2;
if (console_buffer[0] != '\0') {
local_args[2] = console_buffer;
len = 3;
}
/* Continue calling setenv code */
return _do_env_set(flag, len, local_args);
}
#endif
#if defined(CONFIG_CMD_ENV_CALLBACK)
static int print_static_binding(const char *var_name, const char *callback_name)
{
printf("\t%-20s %-20s\n", var_name, callback_name);
return 0;
}
static int print_active_callback(ENTRY *entry)
{
struct env_clbk_tbl *clbkp;
int i;
int num_callbacks;
if (entry->callback == NULL)
return 0;
/* look up the callback in the linker-list */
num_callbacks = ll_entry_count(struct env_clbk_tbl, env_clbk);
for (i = 0, clbkp = ll_entry_start(struct env_clbk_tbl, env_clbk);
i < num_callbacks;
i++, clbkp++) {
#if defined(CONFIG_NEEDS_MANUAL_RELOC)
if (entry->callback == clbkp->callback + gd->reloc_off)
#else
if (entry->callback == clbkp->callback)
#endif
break;
}
if (i == num_callbacks)
/* this should probably never happen, but just in case... */
printf("\t%-20s %p\n", entry->key, entry->callback);
else
printf("\t%-20s %-20s\n", entry->key, clbkp->name);
return 0;
}
/*
* Print the callbacks available and what they are bound to
*/
int do_env_callback(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
struct env_clbk_tbl *clbkp;
int i;
int num_callbacks;
/* Print the available callbacks */
puts("Available callbacks:\n");
puts("\tCallback Name\n");
puts("\t-------------\n");
num_callbacks = ll_entry_count(struct env_clbk_tbl, env_clbk);
for (i = 0, clbkp = ll_entry_start(struct env_clbk_tbl, env_clbk);
i < num_callbacks;
i++, clbkp++)
printf("\t%s\n", clbkp->name);
puts("\n");
/* Print the static bindings that may exist */
puts("Static callback bindings:\n");
printf("\t%-20s %-20s\n", "Variable Name", "Callback Name");
printf("\t%-20s %-20s\n", "-------------", "-------------");
env_attr_walk(ENV_CALLBACK_LIST_STATIC, print_static_binding);
puts("\n");
/* walk through each variable and print the callback if it has one */
puts("Active callback bindings:\n");
printf("\t%-20s %-20s\n", "Variable Name", "Callback Name");
printf("\t%-20s %-20s\n", "-------------", "-------------");
hwalk_r(&env_htab, print_active_callback);
return 0;
}
#endif
#if defined(CONFIG_CMD_ENV_FLAGS)
static int print_static_flags(const char *var_name, const char *flags)
{
enum env_flags_vartype type = env_flags_parse_vartype(flags);
enum env_flags_varaccess access = env_flags_parse_varaccess(flags);
printf("\t%-20s %-20s %-20s\n", var_name,
env_flags_get_vartype_name(type),
env_flags_get_varaccess_name(access));
return 0;
}
static int print_active_flags(ENTRY *entry)
{
enum env_flags_vartype type;
enum env_flags_varaccess access;
if (entry->flags == 0)
return 0;
type = (enum env_flags_vartype)
(entry->flags & ENV_FLAGS_VARTYPE_BIN_MASK);
access = env_flags_parse_varaccess_from_binflags(entry->flags);
printf("\t%-20s %-20s %-20s\n", entry->key,
env_flags_get_vartype_name(type),
env_flags_get_varaccess_name(access));
return 0;
}
/*
* Print the flags available and what variables have flags
*/
int do_env_flags(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
/* Print the available variable types */
printf("Available variable type flags (position %d):\n",
ENV_FLAGS_VARTYPE_LOC);
puts("\tFlag\tVariable Type Name\n");
puts("\t----\t------------------\n");
env_flags_print_vartypes();
puts("\n");
/* Print the available variable access types */
printf("Available variable access flags (position %d):\n",
ENV_FLAGS_VARACCESS_LOC);
puts("\tFlag\tVariable Access Name\n");
puts("\t----\t--------------------\n");
env_flags_print_varaccess();
puts("\n");
/* Print the static flags that may exist */
puts("Static flags:\n");
printf("\t%-20s %-20s %-20s\n", "Variable Name", "Variable Type",
"Variable Access");
printf("\t%-20s %-20s %-20s\n", "-------------", "-------------",
"---------------");
env_attr_walk(ENV_FLAGS_LIST_STATIC, print_static_flags);
puts("\n");
/* walk through each variable and print the flags if non-default */
puts("Active flags:\n");
printf("\t%-20s %-20s %-20s\n", "Variable Name", "Variable Type",
"Variable Access");
printf("\t%-20s %-20s %-20s\n", "-------------", "-------------",
"---------------");
hwalk_r(&env_htab, print_active_flags);
return 0;
}
#endif
/*
* Interactively edit an environment variable
*/
#if defined(CONFIG_CMD_EDITENV)
static int do_env_edit(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[])
{
char buffer[CONFIG_SYS_CBSIZE];
char *init_val;
if (argc < 2)
return CMD_RET_USAGE;
/* Set read buffer to initial value or empty sting */
init_val = getenv(argv[1]);
if (init_val)
sprintf(buffer, "%s", init_val);
else
buffer[0] = '\0';
if (readline_into_buffer("edit: ", buffer, 0) < 0)
return 1;
return setenv(argv[1], buffer);
}
#endif /* CONFIG_CMD_EDITENV */
#endif /* CONFIG_SPL_BUILD */
/*
* Look up variable from environment,
* return address of storage for that variable,
* or NULL if not found
*/
char *getenv(const char *name)
{
if (gd->flags & GD_FLG_ENV_READY) { /* after import into hashtable */
ENTRY e, *ep;
WATCHDOG_RESET();
e.key = name;
e.data = NULL;
hsearch_r(e, FIND, &ep, &env_htab, 0);
return ep ? ep->data : NULL;
}
/* restricted capabilities before import */
if (getenv_f(name, (char *)(gd->env_buf), sizeof(gd->env_buf)) > 0)
return (char *)(gd->env_buf);
return NULL;
}
/*
* Look up variable from environment for restricted C runtime env.
*/
int getenv_f(const char *name, char *buf, unsigned len)
{
int i, nxt;
for (i = 0; env_get_char(i) != '\0'; i = nxt + 1) {
int val, n;
for (nxt = i; env_get_char(nxt) != '\0'; ++nxt) {
if (nxt >= CONFIG_ENV_SIZE)
return -1;
}
val = envmatch((uchar *)name, i);
if (val < 0)
continue;
/* found; copy out */
for (n = 0; n < len; ++n, ++buf) {
*buf = env_get_char(val++);
if (*buf == '\0')
return n;
}
if (n)
*--buf = '\0';
printf("env_buf [%d bytes] too small for value of \"%s\"\n",
len, name);
return n;
}
return -1;
}
/**
* Decode the integer value of an environment variable and return it.
*
* @param name Name of environemnt variable
* @param base Number base to use (normally 10, or 16 for hex)
* @param default_val Default value to return if the variable is not
* found
* @return the decoded value, or default_val if not found
*/
ulong getenv_ulong(const char *name, int base, ulong default_val)
{
/*
* We can use getenv() here, even before relocation, since the
* environment variable value is an integer and thus short.
*/
const char *str = getenv(name);
return str ? simple_strtoul(str, NULL, base) : default_val;
}
#ifndef CONFIG_SPL_BUILD
#if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
static int do_env_save(cmd_tbl_t *cmdtp, int flag, int argc,
char * const argv[])
{
printf("Saving Environment to %s...\n", env_name_spec);
return saveenv() ? 1 : 0;
}
U_BOOT_CMD(
saveenv, 1, 0, do_env_save,
"save environment variables to persistent storage",
""
);
#endif
#endif /* CONFIG_SPL_BUILD */
/*
* Match a name / name=value pair
*
* s1 is either a simple 'name', or a 'name=value' pair.
* i2 is the environment index for a 'name2=value2' pair.
* If the names match, return the index for the value2, else -1.
*/
int envmatch(uchar *s1, int i2)
{
if (s1 == NULL)
return -1;
while (*s1 == env_get_char(i2++))
if (*s1++ == '=')
return i2;
if (*s1 == '\0' && env_get_char(i2-1) == '=')
return i2;
return -1;
}
#ifndef CONFIG_SPL_BUILD
static int do_env_default(cmd_tbl_t *cmdtp, int __flag,
int argc, char * const argv[])
{
int all = 0, flag = 0;
debug("Initial value for argc=%d\n", argc);
while (--argc > 0 && **++argv == '-') {
char *arg = *argv;
while (*++arg) {
switch (*arg) {
case 'a': /* default all */
all = 1;
break;
case 'f': /* force */
flag |= H_FORCE;
break;
default:
return cmd_usage(cmdtp);
}
}
}
debug("Final value for argc=%d\n", argc);
if (all && (argc == 0)) {
/* Reset the whole environment */
set_default_env("## Resetting to default environment\n");
return 0;
}
if (!all && (argc > 0)) {
/* Reset individual variables */
set_default_vars(argc, argv);
return 0;
}
return cmd_usage(cmdtp);
}
static int do_env_delete(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
int env_flag = H_INTERACTIVE;
int ret = 0;
debug("Initial value for argc=%d\n", argc);
while (argc > 1 && **(argv + 1) == '-') {
char *arg = *++argv;
--argc;
while (*++arg) {
switch (*arg) {
case 'f': /* force */
env_flag |= H_FORCE;
break;
default:
return CMD_RET_USAGE;
}
}
}
debug("Final value for argc=%d\n", argc);
env_id++;
while (--argc > 0) {
char *name = *++argv;
if (!hdelete_r(name, &env_htab, env_flag))
ret = 1;
}
return ret;
}
#ifdef CONFIG_CMD_EXPORTENV
/*
* env export [-t | -b | -c] [-s size] addr [var ...]
* -t: export as text format; if size is given, data will be
* padded with '\0' bytes; if not, one terminating '\0'
* will be added (which is included in the "filesize"
* setting so you can for exmple copy this to flash and
* keep the termination).
* -b: export as binary format (name=value pairs separated by
* '\0', list end marked by double "\0\0")
* -c: export as checksum protected environment format as
* used for example by "saveenv" command
* -s size:
* size of output buffer
* addr: memory address where environment gets stored
* var... List of variable names that get included into the
* export. Without arguments, the whole environment gets
* exported.
*
* With "-c" and size is NOT given, then the export command will
* format the data as currently used for the persistent storage,
* i. e. it will use CONFIG_ENV_SECT_SIZE as output block size and
* prepend a valid CRC32 checksum and, in case of resundant
* environment, a "current" redundancy flag. If size is given, this
* value will be used instead of CONFIG_ENV_SECT_SIZE; again, CRC32
* checksum and redundancy flag will be inserted.
*
* With "-b" and "-t", always only the real data (including a
* terminating '\0' byte) will be written; here the optional size
* argument will be used to make sure not to overflow the user
* provided buffer; the command will abort if the size is not
* sufficient. Any remainign space will be '\0' padded.
*
* On successful return, the variable "filesize" will be set.
* Note that filesize includes the trailing/terminating '\0' byte(s).
*
* Usage szenario: create a text snapshot/backup of the current settings:
*
* => env export -t 100000
* => era ${backup_addr} +${filesize}
* => cp.b 100000 ${backup_addr} ${filesize}
*
* Re-import this snapshot, deleting all other settings:
*
* => env import -d -t ${backup_addr}
*/
static int do_env_export(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
char buf[32];
char *addr, *cmd, *res;
size_t size = 0;
ssize_t len;
env_t *envp;
char sep = '\n';
int chk = 0;
int fmt = 0;
cmd = *argv;
while (--argc > 0 && **++argv == '-') {
char *arg = *argv;
while (*++arg) {
switch (*arg) {
case 'b': /* raw binary format */
if (fmt++)
goto sep_err;
sep = '\0';
break;
case 'c': /* external checksum format */
if (fmt++)
goto sep_err;
sep = '\0';
chk = 1;
break;
case 's': /* size given */
if (--argc <= 0)
return cmd_usage(cmdtp);
size = simple_strtoul(*++argv, NULL, 16);
goto NXTARG;
case 't': /* text format */
if (fmt++)
goto sep_err;
sep = '\n';
break;
default:
return CMD_RET_USAGE;
}
}
NXTARG: ;
}
if (argc < 1)
return CMD_RET_USAGE;
addr = (char *)simple_strtoul(argv[0], NULL, 16);
if (size)
memset(addr, '\0', size);
argc--;
argv++;
if (sep) { /* export as text file */
len = hexport_r(&env_htab, sep,
H_MATCH_KEY | H_MATCH_IDENT,
&addr, size, argc, argv);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
return 1;
}
sprintf(buf, "%zX", (size_t)len);
setenv("filesize", buf);
return 0;
}
envp = (env_t *)addr;
if (chk) /* export as checksum protected block */
res = (char *)envp->data;
else /* export as raw binary data */
res = addr;
len = hexport_r(&env_htab, '\0',
H_MATCH_KEY | H_MATCH_IDENT,
&res, ENV_SIZE, argc, argv);
if (len < 0) {
error("Cannot export environment: errno = %d\n", errno);
return 1;
}
if (chk) {
envp->crc = crc32(0, envp->data, ENV_SIZE);
#ifdef CONFIG_ENV_ADDR_REDUND
envp->flags = ACTIVE_FLAG;
#endif
}
setenv_hex("filesize", len + offsetof(env_t, data));
return 0;
sep_err:
printf("## %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n", cmd);
return 1;
}
#endif
#ifdef CONFIG_CMD_IMPORTENV
/*
* env import [-d] [-t | -b | -c] addr [size]
* -d: delete existing environment before importing;
* otherwise overwrite / append to existion definitions
* -t: assume text format; either "size" must be given or the
* text data must be '\0' terminated
* -b: assume binary format ('\0' separated, "\0\0" terminated)
* -c: assume checksum protected environment format
* addr: memory address to read from
* size: length of input data; if missing, proper '\0'
* termination is mandatory
*/
static int do_env_import(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
char *cmd, *addr;
char sep = '\n';
int chk = 0;
int fmt = 0;
int del = 0;
size_t size;
cmd = *argv;
while (--argc > 0 && **++argv == '-') {
char *arg = *argv;
while (*++arg) {
switch (*arg) {
case 'b': /* raw binary format */
if (fmt++)
goto sep_err;
sep = '\0';
break;
case 'c': /* external checksum format */
if (fmt++)
goto sep_err;
sep = '\0';
chk = 1;
break;
case 't': /* text format */
if (fmt++)
goto sep_err;
sep = '\n';
break;
case 'd':
del = 1;
break;
default:
return CMD_RET_USAGE;
}
}
}
if (argc < 1)
return CMD_RET_USAGE;
if (!fmt)
printf("## Warning: defaulting to text format\n");
addr = (char *)simple_strtoul(argv[0], NULL, 16);
if (argc == 2) {
size = simple_strtoul(argv[1], NULL, 16);
} else {
char *s = addr;
size = 0;
while (size < MAX_ENV_SIZE) {
if ((*s == sep) && (*(s+1) == '\0'))
break;
++s;
++size;
}
if (size == MAX_ENV_SIZE) {
printf("## Warning: Input data exceeds %d bytes"
" - truncated\n", MAX_ENV_SIZE);
}
size += 2;
printf("## Info: input data size = %zu = 0x%zX\n", size, size);
}
if (chk) {
uint32_t crc;
env_t *ep = (env_t *)addr;
size -= offsetof(env_t, data);
memcpy(&crc, &ep->crc, sizeof(crc));
if (crc32(0, ep->data, size) != crc) {
puts("## Error: bad CRC, import failed\n");
return 1;
}
addr = (char *)ep->data;
}
if (himport_r(&env_htab, addr, size, sep, del ? 0 : H_NOCLEAR,
0, NULL) == 0) {
error("Environment import failed: errno = %d\n", errno);
return 1;
}
gd->flags |= GD_FLG_ENV_READY;
return 0;
sep_err:
printf("## %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n",
cmd);
return 1;
}
#endif
/*
* New command line interface: "env" command with subcommands
*/
static cmd_tbl_t cmd_env_sub[] = {
#if defined(CONFIG_CMD_ASKENV)
U_BOOT_CMD_MKENT(ask, CONFIG_SYS_MAXARGS, 1, do_env_ask, "", ""),
#endif
U_BOOT_CMD_MKENT(default, 1, 0, do_env_default, "", ""),
U_BOOT_CMD_MKENT(delete, CONFIG_SYS_MAXARGS, 0, do_env_delete, "", ""),
#if defined(CONFIG_CMD_EDITENV)
U_BOOT_CMD_MKENT(edit, 2, 0, do_env_edit, "", ""),
#endif
#if defined(CONFIG_CMD_ENV_CALLBACK)
U_BOOT_CMD_MKENT(callbacks, 1, 0, do_env_callback, "", ""),
#endif
#if defined(CONFIG_CMD_ENV_FLAGS)
U_BOOT_CMD_MKENT(flags, 1, 0, do_env_flags, "", ""),
#endif
#if defined(CONFIG_CMD_EXPORTENV)
U_BOOT_CMD_MKENT(export, 4, 0, do_env_export, "", ""),
#endif
#if defined(CONFIG_CMD_GREPENV)
U_BOOT_CMD_MKENT(grep, CONFIG_SYS_MAXARGS, 1, do_env_grep, "", ""),
#endif
#if defined(CONFIG_CMD_IMPORTENV)
U_BOOT_CMD_MKENT(import, 5, 0, do_env_import, "", ""),
#endif
U_BOOT_CMD_MKENT(print, CONFIG_SYS_MAXARGS, 1, do_env_print, "", ""),
#if defined(CONFIG_CMD_RUN)
U_BOOT_CMD_MKENT(run, CONFIG_SYS_MAXARGS, 1, do_run, "", ""),
#endif
#if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
U_BOOT_CMD_MKENT(save, 1, 0, do_env_save, "", ""),
#endif
U_BOOT_CMD_MKENT(set, CONFIG_SYS_MAXARGS, 0, do_env_set, "", ""),
};
#if defined(CONFIG_NEEDS_MANUAL_RELOC)
void env_reloc(void)
{
fixup_cmdtable(cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
}
#endif
static int do_env(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
cmd_tbl_t *cp;
if (argc < 2)
return CMD_RET_USAGE;
/* drop initial "env" arg */
argc--;
argv++;
cp = find_cmd_tbl(argv[0], cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
if (cp)
return cp->cmd(cmdtp, flag, argc, argv);
return CMD_RET_USAGE;
}
#ifdef CONFIG_SYS_LONGHELP
static char env_help_text[] =
#if defined(CONFIG_CMD_ASKENV)
"ask name [message] [size] - ask for environment variable\nenv "
#endif
#if defined(CONFIG_CMD_ENV_CALLBACK)
"callbacks - print callbacks and their associated variables\nenv "
#endif
"default [-f] -a - [forcibly] reset default environment\n"
"env default [-f] var [...] - [forcibly] reset variable(s) to their default values\n"
"env delete [-f] var [...] - [forcibly] delete variable(s)\n"
#if defined(CONFIG_CMD_EDITENV)
"env edit name - edit environment variable\n"
#endif
#if defined(CONFIG_CMD_EXPORTENV)
"env export [-t | -b | -c] [-s size] addr [var ...] - export environment\n"
#endif
#if defined(CONFIG_CMD_ENV_FLAGS)
"env flags - print variables that have non-default flags\n"
#endif
#if defined(CONFIG_CMD_GREPENV)
#ifdef CONFIG_REGEX
"env grep [-e] [-n | -v | -b] string [...] - search environment\n"
#else
"env grep [-n | -v | -b] string [...] - search environment\n"
#endif
#endif
#if defined(CONFIG_CMD_IMPORTENV)
"env import [-d] [-t | -b | -c] addr [size] - import environment\n"
#endif
"env print [-a | name ...] - print environment\n"
#if defined(CONFIG_CMD_RUN)
"env run var [...] - run commands in an environment variable\n"
#endif
#if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
"env save - save environment\n"
#endif
"env set [-f] name [arg ...]\n";
#endif
U_BOOT_CMD(
env, CONFIG_SYS_MAXARGS, 1, do_env,
"environment handling commands", env_help_text
);
/*
* Old command line interface, kept for compatibility
*/
#if defined(CONFIG_CMD_EDITENV)
U_BOOT_CMD_COMPLETE(
editenv, 2, 0, do_env_edit,
"edit environment variable",
"name\n"
" - edit environment variable 'name'",
var_complete
);
#endif
U_BOOT_CMD_COMPLETE(
printenv, CONFIG_SYS_MAXARGS, 1, do_env_print,
"print environment variables",
"[-a]\n - print [all] values of all environment variables\n"
"printenv name ...\n"
" - print value of environment variable 'name'",
var_complete
);
#ifdef CONFIG_CMD_GREPENV
U_BOOT_CMD_COMPLETE(
grepenv, CONFIG_SYS_MAXARGS, 0, do_env_grep,
"search environment variables",
#ifdef CONFIG_REGEX
"[-e] [-n | -v | -b] string ...\n"
#else
"[-n | -v | -b] string ...\n"
#endif
" - list environment name=value pairs matching 'string'\n"
#ifdef CONFIG_REGEX
" \"-e\": enable regular expressions;\n"
#endif
" \"-n\": search variable names; \"-v\": search values;\n"
" \"-b\": search both names and values (default)",
var_complete
);
#endif
U_BOOT_CMD_COMPLETE(
setenv, CONFIG_SYS_MAXARGS, 0, do_env_set,
"set environment variables",
"[-f] name value ...\n"
" - [forcibly] set environment variable 'name' to 'value ...'\n"
"setenv [-f] name\n"
" - [forcibly] delete environment variable 'name'",
var_complete
);
#if defined(CONFIG_CMD_ASKENV)
U_BOOT_CMD(
askenv, CONFIG_SYS_MAXARGS, 1, do_env_ask,
"get environment variables from stdin",
"name [message] [size]\n"
" - get environment variable 'name' from stdin (max 'size' chars)"
);
#endif
#if defined(CONFIG_CMD_RUN)
U_BOOT_CMD_COMPLETE(
run, CONFIG_SYS_MAXARGS, 1, do_run,
"run commands in an environment variable",
"var [...]\n"
" - run the commands in the environment variable(s) 'var'",
var_complete
);
#endif
#endif /* CONFIG_SPL_BUILD */
| gpl-3.0 |
AnarchiA99/verlihub | src/cconfmysql.cpp | 1 | 10919 | /*
Copyright (C) 2003-2005 Daniel Muller, dan at verliba dot cz
Copyright (C) 2006-2016 Verlihub Team, info at verlihub dot net
Verlihub is free software; You can redistribute it
and 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.
Verlihub 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.
Please see http://www.gnu.org/licenses/ for a copy
of the GNU General Public License.
*/
#include "cconfmysql.h"
#include <algorithm>
#include <string.h>
using namespace std;
namespace nVerliHub {
using namespace nConfig;
using namespace nMySQL;
using namespace nEnums;
namespace nMySQL {
cMySQLColumn::cMySQLColumn(): mNull(false)
{}
cMySQLColumn::~cMySQLColumn()
{}
void cMySQLColumn::AppendDesc(ostream &os) const
{
string isNull;
mNull ? isNull = "" : isNull = " NOT NULL";
os << mName << " " << mType << isNull;
if (mDefault.size()) {
os << " DEFAULT '";
cConfMySQL::WriteStringConstant(os, mDefault);
os << "'";
}
}
void cMySQLColumn::ReadFromRow(const MYSQL_ROW &row)
{
mName = row[0] ? row[0] : ""; // just for sure
mType = row[1] ? row[1] : ""; // just for sure
mDefault = row[4] ? row[4] : "";
mNull = ((row[2] != NULL) && strlen(row[2]));
}
bool cMySQLColumn::operator!=(const cMySQLColumn &col) const
{
return (this->mType != col.mType) || ((this->mDefault != col.mDefault) && this->mDefault.size());
}
cMySQLTable::cMySQLTable(cMySQL &mysql): cObj("cMySQLTable"), mQuery(mysql)
{}
cMySQLTable::~cMySQLTable()
{}
bool cMySQLTable::GetCollation()
{
int i = 0, n;
MYSQL_ROW row;
mQuery.OStream() << "SELECT TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_NAME='" << mName << "' AND TABLE_SCHEMA='" << mQuery.getMySQL().GetDBName() << "'";
if (mQuery.Query() <= 0) {
mQuery.Clear();
return false;
}
n = mQuery.StoreResult();
cMySQLColumn col;
for (; i < n; i++) {
row = mQuery.Row();
mCollation = row[0];
}
mQuery.Clear();
return true;
}
bool cMySQLTable::GetDescription(const string &tableName)
{
int i = 0, n;
MYSQL_ROW row;
mName = tableName;
mQuery.OStream() << "SHOW COLUMNS FROM " << tableName;
if (mQuery.Query() <= 0) {
mQuery.Clear();
return false;
}
n = mQuery.StoreResult();
cMySQLColumn col;
for (; i < n; i++) { // 0=Field, 1=Type, 2=Null, 3=Key, 4=Default, 5=Extra
row = mQuery.Row();
col.ReadFromRow(row);
mColumns.push_back(col);
}
mQuery.Clear();
return true;
}
const cMySQLColumn * cMySQLTable::GetColumn(const string &colName) const
{
vector<cMySQLColumn>::const_iterator it;
for (it = mColumns.begin(); it != mColumns.end(); ++it) {
if (it->mName == colName)
return &(*it);
}
return NULL;
}
bool cMySQLTable::CreateTable()
{
vector<cMySQLColumn>::iterator it;
bool IsFirstCol = true;
mQuery.OStream() << "CREATE TABLE IF NOT EXISTS " << mName << " ("; // try to create first
for (it = mColumns.begin(); it != mColumns.end(); ++it) {
mQuery.OStream() << (IsFirstCol ? "" : ", ");
it->AppendDesc(mQuery.OStream());
IsFirstCol = false;
}
if (mExtra.size())
mQuery.OStream() << ", " << mExtra;
mQuery.OStream() << ") CHARACTER SET " << DEFAULT_CHARSET << " COLLATE " << DEFAULT_COLLATION;
mQuery.Query();
mQuery.Clear();
return true;
}
void cMySQLTable::TruncateTable()
{
mQuery.OStream() << "TRUNCATE TABLE " << mName;
mQuery.Query();
mQuery.Clear();
}
bool cMySQLTable::AutoAlterTable(const cMySQLTable &original)
{
vector<cMySQLColumn>::iterator it;
const cMySQLColumn *col;
bool NeedAdd = false, NeedModif = false, result = false;
for (it = mColumns.begin(); it != mColumns.end(); ++it) {
NeedAdd = NeedModif = false;
if ((col = original.GetColumn(it->mName)) == NULL)
NeedAdd = true;
else
NeedModif = ((*it) != (*col));
if (NeedAdd || NeedModif) {
result = true;
if (Log(1))
LogStream() << "Altering table " << mName << (NeedAdd ? " add column " : " modify column") << it->mName << " with type: " << it->mType << endl;
mQuery.OStream() << "ALTER TABLE " << mName << (NeedAdd ? " ADD COLUMN " : " MODIFY COLUMN ");
it->AppendDesc(mQuery.OStream());
mQuery.Query();
mQuery.Clear();
}
}
if (GetCollation() && (mCollation != DEFAULT_COLLATION)) {
if (Log(1))
LogStream() << "Altering table " << mName << ", setting character set to " << DEFAULT_CHARSET << " and collation to " << DEFAULT_COLLATION << endl;
mQuery.OStream() << "ALTER TABLE " << mName << " CHARACTER SET " << DEFAULT_CHARSET << " COLLATE " << DEFAULT_COLLATION;
mQuery.Query();
mQuery.Clear();
}
return result;
}
}; // namespace nMySQL
namespace nConfig {
cConfMySQL::cConfMySQL(cMySQL &mysql): mMySQL(mysql), mQuery(mMySQL), mMySQLTable(mMySQL)
{
if (mItemCreator != NULL)
delete mItemCreator;
mItemCreator = new cMySQLItemCreator;
}
cConfMySQL::~cConfMySQL()
{}
void cConfMySQL::CreateTable()
{
cMySQLTable existing_desc(mMySQL);
if (existing_desc.GetDescription(mMySQLTable.mName))
mMySQLTable.AutoAlterTable(existing_desc);
else
mMySQLTable.CreateTable();
}
void cConfMySQL::TruncateTable()
{
mMySQLTable.TruncateTable();
}
int cConfMySQL::Save()
{
SavePK(false);
return 0;
}
int cConfMySQL::Load()
{
return Load(mQuery);
}
int cConfMySQL::Load(cQuery &Query)
{
MYSQL_ROW row;
if (!(row = Query.Row()))
return -1;
for_each(mhItems.begin(), mhItems.end(), ufLoad(row));
return 0;
}
/** return -1 on error, otherwinse number of results */
int cConfMySQL::StartQuery()
{
return StartQuery(mQuery);
}
int cConfMySQL::StartQuery(cQuery &Query)
{
int ret = Query.Query();
if (ret <= 0) {
Query.Clear();
return ret;
}
Query.StoreResult();
mCols = Query.Cols();
return ret;
}
/** return -1 on error, otherwinse number of results */
int cConfMySQL::StartQuery(string query)
{
mQuery.OStream() << query;
return StartQuery();
}
int cConfMySQL::EndQuery()
{
return EndQuery(mQuery);
}
int cConfMySQL::EndQuery(cQuery &Query)
{
Query.Clear();
return 0;
}
void cConfMySQL::AddPrimaryKey(const char *key)
{
string Key(key);
tItemHashType Hash = msHasher(Key);
cConfigItemBase *item = mhItems.GetByHash(Hash);
if (item != NULL)
mPrimaryKey.AddWithHash(item, Hash);
}
void cConfMySQL::WherePKey(ostream &os)
{
os << " WHERE (";
AllPKFields(os, true, true, false, string(" AND "));
os << " )";
}
void cConfMySQL::AllFields(ostream &os, bool DoF, bool DoV, bool IsAff, string joint)
{
for_each(mhItems.begin(), mhItems.end(), ufEqual(os, joint , DoF, DoV, IsAff));
}
void cConfMySQL::AllPKFields(ostream &os, bool DoF, bool DoV, bool IsAff, string joint)
{
for_each(mPrimaryKey.begin(), mPrimaryKey.end(), ufEqual(os, joint , DoF, DoV, IsAff));
}
void cConfMySQL::SelectFields(ostream &os)
{
os << "SELECT ";
AllFields(os, true, false, false, string(", "));
os << " FROM " << mMySQLTable.mName << " ";
}
void cConfMySQL::UpdateFields(ostream &os)
{
os << "UPDATE " << mMySQLTable.mName << " SET ";
AllFields(mQuery.OStream(), true, true, true, string(", "));
}
bool cConfMySQL::LoadPK()
{
ostringstream query;
SelectFields(query);
WherePKey(query);
if (StartQuery(query.str()) == -1)
return false;
bool found = (Load() >= 0);
EndQuery();
return found;
}
bool cConfMySQL::SavePK(bool dup)
{
mQuery.OStream() << "INSERT IGNORE INTO " << mMySQLTable.mName << " (";
AllFields(mQuery.OStream(), true, false, false, string(", "));
mQuery.OStream() << ") VALUES (";
AllFields(mQuery.OStream(), false, true, true, string(", "));
mQuery.OStream() << ")";
if (dup) {
mQuery.OStream() << " ON DUPLICATE SET ";
AllFields(mQuery.OStream(), true, true, true, string(", "));
}
bool ret = mQuery.Query();
mQuery.Clear();
return ret;
}
void cConfMySQL::DeletePK()
{
mQuery.Clear();
mQuery.OStream() << "DELETE FROM " << mMySQLTable.mName << " ";
WherePKey(mQuery.OStream());
mQuery.Query();
mQuery.Clear();
}
cConfMySQL::db_iterator &cConfMySQL::db_begin()
{
return db_begin(mQuery);
}
cConfMySQL::db_iterator &cConfMySQL::db_begin(cQuery &Query)
{
if ((-1 == this->StartQuery(Query)) || (Load(Query) < 0))
mDBBegin = NULL;
else
mDBBegin = db_iterator(this, &Query);
return mDBBegin;
}
cConfMySQL::db_iterator &cConfMySQL::db_iterator::operator++()
{
if ((mConf != NULL) && (mQuery != NULL)) {
if (mConf->Load(*mQuery) < 0) {
mConf->EndQuery(*mQuery);
mConf = NULL;
mQuery = NULL;
}
}
return *this;
}
ostream &cConfigItemMySQLPChar::WriteToStream (ostream& os)
{
if (!IsEmpty()) {
os << '"';
cConfMySQL::WriteStringConstant(os, this->Data());
os << '"';
} else
os << " NULL ";
return os;
}
ostream &cConfigItemMySQLString::WriteToStream (ostream& os)
{
if (!IsEmpty()) {
os << '"';
cConfMySQL::WriteStringConstant(os, this->Data());
os << '"';
} else
os << " NULL ";
return os;
}
bool cConfMySQL::UpdatePKVar(const char* var_name, string &new_val)
{
cConfigItemBase * item = NULL;
string var(var_name);
item = operator[](var);
if (!item)
return false;
LoadPK();
item->ConvertFrom(new_val);
return UpdatePKVar(item);
}
bool cConfMySQL::UpdatePKVar(cConfigItemBase *item)
{
mQuery.OStream() << "UPDATE " << mMySQLTable.mName << " SET ";
ufEqual(mQuery.OStream(), string(", "), true, true, true)(item);
WherePKey(mQuery.OStream());
bool ret = mQuery.Query();
mQuery.Clear();
return ret;
}
bool cConfMySQL::UpdatePK()
{
return UpdatePK(mQuery);
}
bool cConfMySQL::UpdatePK(cQuery &Query)
{
UpdateFields(Query.OStream());
WherePKey(Query.OStream());
bool ret = Query.Query();
Query.Clear();
return ret;
}
bool cConfMySQL::UpdatePKVar(const char *field)
{
cConfigItemBase *item = operator[](field);
if (!item)
return false;
return UpdatePKVar(item);
}
void cConfMySQL::WriteStringConstant(ostream &os, const string &str)
{
string tmp;
// replace all \ by "\\"
// replace all " by \"
size_t pos = 0, lastpos = 0;
char c;
while ((str.npos != lastpos) && (str.npos != (pos = str.find_first_of("\\\"'`", lastpos)))) {
tmp.append(str, lastpos, pos - lastpos);
tmp.append("\\");
c = str[pos];
tmp.append(&c, 1);
lastpos = pos + 1;
}
if (str.npos != lastpos)
tmp.append(str, lastpos, pos - lastpos);
os << tmp;
}
void cConfMySQL::ufEqual::operator()(cConfigItemBase* item)
{
if (!start)
mOS << mJoint;
else
start = false;
if (mDoField)
mOS << (item->mName);
if (mDoValue) {
tItemType TypeId = item->GetTypeID();
bool IsNull = item->IsEmpty() && ((TypeId == eIT_TIMET) || (TypeId == eIT_LONG));
if (mDoField) {
if (IsNull && !mIsAffect)
mOS << " IS ";
else
mOS << " = ";
}
if (IsNull)
mOS << "NULL ";
else
item->WriteToStream(mOS);
}
}
}; // namespace nConfig
}; // namespace nVerliHub
| gpl-3.0 |
gnu-user/qa-project | FrontEnd/src/Logout.cpp | 1 | 1365 | /**
* Swift Ticket -- Front End Interface
*
* Copyright (C) 2013, Jonathan Gillett, Daniel Smullen, and Rayan Alfaheid
* 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 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 "../include/Logout.hpp"
Logout::Logout(User current_user)
{
/* If the user has not logged in throw exception */
if (! current_user.get_status())
{
throw Exception(MUST_LOGIN);
}
this->code = "00";
this->user = current_user;
save_transaction();
}
void Logout::save_transaction()
{
this->transaction = format(
code,
user.get_username(),
user.get_type(),
user.get_credit()
);
}
| gpl-3.0 |
cooljeanius/CEGUI | cegui/src/ScriptingModules/PythonScriptModule/bindings/output/CEGUI/NamedArea.pypp.cpp | 1 | 3794 | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "python_CEGUI.h"
#include "NamedArea.pypp.hpp"
namespace bp = boost::python;
void register_NamedArea_class(){
{ //::CEGUI::NamedArea
typedef bp::class_< CEGUI::NamedArea > NamedArea_exposer_t;
NamedArea_exposer_t NamedArea_exposer = NamedArea_exposer_t( "NamedArea", "*!\n\
\n\
NamedArea defines an area for a component which may later be obtained\n\
and referenced by a name unique to the WidgetLook holding the NamedArea.\n\
*\n", bp::init< >() );
bp::scope NamedArea_scope( NamedArea_exposer );
NamedArea_exposer.def( bp::init< CEGUI::String const & >(( bp::arg("name") )) );
bp::implicitly_convertible< CEGUI::String const &, CEGUI::NamedArea >();
{ //::CEGUI::NamedArea::getArea
typedef ::CEGUI::ComponentArea const & ( ::CEGUI::NamedArea::*getArea_function_type )( ) const;
NamedArea_exposer.def(
"getArea"
, getArea_function_type( &::CEGUI::NamedArea::getArea )
, bp::return_value_policy< bp::copy_const_reference >()
, "*!\n\
\n\
Return the ComponentArea of this NamedArea\n\
\n\
@return\n\
ComponentArea object describing the NamedArea's current target area.\n\
*\n" );
}
{ //::CEGUI::NamedArea::getName
typedef ::CEGUI::String const & ( ::CEGUI::NamedArea::*getName_function_type )( ) const;
NamedArea_exposer.def(
"getName"
, getName_function_type( &::CEGUI::NamedArea::getName )
, bp::return_value_policy< bp::copy_const_reference >()
, "*!\n\
\n\
Return the name of this NamedArea.\n\
\n\
@return\n\
String object holding the name of this NamedArea.\n\
*\n" );
}
{ //::CEGUI::NamedArea::setArea
typedef void ( ::CEGUI::NamedArea::*setArea_function_type )( ::CEGUI::ComponentArea const & ) ;
NamedArea_exposer.def(
"setArea"
, setArea_function_type( &::CEGUI::NamedArea::setArea )
, ( bp::arg("area") )
, "*!\n\
\n\
Set the Area for this NamedArea.\n\
\n\
@param area\n\
ComponentArea object describing a new target area for the NamedArea..\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::NamedArea::writeXMLToStream
typedef void ( ::CEGUI::NamedArea::*writeXMLToStream_function_type )( ::CEGUI::XMLSerializer & ) const;
NamedArea_exposer.def(
"writeXMLToStream"
, writeXMLToStream_function_type( &::CEGUI::NamedArea::writeXMLToStream )
, ( bp::arg("xml_stream") )
, "*!\n\
\n\
Writes an xml representation of this NamedArea to out_stream.\n\
\n\
@param out_stream\n\
Stream where xml data should be output.\n\
\n\
@param indentLevel\n\
Current XML indentation level\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
}
}
| gpl-3.0 |
mymedia2/tdesktop | Telegram/SourceFiles/data/data_user.cpp | 1 | 6978 | /*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "data/data_user.h"
#include "storage/localstorage.h"
#include "main/main_session.h"
#include "data/data_session.h"
#include "data/data_changes.h"
#include "ui/text/text_options.h"
#include "apiwrap.h"
#include "lang/lang_keys.h"
namespace {
// User with hidden last seen stays online in UI for such amount of seconds.
constexpr auto kSetOnlineAfterActivity = TimeId(30);
using UpdateFlag = Data::PeerUpdate::Flag;
} // namespace
UserData::UserData(not_null<Data::Session*> owner, PeerId id)
: PeerData(owner, id)
, _flags((id == owner->session().userPeerId()) ? Flag::Self : Flag(0)) {
}
bool UserData::canShareThisContact() const {
return canShareThisContactFast()
|| !owner().findContactPhone(peerToUser(id)).isEmpty();
}
void UserData::setIsContact(bool is) {
const auto status = is
? ContactStatus::Contact
: ContactStatus::NotContact;
if (_contactStatus != status) {
_contactStatus = status;
session().changes().peerUpdated(this, UpdateFlag::IsContact);
}
}
// see Serialize::readPeer as well
void UserData::setPhoto(const MTPUserProfilePhoto &photo) {
photo.match([&](const MTPDuserProfilePhoto &data) {
updateUserpic(data.vphoto_id().v, data.vdc_id().v);
}, [&](const MTPDuserProfilePhotoEmpty &) {
clearUserpic();
});
}
auto UserData::unavailableReasons() const
-> const std::vector<Data::UnavailableReason> & {
return _unavailableReasons;
}
void UserData::setUnavailableReasons(
std::vector<Data::UnavailableReason> &&reasons) {
if (_unavailableReasons != reasons) {
_unavailableReasons = std::move(reasons);
session().changes().peerUpdated(
this,
UpdateFlag::UnavailableReason);
}
}
void UserData::setCommonChatsCount(int count) {
if (_commonChatsCount != count) {
_commonChatsCount = count;
session().changes().peerUpdated(this, UpdateFlag::CommonChats);
}
}
void UserData::setName(const QString &newFirstName, const QString &newLastName, const QString &newPhoneName, const QString &newUsername) {
bool changeName = !newFirstName.isEmpty() || !newLastName.isEmpty();
QString newFullName;
if (changeName && newFirstName.trimmed().isEmpty()) {
firstName = newLastName;
lastName = QString();
newFullName = firstName;
} else {
if (changeName) {
firstName = newFirstName;
lastName = newLastName;
}
newFullName = lastName.isEmpty() ? firstName : tr::lng_full_name(tr::now, lt_first_name, firstName, lt_last_name, lastName);
}
updateNameDelayed(newFullName, newPhoneName, newUsername);
}
void UserData::setPhone(const QString &newPhone) {
if (_phone != newPhone) {
_phone = newPhone;
}
}
void UserData::setBotInfoVersion(int version) {
if (version < 0) {
// We don't support bots becoming non-bots.
} else if (!botInfo) {
botInfo = std::make_unique<BotInfo>();
botInfo->version = version;
owner().userIsBotChanged(this);
} else if (botInfo->version < version) {
if (!botInfo->commands.empty()) {
botInfo->commands.clear();
owner().botCommandsChanged(this);
}
botInfo->description.clear();
botInfo->version = version;
botInfo->inited = false;
}
}
void UserData::setBotInfo(const MTPBotInfo &info) {
switch (info.type()) {
case mtpc_botInfo: {
const auto &d = info.c_botInfo();
if (peerFromUser(d.vuser_id().v) != id || !isBot()) {
return;
}
QString desc = qs(d.vdescription());
if (botInfo->description != desc) {
botInfo->description = desc;
botInfo->text = Ui::Text::String(st::msgMinWidth);
}
const auto changedCommands = Data::UpdateBotCommands(
botInfo->commands,
d.vcommands());
botInfo->inited = true;
if (changedCommands) {
owner().botCommandsChanged(this);
}
} break;
}
}
void UserData::setNameOrPhone(const QString &newNameOrPhone) {
if (nameOrPhone != newNameOrPhone) {
nameOrPhone = newNameOrPhone;
phoneText.setText(
st::msgNameStyle,
nameOrPhone,
Ui::NameTextOptions());
}
}
void UserData::madeAction(TimeId when) {
if (isBot() || isServiceUser() || when <= 0) {
return;
} else if (onlineTill <= 0 && -onlineTill < when) {
onlineTill = -when - kSetOnlineAfterActivity;
session().changes().peerUpdated(this, UpdateFlag::OnlineStatus);
} else if (onlineTill > 0 && onlineTill < when + 1) {
onlineTill = when + kSetOnlineAfterActivity;
session().changes().peerUpdated(this, UpdateFlag::OnlineStatus);
}
}
void UserData::setAccessHash(uint64 accessHash) {
if (accessHash == kInaccessibleAccessHashOld) {
_accessHash = 0;
_flags.add(Flag::Deleted);
} else {
_accessHash = accessHash;
}
}
void UserData::setFlags(UserDataFlags which) {
_flags.set((flags() & UserDataFlag::Self)
| (which & ~UserDataFlag::Self));
}
void UserData::addFlags(UserDataFlags which) {
_flags.add(which & ~UserDataFlag::Self);
}
void UserData::removeFlags(UserDataFlags which) {
_flags.remove(which & ~UserDataFlag::Self);
}
void UserData::setCallsStatus(CallsStatus callsStatus) {
if (callsStatus != _callsStatus) {
_callsStatus = callsStatus;
session().changes().peerUpdated(this, UpdateFlag::HasCalls);
}
}
bool UserData::hasCalls() const {
return (callsStatus() != CallsStatus::Disabled)
&& (callsStatus() != CallsStatus::Unknown);
}
namespace Data {
void ApplyUserUpdate(not_null<UserData*> user, const MTPDuserFull &update) {
if (const auto photo = update.vprofile_photo()) {
user->owner().processPhoto(*photo);
}
user->setSettings(update.vsettings());
user->session().api().applyNotifySettings(
MTP_inputNotifyPeer(user->input),
update.vnotify_settings());
user->setMessagesTTL(update.vttl_period().value_or_empty());
if (const auto info = update.vbot_info()) {
user->setBotInfo(*info);
} else {
user->setBotInfoVersion(-1);
}
if (const auto pinned = update.vpinned_msg_id()) {
SetTopPinnedMessageId(user, pinned->v);
}
using Flag = UserDataFlag;
const auto mask = Flag::Blocked
| Flag::HasPhoneCalls
| Flag::PhoneCallsPrivate
| Flag::CanPinMessages;
user->setFlags((user->flags() & ~mask)
| (update.is_phone_calls_private() ? Flag::PhoneCallsPrivate : Flag())
| (update.is_phone_calls_available() ? Flag::HasPhoneCalls : Flag())
| (update.is_can_pin_message() ? Flag::CanPinMessages : Flag())
| (update.is_blocked() ? Flag::Blocked : Flag()));
user->setIsBlocked(update.is_blocked());
user->setCallsStatus(update.is_phone_calls_private()
? UserData::CallsStatus::Private
: update.is_phone_calls_available()
? UserData::CallsStatus::Enabled
: UserData::CallsStatus::Disabled);
user->setAbout(qs(update.vabout().value_or_empty()));
user->setCommonChatsCount(update.vcommon_chats_count().v);
user->checkFolder(update.vfolder_id().value_or_empty());
user->setThemeEmoji(qs(update.vtheme_emoticon().value_or_empty()));
user->fullUpdated();
}
} // namespace Data
| gpl-3.0 |
AaronVanGeffen/OpenRCT2 | src/openrct2/audio/Audio.cpp | 1 | 12885 | /*****************************************************************************
* Copyright (c) 2014-2020 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#include "audio.h"
#include "../Context.h"
#include "../Intro.h"
#include "../OpenRCT2.h"
#include "../config/Config.h"
#include "../core/File.h"
#include "../core/FileStream.hpp"
#include "../core/Memory.hpp"
#include "../core/String.hpp"
#include "../interface/Viewport.h"
#include "../localisation/Language.h"
#include "../localisation/StringIds.h"
#include "../peep/Peep.h"
#include "../ride/Ride.h"
#include "../ui/UiContext.h"
#include "../util/Util.h"
#include "AudioContext.h"
#include "AudioMixer.h"
#include <algorithm>
#include <vector>
namespace OpenRCT2::Audio
{
struct AudioParams
{
bool in_range;
int32_t volume;
int32_t pan;
};
static std::vector<std::string> _audioDevices;
static int32_t _currentAudioDevice = -1;
bool gGameSoundsOff = false;
int32_t gVolumeAdjustZoom = 0;
void* gTitleMusicChannel = nullptr;
void* gWeatherSoundChannel = nullptr;
RideMusic gRideMusicList[MaxRideMusic];
RideMusicParams gRideMusicParamsList[MaxRideMusic];
RideMusicParams* gRideMusicParamsListEnd;
VehicleSound gVehicleSoundList[MaxVehicleSounds];
// clang-format off
static int32_t SoundVolumeAdjust[RCT2SoundCount] =
{
0, // LiftClassic
0, // TrackFrictionClassicWood
0, // FrictionClassic
0, // Scream1
0, // Click1
0, // Click2
0, // PlaceItem
0, // Scream2
0, // Scream3
0, // Scream4
0, // Scream5
0, // Scream6
0, // LiftFrictionWheels
-400, // Purchase
0, // Crash
0, // LayingOutWater
0, // Water1
0, // Water2
0, // TrainWhistle
0, // TrainDeparting
-1000, // WaterSplash
0, // GoKartEngine
-800, // RideLaunch1
-1700, // RideLaunch2
-700, // Cough1
-700, // Cough2
-700, // Cough3
-700, // Cough4
0, // Rain
0, // Thunder1
0, // Thunder2
0, // TrackFrictionTrain
0, // TrackFrictionWater
0, // BalloonPop
-700, // MechanicFix
0, // Scream7
-2500, // ToiletFlush original value: -1000
0, // Click3
0, // Quack
0, // NewsItem
0, // WindowOpen
-900, // Laugh1
-900, // Laugh2
-900, // Laugh3
0, // Applause
-600, // HauntedHouseScare
-700, // HauntedHouseScream1
-700, // HauntedHouseScream2
-2550, // BlockBrakeClose
-2900, // BlockBrakeRelease
0, // Error
-3400, // BrakeRelease
0, // LiftArrow
0, // LiftWood
0, // TrackFrictionWood
0, // LiftWildMouse
0, // LiftBM
0, // TrackFrictionBM
0, // Scream8
0, // Tram
-2000, // DoorOpen
-2700, // DoorClose
-700 // Portcullis
};
// clang-format on
static AudioParams GetParametersFromLocation(SoundId soundId, const CoordsXYZ& location);
bool IsAvailable()
{
if (_currentAudioDevice == -1)
return false;
if (gGameSoundsOff)
return false;
if (!gConfigSound.sound_enabled)
return false;
if (gOpenRCT2Headless)
return false;
return true;
}
void Init()
{
if (str_is_null_or_empty(gConfigSound.device))
{
Mixer_Init(nullptr);
_currentAudioDevice = 0;
}
else
{
Mixer_Init(gConfigSound.device);
PopulateDevices();
for (int32_t i = 0; i < GetDeviceCount(); i++)
{
if (_audioDevices[i] == gConfigSound.device)
{
_currentAudioDevice = i;
}
}
}
}
void PopulateDevices()
{
auto audioContext = OpenRCT2::GetContext()->GetAudioContext();
std::vector<std::string> devices = audioContext->GetOutputDevices();
// Replace blanks with localised unknown string
for (auto& device : devices)
{
if (device.empty())
{
device = language_get_string(STR_OPTIONS_SOUND_VALUE_DEFAULT);
}
}
#ifndef __linux__
// The first device is always system default on Windows and macOS
std::string defaultDevice = language_get_string(STR_OPTIONS_SOUND_VALUE_DEFAULT);
devices.insert(devices.begin(), defaultDevice);
#endif
_audioDevices = devices;
}
void Play3D(SoundId soundId, const CoordsXYZ& loc)
{
if (!IsAvailable())
return;
AudioParams params = GetParametersFromLocation(soundId, loc);
if (params.in_range)
{
Play(soundId, params.volume, params.pan);
}
}
/**
* Returns the audio parameters to use when playing the specified sound at a virtual location.
* @param soundId The sound effect to be played.
* @param location The location at which the sound effect is to be played.
* @return The audio parameters to be used when playing this sound effect.
*/
static AudioParams GetParametersFromLocation(SoundId soundId, const CoordsXYZ& location)
{
int32_t volumeDown = 0;
AudioParams params;
params.in_range = true;
params.volume = 0;
params.pan = 0;
auto element = map_get_surface_element_at(location);
if (element && (element->GetBaseZ()) - 5 > location.z)
{
volumeDown = 10;
}
uint8_t rotation = get_current_rotation();
auto pos2 = translate_3d_to_2d_with_z(rotation, location);
rct_viewport* viewport = nullptr;
while ((viewport = window_get_previous_viewport(viewport)) != nullptr)
{
if (viewport->flags & VIEWPORT_FLAG_SOUND_ON)
{
int16_t vx = pos2.x - viewport->viewPos.x;
params.pan = viewport->pos.x + (vx / viewport->zoom);
params.volume = SoundVolumeAdjust[static_cast<uint8_t>(soundId)]
+ ((-1024 * viewport->zoom - 1) * (1 << volumeDown)) + 1;
if (!viewport->Contains(pos2) || params.volume < -10000)
{
params.in_range = false;
return params;
}
}
}
return params;
}
void Play(SoundId soundId, int32_t volume, int32_t pan)
{
if (gGameSoundsOff)
return;
int32_t mixerPan = 0;
if (pan != AUDIO_PLAY_AT_CENTRE)
{
int32_t x2 = pan << 16;
uint16_t screenWidth = std::max<int32_t>(64, OpenRCT2::GetContext()->GetUiContext()->GetWidth());
mixerPan = ((x2 / screenWidth) - 0x8000) >> 4;
}
Mixer_Play_Effect(soundId, MIXER_LOOP_NONE, DStoMixerVolume(volume), DStoMixerPan(mixerPan), 1, 1);
}
void PlayTitleMusic()
{
if (gGameSoundsOff || !(gScreenFlags & SCREEN_FLAGS_TITLE_DEMO) || gIntroState != IntroState::None)
{
StopTitleMusic();
return;
}
if (gTitleMusicChannel != nullptr)
{
return;
}
int32_t pathId;
switch (gConfigSound.title_music)
{
case 1:
pathId = PATH_ID_CSS50;
break;
case 2:
pathId = PATH_ID_CSS17;
break;
case 3:
pathId = (util_rand() & 1) ? PATH_ID_CSS50 : PATH_ID_CSS17;
break;
default:
return;
}
gTitleMusicChannel = Mixer_Play_Music(pathId, MIXER_LOOP_INFINITE, true);
if (gTitleMusicChannel != nullptr)
{
Mixer_Channel_SetGroup(gTitleMusicChannel, OpenRCT2::Audio::MixerGroup::TitleMusic);
}
}
void StopRideMusic()
{
for (auto& rideMusic : gRideMusicList)
{
if (rideMusic.ride_id != RIDE_ID_NULL)
{
rideMusic.ride_id = RIDE_ID_NULL;
if (rideMusic.sound_channel != nullptr)
{
Mixer_Stop_Channel(rideMusic.sound_channel);
}
}
}
}
void StopAll()
{
StopTitleMusic();
StopVehicleSounds();
StopRideMusic();
peep_stop_crowd_noise();
StopWeatherSound();
}
int32_t GetDeviceCount()
{
return static_cast<int32_t>(_audioDevices.size());
}
const std::string& GetDeviceName(int32_t index)
{
Guard::Assert(index >= 0 && index < GetDeviceCount());
if (index < 0 || index >= GetDeviceCount())
{
static std::string InvalidDevice = "Invalid Device";
return InvalidDevice;
}
return _audioDevices[index];
}
int32_t GetCurrentDeviceIndex()
{
return _currentAudioDevice;
}
void StopTitleMusic()
{
if (gTitleMusicChannel != nullptr)
{
Mixer_Stop_Channel(gTitleMusicChannel);
gTitleMusicChannel = nullptr;
}
}
void StopWeatherSound()
{
if (gWeatherSoundChannel != nullptr)
{
Mixer_Stop_Channel(gWeatherSoundChannel);
gWeatherSoundChannel = nullptr;
}
}
void InitRideSoundsAndInfo()
{
int32_t deviceNum = 0;
InitRideSounds(deviceNum);
for (auto& rideMusicInfo : gRideMusicInfoList)
{
const utf8* path = context_get_path_legacy(rideMusicInfo.path_id);
if (File::Exists(path))
{
try
{
auto fs = OpenRCT2::FileStream(path, OpenRCT2::FILE_MODE_OPEN);
uint32_t head = fs.ReadValue<uint32_t>();
if (head == 0x78787878)
{
rideMusicInfo.length = 0;
}
// The length used to be hardcoded, but we stopped doing that to allow replacement.
if (rideMusicInfo.length == 0)
{
rideMusicInfo.length = fs.GetLength();
}
}
catch (const std::exception&)
{
}
}
}
}
void InitRideSounds(int32_t device)
{
Close();
for (auto& vehicleSound : gVehicleSoundList)
{
vehicleSound.id = SoundIdNull;
}
_currentAudioDevice = device;
config_save_default();
for (auto& rideMusic : gRideMusicList)
{
rideMusic.ride_id = RIDE_ID_NULL;
}
}
void Close()
{
peep_stop_crowd_noise();
StopTitleMusic();
StopRideMusic();
StopWeatherSound();
_currentAudioDevice = -1;
}
void ToggleAllSounds()
{
gConfigSound.master_sound_enabled = !gConfigSound.master_sound_enabled;
if (gConfigSound.master_sound_enabled)
{
Resume();
}
else
{
StopTitleMusic();
Pause();
}
window_invalidate_by_class(WC_OPTIONS);
}
void Pause()
{
gGameSoundsOff = true;
StopVehicleSounds();
StopRideMusic();
peep_stop_crowd_noise();
StopWeatherSound();
}
void Resume()
{
gGameSoundsOff = false;
}
void StopVehicleSounds()
{
if (!IsAvailable())
return;
for (auto& vehicleSound : gVehicleSoundList)
{
if (vehicleSound.id != SoundIdNull)
{
vehicleSound.id = SoundIdNull;
if (vehicleSound.TrackSound.Id != SoundId::Null)
{
Mixer_Stop_Channel(vehicleSound.TrackSound.Channel);
}
if (vehicleSound.OtherSound.Id != SoundId::Null)
{
Mixer_Stop_Channel(vehicleSound.OtherSound.Channel);
}
}
}
}
} // namespace OpenRCT2::Audio
| gpl-3.0 |
Bootz/multicore-opimization | llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerRegistry.cpp | 1 | 5154 | //===--- CheckerRegistry.cpp - Maintains all available checkers -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Core/CheckerRegistry.h"
#include "clang/StaticAnalyzer/Core/CheckerOptInfo.h"
using namespace clang;
using namespace ento;
static const char PackageSeparator = '.';
typedef llvm::DenseSet<const CheckerRegistry::CheckerInfo *> CheckerInfoSet;
static bool checkerNameLT(const CheckerRegistry::CheckerInfo &a,
const CheckerRegistry::CheckerInfo &b) {
return a.FullName < b.FullName;
}
static bool isInPackage(const CheckerRegistry::CheckerInfo &checker,
StringRef packageName) {
// Does the checker's full name have the package as a prefix?
if (!checker.FullName.startswith(packageName))
return false;
// Is the package actually just the name of a specific checker?
if (checker.FullName.size() == packageName.size())
return true;
// Is the checker in the package (or a subpackage)?
if (checker.FullName[packageName.size()] == PackageSeparator)
return true;
return false;
}
static void collectCheckers(const CheckerRegistry::CheckerInfoList &checkers,
const llvm::StringMap<size_t> &packageSizes,
CheckerOptInfo &opt, CheckerInfoSet &collected) {
// Use a binary search to find the possible start of the package.
CheckerRegistry::CheckerInfo packageInfo(NULL, opt.getName(), "");
CheckerRegistry::CheckerInfoList::const_iterator e = checkers.end();
CheckerRegistry::CheckerInfoList::const_iterator i =
std::lower_bound(checkers.begin(), e, packageInfo, checkerNameLT);
// If we didn't even find a possible package, give up.
if (i == e)
return;
// If what we found doesn't actually start the package, give up.
if (!isInPackage(*i, opt.getName()))
return;
// There is at least one checker in the package; claim the option.
opt.claim();
// See how large the package is.
// If the package doesn't exist, assume the option refers to a single checker.
size_t size = 1;
llvm::StringMap<size_t>::const_iterator packageSize =
packageSizes.find(opt.getName());
if (packageSize != packageSizes.end())
size = packageSize->getValue();
// Step through all the checkers in the package.
for (e = i+size; i != e; ++i) {
if (opt.isEnabled())
collected.insert(&*i);
else
collected.erase(&*i);
}
}
void CheckerRegistry::addChecker(InitializationFunction fn, StringRef name,
StringRef desc) {
Checkers.push_back(CheckerInfo(fn, name, desc));
// Record the presence of the checker in its packages.
StringRef packageName, leafName;
llvm::tie(packageName, leafName) = name.rsplit(PackageSeparator);
while (!leafName.empty()) {
Packages[packageName] += 1;
llvm::tie(packageName, leafName) = packageName.rsplit(PackageSeparator);
}
}
void CheckerRegistry::initializeManager(CheckerManager &checkerMgr,
SmallVectorImpl<CheckerOptInfo> &opts) const {
// Sort checkers for efficient collection.
std::sort(Checkers.begin(), Checkers.end(), checkerNameLT);
// Collect checkers enabled by the options.
CheckerInfoSet enabledCheckers;
for (SmallVectorImpl<CheckerOptInfo>::iterator
i = opts.begin(), e = opts.end(); i != e; ++i) {
collectCheckers(Checkers, Packages, *i, enabledCheckers);
}
// Initialize the CheckerManager with all enabled checkers.
for (CheckerInfoSet::iterator
i = enabledCheckers.begin(), e = enabledCheckers.end(); i != e; ++i) {
(*i)->Initialize(checkerMgr);
}
}
void CheckerRegistry::printHelp(llvm::raw_ostream &out,
size_t maxNameChars) const {
// FIXME: Alphabetical sort puts 'experimental' in the middle.
// Would it be better to name it '~experimental' or something else
// that's ASCIIbetically last?
std::sort(Checkers.begin(), Checkers.end(), checkerNameLT);
// FIXME: Print available packages.
out << "CHECKERS:\n";
// Find the maximum option length.
size_t optionFieldWidth = 0;
for (CheckerInfoList::const_iterator i = Checkers.begin(), e = Checkers.end();
i != e; ++i) {
// Limit the amount of padding we are willing to give up for alignment.
// Package.Name Description [Hidden]
size_t nameLength = i->FullName.size();
if (nameLength <= maxNameChars)
optionFieldWidth = std::max(optionFieldWidth, nameLength);
}
const size_t initialPad = 2;
for (CheckerInfoList::const_iterator i = Checkers.begin(), e = Checkers.end();
i != e; ++i) {
out.indent(initialPad) << i->FullName;
int pad = optionFieldWidth - i->FullName.size();
// Break on long option names.
if (pad < 0) {
out << '\n';
pad = optionFieldWidth + initialPad;
}
out.indent(pad + 2) << i->Desc;
out << '\n';
}
}
| gpl-3.0 |
helsinkiAUV/auv | arduinoMain/navigation.cpp | 1 | 5768 | /*
* Navigation function.
* Created by Juho Iipponen on March 11, 2016.
*
* This file is part of the University of Helsinki AUV source code.
*
* The AUV source code 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.
*
* The AUV source 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with the source code. If not, see <http://www.gnu.org/licenses/>.
*
* @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
*/
#include "auv.h"
#include "navigation.h"
void newBearing (const Coord& start, const Coord& target, const Coord& current, const float maxPassDist,
const float maxCrossTrackErr, int& nextBearing, float& distToTarget, float& crossTrackErr, bool& inForbiddenZone)
{
distToTarget = current.distanceTo(target); // Distance from current point to target.
float distStartToTarget = start.distanceTo(target); // Distance between waypoints.
// Compute projection of the current point to the great circle.
Coord projectionToGc = current.closestGreatCirclePoint(start, target);
float distProjToTarget = projectionToGc.distanceTo(target);
float distStartToProj = 0.0;
// Check if we have accidentally gone past the target point, but are not within the maxPassDist.
if (projectionToGc.distanceTo(start) >= distStartToTarget)
{
distStartToProj = distStartToTarget + distProjToTarget;
}
else
{
distStartToProj = distStartToTarget - distProjToTarget;
}
if (distStartToProj >= distStartToTarget - maxPassDist) // If close to the target, approach target directly.
{
nextBearing = (int) (current.bearingTo(target) * 180 / M_PI);
crossTrackErr = distToTarget;
inForbiddenZone = true;
return;
}
else
{
// Distance away from which the auv will begin approaching closer to the target.
float approachDistance = fmax(distStartToTarget - 5 * maxPassDist, 0.0);
float distToForbidZoneFromGc; // Distance from the great circle (between start and target) to the boundary of the forbidden zone.
if (distStartToProj < approachDistance)
{
distToForbidZoneFromGc = maxCrossTrackErr;
}
else // On approach to target.
{
// Slope of approach.
float appSlope = (maxCrossTrackErr - maxPassDist) / (maxPassDist - approachDistance);
distToForbidZoneFromGc = maxPassDist + appSlope * (distStartToProj - (distStartToTarget - maxPassDist));
}
crossTrackErr = current.distanceTo(projectionToGc); // Cross-track error.
float bearingToTarget = current.bearingTo(target);
float bearingToProjection = current.bearingTo(projectionToGc);
float cteRatio = crossTrackErr / distToForbidZoneFromGc;
float correctionAngle;
if (cteRatio > 0.05) // Significantly off of the great circle.
{
// The larger the cross-track error, the steeper we approach the great circle.
// Correction is negative if on the right side of the great circle.
// The boat will head perpendicular to the track, if cteRatio >= 0.75 (1.0 is the
// forbidden zone limit).
correctionAngle = fmin(cteRatio * 4.0 / 3.0, 1.0) * angleBetweenBearings(bearingToProjection, bearingToTarget);
}
else // Near the great circle.
{
correctionAngle = 0.0;
}
nextBearing = (int) ((bearingToTarget + correctionAngle) * 180.0 / M_PI);
if (nextBearing >= 360) nextBearing -= 360;
if (nextBearing < 0) nextBearing += 360;
inForbiddenZone = crossTrackErr > distToForbidZoneFromGc;
return;
}
}
void holdCourse(Gps& gpsOnly, Coord& start, Coord& current, const Coord& target, float passDist, ServoAuv& rudderServo, int course, float holdDistance,
float bearingComputeDistance, int& bearing, float crossTrackError)
{
#ifdef ARDUINO
float courseInRad = course * M_PI / 180;
float bearingInRad = bearing * M_PI / 180;
int numBearingComputations = 0;
current = gpsOnly.averageCoordinate(10);
Coord origin = current;
Coord previousBearingPoint = origin;
while (current.distanceTo(origin) < holdDistance)
{
float courseDeviation = -angleBetweenBearings(bearingInRad, courseInRad);
int servoSteps = rudderServo.getNumSteps();
int rudderState = round(clamp(-servoSteps, courseDeviation / sectorWidthInRad * servoSteps, servoSteps));
rudderServo.turnTo(rudderState);
// Serial.print("Heading, Course, Course deviation, rudderState: ");
// Serial.print(orient.heading()); Serial.print(" ");
//Serial.print("Course: ");
while (current.distanceTo(previousBearingPoint) < bearingComputeDistance)
{
current = gpsOnly.averageCoordinate(10);
Serial.print(course);Serial.print(",");
Serial.print(bearing);Serial.print(",");
Serial.print(current.latd,7);Serial.print(",");Serial.print(current.lond,7);Serial.print(",");
Serial.print(rudderState);Serial.print(",");
Coord projectionToGc = current.closestGreatCirclePoint(start, target);
crossTrackError = current.distanceTo(projectionToGc);
Serial.print(crossTrackError);Serial.print(",");
Serial.print(current.distanceTo(target));
Serial.println();
if (current.distanceTo(target) < passDist)
{
return;
}
}
bearingInRad = previousBearingPoint.bearingTo(current)*180/M_PI;
bearing = (int) bearingInRad;
previousBearingPoint = current;
}
#endif
}
| gpl-3.0 |
falltergeist/falltergeist | src/Format/Sve/File.cpp | 1 | 1845 | // Project includes
#include "../../Exception.h"
#include "../Dat/Stream.h"
#include "../Sve/File.h"
// Third-party includes
// stdlib
namespace Falltergeist
{
namespace Format
{
namespace Sve
{
File::File(Dat::Stream&& stream)
{
stream.setPosition(0);
std::string line;
unsigned char ch = 0;
for (unsigned int i = 0; i != stream.size(); ++i)
{
stream >> ch;
if (ch == 0x0D) // \r
{
// do nothing
}
else if (ch == 0x0A) // \n
{
_addString(line);
line.clear();
}
else
{
line += ch;
}
}
if (line.size() != 0)
{
_addString(line);
}
}
void File::_addString(std::string line)
{
auto pos = line.find(":");
if (pos != std::string::npos)
{
auto frame = line.substr(0, pos);
line = line.substr(pos+1);
_subs.insert(std::pair<int,std::string>(std::stoi(frame),line));
}
}
std::pair<int,std::string> File::getSubLine(int frame)
{
auto it = _subs.lower_bound(frame);
if (it != _subs.end())
{
return *it;
}
else
{
return std::pair<int,std::string>(999999, "");
}
}
}
}
}
| gpl-3.0 |
GameCodingNinja/sdl2-opengl-game-engine | obsolete/cubeWorks/source/smartGUI/smartresetkeybind.cpp | 1 | 1674 |
/************************************************************************
* FILE NAME: smartresetkeybind.cpp
*
* DESCRIPTION: Class CSmartExitBtn
************************************************************************/
// Physical component dependency
#include "smartresetkeybind.h"
// Game lib dependencies
#include <managers/actionmanager.h>
#include <gui/menumanager.h>
#include <gui/uicontrol.h>
#include <gui/menu.h>
#include <gui/uiscrollbox.h>
#include <utilities/genfunc.h>
/************************************************************************
* desc: Constructer
************************************************************************/
CSmartResetKeyBindBtn::CSmartResetKeyBindBtn( CUIControl * pUIControl ) :
CSmartGuiControl( pUIControl )
{
} // constructor
/***************************************************************************
* decs: Called when the control is executed - quits the game
****************************************************************************/
void CSmartResetKeyBindBtn::Execute()
{
// Reset the key bindings for all controls and save
CActionMgr::Instance().ResetKeyBindingsToDefault();
// Get a pointer to the scroll box
CMenu & rMenu = CMenuManager::Instance().GetMenu( "key_bindings_menu" );
CUIScrollBox * pScrollBoxCtrl = NGenFunc::DynCast<CUIScrollBox>(rMenu.GetPtrToControl("key_binding_scroll_box"));
// Reset all the key binding buttons
const auto & scrollCtrlVec = pScrollBoxCtrl->GetScrollCtrlVec();
for( auto iter : scrollCtrlVec )
iter->SmartCreate();
} // Execute
| gpl-3.0 |
zrax/libhsplasma | Python/PRP/Avatar/pyOmniCutoffApplicator.cpp | 1 | 1377 | /* This file is part of HSPlasma.
*
* HSPlasma 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.
*
* HSPlasma 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 HSPlasma. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pyAGApplicator.h"
#include <PRP/Avatar/plAGApplicator.h>
#include "PRP/pyCreatable.h"
PY_PLASMA_NEW(OmniCutoffApplicator, plOmniCutoffApplicator)
PY_PLASMA_TYPE(OmniCutoffApplicator, plOmniCutoffApplicator,
"plOmniCutoffApplicator wrapper")
PY_PLASMA_TYPE_INIT(OmniCutoffApplicator) {
pyOmniCutoffApplicator_Type.tp_new = pyOmniCutoffApplicator_new;
pyOmniCutoffApplicator_Type.tp_base = &pyAGApplicator_Type;
if (PyType_CheckAndReady(&pyOmniCutoffApplicator_Type) < 0)
return NULL;
Py_INCREF(&pyOmniCutoffApplicator_Type);
return (PyObject*)&pyOmniCutoffApplicator_Type;
}
PY_PLASMA_IFC_METHODS(OmniCutoffApplicator, plOmniCutoffApplicator)
| gpl-3.0 |
mstuttgart/qchip8-emulator | src/chip8_cpu.cpp | 1 | 15362 | #include "chip8_cpu.hpp"
using namespace std;
////////////////////////////////////////////////////////////////////////////
Chip8_CPU::Chip8_CPU() {}
////////////////////////////////////////////////////////////////////////////
Chip8_CPU::~Chip8_CPU() {}
////////////////////////////////////////////////////////////////////////////
// Inicializamos o registros do emulador
void Chip8_CPU::hardReset()
{
// Inicializamos os registros gerais do emulador
softReset();
// Zeramos a memoria
for ( int i = 80; i < MEMORY_SIZE; i++ )
{
memory[i] = 0;
}
quint8 chip8_fontset[80] =
{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
};
// Load fontset
for ( int i = 0; i < 80; i++ )
{
memory[i] = chip8_fontset[i];
}
// Incializamos o gerador randomico
srand ( time ( NULL ) );
// Iniciando mapa com metodos
opcodeMap[0] = &Chip8_CPU::opcodePrefix0;
opcodeMap[1] = &Chip8_CPU::opcodePrefix1;
opcodeMap[2] = &Chip8_CPU::opcodePrefix2;
opcodeMap[3] = &Chip8_CPU::opcodePrefix3;
opcodeMap[4] = &Chip8_CPU::opcodePrefix4;
opcodeMap[5] = &Chip8_CPU::opcodePrefix5;
opcodeMap[6] = &Chip8_CPU::opcodePrefix6;
opcodeMap[7] = &Chip8_CPU::opcodePrefix7;
opcodeMap[8] = &Chip8_CPU::opcodePrefix8;
opcodeMap[9] = &Chip8_CPU::opcodePrefix9;
opcodeMap[10] = &Chip8_CPU::opcodePrefixA;
opcodeMap[11] = &Chip8_CPU::opcodePrefixB;
opcodeMap[12] = &Chip8_CPU::opcodePrefixC;
opcodeMap[13] = &Chip8_CPU::opcodePrefixD;
opcodeMap[14] = &Chip8_CPU::opcodePrefixE;
opcodeMap[15] = &Chip8_CPU::opcodePrefixF;
cout << "Init CHIP8 CPU" << endl;
}
////////////////////////////////////////////////////////////////////////////
void Chip8_CPU::softReset()
{
// Inicializamos os registros
opcode = 0;
I = 0;
SP = STACK_SIZE;
PC = 0x200;
// Zeramos a pilha, registros e vetor de keys
for ( int i = 0; i < 16; i++ )
{
V[i] = 0;
stack[i] = 0;
currentKeyState[i] = false;
lastKeyState[i] = false;
}
waitForKey = false;
for ( int i = 0; i < DISPLAY; i++ )
{
display[i] = false;
}
// Reset timer
delay_timer = 0;
sound_timer = 0;
}
////////////////////////////////////////////////////////////////////////////
bool Chip8_CPU::load ( const string &fileName )
{
// Carregamos o arquivo
ifstream is ( fileName.c_str(), std::ifstream::binary );
if ( !is )
return false;
// Incializamos os registros, memoria e etc do chip8
hardReset();
// get length of file:
is.seekg ( 0, is.end );
int length = is.tellg();
is.seekg ( 0, is.beg );
char *buffer = new char [length];
cout << "Loading ROM..." << endl;
// read data as a block:
is.read ( buffer, length );
if ( !is )
{
std::cout << "ERROR: only " << is.gcount() << " could be read";
return false;
}
if ( length > ( MEMORY_SIZE - 512 ) )
{
cout << "ERROR: ROM too big for memory" << endl;
return false;
}
// Copiamos conteudo do buffer para a memoria
for ( int i = 0; i < length; i++ )
{
memory[i + 0x200] = static_cast<quint8> ( buffer[i] );
}
// Fechamos o arquivo
is.close();
// ...buffer contains the entire file...
delete[] buffer;
return true;
}
////////////////////////////////////////////////////////////////////////////
void Chip8_CPU::fetch()
{
// Lendo o opcode. Concatenamos os MSByte com LSBytes
opcode = ( memory[PC] << 8 ) | memory[PC + 1];
}
////////////////////////////////////////////////////////////////////////////
void Chip8_CPU::execute()
{
// Chamamos o metodo do respectivo opcode
( this->*opcodeMap[ ( opcode & 0xF000 ) >> 12 ] ) ();
// Update timers
if ( delay_timer != 0 )
--delay_timer;
if ( sound_timer > 0 )
{
--sound_timer;
if ( sound_timer == 1 )
cout << "BEEP!" << endl;
}//if
}
////////////////////////////////////////////////////////////////////////////
void Chip8_CPU::opcodePrefix0()
{
switch ( opcode & 0x00FF )
{
case 0x00E0: // Clear screen
for ( int i = 0; i < DISPLAY; i++ )
display[i] = false;
PC += 2;
break;
case 0x00EE: // Returns from a subroutine.
PC = stack[SP];
++SP;
break;
case 0x00FB: // scroll screen 4 pixels right - schip
break;
case 0x00FC: // scroll screen 4 pixels left
break;
case 0x00FE: // disable extended screen mode
extendDisplayMode = false;
break;
case 0x00FF: // enable extended screen mode (128 x 64)
extendDisplayMode = true;
break;
default:
switch ( opcode & 0xFFF0 )
{
case 0x00C0: // Scroll the screen down N lines - SuperChip
break;
default:
cout << "Invalid OpcodePrefix0" << endl;
break;
}
break;
}//switch
}
////////////////////////////////////////////////////////////////////////////
// Jumps to address NNN.
void Chip8_CPU::opcodePrefix1()
{
PC = opcode & 0xfff;
}
////////////////////////////////////////////////////////////////////////////
// Calls subroutine at NNN.
void Chip8_CPU::opcodePrefix2()
{
SP--;
stack[SP] = PC + 2;
PC = opcode & 0x0fff;
}
////////////////////////////////////////////////////////////////////////////
// 3XNN - Skips the next instruction if VX equals NN.
void Chip8_CPU::opcodePrefix3()
{
PC += V[ decodeX() ] == decodeNN() ? 4 : 2;
}
////////////////////////////////////////////////////////////////////////////
// 4XNN - Skips the next instruction if VX doesn’t equal NN.
void Chip8_CPU::opcodePrefix4()
{
PC += ( V[ decodeX() ] != decodeNN() ) ? 4 : 2;
}
////////////////////////////////////////////////////////////////////////////
// 5XYN - Skips the next instruction if VX equals VY.
void Chip8_CPU::opcodePrefix5()
{
PC += ( V[ decodeX() ] == V[ decodeY()] ) ? 4 : 2;
}
////////////////////////////////////////////////////////////////////////////
// 6XNN - Sets VX to NN.
void Chip8_CPU::opcodePrefix6()
{
V[ decodeX() ] = decodeNN();
PC += 2;
}
////////////////////////////////////////////////////////////////////////////
// 7XNN Adds NN to VX.
void Chip8_CPU::opcodePrefix7()
{
V[ decodeX() ] += decodeNN();
PC += 2;
}
////////////////////////////////////////////////////////////////////////////
void Chip8_CPU::opcodePrefix8()
{
quint8 idx = decodeX(); //( opcode & 0x0f00 ) >> 8;
quint8 idy = decodeY(); //( opcode & 0x00f0 ) >> 4;
switch ( opcode & 0x000F )
{
// 8XY0 Sets VX to the value of VY.
case 0x0000:
V[idx] = V[idy];
break;
// 8XY1 Sets VX to VX or VY.
case 0x0001:
V[idx] = V[idx] | V[idy];
break;
case 0x0002: // 8XY2 Sets VX to VX and VY.
V[idx] = V[idx] & V[idy];
break;
case 0x0003: // 8XY3 Sets VX to VX xor VY.
V[idx] = V[idx] ^ V[idy];
break;
case 0x0004:
// 8XY4 Adds VY to VX. VF is set to 1 when there’s a
// carry, and to 0 when there isn’t.
V[0xf] = ( V[idy] > ( 0xff - V[idx] ) ) ? 1 : 0;
V[idx] += V[idy];
break;
case 0x0005:
// 8XY5 VY is subtracted from VX. VF is set to 0 when
// there’s a borrow, and 1 when there isn’t.
V[0xf] = ( V[idy] > V[idx] ) ? 0 : 1;
V[idx] -= V[idy] ;
break;
case 0x0006:
// 8XY6 Shifts VX right by one. VF is set to the value
// of the least significant bit of VX before the shift
//V[0xf] = V[idx] & 0x1;
// V[idx] >>= 1;
V[0xf] = V[idy] & 0x1;
V[idx] = V[idy] >> 1;
break;
case 0x0007:
// 8XY7 Sets VX to VY minus VX. VF is set to 0 when
// there’s a borrow, and 1 when there isn’t.
V[0xf] = ( V[idx] > V[idy] ) ? 0 : 1;
V[idx] = V[idy] - V[idx];
break;
case 0x000E:
// 8XYE Shifts VX left by one. VF is set to the valueProgram exited with return code: 0
// of the most significant bit of VX before the shift
//V[0xf] = ( V[idx] & 0x80 ) == 0x80 ? 1 : 0;
//V[0xf] = V[idx] >> 7;
//V[idx] <<= 1;
V[0xf] = ( V[idy] & 0x80 ) == 0x80 ? 1 : 0;
V[idx] = V[idy] << 1;
break;
default:
//cout << "Invalid opcode: " << opcode << endl;
break;
}//switch
PC += 2;
}
////////////////////////////////////////////////////////////////////////////
// Skip next instruction if Vx != Vy.
void Chip8_CPU::opcodePrefix9()
{
PC += V[ decodeX() ] != V[ decodeY() ] ? 4 : 2;
}
////////////////////////////////////////////////////////////////////////////
// ANNN: Sets I to the address NNN
void Chip8_CPU::opcodePrefixA()
{
I = opcode & 0x0fff;
PC += 2;
}
////////////////////////////////////////////////////////////////////////////
// BNNN Jumps to the address NNN plus V0.
void Chip8_CPU::opcodePrefixB()
{
PC = ( opcode & 0x0fff ) + V[0];
}
////////////////////////////////////////////////////////////////////////////
// CXNN Sets VX to a random number and NN.
void Chip8_CPU::opcodePrefixC()
{
V[ decodeX() ] = decodeNN() & ( std::rand() % 0xff );
PC += 2;
}
////////////////////////////////////////////////////////////////////////////
// 0xDXYN Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision.
void Chip8_CPU::opcodePrefixD()
{
// Recebemos as coordenadas do sprite
quint16 x = V[ decodeX() ];
quint16 y = V[ decodeY() ];
// Altura do sprite
quint16 lines = decodeN();
// Receb o byte doo sprite
quint8 sprByte;
quint16 px;
quint16 py;
V[0xF] = 0;
for ( int i = 0; i < lines; i++ )
{
sprByte = memory[ I + i ];
py = ( y + i ) << 6;//* 64
for ( int j = 0; j < 8; j++ )
{
px = ( x + j );
if ( ( sprByte & ( 0x80 >> j ) ) != 0 )
{
if ( display[ px + py ] )
V[0xf] = 1;
display[ px + py ] ^= true;
}//if
}//for j
}// for i
PC += 2;
}
////////////////////////////////////////////////////////////////////////////
void Chip8_CPU::opcodePrefixE()
{
switch ( opcode & 0x00FF )
{
case 0x009E:
// EX9E Skips the next instruction if the key
// stored in VX is pressed.
PC += ( currentKeyState[ V[ decodeX() ] ] ) ? 4 : 2;
break;
case 0x00A1:
// EXA1 Skips the next instruction if the key
// stored in VX isn’t pressed.
PC += ( !currentKeyState[ V[ decodeX() ] ] ) ? 4 : 2;
break;
default:
break;
}//switch
}
////////////////////////////////////////////////////////////////////////////
void Chip8_CPU::opcodePrefixF()
{
unsigned char idx = decodeX();
switch ( opcode & 0x00FF )
{
case 0x0007: // FX07 Sets VX to the value of the delay timer.
V[idx] = delay_timer;
break;
case 0x000A: // FX0A - A key press is awaited, and then stored in VX.
if ( !waitForKey )
{
// Copiamos o estado de cada tecla para o vetor de teclas anteriores
for ( int i = 0; i < KEY_SIZE; i++ )
{
lastKeyState[i] = currentKeyState[i];
}
// Indicamos que estamos esperando o pressionamento de uma tecla
waitForKey = true;
return;
}//if
else
{
// Verificamos se alguma tecla mudou de estado
for ( int i = 0; i < KEY_SIZE; i++ )
{
if ( !lastKeyState[i] && currentKeyState[i] )
{
V[idx] = i;
PC += 2;
waitForKey = false;
return;
}
// Permite detectar se uma tecla estava pressiona
// foi solta e depois pressionada novamente
lastKeyState[i] = currentKeyState[i];
}
return;
}//else
break;
case 0x0015: // FX15 Sets the delay timer to VX.
delay_timer = V[idx];
break;
case 0x0018: // FX18 Sets the sound timer to VX.
sound_timer = V[idx];
break;
case 0x001E: // FX1E Adds VX to I
V[0xf] = ( I + V[idx] > 0xfff ) ? 1 : 0;
I += ( quint16 ) V[idx];
break;
case 0x0029:
// FX29 Sets I to the location of the sprite for the
// character in VX. Characters 0-F (in hexadecimal) are
// represented by a 4×5 font.
I = ( quint16 ) V[idx] * 0x5;
break;
case 0x0033:
{
// FX33 - Stores the Binary-coded decimal representation of VX
// at the addresses I, I plus 1, and I plus 2
quint8 value = V[idx];
memory[I] = value / 100;
value = value % 100;
memory[I + 1] = value / 10;
memory[I + 2] = value % 10;
}
break;
case 0x0055:
// FX55 Stores V0 to VX in memory starting at address I
for ( int i = 0; i <= idx; ++i )
memory[ I + i ] = V[i];
// I += ( quint16 ) idx + 1;
break;
case 0x0065:
// FX65 Fills V0 to VX with values from memory starting at address I
for ( int i = 0; i <= idx; ++i )
V[i] = memory[ I + i ];
// I += ( quint16 ) idx + 1;
break;
default:
break;
}//switch
PC += 2;
}
////////////////////////////////////////////////////////////////////////////
quint8 Chip8_CPU::decodeN()
{
return opcode & 0x000f;
}
////////////////////////////////////////////////////////////////////////////
quint8 Chip8_CPU::decodeNN()
{
return opcode & 0x00ff;
}
////////////////////////////////////////////////////////////////////////////
quint8 Chip8_CPU::decodeX()
{
return ( opcode & 0x0f00 ) >> 8;
}
////////////////////////////////////////////////////////////////////////////
quint8 Chip8_CPU::decodeY()
{
return ( opcode & 0x00f0 ) >> 4;
}
////////////////////////////////////////////////////////////////////////////
const bool *Chip8_CPU::getDisplay() const
{
return display;
}
////////////////////////////////////////////////////////////////////////////
void Chip8_CPU::setKey ( int key, bool state )
{
currentKeyState[ key ] = state;
}
////////////////////////////////////////////////////////////////////////////
| gpl-3.0 |
devkitPro/gp32-tools | src/b2fxec/chuff.cpp | 1 | 11613 | /////////////////////////////////////////////////////////////////////
//
// Module: chuff.cpp
//
// Author: Jouni 'Mr.Spiv' Korhonen
//
// Purpose: methods for class chuf. These methods and
// member functions calculate canonical codes for
// given alphabet & frequency distribution.
//
// This cacnonical huffman encoder uses following nice stuff:
// - tree balancing i.e. one can define maximum depth for the tree
// - Moffat's inplace linear calculation of minimum redundancy codes
//
// To be honest this encoder has never seen any form of binary tree :)
//
// Restrictions: One symbol frequency is not allowed to
// exceed 32767 and total frequency must not exceed
// 65535! (???)
//
// Revision:
// v0.1 -> 08-Aug-1998 JiK - initial version.
// 0.2 -> 19-Sep-1998 JiK - made to handle endianes.
// 0.3 -> 01-Aug-1999 JiK - minor naming changes & prototype
// redefinitions.
// 0.4 -> 02-Aug-1999 JiK - added outputCodeLengthsBytes() method.
// 0.5 -> 24-Aug-1999 JiK - Fixed a sorting bug in sortFortMin..()
// that caused calculated trees to be different depending on the
// compiler the source was compiled.
// 0.6 -> 02-Jun-2000 JiK - Added namespaces and nothrow..
// 0.7 -> 12-Jun-2000 JiK - reworked deletes and destructor to handle
// NULL pointers which are permitted.
// 0.8 -> 09-Sep-2000 JiK - added addCnt( int,int );
// 0.9 -> 09-Nov-2002 JiK - some fixes for gcc3.1
// 1.0 -> 09-Mar-2004 JiK - Fixed a bug in _balance_canonical_codes()
// 1.1 -> 22-Aug-2004 JiK - Fixed another bug in _balance_canonical_codes()
// 1.2 -> 4-Sep-2004 JiK - Replaced _balance_canonical_codes() with a
// working algorithm :)
//
/////////////////////////////////////////////////////////////////////
#include <iostream>
#include <new> // just for std::nothrow
#include <cstdlib>
#include <cassert>
#include "chuff.h"
using namespace std;
/////////////////////////////////////////////////////////////////////
// Function: EncHuf( int s, int m );
// Parameters:
// s -- size of the alphabet.
// m -- maximum depth of the huffman tree (i.e. maximum code
// lenght).
// Purpose: This is EncHuf class'es default constructor. Allocates
// needed arrays and initialized private stuff.
// Returns:
// Changes:
/////////////////////////////////////////////////////////////////////
EncHuf::EncHuf( int s, int m )
throw ( std::bad_alloc, std::invalid_argument ) {
int n;
//cout << "EncHuf::EncHuf(" << s << "," << m << ");" << endl;
/*
* Size of the alphabet must be atleast two.
*/
if (s < 2) { throw std::invalid_argument(" Huffman alphabet too small"); }
_size = s;
_maxcodelength = m <= MAXCODELENGTH ? m : MAXCODELENGTH;
n = s <= m ? m + 1 : s;
m_A = new(std::nothrow) sym[s];
m_B = new(std::nothrow) unsigned short[n];
// funny way to handle std::bad_alloc..
if (m_A == NULL || m_B == NULL) {
// if these pointers are NULL, delete does nothing..
delete[] m_A;
delete[] m_B;
throw std::bad_alloc();
}
}
/////////////////////////////////////////////////////////////////////
// Function: EncHuf( const EncHuf &e );
// Parameters:
// e -- reference to class to copy.
// Purpose: This is EncHuf class'es 'copy' constructor.
// Returns:
// Changes:
/////////////////////////////////////////////////////////////////////
EncHuf::EncHuf( const EncHuf &e )
throw ( std::bad_alloc ) {
int n;
_size = e._size;
_maxcodelength = e._maxcodelength;
_start = e._start;
n = _size <= _maxcodelength ? _maxcodelength + 1 : _size;
m_A = new(std::nothrow) sym[_size];
m_B = new(std::nothrow) unsigned short[n];
if (m_A == NULL || m_B == NULL) {
// if these pointers are NULL, delete does nothing..
delete[] m_A;
delete[] m_B;
throw std::bad_alloc();
}
for (n = 0; n < _size; n++) {
m_A[n] = e.m_A[n];
}
for (n = 0; n <= _maxcodelength; n++) {
m_B[n] = e.m_B[n];
}
}
EncHuf& EncHuf::operator=( const EncHuf &e )
throw (std::range_error) {
int n;
if (_size != e._size || _maxcodelength != e._maxcodelength) {
throw std::range_error("Huffman encoder assignment");
}
init();
for (n = 0; n < _size; n++) {
m_A[n] = e.m_A[n];
}
for (n = 0; n <= _maxcodelength; n++) {
m_B[n] = e.m_B[n];
}
_start = e._start;
return *this;
}
/////////////////////////////////////////////////////////////////////
// Function: ~EncHuf()
// Parameters:
// Purpose: the EncHuf class'es destructur.
// Returns:
// Changes:
/////////////////////////////////////////////////////////////////////
EncHuf::~EncHuf() {
delete[] m_A;
delete[] m_B;
}
/////////////////////////////////////////////////////////////////////
// Function: void init();
// Parameters:
// Purpose: (Re)Initializes EncHuf class to unused state.
// Changes: A & B array contents.
/////////////////////////////////////////////////////////////////////
void EncHuf::init() {
int i;
for (i = 0; i < _size; i++) {
m_A[i].u.s.cnt = 0;
m_A[i].u.s.alp = i;
m_A[i].cde = 0;
}
for (i = 0; i <= _maxcodelength; i++) {
m_B[i] = 0;
}
}
/////////////////////////////////////////////////////////////////////
// Function: int balance_canonical_codes( int ovl );
// Parameters:
// ovl -- the number of overflow leaves in the huffman tree.
// Purpose: Balances the huffman tree to 'maxcodelenght'
// maximum depth i.e. makes sure that no leaf has greater
// depth than 'maxcodelenght'.
// Returns: 0 if ok, > 0 if the tree can not balanced to
// 'maxcodelenght' maximum depth i.e. the 'maxcodelenghtä is too
// small for this alphabet and symbol frequencies.
// Changes: B
/////////////////////////////////////////////////////////////////////
int EncHuf::_balance_canonical_codes( int ovl ) {
int i;
//
// This algorithm is far away from an optimal
// one.. but does its job.
//
// replace internal node with a leaf
m_B[_maxcodelength]++;
ovl--;
// check for pathetic cases..
if ((m_B[_maxcodelength] == 1) && (ovl > 0)) {
m_B[_maxcodelength]++;
ovl--;
}
// balance
while (ovl > 0) {
i = _maxcodelength - 1;
while (!m_B[i]) { i--; }
m_B[i]--;
m_B[i + 1] += 2;
if (m_B[i + 1] > (1 << (i + 1))) { return 1; }
ovl--;
}
return 0;
}
/////////////////////////////////////////////////////////////////////
// Function:
//
//
//
//
/////////////////////////////////////////////////////////////////////
void EncHuf::_calculate_canonical_codes() {
unsigned long c = 0;
int p = 0;
int n;
//
// This algorithm assumes that the symbols
// are in ascending order by symbol
// depth. Symbols with same depth must be in
// ascending order by alphabets.
//
for (n = _start; n < _size; n++) {
if (m_A[n].u.s.cnt == 0) { continue; }
if (m_A[n].u.s.cnt > p) {
c <<= (m_A[n].u.s.cnt - p);
p = m_A[n].u.s.cnt;
}
m_A[n].cde = c;
c++;
}
}
/////////////////////////////////////////////////////////////////////
//
//
//
//
//
/////////////////////////////////////////////////////////////////////
int cmp::both( const void *a, const void *b ) {
#ifndef BIGENDIAN
unsigned long aa = (((sym*)a)->u.s.cnt << 16) | ((sym*)a)->u.s.alp;
unsigned long bb = (((sym*)b)->u.s.cnt << 16) | ((sym*)b)->u.s.alp;
return (aa - bb);
#else
return ( ((sym*)a)->bth - ((sym*)b)->bth );
#endif
}
int cmp::sfe( const void *a, const void *b ) {
return ( ((sym*)(a))->u.s.alp - ((sym*)(b))->u.s.alp );
}
void EncHuf::_sort_for_minimum_redundancy() {
int n = 0;
qsort((void *)m_A,_size,sizeof(sym),cmp::both);
while (n < _size && !m_A[n].u.s.cnt) { n++; }
_start = n;
}
void EncHuf::_sort_for_canonical_codes() {
qsort((void *)&m_A[_start],_size - _start,sizeof(sym),cmp::both);
}
void EncHuf::_sort_A_for_encoding() {
qsort((void *)m_A,_size,sizeof(sym),cmp::sfe);
}
/////////////////////////////////////////////////////////////////////
//
//
//
//
//
/////////////////////////////////////////////////////////////////////
void EncHuf::_build_B_from_A_for_balancing() {
unsigned short c;
int n;
for (n = 0; n <= _maxcodelength; n++) {
m_B[n] = 0;
}
for (n = _start; n < _size; n++) {
c = m_A[n].u.s.cnt;
//if (c > _maxcodelength) { c = _maxcodelength; }
if (c <= _maxcodelength) { m_B[c]++; }
}
}
/////////////////////////////////////////////////////////////////////
//
//
//
//
//
/////////////////////////////////////////////////////////////////////
void EncHuf::_rebuild_A_from_B_for_encoding() {
int m, n;
for (n = 0; n < _size; n++) {
m_A[0].u.s.cnt = 0;
}
for (n = _maxcodelength, m = _start; n >= 0; n--) {
if (m_B[n] == 0) { continue; }
while (m_B[n]-- > 0) { m_A[m++].u.s.cnt = n; }
}
}
/////////////////////////////////////////////////////////////////////
//
//
//
//
//
/////////////////////////////////////////////////////////////////////
const unsigned short* EncHuf::outputCodeLengths() {
int n;
for (n = 0; n < _size; n++) {
m_B[n] = m_A[n].u.s.cnt;
}
return m_B;
}
const unsigned char* EncHuf::outputCodeLengthsBytes() {
// static_cast<unsigned char*>
unsigned char* b = reinterpret_cast<unsigned char*>(m_B);
int n;
for (n = 0; n < _size; n++) {
b[n] = m_A[n].u.s.cnt & 0xff;
}
return b;
}
/////////////////////////////////////////////////////////////////////
//
//
//
//
//
/////////////////////////////////////////////////////////////////////
int EncHuf::_calculate_minimum_redundancy() {
int r; /* next root node to be used */
int l; /* next leaf to be used */
int n; /* next value to be assigned */
int a; /* number of available nodes */
int u; /* number of internal nodes */
int d; /* current depth of leaves */
int o = 0; /* number of depth overflows */
/*
* check for pathological cases
*/
if (_size == _start) { return -1; }
if (_size - 1 == _start) {
m_A[_start].u.s.cnt = 1;
m_A[_start].cde = 0;
return 0;
}
/* first pass, left to right, setting parent pointers */
m_A[_start].u.s.cnt += m_A[_start + 1].u.s.cnt; r = _start; l = _start + 2;
for (n = _start + 1; n < _size - 1; n++) {
/* select first item for a pairing */
if (l >= _size || m_A[r].u.s.cnt < m_A[l].u.s.cnt) {
m_A[n].u.s.cnt = m_A[r].u.s.cnt; m_A[r++].u.s.cnt = n;
} else {
m_A[n].u.s.cnt = m_A[l++].u.s.cnt;
}
/* add on the second item */
if (l >= _size || (r < n && m_A[r].u.s.cnt < m_A[l].u.s.cnt)) {
m_A[n].u.s.cnt += m_A[r].u.s.cnt; m_A[r++].u.s.cnt = n;
} else {
m_A[n].u.s.cnt += m_A[l++].u.s.cnt;
}
}
/* second pass, right to left, setting internal depths */
m_A[_size - 2].u.s.cnt = 0;
for (n = _size - 3; n >= _start; n--) {
m_A[n].u.s.cnt = m_A[m_A[n].u.s.cnt].u.s.cnt + 1;
}
/* third pass, right to left, setting leaf depths */
a = 1; u = d = 0; r = _size - 2; n = _size - 1;
while (a > 0) {
while (r >= _start && m_A[r].u.s.cnt == d) {
u++; r--;
}
while (a > u) {
m_A[n--].u.s.cnt = d; a--;
if (d > _maxcodelength) { o++; }
}
a = 2 * u; d++; u = 0;
}
return o;
}
/////////////////////////////////////////////////////////////////////
//
//
//
//
//
/////////////////////////////////////////////////////////////////////
int EncHuf::buildCanonicalCodes() {
int ovl;
_sort_for_minimum_redundancy();
ovl = _calculate_minimum_redundancy();
//assert(ovl >= 0);
if (ovl < 0) {
//cerr << "ovl is negative: " << ovl << endl;
//return 1;
return 0;
}
if (ovl > 0) {
_build_B_from_A_for_balancing();
if (_balance_canonical_codes(ovl)) {
cerr << "Code length " << _maxcodelength << " too small!" << endl;
exit(1);
}
_rebuild_A_from_B_for_encoding();
}
_sort_for_canonical_codes();
_calculate_canonical_codes();
_sort_A_for_encoding();
return 0;
}
| gpl-3.0 |
matgla/AquaLampWiFiModule | src/logger/logger.cpp | 1 | 1217 | #include "logger.hpp"
#include <mutex>
#ifndef X86_ARCH
namespace std
{
struct mutex
{
void lock()
{
}
void unlock()
{
}
};
}
#endif
namespace logger
{
static std::mutex logMutex;
Logger::Logger(std::string name, bool insertNewlineWhenDestruct)
: name_(std::move(name)), insertNewlineWhenDestruct_(insertNewlineWhenDestruct)
{
}
Logger::~Logger()
{
if (insertNewlineWhenDestruct_)
{
operator<<("\n");
logMutex.unlock();
}
}
Logger Logger::debug()
{
logMutex.lock();
for (auto& logger : LoggerConf::get().getLoggers())
{
logger.debug(name_);
}
return Logger(name_, true);
}
Logger Logger::info()
{
logMutex.lock();
for (auto& logger : LoggerConf::get().getLoggers())
{
logger.info(name_);
}
return Logger(name_, true);
}
Logger Logger::warn()
{
logMutex.lock();
for (auto& logger : LoggerConf::get().getLoggers())
{
logger.warn(name_);
}
return Logger(name_, true);
}
Logger Logger::error()
{
logMutex.lock();
for (auto& logger : LoggerConf::get().getLoggers())
{
logger.error(name_);
}
return Logger(name_, true);
}
} // namespace logger
| gpl-3.0 |
pavel-pimenov/eiskaltdcpp | dcpp/HashBloom.cpp | 2 | 2365 | /*
* Copyright (C) 2001-2019 Jacek Sieka, arnetheduck on gmail point 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 <https://www.gnu.org/licenses/>.
*/
#include "stdinc.h"
#include "HashBloom.h"
#include <cmath>
#include "MerkleTree.h"
namespace dcpp {
size_t HashBloom::get_k(size_t n, size_t h) {
for(size_t k = TTHValue::BITS/h; k > 1; --k) {
uint64_t m = get_m(n, k);
if(m >> 24 == 0) {
return k;
}
}
return 1;
}
uint64_t HashBloom::get_m(size_t n, size_t k) {
uint64_t m = (static_cast<uint64_t>(ceil(static_cast<double>(n) * k / log(2.))));
// 64-bit boundary as per spec
return ((m + 63ULL )/ 64ULL) * 64ULL;
}
void HashBloom::add(const TTHValue& tth) {
for(size_t i = 0; i < k; ++i) {
bloom[pos(tth, i)] = true;
}
}
bool HashBloom::match(const TTHValue& tth) const {
if(bloom.empty()) {
return false;
}
for(size_t i = 0; i < k; ++i) {
if(!bloom[pos(tth, i)]) {
return false;
}
}
return true;
}
void HashBloom::push_back(bool v) {
bloom.push_back(v);
}
void HashBloom::reset(size_t k_, size_t m, size_t h_) {
bloom.resize(m);
k = k_;
h = h_;
}
size_t HashBloom::pos(const TTHValue& tth, size_t n) const {
if((n+1)*h > TTHValue::BITS) {
return 0;
}
uint64_t x = 0;
size_t start = n * h;
for(size_t i = 0; i < h; ++i) {
size_t bit = start + i;
size_t byte = bit / 8;
size_t pos = bit % 8;
if(tth.data[byte] & (1 << pos)) {
x |= (1LL << i);
}
}
return x % bloom.size();
}
void HashBloom::copy_to(ByteVector& v) const {
v.resize(bloom.size() / 8);
for(size_t i = 0; i < bloom.size(); ++i) {
v[i/8] |= bloom[i] << (i % 8);
}
}
}
| gpl-3.0 |
Phil9l/cosmos | code/data_structures/src/tree/binary_tree/binary_tree/is_binary_tree/is_binary_tree.cpp | 2 | 1412 | /* A binary tree node has data, pointer to left child
* and a pointer to right child
*
* struct Node {
* int data;
* Node* left, * right;
* };
*
*/
/* Should return true if tree represented by root is BST.
* For example, return value should be 1 for following tree.
* 20
* / \
* 10 30
* and return value should be 0 for following tree.
* 10
* / \
* 20 30 */
template<typename Node>
Node *findmax(Node *root)
{
if (!root)
return nullptr;
while (root->right)
root = root->right;
return root;
}
template<typename Node>
Node *findmin(Node *root)
{
if (!root)
return nullptr;
while (root->left)
root = root->left;
return root;
}
template<typename Node>
bool isBST(Node* root)
{
if (!root)
return 1;
if (root->left && findmax(root->left)->data > (root->data))
return 0;
if (root->right && findmin(root->right)->data < (root->data))
return 0;
if (!isBST(root->left) || !isBST(root->right))
return 0;
return 1;
}
// Another variation
// Utility function
template<typename Node>
int isBSTUtil(Node *root, int min, int max)
{
if (!root)
return 1;
if (root->data < min || root->data > max)
return 0;
return isBSTUtil(root->left, min, root->data - 1) &&
isBSTUtil(root->right, root->data + 1, max);
}
| gpl-3.0 |
ystk/debian-coreutils | src/cksum.c | 2 | 9714 | /* cksum -- calculate and print POSIX checksums and sizes of files
Copyright (C) 1992, 1995-2006, 2008-2010 Free Software Foundation, 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 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/>. */
/* Written by Q. Frank Xia, qx@math.columbia.edu.
Cosmetic changes and reorganization by David MacKenzie, djm@gnu.ai.mit.edu.
Usage: cksum [file...]
The code segment between "#ifdef CRCTAB" and "#else" is the code
which calculates the "crctab". It is included for those who want
verify the correctness of the "crctab". To recreate the "crctab",
do something like the following:
cc -DCRCTAB -o crctab cksum.c
crctab > crctab.h
This software is compatible with neither the System V nor the BSD
`sum' program. It is supposed to conform to POSIX, except perhaps
for foreign language support. Any inconsistency with the standard
(other than foreign language support) is a bug. */
#include <config.h>
/* The official name of this program (e.g., no `g' prefix). */
#define PROGRAM_NAME "cksum"
#define AUTHORS proper_name ("Q. Frank Xia")
#include <stdio.h>
#include <sys/types.h>
#include <stdint.h>
#include "system.h"
#include "xfreopen.h"
#ifdef CRCTAB
# define BIT(x) ((uint_fast32_t) 1 << (x))
# define SBIT BIT (31)
/* The generating polynomial is
32 26 23 22 16 12 11 10 8 7 5 4 2 1
G(X)=X + X + X + X + X + X + X + X + X + X + X + X + X + X + 1
The i bit in GEN is set if X^i is a summand of G(X) except X^32. */
# define GEN (BIT (26) | BIT (23) | BIT (22) | BIT (16) | BIT (12) \
| BIT (11) | BIT (10) | BIT (8) | BIT (7) | BIT (5) \
| BIT (4) | BIT (2) | BIT (1) | BIT (0))
static uint_fast32_t r[8];
static void
fill_r (void)
{
int i;
r[0] = GEN;
for (i = 1; i < 8; i++)
r[i] = (r[i - 1] << 1) ^ ((r[i - 1] & SBIT) ? GEN : 0);
}
static uint_fast32_t
crc_remainder (int m)
{
uint_fast32_t rem = 0;
int i;
for (i = 0; i < 8; i++)
if (BIT (i) & m)
rem ^= r[i];
return rem & 0xFFFFFFFF; /* Make it run on 64-bit machine. */
}
int
main (void)
{
int i;
fill_r ();
printf ("static uint_fast32_t const crctab[256] =\n{\n 0x00000000");
for (i = 0; i < 51; i++)
{
printf (",\n 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x",
crc_remainder (i * 5 + 1), crc_remainder (i * 5 + 2),
crc_remainder (i * 5 + 3), crc_remainder (i * 5 + 4),
crc_remainder (i * 5 + 5));
}
printf ("\n};\n");
exit (EXIT_SUCCESS);
}
#else /* !CRCTAB */
# include <getopt.h>
# include "long-options.h"
# include "error.h"
/* Number of bytes to read at once. */
# define BUFLEN (1 << 16)
static uint_fast32_t const crctab[256] =
{
0x00000000,
0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6,
0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac,
0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f,
0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a,
0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58,
0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033,
0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe,
0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4,
0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5,
0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07,
0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c,
0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1,
0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b,
0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698,
0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d,
0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f,
0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80,
0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a,
0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629,
0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c,
0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e,
0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65,
0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8,
0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2,
0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74,
0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21,
0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a,
0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087,
0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d,
0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce,
0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb,
0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09,
0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf,
0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};
/* Nonzero if any of the files read were the standard input. */
static bool have_read_stdin;
/* Calculate and print the checksum and length in bytes
of file FILE, or of the standard input if FILE is "-".
If PRINT_NAME is true, print FILE next to the checksum and size.
Return true if successful. */
static bool
cksum (const char *file, bool print_name)
{
unsigned char buf[BUFLEN];
uint_fast32_t crc = 0;
uintmax_t length = 0;
size_t bytes_read;
FILE *fp;
char length_buf[INT_BUFSIZE_BOUND (uintmax_t)];
char const *hp;
if (STREQ (file, "-"))
{
fp = stdin;
have_read_stdin = true;
if (O_BINARY && ! isatty (STDIN_FILENO))
xfreopen (NULL, "rb", stdin);
}
else
{
fp = fopen (file, (O_BINARY ? "rb" : "r"));
if (fp == NULL)
{
error (0, errno, "%s", file);
return false;
}
}
while ((bytes_read = fread (buf, 1, BUFLEN, fp)) > 0)
{
unsigned char *cp = buf;
if (length + bytes_read < length)
error (EXIT_FAILURE, 0, _("%s: file too long"), file);
length += bytes_read;
while (bytes_read--)
crc = (crc << 8) ^ crctab[((crc >> 24) ^ *cp++) & 0xFF];
if (feof (fp))
break;
}
if (ferror (fp))
{
error (0, errno, "%s", file);
if (!STREQ (file, "-"))
fclose (fp);
return false;
}
if (!STREQ (file, "-") && fclose (fp) == EOF)
{
error (0, errno, "%s", file);
return false;
}
hp = umaxtostr (length, length_buf);
for (; length; length >>= 8)
crc = (crc << 8) ^ crctab[((crc >> 24) ^ length) & 0xFF];
crc = ~crc & 0xFFFFFFFF;
if (print_name)
printf ("%u %s %s\n", (unsigned int) crc, hp, file);
else
printf ("%u %s\n", (unsigned int) crc, hp);
if (ferror (stdout))
error (EXIT_FAILURE, errno, "-: %s", _("write error"));
return true;
}
void
usage (int status)
{
if (status != EXIT_SUCCESS)
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
else
{
printf (_("\
Usage: %s [FILE]...\n\
or: %s [OPTION]\n\
"),
program_name, program_name);
fputs (_("\
Print CRC checksum and byte counts of each FILE.\n\
\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
emit_ancillary_info ();
}
exit (status);
}
int
main (int argc, char **argv)
{
int i;
bool ok;
initialize_main (&argc, &argv);
set_program_name (argv[0]);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
atexit (close_stdout);
parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, Version,
usage, AUTHORS, (char const *) NULL);
if (getopt_long (argc, argv, "", NULL, NULL) != -1)
usage (EXIT_FAILURE);
have_read_stdin = false;
if (optind == argc)
ok = cksum ("-", false);
else
{
ok = true;
for (i = optind; i < argc; i++)
ok &= cksum (argv[i], true);
}
if (have_read_stdin && fclose (stdin) == EOF)
error (EXIT_FAILURE, errno, "-");
exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
}
#endif /* !CRCTAB */
| gpl-3.0 |
DarkCaster/emu-ex-plus-alpha | C64.emu/src/vice/serial/serial-iec.c | 2 | 3008 | /*
* serial-iec.c
*
* Written by
* Andreas Boose <viceteam@t-online.de>
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* 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 "vice.h"
#include "serial-iec-bus.h"
#include "serial-iec.h"
#include "types.h"
static int serial_iec_st = 0;
static unsigned int listen_active = 0;
static unsigned int talk = 0;
static void serial_iec_set_st(uint8_t st)
{
serial_iec_st = (int)st;
}
int serial_iec_open(unsigned int unit, unsigned int secondary,
const char *name, unsigned int length)
{
unsigned int i;
serial_iec_bus_open(unit, (uint8_t)secondary, serial_iec_set_st);
for (i = 0; i < length; i++) {
serial_iec_bus_write(unit, (uint8_t)secondary, name[i], serial_iec_set_st);
}
serial_iec_bus_unlisten(unit, (uint8_t)secondary, serial_iec_set_st);
return 0;
}
int serial_iec_close(unsigned int unit, unsigned int secondary)
{
if (listen_active) {
serial_iec_bus_unlisten(unit, (uint8_t)secondary, serial_iec_set_st);
listen_active = 0;
}
if (talk) {
serial_iec_bus_untalk(unit, (uint8_t)secondary, serial_iec_set_st);
talk = 0;
}
serial_iec_bus_close(unit, (uint8_t)secondary, serial_iec_set_st);
return 0;
}
int serial_iec_read(unsigned int unit, unsigned int secondary, uint8_t *data)
{
if (listen_active) {
serial_iec_bus_unlisten(unit, (uint8_t)secondary, serial_iec_set_st);
listen_active = 0;
}
if (!talk) {
serial_iec_bus_talk(unit | 0x40, (uint8_t)secondary, serial_iec_set_st);
talk = 1;
}
*data = serial_iec_bus_read(unit, (uint8_t)secondary, serial_iec_set_st);
return serial_iec_st;
}
int serial_iec_write(unsigned int unit, unsigned int secondary, uint8_t data)
{
if (talk) {
serial_iec_bus_untalk(unit, (uint8_t)secondary, serial_iec_set_st);
talk = 0;
}
if (!listen_active) {
serial_iec_bus_listen(unit | 0x20, (uint8_t)secondary, serial_iec_set_st);
listen_active = 1;
}
serial_iec_bus_write(unit, (uint8_t)secondary, data, serial_iec_set_st);
return serial_iec_st;
}
int serial_iec_flush(unsigned int unit, unsigned int secondary)
{
return 0;
}
| gpl-3.0 |
BeGe78/esood | vendor/bundle/ruby/3.0.0/gems/passenger-6.0.5/src/agent/Shared/Fundamentals/Utils.cpp | 3 | 3339 | /*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2010-2017 Phusion Holding B.V.
*
* "Passenger", "Phusion Passenger" and "Union Station" are registered
* trademarks of Phusion Holding B.V.
*
* 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.
*/
#include <Shared/Fundamentals/Utils.h>
#include <oxt/backtrace.hpp>
#include <cstdlib>
#include <cstring>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
namespace Passenger {
namespace Agent {
namespace Fundamentals {
using namespace std;
const char *
getEnvString(const char *name, const char *defaultValue) {
const char *value = getenv(name);
if (value != NULL && *value != '\0') {
return value;
} else {
return defaultValue;
}
}
bool
getEnvBool(const char *name, bool defaultValue) {
const char *value = getEnvString(name);
if (value != NULL) {
return strcmp(value, "yes") == 0
|| strcmp(value, "y") == 0
|| strcmp(value, "1") == 0
|| strcmp(value, "on") == 0
|| strcmp(value, "true") == 0;
} else {
return defaultValue;
}
}
void
ignoreSigpipe() {
struct sigaction action;
action.sa_handler = SIG_IGN;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGPIPE, &action, NULL);
}
/**
* Linux-only way to change OOM killer configuration for
* current process. Requires root privileges, which we
* should have.
*
* Returns 0 on success, or an errno code on error.
*
* This function is async signal-safe.
*/
int
tryRestoreOomScore(const StaticString &scoreString, bool &isLegacy) {
TRACE_POINT();
if (scoreString.empty()) {
return 0;
}
int fd, ret, e;
size_t written = 0;
StaticString score;
if (scoreString.at(0) == 'l') {
isLegacy = true;
score = scoreString.substr(1);
fd = open("/proc/self/oom_adj", O_WRONLY | O_TRUNC, 0600);
} else {
isLegacy = false;
score = scoreString;
fd = open("/proc/self/oom_score_adj", O_WRONLY | O_TRUNC, 0600);
}
if (fd == -1) {
return errno;
}
do {
ret = write(fd, score.data() + written, score.size() - written);
if (ret != -1) {
written += ret;
}
} while (ret == -1 && errno != EAGAIN && written < score.size());
e = errno;
close(fd);
if (ret == -1) {
return e;
} else {
return 0;
}
}
} // namespace Fundamentals
} // namespace Agent
} // namespace Passenger
| gpl-3.0 |
jshackley/darkstar | src/map/ai/states/magic_state.cpp | 3 | 28942 | /*
===========================================================================
Copyright (c) 2010-2015 Darkstar Dev Teams
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/
This file is part of DarkStar-server source code.
===========================================================================
*/
#include "magic_state.h"
#include "../../entities/mobentity.h"
#include "../../entities/charentity.h"
#include "../../lua/luautils.h"
#include "../../utils/battleutils.h"
#include "../../utils/charutils.h"
#include "../ai_pet_dummy.h"
#include "../../packets/char_update.h"
#include "../../spell.h"
CMagicState::CMagicState(CBattleEntity* PEntity, CTargetFind* PTargetFind, float maxStartDistance, float maxFinishDistance)
: CState(PEntity, PTargetFind)
{
m_PSpell = nullptr;
m_enableCasting = true;
m_maxStartDistance = maxStartDistance;
m_maxFinishDistance = maxFinishDistance;
}
STATESTATUS CMagicState::CastSpell(CSpell* PSpell, CBattleEntity* PTarget, uint8 flags)
{
if(!CanCastSpell(PSpell, PTarget, flags))
{
return STATESTATUS_ERROR;
}
Clear();
m_PSpell = PSpell;
m_PTarget = PTarget;
m_flags = flags;
m_startPosition = m_PEntity->loc.p;
m_castTime = CalculateCastTime(PSpell);
apAction_t action;
action.ActionTarget = m_PTarget;
action.reaction = REACTION_NONE;
action.speceffect = SPECEFFECT_NONE;
action.animation = 0;
action.param = m_PSpell->getID();
action.messageID = 327; // starts casting
m_PEntity->m_ActionList.clear();
m_PEntity->m_ActionList.push_back(action);
m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(m_PEntity));
return STATESTATUS_START;
}
bool CMagicState::CanCastSpell(CSpell* PSpell, CBattleEntity* PTarget, uint8 flags)
{
if(PSpell == nullptr) return false;
if(!ValidCast(PSpell, PTarget))
{
return false;
}
if(m_PEntity->objtype == TYPE_PC)
{
float distanceValue = distance(m_PEntity->loc.p, PTarget->loc.p);
// pc has special messages
if(distanceValue > 25)
{
PushError(MSGBASIC_TOO_FAR_AWAY, PSpell->getID(), 0, PTarget);
return false;
}
else if(distanceValue > m_maxStartDistance)
{
PushError(MSGBASIC_OUT_OF_RANGE_UNABLE_CAST, PSpell->getID(), 0, PTarget);
return false;
}
}
else if(!m_PTargetFind->isWithinRange(&PTarget->loc.p, m_maxStartDistance)){
return false;
}
// player specific
if(m_PEntity->objtype == TYPE_PC && !ValidCharCast(PSpell))
{
return false;
}
int32 msgID = luautils::OnMagicCastingCheck(m_PEntity, PTarget, PSpell);
if(msgID){
PushError((MSGBASIC_ID)msgID, PSpell->getID(), 0, PTarget);
return false;
}
return true;
}
bool CMagicState::IsInterrupted()
{
return m_interruptSpell;
}
void CMagicState::ForceInterrupt()
{
m_interruptSpell = true;
}
CSpell* CMagicState::GetSpell()
{
return m_PSpell;
}
STATESTATUS CMagicState::Update(uint32 tick)
{
if(CState::Update(tick) == STATESTATUS_ERROR || !CheckValidTarget(m_PTarget))
{
return STATESTATUS_ERROR;
}
if(m_startTime == 0) m_startTime = tick;
if(tick - m_startTime >= m_castTime)
{
if(CheckInterrupt())
{
return STATESTATUS_INTERRUPT;
}
else
{
return STATESTATUS_FINISH;
}
}
return STATESTATUS_TICK;
}
void CMagicState::Clear()
{
CState::Clear();
m_PSpell = nullptr;
m_interruptSpell = false;
m_startTime = 0;
}
uint32 CMagicState::CalculateCastTime(CSpell* PSpell)
{
if(PSpell == nullptr)
{
return 0;
}
bool applyArts = true;
uint32 base = PSpell->getCastTime();
uint32 cast = base;
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_HASSO) || m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_SEIGAN))
{
cast = cast * 1.5f;
}
if (PSpell->getSpellGroup() == SPELLGROUP_BLACK)
{
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_ALACRITY))
{
uint16 bonus = 0;
//Only apply Alacrity/celerity mod if the spell element matches the weather.
if(battleutils::WeatherMatchesElement(battleutils::GetWeather(m_PEntity,false),PSpell->getElement()))
{
bonus = m_PEntity->getMod(MOD_ALACRITY_CELERITY_EFFECT);
}
cast -= base * ((100 - (50 + bonus)) / 100.0f);
applyArts = false;
}
else if (applyArts)
{
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_DARK_ARTS) || m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_ADDENDUM_BLACK))
{
// Add any "Grimoire: Reduces spellcasting time" bonuses
cast = cast * (1.0f + (m_PEntity->getMod(MOD_BLACK_MAGIC_CAST)+m_PEntity->getMod(MOD_GRIMOIRE_SPELLCASTING))/100.0f);
}
else
{
cast = cast * (1.0f + m_PEntity->getMod(MOD_BLACK_MAGIC_CAST)/100.0f);
}
}
}
else if (PSpell->getSpellGroup() == SPELLGROUP_WHITE)
{
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_CELERITY))
{
uint16 bonus = 0;
//Only apply Alacrity/celerity mod if the spell element matches the weather.
if(battleutils::WeatherMatchesElement(battleutils::GetWeather(m_PEntity,false),PSpell->getElement()))
{
bonus = m_PEntity->getMod(MOD_ALACRITY_CELERITY_EFFECT);
}
cast -= base * ((100 - (50 + bonus)) / 100.0f);
applyArts = false;
}
else if (applyArts)
{
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_LIGHT_ARTS) || m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_ADDENDUM_WHITE))
{
// Add any "Grimoire: Reduces spellcasting time" bonuses
cast = cast * (1.0f + (m_PEntity->getMod(MOD_WHITE_MAGIC_CAST)+m_PEntity->getMod(MOD_GRIMOIRE_SPELLCASTING))/100.0f);
}
else
{
cast = cast * (1.0f + m_PEntity->getMod(MOD_WHITE_MAGIC_CAST)/100.0f);
}
}
}
else if (PSpell->getSpellGroup() == SPELLGROUP_SONG)
{
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_PIANISSIMO))
{
if (PSpell->getAOE() == SPELLAOE_PIANISSIMO)
{
cast = base / 2;
}
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_NIGHTINGALE))
{
if (m_PEntity->objtype == TYPE_PC &&
dsprand::GetRandomNumber(100) < ((CCharEntity*)m_PEntity)->PMeritPoints->GetMeritValue(MERIT_NIGHTINGALE, (CCharEntity*)m_PEntity) - 25)
{
return 0;
}
cast = cast * 0.5f;
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_TROUBADOUR))
{
cast = cast * 1.5f;
}
uint16 songcasting = m_PEntity->getMod(MOD_SONG_SPELLCASTING_TIME);
cast = cast * (1.0f - ((songcasting > 50 ? 50 : songcasting) / 100.0f));
}
int16 fastCast = dsp_cap(m_PEntity->getMod(MOD_FASTCAST), -100, 50);
if (PSpell->isCure()) // Cure cast time reductions
{
fastCast += m_PEntity->getMod(MOD_CURE_CAST_TIME);
if (m_PEntity->objtype == TYPE_PC)
{
fastCast += ((CCharEntity*)m_PEntity)->PMeritPoints->GetMeritValue(MERIT_CURE_CAST_TIME, (CCharEntity*)m_PEntity);
}
fastCast = dsp_cap(fastCast, -100, 80);
}
int16 uncappedFastCast = dsp_cap(m_PEntity->getMod(MOD_UFASTCAST), -100, 100);
float sumFastCast = dsp_cap(fastCast + uncappedFastCast, -100, 100);
return cast * ((100.0f - sumFastCast)/100.0f);
}
int16 CMagicState::CalculateMPCost(CSpell* PSpell)
{
if(PSpell == nullptr)
{
ShowWarning("CMagicState::CalculateMPCost Spell is NULL\n");
return 0;
}
// ninja tools or bard song
if(!PSpell->hasMPCost())
{
return 0;
}
bool applyArts = true;
uint16 base = PSpell->getMPCost();
if (PSpell->getID() == 478 || PSpell->getID() == 502) //Embrava/Kaustra
{
base = m_PEntity->health.maxmp * 0.2;
}
int16 cost = base;
if (PSpell->getSpellGroup() == SPELLGROUP_BLACK)
{
if (PSpell->getAOE() == SPELLAOE_RADIAL_MANI && m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_MANIFESTATION))
{
cost *= 2;
applyArts = false;
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_PARSIMONY))
{
cost /= 2;
applyArts = false;
}
else if (applyArts)
{
cost += base * (m_PEntity->getMod(MOD_BLACK_MAGIC_COST)/100.0f);
}
}
else if (PSpell->getSpellGroup() == SPELLGROUP_WHITE)
{
if (PSpell->getAOE() == SPELLAOE_RADIAL_ACCE && m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_ACCESSION))
{
cost *= 2;
applyArts = false;
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_PENURY))
{
cost /= 2;
applyArts = false;
}
else if (applyArts)
{
cost += base * (m_PEntity->getMod(MOD_WHITE_MAGIC_COST)/100.0f);
}
}
if (dsprand::GetRandomNumber(100) < (m_PEntity->getMod(MOD_NO_SPELL_MP_DEPLETION)))
{
cost = 0;
}
return dsp_cap(cost, 0, 9999);
}
uint32 CMagicState::CalculateRecastTime(CSpell* PSpell)
{
if(PSpell == nullptr)
{
return 0;
}
bool applyArts = true;
uint32 base = PSpell->getRecastTime();
uint32 recast = base;
//apply Fast Cast
recast *= ((100.0f-dsp_cap((float)m_PEntity->getMod(MOD_FASTCAST)/2.0f,0.0f,25.0f))/100.0f);
int16 haste = m_PEntity->getMod(MOD_HASTE_MAGIC) + m_PEntity->getMod(MOD_HASTE_GEAR);
recast *= ((float)(1024-haste)/1024);
recast = dsp_max(recast, base * 0.2f);
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_COMPOSURE))
{
recast *= 1.25;
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_HASSO) || m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_SEIGAN))
{
recast *= 1.5;
}
if (PSpell->getSpellGroup() == SPELLGROUP_BLACK)
{
if (PSpell->getAOE() == SPELLAOE_RADIAL_MANI && m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_MANIFESTATION))
{
if (m_PEntity->GetMJob() == JOB_SCH)
{
recast *= 2;
}
else
{
recast *= 3;
}
applyArts = false;
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_ALACRITY))
{
uint16 bonus = 0;
//Only apply Alacrity/celerity mod if the spell element matches the weather.
if (battleutils::WeatherMatchesElement(battleutils::GetWeather(m_PEntity,false), PSpell->getElement()))
{
bonus = m_PEntity->getMod(MOD_ALACRITY_CELERITY_EFFECT);
}
recast *= ((50 - bonus) / 100.0f);
applyArts = false;
}
if (applyArts)
{
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_DARK_ARTS) || m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_ADDENDUM_BLACK))
{
// Add any "Grimoire: Reduces spellcasting time" bonuses
recast *= (1.0f + (m_PEntity->getMod(MOD_BLACK_MAGIC_RECAST)+m_PEntity->getMod(MOD_GRIMOIRE_SPELLCASTING))/100.0f);
}
else
{
recast *= (1.0f + m_PEntity->getMod(MOD_BLACK_MAGIC_RECAST)/100.0f);
}
}
}
else if (PSpell->getSpellGroup() == SPELLGROUP_WHITE)
{
if (PSpell->getAOE() == SPELLAOE_RADIAL_ACCE && m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_ACCESSION))
{
if (m_PEntity->GetMJob() == JOB_SCH)
{
recast *= 2;
}
else
{
recast *= 3;
}
applyArts = false;
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_CELERITY))
{
uint16 bonus = 0;
//Only apply Alacrity/celerity mod if the spell element matches the weather.
if (battleutils::WeatherMatchesElement(battleutils::GetWeather(m_PEntity, true), PSpell->getElement()))
{
bonus = m_PEntity->getMod(MOD_ALACRITY_CELERITY_EFFECT);
}
recast *= ((50 - bonus) / 100.0f);
applyArts = false;
}
if (applyArts)
{
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_LIGHT_ARTS) || m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_ADDENDUM_WHITE))
{
// Add any "Grimoire: Reduces spellcasting time" bonuses
recast *= (1.0f + (m_PEntity->getMod(MOD_WHITE_MAGIC_RECAST)+m_PEntity->getMod(MOD_GRIMOIRE_SPELLCASTING))/100.0f);
}
else
{
recast *= (1.0f + m_PEntity->getMod(MOD_WHITE_MAGIC_RECAST)/100.0f);
}
}
}
else if (PSpell->getSpellGroup() == SPELLGROUP_SONG)
{
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_NIGHTINGALE))
{
recast *= 0.5f;
}
}
return recast/1000;
}
bool CMagicState::CheckInterrupt()
{
if(m_interruptSpell)
{
PushMessage(MSGBASIC_IS_INTERRUPTED);
return true;
}
if(!m_PTargetFind->isWithinRange(&m_PTarget->loc.p, m_maxFinishDistance))
{
PushError(MSGBASIC_OUT_OF_RANGE_UNABLE_CAST, m_PSpell->getID());
return true;
}
// check if in same place
if(m_PEntity->objtype == TYPE_PC && HasMoved())
{
PushError(MSGBASIC_IS_INTERRUPTED, m_PSpell->getID());
return true;
}
if(!ValidCast(m_PSpell, m_PTarget))
{
return true;
}
if(battleutils::IsIntimidated(m_PEntity, m_PTarget))
{
PushMessage(MSGBASIC_IS_INTIMIDATED);
return true;
}
if(battleutils::IsParalyzed(m_PEntity))
{
PushMessage(MSGBASIC_IS_PARALYZED);
return true;
}
return false;
}
bool CMagicState::ValidCast(CSpell* PSpell, CBattleEntity* PTarget)
{
if (!CheckValidTarget(PTarget))
{
PushError(MSGBASIC_CANNOT_ON_THAT_TARG, 0);
return false;
}
if(!m_enableCasting ||
m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_SILENCE) ||
m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_MUTE))
{
PushError(MSGBASIC_UNABLE_TO_CAST_SPELLS, PSpell->getID());
return false;
}
if (PSpell->getSpellGroup() == SPELLGROUP_NINJUTSU)
{
if(m_PEntity->objtype == TYPE_PC && !(m_flags & MAGICFLAGS_IGNORE_TOOLS) && !battleutils::HasNinjaTool(m_PEntity, PSpell, false))
{
PushError(MSGBASIC_NO_NINJA_TOOLS, PSpell->getID());
return false;
}
}
// check has mp available
else if(!m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_MANAFONT) && !(m_flags & MAGICFLAGS_IGNORE_MP) && CalculateMPCost(PSpell) > m_PEntity->health.mp)
{
if(m_PEntity->objtype == TYPE_MOB && m_PEntity->health.maxmp == 0)
{
ShowWarning("CMagicState::ValidCast Mob (%u) tried to cast magic with no mp!\n", m_PEntity->id);
}
PushError(MSGBASIC_NOT_ENOUGH_MP, PSpell->getID());
return false;
}
if (!spell::CanUseSpell(m_PEntity, PSpell->getID()))
{
PushError(MSGBASIC_CANNOT_CAST_SPELL, PSpell->getID());
return false;
}
if(PTarget->isDead() && !(PSpell->getValidTarget() & TARGET_PLAYER_DEAD))
{
return false;
}
if(!PTarget->isDead() && (PSpell->getValidTarget() & TARGET_PLAYER_DEAD))
{
return false;
}
return true;
}
void CMagicState::InterruptSpell()
{
DSP_DEBUG_BREAK_IF(m_PSpell == nullptr);
DSP_DEBUG_BREAK_IF(m_PEntity->PBattleAI->GetCurrentAction() != ACTION_MAGIC_INTERRUPT);
apAction_t action;
action.ActionTarget = m_PEntity;
action.reaction = REACTION_NONE;
action.speceffect = SPECEFFECT_NONE;
action.animation = m_PSpell->getAnimationID();
action.param = 0;
action.messageID = 0;
m_PEntity->m_ActionList.clear();
m_PEntity->m_ActionList.push_back(action);
m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(m_PEntity));
Clear();
}
void CMagicState::FinishSpell()
{
DSP_DEBUG_BREAK_IF(m_PSpell == nullptr);
DSP_DEBUG_BREAK_IF(m_PEntity->PBattleAI->GetCurrentAction() != ACTION_MAGIC_FINISH);
luautils::OnSpellPrecast(m_PEntity, m_PSpell);
SpendCost(m_PSpell);
SetRecast(m_PSpell);
// remove effects based on spell cast first
int16 effectFlags = EFFECTFLAG_INVISIBLE | EFFECTFLAG_MAGIC_BEGIN;
if (m_PSpell->canTargetEnemy())
{
effectFlags |= EFFECTFLAG_DETECTABLE;
}
m_PEntity->StatusEffectContainer->DelStatusEffectsByFlag(effectFlags);
m_PTargetFind->reset();
m_PEntity->m_ActionList.clear();
// setup special targeting flags
// can this spell target the dead?
uint8 flags = FINDFLAGS_NONE;
if (m_PSpell->getValidTarget() & TARGET_PLAYER_DEAD)
{
flags |= FINDFLAGS_DEAD;
}
if (m_PSpell->getFlag() & SPELLFLAG_HIT_ALL)
{
flags |= FINDFLAGS_HIT_ALL;
}
uint8 aoeType = battleutils::GetSpellAoEType(m_PEntity, m_PSpell);
if (aoeType == SPELLAOE_RADIAL) {
float distance = spell::GetSpellRadius(m_PSpell, m_PEntity);
m_PTargetFind->findWithinArea(m_PTarget, AOERADIUS_TARGET, distance, flags);
}
else if (aoeType == SPELLAOE_CONAL)
{
//TODO: actual radius calculation
float radius = spell::GetSpellRadius(m_PSpell, m_PEntity);
m_PTargetFind->findWithinCone(m_PTarget, radius, 45, flags);
}
else
{
// only add target
m_PTargetFind->findSingleTarget(m_PTarget, flags);
}
uint16 totalTargets = m_PTargetFind->m_targets.size();
m_PSpell->setTotalTargets(totalTargets);
apAction_t action;
action.ActionTarget = m_PTarget;
action.reaction = REACTION_NONE;
action.speceffect = SPECEFFECT_NONE;
action.animation = m_PSpell->getAnimationID();
action.param = 0;
action.messageID = 0;
uint16 msg = 0;
int16 ce = 0;
int16 ve = 0;
for (std::vector<CBattleEntity*>::iterator it = m_PTargetFind->m_targets.begin() ; it != m_PTargetFind->m_targets.end(); ++it)
{
CBattleEntity* PTarget = *it;
action.ActionTarget = PTarget;
ce = m_PSpell->getCE();
ve = m_PSpell->getVE();
// take all shadows
if (m_PSpell->canTargetEnemy() && aoeType > 0)
{
PTarget->StatusEffectContainer->DelStatusEffect(EFFECT_BLINK);
PTarget->StatusEffectContainer->DelStatusEffect(EFFECT_COPY_IMAGE);
}
// TODO: this is really hacky and should eventually be moved into lua
if (m_PSpell->canHitShadow() && aoeType == SPELLAOE_NONE && battleutils::IsAbsorbByShadow(PTarget))
{
// take shadow
msg = 31;
action.param = 1;
ve = 0;
ce = 0;
}
else
{
action.param = luautils::OnSpellCast(m_PEntity, PTarget, m_PSpell);
// remove effects from damage
if (m_PSpell->canTargetEnemy() && action.param > 0 && m_PSpell->dealsDamage())
{
PTarget->StatusEffectContainer->DelStatusEffectsByFlag(EFFECTFLAG_DAMAGE);
// Check for bind breaking
battleutils::BindBreakCheck(m_PEntity, PTarget);
}
if(msg == 0)
{
msg = m_PSpell->getMessage();
}
else
{
msg = m_PSpell->getAoEMessage();
}
}
if (action.animation == 122 && msg == 283) // teleport spells don't target unqualified members
continue;
action.messageID = msg;
if (PTarget->objtype == TYPE_MOB && msg != 31) // If message isn't the shadow loss message, because I had to move this outside of the above check for it.
{
luautils::OnMagicHit(m_PEntity, PTarget, m_PSpell);
}
if (m_PSpell->getID() != 305) //I hate to do this, but there really is no other spell like Odin
CharOnTarget(&action, ce, ve);
m_PEntity->m_ActionList.push_back(action);
}
CharAfterFinish();
m_PEntity->StatusEffectContainer->DelStatusEffectsByFlag(EFFECTFLAG_MAGIC_END);
DSP_DEBUG_BREAK_IF(m_PEntity->PBattleAI->GetCurrentAction() != ACTION_MAGIC_FINISH);
m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(m_PEntity));
Clear();
}
void CMagicState::CharOnTarget(apAction_t* action, int16 ce, int16 ve)
{
if(m_PEntity->objtype != TYPE_PC)
{
return;
}
CBattleEntity* PTarget = action->ActionTarget;
bool enmityApplied = false;
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_TRANQUILITY) && m_PSpell->getSpellGroup() == SPELLGROUP_WHITE)
{
m_PEntity->addModifier(MOD_ENMITY, -m_PEntity->StatusEffectContainer->GetStatusEffect(EFFECT_TRANQUILITY)->GetPower());
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_EQUANIMITY) && m_PSpell->getSpellGroup() == SPELLGROUP_BLACK)
{
m_PEntity->addModifier(MOD_ENMITY, -m_PEntity->StatusEffectContainer->GetStatusEffect(EFFECT_EQUANIMITY)->GetPower());
}
if (PTarget->objtype == TYPE_MOB && PTarget->allegiance != m_PEntity->allegiance)
{
if (PTarget->isDead())
{
((CMobEntity*)PTarget)->m_DropItemTime = m_PSpell->getAnimationTime();
}
if (!(m_PSpell->isHeal()) || m_PSpell->tookEffect()) //can't claim mob with cure unless it does damage
{
((CMobEntity*)PTarget)->m_OwnerID.id = m_PEntity->id;
((CMobEntity*)PTarget)->m_OwnerID.targid = m_PEntity->targid;
((CMobEntity*)PTarget)->updatemask |= UPDATE_STATUS;
((CMobEntity*)PTarget)->PEnmityContainer->UpdateEnmity(m_PEntity, ce, ve);
enmityApplied = true;
}
}
else if (PTarget->allegiance == m_PEntity->allegiance)
{
battleutils::GenerateInRangeEnmity(m_PEntity, ce, ve);
enmityApplied = true;
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_TRANQUILITY) && m_PSpell->getSpellGroup() == SPELLGROUP_WHITE)
{
m_PEntity->delModifier(MOD_ENMITY, -m_PEntity->StatusEffectContainer->GetStatusEffect(EFFECT_TRANQUILITY)->GetPower());
if (enmityApplied)
m_PEntity->StatusEffectContainer->DelStatusEffect(EFFECT_TRANQUILITY);
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_EQUANIMITY) && m_PSpell->getSpellGroup() == SPELLGROUP_BLACK)
{
m_PEntity->delModifier(MOD_ENMITY, -m_PEntity->StatusEffectContainer->GetStatusEffect(EFFECT_EQUANIMITY)->GetPower());
if (enmityApplied)
m_PEntity->StatusEffectContainer->DelStatusEffect(EFFECT_EQUANIMITY);
}
if(action->param > 0 && m_PSpell->dealsDamage() && m_PSpell->getSpellGroup() == SPELLGROUP_BLUE &&
m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_CHAIN_AFFINITY) && ((CBlueSpell*)m_PSpell)->getPrimarySkillchain() != 0)
{
SUBEFFECT effect = battleutils::GetSkillChainEffect(PTarget, (CBlueSpell*)m_PSpell);
if (effect != SUBEFFECT_NONE)
{
uint16 skillChainDamage = battleutils::TakeSkillchainDamage(m_PEntity, PTarget, action->param);
action->addEffectParam = skillChainDamage;
action->addEffectMessage = 287 + effect;
action->additionalEffect = effect;
}
if (m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_SEKKANOKI) || m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_MEIKYO_SHISUI))
{
m_PEntity->health.tp = (m_PEntity->health.tp > 1000 ? m_PEntity->health.tp - 1000 : 0);
}
else
{
m_PEntity->health.tp = 0;
}
m_PEntity->StatusEffectContainer->DelStatusEffectSilent(EFFECT_CHAIN_AFFINITY);
}
}
void CMagicState::CharAfterFinish()
{
if(m_PEntity->objtype != TYPE_PC)
{
return;
}
CCharEntity* PChar = (CCharEntity*)m_PEntity;
charutils::RemoveStratagems(PChar, m_PSpell);
charutils::UpdateHealth(PChar);
// only skill up if the effect landed
if(m_PSpell->tookEffect()){
charutils::TrySkillUP(PChar, (SKILLTYPE)m_PSpell->getSkillType(), m_PTarget->GetMLevel());
if (m_PSpell->getSkillType() == SKILL_SNG)
{
CItemWeapon* PItem = (CItemWeapon*)PChar->getEquip(SLOT_RANGED);
if (PItem && PItem->isType(ITEM_ARMOR))
{
SKILLTYPE Skilltype = (SKILLTYPE)PItem->getSkillType();
if (Skilltype == SKILL_STR || Skilltype == SKILL_WND || Skilltype == SKILL_SNG)
{
charutils::TrySkillUP(PChar, Skilltype, m_PTarget->GetMLevel());
}
}
}
}
PChar->pushPacket(new CCharUpdatePacket(PChar));
// make wyvern use breath
if(PChar->PPet!=nullptr && ((CPetEntity*)PChar->PPet)->getPetType() == PETTYPE_WYVERN)
{
((CAIPetDummy*)PChar->PPet->PBattleAI)->m_MasterCommand = MASTERCOMMAND_HEALING_BREATH;
PChar->PPet->PBattleAI->SetCurrentAction(ACTION_MOBABILITY_START);
}
SetHiPCLvl(m_PTarget, PChar->GetMLevel());
}
bool CMagicState::TryHitInterrupt(CBattleEntity* PAttacker)
{
if (!IsCasting() || IsInterrupted() || m_PSpell->getSpellGroup() == SPELLGROUP_SONG)
{
return false;
}
if(battleutils::TryInterruptSpell(PAttacker, m_PEntity))
{
ForceInterrupt();
return true;
}
return false;
}
bool CMagicState::IsCasting()
{
return m_PSpell != nullptr;
}
bool CMagicState::ValidCharCast(CSpell* PSpell)
{
CCharEntity* PChar = (CCharEntity*)m_PEntity;
// has spell and can use it
int16 spellID = PSpell->getID();
if (!charutils::hasSpell(PChar, spellID) || !spell::CanUseSpell(PChar, spellID))
{
PushError(MSGBASIC_CANNOT_CAST_SPELL, spellID);
return false;
}
// check recast
if (PChar->PRecastContainer->Has(RECAST_MAGIC, spellID))
{
PushError(MSGBASIC_UNABLE_TO_CAST, spellID);
return false;
}
// can use msic
if (!m_PEntity->loc.zone->CanUseMisc(PSpell->getZoneMisc()))
{
PushError(MSGBASIC_CANNOT_USE_IN_AREA, spellID);
return false;
}
// check summoning
if (PSpell->getSpellGroup() == SPELLGROUP_SUMMONING && PChar->PPet != nullptr)
{
PushError(MSGBASIC_ALREADY_HAS_A_PET, spellID);
return false;
}
return true;
}
void CMagicState::SpendCost(CSpell* PSpell)
{
if(m_PSpell->getSpellGroup() == SPELLGROUP_NINJUTSU)
{
if(!(m_flags & MAGICFLAGS_IGNORE_TOOLS))
{
// handle ninja tools
battleutils::HasNinjaTool(m_PEntity, PSpell, true);
}
}
else if (PSpell->hasMPCost() && !m_PEntity->StatusEffectContainer->HasStatusEffect(EFFECT_MANAFONT) && !(m_flags & MAGICFLAGS_IGNORE_MP))
{
int16 cost = CalculateMPCost(PSpell);
// conserve mp
int16 rate = m_PEntity->getMod(MOD_CONSERVE_MP);
if (dsprand::GetRandomNumber(100) < rate)
{
cost = ConserveMP(cost);
}
m_PEntity->addMP(-cost);
}
}
int16 CMagicState::ConserveMP(int16 cost)
{
return cost * (dsprand::GetRandomNumber(8.f,16.f) / 16.0f);
}
void CMagicState::SetRecast(CSpell* PSpell)
{
// only applies to pcs
if(m_PEntity->objtype != TYPE_PC)
{
return;
}
CCharEntity* PChar = (CCharEntity*)m_PEntity;
uint32 RecastTime = 3;
if (!PChar->StatusEffectContainer->HasStatusEffect(EFFECT_CHAINSPELL) &&
!PChar->StatusEffectContainer->HasStatusEffect(EFFECT_SPONTANEITY))
{
RecastTime = CalculateRecastTime(PSpell);
}
//needed so the client knows of the reduced recast time!
PSpell->setModifiedRecast(RecastTime);
PChar->PRecastContainer->Add(RECAST_MAGIC, PSpell->getID(), RecastTime);
}
| gpl-3.0 |
52North/IlwisCore | core/geos/src/geomgraph/index/SimpleMCSweepLineIntersector.cpp | 3 | 4271 | /**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#include <algorithm>
#include <vector>
#include <geos/geomgraph/index/SimpleMCSweepLineIntersector.h>
#include <geos/geomgraph/index/MonotoneChainEdge.h>
#include <geos/geomgraph/index/MonotoneChain.h>
#include <geos/geomgraph/index/SweepLineEvent.h>
#include <geos/geomgraph/Edge.h>
#include <geos/util/Interrupt.h>
using namespace std;
namespace geos {
namespace geomgraph { // geos.geomgraph
namespace index { // geos.geomgraph.index
SimpleMCSweepLineIntersector::SimpleMCSweepLineIntersector()
//events(new vector<SweepLineEvent*>())
{
}
SimpleMCSweepLineIntersector::~SimpleMCSweepLineIntersector()
{
for(size_t i=0; i<events.size(); ++i)
{
SweepLineEvent *sle=events[i];
if (sle->isDelete()) delete sle;
}
//delete events;
}
void
SimpleMCSweepLineIntersector::computeIntersections(vector<Edge*> *edges,
SegmentIntersector *si, bool testAllSegments)
{
if (testAllSegments)
add(edges,NULL);
else
add(edges);
computeIntersections(si);
}
void
SimpleMCSweepLineIntersector::computeIntersections(vector<Edge*> *edges0,
vector<Edge*> *edges1, SegmentIntersector *si)
{
add(edges0,edges0);
add(edges1,edges1);
computeIntersections(si);
}
void
SimpleMCSweepLineIntersector::add(vector<Edge*> *edges)
{
for (size_t i=0; i<edges->size(); ++i)
{
Edge *edge=(*edges)[i];
// edge is its own group
add(edge, edge);
}
}
void
SimpleMCSweepLineIntersector::add(vector<Edge*> *edges,void* edgeSet)
{
for (size_t i=0; i<edges->size(); ++i)
{
Edge *edge=(*edges)[i];
add(edge,edgeSet);
}
}
void
SimpleMCSweepLineIntersector::add(Edge *edge, void* edgeSet)
{
MonotoneChainEdge *mce=edge->getMonotoneChainEdge();
vector<int> &startIndex=mce->getStartIndexes();
size_t n = startIndex.size()-1;
events.reserve(events.size()+(n*2));
for(size_t i=0; i<n; ++i)
{
GEOS_CHECK_FOR_INTERRUPTS();
MonotoneChain *mc=new MonotoneChain(mce,i);
SweepLineEvent *insertEvent=new SweepLineEvent(edgeSet,mce->getMinX(i),NULL,mc);
events.push_back(insertEvent);
events.push_back(new SweepLineEvent(edgeSet,mce->getMaxX(i),insertEvent,mc));
}
}
/**
* Because Delete Events have a link to their corresponding Insert event,
* it is possible to compute exactly the range of events which must be
* compared to a given Insert event object.
*/
void
SimpleMCSweepLineIntersector::prepareEvents()
{
sort(events.begin(), events.end(), SweepLineEventLessThen());
for(size_t i=0; i<events.size(); ++i)
{
GEOS_CHECK_FOR_INTERRUPTS();
SweepLineEvent *ev=events[i];
if (ev->isDelete())
{
ev->getInsertEvent()->setDeleteEventIndex(i);
}
}
}
void
SimpleMCSweepLineIntersector::computeIntersections(SegmentIntersector *si)
{
nOverlaps=0;
prepareEvents();
for(size_t i=0; i<events.size(); ++i)
{
GEOS_CHECK_FOR_INTERRUPTS();
SweepLineEvent *ev=events[i];
if (ev->isInsert())
{
processOverlaps(i,ev->getDeleteEventIndex(),ev,si);
}
}
}
void
SimpleMCSweepLineIntersector::processOverlaps(int start, int end,
SweepLineEvent *ev0, SegmentIntersector *si)
{
MonotoneChain *mc0=(MonotoneChain*) ev0->getObject();
/*
* Since we might need to test for self-intersections,
* include current insert event object in list of event objects to test.
* Last index can be skipped, because it must be a Delete event.
*/
for(int i=start; i<end; ++i)
{
SweepLineEvent *ev1=events[i];
if (ev1->isInsert())
{
MonotoneChain *mc1=(MonotoneChain*) ev1->getObject();
// don't compare edges in same group
// null group indicates that edges should be compared
if (ev0->edgeSet==NULL || (ev0->edgeSet!=ev1->edgeSet))
{
mc0->computeIntersections(mc1,si);
nOverlaps++;
}
}
}
}
} // namespace geos.geomgraph.index
} // namespace geos.geomgraph
} // namespace geos
| gpl-3.0 |
RunningTime/my_temple_for_ACM | Data_Structure/Heavy_Light_Decomposition.cpp | 3 | 1773 | /*
*树链剖分(例题:BZOJ 1036 [ZJOI2008]树的统计Count)
*I. 把结点u的权值改为t
*II. 询问从点u到点v的路径上的节点的最大权值
*III. 询问从点u到点v的路径上的节点的权值和 注意:从点u到点v的路径上的节点包括u和v本身
*/
int sz[N], son[N], fa[N], dep[N];
void DFS1(int u, int pa) {
sz[u] = 1;
dep[u] = dep[pa] + 1;
fa[u] = pa;
for (int i=0; i<edge[u].size(); ++i) {
int v = edge[u][i];
if (v == pa) continue;
DFS1(v, u);
if (sz[v] > sz[son[u]]) son[u] = v;
sz[u] += sz[v];
}
}
int top[N], dfn[N], dfs_clock;
void DFS2(int u, int t) {
dfn[u] = ++dfs_clock;
top[u] = t;
if (son[u] != 0) DFS2(son[u], t);
for (int i=0; i<edge[u].size(); ++i) {
int v = edge[u][i];
if (v == fa[u] || v == son[u]) continue;
DFS2(v, v);
}
}
int LCA(int u, int v) {
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) swap(u, v);
u = fa[top[u]];
}
return dep[u] < dep[v] ? u : v;
}
//segment_tree/fenwick_tree部分
int get_sum(int u, int lca) {
int ret = 0;
while (top[u] != top[lca]) {
ret += query_sum(dfn[top[u]], dfn[u], 1, n, 1);
u = fa[top[u]];
}
ret += query_sum(dfn[lca], dfn[u], 1, n, 1);
return ret;
}
int get_max(int u, int lca) {
int ret = -INF;
while (top[u] != top[lca]) {
ret = max(ret, query_max(dfn[top[u]], dfn[u], 1, n, 1));
u = fa[top[u]];
}
ret = max(ret, query_max(dfn[lca], dfn[u], 1, n, 1));
return ret;
}
void prepare() {
sz[0] = son[0] = dep[0] = 0;
dfs_clock = 0;
DFS1(1, 0);
DFS2(1, 1);
for (int i=1; i<=n; ++i) {
updata(dfn[i], a[i], 1, n, 1);
}
}
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.