repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
AudioGod/DTS-Sound-Integration_CAF-Android-kernel | net/llc/llc_c_ev.c | 15053 | 21776 | /*
* llc_c_ev.c - Connection component state transition event qualifiers
*
* A 'state' consists of a number of possible event matching functions,
* the actions associated with each being executed when that event is
* matched; a 'state machine' accepts events in a serial fashion from an
* event queue. Each event is passed to each successive event matching
* function until a match is made (the event matching function returns
* success, or '0') or the list of event matching functions is exhausted.
* If a match is made, the actions associated with the event are executed
* and the state is changed to that event's transition state. Before some
* events are recognized, even after a match has been made, a certain
* number of 'event qualifier' functions must also be executed. If these
* all execute successfully, then the event is finally executed.
*
* These event functions must return 0 for success, to show a matched
* event, of 1 if the event does not match. Event qualifier functions
* must return a 0 for success or a non-zero for failure. Each function
* is simply responsible for verifying one single thing and returning
* either a success or failure.
*
* All of followed event functions are described in 802.2 LLC Protocol
* standard document except two functions that we added that will explain
* in their comments, at below.
*
* Copyright (c) 1997 by Procom Technology, Inc.
* 2001-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program can be redistributed or modified under the terms of the
* GNU General Public License as published by the Free Software Foundation.
* This program is distributed without any warranty or implied warranty
* of merchantability or fitness for a particular purpose.
*
* See the GNU General Public License for more details.
*/
#include <linux/netdevice.h>
#include <net/llc_conn.h>
#include <net/llc_sap.h>
#include <net/sock.h>
#include <net/llc_c_ac.h>
#include <net/llc_c_ev.h>
#include <net/llc_pdu.h>
#if 1
#define dprintk(args...) printk(KERN_DEBUG args)
#else
#define dprintk(args...)
#endif
/**
* llc_util_ns_inside_rx_window - check if sequence number is in rx window
* @ns: sequence number of received pdu.
* @vr: sequence number which receiver expects to receive.
* @rw: receive window size of receiver.
*
* Checks if sequence number of received PDU is in range of receive
* window. Returns 0 for success, 1 otherwise
*/
static u16 llc_util_ns_inside_rx_window(u8 ns, u8 vr, u8 rw)
{
return !llc_circular_between(vr, ns,
(vr + rw - 1) % LLC_2_SEQ_NBR_MODULO);
}
/**
* llc_util_nr_inside_tx_window - check if sequence number is in tx window
* @sk: current connection.
* @nr: N(R) of received PDU.
*
* This routine checks if N(R) of received PDU is in range of transmit
* window; on the other hand checks if received PDU acknowledges some
* outstanding PDUs that are in transmit window. Returns 0 for success, 1
* otherwise.
*/
static u16 llc_util_nr_inside_tx_window(struct sock *sk, u8 nr)
{
u8 nr1, nr2;
struct sk_buff *skb;
struct llc_pdu_sn *pdu;
struct llc_sock *llc = llc_sk(sk);
int rc = 0;
if (llc->dev->flags & IFF_LOOPBACK)
goto out;
rc = 1;
if (skb_queue_empty(&llc->pdu_unack_q))
goto out;
skb = skb_peek(&llc->pdu_unack_q);
pdu = llc_pdu_sn_hdr(skb);
nr1 = LLC_I_GET_NS(pdu);
skb = skb_peek_tail(&llc->pdu_unack_q);
pdu = llc_pdu_sn_hdr(skb);
nr2 = LLC_I_GET_NS(pdu);
rc = !llc_circular_between(nr1, nr, (nr2 + 1) % LLC_2_SEQ_NBR_MODULO);
out:
return rc;
}
int llc_conn_ev_conn_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_CONN_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_data_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_DATA_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_disc_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_DISC_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_rst_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_RESET_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_local_busy_detected(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_LOCAL_BUSY_DETECTED ? 0 : 1;
}
int llc_conn_ev_local_busy_cleared(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_LOCAL_BUSY_CLEARED ? 0 : 1;
}
int llc_conn_ev_rx_bad_pdu(struct sock *sk, struct sk_buff *skb)
{
return 1;
}
int llc_conn_ev_rx_disc_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_DISC ? 0 : 1;
}
int llc_conn_ev_rx_dm_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_DM ? 0 : 1;
}
int llc_conn_ev_rx_frmr_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_FRMR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_0_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_1_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_x_inval_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn * pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
const u16 rc = LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
ns != vr &&
llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
if (!rc)
dprintk("%s: matched, state=%d, ns=%d, vr=%d\n",
__func__, llc_sk(sk)->state, ns, vr);
return rc;
}
int llc_conn_ev_rx_i_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_0_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_1_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x_inval_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
const u16 rc = LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
ns != vr &&
llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
if (!rc)
dprintk("%s: matched, state=%d, ns=%d, vr=%d\n",
__func__, llc_sk(sk)->state, ns, vr);
return rc;
}
int llc_conn_ev_rx_rej_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rnr_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rr_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RR ? 0 : 1;
}
int llc_conn_ev_rx_sabme_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_SABME ? 0 : 1;
}
int llc_conn_ev_rx_ua_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_UA ? 0 : 1;
}
int llc_conn_ev_rx_xxx_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
if (LLC_PDU_IS_CMD(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) {
if (LLC_I_PF_IS_1(pdu))
rc = 0;
} else if (LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PF_IS_1(pdu))
rc = 0;
}
return rc;
}
int llc_conn_ev_rx_xxx_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
if (LLC_PDU_IS_CMD(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu))
rc = 0;
else if (LLC_PDU_TYPE_IS_U(pdu))
switch (LLC_U_PDU_CMD(pdu)) {
case LLC_2_PDU_CMD_SABME:
case LLC_2_PDU_CMD_DISC:
rc = 0;
break;
}
}
return rc;
}
int llc_conn_ev_rx_xxx_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
if (LLC_PDU_IS_RSP(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu))
rc = 0;
else if (LLC_PDU_TYPE_IS_U(pdu))
switch (LLC_U_PDU_RSP(pdu)) {
case LLC_2_PDU_RSP_UA:
case LLC_2_PDU_RSP_DM:
case LLC_2_PDU_RSP_FRMR:
rc = 0;
break;
}
}
return rc;
}
int llc_conn_ev_rx_zzz_cmd_pbit_set_x_inval_nr(struct sock *sk,
struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vs = llc_sk(sk)->vS;
const u8 nr = LLC_I_GET_NR(pdu);
if (LLC_PDU_IS_CMD(pdu) &&
(LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) &&
nr != vs && llc_util_nr_inside_tx_window(sk, nr)) {
dprintk("%s: matched, state=%d, vs=%d, nr=%d\n",
__func__, llc_sk(sk)->state, vs, nr);
rc = 0;
}
return rc;
}
int llc_conn_ev_rx_zzz_rsp_fbit_set_x_inval_nr(struct sock *sk,
struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vs = llc_sk(sk)->vS;
const u8 nr = LLC_I_GET_NR(pdu);
if (LLC_PDU_IS_RSP(pdu) &&
(LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) &&
nr != vs && llc_util_nr_inside_tx_window(sk, nr)) {
rc = 0;
dprintk("%s: matched, state=%d, vs=%d, nr=%d\n",
__func__, llc_sk(sk)->state, vs, nr);
}
return rc;
}
int llc_conn_ev_rx_any_frame(struct sock *sk, struct sk_buff *skb)
{
return 0;
}
int llc_conn_ev_p_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_P_TMR;
}
int llc_conn_ev_ack_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_ACK_TMR;
}
int llc_conn_ev_rej_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_REJ_TMR;
}
int llc_conn_ev_busy_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_BUSY_TMR;
}
int llc_conn_ev_init_p_f_cycle(struct sock *sk, struct sk_buff *skb)
{
return 1;
}
int llc_conn_ev_tx_buffer_full(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_TX_BUFF_FULL ? 0 : 1;
}
/* Event qualifier functions
*
* these functions simply verify the value of a state flag associated with
* the connection and return either a 0 for success or a non-zero value
* for not-success; verify the event is the type we expect
*/
int llc_conn_ev_qlfy_data_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag != 1;
}
int llc_conn_ev_qlfy_data_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag;
}
int llc_conn_ev_qlfy_data_flag_eq_2(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag != 2;
}
int llc_conn_ev_qlfy_p_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->p_flag != 1;
}
/**
* conn_ev_qlfy_last_frame_eq_1 - checks if frame is last in tx window
* @sk: current connection structure.
* @skb: current event.
*
* This function determines when frame which is sent, is last frame of
* transmit window, if it is then this function return zero else return
* one. This function is used for sending last frame of transmit window
* as I-format command with p-bit set to one. Returns 0 if frame is last
* frame, 1 otherwise.
*/
int llc_conn_ev_qlfy_last_frame_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !(skb_queue_len(&llc_sk(sk)->pdu_unack_q) + 1 == llc_sk(sk)->k);
}
/**
* conn_ev_qlfy_last_frame_eq_0 - checks if frame isn't last in tx window
* @sk: current connection structure.
* @skb: current event.
*
* This function determines when frame which is sent, isn't last frame of
* transmit window, if it isn't then this function return zero else return
* one. Returns 0 if frame isn't last frame, 1 otherwise.
*/
int llc_conn_ev_qlfy_last_frame_eq_0(struct sock *sk, struct sk_buff *skb)
{
return skb_queue_len(&llc_sk(sk)->pdu_unack_q) + 1 == llc_sk(sk)->k;
}
int llc_conn_ev_qlfy_p_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->p_flag;
}
int llc_conn_ev_qlfy_p_flag_eq_f(struct sock *sk, struct sk_buff *skb)
{
u8 f_bit;
llc_pdu_decode_pf_bit(skb, &f_bit);
return llc_sk(sk)->p_flag == f_bit ? 0 : 1;
}
int llc_conn_ev_qlfy_remote_busy_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->remote_busy_flag;
}
int llc_conn_ev_qlfy_remote_busy_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->remote_busy_flag;
}
int llc_conn_ev_qlfy_retry_cnt_lt_n2(struct sock *sk, struct sk_buff *skb)
{
return !(llc_sk(sk)->retry_count < llc_sk(sk)->n2);
}
int llc_conn_ev_qlfy_retry_cnt_gte_n2(struct sock *sk, struct sk_buff *skb)
{
return !(llc_sk(sk)->retry_count >= llc_sk(sk)->n2);
}
int llc_conn_ev_qlfy_s_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->s_flag;
}
int llc_conn_ev_qlfy_s_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->s_flag;
}
int llc_conn_ev_qlfy_cause_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->cause_flag;
}
int llc_conn_ev_qlfy_cause_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->cause_flag;
}
int llc_conn_ev_qlfy_set_status_conn(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_CONN;
return 0;
}
int llc_conn_ev_qlfy_set_status_disc(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_DISC;
return 0;
}
int llc_conn_ev_qlfy_set_status_failed(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_FAILED;
return 0;
}
int llc_conn_ev_qlfy_set_status_remote_busy(struct sock *sk,
struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_REMOTE_BUSY;
return 0;
}
int llc_conn_ev_qlfy_set_status_refuse(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_REFUSE;
return 0;
}
int llc_conn_ev_qlfy_set_status_conflict(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_CONFLICT;
return 0;
}
int llc_conn_ev_qlfy_set_status_rst_done(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_RESET_DONE;
return 0;
}
| gpl-2.0 |
limitedgilin/d1lkt-buffer | drivers/video/msm/vidc/1080p/ddl/vcd_ddl_metadata.c | 206 | 16330 | /* Copyright (c) 2010, 2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "vcd_ddl.h"
#include "vcd_ddl_shared_mem.h"
#include "vcd_ddl_metadata.h"
static u32 *ddl_metadata_hdr_entry(struct ddl_client_context *ddl,
u32 meta_data)
{
u32 skip_words = 0;
u32 *buffer;
if (ddl->decoding) {
buffer = (u32 *) ddl->codec_data.decoder.meta_data_input.
align_virtual_addr;
skip_words = 32 + 1;
buffer += skip_words;
switch (meta_data) {
default:
case VCD_METADATA_DATANONE:
skip_words = 0;
break;
case VCD_METADATA_QPARRAY:
skip_words = 3;
break;
case VCD_METADATA_CONCEALMB:
skip_words = 6;
break;
case VCD_METADATA_VC1:
skip_words = 9;
break;
case VCD_METADATA_SEI:
skip_words = 12;
break;
case VCD_METADATA_VUI:
skip_words = 15;
break;
case VCD_METADATA_PASSTHROUGH:
skip_words = 18;
break;
case VCD_METADATA_QCOMFILLER:
skip_words = 21;
break;
}
} else {
buffer = (u32 *) ddl->codec_data.encoder.meta_data_input.
align_virtual_addr;
skip_words = 2;
buffer += skip_words;
switch (meta_data) {
default:
case VCD_METADATA_DATANONE:
skip_words = 0;
break;
case VCD_METADATA_ENC_SLICE:
skip_words = 3;
break;
case VCD_METADATA_QCOMFILLER:
skip_words = 6;
break;
}
}
buffer += skip_words;
return buffer;
}
void ddl_set_default_meta_data_hdr(struct ddl_client_context *ddl)
{
struct ddl_buf_addr *main_buffer =
&ddl->ddl_context->metadata_shared_input;
struct ddl_buf_addr *client_buffer;
u32 *hdr_entry;
if (ddl->decoding)
client_buffer = &(ddl->codec_data.decoder.meta_data_input);
else
client_buffer = &(ddl->codec_data.encoder.meta_data_input);
DDL_METADATA_CLIENT_INPUTBUF(main_buffer, client_buffer,
ddl->instance_id);
hdr_entry = ddl_metadata_hdr_entry(ddl, VCD_METADATA_QCOMFILLER);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] = VCD_METADATA_QCOMFILLER;
hdr_entry = ddl_metadata_hdr_entry(ddl, VCD_METADATA_DATANONE);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] = VCD_METADATA_DATANONE;
if (ddl->decoding) {
hdr_entry = ddl_metadata_hdr_entry(ddl, VCD_METADATA_QPARRAY);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] = VCD_METADATA_QPARRAY;
hdr_entry = ddl_metadata_hdr_entry(ddl, VCD_METADATA_CONCEALMB);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] = VCD_METADATA_CONCEALMB;
hdr_entry = ddl_metadata_hdr_entry(ddl, VCD_METADATA_SEI);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] = VCD_METADATA_SEI;
hdr_entry = ddl_metadata_hdr_entry(ddl, VCD_METADATA_VUI);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] = VCD_METADATA_VUI;
hdr_entry = ddl_metadata_hdr_entry(ddl, VCD_METADATA_VC1);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] = VCD_METADATA_VC1;
hdr_entry = ddl_metadata_hdr_entry(ddl,
VCD_METADATA_PASSTHROUGH);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] =
VCD_METADATA_PASSTHROUGH;
} else {
hdr_entry = ddl_metadata_hdr_entry(ddl, VCD_METADATA_ENC_SLICE);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] = 0x00000101;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] = 1;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] = VCD_METADATA_ENC_SLICE;
}
}
static u32 ddl_supported_metadata_flag(struct ddl_client_context *ddl)
{
u32 flag = 0;
if (ddl->decoding) {
enum vcd_codec codec =
ddl->codec_data.decoder.codec.codec;
flag |= (VCD_METADATA_CONCEALMB | VCD_METADATA_PASSTHROUGH |
VCD_METADATA_QPARRAY);
if (codec == VCD_CODEC_H264)
flag |= (VCD_METADATA_SEI | VCD_METADATA_VUI);
else if (codec == VCD_CODEC_VC1 ||
codec == VCD_CODEC_VC1_RCV)
flag |= VCD_METADATA_VC1;
} else
flag |= VCD_METADATA_ENC_SLICE;
return flag;
}
void ddl_set_default_metadata_flag(struct ddl_client_context *ddl)
{
if (ddl->decoding)
ddl->codec_data.decoder.meta_data_enable_flag = 0;
else
ddl->codec_data.encoder.meta_data_enable_flag = 0;
}
void ddl_set_default_decoder_metadata_buffer_size(struct ddl_decoder_data
*decoder, struct vcd_property_frame_size *frame_size,
struct vcd_buffer_requirement *output_buf_req)
{
u32 flag = decoder->meta_data_enable_flag;
u32 suffix = 0, size = 0;
if (!flag) {
decoder->suffix = 0;
return;
}
if (flag & VCD_METADATA_QPARRAY) {
u32 num_of_mb = DDL_NO_OF_MB(frame_size->width,
frame_size->height);
size = DDL_METADATA_HDR_SIZE;
size += num_of_mb;
DDL_METADATA_ALIGNSIZE(size);
suffix += size;
}
if (flag & VCD_METADATA_CONCEALMB) {
u32 num_of_mb = DDL_NO_OF_MB(frame_size->width,
frame_size->height);
size = DDL_METADATA_HDR_SIZE + (num_of_mb >> 3);
DDL_METADATA_ALIGNSIZE(size);
suffix += size;
}
if (flag & VCD_METADATA_VC1) {
size = DDL_METADATA_HDR_SIZE;
size += DDL_METADATA_VC1_PAYLOAD_SIZE;
DDL_METADATA_ALIGNSIZE(size);
suffix += size;
}
if (flag & VCD_METADATA_SEI) {
size = DDL_METADATA_HDR_SIZE;
size += DDL_METADATA_SEI_PAYLOAD_SIZE;
DDL_METADATA_ALIGNSIZE(size);
suffix += (size * DDL_METADATA_SEI_MAX);
}
if (flag & VCD_METADATA_VUI) {
size = DDL_METADATA_HDR_SIZE;
size += DDL_METADATA_VUI_PAYLOAD_SIZE;
DDL_METADATA_ALIGNSIZE(size);
suffix += (size);
}
if (flag & VCD_METADATA_PASSTHROUGH) {
size = DDL_METADATA_HDR_SIZE;
size += DDL_METADATA_PASSTHROUGH_PAYLOAD_SIZE;
DDL_METADATA_ALIGNSIZE(size);
suffix += (size);
}
size = DDL_METADATA_EXTRADATANONE_SIZE;
DDL_METADATA_ALIGNSIZE(size);
suffix += (size);
suffix += DDL_METADATA_EXTRAPAD_SIZE;
DDL_METADATA_ALIGNSIZE(suffix);
decoder->suffix = suffix;
output_buf_req->sz += suffix;
decoder->meta_data_offset = 0;
DDL_MSG_LOW("metadata output buf size : %d", suffix);
}
void ddl_set_default_encoder_metadata_buffer_size(struct ddl_encoder_data
*encoder)
{
u32 flag = encoder->meta_data_enable_flag;
u32 suffix = 0, size = 0;
if (!flag) {
encoder->suffix = 0;
return;
}
if (flag & VCD_METADATA_ENC_SLICE) {
u32 num_of_mb = DDL_NO_OF_MB(encoder->frame_size.width,
encoder->frame_size.height);
size = DDL_METADATA_HDR_SIZE;
size += 4;
size += (num_of_mb << 3);
DDL_METADATA_ALIGNSIZE(size);
suffix += size;
}
size = DDL_METADATA_EXTRADATANONE_SIZE;
DDL_METADATA_ALIGNSIZE(size);
suffix += (size);
suffix += DDL_METADATA_EXTRAPAD_SIZE;
DDL_METADATA_ALIGNSIZE(suffix);
encoder->suffix = suffix;
encoder->output_buf_req.sz += suffix;
encoder->output_buf_req.sz =
DDL_ALIGN(encoder->output_buf_req.sz, DDL_KILO_BYTE(4));
}
u32 ddl_set_metadata_params(struct ddl_client_context *ddl,
struct vcd_property_hdr *property_hdr, void *property_value)
{
u32 vcd_status = VCD_ERR_ILLEGAL_PARM;
if (property_hdr->prop_id == VCD_I_METADATA_ENABLE) {
struct vcd_property_meta_data_enable *meta_data_enable =
(struct vcd_property_meta_data_enable *) property_value;
u32 *meta_data_enable_flag;
enum vcd_codec codec;
if (ddl->decoding) {
meta_data_enable_flag =
&(ddl->codec_data.decoder.meta_data_enable_flag);
codec = ddl->codec_data.decoder.codec.codec;
} else {
meta_data_enable_flag =
&ddl->codec_data.encoder.meta_data_enable_flag;
codec = ddl->codec_data.encoder.codec.codec;
}
if (sizeof(struct vcd_property_meta_data_enable) ==
property_hdr->sz &&
DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN) && codec) {
u32 flag = ddl_supported_metadata_flag(ddl);
flag &= (meta_data_enable->meta_data_enable_flag);
if (flag)
flag |= DDL_METADATA_MANDATORY;
if (*meta_data_enable_flag != flag) {
*meta_data_enable_flag = flag;
if (ddl->decoding)
ddl_set_default_decoder_buffer_req(
&ddl->codec_data.decoder, true);
else
ddl_set_default_encoder_buffer_req(
&ddl->codec_data.encoder);
}
vcd_status = VCD_S_SUCCESS;
}
} else if (property_hdr->prop_id == VCD_I_METADATA_HEADER) {
struct vcd_property_metadata_hdr *hdr =
(struct vcd_property_metadata_hdr *) property_value;
if (sizeof(struct vcd_property_metadata_hdr) ==
property_hdr->sz) {
u32 flag = ddl_supported_metadata_flag(ddl);
flag |= DDL_METADATA_MANDATORY;
flag &= hdr->meta_data_id;
if (!(flag & (flag - 1))) {
u32 *hdr_entry = ddl_metadata_hdr_entry(ddl,
flag);
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX] =
hdr->version;
hdr_entry[DDL_METADATA_HDR_PORT_INDEX] =
hdr->port_index;
hdr_entry[DDL_METADATA_HDR_TYPE_INDEX] =
hdr->type;
vcd_status = VCD_S_SUCCESS;
}
}
}
return vcd_status;
}
u32 ddl_get_metadata_params(struct ddl_client_context *ddl,
struct vcd_property_hdr *property_hdr, void *property_value)
{
u32 vcd_status = VCD_ERR_ILLEGAL_PARM;
if (property_hdr->prop_id == VCD_I_METADATA_ENABLE &&
sizeof(struct vcd_property_meta_data_enable) ==
property_hdr->sz) {
struct vcd_property_meta_data_enable *meta_data_enable =
(struct vcd_property_meta_data_enable *) property_value;
meta_data_enable->meta_data_enable_flag =
((ddl->decoding) ?
(ddl->codec_data.decoder.meta_data_enable_flag) :
(ddl->codec_data.encoder.meta_data_enable_flag));
vcd_status = VCD_S_SUCCESS;
} else if (property_hdr->prop_id == VCD_I_METADATA_HEADER &&
sizeof(struct vcd_property_metadata_hdr) ==
property_hdr->sz) {
struct vcd_property_metadata_hdr *hdr =
(struct vcd_property_metadata_hdr *) property_value;
u32 flag = ddl_supported_metadata_flag(ddl);
flag |= DDL_METADATA_MANDATORY;
flag &= hdr->meta_data_id;
if (!(flag & (flag - 1))) {
u32 *hdr_entry = ddl_metadata_hdr_entry(ddl, flag);
hdr->version =
hdr_entry[DDL_METADATA_HDR_VERSION_INDEX];
hdr->port_index =
hdr_entry[DDL_METADATA_HDR_PORT_INDEX];
hdr->type = hdr_entry[DDL_METADATA_HDR_TYPE_INDEX];
vcd_status = VCD_S_SUCCESS;
}
}
return vcd_status;
}
void ddl_vidc_metadata_enable(struct ddl_client_context *ddl)
{
u32 flag, extradata_enable = false;
u32 qp_enable = false, concealed_mb_enable = false;
u32 vc1_param_enable = false, sei_nal_enable = false;
u32 vui_enable = false, enc_slice_size_enable = false;
if (ddl->decoding)
flag = ddl->codec_data.decoder.meta_data_enable_flag;
else
flag = ddl->codec_data.encoder.meta_data_enable_flag;
if (flag) {
if (flag & VCD_METADATA_QPARRAY)
qp_enable = true;
if (flag & VCD_METADATA_CONCEALMB)
concealed_mb_enable = true;
if (flag & VCD_METADATA_VC1)
vc1_param_enable = true;
if (flag & VCD_METADATA_SEI)
sei_nal_enable = true;
if (flag & VCD_METADATA_VUI)
vui_enable = true;
if (flag & VCD_METADATA_ENC_SLICE)
enc_slice_size_enable = true;
if (flag & VCD_METADATA_PASSTHROUGH)
extradata_enable = true;
}
DDL_MSG_LOW("metadata enable flag : %d", sei_nal_enable);
vidc_sm_set_metadata_enable(&ddl->shared_mem
[ddl->command_channel], extradata_enable, qp_enable,
concealed_mb_enable, vc1_param_enable, sei_nal_enable,
vui_enable, enc_slice_size_enable);
}
u32 ddl_vidc_encode_set_metadata_output_buf(struct ddl_client_context *ddl)
{
struct ddl_encoder_data *encoder = &ddl->codec_data.encoder;
struct vcd_frame_data *stream = &ddl->output_frame.vcd_frm;
struct ddl_context *ddl_context;
u32 ext_buffer_end, hw_metadata_start;
u32 *buffer;
ddl_context = ddl_get_context();
ext_buffer_end = (u32) stream->physical + stream->alloc_len;
if (!encoder->meta_data_enable_flag) {
ext_buffer_end &= ~(DDL_STREAMBUF_ALIGN_GUARD_BYTES);
return ext_buffer_end;
}
hw_metadata_start = (ext_buffer_end - encoder->suffix) &
~(DDL_STREAMBUF_ALIGN_GUARD_BYTES);
ext_buffer_end = (hw_metadata_start - 1) &
~(DDL_STREAMBUF_ALIGN_GUARD_BYTES);
buffer = (u32 *) encoder->meta_data_input.align_virtual_addr;
*buffer++ = encoder->suffix;
*buffer = DDL_OFFSET(ddl_context->dram_base_a.align_physical_addr,
hw_metadata_start);
encoder->meta_data_offset = hw_metadata_start - (u32) stream->physical;
return ext_buffer_end;
}
void ddl_vidc_decode_set_metadata_output(struct ddl_decoder_data *decoder)
{
struct ddl_context *ddl_context;
u32 loopc, yuv_size;
u32 *buffer;
if (!decoder->meta_data_enable_flag) {
decoder->meta_data_offset = 0;
return;
}
ddl_context = ddl_get_context();
yuv_size = ddl_get_yuv_buffer_size(&decoder->client_frame_size,
&decoder->buf_format, !decoder->progressive_only,
decoder->hdr.decoding, NULL);
decoder->meta_data_offset = DDL_ALIGN_SIZE(yuv_size,
DDL_LINEAR_BUF_ALIGN_GUARD_BYTES, DDL_LINEAR_BUF_ALIGN_MASK);
buffer = (u32 *) decoder->meta_data_input.align_virtual_addr;
*buffer++ = decoder->suffix;
DDL_MSG_LOW("Metadata offset & size : %d/%d",
decoder->meta_data_offset, decoder->suffix);
for (loopc = 0; loopc < decoder->dp_buf.no_of_dec_pic_buf;
++loopc) {
*buffer++ = (u32)(decoder->meta_data_offset + (u8 *)
DDL_OFFSET(ddl_context->dram_base_a.
align_physical_addr, decoder->dp_buf.
dec_pic_buffers[loopc].vcd_frm.physical));
}
}
void ddl_process_encoder_metadata(struct ddl_client_context *ddl)
{
struct ddl_encoder_data *encoder = &(ddl->codec_data.encoder);
struct vcd_frame_data *out_frame =
&(ddl->output_frame.vcd_frm);
u32 *qfiller_hdr, *qfiller, start_addr;
u32 qfiller_size;
if (!encoder->meta_data_enable_flag) {
out_frame->flags &= ~(VCD_FRAME_FLAG_EXTRADATA);
return;
}
if (!encoder->enc_frame_info.meta_data_exists) {
out_frame->flags &= ~(VCD_FRAME_FLAG_EXTRADATA);
return;
}
out_frame->flags |= VCD_FRAME_FLAG_EXTRADATA;
DDL_MSG_LOW("processing metadata for encoder");
start_addr = (u32) ((u8 *)out_frame->virtual + out_frame->offset);
qfiller = (u32 *)((out_frame->data_len +
start_addr + 3) & ~3);
qfiller_size = (u32)((encoder->meta_data_offset +
(u8 *) out_frame->virtual) - (u8 *) qfiller);
qfiller_hdr = ddl_metadata_hdr_entry(ddl, VCD_METADATA_QCOMFILLER);
*qfiller++ = qfiller_size;
*qfiller++ = qfiller_hdr[DDL_METADATA_HDR_VERSION_INDEX];
*qfiller++ = qfiller_hdr[DDL_METADATA_HDR_PORT_INDEX];
*qfiller++ = qfiller_hdr[DDL_METADATA_HDR_TYPE_INDEX];
*qfiller = (u32)(qfiller_size - DDL_METADATA_HDR_SIZE);
}
void ddl_process_decoder_metadata(struct ddl_client_context *ddl)
{
struct ddl_decoder_data *decoder = &(ddl->codec_data.decoder);
struct vcd_frame_data *output_frame =
&(ddl->output_frame.vcd_frm);
u32 *qfiller_hdr, *qfiller;
u32 qfiller_size;
if (!decoder->meta_data_enable_flag) {
output_frame->flags &= ~(VCD_FRAME_FLAG_EXTRADATA);
return;
}
if (!decoder->meta_data_exists) {
output_frame->flags &= ~(VCD_FRAME_FLAG_EXTRADATA);
return;
}
DDL_MSG_LOW("processing metadata for decoder");
DDL_MSG_LOW("data_len/metadata_offset : %d/%d",
output_frame->data_len, decoder->meta_data_offset);
output_frame->flags |= VCD_FRAME_FLAG_EXTRADATA;
if (output_frame->data_len != decoder->meta_data_offset) {
qfiller = (u32 *)((u32)((output_frame->data_len +
output_frame->offset +
(u8 *) output_frame->virtual) + 3) & ~3);
qfiller_size = (u32)((decoder->meta_data_offset +
(u8 *) output_frame->virtual) -
(u8 *) qfiller);
qfiller_hdr = ddl_metadata_hdr_entry(ddl,
VCD_METADATA_QCOMFILLER);
*qfiller++ = qfiller_size;
*qfiller++ = qfiller_hdr[DDL_METADATA_HDR_VERSION_INDEX];
*qfiller++ = qfiller_hdr[DDL_METADATA_HDR_PORT_INDEX];
*qfiller++ = qfiller_hdr[DDL_METADATA_HDR_TYPE_INDEX];
*qfiller = (u32)(qfiller_size - DDL_METADATA_HDR_SIZE);
}
}
| gpl-2.0 |
ErcOne/kernel-3-4-projek-n7000 | drivers/ata/libahci.c | 206 | 58408 | /*
* libahci.c - Common AHCI SATA low-level routines
*
* Maintained by: Jeff Garzik <jgarzik@pobox.com>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2004-2005 Red Hat, 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, 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.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* AHCI hardware documentation:
* http://www.intel.com/technology/serialata/pdf/rev1_0.pdf
* http://www.intel.com/technology/serialata/pdf/rev1_1.pdf
*
*/
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <linux/libata.h>
#include "ahci.h"
static int ahci_skip_host_reset;
int ahci_ignore_sss;
EXPORT_SYMBOL_GPL(ahci_ignore_sss);
module_param_named(skip_host_reset, ahci_skip_host_reset, int, 0444);
MODULE_PARM_DESC(skip_host_reset, "skip global host reset (0=don't skip, 1=skip)");
module_param_named(ignore_sss, ahci_ignore_sss, int, 0444);
MODULE_PARM_DESC(ignore_sss, "Ignore staggered spinup flag (0=don't ignore, 1=ignore)");
static int ahci_set_lpm(struct ata_link *link, enum ata_lpm_policy policy,
unsigned hints);
static ssize_t ahci_led_show(struct ata_port *ap, char *buf);
static ssize_t ahci_led_store(struct ata_port *ap, const char *buf,
size_t size);
static ssize_t ahci_transmit_led_message(struct ata_port *ap, u32 state,
ssize_t size);
static int ahci_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val);
static int ahci_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val);
static unsigned int ahci_qc_issue(struct ata_queued_cmd *qc);
static bool ahci_qc_fill_rtf(struct ata_queued_cmd *qc);
static int ahci_port_start(struct ata_port *ap);
static void ahci_port_stop(struct ata_port *ap);
static void ahci_qc_prep(struct ata_queued_cmd *qc);
static int ahci_pmp_qc_defer(struct ata_queued_cmd *qc);
static void ahci_freeze(struct ata_port *ap);
static void ahci_thaw(struct ata_port *ap);
static void ahci_enable_fbs(struct ata_port *ap);
static void ahci_disable_fbs(struct ata_port *ap);
static void ahci_pmp_attach(struct ata_port *ap);
static void ahci_pmp_detach(struct ata_port *ap);
static int ahci_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static int ahci_pmp_retry_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static int ahci_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static void ahci_postreset(struct ata_link *link, unsigned int *class);
static void ahci_error_handler(struct ata_port *ap);
static void ahci_post_internal_cmd(struct ata_queued_cmd *qc);
static void ahci_dev_config(struct ata_device *dev);
#ifdef CONFIG_PM
static int ahci_port_suspend(struct ata_port *ap, pm_message_t mesg);
#endif
static ssize_t ahci_activity_show(struct ata_device *dev, char *buf);
static ssize_t ahci_activity_store(struct ata_device *dev,
enum sw_activity val);
static void ahci_init_sw_activity(struct ata_link *link);
static ssize_t ahci_show_host_caps(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t ahci_show_host_cap2(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t ahci_show_host_version(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t ahci_show_port_cmd(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t ahci_read_em_buffer(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t ahci_store_em_buffer(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size);
static ssize_t ahci_show_em_supported(struct device *dev,
struct device_attribute *attr, char *buf);
static DEVICE_ATTR(ahci_host_caps, S_IRUGO, ahci_show_host_caps, NULL);
static DEVICE_ATTR(ahci_host_cap2, S_IRUGO, ahci_show_host_cap2, NULL);
static DEVICE_ATTR(ahci_host_version, S_IRUGO, ahci_show_host_version, NULL);
static DEVICE_ATTR(ahci_port_cmd, S_IRUGO, ahci_show_port_cmd, NULL);
static DEVICE_ATTR(em_buffer, S_IWUSR | S_IRUGO,
ahci_read_em_buffer, ahci_store_em_buffer);
static DEVICE_ATTR(em_message_supported, S_IRUGO, ahci_show_em_supported, NULL);
struct device_attribute *ahci_shost_attrs[] = {
&dev_attr_link_power_management_policy,
&dev_attr_em_message_type,
&dev_attr_em_message,
&dev_attr_ahci_host_caps,
&dev_attr_ahci_host_cap2,
&dev_attr_ahci_host_version,
&dev_attr_ahci_port_cmd,
&dev_attr_em_buffer,
&dev_attr_em_message_supported,
NULL
};
EXPORT_SYMBOL_GPL(ahci_shost_attrs);
struct device_attribute *ahci_sdev_attrs[] = {
&dev_attr_sw_activity,
&dev_attr_unload_heads,
NULL
};
EXPORT_SYMBOL_GPL(ahci_sdev_attrs);
struct ata_port_operations ahci_ops = {
.inherits = &sata_pmp_port_ops,
.qc_defer = ahci_pmp_qc_defer,
.qc_prep = ahci_qc_prep,
.qc_issue = ahci_qc_issue,
.qc_fill_rtf = ahci_qc_fill_rtf,
.freeze = ahci_freeze,
.thaw = ahci_thaw,
.softreset = ahci_softreset,
.hardreset = ahci_hardreset,
.postreset = ahci_postreset,
.pmp_softreset = ahci_softreset,
.error_handler = ahci_error_handler,
.post_internal_cmd = ahci_post_internal_cmd,
.dev_config = ahci_dev_config,
.scr_read = ahci_scr_read,
.scr_write = ahci_scr_write,
.pmp_attach = ahci_pmp_attach,
.pmp_detach = ahci_pmp_detach,
.set_lpm = ahci_set_lpm,
.em_show = ahci_led_show,
.em_store = ahci_led_store,
.sw_activity_show = ahci_activity_show,
.sw_activity_store = ahci_activity_store,
#ifdef CONFIG_PM
.port_suspend = ahci_port_suspend,
.port_resume = ahci_port_resume,
#endif
.port_start = ahci_port_start,
.port_stop = ahci_port_stop,
};
EXPORT_SYMBOL_GPL(ahci_ops);
struct ata_port_operations ahci_pmp_retry_srst_ops = {
.inherits = &ahci_ops,
.softreset = ahci_pmp_retry_softreset,
};
EXPORT_SYMBOL_GPL(ahci_pmp_retry_srst_ops);
int ahci_em_messages = 1;
EXPORT_SYMBOL_GPL(ahci_em_messages);
module_param(ahci_em_messages, int, 0444);
/* add other LED protocol types when they become supported */
MODULE_PARM_DESC(ahci_em_messages,
"AHCI Enclosure Management Message control (0 = off, 1 = on)");
static void ahci_enable_ahci(void __iomem *mmio)
{
int i;
u32 tmp;
/* turn on AHCI_EN */
tmp = readl(mmio + HOST_CTL);
if (tmp & HOST_AHCI_EN)
return;
/* Some controllers need AHCI_EN to be written multiple times.
* Try a few times before giving up.
*/
for (i = 0; i < 5; i++) {
tmp |= HOST_AHCI_EN;
writel(tmp, mmio + HOST_CTL);
tmp = readl(mmio + HOST_CTL); /* flush && sanity check */
if (tmp & HOST_AHCI_EN)
return;
msleep(10);
}
WARN_ON(1);
}
static ssize_t ahci_show_host_caps(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
struct ahci_host_priv *hpriv = ap->host->private_data;
return sprintf(buf, "%x\n", hpriv->cap);
}
static ssize_t ahci_show_host_cap2(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
struct ahci_host_priv *hpriv = ap->host->private_data;
return sprintf(buf, "%x\n", hpriv->cap2);
}
static ssize_t ahci_show_host_version(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
struct ahci_host_priv *hpriv = ap->host->private_data;
void __iomem *mmio = hpriv->mmio;
return sprintf(buf, "%x\n", readl(mmio + HOST_VERSION));
}
static ssize_t ahci_show_port_cmd(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
void __iomem *port_mmio = ahci_port_base(ap);
return sprintf(buf, "%x\n", readl(port_mmio + PORT_CMD));
}
static ssize_t ahci_read_em_buffer(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
struct ahci_host_priv *hpriv = ap->host->private_data;
void __iomem *mmio = hpriv->mmio;
void __iomem *em_mmio = mmio + hpriv->em_loc;
u32 em_ctl, msg;
unsigned long flags;
size_t count;
int i;
spin_lock_irqsave(ap->lock, flags);
em_ctl = readl(mmio + HOST_EM_CTL);
if (!(ap->flags & ATA_FLAG_EM) || em_ctl & EM_CTL_XMT ||
!(hpriv->em_msg_type & EM_MSG_TYPE_SGPIO)) {
spin_unlock_irqrestore(ap->lock, flags);
return -EINVAL;
}
if (!(em_ctl & EM_CTL_MR)) {
spin_unlock_irqrestore(ap->lock, flags);
return -EAGAIN;
}
if (!(em_ctl & EM_CTL_SMB))
em_mmio += hpriv->em_buf_sz;
count = hpriv->em_buf_sz;
/* the count should not be larger than PAGE_SIZE */
if (count > PAGE_SIZE) {
if (printk_ratelimit())
ata_port_warn(ap,
"EM read buffer size too large: "
"buffer size %u, page size %lu\n",
hpriv->em_buf_sz, PAGE_SIZE);
count = PAGE_SIZE;
}
for (i = 0; i < count; i += 4) {
msg = readl(em_mmio + i);
buf[i] = msg & 0xff;
buf[i + 1] = (msg >> 8) & 0xff;
buf[i + 2] = (msg >> 16) & 0xff;
buf[i + 3] = (msg >> 24) & 0xff;
}
spin_unlock_irqrestore(ap->lock, flags);
return i;
}
static ssize_t ahci_store_em_buffer(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
struct ahci_host_priv *hpriv = ap->host->private_data;
void __iomem *mmio = hpriv->mmio;
void __iomem *em_mmio = mmio + hpriv->em_loc;
const unsigned char *msg_buf = buf;
u32 em_ctl, msg;
unsigned long flags;
int i;
/* check size validity */
if (!(ap->flags & ATA_FLAG_EM) ||
!(hpriv->em_msg_type & EM_MSG_TYPE_SGPIO) ||
size % 4 || size > hpriv->em_buf_sz)
return -EINVAL;
spin_lock_irqsave(ap->lock, flags);
em_ctl = readl(mmio + HOST_EM_CTL);
if (em_ctl & EM_CTL_TM) {
spin_unlock_irqrestore(ap->lock, flags);
return -EBUSY;
}
for (i = 0; i < size; i += 4) {
msg = msg_buf[i] | msg_buf[i + 1] << 8 |
msg_buf[i + 2] << 16 | msg_buf[i + 3] << 24;
writel(msg, em_mmio + i);
}
writel(em_ctl | EM_CTL_TM, mmio + HOST_EM_CTL);
spin_unlock_irqrestore(ap->lock, flags);
return size;
}
static ssize_t ahci_show_em_supported(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ata_port *ap = ata_shost_to_port(shost);
struct ahci_host_priv *hpriv = ap->host->private_data;
void __iomem *mmio = hpriv->mmio;
u32 em_ctl;
em_ctl = readl(mmio + HOST_EM_CTL);
return sprintf(buf, "%s%s%s%s\n",
em_ctl & EM_CTL_LED ? "led " : "",
em_ctl & EM_CTL_SAFTE ? "saf-te " : "",
em_ctl & EM_CTL_SES ? "ses-2 " : "",
em_ctl & EM_CTL_SGPIO ? "sgpio " : "");
}
/**
* ahci_save_initial_config - Save and fixup initial config values
* @dev: target AHCI device
* @hpriv: host private area to store config values
* @force_port_map: force port map to a specified value
* @mask_port_map: mask out particular bits from port map
*
* Some registers containing configuration info might be setup by
* BIOS and might be cleared on reset. This function saves the
* initial values of those registers into @hpriv such that they
* can be restored after controller reset.
*
* If inconsistent, config values are fixed up by this function.
*
* LOCKING:
* None.
*/
void ahci_save_initial_config(struct device *dev,
struct ahci_host_priv *hpriv,
unsigned int force_port_map,
unsigned int mask_port_map)
{
void __iomem *mmio = hpriv->mmio;
u32 cap, cap2, vers, port_map;
int i;
/* make sure AHCI mode is enabled before accessing CAP */
ahci_enable_ahci(mmio);
/* Values prefixed with saved_ are written back to host after
* reset. Values without are used for driver operation.
*/
hpriv->saved_cap = cap = readl(mmio + HOST_CAP);
hpriv->saved_port_map = port_map = readl(mmio + HOST_PORTS_IMPL);
/* CAP2 register is only defined for AHCI 1.2 and later */
vers = readl(mmio + HOST_VERSION);
if ((vers >> 16) > 1 ||
((vers >> 16) == 1 && (vers & 0xFFFF) >= 0x200))
hpriv->saved_cap2 = cap2 = readl(mmio + HOST_CAP2);
else
hpriv->saved_cap2 = cap2 = 0;
/* some chips have errata preventing 64bit use */
if ((cap & HOST_CAP_64) && (hpriv->flags & AHCI_HFLAG_32BIT_ONLY)) {
dev_info(dev, "controller can't do 64bit DMA, forcing 32bit\n");
cap &= ~HOST_CAP_64;
}
if ((cap & HOST_CAP_NCQ) && (hpriv->flags & AHCI_HFLAG_NO_NCQ)) {
dev_info(dev, "controller can't do NCQ, turning off CAP_NCQ\n");
cap &= ~HOST_CAP_NCQ;
}
if (!(cap & HOST_CAP_NCQ) && (hpriv->flags & AHCI_HFLAG_YES_NCQ)) {
dev_info(dev, "controller can do NCQ, turning on CAP_NCQ\n");
cap |= HOST_CAP_NCQ;
}
if ((cap & HOST_CAP_PMP) && (hpriv->flags & AHCI_HFLAG_NO_PMP)) {
dev_info(dev, "controller can't do PMP, turning off CAP_PMP\n");
cap &= ~HOST_CAP_PMP;
}
if ((cap & HOST_CAP_SNTF) && (hpriv->flags & AHCI_HFLAG_NO_SNTF)) {
dev_info(dev,
"controller can't do SNTF, turning off CAP_SNTF\n");
cap &= ~HOST_CAP_SNTF;
}
if (!(cap & HOST_CAP_FBS) && (hpriv->flags & AHCI_HFLAG_YES_FBS)) {
dev_info(dev, "controller can do FBS, turning on CAP_FBS\n");
cap |= HOST_CAP_FBS;
}
if (force_port_map && port_map != force_port_map) {
dev_info(dev, "forcing port_map 0x%x -> 0x%x\n",
port_map, force_port_map);
port_map = force_port_map;
}
if (mask_port_map) {
dev_warn(dev, "masking port_map 0x%x -> 0x%x\n",
port_map,
port_map & mask_port_map);
port_map &= mask_port_map;
}
/* cross check port_map and cap.n_ports */
if (port_map) {
int map_ports = 0;
for (i = 0; i < AHCI_MAX_PORTS; i++)
if (port_map & (1 << i))
map_ports++;
/* If PI has more ports than n_ports, whine, clear
* port_map and let it be generated from n_ports.
*/
if (map_ports > ahci_nr_ports(cap)) {
dev_warn(dev,
"implemented port map (0x%x) contains more ports than nr_ports (%u), using nr_ports\n",
port_map, ahci_nr_ports(cap));
port_map = 0;
}
}
/* fabricate port_map from cap.nr_ports */
if (!port_map) {
port_map = (1 << ahci_nr_ports(cap)) - 1;
dev_warn(dev, "forcing PORTS_IMPL to 0x%x\n", port_map);
/* write the fixed up value to the PI register */
hpriv->saved_port_map = port_map;
}
/* record values to use during operation */
hpriv->cap = cap;
hpriv->cap2 = cap2;
hpriv->port_map = port_map;
}
EXPORT_SYMBOL_GPL(ahci_save_initial_config);
/**
* ahci_restore_initial_config - Restore initial config
* @host: target ATA host
*
* Restore initial config stored by ahci_save_initial_config().
*
* LOCKING:
* None.
*/
static void ahci_restore_initial_config(struct ata_host *host)
{
struct ahci_host_priv *hpriv = host->private_data;
void __iomem *mmio = hpriv->mmio;
writel(hpriv->saved_cap, mmio + HOST_CAP);
if (hpriv->saved_cap2)
writel(hpriv->saved_cap2, mmio + HOST_CAP2);
writel(hpriv->saved_port_map, mmio + HOST_PORTS_IMPL);
(void) readl(mmio + HOST_PORTS_IMPL); /* flush */
}
static unsigned ahci_scr_offset(struct ata_port *ap, unsigned int sc_reg)
{
static const int offset[] = {
[SCR_STATUS] = PORT_SCR_STAT,
[SCR_CONTROL] = PORT_SCR_CTL,
[SCR_ERROR] = PORT_SCR_ERR,
[SCR_ACTIVE] = PORT_SCR_ACT,
[SCR_NOTIFICATION] = PORT_SCR_NTF,
};
struct ahci_host_priv *hpriv = ap->host->private_data;
if (sc_reg < ARRAY_SIZE(offset) &&
(sc_reg != SCR_NOTIFICATION || (hpriv->cap & HOST_CAP_SNTF)))
return offset[sc_reg];
return 0;
}
static int ahci_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val)
{
void __iomem *port_mmio = ahci_port_base(link->ap);
int offset = ahci_scr_offset(link->ap, sc_reg);
if (offset) {
*val = readl(port_mmio + offset);
return 0;
}
return -EINVAL;
}
static int ahci_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val)
{
void __iomem *port_mmio = ahci_port_base(link->ap);
int offset = ahci_scr_offset(link->ap, sc_reg);
if (offset) {
writel(val, port_mmio + offset);
return 0;
}
return -EINVAL;
}
void ahci_start_engine(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
u32 tmp;
/* start DMA */
tmp = readl(port_mmio + PORT_CMD);
tmp |= PORT_CMD_START;
writel(tmp, port_mmio + PORT_CMD);
readl(port_mmio + PORT_CMD); /* flush */
}
EXPORT_SYMBOL_GPL(ahci_start_engine);
int ahci_stop_engine(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
u32 tmp;
tmp = readl(port_mmio + PORT_CMD);
/* check if the HBA is idle */
if ((tmp & (PORT_CMD_START | PORT_CMD_LIST_ON)) == 0)
return 0;
/* setting HBA to idle */
tmp &= ~PORT_CMD_START;
writel(tmp, port_mmio + PORT_CMD);
/* wait for engine to stop. This could be as long as 500 msec */
tmp = ata_wait_register(ap, port_mmio + PORT_CMD,
PORT_CMD_LIST_ON, PORT_CMD_LIST_ON, 1, 500);
if (tmp & PORT_CMD_LIST_ON)
return -EIO;
return 0;
}
EXPORT_SYMBOL_GPL(ahci_stop_engine);
static void ahci_start_fis_rx(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
struct ahci_host_priv *hpriv = ap->host->private_data;
struct ahci_port_priv *pp = ap->private_data;
u32 tmp;
/* set FIS registers */
if (hpriv->cap & HOST_CAP_64)
writel((pp->cmd_slot_dma >> 16) >> 16,
port_mmio + PORT_LST_ADDR_HI);
writel(pp->cmd_slot_dma & 0xffffffff, port_mmio + PORT_LST_ADDR);
if (hpriv->cap & HOST_CAP_64)
writel((pp->rx_fis_dma >> 16) >> 16,
port_mmio + PORT_FIS_ADDR_HI);
writel(pp->rx_fis_dma & 0xffffffff, port_mmio + PORT_FIS_ADDR);
/* enable FIS reception */
tmp = readl(port_mmio + PORT_CMD);
tmp |= PORT_CMD_FIS_RX;
writel(tmp, port_mmio + PORT_CMD);
/* flush */
readl(port_mmio + PORT_CMD);
}
static int ahci_stop_fis_rx(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
u32 tmp;
/* disable FIS reception */
tmp = readl(port_mmio + PORT_CMD);
tmp &= ~PORT_CMD_FIS_RX;
writel(tmp, port_mmio + PORT_CMD);
/* wait for completion, spec says 500ms, give it 1000 */
tmp = ata_wait_register(ap, port_mmio + PORT_CMD, PORT_CMD_FIS_ON,
PORT_CMD_FIS_ON, 10, 1000);
if (tmp & PORT_CMD_FIS_ON)
return -EBUSY;
return 0;
}
static void ahci_power_up(struct ata_port *ap)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
u32 cmd;
cmd = readl(port_mmio + PORT_CMD) & ~PORT_CMD_ICC_MASK;
/* spin up device */
if (hpriv->cap & HOST_CAP_SSS) {
cmd |= PORT_CMD_SPIN_UP;
writel(cmd, port_mmio + PORT_CMD);
}
/* wake up link */
writel(cmd | PORT_CMD_ICC_ACTIVE, port_mmio + PORT_CMD);
}
static int ahci_set_lpm(struct ata_link *link, enum ata_lpm_policy policy,
unsigned int hints)
{
struct ata_port *ap = link->ap;
struct ahci_host_priv *hpriv = ap->host->private_data;
struct ahci_port_priv *pp = ap->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
if (policy != ATA_LPM_MAX_POWER) {
/*
* Disable interrupts on Phy Ready. This keeps us from
* getting woken up due to spurious phy ready
* interrupts.
*/
pp->intr_mask &= ~PORT_IRQ_PHYRDY;
writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
sata_link_scr_lpm(link, policy, false);
}
if (hpriv->cap & HOST_CAP_ALPM) {
u32 cmd = readl(port_mmio + PORT_CMD);
if (policy == ATA_LPM_MAX_POWER || !(hints & ATA_LPM_HIPM)) {
cmd &= ~(PORT_CMD_ASP | PORT_CMD_ALPE);
cmd |= PORT_CMD_ICC_ACTIVE;
writel(cmd, port_mmio + PORT_CMD);
readl(port_mmio + PORT_CMD);
/* wait 10ms to be sure we've come out of LPM state */
ata_msleep(ap, 10);
} else {
cmd |= PORT_CMD_ALPE;
if (policy == ATA_LPM_MIN_POWER)
cmd |= PORT_CMD_ASP;
/* write out new cmd value */
writel(cmd, port_mmio + PORT_CMD);
}
}
if (policy == ATA_LPM_MAX_POWER) {
sata_link_scr_lpm(link, policy, false);
/* turn PHYRDY IRQ back on */
pp->intr_mask |= PORT_IRQ_PHYRDY;
writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
}
return 0;
}
#ifdef CONFIG_PM
static void ahci_power_down(struct ata_port *ap)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
u32 cmd, scontrol;
if (!(hpriv->cap & HOST_CAP_SSS))
return;
/* put device into listen mode, first set PxSCTL.DET to 0 */
scontrol = readl(port_mmio + PORT_SCR_CTL);
scontrol &= ~0xf;
writel(scontrol, port_mmio + PORT_SCR_CTL);
/* then set PxCMD.SUD to 0 */
cmd = readl(port_mmio + PORT_CMD) & ~PORT_CMD_ICC_MASK;
cmd &= ~PORT_CMD_SPIN_UP;
writel(cmd, port_mmio + PORT_CMD);
}
#endif
static void ahci_start_port(struct ata_port *ap)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
struct ahci_port_priv *pp = ap->private_data;
struct ata_link *link;
struct ahci_em_priv *emp;
ssize_t rc;
int i;
/* enable FIS reception */
ahci_start_fis_rx(ap);
/* enable DMA */
if (!(hpriv->flags & AHCI_HFLAG_DELAY_ENGINE))
ahci_start_engine(ap);
/* turn on LEDs */
if (ap->flags & ATA_FLAG_EM) {
ata_for_each_link(link, ap, EDGE) {
emp = &pp->em_priv[link->pmp];
/* EM Transmit bit maybe busy during init */
for (i = 0; i < EM_MAX_RETRY; i++) {
rc = ahci_transmit_led_message(ap,
emp->led_state,
4);
if (rc == -EBUSY)
ata_msleep(ap, 1);
else
break;
}
}
}
if (ap->flags & ATA_FLAG_SW_ACTIVITY)
ata_for_each_link(link, ap, EDGE)
ahci_init_sw_activity(link);
}
static int ahci_deinit_port(struct ata_port *ap, const char **emsg)
{
int rc;
/* disable DMA */
rc = ahci_stop_engine(ap);
if (rc) {
*emsg = "failed to stop engine";
return rc;
}
/* disable FIS reception */
rc = ahci_stop_fis_rx(ap);
if (rc) {
*emsg = "failed stop FIS RX";
return rc;
}
return 0;
}
int ahci_reset_controller(struct ata_host *host)
{
struct ahci_host_priv *hpriv = host->private_data;
void __iomem *mmio = hpriv->mmio;
u32 tmp;
/* we must be in AHCI mode, before using anything
* AHCI-specific, such as HOST_RESET.
*/
ahci_enable_ahci(mmio);
/* global controller reset */
if (!ahci_skip_host_reset) {
tmp = readl(mmio + HOST_CTL);
if ((tmp & HOST_RESET) == 0) {
writel(tmp | HOST_RESET, mmio + HOST_CTL);
readl(mmio + HOST_CTL); /* flush */
}
/*
* to perform host reset, OS should set HOST_RESET
* and poll until this bit is read to be "0".
* reset must complete within 1 second, or
* the hardware should be considered fried.
*/
tmp = ata_wait_register(NULL, mmio + HOST_CTL, HOST_RESET,
HOST_RESET, 10, 1000);
if (tmp & HOST_RESET) {
dev_err(host->dev, "controller reset failed (0x%x)\n",
tmp);
return -EIO;
}
/* turn on AHCI mode */
ahci_enable_ahci(mmio);
/* Some registers might be cleared on reset. Restore
* initial values.
*/
ahci_restore_initial_config(host);
} else
dev_info(host->dev, "skipping global host reset\n");
return 0;
}
EXPORT_SYMBOL_GPL(ahci_reset_controller);
static void ahci_sw_activity(struct ata_link *link)
{
struct ata_port *ap = link->ap;
struct ahci_port_priv *pp = ap->private_data;
struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
if (!(link->flags & ATA_LFLAG_SW_ACTIVITY))
return;
emp->activity++;
if (!timer_pending(&emp->timer))
mod_timer(&emp->timer, jiffies + msecs_to_jiffies(10));
}
static void ahci_sw_activity_blink(unsigned long arg)
{
struct ata_link *link = (struct ata_link *)arg;
struct ata_port *ap = link->ap;
struct ahci_port_priv *pp = ap->private_data;
struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
unsigned long led_message = emp->led_state;
u32 activity_led_state;
unsigned long flags;
led_message &= EM_MSG_LED_VALUE;
led_message |= ap->port_no | (link->pmp << 8);
/* check to see if we've had activity. If so,
* toggle state of LED and reset timer. If not,
* turn LED to desired idle state.
*/
spin_lock_irqsave(ap->lock, flags);
if (emp->saved_activity != emp->activity) {
emp->saved_activity = emp->activity;
/* get the current LED state */
activity_led_state = led_message & EM_MSG_LED_VALUE_ON;
if (activity_led_state)
activity_led_state = 0;
else
activity_led_state = 1;
/* clear old state */
led_message &= ~EM_MSG_LED_VALUE_ACTIVITY;
/* toggle state */
led_message |= (activity_led_state << 16);
mod_timer(&emp->timer, jiffies + msecs_to_jiffies(100));
} else {
/* switch to idle */
led_message &= ~EM_MSG_LED_VALUE_ACTIVITY;
if (emp->blink_policy == BLINK_OFF)
led_message |= (1 << 16);
}
spin_unlock_irqrestore(ap->lock, flags);
ahci_transmit_led_message(ap, led_message, 4);
}
static void ahci_init_sw_activity(struct ata_link *link)
{
struct ata_port *ap = link->ap;
struct ahci_port_priv *pp = ap->private_data;
struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
/* init activity stats, setup timer */
emp->saved_activity = emp->activity = 0;
setup_timer(&emp->timer, ahci_sw_activity_blink, (unsigned long)link);
/* check our blink policy and set flag for link if it's enabled */
if (emp->blink_policy)
link->flags |= ATA_LFLAG_SW_ACTIVITY;
}
int ahci_reset_em(struct ata_host *host)
{
struct ahci_host_priv *hpriv = host->private_data;
void __iomem *mmio = hpriv->mmio;
u32 em_ctl;
em_ctl = readl(mmio + HOST_EM_CTL);
if ((em_ctl & EM_CTL_TM) || (em_ctl & EM_CTL_RST))
return -EINVAL;
writel(em_ctl | EM_CTL_RST, mmio + HOST_EM_CTL);
return 0;
}
EXPORT_SYMBOL_GPL(ahci_reset_em);
static ssize_t ahci_transmit_led_message(struct ata_port *ap, u32 state,
ssize_t size)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
struct ahci_port_priv *pp = ap->private_data;
void __iomem *mmio = hpriv->mmio;
u32 em_ctl;
u32 message[] = {0, 0};
unsigned long flags;
int pmp;
struct ahci_em_priv *emp;
/* get the slot number from the message */
pmp = (state & EM_MSG_LED_PMP_SLOT) >> 8;
if (pmp < EM_MAX_SLOTS)
emp = &pp->em_priv[pmp];
else
return -EINVAL;
spin_lock_irqsave(ap->lock, flags);
/*
* if we are still busy transmitting a previous message,
* do not allow
*/
em_ctl = readl(mmio + HOST_EM_CTL);
if (em_ctl & EM_CTL_TM) {
spin_unlock_irqrestore(ap->lock, flags);
return -EBUSY;
}
if (hpriv->em_msg_type & EM_MSG_TYPE_LED) {
/*
* create message header - this is all zero except for
* the message size, which is 4 bytes.
*/
message[0] |= (4 << 8);
/* ignore 0:4 of byte zero, fill in port info yourself */
message[1] = ((state & ~EM_MSG_LED_HBA_PORT) | ap->port_no);
/* write message to EM_LOC */
writel(message[0], mmio + hpriv->em_loc);
writel(message[1], mmio + hpriv->em_loc+4);
/*
* tell hardware to transmit the message
*/
writel(em_ctl | EM_CTL_TM, mmio + HOST_EM_CTL);
}
/* save off new led state for port/slot */
emp->led_state = state;
spin_unlock_irqrestore(ap->lock, flags);
return size;
}
static ssize_t ahci_led_show(struct ata_port *ap, char *buf)
{
struct ahci_port_priv *pp = ap->private_data;
struct ata_link *link;
struct ahci_em_priv *emp;
int rc = 0;
ata_for_each_link(link, ap, EDGE) {
emp = &pp->em_priv[link->pmp];
rc += sprintf(buf, "%lx\n", emp->led_state);
}
return rc;
}
static ssize_t ahci_led_store(struct ata_port *ap, const char *buf,
size_t size)
{
int state;
int pmp;
struct ahci_port_priv *pp = ap->private_data;
struct ahci_em_priv *emp;
state = simple_strtoul(buf, NULL, 0);
/* get the slot number from the message */
pmp = (state & EM_MSG_LED_PMP_SLOT) >> 8;
if (pmp < EM_MAX_SLOTS)
emp = &pp->em_priv[pmp];
else
return -EINVAL;
/* mask off the activity bits if we are in sw_activity
* mode, user should turn off sw_activity before setting
* activity led through em_message
*/
if (emp->blink_policy)
state &= ~EM_MSG_LED_VALUE_ACTIVITY;
return ahci_transmit_led_message(ap, state, size);
}
static ssize_t ahci_activity_store(struct ata_device *dev, enum sw_activity val)
{
struct ata_link *link = dev->link;
struct ata_port *ap = link->ap;
struct ahci_port_priv *pp = ap->private_data;
struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
u32 port_led_state = emp->led_state;
/* save the desired Activity LED behavior */
if (val == OFF) {
/* clear LFLAG */
link->flags &= ~(ATA_LFLAG_SW_ACTIVITY);
/* set the LED to OFF */
port_led_state &= EM_MSG_LED_VALUE_OFF;
port_led_state |= (ap->port_no | (link->pmp << 8));
ahci_transmit_led_message(ap, port_led_state, 4);
} else {
link->flags |= ATA_LFLAG_SW_ACTIVITY;
if (val == BLINK_OFF) {
/* set LED to ON for idle */
port_led_state &= EM_MSG_LED_VALUE_OFF;
port_led_state |= (ap->port_no | (link->pmp << 8));
port_led_state |= EM_MSG_LED_VALUE_ON; /* check this */
ahci_transmit_led_message(ap, port_led_state, 4);
}
}
emp->blink_policy = val;
return 0;
}
static ssize_t ahci_activity_show(struct ata_device *dev, char *buf)
{
struct ata_link *link = dev->link;
struct ata_port *ap = link->ap;
struct ahci_port_priv *pp = ap->private_data;
struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
/* display the saved value of activity behavior for this
* disk.
*/
return sprintf(buf, "%d\n", emp->blink_policy);
}
static void ahci_port_init(struct device *dev, struct ata_port *ap,
int port_no, void __iomem *mmio,
void __iomem *port_mmio)
{
const char *emsg = NULL;
int rc;
u32 tmp;
/* make sure port is not active */
rc = ahci_deinit_port(ap, &emsg);
if (rc)
dev_warn(dev, "%s (%d)\n", emsg, rc);
/* clear SError */
tmp = readl(port_mmio + PORT_SCR_ERR);
VPRINTK("PORT_SCR_ERR 0x%x\n", tmp);
writel(tmp, port_mmio + PORT_SCR_ERR);
/* clear port IRQ */
tmp = readl(port_mmio + PORT_IRQ_STAT);
VPRINTK("PORT_IRQ_STAT 0x%x\n", tmp);
if (tmp)
writel(tmp, port_mmio + PORT_IRQ_STAT);
writel(1 << port_no, mmio + HOST_IRQ_STAT);
}
void ahci_init_controller(struct ata_host *host)
{
struct ahci_host_priv *hpriv = host->private_data;
void __iomem *mmio = hpriv->mmio;
int i;
void __iomem *port_mmio;
u32 tmp;
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
port_mmio = ahci_port_base(ap);
if (ata_port_is_dummy(ap))
continue;
ahci_port_init(host->dev, ap, i, mmio, port_mmio);
}
tmp = readl(mmio + HOST_CTL);
VPRINTK("HOST_CTL 0x%x\n", tmp);
writel(tmp | HOST_IRQ_EN, mmio + HOST_CTL);
tmp = readl(mmio + HOST_CTL);
VPRINTK("HOST_CTL 0x%x\n", tmp);
}
EXPORT_SYMBOL_GPL(ahci_init_controller);
static void ahci_dev_config(struct ata_device *dev)
{
struct ahci_host_priv *hpriv = dev->link->ap->host->private_data;
if (hpriv->flags & AHCI_HFLAG_SECT255) {
dev->max_sectors = 255;
ata_dev_info(dev,
"SB600 AHCI: limiting to 255 sectors per cmd\n");
}
}
static unsigned int ahci_dev_classify(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
struct ata_taskfile tf;
u32 tmp;
tmp = readl(port_mmio + PORT_SIG);
tf.lbah = (tmp >> 24) & 0xff;
tf.lbam = (tmp >> 16) & 0xff;
tf.lbal = (tmp >> 8) & 0xff;
tf.nsect = (tmp) & 0xff;
return ata_dev_classify(&tf);
}
void ahci_fill_cmd_slot(struct ahci_port_priv *pp, unsigned int tag,
u32 opts)
{
dma_addr_t cmd_tbl_dma;
cmd_tbl_dma = pp->cmd_tbl_dma + tag * AHCI_CMD_TBL_SZ;
pp->cmd_slot[tag].opts = cpu_to_le32(opts);
pp->cmd_slot[tag].status = 0;
pp->cmd_slot[tag].tbl_addr = cpu_to_le32(cmd_tbl_dma & 0xffffffff);
pp->cmd_slot[tag].tbl_addr_hi = cpu_to_le32((cmd_tbl_dma >> 16) >> 16);
}
EXPORT_SYMBOL_GPL(ahci_fill_cmd_slot);
int ahci_kick_engine(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
struct ahci_host_priv *hpriv = ap->host->private_data;
u8 status = readl(port_mmio + PORT_TFDATA) & 0xFF;
u32 tmp;
int busy, rc;
/* stop engine */
rc = ahci_stop_engine(ap);
if (rc)
goto out_restart;
/* need to do CLO?
* always do CLO if PMP is attached (AHCI-1.3 9.2)
*/
busy = status & (ATA_BUSY | ATA_DRQ);
if (!busy && !sata_pmp_attached(ap)) {
rc = 0;
goto out_restart;
}
if (!(hpriv->cap & HOST_CAP_CLO)) {
rc = -EOPNOTSUPP;
goto out_restart;
}
/* perform CLO */
tmp = readl(port_mmio + PORT_CMD);
tmp |= PORT_CMD_CLO;
writel(tmp, port_mmio + PORT_CMD);
rc = 0;
tmp = ata_wait_register(ap, port_mmio + PORT_CMD,
PORT_CMD_CLO, PORT_CMD_CLO, 1, 500);
if (tmp & PORT_CMD_CLO)
rc = -EIO;
/* restart engine */
out_restart:
ahci_start_engine(ap);
return rc;
}
EXPORT_SYMBOL_GPL(ahci_kick_engine);
static int ahci_exec_polled_cmd(struct ata_port *ap, int pmp,
struct ata_taskfile *tf, int is_cmd, u16 flags,
unsigned long timeout_msec)
{
const u32 cmd_fis_len = 5; /* five dwords */
struct ahci_port_priv *pp = ap->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
u8 *fis = pp->cmd_tbl;
u32 tmp;
/* prep the command */
ata_tf_to_fis(tf, pmp, is_cmd, fis);
ahci_fill_cmd_slot(pp, 0, cmd_fis_len | flags | (pmp << 12));
/* issue & wait */
writel(1, port_mmio + PORT_CMD_ISSUE);
if (timeout_msec) {
tmp = ata_wait_register(ap, port_mmio + PORT_CMD_ISSUE,
0x1, 0x1, 1, timeout_msec);
if (tmp & 0x1) {
ahci_kick_engine(ap);
return -EBUSY;
}
} else
readl(port_mmio + PORT_CMD_ISSUE); /* flush */
return 0;
}
int ahci_do_softreset(struct ata_link *link, unsigned int *class,
int pmp, unsigned long deadline,
int (*check_ready)(struct ata_link *link))
{
struct ata_port *ap = link->ap;
struct ahci_host_priv *hpriv = ap->host->private_data;
const char *reason = NULL;
unsigned long now, msecs;
struct ata_taskfile tf;
int rc;
DPRINTK("ENTER\n");
/* prepare for SRST (AHCI-1.1 10.4.1) */
rc = ahci_kick_engine(ap);
if (rc && rc != -EOPNOTSUPP)
ata_link_warn(link, "failed to reset engine (errno=%d)\n", rc);
ata_tf_init(link->device, &tf);
/* issue the first D2H Register FIS */
msecs = 0;
now = jiffies;
if (time_after(deadline, now))
msecs = jiffies_to_msecs(deadline - now);
tf.ctl |= ATA_SRST;
if (ahci_exec_polled_cmd(ap, pmp, &tf, 0,
AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY, msecs)) {
rc = -EIO;
reason = "1st FIS failed";
goto fail;
}
/* spec says at least 5us, but be generous and sleep for 1ms */
ata_msleep(ap, 1);
/* issue the second D2H Register FIS */
tf.ctl &= ~ATA_SRST;
ahci_exec_polled_cmd(ap, pmp, &tf, 0, 0, 0);
/* wait for link to become ready */
rc = ata_wait_after_reset(link, deadline, check_ready);
if (rc == -EBUSY && hpriv->flags & AHCI_HFLAG_SRST_TOUT_IS_OFFLINE) {
/*
* Workaround for cases where link online status can't
* be trusted. Treat device readiness timeout as link
* offline.
*/
ata_link_info(link, "device not ready, treating as offline\n");
*class = ATA_DEV_NONE;
} else if (rc) {
/* link occupied, -ENODEV too is an error */
reason = "device not ready";
goto fail;
} else
*class = ahci_dev_classify(ap);
DPRINTK("EXIT, class=%u\n", *class);
return 0;
fail:
ata_link_err(link, "softreset failed (%s)\n", reason);
return rc;
}
int ahci_check_ready(struct ata_link *link)
{
void __iomem *port_mmio = ahci_port_base(link->ap);
u8 status = readl(port_mmio + PORT_TFDATA) & 0xFF;
return ata_check_ready(status);
}
EXPORT_SYMBOL_GPL(ahci_check_ready);
static int ahci_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
int pmp = sata_srst_pmp(link);
DPRINTK("ENTER\n");
return ahci_do_softreset(link, class, pmp, deadline, ahci_check_ready);
}
EXPORT_SYMBOL_GPL(ahci_do_softreset);
static int ahci_bad_pmp_check_ready(struct ata_link *link)
{
void __iomem *port_mmio = ahci_port_base(link->ap);
u8 status = readl(port_mmio + PORT_TFDATA) & 0xFF;
u32 irq_status = readl(port_mmio + PORT_IRQ_STAT);
/*
* There is no need to check TFDATA if BAD PMP is found due to HW bug,
* which can save timeout delay.
*/
if (irq_status & PORT_IRQ_BAD_PMP)
return -EIO;
return ata_check_ready(status);
}
int ahci_pmp_retry_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
void __iomem *port_mmio = ahci_port_base(ap);
int pmp = sata_srst_pmp(link);
int rc;
u32 irq_sts;
DPRINTK("ENTER\n");
rc = ahci_do_softreset(link, class, pmp, deadline,
ahci_bad_pmp_check_ready);
/*
* Soft reset fails with IPMS set when PMP is enabled but
* SATA HDD/ODD is connected to SATA port, do soft reset
* again to port 0.
*/
if (rc == -EIO) {
irq_sts = readl(port_mmio + PORT_IRQ_STAT);
if (irq_sts & PORT_IRQ_BAD_PMP) {
ata_link_printk(link, KERN_WARNING,
"applying PMP SRST workaround "
"and retrying\n");
rc = ahci_do_softreset(link, class, 0, deadline,
ahci_check_ready);
}
}
return rc;
}
static int ahci_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
const unsigned long *timing = sata_ehc_deb_timing(&link->eh_context);
struct ata_port *ap = link->ap;
struct ahci_port_priv *pp = ap->private_data;
u8 *d2h_fis = pp->rx_fis + RX_FIS_D2H_REG;
struct ata_taskfile tf;
bool online;
int rc;
DPRINTK("ENTER\n");
ahci_stop_engine(ap);
/* clear D2H reception area to properly wait for D2H FIS */
ata_tf_init(link->device, &tf);
tf.command = 0x80;
ata_tf_to_fis(&tf, 0, 0, d2h_fis);
rc = sata_link_hardreset(link, timing, deadline, &online,
ahci_check_ready);
ahci_start_engine(ap);
if (online)
*class = ahci_dev_classify(ap);
DPRINTK("EXIT, rc=%d, class=%u\n", rc, *class);
return rc;
}
static void ahci_postreset(struct ata_link *link, unsigned int *class)
{
struct ata_port *ap = link->ap;
void __iomem *port_mmio = ahci_port_base(ap);
u32 new_tmp, tmp;
ata_std_postreset(link, class);
/* Make sure port's ATAPI bit is set appropriately */
new_tmp = tmp = readl(port_mmio + PORT_CMD);
if (*class == ATA_DEV_ATAPI)
new_tmp |= PORT_CMD_ATAPI;
else
new_tmp &= ~PORT_CMD_ATAPI;
if (new_tmp != tmp) {
writel(new_tmp, port_mmio + PORT_CMD);
readl(port_mmio + PORT_CMD); /* flush */
}
}
static unsigned int ahci_fill_sg(struct ata_queued_cmd *qc, void *cmd_tbl)
{
struct scatterlist *sg;
struct ahci_sg *ahci_sg = cmd_tbl + AHCI_CMD_TBL_HDR_SZ;
unsigned int si;
VPRINTK("ENTER\n");
/*
* Next, the S/G list.
*/
for_each_sg(qc->sg, sg, qc->n_elem, si) {
dma_addr_t addr = sg_dma_address(sg);
u32 sg_len = sg_dma_len(sg);
ahci_sg[si].addr = cpu_to_le32(addr & 0xffffffff);
ahci_sg[si].addr_hi = cpu_to_le32((addr >> 16) >> 16);
ahci_sg[si].flags_size = cpu_to_le32(sg_len - 1);
}
return si;
}
static int ahci_pmp_qc_defer(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ahci_port_priv *pp = ap->private_data;
if (!sata_pmp_attached(ap) || pp->fbs_enabled)
return ata_std_qc_defer(qc);
else
return sata_pmp_qc_defer_cmd_switch(qc);
}
static void ahci_qc_prep(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ahci_port_priv *pp = ap->private_data;
int is_atapi = ata_is_atapi(qc->tf.protocol);
void *cmd_tbl;
u32 opts;
const u32 cmd_fis_len = 5; /* five dwords */
unsigned int n_elem;
/*
* Fill in command table information. First, the header,
* a SATA Register - Host to Device command FIS.
*/
cmd_tbl = pp->cmd_tbl + qc->tag * AHCI_CMD_TBL_SZ;
ata_tf_to_fis(&qc->tf, qc->dev->link->pmp, 1, cmd_tbl);
if (is_atapi) {
memset(cmd_tbl + AHCI_CMD_TBL_CDB, 0, 32);
memcpy(cmd_tbl + AHCI_CMD_TBL_CDB, qc->cdb, qc->dev->cdb_len);
}
n_elem = 0;
if (qc->flags & ATA_QCFLAG_DMAMAP)
n_elem = ahci_fill_sg(qc, cmd_tbl);
/*
* Fill in command slot information.
*/
opts = cmd_fis_len | n_elem << 16 | (qc->dev->link->pmp << 12);
if (qc->tf.flags & ATA_TFLAG_WRITE)
opts |= AHCI_CMD_WRITE;
if (is_atapi)
opts |= AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH;
ahci_fill_cmd_slot(pp, qc->tag, opts);
}
static void ahci_fbs_dec_intr(struct ata_port *ap)
{
struct ahci_port_priv *pp = ap->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
u32 fbs = readl(port_mmio + PORT_FBS);
int retries = 3;
DPRINTK("ENTER\n");
BUG_ON(!pp->fbs_enabled);
/* time to wait for DEC is not specified by AHCI spec,
* add a retry loop for safety.
*/
writel(fbs | PORT_FBS_DEC, port_mmio + PORT_FBS);
fbs = readl(port_mmio + PORT_FBS);
while ((fbs & PORT_FBS_DEC) && retries--) {
udelay(1);
fbs = readl(port_mmio + PORT_FBS);
}
if (fbs & PORT_FBS_DEC)
dev_err(ap->host->dev, "failed to clear device error\n");
}
static void ahci_error_intr(struct ata_port *ap, u32 irq_stat)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
struct ahci_port_priv *pp = ap->private_data;
struct ata_eh_info *host_ehi = &ap->link.eh_info;
struct ata_link *link = NULL;
struct ata_queued_cmd *active_qc;
struct ata_eh_info *active_ehi;
bool fbs_need_dec = false;
u32 serror;
/* determine active link with error */
if (pp->fbs_enabled) {
void __iomem *port_mmio = ahci_port_base(ap);
u32 fbs = readl(port_mmio + PORT_FBS);
int pmp = fbs >> PORT_FBS_DWE_OFFSET;
if ((fbs & PORT_FBS_SDE) && (pmp < ap->nr_pmp_links)) {
link = &ap->pmp_link[pmp];
fbs_need_dec = true;
}
} else
ata_for_each_link(link, ap, EDGE)
if (ata_link_active(link))
break;
if (!link)
link = &ap->link;
active_qc = ata_qc_from_tag(ap, link->active_tag);
active_ehi = &link->eh_info;
/* record irq stat */
ata_ehi_clear_desc(host_ehi);
ata_ehi_push_desc(host_ehi, "irq_stat 0x%08x", irq_stat);
/* AHCI needs SError cleared; otherwise, it might lock up */
ahci_scr_read(&ap->link, SCR_ERROR, &serror);
ahci_scr_write(&ap->link, SCR_ERROR, serror);
host_ehi->serror |= serror;
/* some controllers set IRQ_IF_ERR on device errors, ignore it */
if (hpriv->flags & AHCI_HFLAG_IGN_IRQ_IF_ERR)
irq_stat &= ~PORT_IRQ_IF_ERR;
if (irq_stat & PORT_IRQ_TF_ERR) {
/* If qc is active, charge it; otherwise, the active
* link. There's no active qc on NCQ errors. It will
* be determined by EH by reading log page 10h.
*/
if (active_qc)
active_qc->err_mask |= AC_ERR_DEV;
else
active_ehi->err_mask |= AC_ERR_DEV;
if (hpriv->flags & AHCI_HFLAG_IGN_SERR_INTERNAL)
host_ehi->serror &= ~SERR_INTERNAL;
}
if (irq_stat & PORT_IRQ_UNK_FIS) {
u32 *unk = (u32 *)(pp->rx_fis + RX_FIS_UNK);
active_ehi->err_mask |= AC_ERR_HSM;
active_ehi->action |= ATA_EH_RESET;
ata_ehi_push_desc(active_ehi,
"unknown FIS %08x %08x %08x %08x" ,
unk[0], unk[1], unk[2], unk[3]);
}
if (sata_pmp_attached(ap) && (irq_stat & PORT_IRQ_BAD_PMP)) {
active_ehi->err_mask |= AC_ERR_HSM;
active_ehi->action |= ATA_EH_RESET;
ata_ehi_push_desc(active_ehi, "incorrect PMP");
}
if (irq_stat & (PORT_IRQ_HBUS_ERR | PORT_IRQ_HBUS_DATA_ERR)) {
host_ehi->err_mask |= AC_ERR_HOST_BUS;
host_ehi->action |= ATA_EH_RESET;
ata_ehi_push_desc(host_ehi, "host bus error");
}
if (irq_stat & PORT_IRQ_IF_ERR) {
if (fbs_need_dec)
active_ehi->err_mask |= AC_ERR_DEV;
else {
host_ehi->err_mask |= AC_ERR_ATA_BUS;
host_ehi->action |= ATA_EH_RESET;
}
ata_ehi_push_desc(host_ehi, "interface fatal error");
}
if (irq_stat & (PORT_IRQ_CONNECT | PORT_IRQ_PHYRDY)) {
ata_ehi_hotplugged(host_ehi);
ata_ehi_push_desc(host_ehi, "%s",
irq_stat & PORT_IRQ_CONNECT ?
"connection status changed" : "PHY RDY changed");
}
/* okay, let's hand over to EH */
if (irq_stat & PORT_IRQ_FREEZE)
ata_port_freeze(ap);
else if (fbs_need_dec) {
ata_link_abort(link);
ahci_fbs_dec_intr(ap);
} else
ata_port_abort(ap);
}
static void ahci_port_intr(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
struct ata_eh_info *ehi = &ap->link.eh_info;
struct ahci_port_priv *pp = ap->private_data;
struct ahci_host_priv *hpriv = ap->host->private_data;
int resetting = !!(ap->pflags & ATA_PFLAG_RESETTING);
u32 status, qc_active = 0;
int rc;
status = readl(port_mmio + PORT_IRQ_STAT);
writel(status, port_mmio + PORT_IRQ_STAT);
/* ignore BAD_PMP while resetting */
if (unlikely(resetting))
status &= ~PORT_IRQ_BAD_PMP;
/* if LPM is enabled, PHYRDY doesn't mean anything */
if (ap->link.lpm_policy > ATA_LPM_MAX_POWER) {
status &= ~PORT_IRQ_PHYRDY;
ahci_scr_write(&ap->link, SCR_ERROR, SERR_PHYRDY_CHG);
}
if (unlikely(status & PORT_IRQ_ERROR)) {
ahci_error_intr(ap, status);
return;
}
if (status & PORT_IRQ_SDB_FIS) {
/* If SNotification is available, leave notification
* handling to sata_async_notification(). If not,
* emulate it by snooping SDB FIS RX area.
*
* Snooping FIS RX area is probably cheaper than
* poking SNotification but some constrollers which
* implement SNotification, ICH9 for example, don't
* store AN SDB FIS into receive area.
*/
if (hpriv->cap & HOST_CAP_SNTF)
sata_async_notification(ap);
else {
/* If the 'N' bit in word 0 of the FIS is set,
* we just received asynchronous notification.
* Tell libata about it.
*
* Lack of SNotification should not appear in
* ahci 1.2, so the workaround is unnecessary
* when FBS is enabled.
*/
if (pp->fbs_enabled)
WARN_ON_ONCE(1);
else {
const __le32 *f = pp->rx_fis + RX_FIS_SDB;
u32 f0 = le32_to_cpu(f[0]);
if (f0 & (1 << 15))
sata_async_notification(ap);
}
}
}
/* pp->active_link is not reliable once FBS is enabled, both
* PORT_SCR_ACT and PORT_CMD_ISSUE should be checked because
* NCQ and non-NCQ commands may be in flight at the same time.
*/
if (pp->fbs_enabled) {
if (ap->qc_active) {
qc_active = readl(port_mmio + PORT_SCR_ACT);
qc_active |= readl(port_mmio + PORT_CMD_ISSUE);
}
} else {
/* pp->active_link is valid iff any command is in flight */
if (ap->qc_active && pp->active_link->sactive)
qc_active = readl(port_mmio + PORT_SCR_ACT);
else
qc_active = readl(port_mmio + PORT_CMD_ISSUE);
}
rc = ata_qc_complete_multiple(ap, qc_active);
/* while resetting, invalid completions are expected */
if (unlikely(rc < 0 && !resetting)) {
ehi->err_mask |= AC_ERR_HSM;
ehi->action |= ATA_EH_RESET;
ata_port_freeze(ap);
}
}
irqreturn_t ahci_interrupt(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
struct ahci_host_priv *hpriv;
unsigned int i, handled = 0;
void __iomem *mmio;
u32 irq_stat, irq_masked;
VPRINTK("ENTER\n");
hpriv = host->private_data;
mmio = hpriv->mmio;
/* sigh. 0xffffffff is a valid return from h/w */
irq_stat = readl(mmio + HOST_IRQ_STAT);
if (!irq_stat)
return IRQ_NONE;
irq_masked = irq_stat & hpriv->port_map;
spin_lock(&host->lock);
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap;
if (!(irq_masked & (1 << i)))
continue;
ap = host->ports[i];
if (ap) {
ahci_port_intr(ap);
VPRINTK("port %u\n", i);
} else {
VPRINTK("port %u (no irq)\n", i);
if (ata_ratelimit())
dev_warn(host->dev,
"interrupt on disabled port %u\n", i);
}
handled = 1;
}
/* HOST_IRQ_STAT behaves as level triggered latch meaning that
* it should be cleared after all the port events are cleared;
* otherwise, it will raise a spurious interrupt after each
* valid one. Please read section 10.6.2 of ahci 1.1 for more
* information.
*
* Also, use the unmasked value to clear interrupt as spurious
* pending event on a dummy port might cause screaming IRQ.
*/
writel(irq_stat, mmio + HOST_IRQ_STAT);
spin_unlock(&host->lock);
VPRINTK("EXIT\n");
return IRQ_RETVAL(handled);
}
EXPORT_SYMBOL_GPL(ahci_interrupt);
static unsigned int ahci_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
void __iomem *port_mmio = ahci_port_base(ap);
struct ahci_port_priv *pp = ap->private_data;
/* Keep track of the currently active link. It will be used
* in completion path to determine whether NCQ phase is in
* progress.
*/
pp->active_link = qc->dev->link;
if (qc->tf.protocol == ATA_PROT_NCQ)
writel(1 << qc->tag, port_mmio + PORT_SCR_ACT);
if (pp->fbs_enabled && pp->fbs_last_dev != qc->dev->link->pmp) {
u32 fbs = readl(port_mmio + PORT_FBS);
fbs &= ~(PORT_FBS_DEV_MASK | PORT_FBS_DEC);
fbs |= qc->dev->link->pmp << PORT_FBS_DEV_OFFSET;
writel(fbs, port_mmio + PORT_FBS);
pp->fbs_last_dev = qc->dev->link->pmp;
}
writel(1 << qc->tag, port_mmio + PORT_CMD_ISSUE);
ahci_sw_activity(qc->dev->link);
return 0;
}
static bool ahci_qc_fill_rtf(struct ata_queued_cmd *qc)
{
struct ahci_port_priv *pp = qc->ap->private_data;
u8 *rx_fis = pp->rx_fis;
if (pp->fbs_enabled)
rx_fis += qc->dev->link->pmp * AHCI_RX_FIS_SZ;
/*
* After a successful execution of an ATA PIO data-in command,
* the device doesn't send D2H Reg FIS to update the TF and
* the host should take TF and E_Status from the preceding PIO
* Setup FIS.
*/
if (qc->tf.protocol == ATA_PROT_PIO && qc->dma_dir == DMA_FROM_DEVICE &&
!(qc->flags & ATA_QCFLAG_FAILED)) {
ata_tf_from_fis(rx_fis + RX_FIS_PIO_SETUP, &qc->result_tf);
qc->result_tf.command = (rx_fis + RX_FIS_PIO_SETUP)[15];
} else
ata_tf_from_fis(rx_fis + RX_FIS_D2H_REG, &qc->result_tf);
return true;
}
static void ahci_freeze(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
/* turn IRQ off */
writel(0, port_mmio + PORT_IRQ_MASK);
}
static void ahci_thaw(struct ata_port *ap)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
void __iomem *mmio = hpriv->mmio;
void __iomem *port_mmio = ahci_port_base(ap);
u32 tmp;
struct ahci_port_priv *pp = ap->private_data;
/* clear IRQ */
tmp = readl(port_mmio + PORT_IRQ_STAT);
writel(tmp, port_mmio + PORT_IRQ_STAT);
writel(1 << ap->port_no, mmio + HOST_IRQ_STAT);
/* turn IRQ back on */
writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
}
static void ahci_error_handler(struct ata_port *ap)
{
if (!(ap->pflags & ATA_PFLAG_FROZEN)) {
/* restart engine */
ahci_stop_engine(ap);
ahci_start_engine(ap);
}
sata_pmp_error_handler(ap);
if (!ata_dev_enabled(ap->link.device))
ahci_stop_engine(ap);
}
static void ahci_post_internal_cmd(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
/* make DMA engine forget about the failed command */
if (qc->flags & ATA_QCFLAG_FAILED)
ahci_kick_engine(ap);
}
static void ahci_enable_fbs(struct ata_port *ap)
{
struct ahci_port_priv *pp = ap->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
u32 fbs;
int rc;
if (!pp->fbs_supported)
return;
fbs = readl(port_mmio + PORT_FBS);
if (fbs & PORT_FBS_EN) {
pp->fbs_enabled = true;
pp->fbs_last_dev = -1; /* initialization */
return;
}
rc = ahci_stop_engine(ap);
if (rc)
return;
writel(fbs | PORT_FBS_EN, port_mmio + PORT_FBS);
fbs = readl(port_mmio + PORT_FBS);
if (fbs & PORT_FBS_EN) {
dev_info(ap->host->dev, "FBS is enabled\n");
pp->fbs_enabled = true;
pp->fbs_last_dev = -1; /* initialization */
} else
dev_err(ap->host->dev, "Failed to enable FBS\n");
ahci_start_engine(ap);
}
static void ahci_disable_fbs(struct ata_port *ap)
{
struct ahci_port_priv *pp = ap->private_data;
void __iomem *port_mmio = ahci_port_base(ap);
u32 fbs;
int rc;
if (!pp->fbs_supported)
return;
fbs = readl(port_mmio + PORT_FBS);
if ((fbs & PORT_FBS_EN) == 0) {
pp->fbs_enabled = false;
return;
}
rc = ahci_stop_engine(ap);
if (rc)
return;
writel(fbs & ~PORT_FBS_EN, port_mmio + PORT_FBS);
fbs = readl(port_mmio + PORT_FBS);
if (fbs & PORT_FBS_EN)
dev_err(ap->host->dev, "Failed to disable FBS\n");
else {
dev_info(ap->host->dev, "FBS is disabled\n");
pp->fbs_enabled = false;
}
ahci_start_engine(ap);
}
static void ahci_pmp_attach(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
struct ahci_port_priv *pp = ap->private_data;
u32 cmd;
cmd = readl(port_mmio + PORT_CMD);
cmd |= PORT_CMD_PMP;
writel(cmd, port_mmio + PORT_CMD);
ahci_enable_fbs(ap);
pp->intr_mask |= PORT_IRQ_BAD_PMP;
/*
* We must not change the port interrupt mask register if the
* port is marked frozen, the value in pp->intr_mask will be
* restored later when the port is thawed.
*
* Note that during initialization, the port is marked as
* frozen since the irq handler is not yet registered.
*/
if (!(ap->pflags & ATA_PFLAG_FROZEN))
writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
}
static void ahci_pmp_detach(struct ata_port *ap)
{
void __iomem *port_mmio = ahci_port_base(ap);
struct ahci_port_priv *pp = ap->private_data;
u32 cmd;
ahci_disable_fbs(ap);
cmd = readl(port_mmio + PORT_CMD);
cmd &= ~PORT_CMD_PMP;
writel(cmd, port_mmio + PORT_CMD);
pp->intr_mask &= ~PORT_IRQ_BAD_PMP;
/* see comment above in ahci_pmp_attach() */
if (!(ap->pflags & ATA_PFLAG_FROZEN))
writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
}
int ahci_port_resume(struct ata_port *ap)
{
ahci_power_up(ap);
ahci_start_port(ap);
if (sata_pmp_attached(ap))
ahci_pmp_attach(ap);
else
ahci_pmp_detach(ap);
return 0;
}
EXPORT_SYMBOL_GPL(ahci_port_resume);
#ifdef CONFIG_PM
static int ahci_port_suspend(struct ata_port *ap, pm_message_t mesg)
{
const char *emsg = NULL;
int rc;
rc = ahci_deinit_port(ap, &emsg);
if (rc == 0)
ahci_power_down(ap);
else {
ata_port_err(ap, "%s (%d)\n", emsg, rc);
ata_port_freeze(ap);
}
return rc;
}
#endif
static int ahci_port_start(struct ata_port *ap)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
struct device *dev = ap->host->dev;
struct ahci_port_priv *pp;
void *mem;
dma_addr_t mem_dma;
size_t dma_sz, rx_fis_sz;
pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
if (!pp)
return -ENOMEM;
/* check FBS capability */
if ((hpriv->cap & HOST_CAP_FBS) && sata_pmp_supported(ap)) {
void __iomem *port_mmio = ahci_port_base(ap);
u32 cmd = readl(port_mmio + PORT_CMD);
if (cmd & PORT_CMD_FBSCP)
pp->fbs_supported = true;
else if (hpriv->flags & AHCI_HFLAG_YES_FBS) {
dev_info(dev, "port %d can do FBS, forcing FBSCP\n",
ap->port_no);
pp->fbs_supported = true;
} else
dev_warn(dev, "port %d is not capable of FBS\n",
ap->port_no);
}
if (pp->fbs_supported) {
dma_sz = AHCI_PORT_PRIV_FBS_DMA_SZ;
rx_fis_sz = AHCI_RX_FIS_SZ * 16;
} else {
dma_sz = AHCI_PORT_PRIV_DMA_SZ;
rx_fis_sz = AHCI_RX_FIS_SZ;
}
mem = dmam_alloc_coherent(dev, dma_sz, &mem_dma, GFP_KERNEL);
if (!mem)
return -ENOMEM;
memset(mem, 0, dma_sz);
/*
* First item in chunk of DMA memory: 32-slot command table,
* 32 bytes each in size
*/
pp->cmd_slot = mem;
pp->cmd_slot_dma = mem_dma;
mem += AHCI_CMD_SLOT_SZ;
mem_dma += AHCI_CMD_SLOT_SZ;
/*
* Second item: Received-FIS area
*/
pp->rx_fis = mem;
pp->rx_fis_dma = mem_dma;
mem += rx_fis_sz;
mem_dma += rx_fis_sz;
/*
* Third item: data area for storing a single command
* and its scatter-gather table
*/
pp->cmd_tbl = mem;
pp->cmd_tbl_dma = mem_dma;
/*
* Save off initial list of interrupts to be enabled.
* This could be changed later
*/
pp->intr_mask = DEF_PORT_IRQ;
ap->private_data = pp;
/* engage engines, captain */
return ahci_port_resume(ap);
}
static void ahci_port_stop(struct ata_port *ap)
{
const char *emsg = NULL;
int rc;
/* de-initialize port */
rc = ahci_deinit_port(ap, &emsg);
if (rc)
ata_port_warn(ap, "%s (%d)\n", emsg, rc);
}
void ahci_print_info(struct ata_host *host, const char *scc_s)
{
struct ahci_host_priv *hpriv = host->private_data;
void __iomem *mmio = hpriv->mmio;
u32 vers, cap, cap2, impl, speed;
const char *speed_s;
vers = readl(mmio + HOST_VERSION);
cap = hpriv->cap;
cap2 = hpriv->cap2;
impl = hpriv->port_map;
speed = (cap >> 20) & 0xf;
if (speed == 1)
speed_s = "1.5";
else if (speed == 2)
speed_s = "3";
else if (speed == 3)
speed_s = "6";
else
speed_s = "?";
dev_info(host->dev,
"AHCI %02x%02x.%02x%02x "
"%u slots %u ports %s Gbps 0x%x impl %s mode\n"
,
(vers >> 24) & 0xff,
(vers >> 16) & 0xff,
(vers >> 8) & 0xff,
vers & 0xff,
((cap >> 8) & 0x1f) + 1,
(cap & 0x1f) + 1,
speed_s,
impl,
scc_s);
dev_info(host->dev,
"flags: "
"%s%s%s%s%s%s%s"
"%s%s%s%s%s%s%s"
"%s%s%s%s%s%s\n"
,
cap & HOST_CAP_64 ? "64bit " : "",
cap & HOST_CAP_NCQ ? "ncq " : "",
cap & HOST_CAP_SNTF ? "sntf " : "",
cap & HOST_CAP_MPS ? "ilck " : "",
cap & HOST_CAP_SSS ? "stag " : "",
cap & HOST_CAP_ALPM ? "pm " : "",
cap & HOST_CAP_LED ? "led " : "",
cap & HOST_CAP_CLO ? "clo " : "",
cap & HOST_CAP_ONLY ? "only " : "",
cap & HOST_CAP_PMP ? "pmp " : "",
cap & HOST_CAP_FBS ? "fbs " : "",
cap & HOST_CAP_PIO_MULTI ? "pio " : "",
cap & HOST_CAP_SSC ? "slum " : "",
cap & HOST_CAP_PART ? "part " : "",
cap & HOST_CAP_CCC ? "ccc " : "",
cap & HOST_CAP_EMS ? "ems " : "",
cap & HOST_CAP_SXS ? "sxs " : "",
cap2 & HOST_CAP2_APST ? "apst " : "",
cap2 & HOST_CAP2_NVMHCI ? "nvmp " : "",
cap2 & HOST_CAP2_BOH ? "boh " : ""
);
}
EXPORT_SYMBOL_GPL(ahci_print_info);
void ahci_set_em_messages(struct ahci_host_priv *hpriv,
struct ata_port_info *pi)
{
u8 messages;
void __iomem *mmio = hpriv->mmio;
u32 em_loc = readl(mmio + HOST_EM_LOC);
u32 em_ctl = readl(mmio + HOST_EM_CTL);
if (!ahci_em_messages || !(hpriv->cap & HOST_CAP_EMS))
return;
messages = (em_ctl & EM_CTRL_MSG_TYPE) >> 16;
if (messages) {
/* store em_loc */
hpriv->em_loc = ((em_loc >> 16) * 4);
hpriv->em_buf_sz = ((em_loc & 0xff) * 4);
hpriv->em_msg_type = messages;
pi->flags |= ATA_FLAG_EM;
if (!(em_ctl & EM_CTL_ALHD))
pi->flags |= ATA_FLAG_SW_ACTIVITY;
}
}
EXPORT_SYMBOL_GPL(ahci_set_em_messages);
MODULE_AUTHOR("Jeff Garzik");
MODULE_DESCRIPTION("Common AHCI SATA low-level routines");
MODULE_LICENSE("GPL");
| gpl-2.0 |
bensonhsu2013/diff_variant_i8160 | arch/x86/kvm/emulate.c | 462 | 90567 | /******************************************************************************
* emulate.c
*
* Generic x86 (32-bit and 64-bit) instruction decoder and emulator.
*
* Copyright (c) 2005 Keir Fraser
*
* Linux coding style, mod r/m decoder, segment base fixes, real-mode
* privileged instructions:
*
* Copyright (C) 2006 Qumranet
*
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
* From: xen-unstable 10676:af9809f51f81a3c43f276f00c81a52ef558afda4
*/
#ifndef __KERNEL__
#include <stdio.h>
#include <stdint.h>
#include <public/xen.h>
#define DPRINTF(_f, _a ...) printf(_f , ## _a)
#else
#include <linux/kvm_host.h>
#include "kvm_cache_regs.h"
#define DPRINTF(x...) do {} while (0)
#endif
#include <linux/module.h>
#include <asm/kvm_emulate.h>
#include "x86.h"
#include "tss.h"
/*
* Opcode effective-address decode tables.
* Note that we only emulate instructions that have at least one memory
* operand (excluding implicit stack references). We assume that stack
* references and instruction fetches will never occur in special memory
* areas that require emulation. So, for example, 'mov <imm>,<reg>' need
* not be handled.
*/
/* Operand sizes: 8-bit operands or specified/overridden size. */
#define ByteOp (1<<0) /* 8-bit operands. */
/* Destination operand type. */
#define ImplicitOps (1<<1) /* Implicit in opcode. No generic decode. */
#define DstReg (2<<1) /* Register operand. */
#define DstMem (3<<1) /* Memory operand. */
#define DstAcc (4<<1) /* Destination Accumulator */
#define DstDI (5<<1) /* Destination is in ES:(E)DI */
#define DstMem64 (6<<1) /* 64bit memory operand */
#define DstMask (7<<1)
/* Source operand type. */
#define SrcNone (0<<4) /* No source operand. */
#define SrcImplicit (0<<4) /* Source operand is implicit in the opcode. */
#define SrcReg (1<<4) /* Register operand. */
#define SrcMem (2<<4) /* Memory operand. */
#define SrcMem16 (3<<4) /* Memory operand (16-bit). */
#define SrcMem32 (4<<4) /* Memory operand (32-bit). */
#define SrcImm (5<<4) /* Immediate operand. */
#define SrcImmByte (6<<4) /* 8-bit sign-extended immediate operand. */
#define SrcOne (7<<4) /* Implied '1' */
#define SrcImmUByte (8<<4) /* 8-bit unsigned immediate operand. */
#define SrcImmU (9<<4) /* Immediate operand, unsigned */
#define SrcSI (0xa<<4) /* Source is in the DS:RSI */
#define SrcMask (0xf<<4)
/* Generic ModRM decode. */
#define ModRM (1<<8)
/* Destination is only written; never read. */
#define Mov (1<<9)
#define BitOp (1<<10)
#define MemAbs (1<<11) /* Memory operand is absolute displacement */
#define String (1<<12) /* String instruction (rep capable) */
#define Stack (1<<13) /* Stack instruction (push/pop) */
#define Group (1<<14) /* Bits 3:5 of modrm byte extend opcode */
#define GroupDual (1<<15) /* Alternate decoding of mod == 3 */
#define GroupMask 0xff /* Group number stored in bits 0:7 */
/* Misc flags */
#define Lock (1<<26) /* lock prefix is allowed for the instruction */
#define Priv (1<<27) /* instruction generates #GP if current CPL != 0 */
#define No64 (1<<28)
/* Source 2 operand type */
#define Src2None (0<<29)
#define Src2CL (1<<29)
#define Src2ImmByte (2<<29)
#define Src2One (3<<29)
#define Src2Imm16 (4<<29)
#define Src2Mem16 (5<<29) /* Used for Ep encoding. First argument has to be
in memory and second argument is located
immediately after the first one in memory. */
#define Src2Mask (7<<29)
enum {
Group1_80, Group1_81, Group1_82, Group1_83,
Group1A, Group3_Byte, Group3, Group4, Group5, Group7,
Group8, Group9,
};
static u32 opcode_table[256] = {
/* 0x00 - 0x07 */
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
ByteOp | DstReg | SrcMem | ModRM, DstReg | SrcMem | ModRM,
ByteOp | DstAcc | SrcImm, DstAcc | SrcImm,
ImplicitOps | Stack | No64, ImplicitOps | Stack | No64,
/* 0x08 - 0x0F */
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
ByteOp | DstReg | SrcMem | ModRM, DstReg | SrcMem | ModRM,
ByteOp | DstAcc | SrcImm, DstAcc | SrcImm,
ImplicitOps | Stack | No64, 0,
/* 0x10 - 0x17 */
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
ByteOp | DstReg | SrcMem | ModRM, DstReg | SrcMem | ModRM,
ByteOp | DstAcc | SrcImm, DstAcc | SrcImm,
ImplicitOps | Stack | No64, ImplicitOps | Stack | No64,
/* 0x18 - 0x1F */
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
ByteOp | DstReg | SrcMem | ModRM, DstReg | SrcMem | ModRM,
ByteOp | DstAcc | SrcImm, DstAcc | SrcImm,
ImplicitOps | Stack | No64, ImplicitOps | Stack | No64,
/* 0x20 - 0x27 */
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
ByteOp | DstReg | SrcMem | ModRM, DstReg | SrcMem | ModRM,
DstAcc | SrcImmByte, DstAcc | SrcImm, 0, 0,
/* 0x28 - 0x2F */
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
ByteOp | DstReg | SrcMem | ModRM, DstReg | SrcMem | ModRM,
0, 0, 0, 0,
/* 0x30 - 0x37 */
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
ByteOp | DstReg | SrcMem | ModRM, DstReg | SrcMem | ModRM,
0, 0, 0, 0,
/* 0x38 - 0x3F */
ByteOp | DstMem | SrcReg | ModRM, DstMem | SrcReg | ModRM,
ByteOp | DstReg | SrcMem | ModRM, DstReg | SrcMem | ModRM,
ByteOp | DstAcc | SrcImm, DstAcc | SrcImm,
0, 0,
/* 0x40 - 0x47 */
DstReg, DstReg, DstReg, DstReg, DstReg, DstReg, DstReg, DstReg,
/* 0x48 - 0x4F */
DstReg, DstReg, DstReg, DstReg, DstReg, DstReg, DstReg, DstReg,
/* 0x50 - 0x57 */
SrcReg | Stack, SrcReg | Stack, SrcReg | Stack, SrcReg | Stack,
SrcReg | Stack, SrcReg | Stack, SrcReg | Stack, SrcReg | Stack,
/* 0x58 - 0x5F */
DstReg | Stack, DstReg | Stack, DstReg | Stack, DstReg | Stack,
DstReg | Stack, DstReg | Stack, DstReg | Stack, DstReg | Stack,
/* 0x60 - 0x67 */
ImplicitOps | Stack | No64, ImplicitOps | Stack | No64,
0, DstReg | SrcMem32 | ModRM | Mov /* movsxd (x86/64) */ ,
0, 0, 0, 0,
/* 0x68 - 0x6F */
SrcImm | Mov | Stack, 0, SrcImmByte | Mov | Stack, 0,
DstDI | ByteOp | Mov | String, DstDI | Mov | String, /* insb, insw/insd */
SrcSI | ByteOp | ImplicitOps | String, SrcSI | ImplicitOps | String, /* outsb, outsw/outsd */
/* 0x70 - 0x77 */
SrcImmByte, SrcImmByte, SrcImmByte, SrcImmByte,
SrcImmByte, SrcImmByte, SrcImmByte, SrcImmByte,
/* 0x78 - 0x7F */
SrcImmByte, SrcImmByte, SrcImmByte, SrcImmByte,
SrcImmByte, SrcImmByte, SrcImmByte, SrcImmByte,
/* 0x80 - 0x87 */
Group | Group1_80, Group | Group1_81,
Group | Group1_82, Group | Group1_83,
ByteOp | DstMem | SrcReg | ModRM, DstMem | SrcReg | ModRM,
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
/* 0x88 - 0x8F */
ByteOp | DstMem | SrcReg | ModRM | Mov, DstMem | SrcReg | ModRM | Mov,
ByteOp | DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
DstMem | SrcReg | ModRM | Mov, ModRM | DstReg,
DstReg | SrcMem | ModRM | Mov, Group | Group1A,
/* 0x90 - 0x97 */
DstReg, DstReg, DstReg, DstReg, DstReg, DstReg, DstReg, DstReg,
/* 0x98 - 0x9F */
0, 0, SrcImm | Src2Imm16 | No64, 0,
ImplicitOps | Stack, ImplicitOps | Stack, 0, 0,
/* 0xA0 - 0xA7 */
ByteOp | DstReg | SrcMem | Mov | MemAbs, DstReg | SrcMem | Mov | MemAbs,
ByteOp | DstMem | SrcReg | Mov | MemAbs, DstMem | SrcReg | Mov | MemAbs,
ByteOp | SrcSI | DstDI | Mov | String, SrcSI | DstDI | Mov | String,
ByteOp | SrcSI | DstDI | String, SrcSI | DstDI | String,
/* 0xA8 - 0xAF */
0, 0, ByteOp | DstDI | Mov | String, DstDI | Mov | String,
ByteOp | SrcSI | DstAcc | Mov | String, SrcSI | DstAcc | Mov | String,
ByteOp | DstDI | String, DstDI | String,
/* 0xB0 - 0xB7 */
ByteOp | DstReg | SrcImm | Mov, ByteOp | DstReg | SrcImm | Mov,
ByteOp | DstReg | SrcImm | Mov, ByteOp | DstReg | SrcImm | Mov,
ByteOp | DstReg | SrcImm | Mov, ByteOp | DstReg | SrcImm | Mov,
ByteOp | DstReg | SrcImm | Mov, ByteOp | DstReg | SrcImm | Mov,
/* 0xB8 - 0xBF */
DstReg | SrcImm | Mov, DstReg | SrcImm | Mov,
DstReg | SrcImm | Mov, DstReg | SrcImm | Mov,
DstReg | SrcImm | Mov, DstReg | SrcImm | Mov,
DstReg | SrcImm | Mov, DstReg | SrcImm | Mov,
/* 0xC0 - 0xC7 */
ByteOp | DstMem | SrcImm | ModRM, DstMem | SrcImmByte | ModRM,
0, ImplicitOps | Stack, 0, 0,
ByteOp | DstMem | SrcImm | ModRM | Mov, DstMem | SrcImm | ModRM | Mov,
/* 0xC8 - 0xCF */
0, 0, 0, ImplicitOps | Stack,
ImplicitOps, SrcImmByte, ImplicitOps | No64, ImplicitOps,
/* 0xD0 - 0xD7 */
ByteOp | DstMem | SrcImplicit | ModRM, DstMem | SrcImplicit | ModRM,
ByteOp | DstMem | SrcImplicit | ModRM, DstMem | SrcImplicit | ModRM,
0, 0, 0, 0,
/* 0xD8 - 0xDF */
0, 0, 0, 0, 0, 0, 0, 0,
/* 0xE0 - 0xE7 */
0, 0, 0, 0,
ByteOp | SrcImmUByte | DstAcc, SrcImmUByte | DstAcc,
ByteOp | SrcImmUByte | DstAcc, SrcImmUByte | DstAcc,
/* 0xE8 - 0xEF */
SrcImm | Stack, SrcImm | ImplicitOps,
SrcImmU | Src2Imm16 | No64, SrcImmByte | ImplicitOps,
SrcNone | ByteOp | DstAcc, SrcNone | DstAcc,
SrcNone | ByteOp | DstAcc, SrcNone | DstAcc,
/* 0xF0 - 0xF7 */
0, 0, 0, 0,
ImplicitOps | Priv, ImplicitOps, Group | Group3_Byte, Group | Group3,
/* 0xF8 - 0xFF */
ImplicitOps, 0, ImplicitOps, ImplicitOps,
ImplicitOps, ImplicitOps, Group | Group4, Group | Group5,
};
static u32 twobyte_table[256] = {
/* 0x00 - 0x0F */
0, Group | GroupDual | Group7, 0, 0,
0, ImplicitOps, ImplicitOps | Priv, 0,
ImplicitOps | Priv, ImplicitOps | Priv, 0, 0,
0, ImplicitOps | ModRM, 0, 0,
/* 0x10 - 0x1F */
0, 0, 0, 0, 0, 0, 0, 0, ImplicitOps | ModRM, 0, 0, 0, 0, 0, 0, 0,
/* 0x20 - 0x2F */
ModRM | ImplicitOps | Priv, ModRM | Priv,
ModRM | ImplicitOps | Priv, ModRM | Priv,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
/* 0x30 - 0x3F */
ImplicitOps | Priv, 0, ImplicitOps | Priv, 0,
ImplicitOps, ImplicitOps | Priv, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
/* 0x40 - 0x47 */
DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
/* 0x48 - 0x4F */
DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
DstReg | SrcMem | ModRM | Mov, DstReg | SrcMem | ModRM | Mov,
/* 0x50 - 0x5F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0x60 - 0x6F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0x70 - 0x7F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0x80 - 0x8F */
SrcImm, SrcImm, SrcImm, SrcImm, SrcImm, SrcImm, SrcImm, SrcImm,
SrcImm, SrcImm, SrcImm, SrcImm, SrcImm, SrcImm, SrcImm, SrcImm,
/* 0x90 - 0x9F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0xA0 - 0xA7 */
ImplicitOps | Stack, ImplicitOps | Stack,
0, DstMem | SrcReg | ModRM | BitOp,
DstMem | SrcReg | Src2ImmByte | ModRM,
DstMem | SrcReg | Src2CL | ModRM, 0, 0,
/* 0xA8 - 0xAF */
ImplicitOps | Stack, ImplicitOps | Stack,
0, DstMem | SrcReg | ModRM | BitOp | Lock,
DstMem | SrcReg | Src2ImmByte | ModRM,
DstMem | SrcReg | Src2CL | ModRM,
ModRM, 0,
/* 0xB0 - 0xB7 */
ByteOp | DstMem | SrcReg | ModRM | Lock, DstMem | SrcReg | ModRM | Lock,
0, DstMem | SrcReg | ModRM | BitOp | Lock,
0, 0, ByteOp | DstReg | SrcMem | ModRM | Mov,
DstReg | SrcMem16 | ModRM | Mov,
/* 0xB8 - 0xBF */
0, 0,
Group | Group8, DstMem | SrcReg | ModRM | BitOp | Lock,
0, 0, ByteOp | DstReg | SrcMem | ModRM | Mov,
DstReg | SrcMem16 | ModRM | Mov,
/* 0xC0 - 0xCF */
0, 0, 0, DstMem | SrcReg | ModRM | Mov,
0, 0, 0, Group | GroupDual | Group9,
0, 0, 0, 0, 0, 0, 0, 0,
/* 0xD0 - 0xDF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0xE0 - 0xEF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 0xF0 - 0xFF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static u32 group_table[] = {
[Group1_80*8] =
ByteOp | DstMem | SrcImm | ModRM | Lock,
ByteOp | DstMem | SrcImm | ModRM | Lock,
ByteOp | DstMem | SrcImm | ModRM | Lock,
ByteOp | DstMem | SrcImm | ModRM | Lock,
ByteOp | DstMem | SrcImm | ModRM | Lock,
ByteOp | DstMem | SrcImm | ModRM | Lock,
ByteOp | DstMem | SrcImm | ModRM | Lock,
ByteOp | DstMem | SrcImm | ModRM,
[Group1_81*8] =
DstMem | SrcImm | ModRM | Lock,
DstMem | SrcImm | ModRM | Lock,
DstMem | SrcImm | ModRM | Lock,
DstMem | SrcImm | ModRM | Lock,
DstMem | SrcImm | ModRM | Lock,
DstMem | SrcImm | ModRM | Lock,
DstMem | SrcImm | ModRM | Lock,
DstMem | SrcImm | ModRM,
[Group1_82*8] =
ByteOp | DstMem | SrcImm | ModRM | No64 | Lock,
ByteOp | DstMem | SrcImm | ModRM | No64 | Lock,
ByteOp | DstMem | SrcImm | ModRM | No64 | Lock,
ByteOp | DstMem | SrcImm | ModRM | No64 | Lock,
ByteOp | DstMem | SrcImm | ModRM | No64 | Lock,
ByteOp | DstMem | SrcImm | ModRM | No64 | Lock,
ByteOp | DstMem | SrcImm | ModRM | No64 | Lock,
ByteOp | DstMem | SrcImm | ModRM | No64,
[Group1_83*8] =
DstMem | SrcImmByte | ModRM | Lock,
DstMem | SrcImmByte | ModRM | Lock,
DstMem | SrcImmByte | ModRM | Lock,
DstMem | SrcImmByte | ModRM | Lock,
DstMem | SrcImmByte | ModRM | Lock,
DstMem | SrcImmByte | ModRM | Lock,
DstMem | SrcImmByte | ModRM | Lock,
DstMem | SrcImmByte | ModRM,
[Group1A*8] =
DstMem | SrcNone | ModRM | Mov | Stack, 0, 0, 0, 0, 0, 0, 0,
[Group3_Byte*8] =
ByteOp | SrcImm | DstMem | ModRM, 0,
ByteOp | DstMem | SrcNone | ModRM, ByteOp | DstMem | SrcNone | ModRM,
0, 0, 0, 0,
[Group3*8] =
DstMem | SrcImm | ModRM, 0,
DstMem | SrcNone | ModRM, DstMem | SrcNone | ModRM,
0, 0, 0, 0,
[Group4*8] =
ByteOp | DstMem | SrcNone | ModRM | Lock, ByteOp | DstMem | SrcNone | ModRM | Lock,
0, 0, 0, 0, 0, 0,
[Group5*8] =
DstMem | SrcNone | ModRM | Lock, DstMem | SrcNone | ModRM | Lock,
SrcMem | ModRM | Stack, 0,
SrcMem | ModRM | Stack, SrcMem | ModRM | Src2Mem16 | ImplicitOps,
SrcMem | ModRM | Stack, 0,
[Group7*8] =
0, 0, ModRM | SrcMem | Priv, ModRM | SrcMem | Priv,
SrcNone | ModRM | DstMem | Mov, 0,
SrcMem16 | ModRM | Mov | Priv, SrcMem | ModRM | ByteOp | Priv,
[Group8*8] =
0, 0, 0, 0,
DstMem | SrcImmByte | ModRM, DstMem | SrcImmByte | ModRM | Lock,
DstMem | SrcImmByte | ModRM | Lock, DstMem | SrcImmByte | ModRM | Lock,
[Group9*8] =
0, DstMem64 | ModRM | Lock, 0, 0, 0, 0, 0, 0,
};
static u32 group2_table[] = {
[Group7*8] =
SrcNone | ModRM | Priv, 0, 0, SrcNone | ModRM | Priv,
SrcNone | ModRM | DstMem | Mov, 0,
SrcMem16 | ModRM | Mov | Priv, 0,
[Group9*8] =
0, 0, 0, 0, 0, 0, 0, 0,
};
/* EFLAGS bit definitions. */
#define EFLG_ID (1<<21)
#define EFLG_VIP (1<<20)
#define EFLG_VIF (1<<19)
#define EFLG_AC (1<<18)
#define EFLG_VM (1<<17)
#define EFLG_RF (1<<16)
#define EFLG_IOPL (3<<12)
#define EFLG_NT (1<<14)
#define EFLG_OF (1<<11)
#define EFLG_DF (1<<10)
#define EFLG_IF (1<<9)
#define EFLG_TF (1<<8)
#define EFLG_SF (1<<7)
#define EFLG_ZF (1<<6)
#define EFLG_AF (1<<4)
#define EFLG_PF (1<<2)
#define EFLG_CF (1<<0)
/*
* Instruction emulation:
* Most instructions are emulated directly via a fragment of inline assembly
* code. This allows us to save/restore EFLAGS and thus very easily pick up
* any modified flags.
*/
#if defined(CONFIG_X86_64)
#define _LO32 "k" /* force 32-bit operand */
#define _STK "%%rsp" /* stack pointer */
#elif defined(__i386__)
#define _LO32 "" /* force 32-bit operand */
#define _STK "%%esp" /* stack pointer */
#endif
/*
* These EFLAGS bits are restored from saved value during emulation, and
* any changes are written back to the saved value after emulation.
*/
#define EFLAGS_MASK (EFLG_OF|EFLG_SF|EFLG_ZF|EFLG_AF|EFLG_PF|EFLG_CF)
/* Before executing instruction: restore necessary bits in EFLAGS. */
#define _PRE_EFLAGS(_sav, _msk, _tmp) \
/* EFLAGS = (_sav & _msk) | (EFLAGS & ~_msk); _sav &= ~_msk; */ \
"movl %"_sav",%"_LO32 _tmp"; " \
"push %"_tmp"; " \
"push %"_tmp"; " \
"movl %"_msk",%"_LO32 _tmp"; " \
"andl %"_LO32 _tmp",("_STK"); " \
"pushf; " \
"notl %"_LO32 _tmp"; " \
"andl %"_LO32 _tmp",("_STK"); " \
"andl %"_LO32 _tmp","__stringify(BITS_PER_LONG/4)"("_STK"); " \
"pop %"_tmp"; " \
"orl %"_LO32 _tmp",("_STK"); " \
"popf; " \
"pop %"_sav"; "
/* After executing instruction: write-back necessary bits in EFLAGS. */
#define _POST_EFLAGS(_sav, _msk, _tmp) \
/* _sav |= EFLAGS & _msk; */ \
"pushf; " \
"pop %"_tmp"; " \
"andl %"_msk",%"_LO32 _tmp"; " \
"orl %"_LO32 _tmp",%"_sav"; "
#ifdef CONFIG_X86_64
#define ON64(x) x
#else
#define ON64(x)
#endif
#define ____emulate_2op(_op, _src, _dst, _eflags, _x, _y, _suffix) \
do { \
__asm__ __volatile__ ( \
_PRE_EFLAGS("0", "4", "2") \
_op _suffix " %"_x"3,%1; " \
_POST_EFLAGS("0", "4", "2") \
: "=m" (_eflags), "=m" ((_dst).val), \
"=&r" (_tmp) \
: _y ((_src).val), "i" (EFLAGS_MASK)); \
} while (0)
/* Raw emulation: instruction has two explicit operands. */
#define __emulate_2op_nobyte(_op,_src,_dst,_eflags,_wx,_wy,_lx,_ly,_qx,_qy) \
do { \
unsigned long _tmp; \
\
switch ((_dst).bytes) { \
case 2: \
____emulate_2op(_op,_src,_dst,_eflags,_wx,_wy,"w"); \
break; \
case 4: \
____emulate_2op(_op,_src,_dst,_eflags,_lx,_ly,"l"); \
break; \
case 8: \
ON64(____emulate_2op(_op,_src,_dst,_eflags,_qx,_qy,"q")); \
break; \
} \
} while (0)
#define __emulate_2op(_op,_src,_dst,_eflags,_bx,_by,_wx,_wy,_lx,_ly,_qx,_qy) \
do { \
unsigned long _tmp; \
switch ((_dst).bytes) { \
case 1: \
____emulate_2op(_op,_src,_dst,_eflags,_bx,_by,"b"); \
break; \
default: \
__emulate_2op_nobyte(_op, _src, _dst, _eflags, \
_wx, _wy, _lx, _ly, _qx, _qy); \
break; \
} \
} while (0)
/* Source operand is byte-sized and may be restricted to just %cl. */
#define emulate_2op_SrcB(_op, _src, _dst, _eflags) \
__emulate_2op(_op, _src, _dst, _eflags, \
"b", "c", "b", "c", "b", "c", "b", "c")
/* Source operand is byte, word, long or quad sized. */
#define emulate_2op_SrcV(_op, _src, _dst, _eflags) \
__emulate_2op(_op, _src, _dst, _eflags, \
"b", "q", "w", "r", _LO32, "r", "", "r")
/* Source operand is word, long or quad sized. */
#define emulate_2op_SrcV_nobyte(_op, _src, _dst, _eflags) \
__emulate_2op_nobyte(_op, _src, _dst, _eflags, \
"w", "r", _LO32, "r", "", "r")
/* Instruction has three operands and one operand is stored in ECX register */
#define __emulate_2op_cl(_op, _cl, _src, _dst, _eflags, _suffix, _type) \
do { \
unsigned long _tmp; \
_type _clv = (_cl).val; \
_type _srcv = (_src).val; \
_type _dstv = (_dst).val; \
\
__asm__ __volatile__ ( \
_PRE_EFLAGS("0", "5", "2") \
_op _suffix " %4,%1 \n" \
_POST_EFLAGS("0", "5", "2") \
: "=m" (_eflags), "+r" (_dstv), "=&r" (_tmp) \
: "c" (_clv) , "r" (_srcv), "i" (EFLAGS_MASK) \
); \
\
(_cl).val = (unsigned long) _clv; \
(_src).val = (unsigned long) _srcv; \
(_dst).val = (unsigned long) _dstv; \
} while (0)
#define emulate_2op_cl(_op, _cl, _src, _dst, _eflags) \
do { \
switch ((_dst).bytes) { \
case 2: \
__emulate_2op_cl(_op, _cl, _src, _dst, _eflags, \
"w", unsigned short); \
break; \
case 4: \
__emulate_2op_cl(_op, _cl, _src, _dst, _eflags, \
"l", unsigned int); \
break; \
case 8: \
ON64(__emulate_2op_cl(_op, _cl, _src, _dst, _eflags, \
"q", unsigned long)); \
break; \
} \
} while (0)
#define __emulate_1op(_op, _dst, _eflags, _suffix) \
do { \
unsigned long _tmp; \
\
__asm__ __volatile__ ( \
_PRE_EFLAGS("0", "3", "2") \
_op _suffix " %1; " \
_POST_EFLAGS("0", "3", "2") \
: "=m" (_eflags), "+m" ((_dst).val), \
"=&r" (_tmp) \
: "i" (EFLAGS_MASK)); \
} while (0)
/* Instruction has only one explicit operand (no source operand). */
#define emulate_1op(_op, _dst, _eflags) \
do { \
switch ((_dst).bytes) { \
case 1: __emulate_1op(_op, _dst, _eflags, "b"); break; \
case 2: __emulate_1op(_op, _dst, _eflags, "w"); break; \
case 4: __emulate_1op(_op, _dst, _eflags, "l"); break; \
case 8: ON64(__emulate_1op(_op, _dst, _eflags, "q")); break; \
} \
} while (0)
/* Fetch next part of the instruction being emulated. */
#define insn_fetch(_type, _size, _eip) \
({ unsigned long _x; \
rc = do_insn_fetch(ctxt, ops, (_eip), &_x, (_size)); \
if (rc != X86EMUL_CONTINUE) \
goto done; \
(_eip) += (_size); \
(_type)_x; \
})
static inline unsigned long ad_mask(struct decode_cache *c)
{
return (1UL << (c->ad_bytes << 3)) - 1;
}
/* Access/update address held in a register, based on addressing mode. */
static inline unsigned long
address_mask(struct decode_cache *c, unsigned long reg)
{
if (c->ad_bytes == sizeof(unsigned long))
return reg;
else
return reg & ad_mask(c);
}
static inline unsigned long
register_address(struct decode_cache *c, unsigned long base, unsigned long reg)
{
return base + address_mask(c, reg);
}
static inline void
register_address_increment(struct decode_cache *c, unsigned long *reg, int inc)
{
if (c->ad_bytes == sizeof(unsigned long))
*reg += inc;
else
*reg = (*reg & ~ad_mask(c)) | ((*reg + inc) & ad_mask(c));
}
static inline void jmp_rel(struct decode_cache *c, int rel)
{
register_address_increment(c, &c->eip, rel);
}
static void set_seg_override(struct decode_cache *c, int seg)
{
c->has_seg_override = true;
c->seg_override = seg;
}
static unsigned long seg_base(struct x86_emulate_ctxt *ctxt, int seg)
{
if (ctxt->mode == X86EMUL_MODE_PROT64 && seg < VCPU_SREG_FS)
return 0;
return kvm_x86_ops->get_segment_base(ctxt->vcpu, seg);
}
static unsigned long seg_override_base(struct x86_emulate_ctxt *ctxt,
struct decode_cache *c)
{
if (!c->has_seg_override)
return 0;
return seg_base(ctxt, c->seg_override);
}
static unsigned long es_base(struct x86_emulate_ctxt *ctxt)
{
return seg_base(ctxt, VCPU_SREG_ES);
}
static unsigned long ss_base(struct x86_emulate_ctxt *ctxt)
{
return seg_base(ctxt, VCPU_SREG_SS);
}
static int do_fetch_insn_byte(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
unsigned long eip, u8 *dest)
{
struct fetch_cache *fc = &ctxt->decode.fetch;
int rc;
int size, cur_size;
if (eip == fc->end) {
cur_size = fc->end - fc->start;
size = min(15UL - cur_size, PAGE_SIZE - offset_in_page(eip));
rc = ops->fetch(ctxt->cs_base + eip, fc->data + cur_size,
size, ctxt->vcpu, NULL);
if (rc != X86EMUL_CONTINUE)
return rc;
fc->end += size;
}
*dest = fc->data[eip - fc->start];
return X86EMUL_CONTINUE;
}
static int do_insn_fetch(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
unsigned long eip, void *dest, unsigned size)
{
int rc;
/* x86 instructions are limited to 15 bytes. */
if (eip + size - ctxt->eip > 15)
return X86EMUL_UNHANDLEABLE;
while (size--) {
rc = do_fetch_insn_byte(ctxt, ops, eip++, dest++);
if (rc != X86EMUL_CONTINUE)
return rc;
}
return X86EMUL_CONTINUE;
}
/*
* Given the 'reg' portion of a ModRM byte, and a register block, return a
* pointer into the block that addresses the relevant register.
* @highbyte_regs specifies whether to decode AH,CH,DH,BH.
*/
static void *decode_register(u8 modrm_reg, unsigned long *regs,
int highbyte_regs)
{
void *p;
p = ®s[modrm_reg];
if (highbyte_regs && modrm_reg >= 4 && modrm_reg < 8)
p = (unsigned char *)®s[modrm_reg & 3] + 1;
return p;
}
static int read_descriptor(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
void *ptr,
u16 *size, unsigned long *address, int op_bytes)
{
int rc;
if (op_bytes == 2)
op_bytes = 3;
*address = 0;
rc = ops->read_std((unsigned long)ptr, (unsigned long *)size, 2,
ctxt->vcpu, NULL);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = ops->read_std((unsigned long)ptr + 2, address, op_bytes,
ctxt->vcpu, NULL);
return rc;
}
static int test_cc(unsigned int condition, unsigned int flags)
{
int rc = 0;
switch ((condition & 15) >> 1) {
case 0: /* o */
rc |= (flags & EFLG_OF);
break;
case 1: /* b/c/nae */
rc |= (flags & EFLG_CF);
break;
case 2: /* z/e */
rc |= (flags & EFLG_ZF);
break;
case 3: /* be/na */
rc |= (flags & (EFLG_CF|EFLG_ZF));
break;
case 4: /* s */
rc |= (flags & EFLG_SF);
break;
case 5: /* p/pe */
rc |= (flags & EFLG_PF);
break;
case 7: /* le/ng */
rc |= (flags & EFLG_ZF);
/* fall through */
case 6: /* l/nge */
rc |= (!(flags & EFLG_SF) != !(flags & EFLG_OF));
break;
}
/* Odd condition identifiers (lsb == 1) have inverted sense. */
return (!!rc ^ (condition & 1));
}
static void decode_register_operand(struct operand *op,
struct decode_cache *c,
int inhibit_bytereg)
{
unsigned reg = c->modrm_reg;
int highbyte_regs = c->rex_prefix == 0;
if (!(c->d & ModRM))
reg = (c->b & 7) | ((c->rex_prefix & 1) << 3);
op->type = OP_REG;
if ((c->d & ByteOp) && !inhibit_bytereg) {
op->ptr = decode_register(reg, c->regs, highbyte_regs);
op->val = *(u8 *)op->ptr;
op->bytes = 1;
} else {
op->ptr = decode_register(reg, c->regs, 0);
op->bytes = c->op_bytes;
switch (op->bytes) {
case 2:
op->val = *(u16 *)op->ptr;
break;
case 4:
op->val = *(u32 *)op->ptr;
break;
case 8:
op->val = *(u64 *) op->ptr;
break;
}
}
op->orig_val = op->val;
}
static int decode_modrm(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
u8 sib;
int index_reg = 0, base_reg = 0, scale;
int rc = X86EMUL_CONTINUE;
if (c->rex_prefix) {
c->modrm_reg = (c->rex_prefix & 4) << 1; /* REX.R */
index_reg = (c->rex_prefix & 2) << 2; /* REX.X */
c->modrm_rm = base_reg = (c->rex_prefix & 1) << 3; /* REG.B */
}
c->modrm = insn_fetch(u8, 1, c->eip);
c->modrm_mod |= (c->modrm & 0xc0) >> 6;
c->modrm_reg |= (c->modrm & 0x38) >> 3;
c->modrm_rm |= (c->modrm & 0x07);
c->modrm_ea = 0;
c->use_modrm_ea = 1;
if (c->modrm_mod == 3) {
c->modrm_ptr = decode_register(c->modrm_rm,
c->regs, c->d & ByteOp);
c->modrm_val = *(unsigned long *)c->modrm_ptr;
return rc;
}
if (c->ad_bytes == 2) {
unsigned bx = c->regs[VCPU_REGS_RBX];
unsigned bp = c->regs[VCPU_REGS_RBP];
unsigned si = c->regs[VCPU_REGS_RSI];
unsigned di = c->regs[VCPU_REGS_RDI];
/* 16-bit ModR/M decode. */
switch (c->modrm_mod) {
case 0:
if (c->modrm_rm == 6)
c->modrm_ea += insn_fetch(u16, 2, c->eip);
break;
case 1:
c->modrm_ea += insn_fetch(s8, 1, c->eip);
break;
case 2:
c->modrm_ea += insn_fetch(u16, 2, c->eip);
break;
}
switch (c->modrm_rm) {
case 0:
c->modrm_ea += bx + si;
break;
case 1:
c->modrm_ea += bx + di;
break;
case 2:
c->modrm_ea += bp + si;
break;
case 3:
c->modrm_ea += bp + di;
break;
case 4:
c->modrm_ea += si;
break;
case 5:
c->modrm_ea += di;
break;
case 6:
if (c->modrm_mod != 0)
c->modrm_ea += bp;
break;
case 7:
c->modrm_ea += bx;
break;
}
if (c->modrm_rm == 2 || c->modrm_rm == 3 ||
(c->modrm_rm == 6 && c->modrm_mod != 0))
if (!c->has_seg_override)
set_seg_override(c, VCPU_SREG_SS);
c->modrm_ea = (u16)c->modrm_ea;
} else {
/* 32/64-bit ModR/M decode. */
if ((c->modrm_rm & 7) == 4) {
sib = insn_fetch(u8, 1, c->eip);
index_reg |= (sib >> 3) & 7;
base_reg |= sib & 7;
scale = sib >> 6;
if ((base_reg & 7) == 5 && c->modrm_mod == 0)
c->modrm_ea += insn_fetch(s32, 4, c->eip);
else
c->modrm_ea += c->regs[base_reg];
if (index_reg != 4)
c->modrm_ea += c->regs[index_reg] << scale;
} else if ((c->modrm_rm & 7) == 5 && c->modrm_mod == 0) {
if (ctxt->mode == X86EMUL_MODE_PROT64)
c->rip_relative = 1;
} else
c->modrm_ea += c->regs[c->modrm_rm];
switch (c->modrm_mod) {
case 0:
if (c->modrm_rm == 5)
c->modrm_ea += insn_fetch(s32, 4, c->eip);
break;
case 1:
c->modrm_ea += insn_fetch(s8, 1, c->eip);
break;
case 2:
c->modrm_ea += insn_fetch(s32, 4, c->eip);
break;
}
}
done:
return rc;
}
static int decode_abs(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
int rc = X86EMUL_CONTINUE;
switch (c->ad_bytes) {
case 2:
c->modrm_ea = insn_fetch(u16, 2, c->eip);
break;
case 4:
c->modrm_ea = insn_fetch(u32, 4, c->eip);
break;
case 8:
c->modrm_ea = insn_fetch(u64, 8, c->eip);
break;
}
done:
return rc;
}
int
x86_decode_insn(struct x86_emulate_ctxt *ctxt, struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
int rc = X86EMUL_CONTINUE;
int mode = ctxt->mode;
int def_op_bytes, def_ad_bytes, group;
/* we cannot decode insn before we complete previous rep insn */
WARN_ON(ctxt->restart);
/* Shadow copy of register state. Committed on successful emulation. */
memset(c, 0, sizeof(struct decode_cache));
c->eip = ctxt->eip;
c->fetch.start = c->fetch.end = c->eip;
ctxt->cs_base = seg_base(ctxt, VCPU_SREG_CS);
memcpy(c->regs, ctxt->vcpu->arch.regs, sizeof c->regs);
switch (mode) {
case X86EMUL_MODE_REAL:
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
def_op_bytes = def_ad_bytes = 2;
break;
case X86EMUL_MODE_PROT32:
def_op_bytes = def_ad_bytes = 4;
break;
#ifdef CONFIG_X86_64
case X86EMUL_MODE_PROT64:
def_op_bytes = 4;
def_ad_bytes = 8;
break;
#endif
default:
return -1;
}
c->op_bytes = def_op_bytes;
c->ad_bytes = def_ad_bytes;
/* Legacy prefixes. */
for (;;) {
switch (c->b = insn_fetch(u8, 1, c->eip)) {
case 0x66: /* operand-size override */
/* switch between 2/4 bytes */
c->op_bytes = def_op_bytes ^ 6;
break;
case 0x67: /* address-size override */
if (mode == X86EMUL_MODE_PROT64)
/* switch between 4/8 bytes */
c->ad_bytes = def_ad_bytes ^ 12;
else
/* switch between 2/4 bytes */
c->ad_bytes = def_ad_bytes ^ 6;
break;
case 0x26: /* ES override */
case 0x2e: /* CS override */
case 0x36: /* SS override */
case 0x3e: /* DS override */
set_seg_override(c, (c->b >> 3) & 3);
break;
case 0x64: /* FS override */
case 0x65: /* GS override */
set_seg_override(c, c->b & 7);
break;
case 0x40 ... 0x4f: /* REX */
if (mode != X86EMUL_MODE_PROT64)
goto done_prefixes;
c->rex_prefix = c->b;
continue;
case 0xf0: /* LOCK */
c->lock_prefix = 1;
break;
case 0xf2: /* REPNE/REPNZ */
c->rep_prefix = REPNE_PREFIX;
break;
case 0xf3: /* REP/REPE/REPZ */
c->rep_prefix = REPE_PREFIX;
break;
default:
goto done_prefixes;
}
/* Any legacy prefix after a REX prefix nullifies its effect. */
c->rex_prefix = 0;
}
done_prefixes:
/* REX prefix. */
if (c->rex_prefix)
if (c->rex_prefix & 8)
c->op_bytes = 8; /* REX.W */
/* Opcode byte(s). */
c->d = opcode_table[c->b];
if (c->d == 0) {
/* Two-byte opcode? */
if (c->b == 0x0f) {
c->twobyte = 1;
c->b = insn_fetch(u8, 1, c->eip);
c->d = twobyte_table[c->b];
}
}
if (c->d & Group) {
group = c->d & GroupMask;
c->modrm = insn_fetch(u8, 1, c->eip);
--c->eip;
group = (group << 3) + ((c->modrm >> 3) & 7);
if ((c->d & GroupDual) && (c->modrm >> 6) == 3)
c->d = group2_table[group];
else
c->d = group_table[group];
}
/* Unrecognised? */
if (c->d == 0) {
DPRINTF("Cannot emulate %02x\n", c->b);
return -1;
}
if (mode == X86EMUL_MODE_PROT64 && (c->d & Stack))
c->op_bytes = 8;
/* ModRM and SIB bytes. */
if (c->d & ModRM)
rc = decode_modrm(ctxt, ops);
else if (c->d & MemAbs)
rc = decode_abs(ctxt, ops);
if (rc != X86EMUL_CONTINUE)
goto done;
if (!c->has_seg_override)
set_seg_override(c, VCPU_SREG_DS);
if (!(!c->twobyte && c->b == 0x8d))
c->modrm_ea += seg_override_base(ctxt, c);
if (c->ad_bytes != 8)
c->modrm_ea = (u32)c->modrm_ea;
if (c->rip_relative)
c->modrm_ea += c->eip;
/*
* Decode and fetch the source operand: register, memory
* or immediate.
*/
switch (c->d & SrcMask) {
case SrcNone:
break;
case SrcReg:
decode_register_operand(&c->src, c, 0);
break;
case SrcMem16:
c->src.bytes = 2;
goto srcmem_common;
case SrcMem32:
c->src.bytes = 4;
goto srcmem_common;
case SrcMem:
c->src.bytes = (c->d & ByteOp) ? 1 :
c->op_bytes;
/* Don't fetch the address for invlpg: it could be unmapped. */
if (c->twobyte && c->b == 0x01 && c->modrm_reg == 7)
break;
srcmem_common:
/*
* For instructions with a ModR/M byte, switch to register
* access if Mod = 3.
*/
if ((c->d & ModRM) && c->modrm_mod == 3) {
c->src.type = OP_REG;
c->src.val = c->modrm_val;
c->src.ptr = c->modrm_ptr;
break;
}
c->src.type = OP_MEM;
c->src.ptr = (unsigned long *)c->modrm_ea;
c->src.val = 0;
break;
case SrcImm:
case SrcImmU:
c->src.type = OP_IMM;
c->src.ptr = (unsigned long *)c->eip;
c->src.bytes = (c->d & ByteOp) ? 1 : c->op_bytes;
if (c->src.bytes == 8)
c->src.bytes = 4;
/* NB. Immediates are sign-extended as necessary. */
switch (c->src.bytes) {
case 1:
c->src.val = insn_fetch(s8, 1, c->eip);
break;
case 2:
c->src.val = insn_fetch(s16, 2, c->eip);
break;
case 4:
c->src.val = insn_fetch(s32, 4, c->eip);
break;
}
if ((c->d & SrcMask) == SrcImmU) {
switch (c->src.bytes) {
case 1:
c->src.val &= 0xff;
break;
case 2:
c->src.val &= 0xffff;
break;
case 4:
c->src.val &= 0xffffffff;
break;
}
}
break;
case SrcImmByte:
case SrcImmUByte:
c->src.type = OP_IMM;
c->src.ptr = (unsigned long *)c->eip;
c->src.bytes = 1;
if ((c->d & SrcMask) == SrcImmByte)
c->src.val = insn_fetch(s8, 1, c->eip);
else
c->src.val = insn_fetch(u8, 1, c->eip);
break;
case SrcOne:
c->src.bytes = 1;
c->src.val = 1;
break;
case SrcSI:
c->src.type = OP_MEM;
c->src.bytes = (c->d & ByteOp) ? 1 : c->op_bytes;
c->src.ptr = (unsigned long *)
register_address(c, seg_override_base(ctxt, c),
c->regs[VCPU_REGS_RSI]);
c->src.val = 0;
break;
}
/*
* Decode and fetch the second source operand: register, memory
* or immediate.
*/
switch (c->d & Src2Mask) {
case Src2None:
break;
case Src2CL:
c->src2.bytes = 1;
c->src2.val = c->regs[VCPU_REGS_RCX] & 0x8;
break;
case Src2ImmByte:
c->src2.type = OP_IMM;
c->src2.ptr = (unsigned long *)c->eip;
c->src2.bytes = 1;
c->src2.val = insn_fetch(u8, 1, c->eip);
break;
case Src2Imm16:
c->src2.type = OP_IMM;
c->src2.ptr = (unsigned long *)c->eip;
c->src2.bytes = 2;
c->src2.val = insn_fetch(u16, 2, c->eip);
break;
case Src2One:
c->src2.bytes = 1;
c->src2.val = 1;
break;
case Src2Mem16:
c->src2.type = OP_MEM;
c->src2.bytes = 2;
c->src2.ptr = (unsigned long *)(c->modrm_ea + c->src.bytes);
c->src2.val = 0;
break;
}
/* Decode and fetch the destination operand: register or memory. */
switch (c->d & DstMask) {
case ImplicitOps:
/* Special instructions do their own operand decoding. */
return 0;
case DstReg:
decode_register_operand(&c->dst, c,
c->twobyte && (c->b == 0xb6 || c->b == 0xb7));
break;
case DstMem:
case DstMem64:
if ((c->d & ModRM) && c->modrm_mod == 3) {
c->dst.bytes = (c->d & ByteOp) ? 1 : c->op_bytes;
c->dst.type = OP_REG;
c->dst.val = c->dst.orig_val = c->modrm_val;
c->dst.ptr = c->modrm_ptr;
break;
}
c->dst.type = OP_MEM;
c->dst.ptr = (unsigned long *)c->modrm_ea;
if ((c->d & DstMask) == DstMem64)
c->dst.bytes = 8;
else
c->dst.bytes = (c->d & ByteOp) ? 1 : c->op_bytes;
c->dst.val = 0;
if (c->d & BitOp) {
unsigned long mask = ~(c->dst.bytes * 8 - 1);
c->dst.ptr = (void *)c->dst.ptr +
(c->src.val & mask) / 8;
}
break;
case DstAcc:
c->dst.type = OP_REG;
c->dst.bytes = (c->d & ByteOp) ? 1 : c->op_bytes;
c->dst.ptr = &c->regs[VCPU_REGS_RAX];
switch (c->dst.bytes) {
case 1:
c->dst.val = *(u8 *)c->dst.ptr;
break;
case 2:
c->dst.val = *(u16 *)c->dst.ptr;
break;
case 4:
c->dst.val = *(u32 *)c->dst.ptr;
break;
case 8:
c->dst.val = *(u64 *)c->dst.ptr;
break;
}
c->dst.orig_val = c->dst.val;
break;
case DstDI:
c->dst.type = OP_MEM;
c->dst.bytes = (c->d & ByteOp) ? 1 : c->op_bytes;
c->dst.ptr = (unsigned long *)
register_address(c, es_base(ctxt),
c->regs[VCPU_REGS_RDI]);
c->dst.val = 0;
break;
}
done:
return (rc == X86EMUL_UNHANDLEABLE) ? -1 : 0;
}
static int pio_in_emulated(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
unsigned int size, unsigned short port,
void *dest)
{
struct read_cache *rc = &ctxt->decode.io_read;
if (rc->pos == rc->end) { /* refill pio read ahead */
struct decode_cache *c = &ctxt->decode;
unsigned int in_page, n;
unsigned int count = c->rep_prefix ?
address_mask(c, c->regs[VCPU_REGS_RCX]) : 1;
in_page = (ctxt->eflags & EFLG_DF) ?
offset_in_page(c->regs[VCPU_REGS_RDI]) :
PAGE_SIZE - offset_in_page(c->regs[VCPU_REGS_RDI]);
n = min(min(in_page, (unsigned int)sizeof(rc->data)) / size,
count);
if (n == 0)
n = 1;
rc->pos = rc->end = 0;
if (!ops->pio_in_emulated(size, port, rc->data, n, ctxt->vcpu))
return 0;
rc->end = n * size;
}
memcpy(dest, rc->data + rc->pos, size);
rc->pos += size;
return 1;
}
static u32 desc_limit_scaled(struct desc_struct *desc)
{
u32 limit = get_desc_limit(desc);
return desc->g ? (limit << 12) | 0xfff : limit;
}
static void get_descriptor_table_ptr(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 selector, struct desc_ptr *dt)
{
if (selector & 1 << 2) {
struct desc_struct desc;
memset (dt, 0, sizeof *dt);
if (!ops->get_cached_descriptor(&desc, VCPU_SREG_LDTR, ctxt->vcpu))
return;
dt->size = desc_limit_scaled(&desc); /* what if limit > 65535? */
dt->address = get_desc_base(&desc);
} else
ops->get_gdt(dt, ctxt->vcpu);
}
/* allowed just for 8 bytes segments */
static int read_segment_descriptor(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 selector, struct desc_struct *desc)
{
struct desc_ptr dt;
u16 index = selector >> 3;
int ret;
u32 err;
ulong addr;
get_descriptor_table_ptr(ctxt, ops, selector, &dt);
if (dt.size < index * 8 + 7) {
kvm_inject_gp(ctxt->vcpu, selector & 0xfffc);
return X86EMUL_PROPAGATE_FAULT;
}
addr = dt.address + index * 8;
ret = ops->read_std(addr, desc, sizeof *desc, ctxt->vcpu, &err);
if (ret == X86EMUL_PROPAGATE_FAULT)
kvm_inject_page_fault(ctxt->vcpu, addr, err);
return ret;
}
/* allowed just for 8 bytes segments */
static int write_segment_descriptor(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 selector, struct desc_struct *desc)
{
struct desc_ptr dt;
u16 index = selector >> 3;
u32 err;
ulong addr;
int ret;
get_descriptor_table_ptr(ctxt, ops, selector, &dt);
if (dt.size < index * 8 + 7) {
kvm_inject_gp(ctxt->vcpu, selector & 0xfffc);
return X86EMUL_PROPAGATE_FAULT;
}
addr = dt.address + index * 8;
ret = ops->write_std(addr, desc, sizeof *desc, ctxt->vcpu, &err);
if (ret == X86EMUL_PROPAGATE_FAULT)
kvm_inject_page_fault(ctxt->vcpu, addr, err);
return ret;
}
static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 selector, int seg)
{
struct desc_struct seg_desc;
u8 dpl, rpl, cpl;
unsigned err_vec = GP_VECTOR;
u32 err_code = 0;
bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
int ret;
memset(&seg_desc, 0, sizeof seg_desc);
if ((seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86)
|| ctxt->mode == X86EMUL_MODE_REAL) {
/* set real mode segment descriptor */
set_desc_base(&seg_desc, selector << 4);
set_desc_limit(&seg_desc, 0xffff);
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
goto load;
}
/* NULL selector is not valid for TR, CS and SS */
if ((seg == VCPU_SREG_CS || seg == VCPU_SREG_SS || seg == VCPU_SREG_TR)
&& null_selector)
goto exception;
/* TR should be in GDT only */
if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
goto exception;
if (null_selector) /* for NULL selector skip all following checks */
goto load;
ret = read_segment_descriptor(ctxt, ops, selector, &seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
err_code = selector & 0xfffc;
err_vec = GP_VECTOR;
/* can't load system descriptor into segment selecor */
if (seg <= VCPU_SREG_GS && !seg_desc.s)
goto exception;
if (!seg_desc.p) {
err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
goto exception;
}
rpl = selector & 3;
dpl = seg_desc.dpl;
cpl = ops->cpl(ctxt->vcpu);
switch (seg) {
case VCPU_SREG_SS:
/*
* segment is not a writable data segment or segment
* selector's RPL != CPL or segment selector's RPL != CPL
*/
if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
goto exception;
break;
case VCPU_SREG_CS:
if (!(seg_desc.type & 8))
goto exception;
if (seg_desc.type & 4) {
/* conforming */
if (dpl > cpl)
goto exception;
} else {
/* nonconforming */
if (rpl > cpl || dpl != cpl)
goto exception;
}
/* CS(RPL) <- CPL */
selector = (selector & 0xfffc) | cpl;
break;
case VCPU_SREG_TR:
if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
goto exception;
break;
case VCPU_SREG_LDTR:
if (seg_desc.s || seg_desc.type != 2)
goto exception;
break;
default: /* DS, ES, FS, or GS */
/*
* segment is not a data or readable code segment or
* ((segment is a data or nonconforming code segment)
* and (both RPL and CPL > DPL))
*/
if ((seg_desc.type & 0xa) == 0x8 ||
(((seg_desc.type & 0xc) != 0xc) &&
(rpl > dpl && cpl > dpl)))
goto exception;
break;
}
if (seg_desc.s) {
/* mark segment as accessed */
seg_desc.type |= 1;
ret = write_segment_descriptor(ctxt, ops, selector, &seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
}
load:
ops->set_segment_selector(selector, seg, ctxt->vcpu);
ops->set_cached_descriptor(&seg_desc, seg, ctxt->vcpu);
return X86EMUL_CONTINUE;
exception:
kvm_queue_exception_e(ctxt->vcpu, err_vec, err_code);
return X86EMUL_PROPAGATE_FAULT;
}
static inline void emulate_push(struct x86_emulate_ctxt *ctxt)
{
struct decode_cache *c = &ctxt->decode;
c->dst.type = OP_MEM;
c->dst.bytes = c->op_bytes;
c->dst.val = c->src.val;
register_address_increment(c, &c->regs[VCPU_REGS_RSP], -c->op_bytes);
c->dst.ptr = (void *) register_address(c, ss_base(ctxt),
c->regs[VCPU_REGS_RSP]);
}
static int emulate_pop(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
void *dest, int len)
{
struct decode_cache *c = &ctxt->decode;
int rc;
rc = ops->read_emulated(register_address(c, ss_base(ctxt),
c->regs[VCPU_REGS_RSP]),
dest, len, ctxt->vcpu);
if (rc != X86EMUL_CONTINUE)
return rc;
register_address_increment(c, &c->regs[VCPU_REGS_RSP], len);
return rc;
}
static int emulate_popf(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
void *dest, int len)
{
int rc;
unsigned long val, change_mask;
int iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> IOPL_SHIFT;
int cpl = ops->cpl(ctxt->vcpu);
rc = emulate_pop(ctxt, ops, &val, len);
if (rc != X86EMUL_CONTINUE)
return rc;
change_mask = EFLG_CF | EFLG_PF | EFLG_AF | EFLG_ZF | EFLG_SF | EFLG_OF
| EFLG_TF | EFLG_DF | EFLG_NT | EFLG_RF | EFLG_AC | EFLG_ID;
switch(ctxt->mode) {
case X86EMUL_MODE_PROT64:
case X86EMUL_MODE_PROT32:
case X86EMUL_MODE_PROT16:
if (cpl == 0)
change_mask |= EFLG_IOPL;
if (cpl <= iopl)
change_mask |= EFLG_IF;
break;
case X86EMUL_MODE_VM86:
if (iopl < 3) {
kvm_inject_gp(ctxt->vcpu, 0);
return X86EMUL_PROPAGATE_FAULT;
}
change_mask |= EFLG_IF;
break;
default: /* real mode */
change_mask |= (EFLG_IOPL | EFLG_IF);
break;
}
*(unsigned long *)dest =
(ctxt->eflags & ~change_mask) | (val & change_mask);
return rc;
}
static void emulate_push_sreg(struct x86_emulate_ctxt *ctxt, int seg)
{
struct decode_cache *c = &ctxt->decode;
struct kvm_segment segment;
kvm_x86_ops->get_segment(ctxt->vcpu, &segment, seg);
c->src.val = segment.selector;
emulate_push(ctxt);
}
static int emulate_pop_sreg(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops, int seg)
{
struct decode_cache *c = &ctxt->decode;
unsigned long selector;
int rc;
rc = emulate_pop(ctxt, ops, &selector, c->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = load_segment_descriptor(ctxt, ops, (u16)selector, seg);
return rc;
}
static void emulate_pusha(struct x86_emulate_ctxt *ctxt)
{
struct decode_cache *c = &ctxt->decode;
unsigned long old_esp = c->regs[VCPU_REGS_RSP];
int reg = VCPU_REGS_RAX;
while (reg <= VCPU_REGS_RDI) {
(reg == VCPU_REGS_RSP) ?
(c->src.val = old_esp) : (c->src.val = c->regs[reg]);
emulate_push(ctxt);
++reg;
}
}
static int emulate_popa(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
int rc = X86EMUL_CONTINUE;
int reg = VCPU_REGS_RDI;
while (reg >= VCPU_REGS_RAX) {
if (reg == VCPU_REGS_RSP) {
register_address_increment(c, &c->regs[VCPU_REGS_RSP],
c->op_bytes);
--reg;
}
rc = emulate_pop(ctxt, ops, &c->regs[reg], c->op_bytes);
if (rc != X86EMUL_CONTINUE)
break;
--reg;
}
return rc;
}
static inline int emulate_grp1a(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
return emulate_pop(ctxt, ops, &c->dst.val, c->dst.bytes);
}
static inline void emulate_grp2(struct x86_emulate_ctxt *ctxt)
{
struct decode_cache *c = &ctxt->decode;
switch (c->modrm_reg) {
case 0: /* rol */
emulate_2op_SrcB("rol", c->src, c->dst, ctxt->eflags);
break;
case 1: /* ror */
emulate_2op_SrcB("ror", c->src, c->dst, ctxt->eflags);
break;
case 2: /* rcl */
emulate_2op_SrcB("rcl", c->src, c->dst, ctxt->eflags);
break;
case 3: /* rcr */
emulate_2op_SrcB("rcr", c->src, c->dst, ctxt->eflags);
break;
case 4: /* sal/shl */
case 6: /* sal/shl */
emulate_2op_SrcB("sal", c->src, c->dst, ctxt->eflags);
break;
case 5: /* shr */
emulate_2op_SrcB("shr", c->src, c->dst, ctxt->eflags);
break;
case 7: /* sar */
emulate_2op_SrcB("sar", c->src, c->dst, ctxt->eflags);
break;
}
}
static inline int emulate_grp3(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
switch (c->modrm_reg) {
case 0 ... 1: /* test */
emulate_2op_SrcV("test", c->src, c->dst, ctxt->eflags);
break;
case 2: /* not */
c->dst.val = ~c->dst.val;
break;
case 3: /* neg */
emulate_1op("neg", c->dst, ctxt->eflags);
break;
default:
return 0;
}
return 1;
}
static inline int emulate_grp45(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
switch (c->modrm_reg) {
case 0: /* inc */
emulate_1op("inc", c->dst, ctxt->eflags);
break;
case 1: /* dec */
emulate_1op("dec", c->dst, ctxt->eflags);
break;
case 2: /* call near abs */ {
long int old_eip;
old_eip = c->eip;
c->eip = c->src.val;
c->src.val = old_eip;
emulate_push(ctxt);
break;
}
case 4: /* jmp abs */
c->eip = c->src.val;
break;
case 6: /* push */
emulate_push(ctxt);
break;
}
return X86EMUL_CONTINUE;
}
static inline int emulate_grp9(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
u64 old = c->dst.orig_val;
if (((u32) (old >> 0) != (u32) c->regs[VCPU_REGS_RAX]) ||
((u32) (old >> 32) != (u32) c->regs[VCPU_REGS_RDX])) {
c->regs[VCPU_REGS_RAX] = (u32) (old >> 0);
c->regs[VCPU_REGS_RDX] = (u32) (old >> 32);
ctxt->eflags &= ~EFLG_ZF;
} else {
c->dst.val = ((u64)c->regs[VCPU_REGS_RCX] << 32) |
(u32) c->regs[VCPU_REGS_RBX];
ctxt->eflags |= EFLG_ZF;
}
return X86EMUL_CONTINUE;
}
static int emulate_ret_far(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
struct decode_cache *c = &ctxt->decode;
int rc;
unsigned long cs;
rc = emulate_pop(ctxt, ops, &c->eip, c->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
if (c->op_bytes == 4)
c->eip = (u32)c->eip;
rc = emulate_pop(ctxt, ops, &cs, c->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = load_segment_descriptor(ctxt, ops, (u16)cs, VCPU_SREG_CS);
return rc;
}
static inline int writeback(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
int rc;
struct decode_cache *c = &ctxt->decode;
switch (c->dst.type) {
case OP_REG:
/* The 4-byte case *is* correct:
* in 64-bit mode we zero-extend.
*/
switch (c->dst.bytes) {
case 1:
*(u8 *)c->dst.ptr = (u8)c->dst.val;
break;
case 2:
*(u16 *)c->dst.ptr = (u16)c->dst.val;
break;
case 4:
*c->dst.ptr = (u32)c->dst.val;
break; /* 64b: zero-ext */
case 8:
*c->dst.ptr = c->dst.val;
break;
}
break;
case OP_MEM:
if (c->lock_prefix)
rc = ops->cmpxchg_emulated(
(unsigned long)c->dst.ptr,
&c->dst.orig_val,
&c->dst.val,
c->dst.bytes,
ctxt->vcpu);
else
rc = ops->write_emulated(
(unsigned long)c->dst.ptr,
&c->dst.val,
c->dst.bytes,
ctxt->vcpu);
if (rc != X86EMUL_CONTINUE)
return rc;
break;
case OP_NONE:
/* no writeback */
break;
default:
break;
}
return X86EMUL_CONTINUE;
}
static void toggle_interruptibility(struct x86_emulate_ctxt *ctxt, u32 mask)
{
u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(ctxt->vcpu, mask);
/*
* an sti; sti; sequence only disable interrupts for the first
* instruction. So, if the last instruction, be it emulated or
* not, left the system with the INT_STI flag enabled, it
* means that the last instruction is an sti. We should not
* leave the flag on in this case. The same goes for mov ss
*/
if (!(int_shadow & mask))
ctxt->interruptibility = mask;
}
static inline void
setup_syscalls_segments(struct x86_emulate_ctxt *ctxt,
struct kvm_segment *cs, struct kvm_segment *ss)
{
memset(cs, 0, sizeof(struct kvm_segment));
kvm_x86_ops->get_segment(ctxt->vcpu, cs, VCPU_SREG_CS);
memset(ss, 0, sizeof(struct kvm_segment));
cs->l = 0; /* will be adjusted later */
cs->base = 0; /* flat segment */
cs->g = 1; /* 4kb granularity */
cs->limit = 0xffffffff; /* 4GB limit */
cs->type = 0x0b; /* Read, Execute, Accessed */
cs->s = 1;
cs->dpl = 0; /* will be adjusted later */
cs->present = 1;
cs->db = 1;
ss->unusable = 0;
ss->base = 0; /* flat segment */
ss->limit = 0xffffffff; /* 4GB limit */
ss->g = 1; /* 4kb granularity */
ss->s = 1;
ss->type = 0x03; /* Read/Write, Accessed */
ss->db = 1; /* 32bit stack segment */
ss->dpl = 0;
ss->present = 1;
}
static int
emulate_syscall(struct x86_emulate_ctxt *ctxt)
{
struct decode_cache *c = &ctxt->decode;
struct kvm_segment cs, ss;
u64 msr_data;
/* syscall is not available in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86) {
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
return X86EMUL_PROPAGATE_FAULT;
}
setup_syscalls_segments(ctxt, &cs, &ss);
kvm_x86_ops->get_msr(ctxt->vcpu, MSR_STAR, &msr_data);
msr_data >>= 32;
cs.selector = (u16)(msr_data & 0xfffc);
ss.selector = (u16)(msr_data + 8);
if (is_long_mode(ctxt->vcpu)) {
cs.db = 0;
cs.l = 1;
}
kvm_x86_ops->set_segment(ctxt->vcpu, &cs, VCPU_SREG_CS);
kvm_x86_ops->set_segment(ctxt->vcpu, &ss, VCPU_SREG_SS);
c->regs[VCPU_REGS_RCX] = c->eip;
if (is_long_mode(ctxt->vcpu)) {
#ifdef CONFIG_X86_64
c->regs[VCPU_REGS_R11] = ctxt->eflags & ~EFLG_RF;
kvm_x86_ops->get_msr(ctxt->vcpu,
ctxt->mode == X86EMUL_MODE_PROT64 ?
MSR_LSTAR : MSR_CSTAR, &msr_data);
c->eip = msr_data;
kvm_x86_ops->get_msr(ctxt->vcpu, MSR_SYSCALL_MASK, &msr_data);
ctxt->eflags &= ~(msr_data | EFLG_RF);
#endif
} else {
/* legacy mode */
kvm_x86_ops->get_msr(ctxt->vcpu, MSR_STAR, &msr_data);
c->eip = (u32)msr_data;
ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF);
}
return X86EMUL_CONTINUE;
}
static int
emulate_sysenter(struct x86_emulate_ctxt *ctxt)
{
struct decode_cache *c = &ctxt->decode;
struct kvm_segment cs, ss;
u64 msr_data;
/* inject #GP if in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL) {
kvm_inject_gp(ctxt->vcpu, 0);
return X86EMUL_PROPAGATE_FAULT;
}
/* XXX sysenter/sysexit have not been tested in 64bit mode.
* Therefore, we inject an #UD.
*/
if (ctxt->mode == X86EMUL_MODE_PROT64) {
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
return X86EMUL_PROPAGATE_FAULT;
}
setup_syscalls_segments(ctxt, &cs, &ss);
kvm_x86_ops->get_msr(ctxt->vcpu, MSR_IA32_SYSENTER_CS, &msr_data);
switch (ctxt->mode) {
case X86EMUL_MODE_PROT32:
if ((msr_data & 0xfffc) == 0x0) {
kvm_inject_gp(ctxt->vcpu, 0);
return X86EMUL_PROPAGATE_FAULT;
}
break;
case X86EMUL_MODE_PROT64:
if (msr_data == 0x0) {
kvm_inject_gp(ctxt->vcpu, 0);
return X86EMUL_PROPAGATE_FAULT;
}
break;
}
ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF);
cs.selector = (u16)msr_data;
cs.selector &= ~SELECTOR_RPL_MASK;
ss.selector = cs.selector + 8;
ss.selector &= ~SELECTOR_RPL_MASK;
if (ctxt->mode == X86EMUL_MODE_PROT64
|| is_long_mode(ctxt->vcpu)) {
cs.db = 0;
cs.l = 1;
}
kvm_x86_ops->set_segment(ctxt->vcpu, &cs, VCPU_SREG_CS);
kvm_x86_ops->set_segment(ctxt->vcpu, &ss, VCPU_SREG_SS);
kvm_x86_ops->get_msr(ctxt->vcpu, MSR_IA32_SYSENTER_EIP, &msr_data);
c->eip = msr_data;
kvm_x86_ops->get_msr(ctxt->vcpu, MSR_IA32_SYSENTER_ESP, &msr_data);
c->regs[VCPU_REGS_RSP] = msr_data;
return X86EMUL_CONTINUE;
}
static int
emulate_sysexit(struct x86_emulate_ctxt *ctxt)
{
struct decode_cache *c = &ctxt->decode;
struct kvm_segment cs, ss;
u64 msr_data;
int usermode;
/* inject #GP if in real mode or Virtual 8086 mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86) {
kvm_inject_gp(ctxt->vcpu, 0);
return X86EMUL_PROPAGATE_FAULT;
}
setup_syscalls_segments(ctxt, &cs, &ss);
if ((c->rex_prefix & 0x8) != 0x0)
usermode = X86EMUL_MODE_PROT64;
else
usermode = X86EMUL_MODE_PROT32;
cs.dpl = 3;
ss.dpl = 3;
kvm_x86_ops->get_msr(ctxt->vcpu, MSR_IA32_SYSENTER_CS, &msr_data);
switch (usermode) {
case X86EMUL_MODE_PROT32:
cs.selector = (u16)(msr_data + 16);
if ((msr_data & 0xfffc) == 0x0) {
kvm_inject_gp(ctxt->vcpu, 0);
return X86EMUL_PROPAGATE_FAULT;
}
ss.selector = (u16)(msr_data + 24);
break;
case X86EMUL_MODE_PROT64:
cs.selector = (u16)(msr_data + 32);
if (msr_data == 0x0) {
kvm_inject_gp(ctxt->vcpu, 0);
return X86EMUL_PROPAGATE_FAULT;
}
ss.selector = cs.selector + 8;
cs.db = 0;
cs.l = 1;
break;
}
cs.selector |= SELECTOR_RPL_MASK;
ss.selector |= SELECTOR_RPL_MASK;
kvm_x86_ops->set_segment(ctxt->vcpu, &cs, VCPU_SREG_CS);
kvm_x86_ops->set_segment(ctxt->vcpu, &ss, VCPU_SREG_SS);
c->eip = ctxt->vcpu->arch.regs[VCPU_REGS_RDX];
c->regs[VCPU_REGS_RSP] = ctxt->vcpu->arch.regs[VCPU_REGS_RCX];
return X86EMUL_CONTINUE;
}
static bool emulator_bad_iopl(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops)
{
int iopl;
if (ctxt->mode == X86EMUL_MODE_REAL)
return false;
if (ctxt->mode == X86EMUL_MODE_VM86)
return true;
iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> IOPL_SHIFT;
return ops->cpl(ctxt->vcpu) > iopl;
}
static bool emulator_io_port_access_allowed(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 port, u16 len)
{
struct kvm_segment tr_seg;
int r;
u16 io_bitmap_ptr;
u8 perm, bit_idx = port & 0x7;
unsigned mask = (1 << len) - 1;
kvm_get_segment(ctxt->vcpu, &tr_seg, VCPU_SREG_TR);
if (tr_seg.unusable)
return false;
if (tr_seg.limit < 103)
return false;
r = ops->read_std(tr_seg.base + 102, &io_bitmap_ptr, 2, ctxt->vcpu,
NULL);
if (r != X86EMUL_CONTINUE)
return false;
if (io_bitmap_ptr + port/8 > tr_seg.limit)
return false;
r = ops->read_std(tr_seg.base + io_bitmap_ptr + port/8, &perm, 1,
ctxt->vcpu, NULL);
if (r != X86EMUL_CONTINUE)
return false;
if ((perm >> bit_idx) & mask)
return false;
return true;
}
static bool emulator_io_permited(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 port, u16 len)
{
if (emulator_bad_iopl(ctxt, ops))
if (!emulator_io_port_access_allowed(ctxt, ops, port, len))
return false;
return true;
}
static u32 get_cached_descriptor_base(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
int seg)
{
struct desc_struct desc;
if (ops->get_cached_descriptor(&desc, seg, ctxt->vcpu))
return get_desc_base(&desc);
else
return ~0;
}
static void save_state_to_tss16(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
struct tss_segment_16 *tss)
{
struct decode_cache *c = &ctxt->decode;
tss->ip = c->eip;
tss->flag = ctxt->eflags;
tss->ax = c->regs[VCPU_REGS_RAX];
tss->cx = c->regs[VCPU_REGS_RCX];
tss->dx = c->regs[VCPU_REGS_RDX];
tss->bx = c->regs[VCPU_REGS_RBX];
tss->sp = c->regs[VCPU_REGS_RSP];
tss->bp = c->regs[VCPU_REGS_RBP];
tss->si = c->regs[VCPU_REGS_RSI];
tss->di = c->regs[VCPU_REGS_RDI];
tss->es = ops->get_segment_selector(VCPU_SREG_ES, ctxt->vcpu);
tss->cs = ops->get_segment_selector(VCPU_SREG_CS, ctxt->vcpu);
tss->ss = ops->get_segment_selector(VCPU_SREG_SS, ctxt->vcpu);
tss->ds = ops->get_segment_selector(VCPU_SREG_DS, ctxt->vcpu);
tss->ldt = ops->get_segment_selector(VCPU_SREG_LDTR, ctxt->vcpu);
}
static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
struct tss_segment_16 *tss)
{
struct decode_cache *c = &ctxt->decode;
int ret;
c->eip = tss->ip;
ctxt->eflags = tss->flag | 2;
c->regs[VCPU_REGS_RAX] = tss->ax;
c->regs[VCPU_REGS_RCX] = tss->cx;
c->regs[VCPU_REGS_RDX] = tss->dx;
c->regs[VCPU_REGS_RBX] = tss->bx;
c->regs[VCPU_REGS_RSP] = tss->sp;
c->regs[VCPU_REGS_RBP] = tss->bp;
c->regs[VCPU_REGS_RSI] = tss->si;
c->regs[VCPU_REGS_RDI] = tss->di;
/*
* SDM says that segment selectors are loaded before segment
* descriptors
*/
ops->set_segment_selector(tss->ldt, VCPU_SREG_LDTR, ctxt->vcpu);
ops->set_segment_selector(tss->es, VCPU_SREG_ES, ctxt->vcpu);
ops->set_segment_selector(tss->cs, VCPU_SREG_CS, ctxt->vcpu);
ops->set_segment_selector(tss->ss, VCPU_SREG_SS, ctxt->vcpu);
ops->set_segment_selector(tss->ds, VCPU_SREG_DS, ctxt->vcpu);
/*
* Now load segment descriptors. If fault happenes at this stage
* it is handled in a context of new task
*/
ret = load_segment_descriptor(ctxt, ops, tss->ldt, VCPU_SREG_LDTR);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->es, VCPU_SREG_ES);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->cs, VCPU_SREG_CS);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->ss, VCPU_SREG_SS);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->ds, VCPU_SREG_DS);
if (ret != X86EMUL_CONTINUE)
return ret;
return X86EMUL_CONTINUE;
}
static int task_switch_16(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 tss_selector, u16 old_tss_sel,
ulong old_tss_base, struct desc_struct *new_desc)
{
struct tss_segment_16 tss_seg;
int ret;
u32 err, new_tss_base = get_desc_base(new_desc);
ret = ops->read_std(old_tss_base, &tss_seg, sizeof tss_seg, ctxt->vcpu,
&err);
if (ret == X86EMUL_PROPAGATE_FAULT) {
/* FIXME: need to provide precise fault address */
kvm_inject_page_fault(ctxt->vcpu, old_tss_base, err);
return ret;
}
save_state_to_tss16(ctxt, ops, &tss_seg);
ret = ops->write_std(old_tss_base, &tss_seg, sizeof tss_seg, ctxt->vcpu,
&err);
if (ret == X86EMUL_PROPAGATE_FAULT) {
/* FIXME: need to provide precise fault address */
kvm_inject_page_fault(ctxt->vcpu, old_tss_base, err);
return ret;
}
ret = ops->read_std(new_tss_base, &tss_seg, sizeof tss_seg, ctxt->vcpu,
&err);
if (ret == X86EMUL_PROPAGATE_FAULT) {
/* FIXME: need to provide precise fault address */
kvm_inject_page_fault(ctxt->vcpu, new_tss_base, err);
return ret;
}
if (old_tss_sel != 0xffff) {
tss_seg.prev_task_link = old_tss_sel;
ret = ops->write_std(new_tss_base,
&tss_seg.prev_task_link,
sizeof tss_seg.prev_task_link,
ctxt->vcpu, &err);
if (ret == X86EMUL_PROPAGATE_FAULT) {
/* FIXME: need to provide precise fault address */
kvm_inject_page_fault(ctxt->vcpu, new_tss_base, err);
return ret;
}
}
return load_state_from_tss16(ctxt, ops, &tss_seg);
}
static void save_state_to_tss32(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
struct tss_segment_32 *tss)
{
struct decode_cache *c = &ctxt->decode;
tss->cr3 = ops->get_cr(3, ctxt->vcpu);
tss->eip = c->eip;
tss->eflags = ctxt->eflags;
tss->eax = c->regs[VCPU_REGS_RAX];
tss->ecx = c->regs[VCPU_REGS_RCX];
tss->edx = c->regs[VCPU_REGS_RDX];
tss->ebx = c->regs[VCPU_REGS_RBX];
tss->esp = c->regs[VCPU_REGS_RSP];
tss->ebp = c->regs[VCPU_REGS_RBP];
tss->esi = c->regs[VCPU_REGS_RSI];
tss->edi = c->regs[VCPU_REGS_RDI];
tss->es = ops->get_segment_selector(VCPU_SREG_ES, ctxt->vcpu);
tss->cs = ops->get_segment_selector(VCPU_SREG_CS, ctxt->vcpu);
tss->ss = ops->get_segment_selector(VCPU_SREG_SS, ctxt->vcpu);
tss->ds = ops->get_segment_selector(VCPU_SREG_DS, ctxt->vcpu);
tss->fs = ops->get_segment_selector(VCPU_SREG_FS, ctxt->vcpu);
tss->gs = ops->get_segment_selector(VCPU_SREG_GS, ctxt->vcpu);
tss->ldt_selector = ops->get_segment_selector(VCPU_SREG_LDTR, ctxt->vcpu);
}
static int load_state_from_tss32(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
struct tss_segment_32 *tss)
{
struct decode_cache *c = &ctxt->decode;
int ret;
ops->set_cr(3, tss->cr3, ctxt->vcpu);
c->eip = tss->eip;
ctxt->eflags = tss->eflags | 2;
c->regs[VCPU_REGS_RAX] = tss->eax;
c->regs[VCPU_REGS_RCX] = tss->ecx;
c->regs[VCPU_REGS_RDX] = tss->edx;
c->regs[VCPU_REGS_RBX] = tss->ebx;
c->regs[VCPU_REGS_RSP] = tss->esp;
c->regs[VCPU_REGS_RBP] = tss->ebp;
c->regs[VCPU_REGS_RSI] = tss->esi;
c->regs[VCPU_REGS_RDI] = tss->edi;
/*
* SDM says that segment selectors are loaded before segment
* descriptors
*/
ops->set_segment_selector(tss->ldt_selector, VCPU_SREG_LDTR, ctxt->vcpu);
ops->set_segment_selector(tss->es, VCPU_SREG_ES, ctxt->vcpu);
ops->set_segment_selector(tss->cs, VCPU_SREG_CS, ctxt->vcpu);
ops->set_segment_selector(tss->ss, VCPU_SREG_SS, ctxt->vcpu);
ops->set_segment_selector(tss->ds, VCPU_SREG_DS, ctxt->vcpu);
ops->set_segment_selector(tss->fs, VCPU_SREG_FS, ctxt->vcpu);
ops->set_segment_selector(tss->gs, VCPU_SREG_GS, ctxt->vcpu);
/*
* Now load segment descriptors. If fault happenes at this stage
* it is handled in a context of new task
*/
ret = load_segment_descriptor(ctxt, ops, tss->ldt_selector, VCPU_SREG_LDTR);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->es, VCPU_SREG_ES);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->cs, VCPU_SREG_CS);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->ss, VCPU_SREG_SS);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->ds, VCPU_SREG_DS);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->fs, VCPU_SREG_FS);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = load_segment_descriptor(ctxt, ops, tss->gs, VCPU_SREG_GS);
if (ret != X86EMUL_CONTINUE)
return ret;
return X86EMUL_CONTINUE;
}
static int task_switch_32(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 tss_selector, u16 old_tss_sel,
ulong old_tss_base, struct desc_struct *new_desc)
{
struct tss_segment_32 tss_seg;
int ret;
u32 err, new_tss_base = get_desc_base(new_desc);
ret = ops->read_std(old_tss_base, &tss_seg, sizeof tss_seg, ctxt->vcpu,
&err);
if (ret == X86EMUL_PROPAGATE_FAULT) {
/* FIXME: need to provide precise fault address */
kvm_inject_page_fault(ctxt->vcpu, old_tss_base, err);
return ret;
}
save_state_to_tss32(ctxt, ops, &tss_seg);
ret = ops->write_std(old_tss_base, &tss_seg, sizeof tss_seg, ctxt->vcpu,
&err);
if (ret == X86EMUL_PROPAGATE_FAULT) {
/* FIXME: need to provide precise fault address */
kvm_inject_page_fault(ctxt->vcpu, old_tss_base, err);
return ret;
}
ret = ops->read_std(new_tss_base, &tss_seg, sizeof tss_seg, ctxt->vcpu,
&err);
if (ret == X86EMUL_PROPAGATE_FAULT) {
/* FIXME: need to provide precise fault address */
kvm_inject_page_fault(ctxt->vcpu, new_tss_base, err);
return ret;
}
if (old_tss_sel != 0xffff) {
tss_seg.prev_task_link = old_tss_sel;
ret = ops->write_std(new_tss_base,
&tss_seg.prev_task_link,
sizeof tss_seg.prev_task_link,
ctxt->vcpu, &err);
if (ret == X86EMUL_PROPAGATE_FAULT) {
/* FIXME: need to provide precise fault address */
kvm_inject_page_fault(ctxt->vcpu, new_tss_base, err);
return ret;
}
}
return load_state_from_tss32(ctxt, ops, &tss_seg);
}
static int emulator_do_task_switch(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 tss_selector, int reason,
bool has_error_code, u32 error_code)
{
struct desc_struct curr_tss_desc, next_tss_desc;
int ret;
u16 old_tss_sel = ops->get_segment_selector(VCPU_SREG_TR, ctxt->vcpu);
ulong old_tss_base =
get_cached_descriptor_base(ctxt, ops, VCPU_SREG_TR);
u32 desc_limit;
/* FIXME: old_tss_base == ~0 ? */
ret = read_segment_descriptor(ctxt, ops, tss_selector, &next_tss_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = read_segment_descriptor(ctxt, ops, old_tss_sel, &curr_tss_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
/* FIXME: check that next_tss_desc is tss */
if (reason != TASK_SWITCH_IRET) {
if ((tss_selector & 3) > next_tss_desc.dpl ||
ops->cpl(ctxt->vcpu) > next_tss_desc.dpl) {
kvm_inject_gp(ctxt->vcpu, 0);
return X86EMUL_PROPAGATE_FAULT;
}
}
desc_limit = desc_limit_scaled(&next_tss_desc);
if (!next_tss_desc.p ||
((desc_limit < 0x67 && (next_tss_desc.type & 8)) ||
desc_limit < 0x2b)) {
kvm_queue_exception_e(ctxt->vcpu, TS_VECTOR,
tss_selector & 0xfffc);
return X86EMUL_PROPAGATE_FAULT;
}
if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
curr_tss_desc.type &= ~(1 << 1); /* clear busy flag */
write_segment_descriptor(ctxt, ops, old_tss_sel,
&curr_tss_desc);
}
if (reason == TASK_SWITCH_IRET)
ctxt->eflags = ctxt->eflags & ~X86_EFLAGS_NT;
/* set back link to prev task only if NT bit is set in eflags
note that old_tss_sel is not used afetr this point */
if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
old_tss_sel = 0xffff;
if (next_tss_desc.type & 8)
ret = task_switch_32(ctxt, ops, tss_selector, old_tss_sel,
old_tss_base, &next_tss_desc);
else
ret = task_switch_16(ctxt, ops, tss_selector, old_tss_sel,
old_tss_base, &next_tss_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE)
ctxt->eflags = ctxt->eflags | X86_EFLAGS_NT;
if (reason != TASK_SWITCH_IRET) {
next_tss_desc.type |= (1 << 1); /* set busy flag */
write_segment_descriptor(ctxt, ops, tss_selector,
&next_tss_desc);
}
ops->set_cr(0, ops->get_cr(0, ctxt->vcpu) | X86_CR0_TS, ctxt->vcpu);
ops->set_cached_descriptor(&next_tss_desc, VCPU_SREG_TR, ctxt->vcpu);
ops->set_segment_selector(tss_selector, VCPU_SREG_TR, ctxt->vcpu);
if (has_error_code) {
struct decode_cache *c = &ctxt->decode;
c->op_bytes = c->ad_bytes = (next_tss_desc.type & 8) ? 4 : 2;
c->lock_prefix = 0;
c->src.val = (unsigned long) error_code;
emulate_push(ctxt);
}
return ret;
}
int emulator_task_switch(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
u16 tss_selector, int reason,
bool has_error_code, u32 error_code)
{
struct decode_cache *c = &ctxt->decode;
int rc;
memset(c, 0, sizeof(struct decode_cache));
c->eip = ctxt->eip;
memcpy(c->regs, ctxt->vcpu->arch.regs, sizeof c->regs);
c->dst.type = OP_NONE;
rc = emulator_do_task_switch(ctxt, ops, tss_selector, reason,
has_error_code, error_code);
if (rc == X86EMUL_CONTINUE) {
memcpy(ctxt->vcpu->arch.regs, c->regs, sizeof c->regs);
kvm_rip_write(ctxt->vcpu, c->eip);
rc = writeback(ctxt, ops);
}
return (rc == X86EMUL_UNHANDLEABLE) ? -1 : 0;
}
static void string_addr_inc(struct x86_emulate_ctxt *ctxt, unsigned long base,
int reg, struct operand *op)
{
struct decode_cache *c = &ctxt->decode;
int df = (ctxt->eflags & EFLG_DF) ? -1 : 1;
register_address_increment(c, &c->regs[reg], df * op->bytes);
op->ptr = (unsigned long *)register_address(c, base, c->regs[reg]);
}
int
x86_emulate_insn(struct x86_emulate_ctxt *ctxt, struct x86_emulate_ops *ops)
{
u64 msr_data;
struct decode_cache *c = &ctxt->decode;
int rc = X86EMUL_CONTINUE;
int saved_dst_type = c->dst.type;
ctxt->interruptibility = 0;
/* Shadow copy of register state. Committed on successful emulation.
* NOTE: we can copy them from vcpu as x86_decode_insn() doesn't
* modify them.
*/
memcpy(c->regs, ctxt->vcpu->arch.regs, sizeof c->regs);
if (ctxt->mode == X86EMUL_MODE_PROT64 && (c->d & No64)) {
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
goto done;
}
/* LOCK prefix is allowed only with some instructions */
if (c->lock_prefix && (!(c->d & Lock) || c->dst.type != OP_MEM)) {
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
goto done;
}
/* Privileged instruction can be executed only in CPL=0 */
if ((c->d & Priv) && ops->cpl(ctxt->vcpu)) {
kvm_inject_gp(ctxt->vcpu, 0);
goto done;
}
if (c->rep_prefix && (c->d & String)) {
ctxt->restart = true;
/* All REP prefixes have the same first termination condition */
if (address_mask(c, c->regs[VCPU_REGS_RCX]) == 0) {
string_done:
ctxt->restart = false;
kvm_rip_write(ctxt->vcpu, c->eip);
goto done;
}
/* The second termination condition only applies for REPE
* and REPNE. Test if the repeat string operation prefix is
* REPE/REPZ or REPNE/REPNZ and if it's the case it tests the
* corresponding termination condition according to:
* - if REPE/REPZ and ZF = 0 then done
* - if REPNE/REPNZ and ZF = 1 then done
*/
if ((c->b == 0xa6) || (c->b == 0xa7) ||
(c->b == 0xae) || (c->b == 0xaf)) {
if ((c->rep_prefix == REPE_PREFIX) &&
((ctxt->eflags & EFLG_ZF) == 0))
goto string_done;
if ((c->rep_prefix == REPNE_PREFIX) &&
((ctxt->eflags & EFLG_ZF) == EFLG_ZF))
goto string_done;
}
c->eip = ctxt->eip;
}
if (c->src.type == OP_MEM) {
rc = ops->read_emulated((unsigned long)c->src.ptr,
&c->src.val,
c->src.bytes,
ctxt->vcpu);
if (rc != X86EMUL_CONTINUE)
goto done;
c->src.orig_val = c->src.val;
}
if (c->src2.type == OP_MEM) {
rc = ops->read_emulated((unsigned long)c->src2.ptr,
&c->src2.val,
c->src2.bytes,
ctxt->vcpu);
if (rc != X86EMUL_CONTINUE)
goto done;
}
if ((c->d & DstMask) == ImplicitOps)
goto special_insn;
if ((c->dst.type == OP_MEM) && !(c->d & Mov)) {
/* optimisation - avoid slow emulated read if Mov */
rc = ops->read_emulated((unsigned long)c->dst.ptr, &c->dst.val,
c->dst.bytes, ctxt->vcpu);
if (rc != X86EMUL_CONTINUE)
goto done;
}
c->dst.orig_val = c->dst.val;
special_insn:
if (c->twobyte)
goto twobyte_insn;
switch (c->b) {
case 0x00 ... 0x05:
add: /* add */
emulate_2op_SrcV("add", c->src, c->dst, ctxt->eflags);
break;
case 0x06: /* push es */
emulate_push_sreg(ctxt, VCPU_SREG_ES);
break;
case 0x07: /* pop es */
rc = emulate_pop_sreg(ctxt, ops, VCPU_SREG_ES);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0x08 ... 0x0d:
or: /* or */
emulate_2op_SrcV("or", c->src, c->dst, ctxt->eflags);
break;
case 0x0e: /* push cs */
emulate_push_sreg(ctxt, VCPU_SREG_CS);
break;
case 0x10 ... 0x15:
adc: /* adc */
emulate_2op_SrcV("adc", c->src, c->dst, ctxt->eflags);
break;
case 0x16: /* push ss */
emulate_push_sreg(ctxt, VCPU_SREG_SS);
break;
case 0x17: /* pop ss */
rc = emulate_pop_sreg(ctxt, ops, VCPU_SREG_SS);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0x18 ... 0x1d:
sbb: /* sbb */
emulate_2op_SrcV("sbb", c->src, c->dst, ctxt->eflags);
break;
case 0x1e: /* push ds */
emulate_push_sreg(ctxt, VCPU_SREG_DS);
break;
case 0x1f: /* pop ds */
rc = emulate_pop_sreg(ctxt, ops, VCPU_SREG_DS);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0x20 ... 0x25:
and: /* and */
emulate_2op_SrcV("and", c->src, c->dst, ctxt->eflags);
break;
case 0x28 ... 0x2d:
sub: /* sub */
emulate_2op_SrcV("sub", c->src, c->dst, ctxt->eflags);
break;
case 0x30 ... 0x35:
xor: /* xor */
emulate_2op_SrcV("xor", c->src, c->dst, ctxt->eflags);
break;
case 0x38 ... 0x3d:
cmp: /* cmp */
emulate_2op_SrcV("cmp", c->src, c->dst, ctxt->eflags);
break;
case 0x40 ... 0x47: /* inc r16/r32 */
emulate_1op("inc", c->dst, ctxt->eflags);
break;
case 0x48 ... 0x4f: /* dec r16/r32 */
emulate_1op("dec", c->dst, ctxt->eflags);
break;
case 0x50 ... 0x57: /* push reg */
emulate_push(ctxt);
break;
case 0x58 ... 0x5f: /* pop reg */
pop_instruction:
rc = emulate_pop(ctxt, ops, &c->dst.val, c->op_bytes);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0x60: /* pusha */
emulate_pusha(ctxt);
break;
case 0x61: /* popa */
rc = emulate_popa(ctxt, ops);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0x63: /* movsxd */
if (ctxt->mode != X86EMUL_MODE_PROT64)
goto cannot_emulate;
c->dst.val = (s32) c->src.val;
break;
case 0x68: /* push imm */
case 0x6a: /* push imm8 */
emulate_push(ctxt);
break;
case 0x6c: /* insb */
case 0x6d: /* insw/insd */
c->dst.bytes = min(c->dst.bytes, 4u);
if (!emulator_io_permited(ctxt, ops, c->regs[VCPU_REGS_RDX],
c->dst.bytes)) {
kvm_inject_gp(ctxt->vcpu, 0);
goto done;
}
if (!pio_in_emulated(ctxt, ops, c->dst.bytes,
c->regs[VCPU_REGS_RDX], &c->dst.val))
goto done; /* IO is needed, skip writeback */
break;
case 0x6e: /* outsb */
case 0x6f: /* outsw/outsd */
c->src.bytes = min(c->src.bytes, 4u);
if (!emulator_io_permited(ctxt, ops, c->regs[VCPU_REGS_RDX],
c->src.bytes)) {
kvm_inject_gp(ctxt->vcpu, 0);
goto done;
}
ops->pio_out_emulated(c->src.bytes, c->regs[VCPU_REGS_RDX],
&c->src.val, 1, ctxt->vcpu);
c->dst.type = OP_NONE; /* nothing to writeback */
break;
case 0x70 ... 0x7f: /* jcc (short) */
if (test_cc(c->b, ctxt->eflags))
jmp_rel(c, c->src.val);
break;
case 0x80 ... 0x83: /* Grp1 */
switch (c->modrm_reg) {
case 0:
goto add;
case 1:
goto or;
case 2:
goto adc;
case 3:
goto sbb;
case 4:
goto and;
case 5:
goto sub;
case 6:
goto xor;
case 7:
goto cmp;
}
break;
case 0x84 ... 0x85:
emulate_2op_SrcV("test", c->src, c->dst, ctxt->eflags);
break;
case 0x86 ... 0x87: /* xchg */
xchg:
/* Write back the register source. */
switch (c->dst.bytes) {
case 1:
*(u8 *) c->src.ptr = (u8) c->dst.val;
break;
case 2:
*(u16 *) c->src.ptr = (u16) c->dst.val;
break;
case 4:
*c->src.ptr = (u32) c->dst.val;
break; /* 64b reg: zero-extend */
case 8:
*c->src.ptr = c->dst.val;
break;
}
/*
* Write back the memory destination with implicit LOCK
* prefix.
*/
c->dst.val = c->src.val;
c->lock_prefix = 1;
break;
case 0x88 ... 0x8b: /* mov */
goto mov;
case 0x8c: { /* mov r/m, sreg */
struct kvm_segment segreg;
if (c->modrm_reg <= VCPU_SREG_GS)
kvm_get_segment(ctxt->vcpu, &segreg, c->modrm_reg);
else {
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
goto done;
}
c->dst.val = segreg.selector;
break;
}
case 0x8d: /* lea r16/r32, m */
c->dst.val = c->modrm_ea;
break;
case 0x8e: { /* mov seg, r/m16 */
uint16_t sel;
sel = c->src.val;
if (c->modrm_reg == VCPU_SREG_CS ||
c->modrm_reg > VCPU_SREG_GS) {
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
goto done;
}
if (c->modrm_reg == VCPU_SREG_SS)
toggle_interruptibility(ctxt, KVM_X86_SHADOW_INT_MOV_SS);
rc = load_segment_descriptor(ctxt, ops, sel, c->modrm_reg);
c->dst.type = OP_NONE; /* Disable writeback. */
break;
}
case 0x8f: /* pop (sole member of Grp1a) */
rc = emulate_grp1a(ctxt, ops);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0x90: /* nop / xchg r8,rax */
if (!(c->rex_prefix & 1)) { /* nop */
c->dst.type = OP_NONE;
break;
}
case 0x91 ... 0x97: /* xchg reg,rax */
c->src.type = c->dst.type = OP_REG;
c->src.bytes = c->dst.bytes = c->op_bytes;
c->src.ptr = (unsigned long *) &c->regs[VCPU_REGS_RAX];
c->src.val = *(c->src.ptr);
goto xchg;
case 0x9c: /* pushf */
c->src.val = (unsigned long) ctxt->eflags;
emulate_push(ctxt);
break;
case 0x9d: /* popf */
c->dst.type = OP_REG;
c->dst.ptr = (unsigned long *) &ctxt->eflags;
c->dst.bytes = c->op_bytes;
rc = emulate_popf(ctxt, ops, &c->dst.val, c->op_bytes);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0xa0 ... 0xa1: /* mov */
c->dst.ptr = (unsigned long *)&c->regs[VCPU_REGS_RAX];
c->dst.val = c->src.val;
break;
case 0xa2 ... 0xa3: /* mov */
c->dst.val = (unsigned long)c->regs[VCPU_REGS_RAX];
break;
case 0xa4 ... 0xa5: /* movs */
goto mov;
case 0xa6 ... 0xa7: /* cmps */
c->dst.type = OP_NONE; /* Disable writeback. */
DPRINTF("cmps: mem1=0x%p mem2=0x%p\n", c->src.ptr, c->dst.ptr);
goto cmp;
case 0xaa ... 0xab: /* stos */
c->dst.val = c->regs[VCPU_REGS_RAX];
break;
case 0xac ... 0xad: /* lods */
goto mov;
case 0xae ... 0xaf: /* scas */
DPRINTF("Urk! I don't handle SCAS.\n");
goto cannot_emulate;
case 0xb0 ... 0xbf: /* mov r, imm */
goto mov;
case 0xc0 ... 0xc1:
emulate_grp2(ctxt);
break;
case 0xc3: /* ret */
c->dst.type = OP_REG;
c->dst.ptr = &c->eip;
c->dst.bytes = c->op_bytes;
goto pop_instruction;
case 0xc6 ... 0xc7: /* mov (sole member of Grp11) */
mov:
c->dst.val = c->src.val;
break;
case 0xcb: /* ret far */
rc = emulate_ret_far(ctxt, ops);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0xd0 ... 0xd1: /* Grp2 */
c->src.val = 1;
emulate_grp2(ctxt);
break;
case 0xd2 ... 0xd3: /* Grp2 */
c->src.val = c->regs[VCPU_REGS_RCX];
emulate_grp2(ctxt);
break;
case 0xe4: /* inb */
case 0xe5: /* in */
goto do_io_in;
case 0xe6: /* outb */
case 0xe7: /* out */
goto do_io_out;
case 0xe8: /* call (near) */ {
long int rel = c->src.val;
c->src.val = (unsigned long) c->eip;
jmp_rel(c, rel);
emulate_push(ctxt);
break;
}
case 0xe9: /* jmp rel */
goto jmp;
case 0xea: /* jmp far */
jump_far:
if (load_segment_descriptor(ctxt, ops, c->src2.val,
VCPU_SREG_CS))
goto done;
c->eip = c->src.val;
break;
case 0xeb:
jmp: /* jmp rel short */
jmp_rel(c, c->src.val);
c->dst.type = OP_NONE; /* Disable writeback. */
break;
case 0xec: /* in al,dx */
case 0xed: /* in (e/r)ax,dx */
c->src.val = c->regs[VCPU_REGS_RDX];
do_io_in:
c->dst.bytes = min(c->dst.bytes, 4u);
if (!emulator_io_permited(ctxt, ops, c->src.val, c->dst.bytes)) {
kvm_inject_gp(ctxt->vcpu, 0);
goto done;
}
if (!pio_in_emulated(ctxt, ops, c->dst.bytes, c->src.val,
&c->dst.val))
goto done; /* IO is needed */
break;
case 0xee: /* out al,dx */
case 0xef: /* out (e/r)ax,dx */
c->src.val = c->regs[VCPU_REGS_RDX];
do_io_out:
c->dst.bytes = min(c->dst.bytes, 4u);
if (!emulator_io_permited(ctxt, ops, c->src.val, c->dst.bytes)) {
kvm_inject_gp(ctxt->vcpu, 0);
goto done;
}
ops->pio_out_emulated(c->dst.bytes, c->src.val, &c->dst.val, 1,
ctxt->vcpu);
c->dst.type = OP_NONE; /* Disable writeback. */
break;
case 0xf4: /* hlt */
ctxt->vcpu->arch.halt_request = 1;
break;
case 0xf5: /* cmc */
/* complement carry flag from eflags reg */
ctxt->eflags ^= EFLG_CF;
c->dst.type = OP_NONE; /* Disable writeback. */
break;
case 0xf6 ... 0xf7: /* Grp3 */
if (!emulate_grp3(ctxt, ops))
goto cannot_emulate;
break;
case 0xf8: /* clc */
ctxt->eflags &= ~EFLG_CF;
c->dst.type = OP_NONE; /* Disable writeback. */
break;
case 0xfa: /* cli */
if (emulator_bad_iopl(ctxt, ops))
kvm_inject_gp(ctxt->vcpu, 0);
else {
ctxt->eflags &= ~X86_EFLAGS_IF;
c->dst.type = OP_NONE; /* Disable writeback. */
}
break;
case 0xfb: /* sti */
if (emulator_bad_iopl(ctxt, ops))
kvm_inject_gp(ctxt->vcpu, 0);
else {
toggle_interruptibility(ctxt, KVM_X86_SHADOW_INT_STI);
ctxt->eflags |= X86_EFLAGS_IF;
c->dst.type = OP_NONE; /* Disable writeback. */
}
break;
case 0xfc: /* cld */
ctxt->eflags &= ~EFLG_DF;
c->dst.type = OP_NONE; /* Disable writeback. */
break;
case 0xfd: /* std */
ctxt->eflags |= EFLG_DF;
c->dst.type = OP_NONE; /* Disable writeback. */
break;
case 0xfe: /* Grp4 */
grp45:
rc = emulate_grp45(ctxt, ops);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0xff: /* Grp5 */
if (c->modrm_reg == 5)
goto jump_far;
goto grp45;
}
writeback:
rc = writeback(ctxt, ops);
if (rc != X86EMUL_CONTINUE)
goto done;
/*
* restore dst type in case the decoding will be reused
* (happens for string instruction )
*/
c->dst.type = saved_dst_type;
if ((c->d & SrcMask) == SrcSI)
string_addr_inc(ctxt, seg_override_base(ctxt, c), VCPU_REGS_RSI,
&c->src);
if ((c->d & DstMask) == DstDI)
string_addr_inc(ctxt, es_base(ctxt), VCPU_REGS_RDI, &c->dst);
if (c->rep_prefix && (c->d & String)) {
struct read_cache *rc = &ctxt->decode.io_read;
register_address_increment(c, &c->regs[VCPU_REGS_RCX], -1);
/*
* Re-enter guest when pio read ahead buffer is empty or,
* if it is not used, after each 1024 iteration.
*/
if ((rc->end == 0 && !(c->regs[VCPU_REGS_RCX] & 0x3ff)) ||
(rc->end != 0 && rc->end == rc->pos))
ctxt->restart = false;
}
/* Commit shadow register state. */
memcpy(ctxt->vcpu->arch.regs, c->regs, sizeof c->regs);
kvm_rip_write(ctxt->vcpu, c->eip);
ops->set_rflags(ctxt->vcpu, ctxt->eflags);
done:
return (rc == X86EMUL_UNHANDLEABLE) ? -1 : 0;
twobyte_insn:
switch (c->b) {
case 0x01: /* lgdt, lidt, lmsw */
switch (c->modrm_reg) {
u16 size;
unsigned long address;
case 0: /* vmcall */
if (c->modrm_mod != 3 || c->modrm_rm != 1)
goto cannot_emulate;
rc = kvm_fix_hypercall(ctxt->vcpu);
if (rc != X86EMUL_CONTINUE)
goto done;
/* Let the processor re-execute the fixed hypercall */
c->eip = ctxt->eip;
/* Disable writeback. */
c->dst.type = OP_NONE;
break;
case 2: /* lgdt */
rc = read_descriptor(ctxt, ops, c->src.ptr,
&size, &address, c->op_bytes);
if (rc != X86EMUL_CONTINUE)
goto done;
realmode_lgdt(ctxt->vcpu, size, address);
/* Disable writeback. */
c->dst.type = OP_NONE;
break;
case 3: /* lidt/vmmcall */
if (c->modrm_mod == 3) {
switch (c->modrm_rm) {
case 1:
rc = kvm_fix_hypercall(ctxt->vcpu);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
default:
goto cannot_emulate;
}
} else {
rc = read_descriptor(ctxt, ops, c->src.ptr,
&size, &address,
c->op_bytes);
if (rc != X86EMUL_CONTINUE)
goto done;
realmode_lidt(ctxt->vcpu, size, address);
}
/* Disable writeback. */
c->dst.type = OP_NONE;
break;
case 4: /* smsw */
c->dst.bytes = 2;
c->dst.val = ops->get_cr(0, ctxt->vcpu);
break;
case 6: /* lmsw */
ops->set_cr(0, (ops->get_cr(0, ctxt->vcpu) & ~0x0ful) |
(c->src.val & 0x0f), ctxt->vcpu);
c->dst.type = OP_NONE;
break;
case 5: /* not defined */
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
goto done;
case 7: /* invlpg*/
emulate_invlpg(ctxt->vcpu, c->modrm_ea);
/* Disable writeback. */
c->dst.type = OP_NONE;
break;
default:
goto cannot_emulate;
}
break;
case 0x05: /* syscall */
rc = emulate_syscall(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
else
goto writeback;
break;
case 0x06:
emulate_clts(ctxt->vcpu);
c->dst.type = OP_NONE;
break;
case 0x08: /* invd */
case 0x09: /* wbinvd */
case 0x0d: /* GrpP (prefetch) */
case 0x18: /* Grp16 (prefetch/nop) */
c->dst.type = OP_NONE;
break;
case 0x20: /* mov cr, reg */
switch (c->modrm_reg) {
case 1:
case 5 ... 7:
case 9 ... 15:
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
goto done;
}
c->regs[c->modrm_rm] = ops->get_cr(c->modrm_reg, ctxt->vcpu);
c->dst.type = OP_NONE; /* no writeback */
break;
case 0x21: /* mov from dr to reg */
if ((ops->get_cr(4, ctxt->vcpu) & X86_CR4_DE) &&
(c->modrm_reg == 4 || c->modrm_reg == 5)) {
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
goto done;
}
emulator_get_dr(ctxt, c->modrm_reg, &c->regs[c->modrm_rm]);
c->dst.type = OP_NONE; /* no writeback */
break;
case 0x22: /* mov reg, cr */
ops->set_cr(c->modrm_reg, c->modrm_val, ctxt->vcpu);
c->dst.type = OP_NONE;
break;
case 0x23: /* mov from reg to dr */
if ((ops->get_cr(4, ctxt->vcpu) & X86_CR4_DE) &&
(c->modrm_reg == 4 || c->modrm_reg == 5)) {
kvm_queue_exception(ctxt->vcpu, UD_VECTOR);
goto done;
}
emulator_set_dr(ctxt, c->modrm_reg, c->regs[c->modrm_rm]);
c->dst.type = OP_NONE; /* no writeback */
break;
case 0x30:
/* wrmsr */
msr_data = (u32)c->regs[VCPU_REGS_RAX]
| ((u64)c->regs[VCPU_REGS_RDX] << 32);
if (kvm_set_msr(ctxt->vcpu, c->regs[VCPU_REGS_RCX], msr_data)) {
kvm_inject_gp(ctxt->vcpu, 0);
goto done;
}
rc = X86EMUL_CONTINUE;
c->dst.type = OP_NONE;
break;
case 0x32:
/* rdmsr */
if (kvm_get_msr(ctxt->vcpu, c->regs[VCPU_REGS_RCX], &msr_data)) {
kvm_inject_gp(ctxt->vcpu, 0);
goto done;
} else {
c->regs[VCPU_REGS_RAX] = (u32)msr_data;
c->regs[VCPU_REGS_RDX] = msr_data >> 32;
}
rc = X86EMUL_CONTINUE;
c->dst.type = OP_NONE;
break;
case 0x34: /* sysenter */
rc = emulate_sysenter(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
else
goto writeback;
break;
case 0x35: /* sysexit */
rc = emulate_sysexit(ctxt);
if (rc != X86EMUL_CONTINUE)
goto done;
else
goto writeback;
break;
case 0x40 ... 0x4f: /* cmov */
c->dst.val = c->dst.orig_val = c->src.val;
if (!test_cc(c->b, ctxt->eflags))
c->dst.type = OP_NONE; /* no writeback */
break;
case 0x80 ... 0x8f: /* jnz rel, etc*/
if (test_cc(c->b, ctxt->eflags))
jmp_rel(c, c->src.val);
c->dst.type = OP_NONE;
break;
case 0xa0: /* push fs */
emulate_push_sreg(ctxt, VCPU_SREG_FS);
break;
case 0xa1: /* pop fs */
rc = emulate_pop_sreg(ctxt, ops, VCPU_SREG_FS);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0xa3:
bt: /* bt */
c->dst.type = OP_NONE;
/* only subword offset */
c->src.val &= (c->dst.bytes << 3) - 1;
emulate_2op_SrcV_nobyte("bt", c->src, c->dst, ctxt->eflags);
break;
case 0xa4: /* shld imm8, r, r/m */
case 0xa5: /* shld cl, r, r/m */
emulate_2op_cl("shld", c->src2, c->src, c->dst, ctxt->eflags);
break;
case 0xa8: /* push gs */
emulate_push_sreg(ctxt, VCPU_SREG_GS);
break;
case 0xa9: /* pop gs */
rc = emulate_pop_sreg(ctxt, ops, VCPU_SREG_GS);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
case 0xab:
bts: /* bts */
/* only subword offset */
c->src.val &= (c->dst.bytes << 3) - 1;
emulate_2op_SrcV_nobyte("bts", c->src, c->dst, ctxt->eflags);
break;
case 0xac: /* shrd imm8, r, r/m */
case 0xad: /* shrd cl, r, r/m */
emulate_2op_cl("shrd", c->src2, c->src, c->dst, ctxt->eflags);
break;
case 0xae: /* clflush */
break;
case 0xb0 ... 0xb1: /* cmpxchg */
/*
* Save real source value, then compare EAX against
* destination.
*/
c->src.orig_val = c->src.val;
c->src.val = c->regs[VCPU_REGS_RAX];
emulate_2op_SrcV("cmp", c->src, c->dst, ctxt->eflags);
if (ctxt->eflags & EFLG_ZF) {
/* Success: write back to memory. */
c->dst.val = c->src.orig_val;
} else {
/* Failure: write the value we saw to EAX. */
c->dst.type = OP_REG;
c->dst.ptr = (unsigned long *)&c->regs[VCPU_REGS_RAX];
}
break;
case 0xb3:
btr: /* btr */
/* only subword offset */
c->src.val &= (c->dst.bytes << 3) - 1;
emulate_2op_SrcV_nobyte("btr", c->src, c->dst, ctxt->eflags);
break;
case 0xb6 ... 0xb7: /* movzx */
c->dst.bytes = c->op_bytes;
c->dst.val = (c->d & ByteOp) ? (u8) c->src.val
: (u16) c->src.val;
break;
case 0xba: /* Grp8 */
switch (c->modrm_reg & 3) {
case 0:
goto bt;
case 1:
goto bts;
case 2:
goto btr;
case 3:
goto btc;
}
break;
case 0xbb:
btc: /* btc */
/* only subword offset */
c->src.val &= (c->dst.bytes << 3) - 1;
emulate_2op_SrcV_nobyte("btc", c->src, c->dst, ctxt->eflags);
break;
case 0xbe ... 0xbf: /* movsx */
c->dst.bytes = c->op_bytes;
c->dst.val = (c->d & ByteOp) ? (s8) c->src.val :
(s16) c->src.val;
break;
case 0xc3: /* movnti */
c->dst.bytes = c->op_bytes;
c->dst.val = (c->op_bytes == 4) ? (u32) c->src.val :
(u64) c->src.val;
break;
case 0xc7: /* Grp9 (cmpxchg8b) */
rc = emulate_grp9(ctxt, ops);
if (rc != X86EMUL_CONTINUE)
goto done;
break;
}
goto writeback;
cannot_emulate:
DPRINTF("Cannot emulate %02x\n", c->b);
return -1;
}
| gpl-2.0 |
halfline/linux | drivers/mtd/ubi/debug.c | 718 | 15666 | /*
* Copyright (c) International Business Machines Corp., 2006
*
* 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
*
* Author: Artem Bityutskiy (Битюцкий Артём)
*/
#include "ubi.h"
#include <linux/debugfs.h>
#include <linux/uaccess.h>
#include <linux/module.h>
/**
* ubi_dump_flash - dump a region of flash.
* @ubi: UBI device description object
* @pnum: the physical eraseblock number to dump
* @offset: the starting offset within the physical eraseblock to dump
* @len: the length of the region to dump
*/
void ubi_dump_flash(struct ubi_device *ubi, int pnum, int offset, int len)
{
int err;
size_t read;
void *buf;
loff_t addr = (loff_t)pnum * ubi->peb_size + offset;
buf = vmalloc(len);
if (!buf)
return;
err = mtd_read(ubi->mtd, addr, len, &read, buf);
if (err && err != -EUCLEAN) {
ubi_err(ubi, "err %d while reading %d bytes from PEB %d:%d, read %zd bytes",
err, len, pnum, offset, read);
goto out;
}
ubi_msg(ubi, "dumping %d bytes of data from PEB %d, offset %d",
len, pnum, offset);
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1, buf, len, 1);
out:
vfree(buf);
return;
}
/**
* ubi_dump_ec_hdr - dump an erase counter header.
* @ec_hdr: the erase counter header to dump
*/
void ubi_dump_ec_hdr(const struct ubi_ec_hdr *ec_hdr)
{
pr_err("Erase counter header dump:\n");
pr_err("\tmagic %#08x\n", be32_to_cpu(ec_hdr->magic));
pr_err("\tversion %d\n", (int)ec_hdr->version);
pr_err("\tec %llu\n", (long long)be64_to_cpu(ec_hdr->ec));
pr_err("\tvid_hdr_offset %d\n", be32_to_cpu(ec_hdr->vid_hdr_offset));
pr_err("\tdata_offset %d\n", be32_to_cpu(ec_hdr->data_offset));
pr_err("\timage_seq %d\n", be32_to_cpu(ec_hdr->image_seq));
pr_err("\thdr_crc %#08x\n", be32_to_cpu(ec_hdr->hdr_crc));
pr_err("erase counter header hexdump:\n");
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
ec_hdr, UBI_EC_HDR_SIZE, 1);
}
/**
* ubi_dump_vid_hdr - dump a volume identifier header.
* @vid_hdr: the volume identifier header to dump
*/
void ubi_dump_vid_hdr(const struct ubi_vid_hdr *vid_hdr)
{
pr_err("Volume identifier header dump:\n");
pr_err("\tmagic %08x\n", be32_to_cpu(vid_hdr->magic));
pr_err("\tversion %d\n", (int)vid_hdr->version);
pr_err("\tvol_type %d\n", (int)vid_hdr->vol_type);
pr_err("\tcopy_flag %d\n", (int)vid_hdr->copy_flag);
pr_err("\tcompat %d\n", (int)vid_hdr->compat);
pr_err("\tvol_id %d\n", be32_to_cpu(vid_hdr->vol_id));
pr_err("\tlnum %d\n", be32_to_cpu(vid_hdr->lnum));
pr_err("\tdata_size %d\n", be32_to_cpu(vid_hdr->data_size));
pr_err("\tused_ebs %d\n", be32_to_cpu(vid_hdr->used_ebs));
pr_err("\tdata_pad %d\n", be32_to_cpu(vid_hdr->data_pad));
pr_err("\tsqnum %llu\n",
(unsigned long long)be64_to_cpu(vid_hdr->sqnum));
pr_err("\thdr_crc %08x\n", be32_to_cpu(vid_hdr->hdr_crc));
pr_err("Volume identifier header hexdump:\n");
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
vid_hdr, UBI_VID_HDR_SIZE, 1);
}
/**
* ubi_dump_vol_info - dump volume information.
* @vol: UBI volume description object
*/
void ubi_dump_vol_info(const struct ubi_volume *vol)
{
pr_err("Volume information dump:\n");
pr_err("\tvol_id %d\n", vol->vol_id);
pr_err("\treserved_pebs %d\n", vol->reserved_pebs);
pr_err("\talignment %d\n", vol->alignment);
pr_err("\tdata_pad %d\n", vol->data_pad);
pr_err("\tvol_type %d\n", vol->vol_type);
pr_err("\tname_len %d\n", vol->name_len);
pr_err("\tusable_leb_size %d\n", vol->usable_leb_size);
pr_err("\tused_ebs %d\n", vol->used_ebs);
pr_err("\tused_bytes %lld\n", vol->used_bytes);
pr_err("\tlast_eb_bytes %d\n", vol->last_eb_bytes);
pr_err("\tcorrupted %d\n", vol->corrupted);
pr_err("\tupd_marker %d\n", vol->upd_marker);
if (vol->name_len <= UBI_VOL_NAME_MAX &&
strnlen(vol->name, vol->name_len + 1) == vol->name_len) {
pr_err("\tname %s\n", vol->name);
} else {
pr_err("\t1st 5 characters of name: %c%c%c%c%c\n",
vol->name[0], vol->name[1], vol->name[2],
vol->name[3], vol->name[4]);
}
}
/**
* ubi_dump_vtbl_record - dump a &struct ubi_vtbl_record object.
* @r: the object to dump
* @idx: volume table index
*/
void ubi_dump_vtbl_record(const struct ubi_vtbl_record *r, int idx)
{
int name_len = be16_to_cpu(r->name_len);
pr_err("Volume table record %d dump:\n", idx);
pr_err("\treserved_pebs %d\n", be32_to_cpu(r->reserved_pebs));
pr_err("\talignment %d\n", be32_to_cpu(r->alignment));
pr_err("\tdata_pad %d\n", be32_to_cpu(r->data_pad));
pr_err("\tvol_type %d\n", (int)r->vol_type);
pr_err("\tupd_marker %d\n", (int)r->upd_marker);
pr_err("\tname_len %d\n", name_len);
if (r->name[0] == '\0') {
pr_err("\tname NULL\n");
return;
}
if (name_len <= UBI_VOL_NAME_MAX &&
strnlen(&r->name[0], name_len + 1) == name_len) {
pr_err("\tname %s\n", &r->name[0]);
} else {
pr_err("\t1st 5 characters of name: %c%c%c%c%c\n",
r->name[0], r->name[1], r->name[2], r->name[3],
r->name[4]);
}
pr_err("\tcrc %#08x\n", be32_to_cpu(r->crc));
}
/**
* ubi_dump_av - dump a &struct ubi_ainf_volume object.
* @av: the object to dump
*/
void ubi_dump_av(const struct ubi_ainf_volume *av)
{
pr_err("Volume attaching information dump:\n");
pr_err("\tvol_id %d\n", av->vol_id);
pr_err("\thighest_lnum %d\n", av->highest_lnum);
pr_err("\tleb_count %d\n", av->leb_count);
pr_err("\tcompat %d\n", av->compat);
pr_err("\tvol_type %d\n", av->vol_type);
pr_err("\tused_ebs %d\n", av->used_ebs);
pr_err("\tlast_data_size %d\n", av->last_data_size);
pr_err("\tdata_pad %d\n", av->data_pad);
}
/**
* ubi_dump_aeb - dump a &struct ubi_ainf_peb object.
* @aeb: the object to dump
* @type: object type: 0 - not corrupted, 1 - corrupted
*/
void ubi_dump_aeb(const struct ubi_ainf_peb *aeb, int type)
{
pr_err("eraseblock attaching information dump:\n");
pr_err("\tec %d\n", aeb->ec);
pr_err("\tpnum %d\n", aeb->pnum);
if (type == 0) {
pr_err("\tlnum %d\n", aeb->lnum);
pr_err("\tscrub %d\n", aeb->scrub);
pr_err("\tsqnum %llu\n", aeb->sqnum);
}
}
/**
* ubi_dump_mkvol_req - dump a &struct ubi_mkvol_req object.
* @req: the object to dump
*/
void ubi_dump_mkvol_req(const struct ubi_mkvol_req *req)
{
char nm[17];
pr_err("Volume creation request dump:\n");
pr_err("\tvol_id %d\n", req->vol_id);
pr_err("\talignment %d\n", req->alignment);
pr_err("\tbytes %lld\n", (long long)req->bytes);
pr_err("\tvol_type %d\n", req->vol_type);
pr_err("\tname_len %d\n", req->name_len);
memcpy(nm, req->name, 16);
nm[16] = 0;
pr_err("\t1st 16 characters of name: %s\n", nm);
}
/*
* Root directory for UBI stuff in debugfs. Contains sub-directories which
* contain the stuff specific to particular UBI devices.
*/
static struct dentry *dfs_rootdir;
/**
* ubi_debugfs_init - create UBI debugfs directory.
*
* Create UBI debugfs directory. Returns zero in case of success and a negative
* error code in case of failure.
*/
int ubi_debugfs_init(void)
{
if (!IS_ENABLED(CONFIG_DEBUG_FS))
return 0;
dfs_rootdir = debugfs_create_dir("ubi", NULL);
if (IS_ERR_OR_NULL(dfs_rootdir)) {
int err = dfs_rootdir ? -ENODEV : PTR_ERR(dfs_rootdir);
pr_err("UBI error: cannot create \"ubi\" debugfs directory, error %d\n",
err);
return err;
}
return 0;
}
/**
* ubi_debugfs_exit - remove UBI debugfs directory.
*/
void ubi_debugfs_exit(void)
{
if (IS_ENABLED(CONFIG_DEBUG_FS))
debugfs_remove(dfs_rootdir);
}
/* Read an UBI debugfs file */
static ssize_t dfs_file_read(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
unsigned long ubi_num = (unsigned long)file->private_data;
struct dentry *dent = file->f_path.dentry;
struct ubi_device *ubi;
struct ubi_debug_info *d;
char buf[8];
int val;
ubi = ubi_get_device(ubi_num);
if (!ubi)
return -ENODEV;
d = &ubi->dbg;
if (dent == d->dfs_chk_gen)
val = d->chk_gen;
else if (dent == d->dfs_chk_io)
val = d->chk_io;
else if (dent == d->dfs_chk_fastmap)
val = d->chk_fastmap;
else if (dent == d->dfs_disable_bgt)
val = d->disable_bgt;
else if (dent == d->dfs_emulate_bitflips)
val = d->emulate_bitflips;
else if (dent == d->dfs_emulate_io_failures)
val = d->emulate_io_failures;
else if (dent == d->dfs_emulate_power_cut) {
snprintf(buf, sizeof(buf), "%u\n", d->emulate_power_cut);
count = simple_read_from_buffer(user_buf, count, ppos,
buf, strlen(buf));
goto out;
} else if (dent == d->dfs_power_cut_min) {
snprintf(buf, sizeof(buf), "%u\n", d->power_cut_min);
count = simple_read_from_buffer(user_buf, count, ppos,
buf, strlen(buf));
goto out;
} else if (dent == d->dfs_power_cut_max) {
snprintf(buf, sizeof(buf), "%u\n", d->power_cut_max);
count = simple_read_from_buffer(user_buf, count, ppos,
buf, strlen(buf));
goto out;
}
else {
count = -EINVAL;
goto out;
}
if (val)
buf[0] = '1';
else
buf[0] = '0';
buf[1] = '\n';
buf[2] = 0x00;
count = simple_read_from_buffer(user_buf, count, ppos, buf, 2);
out:
ubi_put_device(ubi);
return count;
}
/* Write an UBI debugfs file */
static ssize_t dfs_file_write(struct file *file, const char __user *user_buf,
size_t count, loff_t *ppos)
{
unsigned long ubi_num = (unsigned long)file->private_data;
struct dentry *dent = file->f_path.dentry;
struct ubi_device *ubi;
struct ubi_debug_info *d;
size_t buf_size;
char buf[8] = {0};
int val;
ubi = ubi_get_device(ubi_num);
if (!ubi)
return -ENODEV;
d = &ubi->dbg;
buf_size = min_t(size_t, count, (sizeof(buf) - 1));
if (copy_from_user(buf, user_buf, buf_size)) {
count = -EFAULT;
goto out;
}
if (dent == d->dfs_power_cut_min) {
if (kstrtouint(buf, 0, &d->power_cut_min) != 0)
count = -EINVAL;
goto out;
} else if (dent == d->dfs_power_cut_max) {
if (kstrtouint(buf, 0, &d->power_cut_max) != 0)
count = -EINVAL;
goto out;
} else if (dent == d->dfs_emulate_power_cut) {
if (kstrtoint(buf, 0, &val) != 0)
count = -EINVAL;
d->emulate_power_cut = val;
goto out;
}
if (buf[0] == '1')
val = 1;
else if (buf[0] == '0')
val = 0;
else {
count = -EINVAL;
goto out;
}
if (dent == d->dfs_chk_gen)
d->chk_gen = val;
else if (dent == d->dfs_chk_io)
d->chk_io = val;
else if (dent == d->dfs_chk_fastmap)
d->chk_fastmap = val;
else if (dent == d->dfs_disable_bgt)
d->disable_bgt = val;
else if (dent == d->dfs_emulate_bitflips)
d->emulate_bitflips = val;
else if (dent == d->dfs_emulate_io_failures)
d->emulate_io_failures = val;
else
count = -EINVAL;
out:
ubi_put_device(ubi);
return count;
}
/* File operations for all UBI debugfs files */
static const struct file_operations dfs_fops = {
.read = dfs_file_read,
.write = dfs_file_write,
.open = simple_open,
.llseek = no_llseek,
.owner = THIS_MODULE,
};
/**
* ubi_debugfs_init_dev - initialize debugfs for an UBI device.
* @ubi: UBI device description object
*
* This function creates all debugfs files for UBI device @ubi. Returns zero in
* case of success and a negative error code in case of failure.
*/
int ubi_debugfs_init_dev(struct ubi_device *ubi)
{
int err, n;
unsigned long ubi_num = ubi->ubi_num;
const char *fname;
struct dentry *dent;
struct ubi_debug_info *d = &ubi->dbg;
if (!IS_ENABLED(CONFIG_DEBUG_FS))
return 0;
n = snprintf(d->dfs_dir_name, UBI_DFS_DIR_LEN + 1, UBI_DFS_DIR_NAME,
ubi->ubi_num);
if (n == UBI_DFS_DIR_LEN) {
/* The array size is too small */
fname = UBI_DFS_DIR_NAME;
dent = ERR_PTR(-EINVAL);
goto out;
}
fname = d->dfs_dir_name;
dent = debugfs_create_dir(fname, dfs_rootdir);
if (IS_ERR_OR_NULL(dent))
goto out;
d->dfs_dir = dent;
fname = "chk_gen";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_chk_gen = dent;
fname = "chk_io";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_chk_io = dent;
fname = "chk_fastmap";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_chk_fastmap = dent;
fname = "tst_disable_bgt";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_disable_bgt = dent;
fname = "tst_emulate_bitflips";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_emulate_bitflips = dent;
fname = "tst_emulate_io_failures";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_emulate_io_failures = dent;
fname = "tst_emulate_power_cut";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_emulate_power_cut = dent;
fname = "tst_emulate_power_cut_min";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_power_cut_min = dent;
fname = "tst_emulate_power_cut_max";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_power_cut_max = dent;
return 0;
out_remove:
debugfs_remove_recursive(d->dfs_dir);
out:
err = dent ? PTR_ERR(dent) : -ENODEV;
ubi_err(ubi, "cannot create \"%s\" debugfs file or directory, error %d\n",
fname, err);
return err;
}
/**
* dbg_debug_exit_dev - free all debugfs files corresponding to device @ubi
* @ubi: UBI device description object
*/
void ubi_debugfs_exit_dev(struct ubi_device *ubi)
{
if (IS_ENABLED(CONFIG_DEBUG_FS))
debugfs_remove_recursive(ubi->dbg.dfs_dir);
}
/**
* ubi_dbg_power_cut - emulate a power cut if it is time to do so
* @ubi: UBI device description object
* @caller: Flags set to indicate from where the function is being called
*
* Returns non-zero if a power cut was emulated, zero if not.
*/
int ubi_dbg_power_cut(struct ubi_device *ubi, int caller)
{
unsigned int range;
if ((ubi->dbg.emulate_power_cut & caller) == 0)
return 0;
if (ubi->dbg.power_cut_counter == 0) {
ubi->dbg.power_cut_counter = ubi->dbg.power_cut_min;
if (ubi->dbg.power_cut_max > ubi->dbg.power_cut_min) {
range = ubi->dbg.power_cut_max - ubi->dbg.power_cut_min;
ubi->dbg.power_cut_counter += prandom_u32() % range;
}
return 0;
}
ubi->dbg.power_cut_counter--;
if (ubi->dbg.power_cut_counter)
return 0;
ubi_msg(ubi, "XXXXXXXXXXXXXXX emulating a power cut XXXXXXXXXXXXXXXX");
ubi_ro_mode(ubi);
return 1;
}
| gpl-2.0 |
googyanas/Googy-Max4-CM-Kernel | arch/mips/mm/dma-default.c | 718 | 9190 | /*
* 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) 2000 Ani Joshi <ajoshi@unixbox.com>
* Copyright (C) 2000, 2001, 06 Ralf Baechle <ralf@linux-mips.org>
* swiped from i386, and cloned for MIPS by Geert, polished by Ralf.
*/
#include <linux/types.h>
#include <linux/dma-mapping.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/scatterlist.h>
#include <linux/string.h>
#include <linux/gfp.h>
#include <linux/highmem.h>
#include <asm/cache.h>
#include <asm/io.h>
#include <dma-coherence.h>
static inline struct page *dma_addr_to_page(struct device *dev,
dma_addr_t dma_addr)
{
return pfn_to_page(
plat_dma_addr_to_phys(dev, dma_addr) >> PAGE_SHIFT);
}
/*
* The affected CPUs below in 'cpu_needs_post_dma_flush()' can
* speculatively fill random cachelines with stale data at any time,
* requiring an extra flush post-DMA.
*
* Warning on the terminology - Linux calls an uncached area coherent;
* MIPS terminology calls memory areas with hardware maintained coherency
* coherent.
*/
static inline int cpu_needs_post_dma_flush(struct device *dev)
{
return !plat_device_is_coherent(dev) &&
(current_cpu_type() == CPU_R10000 ||
current_cpu_type() == CPU_R12000 ||
current_cpu_type() == CPU_BMIPS5000);
}
static gfp_t massage_gfp_flags(const struct device *dev, gfp_t gfp)
{
gfp_t dma_flag;
/* ignore region specifiers */
gfp &= ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM);
#ifdef CONFIG_ISA
if (dev == NULL)
dma_flag = __GFP_DMA;
else
#endif
#if defined(CONFIG_ZONE_DMA32) && defined(CONFIG_ZONE_DMA)
if (dev->coherent_dma_mask < DMA_BIT_MASK(32))
dma_flag = __GFP_DMA;
else if (dev->coherent_dma_mask < DMA_BIT_MASK(64))
dma_flag = __GFP_DMA32;
else
#endif
#if defined(CONFIG_ZONE_DMA32) && !defined(CONFIG_ZONE_DMA)
if (dev->coherent_dma_mask < DMA_BIT_MASK(64))
dma_flag = __GFP_DMA32;
else
#endif
#if defined(CONFIG_ZONE_DMA) && !defined(CONFIG_ZONE_DMA32)
if (dev->coherent_dma_mask < DMA_BIT_MASK(64))
dma_flag = __GFP_DMA;
else
#endif
dma_flag = 0;
/* Don't invoke OOM killer */
gfp |= __GFP_NORETRY;
return gfp | dma_flag;
}
void *dma_alloc_noncoherent(struct device *dev, size_t size,
dma_addr_t * dma_handle, gfp_t gfp)
{
void *ret;
gfp = massage_gfp_flags(dev, gfp);
ret = (void *) __get_free_pages(gfp, get_order(size));
if (ret != NULL) {
memset(ret, 0, size);
*dma_handle = plat_map_dma_mem(dev, ret, size);
}
return ret;
}
EXPORT_SYMBOL(dma_alloc_noncoherent);
static void *mips_dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t * dma_handle, gfp_t gfp, struct dma_attrs *attrs)
{
void *ret;
if (dma_alloc_from_coherent(dev, size, dma_handle, &ret))
return ret;
gfp = massage_gfp_flags(dev, gfp);
ret = (void *) __get_free_pages(gfp, get_order(size));
if (ret) {
memset(ret, 0, size);
*dma_handle = plat_map_dma_mem(dev, ret, size);
if (!plat_device_is_coherent(dev)) {
dma_cache_wback_inv((unsigned long) ret, size);
ret = UNCAC_ADDR(ret);
}
}
return ret;
}
void dma_free_noncoherent(struct device *dev, size_t size, void *vaddr,
dma_addr_t dma_handle)
{
plat_unmap_dma_mem(dev, dma_handle, size, DMA_BIDIRECTIONAL);
free_pages((unsigned long) vaddr, get_order(size));
}
EXPORT_SYMBOL(dma_free_noncoherent);
static void mips_dma_free_coherent(struct device *dev, size_t size, void *vaddr,
dma_addr_t dma_handle, struct dma_attrs *attrs)
{
unsigned long addr = (unsigned long) vaddr;
int order = get_order(size);
if (dma_release_from_coherent(dev, order, vaddr))
return;
plat_unmap_dma_mem(dev, dma_handle, size, DMA_BIDIRECTIONAL);
if (!plat_device_is_coherent(dev))
addr = CAC_ADDR(addr);
free_pages(addr, get_order(size));
}
static inline void __dma_sync_virtual(void *addr, size_t size,
enum dma_data_direction direction)
{
switch (direction) {
case DMA_TO_DEVICE:
dma_cache_wback((unsigned long)addr, size);
break;
case DMA_FROM_DEVICE:
dma_cache_inv((unsigned long)addr, size);
break;
case DMA_BIDIRECTIONAL:
dma_cache_wback_inv((unsigned long)addr, size);
break;
default:
BUG();
}
}
/*
* A single sg entry may refer to multiple physically contiguous
* pages. But we still need to process highmem pages individually.
* If highmem is not configured then the bulk of this loop gets
* optimized out.
*/
static inline void __dma_sync(struct page *page,
unsigned long offset, size_t size, enum dma_data_direction direction)
{
size_t left = size;
do {
size_t len = left;
if (PageHighMem(page)) {
void *addr;
if (offset + len > PAGE_SIZE) {
if (offset >= PAGE_SIZE) {
page += offset >> PAGE_SHIFT;
offset &= ~PAGE_MASK;
}
len = PAGE_SIZE - offset;
}
addr = kmap_atomic(page);
__dma_sync_virtual(addr + offset, len, direction);
kunmap_atomic(addr);
} else
__dma_sync_virtual(page_address(page) + offset,
size, direction);
offset = 0;
page++;
left -= len;
} while (left);
}
static void mips_dma_unmap_page(struct device *dev, dma_addr_t dma_addr,
size_t size, enum dma_data_direction direction, struct dma_attrs *attrs)
{
if (cpu_needs_post_dma_flush(dev))
__dma_sync(dma_addr_to_page(dev, dma_addr),
dma_addr & ~PAGE_MASK, size, direction);
plat_unmap_dma_mem(dev, dma_addr, size, direction);
}
static int mips_dma_map_sg(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction direction, struct dma_attrs *attrs)
{
int i;
for (i = 0; i < nents; i++, sg++) {
if (!plat_device_is_coherent(dev))
__dma_sync(sg_page(sg), sg->offset, sg->length,
direction);
sg->dma_address = plat_map_dma_mem_page(dev, sg_page(sg)) +
sg->offset;
}
return nents;
}
static dma_addr_t mips_dma_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
if (!plat_device_is_coherent(dev))
__dma_sync(page, offset, size, direction);
return plat_map_dma_mem_page(dev, page) + offset;
}
static void mips_dma_unmap_sg(struct device *dev, struct scatterlist *sg,
int nhwentries, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
int i;
for (i = 0; i < nhwentries; i++, sg++) {
if (!plat_device_is_coherent(dev) &&
direction != DMA_TO_DEVICE)
__dma_sync(sg_page(sg), sg->offset, sg->length,
direction);
plat_unmap_dma_mem(dev, sg->dma_address, sg->length, direction);
}
}
static void mips_dma_sync_single_for_cpu(struct device *dev,
dma_addr_t dma_handle, size_t size, enum dma_data_direction direction)
{
if (cpu_needs_post_dma_flush(dev))
__dma_sync(dma_addr_to_page(dev, dma_handle),
dma_handle & ~PAGE_MASK, size, direction);
}
static void mips_dma_sync_single_for_device(struct device *dev,
dma_addr_t dma_handle, size_t size, enum dma_data_direction direction)
{
plat_extra_sync_for_device(dev);
if (!plat_device_is_coherent(dev))
__dma_sync(dma_addr_to_page(dev, dma_handle),
dma_handle & ~PAGE_MASK, size, direction);
}
static void mips_dma_sync_sg_for_cpu(struct device *dev,
struct scatterlist *sg, int nelems, enum dma_data_direction direction)
{
int i;
/* Make sure that gcc doesn't leave the empty loop body. */
for (i = 0; i < nelems; i++, sg++) {
if (cpu_needs_post_dma_flush(dev))
__dma_sync(sg_page(sg), sg->offset, sg->length,
direction);
}
}
static void mips_dma_sync_sg_for_device(struct device *dev,
struct scatterlist *sg, int nelems, enum dma_data_direction direction)
{
int i;
/* Make sure that gcc doesn't leave the empty loop body. */
for (i = 0; i < nelems; i++, sg++) {
if (!plat_device_is_coherent(dev))
__dma_sync(sg_page(sg), sg->offset, sg->length,
direction);
}
}
int mips_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
{
return plat_dma_mapping_error(dev, dma_addr);
}
int mips_dma_supported(struct device *dev, u64 mask)
{
return plat_dma_supported(dev, mask);
}
void dma_cache_sync(struct device *dev, void *vaddr, size_t size,
enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
plat_extra_sync_for_device(dev);
if (!plat_device_is_coherent(dev))
__dma_sync_virtual(vaddr, size, direction);
}
EXPORT_SYMBOL(dma_cache_sync);
static struct dma_map_ops mips_default_dma_map_ops = {
.alloc = mips_dma_alloc_coherent,
.free = mips_dma_free_coherent,
.map_page = mips_dma_map_page,
.unmap_page = mips_dma_unmap_page,
.map_sg = mips_dma_map_sg,
.unmap_sg = mips_dma_unmap_sg,
.sync_single_for_cpu = mips_dma_sync_single_for_cpu,
.sync_single_for_device = mips_dma_sync_single_for_device,
.sync_sg_for_cpu = mips_dma_sync_sg_for_cpu,
.sync_sg_for_device = mips_dma_sync_sg_for_device,
.mapping_error = mips_dma_mapping_error,
.dma_supported = mips_dma_supported
};
struct dma_map_ops *mips_dma_map_ops = &mips_default_dma_map_ops;
EXPORT_SYMBOL(mips_dma_map_ops);
#define PREALLOC_DMA_DEBUG_ENTRIES (1 << 16)
static int __init mips_dma_init(void)
{
dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES);
return 0;
}
fs_initcall(mips_dma_init);
| gpl-2.0 |
SteveLinCH/linux | drivers/net/wireless/realtek/rtlwifi/rtl8188ee/trx.c | 974 | 24493 | /******************************************************************************
*
* Copyright(c) 2009-2013 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../pci.h"
#include "../base.h"
#include "../stats.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "trx.h"
#include "led.h"
#include "dm.h"
#include "phy.h"
static u8 _rtl88ee_map_hwqueue_to_fwqueue(struct sk_buff *skb, u8 hw_queue)
{
__le16 fc = rtl_get_fc(skb);
if (unlikely(ieee80211_is_beacon(fc)))
return QSLT_BEACON;
if (ieee80211_is_mgmt(fc) || ieee80211_is_ctl(fc))
return QSLT_MGNT;
return skb->priority;
}
static void _rtl88ee_query_rxphystatus(struct ieee80211_hw *hw,
struct rtl_stats *pstatus, u8 *pdesc,
struct rx_fwinfo_88e *p_drvinfo,
bool bpacket_match_bssid,
bool bpacket_toself, bool packet_beacon)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtlpriv);
struct phy_sts_cck_8192s_t *cck_buf;
struct phy_status_rpt *phystrpt =
(struct phy_status_rpt *)p_drvinfo;
struct rtl_dm *rtldm = rtl_dm(rtl_priv(hw));
char rx_pwr_all = 0, rx_pwr[4];
u8 rf_rx_num = 0, evm, pwdb_all;
u8 i, max_spatial_stream;
u32 rssi, total_rssi = 0;
bool is_cck = pstatus->is_cck;
u8 lan_idx, vga_idx;
/* Record it for next packet processing */
pstatus->packet_matchbssid = bpacket_match_bssid;
pstatus->packet_toself = bpacket_toself;
pstatus->packet_beacon = packet_beacon;
pstatus->rx_mimo_signalquality[0] = -1;
pstatus->rx_mimo_signalquality[1] = -1;
if (is_cck) {
u8 cck_highpwr;
u8 cck_agc_rpt;
/* CCK Driver info Structure is not the same as OFDM packet. */
cck_buf = (struct phy_sts_cck_8192s_t *)p_drvinfo;
cck_agc_rpt = cck_buf->cck_agc_rpt;
/* (1)Hardware does not provide RSSI for CCK
* (2)PWDB, Average PWDB cacluated by
* hardware (for rate adaptive)
*/
if (ppsc->rfpwr_state == ERFON)
cck_highpwr =
(u8)rtl_get_bbreg(hw, RFPGA0_XA_HSSIPARAMETER2,
BIT(9));
else
cck_highpwr = false;
lan_idx = ((cck_agc_rpt & 0xE0) >> 5);
vga_idx = (cck_agc_rpt & 0x1f);
switch (lan_idx) {
case 7:
if (vga_idx <= 27)
/*VGA_idx = 27~2*/
rx_pwr_all = -100 + 2*(27-vga_idx);
else
rx_pwr_all = -100;
break;
case 6:
/*VGA_idx = 2~0*/
rx_pwr_all = -48 + 2*(2-vga_idx);
break;
case 5:
/*VGA_idx = 7~5*/
rx_pwr_all = -42 + 2*(7-vga_idx);
break;
case 4:
/*VGA_idx = 7~4*/
rx_pwr_all = -36 + 2*(7-vga_idx);
break;
case 3:
/*VGA_idx = 7~0*/
rx_pwr_all = -24 + 2*(7-vga_idx);
break;
case 2:
if (cck_highpwr)
/*VGA_idx = 5~0*/
rx_pwr_all = -12 + 2*(5-vga_idx);
else
rx_pwr_all = -6 + 2*(5-vga_idx);
break;
case 1:
rx_pwr_all = 8-2*vga_idx;
break;
case 0:
rx_pwr_all = 14-2*vga_idx;
break;
default:
break;
}
rx_pwr_all += 6;
pwdb_all = rtl_query_rxpwrpercentage(rx_pwr_all);
/* CCK gain is smaller than OFDM/MCS gain, */
/* so we add gain diff by experiences, the val is 6 */
pwdb_all += 6;
if (pwdb_all > 100)
pwdb_all = 100;
/* modify the offset to make the same
* gain index with OFDM.
*/
if (pwdb_all > 34 && pwdb_all <= 42)
pwdb_all -= 2;
else if (pwdb_all > 26 && pwdb_all <= 34)
pwdb_all -= 6;
else if (pwdb_all > 14 && pwdb_all <= 26)
pwdb_all -= 8;
else if (pwdb_all > 4 && pwdb_all <= 14)
pwdb_all -= 4;
if (!cck_highpwr) {
if (pwdb_all >= 80)
pwdb_all = ((pwdb_all-80)<<1) +
((pwdb_all-80)>>1) + 80;
else if ((pwdb_all <= 78) && (pwdb_all >= 20))
pwdb_all += 3;
if (pwdb_all > 100)
pwdb_all = 100;
}
pstatus->rx_pwdb_all = pwdb_all;
pstatus->recvsignalpower = rx_pwr_all;
/* (3) Get Signal Quality (EVM) */
if (bpacket_match_bssid) {
u8 sq;
if (pstatus->rx_pwdb_all > 40)
sq = 100;
else {
sq = cck_buf->sq_rpt;
if (sq > 64)
sq = 0;
else if (sq < 20)
sq = 100;
else
sq = ((64 - sq) * 100) / 44;
}
pstatus->signalquality = sq;
pstatus->rx_mimo_signalquality[0] = sq;
pstatus->rx_mimo_signalquality[1] = -1;
}
} else {
rtlpriv->dm.rfpath_rxenable[0] =
rtlpriv->dm.rfpath_rxenable[1] = true;
/* (1)Get RSSI for HT rate */
for (i = RF90_PATH_A; i < RF6052_MAX_PATH; i++) {
/* we will judge RF RX path now. */
if (rtlpriv->dm.rfpath_rxenable[i])
rf_rx_num++;
rx_pwr[i] = ((p_drvinfo->gain_trsw[i] &
0x3f) * 2) - 110;
/* Translate DBM to percentage. */
rssi = rtl_query_rxpwrpercentage(rx_pwr[i]);
total_rssi += rssi;
/* Get Rx snr value in DB */
rtlpriv->stats.rx_snr_db[i] =
(long)(p_drvinfo->rxsnr[i] / 2);
/* Record Signal Strength for next packet */
if (bpacket_match_bssid)
pstatus->rx_mimo_signalstrength[i] = (u8)rssi;
}
/* (2)PWDB, Average PWDB cacluated by
* hardware (for rate adaptive)
*/
rx_pwr_all = ((p_drvinfo->pwdb_all >> 1) & 0x7f) - 110;
pwdb_all = rtl_query_rxpwrpercentage(rx_pwr_all);
pstatus->rx_pwdb_all = pwdb_all;
pstatus->rxpower = rx_pwr_all;
pstatus->recvsignalpower = rx_pwr_all;
/* (3)EVM of HT rate */
if (pstatus->is_ht && pstatus->rate >= DESC92C_RATEMCS8 &&
pstatus->rate <= DESC92C_RATEMCS15)
max_spatial_stream = 2;
else
max_spatial_stream = 1;
for (i = 0; i < max_spatial_stream; i++) {
evm = rtl_evm_db_to_percentage(p_drvinfo->rxevm[i]);
if (bpacket_match_bssid) {
/* Fill value in RFD, Get the first
* spatial stream onlyi
*/
if (i == 0)
pstatus->signalquality =
(u8)(evm & 0xff);
pstatus->rx_mimo_signalquality[i] =
(u8)(evm & 0xff);
}
}
}
/* UI BSS List signal strength(in percentage),
* make it good looking, from 0~100.
*/
if (is_cck)
pstatus->signalstrength = (u8)(rtl_signal_scale_mapping(hw,
pwdb_all));
else if (rf_rx_num != 0)
pstatus->signalstrength = (u8)(rtl_signal_scale_mapping(hw,
total_rssi /= rf_rx_num));
/*HW antenna diversity*/
rtldm->fat_table.antsel_rx_keep_0 = phystrpt->ant_sel;
rtldm->fat_table.antsel_rx_keep_1 = phystrpt->ant_sel_b;
rtldm->fat_table.antsel_rx_keep_2 = phystrpt->antsel_rx_keep_2;
}
static void _rtl88ee_smart_antenna(struct ieee80211_hw *hw,
struct rtl_stats *pstatus)
{
struct rtl_dm *rtldm = rtl_dm(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u8 antsel_tr_mux;
struct fast_ant_training *pfat_table = &rtldm->fat_table;
if (rtlefuse->antenna_div_type == CG_TRX_SMART_ANTDIV) {
if (pfat_table->fat_state == FAT_TRAINING_STATE) {
if (pstatus->packet_toself) {
antsel_tr_mux =
(pfat_table->antsel_rx_keep_2 << 2) |
(pfat_table->antsel_rx_keep_1 << 1) |
pfat_table->antsel_rx_keep_0;
pfat_table->ant_sum[antsel_tr_mux] +=
pstatus->rx_pwdb_all;
pfat_table->ant_cnt[antsel_tr_mux]++;
}
}
} else if ((rtlefuse->antenna_div_type == CG_TRX_HW_ANTDIV) ||
(rtlefuse->antenna_div_type == CGCS_RX_HW_ANTDIV)) {
if (pstatus->packet_toself || pstatus->packet_matchbssid) {
antsel_tr_mux = (pfat_table->antsel_rx_keep_2 << 2) |
(pfat_table->antsel_rx_keep_1 << 1) |
pfat_table->antsel_rx_keep_0;
rtl88e_dm_ant_sel_statistics(hw, antsel_tr_mux, 0,
pstatus->rx_pwdb_all);
}
}
}
static void _rtl88ee_translate_rx_signal_stuff(struct ieee80211_hw *hw,
struct sk_buff *skb,
struct rtl_stats *pstatus,
u8 *pdesc,
struct rx_fwinfo_88e *p_drvinfo)
{
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
struct ieee80211_hdr *hdr;
u8 *tmp_buf;
u8 *praddr;
u8 *psaddr;
__le16 fc;
bool packet_matchbssid, packet_toself, packet_beacon;
tmp_buf = skb->data + pstatus->rx_drvinfo_size + pstatus->rx_bufshift;
hdr = (struct ieee80211_hdr *)tmp_buf;
fc = hdr->frame_control;
praddr = hdr->addr1;
psaddr = ieee80211_get_SA(hdr);
memcpy(pstatus->psaddr, psaddr, ETH_ALEN);
packet_matchbssid = ((!ieee80211_is_ctl(fc)) &&
(ether_addr_equal(mac->bssid, ieee80211_has_tods(fc) ?
hdr->addr1 : ieee80211_has_fromds(fc) ?
hdr->addr2 : hdr->addr3)) &&
(!pstatus->hwerror) &&
(!pstatus->crc) && (!pstatus->icv));
packet_toself = packet_matchbssid &&
(ether_addr_equal(praddr, rtlefuse->dev_addr));
if (ieee80211_is_beacon(hdr->frame_control))
packet_beacon = true;
else
packet_beacon = false;
_rtl88ee_query_rxphystatus(hw, pstatus, pdesc, p_drvinfo,
packet_matchbssid, packet_toself,
packet_beacon);
_rtl88ee_smart_antenna(hw, pstatus);
rtl_process_phyinfo(hw, tmp_buf, pstatus);
}
static void _rtl88ee_insert_emcontent(struct rtl_tcb_desc *ptcb_desc,
u8 *virtualaddress)
{
u32 dwtmp = 0;
memset(virtualaddress, 0, 8);
SET_EARLYMODE_PKTNUM(virtualaddress, ptcb_desc->empkt_num);
if (ptcb_desc->empkt_num == 1) {
dwtmp = ptcb_desc->empkt_len[0];
} else {
dwtmp = ptcb_desc->empkt_len[0];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[1];
}
SET_EARLYMODE_LEN0(virtualaddress, dwtmp);
if (ptcb_desc->empkt_num <= 3) {
dwtmp = ptcb_desc->empkt_len[2];
} else {
dwtmp = ptcb_desc->empkt_len[2];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[3];
}
SET_EARLYMODE_LEN1(virtualaddress, dwtmp);
if (ptcb_desc->empkt_num <= 5) {
dwtmp = ptcb_desc->empkt_len[4];
} else {
dwtmp = ptcb_desc->empkt_len[4];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[5];
}
SET_EARLYMODE_LEN2_1(virtualaddress, dwtmp & 0xF);
SET_EARLYMODE_LEN2_2(virtualaddress, dwtmp >> 4);
if (ptcb_desc->empkt_num <= 7) {
dwtmp = ptcb_desc->empkt_len[6];
} else {
dwtmp = ptcb_desc->empkt_len[6];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[7];
}
SET_EARLYMODE_LEN3(virtualaddress, dwtmp);
if (ptcb_desc->empkt_num <= 9) {
dwtmp = ptcb_desc->empkt_len[8];
} else {
dwtmp = ptcb_desc->empkt_len[8];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[9];
}
SET_EARLYMODE_LEN4(virtualaddress, dwtmp);
}
bool rtl88ee_rx_query_desc(struct ieee80211_hw *hw,
struct rtl_stats *status,
struct ieee80211_rx_status *rx_status,
u8 *pdesc, struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rx_fwinfo_88e *p_drvinfo;
struct ieee80211_hdr *hdr;
u32 phystatus = GET_RX_DESC_PHYST(pdesc);
status->packet_report_type = (u8)GET_RX_STATUS_DESC_RPT_SEL(pdesc);
if (status->packet_report_type == TX_REPORT2)
status->length = (u16)GET_RX_RPT2_DESC_PKT_LEN(pdesc);
else
status->length = (u16)GET_RX_DESC_PKT_LEN(pdesc);
status->rx_drvinfo_size = (u8)GET_RX_DESC_DRV_INFO_SIZE(pdesc) *
RX_DRV_INFO_SIZE_UNIT;
status->rx_bufshift = (u8)(GET_RX_DESC_SHIFT(pdesc) & 0x03);
status->icv = (u16)GET_RX_DESC_ICV(pdesc);
status->crc = (u16)GET_RX_DESC_CRC32(pdesc);
status->hwerror = (status->crc | status->icv);
status->decrypted = !GET_RX_DESC_SWDEC(pdesc);
status->rate = (u8)GET_RX_DESC_RXMCS(pdesc);
status->shortpreamble = (u16)GET_RX_DESC_SPLCP(pdesc);
status->isampdu = (bool) (GET_RX_DESC_PAGGR(pdesc) == 1);
status->isfirst_ampdu = (bool)((GET_RX_DESC_PAGGR(pdesc) == 1) &&
(GET_RX_DESC_FAGGR(pdesc) == 1));
if (status->packet_report_type == NORMAL_RX)
status->timestamp_low = GET_RX_DESC_TSFL(pdesc);
status->rx_is40Mhzpacket = (bool) GET_RX_DESC_BW(pdesc);
status->is_ht = (bool)GET_RX_DESC_RXHT(pdesc);
status->is_cck = RTL8188_RX_HAL_IS_CCK_RATE(status->rate);
status->macid = GET_RX_DESC_MACID(pdesc);
if (GET_RX_STATUS_DESC_MAGIC_MATCH(pdesc))
status->wake_match = BIT(2);
else if (GET_RX_STATUS_DESC_MAGIC_MATCH(pdesc))
status->wake_match = BIT(1);
else if (GET_RX_STATUS_DESC_UNICAST_MATCH(pdesc))
status->wake_match = BIT(0);
else
status->wake_match = 0;
if (status->wake_match)
RT_TRACE(rtlpriv, COMP_RXDESC, DBG_LOUD,
"GGGGGGGGGGGGGet Wakeup Packet!! WakeMatch=%d\n",
status->wake_match);
rx_status->freq = hw->conf.chandef.chan->center_freq;
rx_status->band = hw->conf.chandef.chan->band;
hdr = (struct ieee80211_hdr *)(skb->data + status->rx_drvinfo_size
+ status->rx_bufshift);
if (status->crc)
rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
if (status->rx_is40Mhzpacket)
rx_status->flag |= RX_FLAG_40MHZ;
if (status->is_ht)
rx_status->flag |= RX_FLAG_HT;
rx_status->flag |= RX_FLAG_MACTIME_START;
/* hw will set status->decrypted true, if it finds the
* frame is open data frame or mgmt frame.
* So hw will not decryption robust managment frame
* for IEEE80211w but still set status->decrypted
* true, so here we should set it back to undecrypted
* for IEEE80211w frame, and mac80211 sw will help
* to decrypt it
*/
if (status->decrypted) {
if ((!_ieee80211_is_robust_mgmt_frame(hdr)) &&
(ieee80211_has_protected(hdr->frame_control)))
rx_status->flag |= RX_FLAG_DECRYPTED;
else
rx_status->flag &= ~RX_FLAG_DECRYPTED;
}
/* rate_idx: index of data rate into band's
* supported rates or MCS index if HT rates
* are use (RX_FLAG_HT)
* Notice: this is diff with windows define
*/
rx_status->rate_idx = rtlwifi_rate_mapping(hw, status->is_ht,
false, status->rate);
rx_status->mactime = status->timestamp_low;
if (phystatus == true) {
p_drvinfo = (struct rx_fwinfo_88e *)(skb->data +
status->rx_bufshift);
_rtl88ee_translate_rx_signal_stuff(hw,
skb, status, pdesc,
p_drvinfo);
}
rx_status->signal = status->recvsignalpower + 10;
if (status->packet_report_type == TX_REPORT2) {
status->macid_valid_entry[0] =
GET_RX_RPT2_DESC_MACID_VALID_1(pdesc);
status->macid_valid_entry[1] =
GET_RX_RPT2_DESC_MACID_VALID_2(pdesc);
}
return true;
}
void rtl88ee_tx_fill_desc(struct ieee80211_hw *hw,
struct ieee80211_hdr *hdr, u8 *pdesc_tx,
u8 *txbd, struct ieee80211_tx_info *info,
struct ieee80211_sta *sta,
struct sk_buff *skb,
u8 hw_queue, struct rtl_tcb_desc *ptcb_desc)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtlpriv);
u8 *pdesc = (u8 *)pdesc_tx;
u16 seq_number;
__le16 fc = hdr->frame_control;
unsigned int buf_len = 0;
unsigned int skb_len = skb->len;
u8 fw_qsel = _rtl88ee_map_hwqueue_to_fwqueue(skb, hw_queue);
bool firstseg = ((hdr->seq_ctrl &
cpu_to_le16(IEEE80211_SCTL_FRAG)) == 0);
bool lastseg = ((hdr->frame_control &
cpu_to_le16(IEEE80211_FCTL_MOREFRAGS)) == 0);
dma_addr_t mapping;
u8 bw_40 = 0;
u8 short_gi = 0;
if (mac->opmode == NL80211_IFTYPE_STATION) {
bw_40 = mac->bw_40;
} else if (mac->opmode == NL80211_IFTYPE_AP ||
mac->opmode == NL80211_IFTYPE_ADHOC) {
if (sta)
bw_40 = sta->ht_cap.cap &
IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
seq_number = (le16_to_cpu(hdr->seq_ctrl) & IEEE80211_SCTL_SEQ) >> 4;
rtl_get_tcb_desc(hw, info, sta, skb, ptcb_desc);
/* reserve 8 byte for AMPDU early mode */
if (rtlhal->earlymode_enable) {
skb_push(skb, EM_HDR_LEN);
memset(skb->data, 0, EM_HDR_LEN);
}
buf_len = skb->len;
mapping = pci_map_single(rtlpci->pdev, skb->data, skb->len,
PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(rtlpci->pdev, mapping)) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"DMA mapping error");
return;
}
CLEAR_PCI_TX_DESC_CONTENT(pdesc, sizeof(struct tx_desc_88e));
if (ieee80211_is_nullfunc(fc) || ieee80211_is_ctl(fc)) {
firstseg = true;
lastseg = true;
}
if (firstseg) {
if (rtlhal->earlymode_enable) {
SET_TX_DESC_PKT_OFFSET(pdesc, 1);
SET_TX_DESC_OFFSET(pdesc, USB_HWDESC_HEADER_LEN +
EM_HDR_LEN);
if (ptcb_desc->empkt_num) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"Insert 8 byte.pTcb->EMPktNum:%d\n",
ptcb_desc->empkt_num);
_rtl88ee_insert_emcontent(ptcb_desc,
(u8 *)(skb->data));
}
} else {
SET_TX_DESC_OFFSET(pdesc, USB_HWDESC_HEADER_LEN);
}
ptcb_desc->use_driver_rate = true;
SET_TX_DESC_TX_RATE(pdesc, ptcb_desc->hw_rate);
if (ptcb_desc->hw_rate > DESC92C_RATEMCS0)
short_gi = (ptcb_desc->use_shortgi) ? 1 : 0;
else
short_gi = (ptcb_desc->use_shortpreamble) ? 1 : 0;
SET_TX_DESC_DATA_SHORTGI(pdesc, short_gi);
if (info->flags & IEEE80211_TX_CTL_AMPDU) {
SET_TX_DESC_AGG_ENABLE(pdesc, 1);
SET_TX_DESC_MAX_AGG_NUM(pdesc, 0x14);
}
SET_TX_DESC_SEQ(pdesc, seq_number);
SET_TX_DESC_RTS_ENABLE(pdesc, ((ptcb_desc->rts_enable &&
!ptcb_desc->cts_enable) ? 1 : 0));
SET_TX_DESC_HW_RTS_ENABLE(pdesc, 0);
SET_TX_DESC_CTS2SELF(pdesc, ((ptcb_desc->cts_enable) ? 1 : 0));
SET_TX_DESC_RTS_STBC(pdesc, ((ptcb_desc->rts_stbc) ? 1 : 0));
SET_TX_DESC_RTS_RATE(pdesc, ptcb_desc->rts_rate);
SET_TX_DESC_RTS_BW(pdesc, 0);
SET_TX_DESC_RTS_SC(pdesc, ptcb_desc->rts_sc);
SET_TX_DESC_RTS_SHORT(pdesc,
((ptcb_desc->rts_rate <= DESC92C_RATE54M) ?
(ptcb_desc->rts_use_shortpreamble ? 1 : 0) :
(ptcb_desc->rts_use_shortgi ? 1 : 0)));
if (ptcb_desc->tx_enable_sw_calc_duration)
SET_TX_DESC_NAV_USE_HDR(pdesc, 1);
if (bw_40) {
if (ptcb_desc->packet_bw == HT_CHANNEL_WIDTH_20_40) {
SET_TX_DESC_DATA_BW(pdesc, 1);
SET_TX_DESC_TX_SUB_CARRIER(pdesc, 3);
} else {
SET_TX_DESC_DATA_BW(pdesc, 0);
SET_TX_DESC_TX_SUB_CARRIER(pdesc,
mac->cur_40_prime_sc);
}
} else {
SET_TX_DESC_DATA_BW(pdesc, 0);
SET_TX_DESC_TX_SUB_CARRIER(pdesc, 0);
}
SET_TX_DESC_LINIP(pdesc, 0);
SET_TX_DESC_PKT_SIZE(pdesc, (u16)skb_len);
if (sta) {
u8 ampdu_density = sta->ht_cap.ampdu_density;
SET_TX_DESC_AMPDU_DENSITY(pdesc, ampdu_density);
}
if (info->control.hw_key) {
struct ieee80211_key_conf *keyconf;
keyconf = info->control.hw_key;
switch (keyconf->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
case WLAN_CIPHER_SUITE_TKIP:
SET_TX_DESC_SEC_TYPE(pdesc, 0x1);
break;
case WLAN_CIPHER_SUITE_CCMP:
SET_TX_DESC_SEC_TYPE(pdesc, 0x3);
break;
default:
SET_TX_DESC_SEC_TYPE(pdesc, 0x0);
break;
}
}
SET_TX_DESC_QUEUE_SEL(pdesc, fw_qsel);
SET_TX_DESC_DATA_RATE_FB_LIMIT(pdesc, 0x1F);
SET_TX_DESC_RTS_RATE_FB_LIMIT(pdesc, 0xF);
SET_TX_DESC_DISABLE_FB(pdesc, ptcb_desc->disable_ratefallback ?
1 : 0);
SET_TX_DESC_USE_RATE(pdesc, ptcb_desc->use_driver_rate ? 1 : 0);
/*SET_TX_DESC_PWR_STATUS(pdesc, pwr_status);*/
/* Set TxRate and RTSRate in TxDesc */
/* This prevent Tx initial rate of new-coming packets */
/* from being overwritten by retried packet rate.*/
if (!ptcb_desc->use_driver_rate) {
/*SET_TX_DESC_RTS_RATE(pdesc, 0x08); */
/* SET_TX_DESC_TX_RATE(pdesc, 0x0b); */
}
if (ieee80211_is_data_qos(fc)) {
if (mac->rdg_en) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"Enable RDG function.\n");
SET_TX_DESC_RDG_ENABLE(pdesc, 1);
SET_TX_DESC_HTC(pdesc, 1);
}
}
}
SET_TX_DESC_FIRST_SEG(pdesc, (firstseg ? 1 : 0));
SET_TX_DESC_LAST_SEG(pdesc, (lastseg ? 1 : 0));
SET_TX_DESC_TX_BUFFER_SIZE(pdesc, (u16)buf_len);
SET_TX_DESC_TX_BUFFER_ADDRESS(pdesc, mapping);
if (rtlpriv->dm.useramask) {
SET_TX_DESC_RATE_ID(pdesc, ptcb_desc->ratr_index);
SET_TX_DESC_MACID(pdesc, ptcb_desc->mac_id);
} else {
SET_TX_DESC_RATE_ID(pdesc, 0xC + ptcb_desc->ratr_index);
SET_TX_DESC_MACID(pdesc, ptcb_desc->ratr_index);
}
if (ieee80211_is_data_qos(fc))
SET_TX_DESC_QOS(pdesc, 1);
if (!ieee80211_is_data_qos(fc))
SET_TX_DESC_HWSEQ_EN(pdesc, 1);
SET_TX_DESC_MORE_FRAG(pdesc, (lastseg ? 0 : 1));
if (is_multicast_ether_addr(ieee80211_get_DA(hdr)) ||
is_broadcast_ether_addr(ieee80211_get_DA(hdr))) {
SET_TX_DESC_BMC(pdesc, 1);
}
rtl88e_dm_set_tx_ant_by_tx_info(hw, pdesc, ptcb_desc->mac_id);
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE, "\n");
}
void rtl88ee_tx_fill_cmddesc(struct ieee80211_hw *hw,
u8 *pdesc, bool firstseg,
bool lastseg, struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u8 fw_queue = QSLT_BEACON;
dma_addr_t mapping = pci_map_single(rtlpci->pdev,
skb->data, skb->len,
PCI_DMA_TODEVICE);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)(skb->data);
__le16 fc = hdr->frame_control;
if (pci_dma_mapping_error(rtlpci->pdev, mapping)) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"DMA mapping error");
return;
}
CLEAR_PCI_TX_DESC_CONTENT(pdesc, TX_DESC_SIZE);
if (firstseg)
SET_TX_DESC_OFFSET(pdesc, USB_HWDESC_HEADER_LEN);
SET_TX_DESC_TX_RATE(pdesc, DESC92C_RATE1M);
SET_TX_DESC_SEQ(pdesc, 0);
SET_TX_DESC_LINIP(pdesc, 0);
SET_TX_DESC_QUEUE_SEL(pdesc, fw_queue);
SET_TX_DESC_FIRST_SEG(pdesc, 1);
SET_TX_DESC_LAST_SEG(pdesc, 1);
SET_TX_DESC_TX_BUFFER_SIZE(pdesc, (u16)(skb->len));
SET_TX_DESC_TX_BUFFER_ADDRESS(pdesc, mapping);
SET_TX_DESC_RATE_ID(pdesc, 7);
SET_TX_DESC_MACID(pdesc, 0);
SET_TX_DESC_OWN(pdesc, 1);
SET_TX_DESC_PKT_SIZE(pdesc, (u16)(skb->len));
SET_TX_DESC_FIRST_SEG(pdesc, 1);
SET_TX_DESC_LAST_SEG(pdesc, 1);
SET_TX_DESC_OFFSET(pdesc, 0x20);
SET_TX_DESC_USE_RATE(pdesc, 1);
if (!ieee80211_is_data_qos(fc))
SET_TX_DESC_HWSEQ_EN(pdesc, 1);
RT_PRINT_DATA(rtlpriv, COMP_CMD, DBG_LOUD,
"H2C Tx Cmd Content\n",
pdesc, TX_DESC_SIZE);
}
void rtl88ee_set_desc(struct ieee80211_hw *hw, u8 *pdesc,
bool istx, u8 desc_name, u8 *val)
{
if (istx == true) {
switch (desc_name) {
case HW_DESC_OWN:
SET_TX_DESC_OWN(pdesc, 1);
break;
case HW_DESC_TX_NEXTDESC_ADDR:
SET_TX_DESC_NEXT_DESC_ADDRESS(pdesc, *(u32 *)val);
break;
default:
RT_ASSERT(false, "ERR txdesc :%d not process\n",
desc_name);
break;
}
} else {
switch (desc_name) {
case HW_DESC_RXOWN:
SET_RX_DESC_OWN(pdesc, 1);
break;
case HW_DESC_RXBUFF_ADDR:
SET_RX_DESC_BUFF_ADDR(pdesc, *(u32 *)val);
break;
case HW_DESC_RXPKT_LEN:
SET_RX_DESC_PKT_LEN(pdesc, *(u32 *)val);
break;
case HW_DESC_RXERO:
SET_RX_DESC_EOR(pdesc, 1);
break;
default:
RT_ASSERT(false, "ERR rxdesc :%d not process\n",
desc_name);
break;
}
}
}
u32 rtl88ee_get_desc(u8 *pdesc, bool istx, u8 desc_name)
{
u32 ret = 0;
if (istx == true) {
switch (desc_name) {
case HW_DESC_OWN:
ret = GET_TX_DESC_OWN(pdesc);
break;
case HW_DESC_TXBUFF_ADDR:
ret = GET_TX_DESC_TX_BUFFER_ADDRESS(pdesc);
break;
default:
RT_ASSERT(false, "ERR txdesc :%d not process\n",
desc_name);
break;
}
} else {
switch (desc_name) {
case HW_DESC_OWN:
ret = GET_RX_DESC_OWN(pdesc);
break;
case HW_DESC_RXPKT_LEN:
ret = GET_RX_DESC_PKT_LEN(pdesc);
break;
case HW_DESC_RXBUFF_ADDR:
ret = GET_RX_DESC_BUFF_ADDR(pdesc);
break;
default:
RT_ASSERT(false, "ERR rxdesc :%d not process\n",
desc_name);
break;
}
}
return ret;
}
bool rtl88ee_is_tx_desc_closed(struct ieee80211_hw *hw, u8 hw_queue, u16 index)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl8192_tx_ring *ring = &rtlpci->tx_ring[hw_queue];
u8 *entry = (u8 *)(&ring->desc[ring->idx]);
u8 own = (u8)rtl88ee_get_desc(entry, true, HW_DESC_OWN);
/*beacon packet will only use the first
*descriptor defautly,and the own may not
*be cleared by the hardware
*/
if (own)
return false;
return true;
}
void rtl88ee_tx_polling(struct ieee80211_hw *hw, u8 hw_queue)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (hw_queue == BEACON_QUEUE) {
rtl_write_word(rtlpriv, REG_PCIE_CTRL_REG, BIT(4));
} else {
rtl_write_word(rtlpriv, REG_PCIE_CTRL_REG,
BIT(0) << (hw_queue));
}
}
u32 rtl88ee_rx_command_packet(struct ieee80211_hw *hw,
struct rtl_stats status,
struct sk_buff *skb)
{
return 0;
}
| gpl-2.0 |
pscholl/jennic-usb-zigbee-linux-driver | drivers/hid/hid-sunplus.c | 1486 | 2094 | /*
* HID driver for some sunplus "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2007 Paul Walmsley
* Copyright (c) 2008 Jiri Slaby
*/
/*
* 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/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
static void sp_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int rsize)
{
if (rsize >= 107 && rdesc[104] == 0x26 && rdesc[105] == 0x80 &&
rdesc[106] == 0x03) {
dev_info(&hdev->dev, "fixing up Sunplus Wireless Desktop "
"report descriptor\n");
rdesc[105] = rdesc[110] = 0x03;
rdesc[106] = rdesc[111] = 0x21;
}
}
#define sp_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \
EV_KEY, (c))
static int sp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER)
return 0;
switch (usage->hid & HID_USAGE) {
case 0x2003: sp_map_key_clear(KEY_ZOOMIN); break;
case 0x2103: sp_map_key_clear(KEY_ZOOMOUT); break;
default:
return 0;
}
return 1;
}
static const struct hid_device_id sp_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_SUNPLUS, USB_DEVICE_ID_SUNPLUS_WDESKTOP) },
{ }
};
MODULE_DEVICE_TABLE(hid, sp_devices);
static struct hid_driver sp_driver = {
.name = "sunplus",
.id_table = sp_devices,
.report_fixup = sp_report_fixup,
.input_mapping = sp_input_mapping,
};
static int __init sp_init(void)
{
return hid_register_driver(&sp_driver);
}
static void __exit sp_exit(void)
{
hid_unregister_driver(&sp_driver);
}
module_init(sp_init);
module_exit(sp_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
TimmyTossPot/kernel_endeavoru | drivers/scsi/isci/probe_roms.c | 1998 | 5763 | /*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
* The full GNU General Public License is included in this distribution
* in the file called LICENSE.GPL.
*/
/* probe_roms - scan for oem parameters */
#include <linux/kernel.h>
#include <linux/firmware.h>
#include <linux/uaccess.h>
#include <linux/efi.h>
#include <asm/probe_roms.h>
#include "isci.h"
#include "task.h"
#include "probe_roms.h"
static efi_char16_t isci_efivar_name[] = {
'R', 's', 't', 'S', 'c', 'u', 'O'
};
struct isci_orom *isci_request_oprom(struct pci_dev *pdev)
{
void __iomem *oprom = pci_map_biosrom(pdev);
struct isci_orom *rom = NULL;
size_t len, i;
int j;
char oem_sig[4];
struct isci_oem_hdr oem_hdr;
u8 *tmp, sum;
if (!oprom)
return NULL;
len = pci_biosrom_size(pdev);
rom = devm_kzalloc(&pdev->dev, sizeof(*rom), GFP_KERNEL);
if (!rom) {
dev_warn(&pdev->dev,
"Unable to allocate memory for orom\n");
return NULL;
}
for (i = 0; i < len && rom; i += ISCI_OEM_SIG_SIZE) {
memcpy_fromio(oem_sig, oprom + i, ISCI_OEM_SIG_SIZE);
/* we think we found the OEM table */
if (memcmp(oem_sig, ISCI_OEM_SIG, ISCI_OEM_SIG_SIZE) == 0) {
size_t copy_len;
memcpy_fromio(&oem_hdr, oprom + i, sizeof(oem_hdr));
copy_len = min(oem_hdr.len - sizeof(oem_hdr),
sizeof(*rom));
memcpy_fromio(rom,
oprom + i + sizeof(oem_hdr),
copy_len);
/* calculate checksum */
tmp = (u8 *)&oem_hdr;
for (j = 0, sum = 0; j < sizeof(oem_hdr); j++, tmp++)
sum += *tmp;
tmp = (u8 *)rom;
for (j = 0; j < sizeof(*rom); j++, tmp++)
sum += *tmp;
if (sum != 0) {
dev_warn(&pdev->dev,
"OEM table checksum failed\n");
continue;
}
/* keep going if that's not the oem param table */
if (memcmp(rom->hdr.signature,
ISCI_ROM_SIG,
ISCI_ROM_SIG_SIZE) != 0)
continue;
dev_info(&pdev->dev,
"OEM parameter table found in OROM\n");
break;
}
}
if (i >= len) {
dev_err(&pdev->dev, "oprom parse error\n");
devm_kfree(&pdev->dev, rom);
rom = NULL;
}
pci_unmap_biosrom(oprom);
return rom;
}
enum sci_status isci_parse_oem_parameters(struct sci_oem_params *oem,
struct isci_orom *orom, int scu_index)
{
/* check for valid inputs */
if (scu_index < 0 || scu_index >= SCI_MAX_CONTROLLERS ||
scu_index > orom->hdr.num_elements || !oem)
return -EINVAL;
*oem = orom->ctrl[scu_index];
return 0;
}
struct isci_orom *isci_request_firmware(struct pci_dev *pdev, const struct firmware *fw)
{
struct isci_orom *orom = NULL, *data;
int i, j;
if (request_firmware(&fw, ISCI_FW_NAME, &pdev->dev) != 0)
return NULL;
if (fw->size < sizeof(*orom))
goto out;
data = (struct isci_orom *)fw->data;
if (strncmp(ISCI_ROM_SIG, data->hdr.signature,
strlen(ISCI_ROM_SIG)) != 0)
goto out;
orom = devm_kzalloc(&pdev->dev, fw->size, GFP_KERNEL);
if (!orom)
goto out;
memcpy(orom, fw->data, fw->size);
if (is_c0(pdev))
goto out;
/*
* deprecated: override default amp_control for pre-preproduction
* silicon revisions
*/
for (i = 0; i < ARRAY_SIZE(orom->ctrl); i++)
for (j = 0; j < ARRAY_SIZE(orom->ctrl[i].phys); j++) {
orom->ctrl[i].phys[j].afe_tx_amp_control0 = 0xe7c03;
orom->ctrl[i].phys[j].afe_tx_amp_control1 = 0xe7c03;
orom->ctrl[i].phys[j].afe_tx_amp_control2 = 0xe7c03;
orom->ctrl[i].phys[j].afe_tx_amp_control3 = 0xe7c03;
}
out:
release_firmware(fw);
return orom;
}
static struct efi *get_efi(void)
{
#ifdef CONFIG_EFI
return &efi;
#else
return NULL;
#endif
}
struct isci_orom *isci_get_efi_var(struct pci_dev *pdev)
{
efi_status_t status;
struct isci_orom *rom;
struct isci_oem_hdr *oem_hdr;
u8 *tmp, sum;
int j;
unsigned long data_len;
u8 *efi_data;
u32 efi_attrib = 0;
data_len = 1024;
efi_data = devm_kzalloc(&pdev->dev, data_len, GFP_KERNEL);
if (!efi_data) {
dev_warn(&pdev->dev,
"Unable to allocate memory for EFI data\n");
return NULL;
}
rom = (struct isci_orom *)(efi_data + sizeof(struct isci_oem_hdr));
if (get_efi())
status = get_efi()->get_variable(isci_efivar_name,
&ISCI_EFI_VENDOR_GUID,
&efi_attrib,
&data_len,
efi_data);
else
status = EFI_NOT_FOUND;
if (status != EFI_SUCCESS) {
dev_warn(&pdev->dev,
"Unable to obtain EFI var data for OEM parms\n");
return NULL;
}
oem_hdr = (struct isci_oem_hdr *)efi_data;
if (memcmp(oem_hdr->sig, ISCI_OEM_SIG, ISCI_OEM_SIG_SIZE) != 0) {
dev_warn(&pdev->dev,
"Invalid OEM header signature\n");
return NULL;
}
/* calculate checksum */
tmp = (u8 *)efi_data;
for (j = 0, sum = 0; j < (sizeof(*oem_hdr) + sizeof(*rom)); j++, tmp++)
sum += *tmp;
if (sum != 0) {
dev_warn(&pdev->dev,
"OEM table checksum failed\n");
return NULL;
}
if (memcmp(rom->hdr.signature,
ISCI_ROM_SIG,
ISCI_ROM_SIG_SIZE) != 0) {
dev_warn(&pdev->dev,
"Invalid OEM table signature\n");
return NULL;
}
return rom;
}
| gpl-2.0 |
pali/linux-n900 | drivers/ssb/sprom.c | 2510 | 5314 | /*
* Sonics Silicon Backplane
* Common SPROM support routines
*
* Copyright (C) 2005-2008 Michael Buesch <m@bues.ch>
* Copyright (C) 2005 Martin Langer <martin-langer@gmx.de>
* Copyright (C) 2005 Stefano Brivio <st3@riseup.net>
* Copyright (C) 2005 Danny van Dyk <kugelfang@gentoo.org>
* Copyright (C) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch>
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include "ssb_private.h"
#include <linux/ctype.h>
#include <linux/slab.h>
static int(*get_fallback_sprom)(struct ssb_bus *dev, struct ssb_sprom *out);
static int sprom2hex(const u16 *sprom, char *buf, size_t buf_len,
size_t sprom_size_words)
{
int i, pos = 0;
for (i = 0; i < sprom_size_words; i++)
pos += snprintf(buf + pos, buf_len - pos - 1,
"%04X", swab16(sprom[i]) & 0xFFFF);
pos += snprintf(buf + pos, buf_len - pos - 1, "\n");
return pos + 1;
}
static int hex2sprom(u16 *sprom, const char *dump, size_t len,
size_t sprom_size_words)
{
char c, tmp[5] = { 0 };
int err, cnt = 0;
unsigned long parsed;
/* Strip whitespace at the end. */
while (len) {
c = dump[len - 1];
if (!isspace(c) && c != '\0')
break;
len--;
}
/* Length must match exactly. */
if (len != sprom_size_words * 4)
return -EINVAL;
while (cnt < sprom_size_words) {
memcpy(tmp, dump, 4);
dump += 4;
err = kstrtoul(tmp, 16, &parsed);
if (err)
return err;
sprom[cnt++] = swab16((u16)parsed);
}
return 0;
}
/* Common sprom device-attribute show-handler */
ssize_t ssb_attr_sprom_show(struct ssb_bus *bus, char *buf,
int (*sprom_read)(struct ssb_bus *bus, u16 *sprom))
{
u16 *sprom;
int err = -ENOMEM;
ssize_t count = 0;
size_t sprom_size_words = bus->sprom_size;
sprom = kcalloc(sprom_size_words, sizeof(u16), GFP_KERNEL);
if (!sprom)
goto out;
/* Use interruptible locking, as the SPROM write might
* be holding the lock for several seconds. So allow userspace
* to cancel operation. */
err = -ERESTARTSYS;
if (mutex_lock_interruptible(&bus->sprom_mutex))
goto out_kfree;
err = sprom_read(bus, sprom);
mutex_unlock(&bus->sprom_mutex);
if (!err)
count = sprom2hex(sprom, buf, PAGE_SIZE, sprom_size_words);
out_kfree:
kfree(sprom);
out:
return err ? err : count;
}
/* Common sprom device-attribute store-handler */
ssize_t ssb_attr_sprom_store(struct ssb_bus *bus,
const char *buf, size_t count,
int (*sprom_check_crc)(const u16 *sprom, size_t size),
int (*sprom_write)(struct ssb_bus *bus, const u16 *sprom))
{
u16 *sprom;
int res = 0, err = -ENOMEM;
size_t sprom_size_words = bus->sprom_size;
struct ssb_freeze_context freeze;
sprom = kcalloc(bus->sprom_size, sizeof(u16), GFP_KERNEL);
if (!sprom)
goto out;
err = hex2sprom(sprom, buf, count, sprom_size_words);
if (err) {
err = -EINVAL;
goto out_kfree;
}
err = sprom_check_crc(sprom, sprom_size_words);
if (err) {
err = -EINVAL;
goto out_kfree;
}
/* Use interruptible locking, as the SPROM write might
* be holding the lock for several seconds. So allow userspace
* to cancel operation. */
err = -ERESTARTSYS;
if (mutex_lock_interruptible(&bus->sprom_mutex))
goto out_kfree;
err = ssb_devices_freeze(bus, &freeze);
if (err) {
ssb_err("SPROM write: Could not freeze all devices\n");
goto out_unlock;
}
res = sprom_write(bus, sprom);
err = ssb_devices_thaw(&freeze);
if (err)
ssb_err("SPROM write: Could not thaw all devices\n");
out_unlock:
mutex_unlock(&bus->sprom_mutex);
out_kfree:
kfree(sprom);
out:
if (res)
return res;
return err ? err : count;
}
/**
* ssb_arch_register_fallback_sprom - Registers a method providing a
* fallback SPROM if no SPROM is found.
*
* @sprom_callback: The callback function.
*
* With this function the architecture implementation may register a
* callback handler which fills the SPROM data structure. The fallback is
* only used for PCI based SSB devices, where no valid SPROM can be found
* in the shadow registers.
*
* This function is useful for weird architectures that have a half-assed
* SSB device hardwired to their PCI bus.
*
* Note that it does only work with PCI attached SSB devices. PCMCIA
* devices currently don't use this fallback.
* Architectures must provide the SPROM for native SSB devices anyway, so
* the fallback also isn't used for native devices.
*
* This function is available for architecture code, only. So it is not
* exported.
*/
int ssb_arch_register_fallback_sprom(int (*sprom_callback)(struct ssb_bus *bus,
struct ssb_sprom *out))
{
if (get_fallback_sprom)
return -EEXIST;
get_fallback_sprom = sprom_callback;
return 0;
}
int ssb_fill_sprom_with_fallback(struct ssb_bus *bus, struct ssb_sprom *out)
{
if (!get_fallback_sprom)
return -ENOENT;
return get_fallback_sprom(bus, out);
}
/* http://bcm-v4.sipsolutions.net/802.11/IsSpromAvailable */
bool ssb_is_sprom_available(struct ssb_bus *bus)
{
/* status register only exists on chipcomon rev >= 11 and we need check
for >= 31 only */
/* this routine differs from specs as we do not access SPROM directly
on PCMCIA */
if (bus->bustype == SSB_BUSTYPE_PCI &&
bus->chipco.dev && /* can be unavailable! */
bus->chipco.dev->id.revision >= 31)
return bus->chipco.capabilities & SSB_CHIPCO_CAP_SPROM;
return true;
}
| gpl-2.0 |
kannu1994/crespo_kernel | sound/soc/pxa/e740_wm9705.c | 3022 | 5139 | /*
* e740-wm9705.c -- SoC audio for e740
*
* Copyright 2007 (c) Ian Molton <spyro@f2s.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; version 2 ONLY.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/gpio.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <mach/audio.h>
#include <mach/eseries-gpio.h>
#include <asm/mach-types.h>
#include "../codecs/wm9705.h"
#include "pxa2xx-ac97.h"
#define E740_AUDIO_OUT 1
#define E740_AUDIO_IN 2
static int e740_audio_power;
static void e740_sync_audio_power(int status)
{
gpio_set_value(GPIO_E740_WM9705_nAVDD2, !status);
gpio_set_value(GPIO_E740_AMP_ON, (status & E740_AUDIO_OUT) ? 1 : 0);
gpio_set_value(GPIO_E740_MIC_ON, (status & E740_AUDIO_IN) ? 1 : 0);
}
static int e740_mic_amp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
if (event & SND_SOC_DAPM_PRE_PMU)
e740_audio_power |= E740_AUDIO_IN;
else if (event & SND_SOC_DAPM_POST_PMD)
e740_audio_power &= ~E740_AUDIO_IN;
e740_sync_audio_power(e740_audio_power);
return 0;
}
static int e740_output_amp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
if (event & SND_SOC_DAPM_PRE_PMU)
e740_audio_power |= E740_AUDIO_OUT;
else if (event & SND_SOC_DAPM_POST_PMD)
e740_audio_power &= ~E740_AUDIO_OUT;
e740_sync_audio_power(e740_audio_power);
return 0;
}
static const struct snd_soc_dapm_widget e740_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_SPK("Speaker", NULL),
SND_SOC_DAPM_MIC("Mic (Internal)", NULL),
SND_SOC_DAPM_PGA_E("Output Amp", SND_SOC_NOPM, 0, 0, NULL, 0,
e740_output_amp_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("Mic Amp", SND_SOC_NOPM, 0, 0, NULL, 0,
e740_mic_amp_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
};
static const struct snd_soc_dapm_route audio_map[] = {
{"Output Amp", NULL, "LOUT"},
{"Output Amp", NULL, "ROUT"},
{"Output Amp", NULL, "MONOOUT"},
{"Speaker", NULL, "Output Amp"},
{"Headphone Jack", NULL, "Output Amp"},
{"MIC1", NULL, "Mic Amp"},
{"Mic Amp", NULL, "Mic (Internal)"},
};
static int e740_ac97_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_dapm_nc_pin(dapm, "HPOUTL");
snd_soc_dapm_nc_pin(dapm, "HPOUTR");
snd_soc_dapm_nc_pin(dapm, "PHONE");
snd_soc_dapm_nc_pin(dapm, "LINEINL");
snd_soc_dapm_nc_pin(dapm, "LINEINR");
snd_soc_dapm_nc_pin(dapm, "CDINL");
snd_soc_dapm_nc_pin(dapm, "CDINR");
snd_soc_dapm_nc_pin(dapm, "PCBEEP");
snd_soc_dapm_nc_pin(dapm, "MIC2");
snd_soc_dapm_new_controls(dapm, e740_dapm_widgets,
ARRAY_SIZE(e740_dapm_widgets));
snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map));
snd_soc_dapm_sync(dapm);
return 0;
}
static struct snd_soc_dai_link e740_dai[] = {
{
.name = "AC97",
.stream_name = "AC97 HiFi",
.cpu_dai_name = "pxa2xx-ac97",
.codec_dai_name = "wm9705-hifi",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm9705-codec",
.init = e740_ac97_init,
},
{
.name = "AC97 Aux",
.stream_name = "AC97 Aux",
.cpu_dai_name = "pxa2xx-ac97-aux",
.codec_dai_name = "wm9705-aux",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm9705-codec",
},
};
static struct snd_soc_card e740 = {
.name = "Toshiba e740",
.dai_link = e740_dai,
.num_links = ARRAY_SIZE(e740_dai),
};
static struct platform_device *e740_snd_device;
static int __init e740_init(void)
{
int ret;
if (!machine_is_e740())
return -ENODEV;
ret = gpio_request(GPIO_E740_MIC_ON, "Mic amp");
if (ret)
return ret;
ret = gpio_request(GPIO_E740_AMP_ON, "Output amp");
if (ret)
goto free_mic_amp_gpio;
ret = gpio_request(GPIO_E740_WM9705_nAVDD2, "Audio power");
if (ret)
goto free_op_amp_gpio;
/* Disable audio */
ret = gpio_direction_output(GPIO_E740_MIC_ON, 0);
if (ret)
goto free_apwr_gpio;
ret = gpio_direction_output(GPIO_E740_AMP_ON, 0);
if (ret)
goto free_apwr_gpio;
ret = gpio_direction_output(GPIO_E740_WM9705_nAVDD2, 1);
if (ret)
goto free_apwr_gpio;
e740_snd_device = platform_device_alloc("soc-audio", -1);
if (!e740_snd_device) {
ret = -ENOMEM;
goto free_apwr_gpio;
}
platform_set_drvdata(e740_snd_device, &e740);
ret = platform_device_add(e740_snd_device);
if (!ret)
return 0;
/* Fail gracefully */
platform_device_put(e740_snd_device);
free_apwr_gpio:
gpio_free(GPIO_E740_WM9705_nAVDD2);
free_op_amp_gpio:
gpio_free(GPIO_E740_AMP_ON);
free_mic_amp_gpio:
gpio_free(GPIO_E740_MIC_ON);
return ret;
}
static void __exit e740_exit(void)
{
platform_device_unregister(e740_snd_device);
gpio_free(GPIO_E740_WM9705_nAVDD2);
gpio_free(GPIO_E740_AMP_ON);
gpio_free(GPIO_E740_MIC_ON);
}
module_init(e740_init);
module_exit(e740_exit);
/* Module information */
MODULE_AUTHOR("Ian Molton <spyro@f2s.com>");
MODULE_DESCRIPTION("ALSA SoC driver for e740");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
robacklin/linux-2.6.39.4 | sound/soc/pxa/e750_wm9705.c | 3022 | 4522 | /*
* e750-wm9705.c -- SoC audio for e750
*
* Copyright 2007 (c) Ian Molton <spyro@f2s.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; version 2 ONLY.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/gpio.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <mach/audio.h>
#include <mach/eseries-gpio.h>
#include <asm/mach-types.h>
#include "../codecs/wm9705.h"
#include "pxa2xx-ac97.h"
static int e750_spk_amp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
if (event & SND_SOC_DAPM_PRE_PMU)
gpio_set_value(GPIO_E750_SPK_AMP_OFF, 0);
else if (event & SND_SOC_DAPM_POST_PMD)
gpio_set_value(GPIO_E750_SPK_AMP_OFF, 1);
return 0;
}
static int e750_hp_amp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
if (event & SND_SOC_DAPM_PRE_PMU)
gpio_set_value(GPIO_E750_HP_AMP_OFF, 0);
else if (event & SND_SOC_DAPM_POST_PMD)
gpio_set_value(GPIO_E750_HP_AMP_OFF, 1);
return 0;
}
static const struct snd_soc_dapm_widget e750_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_SPK("Speaker", NULL),
SND_SOC_DAPM_MIC("Mic (Internal)", NULL),
SND_SOC_DAPM_PGA_E("Headphone Amp", SND_SOC_NOPM, 0, 0, NULL, 0,
e750_hp_amp_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("Speaker Amp", SND_SOC_NOPM, 0, 0, NULL, 0,
e750_spk_amp_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
};
static const struct snd_soc_dapm_route audio_map[] = {
{"Headphone Amp", NULL, "HPOUTL"},
{"Headphone Amp", NULL, "HPOUTR"},
{"Headphone Jack", NULL, "Headphone Amp"},
{"Speaker Amp", NULL, "MONOOUT"},
{"Speaker", NULL, "Speaker Amp"},
{"MIC1", NULL, "Mic (Internal)"},
};
static int e750_ac97_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_dapm_nc_pin(dapm, "LOUT");
snd_soc_dapm_nc_pin(dapm, "ROUT");
snd_soc_dapm_nc_pin(dapm, "PHONE");
snd_soc_dapm_nc_pin(dapm, "LINEINL");
snd_soc_dapm_nc_pin(dapm, "LINEINR");
snd_soc_dapm_nc_pin(dapm, "CDINL");
snd_soc_dapm_nc_pin(dapm, "CDINR");
snd_soc_dapm_nc_pin(dapm, "PCBEEP");
snd_soc_dapm_nc_pin(dapm, "MIC2");
snd_soc_dapm_new_controls(dapm, e750_dapm_widgets,
ARRAY_SIZE(e750_dapm_widgets));
snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map));
snd_soc_dapm_sync(dapm);
return 0;
}
static struct snd_soc_dai_link e750_dai[] = {
{
.name = "AC97",
.stream_name = "AC97 HiFi",
.cpu_dai_name = "pxa2xx-ac97",
.codec_dai_name = "wm9705-hifi",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm9705-codec",
.init = e750_ac97_init,
/* use ops to check startup state */
},
{
.name = "AC97 Aux",
.stream_name = "AC97 Aux",
.cpu_dai_name = "pxa2xx-ac97-aux",
.codec_dai_name ="wm9705-aux",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm9705-codec",
},
};
static struct snd_soc_card e750 = {
.name = "Toshiba e750",
.dai_link = e750_dai,
.num_links = ARRAY_SIZE(e750_dai),
};
static struct platform_device *e750_snd_device;
static int __init e750_init(void)
{
int ret;
if (!machine_is_e750())
return -ENODEV;
ret = gpio_request(GPIO_E750_HP_AMP_OFF, "Headphone amp");
if (ret)
return ret;
ret = gpio_request(GPIO_E750_SPK_AMP_OFF, "Speaker amp");
if (ret)
goto free_hp_amp_gpio;
ret = gpio_direction_output(GPIO_E750_HP_AMP_OFF, 1);
if (ret)
goto free_spk_amp_gpio;
ret = gpio_direction_output(GPIO_E750_SPK_AMP_OFF, 1);
if (ret)
goto free_spk_amp_gpio;
e750_snd_device = platform_device_alloc("soc-audio", -1);
if (!e750_snd_device) {
ret = -ENOMEM;
goto free_spk_amp_gpio;
}
platform_set_drvdata(e750_snd_device, &e750);
ret = platform_device_add(e750_snd_device);
if (!ret)
return 0;
/* Fail gracefully */
platform_device_put(e750_snd_device);
free_spk_amp_gpio:
gpio_free(GPIO_E750_SPK_AMP_OFF);
free_hp_amp_gpio:
gpio_free(GPIO_E750_HP_AMP_OFF);
return ret;
}
static void __exit e750_exit(void)
{
platform_device_unregister(e750_snd_device);
gpio_free(GPIO_E750_SPK_AMP_OFF);
gpio_free(GPIO_E750_HP_AMP_OFF);
}
module_init(e750_init);
module_exit(e750_exit);
/* Module information */
MODULE_AUTHOR("Ian Molton <spyro@f2s.com>");
MODULE_DESCRIPTION("ALSA SoC driver for e750");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
NoelMacwan/SXDNanhu | arch/sh/drivers/dma/dma-pvr2.c | 3790 | 2438 | /*
* arch/sh/drivers/dma/dma-pvr2.c
*
* NEC PowerVR 2 (Dreamcast) DMA support
*
* Copyright (C) 2003, 2004 Paul Mundt
*
* 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/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <mach/sysasic.h>
#include <mach/dma.h>
#include <asm/dma.h>
#include <asm/io.h>
static unsigned int xfer_complete;
static int count;
static irqreturn_t pvr2_dma_interrupt(int irq, void *dev_id)
{
if (get_dma_residue(PVR2_CASCADE_CHAN)) {
printk(KERN_WARNING "DMA: SH DMAC did not complete transfer "
"on channel %d, waiting..\n", PVR2_CASCADE_CHAN);
dma_wait_for_completion(PVR2_CASCADE_CHAN);
}
if (count++ < 10)
pr_debug("Got a pvr2 dma interrupt for channel %d\n",
irq - HW_EVENT_PVR2_DMA);
xfer_complete = 1;
return IRQ_HANDLED;
}
static int pvr2_request_dma(struct dma_channel *chan)
{
if (__raw_readl(PVR2_DMA_MODE) != 0)
return -EBUSY;
__raw_writel(0, PVR2_DMA_LMMODE0);
return 0;
}
static int pvr2_get_dma_residue(struct dma_channel *chan)
{
return xfer_complete == 0;
}
static int pvr2_xfer_dma(struct dma_channel *chan)
{
if (chan->sar || !chan->dar)
return -EINVAL;
xfer_complete = 0;
__raw_writel(chan->dar, PVR2_DMA_ADDR);
__raw_writel(chan->count, PVR2_DMA_COUNT);
__raw_writel(chan->mode & DMA_MODE_MASK, PVR2_DMA_MODE);
return 0;
}
static struct irqaction pvr2_dma_irq = {
.name = "pvr2 DMA handler",
.handler = pvr2_dma_interrupt,
.flags = IRQF_DISABLED,
};
static struct dma_ops pvr2_dma_ops = {
.request = pvr2_request_dma,
.get_residue = pvr2_get_dma_residue,
.xfer = pvr2_xfer_dma,
};
static struct dma_info pvr2_dma_info = {
.name = "pvr2_dmac",
.nr_channels = 1,
.ops = &pvr2_dma_ops,
.flags = DMAC_CHANNELS_TEI_CAPABLE,
};
static int __init pvr2_dma_init(void)
{
setup_irq(HW_EVENT_PVR2_DMA, &pvr2_dma_irq);
request_dma(PVR2_CASCADE_CHAN, "pvr2 cascade");
return register_dmac(&pvr2_dma_info);
}
static void __exit pvr2_dma_exit(void)
{
free_dma(PVR2_CASCADE_CHAN);
free_irq(HW_EVENT_PVR2_DMA, 0);
unregister_dmac(&pvr2_dma_info);
}
subsys_initcall(pvr2_dma_init);
module_exit(pvr2_dma_exit);
MODULE_AUTHOR("Paul Mundt <lethal@linux-sh.org>");
MODULE_DESCRIPTION("NEC PowerVR 2 DMA driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
kbc-developers/android_kernel_samsung_jfdcm | arch/powerpc/platforms/powermac/pic.c | 4558 | 17784 | /*
* Support for the interrupt controllers found on Power Macintosh,
* currently Apple's "Grand Central" interrupt controller in all
* it's incarnations. OpenPIC support used on newer machines is
* in a separate file
*
* Copyright (C) 1997 Paul Mackerras (paulus@samba.org)
* Copyright (C) 2005 Benjamin Herrenschmidt (benh@kernel.crashing.org)
* IBM, Corp.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <linux/stddef.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/syscore_ops.h>
#include <linux/adb.h>
#include <linux/pmu.h>
#include <asm/sections.h>
#include <asm/io.h>
#include <asm/smp.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include <asm/time.h>
#include <asm/pmac_feature.h>
#include <asm/mpic.h>
#include <asm/xmon.h>
#include "pmac.h"
#ifdef CONFIG_PPC32
struct pmac_irq_hw {
unsigned int event;
unsigned int enable;
unsigned int ack;
unsigned int level;
};
/* Workaround flags for 32bit powermac machines */
unsigned int of_irq_workarounds;
struct device_node *of_irq_dflt_pic;
/* Default addresses */
static volatile struct pmac_irq_hw __iomem *pmac_irq_hw[4];
static int max_irqs;
static int max_real_irqs;
static DEFINE_RAW_SPINLOCK(pmac_pic_lock);
/* The max irq number this driver deals with is 128; see max_irqs */
static DECLARE_BITMAP(ppc_lost_interrupts, 128);
static DECLARE_BITMAP(ppc_cached_irq_mask, 128);
static int pmac_irq_cascade = -1;
static struct irq_domain *pmac_pic_host;
static void __pmac_retrigger(unsigned int irq_nr)
{
if (irq_nr >= max_real_irqs && pmac_irq_cascade > 0) {
__set_bit(irq_nr, ppc_lost_interrupts);
irq_nr = pmac_irq_cascade;
mb();
}
if (!__test_and_set_bit(irq_nr, ppc_lost_interrupts)) {
atomic_inc(&ppc_n_lost_interrupts);
set_dec(1);
}
}
static void pmac_mask_and_ack_irq(struct irq_data *d)
{
unsigned int src = irqd_to_hwirq(d);
unsigned long bit = 1UL << (src & 0x1f);
int i = src >> 5;
unsigned long flags;
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
__clear_bit(src, ppc_cached_irq_mask);
if (__test_and_clear_bit(src, ppc_lost_interrupts))
atomic_dec(&ppc_n_lost_interrupts);
out_le32(&pmac_irq_hw[i]->enable, ppc_cached_irq_mask[i]);
out_le32(&pmac_irq_hw[i]->ack, bit);
do {
/* make sure ack gets to controller before we enable
interrupts */
mb();
} while((in_le32(&pmac_irq_hw[i]->enable) & bit)
!= (ppc_cached_irq_mask[i] & bit));
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
}
static void pmac_ack_irq(struct irq_data *d)
{
unsigned int src = irqd_to_hwirq(d);
unsigned long bit = 1UL << (src & 0x1f);
int i = src >> 5;
unsigned long flags;
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
if (__test_and_clear_bit(src, ppc_lost_interrupts))
atomic_dec(&ppc_n_lost_interrupts);
out_le32(&pmac_irq_hw[i]->ack, bit);
(void)in_le32(&pmac_irq_hw[i]->ack);
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
}
static void __pmac_set_irq_mask(unsigned int irq_nr, int nokicklost)
{
unsigned long bit = 1UL << (irq_nr & 0x1f);
int i = irq_nr >> 5;
if ((unsigned)irq_nr >= max_irqs)
return;
/* enable unmasked interrupts */
out_le32(&pmac_irq_hw[i]->enable, ppc_cached_irq_mask[i]);
do {
/* make sure mask gets to controller before we
return to user */
mb();
} while((in_le32(&pmac_irq_hw[i]->enable) & bit)
!= (ppc_cached_irq_mask[i] & bit));
/*
* Unfortunately, setting the bit in the enable register
* when the device interrupt is already on *doesn't* set
* the bit in the flag register or request another interrupt.
*/
if (bit & ppc_cached_irq_mask[i] & in_le32(&pmac_irq_hw[i]->level))
__pmac_retrigger(irq_nr);
}
/* When an irq gets requested for the first client, if it's an
* edge interrupt, we clear any previous one on the controller
*/
static unsigned int pmac_startup_irq(struct irq_data *d)
{
unsigned long flags;
unsigned int src = irqd_to_hwirq(d);
unsigned long bit = 1UL << (src & 0x1f);
int i = src >> 5;
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
if (!irqd_is_level_type(d))
out_le32(&pmac_irq_hw[i]->ack, bit);
__set_bit(src, ppc_cached_irq_mask);
__pmac_set_irq_mask(src, 0);
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
return 0;
}
static void pmac_mask_irq(struct irq_data *d)
{
unsigned long flags;
unsigned int src = irqd_to_hwirq(d);
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
__clear_bit(src, ppc_cached_irq_mask);
__pmac_set_irq_mask(src, 1);
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
}
static void pmac_unmask_irq(struct irq_data *d)
{
unsigned long flags;
unsigned int src = irqd_to_hwirq(d);
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
__set_bit(src, ppc_cached_irq_mask);
__pmac_set_irq_mask(src, 0);
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
}
static int pmac_retrigger(struct irq_data *d)
{
unsigned long flags;
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
__pmac_retrigger(irqd_to_hwirq(d));
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
return 1;
}
static struct irq_chip pmac_pic = {
.name = "PMAC-PIC",
.irq_startup = pmac_startup_irq,
.irq_mask = pmac_mask_irq,
.irq_ack = pmac_ack_irq,
.irq_mask_ack = pmac_mask_and_ack_irq,
.irq_unmask = pmac_unmask_irq,
.irq_retrigger = pmac_retrigger,
};
static irqreturn_t gatwick_action(int cpl, void *dev_id)
{
unsigned long flags;
int irq, bits;
int rc = IRQ_NONE;
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
for (irq = max_irqs; (irq -= 32) >= max_real_irqs; ) {
int i = irq >> 5;
bits = in_le32(&pmac_irq_hw[i]->event) | ppc_lost_interrupts[i];
bits |= in_le32(&pmac_irq_hw[i]->level);
bits &= ppc_cached_irq_mask[i];
if (bits == 0)
continue;
irq += __ilog2(bits);
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
generic_handle_irq(irq);
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
rc = IRQ_HANDLED;
}
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
return rc;
}
static unsigned int pmac_pic_get_irq(void)
{
int irq;
unsigned long bits = 0;
unsigned long flags;
#ifdef CONFIG_PPC_PMAC32_PSURGE
/* IPI's are a hack on the powersurge -- Cort */
if (smp_processor_id() != 0) {
return psurge_secondary_virq;
}
#endif /* CONFIG_PPC_PMAC32_PSURGE */
raw_spin_lock_irqsave(&pmac_pic_lock, flags);
for (irq = max_real_irqs; (irq -= 32) >= 0; ) {
int i = irq >> 5;
bits = in_le32(&pmac_irq_hw[i]->event) | ppc_lost_interrupts[i];
bits |= in_le32(&pmac_irq_hw[i]->level);
bits &= ppc_cached_irq_mask[i];
if (bits == 0)
continue;
irq += __ilog2(bits);
break;
}
raw_spin_unlock_irqrestore(&pmac_pic_lock, flags);
if (unlikely(irq < 0))
return NO_IRQ;
return irq_linear_revmap(pmac_pic_host, irq);
}
#ifdef CONFIG_XMON
static struct irqaction xmon_action = {
.handler = xmon_irq,
.flags = 0,
.name = "NMI - XMON"
};
#endif
static struct irqaction gatwick_cascade_action = {
.handler = gatwick_action,
.name = "cascade",
};
static int pmac_pic_host_match(struct irq_domain *h, struct device_node *node)
{
/* We match all, we don't always have a node anyway */
return 1;
}
static int pmac_pic_host_map(struct irq_domain *h, unsigned int virq,
irq_hw_number_t hw)
{
if (hw >= max_irqs)
return -EINVAL;
/* Mark level interrupts, set delayed disable for edge ones and set
* handlers
*/
irq_set_status_flags(virq, IRQ_LEVEL);
irq_set_chip_and_handler(virq, &pmac_pic, handle_level_irq);
return 0;
}
static const struct irq_domain_ops pmac_pic_host_ops = {
.match = pmac_pic_host_match,
.map = pmac_pic_host_map,
.xlate = irq_domain_xlate_onecell,
};
static void __init pmac_pic_probe_oldstyle(void)
{
int i;
struct device_node *master = NULL;
struct device_node *slave = NULL;
u8 __iomem *addr;
struct resource r;
/* Set our get_irq function */
ppc_md.get_irq = pmac_pic_get_irq;
/*
* Find the interrupt controller type & node
*/
if ((master = of_find_node_by_name(NULL, "gc")) != NULL) {
max_irqs = max_real_irqs = 32;
} else if ((master = of_find_node_by_name(NULL, "ohare")) != NULL) {
max_irqs = max_real_irqs = 32;
/* We might have a second cascaded ohare */
slave = of_find_node_by_name(NULL, "pci106b,7");
if (slave)
max_irqs = 64;
} else if ((master = of_find_node_by_name(NULL, "mac-io")) != NULL) {
max_irqs = max_real_irqs = 64;
/* We might have a second cascaded heathrow */
slave = of_find_node_by_name(master, "mac-io");
/* Check ordering of master & slave */
if (of_device_is_compatible(master, "gatwick")) {
struct device_node *tmp;
BUG_ON(slave == NULL);
tmp = master;
master = slave;
slave = tmp;
}
/* We found a slave */
if (slave)
max_irqs = 128;
}
BUG_ON(master == NULL);
/*
* Allocate an irq host
*/
pmac_pic_host = irq_domain_add_linear(master, max_irqs,
&pmac_pic_host_ops, NULL);
BUG_ON(pmac_pic_host == NULL);
irq_set_default_host(pmac_pic_host);
/* Get addresses of first controller if we have a node for it */
BUG_ON(of_address_to_resource(master, 0, &r));
/* Map interrupts of primary controller */
addr = (u8 __iomem *) ioremap(r.start, 0x40);
i = 0;
pmac_irq_hw[i++] = (volatile struct pmac_irq_hw __iomem *)
(addr + 0x20);
if (max_real_irqs > 32)
pmac_irq_hw[i++] = (volatile struct pmac_irq_hw __iomem *)
(addr + 0x10);
of_node_put(master);
printk(KERN_INFO "irq: Found primary Apple PIC %s for %d irqs\n",
master->full_name, max_real_irqs);
/* Map interrupts of cascaded controller */
if (slave && !of_address_to_resource(slave, 0, &r)) {
addr = (u8 __iomem *)ioremap(r.start, 0x40);
pmac_irq_hw[i++] = (volatile struct pmac_irq_hw __iomem *)
(addr + 0x20);
if (max_irqs > 64)
pmac_irq_hw[i++] =
(volatile struct pmac_irq_hw __iomem *)
(addr + 0x10);
pmac_irq_cascade = irq_of_parse_and_map(slave, 0);
printk(KERN_INFO "irq: Found slave Apple PIC %s for %d irqs"
" cascade: %d\n", slave->full_name,
max_irqs - max_real_irqs, pmac_irq_cascade);
}
of_node_put(slave);
/* Disable all interrupts in all controllers */
for (i = 0; i * 32 < max_irqs; ++i)
out_le32(&pmac_irq_hw[i]->enable, 0);
/* Hookup cascade irq */
if (slave && pmac_irq_cascade != NO_IRQ)
setup_irq(pmac_irq_cascade, &gatwick_cascade_action);
printk(KERN_INFO "irq: System has %d possible interrupts\n", max_irqs);
#ifdef CONFIG_XMON
setup_irq(irq_create_mapping(NULL, 20), &xmon_action);
#endif
}
int of_irq_map_oldworld(struct device_node *device, int index,
struct of_irq *out_irq)
{
const u32 *ints = NULL;
int intlen;
/*
* Old machines just have a list of interrupt numbers
* and no interrupt-controller nodes. We also have dodgy
* cases where the APPL,interrupts property is completely
* missing behind pci-pci bridges and we have to get it
* from the parent (the bridge itself, as apple just wired
* everything together on these)
*/
while (device) {
ints = of_get_property(device, "AAPL,interrupts", &intlen);
if (ints != NULL)
break;
device = device->parent;
if (device && strcmp(device->type, "pci") != 0)
break;
}
if (ints == NULL)
return -EINVAL;
intlen /= sizeof(u32);
if (index >= intlen)
return -EINVAL;
out_irq->controller = NULL;
out_irq->specifier[0] = ints[index];
out_irq->size = 1;
return 0;
}
#endif /* CONFIG_PPC32 */
static void __init pmac_pic_setup_mpic_nmi(struct mpic *mpic)
{
#if defined(CONFIG_XMON) && defined(CONFIG_PPC32)
struct device_node* pswitch;
int nmi_irq;
pswitch = of_find_node_by_name(NULL, "programmer-switch");
if (pswitch) {
nmi_irq = irq_of_parse_and_map(pswitch, 0);
if (nmi_irq != NO_IRQ) {
mpic_irq_set_priority(nmi_irq, 9);
setup_irq(nmi_irq, &xmon_action);
}
of_node_put(pswitch);
}
#endif /* defined(CONFIG_XMON) && defined(CONFIG_PPC32) */
}
static struct mpic * __init pmac_setup_one_mpic(struct device_node *np,
int master)
{
const char *name = master ? " MPIC 1 " : " MPIC 2 ";
struct mpic *mpic;
unsigned int flags = master ? 0 : MPIC_SECONDARY;
pmac_call_feature(PMAC_FTR_ENABLE_MPIC, np, 0, 0);
if (of_get_property(np, "big-endian", NULL))
flags |= MPIC_BIG_ENDIAN;
/* Primary Big Endian means HT interrupts. This is quite dodgy
* but works until I find a better way
*/
if (master && (flags & MPIC_BIG_ENDIAN))
flags |= MPIC_U3_HT_IRQS;
mpic = mpic_alloc(np, 0, flags, 0, 0, name);
if (mpic == NULL)
return NULL;
mpic_init(mpic);
return mpic;
}
static int __init pmac_pic_probe_mpic(void)
{
struct mpic *mpic1, *mpic2;
struct device_node *np, *master = NULL, *slave = NULL;
/* We can have up to 2 MPICs cascaded */
for (np = NULL; (np = of_find_node_by_type(np, "open-pic"))
!= NULL;) {
if (master == NULL &&
of_get_property(np, "interrupts", NULL) == NULL)
master = of_node_get(np);
else if (slave == NULL)
slave = of_node_get(np);
if (master && slave)
break;
}
/* Check for bogus setups */
if (master == NULL && slave != NULL) {
master = slave;
slave = NULL;
}
/* Not found, default to good old pmac pic */
if (master == NULL)
return -ENODEV;
/* Set master handler */
ppc_md.get_irq = mpic_get_irq;
/* Setup master */
mpic1 = pmac_setup_one_mpic(master, 1);
BUG_ON(mpic1 == NULL);
/* Install NMI if any */
pmac_pic_setup_mpic_nmi(mpic1);
of_node_put(master);
/* Set up a cascaded controller, if present */
if (slave) {
mpic2 = pmac_setup_one_mpic(slave, 0);
if (mpic2 == NULL)
printk(KERN_ERR "Failed to setup slave MPIC\n");
of_node_put(slave);
}
return 0;
}
void __init pmac_pic_init(void)
{
/* We configure the OF parsing based on our oldworld vs. newworld
* platform type and wether we were booted by BootX.
*/
#ifdef CONFIG_PPC32
if (!pmac_newworld)
of_irq_workarounds |= OF_IMAP_OLDWORLD_MAC;
if (of_get_property(of_chosen, "linux,bootx", NULL) != NULL)
of_irq_workarounds |= OF_IMAP_NO_PHANDLE;
/* If we don't have phandles on a newworld, then try to locate a
* default interrupt controller (happens when booting with BootX).
* We do a first match here, hopefully, that only ever happens on
* machines with one controller.
*/
if (pmac_newworld && (of_irq_workarounds & OF_IMAP_NO_PHANDLE)) {
struct device_node *np;
for_each_node_with_property(np, "interrupt-controller") {
/* Skip /chosen/interrupt-controller */
if (strcmp(np->name, "chosen") == 0)
continue;
/* It seems like at least one person wants
* to use BootX on a machine with an AppleKiwi
* controller which happens to pretend to be an
* interrupt controller too. */
if (strcmp(np->name, "AppleKiwi") == 0)
continue;
/* I think we found one ! */
of_irq_dflt_pic = np;
break;
}
}
#endif /* CONFIG_PPC32 */
/* We first try to detect Apple's new Core99 chipset, since mac-io
* is quite different on those machines and contains an IBM MPIC2.
*/
if (pmac_pic_probe_mpic() == 0)
return;
#ifdef CONFIG_PPC32
pmac_pic_probe_oldstyle();
#endif
}
#if defined(CONFIG_PM) && defined(CONFIG_PPC32)
/*
* These procedures are used in implementing sleep on the powerbooks.
* sleep_save_intrs() saves the states of all interrupt enables
* and disables all interrupts except for the nominated one.
* sleep_restore_intrs() restores the states of all interrupt enables.
*/
unsigned long sleep_save_mask[2];
/* This used to be passed by the PMU driver but that link got
* broken with the new driver model. We use this tweak for now...
* We really want to do things differently though...
*/
static int pmacpic_find_viaint(void)
{
int viaint = -1;
#ifdef CONFIG_ADB_PMU
struct device_node *np;
if (pmu_get_model() != PMU_OHARE_BASED)
goto not_found;
np = of_find_node_by_name(NULL, "via-pmu");
if (np == NULL)
goto not_found;
viaint = irq_of_parse_and_map(np, 0);
not_found:
#endif /* CONFIG_ADB_PMU */
return viaint;
}
static int pmacpic_suspend(void)
{
int viaint = pmacpic_find_viaint();
sleep_save_mask[0] = ppc_cached_irq_mask[0];
sleep_save_mask[1] = ppc_cached_irq_mask[1];
ppc_cached_irq_mask[0] = 0;
ppc_cached_irq_mask[1] = 0;
if (viaint > 0)
set_bit(viaint, ppc_cached_irq_mask);
out_le32(&pmac_irq_hw[0]->enable, ppc_cached_irq_mask[0]);
if (max_real_irqs > 32)
out_le32(&pmac_irq_hw[1]->enable, ppc_cached_irq_mask[1]);
(void)in_le32(&pmac_irq_hw[0]->event);
/* make sure mask gets to controller before we return to caller */
mb();
(void)in_le32(&pmac_irq_hw[0]->enable);
return 0;
}
static void pmacpic_resume(void)
{
int i;
out_le32(&pmac_irq_hw[0]->enable, 0);
if (max_real_irqs > 32)
out_le32(&pmac_irq_hw[1]->enable, 0);
mb();
for (i = 0; i < max_real_irqs; ++i)
if (test_bit(i, sleep_save_mask))
pmac_unmask_irq(irq_get_irq_data(i));
}
static struct syscore_ops pmacpic_syscore_ops = {
.suspend = pmacpic_suspend,
.resume = pmacpic_resume,
};
static int __init init_pmacpic_syscore(void)
{
if (pmac_irq_hw[0])
register_syscore_ops(&pmacpic_syscore_ops);
return 0;
}
machine_subsys_initcall(powermac, init_pmacpic_syscore);
#endif /* CONFIG_PM && CONFIG_PPC32 */
| gpl-2.0 |
ZdrowyGosciu/kernel_lge_g2_msm8974-caf_lg-devs | arch/arm/mach-s3c2410/pll.c | 5070 | 3665 | /* arch/arm/mach-s3c2410/pll.c
*
* Copyright (c) 2006-2007 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
* Vincent Sanders <vince@arm.linux.org.uk>
*
* S3C2410 CPU PLL tables
*
* 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/types.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/list.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <plat/cpu.h>
#include <plat/cpu-freq-core.h>
static struct cpufreq_frequency_table pll_vals_12MHz[] = {
{ .frequency = 34000000, .index = PLLVAL(82, 2, 3), },
{ .frequency = 45000000, .index = PLLVAL(82, 1, 3), },
{ .frequency = 51000000, .index = PLLVAL(161, 3, 3), },
{ .frequency = 48000000, .index = PLLVAL(120, 2, 3), },
{ .frequency = 56000000, .index = PLLVAL(142, 2, 3), },
{ .frequency = 68000000, .index = PLLVAL(82, 2, 2), },
{ .frequency = 79000000, .index = PLLVAL(71, 1, 2), },
{ .frequency = 85000000, .index = PLLVAL(105, 2, 2), },
{ .frequency = 90000000, .index = PLLVAL(112, 2, 2), },
{ .frequency = 101000000, .index = PLLVAL(127, 2, 2), },
{ .frequency = 113000000, .index = PLLVAL(105, 1, 2), },
{ .frequency = 118000000, .index = PLLVAL(150, 2, 2), },
{ .frequency = 124000000, .index = PLLVAL(116, 1, 2), },
{ .frequency = 135000000, .index = PLLVAL(82, 2, 1), },
{ .frequency = 147000000, .index = PLLVAL(90, 2, 1), },
{ .frequency = 152000000, .index = PLLVAL(68, 1, 1), },
{ .frequency = 158000000, .index = PLLVAL(71, 1, 1), },
{ .frequency = 170000000, .index = PLLVAL(77, 1, 1), },
{ .frequency = 180000000, .index = PLLVAL(82, 1, 1), },
{ .frequency = 186000000, .index = PLLVAL(85, 1, 1), },
{ .frequency = 192000000, .index = PLLVAL(88, 1, 1), },
{ .frequency = 203000000, .index = PLLVAL(161, 3, 1), },
/* 2410A extras */
{ .frequency = 210000000, .index = PLLVAL(132, 2, 1), },
{ .frequency = 226000000, .index = PLLVAL(105, 1, 1), },
{ .frequency = 266000000, .index = PLLVAL(125, 1, 1), },
{ .frequency = 268000000, .index = PLLVAL(126, 1, 1), },
{ .frequency = 270000000, .index = PLLVAL(127, 1, 1), },
};
static int s3c2410_plls_add(struct device *dev, struct subsys_interface *sif)
{
return s3c_plltab_register(pll_vals_12MHz, ARRAY_SIZE(pll_vals_12MHz));
}
static struct subsys_interface s3c2410_plls_interface = {
.name = "s3c2410_plls",
.subsys = &s3c2410_subsys,
.add_dev = s3c2410_plls_add,
};
static int __init s3c2410_pll_init(void)
{
return subsys_interface_register(&s3c2410_plls_interface);
}
arch_initcall(s3c2410_pll_init);
static struct subsys_interface s3c2410a_plls_interface = {
.name = "s3c2410a_plls",
.subsys = &s3c2410a_subsys,
.add_dev = s3c2410_plls_add,
};
static int __init s3c2410a_pll_init(void)
{
return subsys_interface_register(&s3c2410a_plls_interface);
}
arch_initcall(s3c2410a_pll_init);
| gpl-2.0 |
hyuh/kernel-ville | drivers/mtd/maps/sun_uflash.c | 5070 | 3689 | /* sun_uflash.c - Driver for user-programmable flash on
* Sun Microsystems SME boardsets.
*
* This driver does NOT provide access to the OBP-flash for
* safety reasons-- use <linux>/drivers/sbus/char/flash.c instead.
*
* Copyright (c) 2001 Eric Brower (ebrower@usa.net)
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/slab.h>
#include <asm/prom.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#define UFLASH_OBPNAME "flashprom"
#define DRIVER_NAME "sun_uflash"
#define PFX DRIVER_NAME ": "
#define UFLASH_WINDOW_SIZE 0x200000
#define UFLASH_BUSWIDTH 1 /* EBus is 8-bit */
MODULE_AUTHOR("Eric Brower <ebrower@usa.net>");
MODULE_DESCRIPTION("User-programmable flash device on Sun Microsystems boardsets");
MODULE_SUPPORTED_DEVICE(DRIVER_NAME);
MODULE_LICENSE("GPL");
MODULE_VERSION("2.1");
struct uflash_dev {
const char *name; /* device name */
struct map_info map; /* mtd map info */
struct mtd_info *mtd; /* mtd info */
};
struct map_info uflash_map_templ = {
.name = "SUNW,???-????",
.size = UFLASH_WINDOW_SIZE,
.bankwidth = UFLASH_BUSWIDTH,
};
int uflash_devinit(struct platform_device *op, struct device_node *dp)
{
struct uflash_dev *up;
if (op->resource[1].flags) {
/* Non-CFI userflash device-- once I find one we
* can work on supporting it.
*/
printk(KERN_ERR PFX "Unsupported device at %s, 0x%llx\n",
dp->full_name, (unsigned long long)op->resource[0].start);
return -ENODEV;
}
up = kzalloc(sizeof(struct uflash_dev), GFP_KERNEL);
if (!up) {
printk(KERN_ERR PFX "Cannot allocate struct uflash_dev\n");
return -ENOMEM;
}
/* copy defaults and tweak parameters */
memcpy(&up->map, &uflash_map_templ, sizeof(uflash_map_templ));
up->map.size = resource_size(&op->resource[0]);
up->name = of_get_property(dp, "model", NULL);
if (up->name && 0 < strlen(up->name))
up->map.name = (char *)up->name;
up->map.phys = op->resource[0].start;
up->map.virt = of_ioremap(&op->resource[0], 0, up->map.size,
DRIVER_NAME);
if (!up->map.virt) {
printk(KERN_ERR PFX "Failed to map device.\n");
kfree(up);
return -EINVAL;
}
simple_map_init(&up->map);
/* MTD registration */
up->mtd = do_map_probe("cfi_probe", &up->map);
if (!up->mtd) {
of_iounmap(&op->resource[0], up->map.virt, up->map.size);
kfree(up);
return -ENXIO;
}
up->mtd->owner = THIS_MODULE;
mtd_device_register(up->mtd, NULL, 0);
dev_set_drvdata(&op->dev, up);
return 0;
}
static int __devinit uflash_probe(struct platform_device *op)
{
struct device_node *dp = op->dev.of_node;
/* Flashprom must have the "user" property in order to
* be used by this driver.
*/
if (!of_find_property(dp, "user", NULL))
return -ENODEV;
return uflash_devinit(op, dp);
}
static int __devexit uflash_remove(struct platform_device *op)
{
struct uflash_dev *up = dev_get_drvdata(&op->dev);
if (up->mtd) {
mtd_device_unregister(up->mtd);
map_destroy(up->mtd);
}
if (up->map.virt) {
of_iounmap(&op->resource[0], up->map.virt, up->map.size);
up->map.virt = NULL;
}
kfree(up);
return 0;
}
static const struct of_device_id uflash_match[] = {
{
.name = UFLASH_OBPNAME,
},
{},
};
MODULE_DEVICE_TABLE(of, uflash_match);
static struct platform_driver uflash_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
.of_match_table = uflash_match,
},
.probe = uflash_probe,
.remove = __devexit_p(uflash_remove),
};
module_platform_driver(uflash_driver);
| gpl-2.0 |
m-labs/linux-milkymist | arch/arm/mach-s3c2410/cpu-freq.c | 5070 | 3837 | /* linux/arch/arm/mach-s3c2410/cpu-freq.c
*
* Copyright (c) 2006-2008 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* S3C2410 CPU Frequency scaling
*
* 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/ioport.h>
#include <linux/cpufreq.h>
#include <linux/device.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/regs-clock.h>
#include <plat/cpu.h>
#include <plat/clock.h>
#include <plat/cpu-freq-core.h>
/* Note, 2410A has an extra mode for 1:4:4 ratio, bit 2 of CLKDIV */
static void s3c2410_cpufreq_setdivs(struct s3c_cpufreq_config *cfg)
{
u32 clkdiv = 0;
if (cfg->divs.h_divisor == 2)
clkdiv |= S3C2410_CLKDIVN_HDIVN;
if (cfg->divs.p_divisor != cfg->divs.h_divisor)
clkdiv |= S3C2410_CLKDIVN_PDIVN;
__raw_writel(clkdiv, S3C2410_CLKDIVN);
}
static int s3c2410_cpufreq_calcdivs(struct s3c_cpufreq_config *cfg)
{
unsigned long hclk, fclk, pclk;
unsigned int hdiv, pdiv;
unsigned long hclk_max;
fclk = cfg->freq.fclk;
hclk_max = cfg->max.hclk;
cfg->freq.armclk = fclk;
s3c_freq_dbg("%s: fclk is %lu, max hclk %lu\n",
__func__, fclk, hclk_max);
hdiv = (fclk > cfg->max.hclk) ? 2 : 1;
hclk = fclk / hdiv;
if (hclk > cfg->max.hclk) {
s3c_freq_dbg("%s: hclk too big\n", __func__);
return -EINVAL;
}
pdiv = (hclk > cfg->max.pclk) ? 2 : 1;
pclk = hclk / pdiv;
if (pclk > cfg->max.pclk) {
s3c_freq_dbg("%s: pclk too big\n", __func__);
return -EINVAL;
}
pdiv *= hdiv;
/* record the result */
cfg->divs.p_divisor = pdiv;
cfg->divs.h_divisor = hdiv;
return 0 ;
}
static struct s3c_cpufreq_info s3c2410_cpufreq_info = {
.max = {
.fclk = 200000000,
.hclk = 100000000,
.pclk = 50000000,
},
/* transition latency is about 5ms worst-case, so
* set 10ms to be sure */
.latency = 10000000,
.locktime_m = 150,
.locktime_u = 150,
.locktime_bits = 12,
.need_pll = 1,
.name = "s3c2410",
.calc_iotiming = s3c2410_iotiming_calc,
.set_iotiming = s3c2410_iotiming_set,
.get_iotiming = s3c2410_iotiming_get,
.resume_clocks = s3c2410_setup_clocks,
.set_fvco = s3c2410_set_fvco,
.set_refresh = s3c2410_cpufreq_setrefresh,
.set_divs = s3c2410_cpufreq_setdivs,
.calc_divs = s3c2410_cpufreq_calcdivs,
.debug_io_show = s3c_cpufreq_debugfs_call(s3c2410_iotiming_debugfs),
};
static int s3c2410_cpufreq_add(struct device *dev,
struct subsys_interface *sif)
{
return s3c_cpufreq_register(&s3c2410_cpufreq_info);
}
static struct subsys_interface s3c2410_cpufreq_interface = {
.name = "s3c2410_cpufreq",
.subsys = &s3c2410_subsys,
.add_dev = s3c2410_cpufreq_add,
};
static int __init s3c2410_cpufreq_init(void)
{
return subsys_interface_register(&s3c2410_cpufreq_interface);
}
arch_initcall(s3c2410_cpufreq_init);
static int s3c2410a_cpufreq_add(struct device *dev,
struct subsys_interface *sif)
{
/* alter the maximum freq settings for S3C2410A. If a board knows
* it only has a maximum of 200, then it should register its own
* limits. */
s3c2410_cpufreq_info.max.fclk = 266000000;
s3c2410_cpufreq_info.max.hclk = 133000000;
s3c2410_cpufreq_info.max.pclk = 66500000;
s3c2410_cpufreq_info.name = "s3c2410a";
return s3c2410_cpufreq_add(dev, sif);
}
static struct subsys_interface s3c2410a_cpufreq_interface = {
.name = "s3c2410a_cpufreq",
.subsys = &s3c2410a_subsys,
.add_dev = s3c2410a_cpufreq_add,
};
static int __init s3c2410a_cpufreq_init(void)
{
return subsys_interface_register(&s3c2410a_cpufreq_interface);
}
arch_initcall(s3c2410a_cpufreq_init);
| gpl-2.0 |
Pillar1989/linux-a80-3.4 | arch/parisc/kernel/pci-dma.c | 8142 | 16012 | /*
** PARISC 1.1 Dynamic DMA mapping support.
** This implementation is for PA-RISC platforms that do not support
** I/O TLBs (aka DMA address translation hardware).
** See Documentation/DMA-API-HOWTO.txt for interface definitions.
**
** (c) Copyright 1999,2000 Hewlett-Packard Company
** (c) Copyright 2000 Grant Grundler
** (c) Copyright 2000 Philipp Rumpf <prumpf@tux.org>
** (c) Copyright 2000 John Marvin
**
** "leveraged" from 2.3.47: arch/ia64/kernel/pci-dma.c.
** (I assume it's from David Mosberger-Tang but there was no Copyright)
**
** AFAIK, all PA7100LC and PA7300LC platforms can use this code.
**
** - ggg
*/
#include <linux/init.h>
#include <linux/gfp.h>
#include <linux/mm.h>
#include <linux/pci.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/scatterlist.h>
#include <linux/export.h>
#include <asm/cacheflush.h>
#include <asm/dma.h> /* for DMA_CHUNK_SIZE */
#include <asm/io.h>
#include <asm/page.h> /* get_order */
#include <asm/pgalloc.h>
#include <asm/uaccess.h>
#include <asm/tlbflush.h> /* for purge_tlb_*() macros */
static struct proc_dir_entry * proc_gsc_root __read_mostly = NULL;
static unsigned long pcxl_used_bytes __read_mostly = 0;
static unsigned long pcxl_used_pages __read_mostly = 0;
extern unsigned long pcxl_dma_start; /* Start of pcxl dma mapping area */
static spinlock_t pcxl_res_lock;
static char *pcxl_res_map;
static int pcxl_res_hint;
static int pcxl_res_size;
#ifdef DEBUG_PCXL_RESOURCE
#define DBG_RES(x...) printk(x)
#else
#define DBG_RES(x...)
#endif
/*
** Dump a hex representation of the resource map.
*/
#ifdef DUMP_RESMAP
static
void dump_resmap(void)
{
u_long *res_ptr = (unsigned long *)pcxl_res_map;
u_long i = 0;
printk("res_map: ");
for(; i < (pcxl_res_size / sizeof(unsigned long)); ++i, ++res_ptr)
printk("%08lx ", *res_ptr);
printk("\n");
}
#else
static inline void dump_resmap(void) {;}
#endif
static int pa11_dma_supported( struct device *dev, u64 mask)
{
return 1;
}
static inline int map_pte_uncached(pte_t * pte,
unsigned long vaddr,
unsigned long size, unsigned long *paddr_ptr)
{
unsigned long end;
unsigned long orig_vaddr = vaddr;
vaddr &= ~PMD_MASK;
end = vaddr + size;
if (end > PMD_SIZE)
end = PMD_SIZE;
do {
unsigned long flags;
if (!pte_none(*pte))
printk(KERN_ERR "map_pte_uncached: page already exists\n");
set_pte(pte, __mk_pte(*paddr_ptr, PAGE_KERNEL_UNC));
purge_tlb_start(flags);
pdtlb_kernel(orig_vaddr);
purge_tlb_end(flags);
vaddr += PAGE_SIZE;
orig_vaddr += PAGE_SIZE;
(*paddr_ptr) += PAGE_SIZE;
pte++;
} while (vaddr < end);
return 0;
}
static inline int map_pmd_uncached(pmd_t * pmd, unsigned long vaddr,
unsigned long size, unsigned long *paddr_ptr)
{
unsigned long end;
unsigned long orig_vaddr = vaddr;
vaddr &= ~PGDIR_MASK;
end = vaddr + size;
if (end > PGDIR_SIZE)
end = PGDIR_SIZE;
do {
pte_t * pte = pte_alloc_kernel(pmd, vaddr);
if (!pte)
return -ENOMEM;
if (map_pte_uncached(pte, orig_vaddr, end - vaddr, paddr_ptr))
return -ENOMEM;
vaddr = (vaddr + PMD_SIZE) & PMD_MASK;
orig_vaddr += PMD_SIZE;
pmd++;
} while (vaddr < end);
return 0;
}
static inline int map_uncached_pages(unsigned long vaddr, unsigned long size,
unsigned long paddr)
{
pgd_t * dir;
unsigned long end = vaddr + size;
dir = pgd_offset_k(vaddr);
do {
pmd_t *pmd;
pmd = pmd_alloc(NULL, dir, vaddr);
if (!pmd)
return -ENOMEM;
if (map_pmd_uncached(pmd, vaddr, end - vaddr, &paddr))
return -ENOMEM;
vaddr = vaddr + PGDIR_SIZE;
dir++;
} while (vaddr && (vaddr < end));
return 0;
}
static inline void unmap_uncached_pte(pmd_t * pmd, unsigned long vaddr,
unsigned long size)
{
pte_t * pte;
unsigned long end;
unsigned long orig_vaddr = vaddr;
if (pmd_none(*pmd))
return;
if (pmd_bad(*pmd)) {
pmd_ERROR(*pmd);
pmd_clear(pmd);
return;
}
pte = pte_offset_map(pmd, vaddr);
vaddr &= ~PMD_MASK;
end = vaddr + size;
if (end > PMD_SIZE)
end = PMD_SIZE;
do {
unsigned long flags;
pte_t page = *pte;
pte_clear(&init_mm, vaddr, pte);
purge_tlb_start(flags);
pdtlb_kernel(orig_vaddr);
purge_tlb_end(flags);
vaddr += PAGE_SIZE;
orig_vaddr += PAGE_SIZE;
pte++;
if (pte_none(page) || pte_present(page))
continue;
printk(KERN_CRIT "Whee.. Swapped out page in kernel page table\n");
} while (vaddr < end);
}
static inline void unmap_uncached_pmd(pgd_t * dir, unsigned long vaddr,
unsigned long size)
{
pmd_t * pmd;
unsigned long end;
unsigned long orig_vaddr = vaddr;
if (pgd_none(*dir))
return;
if (pgd_bad(*dir)) {
pgd_ERROR(*dir);
pgd_clear(dir);
return;
}
pmd = pmd_offset(dir, vaddr);
vaddr &= ~PGDIR_MASK;
end = vaddr + size;
if (end > PGDIR_SIZE)
end = PGDIR_SIZE;
do {
unmap_uncached_pte(pmd, orig_vaddr, end - vaddr);
vaddr = (vaddr + PMD_SIZE) & PMD_MASK;
orig_vaddr += PMD_SIZE;
pmd++;
} while (vaddr < end);
}
static void unmap_uncached_pages(unsigned long vaddr, unsigned long size)
{
pgd_t * dir;
unsigned long end = vaddr + size;
dir = pgd_offset_k(vaddr);
do {
unmap_uncached_pmd(dir, vaddr, end - vaddr);
vaddr = vaddr + PGDIR_SIZE;
dir++;
} while (vaddr && (vaddr < end));
}
#define PCXL_SEARCH_LOOP(idx, mask, size) \
for(; res_ptr < res_end; ++res_ptr) \
{ \
if(0 == ((*res_ptr) & mask)) { \
*res_ptr |= mask; \
idx = (int)((u_long)res_ptr - (u_long)pcxl_res_map); \
pcxl_res_hint = idx + (size >> 3); \
goto resource_found; \
} \
}
#define PCXL_FIND_FREE_MAPPING(idx, mask, size) { \
u##size *res_ptr = (u##size *)&(pcxl_res_map[pcxl_res_hint & ~((size >> 3) - 1)]); \
u##size *res_end = (u##size *)&pcxl_res_map[pcxl_res_size]; \
PCXL_SEARCH_LOOP(idx, mask, size); \
res_ptr = (u##size *)&pcxl_res_map[0]; \
PCXL_SEARCH_LOOP(idx, mask, size); \
}
unsigned long
pcxl_alloc_range(size_t size)
{
int res_idx;
u_long mask, flags;
unsigned int pages_needed = size >> PAGE_SHIFT;
mask = (u_long) -1L;
mask >>= BITS_PER_LONG - pages_needed;
DBG_RES("pcxl_alloc_range() size: %d pages_needed %d pages_mask 0x%08lx\n",
size, pages_needed, mask);
spin_lock_irqsave(&pcxl_res_lock, flags);
if(pages_needed <= 8) {
PCXL_FIND_FREE_MAPPING(res_idx, mask, 8);
} else if(pages_needed <= 16) {
PCXL_FIND_FREE_MAPPING(res_idx, mask, 16);
} else if(pages_needed <= 32) {
PCXL_FIND_FREE_MAPPING(res_idx, mask, 32);
} else {
panic("%s: pcxl_alloc_range() Too many pages to map.\n",
__FILE__);
}
dump_resmap();
panic("%s: pcxl_alloc_range() out of dma mapping resources\n",
__FILE__);
resource_found:
DBG_RES("pcxl_alloc_range() res_idx %d mask 0x%08lx res_hint: %d\n",
res_idx, mask, pcxl_res_hint);
pcxl_used_pages += pages_needed;
pcxl_used_bytes += ((pages_needed >> 3) ? (pages_needed >> 3) : 1);
spin_unlock_irqrestore(&pcxl_res_lock, flags);
dump_resmap();
/*
** return the corresponding vaddr in the pcxl dma map
*/
return (pcxl_dma_start + (res_idx << (PAGE_SHIFT + 3)));
}
#define PCXL_FREE_MAPPINGS(idx, m, size) \
u##size *res_ptr = (u##size *)&(pcxl_res_map[(idx) + (((size >> 3) - 1) & (~((size >> 3) - 1)))]); \
/* BUG_ON((*res_ptr & m) != m); */ \
*res_ptr &= ~m;
/*
** clear bits in the pcxl resource map
*/
static void
pcxl_free_range(unsigned long vaddr, size_t size)
{
u_long mask, flags;
unsigned int res_idx = (vaddr - pcxl_dma_start) >> (PAGE_SHIFT + 3);
unsigned int pages_mapped = size >> PAGE_SHIFT;
mask = (u_long) -1L;
mask >>= BITS_PER_LONG - pages_mapped;
DBG_RES("pcxl_free_range() res_idx: %d size: %d pages_mapped %d mask 0x%08lx\n",
res_idx, size, pages_mapped, mask);
spin_lock_irqsave(&pcxl_res_lock, flags);
if(pages_mapped <= 8) {
PCXL_FREE_MAPPINGS(res_idx, mask, 8);
} else if(pages_mapped <= 16) {
PCXL_FREE_MAPPINGS(res_idx, mask, 16);
} else if(pages_mapped <= 32) {
PCXL_FREE_MAPPINGS(res_idx, mask, 32);
} else {
panic("%s: pcxl_free_range() Too many pages to unmap.\n",
__FILE__);
}
pcxl_used_pages -= (pages_mapped ? pages_mapped : 1);
pcxl_used_bytes -= ((pages_mapped >> 3) ? (pages_mapped >> 3) : 1);
spin_unlock_irqrestore(&pcxl_res_lock, flags);
dump_resmap();
}
static int proc_pcxl_dma_show(struct seq_file *m, void *v)
{
#if 0
u_long i = 0;
unsigned long *res_ptr = (u_long *)pcxl_res_map;
#endif
unsigned long total_pages = pcxl_res_size << 3; /* 8 bits per byte */
seq_printf(m, "\nDMA Mapping Area size : %d bytes (%ld pages)\n",
PCXL_DMA_MAP_SIZE, total_pages);
seq_printf(m, "Resource bitmap : %d bytes\n", pcxl_res_size);
seq_puts(m, " total: free: used: % used:\n");
seq_printf(m, "blocks %8d %8ld %8ld %8ld%%\n", pcxl_res_size,
pcxl_res_size - pcxl_used_bytes, pcxl_used_bytes,
(pcxl_used_bytes * 100) / pcxl_res_size);
seq_printf(m, "pages %8ld %8ld %8ld %8ld%%\n", total_pages,
total_pages - pcxl_used_pages, pcxl_used_pages,
(pcxl_used_pages * 100 / total_pages));
#if 0
seq_puts(m, "\nResource bitmap:");
for(; i < (pcxl_res_size / sizeof(u_long)); ++i, ++res_ptr) {
if ((i & 7) == 0)
seq_puts(m,"\n ");
seq_printf(m, "%s %08lx", buf, *res_ptr);
}
#endif
seq_putc(m, '\n');
return 0;
}
static int proc_pcxl_dma_open(struct inode *inode, struct file *file)
{
return single_open(file, proc_pcxl_dma_show, NULL);
}
static const struct file_operations proc_pcxl_dma_ops = {
.owner = THIS_MODULE,
.open = proc_pcxl_dma_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init
pcxl_dma_init(void)
{
if (pcxl_dma_start == 0)
return 0;
spin_lock_init(&pcxl_res_lock);
pcxl_res_size = PCXL_DMA_MAP_SIZE >> (PAGE_SHIFT + 3);
pcxl_res_hint = 0;
pcxl_res_map = (char *)__get_free_pages(GFP_KERNEL,
get_order(pcxl_res_size));
memset(pcxl_res_map, 0, pcxl_res_size);
proc_gsc_root = proc_mkdir("gsc", NULL);
if (!proc_gsc_root)
printk(KERN_WARNING
"pcxl_dma_init: Unable to create gsc /proc dir entry\n");
else {
struct proc_dir_entry* ent;
ent = proc_create("pcxl_dma", 0, proc_gsc_root,
&proc_pcxl_dma_ops);
if (!ent)
printk(KERN_WARNING
"pci-dma.c: Unable to create pcxl_dma /proc entry.\n");
}
return 0;
}
__initcall(pcxl_dma_init);
static void * pa11_dma_alloc_consistent (struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flag)
{
unsigned long vaddr;
unsigned long paddr;
int order;
order = get_order(size);
size = 1 << (order + PAGE_SHIFT);
vaddr = pcxl_alloc_range(size);
paddr = __get_free_pages(flag, order);
flush_kernel_dcache_range(paddr, size);
paddr = __pa(paddr);
map_uncached_pages(vaddr, size, paddr);
*dma_handle = (dma_addr_t) paddr;
#if 0
/* This probably isn't needed to support EISA cards.
** ISA cards will certainly only support 24-bit DMA addressing.
** Not clear if we can, want, or need to support ISA.
*/
if (!dev || *dev->coherent_dma_mask < 0xffffffff)
gfp |= GFP_DMA;
#endif
return (void *)vaddr;
}
static void pa11_dma_free_consistent (struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle)
{
int order;
order = get_order(size);
size = 1 << (order + PAGE_SHIFT);
unmap_uncached_pages((unsigned long)vaddr, size);
pcxl_free_range((unsigned long)vaddr, size);
free_pages((unsigned long)__va(dma_handle), order);
}
static dma_addr_t pa11_dma_map_single(struct device *dev, void *addr, size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
flush_kernel_dcache_range((unsigned long) addr, size);
return virt_to_phys(addr);
}
static void pa11_dma_unmap_single(struct device *dev, dma_addr_t dma_handle, size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
if (direction == DMA_TO_DEVICE)
return;
/*
* For PCI_DMA_FROMDEVICE this flush is not necessary for the
* simple map/unmap case. However, it IS necessary if if
* pci_dma_sync_single_* has been called and the buffer reused.
*/
flush_kernel_dcache_range((unsigned long) phys_to_virt(dma_handle), size);
return;
}
static int pa11_dma_map_sg(struct device *dev, struct scatterlist *sglist, int nents, enum dma_data_direction direction)
{
int i;
BUG_ON(direction == DMA_NONE);
for (i = 0; i < nents; i++, sglist++ ) {
unsigned long vaddr = sg_virt_addr(sglist);
sg_dma_address(sglist) = (dma_addr_t) virt_to_phys(vaddr);
sg_dma_len(sglist) = sglist->length;
flush_kernel_dcache_range(vaddr, sglist->length);
}
return nents;
}
static void pa11_dma_unmap_sg(struct device *dev, struct scatterlist *sglist, int nents, enum dma_data_direction direction)
{
int i;
BUG_ON(direction == DMA_NONE);
if (direction == DMA_TO_DEVICE)
return;
/* once we do combining we'll need to use phys_to_virt(sg_dma_address(sglist)) */
for (i = 0; i < nents; i++, sglist++ )
flush_kernel_dcache_range(sg_virt_addr(sglist), sglist->length);
return;
}
static void pa11_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle, unsigned long offset, size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
flush_kernel_dcache_range((unsigned long) phys_to_virt(dma_handle) + offset, size);
}
static void pa11_dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle, unsigned long offset, size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
flush_kernel_dcache_range((unsigned long) phys_to_virt(dma_handle) + offset, size);
}
static void pa11_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sglist, int nents, enum dma_data_direction direction)
{
int i;
/* once we do combining we'll need to use phys_to_virt(sg_dma_address(sglist)) */
for (i = 0; i < nents; i++, sglist++ )
flush_kernel_dcache_range(sg_virt_addr(sglist), sglist->length);
}
static void pa11_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sglist, int nents, enum dma_data_direction direction)
{
int i;
/* once we do combining we'll need to use phys_to_virt(sg_dma_address(sglist)) */
for (i = 0; i < nents; i++, sglist++ )
flush_kernel_dcache_range(sg_virt_addr(sglist), sglist->length);
}
struct hppa_dma_ops pcxl_dma_ops = {
.dma_supported = pa11_dma_supported,
.alloc_consistent = pa11_dma_alloc_consistent,
.alloc_noncoherent = pa11_dma_alloc_consistent,
.free_consistent = pa11_dma_free_consistent,
.map_single = pa11_dma_map_single,
.unmap_single = pa11_dma_unmap_single,
.map_sg = pa11_dma_map_sg,
.unmap_sg = pa11_dma_unmap_sg,
.dma_sync_single_for_cpu = pa11_dma_sync_single_for_cpu,
.dma_sync_single_for_device = pa11_dma_sync_single_for_device,
.dma_sync_sg_for_cpu = pa11_dma_sync_sg_for_cpu,
.dma_sync_sg_for_device = pa11_dma_sync_sg_for_device,
};
static void *fail_alloc_consistent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flag)
{
return NULL;
}
static void *pa11_dma_alloc_noncoherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flag)
{
void *addr;
addr = (void *)__get_free_pages(flag, get_order(size));
if (addr)
*dma_handle = (dma_addr_t)virt_to_phys(addr);
return addr;
}
static void pa11_dma_free_noncoherent(struct device *dev, size_t size,
void *vaddr, dma_addr_t iova)
{
free_pages((unsigned long)vaddr, get_order(size));
return;
}
struct hppa_dma_ops pcx_dma_ops = {
.dma_supported = pa11_dma_supported,
.alloc_consistent = fail_alloc_consistent,
.alloc_noncoherent = pa11_dma_alloc_noncoherent,
.free_consistent = pa11_dma_free_noncoherent,
.map_single = pa11_dma_map_single,
.unmap_single = pa11_dma_unmap_single,
.map_sg = pa11_dma_map_sg,
.unmap_sg = pa11_dma_unmap_sg,
.dma_sync_single_for_cpu = pa11_dma_sync_single_for_cpu,
.dma_sync_single_for_device = pa11_dma_sync_single_for_device,
.dma_sync_sg_for_cpu = pa11_dma_sync_sg_for_cpu,
.dma_sync_sg_for_device = pa11_dma_sync_sg_for_device,
};
| gpl-2.0 |
FennyFatal/SGS4-M919-FennyKernel | sound/pci/asihpi/hpi6000.c | 8398 | 49704 | /******************************************************************************
AudioScience HPI driver
Copyright (C) 1997-2011 AudioScience Inc. <support@audioscience.com>
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
Hardware Programming Interface (HPI) for AudioScience ASI6200 series adapters.
These PCI bus adapters are based on the TI C6711 DSP.
Exported functions:
void HPI_6000(struct hpi_message *phm, struct hpi_response *phr)
#defines
HIDE_PCI_ASSERTS to show the PCI asserts
PROFILE_DSP2 get profile data from DSP2 if present (instead of DSP 1)
(C) Copyright AudioScience Inc. 1998-2003
*******************************************************************************/
#define SOURCEFILE_NAME "hpi6000.c"
#include "hpi_internal.h"
#include "hpimsginit.h"
#include "hpidebug.h"
#include "hpi6000.h"
#include "hpidspcd.h"
#include "hpicmn.h"
#define HPI_HIF_BASE (0x00000200) /* start of C67xx internal RAM */
#define HPI_HIF_ADDR(member) \
(HPI_HIF_BASE + offsetof(struct hpi_hif_6000, member))
#define HPI_HIF_ERROR_MASK 0x4000
/* HPI6000 specific error codes */
#define HPI6000_ERROR_BASE 900 /* not actually used anywhere */
/* operational/messaging errors */
#define HPI6000_ERROR_MSG_RESP_IDLE_TIMEOUT 901
#define HPI6000_ERROR_MSG_RESP_GET_RESP_ACK 903
#define HPI6000_ERROR_MSG_GET_ADR 904
#define HPI6000_ERROR_RESP_GET_ADR 905
#define HPI6000_ERROR_MSG_RESP_BLOCKWRITE32 906
#define HPI6000_ERROR_MSG_RESP_BLOCKREAD32 907
#define HPI6000_ERROR_CONTROL_CACHE_PARAMS 909
#define HPI6000_ERROR_SEND_DATA_IDLE_TIMEOUT 911
#define HPI6000_ERROR_SEND_DATA_ACK 912
#define HPI6000_ERROR_SEND_DATA_ADR 913
#define HPI6000_ERROR_SEND_DATA_TIMEOUT 914
#define HPI6000_ERROR_SEND_DATA_CMD 915
#define HPI6000_ERROR_SEND_DATA_WRITE 916
#define HPI6000_ERROR_SEND_DATA_IDLECMD 917
#define HPI6000_ERROR_GET_DATA_IDLE_TIMEOUT 921
#define HPI6000_ERROR_GET_DATA_ACK 922
#define HPI6000_ERROR_GET_DATA_CMD 923
#define HPI6000_ERROR_GET_DATA_READ 924
#define HPI6000_ERROR_GET_DATA_IDLECMD 925
#define HPI6000_ERROR_CONTROL_CACHE_ADDRLEN 951
#define HPI6000_ERROR_CONTROL_CACHE_READ 952
#define HPI6000_ERROR_CONTROL_CACHE_FLUSH 953
#define HPI6000_ERROR_MSG_RESP_GETRESPCMD 961
#define HPI6000_ERROR_MSG_RESP_IDLECMD 962
/* Initialisation/bootload errors */
#define HPI6000_ERROR_UNHANDLED_SUBSYS_ID 930
/* can't access PCI2040 */
#define HPI6000_ERROR_INIT_PCI2040 931
/* can't access DSP HPI i/f */
#define HPI6000_ERROR_INIT_DSPHPI 932
/* can't access internal DSP memory */
#define HPI6000_ERROR_INIT_DSPINTMEM 933
/* can't access SDRAM - test#1 */
#define HPI6000_ERROR_INIT_SDRAM1 934
/* can't access SDRAM - test#2 */
#define HPI6000_ERROR_INIT_SDRAM2 935
#define HPI6000_ERROR_INIT_VERIFY 938
#define HPI6000_ERROR_INIT_NOACK 939
#define HPI6000_ERROR_INIT_PLDTEST1 941
#define HPI6000_ERROR_INIT_PLDTEST2 942
/* local defines */
#define HIDE_PCI_ASSERTS
#define PROFILE_DSP2
/* for PCI2040 i/f chip */
/* HPI CSR registers */
/* word offsets from CSR base */
/* use when io addresses defined as u32 * */
#define INTERRUPT_EVENT_SET 0
#define INTERRUPT_EVENT_CLEAR 1
#define INTERRUPT_MASK_SET 2
#define INTERRUPT_MASK_CLEAR 3
#define HPI_ERROR_REPORT 4
#define HPI_RESET 5
#define HPI_DATA_WIDTH 6
#define MAX_DSPS 2
/* HPI registers, spaced 8K bytes = 2K words apart */
#define DSP_SPACING 0x800
#define CONTROL 0x0000
#define ADDRESS 0x0200
#define DATA_AUTOINC 0x0400
#define DATA 0x0600
#define TIMEOUT 500000
struct dsp_obj {
__iomem u32 *prHPI_control;
__iomem u32 *prHPI_address;
__iomem u32 *prHPI_data;
__iomem u32 *prHPI_data_auto_inc;
char c_dsp_rev; /*A, B */
u32 control_cache_address_on_dsp;
u32 control_cache_length_on_dsp;
struct hpi_adapter_obj *pa_parent_adapter;
};
struct hpi_hw_obj {
__iomem u32 *dw2040_HPICSR;
__iomem u32 *dw2040_HPIDSP;
u16 num_dsp;
struct dsp_obj ado[MAX_DSPS];
u32 message_buffer_address_on_dsp;
u32 response_buffer_address_on_dsp;
u32 pCI2040HPI_error_count;
struct hpi_control_cache_single control_cache[HPI_NMIXER_CONTROLS];
struct hpi_control_cache *p_cache;
};
static u16 hpi6000_dsp_block_write32(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 hpi_address, u32 *source, u32 count);
static u16 hpi6000_dsp_block_read32(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 hpi_address, u32 *dest, u32 count);
static short hpi6000_adapter_boot_load_dsp(struct hpi_adapter_obj *pao,
u32 *pos_error_code);
static short hpi6000_check_PCI2040_error_flag(struct hpi_adapter_obj *pao,
u16 read_or_write);
#define H6READ 1
#define H6WRITE 0
static short hpi6000_update_control_cache(struct hpi_adapter_obj *pao,
struct hpi_message *phm);
static short hpi6000_message_response_sequence(struct hpi_adapter_obj *pao,
u16 dsp_index, struct hpi_message *phm, struct hpi_response *phr);
static void hw_message(struct hpi_adapter_obj *pao, struct hpi_message *phm,
struct hpi_response *phr);
static short hpi6000_wait_dsp_ack(struct hpi_adapter_obj *pao, u16 dsp_index,
u32 ack_value);
static short hpi6000_send_host_command(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 host_cmd);
static void hpi6000_send_dsp_interrupt(struct dsp_obj *pdo);
static short hpi6000_send_data(struct hpi_adapter_obj *pao, u16 dsp_index,
struct hpi_message *phm, struct hpi_response *phr);
static short hpi6000_get_data(struct hpi_adapter_obj *pao, u16 dsp_index,
struct hpi_message *phm, struct hpi_response *phr);
static void hpi_write_word(struct dsp_obj *pdo, u32 address, u32 data);
static u32 hpi_read_word(struct dsp_obj *pdo, u32 address);
static void hpi_write_block(struct dsp_obj *pdo, u32 address, u32 *pdata,
u32 length);
static void hpi_read_block(struct dsp_obj *pdo, u32 address, u32 *pdata,
u32 length);
static void subsys_create_adapter(struct hpi_message *phm,
struct hpi_response *phr);
static void adapter_delete(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void adapter_get_asserts(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static short create_adapter_obj(struct hpi_adapter_obj *pao,
u32 *pos_error_code);
static void delete_adapter_obj(struct hpi_adapter_obj *pao);
/* local globals */
static u16 gw_pci_read_asserts; /* used to count PCI2040 errors */
static u16 gw_pci_write_asserts; /* used to count PCI2040 errors */
static void subsys_message(struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_SUBSYS_CREATE_ADAPTER:
subsys_create_adapter(phm, phr);
break;
default:
phr->error = HPI_ERROR_INVALID_FUNC;
break;
}
}
static void control_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
switch (phm->function) {
case HPI_CONTROL_GET_STATE:
if (pao->has_control_cache) {
u16 err;
err = hpi6000_update_control_cache(pao, phm);
if (err) {
if (err >= HPI_ERROR_BACKEND_BASE) {
phr->error =
HPI_ERROR_CONTROL_CACHING;
phr->specific_error = err;
} else {
phr->error = err;
}
break;
}
if (hpi_check_control_cache(phw->p_cache, phm, phr))
break;
}
hw_message(pao, phm, phr);
break;
case HPI_CONTROL_SET_STATE:
hw_message(pao, phm, phr);
hpi_cmn_control_cache_sync_to_msg(phw->p_cache, phm, phr);
break;
case HPI_CONTROL_GET_INFO:
default:
hw_message(pao, phm, phr);
break;
}
}
static void adapter_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_ADAPTER_GET_ASSERT:
adapter_get_asserts(pao, phm, phr);
break;
case HPI_ADAPTER_DELETE:
adapter_delete(pao, phm, phr);
break;
default:
hw_message(pao, phm, phr);
break;
}
}
static void outstream_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_OSTREAM_HOSTBUFFER_ALLOC:
case HPI_OSTREAM_HOSTBUFFER_FREE:
/* Don't let these messages go to the HW function because
* they're called without locking the spinlock.
* For the HPI6000 adapters the HW would return
* HPI_ERROR_INVALID_FUNC anyway.
*/
phr->error = HPI_ERROR_INVALID_FUNC;
break;
default:
hw_message(pao, phm, phr);
return;
}
}
static void instream_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_ISTREAM_HOSTBUFFER_ALLOC:
case HPI_ISTREAM_HOSTBUFFER_FREE:
/* Don't let these messages go to the HW function because
* they're called without locking the spinlock.
* For the HPI6000 adapters the HW would return
* HPI_ERROR_INVALID_FUNC anyway.
*/
phr->error = HPI_ERROR_INVALID_FUNC;
break;
default:
hw_message(pao, phm, phr);
return;
}
}
/************************************************************************/
/** HPI_6000()
* Entry point from HPIMAN
* All calls to the HPI start here
*/
void HPI_6000(struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_adapter_obj *pao = NULL;
if (phm->object != HPI_OBJ_SUBSYSTEM) {
pao = hpi_find_adapter(phm->adapter_index);
if (!pao) {
hpi_init_response(phr, phm->object, phm->function,
HPI_ERROR_BAD_ADAPTER_NUMBER);
HPI_DEBUG_LOG(DEBUG, "invalid adapter index: %d \n",
phm->adapter_index);
return;
}
/* Don't even try to communicate with crashed DSP */
if (pao->dsp_crashed >= 10) {
hpi_init_response(phr, phm->object, phm->function,
HPI_ERROR_DSP_HARDWARE);
HPI_DEBUG_LOG(DEBUG, "adapter %d dsp crashed\n",
phm->adapter_index);
return;
}
}
/* Init default response including the size field */
if (phm->function != HPI_SUBSYS_CREATE_ADAPTER)
hpi_init_response(phr, phm->object, phm->function,
HPI_ERROR_PROCESSING_MESSAGE);
switch (phm->type) {
case HPI_TYPE_REQUEST:
switch (phm->object) {
case HPI_OBJ_SUBSYSTEM:
subsys_message(phm, phr);
break;
case HPI_OBJ_ADAPTER:
phr->size =
sizeof(struct hpi_response_header) +
sizeof(struct hpi_adapter_res);
adapter_message(pao, phm, phr);
break;
case HPI_OBJ_CONTROL:
control_message(pao, phm, phr);
break;
case HPI_OBJ_OSTREAM:
outstream_message(pao, phm, phr);
break;
case HPI_OBJ_ISTREAM:
instream_message(pao, phm, phr);
break;
default:
hw_message(pao, phm, phr);
break;
}
break;
default:
phr->error = HPI_ERROR_INVALID_TYPE;
break;
}
}
/************************************************************************/
/* SUBSYSTEM */
/* create an adapter object and initialise it based on resource information
* passed in in the message
* NOTE - you cannot use this function AND the FindAdapters function at the
* same time, the application must use only one of them to get the adapters
*/
static void subsys_create_adapter(struct hpi_message *phm,
struct hpi_response *phr)
{
/* create temp adapter obj, because we don't know what index yet */
struct hpi_adapter_obj ao;
struct hpi_adapter_obj *pao;
u32 os_error_code;
u16 err = 0;
u32 dsp_index = 0;
HPI_DEBUG_LOG(VERBOSE, "subsys_create_adapter\n");
memset(&ao, 0, sizeof(ao));
ao.priv = kzalloc(sizeof(struct hpi_hw_obj), GFP_KERNEL);
if (!ao.priv) {
HPI_DEBUG_LOG(ERROR, "can't get mem for adapter object\n");
phr->error = HPI_ERROR_MEMORY_ALLOC;
return;
}
/* create the adapter object based on the resource information */
ao.pci = *phm->u.s.resource.r.pci;
err = create_adapter_obj(&ao, &os_error_code);
if (err) {
delete_adapter_obj(&ao);
if (err >= HPI_ERROR_BACKEND_BASE) {
phr->error = HPI_ERROR_DSP_BOOTLOAD;
phr->specific_error = err;
} else {
phr->error = err;
}
phr->u.s.data = os_error_code;
return;
}
/* need to update paParentAdapter */
pao = hpi_find_adapter(ao.index);
if (!pao) {
/* We just added this adapter, why can't we find it!? */
HPI_DEBUG_LOG(ERROR, "lost adapter after boot\n");
phr->error = HPI_ERROR_BAD_ADAPTER;
return;
}
for (dsp_index = 0; dsp_index < MAX_DSPS; dsp_index++) {
struct hpi_hw_obj *phw = pao->priv;
phw->ado[dsp_index].pa_parent_adapter = pao;
}
phr->u.s.adapter_type = ao.type;
phr->u.s.adapter_index = ao.index;
phr->error = 0;
}
static void adapter_delete(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
delete_adapter_obj(pao);
hpi_delete_adapter(pao);
phr->error = 0;
}
/* this routine is called from SubSysFindAdapter and SubSysCreateAdapter */
static short create_adapter_obj(struct hpi_adapter_obj *pao,
u32 *pos_error_code)
{
short boot_error = 0;
u32 dsp_index = 0;
u32 control_cache_size = 0;
u32 control_cache_count = 0;
struct hpi_hw_obj *phw = pao->priv;
/* The PCI2040 has the following address map */
/* BAR0 - 4K = HPI control and status registers on PCI2040 (HPI CSR) */
/* BAR1 - 32K = HPI registers on DSP */
phw->dw2040_HPICSR = pao->pci.ap_mem_base[0];
phw->dw2040_HPIDSP = pao->pci.ap_mem_base[1];
HPI_DEBUG_LOG(VERBOSE, "csr %p, dsp %p\n", phw->dw2040_HPICSR,
phw->dw2040_HPIDSP);
/* set addresses for the possible DSP HPI interfaces */
for (dsp_index = 0; dsp_index < MAX_DSPS; dsp_index++) {
phw->ado[dsp_index].prHPI_control =
phw->dw2040_HPIDSP + (CONTROL +
DSP_SPACING * dsp_index);
phw->ado[dsp_index].prHPI_address =
phw->dw2040_HPIDSP + (ADDRESS +
DSP_SPACING * dsp_index);
phw->ado[dsp_index].prHPI_data =
phw->dw2040_HPIDSP + (DATA + DSP_SPACING * dsp_index);
phw->ado[dsp_index].prHPI_data_auto_inc =
phw->dw2040_HPIDSP + (DATA_AUTOINC +
DSP_SPACING * dsp_index);
HPI_DEBUG_LOG(VERBOSE, "ctl %p, adr %p, dat %p, dat++ %p\n",
phw->ado[dsp_index].prHPI_control,
phw->ado[dsp_index].prHPI_address,
phw->ado[dsp_index].prHPI_data,
phw->ado[dsp_index].prHPI_data_auto_inc);
phw->ado[dsp_index].pa_parent_adapter = pao;
}
phw->pCI2040HPI_error_count = 0;
pao->has_control_cache = 0;
/* Set the default number of DSPs on this card */
/* This is (conditionally) adjusted after bootloading */
/* of the first DSP in the bootload section. */
phw->num_dsp = 1;
boot_error = hpi6000_adapter_boot_load_dsp(pao, pos_error_code);
if (boot_error)
return boot_error;
HPI_DEBUG_LOG(INFO, "bootload DSP OK\n");
phw->message_buffer_address_on_dsp = 0L;
phw->response_buffer_address_on_dsp = 0L;
/* get info about the adapter by asking the adapter */
/* send a HPI_ADAPTER_GET_INFO message */
{
struct hpi_message hm;
struct hpi_response hr0; /* response from DSP 0 */
struct hpi_response hr1; /* response from DSP 1 */
u16 error = 0;
HPI_DEBUG_LOG(VERBOSE, "send ADAPTER_GET_INFO\n");
memset(&hm, 0, sizeof(hm));
hm.type = HPI_TYPE_REQUEST;
hm.size = sizeof(struct hpi_message);
hm.object = HPI_OBJ_ADAPTER;
hm.function = HPI_ADAPTER_GET_INFO;
hm.adapter_index = 0;
memset(&hr0, 0, sizeof(hr0));
memset(&hr1, 0, sizeof(hr1));
hr0.size = sizeof(hr0);
hr1.size = sizeof(hr1);
error = hpi6000_message_response_sequence(pao, 0, &hm, &hr0);
if (hr0.error) {
HPI_DEBUG_LOG(DEBUG, "message error %d\n", hr0.error);
return hr0.error;
}
if (phw->num_dsp == 2) {
error = hpi6000_message_response_sequence(pao, 1, &hm,
&hr1);
if (error)
return error;
}
pao->type = hr0.u.ax.info.adapter_type;
pao->index = hr0.u.ax.info.adapter_index;
}
memset(&phw->control_cache[0], 0,
sizeof(struct hpi_control_cache_single) *
HPI_NMIXER_CONTROLS);
/* Read the control cache length to figure out if it is turned on */
control_cache_size =
hpi_read_word(&phw->ado[0],
HPI_HIF_ADDR(control_cache_size_in_bytes));
if (control_cache_size) {
control_cache_count =
hpi_read_word(&phw->ado[0],
HPI_HIF_ADDR(control_cache_count));
phw->p_cache =
hpi_alloc_control_cache(control_cache_count,
control_cache_size, (unsigned char *)
&phw->control_cache[0]
);
if (phw->p_cache)
pao->has_control_cache = 1;
}
HPI_DEBUG_LOG(DEBUG, "get adapter info ASI%04X index %d\n", pao->type,
pao->index);
if (phw->p_cache)
phw->p_cache->adap_idx = pao->index;
return hpi_add_adapter(pao);
}
static void delete_adapter_obj(struct hpi_adapter_obj *pao)
{
struct hpi_hw_obj *phw = pao->priv;
if (pao->has_control_cache)
hpi_free_control_cache(phw->p_cache);
/* reset DSPs on adapter */
iowrite32(0x0003000F, phw->dw2040_HPICSR + HPI_RESET);
kfree(phw);
}
/************************************************************************/
/* ADAPTER */
static void adapter_get_asserts(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
#ifndef HIDE_PCI_ASSERTS
/* if we have PCI2040 asserts then collect them */
if ((gw_pci_read_asserts > 0) || (gw_pci_write_asserts > 0)) {
phr->u.ax.assert.p1 =
gw_pci_read_asserts * 100 + gw_pci_write_asserts;
phr->u.ax.assert.p2 = 0;
phr->u.ax.assert.count = 1; /* assert count */
phr->u.ax.assert.dsp_index = -1; /* "dsp index" */
strcpy(phr->u.ax.assert.sz_message, "PCI2040 error");
phr->u.ax.assert.dsp_msg_addr = 0;
gw_pci_read_asserts = 0;
gw_pci_write_asserts = 0;
phr->error = 0;
} else
#endif
hw_message(pao, phm, phr); /*get DSP asserts */
return;
}
/************************************************************************/
/* LOW-LEVEL */
static short hpi6000_adapter_boot_load_dsp(struct hpi_adapter_obj *pao,
u32 *pos_error_code)
{
struct hpi_hw_obj *phw = pao->priv;
short error;
u32 timeout;
u32 read = 0;
u32 i = 0;
u32 data = 0;
u32 j = 0;
u32 test_addr = 0x80000000;
u32 test_data = 0x00000001;
u32 dw2040_reset = 0;
u32 dsp_index = 0;
u32 endian = 0;
u32 adapter_info = 0;
u32 delay = 0;
struct dsp_code dsp_code;
u16 boot_load_family = 0;
/* NOTE don't use wAdapterType in this routine. It is not setup yet */
switch (pao->pci.pci_dev->subsystem_device) {
case 0x5100:
case 0x5110: /* ASI5100 revB or higher with C6711D */
case 0x5200: /* ASI5200 PCIe version of ASI5100 */
case 0x6100:
case 0x6200:
boot_load_family = HPI_ADAPTER_FAMILY_ASI(0x6200);
break;
default:
return HPI6000_ERROR_UNHANDLED_SUBSYS_ID;
}
/* reset all DSPs, indicate two DSPs are present
* set RST3-=1 to disconnect HAD8 to set DSP in little endian mode
*/
endian = 0;
dw2040_reset = 0x0003000F;
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
/* read back register to make sure PCI2040 chip is functioning
* note that bits 4..15 are read-only and so should always return zero,
* even though we wrote 1 to them
*/
hpios_delay_micro_seconds(1000);
delay = ioread32(phw->dw2040_HPICSR + HPI_RESET);
if (delay != dw2040_reset) {
HPI_DEBUG_LOG(ERROR, "INIT_PCI2040 %x %x\n", dw2040_reset,
delay);
return HPI6000_ERROR_INIT_PCI2040;
}
/* Indicate that DSP#0,1 is a C6X */
iowrite32(0x00000003, phw->dw2040_HPICSR + HPI_DATA_WIDTH);
/* set Bit30 and 29 - which will prevent Target aborts from being
* issued upon HPI or GP error
*/
iowrite32(0x60000000, phw->dw2040_HPICSR + INTERRUPT_MASK_SET);
/* isolate DSP HAD8 line from PCI2040 so that
* Little endian can be set by pullup
*/
dw2040_reset = dw2040_reset & (~(endian << 3));
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
phw->ado[0].c_dsp_rev = 'B'; /* revB */
phw->ado[1].c_dsp_rev = 'B'; /* revB */
/*Take both DSPs out of reset, setting HAD8 to the correct Endian */
dw2040_reset = dw2040_reset & (~0x00000001); /* start DSP 0 */
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
dw2040_reset = dw2040_reset & (~0x00000002); /* start DSP 1 */
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
/* set HAD8 back to PCI2040, now that DSP set to little endian mode */
dw2040_reset = dw2040_reset & (~0x00000008);
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
/*delay to allow DSP to get going */
hpios_delay_micro_seconds(100);
/* loop through all DSPs, downloading DSP code */
for (dsp_index = 0; dsp_index < phw->num_dsp; dsp_index++) {
struct dsp_obj *pdo = &phw->ado[dsp_index];
/* configure DSP so that we download code into the SRAM */
/* set control reg for little endian, HWOB=1 */
iowrite32(0x00010001, pdo->prHPI_control);
/* test access to the HPI address register (HPIA) */
test_data = 0x00000001;
for (j = 0; j < 32; j++) {
iowrite32(test_data, pdo->prHPI_address);
data = ioread32(pdo->prHPI_address);
if (data != test_data) {
HPI_DEBUG_LOG(ERROR, "INIT_DSPHPI %x %x %x\n",
test_data, data, dsp_index);
return HPI6000_ERROR_INIT_DSPHPI;
}
test_data = test_data << 1;
}
/* if C6713 the setup PLL to generate 225MHz from 25MHz.
* Since the PLLDIV1 read is sometimes wrong, even on a C6713,
* we're going to do this unconditionally
*/
/* PLLDIV1 should have a value of 8000 after reset */
/*
if (HpiReadWord(pdo,0x01B7C118) == 0x8000)
*/
{
/* C6713 datasheet says we cannot program PLL from HPI,
* and indeed if we try to set the PLL multiply from the
* HPI, the PLL does not seem to lock,
* so we enable the PLL and use the default of x 7
*/
/* bypass PLL */
hpi_write_word(pdo, 0x01B7C100, 0x0000);
hpios_delay_micro_seconds(100);
/* ** use default of PLL x7 ** */
/* EMIF = 225/3=75MHz */
hpi_write_word(pdo, 0x01B7C120, 0x8002);
hpios_delay_micro_seconds(100);
/* peri = 225/2 */
hpi_write_word(pdo, 0x01B7C11C, 0x8001);
hpios_delay_micro_seconds(100);
/* cpu = 225/1 */
hpi_write_word(pdo, 0x01B7C118, 0x8000);
/* ~2ms delay */
hpios_delay_micro_seconds(2000);
/* PLL not bypassed */
hpi_write_word(pdo, 0x01B7C100, 0x0001);
/* ~2ms delay */
hpios_delay_micro_seconds(2000);
}
/* test r/w to internal DSP memory
* C6711 has L2 cache mapped to 0x0 when reset
*
* revB - because of bug 3.0.1 last HPI read
* (before HPI address issued) must be non-autoinc
*/
/* test each bit in the 32bit word */
for (i = 0; i < 100; i++) {
test_addr = 0x00000000;
test_data = 0x00000001;
for (j = 0; j < 32; j++) {
hpi_write_word(pdo, test_addr + i, test_data);
data = hpi_read_word(pdo, test_addr + i);
if (data != test_data) {
HPI_DEBUG_LOG(ERROR,
"DSP mem %x %x %x %x\n",
test_addr + i, test_data,
data, dsp_index);
return HPI6000_ERROR_INIT_DSPINTMEM;
}
test_data = test_data << 1;
}
}
/* memory map of ASI6200
00000000-0000FFFF 16Kx32 internal program
01800000-019FFFFF Internal peripheral
80000000-807FFFFF CE0 2Mx32 SDRAM running @ 100MHz
90000000-9000FFFF CE1 Async peripherals:
EMIF config
------------
Global EMIF control
0 -
1 -
2 -
3 CLK2EN = 1 CLKOUT2 enabled
4 CLK1EN = 0 CLKOUT1 disabled
5 EKEN = 1 <--!! C6713 specific, enables ECLKOUT
6 -
7 NOHOLD = 1 external HOLD disabled
8 HOLDA = 0 HOLDA output is low
9 HOLD = 0 HOLD input is low
10 ARDY = 1 ARDY input is high
11 BUSREQ = 0 BUSREQ output is low
12,13 Reserved = 1
*/
hpi_write_word(pdo, 0x01800000, 0x34A8);
/* EMIF CE0 setup - 2Mx32 Sync DRAM
31..28 Wr setup
27..22 Wr strobe
21..20 Wr hold
19..16 Rd setup
15..14 -
13..8 Rd strobe
7..4 MTYPE 0011 Sync DRAM 32bits
3 Wr hold MSB
2..0 Rd hold
*/
hpi_write_word(pdo, 0x01800008, 0x00000030);
/* EMIF SDRAM Extension
31-21 0
20 WR2RD = 0
19-18 WR2DEAC = 1
17 WR2WR = 0
16-15 R2WDQM = 2
14-12 RD2WR = 4
11-10 RD2DEAC = 1
9 RD2RD = 1
8-7 THZP = 10b
6-5 TWR = 2-1 = 01b (tWR = 10ns)
4 TRRD = 0b = 2 ECLK (tRRD = 14ns)
3-1 TRAS = 5-1 = 100b (Tras=42ns = 5 ECLK)
1 CAS latency = 3 ECLK
(for Micron 2M32-7 operating at 100Mhz)
*/
/* need to use this else DSP code crashes */
hpi_write_word(pdo, 0x01800020, 0x001BDF29);
/* EMIF SDRAM control - set up for a 2Mx32 SDRAM (512x32x4 bank)
31 - -
30 SDBSZ 1 4 bank
29..28 SDRSZ 00 11 row address pins
27..26 SDCSZ 01 8 column address pins
25 RFEN 1 refersh enabled
24 INIT 1 init SDRAM
23..20 TRCD 0001
19..16 TRP 0001
15..12 TRC 0110
11..0 - -
*/
/* need to use this else DSP code crashes */
hpi_write_word(pdo, 0x01800018, 0x47117000);
/* EMIF SDRAM Refresh Timing */
hpi_write_word(pdo, 0x0180001C, 0x00000410);
/*MIF CE1 setup - Async peripherals
@100MHz bus speed, each cycle is 10ns,
31..28 Wr setup = 1
27..22 Wr strobe = 3 30ns
21..20 Wr hold = 1
19..16 Rd setup =1
15..14 Ta = 2
13..8 Rd strobe = 3 30ns
7..4 MTYPE 0010 Async 32bits
3 Wr hold MSB =0
2..0 Rd hold = 1
*/
{
u32 cE1 =
(1L << 28) | (3L << 22) | (1L << 20) | (1L <<
16) | (2L << 14) | (3L << 8) | (2L << 4) | 1L;
hpi_write_word(pdo, 0x01800004, cE1);
}
/* delay a little to allow SDRAM and DSP to "get going" */
hpios_delay_micro_seconds(1000);
/* test access to SDRAM */
{
test_addr = 0x80000000;
test_data = 0x00000001;
/* test each bit in the 32bit word */
for (j = 0; j < 32; j++) {
hpi_write_word(pdo, test_addr, test_data);
data = hpi_read_word(pdo, test_addr);
if (data != test_data) {
HPI_DEBUG_LOG(ERROR,
"DSP dram %x %x %x %x\n",
test_addr, test_data, data,
dsp_index);
return HPI6000_ERROR_INIT_SDRAM1;
}
test_data = test_data << 1;
}
/* test every Nth address in the DRAM */
#define DRAM_SIZE_WORDS 0x200000 /*2_mx32 */
#define DRAM_INC 1024
test_addr = 0x80000000;
test_data = 0x0;
for (i = 0; i < DRAM_SIZE_WORDS; i = i + DRAM_INC) {
hpi_write_word(pdo, test_addr + i, test_data);
test_data++;
}
test_addr = 0x80000000;
test_data = 0x0;
for (i = 0; i < DRAM_SIZE_WORDS; i = i + DRAM_INC) {
data = hpi_read_word(pdo, test_addr + i);
if (data != test_data) {
HPI_DEBUG_LOG(ERROR,
"DSP dram %x %x %x %x\n",
test_addr + i, test_data,
data, dsp_index);
return HPI6000_ERROR_INIT_SDRAM2;
}
test_data++;
}
}
/* write the DSP code down into the DSPs memory */
error = hpi_dsp_code_open(boot_load_family, pao->pci.pci_dev,
&dsp_code, pos_error_code);
if (error)
return error;
while (1) {
u32 length;
u32 address;
u32 type;
u32 *pcode;
error = hpi_dsp_code_read_word(&dsp_code, &length);
if (error)
break;
if (length == 0xFFFFFFFF)
break; /* end of code */
error = hpi_dsp_code_read_word(&dsp_code, &address);
if (error)
break;
error = hpi_dsp_code_read_word(&dsp_code, &type);
if (error)
break;
error = hpi_dsp_code_read_block(length, &dsp_code,
&pcode);
if (error)
break;
error = hpi6000_dsp_block_write32(pao, (u16)dsp_index,
address, pcode, length);
if (error)
break;
}
if (error) {
hpi_dsp_code_close(&dsp_code);
return error;
}
/* verify that code was written correctly */
/* this time through, assume no errors in DSP code file/array */
hpi_dsp_code_rewind(&dsp_code);
while (1) {
u32 length;
u32 address;
u32 type;
u32 *pcode;
hpi_dsp_code_read_word(&dsp_code, &length);
if (length == 0xFFFFFFFF)
break; /* end of code */
hpi_dsp_code_read_word(&dsp_code, &address);
hpi_dsp_code_read_word(&dsp_code, &type);
hpi_dsp_code_read_block(length, &dsp_code, &pcode);
for (i = 0; i < length; i++) {
data = hpi_read_word(pdo, address);
if (data != *pcode) {
error = HPI6000_ERROR_INIT_VERIFY;
HPI_DEBUG_LOG(ERROR,
"DSP verify %x %x %x %x\n",
address, *pcode, data,
dsp_index);
break;
}
pcode++;
address += 4;
}
if (error)
break;
}
hpi_dsp_code_close(&dsp_code);
if (error)
return error;
/* zero out the hostmailbox */
{
u32 address = HPI_HIF_ADDR(host_cmd);
for (i = 0; i < 4; i++) {
hpi_write_word(pdo, address, 0);
address += 4;
}
}
/* write the DSP number into the hostmailbox */
/* structure before starting the DSP */
hpi_write_word(pdo, HPI_HIF_ADDR(dsp_number), dsp_index);
/* write the DSP adapter Info into the */
/* hostmailbox before starting the DSP */
if (dsp_index > 0)
hpi_write_word(pdo, HPI_HIF_ADDR(adapter_info),
adapter_info);
/* step 3. Start code by sending interrupt */
iowrite32(0x00030003, pdo->prHPI_control);
hpios_delay_micro_seconds(10000);
/* wait for a non-zero value in hostcmd -
* indicating initialization is complete
*
* Init could take a while if DSP checks SDRAM memory
* Was 200000. Increased to 2000000 for ASI8801 so we
* don't get 938 errors.
*/
timeout = 2000000;
while (timeout) {
do {
read = hpi_read_word(pdo,
HPI_HIF_ADDR(host_cmd));
} while (--timeout
&& hpi6000_check_PCI2040_error_flag(pao,
H6READ));
if (read)
break;
/* The following is a workaround for bug #94:
* Bluescreen on install and subsequent boots on a
* DELL PowerEdge 600SC PC with 1.8GHz P4 and
* ServerWorks chipset. Without this delay the system
* locks up with a bluescreen (NOT GPF or pagefault).
*/
else
hpios_delay_micro_seconds(10000);
}
if (timeout == 0)
return HPI6000_ERROR_INIT_NOACK;
/* read the DSP adapter Info from the */
/* hostmailbox structure after starting the DSP */
if (dsp_index == 0) {
/*u32 dwTestData=0; */
u32 mask = 0;
adapter_info =
hpi_read_word(pdo,
HPI_HIF_ADDR(adapter_info));
if (HPI_ADAPTER_FAMILY_ASI
(HPI_HIF_ADAPTER_INFO_EXTRACT_ADAPTER
(adapter_info)) ==
HPI_ADAPTER_FAMILY_ASI(0x6200))
/* all 6200 cards have this many DSPs */
phw->num_dsp = 2;
/* test that the PLD is programmed */
/* and we can read/write 24bits */
#define PLD_BASE_ADDRESS 0x90000000L /*for ASI6100/6200/8800 */
switch (boot_load_family) {
case HPI_ADAPTER_FAMILY_ASI(0x6200):
/* ASI6100/6200 has 24bit path to FPGA */
mask = 0xFFFFFF00L;
/* ASI5100 uses AX6 code, */
/* but has no PLD r/w register to test */
if (HPI_ADAPTER_FAMILY_ASI(pao->pci.pci_dev->
subsystem_device) ==
HPI_ADAPTER_FAMILY_ASI(0x5100))
mask = 0x00000000L;
/* ASI5200 uses AX6 code, */
/* but has no PLD r/w register to test */
if (HPI_ADAPTER_FAMILY_ASI(pao->pci.pci_dev->
subsystem_device) ==
HPI_ADAPTER_FAMILY_ASI(0x5200))
mask = 0x00000000L;
break;
case HPI_ADAPTER_FAMILY_ASI(0x8800):
/* ASI8800 has 16bit path to FPGA */
mask = 0xFFFF0000L;
break;
}
test_data = 0xAAAAAA00L & mask;
/* write to 24 bit Debug register (D31-D8) */
hpi_write_word(pdo, PLD_BASE_ADDRESS + 4L, test_data);
read = hpi_read_word(pdo,
PLD_BASE_ADDRESS + 4L) & mask;
if (read != test_data) {
HPI_DEBUG_LOG(ERROR, "PLD %x %x\n", test_data,
read);
return HPI6000_ERROR_INIT_PLDTEST1;
}
test_data = 0x55555500L & mask;
hpi_write_word(pdo, PLD_BASE_ADDRESS + 4L, test_data);
read = hpi_read_word(pdo,
PLD_BASE_ADDRESS + 4L) & mask;
if (read != test_data) {
HPI_DEBUG_LOG(ERROR, "PLD %x %x\n", test_data,
read);
return HPI6000_ERROR_INIT_PLDTEST2;
}
}
} /* for numDSP */
return 0;
}
#define PCI_TIMEOUT 100
static int hpi_set_address(struct dsp_obj *pdo, u32 address)
{
u32 timeout = PCI_TIMEOUT;
do {
iowrite32(address, pdo->prHPI_address);
} while (hpi6000_check_PCI2040_error_flag(pdo->pa_parent_adapter,
H6WRITE)
&& --timeout);
if (timeout)
return 0;
return 1;
}
/* write one word to the HPI port */
static void hpi_write_word(struct dsp_obj *pdo, u32 address, u32 data)
{
if (hpi_set_address(pdo, address))
return;
iowrite32(data, pdo->prHPI_data);
}
/* read one word from the HPI port */
static u32 hpi_read_word(struct dsp_obj *pdo, u32 address)
{
u32 data = 0;
if (hpi_set_address(pdo, address))
return 0; /*? No way to return error */
/* take care of errata in revB DSP (2.0.1) */
data = ioread32(pdo->prHPI_data);
return data;
}
/* write a block of 32bit words to the DSP HPI port using auto-inc mode */
static void hpi_write_block(struct dsp_obj *pdo, u32 address, u32 *pdata,
u32 length)
{
u16 length16 = length - 1;
if (length == 0)
return;
if (hpi_set_address(pdo, address))
return;
iowrite32_rep(pdo->prHPI_data_auto_inc, pdata, length16);
/* take care of errata in revB DSP (2.0.1) */
/* must end with non auto-inc */
iowrite32(*(pdata + length - 1), pdo->prHPI_data);
}
/** read a block of 32bit words from the DSP HPI port using auto-inc mode
*/
static void hpi_read_block(struct dsp_obj *pdo, u32 address, u32 *pdata,
u32 length)
{
u16 length16 = length - 1;
if (length == 0)
return;
if (hpi_set_address(pdo, address))
return;
ioread32_rep(pdo->prHPI_data_auto_inc, pdata, length16);
/* take care of errata in revB DSP (2.0.1) */
/* must end with non auto-inc */
*(pdata + length - 1) = ioread32(pdo->prHPI_data);
}
static u16 hpi6000_dsp_block_write32(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 hpi_address, u32 *source, u32 count)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 time_out = PCI_TIMEOUT;
int c6711_burst_size = 128;
u32 local_hpi_address = hpi_address;
int local_count = count;
int xfer_size;
u32 *pdata = source;
while (local_count) {
if (local_count > c6711_burst_size)
xfer_size = c6711_burst_size;
else
xfer_size = local_count;
time_out = PCI_TIMEOUT;
do {
hpi_write_block(pdo, local_hpi_address, pdata,
xfer_size);
} while (hpi6000_check_PCI2040_error_flag(pao, H6WRITE)
&& --time_out);
if (!time_out)
break;
pdata += xfer_size;
local_hpi_address += sizeof(u32) * xfer_size;
local_count -= xfer_size;
}
if (time_out)
return 0;
else
return 1;
}
static u16 hpi6000_dsp_block_read32(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 hpi_address, u32 *dest, u32 count)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 time_out = PCI_TIMEOUT;
int c6711_burst_size = 16;
u32 local_hpi_address = hpi_address;
int local_count = count;
int xfer_size;
u32 *pdata = dest;
u32 loop_count = 0;
while (local_count) {
if (local_count > c6711_burst_size)
xfer_size = c6711_burst_size;
else
xfer_size = local_count;
time_out = PCI_TIMEOUT;
do {
hpi_read_block(pdo, local_hpi_address, pdata,
xfer_size);
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ)
&& --time_out);
if (!time_out)
break;
pdata += xfer_size;
local_hpi_address += sizeof(u32) * xfer_size;
local_count -= xfer_size;
loop_count++;
}
if (time_out)
return 0;
else
return 1;
}
static short hpi6000_message_response_sequence(struct hpi_adapter_obj *pao,
u16 dsp_index, struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 timeout;
u16 ack;
u32 address;
u32 length;
u32 *p_data;
u16 error = 0;
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_IDLE);
if (ack & HPI_HIF_ERROR_MASK) {
pao->dsp_crashed++;
return HPI6000_ERROR_MSG_RESP_IDLE_TIMEOUT;
}
pao->dsp_crashed = 0;
/* get the message address and size */
if (phw->message_buffer_address_on_dsp == 0) {
timeout = TIMEOUT;
do {
address =
hpi_read_word(pdo,
HPI_HIF_ADDR(message_buffer_address));
phw->message_buffer_address_on_dsp = address;
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ)
&& --timeout);
if (!timeout)
return HPI6000_ERROR_MSG_GET_ADR;
} else
address = phw->message_buffer_address_on_dsp;
length = phm->size;
/* send the message */
p_data = (u32 *)phm;
if (hpi6000_dsp_block_write32(pao, dsp_index, address, p_data,
(u16)length / 4))
return HPI6000_ERROR_MSG_RESP_BLOCKWRITE32;
if (hpi6000_send_host_command(pao, dsp_index, HPI_HIF_GET_RESP))
return HPI6000_ERROR_MSG_RESP_GETRESPCMD;
hpi6000_send_dsp_interrupt(pdo);
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_GET_RESP);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_MSG_RESP_GET_RESP_ACK;
/* get the response address */
if (phw->response_buffer_address_on_dsp == 0) {
timeout = TIMEOUT;
do {
address =
hpi_read_word(pdo,
HPI_HIF_ADDR(response_buffer_address));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ)
&& --timeout);
phw->response_buffer_address_on_dsp = address;
if (!timeout)
return HPI6000_ERROR_RESP_GET_ADR;
} else
address = phw->response_buffer_address_on_dsp;
/* read the length of the response back from the DSP */
timeout = TIMEOUT;
do {
length = hpi_read_word(pdo, HPI_HIF_ADDR(length));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ) && --timeout);
if (!timeout)
length = sizeof(struct hpi_response);
/* get the response */
p_data = (u32 *)phr;
if (hpi6000_dsp_block_read32(pao, dsp_index, address, p_data,
(u16)length / 4))
return HPI6000_ERROR_MSG_RESP_BLOCKREAD32;
/* set i/f back to idle */
if (hpi6000_send_host_command(pao, dsp_index, HPI_HIF_IDLE))
return HPI6000_ERROR_MSG_RESP_IDLECMD;
hpi6000_send_dsp_interrupt(pdo);
error = hpi_validate_response(phm, phr);
return error;
}
/* have to set up the below defines to match stuff in the MAP file */
#define MSG_ADDRESS (HPI_HIF_BASE+0x18)
#define MSG_LENGTH 11
#define RESP_ADDRESS (HPI_HIF_BASE+0x44)
#define RESP_LENGTH 16
#define QUEUE_START (HPI_HIF_BASE+0x88)
#define QUEUE_SIZE 0x8000
static short hpi6000_send_data_check_adr(u32 address, u32 length_in_dwords)
{
/*#define CHECKING // comment this line in to enable checking */
#ifdef CHECKING
if (address < (u32)MSG_ADDRESS)
return 0;
if (address > (u32)(QUEUE_START + QUEUE_SIZE))
return 0;
if ((address + (length_in_dwords << 2)) >
(u32)(QUEUE_START + QUEUE_SIZE))
return 0;
#else
(void)address;
(void)length_in_dwords;
return 1;
#endif
}
static short hpi6000_send_data(struct hpi_adapter_obj *pao, u16 dsp_index,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 data_sent = 0;
u16 ack;
u32 length, address;
u32 *p_data = (u32 *)phm->u.d.u.data.pb_data;
u16 time_out = 8;
(void)phr;
/* round dwDataSize down to nearest 4 bytes */
while ((data_sent < (phm->u.d.u.data.data_size & ~3L))
&& --time_out) {
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_IDLE);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_SEND_DATA_IDLE_TIMEOUT;
if (hpi6000_send_host_command(pao, dsp_index,
HPI_HIF_SEND_DATA))
return HPI6000_ERROR_SEND_DATA_CMD;
hpi6000_send_dsp_interrupt(pdo);
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_SEND_DATA);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_SEND_DATA_ACK;
do {
/* get the address and size */
address = hpi_read_word(pdo, HPI_HIF_ADDR(address));
/* DSP returns number of DWORDS */
length = hpi_read_word(pdo, HPI_HIF_ADDR(length));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ));
if (!hpi6000_send_data_check_adr(address, length))
return HPI6000_ERROR_SEND_DATA_ADR;
/* send the data. break data into 512 DWORD blocks (2K bytes)
* and send using block write. 2Kbytes is the max as this is the
* memory window given to the HPI data register by the PCI2040
*/
{
u32 len = length;
u32 blk_len = 512;
while (len) {
if (len < blk_len)
blk_len = len;
if (hpi6000_dsp_block_write32(pao, dsp_index,
address, p_data, blk_len))
return HPI6000_ERROR_SEND_DATA_WRITE;
address += blk_len * 4;
p_data += blk_len;
len -= blk_len;
}
}
if (hpi6000_send_host_command(pao, dsp_index, HPI_HIF_IDLE))
return HPI6000_ERROR_SEND_DATA_IDLECMD;
hpi6000_send_dsp_interrupt(pdo);
data_sent += length * 4;
}
if (!time_out)
return HPI6000_ERROR_SEND_DATA_TIMEOUT;
return 0;
}
static short hpi6000_get_data(struct hpi_adapter_obj *pao, u16 dsp_index,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 data_got = 0;
u16 ack;
u32 length, address;
u32 *p_data = (u32 *)phm->u.d.u.data.pb_data;
(void)phr; /* this parameter not used! */
/* round dwDataSize down to nearest 4 bytes */
while (data_got < (phm->u.d.u.data.data_size & ~3L)) {
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_IDLE);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_GET_DATA_IDLE_TIMEOUT;
if (hpi6000_send_host_command(pao, dsp_index,
HPI_HIF_GET_DATA))
return HPI6000_ERROR_GET_DATA_CMD;
hpi6000_send_dsp_interrupt(pdo);
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_GET_DATA);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_GET_DATA_ACK;
/* get the address and size */
do {
address = hpi_read_word(pdo, HPI_HIF_ADDR(address));
length = hpi_read_word(pdo, HPI_HIF_ADDR(length));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ));
/* read the data */
{
u32 len = length;
u32 blk_len = 512;
while (len) {
if (len < blk_len)
blk_len = len;
if (hpi6000_dsp_block_read32(pao, dsp_index,
address, p_data, blk_len))
return HPI6000_ERROR_GET_DATA_READ;
address += blk_len * 4;
p_data += blk_len;
len -= blk_len;
}
}
if (hpi6000_send_host_command(pao, dsp_index, HPI_HIF_IDLE))
return HPI6000_ERROR_GET_DATA_IDLECMD;
hpi6000_send_dsp_interrupt(pdo);
data_got += length * 4;
}
return 0;
}
static void hpi6000_send_dsp_interrupt(struct dsp_obj *pdo)
{
iowrite32(0x00030003, pdo->prHPI_control); /* DSPINT */
}
static short hpi6000_send_host_command(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 host_cmd)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 timeout = TIMEOUT;
/* set command */
do {
hpi_write_word(pdo, HPI_HIF_ADDR(host_cmd), host_cmd);
/* flush the FIFO */
hpi_set_address(pdo, HPI_HIF_ADDR(host_cmd));
} while (hpi6000_check_PCI2040_error_flag(pao, H6WRITE) && --timeout);
/* reset the interrupt bit */
iowrite32(0x00040004, pdo->prHPI_control);
if (timeout)
return 0;
else
return 1;
}
/* if the PCI2040 has recorded an HPI timeout, reset the error and return 1 */
static short hpi6000_check_PCI2040_error_flag(struct hpi_adapter_obj *pao,
u16 read_or_write)
{
u32 hPI_error;
struct hpi_hw_obj *phw = pao->priv;
/* read the error bits from the PCI2040 */
hPI_error = ioread32(phw->dw2040_HPICSR + HPI_ERROR_REPORT);
if (hPI_error) {
/* reset the error flag */
iowrite32(0L, phw->dw2040_HPICSR + HPI_ERROR_REPORT);
phw->pCI2040HPI_error_count++;
if (read_or_write == 1)
gw_pci_read_asserts++; /************* inc global */
else
gw_pci_write_asserts++;
return 1;
} else
return 0;
}
static short hpi6000_wait_dsp_ack(struct hpi_adapter_obj *pao, u16 dsp_index,
u32 ack_value)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 ack = 0L;
u32 timeout;
u32 hPIC = 0L;
/* wait for host interrupt to signal ack is ready */
timeout = TIMEOUT;
while (--timeout) {
hPIC = ioread32(pdo->prHPI_control);
if (hPIC & 0x04) /* 0x04 = HINT from DSP */
break;
}
if (timeout == 0)
return HPI_HIF_ERROR_MASK;
/* wait for dwAckValue */
timeout = TIMEOUT;
while (--timeout) {
/* read the ack mailbox */
ack = hpi_read_word(pdo, HPI_HIF_ADDR(dsp_ack));
if (ack == ack_value)
break;
if ((ack & HPI_HIF_ERROR_MASK)
&& !hpi6000_check_PCI2040_error_flag(pao, H6READ))
break;
/*for (i=0;i<1000;i++) */
/* dwPause=i+1; */
}
if (ack & HPI_HIF_ERROR_MASK)
/* indicates bad read from DSP -
typically 0xffffff is read for some reason */
ack = HPI_HIF_ERROR_MASK;
if (timeout == 0)
ack = HPI_HIF_ERROR_MASK;
return (short)ack;
}
static short hpi6000_update_control_cache(struct hpi_adapter_obj *pao,
struct hpi_message *phm)
{
const u16 dsp_index = 0;
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 timeout;
u32 cache_dirty_flag;
u16 err;
hpios_dsplock_lock(pao);
timeout = TIMEOUT;
do {
cache_dirty_flag =
hpi_read_word((struct dsp_obj *)pdo,
HPI_HIF_ADDR(control_cache_is_dirty));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ) && --timeout);
if (!timeout) {
err = HPI6000_ERROR_CONTROL_CACHE_PARAMS;
goto unlock;
}
if (cache_dirty_flag) {
/* read the cached controls */
u32 address;
u32 length;
timeout = TIMEOUT;
if (pdo->control_cache_address_on_dsp == 0) {
do {
address =
hpi_read_word((struct dsp_obj *)pdo,
HPI_HIF_ADDR(control_cache_address));
length = hpi_read_word((struct dsp_obj *)pdo,
HPI_HIF_ADDR
(control_cache_size_in_bytes));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ)
&& --timeout);
if (!timeout) {
err = HPI6000_ERROR_CONTROL_CACHE_ADDRLEN;
goto unlock;
}
pdo->control_cache_address_on_dsp = address;
pdo->control_cache_length_on_dsp = length;
} else {
address = pdo->control_cache_address_on_dsp;
length = pdo->control_cache_length_on_dsp;
}
if (hpi6000_dsp_block_read32(pao, dsp_index, address,
(u32 *)&phw->control_cache[0],
length / sizeof(u32))) {
err = HPI6000_ERROR_CONTROL_CACHE_READ;
goto unlock;
}
do {
hpi_write_word((struct dsp_obj *)pdo,
HPI_HIF_ADDR(control_cache_is_dirty), 0);
/* flush the FIFO */
hpi_set_address(pdo, HPI_HIF_ADDR(host_cmd));
} while (hpi6000_check_PCI2040_error_flag(pao, H6WRITE)
&& --timeout);
if (!timeout) {
err = HPI6000_ERROR_CONTROL_CACHE_FLUSH;
goto unlock;
}
}
err = 0;
unlock:
hpios_dsplock_unlock(pao);
return err;
}
/** Get dsp index for multi DSP adapters only */
static u16 get_dsp_index(struct hpi_adapter_obj *pao, struct hpi_message *phm)
{
u16 ret = 0;
switch (phm->object) {
case HPI_OBJ_ISTREAM:
if (phm->obj_index < 2)
ret = 1;
break;
case HPI_OBJ_PROFILE:
ret = phm->obj_index;
break;
default:
break;
}
return ret;
}
/** Complete transaction with DSP
Send message, get response, send or get stream data if any.
*/
static void hw_message(struct hpi_adapter_obj *pao, struct hpi_message *phm,
struct hpi_response *phr)
{
u16 error = 0;
u16 dsp_index = 0;
struct hpi_hw_obj *phw = pao->priv;
u16 num_dsp = phw->num_dsp;
if (num_dsp < 2)
dsp_index = 0;
else {
dsp_index = get_dsp_index(pao, phm);
/* is this checked on the DSP anyway? */
if ((phm->function == HPI_ISTREAM_GROUP_ADD)
|| (phm->function == HPI_OSTREAM_GROUP_ADD)) {
struct hpi_message hm;
u16 add_index;
hm.obj_index = phm->u.d.u.stream.stream_index;
hm.object = phm->u.d.u.stream.object_type;
add_index = get_dsp_index(pao, &hm);
if (add_index != dsp_index) {
phr->error = HPI_ERROR_NO_INTERDSP_GROUPS;
return;
}
}
}
hpios_dsplock_lock(pao);
error = hpi6000_message_response_sequence(pao, dsp_index, phm, phr);
if (error) /* something failed in the HPI/DSP interface */
goto err;
if (phr->error) /* something failed in the DSP */
goto out;
switch (phm->function) {
case HPI_OSTREAM_WRITE:
case HPI_ISTREAM_ANC_WRITE:
error = hpi6000_send_data(pao, dsp_index, phm, phr);
break;
case HPI_ISTREAM_READ:
case HPI_OSTREAM_ANC_READ:
error = hpi6000_get_data(pao, dsp_index, phm, phr);
break;
case HPI_ADAPTER_GET_ASSERT:
phr->u.ax.assert.dsp_index = 0; /* dsp 0 default */
if (num_dsp == 2) {
if (!phr->u.ax.assert.count) {
/* no assert from dsp 0, check dsp 1 */
error = hpi6000_message_response_sequence(pao,
1, phm, phr);
phr->u.ax.assert.dsp_index = 1;
}
}
}
err:
if (error) {
if (error >= HPI_ERROR_BACKEND_BASE) {
phr->error = HPI_ERROR_DSP_COMMUNICATION;
phr->specific_error = error;
} else {
phr->error = error;
}
/* just the header of the response is valid */
phr->size = sizeof(struct hpi_response_header);
}
out:
hpios_dsplock_unlock(pao);
return;
}
| gpl-2.0 |
SomeshThakur/Xeon-Kernel | sound/pci/asihpi/hpi6000.c | 8398 | 49704 | /******************************************************************************
AudioScience HPI driver
Copyright (C) 1997-2011 AudioScience Inc. <support@audioscience.com>
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
Hardware Programming Interface (HPI) for AudioScience ASI6200 series adapters.
These PCI bus adapters are based on the TI C6711 DSP.
Exported functions:
void HPI_6000(struct hpi_message *phm, struct hpi_response *phr)
#defines
HIDE_PCI_ASSERTS to show the PCI asserts
PROFILE_DSP2 get profile data from DSP2 if present (instead of DSP 1)
(C) Copyright AudioScience Inc. 1998-2003
*******************************************************************************/
#define SOURCEFILE_NAME "hpi6000.c"
#include "hpi_internal.h"
#include "hpimsginit.h"
#include "hpidebug.h"
#include "hpi6000.h"
#include "hpidspcd.h"
#include "hpicmn.h"
#define HPI_HIF_BASE (0x00000200) /* start of C67xx internal RAM */
#define HPI_HIF_ADDR(member) \
(HPI_HIF_BASE + offsetof(struct hpi_hif_6000, member))
#define HPI_HIF_ERROR_MASK 0x4000
/* HPI6000 specific error codes */
#define HPI6000_ERROR_BASE 900 /* not actually used anywhere */
/* operational/messaging errors */
#define HPI6000_ERROR_MSG_RESP_IDLE_TIMEOUT 901
#define HPI6000_ERROR_MSG_RESP_GET_RESP_ACK 903
#define HPI6000_ERROR_MSG_GET_ADR 904
#define HPI6000_ERROR_RESP_GET_ADR 905
#define HPI6000_ERROR_MSG_RESP_BLOCKWRITE32 906
#define HPI6000_ERROR_MSG_RESP_BLOCKREAD32 907
#define HPI6000_ERROR_CONTROL_CACHE_PARAMS 909
#define HPI6000_ERROR_SEND_DATA_IDLE_TIMEOUT 911
#define HPI6000_ERROR_SEND_DATA_ACK 912
#define HPI6000_ERROR_SEND_DATA_ADR 913
#define HPI6000_ERROR_SEND_DATA_TIMEOUT 914
#define HPI6000_ERROR_SEND_DATA_CMD 915
#define HPI6000_ERROR_SEND_DATA_WRITE 916
#define HPI6000_ERROR_SEND_DATA_IDLECMD 917
#define HPI6000_ERROR_GET_DATA_IDLE_TIMEOUT 921
#define HPI6000_ERROR_GET_DATA_ACK 922
#define HPI6000_ERROR_GET_DATA_CMD 923
#define HPI6000_ERROR_GET_DATA_READ 924
#define HPI6000_ERROR_GET_DATA_IDLECMD 925
#define HPI6000_ERROR_CONTROL_CACHE_ADDRLEN 951
#define HPI6000_ERROR_CONTROL_CACHE_READ 952
#define HPI6000_ERROR_CONTROL_CACHE_FLUSH 953
#define HPI6000_ERROR_MSG_RESP_GETRESPCMD 961
#define HPI6000_ERROR_MSG_RESP_IDLECMD 962
/* Initialisation/bootload errors */
#define HPI6000_ERROR_UNHANDLED_SUBSYS_ID 930
/* can't access PCI2040 */
#define HPI6000_ERROR_INIT_PCI2040 931
/* can't access DSP HPI i/f */
#define HPI6000_ERROR_INIT_DSPHPI 932
/* can't access internal DSP memory */
#define HPI6000_ERROR_INIT_DSPINTMEM 933
/* can't access SDRAM - test#1 */
#define HPI6000_ERROR_INIT_SDRAM1 934
/* can't access SDRAM - test#2 */
#define HPI6000_ERROR_INIT_SDRAM2 935
#define HPI6000_ERROR_INIT_VERIFY 938
#define HPI6000_ERROR_INIT_NOACK 939
#define HPI6000_ERROR_INIT_PLDTEST1 941
#define HPI6000_ERROR_INIT_PLDTEST2 942
/* local defines */
#define HIDE_PCI_ASSERTS
#define PROFILE_DSP2
/* for PCI2040 i/f chip */
/* HPI CSR registers */
/* word offsets from CSR base */
/* use when io addresses defined as u32 * */
#define INTERRUPT_EVENT_SET 0
#define INTERRUPT_EVENT_CLEAR 1
#define INTERRUPT_MASK_SET 2
#define INTERRUPT_MASK_CLEAR 3
#define HPI_ERROR_REPORT 4
#define HPI_RESET 5
#define HPI_DATA_WIDTH 6
#define MAX_DSPS 2
/* HPI registers, spaced 8K bytes = 2K words apart */
#define DSP_SPACING 0x800
#define CONTROL 0x0000
#define ADDRESS 0x0200
#define DATA_AUTOINC 0x0400
#define DATA 0x0600
#define TIMEOUT 500000
struct dsp_obj {
__iomem u32 *prHPI_control;
__iomem u32 *prHPI_address;
__iomem u32 *prHPI_data;
__iomem u32 *prHPI_data_auto_inc;
char c_dsp_rev; /*A, B */
u32 control_cache_address_on_dsp;
u32 control_cache_length_on_dsp;
struct hpi_adapter_obj *pa_parent_adapter;
};
struct hpi_hw_obj {
__iomem u32 *dw2040_HPICSR;
__iomem u32 *dw2040_HPIDSP;
u16 num_dsp;
struct dsp_obj ado[MAX_DSPS];
u32 message_buffer_address_on_dsp;
u32 response_buffer_address_on_dsp;
u32 pCI2040HPI_error_count;
struct hpi_control_cache_single control_cache[HPI_NMIXER_CONTROLS];
struct hpi_control_cache *p_cache;
};
static u16 hpi6000_dsp_block_write32(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 hpi_address, u32 *source, u32 count);
static u16 hpi6000_dsp_block_read32(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 hpi_address, u32 *dest, u32 count);
static short hpi6000_adapter_boot_load_dsp(struct hpi_adapter_obj *pao,
u32 *pos_error_code);
static short hpi6000_check_PCI2040_error_flag(struct hpi_adapter_obj *pao,
u16 read_or_write);
#define H6READ 1
#define H6WRITE 0
static short hpi6000_update_control_cache(struct hpi_adapter_obj *pao,
struct hpi_message *phm);
static short hpi6000_message_response_sequence(struct hpi_adapter_obj *pao,
u16 dsp_index, struct hpi_message *phm, struct hpi_response *phr);
static void hw_message(struct hpi_adapter_obj *pao, struct hpi_message *phm,
struct hpi_response *phr);
static short hpi6000_wait_dsp_ack(struct hpi_adapter_obj *pao, u16 dsp_index,
u32 ack_value);
static short hpi6000_send_host_command(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 host_cmd);
static void hpi6000_send_dsp_interrupt(struct dsp_obj *pdo);
static short hpi6000_send_data(struct hpi_adapter_obj *pao, u16 dsp_index,
struct hpi_message *phm, struct hpi_response *phr);
static short hpi6000_get_data(struct hpi_adapter_obj *pao, u16 dsp_index,
struct hpi_message *phm, struct hpi_response *phr);
static void hpi_write_word(struct dsp_obj *pdo, u32 address, u32 data);
static u32 hpi_read_word(struct dsp_obj *pdo, u32 address);
static void hpi_write_block(struct dsp_obj *pdo, u32 address, u32 *pdata,
u32 length);
static void hpi_read_block(struct dsp_obj *pdo, u32 address, u32 *pdata,
u32 length);
static void subsys_create_adapter(struct hpi_message *phm,
struct hpi_response *phr);
static void adapter_delete(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void adapter_get_asserts(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static short create_adapter_obj(struct hpi_adapter_obj *pao,
u32 *pos_error_code);
static void delete_adapter_obj(struct hpi_adapter_obj *pao);
/* local globals */
static u16 gw_pci_read_asserts; /* used to count PCI2040 errors */
static u16 gw_pci_write_asserts; /* used to count PCI2040 errors */
static void subsys_message(struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_SUBSYS_CREATE_ADAPTER:
subsys_create_adapter(phm, phr);
break;
default:
phr->error = HPI_ERROR_INVALID_FUNC;
break;
}
}
static void control_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
switch (phm->function) {
case HPI_CONTROL_GET_STATE:
if (pao->has_control_cache) {
u16 err;
err = hpi6000_update_control_cache(pao, phm);
if (err) {
if (err >= HPI_ERROR_BACKEND_BASE) {
phr->error =
HPI_ERROR_CONTROL_CACHING;
phr->specific_error = err;
} else {
phr->error = err;
}
break;
}
if (hpi_check_control_cache(phw->p_cache, phm, phr))
break;
}
hw_message(pao, phm, phr);
break;
case HPI_CONTROL_SET_STATE:
hw_message(pao, phm, phr);
hpi_cmn_control_cache_sync_to_msg(phw->p_cache, phm, phr);
break;
case HPI_CONTROL_GET_INFO:
default:
hw_message(pao, phm, phr);
break;
}
}
static void adapter_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_ADAPTER_GET_ASSERT:
adapter_get_asserts(pao, phm, phr);
break;
case HPI_ADAPTER_DELETE:
adapter_delete(pao, phm, phr);
break;
default:
hw_message(pao, phm, phr);
break;
}
}
static void outstream_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_OSTREAM_HOSTBUFFER_ALLOC:
case HPI_OSTREAM_HOSTBUFFER_FREE:
/* Don't let these messages go to the HW function because
* they're called without locking the spinlock.
* For the HPI6000 adapters the HW would return
* HPI_ERROR_INVALID_FUNC anyway.
*/
phr->error = HPI_ERROR_INVALID_FUNC;
break;
default:
hw_message(pao, phm, phr);
return;
}
}
static void instream_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_ISTREAM_HOSTBUFFER_ALLOC:
case HPI_ISTREAM_HOSTBUFFER_FREE:
/* Don't let these messages go to the HW function because
* they're called without locking the spinlock.
* For the HPI6000 adapters the HW would return
* HPI_ERROR_INVALID_FUNC anyway.
*/
phr->error = HPI_ERROR_INVALID_FUNC;
break;
default:
hw_message(pao, phm, phr);
return;
}
}
/************************************************************************/
/** HPI_6000()
* Entry point from HPIMAN
* All calls to the HPI start here
*/
void HPI_6000(struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_adapter_obj *pao = NULL;
if (phm->object != HPI_OBJ_SUBSYSTEM) {
pao = hpi_find_adapter(phm->adapter_index);
if (!pao) {
hpi_init_response(phr, phm->object, phm->function,
HPI_ERROR_BAD_ADAPTER_NUMBER);
HPI_DEBUG_LOG(DEBUG, "invalid adapter index: %d \n",
phm->adapter_index);
return;
}
/* Don't even try to communicate with crashed DSP */
if (pao->dsp_crashed >= 10) {
hpi_init_response(phr, phm->object, phm->function,
HPI_ERROR_DSP_HARDWARE);
HPI_DEBUG_LOG(DEBUG, "adapter %d dsp crashed\n",
phm->adapter_index);
return;
}
}
/* Init default response including the size field */
if (phm->function != HPI_SUBSYS_CREATE_ADAPTER)
hpi_init_response(phr, phm->object, phm->function,
HPI_ERROR_PROCESSING_MESSAGE);
switch (phm->type) {
case HPI_TYPE_REQUEST:
switch (phm->object) {
case HPI_OBJ_SUBSYSTEM:
subsys_message(phm, phr);
break;
case HPI_OBJ_ADAPTER:
phr->size =
sizeof(struct hpi_response_header) +
sizeof(struct hpi_adapter_res);
adapter_message(pao, phm, phr);
break;
case HPI_OBJ_CONTROL:
control_message(pao, phm, phr);
break;
case HPI_OBJ_OSTREAM:
outstream_message(pao, phm, phr);
break;
case HPI_OBJ_ISTREAM:
instream_message(pao, phm, phr);
break;
default:
hw_message(pao, phm, phr);
break;
}
break;
default:
phr->error = HPI_ERROR_INVALID_TYPE;
break;
}
}
/************************************************************************/
/* SUBSYSTEM */
/* create an adapter object and initialise it based on resource information
* passed in in the message
* NOTE - you cannot use this function AND the FindAdapters function at the
* same time, the application must use only one of them to get the adapters
*/
static void subsys_create_adapter(struct hpi_message *phm,
struct hpi_response *phr)
{
/* create temp adapter obj, because we don't know what index yet */
struct hpi_adapter_obj ao;
struct hpi_adapter_obj *pao;
u32 os_error_code;
u16 err = 0;
u32 dsp_index = 0;
HPI_DEBUG_LOG(VERBOSE, "subsys_create_adapter\n");
memset(&ao, 0, sizeof(ao));
ao.priv = kzalloc(sizeof(struct hpi_hw_obj), GFP_KERNEL);
if (!ao.priv) {
HPI_DEBUG_LOG(ERROR, "can't get mem for adapter object\n");
phr->error = HPI_ERROR_MEMORY_ALLOC;
return;
}
/* create the adapter object based on the resource information */
ao.pci = *phm->u.s.resource.r.pci;
err = create_adapter_obj(&ao, &os_error_code);
if (err) {
delete_adapter_obj(&ao);
if (err >= HPI_ERROR_BACKEND_BASE) {
phr->error = HPI_ERROR_DSP_BOOTLOAD;
phr->specific_error = err;
} else {
phr->error = err;
}
phr->u.s.data = os_error_code;
return;
}
/* need to update paParentAdapter */
pao = hpi_find_adapter(ao.index);
if (!pao) {
/* We just added this adapter, why can't we find it!? */
HPI_DEBUG_LOG(ERROR, "lost adapter after boot\n");
phr->error = HPI_ERROR_BAD_ADAPTER;
return;
}
for (dsp_index = 0; dsp_index < MAX_DSPS; dsp_index++) {
struct hpi_hw_obj *phw = pao->priv;
phw->ado[dsp_index].pa_parent_adapter = pao;
}
phr->u.s.adapter_type = ao.type;
phr->u.s.adapter_index = ao.index;
phr->error = 0;
}
static void adapter_delete(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
delete_adapter_obj(pao);
hpi_delete_adapter(pao);
phr->error = 0;
}
/* this routine is called from SubSysFindAdapter and SubSysCreateAdapter */
static short create_adapter_obj(struct hpi_adapter_obj *pao,
u32 *pos_error_code)
{
short boot_error = 0;
u32 dsp_index = 0;
u32 control_cache_size = 0;
u32 control_cache_count = 0;
struct hpi_hw_obj *phw = pao->priv;
/* The PCI2040 has the following address map */
/* BAR0 - 4K = HPI control and status registers on PCI2040 (HPI CSR) */
/* BAR1 - 32K = HPI registers on DSP */
phw->dw2040_HPICSR = pao->pci.ap_mem_base[0];
phw->dw2040_HPIDSP = pao->pci.ap_mem_base[1];
HPI_DEBUG_LOG(VERBOSE, "csr %p, dsp %p\n", phw->dw2040_HPICSR,
phw->dw2040_HPIDSP);
/* set addresses for the possible DSP HPI interfaces */
for (dsp_index = 0; dsp_index < MAX_DSPS; dsp_index++) {
phw->ado[dsp_index].prHPI_control =
phw->dw2040_HPIDSP + (CONTROL +
DSP_SPACING * dsp_index);
phw->ado[dsp_index].prHPI_address =
phw->dw2040_HPIDSP + (ADDRESS +
DSP_SPACING * dsp_index);
phw->ado[dsp_index].prHPI_data =
phw->dw2040_HPIDSP + (DATA + DSP_SPACING * dsp_index);
phw->ado[dsp_index].prHPI_data_auto_inc =
phw->dw2040_HPIDSP + (DATA_AUTOINC +
DSP_SPACING * dsp_index);
HPI_DEBUG_LOG(VERBOSE, "ctl %p, adr %p, dat %p, dat++ %p\n",
phw->ado[dsp_index].prHPI_control,
phw->ado[dsp_index].prHPI_address,
phw->ado[dsp_index].prHPI_data,
phw->ado[dsp_index].prHPI_data_auto_inc);
phw->ado[dsp_index].pa_parent_adapter = pao;
}
phw->pCI2040HPI_error_count = 0;
pao->has_control_cache = 0;
/* Set the default number of DSPs on this card */
/* This is (conditionally) adjusted after bootloading */
/* of the first DSP in the bootload section. */
phw->num_dsp = 1;
boot_error = hpi6000_adapter_boot_load_dsp(pao, pos_error_code);
if (boot_error)
return boot_error;
HPI_DEBUG_LOG(INFO, "bootload DSP OK\n");
phw->message_buffer_address_on_dsp = 0L;
phw->response_buffer_address_on_dsp = 0L;
/* get info about the adapter by asking the adapter */
/* send a HPI_ADAPTER_GET_INFO message */
{
struct hpi_message hm;
struct hpi_response hr0; /* response from DSP 0 */
struct hpi_response hr1; /* response from DSP 1 */
u16 error = 0;
HPI_DEBUG_LOG(VERBOSE, "send ADAPTER_GET_INFO\n");
memset(&hm, 0, sizeof(hm));
hm.type = HPI_TYPE_REQUEST;
hm.size = sizeof(struct hpi_message);
hm.object = HPI_OBJ_ADAPTER;
hm.function = HPI_ADAPTER_GET_INFO;
hm.adapter_index = 0;
memset(&hr0, 0, sizeof(hr0));
memset(&hr1, 0, sizeof(hr1));
hr0.size = sizeof(hr0);
hr1.size = sizeof(hr1);
error = hpi6000_message_response_sequence(pao, 0, &hm, &hr0);
if (hr0.error) {
HPI_DEBUG_LOG(DEBUG, "message error %d\n", hr0.error);
return hr0.error;
}
if (phw->num_dsp == 2) {
error = hpi6000_message_response_sequence(pao, 1, &hm,
&hr1);
if (error)
return error;
}
pao->type = hr0.u.ax.info.adapter_type;
pao->index = hr0.u.ax.info.adapter_index;
}
memset(&phw->control_cache[0], 0,
sizeof(struct hpi_control_cache_single) *
HPI_NMIXER_CONTROLS);
/* Read the control cache length to figure out if it is turned on */
control_cache_size =
hpi_read_word(&phw->ado[0],
HPI_HIF_ADDR(control_cache_size_in_bytes));
if (control_cache_size) {
control_cache_count =
hpi_read_word(&phw->ado[0],
HPI_HIF_ADDR(control_cache_count));
phw->p_cache =
hpi_alloc_control_cache(control_cache_count,
control_cache_size, (unsigned char *)
&phw->control_cache[0]
);
if (phw->p_cache)
pao->has_control_cache = 1;
}
HPI_DEBUG_LOG(DEBUG, "get adapter info ASI%04X index %d\n", pao->type,
pao->index);
if (phw->p_cache)
phw->p_cache->adap_idx = pao->index;
return hpi_add_adapter(pao);
}
static void delete_adapter_obj(struct hpi_adapter_obj *pao)
{
struct hpi_hw_obj *phw = pao->priv;
if (pao->has_control_cache)
hpi_free_control_cache(phw->p_cache);
/* reset DSPs on adapter */
iowrite32(0x0003000F, phw->dw2040_HPICSR + HPI_RESET);
kfree(phw);
}
/************************************************************************/
/* ADAPTER */
static void adapter_get_asserts(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
#ifndef HIDE_PCI_ASSERTS
/* if we have PCI2040 asserts then collect them */
if ((gw_pci_read_asserts > 0) || (gw_pci_write_asserts > 0)) {
phr->u.ax.assert.p1 =
gw_pci_read_asserts * 100 + gw_pci_write_asserts;
phr->u.ax.assert.p2 = 0;
phr->u.ax.assert.count = 1; /* assert count */
phr->u.ax.assert.dsp_index = -1; /* "dsp index" */
strcpy(phr->u.ax.assert.sz_message, "PCI2040 error");
phr->u.ax.assert.dsp_msg_addr = 0;
gw_pci_read_asserts = 0;
gw_pci_write_asserts = 0;
phr->error = 0;
} else
#endif
hw_message(pao, phm, phr); /*get DSP asserts */
return;
}
/************************************************************************/
/* LOW-LEVEL */
static short hpi6000_adapter_boot_load_dsp(struct hpi_adapter_obj *pao,
u32 *pos_error_code)
{
struct hpi_hw_obj *phw = pao->priv;
short error;
u32 timeout;
u32 read = 0;
u32 i = 0;
u32 data = 0;
u32 j = 0;
u32 test_addr = 0x80000000;
u32 test_data = 0x00000001;
u32 dw2040_reset = 0;
u32 dsp_index = 0;
u32 endian = 0;
u32 adapter_info = 0;
u32 delay = 0;
struct dsp_code dsp_code;
u16 boot_load_family = 0;
/* NOTE don't use wAdapterType in this routine. It is not setup yet */
switch (pao->pci.pci_dev->subsystem_device) {
case 0x5100:
case 0x5110: /* ASI5100 revB or higher with C6711D */
case 0x5200: /* ASI5200 PCIe version of ASI5100 */
case 0x6100:
case 0x6200:
boot_load_family = HPI_ADAPTER_FAMILY_ASI(0x6200);
break;
default:
return HPI6000_ERROR_UNHANDLED_SUBSYS_ID;
}
/* reset all DSPs, indicate two DSPs are present
* set RST3-=1 to disconnect HAD8 to set DSP in little endian mode
*/
endian = 0;
dw2040_reset = 0x0003000F;
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
/* read back register to make sure PCI2040 chip is functioning
* note that bits 4..15 are read-only and so should always return zero,
* even though we wrote 1 to them
*/
hpios_delay_micro_seconds(1000);
delay = ioread32(phw->dw2040_HPICSR + HPI_RESET);
if (delay != dw2040_reset) {
HPI_DEBUG_LOG(ERROR, "INIT_PCI2040 %x %x\n", dw2040_reset,
delay);
return HPI6000_ERROR_INIT_PCI2040;
}
/* Indicate that DSP#0,1 is a C6X */
iowrite32(0x00000003, phw->dw2040_HPICSR + HPI_DATA_WIDTH);
/* set Bit30 and 29 - which will prevent Target aborts from being
* issued upon HPI or GP error
*/
iowrite32(0x60000000, phw->dw2040_HPICSR + INTERRUPT_MASK_SET);
/* isolate DSP HAD8 line from PCI2040 so that
* Little endian can be set by pullup
*/
dw2040_reset = dw2040_reset & (~(endian << 3));
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
phw->ado[0].c_dsp_rev = 'B'; /* revB */
phw->ado[1].c_dsp_rev = 'B'; /* revB */
/*Take both DSPs out of reset, setting HAD8 to the correct Endian */
dw2040_reset = dw2040_reset & (~0x00000001); /* start DSP 0 */
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
dw2040_reset = dw2040_reset & (~0x00000002); /* start DSP 1 */
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
/* set HAD8 back to PCI2040, now that DSP set to little endian mode */
dw2040_reset = dw2040_reset & (~0x00000008);
iowrite32(dw2040_reset, phw->dw2040_HPICSR + HPI_RESET);
/*delay to allow DSP to get going */
hpios_delay_micro_seconds(100);
/* loop through all DSPs, downloading DSP code */
for (dsp_index = 0; dsp_index < phw->num_dsp; dsp_index++) {
struct dsp_obj *pdo = &phw->ado[dsp_index];
/* configure DSP so that we download code into the SRAM */
/* set control reg for little endian, HWOB=1 */
iowrite32(0x00010001, pdo->prHPI_control);
/* test access to the HPI address register (HPIA) */
test_data = 0x00000001;
for (j = 0; j < 32; j++) {
iowrite32(test_data, pdo->prHPI_address);
data = ioread32(pdo->prHPI_address);
if (data != test_data) {
HPI_DEBUG_LOG(ERROR, "INIT_DSPHPI %x %x %x\n",
test_data, data, dsp_index);
return HPI6000_ERROR_INIT_DSPHPI;
}
test_data = test_data << 1;
}
/* if C6713 the setup PLL to generate 225MHz from 25MHz.
* Since the PLLDIV1 read is sometimes wrong, even on a C6713,
* we're going to do this unconditionally
*/
/* PLLDIV1 should have a value of 8000 after reset */
/*
if (HpiReadWord(pdo,0x01B7C118) == 0x8000)
*/
{
/* C6713 datasheet says we cannot program PLL from HPI,
* and indeed if we try to set the PLL multiply from the
* HPI, the PLL does not seem to lock,
* so we enable the PLL and use the default of x 7
*/
/* bypass PLL */
hpi_write_word(pdo, 0x01B7C100, 0x0000);
hpios_delay_micro_seconds(100);
/* ** use default of PLL x7 ** */
/* EMIF = 225/3=75MHz */
hpi_write_word(pdo, 0x01B7C120, 0x8002);
hpios_delay_micro_seconds(100);
/* peri = 225/2 */
hpi_write_word(pdo, 0x01B7C11C, 0x8001);
hpios_delay_micro_seconds(100);
/* cpu = 225/1 */
hpi_write_word(pdo, 0x01B7C118, 0x8000);
/* ~2ms delay */
hpios_delay_micro_seconds(2000);
/* PLL not bypassed */
hpi_write_word(pdo, 0x01B7C100, 0x0001);
/* ~2ms delay */
hpios_delay_micro_seconds(2000);
}
/* test r/w to internal DSP memory
* C6711 has L2 cache mapped to 0x0 when reset
*
* revB - because of bug 3.0.1 last HPI read
* (before HPI address issued) must be non-autoinc
*/
/* test each bit in the 32bit word */
for (i = 0; i < 100; i++) {
test_addr = 0x00000000;
test_data = 0x00000001;
for (j = 0; j < 32; j++) {
hpi_write_word(pdo, test_addr + i, test_data);
data = hpi_read_word(pdo, test_addr + i);
if (data != test_data) {
HPI_DEBUG_LOG(ERROR,
"DSP mem %x %x %x %x\n",
test_addr + i, test_data,
data, dsp_index);
return HPI6000_ERROR_INIT_DSPINTMEM;
}
test_data = test_data << 1;
}
}
/* memory map of ASI6200
00000000-0000FFFF 16Kx32 internal program
01800000-019FFFFF Internal peripheral
80000000-807FFFFF CE0 2Mx32 SDRAM running @ 100MHz
90000000-9000FFFF CE1 Async peripherals:
EMIF config
------------
Global EMIF control
0 -
1 -
2 -
3 CLK2EN = 1 CLKOUT2 enabled
4 CLK1EN = 0 CLKOUT1 disabled
5 EKEN = 1 <--!! C6713 specific, enables ECLKOUT
6 -
7 NOHOLD = 1 external HOLD disabled
8 HOLDA = 0 HOLDA output is low
9 HOLD = 0 HOLD input is low
10 ARDY = 1 ARDY input is high
11 BUSREQ = 0 BUSREQ output is low
12,13 Reserved = 1
*/
hpi_write_word(pdo, 0x01800000, 0x34A8);
/* EMIF CE0 setup - 2Mx32 Sync DRAM
31..28 Wr setup
27..22 Wr strobe
21..20 Wr hold
19..16 Rd setup
15..14 -
13..8 Rd strobe
7..4 MTYPE 0011 Sync DRAM 32bits
3 Wr hold MSB
2..0 Rd hold
*/
hpi_write_word(pdo, 0x01800008, 0x00000030);
/* EMIF SDRAM Extension
31-21 0
20 WR2RD = 0
19-18 WR2DEAC = 1
17 WR2WR = 0
16-15 R2WDQM = 2
14-12 RD2WR = 4
11-10 RD2DEAC = 1
9 RD2RD = 1
8-7 THZP = 10b
6-5 TWR = 2-1 = 01b (tWR = 10ns)
4 TRRD = 0b = 2 ECLK (tRRD = 14ns)
3-1 TRAS = 5-1 = 100b (Tras=42ns = 5 ECLK)
1 CAS latency = 3 ECLK
(for Micron 2M32-7 operating at 100Mhz)
*/
/* need to use this else DSP code crashes */
hpi_write_word(pdo, 0x01800020, 0x001BDF29);
/* EMIF SDRAM control - set up for a 2Mx32 SDRAM (512x32x4 bank)
31 - -
30 SDBSZ 1 4 bank
29..28 SDRSZ 00 11 row address pins
27..26 SDCSZ 01 8 column address pins
25 RFEN 1 refersh enabled
24 INIT 1 init SDRAM
23..20 TRCD 0001
19..16 TRP 0001
15..12 TRC 0110
11..0 - -
*/
/* need to use this else DSP code crashes */
hpi_write_word(pdo, 0x01800018, 0x47117000);
/* EMIF SDRAM Refresh Timing */
hpi_write_word(pdo, 0x0180001C, 0x00000410);
/*MIF CE1 setup - Async peripherals
@100MHz bus speed, each cycle is 10ns,
31..28 Wr setup = 1
27..22 Wr strobe = 3 30ns
21..20 Wr hold = 1
19..16 Rd setup =1
15..14 Ta = 2
13..8 Rd strobe = 3 30ns
7..4 MTYPE 0010 Async 32bits
3 Wr hold MSB =0
2..0 Rd hold = 1
*/
{
u32 cE1 =
(1L << 28) | (3L << 22) | (1L << 20) | (1L <<
16) | (2L << 14) | (3L << 8) | (2L << 4) | 1L;
hpi_write_word(pdo, 0x01800004, cE1);
}
/* delay a little to allow SDRAM and DSP to "get going" */
hpios_delay_micro_seconds(1000);
/* test access to SDRAM */
{
test_addr = 0x80000000;
test_data = 0x00000001;
/* test each bit in the 32bit word */
for (j = 0; j < 32; j++) {
hpi_write_word(pdo, test_addr, test_data);
data = hpi_read_word(pdo, test_addr);
if (data != test_data) {
HPI_DEBUG_LOG(ERROR,
"DSP dram %x %x %x %x\n",
test_addr, test_data, data,
dsp_index);
return HPI6000_ERROR_INIT_SDRAM1;
}
test_data = test_data << 1;
}
/* test every Nth address in the DRAM */
#define DRAM_SIZE_WORDS 0x200000 /*2_mx32 */
#define DRAM_INC 1024
test_addr = 0x80000000;
test_data = 0x0;
for (i = 0; i < DRAM_SIZE_WORDS; i = i + DRAM_INC) {
hpi_write_word(pdo, test_addr + i, test_data);
test_data++;
}
test_addr = 0x80000000;
test_data = 0x0;
for (i = 0; i < DRAM_SIZE_WORDS; i = i + DRAM_INC) {
data = hpi_read_word(pdo, test_addr + i);
if (data != test_data) {
HPI_DEBUG_LOG(ERROR,
"DSP dram %x %x %x %x\n",
test_addr + i, test_data,
data, dsp_index);
return HPI6000_ERROR_INIT_SDRAM2;
}
test_data++;
}
}
/* write the DSP code down into the DSPs memory */
error = hpi_dsp_code_open(boot_load_family, pao->pci.pci_dev,
&dsp_code, pos_error_code);
if (error)
return error;
while (1) {
u32 length;
u32 address;
u32 type;
u32 *pcode;
error = hpi_dsp_code_read_word(&dsp_code, &length);
if (error)
break;
if (length == 0xFFFFFFFF)
break; /* end of code */
error = hpi_dsp_code_read_word(&dsp_code, &address);
if (error)
break;
error = hpi_dsp_code_read_word(&dsp_code, &type);
if (error)
break;
error = hpi_dsp_code_read_block(length, &dsp_code,
&pcode);
if (error)
break;
error = hpi6000_dsp_block_write32(pao, (u16)dsp_index,
address, pcode, length);
if (error)
break;
}
if (error) {
hpi_dsp_code_close(&dsp_code);
return error;
}
/* verify that code was written correctly */
/* this time through, assume no errors in DSP code file/array */
hpi_dsp_code_rewind(&dsp_code);
while (1) {
u32 length;
u32 address;
u32 type;
u32 *pcode;
hpi_dsp_code_read_word(&dsp_code, &length);
if (length == 0xFFFFFFFF)
break; /* end of code */
hpi_dsp_code_read_word(&dsp_code, &address);
hpi_dsp_code_read_word(&dsp_code, &type);
hpi_dsp_code_read_block(length, &dsp_code, &pcode);
for (i = 0; i < length; i++) {
data = hpi_read_word(pdo, address);
if (data != *pcode) {
error = HPI6000_ERROR_INIT_VERIFY;
HPI_DEBUG_LOG(ERROR,
"DSP verify %x %x %x %x\n",
address, *pcode, data,
dsp_index);
break;
}
pcode++;
address += 4;
}
if (error)
break;
}
hpi_dsp_code_close(&dsp_code);
if (error)
return error;
/* zero out the hostmailbox */
{
u32 address = HPI_HIF_ADDR(host_cmd);
for (i = 0; i < 4; i++) {
hpi_write_word(pdo, address, 0);
address += 4;
}
}
/* write the DSP number into the hostmailbox */
/* structure before starting the DSP */
hpi_write_word(pdo, HPI_HIF_ADDR(dsp_number), dsp_index);
/* write the DSP adapter Info into the */
/* hostmailbox before starting the DSP */
if (dsp_index > 0)
hpi_write_word(pdo, HPI_HIF_ADDR(adapter_info),
adapter_info);
/* step 3. Start code by sending interrupt */
iowrite32(0x00030003, pdo->prHPI_control);
hpios_delay_micro_seconds(10000);
/* wait for a non-zero value in hostcmd -
* indicating initialization is complete
*
* Init could take a while if DSP checks SDRAM memory
* Was 200000. Increased to 2000000 for ASI8801 so we
* don't get 938 errors.
*/
timeout = 2000000;
while (timeout) {
do {
read = hpi_read_word(pdo,
HPI_HIF_ADDR(host_cmd));
} while (--timeout
&& hpi6000_check_PCI2040_error_flag(pao,
H6READ));
if (read)
break;
/* The following is a workaround for bug #94:
* Bluescreen on install and subsequent boots on a
* DELL PowerEdge 600SC PC with 1.8GHz P4 and
* ServerWorks chipset. Without this delay the system
* locks up with a bluescreen (NOT GPF or pagefault).
*/
else
hpios_delay_micro_seconds(10000);
}
if (timeout == 0)
return HPI6000_ERROR_INIT_NOACK;
/* read the DSP adapter Info from the */
/* hostmailbox structure after starting the DSP */
if (dsp_index == 0) {
/*u32 dwTestData=0; */
u32 mask = 0;
adapter_info =
hpi_read_word(pdo,
HPI_HIF_ADDR(adapter_info));
if (HPI_ADAPTER_FAMILY_ASI
(HPI_HIF_ADAPTER_INFO_EXTRACT_ADAPTER
(adapter_info)) ==
HPI_ADAPTER_FAMILY_ASI(0x6200))
/* all 6200 cards have this many DSPs */
phw->num_dsp = 2;
/* test that the PLD is programmed */
/* and we can read/write 24bits */
#define PLD_BASE_ADDRESS 0x90000000L /*for ASI6100/6200/8800 */
switch (boot_load_family) {
case HPI_ADAPTER_FAMILY_ASI(0x6200):
/* ASI6100/6200 has 24bit path to FPGA */
mask = 0xFFFFFF00L;
/* ASI5100 uses AX6 code, */
/* but has no PLD r/w register to test */
if (HPI_ADAPTER_FAMILY_ASI(pao->pci.pci_dev->
subsystem_device) ==
HPI_ADAPTER_FAMILY_ASI(0x5100))
mask = 0x00000000L;
/* ASI5200 uses AX6 code, */
/* but has no PLD r/w register to test */
if (HPI_ADAPTER_FAMILY_ASI(pao->pci.pci_dev->
subsystem_device) ==
HPI_ADAPTER_FAMILY_ASI(0x5200))
mask = 0x00000000L;
break;
case HPI_ADAPTER_FAMILY_ASI(0x8800):
/* ASI8800 has 16bit path to FPGA */
mask = 0xFFFF0000L;
break;
}
test_data = 0xAAAAAA00L & mask;
/* write to 24 bit Debug register (D31-D8) */
hpi_write_word(pdo, PLD_BASE_ADDRESS + 4L, test_data);
read = hpi_read_word(pdo,
PLD_BASE_ADDRESS + 4L) & mask;
if (read != test_data) {
HPI_DEBUG_LOG(ERROR, "PLD %x %x\n", test_data,
read);
return HPI6000_ERROR_INIT_PLDTEST1;
}
test_data = 0x55555500L & mask;
hpi_write_word(pdo, PLD_BASE_ADDRESS + 4L, test_data);
read = hpi_read_word(pdo,
PLD_BASE_ADDRESS + 4L) & mask;
if (read != test_data) {
HPI_DEBUG_LOG(ERROR, "PLD %x %x\n", test_data,
read);
return HPI6000_ERROR_INIT_PLDTEST2;
}
}
} /* for numDSP */
return 0;
}
#define PCI_TIMEOUT 100
static int hpi_set_address(struct dsp_obj *pdo, u32 address)
{
u32 timeout = PCI_TIMEOUT;
do {
iowrite32(address, pdo->prHPI_address);
} while (hpi6000_check_PCI2040_error_flag(pdo->pa_parent_adapter,
H6WRITE)
&& --timeout);
if (timeout)
return 0;
return 1;
}
/* write one word to the HPI port */
static void hpi_write_word(struct dsp_obj *pdo, u32 address, u32 data)
{
if (hpi_set_address(pdo, address))
return;
iowrite32(data, pdo->prHPI_data);
}
/* read one word from the HPI port */
static u32 hpi_read_word(struct dsp_obj *pdo, u32 address)
{
u32 data = 0;
if (hpi_set_address(pdo, address))
return 0; /*? No way to return error */
/* take care of errata in revB DSP (2.0.1) */
data = ioread32(pdo->prHPI_data);
return data;
}
/* write a block of 32bit words to the DSP HPI port using auto-inc mode */
static void hpi_write_block(struct dsp_obj *pdo, u32 address, u32 *pdata,
u32 length)
{
u16 length16 = length - 1;
if (length == 0)
return;
if (hpi_set_address(pdo, address))
return;
iowrite32_rep(pdo->prHPI_data_auto_inc, pdata, length16);
/* take care of errata in revB DSP (2.0.1) */
/* must end with non auto-inc */
iowrite32(*(pdata + length - 1), pdo->prHPI_data);
}
/** read a block of 32bit words from the DSP HPI port using auto-inc mode
*/
static void hpi_read_block(struct dsp_obj *pdo, u32 address, u32 *pdata,
u32 length)
{
u16 length16 = length - 1;
if (length == 0)
return;
if (hpi_set_address(pdo, address))
return;
ioread32_rep(pdo->prHPI_data_auto_inc, pdata, length16);
/* take care of errata in revB DSP (2.0.1) */
/* must end with non auto-inc */
*(pdata + length - 1) = ioread32(pdo->prHPI_data);
}
static u16 hpi6000_dsp_block_write32(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 hpi_address, u32 *source, u32 count)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 time_out = PCI_TIMEOUT;
int c6711_burst_size = 128;
u32 local_hpi_address = hpi_address;
int local_count = count;
int xfer_size;
u32 *pdata = source;
while (local_count) {
if (local_count > c6711_burst_size)
xfer_size = c6711_burst_size;
else
xfer_size = local_count;
time_out = PCI_TIMEOUT;
do {
hpi_write_block(pdo, local_hpi_address, pdata,
xfer_size);
} while (hpi6000_check_PCI2040_error_flag(pao, H6WRITE)
&& --time_out);
if (!time_out)
break;
pdata += xfer_size;
local_hpi_address += sizeof(u32) * xfer_size;
local_count -= xfer_size;
}
if (time_out)
return 0;
else
return 1;
}
static u16 hpi6000_dsp_block_read32(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 hpi_address, u32 *dest, u32 count)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 time_out = PCI_TIMEOUT;
int c6711_burst_size = 16;
u32 local_hpi_address = hpi_address;
int local_count = count;
int xfer_size;
u32 *pdata = dest;
u32 loop_count = 0;
while (local_count) {
if (local_count > c6711_burst_size)
xfer_size = c6711_burst_size;
else
xfer_size = local_count;
time_out = PCI_TIMEOUT;
do {
hpi_read_block(pdo, local_hpi_address, pdata,
xfer_size);
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ)
&& --time_out);
if (!time_out)
break;
pdata += xfer_size;
local_hpi_address += sizeof(u32) * xfer_size;
local_count -= xfer_size;
loop_count++;
}
if (time_out)
return 0;
else
return 1;
}
static short hpi6000_message_response_sequence(struct hpi_adapter_obj *pao,
u16 dsp_index, struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 timeout;
u16 ack;
u32 address;
u32 length;
u32 *p_data;
u16 error = 0;
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_IDLE);
if (ack & HPI_HIF_ERROR_MASK) {
pao->dsp_crashed++;
return HPI6000_ERROR_MSG_RESP_IDLE_TIMEOUT;
}
pao->dsp_crashed = 0;
/* get the message address and size */
if (phw->message_buffer_address_on_dsp == 0) {
timeout = TIMEOUT;
do {
address =
hpi_read_word(pdo,
HPI_HIF_ADDR(message_buffer_address));
phw->message_buffer_address_on_dsp = address;
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ)
&& --timeout);
if (!timeout)
return HPI6000_ERROR_MSG_GET_ADR;
} else
address = phw->message_buffer_address_on_dsp;
length = phm->size;
/* send the message */
p_data = (u32 *)phm;
if (hpi6000_dsp_block_write32(pao, dsp_index, address, p_data,
(u16)length / 4))
return HPI6000_ERROR_MSG_RESP_BLOCKWRITE32;
if (hpi6000_send_host_command(pao, dsp_index, HPI_HIF_GET_RESP))
return HPI6000_ERROR_MSG_RESP_GETRESPCMD;
hpi6000_send_dsp_interrupt(pdo);
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_GET_RESP);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_MSG_RESP_GET_RESP_ACK;
/* get the response address */
if (phw->response_buffer_address_on_dsp == 0) {
timeout = TIMEOUT;
do {
address =
hpi_read_word(pdo,
HPI_HIF_ADDR(response_buffer_address));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ)
&& --timeout);
phw->response_buffer_address_on_dsp = address;
if (!timeout)
return HPI6000_ERROR_RESP_GET_ADR;
} else
address = phw->response_buffer_address_on_dsp;
/* read the length of the response back from the DSP */
timeout = TIMEOUT;
do {
length = hpi_read_word(pdo, HPI_HIF_ADDR(length));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ) && --timeout);
if (!timeout)
length = sizeof(struct hpi_response);
/* get the response */
p_data = (u32 *)phr;
if (hpi6000_dsp_block_read32(pao, dsp_index, address, p_data,
(u16)length / 4))
return HPI6000_ERROR_MSG_RESP_BLOCKREAD32;
/* set i/f back to idle */
if (hpi6000_send_host_command(pao, dsp_index, HPI_HIF_IDLE))
return HPI6000_ERROR_MSG_RESP_IDLECMD;
hpi6000_send_dsp_interrupt(pdo);
error = hpi_validate_response(phm, phr);
return error;
}
/* have to set up the below defines to match stuff in the MAP file */
#define MSG_ADDRESS (HPI_HIF_BASE+0x18)
#define MSG_LENGTH 11
#define RESP_ADDRESS (HPI_HIF_BASE+0x44)
#define RESP_LENGTH 16
#define QUEUE_START (HPI_HIF_BASE+0x88)
#define QUEUE_SIZE 0x8000
static short hpi6000_send_data_check_adr(u32 address, u32 length_in_dwords)
{
/*#define CHECKING // comment this line in to enable checking */
#ifdef CHECKING
if (address < (u32)MSG_ADDRESS)
return 0;
if (address > (u32)(QUEUE_START + QUEUE_SIZE))
return 0;
if ((address + (length_in_dwords << 2)) >
(u32)(QUEUE_START + QUEUE_SIZE))
return 0;
#else
(void)address;
(void)length_in_dwords;
return 1;
#endif
}
static short hpi6000_send_data(struct hpi_adapter_obj *pao, u16 dsp_index,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 data_sent = 0;
u16 ack;
u32 length, address;
u32 *p_data = (u32 *)phm->u.d.u.data.pb_data;
u16 time_out = 8;
(void)phr;
/* round dwDataSize down to nearest 4 bytes */
while ((data_sent < (phm->u.d.u.data.data_size & ~3L))
&& --time_out) {
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_IDLE);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_SEND_DATA_IDLE_TIMEOUT;
if (hpi6000_send_host_command(pao, dsp_index,
HPI_HIF_SEND_DATA))
return HPI6000_ERROR_SEND_DATA_CMD;
hpi6000_send_dsp_interrupt(pdo);
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_SEND_DATA);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_SEND_DATA_ACK;
do {
/* get the address and size */
address = hpi_read_word(pdo, HPI_HIF_ADDR(address));
/* DSP returns number of DWORDS */
length = hpi_read_word(pdo, HPI_HIF_ADDR(length));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ));
if (!hpi6000_send_data_check_adr(address, length))
return HPI6000_ERROR_SEND_DATA_ADR;
/* send the data. break data into 512 DWORD blocks (2K bytes)
* and send using block write. 2Kbytes is the max as this is the
* memory window given to the HPI data register by the PCI2040
*/
{
u32 len = length;
u32 blk_len = 512;
while (len) {
if (len < blk_len)
blk_len = len;
if (hpi6000_dsp_block_write32(pao, dsp_index,
address, p_data, blk_len))
return HPI6000_ERROR_SEND_DATA_WRITE;
address += blk_len * 4;
p_data += blk_len;
len -= blk_len;
}
}
if (hpi6000_send_host_command(pao, dsp_index, HPI_HIF_IDLE))
return HPI6000_ERROR_SEND_DATA_IDLECMD;
hpi6000_send_dsp_interrupt(pdo);
data_sent += length * 4;
}
if (!time_out)
return HPI6000_ERROR_SEND_DATA_TIMEOUT;
return 0;
}
static short hpi6000_get_data(struct hpi_adapter_obj *pao, u16 dsp_index,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 data_got = 0;
u16 ack;
u32 length, address;
u32 *p_data = (u32 *)phm->u.d.u.data.pb_data;
(void)phr; /* this parameter not used! */
/* round dwDataSize down to nearest 4 bytes */
while (data_got < (phm->u.d.u.data.data_size & ~3L)) {
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_IDLE);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_GET_DATA_IDLE_TIMEOUT;
if (hpi6000_send_host_command(pao, dsp_index,
HPI_HIF_GET_DATA))
return HPI6000_ERROR_GET_DATA_CMD;
hpi6000_send_dsp_interrupt(pdo);
ack = hpi6000_wait_dsp_ack(pao, dsp_index, HPI_HIF_GET_DATA);
if (ack & HPI_HIF_ERROR_MASK)
return HPI6000_ERROR_GET_DATA_ACK;
/* get the address and size */
do {
address = hpi_read_word(pdo, HPI_HIF_ADDR(address));
length = hpi_read_word(pdo, HPI_HIF_ADDR(length));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ));
/* read the data */
{
u32 len = length;
u32 blk_len = 512;
while (len) {
if (len < blk_len)
blk_len = len;
if (hpi6000_dsp_block_read32(pao, dsp_index,
address, p_data, blk_len))
return HPI6000_ERROR_GET_DATA_READ;
address += blk_len * 4;
p_data += blk_len;
len -= blk_len;
}
}
if (hpi6000_send_host_command(pao, dsp_index, HPI_HIF_IDLE))
return HPI6000_ERROR_GET_DATA_IDLECMD;
hpi6000_send_dsp_interrupt(pdo);
data_got += length * 4;
}
return 0;
}
static void hpi6000_send_dsp_interrupt(struct dsp_obj *pdo)
{
iowrite32(0x00030003, pdo->prHPI_control); /* DSPINT */
}
static short hpi6000_send_host_command(struct hpi_adapter_obj *pao,
u16 dsp_index, u32 host_cmd)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 timeout = TIMEOUT;
/* set command */
do {
hpi_write_word(pdo, HPI_HIF_ADDR(host_cmd), host_cmd);
/* flush the FIFO */
hpi_set_address(pdo, HPI_HIF_ADDR(host_cmd));
} while (hpi6000_check_PCI2040_error_flag(pao, H6WRITE) && --timeout);
/* reset the interrupt bit */
iowrite32(0x00040004, pdo->prHPI_control);
if (timeout)
return 0;
else
return 1;
}
/* if the PCI2040 has recorded an HPI timeout, reset the error and return 1 */
static short hpi6000_check_PCI2040_error_flag(struct hpi_adapter_obj *pao,
u16 read_or_write)
{
u32 hPI_error;
struct hpi_hw_obj *phw = pao->priv;
/* read the error bits from the PCI2040 */
hPI_error = ioread32(phw->dw2040_HPICSR + HPI_ERROR_REPORT);
if (hPI_error) {
/* reset the error flag */
iowrite32(0L, phw->dw2040_HPICSR + HPI_ERROR_REPORT);
phw->pCI2040HPI_error_count++;
if (read_or_write == 1)
gw_pci_read_asserts++; /************* inc global */
else
gw_pci_write_asserts++;
return 1;
} else
return 0;
}
static short hpi6000_wait_dsp_ack(struct hpi_adapter_obj *pao, u16 dsp_index,
u32 ack_value)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 ack = 0L;
u32 timeout;
u32 hPIC = 0L;
/* wait for host interrupt to signal ack is ready */
timeout = TIMEOUT;
while (--timeout) {
hPIC = ioread32(pdo->prHPI_control);
if (hPIC & 0x04) /* 0x04 = HINT from DSP */
break;
}
if (timeout == 0)
return HPI_HIF_ERROR_MASK;
/* wait for dwAckValue */
timeout = TIMEOUT;
while (--timeout) {
/* read the ack mailbox */
ack = hpi_read_word(pdo, HPI_HIF_ADDR(dsp_ack));
if (ack == ack_value)
break;
if ((ack & HPI_HIF_ERROR_MASK)
&& !hpi6000_check_PCI2040_error_flag(pao, H6READ))
break;
/*for (i=0;i<1000;i++) */
/* dwPause=i+1; */
}
if (ack & HPI_HIF_ERROR_MASK)
/* indicates bad read from DSP -
typically 0xffffff is read for some reason */
ack = HPI_HIF_ERROR_MASK;
if (timeout == 0)
ack = HPI_HIF_ERROR_MASK;
return (short)ack;
}
static short hpi6000_update_control_cache(struct hpi_adapter_obj *pao,
struct hpi_message *phm)
{
const u16 dsp_index = 0;
struct hpi_hw_obj *phw = pao->priv;
struct dsp_obj *pdo = &phw->ado[dsp_index];
u32 timeout;
u32 cache_dirty_flag;
u16 err;
hpios_dsplock_lock(pao);
timeout = TIMEOUT;
do {
cache_dirty_flag =
hpi_read_word((struct dsp_obj *)pdo,
HPI_HIF_ADDR(control_cache_is_dirty));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ) && --timeout);
if (!timeout) {
err = HPI6000_ERROR_CONTROL_CACHE_PARAMS;
goto unlock;
}
if (cache_dirty_flag) {
/* read the cached controls */
u32 address;
u32 length;
timeout = TIMEOUT;
if (pdo->control_cache_address_on_dsp == 0) {
do {
address =
hpi_read_word((struct dsp_obj *)pdo,
HPI_HIF_ADDR(control_cache_address));
length = hpi_read_word((struct dsp_obj *)pdo,
HPI_HIF_ADDR
(control_cache_size_in_bytes));
} while (hpi6000_check_PCI2040_error_flag(pao, H6READ)
&& --timeout);
if (!timeout) {
err = HPI6000_ERROR_CONTROL_CACHE_ADDRLEN;
goto unlock;
}
pdo->control_cache_address_on_dsp = address;
pdo->control_cache_length_on_dsp = length;
} else {
address = pdo->control_cache_address_on_dsp;
length = pdo->control_cache_length_on_dsp;
}
if (hpi6000_dsp_block_read32(pao, dsp_index, address,
(u32 *)&phw->control_cache[0],
length / sizeof(u32))) {
err = HPI6000_ERROR_CONTROL_CACHE_READ;
goto unlock;
}
do {
hpi_write_word((struct dsp_obj *)pdo,
HPI_HIF_ADDR(control_cache_is_dirty), 0);
/* flush the FIFO */
hpi_set_address(pdo, HPI_HIF_ADDR(host_cmd));
} while (hpi6000_check_PCI2040_error_flag(pao, H6WRITE)
&& --timeout);
if (!timeout) {
err = HPI6000_ERROR_CONTROL_CACHE_FLUSH;
goto unlock;
}
}
err = 0;
unlock:
hpios_dsplock_unlock(pao);
return err;
}
/** Get dsp index for multi DSP adapters only */
static u16 get_dsp_index(struct hpi_adapter_obj *pao, struct hpi_message *phm)
{
u16 ret = 0;
switch (phm->object) {
case HPI_OBJ_ISTREAM:
if (phm->obj_index < 2)
ret = 1;
break;
case HPI_OBJ_PROFILE:
ret = phm->obj_index;
break;
default:
break;
}
return ret;
}
/** Complete transaction with DSP
Send message, get response, send or get stream data if any.
*/
static void hw_message(struct hpi_adapter_obj *pao, struct hpi_message *phm,
struct hpi_response *phr)
{
u16 error = 0;
u16 dsp_index = 0;
struct hpi_hw_obj *phw = pao->priv;
u16 num_dsp = phw->num_dsp;
if (num_dsp < 2)
dsp_index = 0;
else {
dsp_index = get_dsp_index(pao, phm);
/* is this checked on the DSP anyway? */
if ((phm->function == HPI_ISTREAM_GROUP_ADD)
|| (phm->function == HPI_OSTREAM_GROUP_ADD)) {
struct hpi_message hm;
u16 add_index;
hm.obj_index = phm->u.d.u.stream.stream_index;
hm.object = phm->u.d.u.stream.object_type;
add_index = get_dsp_index(pao, &hm);
if (add_index != dsp_index) {
phr->error = HPI_ERROR_NO_INTERDSP_GROUPS;
return;
}
}
}
hpios_dsplock_lock(pao);
error = hpi6000_message_response_sequence(pao, dsp_index, phm, phr);
if (error) /* something failed in the HPI/DSP interface */
goto err;
if (phr->error) /* something failed in the DSP */
goto out;
switch (phm->function) {
case HPI_OSTREAM_WRITE:
case HPI_ISTREAM_ANC_WRITE:
error = hpi6000_send_data(pao, dsp_index, phm, phr);
break;
case HPI_ISTREAM_READ:
case HPI_OSTREAM_ANC_READ:
error = hpi6000_get_data(pao, dsp_index, phm, phr);
break;
case HPI_ADAPTER_GET_ASSERT:
phr->u.ax.assert.dsp_index = 0; /* dsp 0 default */
if (num_dsp == 2) {
if (!phr->u.ax.assert.count) {
/* no assert from dsp 0, check dsp 1 */
error = hpi6000_message_response_sequence(pao,
1, phm, phr);
phr->u.ax.assert.dsp_index = 1;
}
}
}
err:
if (error) {
if (error >= HPI_ERROR_BACKEND_BASE) {
phr->error = HPI_ERROR_DSP_COMMUNICATION;
phr->specific_error = error;
} else {
phr->error = error;
}
/* just the header of the response is valid */
phr->size = sizeof(struct hpi_response_header);
}
out:
hpios_dsplock_unlock(pao);
return;
}
| gpl-2.0 |
ARMWorks/FA_210_Android_Kernel | arch/powerpc/platforms/wsp/scom_wsp.c | 9678 | 1745 | /*
* SCOM backend for WSP
*
* Copyright 2010 Benjamin Herrenschmidt, IBM Corp.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/cpumask.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <asm/cputhreads.h>
#include <asm/reg_a2.h>
#include <asm/scom.h>
#include <asm/udbg.h>
#include "wsp.h"
static scom_map_t wsp_scom_map(struct device_node *dev, u64 reg, u64 count)
{
struct resource r;
u64 xscom_addr;
if (!of_get_property(dev, "scom-controller", NULL)) {
pr_err("%s: device %s is not a SCOM controller\n",
__func__, dev->full_name);
return SCOM_MAP_INVALID;
}
if (of_address_to_resource(dev, 0, &r)) {
pr_debug("Failed to find SCOM controller address\n");
return 0;
}
/* Transform the SCOM address into an XSCOM offset */
xscom_addr = ((reg & 0x7f000000) >> 1) | ((reg & 0xfffff) << 3);
return (scom_map_t)ioremap(r.start + xscom_addr, count << 3);
}
static void wsp_scom_unmap(scom_map_t map)
{
iounmap((void *)map);
}
static u64 wsp_scom_read(scom_map_t map, u32 reg)
{
u64 __iomem *addr = (u64 __iomem *)map;
return in_be64(addr + reg);
}
static void wsp_scom_write(scom_map_t map, u32 reg, u64 value)
{
u64 __iomem *addr = (u64 __iomem *)map;
return out_be64(addr + reg, value);
}
static const struct scom_controller wsp_scom_controller = {
.map = wsp_scom_map,
.unmap = wsp_scom_unmap,
.read = wsp_scom_read,
.write = wsp_scom_write
};
void scom_init_wsp(void)
{
scom_init(&wsp_scom_controller);
}
| gpl-2.0 |
halaszk/android_kernel_samsung_lt03 | drivers/gpu/drm/radeon/si_blit_shaders.c | 10190 | 5916 | /*
* Copyright 2011 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* Alex Deucher <alexander.deucher@amd.com>
*/
#include <linux/types.h>
#include <linux/bug.h>
#include <linux/kernel.h>
const u32 si_default_state[] =
{
0xc0066900,
0x00000000,
0x00000060, /* DB_RENDER_CONTROL */
0x00000000, /* DB_COUNT_CONTROL */
0x00000000, /* DB_DEPTH_VIEW */
0x0000002a, /* DB_RENDER_OVERRIDE */
0x00000000, /* DB_RENDER_OVERRIDE2 */
0x00000000, /* DB_HTILE_DATA_BASE */
0xc0046900,
0x00000008,
0x00000000, /* DB_DEPTH_BOUNDS_MIN */
0x00000000, /* DB_DEPTH_BOUNDS_MAX */
0x00000000, /* DB_STENCIL_CLEAR */
0x00000000, /* DB_DEPTH_CLEAR */
0xc0036900,
0x0000000f,
0x00000000, /* DB_DEPTH_INFO */
0x00000000, /* DB_Z_INFO */
0x00000000, /* DB_STENCIL_INFO */
0xc0016900,
0x00000080,
0x00000000, /* PA_SC_WINDOW_OFFSET */
0xc00d6900,
0x00000083,
0x0000ffff, /* PA_SC_CLIPRECT_RULE */
0x00000000, /* PA_SC_CLIPRECT_0_TL */
0x20002000, /* PA_SC_CLIPRECT_0_BR */
0x00000000,
0x20002000,
0x00000000,
0x20002000,
0x00000000,
0x20002000,
0xaaaaaaaa, /* PA_SC_EDGERULE */
0x00000000, /* PA_SU_HARDWARE_SCREEN_OFFSET */
0x0000000f, /* CB_TARGET_MASK */
0x0000000f, /* CB_SHADER_MASK */
0xc0226900,
0x00000094,
0x80000000, /* PA_SC_VPORT_SCISSOR_0_TL */
0x20002000, /* PA_SC_VPORT_SCISSOR_0_BR */
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x00000000, /* PA_SC_VPORT_ZMIN_0 */
0x3f800000, /* PA_SC_VPORT_ZMAX_0 */
0xc0026900,
0x000000d9,
0x00000000, /* CP_RINGID */
0x00000000, /* CP_VMID */
0xc0046900,
0x00000100,
0xffffffff, /* VGT_MAX_VTX_INDX */
0x00000000, /* VGT_MIN_VTX_INDX */
0x00000000, /* VGT_INDX_OFFSET */
0x00000000, /* VGT_MULTI_PRIM_IB_RESET_INDX */
0xc0046900,
0x00000105,
0x00000000, /* CB_BLEND_RED */
0x00000000, /* CB_BLEND_GREEN */
0x00000000, /* CB_BLEND_BLUE */
0x00000000, /* CB_BLEND_ALPHA */
0xc0016900,
0x000001e0,
0x00000000, /* CB_BLEND0_CONTROL */
0xc00e6900,
0x00000200,
0x00000000, /* DB_DEPTH_CONTROL */
0x00000000, /* DB_EQAA */
0x00cc0010, /* CB_COLOR_CONTROL */
0x00000210, /* DB_SHADER_CONTROL */
0x00010000, /* PA_CL_CLIP_CNTL */
0x00000004, /* PA_SU_SC_MODE_CNTL */
0x00000100, /* PA_CL_VTE_CNTL */
0x00000000, /* PA_CL_VS_OUT_CNTL */
0x00000000, /* PA_CL_NANINF_CNTL */
0x00000000, /* PA_SU_LINE_STIPPLE_CNTL */
0x00000000, /* PA_SU_LINE_STIPPLE_SCALE */
0x00000000, /* PA_SU_PRIM_FILTER_CNTL */
0x00000000, /* */
0x00000000, /* */
0xc0116900,
0x00000280,
0x00000000, /* PA_SU_POINT_SIZE */
0x00000000, /* PA_SU_POINT_MINMAX */
0x00000008, /* PA_SU_LINE_CNTL */
0x00000000, /* PA_SC_LINE_STIPPLE */
0x00000000, /* VGT_OUTPUT_PATH_CNTL */
0x00000000, /* VGT_HOS_CNTL */
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000, /* VGT_GS_MODE */
0xc0026900,
0x00000292,
0x00000000, /* PA_SC_MODE_CNTL_0 */
0x00000000, /* PA_SC_MODE_CNTL_1 */
0xc0016900,
0x000002a1,
0x00000000, /* VGT_PRIMITIVEID_EN */
0xc0016900,
0x000002a5,
0x00000000, /* VGT_MULTI_PRIM_IB_RESET_EN */
0xc0026900,
0x000002a8,
0x00000000, /* VGT_INSTANCE_STEP_RATE_0 */
0x00000000,
0xc0026900,
0x000002ad,
0x00000000, /* VGT_REUSE_OFF */
0x00000000,
0xc0016900,
0x000002d5,
0x00000000, /* VGT_SHADER_STAGES_EN */
0xc0016900,
0x000002dc,
0x0000aa00, /* DB_ALPHA_TO_MASK */
0xc0066900,
0x000002de,
0x00000000, /* PA_SU_POLY_OFFSET_DB_FMT_CNTL */
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0026900,
0x000002e5,
0x00000000, /* VGT_STRMOUT_CONFIG */
0x00000000,
0xc01b6900,
0x000002f5,
0x76543210, /* PA_SC_CENTROID_PRIORITY_0 */
0xfedcba98, /* PA_SC_CENTROID_PRIORITY_1 */
0x00000000, /* PA_SC_LINE_CNTL */
0x00000000, /* PA_SC_AA_CONFIG */
0x00000005, /* PA_SU_VTX_CNTL */
0x3f800000, /* PA_CL_GB_VERT_CLIP_ADJ */
0x3f800000, /* PA_CL_GB_VERT_DISC_ADJ */
0x3f800000, /* PA_CL_GB_HORZ_CLIP_ADJ */
0x3f800000, /* PA_CL_GB_HORZ_DISC_ADJ */
0x00000000, /* PA_SC_AA_SAMPLE_LOCS_PIXEL_X0Y0_0 */
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xffffffff, /* PA_SC_AA_MASK_X0Y0_X1Y0 */
0xffffffff,
0xc0026900,
0x00000316,
0x0000000e, /* VGT_VERTEX_REUSE_BLOCK_CNTL */
0x00000010, /* */
};
const u32 si_default_size = ARRAY_SIZE(si_default_state);
| gpl-2.0 |
romracer/atrix-kernel | net/ipv6/ip6mr.c | 463 | 40790 | /*
* Linux IPv6 multicast routing support for BSD pim6sd
* Based on net/ipv4/ipmr.c.
*
* (c) 2004 Mickael Hoerdt, <hoerdt@clarinet.u-strasbg.fr>
* LSIIT Laboratory, Strasbourg, France
* (c) 2004 Jean-Philippe Andriot, <jean-philippe.andriot@6WIND.com>
* 6WIND, Paris, France
* Copyright (C)2007,2008 USAGI/WIDE Project
* YOSHIFUJI Hideaki <yoshfuji@linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <asm/system.h>
#include <asm/uaccess.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/kernel.h>
#include <linux/fcntl.h>
#include <linux/stat.h>
#include <linux/socket.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/inetdevice.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/raw.h>
#include <linux/notifier.h>
#include <linux/if_arp.h>
#include <net/checksum.h>
#include <net/netlink.h>
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <linux/mroute6.h>
#include <linux/pim.h>
#include <net/addrconf.h>
#include <linux/netfilter_ipv6.h>
#include <net/ip6_checksum.h>
/* Big lock, protecting vif table, mrt cache and mroute socket state.
Note that the changes are semaphored via rtnl_lock.
*/
static DEFINE_RWLOCK(mrt_lock);
/*
* Multicast router control variables
*/
#define MIF_EXISTS(_net, _idx) ((_net)->ipv6.vif6_table[_idx].dev != NULL)
static struct mfc6_cache *mfc_unres_queue; /* Queue of unresolved entries */
/* Special spinlock for queue of unresolved entries */
static DEFINE_SPINLOCK(mfc_unres_lock);
/* We return to original Alan's scheme. Hash table of resolved
entries is changed only in process context and protected
with weak lock mrt_lock. Queue of unresolved entries is protected
with strong spinlock mfc_unres_lock.
In this case data path is free of exclusive locks at all.
*/
static struct kmem_cache *mrt_cachep __read_mostly;
static int ip6_mr_forward(struct sk_buff *skb, struct mfc6_cache *cache);
static int ip6mr_cache_report(struct net *net, struct sk_buff *pkt,
mifi_t mifi, int assert);
static int ip6mr_fill_mroute(struct sk_buff *skb, struct mfc6_cache *c, struct rtmsg *rtm);
static void mroute_clean_tables(struct net *net);
static struct timer_list ipmr_expire_timer;
#ifdef CONFIG_PROC_FS
struct ipmr_mfc_iter {
struct seq_net_private p;
struct mfc6_cache **cache;
int ct;
};
static struct mfc6_cache *ipmr_mfc_seq_idx(struct net *net,
struct ipmr_mfc_iter *it, loff_t pos)
{
struct mfc6_cache *mfc;
it->cache = net->ipv6.mfc6_cache_array;
read_lock(&mrt_lock);
for (it->ct = 0; it->ct < MFC6_LINES; it->ct++)
for (mfc = net->ipv6.mfc6_cache_array[it->ct];
mfc; mfc = mfc->next)
if (pos-- == 0)
return mfc;
read_unlock(&mrt_lock);
it->cache = &mfc_unres_queue;
spin_lock_bh(&mfc_unres_lock);
for (mfc = mfc_unres_queue; mfc; mfc = mfc->next)
if (net_eq(mfc6_net(mfc), net) &&
pos-- == 0)
return mfc;
spin_unlock_bh(&mfc_unres_lock);
it->cache = NULL;
return NULL;
}
/*
* The /proc interfaces to multicast routing /proc/ip6_mr_cache /proc/ip6_mr_vif
*/
struct ipmr_vif_iter {
struct seq_net_private p;
int ct;
};
static struct mif_device *ip6mr_vif_seq_idx(struct net *net,
struct ipmr_vif_iter *iter,
loff_t pos)
{
for (iter->ct = 0; iter->ct < net->ipv6.maxvif; ++iter->ct) {
if (!MIF_EXISTS(net, iter->ct))
continue;
if (pos-- == 0)
return &net->ipv6.vif6_table[iter->ct];
}
return NULL;
}
static void *ip6mr_vif_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(mrt_lock)
{
struct net *net = seq_file_net(seq);
read_lock(&mrt_lock);
return *pos ? ip6mr_vif_seq_idx(net, seq->private, *pos - 1)
: SEQ_START_TOKEN;
}
static void *ip6mr_vif_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct ipmr_vif_iter *iter = seq->private;
struct net *net = seq_file_net(seq);
++*pos;
if (v == SEQ_START_TOKEN)
return ip6mr_vif_seq_idx(net, iter, 0);
while (++iter->ct < net->ipv6.maxvif) {
if (!MIF_EXISTS(net, iter->ct))
continue;
return &net->ipv6.vif6_table[iter->ct];
}
return NULL;
}
static void ip6mr_vif_seq_stop(struct seq_file *seq, void *v)
__releases(mrt_lock)
{
read_unlock(&mrt_lock);
}
static int ip6mr_vif_seq_show(struct seq_file *seq, void *v)
{
struct net *net = seq_file_net(seq);
if (v == SEQ_START_TOKEN) {
seq_puts(seq,
"Interface BytesIn PktsIn BytesOut PktsOut Flags\n");
} else {
const struct mif_device *vif = v;
const char *name = vif->dev ? vif->dev->name : "none";
seq_printf(seq,
"%2td %-10s %8ld %7ld %8ld %7ld %05X\n",
vif - net->ipv6.vif6_table,
name, vif->bytes_in, vif->pkt_in,
vif->bytes_out, vif->pkt_out,
vif->flags);
}
return 0;
}
static const struct seq_operations ip6mr_vif_seq_ops = {
.start = ip6mr_vif_seq_start,
.next = ip6mr_vif_seq_next,
.stop = ip6mr_vif_seq_stop,
.show = ip6mr_vif_seq_show,
};
static int ip6mr_vif_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ip6mr_vif_seq_ops,
sizeof(struct ipmr_vif_iter));
}
static const struct file_operations ip6mr_vif_fops = {
.owner = THIS_MODULE,
.open = ip6mr_vif_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static void *ipmr_mfc_seq_start(struct seq_file *seq, loff_t *pos)
{
struct net *net = seq_file_net(seq);
return *pos ? ipmr_mfc_seq_idx(net, seq->private, *pos - 1)
: SEQ_START_TOKEN;
}
static void *ipmr_mfc_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct mfc6_cache *mfc = v;
struct ipmr_mfc_iter *it = seq->private;
struct net *net = seq_file_net(seq);
++*pos;
if (v == SEQ_START_TOKEN)
return ipmr_mfc_seq_idx(net, seq->private, 0);
if (mfc->next)
return mfc->next;
if (it->cache == &mfc_unres_queue)
goto end_of_list;
BUG_ON(it->cache != net->ipv6.mfc6_cache_array);
while (++it->ct < MFC6_LINES) {
mfc = net->ipv6.mfc6_cache_array[it->ct];
if (mfc)
return mfc;
}
/* exhausted cache_array, show unresolved */
read_unlock(&mrt_lock);
it->cache = &mfc_unres_queue;
it->ct = 0;
spin_lock_bh(&mfc_unres_lock);
mfc = mfc_unres_queue;
if (mfc)
return mfc;
end_of_list:
spin_unlock_bh(&mfc_unres_lock);
it->cache = NULL;
return NULL;
}
static void ipmr_mfc_seq_stop(struct seq_file *seq, void *v)
{
struct ipmr_mfc_iter *it = seq->private;
struct net *net = seq_file_net(seq);
if (it->cache == &mfc_unres_queue)
spin_unlock_bh(&mfc_unres_lock);
else if (it->cache == net->ipv6.mfc6_cache_array)
read_unlock(&mrt_lock);
}
static int ipmr_mfc_seq_show(struct seq_file *seq, void *v)
{
int n;
struct net *net = seq_file_net(seq);
if (v == SEQ_START_TOKEN) {
seq_puts(seq,
"Group "
"Origin "
"Iif Pkts Bytes Wrong Oifs\n");
} else {
const struct mfc6_cache *mfc = v;
const struct ipmr_mfc_iter *it = seq->private;
seq_printf(seq, "%pI6 %pI6 %-3hd",
&mfc->mf6c_mcastgrp, &mfc->mf6c_origin,
mfc->mf6c_parent);
if (it->cache != &mfc_unres_queue) {
seq_printf(seq, " %8lu %8lu %8lu",
mfc->mfc_un.res.pkt,
mfc->mfc_un.res.bytes,
mfc->mfc_un.res.wrong_if);
for (n = mfc->mfc_un.res.minvif;
n < mfc->mfc_un.res.maxvif; n++) {
if (MIF_EXISTS(net, n) &&
mfc->mfc_un.res.ttls[n] < 255)
seq_printf(seq,
" %2d:%-3d",
n, mfc->mfc_un.res.ttls[n]);
}
} else {
/* unresolved mfc_caches don't contain
* pkt, bytes and wrong_if values
*/
seq_printf(seq, " %8lu %8lu %8lu", 0ul, 0ul, 0ul);
}
seq_putc(seq, '\n');
}
return 0;
}
static const struct seq_operations ipmr_mfc_seq_ops = {
.start = ipmr_mfc_seq_start,
.next = ipmr_mfc_seq_next,
.stop = ipmr_mfc_seq_stop,
.show = ipmr_mfc_seq_show,
};
static int ipmr_mfc_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ipmr_mfc_seq_ops,
sizeof(struct ipmr_mfc_iter));
}
static const struct file_operations ip6mr_mfc_fops = {
.owner = THIS_MODULE,
.open = ipmr_mfc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
#ifdef CONFIG_IPV6_PIMSM_V2
static int pim6_rcv(struct sk_buff *skb)
{
struct pimreghdr *pim;
struct ipv6hdr *encap;
struct net_device *reg_dev = NULL;
struct net *net = dev_net(skb->dev);
int reg_vif_num = net->ipv6.mroute_reg_vif_num;
if (!pskb_may_pull(skb, sizeof(*pim) + sizeof(*encap)))
goto drop;
pim = (struct pimreghdr *)skb_transport_header(skb);
if (pim->type != ((PIM_VERSION << 4) | PIM_REGISTER) ||
(pim->flags & PIM_NULL_REGISTER) ||
(csum_ipv6_magic(&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr,
sizeof(*pim), IPPROTO_PIM,
csum_partial((void *)pim, sizeof(*pim), 0)) &&
csum_fold(skb_checksum(skb, 0, skb->len, 0))))
goto drop;
/* check if the inner packet is destined to mcast group */
encap = (struct ipv6hdr *)(skb_transport_header(skb) +
sizeof(*pim));
if (!ipv6_addr_is_multicast(&encap->daddr) ||
encap->payload_len == 0 ||
ntohs(encap->payload_len) + sizeof(*pim) > skb->len)
goto drop;
read_lock(&mrt_lock);
if (reg_vif_num >= 0)
reg_dev = net->ipv6.vif6_table[reg_vif_num].dev;
if (reg_dev)
dev_hold(reg_dev);
read_unlock(&mrt_lock);
if (reg_dev == NULL)
goto drop;
skb->mac_header = skb->network_header;
skb_pull(skb, (u8 *)encap - skb->data);
skb_reset_network_header(skb);
skb->dev = reg_dev;
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = 0;
skb->pkt_type = PACKET_HOST;
skb_dst_drop(skb);
reg_dev->stats.rx_bytes += skb->len;
reg_dev->stats.rx_packets++;
nf_reset(skb);
netif_rx(skb);
dev_put(reg_dev);
return 0;
drop:
kfree_skb(skb);
return 0;
}
static const struct inet6_protocol pim6_protocol = {
.handler = pim6_rcv,
};
/* Service routines creating virtual interfaces: PIMREG */
static netdev_tx_t reg_vif_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct net *net = dev_net(dev);
read_lock(&mrt_lock);
dev->stats.tx_bytes += skb->len;
dev->stats.tx_packets++;
ip6mr_cache_report(net, skb, net->ipv6.mroute_reg_vif_num,
MRT6MSG_WHOLEPKT);
read_unlock(&mrt_lock);
kfree_skb(skb);
return NETDEV_TX_OK;
}
static const struct net_device_ops reg_vif_netdev_ops = {
.ndo_start_xmit = reg_vif_xmit,
};
static void reg_vif_setup(struct net_device *dev)
{
dev->type = ARPHRD_PIMREG;
dev->mtu = 1500 - sizeof(struct ipv6hdr) - 8;
dev->flags = IFF_NOARP;
dev->netdev_ops = ®_vif_netdev_ops;
dev->destructor = free_netdev;
dev->features |= NETIF_F_NETNS_LOCAL;
}
static struct net_device *ip6mr_reg_vif(struct net *net)
{
struct net_device *dev;
dev = alloc_netdev(0, "pim6reg", reg_vif_setup);
if (dev == NULL)
return NULL;
dev_net_set(dev, net);
if (register_netdevice(dev)) {
free_netdev(dev);
return NULL;
}
dev->iflink = 0;
if (dev_open(dev))
goto failure;
dev_hold(dev);
return dev;
failure:
/* allow the register to be completed before unregistering. */
rtnl_unlock();
rtnl_lock();
unregister_netdevice(dev);
return NULL;
}
#endif
/*
* Delete a VIF entry
*/
static int mif6_delete(struct net *net, int vifi)
{
struct mif_device *v;
struct net_device *dev;
struct inet6_dev *in6_dev;
if (vifi < 0 || vifi >= net->ipv6.maxvif)
return -EADDRNOTAVAIL;
v = &net->ipv6.vif6_table[vifi];
write_lock_bh(&mrt_lock);
dev = v->dev;
v->dev = NULL;
if (!dev) {
write_unlock_bh(&mrt_lock);
return -EADDRNOTAVAIL;
}
#ifdef CONFIG_IPV6_PIMSM_V2
if (vifi == net->ipv6.mroute_reg_vif_num)
net->ipv6.mroute_reg_vif_num = -1;
#endif
if (vifi + 1 == net->ipv6.maxvif) {
int tmp;
for (tmp = vifi - 1; tmp >= 0; tmp--) {
if (MIF_EXISTS(net, tmp))
break;
}
net->ipv6.maxvif = tmp + 1;
}
write_unlock_bh(&mrt_lock);
dev_set_allmulti(dev, -1);
in6_dev = __in6_dev_get(dev);
if (in6_dev)
in6_dev->cnf.mc_forwarding--;
if (v->flags & MIFF_REGISTER)
unregister_netdevice(dev);
dev_put(dev);
return 0;
}
static inline void ip6mr_cache_free(struct mfc6_cache *c)
{
release_net(mfc6_net(c));
kmem_cache_free(mrt_cachep, c);
}
/* Destroy an unresolved cache entry, killing queued skbs
and reporting error to netlink readers.
*/
static void ip6mr_destroy_unres(struct mfc6_cache *c)
{
struct sk_buff *skb;
struct net *net = mfc6_net(c);
atomic_dec(&net->ipv6.cache_resolve_queue_len);
while((skb = skb_dequeue(&c->mfc_un.unres.unresolved)) != NULL) {
if (ipv6_hdr(skb)->version == 0) {
struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct ipv6hdr));
nlh->nlmsg_type = NLMSG_ERROR;
nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr));
skb_trim(skb, nlh->nlmsg_len);
((struct nlmsgerr *)NLMSG_DATA(nlh))->error = -ETIMEDOUT;
rtnl_unicast(skb, net, NETLINK_CB(skb).pid);
} else
kfree_skb(skb);
}
ip6mr_cache_free(c);
}
/* Single timer process for all the unresolved queue. */
static void ipmr_do_expire_process(unsigned long dummy)
{
unsigned long now = jiffies;
unsigned long expires = 10 * HZ;
struct mfc6_cache *c, **cp;
cp = &mfc_unres_queue;
while ((c = *cp) != NULL) {
if (time_after(c->mfc_un.unres.expires, now)) {
/* not yet... */
unsigned long interval = c->mfc_un.unres.expires - now;
if (interval < expires)
expires = interval;
cp = &c->next;
continue;
}
*cp = c->next;
ip6mr_destroy_unres(c);
}
if (mfc_unres_queue != NULL)
mod_timer(&ipmr_expire_timer, jiffies + expires);
}
static void ipmr_expire_process(unsigned long dummy)
{
if (!spin_trylock(&mfc_unres_lock)) {
mod_timer(&ipmr_expire_timer, jiffies + 1);
return;
}
if (mfc_unres_queue != NULL)
ipmr_do_expire_process(dummy);
spin_unlock(&mfc_unres_lock);
}
/* Fill oifs list. It is called under write locked mrt_lock. */
static void ip6mr_update_thresholds(struct mfc6_cache *cache, unsigned char *ttls)
{
int vifi;
struct net *net = mfc6_net(cache);
cache->mfc_un.res.minvif = MAXMIFS;
cache->mfc_un.res.maxvif = 0;
memset(cache->mfc_un.res.ttls, 255, MAXMIFS);
for (vifi = 0; vifi < net->ipv6.maxvif; vifi++) {
if (MIF_EXISTS(net, vifi) &&
ttls[vifi] && ttls[vifi] < 255) {
cache->mfc_un.res.ttls[vifi] = ttls[vifi];
if (cache->mfc_un.res.minvif > vifi)
cache->mfc_un.res.minvif = vifi;
if (cache->mfc_un.res.maxvif <= vifi)
cache->mfc_un.res.maxvif = vifi + 1;
}
}
}
static int mif6_add(struct net *net, struct mif6ctl *vifc, int mrtsock)
{
int vifi = vifc->mif6c_mifi;
struct mif_device *v = &net->ipv6.vif6_table[vifi];
struct net_device *dev;
struct inet6_dev *in6_dev;
int err;
/* Is vif busy ? */
if (MIF_EXISTS(net, vifi))
return -EADDRINUSE;
switch (vifc->mif6c_flags) {
#ifdef CONFIG_IPV6_PIMSM_V2
case MIFF_REGISTER:
/*
* Special Purpose VIF in PIM
* All the packets will be sent to the daemon
*/
if (net->ipv6.mroute_reg_vif_num >= 0)
return -EADDRINUSE;
dev = ip6mr_reg_vif(net);
if (!dev)
return -ENOBUFS;
err = dev_set_allmulti(dev, 1);
if (err) {
unregister_netdevice(dev);
dev_put(dev);
return err;
}
break;
#endif
case 0:
dev = dev_get_by_index(net, vifc->mif6c_pifi);
if (!dev)
return -EADDRNOTAVAIL;
err = dev_set_allmulti(dev, 1);
if (err) {
dev_put(dev);
return err;
}
break;
default:
return -EINVAL;
}
in6_dev = __in6_dev_get(dev);
if (in6_dev)
in6_dev->cnf.mc_forwarding++;
/*
* Fill in the VIF structures
*/
v->rate_limit = vifc->vifc_rate_limit;
v->flags = vifc->mif6c_flags;
if (!mrtsock)
v->flags |= VIFF_STATIC;
v->threshold = vifc->vifc_threshold;
v->bytes_in = 0;
v->bytes_out = 0;
v->pkt_in = 0;
v->pkt_out = 0;
v->link = dev->ifindex;
if (v->flags & MIFF_REGISTER)
v->link = dev->iflink;
/* And finish update writing critical data */
write_lock_bh(&mrt_lock);
v->dev = dev;
#ifdef CONFIG_IPV6_PIMSM_V2
if (v->flags & MIFF_REGISTER)
net->ipv6.mroute_reg_vif_num = vifi;
#endif
if (vifi + 1 > net->ipv6.maxvif)
net->ipv6.maxvif = vifi + 1;
write_unlock_bh(&mrt_lock);
return 0;
}
static struct mfc6_cache *ip6mr_cache_find(struct net *net,
struct in6_addr *origin,
struct in6_addr *mcastgrp)
{
int line = MFC6_HASH(mcastgrp, origin);
struct mfc6_cache *c;
for (c = net->ipv6.mfc6_cache_array[line]; c; c = c->next) {
if (ipv6_addr_equal(&c->mf6c_origin, origin) &&
ipv6_addr_equal(&c->mf6c_mcastgrp, mcastgrp))
break;
}
return c;
}
/*
* Allocate a multicast cache entry
*/
static struct mfc6_cache *ip6mr_cache_alloc(struct net *net)
{
struct mfc6_cache *c = kmem_cache_zalloc(mrt_cachep, GFP_KERNEL);
if (c == NULL)
return NULL;
c->mfc_un.res.minvif = MAXMIFS;
mfc6_net_set(c, net);
return c;
}
static struct mfc6_cache *ip6mr_cache_alloc_unres(struct net *net)
{
struct mfc6_cache *c = kmem_cache_zalloc(mrt_cachep, GFP_ATOMIC);
if (c == NULL)
return NULL;
skb_queue_head_init(&c->mfc_un.unres.unresolved);
c->mfc_un.unres.expires = jiffies + 10 * HZ;
mfc6_net_set(c, net);
return c;
}
/*
* A cache entry has gone into a resolved state from queued
*/
static void ip6mr_cache_resolve(struct mfc6_cache *uc, struct mfc6_cache *c)
{
struct sk_buff *skb;
/*
* Play the pending entries through our router
*/
while((skb = __skb_dequeue(&uc->mfc_un.unres.unresolved))) {
if (ipv6_hdr(skb)->version == 0) {
int err;
struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct ipv6hdr));
if (ip6mr_fill_mroute(skb, c, NLMSG_DATA(nlh)) > 0) {
nlh->nlmsg_len = skb_tail_pointer(skb) - (u8 *)nlh;
} else {
nlh->nlmsg_type = NLMSG_ERROR;
nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr));
skb_trim(skb, nlh->nlmsg_len);
((struct nlmsgerr *)NLMSG_DATA(nlh))->error = -EMSGSIZE;
}
err = rtnl_unicast(skb, mfc6_net(uc), NETLINK_CB(skb).pid);
} else
ip6_mr_forward(skb, c);
}
}
/*
* Bounce a cache query up to pim6sd. We could use netlink for this but pim6sd
* expects the following bizarre scheme.
*
* Called under mrt_lock.
*/
static int ip6mr_cache_report(struct net *net, struct sk_buff *pkt, mifi_t mifi,
int assert)
{
struct sk_buff *skb;
struct mrt6msg *msg;
int ret;
#ifdef CONFIG_IPV6_PIMSM_V2
if (assert == MRT6MSG_WHOLEPKT)
skb = skb_realloc_headroom(pkt, -skb_network_offset(pkt)
+sizeof(*msg));
else
#endif
skb = alloc_skb(sizeof(struct ipv6hdr) + sizeof(*msg), GFP_ATOMIC);
if (!skb)
return -ENOBUFS;
/* I suppose that internal messages
* do not require checksums */
skb->ip_summed = CHECKSUM_UNNECESSARY;
#ifdef CONFIG_IPV6_PIMSM_V2
if (assert == MRT6MSG_WHOLEPKT) {
/* Ugly, but we have no choice with this interface.
Duplicate old header, fix length etc.
And all this only to mangle msg->im6_msgtype and
to set msg->im6_mbz to "mbz" :-)
*/
skb_push(skb, -skb_network_offset(pkt));
skb_push(skb, sizeof(*msg));
skb_reset_transport_header(skb);
msg = (struct mrt6msg *)skb_transport_header(skb);
msg->im6_mbz = 0;
msg->im6_msgtype = MRT6MSG_WHOLEPKT;
msg->im6_mif = net->ipv6.mroute_reg_vif_num;
msg->im6_pad = 0;
ipv6_addr_copy(&msg->im6_src, &ipv6_hdr(pkt)->saddr);
ipv6_addr_copy(&msg->im6_dst, &ipv6_hdr(pkt)->daddr);
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else
#endif
{
/*
* Copy the IP header
*/
skb_put(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
skb_copy_to_linear_data(skb, ipv6_hdr(pkt), sizeof(struct ipv6hdr));
/*
* Add our header
*/
skb_put(skb, sizeof(*msg));
skb_reset_transport_header(skb);
msg = (struct mrt6msg *)skb_transport_header(skb);
msg->im6_mbz = 0;
msg->im6_msgtype = assert;
msg->im6_mif = mifi;
msg->im6_pad = 0;
ipv6_addr_copy(&msg->im6_src, &ipv6_hdr(pkt)->saddr);
ipv6_addr_copy(&msg->im6_dst, &ipv6_hdr(pkt)->daddr);
skb_dst_set(skb, dst_clone(skb_dst(pkt)));
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
if (net->ipv6.mroute6_sk == NULL) {
kfree_skb(skb);
return -EINVAL;
}
/*
* Deliver to user space multicast routing algorithms
*/
ret = sock_queue_rcv_skb(net->ipv6.mroute6_sk, skb);
if (ret < 0) {
if (net_ratelimit())
printk(KERN_WARNING "mroute6: pending queue full, dropping entries.\n");
kfree_skb(skb);
}
return ret;
}
/*
* Queue a packet for resolution. It gets locked cache entry!
*/
static int
ip6mr_cache_unresolved(struct net *net, mifi_t mifi, struct sk_buff *skb)
{
int err;
struct mfc6_cache *c;
spin_lock_bh(&mfc_unres_lock);
for (c = mfc_unres_queue; c; c = c->next) {
if (net_eq(mfc6_net(c), net) &&
ipv6_addr_equal(&c->mf6c_mcastgrp, &ipv6_hdr(skb)->daddr) &&
ipv6_addr_equal(&c->mf6c_origin, &ipv6_hdr(skb)->saddr))
break;
}
if (c == NULL) {
/*
* Create a new entry if allowable
*/
if (atomic_read(&net->ipv6.cache_resolve_queue_len) >= 10 ||
(c = ip6mr_cache_alloc_unres(net)) == NULL) {
spin_unlock_bh(&mfc_unres_lock);
kfree_skb(skb);
return -ENOBUFS;
}
/*
* Fill in the new cache entry
*/
c->mf6c_parent = -1;
c->mf6c_origin = ipv6_hdr(skb)->saddr;
c->mf6c_mcastgrp = ipv6_hdr(skb)->daddr;
/*
* Reflect first query at pim6sd
*/
err = ip6mr_cache_report(net, skb, mifi, MRT6MSG_NOCACHE);
if (err < 0) {
/* If the report failed throw the cache entry
out - Brad Parker
*/
spin_unlock_bh(&mfc_unres_lock);
ip6mr_cache_free(c);
kfree_skb(skb);
return err;
}
atomic_inc(&net->ipv6.cache_resolve_queue_len);
c->next = mfc_unres_queue;
mfc_unres_queue = c;
ipmr_do_expire_process(1);
}
/*
* See if we can append the packet
*/
if (c->mfc_un.unres.unresolved.qlen > 3) {
kfree_skb(skb);
err = -ENOBUFS;
} else {
skb_queue_tail(&c->mfc_un.unres.unresolved, skb);
err = 0;
}
spin_unlock_bh(&mfc_unres_lock);
return err;
}
/*
* MFC6 cache manipulation by user space
*/
static int ip6mr_mfc_delete(struct net *net, struct mf6cctl *mfc)
{
int line;
struct mfc6_cache *c, **cp;
line = MFC6_HASH(&mfc->mf6cc_mcastgrp.sin6_addr, &mfc->mf6cc_origin.sin6_addr);
for (cp = &net->ipv6.mfc6_cache_array[line];
(c = *cp) != NULL; cp = &c->next) {
if (ipv6_addr_equal(&c->mf6c_origin, &mfc->mf6cc_origin.sin6_addr) &&
ipv6_addr_equal(&c->mf6c_mcastgrp, &mfc->mf6cc_mcastgrp.sin6_addr)) {
write_lock_bh(&mrt_lock);
*cp = c->next;
write_unlock_bh(&mrt_lock);
ip6mr_cache_free(c);
return 0;
}
}
return -ENOENT;
}
static int ip6mr_device_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
struct net *net = dev_net(dev);
struct mif_device *v;
int ct;
if (event != NETDEV_UNREGISTER)
return NOTIFY_DONE;
v = &net->ipv6.vif6_table[0];
for (ct = 0; ct < net->ipv6.maxvif; ct++, v++) {
if (v->dev == dev)
mif6_delete(net, ct);
}
return NOTIFY_DONE;
}
static struct notifier_block ip6_mr_notifier = {
.notifier_call = ip6mr_device_event
};
/*
* Setup for IP multicast routing
*/
static int __net_init ip6mr_net_init(struct net *net)
{
int err = 0;
net->ipv6.vif6_table = kcalloc(MAXMIFS, sizeof(struct mif_device),
GFP_KERNEL);
if (!net->ipv6.vif6_table) {
err = -ENOMEM;
goto fail;
}
/* Forwarding cache */
net->ipv6.mfc6_cache_array = kcalloc(MFC6_LINES,
sizeof(struct mfc6_cache *),
GFP_KERNEL);
if (!net->ipv6.mfc6_cache_array) {
err = -ENOMEM;
goto fail_mfc6_cache;
}
#ifdef CONFIG_IPV6_PIMSM_V2
net->ipv6.mroute_reg_vif_num = -1;
#endif
#ifdef CONFIG_PROC_FS
err = -ENOMEM;
if (!proc_net_fops_create(net, "ip6_mr_vif", 0, &ip6mr_vif_fops))
goto proc_vif_fail;
if (!proc_net_fops_create(net, "ip6_mr_cache", 0, &ip6mr_mfc_fops))
goto proc_cache_fail;
#endif
return 0;
#ifdef CONFIG_PROC_FS
proc_cache_fail:
proc_net_remove(net, "ip6_mr_vif");
proc_vif_fail:
kfree(net->ipv6.mfc6_cache_array);
#endif
fail_mfc6_cache:
kfree(net->ipv6.vif6_table);
fail:
return err;
}
static void __net_exit ip6mr_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
proc_net_remove(net, "ip6_mr_cache");
proc_net_remove(net, "ip6_mr_vif");
#endif
mroute_clean_tables(net);
kfree(net->ipv6.mfc6_cache_array);
kfree(net->ipv6.vif6_table);
}
static struct pernet_operations ip6mr_net_ops = {
.init = ip6mr_net_init,
.exit = ip6mr_net_exit,
};
int __init ip6_mr_init(void)
{
int err;
mrt_cachep = kmem_cache_create("ip6_mrt_cache",
sizeof(struct mfc6_cache),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!mrt_cachep)
return -ENOMEM;
err = register_pernet_subsys(&ip6mr_net_ops);
if (err)
goto reg_pernet_fail;
setup_timer(&ipmr_expire_timer, ipmr_expire_process, 0);
err = register_netdevice_notifier(&ip6_mr_notifier);
if (err)
goto reg_notif_fail;
#ifdef CONFIG_IPV6_PIMSM_V2
if (inet6_add_protocol(&pim6_protocol, IPPROTO_PIM) < 0) {
printk(KERN_ERR "ip6_mr_init: can't add PIM protocol\n");
err = -EAGAIN;
goto add_proto_fail;
}
#endif
return 0;
#ifdef CONFIG_IPV6_PIMSM_V2
add_proto_fail:
unregister_netdevice_notifier(&ip6_mr_notifier);
#endif
reg_notif_fail:
del_timer(&ipmr_expire_timer);
unregister_pernet_subsys(&ip6mr_net_ops);
reg_pernet_fail:
kmem_cache_destroy(mrt_cachep);
return err;
}
void ip6_mr_cleanup(void)
{
unregister_netdevice_notifier(&ip6_mr_notifier);
del_timer(&ipmr_expire_timer);
unregister_pernet_subsys(&ip6mr_net_ops);
kmem_cache_destroy(mrt_cachep);
}
static int ip6mr_mfc_add(struct net *net, struct mf6cctl *mfc, int mrtsock)
{
int line;
struct mfc6_cache *uc, *c, **cp;
unsigned char ttls[MAXMIFS];
int i;
memset(ttls, 255, MAXMIFS);
for (i = 0; i < MAXMIFS; i++) {
if (IF_ISSET(i, &mfc->mf6cc_ifset))
ttls[i] = 1;
}
line = MFC6_HASH(&mfc->mf6cc_mcastgrp.sin6_addr, &mfc->mf6cc_origin.sin6_addr);
for (cp = &net->ipv6.mfc6_cache_array[line];
(c = *cp) != NULL; cp = &c->next) {
if (ipv6_addr_equal(&c->mf6c_origin, &mfc->mf6cc_origin.sin6_addr) &&
ipv6_addr_equal(&c->mf6c_mcastgrp, &mfc->mf6cc_mcastgrp.sin6_addr))
break;
}
if (c != NULL) {
write_lock_bh(&mrt_lock);
c->mf6c_parent = mfc->mf6cc_parent;
ip6mr_update_thresholds(c, ttls);
if (!mrtsock)
c->mfc_flags |= MFC_STATIC;
write_unlock_bh(&mrt_lock);
return 0;
}
if (!ipv6_addr_is_multicast(&mfc->mf6cc_mcastgrp.sin6_addr))
return -EINVAL;
c = ip6mr_cache_alloc(net);
if (c == NULL)
return -ENOMEM;
c->mf6c_origin = mfc->mf6cc_origin.sin6_addr;
c->mf6c_mcastgrp = mfc->mf6cc_mcastgrp.sin6_addr;
c->mf6c_parent = mfc->mf6cc_parent;
ip6mr_update_thresholds(c, ttls);
if (!mrtsock)
c->mfc_flags |= MFC_STATIC;
write_lock_bh(&mrt_lock);
c->next = net->ipv6.mfc6_cache_array[line];
net->ipv6.mfc6_cache_array[line] = c;
write_unlock_bh(&mrt_lock);
/*
* Check to see if we resolved a queued list. If so we
* need to send on the frames and tidy up.
*/
spin_lock_bh(&mfc_unres_lock);
for (cp = &mfc_unres_queue; (uc = *cp) != NULL;
cp = &uc->next) {
if (net_eq(mfc6_net(uc), net) &&
ipv6_addr_equal(&uc->mf6c_origin, &c->mf6c_origin) &&
ipv6_addr_equal(&uc->mf6c_mcastgrp, &c->mf6c_mcastgrp)) {
*cp = uc->next;
atomic_dec(&net->ipv6.cache_resolve_queue_len);
break;
}
}
if (mfc_unres_queue == NULL)
del_timer(&ipmr_expire_timer);
spin_unlock_bh(&mfc_unres_lock);
if (uc) {
ip6mr_cache_resolve(uc, c);
ip6mr_cache_free(uc);
}
return 0;
}
/*
* Close the multicast socket, and clear the vif tables etc
*/
static void mroute_clean_tables(struct net *net)
{
int i;
/*
* Shut down all active vif entries
*/
for (i = 0; i < net->ipv6.maxvif; i++) {
if (!(net->ipv6.vif6_table[i].flags & VIFF_STATIC))
mif6_delete(net, i);
}
/*
* Wipe the cache
*/
for (i = 0; i < MFC6_LINES; i++) {
struct mfc6_cache *c, **cp;
cp = &net->ipv6.mfc6_cache_array[i];
while ((c = *cp) != NULL) {
if (c->mfc_flags & MFC_STATIC) {
cp = &c->next;
continue;
}
write_lock_bh(&mrt_lock);
*cp = c->next;
write_unlock_bh(&mrt_lock);
ip6mr_cache_free(c);
}
}
if (atomic_read(&net->ipv6.cache_resolve_queue_len) != 0) {
struct mfc6_cache *c, **cp;
spin_lock_bh(&mfc_unres_lock);
cp = &mfc_unres_queue;
while ((c = *cp) != NULL) {
if (!net_eq(mfc6_net(c), net)) {
cp = &c->next;
continue;
}
*cp = c->next;
ip6mr_destroy_unres(c);
}
spin_unlock_bh(&mfc_unres_lock);
}
}
static int ip6mr_sk_init(struct sock *sk)
{
int err = 0;
struct net *net = sock_net(sk);
rtnl_lock();
write_lock_bh(&mrt_lock);
if (likely(net->ipv6.mroute6_sk == NULL)) {
net->ipv6.mroute6_sk = sk;
net->ipv6.devconf_all->mc_forwarding++;
}
else
err = -EADDRINUSE;
write_unlock_bh(&mrt_lock);
rtnl_unlock();
return err;
}
int ip6mr_sk_done(struct sock *sk)
{
int err = 0;
struct net *net = sock_net(sk);
rtnl_lock();
if (sk == net->ipv6.mroute6_sk) {
write_lock_bh(&mrt_lock);
net->ipv6.mroute6_sk = NULL;
net->ipv6.devconf_all->mc_forwarding--;
write_unlock_bh(&mrt_lock);
mroute_clean_tables(net);
} else
err = -EACCES;
rtnl_unlock();
return err;
}
/*
* Socket options and virtual interface manipulation. The whole
* virtual interface system is a complete heap, but unfortunately
* that's how BSD mrouted happens to think. Maybe one day with a proper
* MOSPF/PIM router set up we can clean this up.
*/
int ip6_mroute_setsockopt(struct sock *sk, int optname, char __user *optval, unsigned int optlen)
{
int ret;
struct mif6ctl vif;
struct mf6cctl mfc;
mifi_t mifi;
struct net *net = sock_net(sk);
if (optname != MRT6_INIT) {
if (sk != net->ipv6.mroute6_sk && !capable(CAP_NET_ADMIN))
return -EACCES;
}
switch (optname) {
case MRT6_INIT:
if (sk->sk_type != SOCK_RAW ||
inet_sk(sk)->num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
if (optlen < sizeof(int))
return -EINVAL;
return ip6mr_sk_init(sk);
case MRT6_DONE:
return ip6mr_sk_done(sk);
case MRT6_ADD_MIF:
if (optlen < sizeof(vif))
return -EINVAL;
if (copy_from_user(&vif, optval, sizeof(vif)))
return -EFAULT;
if (vif.mif6c_mifi >= MAXMIFS)
return -ENFILE;
rtnl_lock();
ret = mif6_add(net, &vif, sk == net->ipv6.mroute6_sk);
rtnl_unlock();
return ret;
case MRT6_DEL_MIF:
if (optlen < sizeof(mifi_t))
return -EINVAL;
if (copy_from_user(&mifi, optval, sizeof(mifi_t)))
return -EFAULT;
rtnl_lock();
ret = mif6_delete(net, mifi);
rtnl_unlock();
return ret;
/*
* Manipulate the forwarding caches. These live
* in a sort of kernel/user symbiosis.
*/
case MRT6_ADD_MFC:
case MRT6_DEL_MFC:
if (optlen < sizeof(mfc))
return -EINVAL;
if (copy_from_user(&mfc, optval, sizeof(mfc)))
return -EFAULT;
rtnl_lock();
if (optname == MRT6_DEL_MFC)
ret = ip6mr_mfc_delete(net, &mfc);
else
ret = ip6mr_mfc_add(net, &mfc,
sk == net->ipv6.mroute6_sk);
rtnl_unlock();
return ret;
/*
* Control PIM assert (to activate pim will activate assert)
*/
case MRT6_ASSERT:
{
int v;
if (get_user(v, (int __user *)optval))
return -EFAULT;
net->ipv6.mroute_do_assert = !!v;
return 0;
}
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
{
int v;
if (get_user(v, (int __user *)optval))
return -EFAULT;
v = !!v;
rtnl_lock();
ret = 0;
if (v != net->ipv6.mroute_do_pim) {
net->ipv6.mroute_do_pim = v;
net->ipv6.mroute_do_assert = v;
}
rtnl_unlock();
return ret;
}
#endif
/*
* Spurious command, or MRT6_VERSION which you cannot
* set.
*/
default:
return -ENOPROTOOPT;
}
}
/*
* Getsock opt support for the multicast routing system.
*/
int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval,
int __user *optlen)
{
int olr;
int val;
struct net *net = sock_net(sk);
switch (optname) {
case MRT6_VERSION:
val = 0x0305;
break;
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
val = net->ipv6.mroute_do_pim;
break;
#endif
case MRT6_ASSERT:
val = net->ipv6.mroute_do_assert;
break;
default:
return -ENOPROTOOPT;
}
if (get_user(olr, optlen))
return -EFAULT;
olr = min_t(int, olr, sizeof(int));
if (olr < 0)
return -EINVAL;
if (put_user(olr, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, olr))
return -EFAULT;
return 0;
}
/*
* The IP multicast ioctl support routines.
*/
int ip6mr_ioctl(struct sock *sk, int cmd, void __user *arg)
{
struct sioc_sg_req6 sr;
struct sioc_mif_req6 vr;
struct mif_device *vif;
struct mfc6_cache *c;
struct net *net = sock_net(sk);
switch (cmd) {
case SIOCGETMIFCNT_IN6:
if (copy_from_user(&vr, arg, sizeof(vr)))
return -EFAULT;
if (vr.mifi >= net->ipv6.maxvif)
return -EINVAL;
read_lock(&mrt_lock);
vif = &net->ipv6.vif6_table[vr.mifi];
if (MIF_EXISTS(net, vr.mifi)) {
vr.icount = vif->pkt_in;
vr.ocount = vif->pkt_out;
vr.ibytes = vif->bytes_in;
vr.obytes = vif->bytes_out;
read_unlock(&mrt_lock);
if (copy_to_user(arg, &vr, sizeof(vr)))
return -EFAULT;
return 0;
}
read_unlock(&mrt_lock);
return -EADDRNOTAVAIL;
case SIOCGETSGCNT_IN6:
if (copy_from_user(&sr, arg, sizeof(sr)))
return -EFAULT;
read_lock(&mrt_lock);
c = ip6mr_cache_find(net, &sr.src.sin6_addr, &sr.grp.sin6_addr);
if (c) {
sr.pktcnt = c->mfc_un.res.pkt;
sr.bytecnt = c->mfc_un.res.bytes;
sr.wrong_if = c->mfc_un.res.wrong_if;
read_unlock(&mrt_lock);
if (copy_to_user(arg, &sr, sizeof(sr)))
return -EFAULT;
return 0;
}
read_unlock(&mrt_lock);
return -EADDRNOTAVAIL;
default:
return -ENOIOCTLCMD;
}
}
static inline int ip6mr_forward2_finish(struct sk_buff *skb)
{
IP6_INC_STATS_BH(dev_net(skb_dst(skb)->dev), ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTFORWDATAGRAMS);
return dst_output(skb);
}
/*
* Processing handlers for ip6mr_forward
*/
static int ip6mr_forward2(struct sk_buff *skb, struct mfc6_cache *c, int vifi)
{
struct ipv6hdr *ipv6h;
struct net *net = mfc6_net(c);
struct mif_device *vif = &net->ipv6.vif6_table[vifi];
struct net_device *dev;
struct dst_entry *dst;
struct flowi fl;
if (vif->dev == NULL)
goto out_free;
#ifdef CONFIG_IPV6_PIMSM_V2
if (vif->flags & MIFF_REGISTER) {
vif->pkt_out++;
vif->bytes_out += skb->len;
vif->dev->stats.tx_bytes += skb->len;
vif->dev->stats.tx_packets++;
ip6mr_cache_report(net, skb, vifi, MRT6MSG_WHOLEPKT);
goto out_free;
}
#endif
ipv6h = ipv6_hdr(skb);
fl = (struct flowi) {
.oif = vif->link,
.nl_u = { .ip6_u =
{ .daddr = ipv6h->daddr, }
}
};
dst = ip6_route_output(net, NULL, &fl);
if (!dst)
goto out_free;
skb_dst_drop(skb);
skb_dst_set(skb, dst);
/*
* RFC1584 teaches, that DVMRP/PIM router must deliver packets locally
* not only before forwarding, but after forwarding on all output
* interfaces. It is clear, if mrouter runs a multicasting
* program, it should receive packets not depending to what interface
* program is joined.
* If we will not make it, the program will have to join on all
* interfaces. On the other hand, multihoming host (or router, but
* not mrouter) cannot join to more than one interface - it will
* result in receiving multiple packets.
*/
dev = vif->dev;
skb->dev = dev;
vif->pkt_out++;
vif->bytes_out += skb->len;
/* We are about to write */
/* XXX: extension headers? */
if (skb_cow(skb, sizeof(*ipv6h) + LL_RESERVED_SPACE(dev)))
goto out_free;
ipv6h = ipv6_hdr(skb);
ipv6h->hop_limit--;
IP6CB(skb)->flags |= IP6SKB_FORWARDED;
return NF_HOOK(PF_INET6, NF_INET_FORWARD, skb, skb->dev, dev,
ip6mr_forward2_finish);
out_free:
kfree_skb(skb);
return 0;
}
static int ip6mr_find_vif(struct net_device *dev)
{
struct net *net = dev_net(dev);
int ct;
for (ct = net->ipv6.maxvif - 1; ct >= 0; ct--) {
if (net->ipv6.vif6_table[ct].dev == dev)
break;
}
return ct;
}
static int ip6_mr_forward(struct sk_buff *skb, struct mfc6_cache *cache)
{
int psend = -1;
int vif, ct;
struct net *net = mfc6_net(cache);
vif = cache->mf6c_parent;
cache->mfc_un.res.pkt++;
cache->mfc_un.res.bytes += skb->len;
/*
* Wrong interface: drop packet and (maybe) send PIM assert.
*/
if (net->ipv6.vif6_table[vif].dev != skb->dev) {
int true_vifi;
cache->mfc_un.res.wrong_if++;
true_vifi = ip6mr_find_vif(skb->dev);
if (true_vifi >= 0 && net->ipv6.mroute_do_assert &&
/* pimsm uses asserts, when switching from RPT to SPT,
so that we cannot check that packet arrived on an oif.
It is bad, but otherwise we would need to move pretty
large chunk of pimd to kernel. Ough... --ANK
*/
(net->ipv6.mroute_do_pim ||
cache->mfc_un.res.ttls[true_vifi] < 255) &&
time_after(jiffies,
cache->mfc_un.res.last_assert + MFC_ASSERT_THRESH)) {
cache->mfc_un.res.last_assert = jiffies;
ip6mr_cache_report(net, skb, true_vifi, MRT6MSG_WRONGMIF);
}
goto dont_forward;
}
net->ipv6.vif6_table[vif].pkt_in++;
net->ipv6.vif6_table[vif].bytes_in += skb->len;
/*
* Forward the frame
*/
for (ct = cache->mfc_un.res.maxvif - 1; ct >= cache->mfc_un.res.minvif; ct--) {
if (ipv6_hdr(skb)->hop_limit > cache->mfc_un.res.ttls[ct]) {
if (psend != -1) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2)
ip6mr_forward2(skb2, cache, psend);
}
psend = ct;
}
}
if (psend != -1) {
ip6mr_forward2(skb, cache, psend);
return 0;
}
dont_forward:
kfree_skb(skb);
return 0;
}
/*
* Multicast packets for forwarding arrive here
*/
int ip6_mr_input(struct sk_buff *skb)
{
struct mfc6_cache *cache;
struct net *net = dev_net(skb->dev);
read_lock(&mrt_lock);
cache = ip6mr_cache_find(net,
&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr);
/*
* No usable cache entry
*/
if (cache == NULL) {
int vif;
vif = ip6mr_find_vif(skb->dev);
if (vif >= 0) {
int err = ip6mr_cache_unresolved(net, vif, skb);
read_unlock(&mrt_lock);
return err;
}
read_unlock(&mrt_lock);
kfree_skb(skb);
return -ENODEV;
}
ip6_mr_forward(skb, cache);
read_unlock(&mrt_lock);
return 0;
}
static int
ip6mr_fill_mroute(struct sk_buff *skb, struct mfc6_cache *c, struct rtmsg *rtm)
{
int ct;
struct rtnexthop *nhp;
struct net *net = mfc6_net(c);
struct net_device *dev = net->ipv6.vif6_table[c->mf6c_parent].dev;
u8 *b = skb_tail_pointer(skb);
struct rtattr *mp_head;
if (dev)
RTA_PUT(skb, RTA_IIF, 4, &dev->ifindex);
mp_head = (struct rtattr *)skb_put(skb, RTA_LENGTH(0));
for (ct = c->mfc_un.res.minvif; ct < c->mfc_un.res.maxvif; ct++) {
if (c->mfc_un.res.ttls[ct] < 255) {
if (skb_tailroom(skb) < RTA_ALIGN(RTA_ALIGN(sizeof(*nhp)) + 4))
goto rtattr_failure;
nhp = (struct rtnexthop *)skb_put(skb, RTA_ALIGN(sizeof(*nhp)));
nhp->rtnh_flags = 0;
nhp->rtnh_hops = c->mfc_un.res.ttls[ct];
nhp->rtnh_ifindex = net->ipv6.vif6_table[ct].dev->ifindex;
nhp->rtnh_len = sizeof(*nhp);
}
}
mp_head->rta_type = RTA_MULTIPATH;
mp_head->rta_len = skb_tail_pointer(skb) - (u8 *)mp_head;
rtm->rtm_type = RTN_MULTICAST;
return 1;
rtattr_failure:
nlmsg_trim(skb, b);
return -EMSGSIZE;
}
int ip6mr_get_route(struct net *net,
struct sk_buff *skb, struct rtmsg *rtm, int nowait)
{
int err;
struct mfc6_cache *cache;
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
read_lock(&mrt_lock);
cache = ip6mr_cache_find(net, &rt->rt6i_src.addr, &rt->rt6i_dst.addr);
if (!cache) {
struct sk_buff *skb2;
struct ipv6hdr *iph;
struct net_device *dev;
int vif;
if (nowait) {
read_unlock(&mrt_lock);
return -EAGAIN;
}
dev = skb->dev;
if (dev == NULL || (vif = ip6mr_find_vif(dev)) < 0) {
read_unlock(&mrt_lock);
return -ENODEV;
}
/* really correct? */
skb2 = alloc_skb(sizeof(struct ipv6hdr), GFP_ATOMIC);
if (!skb2) {
read_unlock(&mrt_lock);
return -ENOMEM;
}
skb_reset_transport_header(skb2);
skb_put(skb2, sizeof(struct ipv6hdr));
skb_reset_network_header(skb2);
iph = ipv6_hdr(skb2);
iph->version = 0;
iph->priority = 0;
iph->flow_lbl[0] = 0;
iph->flow_lbl[1] = 0;
iph->flow_lbl[2] = 0;
iph->payload_len = 0;
iph->nexthdr = IPPROTO_NONE;
iph->hop_limit = 0;
ipv6_addr_copy(&iph->saddr, &rt->rt6i_src.addr);
ipv6_addr_copy(&iph->daddr, &rt->rt6i_dst.addr);
err = ip6mr_cache_unresolved(net, vif, skb2);
read_unlock(&mrt_lock);
return err;
}
if (!nowait && (rtm->rtm_flags&RTM_F_NOTIFY))
cache->mfc_flags |= MFC_NOTIFY;
err = ip6mr_fill_mroute(skb, cache, rtm);
read_unlock(&mrt_lock);
return err;
}
| gpl-2.0 |
Zenfone2-development/android_kernel_asus_moorefield | drivers/staging/iio/impedance-analyzer/ad5933.c | 719 | 20303 | /*
* AD5933 AD5934 Impedance Converter, Network Analyzer
*
* Copyright 2011 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/sysfs.h>
#include <linux/i2c.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <asm/div64.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/buffer.h>
#include <linux/iio/kfifo_buf.h>
#include "ad5933.h"
/* AD5933/AD5934 Registers */
#define AD5933_REG_CONTROL_HB 0x80 /* R/W, 2 bytes */
#define AD5933_REG_CONTROL_LB 0x81 /* R/W, 2 bytes */
#define AD5933_REG_FREQ_START 0x82 /* R/W, 3 bytes */
#define AD5933_REG_FREQ_INC 0x85 /* R/W, 3 bytes */
#define AD5933_REG_INC_NUM 0x88 /* R/W, 2 bytes, 9 bit */
#define AD5933_REG_SETTLING_CYCLES 0x8A /* R/W, 2 bytes */
#define AD5933_REG_STATUS 0x8F /* R, 1 byte */
#define AD5933_REG_TEMP_DATA 0x92 /* R, 2 bytes*/
#define AD5933_REG_REAL_DATA 0x94 /* R, 2 bytes*/
#define AD5933_REG_IMAG_DATA 0x96 /* R, 2 bytes*/
/* AD5933_REG_CONTROL_HB Bits */
#define AD5933_CTRL_INIT_START_FREQ (0x1 << 4)
#define AD5933_CTRL_START_SWEEP (0x2 << 4)
#define AD5933_CTRL_INC_FREQ (0x3 << 4)
#define AD5933_CTRL_REPEAT_FREQ (0x4 << 4)
#define AD5933_CTRL_MEASURE_TEMP (0x9 << 4)
#define AD5933_CTRL_POWER_DOWN (0xA << 4)
#define AD5933_CTRL_STANDBY (0xB << 4)
#define AD5933_CTRL_RANGE_2000mVpp (0x0 << 1)
#define AD5933_CTRL_RANGE_200mVpp (0x1 << 1)
#define AD5933_CTRL_RANGE_400mVpp (0x2 << 1)
#define AD5933_CTRL_RANGE_1000mVpp (0x3 << 1)
#define AD5933_CTRL_RANGE(x) ((x) << 1)
#define AD5933_CTRL_PGA_GAIN_1 (0x1 << 0)
#define AD5933_CTRL_PGA_GAIN_5 (0x0 << 0)
/* AD5933_REG_CONTROL_LB Bits */
#define AD5933_CTRL_RESET (0x1 << 4)
#define AD5933_CTRL_INT_SYSCLK (0x0 << 3)
#define AD5933_CTRL_EXT_SYSCLK (0x1 << 3)
/* AD5933_REG_STATUS Bits */
#define AD5933_STAT_TEMP_VALID (0x1 << 0)
#define AD5933_STAT_DATA_VALID (0x1 << 1)
#define AD5933_STAT_SWEEP_DONE (0x1 << 2)
/* I2C Block Commands */
#define AD5933_I2C_BLOCK_WRITE 0xA0
#define AD5933_I2C_BLOCK_READ 0xA1
#define AD5933_I2C_ADDR_POINTER 0xB0
/* Device Specs */
#define AD5933_INT_OSC_FREQ_Hz 16776000
#define AD5933_MAX_OUTPUT_FREQ_Hz 100000
#define AD5933_MAX_RETRIES 100
#define AD5933_OUT_RANGE 1
#define AD5933_OUT_RANGE_AVAIL 2
#define AD5933_OUT_SETTLING_CYCLES 3
#define AD5933_IN_PGA_GAIN 4
#define AD5933_IN_PGA_GAIN_AVAIL 5
#define AD5933_FREQ_POINTS 6
#define AD5933_POLL_TIME_ms 10
#define AD5933_INIT_EXCITATION_TIME_ms 100
struct ad5933_state {
struct i2c_client *client;
struct regulator *reg;
struct ad5933_platform_data *pdata;
struct delayed_work work;
unsigned long mclk_hz;
unsigned char ctrl_hb;
unsigned char ctrl_lb;
unsigned range_avail[4];
unsigned short vref_mv;
unsigned short settling_cycles;
unsigned short freq_points;
unsigned freq_start;
unsigned freq_inc;
unsigned state;
unsigned poll_time_jiffies;
};
static struct ad5933_platform_data ad5933_default_pdata = {
.vref_mv = 3300,
};
static const struct iio_chan_spec ad5933_channels[] = {
{
.type = IIO_TEMP,
.indexed = 1,
.channel = 0,
.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
.address = AD5933_REG_TEMP_DATA,
.scan_index = -1,
.scan_type = {
.sign = 's',
.realbits = 14,
.storagebits = 16,
},
}, { /* Ring Channels */
.type = IIO_VOLTAGE,
.indexed = 1,
.channel = 0,
.extend_name = "real",
.address = AD5933_REG_REAL_DATA,
.scan_index = 0,
.scan_type = {
.sign = 's',
.realbits = 16,
.storagebits = 16,
},
}, {
.type = IIO_VOLTAGE,
.indexed = 1,
.channel = 0,
.extend_name = "imag",
.address = AD5933_REG_IMAG_DATA,
.scan_index = 1,
.scan_type = {
.sign = 's',
.realbits = 16,
.storagebits = 16,
},
},
};
static int ad5933_i2c_write(struct i2c_client *client,
u8 reg, u8 len, u8 *data)
{
int ret;
while (len--) {
ret = i2c_smbus_write_byte_data(client, reg++, *data++);
if (ret < 0) {
dev_err(&client->dev, "I2C write error\n");
return ret;
}
}
return 0;
}
static int ad5933_i2c_read(struct i2c_client *client,
u8 reg, u8 len, u8 *data)
{
int ret;
while (len--) {
ret = i2c_smbus_read_byte_data(client, reg++);
if (ret < 0) {
dev_err(&client->dev, "I2C read error\n");
return ret;
}
*data++ = ret;
}
return 0;
}
static int ad5933_cmd(struct ad5933_state *st, unsigned char cmd)
{
unsigned char dat = st->ctrl_hb | cmd;
return ad5933_i2c_write(st->client,
AD5933_REG_CONTROL_HB, 1, &dat);
}
static int ad5933_reset(struct ad5933_state *st)
{
unsigned char dat = st->ctrl_lb | AD5933_CTRL_RESET;
return ad5933_i2c_write(st->client,
AD5933_REG_CONTROL_LB, 1, &dat);
}
static int ad5933_wait_busy(struct ad5933_state *st, unsigned char event)
{
unsigned char val, timeout = AD5933_MAX_RETRIES;
int ret;
while (timeout--) {
ret = ad5933_i2c_read(st->client, AD5933_REG_STATUS, 1, &val);
if (ret < 0)
return ret;
if (val & event)
return val;
cpu_relax();
mdelay(1);
}
return -EAGAIN;
}
static int ad5933_set_freq(struct ad5933_state *st,
unsigned reg, unsigned long freq)
{
unsigned long long freqreg;
union {
u32 d32;
u8 d8[4];
} dat;
freqreg = (u64) freq * (u64) (1 << 27);
do_div(freqreg, st->mclk_hz / 4);
switch (reg) {
case AD5933_REG_FREQ_START:
st->freq_start = freq;
break;
case AD5933_REG_FREQ_INC:
st->freq_inc = freq;
break;
default:
return -EINVAL;
}
dat.d32 = cpu_to_be32(freqreg);
return ad5933_i2c_write(st->client, reg, 3, &dat.d8[1]);
}
static int ad5933_setup(struct ad5933_state *st)
{
unsigned short dat;
int ret;
ret = ad5933_reset(st);
if (ret < 0)
return ret;
ret = ad5933_set_freq(st, AD5933_REG_FREQ_START, 10000);
if (ret < 0)
return ret;
ret = ad5933_set_freq(st, AD5933_REG_FREQ_INC, 200);
if (ret < 0)
return ret;
st->settling_cycles = 10;
dat = cpu_to_be16(st->settling_cycles);
ret = ad5933_i2c_write(st->client,
AD5933_REG_SETTLING_CYCLES, 2, (u8 *)&dat);
if (ret < 0)
return ret;
st->freq_points = 100;
dat = cpu_to_be16(st->freq_points);
return ad5933_i2c_write(st->client, AD5933_REG_INC_NUM, 2, (u8 *)&dat);
}
static void ad5933_calc_out_ranges(struct ad5933_state *st)
{
int i;
unsigned normalized_3v3[4] = {1980, 198, 383, 970};
for (i = 0; i < 4; i++)
st->range_avail[i] = normalized_3v3[i] * st->vref_mv / 3300;
}
/*
* handles: AD5933_REG_FREQ_START and AD5933_REG_FREQ_INC
*/
static ssize_t ad5933_show_frequency(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ad5933_state *st = iio_priv(indio_dev);
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
int ret;
unsigned long long freqreg;
union {
u32 d32;
u8 d8[4];
} dat;
mutex_lock(&indio_dev->mlock);
ret = ad5933_i2c_read(st->client, this_attr->address, 3, &dat.d8[1]);
mutex_unlock(&indio_dev->mlock);
if (ret < 0)
return ret;
freqreg = be32_to_cpu(dat.d32) & 0xFFFFFF;
freqreg = (u64) freqreg * (u64) (st->mclk_hz / 4);
do_div(freqreg, 1 << 27);
return sprintf(buf, "%d\n", (int) freqreg);
}
static ssize_t ad5933_store_frequency(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ad5933_state *st = iio_priv(indio_dev);
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
long val;
int ret;
ret = strict_strtoul(buf, 10, &val);
if (ret)
return ret;
if (val > AD5933_MAX_OUTPUT_FREQ_Hz)
return -EINVAL;
mutex_lock(&indio_dev->mlock);
ret = ad5933_set_freq(st, this_attr->address, val);
mutex_unlock(&indio_dev->mlock);
return ret ? ret : len;
}
static IIO_DEVICE_ATTR(out_voltage0_freq_start, S_IRUGO | S_IWUSR,
ad5933_show_frequency,
ad5933_store_frequency,
AD5933_REG_FREQ_START);
static IIO_DEVICE_ATTR(out_voltage0_freq_increment, S_IRUGO | S_IWUSR,
ad5933_show_frequency,
ad5933_store_frequency,
AD5933_REG_FREQ_INC);
static ssize_t ad5933_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ad5933_state *st = iio_priv(indio_dev);
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
int ret = 0, len = 0;
mutex_lock(&indio_dev->mlock);
switch ((u32) this_attr->address) {
case AD5933_OUT_RANGE:
len = sprintf(buf, "%d\n",
st->range_avail[(st->ctrl_hb >> 1) & 0x3]);
break;
case AD5933_OUT_RANGE_AVAIL:
len = sprintf(buf, "%d %d %d %d\n", st->range_avail[0],
st->range_avail[3], st->range_avail[2],
st->range_avail[1]);
break;
case AD5933_OUT_SETTLING_CYCLES:
len = sprintf(buf, "%d\n", st->settling_cycles);
break;
case AD5933_IN_PGA_GAIN:
len = sprintf(buf, "%s\n",
(st->ctrl_hb & AD5933_CTRL_PGA_GAIN_1) ?
"1" : "0.2");
break;
case AD5933_IN_PGA_GAIN_AVAIL:
len = sprintf(buf, "1 0.2\n");
break;
case AD5933_FREQ_POINTS:
len = sprintf(buf, "%d\n", st->freq_points);
break;
default:
ret = -EINVAL;
}
mutex_unlock(&indio_dev->mlock);
return ret ? ret : len;
}
static ssize_t ad5933_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ad5933_state *st = iio_priv(indio_dev);
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
long val;
int i, ret = 0;
unsigned short dat;
if (this_attr->address != AD5933_IN_PGA_GAIN) {
ret = strict_strtol(buf, 10, &val);
if (ret)
return ret;
}
mutex_lock(&indio_dev->mlock);
switch ((u32) this_attr->address) {
case AD5933_OUT_RANGE:
for (i = 0; i < 4; i++)
if (val == st->range_avail[i]) {
st->ctrl_hb &= ~AD5933_CTRL_RANGE(0x3);
st->ctrl_hb |= AD5933_CTRL_RANGE(i);
ret = ad5933_cmd(st, 0);
break;
}
ret = -EINVAL;
break;
case AD5933_IN_PGA_GAIN:
if (sysfs_streq(buf, "1")) {
st->ctrl_hb |= AD5933_CTRL_PGA_GAIN_1;
} else if (sysfs_streq(buf, "0.2")) {
st->ctrl_hb &= ~AD5933_CTRL_PGA_GAIN_1;
} else {
ret = -EINVAL;
break;
}
ret = ad5933_cmd(st, 0);
break;
case AD5933_OUT_SETTLING_CYCLES:
val = clamp(val, 0L, 0x7FFL);
st->settling_cycles = val;
/* 2x, 4x handling, see datasheet */
if (val > 511)
val = (val >> 1) | (1 << 9);
else if (val > 1022)
val = (val >> 2) | (3 << 9);
dat = cpu_to_be16(val);
ret = ad5933_i2c_write(st->client,
AD5933_REG_SETTLING_CYCLES, 2, (u8 *)&dat);
break;
case AD5933_FREQ_POINTS:
val = clamp(val, 0L, 511L);
st->freq_points = val;
dat = cpu_to_be16(val);
ret = ad5933_i2c_write(st->client, AD5933_REG_INC_NUM, 2,
(u8 *)&dat);
break;
default:
ret = -EINVAL;
}
mutex_unlock(&indio_dev->mlock);
return ret ? ret : len;
}
static IIO_DEVICE_ATTR(out_voltage0_scale, S_IRUGO | S_IWUSR,
ad5933_show,
ad5933_store,
AD5933_OUT_RANGE);
static IIO_DEVICE_ATTR(out_voltage0_scale_available, S_IRUGO,
ad5933_show,
NULL,
AD5933_OUT_RANGE_AVAIL);
static IIO_DEVICE_ATTR(in_voltage0_scale, S_IRUGO | S_IWUSR,
ad5933_show,
ad5933_store,
AD5933_IN_PGA_GAIN);
static IIO_DEVICE_ATTR(in_voltage0_scale_available, S_IRUGO,
ad5933_show,
NULL,
AD5933_IN_PGA_GAIN_AVAIL);
static IIO_DEVICE_ATTR(out_voltage0_freq_points, S_IRUGO | S_IWUSR,
ad5933_show,
ad5933_store,
AD5933_FREQ_POINTS);
static IIO_DEVICE_ATTR(out_voltage0_settling_cycles, S_IRUGO | S_IWUSR,
ad5933_show,
ad5933_store,
AD5933_OUT_SETTLING_CYCLES);
/* note:
* ideally we would handle the scale attributes via the iio_info
* (read|write)_raw methods, however this part is a untypical since we
* don't create dedicated sysfs channel attributes for out0 and in0.
*/
static struct attribute *ad5933_attributes[] = {
&iio_dev_attr_out_voltage0_scale.dev_attr.attr,
&iio_dev_attr_out_voltage0_scale_available.dev_attr.attr,
&iio_dev_attr_out_voltage0_freq_start.dev_attr.attr,
&iio_dev_attr_out_voltage0_freq_increment.dev_attr.attr,
&iio_dev_attr_out_voltage0_freq_points.dev_attr.attr,
&iio_dev_attr_out_voltage0_settling_cycles.dev_attr.attr,
&iio_dev_attr_in_voltage0_scale.dev_attr.attr,
&iio_dev_attr_in_voltage0_scale_available.dev_attr.attr,
NULL
};
static const struct attribute_group ad5933_attribute_group = {
.attrs = ad5933_attributes,
};
static int ad5933_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val,
int *val2,
long m)
{
struct ad5933_state *st = iio_priv(indio_dev);
unsigned short dat;
int ret = -EINVAL;
mutex_lock(&indio_dev->mlock);
switch (m) {
case IIO_CHAN_INFO_RAW:
case IIO_CHAN_INFO_PROCESSED:
if (iio_buffer_enabled(indio_dev)) {
ret = -EBUSY;
goto out;
}
ret = ad5933_cmd(st, AD5933_CTRL_MEASURE_TEMP);
if (ret < 0)
goto out;
ret = ad5933_wait_busy(st, AD5933_STAT_TEMP_VALID);
if (ret < 0)
goto out;
ret = ad5933_i2c_read(st->client,
AD5933_REG_TEMP_DATA, 2,
(u8 *)&dat);
if (ret < 0)
goto out;
mutex_unlock(&indio_dev->mlock);
ret = be16_to_cpu(dat);
/* Temp in Milli degrees Celsius */
if (ret < 8192)
*val = ret * 1000 / 32;
else
*val = (ret - 16384) * 1000 / 32;
return IIO_VAL_INT;
}
out:
mutex_unlock(&indio_dev->mlock);
return ret;
}
static const struct iio_info ad5933_info = {
.read_raw = &ad5933_read_raw,
.attrs = &ad5933_attribute_group,
.driver_module = THIS_MODULE,
};
static int ad5933_ring_preenable(struct iio_dev *indio_dev)
{
struct ad5933_state *st = iio_priv(indio_dev);
int ret;
if (bitmap_empty(indio_dev->active_scan_mask, indio_dev->masklength))
return -EINVAL;
ret = iio_sw_buffer_preenable(indio_dev);
if (ret < 0)
return ret;
ret = ad5933_reset(st);
if (ret < 0)
return ret;
ret = ad5933_cmd(st, AD5933_CTRL_STANDBY);
if (ret < 0)
return ret;
ret = ad5933_cmd(st, AD5933_CTRL_INIT_START_FREQ);
if (ret < 0)
return ret;
st->state = AD5933_CTRL_INIT_START_FREQ;
return 0;
}
static int ad5933_ring_postenable(struct iio_dev *indio_dev)
{
struct ad5933_state *st = iio_priv(indio_dev);
/* AD5933_CTRL_INIT_START_FREQ:
* High Q complex circuits require a long time to reach steady state.
* To facilitate the measurement of such impedances, this mode allows
* the user full control of the settling time requirement before
* entering start frequency sweep mode where the impedance measurement
* takes place. In this mode the impedance is excited with the
* programmed start frequency (ad5933_ring_preenable),
* but no measurement takes place.
*/
schedule_delayed_work(&st->work,
msecs_to_jiffies(AD5933_INIT_EXCITATION_TIME_ms));
return 0;
}
static int ad5933_ring_postdisable(struct iio_dev *indio_dev)
{
struct ad5933_state *st = iio_priv(indio_dev);
cancel_delayed_work_sync(&st->work);
return ad5933_cmd(st, AD5933_CTRL_POWER_DOWN);
}
static const struct iio_buffer_setup_ops ad5933_ring_setup_ops = {
.preenable = &ad5933_ring_preenable,
.postenable = &ad5933_ring_postenable,
.postdisable = &ad5933_ring_postdisable,
};
static int ad5933_register_ring_funcs_and_init(struct iio_dev *indio_dev)
{
indio_dev->buffer = iio_kfifo_allocate(indio_dev);
if (!indio_dev->buffer)
return -ENOMEM;
/* Ring buffer functions - here trigger setup related */
indio_dev->setup_ops = &ad5933_ring_setup_ops;
indio_dev->modes |= INDIO_BUFFER_HARDWARE;
return 0;
}
static void ad5933_work(struct work_struct *work)
{
struct ad5933_state *st = container_of(work,
struct ad5933_state, work.work);
struct iio_dev *indio_dev = i2c_get_clientdata(st->client);
signed short buf[2];
unsigned char status;
mutex_lock(&indio_dev->mlock);
if (st->state == AD5933_CTRL_INIT_START_FREQ) {
/* start sweep */
ad5933_cmd(st, AD5933_CTRL_START_SWEEP);
st->state = AD5933_CTRL_START_SWEEP;
schedule_delayed_work(&st->work, st->poll_time_jiffies);
mutex_unlock(&indio_dev->mlock);
return;
}
ad5933_i2c_read(st->client, AD5933_REG_STATUS, 1, &status);
if (status & AD5933_STAT_DATA_VALID) {
int scan_count = bitmap_weight(indio_dev->active_scan_mask,
indio_dev->masklength);
ad5933_i2c_read(st->client,
test_bit(1, indio_dev->active_scan_mask) ?
AD5933_REG_REAL_DATA : AD5933_REG_IMAG_DATA,
scan_count * 2, (u8 *)buf);
if (scan_count == 2) {
buf[0] = be16_to_cpu(buf[0]);
buf[1] = be16_to_cpu(buf[1]);
} else {
buf[0] = be16_to_cpu(buf[0]);
}
iio_push_to_buffers(indio_dev, (u8 *)buf);
} else {
/* no data available - try again later */
schedule_delayed_work(&st->work, st->poll_time_jiffies);
mutex_unlock(&indio_dev->mlock);
return;
}
if (status & AD5933_STAT_SWEEP_DONE) {
/* last sample received - power down do nothing until
* the ring enable is toggled */
ad5933_cmd(st, AD5933_CTRL_POWER_DOWN);
} else {
/* we just received a valid datum, move on to the next */
ad5933_cmd(st, AD5933_CTRL_INC_FREQ);
schedule_delayed_work(&st->work, st->poll_time_jiffies);
}
mutex_unlock(&indio_dev->mlock);
}
static int ad5933_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret, voltage_uv = 0;
struct ad5933_platform_data *pdata = client->dev.platform_data;
struct ad5933_state *st;
struct iio_dev *indio_dev = iio_device_alloc(sizeof(*st));
if (indio_dev == NULL)
return -ENOMEM;
st = iio_priv(indio_dev);
i2c_set_clientdata(client, indio_dev);
st->client = client;
if (!pdata)
st->pdata = &ad5933_default_pdata;
else
st->pdata = pdata;
st->reg = regulator_get(&client->dev, "vcc");
if (!IS_ERR(st->reg)) {
ret = regulator_enable(st->reg);
if (ret)
goto error_put_reg;
voltage_uv = regulator_get_voltage(st->reg);
}
if (voltage_uv)
st->vref_mv = voltage_uv / 1000;
else
st->vref_mv = st->pdata->vref_mv;
if (st->pdata->ext_clk_Hz) {
st->mclk_hz = st->pdata->ext_clk_Hz;
st->ctrl_lb = AD5933_CTRL_EXT_SYSCLK;
} else {
st->mclk_hz = AD5933_INT_OSC_FREQ_Hz;
st->ctrl_lb = AD5933_CTRL_INT_SYSCLK;
}
ad5933_calc_out_ranges(st);
INIT_DELAYED_WORK(&st->work, ad5933_work);
st->poll_time_jiffies = msecs_to_jiffies(AD5933_POLL_TIME_ms);
indio_dev->dev.parent = &client->dev;
indio_dev->info = &ad5933_info;
indio_dev->name = id->name;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->channels = ad5933_channels;
indio_dev->num_channels = ARRAY_SIZE(ad5933_channels);
ret = ad5933_register_ring_funcs_and_init(indio_dev);
if (ret)
goto error_disable_reg;
ret = iio_buffer_register(indio_dev, ad5933_channels,
ARRAY_SIZE(ad5933_channels));
if (ret)
goto error_unreg_ring;
/* enable both REAL and IMAG channels by default */
iio_scan_mask_set(indio_dev, indio_dev->buffer, 0);
iio_scan_mask_set(indio_dev, indio_dev->buffer, 1);
ret = ad5933_setup(st);
if (ret)
goto error_uninitialize_ring;
ret = iio_device_register(indio_dev);
if (ret)
goto error_uninitialize_ring;
return 0;
error_uninitialize_ring:
iio_buffer_unregister(indio_dev);
error_unreg_ring:
iio_kfifo_free(indio_dev->buffer);
error_disable_reg:
if (!IS_ERR(st->reg))
regulator_disable(st->reg);
error_put_reg:
if (!IS_ERR(st->reg))
regulator_put(st->reg);
iio_device_free(indio_dev);
return ret;
}
static int ad5933_remove(struct i2c_client *client)
{
struct iio_dev *indio_dev = i2c_get_clientdata(client);
struct ad5933_state *st = iio_priv(indio_dev);
iio_device_unregister(indio_dev);
iio_buffer_unregister(indio_dev);
iio_kfifo_free(indio_dev->buffer);
if (!IS_ERR(st->reg)) {
regulator_disable(st->reg);
regulator_put(st->reg);
}
iio_device_free(indio_dev);
return 0;
}
static const struct i2c_device_id ad5933_id[] = {
{ "ad5933", 0 },
{ "ad5934", 0 },
{}
};
MODULE_DEVICE_TABLE(i2c, ad5933_id);
static struct i2c_driver ad5933_driver = {
.driver = {
.name = "ad5933",
},
.probe = ad5933_probe,
.remove = ad5933_remove,
.id_table = ad5933_id,
};
module_i2c_driver(ad5933_driver);
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Analog Devices AD5933 Impedance Conv. Network Analyzer");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
lp0/linux | drivers/gpu/drm/nouveau/nvkm/engine/disp/gt215.c | 719 | 2133 | /*
* Copyright 2012 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "nv50.h"
#include "rootnv50.h"
static const struct nv50_disp_func
gt215_disp = {
.intr = nv50_disp_intr,
.uevent = &nv50_disp_chan_uevent,
.super = nv50_disp_intr_supervisor,
.root = >215_disp_root_oclass,
.head.vblank_init = nv50_disp_vblank_init,
.head.vblank_fini = nv50_disp_vblank_fini,
.head.scanoutpos = nv50_disp_root_scanoutpos,
.outp.internal.crt = nv50_dac_output_new,
.outp.internal.tmds = nv50_sor_output_new,
.outp.internal.lvds = nv50_sor_output_new,
.outp.internal.dp = g94_sor_dp_new,
.outp.external.tmds = nv50_pior_output_new,
.outp.external.dp = nv50_pior_dp_new,
.dac.nr = 3,
.dac.power = nv50_dac_power,
.dac.sense = nv50_dac_sense,
.sor.nr = 4,
.sor.power = nv50_sor_power,
.sor.hda_eld = gt215_hda_eld,
.sor.hdmi = gt215_hdmi_ctrl,
.pior.nr = 3,
.pior.power = nv50_pior_power,
};
int
gt215_disp_new(struct nvkm_device *device, int index, struct nvkm_disp **pdisp)
{
return nv50_disp_new_(>215_disp, device, index, 2, pdisp);
}
| gpl-2.0 |
loli10K/linux-hardkernel | drivers/base/regmap/regcache-flat.c | 975 | 1477 | /*
* Register cache access API - flat caching support
*
* 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/seq_file.h>
#include <linux/slab.h>
#include "internal.h"
static int regcache_flat_init(struct regmap *map)
{
int i;
unsigned int *cache;
map->cache = kzalloc(sizeof(unsigned int) * (map->max_register + 1),
GFP_KERNEL);
if (!map->cache)
return -ENOMEM;
cache = map->cache;
for (i = 0; i < map->num_reg_defaults; i++)
cache[map->reg_defaults[i].reg] = map->reg_defaults[i].def;
return 0;
}
static int regcache_flat_exit(struct regmap *map)
{
kfree(map->cache);
map->cache = NULL;
return 0;
}
static int regcache_flat_read(struct regmap *map,
unsigned int reg, unsigned int *value)
{
unsigned int *cache = map->cache;
*value = cache[reg];
return 0;
}
static int regcache_flat_write(struct regmap *map, unsigned int reg,
unsigned int value)
{
unsigned int *cache = map->cache;
cache[reg] = value;
return 0;
}
struct regcache_ops regcache_flat_ops = {
.type = REGCACHE_FLAT,
.name = "flat",
.init = regcache_flat_init,
.exit = regcache_flat_exit,
.read = regcache_flat_read,
.write = regcache_flat_write,
};
| gpl-2.0 |
hroark13/Warp_Kernel-Jellybean | arch/x86/mm/memtest.c | 1487 | 3064 | #include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/pfn.h>
#include <asm/e820.h>
static u64 patterns[] __initdata = {
0,
0xffffffffffffffffULL,
0x5555555555555555ULL,
0xaaaaaaaaaaaaaaaaULL,
0x1111111111111111ULL,
0x2222222222222222ULL,
0x4444444444444444ULL,
0x8888888888888888ULL,
0x3333333333333333ULL,
0x6666666666666666ULL,
0x9999999999999999ULL,
0xccccccccccccccccULL,
0x7777777777777777ULL,
0xbbbbbbbbbbbbbbbbULL,
0xddddddddddddddddULL,
0xeeeeeeeeeeeeeeeeULL,
0x7a6c7258554e494cULL, /* yeah ;-) */
};
static void __init reserve_bad_mem(u64 pattern, u64 start_bad, u64 end_bad)
{
printk(KERN_INFO " %016llx bad mem addr %010llx - %010llx reserved\n",
(unsigned long long) pattern,
(unsigned long long) start_bad,
(unsigned long long) end_bad);
reserve_early(start_bad, end_bad, "BAD RAM");
}
static void __init memtest(u64 pattern, u64 start_phys, u64 size)
{
u64 *p, *start, *end;
u64 start_bad, last_bad;
u64 start_phys_aligned;
const size_t incr = sizeof(pattern);
start_phys_aligned = ALIGN(start_phys, incr);
start = __va(start_phys_aligned);
end = start + (size - (start_phys_aligned - start_phys)) / incr;
start_bad = 0;
last_bad = 0;
for (p = start; p < end; p++)
*p = pattern;
for (p = start; p < end; p++, start_phys_aligned += incr) {
if (*p == pattern)
continue;
if (start_phys_aligned == last_bad + incr) {
last_bad += incr;
continue;
}
if (start_bad)
reserve_bad_mem(pattern, start_bad, last_bad + incr);
start_bad = last_bad = start_phys_aligned;
}
if (start_bad)
reserve_bad_mem(pattern, start_bad, last_bad + incr);
}
static void __init do_one_pass(u64 pattern, u64 start, u64 end)
{
u64 size = 0;
while (start < end) {
start = find_e820_area_size(start, &size, 1);
/* done ? */
if (start >= end)
break;
if (start + size > end)
size = end - start;
printk(KERN_INFO " %010llx - %010llx pattern %016llx\n",
(unsigned long long) start,
(unsigned long long) start + size,
(unsigned long long) cpu_to_be64(pattern));
memtest(pattern, start, size);
start += size;
}
}
/* default is disabled */
static int memtest_pattern __initdata;
static int __init parse_memtest(char *arg)
{
if (arg)
memtest_pattern = simple_strtoul(arg, NULL, 0);
else
memtest_pattern = ARRAY_SIZE(patterns);
return 0;
}
early_param("memtest", parse_memtest);
void __init early_memtest(unsigned long start, unsigned long end)
{
unsigned int i;
unsigned int idx = 0;
if (!memtest_pattern)
return;
printk(KERN_INFO "early_memtest: # of tests: %d\n", memtest_pattern);
for (i = 0; i < memtest_pattern; i++) {
idx = i % ARRAY_SIZE(patterns);
do_one_pass(patterns[idx], start, end);
}
if (idx > 0) {
printk(KERN_INFO "early_memtest: wipe out "
"test pattern from memory\n");
/* additional test with pattern 0 will do this */
do_one_pass(0, start, end);
}
}
| gpl-2.0 |
ftCommunity/ft-TXT | board/knobloch/TXT/board-support/ti-linux/drivers/net/ethernet/chelsio/cxgb/pm3393.c | 1743 | 30258 | /*****************************************************************************
* *
* File: pm3393.c *
* $Revision: 1.16 $ *
* $Date: 2005/05/14 00:59:32 $ *
* Description: *
* PMC/SIERRA (pm3393) MAC-PHY functionality. *
* part of the Chelsio 10Gb Ethernet Driver. *
* *
* 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. *
* *
* 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 SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *
* *
* http://www.chelsio.com *
* *
* Copyright (c) 2003 - 2005 Chelsio Communications, Inc. *
* All rights reserved. *
* *
* Maintainers: maintainers@chelsio.com *
* *
* Authors: Dimitrios Michailidis <dm@chelsio.com> *
* Tina Yang <tainay@chelsio.com> *
* Felix Marti <felix@chelsio.com> *
* Scott Bardone <sbardone@chelsio.com> *
* Kurt Ottaway <kottaway@chelsio.com> *
* Frank DiMambro <frank@chelsio.com> *
* *
* History: *
* *
****************************************************************************/
#include "common.h"
#include "regs.h"
#include "gmac.h"
#include "elmer0.h"
#include "suni1x10gexp_regs.h"
#include <linux/crc32.h>
#include <linux/slab.h>
#define OFFSET(REG_ADDR) ((REG_ADDR) << 2)
/* Max frame size PM3393 can handle. Includes Ethernet header and CRC. */
#define MAX_FRAME_SIZE 9600
#define IPG 12
#define TXXG_CONF1_VAL ((IPG << SUNI1x10GEXP_BITOFF_TXXG_IPGT) | \
SUNI1x10GEXP_BITMSK_TXXG_32BIT_ALIGN | SUNI1x10GEXP_BITMSK_TXXG_CRCEN | \
SUNI1x10GEXP_BITMSK_TXXG_PADEN)
#define RXXG_CONF1_VAL (SUNI1x10GEXP_BITMSK_RXXG_PUREP | 0x14 | \
SUNI1x10GEXP_BITMSK_RXXG_FLCHK | SUNI1x10GEXP_BITMSK_RXXG_CRC_STRIP)
/* Update statistics every 15 minutes */
#define STATS_TICK_SECS (15 * 60)
enum { /* RMON registers */
RxOctetsReceivedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_1_LOW,
RxUnicastFramesReceivedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_4_LOW,
RxMulticastFramesReceivedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_5_LOW,
RxBroadcastFramesReceivedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_6_LOW,
RxPAUSEMACCtrlFramesReceived = SUNI1x10GEXP_REG_MSTAT_COUNTER_8_LOW,
RxFrameCheckSequenceErrors = SUNI1x10GEXP_REG_MSTAT_COUNTER_10_LOW,
RxFramesLostDueToInternalMACErrors = SUNI1x10GEXP_REG_MSTAT_COUNTER_11_LOW,
RxSymbolErrors = SUNI1x10GEXP_REG_MSTAT_COUNTER_12_LOW,
RxInRangeLengthErrors = SUNI1x10GEXP_REG_MSTAT_COUNTER_13_LOW,
RxFramesTooLongErrors = SUNI1x10GEXP_REG_MSTAT_COUNTER_15_LOW,
RxJabbers = SUNI1x10GEXP_REG_MSTAT_COUNTER_16_LOW,
RxFragments = SUNI1x10GEXP_REG_MSTAT_COUNTER_17_LOW,
RxUndersizedFrames = SUNI1x10GEXP_REG_MSTAT_COUNTER_18_LOW,
RxJumboFramesReceivedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_25_LOW,
RxJumboOctetsReceivedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_26_LOW,
TxOctetsTransmittedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_33_LOW,
TxFramesLostDueToInternalMACTransmissionError = SUNI1x10GEXP_REG_MSTAT_COUNTER_35_LOW,
TxTransmitSystemError = SUNI1x10GEXP_REG_MSTAT_COUNTER_36_LOW,
TxUnicastFramesTransmittedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_38_LOW,
TxMulticastFramesTransmittedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_40_LOW,
TxBroadcastFramesTransmittedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_42_LOW,
TxPAUSEMACCtrlFramesTransmitted = SUNI1x10GEXP_REG_MSTAT_COUNTER_43_LOW,
TxJumboFramesReceivedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_51_LOW,
TxJumboOctetsReceivedOK = SUNI1x10GEXP_REG_MSTAT_COUNTER_52_LOW
};
struct _cmac_instance {
u8 enabled;
u8 fc;
u8 mac_addr[6];
};
static int pmread(struct cmac *cmac, u32 reg, u32 * data32)
{
t1_tpi_read(cmac->adapter, OFFSET(reg), data32);
return 0;
}
static int pmwrite(struct cmac *cmac, u32 reg, u32 data32)
{
t1_tpi_write(cmac->adapter, OFFSET(reg), data32);
return 0;
}
/* Port reset. */
static int pm3393_reset(struct cmac *cmac)
{
return 0;
}
/*
* Enable interrupts for the PM3393
*
* 1. Enable PM3393 BLOCK interrupts.
* 2. Enable PM3393 Master Interrupt bit(INTE)
* 3. Enable ELMER's PM3393 bit.
* 4. Enable Terminator external interrupt.
*/
static int pm3393_interrupt_enable(struct cmac *cmac)
{
u32 pl_intr;
/* PM3393 - Enabling all hardware block interrupts.
*/
pmwrite(cmac, SUNI1x10GEXP_REG_SERDES_3125_INTERRUPT_ENABLE, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_XRF_INTERRUPT_ENABLE, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_XRF_DIAG_INTERRUPT_ENABLE, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_RXOAM_INTERRUPT_ENABLE, 0xffff);
/* Don't interrupt on statistics overflow, we are polling */
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_INTERRUPT_MASK_0, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_INTERRUPT_MASK_1, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_INTERRUPT_MASK_2, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_INTERRUPT_MASK_3, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_IFLX_FIFO_OVERFLOW_ENABLE, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_PL4ODP_INTERRUPT_MASK, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_XTEF_INTERRUPT_ENABLE, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_TXOAM_INTERRUPT_ENABLE, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_CONFIG_3, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_PL4IO_LOCK_DETECT_MASK, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_TXXG_CONFIG_3, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_PL4IDU_INTERRUPT_MASK, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_EFLX_FIFO_OVERFLOW_ERROR_ENABLE, 0xffff);
/* PM3393 - Global interrupt enable
*/
/* TBD XXX Disable for now until we figure out why error interrupts keep asserting. */
pmwrite(cmac, SUNI1x10GEXP_REG_GLOBAL_INTERRUPT_ENABLE,
0 /*SUNI1x10GEXP_BITMSK_TOP_INTE */ );
/* TERMINATOR - PL_INTERUPTS_EXT */
pl_intr = readl(cmac->adapter->regs + A_PL_ENABLE);
pl_intr |= F_PL_INTR_EXT;
writel(pl_intr, cmac->adapter->regs + A_PL_ENABLE);
return 0;
}
static int pm3393_interrupt_disable(struct cmac *cmac)
{
u32 elmer;
/* PM3393 - Enabling HW interrupt blocks. */
pmwrite(cmac, SUNI1x10GEXP_REG_SERDES_3125_INTERRUPT_ENABLE, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_XRF_INTERRUPT_ENABLE, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_XRF_DIAG_INTERRUPT_ENABLE, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_RXOAM_INTERRUPT_ENABLE, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_INTERRUPT_MASK_0, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_INTERRUPT_MASK_1, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_INTERRUPT_MASK_2, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_INTERRUPT_MASK_3, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_IFLX_FIFO_OVERFLOW_ENABLE, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_PL4ODP_INTERRUPT_MASK, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_XTEF_INTERRUPT_ENABLE, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_TXOAM_INTERRUPT_ENABLE, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_CONFIG_3, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_PL4IO_LOCK_DETECT_MASK, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_TXXG_CONFIG_3, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_PL4IDU_INTERRUPT_MASK, 0);
pmwrite(cmac, SUNI1x10GEXP_REG_EFLX_FIFO_OVERFLOW_ERROR_ENABLE, 0);
/* PM3393 - Global interrupt enable */
pmwrite(cmac, SUNI1x10GEXP_REG_GLOBAL_INTERRUPT_ENABLE, 0);
/* ELMER - External chip interrupts. */
t1_tpi_read(cmac->adapter, A_ELMER0_INT_ENABLE, &elmer);
elmer &= ~ELMER0_GP_BIT1;
t1_tpi_write(cmac->adapter, A_ELMER0_INT_ENABLE, elmer);
/* TERMINATOR - PL_INTERUPTS_EXT */
/* DO NOT DISABLE TERMINATOR's EXTERNAL INTERRUPTS. ANOTHER CHIP
* COULD WANT THEM ENABLED. We disable PM3393 at the ELMER level.
*/
return 0;
}
static int pm3393_interrupt_clear(struct cmac *cmac)
{
u32 elmer;
u32 pl_intr;
u32 val32;
/* PM3393 - Clearing HW interrupt blocks. Note, this assumes
* bit WCIMODE=0 for a clear-on-read.
*/
pmread(cmac, SUNI1x10GEXP_REG_SERDES_3125_INTERRUPT_STATUS, &val32);
pmread(cmac, SUNI1x10GEXP_REG_XRF_INTERRUPT_STATUS, &val32);
pmread(cmac, SUNI1x10GEXP_REG_XRF_DIAG_INTERRUPT_STATUS, &val32);
pmread(cmac, SUNI1x10GEXP_REG_RXOAM_INTERRUPT_STATUS, &val32);
pmread(cmac, SUNI1x10GEXP_REG_PL4ODP_INTERRUPT, &val32);
pmread(cmac, SUNI1x10GEXP_REG_XTEF_INTERRUPT_STATUS, &val32);
pmread(cmac, SUNI1x10GEXP_REG_IFLX_FIFO_OVERFLOW_INTERRUPT, &val32);
pmread(cmac, SUNI1x10GEXP_REG_TXOAM_INTERRUPT_STATUS, &val32);
pmread(cmac, SUNI1x10GEXP_REG_RXXG_INTERRUPT, &val32);
pmread(cmac, SUNI1x10GEXP_REG_TXXG_INTERRUPT, &val32);
pmread(cmac, SUNI1x10GEXP_REG_PL4IDU_INTERRUPT, &val32);
pmread(cmac, SUNI1x10GEXP_REG_EFLX_FIFO_OVERFLOW_ERROR_INDICATION,
&val32);
pmread(cmac, SUNI1x10GEXP_REG_PL4IO_LOCK_DETECT_STATUS, &val32);
pmread(cmac, SUNI1x10GEXP_REG_PL4IO_LOCK_DETECT_CHANGE, &val32);
/* PM3393 - Global interrupt status
*/
pmread(cmac, SUNI1x10GEXP_REG_MASTER_INTERRUPT_STATUS, &val32);
/* ELMER - External chip interrupts.
*/
t1_tpi_read(cmac->adapter, A_ELMER0_INT_CAUSE, &elmer);
elmer |= ELMER0_GP_BIT1;
t1_tpi_write(cmac->adapter, A_ELMER0_INT_CAUSE, elmer);
/* TERMINATOR - PL_INTERUPTS_EXT
*/
pl_intr = readl(cmac->adapter->regs + A_PL_CAUSE);
pl_intr |= F_PL_INTR_EXT;
writel(pl_intr, cmac->adapter->regs + A_PL_CAUSE);
return 0;
}
/* Interrupt handler */
static int pm3393_interrupt_handler(struct cmac *cmac)
{
u32 master_intr_status;
/* Read the master interrupt status register. */
pmread(cmac, SUNI1x10GEXP_REG_MASTER_INTERRUPT_STATUS,
&master_intr_status);
if (netif_msg_intr(cmac->adapter))
dev_dbg(&cmac->adapter->pdev->dev, "PM3393 intr cause 0x%x\n",
master_intr_status);
/* TBD XXX Lets just clear everything for now */
pm3393_interrupt_clear(cmac);
return 0;
}
static int pm3393_enable(struct cmac *cmac, int which)
{
if (which & MAC_DIRECTION_RX)
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_CONFIG_1,
(RXXG_CONF1_VAL | SUNI1x10GEXP_BITMSK_RXXG_RXEN));
if (which & MAC_DIRECTION_TX) {
u32 val = TXXG_CONF1_VAL | SUNI1x10GEXP_BITMSK_TXXG_TXEN0;
if (cmac->instance->fc & PAUSE_RX)
val |= SUNI1x10GEXP_BITMSK_TXXG_FCRX;
if (cmac->instance->fc & PAUSE_TX)
val |= SUNI1x10GEXP_BITMSK_TXXG_FCTX;
pmwrite(cmac, SUNI1x10GEXP_REG_TXXG_CONFIG_1, val);
}
cmac->instance->enabled |= which;
return 0;
}
static int pm3393_enable_port(struct cmac *cmac, int which)
{
/* Clear port statistics */
pmwrite(cmac, SUNI1x10GEXP_REG_MSTAT_CONTROL,
SUNI1x10GEXP_BITMSK_MSTAT_CLEAR);
udelay(2);
memset(&cmac->stats, 0, sizeof(struct cmac_statistics));
pm3393_enable(cmac, which);
/*
* XXX This should be done by the PHY and preferably not at all.
* The PHY doesn't give us link status indication on its own so have
* the link management code query it instead.
*/
t1_link_changed(cmac->adapter, 0);
return 0;
}
static int pm3393_disable(struct cmac *cmac, int which)
{
if (which & MAC_DIRECTION_RX)
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_CONFIG_1, RXXG_CONF1_VAL);
if (which & MAC_DIRECTION_TX)
pmwrite(cmac, SUNI1x10GEXP_REG_TXXG_CONFIG_1, TXXG_CONF1_VAL);
/*
* The disable is graceful. Give the PM3393 time. Can't wait very
* long here, we may be holding locks.
*/
udelay(20);
cmac->instance->enabled &= ~which;
return 0;
}
static int pm3393_loopback_enable(struct cmac *cmac)
{
return 0;
}
static int pm3393_loopback_disable(struct cmac *cmac)
{
return 0;
}
static int pm3393_set_mtu(struct cmac *cmac, int mtu)
{
int enabled = cmac->instance->enabled;
/* MAX_FRAME_SIZE includes header + FCS, mtu doesn't */
mtu += 14 + 4;
if (mtu > MAX_FRAME_SIZE)
return -EINVAL;
/* Disable Rx/Tx MAC before configuring it. */
if (enabled)
pm3393_disable(cmac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MAX_FRAME_LENGTH, mtu);
pmwrite(cmac, SUNI1x10GEXP_REG_TXXG_MAX_FRAME_SIZE, mtu);
if (enabled)
pm3393_enable(cmac, enabled);
return 0;
}
static int pm3393_set_rx_mode(struct cmac *cmac, struct t1_rx_mode *rm)
{
int enabled = cmac->instance->enabled & MAC_DIRECTION_RX;
u32 rx_mode;
/* Disable MAC RX before reconfiguring it */
if (enabled)
pm3393_disable(cmac, MAC_DIRECTION_RX);
pmread(cmac, SUNI1x10GEXP_REG_RXXG_ADDRESS_FILTER_CONTROL_2, &rx_mode);
rx_mode &= ~(SUNI1x10GEXP_BITMSK_RXXG_PMODE |
SUNI1x10GEXP_BITMSK_RXXG_MHASH_EN);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_ADDRESS_FILTER_CONTROL_2,
(u16)rx_mode);
if (t1_rx_mode_promisc(rm)) {
/* Promiscuous mode. */
rx_mode |= SUNI1x10GEXP_BITMSK_RXXG_PMODE;
}
if (t1_rx_mode_allmulti(rm)) {
/* Accept all multicast. */
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MULTICAST_HASH_LOW, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MULTICAST_HASH_MIDLOW, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MULTICAST_HASH_MIDHIGH, 0xffff);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MULTICAST_HASH_HIGH, 0xffff);
rx_mode |= SUNI1x10GEXP_BITMSK_RXXG_MHASH_EN;
} else if (t1_rx_mode_mc_cnt(rm)) {
/* Accept one or more multicast(s). */
struct netdev_hw_addr *ha;
int bit;
u16 mc_filter[4] = { 0, };
netdev_for_each_mc_addr(ha, t1_get_netdev(rm)) {
/* bit[23:28] */
bit = (ether_crc(ETH_ALEN, ha->addr) >> 23) & 0x3f;
mc_filter[bit >> 4] |= 1 << (bit & 0xf);
}
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MULTICAST_HASH_LOW, mc_filter[0]);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MULTICAST_HASH_MIDLOW, mc_filter[1]);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MULTICAST_HASH_MIDHIGH, mc_filter[2]);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_MULTICAST_HASH_HIGH, mc_filter[3]);
rx_mode |= SUNI1x10GEXP_BITMSK_RXXG_MHASH_EN;
}
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_ADDRESS_FILTER_CONTROL_2, (u16)rx_mode);
if (enabled)
pm3393_enable(cmac, MAC_DIRECTION_RX);
return 0;
}
static int pm3393_get_speed_duplex_fc(struct cmac *cmac, int *speed,
int *duplex, int *fc)
{
if (speed)
*speed = SPEED_10000;
if (duplex)
*duplex = DUPLEX_FULL;
if (fc)
*fc = cmac->instance->fc;
return 0;
}
static int pm3393_set_speed_duplex_fc(struct cmac *cmac, int speed, int duplex,
int fc)
{
if (speed >= 0 && speed != SPEED_10000)
return -1;
if (duplex >= 0 && duplex != DUPLEX_FULL)
return -1;
if (fc & ~(PAUSE_TX | PAUSE_RX))
return -1;
if (fc != cmac->instance->fc) {
cmac->instance->fc = (u8) fc;
if (cmac->instance->enabled & MAC_DIRECTION_TX)
pm3393_enable(cmac, MAC_DIRECTION_TX);
}
return 0;
}
#define RMON_UPDATE(mac, name, stat_name) \
{ \
t1_tpi_read((mac)->adapter, OFFSET(name), &val0); \
t1_tpi_read((mac)->adapter, OFFSET((name)+1), &val1); \
t1_tpi_read((mac)->adapter, OFFSET((name)+2), &val2); \
(mac)->stats.stat_name = (u64)(val0 & 0xffff) | \
((u64)(val1 & 0xffff) << 16) | \
((u64)(val2 & 0xff) << 32) | \
((mac)->stats.stat_name & \
0xffffff0000000000ULL); \
if (ro & \
(1ULL << ((name - SUNI1x10GEXP_REG_MSTAT_COUNTER_0_LOW) >> 2))) \
(mac)->stats.stat_name += 1ULL << 40; \
}
static const struct cmac_statistics *pm3393_update_statistics(struct cmac *mac,
int flag)
{
u64 ro;
u32 val0, val1, val2, val3;
/* Snap the counters */
pmwrite(mac, SUNI1x10GEXP_REG_MSTAT_CONTROL,
SUNI1x10GEXP_BITMSK_MSTAT_SNAP);
/* Counter rollover, clear on read */
pmread(mac, SUNI1x10GEXP_REG_MSTAT_COUNTER_ROLLOVER_0, &val0);
pmread(mac, SUNI1x10GEXP_REG_MSTAT_COUNTER_ROLLOVER_1, &val1);
pmread(mac, SUNI1x10GEXP_REG_MSTAT_COUNTER_ROLLOVER_2, &val2);
pmread(mac, SUNI1x10GEXP_REG_MSTAT_COUNTER_ROLLOVER_3, &val3);
ro = ((u64)val0 & 0xffff) | (((u64)val1 & 0xffff) << 16) |
(((u64)val2 & 0xffff) << 32) | (((u64)val3 & 0xffff) << 48);
/* Rx stats */
RMON_UPDATE(mac, RxOctetsReceivedOK, RxOctetsOK);
RMON_UPDATE(mac, RxUnicastFramesReceivedOK, RxUnicastFramesOK);
RMON_UPDATE(mac, RxMulticastFramesReceivedOK, RxMulticastFramesOK);
RMON_UPDATE(mac, RxBroadcastFramesReceivedOK, RxBroadcastFramesOK);
RMON_UPDATE(mac, RxPAUSEMACCtrlFramesReceived, RxPauseFrames);
RMON_UPDATE(mac, RxFrameCheckSequenceErrors, RxFCSErrors);
RMON_UPDATE(mac, RxFramesLostDueToInternalMACErrors,
RxInternalMACRcvError);
RMON_UPDATE(mac, RxSymbolErrors, RxSymbolErrors);
RMON_UPDATE(mac, RxInRangeLengthErrors, RxInRangeLengthErrors);
RMON_UPDATE(mac, RxFramesTooLongErrors , RxFrameTooLongErrors);
RMON_UPDATE(mac, RxJabbers, RxJabberErrors);
RMON_UPDATE(mac, RxFragments, RxRuntErrors);
RMON_UPDATE(mac, RxUndersizedFrames, RxRuntErrors);
RMON_UPDATE(mac, RxJumboFramesReceivedOK, RxJumboFramesOK);
RMON_UPDATE(mac, RxJumboOctetsReceivedOK, RxJumboOctetsOK);
/* Tx stats */
RMON_UPDATE(mac, TxOctetsTransmittedOK, TxOctetsOK);
RMON_UPDATE(mac, TxFramesLostDueToInternalMACTransmissionError,
TxInternalMACXmitError);
RMON_UPDATE(mac, TxTransmitSystemError, TxFCSErrors);
RMON_UPDATE(mac, TxUnicastFramesTransmittedOK, TxUnicastFramesOK);
RMON_UPDATE(mac, TxMulticastFramesTransmittedOK, TxMulticastFramesOK);
RMON_UPDATE(mac, TxBroadcastFramesTransmittedOK, TxBroadcastFramesOK);
RMON_UPDATE(mac, TxPAUSEMACCtrlFramesTransmitted, TxPauseFrames);
RMON_UPDATE(mac, TxJumboFramesReceivedOK, TxJumboFramesOK);
RMON_UPDATE(mac, TxJumboOctetsReceivedOK, TxJumboOctetsOK);
return &mac->stats;
}
static int pm3393_macaddress_get(struct cmac *cmac, u8 mac_addr[6])
{
memcpy(mac_addr, cmac->instance->mac_addr, ETH_ALEN);
return 0;
}
static int pm3393_macaddress_set(struct cmac *cmac, u8 ma[6])
{
u32 val, lo, mid, hi, enabled = cmac->instance->enabled;
/*
* MAC addr: 00:07:43:00:13:09
*
* ma[5] = 0x09
* ma[4] = 0x13
* ma[3] = 0x00
* ma[2] = 0x43
* ma[1] = 0x07
* ma[0] = 0x00
*
* The PM3393 requires byte swapping and reverse order entry
* when programming MAC addresses:
*
* low_bits[15:0] = ma[1]:ma[0]
* mid_bits[31:16] = ma[3]:ma[2]
* high_bits[47:32] = ma[5]:ma[4]
*/
/* Store local copy */
memcpy(cmac->instance->mac_addr, ma, ETH_ALEN);
lo = ((u32) ma[1] << 8) | (u32) ma[0];
mid = ((u32) ma[3] << 8) | (u32) ma[2];
hi = ((u32) ma[5] << 8) | (u32) ma[4];
/* Disable Rx/Tx MAC before configuring it. */
if (enabled)
pm3393_disable(cmac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
/* Set RXXG Station Address */
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_SA_15_0, lo);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_SA_31_16, mid);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_SA_47_32, hi);
/* Set TXXG Station Address */
pmwrite(cmac, SUNI1x10GEXP_REG_TXXG_SA_15_0, lo);
pmwrite(cmac, SUNI1x10GEXP_REG_TXXG_SA_31_16, mid);
pmwrite(cmac, SUNI1x10GEXP_REG_TXXG_SA_47_32, hi);
/* Setup Exact Match Filter 1 with our MAC address
*
* Must disable exact match filter before configuring it.
*/
pmread(cmac, SUNI1x10GEXP_REG_RXXG_ADDRESS_FILTER_CONTROL_0, &val);
val &= 0xff0f;
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_ADDRESS_FILTER_CONTROL_0, val);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_EXACT_MATCH_ADDR_1_LOW, lo);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_EXACT_MATCH_ADDR_1_MID, mid);
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_EXACT_MATCH_ADDR_1_HIGH, hi);
val |= 0x0090;
pmwrite(cmac, SUNI1x10GEXP_REG_RXXG_ADDRESS_FILTER_CONTROL_0, val);
if (enabled)
pm3393_enable(cmac, enabled);
return 0;
}
static void pm3393_destroy(struct cmac *cmac)
{
kfree(cmac);
}
static struct cmac_ops pm3393_ops = {
.destroy = pm3393_destroy,
.reset = pm3393_reset,
.interrupt_enable = pm3393_interrupt_enable,
.interrupt_disable = pm3393_interrupt_disable,
.interrupt_clear = pm3393_interrupt_clear,
.interrupt_handler = pm3393_interrupt_handler,
.enable = pm3393_enable_port,
.disable = pm3393_disable,
.loopback_enable = pm3393_loopback_enable,
.loopback_disable = pm3393_loopback_disable,
.set_mtu = pm3393_set_mtu,
.set_rx_mode = pm3393_set_rx_mode,
.get_speed_duplex_fc = pm3393_get_speed_duplex_fc,
.set_speed_duplex_fc = pm3393_set_speed_duplex_fc,
.statistics_update = pm3393_update_statistics,
.macaddress_get = pm3393_macaddress_get,
.macaddress_set = pm3393_macaddress_set
};
static struct cmac *pm3393_mac_create(adapter_t *adapter, int index)
{
struct cmac *cmac;
cmac = kzalloc(sizeof(*cmac) + sizeof(cmac_instance), GFP_KERNEL);
if (!cmac)
return NULL;
cmac->ops = &pm3393_ops;
cmac->instance = (cmac_instance *) (cmac + 1);
cmac->adapter = adapter;
cmac->instance->fc = PAUSE_TX | PAUSE_RX;
t1_tpi_write(adapter, OFFSET(0x0001), 0x00008000);
t1_tpi_write(adapter, OFFSET(0x0001), 0x00000000);
t1_tpi_write(adapter, OFFSET(0x2308), 0x00009800);
t1_tpi_write(adapter, OFFSET(0x2305), 0x00001001); /* PL4IO Enable */
t1_tpi_write(adapter, OFFSET(0x2320), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2321), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2322), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2323), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2324), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2325), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2326), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2327), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2328), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x2329), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x232a), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x232b), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x232c), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x232d), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x232e), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x232f), 0x00008800);
t1_tpi_write(adapter, OFFSET(0x230d), 0x00009c00);
t1_tpi_write(adapter, OFFSET(0x2304), 0x00000202); /* PL4IO Calendar Repetitions */
t1_tpi_write(adapter, OFFSET(0x3200), 0x00008080); /* EFLX Enable */
t1_tpi_write(adapter, OFFSET(0x3210), 0x00000000); /* EFLX Channel Deprovision */
t1_tpi_write(adapter, OFFSET(0x3203), 0x00000000); /* EFLX Low Limit */
t1_tpi_write(adapter, OFFSET(0x3204), 0x00000040); /* EFLX High Limit */
t1_tpi_write(adapter, OFFSET(0x3205), 0x000002cc); /* EFLX Almost Full */
t1_tpi_write(adapter, OFFSET(0x3206), 0x00000199); /* EFLX Almost Empty */
t1_tpi_write(adapter, OFFSET(0x3207), 0x00000240); /* EFLX Cut Through Threshold */
t1_tpi_write(adapter, OFFSET(0x3202), 0x00000000); /* EFLX Indirect Register Update */
t1_tpi_write(adapter, OFFSET(0x3210), 0x00000001); /* EFLX Channel Provision */
t1_tpi_write(adapter, OFFSET(0x3208), 0x0000ffff); /* EFLX Undocumented */
t1_tpi_write(adapter, OFFSET(0x320a), 0x0000ffff); /* EFLX Undocumented */
t1_tpi_write(adapter, OFFSET(0x320c), 0x0000ffff); /* EFLX enable overflow interrupt The other bit are undocumented */
t1_tpi_write(adapter, OFFSET(0x320e), 0x0000ffff); /* EFLX Undocumented */
t1_tpi_write(adapter, OFFSET(0x2200), 0x0000c000); /* IFLX Configuration - enable */
t1_tpi_write(adapter, OFFSET(0x2201), 0x00000000); /* IFLX Channel Deprovision */
t1_tpi_write(adapter, OFFSET(0x220e), 0x00000000); /* IFLX Low Limit */
t1_tpi_write(adapter, OFFSET(0x220f), 0x00000100); /* IFLX High Limit */
t1_tpi_write(adapter, OFFSET(0x2210), 0x00000c00); /* IFLX Almost Full Limit */
t1_tpi_write(adapter, OFFSET(0x2211), 0x00000599); /* IFLX Almost Empty Limit */
t1_tpi_write(adapter, OFFSET(0x220d), 0x00000000); /* IFLX Indirect Register Update */
t1_tpi_write(adapter, OFFSET(0x2201), 0x00000001); /* IFLX Channel Provision */
t1_tpi_write(adapter, OFFSET(0x2203), 0x0000ffff); /* IFLX Undocumented */
t1_tpi_write(adapter, OFFSET(0x2205), 0x0000ffff); /* IFLX Undocumented */
t1_tpi_write(adapter, OFFSET(0x2209), 0x0000ffff); /* IFLX Enable overflow interrupt. The other bit are undocumented */
t1_tpi_write(adapter, OFFSET(0x2241), 0xfffffffe); /* PL4MOS Undocumented */
t1_tpi_write(adapter, OFFSET(0x2242), 0x0000ffff); /* PL4MOS Undocumented */
t1_tpi_write(adapter, OFFSET(0x2243), 0x00000008); /* PL4MOS Starving Burst Size */
t1_tpi_write(adapter, OFFSET(0x2244), 0x00000008); /* PL4MOS Hungry Burst Size */
t1_tpi_write(adapter, OFFSET(0x2245), 0x00000008); /* PL4MOS Transfer Size */
t1_tpi_write(adapter, OFFSET(0x2240), 0x00000005); /* PL4MOS Disable */
t1_tpi_write(adapter, OFFSET(0x2280), 0x00002103); /* PL4ODP Training Repeat and SOP rule */
t1_tpi_write(adapter, OFFSET(0x2284), 0x00000000); /* PL4ODP MAX_T setting */
t1_tpi_write(adapter, OFFSET(0x3280), 0x00000087); /* PL4IDU Enable data forward, port state machine. Set ALLOW_NON_ZERO_OLB */
t1_tpi_write(adapter, OFFSET(0x3282), 0x0000001f); /* PL4IDU Enable Dip4 check error interrupts */
t1_tpi_write(adapter, OFFSET(0x3040), 0x0c32); /* # TXXG Config */
/* For T1 use timer based Mac flow control. */
t1_tpi_write(adapter, OFFSET(0x304d), 0x8000);
t1_tpi_write(adapter, OFFSET(0x2040), 0x059c); /* # RXXG Config */
t1_tpi_write(adapter, OFFSET(0x2049), 0x0001); /* # RXXG Cut Through */
t1_tpi_write(adapter, OFFSET(0x2070), 0x0000); /* # Disable promiscuous mode */
/* Setup Exact Match Filter 0 to allow broadcast packets.
*/
t1_tpi_write(adapter, OFFSET(0x206e), 0x0000); /* # Disable Match Enable bit */
t1_tpi_write(adapter, OFFSET(0x204a), 0xffff); /* # low addr */
t1_tpi_write(adapter, OFFSET(0x204b), 0xffff); /* # mid addr */
t1_tpi_write(adapter, OFFSET(0x204c), 0xffff); /* # high addr */
t1_tpi_write(adapter, OFFSET(0x206e), 0x0009); /* # Enable Match Enable bit */
t1_tpi_write(adapter, OFFSET(0x0003), 0x0000); /* # NO SOP/ PAD_EN setup */
t1_tpi_write(adapter, OFFSET(0x0100), 0x0ff0); /* # RXEQB disabled */
t1_tpi_write(adapter, OFFSET(0x0101), 0x0f0f); /* # No Preemphasis */
return cmac;
}
static int pm3393_mac_reset(adapter_t * adapter)
{
u32 val;
u32 x;
u32 is_pl4_reset_finished;
u32 is_pl4_outof_lock;
u32 is_xaui_mabc_pll_locked;
u32 successful_reset;
int i;
/* The following steps are required to properly reset
* the PM3393. This information is provided in the
* PM3393 datasheet (Issue 2: November 2002)
* section 13.1 -- Device Reset.
*
* The PM3393 has three types of components that are
* individually reset:
*
* DRESETB - Digital circuitry
* PL4_ARESETB - PL4 analog circuitry
* XAUI_ARESETB - XAUI bus analog circuitry
*
* Steps to reset PM3393 using RSTB pin:
*
* 1. Assert RSTB pin low ( write 0 )
* 2. Wait at least 1ms to initiate a complete initialization of device.
* 3. Wait until all external clocks and REFSEL are stable.
* 4. Wait minimum of 1ms. (after external clocks and REFEL are stable)
* 5. De-assert RSTB ( write 1 )
* 6. Wait until internal timers to expires after ~14ms.
* - Allows analog clock synthesizer(PL4CSU) to stabilize to
* selected reference frequency before allowing the digital
* portion of the device to operate.
* 7. Wait at least 200us for XAUI interface to stabilize.
* 8. Verify the PM3393 came out of reset successfully.
* Set successful reset flag if everything worked else try again
* a few more times.
*/
successful_reset = 0;
for (i = 0; i < 3 && !successful_reset; i++) {
/* 1 */
t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~1;
t1_tpi_write(adapter, A_ELMER0_GPO, val);
/* 2 */
msleep(1);
/* 3 */
msleep(1);
/* 4 */
msleep(2 /*1 extra ms for safety */ );
/* 5 */
val |= 1;
t1_tpi_write(adapter, A_ELMER0_GPO, val);
/* 6 */
msleep(15 /*1 extra ms for safety */ );
/* 7 */
msleep(1);
/* 8 */
/* Has PL4 analog block come out of reset correctly? */
t1_tpi_read(adapter, OFFSET(SUNI1x10GEXP_REG_DEVICE_STATUS), &val);
is_pl4_reset_finished = (val & SUNI1x10GEXP_BITMSK_TOP_EXPIRED);
/* TBD XXX SUNI1x10GEXP_BITMSK_TOP_PL4_IS_DOOL gets locked later in the init sequence
* figure out why? */
/* Have all PL4 block clocks locked? */
x = (SUNI1x10GEXP_BITMSK_TOP_PL4_ID_DOOL
/*| SUNI1x10GEXP_BITMSK_TOP_PL4_IS_DOOL */ |
SUNI1x10GEXP_BITMSK_TOP_PL4_ID_ROOL |
SUNI1x10GEXP_BITMSK_TOP_PL4_IS_ROOL |
SUNI1x10GEXP_BITMSK_TOP_PL4_OUT_ROOL);
is_pl4_outof_lock = (val & x);
/* ??? If this fails, might be able to software reset the XAUI part
* and try to recover... thus saving us from doing another HW reset */
/* Has the XAUI MABC PLL circuitry stablized? */
is_xaui_mabc_pll_locked =
(val & SUNI1x10GEXP_BITMSK_TOP_SXRA_EXPIRED);
successful_reset = (is_pl4_reset_finished && !is_pl4_outof_lock
&& is_xaui_mabc_pll_locked);
if (netif_msg_hw(adapter))
dev_dbg(&adapter->pdev->dev,
"PM3393 HW reset %d: pl4_reset 0x%x, val 0x%x, "
"is_pl4_outof_lock 0x%x, xaui_locked 0x%x\n",
i, is_pl4_reset_finished, val,
is_pl4_outof_lock, is_xaui_mabc_pll_locked);
}
return successful_reset ? 0 : 1;
}
const struct gmac t1_pm3393_ops = {
.stats_update_period = STATS_TICK_SECS,
.create = pm3393_mac_create,
.reset = pm3393_mac_reset,
};
| gpl-2.0 |
NieNs/IM-A840S-kernel-1 | fs/exofs/inode.c | 2511 | 34166 | /*
* Copyright (C) 2005, 2006
* Avishay Traeger (avishay@gmail.com)
* Copyright (C) 2008, 2009
* Boaz Harrosh <bharrosh@panasas.com>
*
* Copyrights for code taken from ext2:
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
* from
* linux/fs/minix/inode.c
* Copyright (C) 1991, 1992 Linus Torvalds
*
* This file is part of exofs.
*
* exofs 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. Since it is based on ext2, and the only
* valid version of GPL for the Linux kernel is version 2, the only valid
* version of GPL for exofs is version 2.
*
* exofs 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 exofs; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/slab.h>
#include "exofs.h"
#define EXOFS_DBGMSG2(M...) do {} while (0)
enum { BIO_MAX_PAGES_KMALLOC =
(PAGE_SIZE - sizeof(struct bio)) / sizeof(struct bio_vec),
MAX_PAGES_KMALLOC =
PAGE_SIZE / sizeof(struct page *),
};
unsigned exofs_max_io_pages(struct exofs_layout *layout,
unsigned expected_pages)
{
unsigned pages = min_t(unsigned, expected_pages, MAX_PAGES_KMALLOC);
/* TODO: easily support bio chaining */
pages = min_t(unsigned, pages,
layout->group_width * BIO_MAX_PAGES_KMALLOC);
return pages;
}
struct page_collect {
struct exofs_sb_info *sbi;
struct inode *inode;
unsigned expected_pages;
struct exofs_io_state *ios;
struct page **pages;
unsigned alloc_pages;
unsigned nr_pages;
unsigned long length;
loff_t pg_first; /* keep 64bit also in 32-arches */
bool read_4_write; /* This means two things: that the read is sync
* And the pages should not be unlocked.
*/
};
static void _pcol_init(struct page_collect *pcol, unsigned expected_pages,
struct inode *inode)
{
struct exofs_sb_info *sbi = inode->i_sb->s_fs_info;
pcol->sbi = sbi;
pcol->inode = inode;
pcol->expected_pages = expected_pages;
pcol->ios = NULL;
pcol->pages = NULL;
pcol->alloc_pages = 0;
pcol->nr_pages = 0;
pcol->length = 0;
pcol->pg_first = -1;
pcol->read_4_write = false;
}
static void _pcol_reset(struct page_collect *pcol)
{
pcol->expected_pages -= min(pcol->nr_pages, pcol->expected_pages);
pcol->pages = NULL;
pcol->alloc_pages = 0;
pcol->nr_pages = 0;
pcol->length = 0;
pcol->pg_first = -1;
pcol->ios = NULL;
/* this is probably the end of the loop but in writes
* it might not end here. don't be left with nothing
*/
if (!pcol->expected_pages)
pcol->expected_pages = MAX_PAGES_KMALLOC;
}
static int pcol_try_alloc(struct page_collect *pcol)
{
unsigned pages;
if (!pcol->ios) { /* First time allocate io_state */
int ret = exofs_get_io_state(&pcol->sbi->layout, &pcol->ios);
if (ret)
return ret;
}
/* TODO: easily support bio chaining */
pages = exofs_max_io_pages(&pcol->sbi->layout, pcol->expected_pages);
for (; pages; pages >>= 1) {
pcol->pages = kmalloc(pages * sizeof(struct page *),
GFP_KERNEL);
if (likely(pcol->pages)) {
pcol->alloc_pages = pages;
return 0;
}
}
EXOFS_ERR("Failed to kmalloc expected_pages=%u\n",
pcol->expected_pages);
return -ENOMEM;
}
static void pcol_free(struct page_collect *pcol)
{
kfree(pcol->pages);
pcol->pages = NULL;
if (pcol->ios) {
exofs_put_io_state(pcol->ios);
pcol->ios = NULL;
}
}
static int pcol_add_page(struct page_collect *pcol, struct page *page,
unsigned len)
{
if (unlikely(pcol->nr_pages >= pcol->alloc_pages))
return -ENOMEM;
pcol->pages[pcol->nr_pages++] = page;
pcol->length += len;
return 0;
}
static int update_read_page(struct page *page, int ret)
{
if (ret == 0) {
/* Everything is OK */
SetPageUptodate(page);
if (PageError(page))
ClearPageError(page);
} else if (ret == -EFAULT) {
/* In this case we were trying to read something that wasn't on
* disk yet - return a page full of zeroes. This should be OK,
* because the object should be empty (if there was a write
* before this read, the read would be waiting with the page
* locked */
clear_highpage(page);
SetPageUptodate(page);
if (PageError(page))
ClearPageError(page);
ret = 0; /* recovered error */
EXOFS_DBGMSG("recovered read error\n");
} else /* Error */
SetPageError(page);
return ret;
}
static void update_write_page(struct page *page, int ret)
{
if (ret) {
mapping_set_error(page->mapping, ret);
SetPageError(page);
}
end_page_writeback(page);
}
/* Called at the end of reads, to optionally unlock pages and update their
* status.
*/
static int __readpages_done(struct page_collect *pcol)
{
int i;
u64 resid;
u64 good_bytes;
u64 length = 0;
int ret = exofs_check_io(pcol->ios, &resid);
if (likely(!ret))
good_bytes = pcol->length;
else
good_bytes = pcol->length - resid;
EXOFS_DBGMSG2("readpages_done(0x%lx) good_bytes=0x%llx"
" length=0x%lx nr_pages=%u\n",
pcol->inode->i_ino, _LLU(good_bytes), pcol->length,
pcol->nr_pages);
for (i = 0; i < pcol->nr_pages; i++) {
struct page *page = pcol->pages[i];
struct inode *inode = page->mapping->host;
int page_stat;
if (inode != pcol->inode)
continue; /* osd might add more pages at end */
if (likely(length < good_bytes))
page_stat = 0;
else
page_stat = ret;
EXOFS_DBGMSG2(" readpages_done(0x%lx, 0x%lx) %s\n",
inode->i_ino, page->index,
page_stat ? "bad_bytes" : "good_bytes");
ret = update_read_page(page, page_stat);
if (!pcol->read_4_write)
unlock_page(page);
length += PAGE_SIZE;
}
pcol_free(pcol);
EXOFS_DBGMSG2("readpages_done END\n");
return ret;
}
/* callback of async reads */
static void readpages_done(struct exofs_io_state *ios, void *p)
{
struct page_collect *pcol = p;
__readpages_done(pcol);
atomic_dec(&pcol->sbi->s_curr_pending);
kfree(pcol);
}
static void _unlock_pcol_pages(struct page_collect *pcol, int ret, int rw)
{
int i;
for (i = 0; i < pcol->nr_pages; i++) {
struct page *page = pcol->pages[i];
if (rw == READ)
update_read_page(page, ret);
else
update_write_page(page, ret);
unlock_page(page);
}
}
static int read_exec(struct page_collect *pcol)
{
struct exofs_i_info *oi = exofs_i(pcol->inode);
struct exofs_io_state *ios = pcol->ios;
struct page_collect *pcol_copy = NULL;
int ret;
if (!pcol->pages)
return 0;
ios->pages = pcol->pages;
ios->nr_pages = pcol->nr_pages;
ios->length = pcol->length;
ios->offset = pcol->pg_first << PAGE_CACHE_SHIFT;
if (pcol->read_4_write) {
exofs_oi_read(oi, pcol->ios);
return __readpages_done(pcol);
}
pcol_copy = kmalloc(sizeof(*pcol_copy), GFP_KERNEL);
if (!pcol_copy) {
ret = -ENOMEM;
goto err;
}
*pcol_copy = *pcol;
ios->done = readpages_done;
ios->private = pcol_copy;
ret = exofs_oi_read(oi, ios);
if (unlikely(ret))
goto err;
atomic_inc(&pcol->sbi->s_curr_pending);
EXOFS_DBGMSG2("read_exec obj=0x%llx start=0x%llx length=0x%lx\n",
ios->obj.id, _LLU(ios->offset), pcol->length);
/* pages ownership was passed to pcol_copy */
_pcol_reset(pcol);
return 0;
err:
if (!pcol->read_4_write)
_unlock_pcol_pages(pcol, ret, READ);
pcol_free(pcol);
kfree(pcol_copy);
return ret;
}
/* readpage_strip is called either directly from readpage() or by the VFS from
* within read_cache_pages(), to add one more page to be read. It will try to
* collect as many contiguous pages as posible. If a discontinuity is
* encountered, or it runs out of resources, it will submit the previous segment
* and will start a new collection. Eventually caller must submit the last
* segment if present.
*/
static int readpage_strip(void *data, struct page *page)
{
struct page_collect *pcol = data;
struct inode *inode = pcol->inode;
struct exofs_i_info *oi = exofs_i(inode);
loff_t i_size = i_size_read(inode);
pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
size_t len;
int ret;
/* FIXME: Just for debugging, will be removed */
if (PageUptodate(page))
EXOFS_ERR("PageUptodate(0x%lx, 0x%lx)\n", pcol->inode->i_ino,
page->index);
if (page->index < end_index)
len = PAGE_CACHE_SIZE;
else if (page->index == end_index)
len = i_size & ~PAGE_CACHE_MASK;
else
len = 0;
if (!len || !obj_created(oi)) {
/* this will be out of bounds, or doesn't exist yet.
* Current page is cleared and the request is split
*/
clear_highpage(page);
SetPageUptodate(page);
if (PageError(page))
ClearPageError(page);
if (!pcol->read_4_write)
unlock_page(page);
EXOFS_DBGMSG("readpage_strip(0x%lx) empty page len=%zx "
"read_4_write=%d index=0x%lx end_index=0x%lx "
"splitting\n", inode->i_ino, len,
pcol->read_4_write, page->index, end_index);
return read_exec(pcol);
}
try_again:
if (unlikely(pcol->pg_first == -1)) {
pcol->pg_first = page->index;
} else if (unlikely((pcol->pg_first + pcol->nr_pages) !=
page->index)) {
/* Discontinuity detected, split the request */
ret = read_exec(pcol);
if (unlikely(ret))
goto fail;
goto try_again;
}
if (!pcol->pages) {
ret = pcol_try_alloc(pcol);
if (unlikely(ret))
goto fail;
}
if (len != PAGE_CACHE_SIZE)
zero_user(page, len, PAGE_CACHE_SIZE - len);
EXOFS_DBGMSG2(" readpage_strip(0x%lx, 0x%lx) len=0x%zx\n",
inode->i_ino, page->index, len);
ret = pcol_add_page(pcol, page, len);
if (ret) {
EXOFS_DBGMSG2("Failed pcol_add_page pages[i]=%p "
"this_len=0x%zx nr_pages=%u length=0x%lx\n",
page, len, pcol->nr_pages, pcol->length);
/* split the request, and start again with current page */
ret = read_exec(pcol);
if (unlikely(ret))
goto fail;
goto try_again;
}
return 0;
fail:
/* SetPageError(page); ??? */
unlock_page(page);
return ret;
}
static int exofs_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
struct page_collect pcol;
int ret;
_pcol_init(&pcol, nr_pages, mapping->host);
ret = read_cache_pages(mapping, pages, readpage_strip, &pcol);
if (ret) {
EXOFS_ERR("read_cache_pages => %d\n", ret);
return ret;
}
return read_exec(&pcol);
}
static int _readpage(struct page *page, bool read_4_write)
{
struct page_collect pcol;
int ret;
_pcol_init(&pcol, 1, page->mapping->host);
pcol.read_4_write = read_4_write;
ret = readpage_strip(&pcol, page);
if (ret) {
EXOFS_ERR("_readpage => %d\n", ret);
return ret;
}
return read_exec(&pcol);
}
/*
* We don't need the file
*/
static int exofs_readpage(struct file *file, struct page *page)
{
return _readpage(page, false);
}
/* Callback for osd_write. All writes are asynchronous */
static void writepages_done(struct exofs_io_state *ios, void *p)
{
struct page_collect *pcol = p;
int i;
u64 resid;
u64 good_bytes;
u64 length = 0;
int ret = exofs_check_io(ios, &resid);
atomic_dec(&pcol->sbi->s_curr_pending);
if (likely(!ret))
good_bytes = pcol->length;
else
good_bytes = pcol->length - resid;
EXOFS_DBGMSG2("writepages_done(0x%lx) good_bytes=0x%llx"
" length=0x%lx nr_pages=%u\n",
pcol->inode->i_ino, _LLU(good_bytes), pcol->length,
pcol->nr_pages);
for (i = 0; i < pcol->nr_pages; i++) {
struct page *page = pcol->pages[i];
struct inode *inode = page->mapping->host;
int page_stat;
if (inode != pcol->inode)
continue; /* osd might add more pages to a bio */
if (likely(length < good_bytes))
page_stat = 0;
else
page_stat = ret;
update_write_page(page, page_stat);
unlock_page(page);
EXOFS_DBGMSG2(" writepages_done(0x%lx, 0x%lx) status=%d\n",
inode->i_ino, page->index, page_stat);
length += PAGE_SIZE;
}
pcol_free(pcol);
kfree(pcol);
EXOFS_DBGMSG2("writepages_done END\n");
}
static int write_exec(struct page_collect *pcol)
{
struct exofs_i_info *oi = exofs_i(pcol->inode);
struct exofs_io_state *ios = pcol->ios;
struct page_collect *pcol_copy = NULL;
int ret;
if (!pcol->pages)
return 0;
pcol_copy = kmalloc(sizeof(*pcol_copy), GFP_KERNEL);
if (!pcol_copy) {
EXOFS_ERR("write_exec: Failed to kmalloc(pcol)\n");
ret = -ENOMEM;
goto err;
}
*pcol_copy = *pcol;
ios->pages = pcol_copy->pages;
ios->nr_pages = pcol_copy->nr_pages;
ios->offset = pcol_copy->pg_first << PAGE_CACHE_SHIFT;
ios->length = pcol_copy->length;
ios->done = writepages_done;
ios->private = pcol_copy;
ret = exofs_oi_write(oi, ios);
if (unlikely(ret)) {
EXOFS_ERR("write_exec: exofs_oi_write() Failed\n");
goto err;
}
atomic_inc(&pcol->sbi->s_curr_pending);
EXOFS_DBGMSG2("write_exec(0x%lx, 0x%llx) start=0x%llx length=0x%lx\n",
pcol->inode->i_ino, pcol->pg_first, _LLU(ios->offset),
pcol->length);
/* pages ownership was passed to pcol_copy */
_pcol_reset(pcol);
return 0;
err:
_unlock_pcol_pages(pcol, ret, WRITE);
pcol_free(pcol);
kfree(pcol_copy);
return ret;
}
/* writepage_strip is called either directly from writepage() or by the VFS from
* within write_cache_pages(), to add one more page to be written to storage.
* It will try to collect as many contiguous pages as possible. If a
* discontinuity is encountered or it runs out of resources it will submit the
* previous segment and will start a new collection.
* Eventually caller must submit the last segment if present.
*/
static int writepage_strip(struct page *page,
struct writeback_control *wbc_unused, void *data)
{
struct page_collect *pcol = data;
struct inode *inode = pcol->inode;
struct exofs_i_info *oi = exofs_i(inode);
loff_t i_size = i_size_read(inode);
pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
size_t len;
int ret;
BUG_ON(!PageLocked(page));
ret = wait_obj_created(oi);
if (unlikely(ret))
goto fail;
if (page->index < end_index)
/* in this case, the page is within the limits of the file */
len = PAGE_CACHE_SIZE;
else {
len = i_size & ~PAGE_CACHE_MASK;
if (page->index > end_index || !len) {
/* in this case, the page is outside the limits
* (truncate in progress)
*/
ret = write_exec(pcol);
if (unlikely(ret))
goto fail;
if (PageError(page))
ClearPageError(page);
unlock_page(page);
EXOFS_DBGMSG("writepage_strip(0x%lx, 0x%lx) "
"outside the limits\n",
inode->i_ino, page->index);
return 0;
}
}
try_again:
if (unlikely(pcol->pg_first == -1)) {
pcol->pg_first = page->index;
} else if (unlikely((pcol->pg_first + pcol->nr_pages) !=
page->index)) {
/* Discontinuity detected, split the request */
ret = write_exec(pcol);
if (unlikely(ret))
goto fail;
EXOFS_DBGMSG("writepage_strip(0x%lx, 0x%lx) Discontinuity\n",
inode->i_ino, page->index);
goto try_again;
}
if (!pcol->pages) {
ret = pcol_try_alloc(pcol);
if (unlikely(ret))
goto fail;
}
EXOFS_DBGMSG2(" writepage_strip(0x%lx, 0x%lx) len=0x%zx\n",
inode->i_ino, page->index, len);
ret = pcol_add_page(pcol, page, len);
if (unlikely(ret)) {
EXOFS_DBGMSG2("Failed pcol_add_page "
"nr_pages=%u total_length=0x%lx\n",
pcol->nr_pages, pcol->length);
/* split the request, next loop will start again */
ret = write_exec(pcol);
if (unlikely(ret)) {
EXOFS_DBGMSG("write_exec failed => %d", ret);
goto fail;
}
goto try_again;
}
BUG_ON(PageWriteback(page));
set_page_writeback(page);
return 0;
fail:
EXOFS_DBGMSG("Error: writepage_strip(0x%lx, 0x%lx)=>%d\n",
inode->i_ino, page->index, ret);
set_bit(AS_EIO, &page->mapping->flags);
unlock_page(page);
return ret;
}
static int exofs_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct page_collect pcol;
long start, end, expected_pages;
int ret;
start = wbc->range_start >> PAGE_CACHE_SHIFT;
end = (wbc->range_end == LLONG_MAX) ?
start + mapping->nrpages :
wbc->range_end >> PAGE_CACHE_SHIFT;
if (start || end)
expected_pages = end - start + 1;
else
expected_pages = mapping->nrpages;
if (expected_pages < 32L)
expected_pages = 32L;
EXOFS_DBGMSG2("inode(0x%lx) wbc->start=0x%llx wbc->end=0x%llx "
"nrpages=%lu start=0x%lx end=0x%lx expected_pages=%ld\n",
mapping->host->i_ino, wbc->range_start, wbc->range_end,
mapping->nrpages, start, end, expected_pages);
_pcol_init(&pcol, expected_pages, mapping->host);
ret = write_cache_pages(mapping, wbc, writepage_strip, &pcol);
if (ret) {
EXOFS_ERR("write_cache_pages => %d\n", ret);
return ret;
}
return write_exec(&pcol);
}
static int exofs_writepage(struct page *page, struct writeback_control *wbc)
{
struct page_collect pcol;
int ret;
_pcol_init(&pcol, 1, page->mapping->host);
ret = writepage_strip(page, NULL, &pcol);
if (ret) {
EXOFS_ERR("exofs_writepage => %d\n", ret);
return ret;
}
return write_exec(&pcol);
}
/* i_mutex held using inode->i_size directly */
static void _write_failed(struct inode *inode, loff_t to)
{
if (to > inode->i_size)
truncate_pagecache(inode, to, inode->i_size);
}
int exofs_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
int ret = 0;
struct page *page;
page = *pagep;
if (page == NULL) {
ret = simple_write_begin(file, mapping, pos, len, flags, pagep,
fsdata);
if (ret) {
EXOFS_DBGMSG("simple_write_begin failed\n");
goto out;
}
page = *pagep;
}
/* read modify write */
if (!PageUptodate(page) && (len != PAGE_CACHE_SIZE)) {
loff_t i_size = i_size_read(mapping->host);
pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
size_t rlen;
if (page->index < end_index)
rlen = PAGE_CACHE_SIZE;
else if (page->index == end_index)
rlen = i_size & ~PAGE_CACHE_MASK;
else
rlen = 0;
if (!rlen) {
clear_highpage(page);
SetPageUptodate(page);
goto out;
}
ret = _readpage(page, true);
if (ret) {
/*SetPageError was done by _readpage. Is it ok?*/
unlock_page(page);
EXOFS_DBGMSG("__readpage failed\n");
}
}
out:
if (unlikely(ret))
_write_failed(mapping->host, pos + len);
return ret;
}
static int exofs_write_begin_export(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
*pagep = NULL;
return exofs_write_begin(file, mapping, pos, len, flags, pagep,
fsdata);
}
static int exofs_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct inode *inode = mapping->host;
/* According to comment in simple_write_end i_mutex is held */
loff_t i_size = inode->i_size;
int ret;
ret = simple_write_end(file, mapping,pos, len, copied, page, fsdata);
if (unlikely(ret))
_write_failed(inode, pos + len);
/* TODO: once simple_write_end marks inode dirty remove */
if (i_size != inode->i_size)
mark_inode_dirty(inode);
return ret;
}
static int exofs_releasepage(struct page *page, gfp_t gfp)
{
EXOFS_DBGMSG("page 0x%lx\n", page->index);
WARN_ON(1);
return 0;
}
static void exofs_invalidatepage(struct page *page, unsigned long offset)
{
EXOFS_DBGMSG("page 0x%lx offset 0x%lx\n", page->index, offset);
WARN_ON(1);
}
const struct address_space_operations exofs_aops = {
.readpage = exofs_readpage,
.readpages = exofs_readpages,
.writepage = exofs_writepage,
.writepages = exofs_writepages,
.write_begin = exofs_write_begin_export,
.write_end = exofs_write_end,
.releasepage = exofs_releasepage,
.set_page_dirty = __set_page_dirty_nobuffers,
.invalidatepage = exofs_invalidatepage,
/* Not implemented Yet */
.bmap = NULL, /* TODO: use osd's OSD_ACT_READ_MAP */
.direct_IO = NULL, /* TODO: Should be trivial to do */
/* With these NULL has special meaning or default is not exported */
.get_xip_mem = NULL,
.migratepage = NULL,
.launder_page = NULL,
.is_partially_uptodate = NULL,
.error_remove_page = NULL,
};
/******************************************************************************
* INODE OPERATIONS
*****************************************************************************/
/*
* Test whether an inode is a fast symlink.
*/
static inline int exofs_inode_is_fast_symlink(struct inode *inode)
{
struct exofs_i_info *oi = exofs_i(inode);
return S_ISLNK(inode->i_mode) && (oi->i_data[0] != 0);
}
const struct osd_attr g_attr_logical_length = ATTR_DEF(
OSD_APAGE_OBJECT_INFORMATION, OSD_ATTR_OI_LOGICAL_LENGTH, 8);
static int _do_truncate(struct inode *inode, loff_t newsize)
{
struct exofs_i_info *oi = exofs_i(inode);
int ret;
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
ret = exofs_oi_truncate(oi, (u64)newsize);
if (likely(!ret))
truncate_setsize(inode, newsize);
EXOFS_DBGMSG("(0x%lx) size=0x%llx ret=>%d\n",
inode->i_ino, newsize, ret);
return ret;
}
/*
* Set inode attributes - update size attribute on OSD if needed,
* otherwise just call generic functions.
*/
int exofs_setattr(struct dentry *dentry, struct iattr *iattr)
{
struct inode *inode = dentry->d_inode;
int error;
/* if we are about to modify an object, and it hasn't been
* created yet, wait
*/
error = wait_obj_created(exofs_i(inode));
if (unlikely(error))
return error;
error = inode_change_ok(inode, iattr);
if (unlikely(error))
return error;
if ((iattr->ia_valid & ATTR_SIZE) &&
iattr->ia_size != i_size_read(inode)) {
error = _do_truncate(inode, iattr->ia_size);
if (unlikely(error))
return error;
}
setattr_copy(inode, iattr);
mark_inode_dirty(inode);
return 0;
}
static const struct osd_attr g_attr_inode_file_layout = ATTR_DEF(
EXOFS_APAGE_FS_DATA,
EXOFS_ATTR_INODE_FILE_LAYOUT,
0);
static const struct osd_attr g_attr_inode_dir_layout = ATTR_DEF(
EXOFS_APAGE_FS_DATA,
EXOFS_ATTR_INODE_DIR_LAYOUT,
0);
/*
* Read the Linux inode info from the OSD, and return it as is. In exofs the
* inode info is in an application specific page/attribute of the osd-object.
*/
static int exofs_get_inode(struct super_block *sb, struct exofs_i_info *oi,
struct exofs_fcb *inode)
{
struct exofs_sb_info *sbi = sb->s_fs_info;
struct osd_attr attrs[] = {
[0] = g_attr_inode_data,
[1] = g_attr_inode_file_layout,
[2] = g_attr_inode_dir_layout,
};
struct exofs_io_state *ios;
struct exofs_on_disk_inode_layout *layout;
int ret;
ret = exofs_get_io_state(&sbi->layout, &ios);
if (unlikely(ret)) {
EXOFS_ERR("%s: exofs_get_io_state failed.\n", __func__);
return ret;
}
ios->obj.id = exofs_oi_objno(oi);
exofs_make_credential(oi->i_cred, &ios->obj);
ios->cred = oi->i_cred;
attrs[1].len = exofs_on_disk_inode_layout_size(sbi->layout.s_numdevs);
attrs[2].len = exofs_on_disk_inode_layout_size(sbi->layout.s_numdevs);
ios->in_attr = attrs;
ios->in_attr_len = ARRAY_SIZE(attrs);
ret = exofs_sbi_read(ios);
if (unlikely(ret)) {
EXOFS_ERR("object(0x%llx) corrupted, return empty file=>%d\n",
_LLU(ios->obj.id), ret);
memset(inode, 0, sizeof(*inode));
inode->i_mode = 0040000 | (0777 & ~022);
/* If object is lost on target we might as well enable it's
* delete.
*/
if ((ret == -ENOENT) || (ret == -EINVAL))
ret = 0;
goto out;
}
ret = extract_attr_from_ios(ios, &attrs[0]);
if (ret) {
EXOFS_ERR("%s: extract_attr of inode_data failed\n", __func__);
goto out;
}
WARN_ON(attrs[0].len != EXOFS_INO_ATTR_SIZE);
memcpy(inode, attrs[0].val_ptr, EXOFS_INO_ATTR_SIZE);
ret = extract_attr_from_ios(ios, &attrs[1]);
if (ret) {
EXOFS_ERR("%s: extract_attr of inode_data failed\n", __func__);
goto out;
}
if (attrs[1].len) {
layout = attrs[1].val_ptr;
if (layout->gen_func != cpu_to_le16(LAYOUT_MOVING_WINDOW)) {
EXOFS_ERR("%s: unsupported files layout %d\n",
__func__, layout->gen_func);
ret = -ENOTSUPP;
goto out;
}
}
ret = extract_attr_from_ios(ios, &attrs[2]);
if (ret) {
EXOFS_ERR("%s: extract_attr of inode_data failed\n", __func__);
goto out;
}
if (attrs[2].len) {
layout = attrs[2].val_ptr;
if (layout->gen_func != cpu_to_le16(LAYOUT_MOVING_WINDOW)) {
EXOFS_ERR("%s: unsupported meta-data layout %d\n",
__func__, layout->gen_func);
ret = -ENOTSUPP;
goto out;
}
}
out:
exofs_put_io_state(ios);
return ret;
}
static void __oi_init(struct exofs_i_info *oi)
{
init_waitqueue_head(&oi->i_wq);
oi->i_flags = 0;
}
/*
* Fill in an inode read from the OSD and set it up for use
*/
struct inode *exofs_iget(struct super_block *sb, unsigned long ino)
{
struct exofs_i_info *oi;
struct exofs_fcb fcb;
struct inode *inode;
int ret;
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
oi = exofs_i(inode);
__oi_init(oi);
/* read the inode from the osd */
ret = exofs_get_inode(sb, oi, &fcb);
if (ret)
goto bad_inode;
set_obj_created(oi);
/* copy stuff from on-disk struct to in-memory struct */
inode->i_mode = le16_to_cpu(fcb.i_mode);
inode->i_uid = le32_to_cpu(fcb.i_uid);
inode->i_gid = le32_to_cpu(fcb.i_gid);
inode->i_nlink = le16_to_cpu(fcb.i_links_count);
inode->i_ctime.tv_sec = (signed)le32_to_cpu(fcb.i_ctime);
inode->i_atime.tv_sec = (signed)le32_to_cpu(fcb.i_atime);
inode->i_mtime.tv_sec = (signed)le32_to_cpu(fcb.i_mtime);
inode->i_ctime.tv_nsec =
inode->i_atime.tv_nsec = inode->i_mtime.tv_nsec = 0;
oi->i_commit_size = le64_to_cpu(fcb.i_size);
i_size_write(inode, oi->i_commit_size);
inode->i_blkbits = EXOFS_BLKSHIFT;
inode->i_generation = le32_to_cpu(fcb.i_generation);
oi->i_dir_start_lookup = 0;
if ((inode->i_nlink == 0) && (inode->i_mode == 0)) {
ret = -ESTALE;
goto bad_inode;
}
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
if (fcb.i_data[0])
inode->i_rdev =
old_decode_dev(le32_to_cpu(fcb.i_data[0]));
else
inode->i_rdev =
new_decode_dev(le32_to_cpu(fcb.i_data[1]));
} else {
memcpy(oi->i_data, fcb.i_data, sizeof(fcb.i_data));
}
inode->i_mapping->backing_dev_info = sb->s_bdi;
if (S_ISREG(inode->i_mode)) {
inode->i_op = &exofs_file_inode_operations;
inode->i_fop = &exofs_file_operations;
inode->i_mapping->a_ops = &exofs_aops;
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &exofs_dir_inode_operations;
inode->i_fop = &exofs_dir_operations;
inode->i_mapping->a_ops = &exofs_aops;
} else if (S_ISLNK(inode->i_mode)) {
if (exofs_inode_is_fast_symlink(inode))
inode->i_op = &exofs_fast_symlink_inode_operations;
else {
inode->i_op = &exofs_symlink_inode_operations;
inode->i_mapping->a_ops = &exofs_aops;
}
} else {
inode->i_op = &exofs_special_inode_operations;
if (fcb.i_data[0])
init_special_inode(inode, inode->i_mode,
old_decode_dev(le32_to_cpu(fcb.i_data[0])));
else
init_special_inode(inode, inode->i_mode,
new_decode_dev(le32_to_cpu(fcb.i_data[1])));
}
unlock_new_inode(inode);
return inode;
bad_inode:
iget_failed(inode);
return ERR_PTR(ret);
}
int __exofs_wait_obj_created(struct exofs_i_info *oi)
{
if (!obj_created(oi)) {
EXOFS_DBGMSG("!obj_created\n");
BUG_ON(!obj_2bcreated(oi));
wait_event(oi->i_wq, obj_created(oi));
EXOFS_DBGMSG("wait_event done\n");
}
return unlikely(is_bad_inode(&oi->vfs_inode)) ? -EIO : 0;
}
/*
* Callback function from exofs_new_inode(). The important thing is that we
* set the obj_created flag so that other methods know that the object exists on
* the OSD.
*/
static void create_done(struct exofs_io_state *ios, void *p)
{
struct inode *inode = p;
struct exofs_i_info *oi = exofs_i(inode);
struct exofs_sb_info *sbi = inode->i_sb->s_fs_info;
int ret;
ret = exofs_check_io(ios, NULL);
exofs_put_io_state(ios);
atomic_dec(&sbi->s_curr_pending);
if (unlikely(ret)) {
EXOFS_ERR("object=0x%llx creation failed in pid=0x%llx",
_LLU(exofs_oi_objno(oi)), _LLU(sbi->layout.s_pid));
/*TODO: When FS is corrupted creation can fail, object already
* exist. Get rid of this asynchronous creation, if exist
* increment the obj counter and try the next object. Until we
* succeed. All these dangling objects will be made into lost
* files by chkfs.exofs
*/
}
set_obj_created(oi);
wake_up(&oi->i_wq);
}
/*
* Set up a new inode and create an object for it on the OSD
*/
struct inode *exofs_new_inode(struct inode *dir, int mode)
{
struct super_block *sb;
struct inode *inode;
struct exofs_i_info *oi;
struct exofs_sb_info *sbi;
struct exofs_io_state *ios;
int ret;
sb = dir->i_sb;
inode = new_inode(sb);
if (!inode)
return ERR_PTR(-ENOMEM);
oi = exofs_i(inode);
__oi_init(oi);
set_obj_2bcreated(oi);
sbi = sb->s_fs_info;
inode->i_mapping->backing_dev_info = sb->s_bdi;
inode_init_owner(inode, dir, mode);
inode->i_ino = sbi->s_nextid++;
inode->i_blkbits = EXOFS_BLKSHIFT;
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
oi->i_commit_size = inode->i_size = 0;
spin_lock(&sbi->s_next_gen_lock);
inode->i_generation = sbi->s_next_generation++;
spin_unlock(&sbi->s_next_gen_lock);
insert_inode_hash(inode);
exofs_sbi_write_stats(sbi); /* Make sure new sbi->s_nextid is on disk */
mark_inode_dirty(inode);
ret = exofs_get_io_state(&sbi->layout, &ios);
if (unlikely(ret)) {
EXOFS_ERR("exofs_new_inode: exofs_get_io_state failed\n");
return ERR_PTR(ret);
}
ios->obj.id = exofs_oi_objno(oi);
exofs_make_credential(oi->i_cred, &ios->obj);
ios->done = create_done;
ios->private = inode;
ios->cred = oi->i_cred;
ret = exofs_sbi_create(ios);
if (ret) {
exofs_put_io_state(ios);
return ERR_PTR(ret);
}
atomic_inc(&sbi->s_curr_pending);
return inode;
}
/*
* struct to pass two arguments to update_inode's callback
*/
struct updatei_args {
struct exofs_sb_info *sbi;
struct exofs_fcb fcb;
};
/*
* Callback function from exofs_update_inode().
*/
static void updatei_done(struct exofs_io_state *ios, void *p)
{
struct updatei_args *args = p;
exofs_put_io_state(ios);
atomic_dec(&args->sbi->s_curr_pending);
kfree(args);
}
/*
* Write the inode to the OSD. Just fill up the struct, and set the attribute
* synchronously or asynchronously depending on the do_sync flag.
*/
static int exofs_update_inode(struct inode *inode, int do_sync)
{
struct exofs_i_info *oi = exofs_i(inode);
struct super_block *sb = inode->i_sb;
struct exofs_sb_info *sbi = sb->s_fs_info;
struct exofs_io_state *ios;
struct osd_attr attr;
struct exofs_fcb *fcb;
struct updatei_args *args;
int ret;
args = kzalloc(sizeof(*args), GFP_KERNEL);
if (!args) {
EXOFS_DBGMSG("Failed kzalloc of args\n");
return -ENOMEM;
}
fcb = &args->fcb;
fcb->i_mode = cpu_to_le16(inode->i_mode);
fcb->i_uid = cpu_to_le32(inode->i_uid);
fcb->i_gid = cpu_to_le32(inode->i_gid);
fcb->i_links_count = cpu_to_le16(inode->i_nlink);
fcb->i_ctime = cpu_to_le32(inode->i_ctime.tv_sec);
fcb->i_atime = cpu_to_le32(inode->i_atime.tv_sec);
fcb->i_mtime = cpu_to_le32(inode->i_mtime.tv_sec);
oi->i_commit_size = i_size_read(inode);
fcb->i_size = cpu_to_le64(oi->i_commit_size);
fcb->i_generation = cpu_to_le32(inode->i_generation);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
if (old_valid_dev(inode->i_rdev)) {
fcb->i_data[0] =
cpu_to_le32(old_encode_dev(inode->i_rdev));
fcb->i_data[1] = 0;
} else {
fcb->i_data[0] = 0;
fcb->i_data[1] =
cpu_to_le32(new_encode_dev(inode->i_rdev));
fcb->i_data[2] = 0;
}
} else
memcpy(fcb->i_data, oi->i_data, sizeof(fcb->i_data));
ret = exofs_get_io_state(&sbi->layout, &ios);
if (unlikely(ret)) {
EXOFS_ERR("%s: exofs_get_io_state failed.\n", __func__);
goto free_args;
}
attr = g_attr_inode_data;
attr.val_ptr = fcb;
ios->out_attr_len = 1;
ios->out_attr = &attr;
wait_obj_created(oi);
if (!do_sync) {
args->sbi = sbi;
ios->done = updatei_done;
ios->private = args;
}
ret = exofs_oi_write(oi, ios);
if (!do_sync && !ret) {
atomic_inc(&sbi->s_curr_pending);
goto out; /* deallocation in updatei_done */
}
exofs_put_io_state(ios);
free_args:
kfree(args);
out:
EXOFS_DBGMSG("(0x%lx) do_sync=%d ret=>%d\n",
inode->i_ino, do_sync, ret);
return ret;
}
int exofs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
/* FIXME: fix fsync and use wbc->sync_mode == WB_SYNC_ALL */
return exofs_update_inode(inode, 1);
}
/*
* Callback function from exofs_delete_inode() - don't have much cleaning up to
* do.
*/
static void delete_done(struct exofs_io_state *ios, void *p)
{
struct exofs_sb_info *sbi = p;
exofs_put_io_state(ios);
atomic_dec(&sbi->s_curr_pending);
}
/*
* Called when the refcount of an inode reaches zero. We remove the object
* from the OSD here. We make sure the object was created before we try and
* delete it.
*/
void exofs_evict_inode(struct inode *inode)
{
struct exofs_i_info *oi = exofs_i(inode);
struct super_block *sb = inode->i_sb;
struct exofs_sb_info *sbi = sb->s_fs_info;
struct exofs_io_state *ios;
int ret;
truncate_inode_pages(&inode->i_data, 0);
/* TODO: should do better here */
if (inode->i_nlink || is_bad_inode(inode))
goto no_delete;
inode->i_size = 0;
end_writeback(inode);
/* if we are deleting an obj that hasn't been created yet, wait.
* This also makes sure that create_done cannot be called with an
* already evicted inode.
*/
wait_obj_created(oi);
/* ignore the error, attempt a remove anyway */
/* Now Remove the OSD objects */
ret = exofs_get_io_state(&sbi->layout, &ios);
if (unlikely(ret)) {
EXOFS_ERR("%s: exofs_get_io_state failed\n", __func__);
return;
}
ios->obj.id = exofs_oi_objno(oi);
ios->done = delete_done;
ios->private = sbi;
ios->cred = oi->i_cred;
ret = exofs_sbi_remove(ios);
if (ret) {
EXOFS_ERR("%s: exofs_sbi_remove failed\n", __func__);
exofs_put_io_state(ios);
return;
}
atomic_inc(&sbi->s_curr_pending);
return;
no_delete:
end_writeback(inode);
}
| gpl-2.0 |
CyanogenMod/android_kernel_bn_encore | drivers/net/tulip/media.c | 2767 | 16803 | /*
drivers/net/tulip/media.c
Copyright 2000,2001 The Linux Kernel Team
Written/copyright 1994-2001 by Donald Becker.
This software may be used and distributed according to the terms
of the GNU General Public License, incorporated herein by reference.
Please refer to Documentation/DocBook/tulip-user.{pdf,ps,html}
for more information on this driver.
Please submit bugs to http://bugzilla.kernel.org/ .
*/
#include <linux/kernel.h>
#include <linux/mii.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include "tulip.h"
/* The maximum data clock rate is 2.5 Mhz. The minimum timing is usually
met by back-to-back PCI I/O cycles, but we insert a delay to avoid
"overclocking" issues or future 66Mhz PCI. */
#define mdio_delay() ioread32(mdio_addr)
/* Read and write the MII registers using software-generated serial
MDIO protocol. It is just different enough from the EEPROM protocol
to not share code. The maxium data clock rate is 2.5 Mhz. */
#define MDIO_SHIFT_CLK 0x10000
#define MDIO_DATA_WRITE0 0x00000
#define MDIO_DATA_WRITE1 0x20000
#define MDIO_ENB 0x00000 /* Ignore the 0x02000 databook setting. */
#define MDIO_ENB_IN 0x40000
#define MDIO_DATA_READ 0x80000
static const unsigned char comet_miireg2offset[32] = {
0xB4, 0xB8, 0xBC, 0xC0, 0xC4, 0xC8, 0xCC, 0, 0,0,0,0, 0,0,0,0,
0,0xD0,0,0, 0,0,0,0, 0,0,0,0, 0, 0xD4, 0xD8, 0xDC, };
/* MII transceiver control section.
Read and write the MII registers using software-generated serial
MDIO protocol.
See IEEE 802.3-2002.pdf (Section 2, Chapter "22.2.4 Management functions")
or DP83840A data sheet for more details.
*/
int tulip_mdio_read(struct net_device *dev, int phy_id, int location)
{
struct tulip_private *tp = netdev_priv(dev);
int i;
int read_cmd = (0xf6 << 10) | ((phy_id & 0x1f) << 5) | location;
int retval = 0;
void __iomem *ioaddr = tp->base_addr;
void __iomem *mdio_addr = ioaddr + CSR9;
unsigned long flags;
if (location & ~0x1f)
return 0xffff;
if (tp->chip_id == COMET && phy_id == 30) {
if (comet_miireg2offset[location])
return ioread32(ioaddr + comet_miireg2offset[location]);
return 0xffff;
}
spin_lock_irqsave(&tp->mii_lock, flags);
if (tp->chip_id == LC82C168) {
iowrite32(0x60020000 + (phy_id<<23) + (location<<18), ioaddr + 0xA0);
ioread32(ioaddr + 0xA0);
ioread32(ioaddr + 0xA0);
for (i = 1000; i >= 0; --i) {
barrier();
if ( ! ((retval = ioread32(ioaddr + 0xA0)) & 0x80000000))
break;
}
spin_unlock_irqrestore(&tp->mii_lock, flags);
return retval & 0xffff;
}
/* Establish sync by sending at least 32 logic ones. */
for (i = 32; i >= 0; i--) {
iowrite32(MDIO_ENB | MDIO_DATA_WRITE1, mdio_addr);
mdio_delay();
iowrite32(MDIO_ENB | MDIO_DATA_WRITE1 | MDIO_SHIFT_CLK, mdio_addr);
mdio_delay();
}
/* Shift the read command bits out. */
for (i = 15; i >= 0; i--) {
int dataval = (read_cmd & (1 << i)) ? MDIO_DATA_WRITE1 : 0;
iowrite32(MDIO_ENB | dataval, mdio_addr);
mdio_delay();
iowrite32(MDIO_ENB | dataval | MDIO_SHIFT_CLK, mdio_addr);
mdio_delay();
}
/* Read the two transition, 16 data, and wire-idle bits. */
for (i = 19; i > 0; i--) {
iowrite32(MDIO_ENB_IN, mdio_addr);
mdio_delay();
retval = (retval << 1) | ((ioread32(mdio_addr) & MDIO_DATA_READ) ? 1 : 0);
iowrite32(MDIO_ENB_IN | MDIO_SHIFT_CLK, mdio_addr);
mdio_delay();
}
spin_unlock_irqrestore(&tp->mii_lock, flags);
return (retval>>1) & 0xffff;
}
void tulip_mdio_write(struct net_device *dev, int phy_id, int location, int val)
{
struct tulip_private *tp = netdev_priv(dev);
int i;
int cmd = (0x5002 << 16) | ((phy_id & 0x1f) << 23) | (location<<18) | (val & 0xffff);
void __iomem *ioaddr = tp->base_addr;
void __iomem *mdio_addr = ioaddr + CSR9;
unsigned long flags;
if (location & ~0x1f)
return;
if (tp->chip_id == COMET && phy_id == 30) {
if (comet_miireg2offset[location])
iowrite32(val, ioaddr + comet_miireg2offset[location]);
return;
}
spin_lock_irqsave(&tp->mii_lock, flags);
if (tp->chip_id == LC82C168) {
iowrite32(cmd, ioaddr + 0xA0);
for (i = 1000; i >= 0; --i) {
barrier();
if ( ! (ioread32(ioaddr + 0xA0) & 0x80000000))
break;
}
spin_unlock_irqrestore(&tp->mii_lock, flags);
return;
}
/* Establish sync by sending 32 logic ones. */
for (i = 32; i >= 0; i--) {
iowrite32(MDIO_ENB | MDIO_DATA_WRITE1, mdio_addr);
mdio_delay();
iowrite32(MDIO_ENB | MDIO_DATA_WRITE1 | MDIO_SHIFT_CLK, mdio_addr);
mdio_delay();
}
/* Shift the command bits out. */
for (i = 31; i >= 0; i--) {
int dataval = (cmd & (1 << i)) ? MDIO_DATA_WRITE1 : 0;
iowrite32(MDIO_ENB | dataval, mdio_addr);
mdio_delay();
iowrite32(MDIO_ENB | dataval | MDIO_SHIFT_CLK, mdio_addr);
mdio_delay();
}
/* Clear out extra bits. */
for (i = 2; i > 0; i--) {
iowrite32(MDIO_ENB_IN, mdio_addr);
mdio_delay();
iowrite32(MDIO_ENB_IN | MDIO_SHIFT_CLK, mdio_addr);
mdio_delay();
}
spin_unlock_irqrestore(&tp->mii_lock, flags);
}
/* Set up the transceiver control registers for the selected media type. */
void tulip_select_media(struct net_device *dev, int startup)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
struct mediatable *mtable = tp->mtable;
u32 new_csr6;
int i;
if (mtable) {
struct medialeaf *mleaf = &mtable->mleaf[tp->cur_index];
unsigned char *p = mleaf->leafdata;
switch (mleaf->type) {
case 0: /* 21140 non-MII xcvr. */
if (tulip_debug > 1)
netdev_dbg(dev, "Using a 21140 non-MII transceiver with control setting %02x\n",
p[1]);
dev->if_port = p[0];
if (startup)
iowrite32(mtable->csr12dir | 0x100, ioaddr + CSR12);
iowrite32(p[1], ioaddr + CSR12);
new_csr6 = 0x02000000 | ((p[2] & 0x71) << 18);
break;
case 2: case 4: {
u16 setup[5];
u32 csr13val, csr14val, csr15dir, csr15val;
for (i = 0; i < 5; i++)
setup[i] = get_u16(&p[i*2 + 1]);
dev->if_port = p[0] & MEDIA_MASK;
if (tulip_media_cap[dev->if_port] & MediaAlwaysFD)
tp->full_duplex = 1;
if (startup && mtable->has_reset) {
struct medialeaf *rleaf = &mtable->mleaf[mtable->has_reset];
unsigned char *rst = rleaf->leafdata;
if (tulip_debug > 1)
netdev_dbg(dev, "Resetting the transceiver\n");
for (i = 0; i < rst[0]; i++)
iowrite32(get_u16(rst + 1 + (i<<1)) << 16, ioaddr + CSR15);
}
if (tulip_debug > 1)
netdev_dbg(dev, "21143 non-MII %s transceiver control %04x/%04x\n",
medianame[dev->if_port],
setup[0], setup[1]);
if (p[0] & 0x40) { /* SIA (CSR13-15) setup values are provided. */
csr13val = setup[0];
csr14val = setup[1];
csr15dir = (setup[3]<<16) | setup[2];
csr15val = (setup[4]<<16) | setup[2];
iowrite32(0, ioaddr + CSR13);
iowrite32(csr14val, ioaddr + CSR14);
iowrite32(csr15dir, ioaddr + CSR15); /* Direction */
iowrite32(csr15val, ioaddr + CSR15); /* Data */
iowrite32(csr13val, ioaddr + CSR13);
} else {
csr13val = 1;
csr14val = 0;
csr15dir = (setup[0]<<16) | 0x0008;
csr15val = (setup[1]<<16) | 0x0008;
if (dev->if_port <= 4)
csr14val = t21142_csr14[dev->if_port];
if (startup) {
iowrite32(0, ioaddr + CSR13);
iowrite32(csr14val, ioaddr + CSR14);
}
iowrite32(csr15dir, ioaddr + CSR15); /* Direction */
iowrite32(csr15val, ioaddr + CSR15); /* Data */
if (startup) iowrite32(csr13val, ioaddr + CSR13);
}
if (tulip_debug > 1)
netdev_dbg(dev, "Setting CSR15 to %08x/%08x\n",
csr15dir, csr15val);
if (mleaf->type == 4)
new_csr6 = 0x82020000 | ((setup[2] & 0x71) << 18);
else
new_csr6 = 0x82420000;
break;
}
case 1: case 3: {
int phy_num = p[0];
int init_length = p[1];
u16 *misc_info, tmp_info;
dev->if_port = 11;
new_csr6 = 0x020E0000;
if (mleaf->type == 3) { /* 21142 */
u16 *init_sequence = (u16*)(p+2);
u16 *reset_sequence = &((u16*)(p+3))[init_length];
int reset_length = p[2 + init_length*2];
misc_info = reset_sequence + reset_length;
if (startup) {
int timeout = 10; /* max 1 ms */
for (i = 0; i < reset_length; i++)
iowrite32(get_u16(&reset_sequence[i]) << 16, ioaddr + CSR15);
/* flush posted writes */
ioread32(ioaddr + CSR15);
/* Sect 3.10.3 in DP83840A.pdf (p39) */
udelay(500);
/* Section 4.2 in DP83840A.pdf (p43) */
/* and IEEE 802.3 "22.2.4.1.1 Reset" */
while (timeout-- &&
(tulip_mdio_read (dev, phy_num, MII_BMCR) & BMCR_RESET))
udelay(100);
}
for (i = 0; i < init_length; i++)
iowrite32(get_u16(&init_sequence[i]) << 16, ioaddr + CSR15);
ioread32(ioaddr + CSR15); /* flush posted writes */
} else {
u8 *init_sequence = p + 2;
u8 *reset_sequence = p + 3 + init_length;
int reset_length = p[2 + init_length];
misc_info = (u16*)(reset_sequence + reset_length);
if (startup) {
int timeout = 10; /* max 1 ms */
iowrite32(mtable->csr12dir | 0x100, ioaddr + CSR12);
for (i = 0; i < reset_length; i++)
iowrite32(reset_sequence[i], ioaddr + CSR12);
/* flush posted writes */
ioread32(ioaddr + CSR12);
/* Sect 3.10.3 in DP83840A.pdf (p39) */
udelay(500);
/* Section 4.2 in DP83840A.pdf (p43) */
/* and IEEE 802.3 "22.2.4.1.1 Reset" */
while (timeout-- &&
(tulip_mdio_read (dev, phy_num, MII_BMCR) & BMCR_RESET))
udelay(100);
}
for (i = 0; i < init_length; i++)
iowrite32(init_sequence[i], ioaddr + CSR12);
ioread32(ioaddr + CSR12); /* flush posted writes */
}
tmp_info = get_u16(&misc_info[1]);
if (tmp_info)
tp->advertising[phy_num] = tmp_info | 1;
if (tmp_info && startup < 2) {
if (tp->mii_advertise == 0)
tp->mii_advertise = tp->advertising[phy_num];
if (tulip_debug > 1)
netdev_dbg(dev, " Advertising %04x on MII %d\n",
tp->mii_advertise,
tp->phys[phy_num]);
tulip_mdio_write(dev, tp->phys[phy_num], 4, tp->mii_advertise);
}
break;
}
case 5: case 6: {
u16 setup[5];
new_csr6 = 0; /* FIXME */
for (i = 0; i < 5; i++)
setup[i] = get_u16(&p[i*2 + 1]);
if (startup && mtable->has_reset) {
struct medialeaf *rleaf = &mtable->mleaf[mtable->has_reset];
unsigned char *rst = rleaf->leafdata;
if (tulip_debug > 1)
netdev_dbg(dev, "Resetting the transceiver\n");
for (i = 0; i < rst[0]; i++)
iowrite32(get_u16(rst + 1 + (i<<1)) << 16, ioaddr + CSR15);
}
break;
}
default:
netdev_dbg(dev, " Invalid media table selection %d\n",
mleaf->type);
new_csr6 = 0x020E0000;
}
if (tulip_debug > 1)
netdev_dbg(dev, "Using media type %s, CSR12 is %02x\n",
medianame[dev->if_port],
ioread32(ioaddr + CSR12) & 0xff);
} else if (tp->chip_id == LC82C168) {
if (startup && ! tp->medialock)
dev->if_port = tp->mii_cnt ? 11 : 0;
if (tulip_debug > 1)
netdev_dbg(dev, "PNIC PHY status is %3.3x, media %s\n",
ioread32(ioaddr + 0xB8),
medianame[dev->if_port]);
if (tp->mii_cnt) {
new_csr6 = 0x810C0000;
iowrite32(0x0001, ioaddr + CSR15);
iowrite32(0x0201B07A, ioaddr + 0xB8);
} else if (startup) {
/* Start with 10mbps to do autonegotiation. */
iowrite32(0x32, ioaddr + CSR12);
new_csr6 = 0x00420000;
iowrite32(0x0001B078, ioaddr + 0xB8);
iowrite32(0x0201B078, ioaddr + 0xB8);
} else if (dev->if_port == 3 || dev->if_port == 5) {
iowrite32(0x33, ioaddr + CSR12);
new_csr6 = 0x01860000;
/* Trigger autonegotiation. */
iowrite32(startup ? 0x0201F868 : 0x0001F868, ioaddr + 0xB8);
} else {
iowrite32(0x32, ioaddr + CSR12);
new_csr6 = 0x00420000;
iowrite32(0x1F078, ioaddr + 0xB8);
}
} else { /* Unknown chip type with no media table. */
if (tp->default_port == 0)
dev->if_port = tp->mii_cnt ? 11 : 3;
if (tulip_media_cap[dev->if_port] & MediaIsMII) {
new_csr6 = 0x020E0000;
} else if (tulip_media_cap[dev->if_port] & MediaIsFx) {
new_csr6 = 0x02860000;
} else
new_csr6 = 0x03860000;
if (tulip_debug > 1)
netdev_dbg(dev, "No media description table, assuming %s transceiver, CSR12 %02x\n",
medianame[dev->if_port],
ioread32(ioaddr + CSR12));
}
tp->csr6 = new_csr6 | (tp->csr6 & 0xfdff) | (tp->full_duplex ? 0x0200 : 0);
mdelay(1);
}
/*
Check the MII negotiated duplex and change the CSR6 setting if
required.
Return 0 if everything is OK.
Return < 0 if the transceiver is missing or has no link beat.
*/
int tulip_check_duplex(struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
unsigned int bmsr, lpa, negotiated, new_csr6;
bmsr = tulip_mdio_read(dev, tp->phys[0], MII_BMSR);
lpa = tulip_mdio_read(dev, tp->phys[0], MII_LPA);
if (tulip_debug > 1)
dev_info(&dev->dev, "MII status %04x, Link partner report %04x\n",
bmsr, lpa);
if (bmsr == 0xffff)
return -2;
if ((bmsr & BMSR_LSTATUS) == 0) {
int new_bmsr = tulip_mdio_read(dev, tp->phys[0], MII_BMSR);
if ((new_bmsr & BMSR_LSTATUS) == 0) {
if (tulip_debug > 1)
dev_info(&dev->dev,
"No link beat on the MII interface, status %04x\n",
new_bmsr);
return -1;
}
}
negotiated = lpa & tp->advertising[0];
tp->full_duplex = mii_duplex(tp->full_duplex_lock, negotiated);
new_csr6 = tp->csr6;
if (negotiated & LPA_100) new_csr6 &= ~TxThreshold;
else new_csr6 |= TxThreshold;
if (tp->full_duplex) new_csr6 |= FullDuplex;
else new_csr6 &= ~FullDuplex;
if (new_csr6 != tp->csr6) {
tp->csr6 = new_csr6;
tulip_restart_rxtx(tp);
if (tulip_debug > 0)
dev_info(&dev->dev,
"Setting %s-duplex based on MII#%d link partner capability of %04x\n",
tp->full_duplex ? "full" : "half",
tp->phys[0], lpa);
return 1;
}
return 0;
}
void __devinit tulip_find_mii (struct net_device *dev, int board_idx)
{
struct tulip_private *tp = netdev_priv(dev);
int phyn, phy_idx = 0;
int mii_reg0;
int mii_advert;
unsigned int to_advert, new_bmcr, ane_switch;
/* Find the connected MII xcvrs.
Doing this in open() would allow detecting external xcvrs later,
but takes much time. */
for (phyn = 1; phyn <= 32 && phy_idx < sizeof (tp->phys); phyn++) {
int phy = phyn & 0x1f;
int mii_status = tulip_mdio_read (dev, phy, MII_BMSR);
if ((mii_status & 0x8301) == 0x8001 ||
((mii_status & BMSR_100BASE4) == 0 &&
(mii_status & 0x7800) != 0)) {
/* preserve Becker logic, gain indentation level */
} else {
continue;
}
mii_reg0 = tulip_mdio_read (dev, phy, MII_BMCR);
mii_advert = tulip_mdio_read (dev, phy, MII_ADVERTISE);
ane_switch = 0;
/* if not advertising at all, gen an
* advertising value from the capability
* bits in BMSR
*/
if ((mii_advert & ADVERTISE_ALL) == 0) {
unsigned int tmpadv = tulip_mdio_read (dev, phy, MII_BMSR);
mii_advert = ((tmpadv >> 6) & 0x3e0) | 1;
}
if (tp->mii_advertise) {
tp->advertising[phy_idx] =
to_advert = tp->mii_advertise;
} else if (tp->advertising[phy_idx]) {
to_advert = tp->advertising[phy_idx];
} else {
tp->advertising[phy_idx] =
tp->mii_advertise =
to_advert = mii_advert;
}
tp->phys[phy_idx++] = phy;
pr_info("tulip%d: MII transceiver #%d config %04x status %04x advertising %04x\n",
board_idx, phy, mii_reg0, mii_status, mii_advert);
/* Fixup for DLink with miswired PHY. */
if (mii_advert != to_advert) {
pr_debug("tulip%d: Advertising %04x on PHY %d, previously advertising %04x\n",
board_idx, to_advert, phy, mii_advert);
tulip_mdio_write (dev, phy, 4, to_advert);
}
/* Enable autonegotiation: some boards default to off. */
if (tp->default_port == 0) {
new_bmcr = mii_reg0 | BMCR_ANENABLE;
if (new_bmcr != mii_reg0) {
new_bmcr |= BMCR_ANRESTART;
ane_switch = 1;
}
}
/* ...or disable nway, if forcing media */
else {
new_bmcr = mii_reg0 & ~BMCR_ANENABLE;
if (new_bmcr != mii_reg0)
ane_switch = 1;
}
/* clear out bits we never want at this point */
new_bmcr &= ~(BMCR_CTST | BMCR_FULLDPLX | BMCR_ISOLATE |
BMCR_PDOWN | BMCR_SPEED100 | BMCR_LOOPBACK |
BMCR_RESET);
if (tp->full_duplex)
new_bmcr |= BMCR_FULLDPLX;
if (tulip_media_cap[tp->default_port] & MediaIs100)
new_bmcr |= BMCR_SPEED100;
if (new_bmcr != mii_reg0) {
/* some phys need the ANE switch to
* happen before forced media settings
* will "take." However, we write the
* same value twice in order not to
* confuse the sane phys.
*/
if (ane_switch) {
tulip_mdio_write (dev, phy, MII_BMCR, new_bmcr);
udelay (10);
}
tulip_mdio_write (dev, phy, MII_BMCR, new_bmcr);
}
}
tp->mii_cnt = phy_idx;
if (tp->mtable && tp->mtable->has_mii && phy_idx == 0) {
pr_info("tulip%d: ***WARNING***: No MII transceiver found!\n",
board_idx);
tp->phys[0] = 1;
}
}
| gpl-2.0 |
Tasssadar/android_kernel_asus_grouper | drivers/staging/rtl8712/rtl8712_recv.c | 2767 | 35638 | /******************************************************************************
* rtl8712_recv.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL8712_RECV_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "recv_osdep.h"
#include "mlme_osdep.h"
#include "ip.h"
#include "if_ether.h"
#include "ethernet.h"
#include "usb_ops.h"
#include "wifi.h"
/* Bridge-Tunnel header (for EtherTypes ETH_P_AARP and ETH_P_IPX) */
static u8 bridge_tunnel_header[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0xf8};
/* Ethernet-II snap header (RFC1042 for most EtherTypes) */
static u8 rfc1042_header[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
static void recv_tasklet(void *priv);
int r8712_init_recv_priv(struct recv_priv *precvpriv, struct _adapter *padapter)
{
int i;
struct recv_buf *precvbuf;
int res = _SUCCESS;
addr_t tmpaddr = 0;
int alignment = 0;
struct sk_buff *pskb = NULL;
sema_init(&precvpriv->recv_sema, 0);
sema_init(&precvpriv->terminate_recvthread_sema, 0);
/*init recv_buf*/
_init_queue(&precvpriv->free_recv_buf_queue);
precvpriv->pallocated_recv_buf = _malloc(NR_RECVBUFF *
sizeof(struct recv_buf) + 4);
if (precvpriv->pallocated_recv_buf == NULL)
return _FAIL;
memset(precvpriv->pallocated_recv_buf, 0, NR_RECVBUFF *
sizeof(struct recv_buf) + 4);
precvpriv->precv_buf = precvpriv->pallocated_recv_buf + 4 -
((addr_t) (precvpriv->pallocated_recv_buf) & 3);
precvbuf = (struct recv_buf *)precvpriv->precv_buf;
for (i = 0; i < NR_RECVBUFF; i++) {
_init_listhead(&precvbuf->list);
spin_lock_init(&precvbuf->recvbuf_lock);
res = r8712_os_recvbuf_resource_alloc(padapter, precvbuf);
if (res == _FAIL)
break;
precvbuf->ref_cnt = 0;
precvbuf->adapter = padapter;
list_insert_tail(&precvbuf->list,
&(precvpriv->free_recv_buf_queue.queue));
precvbuf++;
}
precvpriv->free_recv_buf_queue_cnt = NR_RECVBUFF;
tasklet_init(&precvpriv->recv_tasklet,
(void(*)(unsigned long))recv_tasklet,
(unsigned long)padapter);
skb_queue_head_init(&precvpriv->rx_skb_queue);
skb_queue_head_init(&precvpriv->free_recv_skb_queue);
for (i = 0; i < NR_PREALLOC_RECV_SKB; i++) {
pskb = netdev_alloc_skb(padapter->pnetdev, MAX_RECVBUF_SZ +
RECVBUFF_ALIGN_SZ);
if (pskb) {
pskb->dev = padapter->pnetdev;
tmpaddr = (addr_t)pskb->data;
alignment = tmpaddr & (RECVBUFF_ALIGN_SZ-1);
skb_reserve(pskb, (RECVBUFF_ALIGN_SZ - alignment));
skb_queue_tail(&precvpriv->free_recv_skb_queue, pskb);
}
pskb = NULL;
}
return res;
}
void r8712_free_recv_priv(struct recv_priv *precvpriv)
{
int i;
struct recv_buf *precvbuf;
struct _adapter *padapter = precvpriv->adapter;
precvbuf = (struct recv_buf *)precvpriv->precv_buf;
for (i = 0; i < NR_RECVBUFF ; i++) {
r8712_os_recvbuf_resource_free(padapter, precvbuf);
precvbuf++;
}
kfree(precvpriv->pallocated_recv_buf);
skb_queue_purge(&precvpriv->rx_skb_queue);
if (skb_queue_len(&precvpriv->rx_skb_queue))
printk(KERN_WARNING "r8712u: rx_skb_queue not empty\n");
skb_queue_purge(&precvpriv->free_recv_skb_queue);
if (skb_queue_len(&precvpriv->free_recv_skb_queue))
printk(KERN_WARNING "r8712u: free_recv_skb_queue not empty "
"%d\n", skb_queue_len(&precvpriv->free_recv_skb_queue));
}
int r8712_init_recvbuf(struct _adapter *padapter, struct recv_buf *precvbuf)
{
int res = _SUCCESS;
precvbuf->transfer_len = 0;
precvbuf->len = 0;
precvbuf->ref_cnt = 0;
if (precvbuf->pbuf) {
precvbuf->pdata = precvbuf->pbuf;
precvbuf->phead = precvbuf->pbuf;
precvbuf->ptail = precvbuf->pbuf;
precvbuf->pend = precvbuf->pdata + MAX_RECVBUF_SZ;
}
return res;
}
int r8712_free_recvframe(union recv_frame *precvframe,
struct __queue *pfree_recv_queue)
{
unsigned long irqL;
struct _adapter *padapter = precvframe->u.hdr.adapter;
struct recv_priv *precvpriv = &padapter->recvpriv;
if (precvframe->u.hdr.pkt) {
dev_kfree_skb_any(precvframe->u.hdr.pkt);/*free skb by driver*/
precvframe->u.hdr.pkt = NULL;
}
spin_lock_irqsave(&pfree_recv_queue->lock, irqL);
list_delete(&(precvframe->u.hdr.list));
list_insert_tail(&(precvframe->u.hdr.list),
get_list_head(pfree_recv_queue));
if (padapter != NULL) {
if (pfree_recv_queue == &precvpriv->free_recv_queue)
precvpriv->free_recvframe_cnt++;
}
spin_unlock_irqrestore(&pfree_recv_queue->lock, irqL);
return _SUCCESS;
}
static void update_recvframe_attrib_from_recvstat(struct rx_pkt_attrib *pattrib,
struct recv_stat *prxstat)
{
u32 *pphy_info;
struct phy_stat *pphy_stat;
u16 drvinfo_sz = 0;
drvinfo_sz = (le32_to_cpu(prxstat->rxdw0)&0x000f0000)>>16;
drvinfo_sz = drvinfo_sz<<3;
/*TODO:
* Offset 0 */
pattrib->bdecrypted = ((le32_to_cpu(prxstat->rxdw0) & BIT(27)) >> 27)
? 0 : 1;
pattrib->crc_err = ((le32_to_cpu(prxstat->rxdw0) & BIT(14)) >> 14);
/*Offset 4*/
/*Offset 8*/
/*Offset 12*/
if (le32_to_cpu(prxstat->rxdw3) & BIT(13)) {
pattrib->tcpchk_valid = 1; /* valid */
if (le32_to_cpu(prxstat->rxdw3) & BIT(11))
pattrib->tcp_chkrpt = 1; /* correct */
else
pattrib->tcp_chkrpt = 0; /* incorrect */
if (le32_to_cpu(prxstat->rxdw3) & BIT(12))
pattrib->ip_chkrpt = 1; /* correct */
else
pattrib->ip_chkrpt = 0; /* incorrect */
} else
pattrib->tcpchk_valid = 0; /* invalid */
pattrib->mcs_rate = (u8)((le32_to_cpu(prxstat->rxdw3)) & 0x3f);
pattrib->htc = (u8)((le32_to_cpu(prxstat->rxdw3) >> 6) & 0x1);
/*Offset 16*/
/*Offset 20*/
/*phy_info*/
if (drvinfo_sz) {
pphy_stat = (struct phy_stat *)(prxstat+1);
pphy_info = (u32 *)prxstat+1;
}
}
/*perform defrag*/
static union recv_frame *recvframe_defrag(struct _adapter *adapter,
struct __queue *defrag_q)
{
struct list_head *plist, *phead;
u8 wlanhdr_offset;
u8 curfragnum;
struct recv_frame_hdr *pfhdr, *pnfhdr;
union recv_frame *prframe, *pnextrframe;
struct __queue *pfree_recv_queue;
pfree_recv_queue = &adapter->recvpriv.free_recv_queue;
phead = get_list_head(defrag_q);
plist = get_next(phead);
prframe = LIST_CONTAINOR(plist, union recv_frame, u);
list_delete(&prframe->u.list);
pfhdr = &prframe->u.hdr;
curfragnum = 0;
if (curfragnum != pfhdr->attrib.frag_num) {
/*the first fragment number must be 0
*free the whole queue*/
r8712_free_recvframe(prframe, pfree_recv_queue);
prframe = NULL;
goto exit;
}
plist = get_next(phead);
while (end_of_queue_search(phead, plist) == false) {
pnextrframe = LIST_CONTAINOR(plist, union recv_frame, u);
/*check the fragment sequence (2nd ~n fragment frame) */
pnfhdr = &pnextrframe->u.hdr;
curfragnum++;
if (curfragnum != pnfhdr->attrib.frag_num) {
/* the fragment number must increase (after decache)
* release the defrag_q & prframe */
r8712_free_recvframe(prframe, pfree_recv_queue);
prframe = NULL;
goto exit;
}
/* copy the 2nd~n fragment frame's payload to the first fragment
* get the 2nd~last fragment frame's payload */
wlanhdr_offset = pnfhdr->attrib.hdrlen + pnfhdr->attrib.iv_len;
recvframe_pull(pnextrframe, wlanhdr_offset);
/* append to first fragment frame's tail (if privacy frame,
* pull the ICV) */
recvframe_pull_tail(prframe, pfhdr->attrib.icv_len);
memcpy(pfhdr->rx_tail, pnfhdr->rx_data, pnfhdr->len);
recvframe_put(prframe, pnfhdr->len);
pfhdr->attrib.icv_len = pnfhdr->attrib.icv_len;
plist = get_next(plist);
}
exit:
/* free the defrag_q queue and return the prframe */
r8712_free_recvframe_queue(defrag_q, pfree_recv_queue);
return prframe;
}
/* check if need to defrag, if needed queue the frame to defrag_q */
union recv_frame *r8712_recvframe_chk_defrag(struct _adapter *padapter,
union recv_frame *precv_frame)
{
u8 ismfrag;
u8 fragnum;
u8 *psta_addr;
struct recv_frame_hdr *pfhdr;
struct sta_info *psta;
struct sta_priv *pstapriv ;
struct list_head *phead;
union recv_frame *prtnframe = NULL;
struct __queue *pfree_recv_queue, *pdefrag_q;
pstapriv = &padapter->stapriv;
pfhdr = &precv_frame->u.hdr;
pfree_recv_queue = &padapter->recvpriv.free_recv_queue;
/* need to define struct of wlan header frame ctrl */
ismfrag = pfhdr->attrib.mfrag;
fragnum = pfhdr->attrib.frag_num;
psta_addr = pfhdr->attrib.ta;
psta = r8712_get_stainfo(pstapriv, psta_addr);
if (psta == NULL)
pdefrag_q = NULL;
else
pdefrag_q = &psta->sta_recvpriv.defrag_q;
if ((ismfrag == 0) && (fragnum == 0))
prtnframe = precv_frame;/*isn't a fragment frame*/
if (ismfrag == 1) {
/* 0~(n-1) fragment frame
* enqueue to defraf_g */
if (pdefrag_q != NULL) {
if (fragnum == 0) {
/*the first fragment*/
if (_queue_empty(pdefrag_q) == false) {
/*free current defrag_q */
r8712_free_recvframe_queue(pdefrag_q,
pfree_recv_queue);
}
}
/* Then enqueue the 0~(n-1) fragment to the defrag_q */
phead = get_list_head(pdefrag_q);
list_insert_tail(&pfhdr->list, phead);
prtnframe = NULL;
} else {
/* can't find this ta's defrag_queue, so free this
* recv_frame */
r8712_free_recvframe(precv_frame, pfree_recv_queue);
prtnframe = NULL;
}
}
if ((ismfrag == 0) && (fragnum != 0)) {
/* the last fragment frame
* enqueue the last fragment */
if (pdefrag_q != NULL) {
phead = get_list_head(pdefrag_q);
list_insert_tail(&pfhdr->list, phead);
/*call recvframe_defrag to defrag*/
precv_frame = recvframe_defrag(padapter, pdefrag_q);
prtnframe = precv_frame;
} else {
/* can't find this ta's defrag_queue, so free this
* recv_frame */
r8712_free_recvframe(precv_frame, pfree_recv_queue);
prtnframe = NULL;
}
}
if ((prtnframe != NULL) && (prtnframe->u.hdr.attrib.privacy)) {
/* after defrag we must check tkip mic code */
if (r8712_recvframe_chkmic(padapter, prtnframe) == _FAIL) {
r8712_free_recvframe(prtnframe, pfree_recv_queue);
prtnframe = NULL;
}
}
return prtnframe;
}
static int amsdu_to_msdu(struct _adapter *padapter, union recv_frame *prframe)
{
int a_len, padding_len;
u16 eth_type, nSubframe_Length;
u8 nr_subframes, i;
unsigned char *data_ptr, *pdata;
struct rx_pkt_attrib *pattrib;
_pkt *sub_skb, *subframes[MAX_SUBFRAME_COUNT];
struct recv_priv *precvpriv = &padapter->recvpriv;
struct __queue *pfree_recv_queue = &(precvpriv->free_recv_queue);
int ret = _SUCCESS;
nr_subframes = 0;
pattrib = &prframe->u.hdr.attrib;
recvframe_pull(prframe, prframe->u.hdr.attrib.hdrlen);
if (prframe->u.hdr.attrib.iv_len > 0)
recvframe_pull(prframe, prframe->u.hdr.attrib.iv_len);
a_len = prframe->u.hdr.len;
pdata = prframe->u.hdr.rx_data;
while (a_len > ETH_HLEN) {
/* Offset 12 denote 2 mac address */
nSubframe_Length = *((u16 *)(pdata + 12));
/*==m==>change the length order*/
nSubframe_Length = (nSubframe_Length >> 8) +
(nSubframe_Length << 8);
if (a_len < (ETHERNET_HEADER_SIZE + nSubframe_Length)) {
printk(KERN_WARNING "r8712u: nRemain_Length is %d and"
" nSubframe_Length is: %d\n",
a_len, nSubframe_Length);
goto exit;
}
/* move the data point to data content */
pdata += ETH_HLEN;
a_len -= ETH_HLEN;
/* Allocate new skb for releasing to upper layer */
sub_skb = dev_alloc_skb(nSubframe_Length + 12);
skb_reserve(sub_skb, 12);
data_ptr = (u8 *)skb_put(sub_skb, nSubframe_Length);
memcpy(data_ptr, pdata, nSubframe_Length);
subframes[nr_subframes++] = sub_skb;
if (nr_subframes >= MAX_SUBFRAME_COUNT) {
printk(KERN_WARNING "r8712u: ParseSubframe(): Too"
" many Subframes! Packets dropped!\n");
break;
}
pdata += nSubframe_Length;
a_len -= nSubframe_Length;
if (a_len != 0) {
padding_len = 4 - ((nSubframe_Length + ETH_HLEN) & 3);
if (padding_len == 4)
padding_len = 0;
if (a_len < padding_len)
goto exit;
pdata += padding_len;
a_len -= padding_len;
}
}
for (i = 0; i < nr_subframes; i++) {
sub_skb = subframes[i];
/* convert hdr + possible LLC headers into Ethernet header */
eth_type = (sub_skb->data[6] << 8) | sub_skb->data[7];
if (sub_skb->len >= 8 &&
((!memcmp(sub_skb->data, rfc1042_header, SNAP_SIZE) &&
eth_type != ETH_P_AARP && eth_type != ETH_P_IPX) ||
!memcmp(sub_skb->data, bridge_tunnel_header, SNAP_SIZE))) {
/* remove RFC1042 or Bridge-Tunnel encapsulation and
* replace EtherType */
skb_pull(sub_skb, SNAP_SIZE);
memcpy(skb_push(sub_skb, ETH_ALEN), pattrib->src,
ETH_ALEN);
memcpy(skb_push(sub_skb, ETH_ALEN), pattrib->dst,
ETH_ALEN);
} else {
u16 len;
/* Leave Ethernet header part of hdr and full payload */
len = htons(sub_skb->len);
memcpy(skb_push(sub_skb, 2), &len, 2);
memcpy(skb_push(sub_skb, ETH_ALEN), pattrib->src,
ETH_ALEN);
memcpy(skb_push(sub_skb, ETH_ALEN), pattrib->dst,
ETH_ALEN);
}
/* Indicate the packets to upper layer */
if (sub_skb) {
sub_skb->protocol =
eth_type_trans(sub_skb, padapter->pnetdev);
sub_skb->dev = padapter->pnetdev;
if ((pattrib->tcpchk_valid == 1) &&
(pattrib->tcp_chkrpt == 1)) {
sub_skb->ip_summed = CHECKSUM_UNNECESSARY;
} else
sub_skb->ip_summed = CHECKSUM_NONE;
netif_rx(sub_skb);
}
}
exit:
prframe->u.hdr.len = 0;
r8712_free_recvframe(prframe, pfree_recv_queue);
return ret;
}
void r8712_rxcmd_event_hdl(struct _adapter *padapter, void *prxcmdbuf)
{
uint voffset;
u8 *poffset;
u16 pkt_len, cmd_len, drvinfo_sz;
u8 eid, cmd_seq;
struct recv_stat *prxstat;
poffset = (u8 *)prxcmdbuf;
voffset = *(uint *)poffset;
pkt_len = le32_to_cpu(voffset) & 0x00003fff;
prxstat = (struct recv_stat *)prxcmdbuf;
drvinfo_sz = ((le32_to_cpu(prxstat->rxdw0) & 0x000f0000) >> 16);
drvinfo_sz = drvinfo_sz << 3;
poffset += RXDESC_SIZE + drvinfo_sz;
do {
voffset = *(uint *)poffset;
cmd_len = (u16)(le32_to_cpu(voffset) & 0xffff);
cmd_seq = (u8)((le32_to_cpu(voffset) >> 24) & 0x7f);
eid = (u8)((le32_to_cpu(voffset) >> 16) & 0xff);
r8712_event_handle(padapter, (uint *)poffset);
poffset += (cmd_len + 8);/*8 bytes aligment*/
} while (le32_to_cpu(voffset) & BIT(31));
}
static int check_indicate_seq(struct recv_reorder_ctrl *preorder_ctrl,
u16 seq_num)
{
u8 wsize = preorder_ctrl->wsize_b;
u16 wend = (preorder_ctrl->indicate_seq + wsize - 1) % 4096;
/* Rx Reorder initialize condition.*/
if (preorder_ctrl->indicate_seq == 0xffff)
preorder_ctrl->indicate_seq = seq_num;
/* Drop out the packet which SeqNum is smaller than WinStart */
if (SN_LESS(seq_num, preorder_ctrl->indicate_seq))
return false;
/*
* Sliding window manipulation. Conditions includes:
* 1. Incoming SeqNum is equal to WinStart =>Window shift 1
* 2. Incoming SeqNum is larger than the WinEnd => Window shift N
*/
if (SN_EQUAL(seq_num, preorder_ctrl->indicate_seq))
preorder_ctrl->indicate_seq = (preorder_ctrl->indicate_seq +
1) % 4096;
else if (SN_LESS(wend, seq_num)) {
if (seq_num >= (wsize - 1))
preorder_ctrl->indicate_seq = seq_num + 1 - wsize;
else
preorder_ctrl->indicate_seq = 4095 - (wsize -
(seq_num + 1)) + 1;
}
return true;
}
static int enqueue_reorder_recvframe(struct recv_reorder_ctrl *preorder_ctrl,
union recv_frame *prframe)
{
struct list_head *phead, *plist;
union recv_frame *pnextrframe;
struct rx_pkt_attrib *pnextattrib;
struct __queue *ppending_recvframe_queue =
&preorder_ctrl->pending_recvframe_queue;
struct rx_pkt_attrib *pattrib = &prframe->u.hdr.attrib;
phead = get_list_head(ppending_recvframe_queue);
plist = get_next(phead);
while (end_of_queue_search(phead, plist) == false) {
pnextrframe = LIST_CONTAINOR(plist, union recv_frame, u);
pnextattrib = &pnextrframe->u.hdr.attrib;
if (SN_LESS(pnextattrib->seq_num, pattrib->seq_num))
plist = get_next(plist);
else if (SN_EQUAL(pnextattrib->seq_num, pattrib->seq_num))
return false;
else
break;
}
list_delete(&(prframe->u.hdr.list));
list_insert_tail(&(prframe->u.hdr.list), plist);
return true;
}
int r8712_recv_indicatepkts_in_order(struct _adapter *padapter,
struct recv_reorder_ctrl *preorder_ctrl,
int bforced)
{
struct list_head *phead, *plist;
union recv_frame *prframe;
struct rx_pkt_attrib *pattrib;
int bPktInBuf = false;
struct recv_priv *precvpriv = &padapter->recvpriv;
struct __queue *ppending_recvframe_queue =
&preorder_ctrl->pending_recvframe_queue;
phead = get_list_head(ppending_recvframe_queue);
plist = get_next(phead);
/* Handling some condition for forced indicate case.*/
if (bforced == true) {
if (is_list_empty(phead))
return true;
else {
prframe = LIST_CONTAINOR(plist, union recv_frame, u);
pattrib = &prframe->u.hdr.attrib;
preorder_ctrl->indicate_seq = pattrib->seq_num;
}
}
/* Prepare indication list and indication.
* Check if there is any packet need indicate. */
while (!is_list_empty(phead)) {
prframe = LIST_CONTAINOR(plist, union recv_frame, u);
pattrib = &prframe->u.hdr.attrib;
if (!SN_LESS(preorder_ctrl->indicate_seq, pattrib->seq_num)) {
plist = get_next(plist);
list_delete(&(prframe->u.hdr.list));
if (SN_EQUAL(preorder_ctrl->indicate_seq,
pattrib->seq_num))
preorder_ctrl->indicate_seq =
(preorder_ctrl->indicate_seq + 1) % 4096;
/*indicate this recv_frame*/
if (!pattrib->amsdu) {
if ((padapter->bDriverStopped == false) &&
(padapter->bSurpriseRemoved == false)) {
/* indicate this recv_frame */
r8712_recv_indicatepkt(padapter,
prframe);
}
} else if (pattrib->amsdu == 1) {
if (amsdu_to_msdu(padapter, prframe) !=
_SUCCESS)
r8712_free_recvframe(prframe,
&precvpriv->free_recv_queue);
}
/* Update local variables. */
bPktInBuf = false;
} else {
bPktInBuf = true;
break;
}
}
return bPktInBuf;
}
static int recv_indicatepkt_reorder(struct _adapter *padapter,
union recv_frame *prframe)
{
unsigned long irql;
struct rx_pkt_attrib *pattrib = &prframe->u.hdr.attrib;
struct recv_reorder_ctrl *preorder_ctrl = prframe->u.hdr.preorder_ctrl;
struct __queue *ppending_recvframe_queue =
&preorder_ctrl->pending_recvframe_queue;
if (!pattrib->amsdu) {
/* s1. */
r8712_wlanhdr_to_ethhdr(prframe);
if (pattrib->qos != 1) {
if ((padapter->bDriverStopped == false) &&
(padapter->bSurpriseRemoved == false)) {
r8712_recv_indicatepkt(padapter, prframe);
return _SUCCESS;
} else
return _FAIL;
}
}
spin_lock_irqsave(&ppending_recvframe_queue->lock, irql);
/*s2. check if winstart_b(indicate_seq) needs to been updated*/
if (!check_indicate_seq(preorder_ctrl, pattrib->seq_num))
goto _err_exit;
/*s3. Insert all packet into Reorder Queue to maintain its ordering.*/
if (!enqueue_reorder_recvframe(preorder_ctrl, prframe))
goto _err_exit;
/*s4.
* Indication process.
* After Packet dropping and Sliding Window shifting as above, we can
* now just indicate the packets with the SeqNum smaller than latest
* WinStart and buffer other packets.
*
* For Rx Reorder condition:
* 1. All packets with SeqNum smaller than WinStart => Indicate
* 2. All packets with SeqNum larger than or equal to
* WinStart => Buffer it.
*/
if (r8712_recv_indicatepkts_in_order(padapter, preorder_ctrl, false) ==
true) {
_set_timer(&preorder_ctrl->reordering_ctrl_timer,
REORDER_WAIT_TIME);
spin_unlock_irqrestore(&ppending_recvframe_queue->lock, irql);
} else {
spin_unlock_irqrestore(&ppending_recvframe_queue->lock, irql);
_cancel_timer_ex(&preorder_ctrl->reordering_ctrl_timer);
}
return _SUCCESS;
_err_exit:
spin_unlock_irqrestore(&ppending_recvframe_queue->lock, irql);
return _FAIL;
}
void r8712_reordering_ctrl_timeout_handler(void *pcontext)
{
unsigned long irql;
struct recv_reorder_ctrl *preorder_ctrl =
(struct recv_reorder_ctrl *)pcontext;
struct _adapter *padapter = preorder_ctrl->padapter;
struct __queue *ppending_recvframe_queue =
&preorder_ctrl->pending_recvframe_queue;
if (padapter->bDriverStopped || padapter->bSurpriseRemoved)
return;
spin_lock_irqsave(&ppending_recvframe_queue->lock, irql);
r8712_recv_indicatepkts_in_order(padapter, preorder_ctrl, true);
spin_unlock_irqrestore(&ppending_recvframe_queue->lock, irql);
}
static int r8712_process_recv_indicatepkts(struct _adapter *padapter,
union recv_frame *prframe)
{
int retval = _SUCCESS;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct ht_priv *phtpriv = &pmlmepriv->htpriv;
if (phtpriv->ht_option == 1) { /*B/G/N Mode*/
if (recv_indicatepkt_reorder(padapter, prframe) != _SUCCESS) {
/* including perform A-MPDU Rx Ordering Buffer Control*/
if ((padapter->bDriverStopped == false) &&
(padapter->bSurpriseRemoved == false))
return _FAIL;
}
} else { /*B/G mode*/
retval = r8712_wlanhdr_to_ethhdr(prframe);
if (retval != _SUCCESS)
return retval;
if ((padapter->bDriverStopped == false) &&
(padapter->bSurpriseRemoved == false)) {
/* indicate this recv_frame */
r8712_recv_indicatepkt(padapter, prframe);
} else
return _FAIL;
}
return retval;
}
static u8 query_rx_pwr_percentage(s8 antpower)
{
if ((antpower <= -100) || (antpower >= 20))
return 0;
else if (antpower >= 0)
return 100;
else
return 100 + antpower;
}
static u8 evm_db2percentage(s8 value)
{
/*
* -33dB~0dB to 0%~99%
*/
s8 ret_val;
ret_val = value;
if (ret_val >= 0)
ret_val = 0;
if (ret_val <= -33)
ret_val = -33;
ret_val = -ret_val;
ret_val *= 3;
if (ret_val == 99)
ret_val = 100;
return ret_val;
}
s32 r8712_signal_scale_mapping(s32 cur_sig)
{
s32 ret_sig;
if (cur_sig >= 51 && cur_sig <= 100)
ret_sig = 100;
else if (cur_sig >= 41 && cur_sig <= 50)
ret_sig = 80 + ((cur_sig - 40) * 2);
else if (cur_sig >= 31 && cur_sig <= 40)
ret_sig = 66 + (cur_sig - 30);
else if (cur_sig >= 21 && cur_sig <= 30)
ret_sig = 54 + (cur_sig - 20);
else if (cur_sig >= 10 && cur_sig <= 20)
ret_sig = 42 + (((cur_sig - 10) * 2) / 3);
else if (cur_sig >= 5 && cur_sig <= 9)
ret_sig = 22 + (((cur_sig - 5) * 3) / 2);
else if (cur_sig >= 1 && cur_sig <= 4)
ret_sig = 6 + (((cur_sig - 1) * 3) / 2);
else
ret_sig = cur_sig;
return ret_sig;
}
static s32 translate2dbm(struct _adapter *padapter, u8 signal_strength_idx)
{
s32 signal_power; /* in dBm.*/
/* Translate to dBm (x=0.5y-95).*/
signal_power = (s32)((signal_strength_idx + 1) >> 1);
signal_power -= 95;
return signal_power;
}
static void query_rx_phy_status(struct _adapter *padapter,
union recv_frame *prframe)
{
u8 i, max_spatial_stream, evm;
struct recv_stat *prxstat = (struct recv_stat *)prframe->u.hdr.rx_head;
struct phy_stat *pphy_stat = (struct phy_stat *)(prxstat + 1);
u8 *pphy_head = (u8 *)(prxstat + 1);
s8 rx_pwr[4], rx_pwr_all;
u8 pwdb_all;
u32 rssi, total_rssi = 0;
u8 bcck_rate = 0, rf_rx_num = 0, cck_highpwr = 0;
struct phy_cck_rx_status *pcck_buf;
u8 sq;
/* Record it for next packet processing*/
bcck_rate = (prframe->u.hdr.attrib.mcs_rate <= 3 ? 1 : 0);
if (bcck_rate) {
u8 report;
/* CCK Driver info Structure is not the same as OFDM packet.*/
pcck_buf = (struct phy_cck_rx_status *)pphy_stat;
/* (1)Hardware does not provide RSSI for CCK
* (2)PWDB, Average PWDB cacluated by hardware
* (for rate adaptive)
*/
if (!cck_highpwr) {
report = pcck_buf->cck_agc_rpt & 0xc0;
report = report >> 6;
switch (report) {
/* Modify the RF RNA gain value to -40, -20,
* -2, 14 by Jenyu's suggestion
* Note: different RF with the different
* RNA gain. */
case 0x3:
rx_pwr_all = -40 - (pcck_buf->cck_agc_rpt &
0x3e);
break;
case 0x2:
rx_pwr_all = -20 - (pcck_buf->cck_agc_rpt &
0x3e);
break;
case 0x1:
rx_pwr_all = -2 - (pcck_buf->cck_agc_rpt &
0x3e);
break;
case 0x0:
rx_pwr_all = 14 - (pcck_buf->cck_agc_rpt &
0x3e);
break;
}
} else {
report = ((u8)(le32_to_cpu(pphy_stat->phydw1) >> 8)) &
0x60;
report = report >> 5;
switch (report) {
case 0x3:
rx_pwr_all = -40 - ((pcck_buf->cck_agc_rpt &
0x1f) << 1);
break;
case 0x2:
rx_pwr_all = -20 - ((pcck_buf->cck_agc_rpt &
0x1f) << 1);
break;
case 0x1:
rx_pwr_all = -2 - ((pcck_buf->cck_agc_rpt &
0x1f) << 1);
break;
case 0x0:
rx_pwr_all = 14 - ((pcck_buf->cck_agc_rpt &
0x1f) << 1);
break;
}
}
pwdb_all = query_rx_pwr_percentage(rx_pwr_all);
/* CCK gain is smaller than OFDM/MCS gain,*/
/* so we add gain diff by experiences, the val is 6 */
pwdb_all += 6;
if (pwdb_all > 100)
pwdb_all = 100;
/* modify the offset to make the same gain index with OFDM.*/
if (pwdb_all > 34 && pwdb_all <= 42)
pwdb_all -= 2;
else if (pwdb_all > 26 && pwdb_all <= 34)
pwdb_all -= 6;
else if (pwdb_all > 14 && pwdb_all <= 26)
pwdb_all -= 8;
else if (pwdb_all > 4 && pwdb_all <= 14)
pwdb_all -= 4;
/*
* (3) Get Signal Quality (EVM)
*/
if (pwdb_all > 40)
sq = 100;
else {
sq = pcck_buf->sq_rpt;
if (pcck_buf->sq_rpt > 64)
sq = 0;
else if (pcck_buf->sq_rpt < 20)
sq = 100;
else
sq = ((64-sq) * 100) / 44;
}
prframe->u.hdr.attrib.signal_qual = sq;
prframe->u.hdr.attrib.rx_mimo_signal_qual[0] = sq;
prframe->u.hdr.attrib.rx_mimo_signal_qual[1] = -1;
} else {
/* (1)Get RSSI for HT rate */
for (i = 0; i < ((padapter->registrypriv.rf_config) &
0x0f) ; i++) {
rf_rx_num++;
rx_pwr[i] = ((pphy_head[PHY_STAT_GAIN_TRSW_SHT + i]
& 0x3F) * 2) - 110;
/* Translate DBM to percentage. */
rssi = query_rx_pwr_percentage(rx_pwr[i]);
total_rssi += rssi;
}
/* (2)PWDB, Average PWDB cacluated by hardware (for
* rate adaptive) */
rx_pwr_all = (((pphy_head[PHY_STAT_PWDB_ALL_SHT]) >> 1) & 0x7f)
- 106;
pwdb_all = query_rx_pwr_percentage(rx_pwr_all);
{
/* (3)EVM of HT rate */
if (prframe->u.hdr.attrib.htc &&
prframe->u.hdr.attrib.mcs_rate >= 20 &&
prframe->u.hdr.attrib.mcs_rate <= 27) {
/* both spatial stream make sense */
max_spatial_stream = 2;
} else {
/* only spatial stream 1 makes sense */
max_spatial_stream = 1;
}
for (i = 0; i < max_spatial_stream; i++) {
evm = evm_db2percentage((pphy_head
[PHY_STAT_RXEVM_SHT + i]));/*dbm*/
prframe->u.hdr.attrib.signal_qual =
(u8)(evm & 0xff);
prframe->u.hdr.attrib.rx_mimo_signal_qual[i] =
(u8)(evm & 0xff);
}
}
}
/* UI BSS List signal strength(in percentage), make it good looking,
* from 0~100. It is assigned to the BSS List in
* GetValueFromBeaconOrProbeRsp(). */
if (bcck_rate)
prframe->u.hdr.attrib.signal_strength =
(u8)r8712_signal_scale_mapping(pwdb_all);
else {
if (rf_rx_num != 0)
prframe->u.hdr.attrib.signal_strength =
(u8)(r8712_signal_scale_mapping(total_rssi /=
rf_rx_num));
}
}
static void process_link_qual(struct _adapter *padapter,
union recv_frame *prframe)
{
u32 last_evm = 0, tmpVal;
struct rx_pkt_attrib *pattrib;
if (prframe == NULL || padapter == NULL)
return;
pattrib = &prframe->u.hdr.attrib;
if (pattrib->signal_qual != 0) {
/*
* 1. Record the general EVM to the sliding window.
*/
if (padapter->recvpriv.signal_qual_data.total_num++ >=
PHY_LINKQUALITY_SLID_WIN_MAX) {
padapter->recvpriv.signal_qual_data.total_num =
PHY_LINKQUALITY_SLID_WIN_MAX;
last_evm = padapter->recvpriv.signal_qual_data.elements
[padapter->recvpriv.signal_qual_data.index];
padapter->recvpriv.signal_qual_data.total_val -=
last_evm;
}
padapter->recvpriv.signal_qual_data.total_val +=
pattrib->signal_qual;
padapter->recvpriv.signal_qual_data.elements[padapter->
recvpriv.signal_qual_data.index++] =
pattrib->signal_qual;
if (padapter->recvpriv.signal_qual_data.index >=
PHY_LINKQUALITY_SLID_WIN_MAX)
padapter->recvpriv.signal_qual_data.index = 0;
/* <1> Showed on UI for user, in percentage. */
tmpVal = padapter->recvpriv.signal_qual_data.total_val /
padapter->recvpriv.signal_qual_data.total_num;
padapter->recvpriv.signal = (u8)tmpVal;
}
}
static void process_rssi(struct _adapter *padapter, union recv_frame *prframe)
{
u32 last_rssi, tmp_val;
struct rx_pkt_attrib *pattrib = &prframe->u.hdr.attrib;
if (padapter->recvpriv.signal_strength_data.total_num++ >=
PHY_RSSI_SLID_WIN_MAX) {
padapter->recvpriv.signal_strength_data.total_num =
PHY_RSSI_SLID_WIN_MAX;
last_rssi = padapter->recvpriv.signal_strength_data.elements
[padapter->recvpriv.signal_strength_data.index];
padapter->recvpriv.signal_strength_data.total_val -= last_rssi;
}
padapter->recvpriv.signal_strength_data.total_val +=
pattrib->signal_strength;
padapter->recvpriv.signal_strength_data.elements[padapter->recvpriv.
signal_strength_data.index++] =
pattrib->signal_strength;
if (padapter->recvpriv.signal_strength_data.index >=
PHY_RSSI_SLID_WIN_MAX)
padapter->recvpriv.signal_strength_data.index = 0;
tmp_val = padapter->recvpriv.signal_strength_data.total_val /
padapter->recvpriv.signal_strength_data.total_num;
padapter->recvpriv.rssi = (s8)translate2dbm(padapter, (u8)tmp_val);
}
static void process_phy_info(struct _adapter *padapter,
union recv_frame *prframe)
{
query_rx_phy_status(padapter, prframe);
process_rssi(padapter, prframe);
process_link_qual(padapter, prframe);
}
int recv_func(struct _adapter *padapter, void *pcontext)
{
struct rx_pkt_attrib *pattrib;
union recv_frame *prframe, *orig_prframe;
int retval = _SUCCESS;
struct __queue *pfree_recv_queue = &padapter->recvpriv.free_recv_queue;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
prframe = (union recv_frame *)pcontext;
orig_prframe = prframe;
pattrib = &prframe->u.hdr.attrib;
if ((check_fwstate(pmlmepriv, WIFI_MP_STATE) == true)) {
if (pattrib->crc_err == 1)
padapter->mppriv.rx_crcerrpktcount++;
else
padapter->mppriv.rx_pktcount++;
if (check_fwstate(pmlmepriv, WIFI_MP_LPBK_STATE) == false) {
/* free this recv_frame */
r8712_free_recvframe(orig_prframe, pfree_recv_queue);
goto _exit_recv_func;
}
}
/* check the frame crtl field and decache */
retval = r8712_validate_recv_frame(padapter, prframe);
if (retval != _SUCCESS) {
/* free this recv_frame */
r8712_free_recvframe(orig_prframe, pfree_recv_queue);
goto _exit_recv_func;
}
process_phy_info(padapter, prframe);
prframe = r8712_decryptor(padapter, prframe);
if (prframe == NULL) {
retval = _FAIL;
goto _exit_recv_func;
}
prframe = r8712_recvframe_chk_defrag(padapter, prframe);
if (prframe == NULL)
goto _exit_recv_func;
prframe = r8712_portctrl(padapter, prframe);
if (prframe == NULL) {
retval = _FAIL;
goto _exit_recv_func;
}
retval = r8712_process_recv_indicatepkts(padapter, prframe);
if (retval != _SUCCESS) {
r8712_free_recvframe(orig_prframe, pfree_recv_queue);
goto _exit_recv_func;
}
_exit_recv_func:
return retval;
}
static int recvbuf2recvframe(struct _adapter *padapter, struct sk_buff *pskb)
{
u8 *pbuf, shift_sz = 0;
u8 frag, mf;
uint pkt_len;
u32 transfer_len;
struct recv_stat *prxstat;
u16 pkt_cnt, drvinfo_sz, pkt_offset, tmp_len, alloc_sz;
struct __queue *pfree_recv_queue;
_pkt *pkt_copy = NULL;
union recv_frame *precvframe = NULL;
struct recv_priv *precvpriv = &padapter->recvpriv;
pfree_recv_queue = &(precvpriv->free_recv_queue);
pbuf = pskb->data;
prxstat = (struct recv_stat *)pbuf;
pkt_cnt = (le32_to_cpu(prxstat->rxdw2)>>16)&0xff;
pkt_len = le32_to_cpu(prxstat->rxdw0)&0x00003fff;
transfer_len = pskb->len;
/* Test throughput with Netgear 3700 (No security) with Chariot 3T3R
* pairs. The packet count will be a big number so that the containing
* packet will effect the Rx reordering. */
if (transfer_len < pkt_len) {
/* In this case, it means the MAX_RECVBUF_SZ is too small to
* get the data from 8712u. */
return _FAIL;
}
do {
prxstat = (struct recv_stat *)pbuf;
pkt_len = le32_to_cpu(prxstat->rxdw0)&0x00003fff;
/* more fragment bit */
mf = (le32_to_cpu(prxstat->rxdw1) >> 27) & 0x1;
/* ragmentation number */
frag = (le32_to_cpu(prxstat->rxdw2) >> 12) & 0xf;
/* uint 2^3 = 8 bytes */
drvinfo_sz = (le32_to_cpu(prxstat->rxdw0) & 0x000f0000) >> 16;
drvinfo_sz = drvinfo_sz<<3;
if (pkt_len <= 0)
goto _exit_recvbuf2recvframe;
/* Qos data, wireless lan header length is 26 */
if ((le32_to_cpu(prxstat->rxdw0) >> 23) & 0x01)
shift_sz = 2;
precvframe = r8712_alloc_recvframe(pfree_recv_queue);
if (precvframe == NULL)
goto _exit_recvbuf2recvframe;
_init_listhead(&precvframe->u.hdr.list);
precvframe->u.hdr.precvbuf = NULL; /*can't access the precvbuf*/
precvframe->u.hdr.len = 0;
tmp_len = pkt_len + drvinfo_sz + RXDESC_SIZE;
pkt_offset = (u16)_RND128(tmp_len);
/* for first fragment packet, driver need allocate 1536 +
* drvinfo_sz + RXDESC_SIZE to defrag packet. */
if ((mf == 1) && (frag == 0))
alloc_sz = 1658;
else
alloc_sz = tmp_len;
/* 2 is for IP header 4 bytes alignment in QoS packet case.
* 4 is for skb->data 4 bytes alignment. */
alloc_sz += 6;
pkt_copy = netdev_alloc_skb(padapter->pnetdev, alloc_sz);
if (pkt_copy) {
pkt_copy->dev = padapter->pnetdev;
precvframe->u.hdr.pkt = pkt_copy;
skb_reserve(pkt_copy, 4 - ((addr_t)(pkt_copy->data)
% 4));
skb_reserve(pkt_copy, shift_sz);
memcpy(pkt_copy->data, pbuf, tmp_len);
precvframe->u.hdr.rx_head = precvframe->u.hdr.rx_data =
precvframe->u.hdr.rx_tail = pkt_copy->data;
precvframe->u.hdr.rx_end = pkt_copy->data + alloc_sz;
} else {
precvframe->u.hdr.pkt = skb_clone(pskb, GFP_ATOMIC);
precvframe->u.hdr.rx_head = pbuf;
precvframe->u.hdr.rx_data = pbuf;
precvframe->u.hdr.rx_tail = pbuf;
precvframe->u.hdr.rx_end = pbuf + alloc_sz;
}
recvframe_put(precvframe, tmp_len);
recvframe_pull(precvframe, drvinfo_sz + RXDESC_SIZE);
/* because the endian issue, driver avoid reference to the
* rxstat after calling update_recvframe_attrib_from_recvstat();
*/
update_recvframe_attrib_from_recvstat(&precvframe->u.hdr.attrib,
prxstat);
r8712_recv_entry(precvframe);
transfer_len -= pkt_offset;
pbuf += pkt_offset;
pkt_cnt--;
precvframe = NULL;
pkt_copy = NULL;
} while ((transfer_len > 0) && pkt_cnt > 0);
_exit_recvbuf2recvframe:
return _SUCCESS;
}
static void recv_tasklet(void *priv)
{
struct sk_buff *pskb;
struct _adapter *padapter = (struct _adapter *)priv;
struct recv_priv *precvpriv = &padapter->recvpriv;
while (NULL != (pskb = skb_dequeue(&precvpriv->rx_skb_queue))) {
recvbuf2recvframe(padapter, pskb);
skb_reset_tail_pointer(pskb);
pskb->len = 0;
skb_queue_tail(&precvpriv->free_recv_skb_queue, pskb);
}
}
| gpl-2.0 |
xenon92/android_kernel_nebula | sound/soc/codecs/da7210.c | 3023 | 16525 | /*
* DA7210 ALSA Soc codec driver
*
* Copyright (c) 2009 Dialog Semiconductor
* Written by David Chen <Dajun.chen@diasemi.com>
*
* Copyright (C) 2009 Renesas Solutions Corp.
* Cleanups by Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Tested on SuperH Ecovec24 board with S16/S24 LE in 48KHz using I2S
*
* 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/delay.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
/* DA7210 register space */
#define DA7210_STATUS 0x02
#define DA7210_STARTUP1 0x03
#define DA7210_MIC_L 0x07
#define DA7210_MIC_R 0x08
#define DA7210_INMIX_L 0x0D
#define DA7210_INMIX_R 0x0E
#define DA7210_ADC_HPF 0x0F
#define DA7210_ADC 0x10
#define DA7210_DAC_HPF 0x14
#define DA7210_DAC_L 0x15
#define DA7210_DAC_R 0x16
#define DA7210_DAC_SEL 0x17
#define DA7210_OUTMIX_L 0x1C
#define DA7210_OUTMIX_R 0x1D
#define DA7210_HP_L_VOL 0x21
#define DA7210_HP_R_VOL 0x22
#define DA7210_HP_CFG 0x23
#define DA7210_DAI_SRC_SEL 0x25
#define DA7210_DAI_CFG1 0x26
#define DA7210_DAI_CFG3 0x28
#define DA7210_PLL_DIV1 0x29
#define DA7210_PLL_DIV2 0x2A
#define DA7210_PLL_DIV3 0x2B
#define DA7210_PLL 0x2C
#define DA7210_A_HID_UNLOCK 0x8A
#define DA7210_A_TEST_UNLOCK 0x8B
#define DA7210_A_PLL1 0x90
#define DA7210_A_CP_MODE 0xA7
/* STARTUP1 bit fields */
#define DA7210_SC_MST_EN (1 << 0)
/* MIC_L bit fields */
#define DA7210_MICBIAS_EN (1 << 6)
#define DA7210_MIC_L_EN (1 << 7)
/* MIC_R bit fields */
#define DA7210_MIC_R_EN (1 << 7)
/* INMIX_L bit fields */
#define DA7210_IN_L_EN (1 << 7)
/* INMIX_R bit fields */
#define DA7210_IN_R_EN (1 << 7)
/* ADC bit fields */
#define DA7210_ADC_L_EN (1 << 3)
#define DA7210_ADC_R_EN (1 << 7)
/* DAC/ADC HPF fields */
#define DA7210_VOICE_F0_MASK (0x7 << 4)
#define DA7210_VOICE_F0_25 (1 << 4)
#define DA7210_VOICE_EN (1 << 7)
/* DAC_SEL bit fields */
#define DA7210_DAC_L_SRC_DAI_L (4 << 0)
#define DA7210_DAC_L_EN (1 << 3)
#define DA7210_DAC_R_SRC_DAI_R (5 << 4)
#define DA7210_DAC_R_EN (1 << 7)
/* OUTMIX_L bit fields */
#define DA7210_OUT_L_EN (1 << 7)
/* OUTMIX_R bit fields */
#define DA7210_OUT_R_EN (1 << 7)
/* HP_CFG bit fields */
#define DA7210_HP_2CAP_MODE (1 << 1)
#define DA7210_HP_SENSE_EN (1 << 2)
#define DA7210_HP_L_EN (1 << 3)
#define DA7210_HP_MODE (1 << 6)
#define DA7210_HP_R_EN (1 << 7)
/* DAI_SRC_SEL bit fields */
#define DA7210_DAI_OUT_L_SRC (6 << 0)
#define DA7210_DAI_OUT_R_SRC (7 << 4)
/* DAI_CFG1 bit fields */
#define DA7210_DAI_WORD_S16_LE (0 << 0)
#define DA7210_DAI_WORD_S24_LE (2 << 0)
#define DA7210_DAI_FLEN_64BIT (1 << 2)
#define DA7210_DAI_MODE_MASTER (1 << 7)
/* DAI_CFG3 bit fields */
#define DA7210_DAI_FORMAT_I2SMODE (0 << 0)
#define DA7210_DAI_OE (1 << 3)
#define DA7210_DAI_EN (1 << 7)
/*PLL_DIV3 bit fields */
#define DA7210_MCLK_RANGE_10_20_MHZ (1 << 4)
#define DA7210_PLL_BYP (1 << 6)
/* PLL bit fields */
#define DA7210_PLL_FS_MASK (0xF << 0)
#define DA7210_PLL_FS_8000 (0x1 << 0)
#define DA7210_PLL_FS_11025 (0x2 << 0)
#define DA7210_PLL_FS_12000 (0x3 << 0)
#define DA7210_PLL_FS_16000 (0x5 << 0)
#define DA7210_PLL_FS_22050 (0x6 << 0)
#define DA7210_PLL_FS_24000 (0x7 << 0)
#define DA7210_PLL_FS_32000 (0x9 << 0)
#define DA7210_PLL_FS_44100 (0xA << 0)
#define DA7210_PLL_FS_48000 (0xB << 0)
#define DA7210_PLL_FS_88200 (0xE << 0)
#define DA7210_PLL_FS_96000 (0xF << 0)
#define DA7210_PLL_EN (0x1 << 7)
#define DA7210_VERSION "0.0.1"
/*
* Playback Volume
*
* max : 0x3F (+15.0 dB)
* (1.5 dB step)
* min : 0x11 (-54.0 dB)
* mute : 0x10
* reserved : 0x00 - 0x0F
*
* ** FIXME **
*
* Reserved area are considered as "mute".
* -> min = -79.5 dB
*/
static const DECLARE_TLV_DB_SCALE(hp_out_tlv, -7950, 150, 1);
static const struct snd_kcontrol_new da7210_snd_controls[] = {
SOC_DOUBLE_R_TLV("HeadPhone Playback Volume",
DA7210_HP_L_VOL, DA7210_HP_R_VOL,
0, 0x3F, 0, hp_out_tlv),
};
/* Codec private data */
struct da7210_priv {
enum snd_soc_control_type control_type;
void *control_data;
};
/*
* Register cache
*/
static const u8 da7210_reg[] = {
0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R0 - R7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, /* R8 - RF */
0x00, 0x00, 0x00, 0x00, 0x08, 0x10, 0x10, 0x54, /* R10 - R17 */
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R18 - R1F */
0x00, 0x00, 0x00, 0x02, 0x00, 0x76, 0x00, 0x00, /* R20 - R27 */
0x04, 0x00, 0x00, 0x30, 0x2A, 0x00, 0x40, 0x00, /* R28 - R2F */
0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, /* R30 - R37 */
0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x00, 0x00, /* R38 - R3F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R40 - R4F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R48 - R4F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R50 - R57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R58 - R5F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R60 - R67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R68 - R6F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R70 - R77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x54, 0x00, /* R78 - R7F */
0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x00, /* R80 - R87 */
0x00, /* R88 */
};
/*
* Read da7210 register cache
*/
static inline u32 da7210_read_reg_cache(struct snd_soc_codec *codec, u32 reg)
{
u8 *cache = codec->reg_cache;
BUG_ON(reg >= ARRAY_SIZE(da7210_reg));
return cache[reg];
}
/*
* Write to the da7210 register space
*/
static int da7210_write(struct snd_soc_codec *codec, u32 reg, u32 value)
{
u8 *cache = codec->reg_cache;
u8 data[2];
BUG_ON(codec->driver->volatile_register);
data[0] = reg & 0xff;
data[1] = value & 0xff;
if (reg >= codec->driver->reg_cache_size)
return -EIO;
if (2 != codec->hw_write(codec->control_data, data, 2))
return -EIO;
cache[reg] = value;
return 0;
}
/*
* Read from the da7210 register space.
*/
static inline u32 da7210_read(struct snd_soc_codec *codec, u32 reg)
{
if (DA7210_STATUS == reg)
return i2c_smbus_read_byte_data(codec->control_data, reg);
return da7210_read_reg_cache(codec, reg);
}
static int da7210_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
int is_play = substream->stream == SNDRV_PCM_STREAM_PLAYBACK;
struct snd_soc_codec *codec = dai->codec;
if (is_play) {
/* Enable Out */
snd_soc_update_bits(codec, DA7210_OUTMIX_L, 0x1F, 0x10);
snd_soc_update_bits(codec, DA7210_OUTMIX_R, 0x1F, 0x10);
} else {
/* Volume 7 */
snd_soc_update_bits(codec, DA7210_MIC_L, 0x7, 0x7);
snd_soc_update_bits(codec, DA7210_MIC_R, 0x7, 0x7);
/* Enable Mic */
snd_soc_update_bits(codec, DA7210_INMIX_L, 0x1F, 0x1);
snd_soc_update_bits(codec, DA7210_INMIX_R, 0x1F, 0x1);
}
return 0;
}
/*
* Set PCM DAI word length.
*/
static int da7210_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
u32 dai_cfg1;
u32 hpf_reg, hpf_mask, hpf_value;
u32 fs, bypass;
/* set DAI source to Left and Right ADC */
da7210_write(codec, DA7210_DAI_SRC_SEL,
DA7210_DAI_OUT_R_SRC | DA7210_DAI_OUT_L_SRC);
/* Enable DAI */
da7210_write(codec, DA7210_DAI_CFG3, DA7210_DAI_OE | DA7210_DAI_EN);
dai_cfg1 = 0xFC & da7210_read(codec, DA7210_DAI_CFG1);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
dai_cfg1 |= DA7210_DAI_WORD_S16_LE;
break;
case SNDRV_PCM_FORMAT_S24_LE:
dai_cfg1 |= DA7210_DAI_WORD_S24_LE;
break;
default:
return -EINVAL;
}
da7210_write(codec, DA7210_DAI_CFG1, dai_cfg1);
hpf_reg = (SNDRV_PCM_STREAM_PLAYBACK == substream->stream) ?
DA7210_DAC_HPF : DA7210_ADC_HPF;
switch (params_rate(params)) {
case 8000:
fs = DA7210_PLL_FS_8000;
hpf_mask = DA7210_VOICE_F0_MASK | DA7210_VOICE_EN;
hpf_value = DA7210_VOICE_F0_25 | DA7210_VOICE_EN;
bypass = DA7210_PLL_BYP;
break;
case 11025:
fs = DA7210_PLL_FS_11025;
hpf_mask = DA7210_VOICE_F0_MASK | DA7210_VOICE_EN;
hpf_value = DA7210_VOICE_F0_25 | DA7210_VOICE_EN;
bypass = 0;
break;
case 12000:
fs = DA7210_PLL_FS_12000;
hpf_mask = DA7210_VOICE_F0_MASK | DA7210_VOICE_EN;
hpf_value = DA7210_VOICE_F0_25 | DA7210_VOICE_EN;
bypass = DA7210_PLL_BYP;
break;
case 16000:
fs = DA7210_PLL_FS_16000;
hpf_mask = DA7210_VOICE_F0_MASK | DA7210_VOICE_EN;
hpf_value = DA7210_VOICE_F0_25 | DA7210_VOICE_EN;
bypass = DA7210_PLL_BYP;
break;
case 22050:
fs = DA7210_PLL_FS_22050;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = 0;
break;
case 32000:
fs = DA7210_PLL_FS_32000;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = DA7210_PLL_BYP;
break;
case 44100:
fs = DA7210_PLL_FS_44100;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = 0;
break;
case 48000:
fs = DA7210_PLL_FS_48000;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = DA7210_PLL_BYP;
break;
case 88200:
fs = DA7210_PLL_FS_88200;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = 0;
break;
case 96000:
fs = DA7210_PLL_FS_96000;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = DA7210_PLL_BYP;
break;
default:
return -EINVAL;
}
/* Disable active mode */
snd_soc_update_bits(codec, DA7210_STARTUP1, DA7210_SC_MST_EN, 0);
snd_soc_update_bits(codec, hpf_reg, hpf_mask, hpf_value);
snd_soc_update_bits(codec, DA7210_PLL, DA7210_PLL_FS_MASK, fs);
snd_soc_update_bits(codec, DA7210_PLL_DIV3, DA7210_PLL_BYP, bypass);
/* Enable active mode */
snd_soc_update_bits(codec, DA7210_STARTUP1,
DA7210_SC_MST_EN, DA7210_SC_MST_EN);
return 0;
}
/*
* Set DAI mode and Format
*/
static int da7210_set_dai_fmt(struct snd_soc_dai *codec_dai, u32 fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u32 dai_cfg1;
u32 dai_cfg3;
dai_cfg1 = 0x7f & da7210_read(codec, DA7210_DAI_CFG1);
dai_cfg3 = 0xfc & da7210_read(codec, DA7210_DAI_CFG3);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
dai_cfg1 |= DA7210_DAI_MODE_MASTER;
break;
default:
return -EINVAL;
}
/* FIXME
*
* It support I2S only now
*/
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
dai_cfg3 |= DA7210_DAI_FORMAT_I2SMODE;
break;
default:
return -EINVAL;
}
/* FIXME
*
* It support 64bit data transmission only now
*/
dai_cfg1 |= DA7210_DAI_FLEN_64BIT;
da7210_write(codec, DA7210_DAI_CFG1, dai_cfg1);
da7210_write(codec, DA7210_DAI_CFG3, dai_cfg3);
return 0;
}
#define DA7210_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE)
/* DAI operations */
static struct snd_soc_dai_ops da7210_dai_ops = {
.startup = da7210_startup,
.hw_params = da7210_hw_params,
.set_fmt = da7210_set_dai_fmt,
};
static struct snd_soc_dai_driver da7210_dai = {
.name = "da7210-hifi",
/* playback capabilities */
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_96000,
.formats = DA7210_FORMATS,
},
/* capture capabilities */
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_96000,
.formats = DA7210_FORMATS,
},
.ops = &da7210_dai_ops,
.symmetric_rates = 1,
};
static int da7210_probe(struct snd_soc_codec *codec)
{
struct da7210_priv *da7210 = snd_soc_codec_get_drvdata(codec);
dev_info(codec->dev, "DA7210 Audio Codec %s\n", DA7210_VERSION);
codec->control_data = da7210->control_data;
codec->hw_write = (hw_write_t)i2c_master_send;
/* FIXME
*
* This driver use fixed value here
* And below settings expects MCLK = 12.288MHz
*
* When you select different MCLK, please check...
* DA7210_PLL_DIV1 val
* DA7210_PLL_DIV2 val
* DA7210_PLL_DIV3 val
* DA7210_PLL_DIV3 :: DA7210_MCLK_RANGExxx
*/
/*
* make sure that DA7210 use bypass mode before start up
*/
da7210_write(codec, DA7210_STARTUP1, 0);
da7210_write(codec, DA7210_PLL_DIV3,
DA7210_MCLK_RANGE_10_20_MHZ | DA7210_PLL_BYP);
/*
* ADC settings
*/
/* Enable Left & Right MIC PGA and Mic Bias */
da7210_write(codec, DA7210_MIC_L, DA7210_MIC_L_EN | DA7210_MICBIAS_EN);
da7210_write(codec, DA7210_MIC_R, DA7210_MIC_R_EN);
/* Enable Left and Right input PGA */
da7210_write(codec, DA7210_INMIX_L, DA7210_IN_L_EN);
da7210_write(codec, DA7210_INMIX_R, DA7210_IN_R_EN);
/* Enable Left and Right ADC */
da7210_write(codec, DA7210_ADC, DA7210_ADC_L_EN | DA7210_ADC_R_EN);
/*
* DAC settings
*/
/* Enable Left and Right DAC */
da7210_write(codec, DA7210_DAC_SEL,
DA7210_DAC_L_SRC_DAI_L | DA7210_DAC_L_EN |
DA7210_DAC_R_SRC_DAI_R | DA7210_DAC_R_EN);
/* Enable Left and Right out PGA */
da7210_write(codec, DA7210_OUTMIX_L, DA7210_OUT_L_EN);
da7210_write(codec, DA7210_OUTMIX_R, DA7210_OUT_R_EN);
/* Enable Left and Right HeadPhone PGA */
da7210_write(codec, DA7210_HP_CFG,
DA7210_HP_2CAP_MODE | DA7210_HP_SENSE_EN |
DA7210_HP_L_EN | DA7210_HP_MODE | DA7210_HP_R_EN);
/* Diable PLL and bypass it */
da7210_write(codec, DA7210_PLL, DA7210_PLL_FS_48000);
/*
* If 48kHz sound came, it use bypass mode,
* and when it is 44.1kHz, it use PLL.
*
* This time, this driver sets PLL always ON
* and controls bypass/PLL mode by switching
* DA7210_PLL_DIV3 :: DA7210_PLL_BYP bit.
* see da7210_hw_params
*/
da7210_write(codec, DA7210_PLL_DIV1, 0xE5); /* MCLK = 12.288MHz */
da7210_write(codec, DA7210_PLL_DIV2, 0x99);
da7210_write(codec, DA7210_PLL_DIV3, 0x0A |
DA7210_MCLK_RANGE_10_20_MHZ | DA7210_PLL_BYP);
snd_soc_update_bits(codec, DA7210_PLL, DA7210_PLL_EN, DA7210_PLL_EN);
/* As suggested by Dialog */
da7210_write(codec, DA7210_A_HID_UNLOCK, 0x8B); /* unlock */
da7210_write(codec, DA7210_A_TEST_UNLOCK, 0xB4);
da7210_write(codec, DA7210_A_PLL1, 0x01);
da7210_write(codec, DA7210_A_CP_MODE, 0x7C);
da7210_write(codec, DA7210_A_HID_UNLOCK, 0x00); /* re-lock */
da7210_write(codec, DA7210_A_TEST_UNLOCK, 0x00);
/* Activate all enabled subsystem */
da7210_write(codec, DA7210_STARTUP1, DA7210_SC_MST_EN);
snd_soc_add_controls(codec, da7210_snd_controls,
ARRAY_SIZE(da7210_snd_controls));
dev_info(codec->dev, "DA7210 Audio Codec %s\n", DA7210_VERSION);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_da7210 = {
.probe = da7210_probe,
.read = da7210_read,
.write = da7210_write,
.reg_cache_size = ARRAY_SIZE(da7210_reg),
.reg_word_size = sizeof(u8),
.reg_cache_default = da7210_reg,
};
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static int __devinit da7210_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct da7210_priv *da7210;
int ret;
da7210 = kzalloc(sizeof(struct da7210_priv), GFP_KERNEL);
if (!da7210)
return -ENOMEM;
i2c_set_clientdata(i2c, da7210);
da7210->control_data = i2c;
da7210->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_da7210, &da7210_dai, 1);
if (ret < 0)
kfree(da7210);
return ret;
}
static int __devexit da7210_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
kfree(i2c_get_clientdata(client));
return 0;
}
static const struct i2c_device_id da7210_i2c_id[] = {
{ "da7210", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, da7210_i2c_id);
/* I2C codec control layer */
static struct i2c_driver da7210_i2c_driver = {
.driver = {
.name = "da7210-codec",
.owner = THIS_MODULE,
},
.probe = da7210_i2c_probe,
.remove = __devexit_p(da7210_i2c_remove),
.id_table = da7210_i2c_id,
};
#endif
static int __init da7210_modinit(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&da7210_i2c_driver);
#endif
return ret;
}
module_init(da7210_modinit);
static void __exit da7210_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&da7210_i2c_driver);
#endif
}
module_exit(da7210_exit);
MODULE_DESCRIPTION("ASoC DA7210 driver");
MODULE_AUTHOR("David Chen, Kuninori Morimoto");
MODULE_LICENSE("GPL");
| gpl-2.0 |
daeiron/LGD855_kernel | drivers/staging/rtl8187se/r8180_rtl8225z2.c | 5071 | 27812 | /*
* This is part of the rtl8180-sa2400 driver
* released under the GPL (See file COPYING for details).
* Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
*
* This files contains programming code for the rtl8225
* radio frontend.
*
* *Many* thanks to Realtek Corp. for their great support!
*/
#include "r8180_hw.h"
#include "r8180_rtl8225.h"
#include "r8180_93cx6.h"
#include "ieee80211/dot11d.h"
static void write_rtl8225(struct net_device *dev, u8 adr, u16 data)
{
int i;
u16 out, select;
u8 bit;
u32 bangdata = (data << 4) | (adr & 0xf);
out = read_nic_word(dev, RFPinsOutput) & 0xfff3;
write_nic_word(dev, RFPinsEnable,
(read_nic_word(dev, RFPinsEnable) | 0x7));
select = read_nic_word(dev, RFPinsSelect);
write_nic_word(dev, RFPinsSelect, select | 0x7 |
SW_CONTROL_GPIO);
force_pci_posting(dev);
udelay(10);
write_nic_word(dev, RFPinsOutput, out | BB_HOST_BANG_EN);
force_pci_posting(dev);
udelay(2);
write_nic_word(dev, RFPinsOutput, out);
force_pci_posting(dev);
udelay(10);
for (i = 15; i >= 0; i--) {
bit = (bangdata & (1 << i)) >> i;
write_nic_word(dev, RFPinsOutput, bit | out);
write_nic_word(dev, RFPinsOutput, bit | out | BB_HOST_BANG_CLK);
write_nic_word(dev, RFPinsOutput, bit | out | BB_HOST_BANG_CLK);
i--;
bit = (bangdata & (1 << i)) >> i;
write_nic_word(dev, RFPinsOutput, bit | out | BB_HOST_BANG_CLK);
write_nic_word(dev, RFPinsOutput, bit | out | BB_HOST_BANG_CLK);
write_nic_word(dev, RFPinsOutput, bit | out);
}
write_nic_word(dev, RFPinsOutput, out | BB_HOST_BANG_EN);
force_pci_posting(dev);
udelay(10);
write_nic_word(dev, RFPinsOutput, out | BB_HOST_BANG_EN);
write_nic_word(dev, RFPinsSelect, select | SW_CONTROL_GPIO);
rtl8185_rf_pins_enable(dev);
}
static const u16 rtl8225bcd_rxgain[] = {
0x0400, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0408, 0x0409,
0x040a, 0x040b, 0x0502, 0x0503, 0x0504, 0x0505, 0x0540, 0x0541,
0x0542, 0x0543, 0x0544, 0x0545, 0x0580, 0x0581, 0x0582, 0x0583,
0x0584, 0x0585, 0x0588, 0x0589, 0x058a, 0x058b, 0x0643, 0x0644,
0x0645, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0688,
0x0689, 0x068a, 0x068b, 0x068c, 0x0742, 0x0743, 0x0744, 0x0745,
0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0788, 0x0789,
0x078a, 0x078b, 0x078c, 0x078d, 0x0790, 0x0791, 0x0792, 0x0793,
0x0794, 0x0795, 0x0798, 0x0799, 0x079a, 0x079b, 0x079c, 0x079d,
0x07a0, 0x07a1, 0x07a2, 0x07a3, 0x07a4, 0x07a5, 0x07a8, 0x07a9,
0x07aa, 0x07ab, 0x07ac, 0x07ad, 0x07b0, 0x07b1, 0x07b2, 0x07b3,
0x07b4, 0x07b5, 0x07b8, 0x07b9, 0x07ba, 0x07bb, 0x07bb
};
static const u8 rtl8225_agc[] = {
0x9e, 0x9e, 0x9e, 0x9e, 0x9e, 0x9e, 0x9e, 0x9e,
0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96,
0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e,
0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86,
0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x3f, 0x3e,
0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36,
0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e,
0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26,
0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e,
0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16,
0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x0f, 0x0e,
0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06,
0x05, 0x04, 0x03, 0x02, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
};
static const u8 rtl8225_gain[] = {
0x23, 0x88, 0x7c, 0xa5, /* -82dBm */
0x23, 0x88, 0x7c, 0xb5, /* -82dBm */
0x23, 0x88, 0x7c, 0xc5, /* -82dBm */
0x33, 0x80, 0x79, 0xc5, /* -78dBm */
0x43, 0x78, 0x76, 0xc5, /* -74dBm */
0x53, 0x60, 0x73, 0xc5, /* -70dBm */
0x63, 0x58, 0x70, 0xc5, /* -66dBm */
};
static const u8 rtl8225_tx_gain_cck_ofdm[] = {
0x02, 0x06, 0x0e, 0x1e, 0x3e, 0x7e
};
static const u8 rtl8225_tx_power_cck[] = {
0x18, 0x17, 0x15, 0x11, 0x0c, 0x08, 0x04, 0x02,
0x1b, 0x1a, 0x17, 0x13, 0x0e, 0x09, 0x04, 0x02,
0x1f, 0x1e, 0x1a, 0x15, 0x10, 0x0a, 0x05, 0x02,
0x22, 0x21, 0x1d, 0x18, 0x11, 0x0b, 0x06, 0x02,
0x26, 0x25, 0x21, 0x1b, 0x14, 0x0d, 0x06, 0x03,
0x2b, 0x2a, 0x25, 0x1e, 0x16, 0x0e, 0x07, 0x03
};
static const u8 rtl8225_tx_power_cck_ch14[] = {
0x18, 0x17, 0x15, 0x0c, 0x00, 0x00, 0x00, 0x00,
0x1b, 0x1a, 0x17, 0x0e, 0x00, 0x00, 0x00, 0x00,
0x1f, 0x1e, 0x1a, 0x0f, 0x00, 0x00, 0x00, 0x00,
0x22, 0x21, 0x1d, 0x11, 0x00, 0x00, 0x00, 0x00,
0x26, 0x25, 0x21, 0x13, 0x00, 0x00, 0x00, 0x00,
0x2b, 0x2a, 0x25, 0x15, 0x00, 0x00, 0x00, 0x00
};
static const u8 rtl8225_tx_power_ofdm[] = {
0x80, 0x90, 0xa2, 0xb5, 0xcb, 0xe4
};
static const u32 rtl8225_chan[] = {
0,
0x0080, 0x0100, 0x0180, 0x0200, 0x0280, 0x0300, 0x0380,
0x0400, 0x0480, 0x0500, 0x0580, 0x0600, 0x0680, 0x074A,
};
static void rtl8225_SetTXPowerLevel(struct net_device *dev, short ch)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int GainIdx;
int GainSetting;
int i;
u8 power;
const u8 *cck_power_table;
u8 max_cck_power_level;
u8 max_ofdm_power_level;
u8 min_ofdm_power_level;
u8 cck_power_level = 0xff & priv->chtxpwr[ch];
u8 ofdm_power_level = 0xff & priv->chtxpwr_ofdm[ch];
max_cck_power_level = 35;
max_ofdm_power_level = 35;
min_ofdm_power_level = 0;
if (cck_power_level > max_cck_power_level)
cck_power_level = max_cck_power_level;
GainIdx = cck_power_level % 6;
GainSetting = cck_power_level / 6;
if (ch == 14)
cck_power_table = rtl8225_tx_power_cck_ch14;
else
cck_power_table = rtl8225_tx_power_cck;
write_nic_byte(dev, TX_GAIN_CCK,
rtl8225_tx_gain_cck_ofdm[GainSetting] >> 1);
for (i = 0; i < 8; i++) {
power = cck_power_table[GainIdx * 8 + i];
write_phy_cck(dev, 0x44 + i, power);
}
/* FIXME Is this delay really needeed ? */
force_pci_posting(dev);
mdelay(1);
if (ofdm_power_level > (max_ofdm_power_level - min_ofdm_power_level))
ofdm_power_level = max_ofdm_power_level;
else
ofdm_power_level += min_ofdm_power_level;
if (ofdm_power_level > 35)
ofdm_power_level = 35;
GainIdx = ofdm_power_level % 6;
GainSetting = ofdm_power_level / 6;
rtl8185_set_anaparam2(dev, RTL8225_ANAPARAM2_ON);
write_phy_ofdm(dev, 2, 0x42);
write_phy_ofdm(dev, 6, 0x00);
write_phy_ofdm(dev, 8, 0x00);
write_nic_byte(dev, TX_GAIN_OFDM,
rtl8225_tx_gain_cck_ofdm[GainSetting] >> 1);
power = rtl8225_tx_power_ofdm[GainIdx];
write_phy_ofdm(dev, 5, power);
write_phy_ofdm(dev, 7, power);
force_pci_posting(dev);
mdelay(1);
}
static const u8 rtl8225z2_threshold[] = {
0x8d, 0x8d, 0x8d, 0x8d, 0x9d, 0xad, 0xbd,
};
static const u8 rtl8225z2_gain_bg[] = {
0x23, 0x15, 0xa5, /* -82-1dBm */
0x23, 0x15, 0xb5, /* -82-2dBm */
0x23, 0x15, 0xc5, /* -82-3dBm */
0x33, 0x15, 0xc5, /* -78dBm */
0x43, 0x15, 0xc5, /* -74dBm */
0x53, 0x15, 0xc5, /* -70dBm */
0x63, 0x15, 0xc5, /* -66dBm */
};
static const u8 rtl8225z2_gain_a[] = {
0x13, 0x27, 0x5a, /* -82dBm */
0x23, 0x23, 0x58, /* -82dBm */
0x33, 0x1f, 0x56, /* -82dBm */
0x43, 0x1b, 0x54, /* -78dBm */
0x53, 0x17, 0x51, /* -74dBm */
0x63, 0x24, 0x4f, /* -70dBm */
0x73, 0x0f, 0x4c, /* -66dBm */
};
static const u16 rtl8225z2_rxgain[] = {
0x0400, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0408, 0x0409,
0x040a, 0x040b, 0x0502, 0x0503, 0x0504, 0x0505, 0x0540, 0x0541,
0x0542, 0x0543, 0x0544, 0x0545, 0x0580, 0x0581, 0x0582, 0x0583,
0x0584, 0x0585, 0x0588, 0x0589, 0x058a, 0x058b, 0x0643, 0x0644,
0x0645, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0688,
0x0689, 0x068a, 0x068b, 0x068c, 0x0742, 0x0743, 0x0744, 0x0745,
0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0788, 0x0789,
0x078a, 0x078b, 0x078c, 0x078d, 0x0790, 0x0791, 0x0792, 0x0793,
0x0794, 0x0795, 0x0798, 0x0799, 0x079a, 0x079b, 0x079c, 0x079d,
0x07a0, 0x07a1, 0x07a2, 0x07a3, 0x07a4, 0x07a5, 0x07a8, 0x07a9,
0x03aa, 0x03ab, 0x03ac, 0x03ad, 0x03b0, 0x03b1, 0x03b2, 0x03b3,
0x03b4, 0x03b5, 0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bb
};
static const u8 ZEBRA2_CCK_OFDM_GAIN_SETTING[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11,
0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
};
static const u8 rtl8225z2_tx_power_ofdm[] = {
0x42, 0x00, 0x40, 0x00, 0x40
};
static const u8 rtl8225z2_tx_power_cck_ch14[] = {
0x36, 0x35, 0x2e, 0x1b, 0x00, 0x00, 0x00, 0x00
};
static const u8 rtl8225z2_tx_power_cck[] = {
0x36, 0x35, 0x2e, 0x25, 0x1c, 0x12, 0x09, 0x04
};
void rtl8225z2_set_gain(struct net_device *dev, short gain)
{
const u8 *rtl8225_gain;
struct r8180_priv *priv = ieee80211_priv(dev);
u8 mode = priv->ieee80211->mode;
if (mode == IEEE_B || mode == IEEE_G)
rtl8225_gain = rtl8225z2_gain_bg;
else
rtl8225_gain = rtl8225z2_gain_a;
write_phy_ofdm(dev, 0x0b, rtl8225_gain[gain * 3]);
write_phy_ofdm(dev, 0x1b, rtl8225_gain[gain * 3 + 1]);
write_phy_ofdm(dev, 0x1d, rtl8225_gain[gain * 3 + 2]);
write_phy_ofdm(dev, 0x21, 0x37);
}
static u32 read_rtl8225(struct net_device *dev, u8 adr)
{
u32 data2Write = ((u32)(adr & 0x1f)) << 27;
u32 dataRead;
u32 mask;
u16 oval, oval2, oval3, tmp;
int i;
short bit, rw;
u8 wLength = 6;
u8 rLength = 12;
u8 low2high = 0;
oval = read_nic_word(dev, RFPinsOutput);
oval2 = read_nic_word(dev, RFPinsEnable);
oval3 = read_nic_word(dev, RFPinsSelect);
write_nic_word(dev, RFPinsEnable, (oval2|0xf));
write_nic_word(dev, RFPinsSelect, (oval3|0xf));
dataRead = 0;
oval &= ~0xf;
write_nic_word(dev, RFPinsOutput, oval | BB_HOST_BANG_EN);
udelay(4);
write_nic_word(dev, RFPinsOutput, oval);
udelay(5);
rw = 0;
mask = (low2high) ? 0x01 : (((u32)0x01)<<(32-1));
for (i = 0; i < wLength/2; i++) {
bit = ((data2Write&mask) != 0) ? 1 : 0;
write_nic_word(dev, RFPinsOutput, bit | oval | rw);
udelay(1);
write_nic_word(dev, RFPinsOutput,
bit | oval | BB_HOST_BANG_CLK | rw);
udelay(2);
write_nic_word(dev, RFPinsOutput,
bit | oval | BB_HOST_BANG_CLK | rw);
udelay(2);
mask = (low2high) ? (mask<<1) : (mask>>1);
if (i == 2) {
rw = BB_HOST_BANG_RW;
write_nic_word(dev, RFPinsOutput,
bit | oval | BB_HOST_BANG_CLK | rw);
udelay(2);
write_nic_word(dev, RFPinsOutput, bit | oval | rw);
udelay(2);
break;
}
bit = ((data2Write&mask) != 0) ? 1 : 0;
write_nic_word(dev, RFPinsOutput,
oval | bit | rw | BB_HOST_BANG_CLK);
udelay(2);
write_nic_word(dev, RFPinsOutput,
oval | bit | rw | BB_HOST_BANG_CLK);
udelay(2);
write_nic_word(dev, RFPinsOutput, oval | bit | rw);
udelay(1);
mask = (low2high) ? (mask<<1) : (mask>>1);
}
write_nic_word(dev, RFPinsOutput, rw|oval);
udelay(2);
mask = (low2high) ? 0x01 : (((u32)0x01) << (12-1));
/*
* We must set data pin to HW controlled, otherwise RF can't driver it
* and value RF register won't be able to read back properly.
*/
write_nic_word(dev, RFPinsEnable, (oval2 & (~0x01)));
for (i = 0; i < rLength; i++) {
write_nic_word(dev, RFPinsOutput, rw|oval); udelay(1);
write_nic_word(dev, RFPinsOutput, rw|oval|BB_HOST_BANG_CLK);
udelay(2);
write_nic_word(dev, RFPinsOutput, rw|oval|BB_HOST_BANG_CLK);
udelay(2);
write_nic_word(dev, RFPinsOutput, rw|oval|BB_HOST_BANG_CLK);
udelay(2);
tmp = read_nic_word(dev, RFPinsInput);
dataRead |= (tmp & BB_HOST_BANG_CLK ? mask : 0);
write_nic_word(dev, RFPinsOutput, (rw|oval)); udelay(2);
mask = (low2high) ? (mask<<1) : (mask>>1);
}
write_nic_word(dev, RFPinsOutput,
BB_HOST_BANG_EN | BB_HOST_BANG_RW | oval);
udelay(2);
write_nic_word(dev, RFPinsEnable, oval2);
write_nic_word(dev, RFPinsSelect, oval3); /* Set To SW Switch */
write_nic_word(dev, RFPinsOutput, 0x3a0);
return dataRead;
}
short rtl8225_is_V_z2(struct net_device *dev)
{
short vz2 = 1;
if (read_rtl8225(dev, 8) != 0x588)
vz2 = 0;
else /* reg 9 pg 1 = 24 */
if (read_rtl8225(dev, 9) != 0x700)
vz2 = 0;
/* sw back to pg 0 */
write_rtl8225(dev, 0, 0xb7);
return vz2;
}
void rtl8225z2_rf_close(struct net_device *dev)
{
RF_WriteReg(dev, 0x4, 0x1f);
force_pci_posting(dev);
mdelay(1);
rtl8180_set_anaparam(dev, RTL8225z2_ANAPARAM_OFF);
rtl8185_set_anaparam2(dev, RTL8225z2_ANAPARAM2_OFF);
}
/*
* Map dBm into Tx power index according to current HW model, for example,
* RF and PA, and current wireless mode.
*/
s8 DbmToTxPwrIdx(struct r8180_priv *priv, WIRELESS_MODE WirelessMode,
s32 PowerInDbm)
{
bool bUseDefault = true;
s8 TxPwrIdx = 0;
/*
* OFDM Power in dBm = Index * 0.5 + 0
* CCK Power in dBm = Index * 0.25 + 13
*/
s32 tmp = 0;
if (WirelessMode == WIRELESS_MODE_G) {
bUseDefault = false;
tmp = (2 * PowerInDbm);
if (tmp < 0)
TxPwrIdx = 0;
else if (tmp > 40) /* 40 means 20 dBm. */
TxPwrIdx = 40;
else
TxPwrIdx = (s8)tmp;
} else if (WirelessMode == WIRELESS_MODE_B) {
bUseDefault = false;
tmp = (4 * PowerInDbm) - 52;
if (tmp < 0)
TxPwrIdx = 0;
else if (tmp > 28) /* 28 means 20 dBm. */
TxPwrIdx = 28;
else
TxPwrIdx = (s8)tmp;
}
/*
* TRUE if we want to use a default implementation.
* We shall set it to FALSE when we have exact translation formular
* for target IC. 070622, by rcnjko.
*/
if (bUseDefault) {
if (PowerInDbm < 0)
TxPwrIdx = 0;
else if (PowerInDbm > 35)
TxPwrIdx = 35;
else
TxPwrIdx = (u8)PowerInDbm;
}
return TxPwrIdx;
}
void rtl8225z2_SetTXPowerLevel(struct net_device *dev, short ch)
{
struct r8180_priv *priv = ieee80211_priv(dev);
u8 max_cck_power_level;
u8 max_ofdm_power_level;
u8 min_ofdm_power_level;
char cck_power_level = (char)(0xff & priv->chtxpwr[ch]);
char ofdm_power_level = (char)(0xff & priv->chtxpwr_ofdm[ch]);
if (IS_DOT11D_ENABLE(priv->ieee80211) &&
IS_DOT11D_STATE_DONE(priv->ieee80211)) {
u8 MaxTxPwrInDbm = DOT11D_GetMaxTxPwrInDbm(priv->ieee80211, ch);
u8 CckMaxPwrIdx = DbmToTxPwrIdx(priv, WIRELESS_MODE_B,
MaxTxPwrInDbm);
u8 OfdmMaxPwrIdx = DbmToTxPwrIdx(priv, WIRELESS_MODE_G,
MaxTxPwrInDbm);
if (cck_power_level > CckMaxPwrIdx)
cck_power_level = CckMaxPwrIdx;
if (ofdm_power_level > OfdmMaxPwrIdx)
ofdm_power_level = OfdmMaxPwrIdx;
}
max_cck_power_level = 15;
max_ofdm_power_level = 25;
min_ofdm_power_level = 10;
if (cck_power_level > 35)
cck_power_level = 35;
write_nic_byte(dev, CCK_TXAGC,
(ZEBRA2_CCK_OFDM_GAIN_SETTING[(u8)cck_power_level]));
force_pci_posting(dev);
mdelay(1);
if (ofdm_power_level > 35)
ofdm_power_level = 35;
if (priv->up == 0) {
write_phy_ofdm(dev, 2, 0x42);
write_phy_ofdm(dev, 5, 0x00);
write_phy_ofdm(dev, 6, 0x40);
write_phy_ofdm(dev, 7, 0x00);
write_phy_ofdm(dev, 8, 0x40);
}
write_nic_byte(dev, OFDM_TXAGC,
ZEBRA2_CCK_OFDM_GAIN_SETTING[(u8)ofdm_power_level]);
if (ofdm_power_level <= 11) {
write_phy_ofdm(dev, 0x07, 0x5c);
write_phy_ofdm(dev, 0x09, 0x5c);
}
if (ofdm_power_level <= 17) {
write_phy_ofdm(dev, 0x07, 0x54);
write_phy_ofdm(dev, 0x09, 0x54);
} else {
write_phy_ofdm(dev, 0x07, 0x50);
write_phy_ofdm(dev, 0x09, 0x50);
}
force_pci_posting(dev);
mdelay(1);
}
void rtl8225z2_rf_set_chan(struct net_device *dev, short ch)
{
rtl8225z2_SetTXPowerLevel(dev, ch);
RF_WriteReg(dev, 0x7, rtl8225_chan[ch]);
if ((RF_ReadReg(dev, 0x7) & 0x0F80) != rtl8225_chan[ch])
RF_WriteReg(dev, 0x7, rtl8225_chan[ch]);
mdelay(1);
force_pci_posting(dev);
mdelay(10);
}
static void rtl8225_host_pci_init(struct net_device *dev)
{
write_nic_word(dev, RFPinsOutput, 0x480);
rtl8185_rf_pins_enable(dev);
write_nic_word(dev, RFPinsSelect, 0x88 | SW_CONTROL_GPIO);
write_nic_byte(dev, GP_ENABLE, 0);
force_pci_posting(dev);
mdelay(200);
/* bit 6 is for RF on/off detection */
write_nic_word(dev, GP_ENABLE, 0xff & (~(1 << 6)));
}
static void rtl8225_rf_set_chan(struct net_device *dev, short ch)
{
struct r8180_priv *priv = ieee80211_priv(dev);
short gset = (priv->ieee80211->state == IEEE80211_LINKED &&
ieee80211_is_54g(&priv->ieee80211->current_network)) ||
priv->ieee80211->iw_mode == IW_MODE_MONITOR;
rtl8225_SetTXPowerLevel(dev, ch);
write_rtl8225(dev, 0x7, rtl8225_chan[ch]);
force_pci_posting(dev);
mdelay(10);
if (gset) {
write_nic_byte(dev, SIFS, 0x22);
write_nic_byte(dev, DIFS, 0x14);
} else {
write_nic_byte(dev, SIFS, 0x44);
write_nic_byte(dev, DIFS, 0x24);
}
if (priv->ieee80211->state == IEEE80211_LINKED &&
ieee80211_is_shortslot(&priv->ieee80211->current_network))
write_nic_byte(dev, SLOT, 0x9);
else
write_nic_byte(dev, SLOT, 0x14);
if (gset) {
write_nic_byte(dev, EIFS, 81);
write_nic_byte(dev, CW_VAL, 0x73);
} else {
write_nic_byte(dev, EIFS, 81);
write_nic_byte(dev, CW_VAL, 0xa5);
}
}
void rtl8225z2_rf_init(struct net_device *dev)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int i;
short channel = 1;
u16 brsr;
u32 data, addr;
priv->chan = channel;
rtl8225_host_pci_init(dev);
write_nic_dword(dev, RF_TIMING, 0x000a8008);
brsr = read_nic_word(dev, BRSR);
write_nic_word(dev, BRSR, 0xffff);
write_nic_dword(dev, RF_PARA, 0x100044);
rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
write_nic_byte(dev, CONFIG3, 0x44);
rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
rtl8185_rf_pins_enable(dev);
write_rtl8225(dev, 0x0, 0x2bf); mdelay(1);
write_rtl8225(dev, 0x1, 0xee0); mdelay(1);
write_rtl8225(dev, 0x2, 0x44d); mdelay(1);
write_rtl8225(dev, 0x3, 0x441); mdelay(1);
write_rtl8225(dev, 0x4, 0x8c3); mdelay(1);
write_rtl8225(dev, 0x5, 0xc72); mdelay(1);
write_rtl8225(dev, 0x6, 0xe6); mdelay(1);
write_rtl8225(dev, 0x7, rtl8225_chan[channel]); mdelay(1);
write_rtl8225(dev, 0x8, 0x3f); mdelay(1);
write_rtl8225(dev, 0x9, 0x335); mdelay(1);
write_rtl8225(dev, 0xa, 0x9d4); mdelay(1);
write_rtl8225(dev, 0xb, 0x7bb); mdelay(1);
write_rtl8225(dev, 0xc, 0x850); mdelay(1);
write_rtl8225(dev, 0xd, 0xcdf); mdelay(1);
write_rtl8225(dev, 0xe, 0x2b); mdelay(1);
write_rtl8225(dev, 0xf, 0x114);
mdelay(100);
write_rtl8225(dev, 0x0, 0x1b7);
for (i = 0; i < 95; i++) {
write_rtl8225(dev, 0x1, (u8)(i + 1));
write_rtl8225(dev, 0x2, rtl8225z2_rxgain[i]);
}
write_rtl8225(dev, 0x3, 0x80);
write_rtl8225(dev, 0x5, 0x4);
write_rtl8225(dev, 0x0, 0xb7);
write_rtl8225(dev, 0x2, 0xc4d);
/* FIXME!! rtl8187 we have to check if calibrarion
* is successful and eventually cal. again (repeat
* the two write on reg 2)
*/
data = read_rtl8225(dev, 6);
if (!(data & 0x00000080)) {
write_rtl8225(dev, 0x02, 0x0c4d);
force_pci_posting(dev); mdelay(200);
write_rtl8225(dev, 0x02, 0x044d);
force_pci_posting(dev); mdelay(100);
data = read_rtl8225(dev, 6);
if (!(data & 0x00000080))
DMESGW("RF Calibration Failed!!!!\n");
}
mdelay(200);
write_rtl8225(dev, 0x0, 0x2bf);
for (i = 0; i < 128; i++) {
data = rtl8225_agc[i];
addr = i + 0x80; /* enable writing AGC table */
write_phy_ofdm(dev, 0xb, data);
mdelay(1);
write_phy_ofdm(dev, 0xa, addr);
mdelay(1);
}
force_pci_posting(dev);
mdelay(1);
write_phy_ofdm(dev, 0x00, 0x01); mdelay(1);
write_phy_ofdm(dev, 0x01, 0x02); mdelay(1);
write_phy_ofdm(dev, 0x02, 0x62); mdelay(1);
write_phy_ofdm(dev, 0x03, 0x00); mdelay(1);
write_phy_ofdm(dev, 0x04, 0x00); mdelay(1);
write_phy_ofdm(dev, 0x05, 0x00); mdelay(1);
write_phy_ofdm(dev, 0x06, 0x40); mdelay(1);
write_phy_ofdm(dev, 0x07, 0x00); mdelay(1);
write_phy_ofdm(dev, 0x08, 0x40); mdelay(1);
write_phy_ofdm(dev, 0x09, 0xfe); mdelay(1);
write_phy_ofdm(dev, 0x0a, 0x08); mdelay(1);
write_phy_ofdm(dev, 0x0b, 0x80); mdelay(1);
write_phy_ofdm(dev, 0x0c, 0x01); mdelay(1);
write_phy_ofdm(dev, 0x0d, 0x43);
write_phy_ofdm(dev, 0x0e, 0xd3); mdelay(1);
write_phy_ofdm(dev, 0x0f, 0x38); mdelay(1);
write_phy_ofdm(dev, 0x10, 0x84); mdelay(1);
write_phy_ofdm(dev, 0x11, 0x07); mdelay(1);
write_phy_ofdm(dev, 0x12, 0x20); mdelay(1);
write_phy_ofdm(dev, 0x13, 0x20); mdelay(1);
write_phy_ofdm(dev, 0x14, 0x00); mdelay(1);
write_phy_ofdm(dev, 0x15, 0x40); mdelay(1);
write_phy_ofdm(dev, 0x16, 0x00); mdelay(1);
write_phy_ofdm(dev, 0x17, 0x40); mdelay(1);
write_phy_ofdm(dev, 0x18, 0xef); mdelay(1);
write_phy_ofdm(dev, 0x19, 0x19); mdelay(1);
write_phy_ofdm(dev, 0x1a, 0x20); mdelay(1);
write_phy_ofdm(dev, 0x1b, 0x15); mdelay(1);
write_phy_ofdm(dev, 0x1c, 0x04); mdelay(1);
write_phy_ofdm(dev, 0x1d, 0xc5); mdelay(1);
write_phy_ofdm(dev, 0x1e, 0x95); mdelay(1);
write_phy_ofdm(dev, 0x1f, 0x75); mdelay(1);
write_phy_ofdm(dev, 0x20, 0x1f); mdelay(1);
write_phy_ofdm(dev, 0x21, 0x17); mdelay(1);
write_phy_ofdm(dev, 0x22, 0x16); mdelay(1);
write_phy_ofdm(dev, 0x23, 0x80); mdelay(1); /* FIXME maybe not needed */
write_phy_ofdm(dev, 0x24, 0x46); mdelay(1);
write_phy_ofdm(dev, 0x25, 0x00); mdelay(1);
write_phy_ofdm(dev, 0x26, 0x90); mdelay(1);
write_phy_ofdm(dev, 0x27, 0x88); mdelay(1);
rtl8225z2_set_gain(dev, 4);
write_phy_cck(dev, 0x0, 0x98); mdelay(1);
write_phy_cck(dev, 0x3, 0x20); mdelay(1);
write_phy_cck(dev, 0x4, 0x7e); mdelay(1);
write_phy_cck(dev, 0x5, 0x12); mdelay(1);
write_phy_cck(dev, 0x6, 0xfc); mdelay(1);
write_phy_cck(dev, 0x7, 0x78); mdelay(1);
write_phy_cck(dev, 0x8, 0x2e); mdelay(1);
write_phy_cck(dev, 0x10, 0x93); mdelay(1);
write_phy_cck(dev, 0x11, 0x88); mdelay(1);
write_phy_cck(dev, 0x12, 0x47); mdelay(1);
write_phy_cck(dev, 0x13, 0xd0);
write_phy_cck(dev, 0x19, 0x00);
write_phy_cck(dev, 0x1a, 0xa0);
write_phy_cck(dev, 0x1b, 0x08);
write_phy_cck(dev, 0x40, 0x86); /* CCK Carrier Sense Threshold */
write_phy_cck(dev, 0x41, 0x8d); mdelay(1);
write_phy_cck(dev, 0x42, 0x15); mdelay(1);
write_phy_cck(dev, 0x43, 0x18); mdelay(1);
write_phy_cck(dev, 0x44, 0x36); mdelay(1);
write_phy_cck(dev, 0x45, 0x35); mdelay(1);
write_phy_cck(dev, 0x46, 0x2e); mdelay(1);
write_phy_cck(dev, 0x47, 0x25); mdelay(1);
write_phy_cck(dev, 0x48, 0x1c); mdelay(1);
write_phy_cck(dev, 0x49, 0x12); mdelay(1);
write_phy_cck(dev, 0x4a, 0x09); mdelay(1);
write_phy_cck(dev, 0x4b, 0x04); mdelay(1);
write_phy_cck(dev, 0x4c, 0x05); mdelay(1);
write_nic_byte(dev, 0x5b, 0x0d); mdelay(1);
rtl8225z2_SetTXPowerLevel(dev, channel);
/* RX antenna default to A */
write_phy_cck(dev, 0x11, 0x9b); mdelay(1); /* B: 0xDB */
write_phy_ofdm(dev, 0x26, 0x90); mdelay(1); /* B: 0x10 */
rtl8185_tx_antenna(dev, 0x03); /* B: 0x00 */
/* switch to high-speed 3-wire
* last digit. 2 for both cck and ofdm
*/
write_nic_dword(dev, 0x94, 0x15c00002);
rtl8185_rf_pins_enable(dev);
rtl8225_rf_set_chan(dev, priv->chan);
}
void rtl8225z2_rf_set_mode(struct net_device *dev)
{
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->mode == IEEE_A) {
write_rtl8225(dev, 0x5, 0x1865);
write_nic_dword(dev, RF_PARA, 0x10084);
write_nic_dword(dev, RF_TIMING, 0xa8008);
write_phy_ofdm(dev, 0x0, 0x0);
write_phy_ofdm(dev, 0xa, 0x6);
write_phy_ofdm(dev, 0xb, 0x99);
write_phy_ofdm(dev, 0xf, 0x20);
write_phy_ofdm(dev, 0x11, 0x7);
rtl8225z2_set_gain(dev, 4);
write_phy_ofdm(dev, 0x15, 0x40);
write_phy_ofdm(dev, 0x17, 0x40);
write_nic_dword(dev, 0x94, 0x10000000);
} else {
write_rtl8225(dev, 0x5, 0x1864);
write_nic_dword(dev, RF_PARA, 0x10044);
write_nic_dword(dev, RF_TIMING, 0xa8008);
write_phy_ofdm(dev, 0x0, 0x1);
write_phy_ofdm(dev, 0xa, 0x6);
write_phy_ofdm(dev, 0xb, 0x99);
write_phy_ofdm(dev, 0xf, 0x20);
write_phy_ofdm(dev, 0x11, 0x7);
rtl8225z2_set_gain(dev, 4);
write_phy_ofdm(dev, 0x15, 0x40);
write_phy_ofdm(dev, 0x17, 0x40);
write_nic_dword(dev, 0x94, 0x04000002);
}
}
#define MAX_DOZE_WAITING_TIMES_85B 20
#define MAX_POLLING_24F_TIMES_87SE 10
#define LPS_MAX_SLEEP_WAITING_TIMES_87SE 5
bool SetZebraRFPowerState8185(struct net_device *dev,
RT_RF_POWER_STATE eRFPowerState)
{
struct r8180_priv *priv = ieee80211_priv(dev);
u8 btCR9346, btConfig3;
bool bActionAllowed = true, bTurnOffBB = true;
u8 u1bTmp;
int i;
bool bResult = true;
u8 QueueID;
if (priv->SetRFPowerStateInProgress == true)
return false;
priv->SetRFPowerStateInProgress = true;
btCR9346 = read_nic_byte(dev, CR9346);
write_nic_byte(dev, CR9346, (btCR9346 | 0xC0));
btConfig3 = read_nic_byte(dev, CONFIG3);
write_nic_byte(dev, CONFIG3, (btConfig3 | CONFIG3_PARM_En));
switch (eRFPowerState) {
case eRfOn:
write_nic_word(dev, 0x37C, 0x00EC);
/* turn on AFE */
write_nic_byte(dev, 0x54, 0x00);
write_nic_byte(dev, 0x62, 0x00);
/* turn on RF */
RF_WriteReg(dev, 0x0, 0x009f); udelay(500);
RF_WriteReg(dev, 0x4, 0x0972); udelay(500);
/* turn on RF again */
RF_WriteReg(dev, 0x0, 0x009f); udelay(500);
RF_WriteReg(dev, 0x4, 0x0972); udelay(500);
/* turn on BB */
write_phy_ofdm(dev, 0x10, 0x40);
write_phy_ofdm(dev, 0x12, 0x40);
/* Avoid power down at init time. */
write_nic_byte(dev, CONFIG4, priv->RFProgType);
u1bTmp = read_nic_byte(dev, 0x24E);
write_nic_byte(dev, 0x24E, (u1bTmp & (~(BIT5 | BIT6))));
break;
case eRfSleep:
for (QueueID = 0, i = 0; QueueID < 6;) {
if (get_curr_tx_free_desc(dev, QueueID) ==
priv->txringcount) {
QueueID++;
continue;
} else {
priv->TxPollingTimes++;
if (priv->TxPollingTimes >=
LPS_MAX_SLEEP_WAITING_TIMES_87SE) {
bActionAllowed = false;
break;
} else
udelay(10);
}
}
if (bActionAllowed) {
/* turn off BB RXIQ matrix to cut off rx signal */
write_phy_ofdm(dev, 0x10, 0x00);
write_phy_ofdm(dev, 0x12, 0x00);
/* turn off RF */
RF_WriteReg(dev, 0x4, 0x0000);
RF_WriteReg(dev, 0x0, 0x0000);
/* turn off AFE except PLL */
write_nic_byte(dev, 0x62, 0xff);
write_nic_byte(dev, 0x54, 0xec);
mdelay(1);
{
int i = 0;
while (true) {
u8 tmp24F = read_nic_byte(dev, 0x24f);
if ((tmp24F == 0x01) ||
(tmp24F == 0x09)) {
bTurnOffBB = true;
break;
} else {
udelay(10);
i++;
priv->TxPollingTimes++;
if (priv->TxPollingTimes >= LPS_MAX_SLEEP_WAITING_TIMES_87SE) {
bTurnOffBB = false;
break;
} else
udelay(10);
}
}
}
if (bTurnOffBB) {
/* turn off BB */
u1bTmp = read_nic_byte(dev, 0x24E);
write_nic_byte(dev, 0x24E,
(u1bTmp | BIT5 | BIT6));
/* turn off AFE PLL */
write_nic_byte(dev, 0x54, 0xFC);
write_nic_word(dev, 0x37C, 0x00FC);
}
}
break;
case eRfOff:
for (QueueID = 0, i = 0; QueueID < 6;) {
if (get_curr_tx_free_desc(dev, QueueID) ==
priv->txringcount) {
QueueID++;
continue;
} else {
udelay(10);
i++;
}
if (i >= MAX_DOZE_WAITING_TIMES_85B)
break;
}
/* turn off BB RXIQ matrix to cut off rx signal */
write_phy_ofdm(dev, 0x10, 0x00);
write_phy_ofdm(dev, 0x12, 0x00);
/* turn off RF */
RF_WriteReg(dev, 0x4, 0x0000);
RF_WriteReg(dev, 0x0, 0x0000);
/* turn off AFE except PLL */
write_nic_byte(dev, 0x62, 0xff);
write_nic_byte(dev, 0x54, 0xec);
mdelay(1);
{
int i = 0;
while (true) {
u8 tmp24F = read_nic_byte(dev, 0x24f);
if ((tmp24F == 0x01) || (tmp24F == 0x09)) {
bTurnOffBB = true;
break;
} else {
bTurnOffBB = false;
udelay(10);
i++;
}
if (i > MAX_POLLING_24F_TIMES_87SE)
break;
}
}
if (bTurnOffBB) {
/* turn off BB */
u1bTmp = read_nic_byte(dev, 0x24E);
write_nic_byte(dev, 0x24E, (u1bTmp | BIT5 | BIT6));
/* turn off AFE PLL (80M) */
write_nic_byte(dev, 0x54, 0xFC);
write_nic_word(dev, 0x37C, 0x00FC);
}
break;
}
btConfig3 &= ~(CONFIG3_PARM_En);
write_nic_byte(dev, CONFIG3, btConfig3);
btCR9346 &= ~(0xC0);
write_nic_byte(dev, CR9346, btCR9346);
if (bResult && bActionAllowed)
priv->eRFPowerState = eRFPowerState;
priv->SetRFPowerStateInProgress = false;
return bResult && bActionAllowed;
}
void rtl8225z4_rf_sleep(struct net_device *dev)
{
MgntActSet_RF_State(dev, eRfSleep, RF_CHANGE_BY_PS);
}
void rtl8225z4_rf_wakeup(struct net_device *dev)
{
MgntActSet_RF_State(dev, eRfOn, RF_CHANGE_BY_PS);
}
| gpl-2.0 |
widz4rd/WIDzard-A860S | drivers/acpi/dock.c | 5071 | 28515 | /*
* dock.c - ACPI dock station driver
*
* Copyright (C) 2006 Kristen Carlson Accardi <kristen.c.accardi@intel.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/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/notifier.h>
#include <linux/platform_device.h>
#include <linux/jiffies.h>
#include <linux/stddef.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#define PREFIX "ACPI: "
#define ACPI_DOCK_DRIVER_DESCRIPTION "ACPI Dock Station Driver"
ACPI_MODULE_NAME("dock");
MODULE_AUTHOR("Kristen Carlson Accardi");
MODULE_DESCRIPTION(ACPI_DOCK_DRIVER_DESCRIPTION);
MODULE_LICENSE("GPL");
static bool immediate_undock = 1;
module_param(immediate_undock, bool, 0644);
MODULE_PARM_DESC(immediate_undock, "1 (default) will cause the driver to "
"undock immediately when the undock button is pressed, 0 will cause"
" the driver to wait for userspace to write the undock sysfs file "
" before undocking");
static struct atomic_notifier_head dock_notifier_list;
static const struct acpi_device_id dock_device_ids[] = {
{"LNXDOCK", 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, dock_device_ids);
struct dock_station {
acpi_handle handle;
unsigned long last_dock_time;
u32 flags;
spinlock_t dd_lock;
struct mutex hp_lock;
struct list_head dependent_devices;
struct list_head hotplug_devices;
struct list_head sibling;
struct platform_device *dock_device;
};
static LIST_HEAD(dock_stations);
static int dock_station_count;
struct dock_dependent_device {
struct list_head list;
struct list_head hotplug_list;
acpi_handle handle;
const struct acpi_dock_ops *ops;
void *context;
};
#define DOCK_DOCKING 0x00000001
#define DOCK_UNDOCKING 0x00000002
#define DOCK_IS_DOCK 0x00000010
#define DOCK_IS_ATA 0x00000020
#define DOCK_IS_BAT 0x00000040
#define DOCK_EVENT 3
#define UNDOCK_EVENT 2
/*****************************************************************************
* Dock Dependent device functions *
*****************************************************************************/
/**
* add_dock_dependent_device - associate a device with the dock station
* @ds: The dock station
* @handle: handle of the dependent device
*
* Add the dependent device to the dock's dependent device list.
*/
static int
add_dock_dependent_device(struct dock_station *ds, acpi_handle handle)
{
struct dock_dependent_device *dd;
dd = kzalloc(sizeof(*dd), GFP_KERNEL);
if (!dd)
return -ENOMEM;
dd->handle = handle;
INIT_LIST_HEAD(&dd->list);
INIT_LIST_HEAD(&dd->hotplug_list);
spin_lock(&ds->dd_lock);
list_add_tail(&dd->list, &ds->dependent_devices);
spin_unlock(&ds->dd_lock);
return 0;
}
/**
* dock_add_hotplug_device - associate a hotplug handler with the dock station
* @ds: The dock station
* @dd: The dependent device struct
*
* Add the dependent device to the dock's hotplug device list
*/
static void
dock_add_hotplug_device(struct dock_station *ds,
struct dock_dependent_device *dd)
{
mutex_lock(&ds->hp_lock);
list_add_tail(&dd->hotplug_list, &ds->hotplug_devices);
mutex_unlock(&ds->hp_lock);
}
/**
* dock_del_hotplug_device - remove a hotplug handler from the dock station
* @ds: The dock station
* @dd: the dependent device struct
*
* Delete the dependent device from the dock's hotplug device list
*/
static void
dock_del_hotplug_device(struct dock_station *ds,
struct dock_dependent_device *dd)
{
mutex_lock(&ds->hp_lock);
list_del(&dd->hotplug_list);
mutex_unlock(&ds->hp_lock);
}
/**
* find_dock_dependent_device - get a device dependent on this dock
* @ds: the dock station
* @handle: the acpi_handle of the device we want
*
* iterate over the dependent device list for this dock. If the
* dependent device matches the handle, return.
*/
static struct dock_dependent_device *
find_dock_dependent_device(struct dock_station *ds, acpi_handle handle)
{
struct dock_dependent_device *dd;
spin_lock(&ds->dd_lock);
list_for_each_entry(dd, &ds->dependent_devices, list) {
if (handle == dd->handle) {
spin_unlock(&ds->dd_lock);
return dd;
}
}
spin_unlock(&ds->dd_lock);
return NULL;
}
/*****************************************************************************
* Dock functions *
*****************************************************************************/
/**
* is_dock - see if a device is a dock station
* @handle: acpi handle of the device
*
* If an acpi object has a _DCK method, then it is by definition a dock
* station, so return true.
*/
static int is_dock(acpi_handle handle)
{
acpi_status status;
acpi_handle tmp;
status = acpi_get_handle(handle, "_DCK", &tmp);
if (ACPI_FAILURE(status))
return 0;
return 1;
}
static int is_ejectable(acpi_handle handle)
{
acpi_status status;
acpi_handle tmp;
status = acpi_get_handle(handle, "_EJ0", &tmp);
if (ACPI_FAILURE(status))
return 0;
return 1;
}
static int is_ata(acpi_handle handle)
{
acpi_handle tmp;
if ((ACPI_SUCCESS(acpi_get_handle(handle, "_GTF", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_GTM", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_STM", &tmp))) ||
(ACPI_SUCCESS(acpi_get_handle(handle, "_SDD", &tmp))))
return 1;
return 0;
}
static int is_battery(acpi_handle handle)
{
struct acpi_device_info *info;
int ret = 1;
if (!ACPI_SUCCESS(acpi_get_object_info(handle, &info)))
return 0;
if (!(info->valid & ACPI_VALID_HID))
ret = 0;
else
ret = !strcmp("PNP0C0A", info->hardware_id.string);
kfree(info);
return ret;
}
static int is_ejectable_bay(acpi_handle handle)
{
acpi_handle phandle;
if (!is_ejectable(handle))
return 0;
if (is_battery(handle) || is_ata(handle))
return 1;
if (!acpi_get_parent(handle, &phandle) && is_ata(phandle))
return 1;
return 0;
}
/**
* is_dock_device - see if a device is on a dock station
* @handle: acpi handle of the device
*
* If this device is either the dock station itself,
* or is a device dependent on the dock station, then it
* is a dock device
*/
int is_dock_device(acpi_handle handle)
{
struct dock_station *dock_station;
if (!dock_station_count)
return 0;
if (is_dock(handle))
return 1;
list_for_each_entry(dock_station, &dock_stations, sibling)
if (find_dock_dependent_device(dock_station, handle))
return 1;
return 0;
}
EXPORT_SYMBOL_GPL(is_dock_device);
/**
* dock_present - see if the dock station is present.
* @ds: the dock station
*
* execute the _STA method. note that present does not
* imply that we are docked.
*/
static int dock_present(struct dock_station *ds)
{
unsigned long long sta;
acpi_status status;
if (ds) {
status = acpi_evaluate_integer(ds->handle, "_STA", NULL, &sta);
if (ACPI_SUCCESS(status) && sta)
return 1;
}
return 0;
}
/**
* dock_create_acpi_device - add new devices to acpi
* @handle - handle of the device to add
*
* This function will create a new acpi_device for the given
* handle if one does not exist already. This should cause
* acpi to scan for drivers for the given devices, and call
* matching driver's add routine.
*
* Returns a pointer to the acpi_device corresponding to the handle.
*/
static struct acpi_device * dock_create_acpi_device(acpi_handle handle)
{
struct acpi_device *device;
struct acpi_device *parent_device;
acpi_handle parent;
int ret;
if (acpi_bus_get_device(handle, &device)) {
/*
* no device created for this object,
* so we should create one.
*/
acpi_get_parent(handle, &parent);
if (acpi_bus_get_device(parent, &parent_device))
parent_device = NULL;
ret = acpi_bus_add(&device, parent_device, handle,
ACPI_BUS_TYPE_DEVICE);
if (ret) {
pr_debug("error adding bus, %x\n", -ret);
return NULL;
}
}
return device;
}
/**
* dock_remove_acpi_device - remove the acpi_device struct from acpi
* @handle - the handle of the device to remove
*
* Tell acpi to remove the acpi_device. This should cause any loaded
* driver to have it's remove routine called.
*/
static void dock_remove_acpi_device(acpi_handle handle)
{
struct acpi_device *device;
int ret;
if (!acpi_bus_get_device(handle, &device)) {
ret = acpi_bus_trim(device, 1);
if (ret)
pr_debug("error removing bus, %x\n", -ret);
}
}
/**
* hotplug_dock_devices - insert or remove devices on the dock station
* @ds: the dock station
* @event: either bus check or eject request
*
* Some devices on the dock station need to have drivers called
* to perform hotplug operations after a dock event has occurred.
* Traverse the list of dock devices that have registered a
* hotplug handler, and call the handler.
*/
static void hotplug_dock_devices(struct dock_station *ds, u32 event)
{
struct dock_dependent_device *dd;
mutex_lock(&ds->hp_lock);
/*
* First call driver specific hotplug functions
*/
list_for_each_entry(dd, &ds->hotplug_devices, hotplug_list)
if (dd->ops && dd->ops->handler)
dd->ops->handler(dd->handle, event, dd->context);
/*
* Now make sure that an acpi_device is created for each
* dependent device, or removed if this is an eject request.
* This will cause acpi_drivers to be stopped/started if they
* exist
*/
list_for_each_entry(dd, &ds->dependent_devices, list) {
if (event == ACPI_NOTIFY_EJECT_REQUEST)
dock_remove_acpi_device(dd->handle);
else
dock_create_acpi_device(dd->handle);
}
mutex_unlock(&ds->hp_lock);
}
static void dock_event(struct dock_station *ds, u32 event, int num)
{
struct device *dev = &ds->dock_device->dev;
char event_string[13];
char *envp[] = { event_string, NULL };
struct dock_dependent_device *dd;
if (num == UNDOCK_EVENT)
sprintf(event_string, "EVENT=undock");
else
sprintf(event_string, "EVENT=dock");
/*
* Indicate that the status of the dock station has
* changed.
*/
if (num == DOCK_EVENT)
kobject_uevent_env(&dev->kobj, KOBJ_CHANGE, envp);
list_for_each_entry(dd, &ds->hotplug_devices, hotplug_list)
if (dd->ops && dd->ops->uevent)
dd->ops->uevent(dd->handle, event, dd->context);
if (num != DOCK_EVENT)
kobject_uevent_env(&dev->kobj, KOBJ_CHANGE, envp);
}
/**
* eject_dock - respond to a dock eject request
* @ds: the dock station
*
* This is called after _DCK is called, to execute the dock station's
* _EJ0 method.
*/
static void eject_dock(struct dock_station *ds)
{
struct acpi_object_list arg_list;
union acpi_object arg;
acpi_status status;
acpi_handle tmp;
/* all dock devices should have _EJ0, but check anyway */
status = acpi_get_handle(ds->handle, "_EJ0", &tmp);
if (ACPI_FAILURE(status)) {
pr_debug("No _EJ0 support for dock device\n");
return;
}
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = 1;
status = acpi_evaluate_object(ds->handle, "_EJ0", &arg_list, NULL);
if (ACPI_FAILURE(status))
pr_debug("Failed to evaluate _EJ0!\n");
}
/**
* handle_dock - handle a dock event
* @ds: the dock station
* @dock: to dock, or undock - that is the question
*
* Execute the _DCK method in response to an acpi event
*/
static void handle_dock(struct dock_station *ds, int dock)
{
acpi_status status;
struct acpi_object_list arg_list;
union acpi_object arg;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
struct acpi_buffer name_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
acpi_get_name(ds->handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_INFO PREFIX "%s - %s\n",
(char *)name_buffer.pointer, dock ? "docking" : "undocking");
/* _DCK method has one argument */
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = dock;
status = acpi_evaluate_object(ds->handle, "_DCK", &arg_list, &buffer);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND)
ACPI_EXCEPTION((AE_INFO, status, "%s - failed to execute"
" _DCK\n", (char *)name_buffer.pointer));
kfree(buffer.pointer);
kfree(name_buffer.pointer);
}
static inline void dock(struct dock_station *ds)
{
handle_dock(ds, 1);
}
static inline void undock(struct dock_station *ds)
{
handle_dock(ds, 0);
}
static inline void begin_dock(struct dock_station *ds)
{
ds->flags |= DOCK_DOCKING;
}
static inline void complete_dock(struct dock_station *ds)
{
ds->flags &= ~(DOCK_DOCKING);
ds->last_dock_time = jiffies;
}
static inline void begin_undock(struct dock_station *ds)
{
ds->flags |= DOCK_UNDOCKING;
}
static inline void complete_undock(struct dock_station *ds)
{
ds->flags &= ~(DOCK_UNDOCKING);
}
static void dock_lock(struct dock_station *ds, int lock)
{
struct acpi_object_list arg_list;
union acpi_object arg;
acpi_status status;
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = !!lock;
status = acpi_evaluate_object(ds->handle, "_LCK", &arg_list, NULL);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
if (lock)
printk(KERN_WARNING PREFIX "Locking device failed\n");
else
printk(KERN_WARNING PREFIX "Unlocking device failed\n");
}
}
/**
* dock_in_progress - see if we are in the middle of handling a dock event
* @ds: the dock station
*
* Sometimes while docking, false dock events can be sent to the driver
* because good connections aren't made or some other reason. Ignore these
* if we are in the middle of doing something.
*/
static int dock_in_progress(struct dock_station *ds)
{
if ((ds->flags & DOCK_DOCKING) ||
time_before(jiffies, (ds->last_dock_time + HZ)))
return 1;
return 0;
}
/**
* register_dock_notifier - add yourself to the dock notifier list
* @nb: the callers notifier block
*
* If a driver wishes to be notified about dock events, they can
* use this function to put a notifier block on the dock notifier list.
* this notifier call chain will be called after a dock event, but
* before hotplugging any new devices.
*/
int register_dock_notifier(struct notifier_block *nb)
{
if (!dock_station_count)
return -ENODEV;
return atomic_notifier_chain_register(&dock_notifier_list, nb);
}
EXPORT_SYMBOL_GPL(register_dock_notifier);
/**
* unregister_dock_notifier - remove yourself from the dock notifier list
* @nb: the callers notifier block
*/
void unregister_dock_notifier(struct notifier_block *nb)
{
if (!dock_station_count)
return;
atomic_notifier_chain_unregister(&dock_notifier_list, nb);
}
EXPORT_SYMBOL_GPL(unregister_dock_notifier);
/**
* register_hotplug_dock_device - register a hotplug function
* @handle: the handle of the device
* @ops: handlers to call after docking
* @context: device specific data
*
* If a driver would like to perform a hotplug operation after a dock
* event, they can register an acpi_notifiy_handler to be called by
* the dock driver after _DCK is executed.
*/
int
register_hotplug_dock_device(acpi_handle handle, const struct acpi_dock_ops *ops,
void *context)
{
struct dock_dependent_device *dd;
struct dock_station *dock_station;
int ret = -EINVAL;
if (!dock_station_count)
return -ENODEV;
/*
* make sure this handle is for a device dependent on the dock,
* this would include the dock station itself
*/
list_for_each_entry(dock_station, &dock_stations, sibling) {
/*
* An ATA bay can be in a dock and itself can be ejected
* separately, so there are two 'dock stations' which need the
* ops
*/
dd = find_dock_dependent_device(dock_station, handle);
if (dd) {
dd->ops = ops;
dd->context = context;
dock_add_hotplug_device(dock_station, dd);
ret = 0;
}
}
return ret;
}
EXPORT_SYMBOL_GPL(register_hotplug_dock_device);
/**
* unregister_hotplug_dock_device - remove yourself from the hotplug list
* @handle: the acpi handle of the device
*/
void unregister_hotplug_dock_device(acpi_handle handle)
{
struct dock_dependent_device *dd;
struct dock_station *dock_station;
if (!dock_station_count)
return;
list_for_each_entry(dock_station, &dock_stations, sibling) {
dd = find_dock_dependent_device(dock_station, handle);
if (dd)
dock_del_hotplug_device(dock_station, dd);
}
}
EXPORT_SYMBOL_GPL(unregister_hotplug_dock_device);
/**
* handle_eject_request - handle an undock request checking for error conditions
*
* Check to make sure the dock device is still present, then undock and
* hotremove all the devices that may need removing.
*/
static int handle_eject_request(struct dock_station *ds, u32 event)
{
if (dock_in_progress(ds))
return -EBUSY;
/*
* here we need to generate the undock
* event prior to actually doing the undock
* so that the device struct still exists.
* Also, even send the dock event if the
* device is not present anymore
*/
dock_event(ds, event, UNDOCK_EVENT);
hotplug_dock_devices(ds, ACPI_NOTIFY_EJECT_REQUEST);
undock(ds);
dock_lock(ds, 0);
eject_dock(ds);
if (dock_present(ds)) {
printk(KERN_ERR PREFIX "Unable to undock!\n");
return -EBUSY;
}
complete_undock(ds);
return 0;
}
/**
* dock_notify - act upon an acpi dock notification
* @handle: the dock station handle
* @event: the acpi event
* @data: our driver data struct
*
* If we are notified to dock, then check to see if the dock is
* present and then dock. Notify all drivers of the dock event,
* and then hotplug and devices that may need hotplugging.
*/
static void dock_notify(acpi_handle handle, u32 event, void *data)
{
struct dock_station *ds = data;
struct acpi_device *tmp;
int surprise_removal = 0;
/*
* According to acpi spec 3.0a, if a DEVICE_CHECK notification
* is sent and _DCK is present, it is assumed to mean an undock
* request.
*/
if ((ds->flags & DOCK_IS_DOCK) && event == ACPI_NOTIFY_DEVICE_CHECK)
event = ACPI_NOTIFY_EJECT_REQUEST;
/*
* dock station: BUS_CHECK - docked or surprise removal
* DEVICE_CHECK - undocked
* other device: BUS_CHECK/DEVICE_CHECK - added or surprise removal
*
* To simplify event handling, dock dependent device handler always
* get ACPI_NOTIFY_BUS_CHECK/ACPI_NOTIFY_DEVICE_CHECK for add and
* ACPI_NOTIFY_EJECT_REQUEST for removal
*/
switch (event) {
case ACPI_NOTIFY_BUS_CHECK:
case ACPI_NOTIFY_DEVICE_CHECK:
if (!dock_in_progress(ds) && acpi_bus_get_device(ds->handle,
&tmp)) {
begin_dock(ds);
dock(ds);
if (!dock_present(ds)) {
printk(KERN_ERR PREFIX "Unable to dock!\n");
complete_dock(ds);
break;
}
atomic_notifier_call_chain(&dock_notifier_list,
event, NULL);
hotplug_dock_devices(ds, event);
complete_dock(ds);
dock_event(ds, event, DOCK_EVENT);
dock_lock(ds, 1);
acpi_update_all_gpes();
break;
}
if (dock_present(ds) || dock_in_progress(ds))
break;
/* This is a surprise removal */
surprise_removal = 1;
event = ACPI_NOTIFY_EJECT_REQUEST;
/* Fall back */
case ACPI_NOTIFY_EJECT_REQUEST:
begin_undock(ds);
if ((immediate_undock && !(ds->flags & DOCK_IS_ATA))
|| surprise_removal)
handle_eject_request(ds, event);
else
dock_event(ds, event, UNDOCK_EVENT);
break;
default:
printk(KERN_ERR PREFIX "Unknown dock event %d\n", event);
}
}
struct dock_data {
acpi_handle handle;
unsigned long event;
struct dock_station *ds;
};
static void acpi_dock_deferred_cb(void *context)
{
struct dock_data *data = context;
dock_notify(data->handle, data->event, data->ds);
kfree(data);
}
static int acpi_dock_notifier_call(struct notifier_block *this,
unsigned long event, void *data)
{
struct dock_station *dock_station;
acpi_handle handle = data;
if (event != ACPI_NOTIFY_BUS_CHECK && event != ACPI_NOTIFY_DEVICE_CHECK
&& event != ACPI_NOTIFY_EJECT_REQUEST)
return 0;
list_for_each_entry(dock_station, &dock_stations, sibling) {
if (dock_station->handle == handle) {
struct dock_data *dd;
dd = kmalloc(sizeof(*dd), GFP_KERNEL);
if (!dd)
return 0;
dd->handle = handle;
dd->event = event;
dd->ds = dock_station;
acpi_os_hotplug_execute(acpi_dock_deferred_cb, dd);
return 0 ;
}
}
return 0;
}
static struct notifier_block dock_acpi_notifier = {
.notifier_call = acpi_dock_notifier_call,
};
/**
* find_dock_devices - find devices on the dock station
* @handle: the handle of the device we are examining
* @lvl: unused
* @context: the dock station private data
* @rv: unused
*
* This function is called by acpi_walk_namespace. It will
* check to see if an object has an _EJD method. If it does, then it
* will see if it is dependent on the dock station.
*/
static acpi_status
find_dock_devices(acpi_handle handle, u32 lvl, void *context, void **rv)
{
acpi_status status;
acpi_handle tmp, parent;
struct dock_station *ds = context;
status = acpi_bus_get_ejd(handle, &tmp);
if (ACPI_FAILURE(status)) {
/* try the parent device as well */
status = acpi_get_parent(handle, &parent);
if (ACPI_FAILURE(status))
goto fdd_out;
/* see if parent is dependent on dock */
status = acpi_bus_get_ejd(parent, &tmp);
if (ACPI_FAILURE(status))
goto fdd_out;
}
if (tmp == ds->handle)
add_dock_dependent_device(ds, handle);
fdd_out:
return AE_OK;
}
/*
* show_docked - read method for "docked" file in sysfs
*/
static ssize_t show_docked(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct acpi_device *tmp;
struct dock_station *dock_station = dev->platform_data;
if (ACPI_SUCCESS(acpi_bus_get_device(dock_station->handle, &tmp)))
return snprintf(buf, PAGE_SIZE, "1\n");
return snprintf(buf, PAGE_SIZE, "0\n");
}
static DEVICE_ATTR(docked, S_IRUGO, show_docked, NULL);
/*
* show_flags - read method for flags file in sysfs
*/
static ssize_t show_flags(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct dock_station *dock_station = dev->platform_data;
return snprintf(buf, PAGE_SIZE, "%d\n", dock_station->flags);
}
static DEVICE_ATTR(flags, S_IRUGO, show_flags, NULL);
/*
* write_undock - write method for "undock" file in sysfs
*/
static ssize_t write_undock(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int ret;
struct dock_station *dock_station = dev->platform_data;
if (!count)
return -EINVAL;
begin_undock(dock_station);
ret = handle_eject_request(dock_station, ACPI_NOTIFY_EJECT_REQUEST);
return ret ? ret: count;
}
static DEVICE_ATTR(undock, S_IWUSR, NULL, write_undock);
/*
* show_dock_uid - read method for "uid" file in sysfs
*/
static ssize_t show_dock_uid(struct device *dev,
struct device_attribute *attr, char *buf)
{
unsigned long long lbuf;
struct dock_station *dock_station = dev->platform_data;
acpi_status status = acpi_evaluate_integer(dock_station->handle,
"_UID", NULL, &lbuf);
if (ACPI_FAILURE(status))
return 0;
return snprintf(buf, PAGE_SIZE, "%llx\n", lbuf);
}
static DEVICE_ATTR(uid, S_IRUGO, show_dock_uid, NULL);
static ssize_t show_dock_type(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct dock_station *dock_station = dev->platform_data;
char *type;
if (dock_station->flags & DOCK_IS_DOCK)
type = "dock_station";
else if (dock_station->flags & DOCK_IS_ATA)
type = "ata_bay";
else if (dock_station->flags & DOCK_IS_BAT)
type = "battery_bay";
else
type = "unknown";
return snprintf(buf, PAGE_SIZE, "%s\n", type);
}
static DEVICE_ATTR(type, S_IRUGO, show_dock_type, NULL);
static struct attribute *dock_attributes[] = {
&dev_attr_docked.attr,
&dev_attr_flags.attr,
&dev_attr_undock.attr,
&dev_attr_uid.attr,
&dev_attr_type.attr,
NULL
};
static struct attribute_group dock_attribute_group = {
.attrs = dock_attributes
};
/**
* dock_add - add a new dock station
* @handle: the dock station handle
*
* allocated and initialize a new dock station device. Find all devices
* that are on the dock station, and register for dock event notifications.
*/
static int __init dock_add(acpi_handle handle)
{
int ret, id;
struct dock_station ds, *dock_station;
struct platform_device *dd;
id = dock_station_count;
memset(&ds, 0, sizeof(ds));
dd = platform_device_register_data(NULL, "dock", id, &ds, sizeof(ds));
if (IS_ERR(dd))
return PTR_ERR(dd);
dock_station = dd->dev.platform_data;
dock_station->handle = handle;
dock_station->dock_device = dd;
dock_station->last_dock_time = jiffies - HZ;
mutex_init(&dock_station->hp_lock);
spin_lock_init(&dock_station->dd_lock);
INIT_LIST_HEAD(&dock_station->sibling);
INIT_LIST_HEAD(&dock_station->hotplug_devices);
ATOMIC_INIT_NOTIFIER_HEAD(&dock_notifier_list);
INIT_LIST_HEAD(&dock_station->dependent_devices);
/* we want the dock device to send uevents */
dev_set_uevent_suppress(&dd->dev, 0);
if (is_dock(handle))
dock_station->flags |= DOCK_IS_DOCK;
if (is_ata(handle))
dock_station->flags |= DOCK_IS_ATA;
if (is_battery(handle))
dock_station->flags |= DOCK_IS_BAT;
ret = sysfs_create_group(&dd->dev.kobj, &dock_attribute_group);
if (ret)
goto err_unregister;
/* Find dependent devices */
acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, find_dock_devices, NULL,
dock_station, NULL);
/* add the dock station as a device dependent on itself */
ret = add_dock_dependent_device(dock_station, handle);
if (ret)
goto err_rmgroup;
dock_station_count++;
list_add(&dock_station->sibling, &dock_stations);
return 0;
err_rmgroup:
sysfs_remove_group(&dd->dev.kobj, &dock_attribute_group);
err_unregister:
platform_device_unregister(dd);
printk(KERN_ERR "%s encountered error %d\n", __func__, ret);
return ret;
}
/**
* dock_remove - free up resources related to the dock station
*/
static int dock_remove(struct dock_station *ds)
{
struct dock_dependent_device *dd, *tmp;
struct platform_device *dock_device = ds->dock_device;
if (!dock_station_count)
return 0;
/* remove dependent devices */
list_for_each_entry_safe(dd, tmp, &ds->dependent_devices, list)
kfree(dd);
list_del(&ds->sibling);
/* cleanup sysfs */
sysfs_remove_group(&dock_device->dev.kobj, &dock_attribute_group);
platform_device_unregister(dock_device);
return 0;
}
/**
* find_dock - look for a dock station
* @handle: acpi handle of a device
* @lvl: unused
* @context: counter of dock stations found
* @rv: unused
*
* This is called by acpi_walk_namespace to look for dock stations.
*/
static __init acpi_status
find_dock(acpi_handle handle, u32 lvl, void *context, void **rv)
{
if (is_dock(handle))
dock_add(handle);
return AE_OK;
}
static __init acpi_status
find_bay(acpi_handle handle, u32 lvl, void *context, void **rv)
{
/* If bay is a dock, it's already handled */
if (is_ejectable_bay(handle) && !is_dock(handle))
dock_add(handle);
return AE_OK;
}
static int __init dock_init(void)
{
if (acpi_disabled)
return 0;
/* look for a dock station */
acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, find_dock, NULL, NULL, NULL);
/* look for bay */
acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, find_bay, NULL, NULL, NULL);
if (!dock_station_count) {
printk(KERN_INFO PREFIX "No dock devices found.\n");
return 0;
}
register_acpi_bus_notifier(&dock_acpi_notifier);
printk(KERN_INFO PREFIX "%s: %d docks/bays found\n",
ACPI_DOCK_DRIVER_DESCRIPTION, dock_station_count);
return 0;
}
static void __exit dock_exit(void)
{
struct dock_station *tmp, *dock_station;
unregister_acpi_bus_notifier(&dock_acpi_notifier);
list_for_each_entry_safe(dock_station, tmp, &dock_stations, sibling)
dock_remove(dock_station);
}
/*
* Must be called before drivers of devices in dock, otherwise we can't know
* which devices are in a dock
*/
subsys_initcall(dock_init);
module_exit(dock_exit);
| gpl-2.0 |
jthatch12/STi2_M7 | sound/soc/sh/ssi.c | 5071 | 10322 | /*
* Serial Sound Interface (I2S) support for SH7760/SH7780
*
* Copyright (c) 2007 Manuel Lauss <mano@roarinelk.homelinux.net>
*
* licensed under the terms outlined in the file COPYING at the root
* of the linux kernel sources.
*
* dont forget to set IPSEL/OMSEL register bits (in your board code) to
* enable SSI output pins!
*/
/*
* LIMITATIONS:
* The SSI unit has only one physical data line, so full duplex is
* impossible. This can be remedied on the SH7760 by using the
* other SSI unit for recording; however the SH7780 has only 1 SSI
* unit, and its pins are shared with the AC97 unit, among others.
*
* FEATURES:
* The SSI features "compressed mode": in this mode it continuously
* streams PCM data over the I2S lines and uses LRCK as a handshake
* signal. Can be used to send compressed data (AC3/DTS) to a DSP.
* The number of bits sent over the wire in a frame can be adjusted
* and can be independent from the actual sample bit depth. This is
* useful to support TDM mode codecs like the AD1939 which have a
* fixed TDM slot size, regardless of sample resolution.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <asm/io.h>
#define SSICR 0x00
#define SSISR 0x04
#define CR_DMAEN (1 << 28)
#define CR_CHNL_SHIFT 22
#define CR_CHNL_MASK (3 << CR_CHNL_SHIFT)
#define CR_DWL_SHIFT 19
#define CR_DWL_MASK (7 << CR_DWL_SHIFT)
#define CR_SWL_SHIFT 16
#define CR_SWL_MASK (7 << CR_SWL_SHIFT)
#define CR_SCK_MASTER (1 << 15) /* bitclock master bit */
#define CR_SWS_MASTER (1 << 14) /* wordselect master bit */
#define CR_SCKP (1 << 13) /* I2Sclock polarity */
#define CR_SWSP (1 << 12) /* LRCK polarity */
#define CR_SPDP (1 << 11)
#define CR_SDTA (1 << 10) /* i2s alignment (msb/lsb) */
#define CR_PDTA (1 << 9) /* fifo data alignment */
#define CR_DEL (1 << 8) /* delay data by 1 i2sclk */
#define CR_BREN (1 << 7) /* clock gating in burst mode */
#define CR_CKDIV_SHIFT 4
#define CR_CKDIV_MASK (7 << CR_CKDIV_SHIFT) /* bitclock divider */
#define CR_MUTE (1 << 3) /* SSI mute */
#define CR_CPEN (1 << 2) /* compressed mode */
#define CR_TRMD (1 << 1) /* transmit/receive select */
#define CR_EN (1 << 0) /* enable SSI */
#define SSIREG(reg) (*(unsigned long *)(ssi->mmio + (reg)))
struct ssi_priv {
unsigned long mmio;
unsigned long sysclk;
int inuse;
} ssi_cpu_data[] = {
#if defined(CONFIG_CPU_SUBTYPE_SH7760)
{
.mmio = 0xFE680000,
},
{
.mmio = 0xFE690000,
},
#elif defined(CONFIG_CPU_SUBTYPE_SH7780)
{
.mmio = 0xFFE70000,
},
#else
#error "Unsupported SuperH SoC"
#endif
};
/*
* track usage of the SSI; it is simplex-only so prevent attempts of
* concurrent playback + capture. FIXME: any locking required?
*/
static int ssi_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct ssi_priv *ssi = &ssi_cpu_data[dai->id];
if (ssi->inuse) {
pr_debug("ssi: already in use!\n");
return -EBUSY;
} else
ssi->inuse = 1;
return 0;
}
static void ssi_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct ssi_priv *ssi = &ssi_cpu_data[dai->id];
ssi->inuse = 0;
}
static int ssi_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct ssi_priv *ssi = &ssi_cpu_data[dai->id];
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
SSIREG(SSICR) |= CR_DMAEN | CR_EN;
break;
case SNDRV_PCM_TRIGGER_STOP:
SSIREG(SSICR) &= ~(CR_DMAEN | CR_EN);
break;
default:
return -EINVAL;
}
return 0;
}
static int ssi_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct ssi_priv *ssi = &ssi_cpu_data[dai->id];
unsigned long ssicr = SSIREG(SSICR);
unsigned int bits, channels, swl, recv, i;
channels = params_channels(params);
bits = params->msbits;
recv = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ? 0 : 1;
pr_debug("ssi_hw_params() enter\nssicr was %08lx\n", ssicr);
pr_debug("bits: %u channels: %u\n", bits, channels);
ssicr &= ~(CR_TRMD | CR_CHNL_MASK | CR_DWL_MASK | CR_PDTA |
CR_SWL_MASK);
/* direction (send/receive) */
if (!recv)
ssicr |= CR_TRMD; /* transmit */
/* channels */
if ((channels < 2) || (channels > 8) || (channels & 1)) {
pr_debug("ssi: invalid number of channels\n");
return -EINVAL;
}
ssicr |= ((channels >> 1) - 1) << CR_CHNL_SHIFT;
/* DATA WORD LENGTH (DWL): databits in audio sample */
i = 0;
switch (bits) {
case 32: ++i;
case 24: ++i;
case 22: ++i;
case 20: ++i;
case 18: ++i;
case 16: ++i;
ssicr |= i << CR_DWL_SHIFT;
case 8: break;
default:
pr_debug("ssi: invalid sample width\n");
return -EINVAL;
}
/*
* SYSTEM WORD LENGTH: size in bits of half a frame over the I2S
* wires. This is usually bits_per_sample x channels/2; i.e. in
* Stereo mode the SWL equals DWL. SWL can be bigger than the
* product of (channels_per_slot x samplebits), e.g. for codecs
* like the AD1939 which only accept 32bit wide TDM slots. For
* "standard" I2S operation we set SWL = chans / 2 * DWL here.
* Waiting for ASoC to get TDM support ;-)
*/
if ((bits > 16) && (bits <= 24)) {
bits = 24; /* these are padded by the SSI */
/*ssicr |= CR_PDTA;*/ /* cpu/data endianness ? */
}
i = 0;
swl = (bits * channels) / 2;
switch (swl) {
case 256: ++i;
case 128: ++i;
case 64: ++i;
case 48: ++i;
case 32: ++i;
case 16: ++i;
ssicr |= i << CR_SWL_SHIFT;
case 8: break;
default:
pr_debug("ssi: invalid system word length computed\n");
return -EINVAL;
}
SSIREG(SSICR) = ssicr;
pr_debug("ssi_hw_params() leave\nssicr is now %08lx\n", ssicr);
return 0;
}
static int ssi_set_sysclk(struct snd_soc_dai *cpu_dai, int clk_id,
unsigned int freq, int dir)
{
struct ssi_priv *ssi = &ssi_cpu_data[cpu_dai->id];
ssi->sysclk = freq;
return 0;
}
/*
* This divider is used to generate the SSI_SCK (I2S bitclock) from the
* clock at the HAC_BIT_CLK ("oversampling clock") pin.
*/
static int ssi_set_clkdiv(struct snd_soc_dai *dai, int did, int div)
{
struct ssi_priv *ssi = &ssi_cpu_data[dai->id];
unsigned long ssicr;
int i;
i = 0;
ssicr = SSIREG(SSICR) & ~CR_CKDIV_MASK;
switch (div) {
case 16: ++i;
case 8: ++i;
case 4: ++i;
case 2: ++i;
SSIREG(SSICR) = ssicr | (i << CR_CKDIV_SHIFT);
case 1: break;
default:
pr_debug("ssi: invalid sck divider %d\n", div);
return -EINVAL;
}
return 0;
}
static int ssi_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct ssi_priv *ssi = &ssi_cpu_data[dai->id];
unsigned long ssicr = SSIREG(SSICR);
pr_debug("ssi_set_fmt()\nssicr was 0x%08lx\n", ssicr);
ssicr &= ~(CR_DEL | CR_PDTA | CR_BREN | CR_SWSP | CR_SCKP |
CR_SWS_MASTER | CR_SCK_MASTER);
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
break;
case SND_SOC_DAIFMT_RIGHT_J:
ssicr |= CR_DEL | CR_PDTA;
break;
case SND_SOC_DAIFMT_LEFT_J:
ssicr |= CR_DEL;
break;
default:
pr_debug("ssi: unsupported format\n");
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_CLOCK_MASK) {
case SND_SOC_DAIFMT_CONT:
break;
case SND_SOC_DAIFMT_GATED:
ssicr |= CR_BREN;
break;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
ssicr |= CR_SCKP; /* sample data at low clkedge */
break;
case SND_SOC_DAIFMT_NB_IF:
ssicr |= CR_SCKP | CR_SWSP;
break;
case SND_SOC_DAIFMT_IB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
ssicr |= CR_SWSP; /* word select starts low */
break;
default:
pr_debug("ssi: invalid inversion\n");
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
break;
case SND_SOC_DAIFMT_CBS_CFM:
ssicr |= CR_SCK_MASTER;
break;
case SND_SOC_DAIFMT_CBM_CFS:
ssicr |= CR_SWS_MASTER;
break;
case SND_SOC_DAIFMT_CBS_CFS:
ssicr |= CR_SWS_MASTER | CR_SCK_MASTER;
break;
default:
pr_debug("ssi: invalid master/slave configuration\n");
return -EINVAL;
}
SSIREG(SSICR) = ssicr;
pr_debug("ssi_set_fmt() leave\nssicr is now 0x%08lx\n", ssicr);
return 0;
}
/* the SSI depends on an external clocksource (at HAC_BIT_CLK) even in
* Master mode, so really this is board specific; the SSI can do any
* rate with the right bitclk and divider settings.
*/
#define SSI_RATES \
SNDRV_PCM_RATE_8000_192000
/* the SSI can do 8-32 bit samples, with 8 possible channels */
#define SSI_FMTS \
(SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_U8 | \
SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U16_LE | \
SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_U20_3LE | \
SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_U24_3LE | \
SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_U32_LE)
static const struct snd_soc_dai_ops ssi_dai_ops = {
.startup = ssi_startup,
.shutdown = ssi_shutdown,
.trigger = ssi_trigger,
.hw_params = ssi_hw_params,
.set_sysclk = ssi_set_sysclk,
.set_clkdiv = ssi_set_clkdiv,
.set_fmt = ssi_set_fmt,
};
static struct snd_soc_dai_driver sh4_ssi_dai[] = {
{
.name = "ssi-dai.0",
.playback = {
.rates = SSI_RATES,
.formats = SSI_FMTS,
.channels_min = 2,
.channels_max = 8,
},
.capture = {
.rates = SSI_RATES,
.formats = SSI_FMTS,
.channels_min = 2,
.channels_max = 8,
},
.ops = &ssi_dai_ops,
},
#ifdef CONFIG_CPU_SUBTYPE_SH7760
{
.name = "ssi-dai.1",
.playback = {
.rates = SSI_RATES,
.formats = SSI_FMTS,
.channels_min = 2,
.channels_max = 8,
},
.capture = {
.rates = SSI_RATES,
.formats = SSI_FMTS,
.channels_min = 2,
.channels_max = 8,
},
.ops = &ssi_dai_ops,
},
#endif
};
static int __devinit sh4_soc_dai_probe(struct platform_device *pdev)
{
return snd_soc_register_dais(&pdev->dev, sh4_ssi_dai,
ARRAY_SIZE(sh4_ssi_dai));
}
static int __devexit sh4_soc_dai_remove(struct platform_device *pdev)
{
snd_soc_unregister_dais(&pdev->dev, ARRAY_SIZE(sh4_ssi_dai));
return 0;
}
static struct platform_driver sh4_ssi_driver = {
.driver = {
.name = "sh4-ssi-dai",
.owner = THIS_MODULE,
},
.probe = sh4_soc_dai_probe,
.remove = __devexit_p(sh4_soc_dai_remove),
};
module_platform_driver(sh4_ssi_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SuperH onchip SSI (I2S) audio driver");
MODULE_AUTHOR("Manuel Lauss <mano@roarinelk.homelinux.net>");
| gpl-2.0 |
Cpasjuste/kernel_amazon_hdx-common | arch/arm/mach-dove/addr-map.c | 5071 | 2966 | /*
* arch/arm/mach-dove/addr-map.c
*
* Address map functions for Marvell Dove 88AP510 SoC
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/mbus.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/setup.h>
#include <mach/dove.h>
#include <plat/addr-map.h>
#include "common.h"
/*
* Generic Address Decode Windows bit settings
*/
#define TARGET_DDR 0x0
#define TARGET_BOOTROM 0x1
#define TARGET_CESA 0x3
#define TARGET_PCIE0 0x4
#define TARGET_PCIE1 0x8
#define TARGET_SCRATCHPAD 0xd
#define ATTR_CESA 0x01
#define ATTR_BOOTROM 0xfd
#define ATTR_DEV_SPI0_ROM 0xfe
#define ATTR_DEV_SPI1_ROM 0xfb
#define ATTR_PCIE_IO 0xe0
#define ATTR_PCIE_MEM 0xe8
#define ATTR_SCRATCHPAD 0x0
static inline void __iomem *ddr_map_sc(int i)
{
return (void __iomem *)(DOVE_MC_VIRT_BASE + 0x100 + ((i) << 4));
}
/*
* Description of the windows needed by the platform code
*/
static struct __initdata orion_addr_map_cfg addr_map_cfg = {
.num_wins = 8,
.remappable_wins = 4,
.bridge_virt_base = BRIDGE_VIRT_BASE,
};
static const struct __initdata orion_addr_map_info addr_map_info[] = {
/*
* Windows for PCIe IO+MEM space.
*/
{ 0, DOVE_PCIE0_IO_PHYS_BASE, DOVE_PCIE0_IO_SIZE,
TARGET_PCIE0, ATTR_PCIE_IO, DOVE_PCIE0_IO_BUS_BASE
},
{ 1, DOVE_PCIE1_IO_PHYS_BASE, DOVE_PCIE1_IO_SIZE,
TARGET_PCIE1, ATTR_PCIE_IO, DOVE_PCIE1_IO_BUS_BASE
},
{ 2, DOVE_PCIE0_MEM_PHYS_BASE, DOVE_PCIE0_MEM_SIZE,
TARGET_PCIE0, ATTR_PCIE_MEM, -1
},
{ 3, DOVE_PCIE1_MEM_PHYS_BASE, DOVE_PCIE1_MEM_SIZE,
TARGET_PCIE1, ATTR_PCIE_MEM, -1
},
/*
* Window for CESA engine.
*/
{ 4, DOVE_CESA_PHYS_BASE, DOVE_CESA_SIZE,
TARGET_CESA, ATTR_CESA, -1
},
/*
* Window to the BootROM for Standby and Sleep Resume
*/
{ 5, DOVE_BOOTROM_PHYS_BASE, DOVE_BOOTROM_SIZE,
TARGET_BOOTROM, ATTR_BOOTROM, -1
},
/*
* Window to the PMU Scratch Pad space
*/
{ 6, DOVE_SCRATCHPAD_PHYS_BASE, DOVE_SCRATCHPAD_SIZE,
TARGET_SCRATCHPAD, ATTR_SCRATCHPAD, -1
},
/* End marker */
{ -1, 0, 0, 0, 0, 0 }
};
void __init dove_setup_cpu_mbus(void)
{
int i;
int cs;
/*
* Disable, clear and configure windows.
*/
orion_config_wins(&addr_map_cfg, addr_map_info);
/*
* Setup MBUS dram target info.
*/
orion_mbus_dram_info.mbus_dram_target_id = TARGET_DDR;
for (i = 0, cs = 0; i < 2; i++) {
u32 map = readl(ddr_map_sc(i));
/*
* Chip select enabled?
*/
if (map & 1) {
struct mbus_dram_window *w;
w = &orion_mbus_dram_info.cs[cs++];
w->cs_index = i;
w->mbus_attr = 0; /* CS address decoding done inside */
/* the DDR controller, no need to */
/* provide attributes */
w->base = map & 0xff800000;
w->size = 0x100000 << (((map & 0x000f0000) >> 16) - 4);
}
}
orion_mbus_dram_info.num_cs = cs;
}
| gpl-2.0 |
RealVNC/Android-kernel-mako-NCM | drivers/s390/scsi/zfcp_erp.c | 6351 | 43771 | /*
* zfcp device driver
*
* Error Recovery Procedures (ERP).
*
* Copyright IBM Corporation 2002, 2010
*/
#define KMSG_COMPONENT "zfcp"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/kthread.h>
#include "zfcp_ext.h"
#include "zfcp_reqlist.h"
#define ZFCP_MAX_ERPS 3
enum zfcp_erp_act_flags {
ZFCP_STATUS_ERP_TIMEDOUT = 0x10000000,
ZFCP_STATUS_ERP_CLOSE_ONLY = 0x01000000,
ZFCP_STATUS_ERP_DISMISSING = 0x00100000,
ZFCP_STATUS_ERP_DISMISSED = 0x00200000,
ZFCP_STATUS_ERP_LOWMEM = 0x00400000,
ZFCP_STATUS_ERP_NO_REF = 0x00800000,
};
enum zfcp_erp_steps {
ZFCP_ERP_STEP_UNINITIALIZED = 0x0000,
ZFCP_ERP_STEP_FSF_XCONFIG = 0x0001,
ZFCP_ERP_STEP_PHYS_PORT_CLOSING = 0x0010,
ZFCP_ERP_STEP_PORT_CLOSING = 0x0100,
ZFCP_ERP_STEP_PORT_OPENING = 0x0800,
ZFCP_ERP_STEP_LUN_CLOSING = 0x1000,
ZFCP_ERP_STEP_LUN_OPENING = 0x2000,
};
enum zfcp_erp_act_type {
ZFCP_ERP_ACTION_REOPEN_LUN = 1,
ZFCP_ERP_ACTION_REOPEN_PORT = 2,
ZFCP_ERP_ACTION_REOPEN_PORT_FORCED = 3,
ZFCP_ERP_ACTION_REOPEN_ADAPTER = 4,
};
enum zfcp_erp_act_state {
ZFCP_ERP_ACTION_RUNNING = 1,
ZFCP_ERP_ACTION_READY = 2,
};
enum zfcp_erp_act_result {
ZFCP_ERP_SUCCEEDED = 0,
ZFCP_ERP_FAILED = 1,
ZFCP_ERP_CONTINUES = 2,
ZFCP_ERP_EXIT = 3,
ZFCP_ERP_DISMISSED = 4,
ZFCP_ERP_NOMEM = 5,
};
static void zfcp_erp_adapter_block(struct zfcp_adapter *adapter, int mask)
{
zfcp_erp_clear_adapter_status(adapter,
ZFCP_STATUS_COMMON_UNBLOCKED | mask);
}
static int zfcp_erp_action_exists(struct zfcp_erp_action *act)
{
struct zfcp_erp_action *curr_act;
list_for_each_entry(curr_act, &act->adapter->erp_running_head, list)
if (act == curr_act)
return ZFCP_ERP_ACTION_RUNNING;
return 0;
}
static void zfcp_erp_action_ready(struct zfcp_erp_action *act)
{
struct zfcp_adapter *adapter = act->adapter;
list_move(&act->list, &act->adapter->erp_ready_head);
zfcp_dbf_rec_run("erardy1", act);
wake_up(&adapter->erp_ready_wq);
zfcp_dbf_rec_run("erardy2", act);
}
static void zfcp_erp_action_dismiss(struct zfcp_erp_action *act)
{
act->status |= ZFCP_STATUS_ERP_DISMISSED;
if (zfcp_erp_action_exists(act) == ZFCP_ERP_ACTION_RUNNING)
zfcp_erp_action_ready(act);
}
static void zfcp_erp_action_dismiss_lun(struct scsi_device *sdev)
{
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
if (atomic_read(&zfcp_sdev->status) & ZFCP_STATUS_COMMON_ERP_INUSE)
zfcp_erp_action_dismiss(&zfcp_sdev->erp_action);
}
static void zfcp_erp_action_dismiss_port(struct zfcp_port *port)
{
struct scsi_device *sdev;
if (atomic_read(&port->status) & ZFCP_STATUS_COMMON_ERP_INUSE)
zfcp_erp_action_dismiss(&port->erp_action);
else
shost_for_each_device(sdev, port->adapter->scsi_host)
if (sdev_to_zfcp(sdev)->port == port)
zfcp_erp_action_dismiss_lun(sdev);
}
static void zfcp_erp_action_dismiss_adapter(struct zfcp_adapter *adapter)
{
struct zfcp_port *port;
if (atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_ERP_INUSE)
zfcp_erp_action_dismiss(&adapter->erp_action);
else {
read_lock(&adapter->port_list_lock);
list_for_each_entry(port, &adapter->port_list, list)
zfcp_erp_action_dismiss_port(port);
read_unlock(&adapter->port_list_lock);
}
}
static int zfcp_erp_required_act(int want, struct zfcp_adapter *adapter,
struct zfcp_port *port,
struct scsi_device *sdev)
{
int need = want;
int l_status, p_status, a_status;
struct zfcp_scsi_dev *zfcp_sdev;
switch (want) {
case ZFCP_ERP_ACTION_REOPEN_LUN:
zfcp_sdev = sdev_to_zfcp(sdev);
l_status = atomic_read(&zfcp_sdev->status);
if (l_status & ZFCP_STATUS_COMMON_ERP_INUSE)
return 0;
p_status = atomic_read(&port->status);
if (!(p_status & ZFCP_STATUS_COMMON_RUNNING) ||
p_status & ZFCP_STATUS_COMMON_ERP_FAILED)
return 0;
if (!(p_status & ZFCP_STATUS_COMMON_UNBLOCKED))
need = ZFCP_ERP_ACTION_REOPEN_PORT;
/* fall through */
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
p_status = atomic_read(&port->status);
if (!(p_status & ZFCP_STATUS_COMMON_OPEN))
need = ZFCP_ERP_ACTION_REOPEN_PORT;
/* fall through */
case ZFCP_ERP_ACTION_REOPEN_PORT:
p_status = atomic_read(&port->status);
if (p_status & ZFCP_STATUS_COMMON_ERP_INUSE)
return 0;
a_status = atomic_read(&adapter->status);
if (!(a_status & ZFCP_STATUS_COMMON_RUNNING) ||
a_status & ZFCP_STATUS_COMMON_ERP_FAILED)
return 0;
if (p_status & ZFCP_STATUS_COMMON_NOESC)
return need;
if (!(a_status & ZFCP_STATUS_COMMON_UNBLOCKED))
need = ZFCP_ERP_ACTION_REOPEN_ADAPTER;
/* fall through */
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
a_status = atomic_read(&adapter->status);
if (a_status & ZFCP_STATUS_COMMON_ERP_INUSE)
return 0;
if (!(a_status & ZFCP_STATUS_COMMON_RUNNING) &&
!(a_status & ZFCP_STATUS_COMMON_OPEN))
return 0; /* shutdown requested for closed adapter */
}
return need;
}
static struct zfcp_erp_action *zfcp_erp_setup_act(int need, u32 act_status,
struct zfcp_adapter *adapter,
struct zfcp_port *port,
struct scsi_device *sdev)
{
struct zfcp_erp_action *erp_action;
struct zfcp_scsi_dev *zfcp_sdev;
switch (need) {
case ZFCP_ERP_ACTION_REOPEN_LUN:
zfcp_sdev = sdev_to_zfcp(sdev);
if (!(act_status & ZFCP_STATUS_ERP_NO_REF))
if (scsi_device_get(sdev))
return NULL;
atomic_set_mask(ZFCP_STATUS_COMMON_ERP_INUSE,
&zfcp_sdev->status);
erp_action = &zfcp_sdev->erp_action;
memset(erp_action, 0, sizeof(struct zfcp_erp_action));
erp_action->port = port;
erp_action->sdev = sdev;
if (!(atomic_read(&zfcp_sdev->status) &
ZFCP_STATUS_COMMON_RUNNING))
act_status |= ZFCP_STATUS_ERP_CLOSE_ONLY;
break;
case ZFCP_ERP_ACTION_REOPEN_PORT:
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
if (!get_device(&port->dev))
return NULL;
zfcp_erp_action_dismiss_port(port);
atomic_set_mask(ZFCP_STATUS_COMMON_ERP_INUSE, &port->status);
erp_action = &port->erp_action;
memset(erp_action, 0, sizeof(struct zfcp_erp_action));
erp_action->port = port;
if (!(atomic_read(&port->status) & ZFCP_STATUS_COMMON_RUNNING))
act_status |= ZFCP_STATUS_ERP_CLOSE_ONLY;
break;
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
kref_get(&adapter->ref);
zfcp_erp_action_dismiss_adapter(adapter);
atomic_set_mask(ZFCP_STATUS_COMMON_ERP_INUSE, &adapter->status);
erp_action = &adapter->erp_action;
memset(erp_action, 0, sizeof(struct zfcp_erp_action));
if (!(atomic_read(&adapter->status) &
ZFCP_STATUS_COMMON_RUNNING))
act_status |= ZFCP_STATUS_ERP_CLOSE_ONLY;
break;
default:
return NULL;
}
erp_action->adapter = adapter;
erp_action->action = need;
erp_action->status = act_status;
return erp_action;
}
static int zfcp_erp_action_enqueue(int want, struct zfcp_adapter *adapter,
struct zfcp_port *port,
struct scsi_device *sdev,
char *id, u32 act_status)
{
int retval = 1, need;
struct zfcp_erp_action *act;
if (!adapter->erp_thread)
return -EIO;
need = zfcp_erp_required_act(want, adapter, port, sdev);
if (!need)
goto out;
act = zfcp_erp_setup_act(need, act_status, adapter, port, sdev);
if (!act)
goto out;
atomic_set_mask(ZFCP_STATUS_ADAPTER_ERP_PENDING, &adapter->status);
++adapter->erp_total_count;
list_add_tail(&act->list, &adapter->erp_ready_head);
wake_up(&adapter->erp_ready_wq);
retval = 0;
out:
zfcp_dbf_rec_trig(id, adapter, port, sdev, want, need);
return retval;
}
static int _zfcp_erp_adapter_reopen(struct zfcp_adapter *adapter,
int clear_mask, char *id)
{
zfcp_erp_adapter_block(adapter, clear_mask);
zfcp_scsi_schedule_rports_block(adapter);
/* ensure propagation of failed status to new devices */
if (atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_ERP_FAILED) {
zfcp_erp_set_adapter_status(adapter,
ZFCP_STATUS_COMMON_ERP_FAILED);
return -EIO;
}
return zfcp_erp_action_enqueue(ZFCP_ERP_ACTION_REOPEN_ADAPTER,
adapter, NULL, NULL, id, 0);
}
/**
* zfcp_erp_adapter_reopen - Reopen adapter.
* @adapter: Adapter to reopen.
* @clear: Status flags to clear.
* @id: Id for debug trace event.
*/
void zfcp_erp_adapter_reopen(struct zfcp_adapter *adapter, int clear, char *id)
{
unsigned long flags;
zfcp_erp_adapter_block(adapter, clear);
zfcp_scsi_schedule_rports_block(adapter);
write_lock_irqsave(&adapter->erp_lock, flags);
if (atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_ERP_FAILED)
zfcp_erp_set_adapter_status(adapter,
ZFCP_STATUS_COMMON_ERP_FAILED);
else
zfcp_erp_action_enqueue(ZFCP_ERP_ACTION_REOPEN_ADAPTER, adapter,
NULL, NULL, id, 0);
write_unlock_irqrestore(&adapter->erp_lock, flags);
}
/**
* zfcp_erp_adapter_shutdown - Shutdown adapter.
* @adapter: Adapter to shut down.
* @clear: Status flags to clear.
* @id: Id for debug trace event.
*/
void zfcp_erp_adapter_shutdown(struct zfcp_adapter *adapter, int clear,
char *id)
{
int flags = ZFCP_STATUS_COMMON_RUNNING | ZFCP_STATUS_COMMON_ERP_FAILED;
zfcp_erp_adapter_reopen(adapter, clear | flags, id);
}
/**
* zfcp_erp_port_shutdown - Shutdown port
* @port: Port to shut down.
* @clear: Status flags to clear.
* @id: Id for debug trace event.
*/
void zfcp_erp_port_shutdown(struct zfcp_port *port, int clear, char *id)
{
int flags = ZFCP_STATUS_COMMON_RUNNING | ZFCP_STATUS_COMMON_ERP_FAILED;
zfcp_erp_port_reopen(port, clear | flags, id);
}
static void zfcp_erp_port_block(struct zfcp_port *port, int clear)
{
zfcp_erp_clear_port_status(port,
ZFCP_STATUS_COMMON_UNBLOCKED | clear);
}
static void _zfcp_erp_port_forced_reopen(struct zfcp_port *port, int clear,
char *id)
{
zfcp_erp_port_block(port, clear);
zfcp_scsi_schedule_rport_block(port);
if (atomic_read(&port->status) & ZFCP_STATUS_COMMON_ERP_FAILED)
return;
zfcp_erp_action_enqueue(ZFCP_ERP_ACTION_REOPEN_PORT_FORCED,
port->adapter, port, NULL, id, 0);
}
/**
* zfcp_erp_port_forced_reopen - Forced close of port and open again
* @port: Port to force close and to reopen.
* @clear: Status flags to clear.
* @id: Id for debug trace event.
*/
void zfcp_erp_port_forced_reopen(struct zfcp_port *port, int clear, char *id)
{
unsigned long flags;
struct zfcp_adapter *adapter = port->adapter;
write_lock_irqsave(&adapter->erp_lock, flags);
_zfcp_erp_port_forced_reopen(port, clear, id);
write_unlock_irqrestore(&adapter->erp_lock, flags);
}
static int _zfcp_erp_port_reopen(struct zfcp_port *port, int clear, char *id)
{
zfcp_erp_port_block(port, clear);
zfcp_scsi_schedule_rport_block(port);
if (atomic_read(&port->status) & ZFCP_STATUS_COMMON_ERP_FAILED) {
/* ensure propagation of failed status to new devices */
zfcp_erp_set_port_status(port, ZFCP_STATUS_COMMON_ERP_FAILED);
return -EIO;
}
return zfcp_erp_action_enqueue(ZFCP_ERP_ACTION_REOPEN_PORT,
port->adapter, port, NULL, id, 0);
}
/**
* zfcp_erp_port_reopen - trigger remote port recovery
* @port: port to recover
* @clear_mask: flags in port status to be cleared
* @id: Id for debug trace event.
*
* Returns 0 if recovery has been triggered, < 0 if not.
*/
int zfcp_erp_port_reopen(struct zfcp_port *port, int clear, char *id)
{
int retval;
unsigned long flags;
struct zfcp_adapter *adapter = port->adapter;
write_lock_irqsave(&adapter->erp_lock, flags);
retval = _zfcp_erp_port_reopen(port, clear, id);
write_unlock_irqrestore(&adapter->erp_lock, flags);
return retval;
}
static void zfcp_erp_lun_block(struct scsi_device *sdev, int clear_mask)
{
zfcp_erp_clear_lun_status(sdev,
ZFCP_STATUS_COMMON_UNBLOCKED | clear_mask);
}
static void _zfcp_erp_lun_reopen(struct scsi_device *sdev, int clear, char *id,
u32 act_status)
{
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
struct zfcp_adapter *adapter = zfcp_sdev->port->adapter;
zfcp_erp_lun_block(sdev, clear);
if (atomic_read(&zfcp_sdev->status) & ZFCP_STATUS_COMMON_ERP_FAILED)
return;
zfcp_erp_action_enqueue(ZFCP_ERP_ACTION_REOPEN_LUN, adapter,
zfcp_sdev->port, sdev, id, act_status);
}
/**
* zfcp_erp_lun_reopen - initiate reopen of a LUN
* @sdev: SCSI device / LUN to be reopened
* @clear_mask: specifies flags in LUN status to be cleared
* @id: Id for debug trace event.
*
* Return: 0 on success, < 0 on error
*/
void zfcp_erp_lun_reopen(struct scsi_device *sdev, int clear, char *id)
{
unsigned long flags;
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
struct zfcp_port *port = zfcp_sdev->port;
struct zfcp_adapter *adapter = port->adapter;
write_lock_irqsave(&adapter->erp_lock, flags);
_zfcp_erp_lun_reopen(sdev, clear, id, 0);
write_unlock_irqrestore(&adapter->erp_lock, flags);
}
/**
* zfcp_erp_lun_shutdown - Shutdown LUN
* @sdev: SCSI device / LUN to shut down.
* @clear: Status flags to clear.
* @id: Id for debug trace event.
*/
void zfcp_erp_lun_shutdown(struct scsi_device *sdev, int clear, char *id)
{
int flags = ZFCP_STATUS_COMMON_RUNNING | ZFCP_STATUS_COMMON_ERP_FAILED;
zfcp_erp_lun_reopen(sdev, clear | flags, id);
}
/**
* zfcp_erp_lun_shutdown_wait - Shutdown LUN and wait for erp completion
* @sdev: SCSI device / LUN to shut down.
* @id: Id for debug trace event.
*
* Do not acquire a reference for the LUN when creating the ERP
* action. It is safe, because this function waits for the ERP to
* complete first. This allows to shutdown the LUN, even when the SCSI
* device is in the state SDEV_DEL when scsi_device_get will fail.
*/
void zfcp_erp_lun_shutdown_wait(struct scsi_device *sdev, char *id)
{
unsigned long flags;
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
struct zfcp_port *port = zfcp_sdev->port;
struct zfcp_adapter *adapter = port->adapter;
int clear = ZFCP_STATUS_COMMON_RUNNING | ZFCP_STATUS_COMMON_ERP_FAILED;
write_lock_irqsave(&adapter->erp_lock, flags);
_zfcp_erp_lun_reopen(sdev, clear, id, ZFCP_STATUS_ERP_NO_REF);
write_unlock_irqrestore(&adapter->erp_lock, flags);
zfcp_erp_wait(adapter);
}
static int status_change_set(unsigned long mask, atomic_t *status)
{
return (atomic_read(status) ^ mask) & mask;
}
static void zfcp_erp_adapter_unblock(struct zfcp_adapter *adapter)
{
if (status_change_set(ZFCP_STATUS_COMMON_UNBLOCKED, &adapter->status))
zfcp_dbf_rec_run("eraubl1", &adapter->erp_action);
atomic_set_mask(ZFCP_STATUS_COMMON_UNBLOCKED, &adapter->status);
}
static void zfcp_erp_port_unblock(struct zfcp_port *port)
{
if (status_change_set(ZFCP_STATUS_COMMON_UNBLOCKED, &port->status))
zfcp_dbf_rec_run("erpubl1", &port->erp_action);
atomic_set_mask(ZFCP_STATUS_COMMON_UNBLOCKED, &port->status);
}
static void zfcp_erp_lun_unblock(struct scsi_device *sdev)
{
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
if (status_change_set(ZFCP_STATUS_COMMON_UNBLOCKED, &zfcp_sdev->status))
zfcp_dbf_rec_run("erlubl1", &sdev_to_zfcp(sdev)->erp_action);
atomic_set_mask(ZFCP_STATUS_COMMON_UNBLOCKED, &zfcp_sdev->status);
}
static void zfcp_erp_action_to_running(struct zfcp_erp_action *erp_action)
{
list_move(&erp_action->list, &erp_action->adapter->erp_running_head);
zfcp_dbf_rec_run("erator1", erp_action);
}
static void zfcp_erp_strategy_check_fsfreq(struct zfcp_erp_action *act)
{
struct zfcp_adapter *adapter = act->adapter;
struct zfcp_fsf_req *req;
if (!act->fsf_req_id)
return;
spin_lock(&adapter->req_list->lock);
req = _zfcp_reqlist_find(adapter->req_list, act->fsf_req_id);
if (req && req->erp_action == act) {
if (act->status & (ZFCP_STATUS_ERP_DISMISSED |
ZFCP_STATUS_ERP_TIMEDOUT)) {
req->status |= ZFCP_STATUS_FSFREQ_DISMISSED;
zfcp_dbf_rec_run("erscf_1", act);
req->erp_action = NULL;
}
if (act->status & ZFCP_STATUS_ERP_TIMEDOUT)
zfcp_dbf_rec_run("erscf_2", act);
if (req->status & ZFCP_STATUS_FSFREQ_DISMISSED)
act->fsf_req_id = 0;
} else
act->fsf_req_id = 0;
spin_unlock(&adapter->req_list->lock);
}
/**
* zfcp_erp_notify - Trigger ERP action.
* @erp_action: ERP action to continue.
* @set_mask: ERP action status flags to set.
*/
void zfcp_erp_notify(struct zfcp_erp_action *erp_action, unsigned long set_mask)
{
struct zfcp_adapter *adapter = erp_action->adapter;
unsigned long flags;
write_lock_irqsave(&adapter->erp_lock, flags);
if (zfcp_erp_action_exists(erp_action) == ZFCP_ERP_ACTION_RUNNING) {
erp_action->status |= set_mask;
zfcp_erp_action_ready(erp_action);
}
write_unlock_irqrestore(&adapter->erp_lock, flags);
}
/**
* zfcp_erp_timeout_handler - Trigger ERP action from timed out ERP request
* @data: ERP action (from timer data)
*/
void zfcp_erp_timeout_handler(unsigned long data)
{
struct zfcp_erp_action *act = (struct zfcp_erp_action *) data;
zfcp_erp_notify(act, ZFCP_STATUS_ERP_TIMEDOUT);
}
static void zfcp_erp_memwait_handler(unsigned long data)
{
zfcp_erp_notify((struct zfcp_erp_action *)data, 0);
}
static void zfcp_erp_strategy_memwait(struct zfcp_erp_action *erp_action)
{
init_timer(&erp_action->timer);
erp_action->timer.function = zfcp_erp_memwait_handler;
erp_action->timer.data = (unsigned long) erp_action;
erp_action->timer.expires = jiffies + HZ;
add_timer(&erp_action->timer);
}
static void _zfcp_erp_port_reopen_all(struct zfcp_adapter *adapter,
int clear, char *id)
{
struct zfcp_port *port;
read_lock(&adapter->port_list_lock);
list_for_each_entry(port, &adapter->port_list, list)
_zfcp_erp_port_reopen(port, clear, id);
read_unlock(&adapter->port_list_lock);
}
static void _zfcp_erp_lun_reopen_all(struct zfcp_port *port, int clear,
char *id)
{
struct scsi_device *sdev;
shost_for_each_device(sdev, port->adapter->scsi_host)
if (sdev_to_zfcp(sdev)->port == port)
_zfcp_erp_lun_reopen(sdev, clear, id, 0);
}
static void zfcp_erp_strategy_followup_failed(struct zfcp_erp_action *act)
{
switch (act->action) {
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
_zfcp_erp_adapter_reopen(act->adapter, 0, "ersff_1");
break;
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
_zfcp_erp_port_forced_reopen(act->port, 0, "ersff_2");
break;
case ZFCP_ERP_ACTION_REOPEN_PORT:
_zfcp_erp_port_reopen(act->port, 0, "ersff_3");
break;
case ZFCP_ERP_ACTION_REOPEN_LUN:
_zfcp_erp_lun_reopen(act->sdev, 0, "ersff_4", 0);
break;
}
}
static void zfcp_erp_strategy_followup_success(struct zfcp_erp_action *act)
{
switch (act->action) {
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
_zfcp_erp_port_reopen_all(act->adapter, 0, "ersfs_1");
break;
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
_zfcp_erp_port_reopen(act->port, 0, "ersfs_2");
break;
case ZFCP_ERP_ACTION_REOPEN_PORT:
_zfcp_erp_lun_reopen_all(act->port, 0, "ersfs_3");
break;
}
}
static void zfcp_erp_wakeup(struct zfcp_adapter *adapter)
{
unsigned long flags;
read_lock_irqsave(&adapter->erp_lock, flags);
if (list_empty(&adapter->erp_ready_head) &&
list_empty(&adapter->erp_running_head)) {
atomic_clear_mask(ZFCP_STATUS_ADAPTER_ERP_PENDING,
&adapter->status);
wake_up(&adapter->erp_done_wqh);
}
read_unlock_irqrestore(&adapter->erp_lock, flags);
}
static void zfcp_erp_enqueue_ptp_port(struct zfcp_adapter *adapter)
{
struct zfcp_port *port;
port = zfcp_port_enqueue(adapter, adapter->peer_wwpn, 0,
adapter->peer_d_id);
if (IS_ERR(port)) /* error or port already attached */
return;
_zfcp_erp_port_reopen(port, 0, "ereptp1");
}
static int zfcp_erp_adapter_strat_fsf_xconf(struct zfcp_erp_action *erp_action)
{
int retries;
int sleep = 1;
struct zfcp_adapter *adapter = erp_action->adapter;
atomic_clear_mask(ZFCP_STATUS_ADAPTER_XCONFIG_OK, &adapter->status);
for (retries = 7; retries; retries--) {
atomic_clear_mask(ZFCP_STATUS_ADAPTER_HOST_CON_INIT,
&adapter->status);
write_lock_irq(&adapter->erp_lock);
zfcp_erp_action_to_running(erp_action);
write_unlock_irq(&adapter->erp_lock);
if (zfcp_fsf_exchange_config_data(erp_action)) {
atomic_clear_mask(ZFCP_STATUS_ADAPTER_HOST_CON_INIT,
&adapter->status);
return ZFCP_ERP_FAILED;
}
wait_event(adapter->erp_ready_wq,
!list_empty(&adapter->erp_ready_head));
if (erp_action->status & ZFCP_STATUS_ERP_TIMEDOUT)
break;
if (!(atomic_read(&adapter->status) &
ZFCP_STATUS_ADAPTER_HOST_CON_INIT))
break;
ssleep(sleep);
sleep *= 2;
}
atomic_clear_mask(ZFCP_STATUS_ADAPTER_HOST_CON_INIT,
&adapter->status);
if (!(atomic_read(&adapter->status) & ZFCP_STATUS_ADAPTER_XCONFIG_OK))
return ZFCP_ERP_FAILED;
if (fc_host_port_type(adapter->scsi_host) == FC_PORTTYPE_PTP)
zfcp_erp_enqueue_ptp_port(adapter);
return ZFCP_ERP_SUCCEEDED;
}
static int zfcp_erp_adapter_strategy_open_fsf_xport(struct zfcp_erp_action *act)
{
int ret;
struct zfcp_adapter *adapter = act->adapter;
write_lock_irq(&adapter->erp_lock);
zfcp_erp_action_to_running(act);
write_unlock_irq(&adapter->erp_lock);
ret = zfcp_fsf_exchange_port_data(act);
if (ret == -EOPNOTSUPP)
return ZFCP_ERP_SUCCEEDED;
if (ret)
return ZFCP_ERP_FAILED;
zfcp_dbf_rec_run("erasox1", act);
wait_event(adapter->erp_ready_wq,
!list_empty(&adapter->erp_ready_head));
zfcp_dbf_rec_run("erasox2", act);
if (act->status & ZFCP_STATUS_ERP_TIMEDOUT)
return ZFCP_ERP_FAILED;
return ZFCP_ERP_SUCCEEDED;
}
static int zfcp_erp_adapter_strategy_open_fsf(struct zfcp_erp_action *act)
{
if (zfcp_erp_adapter_strat_fsf_xconf(act) == ZFCP_ERP_FAILED)
return ZFCP_ERP_FAILED;
if (zfcp_erp_adapter_strategy_open_fsf_xport(act) == ZFCP_ERP_FAILED)
return ZFCP_ERP_FAILED;
if (mempool_resize(act->adapter->pool.sr_data,
act->adapter->stat_read_buf_num, GFP_KERNEL))
return ZFCP_ERP_FAILED;
if (mempool_resize(act->adapter->pool.status_read_req,
act->adapter->stat_read_buf_num, GFP_KERNEL))
return ZFCP_ERP_FAILED;
atomic_set(&act->adapter->stat_miss, act->adapter->stat_read_buf_num);
if (zfcp_status_read_refill(act->adapter))
return ZFCP_ERP_FAILED;
return ZFCP_ERP_SUCCEEDED;
}
static void zfcp_erp_adapter_strategy_close(struct zfcp_erp_action *act)
{
struct zfcp_adapter *adapter = act->adapter;
/* close queues to ensure that buffers are not accessed by adapter */
zfcp_qdio_close(adapter->qdio);
zfcp_fsf_req_dismiss_all(adapter);
adapter->fsf_req_seq_no = 0;
zfcp_fc_wka_ports_force_offline(adapter->gs);
/* all ports and LUNs are closed */
zfcp_erp_clear_adapter_status(adapter, ZFCP_STATUS_COMMON_OPEN);
atomic_clear_mask(ZFCP_STATUS_ADAPTER_XCONFIG_OK |
ZFCP_STATUS_ADAPTER_LINK_UNPLUGGED, &adapter->status);
}
static int zfcp_erp_adapter_strategy_open(struct zfcp_erp_action *act)
{
struct zfcp_adapter *adapter = act->adapter;
if (zfcp_qdio_open(adapter->qdio)) {
atomic_clear_mask(ZFCP_STATUS_ADAPTER_XCONFIG_OK |
ZFCP_STATUS_ADAPTER_LINK_UNPLUGGED,
&adapter->status);
return ZFCP_ERP_FAILED;
}
if (zfcp_erp_adapter_strategy_open_fsf(act)) {
zfcp_erp_adapter_strategy_close(act);
return ZFCP_ERP_FAILED;
}
atomic_set_mask(ZFCP_STATUS_COMMON_OPEN, &adapter->status);
return ZFCP_ERP_SUCCEEDED;
}
static int zfcp_erp_adapter_strategy(struct zfcp_erp_action *act)
{
struct zfcp_adapter *adapter = act->adapter;
if (atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_OPEN) {
zfcp_erp_adapter_strategy_close(act);
if (act->status & ZFCP_STATUS_ERP_CLOSE_ONLY)
return ZFCP_ERP_EXIT;
}
if (zfcp_erp_adapter_strategy_open(act)) {
ssleep(8);
return ZFCP_ERP_FAILED;
}
return ZFCP_ERP_SUCCEEDED;
}
static int zfcp_erp_port_forced_strategy_close(struct zfcp_erp_action *act)
{
int retval;
retval = zfcp_fsf_close_physical_port(act);
if (retval == -ENOMEM)
return ZFCP_ERP_NOMEM;
act->step = ZFCP_ERP_STEP_PHYS_PORT_CLOSING;
if (retval)
return ZFCP_ERP_FAILED;
return ZFCP_ERP_CONTINUES;
}
static void zfcp_erp_port_strategy_clearstati(struct zfcp_port *port)
{
atomic_clear_mask(ZFCP_STATUS_COMMON_ACCESS_DENIED, &port->status);
}
static int zfcp_erp_port_forced_strategy(struct zfcp_erp_action *erp_action)
{
struct zfcp_port *port = erp_action->port;
int status = atomic_read(&port->status);
switch (erp_action->step) {
case ZFCP_ERP_STEP_UNINITIALIZED:
zfcp_erp_port_strategy_clearstati(port);
if ((status & ZFCP_STATUS_PORT_PHYS_OPEN) &&
(status & ZFCP_STATUS_COMMON_OPEN))
return zfcp_erp_port_forced_strategy_close(erp_action);
else
return ZFCP_ERP_FAILED;
case ZFCP_ERP_STEP_PHYS_PORT_CLOSING:
if (!(status & ZFCP_STATUS_PORT_PHYS_OPEN))
return ZFCP_ERP_SUCCEEDED;
}
return ZFCP_ERP_FAILED;
}
static int zfcp_erp_port_strategy_close(struct zfcp_erp_action *erp_action)
{
int retval;
retval = zfcp_fsf_close_port(erp_action);
if (retval == -ENOMEM)
return ZFCP_ERP_NOMEM;
erp_action->step = ZFCP_ERP_STEP_PORT_CLOSING;
if (retval)
return ZFCP_ERP_FAILED;
return ZFCP_ERP_CONTINUES;
}
static int zfcp_erp_port_strategy_open_port(struct zfcp_erp_action *erp_action)
{
int retval;
retval = zfcp_fsf_open_port(erp_action);
if (retval == -ENOMEM)
return ZFCP_ERP_NOMEM;
erp_action->step = ZFCP_ERP_STEP_PORT_OPENING;
if (retval)
return ZFCP_ERP_FAILED;
return ZFCP_ERP_CONTINUES;
}
static int zfcp_erp_open_ptp_port(struct zfcp_erp_action *act)
{
struct zfcp_adapter *adapter = act->adapter;
struct zfcp_port *port = act->port;
if (port->wwpn != adapter->peer_wwpn) {
zfcp_erp_set_port_status(port, ZFCP_STATUS_COMMON_ERP_FAILED);
return ZFCP_ERP_FAILED;
}
port->d_id = adapter->peer_d_id;
return zfcp_erp_port_strategy_open_port(act);
}
static int zfcp_erp_port_strategy_open_common(struct zfcp_erp_action *act)
{
struct zfcp_adapter *adapter = act->adapter;
struct zfcp_port *port = act->port;
int p_status = atomic_read(&port->status);
switch (act->step) {
case ZFCP_ERP_STEP_UNINITIALIZED:
case ZFCP_ERP_STEP_PHYS_PORT_CLOSING:
case ZFCP_ERP_STEP_PORT_CLOSING:
if (fc_host_port_type(adapter->scsi_host) == FC_PORTTYPE_PTP)
return zfcp_erp_open_ptp_port(act);
if (!port->d_id) {
zfcp_fc_trigger_did_lookup(port);
return ZFCP_ERP_EXIT;
}
return zfcp_erp_port_strategy_open_port(act);
case ZFCP_ERP_STEP_PORT_OPENING:
/* D_ID might have changed during open */
if (p_status & ZFCP_STATUS_COMMON_OPEN) {
if (!port->d_id) {
zfcp_fc_trigger_did_lookup(port);
return ZFCP_ERP_EXIT;
}
return ZFCP_ERP_SUCCEEDED;
}
if (port->d_id && !(p_status & ZFCP_STATUS_COMMON_NOESC)) {
port->d_id = 0;
return ZFCP_ERP_FAILED;
}
/* fall through otherwise */
}
return ZFCP_ERP_FAILED;
}
static int zfcp_erp_port_strategy(struct zfcp_erp_action *erp_action)
{
struct zfcp_port *port = erp_action->port;
int p_status = atomic_read(&port->status);
if ((p_status & ZFCP_STATUS_COMMON_NOESC) &&
!(p_status & ZFCP_STATUS_COMMON_OPEN))
goto close_init_done;
switch (erp_action->step) {
case ZFCP_ERP_STEP_UNINITIALIZED:
zfcp_erp_port_strategy_clearstati(port);
if (p_status & ZFCP_STATUS_COMMON_OPEN)
return zfcp_erp_port_strategy_close(erp_action);
break;
case ZFCP_ERP_STEP_PORT_CLOSING:
if (p_status & ZFCP_STATUS_COMMON_OPEN)
return ZFCP_ERP_FAILED;
break;
}
close_init_done:
if (erp_action->status & ZFCP_STATUS_ERP_CLOSE_ONLY)
return ZFCP_ERP_EXIT;
return zfcp_erp_port_strategy_open_common(erp_action);
}
static void zfcp_erp_lun_strategy_clearstati(struct scsi_device *sdev)
{
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
atomic_clear_mask(ZFCP_STATUS_COMMON_ACCESS_DENIED |
ZFCP_STATUS_LUN_SHARED | ZFCP_STATUS_LUN_READONLY,
&zfcp_sdev->status);
}
static int zfcp_erp_lun_strategy_close(struct zfcp_erp_action *erp_action)
{
int retval = zfcp_fsf_close_lun(erp_action);
if (retval == -ENOMEM)
return ZFCP_ERP_NOMEM;
erp_action->step = ZFCP_ERP_STEP_LUN_CLOSING;
if (retval)
return ZFCP_ERP_FAILED;
return ZFCP_ERP_CONTINUES;
}
static int zfcp_erp_lun_strategy_open(struct zfcp_erp_action *erp_action)
{
int retval = zfcp_fsf_open_lun(erp_action);
if (retval == -ENOMEM)
return ZFCP_ERP_NOMEM;
erp_action->step = ZFCP_ERP_STEP_LUN_OPENING;
if (retval)
return ZFCP_ERP_FAILED;
return ZFCP_ERP_CONTINUES;
}
static int zfcp_erp_lun_strategy(struct zfcp_erp_action *erp_action)
{
struct scsi_device *sdev = erp_action->sdev;
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
switch (erp_action->step) {
case ZFCP_ERP_STEP_UNINITIALIZED:
zfcp_erp_lun_strategy_clearstati(sdev);
if (atomic_read(&zfcp_sdev->status) & ZFCP_STATUS_COMMON_OPEN)
return zfcp_erp_lun_strategy_close(erp_action);
/* already closed, fall through */
case ZFCP_ERP_STEP_LUN_CLOSING:
if (atomic_read(&zfcp_sdev->status) & ZFCP_STATUS_COMMON_OPEN)
return ZFCP_ERP_FAILED;
if (erp_action->status & ZFCP_STATUS_ERP_CLOSE_ONLY)
return ZFCP_ERP_EXIT;
return zfcp_erp_lun_strategy_open(erp_action);
case ZFCP_ERP_STEP_LUN_OPENING:
if (atomic_read(&zfcp_sdev->status) & ZFCP_STATUS_COMMON_OPEN)
return ZFCP_ERP_SUCCEEDED;
}
return ZFCP_ERP_FAILED;
}
static int zfcp_erp_strategy_check_lun(struct scsi_device *sdev, int result)
{
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
switch (result) {
case ZFCP_ERP_SUCCEEDED :
atomic_set(&zfcp_sdev->erp_counter, 0);
zfcp_erp_lun_unblock(sdev);
break;
case ZFCP_ERP_FAILED :
atomic_inc(&zfcp_sdev->erp_counter);
if (atomic_read(&zfcp_sdev->erp_counter) > ZFCP_MAX_ERPS) {
dev_err(&zfcp_sdev->port->adapter->ccw_device->dev,
"ERP failed for LUN 0x%016Lx on "
"port 0x%016Lx\n",
(unsigned long long)zfcp_scsi_dev_lun(sdev),
(unsigned long long)zfcp_sdev->port->wwpn);
zfcp_erp_set_lun_status(sdev,
ZFCP_STATUS_COMMON_ERP_FAILED);
}
break;
}
if (atomic_read(&zfcp_sdev->status) & ZFCP_STATUS_COMMON_ERP_FAILED) {
zfcp_erp_lun_block(sdev, 0);
result = ZFCP_ERP_EXIT;
}
return result;
}
static int zfcp_erp_strategy_check_port(struct zfcp_port *port, int result)
{
switch (result) {
case ZFCP_ERP_SUCCEEDED :
atomic_set(&port->erp_counter, 0);
zfcp_erp_port_unblock(port);
break;
case ZFCP_ERP_FAILED :
if (atomic_read(&port->status) & ZFCP_STATUS_COMMON_NOESC) {
zfcp_erp_port_block(port, 0);
result = ZFCP_ERP_EXIT;
}
atomic_inc(&port->erp_counter);
if (atomic_read(&port->erp_counter) > ZFCP_MAX_ERPS) {
dev_err(&port->adapter->ccw_device->dev,
"ERP failed for remote port 0x%016Lx\n",
(unsigned long long)port->wwpn);
zfcp_erp_set_port_status(port,
ZFCP_STATUS_COMMON_ERP_FAILED);
}
break;
}
if (atomic_read(&port->status) & ZFCP_STATUS_COMMON_ERP_FAILED) {
zfcp_erp_port_block(port, 0);
result = ZFCP_ERP_EXIT;
}
return result;
}
static int zfcp_erp_strategy_check_adapter(struct zfcp_adapter *adapter,
int result)
{
switch (result) {
case ZFCP_ERP_SUCCEEDED :
atomic_set(&adapter->erp_counter, 0);
zfcp_erp_adapter_unblock(adapter);
break;
case ZFCP_ERP_FAILED :
atomic_inc(&adapter->erp_counter);
if (atomic_read(&adapter->erp_counter) > ZFCP_MAX_ERPS) {
dev_err(&adapter->ccw_device->dev,
"ERP cannot recover an error "
"on the FCP device\n");
zfcp_erp_set_adapter_status(adapter,
ZFCP_STATUS_COMMON_ERP_FAILED);
}
break;
}
if (atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_ERP_FAILED) {
zfcp_erp_adapter_block(adapter, 0);
result = ZFCP_ERP_EXIT;
}
return result;
}
static int zfcp_erp_strategy_check_target(struct zfcp_erp_action *erp_action,
int result)
{
struct zfcp_adapter *adapter = erp_action->adapter;
struct zfcp_port *port = erp_action->port;
struct scsi_device *sdev = erp_action->sdev;
switch (erp_action->action) {
case ZFCP_ERP_ACTION_REOPEN_LUN:
result = zfcp_erp_strategy_check_lun(sdev, result);
break;
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
case ZFCP_ERP_ACTION_REOPEN_PORT:
result = zfcp_erp_strategy_check_port(port, result);
break;
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
result = zfcp_erp_strategy_check_adapter(adapter, result);
break;
}
return result;
}
static int zfcp_erp_strat_change_det(atomic_t *target_status, u32 erp_status)
{
int status = atomic_read(target_status);
if ((status & ZFCP_STATUS_COMMON_RUNNING) &&
(erp_status & ZFCP_STATUS_ERP_CLOSE_ONLY))
return 1; /* take it online */
if (!(status & ZFCP_STATUS_COMMON_RUNNING) &&
!(erp_status & ZFCP_STATUS_ERP_CLOSE_ONLY))
return 1; /* take it offline */
return 0;
}
static int zfcp_erp_strategy_statechange(struct zfcp_erp_action *act, int ret)
{
int action = act->action;
struct zfcp_adapter *adapter = act->adapter;
struct zfcp_port *port = act->port;
struct scsi_device *sdev = act->sdev;
struct zfcp_scsi_dev *zfcp_sdev;
u32 erp_status = act->status;
switch (action) {
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
if (zfcp_erp_strat_change_det(&adapter->status, erp_status)) {
_zfcp_erp_adapter_reopen(adapter,
ZFCP_STATUS_COMMON_ERP_FAILED,
"ersscg1");
return ZFCP_ERP_EXIT;
}
break;
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
case ZFCP_ERP_ACTION_REOPEN_PORT:
if (zfcp_erp_strat_change_det(&port->status, erp_status)) {
_zfcp_erp_port_reopen(port,
ZFCP_STATUS_COMMON_ERP_FAILED,
"ersscg2");
return ZFCP_ERP_EXIT;
}
break;
case ZFCP_ERP_ACTION_REOPEN_LUN:
zfcp_sdev = sdev_to_zfcp(sdev);
if (zfcp_erp_strat_change_det(&zfcp_sdev->status, erp_status)) {
_zfcp_erp_lun_reopen(sdev,
ZFCP_STATUS_COMMON_ERP_FAILED,
"ersscg3", 0);
return ZFCP_ERP_EXIT;
}
break;
}
return ret;
}
static void zfcp_erp_action_dequeue(struct zfcp_erp_action *erp_action)
{
struct zfcp_adapter *adapter = erp_action->adapter;
struct zfcp_scsi_dev *zfcp_sdev;
adapter->erp_total_count--;
if (erp_action->status & ZFCP_STATUS_ERP_LOWMEM) {
adapter->erp_low_mem_count--;
erp_action->status &= ~ZFCP_STATUS_ERP_LOWMEM;
}
list_del(&erp_action->list);
zfcp_dbf_rec_run("eractd1", erp_action);
switch (erp_action->action) {
case ZFCP_ERP_ACTION_REOPEN_LUN:
zfcp_sdev = sdev_to_zfcp(erp_action->sdev);
atomic_clear_mask(ZFCP_STATUS_COMMON_ERP_INUSE,
&zfcp_sdev->status);
break;
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
case ZFCP_ERP_ACTION_REOPEN_PORT:
atomic_clear_mask(ZFCP_STATUS_COMMON_ERP_INUSE,
&erp_action->port->status);
break;
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
atomic_clear_mask(ZFCP_STATUS_COMMON_ERP_INUSE,
&erp_action->adapter->status);
break;
}
}
static void zfcp_erp_action_cleanup(struct zfcp_erp_action *act, int result)
{
struct zfcp_adapter *adapter = act->adapter;
struct zfcp_port *port = act->port;
struct scsi_device *sdev = act->sdev;
switch (act->action) {
case ZFCP_ERP_ACTION_REOPEN_LUN:
if (!(act->status & ZFCP_STATUS_ERP_NO_REF))
scsi_device_put(sdev);
break;
case ZFCP_ERP_ACTION_REOPEN_PORT:
if (result == ZFCP_ERP_SUCCEEDED)
zfcp_scsi_schedule_rport_register(port);
/* fall through */
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
put_device(&port->dev);
break;
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
if (result == ZFCP_ERP_SUCCEEDED) {
register_service_level(&adapter->service_level);
queue_work(adapter->work_queue, &adapter->scan_work);
queue_work(adapter->work_queue, &adapter->ns_up_work);
} else
unregister_service_level(&adapter->service_level);
kref_put(&adapter->ref, zfcp_adapter_release);
break;
}
}
static int zfcp_erp_strategy_do_action(struct zfcp_erp_action *erp_action)
{
switch (erp_action->action) {
case ZFCP_ERP_ACTION_REOPEN_ADAPTER:
return zfcp_erp_adapter_strategy(erp_action);
case ZFCP_ERP_ACTION_REOPEN_PORT_FORCED:
return zfcp_erp_port_forced_strategy(erp_action);
case ZFCP_ERP_ACTION_REOPEN_PORT:
return zfcp_erp_port_strategy(erp_action);
case ZFCP_ERP_ACTION_REOPEN_LUN:
return zfcp_erp_lun_strategy(erp_action);
}
return ZFCP_ERP_FAILED;
}
static int zfcp_erp_strategy(struct zfcp_erp_action *erp_action)
{
int retval;
unsigned long flags;
struct zfcp_adapter *adapter = erp_action->adapter;
kref_get(&adapter->ref);
write_lock_irqsave(&adapter->erp_lock, flags);
zfcp_erp_strategy_check_fsfreq(erp_action);
if (erp_action->status & ZFCP_STATUS_ERP_DISMISSED) {
zfcp_erp_action_dequeue(erp_action);
retval = ZFCP_ERP_DISMISSED;
goto unlock;
}
if (erp_action->status & ZFCP_STATUS_ERP_TIMEDOUT) {
retval = ZFCP_ERP_FAILED;
goto check_target;
}
zfcp_erp_action_to_running(erp_action);
/* no lock to allow for blocking operations */
write_unlock_irqrestore(&adapter->erp_lock, flags);
retval = zfcp_erp_strategy_do_action(erp_action);
write_lock_irqsave(&adapter->erp_lock, flags);
if (erp_action->status & ZFCP_STATUS_ERP_DISMISSED)
retval = ZFCP_ERP_CONTINUES;
switch (retval) {
case ZFCP_ERP_NOMEM:
if (!(erp_action->status & ZFCP_STATUS_ERP_LOWMEM)) {
++adapter->erp_low_mem_count;
erp_action->status |= ZFCP_STATUS_ERP_LOWMEM;
}
if (adapter->erp_total_count == adapter->erp_low_mem_count)
_zfcp_erp_adapter_reopen(adapter, 0, "erstgy1");
else {
zfcp_erp_strategy_memwait(erp_action);
retval = ZFCP_ERP_CONTINUES;
}
goto unlock;
case ZFCP_ERP_CONTINUES:
if (erp_action->status & ZFCP_STATUS_ERP_LOWMEM) {
--adapter->erp_low_mem_count;
erp_action->status &= ~ZFCP_STATUS_ERP_LOWMEM;
}
goto unlock;
}
check_target:
retval = zfcp_erp_strategy_check_target(erp_action, retval);
zfcp_erp_action_dequeue(erp_action);
retval = zfcp_erp_strategy_statechange(erp_action, retval);
if (retval == ZFCP_ERP_EXIT)
goto unlock;
if (retval == ZFCP_ERP_SUCCEEDED)
zfcp_erp_strategy_followup_success(erp_action);
if (retval == ZFCP_ERP_FAILED)
zfcp_erp_strategy_followup_failed(erp_action);
unlock:
write_unlock_irqrestore(&adapter->erp_lock, flags);
if (retval != ZFCP_ERP_CONTINUES)
zfcp_erp_action_cleanup(erp_action, retval);
kref_put(&adapter->ref, zfcp_adapter_release);
return retval;
}
static int zfcp_erp_thread(void *data)
{
struct zfcp_adapter *adapter = (struct zfcp_adapter *) data;
struct list_head *next;
struct zfcp_erp_action *act;
unsigned long flags;
for (;;) {
wait_event_interruptible(adapter->erp_ready_wq,
!list_empty(&adapter->erp_ready_head) ||
kthread_should_stop());
if (kthread_should_stop())
break;
write_lock_irqsave(&adapter->erp_lock, flags);
next = adapter->erp_ready_head.next;
write_unlock_irqrestore(&adapter->erp_lock, flags);
if (next != &adapter->erp_ready_head) {
act = list_entry(next, struct zfcp_erp_action, list);
/* there is more to come after dismission, no notify */
if (zfcp_erp_strategy(act) != ZFCP_ERP_DISMISSED)
zfcp_erp_wakeup(adapter);
}
}
return 0;
}
/**
* zfcp_erp_thread_setup - Start ERP thread for adapter
* @adapter: Adapter to start the ERP thread for
*
* Returns 0 on success or error code from kernel_thread()
*/
int zfcp_erp_thread_setup(struct zfcp_adapter *adapter)
{
struct task_struct *thread;
thread = kthread_run(zfcp_erp_thread, adapter, "zfcperp%s",
dev_name(&adapter->ccw_device->dev));
if (IS_ERR(thread)) {
dev_err(&adapter->ccw_device->dev,
"Creating an ERP thread for the FCP device failed.\n");
return PTR_ERR(thread);
}
adapter->erp_thread = thread;
return 0;
}
/**
* zfcp_erp_thread_kill - Stop ERP thread.
* @adapter: Adapter where the ERP thread should be stopped.
*
* The caller of this routine ensures that the specified adapter has
* been shut down and that this operation has been completed. Thus,
* there are no pending erp_actions which would need to be handled
* here.
*/
void zfcp_erp_thread_kill(struct zfcp_adapter *adapter)
{
kthread_stop(adapter->erp_thread);
adapter->erp_thread = NULL;
WARN_ON(!list_empty(&adapter->erp_ready_head));
WARN_ON(!list_empty(&adapter->erp_running_head));
}
/**
* zfcp_erp_wait - wait for completion of error recovery on an adapter
* @adapter: adapter for which to wait for completion of its error recovery
*/
void zfcp_erp_wait(struct zfcp_adapter *adapter)
{
wait_event(adapter->erp_done_wqh,
!(atomic_read(&adapter->status) &
ZFCP_STATUS_ADAPTER_ERP_PENDING));
}
/**
* zfcp_erp_set_adapter_status - set adapter status bits
* @adapter: adapter to change the status
* @mask: status bits to change
*
* Changes in common status bits are propagated to attached ports and LUNs.
*/
void zfcp_erp_set_adapter_status(struct zfcp_adapter *adapter, u32 mask)
{
struct zfcp_port *port;
struct scsi_device *sdev;
unsigned long flags;
u32 common_mask = mask & ZFCP_COMMON_FLAGS;
atomic_set_mask(mask, &adapter->status);
if (!common_mask)
return;
read_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry(port, &adapter->port_list, list)
atomic_set_mask(common_mask, &port->status);
read_unlock_irqrestore(&adapter->port_list_lock, flags);
shost_for_each_device(sdev, adapter->scsi_host)
atomic_set_mask(common_mask, &sdev_to_zfcp(sdev)->status);
}
/**
* zfcp_erp_clear_adapter_status - clear adapter status bits
* @adapter: adapter to change the status
* @mask: status bits to change
*
* Changes in common status bits are propagated to attached ports and LUNs.
*/
void zfcp_erp_clear_adapter_status(struct zfcp_adapter *adapter, u32 mask)
{
struct zfcp_port *port;
struct scsi_device *sdev;
unsigned long flags;
u32 common_mask = mask & ZFCP_COMMON_FLAGS;
u32 clear_counter = mask & ZFCP_STATUS_COMMON_ERP_FAILED;
atomic_clear_mask(mask, &adapter->status);
if (!common_mask)
return;
if (clear_counter)
atomic_set(&adapter->erp_counter, 0);
read_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry(port, &adapter->port_list, list) {
atomic_clear_mask(common_mask, &port->status);
if (clear_counter)
atomic_set(&port->erp_counter, 0);
}
read_unlock_irqrestore(&adapter->port_list_lock, flags);
shost_for_each_device(sdev, adapter->scsi_host) {
atomic_clear_mask(common_mask, &sdev_to_zfcp(sdev)->status);
if (clear_counter)
atomic_set(&sdev_to_zfcp(sdev)->erp_counter, 0);
}
}
/**
* zfcp_erp_set_port_status - set port status bits
* @port: port to change the status
* @mask: status bits to change
*
* Changes in common status bits are propagated to attached LUNs.
*/
void zfcp_erp_set_port_status(struct zfcp_port *port, u32 mask)
{
struct scsi_device *sdev;
u32 common_mask = mask & ZFCP_COMMON_FLAGS;
atomic_set_mask(mask, &port->status);
if (!common_mask)
return;
shost_for_each_device(sdev, port->adapter->scsi_host)
if (sdev_to_zfcp(sdev)->port == port)
atomic_set_mask(common_mask,
&sdev_to_zfcp(sdev)->status);
}
/**
* zfcp_erp_clear_port_status - clear port status bits
* @port: adapter to change the status
* @mask: status bits to change
*
* Changes in common status bits are propagated to attached LUNs.
*/
void zfcp_erp_clear_port_status(struct zfcp_port *port, u32 mask)
{
struct scsi_device *sdev;
u32 common_mask = mask & ZFCP_COMMON_FLAGS;
u32 clear_counter = mask & ZFCP_STATUS_COMMON_ERP_FAILED;
atomic_clear_mask(mask, &port->status);
if (!common_mask)
return;
if (clear_counter)
atomic_set(&port->erp_counter, 0);
shost_for_each_device(sdev, port->adapter->scsi_host)
if (sdev_to_zfcp(sdev)->port == port) {
atomic_clear_mask(common_mask,
&sdev_to_zfcp(sdev)->status);
if (clear_counter)
atomic_set(&sdev_to_zfcp(sdev)->erp_counter, 0);
}
}
/**
* zfcp_erp_set_lun_status - set lun status bits
* @sdev: SCSI device / lun to set the status bits
* @mask: status bits to change
*/
void zfcp_erp_set_lun_status(struct scsi_device *sdev, u32 mask)
{
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
atomic_set_mask(mask, &zfcp_sdev->status);
}
/**
* zfcp_erp_clear_lun_status - clear lun status bits
* @sdev: SCSi device / lun to clear the status bits
* @mask: status bits to change
*/
void zfcp_erp_clear_lun_status(struct scsi_device *sdev, u32 mask)
{
struct zfcp_scsi_dev *zfcp_sdev = sdev_to_zfcp(sdev);
atomic_clear_mask(mask, &zfcp_sdev->status);
if (mask & ZFCP_STATUS_COMMON_ERP_FAILED)
atomic_set(&zfcp_sdev->erp_counter, 0);
}
| gpl-2.0 |
sud-vastav/android_kernel_xiaomi_armani_old | drivers/usb/image/mdc800.c | 8143 | 24697 | /*
* copyright (C) 1999/2000 by Henning Zabel <henning@uni-paderborn.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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* USB-Kernel Driver for the Mustek MDC800 Digital Camera
* (c) 1999/2000 Henning Zabel <henning@uni-paderborn.de>
*
*
* The driver brings the USB functions of the MDC800 to Linux.
* To use the Camera you must support the USB Protocol of the camera
* to the Kernel Node.
* The Driver uses a misc device Node. Create it with :
* mknod /dev/mustek c 180 32
*
* The driver supports only one camera.
*
* Fix: mdc800 used sleep_on and slept with io_lock held.
* Converted sleep_on to waitqueues with schedule_timeout and made io_lock
* a semaphore from a spinlock.
* by Oliver Neukum <oliver@neukum.name>
* (02/12/2001)
*
* Identify version on module load.
* (08/04/2001) gb
*
* version 0.7.5
* Fixed potential SMP races with Spinlocks.
* Thanks to Oliver Neukum <oliver@neukum.name> who
* noticed the race conditions.
* (30/10/2000)
*
* Fixed: Setting urb->dev before submitting urb.
* by Greg KH <greg@kroah.com>
* (13/10/2000)
*
* version 0.7.3
* bugfix : The mdc800->state field gets set to READY after the
* the diconnect function sets it to NOT_CONNECTED. This makes the
* driver running like the camera is connected and causes some
* hang ups.
*
* version 0.7.1
* MOD_INC and MOD_DEC are changed in usb_probe to prevent load/unload
* problems when compiled as Module.
* (04/04/2000)
*
* The mdc800 driver gets assigned the USB Minor 32-47. The Registration
* was updated to use these values.
* (26/03/2000)
*
* The Init und Exit Module Function are updated.
* (01/03/2000)
*
* version 0.7.0
* Rewrite of the driver : The driver now uses URB's. The old stuff
* has been removed.
*
* version 0.6.0
* Rewrite of this driver: The Emulation of the rs232 protocoll
* has been removed from the driver. A special executeCommand function
* for this driver is included to gphoto.
* The driver supports two kind of communication to bulk endpoints.
* Either with the dev->bus->ops->bulk... or with callback function.
* (09/11/1999)
*
* version 0.5.0:
* first Version that gets a version number. Most of the needed
* functions work.
* (20/10/1999)
*/
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/random.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/wait.h>
#include <linux/mutex.h>
#include <linux/usb.h>
#include <linux/fs.h>
/*
* Version Information
*/
#define DRIVER_VERSION "v0.7.5 (30/10/2000)"
#define DRIVER_AUTHOR "Henning Zabel <henning@uni-paderborn.de>"
#define DRIVER_DESC "USB Driver for Mustek MDC800 Digital Camera"
/* Vendor and Product Information */
#define MDC800_VENDOR_ID 0x055f
#define MDC800_PRODUCT_ID 0xa800
/* Timeouts (msec) */
#define TO_DOWNLOAD_GET_READY 1500
#define TO_DOWNLOAD_GET_BUSY 1500
#define TO_WRITE_GET_READY 1000
#define TO_DEFAULT_COMMAND 5000
#define TO_READ_FROM_IRQ TO_DEFAULT_COMMAND
#define TO_GET_READY TO_DEFAULT_COMMAND
/* Minor Number of the device (create with mknod /dev/mustek c 180 32) */
#define MDC800_DEVICE_MINOR_BASE 32
/**************************************************************************
Data and structs
***************************************************************************/
typedef enum {
NOT_CONNECTED, READY, WORKING, DOWNLOAD
} mdc800_state;
/* Data for the driver */
struct mdc800_data
{
struct usb_device * dev; // Device Data
mdc800_state state;
unsigned int endpoint [4];
struct urb * irq_urb;
wait_queue_head_t irq_wait;
int irq_woken;
char* irq_urb_buffer;
int camera_busy; // is camera busy ?
int camera_request_ready; // Status to synchronize with irq
char camera_response [8]; // last Bytes send after busy
struct urb * write_urb;
char* write_urb_buffer;
wait_queue_head_t write_wait;
int written;
struct urb * download_urb;
char* download_urb_buffer;
wait_queue_head_t download_wait;
int downloaded;
int download_left; // Bytes left to download ?
/* Device Data */
char out [64]; // Answer Buffer
int out_ptr; // Index to the first not readen byte
int out_count; // Bytes in the buffer
int open; // Camera device open ?
struct mutex io_lock; // IO -lock
char in [8]; // Command Input Buffer
int in_count;
int pic_index; // Cache for the Imagesize (-1 for nothing cached )
int pic_len;
int minor;
};
/* Specification of the Endpoints */
static struct usb_endpoint_descriptor mdc800_ed [4] =
{
{
.bLength = 0,
.bDescriptorType = 0,
.bEndpointAddress = 0x01,
.bmAttributes = 0x02,
.wMaxPacketSize = cpu_to_le16(8),
.bInterval = 0,
.bRefresh = 0,
.bSynchAddress = 0,
},
{
.bLength = 0,
.bDescriptorType = 0,
.bEndpointAddress = 0x82,
.bmAttributes = 0x03,
.wMaxPacketSize = cpu_to_le16(8),
.bInterval = 0,
.bRefresh = 0,
.bSynchAddress = 0,
},
{
.bLength = 0,
.bDescriptorType = 0,
.bEndpointAddress = 0x03,
.bmAttributes = 0x02,
.wMaxPacketSize = cpu_to_le16(64),
.bInterval = 0,
.bRefresh = 0,
.bSynchAddress = 0,
},
{
.bLength = 0,
.bDescriptorType = 0,
.bEndpointAddress = 0x84,
.bmAttributes = 0x02,
.wMaxPacketSize = cpu_to_le16(64),
.bInterval = 0,
.bRefresh = 0,
.bSynchAddress = 0,
},
};
/* The Variable used by the driver */
static struct mdc800_data* mdc800;
/***************************************************************************
The USB Part of the driver
****************************************************************************/
static int mdc800_endpoint_equals (struct usb_endpoint_descriptor *a,struct usb_endpoint_descriptor *b)
{
return (
( a->bEndpointAddress == b->bEndpointAddress )
&& ( a->bmAttributes == b->bmAttributes )
&& ( a->wMaxPacketSize == b->wMaxPacketSize )
);
}
/*
* Checks whether the camera responds busy
*/
static int mdc800_isBusy (char* ch)
{
int i=0;
while (i<8)
{
if (ch [i] != (char)0x99)
return 0;
i++;
}
return 1;
}
/*
* Checks whether the Camera is ready
*/
static int mdc800_isReady (char *ch)
{
int i=0;
while (i<8)
{
if (ch [i] != (char)0xbb)
return 0;
i++;
}
return 1;
}
/*
* USB IRQ Handler for InputLine
*/
static void mdc800_usb_irq (struct urb *urb)
{
int data_received=0, wake_up;
unsigned char* b=urb->transfer_buffer;
struct mdc800_data* mdc800=urb->context;
int status = urb->status;
if (status >= 0) {
//dbg ("%i %i %i %i %i %i %i %i \n",b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7]);
if (mdc800_isBusy (b))
{
if (!mdc800->camera_busy)
{
mdc800->camera_busy=1;
dbg ("gets busy");
}
}
else
{
if (mdc800->camera_busy && mdc800_isReady (b))
{
mdc800->camera_busy=0;
dbg ("gets ready");
}
}
if (!(mdc800_isBusy (b) || mdc800_isReady (b)))
{
/* Store Data in camera_answer field */
dbg ("%i %i %i %i %i %i %i %i ",b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7]);
memcpy (mdc800->camera_response,b,8);
data_received=1;
}
}
wake_up= ( mdc800->camera_request_ready > 0 )
&&
(
((mdc800->camera_request_ready == 1) && (!mdc800->camera_busy))
||
((mdc800->camera_request_ready == 2) && data_received)
||
((mdc800->camera_request_ready == 3) && (mdc800->camera_busy))
||
(status < 0)
);
if (wake_up)
{
mdc800->camera_request_ready=0;
mdc800->irq_woken=1;
wake_up (&mdc800->irq_wait);
}
}
/*
* Waits a while until the irq responds that camera is ready
*
* mode : 0: Wait for camera gets ready
* 1: Wait for receiving data
* 2: Wait for camera gets busy
*
* msec: Time to wait
*/
static int mdc800_usb_waitForIRQ (int mode, int msec)
{
mdc800->camera_request_ready=1+mode;
wait_event_timeout(mdc800->irq_wait, mdc800->irq_woken, msec*HZ/1000);
mdc800->irq_woken = 0;
if (mdc800->camera_request_ready>0)
{
mdc800->camera_request_ready=0;
dev_err(&mdc800->dev->dev, "timeout waiting for camera.\n");
return -1;
}
if (mdc800->state == NOT_CONNECTED)
{
printk(KERN_WARNING "mdc800: Camera gets disconnected "
"during waiting for irq.\n");
mdc800->camera_request_ready=0;
return -2;
}
return 0;
}
/*
* The write_urb callback function
*/
static void mdc800_usb_write_notify (struct urb *urb)
{
struct mdc800_data* mdc800=urb->context;
int status = urb->status;
if (status != 0)
dev_err(&mdc800->dev->dev,
"writing command fails (status=%i)\n", status);
else
mdc800->state=READY;
mdc800->written = 1;
wake_up (&mdc800->write_wait);
}
/*
* The download_urb callback function
*/
static void mdc800_usb_download_notify (struct urb *urb)
{
struct mdc800_data* mdc800=urb->context;
int status = urb->status;
if (status == 0) {
/* Fill output buffer with these data */
memcpy (mdc800->out, urb->transfer_buffer, 64);
mdc800->out_count=64;
mdc800->out_ptr=0;
mdc800->download_left-=64;
if (mdc800->download_left == 0)
{
mdc800->state=READY;
}
} else {
dev_err(&mdc800->dev->dev,
"request bytes fails (status:%i)\n", status);
}
mdc800->downloaded = 1;
wake_up (&mdc800->download_wait);
}
/***************************************************************************
Probing for the Camera
***************************************************************************/
static struct usb_driver mdc800_usb_driver;
static const struct file_operations mdc800_device_ops;
static struct usb_class_driver mdc800_class = {
.name = "mdc800%d",
.fops = &mdc800_device_ops,
.minor_base = MDC800_DEVICE_MINOR_BASE,
};
/*
* Callback to search the Mustek MDC800 on the USB Bus
*/
static int mdc800_usb_probe (struct usb_interface *intf,
const struct usb_device_id *id)
{
int i,j;
struct usb_host_interface *intf_desc;
struct usb_device *dev = interface_to_usbdev (intf);
int irq_interval=0;
int retval;
dbg ("(mdc800_usb_probe) called.");
if (mdc800->dev != NULL)
{
dev_warn(&intf->dev, "only one Mustek MDC800 is supported.\n");
return -ENODEV;
}
if (dev->descriptor.bNumConfigurations != 1)
{
dev_err(&intf->dev,
"probe fails -> wrong Number of Configuration\n");
return -ENODEV;
}
intf_desc = intf->cur_altsetting;
if (
( intf_desc->desc.bInterfaceClass != 0xff )
|| ( intf_desc->desc.bInterfaceSubClass != 0 )
|| ( intf_desc->desc.bInterfaceProtocol != 0 )
|| ( intf_desc->desc.bNumEndpoints != 4)
)
{
dev_err(&intf->dev, "probe fails -> wrong Interface\n");
return -ENODEV;
}
/* Check the Endpoints */
for (i=0; i<4; i++)
{
mdc800->endpoint[i]=-1;
for (j=0; j<4; j++)
{
if (mdc800_endpoint_equals (&intf_desc->endpoint [j].desc,&mdc800_ed [i]))
{
mdc800->endpoint[i]=intf_desc->endpoint [j].desc.bEndpointAddress ;
if (i==1)
{
irq_interval=intf_desc->endpoint [j].desc.bInterval;
}
}
}
if (mdc800->endpoint[i] == -1)
{
dev_err(&intf->dev, "probe fails -> Wrong Endpoints.\n");
return -ENODEV;
}
}
dev_info(&intf->dev, "Found Mustek MDC800 on USB.\n");
mutex_lock(&mdc800->io_lock);
retval = usb_register_dev(intf, &mdc800_class);
if (retval) {
dev_err(&intf->dev, "Not able to get a minor for this device.\n");
mutex_unlock(&mdc800->io_lock);
return -ENODEV;
}
mdc800->dev=dev;
mdc800->open=0;
/* Setup URB Structs */
usb_fill_int_urb (
mdc800->irq_urb,
mdc800->dev,
usb_rcvintpipe (mdc800->dev,mdc800->endpoint [1]),
mdc800->irq_urb_buffer,
8,
mdc800_usb_irq,
mdc800,
irq_interval
);
usb_fill_bulk_urb (
mdc800->write_urb,
mdc800->dev,
usb_sndbulkpipe (mdc800->dev, mdc800->endpoint[0]),
mdc800->write_urb_buffer,
8,
mdc800_usb_write_notify,
mdc800
);
usb_fill_bulk_urb (
mdc800->download_urb,
mdc800->dev,
usb_rcvbulkpipe (mdc800->dev, mdc800->endpoint [3]),
mdc800->download_urb_buffer,
64,
mdc800_usb_download_notify,
mdc800
);
mdc800->state=READY;
mutex_unlock(&mdc800->io_lock);
usb_set_intfdata(intf, mdc800);
return 0;
}
/*
* Disconnect USB device (maybe the MDC800)
*/
static void mdc800_usb_disconnect (struct usb_interface *intf)
{
struct mdc800_data* mdc800 = usb_get_intfdata(intf);
dbg ("(mdc800_usb_disconnect) called");
if (mdc800) {
if (mdc800->state == NOT_CONNECTED)
return;
usb_deregister_dev(intf, &mdc800_class);
/* must be under lock to make sure no URB
is submitted after usb_kill_urb() */
mutex_lock(&mdc800->io_lock);
mdc800->state=NOT_CONNECTED;
usb_kill_urb(mdc800->irq_urb);
usb_kill_urb(mdc800->write_urb);
usb_kill_urb(mdc800->download_urb);
mutex_unlock(&mdc800->io_lock);
mdc800->dev = NULL;
usb_set_intfdata(intf, NULL);
}
dev_info(&intf->dev, "Mustek MDC800 disconnected from USB.\n");
}
/***************************************************************************
The Misc device Part (file_operations)
****************************************************************************/
/*
* This Function calc the Answersize for a command.
*/
static int mdc800_getAnswerSize (char command)
{
switch ((unsigned char) command)
{
case 0x2a:
case 0x49:
case 0x51:
case 0x0d:
case 0x20:
case 0x07:
case 0x01:
case 0x25:
case 0x00:
return 8;
case 0x05:
case 0x3e:
return mdc800->pic_len;
case 0x09:
return 4096;
default:
return 0;
}
}
/*
* Init the device: (1) alloc mem (2) Increase MOD Count ..
*/
static int mdc800_device_open (struct inode* inode, struct file *file)
{
int retval=0;
int errn=0;
mutex_lock(&mdc800->io_lock);
if (mdc800->state == NOT_CONNECTED)
{
errn=-EBUSY;
goto error_out;
}
if (mdc800->open)
{
errn=-EBUSY;
goto error_out;
}
mdc800->in_count=0;
mdc800->out_count=0;
mdc800->out_ptr=0;
mdc800->pic_index=0;
mdc800->pic_len=-1;
mdc800->download_left=0;
mdc800->camera_busy=0;
mdc800->camera_request_ready=0;
retval=0;
mdc800->irq_urb->dev = mdc800->dev;
retval = usb_submit_urb (mdc800->irq_urb, GFP_KERNEL);
if (retval) {
dev_err(&mdc800->dev->dev,
"request USB irq fails (submit_retval=%i).\n", retval);
errn = -EIO;
goto error_out;
}
mdc800->open=1;
dbg ("Mustek MDC800 device opened.");
error_out:
mutex_unlock(&mdc800->io_lock);
return errn;
}
/*
* Close the Camera and release Memory
*/
static int mdc800_device_release (struct inode* inode, struct file *file)
{
int retval=0;
dbg ("Mustek MDC800 device closed.");
mutex_lock(&mdc800->io_lock);
if (mdc800->open && (mdc800->state != NOT_CONNECTED))
{
usb_kill_urb(mdc800->irq_urb);
usb_kill_urb(mdc800->write_urb);
usb_kill_urb(mdc800->download_urb);
mdc800->open=0;
}
else
{
retval=-EIO;
}
mutex_unlock(&mdc800->io_lock);
return retval;
}
/*
* The Device read callback Function
*/
static ssize_t mdc800_device_read (struct file *file, char __user *buf, size_t len, loff_t *pos)
{
size_t left=len, sts=len; /* single transfer size */
char __user *ptr = buf;
int retval;
mutex_lock(&mdc800->io_lock);
if (mdc800->state == NOT_CONNECTED)
{
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
if (mdc800->state == WORKING)
{
printk(KERN_WARNING "mdc800: Illegal State \"working\""
"reached during read ?!\n");
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
if (!mdc800->open)
{
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
while (left)
{
if (signal_pending (current))
{
mutex_unlock(&mdc800->io_lock);
return -EINTR;
}
sts=left > (mdc800->out_count-mdc800->out_ptr)?mdc800->out_count-mdc800->out_ptr:left;
if (sts <= 0)
{
/* Too less Data in buffer */
if (mdc800->state == DOWNLOAD)
{
mdc800->out_count=0;
mdc800->out_ptr=0;
/* Download -> Request new bytes */
mdc800->download_urb->dev = mdc800->dev;
retval = usb_submit_urb (mdc800->download_urb, GFP_KERNEL);
if (retval) {
dev_err(&mdc800->dev->dev,
"Can't submit download urb "
"(retval=%i)\n", retval);
mutex_unlock(&mdc800->io_lock);
return len-left;
}
wait_event_timeout(mdc800->download_wait, mdc800->downloaded,
TO_DOWNLOAD_GET_READY*HZ/1000);
mdc800->downloaded = 0;
if (mdc800->download_urb->status != 0)
{
dev_err(&mdc800->dev->dev,
"request download-bytes fails "
"(status=%i)\n",
mdc800->download_urb->status);
mutex_unlock(&mdc800->io_lock);
return len-left;
}
}
else
{
/* No more bytes -> that's an error*/
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
}
else
{
/* Copy Bytes */
if (copy_to_user(ptr, &mdc800->out [mdc800->out_ptr],
sts)) {
mutex_unlock(&mdc800->io_lock);
return -EFAULT;
}
ptr+=sts;
left-=sts;
mdc800->out_ptr+=sts;
}
}
mutex_unlock(&mdc800->io_lock);
return len-left;
}
/*
* The Device write callback Function
* If a 8Byte Command is received, it will be send to the camera.
* After this the driver initiates the request for the answer or
* just waits until the camera becomes ready.
*/
static ssize_t mdc800_device_write (struct file *file, const char __user *buf, size_t len, loff_t *pos)
{
size_t i=0;
int retval;
mutex_lock(&mdc800->io_lock);
if (mdc800->state != READY)
{
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
if (!mdc800->open )
{
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
while (i<len)
{
unsigned char c;
if (signal_pending (current))
{
mutex_unlock(&mdc800->io_lock);
return -EINTR;
}
if(get_user(c, buf+i))
{
mutex_unlock(&mdc800->io_lock);
return -EFAULT;
}
/* check for command start */
if (c == 0x55)
{
mdc800->in_count=0;
mdc800->out_count=0;
mdc800->out_ptr=0;
mdc800->download_left=0;
}
/* save command byte */
if (mdc800->in_count < 8)
{
mdc800->in[mdc800->in_count] = c;
mdc800->in_count++;
}
else
{
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
/* Command Buffer full ? -> send it to camera */
if (mdc800->in_count == 8)
{
int answersize;
if (mdc800_usb_waitForIRQ (0,TO_GET_READY))
{
dev_err(&mdc800->dev->dev,
"Camera didn't get ready.\n");
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
answersize=mdc800_getAnswerSize (mdc800->in[1]);
mdc800->state=WORKING;
memcpy (mdc800->write_urb->transfer_buffer, mdc800->in,8);
mdc800->write_urb->dev = mdc800->dev;
retval = usb_submit_urb (mdc800->write_urb, GFP_KERNEL);
if (retval) {
dev_err(&mdc800->dev->dev,
"submitting write urb fails "
"(retval=%i)\n", retval);
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
wait_event_timeout(mdc800->write_wait, mdc800->written, TO_WRITE_GET_READY*HZ/1000);
mdc800->written = 0;
if (mdc800->state == WORKING)
{
usb_kill_urb(mdc800->write_urb);
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
switch ((unsigned char) mdc800->in[1])
{
case 0x05: /* Download Image */
case 0x3e: /* Take shot in Fine Mode (WCam Mode) */
if (mdc800->pic_len < 0)
{
dev_err(&mdc800->dev->dev,
"call 0x07 before "
"0x05,0x3e\n");
mdc800->state=READY;
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
mdc800->pic_len=-1;
case 0x09: /* Download Thumbnail */
mdc800->download_left=answersize+64;
mdc800->state=DOWNLOAD;
mdc800_usb_waitForIRQ (0,TO_DOWNLOAD_GET_BUSY);
break;
default:
if (answersize)
{
if (mdc800_usb_waitForIRQ (1,TO_READ_FROM_IRQ))
{
dev_err(&mdc800->dev->dev, "requesting answer from irq fails\n");
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
/* Write dummy data, (this is ugly but part of the USB Protocol */
/* if you use endpoint 1 as bulk and not as irq) */
memcpy (mdc800->out, mdc800->camera_response,8);
/* This is the interpreted answer */
memcpy (&mdc800->out[8], mdc800->camera_response,8);
mdc800->out_ptr=0;
mdc800->out_count=16;
/* Cache the Imagesize, if command was getImageSize */
if (mdc800->in [1] == (char) 0x07)
{
mdc800->pic_len=(int) 65536*(unsigned char) mdc800->camera_response[0]+256*(unsigned char) mdc800->camera_response[1]+(unsigned char) mdc800->camera_response[2];
dbg ("cached imagesize = %i",mdc800->pic_len);
}
}
else
{
if (mdc800_usb_waitForIRQ (0,TO_DEFAULT_COMMAND))
{
dev_err(&mdc800->dev->dev, "Command Timeout.\n");
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
}
mdc800->state=READY;
break;
}
}
i++;
}
mutex_unlock(&mdc800->io_lock);
return i;
}
/***************************************************************************
Init and Cleanup this driver (Structs and types)
****************************************************************************/
/* File Operations of this drivers */
static const struct file_operations mdc800_device_ops =
{
.owner = THIS_MODULE,
.read = mdc800_device_read,
.write = mdc800_device_write,
.open = mdc800_device_open,
.release = mdc800_device_release,
.llseek = noop_llseek,
};
static const struct usb_device_id mdc800_table[] = {
{ USB_DEVICE(MDC800_VENDOR_ID, MDC800_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, mdc800_table);
/*
* USB Driver Struct for this device
*/
static struct usb_driver mdc800_usb_driver =
{
.name = "mdc800",
.probe = mdc800_usb_probe,
.disconnect = mdc800_usb_disconnect,
.id_table = mdc800_table
};
/************************************************************************
Init and Cleanup this driver (Main Functions)
*************************************************************************/
static int __init usb_mdc800_init (void)
{
int retval = -ENODEV;
/* Allocate Memory */
mdc800=kzalloc (sizeof (struct mdc800_data), GFP_KERNEL);
if (!mdc800)
goto cleanup_on_fail;
mdc800->dev = NULL;
mdc800->state=NOT_CONNECTED;
mutex_init (&mdc800->io_lock);
init_waitqueue_head (&mdc800->irq_wait);
init_waitqueue_head (&mdc800->write_wait);
init_waitqueue_head (&mdc800->download_wait);
mdc800->irq_woken = 0;
mdc800->downloaded = 0;
mdc800->written = 0;
mdc800->irq_urb_buffer=kmalloc (8, GFP_KERNEL);
if (!mdc800->irq_urb_buffer)
goto cleanup_on_fail;
mdc800->write_urb_buffer=kmalloc (8, GFP_KERNEL);
if (!mdc800->write_urb_buffer)
goto cleanup_on_fail;
mdc800->download_urb_buffer=kmalloc (64, GFP_KERNEL);
if (!mdc800->download_urb_buffer)
goto cleanup_on_fail;
mdc800->irq_urb=usb_alloc_urb (0, GFP_KERNEL);
if (!mdc800->irq_urb)
goto cleanup_on_fail;
mdc800->download_urb=usb_alloc_urb (0, GFP_KERNEL);
if (!mdc800->download_urb)
goto cleanup_on_fail;
mdc800->write_urb=usb_alloc_urb (0, GFP_KERNEL);
if (!mdc800->write_urb)
goto cleanup_on_fail;
/* Register the driver */
retval = usb_register(&mdc800_usb_driver);
if (retval)
goto cleanup_on_fail;
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
return 0;
/* Clean driver up, when something fails */
cleanup_on_fail:
if (mdc800 != NULL)
{
printk(KERN_ERR "mdc800: can't alloc memory!\n");
kfree(mdc800->download_urb_buffer);
kfree(mdc800->write_urb_buffer);
kfree(mdc800->irq_urb_buffer);
usb_free_urb(mdc800->write_urb);
usb_free_urb(mdc800->download_urb);
usb_free_urb(mdc800->irq_urb);
kfree (mdc800);
}
mdc800 = NULL;
return retval;
}
static void __exit usb_mdc800_cleanup (void)
{
usb_deregister (&mdc800_usb_driver);
usb_free_urb (mdc800->irq_urb);
usb_free_urb (mdc800->download_urb);
usb_free_urb (mdc800->write_urb);
kfree (mdc800->irq_urb_buffer);
kfree (mdc800->write_urb_buffer);
kfree (mdc800->download_urb_buffer);
kfree (mdc800);
mdc800 = NULL;
}
module_init (usb_mdc800_init);
module_exit (usb_mdc800_cleanup);
MODULE_AUTHOR( DRIVER_AUTHOR );
MODULE_DESCRIPTION( DRIVER_DESC );
MODULE_LICENSE("GPL");
| gpl-2.0 |
isimobile/android_kernel_sony_fusion3 | sound/pci/asihpi/hpidebug.c | 9679 | 1946 | /************************************************************************
AudioScience HPI driver
Copyright (C) 1997-2011 AudioScience Inc. <support@audioscience.com>
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
Debug macro translation.
************************************************************************/
#include "hpi_internal.h"
#include "hpidebug.h"
/* Debug level; 0 quiet; 1 informative, 2 debug, 3 verbose debug. */
int hpi_debug_level = HPI_DEBUG_LEVEL_DEFAULT;
void hpi_debug_init(void)
{
printk(KERN_INFO "debug start\n");
}
int hpi_debug_level_set(int level)
{
int old_level;
old_level = hpi_debug_level;
hpi_debug_level = level;
return old_level;
}
int hpi_debug_level_get(void)
{
return hpi_debug_level;
}
void hpi_debug_message(struct hpi_message *phm, char *sz_fileline)
{
if (phm) {
printk(KERN_DEBUG "HPI_MSG%d,%d,%d,%d,%d\n", phm->version,
phm->adapter_index, phm->obj_index, phm->function,
phm->u.c.attribute);
}
}
void hpi_debug_data(u16 *pdata, u32 len)
{
u32 i;
int j;
int k;
int lines;
int cols = 8;
lines = (len + cols - 1) / cols;
if (lines > 8)
lines = 8;
for (i = 0, j = 0; j < lines; j++) {
printk(KERN_DEBUG "%p:", (pdata + i));
for (k = 0; k < cols && i < len; i++, k++)
printk("%s%04x", k == 0 ? "" : " ", pdata[i]);
printk("\n");
}
}
| gpl-2.0 |
jiangbeilengyu/famkernel | arch/powerpc/platforms/embedded6xx/usbgecko_udbg.c | 11727 | 6864 | /*
* arch/powerpc/platforms/embedded6xx/usbgecko_udbg.c
*
* udbg serial input/output routines for the USB Gecko adapter.
* Copyright (C) 2008-2009 The GameCube Linux Team
* Copyright (C) 2008,2009 Albert Herranz
*
* 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 <mm/mmu_decl.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/udbg.h>
#include <asm/fixmap.h>
#include "usbgecko_udbg.h"
#define EXI_CLK_32MHZ 5
#define EXI_CSR 0x00
#define EXI_CSR_CLKMASK (0x7<<4)
#define EXI_CSR_CLK_32MHZ (EXI_CLK_32MHZ<<4)
#define EXI_CSR_CSMASK (0x7<<7)
#define EXI_CSR_CS_0 (0x1<<7) /* Chip Select 001 */
#define EXI_CR 0x0c
#define EXI_CR_TSTART (1<<0)
#define EXI_CR_WRITE (1<<2)
#define EXI_CR_READ_WRITE (2<<2)
#define EXI_CR_TLEN(len) (((len)-1)<<4)
#define EXI_DATA 0x10
#define UG_READ_ATTEMPTS 100
#define UG_WRITE_ATTEMPTS 100
static void __iomem *ug_io_base;
/*
* Performs one input/output transaction between the exi host and the usbgecko.
*/
static u32 ug_io_transaction(u32 in)
{
u32 __iomem *csr_reg = ug_io_base + EXI_CSR;
u32 __iomem *data_reg = ug_io_base + EXI_DATA;
u32 __iomem *cr_reg = ug_io_base + EXI_CR;
u32 csr, data, cr;
/* select */
csr = EXI_CSR_CLK_32MHZ | EXI_CSR_CS_0;
out_be32(csr_reg, csr);
/* read/write */
data = in;
out_be32(data_reg, data);
cr = EXI_CR_TLEN(2) | EXI_CR_READ_WRITE | EXI_CR_TSTART;
out_be32(cr_reg, cr);
while (in_be32(cr_reg) & EXI_CR_TSTART)
barrier();
/* deselect */
out_be32(csr_reg, 0);
/* result */
data = in_be32(data_reg);
return data;
}
/*
* Returns true if an usbgecko adapter is found.
*/
static int ug_is_adapter_present(void)
{
if (!ug_io_base)
return 0;
return ug_io_transaction(0x90000000) == 0x04700000;
}
/*
* Returns true if the TX fifo is ready for transmission.
*/
static int ug_is_txfifo_ready(void)
{
return ug_io_transaction(0xc0000000) & 0x04000000;
}
/*
* Tries to transmit a character.
* If the TX fifo is not ready the result is undefined.
*/
static void ug_raw_putc(char ch)
{
ug_io_transaction(0xb0000000 | (ch << 20));
}
/*
* Transmits a character.
* It silently fails if the TX fifo is not ready after a number of retries.
*/
static void ug_putc(char ch)
{
int count = UG_WRITE_ATTEMPTS;
if (!ug_io_base)
return;
if (ch == '\n')
ug_putc('\r');
while (!ug_is_txfifo_ready() && count--)
barrier();
if (count >= 0)
ug_raw_putc(ch);
}
/*
* Returns true if the RX fifo is ready for transmission.
*/
static int ug_is_rxfifo_ready(void)
{
return ug_io_transaction(0xd0000000) & 0x04000000;
}
/*
* Tries to receive a character.
* If a character is unavailable the function returns -1.
*/
static int ug_raw_getc(void)
{
u32 data = ug_io_transaction(0xa0000000);
if (data & 0x08000000)
return (data >> 16) & 0xff;
else
return -1;
}
/*
* Receives a character.
* It fails if the RX fifo is not ready after a number of retries.
*/
static int ug_getc(void)
{
int count = UG_READ_ATTEMPTS;
if (!ug_io_base)
return -1;
while (!ug_is_rxfifo_ready() && count--)
barrier();
return ug_raw_getc();
}
/*
* udbg functions.
*
*/
/*
* Transmits a character.
*/
void ug_udbg_putc(char ch)
{
ug_putc(ch);
}
/*
* Receives a character. Waits until a character is available.
*/
static int ug_udbg_getc(void)
{
int ch;
while ((ch = ug_getc()) == -1)
barrier();
return ch;
}
/*
* Receives a character. If a character is not available, returns -1.
*/
static int ug_udbg_getc_poll(void)
{
if (!ug_is_rxfifo_ready())
return -1;
return ug_getc();
}
/*
* Retrieves and prepares the virtual address needed to access the hardware.
*/
static void __iomem *ug_udbg_setup_exi_io_base(struct device_node *np)
{
void __iomem *exi_io_base = NULL;
phys_addr_t paddr;
const unsigned int *reg;
reg = of_get_property(np, "reg", NULL);
if (reg) {
paddr = of_translate_address(np, reg);
if (paddr)
exi_io_base = ioremap(paddr, reg[1]);
}
return exi_io_base;
}
/*
* Checks if a USB Gecko adapter is inserted in any memory card slot.
*/
static void __iomem *ug_udbg_probe(void __iomem *exi_io_base)
{
int i;
/* look for a usbgecko on memcard slots A and B */
for (i = 0; i < 2; i++) {
ug_io_base = exi_io_base + 0x14 * i;
if (ug_is_adapter_present())
break;
}
if (i == 2)
ug_io_base = NULL;
return ug_io_base;
}
/*
* USB Gecko udbg support initialization.
*/
void __init ug_udbg_init(void)
{
struct device_node *np;
void __iomem *exi_io_base;
if (ug_io_base)
udbg_printf("%s: early -> final\n", __func__);
np = of_find_compatible_node(NULL, NULL, "nintendo,flipper-exi");
if (!np) {
udbg_printf("%s: EXI node not found\n", __func__);
goto done;
}
exi_io_base = ug_udbg_setup_exi_io_base(np);
if (!exi_io_base) {
udbg_printf("%s: failed to setup EXI io base\n", __func__);
goto done;
}
if (!ug_udbg_probe(exi_io_base)) {
udbg_printf("usbgecko_udbg: not found\n");
iounmap(exi_io_base);
} else {
udbg_putc = ug_udbg_putc;
udbg_getc = ug_udbg_getc;
udbg_getc_poll = ug_udbg_getc_poll;
udbg_printf("usbgecko_udbg: ready\n");
}
done:
if (np)
of_node_put(np);
return;
}
#ifdef CONFIG_PPC_EARLY_DEBUG_USBGECKO
static phys_addr_t __init ug_early_grab_io_addr(void)
{
#if defined(CONFIG_GAMECUBE)
return 0x0c000000;
#elif defined(CONFIG_WII)
return 0x0d000000;
#else
#error Invalid platform for USB Gecko based early debugging.
#endif
}
/*
* USB Gecko early debug support initialization for udbg.
*/
void __init udbg_init_usbgecko(void)
{
void __iomem *early_debug_area;
void __iomem *exi_io_base;
/*
* At this point we have a BAT already setup that enables I/O
* to the EXI hardware.
*
* The BAT uses a virtual address range reserved at the fixmap.
* This must match the virtual address configured in
* head_32.S:setup_usbgecko_bat().
*/
early_debug_area = (void __iomem *)__fix_to_virt(FIX_EARLY_DEBUG_BASE);
exi_io_base = early_debug_area + 0x00006800;
/* try to detect a USB Gecko */
if (!ug_udbg_probe(exi_io_base))
return;
/* we found a USB Gecko, load udbg hooks */
udbg_putc = ug_udbg_putc;
udbg_getc = ug_udbg_getc;
udbg_getc_poll = ug_udbg_getc_poll;
/*
* Prepare again the same BAT for MMU_init.
* This allows udbg I/O to continue working after the MMU is
* turned on for real.
* It is safe to continue using the same virtual address as it is
* a reserved fixmap area.
*/
setbat(1, (unsigned long)early_debug_area,
ug_early_grab_io_addr(), 128*1024, PAGE_KERNEL_NCG);
}
#endif /* CONFIG_PPC_EARLY_DEBUG_USBGECKO */
| gpl-2.0 |
OneOfMany07/tty-ng | arch/powerpc/platforms/embedded6xx/usbgecko_udbg.c | 11727 | 6864 | /*
* arch/powerpc/platforms/embedded6xx/usbgecko_udbg.c
*
* udbg serial input/output routines for the USB Gecko adapter.
* Copyright (C) 2008-2009 The GameCube Linux Team
* Copyright (C) 2008,2009 Albert Herranz
*
* 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 <mm/mmu_decl.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/udbg.h>
#include <asm/fixmap.h>
#include "usbgecko_udbg.h"
#define EXI_CLK_32MHZ 5
#define EXI_CSR 0x00
#define EXI_CSR_CLKMASK (0x7<<4)
#define EXI_CSR_CLK_32MHZ (EXI_CLK_32MHZ<<4)
#define EXI_CSR_CSMASK (0x7<<7)
#define EXI_CSR_CS_0 (0x1<<7) /* Chip Select 001 */
#define EXI_CR 0x0c
#define EXI_CR_TSTART (1<<0)
#define EXI_CR_WRITE (1<<2)
#define EXI_CR_READ_WRITE (2<<2)
#define EXI_CR_TLEN(len) (((len)-1)<<4)
#define EXI_DATA 0x10
#define UG_READ_ATTEMPTS 100
#define UG_WRITE_ATTEMPTS 100
static void __iomem *ug_io_base;
/*
* Performs one input/output transaction between the exi host and the usbgecko.
*/
static u32 ug_io_transaction(u32 in)
{
u32 __iomem *csr_reg = ug_io_base + EXI_CSR;
u32 __iomem *data_reg = ug_io_base + EXI_DATA;
u32 __iomem *cr_reg = ug_io_base + EXI_CR;
u32 csr, data, cr;
/* select */
csr = EXI_CSR_CLK_32MHZ | EXI_CSR_CS_0;
out_be32(csr_reg, csr);
/* read/write */
data = in;
out_be32(data_reg, data);
cr = EXI_CR_TLEN(2) | EXI_CR_READ_WRITE | EXI_CR_TSTART;
out_be32(cr_reg, cr);
while (in_be32(cr_reg) & EXI_CR_TSTART)
barrier();
/* deselect */
out_be32(csr_reg, 0);
/* result */
data = in_be32(data_reg);
return data;
}
/*
* Returns true if an usbgecko adapter is found.
*/
static int ug_is_adapter_present(void)
{
if (!ug_io_base)
return 0;
return ug_io_transaction(0x90000000) == 0x04700000;
}
/*
* Returns true if the TX fifo is ready for transmission.
*/
static int ug_is_txfifo_ready(void)
{
return ug_io_transaction(0xc0000000) & 0x04000000;
}
/*
* Tries to transmit a character.
* If the TX fifo is not ready the result is undefined.
*/
static void ug_raw_putc(char ch)
{
ug_io_transaction(0xb0000000 | (ch << 20));
}
/*
* Transmits a character.
* It silently fails if the TX fifo is not ready after a number of retries.
*/
static void ug_putc(char ch)
{
int count = UG_WRITE_ATTEMPTS;
if (!ug_io_base)
return;
if (ch == '\n')
ug_putc('\r');
while (!ug_is_txfifo_ready() && count--)
barrier();
if (count >= 0)
ug_raw_putc(ch);
}
/*
* Returns true if the RX fifo is ready for transmission.
*/
static int ug_is_rxfifo_ready(void)
{
return ug_io_transaction(0xd0000000) & 0x04000000;
}
/*
* Tries to receive a character.
* If a character is unavailable the function returns -1.
*/
static int ug_raw_getc(void)
{
u32 data = ug_io_transaction(0xa0000000);
if (data & 0x08000000)
return (data >> 16) & 0xff;
else
return -1;
}
/*
* Receives a character.
* It fails if the RX fifo is not ready after a number of retries.
*/
static int ug_getc(void)
{
int count = UG_READ_ATTEMPTS;
if (!ug_io_base)
return -1;
while (!ug_is_rxfifo_ready() && count--)
barrier();
return ug_raw_getc();
}
/*
* udbg functions.
*
*/
/*
* Transmits a character.
*/
void ug_udbg_putc(char ch)
{
ug_putc(ch);
}
/*
* Receives a character. Waits until a character is available.
*/
static int ug_udbg_getc(void)
{
int ch;
while ((ch = ug_getc()) == -1)
barrier();
return ch;
}
/*
* Receives a character. If a character is not available, returns -1.
*/
static int ug_udbg_getc_poll(void)
{
if (!ug_is_rxfifo_ready())
return -1;
return ug_getc();
}
/*
* Retrieves and prepares the virtual address needed to access the hardware.
*/
static void __iomem *ug_udbg_setup_exi_io_base(struct device_node *np)
{
void __iomem *exi_io_base = NULL;
phys_addr_t paddr;
const unsigned int *reg;
reg = of_get_property(np, "reg", NULL);
if (reg) {
paddr = of_translate_address(np, reg);
if (paddr)
exi_io_base = ioremap(paddr, reg[1]);
}
return exi_io_base;
}
/*
* Checks if a USB Gecko adapter is inserted in any memory card slot.
*/
static void __iomem *ug_udbg_probe(void __iomem *exi_io_base)
{
int i;
/* look for a usbgecko on memcard slots A and B */
for (i = 0; i < 2; i++) {
ug_io_base = exi_io_base + 0x14 * i;
if (ug_is_adapter_present())
break;
}
if (i == 2)
ug_io_base = NULL;
return ug_io_base;
}
/*
* USB Gecko udbg support initialization.
*/
void __init ug_udbg_init(void)
{
struct device_node *np;
void __iomem *exi_io_base;
if (ug_io_base)
udbg_printf("%s: early -> final\n", __func__);
np = of_find_compatible_node(NULL, NULL, "nintendo,flipper-exi");
if (!np) {
udbg_printf("%s: EXI node not found\n", __func__);
goto done;
}
exi_io_base = ug_udbg_setup_exi_io_base(np);
if (!exi_io_base) {
udbg_printf("%s: failed to setup EXI io base\n", __func__);
goto done;
}
if (!ug_udbg_probe(exi_io_base)) {
udbg_printf("usbgecko_udbg: not found\n");
iounmap(exi_io_base);
} else {
udbg_putc = ug_udbg_putc;
udbg_getc = ug_udbg_getc;
udbg_getc_poll = ug_udbg_getc_poll;
udbg_printf("usbgecko_udbg: ready\n");
}
done:
if (np)
of_node_put(np);
return;
}
#ifdef CONFIG_PPC_EARLY_DEBUG_USBGECKO
static phys_addr_t __init ug_early_grab_io_addr(void)
{
#if defined(CONFIG_GAMECUBE)
return 0x0c000000;
#elif defined(CONFIG_WII)
return 0x0d000000;
#else
#error Invalid platform for USB Gecko based early debugging.
#endif
}
/*
* USB Gecko early debug support initialization for udbg.
*/
void __init udbg_init_usbgecko(void)
{
void __iomem *early_debug_area;
void __iomem *exi_io_base;
/*
* At this point we have a BAT already setup that enables I/O
* to the EXI hardware.
*
* The BAT uses a virtual address range reserved at the fixmap.
* This must match the virtual address configured in
* head_32.S:setup_usbgecko_bat().
*/
early_debug_area = (void __iomem *)__fix_to_virt(FIX_EARLY_DEBUG_BASE);
exi_io_base = early_debug_area + 0x00006800;
/* try to detect a USB Gecko */
if (!ug_udbg_probe(exi_io_base))
return;
/* we found a USB Gecko, load udbg hooks */
udbg_putc = ug_udbg_putc;
udbg_getc = ug_udbg_getc;
udbg_getc_poll = ug_udbg_getc_poll;
/*
* Prepare again the same BAT for MMU_init.
* This allows udbg I/O to continue working after the MMU is
* turned on for real.
* It is safe to continue using the same virtual address as it is
* a reserved fixmap area.
*/
setbat(1, (unsigned long)early_debug_area,
ug_early_grab_io_addr(), 128*1024, PAGE_KERNEL_NCG);
}
#endif /* CONFIG_PPC_EARLY_DEBUG_USBGECKO */
| gpl-2.0 |
geiti94/NEMESIS_KERNEL_N5 | drivers/usb/core/hcd-pci.c | 208 | 17857 | /*
* (C) Copyright David Brownell 2000-2002
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <asm/io.h>
#include <asm/irq.h>
#ifdef CONFIG_PPC_PMAC
#include <asm/machdep.h>
#include <asm/pmac_feature.h>
#include <asm/pci-bridge.h>
#include <asm/prom.h>
#endif
#include "usb.h"
/* PCI-based HCs are common, but plenty of non-PCI HCs are used too */
/*
* Coordinate handoffs between EHCI and companion controllers
* during EHCI probing and system resume.
*/
static DECLARE_RWSEM(companions_rwsem);
#define CL_UHCI PCI_CLASS_SERIAL_USB_UHCI
#define CL_OHCI PCI_CLASS_SERIAL_USB_OHCI
#define CL_EHCI PCI_CLASS_SERIAL_USB_EHCI
static inline int is_ohci_or_uhci(struct pci_dev *pdev)
{
return pdev->class == CL_OHCI || pdev->class == CL_UHCI;
}
typedef void (*companion_fn)(struct pci_dev *pdev, struct usb_hcd *hcd,
struct pci_dev *companion, struct usb_hcd *companion_hcd);
/* Iterate over PCI devices in the same slot as pdev and call fn for each */
static void for_each_companion(struct pci_dev *pdev, struct usb_hcd *hcd,
companion_fn fn)
{
struct pci_dev *companion;
struct usb_hcd *companion_hcd;
unsigned int slot = PCI_SLOT(pdev->devfn);
/*
* Iterate through other PCI functions in the same slot.
* If the function's drvdata isn't set then it isn't bound to
* a USB host controller driver, so skip it.
*/
companion = NULL;
for_each_pci_dev(companion) {
if (companion->bus != pdev->bus ||
PCI_SLOT(companion->devfn) != slot)
continue;
/*
* Companion device should be either UHCI,OHCI or EHCI host
* controller, otherwise skip.
*/
if (companion->class != CL_UHCI && companion->class != CL_OHCI &&
companion->class != CL_EHCI)
continue;
companion_hcd = pci_get_drvdata(companion);
if (!companion_hcd || !companion_hcd->self.root_hub)
continue;
fn(pdev, hcd, companion, companion_hcd);
}
}
/*
* We're about to add an EHCI controller, which will unceremoniously grab
* all the port connections away from its companions. To prevent annoying
* error messages, lock the companion's root hub and gracefully unconfigure
* it beforehand. Leave it locked until the EHCI controller is all set.
*/
static void ehci_pre_add(struct pci_dev *pdev, struct usb_hcd *hcd,
struct pci_dev *companion, struct usb_hcd *companion_hcd)
{
struct usb_device *udev;
if (is_ohci_or_uhci(companion)) {
udev = companion_hcd->self.root_hub;
usb_lock_device(udev);
usb_set_configuration(udev, 0);
}
}
/*
* Adding the EHCI controller has either succeeded or failed. Set the
* companion pointer accordingly, and in either case, reconfigure and
* unlock the root hub.
*/
static void ehci_post_add(struct pci_dev *pdev, struct usb_hcd *hcd,
struct pci_dev *companion, struct usb_hcd *companion_hcd)
{
struct usb_device *udev;
if (is_ohci_or_uhci(companion)) {
if (dev_get_drvdata(&pdev->dev)) { /* Succeeded */
dev_dbg(&pdev->dev, "HS companion for %s\n",
dev_name(&companion->dev));
companion_hcd->self.hs_companion = &hcd->self;
}
udev = companion_hcd->self.root_hub;
usb_set_configuration(udev, 1);
usb_unlock_device(udev);
}
}
/*
* We just added a non-EHCI controller. Find the EHCI controller to
* which it is a companion, and store a pointer to the bus structure.
*/
static void non_ehci_add(struct pci_dev *pdev, struct usb_hcd *hcd,
struct pci_dev *companion, struct usb_hcd *companion_hcd)
{
if (is_ohci_or_uhci(pdev) && companion->class == CL_EHCI) {
dev_dbg(&pdev->dev, "FS/LS companion for %s\n",
dev_name(&companion->dev));
hcd->self.hs_companion = &companion_hcd->self;
}
}
/* We are removing an EHCI controller. Clear the companions' pointers. */
static void ehci_remove(struct pci_dev *pdev, struct usb_hcd *hcd,
struct pci_dev *companion, struct usb_hcd *companion_hcd)
{
if (is_ohci_or_uhci(companion))
companion_hcd->self.hs_companion = NULL;
}
#ifdef CONFIG_PM
/* An EHCI controller must wait for its companions before resuming. */
static void ehci_wait_for_companions(struct pci_dev *pdev, struct usb_hcd *hcd,
struct pci_dev *companion, struct usb_hcd *companion_hcd)
{
if (is_ohci_or_uhci(companion))
device_pm_wait_for_dev(&pdev->dev, &companion->dev);
}
#endif /* CONFIG_PM */
/*-------------------------------------------------------------------------*/
/* configure so an HC device and id are always provided */
/* always called with process context; sleeping is OK */
/**
* usb_hcd_pci_probe - initialize PCI-based HCDs
* @dev: USB Host Controller being probed
* @id: pci hotplug id connecting controller to HCD framework
* Context: !in_interrupt()
*
* Allocates basic PCI resources for this USB host controller, and
* then invokes the start() method for the HCD associated with it
* through the hotplug entry's driver_data.
*
* Store this function in the HCD's struct pci_driver as probe().
*/
int usb_hcd_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
struct hc_driver *driver;
struct usb_hcd *hcd;
int retval;
int hcd_irq = 0;
if (usb_disabled())
return -ENODEV;
if (!id)
return -EINVAL;
driver = (struct hc_driver *)id->driver_data;
if (!driver)
return -EINVAL;
if (pci_enable_device(dev) < 0)
return -ENODEV;
dev->current_state = PCI_D0;
/*
* The xHCI driver has its own irq management
* make sure irq setup is not touched for xhci in generic hcd code
*/
if ((driver->flags & HCD_MASK) != HCD_USB3) {
if (!dev->irq) {
dev_err(&dev->dev,
"Found HC with no IRQ. Check BIOS/PCI %s setup!\n",
pci_name(dev));
retval = -ENODEV;
goto disable_pci;
}
hcd_irq = dev->irq;
}
hcd = usb_create_hcd(driver, &dev->dev, pci_name(dev));
if (!hcd) {
retval = -ENOMEM;
goto disable_pci;
}
if (driver->flags & HCD_MEMORY) {
/* EHCI, OHCI */
hcd->rsrc_start = pci_resource_start(dev, 0);
hcd->rsrc_len = pci_resource_len(dev, 0);
if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len,
driver->description)) {
dev_dbg(&dev->dev, "controller already in use\n");
retval = -EBUSY;
goto put_hcd;
}
hcd->regs = ioremap_nocache(hcd->rsrc_start, hcd->rsrc_len);
if (hcd->regs == NULL) {
dev_dbg(&dev->dev, "error mapping memory\n");
retval = -EFAULT;
goto release_mem_region;
}
} else {
/* UHCI */
int region;
for (region = 0; region < PCI_ROM_RESOURCE; region++) {
if (!(pci_resource_flags(dev, region) &
IORESOURCE_IO))
continue;
hcd->rsrc_start = pci_resource_start(dev, region);
hcd->rsrc_len = pci_resource_len(dev, region);
if (request_region(hcd->rsrc_start, hcd->rsrc_len,
driver->description))
break;
}
if (region == PCI_ROM_RESOURCE) {
dev_dbg(&dev->dev, "no i/o regions available\n");
retval = -EBUSY;
goto put_hcd;
}
}
pci_set_master(dev);
/* Note: dev_set_drvdata must be called while holding the rwsem */
if (dev->class == CL_EHCI) {
down_write(&companions_rwsem);
dev_set_drvdata(&dev->dev, hcd);
for_each_companion(dev, hcd, ehci_pre_add);
retval = usb_add_hcd(hcd, hcd_irq, IRQF_SHARED);
if (retval != 0)
dev_set_drvdata(&dev->dev, NULL);
for_each_companion(dev, hcd, ehci_post_add);
up_write(&companions_rwsem);
} else {
down_read(&companions_rwsem);
dev_set_drvdata(&dev->dev, hcd);
retval = usb_add_hcd(hcd, hcd_irq, IRQF_SHARED);
if (retval != 0)
dev_set_drvdata(&dev->dev, NULL);
else
for_each_companion(dev, hcd, non_ehci_add);
up_read(&companions_rwsem);
}
if (retval != 0)
goto unmap_registers;
if (pci_dev_run_wake(dev))
pm_runtime_put_noidle(&dev->dev);
return retval;
unmap_registers:
if (driver->flags & HCD_MEMORY) {
iounmap(hcd->regs);
release_mem_region:
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
} else
release_region(hcd->rsrc_start, hcd->rsrc_len);
put_hcd:
usb_put_hcd(hcd);
disable_pci:
pci_disable_device(dev);
dev_err(&dev->dev, "init %s fail, %d\n", pci_name(dev), retval);
return retval;
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_probe);
/* may be called without controller electrically present */
/* may be called with controller, bus, and devices active */
/**
* usb_hcd_pci_remove - shutdown processing for PCI-based HCDs
* @dev: USB Host Controller being removed
* Context: !in_interrupt()
*
* Reverses the effect of usb_hcd_pci_probe(), first invoking
* the HCD's stop() method. It is always called from a thread
* context, normally "rmmod", "apmd", or something similar.
*
* Store this function in the HCD's struct pci_driver as remove().
*/
void usb_hcd_pci_remove(struct pci_dev *dev)
{
struct usb_hcd *hcd;
hcd = pci_get_drvdata(dev);
if (!hcd)
return;
if (pci_dev_run_wake(dev))
pm_runtime_get_noresume(&dev->dev);
/* Fake an interrupt request in order to give the driver a chance
* to test whether the controller hardware has been removed (e.g.,
* cardbus physical eject).
*/
local_irq_disable();
usb_hcd_irq(0, hcd);
local_irq_enable();
/* Note: dev_set_drvdata must be called while holding the rwsem */
if (dev->class == CL_EHCI) {
down_write(&companions_rwsem);
for_each_companion(dev, hcd, ehci_remove);
usb_remove_hcd(hcd);
dev_set_drvdata(&dev->dev, NULL);
up_write(&companions_rwsem);
} else {
/* Not EHCI; just clear the companion pointer */
down_read(&companions_rwsem);
hcd->self.hs_companion = NULL;
usb_remove_hcd(hcd);
dev_set_drvdata(&dev->dev, NULL);
up_read(&companions_rwsem);
}
if (hcd->driver->flags & HCD_MEMORY) {
iounmap(hcd->regs);
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
} else {
release_region(hcd->rsrc_start, hcd->rsrc_len);
}
usb_put_hcd(hcd);
pci_disable_device(dev);
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_remove);
/**
* usb_hcd_pci_shutdown - shutdown host controller
* @dev: USB Host Controller being shutdown
*/
void usb_hcd_pci_shutdown(struct pci_dev *dev)
{
struct usb_hcd *hcd;
hcd = pci_get_drvdata(dev);
if (!hcd)
return;
if (test_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags) &&
hcd->driver->shutdown) {
hcd->driver->shutdown(hcd);
pci_disable_device(dev);
}
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_shutdown);
#ifdef CONFIG_PM
#ifdef CONFIG_PPC_PMAC
static void powermac_set_asic(struct pci_dev *pci_dev, int enable)
{
/* Enanble or disable ASIC clocks for USB */
if (machine_is(powermac)) {
struct device_node *of_node;
of_node = pci_device_to_OF_node(pci_dev);
if (of_node)
pmac_call_feature(PMAC_FTR_USB_ENABLE,
of_node, 0, enable);
}
}
#else
static inline void powermac_set_asic(struct pci_dev *pci_dev, int enable)
{}
#endif /* CONFIG_PPC_PMAC */
static int check_root_hub_suspended(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
if (HCD_RH_RUNNING(hcd)) {
dev_warn(dev, "Root hub is not suspended\n");
return -EBUSY;
}
if (hcd->shared_hcd) {
hcd = hcd->shared_hcd;
if (HCD_RH_RUNNING(hcd)) {
dev_warn(dev, "Secondary root hub is not suspended\n");
return -EBUSY;
}
}
return 0;
}
#if defined(CONFIG_PM_SLEEP) || defined(CONFIG_PM_RUNTIME)
static int suspend_common(struct device *dev, bool do_wakeup)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
/* Root hub suspend should have stopped all downstream traffic,
* and all bus master traffic. And done so for both the interface
* and the stub usb_device (which we check here). But maybe it
* didn't; writing sysfs power/state files ignores such rules...
*/
retval = check_root_hub_suspended(dev);
if (retval)
return retval;
if (hcd->driver->pci_suspend && !HCD_DEAD(hcd)) {
/* Optimization: Don't suspend if a root-hub wakeup is
* pending and it would cause the HCD to wake up anyway.
*/
if (do_wakeup && HCD_WAKEUP_PENDING(hcd))
return -EBUSY;
if (do_wakeup && hcd->shared_hcd &&
HCD_WAKEUP_PENDING(hcd->shared_hcd))
return -EBUSY;
retval = hcd->driver->pci_suspend(hcd, do_wakeup);
suspend_report_result(hcd->driver->pci_suspend, retval);
/* Check again in case wakeup raced with pci_suspend */
if ((retval == 0 && do_wakeup && HCD_WAKEUP_PENDING(hcd)) ||
(retval == 0 && do_wakeup && hcd->shared_hcd &&
HCD_WAKEUP_PENDING(hcd->shared_hcd))) {
if (hcd->driver->pci_resume)
hcd->driver->pci_resume(hcd, false);
retval = -EBUSY;
}
if (retval)
return retval;
}
/* If MSI-X is enabled, the driver will have synchronized all vectors
* in pci_suspend(). If MSI or legacy PCI is enabled, that will be
* synchronized here.
*/
if (!hcd->msix_enabled)
synchronize_irq(pci_dev->irq);
/* Downstream ports from this root hub should already be quiesced, so
* there will be no DMA activity. Now we can shut down the upstream
* link (except maybe for PME# resume signaling). We'll enter a
* low power state during suspend_noirq, if the hardware allows.
*/
pci_disable_device(pci_dev);
return retval;
}
static int resume_common(struct device *dev, int event)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
if (HCD_RH_RUNNING(hcd) ||
(hcd->shared_hcd &&
HCD_RH_RUNNING(hcd->shared_hcd))) {
dev_dbg(dev, "can't resume, not suspended!\n");
return 0;
}
retval = pci_enable_device(pci_dev);
if (retval < 0) {
dev_err(dev, "can't re-enable after resume, %d!\n", retval);
return retval;
}
pci_set_master(pci_dev);
if (hcd->driver->pci_resume && !HCD_DEAD(hcd)) {
/*
* Only EHCI controllers have to wait for their companions.
* No locking is needed because PCI controller drivers do not
* get unbound during system resume.
*/
if (pci_dev->class == CL_EHCI && event != PM_EVENT_AUTO_RESUME)
for_each_companion(pci_dev, hcd,
ehci_wait_for_companions);
retval = hcd->driver->pci_resume(hcd,
event == PM_EVENT_RESTORE);
if (retval) {
dev_err(dev, "PCI post-resume error %d!\n", retval);
if (hcd->shared_hcd)
usb_hc_died(hcd->shared_hcd);
usb_hc_died(hcd);
}
}
return retval;
}
#endif /* SLEEP || RUNTIME */
#ifdef CONFIG_PM_SLEEP
static int hcd_pci_suspend(struct device *dev)
{
return suspend_common(dev, device_may_wakeup(dev));
}
static int hcd_pci_suspend_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
retval = check_root_hub_suspended(dev);
if (retval)
return retval;
pci_save_state(pci_dev);
/* If the root hub is dead rather than suspended, disallow remote
* wakeup. usb_hc_died() should ensure that both hosts are marked as
* dying, so we only need to check the primary roothub.
*/
if (HCD_DEAD(hcd))
device_set_wakeup_enable(dev, 0);
dev_dbg(dev, "wakeup: %d\n", device_may_wakeup(dev));
/* Possibly enable remote wakeup,
* choose the appropriate low-power state, and go to that state.
*/
retval = pci_prepare_to_sleep(pci_dev);
if (retval == -EIO) { /* Low-power not supported */
dev_dbg(dev, "--> PCI D0 legacy\n");
retval = 0;
} else if (retval == 0) {
dev_dbg(dev, "--> PCI %s\n",
pci_power_name(pci_dev->current_state));
} else {
suspend_report_result(pci_prepare_to_sleep, retval);
return retval;
}
powermac_set_asic(pci_dev, 0);
return retval;
}
static int hcd_pci_resume_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
powermac_set_asic(pci_dev, 1);
/* Go back to D0 and disable remote wakeup */
pci_back_from_sleep(pci_dev);
return 0;
}
static int hcd_pci_resume(struct device *dev)
{
return resume_common(dev, PM_EVENT_RESUME);
}
static int hcd_pci_restore(struct device *dev)
{
return resume_common(dev, PM_EVENT_RESTORE);
}
#else
#define hcd_pci_suspend NULL
#define hcd_pci_suspend_noirq NULL
#define hcd_pci_resume_noirq NULL
#define hcd_pci_resume NULL
#define hcd_pci_restore NULL
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM_RUNTIME
static int hcd_pci_runtime_suspend(struct device *dev)
{
int retval;
retval = suspend_common(dev, true);
if (retval == 0)
powermac_set_asic(to_pci_dev(dev), 0);
dev_dbg(dev, "hcd_pci_runtime_suspend: %d\n", retval);
return retval;
}
static int hcd_pci_runtime_resume(struct device *dev)
{
int retval;
powermac_set_asic(to_pci_dev(dev), 1);
retval = resume_common(dev, PM_EVENT_AUTO_RESUME);
dev_dbg(dev, "hcd_pci_runtime_resume: %d\n", retval);
return retval;
}
#else
#define hcd_pci_runtime_suspend NULL
#define hcd_pci_runtime_resume NULL
#endif /* CONFIG_PM_RUNTIME */
const struct dev_pm_ops usb_hcd_pci_pm_ops = {
.suspend = hcd_pci_suspend,
.suspend_noirq = hcd_pci_suspend_noirq,
.resume_noirq = hcd_pci_resume_noirq,
.resume = hcd_pci_resume,
.freeze = check_root_hub_suspended,
.freeze_noirq = check_root_hub_suspended,
.thaw_noirq = NULL,
.thaw = NULL,
.poweroff = hcd_pci_suspend,
.poweroff_noirq = hcd_pci_suspend_noirq,
.restore_noirq = hcd_pci_resume_noirq,
.restore = hcd_pci_restore,
.runtime_suspend = hcd_pci_runtime_suspend,
.runtime_resume = hcd_pci_runtime_resume,
};
EXPORT_SYMBOL_GPL(usb_hcd_pci_pm_ops);
#endif /* CONFIG_PM */
| gpl-2.0 |
karandpr/Doppler3ICS | tools/perf/builtin-stat.c | 464 | 12320 | /*
* builtin-stat.c
*
* Builtin stat command: Give a precise performance counters summary
* overview about any workload, CPU or specific PID.
*
* Sample output:
$ perf stat ~/hackbench 10
Time: 0.104
Performance counter stats for '/home/mingo/hackbench':
1255.538611 task clock ticks # 10.143 CPU utilization factor
54011 context switches # 0.043 M/sec
385 CPU migrations # 0.000 M/sec
17755 pagefaults # 0.014 M/sec
3808323185 CPU cycles # 3033.219 M/sec
1575111190 instructions # 1254.530 M/sec
17367895 cache references # 13.833 M/sec
7674421 cache misses # 6.112 M/sec
Wall-clock time elapsed: 123.786620 msecs
*
* Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
*
* Improvements and fixes by:
*
* Arjan van de Ven <arjan@linux.intel.com>
* Yanmin Zhang <yanmin.zhang@intel.com>
* Wu Fengguang <fengguang.wu@intel.com>
* Mike Galbraith <efault@gmx.de>
* Paul Mackerras <paulus@samba.org>
* Jaswinder Singh Rajput <jaswinder@kernel.org>
*
* Released under the GPL v2. (and only v2, not any later version)
*/
#include "perf.h"
#include "builtin.h"
#include "util/util.h"
#include "util/parse-options.h"
#include "util/parse-events.h"
#include "util/event.h"
#include "util/debug.h"
#include <sys/prctl.h>
#include <math.h>
static struct perf_event_attr default_attrs[] = {
{ .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
{ .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES},
{ .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
{ .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
{ .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
{ .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
{ .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CACHE_REFERENCES},
{ .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CACHE_MISSES },
};
static int system_wide = 0;
static unsigned int nr_cpus = 0;
static int run_idx = 0;
static int run_count = 1;
static int inherit = 1;
static int scale = 1;
static pid_t target_pid = -1;
static pid_t child_pid = -1;
static int null_run = 0;
static int fd[MAX_NR_CPUS][MAX_COUNTERS];
static int event_scaled[MAX_COUNTERS];
struct stats
{
double n, mean, M2;
};
static void update_stats(struct stats *stats, u64 val)
{
double delta;
stats->n++;
delta = val - stats->mean;
stats->mean += delta / stats->n;
stats->M2 += delta*(val - stats->mean);
}
static double avg_stats(struct stats *stats)
{
return stats->mean;
}
/*
* http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
*
* (\Sum n_i^2) - ((\Sum n_i)^2)/n
* s^2 = -------------------------------
* n - 1
*
* http://en.wikipedia.org/wiki/Stddev
*
* The std dev of the mean is related to the std dev by:
*
* s
* s_mean = -------
* sqrt(n)
*
*/
static double stddev_stats(struct stats *stats)
{
double variance = stats->M2 / (stats->n - 1);
double variance_mean = variance / stats->n;
return sqrt(variance_mean);
}
struct stats event_res_stats[MAX_COUNTERS][3];
struct stats runtime_nsecs_stats;
struct stats walltime_nsecs_stats;
struct stats runtime_cycles_stats;
#define MATCH_EVENT(t, c, counter) \
(attrs[counter].type == PERF_TYPE_##t && \
attrs[counter].config == PERF_COUNT_##c)
#define ERR_PERF_OPEN \
"Error: counter %d, sys_perf_event_open() syscall returned with %d (%s)\n"
static void create_perf_stat_counter(int counter, int pid)
{
struct perf_event_attr *attr = attrs + counter;
if (scale)
attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
PERF_FORMAT_TOTAL_TIME_RUNNING;
if (system_wide) {
unsigned int cpu;
for (cpu = 0; cpu < nr_cpus; cpu++) {
fd[cpu][counter] = sys_perf_event_open(attr, -1, cpu, -1, 0);
if (fd[cpu][counter] < 0 && verbose)
fprintf(stderr, ERR_PERF_OPEN, counter,
fd[cpu][counter], strerror(errno));
}
} else {
attr->inherit = inherit;
attr->disabled = 1;
attr->enable_on_exec = 1;
fd[0][counter] = sys_perf_event_open(attr, pid, -1, -1, 0);
if (fd[0][counter] < 0 && verbose)
fprintf(stderr, ERR_PERF_OPEN, counter,
fd[0][counter], strerror(errno));
}
}
/*
* Does the counter have nsecs as a unit?
*/
static inline int nsec_counter(int counter)
{
if (MATCH_EVENT(SOFTWARE, SW_CPU_CLOCK, counter) ||
MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter))
return 1;
return 0;
}
/*
* Read out the results of a single counter:
*/
static void read_counter(int counter)
{
u64 count[3], single_count[3];
unsigned int cpu;
size_t res, nv;
int scaled;
int i;
count[0] = count[1] = count[2] = 0;
nv = scale ? 3 : 1;
for (cpu = 0; cpu < nr_cpus; cpu++) {
if (fd[cpu][counter] < 0)
continue;
res = read(fd[cpu][counter], single_count, nv * sizeof(u64));
assert(res == nv * sizeof(u64));
close(fd[cpu][counter]);
fd[cpu][counter] = -1;
count[0] += single_count[0];
if (scale) {
count[1] += single_count[1];
count[2] += single_count[2];
}
}
scaled = 0;
if (scale) {
if (count[2] == 0) {
event_scaled[counter] = -1;
count[0] = 0;
return;
}
if (count[2] < count[1]) {
event_scaled[counter] = 1;
count[0] = (unsigned long long)
((double)count[0] * count[1] / count[2] + 0.5);
}
}
for (i = 0; i < 3; i++)
update_stats(&event_res_stats[counter][i], count[i]);
if (verbose) {
fprintf(stderr, "%s: %Ld %Ld %Ld\n", event_name(counter),
count[0], count[1], count[2]);
}
/*
* Save the full runtime - to allow normalization during printout:
*/
if (MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter))
update_stats(&runtime_nsecs_stats, count[0]);
if (MATCH_EVENT(HARDWARE, HW_CPU_CYCLES, counter))
update_stats(&runtime_cycles_stats, count[0]);
}
static int run_perf_stat(int argc __used, const char **argv)
{
unsigned long long t0, t1;
int status = 0;
int counter;
int pid;
int child_ready_pipe[2], go_pipe[2];
char buf;
if (!system_wide)
nr_cpus = 1;
if (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0) {
perror("failed to create pipes");
exit(1);
}
if ((pid = fork()) < 0)
perror("failed to fork");
if (!pid) {
close(child_ready_pipe[0]);
close(go_pipe[1]);
fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
/*
* Do a dummy execvp to get the PLT entry resolved,
* so we avoid the resolver overhead on the real
* execvp call.
*/
execvp("", (char **)argv);
/*
* Tell the parent we're ready to go
*/
close(child_ready_pipe[1]);
/*
* Wait until the parent tells us to go.
*/
if (read(go_pipe[0], &buf, 1) == -1)
perror("unable to read pipe");
execvp(argv[0], (char **)argv);
perror(argv[0]);
exit(-1);
}
child_pid = pid;
/*
* Wait for the child to be ready to exec.
*/
close(child_ready_pipe[1]);
close(go_pipe[0]);
if (read(child_ready_pipe[0], &buf, 1) == -1)
perror("unable to read pipe");
close(child_ready_pipe[0]);
for (counter = 0; counter < nr_counters; counter++)
create_perf_stat_counter(counter, pid);
/*
* Enable counters and exec the command:
*/
t0 = rdclock();
close(go_pipe[1]);
wait(&status);
t1 = rdclock();
update_stats(&walltime_nsecs_stats, t1 - t0);
for (counter = 0; counter < nr_counters; counter++)
read_counter(counter);
return WEXITSTATUS(status);
}
static void print_noise(int counter, double avg)
{
if (run_count == 1)
return;
fprintf(stderr, " ( +- %7.3f%% )",
100 * stddev_stats(&event_res_stats[counter][0]) / avg);
}
static void nsec_printout(int counter, double avg)
{
double msecs = avg / 1e6;
fprintf(stderr, " %14.6f %-24s", msecs, event_name(counter));
if (MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter)) {
fprintf(stderr, " # %10.3f CPUs ",
avg / avg_stats(&walltime_nsecs_stats));
}
}
static void abs_printout(int counter, double avg)
{
double total, ratio = 0.0;
fprintf(stderr, " %14.0f %-24s", avg, event_name(counter));
if (MATCH_EVENT(HARDWARE, HW_INSTRUCTIONS, counter)) {
total = avg_stats(&runtime_cycles_stats);
if (total)
ratio = avg / total;
fprintf(stderr, " # %10.3f IPC ", ratio);
} else {
total = avg_stats(&runtime_nsecs_stats);
if (total)
ratio = 1000.0 * avg / total;
fprintf(stderr, " # %10.3f M/sec", ratio);
}
}
/*
* Print out the results of a single counter:
*/
static void print_counter(int counter)
{
double avg = avg_stats(&event_res_stats[counter][0]);
int scaled = event_scaled[counter];
if (scaled == -1) {
fprintf(stderr, " %14s %-24s\n",
"<not counted>", event_name(counter));
return;
}
if (nsec_counter(counter))
nsec_printout(counter, avg);
else
abs_printout(counter, avg);
print_noise(counter, avg);
if (scaled) {
double avg_enabled, avg_running;
avg_enabled = avg_stats(&event_res_stats[counter][1]);
avg_running = avg_stats(&event_res_stats[counter][2]);
fprintf(stderr, " (scaled from %.2f%%)",
100 * avg_running / avg_enabled);
}
fprintf(stderr, "\n");
}
static void print_stat(int argc, const char **argv)
{
int i, counter;
fflush(stdout);
fprintf(stderr, "\n");
fprintf(stderr, " Performance counter stats for \'%s", argv[0]);
for (i = 1; i < argc; i++)
fprintf(stderr, " %s", argv[i]);
fprintf(stderr, "\'");
if (run_count > 1)
fprintf(stderr, " (%d runs)", run_count);
fprintf(stderr, ":\n\n");
for (counter = 0; counter < nr_counters; counter++)
print_counter(counter);
fprintf(stderr, "\n");
fprintf(stderr, " %14.9f seconds time elapsed",
avg_stats(&walltime_nsecs_stats)/1e9);
if (run_count > 1) {
fprintf(stderr, " ( +- %7.3f%% )",
100*stddev_stats(&walltime_nsecs_stats) /
avg_stats(&walltime_nsecs_stats));
}
fprintf(stderr, "\n\n");
}
static volatile int signr = -1;
static void skip_signal(int signo)
{
signr = signo;
}
static void sig_atexit(void)
{
if (child_pid != -1)
kill(child_pid, SIGTERM);
if (signr == -1)
return;
signal(signr, SIG_DFL);
kill(getpid(), signr);
}
static const char * const stat_usage[] = {
"perf stat [<options>] <command>",
NULL
};
static const struct option options[] = {
OPT_CALLBACK('e', "event", NULL, "event",
"event selector. use 'perf list' to list available events",
parse_events),
OPT_BOOLEAN('i', "inherit", &inherit,
"child tasks inherit counters"),
OPT_INTEGER('p', "pid", &target_pid,
"stat events on existing pid"),
OPT_BOOLEAN('a', "all-cpus", &system_wide,
"system-wide collection from all CPUs"),
OPT_BOOLEAN('c', "scale", &scale,
"scale/normalize counters"),
OPT_BOOLEAN('v', "verbose", &verbose,
"be more verbose (show counter open errors, etc)"),
OPT_INTEGER('r', "repeat", &run_count,
"repeat command and print average + stddev (max: 100)"),
OPT_BOOLEAN('n', "null", &null_run,
"null run - dont start any counters"),
OPT_END()
};
int cmd_stat(int argc, const char **argv, const char *prefix __used)
{
int status;
argc = parse_options(argc, argv, options, stat_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
if (!argc)
usage_with_options(stat_usage, options);
if (run_count <= 0)
usage_with_options(stat_usage, options);
/* Set attrs and nr_counters if no event is selected and !null_run */
if (!null_run && !nr_counters) {
memcpy(attrs, default_attrs, sizeof(default_attrs));
nr_counters = ARRAY_SIZE(default_attrs);
}
nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
assert(nr_cpus <= MAX_NR_CPUS);
assert((int)nr_cpus >= 0);
/*
* We dont want to block the signals - that would cause
* child tasks to inherit that and Ctrl-C would not work.
* What we want is for Ctrl-C to work in the exec()-ed
* task, but being ignored by perf stat itself:
*/
atexit(sig_atexit);
signal(SIGINT, skip_signal);
signal(SIGALRM, skip_signal);
signal(SIGABRT, skip_signal);
status = 0;
for (run_idx = 0; run_idx < run_count; run_idx++) {
if (run_count != 1 && verbose)
fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
status = run_perf_stat(argc, argv);
}
print_stat(argc, argv);
return status;
}
| gpl-2.0 |
Apollo5520/s9-s5pv210-kernel | drivers/acpi/apei/erst.c | 720 | 19973 | /*
* APEI Error Record Serialization Table support
*
* ERST is a way provided by APEI to save and retrieve hardware error
* infomation to and from a persistent store.
*
* For more information about ERST, please refer to ACPI Specification
* version 4.0, section 17.4.
*
* Copyright 2010 Intel Corp.
* Author: Huang Ying <ying.huang@intel.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/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/acpi.h>
#include <linux/uaccess.h>
#include <linux/cper.h>
#include <linux/nmi.h>
#include <linux/hardirq.h>
#include <acpi/apei.h>
#include "apei-internal.h"
#define ERST_PFX "ERST: "
/* ERST command status */
#define ERST_STATUS_SUCCESS 0x0
#define ERST_STATUS_NOT_ENOUGH_SPACE 0x1
#define ERST_STATUS_HARDWARE_NOT_AVAILABLE 0x2
#define ERST_STATUS_FAILED 0x3
#define ERST_STATUS_RECORD_STORE_EMPTY 0x4
#define ERST_STATUS_RECORD_NOT_FOUND 0x5
#define ERST_TAB_ENTRY(tab) \
((struct acpi_whea_header *)((char *)(tab) + \
sizeof(struct acpi_table_erst)))
#define SPIN_UNIT 100 /* 100ns */
/* Firmware should respond within 1 miliseconds */
#define FIRMWARE_TIMEOUT (1 * NSEC_PER_MSEC)
#define FIRMWARE_MAX_STALL 50 /* 50us */
int erst_disable;
EXPORT_SYMBOL_GPL(erst_disable);
static struct acpi_table_erst *erst_tab;
/* ERST Error Log Address Range atrributes */
#define ERST_RANGE_RESERVED 0x0001
#define ERST_RANGE_NVRAM 0x0002
#define ERST_RANGE_SLOW 0x0004
/*
* ERST Error Log Address Range, used as buffer for reading/writing
* error records.
*/
static struct erst_erange {
u64 base;
u64 size;
void __iomem *vaddr;
u32 attr;
} erst_erange;
/*
* Prevent ERST interpreter to run simultaneously, because the
* corresponding firmware implementation may not work properly when
* invoked simultaneously.
*
* It is used to provide exclusive accessing for ERST Error Log
* Address Range too.
*/
static DEFINE_SPINLOCK(erst_lock);
static inline int erst_errno(int command_status)
{
switch (command_status) {
case ERST_STATUS_SUCCESS:
return 0;
case ERST_STATUS_HARDWARE_NOT_AVAILABLE:
return -ENODEV;
case ERST_STATUS_NOT_ENOUGH_SPACE:
return -ENOSPC;
case ERST_STATUS_RECORD_STORE_EMPTY:
case ERST_STATUS_RECORD_NOT_FOUND:
return -ENOENT;
default:
return -EINVAL;
}
}
static int erst_timedout(u64 *t, u64 spin_unit)
{
if ((s64)*t < spin_unit) {
pr_warning(FW_WARN ERST_PFX
"Firmware does not respond in time\n");
return 1;
}
*t -= spin_unit;
ndelay(spin_unit);
touch_nmi_watchdog();
return 0;
}
static int erst_exec_load_var1(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
return __apei_exec_read_register(entry, &ctx->var1);
}
static int erst_exec_load_var2(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
return __apei_exec_read_register(entry, &ctx->var2);
}
static int erst_exec_store_var1(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
return __apei_exec_write_register(entry, ctx->var1);
}
static int erst_exec_add(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
ctx->var1 += ctx->var2;
return 0;
}
static int erst_exec_subtract(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
ctx->var1 -= ctx->var2;
return 0;
}
static int erst_exec_add_value(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
int rc;
u64 val;
rc = __apei_exec_read_register(entry, &val);
if (rc)
return rc;
val += ctx->value;
rc = __apei_exec_write_register(entry, val);
return rc;
}
static int erst_exec_subtract_value(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
int rc;
u64 val;
rc = __apei_exec_read_register(entry, &val);
if (rc)
return rc;
val -= ctx->value;
rc = __apei_exec_write_register(entry, val);
return rc;
}
static int erst_exec_stall(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
u64 stall_time;
if (ctx->value > FIRMWARE_MAX_STALL) {
if (!in_nmi())
pr_warning(FW_WARN ERST_PFX
"Too long stall time for stall instruction: %llx.\n",
ctx->value);
stall_time = FIRMWARE_MAX_STALL;
} else
stall_time = ctx->value;
udelay(stall_time);
return 0;
}
static int erst_exec_stall_while_true(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
int rc;
u64 val;
u64 timeout = FIRMWARE_TIMEOUT;
u64 stall_time;
if (ctx->var1 > FIRMWARE_MAX_STALL) {
if (!in_nmi())
pr_warning(FW_WARN ERST_PFX
"Too long stall time for stall while true instruction: %llx.\n",
ctx->var1);
stall_time = FIRMWARE_MAX_STALL;
} else
stall_time = ctx->var1;
for (;;) {
rc = __apei_exec_read_register(entry, &val);
if (rc)
return rc;
if (val != ctx->value)
break;
if (erst_timedout(&timeout, stall_time * NSEC_PER_USEC))
return -EIO;
}
return 0;
}
static int erst_exec_skip_next_instruction_if_true(
struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
int rc;
u64 val;
rc = __apei_exec_read_register(entry, &val);
if (rc)
return rc;
if (val == ctx->value) {
ctx->ip += 2;
return APEI_EXEC_SET_IP;
}
return 0;
}
static int erst_exec_goto(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
ctx->ip = ctx->value;
return APEI_EXEC_SET_IP;
}
static int erst_exec_set_src_address_base(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
return __apei_exec_read_register(entry, &ctx->src_base);
}
static int erst_exec_set_dst_address_base(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
return __apei_exec_read_register(entry, &ctx->dst_base);
}
static int erst_exec_move_data(struct apei_exec_context *ctx,
struct acpi_whea_header *entry)
{
int rc;
u64 offset;
rc = __apei_exec_read_register(entry, &offset);
if (rc)
return rc;
memmove((void *)ctx->dst_base + offset,
(void *)ctx->src_base + offset,
ctx->var2);
return 0;
}
static struct apei_exec_ins_type erst_ins_type[] = {
[ACPI_ERST_READ_REGISTER] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = apei_exec_read_register,
},
[ACPI_ERST_READ_REGISTER_VALUE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = apei_exec_read_register_value,
},
[ACPI_ERST_WRITE_REGISTER] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = apei_exec_write_register,
},
[ACPI_ERST_WRITE_REGISTER_VALUE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = apei_exec_write_register_value,
},
[ACPI_ERST_NOOP] = {
.flags = 0,
.run = apei_exec_noop,
},
[ACPI_ERST_LOAD_VAR1] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_load_var1,
},
[ACPI_ERST_LOAD_VAR2] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_load_var2,
},
[ACPI_ERST_STORE_VAR1] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_store_var1,
},
[ACPI_ERST_ADD] = {
.flags = 0,
.run = erst_exec_add,
},
[ACPI_ERST_SUBTRACT] = {
.flags = 0,
.run = erst_exec_subtract,
},
[ACPI_ERST_ADD_VALUE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_add_value,
},
[ACPI_ERST_SUBTRACT_VALUE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_subtract_value,
},
[ACPI_ERST_STALL] = {
.flags = 0,
.run = erst_exec_stall,
},
[ACPI_ERST_STALL_WHILE_TRUE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_stall_while_true,
},
[ACPI_ERST_SKIP_NEXT_IF_TRUE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_skip_next_instruction_if_true,
},
[ACPI_ERST_GOTO] = {
.flags = 0,
.run = erst_exec_goto,
},
[ACPI_ERST_SET_SRC_ADDRESS_BASE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_set_src_address_base,
},
[ACPI_ERST_SET_DST_ADDRESS_BASE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_set_dst_address_base,
},
[ACPI_ERST_MOVE_DATA] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = erst_exec_move_data,
},
};
static inline void erst_exec_ctx_init(struct apei_exec_context *ctx)
{
apei_exec_ctx_init(ctx, erst_ins_type, ARRAY_SIZE(erst_ins_type),
ERST_TAB_ENTRY(erst_tab), erst_tab->entries);
}
static int erst_get_erange(struct erst_erange *range)
{
struct apei_exec_context ctx;
int rc;
erst_exec_ctx_init(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_GET_ERROR_RANGE);
if (rc)
return rc;
range->base = apei_exec_ctx_get_output(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_GET_ERROR_LENGTH);
if (rc)
return rc;
range->size = apei_exec_ctx_get_output(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_GET_ERROR_ATTRIBUTES);
if (rc)
return rc;
range->attr = apei_exec_ctx_get_output(&ctx);
return 0;
}
static ssize_t __erst_get_record_count(void)
{
struct apei_exec_context ctx;
int rc;
erst_exec_ctx_init(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_GET_RECORD_COUNT);
if (rc)
return rc;
return apei_exec_ctx_get_output(&ctx);
}
ssize_t erst_get_record_count(void)
{
ssize_t count;
unsigned long flags;
if (erst_disable)
return -ENODEV;
spin_lock_irqsave(&erst_lock, flags);
count = __erst_get_record_count();
spin_unlock_irqrestore(&erst_lock, flags);
return count;
}
EXPORT_SYMBOL_GPL(erst_get_record_count);
static int __erst_get_next_record_id(u64 *record_id)
{
struct apei_exec_context ctx;
int rc;
erst_exec_ctx_init(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_GET_RECORD_ID);
if (rc)
return rc;
*record_id = apei_exec_ctx_get_output(&ctx);
return 0;
}
/*
* Get the record ID of an existing error record on the persistent
* storage. If there is no error record on the persistent storage, the
* returned record_id is APEI_ERST_INVALID_RECORD_ID.
*/
int erst_get_next_record_id(u64 *record_id)
{
int rc;
unsigned long flags;
if (erst_disable)
return -ENODEV;
spin_lock_irqsave(&erst_lock, flags);
rc = __erst_get_next_record_id(record_id);
spin_unlock_irqrestore(&erst_lock, flags);
return rc;
}
EXPORT_SYMBOL_GPL(erst_get_next_record_id);
static int __erst_write_to_storage(u64 offset)
{
struct apei_exec_context ctx;
u64 timeout = FIRMWARE_TIMEOUT;
u64 val;
int rc;
erst_exec_ctx_init(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_BEGIN_WRITE);
if (rc)
return rc;
apei_exec_ctx_set_input(&ctx, offset);
rc = apei_exec_run(&ctx, ACPI_ERST_SET_RECORD_OFFSET);
if (rc)
return rc;
rc = apei_exec_run(&ctx, ACPI_ERST_EXECUTE_OPERATION);
if (rc)
return rc;
for (;;) {
rc = apei_exec_run(&ctx, ACPI_ERST_CHECK_BUSY_STATUS);
if (rc)
return rc;
val = apei_exec_ctx_get_output(&ctx);
if (!val)
break;
if (erst_timedout(&timeout, SPIN_UNIT))
return -EIO;
}
rc = apei_exec_run(&ctx, ACPI_ERST_GET_COMMAND_STATUS);
if (rc)
return rc;
val = apei_exec_ctx_get_output(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_END);
if (rc)
return rc;
return erst_errno(val);
}
static int __erst_read_from_storage(u64 record_id, u64 offset)
{
struct apei_exec_context ctx;
u64 timeout = FIRMWARE_TIMEOUT;
u64 val;
int rc;
erst_exec_ctx_init(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_BEGIN_READ);
if (rc)
return rc;
apei_exec_ctx_set_input(&ctx, offset);
rc = apei_exec_run(&ctx, ACPI_ERST_SET_RECORD_OFFSET);
if (rc)
return rc;
apei_exec_ctx_set_input(&ctx, record_id);
rc = apei_exec_run(&ctx, ACPI_ERST_SET_RECORD_ID);
if (rc)
return rc;
rc = apei_exec_run(&ctx, ACPI_ERST_EXECUTE_OPERATION);
if (rc)
return rc;
for (;;) {
rc = apei_exec_run(&ctx, ACPI_ERST_CHECK_BUSY_STATUS);
if (rc)
return rc;
val = apei_exec_ctx_get_output(&ctx);
if (!val)
break;
if (erst_timedout(&timeout, SPIN_UNIT))
return -EIO;
};
rc = apei_exec_run(&ctx, ACPI_ERST_GET_COMMAND_STATUS);
if (rc)
return rc;
val = apei_exec_ctx_get_output(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_END);
if (rc)
return rc;
return erst_errno(val);
}
static int __erst_clear_from_storage(u64 record_id)
{
struct apei_exec_context ctx;
u64 timeout = FIRMWARE_TIMEOUT;
u64 val;
int rc;
erst_exec_ctx_init(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_BEGIN_CLEAR);
if (rc)
return rc;
apei_exec_ctx_set_input(&ctx, record_id);
rc = apei_exec_run(&ctx, ACPI_ERST_SET_RECORD_ID);
if (rc)
return rc;
rc = apei_exec_run(&ctx, ACPI_ERST_EXECUTE_OPERATION);
if (rc)
return rc;
for (;;) {
rc = apei_exec_run(&ctx, ACPI_ERST_CHECK_BUSY_STATUS);
if (rc)
return rc;
val = apei_exec_ctx_get_output(&ctx);
if (!val)
break;
if (erst_timedout(&timeout, SPIN_UNIT))
return -EIO;
}
rc = apei_exec_run(&ctx, ACPI_ERST_GET_COMMAND_STATUS);
if (rc)
return rc;
val = apei_exec_ctx_get_output(&ctx);
rc = apei_exec_run(&ctx, ACPI_ERST_END);
if (rc)
return rc;
return erst_errno(val);
}
/* NVRAM ERST Error Log Address Range is not supported yet */
static void pr_unimpl_nvram(void)
{
if (printk_ratelimit())
pr_warning(ERST_PFX
"NVRAM ERST Log Address Range is not implemented yet\n");
}
static int __erst_write_to_nvram(const struct cper_record_header *record)
{
/* do not print message, because printk is not safe for NMI */
return -ENOSYS;
}
static int __erst_read_to_erange_from_nvram(u64 record_id, u64 *offset)
{
pr_unimpl_nvram();
return -ENOSYS;
}
static int __erst_clear_from_nvram(u64 record_id)
{
pr_unimpl_nvram();
return -ENOSYS;
}
int erst_write(const struct cper_record_header *record)
{
int rc;
unsigned long flags;
struct cper_record_header *rcd_erange;
if (erst_disable)
return -ENODEV;
if (memcmp(record->signature, CPER_SIG_RECORD, CPER_SIG_SIZE))
return -EINVAL;
if (erst_erange.attr & ERST_RANGE_NVRAM) {
if (!spin_trylock_irqsave(&erst_lock, flags))
return -EBUSY;
rc = __erst_write_to_nvram(record);
spin_unlock_irqrestore(&erst_lock, flags);
return rc;
}
if (record->record_length > erst_erange.size)
return -EINVAL;
if (!spin_trylock_irqsave(&erst_lock, flags))
return -EBUSY;
memcpy(erst_erange.vaddr, record, record->record_length);
rcd_erange = erst_erange.vaddr;
/* signature for serialization system */
memcpy(&rcd_erange->persistence_information, "ER", 2);
rc = __erst_write_to_storage(0);
spin_unlock_irqrestore(&erst_lock, flags);
return rc;
}
EXPORT_SYMBOL_GPL(erst_write);
static int __erst_read_to_erange(u64 record_id, u64 *offset)
{
int rc;
if (erst_erange.attr & ERST_RANGE_NVRAM)
return __erst_read_to_erange_from_nvram(
record_id, offset);
rc = __erst_read_from_storage(record_id, 0);
if (rc)
return rc;
*offset = 0;
return 0;
}
static ssize_t __erst_read(u64 record_id, struct cper_record_header *record,
size_t buflen)
{
int rc;
u64 offset, len = 0;
struct cper_record_header *rcd_tmp;
rc = __erst_read_to_erange(record_id, &offset);
if (rc)
return rc;
rcd_tmp = erst_erange.vaddr + offset;
len = rcd_tmp->record_length;
if (len <= buflen)
memcpy(record, rcd_tmp, len);
return len;
}
/*
* If return value > buflen, the buffer size is not big enough,
* else if return value < 0, something goes wrong,
* else everything is OK, and return value is record length
*/
ssize_t erst_read(u64 record_id, struct cper_record_header *record,
size_t buflen)
{
ssize_t len;
unsigned long flags;
if (erst_disable)
return -ENODEV;
spin_lock_irqsave(&erst_lock, flags);
len = __erst_read(record_id, record, buflen);
spin_unlock_irqrestore(&erst_lock, flags);
return len;
}
EXPORT_SYMBOL_GPL(erst_read);
/*
* If return value > buflen, the buffer size is not big enough,
* else if return value = 0, there is no more record to read,
* else if return value < 0, something goes wrong,
* else everything is OK, and return value is record length
*/
ssize_t erst_read_next(struct cper_record_header *record, size_t buflen)
{
int rc;
ssize_t len;
unsigned long flags;
u64 record_id;
if (erst_disable)
return -ENODEV;
spin_lock_irqsave(&erst_lock, flags);
rc = __erst_get_next_record_id(&record_id);
if (rc) {
spin_unlock_irqrestore(&erst_lock, flags);
return rc;
}
/* no more record */
if (record_id == APEI_ERST_INVALID_RECORD_ID) {
spin_unlock_irqrestore(&erst_lock, flags);
return 0;
}
len = __erst_read(record_id, record, buflen);
spin_unlock_irqrestore(&erst_lock, flags);
return len;
}
EXPORT_SYMBOL_GPL(erst_read_next);
int erst_clear(u64 record_id)
{
int rc;
unsigned long flags;
if (erst_disable)
return -ENODEV;
spin_lock_irqsave(&erst_lock, flags);
if (erst_erange.attr & ERST_RANGE_NVRAM)
rc = __erst_clear_from_nvram(record_id);
else
rc = __erst_clear_from_storage(record_id);
spin_unlock_irqrestore(&erst_lock, flags);
return rc;
}
EXPORT_SYMBOL_GPL(erst_clear);
static int __init setup_erst_disable(char *str)
{
erst_disable = 1;
return 0;
}
__setup("erst_disable", setup_erst_disable);
static int erst_check_table(struct acpi_table_erst *erst_tab)
{
if (erst_tab->header_length != sizeof(struct acpi_table_erst))
return -EINVAL;
if (erst_tab->header.length < sizeof(struct acpi_table_erst))
return -EINVAL;
if (erst_tab->entries !=
(erst_tab->header.length - sizeof(struct acpi_table_erst)) /
sizeof(struct acpi_erst_entry))
return -EINVAL;
return 0;
}
static int __init erst_init(void)
{
int rc = 0;
acpi_status status;
struct apei_exec_context ctx;
struct apei_resources erst_resources;
struct resource *r;
if (acpi_disabled)
goto err;
if (erst_disable) {
pr_info(ERST_PFX
"Error Record Serialization Table (ERST) support is disabled.\n");
goto err;
}
status = acpi_get_table(ACPI_SIG_ERST, 0,
(struct acpi_table_header **)&erst_tab);
if (status == AE_NOT_FOUND) {
pr_info(ERST_PFX "Table is not found!\n");
goto err;
} else if (ACPI_FAILURE(status)) {
const char *msg = acpi_format_exception(status);
pr_err(ERST_PFX "Failed to get table, %s\n", msg);
rc = -EINVAL;
goto err;
}
rc = erst_check_table(erst_tab);
if (rc) {
pr_err(FW_BUG ERST_PFX "ERST table is invalid\n");
goto err;
}
apei_resources_init(&erst_resources);
erst_exec_ctx_init(&ctx);
rc = apei_exec_collect_resources(&ctx, &erst_resources);
if (rc)
goto err_fini;
rc = apei_resources_request(&erst_resources, "APEI ERST");
if (rc)
goto err_fini;
rc = apei_exec_pre_map_gars(&ctx);
if (rc)
goto err_release;
rc = erst_get_erange(&erst_erange);
if (rc) {
if (rc == -ENODEV)
pr_info(ERST_PFX
"The corresponding hardware device or firmware implementation "
"is not available.\n");
else
pr_err(ERST_PFX
"Failed to get Error Log Address Range.\n");
goto err_unmap_reg;
}
r = request_mem_region(erst_erange.base, erst_erange.size, "APEI ERST");
if (!r) {
pr_err(ERST_PFX
"Can not request iomem region <0x%16llx-0x%16llx> for ERST.\n",
(unsigned long long)erst_erange.base,
(unsigned long long)erst_erange.base + erst_erange.size);
rc = -EIO;
goto err_unmap_reg;
}
rc = -ENOMEM;
erst_erange.vaddr = ioremap_cache(erst_erange.base,
erst_erange.size);
if (!erst_erange.vaddr)
goto err_release_erange;
pr_info(ERST_PFX
"Error Record Serialization Table (ERST) support is initialized.\n");
return 0;
err_release_erange:
release_mem_region(erst_erange.base, erst_erange.size);
err_unmap_reg:
apei_exec_post_unmap_gars(&ctx);
err_release:
apei_resources_release(&erst_resources);
err_fini:
apei_resources_fini(&erst_resources);
err:
erst_disable = 1;
return rc;
}
device_initcall(erst_init);
| gpl-2.0 |
stevezilla/linux-fslc-jethro | drivers/staging/usbip/usbip_event.c | 2000 | 2906 | /*
* Copyright (C) 2003-2008 Takahiro Hirofuchi
*
* This 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 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/kthread.h>
#include <linux/export.h>
#include "usbip_common.h"
static int event_handler(struct usbip_device *ud)
{
usbip_dbg_eh("enter\n");
/*
* Events are handled by only this thread.
*/
while (usbip_event_happened(ud)) {
usbip_dbg_eh("pending event %lx\n", ud->event);
/*
* NOTE: shutdown must come first.
* Shutdown the device.
*/
if (ud->event & USBIP_EH_SHUTDOWN) {
ud->eh_ops.shutdown(ud);
ud->event &= ~USBIP_EH_SHUTDOWN;
}
/* Reset the device. */
if (ud->event & USBIP_EH_RESET) {
ud->eh_ops.reset(ud);
ud->event &= ~USBIP_EH_RESET;
}
/* Mark the device as unusable. */
if (ud->event & USBIP_EH_UNUSABLE) {
ud->eh_ops.unusable(ud);
ud->event &= ~USBIP_EH_UNUSABLE;
}
/* Stop the error handler. */
if (ud->event & USBIP_EH_BYE)
return -1;
}
return 0;
}
static int event_handler_loop(void *data)
{
struct usbip_device *ud = data;
while (!kthread_should_stop()) {
wait_event_interruptible(ud->eh_waitq,
usbip_event_happened(ud) ||
kthread_should_stop());
usbip_dbg_eh("wakeup\n");
if (event_handler(ud) < 0)
break;
}
return 0;
}
int usbip_start_eh(struct usbip_device *ud)
{
init_waitqueue_head(&ud->eh_waitq);
ud->event = 0;
ud->eh = kthread_run(event_handler_loop, ud, "usbip_eh");
if (IS_ERR(ud->eh)) {
pr_warn("Unable to start control thread\n");
return PTR_ERR(ud->eh);
}
return 0;
}
EXPORT_SYMBOL_GPL(usbip_start_eh);
void usbip_stop_eh(struct usbip_device *ud)
{
if (ud->eh == current)
return; /* do not wait for myself */
kthread_stop(ud->eh);
usbip_dbg_eh("usbip_eh has finished\n");
}
EXPORT_SYMBOL_GPL(usbip_stop_eh);
void usbip_event_add(struct usbip_device *ud, unsigned long event)
{
unsigned long flags;
spin_lock_irqsave(&ud->lock, flags);
ud->event |= event;
wake_up(&ud->eh_waitq);
spin_unlock_irqrestore(&ud->lock, flags);
}
EXPORT_SYMBOL_GPL(usbip_event_add);
int usbip_event_happened(struct usbip_device *ud)
{
int happened = 0;
spin_lock(&ud->lock);
if (ud->event != 0)
happened = 1;
spin_unlock(&ud->lock);
return happened;
}
EXPORT_SYMBOL_GPL(usbip_event_happened);
| gpl-2.0 |
psndna88/AGNI-pureSTOCK | drivers/mfd/tps65910.c | 2256 | 5100 | /*
* tps65910.c -- TI TPS6591x
*
* Copyright 2010 Texas Instruments Inc.
*
* Author: Graeme Gregory <gg@slimlogic.co.uk>
* Author: Jorge Eduardo Candelaria <jedu@slimlogic.co.uk>
*
* 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/moduleparam.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/mfd/core.h>
#include <linux/mfd/tps65910.h>
static struct mfd_cell tps65910s[] = {
{
.name = "tps65910-pmic",
},
{
.name = "tps65910-rtc",
},
{
.name = "tps65910-power",
},
};
static int tps65910_i2c_read(struct tps65910 *tps65910, u8 reg,
int bytes, void *dest)
{
struct i2c_client *i2c = tps65910->i2c_client;
struct i2c_msg xfer[2];
int ret;
/* Write register */
xfer[0].addr = i2c->addr;
xfer[0].flags = 0;
xfer[0].len = 1;
xfer[0].buf = ®
/* Read data */
xfer[1].addr = i2c->addr;
xfer[1].flags = I2C_M_RD;
xfer[1].len = bytes;
xfer[1].buf = dest;
ret = i2c_transfer(i2c->adapter, xfer, 2);
if (ret == 2)
ret = 0;
else if (ret >= 0)
ret = -EIO;
return ret;
}
static int tps65910_i2c_write(struct tps65910 *tps65910, u8 reg,
int bytes, void *src)
{
struct i2c_client *i2c = tps65910->i2c_client;
/* we add 1 byte for device register */
u8 msg[TPS65910_MAX_REGISTER + 1];
int ret;
if (bytes > TPS65910_MAX_REGISTER)
return -EINVAL;
msg[0] = reg;
memcpy(&msg[1], src, bytes);
ret = i2c_master_send(i2c, msg, bytes + 1);
if (ret < 0)
return ret;
if (ret != bytes + 1)
return -EIO;
return 0;
}
int tps65910_set_bits(struct tps65910 *tps65910, u8 reg, u8 mask)
{
u8 data;
int err;
mutex_lock(&tps65910->io_mutex);
err = tps65910_i2c_read(tps65910, reg, 1, &data);
if (err) {
dev_err(tps65910->dev, "read from reg %x failed\n", reg);
goto out;
}
data |= mask;
err = tps65910_i2c_write(tps65910, reg, 1, &data);
if (err)
dev_err(tps65910->dev, "write to reg %x failed\n", reg);
out:
mutex_unlock(&tps65910->io_mutex);
return err;
}
EXPORT_SYMBOL_GPL(tps65910_set_bits);
int tps65910_clear_bits(struct tps65910 *tps65910, u8 reg, u8 mask)
{
u8 data;
int err;
mutex_lock(&tps65910->io_mutex);
err = tps65910_i2c_read(tps65910, reg, 1, &data);
if (err) {
dev_err(tps65910->dev, "read from reg %x failed\n", reg);
goto out;
}
data &= mask;
err = tps65910_i2c_write(tps65910, reg, 1, &data);
if (err)
dev_err(tps65910->dev, "write to reg %x failed\n", reg);
out:
mutex_unlock(&tps65910->io_mutex);
return err;
}
EXPORT_SYMBOL_GPL(tps65910_clear_bits);
static int tps65910_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct tps65910 *tps65910;
struct tps65910_board *pmic_plat_data;
struct tps65910_platform_data *init_data;
int ret = 0;
pmic_plat_data = dev_get_platdata(&i2c->dev);
if (!pmic_plat_data)
return -EINVAL;
init_data = kzalloc(sizeof(struct tps65910_platform_data), GFP_KERNEL);
if (init_data == NULL)
return -ENOMEM;
init_data->irq = pmic_plat_data->irq;
init_data->irq_base = pmic_plat_data->irq;
tps65910 = kzalloc(sizeof(struct tps65910), GFP_KERNEL);
if (tps65910 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, tps65910);
tps65910->dev = &i2c->dev;
tps65910->i2c_client = i2c;
tps65910->id = id->driver_data;
tps65910->read = tps65910_i2c_read;
tps65910->write = tps65910_i2c_write;
mutex_init(&tps65910->io_mutex);
ret = mfd_add_devices(tps65910->dev, -1,
tps65910s, ARRAY_SIZE(tps65910s),
NULL, 0);
if (ret < 0)
goto err;
tps65910_gpio_init(tps65910, pmic_plat_data->gpio_base);
ret = tps65910_irq_init(tps65910, init_data->irq, init_data);
if (ret < 0)
goto err;
return ret;
err:
mfd_remove_devices(tps65910->dev);
kfree(tps65910);
return ret;
}
static int tps65910_i2c_remove(struct i2c_client *i2c)
{
struct tps65910 *tps65910 = i2c_get_clientdata(i2c);
mfd_remove_devices(tps65910->dev);
kfree(tps65910);
return 0;
}
static const struct i2c_device_id tps65910_i2c_id[] = {
{ "tps65910", TPS65910 },
{ "tps65911", TPS65911 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tps65910_i2c_id);
static struct i2c_driver tps65910_i2c_driver = {
.driver = {
.name = "tps65910",
.owner = THIS_MODULE,
},
.probe = tps65910_i2c_probe,
.remove = tps65910_i2c_remove,
.id_table = tps65910_i2c_id,
};
static int __init tps65910_i2c_init(void)
{
return i2c_add_driver(&tps65910_i2c_driver);
}
/* init early so consumer devices can complete system boot */
subsys_initcall(tps65910_i2c_init);
static void __exit tps65910_i2c_exit(void)
{
i2c_del_driver(&tps65910_i2c_driver);
}
module_exit(tps65910_i2c_exit);
MODULE_AUTHOR("Graeme Gregory <gg@slimlogic.co.uk>");
MODULE_AUTHOR("Jorge Eduardo Candelaria <jedu@slimlogic.co.uk>");
MODULE_DESCRIPTION("TPS6591x chip family multi-function driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
psyke83/android_hardware_atheros_ath6kl-compat | drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c | 2512 | 4410 | /**************************************************************************
*
* Copyright (c) 2007-2010 VMware, Inc., Palo Alto, CA., USA
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
/*
* Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
*/
#include "vmwgfx_drv.h"
#include <drm/ttm/ttm_module.h>
#include <drm/ttm/ttm_bo_driver.h>
#include <drm/ttm/ttm_placement.h>
#include <linux/idr.h>
#include <linux/spinlock.h>
#include <linux/kernel.h>
struct vmwgfx_gmrid_man {
spinlock_t lock;
struct ida gmr_ida;
uint32_t max_gmr_ids;
uint32_t max_gmr_pages;
uint32_t used_gmr_pages;
};
static int vmw_gmrid_man_get_node(struct ttm_mem_type_manager *man,
struct ttm_buffer_object *bo,
struct ttm_placement *placement,
struct ttm_mem_reg *mem)
{
struct vmwgfx_gmrid_man *gman =
(struct vmwgfx_gmrid_man *)man->priv;
int ret = 0;
int id;
mem->mm_node = NULL;
spin_lock(&gman->lock);
if (gman->max_gmr_pages > 0) {
gman->used_gmr_pages += bo->num_pages;
if (unlikely(gman->used_gmr_pages > gman->max_gmr_pages))
goto out_err_locked;
}
do {
spin_unlock(&gman->lock);
if (unlikely(ida_pre_get(&gman->gmr_ida, GFP_KERNEL) == 0)) {
ret = -ENOMEM;
goto out_err;
}
spin_lock(&gman->lock);
ret = ida_get_new(&gman->gmr_ida, &id);
if (unlikely(ret == 0 && id >= gman->max_gmr_ids)) {
ida_remove(&gman->gmr_ida, id);
ret = 0;
goto out_err_locked;
}
} while (ret == -EAGAIN);
if (likely(ret == 0)) {
mem->mm_node = gman;
mem->start = id;
mem->num_pages = bo->num_pages;
} else
goto out_err_locked;
spin_unlock(&gman->lock);
return 0;
out_err:
spin_lock(&gman->lock);
out_err_locked:
gman->used_gmr_pages -= bo->num_pages;
spin_unlock(&gman->lock);
return ret;
}
static void vmw_gmrid_man_put_node(struct ttm_mem_type_manager *man,
struct ttm_mem_reg *mem)
{
struct vmwgfx_gmrid_man *gman =
(struct vmwgfx_gmrid_man *)man->priv;
if (mem->mm_node) {
spin_lock(&gman->lock);
ida_remove(&gman->gmr_ida, mem->start);
gman->used_gmr_pages -= mem->num_pages;
spin_unlock(&gman->lock);
mem->mm_node = NULL;
}
}
static int vmw_gmrid_man_init(struct ttm_mem_type_manager *man,
unsigned long p_size)
{
struct vmw_private *dev_priv =
container_of(man->bdev, struct vmw_private, bdev);
struct vmwgfx_gmrid_man *gman =
kzalloc(sizeof(*gman), GFP_KERNEL);
if (unlikely(gman == NULL))
return -ENOMEM;
spin_lock_init(&gman->lock);
gman->max_gmr_pages = dev_priv->max_gmr_pages;
gman->used_gmr_pages = 0;
ida_init(&gman->gmr_ida);
gman->max_gmr_ids = p_size;
man->priv = (void *) gman;
return 0;
}
static int vmw_gmrid_man_takedown(struct ttm_mem_type_manager *man)
{
struct vmwgfx_gmrid_man *gman =
(struct vmwgfx_gmrid_man *)man->priv;
if (gman) {
ida_destroy(&gman->gmr_ida);
kfree(gman);
}
return 0;
}
static void vmw_gmrid_man_debug(struct ttm_mem_type_manager *man,
const char *prefix)
{
printk(KERN_INFO "%s: No debug info available for the GMR "
"id manager.\n", prefix);
}
const struct ttm_mem_type_manager_func vmw_gmrid_manager_func = {
vmw_gmrid_man_init,
vmw_gmrid_man_takedown,
vmw_gmrid_man_get_node,
vmw_gmrid_man_put_node,
vmw_gmrid_man_debug
};
| gpl-2.0 |
javilonas/kernel_common | drivers/hwmon/lm95241.c | 2768 | 12620 | /*
* Copyright (C) 2008, 2010 Davide Rizzo <elpa.rizzo@gmail.com>
*
* The LM95241 is a sensor chip made by National Semiconductors.
* It reports up to three temperatures (its own plus up to two external ones).
* Complete datasheet can be obtained from National's website at:
* http://www.national.com/ds.cgi/LM/LM95241.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>
#include <linux/mutex.h>
#include <linux/sysfs.h>
#define DEVNAME "lm95241"
static const unsigned short normal_i2c[] = {
0x19, 0x2a, 0x2b, I2C_CLIENT_END };
/* LM95241 registers */
#define LM95241_REG_R_MAN_ID 0xFE
#define LM95241_REG_R_CHIP_ID 0xFF
#define LM95241_REG_R_STATUS 0x02
#define LM95241_REG_RW_CONFIG 0x03
#define LM95241_REG_RW_REM_FILTER 0x06
#define LM95241_REG_RW_TRUTHERM 0x07
#define LM95241_REG_W_ONE_SHOT 0x0F
#define LM95241_REG_R_LOCAL_TEMPH 0x10
#define LM95241_REG_R_REMOTE1_TEMPH 0x11
#define LM95241_REG_R_REMOTE2_TEMPH 0x12
#define LM95241_REG_R_LOCAL_TEMPL 0x20
#define LM95241_REG_R_REMOTE1_TEMPL 0x21
#define LM95241_REG_R_REMOTE2_TEMPL 0x22
#define LM95241_REG_RW_REMOTE_MODEL 0x30
/* LM95241 specific bitfields */
#define CFG_STOP 0x40
#define CFG_CR0076 0x00
#define CFG_CR0182 0x10
#define CFG_CR1000 0x20
#define CFG_CR2700 0x30
#define R1MS_SHIFT 0
#define R2MS_SHIFT 2
#define R1MS_MASK (0x01 << (R1MS_SHIFT))
#define R2MS_MASK (0x01 << (R2MS_SHIFT))
#define R1DF_SHIFT 1
#define R2DF_SHIFT 2
#define R1DF_MASK (0x01 << (R1DF_SHIFT))
#define R2DF_MASK (0x01 << (R2DF_SHIFT))
#define R1FE_MASK 0x01
#define R2FE_MASK 0x05
#define TT1_SHIFT 0
#define TT2_SHIFT 4
#define TT_OFF 0
#define TT_ON 1
#define TT_MASK 7
#define NATSEMI_MAN_ID 0x01
#define LM95231_CHIP_ID 0xA1
#define LM95241_CHIP_ID 0xA4
static const u8 lm95241_reg_address[] = {
LM95241_REG_R_LOCAL_TEMPH,
LM95241_REG_R_LOCAL_TEMPL,
LM95241_REG_R_REMOTE1_TEMPH,
LM95241_REG_R_REMOTE1_TEMPL,
LM95241_REG_R_REMOTE2_TEMPH,
LM95241_REG_R_REMOTE2_TEMPL
};
/* Client data (each client gets its own) */
struct lm95241_data {
struct device *hwmon_dev;
struct mutex update_lock;
unsigned long last_updated, interval; /* in jiffies */
char valid; /* zero until following fields are valid */
/* registers values */
u8 temp[ARRAY_SIZE(lm95241_reg_address)];
u8 config, model, trutherm;
};
/* Conversions */
static int temp_from_reg_signed(u8 val_h, u8 val_l)
{
s16 val_hl = (val_h << 8) | val_l;
return val_hl * 1000 / 256;
}
static int temp_from_reg_unsigned(u8 val_h, u8 val_l)
{
u16 val_hl = (val_h << 8) | val_l;
return val_hl * 1000 / 256;
}
static struct lm95241_data *lm95241_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + data->interval) ||
!data->valid) {
int i;
dev_dbg(&client->dev, "Updating lm95241 data.\n");
for (i = 0; i < ARRAY_SIZE(lm95241_reg_address); i++)
data->temp[i]
= i2c_smbus_read_byte_data(client,
lm95241_reg_address[i]);
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
/* Sysfs stuff */
static ssize_t show_input(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct lm95241_data *data = lm95241_update_device(dev);
int index = to_sensor_dev_attr(attr)->index;
return snprintf(buf, PAGE_SIZE - 1, "%d\n",
index == 0 || (data->config & (1 << (index / 2))) ?
temp_from_reg_signed(data->temp[index], data->temp[index + 1]) :
temp_from_reg_unsigned(data->temp[index],
data->temp[index + 1]));
}
static ssize_t show_type(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
return snprintf(buf, PAGE_SIZE - 1,
data->model & to_sensor_dev_attr(attr)->index ? "1\n" : "2\n");
}
static ssize_t set_type(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
unsigned long val;
int shift;
u8 mask = to_sensor_dev_attr(attr)->index;
if (kstrtoul(buf, 10, &val) < 0)
return -EINVAL;
if (val != 1 && val != 2)
return -EINVAL;
shift = mask == R1MS_MASK ? TT1_SHIFT : TT2_SHIFT;
mutex_lock(&data->update_lock);
data->trutherm &= ~(TT_MASK << shift);
if (val == 1) {
data->model |= mask;
data->trutherm |= (TT_ON << shift);
} else {
data->model &= ~mask;
data->trutherm |= (TT_OFF << shift);
}
data->valid = 0;
i2c_smbus_write_byte_data(client, LM95241_REG_RW_REMOTE_MODEL,
data->model);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_TRUTHERM,
data->trutherm);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
return snprintf(buf, PAGE_SIZE - 1,
data->config & to_sensor_dev_attr(attr)->index ?
"-127000\n" : "0\n");
}
static ssize_t set_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
long val;
if (kstrtol(buf, 10, &val) < 0)
return -EINVAL;
if (val < -128000)
return -EINVAL;
mutex_lock(&data->update_lock);
if (val < 0)
data->config |= to_sensor_dev_attr(attr)->index;
else
data->config &= ~to_sensor_dev_attr(attr)->index;
data->valid = 0;
i2c_smbus_write_byte_data(client, LM95241_REG_RW_CONFIG, data->config);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
return snprintf(buf, PAGE_SIZE - 1,
data->config & to_sensor_dev_attr(attr)->index ?
"127000\n" : "255000\n");
}
static ssize_t set_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
long val;
if (kstrtol(buf, 10, &val) < 0)
return -EINVAL;
if (val >= 256000)
return -EINVAL;
mutex_lock(&data->update_lock);
if (val <= 127000)
data->config |= to_sensor_dev_attr(attr)->index;
else
data->config &= ~to_sensor_dev_attr(attr)->index;
data->valid = 0;
i2c_smbus_write_byte_data(client, LM95241_REG_RW_CONFIG, data->config);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_interval(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct lm95241_data *data = lm95241_update_device(dev);
return snprintf(buf, PAGE_SIZE - 1, "%lu\n", 1000 * data->interval
/ HZ);
}
static ssize_t set_interval(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
unsigned long val;
if (kstrtoul(buf, 10, &val) < 0)
return -EINVAL;
data->interval = val * HZ / 1000;
return count;
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_input, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_input, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_input, NULL, 4);
static SENSOR_DEVICE_ATTR(temp2_type, S_IWUSR | S_IRUGO, show_type, set_type,
R1MS_MASK);
static SENSOR_DEVICE_ATTR(temp3_type, S_IWUSR | S_IRUGO, show_type, set_type,
R2MS_MASK);
static SENSOR_DEVICE_ATTR(temp2_min, S_IWUSR | S_IRUGO, show_min, set_min,
R1DF_MASK);
static SENSOR_DEVICE_ATTR(temp3_min, S_IWUSR | S_IRUGO, show_min, set_min,
R2DF_MASK);
static SENSOR_DEVICE_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_max, set_max,
R1DF_MASK);
static SENSOR_DEVICE_ATTR(temp3_max, S_IWUSR | S_IRUGO, show_max, set_max,
R2DF_MASK);
static DEVICE_ATTR(update_interval, S_IWUSR | S_IRUGO, show_interval,
set_interval);
static struct attribute *lm95241_attributes[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp2_type.dev_attr.attr,
&sensor_dev_attr_temp3_type.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&dev_attr_update_interval.attr,
NULL
};
static const struct attribute_group lm95241_group = {
.attrs = lm95241_attributes,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int lm95241_detect(struct i2c_client *new_client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = new_client->adapter;
const char *name;
int mfg_id, chip_id;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
mfg_id = i2c_smbus_read_byte_data(new_client, LM95241_REG_R_MAN_ID);
if (mfg_id != NATSEMI_MAN_ID)
return -ENODEV;
chip_id = i2c_smbus_read_byte_data(new_client, LM95241_REG_R_CHIP_ID);
switch (chip_id) {
case LM95231_CHIP_ID:
name = "lm95231";
break;
case LM95241_CHIP_ID:
name = "lm95241";
break;
default:
return -ENODEV;
}
/* Fill the i2c board info */
strlcpy(info->type, name, I2C_NAME_SIZE);
return 0;
}
static void lm95241_init_client(struct i2c_client *client)
{
struct lm95241_data *data = i2c_get_clientdata(client);
data->interval = HZ; /* 1 sec default */
data->valid = 0;
data->config = CFG_CR0076;
data->model = 0;
data->trutherm = (TT_OFF << TT1_SHIFT) | (TT_OFF << TT2_SHIFT);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_CONFIG, data->config);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_REM_FILTER,
R1FE_MASK | R2FE_MASK);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_TRUTHERM,
data->trutherm);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_REMOTE_MODEL,
data->model);
}
static int lm95241_probe(struct i2c_client *new_client,
const struct i2c_device_id *id)
{
struct lm95241_data *data;
int err;
data = devm_kzalloc(&new_client->dev, sizeof(struct lm95241_data),
GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(new_client, data);
mutex_init(&data->update_lock);
/* Initialize the LM95241 chip */
lm95241_init_client(new_client);
/* Register sysfs hooks */
err = sysfs_create_group(&new_client->dev.kobj, &lm95241_group);
if (err)
return err;
data->hwmon_dev = hwmon_device_register(&new_client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove_files;
}
return 0;
exit_remove_files:
sysfs_remove_group(&new_client->dev.kobj, &lm95241_group);
return err;
}
static int lm95241_remove(struct i2c_client *client)
{
struct lm95241_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &lm95241_group);
return 0;
}
/* Driver data (common to all clients) */
static const struct i2c_device_id lm95241_id[] = {
{ "lm95231", 0 },
{ "lm95241", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, lm95241_id);
static struct i2c_driver lm95241_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = DEVNAME,
},
.probe = lm95241_probe,
.remove = lm95241_remove,
.id_table = lm95241_id,
.detect = lm95241_detect,
.address_list = normal_i2c,
};
module_i2c_driver(lm95241_driver);
MODULE_AUTHOR("Davide Rizzo <elpa.rizzo@gmail.com>");
MODULE_DESCRIPTION("LM95241 sensor driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
zf2-laser-dev/android_kernel_asus_msm8916 | drivers/ata/pata_icside.c | 4304 | 16390 | #include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/gfp.h>
#include <scsi/scsi_host.h>
#include <linux/ata.h>
#include <linux/libata.h>
#include <asm/dma.h>
#include <asm/ecard.h>
#define DRV_NAME "pata_icside"
#define ICS_IDENT_OFFSET 0x2280
#define ICS_ARCIN_V5_INTRSTAT 0x0000
#define ICS_ARCIN_V5_INTROFFSET 0x0004
#define ICS_ARCIN_V6_INTROFFSET_1 0x2200
#define ICS_ARCIN_V6_INTRSTAT_1 0x2290
#define ICS_ARCIN_V6_INTROFFSET_2 0x3200
#define ICS_ARCIN_V6_INTRSTAT_2 0x3290
struct portinfo {
unsigned int dataoffset;
unsigned int ctrloffset;
unsigned int stepping;
};
static const struct portinfo pata_icside_portinfo_v5 = {
.dataoffset = 0x2800,
.ctrloffset = 0x2b80,
.stepping = 6,
};
static const struct portinfo pata_icside_portinfo_v6_1 = {
.dataoffset = 0x2000,
.ctrloffset = 0x2380,
.stepping = 6,
};
static const struct portinfo pata_icside_portinfo_v6_2 = {
.dataoffset = 0x3000,
.ctrloffset = 0x3380,
.stepping = 6,
};
struct pata_icside_state {
void __iomem *irq_port;
void __iomem *ioc_base;
unsigned int type;
unsigned int dma;
struct {
u8 port_sel;
u8 disabled;
unsigned int speed[ATA_MAX_DEVICES];
} port[2];
};
struct pata_icside_info {
struct pata_icside_state *state;
struct expansion_card *ec;
void __iomem *base;
void __iomem *irqaddr;
unsigned int irqmask;
const expansioncard_ops_t *irqops;
unsigned int mwdma_mask;
unsigned int nr_ports;
const struct portinfo *port[2];
unsigned long raw_base;
unsigned long raw_ioc_base;
};
#define ICS_TYPE_A3IN 0
#define ICS_TYPE_A3USER 1
#define ICS_TYPE_V6 3
#define ICS_TYPE_V5 15
#define ICS_TYPE_NOTYPE ((unsigned int)-1)
/* ---------------- Version 5 PCB Support Functions --------------------- */
/* Prototype: pata_icside_irqenable_arcin_v5 (struct expansion_card *ec, int irqnr)
* Purpose : enable interrupts from card
*/
static void pata_icside_irqenable_arcin_v5 (struct expansion_card *ec, int irqnr)
{
struct pata_icside_state *state = ec->irq_data;
writeb(0, state->irq_port + ICS_ARCIN_V5_INTROFFSET);
}
/* Prototype: pata_icside_irqdisable_arcin_v5 (struct expansion_card *ec, int irqnr)
* Purpose : disable interrupts from card
*/
static void pata_icside_irqdisable_arcin_v5 (struct expansion_card *ec, int irqnr)
{
struct pata_icside_state *state = ec->irq_data;
readb(state->irq_port + ICS_ARCIN_V5_INTROFFSET);
}
static const expansioncard_ops_t pata_icside_ops_arcin_v5 = {
.irqenable = pata_icside_irqenable_arcin_v5,
.irqdisable = pata_icside_irqdisable_arcin_v5,
};
/* ---------------- Version 6 PCB Support Functions --------------------- */
/* Prototype: pata_icside_irqenable_arcin_v6 (struct expansion_card *ec, int irqnr)
* Purpose : enable interrupts from card
*/
static void pata_icside_irqenable_arcin_v6 (struct expansion_card *ec, int irqnr)
{
struct pata_icside_state *state = ec->irq_data;
void __iomem *base = state->irq_port;
if (!state->port[0].disabled)
writeb(0, base + ICS_ARCIN_V6_INTROFFSET_1);
if (!state->port[1].disabled)
writeb(0, base + ICS_ARCIN_V6_INTROFFSET_2);
}
/* Prototype: pata_icside_irqdisable_arcin_v6 (struct expansion_card *ec, int irqnr)
* Purpose : disable interrupts from card
*/
static void pata_icside_irqdisable_arcin_v6 (struct expansion_card *ec, int irqnr)
{
struct pata_icside_state *state = ec->irq_data;
readb(state->irq_port + ICS_ARCIN_V6_INTROFFSET_1);
readb(state->irq_port + ICS_ARCIN_V6_INTROFFSET_2);
}
/* Prototype: pata_icside_irqprobe(struct expansion_card *ec)
* Purpose : detect an active interrupt from card
*/
static int pata_icside_irqpending_arcin_v6(struct expansion_card *ec)
{
struct pata_icside_state *state = ec->irq_data;
return readb(state->irq_port + ICS_ARCIN_V6_INTRSTAT_1) & 1 ||
readb(state->irq_port + ICS_ARCIN_V6_INTRSTAT_2) & 1;
}
static const expansioncard_ops_t pata_icside_ops_arcin_v6 = {
.irqenable = pata_icside_irqenable_arcin_v6,
.irqdisable = pata_icside_irqdisable_arcin_v6,
.irqpending = pata_icside_irqpending_arcin_v6,
};
/*
* SG-DMA support.
*
* Similar to the BM-DMA, but we use the RiscPCs IOMD DMA controllers.
* There is only one DMA controller per card, which means that only
* one drive can be accessed at one time. NOTE! We do not enforce that
* here, but we rely on the main IDE driver spotting that both
* interfaces use the same IRQ, which should guarantee this.
*/
/*
* Configure the IOMD to give the appropriate timings for the transfer
* mode being requested. We take the advice of the ATA standards, and
* calculate the cycle time based on the transfer mode, and the EIDE
* MW DMA specs that the drive provides in the IDENTIFY command.
*
* We have the following IOMD DMA modes to choose from:
*
* Type Active Recovery Cycle
* A 250 (250) 312 (550) 562 (800)
* B 187 (200) 250 (550) 437 (750)
* C 125 (125) 125 (375) 250 (500)
* D 62 (50) 125 (375) 187 (425)
*
* (figures in brackets are actual measured timings on DIOR/DIOW)
*
* However, we also need to take care of the read/write active and
* recovery timings:
*
* Read Write
* Mode Active -- Recovery -- Cycle IOMD type
* MW0 215 50 215 480 A
* MW1 80 50 50 150 C
* MW2 70 25 25 120 C
*/
static void pata_icside_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
struct pata_icside_state *state = ap->host->private_data;
struct ata_timing t;
unsigned int cycle;
char iomd_type;
/*
* DMA is based on a 16MHz clock
*/
if (ata_timing_compute(adev, adev->dma_mode, &t, 1000, 1))
return;
/*
* Choose the IOMD cycle timing which ensure that the interface
* satisfies the measured active, recovery and cycle times.
*/
if (t.active <= 50 && t.recover <= 375 && t.cycle <= 425)
iomd_type = 'D', cycle = 187;
else if (t.active <= 125 && t.recover <= 375 && t.cycle <= 500)
iomd_type = 'C', cycle = 250;
else if (t.active <= 200 && t.recover <= 550 && t.cycle <= 750)
iomd_type = 'B', cycle = 437;
else
iomd_type = 'A', cycle = 562;
ata_dev_info(adev, "timings: act %dns rec %dns cyc %dns (%c)\n",
t.active, t.recover, t.cycle, iomd_type);
state->port[ap->port_no].speed[adev->devno] = cycle;
}
static void pata_icside_bmdma_setup(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pata_icside_state *state = ap->host->private_data;
unsigned int write = qc->tf.flags & ATA_TFLAG_WRITE;
/*
* We are simplex; BUG if we try to fiddle with DMA
* while it's active.
*/
BUG_ON(dma_channel_active(state->dma));
/*
* Route the DMA signals to the correct interface
*/
writeb(state->port[ap->port_no].port_sel, state->ioc_base);
set_dma_speed(state->dma, state->port[ap->port_no].speed[qc->dev->devno]);
set_dma_sg(state->dma, qc->sg, qc->n_elem);
set_dma_mode(state->dma, write ? DMA_MODE_WRITE : DMA_MODE_READ);
/* issue r/w command */
ap->ops->sff_exec_command(ap, &qc->tf);
}
static void pata_icside_bmdma_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pata_icside_state *state = ap->host->private_data;
BUG_ON(dma_channel_active(state->dma));
enable_dma(state->dma);
}
static void pata_icside_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pata_icside_state *state = ap->host->private_data;
disable_dma(state->dma);
/* see ata_bmdma_stop */
ata_sff_dma_pause(ap);
}
static u8 pata_icside_bmdma_status(struct ata_port *ap)
{
struct pata_icside_state *state = ap->host->private_data;
void __iomem *irq_port;
irq_port = state->irq_port + (ap->port_no ? ICS_ARCIN_V6_INTRSTAT_2 :
ICS_ARCIN_V6_INTRSTAT_1);
return readb(irq_port) & 1 ? ATA_DMA_INTR : 0;
}
static int icside_dma_init(struct pata_icside_info *info)
{
struct pata_icside_state *state = info->state;
struct expansion_card *ec = info->ec;
int i;
for (i = 0; i < ATA_MAX_DEVICES; i++) {
state->port[0].speed[i] = 480;
state->port[1].speed[i] = 480;
}
if (ec->dma != NO_DMA && !request_dma(ec->dma, DRV_NAME)) {
state->dma = ec->dma;
info->mwdma_mask = ATA_MWDMA2;
}
return 0;
}
static struct scsi_host_template pata_icside_sht = {
ATA_BASE_SHT(DRV_NAME),
.sg_tablesize = SCSI_MAX_SG_CHAIN_SEGMENTS,
.dma_boundary = IOMD_DMA_BOUNDARY,
};
static void pata_icside_postreset(struct ata_link *link, unsigned int *classes)
{
struct ata_port *ap = link->ap;
struct pata_icside_state *state = ap->host->private_data;
if (classes[0] != ATA_DEV_NONE || classes[1] != ATA_DEV_NONE)
return ata_sff_postreset(link, classes);
state->port[ap->port_no].disabled = 1;
if (state->type == ICS_TYPE_V6) {
/*
* Disable interrupts from this port, otherwise we
* receive spurious interrupts from the floating
* interrupt line.
*/
void __iomem *irq_port = state->irq_port +
(ap->port_no ? ICS_ARCIN_V6_INTROFFSET_2 : ICS_ARCIN_V6_INTROFFSET_1);
readb(irq_port);
}
}
static struct ata_port_operations pata_icside_port_ops = {
.inherits = &ata_bmdma_port_ops,
/* no need to build any PRD tables for DMA */
.qc_prep = ata_noop_qc_prep,
.sff_data_xfer = ata_sff_data_xfer_noirq,
.bmdma_setup = pata_icside_bmdma_setup,
.bmdma_start = pata_icside_bmdma_start,
.bmdma_stop = pata_icside_bmdma_stop,
.bmdma_status = pata_icside_bmdma_status,
.cable_detect = ata_cable_40wire,
.set_dmamode = pata_icside_set_dmamode,
.postreset = pata_icside_postreset,
.port_start = ATA_OP_NULL, /* don't need PRD table */
};
static void pata_icside_setup_ioaddr(struct ata_port *ap, void __iomem *base,
struct pata_icside_info *info,
const struct portinfo *port)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
void __iomem *cmd = base + port->dataoffset;
ioaddr->cmd_addr = cmd;
ioaddr->data_addr = cmd + (ATA_REG_DATA << port->stepping);
ioaddr->error_addr = cmd + (ATA_REG_ERR << port->stepping);
ioaddr->feature_addr = cmd + (ATA_REG_FEATURE << port->stepping);
ioaddr->nsect_addr = cmd + (ATA_REG_NSECT << port->stepping);
ioaddr->lbal_addr = cmd + (ATA_REG_LBAL << port->stepping);
ioaddr->lbam_addr = cmd + (ATA_REG_LBAM << port->stepping);
ioaddr->lbah_addr = cmd + (ATA_REG_LBAH << port->stepping);
ioaddr->device_addr = cmd + (ATA_REG_DEVICE << port->stepping);
ioaddr->status_addr = cmd + (ATA_REG_STATUS << port->stepping);
ioaddr->command_addr = cmd + (ATA_REG_CMD << port->stepping);
ioaddr->ctl_addr = base + port->ctrloffset;
ioaddr->altstatus_addr = ioaddr->ctl_addr;
ata_port_desc(ap, "cmd 0x%lx ctl 0x%lx",
info->raw_base + port->dataoffset,
info->raw_base + port->ctrloffset);
if (info->raw_ioc_base)
ata_port_desc(ap, "iocbase 0x%lx", info->raw_ioc_base);
}
static int pata_icside_register_v5(struct pata_icside_info *info)
{
struct pata_icside_state *state = info->state;
void __iomem *base;
base = ecardm_iomap(info->ec, ECARD_RES_MEMC, 0, 0);
if (!base)
return -ENOMEM;
state->irq_port = base;
info->base = base;
info->irqaddr = base + ICS_ARCIN_V5_INTRSTAT;
info->irqmask = 1;
info->irqops = &pata_icside_ops_arcin_v5;
info->nr_ports = 1;
info->port[0] = &pata_icside_portinfo_v5;
info->raw_base = ecard_resource_start(info->ec, ECARD_RES_MEMC);
return 0;
}
static int pata_icside_register_v6(struct pata_icside_info *info)
{
struct pata_icside_state *state = info->state;
struct expansion_card *ec = info->ec;
void __iomem *ioc_base, *easi_base;
unsigned int sel = 0;
ioc_base = ecardm_iomap(ec, ECARD_RES_IOCFAST, 0, 0);
if (!ioc_base)
return -ENOMEM;
easi_base = ioc_base;
if (ecard_resource_flags(ec, ECARD_RES_EASI)) {
easi_base = ecardm_iomap(ec, ECARD_RES_EASI, 0, 0);
if (!easi_base)
return -ENOMEM;
/*
* Enable access to the EASI region.
*/
sel = 1 << 5;
}
writeb(sel, ioc_base);
state->irq_port = easi_base;
state->ioc_base = ioc_base;
state->port[0].port_sel = sel;
state->port[1].port_sel = sel | 1;
info->base = easi_base;
info->irqops = &pata_icside_ops_arcin_v6;
info->nr_ports = 2;
info->port[0] = &pata_icside_portinfo_v6_1;
info->port[1] = &pata_icside_portinfo_v6_2;
info->raw_base = ecard_resource_start(ec, ECARD_RES_EASI);
info->raw_ioc_base = ecard_resource_start(ec, ECARD_RES_IOCFAST);
return icside_dma_init(info);
}
static int pata_icside_add_ports(struct pata_icside_info *info)
{
struct expansion_card *ec = info->ec;
struct ata_host *host;
int i;
if (info->irqaddr) {
ec->irqaddr = info->irqaddr;
ec->irqmask = info->irqmask;
}
if (info->irqops)
ecard_setirq(ec, info->irqops, info->state);
/*
* Be on the safe side - disable interrupts
*/
ec->ops->irqdisable(ec, ec->irq);
host = ata_host_alloc(&ec->dev, info->nr_ports);
if (!host)
return -ENOMEM;
host->private_data = info->state;
host->flags = ATA_HOST_SIMPLEX;
for (i = 0; i < info->nr_ports; i++) {
struct ata_port *ap = host->ports[i];
ap->pio_mask = ATA_PIO4;
ap->mwdma_mask = info->mwdma_mask;
ap->flags |= ATA_FLAG_SLAVE_POSS;
ap->ops = &pata_icside_port_ops;
pata_icside_setup_ioaddr(ap, info->base, info, info->port[i]);
}
return ata_host_activate(host, ec->irq, ata_bmdma_interrupt, 0,
&pata_icside_sht);
}
static int pata_icside_probe(struct expansion_card *ec,
const struct ecard_id *id)
{
struct pata_icside_state *state;
struct pata_icside_info info;
void __iomem *idmem;
int ret;
ret = ecard_request_resources(ec);
if (ret)
goto out;
state = devm_kzalloc(&ec->dev, sizeof(*state), GFP_KERNEL);
if (!state) {
ret = -ENOMEM;
goto release;
}
state->type = ICS_TYPE_NOTYPE;
state->dma = NO_DMA;
idmem = ecardm_iomap(ec, ECARD_RES_IOCFAST, 0, 0);
if (idmem) {
unsigned int type;
type = readb(idmem + ICS_IDENT_OFFSET) & 1;
type |= (readb(idmem + ICS_IDENT_OFFSET + 4) & 1) << 1;
type |= (readb(idmem + ICS_IDENT_OFFSET + 8) & 1) << 2;
type |= (readb(idmem + ICS_IDENT_OFFSET + 12) & 1) << 3;
ecardm_iounmap(ec, idmem);
state->type = type;
}
memset(&info, 0, sizeof(info));
info.state = state;
info.ec = ec;
switch (state->type) {
case ICS_TYPE_A3IN:
dev_warn(&ec->dev, "A3IN unsupported\n");
ret = -ENODEV;
break;
case ICS_TYPE_A3USER:
dev_warn(&ec->dev, "A3USER unsupported\n");
ret = -ENODEV;
break;
case ICS_TYPE_V5:
ret = pata_icside_register_v5(&info);
break;
case ICS_TYPE_V6:
ret = pata_icside_register_v6(&info);
break;
default:
dev_warn(&ec->dev, "unknown interface type\n");
ret = -ENODEV;
break;
}
if (ret == 0)
ret = pata_icside_add_ports(&info);
if (ret == 0)
goto out;
release:
ecard_release_resources(ec);
out:
return ret;
}
static void pata_icside_shutdown(struct expansion_card *ec)
{
struct ata_host *host = ecard_get_drvdata(ec);
unsigned long flags;
/*
* Disable interrupts from this card. We need to do
* this before disabling EASI since we may be accessing
* this register via that region.
*/
local_irq_save(flags);
ec->ops->irqdisable(ec, ec->irq);
local_irq_restore(flags);
/*
* Reset the ROM pointer so that we can read the ROM
* after a soft reboot. This also disables access to
* the IDE taskfile via the EASI region.
*/
if (host) {
struct pata_icside_state *state = host->private_data;
if (state->ioc_base)
writeb(0, state->ioc_base);
}
}
static void pata_icside_remove(struct expansion_card *ec)
{
struct ata_host *host = ecard_get_drvdata(ec);
struct pata_icside_state *state = host->private_data;
ata_host_detach(host);
pata_icside_shutdown(ec);
/*
* don't NULL out the drvdata - devres/libata wants it
* to free the ata_host structure.
*/
if (state->dma != NO_DMA)
free_dma(state->dma);
ecard_release_resources(ec);
}
static const struct ecard_id pata_icside_ids[] = {
{ MANU_ICS, PROD_ICS_IDE },
{ MANU_ICS2, PROD_ICS2_IDE },
{ 0xffff, 0xffff }
};
static struct ecard_driver pata_icside_driver = {
.probe = pata_icside_probe,
.remove = pata_icside_remove,
.shutdown = pata_icside_shutdown,
.id_table = pata_icside_ids,
.drv = {
.name = DRV_NAME,
},
};
static int __init pata_icside_init(void)
{
return ecard_register_driver(&pata_icside_driver);
}
static void __exit pata_icside_exit(void)
{
ecard_remove_driver(&pata_icside_driver);
}
MODULE_AUTHOR("Russell King <rmk@arm.linux.org.uk>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("ICS PATA driver");
module_init(pata_icside_init);
module_exit(pata_icside_exit);
| gpl-2.0 |
NoelMacwan/Kernel-Honami-14.1.N.0.52 | drivers/net/wireless/rtlwifi/cam.c | 4816 | 10328 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include <linux/export.h>
#include "wifi.h"
#include "cam.h"
void rtl_cam_reset_sec_info(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->sec.use_defaultkey = false;
rtlpriv->sec.pairwise_enc_algorithm = NO_ENCRYPTION;
rtlpriv->sec.group_enc_algorithm = NO_ENCRYPTION;
memset(rtlpriv->sec.key_buf, 0, KEY_BUF_SIZE * MAX_KEY_LEN);
memset(rtlpriv->sec.key_len, 0, KEY_BUF_SIZE);
rtlpriv->sec.pairwise_key = NULL;
}
static void rtl_cam_program_entry(struct ieee80211_hw *hw, u32 entry_no,
u8 *mac_addr, u8 *key_cont_128, u16 us_config)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 target_command;
u32 target_content = 0;
u8 entry_i;
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"key_cont_128:\n %x:%x:%x:%x:%x:%x\n",
key_cont_128[0], key_cont_128[1],
key_cont_128[2], key_cont_128[3],
key_cont_128[4], key_cont_128[5]);
for (entry_i = 0; entry_i < CAM_CONTENT_COUNT; entry_i++) {
target_command = entry_i + CAM_CONTENT_COUNT * entry_no;
target_command = target_command | BIT(31) | BIT(16);
if (entry_i == 0) {
target_content = (u32) (*(mac_addr + 0)) << 16 |
(u32) (*(mac_addr + 1)) << 24 | (u32) us_config;
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI],
target_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM],
target_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE %x: %x\n",
rtlpriv->cfg->maps[WCAMI], target_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"The Key ID is %d\n", entry_no);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE %x: %x\n",
rtlpriv->cfg->maps[RWCAM], target_command);
} else if (entry_i == 1) {
target_content = (u32) (*(mac_addr + 5)) << 24 |
(u32) (*(mac_addr + 4)) << 16 |
(u32) (*(mac_addr + 3)) << 8 |
(u32) (*(mac_addr + 2));
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI],
target_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM],
target_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE A4: %x\n",
target_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE A0: %x\n",
target_command);
} else {
target_content =
(u32) (*(key_cont_128 + (entry_i * 4 - 8) + 3)) <<
24 | (u32) (*(key_cont_128 + (entry_i * 4 - 8) + 2))
<< 16 |
(u32) (*(key_cont_128 + (entry_i * 4 - 8) + 1)) << 8
| (u32) (*(key_cont_128 + (entry_i * 4 - 8) + 0));
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI],
target_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM],
target_command);
udelay(100);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE A4: %x\n",
target_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE A0: %x\n",
target_command);
}
}
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "after set key, usconfig:%x\n",
us_config);
}
u8 rtl_cam_add_one_entry(struct ieee80211_hw *hw, u8 *mac_addr,
u32 ul_key_id, u32 ul_entry_idx, u32 ul_enc_alg,
u32 ul_default_key, u8 *key_content)
{
u32 us_config;
struct rtl_priv *rtlpriv = rtl_priv(hw);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"EntryNo:%x, ulKeyId=%x, ulEncAlg=%x, ulUseDK=%x MacAddr %pM\n",
ul_entry_idx, ul_key_id, ul_enc_alg,
ul_default_key, mac_addr);
if (ul_key_id == TOTAL_CAM_ENTRY) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"<=== ulKeyId exceed!\n");
return 0;
}
if (ul_default_key == 1) {
us_config = CFG_VALID | ((u16) (ul_enc_alg) << 2);
} else {
us_config = CFG_VALID | ((ul_enc_alg) << 2) | ul_key_id;
}
rtl_cam_program_entry(hw, ul_entry_idx, mac_addr,
(u8 *) key_content, us_config);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "<===\n");
return 1;
}
EXPORT_SYMBOL(rtl_cam_add_one_entry);
int rtl_cam_delete_one_entry(struct ieee80211_hw *hw,
u8 *mac_addr, u32 ul_key_id)
{
u32 ul_command;
struct rtl_priv *rtlpriv = rtl_priv(hw);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "key_idx:%d\n", ul_key_id);
ul_command = ul_key_id * CAM_CONTENT_COUNT;
ul_command = ul_command | BIT(31) | BIT(16);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI], 0);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM], ul_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"rtl_cam_delete_one_entry(): WRITE A4: %x\n", 0);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"rtl_cam_delete_one_entry(): WRITE A0: %x\n", ul_command);
return 0;
}
EXPORT_SYMBOL(rtl_cam_delete_one_entry);
void rtl_cam_reset_all_entry(struct ieee80211_hw *hw)
{
u32 ul_command;
struct rtl_priv *rtlpriv = rtl_priv(hw);
ul_command = BIT(31) | BIT(30);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM], ul_command);
}
EXPORT_SYMBOL(rtl_cam_reset_all_entry);
void rtl_cam_mark_invalid(struct ieee80211_hw *hw, u8 uc_index)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 ul_command;
u32 ul_content;
u32 ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_AES];
switch (rtlpriv->sec.pairwise_enc_algorithm) {
case WEP40_ENCRYPTION:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_WEP40];
break;
case WEP104_ENCRYPTION:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_WEP104];
break;
case TKIP_ENCRYPTION:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_TKIP];
break;
case AESCCMP_ENCRYPTION:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_AES];
break;
default:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_AES];
}
ul_content = (uc_index & 3) | ((u16) (ul_enc_algo) << 2);
ul_content |= BIT(15);
ul_command = CAM_CONTENT_COUNT * uc_index;
ul_command = ul_command | BIT(31) | BIT(16);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI], ul_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM], ul_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"rtl_cam_mark_invalid(): WRITE A4: %x\n", ul_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"rtl_cam_mark_invalid(): WRITE A0: %x\n", ul_command);
}
EXPORT_SYMBOL(rtl_cam_mark_invalid);
void rtl_cam_empty_entry(struct ieee80211_hw *hw, u8 uc_index)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 ul_command;
u32 ul_content;
u32 ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_AES];
u8 entry_i;
switch (rtlpriv->sec.pairwise_enc_algorithm) {
case WEP40_ENCRYPTION:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_WEP40];
break;
case WEP104_ENCRYPTION:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_WEP104];
break;
case TKIP_ENCRYPTION:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_TKIP];
break;
case AESCCMP_ENCRYPTION:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_AES];
break;
default:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_AES];
}
for (entry_i = 0; entry_i < CAM_CONTENT_COUNT; entry_i++) {
if (entry_i == 0) {
ul_content =
(uc_index & 0x03) | ((u16) (ul_encalgo) << 2);
ul_content |= BIT(15);
} else {
ul_content = 0;
}
ul_command = CAM_CONTENT_COUNT * uc_index + entry_i;
ul_command = ul_command | BIT(31) | BIT(16);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI], ul_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM], ul_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"rtl_cam_empty_entry(): WRITE A4: %x\n",
ul_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"rtl_cam_empty_entry(): WRITE A0: %x\n",
ul_command);
}
}
EXPORT_SYMBOL(rtl_cam_empty_entry);
u8 rtl_cam_get_free_entry(struct ieee80211_hw *hw, u8 *sta_addr)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 bitmap = (rtlpriv->sec.hwsec_cam_bitmap) >> 4;
u8 entry_idx = 0;
u8 i, *addr;
if (NULL == sta_addr) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_EMERG, "sta_addr is NULL\n");
return TOTAL_CAM_ENTRY;
}
/* Does STA already exist? */
for (i = 4; i < TOTAL_CAM_ENTRY; i++) {
addr = rtlpriv->sec.hwsec_cam_sta_addr[i];
if (memcmp(addr, sta_addr, ETH_ALEN) == 0)
return i;
}
/* Get a free CAM entry. */
for (entry_idx = 4; entry_idx < TOTAL_CAM_ENTRY; entry_idx++) {
if ((bitmap & BIT(0)) == 0) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_EMERG,
"-----hwsec_cam_bitmap: 0x%x entry_idx=%d\n",
rtlpriv->sec.hwsec_cam_bitmap, entry_idx);
rtlpriv->sec.hwsec_cam_bitmap |= BIT(0) << entry_idx;
memcpy(rtlpriv->sec.hwsec_cam_sta_addr[entry_idx],
sta_addr, ETH_ALEN);
return entry_idx;
}
bitmap = bitmap >> 1;
}
return TOTAL_CAM_ENTRY;
}
EXPORT_SYMBOL(rtl_cam_get_free_entry);
void rtl_cam_del_entry(struct ieee80211_hw *hw, u8 *sta_addr)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 bitmap;
u8 i, *addr;
if (NULL == sta_addr) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_EMERG, "sta_addr is NULL\n");
}
if ((sta_addr[0]|sta_addr[1]|sta_addr[2]|sta_addr[3]|\
sta_addr[4]|sta_addr[5]) == 0) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_EMERG,
"sta_addr is 00:00:00:00:00:00\n");
return;
}
/* Does STA already exist? */
for (i = 4; i < TOTAL_CAM_ENTRY; i++) {
addr = rtlpriv->sec.hwsec_cam_sta_addr[i];
bitmap = (rtlpriv->sec.hwsec_cam_bitmap) >> i;
if (((bitmap & BIT(0)) == BIT(0)) &&
(memcmp(addr, sta_addr, ETH_ALEN) == 0)) {
/* Remove from HW Security CAM */
memset(rtlpriv->sec.hwsec_cam_sta_addr[i], 0, ETH_ALEN);
rtlpriv->sec.hwsec_cam_bitmap &= ~(BIT(0) << i);
pr_info("&&&&&&&&&del entry %d\n", i);
}
}
return;
}
EXPORT_SYMBOL(rtl_cam_del_entry);
| gpl-2.0 |
Split-Screen/android_kernel_motorola_ghost | drivers/usb/storage/option_ms.c | 5072 | 4479 | /*
* Driver for Option High Speed Mobile Devices.
*
* (c) 2008 Dan Williams <dcbw@redhat.com>
*
* Inspiration taken from sierra_ms.c by Kevin Lloyd <klloyd@sierrawireless.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/usb.h>
#include <linux/slab.h>
#include <linux/module.h>
#include "usb.h"
#include "transport.h"
#include "option_ms.h"
#include "debug.h"
#define ZCD_FORCE_MODEM 0x01
#define ZCD_ALLOW_MS 0x02
static unsigned int option_zero_cd = ZCD_FORCE_MODEM;
module_param(option_zero_cd, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(option_zero_cd, "ZeroCD mode (1=Force Modem (default),"
" 2=Allow CD-Rom");
#define RESPONSE_LEN 1024
static int option_rezero(struct us_data *us)
{
const unsigned char rezero_msg[] = {
0x55, 0x53, 0x42, 0x43, 0x78, 0x56, 0x34, 0x12,
0x01, 0x00, 0x00, 0x00, 0x80, 0x00, 0x06, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
char *buffer;
int result;
US_DEBUGP("Option MS: %s", "DEVICE MODE SWITCH\n");
buffer = kzalloc(RESPONSE_LEN, GFP_KERNEL);
if (buffer == NULL)
return USB_STOR_TRANSPORT_ERROR;
memcpy(buffer, rezero_msg, sizeof(rezero_msg));
result = usb_stor_bulk_transfer_buf(us,
us->send_bulk_pipe,
buffer, sizeof(rezero_msg), NULL);
if (result != USB_STOR_XFER_GOOD) {
result = USB_STOR_XFER_ERROR;
goto out;
}
/* Some of the devices need to be asked for a response, but we don't
* care what that response is.
*/
usb_stor_bulk_transfer_buf(us,
us->recv_bulk_pipe,
buffer, RESPONSE_LEN, NULL);
/* Read the CSW */
usb_stor_bulk_transfer_buf(us,
us->recv_bulk_pipe,
buffer, 13, NULL);
result = USB_STOR_XFER_GOOD;
out:
kfree(buffer);
return result;
}
static int option_inquiry(struct us_data *us)
{
const unsigned char inquiry_msg[] = {
0x55, 0x53, 0x42, 0x43, 0x12, 0x34, 0x56, 0x78,
0x24, 0x00, 0x00, 0x00, 0x80, 0x00, 0x06, 0x12,
0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
char *buffer;
int result;
US_DEBUGP("Option MS: %s", "device inquiry for vendor name\n");
buffer = kzalloc(0x24, GFP_KERNEL);
if (buffer == NULL)
return USB_STOR_TRANSPORT_ERROR;
memcpy(buffer, inquiry_msg, sizeof(inquiry_msg));
result = usb_stor_bulk_transfer_buf(us,
us->send_bulk_pipe,
buffer, sizeof(inquiry_msg), NULL);
if (result != USB_STOR_XFER_GOOD) {
result = USB_STOR_XFER_ERROR;
goto out;
}
result = usb_stor_bulk_transfer_buf(us,
us->recv_bulk_pipe,
buffer, 0x24, NULL);
if (result != USB_STOR_XFER_GOOD) {
result = USB_STOR_XFER_ERROR;
goto out;
}
result = memcmp(buffer+8, "Option", 6);
if (result != 0)
result = memcmp(buffer+8, "ZCOPTION", 8);
/* Read the CSW */
usb_stor_bulk_transfer_buf(us,
us->recv_bulk_pipe,
buffer, 13, NULL);
out:
kfree(buffer);
return result;
}
int option_ms_init(struct us_data *us)
{
int result;
US_DEBUGP("Option MS: option_ms_init called\n");
/* Additional test for vendor information via INQUIRY,
* because some vendor/product IDs are ambiguous
*/
result = option_inquiry(us);
if (result != 0) {
US_DEBUGP("Option MS: vendor is not Option or not determinable,"
" no action taken\n");
return 0;
} else
US_DEBUGP("Option MS: this is a genuine Option device,"
" proceeding\n");
/* Force Modem mode */
if (option_zero_cd == ZCD_FORCE_MODEM) {
US_DEBUGP("Option MS: %s", "Forcing Modem Mode\n");
result = option_rezero(us);
if (result != USB_STOR_XFER_GOOD)
US_DEBUGP("Option MS: Failed to switch to modem mode.\n");
return -EIO;
} else if (option_zero_cd == ZCD_ALLOW_MS) {
/* Allow Mass Storage mode (keep CD-Rom) */
US_DEBUGP("Option MS: %s", "Allowing Mass Storage Mode if device"
" requests it\n");
}
return 0;
}
| gpl-2.0 |
amoonhappy/s4kernel | drivers/input/keyboard/bf54x-keys.c | 5072 | 10009 | /*
* File: drivers/input/keyboard/bf54x-keys.c
* Based on:
* Author: Michael Hennerich <hennerich@blackfin.uclinux.org>
*
* Created:
* Description: keypad driver for Analog Devices Blackfin BF54x Processors
*
*
* Modified:
* Copyright 2007-2008 Analog Devices Inc.
*
* Bugs: Enter bugs at http://blackfin.uclinux.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, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/pm.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <asm/portmux.h>
#include <mach/bf54x_keys.h>
#define DRV_NAME "bf54x-keys"
#define TIME_SCALE 100 /* 100 ns */
#define MAX_MULT (0xFF * TIME_SCALE)
#define MAX_RC 8 /* Max Row/Col */
static const u16 per_rows[] = {
P_KEY_ROW7,
P_KEY_ROW6,
P_KEY_ROW5,
P_KEY_ROW4,
P_KEY_ROW3,
P_KEY_ROW2,
P_KEY_ROW1,
P_KEY_ROW0,
0
};
static const u16 per_cols[] = {
P_KEY_COL7,
P_KEY_COL6,
P_KEY_COL5,
P_KEY_COL4,
P_KEY_COL3,
P_KEY_COL2,
P_KEY_COL1,
P_KEY_COL0,
0
};
struct bf54x_kpad {
struct input_dev *input;
int irq;
unsigned short lastkey;
unsigned short *keycode;
struct timer_list timer;
unsigned int keyup_test_jiffies;
unsigned short kpad_msel;
unsigned short kpad_prescale;
unsigned short kpad_ctl;
};
static inline int bfin_kpad_find_key(struct bf54x_kpad *bf54x_kpad,
struct input_dev *input, u16 keyident)
{
u16 i;
for (i = 0; i < input->keycodemax; i++)
if (bf54x_kpad->keycode[i + input->keycodemax] == keyident)
return bf54x_kpad->keycode[i];
return -1;
}
static inline void bfin_keycodecpy(unsigned short *keycode,
const unsigned int *pdata_kc,
unsigned short keymapsize)
{
unsigned int i;
for (i = 0; i < keymapsize; i++) {
keycode[i] = pdata_kc[i] & 0xffff;
keycode[i + keymapsize] = pdata_kc[i] >> 16;
}
}
static inline u16 bfin_kpad_get_prescale(u32 timescale)
{
u32 sclk = get_sclk();
return ((((sclk / 1000) * timescale) / 1024) - 1);
}
static inline u16 bfin_kpad_get_keypressed(struct bf54x_kpad *bf54x_kpad)
{
return (bfin_read_KPAD_STAT() & KPAD_PRESSED);
}
static inline void bfin_kpad_clear_irq(void)
{
bfin_write_KPAD_STAT(0xFFFF);
bfin_write_KPAD_ROWCOL(0xFFFF);
}
static void bfin_kpad_timer(unsigned long data)
{
struct platform_device *pdev = (struct platform_device *) data;
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
if (bfin_kpad_get_keypressed(bf54x_kpad)) {
/* Try again later */
mod_timer(&bf54x_kpad->timer,
jiffies + bf54x_kpad->keyup_test_jiffies);
return;
}
input_report_key(bf54x_kpad->input, bf54x_kpad->lastkey, 0);
input_sync(bf54x_kpad->input);
/* Clear IRQ Status */
bfin_kpad_clear_irq();
enable_irq(bf54x_kpad->irq);
}
static irqreturn_t bfin_kpad_isr(int irq, void *dev_id)
{
struct platform_device *pdev = dev_id;
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
struct input_dev *input = bf54x_kpad->input;
int key;
u16 rowcol = bfin_read_KPAD_ROWCOL();
key = bfin_kpad_find_key(bf54x_kpad, input, rowcol);
input_report_key(input, key, 1);
input_sync(input);
if (bfin_kpad_get_keypressed(bf54x_kpad)) {
disable_irq_nosync(bf54x_kpad->irq);
bf54x_kpad->lastkey = key;
mod_timer(&bf54x_kpad->timer,
jiffies + bf54x_kpad->keyup_test_jiffies);
} else {
input_report_key(input, key, 0);
input_sync(input);
bfin_kpad_clear_irq();
}
return IRQ_HANDLED;
}
static int __devinit bfin_kpad_probe(struct platform_device *pdev)
{
struct bf54x_kpad *bf54x_kpad;
struct bfin_kpad_platform_data *pdata = pdev->dev.platform_data;
struct input_dev *input;
int i, error;
if (!pdata->rows || !pdata->cols || !pdata->keymap) {
dev_err(&pdev->dev, "no rows, cols or keymap from pdata\n");
return -EINVAL;
}
if (!pdata->keymapsize ||
pdata->keymapsize > (pdata->rows * pdata->cols)) {
dev_err(&pdev->dev, "invalid keymapsize\n");
return -EINVAL;
}
bf54x_kpad = kzalloc(sizeof(struct bf54x_kpad), GFP_KERNEL);
if (!bf54x_kpad)
return -ENOMEM;
platform_set_drvdata(pdev, bf54x_kpad);
/* Allocate memory for keymap followed by private LUT */
bf54x_kpad->keycode = kmalloc(pdata->keymapsize *
sizeof(unsigned short) * 2, GFP_KERNEL);
if (!bf54x_kpad->keycode) {
error = -ENOMEM;
goto out;
}
if (!pdata->debounce_time || pdata->debounce_time > MAX_MULT ||
!pdata->coldrive_time || pdata->coldrive_time > MAX_MULT) {
dev_warn(&pdev->dev,
"invalid platform debounce/columndrive time\n");
bfin_write_KPAD_MSEL(0xFF0); /* Default MSEL */
} else {
bfin_write_KPAD_MSEL(
((pdata->debounce_time / TIME_SCALE)
& DBON_SCALE) |
(((pdata->coldrive_time / TIME_SCALE) << 8)
& COLDRV_SCALE));
}
if (!pdata->keyup_test_interval)
bf54x_kpad->keyup_test_jiffies = msecs_to_jiffies(50);
else
bf54x_kpad->keyup_test_jiffies =
msecs_to_jiffies(pdata->keyup_test_interval);
if (peripheral_request_list((u16 *)&per_rows[MAX_RC - pdata->rows],
DRV_NAME)) {
dev_err(&pdev->dev, "requesting peripherals failed\n");
error = -EFAULT;
goto out0;
}
if (peripheral_request_list((u16 *)&per_cols[MAX_RC - pdata->cols],
DRV_NAME)) {
dev_err(&pdev->dev, "requesting peripherals failed\n");
error = -EFAULT;
goto out1;
}
bf54x_kpad->irq = platform_get_irq(pdev, 0);
if (bf54x_kpad->irq < 0) {
error = -ENODEV;
goto out2;
}
error = request_irq(bf54x_kpad->irq, bfin_kpad_isr,
0, DRV_NAME, pdev);
if (error) {
dev_err(&pdev->dev, "unable to claim irq %d\n",
bf54x_kpad->irq);
goto out2;
}
input = input_allocate_device();
if (!input) {
error = -ENOMEM;
goto out3;
}
bf54x_kpad->input = input;
input->name = pdev->name;
input->phys = "bf54x-keys/input0";
input->dev.parent = &pdev->dev;
input_set_drvdata(input, bf54x_kpad);
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
input->keycodesize = sizeof(unsigned short);
input->keycodemax = pdata->keymapsize;
input->keycode = bf54x_kpad->keycode;
bfin_keycodecpy(bf54x_kpad->keycode, pdata->keymap, pdata->keymapsize);
/* setup input device */
__set_bit(EV_KEY, input->evbit);
if (pdata->repeat)
__set_bit(EV_REP, input->evbit);
for (i = 0; i < input->keycodemax; i++)
__set_bit(bf54x_kpad->keycode[i] & KEY_MAX, input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
error = input_register_device(input);
if (error) {
dev_err(&pdev->dev, "unable to register input device\n");
goto out4;
}
/* Init Keypad Key Up/Release test timer */
setup_timer(&bf54x_kpad->timer, bfin_kpad_timer, (unsigned long) pdev);
bfin_write_KPAD_PRESCALE(bfin_kpad_get_prescale(TIME_SCALE));
bfin_write_KPAD_CTL((((pdata->cols - 1) << 13) & KPAD_COLEN) |
(((pdata->rows - 1) << 10) & KPAD_ROWEN) |
(2 & KPAD_IRQMODE));
bfin_write_KPAD_CTL(bfin_read_KPAD_CTL() | KPAD_EN);
device_init_wakeup(&pdev->dev, 1);
return 0;
out4:
input_free_device(input);
out3:
free_irq(bf54x_kpad->irq, pdev);
out2:
peripheral_free_list((u16 *)&per_cols[MAX_RC - pdata->cols]);
out1:
peripheral_free_list((u16 *)&per_rows[MAX_RC - pdata->rows]);
out0:
kfree(bf54x_kpad->keycode);
out:
kfree(bf54x_kpad);
platform_set_drvdata(pdev, NULL);
return error;
}
static int __devexit bfin_kpad_remove(struct platform_device *pdev)
{
struct bfin_kpad_platform_data *pdata = pdev->dev.platform_data;
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
del_timer_sync(&bf54x_kpad->timer);
free_irq(bf54x_kpad->irq, pdev);
input_unregister_device(bf54x_kpad->input);
peripheral_free_list((u16 *)&per_rows[MAX_RC - pdata->rows]);
peripheral_free_list((u16 *)&per_cols[MAX_RC - pdata->cols]);
kfree(bf54x_kpad->keycode);
kfree(bf54x_kpad);
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int bfin_kpad_suspend(struct platform_device *pdev, pm_message_t state)
{
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
bf54x_kpad->kpad_msel = bfin_read_KPAD_MSEL();
bf54x_kpad->kpad_prescale = bfin_read_KPAD_PRESCALE();
bf54x_kpad->kpad_ctl = bfin_read_KPAD_CTL();
if (device_may_wakeup(&pdev->dev))
enable_irq_wake(bf54x_kpad->irq);
return 0;
}
static int bfin_kpad_resume(struct platform_device *pdev)
{
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
bfin_write_KPAD_MSEL(bf54x_kpad->kpad_msel);
bfin_write_KPAD_PRESCALE(bf54x_kpad->kpad_prescale);
bfin_write_KPAD_CTL(bf54x_kpad->kpad_ctl);
if (device_may_wakeup(&pdev->dev))
disable_irq_wake(bf54x_kpad->irq);
return 0;
}
#else
# define bfin_kpad_suspend NULL
# define bfin_kpad_resume NULL
#endif
static struct platform_driver bfin_kpad_device_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = bfin_kpad_probe,
.remove = __devexit_p(bfin_kpad_remove),
.suspend = bfin_kpad_suspend,
.resume = bfin_kpad_resume,
};
module_platform_driver(bfin_kpad_device_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Keypad driver for BF54x Processors");
MODULE_ALIAS("platform:bf54x-keys");
| gpl-2.0 |
RepoBackups/kernel_lge_g3 | drivers/infiniband/hw/nes/nes_mgt.c | 5072 | 36854 | /*
* Copyright (c) 2006 - 2011 Intel-NE, Inc. 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/skbuff.h>
#include <linux/etherdevice.h>
#include <linux/kthread.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <net/tcp.h>
#include "nes.h"
#include "nes_mgt.h"
atomic_t pau_qps_created;
atomic_t pau_qps_destroyed;
static void nes_replenish_mgt_rq(struct nes_vnic_mgt *mgtvnic)
{
unsigned long flags;
dma_addr_t bus_address;
struct sk_buff *skb;
struct nes_hw_nic_rq_wqe *nic_rqe;
struct nes_hw_mgt *nesmgt;
struct nes_device *nesdev;
struct nes_rskb_cb *cb;
u32 rx_wqes_posted = 0;
nesmgt = &mgtvnic->mgt;
nesdev = mgtvnic->nesvnic->nesdev;
spin_lock_irqsave(&nesmgt->rq_lock, flags);
if (nesmgt->replenishing_rq != 0) {
if (((nesmgt->rq_size - 1) == atomic_read(&mgtvnic->rx_skbs_needed)) &&
(atomic_read(&mgtvnic->rx_skb_timer_running) == 0)) {
atomic_set(&mgtvnic->rx_skb_timer_running, 1);
spin_unlock_irqrestore(&nesmgt->rq_lock, flags);
mgtvnic->rq_wqes_timer.expires = jiffies + (HZ / 2); /* 1/2 second */
add_timer(&mgtvnic->rq_wqes_timer);
} else {
spin_unlock_irqrestore(&nesmgt->rq_lock, flags);
}
return;
}
nesmgt->replenishing_rq = 1;
spin_unlock_irqrestore(&nesmgt->rq_lock, flags);
do {
skb = dev_alloc_skb(mgtvnic->nesvnic->max_frame_size);
if (skb) {
skb->dev = mgtvnic->nesvnic->netdev;
bus_address = pci_map_single(nesdev->pcidev,
skb->data, mgtvnic->nesvnic->max_frame_size, PCI_DMA_FROMDEVICE);
cb = (struct nes_rskb_cb *)&skb->cb[0];
cb->busaddr = bus_address;
cb->maplen = mgtvnic->nesvnic->max_frame_size;
nic_rqe = &nesmgt->rq_vbase[mgtvnic->mgt.rq_head];
nic_rqe->wqe_words[NES_NIC_RQ_WQE_LENGTH_1_0_IDX] =
cpu_to_le32(mgtvnic->nesvnic->max_frame_size);
nic_rqe->wqe_words[NES_NIC_RQ_WQE_LENGTH_3_2_IDX] = 0;
nic_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_LOW_IDX] =
cpu_to_le32((u32)bus_address);
nic_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_HIGH_IDX] =
cpu_to_le32((u32)((u64)bus_address >> 32));
nesmgt->rx_skb[nesmgt->rq_head] = skb;
nesmgt->rq_head++;
nesmgt->rq_head &= nesmgt->rq_size - 1;
atomic_dec(&mgtvnic->rx_skbs_needed);
barrier();
if (++rx_wqes_posted == 255) {
nes_write32(nesdev->regs + NES_WQE_ALLOC, (rx_wqes_posted << 24) | nesmgt->qp_id);
rx_wqes_posted = 0;
}
} else {
spin_lock_irqsave(&nesmgt->rq_lock, flags);
if (((nesmgt->rq_size - 1) == atomic_read(&mgtvnic->rx_skbs_needed)) &&
(atomic_read(&mgtvnic->rx_skb_timer_running) == 0)) {
atomic_set(&mgtvnic->rx_skb_timer_running, 1);
spin_unlock_irqrestore(&nesmgt->rq_lock, flags);
mgtvnic->rq_wqes_timer.expires = jiffies + (HZ / 2); /* 1/2 second */
add_timer(&mgtvnic->rq_wqes_timer);
} else {
spin_unlock_irqrestore(&nesmgt->rq_lock, flags);
}
break;
}
} while (atomic_read(&mgtvnic->rx_skbs_needed));
barrier();
if (rx_wqes_posted)
nes_write32(nesdev->regs + NES_WQE_ALLOC, (rx_wqes_posted << 24) | nesmgt->qp_id);
nesmgt->replenishing_rq = 0;
}
/**
* nes_mgt_rq_wqes_timeout
*/
static void nes_mgt_rq_wqes_timeout(unsigned long parm)
{
struct nes_vnic_mgt *mgtvnic = (struct nes_vnic_mgt *)parm;
atomic_set(&mgtvnic->rx_skb_timer_running, 0);
if (atomic_read(&mgtvnic->rx_skbs_needed))
nes_replenish_mgt_rq(mgtvnic);
}
/**
* nes_mgt_free_skb - unmap and free skb
*/
static void nes_mgt_free_skb(struct nes_device *nesdev, struct sk_buff *skb, u32 dir)
{
struct nes_rskb_cb *cb;
cb = (struct nes_rskb_cb *)&skb->cb[0];
pci_unmap_single(nesdev->pcidev, cb->busaddr, cb->maplen, dir);
cb->busaddr = 0;
dev_kfree_skb_any(skb);
}
/**
* nes_download_callback - handle download completions
*/
static void nes_download_callback(struct nes_device *nesdev, struct nes_cqp_request *cqp_request)
{
struct pau_fpdu_info *fpdu_info = cqp_request->cqp_callback_pointer;
struct nes_qp *nesqp = fpdu_info->nesqp;
struct sk_buff *skb;
int i;
for (i = 0; i < fpdu_info->frag_cnt; i++) {
skb = fpdu_info->frags[i].skb;
if (fpdu_info->frags[i].cmplt) {
nes_mgt_free_skb(nesdev, skb, PCI_DMA_TODEVICE);
nes_rem_ref_cm_node(nesqp->cm_node);
}
}
if (fpdu_info->hdr_vbase)
pci_free_consistent(nesdev->pcidev, fpdu_info->hdr_len,
fpdu_info->hdr_vbase, fpdu_info->hdr_pbase);
kfree(fpdu_info);
}
/**
* nes_get_seq - Get the seq, ack_seq and window from the packet
*/
static u32 nes_get_seq(struct sk_buff *skb, u32 *ack, u16 *wnd, u32 *fin_rcvd, u32 *rst_rcvd)
{
struct nes_rskb_cb *cb = (struct nes_rskb_cb *)&skb->cb[0];
struct iphdr *iph = (struct iphdr *)(cb->data_start + ETH_HLEN);
struct tcphdr *tcph = (struct tcphdr *)(((char *)iph) + (4 * iph->ihl));
*ack = be32_to_cpu(tcph->ack_seq);
*wnd = be16_to_cpu(tcph->window);
*fin_rcvd = tcph->fin;
*rst_rcvd = tcph->rst;
return be32_to_cpu(tcph->seq);
}
/**
* nes_get_next_skb - Get the next skb based on where current skb is in the queue
*/
static struct sk_buff *nes_get_next_skb(struct nes_device *nesdev, struct nes_qp *nesqp,
struct sk_buff *skb, u32 nextseq, u32 *ack,
u16 *wnd, u32 *fin_rcvd, u32 *rst_rcvd)
{
u32 seq;
bool processacks;
struct sk_buff *old_skb;
if (skb) {
/* Continue processing fpdu */
if (skb->next == (struct sk_buff *)&nesqp->pau_list)
goto out;
skb = skb->next;
processacks = false;
} else {
/* Starting a new one */
if (skb_queue_empty(&nesqp->pau_list))
goto out;
skb = skb_peek(&nesqp->pau_list);
processacks = true;
}
while (1) {
seq = nes_get_seq(skb, ack, wnd, fin_rcvd, rst_rcvd);
if (seq == nextseq) {
if (skb->len || processacks)
break;
} else if (after(seq, nextseq)) {
goto out;
}
if (skb->next == (struct sk_buff *)&nesqp->pau_list)
goto out;
old_skb = skb;
skb = skb->next;
skb_unlink(old_skb, &nesqp->pau_list);
nes_mgt_free_skb(nesdev, old_skb, PCI_DMA_TODEVICE);
nes_rem_ref_cm_node(nesqp->cm_node);
}
return skb;
out:
return NULL;
}
/**
* get_fpdu_info - Find the next complete fpdu and return its fragments.
*/
static int get_fpdu_info(struct nes_device *nesdev, struct nes_qp *nesqp,
struct pau_fpdu_info **pau_fpdu_info)
{
struct sk_buff *skb;
struct iphdr *iph;
struct tcphdr *tcph;
struct nes_rskb_cb *cb;
struct pau_fpdu_info *fpdu_info = NULL;
struct pau_fpdu_frag frags[MAX_FPDU_FRAGS];
unsigned long flags;
u32 fpdu_len = 0;
u32 tmp_len;
int frag_cnt = 0;
u32 tot_len;
u32 frag_tot;
u32 ack;
u32 fin_rcvd;
u32 rst_rcvd;
u16 wnd;
int i;
int rc = 0;
*pau_fpdu_info = NULL;
spin_lock_irqsave(&nesqp->pau_lock, flags);
skb = nes_get_next_skb(nesdev, nesqp, NULL, nesqp->pau_rcv_nxt, &ack, &wnd, &fin_rcvd, &rst_rcvd);
if (!skb) {
spin_unlock_irqrestore(&nesqp->pau_lock, flags);
goto out;
}
cb = (struct nes_rskb_cb *)&skb->cb[0];
if (skb->len) {
fpdu_len = be16_to_cpu(*(__be16 *) skb->data) + MPA_FRAMING;
fpdu_len = (fpdu_len + 3) & 0xfffffffc;
tmp_len = fpdu_len;
/* See if we have all of the fpdu */
frag_tot = 0;
memset(&frags, 0, sizeof frags);
for (i = 0; i < MAX_FPDU_FRAGS; i++) {
frags[i].physaddr = cb->busaddr;
frags[i].physaddr += skb->data - cb->data_start;
frags[i].frag_len = min(tmp_len, skb->len);
frags[i].skb = skb;
frags[i].cmplt = (skb->len == frags[i].frag_len);
frag_tot += frags[i].frag_len;
frag_cnt++;
tmp_len -= frags[i].frag_len;
if (tmp_len == 0)
break;
skb = nes_get_next_skb(nesdev, nesqp, skb,
nesqp->pau_rcv_nxt + frag_tot, &ack, &wnd, &fin_rcvd, &rst_rcvd);
if (!skb) {
spin_unlock_irqrestore(&nesqp->pau_lock, flags);
goto out;
} else if (rst_rcvd) {
/* rst received in the middle of fpdu */
for (; i >= 0; i--) {
skb_unlink(frags[i].skb, &nesqp->pau_list);
nes_mgt_free_skb(nesdev, frags[i].skb, PCI_DMA_TODEVICE);
}
cb = (struct nes_rskb_cb *)&skb->cb[0];
frags[0].physaddr = cb->busaddr;
frags[0].physaddr += skb->data - cb->data_start;
frags[0].frag_len = skb->len;
frags[0].skb = skb;
frags[0].cmplt = true;
frag_cnt = 1;
break;
}
cb = (struct nes_rskb_cb *)&skb->cb[0];
}
} else {
/* no data */
frags[0].physaddr = cb->busaddr;
frags[0].frag_len = 0;
frags[0].skb = skb;
frags[0].cmplt = true;
frag_cnt = 1;
}
spin_unlock_irqrestore(&nesqp->pau_lock, flags);
/* Found one */
fpdu_info = kzalloc(sizeof(*fpdu_info), GFP_ATOMIC);
if (fpdu_info == NULL) {
nes_debug(NES_DBG_PAU, "Failed to alloc a fpdu_info.\n");
rc = -ENOMEM;
goto out;
}
fpdu_info->cqp_request = nes_get_cqp_request(nesdev);
if (fpdu_info->cqp_request == NULL) {
nes_debug(NES_DBG_PAU, "Failed to get a cqp_request.\n");
rc = -ENOMEM;
goto out;
}
cb = (struct nes_rskb_cb *)&frags[0].skb->cb[0];
iph = (struct iphdr *)(cb->data_start + ETH_HLEN);
tcph = (struct tcphdr *)(((char *)iph) + (4 * iph->ihl));
fpdu_info->hdr_len = (((unsigned char *)tcph) + 4 * (tcph->doff)) - cb->data_start;
fpdu_info->data_len = fpdu_len;
tot_len = fpdu_info->hdr_len + fpdu_len - ETH_HLEN;
if (frags[0].cmplt) {
fpdu_info->hdr_pbase = cb->busaddr;
fpdu_info->hdr_vbase = NULL;
} else {
fpdu_info->hdr_vbase = pci_alloc_consistent(nesdev->pcidev,
fpdu_info->hdr_len, &fpdu_info->hdr_pbase);
if (!fpdu_info->hdr_vbase) {
nes_debug(NES_DBG_PAU, "Unable to allocate memory for pau first frag\n");
rc = -ENOMEM;
goto out;
}
/* Copy hdrs, adjusting len and seqnum */
memcpy(fpdu_info->hdr_vbase, cb->data_start, fpdu_info->hdr_len);
iph = (struct iphdr *)(fpdu_info->hdr_vbase + ETH_HLEN);
tcph = (struct tcphdr *)(((char *)iph) + (4 * iph->ihl));
}
iph->tot_len = cpu_to_be16(tot_len);
iph->saddr = cpu_to_be32(0x7f000001);
tcph->seq = cpu_to_be32(nesqp->pau_rcv_nxt);
tcph->ack_seq = cpu_to_be32(ack);
tcph->window = cpu_to_be16(wnd);
nesqp->pau_rcv_nxt += fpdu_len + fin_rcvd;
memcpy(fpdu_info->frags, frags, sizeof(fpdu_info->frags));
fpdu_info->frag_cnt = frag_cnt;
fpdu_info->nesqp = nesqp;
*pau_fpdu_info = fpdu_info;
/* Update skb's for next pass */
for (i = 0; i < frag_cnt; i++) {
cb = (struct nes_rskb_cb *)&frags[i].skb->cb[0];
skb_pull(frags[i].skb, frags[i].frag_len);
if (frags[i].skb->len == 0) {
/* Pull skb off the list - it will be freed in the callback */
spin_lock_irqsave(&nesqp->pau_lock, flags);
skb_unlink(frags[i].skb, &nesqp->pau_list);
spin_unlock_irqrestore(&nesqp->pau_lock, flags);
} else {
/* Last skb still has data so update the seq */
iph = (struct iphdr *)(cb->data_start + ETH_HLEN);
tcph = (struct tcphdr *)(((char *)iph) + (4 * iph->ihl));
tcph->seq = cpu_to_be32(nesqp->pau_rcv_nxt);
}
}
out:
if (rc) {
if (fpdu_info) {
if (fpdu_info->cqp_request)
nes_put_cqp_request(nesdev, fpdu_info->cqp_request);
kfree(fpdu_info);
}
}
return rc;
}
/**
* forward_fpdu - send complete fpdus, one at a time
*/
static int forward_fpdus(struct nes_vnic *nesvnic, struct nes_qp *nesqp)
{
struct nes_device *nesdev = nesvnic->nesdev;
struct pau_fpdu_info *fpdu_info;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_cqp_request *cqp_request;
u64 u64tmp;
u32 u32tmp;
int rc;
while (1) {
rc = get_fpdu_info(nesdev, nesqp, &fpdu_info);
if (fpdu_info == NULL)
return rc;
cqp_request = fpdu_info->cqp_request;
cqp_wqe = &cqp_request->cqp_wqe;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_DL_OPCODE_IDX,
NES_CQP_DOWNLOAD_SEGMENT |
(((u32)nesvnic->logical_port) << NES_CQP_OP_LOGICAL_PORT_SHIFT));
u32tmp = fpdu_info->hdr_len << 16;
u32tmp |= fpdu_info->hdr_len + (u32)fpdu_info->data_len;
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_DL_LENGTH_0_TOTAL_IDX,
u32tmp);
u32tmp = (fpdu_info->frags[1].frag_len << 16) | fpdu_info->frags[0].frag_len;
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_LENGTH_2_1_IDX,
u32tmp);
u32tmp = (fpdu_info->frags[3].frag_len << 16) | fpdu_info->frags[2].frag_len;
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_LENGTH_4_3_IDX,
u32tmp);
u64tmp = (u64)fpdu_info->hdr_pbase;
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG0_LOW_IDX,
lower_32_bits(u64tmp));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG0_HIGH_IDX,
upper_32_bits(u64tmp >> 32));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG1_LOW_IDX,
lower_32_bits(fpdu_info->frags[0].physaddr));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG1_HIGH_IDX,
upper_32_bits(fpdu_info->frags[0].physaddr));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG2_LOW_IDX,
lower_32_bits(fpdu_info->frags[1].physaddr));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG2_HIGH_IDX,
upper_32_bits(fpdu_info->frags[1].physaddr));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG3_LOW_IDX,
lower_32_bits(fpdu_info->frags[2].physaddr));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG3_HIGH_IDX,
upper_32_bits(fpdu_info->frags[2].physaddr));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG4_LOW_IDX,
lower_32_bits(fpdu_info->frags[3].physaddr));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_NIC_SQ_WQE_FRAG4_HIGH_IDX,
upper_32_bits(fpdu_info->frags[3].physaddr));
cqp_request->cqp_callback_pointer = fpdu_info;
cqp_request->callback = 1;
cqp_request->cqp_callback = nes_download_callback;
atomic_set(&cqp_request->refcount, 1);
nes_post_cqp_request(nesdev, cqp_request);
}
return 0;
}
static void process_fpdus(struct nes_vnic *nesvnic, struct nes_qp *nesqp)
{
int again = 1;
unsigned long flags;
do {
/* Ignore rc - if it failed, tcp retries will cause it to try again */
forward_fpdus(nesvnic, nesqp);
spin_lock_irqsave(&nesqp->pau_lock, flags);
if (nesqp->pau_pending) {
nesqp->pau_pending = 0;
} else {
nesqp->pau_busy = 0;
again = 0;
}
spin_unlock_irqrestore(&nesqp->pau_lock, flags);
} while (again);
}
/**
* queue_fpdus - Handle fpdu's that hw passed up to sw
*/
static void queue_fpdus(struct sk_buff *skb, struct nes_vnic *nesvnic, struct nes_qp *nesqp)
{
struct sk_buff *tmpskb;
struct nes_rskb_cb *cb;
struct iphdr *iph;
struct tcphdr *tcph;
unsigned char *tcph_end;
u32 rcv_nxt;
u32 rcv_wnd;
u32 seqnum;
u32 len;
bool process_it = false;
unsigned long flags;
/* Move data ptr to after tcp header */
iph = (struct iphdr *)skb->data;
tcph = (struct tcphdr *)(((char *)iph) + (4 * iph->ihl));
seqnum = be32_to_cpu(tcph->seq);
tcph_end = (((char *)tcph) + (4 * tcph->doff));
len = be16_to_cpu(iph->tot_len);
if (skb->len > len)
skb_trim(skb, len);
skb_pull(skb, tcph_end - skb->data);
/* Initialize tracking values */
cb = (struct nes_rskb_cb *)&skb->cb[0];
cb->seqnum = seqnum;
/* Make sure data is in the receive window */
rcv_nxt = nesqp->pau_rcv_nxt;
rcv_wnd = le32_to_cpu(nesqp->nesqp_context->rcv_wnd);
if (!between(seqnum, rcv_nxt, (rcv_nxt + rcv_wnd))) {
nes_mgt_free_skb(nesvnic->nesdev, skb, PCI_DMA_TODEVICE);
nes_rem_ref_cm_node(nesqp->cm_node);
return;
}
spin_lock_irqsave(&nesqp->pau_lock, flags);
if (nesqp->pau_busy)
nesqp->pau_pending = 1;
else
nesqp->pau_busy = 1;
/* Queue skb by sequence number */
if (skb_queue_len(&nesqp->pau_list) == 0) {
skb_queue_head(&nesqp->pau_list, skb);
} else {
tmpskb = nesqp->pau_list.next;
while (tmpskb != (struct sk_buff *)&nesqp->pau_list) {
cb = (struct nes_rskb_cb *)&tmpskb->cb[0];
if (before(seqnum, cb->seqnum))
break;
tmpskb = tmpskb->next;
}
skb_insert(tmpskb, skb, &nesqp->pau_list);
}
if (nesqp->pau_state == PAU_READY)
process_it = true;
spin_unlock_irqrestore(&nesqp->pau_lock, flags);
if (process_it)
process_fpdus(nesvnic, nesqp);
return;
}
/**
* mgt_thread - Handle mgt skbs in a safe context
*/
static int mgt_thread(void *context)
{
struct nes_vnic *nesvnic = context;
struct sk_buff *skb;
struct nes_rskb_cb *cb;
while (!kthread_should_stop()) {
wait_event_interruptible(nesvnic->mgt_wait_queue,
skb_queue_len(&nesvnic->mgt_skb_list) || kthread_should_stop());
while ((skb_queue_len(&nesvnic->mgt_skb_list)) && !kthread_should_stop()) {
skb = skb_dequeue(&nesvnic->mgt_skb_list);
cb = (struct nes_rskb_cb *)&skb->cb[0];
cb->data_start = skb->data - ETH_HLEN;
cb->busaddr = pci_map_single(nesvnic->nesdev->pcidev, cb->data_start,
nesvnic->max_frame_size, PCI_DMA_TODEVICE);
queue_fpdus(skb, nesvnic, cb->nesqp);
}
}
/* Closing down so delete any entries on the queue */
while (skb_queue_len(&nesvnic->mgt_skb_list)) {
skb = skb_dequeue(&nesvnic->mgt_skb_list);
cb = (struct nes_rskb_cb *)&skb->cb[0];
nes_rem_ref_cm_node(cb->nesqp->cm_node);
dev_kfree_skb_any(skb);
}
return 0;
}
/**
* nes_queue_skbs - Queue skb so it can be handled in a thread context
*/
void nes_queue_mgt_skbs(struct sk_buff *skb, struct nes_vnic *nesvnic, struct nes_qp *nesqp)
{
struct nes_rskb_cb *cb;
cb = (struct nes_rskb_cb *)&skb->cb[0];
cb->nesqp = nesqp;
skb_queue_tail(&nesvnic->mgt_skb_list, skb);
wake_up_interruptible(&nesvnic->mgt_wait_queue);
}
void nes_destroy_pau_qp(struct nes_device *nesdev, struct nes_qp *nesqp)
{
struct sk_buff *skb;
unsigned long flags;
atomic_inc(&pau_qps_destroyed);
/* Free packets that have not yet been forwarded */
/* Lock is acquired by skb_dequeue when removing the skb */
spin_lock_irqsave(&nesqp->pau_lock, flags);
while (skb_queue_len(&nesqp->pau_list)) {
skb = skb_dequeue(&nesqp->pau_list);
nes_mgt_free_skb(nesdev, skb, PCI_DMA_TODEVICE);
nes_rem_ref_cm_node(nesqp->cm_node);
}
spin_unlock_irqrestore(&nesqp->pau_lock, flags);
}
static void nes_chg_qh_handler(struct nes_device *nesdev, struct nes_cqp_request *cqp_request)
{
struct pau_qh_chg *qh_chg = cqp_request->cqp_callback_pointer;
struct nes_cqp_request *new_request;
struct nes_hw_cqp_wqe *cqp_wqe;
struct nes_adapter *nesadapter;
struct nes_qp *nesqp;
struct nes_v4_quad nes_quad;
u32 crc_value;
u64 u64temp;
nesadapter = nesdev->nesadapter;
nesqp = qh_chg->nesqp;
/* Should we handle the bad completion */
if (cqp_request->major_code) {
printk(KERN_ERR PFX "Invalid cqp_request major_code=0x%x\n",
cqp_request->major_code);
WARN_ON(1);
}
switch (nesqp->pau_state) {
case PAU_DEL_QH:
/* Old hash code deleted, now set the new one */
nesqp->pau_state = PAU_ADD_LB_QH;
new_request = nes_get_cqp_request(nesdev);
if (new_request == NULL) {
nes_debug(NES_DBG_PAU, "Failed to get a new_request.\n");
WARN_ON(1);
return;
}
memset(&nes_quad, 0, sizeof(nes_quad));
nes_quad.DstIpAdrIndex =
cpu_to_le32((u32)PCI_FUNC(nesdev->pcidev->devfn) << 24);
nes_quad.SrcIpadr = cpu_to_be32(0x7f000001);
nes_quad.TcpPorts[0] = swab16(nesqp->nesqp_context->tcpPorts[1]);
nes_quad.TcpPorts[1] = swab16(nesqp->nesqp_context->tcpPorts[0]);
/* Produce hash key */
crc_value = get_crc_value(&nes_quad);
nesqp->hte_index = cpu_to_be32(crc_value ^ 0xffffffff);
nes_debug(NES_DBG_PAU, "new HTE Index = 0x%08X, CRC = 0x%08X\n",
nesqp->hte_index, nesqp->hte_index & nesadapter->hte_index_mask);
nesqp->hte_index &= nesadapter->hte_index_mask;
nesqp->nesqp_context->hte_index = cpu_to_le32(nesqp->hte_index);
nesqp->nesqp_context->ip0 = cpu_to_le32(0x7f000001);
nesqp->nesqp_context->rcv_nxt = cpu_to_le32(nesqp->pau_rcv_nxt);
cqp_wqe = &new_request->cqp_wqe;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words,
NES_CQP_WQE_OPCODE_IDX, NES_CQP_MANAGE_QUAD_HASH |
NES_CQP_QP_TYPE_IWARP | NES_CQP_QP_CONTEXT_VALID | NES_CQP_QP_IWARP_STATE_RTS);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX, nesqp->hwqp.qp_id);
u64temp = (u64)nesqp->nesqp_context_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_QP_WQE_CONTEXT_LOW_IDX, u64temp);
nes_debug(NES_DBG_PAU, "Waiting for CQP completion for adding the quad hash.\n");
new_request->cqp_callback_pointer = qh_chg;
new_request->callback = 1;
new_request->cqp_callback = nes_chg_qh_handler;
atomic_set(&new_request->refcount, 1);
nes_post_cqp_request(nesdev, new_request);
break;
case PAU_ADD_LB_QH:
/* Start processing the queued fpdu's */
nesqp->pau_state = PAU_READY;
process_fpdus(qh_chg->nesvnic, qh_chg->nesqp);
kfree(qh_chg);
break;
}
}
/**
* nes_change_quad_hash
*/
static int nes_change_quad_hash(struct nes_device *nesdev,
struct nes_vnic *nesvnic, struct nes_qp *nesqp)
{
struct nes_cqp_request *cqp_request = NULL;
struct pau_qh_chg *qh_chg = NULL;
u64 u64temp;
struct nes_hw_cqp_wqe *cqp_wqe;
int ret = 0;
cqp_request = nes_get_cqp_request(nesdev);
if (cqp_request == NULL) {
nes_debug(NES_DBG_PAU, "Failed to get a cqp_request.\n");
ret = -ENOMEM;
goto chg_qh_err;
}
qh_chg = kmalloc(sizeof *qh_chg, GFP_ATOMIC);
if (qh_chg == NULL) {
nes_debug(NES_DBG_PAU, "Failed to get a cqp_request.\n");
ret = -ENOMEM;
goto chg_qh_err;
}
qh_chg->nesdev = nesdev;
qh_chg->nesvnic = nesvnic;
qh_chg->nesqp = nesqp;
nesqp->pau_state = PAU_DEL_QH;
cqp_wqe = &cqp_request->cqp_wqe;
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words,
NES_CQP_WQE_OPCODE_IDX, NES_CQP_MANAGE_QUAD_HASH | NES_CQP_QP_DEL_HTE |
NES_CQP_QP_TYPE_IWARP | NES_CQP_QP_CONTEXT_VALID | NES_CQP_QP_IWARP_STATE_RTS);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX, nesqp->hwqp.qp_id);
u64temp = (u64)nesqp->nesqp_context_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_QP_WQE_CONTEXT_LOW_IDX, u64temp);
nes_debug(NES_DBG_PAU, "Waiting for CQP completion for deleting the quad hash.\n");
cqp_request->cqp_callback_pointer = qh_chg;
cqp_request->callback = 1;
cqp_request->cqp_callback = nes_chg_qh_handler;
atomic_set(&cqp_request->refcount, 1);
nes_post_cqp_request(nesdev, cqp_request);
return ret;
chg_qh_err:
kfree(qh_chg);
if (cqp_request)
nes_put_cqp_request(nesdev, cqp_request);
return ret;
}
/**
* nes_mgt_ce_handler
* This management code deals with any packed and unaligned (pau) fpdu's
* that the hardware cannot handle.
*/
static void nes_mgt_ce_handler(struct nes_device *nesdev, struct nes_hw_nic_cq *cq)
{
struct nes_vnic_mgt *mgtvnic = container_of(cq, struct nes_vnic_mgt, mgt_cq);
struct nes_adapter *nesadapter = nesdev->nesadapter;
u32 head;
u32 cq_size;
u32 cqe_count = 0;
u32 cqe_misc;
u32 qp_id = 0;
u32 skbs_needed;
unsigned long context;
struct nes_qp *nesqp;
struct sk_buff *rx_skb;
struct nes_rskb_cb *cb;
head = cq->cq_head;
cq_size = cq->cq_size;
while (1) {
cqe_misc = le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_NIC_CQE_MISC_IDX]);
if (!(cqe_misc & NES_NIC_CQE_VALID))
break;
nesqp = NULL;
if (cqe_misc & NES_NIC_CQE_ACCQP_VALID) {
qp_id = le32_to_cpu(cq->cq_vbase[head].cqe_words[NES_NIC_CQE_ACCQP_ID_IDX]);
qp_id &= 0x001fffff;
if (qp_id < nesadapter->max_qp) {
context = (unsigned long)nesadapter->qp_table[qp_id - NES_FIRST_QPN];
nesqp = (struct nes_qp *)context;
}
}
if (nesqp) {
if (nesqp->pau_mode == false) {
nesqp->pau_mode = true; /* First time for this qp */
nesqp->pau_rcv_nxt = le32_to_cpu(
cq->cq_vbase[head].cqe_words[NES_NIC_CQE_HASH_RCVNXT]);
skb_queue_head_init(&nesqp->pau_list);
spin_lock_init(&nesqp->pau_lock);
atomic_inc(&pau_qps_created);
nes_change_quad_hash(nesdev, mgtvnic->nesvnic, nesqp);
}
rx_skb = mgtvnic->mgt.rx_skb[mgtvnic->mgt.rq_tail];
rx_skb->len = 0;
skb_put(rx_skb, cqe_misc & 0x0000ffff);
rx_skb->protocol = eth_type_trans(rx_skb, mgtvnic->nesvnic->netdev);
cb = (struct nes_rskb_cb *)&rx_skb->cb[0];
pci_unmap_single(nesdev->pcidev, cb->busaddr, cb->maplen, PCI_DMA_FROMDEVICE);
cb->busaddr = 0;
mgtvnic->mgt.rq_tail++;
mgtvnic->mgt.rq_tail &= mgtvnic->mgt.rq_size - 1;
nes_add_ref_cm_node(nesqp->cm_node);
nes_queue_mgt_skbs(rx_skb, mgtvnic->nesvnic, nesqp);
} else {
printk(KERN_ERR PFX "Invalid QP %d for packed/unaligned handling\n", qp_id);
}
cq->cq_vbase[head].cqe_words[NES_NIC_CQE_MISC_IDX] = 0;
cqe_count++;
if (++head >= cq_size)
head = 0;
if (cqe_count == 255) {
/* Replenish mgt CQ */
nes_write32(nesdev->regs + NES_CQE_ALLOC, cq->cq_number | (cqe_count << 16));
nesdev->currcq_count += cqe_count;
cqe_count = 0;
}
skbs_needed = atomic_inc_return(&mgtvnic->rx_skbs_needed);
if (skbs_needed > (mgtvnic->mgt.rq_size >> 1))
nes_replenish_mgt_rq(mgtvnic);
}
cq->cq_head = head;
nes_write32(nesdev->regs + NES_CQE_ALLOC, NES_CQE_ALLOC_NOTIFY_NEXT |
cq->cq_number | (cqe_count << 16));
nes_read32(nesdev->regs + NES_CQE_ALLOC);
nesdev->currcq_count += cqe_count;
}
/**
* nes_init_mgt_qp
*/
int nes_init_mgt_qp(struct nes_device *nesdev, struct net_device *netdev, struct nes_vnic *nesvnic)
{
struct nes_vnic_mgt *mgtvnic;
u32 counter;
void *vmem;
dma_addr_t pmem;
struct nes_hw_cqp_wqe *cqp_wqe;
u32 cqp_head;
unsigned long flags;
struct nes_hw_nic_qp_context *mgt_context;
u64 u64temp;
struct nes_hw_nic_rq_wqe *mgt_rqe;
struct sk_buff *skb;
u32 wqe_count;
struct nes_rskb_cb *cb;
u32 mgt_mem_size;
void *mgt_vbase;
dma_addr_t mgt_pbase;
int i;
int ret;
/* Allocate space the all mgt QPs once */
mgtvnic = kzalloc(NES_MGT_QP_COUNT * sizeof(struct nes_vnic_mgt), GFP_KERNEL);
if (mgtvnic == NULL) {
nes_debug(NES_DBG_INIT, "Unable to allocate memory for mgt structure\n");
return -ENOMEM;
}
/* Allocate fragment, RQ, and CQ; Reuse CEQ based on the PCI function */
/* We are not sending from this NIC so sq is not allocated */
mgt_mem_size = 256 +
(NES_MGT_WQ_COUNT * sizeof(struct nes_hw_nic_rq_wqe)) +
(NES_MGT_WQ_COUNT * sizeof(struct nes_hw_nic_cqe)) +
sizeof(struct nes_hw_nic_qp_context);
mgt_mem_size = (mgt_mem_size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
mgt_vbase = pci_alloc_consistent(nesdev->pcidev, NES_MGT_QP_COUNT * mgt_mem_size, &mgt_pbase);
if (!mgt_vbase) {
kfree(mgtvnic);
nes_debug(NES_DBG_INIT, "Unable to allocate memory for mgt host descriptor rings\n");
return -ENOMEM;
}
nesvnic->mgt_mem_size = NES_MGT_QP_COUNT * mgt_mem_size;
nesvnic->mgt_vbase = mgt_vbase;
nesvnic->mgt_pbase = mgt_pbase;
skb_queue_head_init(&nesvnic->mgt_skb_list);
init_waitqueue_head(&nesvnic->mgt_wait_queue);
nesvnic->mgt_thread = kthread_run(mgt_thread, nesvnic, "nes_mgt_thread");
for (i = 0; i < NES_MGT_QP_COUNT; i++) {
mgtvnic->nesvnic = nesvnic;
mgtvnic->mgt.qp_id = nesdev->mac_index + NES_MGT_QP_OFFSET + i;
memset(mgt_vbase, 0, mgt_mem_size);
nes_debug(NES_DBG_INIT, "Allocated mgt QP structures at %p (phys = %016lX), size = %u.\n",
mgt_vbase, (unsigned long)mgt_pbase, mgt_mem_size);
vmem = (void *)(((unsigned long)mgt_vbase + (256 - 1)) &
~(unsigned long)(256 - 1));
pmem = (dma_addr_t)(((unsigned long long)mgt_pbase + (256 - 1)) &
~(unsigned long long)(256 - 1));
spin_lock_init(&mgtvnic->mgt.rq_lock);
/* setup the RQ */
mgtvnic->mgt.rq_vbase = vmem;
mgtvnic->mgt.rq_pbase = pmem;
mgtvnic->mgt.rq_head = 0;
mgtvnic->mgt.rq_tail = 0;
mgtvnic->mgt.rq_size = NES_MGT_WQ_COUNT;
/* setup the CQ */
vmem += (NES_MGT_WQ_COUNT * sizeof(struct nes_hw_nic_rq_wqe));
pmem += (NES_MGT_WQ_COUNT * sizeof(struct nes_hw_nic_rq_wqe));
mgtvnic->mgt_cq.cq_number = mgtvnic->mgt.qp_id;
mgtvnic->mgt_cq.cq_vbase = vmem;
mgtvnic->mgt_cq.cq_pbase = pmem;
mgtvnic->mgt_cq.cq_head = 0;
mgtvnic->mgt_cq.cq_size = NES_MGT_WQ_COUNT;
mgtvnic->mgt_cq.ce_handler = nes_mgt_ce_handler;
/* Send CreateCQ request to CQP */
spin_lock_irqsave(&nesdev->cqp.lock, flags);
cqp_head = nesdev->cqp.sq_head;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(
NES_CQP_CREATE_CQ | NES_CQP_CQ_CEQ_VALID |
((u32)mgtvnic->mgt_cq.cq_size << 16));
cqp_wqe->wqe_words[NES_CQP_WQE_ID_IDX] = cpu_to_le32(
mgtvnic->mgt_cq.cq_number | ((u32)nesdev->ceq_index << 16));
u64temp = (u64)mgtvnic->mgt_cq.cq_pbase;
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_CQ_WQE_PBL_LOW_IDX, u64temp);
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_HIGH_IDX] = 0;
u64temp = (unsigned long)&mgtvnic->mgt_cq;
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_LOW_IDX] = cpu_to_le32((u32)(u64temp >> 1));
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_CQ_CONTEXT_HIGH_IDX] =
cpu_to_le32(((u32)((u64temp) >> 33)) & 0x7FFFFFFF);
cqp_wqe->wqe_words[NES_CQP_CQ_WQE_DOORBELL_INDEX_HIGH_IDX] = 0;
if (++cqp_head >= nesdev->cqp.sq_size)
cqp_head = 0;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
/* Send CreateQP request to CQP */
mgt_context = (void *)(&mgtvnic->mgt_cq.cq_vbase[mgtvnic->mgt_cq.cq_size]);
mgt_context->context_words[NES_NIC_CTX_MISC_IDX] =
cpu_to_le32((u32)NES_MGT_CTX_SIZE |
((u32)PCI_FUNC(nesdev->pcidev->devfn) << 12));
nes_debug(NES_DBG_INIT, "RX_WINDOW_BUFFER_PAGE_TABLE_SIZE = 0x%08X, RX_WINDOW_BUFFER_SIZE = 0x%08X\n",
nes_read_indexed(nesdev, NES_IDX_RX_WINDOW_BUFFER_PAGE_TABLE_SIZE),
nes_read_indexed(nesdev, NES_IDX_RX_WINDOW_BUFFER_SIZE));
if (nes_read_indexed(nesdev, NES_IDX_RX_WINDOW_BUFFER_SIZE) != 0)
mgt_context->context_words[NES_NIC_CTX_MISC_IDX] |= cpu_to_le32(NES_NIC_BACK_STORE);
u64temp = (u64)mgtvnic->mgt.rq_pbase;
mgt_context->context_words[NES_NIC_CTX_SQ_LOW_IDX] = cpu_to_le32((u32)u64temp);
mgt_context->context_words[NES_NIC_CTX_SQ_HIGH_IDX] = cpu_to_le32((u32)(u64temp >> 32));
u64temp = (u64)mgtvnic->mgt.rq_pbase;
mgt_context->context_words[NES_NIC_CTX_RQ_LOW_IDX] = cpu_to_le32((u32)u64temp);
mgt_context->context_words[NES_NIC_CTX_RQ_HIGH_IDX] = cpu_to_le32((u32)(u64temp >> 32));
cqp_wqe->wqe_words[NES_CQP_WQE_OPCODE_IDX] = cpu_to_le32(NES_CQP_CREATE_QP |
NES_CQP_QP_TYPE_NIC);
cqp_wqe->wqe_words[NES_CQP_WQE_ID_IDX] = cpu_to_le32(mgtvnic->mgt.qp_id);
u64temp = (u64)mgtvnic->mgt_cq.cq_pbase +
(mgtvnic->mgt_cq.cq_size * sizeof(struct nes_hw_nic_cqe));
set_wqe_64bit_value(cqp_wqe->wqe_words, NES_CQP_QP_WQE_CONTEXT_LOW_IDX, u64temp);
if (++cqp_head >= nesdev->cqp.sq_size)
cqp_head = 0;
nesdev->cqp.sq_head = cqp_head;
barrier();
/* Ring doorbell (2 WQEs) */
nes_write32(nesdev->regs + NES_WQE_ALLOC, 0x02800000 | nesdev->cqp.qp_id);
spin_unlock_irqrestore(&nesdev->cqp.lock, flags);
nes_debug(NES_DBG_INIT, "Waiting for create MGT QP%u to complete.\n",
mgtvnic->mgt.qp_id);
ret = wait_event_timeout(nesdev->cqp.waitq, (nesdev->cqp.sq_tail == cqp_head),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_INIT, "Create MGT QP%u completed, wait_event_timeout ret = %u.\n",
mgtvnic->mgt.qp_id, ret);
if (!ret) {
nes_debug(NES_DBG_INIT, "MGT QP%u create timeout expired\n", mgtvnic->mgt.qp_id);
if (i == 0) {
pci_free_consistent(nesdev->pcidev, nesvnic->mgt_mem_size, nesvnic->mgt_vbase,
nesvnic->mgt_pbase);
kfree(mgtvnic);
} else {
nes_destroy_mgt(nesvnic);
}
return -EIO;
}
/* Populate the RQ */
for (counter = 0; counter < (NES_MGT_WQ_COUNT - 1); counter++) {
skb = dev_alloc_skb(nesvnic->max_frame_size);
if (!skb) {
nes_debug(NES_DBG_INIT, "%s: out of memory for receive skb\n", netdev->name);
return -ENOMEM;
}
skb->dev = netdev;
pmem = pci_map_single(nesdev->pcidev, skb->data,
nesvnic->max_frame_size, PCI_DMA_FROMDEVICE);
cb = (struct nes_rskb_cb *)&skb->cb[0];
cb->busaddr = pmem;
cb->maplen = nesvnic->max_frame_size;
mgt_rqe = &mgtvnic->mgt.rq_vbase[counter];
mgt_rqe->wqe_words[NES_NIC_RQ_WQE_LENGTH_1_0_IDX] = cpu_to_le32((u32)nesvnic->max_frame_size);
mgt_rqe->wqe_words[NES_NIC_RQ_WQE_LENGTH_3_2_IDX] = 0;
mgt_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_LOW_IDX] = cpu_to_le32((u32)pmem);
mgt_rqe->wqe_words[NES_NIC_RQ_WQE_FRAG0_HIGH_IDX] = cpu_to_le32((u32)((u64)pmem >> 32));
mgtvnic->mgt.rx_skb[counter] = skb;
}
init_timer(&mgtvnic->rq_wqes_timer);
mgtvnic->rq_wqes_timer.function = nes_mgt_rq_wqes_timeout;
mgtvnic->rq_wqes_timer.data = (unsigned long)mgtvnic;
wqe_count = NES_MGT_WQ_COUNT - 1;
mgtvnic->mgt.rq_head = wqe_count;
barrier();
do {
counter = min(wqe_count, ((u32)255));
wqe_count -= counter;
nes_write32(nesdev->regs + NES_WQE_ALLOC, (counter << 24) | mgtvnic->mgt.qp_id);
} while (wqe_count);
nes_write32(nesdev->regs + NES_CQE_ALLOC, NES_CQE_ALLOC_NOTIFY_NEXT |
mgtvnic->mgt_cq.cq_number);
nes_read32(nesdev->regs + NES_CQE_ALLOC);
mgt_vbase += mgt_mem_size;
mgt_pbase += mgt_mem_size;
nesvnic->mgtvnic[i] = mgtvnic++;
}
return 0;
}
void nes_destroy_mgt(struct nes_vnic *nesvnic)
{
struct nes_device *nesdev = nesvnic->nesdev;
struct nes_vnic_mgt *mgtvnic;
struct nes_vnic_mgt *first_mgtvnic;
unsigned long flags;
struct nes_hw_cqp_wqe *cqp_wqe;
u32 cqp_head;
struct sk_buff *rx_skb;
int i;
int ret;
kthread_stop(nesvnic->mgt_thread);
/* Free remaining NIC receive buffers */
first_mgtvnic = nesvnic->mgtvnic[0];
for (i = 0; i < NES_MGT_QP_COUNT; i++) {
mgtvnic = nesvnic->mgtvnic[i];
if (mgtvnic == NULL)
continue;
while (mgtvnic->mgt.rq_head != mgtvnic->mgt.rq_tail) {
rx_skb = mgtvnic->mgt.rx_skb[mgtvnic->mgt.rq_tail];
nes_mgt_free_skb(nesdev, rx_skb, PCI_DMA_FROMDEVICE);
mgtvnic->mgt.rq_tail++;
mgtvnic->mgt.rq_tail &= (mgtvnic->mgt.rq_size - 1);
}
spin_lock_irqsave(&nesdev->cqp.lock, flags);
/* Destroy NIC QP */
cqp_head = nesdev->cqp.sq_head;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
(NES_CQP_DESTROY_QP | NES_CQP_QP_TYPE_NIC));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX,
mgtvnic->mgt.qp_id);
if (++cqp_head >= nesdev->cqp.sq_size)
cqp_head = 0;
cqp_wqe = &nesdev->cqp.sq_vbase[cqp_head];
/* Destroy NIC CQ */
nes_fill_init_cqp_wqe(cqp_wqe, nesdev);
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_OPCODE_IDX,
(NES_CQP_DESTROY_CQ | ((u32)mgtvnic->mgt_cq.cq_size << 16)));
set_wqe_32bit_value(cqp_wqe->wqe_words, NES_CQP_WQE_ID_IDX,
(mgtvnic->mgt_cq.cq_number | ((u32)nesdev->ceq_index << 16)));
if (++cqp_head >= nesdev->cqp.sq_size)
cqp_head = 0;
nesdev->cqp.sq_head = cqp_head;
barrier();
/* Ring doorbell (2 WQEs) */
nes_write32(nesdev->regs + NES_WQE_ALLOC, 0x02800000 | nesdev->cqp.qp_id);
spin_unlock_irqrestore(&nesdev->cqp.lock, flags);
nes_debug(NES_DBG_SHUTDOWN, "Waiting for CQP, cqp_head=%u, cqp.sq_head=%u,"
" cqp.sq_tail=%u, cqp.sq_size=%u\n",
cqp_head, nesdev->cqp.sq_head,
nesdev->cqp.sq_tail, nesdev->cqp.sq_size);
ret = wait_event_timeout(nesdev->cqp.waitq, (nesdev->cqp.sq_tail == cqp_head),
NES_EVENT_TIMEOUT);
nes_debug(NES_DBG_SHUTDOWN, "Destroy MGT QP returned, wait_event_timeout ret = %u, cqp_head=%u,"
" cqp.sq_head=%u, cqp.sq_tail=%u\n",
ret, cqp_head, nesdev->cqp.sq_head, nesdev->cqp.sq_tail);
if (!ret)
nes_debug(NES_DBG_SHUTDOWN, "MGT QP%u destroy timeout expired\n",
mgtvnic->mgt.qp_id);
nesvnic->mgtvnic[i] = NULL;
}
if (nesvnic->mgt_vbase) {
pci_free_consistent(nesdev->pcidev, nesvnic->mgt_mem_size, nesvnic->mgt_vbase,
nesvnic->mgt_pbase);
nesvnic->mgt_vbase = NULL;
nesvnic->mgt_pbase = 0;
}
kfree(first_mgtvnic);
}
| gpl-2.0 |
Sudokamikaze/XKernel-taoshan | drivers/infiniband/hw/ipath/ipath_diag.c | 5328 | 15615 | /*
* Copyright (c) 2006, 2007, 2008 QLogic Corporation. All rights reserved.
* Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. 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.
*/
/*
* This file contains support for diagnostic functions. It is accessed by
* opening the ipath_diag device, normally minor number 129. Diagnostic use
* of the InfiniPath chip may render the chip or board unusable until the
* driver is unloaded, or in some cases, until the system is rebooted.
*
* Accesses to the chip through this interface are not similar to going
* through the /sys/bus/pci resource mmap interface.
*/
#include <linux/io.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <linux/export.h>
#include <asm/uaccess.h>
#include "ipath_kernel.h"
#include "ipath_common.h"
int ipath_diag_inuse;
static int diag_set_link;
static int ipath_diag_open(struct inode *in, struct file *fp);
static int ipath_diag_release(struct inode *in, struct file *fp);
static ssize_t ipath_diag_read(struct file *fp, char __user *data,
size_t count, loff_t *off);
static ssize_t ipath_diag_write(struct file *fp, const char __user *data,
size_t count, loff_t *off);
static const struct file_operations diag_file_ops = {
.owner = THIS_MODULE,
.write = ipath_diag_write,
.read = ipath_diag_read,
.open = ipath_diag_open,
.release = ipath_diag_release,
.llseek = default_llseek,
};
static ssize_t ipath_diagpkt_write(struct file *fp,
const char __user *data,
size_t count, loff_t *off);
static const struct file_operations diagpkt_file_ops = {
.owner = THIS_MODULE,
.write = ipath_diagpkt_write,
.llseek = noop_llseek,
};
static atomic_t diagpkt_count = ATOMIC_INIT(0);
static struct cdev *diagpkt_cdev;
static struct device *diagpkt_dev;
int ipath_diag_add(struct ipath_devdata *dd)
{
char name[16];
int ret = 0;
if (atomic_inc_return(&diagpkt_count) == 1) {
ret = ipath_cdev_init(IPATH_DIAGPKT_MINOR,
"ipath_diagpkt", &diagpkt_file_ops,
&diagpkt_cdev, &diagpkt_dev);
if (ret) {
ipath_dev_err(dd, "Couldn't create ipath_diagpkt "
"device: %d", ret);
goto done;
}
}
snprintf(name, sizeof(name), "ipath_diag%d", dd->ipath_unit);
ret = ipath_cdev_init(IPATH_DIAG_MINOR_BASE + dd->ipath_unit, name,
&diag_file_ops, &dd->diag_cdev,
&dd->diag_dev);
if (ret)
ipath_dev_err(dd, "Couldn't create %s device: %d",
name, ret);
done:
return ret;
}
void ipath_diag_remove(struct ipath_devdata *dd)
{
if (atomic_dec_and_test(&diagpkt_count))
ipath_cdev_cleanup(&diagpkt_cdev, &diagpkt_dev);
ipath_cdev_cleanup(&dd->diag_cdev, &dd->diag_dev);
}
/**
* ipath_read_umem64 - read a 64-bit quantity from the chip into user space
* @dd: the infinipath device
* @uaddr: the location to store the data in user memory
* @caddr: the source chip address (full pointer, not offset)
* @count: number of bytes to copy (multiple of 32 bits)
*
* This function also localizes all chip memory accesses.
* The copy should be written such that we read full cacheline packets
* from the chip. This is usually used for a single qword
*
* NOTE: This assumes the chip address is 64-bit aligned.
*/
static int ipath_read_umem64(struct ipath_devdata *dd, void __user *uaddr,
const void __iomem *caddr, size_t count)
{
const u64 __iomem *reg_addr = caddr;
const u64 __iomem *reg_end = reg_addr + (count / sizeof(u64));
int ret;
/* not very efficient, but it works for now */
if (reg_addr < dd->ipath_kregbase || reg_end > dd->ipath_kregend) {
ret = -EINVAL;
goto bail;
}
while (reg_addr < reg_end) {
u64 data = readq(reg_addr);
if (copy_to_user(uaddr, &data, sizeof(u64))) {
ret = -EFAULT;
goto bail;
}
reg_addr++;
uaddr += sizeof(u64);
}
ret = 0;
bail:
return ret;
}
/**
* ipath_write_umem64 - write a 64-bit quantity to the chip from user space
* @dd: the infinipath device
* @caddr: the destination chip address (full pointer, not offset)
* @uaddr: the source of the data in user memory
* @count: the number of bytes to copy (multiple of 32 bits)
*
* This is usually used for a single qword
* NOTE: This assumes the chip address is 64-bit aligned.
*/
static int ipath_write_umem64(struct ipath_devdata *dd, void __iomem *caddr,
const void __user *uaddr, size_t count)
{
u64 __iomem *reg_addr = caddr;
const u64 __iomem *reg_end = reg_addr + (count / sizeof(u64));
int ret;
/* not very efficient, but it works for now */
if (reg_addr < dd->ipath_kregbase || reg_end > dd->ipath_kregend) {
ret = -EINVAL;
goto bail;
}
while (reg_addr < reg_end) {
u64 data;
if (copy_from_user(&data, uaddr, sizeof(data))) {
ret = -EFAULT;
goto bail;
}
writeq(data, reg_addr);
reg_addr++;
uaddr += sizeof(u64);
}
ret = 0;
bail:
return ret;
}
/**
* ipath_read_umem32 - read a 32-bit quantity from the chip into user space
* @dd: the infinipath device
* @uaddr: the location to store the data in user memory
* @caddr: the source chip address (full pointer, not offset)
* @count: number of bytes to copy
*
* read 32 bit values, not 64 bit; for memories that only
* support 32 bit reads; usually a single dword.
*/
static int ipath_read_umem32(struct ipath_devdata *dd, void __user *uaddr,
const void __iomem *caddr, size_t count)
{
const u32 __iomem *reg_addr = caddr;
const u32 __iomem *reg_end = reg_addr + (count / sizeof(u32));
int ret;
if (reg_addr < (u32 __iomem *) dd->ipath_kregbase ||
reg_end > (u32 __iomem *) dd->ipath_kregend) {
ret = -EINVAL;
goto bail;
}
/* not very efficient, but it works for now */
while (reg_addr < reg_end) {
u32 data = readl(reg_addr);
if (copy_to_user(uaddr, &data, sizeof(data))) {
ret = -EFAULT;
goto bail;
}
reg_addr++;
uaddr += sizeof(u32);
}
ret = 0;
bail:
return ret;
}
/**
* ipath_write_umem32 - write a 32-bit quantity to the chip from user space
* @dd: the infinipath device
* @caddr: the destination chip address (full pointer, not offset)
* @uaddr: the source of the data in user memory
* @count: number of bytes to copy
*
* write 32 bit values, not 64 bit; for memories that only
* support 32 bit write; usually a single dword.
*/
static int ipath_write_umem32(struct ipath_devdata *dd, void __iomem *caddr,
const void __user *uaddr, size_t count)
{
u32 __iomem *reg_addr = caddr;
const u32 __iomem *reg_end = reg_addr + (count / sizeof(u32));
int ret;
if (reg_addr < (u32 __iomem *) dd->ipath_kregbase ||
reg_end > (u32 __iomem *) dd->ipath_kregend) {
ret = -EINVAL;
goto bail;
}
while (reg_addr < reg_end) {
u32 data;
if (copy_from_user(&data, uaddr, sizeof(data))) {
ret = -EFAULT;
goto bail;
}
writel(data, reg_addr);
reg_addr++;
uaddr += sizeof(u32);
}
ret = 0;
bail:
return ret;
}
static int ipath_diag_open(struct inode *in, struct file *fp)
{
int unit = iminor(in) - IPATH_DIAG_MINOR_BASE;
struct ipath_devdata *dd;
int ret;
mutex_lock(&ipath_mutex);
if (ipath_diag_inuse) {
ret = -EBUSY;
goto bail;
}
dd = ipath_lookup(unit);
if (dd == NULL || !(dd->ipath_flags & IPATH_PRESENT) ||
!dd->ipath_kregbase) {
ret = -ENODEV;
goto bail;
}
fp->private_data = dd;
ipath_diag_inuse = -2;
diag_set_link = 0;
ret = 0;
/* Only expose a way to reset the device if we
make it into diag mode. */
ipath_expose_reset(&dd->pcidev->dev);
bail:
mutex_unlock(&ipath_mutex);
return ret;
}
/**
* ipath_diagpkt_write - write an IB packet
* @fp: the diag data device file pointer
* @data: ipath_diag_pkt structure saying where to get the packet
* @count: size of data to write
* @off: unused by this code
*/
static ssize_t ipath_diagpkt_write(struct file *fp,
const char __user *data,
size_t count, loff_t *off)
{
u32 __iomem *piobuf;
u32 plen, clen, pbufn;
struct ipath_diag_pkt odp;
struct ipath_diag_xpkt dp;
u32 *tmpbuf = NULL;
struct ipath_devdata *dd;
ssize_t ret = 0;
u64 val;
u32 l_state, lt_state; /* LinkState, LinkTrainingState */
if (count < sizeof(odp)) {
ret = -EINVAL;
goto bail;
}
if (count == sizeof(dp)) {
if (copy_from_user(&dp, data, sizeof(dp))) {
ret = -EFAULT;
goto bail;
}
} else if (copy_from_user(&odp, data, sizeof(odp))) {
ret = -EFAULT;
goto bail;
}
/*
* Due to padding/alignment issues (lessened with new struct)
* the old and new structs are the same length. We need to
* disambiguate them, which we can do because odp.len has never
* been less than the total of LRH+BTH+DETH so far, while
* dp.unit (same offset) unit is unlikely to get that high.
* Similarly, dp.data, the pointer to user at the same offset
* as odp.unit, is almost certainly at least one (512byte)page
* "above" NULL. The if-block below can be omitted if compatibility
* between a new driver and older diagnostic code is unimportant.
* compatibility the other direction (new diags, old driver) is
* handled in the diagnostic code, with a warning.
*/
if (dp.unit >= 20 && dp.data < 512) {
/* very probable version mismatch. Fix it up */
memcpy(&odp, &dp, sizeof(odp));
/* We got a legacy dp, copy elements to dp */
dp.unit = odp.unit;
dp.data = odp.data;
dp.len = odp.len;
dp.pbc_wd = 0; /* Indicate we need to compute PBC wd */
}
/* send count must be an exact number of dwords */
if (dp.len & 3) {
ret = -EINVAL;
goto bail;
}
clen = dp.len >> 2;
dd = ipath_lookup(dp.unit);
if (!dd || !(dd->ipath_flags & IPATH_PRESENT) ||
!dd->ipath_kregbase) {
ipath_cdbg(VERBOSE, "illegal unit %u for diag data send\n",
dp.unit);
ret = -ENODEV;
goto bail;
}
if (ipath_diag_inuse && !diag_set_link &&
!(dd->ipath_flags & IPATH_LINKACTIVE)) {
diag_set_link = 1;
ipath_cdbg(VERBOSE, "Trying to set to set link active for "
"diag pkt\n");
ipath_set_linkstate(dd, IPATH_IB_LINKARM);
ipath_set_linkstate(dd, IPATH_IB_LINKACTIVE);
}
if (!(dd->ipath_flags & IPATH_INITTED)) {
/* no hardware, freeze, etc. */
ipath_cdbg(VERBOSE, "unit %u not usable\n", dd->ipath_unit);
ret = -ENODEV;
goto bail;
}
/*
* Want to skip check for l_state if using custom PBC,
* because we might be trying to force an SM packet out.
* first-cut, skip _all_ state checking in that case.
*/
val = ipath_ib_state(dd, dd->ipath_lastibcstat);
lt_state = ipath_ib_linktrstate(dd, dd->ipath_lastibcstat);
l_state = ipath_ib_linkstate(dd, dd->ipath_lastibcstat);
if (!dp.pbc_wd && (lt_state != INFINIPATH_IBCS_LT_STATE_LINKUP ||
(val != dd->ib_init && val != dd->ib_arm &&
val != dd->ib_active))) {
ipath_cdbg(VERBOSE, "unit %u not ready (state %llx)\n",
dd->ipath_unit, (unsigned long long) val);
ret = -EINVAL;
goto bail;
}
/* need total length before first word written */
/* +1 word is for the qword padding */
plen = sizeof(u32) + dp.len;
if ((plen + 4) > dd->ipath_ibmaxlen) {
ipath_dbg("Pkt len 0x%x > ibmaxlen %x\n",
plen - 4, dd->ipath_ibmaxlen);
ret = -EINVAL;
goto bail; /* before writing pbc */
}
tmpbuf = vmalloc(plen);
if (!tmpbuf) {
dev_info(&dd->pcidev->dev, "Unable to allocate tmp buffer, "
"failing\n");
ret = -ENOMEM;
goto bail;
}
if (copy_from_user(tmpbuf,
(const void __user *) (unsigned long) dp.data,
dp.len)) {
ret = -EFAULT;
goto bail;
}
plen >>= 2; /* in dwords */
piobuf = ipath_getpiobuf(dd, plen, &pbufn);
if (!piobuf) {
ipath_cdbg(VERBOSE, "No PIO buffers avail unit for %u\n",
dd->ipath_unit);
ret = -EBUSY;
goto bail;
}
/* disarm it just to be extra sure */
ipath_disarm_piobufs(dd, pbufn, 1);
if (ipath_debug & __IPATH_PKTDBG)
ipath_cdbg(VERBOSE, "unit %u 0x%x+1w pio%d\n",
dd->ipath_unit, plen - 1, pbufn);
if (dp.pbc_wd == 0)
dp.pbc_wd = plen;
writeq(dp.pbc_wd, piobuf);
/*
* Copy all by the trigger word, then flush, so it's written
* to chip before trigger word, then write trigger word, then
* flush again, so packet is sent.
*/
if (dd->ipath_flags & IPATH_PIO_FLUSH_WC) {
ipath_flush_wc();
__iowrite32_copy(piobuf + 2, tmpbuf, clen - 1);
ipath_flush_wc();
__raw_writel(tmpbuf[clen - 1], piobuf + clen + 1);
} else
__iowrite32_copy(piobuf + 2, tmpbuf, clen);
ipath_flush_wc();
ret = sizeof(dp);
bail:
vfree(tmpbuf);
return ret;
}
static int ipath_diag_release(struct inode *in, struct file *fp)
{
mutex_lock(&ipath_mutex);
ipath_diag_inuse = 0;
fp->private_data = NULL;
mutex_unlock(&ipath_mutex);
return 0;
}
static ssize_t ipath_diag_read(struct file *fp, char __user *data,
size_t count, loff_t *off)
{
struct ipath_devdata *dd = fp->private_data;
void __iomem *kreg_base;
ssize_t ret;
kreg_base = dd->ipath_kregbase;
if (count == 0)
ret = 0;
else if ((count % 4) || (*off % 4))
/* address or length is not 32-bit aligned, hence invalid */
ret = -EINVAL;
else if (ipath_diag_inuse < 1 && (*off || count != 8))
ret = -EINVAL; /* prevent cat /dev/ipath_diag* */
else if ((count % 8) || (*off % 8))
/* address or length not 64-bit aligned; do 32-bit reads */
ret = ipath_read_umem32(dd, data, kreg_base + *off, count);
else
ret = ipath_read_umem64(dd, data, kreg_base + *off, count);
if (ret >= 0) {
*off += count;
ret = count;
if (ipath_diag_inuse == -2)
ipath_diag_inuse++;
}
return ret;
}
static ssize_t ipath_diag_write(struct file *fp, const char __user *data,
size_t count, loff_t *off)
{
struct ipath_devdata *dd = fp->private_data;
void __iomem *kreg_base;
ssize_t ret;
kreg_base = dd->ipath_kregbase;
if (count == 0)
ret = 0;
else if ((count % 4) || (*off % 4))
/* address or length is not 32-bit aligned, hence invalid */
ret = -EINVAL;
else if ((ipath_diag_inuse == -1 && (*off || count != 8)) ||
ipath_diag_inuse == -2) /* read qw off 0, write qw off 0 */
ret = -EINVAL; /* before any other write allowed */
else if ((count % 8) || (*off % 8))
/* address or length not 64-bit aligned; do 32-bit writes */
ret = ipath_write_umem32(dd, kreg_base + *off, data, count);
else
ret = ipath_write_umem64(dd, kreg_base + *off, data, count);
if (ret >= 0) {
*off += count;
ret = count;
if (ipath_diag_inuse == -1)
ipath_diag_inuse = 1; /* all read/write OK now */
}
return ret;
}
| gpl-2.0 |
leeboycott/Baloony | drivers/staging/sbe-2t3e3/dc.c | 7888 | 13356 | /*
* SBE 2T3E3 synchronous serial card driver for Linux
*
* Copyright (C) 2009-2010 Krzysztof Halasa <khc@pm.waw.pl>
*
* 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 code is based on a driver written by SBE Inc.
*/
#include <linux/netdevice.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/io.h>
#include "2t3e3.h"
#include "ctrl.h"
void dc_init(struct channel *sc)
{
u32 val;
dc_stop(sc);
/*dc_reset(sc);*/ /* do not want to reset here */
/*
* BUS_MODE (CSR0)
*/
val = SBE_2T3E3_21143_VAL_READ_LINE_ENABLE |
SBE_2T3E3_21143_VAL_READ_MULTIPLE_ENABLE |
SBE_2T3E3_21143_VAL_TRANSMIT_AUTOMATIC_POLLING_200us |
SBE_2T3E3_21143_VAL_BUS_ARBITRATION_RR;
if (sc->h.command & 16)
val |= SBE_2T3E3_21143_VAL_WRITE_AND_INVALIDATE_ENABLE;
switch (sc->h.cache_size) {
case 32:
val |= SBE_2T3E3_21143_VAL_CACHE_ALIGNMENT_32;
break;
case 16:
val |= SBE_2T3E3_21143_VAL_CACHE_ALIGNMENT_16;
break;
case 8:
val |= SBE_2T3E3_21143_VAL_CACHE_ALIGNMENT_8;
break;
default:
break;
}
dc_write(sc->addr, SBE_2T3E3_21143_REG_BUS_MODE, val);
/* OPERATION_MODE (CSR6) */
val = SBE_2T3E3_21143_VAL_RECEIVE_ALL |
SBE_2T3E3_21143_VAL_MUST_BE_ONE |
SBE_2T3E3_21143_VAL_THRESHOLD_CONTROL_BITS_1 |
SBE_2T3E3_21143_VAL_LOOPBACK_OFF |
SBE_2T3E3_21143_VAL_PASS_ALL_MULTICAST |
SBE_2T3E3_21143_VAL_PROMISCUOUS_MODE |
SBE_2T3E3_21143_VAL_PASS_BAD_FRAMES;
dc_write(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE, val);
if (sc->p.loopback == SBE_2T3E3_LOOPBACK_ETHERNET)
sc->p.loopback = SBE_2T3E3_LOOPBACK_NONE;
#if 0 /* No need to clear this register - and it may be in use */
/*
* BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT (CSR9)
*/
val = 0;
dc_write(sc->addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT, val);
#endif
/*
* GENERAL_PURPOSE_TIMER_AND_INTERRUPT_MITIGATION_CONTROL (CSR11)
*/
val = SBE_2T3E3_21143_VAL_CYCLE_SIZE |
SBE_2T3E3_21143_VAL_TRANSMIT_TIMER |
SBE_2T3E3_21143_VAL_NUMBER_OF_TRANSMIT_PACKETS |
SBE_2T3E3_21143_VAL_RECEIVE_TIMER |
SBE_2T3E3_21143_VAL_NUMBER_OF_RECEIVE_PACKETS;
dc_write(sc->addr, SBE_2T3E3_21143_REG_GENERAL_PURPOSE_TIMER_AND_INTERRUPT_MITIGATION_CONTROL, val);
/* prepare descriptors and data for receive and transmit procecsses */
if (dc_init_descriptor_list(sc) != 0)
return;
/* clear ethernet interrupts status */
dc_write(sc->addr, SBE_2T3E3_21143_REG_STATUS, 0xFFFFFFFF);
/* SIA mode registers */
dc_set_output_port(sc);
}
void dc_start(struct channel *sc)
{
u32 val;
if (!(sc->r.flags & SBE_2T3E3_FLAG_NETWORK_UP))
return;
dc_init(sc);
/* get actual LOS and OOF status */
switch (sc->p.frame_type) {
case SBE_2T3E3_FRAME_TYPE_E3_G751:
case SBE_2T3E3_FRAME_TYPE_E3_G832:
val = exar7250_read(sc, SBE_2T3E3_FRAMER_REG_E3_RX_CONFIGURATION_STATUS_2);
dev_dbg(&sc->pdev->dev, "Start Framer Rx Status = %02X\n", val);
sc->s.OOF = val & SBE_2T3E3_FRAMER_VAL_E3_RX_OOF ? 1 : 0;
break;
case SBE_2T3E3_FRAME_TYPE_T3_CBIT:
case SBE_2T3E3_FRAME_TYPE_T3_M13:
val = exar7250_read(sc, SBE_2T3E3_FRAMER_REG_T3_RX_CONFIGURATION_STATUS);
dev_dbg(&sc->pdev->dev, "Start Framer Rx Status = %02X\n", val);
sc->s.OOF = val & SBE_2T3E3_FRAMER_VAL_T3_RX_OOF ? 1 : 0;
break;
default:
break;
}
cpld_LOS_update(sc);
/* start receive and transmit processes */
dc_transmitter_onoff(sc, SBE_2T3E3_ON);
dc_receiver_onoff(sc, SBE_2T3E3_ON);
/* start interrupts */
dc_start_intr(sc);
}
#define MAX_INT_WAIT_CNT 12000
void dc_stop(struct channel *sc)
{
int wcnt;
/* stop receive and transmit processes */
dc_receiver_onoff(sc, SBE_2T3E3_OFF);
dc_transmitter_onoff(sc, SBE_2T3E3_OFF);
/* turn off ethernet interrupts */
dc_stop_intr(sc);
/* wait to ensure the interrupts have been completed */
for (wcnt = 0; wcnt < MAX_INT_WAIT_CNT; wcnt++) {
udelay(5);
if (!sc->interrupt_active)
break;
}
if (wcnt >= MAX_INT_WAIT_CNT)
dev_warn(&sc->pdev->dev, "SBE 2T3E3: Interrupt active too long\n");
/* clear all receive/transmit data */
dc_drop_descriptor_list(sc);
}
void dc_start_intr(struct channel *sc)
{
if (sc->p.loopback == SBE_2T3E3_LOOPBACK_NONE && sc->s.OOF)
return;
if (sc->p.receiver_on || sc->p.transmitter_on) {
if (!sc->ether.interrupt_enable_mask)
dc_write(sc->addr, SBE_2T3E3_21143_REG_STATUS, 0xFFFFFFFF);
sc->ether.interrupt_enable_mask =
SBE_2T3E3_21143_VAL_NORMAL_INTERRUPT_SUMMARY_ENABLE |
SBE_2T3E3_21143_VAL_ABNORMAL_INTERRUPT_SUMMARY_ENABLE |
SBE_2T3E3_21143_VAL_RECEIVE_STOPPED_ENABLE |
SBE_2T3E3_21143_VAL_RECEIVE_BUFFER_UNAVAILABLE_ENABLE |
SBE_2T3E3_21143_VAL_RECEIVE_INTERRUPT_ENABLE |
SBE_2T3E3_21143_VAL_TRANSMIT_UNDERFLOW_INTERRUPT_ENABLE |
SBE_2T3E3_21143_VAL_TRANSMIT_BUFFER_UNAVAILABLE_ENABLE |
SBE_2T3E3_21143_VAL_TRANSMIT_STOPPED_ENABLE |
SBE_2T3E3_21143_VAL_TRANSMIT_INTERRUPT_ENABLE;
dc_write(sc->addr, SBE_2T3E3_21143_REG_INTERRUPT_ENABLE,
sc->ether.interrupt_enable_mask);
}
}
void dc_stop_intr(struct channel *sc)
{
sc->ether.interrupt_enable_mask = 0;
dc_write(sc->addr, SBE_2T3E3_21143_REG_INTERRUPT_ENABLE, 0);
}
void dc_reset(struct channel *sc)
{
/* turn off ethernet interrupts */
dc_write(sc->addr, SBE_2T3E3_21143_REG_INTERRUPT_ENABLE, 0);
dc_write(sc->addr, SBE_2T3E3_21143_REG_STATUS, 0xFFFFFFFF);
/* software reset */
dc_set_bits(sc->addr, SBE_2T3E3_21143_REG_BUS_MODE,
SBE_2T3E3_21143_VAL_SOFTWARE_RESET);
udelay(4); /* 50 PCI cycles < 2us */
/* clear hardware configuration */
dc_write(sc->addr, SBE_2T3E3_21143_REG_BUS_MODE, 0);
/* clear software configuration */
dc_write(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE, 0);
/* turn off SIA reset */
dc_set_bits(sc->addr, SBE_2T3E3_21143_REG_SIA_CONNECTIVITY,
SBE_2T3E3_21143_VAL_SIA_RESET);
dc_write(sc->addr, SBE_2T3E3_21143_REG_SIA_TRANSMIT_AND_RECEIVE, 0);
dc_write(sc->addr, SBE_2T3E3_21143_REG_SIA_AND_GENERAL_PURPOSE_PORT, 0);
}
void dc_receiver_onoff(struct channel *sc, u32 mode)
{
u32 i, state = 0;
if (sc->p.receiver_on == mode)
return;
switch (mode) {
case SBE_2T3E3_OFF:
if (dc_read(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE) &
SBE_2T3E3_21143_VAL_RECEIVE_START) {
dc_clear_bits(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE,
SBE_2T3E3_21143_VAL_RECEIVE_START);
for (i = 0; i < 16; i++) {
state = dc_read(sc->addr, SBE_2T3E3_21143_REG_STATUS) &
SBE_2T3E3_21143_VAL_RECEIVE_PROCESS_STATE;
if (state == SBE_2T3E3_21143_VAL_RX_STOPPED)
break;
udelay(5);
}
if (state != SBE_2T3E3_21143_VAL_RX_STOPPED)
dev_warn(&sc->pdev->dev, "SBE 2T3E3: Rx failed to stop\n");
else
dev_info(&sc->pdev->dev, "SBE 2T3E3: Rx off\n");
}
break;
case SBE_2T3E3_ON:
dc_set_bits(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE,
SBE_2T3E3_21143_VAL_RECEIVE_START);
udelay(100);
dc_write(sc->addr, SBE_2T3E3_21143_REG_RECEIVE_POLL_DEMAND, 0xFFFFFFFF);
break;
default:
return;
}
sc->p.receiver_on = mode;
}
void dc_transmitter_onoff(struct channel *sc, u32 mode)
{
u32 i, state = 0;
if (sc->p.transmitter_on == mode)
return;
switch (mode) {
case SBE_2T3E3_OFF:
if (dc_read(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE) &
SBE_2T3E3_21143_VAL_TRANSMISSION_START) {
dc_clear_bits(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE,
SBE_2T3E3_21143_VAL_TRANSMISSION_START);
for (i = 0; i < 16; i++) {
state = dc_read(sc->addr, SBE_2T3E3_21143_REG_STATUS) &
SBE_2T3E3_21143_VAL_TRANSMISSION_PROCESS_STATE;
if (state == SBE_2T3E3_21143_VAL_TX_STOPPED)
break;
udelay(5);
}
if (state != SBE_2T3E3_21143_VAL_TX_STOPPED)
dev_warn(&sc->pdev->dev, "SBE 2T3E3: Tx failed to stop\n");
}
break;
case SBE_2T3E3_ON:
dc_set_bits(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE,
SBE_2T3E3_21143_VAL_TRANSMISSION_START);
udelay(100);
dc_write(sc->addr, SBE_2T3E3_21143_REG_TRANSMIT_POLL_DEMAND, 0xFFFFFFFF);
break;
default:
return;
}
sc->p.transmitter_on = mode;
}
void dc_set_loopback(struct channel *sc, u32 mode)
{
u32 val;
switch (mode) {
case SBE_2T3E3_21143_VAL_LOOPBACK_OFF:
case SBE_2T3E3_21143_VAL_LOOPBACK_INTERNAL:
break;
default:
return;
}
#if 0
/* restart SIA */
dc_clear_bits(sc->addr, SBE_2T3E3_21143_REG_SIA_CONNECTIVITY,
SBE_2T3E3_21143_VAL_SIA_RESET);
udelay(1000);
dc_set_bits(sc->addr, SBE_2T3E3_21143_REG_SIA_CONNECTIVITY,
SBE_2T3E3_21143_VAL_SIA_RESET);
#endif
/* select loopback mode */
val = dc_read(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE) &
~SBE_2T3E3_21143_VAL_OPERATING_MODE;
val |= mode;
dc_write(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE, val);
if (mode == SBE_2T3E3_21143_VAL_LOOPBACK_OFF)
dc_set_bits(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE,
SBE_2T3E3_21143_VAL_FULL_DUPLEX_MODE);
else
dc_clear_bits(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE,
SBE_2T3E3_21143_VAL_FULL_DUPLEX_MODE);
}
u32 dc_init_descriptor_list(struct channel *sc)
{
u32 i, j;
struct sk_buff *m;
if (sc->ether.rx_ring == NULL)
sc->ether.rx_ring = kzalloc(SBE_2T3E3_RX_DESC_RING_SIZE *
sizeof(t3e3_rx_desc_t), GFP_KERNEL);
if (sc->ether.rx_ring == NULL) {
dev_err(&sc->pdev->dev, "SBE 2T3E3: no buffer space for RX ring\n");
return ENOMEM;
}
if (sc->ether.tx_ring == NULL)
sc->ether.tx_ring = kzalloc(SBE_2T3E3_TX_DESC_RING_SIZE *
sizeof(t3e3_tx_desc_t), GFP_KERNEL);
if (sc->ether.tx_ring == NULL) {
kfree(sc->ether.rx_ring);
sc->ether.rx_ring = NULL;
dev_err(&sc->pdev->dev, "SBE 2T3E3: no buffer space for RX ring\n");
return ENOMEM;
}
/*
* Receive ring
*/
for (i = 0; i < SBE_2T3E3_RX_DESC_RING_SIZE; i++) {
sc->ether.rx_ring[i].rdes0 = SBE_2T3E3_RX_DESC_21143_OWN;
sc->ether.rx_ring[i].rdes1 =
SBE_2T3E3_RX_DESC_SECOND_ADDRESS_CHAINED | SBE_2T3E3_MTU;
if (sc->ether.rx_data[i] == NULL) {
if (!(m = dev_alloc_skb(MCLBYTES))) {
for (j = 0; j < i; j++) {
dev_kfree_skb_any(sc->ether.rx_data[j]);
sc->ether.rx_data[j] = NULL;
}
kfree(sc->ether.rx_ring);
sc->ether.rx_ring = NULL;
kfree(sc->ether.tx_ring);
sc->ether.tx_ring = NULL;
dev_err(&sc->pdev->dev, "SBE 2T3E3: token_alloc err:"
" no buffer space for RX ring\n");
return ENOBUFS;
}
sc->ether.rx_data[i] = m;
}
sc->ether.rx_ring[i].rdes2 = virt_to_phys(sc->ether.rx_data[i]->data);
sc->ether.rx_ring[i].rdes3 = virt_to_phys(
&sc->ether.rx_ring[(i + 1) % SBE_2T3E3_RX_DESC_RING_SIZE]);
}
sc->ether.rx_ring[SBE_2T3E3_RX_DESC_RING_SIZE - 1].rdes1 |=
SBE_2T3E3_RX_DESC_END_OF_RING;
sc->ether.rx_ring_current_read = 0;
dc_write(sc->addr, SBE_2T3E3_21143_REG_RECEIVE_LIST_BASE_ADDRESS,
virt_to_phys(&sc->ether.rx_ring[0]));
/*
* Transmit ring
*/
for (i = 0; i < SBE_2T3E3_TX_DESC_RING_SIZE; i++) {
sc->ether.tx_ring[i].tdes0 = 0;
sc->ether.tx_ring[i].tdes1 = SBE_2T3E3_TX_DESC_SECOND_ADDRESS_CHAINED |
SBE_2T3E3_TX_DESC_DISABLE_PADDING;
sc->ether.tx_ring[i].tdes2 = 0;
sc->ether.tx_data[i] = NULL;
sc->ether.tx_ring[i].tdes3 = virt_to_phys(
&sc->ether.tx_ring[(i + 1) % SBE_2T3E3_TX_DESC_RING_SIZE]);
}
sc->ether.tx_ring[SBE_2T3E3_TX_DESC_RING_SIZE - 1].tdes1 |=
SBE_2T3E3_TX_DESC_END_OF_RING;
dc_write(sc->addr, SBE_2T3E3_21143_REG_TRANSMIT_LIST_BASE_ADDRESS,
virt_to_phys(&sc->ether.tx_ring[0]));
sc->ether.tx_ring_current_read = 0;
sc->ether.tx_ring_current_write = 0;
sc->ether.tx_free_cnt = SBE_2T3E3_TX_DESC_RING_SIZE;
spin_lock_init(&sc->ether.tx_lock);
return 0;
}
void dc_clear_descriptor_list(struct channel *sc)
{
u32 i;
/* clear CSR3 and CSR4 */
dc_write(sc->addr, SBE_2T3E3_21143_REG_RECEIVE_LIST_BASE_ADDRESS, 0);
dc_write(sc->addr, SBE_2T3E3_21143_REG_TRANSMIT_LIST_BASE_ADDRESS, 0);
/* free all data buffers on TX ring */
for (i = 0; i < SBE_2T3E3_TX_DESC_RING_SIZE; i++) {
if (sc->ether.tx_data[i] != NULL) {
dev_kfree_skb_any(sc->ether.tx_data[i]);
sc->ether.tx_data[i] = NULL;
}
}
}
void dc_drop_descriptor_list(struct channel *sc)
{
u32 i;
dc_clear_descriptor_list(sc);
/* free all data buffers on RX ring */
for (i = 0; i < SBE_2T3E3_RX_DESC_RING_SIZE; i++) {
if (sc->ether.rx_data[i] != NULL) {
dev_kfree_skb_any(sc->ether.rx_data[i]);
sc->ether.rx_data[i] = NULL;
}
}
kfree(sc->ether.rx_ring);
sc->ether.rx_ring = NULL;
kfree(sc->ether.tx_ring);
sc->ether.tx_ring = NULL;
}
void dc_set_output_port(struct channel *sc)
{
dc_clear_bits(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE,
SBE_2T3E3_21143_VAL_PORT_SELECT);
dc_write(sc->addr, SBE_2T3E3_21143_REG_SIA_STATUS, 0x00000301);
dc_write(sc->addr, SBE_2T3E3_21143_REG_SIA_CONNECTIVITY, 0);
dc_write(sc->addr, SBE_2T3E3_21143_REG_SIA_TRANSMIT_AND_RECEIVE, 0);
dc_write(sc->addr, SBE_2T3E3_21143_REG_SIA_AND_GENERAL_PURPOSE_PORT, 0x08000011);
dc_set_bits(sc->addr, SBE_2T3E3_21143_REG_OPERATION_MODE,
SBE_2T3E3_21143_VAL_TRANSMIT_THRESHOLD_MODE_100Mbs |
SBE_2T3E3_21143_VAL_HEARTBEAT_DISABLE |
SBE_2T3E3_21143_VAL_PORT_SELECT |
SBE_2T3E3_21143_VAL_FULL_DUPLEX_MODE);
}
void dc_restart(struct channel *sc)
{
dev_warn(&sc->pdev->dev, "SBE 2T3E3: 21143 restart\n");
dc_stop(sc);
dc_reset(sc);
dc_init(sc); /* stop + reset + init */
dc_start(sc);
}
| gpl-2.0 |
Genymobile/genymotion-kernel | drivers/tty/serial/8250/8250_fsl.c | 7888 | 1804 | #include <linux/serial_reg.h>
#include <linux/serial_8250.h>
#include "8250.h"
/*
* Freescale 16550 UART "driver", Copyright (C) 2011 Paul Gortmaker.
*
* 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 isn't a full driver; it just provides an alternate IRQ
* handler to deal with an errata. Everything else is just
* using the bog standard 8250 support.
*
* We follow code flow of serial8250_default_handle_irq() but add
* a check for a break and insert a dummy read on the Rx for the
* immediately following IRQ event.
*
* We re-use the already existing "bug handling" lsr_saved_flags
* field to carry the "what we just did" information from the one
* IRQ event to the next one.
*/
int fsl8250_handle_irq(struct uart_port *port)
{
unsigned char lsr, orig_lsr;
unsigned long flags;
unsigned int iir;
struct uart_8250_port *up =
container_of(port, struct uart_8250_port, port);
spin_lock_irqsave(&up->port.lock, flags);
iir = port->serial_in(port, UART_IIR);
if (iir & UART_IIR_NO_INT) {
spin_unlock_irqrestore(&up->port.lock, flags);
return 0;
}
/* This is the WAR; if last event was BRK, then read and return */
if (unlikely(up->lsr_saved_flags & UART_LSR_BI)) {
up->lsr_saved_flags &= ~UART_LSR_BI;
port->serial_in(port, UART_RX);
spin_unlock_irqrestore(&up->port.lock, flags);
return 1;
}
lsr = orig_lsr = up->port.serial_in(&up->port, UART_LSR);
if (lsr & (UART_LSR_DR | UART_LSR_BI))
lsr = serial8250_rx_chars(up, lsr);
serial8250_modem_status(up);
if (lsr & UART_LSR_THRE)
serial8250_tx_chars(up);
up->lsr_saved_flags = orig_lsr;
spin_unlock_irqrestore(&up->port.lock, flags);
return 1;
}
| gpl-2.0 |
arco/samsung-kernel-msm7x30 | net/ipv6/xfrm6_mode_beet.c | 8144 | 3318 | /*
* xfrm6_mode_beet.c - BEET mode encapsulation for IPv6.
*
* Copyright (c) 2006 Diego Beltrami <diego.beltrami@gmail.com>
* Miika Komu <miika@iki.fi>
* Herbert Xu <herbert@gondor.apana.org.au>
* Abhinav Pathak <abhinav.pathak@hiit.fi>
* Jeff Ahrenholz <ahrenholz@gmail.com>
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/stringify.h>
#include <net/dsfield.h>
#include <net/dst.h>
#include <net/inet_ecn.h>
#include <net/ipv6.h>
#include <net/xfrm.h>
static void xfrm6_beet_make_header(struct sk_buff *skb)
{
struct ipv6hdr *iph = ipv6_hdr(skb);
iph->version = 6;
memcpy(iph->flow_lbl, XFRM_MODE_SKB_CB(skb)->flow_lbl,
sizeof(iph->flow_lbl));
iph->nexthdr = XFRM_MODE_SKB_CB(skb)->protocol;
ipv6_change_dsfield(iph, 0, XFRM_MODE_SKB_CB(skb)->tos);
iph->hop_limit = XFRM_MODE_SKB_CB(skb)->ttl;
}
/* Add encapsulation header.
*
* The top IP header will be constructed per draft-nikander-esp-beet-mode-06.txt.
*/
static int xfrm6_beet_output(struct xfrm_state *x, struct sk_buff *skb)
{
struct ipv6hdr *top_iph;
struct ip_beet_phdr *ph;
int optlen, hdr_len;
hdr_len = 0;
optlen = XFRM_MODE_SKB_CB(skb)->optlen;
if (unlikely(optlen))
hdr_len += IPV4_BEET_PHMAXLEN - (optlen & 4);
skb_set_network_header(skb, -x->props.header_len - hdr_len);
if (x->sel.family != AF_INET6)
skb->network_header += IPV4_BEET_PHMAXLEN;
skb->mac_header = skb->network_header +
offsetof(struct ipv6hdr, nexthdr);
skb->transport_header = skb->network_header + sizeof(*top_iph);
ph = (struct ip_beet_phdr *)__skb_pull(skb, XFRM_MODE_SKB_CB(skb)->ihl-hdr_len);
xfrm6_beet_make_header(skb);
top_iph = ipv6_hdr(skb);
if (unlikely(optlen)) {
BUG_ON(optlen < 0);
ph->padlen = 4 - (optlen & 4);
ph->hdrlen = optlen / 8;
ph->nexthdr = top_iph->nexthdr;
if (ph->padlen)
memset(ph + 1, IPOPT_NOP, ph->padlen);
top_iph->nexthdr = IPPROTO_BEETPH;
}
top_iph->saddr = *(struct in6_addr *)&x->props.saddr;
top_iph->daddr = *(struct in6_addr *)&x->id.daddr;
return 0;
}
static int xfrm6_beet_input(struct xfrm_state *x, struct sk_buff *skb)
{
struct ipv6hdr *ip6h;
int size = sizeof(struct ipv6hdr);
int err;
err = skb_cow_head(skb, size + skb->mac_len);
if (err)
goto out;
__skb_push(skb, size);
skb_reset_network_header(skb);
skb_mac_header_rebuild(skb);
xfrm6_beet_make_header(skb);
ip6h = ipv6_hdr(skb);
ip6h->payload_len = htons(skb->len - size);
ip6h->daddr = *(struct in6_addr *)&x->sel.daddr.a6;
ip6h->saddr = *(struct in6_addr *)&x->sel.saddr.a6;
err = 0;
out:
return err;
}
static struct xfrm_mode xfrm6_beet_mode = {
.input2 = xfrm6_beet_input,
.input = xfrm_prepare_input,
.output2 = xfrm6_beet_output,
.output = xfrm6_prepare_output,
.owner = THIS_MODULE,
.encap = XFRM_MODE_BEET,
.flags = XFRM_MODE_FLAG_TUNNEL,
};
static int __init xfrm6_beet_init(void)
{
return xfrm_register_mode(&xfrm6_beet_mode, AF_INET6);
}
static void __exit xfrm6_beet_exit(void)
{
int err;
err = xfrm_unregister_mode(&xfrm6_beet_mode, AF_INET6);
BUG_ON(err);
}
module_init(xfrm6_beet_init);
module_exit(xfrm6_beet_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_XFRM_MODE(AF_INET6, XFRM_MODE_BEET);
| gpl-2.0 |
CheckYourScreen/Arsenic.Kernel | lib/textsearch.c | 10704 | 9800 | /*
* lib/textsearch.c Generic text search interface
*
* 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.
*
* Authors: Thomas Graf <tgraf@suug.ch>
* Pablo Neira Ayuso <pablo@netfilter.org>
*
* ==========================================================================
*
* INTRODUCTION
*
* The textsearch infrastructure provides text searching facilities for
* both linear and non-linear data. Individual search algorithms are
* implemented in modules and chosen by the user.
*
* ARCHITECTURE
*
* User
* +----------------+
* | finish()|<--------------(6)-----------------+
* |get_next_block()|<--------------(5)---------------+ |
* | | Algorithm | |
* | | +------------------------------+
* | | | init() find() destroy() |
* | | +------------------------------+
* | | Core API ^ ^ ^
* | | +---------------+ (2) (4) (8)
* | (1)|----->| prepare() |---+ | |
* | (3)|----->| find()/next() |-----------+ |
* | (7)|----->| destroy() |----------------------+
* +----------------+ +---------------+
*
* (1) User configures a search by calling _prepare() specifying the
* search parameters such as the pattern and algorithm name.
* (2) Core requests the algorithm to allocate and initialize a search
* configuration according to the specified parameters.
* (3) User starts the search(es) by calling _find() or _next() to
* fetch subsequent occurrences. A state variable is provided
* to the algorithm to store persistent variables.
* (4) Core eventually resets the search offset and forwards the find()
* request to the algorithm.
* (5) Algorithm calls get_next_block() provided by the user continuously
* to fetch the data to be searched in block by block.
* (6) Algorithm invokes finish() after the last call to get_next_block
* to clean up any leftovers from get_next_block. (Optional)
* (7) User destroys the configuration by calling _destroy().
* (8) Core notifies the algorithm to destroy algorithm specific
* allocations. (Optional)
*
* USAGE
*
* Before a search can be performed, a configuration must be created
* by calling textsearch_prepare() specifying the searching algorithm,
* the pattern to look for and flags. As a flag, you can set TS_IGNORECASE
* to perform case insensitive matching. But it might slow down
* performance of algorithm, so you should use it at own your risk.
* The returned configuration may then be used for an arbitrary
* amount of times and even in parallel as long as a separate struct
* ts_state variable is provided to every instance.
*
* The actual search is performed by either calling textsearch_find_-
* continuous() for linear data or by providing an own get_next_block()
* implementation and calling textsearch_find(). Both functions return
* the position of the first occurrence of the pattern or UINT_MAX if
* no match was found. Subsequent occurrences can be found by calling
* textsearch_next() regardless of the linearity of the data.
*
* Once you're done using a configuration it must be given back via
* textsearch_destroy.
*
* EXAMPLE
*
* int pos;
* struct ts_config *conf;
* struct ts_state state;
* const char *pattern = "chicken";
* const char *example = "We dance the funky chicken";
*
* conf = textsearch_prepare("kmp", pattern, strlen(pattern),
* GFP_KERNEL, TS_AUTOLOAD);
* if (IS_ERR(conf)) {
* err = PTR_ERR(conf);
* goto errout;
* }
*
* pos = textsearch_find_continuous(conf, &state, example, strlen(example));
* if (pos != UINT_MAX)
* panic("Oh my god, dancing chickens at %d\n", pos);
*
* textsearch_destroy(conf);
* ==========================================================================
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/rculist.h>
#include <linux/rcupdate.h>
#include <linux/err.h>
#include <linux/textsearch.h>
#include <linux/slab.h>
static LIST_HEAD(ts_ops);
static DEFINE_SPINLOCK(ts_mod_lock);
static inline struct ts_ops *lookup_ts_algo(const char *name)
{
struct ts_ops *o;
rcu_read_lock();
list_for_each_entry_rcu(o, &ts_ops, list) {
if (!strcmp(name, o->name)) {
if (!try_module_get(o->owner))
o = NULL;
rcu_read_unlock();
return o;
}
}
rcu_read_unlock();
return NULL;
}
/**
* textsearch_register - register a textsearch module
* @ops: operations lookup table
*
* This function must be called by textsearch modules to announce
* their presence. The specified &@ops must have %name set to a
* unique identifier and the callbacks find(), init(), get_pattern(),
* and get_pattern_len() must be implemented.
*
* Returns 0 or -EEXISTS if another module has already registered
* with same name.
*/
int textsearch_register(struct ts_ops *ops)
{
int err = -EEXIST;
struct ts_ops *o;
if (ops->name == NULL || ops->find == NULL || ops->init == NULL ||
ops->get_pattern == NULL || ops->get_pattern_len == NULL)
return -EINVAL;
spin_lock(&ts_mod_lock);
list_for_each_entry(o, &ts_ops, list) {
if (!strcmp(ops->name, o->name))
goto errout;
}
list_add_tail_rcu(&ops->list, &ts_ops);
err = 0;
errout:
spin_unlock(&ts_mod_lock);
return err;
}
/**
* textsearch_unregister - unregister a textsearch module
* @ops: operations lookup table
*
* This function must be called by textsearch modules to announce
* their disappearance for examples when the module gets unloaded.
* The &ops parameter must be the same as the one during the
* registration.
*
* Returns 0 on success or -ENOENT if no matching textsearch
* registration was found.
*/
int textsearch_unregister(struct ts_ops *ops)
{
int err = 0;
struct ts_ops *o;
spin_lock(&ts_mod_lock);
list_for_each_entry(o, &ts_ops, list) {
if (o == ops) {
list_del_rcu(&o->list);
goto out;
}
}
err = -ENOENT;
out:
spin_unlock(&ts_mod_lock);
return err;
}
struct ts_linear_state
{
unsigned int len;
const void *data;
};
static unsigned int get_linear_data(unsigned int consumed, const u8 **dst,
struct ts_config *conf,
struct ts_state *state)
{
struct ts_linear_state *st = (struct ts_linear_state *) state->cb;
if (likely(consumed < st->len)) {
*dst = st->data + consumed;
return st->len - consumed;
}
return 0;
}
/**
* textsearch_find_continuous - search a pattern in continuous/linear data
* @conf: search configuration
* @state: search state
* @data: data to search in
* @len: length of data
*
* A simplified version of textsearch_find() for continuous/linear data.
* Call textsearch_next() to retrieve subsequent matches.
*
* Returns the position of first occurrence of the pattern or
* %UINT_MAX if no occurrence was found.
*/
unsigned int textsearch_find_continuous(struct ts_config *conf,
struct ts_state *state,
const void *data, unsigned int len)
{
struct ts_linear_state *st = (struct ts_linear_state *) state->cb;
conf->get_next_block = get_linear_data;
st->data = data;
st->len = len;
return textsearch_find(conf, state);
}
/**
* textsearch_prepare - Prepare a search
* @algo: name of search algorithm
* @pattern: pattern data
* @len: length of pattern
* @gfp_mask: allocation mask
* @flags: search flags
*
* Looks up the search algorithm module and creates a new textsearch
* configuration for the specified pattern. Upon completion all
* necessary refcnts are held and the configuration must be put back
* using textsearch_put() after usage.
*
* Note: The format of the pattern may not be compatible between
* the various search algorithms.
*
* Returns a new textsearch configuration according to the specified
* parameters or a ERR_PTR(). If a zero length pattern is passed, this
* function returns EINVAL.
*/
struct ts_config *textsearch_prepare(const char *algo, const void *pattern,
unsigned int len, gfp_t gfp_mask, int flags)
{
int err = -ENOENT;
struct ts_config *conf;
struct ts_ops *ops;
if (len == 0)
return ERR_PTR(-EINVAL);
ops = lookup_ts_algo(algo);
#ifdef CONFIG_MODULES
/*
* Why not always autoload you may ask. Some users are
* in a situation where requesting a module may deadlock,
* especially when the module is located on a NFS mount.
*/
if (ops == NULL && flags & TS_AUTOLOAD) {
request_module("ts_%s", algo);
ops = lookup_ts_algo(algo);
}
#endif
if (ops == NULL)
goto errout;
conf = ops->init(pattern, len, gfp_mask, flags);
if (IS_ERR(conf)) {
err = PTR_ERR(conf);
goto errout;
}
conf->ops = ops;
return conf;
errout:
if (ops)
module_put(ops->owner);
return ERR_PTR(err);
}
/**
* textsearch_destroy - destroy a search configuration
* @conf: search configuration
*
* Releases all references of the configuration and frees
* up the memory.
*/
void textsearch_destroy(struct ts_config *conf)
{
if (conf->ops) {
if (conf->ops->destroy)
conf->ops->destroy(conf);
module_put(conf->ops->owner);
}
kfree(conf);
}
EXPORT_SYMBOL(textsearch_register);
EXPORT_SYMBOL(textsearch_unregister);
EXPORT_SYMBOL(textsearch_prepare);
EXPORT_SYMBOL(textsearch_find_continuous);
EXPORT_SYMBOL(textsearch_destroy);
| gpl-2.0 |
ZdrowyGosciu/kernel_lge_d802_v30d | sound/core/seq/oss/seq_oss_timer.c | 11984 | 6154 | /*
* OSS compatible sequencer driver
*
* Timer control routines
*
* Copyright (C) 1998,99 Takashi Iwai <tiwai@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "seq_oss_timer.h"
#include "seq_oss_event.h"
#include <sound/seq_oss_legacy.h>
#include <linux/slab.h>
/*
*/
#define MIN_OSS_TEMPO 8
#define MAX_OSS_TEMPO 360
#define MIN_OSS_TIMEBASE 1
#define MAX_OSS_TIMEBASE 1000
/*
*/
static void calc_alsa_tempo(struct seq_oss_timer *timer);
static int send_timer_event(struct seq_oss_devinfo *dp, int type, int value);
/*
* create and register a new timer.
* if queue is not started yet, start it.
*/
struct seq_oss_timer *
snd_seq_oss_timer_new(struct seq_oss_devinfo *dp)
{
struct seq_oss_timer *rec;
rec = kzalloc(sizeof(*rec), GFP_KERNEL);
if (rec == NULL)
return NULL;
rec->dp = dp;
rec->cur_tick = 0;
rec->realtime = 0;
rec->running = 0;
rec->oss_tempo = 60;
rec->oss_timebase = 100;
calc_alsa_tempo(rec);
return rec;
}
/*
* delete timer.
* if no more timer exists, stop the queue.
*/
void
snd_seq_oss_timer_delete(struct seq_oss_timer *rec)
{
if (rec) {
snd_seq_oss_timer_stop(rec);
kfree(rec);
}
}
/*
* process one timing event
* return 1 : event proceseed -- skip this event
* 0 : not a timer event -- enqueue this event
*/
int
snd_seq_oss_process_timer_event(struct seq_oss_timer *rec, union evrec *ev)
{
abstime_t parm = ev->t.time;
if (ev->t.code == EV_TIMING) {
switch (ev->t.cmd) {
case TMR_WAIT_REL:
parm += rec->cur_tick;
rec->realtime = 0;
/* continue to next */
case TMR_WAIT_ABS:
if (parm == 0) {
rec->realtime = 1;
} else if (parm >= rec->cur_tick) {
rec->realtime = 0;
rec->cur_tick = parm;
}
return 1; /* skip this event */
case TMR_START:
snd_seq_oss_timer_start(rec);
return 1;
}
} else if (ev->s.code == SEQ_WAIT) {
/* time = from 1 to 3 bytes */
parm = (ev->echo >> 8) & 0xffffff;
if (parm > rec->cur_tick) {
/* set next event time */
rec->cur_tick = parm;
rec->realtime = 0;
}
return 1;
}
return 0;
}
/*
* convert tempo units
*/
static void
calc_alsa_tempo(struct seq_oss_timer *timer)
{
timer->tempo = (60 * 1000000) / timer->oss_tempo;
timer->ppq = timer->oss_timebase;
}
/*
* dispatch a timer event
*/
static int
send_timer_event(struct seq_oss_devinfo *dp, int type, int value)
{
struct snd_seq_event ev;
memset(&ev, 0, sizeof(ev));
ev.type = type;
ev.source.client = dp->cseq;
ev.source.port = 0;
ev.dest.client = SNDRV_SEQ_CLIENT_SYSTEM;
ev.dest.port = SNDRV_SEQ_PORT_SYSTEM_TIMER;
ev.queue = dp->queue;
ev.data.queue.queue = dp->queue;
ev.data.queue.param.value = value;
return snd_seq_kernel_client_dispatch(dp->cseq, &ev, 1, 0);
}
/*
* set queue tempo and start queue
*/
int
snd_seq_oss_timer_start(struct seq_oss_timer *timer)
{
struct seq_oss_devinfo *dp = timer->dp;
struct snd_seq_queue_tempo tmprec;
if (timer->running)
snd_seq_oss_timer_stop(timer);
memset(&tmprec, 0, sizeof(tmprec));
tmprec.queue = dp->queue;
tmprec.ppq = timer->ppq;
tmprec.tempo = timer->tempo;
snd_seq_set_queue_tempo(dp->cseq, &tmprec);
send_timer_event(dp, SNDRV_SEQ_EVENT_START, 0);
timer->running = 1;
timer->cur_tick = 0;
return 0;
}
/*
* stop queue
*/
int
snd_seq_oss_timer_stop(struct seq_oss_timer *timer)
{
if (! timer->running)
return 0;
send_timer_event(timer->dp, SNDRV_SEQ_EVENT_STOP, 0);
timer->running = 0;
return 0;
}
/*
* continue queue
*/
int
snd_seq_oss_timer_continue(struct seq_oss_timer *timer)
{
if (timer->running)
return 0;
send_timer_event(timer->dp, SNDRV_SEQ_EVENT_CONTINUE, 0);
timer->running = 1;
return 0;
}
/*
* change queue tempo
*/
int
snd_seq_oss_timer_tempo(struct seq_oss_timer *timer, int value)
{
if (value < MIN_OSS_TEMPO)
value = MIN_OSS_TEMPO;
else if (value > MAX_OSS_TEMPO)
value = MAX_OSS_TEMPO;
timer->oss_tempo = value;
calc_alsa_tempo(timer);
if (timer->running)
send_timer_event(timer->dp, SNDRV_SEQ_EVENT_TEMPO, timer->tempo);
return 0;
}
/*
* ioctls
*/
int
snd_seq_oss_timer_ioctl(struct seq_oss_timer *timer, unsigned int cmd, int __user *arg)
{
int value;
if (cmd == SNDCTL_SEQ_CTRLRATE) {
debug_printk(("ctrl rate\n"));
/* if *arg == 0, just return the current rate */
if (get_user(value, arg))
return -EFAULT;
if (value)
return -EINVAL;
value = ((timer->oss_tempo * timer->oss_timebase) + 30) / 60;
return put_user(value, arg) ? -EFAULT : 0;
}
if (timer->dp->seq_mode == SNDRV_SEQ_OSS_MODE_SYNTH)
return 0;
switch (cmd) {
case SNDCTL_TMR_START:
debug_printk(("timer start\n"));
return snd_seq_oss_timer_start(timer);
case SNDCTL_TMR_STOP:
debug_printk(("timer stop\n"));
return snd_seq_oss_timer_stop(timer);
case SNDCTL_TMR_CONTINUE:
debug_printk(("timer continue\n"));
return snd_seq_oss_timer_continue(timer);
case SNDCTL_TMR_TEMPO:
debug_printk(("timer tempo\n"));
if (get_user(value, arg))
return -EFAULT;
return snd_seq_oss_timer_tempo(timer, value);
case SNDCTL_TMR_TIMEBASE:
debug_printk(("timer timebase\n"));
if (get_user(value, arg))
return -EFAULT;
if (value < MIN_OSS_TIMEBASE)
value = MIN_OSS_TIMEBASE;
else if (value > MAX_OSS_TIMEBASE)
value = MAX_OSS_TIMEBASE;
timer->oss_timebase = value;
calc_alsa_tempo(timer);
return 0;
case SNDCTL_TMR_METRONOME:
case SNDCTL_TMR_SELECT:
case SNDCTL_TMR_SOURCE:
debug_printk(("timer XXX\n"));
/* not supported */
return 0;
}
return 0;
}
| gpl-2.0 |
MaxiCM/Samsung_STE_Kernel | drivers/scsi/pcmcia/aha152x_stub.c | 12752 | 6854 | /*======================================================================
A driver for Adaptec AHA152X-compatible PCMCIA SCSI cards.
This driver supports the Adaptec AHA-1460, the New Media Bus
Toaster, and the New Media Toast & Jam.
aha152x_cs.c 1.54 2000/06/12 21:27:25
The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
Alternatively, the contents of this file may be used under the
terms of the GNU General Public License version 2 (the "GPL"), in which
case the provisions of the GPL are applicable instead of the
above. If you wish to allow the use of your version of this file
only under the terms of the GPL and not to allow others to use
your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice
and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this
file under either the MPL or the GPL.
======================================================================*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <scsi/scsi.h>
#include <linux/major.h>
#include <linux/blkdev.h>
#include <scsi/scsi_ioctl.h>
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "aha152x.h"
#include <pcmcia/cistpl.h>
#include <pcmcia/ds.h>
/*====================================================================*/
/* Parameters that can be set with 'insmod' */
/* SCSI bus setup options */
static int host_id = 7;
static int reconnect = 1;
static int parity = 1;
static int synchronous = 1;
static int reset_delay = 100;
static int ext_trans = 0;
module_param(host_id, int, 0);
module_param(reconnect, int, 0);
module_param(parity, int, 0);
module_param(synchronous, int, 0);
module_param(reset_delay, int, 0);
module_param(ext_trans, int, 0);
MODULE_LICENSE("Dual MPL/GPL");
/*====================================================================*/
typedef struct scsi_info_t {
struct pcmcia_device *p_dev;
struct Scsi_Host *host;
} scsi_info_t;
static void aha152x_release_cs(struct pcmcia_device *link);
static void aha152x_detach(struct pcmcia_device *p_dev);
static int aha152x_config_cs(struct pcmcia_device *link);
static int aha152x_probe(struct pcmcia_device *link)
{
scsi_info_t *info;
dev_dbg(&link->dev, "aha152x_attach()\n");
/* Create new SCSI device */
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info) return -ENOMEM;
info->p_dev = link;
link->priv = info;
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO;
link->config_regs = PRESENT_OPTION;
return aha152x_config_cs(link);
} /* aha152x_attach */
/*====================================================================*/
static void aha152x_detach(struct pcmcia_device *link)
{
dev_dbg(&link->dev, "aha152x_detach\n");
aha152x_release_cs(link);
/* Unlink device structure, free bits */
kfree(link->priv);
} /* aha152x_detach */
/*====================================================================*/
static int aha152x_config_check(struct pcmcia_device *p_dev, void *priv_data)
{
p_dev->io_lines = 10;
/* For New Media T&J, look for a SCSI window */
if ((p_dev->resource[0]->end < 0x20) &&
(p_dev->resource[1]->end >= 0x20))
p_dev->resource[0]->start = p_dev->resource[1]->start;
if (p_dev->resource[0]->start >= 0xffff)
return -EINVAL;
p_dev->resource[1]->start = p_dev->resource[1]->end = 0;
p_dev->resource[0]->end = 0x20;
p_dev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO;
return pcmcia_request_io(p_dev);
}
static int aha152x_config_cs(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
struct aha152x_setup s;
int ret;
struct Scsi_Host *host;
dev_dbg(&link->dev, "aha152x_config\n");
ret = pcmcia_loop_config(link, aha152x_config_check, NULL);
if (ret)
goto failed;
if (!link->irq)
goto failed;
ret = pcmcia_enable_device(link);
if (ret)
goto failed;
/* Set configuration options for the aha152x driver */
memset(&s, 0, sizeof(s));
s.conf = "PCMCIA setup";
s.io_port = link->resource[0]->start;
s.irq = link->irq;
s.scsiid = host_id;
s.reconnect = reconnect;
s.parity = parity;
s.synchronous = synchronous;
s.delay = reset_delay;
if (ext_trans)
s.ext_trans = ext_trans;
host = aha152x_probe_one(&s);
if (host == NULL) {
printk(KERN_INFO "aha152x_cs: no SCSI devices found\n");
goto failed;
}
info->host = host;
return 0;
failed:
aha152x_release_cs(link);
return -ENODEV;
}
static void aha152x_release_cs(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
aha152x_release(info->host);
pcmcia_disable_device(link);
}
static int aha152x_resume(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
aha152x_host_reset_host(info->host);
return 0;
}
static const struct pcmcia_device_id aha152x_ids[] = {
PCMCIA_DEVICE_PROD_ID123("New Media", "SCSI", "Bus Toaster", 0xcdf7e4cc, 0x35f26476, 0xa8851d6e),
PCMCIA_DEVICE_PROD_ID123("NOTEWORTHY", "SCSI", "Bus Toaster", 0xad89c6e8, 0x35f26476, 0xa8851d6e),
PCMCIA_DEVICE_PROD_ID12("Adaptec, Inc.", "APA-1460 SCSI Host Adapter", 0x24ba9738, 0x3a3c3d20),
PCMCIA_DEVICE_PROD_ID12("New Media Corporation", "Multimedia Sound/SCSI", 0x085a850b, 0x80a6535c),
PCMCIA_DEVICE_PROD_ID12("NOTEWORTHY", "NWCOMB02 SCSI/AUDIO COMBO CARD", 0xad89c6e8, 0x5f9a615b),
PCMCIA_DEVICE_NULL,
};
MODULE_DEVICE_TABLE(pcmcia, aha152x_ids);
static struct pcmcia_driver aha152x_cs_driver = {
.owner = THIS_MODULE,
.name = "aha152x_cs",
.probe = aha152x_probe,
.remove = aha152x_detach,
.id_table = aha152x_ids,
.resume = aha152x_resume,
};
static int __init init_aha152x_cs(void)
{
return pcmcia_register_driver(&aha152x_cs_driver);
}
static void __exit exit_aha152x_cs(void)
{
pcmcia_unregister_driver(&aha152x_cs_driver);
}
module_init(init_aha152x_cs);
module_exit(exit_aha152x_cs);
| gpl-2.0 |
sakuraba001/android_kernel_samsung_kactivelte | drivers/scsi/pcmcia/aha152x_stub.c | 12752 | 6854 | /*======================================================================
A driver for Adaptec AHA152X-compatible PCMCIA SCSI cards.
This driver supports the Adaptec AHA-1460, the New Media Bus
Toaster, and the New Media Toast & Jam.
aha152x_cs.c 1.54 2000/06/12 21:27:25
The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
Alternatively, the contents of this file may be used under the
terms of the GNU General Public License version 2 (the "GPL"), in which
case the provisions of the GPL are applicable instead of the
above. If you wish to allow the use of your version of this file
only under the terms of the GPL and not to allow others to use
your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice
and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this
file under either the MPL or the GPL.
======================================================================*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <scsi/scsi.h>
#include <linux/major.h>
#include <linux/blkdev.h>
#include <scsi/scsi_ioctl.h>
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "aha152x.h"
#include <pcmcia/cistpl.h>
#include <pcmcia/ds.h>
/*====================================================================*/
/* Parameters that can be set with 'insmod' */
/* SCSI bus setup options */
static int host_id = 7;
static int reconnect = 1;
static int parity = 1;
static int synchronous = 1;
static int reset_delay = 100;
static int ext_trans = 0;
module_param(host_id, int, 0);
module_param(reconnect, int, 0);
module_param(parity, int, 0);
module_param(synchronous, int, 0);
module_param(reset_delay, int, 0);
module_param(ext_trans, int, 0);
MODULE_LICENSE("Dual MPL/GPL");
/*====================================================================*/
typedef struct scsi_info_t {
struct pcmcia_device *p_dev;
struct Scsi_Host *host;
} scsi_info_t;
static void aha152x_release_cs(struct pcmcia_device *link);
static void aha152x_detach(struct pcmcia_device *p_dev);
static int aha152x_config_cs(struct pcmcia_device *link);
static int aha152x_probe(struct pcmcia_device *link)
{
scsi_info_t *info;
dev_dbg(&link->dev, "aha152x_attach()\n");
/* Create new SCSI device */
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info) return -ENOMEM;
info->p_dev = link;
link->priv = info;
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO;
link->config_regs = PRESENT_OPTION;
return aha152x_config_cs(link);
} /* aha152x_attach */
/*====================================================================*/
static void aha152x_detach(struct pcmcia_device *link)
{
dev_dbg(&link->dev, "aha152x_detach\n");
aha152x_release_cs(link);
/* Unlink device structure, free bits */
kfree(link->priv);
} /* aha152x_detach */
/*====================================================================*/
static int aha152x_config_check(struct pcmcia_device *p_dev, void *priv_data)
{
p_dev->io_lines = 10;
/* For New Media T&J, look for a SCSI window */
if ((p_dev->resource[0]->end < 0x20) &&
(p_dev->resource[1]->end >= 0x20))
p_dev->resource[0]->start = p_dev->resource[1]->start;
if (p_dev->resource[0]->start >= 0xffff)
return -EINVAL;
p_dev->resource[1]->start = p_dev->resource[1]->end = 0;
p_dev->resource[0]->end = 0x20;
p_dev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO;
return pcmcia_request_io(p_dev);
}
static int aha152x_config_cs(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
struct aha152x_setup s;
int ret;
struct Scsi_Host *host;
dev_dbg(&link->dev, "aha152x_config\n");
ret = pcmcia_loop_config(link, aha152x_config_check, NULL);
if (ret)
goto failed;
if (!link->irq)
goto failed;
ret = pcmcia_enable_device(link);
if (ret)
goto failed;
/* Set configuration options for the aha152x driver */
memset(&s, 0, sizeof(s));
s.conf = "PCMCIA setup";
s.io_port = link->resource[0]->start;
s.irq = link->irq;
s.scsiid = host_id;
s.reconnect = reconnect;
s.parity = parity;
s.synchronous = synchronous;
s.delay = reset_delay;
if (ext_trans)
s.ext_trans = ext_trans;
host = aha152x_probe_one(&s);
if (host == NULL) {
printk(KERN_INFO "aha152x_cs: no SCSI devices found\n");
goto failed;
}
info->host = host;
return 0;
failed:
aha152x_release_cs(link);
return -ENODEV;
}
static void aha152x_release_cs(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
aha152x_release(info->host);
pcmcia_disable_device(link);
}
static int aha152x_resume(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
aha152x_host_reset_host(info->host);
return 0;
}
static const struct pcmcia_device_id aha152x_ids[] = {
PCMCIA_DEVICE_PROD_ID123("New Media", "SCSI", "Bus Toaster", 0xcdf7e4cc, 0x35f26476, 0xa8851d6e),
PCMCIA_DEVICE_PROD_ID123("NOTEWORTHY", "SCSI", "Bus Toaster", 0xad89c6e8, 0x35f26476, 0xa8851d6e),
PCMCIA_DEVICE_PROD_ID12("Adaptec, Inc.", "APA-1460 SCSI Host Adapter", 0x24ba9738, 0x3a3c3d20),
PCMCIA_DEVICE_PROD_ID12("New Media Corporation", "Multimedia Sound/SCSI", 0x085a850b, 0x80a6535c),
PCMCIA_DEVICE_PROD_ID12("NOTEWORTHY", "NWCOMB02 SCSI/AUDIO COMBO CARD", 0xad89c6e8, 0x5f9a615b),
PCMCIA_DEVICE_NULL,
};
MODULE_DEVICE_TABLE(pcmcia, aha152x_ids);
static struct pcmcia_driver aha152x_cs_driver = {
.owner = THIS_MODULE,
.name = "aha152x_cs",
.probe = aha152x_probe,
.remove = aha152x_detach,
.id_table = aha152x_ids,
.resume = aha152x_resume,
};
static int __init init_aha152x_cs(void)
{
return pcmcia_register_driver(&aha152x_cs_driver);
}
static void __exit exit_aha152x_cs(void)
{
pcmcia_unregister_driver(&aha152x_cs_driver);
}
module_init(init_aha152x_cs);
module_exit(exit_aha152x_cs);
| gpl-2.0 |
thewisenerd/android_kernel_mediatek_sprout | drivers/misc/mediatek/combo/drv_wlan/mt6620/wlan/mgmt/p2p_ie.c | 209 | 16255 | #include "p2p_precomp.h"
#if CFG_SUPPORT_WFD
#if CFG_SUPPORT_WFD_COMPOSE_IE
#if 0
APPEND_VAR_ATTRI_ENTRY_T txProbeRspWFDAttributesTable[] = {
{(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_DEV_INFO), NULL, wfdFuncAppendAttriDevInfo} /* 0 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_ASSOC_BSSID), NULL, wfdFuncAppendAttriAssocBssid} /* 1 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_COUPLED_SINK_INFO), NULL, wfdFuncAppendAttriCoupledSinkInfo} /* 6 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_EXT_CAPABILITY), NULL, wfdFuncAppendAttriExtCapability} /* 7 */
, {0, wfdFuncCalculateAttriLenSessionInfo, wfdFuncAppendAttriSessionInfo} /* 9 */
};
APPEND_VAR_ATTRI_ENTRY_T txBeaconWFDAttributesTable[] = {
{(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_DEV_INFO), NULL, wfdFuncAppendAttriDevInfo} /* 0 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_ASSOC_BSSID), NULL, wfdFuncAppendAttriAssocBssid} /* 1 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_COUPLED_SINK_INFO), NULL, wfdFuncAppendAttriCoupledSinkInfo} /* 6 */
};
APPEND_VAR_ATTRI_ENTRY_T txAssocReqWFDAttributesTable[] = {
{(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_DEV_INFO), NULL, wfdFuncAppendAttriDevInfo} /* 0 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_ASSOC_BSSID), NULL, wfdFuncAppendAttriAssocBssid} /* 1 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_COUPLED_SINK_INFO), NULL, wfdFuncAppendAttriCoupledSinkInfo} /* 6 */
};
#endif
APPEND_VAR_ATTRI_ENTRY_T txAssocRspWFDAttributesTable[] = {
{(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_DEV_INFO), NULL, wfdFuncAppendAttriDevInfo} /* 0 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_ASSOC_BSSID), NULL, wfdFuncAppendAttriAssocBssid} /* 1 */
, {(WFD_ATTRI_HDR_LEN + WFD_ATTRI_MAX_LEN_COUPLED_SINK_INFO), NULL, wfdFuncAppendAttriCoupledSinkInfo} /* 6 */
, {0, wfdFuncCalculateAttriLenSessionInfo, wfdFuncAppendAttriSessionInfo} /* 9 */
};
#endif
UINT_32
p2pCalculate_IEForAssocReq(IN P_ADAPTER_T prAdapter,
IN ENUM_NETWORK_TYPE_INDEX_T eNetTypeIndex, IN P_STA_RECORD_T prStaRec)
{
P_P2P_FSM_INFO_T prP2pFsmInfo = (P_P2P_FSM_INFO_T) NULL;
P_P2P_CONNECTION_REQ_INFO_T prConnReqInfo = (P_P2P_CONNECTION_REQ_INFO_T) NULL;
UINT_32 u4RetValue = 0;
do {
ASSERT_BREAK((eNetTypeIndex == NETWORK_TYPE_P2P_INDEX) && (prAdapter != NULL));
prP2pFsmInfo = prAdapter->rWifiVar.prP2pFsmInfo;
prConnReqInfo = &(prP2pFsmInfo->rConnReqInfo);
u4RetValue = prConnReqInfo->u4BufLength;
/* ADD HT Capability */
u4RetValue += (ELEM_HDR_LEN + ELEM_MAX_LEN_HT_CAP);
/* ADD WMM Information Element */
u4RetValue += (ELEM_HDR_LEN + ELEM_MAX_LEN_WMM_INFO);
} while (FALSE);
return u4RetValue;
} /* p2pCalculate_IEForAssocReq */
/*----------------------------------------------------------------------------*/
/*!
* @brief This function is used to generate P2P IE for Beacon frame.
*
* @param[in] prMsduInfo Pointer to the composed MSDU_INFO_T.
*
* @return none
*/
/*----------------------------------------------------------------------------*/
VOID p2pGenerate_IEForAssocReq(IN P_ADAPTER_T prAdapter, IN P_MSDU_INFO_T prMsduInfo)
{
P_P2P_FSM_INFO_T prP2pFsmInfo = (P_P2P_FSM_INFO_T) NULL;
P_P2P_CONNECTION_REQ_INFO_T prConnReqInfo = (P_P2P_CONNECTION_REQ_INFO_T) NULL;
PUINT_8 pucIEBuf = (PUINT_8) NULL;
do {
ASSERT_BREAK((prAdapter != NULL) && (prMsduInfo != NULL));
prP2pFsmInfo = prAdapter->rWifiVar.prP2pFsmInfo;
prConnReqInfo = &(prP2pFsmInfo->rConnReqInfo);
pucIEBuf =
(PUINT_8) ((UINT_32) prMsduInfo->prPacket +
(UINT_32) prMsduInfo->u2FrameLength);
kalMemCopy(pucIEBuf, prConnReqInfo->aucIEBuf, prConnReqInfo->u4BufLength);
prMsduInfo->u2FrameLength += prConnReqInfo->u4BufLength;
rlmReqGenerateHtCapIE(prAdapter, prMsduInfo);
mqmGenerateWmmInfoIE(prAdapter, prMsduInfo);
} while (FALSE);
return;
} /* p2pGenerate_IEForAssocReq */
UINT_32
wfdFuncAppendAttriDevInfo(IN P_ADAPTER_T prAdapter,
IN BOOLEAN fgIsAssocFrame,
IN PUINT_16 pu2Offset, IN PUINT_8 pucBuf, IN UINT_16 u2BufSize)
{
UINT_32 u4AttriLen = 0;
PUINT_8 pucBuffer = NULL;
P_WFD_DEVICE_INFORMATION_IE_T prWfdDevInfo = (P_WFD_DEVICE_INFORMATION_IE_T) NULL;
P_WFD_CFG_SETTINGS_T prWfdCfgSettings = (P_WFD_CFG_SETTINGS_T) NULL;
do {
ASSERT_BREAK((prAdapter != NULL) && (pucBuf != NULL) && (pu2Offset != NULL));
prWfdCfgSettings = &(prAdapter->rWifiVar.prP2pFsmInfo->rWfdConfigureSettings);
ASSERT_BREAK((prWfdCfgSettings != NULL));
if ((prWfdCfgSettings->ucWfdEnable == 0) ||
((prWfdCfgSettings->u4WfdFlag & WFD_FLAGS_DEV_INFO_VALID) == 0)) {
break;
}
pucBuffer = (PUINT_8) ((UINT_32) pucBuf + (UINT_32) (*pu2Offset));
ASSERT_BREAK(pucBuffer != NULL);
prWfdDevInfo = (P_WFD_DEVICE_INFORMATION_IE_T) pucBuffer;
prWfdDevInfo->ucElemID = WFD_ATTRI_ID_DEV_INFO;
WLAN_SET_FIELD_BE16(&prWfdDevInfo->u2WfdDevInfo, prWfdCfgSettings->u2WfdDevInfo);
WLAN_SET_FIELD_BE16(&prWfdDevInfo->u2SessionMgmtCtrlPort,
prWfdCfgSettings->u2WfdControlPort);
WLAN_SET_FIELD_BE16(&prWfdDevInfo->u2WfdDevMaxSpeed,
prWfdCfgSettings->u2WfdMaximumTp);
WLAN_SET_FIELD_BE16(&prWfdDevInfo->u2Length, WFD_ATTRI_MAX_LEN_DEV_INFO);
u4AttriLen = WFD_ATTRI_MAX_LEN_DEV_INFO + WFD_ATTRI_HDR_LEN;
} while (FALSE);
(*pu2Offset) += (UINT_16) u4AttriLen;
return u4AttriLen;
}
/* wfdFuncAppendAttriDevInfo */
UINT_32
wfdFuncAppendAttriAssocBssid(IN P_ADAPTER_T prAdapter,
IN BOOLEAN fgIsAssocFrame,
IN PUINT_16 pu2Offset, IN PUINT_8 pucBuf, IN UINT_16 u2BufSize)
{
UINT_32 u4AttriLen = 0;
PUINT_8 pucBuffer = NULL;
P_WFD_ASSOCIATED_BSSID_IE_T prWfdAssocBssid = (P_WFD_ASSOCIATED_BSSID_IE_T) NULL;
P_WFD_CFG_SETTINGS_T prWfdCfgSettings = (P_WFD_CFG_SETTINGS_T) NULL;
P_BSS_INFO_T prAisBssInfo = (P_BSS_INFO_T) NULL;
do {
ASSERT_BREAK((prAdapter != NULL) && (pucBuf != NULL) && (pu2Offset != NULL));
prWfdCfgSettings = &(prAdapter->rWifiVar.prP2pFsmInfo->rWfdConfigureSettings);
ASSERT_BREAK((prWfdCfgSettings != NULL));
if (prWfdCfgSettings->ucWfdEnable == 0) {
break;
}
/* AIS network. */
prAisBssInfo = &(prAdapter->rWifiVar.arBssInfo[NETWORK_TYPE_AIS_INDEX]);
if ((!IS_NET_ACTIVE(prAdapter, NETWORK_TYPE_AIS_INDEX)) ||
(prAisBssInfo->eConnectionState != PARAM_MEDIA_STATE_CONNECTED)) {
break;
}
pucBuffer = (PUINT_8) ((UINT_32) pucBuf + (UINT_32) (*pu2Offset));
ASSERT_BREAK(pucBuffer != NULL);
prWfdAssocBssid = (P_WFD_ASSOCIATED_BSSID_IE_T) pucBuffer;
prWfdAssocBssid->ucElemID = WFD_ATTRI_ID_ASSOC_BSSID;
WLAN_SET_FIELD_BE16(&prWfdAssocBssid->u2Length, WFD_ATTRI_MAX_LEN_ASSOC_BSSID);
COPY_MAC_ADDR(prWfdAssocBssid->aucAssocBssid, prAisBssInfo->aucBSSID);
u4AttriLen = WFD_ATTRI_MAX_LEN_ASSOC_BSSID + WFD_ATTRI_HDR_LEN;
} while (FALSE);
(*pu2Offset) += (UINT_16) u4AttriLen;
return u4AttriLen;
}
/* wfdFuncAppendAttriAssocBssid */
UINT_32
wfdFuncAppendAttriCoupledSinkInfo(IN P_ADAPTER_T prAdapter,
IN BOOLEAN fgIsAssocFrame,
IN PUINT_16 pu2Offset, IN PUINT_8 pucBuf, IN UINT_16 u2BufSize)
{
UINT_32 u4AttriLen = 0;
PUINT_8 pucBuffer = NULL;
P_WFD_COUPLE_SINK_INFORMATION_IE_T prWfdCoupleSinkInfo =
(P_WFD_COUPLE_SINK_INFORMATION_IE_T) NULL;
P_WFD_CFG_SETTINGS_T prWfdCfgSettings = (P_WFD_CFG_SETTINGS_T) NULL;
do {
ASSERT_BREAK((prAdapter != NULL) && (pucBuf != NULL) && (pu2Offset != NULL));
prWfdCfgSettings = &(prAdapter->rWifiVar.prP2pFsmInfo->rWfdConfigureSettings);
ASSERT_BREAK((prWfdCfgSettings != NULL));
if ((prWfdCfgSettings->ucWfdEnable == 0) ||
((prWfdCfgSettings->u4WfdFlag & WFD_FLAGS_SINK_INFO_VALID) == 0)) {
break;
}
pucBuffer = (PUINT_8) ((UINT_32) pucBuf + (UINT_32) (*pu2Offset));
ASSERT_BREAK(pucBuffer != NULL);
prWfdCoupleSinkInfo = (P_WFD_COUPLE_SINK_INFORMATION_IE_T) pucBuffer;
prWfdCoupleSinkInfo->ucElemID = WFD_ATTRI_ID_COUPLED_SINK_INFO;
WLAN_SET_FIELD_BE16(&prWfdCoupleSinkInfo->u2Length,
WFD_ATTRI_MAX_LEN_COUPLED_SINK_INFO);
COPY_MAC_ADDR(prWfdCoupleSinkInfo->aucCoupleSinkMac,
prWfdCfgSettings->aucWfdCoupleSinkAddress);
prWfdCoupleSinkInfo->ucCoupleSinkStatusBp = prWfdCfgSettings->ucWfdCoupleSinkStatus;
u4AttriLen = WFD_ATTRI_MAX_LEN_COUPLED_SINK_INFO + WFD_ATTRI_HDR_LEN;
} while (FALSE);
(*pu2Offset) += (UINT_16) u4AttriLen;
return u4AttriLen;
}
/* wfdFuncAppendAttriCoupledSinkInfo */
UINT_32
wfdFuncAppendAttriExtCapability(IN P_ADAPTER_T prAdapter,
IN BOOLEAN fgIsAssocFrame,
IN PUINT_16 pu2Offset, IN PUINT_8 pucBuf, IN UINT_16 u2BufSize)
{
UINT_32 u4AttriLen = 0;
PUINT_8 pucBuffer = NULL;
P_WFD_EXTENDED_CAPABILITY_IE_T prWfdExtCapability = (P_WFD_EXTENDED_CAPABILITY_IE_T) NULL;
P_WFD_CFG_SETTINGS_T prWfdCfgSettings = (P_WFD_CFG_SETTINGS_T) NULL;
do {
ASSERT_BREAK((prAdapter != NULL) && (pucBuf != NULL) && (pu2Offset != NULL));
prWfdCfgSettings = &(prAdapter->rWifiVar.prP2pFsmInfo->rWfdConfigureSettings);
ASSERT_BREAK((prWfdCfgSettings != NULL));
if ((prWfdCfgSettings->ucWfdEnable == 0) ||
((prWfdCfgSettings->u4WfdFlag & WFD_FLAGS_EXT_CAPABILITY_VALID) == 0)) {
break;
}
pucBuffer = (PUINT_8) ((UINT_32) pucBuf + (UINT_32) (*pu2Offset));
ASSERT_BREAK(pucBuffer != NULL);
prWfdExtCapability = (P_WFD_EXTENDED_CAPABILITY_IE_T) pucBuffer;
prWfdExtCapability->ucElemID = WFD_ATTRI_ID_EXT_CAPABILITY;
WLAN_SET_FIELD_BE16(&prWfdExtCapability->u2Length,
WFD_ATTRI_MAX_LEN_EXT_CAPABILITY);
WLAN_SET_FIELD_BE16(&prWfdExtCapability->u2WfdExtCapabilityBp,
prWfdCfgSettings->u2WfdExtendCap);
u4AttriLen = WFD_ATTRI_MAX_LEN_EXT_CAPABILITY + WFD_ATTRI_HDR_LEN;
} while (FALSE);
(*pu2Offset) += (UINT_16) u4AttriLen;
return u4AttriLen;
}
/* wfdFuncAppendAttriExtCapability */
/*----------------------------------------------------------------------------*/
/*!
* @brief This function is used to calculate length of Channel List Attribute
*
* @param[in] prStaRec Pointer to the STA_RECORD_T
*
* @return The length of Attribute added
*/
/*----------------------------------------------------------------------------*/
UINT_32 wfdFuncCalculateAttriLenSessionInfo(IN P_ADAPTER_T prAdapter, IN P_STA_RECORD_T prStaRec)
{
UINT_16 u2AttriLen = 0;
P_WFD_CFG_SETTINGS_T prWfdCfgSettings = (P_WFD_CFG_SETTINGS_T) NULL;
do {
ASSERT_BREAK((prAdapter != NULL) && (prStaRec != NULL));
prWfdCfgSettings = &(prAdapter->rWifiVar.prP2pFsmInfo->rWfdConfigureSettings);
if (prWfdCfgSettings->ucWfdEnable == 0) {
break;
}
u2AttriLen = prWfdCfgSettings->u2WfdSessionInformationIELen + WFD_ATTRI_HDR_LEN;
} while (FALSE);
return (UINT_32) u2AttriLen;
} /* wfdFuncCalculateAttriLenSessionInfo */
UINT_32
wfdFuncAppendAttriSessionInfo(IN P_ADAPTER_T prAdapter,
IN BOOLEAN fgIsAssocFrame,
IN PUINT_16 pu2Offset, IN PUINT_8 pucBuf, IN UINT_16 u2BufSize)
{
UINT_32 u4AttriLen = 0;
PUINT_8 pucBuffer = NULL;
P_WFD_SESSION_INFORMATION_IE_T prWfdSessionInfo = (P_WFD_SESSION_INFORMATION_IE_T) NULL;
P_WFD_CFG_SETTINGS_T prWfdCfgSettings = (P_WFD_CFG_SETTINGS_T) NULL;
do {
ASSERT_BREAK((prAdapter != NULL) && (pucBuf != NULL) && (pu2Offset != NULL));
prWfdCfgSettings = &(prAdapter->rWifiVar.prP2pFsmInfo->rWfdConfigureSettings);
ASSERT_BREAK((prWfdCfgSettings != NULL));
if ((prWfdCfgSettings->ucWfdEnable == 0)
|| (prWfdCfgSettings->u2WfdSessionInformationIELen == 0)) {
break;
}
pucBuffer = (PUINT_8) ((UINT_32) pucBuf + (UINT_32) (*pu2Offset));
ASSERT_BREAK(pucBuffer != NULL);
prWfdSessionInfo = (P_WFD_SESSION_INFORMATION_IE_T) pucBuffer;
prWfdSessionInfo->ucElemID = WFD_ATTRI_ID_SESSION_INFO;
/* TODO: Check endian issue? */
kalMemCopy(prWfdSessionInfo->pucWfdDevInfoDesc,
prWfdCfgSettings->aucWfdSessionInformationIE,
prWfdCfgSettings->u2WfdSessionInformationIELen);
WLAN_SET_FIELD_16(&prWfdSessionInfo->u2Length,
prWfdCfgSettings->u2WfdSessionInformationIELen);
u4AttriLen = prWfdCfgSettings->u2WfdSessionInformationIELen + WFD_ATTRI_HDR_LEN;
}
while (FALSE);
(*pu2Offset) += (UINT_16) u4AttriLen;
return u4AttriLen;
}
/* wfdFuncAppendAttriSessionInfo */
#if CFG_SUPPORT_WFD_COMPOSE_IE
VOID
wfdFuncGenerateWfd_IE(IN P_ADAPTER_T prAdapter,
IN BOOLEAN fgIsAssocFrame,
IN PUINT_16 pu2Offset,
IN PUINT_8 pucBuf,
IN UINT_16 u2BufSize,
IN APPEND_VAR_ATTRI_ENTRY_T arAppendAttriTable[], IN UINT_32 u4AttriTableSize)
{
PUINT_8 pucBuffer = (PUINT_8) NULL;
P_IE_WFD_T prIeWFD = (P_IE_WFD_T) NULL;
UINT_32 u4OverallAttriLen;
UINT_32 u4AttriLen;
UINT_8 aucWfaOui[] = VENDOR_OUI_WFA_SPECIFIC;
UINT_8 aucTempBuffer[P2P_MAXIMUM_ATTRIBUTE_LEN];
UINT_32 i;
do {
ASSERT_BREAK((prAdapter != NULL) && (pucBuf != NULL));
pucBuffer = (PUINT_8) ((UINT_32) pucBuf + (*pu2Offset));
ASSERT_BREAK(pucBuffer != NULL);
/* Check buffer length is still enough. */
ASSERT_BREAK((u2BufSize - (*pu2Offset)) >= WFD_IE_OUI_HDR);
prIeWFD = (P_IE_WFD_T) pucBuffer;
prIeWFD->ucId = ELEM_ID_WFD;
prIeWFD->aucOui[0] = aucWfaOui[0];
prIeWFD->aucOui[1] = aucWfaOui[1];
prIeWFD->aucOui[2] = aucWfaOui[2];
prIeWFD->ucOuiType = VENDOR_OUI_TYPE_WFD;
(*pu2Offset) += WFD_IE_OUI_HDR;
/* Overall length of all Attributes */
u4OverallAttriLen = 0;
for (i = 0; i < u4AttriTableSize; i++) {
if (arAppendAttriTable[i].pfnAppendAttri) {
u4AttriLen =
arAppendAttriTable[i].pfnAppendAttri(prAdapter, fgIsAssocFrame,
pu2Offset, pucBuf,
u2BufSize);
u4OverallAttriLen += u4AttriLen;
if (u4OverallAttriLen > P2P_MAXIMUM_ATTRIBUTE_LEN) {
u4OverallAttriLen -= P2P_MAXIMUM_ATTRIBUTE_LEN;
prIeWFD->ucLength =
(VENDOR_OUI_TYPE_LEN + P2P_MAXIMUM_ATTRIBUTE_LEN);
pucBuffer =
(PUINT_8) ((UINT_32) prIeWFD +
(WFD_IE_OUI_HDR +
P2P_MAXIMUM_ATTRIBUTE_LEN));
prIeWFD =
(P_IE_WFD_T) ((UINT_32) prIeWFD +
(WFD_IE_OUI_HDR +
P2P_MAXIMUM_ATTRIBUTE_LEN));
kalMemCopy(aucTempBuffer, pucBuffer, u4OverallAttriLen);
prIeWFD->ucId = ELEM_ID_WFD;
prIeWFD->aucOui[0] = aucWfaOui[0];
prIeWFD->aucOui[1] = aucWfaOui[1];
prIeWFD->aucOui[2] = aucWfaOui[2];
prIeWFD->ucOuiType = VENDOR_OUI_TYPE_WFD;
kalMemCopy(prIeWFD->aucWFDAttributes, aucTempBuffer,
u4OverallAttriLen);
(*pu2Offset) += WFD_IE_OUI_HDR;
}
}
}
prIeWFD->ucLength = (UINT_8) (VENDOR_OUI_TYPE_LEN + u4OverallAttriLen);
} while (FALSE);
return;
} /* wfdFuncGenerateWfd_IE */
#endif /* CFG_SUPPORT_WFD_COMPOSE_IE */
UINT_32
wfdFuncCalculateWfdIELenForAssocRsp(IN P_ADAPTER_T prAdapter,
IN ENUM_NETWORK_TYPE_INDEX_T eNetTypeIndex,
IN P_STA_RECORD_T prStaRec)
{
#if CFG_SUPPORT_WFD_COMPOSE_IE
P_WFD_CFG_SETTINGS_T prWfdCfgSettings = (P_WFD_CFG_SETTINGS_T) NULL;
prWfdCfgSettings = &(prAdapter->rWifiVar.prP2pFsmInfo->rWfdConfigureSettings);
if (!IS_STA_P2P_TYPE(prStaRec) || (prWfdCfgSettings->ucWfdEnable == 0)) {
return 0;
}
return p2pFuncCalculateP2P_IELen(prAdapter,
eNetTypeIndex,
prStaRec,
txAssocRspWFDAttributesTable,
sizeof(txAssocRspWFDAttributesTable) /
sizeof(APPEND_VAR_ATTRI_ENTRY_T));
#else
return 0;
#endif
} /* wfdFuncCalculateWfdIELenForAssocRsp */
VOID wfdFuncGenerateWfdIEForAssocRsp(IN P_ADAPTER_T prAdapter, IN P_MSDU_INFO_T prMsduInfo)
{
#if CFG_SUPPORT_WFD_COMPOSE_IE
P_WFD_CFG_SETTINGS_T prWfdCfgSettings = (P_WFD_CFG_SETTINGS_T) NULL;
P_STA_RECORD_T prStaRec;
do {
ASSERT_BREAK((prMsduInfo != NULL) && (prAdapter != NULL));
prWfdCfgSettings = &(prAdapter->rWifiVar.prP2pFsmInfo->rWfdConfigureSettings);
prStaRec = cnmGetStaRecByIndex(prAdapter, prMsduInfo->ucStaRecIndex);
if (IS_STA_P2P_TYPE(prStaRec)) {
if (prWfdCfgSettings->ucWfdEnable == 0) {
break;
}
if ((prWfdCfgSettings->u4WfdFlag & WFD_FLAGS_DEV_INFO_VALID) == 0) {
break;
}
wfdFuncGenerateWfd_IE(prAdapter,
FALSE,
&prMsduInfo->u2FrameLength,
prMsduInfo->prPacket,
1500,
txAssocRspWFDAttributesTable,
sizeof(txAssocRspWFDAttributesTable) /
sizeof(APPEND_VAR_ATTRI_ENTRY_T));
}
} while (FALSE);
return;
#else
return;
#endif
} /* wfdFuncGenerateWfdIEForAssocRsp */
#endif
| gpl-2.0 |
martyj/LGP999_V10c_Kernel | drivers/gpu/drm/radeon/radeon_ioc32.c | 465 | 13953 | /**
* \file radeon_ioc32.c
*
* 32-bit ioctl compatibility routines for the Radeon DRM.
*
* \author Paul Mackerras <paulus@samba.org>
*
* Copyright (C) Paul Mackerras 2005
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) 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 AUTHOR 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/compat.h>
#include "drmP.h"
#include "drm.h"
#include "radeon_drm.h"
#include "radeon_drv.h"
typedef struct drm_radeon_init32 {
int func;
u32 sarea_priv_offset;
int is_pci;
int cp_mode;
int gart_size;
int ring_size;
int usec_timeout;
unsigned int fb_bpp;
unsigned int front_offset, front_pitch;
unsigned int back_offset, back_pitch;
unsigned int depth_bpp;
unsigned int depth_offset, depth_pitch;
u32 fb_offset;
u32 mmio_offset;
u32 ring_offset;
u32 ring_rptr_offset;
u32 buffers_offset;
u32 gart_textures_offset;
} drm_radeon_init32_t;
static int compat_radeon_cp_init(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_init32_t init32;
drm_radeon_init_t __user *init;
if (copy_from_user(&init32, (void __user *)arg, sizeof(init32)))
return -EFAULT;
init = compat_alloc_user_space(sizeof(*init));
if (!access_ok(VERIFY_WRITE, init, sizeof(*init))
|| __put_user(init32.func, &init->func)
|| __put_user(init32.sarea_priv_offset, &init->sarea_priv_offset)
|| __put_user(init32.is_pci, &init->is_pci)
|| __put_user(init32.cp_mode, &init->cp_mode)
|| __put_user(init32.gart_size, &init->gart_size)
|| __put_user(init32.ring_size, &init->ring_size)
|| __put_user(init32.usec_timeout, &init->usec_timeout)
|| __put_user(init32.fb_bpp, &init->fb_bpp)
|| __put_user(init32.front_offset, &init->front_offset)
|| __put_user(init32.front_pitch, &init->front_pitch)
|| __put_user(init32.back_offset, &init->back_offset)
|| __put_user(init32.back_pitch, &init->back_pitch)
|| __put_user(init32.depth_bpp, &init->depth_bpp)
|| __put_user(init32.depth_offset, &init->depth_offset)
|| __put_user(init32.depth_pitch, &init->depth_pitch)
|| __put_user(init32.fb_offset, &init->fb_offset)
|| __put_user(init32.mmio_offset, &init->mmio_offset)
|| __put_user(init32.ring_offset, &init->ring_offset)
|| __put_user(init32.ring_rptr_offset, &init->ring_rptr_offset)
|| __put_user(init32.buffers_offset, &init->buffers_offset)
|| __put_user(init32.gart_textures_offset,
&init->gart_textures_offset))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_CP_INIT, (unsigned long)init);
}
typedef struct drm_radeon_clear32 {
unsigned int flags;
unsigned int clear_color;
unsigned int clear_depth;
unsigned int color_mask;
unsigned int depth_mask; /* misnamed field: should be stencil */
u32 depth_boxes;
} drm_radeon_clear32_t;
static int compat_radeon_cp_clear(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_clear32_t clr32;
drm_radeon_clear_t __user *clr;
if (copy_from_user(&clr32, (void __user *)arg, sizeof(clr32)))
return -EFAULT;
clr = compat_alloc_user_space(sizeof(*clr));
if (!access_ok(VERIFY_WRITE, clr, sizeof(*clr))
|| __put_user(clr32.flags, &clr->flags)
|| __put_user(clr32.clear_color, &clr->clear_color)
|| __put_user(clr32.clear_depth, &clr->clear_depth)
|| __put_user(clr32.color_mask, &clr->color_mask)
|| __put_user(clr32.depth_mask, &clr->depth_mask)
|| __put_user((void __user *)(unsigned long)clr32.depth_boxes,
&clr->depth_boxes))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_CLEAR, (unsigned long)clr);
}
typedef struct drm_radeon_stipple32 {
u32 mask;
} drm_radeon_stipple32_t;
static int compat_radeon_cp_stipple(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_stipple32_t __user *argp = (void __user *)arg;
drm_radeon_stipple_t __user *request;
u32 mask;
if (get_user(mask, &argp->mask))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user((unsigned int __user *)(unsigned long)mask,
&request->mask))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_STIPPLE, (unsigned long)request);
}
typedef struct drm_radeon_tex_image32 {
unsigned int x, y; /* Blit coordinates */
unsigned int width, height;
u32 data;
} drm_radeon_tex_image32_t;
typedef struct drm_radeon_texture32 {
unsigned int offset;
int pitch;
int format;
int width; /* Texture image coordinates */
int height;
u32 image;
} drm_radeon_texture32_t;
static int compat_radeon_cp_texture(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_texture32_t req32;
drm_radeon_texture_t __user *request;
drm_radeon_tex_image32_t img32;
drm_radeon_tex_image_t __user *image;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
if (req32.image == 0)
return -EINVAL;
if (copy_from_user(&img32, (void __user *)(unsigned long)req32.image,
sizeof(img32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request) + sizeof(*image));
if (!access_ok(VERIFY_WRITE, request,
sizeof(*request) + sizeof(*image)))
return -EFAULT;
image = (drm_radeon_tex_image_t __user *) (request + 1);
if (__put_user(req32.offset, &request->offset)
|| __put_user(req32.pitch, &request->pitch)
|| __put_user(req32.format, &request->format)
|| __put_user(req32.width, &request->width)
|| __put_user(req32.height, &request->height)
|| __put_user(image, &request->image)
|| __put_user(img32.x, &image->x)
|| __put_user(img32.y, &image->y)
|| __put_user(img32.width, &image->width)
|| __put_user(img32.height, &image->height)
|| __put_user((const void __user *)(unsigned long)img32.data,
&image->data))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_TEXTURE, (unsigned long)request);
}
typedef struct drm_radeon_vertex2_32 {
int idx; /* Index of vertex buffer */
int discard; /* Client finished with buffer? */
int nr_states;
u32 state;
int nr_prims;
u32 prim;
} drm_radeon_vertex2_32_t;
static int compat_radeon_cp_vertex2(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_vertex2_32_t req32;
drm_radeon_vertex2_t __user *request;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.idx, &request->idx)
|| __put_user(req32.discard, &request->discard)
|| __put_user(req32.nr_states, &request->nr_states)
|| __put_user((void __user *)(unsigned long)req32.state,
&request->state)
|| __put_user(req32.nr_prims, &request->nr_prims)
|| __put_user((void __user *)(unsigned long)req32.prim,
&request->prim))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_VERTEX2, (unsigned long)request);
}
typedef struct drm_radeon_cmd_buffer32 {
int bufsz;
u32 buf;
int nbox;
u32 boxes;
} drm_radeon_cmd_buffer32_t;
static int compat_radeon_cp_cmdbuf(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_cmd_buffer32_t req32;
drm_radeon_cmd_buffer_t __user *request;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.bufsz, &request->bufsz)
|| __put_user((void __user *)(unsigned long)req32.buf,
&request->buf)
|| __put_user(req32.nbox, &request->nbox)
|| __put_user((void __user *)(unsigned long)req32.boxes,
&request->boxes))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_CMDBUF, (unsigned long)request);
}
typedef struct drm_radeon_getparam32 {
int param;
u32 value;
} drm_radeon_getparam32_t;
static int compat_radeon_cp_getparam(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_getparam32_t req32;
drm_radeon_getparam_t __user *request;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.param, &request->param)
|| __put_user((void __user *)(unsigned long)req32.value,
&request->value))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_GETPARAM, (unsigned long)request);
}
typedef struct drm_radeon_mem_alloc32 {
int region;
int alignment;
int size;
u32 region_offset; /* offset from start of fb or GART */
} drm_radeon_mem_alloc32_t;
static int compat_radeon_mem_alloc(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_mem_alloc32_t req32;
drm_radeon_mem_alloc_t __user *request;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.region, &request->region)
|| __put_user(req32.alignment, &request->alignment)
|| __put_user(req32.size, &request->size)
|| __put_user((int __user *)(unsigned long)req32.region_offset,
&request->region_offset))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_ALLOC, (unsigned long)request);
}
typedef struct drm_radeon_irq_emit32 {
u32 irq_seq;
} drm_radeon_irq_emit32_t;
static int compat_radeon_irq_emit(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_irq_emit32_t req32;
drm_radeon_irq_emit_t __user *request;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user((int __user *)(unsigned long)req32.irq_seq,
&request->irq_seq))
return -EFAULT;
return drm_ioctl(file->f_path.dentry->d_inode, file,
DRM_IOCTL_RADEON_IRQ_EMIT, (unsigned long)request);
}
/* The two 64-bit arches where alignof(u64)==4 in 32-bit code */
#if defined (CONFIG_X86_64) || defined(CONFIG_IA64)
typedef struct drm_radeon_setparam32 {
int param;
u64 value;
} __attribute__((packed)) drm_radeon_setparam32_t;
static int compat_radeon_cp_setparam(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_radeon_setparam32_t req32;
drm_radeon_setparam_t __user *request;
if (copy_from_user(&req32, (void __user *) arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.param, &request->param)
|| __put_user((void __user *)(unsigned long)req32.value,
&request->value))
return -EFAULT;
return drm_ioctl(file->f_dentry->d_inode, file,
DRM_IOCTL_RADEON_SETPARAM, (unsigned long) request);
}
#else
#define compat_radeon_cp_setparam NULL
#endif /* X86_64 || IA64 */
drm_ioctl_compat_t *radeon_compat_ioctls[] = {
[DRM_RADEON_CP_INIT] = compat_radeon_cp_init,
[DRM_RADEON_CLEAR] = compat_radeon_cp_clear,
[DRM_RADEON_STIPPLE] = compat_radeon_cp_stipple,
[DRM_RADEON_TEXTURE] = compat_radeon_cp_texture,
[DRM_RADEON_VERTEX2] = compat_radeon_cp_vertex2,
[DRM_RADEON_CMDBUF] = compat_radeon_cp_cmdbuf,
[DRM_RADEON_GETPARAM] = compat_radeon_cp_getparam,
[DRM_RADEON_SETPARAM] = compat_radeon_cp_setparam,
[DRM_RADEON_ALLOC] = compat_radeon_mem_alloc,
[DRM_RADEON_IRQ_EMIT] = compat_radeon_irq_emit,
};
/**
* Called whenever a 32-bit process running under a 64-bit kernel
* performs an ioctl on /dev/dri/card<n>.
*
* \param filp file pointer.
* \param cmd command.
* \param arg user argument.
* \return zero on success or negative number on failure.
*/
long radeon_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
unsigned int nr = DRM_IOCTL_NR(cmd);
drm_ioctl_compat_t *fn = NULL;
int ret;
if (nr < DRM_COMMAND_BASE)
return drm_compat_ioctl(filp, cmd, arg);
if (nr < DRM_COMMAND_BASE + DRM_ARRAY_SIZE(radeon_compat_ioctls))
fn = radeon_compat_ioctls[nr - DRM_COMMAND_BASE];
lock_kernel(); /* XXX for now */
if (fn != NULL)
ret = (*fn) (filp, cmd, arg);
else
ret = drm_ioctl(filp->f_path.dentry->d_inode, filp, cmd, arg);
unlock_kernel();
return ret;
}
long radeon_kms_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
unsigned int nr = DRM_IOCTL_NR(cmd);
int ret;
if (nr < DRM_COMMAND_BASE)
return drm_compat_ioctl(filp, cmd, arg);
lock_kernel(); /* XXX for now */
ret = drm_ioctl(filp->f_path.dentry->d_inode, filp, cmd, arg);
unlock_kernel();
return ret;
}
| gpl-2.0 |
Cpasjuste/android_kernel_lg_p990 | drivers/scsi/lpfc/lpfc_hbadisc.c | 465 | 133064 | /*******************************************************************
* This file is part of the Emulex Linux Device Driver for *
* Fibre Channel Host Bus Adapters. *
* Copyright (C) 2004-2009 Emulex. All rights reserved. *
* EMULEX and SLI are trademarks of Emulex. *
* www.emulex.com *
* Portions Copyright (C) 2004-2005 Christoph Hellwig *
* *
* 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. *
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND *
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE *
* DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
* TO BE LEGALLY INVALID. See the GNU General Public License for *
* more details, a copy of which can be found in the file COPYING *
* included with this package. *
*******************************************************************/
#include <linux/blkdev.h>
#include <linux/pci.h>
#include <linux/kthread.h>
#include <linux/interrupt.h>
#include <scsi/scsi.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_fc.h>
#include "lpfc_hw4.h"
#include "lpfc_hw.h"
#include "lpfc_nl.h"
#include "lpfc_disc.h"
#include "lpfc_sli.h"
#include "lpfc_sli4.h"
#include "lpfc_scsi.h"
#include "lpfc.h"
#include "lpfc_logmsg.h"
#include "lpfc_crtn.h"
#include "lpfc_vport.h"
#include "lpfc_debugfs.h"
/* AlpaArray for assignment of scsid for scan-down and bind_method */
static uint8_t lpfcAlpaArray[] = {
0xEF, 0xE8, 0xE4, 0xE2, 0xE1, 0xE0, 0xDC, 0xDA, 0xD9, 0xD6,
0xD5, 0xD4, 0xD3, 0xD2, 0xD1, 0xCE, 0xCD, 0xCC, 0xCB, 0xCA,
0xC9, 0xC7, 0xC6, 0xC5, 0xC3, 0xBC, 0xBA, 0xB9, 0xB6, 0xB5,
0xB4, 0xB3, 0xB2, 0xB1, 0xAE, 0xAD, 0xAC, 0xAB, 0xAA, 0xA9,
0xA7, 0xA6, 0xA5, 0xA3, 0x9F, 0x9E, 0x9D, 0x9B, 0x98, 0x97,
0x90, 0x8F, 0x88, 0x84, 0x82, 0x81, 0x80, 0x7C, 0x7A, 0x79,
0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x6E, 0x6D, 0x6C, 0x6B,
0x6A, 0x69, 0x67, 0x66, 0x65, 0x63, 0x5C, 0x5A, 0x59, 0x56,
0x55, 0x54, 0x53, 0x52, 0x51, 0x4E, 0x4D, 0x4C, 0x4B, 0x4A,
0x49, 0x47, 0x46, 0x45, 0x43, 0x3C, 0x3A, 0x39, 0x36, 0x35,
0x34, 0x33, 0x32, 0x31, 0x2E, 0x2D, 0x2C, 0x2B, 0x2A, 0x29,
0x27, 0x26, 0x25, 0x23, 0x1F, 0x1E, 0x1D, 0x1B, 0x18, 0x17,
0x10, 0x0F, 0x08, 0x04, 0x02, 0x01
};
static void lpfc_disc_timeout_handler(struct lpfc_vport *);
static void lpfc_disc_flush_list(struct lpfc_vport *vport);
static void lpfc_unregister_fcfi_cmpl(struct lpfc_hba *, LPFC_MBOXQ_t *);
void
lpfc_terminate_rport_io(struct fc_rport *rport)
{
struct lpfc_rport_data *rdata;
struct lpfc_nodelist * ndlp;
struct lpfc_hba *phba;
rdata = rport->dd_data;
ndlp = rdata->pnode;
if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
if (rport->roles & FC_RPORT_ROLE_FCP_TARGET)
printk(KERN_ERR "Cannot find remote node"
" to terminate I/O Data x%x\n",
rport->port_id);
return;
}
phba = ndlp->phba;
lpfc_debugfs_disc_trc(ndlp->vport, LPFC_DISC_TRC_RPORT,
"rport terminate: sid:x%x did:x%x flg:x%x",
ndlp->nlp_sid, ndlp->nlp_DID, ndlp->nlp_flag);
if (ndlp->nlp_sid != NLP_NO_SID) {
lpfc_sli_abort_iocb(ndlp->vport,
&phba->sli.ring[phba->sli.fcp_ring],
ndlp->nlp_sid, 0, LPFC_CTX_TGT);
}
}
/*
* This function will be called when dev_loss_tmo fire.
*/
void
lpfc_dev_loss_tmo_callbk(struct fc_rport *rport)
{
struct lpfc_rport_data *rdata;
struct lpfc_nodelist * ndlp;
struct lpfc_vport *vport;
struct lpfc_hba *phba;
struct lpfc_work_evt *evtp;
int put_node;
int put_rport;
rdata = rport->dd_data;
ndlp = rdata->pnode;
if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
return;
vport = ndlp->vport;
phba = vport->phba;
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_RPORT,
"rport devlosscb: sid:x%x did:x%x flg:x%x",
ndlp->nlp_sid, ndlp->nlp_DID, ndlp->nlp_flag);
/* Don't defer this if we are in the process of deleting the vport
* or unloading the driver. The unload will cleanup the node
* appropriately we just need to cleanup the ndlp rport info here.
*/
if (vport->load_flag & FC_UNLOADING) {
put_node = rdata->pnode != NULL;
put_rport = ndlp->rport != NULL;
rdata->pnode = NULL;
ndlp->rport = NULL;
if (put_node)
lpfc_nlp_put(ndlp);
if (put_rport)
put_device(&rport->dev);
return;
}
if (ndlp->nlp_state == NLP_STE_MAPPED_NODE)
return;
evtp = &ndlp->dev_loss_evt;
if (!list_empty(&evtp->evt_listp))
return;
spin_lock_irq(&phba->hbalock);
/* We need to hold the node by incrementing the reference
* count until this queued work is done
*/
evtp->evt_arg1 = lpfc_nlp_get(ndlp);
if (evtp->evt_arg1) {
evtp->evt = LPFC_EVT_DEV_LOSS;
list_add_tail(&evtp->evt_listp, &phba->work_list);
lpfc_worker_wake_up(phba);
}
spin_unlock_irq(&phba->hbalock);
return;
}
/*
* This function is called from the worker thread when dev_loss_tmo
* expire.
*/
static void
lpfc_dev_loss_tmo_handler(struct lpfc_nodelist *ndlp)
{
struct lpfc_rport_data *rdata;
struct fc_rport *rport;
struct lpfc_vport *vport;
struct lpfc_hba *phba;
uint8_t *name;
int put_node;
int put_rport;
int warn_on = 0;
rport = ndlp->rport;
if (!rport)
return;
rdata = rport->dd_data;
name = (uint8_t *) &ndlp->nlp_portname;
vport = ndlp->vport;
phba = vport->phba;
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_RPORT,
"rport devlosstmo:did:x%x type:x%x id:x%x",
ndlp->nlp_DID, ndlp->nlp_type, rport->scsi_target_id);
/* Don't defer this if we are in the process of deleting the vport
* or unloading the driver. The unload will cleanup the node
* appropriately we just need to cleanup the ndlp rport info here.
*/
if (vport->load_flag & FC_UNLOADING) {
if (ndlp->nlp_sid != NLP_NO_SID) {
/* flush the target */
lpfc_sli_abort_iocb(vport,
&phba->sli.ring[phba->sli.fcp_ring],
ndlp->nlp_sid, 0, LPFC_CTX_TGT);
}
put_node = rdata->pnode != NULL;
put_rport = ndlp->rport != NULL;
rdata->pnode = NULL;
ndlp->rport = NULL;
if (put_node)
lpfc_nlp_put(ndlp);
if (put_rport)
put_device(&rport->dev);
return;
}
if (ndlp->nlp_state == NLP_STE_MAPPED_NODE) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0284 Devloss timeout Ignored on "
"WWPN %x:%x:%x:%x:%x:%x:%x:%x "
"NPort x%x\n",
*name, *(name+1), *(name+2), *(name+3),
*(name+4), *(name+5), *(name+6), *(name+7),
ndlp->nlp_DID);
return;
}
if (ndlp->nlp_type & NLP_FABRIC) {
/* We will clean up these Nodes in linkup */
put_node = rdata->pnode != NULL;
put_rport = ndlp->rport != NULL;
rdata->pnode = NULL;
ndlp->rport = NULL;
if (put_node)
lpfc_nlp_put(ndlp);
if (put_rport)
put_device(&rport->dev);
return;
}
if (ndlp->nlp_sid != NLP_NO_SID) {
warn_on = 1;
/* flush the target */
lpfc_sli_abort_iocb(vport, &phba->sli.ring[phba->sli.fcp_ring],
ndlp->nlp_sid, 0, LPFC_CTX_TGT);
}
if (warn_on) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0203 Devloss timeout on "
"WWPN %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x "
"NPort x%06x Data: x%x x%x x%x\n",
*name, *(name+1), *(name+2), *(name+3),
*(name+4), *(name+5), *(name+6), *(name+7),
ndlp->nlp_DID, ndlp->nlp_flag,
ndlp->nlp_state, ndlp->nlp_rpi);
} else {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0204 Devloss timeout on "
"WWPN %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x "
"NPort x%06x Data: x%x x%x x%x\n",
*name, *(name+1), *(name+2), *(name+3),
*(name+4), *(name+5), *(name+6), *(name+7),
ndlp->nlp_DID, ndlp->nlp_flag,
ndlp->nlp_state, ndlp->nlp_rpi);
}
put_node = rdata->pnode != NULL;
put_rport = ndlp->rport != NULL;
rdata->pnode = NULL;
ndlp->rport = NULL;
if (put_node)
lpfc_nlp_put(ndlp);
if (put_rport)
put_device(&rport->dev);
if (!(vport->load_flag & FC_UNLOADING) &&
!(ndlp->nlp_flag & NLP_DELAY_TMO) &&
!(ndlp->nlp_flag & NLP_NPR_2B_DISC) &&
(ndlp->nlp_state != NLP_STE_UNMAPPED_NODE))
lpfc_disc_state_machine(vport, ndlp, NULL, NLP_EVT_DEVICE_RM);
lpfc_unregister_unused_fcf(phba);
}
/**
* lpfc_alloc_fast_evt - Allocates data structure for posting event
* @phba: Pointer to hba context object.
*
* This function is called from the functions which need to post
* events from interrupt context. This function allocates data
* structure required for posting event. It also keeps track of
* number of events pending and prevent event storm when there are
* too many events.
**/
struct lpfc_fast_path_event *
lpfc_alloc_fast_evt(struct lpfc_hba *phba) {
struct lpfc_fast_path_event *ret;
/* If there are lot of fast event do not exhaust memory due to this */
if (atomic_read(&phba->fast_event_count) > LPFC_MAX_EVT_COUNT)
return NULL;
ret = kzalloc(sizeof(struct lpfc_fast_path_event),
GFP_ATOMIC);
if (ret) {
atomic_inc(&phba->fast_event_count);
INIT_LIST_HEAD(&ret->work_evt.evt_listp);
ret->work_evt.evt = LPFC_EVT_FASTPATH_MGMT_EVT;
}
return ret;
}
/**
* lpfc_free_fast_evt - Frees event data structure
* @phba: Pointer to hba context object.
* @evt: Event object which need to be freed.
*
* This function frees the data structure required for posting
* events.
**/
void
lpfc_free_fast_evt(struct lpfc_hba *phba,
struct lpfc_fast_path_event *evt) {
atomic_dec(&phba->fast_event_count);
kfree(evt);
}
/**
* lpfc_send_fastpath_evt - Posts events generated from fast path
* @phba: Pointer to hba context object.
* @evtp: Event data structure.
*
* This function is called from worker thread, when the interrupt
* context need to post an event. This function posts the event
* to fc transport netlink interface.
**/
static void
lpfc_send_fastpath_evt(struct lpfc_hba *phba,
struct lpfc_work_evt *evtp)
{
unsigned long evt_category, evt_sub_category;
struct lpfc_fast_path_event *fast_evt_data;
char *evt_data;
uint32_t evt_data_size;
struct Scsi_Host *shost;
fast_evt_data = container_of(evtp, struct lpfc_fast_path_event,
work_evt);
evt_category = (unsigned long) fast_evt_data->un.fabric_evt.event_type;
evt_sub_category = (unsigned long) fast_evt_data->un.
fabric_evt.subcategory;
shost = lpfc_shost_from_vport(fast_evt_data->vport);
if (evt_category == FC_REG_FABRIC_EVENT) {
if (evt_sub_category == LPFC_EVENT_FCPRDCHKERR) {
evt_data = (char *) &fast_evt_data->un.read_check_error;
evt_data_size = sizeof(fast_evt_data->un.
read_check_error);
} else if ((evt_sub_category == LPFC_EVENT_FABRIC_BUSY) ||
(evt_sub_category == LPFC_EVENT_PORT_BUSY)) {
evt_data = (char *) &fast_evt_data->un.fabric_evt;
evt_data_size = sizeof(fast_evt_data->un.fabric_evt);
} else {
lpfc_free_fast_evt(phba, fast_evt_data);
return;
}
} else if (evt_category == FC_REG_SCSI_EVENT) {
switch (evt_sub_category) {
case LPFC_EVENT_QFULL:
case LPFC_EVENT_DEVBSY:
evt_data = (char *) &fast_evt_data->un.scsi_evt;
evt_data_size = sizeof(fast_evt_data->un.scsi_evt);
break;
case LPFC_EVENT_CHECK_COND:
evt_data = (char *) &fast_evt_data->un.check_cond_evt;
evt_data_size = sizeof(fast_evt_data->un.
check_cond_evt);
break;
case LPFC_EVENT_VARQUEDEPTH:
evt_data = (char *) &fast_evt_data->un.queue_depth_evt;
evt_data_size = sizeof(fast_evt_data->un.
queue_depth_evt);
break;
default:
lpfc_free_fast_evt(phba, fast_evt_data);
return;
}
} else {
lpfc_free_fast_evt(phba, fast_evt_data);
return;
}
fc_host_post_vendor_event(shost,
fc_get_event_number(),
evt_data_size,
evt_data,
LPFC_NL_VENDOR_ID);
lpfc_free_fast_evt(phba, fast_evt_data);
return;
}
static void
lpfc_work_list_done(struct lpfc_hba *phba)
{
struct lpfc_work_evt *evtp = NULL;
struct lpfc_nodelist *ndlp;
int free_evt;
spin_lock_irq(&phba->hbalock);
while (!list_empty(&phba->work_list)) {
list_remove_head((&phba->work_list), evtp, typeof(*evtp),
evt_listp);
spin_unlock_irq(&phba->hbalock);
free_evt = 1;
switch (evtp->evt) {
case LPFC_EVT_ELS_RETRY:
ndlp = (struct lpfc_nodelist *) (evtp->evt_arg1);
lpfc_els_retry_delay_handler(ndlp);
free_evt = 0; /* evt is part of ndlp */
/* decrement the node reference count held
* for this queued work
*/
lpfc_nlp_put(ndlp);
break;
case LPFC_EVT_DEV_LOSS:
ndlp = (struct lpfc_nodelist *)(evtp->evt_arg1);
lpfc_dev_loss_tmo_handler(ndlp);
free_evt = 0;
/* decrement the node reference count held for
* this queued work
*/
lpfc_nlp_put(ndlp);
break;
case LPFC_EVT_ONLINE:
if (phba->link_state < LPFC_LINK_DOWN)
*(int *) (evtp->evt_arg1) = lpfc_online(phba);
else
*(int *) (evtp->evt_arg1) = 0;
complete((struct completion *)(evtp->evt_arg2));
break;
case LPFC_EVT_OFFLINE_PREP:
if (phba->link_state >= LPFC_LINK_DOWN)
lpfc_offline_prep(phba);
*(int *)(evtp->evt_arg1) = 0;
complete((struct completion *)(evtp->evt_arg2));
break;
case LPFC_EVT_OFFLINE:
lpfc_offline(phba);
lpfc_sli_brdrestart(phba);
*(int *)(evtp->evt_arg1) =
lpfc_sli_brdready(phba, HS_FFRDY | HS_MBRDY);
lpfc_unblock_mgmt_io(phba);
complete((struct completion *)(evtp->evt_arg2));
break;
case LPFC_EVT_WARM_START:
lpfc_offline(phba);
lpfc_reset_barrier(phba);
lpfc_sli_brdreset(phba);
lpfc_hba_down_post(phba);
*(int *)(evtp->evt_arg1) =
lpfc_sli_brdready(phba, HS_MBRDY);
lpfc_unblock_mgmt_io(phba);
complete((struct completion *)(evtp->evt_arg2));
break;
case LPFC_EVT_KILL:
lpfc_offline(phba);
*(int *)(evtp->evt_arg1)
= (phba->pport->stopped)
? 0 : lpfc_sli_brdkill(phba);
lpfc_unblock_mgmt_io(phba);
complete((struct completion *)(evtp->evt_arg2));
break;
case LPFC_EVT_FASTPATH_MGMT_EVT:
lpfc_send_fastpath_evt(phba, evtp);
free_evt = 0;
break;
}
if (free_evt)
kfree(evtp);
spin_lock_irq(&phba->hbalock);
}
spin_unlock_irq(&phba->hbalock);
}
static void
lpfc_work_done(struct lpfc_hba *phba)
{
struct lpfc_sli_ring *pring;
uint32_t ha_copy, status, control, work_port_events;
struct lpfc_vport **vports;
struct lpfc_vport *vport;
int i;
spin_lock_irq(&phba->hbalock);
ha_copy = phba->work_ha;
phba->work_ha = 0;
spin_unlock_irq(&phba->hbalock);
/* First, try to post the next mailbox command to SLI4 device */
if (phba->pci_dev_grp == LPFC_PCI_DEV_OC)
lpfc_sli4_post_async_mbox(phba);
if (ha_copy & HA_ERATT)
/* Handle the error attention event */
lpfc_handle_eratt(phba);
if (ha_copy & HA_MBATT)
lpfc_sli_handle_mb_event(phba);
if (ha_copy & HA_LATT)
lpfc_handle_latt(phba);
/* Process SLI4 events */
if (phba->pci_dev_grp == LPFC_PCI_DEV_OC) {
if (phba->hba_flag & FCP_XRI_ABORT_EVENT)
lpfc_sli4_fcp_xri_abort_event_proc(phba);
if (phba->hba_flag & ELS_XRI_ABORT_EVENT)
lpfc_sli4_els_xri_abort_event_proc(phba);
if (phba->hba_flag & ASYNC_EVENT)
lpfc_sli4_async_event_proc(phba);
if (phba->hba_flag & HBA_POST_RECEIVE_BUFFER) {
spin_lock_irq(&phba->hbalock);
phba->hba_flag &= ~HBA_POST_RECEIVE_BUFFER;
spin_unlock_irq(&phba->hbalock);
lpfc_sli_hbqbuf_add_hbqs(phba, LPFC_ELS_HBQ);
}
if (phba->hba_flag & HBA_RECEIVE_BUFFER)
lpfc_sli4_handle_received_buffer(phba);
}
vports = lpfc_create_vport_work_array(phba);
if (vports != NULL)
for (i = 0; i <= phba->max_vports; i++) {
/*
* We could have no vports in array if unloading, so if
* this happens then just use the pport
*/
if (vports[i] == NULL && i == 0)
vport = phba->pport;
else
vport = vports[i];
if (vport == NULL)
break;
spin_lock_irq(&vport->work_port_lock);
work_port_events = vport->work_port_events;
vport->work_port_events &= ~work_port_events;
spin_unlock_irq(&vport->work_port_lock);
if (work_port_events & WORKER_DISC_TMO)
lpfc_disc_timeout_handler(vport);
if (work_port_events & WORKER_ELS_TMO)
lpfc_els_timeout_handler(vport);
if (work_port_events & WORKER_HB_TMO)
lpfc_hb_timeout_handler(phba);
if (work_port_events & WORKER_MBOX_TMO)
lpfc_mbox_timeout_handler(phba);
if (work_port_events & WORKER_FABRIC_BLOCK_TMO)
lpfc_unblock_fabric_iocbs(phba);
if (work_port_events & WORKER_FDMI_TMO)
lpfc_fdmi_timeout_handler(vport);
if (work_port_events & WORKER_RAMP_DOWN_QUEUE)
lpfc_ramp_down_queue_handler(phba);
if (work_port_events & WORKER_RAMP_UP_QUEUE)
lpfc_ramp_up_queue_handler(phba);
}
lpfc_destroy_vport_work_array(phba, vports);
pring = &phba->sli.ring[LPFC_ELS_RING];
status = (ha_copy & (HA_RXMASK << (4*LPFC_ELS_RING)));
status >>= (4*LPFC_ELS_RING);
if ((status & HA_RXMASK)
|| (pring->flag & LPFC_DEFERRED_RING_EVENT)) {
if (pring->flag & LPFC_STOP_IOCB_EVENT) {
pring->flag |= LPFC_DEFERRED_RING_EVENT;
/* Set the lpfc data pending flag */
set_bit(LPFC_DATA_READY, &phba->data_flags);
} else {
pring->flag &= ~LPFC_DEFERRED_RING_EVENT;
lpfc_sli_handle_slow_ring_event(phba, pring,
(status &
HA_RXMASK));
}
/*
* Turn on Ring interrupts
*/
if (phba->sli_rev <= LPFC_SLI_REV3) {
spin_lock_irq(&phba->hbalock);
control = readl(phba->HCregaddr);
if (!(control & (HC_R0INT_ENA << LPFC_ELS_RING))) {
lpfc_debugfs_slow_ring_trc(phba,
"WRK Enable ring: cntl:x%x hacopy:x%x",
control, ha_copy, 0);
control |= (HC_R0INT_ENA << LPFC_ELS_RING);
writel(control, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
} else {
lpfc_debugfs_slow_ring_trc(phba,
"WRK Ring ok: cntl:x%x hacopy:x%x",
control, ha_copy, 0);
}
spin_unlock_irq(&phba->hbalock);
}
}
lpfc_work_list_done(phba);
}
int
lpfc_do_work(void *p)
{
struct lpfc_hba *phba = p;
int rc;
set_user_nice(current, -20);
phba->data_flags = 0;
while (!kthread_should_stop()) {
/* wait and check worker queue activities */
rc = wait_event_interruptible(phba->work_waitq,
(test_and_clear_bit(LPFC_DATA_READY,
&phba->data_flags)
|| kthread_should_stop()));
/* Signal wakeup shall terminate the worker thread */
if (rc) {
lpfc_printf_log(phba, KERN_ERR, LOG_ELS,
"0433 Wakeup on signal: rc=x%x\n", rc);
break;
}
/* Attend pending lpfc data processing */
lpfc_work_done(phba);
}
phba->worker_thread = NULL;
lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
"0432 Worker thread stopped.\n");
return 0;
}
/*
* This is only called to handle FC worker events. Since this a rare
* occurance, we allocate a struct lpfc_work_evt structure here instead of
* embedding it in the IOCB.
*/
int
lpfc_workq_post_event(struct lpfc_hba *phba, void *arg1, void *arg2,
uint32_t evt)
{
struct lpfc_work_evt *evtp;
unsigned long flags;
/*
* All Mailbox completions and LPFC_ELS_RING rcv ring IOCB events will
* be queued to worker thread for processing
*/
evtp = kmalloc(sizeof(struct lpfc_work_evt), GFP_ATOMIC);
if (!evtp)
return 0;
evtp->evt_arg1 = arg1;
evtp->evt_arg2 = arg2;
evtp->evt = evt;
spin_lock_irqsave(&phba->hbalock, flags);
list_add_tail(&evtp->evt_listp, &phba->work_list);
spin_unlock_irqrestore(&phba->hbalock, flags);
lpfc_worker_wake_up(phba);
return 1;
}
void
lpfc_cleanup_rpis(struct lpfc_vport *vport, int remove)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
struct lpfc_nodelist *ndlp, *next_ndlp;
int rc;
list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
if (!NLP_CHK_NODE_ACT(ndlp))
continue;
if (ndlp->nlp_state == NLP_STE_UNUSED_NODE)
continue;
if ((phba->sli3_options & LPFC_SLI3_VPORT_TEARDOWN) ||
((vport->port_type == LPFC_NPIV_PORT) &&
(ndlp->nlp_DID == NameServer_DID)))
lpfc_unreg_rpi(vport, ndlp);
/* Leave Fabric nodes alone on link down */
if (!remove && ndlp->nlp_type & NLP_FABRIC)
continue;
rc = lpfc_disc_state_machine(vport, ndlp, NULL,
remove
? NLP_EVT_DEVICE_RM
: NLP_EVT_DEVICE_RECOVERY);
}
if (phba->sli3_options & LPFC_SLI3_VPORT_TEARDOWN) {
lpfc_mbx_unreg_vpi(vport);
spin_lock_irq(shost->host_lock);
vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
spin_unlock_irq(shost->host_lock);
}
}
void
lpfc_port_link_failure(struct lpfc_vport *vport)
{
/* Cleanup any outstanding RSCN activity */
lpfc_els_flush_rscn(vport);
/* Cleanup any outstanding ELS commands */
lpfc_els_flush_cmd(vport);
lpfc_cleanup_rpis(vport, 0);
/* Turn off discovery timer if its running */
lpfc_can_disctmo(vport);
}
void
lpfc_linkdown_port(struct lpfc_vport *vport)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
fc_host_post_event(shost, fc_get_event_number(), FCH_EVT_LINKDOWN, 0);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_ELS_CMD,
"Link Down: state:x%x rtry:x%x flg:x%x",
vport->port_state, vport->fc_ns_retry, vport->fc_flag);
lpfc_port_link_failure(vport);
}
int
lpfc_linkdown(struct lpfc_hba *phba)
{
struct lpfc_vport *vport = phba->pport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_vport **vports;
LPFC_MBOXQ_t *mb;
int i;
if (phba->link_state == LPFC_LINK_DOWN)
return 0;
spin_lock_irq(&phba->hbalock);
phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_DISCOVERED);
if (phba->link_state > LPFC_LINK_DOWN) {
phba->link_state = LPFC_LINK_DOWN;
phba->pport->fc_flag &= ~FC_LBIT;
}
spin_unlock_irq(&phba->hbalock);
vports = lpfc_create_vport_work_array(phba);
if (vports != NULL)
for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
/* Issue a LINK DOWN event to all nodes */
lpfc_linkdown_port(vports[i]);
}
lpfc_destroy_vport_work_array(phba, vports);
/* Clean up any firmware default rpi's */
mb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (mb) {
lpfc_unreg_did(phba, 0xffff, 0xffffffff, mb);
mb->vport = vport;
mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
if (lpfc_sli_issue_mbox(phba, mb, MBX_NOWAIT)
== MBX_NOT_FINISHED) {
mempool_free(mb, phba->mbox_mem_pool);
}
}
/* Setup myDID for link up if we are in pt2pt mode */
if (phba->pport->fc_flag & FC_PT2PT) {
phba->pport->fc_myDID = 0;
mb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (mb) {
lpfc_config_link(phba, mb);
mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
mb->vport = vport;
if (lpfc_sli_issue_mbox(phba, mb, MBX_NOWAIT)
== MBX_NOT_FINISHED) {
mempool_free(mb, phba->mbox_mem_pool);
}
}
spin_lock_irq(shost->host_lock);
phba->pport->fc_flag &= ~(FC_PT2PT | FC_PT2PT_PLOGI);
spin_unlock_irq(shost->host_lock);
}
return 0;
}
static void
lpfc_linkup_cleanup_nodes(struct lpfc_vport *vport)
{
struct lpfc_nodelist *ndlp;
list_for_each_entry(ndlp, &vport->fc_nodes, nlp_listp) {
if (!NLP_CHK_NODE_ACT(ndlp))
continue;
if (ndlp->nlp_state == NLP_STE_UNUSED_NODE)
continue;
if (ndlp->nlp_type & NLP_FABRIC) {
/* On Linkup its safe to clean up the ndlp
* from Fabric connections.
*/
if (ndlp->nlp_DID != Fabric_DID)
lpfc_unreg_rpi(vport, ndlp);
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
} else if (!(ndlp->nlp_flag & NLP_NPR_ADISC)) {
/* Fail outstanding IO now since device is
* marked for PLOGI.
*/
lpfc_unreg_rpi(vport, ndlp);
}
}
}
static void
lpfc_linkup_port(struct lpfc_vport *vport)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
if ((vport->load_flag & FC_UNLOADING) != 0)
return;
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_ELS_CMD,
"Link Up: top:x%x speed:x%x flg:x%x",
phba->fc_topology, phba->fc_linkspeed, phba->link_flag);
/* If NPIV is not enabled, only bring the physical port up */
if (!(phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
(vport != phba->pport))
return;
fc_host_post_event(shost, fc_get_event_number(), FCH_EVT_LINKUP, 0);
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~(FC_PT2PT | FC_PT2PT_PLOGI | FC_ABORT_DISCOVERY |
FC_RSCN_MODE | FC_NLP_MORE | FC_RSCN_DISCOVERY);
vport->fc_flag |= FC_NDISC_ACTIVE;
vport->fc_ns_retry = 0;
spin_unlock_irq(shost->host_lock);
if (vport->fc_flag & FC_LBIT)
lpfc_linkup_cleanup_nodes(vport);
}
static int
lpfc_linkup(struct lpfc_hba *phba)
{
struct lpfc_vport **vports;
int i;
phba->link_state = LPFC_LINK_UP;
/* Unblock fabric iocbs if they are blocked */
clear_bit(FABRIC_COMANDS_BLOCKED, &phba->bit_flags);
del_timer_sync(&phba->fabric_block_timer);
vports = lpfc_create_vport_work_array(phba);
if (vports != NULL)
for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
lpfc_linkup_port(vports[i]);
lpfc_destroy_vport_work_array(phba, vports);
if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
(phba->sli_rev < LPFC_SLI_REV4))
lpfc_issue_clear_la(phba, phba->pport);
return 0;
}
/*
* This routine handles processing a CLEAR_LA mailbox
* command upon completion. It is setup in the LPFC_MBOXQ
* as the completion routine when the command is
* handed off to the SLI layer.
*/
static void
lpfc_mbx_cmpl_clear_la(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
struct lpfc_vport *vport = pmb->vport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_sli *psli = &phba->sli;
MAILBOX_t *mb = &pmb->u.mb;
uint32_t control;
/* Since we don't do discovery right now, turn these off here */
psli->ring[psli->extra_ring].flag &= ~LPFC_STOP_IOCB_EVENT;
psli->ring[psli->fcp_ring].flag &= ~LPFC_STOP_IOCB_EVENT;
psli->ring[psli->next_ring].flag &= ~LPFC_STOP_IOCB_EVENT;
/* Check for error */
if ((mb->mbxStatus) && (mb->mbxStatus != 0x1601)) {
/* CLEAR_LA mbox error <mbxStatus> state <hba_state> */
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX,
"0320 CLEAR_LA mbxStatus error x%x hba "
"state x%x\n",
mb->mbxStatus, vport->port_state);
phba->link_state = LPFC_HBA_ERROR;
goto out;
}
if (vport->port_type == LPFC_PHYSICAL_PORT)
phba->link_state = LPFC_HBA_READY;
spin_lock_irq(&phba->hbalock);
psli->sli_flag |= LPFC_PROCESS_LA;
control = readl(phba->HCregaddr);
control |= HC_LAINT_ENA;
writel(control, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
spin_unlock_irq(&phba->hbalock);
mempool_free(pmb, phba->mbox_mem_pool);
return;
out:
/* Device Discovery completes */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0225 Device Discovery completes\n");
mempool_free(pmb, phba->mbox_mem_pool);
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~FC_ABORT_DISCOVERY;
spin_unlock_irq(shost->host_lock);
lpfc_can_disctmo(vport);
/* turn on Link Attention interrupts */
spin_lock_irq(&phba->hbalock);
psli->sli_flag |= LPFC_PROCESS_LA;
control = readl(phba->HCregaddr);
control |= HC_LAINT_ENA;
writel(control, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
spin_unlock_irq(&phba->hbalock);
return;
}
static void
lpfc_mbx_cmpl_local_config_link(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
struct lpfc_vport *vport = pmb->vport;
if (pmb->u.mb.mbxStatus)
goto out;
mempool_free(pmb, phba->mbox_mem_pool);
if (phba->fc_topology == TOPOLOGY_LOOP &&
vport->fc_flag & FC_PUBLIC_LOOP &&
!(vport->fc_flag & FC_LBIT)) {
/* Need to wait for FAN - use discovery timer
* for timeout. port_state is identically
* LPFC_LOCAL_CFG_LINK while waiting for FAN
*/
lpfc_set_disctmo(vport);
return;
}
/* Start discovery by sending a FLOGI. port_state is identically
* LPFC_FLOGI while waiting for FLOGI cmpl
*/
if (vport->port_state != LPFC_FLOGI) {
lpfc_initial_flogi(vport);
}
return;
out:
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX,
"0306 CONFIG_LINK mbxStatus error x%x "
"HBA state x%x\n",
pmb->u.mb.mbxStatus, vport->port_state);
mempool_free(pmb, phba->mbox_mem_pool);
lpfc_linkdown(phba);
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0200 CONFIG_LINK bad hba state x%x\n",
vport->port_state);
lpfc_issue_clear_la(phba, vport);
return;
}
static void
lpfc_mbx_cmpl_reg_fcfi(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
{
struct lpfc_vport *vport = mboxq->vport;
unsigned long flags;
if (mboxq->u.mb.mbxStatus) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX,
"2017 REG_FCFI mbxStatus error x%x "
"HBA state x%x\n",
mboxq->u.mb.mbxStatus, vport->port_state);
mempool_free(mboxq, phba->mbox_mem_pool);
return;
}
/* Start FCoE discovery by sending a FLOGI. */
phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi, &mboxq->u.mqe.un.reg_fcfi);
/* Set the FCFI registered flag */
spin_lock_irqsave(&phba->hbalock, flags);
phba->fcf.fcf_flag |= FCF_REGISTERED;
spin_unlock_irqrestore(&phba->hbalock, flags);
/* If there is a pending FCoE event, restart FCF table scan. */
if (lpfc_check_pending_fcoe_event(phba, 1)) {
mempool_free(mboxq, phba->mbox_mem_pool);
return;
}
if (vport->port_state != LPFC_FLOGI) {
spin_lock_irqsave(&phba->hbalock, flags);
phba->fcf.fcf_flag |= (FCF_DISCOVERED | FCF_IN_USE);
phba->hba_flag &= ~FCF_DISC_INPROGRESS;
spin_unlock_irqrestore(&phba->hbalock, flags);
lpfc_initial_flogi(vport);
}
mempool_free(mboxq, phba->mbox_mem_pool);
return;
}
/**
* lpfc_fab_name_match - Check if the fcf fabric name match.
* @fab_name: pointer to fabric name.
* @new_fcf_record: pointer to fcf record.
*
* This routine compare the fcf record's fabric name with provided
* fabric name. If the fabric name are identical this function
* returns 1 else return 0.
**/
static uint32_t
lpfc_fab_name_match(uint8_t *fab_name, struct fcf_record *new_fcf_record)
{
if ((fab_name[0] ==
bf_get(lpfc_fcf_record_fab_name_0, new_fcf_record)) &&
(fab_name[1] ==
bf_get(lpfc_fcf_record_fab_name_1, new_fcf_record)) &&
(fab_name[2] ==
bf_get(lpfc_fcf_record_fab_name_2, new_fcf_record)) &&
(fab_name[3] ==
bf_get(lpfc_fcf_record_fab_name_3, new_fcf_record)) &&
(fab_name[4] ==
bf_get(lpfc_fcf_record_fab_name_4, new_fcf_record)) &&
(fab_name[5] ==
bf_get(lpfc_fcf_record_fab_name_5, new_fcf_record)) &&
(fab_name[6] ==
bf_get(lpfc_fcf_record_fab_name_6, new_fcf_record)) &&
(fab_name[7] ==
bf_get(lpfc_fcf_record_fab_name_7, new_fcf_record)))
return 1;
else
return 0;
}
/**
* lpfc_sw_name_match - Check if the fcf switch name match.
* @fab_name: pointer to fabric name.
* @new_fcf_record: pointer to fcf record.
*
* This routine compare the fcf record's switch name with provided
* switch name. If the switch name are identical this function
* returns 1 else return 0.
**/
static uint32_t
lpfc_sw_name_match(uint8_t *sw_name, struct fcf_record *new_fcf_record)
{
if ((sw_name[0] ==
bf_get(lpfc_fcf_record_switch_name_0, new_fcf_record)) &&
(sw_name[1] ==
bf_get(lpfc_fcf_record_switch_name_1, new_fcf_record)) &&
(sw_name[2] ==
bf_get(lpfc_fcf_record_switch_name_2, new_fcf_record)) &&
(sw_name[3] ==
bf_get(lpfc_fcf_record_switch_name_3, new_fcf_record)) &&
(sw_name[4] ==
bf_get(lpfc_fcf_record_switch_name_4, new_fcf_record)) &&
(sw_name[5] ==
bf_get(lpfc_fcf_record_switch_name_5, new_fcf_record)) &&
(sw_name[6] ==
bf_get(lpfc_fcf_record_switch_name_6, new_fcf_record)) &&
(sw_name[7] ==
bf_get(lpfc_fcf_record_switch_name_7, new_fcf_record)))
return 1;
else
return 0;
}
/**
* lpfc_mac_addr_match - Check if the fcf mac address match.
* @phba: pointer to lpfc hba data structure.
* @new_fcf_record: pointer to fcf record.
*
* This routine compare the fcf record's mac address with HBA's
* FCF mac address. If the mac addresses are identical this function
* returns 1 else return 0.
**/
static uint32_t
lpfc_mac_addr_match(struct lpfc_hba *phba, struct fcf_record *new_fcf_record)
{
if ((phba->fcf.mac_addr[0] ==
bf_get(lpfc_fcf_record_mac_0, new_fcf_record)) &&
(phba->fcf.mac_addr[1] ==
bf_get(lpfc_fcf_record_mac_1, new_fcf_record)) &&
(phba->fcf.mac_addr[2] ==
bf_get(lpfc_fcf_record_mac_2, new_fcf_record)) &&
(phba->fcf.mac_addr[3] ==
bf_get(lpfc_fcf_record_mac_3, new_fcf_record)) &&
(phba->fcf.mac_addr[4] ==
bf_get(lpfc_fcf_record_mac_4, new_fcf_record)) &&
(phba->fcf.mac_addr[5] ==
bf_get(lpfc_fcf_record_mac_5, new_fcf_record)))
return 1;
else
return 0;
}
/**
* lpfc_copy_fcf_record - Copy fcf information to lpfc_hba.
* @phba: pointer to lpfc hba data structure.
* @new_fcf_record: pointer to fcf record.
*
* This routine copies the FCF information from the FCF
* record to lpfc_hba data structure.
**/
static void
lpfc_copy_fcf_record(struct lpfc_hba *phba, struct fcf_record *new_fcf_record)
{
phba->fcf.fabric_name[0] =
bf_get(lpfc_fcf_record_fab_name_0, new_fcf_record);
phba->fcf.fabric_name[1] =
bf_get(lpfc_fcf_record_fab_name_1, new_fcf_record);
phba->fcf.fabric_name[2] =
bf_get(lpfc_fcf_record_fab_name_2, new_fcf_record);
phba->fcf.fabric_name[3] =
bf_get(lpfc_fcf_record_fab_name_3, new_fcf_record);
phba->fcf.fabric_name[4] =
bf_get(lpfc_fcf_record_fab_name_4, new_fcf_record);
phba->fcf.fabric_name[5] =
bf_get(lpfc_fcf_record_fab_name_5, new_fcf_record);
phba->fcf.fabric_name[6] =
bf_get(lpfc_fcf_record_fab_name_6, new_fcf_record);
phba->fcf.fabric_name[7] =
bf_get(lpfc_fcf_record_fab_name_7, new_fcf_record);
phba->fcf.mac_addr[0] =
bf_get(lpfc_fcf_record_mac_0, new_fcf_record);
phba->fcf.mac_addr[1] =
bf_get(lpfc_fcf_record_mac_1, new_fcf_record);
phba->fcf.mac_addr[2] =
bf_get(lpfc_fcf_record_mac_2, new_fcf_record);
phba->fcf.mac_addr[3] =
bf_get(lpfc_fcf_record_mac_3, new_fcf_record);
phba->fcf.mac_addr[4] =
bf_get(lpfc_fcf_record_mac_4, new_fcf_record);
phba->fcf.mac_addr[5] =
bf_get(lpfc_fcf_record_mac_5, new_fcf_record);
phba->fcf.fcf_indx = bf_get(lpfc_fcf_record_fcf_index, new_fcf_record);
phba->fcf.priority = new_fcf_record->fip_priority;
phba->fcf.switch_name[0] =
bf_get(lpfc_fcf_record_switch_name_0, new_fcf_record);
phba->fcf.switch_name[1] =
bf_get(lpfc_fcf_record_switch_name_1, new_fcf_record);
phba->fcf.switch_name[2] =
bf_get(lpfc_fcf_record_switch_name_2, new_fcf_record);
phba->fcf.switch_name[3] =
bf_get(lpfc_fcf_record_switch_name_3, new_fcf_record);
phba->fcf.switch_name[4] =
bf_get(lpfc_fcf_record_switch_name_4, new_fcf_record);
phba->fcf.switch_name[5] =
bf_get(lpfc_fcf_record_switch_name_5, new_fcf_record);
phba->fcf.switch_name[6] =
bf_get(lpfc_fcf_record_switch_name_6, new_fcf_record);
phba->fcf.switch_name[7] =
bf_get(lpfc_fcf_record_switch_name_7, new_fcf_record);
}
/**
* lpfc_register_fcf - Register the FCF with hba.
* @phba: pointer to lpfc hba data structure.
*
* This routine issues a register fcfi mailbox command to register
* the fcf with HBA.
**/
static void
lpfc_register_fcf(struct lpfc_hba *phba)
{
LPFC_MBOXQ_t *fcf_mbxq;
int rc;
unsigned long flags;
spin_lock_irqsave(&phba->hbalock, flags);
/* If the FCF is not availabe do nothing. */
if (!(phba->fcf.fcf_flag & FCF_AVAILABLE)) {
spin_unlock_irqrestore(&phba->hbalock, flags);
return;
}
/* The FCF is already registered, start discovery */
if (phba->fcf.fcf_flag & FCF_REGISTERED) {
phba->fcf.fcf_flag |= (FCF_DISCOVERED | FCF_IN_USE);
phba->hba_flag &= ~FCF_DISC_INPROGRESS;
spin_unlock_irqrestore(&phba->hbalock, flags);
if (phba->pport->port_state != LPFC_FLOGI)
lpfc_initial_flogi(phba->pport);
return;
}
spin_unlock_irqrestore(&phba->hbalock, flags);
fcf_mbxq = mempool_alloc(phba->mbox_mem_pool,
GFP_KERNEL);
if (!fcf_mbxq)
return;
lpfc_reg_fcfi(phba, fcf_mbxq);
fcf_mbxq->vport = phba->pport;
fcf_mbxq->mbox_cmpl = lpfc_mbx_cmpl_reg_fcfi;
rc = lpfc_sli_issue_mbox(phba, fcf_mbxq, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED)
mempool_free(fcf_mbxq, phba->mbox_mem_pool);
return;
}
/**
* lpfc_match_fcf_conn_list - Check if the FCF record can be used for discovery.
* @phba: pointer to lpfc hba data structure.
* @new_fcf_record: pointer to fcf record.
* @boot_flag: Indicates if this record used by boot bios.
* @addr_mode: The address mode to be used by this FCF
*
* This routine compare the fcf record with connect list obtained from the
* config region to decide if this FCF can be used for SAN discovery. It returns
* 1 if this record can be used for SAN discovery else return zero. If this FCF
* record can be used for SAN discovery, the boot_flag will indicate if this FCF
* is used by boot bios and addr_mode will indicate the addressing mode to be
* used for this FCF when the function returns.
* If the FCF record need to be used with a particular vlan id, the vlan is
* set in the vlan_id on return of the function. If not VLAN tagging need to
* be used with the FCF vlan_id will be set to 0xFFFF;
**/
static int
lpfc_match_fcf_conn_list(struct lpfc_hba *phba,
struct fcf_record *new_fcf_record,
uint32_t *boot_flag, uint32_t *addr_mode,
uint16_t *vlan_id)
{
struct lpfc_fcf_conn_entry *conn_entry;
/* If FCF not available return 0 */
if (!bf_get(lpfc_fcf_record_fcf_avail, new_fcf_record) ||
!bf_get(lpfc_fcf_record_fcf_valid, new_fcf_record))
return 0;
if (!phba->cfg_enable_fip) {
*boot_flag = 0;
*addr_mode = bf_get(lpfc_fcf_record_mac_addr_prov,
new_fcf_record);
if (phba->valid_vlan)
*vlan_id = phba->vlan_id;
else
*vlan_id = 0xFFFF;
return 1;
}
/*
* If there are no FCF connection table entry, driver connect to all
* FCFs.
*/
if (list_empty(&phba->fcf_conn_rec_list)) {
*boot_flag = 0;
*addr_mode = bf_get(lpfc_fcf_record_mac_addr_prov,
new_fcf_record);
/*
* When there are no FCF connect entries, use driver's default
* addressing mode - FPMA.
*/
if (*addr_mode & LPFC_FCF_FPMA)
*addr_mode = LPFC_FCF_FPMA;
*vlan_id = 0xFFFF;
return 1;
}
list_for_each_entry(conn_entry, &phba->fcf_conn_rec_list, list) {
if (!(conn_entry->conn_rec.flags & FCFCNCT_VALID))
continue;
if ((conn_entry->conn_rec.flags & FCFCNCT_FBNM_VALID) &&
!lpfc_fab_name_match(conn_entry->conn_rec.fabric_name,
new_fcf_record))
continue;
if ((conn_entry->conn_rec.flags & FCFCNCT_SWNM_VALID) &&
!lpfc_sw_name_match(conn_entry->conn_rec.switch_name,
new_fcf_record))
continue;
if (conn_entry->conn_rec.flags & FCFCNCT_VLAN_VALID) {
/*
* If the vlan bit map does not have the bit set for the
* vlan id to be used, then it is not a match.
*/
if (!(new_fcf_record->vlan_bitmap
[conn_entry->conn_rec.vlan_tag / 8] &
(1 << (conn_entry->conn_rec.vlan_tag % 8))))
continue;
}
/*
* If connection record does not support any addressing mode,
* skip the FCF record.
*/
if (!(bf_get(lpfc_fcf_record_mac_addr_prov, new_fcf_record)
& (LPFC_FCF_FPMA | LPFC_FCF_SPMA)))
continue;
/*
* Check if the connection record specifies a required
* addressing mode.
*/
if ((conn_entry->conn_rec.flags & FCFCNCT_AM_VALID) &&
!(conn_entry->conn_rec.flags & FCFCNCT_AM_PREFERRED)) {
/*
* If SPMA required but FCF not support this continue.
*/
if ((conn_entry->conn_rec.flags & FCFCNCT_AM_SPMA) &&
!(bf_get(lpfc_fcf_record_mac_addr_prov,
new_fcf_record) & LPFC_FCF_SPMA))
continue;
/*
* If FPMA required but FCF not support this continue.
*/
if (!(conn_entry->conn_rec.flags & FCFCNCT_AM_SPMA) &&
!(bf_get(lpfc_fcf_record_mac_addr_prov,
new_fcf_record) & LPFC_FCF_FPMA))
continue;
}
/*
* This fcf record matches filtering criteria.
*/
if (conn_entry->conn_rec.flags & FCFCNCT_BOOT)
*boot_flag = 1;
else
*boot_flag = 0;
/*
* If user did not specify any addressing mode, or if the
* prefered addressing mode specified by user is not supported
* by FCF, allow fabric to pick the addressing mode.
*/
*addr_mode = bf_get(lpfc_fcf_record_mac_addr_prov,
new_fcf_record);
/*
* If the user specified a required address mode, assign that
* address mode
*/
if ((conn_entry->conn_rec.flags & FCFCNCT_AM_VALID) &&
(!(conn_entry->conn_rec.flags & FCFCNCT_AM_PREFERRED)))
*addr_mode = (conn_entry->conn_rec.flags &
FCFCNCT_AM_SPMA) ?
LPFC_FCF_SPMA : LPFC_FCF_FPMA;
/*
* If the user specified a prefered address mode, use the
* addr mode only if FCF support the addr_mode.
*/
else if ((conn_entry->conn_rec.flags & FCFCNCT_AM_VALID) &&
(conn_entry->conn_rec.flags & FCFCNCT_AM_PREFERRED) &&
(conn_entry->conn_rec.flags & FCFCNCT_AM_SPMA) &&
(*addr_mode & LPFC_FCF_SPMA))
*addr_mode = LPFC_FCF_SPMA;
else if ((conn_entry->conn_rec.flags & FCFCNCT_AM_VALID) &&
(conn_entry->conn_rec.flags & FCFCNCT_AM_PREFERRED) &&
!(conn_entry->conn_rec.flags & FCFCNCT_AM_SPMA) &&
(*addr_mode & LPFC_FCF_FPMA))
*addr_mode = LPFC_FCF_FPMA;
if (conn_entry->conn_rec.flags & FCFCNCT_VLAN_VALID)
*vlan_id = conn_entry->conn_rec.vlan_tag;
else
*vlan_id = 0xFFFF;
return 1;
}
return 0;
}
/**
* lpfc_check_pending_fcoe_event - Check if there is pending fcoe event.
* @phba: pointer to lpfc hba data structure.
* @unreg_fcf: Unregister FCF if FCF table need to be re-scaned.
*
* This function check if there is any fcoe event pending while driver
* scan FCF entries. If there is any pending event, it will restart the
* FCF saning and return 1 else return 0.
*/
int
lpfc_check_pending_fcoe_event(struct lpfc_hba *phba, uint8_t unreg_fcf)
{
LPFC_MBOXQ_t *mbox;
int rc;
/*
* If the Link is up and no FCoE events while in the
* FCF discovery, no need to restart FCF discovery.
*/
if ((phba->link_state >= LPFC_LINK_UP) &&
(phba->fcoe_eventtag == phba->fcoe_eventtag_at_fcf_scan))
return 0;
spin_lock_irq(&phba->hbalock);
phba->fcf.fcf_flag &= ~FCF_AVAILABLE;
spin_unlock_irq(&phba->hbalock);
if (phba->link_state >= LPFC_LINK_UP)
lpfc_sli4_read_fcf_record(phba, LPFC_FCOE_FCF_GET_FIRST);
if (unreg_fcf) {
spin_lock_irq(&phba->hbalock);
phba->fcf.fcf_flag &= ~FCF_REGISTERED;
spin_unlock_irq(&phba->hbalock);
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!mbox) {
lpfc_printf_log(phba, KERN_ERR,
LOG_DISCOVERY|LOG_MBOX,
"2610 UNREG_FCFI mbox allocation failed\n");
return 1;
}
lpfc_unreg_fcfi(mbox, phba->fcf.fcfi);
mbox->vport = phba->pport;
mbox->mbox_cmpl = lpfc_unregister_fcfi_cmpl;
rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
lpfc_printf_log(phba, KERN_ERR, LOG_DISCOVERY|LOG_MBOX,
"2611 UNREG_FCFI issue mbox failed\n");
mempool_free(mbox, phba->mbox_mem_pool);
}
}
return 1;
}
/**
* lpfc_mbx_cmpl_read_fcf_record - Completion handler for read_fcf mbox.
* @phba: pointer to lpfc hba data structure.
* @mboxq: pointer to mailbox object.
*
* This function iterate through all the fcf records available in
* HBA and choose the optimal FCF record for discovery. After finding
* the FCF for discovery it register the FCF record and kick start
* discovery.
* If FCF_IN_USE flag is set in currently used FCF, the routine try to
* use a FCF record which match fabric name and mac address of the
* currently used FCF record.
* If the driver support only one FCF, it will try to use the FCF record
* used by BOOT_BIOS.
*/
void
lpfc_mbx_cmpl_read_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
{
void *virt_addr;
dma_addr_t phys_addr;
uint8_t *bytep;
struct lpfc_mbx_sge sge;
struct lpfc_mbx_read_fcf_tbl *read_fcf;
uint32_t shdr_status, shdr_add_status;
union lpfc_sli4_cfg_shdr *shdr;
struct fcf_record *new_fcf_record;
int rc;
uint32_t boot_flag, addr_mode;
uint32_t next_fcf_index;
unsigned long flags;
uint16_t vlan_id;
/* If there is pending FCoE event restart FCF table scan */
if (lpfc_check_pending_fcoe_event(phba, 0)) {
lpfc_sli4_mbox_cmd_free(phba, mboxq);
return;
}
/* Get the first SGE entry from the non-embedded DMA memory. This
* routine only uses a single SGE.
*/
lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
phys_addr = getPaddr(sge.pa_hi, sge.pa_lo);
if (unlikely(!mboxq->sge_array)) {
lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
"2524 Failed to get the non-embedded SGE "
"virtual address\n");
goto out;
}
virt_addr = mboxq->sge_array->addr[0];
shdr = (union lpfc_sli4_cfg_shdr *)virt_addr;
shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
&shdr->response);
/*
* The FCF Record was read and there is no reason for the driver
* to maintain the FCF record data or memory. Instead, just need
* to book keeping the FCFIs can be used.
*/
if (shdr_status || shdr_add_status) {
lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
"2521 READ_FCF_RECORD mailbox failed "
"with status x%x add_status x%x, mbx\n",
shdr_status, shdr_add_status);
goto out;
}
/* Interpreting the returned information of FCF records */
read_fcf = (struct lpfc_mbx_read_fcf_tbl *)virt_addr;
lpfc_sli_pcimem_bcopy(read_fcf, read_fcf,
sizeof(struct lpfc_mbx_read_fcf_tbl));
next_fcf_index = bf_get(lpfc_mbx_read_fcf_tbl_nxt_vindx, read_fcf);
new_fcf_record = (struct fcf_record *)(virt_addr +
sizeof(struct lpfc_mbx_read_fcf_tbl));
lpfc_sli_pcimem_bcopy(new_fcf_record, new_fcf_record,
sizeof(struct fcf_record));
bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
rc = lpfc_match_fcf_conn_list(phba, new_fcf_record,
&boot_flag, &addr_mode,
&vlan_id);
/*
* If the fcf record does not match with connect list entries
* read the next entry.
*/
if (!rc)
goto read_next_fcf;
/*
* If this is not the first FCF discovery of the HBA, use last
* FCF record for the discovery.
*/
spin_lock_irqsave(&phba->hbalock, flags);
if (phba->fcf.fcf_flag & FCF_IN_USE) {
if (lpfc_fab_name_match(phba->fcf.fabric_name,
new_fcf_record) &&
lpfc_sw_name_match(phba->fcf.switch_name,
new_fcf_record) &&
lpfc_mac_addr_match(phba, new_fcf_record)) {
phba->fcf.fcf_flag |= FCF_AVAILABLE;
spin_unlock_irqrestore(&phba->hbalock, flags);
goto out;
}
spin_unlock_irqrestore(&phba->hbalock, flags);
goto read_next_fcf;
}
if (phba->fcf.fcf_flag & FCF_AVAILABLE) {
/*
* If the current FCF record does not have boot flag
* set and new fcf record has boot flag set, use the
* new fcf record.
*/
if (boot_flag && !(phba->fcf.fcf_flag & FCF_BOOT_ENABLE)) {
/* Use this FCF record */
lpfc_copy_fcf_record(phba, new_fcf_record);
phba->fcf.addr_mode = addr_mode;
phba->fcf.fcf_flag |= FCF_BOOT_ENABLE;
if (vlan_id != 0xFFFF) {
phba->fcf.fcf_flag |= FCF_VALID_VLAN;
phba->fcf.vlan_id = vlan_id;
}
spin_unlock_irqrestore(&phba->hbalock, flags);
goto read_next_fcf;
}
/*
* If the current FCF record has boot flag set and the
* new FCF record does not have boot flag, read the next
* FCF record.
*/
if (!boot_flag && (phba->fcf.fcf_flag & FCF_BOOT_ENABLE)) {
spin_unlock_irqrestore(&phba->hbalock, flags);
goto read_next_fcf;
}
/*
* If there is a record with lower priority value for
* the current FCF, use that record.
*/
if (lpfc_fab_name_match(phba->fcf.fabric_name,
new_fcf_record) &&
(new_fcf_record->fip_priority < phba->fcf.priority)) {
/* Use this FCF record */
lpfc_copy_fcf_record(phba, new_fcf_record);
phba->fcf.addr_mode = addr_mode;
if (vlan_id != 0xFFFF) {
phba->fcf.fcf_flag |= FCF_VALID_VLAN;
phba->fcf.vlan_id = vlan_id;
}
spin_unlock_irqrestore(&phba->hbalock, flags);
goto read_next_fcf;
}
spin_unlock_irqrestore(&phba->hbalock, flags);
goto read_next_fcf;
}
/*
* This is the first available FCF record, use this
* record.
*/
lpfc_copy_fcf_record(phba, new_fcf_record);
phba->fcf.addr_mode = addr_mode;
if (boot_flag)
phba->fcf.fcf_flag |= FCF_BOOT_ENABLE;
phba->fcf.fcf_flag |= FCF_AVAILABLE;
if (vlan_id != 0xFFFF) {
phba->fcf.fcf_flag |= FCF_VALID_VLAN;
phba->fcf.vlan_id = vlan_id;
}
spin_unlock_irqrestore(&phba->hbalock, flags);
goto read_next_fcf;
read_next_fcf:
lpfc_sli4_mbox_cmd_free(phba, mboxq);
if (next_fcf_index == LPFC_FCOE_FCF_NEXT_NONE || next_fcf_index == 0)
lpfc_register_fcf(phba);
else
lpfc_sli4_read_fcf_record(phba, next_fcf_index);
return;
out:
lpfc_sli4_mbox_cmd_free(phba, mboxq);
lpfc_register_fcf(phba);
return;
}
/**
* lpfc_init_vpi_cmpl - Completion handler for init_vpi mbox command.
* @phba: pointer to lpfc hba data structure.
* @mboxq: pointer to mailbox data structure.
*
* This function handles completion of init vpi mailbox command.
*/
static void
lpfc_init_vpi_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
{
struct lpfc_vport *vport = mboxq->vport;
if (mboxq->u.mb.mbxStatus) {
lpfc_printf_vlog(vport, KERN_ERR,
LOG_MBOX,
"2609 Init VPI mailbox failed 0x%x\n",
mboxq->u.mb.mbxStatus);
mempool_free(mboxq, phba->mbox_mem_pool);
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
return;
}
vport->fc_flag &= ~FC_VPORT_NEEDS_INIT_VPI;
if (phba->link_flag & LS_NPIV_FAB_SUPPORTED)
lpfc_initial_fdisc(vport);
else {
lpfc_vport_set_state(vport, FC_VPORT_NO_FABRIC_SUPP);
lpfc_printf_vlog(vport, KERN_ERR,
LOG_ELS,
"2606 No NPIV Fabric support\n");
}
return;
}
/**
* lpfc_start_fdiscs - send fdiscs for each vports on this port.
* @phba: pointer to lpfc hba data structure.
*
* This function loops through the list of vports on the @phba and issues an
* FDISC if possible.
*/
void
lpfc_start_fdiscs(struct lpfc_hba *phba)
{
struct lpfc_vport **vports;
int i;
LPFC_MBOXQ_t *mboxq;
int rc;
vports = lpfc_create_vport_work_array(phba);
if (vports != NULL) {
for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
continue;
/* There are no vpi for this vport */
if (vports[i]->vpi > phba->max_vpi) {
lpfc_vport_set_state(vports[i],
FC_VPORT_FAILED);
continue;
}
if (phba->fc_topology == TOPOLOGY_LOOP) {
lpfc_vport_set_state(vports[i],
FC_VPORT_LINKDOWN);
continue;
}
if (vports[i]->fc_flag & FC_VPORT_NEEDS_INIT_VPI) {
mboxq = mempool_alloc(phba->mbox_mem_pool,
GFP_KERNEL);
if (!mboxq) {
lpfc_printf_vlog(vports[i], KERN_ERR,
LOG_MBOX, "2607 Failed to allocate "
"init_vpi mailbox\n");
continue;
}
lpfc_init_vpi(phba, mboxq, vports[i]->vpi);
mboxq->vport = vports[i];
mboxq->mbox_cmpl = lpfc_init_vpi_cmpl;
rc = lpfc_sli_issue_mbox(phba, mboxq,
MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
lpfc_printf_vlog(vports[i], KERN_ERR,
LOG_MBOX, "2608 Failed to issue "
"init_vpi mailbox\n");
mempool_free(mboxq,
phba->mbox_mem_pool);
}
continue;
}
if (phba->link_flag & LS_NPIV_FAB_SUPPORTED)
lpfc_initial_fdisc(vports[i]);
else {
lpfc_vport_set_state(vports[i],
FC_VPORT_NO_FABRIC_SUPP);
lpfc_printf_vlog(vports[i], KERN_ERR,
LOG_ELS,
"0259 No NPIV "
"Fabric support\n");
}
}
}
lpfc_destroy_vport_work_array(phba, vports);
}
void
lpfc_mbx_cmpl_reg_vfi(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
{
struct lpfc_dmabuf *dmabuf = mboxq->context1;
struct lpfc_vport *vport = mboxq->vport;
if (mboxq->u.mb.mbxStatus) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX,
"2018 REG_VFI mbxStatus error x%x "
"HBA state x%x\n",
mboxq->u.mb.mbxStatus, vport->port_state);
if (phba->fc_topology == TOPOLOGY_LOOP) {
/* FLOGI failed, use loop map to make discovery list */
lpfc_disc_list_loopmap(vport);
/* Start discovery */
lpfc_disc_start(vport);
goto fail_free_mem;
}
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
goto fail_free_mem;
}
/* Mark the vport has registered with its VFI */
vport->vfi_state |= LPFC_VFI_REGISTERED;
if (vport->port_state == LPFC_FABRIC_CFG_LINK) {
lpfc_start_fdiscs(phba);
lpfc_do_scr_ns_plogi(phba, vport);
}
fail_free_mem:
mempool_free(mboxq, phba->mbox_mem_pool);
lpfc_mbuf_free(phba, dmabuf->virt, dmabuf->phys);
kfree(dmabuf);
return;
}
static void
lpfc_mbx_cmpl_read_sparam(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
MAILBOX_t *mb = &pmb->u.mb;
struct lpfc_dmabuf *mp = (struct lpfc_dmabuf *) pmb->context1;
struct lpfc_vport *vport = pmb->vport;
/* Check for error */
if (mb->mbxStatus) {
/* READ_SPARAM mbox error <mbxStatus> state <hba_state> */
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX,
"0319 READ_SPARAM mbxStatus error x%x "
"hba state x%x>\n",
mb->mbxStatus, vport->port_state);
lpfc_linkdown(phba);
goto out;
}
memcpy((uint8_t *) &vport->fc_sparam, (uint8_t *) mp->virt,
sizeof (struct serv_parm));
if (phba->cfg_soft_wwnn)
u64_to_wwn(phba->cfg_soft_wwnn,
vport->fc_sparam.nodeName.u.wwn);
if (phba->cfg_soft_wwpn)
u64_to_wwn(phba->cfg_soft_wwpn,
vport->fc_sparam.portName.u.wwn);
memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
sizeof(vport->fc_nodename));
memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
sizeof(vport->fc_portname));
if (vport->port_type == LPFC_PHYSICAL_PORT) {
memcpy(&phba->wwnn, &vport->fc_nodename, sizeof(phba->wwnn));
memcpy(&phba->wwpn, &vport->fc_portname, sizeof(phba->wwnn));
}
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
return;
out:
pmb->context1 = NULL;
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
lpfc_issue_clear_la(phba, vport);
mempool_free(pmb, phba->mbox_mem_pool);
return;
}
static void
lpfc_mbx_process_link_up(struct lpfc_hba *phba, READ_LA_VAR *la)
{
struct lpfc_vport *vport = phba->pport;
LPFC_MBOXQ_t *sparam_mbox, *cfglink_mbox = NULL;
int i;
struct lpfc_dmabuf *mp;
int rc;
struct fcf_record *fcf_record;
sparam_mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
spin_lock_irq(&phba->hbalock);
switch (la->UlnkSpeed) {
case LA_1GHZ_LINK:
phba->fc_linkspeed = LA_1GHZ_LINK;
break;
case LA_2GHZ_LINK:
phba->fc_linkspeed = LA_2GHZ_LINK;
break;
case LA_4GHZ_LINK:
phba->fc_linkspeed = LA_4GHZ_LINK;
break;
case LA_8GHZ_LINK:
phba->fc_linkspeed = LA_8GHZ_LINK;
break;
case LA_10GHZ_LINK:
phba->fc_linkspeed = LA_10GHZ_LINK;
break;
default:
phba->fc_linkspeed = LA_UNKNW_LINK;
break;
}
phba->fc_topology = la->topology;
phba->link_flag &= ~LS_NPIV_FAB_SUPPORTED;
if (phba->fc_topology == TOPOLOGY_LOOP) {
phba->sli3_options &= ~LPFC_SLI3_NPIV_ENABLED;
if (phba->cfg_enable_npiv)
lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
"1309 Link Up Event npiv not supported in loop "
"topology\n");
/* Get Loop Map information */
if (la->il)
vport->fc_flag |= FC_LBIT;
vport->fc_myDID = la->granted_AL_PA;
i = la->un.lilpBde64.tus.f.bdeSize;
if (i == 0) {
phba->alpa_map[0] = 0;
} else {
if (vport->cfg_log_verbose & LOG_LINK_EVENT) {
int numalpa, j, k;
union {
uint8_t pamap[16];
struct {
uint32_t wd1;
uint32_t wd2;
uint32_t wd3;
uint32_t wd4;
} pa;
} un;
numalpa = phba->alpa_map[0];
j = 0;
while (j < numalpa) {
memset(un.pamap, 0, 16);
for (k = 1; j < numalpa; k++) {
un.pamap[k - 1] =
phba->alpa_map[j + 1];
j++;
if (k == 16)
break;
}
/* Link Up Event ALPA map */
lpfc_printf_log(phba,
KERN_WARNING,
LOG_LINK_EVENT,
"1304 Link Up Event "
"ALPA map Data: x%x "
"x%x x%x x%x\n",
un.pa.wd1, un.pa.wd2,
un.pa.wd3, un.pa.wd4);
}
}
}
} else {
if (!(phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)) {
if (phba->max_vpi && phba->cfg_enable_npiv &&
(phba->sli_rev == 3))
phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
}
vport->fc_myDID = phba->fc_pref_DID;
vport->fc_flag |= FC_LBIT;
}
spin_unlock_irq(&phba->hbalock);
lpfc_linkup(phba);
if (sparam_mbox) {
lpfc_read_sparam(phba, sparam_mbox, 0);
sparam_mbox->vport = vport;
sparam_mbox->mbox_cmpl = lpfc_mbx_cmpl_read_sparam;
rc = lpfc_sli_issue_mbox(phba, sparam_mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
mp = (struct lpfc_dmabuf *) sparam_mbox->context1;
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(sparam_mbox, phba->mbox_mem_pool);
goto out;
}
}
if (!(phba->hba_flag & HBA_FCOE_SUPPORT)) {
cfglink_mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!cfglink_mbox)
goto out;
vport->port_state = LPFC_LOCAL_CFG_LINK;
lpfc_config_link(phba, cfglink_mbox);
cfglink_mbox->vport = vport;
cfglink_mbox->mbox_cmpl = lpfc_mbx_cmpl_local_config_link;
rc = lpfc_sli_issue_mbox(phba, cfglink_mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
mempool_free(cfglink_mbox, phba->mbox_mem_pool);
goto out;
}
} else {
vport->port_state = LPFC_VPORT_UNKNOWN;
/*
* Add the driver's default FCF record at FCF index 0 now. This
* is phase 1 implementation that support FCF index 0 and driver
* defaults.
*/
if (phba->cfg_enable_fip == 0) {
fcf_record = kzalloc(sizeof(struct fcf_record),
GFP_KERNEL);
if (unlikely(!fcf_record)) {
lpfc_printf_log(phba, KERN_ERR,
LOG_MBOX | LOG_SLI,
"2554 Could not allocate memmory for "
"fcf record\n");
rc = -ENODEV;
goto out;
}
lpfc_sli4_build_dflt_fcf_record(phba, fcf_record,
LPFC_FCOE_FCF_DEF_INDEX);
rc = lpfc_sli4_add_fcf_record(phba, fcf_record);
if (unlikely(rc)) {
lpfc_printf_log(phba, KERN_ERR,
LOG_MBOX | LOG_SLI,
"2013 Could not manually add FCF "
"record 0, status %d\n", rc);
rc = -ENODEV;
kfree(fcf_record);
goto out;
}
kfree(fcf_record);
}
/*
* The driver is expected to do FIP/FCF. Call the port
* and get the FCF Table.
*/
spin_lock_irq(&phba->hbalock);
if (phba->hba_flag & FCF_DISC_INPROGRESS) {
spin_unlock_irq(&phba->hbalock);
return;
}
spin_unlock_irq(&phba->hbalock);
rc = lpfc_sli4_read_fcf_record(phba,
LPFC_FCOE_FCF_GET_FIRST);
if (rc)
goto out;
}
return;
out:
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX,
"0263 Discovery Mailbox error: state: 0x%x : %p %p\n",
vport->port_state, sparam_mbox, cfglink_mbox);
lpfc_issue_clear_la(phba, vport);
return;
}
static void
lpfc_enable_la(struct lpfc_hba *phba)
{
uint32_t control;
struct lpfc_sli *psli = &phba->sli;
spin_lock_irq(&phba->hbalock);
psli->sli_flag |= LPFC_PROCESS_LA;
if (phba->sli_rev <= LPFC_SLI_REV3) {
control = readl(phba->HCregaddr);
control |= HC_LAINT_ENA;
writel(control, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
}
spin_unlock_irq(&phba->hbalock);
}
static void
lpfc_mbx_issue_link_down(struct lpfc_hba *phba)
{
lpfc_linkdown(phba);
lpfc_enable_la(phba);
lpfc_unregister_unused_fcf(phba);
/* turn on Link Attention interrupts - no CLEAR_LA needed */
}
/*
* This routine handles processing a READ_LA mailbox
* command upon completion. It is setup in the LPFC_MBOXQ
* as the completion routine when the command is
* handed off to the SLI layer.
*/
void
lpfc_mbx_cmpl_read_la(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
struct lpfc_vport *vport = pmb->vport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
READ_LA_VAR *la;
MAILBOX_t *mb = &pmb->u.mb;
struct lpfc_dmabuf *mp = (struct lpfc_dmabuf *) (pmb->context1);
/* Unblock ELS traffic */
phba->sli.ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
/* Check for error */
if (mb->mbxStatus) {
lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
"1307 READ_LA mbox error x%x state x%x\n",
mb->mbxStatus, vport->port_state);
lpfc_mbx_issue_link_down(phba);
phba->link_state = LPFC_HBA_ERROR;
goto lpfc_mbx_cmpl_read_la_free_mbuf;
}
la = (READ_LA_VAR *) &pmb->u.mb.un.varReadLA;
memcpy(&phba->alpa_map[0], mp->virt, 128);
spin_lock_irq(shost->host_lock);
if (la->pb)
vport->fc_flag |= FC_BYPASSED_MODE;
else
vport->fc_flag &= ~FC_BYPASSED_MODE;
spin_unlock_irq(shost->host_lock);
if ((phba->fc_eventTag < la->eventTag) ||
(phba->fc_eventTag == la->eventTag)) {
phba->fc_stat.LinkMultiEvent++;
if (la->attType == AT_LINK_UP)
if (phba->fc_eventTag != 0)
lpfc_linkdown(phba);
}
phba->fc_eventTag = la->eventTag;
if (la->mm)
phba->sli.sli_flag |= LPFC_MENLO_MAINT;
else
phba->sli.sli_flag &= ~LPFC_MENLO_MAINT;
if (la->attType == AT_LINK_UP && (!la->mm)) {
phba->fc_stat.LinkUp++;
if (phba->link_flag & LS_LOOPBACK_MODE) {
lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
"1306 Link Up Event in loop back mode "
"x%x received Data: x%x x%x x%x x%x\n",
la->eventTag, phba->fc_eventTag,
la->granted_AL_PA, la->UlnkSpeed,
phba->alpa_map[0]);
} else {
lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
"1303 Link Up Event x%x received "
"Data: x%x x%x x%x x%x x%x x%x %d\n",
la->eventTag, phba->fc_eventTag,
la->granted_AL_PA, la->UlnkSpeed,
phba->alpa_map[0],
la->mm, la->fa,
phba->wait_4_mlo_maint_flg);
}
lpfc_mbx_process_link_up(phba, la);
} else if (la->attType == AT_LINK_DOWN) {
phba->fc_stat.LinkDown++;
if (phba->link_flag & LS_LOOPBACK_MODE) {
lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
"1308 Link Down Event in loop back mode "
"x%x received "
"Data: x%x x%x x%x\n",
la->eventTag, phba->fc_eventTag,
phba->pport->port_state, vport->fc_flag);
}
else {
lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
"1305 Link Down Event x%x received "
"Data: x%x x%x x%x x%x x%x\n",
la->eventTag, phba->fc_eventTag,
phba->pport->port_state, vport->fc_flag,
la->mm, la->fa);
}
lpfc_mbx_issue_link_down(phba);
}
if (la->mm && la->attType == AT_LINK_UP) {
if (phba->link_state != LPFC_LINK_DOWN) {
phba->fc_stat.LinkDown++;
lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
"1312 Link Down Event x%x received "
"Data: x%x x%x x%x\n",
la->eventTag, phba->fc_eventTag,
phba->pport->port_state, vport->fc_flag);
lpfc_mbx_issue_link_down(phba);
} else
lpfc_enable_la(phba);
lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
"1310 Menlo Maint Mode Link up Event x%x rcvd "
"Data: x%x x%x x%x\n",
la->eventTag, phba->fc_eventTag,
phba->pport->port_state, vport->fc_flag);
/*
* The cmnd that triggered this will be waiting for this
* signal.
*/
/* WAKEUP for MENLO_SET_MODE or MENLO_RESET command. */
if (phba->wait_4_mlo_maint_flg) {
phba->wait_4_mlo_maint_flg = 0;
wake_up_interruptible(&phba->wait_4_mlo_m_q);
}
}
if (la->fa) {
if (la->mm)
lpfc_issue_clear_la(phba, vport);
lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
"1311 fa %d\n", la->fa);
}
lpfc_mbx_cmpl_read_la_free_mbuf:
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
return;
}
/*
* This routine handles processing a REG_LOGIN mailbox
* command upon completion. It is setup in the LPFC_MBOXQ
* as the completion routine when the command is
* handed off to the SLI layer.
*/
void
lpfc_mbx_cmpl_reg_login(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
struct lpfc_vport *vport = pmb->vport;
struct lpfc_dmabuf *mp = (struct lpfc_dmabuf *) (pmb->context1);
struct lpfc_nodelist *ndlp = (struct lpfc_nodelist *) pmb->context2;
pmb->context1 = NULL;
/* Good status, call state machine */
lpfc_disc_state_machine(vport, ndlp, pmb, NLP_EVT_CMPL_REG_LOGIN);
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
/* decrement the node reference count held for this callback
* function.
*/
lpfc_nlp_put(ndlp);
return;
}
static void
lpfc_mbx_cmpl_unreg_vpi(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
MAILBOX_t *mb = &pmb->u.mb;
struct lpfc_vport *vport = pmb->vport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
switch (mb->mbxStatus) {
case 0x0011:
case 0x0020:
case 0x9700:
lpfc_printf_vlog(vport, KERN_INFO, LOG_NODE,
"0911 cmpl_unreg_vpi, mb status = 0x%x\n",
mb->mbxStatus);
break;
}
vport->unreg_vpi_cmpl = VPORT_OK;
mempool_free(pmb, phba->mbox_mem_pool);
/*
* This shost reference might have been taken at the beginning of
* lpfc_vport_delete()
*/
if (vport->load_flag & FC_UNLOADING)
scsi_host_put(shost);
}
int
lpfc_mbx_unreg_vpi(struct lpfc_vport *vport)
{
struct lpfc_hba *phba = vport->phba;
LPFC_MBOXQ_t *mbox;
int rc;
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!mbox)
return 1;
lpfc_unreg_vpi(phba, vport->vpi, mbox);
mbox->vport = vport;
mbox->mbox_cmpl = lpfc_mbx_cmpl_unreg_vpi;
rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX | LOG_VPORT,
"1800 Could not issue unreg_vpi\n");
mempool_free(mbox, phba->mbox_mem_pool);
vport->unreg_vpi_cmpl = VPORT_ERROR;
return rc;
}
return 0;
}
static void
lpfc_mbx_cmpl_reg_vpi(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
struct lpfc_vport *vport = pmb->vport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
MAILBOX_t *mb = &pmb->u.mb;
switch (mb->mbxStatus) {
case 0x0011:
case 0x9601:
case 0x9602:
lpfc_printf_vlog(vport, KERN_INFO, LOG_NODE,
"0912 cmpl_reg_vpi, mb status = 0x%x\n",
mb->mbxStatus);
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~(FC_FABRIC | FC_PUBLIC_LOOP);
spin_unlock_irq(shost->host_lock);
vport->fc_myDID = 0;
goto out;
}
vport->num_disc_nodes = 0;
/* go thru NPR list and issue ELS PLOGIs */
if (vport->fc_npr_cnt)
lpfc_els_disc_plogi(vport);
if (!vport->num_disc_nodes) {
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~FC_NDISC_ACTIVE;
spin_unlock_irq(shost->host_lock);
lpfc_can_disctmo(vport);
}
vport->port_state = LPFC_VPORT_READY;
out:
mempool_free(pmb, phba->mbox_mem_pool);
return;
}
/**
* lpfc_create_static_vport - Read HBA config region to create static vports.
* @phba: pointer to lpfc hba data structure.
*
* This routine issue a DUMP mailbox command for config region 22 to get
* the list of static vports to be created. The function create vports
* based on the information returned from the HBA.
**/
void
lpfc_create_static_vport(struct lpfc_hba *phba)
{
LPFC_MBOXQ_t *pmb = NULL;
MAILBOX_t *mb;
struct static_vport_info *vport_info;
int rc = 0, i;
struct fc_vport_identifiers vport_id;
struct fc_vport *new_fc_vport;
struct Scsi_Host *shost;
struct lpfc_vport *vport;
uint16_t offset = 0;
uint8_t *vport_buff;
struct lpfc_dmabuf *mp;
uint32_t byte_count = 0;
pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmb) {
lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
"0542 lpfc_create_static_vport failed to"
" allocate mailbox memory\n");
return;
}
mb = &pmb->u.mb;
vport_info = kzalloc(sizeof(struct static_vport_info), GFP_KERNEL);
if (!vport_info) {
lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
"0543 lpfc_create_static_vport failed to"
" allocate vport_info\n");
mempool_free(pmb, phba->mbox_mem_pool);
return;
}
vport_buff = (uint8_t *) vport_info;
do {
if (lpfc_dump_static_vport(phba, pmb, offset))
goto out;
pmb->vport = phba->pport;
rc = lpfc_sli_issue_mbox_wait(phba, pmb, LPFC_MBOX_TMO);
if ((rc != MBX_SUCCESS) || mb->mbxStatus) {
lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
"0544 lpfc_create_static_vport failed to"
" issue dump mailbox command ret 0x%x "
"status 0x%x\n",
rc, mb->mbxStatus);
goto out;
}
if (phba->sli_rev == LPFC_SLI_REV4) {
byte_count = pmb->u.mqe.un.mb_words[5];
mp = (struct lpfc_dmabuf *) pmb->context2;
if (byte_count > sizeof(struct static_vport_info) -
offset)
byte_count = sizeof(struct static_vport_info)
- offset;
memcpy(vport_buff + offset, mp->virt, byte_count);
offset += byte_count;
} else {
if (mb->un.varDmp.word_cnt >
sizeof(struct static_vport_info) - offset)
mb->un.varDmp.word_cnt =
sizeof(struct static_vport_info)
- offset;
byte_count = mb->un.varDmp.word_cnt;
lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
vport_buff + offset,
byte_count);
offset += byte_count;
}
} while (byte_count &&
offset < sizeof(struct static_vport_info));
if ((le32_to_cpu(vport_info->signature) != VPORT_INFO_SIG) ||
((le32_to_cpu(vport_info->rev) & VPORT_INFO_REV_MASK)
!= VPORT_INFO_REV)) {
lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
"0545 lpfc_create_static_vport bad"
" information header 0x%x 0x%x\n",
le32_to_cpu(vport_info->signature),
le32_to_cpu(vport_info->rev) & VPORT_INFO_REV_MASK);
goto out;
}
shost = lpfc_shost_from_vport(phba->pport);
for (i = 0; i < MAX_STATIC_VPORT_COUNT; i++) {
memset(&vport_id, 0, sizeof(vport_id));
vport_id.port_name = wwn_to_u64(vport_info->vport_list[i].wwpn);
vport_id.node_name = wwn_to_u64(vport_info->vport_list[i].wwnn);
if (!vport_id.port_name || !vport_id.node_name)
continue;
vport_id.roles = FC_PORT_ROLE_FCP_INITIATOR;
vport_id.vport_type = FC_PORTTYPE_NPIV;
vport_id.disable = false;
new_fc_vport = fc_vport_create(shost, 0, &vport_id);
if (!new_fc_vport) {
lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
"0546 lpfc_create_static_vport failed to"
" create vport\n");
continue;
}
vport = *(struct lpfc_vport **)new_fc_vport->dd_data;
vport->vport_flag |= STATIC_VPORT;
}
out:
kfree(vport_info);
if (rc != MBX_TIMEOUT) {
if (pmb->context2) {
mp = (struct lpfc_dmabuf *) pmb->context2;
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
}
mempool_free(pmb, phba->mbox_mem_pool);
}
return;
}
/*
* This routine handles processing a Fabric REG_LOGIN mailbox
* command upon completion. It is setup in the LPFC_MBOXQ
* as the completion routine when the command is
* handed off to the SLI layer.
*/
void
lpfc_mbx_cmpl_fabric_reg_login(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
struct lpfc_vport *vport = pmb->vport;
MAILBOX_t *mb = &pmb->u.mb;
struct lpfc_dmabuf *mp = (struct lpfc_dmabuf *) (pmb->context1);
struct lpfc_nodelist *ndlp;
ndlp = (struct lpfc_nodelist *) pmb->context2;
pmb->context1 = NULL;
pmb->context2 = NULL;
if (mb->mbxStatus) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX,
"0258 Register Fabric login error: 0x%x\n",
mb->mbxStatus);
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
if (phba->fc_topology == TOPOLOGY_LOOP) {
/* FLOGI failed, use loop map to make discovery list */
lpfc_disc_list_loopmap(vport);
/* Start discovery */
lpfc_disc_start(vport);
/* Decrement the reference count to ndlp after the
* reference to the ndlp are done.
*/
lpfc_nlp_put(ndlp);
return;
}
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
/* Decrement the reference count to ndlp after the reference
* to the ndlp are done.
*/
lpfc_nlp_put(ndlp);
return;
}
ndlp->nlp_rpi = mb->un.varWords[0];
ndlp->nlp_flag |= NLP_RPI_VALID;
ndlp->nlp_type |= NLP_FABRIC;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNMAPPED_NODE);
if (vport->port_state == LPFC_FABRIC_CFG_LINK) {
lpfc_start_fdiscs(phba);
lpfc_do_scr_ns_plogi(phba, vport);
}
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
/* Drop the reference count from the mbox at the end after
* all the current reference to the ndlp have been done.
*/
lpfc_nlp_put(ndlp);
return;
}
/*
* This routine handles processing a NameServer REG_LOGIN mailbox
* command upon completion. It is setup in the LPFC_MBOXQ
* as the completion routine when the command is
* handed off to the SLI layer.
*/
void
lpfc_mbx_cmpl_ns_reg_login(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
MAILBOX_t *mb = &pmb->u.mb;
struct lpfc_dmabuf *mp = (struct lpfc_dmabuf *) (pmb->context1);
struct lpfc_nodelist *ndlp = (struct lpfc_nodelist *) pmb->context2;
struct lpfc_vport *vport = pmb->vport;
if (mb->mbxStatus) {
out:
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0260 Register NameServer error: 0x%x\n",
mb->mbxStatus);
/* decrement the node reference count held for this
* callback function.
*/
lpfc_nlp_put(ndlp);
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
/* If no other thread is using the ndlp, free it */
lpfc_nlp_not_used(ndlp);
if (phba->fc_topology == TOPOLOGY_LOOP) {
/*
* RegLogin failed, use loop map to make discovery
* list
*/
lpfc_disc_list_loopmap(vport);
/* Start discovery */
lpfc_disc_start(vport);
return;
}
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
return;
}
pmb->context1 = NULL;
ndlp->nlp_rpi = mb->un.varWords[0];
ndlp->nlp_flag |= NLP_RPI_VALID;
ndlp->nlp_type |= NLP_FABRIC;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNMAPPED_NODE);
if (vport->port_state < LPFC_VPORT_READY) {
/* Link up discovery requires Fabric registration. */
lpfc_ns_cmd(vport, SLI_CTNS_RFF_ID, 0, 0); /* Do this first! */
lpfc_ns_cmd(vport, SLI_CTNS_RNN_ID, 0, 0);
lpfc_ns_cmd(vport, SLI_CTNS_RSNN_NN, 0, 0);
lpfc_ns_cmd(vport, SLI_CTNS_RSPN_ID, 0, 0);
lpfc_ns_cmd(vport, SLI_CTNS_RFT_ID, 0, 0);
/* Issue SCR just before NameServer GID_FT Query */
lpfc_issue_els_scr(vport, SCR_DID, 0);
}
vport->fc_ns_retry = 0;
/* Good status, issue CT Request to NameServer */
if (lpfc_ns_cmd(vport, SLI_CTNS_GID_FT, 0, 0)) {
/* Cannot issue NameServer Query, so finish up discovery */
goto out;
}
/* decrement the node reference count held for this
* callback function.
*/
lpfc_nlp_put(ndlp);
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
return;
}
static void
lpfc_register_remote_port(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct fc_rport *rport;
struct lpfc_rport_data *rdata;
struct fc_rport_identifiers rport_ids;
struct lpfc_hba *phba = vport->phba;
/* Remote port has reappeared. Re-register w/ FC transport */
rport_ids.node_name = wwn_to_u64(ndlp->nlp_nodename.u.wwn);
rport_ids.port_name = wwn_to_u64(ndlp->nlp_portname.u.wwn);
rport_ids.port_id = ndlp->nlp_DID;
rport_ids.roles = FC_RPORT_ROLE_UNKNOWN;
/*
* We leave our node pointer in rport->dd_data when we unregister a
* FCP target port. But fc_remote_port_add zeros the space to which
* rport->dd_data points. So, if we're reusing a previously
* registered port, drop the reference that we took the last time we
* registered the port.
*/
if (ndlp->rport && ndlp->rport->dd_data &&
((struct lpfc_rport_data *) ndlp->rport->dd_data)->pnode == ndlp)
lpfc_nlp_put(ndlp);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_RPORT,
"rport add: did:x%x flg:x%x type x%x",
ndlp->nlp_DID, ndlp->nlp_flag, ndlp->nlp_type);
ndlp->rport = rport = fc_remote_port_add(shost, 0, &rport_ids);
if (!rport || !get_device(&rport->dev)) {
dev_printk(KERN_WARNING, &phba->pcidev->dev,
"Warning: fc_remote_port_add failed\n");
return;
}
/* initialize static port data */
rport->maxframe_size = ndlp->nlp_maxframe;
rport->supported_classes = ndlp->nlp_class_sup;
rdata = rport->dd_data;
rdata->pnode = lpfc_nlp_get(ndlp);
if (ndlp->nlp_type & NLP_FCP_TARGET)
rport_ids.roles |= FC_RPORT_ROLE_FCP_TARGET;
if (ndlp->nlp_type & NLP_FCP_INITIATOR)
rport_ids.roles |= FC_RPORT_ROLE_FCP_INITIATOR;
if (rport_ids.roles != FC_RPORT_ROLE_UNKNOWN)
fc_remote_port_rolechg(rport, rport_ids.roles);
if ((rport->scsi_target_id != -1) &&
(rport->scsi_target_id < LPFC_MAX_TARGET)) {
ndlp->nlp_sid = rport->scsi_target_id;
}
return;
}
static void
lpfc_unregister_remote_port(struct lpfc_nodelist *ndlp)
{
struct fc_rport *rport = ndlp->rport;
lpfc_debugfs_disc_trc(ndlp->vport, LPFC_DISC_TRC_RPORT,
"rport delete: did:x%x flg:x%x type x%x",
ndlp->nlp_DID, ndlp->nlp_flag, ndlp->nlp_type);
fc_remote_port_delete(rport);
return;
}
static void
lpfc_nlp_counters(struct lpfc_vport *vport, int state, int count)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
spin_lock_irq(shost->host_lock);
switch (state) {
case NLP_STE_UNUSED_NODE:
vport->fc_unused_cnt += count;
break;
case NLP_STE_PLOGI_ISSUE:
vport->fc_plogi_cnt += count;
break;
case NLP_STE_ADISC_ISSUE:
vport->fc_adisc_cnt += count;
break;
case NLP_STE_REG_LOGIN_ISSUE:
vport->fc_reglogin_cnt += count;
break;
case NLP_STE_PRLI_ISSUE:
vport->fc_prli_cnt += count;
break;
case NLP_STE_UNMAPPED_NODE:
vport->fc_unmap_cnt += count;
break;
case NLP_STE_MAPPED_NODE:
vport->fc_map_cnt += count;
break;
case NLP_STE_NPR_NODE:
vport->fc_npr_cnt += count;
break;
}
spin_unlock_irq(shost->host_lock);
}
static void
lpfc_nlp_state_cleanup(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
int old_state, int new_state)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (new_state == NLP_STE_UNMAPPED_NODE) {
ndlp->nlp_type &= ~(NLP_FCP_TARGET | NLP_FCP_INITIATOR);
ndlp->nlp_flag &= ~NLP_NODEV_REMOVE;
ndlp->nlp_type |= NLP_FC_NODE;
}
if (new_state == NLP_STE_MAPPED_NODE)
ndlp->nlp_flag &= ~NLP_NODEV_REMOVE;
if (new_state == NLP_STE_NPR_NODE)
ndlp->nlp_flag &= ~NLP_RCV_PLOGI;
/* Transport interface */
if (ndlp->rport && (old_state == NLP_STE_MAPPED_NODE ||
old_state == NLP_STE_UNMAPPED_NODE)) {
vport->phba->nport_event_cnt++;
lpfc_unregister_remote_port(ndlp);
}
if (new_state == NLP_STE_MAPPED_NODE ||
new_state == NLP_STE_UNMAPPED_NODE) {
vport->phba->nport_event_cnt++;
/*
* Tell the fc transport about the port, if we haven't
* already. If we have, and it's a scsi entity, be
* sure to unblock any attached scsi devices
*/
lpfc_register_remote_port(vport, ndlp);
}
if ((new_state == NLP_STE_MAPPED_NODE) &&
(vport->stat_data_enabled)) {
/*
* A new target is discovered, if there is no buffer for
* statistical data collection allocate buffer.
*/
ndlp->lat_data = kcalloc(LPFC_MAX_BUCKET_COUNT,
sizeof(struct lpfc_scsicmd_bkt),
GFP_KERNEL);
if (!ndlp->lat_data)
lpfc_printf_vlog(vport, KERN_ERR, LOG_NODE,
"0286 lpfc_nlp_state_cleanup failed to "
"allocate statistical data buffer DID "
"0x%x\n", ndlp->nlp_DID);
}
/*
* if we added to Mapped list, but the remote port
* registration failed or assigned a target id outside
* our presentable range - move the node to the
* Unmapped List
*/
if (new_state == NLP_STE_MAPPED_NODE &&
(!ndlp->rport ||
ndlp->rport->scsi_target_id == -1 ||
ndlp->rport->scsi_target_id >= LPFC_MAX_TARGET)) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_TGT_NO_SCSIID;
spin_unlock_irq(shost->host_lock);
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNMAPPED_NODE);
}
}
static char *
lpfc_nlp_state_name(char *buffer, size_t size, int state)
{
static char *states[] = {
[NLP_STE_UNUSED_NODE] = "UNUSED",
[NLP_STE_PLOGI_ISSUE] = "PLOGI",
[NLP_STE_ADISC_ISSUE] = "ADISC",
[NLP_STE_REG_LOGIN_ISSUE] = "REGLOGIN",
[NLP_STE_PRLI_ISSUE] = "PRLI",
[NLP_STE_UNMAPPED_NODE] = "UNMAPPED",
[NLP_STE_MAPPED_NODE] = "MAPPED",
[NLP_STE_NPR_NODE] = "NPR",
};
if (state < NLP_STE_MAX_STATE && states[state])
strlcpy(buffer, states[state], size);
else
snprintf(buffer, size, "unknown (%d)", state);
return buffer;
}
void
lpfc_nlp_set_state(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
int state)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
int old_state = ndlp->nlp_state;
char name1[16], name2[16];
lpfc_printf_vlog(vport, KERN_INFO, LOG_NODE,
"0904 NPort state transition x%06x, %s -> %s\n",
ndlp->nlp_DID,
lpfc_nlp_state_name(name1, sizeof(name1), old_state),
lpfc_nlp_state_name(name2, sizeof(name2), state));
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_NODE,
"node statechg did:x%x old:%d ste:%d",
ndlp->nlp_DID, old_state, state);
if (old_state == NLP_STE_NPR_NODE &&
state != NLP_STE_NPR_NODE)
lpfc_cancel_retry_delay_tmo(vport, ndlp);
if (old_state == NLP_STE_UNMAPPED_NODE) {
ndlp->nlp_flag &= ~NLP_TGT_NO_SCSIID;
ndlp->nlp_type &= ~NLP_FC_NODE;
}
if (list_empty(&ndlp->nlp_listp)) {
spin_lock_irq(shost->host_lock);
list_add_tail(&ndlp->nlp_listp, &vport->fc_nodes);
spin_unlock_irq(shost->host_lock);
} else if (old_state)
lpfc_nlp_counters(vport, old_state, -1);
ndlp->nlp_state = state;
lpfc_nlp_counters(vport, state, 1);
lpfc_nlp_state_cleanup(vport, ndlp, old_state, state);
}
void
lpfc_enqueue_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (list_empty(&ndlp->nlp_listp)) {
spin_lock_irq(shost->host_lock);
list_add_tail(&ndlp->nlp_listp, &vport->fc_nodes);
spin_unlock_irq(shost->host_lock);
}
}
void
lpfc_dequeue_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
lpfc_cancel_retry_delay_tmo(vport, ndlp);
if (ndlp->nlp_state && !list_empty(&ndlp->nlp_listp))
lpfc_nlp_counters(vport, ndlp->nlp_state, -1);
spin_lock_irq(shost->host_lock);
list_del_init(&ndlp->nlp_listp);
spin_unlock_irq(shost->host_lock);
lpfc_nlp_state_cleanup(vport, ndlp, ndlp->nlp_state,
NLP_STE_UNUSED_NODE);
}
static void
lpfc_disable_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
lpfc_cancel_retry_delay_tmo(vport, ndlp);
if (ndlp->nlp_state && !list_empty(&ndlp->nlp_listp))
lpfc_nlp_counters(vport, ndlp->nlp_state, -1);
lpfc_nlp_state_cleanup(vport, ndlp, ndlp->nlp_state,
NLP_STE_UNUSED_NODE);
}
/**
* lpfc_initialize_node - Initialize all fields of node object
* @vport: Pointer to Virtual Port object.
* @ndlp: Pointer to FC node object.
* @did: FC_ID of the node.
*
* This function is always called when node object need to be initialized.
* It initializes all the fields of the node object. Although the reference
* to phba from @ndlp can be obtained indirectly through it's reference to
* @vport, a direct reference to phba is taken here by @ndlp. This is due
* to the life-span of the @ndlp might go beyond the existence of @vport as
* the final release of ndlp is determined by its reference count. And, the
* operation on @ndlp needs the reference to phba.
**/
static inline void
lpfc_initialize_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
uint32_t did)
{
INIT_LIST_HEAD(&ndlp->els_retry_evt.evt_listp);
INIT_LIST_HEAD(&ndlp->dev_loss_evt.evt_listp);
init_timer(&ndlp->nlp_delayfunc);
ndlp->nlp_delayfunc.function = lpfc_els_retry_delay;
ndlp->nlp_delayfunc.data = (unsigned long)ndlp;
ndlp->nlp_DID = did;
ndlp->vport = vport;
ndlp->phba = vport->phba;
ndlp->nlp_sid = NLP_NO_SID;
kref_init(&ndlp->kref);
NLP_INT_NODE_ACT(ndlp);
atomic_set(&ndlp->cmd_pending, 0);
ndlp->cmd_qdepth = LPFC_MAX_TGT_QDEPTH;
}
struct lpfc_nodelist *
lpfc_enable_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
int state)
{
struct lpfc_hba *phba = vport->phba;
uint32_t did;
unsigned long flags;
if (!ndlp)
return NULL;
spin_lock_irqsave(&phba->ndlp_lock, flags);
/* The ndlp should not be in memory free mode */
if (NLP_CHK_FREE_REQ(ndlp)) {
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
lpfc_printf_vlog(vport, KERN_WARNING, LOG_NODE,
"0277 lpfc_enable_node: ndlp:x%p "
"usgmap:x%x refcnt:%d\n",
(void *)ndlp, ndlp->nlp_usg_map,
atomic_read(&ndlp->kref.refcount));
return NULL;
}
/* The ndlp should not already be in active mode */
if (NLP_CHK_NODE_ACT(ndlp)) {
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
lpfc_printf_vlog(vport, KERN_WARNING, LOG_NODE,
"0278 lpfc_enable_node: ndlp:x%p "
"usgmap:x%x refcnt:%d\n",
(void *)ndlp, ndlp->nlp_usg_map,
atomic_read(&ndlp->kref.refcount));
return NULL;
}
/* Keep the original DID */
did = ndlp->nlp_DID;
/* re-initialize ndlp except of ndlp linked list pointer */
memset((((char *)ndlp) + sizeof (struct list_head)), 0,
sizeof (struct lpfc_nodelist) - sizeof (struct list_head));
lpfc_initialize_node(vport, ndlp, did);
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
if (state != NLP_STE_UNUSED_NODE)
lpfc_nlp_set_state(vport, ndlp, state);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_NODE,
"node enable: did:x%x",
ndlp->nlp_DID, 0, 0);
return ndlp;
}
void
lpfc_drop_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
/*
* Use of lpfc_drop_node and UNUSED list: lpfc_drop_node should
* be used if we wish to issue the "last" lpfc_nlp_put() to remove
* the ndlp from the vport. The ndlp marked as UNUSED on the list
* until ALL other outstanding threads have completed. We check
* that the ndlp not already in the UNUSED state before we proceed.
*/
if (ndlp->nlp_state == NLP_STE_UNUSED_NODE)
return;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNUSED_NODE);
lpfc_nlp_put(ndlp);
return;
}
/*
* Start / ReStart rescue timer for Discovery / RSCN handling
*/
void
lpfc_set_disctmo(struct lpfc_vport *vport)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
uint32_t tmo;
if (vport->port_state == LPFC_LOCAL_CFG_LINK) {
/* For FAN, timeout should be greater than edtov */
tmo = (((phba->fc_edtov + 999) / 1000) + 1);
} else {
/* Normal discovery timeout should be > than ELS/CT timeout
* FC spec states we need 3 * ratov for CT requests
*/
tmo = ((phba->fc_ratov * 3) + 3);
}
if (!timer_pending(&vport->fc_disctmo)) {
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_ELS_CMD,
"set disc timer: tmo:x%x state:x%x flg:x%x",
tmo, vport->port_state, vport->fc_flag);
}
mod_timer(&vport->fc_disctmo, jiffies + HZ * tmo);
spin_lock_irq(shost->host_lock);
vport->fc_flag |= FC_DISC_TMO;
spin_unlock_irq(shost->host_lock);
/* Start Discovery Timer state <hba_state> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0247 Start Discovery Timer state x%x "
"Data: x%x x%lx x%x x%x\n",
vport->port_state, tmo,
(unsigned long)&vport->fc_disctmo, vport->fc_plogi_cnt,
vport->fc_adisc_cnt);
return;
}
/*
* Cancel rescue timer for Discovery / RSCN handling
*/
int
lpfc_can_disctmo(struct lpfc_vport *vport)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
unsigned long iflags;
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_ELS_CMD,
"can disc timer: state:x%x rtry:x%x flg:x%x",
vport->port_state, vport->fc_ns_retry, vport->fc_flag);
/* Turn off discovery timer if its running */
if (vport->fc_flag & FC_DISC_TMO) {
spin_lock_irqsave(shost->host_lock, iflags);
vport->fc_flag &= ~FC_DISC_TMO;
spin_unlock_irqrestore(shost->host_lock, iflags);
del_timer_sync(&vport->fc_disctmo);
spin_lock_irqsave(&vport->work_port_lock, iflags);
vport->work_port_events &= ~WORKER_DISC_TMO;
spin_unlock_irqrestore(&vport->work_port_lock, iflags);
}
/* Cancel Discovery Timer state <hba_state> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0248 Cancel Discovery Timer state x%x "
"Data: x%x x%x x%x\n",
vport->port_state, vport->fc_flag,
vport->fc_plogi_cnt, vport->fc_adisc_cnt);
return 0;
}
/*
* Check specified ring for outstanding IOCB on the SLI queue
* Return true if iocb matches the specified nport
*/
int
lpfc_check_sli_ndlp(struct lpfc_hba *phba,
struct lpfc_sli_ring *pring,
struct lpfc_iocbq *iocb,
struct lpfc_nodelist *ndlp)
{
struct lpfc_sli *psli = &phba->sli;
IOCB_t *icmd = &iocb->iocb;
struct lpfc_vport *vport = ndlp->vport;
if (iocb->vport != vport)
return 0;
if (pring->ringno == LPFC_ELS_RING) {
switch (icmd->ulpCommand) {
case CMD_GEN_REQUEST64_CR:
if (iocb->context_un.ndlp == ndlp)
return 1;
case CMD_ELS_REQUEST64_CR:
if (icmd->un.elsreq64.remoteID == ndlp->nlp_DID)
return 1;
case CMD_XMIT_ELS_RSP64_CX:
if (iocb->context1 == (uint8_t *) ndlp)
return 1;
}
} else if (pring->ringno == psli->extra_ring) {
} else if (pring->ringno == psli->fcp_ring) {
/* Skip match check if waiting to relogin to FCP target */
if ((ndlp->nlp_type & NLP_FCP_TARGET) &&
(ndlp->nlp_flag & NLP_DELAY_TMO)) {
return 0;
}
if (icmd->ulpContext == (volatile ushort)ndlp->nlp_rpi) {
return 1;
}
} else if (pring->ringno == psli->next_ring) {
}
return 0;
}
/*
* Free resources / clean up outstanding I/Os
* associated with nlp_rpi in the LPFC_NODELIST entry.
*/
static int
lpfc_no_rpi(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp)
{
LIST_HEAD(completions);
struct lpfc_sli *psli;
struct lpfc_sli_ring *pring;
struct lpfc_iocbq *iocb, *next_iocb;
uint32_t rpi, i;
lpfc_fabric_abort_nport(ndlp);
/*
* Everything that matches on txcmplq will be returned
* by firmware with a no rpi error.
*/
psli = &phba->sli;
rpi = ndlp->nlp_rpi;
if (ndlp->nlp_flag & NLP_RPI_VALID) {
/* Now process each ring */
for (i = 0; i < psli->num_rings; i++) {
pring = &psli->ring[i];
spin_lock_irq(&phba->hbalock);
list_for_each_entry_safe(iocb, next_iocb, &pring->txq,
list) {
/*
* Check to see if iocb matches the nport we are
* looking for
*/
if ((lpfc_check_sli_ndlp(phba, pring, iocb,
ndlp))) {
/* It matches, so deque and call compl
with an error */
list_move_tail(&iocb->list,
&completions);
pring->txq_cnt--;
}
}
spin_unlock_irq(&phba->hbalock);
}
}
/* Cancel all the IOCBs from the completions list */
lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
IOERR_SLI_ABORTED);
return 0;
}
/*
* Free rpi associated with LPFC_NODELIST entry.
* This routine is called from lpfc_freenode(), when we are removing
* a LPFC_NODELIST entry. It is also called if the driver initiates a
* LOGO that completes successfully, and we are waiting to PLOGI back
* to the remote NPort. In addition, it is called after we receive
* and unsolicated ELS cmd, send back a rsp, the rsp completes and
* we are waiting to PLOGI back to the remote NPort.
*/
int
lpfc_unreg_rpi(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
struct lpfc_hba *phba = vport->phba;
LPFC_MBOXQ_t *mbox;
int rc;
if (ndlp->nlp_flag & NLP_RPI_VALID) {
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (mbox) {
lpfc_unreg_login(phba, vport->vpi, ndlp->nlp_rpi, mbox);
mbox->vport = vport;
mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED)
mempool_free(mbox, phba->mbox_mem_pool);
}
lpfc_no_rpi(phba, ndlp);
ndlp->nlp_rpi = 0;
ndlp->nlp_flag &= ~NLP_RPI_VALID;
ndlp->nlp_flag &= ~NLP_NPR_ADISC;
return 1;
}
return 0;
}
void
lpfc_unreg_all_rpis(struct lpfc_vport *vport)
{
struct lpfc_hba *phba = vport->phba;
LPFC_MBOXQ_t *mbox;
int rc;
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (mbox) {
lpfc_unreg_login(phba, vport->vpi, 0xffff, mbox);
mbox->vport = vport;
mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
mbox->context1 = NULL;
rc = lpfc_sli_issue_mbox_wait(phba, mbox, LPFC_MBOX_TMO);
if (rc != MBX_TIMEOUT)
mempool_free(mbox, phba->mbox_mem_pool);
if ((rc == MBX_TIMEOUT) || (rc == MBX_NOT_FINISHED))
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX | LOG_VPORT,
"1836 Could not issue "
"unreg_login(all_rpis) status %d\n", rc);
}
}
void
lpfc_unreg_default_rpis(struct lpfc_vport *vport)
{
struct lpfc_hba *phba = vport->phba;
LPFC_MBOXQ_t *mbox;
int rc;
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (mbox) {
lpfc_unreg_did(phba, vport->vpi, 0xffffffff, mbox);
mbox->vport = vport;
mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
mbox->context1 = NULL;
rc = lpfc_sli_issue_mbox_wait(phba, mbox, LPFC_MBOX_TMO);
if (rc != MBX_TIMEOUT)
mempool_free(mbox, phba->mbox_mem_pool);
if ((rc == MBX_TIMEOUT) || (rc == MBX_NOT_FINISHED))
lpfc_printf_vlog(vport, KERN_ERR, LOG_MBOX | LOG_VPORT,
"1815 Could not issue "
"unreg_did (default rpis) status %d\n",
rc);
}
}
/*
* Free resources associated with LPFC_NODELIST entry
* so it can be freed.
*/
static int
lpfc_cleanup_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
LPFC_MBOXQ_t *mb, *nextmb;
struct lpfc_dmabuf *mp;
/* Cleanup node for NPort <nlp_DID> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_NODE,
"0900 Cleanup node for NPort x%x "
"Data: x%x x%x x%x\n",
ndlp->nlp_DID, ndlp->nlp_flag,
ndlp->nlp_state, ndlp->nlp_rpi);
if (NLP_CHK_FREE_REQ(ndlp)) {
lpfc_printf_vlog(vport, KERN_WARNING, LOG_NODE,
"0280 lpfc_cleanup_node: ndlp:x%p "
"usgmap:x%x refcnt:%d\n",
(void *)ndlp, ndlp->nlp_usg_map,
atomic_read(&ndlp->kref.refcount));
lpfc_dequeue_node(vport, ndlp);
} else {
lpfc_printf_vlog(vport, KERN_WARNING, LOG_NODE,
"0281 lpfc_cleanup_node: ndlp:x%p "
"usgmap:x%x refcnt:%d\n",
(void *)ndlp, ndlp->nlp_usg_map,
atomic_read(&ndlp->kref.refcount));
lpfc_disable_node(vport, ndlp);
}
/* cleanup any ndlp on mbox q waiting for reglogin cmpl */
if ((mb = phba->sli.mbox_active)) {
if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) &&
(ndlp == (struct lpfc_nodelist *) mb->context2)) {
mb->context2 = NULL;
mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
}
}
spin_lock_irq(&phba->hbalock);
list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) &&
(ndlp == (struct lpfc_nodelist *) mb->context2)) {
mp = (struct lpfc_dmabuf *) (mb->context1);
if (mp) {
__lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
}
list_del(&mb->list);
mempool_free(mb, phba->mbox_mem_pool);
/* We shall not invoke the lpfc_nlp_put to decrement
* the ndlp reference count as we are in the process
* of lpfc_nlp_release.
*/
}
}
spin_unlock_irq(&phba->hbalock);
lpfc_els_abort(phba, ndlp);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~NLP_DELAY_TMO;
spin_unlock_irq(shost->host_lock);
ndlp->nlp_last_elscmd = 0;
del_timer_sync(&ndlp->nlp_delayfunc);
list_del_init(&ndlp->els_retry_evt.evt_listp);
list_del_init(&ndlp->dev_loss_evt.evt_listp);
lpfc_unreg_rpi(vport, ndlp);
return 0;
}
/*
* Check to see if we can free the nlp back to the freelist.
* If we are in the middle of using the nlp in the discovery state
* machine, defer the free till we reach the end of the state machine.
*/
static void
lpfc_nlp_remove(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
struct lpfc_hba *phba = vport->phba;
struct lpfc_rport_data *rdata;
LPFC_MBOXQ_t *mbox;
int rc;
lpfc_cancel_retry_delay_tmo(vport, ndlp);
if ((ndlp->nlp_flag & NLP_DEFER_RM) &&
!(ndlp->nlp_flag & NLP_RPI_VALID)) {
/* For this case we need to cleanup the default rpi
* allocated by the firmware.
*/
if ((mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL))
!= NULL) {
rc = lpfc_reg_rpi(phba, vport->vpi, ndlp->nlp_DID,
(uint8_t *) &vport->fc_sparam, mbox, 0);
if (rc) {
mempool_free(mbox, phba->mbox_mem_pool);
}
else {
mbox->mbox_flag |= LPFC_MBX_IMED_UNREG;
mbox->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
mbox->vport = vport;
mbox->context2 = NULL;
rc =lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
mempool_free(mbox, phba->mbox_mem_pool);
}
}
}
}
lpfc_cleanup_node(vport, ndlp);
/*
* We can get here with a non-NULL ndlp->rport because when we
* unregister a rport we don't break the rport/node linkage. So if we
* do, make sure we don't leaving any dangling pointers behind.
*/
if (ndlp->rport) {
rdata = ndlp->rport->dd_data;
rdata->pnode = NULL;
ndlp->rport = NULL;
}
}
static int
lpfc_matchdid(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
uint32_t did)
{
D_ID mydid, ndlpdid, matchdid;
if (did == Bcast_DID)
return 0;
/* First check for Direct match */
if (ndlp->nlp_DID == did)
return 1;
/* Next check for area/domain identically equals 0 match */
mydid.un.word = vport->fc_myDID;
if ((mydid.un.b.domain == 0) && (mydid.un.b.area == 0)) {
return 0;
}
matchdid.un.word = did;
ndlpdid.un.word = ndlp->nlp_DID;
if (matchdid.un.b.id == ndlpdid.un.b.id) {
if ((mydid.un.b.domain == matchdid.un.b.domain) &&
(mydid.un.b.area == matchdid.un.b.area)) {
if ((ndlpdid.un.b.domain == 0) &&
(ndlpdid.un.b.area == 0)) {
if (ndlpdid.un.b.id)
return 1;
}
return 0;
}
matchdid.un.word = ndlp->nlp_DID;
if ((mydid.un.b.domain == ndlpdid.un.b.domain) &&
(mydid.un.b.area == ndlpdid.un.b.area)) {
if ((matchdid.un.b.domain == 0) &&
(matchdid.un.b.area == 0)) {
if (matchdid.un.b.id)
return 1;
}
}
}
return 0;
}
/* Search for a nodelist entry */
static struct lpfc_nodelist *
__lpfc_findnode_did(struct lpfc_vport *vport, uint32_t did)
{
struct lpfc_nodelist *ndlp;
uint32_t data1;
list_for_each_entry(ndlp, &vport->fc_nodes, nlp_listp) {
if (lpfc_matchdid(vport, ndlp, did)) {
data1 = (((uint32_t) ndlp->nlp_state << 24) |
((uint32_t) ndlp->nlp_xri << 16) |
((uint32_t) ndlp->nlp_type << 8) |
((uint32_t) ndlp->nlp_rpi & 0xff));
lpfc_printf_vlog(vport, KERN_INFO, LOG_NODE,
"0929 FIND node DID "
"Data: x%p x%x x%x x%x\n",
ndlp, ndlp->nlp_DID,
ndlp->nlp_flag, data1);
return ndlp;
}
}
/* FIND node did <did> NOT FOUND */
lpfc_printf_vlog(vport, KERN_INFO, LOG_NODE,
"0932 FIND node did x%x NOT FOUND.\n", did);
return NULL;
}
struct lpfc_nodelist *
lpfc_findnode_did(struct lpfc_vport *vport, uint32_t did)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_nodelist *ndlp;
spin_lock_irq(shost->host_lock);
ndlp = __lpfc_findnode_did(vport, did);
spin_unlock_irq(shost->host_lock);
return ndlp;
}
struct lpfc_nodelist *
lpfc_setup_disc_node(struct lpfc_vport *vport, uint32_t did)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_nodelist *ndlp;
ndlp = lpfc_findnode_did(vport, did);
if (!ndlp) {
if ((vport->fc_flag & FC_RSCN_MODE) != 0 &&
lpfc_rscn_payload_check(vport, did) == 0)
return NULL;
ndlp = (struct lpfc_nodelist *)
mempool_alloc(vport->phba->nlp_mem_pool, GFP_KERNEL);
if (!ndlp)
return NULL;
lpfc_nlp_init(vport, ndlp, did);
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NPR_2B_DISC;
spin_unlock_irq(shost->host_lock);
return ndlp;
} else if (!NLP_CHK_NODE_ACT(ndlp)) {
ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_NPR_NODE);
if (!ndlp)
return NULL;
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NPR_2B_DISC;
spin_unlock_irq(shost->host_lock);
return ndlp;
}
if ((vport->fc_flag & FC_RSCN_MODE) &&
!(vport->fc_flag & FC_NDISC_ACTIVE)) {
if (lpfc_rscn_payload_check(vport, did)) {
/* If we've already recieved a PLOGI from this NPort
* we don't need to try to discover it again.
*/
if (ndlp->nlp_flag & NLP_RCV_PLOGI)
return NULL;
/* Since this node is marked for discovery,
* delay timeout is not needed.
*/
lpfc_cancel_retry_delay_tmo(vport, ndlp);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NPR_2B_DISC;
spin_unlock_irq(shost->host_lock);
} else
ndlp = NULL;
} else {
/* If we've already recieved a PLOGI from this NPort,
* or we are already in the process of discovery on it,
* we don't need to try to discover it again.
*/
if (ndlp->nlp_state == NLP_STE_ADISC_ISSUE ||
ndlp->nlp_state == NLP_STE_PLOGI_ISSUE ||
ndlp->nlp_flag & NLP_RCV_PLOGI)
return NULL;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NPR_2B_DISC;
spin_unlock_irq(shost->host_lock);
}
return ndlp;
}
/* Build a list of nodes to discover based on the loopmap */
void
lpfc_disc_list_loopmap(struct lpfc_vport *vport)
{
struct lpfc_hba *phba = vport->phba;
int j;
uint32_t alpa, index;
if (!lpfc_is_link_up(phba))
return;
if (phba->fc_topology != TOPOLOGY_LOOP)
return;
/* Check for loop map present or not */
if (phba->alpa_map[0]) {
for (j = 1; j <= phba->alpa_map[0]; j++) {
alpa = phba->alpa_map[j];
if (((vport->fc_myDID & 0xff) == alpa) || (alpa == 0))
continue;
lpfc_setup_disc_node(vport, alpa);
}
} else {
/* No alpamap, so try all alpa's */
for (j = 0; j < FC_MAXLOOP; j++) {
/* If cfg_scan_down is set, start from highest
* ALPA (0xef) to lowest (0x1).
*/
if (vport->cfg_scan_down)
index = j;
else
index = FC_MAXLOOP - j - 1;
alpa = lpfcAlpaArray[index];
if ((vport->fc_myDID & 0xff) == alpa)
continue;
lpfc_setup_disc_node(vport, alpa);
}
}
return;
}
void
lpfc_issue_clear_la(struct lpfc_hba *phba, struct lpfc_vport *vport)
{
LPFC_MBOXQ_t *mbox;
struct lpfc_sli *psli = &phba->sli;
struct lpfc_sli_ring *extra_ring = &psli->ring[psli->extra_ring];
struct lpfc_sli_ring *fcp_ring = &psli->ring[psli->fcp_ring];
struct lpfc_sli_ring *next_ring = &psli->ring[psli->next_ring];
int rc;
/*
* if it's not a physical port or if we already send
* clear_la then don't send it.
*/
if ((phba->link_state >= LPFC_CLEAR_LA) ||
(vport->port_type != LPFC_PHYSICAL_PORT) ||
(phba->sli_rev == LPFC_SLI_REV4))
return;
/* Link up discovery */
if ((mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL)) != NULL) {
phba->link_state = LPFC_CLEAR_LA;
lpfc_clear_la(phba, mbox);
mbox->mbox_cmpl = lpfc_mbx_cmpl_clear_la;
mbox->vport = vport;
rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
mempool_free(mbox, phba->mbox_mem_pool);
lpfc_disc_flush_list(vport);
extra_ring->flag &= ~LPFC_STOP_IOCB_EVENT;
fcp_ring->flag &= ~LPFC_STOP_IOCB_EVENT;
next_ring->flag &= ~LPFC_STOP_IOCB_EVENT;
phba->link_state = LPFC_HBA_ERROR;
}
}
}
/* Reg_vpi to tell firmware to resume normal operations */
void
lpfc_issue_reg_vpi(struct lpfc_hba *phba, struct lpfc_vport *vport)
{
LPFC_MBOXQ_t *regvpimbox;
regvpimbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (regvpimbox) {
lpfc_reg_vpi(vport, regvpimbox);
regvpimbox->mbox_cmpl = lpfc_mbx_cmpl_reg_vpi;
regvpimbox->vport = vport;
if (lpfc_sli_issue_mbox(phba, regvpimbox, MBX_NOWAIT)
== MBX_NOT_FINISHED) {
mempool_free(regvpimbox, phba->mbox_mem_pool);
}
}
}
/* Start Link up / RSCN discovery on NPR nodes */
void
lpfc_disc_start(struct lpfc_vport *vport)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
uint32_t num_sent;
uint32_t clear_la_pending;
int did_changed;
if (!lpfc_is_link_up(phba))
return;
if (phba->link_state == LPFC_CLEAR_LA)
clear_la_pending = 1;
else
clear_la_pending = 0;
if (vport->port_state < LPFC_VPORT_READY)
vport->port_state = LPFC_DISC_AUTH;
lpfc_set_disctmo(vport);
if (vport->fc_prevDID == vport->fc_myDID)
did_changed = 0;
else
did_changed = 1;
vport->fc_prevDID = vport->fc_myDID;
vport->num_disc_nodes = 0;
/* Start Discovery state <hba_state> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0202 Start Discovery hba state x%x "
"Data: x%x x%x x%x\n",
vport->port_state, vport->fc_flag, vport->fc_plogi_cnt,
vport->fc_adisc_cnt);
/* First do ADISCs - if any */
num_sent = lpfc_els_disc_adisc(vport);
if (num_sent)
return;
/*
* For SLI3, cmpl_reg_vpi will set port_state to READY, and
* continue discovery.
*/
if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
!(vport->fc_flag & FC_PT2PT) &&
!(vport->fc_flag & FC_RSCN_MODE) &&
(phba->sli_rev < LPFC_SLI_REV4)) {
lpfc_issue_reg_vpi(phba, vport);
return;
}
/*
* For SLI2, we need to set port_state to READY and continue
* discovery.
*/
if (vport->port_state < LPFC_VPORT_READY && !clear_la_pending) {
/* If we get here, there is nothing to ADISC */
if (vport->port_type == LPFC_PHYSICAL_PORT)
lpfc_issue_clear_la(phba, vport);
if (!(vport->fc_flag & FC_ABORT_DISCOVERY)) {
vport->num_disc_nodes = 0;
/* go thru NPR nodes and issue ELS PLOGIs */
if (vport->fc_npr_cnt)
lpfc_els_disc_plogi(vport);
if (!vport->num_disc_nodes) {
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~FC_NDISC_ACTIVE;
spin_unlock_irq(shost->host_lock);
lpfc_can_disctmo(vport);
}
}
vport->port_state = LPFC_VPORT_READY;
} else {
/* Next do PLOGIs - if any */
num_sent = lpfc_els_disc_plogi(vport);
if (num_sent)
return;
if (vport->fc_flag & FC_RSCN_MODE) {
/* Check to see if more RSCNs came in while we
* were processing this one.
*/
if ((vport->fc_rscn_id_cnt == 0) &&
(!(vport->fc_flag & FC_RSCN_DISCOVERY))) {
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~FC_RSCN_MODE;
spin_unlock_irq(shost->host_lock);
lpfc_can_disctmo(vport);
} else
lpfc_els_handle_rscn(vport);
}
}
return;
}
/*
* Ignore completion for all IOCBs on tx and txcmpl queue for ELS
* ring the match the sppecified nodelist.
*/
static void
lpfc_free_tx(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp)
{
LIST_HEAD(completions);
struct lpfc_sli *psli;
IOCB_t *icmd;
struct lpfc_iocbq *iocb, *next_iocb;
struct lpfc_sli_ring *pring;
psli = &phba->sli;
pring = &psli->ring[LPFC_ELS_RING];
/* Error matching iocb on txq or txcmplq
* First check the txq.
*/
spin_lock_irq(&phba->hbalock);
list_for_each_entry_safe(iocb, next_iocb, &pring->txq, list) {
if (iocb->context1 != ndlp) {
continue;
}
icmd = &iocb->iocb;
if ((icmd->ulpCommand == CMD_ELS_REQUEST64_CR) ||
(icmd->ulpCommand == CMD_XMIT_ELS_RSP64_CX)) {
list_move_tail(&iocb->list, &completions);
pring->txq_cnt--;
}
}
/* Next check the txcmplq */
list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list) {
if (iocb->context1 != ndlp) {
continue;
}
icmd = &iocb->iocb;
if (icmd->ulpCommand == CMD_ELS_REQUEST64_CR ||
icmd->ulpCommand == CMD_XMIT_ELS_RSP64_CX) {
lpfc_sli_issue_abort_iotag(phba, pring, iocb);
}
}
spin_unlock_irq(&phba->hbalock);
/* Cancel all the IOCBs from the completions list */
lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
IOERR_SLI_ABORTED);
}
static void
lpfc_disc_flush_list(struct lpfc_vport *vport)
{
struct lpfc_nodelist *ndlp, *next_ndlp;
struct lpfc_hba *phba = vport->phba;
if (vport->fc_plogi_cnt || vport->fc_adisc_cnt) {
list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes,
nlp_listp) {
if (!NLP_CHK_NODE_ACT(ndlp))
continue;
if (ndlp->nlp_state == NLP_STE_PLOGI_ISSUE ||
ndlp->nlp_state == NLP_STE_ADISC_ISSUE) {
lpfc_free_tx(phba, ndlp);
}
}
}
}
void
lpfc_cleanup_discovery_resources(struct lpfc_vport *vport)
{
lpfc_els_flush_rscn(vport);
lpfc_els_flush_cmd(vport);
lpfc_disc_flush_list(vport);
}
/*****************************************************************************/
/*
* NAME: lpfc_disc_timeout
*
* FUNCTION: Fibre Channel driver discovery timeout routine.
*
* EXECUTION ENVIRONMENT: interrupt only
*
* CALLED FROM:
* Timer function
*
* RETURNS:
* none
*/
/*****************************************************************************/
void
lpfc_disc_timeout(unsigned long ptr)
{
struct lpfc_vport *vport = (struct lpfc_vport *) ptr;
struct lpfc_hba *phba = vport->phba;
uint32_t tmo_posted;
unsigned long flags = 0;
if (unlikely(!phba))
return;
spin_lock_irqsave(&vport->work_port_lock, flags);
tmo_posted = vport->work_port_events & WORKER_DISC_TMO;
if (!tmo_posted)
vport->work_port_events |= WORKER_DISC_TMO;
spin_unlock_irqrestore(&vport->work_port_lock, flags);
if (!tmo_posted)
lpfc_worker_wake_up(phba);
return;
}
static void
lpfc_disc_timeout_handler(struct lpfc_vport *vport)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
struct lpfc_sli *psli = &phba->sli;
struct lpfc_nodelist *ndlp, *next_ndlp;
LPFC_MBOXQ_t *initlinkmbox;
int rc, clrlaerr = 0;
if (!(vport->fc_flag & FC_DISC_TMO))
return;
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~FC_DISC_TMO;
spin_unlock_irq(shost->host_lock);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_ELS_CMD,
"disc timeout: state:x%x rtry:x%x flg:x%x",
vport->port_state, vport->fc_ns_retry, vport->fc_flag);
switch (vport->port_state) {
case LPFC_LOCAL_CFG_LINK:
/* port_state is identically LPFC_LOCAL_CFG_LINK while waiting for
* FAN
*/
/* FAN timeout */
lpfc_printf_vlog(vport, KERN_WARNING, LOG_DISCOVERY,
"0221 FAN timeout\n");
/* Start discovery by sending FLOGI, clean up old rpis */
list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes,
nlp_listp) {
if (!NLP_CHK_NODE_ACT(ndlp))
continue;
if (ndlp->nlp_state != NLP_STE_NPR_NODE)
continue;
if (ndlp->nlp_type & NLP_FABRIC) {
/* Clean up the ndlp on Fabric connections */
lpfc_drop_node(vport, ndlp);
} else if (!(ndlp->nlp_flag & NLP_NPR_ADISC)) {
/* Fail outstanding IO now since device
* is marked for PLOGI.
*/
lpfc_unreg_rpi(vport, ndlp);
}
}
if (vport->port_state != LPFC_FLOGI) {
lpfc_initial_flogi(vport);
return;
}
break;
case LPFC_FDISC:
case LPFC_FLOGI:
/* port_state is identically LPFC_FLOGI while waiting for FLOGI cmpl */
/* Initial FLOGI timeout */
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0222 Initial %s timeout\n",
vport->vpi ? "FDISC" : "FLOGI");
/* Assume no Fabric and go on with discovery.
* Check for outstanding ELS FLOGI to abort.
*/
/* FLOGI failed, so just use loop map to make discovery list */
lpfc_disc_list_loopmap(vport);
/* Start discovery */
lpfc_disc_start(vport);
break;
case LPFC_FABRIC_CFG_LINK:
/* hba_state is identically LPFC_FABRIC_CFG_LINK while waiting for
NameServer login */
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0223 Timeout while waiting for "
"NameServer login\n");
/* Next look for NameServer ndlp */
ndlp = lpfc_findnode_did(vport, NameServer_DID);
if (ndlp && NLP_CHK_NODE_ACT(ndlp))
lpfc_els_abort(phba, ndlp);
/* ReStart discovery */
goto restart_disc;
case LPFC_NS_QRY:
/* Check for wait for NameServer Rsp timeout */
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0224 NameServer Query timeout "
"Data: x%x x%x\n",
vport->fc_ns_retry, LPFC_MAX_NS_RETRY);
if (vport->fc_ns_retry < LPFC_MAX_NS_RETRY) {
/* Try it one more time */
vport->fc_ns_retry++;
rc = lpfc_ns_cmd(vport, SLI_CTNS_GID_FT,
vport->fc_ns_retry, 0);
if (rc == 0)
break;
}
vport->fc_ns_retry = 0;
restart_disc:
/*
* Discovery is over.
* set port_state to PORT_READY if SLI2.
* cmpl_reg_vpi will set port_state to READY for SLI3.
*/
if (phba->sli_rev < LPFC_SLI_REV4) {
if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
lpfc_issue_reg_vpi(phba, vport);
else { /* NPIV Not enabled */
lpfc_issue_clear_la(phba, vport);
vport->port_state = LPFC_VPORT_READY;
}
}
/* Setup and issue mailbox INITIALIZE LINK command */
initlinkmbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!initlinkmbox) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0206 Device Discovery "
"completion error\n");
phba->link_state = LPFC_HBA_ERROR;
break;
}
lpfc_linkdown(phba);
lpfc_init_link(phba, initlinkmbox, phba->cfg_topology,
phba->cfg_link_speed);
initlinkmbox->u.mb.un.varInitLnk.lipsr_AL_PA = 0;
initlinkmbox->vport = vport;
initlinkmbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
rc = lpfc_sli_issue_mbox(phba, initlinkmbox, MBX_NOWAIT);
lpfc_set_loopback_flag(phba);
if (rc == MBX_NOT_FINISHED)
mempool_free(initlinkmbox, phba->mbox_mem_pool);
break;
case LPFC_DISC_AUTH:
/* Node Authentication timeout */
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0227 Node Authentication timeout\n");
lpfc_disc_flush_list(vport);
/*
* set port_state to PORT_READY if SLI2.
* cmpl_reg_vpi will set port_state to READY for SLI3.
*/
if (phba->sli_rev < LPFC_SLI_REV4) {
if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
lpfc_issue_reg_vpi(phba, vport);
else { /* NPIV Not enabled */
lpfc_issue_clear_la(phba, vport);
vport->port_state = LPFC_VPORT_READY;
}
}
break;
case LPFC_VPORT_READY:
if (vport->fc_flag & FC_RSCN_MODE) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0231 RSCN timeout Data: x%x "
"x%x\n",
vport->fc_ns_retry, LPFC_MAX_NS_RETRY);
/* Cleanup any outstanding ELS commands */
lpfc_els_flush_cmd(vport);
lpfc_els_flush_rscn(vport);
lpfc_disc_flush_list(vport);
}
break;
default:
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0273 Unexpected discovery timeout, "
"vport State x%x\n", vport->port_state);
break;
}
switch (phba->link_state) {
case LPFC_CLEAR_LA:
/* CLEAR LA timeout */
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0228 CLEAR LA timeout\n");
clrlaerr = 1;
break;
case LPFC_LINK_UP:
lpfc_issue_clear_la(phba, vport);
/* Drop thru */
case LPFC_LINK_UNKNOWN:
case LPFC_WARM_START:
case LPFC_INIT_START:
case LPFC_INIT_MBX_CMDS:
case LPFC_LINK_DOWN:
case LPFC_HBA_ERROR:
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0230 Unexpected timeout, hba link "
"state x%x\n", phba->link_state);
clrlaerr = 1;
break;
case LPFC_HBA_READY:
break;
}
if (clrlaerr) {
lpfc_disc_flush_list(vport);
psli->ring[(psli->extra_ring)].flag &= ~LPFC_STOP_IOCB_EVENT;
psli->ring[(psli->fcp_ring)].flag &= ~LPFC_STOP_IOCB_EVENT;
psli->ring[(psli->next_ring)].flag &= ~LPFC_STOP_IOCB_EVENT;
vport->port_state = LPFC_VPORT_READY;
}
return;
}
/*
* This routine handles processing a NameServer REG_LOGIN mailbox
* command upon completion. It is setup in the LPFC_MBOXQ
* as the completion routine when the command is
* handed off to the SLI layer.
*/
void
lpfc_mbx_cmpl_fdmi_reg_login(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
{
MAILBOX_t *mb = &pmb->u.mb;
struct lpfc_dmabuf *mp = (struct lpfc_dmabuf *) (pmb->context1);
struct lpfc_nodelist *ndlp = (struct lpfc_nodelist *) pmb->context2;
struct lpfc_vport *vport = pmb->vport;
pmb->context1 = NULL;
ndlp->nlp_rpi = mb->un.varWords[0];
ndlp->nlp_flag |= NLP_RPI_VALID;
ndlp->nlp_type |= NLP_FABRIC;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNMAPPED_NODE);
/*
* Start issuing Fabric-Device Management Interface (FDMI) command to
* 0xfffffa (FDMI well known port) or Delay issuing FDMI command if
* fdmi-on=2 (supporting RPA/hostnmae)
*/
if (vport->cfg_fdmi_on == 1)
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_DHBA);
else
mod_timer(&vport->fc_fdmitmo, jiffies + HZ * 60);
/* decrement the node reference count held for this callback
* function.
*/
lpfc_nlp_put(ndlp);
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
return;
}
static int
lpfc_filter_by_rpi(struct lpfc_nodelist *ndlp, void *param)
{
uint16_t *rpi = param;
return ndlp->nlp_rpi == *rpi;
}
static int
lpfc_filter_by_wwpn(struct lpfc_nodelist *ndlp, void *param)
{
return memcmp(&ndlp->nlp_portname, param,
sizeof(ndlp->nlp_portname)) == 0;
}
static struct lpfc_nodelist *
__lpfc_find_node(struct lpfc_vport *vport, node_filter filter, void *param)
{
struct lpfc_nodelist *ndlp;
list_for_each_entry(ndlp, &vport->fc_nodes, nlp_listp) {
if (filter(ndlp, param))
return ndlp;
}
return NULL;
}
/*
* This routine looks up the ndlp lists for the given RPI. If rpi found it
* returns the node list element pointer else return NULL.
*/
struct lpfc_nodelist *
__lpfc_findnode_rpi(struct lpfc_vport *vport, uint16_t rpi)
{
return __lpfc_find_node(vport, lpfc_filter_by_rpi, &rpi);
}
/*
* This routine looks up the ndlp lists for the given WWPN. If WWPN found it
* returns the node element list pointer else return NULL.
*/
struct lpfc_nodelist *
lpfc_findnode_wwpn(struct lpfc_vport *vport, struct lpfc_name *wwpn)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_nodelist *ndlp;
spin_lock_irq(shost->host_lock);
ndlp = __lpfc_find_node(vport, lpfc_filter_by_wwpn, wwpn);
spin_unlock_irq(shost->host_lock);
return ndlp;
}
void
lpfc_nlp_init(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
uint32_t did)
{
memset(ndlp, 0, sizeof (struct lpfc_nodelist));
lpfc_initialize_node(vport, ndlp, did);
INIT_LIST_HEAD(&ndlp->nlp_listp);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_NODE,
"node init: did:x%x",
ndlp->nlp_DID, 0, 0);
return;
}
/* This routine releases all resources associated with a specifc NPort's ndlp
* and mempool_free's the nodelist.
*/
static void
lpfc_nlp_release(struct kref *kref)
{
struct lpfc_hba *phba;
unsigned long flags;
struct lpfc_nodelist *ndlp = container_of(kref, struct lpfc_nodelist,
kref);
lpfc_debugfs_disc_trc(ndlp->vport, LPFC_DISC_TRC_NODE,
"node release: did:x%x flg:x%x type:x%x",
ndlp->nlp_DID, ndlp->nlp_flag, ndlp->nlp_type);
lpfc_printf_vlog(ndlp->vport, KERN_INFO, LOG_NODE,
"0279 lpfc_nlp_release: ndlp:x%p "
"usgmap:x%x refcnt:%d\n",
(void *)ndlp, ndlp->nlp_usg_map,
atomic_read(&ndlp->kref.refcount));
/* remove ndlp from action. */
lpfc_nlp_remove(ndlp->vport, ndlp);
/* clear the ndlp active flag for all release cases */
phba = ndlp->phba;
spin_lock_irqsave(&phba->ndlp_lock, flags);
NLP_CLR_NODE_ACT(ndlp);
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
/* free ndlp memory for final ndlp release */
if (NLP_CHK_FREE_REQ(ndlp)) {
kfree(ndlp->lat_data);
mempool_free(ndlp, ndlp->phba->nlp_mem_pool);
}
}
/* This routine bumps the reference count for a ndlp structure to ensure
* that one discovery thread won't free a ndlp while another discovery thread
* is using it.
*/
struct lpfc_nodelist *
lpfc_nlp_get(struct lpfc_nodelist *ndlp)
{
struct lpfc_hba *phba;
unsigned long flags;
if (ndlp) {
lpfc_debugfs_disc_trc(ndlp->vport, LPFC_DISC_TRC_NODE,
"node get: did:x%x flg:x%x refcnt:x%x",
ndlp->nlp_DID, ndlp->nlp_flag,
atomic_read(&ndlp->kref.refcount));
/* The check of ndlp usage to prevent incrementing the
* ndlp reference count that is in the process of being
* released.
*/
phba = ndlp->phba;
spin_lock_irqsave(&phba->ndlp_lock, flags);
if (!NLP_CHK_NODE_ACT(ndlp) || NLP_CHK_FREE_ACK(ndlp)) {
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
lpfc_printf_vlog(ndlp->vport, KERN_WARNING, LOG_NODE,
"0276 lpfc_nlp_get: ndlp:x%p "
"usgmap:x%x refcnt:%d\n",
(void *)ndlp, ndlp->nlp_usg_map,
atomic_read(&ndlp->kref.refcount));
return NULL;
} else
kref_get(&ndlp->kref);
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
}
return ndlp;
}
/* This routine decrements the reference count for a ndlp structure. If the
* count goes to 0, this indicates the the associated nodelist should be
* freed. Returning 1 indicates the ndlp resource has been released; on the
* other hand, returning 0 indicates the ndlp resource has not been released
* yet.
*/
int
lpfc_nlp_put(struct lpfc_nodelist *ndlp)
{
struct lpfc_hba *phba;
unsigned long flags;
if (!ndlp)
return 1;
lpfc_debugfs_disc_trc(ndlp->vport, LPFC_DISC_TRC_NODE,
"node put: did:x%x flg:x%x refcnt:x%x",
ndlp->nlp_DID, ndlp->nlp_flag,
atomic_read(&ndlp->kref.refcount));
phba = ndlp->phba;
spin_lock_irqsave(&phba->ndlp_lock, flags);
/* Check the ndlp memory free acknowledge flag to avoid the
* possible race condition that kref_put got invoked again
* after previous one has done ndlp memory free.
*/
if (NLP_CHK_FREE_ACK(ndlp)) {
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
lpfc_printf_vlog(ndlp->vport, KERN_WARNING, LOG_NODE,
"0274 lpfc_nlp_put: ndlp:x%p "
"usgmap:x%x refcnt:%d\n",
(void *)ndlp, ndlp->nlp_usg_map,
atomic_read(&ndlp->kref.refcount));
return 1;
}
/* Check the ndlp inactivate log flag to avoid the possible
* race condition that kref_put got invoked again after ndlp
* is already in inactivating state.
*/
if (NLP_CHK_IACT_REQ(ndlp)) {
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
lpfc_printf_vlog(ndlp->vport, KERN_WARNING, LOG_NODE,
"0275 lpfc_nlp_put: ndlp:x%p "
"usgmap:x%x refcnt:%d\n",
(void *)ndlp, ndlp->nlp_usg_map,
atomic_read(&ndlp->kref.refcount));
return 1;
}
/* For last put, mark the ndlp usage flags to make sure no
* other kref_get and kref_put on the same ndlp shall get
* in between the process when the final kref_put has been
* invoked on this ndlp.
*/
if (atomic_read(&ndlp->kref.refcount) == 1) {
/* Indicate ndlp is put to inactive state. */
NLP_SET_IACT_REQ(ndlp);
/* Acknowledge ndlp memory free has been seen. */
if (NLP_CHK_FREE_REQ(ndlp))
NLP_SET_FREE_ACK(ndlp);
}
spin_unlock_irqrestore(&phba->ndlp_lock, flags);
/* Note, the kref_put returns 1 when decrementing a reference
* count that was 1, it invokes the release callback function,
* but it still left the reference count as 1 (not actually
* performs the last decrementation). Otherwise, it actually
* decrements the reference count and returns 0.
*/
return kref_put(&ndlp->kref, lpfc_nlp_release);
}
/* This routine free's the specified nodelist if it is not in use
* by any other discovery thread. This routine returns 1 if the
* ndlp has been freed. A return value of 0 indicates the ndlp is
* not yet been released.
*/
int
lpfc_nlp_not_used(struct lpfc_nodelist *ndlp)
{
lpfc_debugfs_disc_trc(ndlp->vport, LPFC_DISC_TRC_NODE,
"node not used: did:x%x flg:x%x refcnt:x%x",
ndlp->nlp_DID, ndlp->nlp_flag,
atomic_read(&ndlp->kref.refcount));
if (atomic_read(&ndlp->kref.refcount) == 1)
if (lpfc_nlp_put(ndlp))
return 1;
return 0;
}
/**
* lpfc_fcf_inuse - Check if FCF can be unregistered.
* @phba: Pointer to hba context object.
*
* This function iterate through all FC nodes associated
* will all vports to check if there is any node with
* fc_rports associated with it. If there is an fc_rport
* associated with the node, then the node is either in
* discovered state or its devloss_timer is pending.
*/
static int
lpfc_fcf_inuse(struct lpfc_hba *phba)
{
struct lpfc_vport **vports;
int i, ret = 0;
struct lpfc_nodelist *ndlp;
struct Scsi_Host *shost;
vports = lpfc_create_vport_work_array(phba);
for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
shost = lpfc_shost_from_vport(vports[i]);
spin_lock_irq(shost->host_lock);
list_for_each_entry(ndlp, &vports[i]->fc_nodes, nlp_listp) {
if (NLP_CHK_NODE_ACT(ndlp) && ndlp->rport &&
(ndlp->rport->roles & FC_RPORT_ROLE_FCP_TARGET)) {
ret = 1;
spin_unlock_irq(shost->host_lock);
goto out;
}
}
spin_unlock_irq(shost->host_lock);
}
out:
lpfc_destroy_vport_work_array(phba, vports);
return ret;
}
/**
* lpfc_unregister_vfi_cmpl - Completion handler for unreg vfi.
* @phba: Pointer to hba context object.
* @mboxq: Pointer to mailbox object.
*
* This function frees memory associated with the mailbox command.
*/
static void
lpfc_unregister_vfi_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
{
struct lpfc_vport *vport = mboxq->vport;
if (mboxq->u.mb.mbxStatus) {
lpfc_printf_log(phba, KERN_ERR, LOG_DISCOVERY|LOG_MBOX,
"2555 UNREG_VFI mbxStatus error x%x "
"HBA state x%x\n",
mboxq->u.mb.mbxStatus, vport->port_state);
}
mempool_free(mboxq, phba->mbox_mem_pool);
return;
}
/**
* lpfc_unregister_fcfi_cmpl - Completion handler for unreg fcfi.
* @phba: Pointer to hba context object.
* @mboxq: Pointer to mailbox object.
*
* This function frees memory associated with the mailbox command.
*/
static void
lpfc_unregister_fcfi_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
{
struct lpfc_vport *vport = mboxq->vport;
if (mboxq->u.mb.mbxStatus) {
lpfc_printf_log(phba, KERN_ERR, LOG_DISCOVERY|LOG_MBOX,
"2550 UNREG_FCFI mbxStatus error x%x "
"HBA state x%x\n",
mboxq->u.mb.mbxStatus, vport->port_state);
}
mempool_free(mboxq, phba->mbox_mem_pool);
return;
}
/**
* lpfc_unregister_unused_fcf - Unregister FCF if all devices are disconnected.
* @phba: Pointer to hba context object.
*
* This function check if there are any connected remote port for the FCF and
* if all the devices are disconnected, this function unregister FCFI.
* This function also tries to use another FCF for discovery.
*/
void
lpfc_unregister_unused_fcf(struct lpfc_hba *phba)
{
LPFC_MBOXQ_t *mbox;
int rc;
struct lpfc_vport **vports;
int i;
spin_lock_irq(&phba->hbalock);
/*
* If HBA is not running in FIP mode or
* If HBA does not support FCoE or
* If FCF is not registered.
* do nothing.
*/
if (!(phba->hba_flag & HBA_FCOE_SUPPORT) ||
!(phba->fcf.fcf_flag & FCF_REGISTERED) ||
(phba->cfg_enable_fip == 0)) {
spin_unlock_irq(&phba->hbalock);
return;
}
spin_unlock_irq(&phba->hbalock);
if (lpfc_fcf_inuse(phba))
return;
/* Unregister VPIs */
vports = lpfc_create_vport_work_array(phba);
if (vports &&
(phba->sli3_options & LPFC_SLI3_NPIV_ENABLED))
for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
lpfc_mbx_unreg_vpi(vports[i]);
vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
vports[i]->vfi_state &= ~LPFC_VFI_REGISTERED;
}
lpfc_destroy_vport_work_array(phba, vports);
/* Unregister VFI */
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!mbox) {
lpfc_printf_log(phba, KERN_ERR, LOG_DISCOVERY|LOG_MBOX,
"2556 UNREG_VFI mbox allocation failed"
"HBA state x%x\n",
phba->pport->port_state);
return;
}
lpfc_unreg_vfi(mbox, phba->pport->vfi);
mbox->vport = phba->pport;
mbox->mbox_cmpl = lpfc_unregister_vfi_cmpl;
rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
lpfc_printf_log(phba, KERN_ERR, LOG_DISCOVERY|LOG_MBOX,
"2557 UNREG_VFI issue mbox failed rc x%x "
"HBA state x%x\n",
rc, phba->pport->port_state);
mempool_free(mbox, phba->mbox_mem_pool);
return;
}
/* Unregister FCF */
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!mbox) {
lpfc_printf_log(phba, KERN_ERR, LOG_DISCOVERY|LOG_MBOX,
"2551 UNREG_FCFI mbox allocation failed"
"HBA state x%x\n",
phba->pport->port_state);
return;
}
lpfc_unreg_fcfi(mbox, phba->fcf.fcfi);
mbox->vport = phba->pport;
mbox->mbox_cmpl = lpfc_unregister_fcfi_cmpl;
rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
lpfc_printf_log(phba, KERN_ERR, LOG_DISCOVERY|LOG_MBOX,
"2552 UNREG_FCFI issue mbox failed rc x%x "
"HBA state x%x\n",
rc, phba->pport->port_state);
mempool_free(mbox, phba->mbox_mem_pool);
return;
}
spin_lock_irq(&phba->hbalock);
phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_REGISTERED |
FCF_DISCOVERED | FCF_BOOT_ENABLE | FCF_IN_USE |
FCF_VALID_VLAN);
spin_unlock_irq(&phba->hbalock);
/*
* If driver is not unloading, check if there is any other
* FCF record that can be used for discovery.
*/
if ((phba->pport->load_flag & FC_UNLOADING) ||
(phba->link_state < LPFC_LINK_UP))
return;
rc = lpfc_sli4_read_fcf_record(phba, LPFC_FCOE_FCF_GET_FIRST);
if (rc)
lpfc_printf_log(phba, KERN_ERR, LOG_DISCOVERY|LOG_MBOX,
"2553 lpfc_unregister_unused_fcf failed to read FCF"
" record HBA state x%x\n",
phba->pport->port_state);
}
/**
* lpfc_read_fcf_conn_tbl - Create driver FCF connection table.
* @phba: Pointer to hba context object.
* @buff: Buffer containing the FCF connection table as in the config
* region.
* This function create driver data structure for the FCF connection
* record table read from config region 23.
*/
static void
lpfc_read_fcf_conn_tbl(struct lpfc_hba *phba,
uint8_t *buff)
{
struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
struct lpfc_fcf_conn_hdr *conn_hdr;
struct lpfc_fcf_conn_rec *conn_rec;
uint32_t record_count;
int i;
/* Free the current connect table */
list_for_each_entry_safe(conn_entry, next_conn_entry,
&phba->fcf_conn_rec_list, list)
kfree(conn_entry);
conn_hdr = (struct lpfc_fcf_conn_hdr *) buff;
record_count = conn_hdr->length * sizeof(uint32_t)/
sizeof(struct lpfc_fcf_conn_rec);
conn_rec = (struct lpfc_fcf_conn_rec *)
(buff + sizeof(struct lpfc_fcf_conn_hdr));
for (i = 0; i < record_count; i++) {
if (!(conn_rec[i].flags & FCFCNCT_VALID))
continue;
conn_entry = kzalloc(sizeof(struct lpfc_fcf_conn_entry),
GFP_KERNEL);
if (!conn_entry) {
lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
"2566 Failed to allocate connection"
" table entry\n");
return;
}
memcpy(&conn_entry->conn_rec, &conn_rec[i],
sizeof(struct lpfc_fcf_conn_rec));
conn_entry->conn_rec.vlan_tag =
le16_to_cpu(conn_entry->conn_rec.vlan_tag) & 0xFFF;
conn_entry->conn_rec.flags =
le16_to_cpu(conn_entry->conn_rec.flags);
list_add_tail(&conn_entry->list,
&phba->fcf_conn_rec_list);
}
}
/**
* lpfc_read_fcoe_param - Read FCoe parameters from conf region..
* @phba: Pointer to hba context object.
* @buff: Buffer containing the FCoE parameter data structure.
*
* This function update driver data structure with config
* parameters read from config region 23.
*/
static void
lpfc_read_fcoe_param(struct lpfc_hba *phba,
uint8_t *buff)
{
struct lpfc_fip_param_hdr *fcoe_param_hdr;
struct lpfc_fcoe_params *fcoe_param;
fcoe_param_hdr = (struct lpfc_fip_param_hdr *)
buff;
fcoe_param = (struct lpfc_fcoe_params *)
(buff + sizeof(struct lpfc_fip_param_hdr));
if ((fcoe_param_hdr->parm_version != FIPP_VERSION) ||
(fcoe_param_hdr->length != FCOE_PARAM_LENGTH))
return;
if (bf_get(lpfc_fip_param_hdr_fipp_mode, fcoe_param_hdr) ==
FIPP_MODE_ON)
phba->cfg_enable_fip = 1;
if (bf_get(lpfc_fip_param_hdr_fipp_mode, fcoe_param_hdr) ==
FIPP_MODE_OFF)
phba->cfg_enable_fip = 0;
if (fcoe_param_hdr->parm_flags & FIPP_VLAN_VALID) {
phba->valid_vlan = 1;
phba->vlan_id = le16_to_cpu(fcoe_param->vlan_tag) &
0xFFF;
}
phba->fc_map[0] = fcoe_param->fc_map[0];
phba->fc_map[1] = fcoe_param->fc_map[1];
phba->fc_map[2] = fcoe_param->fc_map[2];
return;
}
/**
* lpfc_get_rec_conf23 - Get a record type in config region data.
* @buff: Buffer containing config region 23 data.
* @size: Size of the data buffer.
* @rec_type: Record type to be searched.
*
* This function searches config region data to find the begining
* of the record specified by record_type. If record found, this
* function return pointer to the record else return NULL.
*/
static uint8_t *
lpfc_get_rec_conf23(uint8_t *buff, uint32_t size, uint8_t rec_type)
{
uint32_t offset = 0, rec_length;
if ((buff[0] == LPFC_REGION23_LAST_REC) ||
(size < sizeof(uint32_t)))
return NULL;
rec_length = buff[offset + 1];
/*
* One TLV record has one word header and number of data words
* specified in the rec_length field of the record header.
*/
while ((offset + rec_length * sizeof(uint32_t) + sizeof(uint32_t))
<= size) {
if (buff[offset] == rec_type)
return &buff[offset];
if (buff[offset] == LPFC_REGION23_LAST_REC)
return NULL;
offset += rec_length * sizeof(uint32_t) + sizeof(uint32_t);
rec_length = buff[offset + 1];
}
return NULL;
}
/**
* lpfc_parse_fcoe_conf - Parse FCoE config data read from config region 23.
* @phba: Pointer to lpfc_hba data structure.
* @buff: Buffer containing config region 23 data.
* @size: Size of the data buffer.
*
* This fuction parse the FCoE config parameters in config region 23 and
* populate driver data structure with the parameters.
*/
void
lpfc_parse_fcoe_conf(struct lpfc_hba *phba,
uint8_t *buff,
uint32_t size)
{
uint32_t offset = 0, rec_length;
uint8_t *rec_ptr;
/*
* If data size is less than 2 words signature and version cannot be
* verified.
*/
if (size < 2*sizeof(uint32_t))
return;
/* Check the region signature first */
if (memcmp(buff, LPFC_REGION23_SIGNATURE, 4)) {
lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
"2567 Config region 23 has bad signature\n");
return;
}
offset += 4;
/* Check the data structure version */
if (buff[offset] != LPFC_REGION23_VERSION) {
lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
"2568 Config region 23 has bad version\n");
return;
}
offset += 4;
rec_length = buff[offset + 1];
/* Read FCoE param record */
rec_ptr = lpfc_get_rec_conf23(&buff[offset],
size - offset, FCOE_PARAM_TYPE);
if (rec_ptr)
lpfc_read_fcoe_param(phba, rec_ptr);
/* Read FCF connection table */
rec_ptr = lpfc_get_rec_conf23(&buff[offset],
size - offset, FCOE_CONN_TBL_TYPE);
if (rec_ptr)
lpfc_read_fcf_conn_tbl(phba, rec_ptr);
}
| gpl-2.0 |
tanzilli/ariag25-linux-2.6.39 | drivers/staging/quatech_usb2/quatech_usb2.c | 721 | 66258 | /*
* Driver for Quatech Inc USB2.0 to serial adaptors. Largely unrelated to the
* serqt_usb driver, based on a re-write of the vendor supplied serqt_usb2 code,
* which is unrelated to the serqt_usb2 in the staging kernel
*/
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/serial.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/uaccess.h>
static int debug;
/* Version Information */
#define DRIVER_VERSION "v2.00"
#define DRIVER_AUTHOR "Tim Gobeli, Quatech, Inc"
#define DRIVER_DESC "Quatech USB 2.0 to Serial Driver"
/* vendor and device IDs */
#define USB_VENDOR_ID_QUATECH 0x061d /* Quatech VID */
#define QUATECH_SSU2_100 0xC120 /* RS232 single port */
#define QUATECH_DSU2_100 0xC140 /* RS232 dual port */
#define QUATECH_DSU2_400 0xC150 /* RS232/422/485 dual port */
#define QUATECH_QSU2_100 0xC160 /* RS232 four port */
#define QUATECH_QSU2_400 0xC170 /* RS232/422/485 four port */
#define QUATECH_ESU2_100 0xC1A0 /* RS232 eight port */
#define QUATECH_ESU2_400 0xC180 /* RS232/422/485 eight port */
/* magic numbers go here, when we find out which ones are needed */
#define QU2BOXPWRON 0x8000 /* magic number to turn FPGA power on */
#define QU2BOX232 0x40 /* RS232 mode on MEI devices */
#define QU2BOXSPD9600 0x60 /* set speed to 9600 baud */
#define QT2_FIFO_DEPTH 1024 /* size of hardware fifos */
#define QT2_TX_HEADER_LENGTH 5
/* length of the header sent to the box with each write URB */
/* directions for USB transfers */
#define USBD_TRANSFER_DIRECTION_IN 0xc0
#define USBD_TRANSFER_DIRECTION_OUT 0x40
/* special Quatech command IDs. These are pushed down the
USB control pipe to get the box on the end to do things */
#define QT_SET_GET_DEVICE 0xc2
#define QT_OPEN_CLOSE_CHANNEL 0xca
/*#define QT_GET_SET_PREBUF_TRIG_LVL 0xcc
#define QT_SET_ATF 0xcd*/
#define QT2_GET_SET_REGISTER 0xc0
#define QT2_GET_SET_UART 0xc1
#define QT2_HW_FLOW_CONTROL_MASK 0xc5
#define QT2_SW_FLOW_CONTROL_MASK 0xc6
#define QT2_SW_FLOW_CONTROL_DISABLE 0xc7
#define QT2_BREAK_CONTROL 0xc8
#define QT2_STOP_RECEIVE 0xe0
#define QT2_FLUSH_DEVICE 0xc4
#define QT2_GET_SET_QMCR 0xe1
/* sorts of flush we can do on */
#define QT2_FLUSH_RX 0x00
#define QT2_FLUSH_TX 0x01
/* port setting constants, used to set up serial port speeds, flow
* control and so on */
#define QT2_SERIAL_MCR_DTR 0x01
#define QT2_SERIAL_MCR_RTS 0x02
#define QT2_SERIAL_MCR_LOOP 0x10
#define QT2_SERIAL_MSR_CTS 0x10
#define QT2_SERIAL_MSR_CD 0x80
#define QT2_SERIAL_MSR_RI 0x40
#define QT2_SERIAL_MSR_DSR 0x20
#define QT2_SERIAL_MSR_MASK 0xf0
#define QT2_SERIAL_8_DATA 0x03
#define QT2_SERIAL_7_DATA 0x02
#define QT2_SERIAL_6_DATA 0x01
#define QT2_SERIAL_5_DATA 0x00
#define QT2_SERIAL_ODD_PARITY 0x08
#define QT2_SERIAL_EVEN_PARITY 0x18
#define QT2_SERIAL_TWO_STOPB 0x04
#define QT2_SERIAL_ONE_STOPB 0x00
#define QT2_MAX_BAUD_RATE 921600
#define QT2_MAX_BAUD_REMAINDER 4608
#define QT2_SERIAL_LSR_OE 0x02
#define QT2_SERIAL_LSR_PE 0x04
#define QT2_SERIAL_LSR_FE 0x08
#define QT2_SERIAL_LSR_BI 0x10
/* value of Line Status Register when UART has completed
* emptying data out on the line */
#define QT2_LSR_TEMT 0x40
/* register numbers on each UART, for use with qt2_box_[get|set]_register*/
#define QT2_XMT_HOLD_REGISTER 0x00
#define QT2_XVR_BUFFER_REGISTER 0x00
#define QT2_FIFO_CONTROL_REGISTER 0x02
#define QT2_LINE_CONTROL_REGISTER 0x03
#define QT2_MODEM_CONTROL_REGISTER 0x04
#define QT2_LINE_STATUS_REGISTER 0x05
#define QT2_MODEM_STATUS_REGISTER 0x06
/* handy macros for doing escape sequence parsing on data reads */
#define THISCHAR ((unsigned char *)(urb->transfer_buffer))[i]
#define NEXTCHAR ((unsigned char *)(urb->transfer_buffer))[i + 1]
#define THIRDCHAR ((unsigned char *)(urb->transfer_buffer))[i + 2]
#define FOURTHCHAR ((unsigned char *)(urb->transfer_buffer))[i + 3]
#define FIFTHCHAR ((unsigned char *)(urb->transfer_buffer))[i + 4]
static const struct usb_device_id quausb2_id_table[] = {
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_SSU2_100)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU2_100)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU2_400)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU2_100)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU2_400)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU2_100)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU2_400)},
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, quausb2_id_table);
/* custom structures we need go here */
static struct usb_driver quausb2_usb_driver = {
.name = "quatech-usb2-serial",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = quausb2_id_table,
.no_dynamic_id = 1,
};
/**
* quatech2_port: Structure in which to keep all the messy stuff that this
* driver needs alongside the usb_serial_port structure
* @read_urb_busy: Flag indicating that port->read_urb is in use
* @close_pending: flag indicating that this port is in the process of
* being closed (and so no new reads / writes should be started).
* @shadowLSR: Last received state of the line status register, holds the
* value of the line status flags from the port
* @shadowMSR: Last received state of the modem status register, holds
* the value of the modem status received from the port
* @rcv_flush: Flag indicating that a receive flush has occurred on
* the hardware.
* @xmit_flush: Flag indicating that a transmit flush has been processed by
* the hardware.
* @tx_pending_bytes: Number of bytes waiting to be sent. This total
* includes the size (excluding header) of URBs that have been submitted but
* have not yet been sent to to the device, and bytes that have been sent out
* of the port but not yet reported sent by the "xmit_empty" messages (which
* indicate the number of bytes sent each time they are received, despite the
* misleading name).
* - Starts at zero when port is initialised.
* - is incremented by the size of the data to be written (no headers)
* each time a write urb is dispatched.
* - is decremented each time a "transmit empty" message is received
* by the driver in the data stream.
* @lock: Mutex to lock access to this structure when we need to ensure that
* races don't occur to access bits of it.
* @open_count: The number of uses of the port currently having
* it open, i.e. the reference count.
*/
struct quatech2_port {
int magic;
bool read_urb_busy;
bool close_pending;
__u8 shadowLSR;
__u8 shadowMSR;
bool rcv_flush;
bool xmit_flush;
int tx_pending_bytes;
struct mutex modelock;
int open_count;
char active; /* someone has this device open */
unsigned char *xfer_to_tty_buffer;
wait_queue_head_t wait;
__u8 shadowLCR; /* last LCR value received */
__u8 shadowMCR; /* last MCR value received */
char RxHolding;
struct semaphore pend_xmit_sem; /* locks this structure */
spinlock_t lock;
};
/**
* Structure to hold device-wide internal status information
* @param ReadBulkStopped The last bulk read attempt ended in tears
* @param open_ports The number of serial ports currently in use on the box
* @param current_port Pointer to the serial port structure of the port which
* the read stream is currently directed to. Escape sequences in the read
* stream will change this around as data arrives from different ports on the
* box
* @buffer_size: The max size buffer each URB can take, used to set the size of
* the buffers allocated for writing to each port on the device (we need to
* store this because it is known only to the endpoint, but used each time a
* port is opened and a new buffer is allocated.
*/
struct quatech2_dev {
bool ReadBulkStopped;
char open_ports;
struct usb_serial_port *current_port;
int buffer_size;
};
/* structure which holds line and modem status flags */
struct qt2_status_data {
__u8 line_status;
__u8 modem_status;
};
/* Function prototypes */
static int qt2_boxpoweron(struct usb_serial *serial);
static int qt2_boxsetQMCR(struct usb_serial *serial, __u16 Uart_Number,
__u8 QMCR_Value);
static int port_paranoia_check(struct usb_serial_port *port,
const char *function);
static int serial_paranoia_check(struct usb_serial *serial,
const char *function);
static inline struct quatech2_port *qt2_get_port_private(struct usb_serial_port
*port);
static inline void qt2_set_port_private(struct usb_serial_port *port,
struct quatech2_port *data);
static inline struct quatech2_dev *qt2_get_dev_private(struct usb_serial
*serial);
static inline void qt2_set_dev_private(struct usb_serial *serial,
struct quatech2_dev *data);
static int qt2_openboxchannel(struct usb_serial *serial, __u16
Uart_Number, struct qt2_status_data *pDeviceData);
static int qt2_closeboxchannel(struct usb_serial *serial, __u16
Uart_Number);
static int qt2_conf_uart(struct usb_serial *serial, unsigned short Uart_Number,
unsigned short divisor, unsigned char LCR);
static void qt2_read_bulk_callback(struct urb *urb);
static void qt2_write_bulk_callback(struct urb *urb);
static void qt2_process_line_status(struct usb_serial_port *port,
unsigned char LineStatus);
static void qt2_process_modem_status(struct usb_serial_port *port,
unsigned char ModemStatus);
static void qt2_process_xmit_empty(struct usb_serial_port *port,
unsigned char fourth_char, unsigned char fifth_char);
static void qt2_process_port_change(struct usb_serial_port *port,
unsigned char New_Current_Port);
static void qt2_process_rcv_flush(struct usb_serial_port *port);
static void qt2_process_xmit_flush(struct usb_serial_port *port);
static void qt2_process_rx_char(struct usb_serial_port *port,
unsigned char data);
static int qt2_box_get_register(struct usb_serial *serial,
unsigned char uart_number, unsigned short register_num,
__u8 *pValue);
static int qt2_box_set_register(struct usb_serial *serial,
unsigned short Uart_Number, unsigned short Register_Num,
unsigned short Value);
static int qt2_boxsetuart(struct usb_serial *serial, unsigned short Uart_Number,
unsigned short default_divisor, unsigned char default_LCR);
static int qt2_boxsethw_flowctl(struct usb_serial *serial,
unsigned int UartNumber, bool bSet);
static int qt2_boxsetsw_flowctl(struct usb_serial *serial, __u16 UartNumber,
unsigned char stop_char, unsigned char start_char);
static int qt2_boxunsetsw_flowctl(struct usb_serial *serial, __u16 UartNumber);
static int qt2_boxstoprx(struct usb_serial *serial, unsigned short uart_number,
unsigned short stop);
/* implementation functions, roughly in order of use, are here */
static int qt2_calc_num_ports(struct usb_serial *serial)
{
int num_ports;
int flag_as_400;
switch (serial->dev->descriptor.idProduct) {
case QUATECH_SSU2_100:
num_ports = 1;
break;
case QUATECH_DSU2_400:
flag_as_400 = true;
case QUATECH_DSU2_100:
num_ports = 2;
break;
case QUATECH_QSU2_400:
flag_as_400 = true;
case QUATECH_QSU2_100:
num_ports = 4;
break;
case QUATECH_ESU2_400:
flag_as_400 = true;
case QUATECH_ESU2_100:
num_ports = 8;
break;
default:
num_ports = 1;
break;
}
return num_ports;
}
static int qt2_attach(struct usb_serial *serial)
{
struct usb_serial_port *port;
struct quatech2_port *qt2_port; /* port-specific private data pointer */
struct quatech2_dev *qt2_dev; /* dev-specific private data pointer */
int i;
/* stuff for storing endpoint addresses now */
struct usb_endpoint_descriptor *endpoint;
struct usb_host_interface *iface_desc;
struct usb_serial_port *port0; /* first port structure on device */
/* check how many endpoints there are on the device, for
* sanity's sake */
dbg("%s(): Endpoints: %d bulk in, %d bulk out, %d interrupt in",
__func__, serial->num_bulk_in,
serial->num_bulk_out, serial->num_interrupt_in);
if ((serial->num_bulk_in != 1) || (serial->num_bulk_out != 1)) {
dbg("Device has wrong number of bulk endpoints!");
return -ENODEV;
}
iface_desc = serial->interface->cur_altsetting;
/* Set up per-device private data, storing extra data alongside
* struct usb_serial */
qt2_dev = kzalloc(sizeof(*qt2_dev), GFP_KERNEL);
if (!qt2_dev) {
dbg("%s: kmalloc for quatech2_dev failed!",
__func__);
return -ENOMEM;
}
qt2_dev->open_ports = 0; /* no ports open */
qt2_set_dev_private(serial, qt2_dev); /* store private data */
/* Now setup per port private data, which replaces all the things
* that quatech added to standard kernel structures in their driver */
for (i = 0; i < serial->num_ports; i++) {
port = serial->port[i];
qt2_port = kzalloc(sizeof(*qt2_port), GFP_KERNEL);
if (!qt2_port) {
dbg("%s: kmalloc for quatech2_port (%d) failed!.",
__func__, i);
return -ENOMEM;
}
/* initialise stuff in the structure */
qt2_port->open_count = 0; /* port is not open */
spin_lock_init(&qt2_port->lock);
mutex_init(&qt2_port->modelock);
qt2_set_port_private(port, qt2_port);
}
/* gain access to port[0]'s structure because we want to store
* device-level stuff in it */
if (serial_paranoia_check(serial, __func__))
return -ENODEV;
port0 = serial->port[0]; /* get the first port's device structure */
/* print endpoint addresses so we can check them later
* by hand */
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if ((endpoint->bEndpointAddress & 0x80) &&
((endpoint->bmAttributes & 3) == 0x02)) {
/* we found a bulk in endpoint */
dbg("found bulk in at %#.2x",
endpoint->bEndpointAddress);
}
if (((endpoint->bEndpointAddress & 0x80) == 0x00) &&
((endpoint->bmAttributes & 3) == 0x02)) {
/* we found a bulk out endpoint */
dbg("found bulk out at %#.2x",
endpoint->bEndpointAddress);
qt2_dev->buffer_size = endpoint->wMaxPacketSize;
/* max size of URB needs recording for the device */
}
} /* end printing endpoint addresses */
/* switch on power to the hardware */
if (qt2_boxpoweron(serial) < 0) {
dbg("qt2_boxpoweron() failed");
goto startup_error;
}
/* set all ports to RS232 mode */
for (i = 0; i < serial->num_ports; ++i) {
if (qt2_boxsetQMCR(serial, i, QU2BOX232) < 0) {
dbg("qt2_boxsetQMCR() on port %d failed",
i);
goto startup_error;
}
}
return 0;
startup_error:
for (i = 0; i < serial->num_ports; i++) {
port = serial->port[i];
qt2_port = qt2_get_port_private(port);
kfree(qt2_port);
qt2_set_port_private(port, NULL);
}
qt2_dev = qt2_get_dev_private(serial);
kfree(qt2_dev);
qt2_set_dev_private(serial, NULL);
dbg("Exit fail %s\n", __func__);
return -EIO;
}
static void qt2_release(struct usb_serial *serial)
{
struct usb_serial_port *port;
struct quatech2_port *qt_port;
int i;
dbg("enterting %s", __func__);
for (i = 0; i < serial->num_ports; i++) {
port = serial->port[i];
if (!port)
continue;
qt_port = usb_get_serial_port_data(port);
kfree(qt_port);
usb_set_serial_port_data(port, NULL);
}
}
/* This function is called once per serial port on the device, when
* that port is opened by a userspace application.
* The tty_struct and the usb_serial_port belong to this port,
* i.e. there are multiple ones for a multi-port device.
* However the usb_serial_port structure has a back-pointer
* to the parent usb_serial structure which belongs to the device,
* so we can access either the device-wide information or
* any other port's information (because there are also forward
* pointers) via that pointer.
* This is most helpful if the device shares resources (e.g. end
* points) between different ports
*/
int qt2_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct usb_serial *serial; /* device structure */
struct usb_serial_port *port0; /* first port structure on device */
struct quatech2_port *port_extra; /* extra data for this port */
struct quatech2_port *port0_extra; /* extra data for first port */
struct quatech2_dev *dev_extra; /* extra data for the device */
struct qt2_status_data ChannelData;
unsigned short default_divisor = QU2BOXSPD9600;
unsigned char default_LCR = QT2_SERIAL_8_DATA;
int status;
int result;
if (port_paranoia_check(port, __func__))
return -ENODEV;
dbg("%s(): port %d", __func__, port->number);
serial = port->serial; /* get the parent device structure */
if (serial_paranoia_check(serial, __func__)) {
dbg("usb_serial struct failed sanity check");
return -ENODEV;
}
dev_extra = qt2_get_dev_private(serial);
/* get the device private data */
if (dev_extra == NULL) {
dbg("device extra data pointer is null");
return -ENODEV;
}
port0 = serial->port[0]; /* get the first port's device structure */
if (port_paranoia_check(port0, __func__)) {
dbg("port0 usb_serial_port struct failed sanity check");
return -ENODEV;
}
port_extra = qt2_get_port_private(port);
port0_extra = qt2_get_port_private(port0);
if (port_extra == NULL || port0_extra == NULL) {
dbg("failed to get private data for port or port0");
return -ENODEV;
}
/* FIXME: are these needed? Does it even do anything useful? */
/* get the modem and line status values from the UART */
status = qt2_openboxchannel(serial, port->number,
&ChannelData);
if (status < 0) {
dbg("qt2_openboxchannel on channel %d failed",
port->number);
return status;
}
port_extra->shadowLSR = ChannelData.line_status &
(QT2_SERIAL_LSR_OE | QT2_SERIAL_LSR_PE |
QT2_SERIAL_LSR_FE | QT2_SERIAL_LSR_BI);
port_extra->shadowMSR = ChannelData.modem_status &
(QT2_SERIAL_MSR_CTS | QT2_SERIAL_MSR_DSR |
QT2_SERIAL_MSR_RI | QT2_SERIAL_MSR_CD);
/* port_extra->fifo_empty_flag = true;*/
dbg("qt2_openboxchannel on channel %d completed.",
port->number);
/* Set Baud rate to default and turn off flow control here */
status = qt2_conf_uart(serial, port->number, default_divisor,
default_LCR);
if (status < 0) {
dbg("qt2_conf_uart() failed on channel %d",
port->number);
return status;
}
dbg("qt2_conf_uart() completed on channel %d",
port->number);
/*
* At this point we will need some end points to make further progress.
* Handlily, the correct endpoint addresses have been filled out into
* the usb_serial_port structure for us by the driver core, so we
* already have access to them.
* As there is only one bulk in and one bulk out end-point, these are in
* port[0]'s structure, and the rest are uninitialised. Handily,
* when we do a write to a port, we will use the same endpoint
* regardless of the port, with a 5-byte header added on to
* tell the box which port it should eventually come out of, so we only
* need the one set of endpoints. We will have one URB per port for
* writing, so that multiple ports can be writing at once.
* Finally we need a bulk in URB to use for background reads from the
* device, which will deal with uplink data from the box to host.
*/
dbg("port0 bulk in endpoint is %#.2x", port0->bulk_in_endpointAddress);
dbg("port0 bulk out endpoint is %#.2x",
port0->bulk_out_endpointAddress);
/* set up write_urb for bulk out transfers on this port. The USB
* serial framework will have allocated a blank URB, buffer etc for
* port0 when it put the endpoints there, but not for any of the other
* ports on the device because there are no more endpoints. Thus we
* have to allocate our own URBs for ports 1-7
*/
if (port->write_urb == NULL) {
dbg("port->write_urb == NULL, allocating one");
port->write_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!port->write_urb) {
err("Allocating write URB failed");
return -ENOMEM;
}
/* buffer same size as port0 */
port->bulk_out_size = dev_extra->buffer_size;
port->bulk_out_buffer = kmalloc(port->bulk_out_size,
GFP_KERNEL);
if (!port->bulk_out_buffer) {
err("Couldn't allocate bulk_out_buffer");
return -ENOMEM;
}
}
if (serial->dev == NULL)
dbg("serial->dev == NULL");
dbg("port->bulk_out_size is %d", port->bulk_out_size);
usb_fill_bulk_urb(port->write_urb, serial->dev,
usb_sndbulkpipe(serial->dev,
port0->bulk_out_endpointAddress),
port->bulk_out_buffer,
port->bulk_out_size,
qt2_write_bulk_callback,
port);
port_extra->tx_pending_bytes = 0;
if (dev_extra->open_ports == 0) {
/* this is first port to be opened, so need the read URB
* initialised for bulk in transfers (this is shared amongst
* all the ports on the device) */
usb_fill_bulk_urb(port0->read_urb, serial->dev,
usb_rcvbulkpipe(serial->dev,
port0->bulk_in_endpointAddress),
port0->bulk_in_buffer,
port0->bulk_in_size,
qt2_read_bulk_callback, serial);
dbg("port0 bulk in URB initialised");
/* submit URB, i.e. start reading from device (async) */
dev_extra->ReadBulkStopped = false;
port_extra->read_urb_busy = true;
result = usb_submit_urb(port->read_urb, GFP_KERNEL);
if (result) {
dev_err(&port->dev,
"%s(): Error %d submitting bulk in urb",
__func__, result);
port_extra->read_urb_busy = false;
dev_extra->ReadBulkStopped = true;
}
/* When the first port is opened, initialise the value of
* current_port in dev_extra to this port, so it is set
* to something. Once the box sends data it will send the
* relevant escape sequences to get it to the right port anyway
*/
dev_extra->current_port = port;
}
/* initialize our wait queues */
init_waitqueue_head(&port_extra->wait);
/* increment the count of openings of this port by one */
port_extra->open_count++;
/* remember to store dev_extra, port_extra and port0_extra back again at
* end !*/
qt2_set_port_private(port, port_extra);
qt2_set_port_private(serial->port[0], port0_extra);
qt2_set_dev_private(serial, dev_extra);
dev_extra->open_ports++; /* one more port opened */
return 0;
}
/* called when a port is closed by userspace. It won't be called, however,
* until calls to chars_in_buffer() reveal that the port has completed
* sending buffered data, and there is nothing else to do. Thus we don't have
* to rely on forcing data through in this function. */
/* Setting close_pending should keep new data from being written out,
* once all the data in the enpoint buffers is moved out we won't get
* any more. */
/* BoxStopReceive would keep any more data from coming from a given
* port, but isn't called by the vendor driver, although their comments
* mention it. Should it be used here to stop the inbound data
* flow?
*/
static void qt2_close(struct usb_serial_port *port)
{
/* time out value for flush loops */
unsigned long jift;
struct quatech2_port *port_extra; /* extra data for this port */
struct usb_serial *serial; /* device structure */
struct quatech2_dev *dev_extra; /* extra data for the device */
__u8 lsr_value = 0; /* value of Line Status Register */
int status; /* result of last USB comms function */
dbg("%s(): port %d", __func__, port->number);
serial = port->serial; /* get the parent device structure */
dev_extra = qt2_get_dev_private(serial);
/* get the device private data */
port_extra = qt2_get_port_private(port); /* port private data */
/* we can now (and only now) stop reading data */
port_extra->close_pending = true;
dbg("%s(): port_extra->close_pending = true", __func__);
/* although the USB side is now empty, the UART itself may
* still be pushing characters out over the line, so we have to
* wait testing the actual line status until the lines change
* indicating that the data is done transferring. */
/* FIXME: slow this polling down so it doesn't run the USB bus flat out
* if it actually has to spend any time in this loop (which it normally
* doesn't because the buffer is nearly empty) */
jift = jiffies + (10 * HZ); /* 10 sec timeout */
do {
status = qt2_box_get_register(serial, port->number,
QT2_LINE_STATUS_REGISTER, &lsr_value);
if (status < 0) {
dbg("%s(): qt2_box_get_register failed", __func__);
break;
}
if ((lsr_value & QT2_LSR_TEMT)) {
dbg("UART done sending");
break;
}
schedule();
} while (jiffies <= jift);
status = qt2_closeboxchannel(serial, port->number);
if (status < 0)
dbg("%s(): port %d qt2_box_open_close_channel failed",
__func__, port->number);
/* to avoid leaking URBs, we should now free the write_urb for this
* port and set the pointer to null so that next time the port is opened
* a new URB is allocated. This avoids leaking URBs when the device is
* removed */
usb_free_urb(port->write_urb);
kfree(port->bulk_out_buffer);
port->bulk_out_buffer = NULL;
port->bulk_out_size = 0;
/* decrement the count of openings of this port by one */
port_extra->open_count--;
/* one less overall open as well */
dev_extra->open_ports--;
dbg("%s(): Exit, dev_extra->open_ports = %d", __func__,
dev_extra->open_ports);
}
/**
* qt2_write - write bytes from the tty layer out to the USB device.
* @buf: The data to be written, size at least count.
* @count: The number of bytes requested for transmission.
* @return The number of bytes actually accepted for transmission to the device.
*/
static int qt2_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *buf, int count)
{
struct usb_serial *serial; /* parent device struct */
__u8 header_array[5]; /* header used to direct writes to the correct
port on the device */
struct quatech2_port *port_extra; /* extra data for this port */
int result;
serial = port->serial; /* get the parent device of the port */
port_extra = qt2_get_port_private(port); /* port extra info */
if (serial == NULL)
return -ENODEV;
dbg("%s(): port %d, requested to write %d bytes, %d already pending",
__func__, port->number, count, port_extra->tx_pending_bytes);
if (count <= 0) {
dbg("%s(): write request of <= 0 bytes", __func__);
return 0; /* no bytes written */
}
/* check if the write urb is already in use, i.e. data already being
* sent to this port */
if ((port->write_urb->status == -EINPROGRESS)) {
/* Fifo hasn't been emptied since last write to this port */
dbg("%s(): already writing, port->write_urb->status == "
"-EINPROGRESS", __func__);
/* schedule_work(&port->work); commented in vendor driver */
return 0;
} else if (port_extra->tx_pending_bytes >= QT2_FIFO_DEPTH) {
/* buffer is full (==). > should not occur, but would indicate
* that an overflow had occurred */
dbg("%s(): port transmit buffer is full!", __func__);
/* schedule_work(&port->work); commented in vendor driver */
return 0;
}
/* We must fill the first 5 bytes of anything we sent with a transmit
* header which directes the data to the correct port. The maximum
* size we can send out in one URB is port->bulk_out_size, which caps
* the number of bytes of real data we can send in each write. As the
* semantics of write allow us to write less than we were give, we cap
* the maximum we will ever write to the device as 5 bytes less than
* one URB's worth, by reducing the value of the count argument
* appropriately*/
if (count > port->bulk_out_size - QT2_TX_HEADER_LENGTH) {
count = port->bulk_out_size - QT2_TX_HEADER_LENGTH;
dbg("%s(): write request bigger than urb, only accepting "
"%d bytes", __func__, count);
}
/* we must also ensure that the FIFO at the other end can cope with the
* URB we send it, otherwise it will have problems. As above, we can
* restrict the write size by just shrinking count.*/
if (count > (QT2_FIFO_DEPTH - port_extra->tx_pending_bytes)) {
count = QT2_FIFO_DEPTH - port_extra->tx_pending_bytes;
dbg("%s(): not enough room in buffer, only accepting %d bytes",
__func__, count);
}
/* now build the header for transmission */
header_array[0] = 0x1b;
header_array[1] = 0x1b;
header_array[2] = (__u8)port->number;
header_array[3] = (__u8)count;
header_array[4] = (__u8)count >> 8;
/* copy header into URB */
memcpy(port->write_urb->transfer_buffer, header_array,
QT2_TX_HEADER_LENGTH);
/* and actual data to write */
memcpy(port->write_urb->transfer_buffer + 5, buf, count);
dbg("%s(): first data byte to send = %#.2x", __func__, *buf);
/* set up our urb */
usb_fill_bulk_urb(port->write_urb, serial->dev,
usb_sndbulkpipe(serial->dev,
port->bulk_out_endpointAddress),
port->write_urb->transfer_buffer, count + 5,
(qt2_write_bulk_callback), port);
/* send the data out the bulk port */
result = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (result) {
/* error couldn't submit urb */
result = 0; /* return 0 as nothing got written */
dbg("%s(): failed submitting write urb, error %d",
__func__, result);
} else {
port_extra->tx_pending_bytes += count;
result = count; /* return number of bytes written, i.e. count */
dbg("%s(): submitted write urb, wrote %d bytes, "
"total pending bytes %d",
__func__, result, port_extra->tx_pending_bytes);
}
return result;
}
/* This is used by the next layer up to know how much space is available
* in the buffer on the device. It is used on a device closure to avoid
* calling close() until the buffer is reported to be empty.
* The returned value must never go down by more than the number of bytes
* written for correct behaviour further up the driver stack, i.e. if I call
* it, then write 6 bytes, then call again I should get 6 less, or possibly
* only 5 less if one was written in the meantime, etc. I should never get 7
* less (or any bigger number) because I only wrote 6 bytes.
*/
static int qt2_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
/* parent usb_serial_port pointer */
struct quatech2_port *port_extra; /* extra data for this port */
int room = 0;
port_extra = qt2_get_port_private(port);
if (port_extra->close_pending == true) {
dbg("%s(): port_extra->close_pending == true", __func__);
return -ENODEV;
}
/* Q: how many bytes would a write() call actually succeed in writing
* if it happened now?
* A: one QT2_FIFO_DEPTH, less the number of bytes waiting to be sent
* out of the port, unless this is more than the size of the
* write_urb output buffer less the header, which is the maximum
* size write we can do.
* Most of the implementation of this is done when writes to the device
* are started or terminate. When we send a write to the device, we
* reduce the free space count by the size of the dispatched write.
* When a "transmit empty" message comes back up the USB read stream,
* we decrement the count by the number of bytes reported sent, thus
* keeping track of the difference between sent and received bytes.
*/
room = (QT2_FIFO_DEPTH - port_extra->tx_pending_bytes);
/* space in FIFO */
if (room > port->bulk_out_size - QT2_TX_HEADER_LENGTH)
room = port->bulk_out_size - QT2_TX_HEADER_LENGTH;
/* if more than the URB can hold, then cap to that limit */
dbg("%s(): port %d: write room is %d", __func__, port->number, room);
return room;
}
static int qt2_chars_in_buffer(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
/* parent usb_serial_port pointer */
struct quatech2_port *port_extra; /* extra data for this port */
port_extra = qt2_get_port_private(port);
dbg("%s(): port %d: chars_in_buffer = %d", __func__,
port->number, port_extra->tx_pending_bytes);
return port_extra->tx_pending_bytes;
}
/* called when userspace does an ioctl() on the device. Note that
* TIOCMGET and TIOCMSET are filtered off to their own methods before they get
* here, so we don't have to handle them.
*/
static int qt2_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_serial *serial = port->serial;
__u8 mcr_value; /* Modem Control Register value */
__u8 msr_value; /* Modem Status Register value */
unsigned short prev_msr_value; /* Previous value of Modem Status
* Register used to implement waiting for a line status change to
* occur */
struct quatech2_port *port_extra; /* extra data for this port */
DECLARE_WAITQUEUE(wait, current);
/* Declare a wait queue named "wait" */
unsigned int value;
unsigned int UartNumber;
if (serial == NULL)
return -ENODEV;
UartNumber = tty->index - serial->minor;
port_extra = qt2_get_port_private(port);
dbg("%s(): port %d, UartNumber %d, tty =0x%p", __func__,
port->number, UartNumber, tty);
if (cmd == TIOCMBIS || cmd == TIOCMBIC) {
if (qt2_box_get_register(port->serial, UartNumber,
QT2_MODEM_CONTROL_REGISTER, &mcr_value) < 0)
return -ESPIPE;
if (copy_from_user(&value, (unsigned int *)arg,
sizeof(value)))
return -EFAULT;
switch (cmd) {
case TIOCMBIS:
if (value & TIOCM_RTS)
mcr_value |= QT2_SERIAL_MCR_RTS;
if (value & TIOCM_DTR)
mcr_value |= QT2_SERIAL_MCR_DTR;
if (value & TIOCM_LOOP)
mcr_value |= QT2_SERIAL_MCR_LOOP;
break;
case TIOCMBIC:
if (value & TIOCM_RTS)
mcr_value &= ~QT2_SERIAL_MCR_RTS;
if (value & TIOCM_DTR)
mcr_value &= ~QT2_SERIAL_MCR_DTR;
if (value & TIOCM_LOOP)
mcr_value &= ~QT2_SERIAL_MCR_LOOP;
break;
default:
break;
} /* end of local switch on cmd */
if (qt2_box_set_register(port->serial, UartNumber,
QT2_MODEM_CONTROL_REGISTER, mcr_value) < 0) {
return -ESPIPE;
} else {
port_extra->shadowMCR = mcr_value;
return 0;
}
} else if (cmd == TIOCMIWAIT) {
dbg("%s() port %d, cmd == TIOCMIWAIT enter",
__func__, port->number);
prev_msr_value = port_extra->shadowMSR & QT2_SERIAL_MSR_MASK;
while (1) {
add_wait_queue(&port_extra->wait, &wait);
set_current_state(TASK_INTERRUPTIBLE);
schedule();
dbg("%s(): port %d, cmd == TIOCMIWAIT here\n",
__func__, port->number);
remove_wait_queue(&port_extra->wait, &wait);
/* see if a signal woke us up */
if (signal_pending(current))
return -ERESTARTSYS;
msr_value = port_extra->shadowMSR & QT2_SERIAL_MSR_MASK;
if (msr_value == prev_msr_value)
return -EIO; /* no change - error */
if ((arg & TIOCM_RNG &&
((prev_msr_value & QT2_SERIAL_MSR_RI) ==
(msr_value & QT2_SERIAL_MSR_RI))) ||
(arg & TIOCM_DSR &&
((prev_msr_value & QT2_SERIAL_MSR_DSR) ==
(msr_value & QT2_SERIAL_MSR_DSR))) ||
(arg & TIOCM_CD &&
((prev_msr_value & QT2_SERIAL_MSR_CD) ==
(msr_value & QT2_SERIAL_MSR_CD))) ||
(arg & TIOCM_CTS &&
((prev_msr_value & QT2_SERIAL_MSR_CTS) ==
(msr_value & QT2_SERIAL_MSR_CTS)))) {
return 0;
}
} /* end inifinite while */
/* FIXME: This while loop needs a way to break out if the device
* is disconnected while a process is waiting for the MSR to
* change, because once it's disconnected, it isn't going to
* change state ... */
} else {
/* any other ioctls we don't know about come here */
dbg("%s(): No ioctl for that one. port = %d", __func__,
port->number);
return -ENOIOCTLCMD;
}
}
/* Called when the user wishes to change the port settings using the termios
* userspace interface */
static void qt2_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios)
{
struct usb_serial *serial; /* parent serial device */
int baud, divisor, remainder;
unsigned char LCR_change_to = 0;
int status;
__u16 UartNumber;
dbg("%s(): port %d", __func__, port->number);
serial = port->serial;
UartNumber = port->number;
if (old_termios && !tty_termios_hw_change(old_termios, tty->termios))
return;
switch (tty->termios->c_cflag) {
case CS5:
LCR_change_to |= QT2_SERIAL_5_DATA;
break;
case CS6:
LCR_change_to |= QT2_SERIAL_6_DATA;
break;
case CS7:
LCR_change_to |= QT2_SERIAL_7_DATA;
break;
default:
case CS8:
LCR_change_to |= QT2_SERIAL_8_DATA;
break;
}
/* Parity stuff */
if (tty->termios->c_cflag & PARENB) {
if (tty->termios->c_cflag & PARODD)
LCR_change_to |= QT2_SERIAL_ODD_PARITY;
else
LCR_change_to |= QT2_SERIAL_EVEN_PARITY;
}
/* Because LCR_change_to is initialised to zero, we don't have to worry
* about the case where PARENB is not set or clearing bits, because by
* default all of them are cleared, turning parity off.
* as we don't support mark/space parity, we should clear the
* mark/space parity bit in c_cflag, so the caller can tell we have
* ignored the request */
tty->termios->c_cflag &= ~CMSPAR;
if (tty->termios->c_cflag & CSTOPB)
LCR_change_to |= QT2_SERIAL_TWO_STOPB;
else
LCR_change_to |= QT2_SERIAL_ONE_STOPB;
/* Thats the LCR stuff, next we need to work out the divisor as the
* LCR and the divisor are set together */
baud = tty_get_baud_rate(tty);
if (!baud) {
/* pick a default, any default... */
baud = 9600;
}
dbg("%s(): got baud = %d", __func__, baud);
divisor = QT2_MAX_BAUD_RATE / baud;
remainder = QT2_MAX_BAUD_RATE % baud;
/* Round to nearest divisor */
if (((remainder * 2) >= baud) && (baud != 110))
divisor++;
dbg("%s(): setting divisor = %d, QT2_MAX_BAUD_RATE = %d , LCR = %#.2x",
__func__, divisor, QT2_MAX_BAUD_RATE, LCR_change_to);
status = qt2_boxsetuart(serial, UartNumber, (unsigned short) divisor,
LCR_change_to);
if (status < 0) {
dbg("qt2_boxsetuart() failed");
return;
} else {
/* now encode the baud rate we actually set, which may be
* different to the request */
baud = QT2_MAX_BAUD_RATE / divisor;
tty_encode_baud_rate(tty, baud, baud);
}
/* Now determine flow control */
if (tty->termios->c_cflag & CRTSCTS) {
dbg("%s(): Enabling HW flow control port %d", __func__,
port->number);
/* Enable RTS/CTS flow control */
status = qt2_boxsethw_flowctl(serial, UartNumber, true);
if (status < 0) {
dbg("qt2_boxsethw_flowctl() failed");
return;
}
} else {
/* Disable RTS/CTS flow control */
dbg("%s(): disabling HW flow control port %d", __func__,
port->number);
status = qt2_boxsethw_flowctl(serial, UartNumber, false);
if (status < 0) {
dbg("qt2_boxsethw_flowctl failed");
return;
}
}
/* if we are implementing XON/XOFF, set the start and stop character
* in the device */
if (I_IXOFF(tty) || I_IXON(tty)) {
unsigned char stop_char = STOP_CHAR(tty);
unsigned char start_char = START_CHAR(tty);
status = qt2_boxsetsw_flowctl(serial, UartNumber, stop_char,
start_char);
if (status < 0)
dbg("qt2_boxsetsw_flowctl (enabled) failed");
} else {
/* disable SW flow control */
status = qt2_boxunsetsw_flowctl(serial, UartNumber);
if (status < 0)
dbg("qt2_boxunsetsw_flowctl (disabling) failed");
}
}
static int qt2_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_serial *serial = port->serial;
__u8 mcr_value; /* Modem Control Register value */
__u8 msr_value; /* Modem Status Register value */
unsigned int result = 0;
int status;
unsigned int UartNumber;
if (serial == NULL)
return -ENODEV;
dbg("%s(): port %d, tty =0x%p", __func__, port->number, tty);
UartNumber = tty->index - serial->minor;
dbg("UartNumber is %d", UartNumber);
status = qt2_box_get_register(port->serial, UartNumber,
QT2_MODEM_CONTROL_REGISTER, &mcr_value);
if (status >= 0) {
status = qt2_box_get_register(port->serial, UartNumber,
QT2_MODEM_STATUS_REGISTER, &msr_value);
}
if (status >= 0) {
result = ((mcr_value & QT2_SERIAL_MCR_DTR) ? TIOCM_DTR : 0)
/*DTR set */
| ((mcr_value & QT2_SERIAL_MCR_RTS) ? TIOCM_RTS : 0)
/*RTS set */
| ((msr_value & QT2_SERIAL_MSR_CTS) ? TIOCM_CTS : 0)
/* CTS set */
| ((msr_value & QT2_SERIAL_MSR_CD) ? TIOCM_CAR : 0)
/*Carrier detect set */
| ((msr_value & QT2_SERIAL_MSR_RI) ? TIOCM_RI : 0)
/* Ring indicator set */
| ((msr_value & QT2_SERIAL_MSR_DSR) ? TIOCM_DSR : 0);
/* DSR set */
return result;
} else {
return -ESPIPE;
}
}
static int qt2_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_serial *serial = port->serial;
__u8 mcr_value; /* Modem Control Register value */
int status;
unsigned int UartNumber;
if (serial == NULL)
return -ENODEV;
UartNumber = tty->index - serial->minor;
dbg("%s(): port %d, UartNumber %d", __func__, port->number, UartNumber);
status = qt2_box_get_register(port->serial, UartNumber,
QT2_MODEM_CONTROL_REGISTER, &mcr_value);
if (status < 0)
return -ESPIPE;
/* Turn off RTS, DTR and loopback, then only turn on what was asked
* for */
mcr_value &= ~(QT2_SERIAL_MCR_RTS | QT2_SERIAL_MCR_DTR |
QT2_SERIAL_MCR_LOOP);
if (set & TIOCM_RTS)
mcr_value |= QT2_SERIAL_MCR_RTS;
if (set & TIOCM_DTR)
mcr_value |= QT2_SERIAL_MCR_DTR;
if (set & TIOCM_LOOP)
mcr_value |= QT2_SERIAL_MCR_LOOP;
status = qt2_box_set_register(port->serial, UartNumber,
QT2_MODEM_CONTROL_REGISTER, mcr_value);
if (status < 0)
return -ESPIPE;
else
return 0;
}
/** qt2_break - Turn BREAK on and off on the UARTs
*/
static void qt2_break(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data; /* parent port */
struct usb_serial *serial = port->serial; /* parent device */
struct quatech2_port *port_extra; /* extra data for this port */
__u16 break_value;
unsigned int result;
port_extra = qt2_get_port_private(port);
if (!serial) {
dbg("%s(): port %d: no serial object", __func__, port->number);
return;
}
if (break_state == -1)
break_value = 1;
else
break_value = 0;
dbg("%s(): port %d, break_value %d", __func__, port->number,
break_value);
mutex_lock(&port_extra->modelock);
if (!port_extra->open_count) {
dbg("%s(): port not open", __func__);
goto exit;
}
result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_BREAK_CONTROL, 0x40, break_value,
port->number, NULL, 0, 300);
exit:
mutex_unlock(&port_extra->modelock);
dbg("%s(): exit port %d", __func__, port->number);
}
/**
* qt2_throttle: - stop reading new data from the port
*/
static void qt2_throttle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_serial *serial = port->serial;
struct quatech2_port *port_extra; /* extra data for this port */
dbg("%s(): port %d", __func__, port->number);
port_extra = qt2_get_port_private(port);
if (!serial) {
dbg("%s(): enter port %d no serial object", __func__,
port->number);
return;
}
mutex_lock(&port_extra->modelock); /* lock structure */
if (!port_extra->open_count) {
dbg("%s(): port not open", __func__);
goto exit;
}
/* Send command to box to stop receiving stuff. This will stop this
* particular UART from filling the endpoint - in the multiport case the
* FPGA UART will handle any flow control implemented, but for the single
* port it's handed differently and we just quit submitting urbs
*/
if (serial->dev->descriptor.idProduct != QUATECH_SSU2_100)
qt2_boxstoprx(serial, port->number, 1);
port->throttled = 1;
exit:
mutex_unlock(&port_extra->modelock);
dbg("%s(): port %d: setting port->throttled", __func__, port->number);
return;
}
/**
* qt2_unthrottle: - start receiving data through the port again after being
* throttled
*/
static void qt2_unthrottle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_serial *serial = port->serial;
struct quatech2_port *port_extra; /* extra data for this port */
struct usb_serial_port *port0; /* first port structure on device */
struct quatech2_dev *dev_extra; /* extra data for the device */
if (!serial) {
dbg("%s() enter port %d no serial object!", __func__,
port->number);
return;
}
dbg("%s(): enter port %d", __func__, port->number);
dev_extra = qt2_get_dev_private(serial);
port_extra = qt2_get_port_private(port);
port0 = serial->port[0]; /* get the first port's device structure */
mutex_lock(&port_extra->modelock);
if (!port_extra->open_count) {
dbg("%s(): port %d not open", __func__, port->number);
goto exit;
}
if (port->throttled != 0) {
dbg("%s(): port %d: unsetting port->throttled", __func__,
port->number);
port->throttled = 0;
/* Send command to box to start receiving stuff */
if (serial->dev->descriptor.idProduct != QUATECH_SSU2_100) {
qt2_boxstoprx(serial, port->number, 0);
} else if (dev_extra->ReadBulkStopped == true) {
usb_fill_bulk_urb(port0->read_urb, serial->dev,
usb_rcvbulkpipe(serial->dev,
port0->bulk_in_endpointAddress),
port0->bulk_in_buffer,
port0->bulk_in_size,
qt2_read_bulk_callback,
serial);
}
}
exit:
mutex_unlock(&port_extra->modelock);
dbg("%s(): exit port %d", __func__, port->number);
return;
}
/* internal, private helper functions for the driver */
/* Power up the FPGA in the box to get it working */
static int qt2_boxpoweron(struct usb_serial *serial)
{
int result;
__u8 Direcion;
unsigned int pipe;
Direcion = USBD_TRANSFER_DIRECTION_OUT;
pipe = usb_rcvctrlpipe(serial->dev, 0);
result = usb_control_msg(serial->dev, pipe, QT_SET_GET_DEVICE,
Direcion, QU2BOXPWRON, 0x00, NULL, 0x00,
5000);
return result;
}
/*
* qt2_boxsetQMCR Issue a QT2_GET_SET_QMCR vendor-spcific request on the
* default control pipe. If successful return the number of bytes written,
* otherwise return a negative error number of the problem.
*/
static int qt2_boxsetQMCR(struct usb_serial *serial, __u16 Uart_Number,
__u8 QMCR_Value)
{
int result;
__u16 PortSettings;
PortSettings = (__u16)(QMCR_Value);
dbg("%s(): Port = %d, PortSettings = 0x%x", __func__,
Uart_Number, PortSettings);
result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_GET_SET_QMCR, 0x40, PortSettings,
(__u16)Uart_Number, NULL, 0, 5000);
return result;
}
static int port_paranoia_check(struct usb_serial_port *port,
const char *function)
{
if (!port) {
dbg("%s - port == NULL", function);
return -1;
}
if (!port->serial) {
dbg("%s - port->serial == NULL\n", function);
return -1;
}
return 0;
}
static int serial_paranoia_check(struct usb_serial *serial,
const char *function)
{
if (!serial) {
dbg("%s - serial == NULL\n", function);
return -1;
}
if (!serial->type) {
dbg("%s - serial->type == NULL!", function);
return -1;
}
return 0;
}
static inline struct quatech2_port *qt2_get_port_private(struct usb_serial_port
*port)
{
return (struct quatech2_port *)usb_get_serial_port_data(port);
}
static inline void qt2_set_port_private(struct usb_serial_port *port,
struct quatech2_port *data)
{
usb_set_serial_port_data(port, (void *)data);
}
static inline struct quatech2_dev *qt2_get_dev_private(struct usb_serial
*serial)
{
return (struct quatech2_dev *)usb_get_serial_data(serial);
}
static inline void qt2_set_dev_private(struct usb_serial *serial,
struct quatech2_dev *data)
{
usb_set_serial_data(serial, (void *)data);
}
static int qt2_openboxchannel(struct usb_serial *serial, __u16
Uart_Number, struct qt2_status_data *status)
{
int result;
__u16 length;
__u8 Direcion;
unsigned int pipe;
length = sizeof(struct qt2_status_data);
Direcion = USBD_TRANSFER_DIRECTION_IN;
pipe = usb_rcvctrlpipe(serial->dev, 0);
result = usb_control_msg(serial->dev, pipe, QT_OPEN_CLOSE_CHANNEL,
Direcion, 0x00, Uart_Number, status, length, 5000);
return result;
}
static int qt2_closeboxchannel(struct usb_serial *serial, __u16 Uart_Number)
{
int result;
__u8 direcion;
unsigned int pipe;
direcion = USBD_TRANSFER_DIRECTION_OUT;
pipe = usb_sndctrlpipe(serial->dev, 0);
result = usb_control_msg(serial->dev, pipe, QT_OPEN_CLOSE_CHANNEL,
direcion, 0, Uart_Number, NULL, 0, 5000);
return result;
}
/* qt2_conf_uart Issue a SET_UART vendor-spcific request on the default
* control pipe. If successful sets baud rate divisor and LCR value
*/
static int qt2_conf_uart(struct usb_serial *serial, unsigned short Uart_Number,
unsigned short divisor, unsigned char LCR)
{
int result;
unsigned short UartNumandLCR;
UartNumandLCR = (LCR << 8) + Uart_Number;
result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_GET_SET_UART, 0x40, divisor, UartNumandLCR,
NULL, 0, 300);
return result;
}
/** @brief Callback for asynchronous submission of read URBs on bulk in
* endpoints
*
* Registered in qt2_open_port(), used to deal with incomming data
* from the box.
*/
static void qt2_read_bulk_callback(struct urb *urb)
{
/* Get the device pointer (struct usb_serial) back out of the URB */
struct usb_serial *serial = urb->context;
/* get the extra struct for the device */
struct quatech2_dev *dev_extra = qt2_get_dev_private(serial);
/* Get first port structure from the device */
struct usb_serial_port *port0 = serial->port[0];
/* Get the currently active port structure from serial struct */
struct usb_serial_port *active = dev_extra->current_port;
/* get the extra struct for port 0 */
struct quatech2_port *port0_extra = qt2_get_port_private(port0);
/* and for the currently active port */
struct quatech2_port *active_extra = qt2_get_port_private(active);
/* When we finally get to doing some tty stuff, we will need this */
struct tty_struct *tty_st;
unsigned int RxCount; /* the length of the data to process */
unsigned int i; /* loop counter over the data to process */
int result; /* return value cache variable */
bool escapeflag; /* flag set to true if this loop iteration is
* parsing an escape sequence, rather than
* ordinary data */
dbg("%s(): callback running, active port is %d", __func__,
active->number);
if (urb->status) {
/* read didn't go well */
dev_extra->ReadBulkStopped = true;
dbg("%s(): nonzero bulk read status received: %d",
__func__, urb->status);
return;
}
/* inline port_sofrint() here */
if (port_paranoia_check(port0, __func__) != 0) {
dbg("%s - port_paranoia_check on port0 failed, exiting\n",
__func__);
return;
}
if (port_paranoia_check(active, __func__) != 0) {
dbg("%s - port_paranoia_check on current_port "
"failed, exiting", __func__);
return;
}
/* This single callback function has to do for all the ports on
* the device. Data being read up the USB can contain certain
* escape sequences which are used to communicate out-of-band
* information from the serial port in-band over the USB.
* These escapes include sending modem and flow control line
* status, and switching the port. The concept of a "Current Port"
* is used, which is where data is going until a port change
* escape seqence is received. This Current Port is kept between
* callbacks so that when this function enters we know which the
* currently active port is and can get to work right away without
* the box having to send repeat escape sequences (anyway, how
* would it know to do so?).
*/
if (active_extra->close_pending == true) {
/* We are closing , stop reading */
dbg("%s - (active->close_pending == true", __func__);
if (dev_extra->open_ports <= 0) {
/* If this is the only port left open - stop the
* bulk read */
dev_extra->ReadBulkStopped = true;
dbg("%s - (ReadBulkStopped == true;", __func__);
return;
}
}
/*
* RxHolding is asserted by throttle, if we assert it, we're not
* receiving any more characters and let the box handle the flow
* control
*/
if ((port0_extra->RxHolding == true) &&
(serial->dev->descriptor.idProduct == QUATECH_SSU2_100)) {
/* single port device, input is already stopped, so we don't
* need any more input data */
dev_extra->ReadBulkStopped = true;
return;
}
/* finally, we are in a situation where we might consider the data
* that is contained within the URB, and what to do about it.
* This is likely to involved communicating up to the TTY layer, so
* we will need to get hold of the tty for the port we are currently
* dealing with */
/* active is a usb_serial_port. It has a member port which is a
* tty_port. From this we get a tty_struct pointer which is what we
* actually wanted, and keep it on tty_st */
tty_st = tty_port_tty_get(&active->port);
if (!tty_st) {
dbg("%s - bad tty pointer - exiting", __func__);
return;
}
RxCount = urb->actual_length; /* grab length of data handy */
if (RxCount) {
/* skip all this if no data to process */
for (i = 0; i < RxCount ; ++i) {
/* Look ahead code here -works on several bytes at onc*/
if ((i <= (RxCount - 3)) && (THISCHAR == 0x1b)
&& (NEXTCHAR == 0x1b)) {
/* we are in an escape sequence, type
* determined by the 3rd char */
escapeflag = false;
switch (THIRDCHAR) {
case 0x00:
/* Line status change 4th byte must
* follow */
if (i > (RxCount - 4)) {
dbg("Illegal escape sequences "
"in received data");
break;
}
qt2_process_line_status(active,
FOURTHCHAR);
i += 3;
escapeflag = true;
break;
case 0x01:
/* Modem status status change 4th byte
* must follow */
if (i > (RxCount - 4)) {
dbg("Illegal escape sequences "
"in received data");
break;
}
qt2_process_modem_status(active,
FOURTHCHAR);
i += 3;
escapeflag = true;
break;
case 0x02:
/* xmit hold empty 4th byte
* must follow */
if (i > (RxCount - 4)) {
dbg("Illegal escape sequences "
"in received data");
break;
}
qt2_process_xmit_empty(active,
FOURTHCHAR, FIFTHCHAR);
i += 4;
escapeflag = true;
break;
case 0x03:
/* Port number change 4th byte
* must follow */
if (i > (RxCount - 4)) {
dbg("Illegal escape sequences "
"in received data");
break;
}
/* Port change. If port open push
* current data up to tty layer */
if (active_extra->open_count > 0)
tty_flip_buffer_push(tty_st);
dbg("Port Change: new port = %d",
FOURTHCHAR);
qt2_process_port_change(active,
FOURTHCHAR);
i += 3;
escapeflag = true;
/* having changed port, the pointers for
* the currently active port are all out
* of date and need updating */
active = dev_extra->current_port;
active_extra =
qt2_get_port_private(active);
tty_st = tty_port_tty_get(
&active->port);
break;
case 0x04:
/* Recv flush 3rd byte must
* follow */
if (i > (RxCount - 3)) {
dbg("Illegal escape sequences "
"in received data");
break;
}
qt2_process_rcv_flush(active);
i += 2;
escapeflag = true;
break;
case 0x05:
/* xmit flush 3rd byte must follow */
if (i > (RxCount - 3)) {
dbg("Illegal escape sequences "
"in received data");
break;
}
qt2_process_xmit_flush(active);
i += 2;
escapeflag = true;
break;
case 0xff:
dbg("No status sequence");
qt2_process_rx_char(active, THISCHAR);
qt2_process_rx_char(active, NEXTCHAR);
i += 2;
break;
default:
qt2_process_rx_char(active, THISCHAR);
i += 1;
break;
} /*end switch*/
if (escapeflag == true)
continue;
/* if we did an escape char, we don't need
* to mess around pushing data through the
* tty layer, and can go round again */
} /*endif*/
if (tty_st && urb->actual_length) {
tty_buffer_request_room(tty_st, 1);
tty_insert_flip_string(tty_st, &(
(unsigned char *)
(urb->transfer_buffer)
)[i], 1);
}
} /*endfor*/
tty_flip_buffer_push(tty_st);
} /*endif*/
/* at this point we have complete dealing with the data for this
* callback. All we have to do now is to start the async read process
* back off again. */
usb_fill_bulk_urb(port0->read_urb, serial->dev,
usb_rcvbulkpipe(serial->dev, port0->bulk_in_endpointAddress),
port0->bulk_in_buffer, port0->bulk_in_size,
qt2_read_bulk_callback, serial);
result = usb_submit_urb(port0->read_urb, GFP_ATOMIC);
if (result) {
dbg("%s(): failed resubmitting read urb, error %d",
__func__, result);
} else {
dbg("%s() successfully resubmitted read urb", __func__);
if (tty_st && RxCount) {
/* if some inbound data was processed, then
* we need to push that through the tty layer
*/
tty_flip_buffer_push(tty_st);
tty_schedule_flip(tty_st);
}
}
/* cribbed from serqt_usb2 driver, but not sure which work needs
* scheduling - port0 or currently active port? */
/* schedule_work(&port->work); */
dbg("%s() completed", __func__);
return;
}
/** @brief Callback for asynchronous submission of write URBs on bulk in
* endpoints
*
* Registered in qt2_write(), used to deal with outgoing data
* to the box.
*/
static void qt2_write_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = (struct usb_serial_port *)urb->context;
struct usb_serial *serial = port->serial;
dbg("%s(): port %d", __func__, port->number);
if (!serial) {
dbg("%s(): bad serial pointer, exiting", __func__);
return;
}
if (urb->status) {
dbg("%s(): nonzero write bulk status received: %d",
__func__, urb->status);
return;
}
/* FIXME What is supposed to be going on here?
* does this actually do anything useful, and should it?
*/
/*port_softint((void *) serial); commented in vendor driver */
schedule_work(&port->work);
dbg("%s(): port %d exit", __func__, port->number);
return;
}
static void qt2_process_line_status(struct usb_serial_port *port,
unsigned char LineStatus)
{
/* obtain the private structure for the port */
struct quatech2_port *port_extra = qt2_get_port_private(port);
port_extra->shadowLSR = LineStatus & (QT2_SERIAL_LSR_OE |
QT2_SERIAL_LSR_PE | QT2_SERIAL_LSR_FE | QT2_SERIAL_LSR_BI);
}
static void qt2_process_modem_status(struct usb_serial_port *port,
unsigned char ModemStatus)
{
/* obtain the private structure for the port */
struct quatech2_port *port_extra = qt2_get_port_private(port);
port_extra->shadowMSR = ModemStatus;
wake_up_interruptible(&port_extra->wait);
/* this wakes up the otherwise indefinitely waiting code for
* the TIOCMIWAIT ioctl, so that it can notice that
* port_extra->shadowMSR has changed and the ioctl needs to return.
*/
}
static void qt2_process_xmit_empty(struct usb_serial_port *port,
unsigned char fourth_char, unsigned char fifth_char)
{
int byte_count;
/* obtain the private structure for the port */
struct quatech2_port *port_extra = qt2_get_port_private(port);
byte_count = (int)(fifth_char * 16);
byte_count += (int)fourth_char;
/* byte_count indicates how many bytes the device has written out. This
* message appears to occur regularly, and is used in the vendor driver
* to keep track of the fill state of the port transmit buffer */
port_extra->tx_pending_bytes -= byte_count;
/* reduce the stored data queue length by the known number of bytes
* sent */
dbg("port %d: %d bytes reported sent, %d still pending", port->number,
byte_count, port_extra->tx_pending_bytes);
/*port_extra->xmit_fifo_room_bytes = FIFO_DEPTH; ???*/
}
static void qt2_process_port_change(struct usb_serial_port *port,
unsigned char New_Current_Port)
{
/* obtain the parent usb serial device structure */
struct usb_serial *serial = port->serial;
/* obtain the private structure for the device */
struct quatech2_dev *dev_extra = qt2_get_dev_private(serial);
dev_extra->current_port = serial->port[New_Current_Port];
/* what should I do with this? commented out in upstream
* driver */
/*schedule_work(&port->work);*/
}
static void qt2_process_rcv_flush(struct usb_serial_port *port)
{
/* obtain the private structure for the port */
struct quatech2_port *port_extra = qt2_get_port_private(port);
port_extra->rcv_flush = true;
}
static void qt2_process_xmit_flush(struct usb_serial_port *port)
{
/* obtain the private structure for the port */
struct quatech2_port *port_extra = qt2_get_port_private(port);
port_extra->xmit_flush = true;
}
static void qt2_process_rx_char(struct usb_serial_port *port,
unsigned char data)
{
/* get the tty_struct for this port */
struct tty_struct *tty = tty_port_tty_get(&(port->port));
/* get the URB with the data in to push */
struct urb *urb = port->serial->port[0]->read_urb;
if (tty && urb->actual_length) {
tty_buffer_request_room(tty, 1);
tty_insert_flip_string(tty, &data, 1);
/* should this be commented out here? */
/*tty_flip_buffer_push(tty);*/
}
}
/** @brief Retrieve the value of a register from the device
*
* Issues a GET_REGISTER vendor-spcific request over the USB control
* pipe to obtain a value back from a specific register on a specific
* UART
* @param serial Serial device handle to access the device through
* @param uart_number Which UART the value is wanted from
* @param register_num Which register to read the value from
* @param pValue Pointer to somewhere to put the retrieved value
*/
static int qt2_box_get_register(struct usb_serial *serial,
unsigned char uart_number, unsigned short register_num,
__u8 *pValue)
{
int result;
result = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
QT2_GET_SET_REGISTER, 0xC0, register_num,
uart_number, (void *)pValue, sizeof(*pValue), 300);
return result;
}
/** qt2_box_set_register
* Issue a SET_REGISTER vendor-specific request on the default control pipe
*/
static int qt2_box_set_register(struct usb_serial *serial,
unsigned short Uart_Number, unsigned short Register_Num,
unsigned short Value)
{
int result;
unsigned short reg_and_byte;
reg_and_byte = Value;
reg_and_byte = reg_and_byte << 8;
reg_and_byte = reg_and_byte + Register_Num;
result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_GET_SET_REGISTER, 0x40, reg_and_byte,
Uart_Number, NULL, 0, 300);
return result;
}
/** qt2_boxsetuart - Issue a SET_UART vendor-spcific request on the default
* control pipe. If successful sets baud rate divisor and LCR value.
*/
static int qt2_boxsetuart(struct usb_serial *serial, unsigned short Uart_Number,
unsigned short default_divisor, unsigned char default_LCR)
{
unsigned short UartNumandLCR;
UartNumandLCR = (default_LCR << 8) + Uart_Number;
return usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_GET_SET_UART, 0x40, default_divisor, UartNumandLCR,
NULL, 0, 300);
}
/** qt2_boxsethw_flowctl - Turn hardware (RTS/CTS) flow control on and off for
* a hardware UART.
*/
static int qt2_boxsethw_flowctl(struct usb_serial *serial,
unsigned int UartNumber, bool bSet)
{
__u8 MCR_Value = 0;
__u8 MSR_Value = 0;
__u16 MOUT_Value = 0;
if (bSet == true) {
MCR_Value = QT2_SERIAL_MCR_RTS;
/* flow control, box will clear RTS line to prevent remote
* device from transmitting more chars */
} else {
/* no flow control to remote device */
MCR_Value = 0;
}
MOUT_Value = MCR_Value << 8;
if (bSet == true) {
MSR_Value = QT2_SERIAL_MSR_CTS;
/* flow control on, box will inhibit tx data if CTS line is
* asserted */
} else {
/* Box will not inhibit tx data due to CTS line */
MSR_Value = 0;
}
MOUT_Value |= MSR_Value;
return usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_HW_FLOW_CONTROL_MASK, 0x40, MOUT_Value, UartNumber,
NULL, 0, 300);
}
/** qt2_boxsetsw_flowctl - Turn software (XON/XOFF) flow control on for
* a hardware UART, and set the XON and XOFF characters.
*/
static int qt2_boxsetsw_flowctl(struct usb_serial *serial, __u16 UartNumber,
unsigned char stop_char, unsigned char start_char)
{
__u16 nSWflowout;
nSWflowout = start_char << 8;
nSWflowout = (unsigned short)stop_char;
return usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_SW_FLOW_CONTROL_MASK, 0x40, nSWflowout, UartNumber,
NULL, 0, 300);
}
/** qt2_boxunsetsw_flowctl - Turn software (XON/XOFF) flow control off for
* a hardware UART.
*/
static int qt2_boxunsetsw_flowctl(struct usb_serial *serial, __u16 UartNumber)
{
return usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_SW_FLOW_CONTROL_DISABLE, 0x40, 0, UartNumber, NULL,
0, 300);
}
/**
* qt2_boxstoprx - Start and stop reception of data by the FPGA UART in
* response to requests from the tty layer
* @serial: pointer to the usb_serial structure for the parent device
* @uart_number: which UART on the device we are addressing
* @stop: Whether to start or stop data reception. Set to 1 to stop data being
* received, and to 0 to start it being received.
*/
static int qt2_boxstoprx(struct usb_serial *serial, unsigned short uart_number,
unsigned short stop)
{
return usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
QT2_STOP_RECEIVE, 0x40, stop, uart_number, NULL, 0, 300);
}
/*
* last things in file: stuff to register this driver into the generic
* USB serial framework.
*/
static struct usb_serial_driver quatech2_device = {
.driver = {
.owner = THIS_MODULE,
.name = "quatech_usb2",
},
.description = DRIVER_DESC,
.usb_driver = &quausb2_usb_driver,
.id_table = quausb2_id_table,
.num_ports = 8,
.open = qt2_open,
.close = qt2_close,
.write = qt2_write,
.write_room = qt2_write_room,
.chars_in_buffer = qt2_chars_in_buffer,
.throttle = qt2_throttle,
.unthrottle = qt2_unthrottle,
.calc_num_ports = qt2_calc_num_ports,
.ioctl = qt2_ioctl,
.set_termios = qt2_set_termios,
.break_ctl = qt2_break,
.tiocmget = qt2_tiocmget,
.tiocmset = qt2_tiocmset,
.attach = qt2_attach,
.release = qt2_release,
.read_bulk_callback = qt2_read_bulk_callback,
.write_bulk_callback = qt2_write_bulk_callback,
};
static int __init quausb2_usb_init(void)
{
int retval;
dbg("%s\n", __func__);
/* register with usb-serial */
retval = usb_serial_register(&quatech2_device);
if (retval)
goto failed_usb_serial_register;
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
/* register with usb */
retval = usb_register(&quausb2_usb_driver);
if (retval == 0)
return 0;
/* if we're here, usb_register() failed */
usb_serial_deregister(&quatech2_device);
failed_usb_serial_register:
return retval;
}
static void __exit quausb2_usb_exit(void)
{
usb_deregister(&quausb2_usb_driver);
usb_serial_deregister(&quatech2_device);
}
module_init(quausb2_usb_init);
module_exit(quausb2_usb_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
| gpl-2.0 |
pinkflozd/android_kernel_motorola_falcon | drivers/net/ethernet/intel/e1000e/netdev.c | 721 | 185840 | /*******************************************************************************
Intel PRO/1000 Linux 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:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/interrupt.h>
#include <linux/tcp.h>
#include <linux/ipv6.h>
#include <linux/slab.h>
#include <net/checksum.h>
#include <net/ip6_checksum.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include <linux/cpu.h>
#include <linux/smp.h>
#include <linux/pm_qos.h>
#include <linux/pm_runtime.h>
#include <linux/aer.h>
#include <linux/prefetch.h>
#include "e1000.h"
#define DRV_EXTRAVERSION "-k"
#define DRV_VERSION "1.9.5" DRV_EXTRAVERSION
char e1000e_driver_name[] = "e1000e";
const char e1000e_driver_version[] = DRV_VERSION;
#define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV|NETIF_MSG_PROBE|NETIF_MSG_LINK)
static int debug = -1;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
static void e1000e_disable_aspm(struct pci_dev *pdev, u16 state);
static const struct e1000_info *e1000_info_tbl[] = {
[board_82571] = &e1000_82571_info,
[board_82572] = &e1000_82572_info,
[board_82573] = &e1000_82573_info,
[board_82574] = &e1000_82574_info,
[board_82583] = &e1000_82583_info,
[board_80003es2lan] = &e1000_es2_info,
[board_ich8lan] = &e1000_ich8_info,
[board_ich9lan] = &e1000_ich9_info,
[board_ich10lan] = &e1000_ich10_info,
[board_pchlan] = &e1000_pch_info,
[board_pch2lan] = &e1000_pch2_info,
};
struct e1000_reg_info {
u32 ofs;
char *name;
};
#define E1000_RDFH 0x02410 /* Rx Data FIFO Head - RW */
#define E1000_RDFT 0x02418 /* Rx Data FIFO Tail - RW */
#define E1000_RDFHS 0x02420 /* Rx Data FIFO Head Saved - RW */
#define E1000_RDFTS 0x02428 /* Rx Data FIFO Tail Saved - RW */
#define E1000_RDFPC 0x02430 /* Rx Data FIFO Packet Count - RW */
#define E1000_TDFH 0x03410 /* Tx Data FIFO Head - RW */
#define E1000_TDFT 0x03418 /* Tx Data FIFO Tail - RW */
#define E1000_TDFHS 0x03420 /* Tx Data FIFO Head Saved - RW */
#define E1000_TDFTS 0x03428 /* Tx Data FIFO Tail Saved - RW */
#define E1000_TDFPC 0x03430 /* Tx Data FIFO Packet Count - RW */
static const struct e1000_reg_info e1000_reg_info_tbl[] = {
/* General Registers */
{E1000_CTRL, "CTRL"},
{E1000_STATUS, "STATUS"},
{E1000_CTRL_EXT, "CTRL_EXT"},
/* Interrupt Registers */
{E1000_ICR, "ICR"},
/* Rx Registers */
{E1000_RCTL, "RCTL"},
{E1000_RDLEN, "RDLEN"},
{E1000_RDH, "RDH"},
{E1000_RDT, "RDT"},
{E1000_RDTR, "RDTR"},
{E1000_RXDCTL(0), "RXDCTL"},
{E1000_ERT, "ERT"},
{E1000_RDBAL, "RDBAL"},
{E1000_RDBAH, "RDBAH"},
{E1000_RDFH, "RDFH"},
{E1000_RDFT, "RDFT"},
{E1000_RDFHS, "RDFHS"},
{E1000_RDFTS, "RDFTS"},
{E1000_RDFPC, "RDFPC"},
/* Tx Registers */
{E1000_TCTL, "TCTL"},
{E1000_TDBAL, "TDBAL"},
{E1000_TDBAH, "TDBAH"},
{E1000_TDLEN, "TDLEN"},
{E1000_TDH, "TDH"},
{E1000_TDT, "TDT"},
{E1000_TIDV, "TIDV"},
{E1000_TXDCTL(0), "TXDCTL"},
{E1000_TADV, "TADV"},
{E1000_TARC(0), "TARC"},
{E1000_TDFH, "TDFH"},
{E1000_TDFT, "TDFT"},
{E1000_TDFHS, "TDFHS"},
{E1000_TDFTS, "TDFTS"},
{E1000_TDFPC, "TDFPC"},
/* List Terminator */
{0, NULL}
};
/*
* e1000_regdump - register printout routine
*/
static void e1000_regdump(struct e1000_hw *hw, struct e1000_reg_info *reginfo)
{
int n = 0;
char rname[16];
u32 regs[8];
switch (reginfo->ofs) {
case E1000_RXDCTL(0):
for (n = 0; n < 2; n++)
regs[n] = __er32(hw, E1000_RXDCTL(n));
break;
case E1000_TXDCTL(0):
for (n = 0; n < 2; n++)
regs[n] = __er32(hw, E1000_TXDCTL(n));
break;
case E1000_TARC(0):
for (n = 0; n < 2; n++)
regs[n] = __er32(hw, E1000_TARC(n));
break;
default:
pr_info("%-15s %08x\n",
reginfo->name, __er32(hw, reginfo->ofs));
return;
}
snprintf(rname, 16, "%s%s", reginfo->name, "[0-1]");
pr_info("%-15s %08x %08x\n", rname, regs[0], regs[1]);
}
/*
* e1000e_dump - Print registers, Tx-ring and Rx-ring
*/
static void e1000e_dump(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
struct e1000_reg_info *reginfo;
struct e1000_ring *tx_ring = adapter->tx_ring;
struct e1000_tx_desc *tx_desc;
struct my_u0 {
__le64 a;
__le64 b;
} *u0;
struct e1000_buffer *buffer_info;
struct e1000_ring *rx_ring = adapter->rx_ring;
union e1000_rx_desc_packet_split *rx_desc_ps;
union e1000_rx_desc_extended *rx_desc;
struct my_u1 {
__le64 a;
__le64 b;
__le64 c;
__le64 d;
} *u1;
u32 staterr;
int i = 0;
if (!netif_msg_hw(adapter))
return;
/* Print netdevice Info */
if (netdev) {
dev_info(&adapter->pdev->dev, "Net device Info\n");
pr_info("Device Name state trans_start last_rx\n");
pr_info("%-15s %016lX %016lX %016lX\n",
netdev->name, netdev->state, netdev->trans_start,
netdev->last_rx);
}
/* Print Registers */
dev_info(&adapter->pdev->dev, "Register Dump\n");
pr_info(" Register Name Value\n");
for (reginfo = (struct e1000_reg_info *)e1000_reg_info_tbl;
reginfo->name; reginfo++) {
e1000_regdump(hw, reginfo);
}
/* Print Tx Ring Summary */
if (!netdev || !netif_running(netdev))
return;
dev_info(&adapter->pdev->dev, "Tx Ring Summary\n");
pr_info("Queue [NTU] [NTC] [bi(ntc)->dma ] leng ntw timestamp\n");
buffer_info = &tx_ring->buffer_info[tx_ring->next_to_clean];
pr_info(" %5d %5X %5X %016llX %04X %3X %016llX\n",
0, tx_ring->next_to_use, tx_ring->next_to_clean,
(unsigned long long)buffer_info->dma,
buffer_info->length,
buffer_info->next_to_watch,
(unsigned long long)buffer_info->time_stamp);
/* Print Tx Ring */
if (!netif_msg_tx_done(adapter))
goto rx_ring_summary;
dev_info(&adapter->pdev->dev, "Tx Ring Dump\n");
/* Transmit Descriptor Formats - DEXT[29] is 0 (Legacy) or 1 (Extended)
*
* Legacy Transmit Descriptor
* +--------------------------------------------------------------+
* 0 | Buffer Address [63:0] (Reserved on Write Back) |
* +--------------------------------------------------------------+
* 8 | Special | CSS | Status | CMD | CSO | Length |
* +--------------------------------------------------------------+
* 63 48 47 36 35 32 31 24 23 16 15 0
*
* Extended Context Descriptor (DTYP=0x0) for TSO or checksum offload
* 63 48 47 40 39 32 31 16 15 8 7 0
* +----------------------------------------------------------------+
* 0 | TUCSE | TUCS0 | TUCSS | IPCSE | IPCS0 | IPCSS |
* +----------------------------------------------------------------+
* 8 | MSS | HDRLEN | RSV | STA | TUCMD | DTYP | PAYLEN |
* +----------------------------------------------------------------+
* 63 48 47 40 39 36 35 32 31 24 23 20 19 0
*
* Extended Data Descriptor (DTYP=0x1)
* +----------------------------------------------------------------+
* 0 | Buffer Address [63:0] |
* +----------------------------------------------------------------+
* 8 | VLAN tag | POPTS | Rsvd | Status | Command | DTYP | DTALEN |
* +----------------------------------------------------------------+
* 63 48 47 40 39 36 35 32 31 24 23 20 19 0
*/
pr_info("Tl[desc] [address 63:0 ] [SpeCssSCmCsLen] [bi->dma ] leng ntw timestamp bi->skb <-- Legacy format\n");
pr_info("Tc[desc] [Ce CoCsIpceCoS] [MssHlRSCm0Plen] [bi->dma ] leng ntw timestamp bi->skb <-- Ext Context format\n");
pr_info("Td[desc] [address 63:0 ] [VlaPoRSCm1Dlen] [bi->dma ] leng ntw timestamp bi->skb <-- Ext Data format\n");
for (i = 0; tx_ring->desc && (i < tx_ring->count); i++) {
const char *next_desc;
tx_desc = E1000_TX_DESC(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
u0 = (struct my_u0 *)tx_desc;
if (i == tx_ring->next_to_use && i == tx_ring->next_to_clean)
next_desc = " NTC/U";
else if (i == tx_ring->next_to_use)
next_desc = " NTU";
else if (i == tx_ring->next_to_clean)
next_desc = " NTC";
else
next_desc = "";
pr_info("T%c[0x%03X] %016llX %016llX %016llX %04X %3X %016llX %p%s\n",
(!(le64_to_cpu(u0->b) & (1 << 29)) ? 'l' :
((le64_to_cpu(u0->b) & (1 << 20)) ? 'd' : 'c')),
i,
(unsigned long long)le64_to_cpu(u0->a),
(unsigned long long)le64_to_cpu(u0->b),
(unsigned long long)buffer_info->dma,
buffer_info->length, buffer_info->next_to_watch,
(unsigned long long)buffer_info->time_stamp,
buffer_info->skb, next_desc);
if (netif_msg_pktdata(adapter) && buffer_info->dma != 0)
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS,
16, 1, phys_to_virt(buffer_info->dma),
buffer_info->length, true);
}
/* Print Rx Ring Summary */
rx_ring_summary:
dev_info(&adapter->pdev->dev, "Rx Ring Summary\n");
pr_info("Queue [NTU] [NTC]\n");
pr_info(" %5d %5X %5X\n",
0, rx_ring->next_to_use, rx_ring->next_to_clean);
/* Print Rx Ring */
if (!netif_msg_rx_status(adapter))
return;
dev_info(&adapter->pdev->dev, "Rx Ring Dump\n");
switch (adapter->rx_ps_pages) {
case 1:
case 2:
case 3:
/* [Extended] Packet Split Receive Descriptor Format
*
* +-----------------------------------------------------+
* 0 | Buffer Address 0 [63:0] |
* +-----------------------------------------------------+
* 8 | Buffer Address 1 [63:0] |
* +-----------------------------------------------------+
* 16 | Buffer Address 2 [63:0] |
* +-----------------------------------------------------+
* 24 | Buffer Address 3 [63:0] |
* +-----------------------------------------------------+
*/
pr_info("R [desc] [buffer 0 63:0 ] [buffer 1 63:0 ] [buffer 2 63:0 ] [buffer 3 63:0 ] [bi->dma ] [bi->skb] <-- Ext Pkt Split format\n");
/* [Extended] Receive Descriptor (Write-Back) Format
*
* 63 48 47 32 31 13 12 8 7 4 3 0
* +------------------------------------------------------+
* 0 | Packet | IP | Rsvd | MRQ | Rsvd | MRQ RSS |
* | Checksum | Ident | | Queue | | Type |
* +------------------------------------------------------+
* 8 | VLAN Tag | Length | Extended Error | Extended Status |
* +------------------------------------------------------+
* 63 48 47 32 31 20 19 0
*/
pr_info("RWB[desc] [ck ipid mrqhsh] [vl l0 ee es] [ l3 l2 l1 hs] [reserved ] ---------------- [bi->skb] <-- Ext Rx Write-Back format\n");
for (i = 0; i < rx_ring->count; i++) {
const char *next_desc;
buffer_info = &rx_ring->buffer_info[i];
rx_desc_ps = E1000_RX_DESC_PS(*rx_ring, i);
u1 = (struct my_u1 *)rx_desc_ps;
staterr =
le32_to_cpu(rx_desc_ps->wb.middle.status_error);
if (i == rx_ring->next_to_use)
next_desc = " NTU";
else if (i == rx_ring->next_to_clean)
next_desc = " NTC";
else
next_desc = "";
if (staterr & E1000_RXD_STAT_DD) {
/* Descriptor Done */
pr_info("%s[0x%03X] %016llX %016llX %016llX %016llX ---------------- %p%s\n",
"RWB", i,
(unsigned long long)le64_to_cpu(u1->a),
(unsigned long long)le64_to_cpu(u1->b),
(unsigned long long)le64_to_cpu(u1->c),
(unsigned long long)le64_to_cpu(u1->d),
buffer_info->skb, next_desc);
} else {
pr_info("%s[0x%03X] %016llX %016llX %016llX %016llX %016llX %p%s\n",
"R ", i,
(unsigned long long)le64_to_cpu(u1->a),
(unsigned long long)le64_to_cpu(u1->b),
(unsigned long long)le64_to_cpu(u1->c),
(unsigned long long)le64_to_cpu(u1->d),
(unsigned long long)buffer_info->dma,
buffer_info->skb, next_desc);
if (netif_msg_pktdata(adapter))
print_hex_dump(KERN_INFO, "",
DUMP_PREFIX_ADDRESS, 16, 1,
phys_to_virt(buffer_info->dma),
adapter->rx_ps_bsize0, true);
}
}
break;
default:
case 0:
/* Extended Receive Descriptor (Read) Format
*
* +-----------------------------------------------------+
* 0 | Buffer Address [63:0] |
* +-----------------------------------------------------+
* 8 | Reserved |
* +-----------------------------------------------------+
*/
pr_info("R [desc] [buf addr 63:0 ] [reserved 63:0 ] [bi->dma ] [bi->skb] <-- Ext (Read) format\n");
/* Extended Receive Descriptor (Write-Back) Format
*
* 63 48 47 32 31 24 23 4 3 0
* +------------------------------------------------------+
* | RSS Hash | | | |
* 0 +-------------------+ Rsvd | Reserved | MRQ RSS |
* | Packet | IP | | | Type |
* | Checksum | Ident | | | |
* +------------------------------------------------------+
* 8 | VLAN Tag | Length | Extended Error | Extended Status |
* +------------------------------------------------------+
* 63 48 47 32 31 20 19 0
*/
pr_info("RWB[desc] [cs ipid mrq] [vt ln xe xs] [bi->skb] <-- Ext (Write-Back) format\n");
for (i = 0; i < rx_ring->count; i++) {
const char *next_desc;
buffer_info = &rx_ring->buffer_info[i];
rx_desc = E1000_RX_DESC_EXT(*rx_ring, i);
u1 = (struct my_u1 *)rx_desc;
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
if (i == rx_ring->next_to_use)
next_desc = " NTU";
else if (i == rx_ring->next_to_clean)
next_desc = " NTC";
else
next_desc = "";
if (staterr & E1000_RXD_STAT_DD) {
/* Descriptor Done */
pr_info("%s[0x%03X] %016llX %016llX ---------------- %p%s\n",
"RWB", i,
(unsigned long long)le64_to_cpu(u1->a),
(unsigned long long)le64_to_cpu(u1->b),
buffer_info->skb, next_desc);
} else {
pr_info("%s[0x%03X] %016llX %016llX %016llX %p%s\n",
"R ", i,
(unsigned long long)le64_to_cpu(u1->a),
(unsigned long long)le64_to_cpu(u1->b),
(unsigned long long)buffer_info->dma,
buffer_info->skb, next_desc);
if (netif_msg_pktdata(adapter))
print_hex_dump(KERN_INFO, "",
DUMP_PREFIX_ADDRESS, 16,
1,
phys_to_virt
(buffer_info->dma),
adapter->rx_buffer_len,
true);
}
}
}
}
/**
* e1000_desc_unused - calculate if we have unused descriptors
**/
static int e1000_desc_unused(struct e1000_ring *ring)
{
if (ring->next_to_clean > ring->next_to_use)
return ring->next_to_clean - ring->next_to_use - 1;
return ring->count + ring->next_to_clean - ring->next_to_use - 1;
}
/**
* e1000_receive_skb - helper function to handle Rx indications
* @adapter: board private structure
* @status: descriptor status field as written by hardware
* @vlan: descriptor vlan field as written by hardware (no le/be conversion)
* @skb: pointer to sk_buff to be indicated to stack
**/
static void e1000_receive_skb(struct e1000_adapter *adapter,
struct net_device *netdev, struct sk_buff *skb,
u8 status, __le16 vlan)
{
u16 tag = le16_to_cpu(vlan);
skb->protocol = eth_type_trans(skb, netdev);
if (status & E1000_RXD_STAT_VP)
__vlan_hwaccel_put_tag(skb, tag);
napi_gro_receive(&adapter->napi, skb);
}
/**
* e1000_rx_checksum - Receive Checksum Offload
* @adapter: board private structure
* @status_err: receive descriptor status and error fields
* @csum: receive descriptor csum field
* @sk_buff: socket buffer with received data
**/
static void e1000_rx_checksum(struct e1000_adapter *adapter, u32 status_err,
struct sk_buff *skb)
{
u16 status = (u16)status_err;
u8 errors = (u8)(status_err >> 24);
skb_checksum_none_assert(skb);
/* Rx checksum disabled */
if (!(adapter->netdev->features & NETIF_F_RXCSUM))
return;
/* Ignore Checksum bit is set */
if (status & E1000_RXD_STAT_IXSM)
return;
/* TCP/UDP checksum error bit or IP checksum error bit is set */
if (errors & (E1000_RXD_ERR_TCPE | E1000_RXD_ERR_IPE)) {
/* let the stack verify checksum errors */
adapter->hw_csum_err++;
return;
}
/* TCP/UDP Checksum has not been calculated */
if (!(status & (E1000_RXD_STAT_TCPCS | E1000_RXD_STAT_UDPCS)))
return;
/* It must be a TCP or UDP packet with a valid checksum */
skb->ip_summed = CHECKSUM_UNNECESSARY;
adapter->hw_csum_good++;
}
/**
* e1000e_update_tail_wa - helper function for e1000e_update_[rt]dt_wa()
* @hw: pointer to the HW structure
* @tail: address of tail descriptor register
* @i: value to write to tail descriptor register
*
* When updating the tail register, the ME could be accessing Host CSR
* registers at the same time. Normally, this is handled in h/w by an
* arbiter but on some parts there is a bug that acknowledges Host accesses
* later than it should which could result in the descriptor register to
* have an incorrect value. Workaround this by checking the FWSM register
* which has bit 24 set while ME is accessing Host CSR registers, wait
* if it is set and try again a number of times.
**/
static inline s32 e1000e_update_tail_wa(struct e1000_hw *hw, void __iomem *tail,
unsigned int i)
{
unsigned int j = 0;
while ((j++ < E1000_ICH_FWSM_PCIM2PCI_COUNT) &&
(er32(FWSM) & E1000_ICH_FWSM_PCIM2PCI))
udelay(50);
writel(i, tail);
if ((j == E1000_ICH_FWSM_PCIM2PCI_COUNT) && (i != readl(tail)))
return E1000_ERR_SWFW_SYNC;
return 0;
}
static void e1000e_update_rdt_wa(struct e1000_ring *rx_ring, unsigned int i)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct e1000_hw *hw = &adapter->hw;
if (e1000e_update_tail_wa(hw, rx_ring->tail, i)) {
u32 rctl = er32(RCTL);
ew32(RCTL, rctl & ~E1000_RCTL_EN);
e_err("ME firmware caused invalid RDT - resetting\n");
schedule_work(&adapter->reset_task);
}
}
static void e1000e_update_tdt_wa(struct e1000_ring *tx_ring, unsigned int i)
{
struct e1000_adapter *adapter = tx_ring->adapter;
struct e1000_hw *hw = &adapter->hw;
if (e1000e_update_tail_wa(hw, tx_ring->tail, i)) {
u32 tctl = er32(TCTL);
ew32(TCTL, tctl & ~E1000_TCTL_EN);
e_err("ME firmware caused invalid TDT - resetting\n");
schedule_work(&adapter->reset_task);
}
}
/**
* e1000_alloc_rx_buffers - Replace used receive buffers
* @rx_ring: Rx descriptor ring
**/
static void e1000_alloc_rx_buffers(struct e1000_ring *rx_ring,
int cleaned_count, gfp_t gfp)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
union e1000_rx_desc_extended *rx_desc;
struct e1000_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz = adapter->rx_buffer_len;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
while (cleaned_count--) {
skb = buffer_info->skb;
if (skb) {
skb_trim(skb, 0);
goto map_skb;
}
skb = __netdev_alloc_skb_ip_align(netdev, bufsz, gfp);
if (!skb) {
/* Better luck next round */
adapter->alloc_rx_buff_failed++;
break;
}
buffer_info->skb = skb;
map_skb:
buffer_info->dma = dma_map_single(&pdev->dev, skb->data,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma)) {
dev_err(&pdev->dev, "Rx DMA map failed\n");
adapter->rx_dma_failed++;
break;
}
rx_desc = E1000_RX_DESC_EXT(*rx_ring, i);
rx_desc->read.buffer_addr = cpu_to_le64(buffer_info->dma);
if (unlikely(!(i & (E1000_RX_BUFFER_WRITE - 1)))) {
/*
* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64).
*/
wmb();
if (adapter->flags2 & FLAG2_PCIM2PCI_ARBITER_WA)
e1000e_update_rdt_wa(rx_ring, i);
else
writel(i, rx_ring->tail);
}
i++;
if (i == rx_ring->count)
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
rx_ring->next_to_use = i;
}
/**
* e1000_alloc_rx_buffers_ps - Replace used receive buffers; packet split
* @rx_ring: Rx descriptor ring
**/
static void e1000_alloc_rx_buffers_ps(struct e1000_ring *rx_ring,
int cleaned_count, gfp_t gfp)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
union e1000_rx_desc_packet_split *rx_desc;
struct e1000_buffer *buffer_info;
struct e1000_ps_page *ps_page;
struct sk_buff *skb;
unsigned int i, j;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
while (cleaned_count--) {
rx_desc = E1000_RX_DESC_PS(*rx_ring, i);
for (j = 0; j < PS_PAGE_BUFFERS; j++) {
ps_page = &buffer_info->ps_pages[j];
if (j >= adapter->rx_ps_pages) {
/* all unused desc entries get hw null ptr */
rx_desc->read.buffer_addr[j + 1] =
~cpu_to_le64(0);
continue;
}
if (!ps_page->page) {
ps_page->page = alloc_page(gfp);
if (!ps_page->page) {
adapter->alloc_rx_buff_failed++;
goto no_buffers;
}
ps_page->dma = dma_map_page(&pdev->dev,
ps_page->page,
0, PAGE_SIZE,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev,
ps_page->dma)) {
dev_err(&adapter->pdev->dev,
"Rx DMA page map failed\n");
adapter->rx_dma_failed++;
goto no_buffers;
}
}
/*
* Refresh the desc even if buffer_addrs
* didn't change because each write-back
* erases this info.
*/
rx_desc->read.buffer_addr[j + 1] =
cpu_to_le64(ps_page->dma);
}
skb = __netdev_alloc_skb_ip_align(netdev,
adapter->rx_ps_bsize0,
gfp);
if (!skb) {
adapter->alloc_rx_buff_failed++;
break;
}
buffer_info->skb = skb;
buffer_info->dma = dma_map_single(&pdev->dev, skb->data,
adapter->rx_ps_bsize0,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma)) {
dev_err(&pdev->dev, "Rx DMA map failed\n");
adapter->rx_dma_failed++;
/* cleanup skb */
dev_kfree_skb_any(skb);
buffer_info->skb = NULL;
break;
}
rx_desc->read.buffer_addr[0] = cpu_to_le64(buffer_info->dma);
if (unlikely(!(i & (E1000_RX_BUFFER_WRITE - 1)))) {
/*
* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64).
*/
wmb();
if (adapter->flags2 & FLAG2_PCIM2PCI_ARBITER_WA)
e1000e_update_rdt_wa(rx_ring, i << 1);
else
writel(i << 1, rx_ring->tail);
}
i++;
if (i == rx_ring->count)
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
no_buffers:
rx_ring->next_to_use = i;
}
/**
* e1000_alloc_jumbo_rx_buffers - Replace used jumbo receive buffers
* @rx_ring: Rx descriptor ring
* @cleaned_count: number of buffers to allocate this pass
**/
static void e1000_alloc_jumbo_rx_buffers(struct e1000_ring *rx_ring,
int cleaned_count, gfp_t gfp)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
union e1000_rx_desc_extended *rx_desc;
struct e1000_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz = 256 - 16 /* for skb_reserve */;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
while (cleaned_count--) {
skb = buffer_info->skb;
if (skb) {
skb_trim(skb, 0);
goto check_page;
}
skb = __netdev_alloc_skb_ip_align(netdev, bufsz, gfp);
if (unlikely(!skb)) {
/* Better luck next round */
adapter->alloc_rx_buff_failed++;
break;
}
buffer_info->skb = skb;
check_page:
/* allocate a new page if necessary */
if (!buffer_info->page) {
buffer_info->page = alloc_page(gfp);
if (unlikely(!buffer_info->page)) {
adapter->alloc_rx_buff_failed++;
break;
}
}
if (!buffer_info->dma)
buffer_info->dma = dma_map_page(&pdev->dev,
buffer_info->page, 0,
PAGE_SIZE,
DMA_FROM_DEVICE);
rx_desc = E1000_RX_DESC_EXT(*rx_ring, i);
rx_desc->read.buffer_addr = cpu_to_le64(buffer_info->dma);
if (unlikely(++i == rx_ring->count))
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
if (likely(rx_ring->next_to_use != i)) {
rx_ring->next_to_use = i;
if (unlikely(i-- == 0))
i = (rx_ring->count - 1);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
if (adapter->flags2 & FLAG2_PCIM2PCI_ARBITER_WA)
e1000e_update_rdt_wa(rx_ring, i);
else
writel(i, rx_ring->tail);
}
}
static inline void e1000_rx_hash(struct net_device *netdev, __le32 rss,
struct sk_buff *skb)
{
if (netdev->features & NETIF_F_RXHASH)
skb->rxhash = le32_to_cpu(rss);
}
/**
* e1000_clean_rx_irq - Send received data up the network stack
* @rx_ring: Rx descriptor ring
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
static bool e1000_clean_rx_irq(struct e1000_ring *rx_ring, int *work_done,
int work_to_do)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_hw *hw = &adapter->hw;
union e1000_rx_desc_extended *rx_desc, *next_rxd;
struct e1000_buffer *buffer_info, *next_buffer;
u32 length, staterr;
unsigned int i;
int cleaned_count = 0;
bool cleaned = false;
unsigned int total_rx_bytes = 0, total_rx_packets = 0;
i = rx_ring->next_to_clean;
rx_desc = E1000_RX_DESC_EXT(*rx_ring, i);
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
buffer_info = &rx_ring->buffer_info[i];
while (staterr & E1000_RXD_STAT_DD) {
struct sk_buff *skb;
if (*work_done >= work_to_do)
break;
(*work_done)++;
rmb(); /* read descriptor and rx_buffer_info after status DD */
skb = buffer_info->skb;
buffer_info->skb = NULL;
prefetch(skb->data - NET_IP_ALIGN);
i++;
if (i == rx_ring->count)
i = 0;
next_rxd = E1000_RX_DESC_EXT(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
cleaned = true;
cleaned_count++;
dma_unmap_single(&pdev->dev,
buffer_info->dma,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
buffer_info->dma = 0;
length = le16_to_cpu(rx_desc->wb.upper.length);
/*
* !EOP means multiple descriptors were used to store a single
* packet, if that's the case we need to toss it. In fact, we
* need to toss every packet with the EOP bit clear and the
* next frame that _does_ have the EOP bit set, as it is by
* definition only a frame fragment
*/
if (unlikely(!(staterr & E1000_RXD_STAT_EOP)))
adapter->flags2 |= FLAG2_IS_DISCARDING;
if (adapter->flags2 & FLAG2_IS_DISCARDING) {
/* All receives must fit into a single buffer */
e_dbg("Receive packet consumed multiple buffers\n");
/* recycle */
buffer_info->skb = skb;
if (staterr & E1000_RXD_STAT_EOP)
adapter->flags2 &= ~FLAG2_IS_DISCARDING;
goto next_desc;
}
if (unlikely((staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK) &&
!(netdev->features & NETIF_F_RXALL))) {
/* recycle */
buffer_info->skb = skb;
goto next_desc;
}
/* adjust length to remove Ethernet CRC */
if (!(adapter->flags2 & FLAG2_CRC_STRIPPING)) {
/* If configured to store CRC, don't subtract FCS,
* but keep the FCS bytes out of the total_rx_bytes
* counter
*/
if (netdev->features & NETIF_F_RXFCS)
total_rx_bytes -= 4;
else
length -= 4;
}
total_rx_bytes += length;
total_rx_packets++;
/*
* code added for copybreak, this should improve
* performance for small packets with large amounts
* of reassembly being done in the stack
*/
if (length < copybreak) {
struct sk_buff *new_skb =
netdev_alloc_skb_ip_align(netdev, length);
if (new_skb) {
skb_copy_to_linear_data_offset(new_skb,
-NET_IP_ALIGN,
(skb->data -
NET_IP_ALIGN),
(length +
NET_IP_ALIGN));
/* save the skb in buffer_info as good */
buffer_info->skb = skb;
skb = new_skb;
}
/* else just continue with the old one */
}
/* end copybreak code */
skb_put(skb, length);
/* Receive Checksum Offload */
e1000_rx_checksum(adapter, staterr, skb);
e1000_rx_hash(netdev, rx_desc->wb.lower.hi_dword.rss, skb);
e1000_receive_skb(adapter, netdev, skb, staterr,
rx_desc->wb.upper.vlan);
next_desc:
rx_desc->wb.upper.status_error &= cpu_to_le32(~0xFF);
/* return some buffers to hardware, one at a time is too slow */
if (cleaned_count >= E1000_RX_BUFFER_WRITE) {
adapter->alloc_rx_buf(rx_ring, cleaned_count,
GFP_ATOMIC);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
}
rx_ring->next_to_clean = i;
cleaned_count = e1000_desc_unused(rx_ring);
if (cleaned_count)
adapter->alloc_rx_buf(rx_ring, cleaned_count, GFP_ATOMIC);
adapter->total_rx_bytes += total_rx_bytes;
adapter->total_rx_packets += total_rx_packets;
return cleaned;
}
static void e1000_put_txbuf(struct e1000_ring *tx_ring,
struct e1000_buffer *buffer_info)
{
struct e1000_adapter *adapter = tx_ring->adapter;
if (buffer_info->dma) {
if (buffer_info->mapped_as_page)
dma_unmap_page(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
else
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
buffer_info->time_stamp = 0;
}
static void e1000_print_hw_hang(struct work_struct *work)
{
struct e1000_adapter *adapter = container_of(work,
struct e1000_adapter,
print_hang_task);
struct net_device *netdev = adapter->netdev;
struct e1000_ring *tx_ring = adapter->tx_ring;
unsigned int i = tx_ring->next_to_clean;
unsigned int eop = tx_ring->buffer_info[i].next_to_watch;
struct e1000_tx_desc *eop_desc = E1000_TX_DESC(*tx_ring, eop);
struct e1000_hw *hw = &adapter->hw;
u16 phy_status, phy_1000t_status, phy_ext_status;
u16 pci_status;
if (test_bit(__E1000_DOWN, &adapter->state))
return;
if (!adapter->tx_hang_recheck &&
(adapter->flags2 & FLAG2_DMA_BURST)) {
/* May be block on write-back, flush and detect again
* flush pending descriptor writebacks to memory
*/
ew32(TIDV, adapter->tx_int_delay | E1000_TIDV_FPD);
/* execute the writes immediately */
e1e_flush();
/*
* Due to rare timing issues, write to TIDV again to ensure
* the write is successful
*/
ew32(TIDV, adapter->tx_int_delay | E1000_TIDV_FPD);
/* execute the writes immediately */
e1e_flush();
adapter->tx_hang_recheck = true;
return;
}
/* Real hang detected */
adapter->tx_hang_recheck = false;
netif_stop_queue(netdev);
e1e_rphy(hw, PHY_STATUS, &phy_status);
e1e_rphy(hw, PHY_1000T_STATUS, &phy_1000t_status);
e1e_rphy(hw, PHY_EXT_STATUS, &phy_ext_status);
pci_read_config_word(adapter->pdev, PCI_STATUS, &pci_status);
/* detected Hardware unit hang */
e_err("Detected Hardware Unit Hang:\n"
" TDH <%x>\n"
" TDT <%x>\n"
" next_to_use <%x>\n"
" next_to_clean <%x>\n"
"buffer_info[next_to_clean]:\n"
" time_stamp <%lx>\n"
" next_to_watch <%x>\n"
" jiffies <%lx>\n"
" next_to_watch.status <%x>\n"
"MAC Status <%x>\n"
"PHY Status <%x>\n"
"PHY 1000BASE-T Status <%x>\n"
"PHY Extended Status <%x>\n"
"PCI Status <%x>\n",
readl(tx_ring->head),
readl(tx_ring->tail),
tx_ring->next_to_use,
tx_ring->next_to_clean,
tx_ring->buffer_info[eop].time_stamp,
eop,
jiffies,
eop_desc->upper.fields.status,
er32(STATUS),
phy_status,
phy_1000t_status,
phy_ext_status,
pci_status);
}
/**
* e1000_clean_tx_irq - Reclaim resources after transmit completes
* @tx_ring: Tx descriptor ring
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
static bool e1000_clean_tx_irq(struct e1000_ring *tx_ring)
{
struct e1000_adapter *adapter = tx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
struct e1000_tx_desc *tx_desc, *eop_desc;
struct e1000_buffer *buffer_info;
unsigned int i, eop;
unsigned int count = 0;
unsigned int total_tx_bytes = 0, total_tx_packets = 0;
unsigned int bytes_compl = 0, pkts_compl = 0;
i = tx_ring->next_to_clean;
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = E1000_TX_DESC(*tx_ring, eop);
while ((eop_desc->upper.data & cpu_to_le32(E1000_TXD_STAT_DD)) &&
(count < tx_ring->count)) {
bool cleaned = false;
rmb(); /* read buffer_info after eop_desc */
for (; !cleaned; count++) {
tx_desc = E1000_TX_DESC(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
cleaned = (i == eop);
if (cleaned) {
total_tx_packets += buffer_info->segs;
total_tx_bytes += buffer_info->bytecount;
if (buffer_info->skb) {
bytes_compl += buffer_info->skb->len;
pkts_compl++;
}
}
e1000_put_txbuf(tx_ring, buffer_info);
tx_desc->upper.data = 0;
i++;
if (i == tx_ring->count)
i = 0;
}
if (i == tx_ring->next_to_use)
break;
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = E1000_TX_DESC(*tx_ring, eop);
}
tx_ring->next_to_clean = i;
netdev_completed_queue(netdev, pkts_compl, bytes_compl);
#define TX_WAKE_THRESHOLD 32
if (count && netif_carrier_ok(netdev) &&
e1000_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean.
*/
smp_mb();
if (netif_queue_stopped(netdev) &&
!(test_bit(__E1000_DOWN, &adapter->state))) {
netif_wake_queue(netdev);
++adapter->restart_queue;
}
}
if (adapter->detect_tx_hung) {
/*
* Detect a transmit hang in hardware, this serializes the
* check with the clearing of time_stamp and movement of i
*/
adapter->detect_tx_hung = false;
if (tx_ring->buffer_info[i].time_stamp &&
time_after(jiffies, tx_ring->buffer_info[i].time_stamp
+ (adapter->tx_timeout_factor * HZ)) &&
!(er32(STATUS) & E1000_STATUS_TXOFF))
schedule_work(&adapter->print_hang_task);
else
adapter->tx_hang_recheck = false;
}
adapter->total_tx_bytes += total_tx_bytes;
adapter->total_tx_packets += total_tx_packets;
return count < tx_ring->count;
}
/**
* e1000_clean_rx_irq_ps - Send received data up the network stack; packet split
* @rx_ring: Rx descriptor ring
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
static bool e1000_clean_rx_irq_ps(struct e1000_ring *rx_ring, int *work_done,
int work_to_do)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct e1000_hw *hw = &adapter->hw;
union e1000_rx_desc_packet_split *rx_desc, *next_rxd;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_buffer *buffer_info, *next_buffer;
struct e1000_ps_page *ps_page;
struct sk_buff *skb;
unsigned int i, j;
u32 length, staterr;
int cleaned_count = 0;
bool cleaned = false;
unsigned int total_rx_bytes = 0, total_rx_packets = 0;
i = rx_ring->next_to_clean;
rx_desc = E1000_RX_DESC_PS(*rx_ring, i);
staterr = le32_to_cpu(rx_desc->wb.middle.status_error);
buffer_info = &rx_ring->buffer_info[i];
while (staterr & E1000_RXD_STAT_DD) {
if (*work_done >= work_to_do)
break;
(*work_done)++;
skb = buffer_info->skb;
rmb(); /* read descriptor and rx_buffer_info after status DD */
/* in the packet split case this is header only */
prefetch(skb->data - NET_IP_ALIGN);
i++;
if (i == rx_ring->count)
i = 0;
next_rxd = E1000_RX_DESC_PS(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
cleaned = true;
cleaned_count++;
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_ps_bsize0, DMA_FROM_DEVICE);
buffer_info->dma = 0;
/* see !EOP comment in other Rx routine */
if (!(staterr & E1000_RXD_STAT_EOP))
adapter->flags2 |= FLAG2_IS_DISCARDING;
if (adapter->flags2 & FLAG2_IS_DISCARDING) {
e_dbg("Packet Split buffers didn't pick up the full packet\n");
dev_kfree_skb_irq(skb);
if (staterr & E1000_RXD_STAT_EOP)
adapter->flags2 &= ~FLAG2_IS_DISCARDING;
goto next_desc;
}
if (unlikely((staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK) &&
!(netdev->features & NETIF_F_RXALL))) {
dev_kfree_skb_irq(skb);
goto next_desc;
}
length = le16_to_cpu(rx_desc->wb.middle.length0);
if (!length) {
e_dbg("Last part of the packet spanning multiple descriptors\n");
dev_kfree_skb_irq(skb);
goto next_desc;
}
/* Good Receive */
skb_put(skb, length);
{
/*
* this looks ugly, but it seems compiler issues make
* it more efficient than reusing j
*/
int l1 = le16_to_cpu(rx_desc->wb.upper.length[0]);
/*
* page alloc/put takes too long and effects small
* packet throughput, so unsplit small packets and
* save the alloc/put only valid in softirq (napi)
* context to call kmap_*
*/
if (l1 && (l1 <= copybreak) &&
((length + l1) <= adapter->rx_ps_bsize0)) {
u8 *vaddr;
ps_page = &buffer_info->ps_pages[0];
/*
* there is no documentation about how to call
* kmap_atomic, so we can't hold the mapping
* very long
*/
dma_sync_single_for_cpu(&pdev->dev,
ps_page->dma,
PAGE_SIZE,
DMA_FROM_DEVICE);
vaddr = kmap_atomic(ps_page->page);
memcpy(skb_tail_pointer(skb), vaddr, l1);
kunmap_atomic(vaddr);
dma_sync_single_for_device(&pdev->dev,
ps_page->dma,
PAGE_SIZE,
DMA_FROM_DEVICE);
/* remove the CRC */
if (!(adapter->flags2 & FLAG2_CRC_STRIPPING)) {
if (!(netdev->features & NETIF_F_RXFCS))
l1 -= 4;
}
skb_put(skb, l1);
goto copydone;
} /* if */
}
for (j = 0; j < PS_PAGE_BUFFERS; j++) {
length = le16_to_cpu(rx_desc->wb.upper.length[j]);
if (!length)
break;
ps_page = &buffer_info->ps_pages[j];
dma_unmap_page(&pdev->dev, ps_page->dma, PAGE_SIZE,
DMA_FROM_DEVICE);
ps_page->dma = 0;
skb_fill_page_desc(skb, j, ps_page->page, 0, length);
ps_page->page = NULL;
skb->len += length;
skb->data_len += length;
skb->truesize += PAGE_SIZE;
}
/* strip the ethernet crc, problem is we're using pages now so
* this whole operation can get a little cpu intensive
*/
if (!(adapter->flags2 & FLAG2_CRC_STRIPPING)) {
if (!(netdev->features & NETIF_F_RXFCS))
pskb_trim(skb, skb->len - 4);
}
copydone:
total_rx_bytes += skb->len;
total_rx_packets++;
e1000_rx_checksum(adapter, staterr, skb);
e1000_rx_hash(netdev, rx_desc->wb.lower.hi_dword.rss, skb);
if (rx_desc->wb.upper.header_status &
cpu_to_le16(E1000_RXDPS_HDRSTAT_HDRSP))
adapter->rx_hdr_split++;
e1000_receive_skb(adapter, netdev, skb,
staterr, rx_desc->wb.middle.vlan);
next_desc:
rx_desc->wb.middle.status_error &= cpu_to_le32(~0xFF);
buffer_info->skb = NULL;
/* return some buffers to hardware, one at a time is too slow */
if (cleaned_count >= E1000_RX_BUFFER_WRITE) {
adapter->alloc_rx_buf(rx_ring, cleaned_count,
GFP_ATOMIC);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
staterr = le32_to_cpu(rx_desc->wb.middle.status_error);
}
rx_ring->next_to_clean = i;
cleaned_count = e1000_desc_unused(rx_ring);
if (cleaned_count)
adapter->alloc_rx_buf(rx_ring, cleaned_count, GFP_ATOMIC);
adapter->total_rx_bytes += total_rx_bytes;
adapter->total_rx_packets += total_rx_packets;
return cleaned;
}
/**
* e1000_consume_page - helper function
**/
static void e1000_consume_page(struct e1000_buffer *bi, struct sk_buff *skb,
u16 length)
{
bi->page = NULL;
skb->len += length;
skb->data_len += length;
skb->truesize += PAGE_SIZE;
}
/**
* e1000_clean_jumbo_rx_irq - Send received data up the network stack; legacy
* @adapter: board private structure
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
static bool e1000_clean_jumbo_rx_irq(struct e1000_ring *rx_ring, int *work_done,
int work_to_do)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
union e1000_rx_desc_extended *rx_desc, *next_rxd;
struct e1000_buffer *buffer_info, *next_buffer;
u32 length, staterr;
unsigned int i;
int cleaned_count = 0;
bool cleaned = false;
unsigned int total_rx_bytes=0, total_rx_packets=0;
i = rx_ring->next_to_clean;
rx_desc = E1000_RX_DESC_EXT(*rx_ring, i);
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
buffer_info = &rx_ring->buffer_info[i];
while (staterr & E1000_RXD_STAT_DD) {
struct sk_buff *skb;
if (*work_done >= work_to_do)
break;
(*work_done)++;
rmb(); /* read descriptor and rx_buffer_info after status DD */
skb = buffer_info->skb;
buffer_info->skb = NULL;
++i;
if (i == rx_ring->count)
i = 0;
next_rxd = E1000_RX_DESC_EXT(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
cleaned = true;
cleaned_count++;
dma_unmap_page(&pdev->dev, buffer_info->dma, PAGE_SIZE,
DMA_FROM_DEVICE);
buffer_info->dma = 0;
length = le16_to_cpu(rx_desc->wb.upper.length);
/* errors is only valid for DD + EOP descriptors */
if (unlikely((staterr & E1000_RXD_STAT_EOP) &&
((staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK) &&
!(netdev->features & NETIF_F_RXALL)))) {
/* recycle both page and skb */
buffer_info->skb = skb;
/* an error means any chain goes out the window too */
if (rx_ring->rx_skb_top)
dev_kfree_skb_irq(rx_ring->rx_skb_top);
rx_ring->rx_skb_top = NULL;
goto next_desc;
}
#define rxtop (rx_ring->rx_skb_top)
if (!(staterr & E1000_RXD_STAT_EOP)) {
/* this descriptor is only the beginning (or middle) */
if (!rxtop) {
/* this is the beginning of a chain */
rxtop = skb;
skb_fill_page_desc(rxtop, 0, buffer_info->page,
0, length);
} else {
/* this is the middle of a chain */
skb_fill_page_desc(rxtop,
skb_shinfo(rxtop)->nr_frags,
buffer_info->page, 0, length);
/* re-use the skb, only consumed the page */
buffer_info->skb = skb;
}
e1000_consume_page(buffer_info, rxtop, length);
goto next_desc;
} else {
if (rxtop) {
/* end of the chain */
skb_fill_page_desc(rxtop,
skb_shinfo(rxtop)->nr_frags,
buffer_info->page, 0, length);
/* re-use the current skb, we only consumed the
* page */
buffer_info->skb = skb;
skb = rxtop;
rxtop = NULL;
e1000_consume_page(buffer_info, skb, length);
} else {
/* no chain, got EOP, this buf is the packet
* copybreak to save the put_page/alloc_page */
if (length <= copybreak &&
skb_tailroom(skb) >= length) {
u8 *vaddr;
vaddr = kmap_atomic(buffer_info->page);
memcpy(skb_tail_pointer(skb), vaddr,
length);
kunmap_atomic(vaddr);
/* re-use the page, so don't erase
* buffer_info->page */
skb_put(skb, length);
} else {
skb_fill_page_desc(skb, 0,
buffer_info->page, 0,
length);
e1000_consume_page(buffer_info, skb,
length);
}
}
}
/* Receive Checksum Offload */
e1000_rx_checksum(adapter, staterr, skb);
e1000_rx_hash(netdev, rx_desc->wb.lower.hi_dword.rss, skb);
/* probably a little skewed due to removing CRC */
total_rx_bytes += skb->len;
total_rx_packets++;
/* eth type trans needs skb->data to point to something */
if (!pskb_may_pull(skb, ETH_HLEN)) {
e_err("pskb_may_pull failed.\n");
dev_kfree_skb_irq(skb);
goto next_desc;
}
e1000_receive_skb(adapter, netdev, skb, staterr,
rx_desc->wb.upper.vlan);
next_desc:
rx_desc->wb.upper.status_error &= cpu_to_le32(~0xFF);
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= E1000_RX_BUFFER_WRITE)) {
adapter->alloc_rx_buf(rx_ring, cleaned_count,
GFP_ATOMIC);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
}
rx_ring->next_to_clean = i;
cleaned_count = e1000_desc_unused(rx_ring);
if (cleaned_count)
adapter->alloc_rx_buf(rx_ring, cleaned_count, GFP_ATOMIC);
adapter->total_rx_bytes += total_rx_bytes;
adapter->total_rx_packets += total_rx_packets;
return cleaned;
}
/**
* e1000_clean_rx_ring - Free Rx Buffers per Queue
* @rx_ring: Rx descriptor ring
**/
static void e1000_clean_rx_ring(struct e1000_ring *rx_ring)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct e1000_buffer *buffer_info;
struct e1000_ps_page *ps_page;
struct pci_dev *pdev = adapter->pdev;
unsigned int i, j;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
if (buffer_info->dma) {
if (adapter->clean_rx == e1000_clean_rx_irq)
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
else if (adapter->clean_rx == e1000_clean_jumbo_rx_irq)
dma_unmap_page(&pdev->dev, buffer_info->dma,
PAGE_SIZE,
DMA_FROM_DEVICE);
else if (adapter->clean_rx == e1000_clean_rx_irq_ps)
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_ps_bsize0,
DMA_FROM_DEVICE);
buffer_info->dma = 0;
}
if (buffer_info->page) {
put_page(buffer_info->page);
buffer_info->page = NULL;
}
if (buffer_info->skb) {
dev_kfree_skb(buffer_info->skb);
buffer_info->skb = NULL;
}
for (j = 0; j < PS_PAGE_BUFFERS; j++) {
ps_page = &buffer_info->ps_pages[j];
if (!ps_page->page)
break;
dma_unmap_page(&pdev->dev, ps_page->dma, PAGE_SIZE,
DMA_FROM_DEVICE);
ps_page->dma = 0;
put_page(ps_page->page);
ps_page->page = NULL;
}
}
/* there also may be some cached data from a chained receive */
if (rx_ring->rx_skb_top) {
dev_kfree_skb(rx_ring->rx_skb_top);
rx_ring->rx_skb_top = NULL;
}
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
adapter->flags2 &= ~FLAG2_IS_DISCARDING;
writel(0, rx_ring->head);
writel(0, rx_ring->tail);
}
static void e1000e_downshift_workaround(struct work_struct *work)
{
struct e1000_adapter *adapter = container_of(work,
struct e1000_adapter, downshift_task);
if (test_bit(__E1000_DOWN, &adapter->state))
return;
e1000e_gig_downshift_workaround_ich8lan(&adapter->hw);
}
/**
* e1000_intr_msi - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static irqreturn_t e1000_intr_msi(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 icr = er32(ICR);
/*
* read ICR disables interrupts using IAM
*/
if (icr & E1000_ICR_LSC) {
hw->mac.get_link_status = true;
/*
* ICH8 workaround-- Call gig speed drop workaround on cable
* disconnect (LSC) before accessing any PHY registers
*/
if ((adapter->flags & FLAG_LSC_GIG_SPEED_DROP) &&
(!(er32(STATUS) & E1000_STATUS_LU)))
schedule_work(&adapter->downshift_task);
/*
* 80003ES2LAN workaround-- For packet buffer work-around on
* link down event; disable receives here in the ISR and reset
* adapter in watchdog
*/
if (netif_carrier_ok(netdev) &&
adapter->flags & FLAG_RX_NEEDS_RESTART) {
/* disable receives */
u32 rctl = er32(RCTL);
ew32(RCTL, rctl & ~E1000_RCTL_EN);
adapter->flags |= FLAG_RX_RESTART_NOW;
}
/* guard against interrupt when we're going down */
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
if (napi_schedule_prep(&adapter->napi)) {
adapter->total_tx_bytes = 0;
adapter->total_tx_packets = 0;
adapter->total_rx_bytes = 0;
adapter->total_rx_packets = 0;
__napi_schedule(&adapter->napi);
}
return IRQ_HANDLED;
}
/**
* e1000_intr - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static irqreturn_t e1000_intr(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 rctl, icr = er32(ICR);
if (!icr || test_bit(__E1000_DOWN, &adapter->state))
return IRQ_NONE; /* Not our interrupt */
/*
* IMS will not auto-mask if INT_ASSERTED is not set, and if it is
* not set, then the adapter didn't send an interrupt
*/
if (!(icr & E1000_ICR_INT_ASSERTED))
return IRQ_NONE;
/*
* Interrupt Auto-Mask...upon reading ICR,
* interrupts are masked. No need for the
* IMC write
*/
if (icr & E1000_ICR_LSC) {
hw->mac.get_link_status = true;
/*
* ICH8 workaround-- Call gig speed drop workaround on cable
* disconnect (LSC) before accessing any PHY registers
*/
if ((adapter->flags & FLAG_LSC_GIG_SPEED_DROP) &&
(!(er32(STATUS) & E1000_STATUS_LU)))
schedule_work(&adapter->downshift_task);
/*
* 80003ES2LAN workaround--
* For packet buffer work-around on link down event;
* disable receives here in the ISR and
* reset adapter in watchdog
*/
if (netif_carrier_ok(netdev) &&
(adapter->flags & FLAG_RX_NEEDS_RESTART)) {
/* disable receives */
rctl = er32(RCTL);
ew32(RCTL, rctl & ~E1000_RCTL_EN);
adapter->flags |= FLAG_RX_RESTART_NOW;
}
/* guard against interrupt when we're going down */
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
if (napi_schedule_prep(&adapter->napi)) {
adapter->total_tx_bytes = 0;
adapter->total_tx_packets = 0;
adapter->total_rx_bytes = 0;
adapter->total_rx_packets = 0;
__napi_schedule(&adapter->napi);
}
return IRQ_HANDLED;
}
static irqreturn_t e1000_msix_other(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 icr = er32(ICR);
if (!(icr & E1000_ICR_INT_ASSERTED)) {
if (!test_bit(__E1000_DOWN, &adapter->state))
ew32(IMS, E1000_IMS_OTHER);
return IRQ_NONE;
}
if (icr & adapter->eiac_mask)
ew32(ICS, (icr & adapter->eiac_mask));
if (icr & E1000_ICR_OTHER) {
if (!(icr & E1000_ICR_LSC))
goto no_link_interrupt;
hw->mac.get_link_status = true;
/* guard against interrupt when we're going down */
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
no_link_interrupt:
if (!test_bit(__E1000_DOWN, &adapter->state))
ew32(IMS, E1000_IMS_LSC | E1000_IMS_OTHER);
return IRQ_HANDLED;
}
static irqreturn_t e1000_intr_msix_tx(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct e1000_ring *tx_ring = adapter->tx_ring;
adapter->total_tx_bytes = 0;
adapter->total_tx_packets = 0;
if (!e1000_clean_tx_irq(tx_ring))
/* Ring was not completely cleaned, so fire another interrupt */
ew32(ICS, tx_ring->ims_val);
return IRQ_HANDLED;
}
static irqreturn_t e1000_intr_msix_rx(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_ring *rx_ring = adapter->rx_ring;
/* Write the ITR value calculated at the end of the
* previous interrupt.
*/
if (rx_ring->set_itr) {
writel(1000000000 / (rx_ring->itr_val * 256),
rx_ring->itr_register);
rx_ring->set_itr = 0;
}
if (napi_schedule_prep(&adapter->napi)) {
adapter->total_rx_bytes = 0;
adapter->total_rx_packets = 0;
__napi_schedule(&adapter->napi);
}
return IRQ_HANDLED;
}
/**
* e1000_configure_msix - Configure MSI-X hardware
*
* e1000_configure_msix sets up the hardware to properly
* generate MSI-X interrupts.
**/
static void e1000_configure_msix(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct e1000_ring *rx_ring = adapter->rx_ring;
struct e1000_ring *tx_ring = adapter->tx_ring;
int vector = 0;
u32 ctrl_ext, ivar = 0;
adapter->eiac_mask = 0;
/* Workaround issue with spurious interrupts on 82574 in MSI-X mode */
if (hw->mac.type == e1000_82574) {
u32 rfctl = er32(RFCTL);
rfctl |= E1000_RFCTL_ACK_DIS;
ew32(RFCTL, rfctl);
}
#define E1000_IVAR_INT_ALLOC_VALID 0x8
/* Configure Rx vector */
rx_ring->ims_val = E1000_IMS_RXQ0;
adapter->eiac_mask |= rx_ring->ims_val;
if (rx_ring->itr_val)
writel(1000000000 / (rx_ring->itr_val * 256),
rx_ring->itr_register);
else
writel(1, rx_ring->itr_register);
ivar = E1000_IVAR_INT_ALLOC_VALID | vector;
/* Configure Tx vector */
tx_ring->ims_val = E1000_IMS_TXQ0;
vector++;
if (tx_ring->itr_val)
writel(1000000000 / (tx_ring->itr_val * 256),
tx_ring->itr_register);
else
writel(1, tx_ring->itr_register);
adapter->eiac_mask |= tx_ring->ims_val;
ivar |= ((E1000_IVAR_INT_ALLOC_VALID | vector) << 8);
/* set vector for Other Causes, e.g. link changes */
vector++;
ivar |= ((E1000_IVAR_INT_ALLOC_VALID | vector) << 16);
if (rx_ring->itr_val)
writel(1000000000 / (rx_ring->itr_val * 256),
hw->hw_addr + E1000_EITR_82574(vector));
else
writel(1, hw->hw_addr + E1000_EITR_82574(vector));
/* Cause Tx interrupts on every write back */
ivar |= (1 << 31);
ew32(IVAR, ivar);
/* enable MSI-X PBA support */
ctrl_ext = er32(CTRL_EXT);
ctrl_ext |= E1000_CTRL_EXT_PBA_CLR;
/* Auto-Mask Other interrupts upon ICR read */
#define E1000_EIAC_MASK_82574 0x01F00000
ew32(IAM, ~E1000_EIAC_MASK_82574 | E1000_IMS_OTHER);
ctrl_ext |= E1000_CTRL_EXT_EIAME;
ew32(CTRL_EXT, ctrl_ext);
e1e_flush();
}
void e1000e_reset_interrupt_capability(struct e1000_adapter *adapter)
{
if (adapter->msix_entries) {
pci_disable_msix(adapter->pdev);
kfree(adapter->msix_entries);
adapter->msix_entries = NULL;
} else if (adapter->flags & FLAG_MSI_ENABLED) {
pci_disable_msi(adapter->pdev);
adapter->flags &= ~FLAG_MSI_ENABLED;
}
}
/**
* e1000e_set_interrupt_capability - set MSI or MSI-X if supported
*
* Attempt to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
void e1000e_set_interrupt_capability(struct e1000_adapter *adapter)
{
int err;
int i;
switch (adapter->int_mode) {
case E1000E_INT_MODE_MSIX:
if (adapter->flags & FLAG_HAS_MSIX) {
adapter->num_vectors = 3; /* RxQ0, TxQ0 and other */
adapter->msix_entries = kcalloc(adapter->num_vectors,
sizeof(struct msix_entry),
GFP_KERNEL);
if (adapter->msix_entries) {
for (i = 0; i < adapter->num_vectors; i++)
adapter->msix_entries[i].entry = i;
err = pci_enable_msix(adapter->pdev,
adapter->msix_entries,
adapter->num_vectors);
if (err == 0)
return;
}
/* MSI-X failed, so fall through and try MSI */
e_err("Failed to initialize MSI-X interrupts. Falling back to MSI interrupts.\n");
e1000e_reset_interrupt_capability(adapter);
}
adapter->int_mode = E1000E_INT_MODE_MSI;
/* Fall through */
case E1000E_INT_MODE_MSI:
if (!pci_enable_msi(adapter->pdev)) {
adapter->flags |= FLAG_MSI_ENABLED;
} else {
adapter->int_mode = E1000E_INT_MODE_LEGACY;
e_err("Failed to initialize MSI interrupts. Falling back to legacy interrupts.\n");
}
/* Fall through */
case E1000E_INT_MODE_LEGACY:
/* Don't do anything; this is the system default */
break;
}
/* store the number of vectors being used */
adapter->num_vectors = 1;
}
/**
* e1000_request_msix - Initialize MSI-X interrupts
*
* e1000_request_msix allocates MSI-X vectors and requests interrupts from the
* kernel.
**/
static int e1000_request_msix(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err = 0, vector = 0;
if (strlen(netdev->name) < (IFNAMSIZ - 5))
snprintf(adapter->rx_ring->name,
sizeof(adapter->rx_ring->name) - 1,
"%s-rx-0", netdev->name);
else
memcpy(adapter->rx_ring->name, netdev->name, IFNAMSIZ);
err = request_irq(adapter->msix_entries[vector].vector,
e1000_intr_msix_rx, 0, adapter->rx_ring->name,
netdev);
if (err)
return err;
adapter->rx_ring->itr_register = adapter->hw.hw_addr +
E1000_EITR_82574(vector);
adapter->rx_ring->itr_val = adapter->itr;
vector++;
if (strlen(netdev->name) < (IFNAMSIZ - 5))
snprintf(adapter->tx_ring->name,
sizeof(adapter->tx_ring->name) - 1,
"%s-tx-0", netdev->name);
else
memcpy(adapter->tx_ring->name, netdev->name, IFNAMSIZ);
err = request_irq(adapter->msix_entries[vector].vector,
e1000_intr_msix_tx, 0, adapter->tx_ring->name,
netdev);
if (err)
return err;
adapter->tx_ring->itr_register = adapter->hw.hw_addr +
E1000_EITR_82574(vector);
adapter->tx_ring->itr_val = adapter->itr;
vector++;
err = request_irq(adapter->msix_entries[vector].vector,
e1000_msix_other, 0, netdev->name, netdev);
if (err)
return err;
e1000_configure_msix(adapter);
return 0;
}
/**
* e1000_request_irq - initialize interrupts
*
* Attempts to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
static int e1000_request_irq(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err;
if (adapter->msix_entries) {
err = e1000_request_msix(adapter);
if (!err)
return err;
/* fall back to MSI */
e1000e_reset_interrupt_capability(adapter);
adapter->int_mode = E1000E_INT_MODE_MSI;
e1000e_set_interrupt_capability(adapter);
}
if (adapter->flags & FLAG_MSI_ENABLED) {
err = request_irq(adapter->pdev->irq, e1000_intr_msi, 0,
netdev->name, netdev);
if (!err)
return err;
/* fall back to legacy interrupt */
e1000e_reset_interrupt_capability(adapter);
adapter->int_mode = E1000E_INT_MODE_LEGACY;
}
err = request_irq(adapter->pdev->irq, e1000_intr, IRQF_SHARED,
netdev->name, netdev);
if (err)
e_err("Unable to allocate interrupt, Error: %d\n", err);
return err;
}
static void e1000_free_irq(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
if (adapter->msix_entries) {
int vector = 0;
free_irq(adapter->msix_entries[vector].vector, netdev);
vector++;
free_irq(adapter->msix_entries[vector].vector, netdev);
vector++;
/* Other Causes interrupt vector */
free_irq(adapter->msix_entries[vector].vector, netdev);
return;
}
free_irq(adapter->pdev->irq, netdev);
}
/**
* e1000_irq_disable - Mask off interrupt generation on the NIC
**/
static void e1000_irq_disable(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
ew32(IMC, ~0);
if (adapter->msix_entries)
ew32(EIAC_82574, 0);
e1e_flush();
if (adapter->msix_entries) {
int i;
for (i = 0; i < adapter->num_vectors; i++)
synchronize_irq(adapter->msix_entries[i].vector);
} else {
synchronize_irq(adapter->pdev->irq);
}
}
/**
* e1000_irq_enable - Enable default interrupt generation settings
**/
static void e1000_irq_enable(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
if (adapter->msix_entries) {
ew32(EIAC_82574, adapter->eiac_mask & E1000_EIAC_MASK_82574);
ew32(IMS, adapter->eiac_mask | E1000_IMS_OTHER | E1000_IMS_LSC);
} else {
ew32(IMS, IMS_ENABLE_MASK);
}
e1e_flush();
}
/**
* e1000e_get_hw_control - get control of the h/w from f/w
* @adapter: address of board private structure
*
* e1000e_get_hw_control sets {CTRL_EXT|SWSM}:DRV_LOAD bit.
* For ASF and Pass Through versions of f/w this means that
* the driver is loaded. For AMT version (only with 82573)
* of the f/w this means that the network i/f is open.
**/
void e1000e_get_hw_control(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ctrl_ext;
u32 swsm;
/* Let firmware know the driver has taken over */
if (adapter->flags & FLAG_HAS_SWSM_ON_LOAD) {
swsm = er32(SWSM);
ew32(SWSM, swsm | E1000_SWSM_DRV_LOAD);
} else if (adapter->flags & FLAG_HAS_CTRLEXT_ON_LOAD) {
ctrl_ext = er32(CTRL_EXT);
ew32(CTRL_EXT, ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
}
}
/**
* e1000e_release_hw_control - release control of the h/w to f/w
* @adapter: address of board private structure
*
* e1000e_release_hw_control resets {CTRL_EXT|SWSM}:DRV_LOAD bit.
* For ASF and Pass Through versions of f/w this means that the
* driver is no longer loaded. For AMT version (only with 82573) i
* of the f/w this means that the network i/f is closed.
*
**/
void e1000e_release_hw_control(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ctrl_ext;
u32 swsm;
/* Let firmware taken over control of h/w */
if (adapter->flags & FLAG_HAS_SWSM_ON_LOAD) {
swsm = er32(SWSM);
ew32(SWSM, swsm & ~E1000_SWSM_DRV_LOAD);
} else if (adapter->flags & FLAG_HAS_CTRLEXT_ON_LOAD) {
ctrl_ext = er32(CTRL_EXT);
ew32(CTRL_EXT, ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
}
}
/**
* @e1000_alloc_ring - allocate memory for a ring structure
**/
static int e1000_alloc_ring_dma(struct e1000_adapter *adapter,
struct e1000_ring *ring)
{
struct pci_dev *pdev = adapter->pdev;
ring->desc = dma_alloc_coherent(&pdev->dev, ring->size, &ring->dma,
GFP_KERNEL);
if (!ring->desc)
return -ENOMEM;
return 0;
}
/**
* e1000e_setup_tx_resources - allocate Tx resources (Descriptors)
* @tx_ring: Tx descriptor ring
*
* Return 0 on success, negative on failure
**/
int e1000e_setup_tx_resources(struct e1000_ring *tx_ring)
{
struct e1000_adapter *adapter = tx_ring->adapter;
int err = -ENOMEM, size;
size = sizeof(struct e1000_buffer) * tx_ring->count;
tx_ring->buffer_info = vzalloc(size);
if (!tx_ring->buffer_info)
goto err;
/* round up to nearest 4K */
tx_ring->size = tx_ring->count * sizeof(struct e1000_tx_desc);
tx_ring->size = ALIGN(tx_ring->size, 4096);
err = e1000_alloc_ring_dma(adapter, tx_ring);
if (err)
goto err;
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
return 0;
err:
vfree(tx_ring->buffer_info);
e_err("Unable to allocate memory for the transmit descriptor ring\n");
return err;
}
/**
* e1000e_setup_rx_resources - allocate Rx resources (Descriptors)
* @rx_ring: Rx descriptor ring
*
* Returns 0 on success, negative on failure
**/
int e1000e_setup_rx_resources(struct e1000_ring *rx_ring)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct e1000_buffer *buffer_info;
int i, size, desc_len, err = -ENOMEM;
size = sizeof(struct e1000_buffer) * rx_ring->count;
rx_ring->buffer_info = vzalloc(size);
if (!rx_ring->buffer_info)
goto err;
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
buffer_info->ps_pages = kcalloc(PS_PAGE_BUFFERS,
sizeof(struct e1000_ps_page),
GFP_KERNEL);
if (!buffer_info->ps_pages)
goto err_pages;
}
desc_len = sizeof(union e1000_rx_desc_packet_split);
/* Round up to nearest 4K */
rx_ring->size = rx_ring->count * desc_len;
rx_ring->size = ALIGN(rx_ring->size, 4096);
err = e1000_alloc_ring_dma(adapter, rx_ring);
if (err)
goto err_pages;
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
rx_ring->rx_skb_top = NULL;
return 0;
err_pages:
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
kfree(buffer_info->ps_pages);
}
err:
vfree(rx_ring->buffer_info);
e_err("Unable to allocate memory for the receive descriptor ring\n");
return err;
}
/**
* e1000_clean_tx_ring - Free Tx Buffers
* @tx_ring: Tx descriptor ring
**/
static void e1000_clean_tx_ring(struct e1000_ring *tx_ring)
{
struct e1000_adapter *adapter = tx_ring->adapter;
struct e1000_buffer *buffer_info;
unsigned long size;
unsigned int i;
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
e1000_put_txbuf(tx_ring, buffer_info);
}
netdev_reset_queue(adapter->netdev);
size = sizeof(struct e1000_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
writel(0, tx_ring->head);
writel(0, tx_ring->tail);
}
/**
* e1000e_free_tx_resources - Free Tx Resources per Queue
* @tx_ring: Tx descriptor ring
*
* Free all transmit software resources
**/
void e1000e_free_tx_resources(struct e1000_ring *tx_ring)
{
struct e1000_adapter *adapter = tx_ring->adapter;
struct pci_dev *pdev = adapter->pdev;
e1000_clean_tx_ring(tx_ring);
vfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, tx_ring->size, tx_ring->desc,
tx_ring->dma);
tx_ring->desc = NULL;
}
/**
* e1000e_free_rx_resources - Free Rx Resources
* @rx_ring: Rx descriptor ring
*
* Free all receive software resources
**/
void e1000e_free_rx_resources(struct e1000_ring *rx_ring)
{
struct e1000_adapter *adapter = rx_ring->adapter;
struct pci_dev *pdev = adapter->pdev;
int i;
e1000_clean_rx_ring(rx_ring);
for (i = 0; i < rx_ring->count; i++)
kfree(rx_ring->buffer_info[i].ps_pages);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, rx_ring->size, rx_ring->desc,
rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* e1000_update_itr - update the dynamic ITR value based on statistics
* @adapter: pointer to adapter
* @itr_setting: current adapter->itr
* @packets: the number of packets during this measurement interval
* @bytes: the number of bytes during this measurement interval
*
* Stores a new ITR value based on packets and byte
* counts during the last interrupt. The advantage of per interrupt
* computation is faster updates and more accurate ITR for the current
* traffic pattern. Constants in this function were computed
* based on theoretical maximum wire speed and thresholds were set based
* on testing data as well as attempting to minimize response time
* while increasing bulk throughput. This functionality is controlled
* by the InterruptThrottleRate module parameter.
**/
static unsigned int e1000_update_itr(struct e1000_adapter *adapter,
u16 itr_setting, int packets,
int bytes)
{
unsigned int retval = itr_setting;
if (packets == 0)
return itr_setting;
switch (itr_setting) {
case lowest_latency:
/* handle TSO and jumbo frames */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 5) && (bytes > 512))
retval = low_latency;
break;
case low_latency: /* 50 usec aka 20000 ints/s */
if (bytes > 10000) {
/* this if handles the TSO accounting */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 10) || ((bytes/packets) > 1200))
retval = bulk_latency;
else if ((packets > 35))
retval = lowest_latency;
} else if (bytes/packets > 2000) {
retval = bulk_latency;
} else if (packets <= 2 && bytes < 512) {
retval = lowest_latency;
}
break;
case bulk_latency: /* 250 usec aka 4000 ints/s */
if (bytes > 25000) {
if (packets > 35)
retval = low_latency;
} else if (bytes < 6000) {
retval = low_latency;
}
break;
}
return retval;
}
static void e1000_set_itr(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u16 current_itr;
u32 new_itr = adapter->itr;
/* for non-gigabit speeds, just fix the interrupt rate at 4000 */
if (adapter->link_speed != SPEED_1000) {
current_itr = 0;
new_itr = 4000;
goto set_itr_now;
}
if (adapter->flags2 & FLAG2_DISABLE_AIM) {
new_itr = 0;
goto set_itr_now;
}
adapter->tx_itr = e1000_update_itr(adapter,
adapter->tx_itr,
adapter->total_tx_packets,
adapter->total_tx_bytes);
/* conservative mode (itr 3) eliminates the lowest_latency setting */
if (adapter->itr_setting == 3 && adapter->tx_itr == lowest_latency)
adapter->tx_itr = low_latency;
adapter->rx_itr = e1000_update_itr(adapter,
adapter->rx_itr,
adapter->total_rx_packets,
adapter->total_rx_bytes);
/* conservative mode (itr 3) eliminates the lowest_latency setting */
if (adapter->itr_setting == 3 && adapter->rx_itr == lowest_latency)
adapter->rx_itr = low_latency;
current_itr = max(adapter->rx_itr, adapter->tx_itr);
switch (current_itr) {
/* counts and packets in update_itr are dependent on these numbers */
case lowest_latency:
new_itr = 70000;
break;
case low_latency:
new_itr = 20000; /* aka hwitr = ~200 */
break;
case bulk_latency:
new_itr = 4000;
break;
default:
break;
}
set_itr_now:
if (new_itr != adapter->itr) {
/*
* this attempts to bias the interrupt rate towards Bulk
* by adding intermediate steps when interrupt rate is
* increasing
*/
new_itr = new_itr > adapter->itr ?
min(adapter->itr + (new_itr >> 2), new_itr) :
new_itr;
adapter->itr = new_itr;
adapter->rx_ring->itr_val = new_itr;
if (adapter->msix_entries)
adapter->rx_ring->set_itr = 1;
else
if (new_itr)
ew32(ITR, 1000000000 / (new_itr * 256));
else
ew32(ITR, 0);
}
}
/**
* e1000_alloc_queues - Allocate memory for all rings
* @adapter: board private structure to initialize
**/
static int __devinit e1000_alloc_queues(struct e1000_adapter *adapter)
{
int size = sizeof(struct e1000_ring);
adapter->tx_ring = kzalloc(size, GFP_KERNEL);
if (!adapter->tx_ring)
goto err;
adapter->tx_ring->count = adapter->tx_ring_count;
adapter->tx_ring->adapter = adapter;
adapter->rx_ring = kzalloc(size, GFP_KERNEL);
if (!adapter->rx_ring)
goto err;
adapter->rx_ring->count = adapter->rx_ring_count;
adapter->rx_ring->adapter = adapter;
return 0;
err:
e_err("Unable to allocate memory for queues\n");
kfree(adapter->rx_ring);
kfree(adapter->tx_ring);
return -ENOMEM;
}
/**
* e1000_clean - NAPI Rx polling callback
* @napi: struct associated with this polling callback
* @budget: amount of packets driver is allowed to process this poll
**/
static int e1000_clean(struct napi_struct *napi, int budget)
{
struct e1000_adapter *adapter = container_of(napi, struct e1000_adapter, napi);
struct e1000_hw *hw = &adapter->hw;
struct net_device *poll_dev = adapter->netdev;
int tx_cleaned = 1, work_done = 0;
adapter = netdev_priv(poll_dev);
if (adapter->msix_entries &&
!(adapter->rx_ring->ims_val & adapter->tx_ring->ims_val))
goto clean_rx;
tx_cleaned = e1000_clean_tx_irq(adapter->tx_ring);
clean_rx:
adapter->clean_rx(adapter->rx_ring, &work_done, budget);
if (!tx_cleaned)
work_done = budget;
/* If budget not fully consumed, exit the polling mode */
if (work_done < budget) {
if (adapter->itr_setting & 3)
e1000_set_itr(adapter);
napi_complete(napi);
if (!test_bit(__E1000_DOWN, &adapter->state)) {
if (adapter->msix_entries)
ew32(IMS, adapter->rx_ring->ims_val);
else
e1000_irq_enable(adapter);
}
}
return work_done;
}
static int e1000_vlan_rx_add_vid(struct net_device *netdev, u16 vid)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 vfta, index;
/* don't update vlan cookie if already programmed */
if ((adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN) &&
(vid == adapter->mng_vlan_id))
return 0;
/* add VID to filter table */
if (adapter->flags & FLAG_HAS_HW_VLAN_FILTER) {
index = (vid >> 5) & 0x7F;
vfta = E1000_READ_REG_ARRAY(hw, E1000_VFTA, index);
vfta |= (1 << (vid & 0x1F));
hw->mac.ops.write_vfta(hw, index, vfta);
}
set_bit(vid, adapter->active_vlans);
return 0;
}
static int e1000_vlan_rx_kill_vid(struct net_device *netdev, u16 vid)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 vfta, index;
if ((adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN) &&
(vid == adapter->mng_vlan_id)) {
/* release control to f/w */
e1000e_release_hw_control(adapter);
return 0;
}
/* remove VID from filter table */
if (adapter->flags & FLAG_HAS_HW_VLAN_FILTER) {
index = (vid >> 5) & 0x7F;
vfta = E1000_READ_REG_ARRAY(hw, E1000_VFTA, index);
vfta &= ~(1 << (vid & 0x1F));
hw->mac.ops.write_vfta(hw, index, vfta);
}
clear_bit(vid, adapter->active_vlans);
return 0;
}
/**
* e1000e_vlan_filter_disable - helper to disable hw VLAN filtering
* @adapter: board private structure to initialize
**/
static void e1000e_vlan_filter_disable(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
u32 rctl;
if (adapter->flags & FLAG_HAS_HW_VLAN_FILTER) {
/* disable VLAN receive filtering */
rctl = er32(RCTL);
rctl &= ~(E1000_RCTL_VFE | E1000_RCTL_CFIEN);
ew32(RCTL, rctl);
if (adapter->mng_vlan_id != (u16)E1000_MNG_VLAN_NONE) {
e1000_vlan_rx_kill_vid(netdev, adapter->mng_vlan_id);
adapter->mng_vlan_id = E1000_MNG_VLAN_NONE;
}
}
}
/**
* e1000e_vlan_filter_enable - helper to enable HW VLAN filtering
* @adapter: board private structure to initialize
**/
static void e1000e_vlan_filter_enable(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 rctl;
if (adapter->flags & FLAG_HAS_HW_VLAN_FILTER) {
/* enable VLAN receive filtering */
rctl = er32(RCTL);
rctl |= E1000_RCTL_VFE;
rctl &= ~E1000_RCTL_CFIEN;
ew32(RCTL, rctl);
}
}
/**
* e1000e_vlan_strip_enable - helper to disable HW VLAN stripping
* @adapter: board private structure to initialize
**/
static void e1000e_vlan_strip_disable(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ctrl;
/* disable VLAN tag insert/strip */
ctrl = er32(CTRL);
ctrl &= ~E1000_CTRL_VME;
ew32(CTRL, ctrl);
}
/**
* e1000e_vlan_strip_enable - helper to enable HW VLAN stripping
* @adapter: board private structure to initialize
**/
static void e1000e_vlan_strip_enable(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ctrl;
/* enable VLAN tag insert/strip */
ctrl = er32(CTRL);
ctrl |= E1000_CTRL_VME;
ew32(CTRL, ctrl);
}
static void e1000_update_mng_vlan(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u16 vid = adapter->hw.mng_cookie.vlan_id;
u16 old_vid = adapter->mng_vlan_id;
if (adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN) {
e1000_vlan_rx_add_vid(netdev, vid);
adapter->mng_vlan_id = vid;
}
if ((old_vid != (u16)E1000_MNG_VLAN_NONE) && (vid != old_vid))
e1000_vlan_rx_kill_vid(netdev, old_vid);
}
static void e1000_restore_vlan(struct e1000_adapter *adapter)
{
u16 vid;
e1000_vlan_rx_add_vid(adapter->netdev, 0);
for_each_set_bit(vid, adapter->active_vlans, VLAN_N_VID)
e1000_vlan_rx_add_vid(adapter->netdev, vid);
}
static void e1000_init_manageability_pt(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 manc, manc2h, mdef, i, j;
if (!(adapter->flags & FLAG_MNG_PT_ENABLED))
return;
manc = er32(MANC);
/*
* enable receiving management packets to the host. this will probably
* generate destination unreachable messages from the host OS, but
* the packets will be handled on SMBUS
*/
manc |= E1000_MANC_EN_MNG2HOST;
manc2h = er32(MANC2H);
switch (hw->mac.type) {
default:
manc2h |= (E1000_MANC2H_PORT_623 | E1000_MANC2H_PORT_664);
break;
case e1000_82574:
case e1000_82583:
/*
* Check if IPMI pass-through decision filter already exists;
* if so, enable it.
*/
for (i = 0, j = 0; i < 8; i++) {
mdef = er32(MDEF(i));
/* Ignore filters with anything other than IPMI ports */
if (mdef & ~(E1000_MDEF_PORT_623 | E1000_MDEF_PORT_664))
continue;
/* Enable this decision filter in MANC2H */
if (mdef)
manc2h |= (1 << i);
j |= mdef;
}
if (j == (E1000_MDEF_PORT_623 | E1000_MDEF_PORT_664))
break;
/* Create new decision filter in an empty filter */
for (i = 0, j = 0; i < 8; i++)
if (er32(MDEF(i)) == 0) {
ew32(MDEF(i), (E1000_MDEF_PORT_623 |
E1000_MDEF_PORT_664));
manc2h |= (1 << 1);
j++;
break;
}
if (!j)
e_warn("Unable to create IPMI pass-through filter\n");
break;
}
ew32(MANC2H, manc2h);
ew32(MANC, manc);
}
/**
* e1000_configure_tx - Configure Transmit Unit after Reset
* @adapter: board private structure
*
* Configure the Tx unit of the MAC after a reset.
**/
static void e1000_configure_tx(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct e1000_ring *tx_ring = adapter->tx_ring;
u64 tdba;
u32 tdlen, tarc;
/* Setup the HW Tx Head and Tail descriptor pointers */
tdba = tx_ring->dma;
tdlen = tx_ring->count * sizeof(struct e1000_tx_desc);
ew32(TDBAL, (tdba & DMA_BIT_MASK(32)));
ew32(TDBAH, (tdba >> 32));
ew32(TDLEN, tdlen);
ew32(TDH, 0);
ew32(TDT, 0);
tx_ring->head = adapter->hw.hw_addr + E1000_TDH;
tx_ring->tail = adapter->hw.hw_addr + E1000_TDT;
/* Set the Tx Interrupt Delay register */
ew32(TIDV, adapter->tx_int_delay);
/* Tx irq moderation */
ew32(TADV, adapter->tx_abs_int_delay);
if (adapter->flags2 & FLAG2_DMA_BURST) {
u32 txdctl = er32(TXDCTL(0));
txdctl &= ~(E1000_TXDCTL_PTHRESH | E1000_TXDCTL_HTHRESH |
E1000_TXDCTL_WTHRESH);
/*
* set up some performance related parameters to encourage the
* hardware to use the bus more efficiently in bursts, depends
* on the tx_int_delay to be enabled,
* wthresh = 1 ==> burst write is disabled to avoid Tx stalls
* hthresh = 1 ==> prefetch when one or more available
* pthresh = 0x1f ==> prefetch if internal cache 31 or less
* BEWARE: this seems to work but should be considered first if
* there are Tx hangs or other Tx related bugs
*/
txdctl |= E1000_TXDCTL_DMA_BURST_ENABLE;
ew32(TXDCTL(0), txdctl);
}
/* erratum work around: set txdctl the same for both queues */
ew32(TXDCTL(1), er32(TXDCTL(0)));
if (adapter->flags & FLAG_TARC_SPEED_MODE_BIT) {
tarc = er32(TARC(0));
/*
* set the speed mode bit, we'll clear it if we're not at
* gigabit link later
*/
#define SPEED_MODE_BIT (1 << 21)
tarc |= SPEED_MODE_BIT;
ew32(TARC(0), tarc);
}
/* errata: program both queues to unweighted RR */
if (adapter->flags & FLAG_TARC_SET_BIT_ZERO) {
tarc = er32(TARC(0));
tarc |= 1;
ew32(TARC(0), tarc);
tarc = er32(TARC(1));
tarc |= 1;
ew32(TARC(1), tarc);
}
/* Setup Transmit Descriptor Settings for eop descriptor */
adapter->txd_cmd = E1000_TXD_CMD_EOP | E1000_TXD_CMD_IFCS;
/* only set IDE if we are delaying interrupts using the timers */
if (adapter->tx_int_delay)
adapter->txd_cmd |= E1000_TXD_CMD_IDE;
/* enable Report Status bit */
adapter->txd_cmd |= E1000_TXD_CMD_RS;
hw->mac.ops.config_collision_dist(hw);
}
/**
* e1000_setup_rctl - configure the receive control registers
* @adapter: Board private structure
**/
#define PAGE_USE_COUNT(S) (((S) >> PAGE_SHIFT) + \
(((S) & (PAGE_SIZE - 1)) ? 1 : 0))
static void e1000_setup_rctl(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 rctl, rfctl;
u32 pages = 0;
/* Workaround Si errata on 82579 - configure jumbo frame flow */
if (hw->mac.type == e1000_pch2lan) {
s32 ret_val;
if (adapter->netdev->mtu > ETH_DATA_LEN)
ret_val = e1000_lv_jumbo_workaround_ich8lan(hw, true);
else
ret_val = e1000_lv_jumbo_workaround_ich8lan(hw, false);
if (ret_val)
e_dbg("failed to enable jumbo frame workaround mode\n");
}
/* Program MC offset vector base */
rctl = er32(RCTL);
rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
rctl |= E1000_RCTL_EN | E1000_RCTL_BAM |
E1000_RCTL_LBM_NO | E1000_RCTL_RDMTS_HALF |
(adapter->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
/* Do not Store bad packets */
rctl &= ~E1000_RCTL_SBP;
/* Enable Long Packet receive */
if (adapter->netdev->mtu <= ETH_DATA_LEN)
rctl &= ~E1000_RCTL_LPE;
else
rctl |= E1000_RCTL_LPE;
/* Some systems expect that the CRC is included in SMBUS traffic. The
* hardware strips the CRC before sending to both SMBUS (BMC) and to
* host memory when this is enabled
*/
if (adapter->flags2 & FLAG2_CRC_STRIPPING)
rctl |= E1000_RCTL_SECRC;
/* Workaround Si errata on 82577 PHY - configure IPG for jumbos */
if ((hw->phy.type == e1000_phy_82577) && (rctl & E1000_RCTL_LPE)) {
u16 phy_data;
e1e_rphy(hw, PHY_REG(770, 26), &phy_data);
phy_data &= 0xfff8;
phy_data |= (1 << 2);
e1e_wphy(hw, PHY_REG(770, 26), phy_data);
e1e_rphy(hw, 22, &phy_data);
phy_data &= 0x0fff;
phy_data |= (1 << 14);
e1e_wphy(hw, 0x10, 0x2823);
e1e_wphy(hw, 0x11, 0x0003);
e1e_wphy(hw, 22, phy_data);
}
/* Setup buffer sizes */
rctl &= ~E1000_RCTL_SZ_4096;
rctl |= E1000_RCTL_BSEX;
switch (adapter->rx_buffer_len) {
case 2048:
default:
rctl |= E1000_RCTL_SZ_2048;
rctl &= ~E1000_RCTL_BSEX;
break;
case 4096:
rctl |= E1000_RCTL_SZ_4096;
break;
case 8192:
rctl |= E1000_RCTL_SZ_8192;
break;
case 16384:
rctl |= E1000_RCTL_SZ_16384;
break;
}
/* Enable Extended Status in all Receive Descriptors */
rfctl = er32(RFCTL);
rfctl |= E1000_RFCTL_EXTEN;
/*
* 82571 and greater support packet-split where the protocol
* header is placed in skb->data and the packet data is
* placed in pages hanging off of skb_shinfo(skb)->nr_frags.
* In the case of a non-split, skb->data is linearly filled,
* followed by the page buffers. Therefore, skb->data is
* sized to hold the largest protocol header.
*
* allocations using alloc_page take too long for regular MTU
* so only enable packet split for jumbo frames
*
* Using pages when the page size is greater than 16k wastes
* a lot of memory, since we allocate 3 pages at all times
* per packet.
*/
pages = PAGE_USE_COUNT(adapter->netdev->mtu);
if ((pages <= 3) && (PAGE_SIZE <= 16384) && (rctl & E1000_RCTL_LPE))
adapter->rx_ps_pages = pages;
else
adapter->rx_ps_pages = 0;
if (adapter->rx_ps_pages) {
u32 psrctl = 0;
/*
* disable packet split support for IPv6 extension headers,
* because some malformed IPv6 headers can hang the Rx
*/
rfctl |= (E1000_RFCTL_IPV6_EX_DIS |
E1000_RFCTL_NEW_IPV6_EXT_DIS);
/* Enable Packet split descriptors */
rctl |= E1000_RCTL_DTYP_PS;
psrctl |= adapter->rx_ps_bsize0 >>
E1000_PSRCTL_BSIZE0_SHIFT;
switch (adapter->rx_ps_pages) {
case 3:
psrctl |= PAGE_SIZE <<
E1000_PSRCTL_BSIZE3_SHIFT;
case 2:
psrctl |= PAGE_SIZE <<
E1000_PSRCTL_BSIZE2_SHIFT;
case 1:
psrctl |= PAGE_SIZE >>
E1000_PSRCTL_BSIZE1_SHIFT;
break;
}
ew32(PSRCTL, psrctl);
}
/* This is useful for sniffing bad packets. */
if (adapter->netdev->features & NETIF_F_RXALL) {
/* UPE and MPE will be handled by normal PROMISC logic
* in e1000e_set_rx_mode */
rctl |= (E1000_RCTL_SBP | /* Receive bad packets */
E1000_RCTL_BAM | /* RX All Bcast Pkts */
E1000_RCTL_PMCF); /* RX All MAC Ctrl Pkts */
rctl &= ~(E1000_RCTL_VFE | /* Disable VLAN filter */
E1000_RCTL_DPF | /* Allow filtered pause */
E1000_RCTL_CFIEN); /* Dis VLAN CFIEN Filter */
/* Do not mess with E1000_CTRL_VME, it affects transmit as well,
* and that breaks VLANs.
*/
}
ew32(RFCTL, rfctl);
ew32(RCTL, rctl);
/* just started the receive unit, no need to restart */
adapter->flags &= ~FLAG_RX_RESTART_NOW;
}
/**
* e1000_configure_rx - Configure Receive Unit after Reset
* @adapter: board private structure
*
* Configure the Rx unit of the MAC after a reset.
**/
static void e1000_configure_rx(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct e1000_ring *rx_ring = adapter->rx_ring;
u64 rdba;
u32 rdlen, rctl, rxcsum, ctrl_ext;
if (adapter->rx_ps_pages) {
/* this is a 32 byte descriptor */
rdlen = rx_ring->count *
sizeof(union e1000_rx_desc_packet_split);
adapter->clean_rx = e1000_clean_rx_irq_ps;
adapter->alloc_rx_buf = e1000_alloc_rx_buffers_ps;
} else if (adapter->netdev->mtu > ETH_FRAME_LEN + ETH_FCS_LEN) {
rdlen = rx_ring->count * sizeof(union e1000_rx_desc_extended);
adapter->clean_rx = e1000_clean_jumbo_rx_irq;
adapter->alloc_rx_buf = e1000_alloc_jumbo_rx_buffers;
} else {
rdlen = rx_ring->count * sizeof(union e1000_rx_desc_extended);
adapter->clean_rx = e1000_clean_rx_irq;
adapter->alloc_rx_buf = e1000_alloc_rx_buffers;
}
/* disable receives while setting up the descriptors */
rctl = er32(RCTL);
if (!(adapter->flags2 & FLAG2_NO_DISABLE_RX))
ew32(RCTL, rctl & ~E1000_RCTL_EN);
e1e_flush();
usleep_range(10000, 20000);
if (adapter->flags2 & FLAG2_DMA_BURST) {
/*
* set the writeback threshold (only takes effect if the RDTR
* is set). set GRAN=1 and write back up to 0x4 worth, and
* enable prefetching of 0x20 Rx descriptors
* granularity = 01
* wthresh = 04,
* hthresh = 04,
* pthresh = 0x20
*/
ew32(RXDCTL(0), E1000_RXDCTL_DMA_BURST_ENABLE);
ew32(RXDCTL(1), E1000_RXDCTL_DMA_BURST_ENABLE);
/*
* override the delay timers for enabling bursting, only if
* the value was not set by the user via module options
*/
if (adapter->rx_int_delay == DEFAULT_RDTR)
adapter->rx_int_delay = BURST_RDTR;
if (adapter->rx_abs_int_delay == DEFAULT_RADV)
adapter->rx_abs_int_delay = BURST_RADV;
}
/* set the Receive Delay Timer Register */
ew32(RDTR, adapter->rx_int_delay);
/* irq moderation */
ew32(RADV, adapter->rx_abs_int_delay);
if ((adapter->itr_setting != 0) && (adapter->itr != 0))
ew32(ITR, 1000000000 / (adapter->itr * 256));
ctrl_ext = er32(CTRL_EXT);
/* Auto-Mask interrupts upon ICR access */
ctrl_ext |= E1000_CTRL_EXT_IAME;
ew32(IAM, 0xffffffff);
ew32(CTRL_EXT, ctrl_ext);
e1e_flush();
/*
* Setup the HW Rx Head and Tail Descriptor Pointers and
* the Base and Length of the Rx Descriptor Ring
*/
rdba = rx_ring->dma;
ew32(RDBAL, (rdba & DMA_BIT_MASK(32)));
ew32(RDBAH, (rdba >> 32));
ew32(RDLEN, rdlen);
ew32(RDH, 0);
ew32(RDT, 0);
rx_ring->head = adapter->hw.hw_addr + E1000_RDH;
rx_ring->tail = adapter->hw.hw_addr + E1000_RDT;
/* Enable Receive Checksum Offload for TCP and UDP */
rxcsum = er32(RXCSUM);
if (adapter->netdev->features & NETIF_F_RXCSUM)
rxcsum |= E1000_RXCSUM_TUOFL;
else
rxcsum &= ~E1000_RXCSUM_TUOFL;
ew32(RXCSUM, rxcsum);
if (adapter->hw.mac.type == e1000_pch2lan) {
/*
* With jumbo frames, excessive C-state transition
* latencies result in dropped transactions.
*/
if (adapter->netdev->mtu > ETH_DATA_LEN) {
u32 rxdctl = er32(RXDCTL(0));
ew32(RXDCTL(0), rxdctl | 0x3);
pm_qos_update_request(&adapter->netdev->pm_qos_req, 55);
} else {
pm_qos_update_request(&adapter->netdev->pm_qos_req,
PM_QOS_DEFAULT_VALUE);
}
}
/* Enable Receives */
ew32(RCTL, rctl);
}
/**
* e1000e_write_mc_addr_list - write multicast addresses to MTA
* @netdev: network interface device structure
*
* Writes multicast address list to the MTA hash table.
* Returns: -ENOMEM on failure
* 0 on no addresses written
* X on writing X addresses to MTA
*/
static int e1000e_write_mc_addr_list(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u8 *mta_list;
int i;
if (netdev_mc_empty(netdev)) {
/* nothing to program, so clear mc list */
hw->mac.ops.update_mc_addr_list(hw, NULL, 0);
return 0;
}
mta_list = kzalloc(netdev_mc_count(netdev) * ETH_ALEN, GFP_ATOMIC);
if (!mta_list)
return -ENOMEM;
/* update_mc_addr_list expects a packed array of only addresses. */
i = 0;
netdev_for_each_mc_addr(ha, netdev)
memcpy(mta_list + (i++ * ETH_ALEN), ha->addr, ETH_ALEN);
hw->mac.ops.update_mc_addr_list(hw, mta_list, i);
kfree(mta_list);
return netdev_mc_count(netdev);
}
/**
* e1000e_write_uc_addr_list - write unicast addresses to RAR table
* @netdev: network interface device structure
*
* Writes unicast address list to the RAR table.
* Returns: -ENOMEM on failure/insufficient address space
* 0 on no addresses written
* X on writing X addresses to the RAR table
**/
static int e1000e_write_uc_addr_list(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
unsigned int rar_entries = hw->mac.rar_entry_count;
int count = 0;
/* save a rar entry for our hardware address */
rar_entries--;
/* save a rar entry for the LAA workaround */
if (adapter->flags & FLAG_RESET_OVERWRITES_LAA)
rar_entries--;
/* return ENOMEM indicating insufficient memory for addresses */
if (netdev_uc_count(netdev) > rar_entries)
return -ENOMEM;
if (!netdev_uc_empty(netdev) && rar_entries) {
struct netdev_hw_addr *ha;
/*
* write the addresses in reverse order to avoid write
* combining
*/
netdev_for_each_uc_addr(ha, netdev) {
if (!rar_entries)
break;
e1000e_rar_set(hw, ha->addr, rar_entries--);
count++;
}
}
/* zero out the remaining RAR entries not used above */
for (; rar_entries > 0; rar_entries--) {
ew32(RAH(rar_entries), 0);
ew32(RAL(rar_entries), 0);
}
e1e_flush();
return count;
}
/**
* e1000e_set_rx_mode - secondary unicast, Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The ndo_set_rx_mode entry point is called whenever the unicast or multicast
* address list or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper unicast, multicast,
* promiscuous mode, and all-multi behavior.
**/
static void e1000e_set_rx_mode(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 rctl;
/* Check for Promiscuous and All Multicast modes */
rctl = er32(RCTL);
/* clear the affected bits */
rctl &= ~(E1000_RCTL_UPE | E1000_RCTL_MPE);
if (netdev->flags & IFF_PROMISC) {
rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
/* Do not hardware filter VLANs in promisc mode */
e1000e_vlan_filter_disable(adapter);
} else {
int count;
if (netdev->flags & IFF_ALLMULTI) {
rctl |= E1000_RCTL_MPE;
} else {
/*
* Write addresses to the MTA, if the attempt fails
* then we should just turn on promiscuous mode so
* that we can at least receive multicast traffic
*/
count = e1000e_write_mc_addr_list(netdev);
if (count < 0)
rctl |= E1000_RCTL_MPE;
}
e1000e_vlan_filter_enable(adapter);
/*
* Write addresses to available RAR registers, if there is not
* sufficient space to store all the addresses then enable
* unicast promiscuous mode
*/
count = e1000e_write_uc_addr_list(netdev);
if (count < 0)
rctl |= E1000_RCTL_UPE;
}
ew32(RCTL, rctl);
if (netdev->features & NETIF_F_HW_VLAN_RX)
e1000e_vlan_strip_enable(adapter);
else
e1000e_vlan_strip_disable(adapter);
}
static void e1000e_setup_rss_hash(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 mrqc, rxcsum;
int i;
static const u32 rsskey[10] = {
0xda565a6d, 0xc20e5b25, 0x3d256741, 0xb08fa343, 0xcb2bcad0,
0xb4307bae, 0xa32dcb77, 0x0cf23080, 0x3bb7426a, 0xfa01acbe
};
/* Fill out hash function seed */
for (i = 0; i < 10; i++)
ew32(RSSRK(i), rsskey[i]);
/* Direct all traffic to queue 0 */
for (i = 0; i < 32; i++)
ew32(RETA(i), 0);
/*
* Disable raw packet checksumming so that RSS hash is placed in
* descriptor on writeback.
*/
rxcsum = er32(RXCSUM);
rxcsum |= E1000_RXCSUM_PCSD;
ew32(RXCSUM, rxcsum);
mrqc = (E1000_MRQC_RSS_FIELD_IPV4 |
E1000_MRQC_RSS_FIELD_IPV4_TCP |
E1000_MRQC_RSS_FIELD_IPV6 |
E1000_MRQC_RSS_FIELD_IPV6_TCP |
E1000_MRQC_RSS_FIELD_IPV6_TCP_EX);
ew32(MRQC, mrqc);
}
/**
* e1000_configure - configure the hardware for Rx and Tx
* @adapter: private board structure
**/
static void e1000_configure(struct e1000_adapter *adapter)
{
struct e1000_ring *rx_ring = adapter->rx_ring;
e1000e_set_rx_mode(adapter->netdev);
e1000_restore_vlan(adapter);
e1000_init_manageability_pt(adapter);
e1000_configure_tx(adapter);
if (adapter->netdev->features & NETIF_F_RXHASH)
e1000e_setup_rss_hash(adapter);
e1000_setup_rctl(adapter);
e1000_configure_rx(adapter);
adapter->alloc_rx_buf(rx_ring, e1000_desc_unused(rx_ring), GFP_KERNEL);
}
/**
* e1000e_power_up_phy - restore link in case the phy was powered down
* @adapter: address of board private structure
*
* The phy may be powered down to save power and turn off link when the
* driver is unloaded and wake on lan is not enabled (among others)
* *** this routine MUST be followed by a call to e1000e_reset ***
**/
void e1000e_power_up_phy(struct e1000_adapter *adapter)
{
if (adapter->hw.phy.ops.power_up)
adapter->hw.phy.ops.power_up(&adapter->hw);
adapter->hw.mac.ops.setup_link(&adapter->hw);
}
/**
* e1000_power_down_phy - Power down the PHY
*
* Power down the PHY so no link is implied when interface is down.
* The PHY cannot be powered down if management or WoL is active.
*/
static void e1000_power_down_phy(struct e1000_adapter *adapter)
{
/* WoL is enabled */
if (adapter->wol)
return;
if (adapter->hw.phy.ops.power_down)
adapter->hw.phy.ops.power_down(&adapter->hw);
}
/**
* e1000e_reset - bring the hardware into a known good state
*
* This function boots the hardware and enables some settings that
* require a configuration cycle of the hardware - those cannot be
* set/changed during runtime. After reset the device needs to be
* properly configured for Rx, Tx etc.
*/
void e1000e_reset(struct e1000_adapter *adapter)
{
struct e1000_mac_info *mac = &adapter->hw.mac;
struct e1000_fc_info *fc = &adapter->hw.fc;
struct e1000_hw *hw = &adapter->hw;
u32 tx_space, min_tx_space, min_rx_space;
u32 pba = adapter->pba;
u16 hwm;
/* reset Packet Buffer Allocation to default */
ew32(PBA, pba);
if (adapter->max_frame_size > ETH_FRAME_LEN + ETH_FCS_LEN) {
/*
* To maintain wire speed transmits, the Tx FIFO should be
* large enough to accommodate two full transmit packets,
* rounded up to the next 1KB and expressed in KB. Likewise,
* the Rx FIFO should be large enough to accommodate at least
* one full receive packet and is similarly rounded up and
* expressed in KB.
*/
pba = er32(PBA);
/* upper 16 bits has Tx packet buffer allocation size in KB */
tx_space = pba >> 16;
/* lower 16 bits has Rx packet buffer allocation size in KB */
pba &= 0xffff;
/*
* the Tx fifo also stores 16 bytes of information about the Tx
* but don't include ethernet FCS because hardware appends it
*/
min_tx_space = (adapter->max_frame_size +
sizeof(struct e1000_tx_desc) -
ETH_FCS_LEN) * 2;
min_tx_space = ALIGN(min_tx_space, 1024);
min_tx_space >>= 10;
/* software strips receive CRC, so leave room for it */
min_rx_space = adapter->max_frame_size;
min_rx_space = ALIGN(min_rx_space, 1024);
min_rx_space >>= 10;
/*
* If current Tx allocation is less than the min Tx FIFO size,
* and the min Tx FIFO size is less than the current Rx FIFO
* allocation, take space away from current Rx allocation
*/
if ((tx_space < min_tx_space) &&
((min_tx_space - tx_space) < pba)) {
pba -= min_tx_space - tx_space;
/*
* if short on Rx space, Rx wins and must trump Tx
* adjustment or use Early Receive if available
*/
if (pba < min_rx_space)
pba = min_rx_space;
}
ew32(PBA, pba);
}
/*
* flow control settings
*
* The high water mark must be low enough to fit one full frame
* (or the size used for early receive) above it in the Rx FIFO.
* Set it to the lower of:
* - 90% of the Rx FIFO size, and
* - the full Rx FIFO size minus one full frame
*/
if (adapter->flags & FLAG_DISABLE_FC_PAUSE_TIME)
fc->pause_time = 0xFFFF;
else
fc->pause_time = E1000_FC_PAUSE_TIME;
fc->send_xon = true;
fc->current_mode = fc->requested_mode;
switch (hw->mac.type) {
case e1000_ich9lan:
case e1000_ich10lan:
if (adapter->netdev->mtu > ETH_DATA_LEN) {
pba = 14;
ew32(PBA, pba);
fc->high_water = 0x2800;
fc->low_water = fc->high_water - 8;
break;
}
/* fall-through */
default:
hwm = min(((pba << 10) * 9 / 10),
((pba << 10) - adapter->max_frame_size));
fc->high_water = hwm & E1000_FCRTH_RTH; /* 8-byte granularity */
fc->low_water = fc->high_water - 8;
break;
case e1000_pchlan:
/*
* Workaround PCH LOM adapter hangs with certain network
* loads. If hangs persist, try disabling Tx flow control.
*/
if (adapter->netdev->mtu > ETH_DATA_LEN) {
fc->high_water = 0x3500;
fc->low_water = 0x1500;
} else {
fc->high_water = 0x5000;
fc->low_water = 0x3000;
}
fc->refresh_time = 0x1000;
break;
case e1000_pch2lan:
fc->high_water = 0x05C20;
fc->low_water = 0x05048;
fc->pause_time = 0x0650;
fc->refresh_time = 0x0400;
if (adapter->netdev->mtu > ETH_DATA_LEN) {
pba = 14;
ew32(PBA, pba);
}
break;
}
/*
* Disable Adaptive Interrupt Moderation if 2 full packets cannot
* fit in receive buffer.
*/
if (adapter->itr_setting & 0x3) {
if ((adapter->max_frame_size * 2) > (pba << 10)) {
if (!(adapter->flags2 & FLAG2_DISABLE_AIM)) {
dev_info(&adapter->pdev->dev,
"Interrupt Throttle Rate turned off\n");
adapter->flags2 |= FLAG2_DISABLE_AIM;
ew32(ITR, 0);
}
} else if (adapter->flags2 & FLAG2_DISABLE_AIM) {
dev_info(&adapter->pdev->dev,
"Interrupt Throttle Rate turned on\n");
adapter->flags2 &= ~FLAG2_DISABLE_AIM;
adapter->itr = 20000;
ew32(ITR, 1000000000 / (adapter->itr * 256));
}
}
/* Allow time for pending master requests to run */
mac->ops.reset_hw(hw);
/*
* For parts with AMT enabled, let the firmware know
* that the network interface is in control
*/
if (adapter->flags & FLAG_HAS_AMT)
e1000e_get_hw_control(adapter);
ew32(WUC, 0);
if (mac->ops.init_hw(hw))
e_err("Hardware Error\n");
e1000_update_mng_vlan(adapter);
/* Enable h/w to recognize an 802.1Q VLAN Ethernet packet */
ew32(VET, ETH_P_8021Q);
e1000e_reset_adaptive(hw);
if (!netif_running(adapter->netdev) &&
!test_bit(__E1000_TESTING, &adapter->state)) {
e1000_power_down_phy(adapter);
return;
}
e1000_get_phy_info(hw);
if ((adapter->flags & FLAG_HAS_SMART_POWER_DOWN) &&
!(adapter->flags & FLAG_SMART_POWER_DOWN)) {
u16 phy_data = 0;
/*
* speed up time to link by disabling smart power down, ignore
* the return value of this function because there is nothing
* different we would do if it failed
*/
e1e_rphy(hw, IGP02E1000_PHY_POWER_MGMT, &phy_data);
phy_data &= ~IGP02E1000_PM_SPD;
e1e_wphy(hw, IGP02E1000_PHY_POWER_MGMT, phy_data);
}
}
int e1000e_up(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
/* hardware has been reset, we need to reload some things */
e1000_configure(adapter);
clear_bit(__E1000_DOWN, &adapter->state);
if (adapter->msix_entries)
e1000_configure_msix(adapter);
e1000_irq_enable(adapter);
netif_start_queue(adapter->netdev);
/* fire a link change interrupt to start the watchdog */
if (adapter->msix_entries)
ew32(ICS, E1000_ICS_LSC | E1000_ICR_OTHER);
else
ew32(ICS, E1000_ICS_LSC);
return 0;
}
static void e1000e_flush_descriptors(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
if (!(adapter->flags2 & FLAG2_DMA_BURST))
return;
/* flush pending descriptor writebacks to memory */
ew32(TIDV, adapter->tx_int_delay | E1000_TIDV_FPD);
ew32(RDTR, adapter->rx_int_delay | E1000_RDTR_FPD);
/* execute the writes immediately */
e1e_flush();
/*
* due to rare timing issues, write to TIDV/RDTR again to ensure the
* write is successful
*/
ew32(TIDV, adapter->tx_int_delay | E1000_TIDV_FPD);
ew32(RDTR, adapter->rx_int_delay | E1000_RDTR_FPD);
/* execute the writes immediately */
e1e_flush();
}
static void e1000e_update_stats(struct e1000_adapter *adapter);
void e1000e_down(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
u32 tctl, rctl;
/*
* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer
*/
set_bit(__E1000_DOWN, &adapter->state);
/* disable receives in the hardware */
rctl = er32(RCTL);
if (!(adapter->flags2 & FLAG2_NO_DISABLE_RX))
ew32(RCTL, rctl & ~E1000_RCTL_EN);
/* flush and sleep below */
netif_stop_queue(netdev);
/* disable transmits in the hardware */
tctl = er32(TCTL);
tctl &= ~E1000_TCTL_EN;
ew32(TCTL, tctl);
/* flush both disables and wait for them to finish */
e1e_flush();
usleep_range(10000, 20000);
e1000_irq_disable(adapter);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_info_timer);
netif_carrier_off(netdev);
spin_lock(&adapter->stats64_lock);
e1000e_update_stats(adapter);
spin_unlock(&adapter->stats64_lock);
e1000e_flush_descriptors(adapter);
e1000_clean_tx_ring(adapter->tx_ring);
e1000_clean_rx_ring(adapter->rx_ring);
adapter->link_speed = 0;
adapter->link_duplex = 0;
if (!pci_channel_offline(adapter->pdev))
e1000e_reset(adapter);
/*
* TODO: for power management, we could drop the link and
* pci_disable_device here.
*/
}
void e1000e_reinit_locked(struct e1000_adapter *adapter)
{
might_sleep();
while (test_and_set_bit(__E1000_RESETTING, &adapter->state))
usleep_range(1000, 2000);
e1000e_down(adapter);
e1000e_up(adapter);
clear_bit(__E1000_RESETTING, &adapter->state);
}
/**
* e1000_sw_init - Initialize general software structures (struct e1000_adapter)
* @adapter: board private structure to initialize
*
* e1000_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
**/
static int __devinit e1000_sw_init(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
adapter->rx_buffer_len = ETH_FRAME_LEN + VLAN_HLEN + ETH_FCS_LEN;
adapter->rx_ps_bsize0 = 128;
adapter->max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN;
adapter->min_frame_size = ETH_ZLEN + ETH_FCS_LEN;
adapter->tx_ring_count = E1000_DEFAULT_TXD;
adapter->rx_ring_count = E1000_DEFAULT_RXD;
spin_lock_init(&adapter->stats64_lock);
e1000e_set_interrupt_capability(adapter);
if (e1000_alloc_queues(adapter))
return -ENOMEM;
/* Explicitly disable IRQ since the NIC can be in any state. */
e1000_irq_disable(adapter);
set_bit(__E1000_DOWN, &adapter->state);
return 0;
}
/**
* e1000_intr_msi_test - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static irqreturn_t e1000_intr_msi_test(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 icr = er32(ICR);
e_dbg("icr is %08X\n", icr);
if (icr & E1000_ICR_RXSEQ) {
adapter->flags &= ~FLAG_MSI_TEST_FAILED;
wmb();
}
return IRQ_HANDLED;
}
/**
* e1000_test_msi_interrupt - Returns 0 for successful test
* @adapter: board private struct
*
* code flow taken from tg3.c
**/
static int e1000_test_msi_interrupt(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
int err;
/* poll_enable hasn't been called yet, so don't need disable */
/* clear any pending events */
er32(ICR);
/* free the real vector and request a test handler */
e1000_free_irq(adapter);
e1000e_reset_interrupt_capability(adapter);
/* Assume that the test fails, if it succeeds then the test
* MSI irq handler will unset this flag */
adapter->flags |= FLAG_MSI_TEST_FAILED;
err = pci_enable_msi(adapter->pdev);
if (err)
goto msi_test_failed;
err = request_irq(adapter->pdev->irq, e1000_intr_msi_test, 0,
netdev->name, netdev);
if (err) {
pci_disable_msi(adapter->pdev);
goto msi_test_failed;
}
wmb();
e1000_irq_enable(adapter);
/* fire an unusual interrupt on the test handler */
ew32(ICS, E1000_ICS_RXSEQ);
e1e_flush();
msleep(100);
e1000_irq_disable(adapter);
rmb();
if (adapter->flags & FLAG_MSI_TEST_FAILED) {
adapter->int_mode = E1000E_INT_MODE_LEGACY;
e_info("MSI interrupt test failed, using legacy interrupt.\n");
} else {
e_dbg("MSI interrupt test succeeded!\n");
}
free_irq(adapter->pdev->irq, netdev);
pci_disable_msi(adapter->pdev);
msi_test_failed:
e1000e_set_interrupt_capability(adapter);
return e1000_request_irq(adapter);
}
/**
* e1000_test_msi - Returns 0 if MSI test succeeds or INTx mode is restored
* @adapter: board private struct
*
* code flow taken from tg3.c, called with e1000 interrupts disabled.
**/
static int e1000_test_msi(struct e1000_adapter *adapter)
{
int err;
u16 pci_cmd;
if (!(adapter->flags & FLAG_MSI_ENABLED))
return 0;
/* disable SERR in case the MSI write causes a master abort */
pci_read_config_word(adapter->pdev, PCI_COMMAND, &pci_cmd);
if (pci_cmd & PCI_COMMAND_SERR)
pci_write_config_word(adapter->pdev, PCI_COMMAND,
pci_cmd & ~PCI_COMMAND_SERR);
err = e1000_test_msi_interrupt(adapter);
/* re-enable SERR */
if (pci_cmd & PCI_COMMAND_SERR) {
pci_read_config_word(adapter->pdev, PCI_COMMAND, &pci_cmd);
pci_cmd |= PCI_COMMAND_SERR;
pci_write_config_word(adapter->pdev, PCI_COMMAND, pci_cmd);
}
return err;
}
/**
* e1000_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
**/
static int e1000_open(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
int err;
/* disallow open during test */
if (test_bit(__E1000_TESTING, &adapter->state))
return -EBUSY;
pm_runtime_get_sync(&pdev->dev);
netif_carrier_off(netdev);
/* allocate transmit descriptors */
err = e1000e_setup_tx_resources(adapter->tx_ring);
if (err)
goto err_setup_tx;
/* allocate receive descriptors */
err = e1000e_setup_rx_resources(adapter->rx_ring);
if (err)
goto err_setup_rx;
/*
* If AMT is enabled, let the firmware know that the network
* interface is now open and reset the part to a known state.
*/
if (adapter->flags & FLAG_HAS_AMT) {
e1000e_get_hw_control(adapter);
e1000e_reset(adapter);
}
e1000e_power_up_phy(adapter);
adapter->mng_vlan_id = E1000_MNG_VLAN_NONE;
if ((adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN))
e1000_update_mng_vlan(adapter);
/* DMA latency requirement to workaround jumbo issue */
if (adapter->hw.mac.type == e1000_pch2lan)
pm_qos_add_request(&adapter->netdev->pm_qos_req,
PM_QOS_CPU_DMA_LATENCY,
PM_QOS_DEFAULT_VALUE);
/*
* before we allocate an interrupt, we must be ready to handle it.
* Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt
* as soon as we call pci_request_irq, so we have to setup our
* clean_rx handler before we do so.
*/
e1000_configure(adapter);
err = e1000_request_irq(adapter);
if (err)
goto err_req_irq;
/*
* Work around PCIe errata with MSI interrupts causing some chipsets to
* ignore e1000e MSI messages, which means we need to test our MSI
* interrupt now
*/
if (adapter->int_mode != E1000E_INT_MODE_LEGACY) {
err = e1000_test_msi(adapter);
if (err) {
e_err("Interrupt allocation failed\n");
goto err_req_irq;
}
}
/* From here on the code is the same as e1000e_up() */
clear_bit(__E1000_DOWN, &adapter->state);
napi_enable(&adapter->napi);
e1000_irq_enable(adapter);
adapter->tx_hang_recheck = false;
netif_start_queue(netdev);
adapter->idle_check = true;
pm_runtime_put(&pdev->dev);
/* fire a link status change interrupt to start the watchdog */
if (adapter->msix_entries)
ew32(ICS, E1000_ICS_LSC | E1000_ICR_OTHER);
else
ew32(ICS, E1000_ICS_LSC);
return 0;
err_req_irq:
e1000e_release_hw_control(adapter);
e1000_power_down_phy(adapter);
e1000e_free_rx_resources(adapter->rx_ring);
err_setup_rx:
e1000e_free_tx_resources(adapter->tx_ring);
err_setup_tx:
e1000e_reset(adapter);
pm_runtime_put_sync(&pdev->dev);
return err;
}
/**
* e1000_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
**/
static int e1000_close(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct pci_dev *pdev = adapter->pdev;
int count = E1000_CHECK_RESET_COUNT;
while (test_bit(__E1000_RESETTING, &adapter->state) && count--)
usleep_range(10000, 20000);
WARN_ON(test_bit(__E1000_RESETTING, &adapter->state));
pm_runtime_get_sync(&pdev->dev);
napi_disable(&adapter->napi);
if (!test_bit(__E1000_DOWN, &adapter->state)) {
e1000e_down(adapter);
e1000_free_irq(adapter);
}
e1000_power_down_phy(adapter);
e1000e_free_tx_resources(adapter->tx_ring);
e1000e_free_rx_resources(adapter->rx_ring);
/*
* kill manageability vlan ID if supported, but not if a vlan with
* the same ID is registered on the host OS (let 8021q kill it)
*/
if (adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN)
e1000_vlan_rx_kill_vid(netdev, adapter->mng_vlan_id);
/*
* If AMT is enabled, let the firmware know that the network
* interface is now closed
*/
if ((adapter->flags & FLAG_HAS_AMT) &&
!test_bit(__E1000_TESTING, &adapter->state))
e1000e_release_hw_control(adapter);
if (adapter->hw.mac.type == e1000_pch2lan)
pm_qos_remove_request(&adapter->netdev->pm_qos_req);
pm_runtime_put_sync(&pdev->dev);
return 0;
}
/**
* e1000_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
**/
static int e1000_set_mac(struct net_device *netdev, void *p)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
memcpy(adapter->hw.mac.addr, addr->sa_data, netdev->addr_len);
e1000e_rar_set(&adapter->hw, adapter->hw.mac.addr, 0);
if (adapter->flags & FLAG_RESET_OVERWRITES_LAA) {
/* activate the work around */
e1000e_set_laa_state_82571(&adapter->hw, 1);
/*
* Hold a copy of the LAA in RAR[14] This is done so that
* between the time RAR[0] gets clobbered and the time it
* gets fixed (in e1000_watchdog), the actual LAA is in one
* of the RARs and no incoming packets directed to this port
* are dropped. Eventually the LAA will be in RAR[0] and
* RAR[14]
*/
e1000e_rar_set(&adapter->hw,
adapter->hw.mac.addr,
adapter->hw.mac.rar_entry_count - 1);
}
return 0;
}
/**
* e1000e_update_phy_task - work thread to update phy
* @work: pointer to our work struct
*
* this worker thread exists because we must acquire a
* semaphore to read the phy, which we could msleep while
* waiting for it, and we can't msleep in a timer.
**/
static void e1000e_update_phy_task(struct work_struct *work)
{
struct e1000_adapter *adapter = container_of(work,
struct e1000_adapter, update_phy_task);
if (test_bit(__E1000_DOWN, &adapter->state))
return;
e1000_get_phy_info(&adapter->hw);
}
/*
* Need to wait a few seconds after link up to get diagnostic information from
* the phy
*/
static void e1000_update_phy_info(unsigned long data)
{
struct e1000_adapter *adapter = (struct e1000_adapter *) data;
if (test_bit(__E1000_DOWN, &adapter->state))
return;
schedule_work(&adapter->update_phy_task);
}
/**
* e1000e_update_phy_stats - Update the PHY statistics counters
* @adapter: board private structure
*
* Read/clear the upper 16-bit PHY registers and read/accumulate lower
**/
static void e1000e_update_phy_stats(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
s32 ret_val;
u16 phy_data;
ret_val = hw->phy.ops.acquire(hw);
if (ret_val)
return;
/*
* A page set is expensive so check if already on desired page.
* If not, set to the page with the PHY status registers.
*/
hw->phy.addr = 1;
ret_val = e1000e_read_phy_reg_mdic(hw, IGP01E1000_PHY_PAGE_SELECT,
&phy_data);
if (ret_val)
goto release;
if (phy_data != (HV_STATS_PAGE << IGP_PAGE_SHIFT)) {
ret_val = hw->phy.ops.set_page(hw,
HV_STATS_PAGE << IGP_PAGE_SHIFT);
if (ret_val)
goto release;
}
/* Single Collision Count */
hw->phy.ops.read_reg_page(hw, HV_SCC_UPPER, &phy_data);
ret_val = hw->phy.ops.read_reg_page(hw, HV_SCC_LOWER, &phy_data);
if (!ret_val)
adapter->stats.scc += phy_data;
/* Excessive Collision Count */
hw->phy.ops.read_reg_page(hw, HV_ECOL_UPPER, &phy_data);
ret_val = hw->phy.ops.read_reg_page(hw, HV_ECOL_LOWER, &phy_data);
if (!ret_val)
adapter->stats.ecol += phy_data;
/* Multiple Collision Count */
hw->phy.ops.read_reg_page(hw, HV_MCC_UPPER, &phy_data);
ret_val = hw->phy.ops.read_reg_page(hw, HV_MCC_LOWER, &phy_data);
if (!ret_val)
adapter->stats.mcc += phy_data;
/* Late Collision Count */
hw->phy.ops.read_reg_page(hw, HV_LATECOL_UPPER, &phy_data);
ret_val = hw->phy.ops.read_reg_page(hw, HV_LATECOL_LOWER, &phy_data);
if (!ret_val)
adapter->stats.latecol += phy_data;
/* Collision Count - also used for adaptive IFS */
hw->phy.ops.read_reg_page(hw, HV_COLC_UPPER, &phy_data);
ret_val = hw->phy.ops.read_reg_page(hw, HV_COLC_LOWER, &phy_data);
if (!ret_val)
hw->mac.collision_delta = phy_data;
/* Defer Count */
hw->phy.ops.read_reg_page(hw, HV_DC_UPPER, &phy_data);
ret_val = hw->phy.ops.read_reg_page(hw, HV_DC_LOWER, &phy_data);
if (!ret_val)
adapter->stats.dc += phy_data;
/* Transmit with no CRS */
hw->phy.ops.read_reg_page(hw, HV_TNCRS_UPPER, &phy_data);
ret_val = hw->phy.ops.read_reg_page(hw, HV_TNCRS_LOWER, &phy_data);
if (!ret_val)
adapter->stats.tncrs += phy_data;
release:
hw->phy.ops.release(hw);
}
/**
* e1000e_update_stats - Update the board statistics counters
* @adapter: board private structure
**/
static void e1000e_update_stats(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
/*
* Prevent stats update while adapter is being reset, or if the pci
* connection is down.
*/
if (adapter->link_speed == 0)
return;
if (pci_channel_offline(pdev))
return;
adapter->stats.crcerrs += er32(CRCERRS);
adapter->stats.gprc += er32(GPRC);
adapter->stats.gorc += er32(GORCL);
er32(GORCH); /* Clear gorc */
adapter->stats.bprc += er32(BPRC);
adapter->stats.mprc += er32(MPRC);
adapter->stats.roc += er32(ROC);
adapter->stats.mpc += er32(MPC);
/* Half-duplex statistics */
if (adapter->link_duplex == HALF_DUPLEX) {
if (adapter->flags2 & FLAG2_HAS_PHY_STATS) {
e1000e_update_phy_stats(adapter);
} else {
adapter->stats.scc += er32(SCC);
adapter->stats.ecol += er32(ECOL);
adapter->stats.mcc += er32(MCC);
adapter->stats.latecol += er32(LATECOL);
adapter->stats.dc += er32(DC);
hw->mac.collision_delta = er32(COLC);
if ((hw->mac.type != e1000_82574) &&
(hw->mac.type != e1000_82583))
adapter->stats.tncrs += er32(TNCRS);
}
adapter->stats.colc += hw->mac.collision_delta;
}
adapter->stats.xonrxc += er32(XONRXC);
adapter->stats.xontxc += er32(XONTXC);
adapter->stats.xoffrxc += er32(XOFFRXC);
adapter->stats.xofftxc += er32(XOFFTXC);
adapter->stats.gptc += er32(GPTC);
adapter->stats.gotc += er32(GOTCL);
er32(GOTCH); /* Clear gotc */
adapter->stats.rnbc += er32(RNBC);
adapter->stats.ruc += er32(RUC);
adapter->stats.mptc += er32(MPTC);
adapter->stats.bptc += er32(BPTC);
/* used for adaptive IFS */
hw->mac.tx_packet_delta = er32(TPT);
adapter->stats.tpt += hw->mac.tx_packet_delta;
adapter->stats.algnerrc += er32(ALGNERRC);
adapter->stats.rxerrc += er32(RXERRC);
adapter->stats.cexterr += er32(CEXTERR);
adapter->stats.tsctc += er32(TSCTC);
adapter->stats.tsctfc += er32(TSCTFC);
/* Fill out the OS statistics structure */
netdev->stats.multicast = adapter->stats.mprc;
netdev->stats.collisions = adapter->stats.colc;
/* Rx Errors */
/*
* RLEC on some newer hardware can be incorrect so build
* our own version based on RUC and ROC
*/
netdev->stats.rx_errors = adapter->stats.rxerrc +
adapter->stats.crcerrs + adapter->stats.algnerrc +
adapter->stats.ruc + adapter->stats.roc +
adapter->stats.cexterr;
netdev->stats.rx_length_errors = adapter->stats.ruc +
adapter->stats.roc;
netdev->stats.rx_crc_errors = adapter->stats.crcerrs;
netdev->stats.rx_frame_errors = adapter->stats.algnerrc;
netdev->stats.rx_missed_errors = adapter->stats.mpc;
/* Tx Errors */
netdev->stats.tx_errors = adapter->stats.ecol +
adapter->stats.latecol;
netdev->stats.tx_aborted_errors = adapter->stats.ecol;
netdev->stats.tx_window_errors = adapter->stats.latecol;
netdev->stats.tx_carrier_errors = adapter->stats.tncrs;
/* Tx Dropped needs to be maintained elsewhere */
/* Management Stats */
adapter->stats.mgptc += er32(MGTPTC);
adapter->stats.mgprc += er32(MGTPRC);
adapter->stats.mgpdc += er32(MGTPDC);
}
/**
* e1000_phy_read_status - Update the PHY register status snapshot
* @adapter: board private structure
**/
static void e1000_phy_read_status(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct e1000_phy_regs *phy = &adapter->phy_regs;
if ((er32(STATUS) & E1000_STATUS_LU) &&
(adapter->hw.phy.media_type == e1000_media_type_copper)) {
int ret_val;
ret_val = e1e_rphy(hw, PHY_CONTROL, &phy->bmcr);
ret_val |= e1e_rphy(hw, PHY_STATUS, &phy->bmsr);
ret_val |= e1e_rphy(hw, PHY_AUTONEG_ADV, &phy->advertise);
ret_val |= e1e_rphy(hw, PHY_LP_ABILITY, &phy->lpa);
ret_val |= e1e_rphy(hw, PHY_AUTONEG_EXP, &phy->expansion);
ret_val |= e1e_rphy(hw, PHY_1000T_CTRL, &phy->ctrl1000);
ret_val |= e1e_rphy(hw, PHY_1000T_STATUS, &phy->stat1000);
ret_val |= e1e_rphy(hw, PHY_EXT_STATUS, &phy->estatus);
if (ret_val)
e_warn("Error reading PHY register\n");
} else {
/*
* Do not read PHY registers if link is not up
* Set values to typical power-on defaults
*/
phy->bmcr = (BMCR_SPEED1000 | BMCR_ANENABLE | BMCR_FULLDPLX);
phy->bmsr = (BMSR_100FULL | BMSR_100HALF | BMSR_10FULL |
BMSR_10HALF | BMSR_ESTATEN | BMSR_ANEGCAPABLE |
BMSR_ERCAP);
phy->advertise = (ADVERTISE_PAUSE_ASYM | ADVERTISE_PAUSE_CAP |
ADVERTISE_ALL | ADVERTISE_CSMA);
phy->lpa = 0;
phy->expansion = EXPANSION_ENABLENPAGE;
phy->ctrl1000 = ADVERTISE_1000FULL;
phy->stat1000 = 0;
phy->estatus = (ESTATUS_1000_TFULL | ESTATUS_1000_THALF);
}
}
static void e1000_print_link_info(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ctrl = er32(CTRL);
/* Link status message must follow this format for user tools */
printk(KERN_INFO "e1000e: %s NIC Link is Up %d Mbps %s Duplex, Flow Control: %s\n",
adapter->netdev->name,
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ? "Full" : "Half",
(ctrl & E1000_CTRL_TFCE) && (ctrl & E1000_CTRL_RFCE) ? "Rx/Tx" :
(ctrl & E1000_CTRL_RFCE) ? "Rx" :
(ctrl & E1000_CTRL_TFCE) ? "Tx" : "None");
}
static bool e1000e_has_link(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
bool link_active = false;
s32 ret_val = 0;
/*
* get_link_status is set on LSC (link status) interrupt or
* Rx sequence error interrupt. get_link_status will stay
* false until the check_for_link establishes link
* for copper adapters ONLY
*/
switch (hw->phy.media_type) {
case e1000_media_type_copper:
if (hw->mac.get_link_status) {
ret_val = hw->mac.ops.check_for_link(hw);
link_active = !hw->mac.get_link_status;
} else {
link_active = true;
}
break;
case e1000_media_type_fiber:
ret_val = hw->mac.ops.check_for_link(hw);
link_active = !!(er32(STATUS) & E1000_STATUS_LU);
break;
case e1000_media_type_internal_serdes:
ret_val = hw->mac.ops.check_for_link(hw);
link_active = adapter->hw.mac.serdes_has_link;
break;
default:
case e1000_media_type_unknown:
break;
}
if ((ret_val == E1000_ERR_PHY) && (hw->phy.type == e1000_phy_igp_3) &&
(er32(CTRL) & E1000_PHY_CTRL_GBE_DISABLE)) {
/* See e1000_kmrn_lock_loss_workaround_ich8lan() */
e_info("Gigabit has been disabled, downgrading speed\n");
}
return link_active;
}
static void e1000e_enable_receives(struct e1000_adapter *adapter)
{
/* make sure the receive unit is started */
if ((adapter->flags & FLAG_RX_NEEDS_RESTART) &&
(adapter->flags & FLAG_RX_RESTART_NOW)) {
struct e1000_hw *hw = &adapter->hw;
u32 rctl = er32(RCTL);
ew32(RCTL, rctl | E1000_RCTL_EN);
adapter->flags &= ~FLAG_RX_RESTART_NOW;
}
}
static void e1000e_check_82574_phy_workaround(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
/*
* With 82574 controllers, PHY needs to be checked periodically
* for hung state and reset, if two calls return true
*/
if (e1000_check_phy_82574(hw))
adapter->phy_hang_count++;
else
adapter->phy_hang_count = 0;
if (adapter->phy_hang_count > 1) {
adapter->phy_hang_count = 0;
schedule_work(&adapter->reset_task);
}
}
/**
* e1000_watchdog - Timer Call-back
* @data: pointer to adapter cast into an unsigned long
**/
static void e1000_watchdog(unsigned long data)
{
struct e1000_adapter *adapter = (struct e1000_adapter *) data;
/* Do the rest outside of interrupt context */
schedule_work(&adapter->watchdog_task);
/* TODO: make this use queue_delayed_work() */
}
static void e1000_watchdog_task(struct work_struct *work)
{
struct e1000_adapter *adapter = container_of(work,
struct e1000_adapter, watchdog_task);
struct net_device *netdev = adapter->netdev;
struct e1000_mac_info *mac = &adapter->hw.mac;
struct e1000_phy_info *phy = &adapter->hw.phy;
struct e1000_ring *tx_ring = adapter->tx_ring;
struct e1000_hw *hw = &adapter->hw;
u32 link, tctl;
if (test_bit(__E1000_DOWN, &adapter->state))
return;
link = e1000e_has_link(adapter);
if ((netif_carrier_ok(netdev)) && link) {
/* Cancel scheduled suspend requests. */
pm_runtime_resume(netdev->dev.parent);
e1000e_enable_receives(adapter);
goto link_up;
}
if ((e1000e_enable_tx_pkt_filtering(hw)) &&
(adapter->mng_vlan_id != adapter->hw.mng_cookie.vlan_id))
e1000_update_mng_vlan(adapter);
if (link) {
if (!netif_carrier_ok(netdev)) {
bool txb2b = true;
/* Cancel scheduled suspend requests. */
pm_runtime_resume(netdev->dev.parent);
/* update snapshot of PHY registers on LSC */
e1000_phy_read_status(adapter);
mac->ops.get_link_up_info(&adapter->hw,
&adapter->link_speed,
&adapter->link_duplex);
e1000_print_link_info(adapter);
/*
* On supported PHYs, check for duplex mismatch only
* if link has autonegotiated at 10/100 half
*/
if ((hw->phy.type == e1000_phy_igp_3 ||
hw->phy.type == e1000_phy_bm) &&
(hw->mac.autoneg == true) &&
(adapter->link_speed == SPEED_10 ||
adapter->link_speed == SPEED_100) &&
(adapter->link_duplex == HALF_DUPLEX)) {
u16 autoneg_exp;
e1e_rphy(hw, PHY_AUTONEG_EXP, &autoneg_exp);
if (!(autoneg_exp & NWAY_ER_LP_NWAY_CAPS))
e_info("Autonegotiated half duplex but link partner cannot autoneg. Try forcing full duplex if link gets many collisions.\n");
}
/* adjust timeout factor according to speed/duplex */
adapter->tx_timeout_factor = 1;
switch (adapter->link_speed) {
case SPEED_10:
txb2b = false;
adapter->tx_timeout_factor = 16;
break;
case SPEED_100:
txb2b = false;
adapter->tx_timeout_factor = 10;
break;
}
/*
* workaround: re-program speed mode bit after
* link-up event
*/
if ((adapter->flags & FLAG_TARC_SPEED_MODE_BIT) &&
!txb2b) {
u32 tarc0;
tarc0 = er32(TARC(0));
tarc0 &= ~SPEED_MODE_BIT;
ew32(TARC(0), tarc0);
}
/*
* disable TSO for pcie and 10/100 speeds, to avoid
* some hardware issues
*/
if (!(adapter->flags & FLAG_TSO_FORCE)) {
switch (adapter->link_speed) {
case SPEED_10:
case SPEED_100:
e_info("10/100 speed: disabling TSO\n");
netdev->features &= ~NETIF_F_TSO;
netdev->features &= ~NETIF_F_TSO6;
break;
case SPEED_1000:
netdev->features |= NETIF_F_TSO;
netdev->features |= NETIF_F_TSO6;
break;
default:
/* oops */
break;
}
}
/*
* enable transmits in the hardware, need to do this
* after setting TARC(0)
*/
tctl = er32(TCTL);
tctl |= E1000_TCTL_EN;
ew32(TCTL, tctl);
/*
* Perform any post-link-up configuration before
* reporting link up.
*/
if (phy->ops.cfg_on_link_up)
phy->ops.cfg_on_link_up(hw);
netif_carrier_on(netdev);
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->phy_info_timer,
round_jiffies(jiffies + 2 * HZ));
}
} else {
if (netif_carrier_ok(netdev)) {
adapter->link_speed = 0;
adapter->link_duplex = 0;
/* Link status message must follow this format */
printk(KERN_INFO "e1000e: %s NIC Link is Down\n",
adapter->netdev->name);
netif_carrier_off(netdev);
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->phy_info_timer,
round_jiffies(jiffies + 2 * HZ));
if (adapter->flags & FLAG_RX_NEEDS_RESTART)
schedule_work(&adapter->reset_task);
else
pm_schedule_suspend(netdev->dev.parent,
LINK_TIMEOUT);
}
}
link_up:
spin_lock(&adapter->stats64_lock);
e1000e_update_stats(adapter);
mac->tx_packet_delta = adapter->stats.tpt - adapter->tpt_old;
adapter->tpt_old = adapter->stats.tpt;
mac->collision_delta = adapter->stats.colc - adapter->colc_old;
adapter->colc_old = adapter->stats.colc;
adapter->gorc = adapter->stats.gorc - adapter->gorc_old;
adapter->gorc_old = adapter->stats.gorc;
adapter->gotc = adapter->stats.gotc - adapter->gotc_old;
adapter->gotc_old = adapter->stats.gotc;
spin_unlock(&adapter->stats64_lock);
e1000e_update_adaptive(&adapter->hw);
if (!netif_carrier_ok(netdev) &&
(e1000_desc_unused(tx_ring) + 1 < tx_ring->count)) {
/*
* We've lost link, so the controller stops DMA,
* but we've got queued Tx work that's never going
* to get done, so reset controller to flush Tx.
* (Do the reset outside of interrupt context).
*/
schedule_work(&adapter->reset_task);
/* return immediately since reset is imminent */
return;
}
/* Simple mode for Interrupt Throttle Rate (ITR) */
if (adapter->itr_setting == 4) {
/*
* Symmetric Tx/Rx gets a reduced ITR=2000;
* Total asymmetrical Tx or Rx gets ITR=8000;
* everyone else is between 2000-8000.
*/
u32 goc = (adapter->gotc + adapter->gorc) / 10000;
u32 dif = (adapter->gotc > adapter->gorc ?
adapter->gotc - adapter->gorc :
adapter->gorc - adapter->gotc) / 10000;
u32 itr = goc > 0 ? (dif * 6000 / goc + 2000) : 8000;
ew32(ITR, 1000000000 / (itr * 256));
}
/* Cause software interrupt to ensure Rx ring is cleaned */
if (adapter->msix_entries)
ew32(ICS, adapter->rx_ring->ims_val);
else
ew32(ICS, E1000_ICS_RXDMT0);
/* flush pending descriptors to memory before detecting Tx hang */
e1000e_flush_descriptors(adapter);
/* Force detection of hung controller every watchdog period */
adapter->detect_tx_hung = true;
/*
* With 82571 controllers, LAA may be overwritten due to controller
* reset from the other port. Set the appropriate LAA in RAR[0]
*/
if (e1000e_get_laa_state_82571(hw))
e1000e_rar_set(hw, adapter->hw.mac.addr, 0);
if (adapter->flags2 & FLAG2_CHECK_PHY_HANG)
e1000e_check_82574_phy_workaround(adapter);
/* Reset the timer */
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + 2 * HZ));
}
#define E1000_TX_FLAGS_CSUM 0x00000001
#define E1000_TX_FLAGS_VLAN 0x00000002
#define E1000_TX_FLAGS_TSO 0x00000004
#define E1000_TX_FLAGS_IPV4 0x00000008
#define E1000_TX_FLAGS_NO_FCS 0x00000010
#define E1000_TX_FLAGS_VLAN_MASK 0xffff0000
#define E1000_TX_FLAGS_VLAN_SHIFT 16
static int e1000_tso(struct e1000_ring *tx_ring, struct sk_buff *skb)
{
struct e1000_context_desc *context_desc;
struct e1000_buffer *buffer_info;
unsigned int i;
u32 cmd_length = 0;
u16 ipcse = 0, tucse, mss;
u8 ipcss, ipcso, tucss, tucso, hdr_len;
if (!skb_is_gso(skb))
return 0;
if (skb_header_cloned(skb)) {
int err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (err)
return err;
}
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
mss = skb_shinfo(skb)->gso_size;
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
iph->tot_len = 0;
iph->check = 0;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
0, IPPROTO_TCP, 0);
cmd_length = E1000_TXD_CMD_IP;
ipcse = skb_transport_offset(skb) - 1;
} else if (skb_is_gso_v6(skb)) {
ipv6_hdr(skb)->payload_len = 0;
tcp_hdr(skb)->check = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0);
ipcse = 0;
}
ipcss = skb_network_offset(skb);
ipcso = (void *)&(ip_hdr(skb)->check) - (void *)skb->data;
tucss = skb_transport_offset(skb);
tucso = (void *)&(tcp_hdr(skb)->check) - (void *)skb->data;
tucse = 0;
cmd_length |= (E1000_TXD_CMD_DEXT | E1000_TXD_CMD_TSE |
E1000_TXD_CMD_TCP | (skb->len - (hdr_len)));
i = tx_ring->next_to_use;
context_desc = E1000_CONTEXT_DESC(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
context_desc->lower_setup.ip_fields.ipcss = ipcss;
context_desc->lower_setup.ip_fields.ipcso = ipcso;
context_desc->lower_setup.ip_fields.ipcse = cpu_to_le16(ipcse);
context_desc->upper_setup.tcp_fields.tucss = tucss;
context_desc->upper_setup.tcp_fields.tucso = tucso;
context_desc->upper_setup.tcp_fields.tucse = cpu_to_le16(tucse);
context_desc->tcp_seg_setup.fields.mss = cpu_to_le16(mss);
context_desc->tcp_seg_setup.fields.hdr_len = hdr_len;
context_desc->cmd_and_length = cpu_to_le32(cmd_length);
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
i++;
if (i == tx_ring->count)
i = 0;
tx_ring->next_to_use = i;
return 1;
}
static bool e1000_tx_csum(struct e1000_ring *tx_ring, struct sk_buff *skb)
{
struct e1000_adapter *adapter = tx_ring->adapter;
struct e1000_context_desc *context_desc;
struct e1000_buffer *buffer_info;
unsigned int i;
u8 css;
u32 cmd_len = E1000_TXD_CMD_DEXT;
__be16 protocol;
if (skb->ip_summed != CHECKSUM_PARTIAL)
return 0;
if (skb->protocol == cpu_to_be16(ETH_P_8021Q))
protocol = vlan_eth_hdr(skb)->h_vlan_encapsulated_proto;
else
protocol = skb->protocol;
switch (protocol) {
case cpu_to_be16(ETH_P_IP):
if (ip_hdr(skb)->protocol == IPPROTO_TCP)
cmd_len |= E1000_TXD_CMD_TCP;
break;
case cpu_to_be16(ETH_P_IPV6):
/* XXX not handling all IPV6 headers */
if (ipv6_hdr(skb)->nexthdr == IPPROTO_TCP)
cmd_len |= E1000_TXD_CMD_TCP;
break;
default:
if (unlikely(net_ratelimit()))
e_warn("checksum_partial proto=%x!\n",
be16_to_cpu(protocol));
break;
}
css = skb_checksum_start_offset(skb);
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = E1000_CONTEXT_DESC(*tx_ring, i);
context_desc->lower_setup.ip_config = 0;
context_desc->upper_setup.tcp_fields.tucss = css;
context_desc->upper_setup.tcp_fields.tucso =
css + skb->csum_offset;
context_desc->upper_setup.tcp_fields.tucse = 0;
context_desc->tcp_seg_setup.data = 0;
context_desc->cmd_and_length = cpu_to_le32(cmd_len);
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
i++;
if (i == tx_ring->count)
i = 0;
tx_ring->next_to_use = i;
return 1;
}
#define E1000_MAX_PER_TXD 8192
#define E1000_MAX_TXD_PWR 12
static int e1000_tx_map(struct e1000_ring *tx_ring, struct sk_buff *skb,
unsigned int first, unsigned int max_per_txd,
unsigned int nr_frags, unsigned int mss)
{
struct e1000_adapter *adapter = tx_ring->adapter;
struct pci_dev *pdev = adapter->pdev;
struct e1000_buffer *buffer_info;
unsigned int len = skb_headlen(skb);
unsigned int offset = 0, size, count = 0, i;
unsigned int f, bytecount, segs;
i = tx_ring->next_to_use;
while (len) {
buffer_info = &tx_ring->buffer_info[i];
size = min(len, max_per_txd);
buffer_info->length = size;
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->dma = dma_map_single(&pdev->dev,
skb->data + offset,
size, DMA_TO_DEVICE);
buffer_info->mapped_as_page = false;
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
len -= size;
offset += size;
count++;
if (len) {
i++;
if (i == tx_ring->count)
i = 0;
}
}
for (f = 0; f < nr_frags; f++) {
const struct skb_frag_struct *frag;
frag = &skb_shinfo(skb)->frags[f];
len = skb_frag_size(frag);
offset = 0;
while (len) {
i++;
if (i == tx_ring->count)
i = 0;
buffer_info = &tx_ring->buffer_info[i];
size = min(len, max_per_txd);
buffer_info->length = size;
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->dma = skb_frag_dma_map(&pdev->dev, frag,
offset, size, DMA_TO_DEVICE);
buffer_info->mapped_as_page = true;
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
len -= size;
offset += size;
count++;
}
}
segs = skb_shinfo(skb)->gso_segs ? : 1;
/* multiply data chunks by size of headers */
bytecount = ((segs - 1) * skb_headlen(skb)) + skb->len;
tx_ring->buffer_info[i].skb = skb;
tx_ring->buffer_info[i].segs = segs;
tx_ring->buffer_info[i].bytecount = bytecount;
tx_ring->buffer_info[first].next_to_watch = i;
return count;
dma_error:
dev_err(&pdev->dev, "Tx DMA map failed\n");
buffer_info->dma = 0;
if (count)
count--;
while (count--) {
if (i == 0)
i += tx_ring->count;
i--;
buffer_info = &tx_ring->buffer_info[i];
e1000_put_txbuf(tx_ring, buffer_info);
}
return 0;
}
static void e1000_tx_queue(struct e1000_ring *tx_ring, int tx_flags, int count)
{
struct e1000_adapter *adapter = tx_ring->adapter;
struct e1000_tx_desc *tx_desc = NULL;
struct e1000_buffer *buffer_info;
u32 txd_upper = 0, txd_lower = E1000_TXD_CMD_IFCS;
unsigned int i;
if (tx_flags & E1000_TX_FLAGS_TSO) {
txd_lower |= E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D |
E1000_TXD_CMD_TSE;
txd_upper |= E1000_TXD_POPTS_TXSM << 8;
if (tx_flags & E1000_TX_FLAGS_IPV4)
txd_upper |= E1000_TXD_POPTS_IXSM << 8;
}
if (tx_flags & E1000_TX_FLAGS_CSUM) {
txd_lower |= E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D;
txd_upper |= E1000_TXD_POPTS_TXSM << 8;
}
if (tx_flags & E1000_TX_FLAGS_VLAN) {
txd_lower |= E1000_TXD_CMD_VLE;
txd_upper |= (tx_flags & E1000_TX_FLAGS_VLAN_MASK);
}
if (unlikely(tx_flags & E1000_TX_FLAGS_NO_FCS))
txd_lower &= ~(E1000_TXD_CMD_IFCS);
i = tx_ring->next_to_use;
do {
buffer_info = &tx_ring->buffer_info[i];
tx_desc = E1000_TX_DESC(*tx_ring, i);
tx_desc->buffer_addr = cpu_to_le64(buffer_info->dma);
tx_desc->lower.data =
cpu_to_le32(txd_lower | buffer_info->length);
tx_desc->upper.data = cpu_to_le32(txd_upper);
i++;
if (i == tx_ring->count)
i = 0;
} while (--count > 0);
tx_desc->lower.data |= cpu_to_le32(adapter->txd_cmd);
/* txd_cmd re-enables FCS, so we'll re-disable it here as desired. */
if (unlikely(tx_flags & E1000_TX_FLAGS_NO_FCS))
tx_desc->lower.data &= ~(cpu_to_le32(E1000_TXD_CMD_IFCS));
/*
* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64).
*/
wmb();
tx_ring->next_to_use = i;
if (adapter->flags2 & FLAG2_PCIM2PCI_ARBITER_WA)
e1000e_update_tdt_wa(tx_ring, i);
else
writel(i, tx_ring->tail);
/*
* we need this if more than one processor can write to our tail
* at a time, it synchronizes IO on IA64/Altix systems
*/
mmiowb();
}
#define MINIMUM_DHCP_PACKET_SIZE 282
static int e1000_transfer_dhcp_info(struct e1000_adapter *adapter,
struct sk_buff *skb)
{
struct e1000_hw *hw = &adapter->hw;
u16 length, offset;
if (vlan_tx_tag_present(skb)) {
if (!((vlan_tx_tag_get(skb) == adapter->hw.mng_cookie.vlan_id) &&
(adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN)))
return 0;
}
if (skb->len <= MINIMUM_DHCP_PACKET_SIZE)
return 0;
if (((struct ethhdr *) skb->data)->h_proto != htons(ETH_P_IP))
return 0;
{
const struct iphdr *ip = (struct iphdr *)((u8 *)skb->data+14);
struct udphdr *udp;
if (ip->protocol != IPPROTO_UDP)
return 0;
udp = (struct udphdr *)((u8 *)ip + (ip->ihl << 2));
if (ntohs(udp->dest) != 67)
return 0;
offset = (u8 *)udp + 8 - skb->data;
length = skb->len - offset;
return e1000e_mng_write_dhcp_info(hw, (u8 *)udp + 8, length);
}
return 0;
}
static int __e1000_maybe_stop_tx(struct e1000_ring *tx_ring, int size)
{
struct e1000_adapter *adapter = tx_ring->adapter;
netif_stop_queue(adapter->netdev);
/*
* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it.
*/
smp_mb();
/*
* We need to check again in a case another CPU has just
* made room available.
*/
if (e1000_desc_unused(tx_ring) < size)
return -EBUSY;
/* A reprieve! */
netif_start_queue(adapter->netdev);
++adapter->restart_queue;
return 0;
}
static int e1000_maybe_stop_tx(struct e1000_ring *tx_ring, int size)
{
if (e1000_desc_unused(tx_ring) >= size)
return 0;
return __e1000_maybe_stop_tx(tx_ring, size);
}
#define TXD_USE_COUNT(S, X) (((S) >> (X)) + 1)
static netdev_tx_t e1000_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_ring *tx_ring = adapter->tx_ring;
unsigned int first;
unsigned int max_per_txd = E1000_MAX_PER_TXD;
unsigned int max_txd_pwr = E1000_MAX_TXD_PWR;
unsigned int tx_flags = 0;
unsigned int len = skb_headlen(skb);
unsigned int nr_frags;
unsigned int mss;
int count = 0;
int tso;
unsigned int f;
if (test_bit(__E1000_DOWN, &adapter->state)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (skb->len <= 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
mss = skb_shinfo(skb)->gso_size;
/*
* The controller does a simple calculation to
* make sure there is enough room in the FIFO before
* initiating the DMA for each buffer. The calc is:
* 4 = ceil(buffer len/mss). To make sure we don't
* overrun the FIFO, adjust the max buffer len if mss
* drops.
*/
if (mss) {
u8 hdr_len;
max_per_txd = min(mss << 2, max_per_txd);
max_txd_pwr = fls(max_per_txd) - 1;
/*
* TSO Workaround for 82571/2/3 Controllers -- if skb->data
* points to just header, pull a few bytes of payload from
* frags into skb->data
*/
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
/*
* we do this workaround for ES2LAN, but it is un-necessary,
* avoiding it could save a lot of cycles
*/
if (skb->data_len && (hdr_len == len)) {
unsigned int pull_size;
pull_size = min_t(unsigned int, 4, skb->data_len);
if (!__pskb_pull_tail(skb, pull_size)) {
e_err("__pskb_pull_tail failed.\n");
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
len = skb_headlen(skb);
}
}
/* reserve a descriptor for the offload context */
if ((mss) || (skb->ip_summed == CHECKSUM_PARTIAL))
count++;
count++;
count += TXD_USE_COUNT(len, max_txd_pwr);
nr_frags = skb_shinfo(skb)->nr_frags;
for (f = 0; f < nr_frags; f++)
count += TXD_USE_COUNT(skb_frag_size(&skb_shinfo(skb)->frags[f]),
max_txd_pwr);
if (adapter->hw.mac.tx_pkt_filtering)
e1000_transfer_dhcp_info(adapter, skb);
/*
* need: count + 2 desc gap to keep tail from touching
* head, otherwise try next time
*/
if (e1000_maybe_stop_tx(tx_ring, count + 2))
return NETDEV_TX_BUSY;
if (vlan_tx_tag_present(skb)) {
tx_flags |= E1000_TX_FLAGS_VLAN;
tx_flags |= (vlan_tx_tag_get(skb) << E1000_TX_FLAGS_VLAN_SHIFT);
}
first = tx_ring->next_to_use;
tso = e1000_tso(tx_ring, skb);
if (tso < 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (tso)
tx_flags |= E1000_TX_FLAGS_TSO;
else if (e1000_tx_csum(tx_ring, skb))
tx_flags |= E1000_TX_FLAGS_CSUM;
/*
* Old method was to assume IPv4 packet by default if TSO was enabled.
* 82571 hardware supports TSO capabilities for IPv6 as well...
* no longer assume, we must.
*/
if (skb->protocol == htons(ETH_P_IP))
tx_flags |= E1000_TX_FLAGS_IPV4;
if (unlikely(skb->no_fcs))
tx_flags |= E1000_TX_FLAGS_NO_FCS;
/* if count is 0 then mapping error has occurred */
count = e1000_tx_map(tx_ring, skb, first, max_per_txd, nr_frags, mss);
if (count) {
netdev_sent_queue(netdev, skb->len);
e1000_tx_queue(tx_ring, tx_flags, count);
/* Make sure there is space in the ring for the next send. */
e1000_maybe_stop_tx(tx_ring, MAX_SKB_FRAGS + 2);
} else {
dev_kfree_skb_any(skb);
tx_ring->buffer_info[first].time_stamp = 0;
tx_ring->next_to_use = first;
}
return NETDEV_TX_OK;
}
/**
* e1000_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
**/
static void e1000_tx_timeout(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
static void e1000_reset_task(struct work_struct *work)
{
struct e1000_adapter *adapter;
adapter = container_of(work, struct e1000_adapter, reset_task);
/* don't run the task if already down */
if (test_bit(__E1000_DOWN, &adapter->state))
return;
if (!((adapter->flags & FLAG_RX_NEEDS_RESTART) &&
(adapter->flags & FLAG_RX_RESTART_NOW))) {
e1000e_dump(adapter);
e_err("Reset adapter\n");
}
e1000e_reinit_locked(adapter);
}
/**
* e1000_get_stats64 - Get System Network Statistics
* @netdev: network interface device structure
* @stats: rtnl_link_stats64 pointer
*
* Returns the address of the device statistics structure.
**/
struct rtnl_link_stats64 *e1000e_get_stats64(struct net_device *netdev,
struct rtnl_link_stats64 *stats)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
memset(stats, 0, sizeof(struct rtnl_link_stats64));
spin_lock(&adapter->stats64_lock);
e1000e_update_stats(adapter);
/* Fill out the OS statistics structure */
stats->rx_bytes = adapter->stats.gorc;
stats->rx_packets = adapter->stats.gprc;
stats->tx_bytes = adapter->stats.gotc;
stats->tx_packets = adapter->stats.gptc;
stats->multicast = adapter->stats.mprc;
stats->collisions = adapter->stats.colc;
/* Rx Errors */
/*
* RLEC on some newer hardware can be incorrect so build
* our own version based on RUC and ROC
*/
stats->rx_errors = adapter->stats.rxerrc +
adapter->stats.crcerrs + adapter->stats.algnerrc +
adapter->stats.ruc + adapter->stats.roc +
adapter->stats.cexterr;
stats->rx_length_errors = adapter->stats.ruc +
adapter->stats.roc;
stats->rx_crc_errors = adapter->stats.crcerrs;
stats->rx_frame_errors = adapter->stats.algnerrc;
stats->rx_missed_errors = adapter->stats.mpc;
/* Tx Errors */
stats->tx_errors = adapter->stats.ecol +
adapter->stats.latecol;
stats->tx_aborted_errors = adapter->stats.ecol;
stats->tx_window_errors = adapter->stats.latecol;
stats->tx_carrier_errors = adapter->stats.tncrs;
/* Tx Dropped needs to be maintained elsewhere */
spin_unlock(&adapter->stats64_lock);
return stats;
}
/**
* e1000_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
**/
static int e1000_change_mtu(struct net_device *netdev, int new_mtu)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
int max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN;
/* Jumbo frame support */
if ((max_frame > ETH_FRAME_LEN + ETH_FCS_LEN) &&
!(adapter->flags & FLAG_HAS_JUMBO_FRAMES)) {
e_err("Jumbo Frames not supported.\n");
return -EINVAL;
}
/* Supported frame sizes */
if ((new_mtu < ETH_ZLEN + ETH_FCS_LEN + VLAN_HLEN) ||
(max_frame > adapter->max_hw_frame_size)) {
e_err("Unsupported MTU setting\n");
return -EINVAL;
}
/* Jumbo frame workaround on 82579 requires CRC be stripped */
if ((adapter->hw.mac.type == e1000_pch2lan) &&
!(adapter->flags2 & FLAG2_CRC_STRIPPING) &&
(new_mtu > ETH_DATA_LEN)) {
e_err("Jumbo Frames not supported on 82579 when CRC stripping is disabled.\n");
return -EINVAL;
}
while (test_and_set_bit(__E1000_RESETTING, &adapter->state))
usleep_range(1000, 2000);
/* e1000e_down -> e1000e_reset dependent on max_frame_size & mtu */
adapter->max_frame_size = max_frame;
e_info("changing MTU from %d to %d\n", netdev->mtu, new_mtu);
netdev->mtu = new_mtu;
if (netif_running(netdev))
e1000e_down(adapter);
/*
* NOTE: netdev_alloc_skb reserves 16 bytes, and typically NET_IP_ALIGN
* means we reserve 2 more, this pushes us to allocate from the next
* larger slab size.
* i.e. RXBUFFER_2048 --> size-4096 slab
* However with the new *_jumbo_rx* routines, jumbo receives will use
* fragmented skbs
*/
if (max_frame <= 2048)
adapter->rx_buffer_len = 2048;
else
adapter->rx_buffer_len = 4096;
/* adjust allocation if LPE protects us, and we aren't using SBP */
if ((max_frame == ETH_FRAME_LEN + ETH_FCS_LEN) ||
(max_frame == ETH_FRAME_LEN + VLAN_HLEN + ETH_FCS_LEN))
adapter->rx_buffer_len = ETH_FRAME_LEN + VLAN_HLEN
+ ETH_FCS_LEN;
if (netif_running(netdev))
e1000e_up(adapter);
else
e1000e_reset(adapter);
clear_bit(__E1000_RESETTING, &adapter->state);
return 0;
}
static int e1000_mii_ioctl(struct net_device *netdev, struct ifreq *ifr,
int cmd)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct mii_ioctl_data *data = if_mii(ifr);
if (adapter->hw.phy.media_type != e1000_media_type_copper)
return -EOPNOTSUPP;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = adapter->hw.phy.addr;
break;
case SIOCGMIIREG:
e1000_phy_read_status(adapter);
switch (data->reg_num & 0x1F) {
case MII_BMCR:
data->val_out = adapter->phy_regs.bmcr;
break;
case MII_BMSR:
data->val_out = adapter->phy_regs.bmsr;
break;
case MII_PHYSID1:
data->val_out = (adapter->hw.phy.id >> 16);
break;
case MII_PHYSID2:
data->val_out = (adapter->hw.phy.id & 0xFFFF);
break;
case MII_ADVERTISE:
data->val_out = adapter->phy_regs.advertise;
break;
case MII_LPA:
data->val_out = adapter->phy_regs.lpa;
break;
case MII_EXPANSION:
data->val_out = adapter->phy_regs.expansion;
break;
case MII_CTRL1000:
data->val_out = adapter->phy_regs.ctrl1000;
break;
case MII_STAT1000:
data->val_out = adapter->phy_regs.stat1000;
break;
case MII_ESTATUS:
data->val_out = adapter->phy_regs.estatus;
break;
default:
return -EIO;
}
break;
case SIOCSMIIREG:
default:
return -EOPNOTSUPP;
}
return 0;
}
static int e1000_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
return e1000_mii_ioctl(netdev, ifr, cmd);
default:
return -EOPNOTSUPP;
}
}
static int e1000_init_phy_wakeup(struct e1000_adapter *adapter, u32 wufc)
{
struct e1000_hw *hw = &adapter->hw;
u32 i, mac_reg;
u16 phy_reg, wuc_enable;
int retval = 0;
/* copy MAC RARs to PHY RARs */
e1000_copy_rx_addrs_to_phy_ich8lan(hw);
retval = hw->phy.ops.acquire(hw);
if (retval) {
e_err("Could not acquire PHY\n");
return retval;
}
/* Enable access to wakeup registers on and set page to BM_WUC_PAGE */
retval = e1000_enable_phy_wakeup_reg_access_bm(hw, &wuc_enable);
if (retval)
goto release;
/* copy MAC MTA to PHY MTA - only needed for pchlan */
for (i = 0; i < adapter->hw.mac.mta_reg_count; i++) {
mac_reg = E1000_READ_REG_ARRAY(hw, E1000_MTA, i);
hw->phy.ops.write_reg_page(hw, BM_MTA(i),
(u16)(mac_reg & 0xFFFF));
hw->phy.ops.write_reg_page(hw, BM_MTA(i) + 1,
(u16)((mac_reg >> 16) & 0xFFFF));
}
/* configure PHY Rx Control register */
hw->phy.ops.read_reg_page(&adapter->hw, BM_RCTL, &phy_reg);
mac_reg = er32(RCTL);
if (mac_reg & E1000_RCTL_UPE)
phy_reg |= BM_RCTL_UPE;
if (mac_reg & E1000_RCTL_MPE)
phy_reg |= BM_RCTL_MPE;
phy_reg &= ~(BM_RCTL_MO_MASK);
if (mac_reg & E1000_RCTL_MO_3)
phy_reg |= (((mac_reg & E1000_RCTL_MO_3) >> E1000_RCTL_MO_SHIFT)
<< BM_RCTL_MO_SHIFT);
if (mac_reg & E1000_RCTL_BAM)
phy_reg |= BM_RCTL_BAM;
if (mac_reg & E1000_RCTL_PMCF)
phy_reg |= BM_RCTL_PMCF;
mac_reg = er32(CTRL);
if (mac_reg & E1000_CTRL_RFCE)
phy_reg |= BM_RCTL_RFCE;
hw->phy.ops.write_reg_page(&adapter->hw, BM_RCTL, phy_reg);
/* enable PHY wakeup in MAC register */
ew32(WUFC, wufc);
ew32(WUC, E1000_WUC_PHY_WAKE | E1000_WUC_PME_EN);
/* configure and enable PHY wakeup in PHY registers */
hw->phy.ops.write_reg_page(&adapter->hw, BM_WUFC, wufc);
hw->phy.ops.write_reg_page(&adapter->hw, BM_WUC, E1000_WUC_PME_EN);
/* activate PHY wakeup */
wuc_enable |= BM_WUC_ENABLE_BIT | BM_WUC_HOST_WU_BIT;
retval = e1000_disable_phy_wakeup_reg_access_bm(hw, &wuc_enable);
if (retval)
e_err("Could not set PHY Host Wakeup bit\n");
release:
hw->phy.ops.release(hw);
return retval;
}
static int __e1000_shutdown(struct pci_dev *pdev, bool *enable_wake,
bool runtime)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 ctrl, ctrl_ext, rctl, status;
/* Runtime suspend should only enable wakeup for link changes */
u32 wufc = runtime ? E1000_WUFC_LNKC : adapter->wol;
int retval = 0;
netif_device_detach(netdev);
if (netif_running(netdev)) {
int count = E1000_CHECK_RESET_COUNT;
while (test_bit(__E1000_RESETTING, &adapter->state) && count--)
usleep_range(10000, 20000);
WARN_ON(test_bit(__E1000_RESETTING, &adapter->state));
e1000e_down(adapter);
e1000_free_irq(adapter);
}
e1000e_reset_interrupt_capability(adapter);
retval = pci_save_state(pdev);
if (retval)
return retval;
status = er32(STATUS);
if (status & E1000_STATUS_LU)
wufc &= ~E1000_WUFC_LNKC;
if (wufc) {
e1000_setup_rctl(adapter);
e1000e_set_rx_mode(netdev);
/* turn on all-multi mode if wake on multicast is enabled */
if (wufc & E1000_WUFC_MC) {
rctl = er32(RCTL);
rctl |= E1000_RCTL_MPE;
ew32(RCTL, rctl);
}
ctrl = er32(CTRL);
/* advertise wake from D3Cold */
#define E1000_CTRL_ADVD3WUC 0x00100000
/* phy power management enable */
#define E1000_CTRL_EN_PHY_PWR_MGMT 0x00200000
ctrl |= E1000_CTRL_ADVD3WUC;
if (!(adapter->flags2 & FLAG2_HAS_PHY_WAKEUP))
ctrl |= E1000_CTRL_EN_PHY_PWR_MGMT;
ew32(CTRL, ctrl);
if (adapter->hw.phy.media_type == e1000_media_type_fiber ||
adapter->hw.phy.media_type ==
e1000_media_type_internal_serdes) {
/* keep the laser running in D3 */
ctrl_ext = er32(CTRL_EXT);
ctrl_ext |= E1000_CTRL_EXT_SDP3_DATA;
ew32(CTRL_EXT, ctrl_ext);
}
if (adapter->flags & FLAG_IS_ICH)
e1000_suspend_workarounds_ich8lan(&adapter->hw);
/* Allow time for pending master requests to run */
e1000e_disable_pcie_master(&adapter->hw);
if (adapter->flags2 & FLAG2_HAS_PHY_WAKEUP) {
/* enable wakeup by the PHY */
retval = e1000_init_phy_wakeup(adapter, wufc);
if (retval)
return retval;
} else {
/* enable wakeup by the MAC */
ew32(WUFC, wufc);
ew32(WUC, E1000_WUC_PME_EN);
}
} else {
ew32(WUC, 0);
ew32(WUFC, 0);
}
*enable_wake = !!wufc;
/* make sure adapter isn't asleep if manageability is enabled */
if ((adapter->flags & FLAG_MNG_PT_ENABLED) ||
(hw->mac.ops.check_mng_mode(hw)))
*enable_wake = true;
if (adapter->hw.phy.type == e1000_phy_igp_3)
e1000e_igp3_phy_powerdown_workaround_ich8lan(&adapter->hw);
/*
* Release control of h/w to f/w. If f/w is AMT enabled, this
* would have already happened in close and is redundant.
*/
e1000e_release_hw_control(adapter);
pci_clear_master(pdev);
return 0;
}
static void e1000_power_off(struct pci_dev *pdev, bool sleep, bool wake)
{
if (sleep && wake) {
pci_prepare_to_sleep(pdev);
return;
}
pci_wake_from_d3(pdev, wake);
pci_set_power_state(pdev, PCI_D3hot);
}
static void e1000_complete_shutdown(struct pci_dev *pdev, bool sleep,
bool wake)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
/*
* The pci-e switch on some quad port adapters will report a
* correctable error when the MAC transitions from D0 to D3. To
* prevent this we need to mask off the correctable errors on the
* downstream port of the pci-e switch.
*/
if (adapter->flags & FLAG_IS_QUAD_PORT) {
struct pci_dev *us_dev = pdev->bus->self;
int pos = pci_pcie_cap(us_dev);
u16 devctl;
pci_read_config_word(us_dev, pos + PCI_EXP_DEVCTL, &devctl);
pci_write_config_word(us_dev, pos + PCI_EXP_DEVCTL,
(devctl & ~PCI_EXP_DEVCTL_CERE));
e1000_power_off(pdev, sleep, wake);
pci_write_config_word(us_dev, pos + PCI_EXP_DEVCTL, devctl);
} else {
e1000_power_off(pdev, sleep, wake);
}
}
#ifdef CONFIG_PCIEASPM
static void __e1000e_disable_aspm(struct pci_dev *pdev, u16 state)
{
pci_disable_link_state_locked(pdev, state);
}
#else
static void __e1000e_disable_aspm(struct pci_dev *pdev, u16 state)
{
int pos;
u16 reg16;
/*
* Both device and parent should have the same ASPM setting.
* Disable ASPM in downstream component first and then upstream.
*/
pos = pci_pcie_cap(pdev);
pci_read_config_word(pdev, pos + PCI_EXP_LNKCTL, ®16);
reg16 &= ~state;
pci_write_config_word(pdev, pos + PCI_EXP_LNKCTL, reg16);
if (!pdev->bus->self)
return;
pos = pci_pcie_cap(pdev->bus->self);
pci_read_config_word(pdev->bus->self, pos + PCI_EXP_LNKCTL, ®16);
reg16 &= ~state;
pci_write_config_word(pdev->bus->self, pos + PCI_EXP_LNKCTL, reg16);
}
#endif
static void e1000e_disable_aspm(struct pci_dev *pdev, u16 state)
{
dev_info(&pdev->dev, "Disabling ASPM %s %s\n",
(state & PCIE_LINK_STATE_L0S) ? "L0s" : "",
(state & PCIE_LINK_STATE_L1) ? "L1" : "");
__e1000e_disable_aspm(pdev, state);
}
#ifdef CONFIG_PM
static bool e1000e_pm_ready(struct e1000_adapter *adapter)
{
return !!adapter->tx_ring->buffer_info;
}
static int __e1000_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u16 aspm_disable_flag = 0;
u32 err;
if (adapter->flags2 & FLAG2_DISABLE_ASPM_L0S)
aspm_disable_flag = PCIE_LINK_STATE_L0S;
if (adapter->flags2 & FLAG2_DISABLE_ASPM_L1)
aspm_disable_flag |= PCIE_LINK_STATE_L1;
if (aspm_disable_flag)
e1000e_disable_aspm(pdev, aspm_disable_flag);
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
pci_save_state(pdev);
e1000e_set_interrupt_capability(adapter);
if (netif_running(netdev)) {
err = e1000_request_irq(adapter);
if (err)
return err;
}
if (hw->mac.type == e1000_pch2lan)
e1000_resume_workarounds_pchlan(&adapter->hw);
e1000e_power_up_phy(adapter);
/* report the system wakeup cause from S3/S4 */
if (adapter->flags2 & FLAG2_HAS_PHY_WAKEUP) {
u16 phy_data;
e1e_rphy(&adapter->hw, BM_WUS, &phy_data);
if (phy_data) {
e_info("PHY Wakeup cause - %s\n",
phy_data & E1000_WUS_EX ? "Unicast Packet" :
phy_data & E1000_WUS_MC ? "Multicast Packet" :
phy_data & E1000_WUS_BC ? "Broadcast Packet" :
phy_data & E1000_WUS_MAG ? "Magic Packet" :
phy_data & E1000_WUS_LNKC ?
"Link Status Change" : "other");
}
e1e_wphy(&adapter->hw, BM_WUS, ~0);
} else {
u32 wus = er32(WUS);
if (wus) {
e_info("MAC Wakeup cause - %s\n",
wus & E1000_WUS_EX ? "Unicast Packet" :
wus & E1000_WUS_MC ? "Multicast Packet" :
wus & E1000_WUS_BC ? "Broadcast Packet" :
wus & E1000_WUS_MAG ? "Magic Packet" :
wus & E1000_WUS_LNKC ? "Link Status Change" :
"other");
}
ew32(WUS, ~0);
}
e1000e_reset(adapter);
e1000_init_manageability_pt(adapter);
if (netif_running(netdev))
e1000e_up(adapter);
netif_device_attach(netdev);
/*
* If the controller has AMT, do not set DRV_LOAD until the interface
* is up. For all other cases, let the f/w know that the h/w is now
* under the control of the driver.
*/
if (!(adapter->flags & FLAG_HAS_AMT))
e1000e_get_hw_control(adapter);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int e1000_suspend(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
int retval;
bool wake;
retval = __e1000_shutdown(pdev, &wake, false);
if (!retval)
e1000_complete_shutdown(pdev, true, wake);
return retval;
}
static int e1000_resume(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
if (e1000e_pm_ready(adapter))
adapter->idle_check = true;
return __e1000_resume(pdev);
}
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM_RUNTIME
static int e1000_runtime_suspend(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
if (e1000e_pm_ready(adapter)) {
bool wake;
__e1000_shutdown(pdev, &wake, true);
}
return 0;
}
static int e1000_idle(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
if (!e1000e_pm_ready(adapter))
return 0;
if (adapter->idle_check) {
adapter->idle_check = false;
if (!e1000e_has_link(adapter))
pm_schedule_suspend(dev, MSEC_PER_SEC);
}
return -EBUSY;
}
static int e1000_runtime_resume(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
if (!e1000e_pm_ready(adapter))
return 0;
adapter->idle_check = !dev->power.runtime_auto;
return __e1000_resume(pdev);
}
#endif /* CONFIG_PM_RUNTIME */
#endif /* CONFIG_PM */
static void e1000_shutdown(struct pci_dev *pdev)
{
bool wake = false;
__e1000_shutdown(pdev, &wake, false);
if (system_state == SYSTEM_POWER_OFF)
e1000_complete_shutdown(pdev, false, wake);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static irqreturn_t e1000_intr_msix(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
if (adapter->msix_entries) {
int vector, msix_irq;
vector = 0;
msix_irq = adapter->msix_entries[vector].vector;
disable_irq(msix_irq);
e1000_intr_msix_rx(msix_irq, netdev);
enable_irq(msix_irq);
vector++;
msix_irq = adapter->msix_entries[vector].vector;
disable_irq(msix_irq);
e1000_intr_msix_tx(msix_irq, netdev);
enable_irq(msix_irq);
vector++;
msix_irq = adapter->msix_entries[vector].vector;
disable_irq(msix_irq);
e1000_msix_other(msix_irq, netdev);
enable_irq(msix_irq);
}
return IRQ_HANDLED;
}
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void e1000_netpoll(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
switch (adapter->int_mode) {
case E1000E_INT_MODE_MSIX:
e1000_intr_msix(adapter->pdev->irq, netdev);
break;
case E1000E_INT_MODE_MSI:
disable_irq(adapter->pdev->irq);
e1000_intr_msi(adapter->pdev->irq, netdev);
enable_irq(adapter->pdev->irq);
break;
default: /* E1000E_INT_MODE_LEGACY */
disable_irq(adapter->pdev->irq);
e1000_intr(adapter->pdev->irq, netdev);
enable_irq(adapter->pdev->irq);
break;
}
}
#endif
/**
* e1000_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t e1000_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev))
e1000e_down(adapter);
pci_disable_device(pdev);
/* Request a slot slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* e1000_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot. Implementation
* resembles the first-half of the e1000_resume routine.
*/
static pci_ers_result_t e1000_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u16 aspm_disable_flag = 0;
int err;
pci_ers_result_t result;
if (adapter->flags2 & FLAG2_DISABLE_ASPM_L0S)
aspm_disable_flag = PCIE_LINK_STATE_L0S;
if (adapter->flags2 & FLAG2_DISABLE_ASPM_L1)
aspm_disable_flag |= PCIE_LINK_STATE_L1;
if (aspm_disable_flag)
e1000e_disable_aspm(pdev, aspm_disable_flag);
err = pci_enable_device_mem(pdev);
if (err) {
dev_err(&pdev->dev,
"Cannot re-enable PCI device after reset.\n");
result = PCI_ERS_RESULT_DISCONNECT;
} else {
pci_set_master(pdev);
pdev->state_saved = true;
pci_restore_state(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
e1000e_reset(adapter);
ew32(WUS, ~0);
result = PCI_ERS_RESULT_RECOVERED;
}
pci_cleanup_aer_uncorrect_error_status(pdev);
return result;
}
/**
* e1000_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation. Implementation resembles the
* second-half of the e1000_resume routine.
*/
static void e1000_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
e1000_init_manageability_pt(adapter);
if (netif_running(netdev)) {
if (e1000e_up(adapter)) {
dev_err(&pdev->dev,
"can't bring device back up after reset\n");
return;
}
}
netif_device_attach(netdev);
/*
* If the controller has AMT, do not set DRV_LOAD until the interface
* is up. For all other cases, let the f/w know that the h/w is now
* under the control of the driver.
*/
if (!(adapter->flags & FLAG_HAS_AMT))
e1000e_get_hw_control(adapter);
}
static void e1000_print_device_info(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
u32 ret_val;
u8 pba_str[E1000_PBANUM_LENGTH];
/* print bus type/speed/width info */
e_info("(PCI Express:2.5GT/s:%s) %pM\n",
/* bus width */
((hw->bus.width == e1000_bus_width_pcie_x4) ? "Width x4" :
"Width x1"),
/* MAC address */
netdev->dev_addr);
e_info("Intel(R) PRO/%s Network Connection\n",
(hw->phy.type == e1000_phy_ife) ? "10/100" : "1000");
ret_val = e1000_read_pba_string_generic(hw, pba_str,
E1000_PBANUM_LENGTH);
if (ret_val)
strlcpy((char *)pba_str, "Unknown", sizeof(pba_str));
e_info("MAC: %d, PHY: %d, PBA No: %s\n",
hw->mac.type, hw->phy.type, pba_str);
}
static void e1000_eeprom_checks(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
int ret_val;
u16 buf = 0;
if (hw->mac.type != e1000_82573)
return;
ret_val = e1000_read_nvm(hw, NVM_INIT_CONTROL2_REG, 1, &buf);
le16_to_cpus(&buf);
if (!ret_val && (!(buf & (1 << 0)))) {
/* Deep Smart Power Down (DSPD) */
dev_warn(&adapter->pdev->dev,
"Warning: detected DSPD enabled in EEPROM\n");
}
}
static int e1000_set_features(struct net_device *netdev,
netdev_features_t features)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
netdev_features_t changed = features ^ netdev->features;
if (changed & (NETIF_F_TSO | NETIF_F_TSO6))
adapter->flags |= FLAG_TSO_FORCE;
if (!(changed & (NETIF_F_HW_VLAN_RX | NETIF_F_HW_VLAN_TX |
NETIF_F_RXCSUM | NETIF_F_RXHASH | NETIF_F_RXFCS |
NETIF_F_RXALL)))
return 0;
if (changed & NETIF_F_RXFCS) {
if (features & NETIF_F_RXFCS) {
adapter->flags2 &= ~FLAG2_CRC_STRIPPING;
} else {
/* We need to take it back to defaults, which might mean
* stripping is still disabled at the adapter level.
*/
if (adapter->flags2 & FLAG2_DFLT_CRC_STRIPPING)
adapter->flags2 |= FLAG2_CRC_STRIPPING;
else
adapter->flags2 &= ~FLAG2_CRC_STRIPPING;
}
}
netdev->features = features;
if (netif_running(netdev))
e1000e_reinit_locked(adapter);
else
e1000e_reset(adapter);
return 0;
}
static const struct net_device_ops e1000e_netdev_ops = {
.ndo_open = e1000_open,
.ndo_stop = e1000_close,
.ndo_start_xmit = e1000_xmit_frame,
.ndo_get_stats64 = e1000e_get_stats64,
.ndo_set_rx_mode = e1000e_set_rx_mode,
.ndo_set_mac_address = e1000_set_mac,
.ndo_change_mtu = e1000_change_mtu,
.ndo_do_ioctl = e1000_ioctl,
.ndo_tx_timeout = e1000_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_vlan_rx_add_vid = e1000_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = e1000_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = e1000_netpoll,
#endif
.ndo_set_features = e1000_set_features,
};
/**
* e1000_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in e1000_pci_tbl
*
* Returns 0 on success, negative on failure
*
* e1000_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
**/
static int __devinit e1000_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *netdev;
struct e1000_adapter *adapter;
struct e1000_hw *hw;
const struct e1000_info *ei = e1000_info_tbl[ent->driver_data];
resource_size_t mmio_start, mmio_len;
resource_size_t flash_start, flash_len;
static int cards_found;
u16 aspm_disable_flag = 0;
int i, err, pci_using_dac;
u16 eeprom_data = 0;
u16 eeprom_apme_mask = E1000_EEPROM_APME;
if (ei->flags2 & FLAG2_DISABLE_ASPM_L0S)
aspm_disable_flag = PCIE_LINK_STATE_L0S;
if (ei->flags2 & FLAG2_DISABLE_ASPM_L1)
aspm_disable_flag |= PCIE_LINK_STATE_L1;
if (aspm_disable_flag)
e1000e_disable_aspm(pdev, aspm_disable_flag);
err = pci_enable_device_mem(pdev);
if (err)
return err;
pci_using_dac = 0;
err = dma_set_mask(&pdev->dev, DMA_BIT_MASK(64));
if (!err) {
err = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(64));
if (!err)
pci_using_dac = 1;
} else {
err = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
if (err) {
err = dma_set_coherent_mask(&pdev->dev,
DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev, "No usable DMA configuration, aborting\n");
goto err_dma;
}
}
}
err = pci_request_selected_regions_exclusive(pdev,
pci_select_bars(pdev, IORESOURCE_MEM),
e1000e_driver_name);
if (err)
goto err_pci_reg;
/* AER (Advanced Error Reporting) hooks */
pci_enable_pcie_error_reporting(pdev);
pci_set_master(pdev);
/* PCI config space info */
err = pci_save_state(pdev);
if (err)
goto err_alloc_etherdev;
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct e1000_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
netdev->irq = pdev->irq;
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
hw = &adapter->hw;
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->ei = ei;
adapter->pba = ei->pba;
adapter->flags = ei->flags;
adapter->flags2 = ei->flags2;
adapter->hw.adapter = adapter;
adapter->hw.mac.type = ei->mac;
adapter->max_hw_frame_size = ei->max_hw_frame_size;
adapter->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE);
mmio_start = pci_resource_start(pdev, 0);
mmio_len = pci_resource_len(pdev, 0);
err = -EIO;
adapter->hw.hw_addr = ioremap(mmio_start, mmio_len);
if (!adapter->hw.hw_addr)
goto err_ioremap;
if ((adapter->flags & FLAG_HAS_FLASH) &&
(pci_resource_flags(pdev, 1) & IORESOURCE_MEM)) {
flash_start = pci_resource_start(pdev, 1);
flash_len = pci_resource_len(pdev, 1);
adapter->hw.flash_address = ioremap(flash_start, flash_len);
if (!adapter->hw.flash_address)
goto err_flashmap;
}
/* construct the net_device struct */
netdev->netdev_ops = &e1000e_netdev_ops;
e1000e_set_ethtool_ops(netdev);
netdev->watchdog_timeo = 5 * HZ;
netif_napi_add(netdev, &adapter->napi, e1000_clean, 64);
strlcpy(netdev->name, pci_name(pdev), sizeof(netdev->name));
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len;
adapter->bd_number = cards_found++;
e1000e_check_options(adapter);
/* setup adapter struct */
err = e1000_sw_init(adapter);
if (err)
goto err_sw_init;
memcpy(&hw->mac.ops, ei->mac_ops, sizeof(hw->mac.ops));
memcpy(&hw->nvm.ops, ei->nvm_ops, sizeof(hw->nvm.ops));
memcpy(&hw->phy.ops, ei->phy_ops, sizeof(hw->phy.ops));
err = ei->get_variants(adapter);
if (err)
goto err_hw_init;
if ((adapter->flags & FLAG_IS_ICH) &&
(adapter->flags & FLAG_READ_ONLY_NVM))
e1000e_write_protect_nvm_ich8lan(&adapter->hw);
hw->mac.ops.get_bus_info(&adapter->hw);
adapter->hw.phy.autoneg_wait_to_complete = 0;
/* Copper options */
if (adapter->hw.phy.media_type == e1000_media_type_copper) {
adapter->hw.phy.mdix = AUTO_ALL_MODES;
adapter->hw.phy.disable_polarity_correction = 0;
adapter->hw.phy.ms_type = e1000_ms_hw_default;
}
if (hw->phy.ops.check_reset_block && hw->phy.ops.check_reset_block(hw))
e_info("PHY reset is blocked due to SOL/IDER session.\n");
/* Set initial default active device features */
netdev->features = (NETIF_F_SG |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_TX |
NETIF_F_TSO |
NETIF_F_TSO6 |
NETIF_F_RXHASH |
NETIF_F_RXCSUM |
NETIF_F_HW_CSUM);
/* Set user-changeable features (subset of all device features) */
netdev->hw_features = netdev->features;
netdev->hw_features |= NETIF_F_RXFCS;
netdev->priv_flags |= IFF_SUPP_NOFCS;
netdev->hw_features |= NETIF_F_RXALL;
if (adapter->flags & FLAG_HAS_HW_VLAN_FILTER)
netdev->features |= NETIF_F_HW_VLAN_FILTER;
netdev->vlan_features |= (NETIF_F_SG |
NETIF_F_TSO |
NETIF_F_TSO6 |
NETIF_F_HW_CSUM);
netdev->priv_flags |= IFF_UNICAST_FLT;
if (pci_using_dac) {
netdev->features |= NETIF_F_HIGHDMA;
netdev->vlan_features |= NETIF_F_HIGHDMA;
}
if (e1000e_enable_mng_pass_thru(&adapter->hw))
adapter->flags |= FLAG_MNG_PT_ENABLED;
/*
* before reading the NVM, reset the controller to
* put the device in a known good starting state
*/
adapter->hw.mac.ops.reset_hw(&adapter->hw);
/*
* systems with ASPM and others may see the checksum fail on the first
* attempt. Let's give it a few tries
*/
for (i = 0;; i++) {
if (e1000_validate_nvm_checksum(&adapter->hw) >= 0)
break;
if (i == 2) {
e_err("The NVM Checksum Is Not Valid\n");
err = -EIO;
goto err_eeprom;
}
}
e1000_eeprom_checks(adapter);
/* copy the MAC address */
if (e1000e_read_mac_addr(&adapter->hw))
e_err("NVM Read Error while reading MAC address\n");
memcpy(netdev->dev_addr, adapter->hw.mac.addr, netdev->addr_len);
memcpy(netdev->perm_addr, adapter->hw.mac.addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr)) {
e_err("Invalid MAC Address: %pM\n", netdev->perm_addr);
err = -EIO;
goto err_eeprom;
}
init_timer(&adapter->watchdog_timer);
adapter->watchdog_timer.function = e1000_watchdog;
adapter->watchdog_timer.data = (unsigned long) adapter;
init_timer(&adapter->phy_info_timer);
adapter->phy_info_timer.function = e1000_update_phy_info;
adapter->phy_info_timer.data = (unsigned long) adapter;
INIT_WORK(&adapter->reset_task, e1000_reset_task);
INIT_WORK(&adapter->watchdog_task, e1000_watchdog_task);
INIT_WORK(&adapter->downshift_task, e1000e_downshift_workaround);
INIT_WORK(&adapter->update_phy_task, e1000e_update_phy_task);
INIT_WORK(&adapter->print_hang_task, e1000_print_hw_hang);
/* Initialize link parameters. User can change them with ethtool */
adapter->hw.mac.autoneg = 1;
adapter->fc_autoneg = true;
adapter->hw.fc.requested_mode = e1000_fc_default;
adapter->hw.fc.current_mode = e1000_fc_default;
adapter->hw.phy.autoneg_advertised = 0x2f;
/* ring size defaults */
adapter->rx_ring->count = 256;
adapter->tx_ring->count = 256;
/*
* Initial Wake on LAN setting - If APM wake is enabled in
* the EEPROM, enable the ACPI Magic Packet filter
*/
if (adapter->flags & FLAG_APME_IN_WUC) {
/* APME bit in EEPROM is mapped to WUC.APME */
eeprom_data = er32(WUC);
eeprom_apme_mask = E1000_WUC_APME;
if ((hw->mac.type > e1000_ich10lan) &&
(eeprom_data & E1000_WUC_PHY_WAKE))
adapter->flags2 |= FLAG2_HAS_PHY_WAKEUP;
} else if (adapter->flags & FLAG_APME_IN_CTRL3) {
if (adapter->flags & FLAG_APME_CHECK_PORT_B &&
(adapter->hw.bus.func == 1))
e1000_read_nvm(&adapter->hw, NVM_INIT_CONTROL3_PORT_B,
1, &eeprom_data);
else
e1000_read_nvm(&adapter->hw, NVM_INIT_CONTROL3_PORT_A,
1, &eeprom_data);
}
/* fetch WoL from EEPROM */
if (eeprom_data & eeprom_apme_mask)
adapter->eeprom_wol |= E1000_WUFC_MAG;
/*
* now that we have the eeprom settings, apply the special cases
* where the eeprom may be wrong or the board simply won't support
* wake on lan on a particular port
*/
if (!(adapter->flags & FLAG_HAS_WOL))
adapter->eeprom_wol = 0;
/* initialize the wol settings based on the eeprom settings */
adapter->wol = adapter->eeprom_wol;
device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol);
/* save off EEPROM version number */
e1000_read_nvm(&adapter->hw, 5, 1, &adapter->eeprom_vers);
/* reset the hardware with the new settings */
e1000e_reset(adapter);
/*
* If the controller has AMT, do not set DRV_LOAD until the interface
* is up. For all other cases, let the f/w know that the h/w is now
* under the control of the driver.
*/
if (!(adapter->flags & FLAG_HAS_AMT))
e1000e_get_hw_control(adapter);
strlcpy(netdev->name, "eth%d", sizeof(netdev->name));
err = register_netdev(netdev);
if (err)
goto err_register;
/* carrier off reporting is important to ethtool even BEFORE open */
netif_carrier_off(netdev);
e1000_print_device_info(adapter);
if (pci_dev_run_wake(pdev))
pm_runtime_put_noidle(&pdev->dev);
return 0;
err_register:
if (!(adapter->flags & FLAG_HAS_AMT))
e1000e_release_hw_control(adapter);
err_eeprom:
if (hw->phy.ops.check_reset_block && !hw->phy.ops.check_reset_block(hw))
e1000_phy_hw_reset(&adapter->hw);
err_hw_init:
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
err_sw_init:
if (adapter->hw.flash_address)
iounmap(adapter->hw.flash_address);
e1000e_reset_interrupt_capability(adapter);
err_flashmap:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_selected_regions(pdev,
pci_select_bars(pdev, IORESOURCE_MEM));
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/**
* e1000_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* e1000_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
**/
static void __devexit e1000_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
bool down = test_bit(__E1000_DOWN, &adapter->state);
/*
* The timers may be rescheduled, so explicitly disable them
* from being rescheduled.
*/
if (!down)
set_bit(__E1000_DOWN, &adapter->state);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_info_timer);
cancel_work_sync(&adapter->reset_task);
cancel_work_sync(&adapter->watchdog_task);
cancel_work_sync(&adapter->downshift_task);
cancel_work_sync(&adapter->update_phy_task);
cancel_work_sync(&adapter->print_hang_task);
if (!(netdev->flags & IFF_UP))
e1000_power_down_phy(adapter);
/* Don't lie to e1000_close() down the road. */
if (!down)
clear_bit(__E1000_DOWN, &adapter->state);
unregister_netdev(netdev);
if (pci_dev_run_wake(pdev))
pm_runtime_get_noresume(&pdev->dev);
/*
* Release control of h/w to f/w. If f/w is AMT enabled, this
* would have already happened in close and is redundant.
*/
e1000e_release_hw_control(adapter);
e1000e_reset_interrupt_capability(adapter);
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
iounmap(adapter->hw.hw_addr);
if (adapter->hw.flash_address)
iounmap(adapter->hw.flash_address);
pci_release_selected_regions(pdev,
pci_select_bars(pdev, IORESOURCE_MEM));
free_netdev(netdev);
/* AER disable */
pci_disable_pcie_error_reporting(pdev);
pci_disable_device(pdev);
}
/* PCI Error Recovery (ERS) */
static struct pci_error_handlers e1000_err_handler = {
.error_detected = e1000_io_error_detected,
.slot_reset = e1000_io_slot_reset,
.resume = e1000_io_resume,
};
static DEFINE_PCI_DEVICE_TABLE(e1000_pci_tbl) = {
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571EB_COPPER), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571EB_FIBER), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571EB_QUAD_COPPER), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571EB_QUAD_COPPER_LP), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571EB_QUAD_FIBER), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571EB_SERDES), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571EB_SERDES_DUAL), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571EB_SERDES_QUAD), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82571PT_QUAD_COPPER), board_82571 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82572EI), board_82572 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82572EI_COPPER), board_82572 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82572EI_FIBER), board_82572 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82572EI_SERDES), board_82572 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82573E), board_82573 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82573E_IAMT), board_82573 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82573L), board_82573 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82574L), board_82574 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82574LA), board_82574 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82583V), board_82583 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_80003ES2LAN_COPPER_DPT),
board_80003es2lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_80003ES2LAN_COPPER_SPT),
board_80003es2lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_80003ES2LAN_SERDES_DPT),
board_80003es2lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_80003ES2LAN_SERDES_SPT),
board_80003es2lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH8_IFE), board_ich8lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH8_IFE_G), board_ich8lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH8_IFE_GT), board_ich8lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH8_IGP_AMT), board_ich8lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH8_IGP_C), board_ich8lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH8_IGP_M), board_ich8lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH8_IGP_M_AMT), board_ich8lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH8_82567V_3), board_ich8lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_IFE), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_IFE_G), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_IFE_GT), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_IGP_AMT), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_IGP_C), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_BM), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_IGP_M), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_IGP_M_AMT), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH9_IGP_M_V), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH10_R_BM_LM), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH10_R_BM_LF), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH10_R_BM_V), board_ich9lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH10_D_BM_LM), board_ich10lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH10_D_BM_LF), board_ich10lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_ICH10_D_BM_V), board_ich10lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_PCH_M_HV_LM), board_pchlan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_PCH_M_HV_LC), board_pchlan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_PCH_D_HV_DM), board_pchlan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_PCH_D_HV_DC), board_pchlan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_PCH2_LV_LM), board_pch2lan },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_PCH2_LV_V), board_pch2lan },
{ 0, 0, 0, 0, 0, 0, 0 } /* terminate list */
};
MODULE_DEVICE_TABLE(pci, e1000_pci_tbl);
#ifdef CONFIG_PM
static const struct dev_pm_ops e1000_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(e1000_suspend, e1000_resume)
SET_RUNTIME_PM_OPS(e1000_runtime_suspend,
e1000_runtime_resume, e1000_idle)
};
#endif
/* PCI Device API Driver */
static struct pci_driver e1000_driver = {
.name = e1000e_driver_name,
.id_table = e1000_pci_tbl,
.probe = e1000_probe,
.remove = __devexit_p(e1000_remove),
#ifdef CONFIG_PM
.driver = {
.pm = &e1000_pm_ops,
},
#endif
.shutdown = e1000_shutdown,
.err_handler = &e1000_err_handler
};
/**
* e1000_init_module - Driver Registration Routine
*
* e1000_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
**/
static int __init e1000_init_module(void)
{
int ret;
pr_info("Intel(R) PRO/1000 Network Driver - %s\n",
e1000e_driver_version);
pr_info("Copyright(c) 1999 - 2012 Intel Corporation.\n");
ret = pci_register_driver(&e1000_driver);
return ret;
}
module_init(e1000_init_module);
/**
* e1000_exit_module - Driver Exit Cleanup Routine
*
* e1000_exit_module is called just before the driver is removed
* from memory.
**/
static void __exit e1000_exit_module(void)
{
pci_unregister_driver(&e1000_driver);
}
module_exit(e1000_exit_module);
MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>");
MODULE_DESCRIPTION("Intel(R) PRO/1000 Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
/* netdev.c */
| gpl-2.0 |
XXMrHyde/android_kernel_moto_shamu | drivers/media/usb/dvb-usb/pctv452e.c | 2257 | 25204 | /*
* PCTV 452e DVB driver
*
* Copyright (c) 2006-2008 Dominik Kuhlen <dkuhlen@gmx.net>
*
* TT connect S2-3650-CI Common Interface support, MAC readout
* Copyright (C) 2008 Michael H. Schimek <mschimek@gmx.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; either version 2 of
* the License, or (at your option) any later version.
*/
/* dvb usb framework */
#define DVB_USB_LOG_PREFIX "pctv452e"
#include "dvb-usb.h"
/* Demodulator */
#include "stb0899_drv.h"
#include "stb0899_reg.h"
#include "stb0899_cfg.h"
/* Tuner */
#include "stb6100.h"
#include "stb6100_cfg.h"
/* FE Power */
#include "lnbp22.h"
#include "dvb_ca_en50221.h"
#include "ttpci-eeprom.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off).");
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
#define ISOC_INTERFACE_ALTERNATIVE 3
#define SYNC_BYTE_OUT 0xaa
#define SYNC_BYTE_IN 0x55
/* guessed: (copied from ttusb-budget) */
#define PCTV_CMD_RESET 0x15
/* command to poll IR receiver */
#define PCTV_CMD_IR 0x1b
/* command to send I2C */
#define PCTV_CMD_I2C 0x31
#define I2C_ADDR_STB0899 (0xd0 >> 1)
#define I2C_ADDR_STB6100 (0xc0 >> 1)
#define I2C_ADDR_LNBP22 (0x10 >> 1)
#define I2C_ADDR_24C16 (0xa0 >> 1)
#define I2C_ADDR_24C64 (0xa2 >> 1)
/* pctv452e sends us this amount of data for each issued usb-command */
#define PCTV_ANSWER_LEN 64
/* Wait up to 1000ms for device */
#define PCTV_TIMEOUT 1000
#define PCTV_LED_GPIO STB0899_GPIO01
#define PCTV_LED_GREEN 0x82
#define PCTV_LED_ORANGE 0x02
#define ci_dbg(format, arg...) \
do { \
if (0) \
printk(KERN_DEBUG DVB_USB_LOG_PREFIX \
": " format "\n" , ## arg); \
} while (0)
enum {
TT3650_CMD_CI_TEST = 0x40,
TT3650_CMD_CI_RD_CTRL,
TT3650_CMD_CI_WR_CTRL,
TT3650_CMD_CI_RD_ATTR,
TT3650_CMD_CI_WR_ATTR,
TT3650_CMD_CI_RESET,
TT3650_CMD_CI_SET_VIDEO_PORT
};
static struct stb0899_postproc pctv45e_postproc[] = {
{ PCTV_LED_GPIO, STB0899_GPIOPULLUP },
{ 0, 0 }
};
/*
* stores all private variables for communication with the PCTV452e DVB-S2
*/
struct pctv452e_state {
struct dvb_ca_en50221 ca;
struct mutex ca_mutex;
u8 c; /* transaction counter, wraps around... */
u8 initialized; /* set to 1 if 0x15 has been sent */
u16 last_rc_key;
};
static int tt3650_ci_msg(struct dvb_usb_device *d, u8 cmd, u8 *data,
unsigned int write_len, unsigned int read_len)
{
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 buf[64];
u8 id;
unsigned int rlen;
int ret;
BUG_ON(NULL == data && 0 != (write_len | read_len));
BUG_ON(write_len > 64 - 4);
BUG_ON(read_len > 64 - 4);
id = state->c++;
buf[0] = SYNC_BYTE_OUT;
buf[1] = id;
buf[2] = cmd;
buf[3] = write_len;
memcpy(buf + 4, data, write_len);
rlen = (read_len > 0) ? 64 : 0;
ret = dvb_usb_generic_rw(d, buf, 4 + write_len,
buf, rlen, /* delay_ms */ 0);
if (0 != ret)
goto failed;
ret = -EIO;
if (SYNC_BYTE_IN != buf[0] || id != buf[1])
goto failed;
memcpy(data, buf + 4, read_len);
return 0;
failed:
err("CI error %d; %02X %02X %02X -> %*ph.",
ret, SYNC_BYTE_OUT, id, cmd, 3, buf);
return ret;
}
static int tt3650_ci_msg_locked(struct dvb_ca_en50221 *ca,
u8 cmd, u8 *data, unsigned int write_len,
unsigned int read_len)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
int ret;
mutex_lock(&state->ca_mutex);
ret = tt3650_ci_msg(d, cmd, data, write_len, read_len);
mutex_unlock(&state->ca_mutex);
return ret;
}
static int tt3650_ci_read_attribute_mem(struct dvb_ca_en50221 *ca,
int slot, int address)
{
u8 buf[3];
int ret;
if (0 != slot)
return -EINVAL;
buf[0] = (address >> 8) & 0x0F;
buf[1] = address;
ret = tt3650_ci_msg_locked(ca, TT3650_CMD_CI_RD_ATTR, buf, 2, 3);
ci_dbg("%s %04x -> %d 0x%02x",
__func__, address, ret, buf[2]);
if (ret < 0)
return ret;
return buf[2];
}
static int tt3650_ci_write_attribute_mem(struct dvb_ca_en50221 *ca,
int slot, int address, u8 value)
{
u8 buf[3];
ci_dbg("%s %d 0x%04x 0x%02x",
__func__, slot, address, value);
if (0 != slot)
return -EINVAL;
buf[0] = (address >> 8) & 0x0F;
buf[1] = address;
buf[2] = value;
return tt3650_ci_msg_locked(ca, TT3650_CMD_CI_WR_ATTR, buf, 3, 3);
}
static int tt3650_ci_read_cam_control(struct dvb_ca_en50221 *ca,
int slot,
u8 address)
{
u8 buf[2];
int ret;
if (0 != slot)
return -EINVAL;
buf[0] = address & 3;
ret = tt3650_ci_msg_locked(ca, TT3650_CMD_CI_RD_CTRL, buf, 1, 2);
ci_dbg("%s 0x%02x -> %d 0x%02x",
__func__, address, ret, buf[1]);
if (ret < 0)
return ret;
return buf[1];
}
static int tt3650_ci_write_cam_control(struct dvb_ca_en50221 *ca,
int slot,
u8 address,
u8 value)
{
u8 buf[2];
ci_dbg("%s %d 0x%02x 0x%02x",
__func__, slot, address, value);
if (0 != slot)
return -EINVAL;
buf[0] = address;
buf[1] = value;
return tt3650_ci_msg_locked(ca, TT3650_CMD_CI_WR_CTRL, buf, 2, 2);
}
static int tt3650_ci_set_video_port(struct dvb_ca_en50221 *ca,
int slot,
int enable)
{
u8 buf[1];
int ret;
ci_dbg("%s %d %d", __func__, slot, enable);
if (0 != slot)
return -EINVAL;
enable = !!enable;
buf[0] = enable;
ret = tt3650_ci_msg_locked(ca, TT3650_CMD_CI_SET_VIDEO_PORT, buf, 1, 1);
if (ret < 0)
return ret;
if (enable != buf[0]) {
err("CI not %sabled.", enable ? "en" : "dis");
return -EIO;
}
return 0;
}
static int tt3650_ci_slot_shutdown(struct dvb_ca_en50221 *ca, int slot)
{
return tt3650_ci_set_video_port(ca, slot, /* enable */ 0);
}
static int tt3650_ci_slot_ts_enable(struct dvb_ca_en50221 *ca, int slot)
{
return tt3650_ci_set_video_port(ca, slot, /* enable */ 1);
}
static int tt3650_ci_slot_reset(struct dvb_ca_en50221 *ca, int slot)
{
struct dvb_usb_device *d = (struct dvb_usb_device *)ca->data;
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 buf[1];
int ret;
ci_dbg("%s %d", __func__, slot);
if (0 != slot)
return -EINVAL;
buf[0] = 0;
mutex_lock(&state->ca_mutex);
ret = tt3650_ci_msg(d, TT3650_CMD_CI_RESET, buf, 1, 1);
if (0 != ret)
goto failed;
msleep(500);
buf[0] = 1;
ret = tt3650_ci_msg(d, TT3650_CMD_CI_RESET, buf, 1, 1);
if (0 != ret)
goto failed;
msleep(500);
buf[0] = 0; /* FTA */
ret = tt3650_ci_msg(d, TT3650_CMD_CI_SET_VIDEO_PORT, buf, 1, 1);
failed:
mutex_unlock(&state->ca_mutex);
return ret;
}
static int tt3650_ci_poll_slot_status(struct dvb_ca_en50221 *ca,
int slot,
int open)
{
u8 buf[1];
int ret;
if (0 != slot)
return -EINVAL;
ret = tt3650_ci_msg_locked(ca, TT3650_CMD_CI_TEST, buf, 0, 1);
if (0 != ret)
return ret;
if (1 == buf[0])
return DVB_CA_EN50221_POLL_CAM_PRESENT |
DVB_CA_EN50221_POLL_CAM_READY;
return 0;
}
static void tt3650_ci_uninit(struct dvb_usb_device *d)
{
struct pctv452e_state *state;
ci_dbg("%s", __func__);
if (NULL == d)
return;
state = (struct pctv452e_state *)d->priv;
if (NULL == state)
return;
if (NULL == state->ca.data)
return;
/* Error ignored. */
tt3650_ci_set_video_port(&state->ca, /* slot */ 0, /* enable */ 0);
dvb_ca_en50221_release(&state->ca);
memset(&state->ca, 0, sizeof(state->ca));
}
static int tt3650_ci_init(struct dvb_usb_adapter *a)
{
struct dvb_usb_device *d = a->dev;
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
int ret;
ci_dbg("%s", __func__);
mutex_init(&state->ca_mutex);
state->ca.owner = THIS_MODULE;
state->ca.read_attribute_mem = tt3650_ci_read_attribute_mem;
state->ca.write_attribute_mem = tt3650_ci_write_attribute_mem;
state->ca.read_cam_control = tt3650_ci_read_cam_control;
state->ca.write_cam_control = tt3650_ci_write_cam_control;
state->ca.slot_reset = tt3650_ci_slot_reset;
state->ca.slot_shutdown = tt3650_ci_slot_shutdown;
state->ca.slot_ts_enable = tt3650_ci_slot_ts_enable;
state->ca.poll_slot_status = tt3650_ci_poll_slot_status;
state->ca.data = d;
ret = dvb_ca_en50221_init(&a->dvb_adap,
&state->ca,
/* flags */ 0,
/* n_slots */ 1);
if (0 != ret) {
err("Cannot initialize CI: Error %d.", ret);
memset(&state->ca, 0, sizeof(state->ca));
return ret;
}
info("CI initialized.");
return 0;
}
#define CMD_BUFFER_SIZE 0x28
static int pctv452e_i2c_msg(struct dvb_usb_device *d, u8 addr,
const u8 *snd_buf, u8 snd_len,
u8 *rcv_buf, u8 rcv_len)
{
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 buf[64];
u8 id;
int ret;
id = state->c++;
ret = -EINVAL;
if (snd_len > 64 - 7 || rcv_len > 64 - 7)
goto failed;
buf[0] = SYNC_BYTE_OUT;
buf[1] = id;
buf[2] = PCTV_CMD_I2C;
buf[3] = snd_len + 3;
buf[4] = addr << 1;
buf[5] = snd_len;
buf[6] = rcv_len;
memcpy(buf + 7, snd_buf, snd_len);
ret = dvb_usb_generic_rw(d, buf, 7 + snd_len,
buf, /* rcv_len */ 64,
/* delay_ms */ 0);
if (ret < 0)
goto failed;
/* TT USB protocol error. */
ret = -EIO;
if (SYNC_BYTE_IN != buf[0] || id != buf[1])
goto failed;
/* I2C device didn't respond as expected. */
ret = -EREMOTEIO;
if (buf[5] < snd_len || buf[6] < rcv_len)
goto failed;
memcpy(rcv_buf, buf + 7, rcv_len);
return rcv_len;
failed:
err("I2C error %d; %02X %02X %02X %02X %02X -> "
"%02X %02X %02X %02X %02X.",
ret, SYNC_BYTE_OUT, id, addr << 1, snd_len, rcv_len,
buf[0], buf[1], buf[4], buf[5], buf[6]);
return ret;
}
static int pctv452e_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msg,
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adapter);
int i;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
u8 addr, snd_len, rcv_len, *snd_buf, *rcv_buf;
int ret;
if (msg[i].flags & I2C_M_RD) {
addr = msg[i].addr;
snd_buf = NULL;
snd_len = 0;
rcv_buf = msg[i].buf;
rcv_len = msg[i].len;
} else {
addr = msg[i].addr;
snd_buf = msg[i].buf;
snd_len = msg[i].len;
rcv_buf = NULL;
rcv_len = 0;
}
ret = pctv452e_i2c_msg(d, addr, snd_buf, snd_len, rcv_buf,
rcv_len);
if (ret < rcv_len)
break;
}
mutex_unlock(&d->i2c_mutex);
return i;
}
static u32 pctv452e_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static int pctv452e_power_ctrl(struct dvb_usb_device *d, int i)
{
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 b0[] = { 0xaa, 0, PCTV_CMD_RESET, 1, 0 };
u8 rx[PCTV_ANSWER_LEN];
int ret;
info("%s: %d\n", __func__, i);
if (!i)
return 0;
if (state->initialized)
return 0;
/* hmm where shoud this should go? */
ret = usb_set_interface(d->udev, 0, ISOC_INTERFACE_ALTERNATIVE);
if (ret != 0)
info("%s: Warning set interface returned: %d\n",
__func__, ret);
/* this is a one-time initialization, dont know where to put */
b0[1] = state->c++;
/* reset board */
ret = dvb_usb_generic_rw(d, b0, sizeof(b0), rx, PCTV_ANSWER_LEN, 0);
if (ret)
return ret;
b0[1] = state->c++;
b0[4] = 1;
/* reset board (again?) */
ret = dvb_usb_generic_rw(d, b0, sizeof(b0), rx, PCTV_ANSWER_LEN, 0);
if (ret)
return ret;
state->initialized = 1;
return 0;
}
static int pctv452e_rc_query(struct dvb_usb_device *d)
{
struct pctv452e_state *state = (struct pctv452e_state *)d->priv;
u8 b[CMD_BUFFER_SIZE];
u8 rx[PCTV_ANSWER_LEN];
int ret, i;
u8 id = state->c++;
/* prepare command header */
b[0] = SYNC_BYTE_OUT;
b[1] = id;
b[2] = PCTV_CMD_IR;
b[3] = 0;
/* send ir request */
ret = dvb_usb_generic_rw(d, b, 4, rx, PCTV_ANSWER_LEN, 0);
if (ret != 0)
return ret;
if (debug > 3) {
info("%s: read: %2d: %*ph: ", __func__, ret, 3, rx);
for (i = 0; (i < rx[3]) && ((i+3) < PCTV_ANSWER_LEN); i++)
info(" %02x", rx[i+3]);
info("\n");
}
if ((rx[3] == 9) && (rx[12] & 0x01)) {
/* got a "press" event */
state->last_rc_key = (rx[7] << 8) | rx[6];
if (debug > 2)
info("%s: cmd=0x%02x sys=0x%02x\n",
__func__, rx[6], rx[7]);
rc_keydown(d->rc_dev, state->last_rc_key, 0);
} else if (state->last_rc_key) {
rc_keyup(d->rc_dev);
state->last_rc_key = 0;
}
return 0;
}
static int pctv452e_read_mac_address(struct dvb_usb_device *d, u8 mac[6])
{
const u8 mem_addr[] = { 0x1f, 0xcc };
u8 encoded_mac[20];
int ret;
ret = -EAGAIN;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
goto failed;
ret = pctv452e_i2c_msg(d, I2C_ADDR_24C16,
mem_addr + 1, /* snd_len */ 1,
encoded_mac, /* rcv_len */ 20);
if (-EREMOTEIO == ret)
/* Caution! A 24C16 interprets 0xA2 0x1F 0xCC as a
byte write if /WC is low. */
ret = pctv452e_i2c_msg(d, I2C_ADDR_24C64,
mem_addr, 2,
encoded_mac, 20);
mutex_unlock(&d->i2c_mutex);
if (20 != ret)
goto failed;
ret = ttpci_eeprom_decode_mac(mac, encoded_mac);
if (0 != ret)
goto failed;
return 0;
failed:
memset(mac, 0, 6);
return ret;
}
static const struct stb0899_s1_reg pctv452e_init_dev[] = {
{ STB0899_DISCNTRL1, 0x26 },
{ STB0899_DISCNTRL2, 0x80 },
{ STB0899_DISRX_ST0, 0x04 },
{ STB0899_DISRX_ST1, 0x20 },
{ STB0899_DISPARITY, 0x00 },
{ STB0899_DISFIFO, 0x00 },
{ STB0899_DISF22, 0x99 },
{ STB0899_DISF22RX, 0x85 }, /* 0xa8 */
{ STB0899_ACRPRESC, 0x11 },
{ STB0899_ACRDIV1, 0x0a },
{ STB0899_ACRDIV2, 0x05 },
{ STB0899_DACR1 , 0x00 },
{ STB0899_DACR2 , 0x00 },
{ STB0899_OUTCFG, 0x00 },
{ STB0899_MODECFG, 0x00 }, /* Inversion */
{ STB0899_IRQMSK_3, 0xf3 },
{ STB0899_IRQMSK_2, 0xfc },
{ STB0899_IRQMSK_1, 0xff },
{ STB0899_IRQMSK_0, 0xff },
{ STB0899_I2CCFG, 0x88 },
{ STB0899_I2CRPT, 0x58 },
{ STB0899_GPIO00CFG, 0x82 },
{ STB0899_GPIO01CFG, 0x82 }, /* LED: 0x02 green, 0x82 orange */
{ STB0899_GPIO02CFG, 0x82 },
{ STB0899_GPIO03CFG, 0x82 },
{ STB0899_GPIO04CFG, 0x82 },
{ STB0899_GPIO05CFG, 0x82 },
{ STB0899_GPIO06CFG, 0x82 },
{ STB0899_GPIO07CFG, 0x82 },
{ STB0899_GPIO08CFG, 0x82 },
{ STB0899_GPIO09CFG, 0x82 },
{ STB0899_GPIO10CFG, 0x82 },
{ STB0899_GPIO11CFG, 0x82 },
{ STB0899_GPIO12CFG, 0x82 },
{ STB0899_GPIO13CFG, 0x82 },
{ STB0899_GPIO14CFG, 0x82 },
{ STB0899_GPIO15CFG, 0x82 },
{ STB0899_GPIO16CFG, 0x82 },
{ STB0899_GPIO17CFG, 0x82 },
{ STB0899_GPIO18CFG, 0x82 },
{ STB0899_GPIO19CFG, 0x82 },
{ STB0899_GPIO20CFG, 0x82 },
{ STB0899_SDATCFG, 0xb8 },
{ STB0899_SCLTCFG, 0xba },
{ STB0899_AGCRFCFG, 0x1c }, /* 0x11 DVB-S; 0x1c DVB-S2 (1c, rjkm) */
{ STB0899_GPIO22, 0x82 },
{ STB0899_GPIO21, 0x91 },
{ STB0899_DIRCLKCFG, 0x82 },
{ STB0899_CLKOUT27CFG, 0x7e },
{ STB0899_STDBYCFG, 0x82 },
{ STB0899_CS0CFG, 0x82 },
{ STB0899_CS1CFG, 0x82 },
{ STB0899_DISEQCOCFG, 0x20 },
{ STB0899_NCOARSE, 0x15 }, /* 0x15 27Mhz, F/3 198MHz, F/6 108MHz */
{ STB0899_SYNTCTRL, 0x00 }, /* 0x00 CLKI, 0x02 XTALI */
{ STB0899_FILTCTRL, 0x00 },
{ STB0899_SYSCTRL, 0x00 },
{ STB0899_STOPCLK1, 0x20 }, /* orig: 0x00 budget-ci: 0x20 */
{ STB0899_STOPCLK2, 0x00 },
{ STB0899_INTBUFCTRL, 0x0a },
{ STB0899_AGC2I1, 0x00 },
{ STB0899_AGC2I2, 0x00 },
{ STB0899_AGCIQIN, 0x00 },
{ STB0899_TSTRES, 0x40 }, /* rjkm */
{ 0xffff, 0xff },
};
static const struct stb0899_s1_reg pctv452e_init_s1_demod[] = {
{ STB0899_DEMOD, 0x00 },
{ STB0899_RCOMPC, 0xc9 },
{ STB0899_AGC1CN, 0x01 },
{ STB0899_AGC1REF, 0x10 },
{ STB0899_RTC, 0x23 },
{ STB0899_TMGCFG, 0x4e },
{ STB0899_AGC2REF, 0x34 },
{ STB0899_TLSR, 0x84 },
{ STB0899_CFD, 0xf7 },
{ STB0899_ACLC, 0x87 },
{ STB0899_BCLC, 0x94 },
{ STB0899_EQON, 0x41 },
{ STB0899_LDT, 0xf1 },
{ STB0899_LDT2, 0xe3 },
{ STB0899_EQUALREF, 0xb4 },
{ STB0899_TMGRAMP, 0x10 },
{ STB0899_TMGTHD, 0x30 },
{ STB0899_IDCCOMP, 0xfd },
{ STB0899_QDCCOMP, 0xff },
{ STB0899_POWERI, 0x0c },
{ STB0899_POWERQ, 0x0f },
{ STB0899_RCOMP, 0x6c },
{ STB0899_AGCIQIN, 0x80 },
{ STB0899_AGC2I1, 0x06 },
{ STB0899_AGC2I2, 0x00 },
{ STB0899_TLIR, 0x30 },
{ STB0899_RTF, 0x7f },
{ STB0899_DSTATUS, 0x00 },
{ STB0899_LDI, 0xbc },
{ STB0899_CFRM, 0xea },
{ STB0899_CFRL, 0x31 },
{ STB0899_NIRM, 0x2b },
{ STB0899_NIRL, 0x80 },
{ STB0899_ISYMB, 0x1d },
{ STB0899_QSYMB, 0xa6 },
{ STB0899_SFRH, 0x2f },
{ STB0899_SFRM, 0x68 },
{ STB0899_SFRL, 0x40 },
{ STB0899_SFRUPH, 0x2f },
{ STB0899_SFRUPM, 0x68 },
{ STB0899_SFRUPL, 0x40 },
{ STB0899_EQUAI1, 0x02 },
{ STB0899_EQUAQ1, 0xff },
{ STB0899_EQUAI2, 0x04 },
{ STB0899_EQUAQ2, 0x05 },
{ STB0899_EQUAI3, 0x02 },
{ STB0899_EQUAQ3, 0xfd },
{ STB0899_EQUAI4, 0x03 },
{ STB0899_EQUAQ4, 0x07 },
{ STB0899_EQUAI5, 0x08 },
{ STB0899_EQUAQ5, 0xf5 },
{ STB0899_DSTATUS2, 0x00 },
{ STB0899_VSTATUS, 0x00 },
{ STB0899_VERROR, 0x86 },
{ STB0899_IQSWAP, 0x2a },
{ STB0899_ECNT1M, 0x00 },
{ STB0899_ECNT1L, 0x00 },
{ STB0899_ECNT2M, 0x00 },
{ STB0899_ECNT2L, 0x00 },
{ STB0899_ECNT3M, 0x0a },
{ STB0899_ECNT3L, 0xad },
{ STB0899_FECAUTO1, 0x06 },
{ STB0899_FECM, 0x01 },
{ STB0899_VTH12, 0xb0 },
{ STB0899_VTH23, 0x7a },
{ STB0899_VTH34, 0x58 },
{ STB0899_VTH56, 0x38 },
{ STB0899_VTH67, 0x34 },
{ STB0899_VTH78, 0x24 },
{ STB0899_PRVIT, 0xff },
{ STB0899_VITSYNC, 0x19 },
{ STB0899_RSULC, 0xb1 }, /* DVB = 0xb1, DSS = 0xa1 */
{ STB0899_TSULC, 0x42 },
{ STB0899_RSLLC, 0x41 },
{ STB0899_TSLPL, 0x12 },
{ STB0899_TSCFGH, 0x0c },
{ STB0899_TSCFGM, 0x00 },
{ STB0899_TSCFGL, 0x00 },
{ STB0899_TSOUT, 0x69 }, /* 0x0d for CAM */
{ STB0899_RSSYNCDEL, 0x00 },
{ STB0899_TSINHDELH, 0x02 },
{ STB0899_TSINHDELM, 0x00 },
{ STB0899_TSINHDELL, 0x00 },
{ STB0899_TSLLSTKM, 0x1b },
{ STB0899_TSLLSTKL, 0xb3 },
{ STB0899_TSULSTKM, 0x00 },
{ STB0899_TSULSTKL, 0x00 },
{ STB0899_PCKLENUL, 0xbc },
{ STB0899_PCKLENLL, 0xcc },
{ STB0899_RSPCKLEN, 0xbd },
{ STB0899_TSSTATUS, 0x90 },
{ STB0899_ERRCTRL1, 0xb6 },
{ STB0899_ERRCTRL2, 0x95 },
{ STB0899_ERRCTRL3, 0x8d },
{ STB0899_DMONMSK1, 0x27 },
{ STB0899_DMONMSK0, 0x03 },
{ STB0899_DEMAPVIT, 0x5c },
{ STB0899_PLPARM, 0x19 },
{ STB0899_PDELCTRL, 0x48 },
{ STB0899_PDELCTRL2, 0x00 },
{ STB0899_BBHCTRL1, 0x00 },
{ STB0899_BBHCTRL2, 0x00 },
{ STB0899_HYSTTHRESH, 0x77 },
{ STB0899_MATCSTM, 0x00 },
{ STB0899_MATCSTL, 0x00 },
{ STB0899_UPLCSTM, 0x00 },
{ STB0899_UPLCSTL, 0x00 },
{ STB0899_DFLCSTM, 0x00 },
{ STB0899_DFLCSTL, 0x00 },
{ STB0899_SYNCCST, 0x00 },
{ STB0899_SYNCDCSTM, 0x00 },
{ STB0899_SYNCDCSTL, 0x00 },
{ STB0899_ISI_ENTRY, 0x00 },
{ STB0899_ISI_BIT_EN, 0x00 },
{ STB0899_MATSTRM, 0xf0 },
{ STB0899_MATSTRL, 0x02 },
{ STB0899_UPLSTRM, 0x45 },
{ STB0899_UPLSTRL, 0x60 },
{ STB0899_DFLSTRM, 0xe3 },
{ STB0899_DFLSTRL, 0x00 },
{ STB0899_SYNCSTR, 0x47 },
{ STB0899_SYNCDSTRM, 0x05 },
{ STB0899_SYNCDSTRL, 0x18 },
{ STB0899_CFGPDELSTATUS1, 0x19 },
{ STB0899_CFGPDELSTATUS2, 0x2b },
{ STB0899_BBFERRORM, 0x00 },
{ STB0899_BBFERRORL, 0x01 },
{ STB0899_UPKTERRORM, 0x00 },
{ STB0899_UPKTERRORL, 0x00 },
{ 0xffff, 0xff },
};
static struct stb0899_config stb0899_config = {
.init_dev = pctv452e_init_dev,
.init_s2_demod = stb0899_s2_init_2,
.init_s1_demod = pctv452e_init_s1_demod,
.init_s2_fec = stb0899_s2_init_4,
.init_tst = stb0899_s1_init_5,
.demod_address = I2C_ADDR_STB0899, /* I2C Address */
.block_sync_mode = STB0899_SYNC_FORCED, /* ? */
.xtal_freq = 27000000, /* Assume Hz ? */
.inversion = IQ_SWAP_ON, /* ? */
.lo_clk = 76500000,
.hi_clk = 99000000,
.ts_output_mode = 0, /* Use parallel mode */
.clock_polarity = 0,
.data_clk_parity = 0,
.fec_mode = 0,
.esno_ave = STB0899_DVBS2_ESNO_AVE,
.esno_quant = STB0899_DVBS2_ESNO_QUANT,
.avframes_coarse = STB0899_DVBS2_AVFRAMES_COARSE,
.avframes_fine = STB0899_DVBS2_AVFRAMES_FINE,
.miss_threshold = STB0899_DVBS2_MISS_THRESHOLD,
.uwp_threshold_acq = STB0899_DVBS2_UWP_THRESHOLD_ACQ,
.uwp_threshold_track = STB0899_DVBS2_UWP_THRESHOLD_TRACK,
.uwp_threshold_sof = STB0899_DVBS2_UWP_THRESHOLD_SOF,
.sof_search_timeout = STB0899_DVBS2_SOF_SEARCH_TIMEOUT,
.btr_nco_bits = STB0899_DVBS2_BTR_NCO_BITS,
.btr_gain_shift_offset = STB0899_DVBS2_BTR_GAIN_SHIFT_OFFSET,
.crl_nco_bits = STB0899_DVBS2_CRL_NCO_BITS,
.ldpc_max_iter = STB0899_DVBS2_LDPC_MAX_ITER,
.tuner_get_frequency = stb6100_get_frequency,
.tuner_set_frequency = stb6100_set_frequency,
.tuner_set_bandwidth = stb6100_set_bandwidth,
.tuner_get_bandwidth = stb6100_get_bandwidth,
.tuner_set_rfsiggain = NULL,
/* helper for switching LED green/orange */
.postproc = pctv45e_postproc
};
static struct stb6100_config stb6100_config = {
.tuner_address = I2C_ADDR_STB6100,
.refclock = 27000000
};
static struct i2c_algorithm pctv452e_i2c_algo = {
.master_xfer = pctv452e_i2c_xfer,
.functionality = pctv452e_i2c_func
};
static int pctv452e_frontend_attach(struct dvb_usb_adapter *a)
{
struct usb_device_id *id;
a->fe_adap[0].fe = dvb_attach(stb0899_attach, &stb0899_config,
&a->dev->i2c_adap);
if (!a->fe_adap[0].fe)
return -ENODEV;
if ((dvb_attach(lnbp22_attach, a->fe_adap[0].fe,
&a->dev->i2c_adap)) == 0)
err("Cannot attach lnbp22\n");
id = a->dev->desc->warm_ids[0];
if (USB_VID_TECHNOTREND == id->idVendor
&& USB_PID_TECHNOTREND_CONNECT_S2_3650_CI == id->idProduct)
/* Error ignored. */
tt3650_ci_init(a);
return 0;
}
static int pctv452e_tuner_attach(struct dvb_usb_adapter *a)
{
if (!a->fe_adap[0].fe)
return -ENODEV;
if (dvb_attach(stb6100_attach, a->fe_adap[0].fe, &stb6100_config,
&a->dev->i2c_adap) == 0) {
err("%s failed\n", __func__);
return -ENODEV;
}
return 0;
}
static struct usb_device_id pctv452e_usb_table[] = {
{USB_DEVICE(USB_VID_PINNACLE, USB_PID_PCTV_452E)},
{USB_DEVICE(USB_VID_TECHNOTREND, USB_PID_TECHNOTREND_CONNECT_S2_3600)},
{USB_DEVICE(USB_VID_TECHNOTREND,
USB_PID_TECHNOTREND_CONNECT_S2_3650_CI)},
{}
};
MODULE_DEVICE_TABLE(usb, pctv452e_usb_table);
static struct dvb_usb_device_properties pctv452e_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER, /* more ? */
.usb_ctrl = DEVICE_SPECIFIC,
.size_of_priv = sizeof(struct pctv452e_state),
.power_ctrl = pctv452e_power_ctrl,
.rc.core = {
.rc_codes = RC_MAP_DIB0700_RC5_TABLE,
.allowed_protos = RC_BIT_UNKNOWN,
.rc_query = pctv452e_rc_query,
.rc_interval = 100,
},
.num_adapters = 1,
.adapter = {{
.num_frontends = 1,
.fe = {{
.frontend_attach = pctv452e_frontend_attach,
.tuner_attach = pctv452e_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_ISOC,
.count = 4,
.endpoint = 0x02,
.u = {
.isoc = {
.framesperurb = 4,
.framesize = 940,
.interval = 1
}
}
},
} },
} },
.i2c_algo = &pctv452e_i2c_algo,
.generic_bulk_ctrl_endpoint = 1, /* allow generice rw function */
.num_device_descs = 1,
.devices = {
{ .name = "PCTV HDTV USB",
.cold_ids = { NULL, NULL }, /* this is a warm only device */
.warm_ids = { &pctv452e_usb_table[0], NULL }
},
{ 0 },
}
};
static struct dvb_usb_device_properties tt_connect_s2_3600_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER, /* more ? */
.usb_ctrl = DEVICE_SPECIFIC,
.size_of_priv = sizeof(struct pctv452e_state),
.power_ctrl = pctv452e_power_ctrl,
.read_mac_address = pctv452e_read_mac_address,
.rc.core = {
.rc_codes = RC_MAP_TT_1500,
.allowed_protos = RC_BIT_UNKNOWN,
.rc_query = pctv452e_rc_query,
.rc_interval = 100,
},
.num_adapters = 1,
.adapter = {{
.num_frontends = 1,
.fe = {{
.frontend_attach = pctv452e_frontend_attach,
.tuner_attach = pctv452e_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_ISOC,
.count = 7,
.endpoint = 0x02,
.u = {
.isoc = {
.framesperurb = 4,
.framesize = 940,
.interval = 1
}
}
},
} },
} },
.i2c_algo = &pctv452e_i2c_algo,
.generic_bulk_ctrl_endpoint = 1, /* allow generic rw function*/
.num_device_descs = 2,
.devices = {
{ .name = "Technotrend TT Connect S2-3600",
.cold_ids = { NULL, NULL }, /* this is a warm only device */
.warm_ids = { &pctv452e_usb_table[1], NULL }
},
{ .name = "Technotrend TT Connect S2-3650-CI",
.cold_ids = { NULL, NULL },
.warm_ids = { &pctv452e_usb_table[2], NULL }
},
{ 0 },
}
};
static void pctv452e_usb_disconnect(struct usb_interface *intf)
{
struct dvb_usb_device *d = usb_get_intfdata(intf);
tt3650_ci_uninit(d);
dvb_usb_device_exit(intf);
}
static int pctv452e_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
if (0 == dvb_usb_device_init(intf, &pctv452e_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &tt_connect_s2_3600_properties,
THIS_MODULE, NULL, adapter_nr))
return 0;
return -ENODEV;
}
static struct usb_driver pctv452e_usb_driver = {
.name = "pctv452e",
.probe = pctv452e_usb_probe,
.disconnect = pctv452e_usb_disconnect,
.id_table = pctv452e_usb_table,
};
module_usb_driver(pctv452e_usb_driver);
MODULE_AUTHOR("Dominik Kuhlen <dkuhlen@gmx.net>");
MODULE_AUTHOR("Andre Weidemann <Andre.Weidemann@web.de>");
MODULE_AUTHOR("Michael H. Schimek <mschimek@gmx.at>");
MODULE_DESCRIPTION("Pinnacle PCTV HDTV USB DVB / TT connect S2-3600 Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
bluechiptechnology/Rx3_linux_3.0.35_4.0.0 | drivers/edac/e752x_edac.c | 3025 | 40658 | /*
* Intel e752x Memory Controller kernel module
* (C) 2004 Linux Networx (http://lnxi.com)
* This file may be distributed under the terms of the
* GNU General Public License.
*
* See "enum e752x_chips" below for supported chipsets
*
* Written by Tom Zimmerman
*
* Contributors:
* Thayne Harbaugh at realmsys.com (?)
* Wang Zhenyu at intel.com
* Dave Jiang at mvista.com
*
* $Id: edac_e752x.c,v 1.5.2.11 2005/10/05 00:43:44 dsp_llnl Exp $
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/edac.h>
#include "edac_core.h"
#define E752X_REVISION " Ver: 2.0.2"
#define EDAC_MOD_STR "e752x_edac"
static int report_non_memory_errors;
static int force_function_unhide;
static int sysbus_parity = -1;
static struct edac_pci_ctl_info *e752x_pci;
#define e752x_printk(level, fmt, arg...) \
edac_printk(level, "e752x", fmt, ##arg)
#define e752x_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "e752x", fmt, ##arg)
#ifndef PCI_DEVICE_ID_INTEL_7520_0
#define PCI_DEVICE_ID_INTEL_7520_0 0x3590
#endif /* PCI_DEVICE_ID_INTEL_7520_0 */
#ifndef PCI_DEVICE_ID_INTEL_7520_1_ERR
#define PCI_DEVICE_ID_INTEL_7520_1_ERR 0x3591
#endif /* PCI_DEVICE_ID_INTEL_7520_1_ERR */
#ifndef PCI_DEVICE_ID_INTEL_7525_0
#define PCI_DEVICE_ID_INTEL_7525_0 0x359E
#endif /* PCI_DEVICE_ID_INTEL_7525_0 */
#ifndef PCI_DEVICE_ID_INTEL_7525_1_ERR
#define PCI_DEVICE_ID_INTEL_7525_1_ERR 0x3593
#endif /* PCI_DEVICE_ID_INTEL_7525_1_ERR */
#ifndef PCI_DEVICE_ID_INTEL_7320_0
#define PCI_DEVICE_ID_INTEL_7320_0 0x3592
#endif /* PCI_DEVICE_ID_INTEL_7320_0 */
#ifndef PCI_DEVICE_ID_INTEL_7320_1_ERR
#define PCI_DEVICE_ID_INTEL_7320_1_ERR 0x3593
#endif /* PCI_DEVICE_ID_INTEL_7320_1_ERR */
#ifndef PCI_DEVICE_ID_INTEL_3100_0
#define PCI_DEVICE_ID_INTEL_3100_0 0x35B0
#endif /* PCI_DEVICE_ID_INTEL_3100_0 */
#ifndef PCI_DEVICE_ID_INTEL_3100_1_ERR
#define PCI_DEVICE_ID_INTEL_3100_1_ERR 0x35B1
#endif /* PCI_DEVICE_ID_INTEL_3100_1_ERR */
#define E752X_NR_CSROWS 8 /* number of csrows */
/* E752X register addresses - device 0 function 0 */
#define E752X_MCHSCRB 0x52 /* Memory Scrub register (16b) */
/*
* 6:5 Scrub Completion Count
* 3:2 Scrub Rate (i3100 only)
* 01=fast 10=normal
* 1:0 Scrub Mode enable
* 00=off 10=on
*/
#define E752X_DRB 0x60 /* DRAM row boundary register (8b) */
#define E752X_DRA 0x70 /* DRAM row attribute register (8b) */
/*
* 31:30 Device width row 7
* 01=x8 10=x4 11=x8 DDR2
* 27:26 Device width row 6
* 23:22 Device width row 5
* 19:20 Device width row 4
* 15:14 Device width row 3
* 11:10 Device width row 2
* 7:6 Device width row 1
* 3:2 Device width row 0
*/
#define E752X_DRC 0x7C /* DRAM controller mode reg (32b) */
/* FIXME:IS THIS RIGHT? */
/*
* 22 Number channels 0=1,1=2
* 19:18 DRB Granularity 32/64MB
*/
#define E752X_DRM 0x80 /* Dimm mapping register */
#define E752X_DDRCSR 0x9A /* DDR control and status reg (16b) */
/*
* 14:12 1 single A, 2 single B, 3 dual
*/
#define E752X_TOLM 0xC4 /* DRAM top of low memory reg (16b) */
#define E752X_REMAPBASE 0xC6 /* DRAM remap base address reg (16b) */
#define E752X_REMAPLIMIT 0xC8 /* DRAM remap limit address reg (16b) */
#define E752X_REMAPOFFSET 0xCA /* DRAM remap limit offset reg (16b) */
/* E752X register addresses - device 0 function 1 */
#define E752X_FERR_GLOBAL 0x40 /* Global first error register (32b) */
#define E752X_NERR_GLOBAL 0x44 /* Global next error register (32b) */
#define E752X_HI_FERR 0x50 /* Hub interface first error reg (8b) */
#define E752X_HI_NERR 0x52 /* Hub interface next error reg (8b) */
#define E752X_HI_ERRMASK 0x54 /* Hub interface error mask reg (8b) */
#define E752X_HI_SMICMD 0x5A /* Hub interface SMI command reg (8b) */
#define E752X_SYSBUS_FERR 0x60 /* System buss first error reg (16b) */
#define E752X_SYSBUS_NERR 0x62 /* System buss next error reg (16b) */
#define E752X_SYSBUS_ERRMASK 0x64 /* System buss error mask reg (16b) */
#define E752X_SYSBUS_SMICMD 0x6A /* System buss SMI command reg (16b) */
#define E752X_BUF_FERR 0x70 /* Memory buffer first error reg (8b) */
#define E752X_BUF_NERR 0x72 /* Memory buffer next error reg (8b) */
#define E752X_BUF_ERRMASK 0x74 /* Memory buffer error mask reg (8b) */
#define E752X_BUF_SMICMD 0x7A /* Memory buffer SMI cmd reg (8b) */
#define E752X_DRAM_FERR 0x80 /* DRAM first error register (16b) */
#define E752X_DRAM_NERR 0x82 /* DRAM next error register (16b) */
#define E752X_DRAM_ERRMASK 0x84 /* DRAM error mask register (8b) */
#define E752X_DRAM_SMICMD 0x8A /* DRAM SMI command register (8b) */
#define E752X_DRAM_RETR_ADD 0xAC /* DRAM Retry address register (32b) */
#define E752X_DRAM_SEC1_ADD 0xA0 /* DRAM first correctable memory */
/* error address register (32b) */
/*
* 31 Reserved
* 30:2 CE address (64 byte block 34:6
* 1 Reserved
* 0 HiLoCS
*/
#define E752X_DRAM_SEC2_ADD 0xC8 /* DRAM first correctable memory */
/* error address register (32b) */
/*
* 31 Reserved
* 30:2 CE address (64 byte block 34:6)
* 1 Reserved
* 0 HiLoCS
*/
#define E752X_DRAM_DED_ADD 0xA4 /* DRAM first uncorrectable memory */
/* error address register (32b) */
/*
* 31 Reserved
* 30:2 CE address (64 byte block 34:6)
* 1 Reserved
* 0 HiLoCS
*/
#define E752X_DRAM_SCRB_ADD 0xA8 /* DRAM 1st uncorrectable scrub mem */
/* error address register (32b) */
/*
* 31 Reserved
* 30:2 CE address (64 byte block 34:6
* 1 Reserved
* 0 HiLoCS
*/
#define E752X_DRAM_SEC1_SYNDROME 0xC4 /* DRAM first correctable memory */
/* error syndrome register (16b) */
#define E752X_DRAM_SEC2_SYNDROME 0xC6 /* DRAM second correctable memory */
/* error syndrome register (16b) */
#define E752X_DEVPRES1 0xF4 /* Device Present 1 register (8b) */
/* 3100 IMCH specific register addresses - device 0 function 1 */
#define I3100_NSI_FERR 0x48 /* NSI first error reg (32b) */
#define I3100_NSI_NERR 0x4C /* NSI next error reg (32b) */
#define I3100_NSI_SMICMD 0x54 /* NSI SMI command register (32b) */
#define I3100_NSI_EMASK 0x90 /* NSI error mask register (32b) */
/* ICH5R register addresses - device 30 function 0 */
#define ICH5R_PCI_STAT 0x06 /* PCI status register (16b) */
#define ICH5R_PCI_2ND_STAT 0x1E /* PCI status secondary reg (16b) */
#define ICH5R_PCI_BRIDGE_CTL 0x3E /* PCI bridge control register (16b) */
enum e752x_chips {
E7520 = 0,
E7525 = 1,
E7320 = 2,
I3100 = 3
};
struct e752x_pvt {
struct pci_dev *bridge_ck;
struct pci_dev *dev_d0f0;
struct pci_dev *dev_d0f1;
u32 tolm;
u32 remapbase;
u32 remaplimit;
int mc_symmetric;
u8 map[8];
int map_type;
const struct e752x_dev_info *dev_info;
};
struct e752x_dev_info {
u16 err_dev;
u16 ctl_dev;
const char *ctl_name;
};
struct e752x_error_info {
u32 ferr_global;
u32 nerr_global;
u32 nsi_ferr; /* 3100 only */
u32 nsi_nerr; /* 3100 only */
u8 hi_ferr; /* all but 3100 */
u8 hi_nerr; /* all but 3100 */
u16 sysbus_ferr;
u16 sysbus_nerr;
u8 buf_ferr;
u8 buf_nerr;
u16 dram_ferr;
u16 dram_nerr;
u32 dram_sec1_add;
u32 dram_sec2_add;
u16 dram_sec1_syndrome;
u16 dram_sec2_syndrome;
u32 dram_ded_add;
u32 dram_scrb_add;
u32 dram_retr_add;
};
static const struct e752x_dev_info e752x_devs[] = {
[E7520] = {
.err_dev = PCI_DEVICE_ID_INTEL_7520_1_ERR,
.ctl_dev = PCI_DEVICE_ID_INTEL_7520_0,
.ctl_name = "E7520"},
[E7525] = {
.err_dev = PCI_DEVICE_ID_INTEL_7525_1_ERR,
.ctl_dev = PCI_DEVICE_ID_INTEL_7525_0,
.ctl_name = "E7525"},
[E7320] = {
.err_dev = PCI_DEVICE_ID_INTEL_7320_1_ERR,
.ctl_dev = PCI_DEVICE_ID_INTEL_7320_0,
.ctl_name = "E7320"},
[I3100] = {
.err_dev = PCI_DEVICE_ID_INTEL_3100_1_ERR,
.ctl_dev = PCI_DEVICE_ID_INTEL_3100_0,
.ctl_name = "3100"},
};
/* Valid scrub rates for the e752x/3100 hardware memory scrubber. We
* map the scrubbing bandwidth to a hardware register value. The 'set'
* operation finds the 'matching or higher value'. Note that scrubbing
* on the e752x can only be enabled/disabled. The 3100 supports
* a normal and fast mode.
*/
#define SDRATE_EOT 0xFFFFFFFF
struct scrubrate {
u32 bandwidth; /* bandwidth consumed by scrubbing in bytes/sec */
u16 scrubval; /* register value for scrub rate */
};
/* Rate below assumes same performance as i3100 using PC3200 DDR2 in
* normal mode. e752x bridges don't support choosing normal or fast mode,
* so the scrubbing bandwidth value isn't all that important - scrubbing is
* either on or off.
*/
static const struct scrubrate scrubrates_e752x[] = {
{0, 0x00}, /* Scrubbing Off */
{500000, 0x02}, /* Scrubbing On */
{SDRATE_EOT, 0x00} /* End of Table */
};
/* Fast mode: 2 GByte PC3200 DDR2 scrubbed in 33s = 63161283 bytes/s
* Normal mode: 125 (32000 / 256) times slower than fast mode.
*/
static const struct scrubrate scrubrates_i3100[] = {
{0, 0x00}, /* Scrubbing Off */
{500000, 0x0a}, /* Normal mode - 32k clocks */
{62500000, 0x06}, /* Fast mode - 256 clocks */
{SDRATE_EOT, 0x00} /* End of Table */
};
static unsigned long ctl_page_to_phys(struct mem_ctl_info *mci,
unsigned long page)
{
u32 remap;
struct e752x_pvt *pvt = (struct e752x_pvt *)mci->pvt_info;
debugf3("%s()\n", __func__);
if (page < pvt->tolm)
return page;
if ((page >= 0x100000) && (page < pvt->remapbase))
return page;
remap = (page - pvt->tolm) + pvt->remapbase;
if (remap < pvt->remaplimit)
return remap;
e752x_printk(KERN_ERR, "Invalid page %lx - out of range\n", page);
return pvt->tolm - 1;
}
static void do_process_ce(struct mem_ctl_info *mci, u16 error_one,
u32 sec1_add, u16 sec1_syndrome)
{
u32 page;
int row;
int channel;
int i;
struct e752x_pvt *pvt = (struct e752x_pvt *)mci->pvt_info;
debugf3("%s()\n", __func__);
/* convert the addr to 4k page */
page = sec1_add >> (PAGE_SHIFT - 4);
/* FIXME - check for -1 */
if (pvt->mc_symmetric) {
/* chip select are bits 14 & 13 */
row = ((page >> 1) & 3);
e752x_printk(KERN_WARNING,
"Test row %d Table %d %d %d %d %d %d %d %d\n", row,
pvt->map[0], pvt->map[1], pvt->map[2], pvt->map[3],
pvt->map[4], pvt->map[5], pvt->map[6],
pvt->map[7]);
/* test for channel remapping */
for (i = 0; i < 8; i++) {
if (pvt->map[i] == row)
break;
}
e752x_printk(KERN_WARNING, "Test computed row %d\n", i);
if (i < 8)
row = i;
else
e752x_mc_printk(mci, KERN_WARNING,
"row %d not found in remap table\n",
row);
} else
row = edac_mc_find_csrow_by_page(mci, page);
/* 0 = channel A, 1 = channel B */
channel = !(error_one & 1);
/* e752x mc reads 34:6 of the DRAM linear address */
edac_mc_handle_ce(mci, page, offset_in_page(sec1_add << 4),
sec1_syndrome, row, channel, "e752x CE");
}
static inline void process_ce(struct mem_ctl_info *mci, u16 error_one,
u32 sec1_add, u16 sec1_syndrome, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_process_ce(mci, error_one, sec1_add, sec1_syndrome);
}
static void do_process_ue(struct mem_ctl_info *mci, u16 error_one,
u32 ded_add, u32 scrb_add)
{
u32 error_2b, block_page;
int row;
struct e752x_pvt *pvt = (struct e752x_pvt *)mci->pvt_info;
debugf3("%s()\n", __func__);
if (error_one & 0x0202) {
error_2b = ded_add;
/* convert to 4k address */
block_page = error_2b >> (PAGE_SHIFT - 4);
row = pvt->mc_symmetric ?
/* chip select are bits 14 & 13 */
((block_page >> 1) & 3) :
edac_mc_find_csrow_by_page(mci, block_page);
/* e752x mc reads 34:6 of the DRAM linear address */
edac_mc_handle_ue(mci, block_page,
offset_in_page(error_2b << 4),
row, "e752x UE from Read");
}
if (error_one & 0x0404) {
error_2b = scrb_add;
/* convert to 4k address */
block_page = error_2b >> (PAGE_SHIFT - 4);
row = pvt->mc_symmetric ?
/* chip select are bits 14 & 13 */
((block_page >> 1) & 3) :
edac_mc_find_csrow_by_page(mci, block_page);
/* e752x mc reads 34:6 of the DRAM linear address */
edac_mc_handle_ue(mci, block_page,
offset_in_page(error_2b << 4),
row, "e752x UE from Scruber");
}
}
static inline void process_ue(struct mem_ctl_info *mci, u16 error_one,
u32 ded_add, u32 scrb_add, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_process_ue(mci, error_one, ded_add, scrb_add);
}
static inline void process_ue_no_info_wr(struct mem_ctl_info *mci,
int *error_found, int handle_error)
{
*error_found = 1;
if (!handle_error)
return;
debugf3("%s()\n", __func__);
edac_mc_handle_ue_no_info(mci, "e752x UE log memory write");
}
static void do_process_ded_retry(struct mem_ctl_info *mci, u16 error,
u32 retry_add)
{
u32 error_1b, page;
int row;
struct e752x_pvt *pvt = (struct e752x_pvt *)mci->pvt_info;
error_1b = retry_add;
page = error_1b >> (PAGE_SHIFT - 4); /* convert the addr to 4k page */
/* chip select are bits 14 & 13 */
row = pvt->mc_symmetric ? ((page >> 1) & 3) :
edac_mc_find_csrow_by_page(mci, page);
e752x_mc_printk(mci, KERN_WARNING,
"CE page 0x%lx, row %d : Memory read retry\n",
(long unsigned int)page, row);
}
static inline void process_ded_retry(struct mem_ctl_info *mci, u16 error,
u32 retry_add, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_process_ded_retry(mci, error, retry_add);
}
static inline void process_threshold_ce(struct mem_ctl_info *mci, u16 error,
int *error_found, int handle_error)
{
*error_found = 1;
if (handle_error)
e752x_mc_printk(mci, KERN_WARNING, "Memory threshold CE\n");
}
static char *global_message[11] = {
"PCI Express C1",
"PCI Express C",
"PCI Express B1",
"PCI Express B",
"PCI Express A1",
"PCI Express A",
"DMA Controller",
"HUB or NS Interface",
"System Bus",
"DRAM Controller", /* 9th entry */
"Internal Buffer"
};
#define DRAM_ENTRY 9
static char *fatal_message[2] = { "Non-Fatal ", "Fatal " };
static void do_global_error(int fatal, u32 errors)
{
int i;
for (i = 0; i < 11; i++) {
if (errors & (1 << i)) {
/* If the error is from DRAM Controller OR
* we are to report ALL errors, then
* report the error
*/
if ((i == DRAM_ENTRY) || report_non_memory_errors)
e752x_printk(KERN_WARNING, "%sError %s\n",
fatal_message[fatal],
global_message[i]);
}
}
}
static inline void global_error(int fatal, u32 errors, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_global_error(fatal, errors);
}
static char *hub_message[7] = {
"HI Address or Command Parity", "HI Illegal Access",
"HI Internal Parity", "Out of Range Access",
"HI Data Parity", "Enhanced Config Access",
"Hub Interface Target Abort"
};
static void do_hub_error(int fatal, u8 errors)
{
int i;
for (i = 0; i < 7; i++) {
if (errors & (1 << i))
e752x_printk(KERN_WARNING, "%sError %s\n",
fatal_message[fatal], hub_message[i]);
}
}
static inline void hub_error(int fatal, u8 errors, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_hub_error(fatal, errors);
}
#define NSI_FATAL_MASK 0x0c080081
#define NSI_NON_FATAL_MASK 0x23a0ba64
#define NSI_ERR_MASK (NSI_FATAL_MASK | NSI_NON_FATAL_MASK)
static char *nsi_message[30] = {
"NSI Link Down", /* NSI_FERR/NSI_NERR bit 0, fatal error */
"", /* reserved */
"NSI Parity Error", /* bit 2, non-fatal */
"", /* reserved */
"", /* reserved */
"Correctable Error Message", /* bit 5, non-fatal */
"Non-Fatal Error Message", /* bit 6, non-fatal */
"Fatal Error Message", /* bit 7, fatal */
"", /* reserved */
"Receiver Error", /* bit 9, non-fatal */
"", /* reserved */
"Bad TLP", /* bit 11, non-fatal */
"Bad DLLP", /* bit 12, non-fatal */
"REPLAY_NUM Rollover", /* bit 13, non-fatal */
"", /* reserved */
"Replay Timer Timeout", /* bit 15, non-fatal */
"", /* reserved */
"", /* reserved */
"", /* reserved */
"Data Link Protocol Error", /* bit 19, fatal */
"", /* reserved */
"Poisoned TLP", /* bit 21, non-fatal */
"", /* reserved */
"Completion Timeout", /* bit 23, non-fatal */
"Completer Abort", /* bit 24, non-fatal */
"Unexpected Completion", /* bit 25, non-fatal */
"Receiver Overflow", /* bit 26, fatal */
"Malformed TLP", /* bit 27, fatal */
"", /* reserved */
"Unsupported Request" /* bit 29, non-fatal */
};
static void do_nsi_error(int fatal, u32 errors)
{
int i;
for (i = 0; i < 30; i++) {
if (errors & (1 << i))
printk(KERN_WARNING "%sError %s\n",
fatal_message[fatal], nsi_message[i]);
}
}
static inline void nsi_error(int fatal, u32 errors, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_nsi_error(fatal, errors);
}
static char *membuf_message[4] = {
"Internal PMWB to DRAM parity",
"Internal PMWB to System Bus Parity",
"Internal System Bus or IO to PMWB Parity",
"Internal DRAM to PMWB Parity"
};
static void do_membuf_error(u8 errors)
{
int i;
for (i = 0; i < 4; i++) {
if (errors & (1 << i))
e752x_printk(KERN_WARNING, "Non-Fatal Error %s\n",
membuf_message[i]);
}
}
static inline void membuf_error(u8 errors, int *error_found, int handle_error)
{
*error_found = 1;
if (handle_error)
do_membuf_error(errors);
}
static char *sysbus_message[10] = {
"Addr or Request Parity",
"Data Strobe Glitch",
"Addr Strobe Glitch",
"Data Parity",
"Addr Above TOM",
"Non DRAM Lock Error",
"MCERR", "BINIT",
"Memory Parity",
"IO Subsystem Parity"
};
static void do_sysbus_error(int fatal, u32 errors)
{
int i;
for (i = 0; i < 10; i++) {
if (errors & (1 << i))
e752x_printk(KERN_WARNING, "%sError System Bus %s\n",
fatal_message[fatal], sysbus_message[i]);
}
}
static inline void sysbus_error(int fatal, u32 errors, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_sysbus_error(fatal, errors);
}
static void e752x_check_hub_interface(struct e752x_error_info *info,
int *error_found, int handle_error)
{
u8 stat8;
//pci_read_config_byte(dev,E752X_HI_FERR,&stat8);
stat8 = info->hi_ferr;
if (stat8 & 0x7f) { /* Error, so process */
stat8 &= 0x7f;
if (stat8 & 0x2b)
hub_error(1, stat8 & 0x2b, error_found, handle_error);
if (stat8 & 0x54)
hub_error(0, stat8 & 0x54, error_found, handle_error);
}
//pci_read_config_byte(dev,E752X_HI_NERR,&stat8);
stat8 = info->hi_nerr;
if (stat8 & 0x7f) { /* Error, so process */
stat8 &= 0x7f;
if (stat8 & 0x2b)
hub_error(1, stat8 & 0x2b, error_found, handle_error);
if (stat8 & 0x54)
hub_error(0, stat8 & 0x54, error_found, handle_error);
}
}
static void e752x_check_ns_interface(struct e752x_error_info *info,
int *error_found, int handle_error)
{
u32 stat32;
stat32 = info->nsi_ferr;
if (stat32 & NSI_ERR_MASK) { /* Error, so process */
if (stat32 & NSI_FATAL_MASK) /* check for fatal errors */
nsi_error(1, stat32 & NSI_FATAL_MASK, error_found,
handle_error);
if (stat32 & NSI_NON_FATAL_MASK) /* check for non-fatal ones */
nsi_error(0, stat32 & NSI_NON_FATAL_MASK, error_found,
handle_error);
}
stat32 = info->nsi_nerr;
if (stat32 & NSI_ERR_MASK) {
if (stat32 & NSI_FATAL_MASK)
nsi_error(1, stat32 & NSI_FATAL_MASK, error_found,
handle_error);
if (stat32 & NSI_NON_FATAL_MASK)
nsi_error(0, stat32 & NSI_NON_FATAL_MASK, error_found,
handle_error);
}
}
static void e752x_check_sysbus(struct e752x_error_info *info,
int *error_found, int handle_error)
{
u32 stat32, error32;
//pci_read_config_dword(dev,E752X_SYSBUS_FERR,&stat32);
stat32 = info->sysbus_ferr + (info->sysbus_nerr << 16);
if (stat32 == 0)
return; /* no errors */
error32 = (stat32 >> 16) & 0x3ff;
stat32 = stat32 & 0x3ff;
if (stat32 & 0x087)
sysbus_error(1, stat32 & 0x087, error_found, handle_error);
if (stat32 & 0x378)
sysbus_error(0, stat32 & 0x378, error_found, handle_error);
if (error32 & 0x087)
sysbus_error(1, error32 & 0x087, error_found, handle_error);
if (error32 & 0x378)
sysbus_error(0, error32 & 0x378, error_found, handle_error);
}
static void e752x_check_membuf(struct e752x_error_info *info,
int *error_found, int handle_error)
{
u8 stat8;
stat8 = info->buf_ferr;
if (stat8 & 0x0f) { /* Error, so process */
stat8 &= 0x0f;
membuf_error(stat8, error_found, handle_error);
}
stat8 = info->buf_nerr;
if (stat8 & 0x0f) { /* Error, so process */
stat8 &= 0x0f;
membuf_error(stat8, error_found, handle_error);
}
}
static void e752x_check_dram(struct mem_ctl_info *mci,
struct e752x_error_info *info, int *error_found,
int handle_error)
{
u16 error_one, error_next;
error_one = info->dram_ferr;
error_next = info->dram_nerr;
/* decode and report errors */
if (error_one & 0x0101) /* check first error correctable */
process_ce(mci, error_one, info->dram_sec1_add,
info->dram_sec1_syndrome, error_found, handle_error);
if (error_next & 0x0101) /* check next error correctable */
process_ce(mci, error_next, info->dram_sec2_add,
info->dram_sec2_syndrome, error_found, handle_error);
if (error_one & 0x4040)
process_ue_no_info_wr(mci, error_found, handle_error);
if (error_next & 0x4040)
process_ue_no_info_wr(mci, error_found, handle_error);
if (error_one & 0x2020)
process_ded_retry(mci, error_one, info->dram_retr_add,
error_found, handle_error);
if (error_next & 0x2020)
process_ded_retry(mci, error_next, info->dram_retr_add,
error_found, handle_error);
if (error_one & 0x0808)
process_threshold_ce(mci, error_one, error_found, handle_error);
if (error_next & 0x0808)
process_threshold_ce(mci, error_next, error_found,
handle_error);
if (error_one & 0x0606)
process_ue(mci, error_one, info->dram_ded_add,
info->dram_scrb_add, error_found, handle_error);
if (error_next & 0x0606)
process_ue(mci, error_next, info->dram_ded_add,
info->dram_scrb_add, error_found, handle_error);
}
static void e752x_get_error_info(struct mem_ctl_info *mci,
struct e752x_error_info *info)
{
struct pci_dev *dev;
struct e752x_pvt *pvt;
memset(info, 0, sizeof(*info));
pvt = (struct e752x_pvt *)mci->pvt_info;
dev = pvt->dev_d0f1;
pci_read_config_dword(dev, E752X_FERR_GLOBAL, &info->ferr_global);
if (info->ferr_global) {
if (pvt->dev_info->err_dev == PCI_DEVICE_ID_INTEL_3100_1_ERR) {
pci_read_config_dword(dev, I3100_NSI_FERR,
&info->nsi_ferr);
info->hi_ferr = 0;
} else {
pci_read_config_byte(dev, E752X_HI_FERR,
&info->hi_ferr);
info->nsi_ferr = 0;
}
pci_read_config_word(dev, E752X_SYSBUS_FERR,
&info->sysbus_ferr);
pci_read_config_byte(dev, E752X_BUF_FERR, &info->buf_ferr);
pci_read_config_word(dev, E752X_DRAM_FERR, &info->dram_ferr);
pci_read_config_dword(dev, E752X_DRAM_SEC1_ADD,
&info->dram_sec1_add);
pci_read_config_word(dev, E752X_DRAM_SEC1_SYNDROME,
&info->dram_sec1_syndrome);
pci_read_config_dword(dev, E752X_DRAM_DED_ADD,
&info->dram_ded_add);
pci_read_config_dword(dev, E752X_DRAM_SCRB_ADD,
&info->dram_scrb_add);
pci_read_config_dword(dev, E752X_DRAM_RETR_ADD,
&info->dram_retr_add);
/* ignore the reserved bits just in case */
if (info->hi_ferr & 0x7f)
pci_write_config_byte(dev, E752X_HI_FERR,
info->hi_ferr);
if (info->nsi_ferr & NSI_ERR_MASK)
pci_write_config_dword(dev, I3100_NSI_FERR,
info->nsi_ferr);
if (info->sysbus_ferr)
pci_write_config_word(dev, E752X_SYSBUS_FERR,
info->sysbus_ferr);
if (info->buf_ferr & 0x0f)
pci_write_config_byte(dev, E752X_BUF_FERR,
info->buf_ferr);
if (info->dram_ferr)
pci_write_bits16(pvt->bridge_ck, E752X_DRAM_FERR,
info->dram_ferr, info->dram_ferr);
pci_write_config_dword(dev, E752X_FERR_GLOBAL,
info->ferr_global);
}
pci_read_config_dword(dev, E752X_NERR_GLOBAL, &info->nerr_global);
if (info->nerr_global) {
if (pvt->dev_info->err_dev == PCI_DEVICE_ID_INTEL_3100_1_ERR) {
pci_read_config_dword(dev, I3100_NSI_NERR,
&info->nsi_nerr);
info->hi_nerr = 0;
} else {
pci_read_config_byte(dev, E752X_HI_NERR,
&info->hi_nerr);
info->nsi_nerr = 0;
}
pci_read_config_word(dev, E752X_SYSBUS_NERR,
&info->sysbus_nerr);
pci_read_config_byte(dev, E752X_BUF_NERR, &info->buf_nerr);
pci_read_config_word(dev, E752X_DRAM_NERR, &info->dram_nerr);
pci_read_config_dword(dev, E752X_DRAM_SEC2_ADD,
&info->dram_sec2_add);
pci_read_config_word(dev, E752X_DRAM_SEC2_SYNDROME,
&info->dram_sec2_syndrome);
if (info->hi_nerr & 0x7f)
pci_write_config_byte(dev, E752X_HI_NERR,
info->hi_nerr);
if (info->nsi_nerr & NSI_ERR_MASK)
pci_write_config_dword(dev, I3100_NSI_NERR,
info->nsi_nerr);
if (info->sysbus_nerr)
pci_write_config_word(dev, E752X_SYSBUS_NERR,
info->sysbus_nerr);
if (info->buf_nerr & 0x0f)
pci_write_config_byte(dev, E752X_BUF_NERR,
info->buf_nerr);
if (info->dram_nerr)
pci_write_bits16(pvt->bridge_ck, E752X_DRAM_NERR,
info->dram_nerr, info->dram_nerr);
pci_write_config_dword(dev, E752X_NERR_GLOBAL,
info->nerr_global);
}
}
static int e752x_process_error_info(struct mem_ctl_info *mci,
struct e752x_error_info *info,
int handle_errors)
{
u32 error32, stat32;
int error_found;
error_found = 0;
error32 = (info->ferr_global >> 18) & 0x3ff;
stat32 = (info->ferr_global >> 4) & 0x7ff;
if (error32)
global_error(1, error32, &error_found, handle_errors);
if (stat32)
global_error(0, stat32, &error_found, handle_errors);
error32 = (info->nerr_global >> 18) & 0x3ff;
stat32 = (info->nerr_global >> 4) & 0x7ff;
if (error32)
global_error(1, error32, &error_found, handle_errors);
if (stat32)
global_error(0, stat32, &error_found, handle_errors);
e752x_check_hub_interface(info, &error_found, handle_errors);
e752x_check_ns_interface(info, &error_found, handle_errors);
e752x_check_sysbus(info, &error_found, handle_errors);
e752x_check_membuf(info, &error_found, handle_errors);
e752x_check_dram(mci, info, &error_found, handle_errors);
return error_found;
}
static void e752x_check(struct mem_ctl_info *mci)
{
struct e752x_error_info info;
debugf3("%s()\n", __func__);
e752x_get_error_info(mci, &info);
e752x_process_error_info(mci, &info, 1);
}
/* Program byte/sec bandwidth scrub rate to hardware */
static int set_sdram_scrub_rate(struct mem_ctl_info *mci, u32 new_bw)
{
const struct scrubrate *scrubrates;
struct e752x_pvt *pvt = (struct e752x_pvt *) mci->pvt_info;
struct pci_dev *pdev = pvt->dev_d0f0;
int i;
if (pvt->dev_info->ctl_dev == PCI_DEVICE_ID_INTEL_3100_0)
scrubrates = scrubrates_i3100;
else
scrubrates = scrubrates_e752x;
/* Translate the desired scrub rate to a e752x/3100 register value.
* Search for the bandwidth that is equal or greater than the
* desired rate and program the cooresponding register value.
*/
for (i = 0; scrubrates[i].bandwidth != SDRATE_EOT; i++)
if (scrubrates[i].bandwidth >= new_bw)
break;
if (scrubrates[i].bandwidth == SDRATE_EOT)
return -1;
pci_write_config_word(pdev, E752X_MCHSCRB, scrubrates[i].scrubval);
return scrubrates[i].bandwidth;
}
/* Convert current scrub rate value into byte/sec bandwidth */
static int get_sdram_scrub_rate(struct mem_ctl_info *mci)
{
const struct scrubrate *scrubrates;
struct e752x_pvt *pvt = (struct e752x_pvt *) mci->pvt_info;
struct pci_dev *pdev = pvt->dev_d0f0;
u16 scrubval;
int i;
if (pvt->dev_info->ctl_dev == PCI_DEVICE_ID_INTEL_3100_0)
scrubrates = scrubrates_i3100;
else
scrubrates = scrubrates_e752x;
/* Find the bandwidth matching the memory scrubber configuration */
pci_read_config_word(pdev, E752X_MCHSCRB, &scrubval);
scrubval = scrubval & 0x0f;
for (i = 0; scrubrates[i].bandwidth != SDRATE_EOT; i++)
if (scrubrates[i].scrubval == scrubval)
break;
if (scrubrates[i].bandwidth == SDRATE_EOT) {
e752x_printk(KERN_WARNING,
"Invalid sdram scrub control value: 0x%x\n", scrubval);
return -1;
}
return scrubrates[i].bandwidth;
}
/* Return 1 if dual channel mode is active. Else return 0. */
static inline int dual_channel_active(u16 ddrcsr)
{
return (((ddrcsr >> 12) & 3) == 3);
}
/* Remap csrow index numbers if map_type is "reverse"
*/
static inline int remap_csrow_index(struct mem_ctl_info *mci, int index)
{
struct e752x_pvt *pvt = mci->pvt_info;
if (!pvt->map_type)
return (7 - index);
return (index);
}
static void e752x_init_csrows(struct mem_ctl_info *mci, struct pci_dev *pdev,
u16 ddrcsr)
{
struct csrow_info *csrow;
unsigned long last_cumul_size;
int index, mem_dev, drc_chan;
int drc_drbg; /* DRB granularity 0=64mb, 1=128mb */
int drc_ddim; /* DRAM Data Integrity Mode 0=none, 2=edac */
u8 value;
u32 dra, drc, cumul_size;
dra = 0;
for (index = 0; index < 4; index++) {
u8 dra_reg;
pci_read_config_byte(pdev, E752X_DRA + index, &dra_reg);
dra |= dra_reg << (index * 8);
}
pci_read_config_dword(pdev, E752X_DRC, &drc);
drc_chan = dual_channel_active(ddrcsr);
drc_drbg = drc_chan + 1; /* 128 in dual mode, 64 in single */
drc_ddim = (drc >> 20) & 0x3;
/* The dram row boundary (DRB) reg values are boundary address for
* each DRAM row with a granularity of 64 or 128MB (single/dual
* channel operation). DRB regs are cumulative; therefore DRB7 will
* contain the total memory contained in all eight rows.
*/
for (last_cumul_size = index = 0; index < mci->nr_csrows; index++) {
/* mem_dev 0=x8, 1=x4 */
mem_dev = (dra >> (index * 4 + 2)) & 0x3;
csrow = &mci->csrows[remap_csrow_index(mci, index)];
mem_dev = (mem_dev == 2);
pci_read_config_byte(pdev, E752X_DRB + index, &value);
/* convert a 128 or 64 MiB DRB to a page size. */
cumul_size = value << (25 + drc_drbg - PAGE_SHIFT);
debugf3("%s(): (%d) cumul_size 0x%x\n", __func__, index,
cumul_size);
if (cumul_size == last_cumul_size)
continue; /* not populated */
csrow->first_page = last_cumul_size;
csrow->last_page = cumul_size - 1;
csrow->nr_pages = cumul_size - last_cumul_size;
last_cumul_size = cumul_size;
csrow->grain = 1 << 12; /* 4KiB - resolution of CELOG */
csrow->mtype = MEM_RDDR; /* only one type supported */
csrow->dtype = mem_dev ? DEV_X4 : DEV_X8;
/*
* if single channel or x8 devices then SECDED
* if dual channel and x4 then S4ECD4ED
*/
if (drc_ddim) {
if (drc_chan && mem_dev) {
csrow->edac_mode = EDAC_S4ECD4ED;
mci->edac_cap |= EDAC_FLAG_S4ECD4ED;
} else {
csrow->edac_mode = EDAC_SECDED;
mci->edac_cap |= EDAC_FLAG_SECDED;
}
} else
csrow->edac_mode = EDAC_NONE;
}
}
static void e752x_init_mem_map_table(struct pci_dev *pdev,
struct e752x_pvt *pvt)
{
int index;
u8 value, last, row;
last = 0;
row = 0;
for (index = 0; index < 8; index += 2) {
pci_read_config_byte(pdev, E752X_DRB + index, &value);
/* test if there is a dimm in this slot */
if (value == last) {
/* no dimm in the slot, so flag it as empty */
pvt->map[index] = 0xff;
pvt->map[index + 1] = 0xff;
} else { /* there is a dimm in the slot */
pvt->map[index] = row;
row++;
last = value;
/* test the next value to see if the dimm is double
* sided
*/
pci_read_config_byte(pdev, E752X_DRB + index + 1,
&value);
/* the dimm is single sided, so flag as empty */
/* this is a double sided dimm to save the next row #*/
pvt->map[index + 1] = (value == last) ? 0xff : row;
row++;
last = value;
}
}
}
/* Return 0 on success or 1 on failure. */
static int e752x_get_devs(struct pci_dev *pdev, int dev_idx,
struct e752x_pvt *pvt)
{
struct pci_dev *dev;
pvt->bridge_ck = pci_get_device(PCI_VENDOR_ID_INTEL,
pvt->dev_info->err_dev, pvt->bridge_ck);
if (pvt->bridge_ck == NULL)
pvt->bridge_ck = pci_scan_single_device(pdev->bus,
PCI_DEVFN(0, 1));
if (pvt->bridge_ck == NULL) {
e752x_printk(KERN_ERR, "error reporting device not found:"
"vendor %x device 0x%x (broken BIOS?)\n",
PCI_VENDOR_ID_INTEL, e752x_devs[dev_idx].err_dev);
return 1;
}
dev = pci_get_device(PCI_VENDOR_ID_INTEL,
e752x_devs[dev_idx].ctl_dev,
NULL);
if (dev == NULL)
goto fail;
pvt->dev_d0f0 = dev;
pvt->dev_d0f1 = pci_dev_get(pvt->bridge_ck);
return 0;
fail:
pci_dev_put(pvt->bridge_ck);
return 1;
}
/* Setup system bus parity mask register.
* Sysbus parity supported on:
* e7320/e7520/e7525 + Xeon
*/
static void e752x_init_sysbus_parity_mask(struct e752x_pvt *pvt)
{
char *cpu_id = cpu_data(0).x86_model_id;
struct pci_dev *dev = pvt->dev_d0f1;
int enable = 1;
/* Allow module parameter override, else see if CPU supports parity */
if (sysbus_parity != -1) {
enable = sysbus_parity;
} else if (cpu_id[0] && !strstr(cpu_id, "Xeon")) {
e752x_printk(KERN_INFO, "System Bus Parity not "
"supported by CPU, disabling\n");
enable = 0;
}
if (enable)
pci_write_config_word(dev, E752X_SYSBUS_ERRMASK, 0x0000);
else
pci_write_config_word(dev, E752X_SYSBUS_ERRMASK, 0x0309);
}
static void e752x_init_error_reporting_regs(struct e752x_pvt *pvt)
{
struct pci_dev *dev;
dev = pvt->dev_d0f1;
/* Turn off error disable & SMI in case the BIOS turned it on */
if (pvt->dev_info->err_dev == PCI_DEVICE_ID_INTEL_3100_1_ERR) {
pci_write_config_dword(dev, I3100_NSI_EMASK, 0);
pci_write_config_dword(dev, I3100_NSI_SMICMD, 0);
} else {
pci_write_config_byte(dev, E752X_HI_ERRMASK, 0x00);
pci_write_config_byte(dev, E752X_HI_SMICMD, 0x00);
}
e752x_init_sysbus_parity_mask(pvt);
pci_write_config_word(dev, E752X_SYSBUS_SMICMD, 0x00);
pci_write_config_byte(dev, E752X_BUF_ERRMASK, 0x00);
pci_write_config_byte(dev, E752X_BUF_SMICMD, 0x00);
pci_write_config_byte(dev, E752X_DRAM_ERRMASK, 0x00);
pci_write_config_byte(dev, E752X_DRAM_SMICMD, 0x00);
}
static int e752x_probe1(struct pci_dev *pdev, int dev_idx)
{
u16 pci_data;
u8 stat8;
struct mem_ctl_info *mci;
struct e752x_pvt *pvt;
u16 ddrcsr;
int drc_chan; /* Number of channels 0=1chan,1=2chan */
struct e752x_error_info discard;
debugf0("%s(): mci\n", __func__);
debugf0("Starting Probe1\n");
/* check to see if device 0 function 1 is enabled; if it isn't, we
* assume the BIOS has reserved it for a reason and is expecting
* exclusive access, we take care not to violate that assumption and
* fail the probe. */
pci_read_config_byte(pdev, E752X_DEVPRES1, &stat8);
if (!force_function_unhide && !(stat8 & (1 << 5))) {
printk(KERN_INFO "Contact your BIOS vendor to see if the "
"E752x error registers can be safely un-hidden\n");
return -ENODEV;
}
stat8 |= (1 << 5);
pci_write_config_byte(pdev, E752X_DEVPRES1, stat8);
pci_read_config_word(pdev, E752X_DDRCSR, &ddrcsr);
/* FIXME: should check >>12 or 0xf, true for all? */
/* Dual channel = 1, Single channel = 0 */
drc_chan = dual_channel_active(ddrcsr);
mci = edac_mc_alloc(sizeof(*pvt), E752X_NR_CSROWS, drc_chan + 1, 0);
if (mci == NULL) {
return -ENOMEM;
}
debugf3("%s(): init mci\n", __func__);
mci->mtype_cap = MEM_FLAG_RDDR;
/* 3100 IMCH supports SECDEC only */
mci->edac_ctl_cap = (dev_idx == I3100) ? EDAC_FLAG_SECDED :
(EDAC_FLAG_NONE | EDAC_FLAG_SECDED | EDAC_FLAG_S4ECD4ED);
/* FIXME - what if different memory types are in different csrows? */
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = E752X_REVISION;
mci->dev = &pdev->dev;
debugf3("%s(): init pvt\n", __func__);
pvt = (struct e752x_pvt *)mci->pvt_info;
pvt->dev_info = &e752x_devs[dev_idx];
pvt->mc_symmetric = ((ddrcsr & 0x10) != 0);
if (e752x_get_devs(pdev, dev_idx, pvt)) {
edac_mc_free(mci);
return -ENODEV;
}
debugf3("%s(): more mci init\n", __func__);
mci->ctl_name = pvt->dev_info->ctl_name;
mci->dev_name = pci_name(pdev);
mci->edac_check = e752x_check;
mci->ctl_page_to_phys = ctl_page_to_phys;
mci->set_sdram_scrub_rate = set_sdram_scrub_rate;
mci->get_sdram_scrub_rate = get_sdram_scrub_rate;
/* set the map type. 1 = normal, 0 = reversed
* Must be set before e752x_init_csrows in case csrow mapping
* is reversed.
*/
pci_read_config_byte(pdev, E752X_DRM, &stat8);
pvt->map_type = ((stat8 & 0x0f) > ((stat8 >> 4) & 0x0f));
e752x_init_csrows(mci, pdev, ddrcsr);
e752x_init_mem_map_table(pdev, pvt);
if (dev_idx == I3100)
mci->edac_cap = EDAC_FLAG_SECDED; /* the only mode supported */
else
mci->edac_cap |= EDAC_FLAG_NONE;
debugf3("%s(): tolm, remapbase, remaplimit\n", __func__);
/* load the top of low memory, remap base, and remap limit vars */
pci_read_config_word(pdev, E752X_TOLM, &pci_data);
pvt->tolm = ((u32) pci_data) << 4;
pci_read_config_word(pdev, E752X_REMAPBASE, &pci_data);
pvt->remapbase = ((u32) pci_data) << 14;
pci_read_config_word(pdev, E752X_REMAPLIMIT, &pci_data);
pvt->remaplimit = ((u32) pci_data) << 14;
e752x_printk(KERN_INFO,
"tolm = %x, remapbase = %x, remaplimit = %x\n",
pvt->tolm, pvt->remapbase, pvt->remaplimit);
/* Here we assume that we will never see multiple instances of this
* type of memory controller. The ID is therefore hardcoded to 0.
*/
if (edac_mc_add_mc(mci)) {
debugf3("%s(): failed edac_mc_add_mc()\n", __func__);
goto fail;
}
e752x_init_error_reporting_regs(pvt);
e752x_get_error_info(mci, &discard); /* clear other MCH errors */
/* allocating generic PCI control info */
e752x_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!e752x_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n", __func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
/* get this far and it's successful */
debugf3("%s(): success\n", __func__);
return 0;
fail:
pci_dev_put(pvt->dev_d0f0);
pci_dev_put(pvt->dev_d0f1);
pci_dev_put(pvt->bridge_ck);
edac_mc_free(mci);
return -ENODEV;
}
/* returns count (>= 0), or negative on error */
static int __devinit e752x_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
debugf0("%s()\n", __func__);
/* wake up and enable device */
if (pci_enable_device(pdev) < 0)
return -EIO;
return e752x_probe1(pdev, ent->driver_data);
}
static void __devexit e752x_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
struct e752x_pvt *pvt;
debugf0("%s()\n", __func__);
if (e752x_pci)
edac_pci_release_generic_ctl(e752x_pci);
if ((mci = edac_mc_del_mc(&pdev->dev)) == NULL)
return;
pvt = (struct e752x_pvt *)mci->pvt_info;
pci_dev_put(pvt->dev_d0f0);
pci_dev_put(pvt->dev_d0f1);
pci_dev_put(pvt->bridge_ck);
edac_mc_free(mci);
}
static const struct pci_device_id e752x_pci_tbl[] __devinitdata = {
{
PCI_VEND_DEV(INTEL, 7520_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
E7520},
{
PCI_VEND_DEV(INTEL, 7525_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
E7525},
{
PCI_VEND_DEV(INTEL, 7320_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
E7320},
{
PCI_VEND_DEV(INTEL, 3100_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
I3100},
{
0,
} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, e752x_pci_tbl);
static struct pci_driver e752x_driver = {
.name = EDAC_MOD_STR,
.probe = e752x_init_one,
.remove = __devexit_p(e752x_remove_one),
.id_table = e752x_pci_tbl,
};
static int __init e752x_init(void)
{
int pci_rc;
debugf3("%s()\n", __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
pci_rc = pci_register_driver(&e752x_driver);
return (pci_rc < 0) ? pci_rc : 0;
}
static void __exit e752x_exit(void)
{
debugf3("%s()\n", __func__);
pci_unregister_driver(&e752x_driver);
}
module_init(e752x_init);
module_exit(e752x_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux Networx (http://lnxi.com) Tom Zimmerman\n");
MODULE_DESCRIPTION("MC support for Intel e752x/3100 memory controllers");
module_param(force_function_unhide, int, 0444);
MODULE_PARM_DESC(force_function_unhide, "if BIOS sets Dev0:Fun1 up as hidden:"
" 1=force unhide and hope BIOS doesn't fight driver for "
"Dev0:Fun1 access");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
module_param(sysbus_parity, int, 0444);
MODULE_PARM_DESC(sysbus_parity, "0=disable system bus parity checking,"
" 1=enable system bus parity checking, default=auto-detect");
module_param(report_non_memory_errors, int, 0644);
MODULE_PARM_DESC(report_non_memory_errors, "0=disable non-memory error "
"reporting, 1=enable non-memory error reporting");
| gpl-2.0 |
atilag/flatfish-kernel | drivers/edac/e752x_edac.c | 3025 | 40658 | /*
* Intel e752x Memory Controller kernel module
* (C) 2004 Linux Networx (http://lnxi.com)
* This file may be distributed under the terms of the
* GNU General Public License.
*
* See "enum e752x_chips" below for supported chipsets
*
* Written by Tom Zimmerman
*
* Contributors:
* Thayne Harbaugh at realmsys.com (?)
* Wang Zhenyu at intel.com
* Dave Jiang at mvista.com
*
* $Id: edac_e752x.c,v 1.5.2.11 2005/10/05 00:43:44 dsp_llnl Exp $
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/edac.h>
#include "edac_core.h"
#define E752X_REVISION " Ver: 2.0.2"
#define EDAC_MOD_STR "e752x_edac"
static int report_non_memory_errors;
static int force_function_unhide;
static int sysbus_parity = -1;
static struct edac_pci_ctl_info *e752x_pci;
#define e752x_printk(level, fmt, arg...) \
edac_printk(level, "e752x", fmt, ##arg)
#define e752x_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "e752x", fmt, ##arg)
#ifndef PCI_DEVICE_ID_INTEL_7520_0
#define PCI_DEVICE_ID_INTEL_7520_0 0x3590
#endif /* PCI_DEVICE_ID_INTEL_7520_0 */
#ifndef PCI_DEVICE_ID_INTEL_7520_1_ERR
#define PCI_DEVICE_ID_INTEL_7520_1_ERR 0x3591
#endif /* PCI_DEVICE_ID_INTEL_7520_1_ERR */
#ifndef PCI_DEVICE_ID_INTEL_7525_0
#define PCI_DEVICE_ID_INTEL_7525_0 0x359E
#endif /* PCI_DEVICE_ID_INTEL_7525_0 */
#ifndef PCI_DEVICE_ID_INTEL_7525_1_ERR
#define PCI_DEVICE_ID_INTEL_7525_1_ERR 0x3593
#endif /* PCI_DEVICE_ID_INTEL_7525_1_ERR */
#ifndef PCI_DEVICE_ID_INTEL_7320_0
#define PCI_DEVICE_ID_INTEL_7320_0 0x3592
#endif /* PCI_DEVICE_ID_INTEL_7320_0 */
#ifndef PCI_DEVICE_ID_INTEL_7320_1_ERR
#define PCI_DEVICE_ID_INTEL_7320_1_ERR 0x3593
#endif /* PCI_DEVICE_ID_INTEL_7320_1_ERR */
#ifndef PCI_DEVICE_ID_INTEL_3100_0
#define PCI_DEVICE_ID_INTEL_3100_0 0x35B0
#endif /* PCI_DEVICE_ID_INTEL_3100_0 */
#ifndef PCI_DEVICE_ID_INTEL_3100_1_ERR
#define PCI_DEVICE_ID_INTEL_3100_1_ERR 0x35B1
#endif /* PCI_DEVICE_ID_INTEL_3100_1_ERR */
#define E752X_NR_CSROWS 8 /* number of csrows */
/* E752X register addresses - device 0 function 0 */
#define E752X_MCHSCRB 0x52 /* Memory Scrub register (16b) */
/*
* 6:5 Scrub Completion Count
* 3:2 Scrub Rate (i3100 only)
* 01=fast 10=normal
* 1:0 Scrub Mode enable
* 00=off 10=on
*/
#define E752X_DRB 0x60 /* DRAM row boundary register (8b) */
#define E752X_DRA 0x70 /* DRAM row attribute register (8b) */
/*
* 31:30 Device width row 7
* 01=x8 10=x4 11=x8 DDR2
* 27:26 Device width row 6
* 23:22 Device width row 5
* 19:20 Device width row 4
* 15:14 Device width row 3
* 11:10 Device width row 2
* 7:6 Device width row 1
* 3:2 Device width row 0
*/
#define E752X_DRC 0x7C /* DRAM controller mode reg (32b) */
/* FIXME:IS THIS RIGHT? */
/*
* 22 Number channels 0=1,1=2
* 19:18 DRB Granularity 32/64MB
*/
#define E752X_DRM 0x80 /* Dimm mapping register */
#define E752X_DDRCSR 0x9A /* DDR control and status reg (16b) */
/*
* 14:12 1 single A, 2 single B, 3 dual
*/
#define E752X_TOLM 0xC4 /* DRAM top of low memory reg (16b) */
#define E752X_REMAPBASE 0xC6 /* DRAM remap base address reg (16b) */
#define E752X_REMAPLIMIT 0xC8 /* DRAM remap limit address reg (16b) */
#define E752X_REMAPOFFSET 0xCA /* DRAM remap limit offset reg (16b) */
/* E752X register addresses - device 0 function 1 */
#define E752X_FERR_GLOBAL 0x40 /* Global first error register (32b) */
#define E752X_NERR_GLOBAL 0x44 /* Global next error register (32b) */
#define E752X_HI_FERR 0x50 /* Hub interface first error reg (8b) */
#define E752X_HI_NERR 0x52 /* Hub interface next error reg (8b) */
#define E752X_HI_ERRMASK 0x54 /* Hub interface error mask reg (8b) */
#define E752X_HI_SMICMD 0x5A /* Hub interface SMI command reg (8b) */
#define E752X_SYSBUS_FERR 0x60 /* System buss first error reg (16b) */
#define E752X_SYSBUS_NERR 0x62 /* System buss next error reg (16b) */
#define E752X_SYSBUS_ERRMASK 0x64 /* System buss error mask reg (16b) */
#define E752X_SYSBUS_SMICMD 0x6A /* System buss SMI command reg (16b) */
#define E752X_BUF_FERR 0x70 /* Memory buffer first error reg (8b) */
#define E752X_BUF_NERR 0x72 /* Memory buffer next error reg (8b) */
#define E752X_BUF_ERRMASK 0x74 /* Memory buffer error mask reg (8b) */
#define E752X_BUF_SMICMD 0x7A /* Memory buffer SMI cmd reg (8b) */
#define E752X_DRAM_FERR 0x80 /* DRAM first error register (16b) */
#define E752X_DRAM_NERR 0x82 /* DRAM next error register (16b) */
#define E752X_DRAM_ERRMASK 0x84 /* DRAM error mask register (8b) */
#define E752X_DRAM_SMICMD 0x8A /* DRAM SMI command register (8b) */
#define E752X_DRAM_RETR_ADD 0xAC /* DRAM Retry address register (32b) */
#define E752X_DRAM_SEC1_ADD 0xA0 /* DRAM first correctable memory */
/* error address register (32b) */
/*
* 31 Reserved
* 30:2 CE address (64 byte block 34:6
* 1 Reserved
* 0 HiLoCS
*/
#define E752X_DRAM_SEC2_ADD 0xC8 /* DRAM first correctable memory */
/* error address register (32b) */
/*
* 31 Reserved
* 30:2 CE address (64 byte block 34:6)
* 1 Reserved
* 0 HiLoCS
*/
#define E752X_DRAM_DED_ADD 0xA4 /* DRAM first uncorrectable memory */
/* error address register (32b) */
/*
* 31 Reserved
* 30:2 CE address (64 byte block 34:6)
* 1 Reserved
* 0 HiLoCS
*/
#define E752X_DRAM_SCRB_ADD 0xA8 /* DRAM 1st uncorrectable scrub mem */
/* error address register (32b) */
/*
* 31 Reserved
* 30:2 CE address (64 byte block 34:6
* 1 Reserved
* 0 HiLoCS
*/
#define E752X_DRAM_SEC1_SYNDROME 0xC4 /* DRAM first correctable memory */
/* error syndrome register (16b) */
#define E752X_DRAM_SEC2_SYNDROME 0xC6 /* DRAM second correctable memory */
/* error syndrome register (16b) */
#define E752X_DEVPRES1 0xF4 /* Device Present 1 register (8b) */
/* 3100 IMCH specific register addresses - device 0 function 1 */
#define I3100_NSI_FERR 0x48 /* NSI first error reg (32b) */
#define I3100_NSI_NERR 0x4C /* NSI next error reg (32b) */
#define I3100_NSI_SMICMD 0x54 /* NSI SMI command register (32b) */
#define I3100_NSI_EMASK 0x90 /* NSI error mask register (32b) */
/* ICH5R register addresses - device 30 function 0 */
#define ICH5R_PCI_STAT 0x06 /* PCI status register (16b) */
#define ICH5R_PCI_2ND_STAT 0x1E /* PCI status secondary reg (16b) */
#define ICH5R_PCI_BRIDGE_CTL 0x3E /* PCI bridge control register (16b) */
enum e752x_chips {
E7520 = 0,
E7525 = 1,
E7320 = 2,
I3100 = 3
};
struct e752x_pvt {
struct pci_dev *bridge_ck;
struct pci_dev *dev_d0f0;
struct pci_dev *dev_d0f1;
u32 tolm;
u32 remapbase;
u32 remaplimit;
int mc_symmetric;
u8 map[8];
int map_type;
const struct e752x_dev_info *dev_info;
};
struct e752x_dev_info {
u16 err_dev;
u16 ctl_dev;
const char *ctl_name;
};
struct e752x_error_info {
u32 ferr_global;
u32 nerr_global;
u32 nsi_ferr; /* 3100 only */
u32 nsi_nerr; /* 3100 only */
u8 hi_ferr; /* all but 3100 */
u8 hi_nerr; /* all but 3100 */
u16 sysbus_ferr;
u16 sysbus_nerr;
u8 buf_ferr;
u8 buf_nerr;
u16 dram_ferr;
u16 dram_nerr;
u32 dram_sec1_add;
u32 dram_sec2_add;
u16 dram_sec1_syndrome;
u16 dram_sec2_syndrome;
u32 dram_ded_add;
u32 dram_scrb_add;
u32 dram_retr_add;
};
static const struct e752x_dev_info e752x_devs[] = {
[E7520] = {
.err_dev = PCI_DEVICE_ID_INTEL_7520_1_ERR,
.ctl_dev = PCI_DEVICE_ID_INTEL_7520_0,
.ctl_name = "E7520"},
[E7525] = {
.err_dev = PCI_DEVICE_ID_INTEL_7525_1_ERR,
.ctl_dev = PCI_DEVICE_ID_INTEL_7525_0,
.ctl_name = "E7525"},
[E7320] = {
.err_dev = PCI_DEVICE_ID_INTEL_7320_1_ERR,
.ctl_dev = PCI_DEVICE_ID_INTEL_7320_0,
.ctl_name = "E7320"},
[I3100] = {
.err_dev = PCI_DEVICE_ID_INTEL_3100_1_ERR,
.ctl_dev = PCI_DEVICE_ID_INTEL_3100_0,
.ctl_name = "3100"},
};
/* Valid scrub rates for the e752x/3100 hardware memory scrubber. We
* map the scrubbing bandwidth to a hardware register value. The 'set'
* operation finds the 'matching or higher value'. Note that scrubbing
* on the e752x can only be enabled/disabled. The 3100 supports
* a normal and fast mode.
*/
#define SDRATE_EOT 0xFFFFFFFF
struct scrubrate {
u32 bandwidth; /* bandwidth consumed by scrubbing in bytes/sec */
u16 scrubval; /* register value for scrub rate */
};
/* Rate below assumes same performance as i3100 using PC3200 DDR2 in
* normal mode. e752x bridges don't support choosing normal or fast mode,
* so the scrubbing bandwidth value isn't all that important - scrubbing is
* either on or off.
*/
static const struct scrubrate scrubrates_e752x[] = {
{0, 0x00}, /* Scrubbing Off */
{500000, 0x02}, /* Scrubbing On */
{SDRATE_EOT, 0x00} /* End of Table */
};
/* Fast mode: 2 GByte PC3200 DDR2 scrubbed in 33s = 63161283 bytes/s
* Normal mode: 125 (32000 / 256) times slower than fast mode.
*/
static const struct scrubrate scrubrates_i3100[] = {
{0, 0x00}, /* Scrubbing Off */
{500000, 0x0a}, /* Normal mode - 32k clocks */
{62500000, 0x06}, /* Fast mode - 256 clocks */
{SDRATE_EOT, 0x00} /* End of Table */
};
static unsigned long ctl_page_to_phys(struct mem_ctl_info *mci,
unsigned long page)
{
u32 remap;
struct e752x_pvt *pvt = (struct e752x_pvt *)mci->pvt_info;
debugf3("%s()\n", __func__);
if (page < pvt->tolm)
return page;
if ((page >= 0x100000) && (page < pvt->remapbase))
return page;
remap = (page - pvt->tolm) + pvt->remapbase;
if (remap < pvt->remaplimit)
return remap;
e752x_printk(KERN_ERR, "Invalid page %lx - out of range\n", page);
return pvt->tolm - 1;
}
static void do_process_ce(struct mem_ctl_info *mci, u16 error_one,
u32 sec1_add, u16 sec1_syndrome)
{
u32 page;
int row;
int channel;
int i;
struct e752x_pvt *pvt = (struct e752x_pvt *)mci->pvt_info;
debugf3("%s()\n", __func__);
/* convert the addr to 4k page */
page = sec1_add >> (PAGE_SHIFT - 4);
/* FIXME - check for -1 */
if (pvt->mc_symmetric) {
/* chip select are bits 14 & 13 */
row = ((page >> 1) & 3);
e752x_printk(KERN_WARNING,
"Test row %d Table %d %d %d %d %d %d %d %d\n", row,
pvt->map[0], pvt->map[1], pvt->map[2], pvt->map[3],
pvt->map[4], pvt->map[5], pvt->map[6],
pvt->map[7]);
/* test for channel remapping */
for (i = 0; i < 8; i++) {
if (pvt->map[i] == row)
break;
}
e752x_printk(KERN_WARNING, "Test computed row %d\n", i);
if (i < 8)
row = i;
else
e752x_mc_printk(mci, KERN_WARNING,
"row %d not found in remap table\n",
row);
} else
row = edac_mc_find_csrow_by_page(mci, page);
/* 0 = channel A, 1 = channel B */
channel = !(error_one & 1);
/* e752x mc reads 34:6 of the DRAM linear address */
edac_mc_handle_ce(mci, page, offset_in_page(sec1_add << 4),
sec1_syndrome, row, channel, "e752x CE");
}
static inline void process_ce(struct mem_ctl_info *mci, u16 error_one,
u32 sec1_add, u16 sec1_syndrome, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_process_ce(mci, error_one, sec1_add, sec1_syndrome);
}
static void do_process_ue(struct mem_ctl_info *mci, u16 error_one,
u32 ded_add, u32 scrb_add)
{
u32 error_2b, block_page;
int row;
struct e752x_pvt *pvt = (struct e752x_pvt *)mci->pvt_info;
debugf3("%s()\n", __func__);
if (error_one & 0x0202) {
error_2b = ded_add;
/* convert to 4k address */
block_page = error_2b >> (PAGE_SHIFT - 4);
row = pvt->mc_symmetric ?
/* chip select are bits 14 & 13 */
((block_page >> 1) & 3) :
edac_mc_find_csrow_by_page(mci, block_page);
/* e752x mc reads 34:6 of the DRAM linear address */
edac_mc_handle_ue(mci, block_page,
offset_in_page(error_2b << 4),
row, "e752x UE from Read");
}
if (error_one & 0x0404) {
error_2b = scrb_add;
/* convert to 4k address */
block_page = error_2b >> (PAGE_SHIFT - 4);
row = pvt->mc_symmetric ?
/* chip select are bits 14 & 13 */
((block_page >> 1) & 3) :
edac_mc_find_csrow_by_page(mci, block_page);
/* e752x mc reads 34:6 of the DRAM linear address */
edac_mc_handle_ue(mci, block_page,
offset_in_page(error_2b << 4),
row, "e752x UE from Scruber");
}
}
static inline void process_ue(struct mem_ctl_info *mci, u16 error_one,
u32 ded_add, u32 scrb_add, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_process_ue(mci, error_one, ded_add, scrb_add);
}
static inline void process_ue_no_info_wr(struct mem_ctl_info *mci,
int *error_found, int handle_error)
{
*error_found = 1;
if (!handle_error)
return;
debugf3("%s()\n", __func__);
edac_mc_handle_ue_no_info(mci, "e752x UE log memory write");
}
static void do_process_ded_retry(struct mem_ctl_info *mci, u16 error,
u32 retry_add)
{
u32 error_1b, page;
int row;
struct e752x_pvt *pvt = (struct e752x_pvt *)mci->pvt_info;
error_1b = retry_add;
page = error_1b >> (PAGE_SHIFT - 4); /* convert the addr to 4k page */
/* chip select are bits 14 & 13 */
row = pvt->mc_symmetric ? ((page >> 1) & 3) :
edac_mc_find_csrow_by_page(mci, page);
e752x_mc_printk(mci, KERN_WARNING,
"CE page 0x%lx, row %d : Memory read retry\n",
(long unsigned int)page, row);
}
static inline void process_ded_retry(struct mem_ctl_info *mci, u16 error,
u32 retry_add, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_process_ded_retry(mci, error, retry_add);
}
static inline void process_threshold_ce(struct mem_ctl_info *mci, u16 error,
int *error_found, int handle_error)
{
*error_found = 1;
if (handle_error)
e752x_mc_printk(mci, KERN_WARNING, "Memory threshold CE\n");
}
static char *global_message[11] = {
"PCI Express C1",
"PCI Express C",
"PCI Express B1",
"PCI Express B",
"PCI Express A1",
"PCI Express A",
"DMA Controller",
"HUB or NS Interface",
"System Bus",
"DRAM Controller", /* 9th entry */
"Internal Buffer"
};
#define DRAM_ENTRY 9
static char *fatal_message[2] = { "Non-Fatal ", "Fatal " };
static void do_global_error(int fatal, u32 errors)
{
int i;
for (i = 0; i < 11; i++) {
if (errors & (1 << i)) {
/* If the error is from DRAM Controller OR
* we are to report ALL errors, then
* report the error
*/
if ((i == DRAM_ENTRY) || report_non_memory_errors)
e752x_printk(KERN_WARNING, "%sError %s\n",
fatal_message[fatal],
global_message[i]);
}
}
}
static inline void global_error(int fatal, u32 errors, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_global_error(fatal, errors);
}
static char *hub_message[7] = {
"HI Address or Command Parity", "HI Illegal Access",
"HI Internal Parity", "Out of Range Access",
"HI Data Parity", "Enhanced Config Access",
"Hub Interface Target Abort"
};
static void do_hub_error(int fatal, u8 errors)
{
int i;
for (i = 0; i < 7; i++) {
if (errors & (1 << i))
e752x_printk(KERN_WARNING, "%sError %s\n",
fatal_message[fatal], hub_message[i]);
}
}
static inline void hub_error(int fatal, u8 errors, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_hub_error(fatal, errors);
}
#define NSI_FATAL_MASK 0x0c080081
#define NSI_NON_FATAL_MASK 0x23a0ba64
#define NSI_ERR_MASK (NSI_FATAL_MASK | NSI_NON_FATAL_MASK)
static char *nsi_message[30] = {
"NSI Link Down", /* NSI_FERR/NSI_NERR bit 0, fatal error */
"", /* reserved */
"NSI Parity Error", /* bit 2, non-fatal */
"", /* reserved */
"", /* reserved */
"Correctable Error Message", /* bit 5, non-fatal */
"Non-Fatal Error Message", /* bit 6, non-fatal */
"Fatal Error Message", /* bit 7, fatal */
"", /* reserved */
"Receiver Error", /* bit 9, non-fatal */
"", /* reserved */
"Bad TLP", /* bit 11, non-fatal */
"Bad DLLP", /* bit 12, non-fatal */
"REPLAY_NUM Rollover", /* bit 13, non-fatal */
"", /* reserved */
"Replay Timer Timeout", /* bit 15, non-fatal */
"", /* reserved */
"", /* reserved */
"", /* reserved */
"Data Link Protocol Error", /* bit 19, fatal */
"", /* reserved */
"Poisoned TLP", /* bit 21, non-fatal */
"", /* reserved */
"Completion Timeout", /* bit 23, non-fatal */
"Completer Abort", /* bit 24, non-fatal */
"Unexpected Completion", /* bit 25, non-fatal */
"Receiver Overflow", /* bit 26, fatal */
"Malformed TLP", /* bit 27, fatal */
"", /* reserved */
"Unsupported Request" /* bit 29, non-fatal */
};
static void do_nsi_error(int fatal, u32 errors)
{
int i;
for (i = 0; i < 30; i++) {
if (errors & (1 << i))
printk(KERN_WARNING "%sError %s\n",
fatal_message[fatal], nsi_message[i]);
}
}
static inline void nsi_error(int fatal, u32 errors, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_nsi_error(fatal, errors);
}
static char *membuf_message[4] = {
"Internal PMWB to DRAM parity",
"Internal PMWB to System Bus Parity",
"Internal System Bus or IO to PMWB Parity",
"Internal DRAM to PMWB Parity"
};
static void do_membuf_error(u8 errors)
{
int i;
for (i = 0; i < 4; i++) {
if (errors & (1 << i))
e752x_printk(KERN_WARNING, "Non-Fatal Error %s\n",
membuf_message[i]);
}
}
static inline void membuf_error(u8 errors, int *error_found, int handle_error)
{
*error_found = 1;
if (handle_error)
do_membuf_error(errors);
}
static char *sysbus_message[10] = {
"Addr or Request Parity",
"Data Strobe Glitch",
"Addr Strobe Glitch",
"Data Parity",
"Addr Above TOM",
"Non DRAM Lock Error",
"MCERR", "BINIT",
"Memory Parity",
"IO Subsystem Parity"
};
static void do_sysbus_error(int fatal, u32 errors)
{
int i;
for (i = 0; i < 10; i++) {
if (errors & (1 << i))
e752x_printk(KERN_WARNING, "%sError System Bus %s\n",
fatal_message[fatal], sysbus_message[i]);
}
}
static inline void sysbus_error(int fatal, u32 errors, int *error_found,
int handle_error)
{
*error_found = 1;
if (handle_error)
do_sysbus_error(fatal, errors);
}
static void e752x_check_hub_interface(struct e752x_error_info *info,
int *error_found, int handle_error)
{
u8 stat8;
//pci_read_config_byte(dev,E752X_HI_FERR,&stat8);
stat8 = info->hi_ferr;
if (stat8 & 0x7f) { /* Error, so process */
stat8 &= 0x7f;
if (stat8 & 0x2b)
hub_error(1, stat8 & 0x2b, error_found, handle_error);
if (stat8 & 0x54)
hub_error(0, stat8 & 0x54, error_found, handle_error);
}
//pci_read_config_byte(dev,E752X_HI_NERR,&stat8);
stat8 = info->hi_nerr;
if (stat8 & 0x7f) { /* Error, so process */
stat8 &= 0x7f;
if (stat8 & 0x2b)
hub_error(1, stat8 & 0x2b, error_found, handle_error);
if (stat8 & 0x54)
hub_error(0, stat8 & 0x54, error_found, handle_error);
}
}
static void e752x_check_ns_interface(struct e752x_error_info *info,
int *error_found, int handle_error)
{
u32 stat32;
stat32 = info->nsi_ferr;
if (stat32 & NSI_ERR_MASK) { /* Error, so process */
if (stat32 & NSI_FATAL_MASK) /* check for fatal errors */
nsi_error(1, stat32 & NSI_FATAL_MASK, error_found,
handle_error);
if (stat32 & NSI_NON_FATAL_MASK) /* check for non-fatal ones */
nsi_error(0, stat32 & NSI_NON_FATAL_MASK, error_found,
handle_error);
}
stat32 = info->nsi_nerr;
if (stat32 & NSI_ERR_MASK) {
if (stat32 & NSI_FATAL_MASK)
nsi_error(1, stat32 & NSI_FATAL_MASK, error_found,
handle_error);
if (stat32 & NSI_NON_FATAL_MASK)
nsi_error(0, stat32 & NSI_NON_FATAL_MASK, error_found,
handle_error);
}
}
static void e752x_check_sysbus(struct e752x_error_info *info,
int *error_found, int handle_error)
{
u32 stat32, error32;
//pci_read_config_dword(dev,E752X_SYSBUS_FERR,&stat32);
stat32 = info->sysbus_ferr + (info->sysbus_nerr << 16);
if (stat32 == 0)
return; /* no errors */
error32 = (stat32 >> 16) & 0x3ff;
stat32 = stat32 & 0x3ff;
if (stat32 & 0x087)
sysbus_error(1, stat32 & 0x087, error_found, handle_error);
if (stat32 & 0x378)
sysbus_error(0, stat32 & 0x378, error_found, handle_error);
if (error32 & 0x087)
sysbus_error(1, error32 & 0x087, error_found, handle_error);
if (error32 & 0x378)
sysbus_error(0, error32 & 0x378, error_found, handle_error);
}
static void e752x_check_membuf(struct e752x_error_info *info,
int *error_found, int handle_error)
{
u8 stat8;
stat8 = info->buf_ferr;
if (stat8 & 0x0f) { /* Error, so process */
stat8 &= 0x0f;
membuf_error(stat8, error_found, handle_error);
}
stat8 = info->buf_nerr;
if (stat8 & 0x0f) { /* Error, so process */
stat8 &= 0x0f;
membuf_error(stat8, error_found, handle_error);
}
}
static void e752x_check_dram(struct mem_ctl_info *mci,
struct e752x_error_info *info, int *error_found,
int handle_error)
{
u16 error_one, error_next;
error_one = info->dram_ferr;
error_next = info->dram_nerr;
/* decode and report errors */
if (error_one & 0x0101) /* check first error correctable */
process_ce(mci, error_one, info->dram_sec1_add,
info->dram_sec1_syndrome, error_found, handle_error);
if (error_next & 0x0101) /* check next error correctable */
process_ce(mci, error_next, info->dram_sec2_add,
info->dram_sec2_syndrome, error_found, handle_error);
if (error_one & 0x4040)
process_ue_no_info_wr(mci, error_found, handle_error);
if (error_next & 0x4040)
process_ue_no_info_wr(mci, error_found, handle_error);
if (error_one & 0x2020)
process_ded_retry(mci, error_one, info->dram_retr_add,
error_found, handle_error);
if (error_next & 0x2020)
process_ded_retry(mci, error_next, info->dram_retr_add,
error_found, handle_error);
if (error_one & 0x0808)
process_threshold_ce(mci, error_one, error_found, handle_error);
if (error_next & 0x0808)
process_threshold_ce(mci, error_next, error_found,
handle_error);
if (error_one & 0x0606)
process_ue(mci, error_one, info->dram_ded_add,
info->dram_scrb_add, error_found, handle_error);
if (error_next & 0x0606)
process_ue(mci, error_next, info->dram_ded_add,
info->dram_scrb_add, error_found, handle_error);
}
static void e752x_get_error_info(struct mem_ctl_info *mci,
struct e752x_error_info *info)
{
struct pci_dev *dev;
struct e752x_pvt *pvt;
memset(info, 0, sizeof(*info));
pvt = (struct e752x_pvt *)mci->pvt_info;
dev = pvt->dev_d0f1;
pci_read_config_dword(dev, E752X_FERR_GLOBAL, &info->ferr_global);
if (info->ferr_global) {
if (pvt->dev_info->err_dev == PCI_DEVICE_ID_INTEL_3100_1_ERR) {
pci_read_config_dword(dev, I3100_NSI_FERR,
&info->nsi_ferr);
info->hi_ferr = 0;
} else {
pci_read_config_byte(dev, E752X_HI_FERR,
&info->hi_ferr);
info->nsi_ferr = 0;
}
pci_read_config_word(dev, E752X_SYSBUS_FERR,
&info->sysbus_ferr);
pci_read_config_byte(dev, E752X_BUF_FERR, &info->buf_ferr);
pci_read_config_word(dev, E752X_DRAM_FERR, &info->dram_ferr);
pci_read_config_dword(dev, E752X_DRAM_SEC1_ADD,
&info->dram_sec1_add);
pci_read_config_word(dev, E752X_DRAM_SEC1_SYNDROME,
&info->dram_sec1_syndrome);
pci_read_config_dword(dev, E752X_DRAM_DED_ADD,
&info->dram_ded_add);
pci_read_config_dword(dev, E752X_DRAM_SCRB_ADD,
&info->dram_scrb_add);
pci_read_config_dword(dev, E752X_DRAM_RETR_ADD,
&info->dram_retr_add);
/* ignore the reserved bits just in case */
if (info->hi_ferr & 0x7f)
pci_write_config_byte(dev, E752X_HI_FERR,
info->hi_ferr);
if (info->nsi_ferr & NSI_ERR_MASK)
pci_write_config_dword(dev, I3100_NSI_FERR,
info->nsi_ferr);
if (info->sysbus_ferr)
pci_write_config_word(dev, E752X_SYSBUS_FERR,
info->sysbus_ferr);
if (info->buf_ferr & 0x0f)
pci_write_config_byte(dev, E752X_BUF_FERR,
info->buf_ferr);
if (info->dram_ferr)
pci_write_bits16(pvt->bridge_ck, E752X_DRAM_FERR,
info->dram_ferr, info->dram_ferr);
pci_write_config_dword(dev, E752X_FERR_GLOBAL,
info->ferr_global);
}
pci_read_config_dword(dev, E752X_NERR_GLOBAL, &info->nerr_global);
if (info->nerr_global) {
if (pvt->dev_info->err_dev == PCI_DEVICE_ID_INTEL_3100_1_ERR) {
pci_read_config_dword(dev, I3100_NSI_NERR,
&info->nsi_nerr);
info->hi_nerr = 0;
} else {
pci_read_config_byte(dev, E752X_HI_NERR,
&info->hi_nerr);
info->nsi_nerr = 0;
}
pci_read_config_word(dev, E752X_SYSBUS_NERR,
&info->sysbus_nerr);
pci_read_config_byte(dev, E752X_BUF_NERR, &info->buf_nerr);
pci_read_config_word(dev, E752X_DRAM_NERR, &info->dram_nerr);
pci_read_config_dword(dev, E752X_DRAM_SEC2_ADD,
&info->dram_sec2_add);
pci_read_config_word(dev, E752X_DRAM_SEC2_SYNDROME,
&info->dram_sec2_syndrome);
if (info->hi_nerr & 0x7f)
pci_write_config_byte(dev, E752X_HI_NERR,
info->hi_nerr);
if (info->nsi_nerr & NSI_ERR_MASK)
pci_write_config_dword(dev, I3100_NSI_NERR,
info->nsi_nerr);
if (info->sysbus_nerr)
pci_write_config_word(dev, E752X_SYSBUS_NERR,
info->sysbus_nerr);
if (info->buf_nerr & 0x0f)
pci_write_config_byte(dev, E752X_BUF_NERR,
info->buf_nerr);
if (info->dram_nerr)
pci_write_bits16(pvt->bridge_ck, E752X_DRAM_NERR,
info->dram_nerr, info->dram_nerr);
pci_write_config_dword(dev, E752X_NERR_GLOBAL,
info->nerr_global);
}
}
static int e752x_process_error_info(struct mem_ctl_info *mci,
struct e752x_error_info *info,
int handle_errors)
{
u32 error32, stat32;
int error_found;
error_found = 0;
error32 = (info->ferr_global >> 18) & 0x3ff;
stat32 = (info->ferr_global >> 4) & 0x7ff;
if (error32)
global_error(1, error32, &error_found, handle_errors);
if (stat32)
global_error(0, stat32, &error_found, handle_errors);
error32 = (info->nerr_global >> 18) & 0x3ff;
stat32 = (info->nerr_global >> 4) & 0x7ff;
if (error32)
global_error(1, error32, &error_found, handle_errors);
if (stat32)
global_error(0, stat32, &error_found, handle_errors);
e752x_check_hub_interface(info, &error_found, handle_errors);
e752x_check_ns_interface(info, &error_found, handle_errors);
e752x_check_sysbus(info, &error_found, handle_errors);
e752x_check_membuf(info, &error_found, handle_errors);
e752x_check_dram(mci, info, &error_found, handle_errors);
return error_found;
}
static void e752x_check(struct mem_ctl_info *mci)
{
struct e752x_error_info info;
debugf3("%s()\n", __func__);
e752x_get_error_info(mci, &info);
e752x_process_error_info(mci, &info, 1);
}
/* Program byte/sec bandwidth scrub rate to hardware */
static int set_sdram_scrub_rate(struct mem_ctl_info *mci, u32 new_bw)
{
const struct scrubrate *scrubrates;
struct e752x_pvt *pvt = (struct e752x_pvt *) mci->pvt_info;
struct pci_dev *pdev = pvt->dev_d0f0;
int i;
if (pvt->dev_info->ctl_dev == PCI_DEVICE_ID_INTEL_3100_0)
scrubrates = scrubrates_i3100;
else
scrubrates = scrubrates_e752x;
/* Translate the desired scrub rate to a e752x/3100 register value.
* Search for the bandwidth that is equal or greater than the
* desired rate and program the cooresponding register value.
*/
for (i = 0; scrubrates[i].bandwidth != SDRATE_EOT; i++)
if (scrubrates[i].bandwidth >= new_bw)
break;
if (scrubrates[i].bandwidth == SDRATE_EOT)
return -1;
pci_write_config_word(pdev, E752X_MCHSCRB, scrubrates[i].scrubval);
return scrubrates[i].bandwidth;
}
/* Convert current scrub rate value into byte/sec bandwidth */
static int get_sdram_scrub_rate(struct mem_ctl_info *mci)
{
const struct scrubrate *scrubrates;
struct e752x_pvt *pvt = (struct e752x_pvt *) mci->pvt_info;
struct pci_dev *pdev = pvt->dev_d0f0;
u16 scrubval;
int i;
if (pvt->dev_info->ctl_dev == PCI_DEVICE_ID_INTEL_3100_0)
scrubrates = scrubrates_i3100;
else
scrubrates = scrubrates_e752x;
/* Find the bandwidth matching the memory scrubber configuration */
pci_read_config_word(pdev, E752X_MCHSCRB, &scrubval);
scrubval = scrubval & 0x0f;
for (i = 0; scrubrates[i].bandwidth != SDRATE_EOT; i++)
if (scrubrates[i].scrubval == scrubval)
break;
if (scrubrates[i].bandwidth == SDRATE_EOT) {
e752x_printk(KERN_WARNING,
"Invalid sdram scrub control value: 0x%x\n", scrubval);
return -1;
}
return scrubrates[i].bandwidth;
}
/* Return 1 if dual channel mode is active. Else return 0. */
static inline int dual_channel_active(u16 ddrcsr)
{
return (((ddrcsr >> 12) & 3) == 3);
}
/* Remap csrow index numbers if map_type is "reverse"
*/
static inline int remap_csrow_index(struct mem_ctl_info *mci, int index)
{
struct e752x_pvt *pvt = mci->pvt_info;
if (!pvt->map_type)
return (7 - index);
return (index);
}
static void e752x_init_csrows(struct mem_ctl_info *mci, struct pci_dev *pdev,
u16 ddrcsr)
{
struct csrow_info *csrow;
unsigned long last_cumul_size;
int index, mem_dev, drc_chan;
int drc_drbg; /* DRB granularity 0=64mb, 1=128mb */
int drc_ddim; /* DRAM Data Integrity Mode 0=none, 2=edac */
u8 value;
u32 dra, drc, cumul_size;
dra = 0;
for (index = 0; index < 4; index++) {
u8 dra_reg;
pci_read_config_byte(pdev, E752X_DRA + index, &dra_reg);
dra |= dra_reg << (index * 8);
}
pci_read_config_dword(pdev, E752X_DRC, &drc);
drc_chan = dual_channel_active(ddrcsr);
drc_drbg = drc_chan + 1; /* 128 in dual mode, 64 in single */
drc_ddim = (drc >> 20) & 0x3;
/* The dram row boundary (DRB) reg values are boundary address for
* each DRAM row with a granularity of 64 or 128MB (single/dual
* channel operation). DRB regs are cumulative; therefore DRB7 will
* contain the total memory contained in all eight rows.
*/
for (last_cumul_size = index = 0; index < mci->nr_csrows; index++) {
/* mem_dev 0=x8, 1=x4 */
mem_dev = (dra >> (index * 4 + 2)) & 0x3;
csrow = &mci->csrows[remap_csrow_index(mci, index)];
mem_dev = (mem_dev == 2);
pci_read_config_byte(pdev, E752X_DRB + index, &value);
/* convert a 128 or 64 MiB DRB to a page size. */
cumul_size = value << (25 + drc_drbg - PAGE_SHIFT);
debugf3("%s(): (%d) cumul_size 0x%x\n", __func__, index,
cumul_size);
if (cumul_size == last_cumul_size)
continue; /* not populated */
csrow->first_page = last_cumul_size;
csrow->last_page = cumul_size - 1;
csrow->nr_pages = cumul_size - last_cumul_size;
last_cumul_size = cumul_size;
csrow->grain = 1 << 12; /* 4KiB - resolution of CELOG */
csrow->mtype = MEM_RDDR; /* only one type supported */
csrow->dtype = mem_dev ? DEV_X4 : DEV_X8;
/*
* if single channel or x8 devices then SECDED
* if dual channel and x4 then S4ECD4ED
*/
if (drc_ddim) {
if (drc_chan && mem_dev) {
csrow->edac_mode = EDAC_S4ECD4ED;
mci->edac_cap |= EDAC_FLAG_S4ECD4ED;
} else {
csrow->edac_mode = EDAC_SECDED;
mci->edac_cap |= EDAC_FLAG_SECDED;
}
} else
csrow->edac_mode = EDAC_NONE;
}
}
static void e752x_init_mem_map_table(struct pci_dev *pdev,
struct e752x_pvt *pvt)
{
int index;
u8 value, last, row;
last = 0;
row = 0;
for (index = 0; index < 8; index += 2) {
pci_read_config_byte(pdev, E752X_DRB + index, &value);
/* test if there is a dimm in this slot */
if (value == last) {
/* no dimm in the slot, so flag it as empty */
pvt->map[index] = 0xff;
pvt->map[index + 1] = 0xff;
} else { /* there is a dimm in the slot */
pvt->map[index] = row;
row++;
last = value;
/* test the next value to see if the dimm is double
* sided
*/
pci_read_config_byte(pdev, E752X_DRB + index + 1,
&value);
/* the dimm is single sided, so flag as empty */
/* this is a double sided dimm to save the next row #*/
pvt->map[index + 1] = (value == last) ? 0xff : row;
row++;
last = value;
}
}
}
/* Return 0 on success or 1 on failure. */
static int e752x_get_devs(struct pci_dev *pdev, int dev_idx,
struct e752x_pvt *pvt)
{
struct pci_dev *dev;
pvt->bridge_ck = pci_get_device(PCI_VENDOR_ID_INTEL,
pvt->dev_info->err_dev, pvt->bridge_ck);
if (pvt->bridge_ck == NULL)
pvt->bridge_ck = pci_scan_single_device(pdev->bus,
PCI_DEVFN(0, 1));
if (pvt->bridge_ck == NULL) {
e752x_printk(KERN_ERR, "error reporting device not found:"
"vendor %x device 0x%x (broken BIOS?)\n",
PCI_VENDOR_ID_INTEL, e752x_devs[dev_idx].err_dev);
return 1;
}
dev = pci_get_device(PCI_VENDOR_ID_INTEL,
e752x_devs[dev_idx].ctl_dev,
NULL);
if (dev == NULL)
goto fail;
pvt->dev_d0f0 = dev;
pvt->dev_d0f1 = pci_dev_get(pvt->bridge_ck);
return 0;
fail:
pci_dev_put(pvt->bridge_ck);
return 1;
}
/* Setup system bus parity mask register.
* Sysbus parity supported on:
* e7320/e7520/e7525 + Xeon
*/
static void e752x_init_sysbus_parity_mask(struct e752x_pvt *pvt)
{
char *cpu_id = cpu_data(0).x86_model_id;
struct pci_dev *dev = pvt->dev_d0f1;
int enable = 1;
/* Allow module parameter override, else see if CPU supports parity */
if (sysbus_parity != -1) {
enable = sysbus_parity;
} else if (cpu_id[0] && !strstr(cpu_id, "Xeon")) {
e752x_printk(KERN_INFO, "System Bus Parity not "
"supported by CPU, disabling\n");
enable = 0;
}
if (enable)
pci_write_config_word(dev, E752X_SYSBUS_ERRMASK, 0x0000);
else
pci_write_config_word(dev, E752X_SYSBUS_ERRMASK, 0x0309);
}
static void e752x_init_error_reporting_regs(struct e752x_pvt *pvt)
{
struct pci_dev *dev;
dev = pvt->dev_d0f1;
/* Turn off error disable & SMI in case the BIOS turned it on */
if (pvt->dev_info->err_dev == PCI_DEVICE_ID_INTEL_3100_1_ERR) {
pci_write_config_dword(dev, I3100_NSI_EMASK, 0);
pci_write_config_dword(dev, I3100_NSI_SMICMD, 0);
} else {
pci_write_config_byte(dev, E752X_HI_ERRMASK, 0x00);
pci_write_config_byte(dev, E752X_HI_SMICMD, 0x00);
}
e752x_init_sysbus_parity_mask(pvt);
pci_write_config_word(dev, E752X_SYSBUS_SMICMD, 0x00);
pci_write_config_byte(dev, E752X_BUF_ERRMASK, 0x00);
pci_write_config_byte(dev, E752X_BUF_SMICMD, 0x00);
pci_write_config_byte(dev, E752X_DRAM_ERRMASK, 0x00);
pci_write_config_byte(dev, E752X_DRAM_SMICMD, 0x00);
}
static int e752x_probe1(struct pci_dev *pdev, int dev_idx)
{
u16 pci_data;
u8 stat8;
struct mem_ctl_info *mci;
struct e752x_pvt *pvt;
u16 ddrcsr;
int drc_chan; /* Number of channels 0=1chan,1=2chan */
struct e752x_error_info discard;
debugf0("%s(): mci\n", __func__);
debugf0("Starting Probe1\n");
/* check to see if device 0 function 1 is enabled; if it isn't, we
* assume the BIOS has reserved it for a reason and is expecting
* exclusive access, we take care not to violate that assumption and
* fail the probe. */
pci_read_config_byte(pdev, E752X_DEVPRES1, &stat8);
if (!force_function_unhide && !(stat8 & (1 << 5))) {
printk(KERN_INFO "Contact your BIOS vendor to see if the "
"E752x error registers can be safely un-hidden\n");
return -ENODEV;
}
stat8 |= (1 << 5);
pci_write_config_byte(pdev, E752X_DEVPRES1, stat8);
pci_read_config_word(pdev, E752X_DDRCSR, &ddrcsr);
/* FIXME: should check >>12 or 0xf, true for all? */
/* Dual channel = 1, Single channel = 0 */
drc_chan = dual_channel_active(ddrcsr);
mci = edac_mc_alloc(sizeof(*pvt), E752X_NR_CSROWS, drc_chan + 1, 0);
if (mci == NULL) {
return -ENOMEM;
}
debugf3("%s(): init mci\n", __func__);
mci->mtype_cap = MEM_FLAG_RDDR;
/* 3100 IMCH supports SECDEC only */
mci->edac_ctl_cap = (dev_idx == I3100) ? EDAC_FLAG_SECDED :
(EDAC_FLAG_NONE | EDAC_FLAG_SECDED | EDAC_FLAG_S4ECD4ED);
/* FIXME - what if different memory types are in different csrows? */
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = E752X_REVISION;
mci->dev = &pdev->dev;
debugf3("%s(): init pvt\n", __func__);
pvt = (struct e752x_pvt *)mci->pvt_info;
pvt->dev_info = &e752x_devs[dev_idx];
pvt->mc_symmetric = ((ddrcsr & 0x10) != 0);
if (e752x_get_devs(pdev, dev_idx, pvt)) {
edac_mc_free(mci);
return -ENODEV;
}
debugf3("%s(): more mci init\n", __func__);
mci->ctl_name = pvt->dev_info->ctl_name;
mci->dev_name = pci_name(pdev);
mci->edac_check = e752x_check;
mci->ctl_page_to_phys = ctl_page_to_phys;
mci->set_sdram_scrub_rate = set_sdram_scrub_rate;
mci->get_sdram_scrub_rate = get_sdram_scrub_rate;
/* set the map type. 1 = normal, 0 = reversed
* Must be set before e752x_init_csrows in case csrow mapping
* is reversed.
*/
pci_read_config_byte(pdev, E752X_DRM, &stat8);
pvt->map_type = ((stat8 & 0x0f) > ((stat8 >> 4) & 0x0f));
e752x_init_csrows(mci, pdev, ddrcsr);
e752x_init_mem_map_table(pdev, pvt);
if (dev_idx == I3100)
mci->edac_cap = EDAC_FLAG_SECDED; /* the only mode supported */
else
mci->edac_cap |= EDAC_FLAG_NONE;
debugf3("%s(): tolm, remapbase, remaplimit\n", __func__);
/* load the top of low memory, remap base, and remap limit vars */
pci_read_config_word(pdev, E752X_TOLM, &pci_data);
pvt->tolm = ((u32) pci_data) << 4;
pci_read_config_word(pdev, E752X_REMAPBASE, &pci_data);
pvt->remapbase = ((u32) pci_data) << 14;
pci_read_config_word(pdev, E752X_REMAPLIMIT, &pci_data);
pvt->remaplimit = ((u32) pci_data) << 14;
e752x_printk(KERN_INFO,
"tolm = %x, remapbase = %x, remaplimit = %x\n",
pvt->tolm, pvt->remapbase, pvt->remaplimit);
/* Here we assume that we will never see multiple instances of this
* type of memory controller. The ID is therefore hardcoded to 0.
*/
if (edac_mc_add_mc(mci)) {
debugf3("%s(): failed edac_mc_add_mc()\n", __func__);
goto fail;
}
e752x_init_error_reporting_regs(pvt);
e752x_get_error_info(mci, &discard); /* clear other MCH errors */
/* allocating generic PCI control info */
e752x_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!e752x_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n", __func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
/* get this far and it's successful */
debugf3("%s(): success\n", __func__);
return 0;
fail:
pci_dev_put(pvt->dev_d0f0);
pci_dev_put(pvt->dev_d0f1);
pci_dev_put(pvt->bridge_ck);
edac_mc_free(mci);
return -ENODEV;
}
/* returns count (>= 0), or negative on error */
static int __devinit e752x_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
debugf0("%s()\n", __func__);
/* wake up and enable device */
if (pci_enable_device(pdev) < 0)
return -EIO;
return e752x_probe1(pdev, ent->driver_data);
}
static void __devexit e752x_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
struct e752x_pvt *pvt;
debugf0("%s()\n", __func__);
if (e752x_pci)
edac_pci_release_generic_ctl(e752x_pci);
if ((mci = edac_mc_del_mc(&pdev->dev)) == NULL)
return;
pvt = (struct e752x_pvt *)mci->pvt_info;
pci_dev_put(pvt->dev_d0f0);
pci_dev_put(pvt->dev_d0f1);
pci_dev_put(pvt->bridge_ck);
edac_mc_free(mci);
}
static const struct pci_device_id e752x_pci_tbl[] __devinitdata = {
{
PCI_VEND_DEV(INTEL, 7520_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
E7520},
{
PCI_VEND_DEV(INTEL, 7525_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
E7525},
{
PCI_VEND_DEV(INTEL, 7320_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
E7320},
{
PCI_VEND_DEV(INTEL, 3100_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
I3100},
{
0,
} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, e752x_pci_tbl);
static struct pci_driver e752x_driver = {
.name = EDAC_MOD_STR,
.probe = e752x_init_one,
.remove = __devexit_p(e752x_remove_one),
.id_table = e752x_pci_tbl,
};
static int __init e752x_init(void)
{
int pci_rc;
debugf3("%s()\n", __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
pci_rc = pci_register_driver(&e752x_driver);
return (pci_rc < 0) ? pci_rc : 0;
}
static void __exit e752x_exit(void)
{
debugf3("%s()\n", __func__);
pci_unregister_driver(&e752x_driver);
}
module_init(e752x_init);
module_exit(e752x_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux Networx (http://lnxi.com) Tom Zimmerman\n");
MODULE_DESCRIPTION("MC support for Intel e752x/3100 memory controllers");
module_param(force_function_unhide, int, 0444);
MODULE_PARM_DESC(force_function_unhide, "if BIOS sets Dev0:Fun1 up as hidden:"
" 1=force unhide and hope BIOS doesn't fight driver for "
"Dev0:Fun1 access");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
module_param(sysbus_parity, int, 0444);
MODULE_PARM_DESC(sysbus_parity, "0=disable system bus parity checking,"
" 1=enable system bus parity checking, default=auto-detect");
module_param(report_non_memory_errors, int, 0644);
MODULE_PARM_DESC(report_non_memory_errors, "0=disable non-memory error "
"reporting, 1=enable non-memory error reporting");
| gpl-2.0 |
Kato4imoto/armani-kk-kernel | net/ipv6/mip6.c | 3025 | 13608 | /*
* Copyright (C)2003-2006 Helsinki University of Technology
* Copyright (C)2003-2006 USAGI/WIDE Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Authors:
* Noriaki TAKAMIYA @USAGI
* Masahide NAKAMURA @USAGI
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/time.h>
#include <linux/ipv6.h>
#include <linux/icmpv6.h>
#include <net/sock.h>
#include <net/ipv6.h>
#include <net/ip6_checksum.h>
#include <net/rawv6.h>
#include <net/xfrm.h>
#include <net/mip6.h>
static inline unsigned int calc_padlen(unsigned int len, unsigned int n)
{
return (n - len + 16) & 0x7;
}
static inline void *mip6_padn(__u8 *data, __u8 padlen)
{
if (!data)
return NULL;
if (padlen == 1) {
data[0] = IPV6_TLV_PAD0;
} else if (padlen > 1) {
data[0] = IPV6_TLV_PADN;
data[1] = padlen - 2;
if (padlen > 2)
memset(data+2, 0, data[1]);
}
return data + padlen;
}
static inline void mip6_param_prob(struct sk_buff *skb, u8 code, int pos)
{
icmpv6_send(skb, ICMPV6_PARAMPROB, code, pos);
}
static int mip6_mh_len(int type)
{
int len = 0;
switch (type) {
case IP6_MH_TYPE_BRR:
len = 0;
break;
case IP6_MH_TYPE_HOTI:
case IP6_MH_TYPE_COTI:
case IP6_MH_TYPE_BU:
case IP6_MH_TYPE_BACK:
len = 1;
break;
case IP6_MH_TYPE_HOT:
case IP6_MH_TYPE_COT:
case IP6_MH_TYPE_BERROR:
len = 2;
break;
}
return len;
}
static int mip6_mh_filter(struct sock *sk, struct sk_buff *skb)
{
struct ip6_mh *mh;
if (!pskb_may_pull(skb, (skb_transport_offset(skb)) + 8) ||
!pskb_may_pull(skb, (skb_transport_offset(skb) +
((skb_transport_header(skb)[1] + 1) << 3))))
return -1;
mh = (struct ip6_mh *)skb_transport_header(skb);
if (mh->ip6mh_hdrlen < mip6_mh_len(mh->ip6mh_type)) {
LIMIT_NETDEBUG(KERN_DEBUG "mip6: MH message too short: %d vs >=%d\n",
mh->ip6mh_hdrlen, mip6_mh_len(mh->ip6mh_type));
mip6_param_prob(skb, 0, ((&mh->ip6mh_hdrlen) -
skb_network_header(skb)));
return -1;
}
if (mh->ip6mh_proto != IPPROTO_NONE) {
LIMIT_NETDEBUG(KERN_DEBUG "mip6: MH invalid payload proto = %d\n",
mh->ip6mh_proto);
mip6_param_prob(skb, 0, ((&mh->ip6mh_proto) -
skb_network_header(skb)));
return -1;
}
return 0;
}
struct mip6_report_rate_limiter {
spinlock_t lock;
struct timeval stamp;
int iif;
struct in6_addr src;
struct in6_addr dst;
};
static struct mip6_report_rate_limiter mip6_report_rl = {
.lock = __SPIN_LOCK_UNLOCKED(mip6_report_rl.lock)
};
static int mip6_destopt_input(struct xfrm_state *x, struct sk_buff *skb)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
struct ipv6_destopt_hdr *destopt = (struct ipv6_destopt_hdr *)skb->data;
int err = destopt->nexthdr;
spin_lock(&x->lock);
if (!ipv6_addr_equal(&iph->saddr, (struct in6_addr *)x->coaddr) &&
!ipv6_addr_any((struct in6_addr *)x->coaddr))
err = -ENOENT;
spin_unlock(&x->lock);
return err;
}
/* Destination Option Header is inserted.
* IP Header's src address is replaced with Home Address Option in
* Destination Option Header.
*/
static int mip6_destopt_output(struct xfrm_state *x, struct sk_buff *skb)
{
struct ipv6hdr *iph;
struct ipv6_destopt_hdr *dstopt;
struct ipv6_destopt_hao *hao;
u8 nexthdr;
int len;
skb_push(skb, -skb_network_offset(skb));
iph = ipv6_hdr(skb);
nexthdr = *skb_mac_header(skb);
*skb_mac_header(skb) = IPPROTO_DSTOPTS;
dstopt = (struct ipv6_destopt_hdr *)skb_transport_header(skb);
dstopt->nexthdr = nexthdr;
hao = mip6_padn((char *)(dstopt + 1),
calc_padlen(sizeof(*dstopt), 6));
hao->type = IPV6_TLV_HAO;
BUILD_BUG_ON(sizeof(*hao) != 18);
hao->length = sizeof(*hao) - 2;
len = ((char *)hao - (char *)dstopt) + sizeof(*hao);
memcpy(&hao->addr, &iph->saddr, sizeof(hao->addr));
spin_lock_bh(&x->lock);
memcpy(&iph->saddr, x->coaddr, sizeof(iph->saddr));
spin_unlock_bh(&x->lock);
WARN_ON(len != x->props.header_len);
dstopt->hdrlen = (x->props.header_len >> 3) - 1;
return 0;
}
static inline int mip6_report_rl_allow(struct timeval *stamp,
const struct in6_addr *dst,
const struct in6_addr *src, int iif)
{
int allow = 0;
spin_lock_bh(&mip6_report_rl.lock);
if (mip6_report_rl.stamp.tv_sec != stamp->tv_sec ||
mip6_report_rl.stamp.tv_usec != stamp->tv_usec ||
mip6_report_rl.iif != iif ||
!ipv6_addr_equal(&mip6_report_rl.src, src) ||
!ipv6_addr_equal(&mip6_report_rl.dst, dst)) {
mip6_report_rl.stamp.tv_sec = stamp->tv_sec;
mip6_report_rl.stamp.tv_usec = stamp->tv_usec;
mip6_report_rl.iif = iif;
mip6_report_rl.src = *src;
mip6_report_rl.dst = *dst;
allow = 1;
}
spin_unlock_bh(&mip6_report_rl.lock);
return allow;
}
static int mip6_destopt_reject(struct xfrm_state *x, struct sk_buff *skb,
const struct flowi *fl)
{
struct net *net = xs_net(x);
struct inet6_skb_parm *opt = (struct inet6_skb_parm *)skb->cb;
const struct flowi6 *fl6 = &fl->u.ip6;
struct ipv6_destopt_hao *hao = NULL;
struct xfrm_selector sel;
int offset;
struct timeval stamp;
int err = 0;
if (unlikely(fl6->flowi6_proto == IPPROTO_MH &&
fl6->fl6_mh_type <= IP6_MH_TYPE_MAX))
goto out;
if (likely(opt->dsthao)) {
offset = ipv6_find_tlv(skb, opt->dsthao, IPV6_TLV_HAO);
if (likely(offset >= 0))
hao = (struct ipv6_destopt_hao *)
(skb_network_header(skb) + offset);
}
skb_get_timestamp(skb, &stamp);
if (!mip6_report_rl_allow(&stamp, &ipv6_hdr(skb)->daddr,
hao ? &hao->addr : &ipv6_hdr(skb)->saddr,
opt->iif))
goto out;
memset(&sel, 0, sizeof(sel));
memcpy(&sel.daddr, (xfrm_address_t *)&ipv6_hdr(skb)->daddr,
sizeof(sel.daddr));
sel.prefixlen_d = 128;
memcpy(&sel.saddr, (xfrm_address_t *)&ipv6_hdr(skb)->saddr,
sizeof(sel.saddr));
sel.prefixlen_s = 128;
sel.family = AF_INET6;
sel.proto = fl6->flowi6_proto;
sel.dport = xfrm_flowi_dport(fl, &fl6->uli);
if (sel.dport)
sel.dport_mask = htons(~0);
sel.sport = xfrm_flowi_sport(fl, &fl6->uli);
if (sel.sport)
sel.sport_mask = htons(~0);
sel.ifindex = fl6->flowi6_oif;
err = km_report(net, IPPROTO_DSTOPTS, &sel,
(hao ? (xfrm_address_t *)&hao->addr : NULL));
out:
return err;
}
static int mip6_destopt_offset(struct xfrm_state *x, struct sk_buff *skb,
u8 **nexthdr)
{
u16 offset = sizeof(struct ipv6hdr);
struct ipv6_opt_hdr *exthdr =
(struct ipv6_opt_hdr *)(ipv6_hdr(skb) + 1);
const unsigned char *nh = skb_network_header(skb);
unsigned int packet_len = skb->tail - skb->network_header;
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset + 1 <= packet_len) {
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
/*
* HAO MUST NOT appear more than once.
* XXX: It is better to try to find by the end of
* XXX: packet if HAO exists.
*/
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) {
LIMIT_NETDEBUG(KERN_WARNING "mip6: hao exists already, override\n");
return offset;
}
if (found_rhdr)
return offset;
break;
default:
return offset;
}
offset += ipv6_optlen(exthdr);
*nexthdr = &exthdr->nexthdr;
exthdr = (struct ipv6_opt_hdr *)(nh + offset);
}
return offset;
}
static int mip6_destopt_init_state(struct xfrm_state *x)
{
if (x->id.spi) {
printk(KERN_INFO "%s: spi is not 0: %u\n", __func__,
x->id.spi);
return -EINVAL;
}
if (x->props.mode != XFRM_MODE_ROUTEOPTIMIZATION) {
printk(KERN_INFO "%s: state's mode is not %u: %u\n",
__func__, XFRM_MODE_ROUTEOPTIMIZATION, x->props.mode);
return -EINVAL;
}
x->props.header_len = sizeof(struct ipv6_destopt_hdr) +
calc_padlen(sizeof(struct ipv6_destopt_hdr), 6) +
sizeof(struct ipv6_destopt_hao);
WARN_ON(x->props.header_len != 24);
return 0;
}
/*
* Do nothing about destroying since it has no specific operation for
* destination options header unlike IPsec protocols.
*/
static void mip6_destopt_destroy(struct xfrm_state *x)
{
}
static const struct xfrm_type mip6_destopt_type =
{
.description = "MIP6DESTOPT",
.owner = THIS_MODULE,
.proto = IPPROTO_DSTOPTS,
.flags = XFRM_TYPE_NON_FRAGMENT | XFRM_TYPE_LOCAL_COADDR,
.init_state = mip6_destopt_init_state,
.destructor = mip6_destopt_destroy,
.input = mip6_destopt_input,
.output = mip6_destopt_output,
.reject = mip6_destopt_reject,
.hdr_offset = mip6_destopt_offset,
};
static int mip6_rthdr_input(struct xfrm_state *x, struct sk_buff *skb)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
struct rt2_hdr *rt2 = (struct rt2_hdr *)skb->data;
int err = rt2->rt_hdr.nexthdr;
spin_lock(&x->lock);
if (!ipv6_addr_equal(&iph->daddr, (struct in6_addr *)x->coaddr) &&
!ipv6_addr_any((struct in6_addr *)x->coaddr))
err = -ENOENT;
spin_unlock(&x->lock);
return err;
}
/* Routing Header type 2 is inserted.
* IP Header's dst address is replaced with Routing Header's Home Address.
*/
static int mip6_rthdr_output(struct xfrm_state *x, struct sk_buff *skb)
{
struct ipv6hdr *iph;
struct rt2_hdr *rt2;
u8 nexthdr;
skb_push(skb, -skb_network_offset(skb));
iph = ipv6_hdr(skb);
nexthdr = *skb_mac_header(skb);
*skb_mac_header(skb) = IPPROTO_ROUTING;
rt2 = (struct rt2_hdr *)skb_transport_header(skb);
rt2->rt_hdr.nexthdr = nexthdr;
rt2->rt_hdr.hdrlen = (x->props.header_len >> 3) - 1;
rt2->rt_hdr.type = IPV6_SRCRT_TYPE_2;
rt2->rt_hdr.segments_left = 1;
memset(&rt2->reserved, 0, sizeof(rt2->reserved));
WARN_ON(rt2->rt_hdr.hdrlen != 2);
memcpy(&rt2->addr, &iph->daddr, sizeof(rt2->addr));
spin_lock_bh(&x->lock);
memcpy(&iph->daddr, x->coaddr, sizeof(iph->daddr));
spin_unlock_bh(&x->lock);
return 0;
}
static int mip6_rthdr_offset(struct xfrm_state *x, struct sk_buff *skb,
u8 **nexthdr)
{
u16 offset = sizeof(struct ipv6hdr);
struct ipv6_opt_hdr *exthdr =
(struct ipv6_opt_hdr *)(ipv6_hdr(skb) + 1);
const unsigned char *nh = skb_network_header(skb);
unsigned int packet_len = skb->tail - skb->network_header;
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset + 1 <= packet_len) {
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
if (offset + 3 <= packet_len) {
struct ipv6_rt_hdr *rt;
rt = (struct ipv6_rt_hdr *)(nh + offset);
if (rt->type != 0)
return offset;
}
found_rhdr = 1;
break;
case NEXTHDR_DEST:
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
return offset;
if (found_rhdr)
return offset;
break;
default:
return offset;
}
offset += ipv6_optlen(exthdr);
*nexthdr = &exthdr->nexthdr;
exthdr = (struct ipv6_opt_hdr *)(nh + offset);
}
return offset;
}
static int mip6_rthdr_init_state(struct xfrm_state *x)
{
if (x->id.spi) {
printk(KERN_INFO "%s: spi is not 0: %u\n", __func__,
x->id.spi);
return -EINVAL;
}
if (x->props.mode != XFRM_MODE_ROUTEOPTIMIZATION) {
printk(KERN_INFO "%s: state's mode is not %u: %u\n",
__func__, XFRM_MODE_ROUTEOPTIMIZATION, x->props.mode);
return -EINVAL;
}
x->props.header_len = sizeof(struct rt2_hdr);
return 0;
}
/*
* Do nothing about destroying since it has no specific operation for routing
* header type 2 unlike IPsec protocols.
*/
static void mip6_rthdr_destroy(struct xfrm_state *x)
{
}
static const struct xfrm_type mip6_rthdr_type =
{
.description = "MIP6RT",
.owner = THIS_MODULE,
.proto = IPPROTO_ROUTING,
.flags = XFRM_TYPE_NON_FRAGMENT | XFRM_TYPE_REMOTE_COADDR,
.init_state = mip6_rthdr_init_state,
.destructor = mip6_rthdr_destroy,
.input = mip6_rthdr_input,
.output = mip6_rthdr_output,
.hdr_offset = mip6_rthdr_offset,
};
static int __init mip6_init(void)
{
printk(KERN_INFO "Mobile IPv6\n");
if (xfrm_register_type(&mip6_destopt_type, AF_INET6) < 0) {
printk(KERN_INFO "%s: can't add xfrm type(destopt)\n", __func__);
goto mip6_destopt_xfrm_fail;
}
if (xfrm_register_type(&mip6_rthdr_type, AF_INET6) < 0) {
printk(KERN_INFO "%s: can't add xfrm type(rthdr)\n", __func__);
goto mip6_rthdr_xfrm_fail;
}
if (rawv6_mh_filter_register(mip6_mh_filter) < 0) {
printk(KERN_INFO "%s: can't add rawv6 mh filter\n", __func__);
goto mip6_rawv6_mh_fail;
}
return 0;
mip6_rawv6_mh_fail:
xfrm_unregister_type(&mip6_rthdr_type, AF_INET6);
mip6_rthdr_xfrm_fail:
xfrm_unregister_type(&mip6_destopt_type, AF_INET6);
mip6_destopt_xfrm_fail:
return -EAGAIN;
}
static void __exit mip6_fini(void)
{
if (rawv6_mh_filter_unregister(mip6_mh_filter) < 0)
printk(KERN_INFO "%s: can't remove rawv6 mh filter\n", __func__);
if (xfrm_unregister_type(&mip6_rthdr_type, AF_INET6) < 0)
printk(KERN_INFO "%s: can't remove xfrm type(rthdr)\n", __func__);
if (xfrm_unregister_type(&mip6_destopt_type, AF_INET6) < 0)
printk(KERN_INFO "%s: can't remove xfrm type(destopt)\n", __func__);
}
module_init(mip6_init);
module_exit(mip6_fini);
MODULE_LICENSE("GPL");
MODULE_ALIAS_XFRM_TYPE(AF_INET6, XFRM_PROTO_DSTOPTS);
MODULE_ALIAS_XFRM_TYPE(AF_INET6, XFRM_PROTO_ROUTING);
| gpl-2.0 |
j1nx/tlbb-linux-kernel-m3 | arch/powerpc/sysdev/rtc_cmos_setup.c | 4561 | 1590 | /*
* Setup code for PC-style Real-Time Clock.
*
* Author: Wade Farnsworth <wfarnsworth@mvista.com>
*
* 2007 (c) MontaVista Software, Inc. 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/platform_device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/mc146818rtc.h>
#include <asm/prom.h>
static int __init add_rtc(void)
{
struct device_node *np;
struct platform_device *pd;
struct resource res[2];
unsigned int num_res = 1;
int ret;
memset(&res, 0, sizeof(res));
np = of_find_compatible_node(NULL, NULL, "pnpPNP,b00");
if (!np)
return -ENODEV;
ret = of_address_to_resource(np, 0, &res[0]);
of_node_put(np);
if (ret)
return ret;
/*
* RTC_PORT(x) is hardcoded in asm/mc146818rtc.h. Verify that the
* address provided by the device node matches.
*/
if (res[0].start != RTC_PORT(0))
return -EINVAL;
np = of_find_compatible_node(NULL, NULL, "chrp,iic");
if (!np)
np = of_find_compatible_node(NULL, NULL, "pnpPNP,000");
if (np) {
of_node_put(np);
/*
* Use a fixed interrupt value of 8 since on PPC if we are
* using this its off an i8259 which we ensure has interrupt
* numbers 0..15.
*/
res[1].start = 8;
res[1].end = 8;
res[1].flags = IORESOURCE_IRQ;
num_res++;
}
pd = platform_device_register_simple("rtc_cmos", -1,
&res[0], num_res);
if (IS_ERR(pd))
return PTR_ERR(pd);
return 0;
}
fs_initcall(add_rtc);
MODULE_LICENSE("GPL");
| gpl-2.0 |
aaronpoweruser/android_kernel_oppo_find5 | scripts/kconfig/lxdialog/textbox.c | 4817 | 9144 | /*
* textbox.c -- implements the text box
*
* ORIGINAL AUTHOR: Savio Lam (lam836@cs.cuhk.hk)
* MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap (roadcap@cfw.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 "dialog.h"
static void back_lines(int n);
static void print_page(WINDOW * win, int height, int width);
static void print_line(WINDOW * win, int row, int width);
static char *get_line(void);
static void print_position(WINDOW * win);
static int hscroll;
static int begin_reached, end_reached, page_length;
static const char *buf;
static const char *page;
/*
* refresh window content
*/
static void refresh_text_box(WINDOW *dialog, WINDOW *box, int boxh, int boxw,
int cur_y, int cur_x)
{
print_page(box, boxh, boxw);
print_position(dialog);
wmove(dialog, cur_y, cur_x); /* Restore cursor position */
wrefresh(dialog);
}
/*
* Display text from a file in a dialog box.
*/
int dialog_textbox(const char *title, const char *tbuf,
int initial_height, int initial_width)
{
int i, x, y, cur_x, cur_y, key = 0;
int height, width, boxh, boxw;
int passed_end;
WINDOW *dialog, *box;
begin_reached = 1;
end_reached = 0;
page_length = 0;
hscroll = 0;
buf = tbuf;
page = buf; /* page is pointer to start of page to be displayed */
do_resize:
getmaxyx(stdscr, height, width);
if (height < 8 || width < 8)
return -ERRDISPLAYTOOSMALL;
if (initial_height != 0)
height = initial_height;
else
if (height > 4)
height -= 4;
else
height = 0;
if (initial_width != 0)
width = initial_width;
else
if (width > 5)
width -= 5;
else
width = 0;
/* center dialog box on screen */
x = (COLS - width) / 2;
y = (LINES - height) / 2;
draw_shadow(stdscr, y, x, height, width);
dialog = newwin(height, width, y, x);
keypad(dialog, TRUE);
/* Create window for box region, used for scrolling text */
boxh = height - 4;
boxw = width - 2;
box = subwin(dialog, boxh, boxw, y + 1, x + 1);
wattrset(box, dlg.dialog.atr);
wbkgdset(box, dlg.dialog.atr & A_COLOR);
keypad(box, TRUE);
/* register the new window, along with its borders */
draw_box(dialog, 0, 0, height, width,
dlg.dialog.atr, dlg.border.atr);
wattrset(dialog, dlg.border.atr);
mvwaddch(dialog, height - 3, 0, ACS_LTEE);
for (i = 0; i < width - 2; i++)
waddch(dialog, ACS_HLINE);
wattrset(dialog, dlg.dialog.atr);
wbkgdset(dialog, dlg.dialog.atr & A_COLOR);
waddch(dialog, ACS_RTEE);
print_title(dialog, title, width);
print_button(dialog, gettext(" Exit "), height - 2, width / 2 - 4, TRUE);
wnoutrefresh(dialog);
getyx(dialog, cur_y, cur_x); /* Save cursor position */
/* Print first page of text */
attr_clear(box, boxh, boxw, dlg.dialog.atr);
refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x);
while ((key != KEY_ESC) && (key != '\n')) {
key = wgetch(dialog);
switch (key) {
case 'E': /* Exit */
case 'e':
case 'X':
case 'x':
delwin(box);
delwin(dialog);
return 0;
case 'g': /* First page */
case KEY_HOME:
if (!begin_reached) {
begin_reached = 1;
page = buf;
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
}
break;
case 'G': /* Last page */
case KEY_END:
end_reached = 1;
/* point to last char in buf */
page = buf + strlen(buf);
back_lines(boxh);
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case 'K': /* Previous line */
case 'k':
case KEY_UP:
if (!begin_reached) {
back_lines(page_length + 1);
/* We don't call print_page() here but use
* scrolling to ensure faster screen update.
* However, 'end_reached' and 'page_length'
* should still be updated, and 'page' should
* point to start of next page. This is done
* by calling get_line() in the following
* 'for' loop. */
scrollok(box, TRUE);
wscrl(box, -1); /* Scroll box region down one line */
scrollok(box, FALSE);
page_length = 0;
passed_end = 0;
for (i = 0; i < boxh; i++) {
if (!i) {
/* print first line of page */
print_line(box, 0, boxw);
wnoutrefresh(box);
} else
/* Called to update 'end_reached' and 'page' */
get_line();
if (!passed_end)
page_length++;
if (end_reached && !passed_end)
passed_end = 1;
}
print_position(dialog);
wmove(dialog, cur_y, cur_x); /* Restore cursor position */
wrefresh(dialog);
}
break;
case 'B': /* Previous page */
case 'b':
case KEY_PPAGE:
if (begin_reached)
break;
back_lines(page_length + boxh);
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case 'J': /* Next line */
case 'j':
case KEY_DOWN:
if (!end_reached) {
begin_reached = 0;
scrollok(box, TRUE);
scroll(box); /* Scroll box region up one line */
scrollok(box, FALSE);
print_line(box, boxh - 1, boxw);
wnoutrefresh(box);
print_position(dialog);
wmove(dialog, cur_y, cur_x); /* Restore cursor position */
wrefresh(dialog);
}
break;
case KEY_NPAGE: /* Next page */
case ' ':
if (end_reached)
break;
begin_reached = 0;
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case '0': /* Beginning of line */
case 'H': /* Scroll left */
case 'h':
case KEY_LEFT:
if (hscroll <= 0)
break;
if (key == '0')
hscroll = 0;
else
hscroll--;
/* Reprint current page to scroll horizontally */
back_lines(page_length);
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case 'L': /* Scroll right */
case 'l':
case KEY_RIGHT:
if (hscroll >= MAX_LEN)
break;
hscroll++;
/* Reprint current page to scroll horizontally */
back_lines(page_length);
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case KEY_ESC:
key = on_key_esc(dialog);
break;
case KEY_RESIZE:
back_lines(height);
delwin(box);
delwin(dialog);
on_key_resize();
goto do_resize;
}
}
delwin(box);
delwin(dialog);
return key; /* ESC pressed */
}
/*
* Go back 'n' lines in text. Called by dialog_textbox().
* 'page' will be updated to point to the desired line in 'buf'.
*/
static void back_lines(int n)
{
int i;
begin_reached = 0;
/* Go back 'n' lines */
for (i = 0; i < n; i++) {
if (*page == '\0') {
if (end_reached) {
end_reached = 0;
continue;
}
}
if (page == buf) {
begin_reached = 1;
return;
}
page--;
do {
if (page == buf) {
begin_reached = 1;
return;
}
page--;
} while (*page != '\n');
page++;
}
}
/*
* Print a new page of text. Called by dialog_textbox().
*/
static void print_page(WINDOW * win, int height, int width)
{
int i, passed_end = 0;
page_length = 0;
for (i = 0; i < height; i++) {
print_line(win, i, width);
if (!passed_end)
page_length++;
if (end_reached && !passed_end)
passed_end = 1;
}
wnoutrefresh(win);
}
/*
* Print a new line of text. Called by dialog_textbox() and print_page().
*/
static void print_line(WINDOW * win, int row, int width)
{
char *line;
line = get_line();
line += MIN(strlen(line), hscroll); /* Scroll horizontally */
wmove(win, row, 0); /* move cursor to correct line */
waddch(win, ' ');
waddnstr(win, line, MIN(strlen(line), width - 2));
/* Clear 'residue' of previous line */
#if OLD_NCURSES
{
int x = getcurx(win);
int i;
for (i = 0; i < width - x; i++)
waddch(win, ' ');
}
#else
wclrtoeol(win);
#endif
}
/*
* Return current line of text. Called by dialog_textbox() and print_line().
* 'page' should point to start of current line before calling, and will be
* updated to point to start of next line.
*/
static char *get_line(void)
{
int i = 0;
static char line[MAX_LEN + 1];
end_reached = 0;
while (*page != '\n') {
if (*page == '\0') {
if (!end_reached) {
end_reached = 1;
break;
}
} else if (i < MAX_LEN)
line[i++] = *(page++);
else {
/* Truncate lines longer than MAX_LEN characters */
if (i == MAX_LEN)
line[i++] = '\0';
page++;
}
}
if (i <= MAX_LEN)
line[i] = '\0';
if (!end_reached)
page++; /* move pass '\n' */
return line;
}
/*
* Print current position
*/
static void print_position(WINDOW * win)
{
int percent;
wattrset(win, dlg.position_indicator.atr);
wbkgdset(win, dlg.position_indicator.atr & A_COLOR);
percent = (page - buf) * 100 / strlen(buf);
wmove(win, getmaxy(win) - 3, getmaxx(win) - 9);
wprintw(win, "(%3d%%)", percent);
}
| gpl-2.0 |
xens0117/android_kernel_samsung_klte | scripts/kconfig/lxdialog/textbox.c | 4817 | 9144 | /*
* textbox.c -- implements the text box
*
* ORIGINAL AUTHOR: Savio Lam (lam836@cs.cuhk.hk)
* MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap (roadcap@cfw.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 "dialog.h"
static void back_lines(int n);
static void print_page(WINDOW * win, int height, int width);
static void print_line(WINDOW * win, int row, int width);
static char *get_line(void);
static void print_position(WINDOW * win);
static int hscroll;
static int begin_reached, end_reached, page_length;
static const char *buf;
static const char *page;
/*
* refresh window content
*/
static void refresh_text_box(WINDOW *dialog, WINDOW *box, int boxh, int boxw,
int cur_y, int cur_x)
{
print_page(box, boxh, boxw);
print_position(dialog);
wmove(dialog, cur_y, cur_x); /* Restore cursor position */
wrefresh(dialog);
}
/*
* Display text from a file in a dialog box.
*/
int dialog_textbox(const char *title, const char *tbuf,
int initial_height, int initial_width)
{
int i, x, y, cur_x, cur_y, key = 0;
int height, width, boxh, boxw;
int passed_end;
WINDOW *dialog, *box;
begin_reached = 1;
end_reached = 0;
page_length = 0;
hscroll = 0;
buf = tbuf;
page = buf; /* page is pointer to start of page to be displayed */
do_resize:
getmaxyx(stdscr, height, width);
if (height < 8 || width < 8)
return -ERRDISPLAYTOOSMALL;
if (initial_height != 0)
height = initial_height;
else
if (height > 4)
height -= 4;
else
height = 0;
if (initial_width != 0)
width = initial_width;
else
if (width > 5)
width -= 5;
else
width = 0;
/* center dialog box on screen */
x = (COLS - width) / 2;
y = (LINES - height) / 2;
draw_shadow(stdscr, y, x, height, width);
dialog = newwin(height, width, y, x);
keypad(dialog, TRUE);
/* Create window for box region, used for scrolling text */
boxh = height - 4;
boxw = width - 2;
box = subwin(dialog, boxh, boxw, y + 1, x + 1);
wattrset(box, dlg.dialog.atr);
wbkgdset(box, dlg.dialog.atr & A_COLOR);
keypad(box, TRUE);
/* register the new window, along with its borders */
draw_box(dialog, 0, 0, height, width,
dlg.dialog.atr, dlg.border.atr);
wattrset(dialog, dlg.border.atr);
mvwaddch(dialog, height - 3, 0, ACS_LTEE);
for (i = 0; i < width - 2; i++)
waddch(dialog, ACS_HLINE);
wattrset(dialog, dlg.dialog.atr);
wbkgdset(dialog, dlg.dialog.atr & A_COLOR);
waddch(dialog, ACS_RTEE);
print_title(dialog, title, width);
print_button(dialog, gettext(" Exit "), height - 2, width / 2 - 4, TRUE);
wnoutrefresh(dialog);
getyx(dialog, cur_y, cur_x); /* Save cursor position */
/* Print first page of text */
attr_clear(box, boxh, boxw, dlg.dialog.atr);
refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x);
while ((key != KEY_ESC) && (key != '\n')) {
key = wgetch(dialog);
switch (key) {
case 'E': /* Exit */
case 'e':
case 'X':
case 'x':
delwin(box);
delwin(dialog);
return 0;
case 'g': /* First page */
case KEY_HOME:
if (!begin_reached) {
begin_reached = 1;
page = buf;
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
}
break;
case 'G': /* Last page */
case KEY_END:
end_reached = 1;
/* point to last char in buf */
page = buf + strlen(buf);
back_lines(boxh);
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case 'K': /* Previous line */
case 'k':
case KEY_UP:
if (!begin_reached) {
back_lines(page_length + 1);
/* We don't call print_page() here but use
* scrolling to ensure faster screen update.
* However, 'end_reached' and 'page_length'
* should still be updated, and 'page' should
* point to start of next page. This is done
* by calling get_line() in the following
* 'for' loop. */
scrollok(box, TRUE);
wscrl(box, -1); /* Scroll box region down one line */
scrollok(box, FALSE);
page_length = 0;
passed_end = 0;
for (i = 0; i < boxh; i++) {
if (!i) {
/* print first line of page */
print_line(box, 0, boxw);
wnoutrefresh(box);
} else
/* Called to update 'end_reached' and 'page' */
get_line();
if (!passed_end)
page_length++;
if (end_reached && !passed_end)
passed_end = 1;
}
print_position(dialog);
wmove(dialog, cur_y, cur_x); /* Restore cursor position */
wrefresh(dialog);
}
break;
case 'B': /* Previous page */
case 'b':
case KEY_PPAGE:
if (begin_reached)
break;
back_lines(page_length + boxh);
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case 'J': /* Next line */
case 'j':
case KEY_DOWN:
if (!end_reached) {
begin_reached = 0;
scrollok(box, TRUE);
scroll(box); /* Scroll box region up one line */
scrollok(box, FALSE);
print_line(box, boxh - 1, boxw);
wnoutrefresh(box);
print_position(dialog);
wmove(dialog, cur_y, cur_x); /* Restore cursor position */
wrefresh(dialog);
}
break;
case KEY_NPAGE: /* Next page */
case ' ':
if (end_reached)
break;
begin_reached = 0;
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case '0': /* Beginning of line */
case 'H': /* Scroll left */
case 'h':
case KEY_LEFT:
if (hscroll <= 0)
break;
if (key == '0')
hscroll = 0;
else
hscroll--;
/* Reprint current page to scroll horizontally */
back_lines(page_length);
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case 'L': /* Scroll right */
case 'l':
case KEY_RIGHT:
if (hscroll >= MAX_LEN)
break;
hscroll++;
/* Reprint current page to scroll horizontally */
back_lines(page_length);
refresh_text_box(dialog, box, boxh, boxw,
cur_y, cur_x);
break;
case KEY_ESC:
key = on_key_esc(dialog);
break;
case KEY_RESIZE:
back_lines(height);
delwin(box);
delwin(dialog);
on_key_resize();
goto do_resize;
}
}
delwin(box);
delwin(dialog);
return key; /* ESC pressed */
}
/*
* Go back 'n' lines in text. Called by dialog_textbox().
* 'page' will be updated to point to the desired line in 'buf'.
*/
static void back_lines(int n)
{
int i;
begin_reached = 0;
/* Go back 'n' lines */
for (i = 0; i < n; i++) {
if (*page == '\0') {
if (end_reached) {
end_reached = 0;
continue;
}
}
if (page == buf) {
begin_reached = 1;
return;
}
page--;
do {
if (page == buf) {
begin_reached = 1;
return;
}
page--;
} while (*page != '\n');
page++;
}
}
/*
* Print a new page of text. Called by dialog_textbox().
*/
static void print_page(WINDOW * win, int height, int width)
{
int i, passed_end = 0;
page_length = 0;
for (i = 0; i < height; i++) {
print_line(win, i, width);
if (!passed_end)
page_length++;
if (end_reached && !passed_end)
passed_end = 1;
}
wnoutrefresh(win);
}
/*
* Print a new line of text. Called by dialog_textbox() and print_page().
*/
static void print_line(WINDOW * win, int row, int width)
{
char *line;
line = get_line();
line += MIN(strlen(line), hscroll); /* Scroll horizontally */
wmove(win, row, 0); /* move cursor to correct line */
waddch(win, ' ');
waddnstr(win, line, MIN(strlen(line), width - 2));
/* Clear 'residue' of previous line */
#if OLD_NCURSES
{
int x = getcurx(win);
int i;
for (i = 0; i < width - x; i++)
waddch(win, ' ');
}
#else
wclrtoeol(win);
#endif
}
/*
* Return current line of text. Called by dialog_textbox() and print_line().
* 'page' should point to start of current line before calling, and will be
* updated to point to start of next line.
*/
static char *get_line(void)
{
int i = 0;
static char line[MAX_LEN + 1];
end_reached = 0;
while (*page != '\n') {
if (*page == '\0') {
if (!end_reached) {
end_reached = 1;
break;
}
} else if (i < MAX_LEN)
line[i++] = *(page++);
else {
/* Truncate lines longer than MAX_LEN characters */
if (i == MAX_LEN)
line[i++] = '\0';
page++;
}
}
if (i <= MAX_LEN)
line[i] = '\0';
if (!end_reached)
page++; /* move pass '\n' */
return line;
}
/*
* Print current position
*/
static void print_position(WINDOW * win)
{
int percent;
wattrset(win, dlg.position_indicator.atr);
wbkgdset(win, dlg.position_indicator.atr & A_COLOR);
percent = (page - buf) * 100 / strlen(buf);
wmove(win, getmaxy(win) - 3, getmaxx(win) - 9);
wprintw(win, "(%3d%%)", percent);
}
| gpl-2.0 |
tjarnold/android_kernel_jewel_3.4.49 | arch/tile/lib/cpumask.c | 7889 | 1350 | /*
* Copyright 2010 Tilera 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, version 2.
*
* 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.
*/
#include <linux/cpumask.h>
#include <linux/ctype.h>
#include <linux/errno.h>
#include <linux/smp.h>
/*
* Allow cropping out bits beyond the end of the array.
* Move to "lib" directory if more clients want to use this routine.
*/
int bitmap_parselist_crop(const char *bp, unsigned long *maskp, int nmaskbits)
{
unsigned a, b;
bitmap_zero(maskp, nmaskbits);
do {
if (!isdigit(*bp))
return -EINVAL;
a = simple_strtoul(bp, (char **)&bp, 10);
b = a;
if (*bp == '-') {
bp++;
if (!isdigit(*bp))
return -EINVAL;
b = simple_strtoul(bp, (char **)&bp, 10);
}
if (!(a <= b))
return -EINVAL;
if (b >= nmaskbits)
b = nmaskbits-1;
while (a <= b) {
set_bit(a, maskp);
a++;
}
if (*bp == ',')
bp++;
} while (*bp != '\0' && *bp != '\n');
return 0;
}
| gpl-2.0 |
cphelps76/kernel_google_msm | drivers/char/dtlk.c | 8401 | 16693 | /* -*- linux-c -*-
* dtlk.c - DoubleTalk PC driver for Linux
*
* Original author: Chris Pallotta <chris@allmedia.com>
* Current maintainer: Jim Van Zandt <jrv@vanzandt.mv.com>
*
* 2000-03-18 Jim Van Zandt: Fix polling.
* Eliminate dtlk_timer_active flag and separate dtlk_stop_timer
* function. Don't restart timer in dtlk_timer_tick. Restart timer
* in dtlk_poll after every poll. dtlk_poll returns mask (duh).
* Eliminate unused function dtlk_write_byte. Misc. code cleanups.
*/
/* This driver is for the DoubleTalk PC, a speech synthesizer
manufactured by RC Systems (http://www.rcsys.com/). It was written
based on documentation in their User's Manual file and Developer's
Tools disk.
The DoubleTalk PC contains four voice synthesizers: text-to-speech
(TTS), linear predictive coding (LPC), PCM/ADPCM, and CVSD. It
also has a tone generator. Output data for LPC are written to the
LPC port, and output data for the other modes are written to the
TTS port.
Two kinds of data can be read from the DoubleTalk: status
information (in response to the "\001?" interrogation command) is
read from the TTS port, and index markers (which mark the progress
of the speech) are read from the LPC port. Not all models of the
DoubleTalk PC implement index markers. Both the TTS and LPC ports
can also display status flags.
The DoubleTalk PC generates no interrupts.
These characteristics are mapped into the Unix stream I/O model as
follows:
"write" sends bytes to the TTS port. It is the responsibility of
the user program to switch modes among TTS, PCM/ADPCM, and CVSD.
This driver was written for use with the text-to-speech
synthesizer. If LPC output is needed some day, other minor device
numbers can be used to select among output modes.
"read" gets index markers from the LPC port. If the device does
not implement index markers, the read will fail with error EINVAL.
Status information is available using the DTLK_INTERROGATE ioctl.
*/
#include <linux/module.h>
#define KERNEL
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/errno.h> /* for -EBUSY */
#include <linux/ioport.h> /* for request_region */
#include <linux/delay.h> /* for loops_per_jiffy */
#include <linux/sched.h>
#include <linux/mutex.h>
#include <asm/io.h> /* for inb_p, outb_p, inb, outb, etc. */
#include <asm/uaccess.h> /* for get_user, etc. */
#include <linux/wait.h> /* for wait_queue */
#include <linux/init.h> /* for __init, module_{init,exit} */
#include <linux/poll.h> /* for POLLIN, etc. */
#include <linux/dtlk.h> /* local header file for DoubleTalk values */
#ifdef TRACING
#define TRACE_TEXT(str) printk(str);
#define TRACE_RET printk(")")
#else /* !TRACING */
#define TRACE_TEXT(str) ((void) 0)
#define TRACE_RET ((void) 0)
#endif /* TRACING */
static DEFINE_MUTEX(dtlk_mutex);
static void dtlk_timer_tick(unsigned long data);
static int dtlk_major;
static int dtlk_port_lpc;
static int dtlk_port_tts;
static int dtlk_busy;
static int dtlk_has_indexing;
static unsigned int dtlk_portlist[] =
{0x25e, 0x29e, 0x2de, 0x31e, 0x35e, 0x39e, 0};
static wait_queue_head_t dtlk_process_list;
static DEFINE_TIMER(dtlk_timer, dtlk_timer_tick, 0, 0);
/* prototypes for file_operations struct */
static ssize_t dtlk_read(struct file *, char __user *,
size_t nbytes, loff_t * ppos);
static ssize_t dtlk_write(struct file *, const char __user *,
size_t nbytes, loff_t * ppos);
static unsigned int dtlk_poll(struct file *, poll_table *);
static int dtlk_open(struct inode *, struct file *);
static int dtlk_release(struct inode *, struct file *);
static long dtlk_ioctl(struct file *file,
unsigned int cmd, unsigned long arg);
static const struct file_operations dtlk_fops =
{
.owner = THIS_MODULE,
.read = dtlk_read,
.write = dtlk_write,
.poll = dtlk_poll,
.unlocked_ioctl = dtlk_ioctl,
.open = dtlk_open,
.release = dtlk_release,
.llseek = no_llseek,
};
/* local prototypes */
static int dtlk_dev_probe(void);
static struct dtlk_settings *dtlk_interrogate(void);
static int dtlk_readable(void);
static char dtlk_read_lpc(void);
static char dtlk_read_tts(void);
static int dtlk_writeable(void);
static char dtlk_write_bytes(const char *buf, int n);
static char dtlk_write_tts(char);
/*
static void dtlk_handle_error(char, char, unsigned int);
*/
static ssize_t dtlk_read(struct file *file, char __user *buf,
size_t count, loff_t * ppos)
{
unsigned int minor = iminor(file->f_path.dentry->d_inode);
char ch;
int i = 0, retries;
TRACE_TEXT("(dtlk_read");
/* printk("DoubleTalk PC - dtlk_read()\n"); */
if (minor != DTLK_MINOR || !dtlk_has_indexing)
return -EINVAL;
for (retries = 0; retries < loops_per_jiffy; retries++) {
while (i < count && dtlk_readable()) {
ch = dtlk_read_lpc();
/* printk("dtlk_read() reads 0x%02x\n", ch); */
if (put_user(ch, buf++))
return -EFAULT;
i++;
}
if (i)
return i;
if (file->f_flags & O_NONBLOCK)
break;
msleep_interruptible(100);
}
if (retries == loops_per_jiffy)
printk(KERN_ERR "dtlk_read times out\n");
TRACE_RET;
return -EAGAIN;
}
static ssize_t dtlk_write(struct file *file, const char __user *buf,
size_t count, loff_t * ppos)
{
int i = 0, retries = 0, ch;
TRACE_TEXT("(dtlk_write");
#ifdef TRACING
printk(" \"");
{
int i, ch;
for (i = 0; i < count; i++) {
if (get_user(ch, buf + i))
return -EFAULT;
if (' ' <= ch && ch <= '~')
printk("%c", ch);
else
printk("\\%03o", ch);
}
printk("\"");
}
#endif
if (iminor(file->f_path.dentry->d_inode) != DTLK_MINOR)
return -EINVAL;
while (1) {
while (i < count && !get_user(ch, buf) &&
(ch == DTLK_CLEAR || dtlk_writeable())) {
dtlk_write_tts(ch);
buf++;
i++;
if (i % 5 == 0)
/* We yield our time until scheduled
again. This reduces the transfer
rate to 500 bytes/sec, but that's
still enough to keep up with the
speech synthesizer. */
msleep_interruptible(1);
else {
/* the RDY bit goes zero 2-3 usec
after writing, and goes 1 again
180-190 usec later. Here, we wait
up to 250 usec for the RDY bit to
go nonzero. */
for (retries = 0;
retries < loops_per_jiffy / (4000/HZ);
retries++)
if (inb_p(dtlk_port_tts) &
TTS_WRITABLE)
break;
}
retries = 0;
}
if (i == count)
return i;
if (file->f_flags & O_NONBLOCK)
break;
msleep_interruptible(1);
if (++retries > 10 * HZ) { /* wait no more than 10 sec
from last write */
printk("dtlk: write timeout. "
"inb_p(dtlk_port_tts) = 0x%02x\n",
inb_p(dtlk_port_tts));
TRACE_RET;
return -EBUSY;
}
}
TRACE_RET;
return -EAGAIN;
}
static unsigned int dtlk_poll(struct file *file, poll_table * wait)
{
int mask = 0;
unsigned long expires;
TRACE_TEXT(" dtlk_poll");
/*
static long int j;
printk(".");
printk("<%ld>", jiffies-j);
j=jiffies;
*/
poll_wait(file, &dtlk_process_list, wait);
if (dtlk_has_indexing && dtlk_readable()) {
del_timer(&dtlk_timer);
mask = POLLIN | POLLRDNORM;
}
if (dtlk_writeable()) {
del_timer(&dtlk_timer);
mask |= POLLOUT | POLLWRNORM;
}
/* there are no exception conditions */
/* There won't be any interrupts, so we set a timer instead. */
expires = jiffies + 3*HZ / 100;
mod_timer(&dtlk_timer, expires);
return mask;
}
static void dtlk_timer_tick(unsigned long data)
{
TRACE_TEXT(" dtlk_timer_tick");
wake_up_interruptible(&dtlk_process_list);
}
static long dtlk_ioctl(struct file *file,
unsigned int cmd,
unsigned long arg)
{
char __user *argp = (char __user *)arg;
struct dtlk_settings *sp;
char portval;
TRACE_TEXT(" dtlk_ioctl");
switch (cmd) {
case DTLK_INTERROGATE:
mutex_lock(&dtlk_mutex);
sp = dtlk_interrogate();
mutex_unlock(&dtlk_mutex);
if (copy_to_user(argp, sp, sizeof(struct dtlk_settings)))
return -EINVAL;
return 0;
case DTLK_STATUS:
portval = inb_p(dtlk_port_tts);
return put_user(portval, argp);
default:
return -EINVAL;
}
}
/* Note that nobody ever sets dtlk_busy... */
static int dtlk_open(struct inode *inode, struct file *file)
{
TRACE_TEXT("(dtlk_open");
nonseekable_open(inode, file);
switch (iminor(inode)) {
case DTLK_MINOR:
if (dtlk_busy)
return -EBUSY;
return nonseekable_open(inode, file);
default:
return -ENXIO;
}
}
static int dtlk_release(struct inode *inode, struct file *file)
{
TRACE_TEXT("(dtlk_release");
switch (iminor(inode)) {
case DTLK_MINOR:
break;
default:
break;
}
TRACE_RET;
del_timer_sync(&dtlk_timer);
return 0;
}
static int __init dtlk_init(void)
{
int err;
dtlk_port_lpc = 0;
dtlk_port_tts = 0;
dtlk_busy = 0;
dtlk_major = register_chrdev(0, "dtlk", &dtlk_fops);
if (dtlk_major < 0) {
printk(KERN_ERR "DoubleTalk PC - cannot register device\n");
return dtlk_major;
}
err = dtlk_dev_probe();
if (err) {
unregister_chrdev(dtlk_major, "dtlk");
return err;
}
printk(", MAJOR %d\n", dtlk_major);
init_waitqueue_head(&dtlk_process_list);
return 0;
}
static void __exit dtlk_cleanup (void)
{
dtlk_write_bytes("goodbye", 8);
msleep_interruptible(500); /* nap 0.50 sec but
could be awakened
earlier by
signals... */
dtlk_write_tts(DTLK_CLEAR);
unregister_chrdev(dtlk_major, "dtlk");
release_region(dtlk_port_lpc, DTLK_IO_EXTENT);
}
module_init(dtlk_init);
module_exit(dtlk_cleanup);
/* ------------------------------------------------------------------------ */
static int dtlk_readable(void)
{
#ifdef TRACING
printk(" dtlk_readable=%u@%u", inb_p(dtlk_port_lpc) != 0x7f, jiffies);
#endif
return inb_p(dtlk_port_lpc) != 0x7f;
}
static int dtlk_writeable(void)
{
/* TRACE_TEXT(" dtlk_writeable"); */
#ifdef TRACINGMORE
printk(" dtlk_writeable=%u", (inb_p(dtlk_port_tts) & TTS_WRITABLE)!=0);
#endif
return inb_p(dtlk_port_tts) & TTS_WRITABLE;
}
static int __init dtlk_dev_probe(void)
{
unsigned int testval = 0;
int i = 0;
struct dtlk_settings *sp;
if (dtlk_port_lpc | dtlk_port_tts)
return -EBUSY;
for (i = 0; dtlk_portlist[i]; i++) {
#if 0
printk("DoubleTalk PC - Port %03x = %04x\n",
dtlk_portlist[i], (testval = inw_p(dtlk_portlist[i])));
#endif
if (!request_region(dtlk_portlist[i], DTLK_IO_EXTENT,
"dtlk"))
continue;
testval = inw_p(dtlk_portlist[i]);
if ((testval &= 0xfbff) == 0x107f) {
dtlk_port_lpc = dtlk_portlist[i];
dtlk_port_tts = dtlk_port_lpc + 1;
sp = dtlk_interrogate();
printk("DoubleTalk PC at %03x-%03x, "
"ROM version %s, serial number %u",
dtlk_portlist[i], dtlk_portlist[i] +
DTLK_IO_EXTENT - 1,
sp->rom_version, sp->serial_number);
/* put LPC port into known state, so
dtlk_readable() gives valid result */
outb_p(0xff, dtlk_port_lpc);
/* INIT string and index marker */
dtlk_write_bytes("\036\1@\0\0012I\r", 8);
/* posting an index takes 18 msec. Here, we
wait up to 100 msec to see whether it
appears. */
msleep_interruptible(100);
dtlk_has_indexing = dtlk_readable();
#ifdef TRACING
printk(", indexing %d\n", dtlk_has_indexing);
#endif
#ifdef INSCOPE
{
/* This macro records ten samples read from the LPC port, for later display */
#define LOOK \
for (i = 0; i < 10; i++) \
{ \
buffer[b++] = inb_p(dtlk_port_lpc); \
__delay(loops_per_jiffy/(1000000/HZ)); \
}
char buffer[1000];
int b = 0, i, j;
LOOK
outb_p(0xff, dtlk_port_lpc);
buffer[b++] = 0;
LOOK
dtlk_write_bytes("\0012I\r", 4);
buffer[b++] = 0;
__delay(50 * loops_per_jiffy / (1000/HZ));
outb_p(0xff, dtlk_port_lpc);
buffer[b++] = 0;
LOOK
printk("\n");
for (j = 0; j < b; j++)
printk(" %02x", buffer[j]);
printk("\n");
}
#endif /* INSCOPE */
#ifdef OUTSCOPE
{
/* This macro records ten samples read from the TTS port, for later display */
#define LOOK \
for (i = 0; i < 10; i++) \
{ \
buffer[b++] = inb_p(dtlk_port_tts); \
__delay(loops_per_jiffy/(1000000/HZ)); /* 1 us */ \
}
char buffer[1000];
int b = 0, i, j;
mdelay(10); /* 10 ms */
LOOK
outb_p(0x03, dtlk_port_tts);
buffer[b++] = 0;
LOOK
LOOK
printk("\n");
for (j = 0; j < b; j++)
printk(" %02x", buffer[j]);
printk("\n");
}
#endif /* OUTSCOPE */
dtlk_write_bytes("Double Talk found", 18);
return 0;
}
release_region(dtlk_portlist[i], DTLK_IO_EXTENT);
}
printk(KERN_INFO "DoubleTalk PC - not found\n");
return -ENODEV;
}
/*
static void dtlk_handle_error(char op, char rc, unsigned int minor)
{
printk(KERN_INFO"\nDoubleTalk PC - MINOR: %d, OPCODE: %d, ERROR: %d\n",
minor, op, rc);
return;
}
*/
/* interrogate the DoubleTalk PC and return its settings */
static struct dtlk_settings *dtlk_interrogate(void)
{
unsigned char *t;
static char buf[sizeof(struct dtlk_settings) + 1];
int total, i;
static struct dtlk_settings status;
TRACE_TEXT("(dtlk_interrogate");
dtlk_write_bytes("\030\001?", 3);
for (total = 0, i = 0; i < 50; i++) {
buf[total] = dtlk_read_tts();
if (total > 2 && buf[total] == 0x7f)
break;
if (total < sizeof(struct dtlk_settings))
total++;
}
/*
if (i==50) printk("interrogate() read overrun\n");
for (i=0; i<sizeof(buf); i++)
printk(" %02x", buf[i]);
printk("\n");
*/
t = buf;
status.serial_number = t[0] + t[1] * 256; /* serial number is
little endian */
t += 2;
i = 0;
while (*t != '\r') {
status.rom_version[i] = *t;
if (i < sizeof(status.rom_version) - 1)
i++;
t++;
}
status.rom_version[i] = 0;
t++;
status.mode = *t++;
status.punc_level = *t++;
status.formant_freq = *t++;
status.pitch = *t++;
status.speed = *t++;
status.volume = *t++;
status.tone = *t++;
status.expression = *t++;
status.ext_dict_loaded = *t++;
status.ext_dict_status = *t++;
status.free_ram = *t++;
status.articulation = *t++;
status.reverb = *t++;
status.eob = *t++;
status.has_indexing = dtlk_has_indexing;
TRACE_RET;
return &status;
}
static char dtlk_read_tts(void)
{
int portval, retries = 0;
char ch;
TRACE_TEXT("(dtlk_read_tts");
/* verify DT is ready, read char, wait for ACK */
do {
portval = inb_p(dtlk_port_tts);
} while ((portval & TTS_READABLE) == 0 &&
retries++ < DTLK_MAX_RETRIES);
if (retries > DTLK_MAX_RETRIES)
printk(KERN_ERR "dtlk_read_tts() timeout\n");
ch = inb_p(dtlk_port_tts); /* input from TTS port */
ch &= 0x7f;
outb_p(ch, dtlk_port_tts);
retries = 0;
do {
portval = inb_p(dtlk_port_tts);
} while ((portval & TTS_READABLE) != 0 &&
retries++ < DTLK_MAX_RETRIES);
if (retries > DTLK_MAX_RETRIES)
printk(KERN_ERR "dtlk_read_tts() timeout\n");
TRACE_RET;
return ch;
}
static char dtlk_read_lpc(void)
{
int retries = 0;
char ch;
TRACE_TEXT("(dtlk_read_lpc");
/* no need to test -- this is only called when the port is readable */
ch = inb_p(dtlk_port_lpc); /* input from LPC port */
outb_p(0xff, dtlk_port_lpc);
/* acknowledging a read takes 3-4
usec. Here, we wait up to 20 usec
for the acknowledgement */
retries = (loops_per_jiffy * 20) / (1000000/HZ);
while (inb_p(dtlk_port_lpc) != 0x7f && --retries > 0);
if (retries == 0)
printk(KERN_ERR "dtlk_read_lpc() timeout\n");
TRACE_RET;
return ch;
}
/* write n bytes to tts port */
static char dtlk_write_bytes(const char *buf, int n)
{
char val = 0;
/* printk("dtlk_write_bytes(\"%-*s\", %d)\n", n, buf, n); */
TRACE_TEXT("(dtlk_write_bytes");
while (n-- > 0)
val = dtlk_write_tts(*buf++);
TRACE_RET;
return val;
}
static char dtlk_write_tts(char ch)
{
int retries = 0;
#ifdef TRACINGMORE
printk(" dtlk_write_tts(");
if (' ' <= ch && ch <= '~')
printk("'%c'", ch);
else
printk("0x%02x", ch);
#endif
if (ch != DTLK_CLEAR) /* no flow control for CLEAR command */
while ((inb_p(dtlk_port_tts) & TTS_WRITABLE) == 0 &&
retries++ < DTLK_MAX_RETRIES) /* DT ready? */
;
if (retries > DTLK_MAX_RETRIES)
printk(KERN_ERR "dtlk_write_tts() timeout\n");
outb_p(ch, dtlk_port_tts); /* output to TTS port */
/* the RDY bit goes zero 2-3 usec after writing, and goes
1 again 180-190 usec later. Here, we wait up to 10
usec for the RDY bit to go zero. */
for (retries = 0; retries < loops_per_jiffy / (100000/HZ); retries++)
if ((inb_p(dtlk_port_tts) & TTS_WRITABLE) == 0)
break;
#ifdef TRACINGMORE
printk(")\n");
#endif
return 0;
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
gokulnatha/GT-I9505 | drivers/ide/it821x.c | 9169 | 20903 | /*
* Copyright (C) 2004 Red Hat
* Copyright (C) 2007 Bartlomiej Zolnierkiewicz
*
* May be copied or modified under the terms of the GNU General Public License
* Based in part on the ITE vendor provided SCSI driver.
*
* Documentation:
* Datasheet is freely available, some other documents under NDA.
*
* The ITE8212 isn't exactly a standard IDE controller. It has two
* modes. In pass through mode then it is an IDE controller. In its smart
* mode its actually quite a capable hardware raid controller disguised
* as an IDE controller. Smart mode only understands DMA read/write and
* identify, none of the fancier commands apply. The IT8211 is identical
* in other respects but lacks the raid mode.
*
* Errata:
* o Rev 0x10 also requires master/slave hold the same DMA timings and
* cannot do ATAPI MWDMA.
* o The identify data for raid volumes lacks CHS info (technically ok)
* but also fails to set the LBA28 and other bits. We fix these in
* the IDE probe quirk code.
* o If you write LBA48 sized I/O's (ie > 256 sector) in smart mode
* raid then the controller firmware dies
* o Smart mode without RAID doesn't clear all the necessary identify
* bits to reduce the command set to the one used
*
* This has a few impacts on the driver
* - In pass through mode we do all the work you would expect
* - In smart mode the clocking set up is done by the controller generally
* but we must watch the other limits and filter.
* - There are a few extra vendor commands that actually talk to the
* controller but only work PIO with no IRQ.
*
* Vendor areas of the identify block in smart mode are used for the
* timing and policy set up. Each HDD in raid mode also has a serial
* block on the disk. The hardware extra commands are get/set chip status,
* rebuild, get rebuild status.
*
* In Linux the driver supports pass through mode as if the device was
* just another IDE controller. If the smart mode is running then
* volumes are managed by the controller firmware and each IDE "disk"
* is a raid volume. Even more cute - the controller can do automated
* hotplug and rebuild.
*
* The pass through controller itself is a little demented. It has a
* flaw that it has a single set of PIO/MWDMA timings per channel so
* non UDMA devices restrict each others performance. It also has a
* single clock source per channel so mixed UDMA100/133 performance
* isn't perfect and we have to pick a clock. Thankfully none of this
* matters in smart mode. ATAPI DMA is not currently supported.
*
* It seems the smart mode is a win for RAID1/RAID10 but otherwise not.
*
* TODO
* - ATAPI UDMA is ok but not MWDMA it seems
* - RAID configuration ioctls
* - Move to libata once it grows up
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/ide.h>
#include <linux/init.h>
#define DRV_NAME "it821x"
#define QUIRK_VORTEX86 1
struct it821x_dev
{
unsigned int smart:1, /* Are we in smart raid mode */
timing10:1; /* Rev 0x10 */
u8 clock_mode; /* 0, ATA_50 or ATA_66 */
u8 want[2][2]; /* Mode/Pri log for master slave */
/* We need these for switching the clock when DMA goes on/off
The high byte is the 66Mhz timing */
u16 pio[2]; /* Cached PIO values */
u16 mwdma[2]; /* Cached MWDMA values */
u16 udma[2]; /* Cached UDMA values (per drive) */
u16 quirks;
};
#define ATA_66 0
#define ATA_50 1
#define ATA_ANY 2
#define UDMA_OFF 0
#define MWDMA_OFF 0
/*
* We allow users to force the card into non raid mode without
* flashing the alternative BIOS. This is also necessary right now
* for embedded platforms that cannot run a PC BIOS but are using this
* device.
*/
static int it8212_noraid;
/**
* it821x_program - program the PIO/MWDMA registers
* @drive: drive to tune
* @timing: timing info
*
* Program the PIO/MWDMA timing for this channel according to the
* current clock.
*/
static void it821x_program(ide_drive_t *drive, u16 timing)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct it821x_dev *itdev = ide_get_hwifdata(hwif);
int channel = hwif->channel;
u8 conf;
/* Program PIO/MWDMA timing bits */
if(itdev->clock_mode == ATA_66)
conf = timing >> 8;
else
conf = timing & 0xFF;
pci_write_config_byte(dev, 0x54 + 4 * channel, conf);
}
/**
* it821x_program_udma - program the UDMA registers
* @drive: drive to tune
* @timing: timing info
*
* Program the UDMA timing for this drive according to the
* current clock.
*/
static void it821x_program_udma(ide_drive_t *drive, u16 timing)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct it821x_dev *itdev = ide_get_hwifdata(hwif);
int channel = hwif->channel;
u8 unit = drive->dn & 1, conf;
/* Program UDMA timing bits */
if(itdev->clock_mode == ATA_66)
conf = timing >> 8;
else
conf = timing & 0xFF;
if (itdev->timing10 == 0)
pci_write_config_byte(dev, 0x56 + 4 * channel + unit, conf);
else {
pci_write_config_byte(dev, 0x56 + 4 * channel, conf);
pci_write_config_byte(dev, 0x56 + 4 * channel + 1, conf);
}
}
/**
* it821x_clock_strategy
* @drive: drive to set up
*
* Select between the 50 and 66Mhz base clocks to get the best
* results for this interface.
*/
static void it821x_clock_strategy(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct it821x_dev *itdev = ide_get_hwifdata(hwif);
ide_drive_t *pair = ide_get_pair_dev(drive);
int clock, altclock, sel = 0;
u8 unit = drive->dn & 1, v;
if(itdev->want[0][0] > itdev->want[1][0]) {
clock = itdev->want[0][1];
altclock = itdev->want[1][1];
} else {
clock = itdev->want[1][1];
altclock = itdev->want[0][1];
}
/*
* if both clocks can be used for the mode with the higher priority
* use the clock needed by the mode with the lower priority
*/
if (clock == ATA_ANY)
clock = altclock;
/* Nobody cares - keep the same clock */
if(clock == ATA_ANY)
return;
/* No change */
if(clock == itdev->clock_mode)
return;
/* Load this into the controller ? */
if(clock == ATA_66)
itdev->clock_mode = ATA_66;
else {
itdev->clock_mode = ATA_50;
sel = 1;
}
pci_read_config_byte(dev, 0x50, &v);
v &= ~(1 << (1 + hwif->channel));
v |= sel << (1 + hwif->channel);
pci_write_config_byte(dev, 0x50, v);
/*
* Reprogram the UDMA/PIO of the pair drive for the switch
* MWDMA will be dealt with by the dma switcher
*/
if(pair && itdev->udma[1-unit] != UDMA_OFF) {
it821x_program_udma(pair, itdev->udma[1-unit]);
it821x_program(pair, itdev->pio[1-unit]);
}
/*
* Reprogram the UDMA/PIO of our drive for the switch.
* MWDMA will be dealt with by the dma switcher
*/
if(itdev->udma[unit] != UDMA_OFF) {
it821x_program_udma(drive, itdev->udma[unit]);
it821x_program(drive, itdev->pio[unit]);
}
}
/**
* it821x_set_pio_mode - set host controller for PIO mode
* @hwif: port
* @drive: drive
*
* Tune the host to the desired PIO mode taking into the consideration
* the maximum PIO mode supported by the other device on the cable.
*/
static void it821x_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
struct it821x_dev *itdev = ide_get_hwifdata(hwif);
ide_drive_t *pair = ide_get_pair_dev(drive);
const u8 pio = drive->pio_mode - XFER_PIO_0;
u8 unit = drive->dn & 1, set_pio = pio;
/* Spec says 89 ref driver uses 88 */
static u16 pio_timings[]= { 0xAA88, 0xA382, 0xA181, 0x3332, 0x3121 };
static u8 pio_want[] = { ATA_66, ATA_66, ATA_66, ATA_66, ATA_ANY };
/*
* Compute the best PIO mode we can for a given device. We must
* pick a speed that does not cause problems with the other device
* on the cable.
*/
if (pair) {
u8 pair_pio = pair->pio_mode - XFER_PIO_0;
/* trim PIO to the slowest of the master/slave */
if (pair_pio < set_pio)
set_pio = pair_pio;
}
/* We prefer 66Mhz clock for PIO 0-3, don't care for PIO4 */
itdev->want[unit][1] = pio_want[set_pio];
itdev->want[unit][0] = 1; /* PIO is lowest priority */
itdev->pio[unit] = pio_timings[set_pio];
it821x_clock_strategy(drive);
it821x_program(drive, itdev->pio[unit]);
}
/**
* it821x_tune_mwdma - tune a channel for MWDMA
* @drive: drive to set up
* @mode_wanted: the target operating mode
*
* Load the timing settings for this device mode into the
* controller when doing MWDMA in pass through mode. The caller
* must manage the whole lack of per device MWDMA/PIO timings and
* the shared MWDMA/PIO timing register.
*/
static void it821x_tune_mwdma(ide_drive_t *drive, u8 mode_wanted)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct it821x_dev *itdev = (void *)ide_get_hwifdata(hwif);
u8 unit = drive->dn & 1, channel = hwif->channel, conf;
static u16 dma[] = { 0x8866, 0x3222, 0x3121 };
static u8 mwdma_want[] = { ATA_ANY, ATA_66, ATA_ANY };
itdev->want[unit][1] = mwdma_want[mode_wanted];
itdev->want[unit][0] = 2; /* MWDMA is low priority */
itdev->mwdma[unit] = dma[mode_wanted];
itdev->udma[unit] = UDMA_OFF;
/* UDMA bits off - Revision 0x10 do them in pairs */
pci_read_config_byte(dev, 0x50, &conf);
if (itdev->timing10)
conf |= channel ? 0x60: 0x18;
else
conf |= 1 << (3 + 2 * channel + unit);
pci_write_config_byte(dev, 0x50, conf);
it821x_clock_strategy(drive);
/* FIXME: do we need to program this ? */
/* it821x_program(drive, itdev->mwdma[unit]); */
}
/**
* it821x_tune_udma - tune a channel for UDMA
* @drive: drive to set up
* @mode_wanted: the target operating mode
*
* Load the timing settings for this device mode into the
* controller when doing UDMA modes in pass through.
*/
static void it821x_tune_udma(ide_drive_t *drive, u8 mode_wanted)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct it821x_dev *itdev = ide_get_hwifdata(hwif);
u8 unit = drive->dn & 1, channel = hwif->channel, conf;
static u16 udma[] = { 0x4433, 0x4231, 0x3121, 0x2121, 0x1111, 0x2211, 0x1111 };
static u8 udma_want[] = { ATA_ANY, ATA_50, ATA_ANY, ATA_66, ATA_66, ATA_50, ATA_66 };
itdev->want[unit][1] = udma_want[mode_wanted];
itdev->want[unit][0] = 3; /* UDMA is high priority */
itdev->mwdma[unit] = MWDMA_OFF;
itdev->udma[unit] = udma[mode_wanted];
if(mode_wanted >= 5)
itdev->udma[unit] |= 0x8080; /* UDMA 5/6 select on */
/* UDMA on. Again revision 0x10 must do the pair */
pci_read_config_byte(dev, 0x50, &conf);
if (itdev->timing10)
conf &= channel ? 0x9F: 0xE7;
else
conf &= ~ (1 << (3 + 2 * channel + unit));
pci_write_config_byte(dev, 0x50, conf);
it821x_clock_strategy(drive);
it821x_program_udma(drive, itdev->udma[unit]);
}
/**
* it821x_dma_read - DMA hook
* @drive: drive for DMA
*
* The IT821x has a single timing register for MWDMA and for PIO
* operations. As we flip back and forth we have to reload the
* clock. In addition the rev 0x10 device only works if the same
* timing value is loaded into the master and slave UDMA clock
* so we must also reload that.
*
* FIXME: we could figure out in advance if we need to do reloads
*/
static void it821x_dma_start(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct it821x_dev *itdev = ide_get_hwifdata(hwif);
u8 unit = drive->dn & 1;
if(itdev->mwdma[unit] != MWDMA_OFF)
it821x_program(drive, itdev->mwdma[unit]);
else if(itdev->udma[unit] != UDMA_OFF && itdev->timing10)
it821x_program_udma(drive, itdev->udma[unit]);
ide_dma_start(drive);
}
/**
* it821x_dma_write - DMA hook
* @drive: drive for DMA stop
*
* The IT821x has a single timing register for MWDMA and for PIO
* operations. As we flip back and forth we have to reload the
* clock.
*/
static int it821x_dma_end(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct it821x_dev *itdev = ide_get_hwifdata(hwif);
int ret = ide_dma_end(drive);
u8 unit = drive->dn & 1;
if(itdev->mwdma[unit] != MWDMA_OFF)
it821x_program(drive, itdev->pio[unit]);
return ret;
}
/**
* it821x_set_dma_mode - set host controller for DMA mode
* @hwif: port
* @drive: drive
*
* Tune the ITE chipset for the desired DMA mode.
*/
static void it821x_set_dma_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
const u8 speed = drive->dma_mode;
/*
* MWDMA tuning is really hard because our MWDMA and PIO
* timings are kept in the same place. We can switch in the
* host dma on/off callbacks.
*/
if (speed >= XFER_UDMA_0 && speed <= XFER_UDMA_6)
it821x_tune_udma(drive, speed - XFER_UDMA_0);
else if (speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2)
it821x_tune_mwdma(drive, speed - XFER_MW_DMA_0);
}
/**
* it821x_cable_detect - cable detection
* @hwif: interface to check
*
* Check for the presence of an ATA66 capable cable on the
* interface. Problematic as it seems some cards don't have
* the needed logic onboard.
*/
static u8 it821x_cable_detect(ide_hwif_t *hwif)
{
/* The reference driver also only does disk side */
return ATA_CBL_PATA80;
}
/**
* it821x_quirkproc - post init callback
* @drive: drive
*
* This callback is run after the drive has been probed but
* before anything gets attached. It allows drivers to do any
* final tuning that is needed, or fixups to work around bugs.
*/
static void it821x_quirkproc(ide_drive_t *drive)
{
struct it821x_dev *itdev = ide_get_hwifdata(drive->hwif);
u16 *id = drive->id;
if (!itdev->smart) {
/*
* If we are in pass through mode then not much
* needs to be done, but we do bother to clear the
* IRQ mask as we may well be in PIO (eg rev 0x10)
* for now and we know unmasking is safe on this chipset.
*/
drive->dev_flags |= IDE_DFLAG_UNMASK;
} else {
/*
* Perform fixups on smart mode. We need to "lose" some
* capabilities the firmware lacks but does not filter, and
* also patch up some capability bits that it forgets to set
* in RAID mode.
*/
/* Check for RAID v native */
if (strstr((char *)&id[ATA_ID_PROD],
"Integrated Technology Express")) {
/* In raid mode the ident block is slightly buggy
We need to set the bits so that the IDE layer knows
LBA28. LBA48 and DMA ar valid */
id[ATA_ID_CAPABILITY] |= (3 << 8); /* LBA28, DMA */
id[ATA_ID_COMMAND_SET_2] |= 0x0400; /* LBA48 valid */
id[ATA_ID_CFS_ENABLE_2] |= 0x0400; /* LBA48 on */
/* Reporting logic */
printk(KERN_INFO "%s: IT8212 %sRAID %d volume",
drive->name, id[147] ? "Bootable " : "",
id[ATA_ID_CSFO]);
if (id[ATA_ID_CSFO] != 1)
printk(KERN_CONT "(%dK stripe)", id[146]);
printk(KERN_CONT ".\n");
} else {
/* Non RAID volume. Fixups to stop the core code
doing unsupported things */
id[ATA_ID_FIELD_VALID] &= 3;
id[ATA_ID_QUEUE_DEPTH] = 0;
id[ATA_ID_COMMAND_SET_1] = 0;
id[ATA_ID_COMMAND_SET_2] &= 0xC400;
id[ATA_ID_CFSSE] &= 0xC000;
id[ATA_ID_CFS_ENABLE_1] = 0;
id[ATA_ID_CFS_ENABLE_2] &= 0xC400;
id[ATA_ID_CSF_DEFAULT] &= 0xC000;
id[127] = 0;
id[ATA_ID_DLF] = 0;
id[ATA_ID_CSFO] = 0;
id[ATA_ID_CFA_POWER] = 0;
printk(KERN_INFO "%s: Performing identify fixups.\n",
drive->name);
}
/*
* Set MWDMA0 mode as enabled/support - just to tell
* IDE core that DMA is supported (it821x hardware
* takes care of DMA mode programming).
*/
if (ata_id_has_dma(id)) {
id[ATA_ID_MWDMA_MODES] |= 0x0101;
drive->current_speed = XFER_MW_DMA_0;
}
}
}
static struct ide_dma_ops it821x_pass_through_dma_ops = {
.dma_host_set = ide_dma_host_set,
.dma_setup = ide_dma_setup,
.dma_start = it821x_dma_start,
.dma_end = it821x_dma_end,
.dma_test_irq = ide_dma_test_irq,
.dma_lost_irq = ide_dma_lost_irq,
.dma_timer_expiry = ide_dma_sff_timer_expiry,
.dma_sff_read_status = ide_dma_sff_read_status,
};
/**
* init_hwif_it821x - set up hwif structs
* @hwif: interface to set up
*
* We do the basic set up of the interface structure. The IT8212
* requires several custom handlers so we override the default
* ide DMA handlers appropriately
*/
static void __devinit init_hwif_it821x(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(dev);
struct it821x_dev *itdevs = host->host_priv;
struct it821x_dev *idev = itdevs + hwif->channel;
u8 conf;
ide_set_hwifdata(hwif, idev);
pci_read_config_byte(dev, 0x50, &conf);
if (conf & 1) {
idev->smart = 1;
hwif->host_flags |= IDE_HFLAG_NO_ATAPI_DMA;
/* Long I/O's although allowed in LBA48 space cause the
onboard firmware to enter the twighlight zone */
hwif->rqsize = 256;
}
/* Pull the current clocks from 0x50 also */
if (conf & (1 << (1 + hwif->channel)))
idev->clock_mode = ATA_50;
else
idev->clock_mode = ATA_66;
idev->want[0][1] = ATA_ANY;
idev->want[1][1] = ATA_ANY;
/*
* Not in the docs but according to the reference driver
* this is necessary.
*/
if (dev->revision == 0x10) {
idev->timing10 = 1;
hwif->host_flags |= IDE_HFLAG_NO_ATAPI_DMA;
if (idev->smart == 0)
printk(KERN_WARNING DRV_NAME " %s: revision 0x10, "
"workarounds activated\n", pci_name(dev));
}
if (idev->smart == 0) {
/* MWDMA/PIO clock switching for pass through mode */
hwif->dma_ops = &it821x_pass_through_dma_ops;
} else
hwif->host_flags |= IDE_HFLAG_NO_SET_MODE;
if (hwif->dma_base == 0)
return;
hwif->ultra_mask = ATA_UDMA6;
hwif->mwdma_mask = ATA_MWDMA2;
/* Vortex86SX quirk: prevent Ultra-DMA mode to fix BadCRC issue */
if (idev->quirks & QUIRK_VORTEX86) {
if (dev->revision == 0x11)
hwif->ultra_mask = 0;
}
}
static void it8212_disable_raid(struct pci_dev *dev)
{
/* Reset local CPU, and set BIOS not ready */
pci_write_config_byte(dev, 0x5E, 0x01);
/* Set to bypass mode, and reset PCI bus */
pci_write_config_byte(dev, 0x50, 0x00);
pci_write_config_word(dev, PCI_COMMAND,
PCI_COMMAND_PARITY | PCI_COMMAND_IO |
PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER);
pci_write_config_word(dev, 0x40, 0xA0F3);
pci_write_config_dword(dev,0x4C, 0x02040204);
pci_write_config_byte(dev, 0x42, 0x36);
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 0x20);
}
static int init_chipset_it821x(struct pci_dev *dev)
{
u8 conf;
static char *mode[2] = { "pass through", "smart" };
/* Force the card into bypass mode if so requested */
if (it8212_noraid) {
printk(KERN_INFO DRV_NAME " %s: forcing bypass mode\n",
pci_name(dev));
it8212_disable_raid(dev);
}
pci_read_config_byte(dev, 0x50, &conf);
printk(KERN_INFO DRV_NAME " %s: controller in %s mode\n",
pci_name(dev), mode[conf & 1]);
return 0;
}
static const struct ide_port_ops it821x_port_ops = {
/* it821x_set_{pio,dma}_mode() are only used in pass-through mode */
.set_pio_mode = it821x_set_pio_mode,
.set_dma_mode = it821x_set_dma_mode,
.quirkproc = it821x_quirkproc,
.cable_detect = it821x_cable_detect,
};
static const struct ide_port_info it821x_chipset __devinitdata = {
.name = DRV_NAME,
.init_chipset = init_chipset_it821x,
.init_hwif = init_hwif_it821x,
.port_ops = &it821x_port_ops,
.pio_mask = ATA_PIO4,
};
/**
* it821x_init_one - pci layer discovery entry
* @dev: PCI device
* @id: ident table entry
*
* Called by the PCI code when it finds an ITE821x controller.
* We then use the IDE PCI generic helper to do most of the work.
*/
static int __devinit it821x_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
struct it821x_dev *itdevs;
int rc;
itdevs = kzalloc(2 * sizeof(*itdevs), GFP_KERNEL);
if (itdevs == NULL) {
printk(KERN_ERR DRV_NAME " %s: out of memory\n", pci_name(dev));
return -ENOMEM;
}
itdevs->quirks = id->driver_data;
rc = ide_pci_init_one(dev, &it821x_chipset, itdevs);
if (rc)
kfree(itdevs);
return rc;
}
static void __devexit it821x_remove(struct pci_dev *dev)
{
struct ide_host *host = pci_get_drvdata(dev);
struct it821x_dev *itdevs = host->host_priv;
ide_pci_remove(dev);
kfree(itdevs);
}
static const struct pci_device_id it821x_pci_tbl[] = {
{ PCI_VDEVICE(ITE, PCI_DEVICE_ID_ITE_8211), 0 },
{ PCI_VDEVICE(ITE, PCI_DEVICE_ID_ITE_8212), 0 },
{ PCI_VDEVICE(RDC, PCI_DEVICE_ID_RDC_D1010), QUIRK_VORTEX86 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, it821x_pci_tbl);
static struct pci_driver it821x_pci_driver = {
.name = "ITE821x IDE",
.id_table = it821x_pci_tbl,
.probe = it821x_init_one,
.remove = __devexit_p(it821x_remove),
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init it821x_ide_init(void)
{
return ide_pci_register_driver(&it821x_pci_driver);
}
static void __exit it821x_ide_exit(void)
{
pci_unregister_driver(&it821x_pci_driver);
}
module_init(it821x_ide_init);
module_exit(it821x_ide_exit);
module_param_named(noraid, it8212_noraid, int, S_IRUGO);
MODULE_PARM_DESC(noraid, "Force card into bypass mode");
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("PCI driver module for the ITE 821x");
MODULE_LICENSE("GPL");
| gpl-2.0 |
CyanogenMod/android_kernel_lge_g3 | arch/powerpc/boot/wii.c | 13265 | 3221 | /*
* arch/powerpc/boot/wii.c
*
* Nintendo Wii bootwrapper support
* Copyright (C) 2008-2009 The GameCube Linux Team
* Copyright (C) 2008,2009 Albert Herranz
*
* 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 <stddef.h>
#include "stdio.h"
#include "types.h"
#include "io.h"
#include "ops.h"
#include "ugecon.h"
BSS_STACK(8192);
#define HW_REG(x) ((void *)(x))
#define EXI_CTRL HW_REG(0x0d800070)
#define EXI_CTRL_ENABLE (1<<0)
#define MEM2_TOP (0x10000000 + 64*1024*1024)
#define FIRMWARE_DEFAULT_SIZE (12*1024*1024)
struct mipc_infohdr {
char magic[3];
u8 version;
u32 mem2_boundary;
u32 ipc_in;
size_t ipc_in_size;
u32 ipc_out;
size_t ipc_out_size;
};
static int mipc_check_address(u32 pa)
{
/* only MEM2 addresses */
if (pa < 0x10000000 || pa > 0x14000000)
return -EINVAL;
return 0;
}
static struct mipc_infohdr *mipc_get_infohdr(void)
{
struct mipc_infohdr **hdrp, *hdr;
/* 'mini' header pointer is the last word of MEM2 memory */
hdrp = (struct mipc_infohdr **)0x13fffffc;
if (mipc_check_address((u32)hdrp)) {
printf("mini: invalid hdrp %08X\n", (u32)hdrp);
hdr = NULL;
goto out;
}
hdr = *hdrp;
if (mipc_check_address((u32)hdr)) {
printf("mini: invalid hdr %08X\n", (u32)hdr);
hdr = NULL;
goto out;
}
if (memcmp(hdr->magic, "IPC", 3)) {
printf("mini: invalid magic\n");
hdr = NULL;
goto out;
}
out:
return hdr;
}
static int mipc_get_mem2_boundary(u32 *mem2_boundary)
{
struct mipc_infohdr *hdr;
int error;
hdr = mipc_get_infohdr();
if (!hdr) {
error = -1;
goto out;
}
if (mipc_check_address(hdr->mem2_boundary)) {
printf("mini: invalid mem2_boundary %08X\n",
hdr->mem2_boundary);
error = -EINVAL;
goto out;
}
*mem2_boundary = hdr->mem2_boundary;
error = 0;
out:
return error;
}
static void platform_fixups(void)
{
void *mem;
u32 reg[4];
u32 mem2_boundary;
int len;
int error;
mem = finddevice("/memory");
if (!mem)
fatal("Can't find memory node\n");
/* two ranges of (address, size) words */
len = getprop(mem, "reg", reg, sizeof(reg));
if (len != sizeof(reg)) {
/* nothing to do */
goto out;
}
/* retrieve MEM2 boundary from 'mini' */
error = mipc_get_mem2_boundary(&mem2_boundary);
if (error) {
/* if that fails use a sane value */
mem2_boundary = MEM2_TOP - FIRMWARE_DEFAULT_SIZE;
}
if (mem2_boundary > reg[2] && mem2_boundary < reg[2] + reg[3]) {
reg[3] = mem2_boundary - reg[2];
printf("top of MEM2 @ %08X\n", reg[2] + reg[3]);
setprop(mem, "reg", reg, sizeof(reg));
}
out:
return;
}
void platform_init(unsigned long r3, unsigned long r4, unsigned long r5)
{
u32 heapsize = 24*1024*1024 - (u32)_end;
simple_alloc_init(_end, heapsize, 32, 64);
fdt_init(_dtb_start);
/*
* 'mini' boots the Broadway processor with EXI disabled.
* We need it enabled before probing for the USB Gecko.
*/
out_be32(EXI_CTRL, in_be32(EXI_CTRL) | EXI_CTRL_ENABLE);
if (ug_probe())
console_ops.write = ug_console_write;
platform_ops.fixups = platform_fixups;
}
| gpl-2.0 |
asuradaimao/linux | drivers/gpu/drm/sti/sti_awg_utils.c | 210 | 3984 | /*
* Copyright (C) STMicroelectronics SA 2014
* Author: Vincent Abriou <vincent.abriou@st.com> for STMicroelectronics.
* License terms: GNU General Public License (GPL), version 2
*/
#include "sti_awg_utils.h"
#define AWG_OPCODE_OFFSET 10
enum opcode {
SET,
RPTSET,
RPLSET,
SKIP,
STOP,
REPEAT,
REPLAY,
JUMP,
HOLD,
};
static int awg_generate_instr(enum opcode opcode,
long int arg,
long int mux_sel,
long int data_en,
struct awg_code_generation_params *fwparams)
{
u32 instruction = 0;
u32 mux = (mux_sel << 8) & 0x1ff;
u32 data_enable = (data_en << 9) & 0x2ff;
long int arg_tmp = arg;
/* skip, repeat and replay arg should not exceed 1023.
* If user wants to exceed this value, the instruction should be
* duplicate and arg should be adjust for each duplicated instruction.
*/
while (arg_tmp > 0) {
arg = arg_tmp;
if (fwparams->instruction_offset >= AWG_MAX_INST) {
DRM_ERROR("too many number of instructions\n");
return -EINVAL;
}
switch (opcode) {
case SKIP:
/* leave 'arg' + 1 pixel elapsing without changing
* output bus */
arg--; /* pixel adjustment */
arg_tmp--;
if (arg < 0) {
/* SKIP instruction not needed */
return 0;
}
if (arg == 0) {
/* SKIP 0 not permitted but we want to skip 1
* pixel. So we transform SKIP into SET
* instruction */
opcode = SET;
break;
}
mux = 0;
data_enable = 0;
arg &= (0x3ff);
break;
case REPEAT:
case REPLAY:
if (arg == 0) {
/* REPEAT or REPLAY instruction not needed */
return 0;
}
mux = 0;
data_enable = 0;
arg &= (0x3ff);
break;
case JUMP:
mux = 0;
data_enable = 0;
arg |= 0x40; /* for jump instruction 7th bit is 1 */
arg &= 0x3ff;
break;
case STOP:
arg = 0;
break;
case SET:
case RPTSET:
case RPLSET:
case HOLD:
arg &= (0x0ff);
break;
default:
DRM_ERROR("instruction %d does not exist\n", opcode);
return -EINVAL;
}
arg_tmp = arg_tmp - arg;
arg = ((arg + mux) + data_enable);
instruction = ((opcode) << AWG_OPCODE_OFFSET) | arg;
fwparams->ram_code[fwparams->instruction_offset] =
instruction & (0x3fff);
fwparams->instruction_offset++;
}
return 0;
}
int sti_awg_generate_code_data_enable_mode(
struct awg_code_generation_params *fwparams,
struct awg_timing *timing)
{
long int val;
long int data_en;
int ret = 0;
if (timing->trailing_lines > 0) {
/* skip trailing lines */
val = timing->blanking_level;
data_en = 0;
ret |= awg_generate_instr(RPLSET, val, 0, data_en, fwparams);
val = timing->trailing_lines - 1;
data_en = 0;
ret |= awg_generate_instr(REPLAY, val, 0, data_en, fwparams);
}
if (timing->trailing_pixels > 0) {
/* skip trailing pixel */
val = timing->blanking_level;
data_en = 0;
ret |= awg_generate_instr(RPLSET, val, 0, data_en, fwparams);
val = timing->trailing_pixels - 1;
data_en = 0;
ret |= awg_generate_instr(SKIP, val, 0, data_en, fwparams);
}
/* set DE signal high */
val = timing->blanking_level;
data_en = 1;
ret |= awg_generate_instr((timing->trailing_pixels > 0) ? SET : RPLSET,
val, 0, data_en, fwparams);
if (timing->blanking_pixels > 0) {
/* skip the number of active pixel */
val = timing->active_pixels - 1;
data_en = 1;
ret |= awg_generate_instr(SKIP, val, 0, data_en, fwparams);
/* set DE signal low */
val = timing->blanking_level;
data_en = 0;
ret |= awg_generate_instr(SET, val, 0, data_en, fwparams);
}
/* replay the sequence as many active lines defined */
val = timing->active_lines - 1;
data_en = 0;
ret |= awg_generate_instr(REPLAY, val, 0, data_en, fwparams);
if (timing->blanking_lines > 0) {
/* skip blanking lines */
val = timing->blanking_level;
data_en = 0;
ret |= awg_generate_instr(RPLSET, val, 0, data_en, fwparams);
val = timing->blanking_lines - 1;
data_en = 0;
ret |= awg_generate_instr(REPLAY, val, 0, data_en, fwparams);
}
return ret;
}
| gpl-2.0 |
penberg/linux-kvm | drivers/vfio/pci/vfio_pci_intrs.c | 210 | 20312 | /*
* VFIO PCI interrupt handling
*
* Copyright (C) 2012 Red Hat, Inc. All rights reserved.
* Author: Alex Williamson <alex.williamson@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.
*
* Derived from original vfio:
* Copyright 2010 Cisco Systems, Inc. All rights reserved.
* Author: Tom Lyon, pugs@cisco.com
*/
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/eventfd.h>
#include <linux/msi.h>
#include <linux/pci.h>
#include <linux/file.h>
#include <linux/poll.h>
#include <linux/vfio.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
#include "vfio_pci_private.h"
/*
* IRQfd - generic
*/
struct virqfd {
struct vfio_pci_device *vdev;
struct eventfd_ctx *eventfd;
int (*handler)(struct vfio_pci_device *, void *);
void (*thread)(struct vfio_pci_device *, void *);
void *data;
struct work_struct inject;
wait_queue_t wait;
poll_table pt;
struct work_struct shutdown;
struct virqfd **pvirqfd;
};
static struct workqueue_struct *vfio_irqfd_cleanup_wq;
int __init vfio_pci_virqfd_init(void)
{
vfio_irqfd_cleanup_wq =
create_singlethread_workqueue("vfio-irqfd-cleanup");
if (!vfio_irqfd_cleanup_wq)
return -ENOMEM;
return 0;
}
void vfio_pci_virqfd_exit(void)
{
destroy_workqueue(vfio_irqfd_cleanup_wq);
}
static void virqfd_deactivate(struct virqfd *virqfd)
{
queue_work(vfio_irqfd_cleanup_wq, &virqfd->shutdown);
}
static int virqfd_wakeup(wait_queue_t *wait, unsigned mode, int sync, void *key)
{
struct virqfd *virqfd = container_of(wait, struct virqfd, wait);
unsigned long flags = (unsigned long)key;
if (flags & POLLIN) {
/* An event has been signaled, call function */
if ((!virqfd->handler ||
virqfd->handler(virqfd->vdev, virqfd->data)) &&
virqfd->thread)
schedule_work(&virqfd->inject);
}
if (flags & POLLHUP) {
unsigned long flags;
spin_lock_irqsave(&virqfd->vdev->irqlock, flags);
/*
* The eventfd is closing, if the virqfd has not yet been
* queued for release, as determined by testing whether the
* vdev pointer to it is still valid, queue it now. As
* with kvm irqfds, we know we won't race against the virqfd
* going away because we hold wqh->lock to get here.
*/
if (*(virqfd->pvirqfd) == virqfd) {
*(virqfd->pvirqfd) = NULL;
virqfd_deactivate(virqfd);
}
spin_unlock_irqrestore(&virqfd->vdev->irqlock, flags);
}
return 0;
}
static void virqfd_ptable_queue_proc(struct file *file,
wait_queue_head_t *wqh, poll_table *pt)
{
struct virqfd *virqfd = container_of(pt, struct virqfd, pt);
add_wait_queue(wqh, &virqfd->wait);
}
static void virqfd_shutdown(struct work_struct *work)
{
struct virqfd *virqfd = container_of(work, struct virqfd, shutdown);
u64 cnt;
eventfd_ctx_remove_wait_queue(virqfd->eventfd, &virqfd->wait, &cnt);
flush_work(&virqfd->inject);
eventfd_ctx_put(virqfd->eventfd);
kfree(virqfd);
}
static void virqfd_inject(struct work_struct *work)
{
struct virqfd *virqfd = container_of(work, struct virqfd, inject);
if (virqfd->thread)
virqfd->thread(virqfd->vdev, virqfd->data);
}
static int virqfd_enable(struct vfio_pci_device *vdev,
int (*handler)(struct vfio_pci_device *, void *),
void (*thread)(struct vfio_pci_device *, void *),
void *data, struct virqfd **pvirqfd, int fd)
{
struct fd irqfd;
struct eventfd_ctx *ctx;
struct virqfd *virqfd;
int ret = 0;
unsigned int events;
virqfd = kzalloc(sizeof(*virqfd), GFP_KERNEL);
if (!virqfd)
return -ENOMEM;
virqfd->pvirqfd = pvirqfd;
virqfd->vdev = vdev;
virqfd->handler = handler;
virqfd->thread = thread;
virqfd->data = data;
INIT_WORK(&virqfd->shutdown, virqfd_shutdown);
INIT_WORK(&virqfd->inject, virqfd_inject);
irqfd = fdget(fd);
if (!irqfd.file) {
ret = -EBADF;
goto err_fd;
}
ctx = eventfd_ctx_fileget(irqfd.file);
if (IS_ERR(ctx)) {
ret = PTR_ERR(ctx);
goto err_ctx;
}
virqfd->eventfd = ctx;
/*
* virqfds can be released by closing the eventfd or directly
* through ioctl. These are both done through a workqueue, so
* we update the pointer to the virqfd under lock to avoid
* pushing multiple jobs to release the same virqfd.
*/
spin_lock_irq(&vdev->irqlock);
if (*pvirqfd) {
spin_unlock_irq(&vdev->irqlock);
ret = -EBUSY;
goto err_busy;
}
*pvirqfd = virqfd;
spin_unlock_irq(&vdev->irqlock);
/*
* Install our own custom wake-up handling so we are notified via
* a callback whenever someone signals the underlying eventfd.
*/
init_waitqueue_func_entry(&virqfd->wait, virqfd_wakeup);
init_poll_funcptr(&virqfd->pt, virqfd_ptable_queue_proc);
events = irqfd.file->f_op->poll(irqfd.file, &virqfd->pt);
/*
* Check if there was an event already pending on the eventfd
* before we registered and trigger it as if we didn't miss it.
*/
if (events & POLLIN) {
if ((!handler || handler(vdev, data)) && thread)
schedule_work(&virqfd->inject);
}
/*
* Do not drop the file until the irqfd is fully initialized,
* otherwise we might race against the POLLHUP.
*/
fdput(irqfd);
return 0;
err_busy:
eventfd_ctx_put(ctx);
err_ctx:
fdput(irqfd);
err_fd:
kfree(virqfd);
return ret;
}
static void virqfd_disable(struct vfio_pci_device *vdev,
struct virqfd **pvirqfd)
{
unsigned long flags;
spin_lock_irqsave(&vdev->irqlock, flags);
if (*pvirqfd) {
virqfd_deactivate(*pvirqfd);
*pvirqfd = NULL;
}
spin_unlock_irqrestore(&vdev->irqlock, flags);
/*
* Block until we know all outstanding shutdown jobs have completed.
* Even if we don't queue the job, flush the wq to be sure it's
* been released.
*/
flush_workqueue(vfio_irqfd_cleanup_wq);
}
/*
* INTx
*/
static void vfio_send_intx_eventfd(struct vfio_pci_device *vdev, void *unused)
{
if (likely(is_intx(vdev) && !vdev->virq_disabled))
eventfd_signal(vdev->ctx[0].trigger, 1);
}
void vfio_pci_intx_mask(struct vfio_pci_device *vdev)
{
struct pci_dev *pdev = vdev->pdev;
unsigned long flags;
spin_lock_irqsave(&vdev->irqlock, flags);
/*
* Masking can come from interrupt, ioctl, or config space
* via INTx disable. The latter means this can get called
* even when not using intx delivery. In this case, just
* try to have the physical bit follow the virtual bit.
*/
if (unlikely(!is_intx(vdev))) {
if (vdev->pci_2_3)
pci_intx(pdev, 0);
} else if (!vdev->ctx[0].masked) {
/*
* Can't use check_and_mask here because we always want to
* mask, not just when something is pending.
*/
if (vdev->pci_2_3)
pci_intx(pdev, 0);
else
disable_irq_nosync(pdev->irq);
vdev->ctx[0].masked = true;
}
spin_unlock_irqrestore(&vdev->irqlock, flags);
}
/*
* If this is triggered by an eventfd, we can't call eventfd_signal
* or else we'll deadlock on the eventfd wait queue. Return >0 when
* a signal is necessary, which can then be handled via a work queue
* or directly depending on the caller.
*/
static int vfio_pci_intx_unmask_handler(struct vfio_pci_device *vdev,
void *unused)
{
struct pci_dev *pdev = vdev->pdev;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&vdev->irqlock, flags);
/*
* Unmasking comes from ioctl or config, so again, have the
* physical bit follow the virtual even when not using INTx.
*/
if (unlikely(!is_intx(vdev))) {
if (vdev->pci_2_3)
pci_intx(pdev, 1);
} else if (vdev->ctx[0].masked && !vdev->virq_disabled) {
/*
* A pending interrupt here would immediately trigger,
* but we can avoid that overhead by just re-sending
* the interrupt to the user.
*/
if (vdev->pci_2_3) {
if (!pci_check_and_unmask_intx(pdev))
ret = 1;
} else
enable_irq(pdev->irq);
vdev->ctx[0].masked = (ret > 0);
}
spin_unlock_irqrestore(&vdev->irqlock, flags);
return ret;
}
void vfio_pci_intx_unmask(struct vfio_pci_device *vdev)
{
if (vfio_pci_intx_unmask_handler(vdev, NULL) > 0)
vfio_send_intx_eventfd(vdev, NULL);
}
static irqreturn_t vfio_intx_handler(int irq, void *dev_id)
{
struct vfio_pci_device *vdev = dev_id;
unsigned long flags;
int ret = IRQ_NONE;
spin_lock_irqsave(&vdev->irqlock, flags);
if (!vdev->pci_2_3) {
disable_irq_nosync(vdev->pdev->irq);
vdev->ctx[0].masked = true;
ret = IRQ_HANDLED;
} else if (!vdev->ctx[0].masked && /* may be shared */
pci_check_and_mask_intx(vdev->pdev)) {
vdev->ctx[0].masked = true;
ret = IRQ_HANDLED;
}
spin_unlock_irqrestore(&vdev->irqlock, flags);
if (ret == IRQ_HANDLED)
vfio_send_intx_eventfd(vdev, NULL);
return ret;
}
static int vfio_intx_enable(struct vfio_pci_device *vdev)
{
if (!is_irq_none(vdev))
return -EINVAL;
if (!vdev->pdev->irq)
return -ENODEV;
vdev->ctx = kzalloc(sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL);
if (!vdev->ctx)
return -ENOMEM;
vdev->num_ctx = 1;
/*
* If the virtual interrupt is masked, restore it. Devices
* supporting DisINTx can be masked at the hardware level
* here, non-PCI-2.3 devices will have to wait until the
* interrupt is enabled.
*/
vdev->ctx[0].masked = vdev->virq_disabled;
if (vdev->pci_2_3)
pci_intx(vdev->pdev, !vdev->ctx[0].masked);
vdev->irq_type = VFIO_PCI_INTX_IRQ_INDEX;
return 0;
}
static int vfio_intx_set_signal(struct vfio_pci_device *vdev, int fd)
{
struct pci_dev *pdev = vdev->pdev;
unsigned long irqflags = IRQF_SHARED;
struct eventfd_ctx *trigger;
unsigned long flags;
int ret;
if (vdev->ctx[0].trigger) {
free_irq(pdev->irq, vdev);
kfree(vdev->ctx[0].name);
eventfd_ctx_put(vdev->ctx[0].trigger);
vdev->ctx[0].trigger = NULL;
}
if (fd < 0) /* Disable only */
return 0;
vdev->ctx[0].name = kasprintf(GFP_KERNEL, "vfio-intx(%s)",
pci_name(pdev));
if (!vdev->ctx[0].name)
return -ENOMEM;
trigger = eventfd_ctx_fdget(fd);
if (IS_ERR(trigger)) {
kfree(vdev->ctx[0].name);
return PTR_ERR(trigger);
}
vdev->ctx[0].trigger = trigger;
if (!vdev->pci_2_3)
irqflags = 0;
ret = request_irq(pdev->irq, vfio_intx_handler,
irqflags, vdev->ctx[0].name, vdev);
if (ret) {
vdev->ctx[0].trigger = NULL;
kfree(vdev->ctx[0].name);
eventfd_ctx_put(trigger);
return ret;
}
/*
* INTx disable will stick across the new irq setup,
* disable_irq won't.
*/
spin_lock_irqsave(&vdev->irqlock, flags);
if (!vdev->pci_2_3 && vdev->ctx[0].masked)
disable_irq_nosync(pdev->irq);
spin_unlock_irqrestore(&vdev->irqlock, flags);
return 0;
}
static void vfio_intx_disable(struct vfio_pci_device *vdev)
{
vfio_intx_set_signal(vdev, -1);
virqfd_disable(vdev, &vdev->ctx[0].unmask);
virqfd_disable(vdev, &vdev->ctx[0].mask);
vdev->irq_type = VFIO_PCI_NUM_IRQS;
vdev->num_ctx = 0;
kfree(vdev->ctx);
}
/*
* MSI/MSI-X
*/
static irqreturn_t vfio_msihandler(int irq, void *arg)
{
struct eventfd_ctx *trigger = arg;
eventfd_signal(trigger, 1);
return IRQ_HANDLED;
}
static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix)
{
struct pci_dev *pdev = vdev->pdev;
int ret;
if (!is_irq_none(vdev))
return -EINVAL;
vdev->ctx = kzalloc(nvec * sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL);
if (!vdev->ctx)
return -ENOMEM;
if (msix) {
int i;
vdev->msix = kzalloc(nvec * sizeof(struct msix_entry),
GFP_KERNEL);
if (!vdev->msix) {
kfree(vdev->ctx);
return -ENOMEM;
}
for (i = 0; i < nvec; i++)
vdev->msix[i].entry = i;
ret = pci_enable_msix_range(pdev, vdev->msix, 1, nvec);
if (ret < nvec) {
if (ret > 0)
pci_disable_msix(pdev);
kfree(vdev->msix);
kfree(vdev->ctx);
return ret;
}
} else {
ret = pci_enable_msi_range(pdev, 1, nvec);
if (ret < nvec) {
if (ret > 0)
pci_disable_msi(pdev);
kfree(vdev->ctx);
return ret;
}
}
vdev->num_ctx = nvec;
vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX :
VFIO_PCI_MSI_IRQ_INDEX;
if (!msix) {
/*
* Compute the virtual hardware field for max msi vectors -
* it is the log base 2 of the number of vectors.
*/
vdev->msi_qmax = fls(nvec * 2 - 1) - 1;
}
return 0;
}
static int vfio_msi_set_vector_signal(struct vfio_pci_device *vdev,
int vector, int fd, bool msix)
{
struct pci_dev *pdev = vdev->pdev;
int irq = msix ? vdev->msix[vector].vector : pdev->irq + vector;
char *name = msix ? "vfio-msix" : "vfio-msi";
struct eventfd_ctx *trigger;
int ret;
if (vector >= vdev->num_ctx)
return -EINVAL;
if (vdev->ctx[vector].trigger) {
free_irq(irq, vdev->ctx[vector].trigger);
kfree(vdev->ctx[vector].name);
eventfd_ctx_put(vdev->ctx[vector].trigger);
vdev->ctx[vector].trigger = NULL;
}
if (fd < 0)
return 0;
vdev->ctx[vector].name = kasprintf(GFP_KERNEL, "%s[%d](%s)",
name, vector, pci_name(pdev));
if (!vdev->ctx[vector].name)
return -ENOMEM;
trigger = eventfd_ctx_fdget(fd);
if (IS_ERR(trigger)) {
kfree(vdev->ctx[vector].name);
return PTR_ERR(trigger);
}
/*
* The MSIx vector table resides in device memory which may be cleared
* via backdoor resets. We don't allow direct access to the vector
* table so even if a userspace driver attempts to save/restore around
* such a reset it would be unsuccessful. To avoid this, restore the
* cached value of the message prior to enabling.
*/
if (msix) {
struct msi_msg msg;
get_cached_msi_msg(irq, &msg);
write_msi_msg(irq, &msg);
}
ret = request_irq(irq, vfio_msihandler, 0,
vdev->ctx[vector].name, trigger);
if (ret) {
kfree(vdev->ctx[vector].name);
eventfd_ctx_put(trigger);
return ret;
}
vdev->ctx[vector].trigger = trigger;
return 0;
}
static int vfio_msi_set_block(struct vfio_pci_device *vdev, unsigned start,
unsigned count, int32_t *fds, bool msix)
{
int i, j, ret = 0;
if (start + count > vdev->num_ctx)
return -EINVAL;
for (i = 0, j = start; i < count && !ret; i++, j++) {
int fd = fds ? fds[i] : -1;
ret = vfio_msi_set_vector_signal(vdev, j, fd, msix);
}
if (ret) {
for (--j; j >= start; j--)
vfio_msi_set_vector_signal(vdev, j, -1, msix);
}
return ret;
}
static void vfio_msi_disable(struct vfio_pci_device *vdev, bool msix)
{
struct pci_dev *pdev = vdev->pdev;
int i;
vfio_msi_set_block(vdev, 0, vdev->num_ctx, NULL, msix);
for (i = 0; i < vdev->num_ctx; i++) {
virqfd_disable(vdev, &vdev->ctx[i].unmask);
virqfd_disable(vdev, &vdev->ctx[i].mask);
}
if (msix) {
pci_disable_msix(vdev->pdev);
kfree(vdev->msix);
} else
pci_disable_msi(pdev);
vdev->irq_type = VFIO_PCI_NUM_IRQS;
vdev->num_ctx = 0;
kfree(vdev->ctx);
}
/*
* IOCTL support
*/
static int vfio_pci_set_intx_unmask(struct vfio_pci_device *vdev,
unsigned index, unsigned start,
unsigned count, uint32_t flags, void *data)
{
if (!is_intx(vdev) || start != 0 || count != 1)
return -EINVAL;
if (flags & VFIO_IRQ_SET_DATA_NONE) {
vfio_pci_intx_unmask(vdev);
} else if (flags & VFIO_IRQ_SET_DATA_BOOL) {
uint8_t unmask = *(uint8_t *)data;
if (unmask)
vfio_pci_intx_unmask(vdev);
} else if (flags & VFIO_IRQ_SET_DATA_EVENTFD) {
int32_t fd = *(int32_t *)data;
if (fd >= 0)
return virqfd_enable(vdev, vfio_pci_intx_unmask_handler,
vfio_send_intx_eventfd, NULL,
&vdev->ctx[0].unmask, fd);
virqfd_disable(vdev, &vdev->ctx[0].unmask);
}
return 0;
}
static int vfio_pci_set_intx_mask(struct vfio_pci_device *vdev,
unsigned index, unsigned start,
unsigned count, uint32_t flags, void *data)
{
if (!is_intx(vdev) || start != 0 || count != 1)
return -EINVAL;
if (flags & VFIO_IRQ_SET_DATA_NONE) {
vfio_pci_intx_mask(vdev);
} else if (flags & VFIO_IRQ_SET_DATA_BOOL) {
uint8_t mask = *(uint8_t *)data;
if (mask)
vfio_pci_intx_mask(vdev);
} else if (flags & VFIO_IRQ_SET_DATA_EVENTFD) {
return -ENOTTY; /* XXX implement me */
}
return 0;
}
static int vfio_pci_set_intx_trigger(struct vfio_pci_device *vdev,
unsigned index, unsigned start,
unsigned count, uint32_t flags, void *data)
{
if (is_intx(vdev) && !count && (flags & VFIO_IRQ_SET_DATA_NONE)) {
vfio_intx_disable(vdev);
return 0;
}
if (!(is_intx(vdev) || is_irq_none(vdev)) || start != 0 || count != 1)
return -EINVAL;
if (flags & VFIO_IRQ_SET_DATA_EVENTFD) {
int32_t fd = *(int32_t *)data;
int ret;
if (is_intx(vdev))
return vfio_intx_set_signal(vdev, fd);
ret = vfio_intx_enable(vdev);
if (ret)
return ret;
ret = vfio_intx_set_signal(vdev, fd);
if (ret)
vfio_intx_disable(vdev);
return ret;
}
if (!is_intx(vdev))
return -EINVAL;
if (flags & VFIO_IRQ_SET_DATA_NONE) {
vfio_send_intx_eventfd(vdev, NULL);
} else if (flags & VFIO_IRQ_SET_DATA_BOOL) {
uint8_t trigger = *(uint8_t *)data;
if (trigger)
vfio_send_intx_eventfd(vdev, NULL);
}
return 0;
}
static int vfio_pci_set_msi_trigger(struct vfio_pci_device *vdev,
unsigned index, unsigned start,
unsigned count, uint32_t flags, void *data)
{
int i;
bool msix = (index == VFIO_PCI_MSIX_IRQ_INDEX) ? true : false;
if (irq_is(vdev, index) && !count && (flags & VFIO_IRQ_SET_DATA_NONE)) {
vfio_msi_disable(vdev, msix);
return 0;
}
if (!(irq_is(vdev, index) || is_irq_none(vdev)))
return -EINVAL;
if (flags & VFIO_IRQ_SET_DATA_EVENTFD) {
int32_t *fds = data;
int ret;
if (vdev->irq_type == index)
return vfio_msi_set_block(vdev, start, count,
fds, msix);
ret = vfio_msi_enable(vdev, start + count, msix);
if (ret)
return ret;
ret = vfio_msi_set_block(vdev, start, count, fds, msix);
if (ret)
vfio_msi_disable(vdev, msix);
return ret;
}
if (!irq_is(vdev, index) || start + count > vdev->num_ctx)
return -EINVAL;
for (i = start; i < start + count; i++) {
if (!vdev->ctx[i].trigger)
continue;
if (flags & VFIO_IRQ_SET_DATA_NONE) {
eventfd_signal(vdev->ctx[i].trigger, 1);
} else if (flags & VFIO_IRQ_SET_DATA_BOOL) {
uint8_t *bools = data;
if (bools[i - start])
eventfd_signal(vdev->ctx[i].trigger, 1);
}
}
return 0;
}
static int vfio_pci_set_err_trigger(struct vfio_pci_device *vdev,
unsigned index, unsigned start,
unsigned count, uint32_t flags, void *data)
{
int32_t fd = *(int32_t *)data;
if ((index != VFIO_PCI_ERR_IRQ_INDEX) ||
!(flags & VFIO_IRQ_SET_DATA_TYPE_MASK))
return -EINVAL;
/* DATA_NONE/DATA_BOOL enables loopback testing */
if (flags & VFIO_IRQ_SET_DATA_NONE) {
if (vdev->err_trigger)
eventfd_signal(vdev->err_trigger, 1);
return 0;
} else if (flags & VFIO_IRQ_SET_DATA_BOOL) {
uint8_t trigger = *(uint8_t *)data;
if (trigger && vdev->err_trigger)
eventfd_signal(vdev->err_trigger, 1);
return 0;
}
/* Handle SET_DATA_EVENTFD */
if (fd == -1) {
if (vdev->err_trigger)
eventfd_ctx_put(vdev->err_trigger);
vdev->err_trigger = NULL;
return 0;
} else if (fd >= 0) {
struct eventfd_ctx *efdctx;
efdctx = eventfd_ctx_fdget(fd);
if (IS_ERR(efdctx))
return PTR_ERR(efdctx);
if (vdev->err_trigger)
eventfd_ctx_put(vdev->err_trigger);
vdev->err_trigger = efdctx;
return 0;
} else
return -EINVAL;
}
int vfio_pci_set_irqs_ioctl(struct vfio_pci_device *vdev, uint32_t flags,
unsigned index, unsigned start, unsigned count,
void *data)
{
int (*func)(struct vfio_pci_device *vdev, unsigned index,
unsigned start, unsigned count, uint32_t flags,
void *data) = NULL;
switch (index) {
case VFIO_PCI_INTX_IRQ_INDEX:
switch (flags & VFIO_IRQ_SET_ACTION_TYPE_MASK) {
case VFIO_IRQ_SET_ACTION_MASK:
func = vfio_pci_set_intx_mask;
break;
case VFIO_IRQ_SET_ACTION_UNMASK:
func = vfio_pci_set_intx_unmask;
break;
case VFIO_IRQ_SET_ACTION_TRIGGER:
func = vfio_pci_set_intx_trigger;
break;
}
break;
case VFIO_PCI_MSI_IRQ_INDEX:
case VFIO_PCI_MSIX_IRQ_INDEX:
switch (flags & VFIO_IRQ_SET_ACTION_TYPE_MASK) {
case VFIO_IRQ_SET_ACTION_MASK:
case VFIO_IRQ_SET_ACTION_UNMASK:
/* XXX Need masking support exported */
break;
case VFIO_IRQ_SET_ACTION_TRIGGER:
func = vfio_pci_set_msi_trigger;
break;
}
break;
case VFIO_PCI_ERR_IRQ_INDEX:
switch (flags & VFIO_IRQ_SET_ACTION_TYPE_MASK) {
case VFIO_IRQ_SET_ACTION_TRIGGER:
if (pci_is_pcie(vdev->pdev))
func = vfio_pci_set_err_trigger;
break;
}
}
if (!func)
return -ENOTTY;
return func(vdev, index, start, count, flags, data);
}
| gpl-2.0 |
deepongi/android_kernel_sony_msm | drivers/usb/misc/ipc_bridge.c | 978 | 16756 | /* Copyright (c) 2011-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/ch9.h>
#include <linux/usb/cdc.h>
#include <linux/debugfs.h>
#include <mach/ipc_bridge.h>
enum ipc_bridge_rx_state {
RX_IDLE, /* inturb is not queued */
RX_WAIT, /* inturb is queued and waiting for data */
RX_BUSY, /* inturb is completed. processing RX */
};
struct ctl_pkt {
u32 len;
void *buf;
struct list_head list;
};
struct ipc_bridge {
struct usb_device *udev;
struct usb_interface *intf;
struct urb *inturb;
struct urb *readurb;
struct urb *writeurb;
struct usb_ctrlrequest *in_ctlreq;
struct usb_ctrlrequest *out_ctlreq;
void *readbuf;
void *intbuf;
spinlock_t lock;
struct list_head rx_list;
enum ipc_bridge_rx_state rx_state;
struct platform_device *pdev;
struct mutex open_mutex;
struct mutex read_mutex;
struct mutex write_mutex;
bool opened;
struct completion write_done;
int write_result;
wait_queue_head_t read_wait_q;
unsigned int snd_encap_cmd;
unsigned int get_encap_resp;
unsigned int susp_fail_cnt;
};
#define IPC_BRIDGE_MAX_READ_SZ (8 * 1024)
#define IPC_BRIDGE_MAX_WRITE_SZ (8 * 1024)
static struct ipc_bridge *__ipc_bridge_dev;
static int ipc_bridge_submit_inturb(struct ipc_bridge *dev, gfp_t gfp_flags)
{
int ret;
unsigned long flags;
ret = usb_submit_urb(dev->inturb, gfp_flags);
if (ret < 0 && ret != -EPERM)
dev_err(&dev->intf->dev, "int urb submit err %d\n", ret);
spin_lock_irqsave(&dev->lock, flags);
if (ret)
dev->rx_state = RX_IDLE;
else
dev->rx_state = RX_WAIT;
spin_unlock_irqrestore(&dev->lock, flags);
return ret;
}
static void ipc_bridge_write_cb(struct urb *urb)
{
struct ipc_bridge *dev = urb->context;
usb_autopm_put_interface_async(dev->intf);
if (urb->dev->state == USB_STATE_NOTATTACHED)
dev->write_result = -ENODEV;
else if (urb->status < 0)
dev->write_result = urb->status;
else
dev->write_result = urb->actual_length;
complete(&dev->write_done);
}
static void ipc_bridge_read_cb(struct urb *urb)
{
struct ipc_bridge *dev = urb->context;
bool resubmit = true;
struct ctl_pkt *pkt;
unsigned long flags;
usb_autopm_put_interface_async(dev->intf);
if (urb->dev->state == USB_STATE_NOTATTACHED) {
wake_up(&dev->read_wait_q);
return;
}
switch (urb->status) {
case 0:
break;
case -ENOENT:
case -ESHUTDOWN:
case -ECONNRESET:
case -EPROTO:
case -EPIPE:
resubmit = false;
goto done;
case -EOVERFLOW:
default:
goto done;
}
if (!urb->actual_length)
goto done;
pkt = kmalloc(sizeof(*pkt), GFP_ATOMIC);
if (!pkt) {
dev_err(&dev->intf->dev, "fail to allocate pkt\n");
resubmit = false;
goto done;
}
pkt->len = urb->actual_length;
pkt->buf = kmalloc(pkt->len, GFP_ATOMIC);
if (!pkt->buf) {
kfree(pkt);
dev_err(&dev->intf->dev, "fail to allocate pkt buffer\n");
resubmit = false;
goto done;
}
memcpy(pkt->buf, urb->transfer_buffer, pkt->len);
spin_lock_irqsave(&dev->lock, flags);
list_add_tail(&pkt->list, &dev->rx_list);
spin_unlock_irqrestore(&dev->lock, flags);
wake_up(&dev->read_wait_q);
done:
if (resubmit) {
ipc_bridge_submit_inturb(dev, GFP_ATOMIC);
} else {
spin_lock_irqsave(&dev->lock, flags);
dev->rx_state = RX_IDLE;
spin_unlock_irqrestore(&dev->lock, flags);
}
}
static void ipc_bridge_int_cb(struct urb *urb)
{
struct ipc_bridge *dev = urb->context;
struct usb_cdc_notification *ctl;
int status;
unsigned long flags;
if (urb->dev->state == USB_STATE_NOTATTACHED)
return;
spin_lock_irqsave(&dev->lock, flags);
dev->rx_state = RX_IDLE;
spin_unlock_irqrestore(&dev->lock, flags);
switch (urb->status) {
case 0:
case -ENOENT:
break;
case -ESHUTDOWN:
case -ECONNRESET:
case -EPROTO:
case -EPIPE:
return;
case -EOVERFLOW:
default:
ipc_bridge_submit_inturb(dev, GFP_ATOMIC);
return;
}
if (!urb->actual_length)
return;
ctl = urb->transfer_buffer;
switch (ctl->bNotificationType) {
case USB_CDC_NOTIFY_RESPONSE_AVAILABLE:
spin_lock_irqsave(&dev->lock, flags);
dev->rx_state = RX_BUSY;
spin_unlock_irqrestore(&dev->lock, flags);
usb_fill_control_urb(dev->readurb, dev->udev,
usb_rcvctrlpipe(dev->udev, 0),
(unsigned char *)dev->in_ctlreq,
dev->readbuf, IPC_BRIDGE_MAX_READ_SZ,
ipc_bridge_read_cb, dev);
status = usb_submit_urb(dev->readurb, GFP_ATOMIC);
if (status) {
dev_err(&dev->intf->dev, "read urb submit err %d\n",
status);
goto resubmit_int_urb;
}
dev->get_encap_resp++;
/* Tell runtime pm core that we are busy */
usb_autopm_get_interface_async(dev->intf);
return;
default:
dev_err(&dev->intf->dev, "unknown data on int ep\n");
}
resubmit_int_urb:
ipc_bridge_submit_inturb(dev, GFP_ATOMIC);
}
static int ipc_bridge_open(struct platform_device *pdev)
{
struct ipc_bridge *dev = __ipc_bridge_dev;
if (dev->pdev != pdev)
return -EINVAL;
mutex_lock(&dev->open_mutex);
if (dev->opened) {
mutex_unlock(&dev->open_mutex);
dev_dbg(&dev->intf->dev, "bridge already opened\n");
return -EBUSY;
}
dev->opened = true;
mutex_unlock(&dev->open_mutex);
return 0;
}
static int ipc_bridge_rx_list_empty(struct ipc_bridge *dev)
{
int ret;
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
ret = list_empty(&dev->rx_list);
spin_unlock_irqrestore(&dev->lock, flags);
return ret;
}
static int
ipc_bridge_read(struct platform_device *pdev, char *buf, unsigned int count)
{
struct ipc_bridge *dev = __ipc_bridge_dev;
struct ctl_pkt *pkt;
int ret;
unsigned long flags;
if (dev->pdev != pdev)
return -EINVAL;
if (!dev->opened)
return -EPERM;
if (count > IPC_BRIDGE_MAX_READ_SZ)
return -ENOSPC;
mutex_lock(&dev->read_mutex);
wait_event(dev->read_wait_q, (!ipc_bridge_rx_list_empty(dev) ||
(dev->udev->state == USB_STATE_NOTATTACHED)));
if (dev->udev->state == USB_STATE_NOTATTACHED) {
ret = -ENODEV;
goto done;
}
spin_lock_irqsave(&dev->lock, flags);
pkt = list_first_entry(&dev->rx_list, struct ctl_pkt, list);
if (pkt->len > count) {
spin_unlock_irqrestore(&dev->lock, flags);
dev_err(&dev->intf->dev, "large RX packet\n");
ret = -ENOSPC;
goto done;
}
list_del(&pkt->list);
spin_unlock_irqrestore(&dev->lock, flags);
memcpy(buf, pkt->buf, pkt->len);
ret = pkt->len;
kfree(pkt->buf);
kfree(pkt);
done:
mutex_unlock(&dev->read_mutex);
return ret;
}
static int
ipc_bridge_write(struct platform_device *pdev, char *buf, unsigned int count)
{
struct ipc_bridge *dev = __ipc_bridge_dev;
int ret;
if (dev->pdev != pdev)
return -EINVAL;
if (!dev->opened)
return -EPERM;
if (count > IPC_BRIDGE_MAX_WRITE_SZ)
return -EINVAL;
mutex_lock(&dev->write_mutex);
dev->out_ctlreq->wLength = cpu_to_le16(count);
usb_fill_control_urb(dev->writeurb, dev->udev,
usb_sndctrlpipe(dev->udev, 0),
(unsigned char *)dev->out_ctlreq,
(void *)buf, count,
ipc_bridge_write_cb, dev);
ret = usb_autopm_get_interface(dev->intf);
if (ret < 0) {
dev_err(&dev->intf->dev, "write auto pm fail %d\n", ret);
goto done;
}
ret = usb_submit_urb(dev->writeurb, GFP_KERNEL);
if (ret < 0) {
dev_err(&dev->intf->dev, "write urb submit err %d\n", ret);
usb_autopm_put_interface_async(dev->intf);
goto done;
}
dev->snd_encap_cmd++;
wait_for_completion(&dev->write_done);
ret = dev->write_result;
done:
mutex_unlock(&dev->write_mutex);
return ret;
}
static void ipc_bridge_close(struct platform_device *pdev)
{
struct ipc_bridge *dev = __ipc_bridge_dev;
WARN_ON(dev->pdev != pdev);
WARN_ON(dev->udev->state != USB_STATE_NOTATTACHED);
mutex_lock(&dev->open_mutex);
if (!dev->opened) {
mutex_unlock(&dev->open_mutex);
dev_dbg(&dev->intf->dev, "bridge not opened\n");
return;
}
dev->opened = false;
mutex_unlock(&dev->open_mutex);
}
static const struct ipc_bridge_platform_data ipc_bridge_pdata = {
.max_read_size = IPC_BRIDGE_MAX_READ_SZ,
.max_write_size = IPC_BRIDGE_MAX_WRITE_SZ,
.open = ipc_bridge_open,
.read = ipc_bridge_read,
.write = ipc_bridge_write,
.close = ipc_bridge_close,
};
static int ipc_bridge_suspend(struct usb_interface *intf, pm_message_t message)
{
struct ipc_bridge *dev = usb_get_intfdata(intf);
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&dev->lock, flags);
if (dev->rx_state == RX_BUSY) {
dev->susp_fail_cnt++;
ret = -EBUSY;
goto done;
}
spin_unlock_irqrestore(&dev->lock, flags);
usb_kill_urb(dev->inturb);
spin_lock_irqsave(&dev->lock, flags);
if (dev->rx_state != RX_IDLE) {
dev->susp_fail_cnt++;
ret = -EBUSY;
goto done;
}
done:
spin_unlock_irqrestore(&dev->lock, flags);
return ret;
}
static int ipc_bridge_resume(struct usb_interface *intf)
{
struct ipc_bridge *dev = usb_get_intfdata(intf);
return ipc_bridge_submit_inturb(dev, GFP_KERNEL);
}
#define DEBUG_BUF_SIZE 512
static ssize_t ipc_bridge_read_stats(struct file *file, char __user *ubuf,
size_t count, loff_t *ppos)
{
struct ipc_bridge *dev = __ipc_bridge_dev;
char *buf;
int ret;
buf = kzalloc(DEBUG_BUF_SIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
ret = scnprintf(buf, DEBUG_BUF_SIZE,
"ch opened: %d\n"
"encap cmd sent: %u\n"
"encap resp recvd: %u\n"
"suspend fail cnt: %u\n",
dev->opened,
dev->snd_encap_cmd,
dev->get_encap_resp,
dev->susp_fail_cnt
);
ret = simple_read_from_buffer(ubuf, count, ppos, buf, ret);
kfree(buf);
return ret;
}
const struct file_operations ipc_stats_ops = {
.read = ipc_bridge_read_stats,
};
static struct dentry *dir;
static void ipc_bridge_debugfs_init(void)
{
struct dentry *dfile;
dir = debugfs_create_dir("ipc_bridge", 0);
if (IS_ERR_OR_NULL(dir))
return;
dfile = debugfs_create_file("status", 0444, dir, 0, &ipc_stats_ops);
if (IS_ERR_OR_NULL(dfile))
debugfs_remove(dir);
}
static void ipc_bridge_debugfs_cleanup(void)
{
debugfs_remove_recursive(dir);
}
static int
ipc_bridge_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct ipc_bridge *dev;
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_host_interface *intf_desc;
struct usb_endpoint_descriptor *ep;
u16 wMaxPacketSize;
int ret;
intf_desc = intf->cur_altsetting;
if (intf_desc->desc.bNumEndpoints != 1 || !usb_endpoint_is_int_in(
&intf_desc->endpoint[0].desc)) {
dev_err(&intf->dev, "driver expects only 1 int ep\n");
return -ENODEV;
}
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
dev_err(&intf->dev, "fail to allocate dev\n");
return -ENOMEM;
}
__ipc_bridge_dev = dev;
dev->inturb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->inturb) {
dev_err(&intf->dev, "fail to allocate int urb\n");
ret = -ENOMEM;
goto free_dev;
}
ep = &intf->cur_altsetting->endpoint[0].desc;
wMaxPacketSize = le16_to_cpu(ep->wMaxPacketSize);
dev->intbuf = kmalloc(wMaxPacketSize, GFP_KERNEL);
if (!dev->intbuf) {
dev_err(&intf->dev, "%s: error allocating int buffer\n",
__func__);
ret = -ENOMEM;
goto free_inturb;
}
usb_fill_int_urb(dev->inturb, udev,
usb_rcvintpipe(udev, ep->bEndpointAddress),
dev->intbuf, wMaxPacketSize,
ipc_bridge_int_cb, dev, ep->bInterval);
dev->in_ctlreq = kmalloc(sizeof(*dev->in_ctlreq), GFP_KERNEL);
if (!dev->in_ctlreq) {
dev_err(&intf->dev, "error allocating IN control req\n");
ret = -ENOMEM;
goto free_intbuf;
}
dev->in_ctlreq->bRequestType =
(USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE);
dev->in_ctlreq->bRequest = USB_CDC_GET_ENCAPSULATED_RESPONSE;
dev->in_ctlreq->wValue = 0;
dev->in_ctlreq->wIndex = intf->cur_altsetting->desc.bInterfaceNumber;
dev->in_ctlreq->wLength = cpu_to_le16(IPC_BRIDGE_MAX_READ_SZ);
dev->readurb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->readurb) {
dev_err(&intf->dev, "fail to allocate read urb\n");
ret = -ENOMEM;
goto free_in_ctlreq;
}
dev->readbuf = kmalloc(IPC_BRIDGE_MAX_READ_SZ, GFP_KERNEL);
if (!dev->readbuf) {
dev_err(&intf->dev, "fail to allocate read buffer\n");
ret = -ENOMEM;
goto free_readurb;
}
dev->out_ctlreq = kmalloc(sizeof(*dev->out_ctlreq), GFP_KERNEL);
if (!dev->out_ctlreq) {
dev_err(&intf->dev, "error allocating OUT control req\n");
ret = -ENOMEM;
goto free_readbuf;
}
dev->out_ctlreq->bRequestType =
(USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE);
dev->out_ctlreq->bRequest = USB_CDC_SEND_ENCAPSULATED_COMMAND;
dev->out_ctlreq->wValue = 0;
dev->out_ctlreq->wIndex = intf->cur_altsetting->desc.bInterfaceNumber;
dev->writeurb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->writeurb) {
dev_err(&intf->dev, "fail to allocate write urb\n");
ret = -ENOMEM;
goto free_out_ctlreq;
}
dev->udev = usb_get_dev(interface_to_usbdev(intf));
dev->intf = intf;
spin_lock_init(&dev->lock);
init_completion(&dev->write_done);
init_waitqueue_head(&dev->read_wait_q);
INIT_LIST_HEAD(&dev->rx_list);
mutex_init(&dev->open_mutex);
mutex_init(&dev->read_mutex);
mutex_init(&dev->write_mutex);
usb_set_intfdata(intf, dev);
usb_enable_autosuspend(udev);
dev->pdev = platform_device_alloc("ipc_bridge", -1);
if (!dev->pdev) {
dev_err(&intf->dev, "fail to allocate pdev\n");
ret = -ENOMEM;
goto destroy_mutex;
}
ret = platform_device_add_data(dev->pdev, &ipc_bridge_pdata,
sizeof(struct ipc_bridge_platform_data));
if (ret) {
dev_err(&intf->dev, "fail to add pdata\n");
goto put_pdev;
}
ret = platform_device_add(dev->pdev);
if (ret) {
dev_err(&intf->dev, "fail to add pdev\n");
goto put_pdev;
}
ret = ipc_bridge_submit_inturb(dev, GFP_KERNEL);
if (ret) {
dev_err(&intf->dev, "fail to start reading\n");
goto del_pdev;
}
ipc_bridge_debugfs_init();
return 0;
del_pdev:
platform_device_del(dev->pdev);
put_pdev:
platform_device_put(dev->pdev);
destroy_mutex:
usb_disable_autosuspend(udev);
mutex_destroy(&dev->write_mutex);
mutex_destroy(&dev->read_mutex);
mutex_destroy(&dev->open_mutex);
usb_put_dev(dev->udev);
usb_free_urb(dev->writeurb);
free_out_ctlreq:
kfree(dev->out_ctlreq);
free_readbuf:
kfree(dev->readbuf);
free_readurb:
usb_free_urb(dev->readurb);
free_in_ctlreq:
kfree(dev->in_ctlreq);
free_intbuf:
kfree(dev->intbuf);
free_inturb:
usb_free_urb(dev->inturb);
free_dev:
kfree(dev);
__ipc_bridge_dev = NULL;
return ret;
}
static void ipc_bridge_disconnect(struct usb_interface *intf)
{
struct ipc_bridge *dev = usb_get_intfdata(intf);
struct ctl_pkt *pkt;
unsigned long flags;
ipc_bridge_debugfs_cleanup();
usb_kill_urb(dev->writeurb);
usb_kill_urb(dev->inturb);
usb_kill_urb(dev->readurb);
/*
* The readurb may not be active at the time of
* unlink. Wake up the reader explicitly before
* unregistering the platform device.
*/
wake_up(&dev->read_wait_q);
platform_device_unregister(dev->pdev);
WARN_ON(dev->opened);
spin_lock_irqsave(&dev->lock, flags);
while (!list_empty(&dev->rx_list)) {
pkt = list_first_entry(&dev->rx_list, struct ctl_pkt, list);
list_del(&pkt->list);
kfree(pkt->buf);
kfree(pkt);
}
spin_unlock_irqrestore(&dev->lock, flags);
mutex_destroy(&dev->open_mutex);
mutex_destroy(&dev->read_mutex);
mutex_destroy(&dev->write_mutex);
usb_free_urb(dev->writeurb);
kfree(dev->out_ctlreq);
kfree(dev->readbuf);
usb_free_urb(dev->readurb);
kfree(dev->in_ctlreq);
kfree(dev->intbuf);
usb_free_urb(dev->inturb);
usb_put_dev(dev->udev);
kfree(dev);
__ipc_bridge_dev = NULL;
}
static const struct usb_device_id ipc_bridge_ids[] = {
{ USB_DEVICE_INTERFACE_NUMBER(0x5c6, 0x908A, 7) },
{ USB_DEVICE_INTERFACE_NUMBER(0x5c6, 0x908E, 9) },
{ USB_DEVICE_INTERFACE_NUMBER(0x5c6, 0x909D, 5) },
{ USB_DEVICE_INTERFACE_NUMBER(0x5c6, 0x909E, 7) },
{ USB_DEVICE_INTERFACE_NUMBER(0x5c6, 0x90A0, 7) },
{ USB_DEVICE_INTERFACE_NUMBER(0x5c6, 0x90A4, 9) },
{} /* terminating entry */
};
MODULE_DEVICE_TABLE(usb, ipc_bridge_ids);
static struct usb_driver ipc_bridge_driver = {
.name = "ipc_bridge",
.probe = ipc_bridge_probe,
.disconnect = ipc_bridge_disconnect,
.suspend = ipc_bridge_suspend,
.resume = ipc_bridge_resume,
.reset_resume = ipc_bridge_resume,
.id_table = ipc_bridge_ids,
.supports_autosuspend = 1,
};
module_usb_driver(ipc_bridge_driver);
MODULE_DESCRIPTION("USB IPC bridge driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
emceethemouth/kernel_androidone | arch/arm/mach-imx/clk-imx51-imx53.c | 2002 | 32150 | /*
* Copyright (C) 2011 Sascha Hauer, Pengutronix <s.hauer@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/mm.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/clkdev.h>
#include <linux/of.h>
#include <linux/err.h>
#include "crm-regs-imx5.h"
#include "clk.h"
#include "common.h"
#include "hardware.h"
/* Low-power Audio Playback Mode clock */
static const char *lp_apm_sel[] = { "osc", };
/* This is used multiple times */
static const char *standard_pll_sel[] = { "pll1_sw", "pll2_sw", "pll3_sw", "lp_apm", };
static const char *periph_apm_sel[] = { "pll1_sw", "pll3_sw", "lp_apm", };
static const char *main_bus_sel[] = { "pll2_sw", "periph_apm", };
static const char *per_lp_apm_sel[] = { "main_bus", "lp_apm", };
static const char *per_root_sel[] = { "per_podf", "ipg", };
static const char *esdhc_c_sel[] = { "esdhc_a_podf", "esdhc_b_podf", };
static const char *esdhc_d_sel[] = { "esdhc_a_podf", "esdhc_b_podf", };
static const char *ssi_apm_sels[] = { "ckih1", "lp_amp", "ckih2", };
static const char *ssi_clk_sels[] = { "pll1_sw", "pll2_sw", "pll3_sw", "ssi_apm", };
static const char *ssi3_clk_sels[] = { "ssi1_root_gate", "ssi2_root_gate", };
static const char *ssi_ext1_com_sels[] = { "ssi_ext1_podf", "ssi1_root_gate", };
static const char *ssi_ext2_com_sels[] = { "ssi_ext2_podf", "ssi2_root_gate", };
static const char *emi_slow_sel[] = { "main_bus", "ahb", };
static const char *usb_phy_sel_str[] = { "osc", "usb_phy_podf", };
static const char *mx51_ipu_di0_sel[] = { "di_pred", "osc", "ckih1", "tve_di", };
static const char *mx53_ipu_di0_sel[] = { "di_pred", "osc", "ckih1", "di_pll4_podf", "dummy", "ldb_di0_gate", };
static const char *mx53_ldb_di0_sel[] = { "pll3_sw", "pll4_sw", };
static const char *mx51_ipu_di1_sel[] = { "di_pred", "osc", "ckih1", "tve_di", "ipp_di1", };
static const char *mx53_ipu_di1_sel[] = { "di_pred", "osc", "ckih1", "tve_di", "ipp_di1", "ldb_di1_gate", };
static const char *mx53_ldb_di1_sel[] = { "pll3_sw", "pll4_sw", };
static const char *mx51_tve_ext_sel[] = { "osc", "ckih1", };
static const char *mx53_tve_ext_sel[] = { "pll4_sw", "ckih1", };
static const char *mx51_tve_sel[] = { "tve_pred", "tve_ext_sel", };
static const char *ipu_sel[] = { "axi_a", "axi_b", "emi_slow_gate", "ahb", };
static const char *gpu3d_sel[] = { "axi_a", "axi_b", "emi_slow_gate", "ahb" };
static const char *gpu2d_sel[] = { "axi_a", "axi_b", "emi_slow_gate", "ahb" };
static const char *vpu_sel[] = { "axi_a", "axi_b", "emi_slow_gate", "ahb", };
static const char *mx53_can_sel[] = { "ipg", "ckih1", "ckih2", "lp_apm", };
static const char *mx53_cko1_sel[] = {
"cpu_podf", "pll1_sw", "pll2_sw", "pll3_sw",
"emi_slow_podf", "pll4_sw", "nfc_podf", "dummy",
"di_pred", "dummy", "dummy", "ahb",
"ipg", "per_root", "ckil", "dummy",};
static const char *mx53_cko2_sel[] = {
"dummy"/* dptc_core */, "dummy"/* dptc_perich */,
"dummy", "esdhc_a_podf",
"usboh3_podf", "dummy"/* wrck_clk_root */,
"ecspi_podf", "dummy"/* pll1_ref_clk */,
"esdhc_b_podf", "dummy"/* ddr_clk_root */,
"dummy"/* arm_axi_clk_root */, "dummy"/* usb_phy_out */,
"vpu_sel", "ipu_sel",
"osc", "ckih1",
"dummy", "esdhc_c_sel",
"ssi1_root_podf", "ssi2_root_podf",
"dummy", "dummy",
"dummy"/* lpsr_clk_root */, "dummy"/* pgc_clk_root */,
"dummy"/* tve_out */, "usb_phy_sel",
"tve_sel", "lp_apm",
"uart_root", "dummy"/* spdif0_clk_root */,
"dummy", "dummy", };
enum imx5_clks {
dummy, ckil, osc, ckih1, ckih2, ahb, ipg, axi_a, axi_b, uart_pred,
uart_root, esdhc_a_pred, esdhc_b_pred, esdhc_c_s, esdhc_d_s,
emi_sel, emi_slow_podf, nfc_podf, ecspi_pred, ecspi_podf, usboh3_pred,
usboh3_podf, usb_phy_pred, usb_phy_podf, cpu_podf, di_pred, tve_di_unused,
tve_s, uart1_ipg_gate, uart1_per_gate, uart2_ipg_gate,
uart2_per_gate, uart3_ipg_gate, uart3_per_gate, i2c1_gate, i2c2_gate,
gpt_ipg_gate, pwm1_ipg_gate, pwm1_hf_gate, pwm2_ipg_gate, pwm2_hf_gate,
gpt_hf_gate, fec_gate, usboh3_per_gate, esdhc1_ipg_gate, esdhc2_ipg_gate,
esdhc3_ipg_gate, esdhc4_ipg_gate, ssi1_ipg_gate, ssi2_ipg_gate,
ssi3_ipg_gate, ecspi1_ipg_gate, ecspi1_per_gate, ecspi2_ipg_gate,
ecspi2_per_gate, cspi_ipg_gate, sdma_gate, emi_slow_gate, ipu_s,
ipu_gate, nfc_gate, ipu_di1_gate, vpu_s, vpu_gate,
vpu_reference_gate, uart4_ipg_gate, uart4_per_gate, uart5_ipg_gate,
uart5_per_gate, tve_gate, tve_pred, esdhc1_per_gate, esdhc2_per_gate,
esdhc3_per_gate, esdhc4_per_gate, usb_phy_gate, hsi2c_gate,
mipi_hsc1_gate, mipi_hsc2_gate, mipi_esc_gate, mipi_hsp_gate,
ldb_di1_div_3_5, ldb_di1_div, ldb_di0_div_3_5, ldb_di0_div,
ldb_di1_gate, can2_serial_gate, can2_ipg_gate, i2c3_gate, lp_apm,
periph_apm, main_bus, ahb_max, aips_tz1, aips_tz2, tmax1, tmax2,
tmax3, spba, uart_sel, esdhc_a_sel, esdhc_b_sel, esdhc_a_podf,
esdhc_b_podf, ecspi_sel, usboh3_sel, usb_phy_sel, iim_gate,
usboh3_gate, emi_fast_gate, ipu_di0_gate,gpc_dvfs, pll1_sw, pll2_sw,
pll3_sw, ipu_di0_sel, ipu_di1_sel, tve_ext_sel, mx51_mipi, pll4_sw,
ldb_di1_sel, di_pll4_podf, ldb_di0_sel, ldb_di0_gate, usb_phy1_gate,
usb_phy2_gate, per_lp_apm, per_pred1, per_pred2, per_podf, per_root,
ssi_apm, ssi1_root_sel, ssi2_root_sel, ssi3_root_sel, ssi_ext1_sel,
ssi_ext2_sel, ssi_ext1_com_sel, ssi_ext2_com_sel, ssi1_root_pred,
ssi1_root_podf, ssi2_root_pred, ssi2_root_podf, ssi_ext1_pred,
ssi_ext1_podf, ssi_ext2_pred, ssi_ext2_podf, ssi1_root_gate,
ssi2_root_gate, ssi3_root_gate, ssi_ext1_gate, ssi_ext2_gate,
epit1_ipg_gate, epit1_hf_gate, epit2_ipg_gate, epit2_hf_gate,
can_sel, can1_serial_gate, can1_ipg_gate,
owire_gate, gpu3d_s, gpu2d_s, gpu3d_gate, gpu2d_gate, garb_gate,
cko1_sel, cko1_podf, cko1,
cko2_sel, cko2_podf, cko2,
srtc_gate, pata_gate,
clk_max
};
static struct clk *clk[clk_max];
static struct clk_onecell_data clk_data;
static void __init mx5_clocks_common_init(unsigned long rate_ckil,
unsigned long rate_osc, unsigned long rate_ckih1,
unsigned long rate_ckih2)
{
int i;
clk[dummy] = imx_clk_fixed("dummy", 0);
clk[ckil] = imx_clk_fixed("ckil", rate_ckil);
clk[osc] = imx_clk_fixed("osc", rate_osc);
clk[ckih1] = imx_clk_fixed("ckih1", rate_ckih1);
clk[ckih2] = imx_clk_fixed("ckih2", rate_ckih2);
clk[lp_apm] = imx_clk_mux("lp_apm", MXC_CCM_CCSR, 9, 1,
lp_apm_sel, ARRAY_SIZE(lp_apm_sel));
clk[periph_apm] = imx_clk_mux("periph_apm", MXC_CCM_CBCMR, 12, 2,
periph_apm_sel, ARRAY_SIZE(periph_apm_sel));
clk[main_bus] = imx_clk_mux("main_bus", MXC_CCM_CBCDR, 25, 1,
main_bus_sel, ARRAY_SIZE(main_bus_sel));
clk[per_lp_apm] = imx_clk_mux("per_lp_apm", MXC_CCM_CBCMR, 1, 1,
per_lp_apm_sel, ARRAY_SIZE(per_lp_apm_sel));
clk[per_pred1] = imx_clk_divider("per_pred1", "per_lp_apm", MXC_CCM_CBCDR, 6, 2);
clk[per_pred2] = imx_clk_divider("per_pred2", "per_pred1", MXC_CCM_CBCDR, 3, 3);
clk[per_podf] = imx_clk_divider("per_podf", "per_pred2", MXC_CCM_CBCDR, 0, 3);
clk[per_root] = imx_clk_mux("per_root", MXC_CCM_CBCMR, 0, 1,
per_root_sel, ARRAY_SIZE(per_root_sel));
clk[ahb] = imx_clk_divider("ahb", "main_bus", MXC_CCM_CBCDR, 10, 3);
clk[ahb_max] = imx_clk_gate2("ahb_max", "ahb", MXC_CCM_CCGR0, 28);
clk[aips_tz1] = imx_clk_gate2("aips_tz1", "ahb", MXC_CCM_CCGR0, 24);
clk[aips_tz2] = imx_clk_gate2("aips_tz2", "ahb", MXC_CCM_CCGR0, 26);
clk[tmax1] = imx_clk_gate2("tmax1", "ahb", MXC_CCM_CCGR1, 0);
clk[tmax2] = imx_clk_gate2("tmax2", "ahb", MXC_CCM_CCGR1, 2);
clk[tmax3] = imx_clk_gate2("tmax3", "ahb", MXC_CCM_CCGR1, 4);
clk[spba] = imx_clk_gate2("spba", "ipg", MXC_CCM_CCGR5, 0);
clk[ipg] = imx_clk_divider("ipg", "ahb", MXC_CCM_CBCDR, 8, 2);
clk[axi_a] = imx_clk_divider("axi_a", "main_bus", MXC_CCM_CBCDR, 16, 3);
clk[axi_b] = imx_clk_divider("axi_b", "main_bus", MXC_CCM_CBCDR, 19, 3);
clk[uart_sel] = imx_clk_mux("uart_sel", MXC_CCM_CSCMR1, 24, 2,
standard_pll_sel, ARRAY_SIZE(standard_pll_sel));
clk[uart_pred] = imx_clk_divider("uart_pred", "uart_sel", MXC_CCM_CSCDR1, 3, 3);
clk[uart_root] = imx_clk_divider("uart_root", "uart_pred", MXC_CCM_CSCDR1, 0, 3);
clk[esdhc_a_sel] = imx_clk_mux("esdhc_a_sel", MXC_CCM_CSCMR1, 20, 2,
standard_pll_sel, ARRAY_SIZE(standard_pll_sel));
clk[esdhc_b_sel] = imx_clk_mux("esdhc_b_sel", MXC_CCM_CSCMR1, 16, 2,
standard_pll_sel, ARRAY_SIZE(standard_pll_sel));
clk[esdhc_a_pred] = imx_clk_divider("esdhc_a_pred", "esdhc_a_sel", MXC_CCM_CSCDR1, 16, 3);
clk[esdhc_a_podf] = imx_clk_divider("esdhc_a_podf", "esdhc_a_pred", MXC_CCM_CSCDR1, 11, 3);
clk[esdhc_b_pred] = imx_clk_divider("esdhc_b_pred", "esdhc_b_sel", MXC_CCM_CSCDR1, 22, 3);
clk[esdhc_b_podf] = imx_clk_divider("esdhc_b_podf", "esdhc_b_pred", MXC_CCM_CSCDR1, 19, 3);
clk[esdhc_c_s] = imx_clk_mux("esdhc_c_sel", MXC_CCM_CSCMR1, 19, 1, esdhc_c_sel, ARRAY_SIZE(esdhc_c_sel));
clk[esdhc_d_s] = imx_clk_mux("esdhc_d_sel", MXC_CCM_CSCMR1, 18, 1, esdhc_d_sel, ARRAY_SIZE(esdhc_d_sel));
clk[emi_sel] = imx_clk_mux("emi_sel", MXC_CCM_CBCDR, 26, 1,
emi_slow_sel, ARRAY_SIZE(emi_slow_sel));
clk[emi_slow_podf] = imx_clk_divider("emi_slow_podf", "emi_sel", MXC_CCM_CBCDR, 22, 3);
clk[nfc_podf] = imx_clk_divider("nfc_podf", "emi_slow_podf", MXC_CCM_CBCDR, 13, 3);
clk[ecspi_sel] = imx_clk_mux("ecspi_sel", MXC_CCM_CSCMR1, 4, 2,
standard_pll_sel, ARRAY_SIZE(standard_pll_sel));
clk[ecspi_pred] = imx_clk_divider("ecspi_pred", "ecspi_sel", MXC_CCM_CSCDR2, 25, 3);
clk[ecspi_podf] = imx_clk_divider("ecspi_podf", "ecspi_pred", MXC_CCM_CSCDR2, 19, 6);
clk[usboh3_sel] = imx_clk_mux("usboh3_sel", MXC_CCM_CSCMR1, 22, 2,
standard_pll_sel, ARRAY_SIZE(standard_pll_sel));
clk[usboh3_pred] = imx_clk_divider("usboh3_pred", "usboh3_sel", MXC_CCM_CSCDR1, 8, 3);
clk[usboh3_podf] = imx_clk_divider("usboh3_podf", "usboh3_pred", MXC_CCM_CSCDR1, 6, 2);
clk[usb_phy_pred] = imx_clk_divider("usb_phy_pred", "pll3_sw", MXC_CCM_CDCDR, 3, 3);
clk[usb_phy_podf] = imx_clk_divider("usb_phy_podf", "usb_phy_pred", MXC_CCM_CDCDR, 0, 3);
clk[usb_phy_sel] = imx_clk_mux("usb_phy_sel", MXC_CCM_CSCMR1, 26, 1,
usb_phy_sel_str, ARRAY_SIZE(usb_phy_sel_str));
clk[cpu_podf] = imx_clk_divider("cpu_podf", "pll1_sw", MXC_CCM_CACRR, 0, 3);
clk[di_pred] = imx_clk_divider("di_pred", "pll3_sw", MXC_CCM_CDCDR, 6, 3);
clk[iim_gate] = imx_clk_gate2("iim_gate", "ipg", MXC_CCM_CCGR0, 30);
clk[uart1_ipg_gate] = imx_clk_gate2("uart1_ipg_gate", "ipg", MXC_CCM_CCGR1, 6);
clk[uart1_per_gate] = imx_clk_gate2("uart1_per_gate", "uart_root", MXC_CCM_CCGR1, 8);
clk[uart2_ipg_gate] = imx_clk_gate2("uart2_ipg_gate", "ipg", MXC_CCM_CCGR1, 10);
clk[uart2_per_gate] = imx_clk_gate2("uart2_per_gate", "uart_root", MXC_CCM_CCGR1, 12);
clk[uart3_ipg_gate] = imx_clk_gate2("uart3_ipg_gate", "ipg", MXC_CCM_CCGR1, 14);
clk[uart3_per_gate] = imx_clk_gate2("uart3_per_gate", "uart_root", MXC_CCM_CCGR1, 16);
clk[i2c1_gate] = imx_clk_gate2("i2c1_gate", "per_root", MXC_CCM_CCGR1, 18);
clk[i2c2_gate] = imx_clk_gate2("i2c2_gate", "per_root", MXC_CCM_CCGR1, 20);
clk[pwm1_ipg_gate] = imx_clk_gate2("pwm1_ipg_gate", "ipg", MXC_CCM_CCGR2, 10);
clk[pwm1_hf_gate] = imx_clk_gate2("pwm1_hf_gate", "per_root", MXC_CCM_CCGR2, 12);
clk[pwm2_ipg_gate] = imx_clk_gate2("pwm2_ipg_gate", "ipg", MXC_CCM_CCGR2, 14);
clk[pwm2_hf_gate] = imx_clk_gate2("pwm2_hf_gate", "per_root", MXC_CCM_CCGR2, 16);
clk[gpt_ipg_gate] = imx_clk_gate2("gpt_ipg_gate", "ipg", MXC_CCM_CCGR2, 18);
clk[gpt_hf_gate] = imx_clk_gate2("gpt_hf_gate", "per_root", MXC_CCM_CCGR2, 20);
clk[fec_gate] = imx_clk_gate2("fec_gate", "ipg", MXC_CCM_CCGR2, 24);
clk[usboh3_gate] = imx_clk_gate2("usboh3_gate", "ipg", MXC_CCM_CCGR2, 26);
clk[usboh3_per_gate] = imx_clk_gate2("usboh3_per_gate", "usboh3_podf", MXC_CCM_CCGR2, 28);
clk[esdhc1_ipg_gate] = imx_clk_gate2("esdhc1_ipg_gate", "ipg", MXC_CCM_CCGR3, 0);
clk[esdhc2_ipg_gate] = imx_clk_gate2("esdhc2_ipg_gate", "ipg", MXC_CCM_CCGR3, 4);
clk[esdhc3_ipg_gate] = imx_clk_gate2("esdhc3_ipg_gate", "ipg", MXC_CCM_CCGR3, 8);
clk[esdhc4_ipg_gate] = imx_clk_gate2("esdhc4_ipg_gate", "ipg", MXC_CCM_CCGR3, 12);
clk[ssi1_ipg_gate] = imx_clk_gate2("ssi1_ipg_gate", "ipg", MXC_CCM_CCGR3, 16);
clk[ssi2_ipg_gate] = imx_clk_gate2("ssi2_ipg_gate", "ipg", MXC_CCM_CCGR3, 20);
clk[ssi3_ipg_gate] = imx_clk_gate2("ssi3_ipg_gate", "ipg", MXC_CCM_CCGR3, 24);
clk[ecspi1_ipg_gate] = imx_clk_gate2("ecspi1_ipg_gate", "ipg", MXC_CCM_CCGR4, 18);
clk[ecspi1_per_gate] = imx_clk_gate2("ecspi1_per_gate", "ecspi_podf", MXC_CCM_CCGR4, 20);
clk[ecspi2_ipg_gate] = imx_clk_gate2("ecspi2_ipg_gate", "ipg", MXC_CCM_CCGR4, 22);
clk[ecspi2_per_gate] = imx_clk_gate2("ecspi2_per_gate", "ecspi_podf", MXC_CCM_CCGR4, 24);
clk[cspi_ipg_gate] = imx_clk_gate2("cspi_ipg_gate", "ipg", MXC_CCM_CCGR4, 26);
clk[sdma_gate] = imx_clk_gate2("sdma_gate", "ipg", MXC_CCM_CCGR4, 30);
clk[emi_fast_gate] = imx_clk_gate2("emi_fast_gate", "dummy", MXC_CCM_CCGR5, 14);
clk[emi_slow_gate] = imx_clk_gate2("emi_slow_gate", "emi_slow_podf", MXC_CCM_CCGR5, 16);
clk[ipu_s] = imx_clk_mux("ipu_sel", MXC_CCM_CBCMR, 6, 2, ipu_sel, ARRAY_SIZE(ipu_sel));
clk[ipu_gate] = imx_clk_gate2("ipu_gate", "ipu_sel", MXC_CCM_CCGR5, 10);
clk[nfc_gate] = imx_clk_gate2("nfc_gate", "nfc_podf", MXC_CCM_CCGR5, 20);
clk[ipu_di0_gate] = imx_clk_gate2("ipu_di0_gate", "ipu_di0_sel", MXC_CCM_CCGR6, 10);
clk[ipu_di1_gate] = imx_clk_gate2("ipu_di1_gate", "ipu_di1_sel", MXC_CCM_CCGR6, 12);
clk[gpu3d_s] = imx_clk_mux("gpu3d_sel", MXC_CCM_CBCMR, 4, 2, gpu3d_sel, ARRAY_SIZE(gpu3d_sel));
clk[gpu2d_s] = imx_clk_mux("gpu2d_sel", MXC_CCM_CBCMR, 16, 2, gpu2d_sel, ARRAY_SIZE(gpu2d_sel));
clk[gpu3d_gate] = imx_clk_gate2("gpu3d_gate", "gpu3d_sel", MXC_CCM_CCGR5, 2);
clk[garb_gate] = imx_clk_gate2("garb_gate", "axi_a", MXC_CCM_CCGR5, 4);
clk[gpu2d_gate] = imx_clk_gate2("gpu2d_gate", "gpu2d_sel", MXC_CCM_CCGR6, 14);
clk[vpu_s] = imx_clk_mux("vpu_sel", MXC_CCM_CBCMR, 14, 2, vpu_sel, ARRAY_SIZE(vpu_sel));
clk[vpu_gate] = imx_clk_gate2("vpu_gate", "vpu_sel", MXC_CCM_CCGR5, 6);
clk[vpu_reference_gate] = imx_clk_gate2("vpu_reference_gate", "osc", MXC_CCM_CCGR5, 8);
clk[uart4_ipg_gate] = imx_clk_gate2("uart4_ipg_gate", "ipg", MXC_CCM_CCGR7, 8);
clk[uart4_per_gate] = imx_clk_gate2("uart4_per_gate", "uart_root", MXC_CCM_CCGR7, 10);
clk[uart5_ipg_gate] = imx_clk_gate2("uart5_ipg_gate", "ipg", MXC_CCM_CCGR7, 12);
clk[uart5_per_gate] = imx_clk_gate2("uart5_per_gate", "uart_root", MXC_CCM_CCGR7, 14);
clk[gpc_dvfs] = imx_clk_gate2("gpc_dvfs", "dummy", MXC_CCM_CCGR5, 24);
clk[ssi_apm] = imx_clk_mux("ssi_apm", MXC_CCM_CSCMR1, 8, 2, ssi_apm_sels, ARRAY_SIZE(ssi_apm_sels));
clk[ssi1_root_sel] = imx_clk_mux("ssi1_root_sel", MXC_CCM_CSCMR1, 14, 2, ssi_clk_sels, ARRAY_SIZE(ssi_clk_sels));
clk[ssi2_root_sel] = imx_clk_mux("ssi2_root_sel", MXC_CCM_CSCMR1, 12, 2, ssi_clk_sels, ARRAY_SIZE(ssi_clk_sels));
clk[ssi3_root_sel] = imx_clk_mux("ssi3_root_sel", MXC_CCM_CSCMR1, 11, 1, ssi3_clk_sels, ARRAY_SIZE(ssi3_clk_sels));
clk[ssi_ext1_sel] = imx_clk_mux("ssi_ext1_sel", MXC_CCM_CSCMR1, 28, 2, ssi_clk_sels, ARRAY_SIZE(ssi_clk_sels));
clk[ssi_ext2_sel] = imx_clk_mux("ssi_ext2_sel", MXC_CCM_CSCMR1, 30, 2, ssi_clk_sels, ARRAY_SIZE(ssi_clk_sels));
clk[ssi_ext1_com_sel] = imx_clk_mux("ssi_ext1_com_sel", MXC_CCM_CSCMR1, 0, 1, ssi_ext1_com_sels, ARRAY_SIZE(ssi_ext1_com_sels));
clk[ssi_ext2_com_sel] = imx_clk_mux("ssi_ext2_com_sel", MXC_CCM_CSCMR1, 1, 1, ssi_ext2_com_sels, ARRAY_SIZE(ssi_ext2_com_sels));
clk[ssi1_root_pred] = imx_clk_divider("ssi1_root_pred", "ssi1_root_sel", MXC_CCM_CS1CDR, 6, 3);
clk[ssi1_root_podf] = imx_clk_divider("ssi1_root_podf", "ssi1_root_pred", MXC_CCM_CS1CDR, 0, 6);
clk[ssi2_root_pred] = imx_clk_divider("ssi2_root_pred", "ssi2_root_sel", MXC_CCM_CS2CDR, 6, 3);
clk[ssi2_root_podf] = imx_clk_divider("ssi2_root_podf", "ssi2_root_pred", MXC_CCM_CS2CDR, 0, 6);
clk[ssi_ext1_pred] = imx_clk_divider("ssi_ext1_pred", "ssi_ext1_sel", MXC_CCM_CS1CDR, 22, 3);
clk[ssi_ext1_podf] = imx_clk_divider("ssi_ext1_podf", "ssi_ext1_pred", MXC_CCM_CS1CDR, 16, 6);
clk[ssi_ext2_pred] = imx_clk_divider("ssi_ext2_pred", "ssi_ext2_sel", MXC_CCM_CS2CDR, 22, 3);
clk[ssi_ext2_podf] = imx_clk_divider("ssi_ext2_podf", "ssi_ext2_pred", MXC_CCM_CS2CDR, 16, 6);
clk[ssi1_root_gate] = imx_clk_gate2("ssi1_root_gate", "ssi1_root_podf", MXC_CCM_CCGR3, 18);
clk[ssi2_root_gate] = imx_clk_gate2("ssi2_root_gate", "ssi2_root_podf", MXC_CCM_CCGR3, 22);
clk[ssi3_root_gate] = imx_clk_gate2("ssi3_root_gate", "ssi3_root_sel", MXC_CCM_CCGR3, 26);
clk[ssi_ext1_gate] = imx_clk_gate2("ssi_ext1_gate", "ssi_ext1_com_sel", MXC_CCM_CCGR3, 28);
clk[ssi_ext2_gate] = imx_clk_gate2("ssi_ext2_gate", "ssi_ext2_com_sel", MXC_CCM_CCGR3, 30);
clk[epit1_ipg_gate] = imx_clk_gate2("epit1_ipg_gate", "ipg", MXC_CCM_CCGR2, 2);
clk[epit1_hf_gate] = imx_clk_gate2("epit1_hf_gate", "per_root", MXC_CCM_CCGR2, 4);
clk[epit2_ipg_gate] = imx_clk_gate2("epit2_ipg_gate", "ipg", MXC_CCM_CCGR2, 6);
clk[epit2_hf_gate] = imx_clk_gate2("epit2_hf_gate", "per_root", MXC_CCM_CCGR2, 8);
clk[owire_gate] = imx_clk_gate2("owire_gate", "per_root", MXC_CCM_CCGR2, 22);
clk[srtc_gate] = imx_clk_gate2("srtc_gate", "per_root", MXC_CCM_CCGR4, 28);
clk[pata_gate] = imx_clk_gate2("pata_gate", "ipg", MXC_CCM_CCGR4, 0);
for (i = 0; i < ARRAY_SIZE(clk); i++)
if (IS_ERR(clk[i]))
pr_err("i.MX5 clk %d: register failed with %ld\n",
i, PTR_ERR(clk[i]));
clk_register_clkdev(clk[gpt_hf_gate], "per", "imx-gpt.0");
clk_register_clkdev(clk[gpt_ipg_gate], "ipg", "imx-gpt.0");
clk_register_clkdev(clk[uart1_per_gate], "per", "imx21-uart.0");
clk_register_clkdev(clk[uart1_ipg_gate], "ipg", "imx21-uart.0");
clk_register_clkdev(clk[uart2_per_gate], "per", "imx21-uart.1");
clk_register_clkdev(clk[uart2_ipg_gate], "ipg", "imx21-uart.1");
clk_register_clkdev(clk[uart3_per_gate], "per", "imx21-uart.2");
clk_register_clkdev(clk[uart3_ipg_gate], "ipg", "imx21-uart.2");
clk_register_clkdev(clk[uart4_per_gate], "per", "imx21-uart.3");
clk_register_clkdev(clk[uart4_ipg_gate], "ipg", "imx21-uart.3");
clk_register_clkdev(clk[uart5_per_gate], "per", "imx21-uart.4");
clk_register_clkdev(clk[uart5_ipg_gate], "ipg", "imx21-uart.4");
clk_register_clkdev(clk[ecspi1_per_gate], "per", "imx51-ecspi.0");
clk_register_clkdev(clk[ecspi1_ipg_gate], "ipg", "imx51-ecspi.0");
clk_register_clkdev(clk[ecspi2_per_gate], "per", "imx51-ecspi.1");
clk_register_clkdev(clk[ecspi2_ipg_gate], "ipg", "imx51-ecspi.1");
clk_register_clkdev(clk[cspi_ipg_gate], NULL, "imx35-cspi.2");
clk_register_clkdev(clk[pwm1_ipg_gate], "pwm", "mxc_pwm.0");
clk_register_clkdev(clk[pwm2_ipg_gate], "pwm", "mxc_pwm.1");
clk_register_clkdev(clk[i2c1_gate], NULL, "imx21-i2c.0");
clk_register_clkdev(clk[i2c2_gate], NULL, "imx21-i2c.1");
clk_register_clkdev(clk[usboh3_per_gate], "per", "mxc-ehci.0");
clk_register_clkdev(clk[usboh3_gate], "ipg", "mxc-ehci.0");
clk_register_clkdev(clk[usboh3_gate], "ahb", "mxc-ehci.0");
clk_register_clkdev(clk[usboh3_per_gate], "per", "mxc-ehci.1");
clk_register_clkdev(clk[usboh3_gate], "ipg", "mxc-ehci.1");
clk_register_clkdev(clk[usboh3_gate], "ahb", "mxc-ehci.1");
clk_register_clkdev(clk[usboh3_per_gate], "per", "mxc-ehci.2");
clk_register_clkdev(clk[usboh3_gate], "ipg", "mxc-ehci.2");
clk_register_clkdev(clk[usboh3_gate], "ahb", "mxc-ehci.2");
clk_register_clkdev(clk[usboh3_per_gate], "per", "imx-udc-mx51");
clk_register_clkdev(clk[usboh3_gate], "ipg", "imx-udc-mx51");
clk_register_clkdev(clk[usboh3_gate], "ahb", "imx-udc-mx51");
clk_register_clkdev(clk[nfc_gate], NULL, "imx51-nand");
clk_register_clkdev(clk[ssi1_ipg_gate], NULL, "imx-ssi.0");
clk_register_clkdev(clk[ssi2_ipg_gate], NULL, "imx-ssi.1");
clk_register_clkdev(clk[ssi3_ipg_gate], NULL, "imx-ssi.2");
clk_register_clkdev(clk[ssi_ext1_gate], "ssi_ext1", NULL);
clk_register_clkdev(clk[ssi_ext2_gate], "ssi_ext2", NULL);
clk_register_clkdev(clk[sdma_gate], NULL, "imx35-sdma");
clk_register_clkdev(clk[cpu_podf], NULL, "cpufreq-cpu0.0");
clk_register_clkdev(clk[iim_gate], "iim", NULL);
clk_register_clkdev(clk[dummy], NULL, "imx2-wdt.0");
clk_register_clkdev(clk[dummy], NULL, "imx2-wdt.1");
clk_register_clkdev(clk[dummy], NULL, "imx-keypad");
clk_register_clkdev(clk[ipu_di1_gate], "di1", "imx-tve.0");
clk_register_clkdev(clk[gpc_dvfs], "gpc_dvfs", NULL);
clk_register_clkdev(clk[epit1_ipg_gate], "ipg", "imx-epit.0");
clk_register_clkdev(clk[epit1_hf_gate], "per", "imx-epit.0");
clk_register_clkdev(clk[epit2_ipg_gate], "ipg", "imx-epit.1");
clk_register_clkdev(clk[epit2_hf_gate], "per", "imx-epit.1");
/* Set SDHC parents to be PLL2 */
clk_set_parent(clk[esdhc_a_sel], clk[pll2_sw]);
clk_set_parent(clk[esdhc_b_sel], clk[pll2_sw]);
/* move usb phy clk to 24MHz */
clk_set_parent(clk[usb_phy_sel], clk[osc]);
clk_prepare_enable(clk[gpc_dvfs]);
clk_prepare_enable(clk[ahb_max]); /* esdhc3 */
clk_prepare_enable(clk[aips_tz1]);
clk_prepare_enable(clk[aips_tz2]); /* fec */
clk_prepare_enable(clk[spba]);
clk_prepare_enable(clk[emi_fast_gate]); /* fec */
clk_prepare_enable(clk[emi_slow_gate]); /* eim */
clk_prepare_enable(clk[mipi_hsc1_gate]);
clk_prepare_enable(clk[mipi_hsc2_gate]);
clk_prepare_enable(clk[mipi_esc_gate]);
clk_prepare_enable(clk[mipi_hsp_gate]);
clk_prepare_enable(clk[tmax1]);
clk_prepare_enable(clk[tmax2]); /* esdhc2, fec */
clk_prepare_enable(clk[tmax3]); /* esdhc1, esdhc4 */
}
int __init mx51_clocks_init(unsigned long rate_ckil, unsigned long rate_osc,
unsigned long rate_ckih1, unsigned long rate_ckih2)
{
int i;
u32 val;
struct device_node *np;
clk[pll1_sw] = imx_clk_pllv2("pll1_sw", "osc", MX51_DPLL1_BASE);
clk[pll2_sw] = imx_clk_pllv2("pll2_sw", "osc", MX51_DPLL2_BASE);
clk[pll3_sw] = imx_clk_pllv2("pll3_sw", "osc", MX51_DPLL3_BASE);
clk[ipu_di0_sel] = imx_clk_mux("ipu_di0_sel", MXC_CCM_CSCMR2, 26, 3,
mx51_ipu_di0_sel, ARRAY_SIZE(mx51_ipu_di0_sel));
clk[ipu_di1_sel] = imx_clk_mux("ipu_di1_sel", MXC_CCM_CSCMR2, 29, 3,
mx51_ipu_di1_sel, ARRAY_SIZE(mx51_ipu_di1_sel));
clk[tve_ext_sel] = imx_clk_mux_flags("tve_ext_sel", MXC_CCM_CSCMR1, 6, 1,
mx51_tve_ext_sel, ARRAY_SIZE(mx51_tve_ext_sel), CLK_SET_RATE_PARENT);
clk[tve_s] = imx_clk_mux("tve_sel", MXC_CCM_CSCMR1, 7, 1,
mx51_tve_sel, ARRAY_SIZE(mx51_tve_sel));
clk[tve_gate] = imx_clk_gate2("tve_gate", "tve_sel", MXC_CCM_CCGR2, 30);
clk[tve_pred] = imx_clk_divider("tve_pred", "pll3_sw", MXC_CCM_CDCDR, 28, 3);
clk[esdhc1_per_gate] = imx_clk_gate2("esdhc1_per_gate", "esdhc_a_podf", MXC_CCM_CCGR3, 2);
clk[esdhc2_per_gate] = imx_clk_gate2("esdhc2_per_gate", "esdhc_b_podf", MXC_CCM_CCGR3, 6);
clk[esdhc3_per_gate] = imx_clk_gate2("esdhc3_per_gate", "esdhc_c_sel", MXC_CCM_CCGR3, 10);
clk[esdhc4_per_gate] = imx_clk_gate2("esdhc4_per_gate", "esdhc_d_sel", MXC_CCM_CCGR3, 14);
clk[usb_phy_gate] = imx_clk_gate2("usb_phy_gate", "usb_phy_sel", MXC_CCM_CCGR2, 0);
clk[hsi2c_gate] = imx_clk_gate2("hsi2c_gate", "ipg", MXC_CCM_CCGR1, 22);
clk[mipi_hsc1_gate] = imx_clk_gate2("mipi_hsc1_gate", "ipg", MXC_CCM_CCGR4, 6);
clk[mipi_hsc2_gate] = imx_clk_gate2("mipi_hsc2_gate", "ipg", MXC_CCM_CCGR4, 8);
clk[mipi_esc_gate] = imx_clk_gate2("mipi_esc_gate", "ipg", MXC_CCM_CCGR4, 10);
clk[mipi_hsp_gate] = imx_clk_gate2("mipi_hsp_gate", "ipg", MXC_CCM_CCGR4, 12);
for (i = 0; i < ARRAY_SIZE(clk); i++)
if (IS_ERR(clk[i]))
pr_err("i.MX51 clk %d: register failed with %ld\n",
i, PTR_ERR(clk[i]));
np = of_find_compatible_node(NULL, NULL, "fsl,imx51-ccm");
clk_data.clks = clk;
clk_data.clk_num = ARRAY_SIZE(clk);
of_clk_add_provider(np, of_clk_src_onecell_get, &clk_data);
mx5_clocks_common_init(rate_ckil, rate_osc, rate_ckih1, rate_ckih2);
clk_register_clkdev(clk[hsi2c_gate], NULL, "imx21-i2c.2");
clk_register_clkdev(clk[mx51_mipi], "mipi_hsp", NULL);
clk_register_clkdev(clk[vpu_gate], NULL, "imx51-vpu.0");
clk_register_clkdev(clk[fec_gate], NULL, "imx27-fec.0");
clk_register_clkdev(clk[usb_phy_gate], "phy", "mxc-ehci.0");
clk_register_clkdev(clk[esdhc1_ipg_gate], "ipg", "sdhci-esdhc-imx51.0");
clk_register_clkdev(clk[dummy], "ahb", "sdhci-esdhc-imx51.0");
clk_register_clkdev(clk[esdhc1_per_gate], "per", "sdhci-esdhc-imx51.0");
clk_register_clkdev(clk[esdhc2_ipg_gate], "ipg", "sdhci-esdhc-imx51.1");
clk_register_clkdev(clk[dummy], "ahb", "sdhci-esdhc-imx51.1");
clk_register_clkdev(clk[esdhc2_per_gate], "per", "sdhci-esdhc-imx51.1");
clk_register_clkdev(clk[esdhc3_ipg_gate], "ipg", "sdhci-esdhc-imx51.2");
clk_register_clkdev(clk[dummy], "ahb", "sdhci-esdhc-imx51.2");
clk_register_clkdev(clk[esdhc3_per_gate], "per", "sdhci-esdhc-imx51.2");
clk_register_clkdev(clk[esdhc4_ipg_gate], "ipg", "sdhci-esdhc-imx51.3");
clk_register_clkdev(clk[dummy], "ahb", "sdhci-esdhc-imx51.3");
clk_register_clkdev(clk[esdhc4_per_gate], "per", "sdhci-esdhc-imx51.3");
/* set the usboh3 parent to pll2_sw */
clk_set_parent(clk[usboh3_sel], clk[pll2_sw]);
/* set SDHC root clock to 166.25MHZ*/
clk_set_rate(clk[esdhc_a_podf], 166250000);
clk_set_rate(clk[esdhc_b_podf], 166250000);
/* System timer */
mxc_timer_init(MX51_IO_ADDRESS(MX51_GPT1_BASE_ADDR), MX51_INT_GPT);
clk_prepare_enable(clk[iim_gate]);
imx_print_silicon_rev("i.MX51", mx51_revision());
clk_disable_unprepare(clk[iim_gate]);
/*
* Reference Manual says: Functionality of CCDR[18] and CLPCR[23] is no
* longer supported. Set to one for better power saving.
*
* The effect of not setting these bits is that MIPI clocks can't be
* enabled without the IPU clock being enabled aswell.
*/
val = readl(MXC_CCM_CCDR);
val |= 1 << 18;
writel(val, MXC_CCM_CCDR);
val = readl(MXC_CCM_CLPCR);
val |= 1 << 23;
writel(val, MXC_CCM_CLPCR);
return 0;
}
int __init mx53_clocks_init(unsigned long rate_ckil, unsigned long rate_osc,
unsigned long rate_ckih1, unsigned long rate_ckih2)
{
int i;
unsigned long r;
struct device_node *np;
clk[pll1_sw] = imx_clk_pllv2("pll1_sw", "osc", MX53_DPLL1_BASE);
clk[pll2_sw] = imx_clk_pllv2("pll2_sw", "osc", MX53_DPLL2_BASE);
clk[pll3_sw] = imx_clk_pllv2("pll3_sw", "osc", MX53_DPLL3_BASE);
clk[pll4_sw] = imx_clk_pllv2("pll4_sw", "osc", MX53_DPLL4_BASE);
clk[ldb_di1_div_3_5] = imx_clk_fixed_factor("ldb_di1_div_3_5", "ldb_di1_sel", 2, 7);
clk[ldb_di1_div] = imx_clk_divider_flags("ldb_di1_div", "ldb_di1_div_3_5", MXC_CCM_CSCMR2, 11, 1, 0);
clk[ldb_di1_sel] = imx_clk_mux_flags("ldb_di1_sel", MXC_CCM_CSCMR2, 9, 1,
mx53_ldb_di1_sel, ARRAY_SIZE(mx53_ldb_di1_sel), CLK_SET_RATE_PARENT);
clk[di_pll4_podf] = imx_clk_divider("di_pll4_podf", "pll4_sw", MXC_CCM_CDCDR, 16, 3);
clk[ldb_di0_div_3_5] = imx_clk_fixed_factor("ldb_di0_div_3_5", "ldb_di0_sel", 2, 7);
clk[ldb_di0_div] = imx_clk_divider_flags("ldb_di0_div", "ldb_di0_div_3_5", MXC_CCM_CSCMR2, 10, 1, 0);
clk[ldb_di0_sel] = imx_clk_mux_flags("ldb_di0_sel", MXC_CCM_CSCMR2, 8, 1,
mx53_ldb_di0_sel, ARRAY_SIZE(mx53_ldb_di0_sel), CLK_SET_RATE_PARENT);
clk[ldb_di0_gate] = imx_clk_gate2("ldb_di0_gate", "ldb_di0_div", MXC_CCM_CCGR6, 28);
clk[ldb_di1_gate] = imx_clk_gate2("ldb_di1_gate", "ldb_di1_div", MXC_CCM_CCGR6, 30);
clk[ipu_di0_sel] = imx_clk_mux("ipu_di0_sel", MXC_CCM_CSCMR2, 26, 3,
mx53_ipu_di0_sel, ARRAY_SIZE(mx53_ipu_di0_sel));
clk[ipu_di1_sel] = imx_clk_mux("ipu_di1_sel", MXC_CCM_CSCMR2, 29, 3,
mx53_ipu_di1_sel, ARRAY_SIZE(mx53_ipu_di1_sel));
clk[tve_ext_sel] = imx_clk_mux_flags("tve_ext_sel", MXC_CCM_CSCMR1, 6, 1,
mx53_tve_ext_sel, ARRAY_SIZE(mx53_tve_ext_sel), CLK_SET_RATE_PARENT);
clk[tve_gate] = imx_clk_gate2("tve_gate", "tve_pred", MXC_CCM_CCGR2, 30);
clk[tve_pred] = imx_clk_divider("tve_pred", "tve_ext_sel", MXC_CCM_CDCDR, 28, 3);
clk[esdhc1_per_gate] = imx_clk_gate2("esdhc1_per_gate", "esdhc_a_podf", MXC_CCM_CCGR3, 2);
clk[esdhc2_per_gate] = imx_clk_gate2("esdhc2_per_gate", "esdhc_c_sel", MXC_CCM_CCGR3, 6);
clk[esdhc3_per_gate] = imx_clk_gate2("esdhc3_per_gate", "esdhc_b_podf", MXC_CCM_CCGR3, 10);
clk[esdhc4_per_gate] = imx_clk_gate2("esdhc4_per_gate", "esdhc_d_sel", MXC_CCM_CCGR3, 14);
clk[usb_phy1_gate] = imx_clk_gate2("usb_phy1_gate", "usb_phy_sel", MXC_CCM_CCGR4, 10);
clk[usb_phy2_gate] = imx_clk_gate2("usb_phy2_gate", "usb_phy_sel", MXC_CCM_CCGR4, 12);
clk[can_sel] = imx_clk_mux("can_sel", MXC_CCM_CSCMR2, 6, 2,
mx53_can_sel, ARRAY_SIZE(mx53_can_sel));
clk[can1_serial_gate] = imx_clk_gate2("can1_serial_gate", "can_sel", MXC_CCM_CCGR6, 22);
clk[can1_ipg_gate] = imx_clk_gate2("can1_ipg_gate", "ipg", MXC_CCM_CCGR6, 20);
clk[can2_serial_gate] = imx_clk_gate2("can2_serial_gate", "can_sel", MXC_CCM_CCGR4, 8);
clk[can2_ipg_gate] = imx_clk_gate2("can2_ipg_gate", "ipg", MXC_CCM_CCGR4, 6);
clk[i2c3_gate] = imx_clk_gate2("i2c3_gate", "per_root", MXC_CCM_CCGR1, 22);
clk[cko1_sel] = imx_clk_mux("cko1_sel", MXC_CCM_CCOSR, 0, 4,
mx53_cko1_sel, ARRAY_SIZE(mx53_cko1_sel));
clk[cko1_podf] = imx_clk_divider("cko1_podf", "cko1_sel", MXC_CCM_CCOSR, 4, 3);
clk[cko1] = imx_clk_gate2("cko1", "cko1_podf", MXC_CCM_CCOSR, 7);
clk[cko2_sel] = imx_clk_mux("cko2_sel", MXC_CCM_CCOSR, 16, 5,
mx53_cko2_sel, ARRAY_SIZE(mx53_cko2_sel));
clk[cko2_podf] = imx_clk_divider("cko2_podf", "cko2_sel", MXC_CCM_CCOSR, 21, 3);
clk[cko2] = imx_clk_gate2("cko2", "cko2_podf", MXC_CCM_CCOSR, 24);
for (i = 0; i < ARRAY_SIZE(clk); i++)
if (IS_ERR(clk[i]))
pr_err("i.MX53 clk %d: register failed with %ld\n",
i, PTR_ERR(clk[i]));
np = of_find_compatible_node(NULL, NULL, "fsl,imx53-ccm");
clk_data.clks = clk;
clk_data.clk_num = ARRAY_SIZE(clk);
of_clk_add_provider(np, of_clk_src_onecell_get, &clk_data);
mx5_clocks_common_init(rate_ckil, rate_osc, rate_ckih1, rate_ckih2);
clk_register_clkdev(clk[vpu_gate], NULL, "imx53-vpu.0");
clk_register_clkdev(clk[i2c3_gate], NULL, "imx21-i2c.2");
clk_register_clkdev(clk[fec_gate], NULL, "imx25-fec.0");
clk_register_clkdev(clk[usb_phy1_gate], "usb_phy1", "mxc-ehci.0");
clk_register_clkdev(clk[esdhc1_ipg_gate], "ipg", "sdhci-esdhc-imx53.0");
clk_register_clkdev(clk[dummy], "ahb", "sdhci-esdhc-imx53.0");
clk_register_clkdev(clk[esdhc1_per_gate], "per", "sdhci-esdhc-imx53.0");
clk_register_clkdev(clk[esdhc2_ipg_gate], "ipg", "sdhci-esdhc-imx53.1");
clk_register_clkdev(clk[dummy], "ahb", "sdhci-esdhc-imx53.1");
clk_register_clkdev(clk[esdhc2_per_gate], "per", "sdhci-esdhc-imx53.1");
clk_register_clkdev(clk[esdhc3_ipg_gate], "ipg", "sdhci-esdhc-imx53.2");
clk_register_clkdev(clk[dummy], "ahb", "sdhci-esdhc-imx53.2");
clk_register_clkdev(clk[esdhc3_per_gate], "per", "sdhci-esdhc-imx53.2");
clk_register_clkdev(clk[esdhc4_ipg_gate], "ipg", "sdhci-esdhc-imx53.3");
clk_register_clkdev(clk[dummy], "ahb", "sdhci-esdhc-imx53.3");
clk_register_clkdev(clk[esdhc4_per_gate], "per", "sdhci-esdhc-imx53.3");
/* set SDHC root clock to 200MHZ*/
clk_set_rate(clk[esdhc_a_podf], 200000000);
clk_set_rate(clk[esdhc_b_podf], 200000000);
/* System timer */
mxc_timer_init(MX53_IO_ADDRESS(MX53_GPT1_BASE_ADDR), MX53_INT_GPT);
clk_prepare_enable(clk[iim_gate]);
imx_print_silicon_rev("i.MX53", mx53_revision());
clk_disable_unprepare(clk[iim_gate]);
r = clk_round_rate(clk[usboh3_per_gate], 54000000);
clk_set_rate(clk[usboh3_per_gate], r);
return 0;
}
#ifdef CONFIG_OF
static void __init clk_get_freq_dt(unsigned long *ckil, unsigned long *osc,
unsigned long *ckih1, unsigned long *ckih2)
{
struct device_node *np;
/* retrieve the freqency of fixed clocks from device tree */
for_each_compatible_node(np, NULL, "fixed-clock") {
u32 rate;
if (of_property_read_u32(np, "clock-frequency", &rate))
continue;
if (of_device_is_compatible(np, "fsl,imx-ckil"))
*ckil = rate;
else if (of_device_is_compatible(np, "fsl,imx-osc"))
*osc = rate;
else if (of_device_is_compatible(np, "fsl,imx-ckih1"))
*ckih1 = rate;
else if (of_device_is_compatible(np, "fsl,imx-ckih2"))
*ckih2 = rate;
}
}
int __init mx51_clocks_init_dt(void)
{
unsigned long ckil, osc, ckih1, ckih2;
clk_get_freq_dt(&ckil, &osc, &ckih1, &ckih2);
return mx51_clocks_init(ckil, osc, ckih1, ckih2);
}
int __init mx53_clocks_init_dt(void)
{
unsigned long ckil, osc, ckih1, ckih2;
clk_get_freq_dt(&ckil, &osc, &ckih1, &ckih2);
return mx53_clocks_init(ckil, osc, ckih1, ckih2);
}
#endif
| gpl-2.0 |
TeamWin/android_kernel_samsung_crespo | arch/arm/mach-exynos4/hotplug.c | 2002 | 2639 | /* linux arch/arm/mach-exynos4/hotplug.c
*
* Cloned from linux/arch/arm/mach-realview/hotplug.c
*
* Copyright (C) 2002 ARM Ltd.
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/smp.h>
#include <asm/cacheflush.h>
extern volatile int pen_release;
static inline void cpu_enter_lowpower(void)
{
unsigned int v;
flush_cache_all();
asm volatile(
" mcr p15, 0, %1, c7, c5, 0\n"
" mcr p15, 0, %1, c7, c10, 4\n"
/*
* Turn off coherency
*/
" mrc p15, 0, %0, c1, c0, 1\n"
" bic %0, %0, %3\n"
" mcr p15, 0, %0, c1, c0, 1\n"
" mrc p15, 0, %0, c1, c0, 0\n"
" bic %0, %0, %2\n"
" mcr p15, 0, %0, c1, c0, 0\n"
: "=&r" (v)
: "r" (0), "Ir" (CR_C), "Ir" (0x40)
: "cc");
}
static inline void cpu_leave_lowpower(void)
{
unsigned int v;
asm volatile(
"mrc p15, 0, %0, c1, c0, 0\n"
" orr %0, %0, %1\n"
" mcr p15, 0, %0, c1, c0, 0\n"
" mrc p15, 0, %0, c1, c0, 1\n"
" orr %0, %0, %2\n"
" mcr p15, 0, %0, c1, c0, 1\n"
: "=&r" (v)
: "Ir" (CR_C), "Ir" (0x40)
: "cc");
}
static inline void platform_do_lowpower(unsigned int cpu, int *spurious)
{
/*
* there is no power-control hardware on this platform, so all
* we can do is put the core into WFI; this is safe as the calling
* code will have already disabled interrupts
*/
for (;;) {
/*
* here's the WFI
*/
asm(".word 0xe320f003\n"
:
:
: "memory", "cc");
if (pen_release == cpu) {
/*
* OK, proper wakeup, we're done
*/
break;
}
/*
* Getting here, means that we have come out of WFI without
* having been woken up - this shouldn't happen
*
* Just note it happening - when we're woken, we can report
* its occurrence.
*/
(*spurious)++;
}
}
int platform_cpu_kill(unsigned int cpu)
{
return 1;
}
/*
* platform-specific code to shutdown a CPU
*
* Called with IRQs disabled
*/
void platform_cpu_die(unsigned int cpu)
{
int spurious = 0;
/*
* we're ready for shutdown now, so do it
*/
cpu_enter_lowpower();
platform_do_lowpower(cpu, &spurious);
/*
* bring this CPU back into the world of cache
* coherency, and then restore interrupts
*/
cpu_leave_lowpower();
if (spurious)
pr_warn("CPU%u: %u spurious wakeup calls\n", cpu, spurious);
}
int platform_cpu_disable(unsigned int cpu)
{
/*
* we don't allow CPU 0 to be shutdown (it is still too special
* e.g. clock tick interrupts)
*/
return cpu == 0 ? -EPERM : 0;
}
| gpl-2.0 |
1N4148/SAMSUNG_OSRC_DUMPS | drivers/net/wireless/libertas/main.c | 2258 | 29097 | /*
* This file contains the major functions in WLAN
* driver. It includes init, exit, open, close and main
* thread etc..
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/moduleparam.h>
#include <linux/delay.h>
#include <linux/etherdevice.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/kthread.h>
#include <linux/kfifo.h>
#include <linux/slab.h>
#include <net/cfg80211.h>
#include "host.h"
#include "decl.h"
#include "dev.h"
#include "cfg.h"
#include "debugfs.h"
#include "cmd.h"
#define DRIVER_RELEASE_VERSION "323.p0"
const char lbs_driver_version[] = "COMM-USB8388-" DRIVER_RELEASE_VERSION
#ifdef DEBUG
"-dbg"
#endif
"";
/* Module parameters */
unsigned int lbs_debug;
EXPORT_SYMBOL_GPL(lbs_debug);
module_param_named(libertas_debug, lbs_debug, int, 0644);
unsigned int lbs_disablemesh;
EXPORT_SYMBOL_GPL(lbs_disablemesh);
module_param_named(libertas_disablemesh, lbs_disablemesh, int, 0644);
/*
* This global structure is used to send the confirm_sleep command as
* fast as possible down to the firmware.
*/
struct cmd_confirm_sleep confirm_sleep;
/*
* the table to keep region code
*/
u16 lbs_region_code_to_index[MRVDRV_MAX_REGION_CODE] =
{ 0x10, 0x20, 0x30, 0x31, 0x32, 0x40 };
/*
* FW rate table. FW refers to rates by their index in this table, not by the
* rate value itself. Values of 0x00 are
* reserved positions.
*/
static u8 fw_data_rates[MAX_RATES] =
{ 0x02, 0x04, 0x0B, 0x16, 0x00, 0x0C, 0x12,
0x18, 0x24, 0x30, 0x48, 0x60, 0x6C, 0x00
};
/**
* lbs_fw_index_to_data_rate - use index to get the data rate
*
* @idx: The index of data rate
* returns: data rate or 0
*/
u32 lbs_fw_index_to_data_rate(u8 idx)
{
if (idx >= sizeof(fw_data_rates))
idx = 0;
return fw_data_rates[idx];
}
/**
* lbs_data_rate_to_fw_index - use rate to get the index
*
* @rate: data rate
* returns: index or 0
*/
u8 lbs_data_rate_to_fw_index(u32 rate)
{
u8 i;
if (!rate)
return 0;
for (i = 0; i < sizeof(fw_data_rates); i++) {
if (rate == fw_data_rates[i])
return i;
}
return 0;
}
/**
* lbs_dev_open - open the ethX interface
*
* @dev: A pointer to &net_device structure
* returns: 0 or -EBUSY if monitor mode active
*/
static int lbs_dev_open(struct net_device *dev)
{
struct lbs_private *priv = dev->ml_priv;
int ret = 0;
lbs_deb_enter(LBS_DEB_NET);
spin_lock_irq(&priv->driver_lock);
priv->stopping = false;
if (priv->connect_status == LBS_CONNECTED)
netif_carrier_on(dev);
else
netif_carrier_off(dev);
if (!priv->tx_pending_len)
netif_wake_queue(dev);
spin_unlock_irq(&priv->driver_lock);
lbs_deb_leave_args(LBS_DEB_NET, "ret %d", ret);
return ret;
}
/**
* lbs_eth_stop - close the ethX interface
*
* @dev: A pointer to &net_device structure
* returns: 0
*/
static int lbs_eth_stop(struct net_device *dev)
{
struct lbs_private *priv = dev->ml_priv;
lbs_deb_enter(LBS_DEB_NET);
spin_lock_irq(&priv->driver_lock);
priv->stopping = true;
netif_stop_queue(dev);
spin_unlock_irq(&priv->driver_lock);
schedule_work(&priv->mcast_work);
cancel_delayed_work_sync(&priv->scan_work);
if (priv->scan_req) {
cfg80211_scan_done(priv->scan_req, false);
priv->scan_req = NULL;
}
lbs_deb_leave(LBS_DEB_NET);
return 0;
}
void lbs_host_to_card_done(struct lbs_private *priv)
{
unsigned long flags;
lbs_deb_enter(LBS_DEB_THREAD);
spin_lock_irqsave(&priv->driver_lock, flags);
priv->dnld_sent = DNLD_RES_RECEIVED;
/* Wake main thread if commands are pending */
if (!priv->cur_cmd || priv->tx_pending_len > 0) {
if (!priv->wakeup_dev_required)
wake_up_interruptible(&priv->waitq);
}
spin_unlock_irqrestore(&priv->driver_lock, flags);
lbs_deb_leave(LBS_DEB_THREAD);
}
EXPORT_SYMBOL_GPL(lbs_host_to_card_done);
int lbs_set_mac_address(struct net_device *dev, void *addr)
{
int ret = 0;
struct lbs_private *priv = dev->ml_priv;
struct sockaddr *phwaddr = addr;
struct cmd_ds_802_11_mac_address cmd;
lbs_deb_enter(LBS_DEB_NET);
/* In case it was called from the mesh device */
dev = priv->dev;
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.action = cpu_to_le16(CMD_ACT_SET);
memcpy(cmd.macadd, phwaddr->sa_data, ETH_ALEN);
ret = lbs_cmd_with_response(priv, CMD_802_11_MAC_ADDRESS, &cmd);
if (ret) {
lbs_deb_net("set MAC address failed\n");
goto done;
}
memcpy(priv->current_addr, phwaddr->sa_data, ETH_ALEN);
memcpy(dev->dev_addr, phwaddr->sa_data, ETH_ALEN);
if (priv->mesh_dev)
memcpy(priv->mesh_dev->dev_addr, phwaddr->sa_data, ETH_ALEN);
done:
lbs_deb_leave_args(LBS_DEB_NET, "ret %d", ret);
return ret;
}
static inline int mac_in_list(unsigned char *list, int list_len,
unsigned char *mac)
{
while (list_len) {
if (!memcmp(list, mac, ETH_ALEN))
return 1;
list += ETH_ALEN;
list_len--;
}
return 0;
}
static int lbs_add_mcast_addrs(struct cmd_ds_mac_multicast_adr *cmd,
struct net_device *dev, int nr_addrs)
{
int i = nr_addrs;
struct netdev_hw_addr *ha;
int cnt;
if ((dev->flags & (IFF_UP|IFF_MULTICAST)) != (IFF_UP|IFF_MULTICAST))
return nr_addrs;
netif_addr_lock_bh(dev);
cnt = netdev_mc_count(dev);
netdev_for_each_mc_addr(ha, dev) {
if (mac_in_list(cmd->maclist, nr_addrs, ha->addr)) {
lbs_deb_net("mcast address %s:%pM skipped\n", dev->name,
ha->addr);
cnt--;
continue;
}
if (i == MRVDRV_MAX_MULTICAST_LIST_SIZE)
break;
memcpy(&cmd->maclist[6*i], ha->addr, ETH_ALEN);
lbs_deb_net("mcast address %s:%pM added to filter\n", dev->name,
ha->addr);
i++;
cnt--;
}
netif_addr_unlock_bh(dev);
if (cnt)
return -EOVERFLOW;
return i;
}
static void lbs_set_mcast_worker(struct work_struct *work)
{
struct lbs_private *priv = container_of(work, struct lbs_private, mcast_work);
struct cmd_ds_mac_multicast_adr mcast_cmd;
int dev_flags;
int nr_addrs;
int old_mac_control = priv->mac_control;
lbs_deb_enter(LBS_DEB_NET);
dev_flags = priv->dev->flags;
if (priv->mesh_dev)
dev_flags |= priv->mesh_dev->flags;
if (dev_flags & IFF_PROMISC) {
priv->mac_control |= CMD_ACT_MAC_PROMISCUOUS_ENABLE;
priv->mac_control &= ~(CMD_ACT_MAC_ALL_MULTICAST_ENABLE |
CMD_ACT_MAC_MULTICAST_ENABLE);
goto out_set_mac_control;
} else if (dev_flags & IFF_ALLMULTI) {
do_allmulti:
priv->mac_control |= CMD_ACT_MAC_ALL_MULTICAST_ENABLE;
priv->mac_control &= ~(CMD_ACT_MAC_PROMISCUOUS_ENABLE |
CMD_ACT_MAC_MULTICAST_ENABLE);
goto out_set_mac_control;
}
/* Once for priv->dev, again for priv->mesh_dev if it exists */
nr_addrs = lbs_add_mcast_addrs(&mcast_cmd, priv->dev, 0);
if (nr_addrs >= 0 && priv->mesh_dev)
nr_addrs = lbs_add_mcast_addrs(&mcast_cmd, priv->mesh_dev, nr_addrs);
if (nr_addrs < 0)
goto do_allmulti;
if (nr_addrs) {
int size = offsetof(struct cmd_ds_mac_multicast_adr,
maclist[6*nr_addrs]);
mcast_cmd.action = cpu_to_le16(CMD_ACT_SET);
mcast_cmd.hdr.size = cpu_to_le16(size);
mcast_cmd.nr_of_adrs = cpu_to_le16(nr_addrs);
lbs_cmd_async(priv, CMD_MAC_MULTICAST_ADR, &mcast_cmd.hdr, size);
priv->mac_control |= CMD_ACT_MAC_MULTICAST_ENABLE;
} else
priv->mac_control &= ~CMD_ACT_MAC_MULTICAST_ENABLE;
priv->mac_control &= ~(CMD_ACT_MAC_PROMISCUOUS_ENABLE |
CMD_ACT_MAC_ALL_MULTICAST_ENABLE);
out_set_mac_control:
if (priv->mac_control != old_mac_control)
lbs_set_mac_control(priv);
lbs_deb_leave(LBS_DEB_NET);
}
void lbs_set_multicast_list(struct net_device *dev)
{
struct lbs_private *priv = dev->ml_priv;
schedule_work(&priv->mcast_work);
}
/**
* lbs_thread - handles the major jobs in the LBS driver.
* It handles all events generated by firmware, RX data received
* from firmware and TX data sent from kernel.
*
* @data: A pointer to &lbs_thread structure
* returns: 0
*/
static int lbs_thread(void *data)
{
struct net_device *dev = data;
struct lbs_private *priv = dev->ml_priv;
wait_queue_t wait;
lbs_deb_enter(LBS_DEB_THREAD);
init_waitqueue_entry(&wait, current);
for (;;) {
int shouldsleep;
u8 resp_idx;
lbs_deb_thread("1: currenttxskb %p, dnld_sent %d\n",
priv->currenttxskb, priv->dnld_sent);
add_wait_queue(&priv->waitq, &wait);
set_current_state(TASK_INTERRUPTIBLE);
spin_lock_irq(&priv->driver_lock);
if (kthread_should_stop())
shouldsleep = 0; /* Bye */
else if (priv->surpriseremoved)
shouldsleep = 1; /* We need to wait until we're _told_ to die */
else if (priv->psstate == PS_STATE_SLEEP)
shouldsleep = 1; /* Sleep mode. Nothing we can do till it wakes */
else if (priv->cmd_timed_out)
shouldsleep = 0; /* Command timed out. Recover */
else if (!priv->fw_ready)
shouldsleep = 1; /* Firmware not ready. We're waiting for it */
else if (priv->dnld_sent)
shouldsleep = 1; /* Something is en route to the device already */
else if (priv->tx_pending_len > 0)
shouldsleep = 0; /* We've a packet to send */
else if (priv->resp_len[priv->resp_idx])
shouldsleep = 0; /* We have a command response */
else if (priv->cur_cmd)
shouldsleep = 1; /* Can't send a command; one already running */
else if (!list_empty(&priv->cmdpendingq) &&
!(priv->wakeup_dev_required))
shouldsleep = 0; /* We have a command to send */
else if (kfifo_len(&priv->event_fifo))
shouldsleep = 0; /* We have an event to process */
else
shouldsleep = 1; /* No command */
if (shouldsleep) {
lbs_deb_thread("sleeping, connect_status %d, "
"psmode %d, psstate %d\n",
priv->connect_status,
priv->psmode, priv->psstate);
spin_unlock_irq(&priv->driver_lock);
schedule();
} else
spin_unlock_irq(&priv->driver_lock);
lbs_deb_thread("2: currenttxskb %p, dnld_send %d\n",
priv->currenttxskb, priv->dnld_sent);
set_current_state(TASK_RUNNING);
remove_wait_queue(&priv->waitq, &wait);
lbs_deb_thread("3: currenttxskb %p, dnld_sent %d\n",
priv->currenttxskb, priv->dnld_sent);
if (kthread_should_stop()) {
lbs_deb_thread("break from main thread\n");
break;
}
if (priv->surpriseremoved) {
lbs_deb_thread("adapter removed; waiting to die...\n");
continue;
}
lbs_deb_thread("4: currenttxskb %p, dnld_sent %d\n",
priv->currenttxskb, priv->dnld_sent);
/* Process any pending command response */
spin_lock_irq(&priv->driver_lock);
resp_idx = priv->resp_idx;
if (priv->resp_len[resp_idx]) {
spin_unlock_irq(&priv->driver_lock);
lbs_process_command_response(priv,
priv->resp_buf[resp_idx],
priv->resp_len[resp_idx]);
spin_lock_irq(&priv->driver_lock);
priv->resp_len[resp_idx] = 0;
}
spin_unlock_irq(&priv->driver_lock);
/* Process hardware events, e.g. card removed, link lost */
spin_lock_irq(&priv->driver_lock);
while (kfifo_len(&priv->event_fifo)) {
u32 event;
if (kfifo_out(&priv->event_fifo,
(unsigned char *) &event, sizeof(event)) !=
sizeof(event))
break;
spin_unlock_irq(&priv->driver_lock);
lbs_process_event(priv, event);
spin_lock_irq(&priv->driver_lock);
}
spin_unlock_irq(&priv->driver_lock);
if (priv->wakeup_dev_required) {
lbs_deb_thread("Waking up device...\n");
/* Wake up device */
if (priv->exit_deep_sleep(priv))
lbs_deb_thread("Wakeup device failed\n");
continue;
}
/* command timeout stuff */
if (priv->cmd_timed_out && priv->cur_cmd) {
struct cmd_ctrl_node *cmdnode = priv->cur_cmd;
netdev_info(dev, "Timeout submitting command 0x%04x\n",
le16_to_cpu(cmdnode->cmdbuf->command));
lbs_complete_command(priv, cmdnode, -ETIMEDOUT);
if (priv->reset_card)
priv->reset_card(priv);
}
priv->cmd_timed_out = 0;
if (!priv->fw_ready)
continue;
/* Check if we need to confirm Sleep Request received previously */
if (priv->psstate == PS_STATE_PRE_SLEEP &&
!priv->dnld_sent && !priv->cur_cmd) {
if (priv->connect_status == LBS_CONNECTED) {
lbs_deb_thread("pre-sleep, currenttxskb %p, "
"dnld_sent %d, cur_cmd %p\n",
priv->currenttxskb, priv->dnld_sent,
priv->cur_cmd);
lbs_ps_confirm_sleep(priv);
} else {
/* workaround for firmware sending
* deauth/linkloss event immediately
* after sleep request; remove this
* after firmware fixes it
*/
priv->psstate = PS_STATE_AWAKE;
netdev_alert(dev,
"ignore PS_SleepConfirm in non-connected state\n");
}
}
/* The PS state is changed during processing of Sleep Request
* event above
*/
if ((priv->psstate == PS_STATE_SLEEP) ||
(priv->psstate == PS_STATE_PRE_SLEEP))
continue;
if (priv->is_deep_sleep)
continue;
/* Execute the next command */
if (!priv->dnld_sent && !priv->cur_cmd)
lbs_execute_next_command(priv);
spin_lock_irq(&priv->driver_lock);
if (!priv->dnld_sent && priv->tx_pending_len > 0) {
int ret = priv->hw_host_to_card(priv, MVMS_DAT,
priv->tx_pending_buf,
priv->tx_pending_len);
if (ret) {
lbs_deb_tx("host_to_card failed %d\n", ret);
priv->dnld_sent = DNLD_RES_RECEIVED;
}
priv->tx_pending_len = 0;
if (!priv->currenttxskb) {
/* We can wake the queues immediately if we aren't
waiting for TX feedback */
if (priv->connect_status == LBS_CONNECTED)
netif_wake_queue(priv->dev);
if (priv->mesh_dev &&
lbs_mesh_connected(priv))
netif_wake_queue(priv->mesh_dev);
}
}
spin_unlock_irq(&priv->driver_lock);
}
del_timer(&priv->command_timer);
del_timer(&priv->auto_deepsleep_timer);
lbs_deb_leave(LBS_DEB_THREAD);
return 0;
}
/**
* lbs_setup_firmware - gets the HW spec from the firmware and sets
* some basic parameters
*
* @priv: A pointer to &struct lbs_private structure
* returns: 0 or -1
*/
static int lbs_setup_firmware(struct lbs_private *priv)
{
int ret = -1;
s16 curlevel = 0, minlevel = 0, maxlevel = 0;
lbs_deb_enter(LBS_DEB_FW);
/* Read MAC address from firmware */
memset(priv->current_addr, 0xff, ETH_ALEN);
ret = lbs_update_hw_spec(priv);
if (ret)
goto done;
/* Read power levels if available */
ret = lbs_get_tx_power(priv, &curlevel, &minlevel, &maxlevel);
if (ret == 0) {
priv->txpower_cur = curlevel;
priv->txpower_min = minlevel;
priv->txpower_max = maxlevel;
}
/* Send cmd to FW to enable 11D function */
ret = lbs_set_snmp_mib(priv, SNMP_MIB_OID_11D_ENABLE, 1);
lbs_set_mac_control(priv);
done:
lbs_deb_leave_args(LBS_DEB_FW, "ret %d", ret);
return ret;
}
int lbs_suspend(struct lbs_private *priv)
{
int ret;
lbs_deb_enter(LBS_DEB_FW);
if (priv->is_deep_sleep) {
ret = lbs_set_deep_sleep(priv, 0);
if (ret) {
netdev_err(priv->dev,
"deep sleep cancellation failed: %d\n", ret);
return ret;
}
priv->deep_sleep_required = 1;
}
ret = lbs_set_host_sleep(priv, 1);
netif_device_detach(priv->dev);
if (priv->mesh_dev)
netif_device_detach(priv->mesh_dev);
lbs_deb_leave_args(LBS_DEB_FW, "ret %d", ret);
return ret;
}
EXPORT_SYMBOL_GPL(lbs_suspend);
int lbs_resume(struct lbs_private *priv)
{
int ret;
lbs_deb_enter(LBS_DEB_FW);
ret = lbs_set_host_sleep(priv, 0);
netif_device_attach(priv->dev);
if (priv->mesh_dev)
netif_device_attach(priv->mesh_dev);
if (priv->deep_sleep_required) {
priv->deep_sleep_required = 0;
ret = lbs_set_deep_sleep(priv, 1);
if (ret)
netdev_err(priv->dev,
"deep sleep activation failed: %d\n", ret);
}
if (priv->setup_fw_on_resume)
ret = lbs_setup_firmware(priv);
lbs_deb_leave_args(LBS_DEB_FW, "ret %d", ret);
return ret;
}
EXPORT_SYMBOL_GPL(lbs_resume);
/**
* lbs_cmd_timeout_handler - handles the timeout of command sending.
* It will re-send the same command again.
*
* @data: &struct lbs_private pointer
*/
static void lbs_cmd_timeout_handler(unsigned long data)
{
struct lbs_private *priv = (struct lbs_private *)data;
unsigned long flags;
lbs_deb_enter(LBS_DEB_CMD);
spin_lock_irqsave(&priv->driver_lock, flags);
if (!priv->cur_cmd)
goto out;
netdev_info(priv->dev, "command 0x%04x timed out\n",
le16_to_cpu(priv->cur_cmd->cmdbuf->command));
priv->cmd_timed_out = 1;
wake_up_interruptible(&priv->waitq);
out:
spin_unlock_irqrestore(&priv->driver_lock, flags);
lbs_deb_leave(LBS_DEB_CMD);
}
/**
* auto_deepsleep_timer_fn - put the device back to deep sleep mode when
* timer expires and no activity (command, event, data etc.) is detected.
* @data: &struct lbs_private pointer
* returns: N/A
*/
static void auto_deepsleep_timer_fn(unsigned long data)
{
struct lbs_private *priv = (struct lbs_private *)data;
lbs_deb_enter(LBS_DEB_CMD);
if (priv->is_activity_detected) {
priv->is_activity_detected = 0;
} else {
if (priv->is_auto_deep_sleep_enabled &&
(!priv->wakeup_dev_required) &&
(priv->connect_status != LBS_CONNECTED)) {
struct cmd_header cmd;
lbs_deb_main("Entering auto deep sleep mode...\n");
memset(&cmd, 0, sizeof(cmd));
cmd.size = cpu_to_le16(sizeof(cmd));
lbs_cmd_async(priv, CMD_802_11_DEEP_SLEEP, &cmd,
sizeof(cmd));
}
}
mod_timer(&priv->auto_deepsleep_timer , jiffies +
(priv->auto_deep_sleep_timeout * HZ)/1000);
lbs_deb_leave(LBS_DEB_CMD);
}
int lbs_enter_auto_deep_sleep(struct lbs_private *priv)
{
lbs_deb_enter(LBS_DEB_SDIO);
priv->is_auto_deep_sleep_enabled = 1;
if (priv->is_deep_sleep)
priv->wakeup_dev_required = 1;
mod_timer(&priv->auto_deepsleep_timer ,
jiffies + (priv->auto_deep_sleep_timeout * HZ)/1000);
lbs_deb_leave(LBS_DEB_SDIO);
return 0;
}
int lbs_exit_auto_deep_sleep(struct lbs_private *priv)
{
lbs_deb_enter(LBS_DEB_SDIO);
priv->is_auto_deep_sleep_enabled = 0;
priv->auto_deep_sleep_timeout = 0;
del_timer(&priv->auto_deepsleep_timer);
lbs_deb_leave(LBS_DEB_SDIO);
return 0;
}
static int lbs_init_adapter(struct lbs_private *priv)
{
int ret;
lbs_deb_enter(LBS_DEB_MAIN);
memset(priv->current_addr, 0xff, ETH_ALEN);
priv->connect_status = LBS_DISCONNECTED;
priv->channel = DEFAULT_AD_HOC_CHANNEL;
priv->mac_control = CMD_ACT_MAC_RX_ON | CMD_ACT_MAC_TX_ON;
priv->radio_on = 1;
priv->psmode = LBS802_11POWERMODECAM;
priv->psstate = PS_STATE_FULL_POWER;
priv->is_deep_sleep = 0;
priv->is_auto_deep_sleep_enabled = 0;
priv->deep_sleep_required = 0;
priv->wakeup_dev_required = 0;
init_waitqueue_head(&priv->ds_awake_q);
init_waitqueue_head(&priv->scan_q);
priv->authtype_auto = 1;
priv->is_host_sleep_configured = 0;
priv->is_host_sleep_activated = 0;
init_waitqueue_head(&priv->host_sleep_q);
mutex_init(&priv->lock);
setup_timer(&priv->command_timer, lbs_cmd_timeout_handler,
(unsigned long)priv);
setup_timer(&priv->auto_deepsleep_timer, auto_deepsleep_timer_fn,
(unsigned long)priv);
INIT_LIST_HEAD(&priv->cmdfreeq);
INIT_LIST_HEAD(&priv->cmdpendingq);
spin_lock_init(&priv->driver_lock);
/* Allocate the command buffers */
if (lbs_allocate_cmd_buffer(priv)) {
pr_err("Out of memory allocating command buffers\n");
ret = -ENOMEM;
goto out;
}
priv->resp_idx = 0;
priv->resp_len[0] = priv->resp_len[1] = 0;
/* Create the event FIFO */
ret = kfifo_alloc(&priv->event_fifo, sizeof(u32) * 16, GFP_KERNEL);
if (ret) {
pr_err("Out of memory allocating event FIFO buffer\n");
goto out;
}
out:
lbs_deb_leave_args(LBS_DEB_MAIN, "ret %d", ret);
return ret;
}
static void lbs_free_adapter(struct lbs_private *priv)
{
lbs_deb_enter(LBS_DEB_MAIN);
lbs_free_cmd_buffer(priv);
kfifo_free(&priv->event_fifo);
del_timer(&priv->command_timer);
del_timer(&priv->auto_deepsleep_timer);
lbs_deb_leave(LBS_DEB_MAIN);
}
static const struct net_device_ops lbs_netdev_ops = {
.ndo_open = lbs_dev_open,
.ndo_stop = lbs_eth_stop,
.ndo_start_xmit = lbs_hard_start_xmit,
.ndo_set_mac_address = lbs_set_mac_address,
.ndo_set_multicast_list = lbs_set_multicast_list,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
};
/**
* lbs_add_card - adds the card. It will probe the
* card, allocate the lbs_priv and initialize the device.
*
* @card: A pointer to card
* @dmdev: A pointer to &struct device
* returns: A pointer to &struct lbs_private structure
*/
struct lbs_private *lbs_add_card(void *card, struct device *dmdev)
{
struct net_device *dev;
struct wireless_dev *wdev;
struct lbs_private *priv = NULL;
lbs_deb_enter(LBS_DEB_MAIN);
/* Allocate an Ethernet device and register it */
wdev = lbs_cfg_alloc(dmdev);
if (IS_ERR(wdev)) {
pr_err("cfg80211 init failed\n");
goto done;
}
wdev->iftype = NL80211_IFTYPE_STATION;
priv = wdev_priv(wdev);
priv->wdev = wdev;
if (lbs_init_adapter(priv)) {
pr_err("failed to initialize adapter structure\n");
goto err_wdev;
}
dev = alloc_netdev(0, "wlan%d", ether_setup);
if (!dev) {
dev_err(dmdev, "no memory for network device instance\n");
goto err_adapter;
}
dev->ieee80211_ptr = wdev;
dev->ml_priv = priv;
SET_NETDEV_DEV(dev, dmdev);
wdev->netdev = dev;
priv->dev = dev;
dev->netdev_ops = &lbs_netdev_ops;
dev->watchdog_timeo = 5 * HZ;
dev->ethtool_ops = &lbs_ethtool_ops;
dev->flags |= IFF_BROADCAST | IFF_MULTICAST;
priv->card = card;
strcpy(dev->name, "wlan%d");
lbs_deb_thread("Starting main thread...\n");
init_waitqueue_head(&priv->waitq);
priv->main_thread = kthread_run(lbs_thread, dev, "lbs_main");
if (IS_ERR(priv->main_thread)) {
lbs_deb_thread("Error creating main thread.\n");
goto err_ndev;
}
priv->work_thread = create_singlethread_workqueue("lbs_worker");
INIT_WORK(&priv->mcast_work, lbs_set_mcast_worker);
priv->wol_criteria = EHS_REMOVE_WAKEUP;
priv->wol_gpio = 0xff;
priv->wol_gap = 20;
priv->ehs_remove_supported = true;
goto done;
err_ndev:
free_netdev(dev);
err_adapter:
lbs_free_adapter(priv);
err_wdev:
lbs_cfg_free(priv);
priv = NULL;
done:
lbs_deb_leave_args(LBS_DEB_MAIN, "priv %p", priv);
return priv;
}
EXPORT_SYMBOL_GPL(lbs_add_card);
void lbs_remove_card(struct lbs_private *priv)
{
struct net_device *dev = priv->dev;
lbs_deb_enter(LBS_DEB_MAIN);
lbs_remove_mesh(priv);
lbs_scan_deinit(priv);
dev = priv->dev;
cancel_work_sync(&priv->mcast_work);
/* worker thread destruction blocks on the in-flight command which
* should have been cleared already in lbs_stop_card().
*/
lbs_deb_main("destroying worker thread\n");
destroy_workqueue(priv->work_thread);
lbs_deb_main("done destroying worker thread\n");
if (priv->psmode == LBS802_11POWERMODEMAX_PSP) {
priv->psmode = LBS802_11POWERMODECAM;
lbs_set_ps_mode(priv, PS_MODE_ACTION_EXIT_PS, true);
}
if (priv->is_deep_sleep) {
priv->is_deep_sleep = 0;
wake_up_interruptible(&priv->ds_awake_q);
}
priv->is_host_sleep_configured = 0;
priv->is_host_sleep_activated = 0;
wake_up_interruptible(&priv->host_sleep_q);
/* Stop the thread servicing the interrupts */
priv->surpriseremoved = 1;
kthread_stop(priv->main_thread);
lbs_free_adapter(priv);
lbs_cfg_free(priv);
free_netdev(dev);
lbs_deb_leave(LBS_DEB_MAIN);
}
EXPORT_SYMBOL_GPL(lbs_remove_card);
int lbs_rtap_supported(struct lbs_private *priv)
{
if (MRVL_FW_MAJOR_REV(priv->fwrelease) == MRVL_FW_V5)
return 1;
/* newer firmware use a capability mask */
return ((MRVL_FW_MAJOR_REV(priv->fwrelease) >= MRVL_FW_V10) &&
(priv->fwcapinfo & MESH_CAPINFO_ENABLE_MASK));
}
int lbs_start_card(struct lbs_private *priv)
{
struct net_device *dev = priv->dev;
int ret = -1;
lbs_deb_enter(LBS_DEB_MAIN);
/* poke the firmware */
ret = lbs_setup_firmware(priv);
if (ret)
goto done;
if (lbs_cfg_register(priv)) {
pr_err("cannot register device\n");
goto done;
}
lbs_update_channel(priv);
if (!lbs_disablemesh)
lbs_init_mesh(priv);
else
pr_info("%s: mesh disabled\n", dev->name);
lbs_debugfs_init_one(priv, dev);
netdev_info(dev, "Marvell WLAN 802.11 adapter\n");
ret = 0;
done:
lbs_deb_leave_args(LBS_DEB_MAIN, "ret %d", ret);
return ret;
}
EXPORT_SYMBOL_GPL(lbs_start_card);
void lbs_stop_card(struct lbs_private *priv)
{
struct net_device *dev;
struct cmd_ctrl_node *cmdnode;
unsigned long flags;
lbs_deb_enter(LBS_DEB_MAIN);
if (!priv)
goto out;
dev = priv->dev;
netif_stop_queue(dev);
netif_carrier_off(dev);
lbs_debugfs_remove_one(priv);
lbs_deinit_mesh(priv);
/* Delete the timeout of the currently processing command */
del_timer_sync(&priv->command_timer);
del_timer_sync(&priv->auto_deepsleep_timer);
/* Flush pending command nodes */
spin_lock_irqsave(&priv->driver_lock, flags);
lbs_deb_main("clearing pending commands\n");
list_for_each_entry(cmdnode, &priv->cmdpendingq, list) {
cmdnode->result = -ENOENT;
cmdnode->cmdwaitqwoken = 1;
wake_up_interruptible(&cmdnode->cmdwait_q);
}
/* Flush the command the card is currently processing */
if (priv->cur_cmd) {
lbs_deb_main("clearing current command\n");
priv->cur_cmd->result = -ENOENT;
priv->cur_cmd->cmdwaitqwoken = 1;
wake_up_interruptible(&priv->cur_cmd->cmdwait_q);
}
lbs_deb_main("done clearing commands\n");
spin_unlock_irqrestore(&priv->driver_lock, flags);
unregister_netdev(dev);
out:
lbs_deb_leave(LBS_DEB_MAIN);
}
EXPORT_SYMBOL_GPL(lbs_stop_card);
void lbs_queue_event(struct lbs_private *priv, u32 event)
{
unsigned long flags;
lbs_deb_enter(LBS_DEB_THREAD);
spin_lock_irqsave(&priv->driver_lock, flags);
if (priv->psstate == PS_STATE_SLEEP)
priv->psstate = PS_STATE_AWAKE;
kfifo_in(&priv->event_fifo, (unsigned char *) &event, sizeof(u32));
wake_up_interruptible(&priv->waitq);
spin_unlock_irqrestore(&priv->driver_lock, flags);
lbs_deb_leave(LBS_DEB_THREAD);
}
EXPORT_SYMBOL_GPL(lbs_queue_event);
void lbs_notify_command_response(struct lbs_private *priv, u8 resp_idx)
{
lbs_deb_enter(LBS_DEB_THREAD);
if (priv->psstate == PS_STATE_SLEEP)
priv->psstate = PS_STATE_AWAKE;
/* Swap buffers by flipping the response index */
BUG_ON(resp_idx > 1);
priv->resp_idx = resp_idx;
wake_up_interruptible(&priv->waitq);
lbs_deb_leave(LBS_DEB_THREAD);
}
EXPORT_SYMBOL_GPL(lbs_notify_command_response);
/**
* lbs_get_firmware - Retrieves two-stage firmware
*
* @dev: A pointer to &device structure
* @user_helper: User-defined helper firmware file
* @user_mainfw: User-defined main firmware file
* @card_model: Bus-specific card model ID used to filter firmware table
* elements
* @fw_table: Table of firmware file names and device model numbers
* terminated by an entry with a NULL helper name
* @helper: On success, the helper firmware; caller must free
* @mainfw: On success, the main firmware; caller must free
*
* returns: 0 on success, non-zero on failure
*/
int lbs_get_firmware(struct device *dev, const char *user_helper,
const char *user_mainfw, u32 card_model,
const struct lbs_fw_table *fw_table,
const struct firmware **helper,
const struct firmware **mainfw)
{
const struct lbs_fw_table *iter;
int ret;
BUG_ON(helper == NULL);
BUG_ON(mainfw == NULL);
/* Try user-specified firmware first */
if (user_helper) {
ret = request_firmware(helper, user_helper, dev);
if (ret) {
dev_err(dev, "couldn't find helper firmware %s\n",
user_helper);
goto fail;
}
}
if (user_mainfw) {
ret = request_firmware(mainfw, user_mainfw, dev);
if (ret) {
dev_err(dev, "couldn't find main firmware %s\n",
user_mainfw);
goto fail;
}
}
if (*helper && *mainfw)
return 0;
/* Otherwise search for firmware to use. If neither the helper or
* the main firmware were specified by the user, then we need to
* make sure that found helper & main are from the same entry in
* fw_table.
*/
iter = fw_table;
while (iter && iter->helper) {
if (iter->model != card_model)
goto next;
if (*helper == NULL) {
ret = request_firmware(helper, iter->helper, dev);
if (ret)
goto next;
/* If the device has one-stage firmware (ie cf8305) and
* we've got it then we don't need to bother with the
* main firmware.
*/
if (iter->fwname == NULL)
return 0;
}
if (*mainfw == NULL) {
ret = request_firmware(mainfw, iter->fwname, dev);
if (ret && !user_helper) {
/* Clear the helper if it wasn't user-specified
* and the main firmware load failed, to ensure
* we don't have mismatched firmware pairs.
*/
release_firmware(*helper);
*helper = NULL;
}
}
if (*helper && *mainfw)
return 0;
next:
iter++;
}
fail:
/* Failed */
if (*helper) {
release_firmware(*helper);
*helper = NULL;
}
if (*mainfw) {
release_firmware(*mainfw);
*mainfw = NULL;
}
return -ENOENT;
}
EXPORT_SYMBOL_GPL(lbs_get_firmware);
static int __init lbs_init_module(void)
{
lbs_deb_enter(LBS_DEB_MAIN);
memset(&confirm_sleep, 0, sizeof(confirm_sleep));
confirm_sleep.hdr.command = cpu_to_le16(CMD_802_11_PS_MODE);
confirm_sleep.hdr.size = cpu_to_le16(sizeof(confirm_sleep));
confirm_sleep.action = cpu_to_le16(PS_MODE_ACTION_SLEEP_CONFIRMED);
lbs_debugfs_init();
lbs_deb_leave(LBS_DEB_MAIN);
return 0;
}
static void __exit lbs_exit_module(void)
{
lbs_deb_enter(LBS_DEB_MAIN);
lbs_debugfs_remove();
lbs_deb_leave(LBS_DEB_MAIN);
}
module_init(lbs_init_module);
module_exit(lbs_exit_module);
MODULE_DESCRIPTION("Libertas WLAN Driver Library");
MODULE_AUTHOR("Marvell International Ltd.");
MODULE_LICENSE("GPL");
| gpl-2.0 |
andreturket/android_kernel_d1_p1 | drivers/net/pcmcia/pcnet_cs.c | 2770 | 61781 | /*======================================================================
A PCMCIA ethernet driver for NS8390-based cards
This driver supports the D-Link DE-650 and Linksys EthernetCard
cards, the newer D-Link and Linksys combo cards, Accton EN2212
cards, the RPTI EP400, and the PreMax PE-200 in non-shared-memory
mode, and the IBM Credit Card Adapter, the NE4100, the Thomas
Conrad ethernet card, and the Kingston KNE-PCM/x in shared-memory
mode. It will also handle the Socket EA card in either mode.
Copyright (C) 1999 David A. Hinds -- dahinds@users.sourceforge.net
pcnet_cs.c 1.153 2003/11/09 18:53:09
The network driver code is based on Donald Becker's NE2000 code:
Written 1992,1993 by Donald Becker.
Copyright 1993 United States Government as represented by the
Director, National Security Agency. This software may be used and
distributed according to the terms of the GNU General Public License,
incorporated herein by reference.
Donald Becker may be reached at becker@scyld.com
Based also on Keith Moore's changes to Don Becker's code, for IBM
CCAE support. Drivers merged back together, and shared-memory
Socket EA support added, by Ken Raeburn, September 1995.
======================================================================*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/ptrace.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/log2.h>
#include <linux/etherdevice.h>
#include <linux/mii.h>
#include "../8390.h"
#include <pcmcia/cistpl.h>
#include <pcmcia/ciscode.h>
#include <pcmcia/ds.h>
#include <pcmcia/cisreg.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>
#define PCNET_CMD 0x00
#define PCNET_DATAPORT 0x10 /* NatSemi-defined port window offset. */
#define PCNET_RESET 0x1f /* Issue a read to reset, a write to clear. */
#define PCNET_MISC 0x18 /* For IBM CCAE and Socket EA cards */
#define PCNET_START_PG 0x40 /* First page of TX buffer */
#define PCNET_STOP_PG 0x80 /* Last page +1 of RX ring */
/* Socket EA cards have a larger packet buffer */
#define SOCKET_START_PG 0x01
#define SOCKET_STOP_PG 0xff
#define PCNET_RDC_TIMEOUT (2*HZ/100) /* Max wait in jiffies for Tx RDC */
static const char *if_names[] = { "auto", "10baseT", "10base2"};
/*====================================================================*/
/* Module parameters */
MODULE_AUTHOR("David Hinds <dahinds@users.sourceforge.net>");
MODULE_DESCRIPTION("NE2000 compatible PCMCIA ethernet driver");
MODULE_LICENSE("GPL");
#define INT_MODULE_PARM(n, v) static int n = v; module_param(n, int, 0)
INT_MODULE_PARM(if_port, 1); /* Transceiver type */
INT_MODULE_PARM(use_big_buf, 1); /* use 64K packet buffer? */
INT_MODULE_PARM(mem_speed, 0); /* shared mem speed, in ns */
INT_MODULE_PARM(delay_output, 0); /* pause after xmit? */
INT_MODULE_PARM(delay_time, 4); /* in usec */
INT_MODULE_PARM(use_shmem, -1); /* use shared memory? */
INT_MODULE_PARM(full_duplex, 0); /* full duplex? */
/* Ugh! Let the user hardwire the hardware address for queer cards */
static int hw_addr[6] = { 0, /* ... */ };
module_param_array(hw_addr, int, NULL, 0);
/*====================================================================*/
static void mii_phy_probe(struct net_device *dev);
static int pcnet_config(struct pcmcia_device *link);
static void pcnet_release(struct pcmcia_device *link);
static int pcnet_open(struct net_device *dev);
static int pcnet_close(struct net_device *dev);
static int ei_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static irqreturn_t ei_irq_wrapper(int irq, void *dev_id);
static void ei_watchdog(u_long arg);
static void pcnet_reset_8390(struct net_device *dev);
static int set_config(struct net_device *dev, struct ifmap *map);
static int setup_shmem_window(struct pcmcia_device *link, int start_pg,
int stop_pg, int cm_offset);
static int setup_dma_config(struct pcmcia_device *link, int start_pg,
int stop_pg);
static void pcnet_detach(struct pcmcia_device *p_dev);
/*====================================================================*/
typedef struct hw_info_t {
u_int offset;
u_char a0, a1, a2;
u_int flags;
} hw_info_t;
#define DELAY_OUTPUT 0x01
#define HAS_MISC_REG 0x02
#define USE_BIG_BUF 0x04
#define HAS_IBM_MISC 0x08
#define IS_DL10019 0x10
#define IS_DL10022 0x20
#define HAS_MII 0x40
#define USE_SHMEM 0x80 /* autodetected */
#define AM79C9XX_HOME_PHY 0x00006B90 /* HomePNA PHY */
#define AM79C9XX_ETH_PHY 0x00006B70 /* 10baseT PHY */
#define MII_PHYID_REV_MASK 0xfffffff0
#define MII_PHYID_REG1 0x02
#define MII_PHYID_REG2 0x03
static hw_info_t hw_info[] = {
{ /* Accton EN2212 */ 0x0ff0, 0x00, 0x00, 0xe8, DELAY_OUTPUT },
{ /* Allied Telesis LA-PCM */ 0x0ff0, 0x00, 0x00, 0xf4, 0 },
{ /* APEX MultiCard */ 0x03f4, 0x00, 0x20, 0xe5, 0 },
{ /* ASANTE FriendlyNet */ 0x4910, 0x00, 0x00, 0x94,
DELAY_OUTPUT | HAS_IBM_MISC },
{ /* Danpex EN-6200P2 */ 0x0110, 0x00, 0x40, 0xc7, 0 },
{ /* DataTrek NetCard */ 0x0ff0, 0x00, 0x20, 0xe8, 0 },
{ /* Dayna CommuniCard E */ 0x0110, 0x00, 0x80, 0x19, 0 },
{ /* D-Link DE-650 */ 0x0040, 0x00, 0x80, 0xc8, 0 },
{ /* EP-210 Ethernet */ 0x0110, 0x00, 0x40, 0x33, 0 },
{ /* EP4000 Ethernet */ 0x01c0, 0x00, 0x00, 0xb4, 0 },
{ /* Epson EEN10B */ 0x0ff0, 0x00, 0x00, 0x48,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* ELECOM Laneed LD-CDWA */ 0xb8, 0x08, 0x00, 0x42, 0 },
{ /* Hypertec Ethernet */ 0x01c0, 0x00, 0x40, 0x4c, 0 },
{ /* IBM CCAE */ 0x0ff0, 0x08, 0x00, 0x5a,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* IBM CCAE */ 0x0ff0, 0x00, 0x04, 0xac,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* IBM CCAE */ 0x0ff0, 0x00, 0x06, 0x29,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* IBM FME */ 0x0374, 0x08, 0x00, 0x5a,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* IBM FME */ 0x0374, 0x00, 0x04, 0xac,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* Kansai KLA-PCM/T */ 0x0ff0, 0x00, 0x60, 0x87,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* NSC DP83903 */ 0x0374, 0x08, 0x00, 0x17,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* NSC DP83903 */ 0x0374, 0x00, 0xc0, 0xa8,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* NSC DP83903 */ 0x0374, 0x00, 0xa0, 0xb0,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* NSC DP83903 */ 0x0198, 0x00, 0x20, 0xe0,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* I-O DATA PCLA/T */ 0x0ff0, 0x00, 0xa0, 0xb0, 0 },
{ /* Katron PE-520 */ 0x0110, 0x00, 0x40, 0xf6, 0 },
{ /* Kingston KNE-PCM/x */ 0x0ff0, 0x00, 0xc0, 0xf0,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* Kingston KNE-PCM/x */ 0x0ff0, 0xe2, 0x0c, 0x0f,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* Kingston KNE-PC2 */ 0x0180, 0x00, 0xc0, 0xf0, 0 },
{ /* Maxtech PCN2000 */ 0x5000, 0x00, 0x00, 0xe8, 0 },
{ /* NDC Instant-Link */ 0x003a, 0x00, 0x80, 0xc6, 0 },
{ /* NE2000 Compatible */ 0x0ff0, 0x00, 0xa0, 0x0c, 0 },
{ /* Network General Sniffer */ 0x0ff0, 0x00, 0x00, 0x65,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* Panasonic VEL211 */ 0x0ff0, 0x00, 0x80, 0x45,
HAS_MISC_REG | HAS_IBM_MISC },
{ /* PreMax PE-200 */ 0x07f0, 0x00, 0x20, 0xe0, 0 },
{ /* RPTI EP400 */ 0x0110, 0x00, 0x40, 0x95, 0 },
{ /* SCM Ethernet */ 0x0ff0, 0x00, 0x20, 0xcb, 0 },
{ /* Socket EA */ 0x4000, 0x00, 0xc0, 0x1b,
DELAY_OUTPUT | HAS_MISC_REG | USE_BIG_BUF },
{ /* Socket LP-E CF+ */ 0x01c0, 0x00, 0xc0, 0x1b, 0 },
{ /* SuperSocket RE450T */ 0x0110, 0x00, 0xe0, 0x98, 0 },
{ /* Volktek NPL-402CT */ 0x0060, 0x00, 0x40, 0x05, 0 },
{ /* NEC PC-9801N-J12 */ 0x0ff0, 0x00, 0x00, 0x4c, 0 },
{ /* PCMCIA Technology OEM */ 0x01c8, 0x00, 0xa0, 0x0c, 0 }
};
#define NR_INFO ARRAY_SIZE(hw_info)
static hw_info_t default_info = { 0, 0, 0, 0, 0 };
static hw_info_t dl10019_info = { 0, 0, 0, 0, IS_DL10019|HAS_MII };
static hw_info_t dl10022_info = { 0, 0, 0, 0, IS_DL10022|HAS_MII };
typedef struct pcnet_dev_t {
struct pcmcia_device *p_dev;
u_int flags;
void __iomem *base;
struct timer_list watchdog;
int stale, fast_poll;
u_char phy_id;
u_char eth_phy, pna_phy;
u_short link_status;
u_long mii_reset;
} pcnet_dev_t;
static inline pcnet_dev_t *PRIV(struct net_device *dev)
{
char *p = netdev_priv(dev);
return (pcnet_dev_t *)(p + sizeof(struct ei_device));
}
static const struct net_device_ops pcnet_netdev_ops = {
.ndo_open = pcnet_open,
.ndo_stop = pcnet_close,
.ndo_set_config = set_config,
.ndo_start_xmit = ei_start_xmit,
.ndo_get_stats = ei_get_stats,
.ndo_do_ioctl = ei_ioctl,
.ndo_set_multicast_list = ei_set_multicast_list,
.ndo_tx_timeout = ei_tx_timeout,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = ei_poll,
#endif
};
static int pcnet_probe(struct pcmcia_device *link)
{
pcnet_dev_t *info;
struct net_device *dev;
dev_dbg(&link->dev, "pcnet_attach()\n");
/* Create new ethernet device */
dev = __alloc_ei_netdev(sizeof(pcnet_dev_t));
if (!dev) return -ENOMEM;
info = PRIV(dev);
info->p_dev = link;
link->priv = dev;
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO;
dev->netdev_ops = &pcnet_netdev_ops;
return pcnet_config(link);
} /* pcnet_attach */
static void pcnet_detach(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
dev_dbg(&link->dev, "pcnet_detach\n");
unregister_netdev(dev);
pcnet_release(link);
free_netdev(dev);
} /* pcnet_detach */
/*======================================================================
This probes for a card's hardware address, for card types that
encode this information in their CIS.
======================================================================*/
static hw_info_t *get_hwinfo(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
u_char __iomem *base, *virt;
int i, j;
/* Allocate a small memory window */
link->resource[2]->flags |= WIN_DATA_WIDTH_8|WIN_MEMORY_TYPE_AM|WIN_ENABLE;
link->resource[2]->start = 0; link->resource[2]->end = 0;
i = pcmcia_request_window(link, link->resource[2], 0);
if (i != 0)
return NULL;
virt = ioremap(link->resource[2]->start,
resource_size(link->resource[2]));
for (i = 0; i < NR_INFO; i++) {
pcmcia_map_mem_page(link, link->resource[2],
hw_info[i].offset & ~(resource_size(link->resource[2])-1));
base = &virt[hw_info[i].offset & (resource_size(link->resource[2])-1)];
if ((readb(base+0) == hw_info[i].a0) &&
(readb(base+2) == hw_info[i].a1) &&
(readb(base+4) == hw_info[i].a2)) {
for (j = 0; j < 6; j++)
dev->dev_addr[j] = readb(base + (j<<1));
break;
}
}
iounmap(virt);
j = pcmcia_release_window(link, link->resource[2]);
return (i < NR_INFO) ? hw_info+i : NULL;
} /* get_hwinfo */
/*======================================================================
This probes for a card's hardware address by reading the PROM.
It checks the address against a list of known types, then falls
back to a simple NE2000 clone signature check.
======================================================================*/
static hw_info_t *get_prom(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
unsigned int ioaddr = dev->base_addr;
u_char prom[32];
int i, j;
/* This is lifted straight from drivers/net/ne.c */
struct {
u_char value, offset;
} program_seq[] = {
{E8390_NODMA+E8390_PAGE0+E8390_STOP, E8390_CMD}, /* Select page 0*/
{0x48, EN0_DCFG}, /* Set byte-wide (0x48) access. */
{0x00, EN0_RCNTLO}, /* Clear the count regs. */
{0x00, EN0_RCNTHI},
{0x00, EN0_IMR}, /* Mask completion irq. */
{0xFF, EN0_ISR},
{E8390_RXOFF, EN0_RXCR}, /* 0x20 Set to monitor */
{E8390_TXOFF, EN0_TXCR}, /* 0x02 and loopback mode. */
{32, EN0_RCNTLO},
{0x00, EN0_RCNTHI},
{0x00, EN0_RSARLO}, /* DMA starting at 0x0000. */
{0x00, EN0_RSARHI},
{E8390_RREAD+E8390_START, E8390_CMD},
};
pcnet_reset_8390(dev);
mdelay(10);
for (i = 0; i < ARRAY_SIZE(program_seq); i++)
outb_p(program_seq[i].value, ioaddr + program_seq[i].offset);
for (i = 0; i < 32; i++)
prom[i] = inb(ioaddr + PCNET_DATAPORT);
for (i = 0; i < NR_INFO; i++) {
if ((prom[0] == hw_info[i].a0) &&
(prom[2] == hw_info[i].a1) &&
(prom[4] == hw_info[i].a2))
break;
}
if ((i < NR_INFO) || ((prom[28] == 0x57) && (prom[30] == 0x57))) {
for (j = 0; j < 6; j++)
dev->dev_addr[j] = prom[j<<1];
return (i < NR_INFO) ? hw_info+i : &default_info;
}
return NULL;
} /* get_prom */
/*======================================================================
For DL10019 based cards, like the Linksys EtherFast
======================================================================*/
static hw_info_t *get_dl10019(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
int i;
u_char sum;
for (sum = 0, i = 0x14; i < 0x1c; i++)
sum += inb_p(dev->base_addr + i);
if (sum != 0xff)
return NULL;
for (i = 0; i < 6; i++)
dev->dev_addr[i] = inb_p(dev->base_addr + 0x14 + i);
i = inb(dev->base_addr + 0x1f);
return ((i == 0x91)||(i == 0x99)) ? &dl10022_info : &dl10019_info;
}
/*======================================================================
For Asix AX88190 based cards
======================================================================*/
static hw_info_t *get_ax88190(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
unsigned int ioaddr = dev->base_addr;
int i, j;
/* Not much of a test, but the alternatives are messy */
if (link->config_base != 0x03c0)
return NULL;
outb_p(0x01, ioaddr + EN0_DCFG); /* Set word-wide access. */
outb_p(0x00, ioaddr + EN0_RSARLO); /* DMA starting at 0x0400. */
outb_p(0x04, ioaddr + EN0_RSARHI);
outb_p(E8390_RREAD+E8390_START, ioaddr + E8390_CMD);
for (i = 0; i < 6; i += 2) {
j = inw(ioaddr + PCNET_DATAPORT);
dev->dev_addr[i] = j & 0xff;
dev->dev_addr[i+1] = j >> 8;
}
return NULL;
}
/*======================================================================
This should be totally unnecessary... but when we can't figure
out the hardware address any other way, we'll let the user hard
wire it when the module is initialized.
======================================================================*/
static hw_info_t *get_hwired(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
int i;
for (i = 0; i < 6; i++)
if (hw_addr[i] != 0) break;
if (i == 6)
return NULL;
for (i = 0; i < 6; i++)
dev->dev_addr[i] = hw_addr[i];
return &default_info;
} /* get_hwired */
static int try_io_port(struct pcmcia_device *link)
{
int j, ret;
link->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
link->resource[1]->flags &= ~IO_DATA_PATH_WIDTH;
if (link->resource[0]->end == 32) {
link->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO;
if (link->resource[1]->end > 0) {
/* for master/slave multifunction cards */
link->resource[1]->flags |= IO_DATA_PATH_WIDTH_8;
}
} else {
/* This should be two 16-port windows */
link->resource[0]->flags |= IO_DATA_PATH_WIDTH_8;
link->resource[1]->flags |= IO_DATA_PATH_WIDTH_16;
}
if (link->resource[0]->start == 0) {
for (j = 0; j < 0x400; j += 0x20) {
link->resource[0]->start = j ^ 0x300;
link->resource[1]->start = (j ^ 0x300) + 0x10;
link->io_lines = 16;
ret = pcmcia_request_io(link);
if (ret == 0)
return ret;
}
return ret;
} else {
return pcmcia_request_io(link);
}
}
static int pcnet_confcheck(struct pcmcia_device *p_dev, void *priv_data)
{
int *priv = priv_data;
int try = (*priv & 0x1);
*priv &= (p_dev->resource[2]->end >= 0x4000) ? 0x10 : ~0x10;
if (p_dev->config_index == 0)
return -EINVAL;
if (p_dev->resource[0]->end + p_dev->resource[1]->end < 32)
return -EINVAL;
if (try)
p_dev->io_lines = 16;
return try_io_port(p_dev);
}
static hw_info_t *pcnet_try_config(struct pcmcia_device *link,
int *has_shmem, int try)
{
struct net_device *dev = link->priv;
hw_info_t *local_hw_info;
pcnet_dev_t *info = PRIV(dev);
int priv = try;
int ret;
ret = pcmcia_loop_config(link, pcnet_confcheck, &priv);
if (ret) {
dev_warn(&link->dev, "no useable port range found\n");
return NULL;
}
*has_shmem = (priv & 0x10);
if (!link->irq)
return NULL;
if (resource_size(link->resource[1]) == 8)
link->config_flags |= CONF_ENABLE_SPKR;
if ((link->manf_id == MANFID_IBM) &&
(link->card_id == PRODID_IBM_HOME_AND_AWAY))
link->config_index |= 0x10;
ret = pcmcia_enable_device(link);
if (ret)
return NULL;
dev->irq = link->irq;
dev->base_addr = link->resource[0]->start;
if (info->flags & HAS_MISC_REG) {
if ((if_port == 1) || (if_port == 2))
dev->if_port = if_port;
else
dev_notice(&link->dev, "invalid if_port requested\n");
} else
dev->if_port = 0;
if ((link->config_base == 0x03c0) &&
(link->manf_id == 0x149) && (link->card_id == 0xc1ab)) {
dev_info(&link->dev,
"this is an AX88190 card - use axnet_cs instead.\n");
return NULL;
}
local_hw_info = get_hwinfo(link);
if (!local_hw_info)
local_hw_info = get_prom(link);
if (!local_hw_info)
local_hw_info = get_dl10019(link);
if (!local_hw_info)
local_hw_info = get_ax88190(link);
if (!local_hw_info)
local_hw_info = get_hwired(link);
return local_hw_info;
}
static int pcnet_config(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
pcnet_dev_t *info = PRIV(dev);
int start_pg, stop_pg, cm_offset;
int has_shmem = 0;
hw_info_t *local_hw_info;
dev_dbg(&link->dev, "pcnet_config\n");
local_hw_info = pcnet_try_config(link, &has_shmem, 0);
if (!local_hw_info) {
/* check whether forcing io_lines to 16 helps... */
pcmcia_disable_device(link);
local_hw_info = pcnet_try_config(link, &has_shmem, 1);
if (local_hw_info == NULL) {
dev_notice(&link->dev, "unable to read hardware net"
" address for io base %#3lx\n", dev->base_addr);
goto failed;
}
}
info->flags = local_hw_info->flags;
/* Check for user overrides */
info->flags |= (delay_output) ? DELAY_OUTPUT : 0;
if ((link->manf_id == MANFID_SOCKET) &&
((link->card_id == PRODID_SOCKET_LPE) ||
(link->card_id == PRODID_SOCKET_LPE_CF) ||
(link->card_id == PRODID_SOCKET_EIO)))
info->flags &= ~USE_BIG_BUF;
if (!use_big_buf)
info->flags &= ~USE_BIG_BUF;
if (info->flags & USE_BIG_BUF) {
start_pg = SOCKET_START_PG;
stop_pg = SOCKET_STOP_PG;
cm_offset = 0x10000;
} else {
start_pg = PCNET_START_PG;
stop_pg = PCNET_STOP_PG;
cm_offset = 0;
}
/* has_shmem is ignored if use_shmem != -1 */
if ((use_shmem == 0) || (!has_shmem && (use_shmem == -1)) ||
(setup_shmem_window(link, start_pg, stop_pg, cm_offset) != 0))
setup_dma_config(link, start_pg, stop_pg);
ei_status.name = "NE2000";
ei_status.word16 = 1;
ei_status.reset_8390 = pcnet_reset_8390;
if (info->flags & (IS_DL10019|IS_DL10022))
mii_phy_probe(dev);
SET_NETDEV_DEV(dev, &link->dev);
if (register_netdev(dev) != 0) {
pr_notice("register_netdev() failed\n");
goto failed;
}
if (info->flags & (IS_DL10019|IS_DL10022)) {
u_char id = inb(dev->base_addr + 0x1a);
netdev_info(dev, "NE2000 (DL100%d rev %02x): ",
(info->flags & IS_DL10022) ? 22 : 19, id);
if (info->pna_phy)
pr_cont("PNA, ");
} else {
netdev_info(dev, "NE2000 Compatible: ");
}
pr_cont("io %#3lx, irq %d,", dev->base_addr, dev->irq);
if (info->flags & USE_SHMEM)
pr_cont(" mem %#5lx,", dev->mem_start);
if (info->flags & HAS_MISC_REG)
pr_cont(" %s xcvr,", if_names[dev->if_port]);
pr_cont(" hw_addr %pM\n", dev->dev_addr);
return 0;
failed:
pcnet_release(link);
return -ENODEV;
} /* pcnet_config */
static void pcnet_release(struct pcmcia_device *link)
{
pcnet_dev_t *info = PRIV(link->priv);
dev_dbg(&link->dev, "pcnet_release\n");
if (info->flags & USE_SHMEM)
iounmap(info->base);
pcmcia_disable_device(link);
}
static int pcnet_suspend(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
if (link->open)
netif_device_detach(dev);
return 0;
}
static int pcnet_resume(struct pcmcia_device *link)
{
struct net_device *dev = link->priv;
if (link->open) {
pcnet_reset_8390(dev);
NS8390_init(dev, 1);
netif_device_attach(dev);
}
return 0;
}
/*======================================================================
MII interface support for DL10019 and DL10022 based cards
On the DL10019, the MII IO direction bit is 0x10; on the DL10022
it is 0x20. Setting both bits seems to work on both card types.
======================================================================*/
#define DLINK_GPIO 0x1c
#define DLINK_DIAG 0x1d
#define DLINK_EEPROM 0x1e
#define MDIO_SHIFT_CLK 0x80
#define MDIO_DATA_OUT 0x40
#define MDIO_DIR_WRITE 0x30
#define MDIO_DATA_WRITE0 (MDIO_DIR_WRITE)
#define MDIO_DATA_WRITE1 (MDIO_DIR_WRITE | MDIO_DATA_OUT)
#define MDIO_DATA_READ 0x10
#define MDIO_MASK 0x0f
static void mdio_sync(unsigned int addr)
{
int bits, mask = inb(addr) & MDIO_MASK;
for (bits = 0; bits < 32; bits++) {
outb(mask | MDIO_DATA_WRITE1, addr);
outb(mask | MDIO_DATA_WRITE1 | MDIO_SHIFT_CLK, addr);
}
}
static int mdio_read(unsigned int addr, int phy_id, int loc)
{
u_int cmd = (0x06<<10)|(phy_id<<5)|loc;
int i, retval = 0, mask = inb(addr) & MDIO_MASK;
mdio_sync(addr);
for (i = 13; i >= 0; i--) {
int dat = (cmd&(1<<i)) ? MDIO_DATA_WRITE1 : MDIO_DATA_WRITE0;
outb(mask | dat, addr);
outb(mask | dat | MDIO_SHIFT_CLK, addr);
}
for (i = 19; i > 0; i--) {
outb(mask, addr);
retval = (retval << 1) | ((inb(addr) & MDIO_DATA_READ) != 0);
outb(mask | MDIO_SHIFT_CLK, addr);
}
return (retval>>1) & 0xffff;
}
static void mdio_write(unsigned int addr, int phy_id, int loc, int value)
{
u_int cmd = (0x05<<28)|(phy_id<<23)|(loc<<18)|(1<<17)|value;
int i, mask = inb(addr) & MDIO_MASK;
mdio_sync(addr);
for (i = 31; i >= 0; i--) {
int dat = (cmd&(1<<i)) ? MDIO_DATA_WRITE1 : MDIO_DATA_WRITE0;
outb(mask | dat, addr);
outb(mask | dat | MDIO_SHIFT_CLK, addr);
}
for (i = 1; i >= 0; i--) {
outb(mask, addr);
outb(mask | MDIO_SHIFT_CLK, addr);
}
}
/*======================================================================
EEPROM access routines for DL10019 and DL10022 based cards
======================================================================*/
#define EE_EEP 0x40
#define EE_ASIC 0x10
#define EE_CS 0x08
#define EE_CK 0x04
#define EE_DO 0x02
#define EE_DI 0x01
#define EE_ADOT 0x01 /* DataOut for ASIC */
#define EE_READ_CMD 0x06
#define DL19FDUPLX 0x0400 /* DL10019 Full duplex mode */
static int read_eeprom(unsigned int ioaddr, int location)
{
int i, retval = 0;
unsigned int ee_addr = ioaddr + DLINK_EEPROM;
int read_cmd = location | (EE_READ_CMD << 8);
outb(0, ee_addr);
outb(EE_EEP|EE_CS, ee_addr);
/* Shift the read command bits out. */
for (i = 10; i >= 0; i--) {
short dataval = (read_cmd & (1 << i)) ? EE_DO : 0;
outb_p(EE_EEP|EE_CS|dataval, ee_addr);
outb_p(EE_EEP|EE_CS|dataval|EE_CK, ee_addr);
}
outb(EE_EEP|EE_CS, ee_addr);
for (i = 16; i > 0; i--) {
outb_p(EE_EEP|EE_CS | EE_CK, ee_addr);
retval = (retval << 1) | ((inb(ee_addr) & EE_DI) ? 1 : 0);
outb_p(EE_EEP|EE_CS, ee_addr);
}
/* Terminate the EEPROM access. */
outb(0, ee_addr);
return retval;
}
/*
The internal ASIC registers can be changed by EEPROM READ access
with EE_ASIC bit set.
In ASIC mode, EE_ADOT is used to output the data to the ASIC.
*/
static void write_asic(unsigned int ioaddr, int location, short asic_data)
{
int i;
unsigned int ee_addr = ioaddr + DLINK_EEPROM;
short dataval;
int read_cmd = location | (EE_READ_CMD << 8);
asic_data |= read_eeprom(ioaddr, location);
outb(0, ee_addr);
outb(EE_ASIC|EE_CS|EE_DI, ee_addr);
read_cmd = read_cmd >> 1;
/* Shift the read command bits out. */
for (i = 9; i >= 0; i--) {
dataval = (read_cmd & (1 << i)) ? EE_DO : 0;
outb_p(EE_ASIC|EE_CS|EE_DI|dataval, ee_addr);
outb_p(EE_ASIC|EE_CS|EE_DI|dataval|EE_CK, ee_addr);
outb_p(EE_ASIC|EE_CS|EE_DI|dataval, ee_addr);
}
// sync
outb(EE_ASIC|EE_CS, ee_addr);
outb(EE_ASIC|EE_CS|EE_CK, ee_addr);
outb(EE_ASIC|EE_CS, ee_addr);
for (i = 15; i >= 0; i--) {
dataval = (asic_data & (1 << i)) ? EE_ADOT : 0;
outb_p(EE_ASIC|EE_CS|dataval, ee_addr);
outb_p(EE_ASIC|EE_CS|dataval|EE_CK, ee_addr);
outb_p(EE_ASIC|EE_CS|dataval, ee_addr);
}
/* Terminate the ASIC access. */
outb(EE_ASIC|EE_DI, ee_addr);
outb(EE_ASIC|EE_DI| EE_CK, ee_addr);
outb(EE_ASIC|EE_DI, ee_addr);
outb(0, ee_addr);
}
/*====================================================================*/
static void set_misc_reg(struct net_device *dev)
{
unsigned int nic_base = dev->base_addr;
pcnet_dev_t *info = PRIV(dev);
u_char tmp;
if (info->flags & HAS_MISC_REG) {
tmp = inb_p(nic_base + PCNET_MISC) & ~3;
if (dev->if_port == 2)
tmp |= 1;
if (info->flags & USE_BIG_BUF)
tmp |= 2;
if (info->flags & HAS_IBM_MISC)
tmp |= 8;
outb_p(tmp, nic_base + PCNET_MISC);
}
if (info->flags & IS_DL10022) {
if (info->flags & HAS_MII) {
/* Advertise 100F, 100H, 10F, 10H */
mdio_write(nic_base + DLINK_GPIO, info->eth_phy, 4, 0x01e1);
/* Restart MII autonegotiation */
mdio_write(nic_base + DLINK_GPIO, info->eth_phy, 0, 0x0000);
mdio_write(nic_base + DLINK_GPIO, info->eth_phy, 0, 0x1200);
info->mii_reset = jiffies;
} else {
outb(full_duplex ? 4 : 0, nic_base + DLINK_DIAG);
}
} else if (info->flags & IS_DL10019) {
/* Advertise 100F, 100H, 10F, 10H */
mdio_write(nic_base + DLINK_GPIO, info->eth_phy, 4, 0x01e1);
/* Restart MII autonegotiation */
mdio_write(nic_base + DLINK_GPIO, info->eth_phy, 0, 0x0000);
mdio_write(nic_base + DLINK_GPIO, info->eth_phy, 0, 0x1200);
}
}
/*====================================================================*/
static void mii_phy_probe(struct net_device *dev)
{
pcnet_dev_t *info = PRIV(dev);
unsigned int mii_addr = dev->base_addr + DLINK_GPIO;
int i;
u_int tmp, phyid;
for (i = 31; i >= 0; i--) {
tmp = mdio_read(mii_addr, i, 1);
if ((tmp == 0) || (tmp == 0xffff))
continue;
tmp = mdio_read(mii_addr, i, MII_PHYID_REG1);
phyid = tmp << 16;
phyid |= mdio_read(mii_addr, i, MII_PHYID_REG2);
phyid &= MII_PHYID_REV_MASK;
netdev_dbg(dev, "MII at %d is 0x%08x\n", i, phyid);
if (phyid == AM79C9XX_HOME_PHY) {
info->pna_phy = i;
} else if (phyid != AM79C9XX_ETH_PHY) {
info->eth_phy = i;
}
}
}
static int pcnet_open(struct net_device *dev)
{
int ret;
pcnet_dev_t *info = PRIV(dev);
struct pcmcia_device *link = info->p_dev;
unsigned int nic_base = dev->base_addr;
dev_dbg(&link->dev, "pcnet_open('%s')\n", dev->name);
if (!pcmcia_dev_present(link))
return -ENODEV;
set_misc_reg(dev);
outb_p(0xFF, nic_base + EN0_ISR); /* Clear bogus intr. */
ret = request_irq(dev->irq, ei_irq_wrapper, IRQF_SHARED, dev->name, dev);
if (ret)
return ret;
link->open++;
info->phy_id = info->eth_phy;
info->link_status = 0x00;
init_timer(&info->watchdog);
info->watchdog.function = ei_watchdog;
info->watchdog.data = (u_long)dev;
info->watchdog.expires = jiffies + HZ;
add_timer(&info->watchdog);
return ei_open(dev);
} /* pcnet_open */
/*====================================================================*/
static int pcnet_close(struct net_device *dev)
{
pcnet_dev_t *info = PRIV(dev);
struct pcmcia_device *link = info->p_dev;
dev_dbg(&link->dev, "pcnet_close('%s')\n", dev->name);
ei_close(dev);
free_irq(dev->irq, dev);
link->open--;
netif_stop_queue(dev);
del_timer_sync(&info->watchdog);
return 0;
} /* pcnet_close */
/*======================================================================
Hard reset the card. This used to pause for the same period that
a 8390 reset command required, but that shouldn't be necessary.
======================================================================*/
static void pcnet_reset_8390(struct net_device *dev)
{
unsigned int nic_base = dev->base_addr;
int i;
ei_status.txing = ei_status.dmaing = 0;
outb_p(E8390_NODMA+E8390_PAGE0+E8390_STOP, nic_base + E8390_CMD);
outb(inb(nic_base + PCNET_RESET), nic_base + PCNET_RESET);
for (i = 0; i < 100; i++) {
if ((inb_p(nic_base+EN0_ISR) & ENISR_RESET) != 0)
break;
udelay(100);
}
outb_p(ENISR_RESET, nic_base + EN0_ISR); /* Ack intr. */
if (i == 100)
netdev_err(dev, "pcnet_reset_8390() did not complete.\n");
set_misc_reg(dev);
} /* pcnet_reset_8390 */
/*====================================================================*/
static int set_config(struct net_device *dev, struct ifmap *map)
{
pcnet_dev_t *info = PRIV(dev);
if ((map->port != (u_char)(-1)) && (map->port != dev->if_port)) {
if (!(info->flags & HAS_MISC_REG))
return -EOPNOTSUPP;
else if ((map->port < 1) || (map->port > 2))
return -EINVAL;
dev->if_port = map->port;
netdev_info(dev, "switched to %s port\n", if_names[dev->if_port]);
NS8390_init(dev, 1);
}
return 0;
}
/*====================================================================*/
static irqreturn_t ei_irq_wrapper(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
pcnet_dev_t *info;
irqreturn_t ret = ei_interrupt(irq, dev_id);
if (ret == IRQ_HANDLED) {
info = PRIV(dev);
info->stale = 0;
}
return ret;
}
static void ei_watchdog(u_long arg)
{
struct net_device *dev = (struct net_device *)arg;
pcnet_dev_t *info = PRIV(dev);
unsigned int nic_base = dev->base_addr;
unsigned int mii_addr = nic_base + DLINK_GPIO;
u_short link;
if (!netif_device_present(dev)) goto reschedule;
/* Check for pending interrupt with expired latency timer: with
this, we can limp along even if the interrupt is blocked */
if (info->stale++ && (inb_p(nic_base + EN0_ISR) & ENISR_ALL)) {
if (!info->fast_poll)
netdev_info(dev, "interrupt(s) dropped!\n");
ei_irq_wrapper(dev->irq, dev);
info->fast_poll = HZ;
}
if (info->fast_poll) {
info->fast_poll--;
info->watchdog.expires = jiffies + 1;
add_timer(&info->watchdog);
return;
}
if (!(info->flags & HAS_MII))
goto reschedule;
mdio_read(mii_addr, info->phy_id, 1);
link = mdio_read(mii_addr, info->phy_id, 1);
if (!link || (link == 0xffff)) {
if (info->eth_phy) {
info->phy_id = info->eth_phy = 0;
} else {
netdev_info(dev, "MII is missing!\n");
info->flags &= ~HAS_MII;
}
goto reschedule;
}
link &= 0x0004;
if (link != info->link_status) {
u_short p = mdio_read(mii_addr, info->phy_id, 5);
netdev_info(dev, "%s link beat\n", link ? "found" : "lost");
if (link && (info->flags & IS_DL10022)) {
/* Disable collision detection on full duplex links */
outb((p & 0x0140) ? 4 : 0, nic_base + DLINK_DIAG);
} else if (link && (info->flags & IS_DL10019)) {
/* Disable collision detection on full duplex links */
write_asic(dev->base_addr, 4, (p & 0x140) ? DL19FDUPLX : 0);
}
if (link) {
if (info->phy_id == info->eth_phy) {
if (p)
netdev_info(dev, "autonegotiation complete: "
"%sbaseT-%cD selected\n",
((p & 0x0180) ? "100" : "10"),
((p & 0x0140) ? 'F' : 'H'));
else
netdev_info(dev, "link partner did not autonegotiate\n");
}
NS8390_init(dev, 1);
}
info->link_status = link;
}
if (info->pna_phy && time_after(jiffies, info->mii_reset + 6*HZ)) {
link = mdio_read(mii_addr, info->eth_phy, 1) & 0x0004;
if (((info->phy_id == info->pna_phy) && link) ||
((info->phy_id != info->pna_phy) && !link)) {
/* isolate this MII and try flipping to the other one */
mdio_write(mii_addr, info->phy_id, 0, 0x0400);
info->phy_id ^= info->pna_phy ^ info->eth_phy;
netdev_info(dev, "switched to %s transceiver\n",
(info->phy_id == info->eth_phy) ? "ethernet" : "PNA");
mdio_write(mii_addr, info->phy_id, 0,
(info->phy_id == info->eth_phy) ? 0x1000 : 0);
info->link_status = 0;
info->mii_reset = jiffies;
}
}
reschedule:
info->watchdog.expires = jiffies + HZ;
add_timer(&info->watchdog);
}
/*====================================================================*/
static int ei_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
pcnet_dev_t *info = PRIV(dev);
struct mii_ioctl_data *data = if_mii(rq);
unsigned int mii_addr = dev->base_addr + DLINK_GPIO;
if (!(info->flags & (IS_DL10019|IS_DL10022)))
return -EINVAL;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = info->phy_id;
case SIOCGMIIREG: /* Read MII PHY register. */
data->val_out = mdio_read(mii_addr, data->phy_id, data->reg_num & 0x1f);
return 0;
case SIOCSMIIREG: /* Write MII PHY register. */
mdio_write(mii_addr, data->phy_id, data->reg_num & 0x1f, data->val_in);
return 0;
}
return -EOPNOTSUPP;
}
/*====================================================================*/
static void dma_get_8390_hdr(struct net_device *dev,
struct e8390_pkt_hdr *hdr,
int ring_page)
{
unsigned int nic_base = dev->base_addr;
if (ei_status.dmaing) {
netdev_notice(dev, "DMAing conflict in dma_block_input."
"[DMAstat:%1x][irqlock:%1x]\n",
ei_status.dmaing, ei_status.irqlock);
return;
}
ei_status.dmaing |= 0x01;
outb_p(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base + PCNET_CMD);
outb_p(sizeof(struct e8390_pkt_hdr), nic_base + EN0_RCNTLO);
outb_p(0, nic_base + EN0_RCNTHI);
outb_p(0, nic_base + EN0_RSARLO); /* On page boundary */
outb_p(ring_page, nic_base + EN0_RSARHI);
outb_p(E8390_RREAD+E8390_START, nic_base + PCNET_CMD);
insw(nic_base + PCNET_DATAPORT, hdr,
sizeof(struct e8390_pkt_hdr)>>1);
/* Fix for big endian systems */
hdr->count = le16_to_cpu(hdr->count);
outb_p(ENISR_RDC, nic_base + EN0_ISR); /* Ack intr. */
ei_status.dmaing &= ~0x01;
}
/*====================================================================*/
static void dma_block_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset)
{
unsigned int nic_base = dev->base_addr;
int xfer_count = count;
char *buf = skb->data;
if ((ei_debug > 4) && (count != 4))
netdev_dbg(dev, "[bi=%d]\n", count+4);
if (ei_status.dmaing) {
netdev_notice(dev, "DMAing conflict in dma_block_input."
"[DMAstat:%1x][irqlock:%1x]\n",
ei_status.dmaing, ei_status.irqlock);
return;
}
ei_status.dmaing |= 0x01;
outb_p(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base + PCNET_CMD);
outb_p(count & 0xff, nic_base + EN0_RCNTLO);
outb_p(count >> 8, nic_base + EN0_RCNTHI);
outb_p(ring_offset & 0xff, nic_base + EN0_RSARLO);
outb_p(ring_offset >> 8, nic_base + EN0_RSARHI);
outb_p(E8390_RREAD+E8390_START, nic_base + PCNET_CMD);
insw(nic_base + PCNET_DATAPORT,buf,count>>1);
if (count & 0x01)
buf[count-1] = inb(nic_base + PCNET_DATAPORT), xfer_count++;
/* This was for the ALPHA version only, but enough people have been
encountering problems that it is still here. */
#ifdef PCMCIA_DEBUG
if (ei_debug > 4) { /* DMA termination address check... */
int addr, tries = 20;
do {
/* DON'T check for 'inb_p(EN0_ISR) & ENISR_RDC' here
-- it's broken for Rx on some cards! */
int high = inb_p(nic_base + EN0_RSARHI);
int low = inb_p(nic_base + EN0_RSARLO);
addr = (high << 8) + low;
if (((ring_offset + xfer_count) & 0xff) == (addr & 0xff))
break;
} while (--tries > 0);
if (tries <= 0)
netdev_notice(dev, "RX transfer address mismatch,"
"%#4.4x (expected) vs. %#4.4x (actual).\n",
ring_offset + xfer_count, addr);
}
#endif
outb_p(ENISR_RDC, nic_base + EN0_ISR); /* Ack intr. */
ei_status.dmaing &= ~0x01;
} /* dma_block_input */
/*====================================================================*/
static void dma_block_output(struct net_device *dev, int count,
const u_char *buf, const int start_page)
{
unsigned int nic_base = dev->base_addr;
pcnet_dev_t *info = PRIV(dev);
#ifdef PCMCIA_DEBUG
int retries = 0;
#endif
u_long dma_start;
#ifdef PCMCIA_DEBUG
if (ei_debug > 4)
netdev_dbg(dev, "[bo=%d]\n", count);
#endif
/* Round the count up for word writes. Do we need to do this?
What effect will an odd byte count have on the 8390?
I should check someday. */
if (count & 0x01)
count++;
if (ei_status.dmaing) {
netdev_notice(dev, "DMAing conflict in dma_block_output."
"[DMAstat:%1x][irqlock:%1x]\n",
ei_status.dmaing, ei_status.irqlock);
return;
}
ei_status.dmaing |= 0x01;
/* We should already be in page 0, but to be safe... */
outb_p(E8390_PAGE0+E8390_START+E8390_NODMA, nic_base+PCNET_CMD);
#ifdef PCMCIA_DEBUG
retry:
#endif
outb_p(ENISR_RDC, nic_base + EN0_ISR);
/* Now the normal output. */
outb_p(count & 0xff, nic_base + EN0_RCNTLO);
outb_p(count >> 8, nic_base + EN0_RCNTHI);
outb_p(0x00, nic_base + EN0_RSARLO);
outb_p(start_page, nic_base + EN0_RSARHI);
outb_p(E8390_RWRITE+E8390_START, nic_base + PCNET_CMD);
outsw(nic_base + PCNET_DATAPORT, buf, count>>1);
dma_start = jiffies;
#ifdef PCMCIA_DEBUG
/* This was for the ALPHA version only, but enough people have been
encountering problems that it is still here. */
if (ei_debug > 4) { /* DMA termination address check... */
int addr, tries = 20;
do {
int high = inb_p(nic_base + EN0_RSARHI);
int low = inb_p(nic_base + EN0_RSARLO);
addr = (high << 8) + low;
if ((start_page << 8) + count == addr)
break;
} while (--tries > 0);
if (tries <= 0) {
netdev_notice(dev, "Tx packet transfer address mismatch,"
"%#4.4x (expected) vs. %#4.4x (actual).\n",
(start_page << 8) + count, addr);
if (retries++ == 0)
goto retry;
}
}
#endif
while ((inb_p(nic_base + EN0_ISR) & ENISR_RDC) == 0)
if (time_after(jiffies, dma_start + PCNET_RDC_TIMEOUT)) {
netdev_notice(dev, "timeout waiting for Tx RDC.\n");
pcnet_reset_8390(dev);
NS8390_init(dev, 1);
break;
}
outb_p(ENISR_RDC, nic_base + EN0_ISR); /* Ack intr. */
if (info->flags & DELAY_OUTPUT)
udelay((long)delay_time);
ei_status.dmaing &= ~0x01;
}
/*====================================================================*/
static int setup_dma_config(struct pcmcia_device *link, int start_pg,
int stop_pg)
{
struct net_device *dev = link->priv;
ei_status.tx_start_page = start_pg;
ei_status.rx_start_page = start_pg + TX_PAGES;
ei_status.stop_page = stop_pg;
/* set up block i/o functions */
ei_status.get_8390_hdr = dma_get_8390_hdr;
ei_status.block_input = dma_block_input;
ei_status.block_output = dma_block_output;
return 0;
}
/*====================================================================*/
static void copyin(void *dest, void __iomem *src, int c)
{
u_short *d = dest;
u_short __iomem *s = src;
int odd;
if (c <= 0)
return;
odd = (c & 1); c >>= 1;
if (c) {
do { *d++ = __raw_readw(s++); } while (--c);
}
/* get last byte by fetching a word and masking */
if (odd)
*((u_char *)d) = readw(s) & 0xff;
}
static void copyout(void __iomem *dest, const void *src, int c)
{
u_short __iomem *d = dest;
const u_short *s = src;
int odd;
if (c <= 0)
return;
odd = (c & 1); c >>= 1;
if (c) {
do { __raw_writew(*s++, d++); } while (--c);
}
/* copy last byte doing a read-modify-write */
if (odd)
writew((readw(d) & 0xff00) | *(u_char *)s, d);
}
/*====================================================================*/
static void shmem_get_8390_hdr(struct net_device *dev,
struct e8390_pkt_hdr *hdr,
int ring_page)
{
void __iomem *xfer_start = ei_status.mem + (TX_PAGES<<8)
+ (ring_page << 8)
- (ei_status.rx_start_page << 8);
copyin(hdr, xfer_start, sizeof(struct e8390_pkt_hdr));
/* Fix for big endian systems */
hdr->count = le16_to_cpu(hdr->count);
}
/*====================================================================*/
static void shmem_block_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset)
{
void __iomem *base = ei_status.mem;
unsigned long offset = (TX_PAGES<<8) + ring_offset
- (ei_status.rx_start_page << 8);
char *buf = skb->data;
if (offset + count > ei_status.priv) {
/* We must wrap the input move. */
int semi_count = ei_status.priv - offset;
copyin(buf, base + offset, semi_count);
buf += semi_count;
offset = TX_PAGES<<8;
count -= semi_count;
}
copyin(buf, base + offset, count);
}
/*====================================================================*/
static void shmem_block_output(struct net_device *dev, int count,
const u_char *buf, const int start_page)
{
void __iomem *shmem = ei_status.mem + (start_page << 8);
shmem -= ei_status.tx_start_page << 8;
copyout(shmem, buf, count);
}
/*====================================================================*/
static int setup_shmem_window(struct pcmcia_device *link, int start_pg,
int stop_pg, int cm_offset)
{
struct net_device *dev = link->priv;
pcnet_dev_t *info = PRIV(dev);
int i, window_size, offset, ret;
window_size = (stop_pg - start_pg) << 8;
if (window_size > 32 * 1024)
window_size = 32 * 1024;
/* Make sure it's a power of two. */
window_size = roundup_pow_of_two(window_size);
/* Allocate a memory window */
link->resource[3]->flags |= WIN_DATA_WIDTH_16|WIN_MEMORY_TYPE_CM|WIN_ENABLE;
link->resource[3]->flags |= WIN_USE_WAIT;
link->resource[3]->start = 0; link->resource[3]->end = window_size;
ret = pcmcia_request_window(link, link->resource[3], mem_speed);
if (ret)
goto failed;
offset = (start_pg << 8) + cm_offset;
offset -= offset % window_size;
ret = pcmcia_map_mem_page(link, link->resource[3], offset);
if (ret)
goto failed;
/* Try scribbling on the buffer */
info->base = ioremap(link->resource[3]->start,
resource_size(link->resource[3]));
for (i = 0; i < (TX_PAGES<<8); i += 2)
__raw_writew((i>>1), info->base+offset+i);
udelay(100);
for (i = 0; i < (TX_PAGES<<8); i += 2)
if (__raw_readw(info->base+offset+i) != (i>>1)) break;
pcnet_reset_8390(dev);
if (i != (TX_PAGES<<8)) {
iounmap(info->base);
pcmcia_release_window(link, link->resource[3]);
info->base = NULL;
goto failed;
}
ei_status.mem = info->base + offset;
ei_status.priv = resource_size(link->resource[3]);
dev->mem_start = (u_long)ei_status.mem;
dev->mem_end = dev->mem_start + resource_size(link->resource[3]);
ei_status.tx_start_page = start_pg;
ei_status.rx_start_page = start_pg + TX_PAGES;
ei_status.stop_page = start_pg + (
(resource_size(link->resource[3]) - offset) >> 8);
/* set up block i/o functions */
ei_status.get_8390_hdr = shmem_get_8390_hdr;
ei_status.block_input = shmem_block_input;
ei_status.block_output = shmem_block_output;
info->flags |= USE_SHMEM;
return 0;
failed:
return 1;
}
/*====================================================================*/
static const struct pcmcia_device_id pcnet_ids[] = {
PCMCIA_PFC_DEVICE_MANF_CARD(0, 0x0057, 0x0021),
PCMCIA_PFC_DEVICE_MANF_CARD(0, 0x0104, 0x000a),
PCMCIA_PFC_DEVICE_MANF_CARD(0, 0x0105, 0xea15),
PCMCIA_PFC_DEVICE_MANF_CARD(0, 0x0143, 0x3341),
PCMCIA_PFC_DEVICE_MANF_CARD(0, 0x0143, 0xc0ab),
PCMCIA_PFC_DEVICE_MANF_CARD(0, 0x021b, 0x0101),
PCMCIA_PFC_DEVICE_MANF_CARD(0, 0x08a1, 0xc0ab),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "AnyCom", "Fast Ethernet + 56K COMBO", 0x578ba6e7, 0xb0ac62c4),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "ATKK", "LM33-PCM-T", 0xba9eb7e2, 0x077c174e),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "D-Link", "DME336T", 0x1a424a1c, 0xb23897ff),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "Grey Cell", "GCS3000", 0x2a151fac, 0x48b932ae),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "Linksys", "EtherFast 10&100 + 56K PC Card (PCMLM56)", 0x0733cc81, 0xb3765033),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "LINKSYS", "PCMLM336", 0xf7cb0b07, 0x7a821b58),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "MICRO RESEARCH", "COMBO-L/M-336", 0xb2ced065, 0x3ced0555),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "PCMCIAs", "ComboCard", 0xdcfe12d3, 0xcd8906cc),
PCMCIA_PFC_DEVICE_PROD_ID12(0, "PCMCIAs", "LanModem", 0xdcfe12d3, 0xc67c648f),
PCMCIA_MFC_DEVICE_PROD_ID12(0, "IBM", "Home and Away 28.8 PC Card ", 0xb569a6e5, 0x5bd4ff2c),
PCMCIA_MFC_DEVICE_PROD_ID12(0, "IBM", "Home and Away Credit Card Adapter", 0xb569a6e5, 0x4bdf15c3),
PCMCIA_MFC_DEVICE_PROD_ID12(0, "IBM", "w95 Home and Away Credit Card ", 0xb569a6e5, 0xae911c15),
PCMCIA_MFC_DEVICE_PROD_ID123(0, "APEX DATA", "MULTICARD", "ETHERNET-MODEM", 0x11c2da09, 0x7289dc5d, 0xaad95e1f),
PCMCIA_MFC_DEVICE_PROD_ID2(0, "FAX/Modem/Ethernet Combo Card ", 0x1ed59302),
PCMCIA_DEVICE_MANF_CARD(0x0057, 0x1004),
PCMCIA_DEVICE_MANF_CARD(0x0104, 0x000d),
PCMCIA_DEVICE_MANF_CARD(0x0104, 0x0075),
PCMCIA_DEVICE_MANF_CARD(0x0104, 0x0145),
PCMCIA_DEVICE_MANF_CARD(0x0149, 0x0230),
PCMCIA_DEVICE_MANF_CARD(0x0149, 0x4530),
PCMCIA_DEVICE_MANF_CARD(0x0149, 0xc1ab),
PCMCIA_DEVICE_MANF_CARD(0x0186, 0x0110),
PCMCIA_DEVICE_MANF_CARD(0x01bf, 0x8041),
PCMCIA_DEVICE_MANF_CARD(0x0213, 0x2452),
PCMCIA_DEVICE_MANF_CARD(0x026f, 0x0300),
PCMCIA_DEVICE_MANF_CARD(0x026f, 0x0307),
PCMCIA_DEVICE_MANF_CARD(0x026f, 0x030a),
PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1103),
PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1121),
PCMCIA_DEVICE_PROD_ID12("2408LAN", "Ethernet", 0x352fff7f, 0x00b2e941),
PCMCIA_DEVICE_PROD_ID1234("Socket", "CF 10/100 Ethernet Card", "Revision B", "05/11/06", 0xb38bcc2e, 0x4de88352, 0xeaca6c8d, 0x7e57c22e),
PCMCIA_DEVICE_PROD_ID123("Cardwell", "PCMCIA", "ETHERNET", 0x9533672e, 0x281f1c5d, 0x3ff7175b),
PCMCIA_DEVICE_PROD_ID123("CNet ", "CN30BC", "ETHERNET", 0x9fe55d3d, 0x85601198, 0x3ff7175b),
PCMCIA_DEVICE_PROD_ID123("Digital", "Ethernet", "Adapter", 0x9999ab35, 0x00b2e941, 0x4b0d829e),
PCMCIA_DEVICE_PROD_ID123("Edimax Technology Inc.", "PCMCIA", "Ethernet Card", 0x738a0019, 0x281f1c5d, 0x5e9d92c0),
PCMCIA_DEVICE_PROD_ID123("EFA ", "EFA207", "ETHERNET", 0x3d294be4, 0xeb9aab6c, 0x3ff7175b),
PCMCIA_DEVICE_PROD_ID123("I-O DATA", "PCLA", "ETHERNET", 0x1d55d7ec, 0xe4c64d34, 0x3ff7175b),
PCMCIA_DEVICE_PROD_ID123("IO DATA", "PCLATE", "ETHERNET", 0x547e66dc, 0x6b260753, 0x3ff7175b),
PCMCIA_DEVICE_PROD_ID123("KingMax Technology Inc.", "EN10-T2", "PCMCIA Ethernet Card", 0x932b7189, 0x699e4436, 0x6f6652e0),
PCMCIA_DEVICE_PROD_ID123("PCMCIA", "PCMCIA-ETHERNET-CARD", "UE2216", 0x281f1c5d, 0xd4cd2f20, 0xb87add82),
PCMCIA_DEVICE_PROD_ID123("PCMCIA", "PCMCIA-ETHERNET-CARD", "UE2620", 0x281f1c5d, 0xd4cd2f20, 0x7d3d83a8),
PCMCIA_DEVICE_PROD_ID1("2412LAN", 0x67f236ab),
PCMCIA_DEVICE_PROD_ID12("ACCTON", "EN2212", 0xdfc6b5b2, 0xcb112a11),
PCMCIA_DEVICE_PROD_ID12("ACCTON", "EN2216-PCMCIA-ETHERNET", 0xdfc6b5b2, 0x5542bfff),
PCMCIA_DEVICE_PROD_ID12("Allied Telesis, K.K.", "CentreCOM LA100-PCM-T V2 100/10M LAN PC Card", 0xbb7fbdd7, 0xcd91cc68),
PCMCIA_DEVICE_PROD_ID12("Allied Telesis K.K.", "LA100-PCM V2", 0x36634a66, 0xc6d05997),
PCMCIA_DEVICE_PROD_ID12("Allied Telesis, K.K.", "CentreCOM LA-PCM_V2", 0xbb7fBdd7, 0x28e299f8),
PCMCIA_DEVICE_PROD_ID12("Allied Telesis K.K.", "LA-PCM V3", 0x36634a66, 0x62241d96),
PCMCIA_DEVICE_PROD_ID12("AmbiCom", "AMB8010", 0x5070a7f9, 0x82f96e96),
PCMCIA_DEVICE_PROD_ID12("AmbiCom", "AMB8610", 0x5070a7f9, 0x86741224),
PCMCIA_DEVICE_PROD_ID12("AmbiCom Inc", "AMB8002", 0x93b15570, 0x75ec3efb),
PCMCIA_DEVICE_PROD_ID12("AmbiCom Inc", "AMB8002T", 0x93b15570, 0x461c5247),
PCMCIA_DEVICE_PROD_ID12("AmbiCom Inc", "AMB8010", 0x93b15570, 0x82f96e96),
PCMCIA_DEVICE_PROD_ID12("AnyCom", "ECO Ethernet", 0x578ba6e7, 0x0a9888c1),
PCMCIA_DEVICE_PROD_ID12("AnyCom", "ECO Ethernet 10/100", 0x578ba6e7, 0x939fedbd),
PCMCIA_DEVICE_PROD_ID12("AROWANA", "PCMCIA Ethernet LAN Card", 0x313adbc8, 0x08d9f190),
PCMCIA_DEVICE_PROD_ID12("ASANTE", "FriendlyNet PC Card", 0x3a7ade0f, 0x41c64504),
PCMCIA_DEVICE_PROD_ID12("Billionton", "LNT-10TB", 0x552ab682, 0xeeb1ba6a),
PCMCIA_DEVICE_PROD_ID12("CF", "10Base-Ethernet", 0x44ebf863, 0x93ae4d79),
PCMCIA_DEVICE_PROD_ID12("CNet", "CN40BC Ethernet", 0xbc477dde, 0xfba775a7),
PCMCIA_DEVICE_PROD_ID12("COMPU-SHACK", "BASEline PCMCIA 10 MBit Ethernetadapter", 0xfa2e424d, 0xe9190d8a),
PCMCIA_DEVICE_PROD_ID12("COMPU-SHACK", "FASTline PCMCIA 10/100 Fast-Ethernet", 0xfa2e424d, 0x3953d9b9),
PCMCIA_DEVICE_PROD_ID12("CONTEC", "C-NET(PC)C-10L", 0x21cab552, 0xf6f90722),
PCMCIA_DEVICE_PROD_ID12("corega", "FEther PCC-TXF", 0x0a21501a, 0xa51564a2),
PCMCIA_DEVICE_PROD_ID12("corega", "Ether CF-TD", 0x0a21501a, 0x6589340a),
PCMCIA_DEVICE_PROD_ID12("corega K.K.", "corega Ether CF-TD LAN Card", 0x5261440f, 0x8797663b),
PCMCIA_DEVICE_PROD_ID12("corega K.K.", "corega EtherII PCC-T", 0x5261440f, 0xfa9d85bd),
PCMCIA_DEVICE_PROD_ID12("corega K.K.", "corega EtherII PCC-TD", 0x5261440f, 0xc49bd73d),
PCMCIA_DEVICE_PROD_ID12("Corega K.K.", "corega EtherII PCC-TD", 0xd4fdcbd8, 0xc49bd73d),
PCMCIA_DEVICE_PROD_ID12("corega K.K.", "corega Ether PCC-T", 0x5261440f, 0x6705fcaa),
PCMCIA_DEVICE_PROD_ID12("corega K.K.", "corega Ether PCC-TD", 0x5261440f, 0x47d5ca83),
PCMCIA_DEVICE_PROD_ID12("corega K.K.", "corega FastEther PCC-TX", 0x5261440f, 0x485e85d9),
PCMCIA_DEVICE_PROD_ID12("Corega,K.K.", "Ethernet LAN Card", 0x110d26d9, 0x9fd2f0a2),
PCMCIA_DEVICE_PROD_ID12("corega,K.K.", "Ethernet LAN Card", 0x9791a90e, 0x9fd2f0a2),
PCMCIA_DEVICE_PROD_ID12("corega K.K.", "(CG-LAPCCTXD)", 0x5261440f, 0x73ec0d88),
PCMCIA_DEVICE_PROD_ID12("CouplerlessPCMCIA", "100BASE", 0xee5af0ad, 0x7c2add04),
PCMCIA_DEVICE_PROD_ID12("CyQ've", "ELA-010", 0x77008979, 0x9d8d445d),
PCMCIA_DEVICE_PROD_ID12("CyQ've", "ELA-110E 10/100M LAN Card", 0x77008979, 0xfd184814),
PCMCIA_DEVICE_PROD_ID12("DataTrek.", "NetCard ", 0x5cd66d9d, 0x84697ce0),
PCMCIA_DEVICE_PROD_ID12("Dayna Communications, Inc.", "CommuniCard E", 0x0c629325, 0xb4e7dbaf),
PCMCIA_DEVICE_PROD_ID12("Digicom", "Palladio LAN 10/100", 0x697403d8, 0xe160b995),
PCMCIA_DEVICE_PROD_ID12("Digicom", "Palladio LAN 10/100 Dongless", 0x697403d8, 0xa6d3b233),
PCMCIA_DEVICE_PROD_ID12("DIGITAL", "DEPCM-XX", 0x69616cb3, 0xe600e76e),
PCMCIA_DEVICE_PROD_ID12("D-Link", "DE-650", 0x1a424a1c, 0xf28c8398),
PCMCIA_DEVICE_PROD_ID12("D-Link", "DE-660", 0x1a424a1c, 0xd9a1d05b),
PCMCIA_DEVICE_PROD_ID12("D-Link", "DE-660+", 0x1a424a1c, 0x50dcd0ec),
PCMCIA_DEVICE_PROD_ID12("D-Link", "DFE-650", 0x1a424a1c, 0x0f0073f9),
PCMCIA_DEVICE_PROD_ID12("Dual Speed", "10/100 PC Card", 0x725b842d, 0xf1efee84),
PCMCIA_DEVICE_PROD_ID12("Dual Speed", "10/100 Port Attached PC Card", 0x725b842d, 0x2db1f8e9),
PCMCIA_DEVICE_PROD_ID12("Dynalink", "L10BC", 0x55632fd5, 0xdc65f2b1),
PCMCIA_DEVICE_PROD_ID12("DYNALINK", "L10BC", 0x6a26d1cf, 0xdc65f2b1),
PCMCIA_DEVICE_PROD_ID12("DYNALINK", "L10C", 0x6a26d1cf, 0xc4f84efb),
PCMCIA_DEVICE_PROD_ID12("E-CARD", "E-CARD", 0x6701da11, 0x6701da11),
PCMCIA_DEVICE_PROD_ID12("EIGER Labs Inc.", "Ethernet 10BaseT card", 0x53c864c6, 0xedd059f6),
PCMCIA_DEVICE_PROD_ID12("EIGER Labs Inc.", "Ethernet Combo card", 0x53c864c6, 0x929c486c),
PCMCIA_DEVICE_PROD_ID12("Ethernet", "Adapter", 0x00b2e941, 0x4b0d829e),
PCMCIA_DEVICE_PROD_ID12("Ethernet Adapter", "E2000 PCMCIA Ethernet", 0x96767301, 0x71fbbc61),
PCMCIA_DEVICE_PROD_ID12("Ethernet PCMCIA adapter", "EP-210", 0x8dd86181, 0xf2b52517),
PCMCIA_DEVICE_PROD_ID12("Fast Ethernet", "Adapter", 0xb4be14e3, 0x4b0d829e),
PCMCIA_DEVICE_PROD_ID12("Grey Cell", "GCS2000", 0x2a151fac, 0xf00555cb),
PCMCIA_DEVICE_PROD_ID12("Grey Cell", "GCS2220", 0x2a151fac, 0xc1b7e327),
PCMCIA_DEVICE_PROD_ID12("GVC", "NIC-2000p", 0x76e171bd, 0x6eb1c947),
PCMCIA_DEVICE_PROD_ID12("IBM Corp.", "Ethernet", 0xe3736c88, 0x00b2e941),
PCMCIA_DEVICE_PROD_ID12("IC-CARD", "IC-CARD", 0x60cb09a6, 0x60cb09a6),
PCMCIA_DEVICE_PROD_ID12("IC-CARD+", "IC-CARD+", 0x93693494, 0x93693494),
PCMCIA_DEVICE_PROD_ID12("IO DATA", "PCETTX", 0x547e66dc, 0x6fc5459b),
PCMCIA_DEVICE_PROD_ID12("iPort", "10/100 Ethernet Card", 0x56c538d2, 0x11b0ffc0),
PCMCIA_DEVICE_PROD_ID12("KANSAI ELECTRIC CO.,LTD", "KLA-PCM/T", 0xb18dc3b4, 0xcc51a956),
PCMCIA_DEVICE_PROD_ID12("KENTRONICS", "KEP-230", 0xaf8144c9, 0x868f6616),
PCMCIA_DEVICE_PROD_ID12("KCI", "PE520 PCMCIA Ethernet Adapter", 0xa89b87d3, 0x1eb88e64),
PCMCIA_DEVICE_PROD_ID12("KINGMAX", "EN10T2T", 0x7bcb459a, 0xa5c81fa5),
PCMCIA_DEVICE_PROD_ID12("Kingston", "KNE-PC2", 0x1128e633, 0xce2a89b3),
PCMCIA_DEVICE_PROD_ID12("Kingston Technology Corp.", "EtheRx PC Card Ethernet Adapter", 0x313c7be3, 0x0afb54a2),
PCMCIA_DEVICE_PROD_ID12("Laneed", "LD-10/100CD", 0x1b7827b2, 0xcda71d1c),
PCMCIA_DEVICE_PROD_ID12("Laneed", "LD-CDF", 0x1b7827b2, 0xfec71e40),
PCMCIA_DEVICE_PROD_ID12("Laneed", "LD-CDL/T", 0x1b7827b2, 0x79fba4f7),
PCMCIA_DEVICE_PROD_ID12("Laneed", "LD-CDS", 0x1b7827b2, 0x931afaab),
PCMCIA_DEVICE_PROD_ID12("LEMEL", "LM-N89TX PRO", 0xbbefb52f, 0xd2897a97),
PCMCIA_DEVICE_PROD_ID12("Linksys", "Combo PCMCIA EthernetCard (EC2T)", 0x0733cc81, 0x32ee8c78),
PCMCIA_DEVICE_PROD_ID12("LINKSYS", "E-CARD", 0xf7cb0b07, 0x6701da11),
PCMCIA_DEVICE_PROD_ID12("Linksys", "EtherFast 10/100 Integrated PC Card (PCM100)", 0x0733cc81, 0x453c3f9d),
PCMCIA_DEVICE_PROD_ID12("Linksys", "EtherFast 10/100 PC Card (PCMPC100)", 0x0733cc81, 0x66c5a389),
PCMCIA_DEVICE_PROD_ID12("Linksys", "EtherFast 10/100 PC Card (PCMPC100 V2)", 0x0733cc81, 0x3a3b28e9),
PCMCIA_DEVICE_PROD_ID12("Linksys", "HomeLink Phoneline + 10/100 Network PC Card (PCM100H1)", 0x733cc81, 0x7a3e5c3a),
PCMCIA_DEVICE_PROD_ID12("Logitec", "LPM-LN100TX", 0x88fcdeda, 0x6d772737),
PCMCIA_DEVICE_PROD_ID12("Logitec", "LPM-LN100TE", 0x88fcdeda, 0x0e714bee),
PCMCIA_DEVICE_PROD_ID12("Logitec", "LPM-LN20T", 0x88fcdeda, 0x81090922),
PCMCIA_DEVICE_PROD_ID12("Logitec", "LPM-LN10TE", 0x88fcdeda, 0xc1e2521c),
PCMCIA_DEVICE_PROD_ID12("LONGSHINE", "PCMCIA Ethernet Card", 0xf866b0b0, 0x6f6652e0),
PCMCIA_DEVICE_PROD_ID12("MACNICA", "ME1-JEIDA", 0x20841b68, 0xaf8a3578),
PCMCIA_DEVICE_PROD_ID12("Macsense", "MPC-10", 0xd830297f, 0xd265c307),
PCMCIA_DEVICE_PROD_ID12("Matsushita Electric Industrial Co.,LTD.", "CF-VEL211", 0x44445376, 0x8ded41d4),
PCMCIA_DEVICE_PROD_ID12("MAXTECH", "PCN2000", 0x78d64bc0, 0xca0ca4b8),
PCMCIA_DEVICE_PROD_ID12("MELCO", "LPC2-T", 0x481e0094, 0xa2eb0cf3),
PCMCIA_DEVICE_PROD_ID12("MELCO", "LPC2-TX", 0x481e0094, 0x41a6916c),
PCMCIA_DEVICE_PROD_ID12("Microcom C.E.", "Travel Card LAN 10/100", 0x4b91cec7, 0xe70220d6),
PCMCIA_DEVICE_PROD_ID12("Microdyne", "NE4200", 0x2e6da59b, 0x0478e472),
PCMCIA_DEVICE_PROD_ID12("MIDORI ELEC.", "LT-PCMT", 0x648d55c1, 0xbde526c7),
PCMCIA_DEVICE_PROD_ID12("National Semiconductor", "InfoMover 4100", 0x36e1191f, 0x60c229b9),
PCMCIA_DEVICE_PROD_ID12("National Semiconductor", "InfoMover NE4100", 0x36e1191f, 0xa6617ec8),
PCMCIA_DEVICE_PROD_ID12("NEC", "PC-9801N-J12", 0x18df0ba0, 0xbc912d76),
PCMCIA_DEVICE_PROD_ID12("NETGEAR", "FA410TX", 0x9aa79dc3, 0x60e5bc0e),
PCMCIA_DEVICE_PROD_ID12("Network Everywhere", "Fast Ethernet 10/100 PC Card", 0x820a67b6, 0x31ed1a5f),
PCMCIA_DEVICE_PROD_ID12("NextCom K.K.", "Next Hawk", 0xaedaec74, 0xad050ef1),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "10/100Mbps Ethernet Card", 0x281f1c5d, 0x6e41773b),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "Ethernet", 0x281f1c5d, 0x00b2e941),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "ETHERNET", 0x281f1c5d, 0x3ff7175b),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "Ethernet 10BaseT Card", 0x281f1c5d, 0x4de2f6c8),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "Ethernet Card", 0x281f1c5d, 0x5e9d92c0),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "Ethernet Combo card", 0x281f1c5d, 0x929c486c),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "ETHERNET V1.0", 0x281f1c5d, 0x4d8817c8),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "FastEthernet", 0x281f1c5d, 0xfe871eeb),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "Fast-Ethernet", 0x281f1c5d, 0x45f1f3b4),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "FAST ETHERNET CARD", 0x281f1c5d, 0xec5dbca7),
PCMCIA_DEVICE_PROD_ID12("PCMCIA LAN", "Ethernet", 0x7500e246, 0x00b2e941),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "LNT-10TN", 0x281f1c5d, 0xe707f641),
PCMCIA_DEVICE_PROD_ID12("PCMCIAs", "ComboCard", 0xdcfe12d3, 0xcd8906cc),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "UE2212", 0x281f1c5d, 0xbf17199b),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", " Ethernet NE2000 Compatible", 0x281f1c5d, 0x42d5d7e1),
PCMCIA_DEVICE_PROD_ID12("PRETEC", "Ethernet CompactLAN 10baseT 3.3V", 0xebf91155, 0x30074c80),
PCMCIA_DEVICE_PROD_ID12("PRETEC", "Ethernet CompactLAN 10BaseT 3.3V", 0xebf91155, 0x7f5a4f50),
PCMCIA_DEVICE_PROD_ID12("Psion Dacom", "Gold Card Ethernet", 0xf5f025c2, 0x3a30e110),
PCMCIA_DEVICE_PROD_ID12("=RELIA==", "Ethernet", 0xcdd0644a, 0x00b2e941),
PCMCIA_DEVICE_PROD_ID12("RIOS Systems Co.", "PC CARD3 ETHERNET", 0x7dd33481, 0x10b41826),
PCMCIA_DEVICE_PROD_ID12("RP", "1625B Ethernet NE2000 Compatible", 0xe3e66e22, 0xb96150df),
PCMCIA_DEVICE_PROD_ID12("RPTI", "EP400 Ethernet NE2000 Compatible", 0xdc6f88fd, 0x4a7e2ae0),
PCMCIA_DEVICE_PROD_ID12("RPTI", "EP401 Ethernet NE2000 Compatible", 0xdc6f88fd, 0x4bcbd7fd),
PCMCIA_DEVICE_PROD_ID12("RPTI LTD.", "EP400", 0xc53ac515, 0x81e39388),
PCMCIA_DEVICE_PROD_ID12("SCM", "Ethernet Combo card", 0xbdc3b102, 0x929c486c),
PCMCIA_DEVICE_PROD_ID12("Seiko Epson Corp.", "Ethernet", 0x09928730, 0x00b2e941),
PCMCIA_DEVICE_PROD_ID12("SMC", "EZCard-10-PCMCIA", 0xc4f8b18b, 0xfb21d265),
PCMCIA_DEVICE_PROD_ID12("Socket Communications Inc", "Socket EA PCMCIA LAN Adapter Revision D", 0xc70a4760, 0x2ade483e),
PCMCIA_DEVICE_PROD_ID12("Socket Communications Inc", "Socket EA PCMCIA LAN Adapter Revision E", 0xc70a4760, 0x5dd978a8),
PCMCIA_DEVICE_PROD_ID12("TDK", "LAK-CD031 for PCMCIA", 0x1eae9475, 0x0ed386fa),
PCMCIA_DEVICE_PROD_ID12("Telecom Device K.K.", "SuperSocket RE450T", 0x466b05f0, 0x8b74bc4f),
PCMCIA_DEVICE_PROD_ID12("Telecom Device K.K.", "SuperSocket RE550T", 0x466b05f0, 0x33c8db2a),
PCMCIA_DEVICE_PROD_ID13("Hypertec", "EP401", 0x8787bec7, 0xf6e4a31e),
PCMCIA_DEVICE_PROD_ID13("KingMax Technology Inc.", "Ethernet Card", 0x932b7189, 0x5e9d92c0),
PCMCIA_DEVICE_PROD_ID13("LONGSHINE", "EP401", 0xf866b0b0, 0xf6e4a31e),
PCMCIA_DEVICE_PROD_ID13("Xircom", "CFE-10", 0x2e3ee845, 0x22a49f89),
PCMCIA_DEVICE_PROD_ID1("CyQ've 10 Base-T LAN CARD", 0x94faf360),
PCMCIA_DEVICE_PROD_ID1("EP-210 PCMCIA LAN CARD.", 0x8850b4de),
PCMCIA_DEVICE_PROD_ID1("ETHER-C16", 0x06a8514f),
PCMCIA_DEVICE_PROD_ID1("NE2000 Compatible", 0x75b8ad5a),
PCMCIA_DEVICE_PROD_ID2("EN-6200P2", 0xa996d078),
/* too generic! */
/* PCMCIA_DEVICE_PROD_ID12("PCMCIA", "10/100 Ethernet Card", 0x281f1c5d, 0x11b0ffc0), */
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(0, "PCMCIA", "EN2218-LAN/MODEM", 0x281f1c5d, 0x570f348e, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(0, "PCMCIA", "UE2218-LAN/MODEM", 0x281f1c5d, 0x6fdcacee, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(0, "Psion Dacom", "Gold Card V34 Ethernet", 0xf5f025c2, 0x338e8155, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(0, "Psion Dacom", "Gold Card V34 Ethernet GSM", 0xf5f025c2, 0x4ae85d35, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(0, "LINKSYS", "PCMLM28", 0xf7cb0b07, 0x66881874, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(0, "TOSHIBA", "Modem/LAN Card", 0xb4585a1a, 0x53f922f8, "cis/PCMLM28.cis"),
PCMCIA_MFC_DEVICE_CIS_PROD_ID12(0, "DAYNA COMMUNICATIONS", "LAN AND MODEM MULTIFUNCTION", 0x8fdf8f89, 0xdd5ed9e8, "cis/DP83903.cis"),
PCMCIA_MFC_DEVICE_CIS_PROD_ID4(0, "NSC MF LAN/Modem", 0x58fc6056, "cis/DP83903.cis"),
PCMCIA_MFC_DEVICE_CIS_MANF_CARD(0, 0x0175, 0x0000, "cis/DP83903.cis"),
PCMCIA_DEVICE_CIS_PROD_ID12("Allied Telesis,K.K", "Ethernet LAN Card", 0x2ad62f3c, 0x9fd2f0a2, "cis/LA-PCM.cis"),
PCMCIA_DEVICE_CIS_PROD_ID12("KTI", "PE520 PLUS", 0xad180345, 0x9d58d392, "cis/PE520.cis"),
PCMCIA_DEVICE_CIS_PROD_ID12("NDC", "Ethernet", 0x01c43ae1, 0x00b2e941, "cis/NE2K.cis"),
PCMCIA_DEVICE_CIS_PROD_ID12("PMX ", "PE-200", 0x34f3f1c8, 0x10b59f8c, "cis/PE-200.cis"),
PCMCIA_DEVICE_CIS_PROD_ID12("TAMARACK", "Ethernet", 0xcf434fba, 0x00b2e941, "cis/tamarack.cis"),
PCMCIA_DEVICE_PROD_ID12("Ethernet", "CF Size PC Card", 0x00b2e941, 0x43ac239b),
PCMCIA_DEVICE_PROD_ID123("Fast Ethernet", "CF Size PC Card", "1.0",
0xb4be14e3, 0x43ac239b, 0x0877b627),
PCMCIA_DEVICE_NULL
};
MODULE_DEVICE_TABLE(pcmcia, pcnet_ids);
MODULE_FIRMWARE("cis/PCMLM28.cis");
MODULE_FIRMWARE("cis/DP83903.cis");
MODULE_FIRMWARE("cis/LA-PCM.cis");
MODULE_FIRMWARE("cis/PE520.cis");
MODULE_FIRMWARE("cis/NE2K.cis");
MODULE_FIRMWARE("cis/PE-200.cis");
MODULE_FIRMWARE("cis/tamarack.cis");
static struct pcmcia_driver pcnet_driver = {
.name = "pcnet_cs",
.probe = pcnet_probe,
.remove = pcnet_detach,
.owner = THIS_MODULE,
.id_table = pcnet_ids,
.suspend = pcnet_suspend,
.resume = pcnet_resume,
};
static int __init init_pcnet_cs(void)
{
return pcmcia_register_driver(&pcnet_driver);
}
static void __exit exit_pcnet_cs(void)
{
pcmcia_unregister_driver(&pcnet_driver);
}
module_init(init_pcnet_cs);
module_exit(exit_pcnet_cs);
| gpl-2.0 |
embeddedarm/linux-3.0.35-imx6-android | fs/squashfs/file.c | 3026 | 14225 | /*
* Squashfs - a compressed read only filesystem for Linux
*
* Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008
* Phillip Lougher <phillip@squashfs.org.uk>
*
* 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; if not, write to the Free Software
* Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* file.c
*/
/*
* This file contains code for handling regular files. A regular file
* consists of a sequence of contiguous compressed blocks, and/or a
* compressed fragment block (tail-end packed block). The compressed size
* of each datablock is stored in a block list contained within the
* file inode (itself stored in one or more compressed metadata blocks).
*
* To speed up access to datablocks when reading 'large' files (256 Mbytes or
* larger), the code implements an index cache that caches the mapping from
* block index to datablock location on disk.
*
* The index cache allows Squashfs to handle large files (up to 1.75 TiB) while
* retaining a simple and space-efficient block list on disk. The cache
* is split into slots, caching up to eight 224 GiB files (128 KiB blocks).
* Larger files use multiple slots, with 1.75 TiB files using all 8 slots.
* The index cache is designed to be memory efficient, and by default uses
* 16 KiB.
*/
#include <linux/fs.h>
#include <linux/vfs.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/pagemap.h>
#include <linux/mutex.h>
#include "squashfs_fs.h"
#include "squashfs_fs_sb.h"
#include "squashfs_fs_i.h"
#include "squashfs.h"
/*
* Locate cache slot in range [offset, index] for specified inode. If
* there's more than one return the slot closest to index.
*/
static struct meta_index *locate_meta_index(struct inode *inode, int offset,
int index)
{
struct meta_index *meta = NULL;
struct squashfs_sb_info *msblk = inode->i_sb->s_fs_info;
int i;
mutex_lock(&msblk->meta_index_mutex);
TRACE("locate_meta_index: index %d, offset %d\n", index, offset);
if (msblk->meta_index == NULL)
goto not_allocated;
for (i = 0; i < SQUASHFS_META_SLOTS; i++) {
if (msblk->meta_index[i].inode_number == inode->i_ino &&
msblk->meta_index[i].offset >= offset &&
msblk->meta_index[i].offset <= index &&
msblk->meta_index[i].locked == 0) {
TRACE("locate_meta_index: entry %d, offset %d\n", i,
msblk->meta_index[i].offset);
meta = &msblk->meta_index[i];
offset = meta->offset;
}
}
if (meta)
meta->locked = 1;
not_allocated:
mutex_unlock(&msblk->meta_index_mutex);
return meta;
}
/*
* Find and initialise an empty cache slot for index offset.
*/
static struct meta_index *empty_meta_index(struct inode *inode, int offset,
int skip)
{
struct squashfs_sb_info *msblk = inode->i_sb->s_fs_info;
struct meta_index *meta = NULL;
int i;
mutex_lock(&msblk->meta_index_mutex);
TRACE("empty_meta_index: offset %d, skip %d\n", offset, skip);
if (msblk->meta_index == NULL) {
/*
* First time cache index has been used, allocate and
* initialise. The cache index could be allocated at
* mount time but doing it here means it is allocated only
* if a 'large' file is read.
*/
msblk->meta_index = kcalloc(SQUASHFS_META_SLOTS,
sizeof(*(msblk->meta_index)), GFP_KERNEL);
if (msblk->meta_index == NULL) {
ERROR("Failed to allocate meta_index\n");
goto failed;
}
for (i = 0; i < SQUASHFS_META_SLOTS; i++) {
msblk->meta_index[i].inode_number = 0;
msblk->meta_index[i].locked = 0;
}
msblk->next_meta_index = 0;
}
for (i = SQUASHFS_META_SLOTS; i &&
msblk->meta_index[msblk->next_meta_index].locked; i--)
msblk->next_meta_index = (msblk->next_meta_index + 1) %
SQUASHFS_META_SLOTS;
if (i == 0) {
TRACE("empty_meta_index: failed!\n");
goto failed;
}
TRACE("empty_meta_index: returned meta entry %d, %p\n",
msblk->next_meta_index,
&msblk->meta_index[msblk->next_meta_index]);
meta = &msblk->meta_index[msblk->next_meta_index];
msblk->next_meta_index = (msblk->next_meta_index + 1) %
SQUASHFS_META_SLOTS;
meta->inode_number = inode->i_ino;
meta->offset = offset;
meta->skip = skip;
meta->entries = 0;
meta->locked = 1;
failed:
mutex_unlock(&msblk->meta_index_mutex);
return meta;
}
static void release_meta_index(struct inode *inode, struct meta_index *meta)
{
struct squashfs_sb_info *msblk = inode->i_sb->s_fs_info;
mutex_lock(&msblk->meta_index_mutex);
meta->locked = 0;
mutex_unlock(&msblk->meta_index_mutex);
}
/*
* Read the next n blocks from the block list, starting from
* metadata block <start_block, offset>.
*/
static long long read_indexes(struct super_block *sb, int n,
u64 *start_block, int *offset)
{
int err, i;
long long block = 0;
__le32 *blist = kmalloc(PAGE_CACHE_SIZE, GFP_KERNEL);
if (blist == NULL) {
ERROR("read_indexes: Failed to allocate block_list\n");
return -ENOMEM;
}
while (n) {
int blocks = min_t(int, n, PAGE_CACHE_SIZE >> 2);
err = squashfs_read_metadata(sb, blist, start_block,
offset, blocks << 2);
if (err < 0) {
ERROR("read_indexes: reading block [%llx:%x]\n",
*start_block, *offset);
goto failure;
}
for (i = 0; i < blocks; i++) {
int size = le32_to_cpu(blist[i]);
block += SQUASHFS_COMPRESSED_SIZE_BLOCK(size);
}
n -= blocks;
}
kfree(blist);
return block;
failure:
kfree(blist);
return err;
}
/*
* Each cache index slot has SQUASHFS_META_ENTRIES, each of which
* can cache one index -> datablock/blocklist-block mapping. We wish
* to distribute these over the length of the file, entry[0] maps index x,
* entry[1] maps index x + skip, entry[2] maps index x + 2 * skip, and so on.
* The larger the file, the greater the skip factor. The skip factor is
* limited to the size of the metadata cache (SQUASHFS_CACHED_BLKS) to ensure
* the number of metadata blocks that need to be read fits into the cache.
* If the skip factor is limited in this way then the file will use multiple
* slots.
*/
static inline int calculate_skip(int blocks)
{
int skip = blocks / ((SQUASHFS_META_ENTRIES + 1)
* SQUASHFS_META_INDEXES);
return min(SQUASHFS_CACHED_BLKS - 1, skip + 1);
}
/*
* Search and grow the index cache for the specified inode, returning the
* on-disk locations of the datablock and block list metadata block
* <index_block, index_offset> for index (scaled to nearest cache index).
*/
static int fill_meta_index(struct inode *inode, int index,
u64 *index_block, int *index_offset, u64 *data_block)
{
struct squashfs_sb_info *msblk = inode->i_sb->s_fs_info;
int skip = calculate_skip(i_size_read(inode) >> msblk->block_log);
int offset = 0;
struct meta_index *meta;
struct meta_entry *meta_entry;
u64 cur_index_block = squashfs_i(inode)->block_list_start;
int cur_offset = squashfs_i(inode)->offset;
u64 cur_data_block = squashfs_i(inode)->start;
int err, i;
/*
* Scale index to cache index (cache slot entry)
*/
index /= SQUASHFS_META_INDEXES * skip;
while (offset < index) {
meta = locate_meta_index(inode, offset + 1, index);
if (meta == NULL) {
meta = empty_meta_index(inode, offset + 1, skip);
if (meta == NULL)
goto all_done;
} else {
offset = index < meta->offset + meta->entries ? index :
meta->offset + meta->entries - 1;
meta_entry = &meta->meta_entry[offset - meta->offset];
cur_index_block = meta_entry->index_block +
msblk->inode_table;
cur_offset = meta_entry->offset;
cur_data_block = meta_entry->data_block;
TRACE("get_meta_index: offset %d, meta->offset %d, "
"meta->entries %d\n", offset, meta->offset,
meta->entries);
TRACE("get_meta_index: index_block 0x%llx, offset 0x%x"
" data_block 0x%llx\n", cur_index_block,
cur_offset, cur_data_block);
}
/*
* If necessary grow cache slot by reading block list. Cache
* slot is extended up to index or to the end of the slot, in
* which case further slots will be used.
*/
for (i = meta->offset + meta->entries; i <= index &&
i < meta->offset + SQUASHFS_META_ENTRIES; i++) {
int blocks = skip * SQUASHFS_META_INDEXES;
long long res = read_indexes(inode->i_sb, blocks,
&cur_index_block, &cur_offset);
if (res < 0) {
if (meta->entries == 0)
/*
* Don't leave an empty slot on read
* error allocated to this inode...
*/
meta->inode_number = 0;
err = res;
goto failed;
}
cur_data_block += res;
meta_entry = &meta->meta_entry[i - meta->offset];
meta_entry->index_block = cur_index_block -
msblk->inode_table;
meta_entry->offset = cur_offset;
meta_entry->data_block = cur_data_block;
meta->entries++;
offset++;
}
TRACE("get_meta_index: meta->offset %d, meta->entries %d\n",
meta->offset, meta->entries);
release_meta_index(inode, meta);
}
all_done:
*index_block = cur_index_block;
*index_offset = cur_offset;
*data_block = cur_data_block;
/*
* Scale cache index (cache slot entry) to index
*/
return offset * SQUASHFS_META_INDEXES * skip;
failed:
release_meta_index(inode, meta);
return err;
}
/*
* Get the on-disk location and compressed size of the datablock
* specified by index. Fill_meta_index() does most of the work.
*/
static int read_blocklist(struct inode *inode, int index, u64 *block)
{
u64 start;
long long blks;
int offset;
__le32 size;
int res = fill_meta_index(inode, index, &start, &offset, block);
TRACE("read_blocklist: res %d, index %d, start 0x%llx, offset"
" 0x%x, block 0x%llx\n", res, index, start, offset,
*block);
if (res < 0)
return res;
/*
* res contains the index of the mapping returned by fill_meta_index(),
* this will likely be less than the desired index (because the
* meta_index cache works at a higher granularity). Read any
* extra block indexes needed.
*/
if (res < index) {
blks = read_indexes(inode->i_sb, index - res, &start, &offset);
if (blks < 0)
return (int) blks;
*block += blks;
}
/*
* Read length of block specified by index.
*/
res = squashfs_read_metadata(inode->i_sb, &size, &start, &offset,
sizeof(size));
if (res < 0)
return res;
return le32_to_cpu(size);
}
static int squashfs_readpage(struct file *file, struct page *page)
{
struct inode *inode = page->mapping->host;
struct squashfs_sb_info *msblk = inode->i_sb->s_fs_info;
int bytes, i, offset = 0, sparse = 0;
struct squashfs_cache_entry *buffer = NULL;
void *pageaddr;
int mask = (1 << (msblk->block_log - PAGE_CACHE_SHIFT)) - 1;
int index = page->index >> (msblk->block_log - PAGE_CACHE_SHIFT);
int start_index = page->index & ~mask;
int end_index = start_index | mask;
int file_end = i_size_read(inode) >> msblk->block_log;
TRACE("Entered squashfs_readpage, page index %lx, start block %llx\n",
page->index, squashfs_i(inode)->start);
if (page->index >= ((i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
PAGE_CACHE_SHIFT))
goto out;
if (index < file_end || squashfs_i(inode)->fragment_block ==
SQUASHFS_INVALID_BLK) {
/*
* Reading a datablock from disk. Need to read block list
* to get location and block size.
*/
u64 block = 0;
int bsize = read_blocklist(inode, index, &block);
if (bsize < 0)
goto error_out;
if (bsize == 0) { /* hole */
bytes = index == file_end ?
(i_size_read(inode) & (msblk->block_size - 1)) :
msblk->block_size;
sparse = 1;
} else {
/*
* Read and decompress datablock.
*/
buffer = squashfs_get_datablock(inode->i_sb,
block, bsize);
if (buffer->error) {
ERROR("Unable to read page, block %llx, size %x"
"\n", block, bsize);
squashfs_cache_put(buffer);
goto error_out;
}
bytes = buffer->length;
}
} else {
/*
* Datablock is stored inside a fragment (tail-end packed
* block).
*/
buffer = squashfs_get_fragment(inode->i_sb,
squashfs_i(inode)->fragment_block,
squashfs_i(inode)->fragment_size);
if (buffer->error) {
ERROR("Unable to read page, block %llx, size %x\n",
squashfs_i(inode)->fragment_block,
squashfs_i(inode)->fragment_size);
squashfs_cache_put(buffer);
goto error_out;
}
bytes = i_size_read(inode) & (msblk->block_size - 1);
offset = squashfs_i(inode)->fragment_offset;
}
/*
* Loop copying datablock into pages. As the datablock likely covers
* many PAGE_CACHE_SIZE pages (default block size is 128 KiB) explicitly
* grab the pages from the page cache, except for the page that we've
* been called to fill.
*/
for (i = start_index; i <= end_index && bytes > 0; i++,
bytes -= PAGE_CACHE_SIZE, offset += PAGE_CACHE_SIZE) {
struct page *push_page;
int avail = sparse ? 0 : min_t(int, bytes, PAGE_CACHE_SIZE);
TRACE("bytes %d, i %d, available_bytes %d\n", bytes, i, avail);
push_page = (i == page->index) ? page :
grab_cache_page_nowait(page->mapping, i);
if (!push_page)
continue;
if (PageUptodate(push_page))
goto skip_page;
pageaddr = kmap_atomic(push_page, KM_USER0);
squashfs_copy_data(pageaddr, buffer, offset, avail);
memset(pageaddr + avail, 0, PAGE_CACHE_SIZE - avail);
kunmap_atomic(pageaddr, KM_USER0);
flush_dcache_page(push_page);
SetPageUptodate(push_page);
skip_page:
unlock_page(push_page);
if (i != page->index)
page_cache_release(push_page);
}
if (!sparse)
squashfs_cache_put(buffer);
return 0;
error_out:
SetPageError(page);
out:
pageaddr = kmap_atomic(page, KM_USER0);
memset(pageaddr, 0, PAGE_CACHE_SIZE);
kunmap_atomic(pageaddr, KM_USER0);
flush_dcache_page(page);
if (!PageError(page))
SetPageUptodate(page);
unlock_page(page);
return 0;
}
const struct address_space_operations squashfs_aops = {
.readpage = squashfs_readpage
};
| gpl-2.0 |
intdes/linux-MPC8314 | fs/nilfs2/mdt.c | 3026 | 14729 | /*
* mdt.c - meta data file for NILFS
*
* Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by Ryusuke Konishi <ryusuke@osrg.net>
*/
#include <linux/buffer_head.h>
#include <linux/mpage.h>
#include <linux/mm.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/swap.h>
#include <linux/slab.h>
#include "nilfs.h"
#include "btnode.h"
#include "segment.h"
#include "page.h"
#include "mdt.h"
#define NILFS_MDT_MAX_RA_BLOCKS (16 - 1)
static int
nilfs_mdt_insert_new_block(struct inode *inode, unsigned long block,
struct buffer_head *bh,
void (*init_block)(struct inode *,
struct buffer_head *, void *))
{
struct nilfs_inode_info *ii = NILFS_I(inode);
void *kaddr;
int ret;
/* Caller exclude read accesses using page lock */
/* set_buffer_new(bh); */
bh->b_blocknr = 0;
ret = nilfs_bmap_insert(ii->i_bmap, block, (unsigned long)bh);
if (unlikely(ret))
return ret;
set_buffer_mapped(bh);
kaddr = kmap_atomic(bh->b_page, KM_USER0);
memset(kaddr + bh_offset(bh), 0, 1 << inode->i_blkbits);
if (init_block)
init_block(inode, bh, kaddr);
flush_dcache_page(bh->b_page);
kunmap_atomic(kaddr, KM_USER0);
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
nilfs_mdt_mark_dirty(inode);
return 0;
}
static int nilfs_mdt_create_block(struct inode *inode, unsigned long block,
struct buffer_head **out_bh,
void (*init_block)(struct inode *,
struct buffer_head *,
void *))
{
struct super_block *sb = inode->i_sb;
struct nilfs_transaction_info ti;
struct buffer_head *bh;
int err;
nilfs_transaction_begin(sb, &ti, 0);
err = -ENOMEM;
bh = nilfs_grab_buffer(inode, inode->i_mapping, block, 0);
if (unlikely(!bh))
goto failed_unlock;
err = -EEXIST;
if (buffer_uptodate(bh))
goto failed_bh;
wait_on_buffer(bh);
if (buffer_uptodate(bh))
goto failed_bh;
bh->b_bdev = sb->s_bdev;
err = nilfs_mdt_insert_new_block(inode, block, bh, init_block);
if (likely(!err)) {
get_bh(bh);
*out_bh = bh;
}
failed_bh:
unlock_page(bh->b_page);
page_cache_release(bh->b_page);
brelse(bh);
failed_unlock:
if (likely(!err))
err = nilfs_transaction_commit(sb);
else
nilfs_transaction_abort(sb);
return err;
}
static int
nilfs_mdt_submit_block(struct inode *inode, unsigned long blkoff,
int mode, struct buffer_head **out_bh)
{
struct buffer_head *bh;
__u64 blknum = 0;
int ret = -ENOMEM;
bh = nilfs_grab_buffer(inode, inode->i_mapping, blkoff, 0);
if (unlikely(!bh))
goto failed;
ret = -EEXIST; /* internal code */
if (buffer_uptodate(bh))
goto out;
if (mode == READA) {
if (!trylock_buffer(bh)) {
ret = -EBUSY;
goto failed_bh;
}
} else /* mode == READ */
lock_buffer(bh);
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
goto out;
}
ret = nilfs_bmap_lookup(NILFS_I(inode)->i_bmap, blkoff, &blknum);
if (unlikely(ret)) {
unlock_buffer(bh);
goto failed_bh;
}
map_bh(bh, inode->i_sb, (sector_t)blknum);
bh->b_end_io = end_buffer_read_sync;
get_bh(bh);
submit_bh(mode, bh);
ret = 0;
out:
get_bh(bh);
*out_bh = bh;
failed_bh:
unlock_page(bh->b_page);
page_cache_release(bh->b_page);
brelse(bh);
failed:
return ret;
}
static int nilfs_mdt_read_block(struct inode *inode, unsigned long block,
int readahead, struct buffer_head **out_bh)
{
struct buffer_head *first_bh, *bh;
unsigned long blkoff;
int i, nr_ra_blocks = NILFS_MDT_MAX_RA_BLOCKS;
int err;
err = nilfs_mdt_submit_block(inode, block, READ, &first_bh);
if (err == -EEXIST) /* internal code */
goto out;
if (unlikely(err))
goto failed;
if (readahead) {
blkoff = block + 1;
for (i = 0; i < nr_ra_blocks; i++, blkoff++) {
err = nilfs_mdt_submit_block(inode, blkoff, READA, &bh);
if (likely(!err || err == -EEXIST))
brelse(bh);
else if (err != -EBUSY)
break;
/* abort readahead if bmap lookup failed */
if (!buffer_locked(first_bh))
goto out_no_wait;
}
}
wait_on_buffer(first_bh);
out_no_wait:
err = -EIO;
if (!buffer_uptodate(first_bh))
goto failed_bh;
out:
*out_bh = first_bh;
return 0;
failed_bh:
brelse(first_bh);
failed:
return err;
}
/**
* nilfs_mdt_get_block - read or create a buffer on meta data file.
* @inode: inode of the meta data file
* @blkoff: block offset
* @create: create flag
* @init_block: initializer used for newly allocated block
* @out_bh: output of a pointer to the buffer_head
*
* nilfs_mdt_get_block() looks up the specified buffer and tries to create
* a new buffer if @create is not zero. On success, the returned buffer is
* assured to be either existing or formatted using a buffer lock on success.
* @out_bh is substituted only when zero is returned.
*
* Return Value: On success, it returns 0. On error, the following negative
* error code is returned.
*
* %-ENOMEM - Insufficient memory available.
*
* %-EIO - I/O error
*
* %-ENOENT - the specified block does not exist (hole block)
*
* %-EROFS - Read only filesystem (for create mode)
*/
int nilfs_mdt_get_block(struct inode *inode, unsigned long blkoff, int create,
void (*init_block)(struct inode *,
struct buffer_head *, void *),
struct buffer_head **out_bh)
{
int ret;
/* Should be rewritten with merging nilfs_mdt_read_block() */
retry:
ret = nilfs_mdt_read_block(inode, blkoff, !create, out_bh);
if (!create || ret != -ENOENT)
return ret;
ret = nilfs_mdt_create_block(inode, blkoff, out_bh, init_block);
if (unlikely(ret == -EEXIST)) {
/* create = 0; */ /* limit read-create loop retries */
goto retry;
}
return ret;
}
/**
* nilfs_mdt_delete_block - make a hole on the meta data file.
* @inode: inode of the meta data file
* @block: block offset
*
* Return Value: On success, zero is returned.
* On error, one of the following negative error code is returned.
*
* %-ENOMEM - Insufficient memory available.
*
* %-EIO - I/O error
*/
int nilfs_mdt_delete_block(struct inode *inode, unsigned long block)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
int err;
err = nilfs_bmap_delete(ii->i_bmap, block);
if (!err || err == -ENOENT) {
nilfs_mdt_mark_dirty(inode);
nilfs_mdt_forget_block(inode, block);
}
return err;
}
/**
* nilfs_mdt_forget_block - discard dirty state and try to remove the page
* @inode: inode of the meta data file
* @block: block offset
*
* nilfs_mdt_forget_block() clears a dirty flag of the specified buffer, and
* tries to release the page including the buffer from a page cache.
*
* Return Value: On success, 0 is returned. On error, one of the following
* negative error code is returned.
*
* %-EBUSY - page has an active buffer.
*
* %-ENOENT - page cache has no page addressed by the offset.
*/
int nilfs_mdt_forget_block(struct inode *inode, unsigned long block)
{
pgoff_t index = (pgoff_t)block >>
(PAGE_CACHE_SHIFT - inode->i_blkbits);
struct page *page;
unsigned long first_block;
int ret = 0;
int still_dirty;
page = find_lock_page(inode->i_mapping, index);
if (!page)
return -ENOENT;
wait_on_page_writeback(page);
first_block = (unsigned long)index <<
(PAGE_CACHE_SHIFT - inode->i_blkbits);
if (page_has_buffers(page)) {
struct buffer_head *bh;
bh = nilfs_page_get_nth_block(page, block - first_block);
nilfs_forget_buffer(bh);
}
still_dirty = PageDirty(page);
unlock_page(page);
page_cache_release(page);
if (still_dirty ||
invalidate_inode_pages2_range(inode->i_mapping, index, index) != 0)
ret = -EBUSY;
return ret;
}
/**
* nilfs_mdt_mark_block_dirty - mark a block on the meta data file dirty.
* @inode: inode of the meta data file
* @block: block offset
*
* Return Value: On success, it returns 0. On error, the following negative
* error code is returned.
*
* %-ENOMEM - Insufficient memory available.
*
* %-EIO - I/O error
*
* %-ENOENT - the specified block does not exist (hole block)
*/
int nilfs_mdt_mark_block_dirty(struct inode *inode, unsigned long block)
{
struct buffer_head *bh;
int err;
err = nilfs_mdt_read_block(inode, block, 0, &bh);
if (unlikely(err))
return err;
mark_buffer_dirty(bh);
nilfs_mdt_mark_dirty(inode);
brelse(bh);
return 0;
}
int nilfs_mdt_fetch_dirty(struct inode *inode)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
if (nilfs_bmap_test_and_clear_dirty(ii->i_bmap)) {
set_bit(NILFS_I_DIRTY, &ii->i_state);
return 1;
}
return test_bit(NILFS_I_DIRTY, &ii->i_state);
}
static int
nilfs_mdt_write_page(struct page *page, struct writeback_control *wbc)
{
struct inode *inode;
struct super_block *sb;
int err = 0;
redirty_page_for_writepage(wbc, page);
unlock_page(page);
inode = page->mapping->host;
if (!inode)
return 0;
sb = inode->i_sb;
if (wbc->sync_mode == WB_SYNC_ALL)
err = nilfs_construct_segment(sb);
else if (wbc->for_reclaim)
nilfs_flush_segment(sb, inode->i_ino);
return err;
}
static const struct address_space_operations def_mdt_aops = {
.writepage = nilfs_mdt_write_page,
};
static const struct inode_operations def_mdt_iops;
static const struct file_operations def_mdt_fops;
int nilfs_mdt_init(struct inode *inode, gfp_t gfp_mask, size_t objsz)
{
struct nilfs_mdt_info *mi;
mi = kzalloc(max(sizeof(*mi), objsz), GFP_NOFS);
if (!mi)
return -ENOMEM;
init_rwsem(&mi->mi_sem);
inode->i_private = mi;
inode->i_mode = S_IFREG;
mapping_set_gfp_mask(inode->i_mapping, gfp_mask);
inode->i_mapping->backing_dev_info = inode->i_sb->s_bdi;
inode->i_op = &def_mdt_iops;
inode->i_fop = &def_mdt_fops;
inode->i_mapping->a_ops = &def_mdt_aops;
return 0;
}
void nilfs_mdt_set_entry_size(struct inode *inode, unsigned entry_size,
unsigned header_size)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
mi->mi_entry_size = entry_size;
mi->mi_entries_per_block = (1 << inode->i_blkbits) / entry_size;
mi->mi_first_entry_offset = DIV_ROUND_UP(header_size, entry_size);
}
/**
* nilfs_mdt_setup_shadow_map - setup shadow map and bind it to metadata file
* @inode: inode of the metadata file
* @shadow: shadow mapping
*/
int nilfs_mdt_setup_shadow_map(struct inode *inode,
struct nilfs_shadow_map *shadow)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
struct backing_dev_info *bdi = inode->i_sb->s_bdi;
INIT_LIST_HEAD(&shadow->frozen_buffers);
address_space_init_once(&shadow->frozen_data);
nilfs_mapping_init(&shadow->frozen_data, inode, bdi);
address_space_init_once(&shadow->frozen_btnodes);
nilfs_mapping_init(&shadow->frozen_btnodes, inode, bdi);
mi->mi_shadow = shadow;
return 0;
}
/**
* nilfs_mdt_save_to_shadow_map - copy bmap and dirty pages to shadow map
* @inode: inode of the metadata file
*/
int nilfs_mdt_save_to_shadow_map(struct inode *inode)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
struct nilfs_inode_info *ii = NILFS_I(inode);
struct nilfs_shadow_map *shadow = mi->mi_shadow;
int ret;
ret = nilfs_copy_dirty_pages(&shadow->frozen_data, inode->i_mapping);
if (ret)
goto out;
ret = nilfs_copy_dirty_pages(&shadow->frozen_btnodes,
&ii->i_btnode_cache);
if (ret)
goto out;
nilfs_bmap_save(ii->i_bmap, &shadow->bmap_store);
out:
return ret;
}
int nilfs_mdt_freeze_buffer(struct inode *inode, struct buffer_head *bh)
{
struct nilfs_shadow_map *shadow = NILFS_MDT(inode)->mi_shadow;
struct buffer_head *bh_frozen;
struct page *page;
int blkbits = inode->i_blkbits;
page = grab_cache_page(&shadow->frozen_data, bh->b_page->index);
if (!page)
return -ENOMEM;
if (!page_has_buffers(page))
create_empty_buffers(page, 1 << blkbits, 0);
bh_frozen = nilfs_page_get_nth_block(page, bh_offset(bh) >> blkbits);
if (!buffer_uptodate(bh_frozen))
nilfs_copy_buffer(bh_frozen, bh);
if (list_empty(&bh_frozen->b_assoc_buffers)) {
list_add_tail(&bh_frozen->b_assoc_buffers,
&shadow->frozen_buffers);
set_buffer_nilfs_redirected(bh);
} else {
brelse(bh_frozen); /* already frozen */
}
unlock_page(page);
page_cache_release(page);
return 0;
}
struct buffer_head *
nilfs_mdt_get_frozen_buffer(struct inode *inode, struct buffer_head *bh)
{
struct nilfs_shadow_map *shadow = NILFS_MDT(inode)->mi_shadow;
struct buffer_head *bh_frozen = NULL;
struct page *page;
int n;
page = find_lock_page(&shadow->frozen_data, bh->b_page->index);
if (page) {
if (page_has_buffers(page)) {
n = bh_offset(bh) >> inode->i_blkbits;
bh_frozen = nilfs_page_get_nth_block(page, n);
}
unlock_page(page);
page_cache_release(page);
}
return bh_frozen;
}
static void nilfs_release_frozen_buffers(struct nilfs_shadow_map *shadow)
{
struct list_head *head = &shadow->frozen_buffers;
struct buffer_head *bh;
while (!list_empty(head)) {
bh = list_first_entry(head, struct buffer_head,
b_assoc_buffers);
list_del_init(&bh->b_assoc_buffers);
brelse(bh); /* drop ref-count to make it releasable */
}
}
/**
* nilfs_mdt_restore_from_shadow_map - restore dirty pages and bmap state
* @inode: inode of the metadata file
*/
void nilfs_mdt_restore_from_shadow_map(struct inode *inode)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
struct nilfs_inode_info *ii = NILFS_I(inode);
struct nilfs_shadow_map *shadow = mi->mi_shadow;
down_write(&mi->mi_sem);
if (mi->mi_palloc_cache)
nilfs_palloc_clear_cache(inode);
nilfs_clear_dirty_pages(inode->i_mapping);
nilfs_copy_back_pages(inode->i_mapping, &shadow->frozen_data);
nilfs_clear_dirty_pages(&ii->i_btnode_cache);
nilfs_copy_back_pages(&ii->i_btnode_cache, &shadow->frozen_btnodes);
nilfs_bmap_restore(ii->i_bmap, &shadow->bmap_store);
up_write(&mi->mi_sem);
}
/**
* nilfs_mdt_clear_shadow_map - truncate pages in shadow map caches
* @inode: inode of the metadata file
*/
void nilfs_mdt_clear_shadow_map(struct inode *inode)
{
struct nilfs_mdt_info *mi = NILFS_MDT(inode);
struct nilfs_shadow_map *shadow = mi->mi_shadow;
down_write(&mi->mi_sem);
nilfs_release_frozen_buffers(shadow);
truncate_inode_pages(&shadow->frozen_data, 0);
truncate_inode_pages(&shadow->frozen_btnodes, 0);
up_write(&mi->mi_sem);
}
| gpl-2.0 |
BigBot96/android_kernel_samsung_espressovzw-jb | arch/sh/drivers/dma/dma-g2.c | 4562 | 4776 | /*
* arch/sh/drivers/dma/dma-g2.c
*
* G2 bus DMA support
*
* Copyright (C) 2003 - 2006 Paul Mundt
*
* 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/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <asm/cacheflush.h>
#include <mach/sysasic.h>
#include <mach/dma.h>
#include <asm/dma.h>
struct g2_channel {
unsigned long g2_addr; /* G2 bus address */
unsigned long root_addr; /* Root bus (SH-4) address */
unsigned long size; /* Size (in bytes), 32-byte aligned */
unsigned long direction; /* Transfer direction */
unsigned long ctrl; /* Transfer control */
unsigned long chan_enable; /* Channel enable */
unsigned long xfer_enable; /* Transfer enable */
unsigned long xfer_stat; /* Transfer status */
} __attribute__ ((aligned(32)));
struct g2_status {
unsigned long g2_addr;
unsigned long root_addr;
unsigned long size;
unsigned long status;
} __attribute__ ((aligned(16)));
struct g2_dma_info {
struct g2_channel channel[G2_NR_DMA_CHANNELS];
unsigned long pad1[G2_NR_DMA_CHANNELS];
unsigned long wait_state;
unsigned long pad2[10];
unsigned long magic;
struct g2_status status[G2_NR_DMA_CHANNELS];
} __attribute__ ((aligned(256)));
static volatile struct g2_dma_info *g2_dma = (volatile struct g2_dma_info *)0xa05f7800;
#define g2_bytes_remaining(i) \
((g2_dma->channel[i].size - \
g2_dma->status[i].size) & 0x0fffffff)
static irqreturn_t g2_dma_interrupt(int irq, void *dev_id)
{
int i;
for (i = 0; i < G2_NR_DMA_CHANNELS; i++) {
if (g2_dma->status[i].status & 0x20000000) {
unsigned int bytes = g2_bytes_remaining(i);
if (likely(bytes == 0)) {
struct dma_info *info = dev_id;
struct dma_channel *chan = info->channels + i;
wake_up(&chan->wait_queue);
return IRQ_HANDLED;
}
}
}
return IRQ_NONE;
}
static int g2_enable_dma(struct dma_channel *chan)
{
unsigned int chan_nr = chan->chan;
g2_dma->channel[chan_nr].chan_enable = 1;
g2_dma->channel[chan_nr].xfer_enable = 1;
return 0;
}
static int g2_disable_dma(struct dma_channel *chan)
{
unsigned int chan_nr = chan->chan;
g2_dma->channel[chan_nr].chan_enable = 0;
g2_dma->channel[chan_nr].xfer_enable = 0;
return 0;
}
static int g2_xfer_dma(struct dma_channel *chan)
{
unsigned int chan_nr = chan->chan;
if (chan->sar & 31) {
printk("g2dma: unaligned source 0x%lx\n", chan->sar);
return -EINVAL;
}
if (chan->dar & 31) {
printk("g2dma: unaligned dest 0x%lx\n", chan->dar);
return -EINVAL;
}
/* Align the count */
if (chan->count & 31)
chan->count = (chan->count + (32 - 1)) & ~(32 - 1);
/* Fixup destination */
chan->dar += 0xa0800000;
/* Fixup direction */
chan->mode = !chan->mode;
flush_icache_range((unsigned long)chan->sar, chan->count);
g2_disable_dma(chan);
g2_dma->channel[chan_nr].g2_addr = chan->dar & 0x1fffffe0;
g2_dma->channel[chan_nr].root_addr = chan->sar & 0x1fffffe0;
g2_dma->channel[chan_nr].size = (chan->count & ~31) | 0x80000000;
g2_dma->channel[chan_nr].direction = chan->mode;
/*
* bit 0 - ???
* bit 1 - if set, generate a hardware event on transfer completion
* bit 2 - ??? something to do with suspend?
*/
g2_dma->channel[chan_nr].ctrl = 5; /* ?? */
g2_enable_dma(chan);
/* debug cruft */
pr_debug("count, sar, dar, mode, ctrl, chan, xfer: %ld, 0x%08lx, "
"0x%08lx, %ld, %ld, %ld, %ld\n",
g2_dma->channel[chan_nr].size,
g2_dma->channel[chan_nr].root_addr,
g2_dma->channel[chan_nr].g2_addr,
g2_dma->channel[chan_nr].direction,
g2_dma->channel[chan_nr].ctrl,
g2_dma->channel[chan_nr].chan_enable,
g2_dma->channel[chan_nr].xfer_enable);
return 0;
}
static int g2_get_residue(struct dma_channel *chan)
{
return g2_bytes_remaining(chan->chan);
}
static struct dma_ops g2_dma_ops = {
.xfer = g2_xfer_dma,
.get_residue = g2_get_residue,
};
static struct dma_info g2_dma_info = {
.name = "g2_dmac",
.nr_channels = 4,
.ops = &g2_dma_ops,
.flags = DMAC_CHANNELS_TEI_CAPABLE,
};
static int __init g2_dma_init(void)
{
int ret;
ret = request_irq(HW_EVENT_G2_DMA, g2_dma_interrupt, IRQF_DISABLED,
"g2 DMA handler", &g2_dma_info);
if (unlikely(ret))
return -EINVAL;
/* Magic */
g2_dma->wait_state = 27;
g2_dma->magic = 0x4659404f;
ret = register_dmac(&g2_dma_info);
if (unlikely(ret != 0))
free_irq(HW_EVENT_G2_DMA, 0);
return ret;
}
static void __exit g2_dma_exit(void)
{
free_irq(HW_EVENT_G2_DMA, 0);
unregister_dmac(&g2_dma_info);
}
subsys_initcall(g2_dma_init);
module_exit(g2_dma_exit);
MODULE_AUTHOR("Paul Mundt <lethal@linux-sh.org>");
MODULE_DESCRIPTION("G2 bus DMA driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
serj/kernel_graph_2.6.32_rhel | drivers/pci/hotplug/cpqphp_pci.c | 4818 | 39788 | /*
* Compaq Hot Plug Controller Driver
*
* Copyright (C) 1995,2001 Compaq Computer Corporation
* Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2001 IBM Corp.
*
* 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 <greg@kroah.com>
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/proc_fs.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include "../pci.h"
#include "cpqphp.h"
#include "cpqphp_nvram.h"
u8 cpqhp_nic_irq;
u8 cpqhp_disk_irq;
static u16 unused_IRQ;
/*
* detect_HRT_floating_pointer
*
* find the Hot Plug Resource Table in the specified region of memory.
*
*/
static void __iomem *detect_HRT_floating_pointer(void __iomem *begin, void __iomem *end)
{
void __iomem *fp;
void __iomem *endp;
u8 temp1, temp2, temp3, temp4;
int status = 0;
endp = (end - sizeof(struct hrt) + 1);
for (fp = begin; fp <= endp; fp += 16) {
temp1 = readb(fp + SIG0);
temp2 = readb(fp + SIG1);
temp3 = readb(fp + SIG2);
temp4 = readb(fp + SIG3);
if (temp1 == '$' &&
temp2 == 'H' &&
temp3 == 'R' &&
temp4 == 'T') {
status = 1;
break;
}
}
if (!status)
fp = NULL;
dbg("Discovered Hotplug Resource Table at %p\n", fp);
return fp;
}
int cpqhp_configure_device (struct controller* ctrl, struct pci_func* func)
{
unsigned char bus;
struct pci_bus *child;
int num;
if (func->pci_dev == NULL)
func->pci_dev = pci_get_bus_and_slot(func->bus,PCI_DEVFN(func->device, func->function));
/* No pci device, we need to create it then */
if (func->pci_dev == NULL) {
dbg("INFO: pci_dev still null\n");
num = pci_scan_slot(ctrl->pci_dev->bus, PCI_DEVFN(func->device, func->function));
if (num)
pci_bus_add_devices(ctrl->pci_dev->bus);
func->pci_dev = pci_get_bus_and_slot(func->bus, PCI_DEVFN(func->device, func->function));
if (func->pci_dev == NULL) {
dbg("ERROR: pci_dev still null\n");
return 0;
}
}
if (func->pci_dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
pci_read_config_byte(func->pci_dev, PCI_SECONDARY_BUS, &bus);
child = (struct pci_bus*) pci_add_new_bus(func->pci_dev->bus, (func->pci_dev), bus);
pci_do_scan_bus(child);
}
pci_dev_put(func->pci_dev);
return 0;
}
int cpqhp_unconfigure_device(struct pci_func* func)
{
int j;
dbg("%s: bus/dev/func = %x/%x/%x\n", __func__, func->bus, func->device, func->function);
for (j=0; j<8 ; j++) {
struct pci_dev* temp = pci_get_bus_and_slot(func->bus, PCI_DEVFN(func->device, j));
if (temp) {
pci_dev_put(temp);
pci_remove_bus_device(temp);
}
}
return 0;
}
static int PCI_RefinedAccessConfig(struct pci_bus *bus, unsigned int devfn, u8 offset, u32 *value)
{
u32 vendID = 0;
if (pci_bus_read_config_dword (bus, devfn, PCI_VENDOR_ID, &vendID) == -1)
return -1;
if (vendID == 0xffffffff)
return -1;
return pci_bus_read_config_dword (bus, devfn, offset, value);
}
/*
* cpqhp_set_irq
*
* @bus_num: bus number of PCI device
* @dev_num: device number of PCI device
* @slot: pointer to u8 where slot number will be returned
*/
int cpqhp_set_irq (u8 bus_num, u8 dev_num, u8 int_pin, u8 irq_num)
{
int rc = 0;
if (cpqhp_legacy_mode) {
struct pci_dev *fakedev;
struct pci_bus *fakebus;
u16 temp_word;
fakedev = kmalloc(sizeof(*fakedev), GFP_KERNEL);
fakebus = kmalloc(sizeof(*fakebus), GFP_KERNEL);
if (!fakedev || !fakebus) {
kfree(fakedev);
kfree(fakebus);
return -ENOMEM;
}
fakedev->devfn = dev_num << 3;
fakedev->bus = fakebus;
fakebus->number = bus_num;
dbg("%s: dev %d, bus %d, pin %d, num %d\n",
__func__, dev_num, bus_num, int_pin, irq_num);
rc = pcibios_set_irq_routing(fakedev, int_pin - 1, irq_num);
kfree(fakedev);
kfree(fakebus);
dbg("%s: rc %d\n", __func__, rc);
if (!rc)
return !rc;
/* set the Edge Level Control Register (ELCR) */
temp_word = inb(0x4d0);
temp_word |= inb(0x4d1) << 8;
temp_word |= 0x01 << irq_num;
/* This should only be for x86 as it sets the Edge Level
* Control Register
*/
outb((u8) (temp_word & 0xFF), 0x4d0); outb((u8) ((temp_word &
0xFF00) >> 8), 0x4d1); rc = 0; }
return rc;
}
static int PCI_ScanBusForNonBridge(struct controller *ctrl, u8 bus_num, u8 * dev_num)
{
u16 tdevice;
u32 work;
u8 tbus;
ctrl->pci_bus->number = bus_num;
for (tdevice = 0; tdevice < 0xFF; tdevice++) {
/* Scan for access first */
if (PCI_RefinedAccessConfig(ctrl->pci_bus, tdevice, 0x08, &work) == -1)
continue;
dbg("Looking for nonbridge bus_num %d dev_num %d\n", bus_num, tdevice);
/* Yep we got one. Not a bridge ? */
if ((work >> 8) != PCI_TO_PCI_BRIDGE_CLASS) {
*dev_num = tdevice;
dbg("found it !\n");
return 0;
}
}
for (tdevice = 0; tdevice < 0xFF; tdevice++) {
/* Scan for access first */
if (PCI_RefinedAccessConfig(ctrl->pci_bus, tdevice, 0x08, &work) == -1)
continue;
dbg("Looking for bridge bus_num %d dev_num %d\n", bus_num, tdevice);
/* Yep we got one. bridge ? */
if ((work >> 8) == PCI_TO_PCI_BRIDGE_CLASS) {
pci_bus_read_config_byte (ctrl->pci_bus, PCI_DEVFN(tdevice, 0), PCI_SECONDARY_BUS, &tbus);
/* XXX: no recursion, wtf? */
dbg("Recurse on bus_num %d tdevice %d\n", tbus, tdevice);
return 0;
}
}
return -1;
}
static int PCI_GetBusDevHelper(struct controller *ctrl, u8 *bus_num, u8 *dev_num, u8 slot, u8 nobridge)
{
int loop, len;
u32 work;
u8 tbus, tdevice, tslot;
len = cpqhp_routing_table_length();
for (loop = 0; loop < len; ++loop) {
tbus = cpqhp_routing_table->slots[loop].bus;
tdevice = cpqhp_routing_table->slots[loop].devfn;
tslot = cpqhp_routing_table->slots[loop].slot;
if (tslot == slot) {
*bus_num = tbus;
*dev_num = tdevice;
ctrl->pci_bus->number = tbus;
pci_bus_read_config_dword (ctrl->pci_bus, *dev_num, PCI_VENDOR_ID, &work);
if (!nobridge || (work == 0xffffffff))
return 0;
dbg("bus_num %d devfn %d\n", *bus_num, *dev_num);
pci_bus_read_config_dword (ctrl->pci_bus, *dev_num, PCI_CLASS_REVISION, &work);
dbg("work >> 8 (%x) = BRIDGE (%x)\n", work >> 8, PCI_TO_PCI_BRIDGE_CLASS);
if ((work >> 8) == PCI_TO_PCI_BRIDGE_CLASS) {
pci_bus_read_config_byte (ctrl->pci_bus, *dev_num, PCI_SECONDARY_BUS, &tbus);
dbg("Scan bus for Non Bridge: bus %d\n", tbus);
if (PCI_ScanBusForNonBridge(ctrl, tbus, dev_num) == 0) {
*bus_num = tbus;
return 0;
}
} else
return 0;
}
}
return -1;
}
int cpqhp_get_bus_dev (struct controller *ctrl, u8 * bus_num, u8 * dev_num, u8 slot)
{
/* plain (bridges allowed) */
return PCI_GetBusDevHelper(ctrl, bus_num, dev_num, slot, 0);
}
/* More PCI configuration routines; this time centered around hotplug
* controller
*/
/*
* cpqhp_save_config
*
* Reads configuration for all slots in a PCI bus and saves info.
*
* Note: For non-hot plug busses, the slot # saved is the device #
*
* returns 0 if success
*/
int cpqhp_save_config(struct controller *ctrl, int busnumber, int is_hot_plug)
{
long rc;
u8 class_code;
u8 header_type;
u32 ID;
u8 secondary_bus;
struct pci_func *new_slot;
int sub_bus;
int FirstSupported;
int LastSupported;
int max_functions;
int function;
u8 DevError;
int device = 0;
int cloop = 0;
int stop_it;
int index;
/* Decide which slots are supported */
if (is_hot_plug) {
/*
* is_hot_plug is the slot mask
*/
FirstSupported = is_hot_plug >> 4;
LastSupported = FirstSupported + (is_hot_plug & 0x0F) - 1;
} else {
FirstSupported = 0;
LastSupported = 0x1F;
}
/* Save PCI configuration space for all devices in supported slots */
ctrl->pci_bus->number = busnumber;
for (device = FirstSupported; device <= LastSupported; device++) {
ID = 0xFFFFFFFF;
rc = pci_bus_read_config_dword(ctrl->pci_bus, PCI_DEVFN(device, 0), PCI_VENDOR_ID, &ID);
if (ID == 0xFFFFFFFF) {
if (is_hot_plug) {
/* Setup slot structure with entry for empty
* slot
*/
new_slot = cpqhp_slot_create(busnumber);
if (new_slot == NULL)
return 1;
new_slot->bus = (u8) busnumber;
new_slot->device = (u8) device;
new_slot->function = 0;
new_slot->is_a_board = 0;
new_slot->presence_save = 0;
new_slot->switch_save = 0;
}
continue;
}
rc = pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(device, 0), 0x0B, &class_code);
if (rc)
return rc;
rc = pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(device, 0), PCI_HEADER_TYPE, &header_type);
if (rc)
return rc;
/* If multi-function device, set max_functions to 8 */
if (header_type & 0x80)
max_functions = 8;
else
max_functions = 1;
function = 0;
do {
DevError = 0;
if ((header_type & 0x7F) == PCI_HEADER_TYPE_BRIDGE) {
/* Recurse the subordinate bus
* get the subordinate bus number
*/
rc = pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(device, function), PCI_SECONDARY_BUS, &secondary_bus);
if (rc) {
return rc;
} else {
sub_bus = (int) secondary_bus;
/* Save secondary bus cfg spc
* with this recursive call.
*/
rc = cpqhp_save_config(ctrl, sub_bus, 0);
if (rc)
return rc;
ctrl->pci_bus->number = busnumber;
}
}
index = 0;
new_slot = cpqhp_slot_find(busnumber, device, index++);
while (new_slot &&
(new_slot->function != (u8) function))
new_slot = cpqhp_slot_find(busnumber, device, index++);
if (!new_slot) {
/* Setup slot structure. */
new_slot = cpqhp_slot_create(busnumber);
if (new_slot == NULL)
return 1;
}
new_slot->bus = (u8) busnumber;
new_slot->device = (u8) device;
new_slot->function = (u8) function;
new_slot->is_a_board = 1;
new_slot->switch_save = 0x10;
/* In case of unsupported board */
new_slot->status = DevError;
new_slot->pci_dev = pci_get_bus_and_slot(new_slot->bus, (new_slot->device << 3) | new_slot->function);
for (cloop = 0; cloop < 0x20; cloop++) {
rc = pci_bus_read_config_dword(ctrl->pci_bus, PCI_DEVFN(device, function), cloop << 2, (u32 *) & (new_slot-> config_space [cloop]));
if (rc)
return rc;
}
pci_dev_put(new_slot->pci_dev);
function++;
stop_it = 0;
/* this loop skips to the next present function
* reading in Class Code and Header type.
*/
while ((function < max_functions) && (!stop_it)) {
rc = pci_bus_read_config_dword(ctrl->pci_bus, PCI_DEVFN(device, function), PCI_VENDOR_ID, &ID);
if (ID == 0xFFFFFFFF) {
function++;
continue;
}
rc = pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(device, function), 0x0B, &class_code);
if (rc)
return rc;
rc = pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(device, function), PCI_HEADER_TYPE, &header_type);
if (rc)
return rc;
stop_it++;
}
} while (function < max_functions);
} /* End of FOR loop */
return 0;
}
/*
* cpqhp_save_slot_config
*
* Saves configuration info for all PCI devices in a given slot
* including subordinate busses.
*
* returns 0 if success
*/
int cpqhp_save_slot_config (struct controller *ctrl, struct pci_func * new_slot)
{
long rc;
u8 class_code;
u8 header_type;
u32 ID;
u8 secondary_bus;
int sub_bus;
int max_functions;
int function = 0;
int cloop = 0;
int stop_it;
ID = 0xFFFFFFFF;
ctrl->pci_bus->number = new_slot->bus;
pci_bus_read_config_dword (ctrl->pci_bus, PCI_DEVFN(new_slot->device, 0), PCI_VENDOR_ID, &ID);
if (ID == 0xFFFFFFFF)
return 2;
pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(new_slot->device, 0), 0x0B, &class_code);
pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(new_slot->device, 0), PCI_HEADER_TYPE, &header_type);
if (header_type & 0x80) /* Multi-function device */
max_functions = 8;
else
max_functions = 1;
while (function < max_functions) {
if ((header_type & 0x7F) == PCI_HEADER_TYPE_BRIDGE) {
/* Recurse the subordinate bus */
pci_bus_read_config_byte (ctrl->pci_bus, PCI_DEVFN(new_slot->device, function), PCI_SECONDARY_BUS, &secondary_bus);
sub_bus = (int) secondary_bus;
/* Save the config headers for the secondary
* bus.
*/
rc = cpqhp_save_config(ctrl, sub_bus, 0);
if (rc)
return(rc);
ctrl->pci_bus->number = new_slot->bus;
}
new_slot->status = 0;
for (cloop = 0; cloop < 0x20; cloop++)
pci_bus_read_config_dword(ctrl->pci_bus, PCI_DEVFN(new_slot->device, function), cloop << 2, (u32 *) & (new_slot-> config_space [cloop]));
function++;
stop_it = 0;
/* this loop skips to the next present function
* reading in the Class Code and the Header type.
*/
while ((function < max_functions) && (!stop_it)) {
pci_bus_read_config_dword(ctrl->pci_bus, PCI_DEVFN(new_slot->device, function), PCI_VENDOR_ID, &ID);
if (ID == 0xFFFFFFFF)
function++;
else {
pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(new_slot->device, function), 0x0B, &class_code);
pci_bus_read_config_byte(ctrl->pci_bus, PCI_DEVFN(new_slot->device, function), PCI_HEADER_TYPE, &header_type);
stop_it++;
}
}
}
return 0;
}
/*
* cpqhp_save_base_addr_length
*
* Saves the length of all base address registers for the
* specified slot. this is for hot plug REPLACE
*
* returns 0 if success
*/
int cpqhp_save_base_addr_length(struct controller *ctrl, struct pci_func * func)
{
u8 cloop;
u8 header_type;
u8 secondary_bus;
u8 type;
int sub_bus;
u32 temp_register;
u32 base;
u32 rc;
struct pci_func *next;
int index = 0;
struct pci_bus *pci_bus = ctrl->pci_bus;
unsigned int devfn;
func = cpqhp_slot_find(func->bus, func->device, index++);
while (func != NULL) {
pci_bus->number = func->bus;
devfn = PCI_DEVFN(func->device, func->function);
/* Check for Bridge */
pci_bus_read_config_byte (pci_bus, devfn, PCI_HEADER_TYPE, &header_type);
if ((header_type & 0x7F) == PCI_HEADER_TYPE_BRIDGE) {
pci_bus_read_config_byte (pci_bus, devfn, PCI_SECONDARY_BUS, &secondary_bus);
sub_bus = (int) secondary_bus;
next = cpqhp_slot_list[sub_bus];
while (next != NULL) {
rc = cpqhp_save_base_addr_length(ctrl, next);
if (rc)
return rc;
next = next->next;
}
pci_bus->number = func->bus;
/* FIXME: this loop is duplicated in the non-bridge
* case. The two could be rolled together Figure out
* IO and memory base lengths
*/
for (cloop = 0x10; cloop <= 0x14; cloop += 4) {
temp_register = 0xFFFFFFFF;
pci_bus_write_config_dword (pci_bus, devfn, cloop, temp_register);
pci_bus_read_config_dword (pci_bus, devfn, cloop, &base);
/* If this register is implemented */
if (base) {
if (base & 0x01L) {
/* IO base
* set base = amount of IO space
* requested
*/
base = base & 0xFFFFFFFE;
base = (~base) + 1;
type = 1;
} else {
/* memory base */
base = base & 0xFFFFFFF0;
base = (~base) + 1;
type = 0;
}
} else {
base = 0x0L;
type = 0;
}
/* Save information in slot structure */
func->base_length[(cloop - 0x10) >> 2] =
base;
func->base_type[(cloop - 0x10) >> 2] = type;
} /* End of base register loop */
} else if ((header_type & 0x7F) == 0x00) {
/* Figure out IO and memory base lengths */
for (cloop = 0x10; cloop <= 0x24; cloop += 4) {
temp_register = 0xFFFFFFFF;
pci_bus_write_config_dword (pci_bus, devfn, cloop, temp_register);
pci_bus_read_config_dword (pci_bus, devfn, cloop, &base);
/* If this register is implemented */
if (base) {
if (base & 0x01L) {
/* IO base
* base = amount of IO space
* requested
*/
base = base & 0xFFFFFFFE;
base = (~base) + 1;
type = 1;
} else {
/* memory base
* base = amount of memory
* space requested
*/
base = base & 0xFFFFFFF0;
base = (~base) + 1;
type = 0;
}
} else {
base = 0x0L;
type = 0;
}
/* Save information in slot structure */
func->base_length[(cloop - 0x10) >> 2] = base;
func->base_type[(cloop - 0x10) >> 2] = type;
} /* End of base register loop */
} else { /* Some other unknown header type */
}
/* find the next device in this slot */
func = cpqhp_slot_find(func->bus, func->device, index++);
}
return(0);
}
/*
* cpqhp_save_used_resources
*
* Stores used resource information for existing boards. this is
* for boards that were in the system when this driver was loaded.
* this function is for hot plug ADD
*
* returns 0 if success
*/
int cpqhp_save_used_resources (struct controller *ctrl, struct pci_func * func)
{
u8 cloop;
u8 header_type;
u8 secondary_bus;
u8 temp_byte;
u8 b_base;
u8 b_length;
u16 command;
u16 save_command;
u16 w_base;
u16 w_length;
u32 temp_register;
u32 save_base;
u32 base;
int index = 0;
struct pci_resource *mem_node;
struct pci_resource *p_mem_node;
struct pci_resource *io_node;
struct pci_resource *bus_node;
struct pci_bus *pci_bus = ctrl->pci_bus;
unsigned int devfn;
func = cpqhp_slot_find(func->bus, func->device, index++);
while ((func != NULL) && func->is_a_board) {
pci_bus->number = func->bus;
devfn = PCI_DEVFN(func->device, func->function);
/* Save the command register */
pci_bus_read_config_word(pci_bus, devfn, PCI_COMMAND, &save_command);
/* disable card */
command = 0x00;
pci_bus_write_config_word(pci_bus, devfn, PCI_COMMAND, command);
/* Check for Bridge */
pci_bus_read_config_byte(pci_bus, devfn, PCI_HEADER_TYPE, &header_type);
if ((header_type & 0x7F) == PCI_HEADER_TYPE_BRIDGE) {
/* Clear Bridge Control Register */
command = 0x00;
pci_bus_write_config_word(pci_bus, devfn, PCI_BRIDGE_CONTROL, command);
pci_bus_read_config_byte(pci_bus, devfn, PCI_SECONDARY_BUS, &secondary_bus);
pci_bus_read_config_byte(pci_bus, devfn, PCI_SUBORDINATE_BUS, &temp_byte);
bus_node = kmalloc(sizeof(*bus_node), GFP_KERNEL);
if (!bus_node)
return -ENOMEM;
bus_node->base = secondary_bus;
bus_node->length = temp_byte - secondary_bus + 1;
bus_node->next = func->bus_head;
func->bus_head = bus_node;
/* Save IO base and Limit registers */
pci_bus_read_config_byte(pci_bus, devfn, PCI_IO_BASE, &b_base);
pci_bus_read_config_byte(pci_bus, devfn, PCI_IO_LIMIT, &b_length);
if ((b_base <= b_length) && (save_command & 0x01)) {
io_node = kmalloc(sizeof(*io_node), GFP_KERNEL);
if (!io_node)
return -ENOMEM;
io_node->base = (b_base & 0xF0) << 8;
io_node->length = (b_length - b_base + 0x10) << 8;
io_node->next = func->io_head;
func->io_head = io_node;
}
/* Save memory base and Limit registers */
pci_bus_read_config_word(pci_bus, devfn, PCI_MEMORY_BASE, &w_base);
pci_bus_read_config_word(pci_bus, devfn, PCI_MEMORY_LIMIT, &w_length);
if ((w_base <= w_length) && (save_command & 0x02)) {
mem_node = kmalloc(sizeof(*mem_node), GFP_KERNEL);
if (!mem_node)
return -ENOMEM;
mem_node->base = w_base << 16;
mem_node->length = (w_length - w_base + 0x10) << 16;
mem_node->next = func->mem_head;
func->mem_head = mem_node;
}
/* Save prefetchable memory base and Limit registers */
pci_bus_read_config_word(pci_bus, devfn, PCI_PREF_MEMORY_BASE, &w_base);
pci_bus_read_config_word(pci_bus, devfn, PCI_PREF_MEMORY_LIMIT, &w_length);
if ((w_base <= w_length) && (save_command & 0x02)) {
p_mem_node = kmalloc(sizeof(*p_mem_node), GFP_KERNEL);
if (!p_mem_node)
return -ENOMEM;
p_mem_node->base = w_base << 16;
p_mem_node->length = (w_length - w_base + 0x10) << 16;
p_mem_node->next = func->p_mem_head;
func->p_mem_head = p_mem_node;
}
/* Figure out IO and memory base lengths */
for (cloop = 0x10; cloop <= 0x14; cloop += 4) {
pci_bus_read_config_dword (pci_bus, devfn, cloop, &save_base);
temp_register = 0xFFFFFFFF;
pci_bus_write_config_dword(pci_bus, devfn, cloop, temp_register);
pci_bus_read_config_dword(pci_bus, devfn, cloop, &base);
temp_register = base;
/* If this register is implemented */
if (base) {
if (((base & 0x03L) == 0x01)
&& (save_command & 0x01)) {
/* IO base
* set temp_register = amount
* of IO space requested
*/
temp_register = base & 0xFFFFFFFE;
temp_register = (~temp_register) + 1;
io_node = kmalloc(sizeof(*io_node),
GFP_KERNEL);
if (!io_node)
return -ENOMEM;
io_node->base =
save_base & (~0x03L);
io_node->length = temp_register;
io_node->next = func->io_head;
func->io_head = io_node;
} else
if (((base & 0x0BL) == 0x08)
&& (save_command & 0x02)) {
/* prefetchable memory base */
temp_register = base & 0xFFFFFFF0;
temp_register = (~temp_register) + 1;
p_mem_node = kmalloc(sizeof(*p_mem_node),
GFP_KERNEL);
if (!p_mem_node)
return -ENOMEM;
p_mem_node->base = save_base & (~0x0FL);
p_mem_node->length = temp_register;
p_mem_node->next = func->p_mem_head;
func->p_mem_head = p_mem_node;
} else
if (((base & 0x0BL) == 0x00)
&& (save_command & 0x02)) {
/* prefetchable memory base */
temp_register = base & 0xFFFFFFF0;
temp_register = (~temp_register) + 1;
mem_node = kmalloc(sizeof(*mem_node),
GFP_KERNEL);
if (!mem_node)
return -ENOMEM;
mem_node->base = save_base & (~0x0FL);
mem_node->length = temp_register;
mem_node->next = func->mem_head;
func->mem_head = mem_node;
} else
return(1);
}
} /* End of base register loop */
/* Standard header */
} else if ((header_type & 0x7F) == 0x00) {
/* Figure out IO and memory base lengths */
for (cloop = 0x10; cloop <= 0x24; cloop += 4) {
pci_bus_read_config_dword(pci_bus, devfn, cloop, &save_base);
temp_register = 0xFFFFFFFF;
pci_bus_write_config_dword(pci_bus, devfn, cloop, temp_register);
pci_bus_read_config_dword(pci_bus, devfn, cloop, &base);
temp_register = base;
/* If this register is implemented */
if (base) {
if (((base & 0x03L) == 0x01)
&& (save_command & 0x01)) {
/* IO base
* set temp_register = amount
* of IO space requested
*/
temp_register = base & 0xFFFFFFFE;
temp_register = (~temp_register) + 1;
io_node = kmalloc(sizeof(*io_node),
GFP_KERNEL);
if (!io_node)
return -ENOMEM;
io_node->base = save_base & (~0x01L);
io_node->length = temp_register;
io_node->next = func->io_head;
func->io_head = io_node;
} else
if (((base & 0x0BL) == 0x08)
&& (save_command & 0x02)) {
/* prefetchable memory base */
temp_register = base & 0xFFFFFFF0;
temp_register = (~temp_register) + 1;
p_mem_node = kmalloc(sizeof(*p_mem_node),
GFP_KERNEL);
if (!p_mem_node)
return -ENOMEM;
p_mem_node->base = save_base & (~0x0FL);
p_mem_node->length = temp_register;
p_mem_node->next = func->p_mem_head;
func->p_mem_head = p_mem_node;
} else
if (((base & 0x0BL) == 0x00)
&& (save_command & 0x02)) {
/* prefetchable memory base */
temp_register = base & 0xFFFFFFF0;
temp_register = (~temp_register) + 1;
mem_node = kmalloc(sizeof(*mem_node),
GFP_KERNEL);
if (!mem_node)
return -ENOMEM;
mem_node->base = save_base & (~0x0FL);
mem_node->length = temp_register;
mem_node->next = func->mem_head;
func->mem_head = mem_node;
} else
return(1);
}
} /* End of base register loop */
}
/* find the next device in this slot */
func = cpqhp_slot_find(func->bus, func->device, index++);
}
return 0;
}
/*
* cpqhp_configure_board
*
* Copies saved configuration information to one slot.
* this is called recursively for bridge devices.
* this is for hot plug REPLACE!
*
* returns 0 if success
*/
int cpqhp_configure_board(struct controller *ctrl, struct pci_func * func)
{
int cloop;
u8 header_type;
u8 secondary_bus;
int sub_bus;
struct pci_func *next;
u32 temp;
u32 rc;
int index = 0;
struct pci_bus *pci_bus = ctrl->pci_bus;
unsigned int devfn;
func = cpqhp_slot_find(func->bus, func->device, index++);
while (func != NULL) {
pci_bus->number = func->bus;
devfn = PCI_DEVFN(func->device, func->function);
/* Start at the top of config space so that the control
* registers are programmed last
*/
for (cloop = 0x3C; cloop > 0; cloop -= 4)
pci_bus_write_config_dword (pci_bus, devfn, cloop, func->config_space[cloop >> 2]);
pci_bus_read_config_byte (pci_bus, devfn, PCI_HEADER_TYPE, &header_type);
/* If this is a bridge device, restore subordinate devices */
if ((header_type & 0x7F) == PCI_HEADER_TYPE_BRIDGE) {
pci_bus_read_config_byte (pci_bus, devfn, PCI_SECONDARY_BUS, &secondary_bus);
sub_bus = (int) secondary_bus;
next = cpqhp_slot_list[sub_bus];
while (next != NULL) {
rc = cpqhp_configure_board(ctrl, next);
if (rc)
return rc;
next = next->next;
}
} else {
/* Check all the base Address Registers to make sure
* they are the same. If not, the board is different.
*/
for (cloop = 16; cloop < 40; cloop += 4) {
pci_bus_read_config_dword (pci_bus, devfn, cloop, &temp);
if (temp != func->config_space[cloop >> 2]) {
dbg("Config space compare failure!!! offset = %x\n", cloop);
dbg("bus = %x, device = %x, function = %x\n", func->bus, func->device, func->function);
dbg("temp = %x, config space = %x\n\n", temp, func->config_space[cloop >> 2]);
return 1;
}
}
}
func->configured = 1;
func = cpqhp_slot_find(func->bus, func->device, index++);
}
return 0;
}
/*
* cpqhp_valid_replace
*
* this function checks to see if a board is the same as the
* one it is replacing. this check will detect if the device's
* vendor or device id's are the same
*
* returns 0 if the board is the same nonzero otherwise
*/
int cpqhp_valid_replace(struct controller *ctrl, struct pci_func * func)
{
u8 cloop;
u8 header_type;
u8 secondary_bus;
u8 type;
u32 temp_register = 0;
u32 base;
u32 rc;
struct pci_func *next;
int index = 0;
struct pci_bus *pci_bus = ctrl->pci_bus;
unsigned int devfn;
if (!func->is_a_board)
return(ADD_NOT_SUPPORTED);
func = cpqhp_slot_find(func->bus, func->device, index++);
while (func != NULL) {
pci_bus->number = func->bus;
devfn = PCI_DEVFN(func->device, func->function);
pci_bus_read_config_dword (pci_bus, devfn, PCI_VENDOR_ID, &temp_register);
/* No adapter present */
if (temp_register == 0xFFFFFFFF)
return(NO_ADAPTER_PRESENT);
if (temp_register != func->config_space[0])
return(ADAPTER_NOT_SAME);
/* Check for same revision number and class code */
pci_bus_read_config_dword (pci_bus, devfn, PCI_CLASS_REVISION, &temp_register);
/* Adapter not the same */
if (temp_register != func->config_space[0x08 >> 2])
return(ADAPTER_NOT_SAME);
/* Check for Bridge */
pci_bus_read_config_byte (pci_bus, devfn, PCI_HEADER_TYPE, &header_type);
if ((header_type & 0x7F) == PCI_HEADER_TYPE_BRIDGE) {
/* In order to continue checking, we must program the
* bus registers in the bridge to respond to accesses
* for its subordinate bus(es)
*/
temp_register = func->config_space[0x18 >> 2];
pci_bus_write_config_dword (pci_bus, devfn, PCI_PRIMARY_BUS, temp_register);
secondary_bus = (temp_register >> 8) & 0xFF;
next = cpqhp_slot_list[secondary_bus];
while (next != NULL) {
rc = cpqhp_valid_replace(ctrl, next);
if (rc)
return rc;
next = next->next;
}
}
/* Check to see if it is a standard config header */
else if ((header_type & 0x7F) == PCI_HEADER_TYPE_NORMAL) {
/* Check subsystem vendor and ID */
pci_bus_read_config_dword (pci_bus, devfn, PCI_SUBSYSTEM_VENDOR_ID, &temp_register);
if (temp_register != func->config_space[0x2C >> 2]) {
/* If it's a SMART-2 and the register isn't
* filled in, ignore the difference because
* they just have an old rev of the firmware
*/
if (!((func->config_space[0] == 0xAE100E11)
&& (temp_register == 0x00L)))
return(ADAPTER_NOT_SAME);
}
/* Figure out IO and memory base lengths */
for (cloop = 0x10; cloop <= 0x24; cloop += 4) {
temp_register = 0xFFFFFFFF;
pci_bus_write_config_dword (pci_bus, devfn, cloop, temp_register);
pci_bus_read_config_dword (pci_bus, devfn, cloop, &base);
/* If this register is implemented */
if (base) {
if (base & 0x01L) {
/* IO base
* set base = amount of IO
* space requested
*/
base = base & 0xFFFFFFFE;
base = (~base) + 1;
type = 1;
} else {
/* memory base */
base = base & 0xFFFFFFF0;
base = (~base) + 1;
type = 0;
}
} else {
base = 0x0L;
type = 0;
}
/* Check information in slot structure */
if (func->base_length[(cloop - 0x10) >> 2] != base)
return(ADAPTER_NOT_SAME);
if (func->base_type[(cloop - 0x10) >> 2] != type)
return(ADAPTER_NOT_SAME);
} /* End of base register loop */
} /* End of (type 0 config space) else */
else {
/* this is not a type 0 or 1 config space header so
* we don't know how to do it
*/
return(DEVICE_TYPE_NOT_SUPPORTED);
}
/* Get the next function */
func = cpqhp_slot_find(func->bus, func->device, index++);
}
return 0;
}
/*
* cpqhp_find_available_resources
*
* Finds available memory, IO, and IRQ resources for programming
* devices which may be added to the system
* this function is for hot plug ADD!
*
* returns 0 if success
*/
int cpqhp_find_available_resources(struct controller *ctrl, void __iomem *rom_start)
{
u8 temp;
u8 populated_slot;
u8 bridged_slot;
void __iomem *one_slot;
void __iomem *rom_resource_table;
struct pci_func *func = NULL;
int i = 10, index;
u32 temp_dword, rc;
struct pci_resource *mem_node;
struct pci_resource *p_mem_node;
struct pci_resource *io_node;
struct pci_resource *bus_node;
rom_resource_table = detect_HRT_floating_pointer(rom_start, rom_start+0xffff);
dbg("rom_resource_table = %p\n", rom_resource_table);
if (rom_resource_table == NULL)
return -ENODEV;
/* Sum all resources and setup resource maps */
unused_IRQ = readl(rom_resource_table + UNUSED_IRQ);
dbg("unused_IRQ = %x\n", unused_IRQ);
temp = 0;
while (unused_IRQ) {
if (unused_IRQ & 1) {
cpqhp_disk_irq = temp;
break;
}
unused_IRQ = unused_IRQ >> 1;
temp++;
}
dbg("cpqhp_disk_irq= %d\n", cpqhp_disk_irq);
unused_IRQ = unused_IRQ >> 1;
temp++;
while (unused_IRQ) {
if (unused_IRQ & 1) {
cpqhp_nic_irq = temp;
break;
}
unused_IRQ = unused_IRQ >> 1;
temp++;
}
dbg("cpqhp_nic_irq= %d\n", cpqhp_nic_irq);
unused_IRQ = readl(rom_resource_table + PCIIRQ);
temp = 0;
if (!cpqhp_nic_irq)
cpqhp_nic_irq = ctrl->cfgspc_irq;
if (!cpqhp_disk_irq)
cpqhp_disk_irq = ctrl->cfgspc_irq;
dbg("cpqhp_disk_irq, cpqhp_nic_irq= %d, %d\n", cpqhp_disk_irq, cpqhp_nic_irq);
rc = compaq_nvram_load(rom_start, ctrl);
if (rc)
return rc;
one_slot = rom_resource_table + sizeof (struct hrt);
i = readb(rom_resource_table + NUMBER_OF_ENTRIES);
dbg("number_of_entries = %d\n", i);
if (!readb(one_slot + SECONDARY_BUS))
return 1;
dbg("dev|IO base|length|Mem base|length|Pre base|length|PB SB MB\n");
while (i && readb(one_slot + SECONDARY_BUS)) {
u8 dev_func = readb(one_slot + DEV_FUNC);
u8 primary_bus = readb(one_slot + PRIMARY_BUS);
u8 secondary_bus = readb(one_slot + SECONDARY_BUS);
u8 max_bus = readb(one_slot + MAX_BUS);
u16 io_base = readw(one_slot + IO_BASE);
u16 io_length = readw(one_slot + IO_LENGTH);
u16 mem_base = readw(one_slot + MEM_BASE);
u16 mem_length = readw(one_slot + MEM_LENGTH);
u16 pre_mem_base = readw(one_slot + PRE_MEM_BASE);
u16 pre_mem_length = readw(one_slot + PRE_MEM_LENGTH);
dbg("%2.2x | %4.4x | %4.4x | %4.4x | %4.4x | %4.4x | %4.4x |%2.2x %2.2x %2.2x\n",
dev_func, io_base, io_length, mem_base, mem_length, pre_mem_base, pre_mem_length,
primary_bus, secondary_bus, max_bus);
/* If this entry isn't for our controller's bus, ignore it */
if (primary_bus != ctrl->bus) {
i--;
one_slot += sizeof (struct slot_rt);
continue;
}
/* find out if this entry is for an occupied slot */
ctrl->pci_bus->number = primary_bus;
pci_bus_read_config_dword (ctrl->pci_bus, dev_func, PCI_VENDOR_ID, &temp_dword);
dbg("temp_D_word = %x\n", temp_dword);
if (temp_dword != 0xFFFFFFFF) {
index = 0;
func = cpqhp_slot_find(primary_bus, dev_func >> 3, 0);
while (func && (func->function != (dev_func & 0x07))) {
dbg("func = %p (bus, dev, fun) = (%d, %d, %d)\n", func, primary_bus, dev_func >> 3, index);
func = cpqhp_slot_find(primary_bus, dev_func >> 3, index++);
}
/* If we can't find a match, skip this table entry */
if (!func) {
i--;
one_slot += sizeof (struct slot_rt);
continue;
}
/* this may not work and shouldn't be used */
if (secondary_bus != primary_bus)
bridged_slot = 1;
else
bridged_slot = 0;
populated_slot = 1;
} else {
populated_slot = 0;
bridged_slot = 0;
}
/* If we've got a valid IO base, use it */
temp_dword = io_base + io_length;
if ((io_base) && (temp_dword < 0x10000)) {
io_node = kmalloc(sizeof(*io_node), GFP_KERNEL);
if (!io_node)
return -ENOMEM;
io_node->base = io_base;
io_node->length = io_length;
dbg("found io_node(base, length) = %x, %x\n",
io_node->base, io_node->length);
dbg("populated slot =%d \n", populated_slot);
if (!populated_slot) {
io_node->next = ctrl->io_head;
ctrl->io_head = io_node;
} else {
io_node->next = func->io_head;
func->io_head = io_node;
}
}
/* If we've got a valid memory base, use it */
temp_dword = mem_base + mem_length;
if ((mem_base) && (temp_dword < 0x10000)) {
mem_node = kmalloc(sizeof(*mem_node), GFP_KERNEL);
if (!mem_node)
return -ENOMEM;
mem_node->base = mem_base << 16;
mem_node->length = mem_length << 16;
dbg("found mem_node(base, length) = %x, %x\n",
mem_node->base, mem_node->length);
dbg("populated slot =%d \n", populated_slot);
if (!populated_slot) {
mem_node->next = ctrl->mem_head;
ctrl->mem_head = mem_node;
} else {
mem_node->next = func->mem_head;
func->mem_head = mem_node;
}
}
/* If we've got a valid prefetchable memory base, and
* the base + length isn't greater than 0xFFFF
*/
temp_dword = pre_mem_base + pre_mem_length;
if ((pre_mem_base) && (temp_dword < 0x10000)) {
p_mem_node = kmalloc(sizeof(*p_mem_node), GFP_KERNEL);
if (!p_mem_node)
return -ENOMEM;
p_mem_node->base = pre_mem_base << 16;
p_mem_node->length = pre_mem_length << 16;
dbg("found p_mem_node(base, length) = %x, %x\n",
p_mem_node->base, p_mem_node->length);
dbg("populated slot =%d \n", populated_slot);
if (!populated_slot) {
p_mem_node->next = ctrl->p_mem_head;
ctrl->p_mem_head = p_mem_node;
} else {
p_mem_node->next = func->p_mem_head;
func->p_mem_head = p_mem_node;
}
}
/* If we've got a valid bus number, use it
* The second condition is to ignore bus numbers on
* populated slots that don't have PCI-PCI bridges
*/
if (secondary_bus && (secondary_bus != primary_bus)) {
bus_node = kmalloc(sizeof(*bus_node), GFP_KERNEL);
if (!bus_node)
return -ENOMEM;
bus_node->base = secondary_bus;
bus_node->length = max_bus - secondary_bus + 1;
dbg("found bus_node(base, length) = %x, %x\n",
bus_node->base, bus_node->length);
dbg("populated slot =%d \n", populated_slot);
if (!populated_slot) {
bus_node->next = ctrl->bus_head;
ctrl->bus_head = bus_node;
} else {
bus_node->next = func->bus_head;
func->bus_head = bus_node;
}
}
i--;
one_slot += sizeof (struct slot_rt);
}
/* If all of the following fail, we don't have any resources for
* hot plug add
*/
rc = 1;
rc &= cpqhp_resource_sort_and_combine(&(ctrl->mem_head));
rc &= cpqhp_resource_sort_and_combine(&(ctrl->p_mem_head));
rc &= cpqhp_resource_sort_and_combine(&(ctrl->io_head));
rc &= cpqhp_resource_sort_and_combine(&(ctrl->bus_head));
return rc;
}
/*
* cpqhp_return_board_resources
*
* this routine returns all resources allocated to a board to
* the available pool.
*
* returns 0 if success
*/
int cpqhp_return_board_resources(struct pci_func * func, struct resource_lists * resources)
{
int rc = 0;
struct pci_resource *node;
struct pci_resource *t_node;
dbg("%s\n", __func__);
if (!func)
return 1;
node = func->io_head;
func->io_head = NULL;
while (node) {
t_node = node->next;
return_resource(&(resources->io_head), node);
node = t_node;
}
node = func->mem_head;
func->mem_head = NULL;
while (node) {
t_node = node->next;
return_resource(&(resources->mem_head), node);
node = t_node;
}
node = func->p_mem_head;
func->p_mem_head = NULL;
while (node) {
t_node = node->next;
return_resource(&(resources->p_mem_head), node);
node = t_node;
}
node = func->bus_head;
func->bus_head = NULL;
while (node) {
t_node = node->next;
return_resource(&(resources->bus_head), node);
node = t_node;
}
rc |= cpqhp_resource_sort_and_combine(&(resources->mem_head));
rc |= cpqhp_resource_sort_and_combine(&(resources->p_mem_head));
rc |= cpqhp_resource_sort_and_combine(&(resources->io_head));
rc |= cpqhp_resource_sort_and_combine(&(resources->bus_head));
return rc;
}
/*
* cpqhp_destroy_resource_list
*
* Puts node back in the resource list pointed to by head
*/
void cpqhp_destroy_resource_list (struct resource_lists * resources)
{
struct pci_resource *res, *tres;
res = resources->io_head;
resources->io_head = NULL;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
res = resources->mem_head;
resources->mem_head = NULL;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
res = resources->p_mem_head;
resources->p_mem_head = NULL;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
res = resources->bus_head;
resources->bus_head = NULL;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
}
/*
* cpqhp_destroy_board_resources
*
* Puts node back in the resource list pointed to by head
*/
void cpqhp_destroy_board_resources (struct pci_func * func)
{
struct pci_resource *res, *tres;
res = func->io_head;
func->io_head = NULL;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
res = func->mem_head;
func->mem_head = NULL;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
res = func->p_mem_head;
func->p_mem_head = NULL;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
res = func->bus_head;
func->bus_head = NULL;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
}
| gpl-2.0 |
Fagulhas/android_kernel_huawei_u8815 | drivers/net/wireless/iwlwifi/iwl-drv.c | 4818 | 29546 | /******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2007 - 2012 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called LICENSE.GPL.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2005 - 2012 Intel Corporation. All rights reserved.
* 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 Intel Corporation nor the names of its
* 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.
*
*****************************************************************************/
#include <linux/completion.h>
#include <linux/dma-mapping.h>
#include <linux/firmware.h>
#include <linux/module.h>
#include "iwl-drv.h"
#include "iwl-trans.h"
#include "iwl-shared.h"
#include "iwl-op-mode.h"
#include "iwl-agn-hw.h"
/* private includes */
#include "iwl-fw-file.h"
/**
* struct iwl_drv - drv common data
* @fw: the iwl_fw structure
* @shrd: pointer to common shared structure
* @op_mode: the running op_mode
* @fw_index: firmware revision to try loading
* @firmware_name: composite filename of ucode file to load
* @request_firmware_complete: the firmware has been obtained from user space
*/
struct iwl_drv {
struct iwl_fw fw;
struct iwl_shared *shrd;
struct iwl_op_mode *op_mode;
int fw_index; /* firmware we're trying to load */
char firmware_name[25]; /* name of firmware file to load */
struct completion request_firmware_complete;
};
/*
* struct fw_sec: Just for the image parsing proccess.
* For the fw storage we are using struct fw_desc.
*/
struct fw_sec {
const void *data; /* the sec data */
size_t size; /* section size */
u32 offset; /* offset of writing in the device */
};
static void iwl_free_fw_desc(struct iwl_drv *drv, struct fw_desc *desc)
{
if (desc->v_addr)
dma_free_coherent(trans(drv)->dev, desc->len,
desc->v_addr, desc->p_addr);
desc->v_addr = NULL;
desc->len = 0;
}
static void iwl_free_fw_img(struct iwl_drv *drv, struct fw_img *img)
{
int i;
for (i = 0; i < IWL_UCODE_SECTION_MAX; i++)
iwl_free_fw_desc(drv, &img->sec[i]);
}
static void iwl_dealloc_ucode(struct iwl_drv *drv)
{
int i;
for (i = 0; i < IWL_UCODE_TYPE_MAX; i++)
iwl_free_fw_img(drv, drv->fw.img + i);
}
static int iwl_alloc_fw_desc(struct iwl_drv *drv, struct fw_desc *desc,
struct fw_sec *sec)
{
if (!sec || !sec->size) {
desc->v_addr = NULL;
return -EINVAL;
}
desc->v_addr = dma_alloc_coherent(trans(drv)->dev, sec->size,
&desc->p_addr, GFP_KERNEL);
if (!desc->v_addr)
return -ENOMEM;
desc->len = sec->size;
desc->offset = sec->offset;
memcpy(desc->v_addr, sec->data, sec->size);
return 0;
}
static void iwl_ucode_callback(const struct firmware *ucode_raw, void *context);
#define UCODE_EXPERIMENTAL_INDEX 100
#define UCODE_EXPERIMENTAL_TAG "exp"
static int iwl_request_firmware(struct iwl_drv *drv, bool first)
{
const struct iwl_cfg *cfg = cfg(drv);
const char *name_pre = cfg->fw_name_pre;
char tag[8];
if (first) {
#ifdef CONFIG_IWLWIFI_DEBUG_EXPERIMENTAL_UCODE
drv->fw_index = UCODE_EXPERIMENTAL_INDEX;
strcpy(tag, UCODE_EXPERIMENTAL_TAG);
} else if (drv->fw_index == UCODE_EXPERIMENTAL_INDEX) {
#endif
drv->fw_index = cfg->ucode_api_max;
sprintf(tag, "%d", drv->fw_index);
} else {
drv->fw_index--;
sprintf(tag, "%d", drv->fw_index);
}
if (drv->fw_index < cfg->ucode_api_min) {
IWL_ERR(drv, "no suitable firmware found!\n");
return -ENOENT;
}
sprintf(drv->firmware_name, "%s%s%s", name_pre, tag, ".ucode");
IWL_DEBUG_INFO(drv, "attempting to load firmware %s'%s'\n",
(drv->fw_index == UCODE_EXPERIMENTAL_INDEX)
? "EXPERIMENTAL " : "",
drv->firmware_name);
return request_firmware_nowait(THIS_MODULE, 1, drv->firmware_name,
trans(drv)->dev,
GFP_KERNEL, drv, iwl_ucode_callback);
}
struct fw_img_parsing {
struct fw_sec sec[IWL_UCODE_SECTION_MAX];
int sec_counter;
};
/*
* struct fw_sec_parsing: to extract fw section and it's offset from tlv
*/
struct fw_sec_parsing {
__le32 offset;
const u8 data[];
} __packed;
/**
* struct iwl_tlv_calib_data - parse the default calib data from TLV
*
* @ucode_type: the uCode to which the following default calib relates.
* @calib: default calibrations.
*/
struct iwl_tlv_calib_data {
__le32 ucode_type;
__le64 calib;
} __packed;
struct iwl_firmware_pieces {
struct fw_img_parsing img[IWL_UCODE_TYPE_MAX];
u32 init_evtlog_ptr, init_evtlog_size, init_errlog_ptr;
u32 inst_evtlog_ptr, inst_evtlog_size, inst_errlog_ptr;
};
/*
* These functions are just to extract uCode section data from the pieces
* structure.
*/
static struct fw_sec *get_sec(struct iwl_firmware_pieces *pieces,
enum iwl_ucode_type type,
int sec)
{
return &pieces->img[type].sec[sec];
}
static void set_sec_data(struct iwl_firmware_pieces *pieces,
enum iwl_ucode_type type,
int sec,
const void *data)
{
pieces->img[type].sec[sec].data = data;
}
static void set_sec_size(struct iwl_firmware_pieces *pieces,
enum iwl_ucode_type type,
int sec,
size_t size)
{
pieces->img[type].sec[sec].size = size;
}
static size_t get_sec_size(struct iwl_firmware_pieces *pieces,
enum iwl_ucode_type type,
int sec)
{
return pieces->img[type].sec[sec].size;
}
static void set_sec_offset(struct iwl_firmware_pieces *pieces,
enum iwl_ucode_type type,
int sec,
u32 offset)
{
pieces->img[type].sec[sec].offset = offset;
}
/*
* Gets uCode section from tlv.
*/
static int iwl_store_ucode_sec(struct iwl_firmware_pieces *pieces,
const void *data, enum iwl_ucode_type type,
int size)
{
struct fw_img_parsing *img;
struct fw_sec *sec;
struct fw_sec_parsing *sec_parse;
if (WARN_ON(!pieces || !data || type >= IWL_UCODE_TYPE_MAX))
return -1;
sec_parse = (struct fw_sec_parsing *)data;
img = &pieces->img[type];
sec = &img->sec[img->sec_counter];
sec->offset = le32_to_cpu(sec_parse->offset);
sec->data = sec_parse->data;
++img->sec_counter;
return 0;
}
static int iwl_set_default_calib(struct iwl_drv *drv, const u8 *data)
{
struct iwl_tlv_calib_data *def_calib =
(struct iwl_tlv_calib_data *)data;
u32 ucode_type = le32_to_cpu(def_calib->ucode_type);
if (ucode_type >= IWL_UCODE_TYPE_MAX) {
IWL_ERR(drv, "Wrong ucode_type %u for default calibration.\n",
ucode_type);
return -EINVAL;
}
drv->fw.default_calib[ucode_type] = le64_to_cpu(def_calib->calib);
return 0;
}
static int iwl_parse_v1_v2_firmware(struct iwl_drv *drv,
const struct firmware *ucode_raw,
struct iwl_firmware_pieces *pieces)
{
struct iwl_ucode_header *ucode = (void *)ucode_raw->data;
u32 api_ver, hdr_size, build;
char buildstr[25];
const u8 *src;
drv->fw.ucode_ver = le32_to_cpu(ucode->ver);
api_ver = IWL_UCODE_API(drv->fw.ucode_ver);
switch (api_ver) {
default:
hdr_size = 28;
if (ucode_raw->size < hdr_size) {
IWL_ERR(drv, "File size too small!\n");
return -EINVAL;
}
build = le32_to_cpu(ucode->u.v2.build);
set_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST,
le32_to_cpu(ucode->u.v2.inst_size));
set_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA,
le32_to_cpu(ucode->u.v2.data_size));
set_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST,
le32_to_cpu(ucode->u.v2.init_size));
set_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA,
le32_to_cpu(ucode->u.v2.init_data_size));
src = ucode->u.v2.data;
break;
case 0:
case 1:
case 2:
hdr_size = 24;
if (ucode_raw->size < hdr_size) {
IWL_ERR(drv, "File size too small!\n");
return -EINVAL;
}
build = 0;
set_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST,
le32_to_cpu(ucode->u.v1.inst_size));
set_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA,
le32_to_cpu(ucode->u.v1.data_size));
set_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST,
le32_to_cpu(ucode->u.v1.init_size));
set_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA,
le32_to_cpu(ucode->u.v1.init_data_size));
src = ucode->u.v1.data;
break;
}
if (build)
sprintf(buildstr, " build %u%s", build,
(drv->fw_index == UCODE_EXPERIMENTAL_INDEX)
? " (EXP)" : "");
else
buildstr[0] = '\0';
snprintf(drv->fw.fw_version,
sizeof(drv->fw.fw_version),
"%u.%u.%u.%u%s",
IWL_UCODE_MAJOR(drv->fw.ucode_ver),
IWL_UCODE_MINOR(drv->fw.ucode_ver),
IWL_UCODE_API(drv->fw.ucode_ver),
IWL_UCODE_SERIAL(drv->fw.ucode_ver),
buildstr);
/* Verify size of file vs. image size info in file's header */
if (ucode_raw->size != hdr_size +
get_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST) +
get_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA) +
get_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST) +
get_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA)) {
IWL_ERR(drv,
"uCode file size %d does not match expected size\n",
(int)ucode_raw->size);
return -EINVAL;
}
set_sec_data(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST, src);
src += get_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST);
set_sec_offset(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST,
IWLAGN_RTC_INST_LOWER_BOUND);
set_sec_data(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA, src);
src += get_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA);
set_sec_offset(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA,
IWLAGN_RTC_DATA_LOWER_BOUND);
set_sec_data(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST, src);
src += get_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST);
set_sec_offset(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST,
IWLAGN_RTC_INST_LOWER_BOUND);
set_sec_data(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA, src);
src += get_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA);
set_sec_offset(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA,
IWLAGN_RTC_DATA_LOWER_BOUND);
return 0;
}
static int iwl_parse_tlv_firmware(struct iwl_drv *drv,
const struct firmware *ucode_raw,
struct iwl_firmware_pieces *pieces,
struct iwl_ucode_capabilities *capa)
{
struct iwl_tlv_ucode_header *ucode = (void *)ucode_raw->data;
struct iwl_ucode_tlv *tlv;
size_t len = ucode_raw->size;
const u8 *data;
int wanted_alternative = iwlagn_mod_params.wanted_ucode_alternative;
int tmp;
u64 alternatives;
u32 tlv_len;
enum iwl_ucode_tlv_type tlv_type;
const u8 *tlv_data;
char buildstr[25];
u32 build;
if (len < sizeof(*ucode)) {
IWL_ERR(drv, "uCode has invalid length: %zd\n", len);
return -EINVAL;
}
if (ucode->magic != cpu_to_le32(IWL_TLV_UCODE_MAGIC)) {
IWL_ERR(drv, "invalid uCode magic: 0X%x\n",
le32_to_cpu(ucode->magic));
return -EINVAL;
}
/*
* Check which alternatives are present, and "downgrade"
* when the chosen alternative is not present, warning
* the user when that happens. Some files may not have
* any alternatives, so don't warn in that case.
*/
alternatives = le64_to_cpu(ucode->alternatives);
tmp = wanted_alternative;
if (wanted_alternative > 63)
wanted_alternative = 63;
while (wanted_alternative && !(alternatives & BIT(wanted_alternative)))
wanted_alternative--;
if (wanted_alternative && wanted_alternative != tmp)
IWL_WARN(drv,
"uCode alternative %d not available, choosing %d\n",
tmp, wanted_alternative);
drv->fw.ucode_ver = le32_to_cpu(ucode->ver);
build = le32_to_cpu(ucode->build);
if (build)
sprintf(buildstr, " build %u%s", build,
(drv->fw_index == UCODE_EXPERIMENTAL_INDEX)
? " (EXP)" : "");
else
buildstr[0] = '\0';
snprintf(drv->fw.fw_version,
sizeof(drv->fw.fw_version),
"%u.%u.%u.%u%s",
IWL_UCODE_MAJOR(drv->fw.ucode_ver),
IWL_UCODE_MINOR(drv->fw.ucode_ver),
IWL_UCODE_API(drv->fw.ucode_ver),
IWL_UCODE_SERIAL(drv->fw.ucode_ver),
buildstr);
data = ucode->data;
len -= sizeof(*ucode);
while (len >= sizeof(*tlv)) {
u16 tlv_alt;
len -= sizeof(*tlv);
tlv = (void *)data;
tlv_len = le32_to_cpu(tlv->length);
tlv_type = le16_to_cpu(tlv->type);
tlv_alt = le16_to_cpu(tlv->alternative);
tlv_data = tlv->data;
if (len < tlv_len) {
IWL_ERR(drv, "invalid TLV len: %zd/%u\n",
len, tlv_len);
return -EINVAL;
}
len -= ALIGN(tlv_len, 4);
data += sizeof(*tlv) + ALIGN(tlv_len, 4);
/*
* Alternative 0 is always valid.
*
* Skip alternative TLVs that are not selected.
*/
if (tlv_alt != 0 && tlv_alt != wanted_alternative)
continue;
switch (tlv_type) {
case IWL_UCODE_TLV_INST:
set_sec_data(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_INST, tlv_data);
set_sec_size(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_INST, tlv_len);
set_sec_offset(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_INST,
IWLAGN_RTC_INST_LOWER_BOUND);
break;
case IWL_UCODE_TLV_DATA:
set_sec_data(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_DATA, tlv_data);
set_sec_size(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_DATA, tlv_len);
set_sec_offset(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_DATA,
IWLAGN_RTC_DATA_LOWER_BOUND);
break;
case IWL_UCODE_TLV_INIT:
set_sec_data(pieces, IWL_UCODE_INIT,
IWL_UCODE_SECTION_INST, tlv_data);
set_sec_size(pieces, IWL_UCODE_INIT,
IWL_UCODE_SECTION_INST, tlv_len);
set_sec_offset(pieces, IWL_UCODE_INIT,
IWL_UCODE_SECTION_INST,
IWLAGN_RTC_INST_LOWER_BOUND);
break;
case IWL_UCODE_TLV_INIT_DATA:
set_sec_data(pieces, IWL_UCODE_INIT,
IWL_UCODE_SECTION_DATA, tlv_data);
set_sec_size(pieces, IWL_UCODE_INIT,
IWL_UCODE_SECTION_DATA, tlv_len);
set_sec_offset(pieces, IWL_UCODE_INIT,
IWL_UCODE_SECTION_DATA,
IWLAGN_RTC_DATA_LOWER_BOUND);
break;
case IWL_UCODE_TLV_BOOT:
IWL_ERR(drv, "Found unexpected BOOT ucode\n");
break;
case IWL_UCODE_TLV_PROBE_MAX_LEN:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
capa->max_probe_length =
le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_PAN:
if (tlv_len)
goto invalid_tlv_len;
capa->flags |= IWL_UCODE_TLV_FLAGS_PAN;
break;
case IWL_UCODE_TLV_FLAGS:
/* must be at least one u32 */
if (tlv_len < sizeof(u32))
goto invalid_tlv_len;
/* and a proper number of u32s */
if (tlv_len % sizeof(u32))
goto invalid_tlv_len;
/*
* This driver only reads the first u32 as
* right now no more features are defined,
* if that changes then either the driver
* will not work with the new firmware, or
* it'll not take advantage of new features.
*/
capa->flags = le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_INIT_EVTLOG_PTR:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
pieces->init_evtlog_ptr =
le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_INIT_EVTLOG_SIZE:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
pieces->init_evtlog_size =
le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_INIT_ERRLOG_PTR:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
pieces->init_errlog_ptr =
le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_RUNT_EVTLOG_PTR:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
pieces->inst_evtlog_ptr =
le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_RUNT_EVTLOG_SIZE:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
pieces->inst_evtlog_size =
le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_RUNT_ERRLOG_PTR:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
pieces->inst_errlog_ptr =
le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_ENHANCE_SENS_TBL:
if (tlv_len)
goto invalid_tlv_len;
drv->fw.enhance_sensitivity_table = true;
break;
case IWL_UCODE_TLV_WOWLAN_INST:
set_sec_data(pieces, IWL_UCODE_WOWLAN,
IWL_UCODE_SECTION_INST, tlv_data);
set_sec_size(pieces, IWL_UCODE_WOWLAN,
IWL_UCODE_SECTION_INST, tlv_len);
set_sec_offset(pieces, IWL_UCODE_WOWLAN,
IWL_UCODE_SECTION_INST,
IWLAGN_RTC_INST_LOWER_BOUND);
break;
case IWL_UCODE_TLV_WOWLAN_DATA:
set_sec_data(pieces, IWL_UCODE_WOWLAN,
IWL_UCODE_SECTION_DATA, tlv_data);
set_sec_size(pieces, IWL_UCODE_WOWLAN,
IWL_UCODE_SECTION_DATA, tlv_len);
set_sec_offset(pieces, IWL_UCODE_WOWLAN,
IWL_UCODE_SECTION_DATA,
IWLAGN_RTC_DATA_LOWER_BOUND);
break;
case IWL_UCODE_TLV_PHY_CALIBRATION_SIZE:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
capa->standard_phy_calibration_size =
le32_to_cpup((__le32 *)tlv_data);
break;
case IWL_UCODE_TLV_SEC_RT:
iwl_store_ucode_sec(pieces, tlv_data, IWL_UCODE_REGULAR,
tlv_len);
drv->fw.mvm_fw = true;
break;
case IWL_UCODE_TLV_SEC_INIT:
iwl_store_ucode_sec(pieces, tlv_data, IWL_UCODE_INIT,
tlv_len);
drv->fw.mvm_fw = true;
break;
case IWL_UCODE_TLV_SEC_WOWLAN:
iwl_store_ucode_sec(pieces, tlv_data, IWL_UCODE_WOWLAN,
tlv_len);
drv->fw.mvm_fw = true;
break;
case IWL_UCODE_TLV_DEF_CALIB:
if (tlv_len != sizeof(struct iwl_tlv_calib_data))
goto invalid_tlv_len;
if (iwl_set_default_calib(drv, tlv_data))
goto tlv_error;
break;
case IWL_UCODE_TLV_PHY_SKU:
if (tlv_len != sizeof(u32))
goto invalid_tlv_len;
drv->fw.phy_config = le32_to_cpup((__le32 *)tlv_data);
break;
default:
IWL_DEBUG_INFO(drv, "unknown TLV: %d\n", tlv_type);
break;
}
}
if (len) {
IWL_ERR(drv, "invalid TLV after parsing: %zd\n", len);
iwl_print_hex_dump(drv, IWL_DL_FW, (u8 *)data, len);
return -EINVAL;
}
return 0;
invalid_tlv_len:
IWL_ERR(drv, "TLV %d has invalid size: %u\n", tlv_type, tlv_len);
tlv_error:
iwl_print_hex_dump(drv, IWL_DL_FW, tlv_data, tlv_len);
return -EINVAL;
}
static int alloc_pci_desc(struct iwl_drv *drv,
struct iwl_firmware_pieces *pieces,
enum iwl_ucode_type type)
{
int i;
for (i = 0;
i < IWL_UCODE_SECTION_MAX && get_sec_size(pieces, type, i);
i++)
if (iwl_alloc_fw_desc(drv, &(drv->fw.img[type].sec[i]),
get_sec(pieces, type, i)))
return -1;
return 0;
}
static int validate_sec_sizes(struct iwl_drv *drv,
struct iwl_firmware_pieces *pieces,
const struct iwl_cfg *cfg)
{
IWL_DEBUG_INFO(drv, "f/w package hdr runtime inst size = %Zd\n",
get_sec_size(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_INST));
IWL_DEBUG_INFO(drv, "f/w package hdr runtime data size = %Zd\n",
get_sec_size(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_DATA));
IWL_DEBUG_INFO(drv, "f/w package hdr init inst size = %Zd\n",
get_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST));
IWL_DEBUG_INFO(drv, "f/w package hdr init data size = %Zd\n",
get_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA));
/* Verify that uCode images will fit in card's SRAM. */
if (get_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST) >
cfg->max_inst_size) {
IWL_ERR(drv, "uCode instr len %Zd too large to fit in\n",
get_sec_size(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_INST));
return -1;
}
if (get_sec_size(pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA) >
cfg->max_data_size) {
IWL_ERR(drv, "uCode data len %Zd too large to fit in\n",
get_sec_size(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_DATA));
return -1;
}
if (get_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST) >
cfg->max_inst_size) {
IWL_ERR(drv, "uCode init instr len %Zd too large to fit in\n",
get_sec_size(pieces, IWL_UCODE_INIT,
IWL_UCODE_SECTION_INST));
return -1;
}
if (get_sec_size(pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA) >
cfg->max_data_size) {
IWL_ERR(drv, "uCode init data len %Zd too large to fit in\n",
get_sec_size(pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_DATA));
return -1;
}
return 0;
}
/**
* iwl_ucode_callback - callback when firmware was loaded
*
* If loaded successfully, copies the firmware into buffers
* for the card to fetch (via DMA).
*/
static void iwl_ucode_callback(const struct firmware *ucode_raw, void *context)
{
struct iwl_drv *drv = context;
const struct iwl_cfg *cfg = cfg(drv);
struct iwl_fw *fw = &drv->fw;
struct iwl_ucode_header *ucode;
int err;
struct iwl_firmware_pieces pieces;
const unsigned int api_max = cfg->ucode_api_max;
unsigned int api_ok = cfg->ucode_api_ok;
const unsigned int api_min = cfg->ucode_api_min;
u32 api_ver;
int i;
fw->ucode_capa.max_probe_length = 200;
fw->ucode_capa.standard_phy_calibration_size =
IWL_DEFAULT_STANDARD_PHY_CALIBRATE_TBL_SIZE;
if (!api_ok)
api_ok = api_max;
memset(&pieces, 0, sizeof(pieces));
if (!ucode_raw) {
if (drv->fw_index <= api_ok)
IWL_ERR(drv,
"request for firmware file '%s' failed.\n",
drv->firmware_name);
goto try_again;
}
IWL_DEBUG_INFO(drv, "Loaded firmware file '%s' (%zd bytes).\n",
drv->firmware_name, ucode_raw->size);
/* Make sure that we got at least the API version number */
if (ucode_raw->size < 4) {
IWL_ERR(drv, "File size way too small!\n");
goto try_again;
}
/* Data from ucode file: header followed by uCode images */
ucode = (struct iwl_ucode_header *)ucode_raw->data;
if (ucode->ver)
err = iwl_parse_v1_v2_firmware(drv, ucode_raw, &pieces);
else
err = iwl_parse_tlv_firmware(drv, ucode_raw, &pieces,
&fw->ucode_capa);
if (err)
goto try_again;
api_ver = IWL_UCODE_API(drv->fw.ucode_ver);
/*
* api_ver should match the api version forming part of the
* firmware filename ... but we don't check for that and only rely
* on the API version read from firmware header from here on forward
*/
/* no api version check required for experimental uCode */
if (drv->fw_index != UCODE_EXPERIMENTAL_INDEX) {
if (api_ver < api_min || api_ver > api_max) {
IWL_ERR(drv,
"Driver unable to support your firmware API. "
"Driver supports v%u, firmware is v%u.\n",
api_max, api_ver);
goto try_again;
}
if (api_ver < api_ok) {
if (api_ok != api_max)
IWL_ERR(drv, "Firmware has old API version, "
"expected v%u through v%u, got v%u.\n",
api_ok, api_max, api_ver);
else
IWL_ERR(drv, "Firmware has old API version, "
"expected v%u, got v%u.\n",
api_max, api_ver);
IWL_ERR(drv, "New firmware can be obtained from "
"http://www.intellinuxwireless.org/.\n");
}
}
IWL_INFO(drv, "loaded firmware version %s", drv->fw.fw_version);
/*
* For any of the failures below (before allocating pci memory)
* we will try to load a version with a smaller API -- maybe the
* user just got a corrupted version of the latest API.
*/
IWL_DEBUG_INFO(drv, "f/w package hdr ucode version raw = 0x%x\n",
drv->fw.ucode_ver);
IWL_DEBUG_INFO(drv, "f/w package hdr runtime inst size = %Zd\n",
get_sec_size(&pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_INST));
IWL_DEBUG_INFO(drv, "f/w package hdr runtime data size = %Zd\n",
get_sec_size(&pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_DATA));
IWL_DEBUG_INFO(drv, "f/w package hdr init inst size = %Zd\n",
get_sec_size(&pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_INST));
IWL_DEBUG_INFO(drv, "f/w package hdr init data size = %Zd\n",
get_sec_size(&pieces, IWL_UCODE_INIT, IWL_UCODE_SECTION_DATA));
/* Verify that uCode images will fit in card's SRAM */
if (get_sec_size(&pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_INST) >
cfg->max_inst_size) {
IWL_ERR(drv, "uCode instr len %Zd too large to fit in\n",
get_sec_size(&pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_INST));
goto try_again;
}
if (get_sec_size(&pieces, IWL_UCODE_REGULAR, IWL_UCODE_SECTION_DATA) >
cfg->max_data_size) {
IWL_ERR(drv, "uCode data len %Zd too large to fit in\n",
get_sec_size(&pieces, IWL_UCODE_REGULAR,
IWL_UCODE_SECTION_DATA));
goto try_again;
}
/*
* In mvm uCode there is no difference between data and instructions
* sections.
*/
if (!fw->mvm_fw && validate_sec_sizes(drv, &pieces, cfg))
goto try_again;
/* Allocate ucode buffers for card's bus-master loading ... */
/* Runtime instructions and 2 copies of data:
* 1) unmodified from disk
* 2) backup cache for save/restore during power-downs */
for (i = 0; i < IWL_UCODE_TYPE_MAX; i++)
if (alloc_pci_desc(drv, &pieces, i))
goto err_pci_alloc;
/* Now that we can no longer fail, copy information */
/*
* The (size - 16) / 12 formula is based on the information recorded
* for each event, which is of mode 1 (including timestamp) for all
* new microcodes that include this information.
*/
fw->init_evtlog_ptr = pieces.init_evtlog_ptr;
if (pieces.init_evtlog_size)
fw->init_evtlog_size = (pieces.init_evtlog_size - 16)/12;
else
fw->init_evtlog_size =
cfg->base_params->max_event_log_size;
fw->init_errlog_ptr = pieces.init_errlog_ptr;
fw->inst_evtlog_ptr = pieces.inst_evtlog_ptr;
if (pieces.inst_evtlog_size)
fw->inst_evtlog_size = (pieces.inst_evtlog_size - 16)/12;
else
fw->inst_evtlog_size =
cfg->base_params->max_event_log_size;
fw->inst_errlog_ptr = pieces.inst_errlog_ptr;
/*
* figure out the offset of chain noise reset and gain commands
* base on the size of standard phy calibration commands table size
*/
if (fw->ucode_capa.standard_phy_calibration_size >
IWL_MAX_PHY_CALIBRATE_TBL_SIZE)
fw->ucode_capa.standard_phy_calibration_size =
IWL_MAX_STANDARD_PHY_CALIBRATE_TBL_SIZE;
/* We have our copies now, allow OS release its copies */
release_firmware(ucode_raw);
complete(&drv->request_firmware_complete);
drv->op_mode = iwl_dvm_ops.start(drv->shrd->trans, &drv->fw);
if (!drv->op_mode)
goto out_unbind;
return;
try_again:
/* try next, if any */
release_firmware(ucode_raw);
if (iwl_request_firmware(drv, false))
goto out_unbind;
return;
err_pci_alloc:
IWL_ERR(drv, "failed to allocate pci memory\n");
iwl_dealloc_ucode(drv);
release_firmware(ucode_raw);
out_unbind:
complete(&drv->request_firmware_complete);
device_release_driver(trans(drv)->dev);
}
int iwl_drv_start(struct iwl_shared *shrd,
struct iwl_trans *trans, const struct iwl_cfg *cfg)
{
struct iwl_drv *drv;
int ret;
shrd->cfg = cfg;
drv = kzalloc(sizeof(*drv), GFP_KERNEL);
if (!drv) {
dev_printk(KERN_ERR, trans->dev, "Couldn't allocate iwl_drv");
return -ENOMEM;
}
drv->shrd = shrd;
shrd->drv = drv;
init_completion(&drv->request_firmware_complete);
ret = iwl_request_firmware(drv, true);
if (ret) {
dev_printk(KERN_ERR, trans->dev, "Couldn't request the fw");
kfree(drv);
shrd->drv = NULL;
}
return ret;
}
void iwl_drv_stop(struct iwl_shared *shrd)
{
struct iwl_drv *drv = shrd->drv;
wait_for_completion(&drv->request_firmware_complete);
/* op_mode can be NULL if its start failed */
if (drv->op_mode)
iwl_op_mode_stop(drv->op_mode);
iwl_dealloc_ucode(drv);
kfree(drv);
shrd->drv = NULL;
}
| gpl-2.0 |
Sparkey67/android_kernel_lge_g3-1 | drivers/rtc/rtc-puv3.c | 5074 | 7942 | /*
* RTC driver code specific to PKUnity SoC and UniCore ISA
*
* Maintained by GUAN Xue-tao <gxt@mprc.pku.edu.cn>
* Copyright (C) 2001-2010 Guan Xuetao
*
* 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/fs.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/rtc.h>
#include <linux/bcd.h>
#include <linux/clk.h>
#include <linux/log2.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <asm/irq.h>
#include <mach/hardware.h>
static struct resource *puv3_rtc_mem;
static int puv3_rtc_alarmno = IRQ_RTCAlarm;
static int puv3_rtc_tickno = IRQ_RTC;
static DEFINE_SPINLOCK(puv3_rtc_pie_lock);
/* IRQ Handlers */
static irqreturn_t puv3_rtc_alarmirq(int irq, void *id)
{
struct rtc_device *rdev = id;
writel(readl(RTC_RTSR) | RTC_RTSR_AL, RTC_RTSR);
rtc_update_irq(rdev, 1, RTC_AF | RTC_IRQF);
return IRQ_HANDLED;
}
static irqreturn_t puv3_rtc_tickirq(int irq, void *id)
{
struct rtc_device *rdev = id;
writel(readl(RTC_RTSR) | RTC_RTSR_HZ, RTC_RTSR);
rtc_update_irq(rdev, 1, RTC_PF | RTC_IRQF);
return IRQ_HANDLED;
}
/* Update control registers */
static void puv3_rtc_setaie(int to)
{
unsigned int tmp;
pr_debug("%s: aie=%d\n", __func__, to);
tmp = readl(RTC_RTSR) & ~RTC_RTSR_ALE;
if (to)
tmp |= RTC_RTSR_ALE;
writel(tmp, RTC_RTSR);
}
static int puv3_rtc_setpie(struct device *dev, int enabled)
{
unsigned int tmp;
pr_debug("%s: pie=%d\n", __func__, enabled);
spin_lock_irq(&puv3_rtc_pie_lock);
tmp = readl(RTC_RTSR) & ~RTC_RTSR_HZE;
if (enabled)
tmp |= RTC_RTSR_HZE;
writel(tmp, RTC_RTSR);
spin_unlock_irq(&puv3_rtc_pie_lock);
return 0;
}
/* Time read/write */
static int puv3_rtc_gettime(struct device *dev, struct rtc_time *rtc_tm)
{
rtc_time_to_tm(readl(RTC_RCNR), rtc_tm);
pr_debug("read time %02x.%02x.%02x %02x/%02x/%02x\n",
rtc_tm->tm_year, rtc_tm->tm_mon, rtc_tm->tm_mday,
rtc_tm->tm_hour, rtc_tm->tm_min, rtc_tm->tm_sec);
return 0;
}
static int puv3_rtc_settime(struct device *dev, struct rtc_time *tm)
{
unsigned long rtc_count = 0;
pr_debug("set time %02d.%02d.%02d %02d/%02d/%02d\n",
tm->tm_year, tm->tm_mon, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
rtc_tm_to_time(tm, &rtc_count);
writel(rtc_count, RTC_RCNR);
return 0;
}
static int puv3_rtc_getalarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct rtc_time *alm_tm = &alrm->time;
rtc_time_to_tm(readl(RTC_RTAR), alm_tm);
alrm->enabled = readl(RTC_RTSR) & RTC_RTSR_ALE;
pr_debug("read alarm %02x %02x.%02x.%02x %02x/%02x/%02x\n",
alrm->enabled,
alm_tm->tm_year, alm_tm->tm_mon, alm_tm->tm_mday,
alm_tm->tm_hour, alm_tm->tm_min, alm_tm->tm_sec);
return 0;
}
static int puv3_rtc_setalarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct rtc_time *tm = &alrm->time;
unsigned long rtcalarm_count = 0;
pr_debug("puv3_rtc_setalarm: %d, %02x/%02x/%02x %02x.%02x.%02x\n",
alrm->enabled,
tm->tm_mday & 0xff, tm->tm_mon & 0xff, tm->tm_year & 0xff,
tm->tm_hour & 0xff, tm->tm_min & 0xff, tm->tm_sec);
rtc_tm_to_time(tm, &rtcalarm_count);
writel(rtcalarm_count, RTC_RTAR);
puv3_rtc_setaie(alrm->enabled);
if (alrm->enabled)
enable_irq_wake(puv3_rtc_alarmno);
else
disable_irq_wake(puv3_rtc_alarmno);
return 0;
}
static int puv3_rtc_proc(struct device *dev, struct seq_file *seq)
{
seq_printf(seq, "periodic_IRQ\t: %s\n",
(readl(RTC_RTSR) & RTC_RTSR_HZE) ? "yes" : "no");
return 0;
}
static int puv3_rtc_open(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_device *rtc_dev = platform_get_drvdata(pdev);
int ret;
ret = request_irq(puv3_rtc_alarmno, puv3_rtc_alarmirq,
0, "pkunity-rtc alarm", rtc_dev);
if (ret) {
dev_err(dev, "IRQ%d error %d\n", puv3_rtc_alarmno, ret);
return ret;
}
ret = request_irq(puv3_rtc_tickno, puv3_rtc_tickirq,
0, "pkunity-rtc tick", rtc_dev);
if (ret) {
dev_err(dev, "IRQ%d error %d\n", puv3_rtc_tickno, ret);
goto tick_err;
}
return ret;
tick_err:
free_irq(puv3_rtc_alarmno, rtc_dev);
return ret;
}
static void puv3_rtc_release(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_device *rtc_dev = platform_get_drvdata(pdev);
/* do not clear AIE here, it may be needed for wake */
puv3_rtc_setpie(dev, 0);
free_irq(puv3_rtc_alarmno, rtc_dev);
free_irq(puv3_rtc_tickno, rtc_dev);
}
static const struct rtc_class_ops puv3_rtcops = {
.open = puv3_rtc_open,
.release = puv3_rtc_release,
.read_time = puv3_rtc_gettime,
.set_time = puv3_rtc_settime,
.read_alarm = puv3_rtc_getalarm,
.set_alarm = puv3_rtc_setalarm,
.proc = puv3_rtc_proc,
};
static void puv3_rtc_enable(struct platform_device *pdev, int en)
{
if (!en) {
writel(readl(RTC_RTSR) & ~RTC_RTSR_HZE, RTC_RTSR);
} else {
/* re-enable the device, and check it is ok */
if ((readl(RTC_RTSR) & RTC_RTSR_HZE) == 0) {
dev_info(&pdev->dev, "rtc disabled, re-enabling\n");
writel(readl(RTC_RTSR) | RTC_RTSR_HZE, RTC_RTSR);
}
}
}
static int __devexit puv3_rtc_remove(struct platform_device *dev)
{
struct rtc_device *rtc = platform_get_drvdata(dev);
platform_set_drvdata(dev, NULL);
rtc_device_unregister(rtc);
puv3_rtc_setpie(&dev->dev, 0);
puv3_rtc_setaie(0);
release_resource(puv3_rtc_mem);
kfree(puv3_rtc_mem);
return 0;
}
static int __devinit puv3_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtc;
struct resource *res;
int ret;
pr_debug("%s: probe=%p\n", __func__, pdev);
/* find the IRQs */
puv3_rtc_tickno = platform_get_irq(pdev, 1);
if (puv3_rtc_tickno < 0) {
dev_err(&pdev->dev, "no irq for rtc tick\n");
return -ENOENT;
}
puv3_rtc_alarmno = platform_get_irq(pdev, 0);
if (puv3_rtc_alarmno < 0) {
dev_err(&pdev->dev, "no irq for alarm\n");
return -ENOENT;
}
pr_debug("PKUnity_rtc: tick irq %d, alarm irq %d\n",
puv3_rtc_tickno, puv3_rtc_alarmno);
/* get the memory region */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "failed to get memory region resource\n");
return -ENOENT;
}
puv3_rtc_mem = request_mem_region(res->start, resource_size(res),
pdev->name);
if (puv3_rtc_mem == NULL) {
dev_err(&pdev->dev, "failed to reserve memory region\n");
ret = -ENOENT;
goto err_nores;
}
puv3_rtc_enable(pdev, 1);
/* register RTC and exit */
rtc = rtc_device_register("pkunity", &pdev->dev, &puv3_rtcops,
THIS_MODULE);
if (IS_ERR(rtc)) {
dev_err(&pdev->dev, "cannot attach rtc\n");
ret = PTR_ERR(rtc);
goto err_nortc;
}
/* platform setup code should have handled this; sigh */
if (!device_can_wakeup(&pdev->dev))
device_init_wakeup(&pdev->dev, 1);
platform_set_drvdata(pdev, rtc);
return 0;
err_nortc:
puv3_rtc_enable(pdev, 0);
release_resource(puv3_rtc_mem);
err_nores:
return ret;
}
#ifdef CONFIG_PM
static int ticnt_save;
static int puv3_rtc_suspend(struct platform_device *pdev, pm_message_t state)
{
/* save RTAR for anyone using periodic interrupts */
ticnt_save = readl(RTC_RTAR);
puv3_rtc_enable(pdev, 0);
return 0;
}
static int puv3_rtc_resume(struct platform_device *pdev)
{
puv3_rtc_enable(pdev, 1);
writel(ticnt_save, RTC_RTAR);
return 0;
}
#else
#define puv3_rtc_suspend NULL
#define puv3_rtc_resume NULL
#endif
static struct platform_driver puv3_rtc_driver = {
.probe = puv3_rtc_probe,
.remove = __devexit_p(puv3_rtc_remove),
.suspend = puv3_rtc_suspend,
.resume = puv3_rtc_resume,
.driver = {
.name = "PKUnity-v3-RTC",
.owner = THIS_MODULE,
}
};
module_platform_driver(puv3_rtc_driver);
MODULE_DESCRIPTION("RTC Driver for the PKUnity v3 chip");
MODULE_AUTHOR("Hu Dongliang");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
dsb9938/DNA_JB_KERNEL_2 | sound/soc/nuc900/nuc900-ac97.c | 5074 | 10060 | /*
* Copyright (c) 2009-2010 Nuvoton technology corporation.
*
* Wan ZongShun <mcuos.com@gmail.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;version 2 of the License.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/suspend.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <linux/clk.h>
#include <mach/mfp.h>
#include "nuc900-audio.h"
static DEFINE_MUTEX(ac97_mutex);
struct nuc900_audio *nuc900_ac97_data;
static int nuc900_checkready(void)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
if (!(AUDIO_READ(nuc900_audio->mmio + ACTL_ACIS0) & CODEC_READY))
return -EPERM;
return 0;
}
/* AC97 controller reads codec register */
static unsigned short nuc900_ac97_read(struct snd_ac97 *ac97,
unsigned short reg)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long timeout = 0x10000, val;
mutex_lock(&ac97_mutex);
val = nuc900_checkready();
if (val) {
dev_err(nuc900_audio->dev, "AC97 codec is not ready\n");
goto out;
}
/* set the R_WB bit and write register index */
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS1, R_WB | reg);
/* set the valid frame bit and valid slots */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
val |= (VALID_FRAME | SLOT1_VALID);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, val);
udelay(100);
/* polling the AC_R_FINISH */
while (!(AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON) & AC_R_FINISH)
&& timeout--)
mdelay(1);
if (!timeout) {
dev_err(nuc900_audio->dev, "AC97 read register time out !\n");
val = -EPERM;
goto out;
}
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0) ;
val &= ~SLOT1_VALID;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, val);
if (AUDIO_READ(nuc900_audio->mmio + ACTL_ACIS1) >> 2 != reg) {
dev_err(nuc900_audio->dev,
"R_INDEX of REG_ACTL_ACIS1 not match!\n");
}
udelay(100);
val = (AUDIO_READ(nuc900_audio->mmio + ACTL_ACIS2) & 0xFFFF);
out:
mutex_unlock(&ac97_mutex);
return val;
}
/* AC97 controller writes to codec register */
static void nuc900_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long tmp, timeout = 0x10000;
mutex_lock(&ac97_mutex);
tmp = nuc900_checkready();
if (tmp)
dev_err(nuc900_audio->dev, "AC97 codec is not ready\n");
/* clear the R_WB bit and write register index */
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS1, reg);
/* write register value */
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS2, val);
/* set the valid frame bit and valid slots */
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
tmp |= SLOT1_VALID | SLOT2_VALID | VALID_FRAME;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, tmp);
udelay(100);
/* polling the AC_W_FINISH */
while ((AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON) & AC_W_FINISH)
&& timeout--)
mdelay(1);
if (!timeout)
dev_err(nuc900_audio->dev, "AC97 write register time out !\n");
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
tmp &= ~(SLOT1_VALID | SLOT2_VALID);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, tmp);
mutex_unlock(&ac97_mutex);
}
static void nuc900_ac97_warm_reset(struct snd_ac97 *ac97)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long val;
mutex_lock(&ac97_mutex);
/* warm reset AC 97 */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON);
val |= AC_W_RES;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACCON, val);
udelay(100);
val = nuc900_checkready();
if (val)
dev_err(nuc900_audio->dev, "AC97 codec is not ready\n");
mutex_unlock(&ac97_mutex);
}
static void nuc900_ac97_cold_reset(struct snd_ac97 *ac97)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long val;
mutex_lock(&ac97_mutex);
/* reset Audio Controller */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
val |= ACTL_RESET_BIT;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
val &= (~ACTL_RESET_BIT);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
/* reset AC-link interface */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
val |= AC_RESET;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
val &= ~AC_RESET;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
/* cold reset AC 97 */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON);
val |= AC_C_RES;
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACCON, val);
val = AUDIO_READ(nuc900_audio->mmio + ACTL_ACCON);
val &= (~AC_C_RES);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACCON, val);
udelay(100);
mutex_unlock(&ac97_mutex);
}
/* AC97 controller operations */
struct snd_ac97_bus_ops soc_ac97_ops = {
.read = nuc900_ac97_read,
.write = nuc900_ac97_write,
.reset = nuc900_ac97_cold_reset,
.warm_reset = nuc900_ac97_warm_reset,
}
EXPORT_SYMBOL_GPL(soc_ac97_ops);
static int nuc900_ac97_trigger(struct snd_pcm_substream *substream,
int cmd, struct snd_soc_dai *dai)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
int ret;
unsigned long val, tmp;
ret = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
tmp |= (SLOT3_VALID | SLOT4_VALID | VALID_FRAME);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, tmp);
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_PSR);
tmp |= (P_DMA_END_IRQ | P_DMA_MIDDLE_IRQ);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_PSR, tmp);
val |= AC_PLAY;
} else {
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_RSR);
tmp |= (R_DMA_END_IRQ | R_DMA_MIDDLE_IRQ);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RSR, tmp);
val |= AC_RECORD;
}
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
val = AUDIO_READ(nuc900_audio->mmio + ACTL_RESET);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
tmp = AUDIO_READ(nuc900_audio->mmio + ACTL_ACOS0);
tmp &= ~(SLOT3_VALID | SLOT4_VALID);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_ACOS0, tmp);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_PSR, RESET_PRSR);
val &= ~AC_PLAY;
} else {
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RSR, RESET_PRSR);
val &= ~AC_RECORD;
}
AUDIO_WRITE(nuc900_audio->mmio + ACTL_RESET, val);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int nuc900_ac97_probe(struct snd_soc_dai *dai)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
unsigned long val;
mutex_lock(&ac97_mutex);
/* enable unit clock */
clk_enable(nuc900_audio->clk);
/* enable audio controller and AC-link interface */
val = AUDIO_READ(nuc900_audio->mmio + ACTL_CON);
val |= (IIS_AC_PIN_SEL | ACLINK_EN);
AUDIO_WRITE(nuc900_audio->mmio + ACTL_CON, val);
mutex_unlock(&ac97_mutex);
return 0;
}
static int nuc900_ac97_remove(struct snd_soc_dai *dai)
{
struct nuc900_audio *nuc900_audio = nuc900_ac97_data;
clk_disable(nuc900_audio->clk);
return 0;
}
static const struct snd_soc_dai_ops nuc900_ac97_dai_ops = {
.trigger = nuc900_ac97_trigger,
};
static struct snd_soc_dai_driver nuc900_ac97_dai = {
.probe = nuc900_ac97_probe,
.remove = nuc900_ac97_remove,
.ac97_control = 1,
.playback = {
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
},
.capture = {
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
},
.ops = &nuc900_ac97_dai_ops,
};
static int __devinit nuc900_ac97_drvprobe(struct platform_device *pdev)
{
struct nuc900_audio *nuc900_audio;
int ret;
if (nuc900_ac97_data)
return -EBUSY;
nuc900_audio = kzalloc(sizeof(struct nuc900_audio), GFP_KERNEL);
if (!nuc900_audio)
return -ENOMEM;
spin_lock_init(&nuc900_audio->lock);
nuc900_audio->res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!nuc900_audio->res) {
ret = -ENODEV;
goto out0;
}
if (!request_mem_region(nuc900_audio->res->start,
resource_size(nuc900_audio->res), pdev->name)) {
ret = -EBUSY;
goto out0;
}
nuc900_audio->mmio = ioremap(nuc900_audio->res->start,
resource_size(nuc900_audio->res));
if (!nuc900_audio->mmio) {
ret = -ENOMEM;
goto out1;
}
nuc900_audio->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(nuc900_audio->clk)) {
ret = PTR_ERR(nuc900_audio->clk);
goto out2;
}
nuc900_audio->irq_num = platform_get_irq(pdev, 0);
if (!nuc900_audio->irq_num) {
ret = -EBUSY;
goto out3;
}
nuc900_ac97_data = nuc900_audio;
ret = snd_soc_register_dai(&pdev->dev, &nuc900_ac97_dai);
if (ret)
goto out3;
/* enbale ac97 multifunction pin */
mfp_set_groupg(nuc900_audio->dev, NULL);
return 0;
out3:
clk_put(nuc900_audio->clk);
out2:
iounmap(nuc900_audio->mmio);
out1:
release_mem_region(nuc900_audio->res->start,
resource_size(nuc900_audio->res));
out0:
kfree(nuc900_audio);
return ret;
}
static int __devexit nuc900_ac97_drvremove(struct platform_device *pdev)
{
snd_soc_unregister_dai(&pdev->dev);
clk_put(nuc900_ac97_data->clk);
iounmap(nuc900_ac97_data->mmio);
release_mem_region(nuc900_ac97_data->res->start,
resource_size(nuc900_ac97_data->res));
kfree(nuc900_ac97_data);
nuc900_ac97_data = NULL;
return 0;
}
static struct platform_driver nuc900_ac97_driver = {
.driver = {
.name = "nuc900-ac97",
.owner = THIS_MODULE,
},
.probe = nuc900_ac97_drvprobe,
.remove = __devexit_p(nuc900_ac97_drvremove),
};
module_platform_driver(nuc900_ac97_driver);
MODULE_AUTHOR("Wan ZongShun <mcuos.com@gmail.com>");
MODULE_DESCRIPTION("NUC900 AC97 SoC driver!");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:nuc900-ac97");
| gpl-2.0 |
edgestorm/lu3700-cm-gin | drivers/watchdog/w83877f_wdt.c | 5074 | 10364 | /*
* W83877F Computer Watchdog Timer driver
*
* Based on acquirewdt.c by Alan Cox,
* and sbc60xxwdt.c by Jakob Oestergaard <jakob@unthought.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.
*
* The authors do NOT admit liability nor provide warranty for
* any of this software. This material is provided "AS-IS" in
* the hope that it may be useful for others.
*
* (c) Copyright 2001 Scott Jennings <linuxdrivers@oro.net>
*
* 4/19 - 2001 [Initial revision]
* 9/27 - 2001 Added spinlocking
* 4/12 - 2002 [rob@osinvestor.com] Eliminate extra comments
* Eliminate fop_read
* Eliminate extra spin_unlock
* Added KERN_* tags to printks
* add CONFIG_WATCHDOG_NOWAYOUT support
* fix possible wdt_is_open race
* changed watchdog_info to correctly reflect what
* the driver offers
* added WDIOC_GETSTATUS, WDIOC_GETBOOTSTATUS,
* WDIOC_SETTIMEOUT,
* WDIOC_GETTIMEOUT, and WDIOC_SETOPTIONS ioctls
* 09/8 - 2003 [wim@iguana.be] cleanup of trailing spaces
* added extra printk's for startup problems
* use module_param
* made timeout (the emulated heartbeat) a
* module_param
* made the keepalive ping an internal subroutine
*
* This WDT driver is different from most other Linux WDT
* drivers in that the driver will ping the watchdog by itself,
* because this particular WDT has a very short timeout (1.6
* seconds) and it would be insane to count on any userspace
* daemon always getting scheduled within that time frame.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <asm/system.h>
#define OUR_NAME "w83877f_wdt"
#define PFX OUR_NAME ": "
#define ENABLE_W83877F_PORT 0x3F0
#define ENABLE_W83877F 0x87
#define DISABLE_W83877F 0xAA
#define WDT_PING 0x443
#define WDT_REGISTER 0x14
#define WDT_ENABLE 0x9C
#define WDT_DISABLE 0x8C
/*
* The W83877F seems to be fixed at 1.6s timeout (at least on the
* EMACS PC-104 board I'm using). If we reset the watchdog every
* ~250ms we should be safe. */
#define WDT_INTERVAL (HZ/4+1)
/*
* We must not require too good response from the userspace daemon.
* Here we require the userspace daemon to send us a heartbeat
* char to /dev/watchdog every 30 seconds.
*/
#define WATCHDOG_TIMEOUT 30 /* 30 sec default timeout */
/* in seconds, will be multiplied by HZ to get seconds to wait for a ping */
static int timeout = WATCHDOG_TIMEOUT;
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout,
"Watchdog timeout in seconds. (1<=timeout<=3600, default="
__MODULE_STRING(WATCHDOG_TIMEOUT) ")");
static int nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, int, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static void wdt_timer_ping(unsigned long);
static DEFINE_TIMER(timer, wdt_timer_ping, 0, 0);
static unsigned long next_heartbeat;
static unsigned long wdt_is_open;
static char wdt_expect_close;
static DEFINE_SPINLOCK(wdt_spinlock);
/*
* Whack the dog
*/
static void wdt_timer_ping(unsigned long data)
{
/* If we got a heartbeat pulse within the WDT_US_INTERVAL
* we agree to ping the WDT
*/
if (time_before(jiffies, next_heartbeat)) {
/* Ping the WDT */
spin_lock(&wdt_spinlock);
/* Ping the WDT by reading from WDT_PING */
inb_p(WDT_PING);
/* Re-set the timer interval */
mod_timer(&timer, jiffies + WDT_INTERVAL);
spin_unlock(&wdt_spinlock);
} else
printk(KERN_WARNING PFX
"Heartbeat lost! Will not ping the watchdog\n");
}
/*
* Utility routines
*/
static void wdt_change(int writeval)
{
unsigned long flags;
spin_lock_irqsave(&wdt_spinlock, flags);
/* buy some time */
inb_p(WDT_PING);
/* make W83877F available */
outb_p(ENABLE_W83877F, ENABLE_W83877F_PORT);
outb_p(ENABLE_W83877F, ENABLE_W83877F_PORT);
/* enable watchdog */
outb_p(WDT_REGISTER, ENABLE_W83877F_PORT);
outb_p(writeval, ENABLE_W83877F_PORT+1);
/* lock the W8387FF away */
outb_p(DISABLE_W83877F, ENABLE_W83877F_PORT);
spin_unlock_irqrestore(&wdt_spinlock, flags);
}
static void wdt_startup(void)
{
next_heartbeat = jiffies + (timeout * HZ);
/* Start the timer */
mod_timer(&timer, jiffies + WDT_INTERVAL);
wdt_change(WDT_ENABLE);
printk(KERN_INFO PFX "Watchdog timer is now enabled.\n");
}
static void wdt_turnoff(void)
{
/* Stop the timer */
del_timer(&timer);
wdt_change(WDT_DISABLE);
printk(KERN_INFO PFX "Watchdog timer is now disabled...\n");
}
static void wdt_keepalive(void)
{
/* user land ping */
next_heartbeat = jiffies + (timeout * HZ);
}
/*
* /dev/watchdog handling
*/
static ssize_t fop_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
/* See if we got the magic character 'V' and reload the timer */
if (count) {
if (!nowayout) {
size_t ofs;
/* note: just in case someone wrote the magic
character five months ago... */
wdt_expect_close = 0;
/* scan to see whether or not we got the
magic character */
for (ofs = 0; ofs != count; ofs++) {
char c;
if (get_user(c, buf + ofs))
return -EFAULT;
if (c == 'V')
wdt_expect_close = 42;
}
}
/* someone wrote to us, we should restart timer */
wdt_keepalive();
}
return count;
}
static int fop_open(struct inode *inode, struct file *file)
{
/* Just in case we're already talking to someone... */
if (test_and_set_bit(0, &wdt_is_open))
return -EBUSY;
/* Good, fire up the show */
wdt_startup();
return nonseekable_open(inode, file);
}
static int fop_close(struct inode *inode, struct file *file)
{
if (wdt_expect_close == 42)
wdt_turnoff();
else {
del_timer(&timer);
printk(KERN_CRIT PFX
"device file closed unexpectedly. Will not stop the WDT!\n");
}
clear_bit(0, &wdt_is_open);
wdt_expect_close = 0;
return 0;
}
static long fop_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *)arg;
int __user *p = argp;
static const struct watchdog_info ident = {
.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT
| WDIOF_MAGICCLOSE,
.firmware_version = 1,
.identity = "W83877F",
};
switch (cmd) {
case WDIOC_GETSUPPORT:
return copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_SETOPTIONS:
{
int new_options, retval = -EINVAL;
if (get_user(new_options, p))
return -EFAULT;
if (new_options & WDIOS_DISABLECARD) {
wdt_turnoff();
retval = 0;
}
if (new_options & WDIOS_ENABLECARD) {
wdt_startup();
retval = 0;
}
return retval;
}
case WDIOC_KEEPALIVE:
wdt_keepalive();
return 0;
case WDIOC_SETTIMEOUT:
{
int new_timeout;
if (get_user(new_timeout, p))
return -EFAULT;
/* arbitrary upper limit */
if (new_timeout < 1 || new_timeout > 3600)
return -EINVAL;
timeout = new_timeout;
wdt_keepalive();
/* Fall through */
}
case WDIOC_GETTIMEOUT:
return put_user(timeout, p);
default:
return -ENOTTY;
}
}
static const struct file_operations wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = fop_write,
.open = fop_open,
.release = fop_close,
.unlocked_ioctl = fop_ioctl,
};
static struct miscdevice wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &wdt_fops,
};
/*
* Notifier for system down
*/
static int wdt_notify_sys(struct notifier_block *this, unsigned long code,
void *unused)
{
if (code == SYS_DOWN || code == SYS_HALT)
wdt_turnoff();
return NOTIFY_DONE;
}
/*
* The WDT needs to learn about soft shutdowns in order to
* turn the timebomb registers off.
*/
static struct notifier_block wdt_notifier = {
.notifier_call = wdt_notify_sys,
};
static void __exit w83877f_wdt_unload(void)
{
wdt_turnoff();
/* Deregister */
misc_deregister(&wdt_miscdev);
unregister_reboot_notifier(&wdt_notifier);
release_region(WDT_PING, 1);
release_region(ENABLE_W83877F_PORT, 2);
}
static int __init w83877f_wdt_init(void)
{
int rc = -EBUSY;
if (timeout < 1 || timeout > 3600) { /* arbitrary upper limit */
timeout = WATCHDOG_TIMEOUT;
printk(KERN_INFO PFX
"timeout value must be 1 <= x <= 3600, using %d\n",
timeout);
}
if (!request_region(ENABLE_W83877F_PORT, 2, "W83877F WDT")) {
printk(KERN_ERR PFX "I/O address 0x%04x already in use\n",
ENABLE_W83877F_PORT);
rc = -EIO;
goto err_out;
}
if (!request_region(WDT_PING, 1, "W8387FF WDT")) {
printk(KERN_ERR PFX "I/O address 0x%04x already in use\n",
WDT_PING);
rc = -EIO;
goto err_out_region1;
}
rc = register_reboot_notifier(&wdt_notifier);
if (rc) {
printk(KERN_ERR PFX
"cannot register reboot notifier (err=%d)\n", rc);
goto err_out_region2;
}
rc = misc_register(&wdt_miscdev);
if (rc) {
printk(KERN_ERR PFX
"cannot register miscdev on minor=%d (err=%d)\n",
wdt_miscdev.minor, rc);
goto err_out_reboot;
}
printk(KERN_INFO PFX
"WDT driver for W83877F initialised. timeout=%d sec (nowayout=%d)\n",
timeout, nowayout);
return 0;
err_out_reboot:
unregister_reboot_notifier(&wdt_notifier);
err_out_region2:
release_region(WDT_PING, 1);
err_out_region1:
release_region(ENABLE_W83877F_PORT, 2);
err_out:
return rc;
}
module_init(w83877f_wdt_init);
module_exit(w83877f_wdt_unload);
MODULE_AUTHOR("Scott and Bill Jennings");
MODULE_DESCRIPTION("Driver for watchdog timer in w83877f chip");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
| gpl-2.0 |
TeamSXL/htc-cm-kernel-doubleshot-34_old | drivers/ssb/embedded.c | 5330 | 5392 | /*
* Sonics Silicon Backplane
* Embedded systems support code
*
* Copyright 2005-2008, Broadcom Corporation
* Copyright 2006-2008, Michael Buesch <m@bues.ch>
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include <linux/export.h>
#include <linux/ssb/ssb.h>
#include <linux/ssb/ssb_embedded.h>
#include <linux/ssb/ssb_driver_pci.h>
#include <linux/ssb/ssb_driver_gige.h>
#include <linux/pci.h>
#include "ssb_private.h"
int ssb_watchdog_timer_set(struct ssb_bus *bus, u32 ticks)
{
if (ssb_chipco_available(&bus->chipco)) {
ssb_chipco_watchdog_timer_set(&bus->chipco, ticks);
return 0;
}
if (ssb_extif_available(&bus->extif)) {
ssb_extif_watchdog_timer_set(&bus->extif, ticks);
return 0;
}
return -ENODEV;
}
EXPORT_SYMBOL(ssb_watchdog_timer_set);
u32 ssb_gpio_in(struct ssb_bus *bus, u32 mask)
{
unsigned long flags;
u32 res = 0;
spin_lock_irqsave(&bus->gpio_lock, flags);
if (ssb_chipco_available(&bus->chipco))
res = ssb_chipco_gpio_in(&bus->chipco, mask);
else if (ssb_extif_available(&bus->extif))
res = ssb_extif_gpio_in(&bus->extif, mask);
else
SSB_WARN_ON(1);
spin_unlock_irqrestore(&bus->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL(ssb_gpio_in);
u32 ssb_gpio_out(struct ssb_bus *bus, u32 mask, u32 value)
{
unsigned long flags;
u32 res = 0;
spin_lock_irqsave(&bus->gpio_lock, flags);
if (ssb_chipco_available(&bus->chipco))
res = ssb_chipco_gpio_out(&bus->chipco, mask, value);
else if (ssb_extif_available(&bus->extif))
res = ssb_extif_gpio_out(&bus->extif, mask, value);
else
SSB_WARN_ON(1);
spin_unlock_irqrestore(&bus->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL(ssb_gpio_out);
u32 ssb_gpio_outen(struct ssb_bus *bus, u32 mask, u32 value)
{
unsigned long flags;
u32 res = 0;
spin_lock_irqsave(&bus->gpio_lock, flags);
if (ssb_chipco_available(&bus->chipco))
res = ssb_chipco_gpio_outen(&bus->chipco, mask, value);
else if (ssb_extif_available(&bus->extif))
res = ssb_extif_gpio_outen(&bus->extif, mask, value);
else
SSB_WARN_ON(1);
spin_unlock_irqrestore(&bus->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL(ssb_gpio_outen);
u32 ssb_gpio_control(struct ssb_bus *bus, u32 mask, u32 value)
{
unsigned long flags;
u32 res = 0;
spin_lock_irqsave(&bus->gpio_lock, flags);
if (ssb_chipco_available(&bus->chipco))
res = ssb_chipco_gpio_control(&bus->chipco, mask, value);
spin_unlock_irqrestore(&bus->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL(ssb_gpio_control);
u32 ssb_gpio_intmask(struct ssb_bus *bus, u32 mask, u32 value)
{
unsigned long flags;
u32 res = 0;
spin_lock_irqsave(&bus->gpio_lock, flags);
if (ssb_chipco_available(&bus->chipco))
res = ssb_chipco_gpio_intmask(&bus->chipco, mask, value);
else if (ssb_extif_available(&bus->extif))
res = ssb_extif_gpio_intmask(&bus->extif, mask, value);
else
SSB_WARN_ON(1);
spin_unlock_irqrestore(&bus->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL(ssb_gpio_intmask);
u32 ssb_gpio_polarity(struct ssb_bus *bus, u32 mask, u32 value)
{
unsigned long flags;
u32 res = 0;
spin_lock_irqsave(&bus->gpio_lock, flags);
if (ssb_chipco_available(&bus->chipco))
res = ssb_chipco_gpio_polarity(&bus->chipco, mask, value);
else if (ssb_extif_available(&bus->extif))
res = ssb_extif_gpio_polarity(&bus->extif, mask, value);
else
SSB_WARN_ON(1);
spin_unlock_irqrestore(&bus->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL(ssb_gpio_polarity);
#ifdef CONFIG_SSB_DRIVER_GIGE
static int gige_pci_init_callback(struct ssb_bus *bus, unsigned long data)
{
struct pci_dev *pdev = (struct pci_dev *)data;
struct ssb_device *dev;
unsigned int i;
int res;
for (i = 0; i < bus->nr_devices; i++) {
dev = &(bus->devices[i]);
if (dev->id.coreid != SSB_DEV_ETHERNET_GBIT)
continue;
if (!dev->dev ||
!dev->dev->driver ||
!device_is_registered(dev->dev))
continue;
res = ssb_gige_pcibios_plat_dev_init(dev, pdev);
if (res >= 0)
return res;
}
return -ENODEV;
}
#endif /* CONFIG_SSB_DRIVER_GIGE */
int ssb_pcibios_plat_dev_init(struct pci_dev *dev)
{
int err;
err = ssb_pcicore_plat_dev_init(dev);
if (!err)
return 0;
#ifdef CONFIG_SSB_DRIVER_GIGE
err = ssb_for_each_bus_call((unsigned long)dev, gige_pci_init_callback);
if (err >= 0)
return err;
#endif
/* This is not a PCI device on any SSB device. */
return -ENODEV;
}
#ifdef CONFIG_SSB_DRIVER_GIGE
static int gige_map_irq_callback(struct ssb_bus *bus, unsigned long data)
{
const struct pci_dev *pdev = (const struct pci_dev *)data;
struct ssb_device *dev;
unsigned int i;
int res;
for (i = 0; i < bus->nr_devices; i++) {
dev = &(bus->devices[i]);
if (dev->id.coreid != SSB_DEV_ETHERNET_GBIT)
continue;
if (!dev->dev ||
!dev->dev->driver ||
!device_is_registered(dev->dev))
continue;
res = ssb_gige_map_irq(dev, pdev);
if (res >= 0)
return res;
}
return -ENODEV;
}
#endif /* CONFIG_SSB_DRIVER_GIGE */
int ssb_pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
int res;
/* Check if this PCI device is a device on a SSB bus or device
* and return the IRQ number for it. */
res = ssb_pcicore_pcibios_map_irq(dev, slot, pin);
if (res >= 0)
return res;
#ifdef CONFIG_SSB_DRIVER_GIGE
res = ssb_for_each_bus_call((unsigned long)dev, gige_map_irq_callback);
if (res >= 0)
return res;
#endif
/* This is not a PCI device on any SSB device. */
return -ENODEV;
}
| gpl-2.0 |
Kiffmet/FireWork-Kernel-GT-i9506 | drivers/mfd/tps65912-i2c.c | 7890 | 3182 | /*
* tps65912-i2c.c -- I2C access for TI TPS65912x PMIC
*
* Copyright 2011 Texas Instruments Inc.
*
* Author: Margarita Olaya Cabrera <magi@slimlogic.co.uk>
*
* 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 driver is based on wm8350 implementation.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/mfd/core.h>
#include <linux/mfd/tps65912.h>
static int tps65912_i2c_read(struct tps65912 *tps65912, u8 reg,
int bytes, void *dest)
{
struct i2c_client *i2c = tps65912->control_data;
struct i2c_msg xfer[2];
int ret;
/* Write register */
xfer[0].addr = i2c->addr;
xfer[0].flags = 0;
xfer[0].len = 1;
xfer[0].buf = ®
/* Read data */
xfer[1].addr = i2c->addr;
xfer[1].flags = I2C_M_RD;
xfer[1].len = bytes;
xfer[1].buf = dest;
ret = i2c_transfer(i2c->adapter, xfer, 2);
if (ret == 2)
ret = 0;
else if (ret >= 0)
ret = -EIO;
return ret;
}
static int tps65912_i2c_write(struct tps65912 *tps65912, u8 reg,
int bytes, void *src)
{
struct i2c_client *i2c = tps65912->control_data;
/* we add 1 byte for device register */
u8 msg[TPS6591X_MAX_REGISTER + 1];
int ret;
if (bytes > TPS6591X_MAX_REGISTER)
return -EINVAL;
msg[0] = reg;
memcpy(&msg[1], src, bytes);
ret = i2c_master_send(i2c, msg, bytes + 1);
if (ret < 0)
return ret;
if (ret != bytes + 1)
return -EIO;
return 0;
}
static int tps65912_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct tps65912 *tps65912;
tps65912 = kzalloc(sizeof(struct tps65912), GFP_KERNEL);
if (tps65912 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, tps65912);
tps65912->dev = &i2c->dev;
tps65912->control_data = i2c;
tps65912->read = tps65912_i2c_read;
tps65912->write = tps65912_i2c_write;
return tps65912_device_init(tps65912);
}
static int tps65912_i2c_remove(struct i2c_client *i2c)
{
struct tps65912 *tps65912 = i2c_get_clientdata(i2c);
tps65912_device_exit(tps65912);
return 0;
}
static const struct i2c_device_id tps65912_i2c_id[] = {
{"tps65912", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tps65912_i2c_id);
static struct i2c_driver tps65912_i2c_driver = {
.driver = {
.name = "tps65912",
.owner = THIS_MODULE,
},
.probe = tps65912_i2c_probe,
.remove = tps65912_i2c_remove,
.id_table = tps65912_i2c_id,
};
static int __init tps65912_i2c_init(void)
{
int ret;
ret = i2c_add_driver(&tps65912_i2c_driver);
if (ret != 0)
pr_err("Failed to register TPS65912 I2C driver: %d\n", ret);
return ret;
}
/* init early so consumer devices can complete system boot */
subsys_initcall(tps65912_i2c_init);
static void __exit tps65912_i2c_exit(void)
{
i2c_del_driver(&tps65912_i2c_driver);
}
module_exit(tps65912_i2c_exit);
MODULE_AUTHOR("Margarita Olaya <magi@slimlogic.co.uk>");
MODULE_DESCRIPTION("TPS6591x chip family multi-function driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
kgp700/exyroid-sgs2-jb | net/tipc/handler.c | 8146 | 4104 | /*
* net/tipc/handler.c: TIPC signal handling
*
* Copyright (c) 2000-2006, Ericsson AB
* Copyright (c) 2005, Wind River Systems
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* 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.
*/
#include "core.h"
struct queue_item {
struct list_head next_signal;
void (*handler) (unsigned long);
unsigned long data;
};
static struct kmem_cache *tipc_queue_item_cache;
static struct list_head signal_queue_head;
static DEFINE_SPINLOCK(qitem_lock);
static int handler_enabled;
static void process_signal_queue(unsigned long dummy);
static DECLARE_TASKLET_DISABLED(tipc_tasklet, process_signal_queue, 0);
unsigned int tipc_k_signal(Handler routine, unsigned long argument)
{
struct queue_item *item;
if (!handler_enabled) {
err("Signal request ignored by handler\n");
return -ENOPROTOOPT;
}
spin_lock_bh(&qitem_lock);
item = kmem_cache_alloc(tipc_queue_item_cache, GFP_ATOMIC);
if (!item) {
err("Signal queue out of memory\n");
spin_unlock_bh(&qitem_lock);
return -ENOMEM;
}
item->handler = routine;
item->data = argument;
list_add_tail(&item->next_signal, &signal_queue_head);
spin_unlock_bh(&qitem_lock);
tasklet_schedule(&tipc_tasklet);
return 0;
}
static void process_signal_queue(unsigned long dummy)
{
struct queue_item *__volatile__ item;
struct list_head *l, *n;
spin_lock_bh(&qitem_lock);
list_for_each_safe(l, n, &signal_queue_head) {
item = list_entry(l, struct queue_item, next_signal);
list_del(&item->next_signal);
spin_unlock_bh(&qitem_lock);
item->handler(item->data);
spin_lock_bh(&qitem_lock);
kmem_cache_free(tipc_queue_item_cache, item);
}
spin_unlock_bh(&qitem_lock);
}
int tipc_handler_start(void)
{
tipc_queue_item_cache =
kmem_cache_create("tipc_queue_items", sizeof(struct queue_item),
0, SLAB_HWCACHE_ALIGN, NULL);
if (!tipc_queue_item_cache)
return -ENOMEM;
INIT_LIST_HEAD(&signal_queue_head);
tasklet_enable(&tipc_tasklet);
handler_enabled = 1;
return 0;
}
void tipc_handler_stop(void)
{
struct list_head *l, *n;
struct queue_item *item;
if (!handler_enabled)
return;
handler_enabled = 0;
tasklet_disable(&tipc_tasklet);
tasklet_kill(&tipc_tasklet);
spin_lock_bh(&qitem_lock);
list_for_each_safe(l, n, &signal_queue_head) {
item = list_entry(l, struct queue_item, next_signal);
list_del(&item->next_signal);
kmem_cache_free(tipc_queue_item_cache, item);
}
spin_unlock_bh(&qitem_lock);
kmem_cache_destroy(tipc_queue_item_cache);
}
| gpl-2.0 |
mehrvarz/msm-kitkat-tm-usbhost-charge | drivers/ide/ide-atapi.c | 8914 | 18109 | /*
* ATAPI support.
*/
#include <linux/kernel.h>
#include <linux/cdrom.h>
#include <linux/delay.h>
#include <linux/export.h>
#include <linux/ide.h>
#include <linux/scatterlist.h>
#include <linux/gfp.h>
#include <scsi/scsi.h>
#define DRV_NAME "ide-atapi"
#define PFX DRV_NAME ": "
#ifdef DEBUG
#define debug_log(fmt, args...) \
printk(KERN_INFO "ide: " fmt, ## args)
#else
#define debug_log(fmt, args...) do {} while (0)
#endif
#define ATAPI_MIN_CDB_BYTES 12
static inline int dev_is_idecd(ide_drive_t *drive)
{
return drive->media == ide_cdrom || drive->media == ide_optical;
}
/*
* Check whether we can support a device,
* based on the ATAPI IDENTIFY command results.
*/
int ide_check_atapi_device(ide_drive_t *drive, const char *s)
{
u16 *id = drive->id;
u8 gcw[2], protocol, device_type, removable, drq_type, packet_size;
*((u16 *)&gcw) = id[ATA_ID_CONFIG];
protocol = (gcw[1] & 0xC0) >> 6;
device_type = gcw[1] & 0x1F;
removable = (gcw[0] & 0x80) >> 7;
drq_type = (gcw[0] & 0x60) >> 5;
packet_size = gcw[0] & 0x03;
#ifdef CONFIG_PPC
/* kludge for Apple PowerBook internal zip */
if (drive->media == ide_floppy && device_type == 5 &&
!strstr((char *)&id[ATA_ID_PROD], "CD-ROM") &&
strstr((char *)&id[ATA_ID_PROD], "ZIP"))
device_type = 0;
#endif
if (protocol != 2)
printk(KERN_ERR "%s: %s: protocol (0x%02x) is not ATAPI\n",
s, drive->name, protocol);
else if ((drive->media == ide_floppy && device_type != 0) ||
(drive->media == ide_tape && device_type != 1))
printk(KERN_ERR "%s: %s: invalid device type (0x%02x)\n",
s, drive->name, device_type);
else if (removable == 0)
printk(KERN_ERR "%s: %s: the removable flag is not set\n",
s, drive->name);
else if (drive->media == ide_floppy && drq_type == 3)
printk(KERN_ERR "%s: %s: sorry, DRQ type (0x%02x) not "
"supported\n", s, drive->name, drq_type);
else if (packet_size != 0)
printk(KERN_ERR "%s: %s: packet size (0x%02x) is not 12 "
"bytes\n", s, drive->name, packet_size);
else
return 1;
return 0;
}
EXPORT_SYMBOL_GPL(ide_check_atapi_device);
void ide_init_pc(struct ide_atapi_pc *pc)
{
memset(pc, 0, sizeof(*pc));
}
EXPORT_SYMBOL_GPL(ide_init_pc);
/*
* Add a special packet command request to the tail of the request queue,
* and wait for it to be serviced.
*/
int ide_queue_pc_tail(ide_drive_t *drive, struct gendisk *disk,
struct ide_atapi_pc *pc, void *buf, unsigned int bufflen)
{
struct request *rq;
int error;
rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_SPECIAL;
rq->special = (char *)pc;
if (buf && bufflen) {
error = blk_rq_map_kern(drive->queue, rq, buf, bufflen,
GFP_NOIO);
if (error)
goto put_req;
}
memcpy(rq->cmd, pc->c, 12);
if (drive->media == ide_tape)
rq->cmd[13] = REQ_IDETAPE_PC1;
error = blk_execute_rq(drive->queue, disk, rq, 0);
put_req:
blk_put_request(rq);
return error;
}
EXPORT_SYMBOL_GPL(ide_queue_pc_tail);
int ide_do_test_unit_ready(ide_drive_t *drive, struct gendisk *disk)
{
struct ide_atapi_pc pc;
ide_init_pc(&pc);
pc.c[0] = TEST_UNIT_READY;
return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
}
EXPORT_SYMBOL_GPL(ide_do_test_unit_ready);
int ide_do_start_stop(ide_drive_t *drive, struct gendisk *disk, int start)
{
struct ide_atapi_pc pc;
ide_init_pc(&pc);
pc.c[0] = START_STOP;
pc.c[4] = start;
if (drive->media == ide_tape)
pc.flags |= PC_FLAG_WAIT_FOR_DSC;
return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
}
EXPORT_SYMBOL_GPL(ide_do_start_stop);
int ide_set_media_lock(ide_drive_t *drive, struct gendisk *disk, int on)
{
struct ide_atapi_pc pc;
if ((drive->dev_flags & IDE_DFLAG_DOORLOCKING) == 0)
return 0;
ide_init_pc(&pc);
pc.c[0] = ALLOW_MEDIUM_REMOVAL;
pc.c[4] = on;
return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
}
EXPORT_SYMBOL_GPL(ide_set_media_lock);
void ide_create_request_sense_cmd(ide_drive_t *drive, struct ide_atapi_pc *pc)
{
ide_init_pc(pc);
pc->c[0] = REQUEST_SENSE;
if (drive->media == ide_floppy) {
pc->c[4] = 255;
pc->req_xfer = 18;
} else {
pc->c[4] = 20;
pc->req_xfer = 20;
}
}
EXPORT_SYMBOL_GPL(ide_create_request_sense_cmd);
void ide_prep_sense(ide_drive_t *drive, struct request *rq)
{
struct request_sense *sense = &drive->sense_data;
struct request *sense_rq = &drive->sense_rq;
unsigned int cmd_len, sense_len;
int err;
switch (drive->media) {
case ide_floppy:
cmd_len = 255;
sense_len = 18;
break;
case ide_tape:
cmd_len = 20;
sense_len = 20;
break;
default:
cmd_len = 18;
sense_len = 18;
}
BUG_ON(sense_len > sizeof(*sense));
if (rq->cmd_type == REQ_TYPE_SENSE || drive->sense_rq_armed)
return;
memset(sense, 0, sizeof(*sense));
blk_rq_init(rq->q, sense_rq);
err = blk_rq_map_kern(drive->queue, sense_rq, sense, sense_len,
GFP_NOIO);
if (unlikely(err)) {
if (printk_ratelimit())
printk(KERN_WARNING PFX "%s: failed to map sense "
"buffer\n", drive->name);
return;
}
sense_rq->rq_disk = rq->rq_disk;
sense_rq->cmd[0] = GPCMD_REQUEST_SENSE;
sense_rq->cmd[4] = cmd_len;
sense_rq->cmd_type = REQ_TYPE_SENSE;
sense_rq->cmd_flags |= REQ_PREEMPT;
if (drive->media == ide_tape)
sense_rq->cmd[13] = REQ_IDETAPE_PC1;
drive->sense_rq_armed = true;
}
EXPORT_SYMBOL_GPL(ide_prep_sense);
int ide_queue_sense_rq(ide_drive_t *drive, void *special)
{
/* deferred failure from ide_prep_sense() */
if (!drive->sense_rq_armed) {
printk(KERN_WARNING PFX "%s: error queuing a sense request\n",
drive->name);
return -ENOMEM;
}
drive->sense_rq.special = special;
drive->sense_rq_armed = false;
drive->hwif->rq = NULL;
elv_add_request(drive->queue, &drive->sense_rq, ELEVATOR_INSERT_FRONT);
return 0;
}
EXPORT_SYMBOL_GPL(ide_queue_sense_rq);
/*
* Called when an error was detected during the last packet command.
* We queue a request sense packet command at the head of the request
* queue.
*/
void ide_retry_pc(ide_drive_t *drive)
{
struct request *failed_rq = drive->hwif->rq;
struct request *sense_rq = &drive->sense_rq;
struct ide_atapi_pc *pc = &drive->request_sense_pc;
(void)ide_read_error(drive);
/* init pc from sense_rq */
ide_init_pc(pc);
memcpy(pc->c, sense_rq->cmd, 12);
if (drive->media == ide_tape)
drive->atapi_flags |= IDE_AFLAG_IGNORE_DSC;
/*
* Push back the failed request and put request sense on top
* of it. The failed command will be retried after sense data
* is acquired.
*/
drive->hwif->rq = NULL;
ide_requeue_and_plug(drive, failed_rq);
if (ide_queue_sense_rq(drive, pc)) {
blk_start_request(failed_rq);
ide_complete_rq(drive, -EIO, blk_rq_bytes(failed_rq));
}
}
EXPORT_SYMBOL_GPL(ide_retry_pc);
int ide_cd_expiry(ide_drive_t *drive)
{
struct request *rq = drive->hwif->rq;
unsigned long wait = 0;
debug_log("%s: rq->cmd[0]: 0x%x\n", __func__, rq->cmd[0]);
/*
* Some commands are *slow* and normally take a long time to complete.
* Usually we can use the ATAPI "disconnect" to bypass this, but not all
* commands/drives support that. Let ide_timer_expiry keep polling us
* for these.
*/
switch (rq->cmd[0]) {
case GPCMD_BLANK:
case GPCMD_FORMAT_UNIT:
case GPCMD_RESERVE_RZONE_TRACK:
case GPCMD_CLOSE_TRACK:
case GPCMD_FLUSH_CACHE:
wait = ATAPI_WAIT_PC;
break;
default:
if (!(rq->cmd_flags & REQ_QUIET))
printk(KERN_INFO PFX "cmd 0x%x timed out\n",
rq->cmd[0]);
wait = 0;
break;
}
return wait;
}
EXPORT_SYMBOL_GPL(ide_cd_expiry);
int ide_cd_get_xferlen(struct request *rq)
{
switch (rq->cmd_type) {
case REQ_TYPE_FS:
return 32768;
case REQ_TYPE_SENSE:
case REQ_TYPE_BLOCK_PC:
case REQ_TYPE_ATA_PC:
return blk_rq_bytes(rq);
default:
return 0;
}
}
EXPORT_SYMBOL_GPL(ide_cd_get_xferlen);
void ide_read_bcount_and_ireason(ide_drive_t *drive, u16 *bcount, u8 *ireason)
{
struct ide_taskfile tf;
drive->hwif->tp_ops->tf_read(drive, &tf, IDE_VALID_NSECT |
IDE_VALID_LBAM | IDE_VALID_LBAH);
*bcount = (tf.lbah << 8) | tf.lbam;
*ireason = tf.nsect & 3;
}
EXPORT_SYMBOL_GPL(ide_read_bcount_and_ireason);
/*
* Check the contents of the interrupt reason register and attempt to recover if
* there are problems.
*
* Returns:
* - 0 if everything's ok
* - 1 if the request has to be terminated.
*/
int ide_check_ireason(ide_drive_t *drive, struct request *rq, int len,
int ireason, int rw)
{
ide_hwif_t *hwif = drive->hwif;
debug_log("ireason: 0x%x, rw: 0x%x\n", ireason, rw);
if (ireason == (!rw << 1))
return 0;
else if (ireason == (rw << 1)) {
printk(KERN_ERR PFX "%s: %s: wrong transfer direction!\n",
drive->name, __func__);
if (dev_is_idecd(drive))
ide_pad_transfer(drive, rw, len);
} else if (!rw && ireason == ATAPI_COD) {
if (dev_is_idecd(drive)) {
/*
* Some drives (ASUS) seem to tell us that status info
* is available. Just get it and ignore.
*/
(void)hwif->tp_ops->read_status(hwif);
return 0;
}
} else {
if (ireason & ATAPI_COD)
printk(KERN_ERR PFX "%s: CoD != 0 in %s\n", drive->name,
__func__);
/* drive wants a command packet, or invalid ireason... */
printk(KERN_ERR PFX "%s: %s: bad interrupt reason 0x%02x\n",
drive->name, __func__, ireason);
}
if (dev_is_idecd(drive) && rq->cmd_type == REQ_TYPE_ATA_PC)
rq->cmd_flags |= REQ_FAILED;
return 1;
}
EXPORT_SYMBOL_GPL(ide_check_ireason);
/*
* This is the usual interrupt handler which will be called during a packet
* command. We will transfer some of the data (as requested by the drive)
* and will re-point interrupt handler to us.
*/
static ide_startstop_t ide_pc_intr(ide_drive_t *drive)
{
struct ide_atapi_pc *pc = drive->pc;
ide_hwif_t *hwif = drive->hwif;
struct ide_cmd *cmd = &hwif->cmd;
struct request *rq = hwif->rq;
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
unsigned int timeout, done;
u16 bcount;
u8 stat, ireason, dsc = 0;
u8 write = !!(pc->flags & PC_FLAG_WRITING);
debug_log("Enter %s - interrupt handler\n", __func__);
timeout = (drive->media == ide_floppy) ? WAIT_FLOPPY_CMD
: WAIT_TAPE_CMD;
/* Clear the interrupt */
stat = tp_ops->read_status(hwif);
if (pc->flags & PC_FLAG_DMA_IN_PROGRESS) {
int rc;
drive->waiting_for_dma = 0;
rc = hwif->dma_ops->dma_end(drive);
ide_dma_unmap_sg(drive, cmd);
if (rc || (drive->media == ide_tape && (stat & ATA_ERR))) {
if (drive->media == ide_floppy)
printk(KERN_ERR PFX "%s: DMA %s error\n",
drive->name, rq_data_dir(pc->rq)
? "write" : "read");
pc->flags |= PC_FLAG_DMA_ERROR;
} else
rq->resid_len = 0;
debug_log("%s: DMA finished\n", drive->name);
}
/* No more interrupts */
if ((stat & ATA_DRQ) == 0) {
int uptodate, error;
debug_log("Packet command completed, %d bytes transferred\n",
blk_rq_bytes(rq));
pc->flags &= ~PC_FLAG_DMA_IN_PROGRESS;
local_irq_enable_in_hardirq();
if (drive->media == ide_tape &&
(stat & ATA_ERR) && rq->cmd[0] == REQUEST_SENSE)
stat &= ~ATA_ERR;
if ((stat & ATA_ERR) || (pc->flags & PC_FLAG_DMA_ERROR)) {
/* Error detected */
debug_log("%s: I/O error\n", drive->name);
if (drive->media != ide_tape)
pc->rq->errors++;
if (rq->cmd[0] == REQUEST_SENSE) {
printk(KERN_ERR PFX "%s: I/O error in request "
"sense command\n", drive->name);
return ide_do_reset(drive);
}
debug_log("[cmd %x]: check condition\n", rq->cmd[0]);
/* Retry operation */
ide_retry_pc(drive);
/* queued, but not started */
return ide_stopped;
}
pc->error = 0;
if ((pc->flags & PC_FLAG_WAIT_FOR_DSC) && (stat & ATA_DSC) == 0)
dsc = 1;
/*
* ->pc_callback() might change rq->data_len for
* residual count, cache total length.
*/
done = blk_rq_bytes(rq);
/* Command finished - Call the callback function */
uptodate = drive->pc_callback(drive, dsc);
if (uptodate == 0)
drive->failed_pc = NULL;
if (rq->cmd_type == REQ_TYPE_SPECIAL) {
rq->errors = 0;
error = 0;
} else {
if (rq->cmd_type != REQ_TYPE_FS && uptodate <= 0) {
if (rq->errors == 0)
rq->errors = -EIO;
}
error = uptodate ? 0 : -EIO;
}
ide_complete_rq(drive, error, blk_rq_bytes(rq));
return ide_stopped;
}
if (pc->flags & PC_FLAG_DMA_IN_PROGRESS) {
pc->flags &= ~PC_FLAG_DMA_IN_PROGRESS;
printk(KERN_ERR PFX "%s: The device wants to issue more "
"interrupts in DMA mode\n", drive->name);
ide_dma_off(drive);
return ide_do_reset(drive);
}
/* Get the number of bytes to transfer on this interrupt. */
ide_read_bcount_and_ireason(drive, &bcount, &ireason);
if (ide_check_ireason(drive, rq, bcount, ireason, write))
return ide_do_reset(drive);
done = min_t(unsigned int, bcount, cmd->nleft);
ide_pio_bytes(drive, cmd, write, done);
/* Update transferred byte count */
rq->resid_len -= done;
bcount -= done;
if (bcount)
ide_pad_transfer(drive, write, bcount);
debug_log("[cmd %x] transferred %d bytes, padded %d bytes, resid: %u\n",
rq->cmd[0], done, bcount, rq->resid_len);
/* And set the interrupt handler again */
ide_set_handler(drive, ide_pc_intr, timeout);
return ide_started;
}
static void ide_init_packet_cmd(struct ide_cmd *cmd, u8 valid_tf,
u16 bcount, u8 dma)
{
cmd->protocol = dma ? ATAPI_PROT_DMA : ATAPI_PROT_PIO;
cmd->valid.out.tf = IDE_VALID_LBAH | IDE_VALID_LBAM |
IDE_VALID_FEATURE | valid_tf;
cmd->tf.command = ATA_CMD_PACKET;
cmd->tf.feature = dma; /* Use PIO/DMA */
cmd->tf.lbam = bcount & 0xff;
cmd->tf.lbah = (bcount >> 8) & 0xff;
}
static u8 ide_read_ireason(ide_drive_t *drive)
{
struct ide_taskfile tf;
drive->hwif->tp_ops->tf_read(drive, &tf, IDE_VALID_NSECT);
return tf.nsect & 3;
}
static u8 ide_wait_ireason(ide_drive_t *drive, u8 ireason)
{
int retries = 100;
while (retries-- && ((ireason & ATAPI_COD) == 0 ||
(ireason & ATAPI_IO))) {
printk(KERN_ERR PFX "%s: (IO,CoD != (0,1) while issuing "
"a packet command, retrying\n", drive->name);
udelay(100);
ireason = ide_read_ireason(drive);
if (retries == 0) {
printk(KERN_ERR PFX "%s: (IO,CoD != (0,1) while issuing"
" a packet command, ignoring\n",
drive->name);
ireason |= ATAPI_COD;
ireason &= ~ATAPI_IO;
}
}
return ireason;
}
static int ide_delayed_transfer_pc(ide_drive_t *drive)
{
/* Send the actual packet */
drive->hwif->tp_ops->output_data(drive, NULL, drive->pc->c, 12);
/* Timeout for the packet command */
return WAIT_FLOPPY_CMD;
}
static ide_startstop_t ide_transfer_pc(ide_drive_t *drive)
{
struct ide_atapi_pc *uninitialized_var(pc);
ide_hwif_t *hwif = drive->hwif;
struct request *rq = hwif->rq;
ide_expiry_t *expiry;
unsigned int timeout;
int cmd_len;
ide_startstop_t startstop;
u8 ireason;
if (ide_wait_stat(&startstop, drive, ATA_DRQ, ATA_BUSY, WAIT_READY)) {
printk(KERN_ERR PFX "%s: Strange, packet command initiated yet "
"DRQ isn't asserted\n", drive->name);
return startstop;
}
if (drive->atapi_flags & IDE_AFLAG_DRQ_INTERRUPT) {
if (drive->dma)
drive->waiting_for_dma = 1;
}
if (dev_is_idecd(drive)) {
/* ATAPI commands get padded out to 12 bytes minimum */
cmd_len = COMMAND_SIZE(rq->cmd[0]);
if (cmd_len < ATAPI_MIN_CDB_BYTES)
cmd_len = ATAPI_MIN_CDB_BYTES;
timeout = rq->timeout;
expiry = ide_cd_expiry;
} else {
pc = drive->pc;
cmd_len = ATAPI_MIN_CDB_BYTES;
/*
* If necessary schedule the packet transfer to occur 'timeout'
* milliseconds later in ide_delayed_transfer_pc() after the
* device says it's ready for a packet.
*/
if (drive->atapi_flags & IDE_AFLAG_ZIP_DRIVE) {
timeout = drive->pc_delay;
expiry = &ide_delayed_transfer_pc;
} else {
timeout = (drive->media == ide_floppy) ? WAIT_FLOPPY_CMD
: WAIT_TAPE_CMD;
expiry = NULL;
}
ireason = ide_read_ireason(drive);
if (drive->media == ide_tape)
ireason = ide_wait_ireason(drive, ireason);
if ((ireason & ATAPI_COD) == 0 || (ireason & ATAPI_IO)) {
printk(KERN_ERR PFX "%s: (IO,CoD) != (0,1) while "
"issuing a packet command\n", drive->name);
return ide_do_reset(drive);
}
}
hwif->expiry = expiry;
/* Set the interrupt routine */
ide_set_handler(drive,
(dev_is_idecd(drive) ? drive->irq_handler
: ide_pc_intr),
timeout);
/* Send the actual packet */
if ((drive->atapi_flags & IDE_AFLAG_ZIP_DRIVE) == 0)
hwif->tp_ops->output_data(drive, NULL, rq->cmd, cmd_len);
/* Begin DMA, if necessary */
if (dev_is_idecd(drive)) {
if (drive->dma)
hwif->dma_ops->dma_start(drive);
} else {
if (pc->flags & PC_FLAG_DMA_OK) {
pc->flags |= PC_FLAG_DMA_IN_PROGRESS;
hwif->dma_ops->dma_start(drive);
}
}
return ide_started;
}
ide_startstop_t ide_issue_pc(ide_drive_t *drive, struct ide_cmd *cmd)
{
struct ide_atapi_pc *pc;
ide_hwif_t *hwif = drive->hwif;
ide_expiry_t *expiry = NULL;
struct request *rq = hwif->rq;
unsigned int timeout, bytes;
u16 bcount;
u8 valid_tf;
u8 drq_int = !!(drive->atapi_flags & IDE_AFLAG_DRQ_INTERRUPT);
if (dev_is_idecd(drive)) {
valid_tf = IDE_VALID_NSECT | IDE_VALID_LBAL;
bcount = ide_cd_get_xferlen(rq);
expiry = ide_cd_expiry;
timeout = ATAPI_WAIT_PC;
if (drive->dma)
drive->dma = !ide_dma_prepare(drive, cmd);
} else {
pc = drive->pc;
valid_tf = IDE_VALID_DEVICE;
bytes = blk_rq_bytes(rq);
bcount = ((drive->media == ide_tape) ? bytes
: min_t(unsigned int,
bytes, 63 * 1024));
/* We haven't transferred any data yet */
rq->resid_len = bcount;
if (pc->flags & PC_FLAG_DMA_ERROR) {
pc->flags &= ~PC_FLAG_DMA_ERROR;
ide_dma_off(drive);
}
if (pc->flags & PC_FLAG_DMA_OK)
drive->dma = !ide_dma_prepare(drive, cmd);
if (!drive->dma)
pc->flags &= ~PC_FLAG_DMA_OK;
timeout = (drive->media == ide_floppy) ? WAIT_FLOPPY_CMD
: WAIT_TAPE_CMD;
}
ide_init_packet_cmd(cmd, valid_tf, bcount, drive->dma);
(void)do_rw_taskfile(drive, cmd);
if (drq_int) {
if (drive->dma)
drive->waiting_for_dma = 0;
hwif->expiry = expiry;
}
ide_execute_command(drive, cmd, ide_transfer_pc, timeout);
return drq_int ? ide_started : ide_transfer_pc(drive);
}
EXPORT_SYMBOL_GPL(ide_issue_pc);
| gpl-2.0 |
Android4Lumia/kernel_nokia_msm8x27 | security/integrity/ima/ima_crypto.c | 9170 | 3007 | /*
* Copyright (C) 2005,2006,2007,2008 IBM Corporation
*
* Authors:
* Mimi Zohar <zohar@us.ibm.com>
* Kylene Hall <kjhall@us.ibm.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, version 2 of the License.
*
* File: ima_crypto.c
* Calculates md5/sha1 file hash, template hash, boot-aggreate hash
*/
#include <linux/kernel.h>
#include <linux/file.h>
#include <linux/crypto.h>
#include <linux/scatterlist.h>
#include <linux/err.h>
#include <linux/slab.h>
#include "ima.h"
static int init_desc(struct hash_desc *desc)
{
int rc;
desc->tfm = crypto_alloc_hash(ima_hash, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(desc->tfm)) {
pr_info("IMA: failed to load %s transform: %ld\n",
ima_hash, PTR_ERR(desc->tfm));
rc = PTR_ERR(desc->tfm);
return rc;
}
desc->flags = 0;
rc = crypto_hash_init(desc);
if (rc)
crypto_free_hash(desc->tfm);
return rc;
}
/*
* Calculate the MD5/SHA1 file digest
*/
int ima_calc_hash(struct file *file, char *digest)
{
struct hash_desc desc;
struct scatterlist sg[1];
loff_t i_size, offset = 0;
char *rbuf;
int rc;
rc = init_desc(&desc);
if (rc != 0)
return rc;
rbuf = kzalloc(PAGE_SIZE, GFP_KERNEL);
if (!rbuf) {
rc = -ENOMEM;
goto out;
}
i_size = i_size_read(file->f_dentry->d_inode);
while (offset < i_size) {
int rbuf_len;
rbuf_len = kernel_read(file, offset, rbuf, PAGE_SIZE);
if (rbuf_len < 0) {
rc = rbuf_len;
break;
}
if (rbuf_len == 0)
break;
offset += rbuf_len;
sg_init_one(sg, rbuf, rbuf_len);
rc = crypto_hash_update(&desc, sg, rbuf_len);
if (rc)
break;
}
kfree(rbuf);
if (!rc)
rc = crypto_hash_final(&desc, digest);
out:
crypto_free_hash(desc.tfm);
return rc;
}
/*
* Calculate the hash of a given template
*/
int ima_calc_template_hash(int template_len, void *template, char *digest)
{
struct hash_desc desc;
struct scatterlist sg[1];
int rc;
rc = init_desc(&desc);
if (rc != 0)
return rc;
sg_init_one(sg, template, template_len);
rc = crypto_hash_update(&desc, sg, template_len);
if (!rc)
rc = crypto_hash_final(&desc, digest);
crypto_free_hash(desc.tfm);
return rc;
}
static void __init ima_pcrread(int idx, u8 *pcr)
{
if (!ima_used_chip)
return;
if (tpm_pcr_read(TPM_ANY_NUM, idx, pcr) != 0)
pr_err("IMA: Error Communicating to TPM chip\n");
}
/*
* Calculate the boot aggregate hash
*/
int __init ima_calc_boot_aggregate(char *digest)
{
struct hash_desc desc;
struct scatterlist sg;
u8 pcr_i[IMA_DIGEST_SIZE];
int rc, i;
rc = init_desc(&desc);
if (rc != 0)
return rc;
/* cumulative sha1 over tpm registers 0-7 */
for (i = TPM_PCR0; i < TPM_PCR8; i++) {
ima_pcrread(i, pcr_i);
/* now accumulate with current aggregate */
sg_init_one(&sg, pcr_i, IMA_DIGEST_SIZE);
rc = crypto_hash_update(&desc, &sg, IMA_DIGEST_SIZE);
}
if (!rc)
crypto_hash_final(&desc, digest);
crypto_free_hash(desc.tfm);
return rc;
}
| gpl-2.0 |
kozmikkick/OLD_tripndroid-endeavoru-3.1.10 | drivers/char/agp/ali-agp.c | 9170 | 10370 | /*
* ALi AGPGART routines.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/agp_backend.h>
#include <asm/page.h> /* PAGE_SIZE */
#include "agp.h"
#define ALI_AGPCTRL 0xb8
#define ALI_ATTBASE 0xbc
#define ALI_TLBCTRL 0xc0
#define ALI_TAGCTRL 0xc4
#define ALI_CACHE_FLUSH_CTRL 0xD0
#define ALI_CACHE_FLUSH_ADDR_MASK 0xFFFFF000
#define ALI_CACHE_FLUSH_EN 0x100
static int ali_fetch_size(void)
{
int i;
u32 temp;
struct aper_size_info_32 *values;
pci_read_config_dword(agp_bridge->dev, ALI_ATTBASE, &temp);
temp &= ~(0xfffffff0);
values = A_SIZE_32(agp_bridge->driver->aperture_sizes);
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++) {
if (temp == values[i].size_value) {
agp_bridge->previous_size =
agp_bridge->current_size = (void *) (values + i);
agp_bridge->aperture_size_idx = i;
return values[i].size;
}
}
return 0;
}
static void ali_tlbflush(struct agp_memory *mem)
{
u32 temp;
pci_read_config_dword(agp_bridge->dev, ALI_TLBCTRL, &temp);
temp &= 0xfffffff0;
temp |= (1<<0 | 1<<1);
pci_write_config_dword(agp_bridge->dev, ALI_TAGCTRL, temp);
}
static void ali_cleanup(void)
{
struct aper_size_info_32 *previous_size;
u32 temp;
previous_size = A_SIZE_32(agp_bridge->previous_size);
pci_read_config_dword(agp_bridge->dev, ALI_TLBCTRL, &temp);
// clear tag
pci_write_config_dword(agp_bridge->dev, ALI_TAGCTRL,
((temp & 0xffffff00) | 0x00000001|0x00000002));
pci_read_config_dword(agp_bridge->dev, ALI_ATTBASE, &temp);
pci_write_config_dword(agp_bridge->dev, ALI_ATTBASE,
((temp & 0x00000ff0) | previous_size->size_value));
}
static int ali_configure(void)
{
u32 temp;
struct aper_size_info_32 *current_size;
current_size = A_SIZE_32(agp_bridge->current_size);
/* aperture size and gatt addr */
pci_read_config_dword(agp_bridge->dev, ALI_ATTBASE, &temp);
temp = (((temp & 0x00000ff0) | (agp_bridge->gatt_bus_addr & 0xfffff000))
| (current_size->size_value & 0xf));
pci_write_config_dword(agp_bridge->dev, ALI_ATTBASE, temp);
/* tlb control */
pci_read_config_dword(agp_bridge->dev, ALI_TLBCTRL, &temp);
pci_write_config_dword(agp_bridge->dev, ALI_TLBCTRL, ((temp & 0xffffff00) | 0x00000010));
/* address to map to */
pci_read_config_dword(agp_bridge->dev, AGP_APBASE, &temp);
agp_bridge->gart_bus_addr = (temp & PCI_BASE_ADDRESS_MEM_MASK);
#if 0
if (agp_bridge->type == ALI_M1541) {
u32 nlvm_addr = 0;
switch (current_size->size_value) {
case 0: break;
case 1: nlvm_addr = 0x100000;break;
case 2: nlvm_addr = 0x200000;break;
case 3: nlvm_addr = 0x400000;break;
case 4: nlvm_addr = 0x800000;break;
case 6: nlvm_addr = 0x1000000;break;
case 7: nlvm_addr = 0x2000000;break;
case 8: nlvm_addr = 0x4000000;break;
case 9: nlvm_addr = 0x8000000;break;
case 10: nlvm_addr = 0x10000000;break;
default: break;
}
nlvm_addr--;
nlvm_addr&=0xfff00000;
nlvm_addr+= agp_bridge->gart_bus_addr;
nlvm_addr|=(agp_bridge->gart_bus_addr>>12);
dev_info(&agp_bridge->dev->dev, "nlvm top &base = %8x\n",
nlvm_addr);
}
#endif
pci_read_config_dword(agp_bridge->dev, ALI_TLBCTRL, &temp);
temp &= 0xffffff7f; //enable TLB
pci_write_config_dword(agp_bridge->dev, ALI_TLBCTRL, temp);
return 0;
}
static void m1541_cache_flush(void)
{
int i, page_count;
u32 temp;
global_cache_flush();
page_count = 1 << A_SIZE_32(agp_bridge->current_size)->page_order;
for (i = 0; i < PAGE_SIZE * page_count; i += PAGE_SIZE) {
pci_read_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
&temp);
pci_write_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
(((temp & ALI_CACHE_FLUSH_ADDR_MASK) |
(agp_bridge->gatt_bus_addr + i)) |
ALI_CACHE_FLUSH_EN));
}
}
static struct page *m1541_alloc_page(struct agp_bridge_data *bridge)
{
struct page *page = agp_generic_alloc_page(agp_bridge);
u32 temp;
if (!page)
return NULL;
pci_read_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL, &temp);
pci_write_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
(((temp & ALI_CACHE_FLUSH_ADDR_MASK) |
page_to_phys(page)) | ALI_CACHE_FLUSH_EN ));
return page;
}
static void ali_destroy_page(struct page *page, int flags)
{
if (page) {
if (flags & AGP_PAGE_DESTROY_UNMAP) {
global_cache_flush(); /* is this really needed? --hch */
agp_generic_destroy_page(page, flags);
} else
agp_generic_destroy_page(page, flags);
}
}
static void m1541_destroy_page(struct page *page, int flags)
{
u32 temp;
if (page == NULL)
return;
if (flags & AGP_PAGE_DESTROY_UNMAP) {
global_cache_flush();
pci_read_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL, &temp);
pci_write_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
(((temp & ALI_CACHE_FLUSH_ADDR_MASK) |
page_to_phys(page)) | ALI_CACHE_FLUSH_EN));
}
agp_generic_destroy_page(page, flags);
}
/* Setup function */
static const struct aper_size_info_32 ali_generic_sizes[7] =
{
{256, 65536, 6, 10},
{128, 32768, 5, 9},
{64, 16384, 4, 8},
{32, 8192, 3, 7},
{16, 4096, 2, 6},
{8, 2048, 1, 4},
{4, 1024, 0, 3}
};
static const struct agp_bridge_driver ali_generic_bridge = {
.owner = THIS_MODULE,
.aperture_sizes = ali_generic_sizes,
.size_type = U32_APER_SIZE,
.num_aperture_sizes = 7,
.needs_scratch_page = true,
.configure = ali_configure,
.fetch_size = ali_fetch_size,
.cleanup = ali_cleanup,
.tlb_flush = ali_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.agp_enable = agp_generic_enable,
.cache_flush = global_cache_flush,
.create_gatt_table = agp_generic_create_gatt_table,
.free_gatt_table = agp_generic_free_gatt_table,
.insert_memory = agp_generic_insert_memory,
.remove_memory = agp_generic_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = agp_generic_alloc_page,
.agp_destroy_page = ali_destroy_page,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
};
static const struct agp_bridge_driver ali_m1541_bridge = {
.owner = THIS_MODULE,
.aperture_sizes = ali_generic_sizes,
.size_type = U32_APER_SIZE,
.num_aperture_sizes = 7,
.configure = ali_configure,
.fetch_size = ali_fetch_size,
.cleanup = ali_cleanup,
.tlb_flush = ali_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.agp_enable = agp_generic_enable,
.cache_flush = m1541_cache_flush,
.create_gatt_table = agp_generic_create_gatt_table,
.free_gatt_table = agp_generic_free_gatt_table,
.insert_memory = agp_generic_insert_memory,
.remove_memory = agp_generic_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = m1541_alloc_page,
.agp_destroy_page = m1541_destroy_page,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
};
static struct agp_device_ids ali_agp_device_ids[] __devinitdata =
{
{
.device_id = PCI_DEVICE_ID_AL_M1541,
.chipset_name = "M1541",
},
{
.device_id = PCI_DEVICE_ID_AL_M1621,
.chipset_name = "M1621",
},
{
.device_id = PCI_DEVICE_ID_AL_M1631,
.chipset_name = "M1631",
},
{
.device_id = PCI_DEVICE_ID_AL_M1632,
.chipset_name = "M1632",
},
{
.device_id = PCI_DEVICE_ID_AL_M1641,
.chipset_name = "M1641",
},
{
.device_id = PCI_DEVICE_ID_AL_M1644,
.chipset_name = "M1644",
},
{
.device_id = PCI_DEVICE_ID_AL_M1647,
.chipset_name = "M1647",
},
{
.device_id = PCI_DEVICE_ID_AL_M1651,
.chipset_name = "M1651",
},
{
.device_id = PCI_DEVICE_ID_AL_M1671,
.chipset_name = "M1671",
},
{
.device_id = PCI_DEVICE_ID_AL_M1681,
.chipset_name = "M1681",
},
{
.device_id = PCI_DEVICE_ID_AL_M1683,
.chipset_name = "M1683",
},
{ }, /* dummy final entry, always present */
};
static int __devinit agp_ali_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct agp_device_ids *devs = ali_agp_device_ids;
struct agp_bridge_data *bridge;
u8 hidden_1621_id, cap_ptr;
int j;
cap_ptr = pci_find_capability(pdev, PCI_CAP_ID_AGP);
if (!cap_ptr)
return -ENODEV;
/* probe for known chipsets */
for (j = 0; devs[j].chipset_name; j++) {
if (pdev->device == devs[j].device_id)
goto found;
}
dev_err(&pdev->dev, "unsupported ALi chipset [%04x/%04x])\n",
pdev->vendor, pdev->device);
return -ENODEV;
found:
bridge = agp_alloc_bridge();
if (!bridge)
return -ENOMEM;
bridge->dev = pdev;
bridge->capndx = cap_ptr;
switch (pdev->device) {
case PCI_DEVICE_ID_AL_M1541:
bridge->driver = &ali_m1541_bridge;
break;
case PCI_DEVICE_ID_AL_M1621:
pci_read_config_byte(pdev, 0xFB, &hidden_1621_id);
switch (hidden_1621_id) {
case 0x31:
devs[j].chipset_name = "M1631";
break;
case 0x32:
devs[j].chipset_name = "M1632";
break;
case 0x41:
devs[j].chipset_name = "M1641";
break;
case 0x43:
devs[j].chipset_name = "M1621";
break;
case 0x47:
devs[j].chipset_name = "M1647";
break;
case 0x51:
devs[j].chipset_name = "M1651";
break;
default:
break;
}
/*FALLTHROUGH*/
default:
bridge->driver = &ali_generic_bridge;
}
dev_info(&pdev->dev, "ALi %s chipset\n", devs[j].chipset_name);
/* Fill in the mode register */
pci_read_config_dword(pdev,
bridge->capndx+PCI_AGP_STATUS,
&bridge->mode);
pci_set_drvdata(pdev, bridge);
return agp_add_bridge(bridge);
}
static void __devexit agp_ali_remove(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge = pci_get_drvdata(pdev);
agp_remove_bridge(bridge);
agp_put_bridge(bridge);
}
static struct pci_device_id agp_ali_pci_table[] = {
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_AL,
.device = PCI_ANY_ID,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ }
};
MODULE_DEVICE_TABLE(pci, agp_ali_pci_table);
static struct pci_driver agp_ali_pci_driver = {
.name = "agpgart-ali",
.id_table = agp_ali_pci_table,
.probe = agp_ali_probe,
.remove = agp_ali_remove,
};
static int __init agp_ali_init(void)
{
if (agp_off)
return -EINVAL;
return pci_register_driver(&agp_ali_pci_driver);
}
static void __exit agp_ali_cleanup(void)
{
pci_unregister_driver(&agp_ali_pci_driver);
}
module_init(agp_ali_init);
module_exit(agp_ali_cleanup);
MODULE_AUTHOR("Dave Jones <davej@redhat.com>");
MODULE_LICENSE("GPL and additional rights");
| gpl-2.0 |
cxl000/android_kernel_google_msm | drivers/pci/of.c | 9426 | 1561 | /*
* PCI <-> OF mapping helpers
*
* Copyright 2011 IBM Corp.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/of.h>
#include <linux/of_pci.h>
#include "pci.h"
void pci_set_of_node(struct pci_dev *dev)
{
if (!dev->bus->dev.of_node)
return;
dev->dev.of_node = of_pci_find_child_device(dev->bus->dev.of_node,
dev->devfn);
}
void pci_release_of_node(struct pci_dev *dev)
{
of_node_put(dev->dev.of_node);
dev->dev.of_node = NULL;
}
void pci_set_bus_of_node(struct pci_bus *bus)
{
if (bus->self == NULL)
bus->dev.of_node = pcibios_get_phb_of_node(bus);
else
bus->dev.of_node = of_node_get(bus->self->dev.of_node);
}
void pci_release_bus_of_node(struct pci_bus *bus)
{
of_node_put(bus->dev.of_node);
bus->dev.of_node = NULL;
}
struct device_node * __weak pcibios_get_phb_of_node(struct pci_bus *bus)
{
/* This should only be called for PHBs */
if (WARN_ON(bus->self || bus->parent))
return NULL;
/* Look for a node pointer in either the intermediary device we
* create above the root bus or it's own parent. Normally only
* the later is populated.
*/
if (bus->bridge->of_node)
return of_node_get(bus->bridge->of_node);
if (bus->bridge->parent && bus->bridge->parent->of_node)
return of_node_get(bus->bridge->parent->of_node);
return NULL;
}
| gpl-2.0 |
ReconInstruments/jet_kernel | crypto/salsa20_generic.c | 9938 | 6884 | /*
* Salsa20: Salsa20 stream cipher algorithm
*
* Copyright (c) 2007 Tan Swee Heng <thesweeheng@gmail.com>
*
* Derived from:
* - salsa20.c: Public domain C code by Daniel J. Bernstein <djb@cr.yp.to>
*
* Salsa20 is a stream cipher candidate in eSTREAM, the ECRYPT Stream
* Cipher Project. It is designed by Daniel J. Bernstein <djb@cr.yp.to>.
* More information about eSTREAM and Salsa20 can be found here:
* http://www.ecrypt.eu.org/stream/
* http://cr.yp.to/snuffle.html
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/crypto.h>
#include <linux/types.h>
#include <linux/bitops.h>
#include <crypto/algapi.h>
#include <asm/byteorder.h>
#define SALSA20_IV_SIZE 8U
#define SALSA20_MIN_KEY_SIZE 16U
#define SALSA20_MAX_KEY_SIZE 32U
/*
* Start of code taken from D. J. Bernstein's reference implementation.
* With some modifications and optimizations made to suit our needs.
*/
/*
salsa20-ref.c version 20051118
D. J. Bernstein
Public domain.
*/
#define U32TO8_LITTLE(p, v) \
{ (p)[0] = (v >> 0) & 0xff; (p)[1] = (v >> 8) & 0xff; \
(p)[2] = (v >> 16) & 0xff; (p)[3] = (v >> 24) & 0xff; }
#define U8TO32_LITTLE(p) \
(((u32)((p)[0]) ) | ((u32)((p)[1]) << 8) | \
((u32)((p)[2]) << 16) | ((u32)((p)[3]) << 24) )
struct salsa20_ctx
{
u32 input[16];
};
static void salsa20_wordtobyte(u8 output[64], const u32 input[16])
{
u32 x[16];
int i;
memcpy(x, input, sizeof(x));
for (i = 20; i > 0; i -= 2) {
x[ 4] ^= rol32((x[ 0] + x[12]), 7);
x[ 8] ^= rol32((x[ 4] + x[ 0]), 9);
x[12] ^= rol32((x[ 8] + x[ 4]), 13);
x[ 0] ^= rol32((x[12] + x[ 8]), 18);
x[ 9] ^= rol32((x[ 5] + x[ 1]), 7);
x[13] ^= rol32((x[ 9] + x[ 5]), 9);
x[ 1] ^= rol32((x[13] + x[ 9]), 13);
x[ 5] ^= rol32((x[ 1] + x[13]), 18);
x[14] ^= rol32((x[10] + x[ 6]), 7);
x[ 2] ^= rol32((x[14] + x[10]), 9);
x[ 6] ^= rol32((x[ 2] + x[14]), 13);
x[10] ^= rol32((x[ 6] + x[ 2]), 18);
x[ 3] ^= rol32((x[15] + x[11]), 7);
x[ 7] ^= rol32((x[ 3] + x[15]), 9);
x[11] ^= rol32((x[ 7] + x[ 3]), 13);
x[15] ^= rol32((x[11] + x[ 7]), 18);
x[ 1] ^= rol32((x[ 0] + x[ 3]), 7);
x[ 2] ^= rol32((x[ 1] + x[ 0]), 9);
x[ 3] ^= rol32((x[ 2] + x[ 1]), 13);
x[ 0] ^= rol32((x[ 3] + x[ 2]), 18);
x[ 6] ^= rol32((x[ 5] + x[ 4]), 7);
x[ 7] ^= rol32((x[ 6] + x[ 5]), 9);
x[ 4] ^= rol32((x[ 7] + x[ 6]), 13);
x[ 5] ^= rol32((x[ 4] + x[ 7]), 18);
x[11] ^= rol32((x[10] + x[ 9]), 7);
x[ 8] ^= rol32((x[11] + x[10]), 9);
x[ 9] ^= rol32((x[ 8] + x[11]), 13);
x[10] ^= rol32((x[ 9] + x[ 8]), 18);
x[12] ^= rol32((x[15] + x[14]), 7);
x[13] ^= rol32((x[12] + x[15]), 9);
x[14] ^= rol32((x[13] + x[12]), 13);
x[15] ^= rol32((x[14] + x[13]), 18);
}
for (i = 0; i < 16; ++i)
x[i] += input[i];
for (i = 0; i < 16; ++i)
U32TO8_LITTLE(output + 4 * i,x[i]);
}
static const char sigma[16] = "expand 32-byte k";
static const char tau[16] = "expand 16-byte k";
static void salsa20_keysetup(struct salsa20_ctx *ctx, const u8 *k, u32 kbytes)
{
const char *constants;
ctx->input[1] = U8TO32_LITTLE(k + 0);
ctx->input[2] = U8TO32_LITTLE(k + 4);
ctx->input[3] = U8TO32_LITTLE(k + 8);
ctx->input[4] = U8TO32_LITTLE(k + 12);
if (kbytes == 32) { /* recommended */
k += 16;
constants = sigma;
} else { /* kbytes == 16 */
constants = tau;
}
ctx->input[11] = U8TO32_LITTLE(k + 0);
ctx->input[12] = U8TO32_LITTLE(k + 4);
ctx->input[13] = U8TO32_LITTLE(k + 8);
ctx->input[14] = U8TO32_LITTLE(k + 12);
ctx->input[0] = U8TO32_LITTLE(constants + 0);
ctx->input[5] = U8TO32_LITTLE(constants + 4);
ctx->input[10] = U8TO32_LITTLE(constants + 8);
ctx->input[15] = U8TO32_LITTLE(constants + 12);
}
static void salsa20_ivsetup(struct salsa20_ctx *ctx, const u8 *iv)
{
ctx->input[6] = U8TO32_LITTLE(iv + 0);
ctx->input[7] = U8TO32_LITTLE(iv + 4);
ctx->input[8] = 0;
ctx->input[9] = 0;
}
static void salsa20_encrypt_bytes(struct salsa20_ctx *ctx, u8 *dst,
const u8 *src, unsigned int bytes)
{
u8 buf[64];
if (dst != src)
memcpy(dst, src, bytes);
while (bytes) {
salsa20_wordtobyte(buf, ctx->input);
ctx->input[8]++;
if (!ctx->input[8])
ctx->input[9]++;
if (bytes <= 64) {
crypto_xor(dst, buf, bytes);
return;
}
crypto_xor(dst, buf, 64);
bytes -= 64;
dst += 64;
}
}
/*
* End of code taken from D. J. Bernstein's reference implementation.
*/
static int setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int keysize)
{
struct salsa20_ctx *ctx = crypto_tfm_ctx(tfm);
salsa20_keysetup(ctx, key, keysize);
return 0;
}
static int encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct blkcipher_walk walk;
struct crypto_blkcipher *tfm = desc->tfm;
struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm);
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, 64);
salsa20_ivsetup(ctx, walk.iv);
if (likely(walk.nbytes == nbytes))
{
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr, nbytes);
return blkcipher_walk_done(desc, &walk, 0);
}
while (walk.nbytes >= 64) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr,
walk.nbytes - (walk.nbytes % 64));
err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64);
}
if (walk.nbytes) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr, walk.nbytes);
err = blkcipher_walk_done(desc, &walk, 0);
}
return err;
}
static struct crypto_alg alg = {
.cra_name = "salsa20",
.cra_driver_name = "salsa20-generic",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER,
.cra_type = &crypto_blkcipher_type,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct salsa20_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(alg.cra_list),
.cra_u = {
.blkcipher = {
.setkey = setkey,
.encrypt = encrypt,
.decrypt = encrypt,
.min_keysize = SALSA20_MIN_KEY_SIZE,
.max_keysize = SALSA20_MAX_KEY_SIZE,
.ivsize = SALSA20_IV_SIZE,
}
}
};
static int __init salsa20_generic_mod_init(void)
{
return crypto_register_alg(&alg);
}
static void __exit salsa20_generic_mod_fini(void)
{
crypto_unregister_alg(&alg);
}
module_init(salsa20_generic_mod_init);
module_exit(salsa20_generic_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION ("Salsa20 stream cipher algorithm");
MODULE_ALIAS("salsa20");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.