repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
Tof37/Kernel-ES209RA-3.0.8 | drivers/net/wireless/bcmdhd/dhd_cdc.c | 451 | 69047 | /*
* DHD Protocol Module for CDC and BDC.
*
* Copyright (C) 1999-2011, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: dhd_cdc.c,v 1.51.6.31 2011-02-09 14:31:43 Exp $
*
* BDC is like CDC, except it includes a header for data packets to convey
* packet priority over the bus, and flags (e.g. to indicate checksum status
* for dongle offload.)
*/
#include <typedefs.h>
#include <osl.h>
#include <bcmutils.h>
#include <bcmcdc.h>
#include <bcmendian.h>
#include <dngl_stats.h>
#include <dhd.h>
#include <dhd_proto.h>
#include <dhd_bus.h>
#include <dhd_dbg.h>
#ifdef PROP_TXSTATUS
#include <wlfc_proto.h>
#include <dhd_wlfc.h>
#endif
#define RETRIES 2 /* # of retries to retrieve matching ioctl response */
#define BUS_HEADER_LEN (16+DHD_SDALIGN) /* Must be at least SDPCM_RESERVE
* defined in dhd_sdio.c (amount of header tha might be added)
* plus any space that might be needed for alignment padding.
*/
#define ROUND_UP_MARGIN 2048 /* Biggest SDIO block size possible for
* round off at the end of buffer
*/
#define BUS_RETRIES 1 /* # of retries before aborting a bus tx operation */
#ifdef PROP_TXSTATUS
typedef struct dhd_wlfc_commit_info {
uint8 needs_hdr;
uint8 ac_fifo_credit_spent;
ewlfc_packet_state_t pkt_type;
wlfc_mac_descriptor_t* mac_entry;
void* p;
} dhd_wlfc_commit_info_t;
#endif /* PROP_TXSTATUS */
typedef struct dhd_prot {
uint16 reqid;
uint8 pending;
uint32 lastcmd;
uint8 bus_header[BUS_HEADER_LEN];
cdc_ioctl_t msg;
unsigned char buf[WLC_IOCTL_MAXLEN + ROUND_UP_MARGIN];
} dhd_prot_t;
static int
dhdcdc_msg(dhd_pub_t *dhd)
{
int err = 0;
dhd_prot_t *prot = dhd->prot;
int len = ltoh32(prot->msg.len) + sizeof(cdc_ioctl_t);
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
DHD_OS_WAKE_LOCK(dhd);
/* NOTE : cdc->msg.len holds the desired length of the buffer to be
* returned. Only up to CDC_MAX_MSG_SIZE of this buffer area
* is actually sent to the dongle
*/
if (len > CDC_MAX_MSG_SIZE)
len = CDC_MAX_MSG_SIZE;
/* Send request */
err = dhd_bus_txctl(dhd->bus, (uchar*)&prot->msg, len);
DHD_OS_WAKE_UNLOCK(dhd);
return err;
}
static int
dhdcdc_cmplt(dhd_pub_t *dhd, uint32 id, uint32 len)
{
int ret;
int cdc_len = len+sizeof(cdc_ioctl_t);
dhd_prot_t *prot = dhd->prot;
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
do {
ret = dhd_bus_rxctl(dhd->bus, (uchar*)&prot->msg, cdc_len);
if (ret < 0)
break;
} while (CDC_IOC_ID(ltoh32(prot->msg.flags)) != id);
return ret;
}
static int
dhdcdc_query_ioctl(dhd_pub_t *dhd, int ifidx, uint cmd, void *buf, uint len, uint8 action)
{
dhd_prot_t *prot = dhd->prot;
cdc_ioctl_t *msg = &prot->msg;
void *info;
int ret = 0, retries = 0;
uint32 id, flags = 0;
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
DHD_CTL(("%s: cmd %d len %d\n", __FUNCTION__, cmd, len));
/* Respond "bcmerror" and "bcmerrorstr" with local cache */
if (cmd == WLC_GET_VAR && buf)
{
if (!strcmp((char *)buf, "bcmerrorstr"))
{
strncpy((char *)buf, bcmerrorstr(dhd->dongle_error), BCME_STRLEN);
goto done;
}
else if (!strcmp((char *)buf, "bcmerror"))
{
*(int *)buf = dhd->dongle_error;
goto done;
}
}
memset(msg, 0, sizeof(cdc_ioctl_t));
msg->cmd = htol32(cmd);
msg->len = htol32(len);
msg->flags = (++prot->reqid << CDCF_IOC_ID_SHIFT);
CDC_SET_IF_IDX(msg, ifidx);
/* add additional action bits */
action &= WL_IOCTL_ACTION_MASK;
msg->flags |= (action << CDCF_IOC_ACTION_SHIFT);
msg->flags = htol32(msg->flags);
if (buf)
memcpy(prot->buf, buf, len);
if ((ret = dhdcdc_msg(dhd)) < 0) {
if (!dhd->hang_was_sent)
DHD_ERROR(("dhdcdc_query_ioctl: dhdcdc_msg failed w/status %d\n", ret));
goto done;
}
retry:
/* wait for interrupt and get first fragment */
if ((ret = dhdcdc_cmplt(dhd, prot->reqid, len)) < 0)
goto done;
flags = ltoh32(msg->flags);
id = (flags & CDCF_IOC_ID_MASK) >> CDCF_IOC_ID_SHIFT;
if ((id < prot->reqid) && (++retries < RETRIES))
goto retry;
if (id != prot->reqid) {
DHD_ERROR(("%s: %s: unexpected request id %d (expected %d)\n",
dhd_ifname(dhd, ifidx), __FUNCTION__, id, prot->reqid));
ret = -EINVAL;
goto done;
}
/* Check info buffer */
info = (void*)&msg[1];
/* Copy info buffer */
if (buf)
{
if (ret < (int)len)
len = ret;
memcpy(buf, info, len);
}
/* Check the ERROR flag */
if (flags & CDCF_IOC_ERROR)
{
ret = ltoh32(msg->status);
/* Cache error from dongle */
dhd->dongle_error = ret;
}
done:
return ret;
}
static int
dhdcdc_set_ioctl(dhd_pub_t *dhd, int ifidx, uint cmd, void *buf, uint len, uint8 action)
{
dhd_prot_t *prot = dhd->prot;
cdc_ioctl_t *msg = &prot->msg;
int ret = 0;
uint32 flags, id;
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
DHD_CTL(("%s: cmd %d len %d\n", __FUNCTION__, cmd, len));
if (dhd->busstate == DHD_BUS_DOWN) {
DHD_ERROR(("%s : bus is down. we have nothing to do\n", __FUNCTION__));
return -EIO;
}
/* don't talk to the dongle if fw is about to be reloaded */
if (dhd->hang_was_sent) {
DHD_ERROR(("%s: HANG was sent up earlier. Not talking to the chip\n",
__FUNCTION__));
return -EIO;
}
memset(msg, 0, sizeof(cdc_ioctl_t));
msg->cmd = htol32(cmd);
msg->len = htol32(len);
msg->flags = (++prot->reqid << CDCF_IOC_ID_SHIFT);
CDC_SET_IF_IDX(msg, ifidx);
/* add additional action bits */
action &= WL_IOCTL_ACTION_MASK;
msg->flags |= (action << CDCF_IOC_ACTION_SHIFT) | CDCF_IOC_SET;
msg->flags = htol32(msg->flags);
if (buf)
memcpy(prot->buf, buf, len);
if ((ret = dhdcdc_msg(dhd)) < 0) {
DHD_ERROR(("%s: dhdcdc_msg failed w/status %d\n", __FUNCTION__, ret));
goto done;
}
if ((ret = dhdcdc_cmplt(dhd, prot->reqid, len)) < 0)
goto done;
flags = ltoh32(msg->flags);
id = (flags & CDCF_IOC_ID_MASK) >> CDCF_IOC_ID_SHIFT;
if (id != prot->reqid) {
DHD_ERROR(("%s: %s: unexpected request id %d (expected %d)\n",
dhd_ifname(dhd, ifidx), __FUNCTION__, id, prot->reqid));
ret = -EINVAL;
goto done;
}
/* Check the ERROR flag */
if (flags & CDCF_IOC_ERROR)
{
ret = ltoh32(msg->status);
/* Cache error from dongle */
dhd->dongle_error = ret;
}
done:
return ret;
}
int
dhd_prot_ioctl(dhd_pub_t *dhd, int ifidx, wl_ioctl_t * ioc, void * buf, int len)
{
dhd_prot_t *prot = dhd->prot;
int ret = -1;
uint8 action;
if ((dhd->busstate == DHD_BUS_DOWN) || dhd->hang_was_sent) {
DHD_ERROR(("%s : bus is down. we have nothing to do\n", __FUNCTION__));
goto done;
}
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
ASSERT(len <= WLC_IOCTL_MAXLEN);
if (len > WLC_IOCTL_MAXLEN)
goto done;
if (prot->pending == TRUE) {
DHD_ERROR(("CDC packet is pending!!!! cmd=0x%x (%lu) lastcmd=0x%x (%lu)\n",
ioc->cmd, (unsigned long)ioc->cmd, prot->lastcmd,
(unsigned long)prot->lastcmd));
if ((ioc->cmd == WLC_SET_VAR) || (ioc->cmd == WLC_GET_VAR)) {
DHD_TRACE(("iovar cmd=%s\n", (char*)buf));
}
goto done;
}
prot->pending = TRUE;
prot->lastcmd = ioc->cmd;
action = ioc->set;
if (action & WL_IOCTL_ACTION_SET)
ret = dhdcdc_set_ioctl(dhd, ifidx, ioc->cmd, buf, len, action);
else {
ret = dhdcdc_query_ioctl(dhd, ifidx, ioc->cmd, buf, len, action);
if (ret > 0)
ioc->used = ret - sizeof(cdc_ioctl_t);
}
/* Too many programs assume ioctl() returns 0 on success */
if (ret >= 0)
ret = 0;
else {
cdc_ioctl_t *msg = &prot->msg;
ioc->needed = ltoh32(msg->len); /* len == needed when set/query fails from dongle */
}
/* Intercept the wme_dp ioctl here */
if ((!ret) && (ioc->cmd == WLC_SET_VAR) && (!strcmp(buf, "wme_dp"))) {
int slen, val = 0;
slen = strlen("wme_dp") + 1;
if (len >= (int)(slen + sizeof(int)))
bcopy(((char *)buf + slen), &val, sizeof(int));
dhd->wme_dp = (uint8) ltoh32(val);
}
prot->pending = FALSE;
done:
return ret;
}
int
dhd_prot_iovar_op(dhd_pub_t *dhdp, const char *name,
void *params, int plen, void *arg, int len, bool set)
{
return BCME_UNSUPPORTED;
}
#ifdef PROP_TXSTATUS
void
dhd_wlfc_dump(dhd_pub_t *dhdp, struct bcmstrbuf *strbuf)
{
int i;
uint8* ea;
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhdp->wlfc_state;
wlfc_hanger_t* h;
wlfc_mac_descriptor_t* mac_table;
wlfc_mac_descriptor_t* interfaces;
char* iftypes[] = {"STA", "AP", "WDS", "p2pGO", "p2pCL"};
if (wlfc == NULL) {
bcm_bprintf(strbuf, "wlfc not initialized yet\n");
return;
}
h = (wlfc_hanger_t*)wlfc->hanger;
if (h == NULL) {
bcm_bprintf(strbuf, "wlfc-hanger not initialized yet\n");
}
mac_table = wlfc->destination_entries.nodes;
interfaces = wlfc->destination_entries.interfaces;
bcm_bprintf(strbuf, "---- wlfc stats ----\n");
if (h) {
bcm_bprintf(strbuf, "wlfc hanger (pushed,popped,f_push,"
"f_pop,f_slot, pending) = (%d,%d,%d,%d,%d,%d)\n",
h->pushed,
h->popped,
h->failed_to_push,
h->failed_to_pop,
h->failed_slotfind,
(h->pushed - h->popped));
}
bcm_bprintf(strbuf, "wlfc fail(tlv,credit_rqst,mac_update,psmode_update), "
"(dq_full,sendq_full, rollback_fail) = (%d,%d,%d,%d), (%d,%d,%d)\n",
wlfc->stats.tlv_parse_failed,
wlfc->stats.credit_request_failed,
wlfc->stats.mac_update_failed,
wlfc->stats.psmode_update_failed,
wlfc->stats.delayq_full_error,
wlfc->stats.sendq_full_error,
wlfc->stats.rollback_failed);
bcm_bprintf(strbuf, "SENDQ (len,credit,sent) "
"(AC0[%d,%d,%d],AC1[%d,%d,%d],AC2[%d,%d,%d],AC3[%d,%d,%d],BC_MC[%d,%d,%d])\n",
wlfc->SENDQ.q[0].len, wlfc->FIFO_credit[0], wlfc->stats.sendq_pkts[0],
wlfc->SENDQ.q[1].len, wlfc->FIFO_credit[1], wlfc->stats.sendq_pkts[1],
wlfc->SENDQ.q[2].len, wlfc->FIFO_credit[2], wlfc->stats.sendq_pkts[2],
wlfc->SENDQ.q[3].len, wlfc->FIFO_credit[3], wlfc->stats.sendq_pkts[3],
wlfc->SENDQ.q[4].len, wlfc->FIFO_credit[4], wlfc->stats.sendq_pkts[4]);
#ifdef PROP_TXSTATUS_DEBUG
bcm_bprintf(strbuf, "SENDQ dropped: AC[0-3]:(%d,%d,%d,%d), (bcmc,atim):(%d,%d)\n",
wlfc->stats.dropped_qfull[0], wlfc->stats.dropped_qfull[1],
wlfc->stats.dropped_qfull[2], wlfc->stats.dropped_qfull[3],
wlfc->stats.dropped_qfull[4], wlfc->stats.dropped_qfull[5]);
#endif
bcm_bprintf(strbuf, "\n");
for (i = 0; i < WLFC_MAX_IFNUM; i++) {
if (interfaces[i].occupied) {
char* iftype_desc;
if (interfaces[i].iftype > WLC_E_IF_ROLE_P2P_CLIENT)
iftype_desc = "<Unknown";
else
iftype_desc = iftypes[interfaces[i].iftype];
ea = interfaces[i].ea;
bcm_bprintf(strbuf, "INTERFACE[%d].ea = "
"[%02x:%02x:%02x:%02x:%02x:%02x], if:%d, type: %s\n", i,
ea[0], ea[1], ea[2], ea[3], ea[4], ea[5],
interfaces[i].interface_id,
iftype_desc);
bcm_bprintf(strbuf, "INTERFACE[%d].DELAYQ(len,state,credit)"
"= (%d,%s,%d)\n",
i,
interfaces[i].psq.len,
((interfaces[i].state ==
WLFC_STATE_OPEN) ? " OPEN":"CLOSE"),
interfaces[i].requested_credit);
bcm_bprintf(strbuf, "INTERFACE[%d].DELAYQ"
"(sup,ac0),(sup,ac1),(sup,ac2),(sup,ac3) = "
"(%d,%d),(%d,%d),(%d,%d),(%d,%d)\n",
i,
interfaces[i].psq.q[0].len,
interfaces[i].psq.q[1].len,
interfaces[i].psq.q[2].len,
interfaces[i].psq.q[3].len,
interfaces[i].psq.q[4].len,
interfaces[i].psq.q[5].len,
interfaces[i].psq.q[6].len,
interfaces[i].psq.q[7].len);
}
}
bcm_bprintf(strbuf, "\n");
for (i = 0; i < WLFC_MAC_DESC_TABLE_SIZE; i++) {
if (mac_table[i].occupied) {
ea = mac_table[i].ea;
bcm_bprintf(strbuf, "MAC_table[%d].ea = "
"[%02x:%02x:%02x:%02x:%02x:%02x], if:%d\n", i,
ea[0], ea[1], ea[2], ea[3], ea[4], ea[5],
mac_table[i].interface_id);
bcm_bprintf(strbuf, "MAC_table[%d].DELAYQ(len,state,credit)"
"= (%d,%s,%d)\n",
i,
mac_table[i].psq.len,
((mac_table[i].state ==
WLFC_STATE_OPEN) ? " OPEN":"CLOSE"),
mac_table[i].requested_credit);
#ifdef PROP_TXSTATUS_DEBUG
bcm_bprintf(strbuf, "MAC_table[%d]: (opened, closed) = (%d, %d)\n",
i, mac_table[i].opened_ct, mac_table[i].closed_ct);
#endif
bcm_bprintf(strbuf, "MAC_table[%d].DELAYQ"
"(sup,ac0),(sup,ac1),(sup,ac2),(sup,ac3) = "
"(%d,%d),(%d,%d),(%d,%d),(%d,%d)\n",
i,
mac_table[i].psq.q[0].len,
mac_table[i].psq.q[1].len,
mac_table[i].psq.q[2].len,
mac_table[i].psq.q[3].len,
mac_table[i].psq.q[4].len,
mac_table[i].psq.q[5].len,
mac_table[i].psq.q[6].len,
mac_table[i].psq.q[7].len);
}
}
#ifdef PROP_TXSTATUS_DEBUG
{
int avg;
int moving_avg = 0;
int moving_samples;
if (wlfc->stats.latency_sample_count) {
moving_samples = sizeof(wlfc->stats.deltas)/sizeof(uint32);
for (i = 0; i < moving_samples; i++)
moving_avg += wlfc->stats.deltas[i];
moving_avg /= moving_samples;
avg = (100 * wlfc->stats.total_status_latency) /
wlfc->stats.latency_sample_count;
bcm_bprintf(strbuf, "txstatus latency (average, last, moving[%d]) = "
"(%d.%d, %03d, %03d)\n",
moving_samples, avg/100, (avg - (avg/100)*100),
wlfc->stats.latency_most_recent,
moving_avg);
}
}
bcm_bprintf(strbuf, "wlfc- fifo[0-5] credit stats: sent = (%d,%d,%d,%d,%d,%d), "
"back = (%d,%d,%d,%d,%d,%d)\n",
wlfc->stats.fifo_credits_sent[0],
wlfc->stats.fifo_credits_sent[1],
wlfc->stats.fifo_credits_sent[2],
wlfc->stats.fifo_credits_sent[3],
wlfc->stats.fifo_credits_sent[4],
wlfc->stats.fifo_credits_sent[5],
wlfc->stats.fifo_credits_back[0],
wlfc->stats.fifo_credits_back[1],
wlfc->stats.fifo_credits_back[2],
wlfc->stats.fifo_credits_back[3],
wlfc->stats.fifo_credits_back[4],
wlfc->stats.fifo_credits_back[5]);
{
uint32 fifo_cr_sent = 0;
uint32 fifo_cr_acked = 0;
uint32 request_cr_sent = 0;
uint32 request_cr_ack = 0;
uint32 bc_mc_cr_ack = 0;
for (i = 0; i < sizeof(wlfc->stats.fifo_credits_sent)/sizeof(uint32); i++) {
fifo_cr_sent += wlfc->stats.fifo_credits_sent[i];
}
for (i = 0; i < sizeof(wlfc->stats.fifo_credits_back)/sizeof(uint32); i++) {
fifo_cr_acked += wlfc->stats.fifo_credits_back[i];
}
for (i = 0; i < WLFC_MAC_DESC_TABLE_SIZE; i++) {
if (wlfc->destination_entries.nodes[i].occupied) {
request_cr_sent +=
wlfc->destination_entries.nodes[i].dstncredit_sent_packets;
}
}
for (i = 0; i < WLFC_MAX_IFNUM; i++) {
if (wlfc->destination_entries.interfaces[i].occupied) {
request_cr_sent +=
wlfc->destination_entries.interfaces[i].dstncredit_sent_packets;
}
}
for (i = 0; i < WLFC_MAC_DESC_TABLE_SIZE; i++) {
if (wlfc->destination_entries.nodes[i].occupied) {
request_cr_ack +=
wlfc->destination_entries.nodes[i].dstncredit_acks;
}
}
for (i = 0; i < WLFC_MAX_IFNUM; i++) {
if (wlfc->destination_entries.interfaces[i].occupied) {
request_cr_ack +=
wlfc->destination_entries.interfaces[i].dstncredit_acks;
}
}
bcm_bprintf(strbuf, "wlfc- (sent, status) => pq(%d,%d), vq(%d,%d),"
"other:%d, bc_mc:%d, signal-only, (sent,freed): (%d,%d)",
fifo_cr_sent, fifo_cr_acked,
request_cr_sent, request_cr_ack,
wlfc->destination_entries.other.dstncredit_acks,
bc_mc_cr_ack,
wlfc->stats.signal_only_pkts_sent, wlfc->stats.signal_only_pkts_freed);
}
#endif /* PROP_TXSTATUS_DEBUG */
bcm_bprintf(strbuf, "\n");
bcm_bprintf(strbuf, "wlfc- pkt((in,2bus,txstats,hdrpull),(dropped,hdr_only,wlc_tossed)"
"(freed,free_err,rollback)) = "
"((%d,%d,%d,%d),(%d,%d,%d),(%d,%d,%d))\n",
wlfc->stats.pktin,
wlfc->stats.pkt2bus,
wlfc->stats.txstatus_in,
wlfc->stats.dhd_hdrpulls,
wlfc->stats.pktdropped,
wlfc->stats.wlfc_header_only_pkt,
wlfc->stats.wlc_tossed_pkts,
wlfc->stats.pkt_freed,
wlfc->stats.pkt_free_err, wlfc->stats.rollback);
bcm_bprintf(strbuf, "wlfc- suppress((d11,wlc,err),enq(d11,wl,hq,mac?),retx(d11,wlc,hq)) = "
"((%d,%d,%d),(%d,%d,%d,%d),(%d,%d,%d))\n",
wlfc->stats.d11_suppress,
wlfc->stats.wl_suppress,
wlfc->stats.bad_suppress,
wlfc->stats.psq_d11sup_enq,
wlfc->stats.psq_wlsup_enq,
wlfc->stats.psq_hostq_enq,
wlfc->stats.mac_handle_notfound,
wlfc->stats.psq_d11sup_retx,
wlfc->stats.psq_wlsup_retx,
wlfc->stats.psq_hostq_retx);
return;
}
/* Create a place to store all packet pointers submitted to the firmware until
a status comes back, suppress or otherwise.
hang-er: noun, a contrivance on which things are hung, as a hook.
*/
static void*
dhd_wlfc_hanger_create(osl_t *osh, int max_items)
{
int i;
wlfc_hanger_t* hanger;
/* allow only up to a specific size for now */
ASSERT(max_items == WLFC_HANGER_MAXITEMS);
if ((hanger = (wlfc_hanger_t*)MALLOC(osh, WLFC_HANGER_SIZE(max_items))) == NULL)
return NULL;
memset(hanger, 0, WLFC_HANGER_SIZE(max_items));
hanger->max_items = max_items;
for (i = 0; i < hanger->max_items; i++) {
hanger->items[i].state = WLFC_HANGER_ITEM_STATE_FREE;
}
return hanger;
}
static int
dhd_wlfc_hanger_delete(osl_t *osh, void* hanger)
{
wlfc_hanger_t* h = (wlfc_hanger_t*)hanger;
if (h) {
MFREE(osh, h, WLFC_HANGER_SIZE(h->max_items));
return BCME_OK;
}
return BCME_BADARG;
}
static uint16
dhd_wlfc_hanger_get_free_slot(void* hanger)
{
int i;
wlfc_hanger_t* h = (wlfc_hanger_t*)hanger;
if (h) {
for (i = 0; i < h->max_items; i++) {
if (h->items[i].state == WLFC_HANGER_ITEM_STATE_FREE)
return (uint16)i;
}
h->failed_slotfind++;
}
return WLFC_HANGER_MAXITEMS;
}
static int
dhd_wlfc_hanger_pushpkt(void* hanger, void* pkt, uint32 slot_id)
{
int rc = BCME_OK;
wlfc_hanger_t* h = (wlfc_hanger_t*)hanger;
if (h && (slot_id < WLFC_HANGER_MAXITEMS)) {
if (h->items[slot_id].state == WLFC_HANGER_ITEM_STATE_FREE) {
h->items[slot_id].state = WLFC_HANGER_ITEM_STATE_INUSE;
h->items[slot_id].pkt = pkt;
h->items[slot_id].identifier = slot_id;
h->pushed++;
}
else {
h->failed_to_push++;
rc = BCME_NOTFOUND;
}
}
else
rc = BCME_BADARG;
return rc;
}
static int
dhd_wlfc_hanger_poppkt(void* hanger, uint32 slot_id, void** pktout, int remove_from_hanger)
{
int rc = BCME_OK;
wlfc_hanger_t* h = (wlfc_hanger_t*)hanger;
/* this packet was not pushed at the time it went to the firmware */
if (slot_id == WLFC_HANGER_MAXITEMS)
return BCME_NOTFOUND;
if (h) {
if (h->items[slot_id].state == WLFC_HANGER_ITEM_STATE_INUSE) {
*pktout = h->items[slot_id].pkt;
if (remove_from_hanger) {
h->items[slot_id].state =
WLFC_HANGER_ITEM_STATE_FREE;
h->items[slot_id].pkt = NULL;
h->items[slot_id].identifier = 0;
h->popped++;
}
}
else {
h->failed_to_pop++;
rc = BCME_NOTFOUND;
}
}
else
rc = BCME_BADARG;
return rc;
}
static int
_dhd_wlfc_pushheader(athost_wl_status_info_t* ctx, void* p, bool tim_signal,
uint8 tim_bmp, uint8 mac_handle, uint32 htodtag)
{
uint32 wl_pktinfo = 0;
uint8* wlh;
uint8 dataOffset;
uint8 fillers;
uint8 tim_signal_len = 0;
struct bdc_header *h;
if (tim_signal) {
tim_signal_len = 1 + 1 + WLFC_CTL_VALUE_LEN_PENDING_TRAFFIC_BMP;
}
/* +2 is for Type[1] and Len[1] in TLV, plus TIM signal */
dataOffset = WLFC_CTL_VALUE_LEN_PKTTAG + 2 + tim_signal_len;
fillers = ROUNDUP(dataOffset, 4) - dataOffset;
dataOffset += fillers;
PKTPUSH(ctx->osh, p, dataOffset);
wlh = (uint8*) PKTDATA(ctx->osh, p);
wl_pktinfo = htol32(htodtag);
wlh[0] = WLFC_CTL_TYPE_PKTTAG;
wlh[1] = WLFC_CTL_VALUE_LEN_PKTTAG;
memcpy(&wlh[2], &wl_pktinfo, sizeof(uint32));
if (tim_signal_len) {
wlh[dataOffset - fillers - tim_signal_len ] =
WLFC_CTL_TYPE_PENDING_TRAFFIC_BMP;
wlh[dataOffset - fillers - tim_signal_len + 1] =
WLFC_CTL_VALUE_LEN_PENDING_TRAFFIC_BMP;
wlh[dataOffset - fillers - tim_signal_len + 2] = mac_handle;
wlh[dataOffset - fillers - tim_signal_len + 3] = tim_bmp;
}
if (fillers)
memset(&wlh[dataOffset - fillers], WLFC_CTL_TYPE_FILLER, fillers);
PKTPUSH(ctx->osh, p, BDC_HEADER_LEN);
h = (struct bdc_header *)PKTDATA(ctx->osh, p);
h->flags = (BDC_PROTO_VER << BDC_FLAG_VER_SHIFT);
if (PKTSUMNEEDED(p))
h->flags |= BDC_FLAG_SUM_NEEDED;
h->priority = (PKTPRIO(p) & BDC_PRIORITY_MASK);
h->flags2 = 0;
h->dataOffset = dataOffset >> 2;
BDC_SET_IF_IDX(h, DHD_PKTTAG_IF(PKTTAG(p)));
return BCME_OK;
}
static int
_dhd_wlfc_pullheader(athost_wl_status_info_t* ctx, void* pktbuf)
{
struct bdc_header *h;
if (PKTLEN(ctx->osh, pktbuf) < BDC_HEADER_LEN) {
WLFC_DBGMESG(("%s: rx data too short (%d < %d)\n", __FUNCTION__,
PKTLEN(ctx->osh, pktbuf), BDC_HEADER_LEN));
return BCME_ERROR;
}
h = (struct bdc_header *)PKTDATA(ctx->osh, pktbuf);
/* pull BDC header */
PKTPULL(ctx->osh, pktbuf, BDC_HEADER_LEN);
/* pull wl-header */
PKTPULL(ctx->osh, pktbuf, (h->dataOffset << 2));
return BCME_OK;
}
static wlfc_mac_descriptor_t*
_dhd_wlfc_find_table_entry(athost_wl_status_info_t* ctx, void* p)
{
int i;
wlfc_mac_descriptor_t* table = ctx->destination_entries.nodes;
uint8 ifid = DHD_PKTTAG_IF(PKTTAG(p));
uint8* dstn = DHD_PKTTAG_DSTN(PKTTAG(p));
/* no lookup necessary, only if this packet belongs to STA interface */
if (((ctx->destination_entries.interfaces[ifid].iftype == WLC_E_IF_ROLE_STA) ||
ETHER_ISMULTI(dstn) ||
(ctx->destination_entries.interfaces[ifid].iftype == WLC_E_IF_ROLE_P2P_CLIENT)) &&
(ctx->destination_entries.interfaces[ifid].occupied)) {
return &ctx->destination_entries.interfaces[ifid];
}
for (i = 0; i < WLFC_MAC_DESC_TABLE_SIZE; i++) {
if (table[i].occupied) {
if (table[i].interface_id == ifid) {
if (!memcmp(table[i].ea, dstn, ETHER_ADDR_LEN))
return &table[i];
}
}
}
return &ctx->destination_entries.other;
}
static int
_dhd_wlfc_rollback_packet_toq(athost_wl_status_info_t* ctx,
void* p, ewlfc_packet_state_t pkt_type, uint32 hslot)
{
/*
put the packet back to the head of queue
- a packet from send-q will need to go back to send-q and not delay-q
since that will change the order of packets.
- suppressed packet goes back to suppress sub-queue
- pull out the header, if new or delayed packet
Note: hslot is used only when header removal is done.
*/
wlfc_mac_descriptor_t* entry;
void* pktout;
int rc = BCME_OK;
int prec;
entry = _dhd_wlfc_find_table_entry(ctx, p);
prec = DHD_PKTTAG_FIFO(PKTTAG(p));
if (entry != NULL) {
if (pkt_type == eWLFC_PKTTYPE_SUPPRESSED) {
/* wl-header is saved for suppressed packets */
if (WLFC_PKTQ_PENQ_HEAD(&entry->psq, ((prec << 1) + 1), p) == NULL) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
rc = BCME_ERROR;
}
}
else {
/* remove header first */
_dhd_wlfc_pullheader(ctx, p);
if (pkt_type == eWLFC_PKTTYPE_DELAYED) {
/* delay-q packets are going to delay-q */
if (WLFC_PKTQ_PENQ_HEAD(&entry->psq, (prec << 1), p) == NULL) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
rc = BCME_ERROR;
}
}
else {
/* these are going to SENDQ */
if (WLFC_PKTQ_PENQ_HEAD(&ctx->SENDQ, prec, p) == NULL) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
rc = BCME_ERROR;
}
}
/* free the hanger slot */
dhd_wlfc_hanger_poppkt(ctx->hanger, hslot, &pktout, 1);
/* decrement sequence count */
WLFC_DECR_SEQCOUNT(entry, prec);
}
/*
if this packet did not count against FIFO credit, it must have
taken a requested_credit from the firmware (for pspoll etc.)
*/
if (!DHD_PKTTAG_CREDITCHECK(PKTTAG(p))) {
entry->requested_credit++;
}
}
else {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
rc = BCME_ERROR;
}
if (rc != BCME_OK)
ctx->stats.rollback_failed++;
else
ctx->stats.rollback++;
return rc;
}
static void
_dhd_wlfc_flow_control_check(athost_wl_status_info_t* ctx, struct pktq* pq, uint8 if_id)
{
if ((pq->len <= WLFC_FLOWCONTROL_LOWATER) && (ctx->hostif_flow_state[if_id] == ON)) {
/* start traffic */
ctx->hostif_flow_state[if_id] = OFF;
/*
WLFC_DBGMESG(("qlen:%02d, if:%02d, ->OFF, start traffic %s()\n",
pq->len, if_id, __FUNCTION__));
*/
WLFC_DBGMESG(("F"));
/* dhd_txflowcontrol(ctx->dhdp, if_id, OFF); */
ctx->toggle_host_if = 0;
}
if ((pq->len >= WLFC_FLOWCONTROL_HIWATER) && (ctx->hostif_flow_state[if_id] == OFF)) {
/* stop traffic */
ctx->hostif_flow_state[if_id] = ON;
/*
WLFC_DBGMESG(("qlen:%02d, if:%02d, ->ON, stop traffic %s()\n",
pq->len, if_id, __FUNCTION__));
*/
WLFC_DBGMESG(("N"));
/* dhd_txflowcontrol(ctx->dhdp, if_id, ON); */
ctx->host_ifidx = if_id;
ctx->toggle_host_if = 1;
}
return;
}
static int
_dhd_wlfc_send_signalonly_packet(athost_wl_status_info_t* ctx, wlfc_mac_descriptor_t* entry,
uint8 ta_bmp)
{
int rc = BCME_OK;
void* p = NULL;
int dummylen = ((dhd_pub_t *)ctx->dhdp)->hdrlen+ 12;
/* allocate a dummy packet */
p = PKTGET(ctx->osh, dummylen, TRUE);
if (p) {
PKTPULL(ctx->osh, p, dummylen);
DHD_PKTTAG_SET_H2DTAG(PKTTAG(p), 0);
_dhd_wlfc_pushheader(ctx, p, TRUE, ta_bmp, entry->mac_handle, 0);
DHD_PKTTAG_SETSIGNALONLY(PKTTAG(p), 1);
#ifdef PROP_TXSTATUS_DEBUG
ctx->stats.signal_only_pkts_sent++;
#endif
rc = dhd_bus_txdata(((dhd_pub_t *)ctx->dhdp)->bus, p);
if (rc != BCME_OK) {
PKTFREE(ctx->osh, p, TRUE);
}
}
else {
DHD_ERROR(("%s: couldn't allocate new %d-byte packet\n",
__FUNCTION__, dummylen));
rc = BCME_NOMEM;
}
return rc;
}
/* Return TRUE if traffic availability changed */
static bool
_dhd_wlfc_traffic_pending_check(athost_wl_status_info_t* ctx, wlfc_mac_descriptor_t* entry,
int prec)
{
bool rc = FALSE;
if (entry->state == WLFC_STATE_CLOSE) {
if ((pktq_plen(&entry->psq, (prec << 1)) == 0) &&
(pktq_plen(&entry->psq, ((prec << 1) + 1)) == 0)) {
if (entry->traffic_pending_bmp & NBITVAL(prec)) {
rc = TRUE;
entry->traffic_pending_bmp =
entry->traffic_pending_bmp & ~ NBITVAL(prec);
}
}
else {
if (!(entry->traffic_pending_bmp & NBITVAL(prec))) {
rc = TRUE;
entry->traffic_pending_bmp =
entry->traffic_pending_bmp | NBITVAL(prec);
}
}
}
if (rc) {
/* request a TIM update to firmware at the next piggyback opportunity */
if (entry->traffic_lastreported_bmp != entry->traffic_pending_bmp) {
entry->send_tim_signal = 1;
_dhd_wlfc_send_signalonly_packet(ctx, entry, entry->traffic_pending_bmp);
entry->traffic_lastreported_bmp = entry->traffic_pending_bmp;
entry->send_tim_signal = 0;
}
else {
rc = FALSE;
}
}
return rc;
}
static int
_dhd_wlfc_enque_suppressed(athost_wl_status_info_t* ctx, int prec, void* p)
{
wlfc_mac_descriptor_t* entry;
entry = _dhd_wlfc_find_table_entry(ctx, p);
if (entry == NULL) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
return BCME_NOTFOUND;
}
/*
- suppressed packets go to sub_queue[2*prec + 1] AND
- delayed packets go to sub_queue[2*prec + 0] to ensure
order of delivery.
*/
if (WLFC_PKTQ_PENQ(&entry->psq, ((prec << 1) + 1), p) == NULL) {
ctx->stats.delayq_full_error++;
/* WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__)); */
WLFC_DBGMESG(("s"));
return BCME_ERROR;
}
/* A packet has been pushed, update traffic availability bitmap, if applicable */
_dhd_wlfc_traffic_pending_check(ctx, entry, prec);
_dhd_wlfc_flow_control_check(ctx, &entry->psq, DHD_PKTTAG_IF(PKTTAG(p)));
return BCME_OK;
}
static int
_dhd_wlfc_pretx_pktprocess(athost_wl_status_info_t* ctx,
wlfc_mac_descriptor_t* entry, void* p, int header_needed, uint32* slot)
{
int rc = BCME_OK;
int hslot = WLFC_HANGER_MAXITEMS;
bool send_tim_update = FALSE;
uint32 htod = 0;
uint8 free_ctr;
*slot = hslot;
if (entry == NULL) {
entry = _dhd_wlfc_find_table_entry(ctx, p);
}
if (entry == NULL) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
return BCME_ERROR;
}
if (entry->send_tim_signal) {
send_tim_update = TRUE;
entry->send_tim_signal = 0;
entry->traffic_lastreported_bmp = entry->traffic_pending_bmp;
}
if (header_needed) {
hslot = dhd_wlfc_hanger_get_free_slot(ctx->hanger);
free_ctr = WLFC_SEQCOUNT(entry, DHD_PKTTAG_FIFO(PKTTAG(p)));
DHD_PKTTAG_SET_H2DTAG(PKTTAG(p), htod);
}
else {
hslot = WLFC_PKTID_HSLOT_GET(DHD_PKTTAG_H2DTAG(PKTTAG(p)));
free_ctr = WLFC_PKTID_FREERUNCTR_GET(DHD_PKTTAG_H2DTAG(PKTTAG(p)));
}
WLFC_PKTID_HSLOT_SET(htod, hslot);
WLFC_PKTID_FREERUNCTR_SET(htod, free_ctr);
DHD_PKTTAG_SETPKTDIR(PKTTAG(p), 1);
WL_TXSTATUS_SET_FLAGS(htod, WLFC_PKTFLAG_PKTFROMHOST);
WL_TXSTATUS_SET_FIFO(htod, DHD_PKTTAG_FIFO(PKTTAG(p)));
WLFC_PKTFLAG_SET_GENERATION(htod, entry->generation);
if (!DHD_PKTTAG_CREDITCHECK(PKTTAG(p))) {
/*
Indicate that this packet is being sent in response to an
explicit request from the firmware side.
*/
WLFC_PKTFLAG_SET_PKTREQUESTED(htod);
}
else {
WLFC_PKTFLAG_CLR_PKTREQUESTED(htod);
}
if (header_needed) {
rc = _dhd_wlfc_pushheader(ctx, p, send_tim_update,
entry->traffic_lastreported_bmp, entry->mac_handle, htod);
if (rc == BCME_OK) {
DHD_PKTTAG_SET_H2DTAG(PKTTAG(p), htod);
/*
a new header was created for this packet.
push to hanger slot and scrub q. Since bus
send succeeded, increment seq number as well.
*/
rc = dhd_wlfc_hanger_pushpkt(ctx->hanger, p, hslot);
if (rc == BCME_OK) {
/* increment free running sequence count */
WLFC_INCR_SEQCOUNT(entry, DHD_PKTTAG_FIFO(PKTTAG(p)));
#ifdef PROP_TXSTATUS_DEBUG
((wlfc_hanger_t*)(ctx->hanger))->items[hslot].push_time =
OSL_SYSUPTIME();
#endif
}
else {
WLFC_DBGMESG(("%s() hanger_pushpkt() failed, rc: %d\n",
__FUNCTION__, rc));
}
}
}
else {
/* remove old header */
_dhd_wlfc_pullheader(ctx, p);
hslot = WLFC_PKTID_HSLOT_GET(DHD_PKTTAG_H2DTAG(PKTTAG(p)));
free_ctr = WLFC_PKTID_FREERUNCTR_GET(DHD_PKTTAG_H2DTAG(PKTTAG(p)));
/* push new header */
_dhd_wlfc_pushheader(ctx, p, send_tim_update,
entry->traffic_lastreported_bmp, entry->mac_handle, htod);
}
*slot = hslot;
return rc;
}
static int
_dhd_wlfc_is_destination_closed(athost_wl_status_info_t* ctx,
wlfc_mac_descriptor_t* entry, int prec)
{
if (ctx->destination_entries.interfaces[entry->interface_id].iftype ==
WLC_E_IF_ROLE_P2P_GO) {
/* - destination interface is of type p2p GO.
For a p2pGO interface, if the destination is OPEN but the interface is
CLOSEd, do not send traffic. But if the dstn is CLOSEd while there is
destination-specific-credit left send packets. This is because the
firmware storing the destination-specific-requested packet in queue.
*/
if ((entry->state == WLFC_STATE_CLOSE) && (entry->requested_credit == 0) &&
(entry->requested_packet == 0))
return 1;
}
/* AP, p2p_go -> unicast desc entry, STA/p2p_cl -> interface desc. entry */
if (((entry->state == WLFC_STATE_CLOSE) && (entry->requested_credit == 0) &&
(entry->requested_packet == 0)) ||
(!(entry->ac_bitmap & (1 << prec))))
return 1;
return 0;
}
static void*
_dhd_wlfc_deque_delayedq(athost_wl_status_info_t* ctx,
int prec, uint8* ac_credit_spent, uint8* needs_hdr, wlfc_mac_descriptor_t** entry_out)
{
wlfc_mac_descriptor_t* entry;
wlfc_mac_descriptor_t* table;
uint8 token_pos;
int total_entries;
void* p = NULL;
int pout;
int i;
*entry_out = NULL;
token_pos = ctx->token_pos[prec];
/* most cases a packet will count against FIFO credit */
*ac_credit_spent = 1;
*needs_hdr = 1;
/* search all entries, include nodes as well as interfaces */
table = (wlfc_mac_descriptor_t*)&ctx->destination_entries;
total_entries = sizeof(ctx->destination_entries)/sizeof(wlfc_mac_descriptor_t);
for (i = 0; i < total_entries; i++) {
entry = &table[(token_pos + i) % total_entries];
if (entry->occupied) {
if (!_dhd_wlfc_is_destination_closed(ctx, entry, prec)) {
p = pktq_mdeq(&entry->psq,
/* higher precedence will be picked up first,
i.e. suppressed packets before delayed ones
*/
(NBITVAL((prec << 1) + 1) | NBITVAL((prec << 1))),
&pout);
if (p != NULL) {
/* did the packet come from suppress sub-queue? */
if (pout == ((prec << 1) + 1)) {
/*
this packet was suppressed and was sent on the bus
previously; this already has a header
*/
*needs_hdr = 0;
}
if (entry->requested_credit > 0) {
entry->requested_credit--;
#ifdef PROP_TXSTATUS_DEBUG
entry->dstncredit_sent_packets++;
#endif
/*
if the packet was pulled out while destination is in
closed state but had a non-zero packets requested,
then this should not count against the FIFO credit.
That is due to the fact that the firmware will
most likely hold onto this packet until a suitable
time later to push it to the appropriate AC FIFO.
*/
if (entry->state == WLFC_STATE_CLOSE)
*ac_credit_spent = 0;
}
else if (entry->requested_packet > 0) {
entry->requested_packet--;
DHD_PKTTAG_SETONETIMEPKTRQST(PKTTAG(p));
if (entry->state == WLFC_STATE_CLOSE)
*ac_credit_spent = 0;
}
/* move token to ensure fair round-robin */
ctx->token_pos[prec] =
(token_pos + i + 1) % total_entries;
*entry_out = entry;
_dhd_wlfc_flow_control_check(ctx, &entry->psq,
DHD_PKTTAG_IF(PKTTAG(p)));
/*
A packet has been picked up, update traffic
availability bitmap, if applicable
*/
_dhd_wlfc_traffic_pending_check(ctx, entry, prec);
return p;
}
}
}
}
return NULL;
}
static void*
_dhd_wlfc_deque_sendq(athost_wl_status_info_t* ctx, int prec, uint8* ac_credit_spent)
{
wlfc_mac_descriptor_t* entry;
void* p;
/* most cases a packet will count against FIFO credit */
*ac_credit_spent = 1;
p = pktq_pdeq(&ctx->SENDQ, prec);
if (p != NULL) {
if (ETHER_ISMULTI(DHD_PKTTAG_DSTN(PKTTAG(p))))
/* bc/mc packets do not have a delay queue */
return p;
entry = _dhd_wlfc_find_table_entry(ctx, p);
if (entry == NULL) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
return p;
}
while ((p != NULL) && _dhd_wlfc_is_destination_closed(ctx, entry, prec)) {
/*
- suppressed packets go to sub_queue[2*prec + 1] AND
- delayed packets go to sub_queue[2*prec + 0] to ensure
order of delivery.
*/
if (WLFC_PKTQ_PENQ(&entry->psq, (prec << 1), p) == NULL) {
WLFC_DBGMESG(("D"));
/* dhd_txcomplete(ctx->dhdp, p, FALSE); */
PKTFREE(ctx->osh, p, TRUE);
ctx->stats.delayq_full_error++;
}
/*
A packet has been pushed, update traffic availability bitmap,
if applicable
*/
_dhd_wlfc_traffic_pending_check(ctx, entry, prec);
_dhd_wlfc_flow_control_check(ctx, &entry->psq, DHD_PKTTAG_IF(PKTTAG(p)));
p = pktq_pdeq(&ctx->SENDQ, prec);
if (p == NULL)
break;
entry = _dhd_wlfc_find_table_entry(ctx, p);
if ((entry == NULL) || (ETHER_ISMULTI(DHD_PKTTAG_DSTN(PKTTAG(p))))) {
return p;
}
}
if (p) {
if (entry->requested_packet == 0) {
if (entry->requested_credit > 0)
entry->requested_credit--;
}
else {
entry->requested_packet--;
DHD_PKTTAG_SETONETIMEPKTRQST(PKTTAG(p));
}
if (entry->state == WLFC_STATE_CLOSE)
*ac_credit_spent = 0;
#ifdef PROP_TXSTATUS_DEBUG
entry->dstncredit_sent_packets++;
#endif
}
if (p)
_dhd_wlfc_flow_control_check(ctx, &ctx->SENDQ, DHD_PKTTAG_IF(PKTTAG(p)));
}
return p;
}
static int
_dhd_wlfc_mac_entry_update(athost_wl_status_info_t* ctx, wlfc_mac_descriptor_t* entry,
ewlfc_mac_entry_action_t action, uint8 ifid, uint8 iftype, uint8* ea)
{
int rc = BCME_OK;
if (action == eWLFC_MAC_ENTRY_ACTION_ADD) {
entry->occupied = 1;
entry->state = WLFC_STATE_OPEN;
entry->requested_credit = 0;
entry->interface_id = ifid;
entry->iftype = iftype;
entry->ac_bitmap = 0xff; /* update this when handling APSD */
/* for an interface entry we may not care about the MAC address */
if (ea != NULL)
memcpy(&entry->ea[0], ea, ETHER_ADDR_LEN);
pktq_init(&entry->psq, WLFC_PSQ_PREC_COUNT, WLFC_PSQ_LEN);
}
else if (action == eWLFC_MAC_ENTRY_ACTION_DEL) {
entry->occupied = 0;
entry->state = WLFC_STATE_CLOSE;
entry->requested_credit = 0;
/* enable after packets are queued-deqeued properly.
pktq_flush(dhd->osh, &entry->psq, FALSE, NULL, 0);
*/
}
return rc;
}
int
_dhd_wlfc_borrow_credit(athost_wl_status_info_t* ctx, uint8 available_credit_map, int borrower_ac)
{
int lender_ac;
int rc = BCME_ERROR;
if (ctx == NULL || available_credit_map == 0) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
return BCME_BADARG;
}
/* Borrow from lowest priority available AC (including BC/MC credits) */
for (lender_ac = 0; lender_ac <= AC_COUNT; lender_ac++) {
if ((available_credit_map && (1 << lender_ac)) &&
(ctx->FIFO_credit[lender_ac] > 0)) {
ctx->credits_borrowed[borrower_ac][lender_ac]++;
ctx->FIFO_credit[lender_ac]--;
rc = BCME_OK;
break;
}
}
return rc;
}
int
dhd_wlfc_interface_entry_update(void* state,
ewlfc_mac_entry_action_t action, uint8 ifid, uint8 iftype, uint8* ea)
{
athost_wl_status_info_t* ctx = (athost_wl_status_info_t*)state;
wlfc_mac_descriptor_t* entry;
if (ifid >= WLFC_MAX_IFNUM)
return BCME_BADARG;
entry = &ctx->destination_entries.interfaces[ifid];
return _dhd_wlfc_mac_entry_update(ctx, entry, action, ifid, iftype, ea);
}
int
dhd_wlfc_FIFOcreditmap_update(void* state, uint8* credits)
{
athost_wl_status_info_t* ctx = (athost_wl_status_info_t*)state;
/* update the AC FIFO credit map */
ctx->FIFO_credit[0] = credits[0];
ctx->FIFO_credit[1] = credits[1];
ctx->FIFO_credit[2] = credits[2];
ctx->FIFO_credit[3] = credits[3];
/* credit for bc/mc packets */
ctx->FIFO_credit[4] = credits[4];
/* credit for ATIM FIFO is not used yet. */
ctx->FIFO_credit[5] = 0;
return BCME_OK;
}
int
dhd_wlfc_enque_sendq(void* state, int prec, void* p)
{
athost_wl_status_info_t* ctx = (athost_wl_status_info_t*)state;
if ((state == NULL) ||
/* prec = AC_COUNT is used for bc/mc queue */
(prec > AC_COUNT) ||
(p == NULL)) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
return BCME_BADARG;
}
if (FALSE == dhd_prec_enq(ctx->dhdp, &ctx->SENDQ, p, prec)) {
ctx->stats.sendq_full_error++;
/*
WLFC_DBGMESG(("Error: %s():%d, qlen:%d\n",
__FUNCTION__, __LINE__, ctx->SENDQ.len));
*/
WLFC_HOST_FIFO_DROPPEDCTR_INC(ctx, prec);
WLFC_DBGMESG(("Q"));
PKTFREE(ctx->osh, p, TRUE);
return BCME_ERROR;
}
ctx->stats.pktin++;
/* _dhd_wlfc_flow_control_check(ctx, &ctx->SENDQ, DHD_PKTTAG_IF(PKTTAG(p))); */
return BCME_OK;
}
int
_dhd_wlfc_handle_packet_commit(athost_wl_status_info_t* ctx, int ac,
dhd_wlfc_commit_info_t *commit_info, f_commitpkt_t fcommit, void* commit_ctx)
{
uint32 hslot;
int rc;
/*
if ac_fifo_credit_spent = 0
This packet will not count against the FIFO credit.
To ensure the txstatus corresponding to this packet
does not provide an implied credit (default behavior)
mark the packet accordingly.
if ac_fifo_credit_spent = 1
This is a normal packet and it counts against the FIFO
credit count.
*/
DHD_PKTTAG_SETCREDITCHECK(PKTTAG(commit_info->p), commit_info->ac_fifo_credit_spent);
rc = _dhd_wlfc_pretx_pktprocess(ctx, commit_info->mac_entry, commit_info->p,
commit_info->needs_hdr, &hslot);
if (rc == BCME_OK)
rc = fcommit(commit_ctx, commit_info->p);
else
ctx->stats.generic_error++;
if (rc == BCME_OK) {
ctx->stats.pkt2bus++;
if (commit_info->ac_fifo_credit_spent) {
ctx->stats.sendq_pkts[ac]++;
WLFC_HOST_FIFO_CREDIT_INC_SENTCTRS(ctx, ac);
}
}
else {
/*
bus commit has failed, rollback.
- remove wl-header for a delayed packet
- save wl-header header for suppressed packets
*/
rc = _dhd_wlfc_rollback_packet_toq(ctx, commit_info->p,
(commit_info->pkt_type), hslot);
if (rc != BCME_OK)
ctx->stats.rollback_failed++;
rc = BCME_ERROR;
}
return rc;
}
int
dhd_wlfc_commit_packets(void* state, f_commitpkt_t fcommit, void* commit_ctx)
{
int ac;
int credit;
int rc;
dhd_wlfc_commit_info_t commit_info;
athost_wl_status_info_t* ctx = (athost_wl_status_info_t*)state;
int credit_count = 0;
int bus_retry_count = 0;
uint8 ac_available = 0; /* Bitmask for 4 ACs + BC/MC */
if ((state == NULL) ||
(fcommit == NULL)) {
WLFC_DBGMESG(("Error: %s():%d\n", __FUNCTION__, __LINE__));
return BCME_BADARG;
}
memset(&commit_info, 0, sizeof(commit_info));
/*
Commit packets for regular AC traffic. Higher priority first.
First, use up FIFO credits available to each AC. Based on distribution
and credits left, borrow from other ACs as applicable
-NOTE:
If the bus between the host and firmware is overwhelmed by the
traffic from host, it is possible that higher priority traffic
starves the lower priority queue. If that occurs often, we may
have to employ weighted round-robin or ucode scheme to avoid
low priority packet starvation.
*/
for (ac = AC_COUNT; ac >= 0; ac--) {
int initial_credit_count = ctx->FIFO_credit[ac];
for (credit = 0; credit < ctx->FIFO_credit[ac];) {
commit_info.p = _dhd_wlfc_deque_delayedq(ctx, ac,
&(commit_info.ac_fifo_credit_spent),
&(commit_info.needs_hdr),
&(commit_info.mac_entry));
if (commit_info.p == NULL)
break;
commit_info.pkt_type = (commit_info.needs_hdr) ? eWLFC_PKTTYPE_DELAYED :
eWLFC_PKTTYPE_SUPPRESSED;
rc = _dhd_wlfc_handle_packet_commit(ctx, ac, &commit_info,
fcommit, commit_ctx);
/* Bus commits may fail (e.g. flow control); abort after retries */
if (rc == BCME_OK) {
if (commit_info.ac_fifo_credit_spent) {
credit++;
}
}
else {
bus_retry_count++;
if (bus_retry_count >= BUS_RETRIES) {
DHD_ERROR(("dhd_wlfc_commit_packets(): bus error\n"));
ctx->FIFO_credit[ac] -= credit;
return rc;
}
}
}
ctx->FIFO_credit[ac] -= credit;
/* packets from SENDQ are fresh and they'd need header and have no MAC entry */
commit_info.needs_hdr = 1;
commit_info.mac_entry = NULL;
commit_info.pkt_type = eWLFC_PKTTYPE_NEW;
for (credit = 0; credit < ctx->FIFO_credit[ac];) {
commit_info.p = _dhd_wlfc_deque_sendq(ctx, ac,
&(commit_info.ac_fifo_credit_spent));
if (commit_info.p == NULL)
break;
rc = _dhd_wlfc_handle_packet_commit(ctx, ac, &commit_info,
fcommit, commit_ctx);
/* Bus commits may fail (e.g. flow control); abort after retries */
if (rc == BCME_OK) {
if (commit_info.ac_fifo_credit_spent) {
credit++;
}
}
else {
bus_retry_count++;
if (bus_retry_count >= BUS_RETRIES) {
DHD_ERROR(("dhd_wlfc_commit_packets(): bus error\n"));
ctx->FIFO_credit[ac] -= credit;
return rc;
}
}
}
ctx->FIFO_credit[ac] -= credit;
/* If no credits were used, the queue is idle and can be re-used
Note that resv credits cannot be borrowed
*/
if (initial_credit_count == ctx->FIFO_credit[ac]) {
ac_available |= (1 << ac);
credit_count += ctx->FIFO_credit[ac];
}
}
/* We borrow only for AC_BE and only if no other traffic seen for DEFER_PERIOD
Note that (ac_available & WLFC_AC_BE_TRAFFIC_ONLY) is done to:
a) ignore BC/MC for deferring borrow
b) ignore AC_BE being available along with other ACs
(this should happen only for pure BC/MC traffic)
i.e. AC_VI, AC_VO, AC_BK all MUST be available (i.e. no traffic) and
we do not care if AC_BE and BC/MC are available or not
*/
if ((ac_available & WLFC_AC_BE_TRAFFIC_ONLY) == WLFC_AC_BE_TRAFFIC_ONLY) {
if (ctx->allow_credit_borrow) {
ac = 1; /* Set ac to AC_BE and borrow credits */
}
else {
int delta;
int curr_t = OSL_SYSUPTIME();
if (curr_t > ctx->borrow_defer_timestamp)
delta = curr_t - ctx->borrow_defer_timestamp;
else
delta = 0xffffffff + curr_t - ctx->borrow_defer_timestamp;
if (delta >= WLFC_BORROW_DEFER_PERIOD_MS) {
/* Reset borrow but defer to next iteration (defensive borrowing) */
ctx->allow_credit_borrow = TRUE;
ctx->borrow_defer_timestamp = 0;
}
return BCME_OK;
}
}
else {
/* If we have multiple AC traffic, turn off borrowing, mark time and bail out */
ctx->allow_credit_borrow = FALSE;
ctx->borrow_defer_timestamp = OSL_SYSUPTIME();
return BCME_OK;
}
/* At this point, borrow all credits only for "ac" (which should be set above to AC_BE)
Generically use "ac" only in case we extend to all ACs in future
*/
for (; (credit_count > 0);) {
commit_info.p = _dhd_wlfc_deque_delayedq(ctx, ac,
&(commit_info.ac_fifo_credit_spent),
&(commit_info.needs_hdr),
&(commit_info.mac_entry));
if (commit_info.p == NULL)
break;
commit_info.pkt_type = (commit_info.needs_hdr) ? eWLFC_PKTTYPE_DELAYED :
eWLFC_PKTTYPE_SUPPRESSED;
rc = _dhd_wlfc_handle_packet_commit(ctx, ac, &commit_info,
fcommit, commit_ctx);
/* Bus commits may fail (e.g. flow control); abort after retries */
if (rc == BCME_OK) {
if (commit_info.ac_fifo_credit_spent) {
(void) _dhd_wlfc_borrow_credit(ctx, ac_available, ac);
credit_count--;
}
}
else {
bus_retry_count++;
if (bus_retry_count >= BUS_RETRIES) {
DHD_ERROR(("dhd_wlfc_commit_packets(): bus error\n"));
return rc;
}
}
}
/* packets from SENDQ are fresh and they'd need header and have no MAC entry */
commit_info.needs_hdr = 1;
commit_info.mac_entry = NULL;
commit_info.pkt_type = eWLFC_PKTTYPE_NEW;
for (; (credit_count > 0);) {
commit_info.p = _dhd_wlfc_deque_sendq(ctx, ac,
&(commit_info.ac_fifo_credit_spent));
if (commit_info.p == NULL)
break;
rc = _dhd_wlfc_handle_packet_commit(ctx, ac, &commit_info,
fcommit, commit_ctx);
/* Bus commits may fail (e.g. flow control); abort after retries */
if (rc == BCME_OK) {
if (commit_info.ac_fifo_credit_spent) {
(void) _dhd_wlfc_borrow_credit(ctx, ac_available, ac);
credit_count--;
}
}
else {
bus_retry_count++;
if (bus_retry_count >= BUS_RETRIES) {
DHD_ERROR(("dhd_wlfc_commit_packets(): bus error\n"));
return rc;
}
}
}
return BCME_OK;
}
static uint8
dhd_wlfc_find_mac_desc_id_from_mac(dhd_pub_t *dhdp, uint8* ea)
{
wlfc_mac_descriptor_t* table =
((athost_wl_status_info_t*)dhdp->wlfc_state)->destination_entries.nodes;
uint8 table_index;
if (ea != NULL) {
for (table_index = 0; table_index < WLFC_MAC_DESC_TABLE_SIZE; table_index++) {
if ((memcmp(ea, &table[table_index].ea[0], ETHER_ADDR_LEN) == 0) &&
table[table_index].occupied)
return table_index;
}
}
return WLFC_MAC_DESC_ID_INVALID;
}
void
dhd_wlfc_txcomplete(dhd_pub_t *dhd, void *txp, bool success)
{
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
void* p;
int fifo_id;
if (DHD_PKTTAG_SIGNALONLY(PKTTAG(txp))) {
#ifdef PROP_TXSTATUS_DEBUG
wlfc->stats.signal_only_pkts_freed++;
#endif
/* is this a signal-only packet? */
PKTFREE(wlfc->osh, txp, TRUE);
return;
}
if (!success) {
WLFC_DBGMESG(("At: %s():%d, bus_complete() failure for %p, htod_tag:0x%08x\n",
__FUNCTION__, __LINE__, txp, DHD_PKTTAG_H2DTAG(PKTTAG(txp))));
dhd_wlfc_hanger_poppkt(wlfc->hanger, WLFC_PKTID_HSLOT_GET(DHD_PKTTAG_H2DTAG
(PKTTAG(txp))), &p, 1);
/* indicate failure and free the packet */
dhd_txcomplete(dhd, txp, FALSE);
/* return the credit, if necessary */
if (DHD_PKTTAG_CREDITCHECK(PKTTAG(txp))) {
int lender, credit_returned = 0; /* Note that borrower is fifo_id */
fifo_id = DHD_PKTTAG_FIFO(PKTTAG(txp));
/* Return credits to highest priority lender first */
for (lender = AC_COUNT; lender >= 0; lender--) {
if (wlfc->credits_borrowed[fifo_id][lender] > 0) {
wlfc->FIFO_credit[lender]++;
wlfc->credits_borrowed[fifo_id][lender]--;
credit_returned = 1;
break;
}
}
if (!credit_returned) {
wlfc->FIFO_credit[fifo_id]++;
}
}
PKTFREE(wlfc->osh, txp, TRUE);
}
return;
}
/* Handle discard or suppress indication */
static int
dhd_wlfc_txstatus_update(dhd_pub_t *dhd, uint8* pkt_info)
{
uint8 status_flag;
uint32 status;
int ret;
int remove_from_hanger = 1;
void* pktbuf;
uint8 fifo_id;
wlfc_mac_descriptor_t* entry = NULL;
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
memcpy(&status, pkt_info, sizeof(uint32));
status_flag = WL_TXSTATUS_GET_FLAGS(status);
wlfc->stats.txstatus_in++;
if (status_flag == WLFC_CTL_PKTFLAG_DISCARD) {
wlfc->stats.pkt_freed++;
}
else if (status_flag == WLFC_CTL_PKTFLAG_D11SUPPRESS) {
wlfc->stats.d11_suppress++;
remove_from_hanger = 0;
}
else if (status_flag == WLFC_CTL_PKTFLAG_WLSUPPRESS) {
wlfc->stats.wl_suppress++;
remove_from_hanger = 0;
}
else if (status_flag == WLFC_CTL_PKTFLAG_TOSSED_BYWLC) {
wlfc->stats.wlc_tossed_pkts++;
}
ret = dhd_wlfc_hanger_poppkt(wlfc->hanger,
WLFC_PKTID_HSLOT_GET(status), &pktbuf, remove_from_hanger);
if (ret != BCME_OK) {
/* do something */
return ret;
}
if (!remove_from_hanger) {
/* this packet was suppressed */
entry = _dhd_wlfc_find_table_entry(wlfc, pktbuf);
entry->generation = WLFC_PKTID_GEN(status);
}
#ifdef PROP_TXSTATUS_DEBUG
{
uint32 new_t = OSL_SYSUPTIME();
uint32 old_t;
uint32 delta;
old_t = ((wlfc_hanger_t*)(wlfc->hanger))->items[
WLFC_PKTID_HSLOT_GET(status)].push_time;
wlfc->stats.latency_sample_count++;
if (new_t > old_t)
delta = new_t - old_t;
else
delta = 0xffffffff + new_t - old_t;
wlfc->stats.total_status_latency += delta;
wlfc->stats.latency_most_recent = delta;
wlfc->stats.deltas[wlfc->stats.idx_delta++] = delta;
if (wlfc->stats.idx_delta == sizeof(wlfc->stats.deltas)/sizeof(uint32))
wlfc->stats.idx_delta = 0;
}
#endif /* PROP_TXSTATUS_DEBUG */
fifo_id = DHD_PKTTAG_FIFO(PKTTAG(pktbuf));
/* pick up the implicit credit from this packet */
if (DHD_PKTTAG_CREDITCHECK(PKTTAG(pktbuf))) {
if (wlfc->proptxstatus_mode == WLFC_FCMODE_IMPLIED_CREDIT) {
int lender, credit_returned = 0; /* Note that borrower is fifo_id */
/* Return credits to highest priority lender first */
for (lender = AC_COUNT; lender >= 0; lender--) {
if (wlfc->credits_borrowed[fifo_id][lender] > 0) {
wlfc->FIFO_credit[lender]++;
wlfc->credits_borrowed[fifo_id][lender]--;
credit_returned = 1;
break;
}
}
if (!credit_returned) {
wlfc->FIFO_credit[fifo_id]++;
}
}
}
else {
/*
if this packet did not count against FIFO credit, it must have
taken a requested_credit from the destination entry (for pspoll etc.)
*/
if (!entry) {
entry = _dhd_wlfc_find_table_entry(wlfc, pktbuf);
}
if (!DHD_PKTTAG_ONETIMEPKTRQST(PKTTAG(pktbuf)))
entry->requested_credit++;
#ifdef PROP_TXSTATUS_DEBUG
entry->dstncredit_acks++;
#endif
}
if ((status_flag == WLFC_CTL_PKTFLAG_D11SUPPRESS) ||
(status_flag == WLFC_CTL_PKTFLAG_WLSUPPRESS)) {
ret = _dhd_wlfc_enque_suppressed(wlfc, fifo_id, pktbuf);
if (ret != BCME_OK) {
/* delay q is full, drop this packet */
dhd_wlfc_hanger_poppkt(wlfc->hanger, WLFC_PKTID_HSLOT_GET(status),
&pktbuf, 1);
/* indicate failure and free the packet */
dhd_txcomplete(dhd, pktbuf, FALSE);
PKTFREE(wlfc->osh, pktbuf, TRUE);
}
}
else {
dhd_txcomplete(dhd, pktbuf, TRUE);
/* free the packet */
PKTFREE(wlfc->osh, pktbuf, TRUE);
}
return BCME_OK;
}
static int
dhd_wlfc_fifocreditback_indicate(dhd_pub_t *dhd, uint8* credits)
{
int i;
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
for (i = 0; i < WLFC_CTL_VALUE_LEN_FIFO_CREDITBACK; i++) {
#ifdef PROP_TXSTATUS_DEBUG
wlfc->stats.fifo_credits_back[i] += credits[i];
#endif
/* update FIFO credits */
if (wlfc->proptxstatus_mode == WLFC_FCMODE_EXPLICIT_CREDIT)
{
int lender; /* Note that borrower is i */
/* Return credits to highest priority lender first */
for (lender = AC_COUNT; (lender >= 0) && (credits[i] > 0); lender--) {
if (wlfc->credits_borrowed[i][lender] > 0) {
if (credits[i] >= wlfc->credits_borrowed[i][lender]) {
credits[i] -= wlfc->credits_borrowed[i][lender];
wlfc->FIFO_credit[lender] +=
wlfc->credits_borrowed[i][lender];
wlfc->credits_borrowed[i][lender] = 0;
}
else {
wlfc->credits_borrowed[i][lender] -= credits[i];
wlfc->FIFO_credit[lender] += credits[i];
credits[i] = 0;
}
}
}
/* If we have more credits left over, these must belong to the AC */
if (credits[i] > 0) {
wlfc->FIFO_credit[i] += credits[i];
}
}
}
return BCME_OK;
}
static int
dhd_wlfc_rssi_indicate(dhd_pub_t *dhd, uint8* rssi)
{
(void)dhd;
(void)rssi;
return BCME_OK;
}
static int
dhd_wlfc_mac_table_update(dhd_pub_t *dhd, uint8* value, uint8 type)
{
int rc;
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
wlfc_mac_descriptor_t* table;
uint8 existing_index;
uint8 table_index;
uint8 ifid;
uint8* ea;
WLFC_DBGMESG(("%s(), mac [%02x:%02x:%02x:%02x:%02x:%02x],%s,idx:%d,id:0x%02x\n",
__FUNCTION__, value[2], value[3], value[4], value[5], value[6], value[7],
((type == WLFC_CTL_TYPE_MACDESC_ADD) ? "ADD":"DEL"),
WLFC_MAC_DESC_GET_LOOKUP_INDEX(value[0]), value[0]));
table = wlfc->destination_entries.nodes;
table_index = WLFC_MAC_DESC_GET_LOOKUP_INDEX(value[0]);
ifid = value[1];
ea = &value[2];
if (type == WLFC_CTL_TYPE_MACDESC_ADD) {
existing_index = dhd_wlfc_find_mac_desc_id_from_mac(dhd, &value[2]);
if (existing_index == WLFC_MAC_DESC_ID_INVALID) {
/* this MAC entry does not exist, create one */
if (!table[table_index].occupied) {
table[table_index].mac_handle = value[0];
rc = _dhd_wlfc_mac_entry_update(wlfc, &table[table_index],
eWLFC_MAC_ENTRY_ACTION_ADD, ifid,
wlfc->destination_entries.interfaces[ifid].iftype,
ea);
}
else {
/* the space should have been empty, but it's not */
wlfc->stats.mac_update_failed++;
}
}
else {
/*
there is an existing entry, move it to new index
if necessary.
*/
if (existing_index != table_index) {
/* if we already have an entry, free the old one */
table[existing_index].occupied = 0;
table[existing_index].state = WLFC_STATE_CLOSE;
table[existing_index].requested_credit = 0;
table[existing_index].interface_id = 0;
}
}
}
if (type == WLFC_CTL_TYPE_MACDESC_DEL) {
if (table[table_index].occupied) {
rc = _dhd_wlfc_mac_entry_update(wlfc, &table[table_index],
eWLFC_MAC_ENTRY_ACTION_DEL, ifid,
wlfc->destination_entries.interfaces[ifid].iftype,
ea);
}
else {
/* the space should have been occupied, but it's not */
wlfc->stats.mac_update_failed++;
}
}
return BCME_OK;
}
static int
dhd_wlfc_psmode_update(dhd_pub_t *dhd, uint8* value, uint8 type)
{
/* Handle PS on/off indication */
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
wlfc_mac_descriptor_t* table;
wlfc_mac_descriptor_t* desc;
uint8 mac_handle = value[0];
int i;
table = wlfc->destination_entries.nodes;
desc = &table[WLFC_MAC_DESC_GET_LOOKUP_INDEX(mac_handle)];
if (desc->occupied) {
/* a fresh PS mode should wipe old ps credits? */
desc->requested_credit = 0;
if (type == WLFC_CTL_TYPE_MAC_OPEN) {
desc->state = WLFC_STATE_OPEN;
DHD_WLFC_CTRINC_MAC_OPEN(desc);
}
else {
desc->state = WLFC_STATE_CLOSE;
DHD_WLFC_CTRINC_MAC_CLOSE(desc);
/*
Indicate to firmware if there is any traffic pending.
*/
for (i = AC_BE; i < AC_COUNT; i++) {
_dhd_wlfc_traffic_pending_check(wlfc, desc, i);
}
}
}
else {
wlfc->stats.psmode_update_failed++;
}
return BCME_OK;
}
static int
dhd_wlfc_interface_update(dhd_pub_t *dhd, uint8* value, uint8 type)
{
/* Handle PS on/off indication */
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
wlfc_mac_descriptor_t* table;
uint8 if_id = value[0];
if (if_id < WLFC_MAX_IFNUM) {
table = wlfc->destination_entries.interfaces;
if (table[if_id].occupied) {
if (type == WLFC_CTL_TYPE_INTERFACE_OPEN) {
table[if_id].state = WLFC_STATE_OPEN;
/* WLFC_DBGMESG(("INTERFACE[%d] OPEN\n", if_id)); */
}
else {
table[if_id].state = WLFC_STATE_CLOSE;
/* WLFC_DBGMESG(("INTERFACE[%d] CLOSE\n", if_id)); */
}
return BCME_OK;
}
}
wlfc->stats.interface_update_failed++;
return BCME_OK;
}
static int
dhd_wlfc_credit_request(dhd_pub_t *dhd, uint8* value)
{
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
wlfc_mac_descriptor_t* table;
wlfc_mac_descriptor_t* desc;
uint8 mac_handle;
uint8 credit;
table = wlfc->destination_entries.nodes;
mac_handle = value[1];
credit = value[0];
desc = &table[WLFC_MAC_DESC_GET_LOOKUP_INDEX(mac_handle)];
if (desc->occupied) {
desc->requested_credit = credit;
desc->ac_bitmap = value[2];
}
else {
wlfc->stats.credit_request_failed++;
}
return BCME_OK;
}
static int
dhd_wlfc_packet_request(dhd_pub_t *dhd, uint8* value)
{
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
wlfc_mac_descriptor_t* table;
wlfc_mac_descriptor_t* desc;
uint8 mac_handle;
uint8 packet_count;
table = wlfc->destination_entries.nodes;
mac_handle = value[1];
packet_count = value[0];
desc = &table[WLFC_MAC_DESC_GET_LOOKUP_INDEX(mac_handle)];
if (desc->occupied) {
desc->requested_packet = packet_count;
desc->ac_bitmap = value[2];
}
else {
wlfc->stats.packet_request_failed++;
}
return BCME_OK;
}
static int
dhd_wlfc_parse_header_info(dhd_pub_t *dhd, void* pktbuf, int tlv_hdr_len)
{
uint8 type, len;
uint8* value;
uint8* tmpbuf;
uint16 remainder = tlv_hdr_len;
uint16 processed = 0;
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
tmpbuf = (uint8*)PKTDATA(dhd->osh, pktbuf);
if (remainder) {
while ((processed < (WLFC_MAX_PENDING_DATALEN * 2)) && (remainder > 0)) {
type = tmpbuf[processed];
if (type == WLFC_CTL_TYPE_FILLER) {
remainder -= 1;
processed += 1;
continue;
}
len = tmpbuf[processed + 1];
value = &tmpbuf[processed + 2];
if (remainder < (2 + len))
break;
remainder -= 2 + len;
processed += 2 + len;
if (type == WLFC_CTL_TYPE_TXSTATUS)
dhd_wlfc_txstatus_update(dhd, value);
else if (type == WLFC_CTL_TYPE_FIFO_CREDITBACK)
dhd_wlfc_fifocreditback_indicate(dhd, value);
else if (type == WLFC_CTL_TYPE_RSSI)
dhd_wlfc_rssi_indicate(dhd, value);
else if (type == WLFC_CTL_TYPE_MAC_REQUEST_CREDIT)
dhd_wlfc_credit_request(dhd, value);
else if (type == WLFC_CTL_TYPE_MAC_REQUEST_PACKET)
dhd_wlfc_packet_request(dhd, value);
else if ((type == WLFC_CTL_TYPE_MAC_OPEN) ||
(type == WLFC_CTL_TYPE_MAC_CLOSE))
dhd_wlfc_psmode_update(dhd, value, type);
else if ((type == WLFC_CTL_TYPE_MACDESC_ADD) ||
(type == WLFC_CTL_TYPE_MACDESC_DEL))
dhd_wlfc_mac_table_update(dhd, value, type);
else if ((type == WLFC_CTL_TYPE_INTERFACE_OPEN) ||
(type == WLFC_CTL_TYPE_INTERFACE_CLOSE)) {
dhd_wlfc_interface_update(dhd, value, type);
}
}
if (remainder != 0) {
/* trouble..., something is not right */
wlfc->stats.tlv_parse_failed++;
}
}
return BCME_OK;
}
int
dhd_wlfc_init(dhd_pub_t *dhd)
{
char iovbuf[12]; /* Room for "tlv" + '\0' + parameter */
/* enable all signals & indicate host proptxstatus logic is active */
uint32 tlv = dhd->wlfc_enabled?
WLFC_FLAGS_RSSI_SIGNALS |
WLFC_FLAGS_XONXOFF_SIGNALS |
WLFC_FLAGS_CREDIT_STATUS_SIGNALS |
WLFC_FLAGS_HOST_PROPTXSTATUS_ACTIVE : 0;
/*
try to enable/disable signaling by sending "tlv" iovar. if that fails,
fallback to no flow control? Print a message for now.
*/
/* enable proptxtstatus signaling by default */
bcm_mkiovar("tlv", (char *)&tlv, 4, iovbuf, sizeof(iovbuf));
if (dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0) < 0) {
DHD_ERROR(("dhd_wlfc_init(): failed to enable/disable bdcv2 tlv signaling\n"));
}
else {
/*
Leaving the message for now, it should be removed after a while; once
the tlv situation is stable.
*/
DHD_ERROR(("dhd_wlfc_init(): successfully %s bdcv2 tlv signaling, %d\n",
dhd->wlfc_enabled?"enabled":"disabled", tlv));
}
return BCME_OK;
}
int
dhd_wlfc_enable(dhd_pub_t *dhd)
{
int i;
athost_wl_status_info_t* wlfc;
if (!dhd->wlfc_enabled || dhd->wlfc_state)
return BCME_OK;
/* allocate space to track txstatus propagated from firmware */
dhd->wlfc_state = MALLOC(dhd->osh, sizeof(athost_wl_status_info_t));
if (dhd->wlfc_state == NULL)
return BCME_NOMEM;
/* initialize state space */
wlfc = (athost_wl_status_info_t*)dhd->wlfc_state;
memset(wlfc, 0, sizeof(athost_wl_status_info_t));
/* remember osh & dhdp */
wlfc->osh = dhd->osh;
wlfc->dhdp = dhd;
wlfc->hanger =
dhd_wlfc_hanger_create(dhd->osh, WLFC_HANGER_MAXITEMS);
if (wlfc->hanger == NULL) {
MFREE(dhd->osh, dhd->wlfc_state, sizeof(athost_wl_status_info_t));
dhd->wlfc_state = NULL;
return BCME_NOMEM;
}
/* initialize all interfaces to accept traffic */
for (i = 0; i < WLFC_MAX_IFNUM; i++) {
wlfc->hostif_flow_state[i] = OFF;
}
/*
create the SENDQ containing
sub-queues for all AC precedences + 1 for bc/mc traffic
*/
pktq_init(&wlfc->SENDQ, (AC_COUNT + 1), WLFC_SENDQ_LEN);
wlfc->destination_entries.other.state = WLFC_STATE_OPEN;
/* bc/mc FIFO is always open [credit aside], i.e. b[5] */
wlfc->destination_entries.other.ac_bitmap = 0x1f;
wlfc->destination_entries.other.interface_id = 0;
wlfc->proptxstatus_mode = WLFC_FCMODE_EXPLICIT_CREDIT;
wlfc->allow_credit_borrow = TRUE;
wlfc->borrow_defer_timestamp = 0;
return BCME_OK;
}
/* release all packet resources */
void
dhd_wlfc_cleanup(dhd_pub_t *dhd)
{
int i;
int total_entries;
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
wlfc_mac_descriptor_t* table;
wlfc_hanger_t* h;
if (dhd->wlfc_state == NULL)
return;
total_entries = sizeof(wlfc->destination_entries)/sizeof(wlfc_mac_descriptor_t);
/* search all entries, include nodes as well as interfaces */
table = (wlfc_mac_descriptor_t*)&wlfc->destination_entries;
for (i = 0; i < total_entries; i++) {
if (table[i].occupied) {
if (table[i].psq.len) {
WLFC_DBGMESG(("%s(): DELAYQ[%d].len = %d\n",
__FUNCTION__, i, table[i].psq.len));
/* release packets held in DELAYQ */
pktq_flush(wlfc->osh, &table[i].psq, TRUE, NULL, 0);
}
table[i].occupied = 0;
}
}
/* release packets held in SENDQ */
if (wlfc->SENDQ.len)
pktq_flush(wlfc->osh, &wlfc->SENDQ, TRUE, NULL, 0);
/* any in the hanger? */
h = (wlfc_hanger_t*)wlfc->hanger;
for (i = 0; i < h->max_items; i++) {
if (h->items[i].state == WLFC_HANGER_ITEM_STATE_INUSE) {
PKTFREE(wlfc->osh, h->items[i].pkt, TRUE);
}
}
return;
}
void
dhd_wlfc_deinit(dhd_pub_t *dhd)
{
/* cleanup all psq related resources */
athost_wl_status_info_t* wlfc = (athost_wl_status_info_t*)
dhd->wlfc_state;
if (dhd->wlfc_state == NULL)
return;
#ifdef PROP_TXSTATUS_DEBUG
{
int i;
wlfc_hanger_t* h = (wlfc_hanger_t*)wlfc->hanger;
for (i = 0; i < h->max_items; i++) {
if (h->items[i].state == WLFC_HANGER_ITEM_STATE_INUSE) {
WLFC_DBGMESG(("%s() pkt[%d] = 0x%p, FIFO_credit_used:%d\n",
__FUNCTION__, i, h->items[i].pkt,
DHD_PKTTAG_CREDITCHECK(PKTTAG(h->items[i].pkt))));
}
}
}
#endif
/* delete hanger */
dhd_wlfc_hanger_delete(dhd->osh, wlfc->hanger);
/* free top structure */
MFREE(dhd->osh, dhd->wlfc_state, sizeof(athost_wl_status_info_t));
dhd->wlfc_state = NULL;
return;
}
#endif /* PROP_TXSTATUS */
void
dhd_prot_dump(dhd_pub_t *dhdp, struct bcmstrbuf *strbuf)
{
bcm_bprintf(strbuf, "Protocol CDC: reqid %d\n", dhdp->prot->reqid);
#ifdef PROP_TXSTATUS
if (dhdp->wlfc_state)
dhd_wlfc_dump(dhdp, strbuf);
#endif
}
void
dhd_prot_hdrpush(dhd_pub_t *dhd, int ifidx, void *pktbuf)
{
#ifdef BDC
struct bdc_header *h;
#endif /* BDC */
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
#ifdef BDC
/* Push BDC header used to convey priority for buses that don't */
PKTPUSH(dhd->osh, pktbuf, BDC_HEADER_LEN);
h = (struct bdc_header *)PKTDATA(dhd->osh, pktbuf);
h->flags = (BDC_PROTO_VER << BDC_FLAG_VER_SHIFT);
if (PKTSUMNEEDED(pktbuf))
h->flags |= BDC_FLAG_SUM_NEEDED;
h->priority = (PKTPRIO(pktbuf) & BDC_PRIORITY_MASK);
h->flags2 = 0;
h->dataOffset = 0;
#endif /* BDC */
BDC_SET_IF_IDX(h, ifidx);
}
int
dhd_prot_hdrpull(dhd_pub_t *dhd, int *ifidx, void *pktbuf)
{
#ifdef BDC
struct bdc_header *h;
#endif
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
#ifdef BDC
/* Pop BDC header used to convey priority for buses that don't */
if (PKTLEN(dhd->osh, pktbuf) < BDC_HEADER_LEN) {
DHD_ERROR(("%s: rx data too short (%d < %d)\n", __FUNCTION__,
PKTLEN(dhd->osh, pktbuf), BDC_HEADER_LEN));
return BCME_ERROR;
}
h = (struct bdc_header *)PKTDATA(dhd->osh, pktbuf);
if ((*ifidx = BDC_GET_IF_IDX(h)) >= DHD_MAX_IFS) {
DHD_ERROR(("%s: rx data ifnum out of range (%d)\n",
__FUNCTION__, *ifidx));
return BCME_ERROR;
}
if (((h->flags & BDC_FLAG_VER_MASK) >> BDC_FLAG_VER_SHIFT) != BDC_PROTO_VER) {
DHD_ERROR(("%s: non-BDC packet received, flags = 0x%x\n",
dhd_ifname(dhd, *ifidx), h->flags));
if (((h->flags & BDC_FLAG_VER_MASK) >> BDC_FLAG_VER_SHIFT) == BDC_PROTO_VER_1)
h->dataOffset = 0;
else
return BCME_ERROR;
}
if (h->flags & BDC_FLAG_SUM_GOOD) {
DHD_INFO(("%s: BDC packet received with good rx-csum, flags 0x%x\n",
dhd_ifname(dhd, *ifidx), h->flags));
PKTSETSUMGOOD(pktbuf, TRUE);
}
PKTSETPRIO(pktbuf, (h->priority & BDC_PRIORITY_MASK));
PKTPULL(dhd->osh, pktbuf, BDC_HEADER_LEN);
#endif /* BDC */
if (PKTLEN(dhd->osh, pktbuf) < (uint32) (h->dataOffset << 2)) {
DHD_ERROR(("%s: rx data too short (%d < %d)\n", __FUNCTION__,
PKTLEN(dhd->osh, pktbuf), (h->dataOffset * 4)));
return BCME_ERROR;
}
#ifdef PROP_TXSTATUS
if (dhd->wlfc_state &&
((athost_wl_status_info_t*)dhd->wlfc_state)->proptxstatus_mode
!= WLFC_FCMODE_NONE &&
(!DHD_PKTTAG_PKTDIR(PKTTAG(pktbuf)))) {
/*
- parse txstatus only for packets that came from the firmware
*/
dhd_os_wlfc_block(dhd);
dhd_wlfc_parse_header_info(dhd, pktbuf, (h->dataOffset << 2));
((athost_wl_status_info_t*)dhd->wlfc_state)->stats.dhd_hdrpulls++;
dhd_wlfc_commit_packets(dhd->wlfc_state, (f_commitpkt_t)dhd_bus_txdata,
(void *)dhd->bus);
dhd_os_wlfc_unblock(dhd);
}
#endif /* PROP_TXSTATUS */
PKTPULL(dhd->osh, pktbuf, (h->dataOffset << 2));
return 0;
}
int
dhd_prot_attach(dhd_pub_t *dhd)
{
dhd_prot_t *cdc;
if (!(cdc = (dhd_prot_t *)DHD_OS_PREALLOC(dhd->osh, DHD_PREALLOC_PROT,
sizeof(dhd_prot_t)))) {
DHD_ERROR(("%s: kmalloc failed\n", __FUNCTION__));
goto fail;
}
memset(cdc, 0, sizeof(dhd_prot_t));
/* ensure that the msg buf directly follows the cdc msg struct */
if ((uintptr)(&cdc->msg + 1) != (uintptr)cdc->buf) {
DHD_ERROR(("dhd_prot_t is not correctly defined\n"));
goto fail;
}
dhd->prot = cdc;
#ifdef BDC
dhd->hdrlen += BDC_HEADER_LEN;
#endif
dhd->maxctl = WLC_IOCTL_MAXLEN + sizeof(cdc_ioctl_t) + ROUND_UP_MARGIN;
return 0;
fail:
#ifndef DHD_USE_STATIC_BUF
if (cdc != NULL)
MFREE(dhd->osh, cdc, sizeof(dhd_prot_t));
#endif
return BCME_NOMEM;
}
/* ~NOTE~ What if another thread is waiting on the semaphore? Holding it? */
void
dhd_prot_detach(dhd_pub_t *dhd)
{
#ifdef PROP_TXSTATUS
dhd_wlfc_deinit(dhd);
#endif
#ifndef DHD_USE_STATIC_BUF
MFREE(dhd->osh, dhd->prot, sizeof(dhd_prot_t));
#endif
dhd->prot = NULL;
}
void
dhd_prot_dstats(dhd_pub_t *dhd)
{
/* No stats from dongle added yet, copy bus stats */
dhd->dstats.tx_packets = dhd->tx_packets;
dhd->dstats.tx_errors = dhd->tx_errors;
dhd->dstats.rx_packets = dhd->rx_packets;
dhd->dstats.rx_errors = dhd->rx_errors;
dhd->dstats.rx_dropped = dhd->rx_dropped;
dhd->dstats.multicast = dhd->rx_multicast;
return;
}
int
dhd_prot_init(dhd_pub_t *dhd)
{
int ret = 0;
wlc_rev_info_t revinfo;
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
/* Get the device rev info */
memset(&revinfo, 0, sizeof(revinfo));
ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_REVINFO, &revinfo, sizeof(revinfo), FALSE, 0);
if (ret < 0)
goto done;
#ifdef PROP_TXSTATUS
ret = dhd_wlfc_init(dhd);
#endif
#if !defined(WL_CFG80211)
ret = dhd_preinit_ioctls(dhd);
#endif /* WL_CFG80211 */
/* Always assumes wl for now */
dhd->iswl = TRUE;
done:
return ret;
}
void
dhd_prot_stop(dhd_pub_t *dhd)
{
/* Nothing to do for CDC */
}
| gpl-2.0 |
ion-storm/Unleashed-Flo-Kernel | sound/core/control.c | 707 | 45199 | /*
* Routines for driver control interface
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* 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/threads.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/time.h>
#include <sound/core.h>
#include <sound/minors.h>
#include <sound/info.h>
#include <sound/control.h>
/* max number of user-defined controls */
#define MAX_USER_CONTROLS 32
#define MAX_CONTROL_COUNT 1028
struct snd_kctl_ioctl {
struct list_head list; /* list of all ioctls */
snd_kctl_ioctl_func_t fioctl;
};
static DECLARE_RWSEM(snd_ioctl_rwsem);
static LIST_HEAD(snd_control_ioctls);
#ifdef CONFIG_COMPAT
static LIST_HEAD(snd_control_compat_ioctls);
#endif
static int snd_ctl_open(struct inode *inode, struct file *file)
{
unsigned long flags;
struct snd_card *card;
struct snd_ctl_file *ctl;
int err;
err = nonseekable_open(inode, file);
if (err < 0)
return err;
card = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_CONTROL);
if (!card) {
err = -ENODEV;
goto __error1;
}
err = snd_card_file_add(card, file);
if (err < 0) {
err = -ENODEV;
goto __error1;
}
if (!try_module_get(card->module)) {
err = -EFAULT;
goto __error2;
}
ctl = kzalloc(sizeof(*ctl), GFP_KERNEL);
if (ctl == NULL) {
err = -ENOMEM;
goto __error;
}
INIT_LIST_HEAD(&ctl->events);
init_waitqueue_head(&ctl->change_sleep);
spin_lock_init(&ctl->read_lock);
ctl->card = card;
ctl->prefer_pcm_subdevice = -1;
ctl->prefer_rawmidi_subdevice = -1;
ctl->pid = get_pid(task_pid(current));
file->private_data = ctl;
write_lock_irqsave(&card->ctl_files_rwlock, flags);
list_add_tail(&ctl->list, &card->ctl_files);
write_unlock_irqrestore(&card->ctl_files_rwlock, flags);
snd_card_unref(card);
return 0;
__error:
module_put(card->module);
__error2:
snd_card_file_remove(card, file);
__error1:
if (card)
snd_card_unref(card);
return err;
}
static void snd_ctl_empty_read_queue(struct snd_ctl_file * ctl)
{
unsigned long flags;
struct snd_kctl_event *cread;
spin_lock_irqsave(&ctl->read_lock, flags);
while (!list_empty(&ctl->events)) {
cread = snd_kctl_event(ctl->events.next);
list_del(&cread->list);
kfree(cread);
}
spin_unlock_irqrestore(&ctl->read_lock, flags);
}
static int snd_ctl_release(struct inode *inode, struct file *file)
{
unsigned long flags;
struct snd_card *card;
struct snd_ctl_file *ctl;
struct snd_kcontrol *control;
unsigned int idx;
ctl = file->private_data;
file->private_data = NULL;
card = ctl->card;
write_lock_irqsave(&card->ctl_files_rwlock, flags);
list_del(&ctl->list);
write_unlock_irqrestore(&card->ctl_files_rwlock, flags);
down_write(&card->controls_rwsem);
list_for_each_entry(control, &card->controls, list)
for (idx = 0; idx < control->count; idx++)
if (control->vd[idx].owner == ctl)
control->vd[idx].owner = NULL;
up_write(&card->controls_rwsem);
snd_ctl_empty_read_queue(ctl);
put_pid(ctl->pid);
kfree(ctl);
module_put(card->module);
snd_card_file_remove(card, file);
return 0;
}
void snd_ctl_notify(struct snd_card *card, unsigned int mask,
struct snd_ctl_elem_id *id)
{
unsigned long flags;
struct snd_ctl_file *ctl;
struct snd_kctl_event *ev;
if (snd_BUG_ON(!card || !id))
return;
read_lock(&card->ctl_files_rwlock);
#if defined(CONFIG_SND_MIXER_OSS) || defined(CONFIG_SND_MIXER_OSS_MODULE)
card->mixer_oss_change_count++;
#endif
list_for_each_entry(ctl, &card->ctl_files, list) {
if (!ctl->subscribed)
continue;
spin_lock_irqsave(&ctl->read_lock, flags);
list_for_each_entry(ev, &ctl->events, list) {
if (ev->id.numid == id->numid) {
ev->mask |= mask;
goto _found;
}
}
ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
if (ev) {
ev->id = *id;
ev->mask = mask;
list_add_tail(&ev->list, &ctl->events);
} else {
snd_printk(KERN_ERR "No memory available to allocate event\n");
}
_found:
wake_up(&ctl->change_sleep);
spin_unlock_irqrestore(&ctl->read_lock, flags);
kill_fasync(&ctl->fasync, SIGIO, POLL_IN);
}
read_unlock(&card->ctl_files_rwlock);
}
EXPORT_SYMBOL(snd_ctl_notify);
/**
* snd_ctl_new - create a control instance from the template
* @control: the control template
* @access: the default control access
*
* Allocates a new struct snd_kcontrol instance and copies the given template
* to the new instance. It does not copy volatile data (access).
*
* Returns the pointer of the new instance, or NULL on failure.
*/
static struct snd_kcontrol *snd_ctl_new(struct snd_kcontrol *control,
unsigned int access)
{
struct snd_kcontrol *kctl;
unsigned int idx;
if (snd_BUG_ON(!control || !control->count))
return NULL;
if (control->count > MAX_CONTROL_COUNT)
return NULL;
kctl = kzalloc(sizeof(*kctl) + sizeof(struct snd_kcontrol_volatile) * control->count, GFP_KERNEL);
if (kctl == NULL) {
snd_printk(KERN_ERR "Cannot allocate control instance\n");
return NULL;
}
*kctl = *control;
for (idx = 0; idx < kctl->count; idx++)
kctl->vd[idx].access = access;
return kctl;
}
/**
* snd_ctl_new1 - create a control instance from the template
* @ncontrol: the initialization record
* @private_data: the private data to set
*
* Allocates a new struct snd_kcontrol instance and initialize from the given
* template. When the access field of ncontrol is 0, it's assumed as
* READWRITE access. When the count field is 0, it's assumes as one.
*
* Returns the pointer of the newly generated instance, or NULL on failure.
*/
struct snd_kcontrol *snd_ctl_new1(const struct snd_kcontrol_new *ncontrol,
void *private_data)
{
struct snd_kcontrol kctl;
unsigned int access;
if (snd_BUG_ON(!ncontrol || !ncontrol->info))
return NULL;
memset(&kctl, 0, sizeof(kctl));
kctl.id.iface = ncontrol->iface;
kctl.id.device = ncontrol->device;
kctl.id.subdevice = ncontrol->subdevice;
if (ncontrol->name) {
strlcpy(kctl.id.name, ncontrol->name, sizeof(kctl.id.name));
if (strcmp(ncontrol->name, kctl.id.name) != 0)
snd_printk(KERN_WARNING
"Control name '%s' truncated to '%s'\n",
ncontrol->name, kctl.id.name);
}
kctl.id.index = ncontrol->index;
kctl.count = ncontrol->count ? ncontrol->count : 1;
access = ncontrol->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE :
(ncontrol->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE|
SNDRV_CTL_ELEM_ACCESS_INACTIVE|
SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE|
SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND|
SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK));
kctl.info = ncontrol->info;
kctl.get = ncontrol->get;
kctl.put = ncontrol->put;
kctl.tlv.p = ncontrol->tlv.p;
kctl.private_value = ncontrol->private_value;
kctl.private_data = private_data;
return snd_ctl_new(&kctl, access);
}
EXPORT_SYMBOL(snd_ctl_new1);
/**
* snd_ctl_free_one - release the control instance
* @kcontrol: the control instance
*
* Releases the control instance created via snd_ctl_new()
* or snd_ctl_new1().
* Don't call this after the control was added to the card.
*/
void snd_ctl_free_one(struct snd_kcontrol *kcontrol)
{
if (kcontrol) {
if (kcontrol->private_free)
kcontrol->private_free(kcontrol);
kfree(kcontrol);
}
}
EXPORT_SYMBOL(snd_ctl_free_one);
static bool snd_ctl_remove_numid_conflict(struct snd_card *card,
unsigned int count)
{
struct snd_kcontrol *kctl;
list_for_each_entry(kctl, &card->controls, list) {
if (kctl->id.numid < card->last_numid + 1 + count &&
kctl->id.numid + kctl->count > card->last_numid + 1) {
card->last_numid = kctl->id.numid + kctl->count - 1;
return true;
}
}
return false;
}
static int snd_ctl_find_hole(struct snd_card *card, unsigned int count)
{
unsigned int iter = 100000;
while (snd_ctl_remove_numid_conflict(card, count)) {
if (--iter == 0) {
/* this situation is very unlikely */
snd_printk(KERN_ERR "unable to allocate new control numid\n");
return -ENOMEM;
}
}
return 0;
}
/**
* snd_ctl_add - add the control instance to the card
* @card: the card instance
* @kcontrol: the control instance to add
*
* Adds the control instance created via snd_ctl_new() or
* snd_ctl_new1() to the given card. Assigns also an unique
* numid used for fast search.
*
* Returns zero if successful, or a negative error code on failure.
*
* It frees automatically the control which cannot be added.
*/
int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol)
{
struct snd_ctl_elem_id id;
unsigned int idx;
int err = -EINVAL;
if (! kcontrol)
return err;
if (snd_BUG_ON(!card || !kcontrol->info))
goto error;
id = kcontrol->id;
down_write(&card->controls_rwsem);
if (snd_ctl_find_id(card, &id)) {
up_write(&card->controls_rwsem);
snd_printd(KERN_ERR "control %i:%i:%i:%s:%i is already present\n",
id.iface,
id.device,
id.subdevice,
id.name,
id.index);
err = -EBUSY;
goto error;
}
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
err = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return err;
}
EXPORT_SYMBOL(snd_ctl_add);
/**
* snd_ctl_replace - replace the control instance of the card
* @card: the card instance
* @kcontrol: the control instance to replace
* @add_on_replace: add the control if not already added
*
* Replaces the given control. If the given control does not exist
* and the add_on_replace flag is set, the control is added. If the
* control exists, it is destroyed first.
*
* Returns zero if successful, or a negative error code on failure.
*
* It frees automatically the control which cannot be added or replaced.
*/
int snd_ctl_replace(struct snd_card *card, struct snd_kcontrol *kcontrol,
bool add_on_replace)
{
struct snd_ctl_elem_id id;
unsigned int idx;
struct snd_kcontrol *old;
int ret;
if (!kcontrol)
return -EINVAL;
if (snd_BUG_ON(!card || !kcontrol->info)) {
ret = -EINVAL;
goto error;
}
id = kcontrol->id;
down_write(&card->controls_rwsem);
old = snd_ctl_find_id(card, &id);
if (!old) {
if (add_on_replace)
goto add;
up_write(&card->controls_rwsem);
ret = -EINVAL;
goto error;
}
ret = snd_ctl_remove(card, old);
if (ret < 0) {
up_write(&card->controls_rwsem);
goto error;
}
add:
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
ret = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return ret;
}
EXPORT_SYMBOL(snd_ctl_replace);
/**
* snd_ctl_remove - remove the control from the card and release it
* @card: the card instance
* @kcontrol: the control instance to remove
*
* Removes the control from the card and then releases the instance.
* You don't need to call snd_ctl_free_one(). You must be in
* the write lock - down_write(&card->controls_rwsem).
*
* Returns 0 if successful, or a negative error code on failure.
*/
int snd_ctl_remove(struct snd_card *card, struct snd_kcontrol *kcontrol)
{
struct snd_ctl_elem_id id;
unsigned int idx;
if (snd_BUG_ON(!card || !kcontrol))
return -EINVAL;
list_del(&kcontrol->list);
card->controls_count -= kcontrol->count;
id = kcontrol->id;
for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_REMOVE, &id);
snd_ctl_free_one(kcontrol);
return 0;
}
EXPORT_SYMBOL(snd_ctl_remove);
/**
* snd_ctl_remove_id - remove the control of the given id and release it
* @card: the card instance
* @id: the control id to remove
*
* Finds the control instance with the given id, removes it from the
* card list and releases it.
*
* Returns 0 if successful, or a negative error code on failure.
*/
int snd_ctl_remove_id(struct snd_card *card, struct snd_ctl_elem_id *id)
{
struct snd_kcontrol *kctl;
int ret;
down_write(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, id);
if (kctl == NULL) {
up_write(&card->controls_rwsem);
return -ENOENT;
}
ret = snd_ctl_remove(card, kctl);
up_write(&card->controls_rwsem);
return ret;
}
EXPORT_SYMBOL(snd_ctl_remove_id);
/**
* snd_ctl_remove_user_ctl - remove and release the unlocked user control
* @file: active control handle
* @id: the control id to remove
*
* Finds the control instance with the given id, removes it from the
* card list and releases it.
*
* Returns 0 if successful, or a negative error code on failure.
*/
static int snd_ctl_remove_user_ctl(struct snd_ctl_file * file,
struct snd_ctl_elem_id *id)
{
struct snd_card *card = file->card;
struct snd_kcontrol *kctl;
int idx, ret;
down_write(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, id);
if (kctl == NULL) {
ret = -ENOENT;
goto error;
}
if (!(kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_USER)) {
ret = -EINVAL;
goto error;
}
for (idx = 0; idx < kctl->count; idx++)
if (kctl->vd[idx].owner != NULL && kctl->vd[idx].owner != file) {
ret = -EBUSY;
goto error;
}
ret = snd_ctl_remove(card, kctl);
if (ret < 0)
goto error;
card->user_ctl_count--;
error:
up_write(&card->controls_rwsem);
return ret;
}
/**
* snd_ctl_activate_id - activate/inactivate the control of the given id
* @card: the card instance
* @id: the control id to activate/inactivate
* @active: non-zero to activate
*
* Finds the control instance with the given id, and activate or
* inactivate the control together with notification, if changed.
*
* Returns 0 if unchanged, 1 if changed, or a negative error code on failure.
*/
int snd_ctl_activate_id(struct snd_card *card, struct snd_ctl_elem_id *id,
int active)
{
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int ret;
down_write(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, id);
if (kctl == NULL) {
ret = -ENOENT;
goto unlock;
}
index_offset = snd_ctl_get_ioff(kctl, &kctl->id);
vd = &kctl->vd[index_offset];
ret = 0;
if (active) {
if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_INACTIVE))
goto unlock;
vd->access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
} else {
if (vd->access & SNDRV_CTL_ELEM_ACCESS_INACTIVE)
goto unlock;
vd->access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
}
ret = 1;
unlock:
up_write(&card->controls_rwsem);
if (ret > 0)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_INFO, id);
return ret;
}
EXPORT_SYMBOL_GPL(snd_ctl_activate_id);
/**
* snd_ctl_rename_id - replace the id of a control on the card
* @card: the card instance
* @src_id: the old id
* @dst_id: the new id
*
* Finds the control with the old id from the card, and replaces the
* id with the new one.
*
* Returns zero if successful, or a negative error code on failure.
*/
int snd_ctl_rename_id(struct snd_card *card, struct snd_ctl_elem_id *src_id,
struct snd_ctl_elem_id *dst_id)
{
struct snd_kcontrol *kctl;
down_write(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, src_id);
if (kctl == NULL) {
up_write(&card->controls_rwsem);
return -ENOENT;
}
kctl->id = *dst_id;
kctl->id.numid = card->last_numid + 1;
card->last_numid += kctl->count;
up_write(&card->controls_rwsem);
return 0;
}
EXPORT_SYMBOL(snd_ctl_rename_id);
/**
* snd_ctl_find_numid - find the control instance with the given number-id
* @card: the card instance
* @numid: the number-id to search
*
* Finds the control instance with the given number-id from the card.
*
* Returns the pointer of the instance if found, or NULL if not.
*
* The caller must down card->controls_rwsem before calling this function
* (if the race condition can happen).
*/
struct snd_kcontrol *snd_ctl_find_numid(struct snd_card *card, unsigned int numid)
{
struct snd_kcontrol *kctl;
if (snd_BUG_ON(!card || !numid))
return NULL;
list_for_each_entry(kctl, &card->controls, list) {
if (kctl->id.numid <= numid && kctl->id.numid + kctl->count > numid)
return kctl;
}
return NULL;
}
EXPORT_SYMBOL(snd_ctl_find_numid);
/**
* snd_ctl_find_id - find the control instance with the given id
* @card: the card instance
* @id: the id to search
*
* Finds the control instance with the given id from the card.
*
* Returns the pointer of the instance if found, or NULL if not.
*
* The caller must down card->controls_rwsem before calling this function
* (if the race condition can happen).
*/
struct snd_kcontrol *snd_ctl_find_id(struct snd_card *card,
struct snd_ctl_elem_id *id)
{
struct snd_kcontrol *kctl;
if (snd_BUG_ON(!card || !id))
return NULL;
if (id->numid != 0)
return snd_ctl_find_numid(card, id->numid);
list_for_each_entry(kctl, &card->controls, list) {
if (kctl->id.iface != id->iface)
continue;
if (kctl->id.device != id->device)
continue;
if (kctl->id.subdevice != id->subdevice)
continue;
if (strncmp(kctl->id.name, id->name, sizeof(kctl->id.name)))
continue;
if (kctl->id.index > id->index)
continue;
if (kctl->id.index + kctl->count <= id->index)
continue;
return kctl;
}
return NULL;
}
EXPORT_SYMBOL(snd_ctl_find_id);
static int snd_ctl_card_info(struct snd_card *card, struct snd_ctl_file * ctl,
unsigned int cmd, void __user *arg)
{
struct snd_ctl_card_info *info;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (! info)
return -ENOMEM;
down_read(&snd_ioctl_rwsem);
info->card = card->number;
strlcpy(info->id, card->id, sizeof(info->id));
strlcpy(info->driver, card->driver, sizeof(info->driver));
strlcpy(info->name, card->shortname, sizeof(info->name));
strlcpy(info->longname, card->longname, sizeof(info->longname));
strlcpy(info->mixername, card->mixername, sizeof(info->mixername));
strlcpy(info->components, card->components, sizeof(info->components));
up_read(&snd_ioctl_rwsem);
if (copy_to_user(arg, info, sizeof(struct snd_ctl_card_info))) {
kfree(info);
return -EFAULT;
}
kfree(info);
return 0;
}
static int snd_ctl_elem_list(struct snd_card *card,
struct snd_ctl_elem_list __user *_list)
{
struct list_head *plist;
struct snd_ctl_elem_list list;
struct snd_kcontrol *kctl;
struct snd_ctl_elem_id *dst, *id;
unsigned int offset, space, jidx;
if (copy_from_user(&list, _list, sizeof(list)))
return -EFAULT;
offset = list.offset;
space = list.space;
/* try limit maximum space */
if (space > 16384)
return -ENOMEM;
if (space > 0) {
/* allocate temporary buffer for atomic operation */
dst = vmalloc(space * sizeof(struct snd_ctl_elem_id));
if (dst == NULL)
return -ENOMEM;
down_read(&card->controls_rwsem);
list.count = card->controls_count;
plist = card->controls.next;
while (plist != &card->controls) {
if (offset == 0)
break;
kctl = snd_kcontrol(plist);
if (offset < kctl->count)
break;
offset -= kctl->count;
plist = plist->next;
}
list.used = 0;
id = dst;
while (space > 0 && plist != &card->controls) {
kctl = snd_kcontrol(plist);
for (jidx = offset; space > 0 && jidx < kctl->count; jidx++) {
snd_ctl_build_ioff(id, kctl, jidx);
id++;
space--;
list.used++;
}
plist = plist->next;
offset = 0;
}
up_read(&card->controls_rwsem);
if (list.used > 0 &&
copy_to_user(list.pids, dst,
list.used * sizeof(struct snd_ctl_elem_id))) {
vfree(dst);
return -EFAULT;
}
vfree(dst);
} else {
down_read(&card->controls_rwsem);
list.count = card->controls_count;
up_read(&card->controls_rwsem);
}
if (copy_to_user(_list, &list, sizeof(list)))
return -EFAULT;
return 0;
}
static int snd_ctl_elem_info(struct snd_ctl_file *ctl,
struct snd_ctl_elem_info *info)
{
struct snd_card *card = ctl->card;
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int result;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &info->id);
if (kctl == NULL) {
up_read(&card->controls_rwsem);
return -ENOENT;
}
#ifdef CONFIG_SND_DEBUG
info->access = 0;
#endif
result = kctl->info(kctl, info);
if (result >= 0) {
snd_BUG_ON(info->access);
index_offset = snd_ctl_get_ioff(kctl, &info->id);
vd = &kctl->vd[index_offset];
snd_ctl_build_ioff(&info->id, kctl, index_offset);
info->access = vd->access;
if (vd->owner) {
info->access |= SNDRV_CTL_ELEM_ACCESS_LOCK;
if (vd->owner == ctl)
info->access |= SNDRV_CTL_ELEM_ACCESS_OWNER;
info->owner = pid_vnr(vd->owner->pid);
} else {
info->owner = -1;
}
}
up_read(&card->controls_rwsem);
return result;
}
static int snd_ctl_elem_info_user(struct snd_ctl_file *ctl,
struct snd_ctl_elem_info __user *_info)
{
struct snd_ctl_elem_info info;
int result;
if (copy_from_user(&info, _info, sizeof(info)))
return -EFAULT;
snd_power_lock(ctl->card);
result = snd_power_wait(ctl->card, SNDRV_CTL_POWER_D0);
if (result >= 0)
result = snd_ctl_elem_info(ctl, &info);
snd_power_unlock(ctl->card);
if (result >= 0)
if (copy_to_user(_info, &info, sizeof(info)))
return -EFAULT;
return result;
}
static int snd_ctl_elem_read(struct snd_card *card,
struct snd_ctl_elem_value *control)
{
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int result;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &control->id);
if (kctl == NULL) {
result = -ENOENT;
} else {
index_offset = snd_ctl_get_ioff(kctl, &control->id);
vd = &kctl->vd[index_offset];
if ((vd->access & SNDRV_CTL_ELEM_ACCESS_READ) &&
kctl->get != NULL) {
snd_ctl_build_ioff(&control->id, kctl, index_offset);
result = kctl->get(kctl, control);
} else
result = -EPERM;
}
up_read(&card->controls_rwsem);
return result;
}
static int snd_ctl_elem_read_user(struct snd_card *card,
struct snd_ctl_elem_value __user *_control)
{
struct snd_ctl_elem_value *control;
int result;
control = memdup_user(_control, sizeof(*control));
if (IS_ERR(control))
return PTR_ERR(control);
snd_power_lock(card);
result = snd_power_wait(card, SNDRV_CTL_POWER_D0);
if (result >= 0)
result = snd_ctl_elem_read(card, control);
snd_power_unlock(card);
if (result >= 0)
if (copy_to_user(_control, control, sizeof(*control)))
result = -EFAULT;
kfree(control);
return result;
}
static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
struct snd_ctl_elem_value *control)
{
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int result;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &control->id);
if (kctl == NULL) {
result = -ENOENT;
} else {
index_offset = snd_ctl_get_ioff(kctl, &control->id);
vd = &kctl->vd[index_offset];
if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) ||
kctl->put == NULL ||
(file && vd->owner && vd->owner != file)) {
result = -EPERM;
} else {
snd_ctl_build_ioff(&control->id, kctl, index_offset);
result = kctl->put(kctl, control);
}
if (result > 0) {
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&control->id);
return 0;
}
}
up_read(&card->controls_rwsem);
return result;
}
static int snd_ctl_elem_write_user(struct snd_ctl_file *file,
struct snd_ctl_elem_value __user *_control)
{
struct snd_ctl_elem_value *control;
struct snd_card *card;
int result;
control = memdup_user(_control, sizeof(*control));
if (IS_ERR(control))
return PTR_ERR(control);
card = file->card;
snd_power_lock(card);
result = snd_power_wait(card, SNDRV_CTL_POWER_D0);
if (result >= 0)
result = snd_ctl_elem_write(card, file, control);
snd_power_unlock(card);
if (result >= 0)
if (copy_to_user(_control, control, sizeof(*control)))
result = -EFAULT;
kfree(control);
return result;
}
static int snd_ctl_elem_lock(struct snd_ctl_file *file,
struct snd_ctl_elem_id __user *_id)
{
struct snd_card *card = file->card;
struct snd_ctl_elem_id id;
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
int result;
if (copy_from_user(&id, _id, sizeof(id)))
return -EFAULT;
down_write(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &id);
if (kctl == NULL) {
result = -ENOENT;
} else {
vd = &kctl->vd[snd_ctl_get_ioff(kctl, &id)];
if (vd->owner != NULL)
result = -EBUSY;
else {
vd->owner = file;
result = 0;
}
}
up_write(&card->controls_rwsem);
return result;
}
static int snd_ctl_elem_unlock(struct snd_ctl_file *file,
struct snd_ctl_elem_id __user *_id)
{
struct snd_card *card = file->card;
struct snd_ctl_elem_id id;
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
int result;
if (copy_from_user(&id, _id, sizeof(id)))
return -EFAULT;
down_write(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &id);
if (kctl == NULL) {
result = -ENOENT;
} else {
vd = &kctl->vd[snd_ctl_get_ioff(kctl, &id)];
if (vd->owner == NULL)
result = -EINVAL;
else if (vd->owner != file)
result = -EPERM;
else {
vd->owner = NULL;
result = 0;
}
}
up_write(&card->controls_rwsem);
return result;
}
struct user_element {
struct snd_ctl_elem_info info;
void *elem_data; /* element data */
unsigned long elem_data_size; /* size of element data in bytes */
void *tlv_data; /* TLV data */
unsigned long tlv_data_size; /* TLV data size */
void *priv_data; /* private data (like strings for enumerated type) */
};
static int snd_ctl_elem_user_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct user_element *ue = kcontrol->private_data;
*uinfo = ue->info;
return 0;
}
static int snd_ctl_elem_user_enum_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct user_element *ue = kcontrol->private_data;
const char *names;
unsigned int item;
item = uinfo->value.enumerated.item;
*uinfo = ue->info;
item = min(item, uinfo->value.enumerated.items - 1);
uinfo->value.enumerated.item = item;
names = ue->priv_data;
for (; item > 0; --item)
names += strlen(names) + 1;
strcpy(uinfo->value.enumerated.name, names);
return 0;
}
static int snd_ctl_elem_user_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct user_element *ue = kcontrol->private_data;
memcpy(&ucontrol->value, ue->elem_data, ue->elem_data_size);
return 0;
}
static int snd_ctl_elem_user_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change;
struct user_element *ue = kcontrol->private_data;
change = memcmp(&ucontrol->value, ue->elem_data, ue->elem_data_size) != 0;
if (change)
memcpy(ue->elem_data, &ucontrol->value, ue->elem_data_size);
return change;
}
static int snd_ctl_elem_user_tlv(struct snd_kcontrol *kcontrol,
int op_flag,
unsigned int size,
unsigned int __user *tlv)
{
struct user_element *ue = kcontrol->private_data;
int change = 0;
void *new_data;
if (op_flag > 0) {
if (size > 1024 * 128) /* sane value */
return -EINVAL;
new_data = memdup_user(tlv, size);
if (IS_ERR(new_data))
return PTR_ERR(new_data);
change = ue->tlv_data_size != size;
if (!change)
change = memcmp(ue->tlv_data, new_data, size);
kfree(ue->tlv_data);
ue->tlv_data = new_data;
ue->tlv_data_size = size;
} else {
if (! ue->tlv_data_size || ! ue->tlv_data)
return -ENXIO;
if (size < ue->tlv_data_size)
return -ENOSPC;
if (copy_to_user(tlv, ue->tlv_data, ue->tlv_data_size))
return -EFAULT;
}
return change;
}
static int snd_ctl_elem_init_enum_names(struct user_element *ue)
{
char *names, *p;
size_t buf_len, name_len;
unsigned int i;
const uintptr_t user_ptrval = ue->info.value.enumerated.names_ptr;
if (ue->info.value.enumerated.names_length > 64 * 1024)
return -EINVAL;
names = memdup_user((const void __user *)user_ptrval,
ue->info.value.enumerated.names_length);
if (IS_ERR(names))
return PTR_ERR(names);
/* check that there are enough valid names */
buf_len = ue->info.value.enumerated.names_length;
p = names;
for (i = 0; i < ue->info.value.enumerated.items; ++i) {
name_len = strnlen(p, buf_len);
if (name_len == 0 || name_len >= 64 || name_len == buf_len) {
kfree(names);
return -EINVAL;
}
p += name_len + 1;
buf_len -= name_len + 1;
}
ue->priv_data = names;
ue->info.value.enumerated.names_ptr = 0;
return 0;
}
static void snd_ctl_elem_user_free(struct snd_kcontrol *kcontrol)
{
struct user_element *ue = kcontrol->private_data;
kfree(ue->tlv_data);
kfree(ue->priv_data);
kfree(ue);
}
static int snd_ctl_elem_add(struct snd_ctl_file *file,
struct snd_ctl_elem_info *info, int replace)
{
struct snd_card *card = file->card;
struct snd_kcontrol kctl, *_kctl;
unsigned int access;
long private_size;
struct user_element *ue;
int idx, err;
if (!replace && card->user_ctl_count >= MAX_USER_CONTROLS)
return -ENOMEM;
if (info->count < 1)
return -EINVAL;
access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE :
(info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE|
SNDRV_CTL_ELEM_ACCESS_INACTIVE|
SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE));
info->id.numid = 0;
memset(&kctl, 0, sizeof(kctl));
down_write(&card->controls_rwsem);
_kctl = snd_ctl_find_id(card, &info->id);
err = 0;
if (_kctl) {
if (replace)
err = snd_ctl_remove(card, _kctl);
else
err = -EBUSY;
} else {
if (replace)
err = -ENOENT;
}
up_write(&card->controls_rwsem);
if (err < 0)
return err;
memcpy(&kctl.id, &info->id, sizeof(info->id));
kctl.count = info->owner ? info->owner : 1;
access |= SNDRV_CTL_ELEM_ACCESS_USER;
if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
kctl.info = snd_ctl_elem_user_enum_info;
else
kctl.info = snd_ctl_elem_user_info;
if (access & SNDRV_CTL_ELEM_ACCESS_READ)
kctl.get = snd_ctl_elem_user_get;
if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
kctl.put = snd_ctl_elem_user_put;
if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) {
kctl.tlv.c = snd_ctl_elem_user_tlv;
access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
}
switch (info->type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
case SNDRV_CTL_ELEM_TYPE_INTEGER:
private_size = sizeof(long);
if (info->count > 128)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER64:
private_size = sizeof(long long);
if (info->count > 64)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
private_size = sizeof(unsigned int);
if (info->count > 128 || info->value.enumerated.items == 0)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_BYTES:
private_size = sizeof(unsigned char);
if (info->count > 512)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_IEC958:
private_size = sizeof(struct snd_aes_iec958);
if (info->count != 1)
return -EINVAL;
break;
default:
return -EINVAL;
}
private_size *= info->count;
ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL);
if (ue == NULL)
return -ENOMEM;
ue->info = *info;
ue->info.access = 0;
ue->elem_data = (char *)ue + sizeof(*ue);
ue->elem_data_size = private_size;
if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
err = snd_ctl_elem_init_enum_names(ue);
if (err < 0) {
kfree(ue);
return err;
}
}
kctl.private_free = snd_ctl_elem_user_free;
_kctl = snd_ctl_new(&kctl, access);
if (_kctl == NULL) {
kfree(ue->priv_data);
kfree(ue);
return -ENOMEM;
}
_kctl->private_data = ue;
for (idx = 0; idx < _kctl->count; idx++)
_kctl->vd[idx].owner = file;
err = snd_ctl_add(card, _kctl);
if (err < 0)
return err;
down_write(&card->controls_rwsem);
card->user_ctl_count++;
up_write(&card->controls_rwsem);
return 0;
}
static int snd_ctl_elem_add_user(struct snd_ctl_file *file,
struct snd_ctl_elem_info __user *_info, int replace)
{
struct snd_ctl_elem_info info;
if (copy_from_user(&info, _info, sizeof(info)))
return -EFAULT;
return snd_ctl_elem_add(file, &info, replace);
}
static int snd_ctl_elem_remove(struct snd_ctl_file *file,
struct snd_ctl_elem_id __user *_id)
{
struct snd_ctl_elem_id id;
if (copy_from_user(&id, _id, sizeof(id)))
return -EFAULT;
return snd_ctl_remove_user_ctl(file, &id);
}
static int snd_ctl_subscribe_events(struct snd_ctl_file *file, int __user *ptr)
{
int subscribe;
if (get_user(subscribe, ptr))
return -EFAULT;
if (subscribe < 0) {
subscribe = file->subscribed;
if (put_user(subscribe, ptr))
return -EFAULT;
return 0;
}
if (subscribe) {
file->subscribed = 1;
return 0;
} else if (file->subscribed) {
snd_ctl_empty_read_queue(file);
file->subscribed = 0;
}
return 0;
}
static int snd_ctl_tlv_ioctl(struct snd_ctl_file *file,
struct snd_ctl_tlv __user *_tlv,
int op_flag)
{
struct snd_card *card = file->card;
struct snd_ctl_tlv tlv;
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int len;
int err = 0;
if (copy_from_user(&tlv, _tlv, sizeof(tlv)))
return -EFAULT;
if (tlv.length < sizeof(unsigned int) * 2)
return -EINVAL;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_numid(card, tlv.numid);
if (kctl == NULL) {
err = -ENOENT;
goto __kctl_end;
}
if (kctl->tlv.p == NULL) {
err = -ENXIO;
goto __kctl_end;
}
vd = &kctl->vd[tlv.numid - kctl->id.numid];
if ((op_flag == 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_READ) == 0) ||
(op_flag > 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE) == 0) ||
(op_flag < 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND) == 0)) {
err = -ENXIO;
goto __kctl_end;
}
if (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {
if (vd->owner != NULL && vd->owner != file) {
err = -EPERM;
goto __kctl_end;
}
err = kctl->tlv.c(kctl, op_flag, tlv.length, _tlv->tlv);
if (err > 0) {
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_TLV, &kctl->id);
return 0;
}
} else {
if (op_flag) {
err = -ENXIO;
goto __kctl_end;
}
len = kctl->tlv.p[1] + 2 * sizeof(unsigned int);
if (tlv.length < len) {
err = -ENOMEM;
goto __kctl_end;
}
if (copy_to_user(_tlv->tlv, kctl->tlv.p, len))
err = -EFAULT;
}
__kctl_end:
up_read(&card->controls_rwsem);
return err;
}
static long snd_ctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct snd_ctl_file *ctl;
struct snd_card *card;
struct snd_kctl_ioctl *p;
void __user *argp = (void __user *)arg;
int __user *ip = argp;
int err;
ctl = file->private_data;
card = ctl->card;
if (snd_BUG_ON(!card))
return -ENXIO;
switch (cmd) {
case SNDRV_CTL_IOCTL_PVERSION:
return put_user(SNDRV_CTL_VERSION, ip) ? -EFAULT : 0;
case SNDRV_CTL_IOCTL_CARD_INFO:
return snd_ctl_card_info(card, ctl, cmd, argp);
case SNDRV_CTL_IOCTL_ELEM_LIST:
return snd_ctl_elem_list(card, argp);
case SNDRV_CTL_IOCTL_ELEM_INFO:
return snd_ctl_elem_info_user(ctl, argp);
case SNDRV_CTL_IOCTL_ELEM_READ:
return snd_ctl_elem_read_user(card, argp);
case SNDRV_CTL_IOCTL_ELEM_WRITE:
return snd_ctl_elem_write_user(ctl, argp);
case SNDRV_CTL_IOCTL_ELEM_LOCK:
return snd_ctl_elem_lock(ctl, argp);
case SNDRV_CTL_IOCTL_ELEM_UNLOCK:
return snd_ctl_elem_unlock(ctl, argp);
case SNDRV_CTL_IOCTL_ELEM_ADD:
return snd_ctl_elem_add_user(ctl, argp, 0);
case SNDRV_CTL_IOCTL_ELEM_REPLACE:
return snd_ctl_elem_add_user(ctl, argp, 1);
case SNDRV_CTL_IOCTL_ELEM_REMOVE:
return snd_ctl_elem_remove(ctl, argp);
case SNDRV_CTL_IOCTL_SUBSCRIBE_EVENTS:
return snd_ctl_subscribe_events(ctl, ip);
case SNDRV_CTL_IOCTL_TLV_READ:
return snd_ctl_tlv_ioctl(ctl, argp, 0);
case SNDRV_CTL_IOCTL_TLV_WRITE:
return snd_ctl_tlv_ioctl(ctl, argp, 1);
case SNDRV_CTL_IOCTL_TLV_COMMAND:
return snd_ctl_tlv_ioctl(ctl, argp, -1);
case SNDRV_CTL_IOCTL_POWER:
return -ENOPROTOOPT;
case SNDRV_CTL_IOCTL_POWER_STATE:
#ifdef CONFIG_PM
return put_user(card->power_state, ip) ? -EFAULT : 0;
#else
return put_user(SNDRV_CTL_POWER_D0, ip) ? -EFAULT : 0;
#endif
}
down_read(&snd_ioctl_rwsem);
list_for_each_entry(p, &snd_control_ioctls, list) {
err = p->fioctl(card, ctl, cmd, arg);
if (err != -ENOIOCTLCMD) {
up_read(&snd_ioctl_rwsem);
return err;
}
}
up_read(&snd_ioctl_rwsem);
snd_printdd("unknown ioctl = 0x%x\n", cmd);
return -ENOTTY;
}
static ssize_t snd_ctl_read(struct file *file, char __user *buffer,
size_t count, loff_t * offset)
{
struct snd_ctl_file *ctl;
int err = 0;
ssize_t result = 0;
ctl = file->private_data;
if (snd_BUG_ON(!ctl || !ctl->card))
return -ENXIO;
if (!ctl->subscribed)
return -EBADFD;
if (count < sizeof(struct snd_ctl_event))
return -EINVAL;
spin_lock_irq(&ctl->read_lock);
while (count >= sizeof(struct snd_ctl_event)) {
struct snd_ctl_event ev;
struct snd_kctl_event *kev;
while (list_empty(&ctl->events)) {
wait_queue_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto __end_lock;
}
init_waitqueue_entry(&wait, current);
add_wait_queue(&ctl->change_sleep, &wait);
set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_irq(&ctl->read_lock);
schedule();
remove_wait_queue(&ctl->change_sleep, &wait);
if (ctl->card->shutdown)
return -ENODEV;
if (signal_pending(current))
return -ERESTARTSYS;
spin_lock_irq(&ctl->read_lock);
}
kev = snd_kctl_event(ctl->events.next);
ev.type = SNDRV_CTL_EVENT_ELEM;
ev.data.elem.mask = kev->mask;
ev.data.elem.id = kev->id;
list_del(&kev->list);
spin_unlock_irq(&ctl->read_lock);
kfree(kev);
if (copy_to_user(buffer, &ev, sizeof(struct snd_ctl_event))) {
err = -EFAULT;
goto __end;
}
spin_lock_irq(&ctl->read_lock);
buffer += sizeof(struct snd_ctl_event);
count -= sizeof(struct snd_ctl_event);
result += sizeof(struct snd_ctl_event);
}
__end_lock:
spin_unlock_irq(&ctl->read_lock);
__end:
return result > 0 ? result : err;
}
static unsigned int snd_ctl_poll(struct file *file, poll_table * wait)
{
unsigned int mask;
struct snd_ctl_file *ctl;
ctl = file->private_data;
if (!ctl->subscribed)
return 0;
poll_wait(file, &ctl->change_sleep, wait);
mask = 0;
if (!list_empty(&ctl->events))
mask |= POLLIN | POLLRDNORM;
return mask;
}
/*
* register the device-specific control-ioctls.
* called from each device manager like pcm.c, hwdep.c, etc.
*/
static int _snd_ctl_register_ioctl(snd_kctl_ioctl_func_t fcn, struct list_head *lists)
{
struct snd_kctl_ioctl *pn;
pn = kzalloc(sizeof(struct snd_kctl_ioctl), GFP_KERNEL);
if (pn == NULL)
return -ENOMEM;
pn->fioctl = fcn;
down_write(&snd_ioctl_rwsem);
list_add_tail(&pn->list, lists);
up_write(&snd_ioctl_rwsem);
return 0;
}
int snd_ctl_register_ioctl(snd_kctl_ioctl_func_t fcn)
{
return _snd_ctl_register_ioctl(fcn, &snd_control_ioctls);
}
EXPORT_SYMBOL(snd_ctl_register_ioctl);
#ifdef CONFIG_COMPAT
int snd_ctl_register_ioctl_compat(snd_kctl_ioctl_func_t fcn)
{
return _snd_ctl_register_ioctl(fcn, &snd_control_compat_ioctls);
}
EXPORT_SYMBOL(snd_ctl_register_ioctl_compat);
#endif
/*
* de-register the device-specific control-ioctls.
*/
static int _snd_ctl_unregister_ioctl(snd_kctl_ioctl_func_t fcn,
struct list_head *lists)
{
struct snd_kctl_ioctl *p;
if (snd_BUG_ON(!fcn))
return -EINVAL;
down_write(&snd_ioctl_rwsem);
list_for_each_entry(p, lists, list) {
if (p->fioctl == fcn) {
list_del(&p->list);
up_write(&snd_ioctl_rwsem);
kfree(p);
return 0;
}
}
up_write(&snd_ioctl_rwsem);
snd_BUG();
return -EINVAL;
}
int snd_ctl_unregister_ioctl(snd_kctl_ioctl_func_t fcn)
{
return _snd_ctl_unregister_ioctl(fcn, &snd_control_ioctls);
}
EXPORT_SYMBOL(snd_ctl_unregister_ioctl);
#ifdef CONFIG_COMPAT
int snd_ctl_unregister_ioctl_compat(snd_kctl_ioctl_func_t fcn)
{
return _snd_ctl_unregister_ioctl(fcn, &snd_control_compat_ioctls);
}
EXPORT_SYMBOL(snd_ctl_unregister_ioctl_compat);
#endif
static int snd_ctl_fasync(int fd, struct file * file, int on)
{
struct snd_ctl_file *ctl;
ctl = file->private_data;
return fasync_helper(fd, file, on, &ctl->fasync);
}
/*
* ioctl32 compat
*/
#ifdef CONFIG_COMPAT
#include "control_compat.c"
#else
#define snd_ctl_ioctl_compat NULL
#endif
/*
* INIT PART
*/
static const struct file_operations snd_ctl_f_ops =
{
.owner = THIS_MODULE,
.read = snd_ctl_read,
.open = snd_ctl_open,
.release = snd_ctl_release,
.llseek = no_llseek,
.poll = snd_ctl_poll,
.unlocked_ioctl = snd_ctl_ioctl,
.compat_ioctl = snd_ctl_ioctl_compat,
.fasync = snd_ctl_fasync,
};
/*
* registration of the control device
*/
static int snd_ctl_dev_register(struct snd_device *device)
{
struct snd_card *card = device->device_data;
int err, cardnum;
char name[16];
if (snd_BUG_ON(!card))
return -ENXIO;
cardnum = card->number;
if (snd_BUG_ON(cardnum < 0 || cardnum >= SNDRV_CARDS))
return -ENXIO;
sprintf(name, "controlC%i", cardnum);
if ((err = snd_register_device(SNDRV_DEVICE_TYPE_CONTROL, card, -1,
&snd_ctl_f_ops, card, name)) < 0)
return err;
return 0;
}
/*
* disconnection of the control device
*/
static int snd_ctl_dev_disconnect(struct snd_device *device)
{
struct snd_card *card = device->device_data;
struct snd_ctl_file *ctl;
int err, cardnum;
if (snd_BUG_ON(!card))
return -ENXIO;
cardnum = card->number;
if (snd_BUG_ON(cardnum < 0 || cardnum >= SNDRV_CARDS))
return -ENXIO;
read_lock(&card->ctl_files_rwlock);
list_for_each_entry(ctl, &card->ctl_files, list) {
wake_up(&ctl->change_sleep);
kill_fasync(&ctl->fasync, SIGIO, POLL_ERR);
}
read_unlock(&card->ctl_files_rwlock);
if ((err = snd_unregister_device(SNDRV_DEVICE_TYPE_CONTROL,
card, -1)) < 0)
return err;
return 0;
}
/*
* free all controls
*/
static int snd_ctl_dev_free(struct snd_device *device)
{
struct snd_card *card = device->device_data;
struct snd_kcontrol *control;
down_write(&card->controls_rwsem);
while (!list_empty(&card->controls)) {
control = snd_kcontrol(card->controls.next);
snd_ctl_remove(card, control);
}
up_write(&card->controls_rwsem);
return 0;
}
/*
* create control core:
* called from init.c
*/
int snd_ctl_create(struct snd_card *card)
{
static struct snd_device_ops ops = {
.dev_free = snd_ctl_dev_free,
.dev_register = snd_ctl_dev_register,
.dev_disconnect = snd_ctl_dev_disconnect,
};
if (snd_BUG_ON(!card))
return -ENXIO;
return snd_device_new(card, SNDRV_DEV_CONTROL, card, &ops);
}
/*
* Frequently used control callbacks/helpers
*/
int snd_ctl_boolean_mono_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
EXPORT_SYMBOL(snd_ctl_boolean_mono_info);
int snd_ctl_boolean_stereo_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
EXPORT_SYMBOL(snd_ctl_boolean_stereo_info);
/**
* snd_ctl_enum_info - fills the info structure for an enumerated control
* @info: the structure to be filled
* @channels: the number of the control's channels; often one
* @items: the number of control values; also the size of @names
* @names: an array containing the names of all control values
*
* Sets all required fields in @info to their appropriate values.
* If the control's accessibility is not the default (readable and writable),
* the caller has to fill @info->access.
*/
int snd_ctl_enum_info(struct snd_ctl_elem_info *info, unsigned int channels,
unsigned int items, const char *const names[])
{
info->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
info->count = channels;
info->value.enumerated.items = items;
if (info->value.enumerated.item >= items)
info->value.enumerated.item = items - 1;
strlcpy(info->value.enumerated.name,
names[info->value.enumerated.item],
sizeof(info->value.enumerated.name));
return 0;
}
EXPORT_SYMBOL(snd_ctl_enum_info);
| gpl-2.0 |
LorDClockaN/LorDmodSaga | drivers/usb/otg/nop-usb-xceiv.c | 963 | 4016 | /*
* drivers/usb/otg/nop-usb-xceiv.c
*
* NOP USB transceiver for all USB transceiver which are either built-in
* into USB IP or which are mostly autonomous.
*
* Copyright (C) 2009 Texas Instruments Inc
* Author: Ajay Kumar Gupta <ajay.gupta@ti.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.
*
* Current status:
* This provides a "nop" transceiver for PHYs which are
* autonomous such as isp1504, isp1707, etc.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/usb/otg.h>
#include <linux/slab.h>
struct nop_usb_xceiv {
struct otg_transceiver otg;
struct device *dev;
};
static struct platform_device *pd;
void usb_nop_xceiv_register(void)
{
if (pd)
return;
pd = platform_device_register_simple("nop_usb_xceiv", -1, NULL, 0);
if (!pd) {
printk(KERN_ERR "Unable to register usb nop transceiver\n");
return;
}
}
EXPORT_SYMBOL(usb_nop_xceiv_register);
void usb_nop_xceiv_unregister(void)
{
platform_device_unregister(pd);
pd = NULL;
}
EXPORT_SYMBOL(usb_nop_xceiv_unregister);
static inline struct nop_usb_xceiv *xceiv_to_nop(struct otg_transceiver *x)
{
return container_of(x, struct nop_usb_xceiv, otg);
}
static int nop_set_suspend(struct otg_transceiver *x, int suspend)
{
return 0;
}
static int nop_set_peripheral(struct otg_transceiver *x,
struct usb_gadget *gadget)
{
struct nop_usb_xceiv *nop;
if (!x)
return -ENODEV;
nop = xceiv_to_nop(x);
if (!gadget) {
nop->otg.gadget = NULL;
return -ENODEV;
}
nop->otg.gadget = gadget;
nop->otg.state = OTG_STATE_B_IDLE;
return 0;
}
static int nop_set_host(struct otg_transceiver *x, struct usb_bus *host)
{
struct nop_usb_xceiv *nop;
if (!x)
return -ENODEV;
nop = xceiv_to_nop(x);
if (!host) {
nop->otg.host = NULL;
return -ENODEV;
}
nop->otg.host = host;
return 0;
}
static int __devinit nop_usb_xceiv_probe(struct platform_device *pdev)
{
struct nop_usb_xceiv *nop;
int err;
nop = kzalloc(sizeof *nop, GFP_KERNEL);
if (!nop)
return -ENOMEM;
nop->dev = &pdev->dev;
nop->otg.dev = nop->dev;
nop->otg.label = "nop-xceiv";
nop->otg.state = OTG_STATE_UNDEFINED;
nop->otg.set_host = nop_set_host;
nop->otg.set_peripheral = nop_set_peripheral;
nop->otg.set_suspend = nop_set_suspend;
err = otg_set_transceiver(&nop->otg);
if (err) {
dev_err(&pdev->dev, "can't register transceiver, err: %d\n",
err);
goto exit;
}
platform_set_drvdata(pdev, nop);
return 0;
exit:
kfree(nop);
return err;
}
static int __devexit nop_usb_xceiv_remove(struct platform_device *pdev)
{
struct nop_usb_xceiv *nop = platform_get_drvdata(pdev);
otg_set_transceiver(NULL);
platform_set_drvdata(pdev, NULL);
kfree(nop);
return 0;
}
static struct platform_driver nop_usb_xceiv_driver = {
.probe = nop_usb_xceiv_probe,
.remove = __devexit_p(nop_usb_xceiv_remove),
.driver = {
.name = "nop_usb_xceiv",
.owner = THIS_MODULE,
},
};
static int __init nop_usb_xceiv_init(void)
{
return platform_driver_register(&nop_usb_xceiv_driver);
}
subsys_initcall(nop_usb_xceiv_init);
static void __exit nop_usb_xceiv_exit(void)
{
platform_driver_unregister(&nop_usb_xceiv_driver);
}
module_exit(nop_usb_xceiv_exit);
MODULE_ALIAS("platform:nop_usb_xceiv");
MODULE_AUTHOR("Texas Instruments Inc");
MODULE_DESCRIPTION("NOP USB Transceiver driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
xixi012023/sultan-kernel-vivid-homeslice-ION | drivers/net/ks8851.c | 1475 | 44754 | /* drivers/net/ks8851.c
*
* Copyright 2009 Simtec Electronics
* http://www.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define DEBUG
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/cache.h>
#include <linux/crc32.h>
#include <linux/mii.h>
#include <linux/spi/spi.h>
#include "ks8851.h"
/**
* struct ks8851_rxctrl - KS8851 driver rx control
* @mchash: Multicast hash-table data.
* @rxcr1: KS_RXCR1 register setting
* @rxcr2: KS_RXCR2 register setting
*
* Representation of the settings needs to control the receive filtering
* such as the multicast hash-filter and the receive register settings. This
* is used to make the job of working out if the receive settings change and
* then issuing the new settings to the worker that will send the necessary
* commands.
*/
struct ks8851_rxctrl {
u16 mchash[4];
u16 rxcr1;
u16 rxcr2;
};
/**
* union ks8851_tx_hdr - tx header data
* @txb: The header as bytes
* @txw: The header as 16bit, little-endian words
*
* A dual representation of the tx header data to allow
* access to individual bytes, and to allow 16bit accesses
* with 16bit alignment.
*/
union ks8851_tx_hdr {
u8 txb[6];
__le16 txw[3];
};
/**
* struct ks8851_net - KS8851 driver private data
* @netdev: The network device we're bound to
* @spidev: The spi device we're bound to.
* @lock: Lock to ensure that the device is not accessed when busy.
* @statelock: Lock on this structure for tx list.
* @mii: The MII state information for the mii calls.
* @rxctrl: RX settings for @rxctrl_work.
* @tx_work: Work queue for tx packets
* @irq_work: Work queue for servicing interrupts
* @rxctrl_work: Work queue for updating RX mode and multicast lists
* @txq: Queue of packets for transmission.
* @spi_msg1: pre-setup SPI transfer with one message, @spi_xfer1.
* @spi_msg2: pre-setup SPI transfer with two messages, @spi_xfer2.
* @txh: Space for generating packet TX header in DMA-able data
* @rxd: Space for receiving SPI data, in DMA-able space.
* @txd: Space for transmitting SPI data, in DMA-able space.
* @msg_enable: The message flags controlling driver output (see ethtool).
* @fid: Incrementing frame id tag.
* @rc_ier: Cached copy of KS_IER.
* @rc_ccr: Cached copy of KS_CCR.
* @rc_rxqcr: Cached copy of KS_RXQCR.
* @eeprom_size: Companion eeprom size in Bytes, 0 if no eeprom
*
* The @lock ensures that the chip is protected when certain operations are
* in progress. When the read or write packet transfer is in progress, most
* of the chip registers are not ccessible until the transfer is finished and
* the DMA has been de-asserted.
*
* The @statelock is used to protect information in the structure which may
* need to be accessed via several sources, such as the network driver layer
* or one of the work queues.
*
* We align the buffers we may use for rx/tx to ensure that if the SPI driver
* wants to DMA map them, it will not have any problems with data the driver
* modifies.
*/
struct ks8851_net {
struct net_device *netdev;
struct spi_device *spidev;
struct mutex lock;
spinlock_t statelock;
union ks8851_tx_hdr txh ____cacheline_aligned;
u8 rxd[8];
u8 txd[8];
u32 msg_enable ____cacheline_aligned;
u16 tx_space;
u8 fid;
u16 rc_ier;
u16 rc_rxqcr;
u16 rc_ccr;
u16 eeprom_size;
struct mii_if_info mii;
struct ks8851_rxctrl rxctrl;
struct work_struct tx_work;
struct work_struct irq_work;
struct work_struct rxctrl_work;
struct sk_buff_head txq;
struct spi_message spi_msg1;
struct spi_message spi_msg2;
struct spi_transfer spi_xfer1;
struct spi_transfer spi_xfer2[2];
};
static int msg_enable;
/* shift for byte-enable data */
#define BYTE_EN(_x) ((_x) << 2)
/* turn register number and byte-enable mask into data for start of packet */
#define MK_OP(_byteen, _reg) (BYTE_EN(_byteen) | (_reg) << (8+2) | (_reg) >> 6)
/* SPI register read/write calls.
*
* All these calls issue SPI transactions to access the chip's registers. They
* all require that the necessary lock is held to prevent accesses when the
* chip is busy transferring packet data (RX/TX FIFO accesses).
*/
/**
* ks8851_wrreg16 - write 16bit register value to chip
* @ks: The chip state
* @reg: The register address
* @val: The value to write
*
* Issue a write to put the value @val into the register specified in @reg.
*/
static void ks8851_wrreg16(struct ks8851_net *ks, unsigned reg, unsigned val)
{
struct spi_transfer *xfer = &ks->spi_xfer1;
struct spi_message *msg = &ks->spi_msg1;
__le16 txb[2];
int ret;
txb[0] = cpu_to_le16(MK_OP(reg & 2 ? 0xC : 0x03, reg) | KS_SPIOP_WR);
txb[1] = cpu_to_le16(val);
xfer->tx_buf = txb;
xfer->rx_buf = NULL;
xfer->len = 4;
ret = spi_sync(ks->spidev, msg);
if (ret < 0)
netdev_err(ks->netdev, "spi_sync() failed\n");
}
/**
* ks8851_wrreg8 - write 8bit register value to chip
* @ks: The chip state
* @reg: The register address
* @val: The value to write
*
* Issue a write to put the value @val into the register specified in @reg.
*/
static void ks8851_wrreg8(struct ks8851_net *ks, unsigned reg, unsigned val)
{
struct spi_transfer *xfer = &ks->spi_xfer1;
struct spi_message *msg = &ks->spi_msg1;
__le16 txb[2];
int ret;
int bit;
bit = 1 << (reg & 3);
txb[0] = cpu_to_le16(MK_OP(bit, reg) | KS_SPIOP_WR);
txb[1] = val;
xfer->tx_buf = txb;
xfer->rx_buf = NULL;
xfer->len = 3;
ret = spi_sync(ks->spidev, msg);
if (ret < 0)
netdev_err(ks->netdev, "spi_sync() failed\n");
}
/**
* ks8851_rx_1msg - select whether to use one or two messages for spi read
* @ks: The device structure
*
* Return whether to generate a single message with a tx and rx buffer
* supplied to spi_sync(), or alternatively send the tx and rx buffers
* as separate messages.
*
* Depending on the hardware in use, a single message may be more efficient
* on interrupts or work done by the driver.
*
* This currently always returns true until we add some per-device data passed
* from the platform code to specify which mode is better.
*/
static inline bool ks8851_rx_1msg(struct ks8851_net *ks)
{
return true;
}
/**
* ks8851_rdreg - issue read register command and return the data
* @ks: The device state
* @op: The register address and byte enables in message format.
* @rxb: The RX buffer to return the result into
* @rxl: The length of data expected.
*
* This is the low level read call that issues the necessary spi message(s)
* to read data from the register specified in @op.
*/
static void ks8851_rdreg(struct ks8851_net *ks, unsigned op,
u8 *rxb, unsigned rxl)
{
struct spi_transfer *xfer;
struct spi_message *msg;
__le16 *txb = (__le16 *)ks->txd;
u8 *trx = ks->rxd;
int ret;
txb[0] = cpu_to_le16(op | KS_SPIOP_RD);
if (ks8851_rx_1msg(ks)) {
msg = &ks->spi_msg1;
xfer = &ks->spi_xfer1;
xfer->tx_buf = txb;
xfer->rx_buf = trx;
xfer->len = rxl + 2;
} else {
msg = &ks->spi_msg2;
xfer = ks->spi_xfer2;
xfer->tx_buf = txb;
xfer->rx_buf = NULL;
xfer->len = 2;
xfer++;
xfer->tx_buf = NULL;
xfer->rx_buf = trx;
xfer->len = rxl;
}
ret = spi_sync(ks->spidev, msg);
if (ret < 0)
netdev_err(ks->netdev, "read: spi_sync() failed\n");
else if (ks8851_rx_1msg(ks))
memcpy(rxb, trx + 2, rxl);
else
memcpy(rxb, trx, rxl);
}
/**
* ks8851_rdreg8 - read 8 bit register from device
* @ks: The chip information
* @reg: The register address
*
* Read a 8bit register from the chip, returning the result
*/
static unsigned ks8851_rdreg8(struct ks8851_net *ks, unsigned reg)
{
u8 rxb[1];
ks8851_rdreg(ks, MK_OP(1 << (reg & 3), reg), rxb, 1);
return rxb[0];
}
/**
* ks8851_rdreg16 - read 16 bit register from device
* @ks: The chip information
* @reg: The register address
*
* Read a 16bit register from the chip, returning the result
*/
static unsigned ks8851_rdreg16(struct ks8851_net *ks, unsigned reg)
{
__le16 rx = 0;
ks8851_rdreg(ks, MK_OP(reg & 2 ? 0xC : 0x3, reg), (u8 *)&rx, 2);
return le16_to_cpu(rx);
}
/**
* ks8851_rdreg32 - read 32 bit register from device
* @ks: The chip information
* @reg: The register address
*
* Read a 32bit register from the chip.
*
* Note, this read requires the address be aligned to 4 bytes.
*/
static unsigned ks8851_rdreg32(struct ks8851_net *ks, unsigned reg)
{
__le32 rx = 0;
WARN_ON(reg & 3);
ks8851_rdreg(ks, MK_OP(0xf, reg), (u8 *)&rx, 4);
return le32_to_cpu(rx);
}
/**
* ks8851_soft_reset - issue one of the soft reset to the device
* @ks: The device state.
* @op: The bit(s) to set in the GRR
*
* Issue the relevant soft-reset command to the device's GRR register
* specified by @op.
*
* Note, the delays are in there as a caution to ensure that the reset
* has time to take effect and then complete. Since the datasheet does
* not currently specify the exact sequence, we have chosen something
* that seems to work with our device.
*/
static void ks8851_soft_reset(struct ks8851_net *ks, unsigned op)
{
ks8851_wrreg16(ks, KS_GRR, op);
mdelay(1); /* wait a short time to effect reset */
ks8851_wrreg16(ks, KS_GRR, 0);
mdelay(1); /* wait for condition to clear */
}
/**
* ks8851_write_mac_addr - write mac address to device registers
* @dev: The network device
*
* Update the KS8851 MAC address registers from the address in @dev.
*
* This call assumes that the chip is not running, so there is no need to
* shutdown the RXQ process whilst setting this.
*/
static int ks8851_write_mac_addr(struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
int i;
mutex_lock(&ks->lock);
for (i = 0; i < ETH_ALEN; i++)
ks8851_wrreg8(ks, KS_MAR(i), dev->dev_addr[i]);
mutex_unlock(&ks->lock);
return 0;
}
/**
* ks8851_init_mac - initialise the mac address
* @ks: The device structure
*
* Get or create the initial mac address for the device and then set that
* into the station address register. Currently we assume that the device
* does not have a valid mac address in it, and so we use random_ether_addr()
* to create a new one.
*
* In future, the driver should check to see if the device has an EEPROM
* attached and whether that has a valid ethernet address in it.
*/
static void ks8851_init_mac(struct ks8851_net *ks)
{
struct net_device *dev = ks->netdev;
random_ether_addr(dev->dev_addr);
ks8851_write_mac_addr(dev);
}
/**
* ks8851_irq - device interrupt handler
* @irq: Interrupt number passed from the IRQ hnalder.
* @pw: The private word passed to register_irq(), our struct ks8851_net.
*
* Disable the interrupt from happening again until we've processed the
* current status by scheduling ks8851_irq_work().
*/
static irqreturn_t ks8851_irq(int irq, void *pw)
{
struct ks8851_net *ks = pw;
disable_irq_nosync(irq);
schedule_work(&ks->irq_work);
return IRQ_HANDLED;
}
/**
* ks8851_rdfifo - read data from the receive fifo
* @ks: The device state.
* @buff: The buffer address
* @len: The length of the data to read
*
* Issue an RXQ FIFO read command and read the @len amount of data from
* the FIFO into the buffer specified by @buff.
*/
static void ks8851_rdfifo(struct ks8851_net *ks, u8 *buff, unsigned len)
{
struct spi_transfer *xfer = ks->spi_xfer2;
struct spi_message *msg = &ks->spi_msg2;
u8 txb[1];
int ret;
netif_dbg(ks, rx_status, ks->netdev,
"%s: %d@%p\n", __func__, len, buff);
/* set the operation we're issuing */
txb[0] = KS_SPIOP_RXFIFO;
xfer->tx_buf = txb;
xfer->rx_buf = NULL;
xfer->len = 1;
xfer++;
xfer->rx_buf = buff;
xfer->tx_buf = NULL;
xfer->len = len;
ret = spi_sync(ks->spidev, msg);
if (ret < 0)
netdev_err(ks->netdev, "%s: spi_sync() failed\n", __func__);
}
/**
* ks8851_dbg_dumpkkt - dump initial packet contents to debug
* @ks: The device state
* @rxpkt: The data for the received packet
*
* Dump the initial data from the packet to dev_dbg().
*/
static void ks8851_dbg_dumpkkt(struct ks8851_net *ks, u8 *rxpkt)
{
netdev_dbg(ks->netdev,
"pkt %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x\n",
rxpkt[4], rxpkt[5], rxpkt[6], rxpkt[7],
rxpkt[8], rxpkt[9], rxpkt[10], rxpkt[11],
rxpkt[12], rxpkt[13], rxpkt[14], rxpkt[15]);
}
/**
* ks8851_rx_pkts - receive packets from the host
* @ks: The device information.
*
* This is called from the IRQ work queue when the system detects that there
* are packets in the receive queue. Find out how many packets there are and
* read them from the FIFO.
*/
static void ks8851_rx_pkts(struct ks8851_net *ks)
{
struct sk_buff *skb;
unsigned rxfc;
unsigned rxlen;
unsigned rxstat;
u32 rxh;
u8 *rxpkt;
rxfc = ks8851_rdreg8(ks, KS_RXFC);
netif_dbg(ks, rx_status, ks->netdev,
"%s: %d packets\n", __func__, rxfc);
/* Currently we're issuing a read per packet, but we could possibly
* improve the code by issuing a single read, getting the receive
* header, allocating the packet and then reading the packet data
* out in one go.
*
* This form of operation would require us to hold the SPI bus'
* chipselect low during the entie transaction to avoid any
* reset to the data stream coming from the chip.
*/
for (; rxfc != 0; rxfc--) {
rxh = ks8851_rdreg32(ks, KS_RXFHSR);
rxstat = rxh & 0xffff;
rxlen = rxh >> 16;
netif_dbg(ks, rx_status, ks->netdev,
"rx: stat 0x%04x, len 0x%04x\n", rxstat, rxlen);
/* the length of the packet includes the 32bit CRC */
/* set dma read address */
ks8851_wrreg16(ks, KS_RXFDPR, RXFDPR_RXFPAI | 0x00);
/* start the packet dma process, and set auto-dequeue rx */
ks8851_wrreg16(ks, KS_RXQCR,
ks->rc_rxqcr | RXQCR_SDA | RXQCR_ADRFE);
if (rxlen > 4) {
unsigned int rxalign;
rxlen -= 4;
rxalign = ALIGN(rxlen, 4);
skb = netdev_alloc_skb_ip_align(ks->netdev, rxalign);
if (skb) {
/* 4 bytes of status header + 4 bytes of
* garbage: we put them before ethernet
* header, so that they are copied,
* but ignored.
*/
rxpkt = skb_put(skb, rxlen) - 8;
ks8851_rdfifo(ks, rxpkt, rxalign + 8);
if (netif_msg_pktdata(ks))
ks8851_dbg_dumpkkt(ks, rxpkt);
skb->protocol = eth_type_trans(skb, ks->netdev);
netif_rx(skb);
ks->netdev->stats.rx_packets++;
ks->netdev->stats.rx_bytes += rxlen;
}
}
ks8851_wrreg16(ks, KS_RXQCR, ks->rc_rxqcr);
}
}
/**
* ks8851_irq_work - work queue handler for dealing with interrupt requests
* @work: The work structure that was scheduled by schedule_work()
*
* This is the handler invoked when the ks8851_irq() is called to find out
* what happened, as we cannot allow ourselves to sleep whilst waiting for
* anything other process has the chip's lock.
*
* Read the interrupt status, work out what needs to be done and then clear
* any of the interrupts that are not needed.
*/
static void ks8851_irq_work(struct work_struct *work)
{
struct ks8851_net *ks = container_of(work, struct ks8851_net, irq_work);
unsigned status;
unsigned handled = 0;
mutex_lock(&ks->lock);
status = ks8851_rdreg16(ks, KS_ISR);
netif_dbg(ks, intr, ks->netdev,
"%s: status 0x%04x\n", __func__, status);
if (status & IRQ_LCI) {
/* should do something about checking link status */
handled |= IRQ_LCI;
}
if (status & IRQ_LDI) {
u16 pmecr = ks8851_rdreg16(ks, KS_PMECR);
pmecr &= ~PMECR_WKEVT_MASK;
ks8851_wrreg16(ks, KS_PMECR, pmecr | PMECR_WKEVT_LINK);
handled |= IRQ_LDI;
}
if (status & IRQ_RXPSI)
handled |= IRQ_RXPSI;
if (status & IRQ_TXI) {
handled |= IRQ_TXI;
/* no lock here, tx queue should have been stopped */
/* update our idea of how much tx space is available to the
* system */
ks->tx_space = ks8851_rdreg16(ks, KS_TXMIR);
netif_dbg(ks, intr, ks->netdev,
"%s: txspace %d\n", __func__, ks->tx_space);
}
if (status & IRQ_RXI)
handled |= IRQ_RXI;
if (status & IRQ_SPIBEI) {
dev_err(&ks->spidev->dev, "%s: spi bus error\n", __func__);
handled |= IRQ_SPIBEI;
}
ks8851_wrreg16(ks, KS_ISR, handled);
if (status & IRQ_RXI) {
/* the datasheet says to disable the rx interrupt during
* packet read-out, however we're masking the interrupt
* from the device so do not bother masking just the RX
* from the device. */
ks8851_rx_pkts(ks);
}
/* if something stopped the rx process, probably due to wanting
* to change the rx settings, then do something about restarting
* it. */
if (status & IRQ_RXPSI) {
struct ks8851_rxctrl *rxc = &ks->rxctrl;
/* update the multicast hash table */
ks8851_wrreg16(ks, KS_MAHTR0, rxc->mchash[0]);
ks8851_wrreg16(ks, KS_MAHTR1, rxc->mchash[1]);
ks8851_wrreg16(ks, KS_MAHTR2, rxc->mchash[2]);
ks8851_wrreg16(ks, KS_MAHTR3, rxc->mchash[3]);
ks8851_wrreg16(ks, KS_RXCR2, rxc->rxcr2);
ks8851_wrreg16(ks, KS_RXCR1, rxc->rxcr1);
}
mutex_unlock(&ks->lock);
if (status & IRQ_TXI)
netif_wake_queue(ks->netdev);
enable_irq(ks->netdev->irq);
}
/**
* calc_txlen - calculate size of message to send packet
* @len: Length of data
*
* Returns the size of the TXFIFO message needed to send
* this packet.
*/
static inline unsigned calc_txlen(unsigned len)
{
return ALIGN(len + 4, 4);
}
/**
* ks8851_wrpkt - write packet to TX FIFO
* @ks: The device state.
* @txp: The sk_buff to transmit.
* @irq: IRQ on completion of the packet.
*
* Send the @txp to the chip. This means creating the relevant packet header
* specifying the length of the packet and the other information the chip
* needs, such as IRQ on completion. Send the header and the packet data to
* the device.
*/
static void ks8851_wrpkt(struct ks8851_net *ks, struct sk_buff *txp, bool irq)
{
struct spi_transfer *xfer = ks->spi_xfer2;
struct spi_message *msg = &ks->spi_msg2;
unsigned fid = 0;
int ret;
netif_dbg(ks, tx_queued, ks->netdev, "%s: skb %p, %d@%p, irq %d\n",
__func__, txp, txp->len, txp->data, irq);
fid = ks->fid++;
fid &= TXFR_TXFID_MASK;
if (irq)
fid |= TXFR_TXIC; /* irq on completion */
/* start header at txb[1] to align txw entries */
ks->txh.txb[1] = KS_SPIOP_TXFIFO;
ks->txh.txw[1] = cpu_to_le16(fid);
ks->txh.txw[2] = cpu_to_le16(txp->len);
xfer->tx_buf = &ks->txh.txb[1];
xfer->rx_buf = NULL;
xfer->len = 5;
xfer++;
xfer->tx_buf = txp->data;
xfer->rx_buf = NULL;
xfer->len = ALIGN(txp->len, 4);
ret = spi_sync(ks->spidev, msg);
if (ret < 0)
netdev_err(ks->netdev, "%s: spi_sync() failed\n", __func__);
}
/**
* ks8851_done_tx - update and then free skbuff after transmitting
* @ks: The device state
* @txb: The buffer transmitted
*/
static void ks8851_done_tx(struct ks8851_net *ks, struct sk_buff *txb)
{
struct net_device *dev = ks->netdev;
dev->stats.tx_bytes += txb->len;
dev->stats.tx_packets++;
dev_kfree_skb(txb);
}
/**
* ks8851_tx_work - process tx packet(s)
* @work: The work strucutre what was scheduled.
*
* This is called when a number of packets have been scheduled for
* transmission and need to be sent to the device.
*/
static void ks8851_tx_work(struct work_struct *work)
{
struct ks8851_net *ks = container_of(work, struct ks8851_net, tx_work);
struct sk_buff *txb;
bool last = skb_queue_empty(&ks->txq);
mutex_lock(&ks->lock);
while (!last) {
txb = skb_dequeue(&ks->txq);
last = skb_queue_empty(&ks->txq);
if (txb != NULL) {
ks8851_wrreg16(ks, KS_RXQCR, ks->rc_rxqcr | RXQCR_SDA);
ks8851_wrpkt(ks, txb, last);
ks8851_wrreg16(ks, KS_RXQCR, ks->rc_rxqcr);
ks8851_wrreg16(ks, KS_TXQCR, TXQCR_METFE);
ks8851_done_tx(ks, txb);
}
}
mutex_unlock(&ks->lock);
}
/**
* ks8851_set_powermode - set power mode of the device
* @ks: The device state
* @pwrmode: The power mode value to write to KS_PMECR.
*
* Change the power mode of the chip.
*/
static void ks8851_set_powermode(struct ks8851_net *ks, unsigned pwrmode)
{
unsigned pmecr;
netif_dbg(ks, hw, ks->netdev, "setting power mode %d\n", pwrmode);
pmecr = ks8851_rdreg16(ks, KS_PMECR);
pmecr &= ~PMECR_PM_MASK;
pmecr |= pwrmode;
ks8851_wrreg16(ks, KS_PMECR, pmecr);
}
/**
* ks8851_net_open - open network device
* @dev: The network device being opened.
*
* Called when the network device is marked active, such as a user executing
* 'ifconfig up' on the device.
*/
static int ks8851_net_open(struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
/* lock the card, even if we may not actually be doing anything
* else at the moment */
mutex_lock(&ks->lock);
netif_dbg(ks, ifup, ks->netdev, "opening\n");
/* bring chip out of any power saving mode it was in */
ks8851_set_powermode(ks, PMECR_PM_NORMAL);
/* issue a soft reset to the RX/TX QMU to put it into a known
* state. */
ks8851_soft_reset(ks, GRR_QMU);
/* setup transmission parameters */
ks8851_wrreg16(ks, KS_TXCR, (TXCR_TXE | /* enable transmit process */
TXCR_TXPE | /* pad to min length */
TXCR_TXCRC | /* add CRC */
TXCR_TXFCE)); /* enable flow control */
/* auto-increment tx data, reset tx pointer */
ks8851_wrreg16(ks, KS_TXFDPR, TXFDPR_TXFPAI);
/* setup receiver control */
ks8851_wrreg16(ks, KS_RXCR1, (RXCR1_RXPAFMA | /* from mac filter */
RXCR1_RXFCE | /* enable flow control */
RXCR1_RXBE | /* broadcast enable */
RXCR1_RXUE | /* unicast enable */
RXCR1_RXE)); /* enable rx block */
/* transfer entire frames out in one go */
ks8851_wrreg16(ks, KS_RXCR2, RXCR2_SRDBL_FRAME);
/* set receive counter timeouts */
ks8851_wrreg16(ks, KS_RXDTTR, 1000); /* 1ms after first frame to IRQ */
ks8851_wrreg16(ks, KS_RXDBCTR, 4096); /* >4Kbytes in buffer to IRQ */
ks8851_wrreg16(ks, KS_RXFCTR, 10); /* 10 frames to IRQ */
ks->rc_rxqcr = (RXQCR_RXFCTE | /* IRQ on frame count exceeded */
RXQCR_RXDBCTE | /* IRQ on byte count exceeded */
RXQCR_RXDTTE); /* IRQ on time exceeded */
ks8851_wrreg16(ks, KS_RXQCR, ks->rc_rxqcr);
/* clear then enable interrupts */
#define STD_IRQ (IRQ_LCI | /* Link Change */ \
IRQ_TXI | /* TX done */ \
IRQ_RXI | /* RX done */ \
IRQ_SPIBEI | /* SPI bus error */ \
IRQ_TXPSI | /* TX process stop */ \
IRQ_RXPSI) /* RX process stop */
ks->rc_ier = STD_IRQ;
ks8851_wrreg16(ks, KS_ISR, STD_IRQ);
ks8851_wrreg16(ks, KS_IER, STD_IRQ);
netif_start_queue(ks->netdev);
netif_dbg(ks, ifup, ks->netdev, "network device up\n");
mutex_unlock(&ks->lock);
return 0;
}
/**
* ks8851_net_stop - close network device
* @dev: The device being closed.
*
* Called to close down a network device which has been active. Cancell any
* work, shutdown the RX and TX process and then place the chip into a low
* power state whilst it is not being used.
*/
static int ks8851_net_stop(struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
netif_info(ks, ifdown, dev, "shutting down\n");
netif_stop_queue(dev);
mutex_lock(&ks->lock);
/* stop any outstanding work */
flush_work(&ks->irq_work);
flush_work(&ks->tx_work);
flush_work(&ks->rxctrl_work);
/* turn off the IRQs and ack any outstanding */
ks8851_wrreg16(ks, KS_IER, 0x0000);
ks8851_wrreg16(ks, KS_ISR, 0xffff);
/* shutdown RX process */
ks8851_wrreg16(ks, KS_RXCR1, 0x0000);
/* shutdown TX process */
ks8851_wrreg16(ks, KS_TXCR, 0x0000);
/* set powermode to soft power down to save power */
ks8851_set_powermode(ks, PMECR_PM_SOFTDOWN);
/* ensure any queued tx buffers are dumped */
while (!skb_queue_empty(&ks->txq)) {
struct sk_buff *txb = skb_dequeue(&ks->txq);
netif_dbg(ks, ifdown, ks->netdev,
"%s: freeing txb %p\n", __func__, txb);
dev_kfree_skb(txb);
}
mutex_unlock(&ks->lock);
return 0;
}
/**
* ks8851_start_xmit - transmit packet
* @skb: The buffer to transmit
* @dev: The device used to transmit the packet.
*
* Called by the network layer to transmit the @skb. Queue the packet for
* the device and schedule the necessary work to transmit the packet when
* it is free.
*
* We do this to firstly avoid sleeping with the network device locked,
* and secondly so we can round up more than one packet to transmit which
* means we can try and avoid generating too many transmit done interrupts.
*/
static netdev_tx_t ks8851_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
unsigned needed = calc_txlen(skb->len);
netdev_tx_t ret = NETDEV_TX_OK;
netif_dbg(ks, tx_queued, ks->netdev,
"%s: skb %p, %d@%p\n", __func__, skb, skb->len, skb->data);
spin_lock(&ks->statelock);
if (needed > ks->tx_space) {
netif_stop_queue(dev);
ret = NETDEV_TX_BUSY;
} else {
ks->tx_space -= needed;
skb_queue_tail(&ks->txq, skb);
}
spin_unlock(&ks->statelock);
schedule_work(&ks->tx_work);
return ret;
}
/**
* ks8851_rxctrl_work - work handler to change rx mode
* @work: The work structure this belongs to.
*
* Lock the device and issue the necessary changes to the receive mode from
* the network device layer. This is done so that we can do this without
* having to sleep whilst holding the network device lock.
*
* Since the recommendation from Micrel is that the RXQ is shutdown whilst the
* receive parameters are programmed, we issue a write to disable the RXQ and
* then wait for the interrupt handler to be triggered once the RXQ shutdown is
* complete. The interrupt handler then writes the new values into the chip.
*/
static void ks8851_rxctrl_work(struct work_struct *work)
{
struct ks8851_net *ks = container_of(work, struct ks8851_net, rxctrl_work);
mutex_lock(&ks->lock);
/* need to shutdown RXQ before modifying filter parameters */
ks8851_wrreg16(ks, KS_RXCR1, 0x00);
mutex_unlock(&ks->lock);
}
static void ks8851_set_rx_mode(struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
struct ks8851_rxctrl rxctrl;
memset(&rxctrl, 0, sizeof(rxctrl));
if (dev->flags & IFF_PROMISC) {
/* interface to receive everything */
rxctrl.rxcr1 = RXCR1_RXAE | RXCR1_RXINVF;
} else if (dev->flags & IFF_ALLMULTI) {
/* accept all multicast packets */
rxctrl.rxcr1 = (RXCR1_RXME | RXCR1_RXAE |
RXCR1_RXPAFMA | RXCR1_RXMAFMA);
} else if (dev->flags & IFF_MULTICAST && !netdev_mc_empty(dev)) {
struct netdev_hw_addr *ha;
u32 crc;
/* accept some multicast */
netdev_for_each_mc_addr(ha, dev) {
crc = ether_crc(ETH_ALEN, ha->addr);
crc >>= (32 - 6); /* get top six bits */
rxctrl.mchash[crc >> 4] |= (1 << (crc & 0xf));
}
rxctrl.rxcr1 = RXCR1_RXME | RXCR1_RXPAFMA;
} else {
/* just accept broadcast / unicast */
rxctrl.rxcr1 = RXCR1_RXPAFMA;
}
rxctrl.rxcr1 |= (RXCR1_RXUE | /* unicast enable */
RXCR1_RXBE | /* broadcast enable */
RXCR1_RXE | /* RX process enable */
RXCR1_RXFCE); /* enable flow control */
rxctrl.rxcr2 |= RXCR2_SRDBL_FRAME;
/* schedule work to do the actual set of the data if needed */
spin_lock(&ks->statelock);
if (memcmp(&rxctrl, &ks->rxctrl, sizeof(rxctrl)) != 0) {
memcpy(&ks->rxctrl, &rxctrl, sizeof(ks->rxctrl));
schedule_work(&ks->rxctrl_work);
}
spin_unlock(&ks->statelock);
}
static int ks8851_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr *sa = addr;
if (netif_running(dev))
return -EBUSY;
if (!is_valid_ether_addr(sa->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, sa->sa_data, ETH_ALEN);
return ks8851_write_mac_addr(dev);
}
static int ks8851_net_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
struct ks8851_net *ks = netdev_priv(dev);
if (!netif_running(dev))
return -EINVAL;
return generic_mii_ioctl(&ks->mii, if_mii(req), cmd, NULL);
}
static const struct net_device_ops ks8851_netdev_ops = {
.ndo_open = ks8851_net_open,
.ndo_stop = ks8851_net_stop,
.ndo_do_ioctl = ks8851_net_ioctl,
.ndo_start_xmit = ks8851_start_xmit,
.ndo_set_mac_address = ks8851_set_mac_address,
.ndo_set_rx_mode = ks8851_set_rx_mode,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
};
/* Companion eeprom access */
enum { /* EEPROM programming states */
EEPROM_CONTROL,
EEPROM_ADDRESS,
EEPROM_DATA,
EEPROM_COMPLETE
};
/**
* ks8851_eeprom_read - read a 16bits word in ks8851 companion EEPROM
* @dev: The network device the PHY is on.
* @addr: EEPROM address to read
*
* eeprom_size: used to define the data coding length. Can be changed
* through debug-fs.
*
* Programs a read on the EEPROM using ks8851 EEPROM SW access feature.
* Warning: The READ feature is not supported on ks8851 revision 0.
*
* Rough programming model:
* - on period start: set clock high and read value on bus
* - on period / 2: set clock low and program value on bus
* - start on period / 2
*/
unsigned int ks8851_eeprom_read(struct net_device *dev, unsigned int addr)
{
struct ks8851_net *ks = netdev_priv(dev);
int eepcr;
int ctrl = EEPROM_OP_READ;
int state = EEPROM_CONTROL;
int bit_count = EEPROM_OP_LEN - 1;
unsigned int data = 0;
int dummy;
unsigned int addr_len;
addr_len = (ks->eeprom_size == 128) ? 6 : 8;
/* start transaction: chip select high, authorize write */
mutex_lock(&ks->lock);
eepcr = EEPCR_EESA | EEPCR_EESRWA;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
eepcr |= EEPCR_EECS;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
mutex_unlock(&ks->lock);
while (state != EEPROM_COMPLETE) {
/* falling clock period starts... */
/* set EED_IO pin for control and address */
eepcr &= ~EEPCR_EEDO;
switch (state) {
case EEPROM_CONTROL:
eepcr |= ((ctrl >> bit_count) & 1) << 2;
if (bit_count-- <= 0) {
bit_count = addr_len - 1;
state = EEPROM_ADDRESS;
}
break;
case EEPROM_ADDRESS:
eepcr |= ((addr >> bit_count) & 1) << 2;
bit_count--;
break;
case EEPROM_DATA:
/* Change to receive mode */
eepcr &= ~EEPCR_EESRWA;
break;
}
/* lower clock */
eepcr &= ~EEPCR_EESCK;
mutex_lock(&ks->lock);
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
mutex_unlock(&ks->lock);
/* waitread period / 2 */
udelay(EEPROM_SK_PERIOD / 2);
/* rising clock period starts... */
/* raise clock */
mutex_lock(&ks->lock);
eepcr |= EEPCR_EESCK;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
mutex_unlock(&ks->lock);
/* Manage read */
switch (state) {
case EEPROM_ADDRESS:
if (bit_count < 0) {
bit_count = EEPROM_DATA_LEN - 1;
state = EEPROM_DATA;
}
break;
case EEPROM_DATA:
mutex_lock(&ks->lock);
dummy = ks8851_rdreg16(ks, KS_EEPCR);
mutex_unlock(&ks->lock);
data |= ((dummy >> EEPCR_EESB_OFFSET) & 1) << bit_count;
if (bit_count-- <= 0)
state = EEPROM_COMPLETE;
break;
}
/* wait period / 2 */
udelay(EEPROM_SK_PERIOD / 2);
}
/* close transaction */
mutex_lock(&ks->lock);
eepcr &= ~EEPCR_EECS;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
eepcr = 0;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
mutex_unlock(&ks->lock);
return data;
}
/**
* ks8851_eeprom_write - write a 16bits word in ks8851 companion EEPROM
* @dev: The network device the PHY is on.
* @op: operand (can be WRITE, EWEN, EWDS)
* @addr: EEPROM address to write
* @data: data to write
*
* eeprom_size: used to define the data coding length. Can be changed
* through debug-fs.
*
* Programs a write on the EEPROM using ks8851 EEPROM SW access feature.
*
* Note that a write enable is required before writing data.
*
* Rough programming model:
* - on period start: set clock high
* - on period / 2: set clock low and program value on bus
* - start on period / 2
*/
void ks8851_eeprom_write(struct net_device *dev, unsigned int op,
unsigned int addr, unsigned int data)
{
struct ks8851_net *ks = netdev_priv(dev);
int eepcr;
int state = EEPROM_CONTROL;
int bit_count = EEPROM_OP_LEN - 1;
unsigned int addr_len;
addr_len = (ks->eeprom_size == 128) ? 6 : 8;
switch (op) {
case EEPROM_OP_EWEN:
addr = 0x30;
break;
case EEPROM_OP_EWDS:
addr = 0;
break;
}
/* start transaction: chip select high, authorize write */
mutex_lock(&ks->lock);
eepcr = EEPCR_EESA | EEPCR_EESRWA;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
eepcr |= EEPCR_EECS;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
mutex_unlock(&ks->lock);
while (state != EEPROM_COMPLETE) {
/* falling clock period starts... */
/* set EED_IO pin for control and address */
eepcr &= ~EEPCR_EEDO;
switch (state) {
case EEPROM_CONTROL:
eepcr |= ((op >> bit_count) & 1) << 2;
if (bit_count-- <= 0) {
bit_count = addr_len - 1;
state = EEPROM_ADDRESS;
}
break;
case EEPROM_ADDRESS:
eepcr |= ((addr >> bit_count) & 1) << 2;
if (bit_count-- <= 0) {
if (op == EEPROM_OP_WRITE) {
bit_count = EEPROM_DATA_LEN - 1;
state = EEPROM_DATA;
} else {
state = EEPROM_COMPLETE;
}
}
break;
case EEPROM_DATA:
eepcr |= ((data >> bit_count) & 1) << 2;
if (bit_count-- <= 0)
state = EEPROM_COMPLETE;
break;
}
/* lower clock */
eepcr &= ~EEPCR_EESCK;
mutex_lock(&ks->lock);
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
mutex_unlock(&ks->lock);
/* wait period / 2 */
udelay(EEPROM_SK_PERIOD / 2);
/* rising clock period starts... */
/* raise clock */
eepcr |= EEPCR_EESCK;
mutex_lock(&ks->lock);
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
mutex_unlock(&ks->lock);
/* wait period / 2 */
udelay(EEPROM_SK_PERIOD / 2);
}
/* close transaction */
mutex_lock(&ks->lock);
eepcr &= ~EEPCR_EECS;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
eepcr = 0;
ks8851_wrreg16(ks, KS_EEPCR, eepcr);
mutex_unlock(&ks->lock);
}
/* ethtool support */
static void ks8851_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *di)
{
strlcpy(di->driver, "KS8851", sizeof(di->driver));
strlcpy(di->version, "1.00", sizeof(di->version));
strlcpy(di->bus_info, dev_name(dev->dev.parent), sizeof(di->bus_info));
}
static u32 ks8851_get_msglevel(struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
return ks->msg_enable;
}
static void ks8851_set_msglevel(struct net_device *dev, u32 to)
{
struct ks8851_net *ks = netdev_priv(dev);
ks->msg_enable = to;
}
static int ks8851_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct ks8851_net *ks = netdev_priv(dev);
return mii_ethtool_gset(&ks->mii, cmd);
}
static int ks8851_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct ks8851_net *ks = netdev_priv(dev);
return mii_ethtool_sset(&ks->mii, cmd);
}
static u32 ks8851_get_link(struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
return mii_link_ok(&ks->mii);
}
static int ks8851_nway_reset(struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
return mii_nway_restart(&ks->mii);
}
static int ks8851_get_eeprom_len(struct net_device *dev)
{
struct ks8851_net *ks = netdev_priv(dev);
return ks->eeprom_size;
}
static int ks8851_get_eeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct ks8851_net *ks = netdev_priv(dev);
u16 *eeprom_buff;
int first_word;
int last_word;
int ret_val = 0;
u16 i;
if (eeprom->len == 0)
return -EINVAL;
if (eeprom->len > ks->eeprom_size)
return -EINVAL;
eeprom->magic = ks8851_rdreg16(ks, KS_CIDER);
first_word = eeprom->offset >> 1;
last_word = (eeprom->offset + eeprom->len - 1) >> 1;
eeprom_buff = kmalloc(sizeof(u16) *
(last_word - first_word + 1), GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
for (i = 0; i < last_word - first_word + 1; i++)
eeprom_buff[i] = ks8851_eeprom_read(dev, first_word + 1);
/* Device's eeprom is little-endian, word addressable */
for (i = 0; i < last_word - first_word + 1; i++)
le16_to_cpus(&eeprom_buff[i]);
memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 1), eeprom->len);
kfree(eeprom_buff);
return ret_val;
}
static int ks8851_set_eeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct ks8851_net *ks = netdev_priv(dev);
u16 *eeprom_buff;
void *ptr;
int max_len;
int first_word;
int last_word;
int ret_val = 0;
u16 i;
if (eeprom->len == 0)
return -EOPNOTSUPP;
if (eeprom->len > ks->eeprom_size)
return -EINVAL;
if (eeprom->magic != ks8851_rdreg16(ks, KS_CIDER))
return -EFAULT;
first_word = eeprom->offset >> 1;
last_word = (eeprom->offset + eeprom->len - 1) >> 1;
max_len = (last_word - first_word + 1) * 2;
eeprom_buff = kmalloc(max_len, GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
ptr = (void *)eeprom_buff;
if (eeprom->offset & 1) {
/* need read/modify/write of first changed EEPROM word */
/* only the second byte of the word is being modified */
eeprom_buff[0] = ks8851_eeprom_read(dev, first_word);
ptr++;
}
if ((eeprom->offset + eeprom->len) & 1)
/* need read/modify/write of last changed EEPROM word */
/* only the first byte of the word is being modified */
eeprom_buff[last_word - first_word] =
ks8851_eeprom_read(dev, last_word);
/* Device's eeprom is little-endian, word addressable */
le16_to_cpus(&eeprom_buff[0]);
le16_to_cpus(&eeprom_buff[last_word - first_word]);
memcpy(ptr, bytes, eeprom->len);
for (i = 0; i < last_word - first_word + 1; i++)
eeprom_buff[i] = cpu_to_le16(eeprom_buff[i]);
ks8851_eeprom_write(dev, EEPROM_OP_EWEN, 0, 0);
for (i = 0; i < last_word - first_word + 1; i++) {
ks8851_eeprom_write(dev, EEPROM_OP_WRITE, first_word + i,
eeprom_buff[i]);
mdelay(EEPROM_WRITE_TIME);
}
ks8851_eeprom_write(dev, EEPROM_OP_EWDS, 0, 0);
kfree(eeprom_buff);
return ret_val;
}
static const struct ethtool_ops ks8851_ethtool_ops = {
.get_drvinfo = ks8851_get_drvinfo,
.get_msglevel = ks8851_get_msglevel,
.set_msglevel = ks8851_set_msglevel,
.get_settings = ks8851_get_settings,
.set_settings = ks8851_set_settings,
.get_link = ks8851_get_link,
.nway_reset = ks8851_nway_reset,
.get_eeprom_len = ks8851_get_eeprom_len,
.get_eeprom = ks8851_get_eeprom,
.set_eeprom = ks8851_set_eeprom,
};
/* MII interface controls */
/**
* ks8851_phy_reg - convert MII register into a KS8851 register
* @reg: MII register number.
*
* Return the KS8851 register number for the corresponding MII PHY register
* if possible. Return zero if the MII register has no direct mapping to the
* KS8851 register set.
*/
static int ks8851_phy_reg(int reg)
{
switch (reg) {
case MII_BMCR:
return KS_P1MBCR;
case MII_BMSR:
return KS_P1MBSR;
case MII_PHYSID1:
return KS_PHY1ILR;
case MII_PHYSID2:
return KS_PHY1IHR;
case MII_ADVERTISE:
return KS_P1ANAR;
case MII_LPA:
return KS_P1ANLPR;
}
return 0x0;
}
/**
* ks8851_phy_read - MII interface PHY register read.
* @dev: The network device the PHY is on.
* @phy_addr: Address of PHY (ignored as we only have one)
* @reg: The register to read.
*
* This call reads data from the PHY register specified in @reg. Since the
* device does not support all the MII registers, the non-existent values
* are always returned as zero.
*
* We return zero for unsupported registers as the MII code does not check
* the value returned for any error status, and simply returns it to the
* caller. The mii-tool that the driver was tested with takes any -ve error
* as real PHY capabilities, thus displaying incorrect data to the user.
*/
static int ks8851_phy_read(struct net_device *dev, int phy_addr, int reg)
{
struct ks8851_net *ks = netdev_priv(dev);
int ksreg;
int result;
ksreg = ks8851_phy_reg(reg);
if (!ksreg)
return 0x0; /* no error return allowed, so use zero */
mutex_lock(&ks->lock);
result = ks8851_rdreg16(ks, ksreg);
mutex_unlock(&ks->lock);
return result;
}
static void ks8851_phy_write(struct net_device *dev,
int phy, int reg, int value)
{
struct ks8851_net *ks = netdev_priv(dev);
int ksreg;
ksreg = ks8851_phy_reg(reg);
if (ksreg) {
mutex_lock(&ks->lock);
ks8851_wrreg16(ks, ksreg, value);
mutex_unlock(&ks->lock);
}
}
/**
* ks8851_read_selftest - read the selftest memory info.
* @ks: The device state
*
* Read and check the TX/RX memory selftest information.
*/
static int ks8851_read_selftest(struct ks8851_net *ks)
{
unsigned both_done = MBIR_TXMBF | MBIR_RXMBF;
int ret = 0;
unsigned rd;
rd = ks8851_rdreg16(ks, KS_MBIR);
if ((rd & both_done) != both_done) {
netdev_warn(ks->netdev, "Memory selftest not finished\n");
return 0;
}
if (rd & MBIR_TXMBFA) {
netdev_err(ks->netdev, "TX memory selftest fail\n");
ret |= 1;
}
if (rd & MBIR_RXMBFA) {
netdev_err(ks->netdev, "RX memory selftest fail\n");
ret |= 2;
}
return 0;
}
/* driver bus management functions */
#ifdef CONFIG_PM
static int ks8851_suspend(struct spi_device *spi, pm_message_t state)
{
struct ks8851_net *ks = dev_get_drvdata(&spi->dev);
struct net_device *dev = ks->netdev;
if (netif_running(dev)) {
netif_device_detach(dev);
ks8851_net_stop(dev);
}
return 0;
}
static int ks8851_resume(struct spi_device *spi)
{
struct ks8851_net *ks = dev_get_drvdata(&spi->dev);
struct net_device *dev = ks->netdev;
if (netif_running(dev)) {
ks8851_net_open(dev);
netif_device_attach(dev);
}
return 0;
}
#else
#define ks8851_suspend NULL
#define ks8851_resume NULL
#endif
static int __devinit ks8851_probe(struct spi_device *spi)
{
struct net_device *ndev;
struct ks8851_net *ks;
int ret;
ndev = alloc_etherdev(sizeof(struct ks8851_net));
if (!ndev) {
dev_err(&spi->dev, "failed to alloc ethernet device\n");
return -ENOMEM;
}
spi->bits_per_word = 8;
ks = netdev_priv(ndev);
ks->netdev = ndev;
ks->spidev = spi;
ks->tx_space = 6144;
mutex_init(&ks->lock);
spin_lock_init(&ks->statelock);
INIT_WORK(&ks->tx_work, ks8851_tx_work);
INIT_WORK(&ks->irq_work, ks8851_irq_work);
INIT_WORK(&ks->rxctrl_work, ks8851_rxctrl_work);
/* initialise pre-made spi transfer messages */
spi_message_init(&ks->spi_msg1);
spi_message_add_tail(&ks->spi_xfer1, &ks->spi_msg1);
spi_message_init(&ks->spi_msg2);
spi_message_add_tail(&ks->spi_xfer2[0], &ks->spi_msg2);
spi_message_add_tail(&ks->spi_xfer2[1], &ks->spi_msg2);
/* setup mii state */
ks->mii.dev = ndev;
ks->mii.phy_id = 1,
ks->mii.phy_id_mask = 1;
ks->mii.reg_num_mask = 0xf;
ks->mii.mdio_read = ks8851_phy_read;
ks->mii.mdio_write = ks8851_phy_write;
dev_info(&spi->dev, "message enable is %d\n", msg_enable);
/* set the default message enable */
ks->msg_enable = netif_msg_init(msg_enable, (NETIF_MSG_DRV |
NETIF_MSG_PROBE |
NETIF_MSG_LINK));
skb_queue_head_init(&ks->txq);
SET_ETHTOOL_OPS(ndev, &ks8851_ethtool_ops);
SET_NETDEV_DEV(ndev, &spi->dev);
dev_set_drvdata(&spi->dev, ks);
ndev->if_port = IF_PORT_100BASET;
ndev->netdev_ops = &ks8851_netdev_ops;
ndev->irq = spi->irq;
/* issue a global soft reset to reset the device. */
ks8851_soft_reset(ks, GRR_GSR);
/* simple check for a valid chip being connected to the bus */
if ((ks8851_rdreg16(ks, KS_CIDER) & ~CIDER_REV_MASK) != CIDER_ID) {
dev_err(&spi->dev, "failed to read device ID\n");
ret = -ENODEV;
goto err_id;
}
/* cache the contents of the CCR register for EEPROM, etc. */
ks->rc_ccr = ks8851_rdreg16(ks, KS_CCR);
if (ks->rc_ccr & CCR_EEPROM)
ks->eeprom_size = 128;
else
ks->eeprom_size = 0;
ks8851_read_selftest(ks);
ks8851_init_mac(ks);
ret = request_irq(spi->irq, ks8851_irq, IRQF_TRIGGER_LOW,
ndev->name, ks);
if (ret < 0) {
dev_err(&spi->dev, "failed to get irq\n");
goto err_irq;
}
ret = register_netdev(ndev);
if (ret) {
dev_err(&spi->dev, "failed to register network device\n");
goto err_netdev;
}
netdev_info(ndev, "revision %d, MAC %pM, IRQ %d\n",
CIDER_REV_GET(ks8851_rdreg16(ks, KS_CIDER)),
ndev->dev_addr, ndev->irq);
return 0;
err_netdev:
free_irq(ndev->irq, ndev);
err_id:
err_irq:
free_netdev(ndev);
return ret;
}
static int __devexit ks8851_remove(struct spi_device *spi)
{
struct ks8851_net *priv = dev_get_drvdata(&spi->dev);
if (netif_msg_drv(priv))
dev_info(&spi->dev, "remove\n");
unregister_netdev(priv->netdev);
free_irq(spi->irq, priv);
free_netdev(priv->netdev);
return 0;
}
static struct spi_driver ks8851_driver = {
.driver = {
.name = "ks8851",
.owner = THIS_MODULE,
},
.probe = ks8851_probe,
.remove = __devexit_p(ks8851_remove),
.suspend = ks8851_suspend,
.resume = ks8851_resume,
};
static int __init ks8851_init(void)
{
return spi_register_driver(&ks8851_driver);
}
static void __exit ks8851_exit(void)
{
spi_unregister_driver(&ks8851_driver);
}
module_init(ks8851_init);
module_exit(ks8851_exit);
MODULE_DESCRIPTION("KS8851 Network driver");
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_LICENSE("GPL");
module_param_named(message, msg_enable, int, 0);
MODULE_PARM_DESC(message, "Message verbosity level (0=none, 31=all)");
MODULE_ALIAS("spi:ks8851");
| gpl-2.0 |
DrKita/cm14 | drivers/hwmon/asc7621.c | 2243 | 35673 | /*
* asc7621.c - Part of lm_sensors, Linux kernel modules for hardware monitoring
* Copyright (c) 2007, 2010 George Joseph <george.joseph@fairview5.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/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>
/* Addresses to scan */
static const unsigned short normal_i2c[] = {
0x2c, 0x2d, 0x2e, I2C_CLIENT_END
};
enum asc7621_type {
asc7621,
asc7621a
};
#define INTERVAL_HIGH (HZ + HZ / 2)
#define INTERVAL_LOW (1 * 60 * HZ)
#define PRI_NONE 0
#define PRI_LOW 1
#define PRI_HIGH 2
#define FIRST_CHIP asc7621
#define LAST_CHIP asc7621a
struct asc7621_chip {
char *name;
enum asc7621_type chip_type;
u8 company_reg;
u8 company_id;
u8 verstep_reg;
u8 verstep_id;
const unsigned short *addresses;
};
static struct asc7621_chip asc7621_chips[] = {
{
.name = "asc7621",
.chip_type = asc7621,
.company_reg = 0x3e,
.company_id = 0x61,
.verstep_reg = 0x3f,
.verstep_id = 0x6c,
.addresses = normal_i2c,
},
{
.name = "asc7621a",
.chip_type = asc7621a,
.company_reg = 0x3e,
.company_id = 0x61,
.verstep_reg = 0x3f,
.verstep_id = 0x6d,
.addresses = normal_i2c,
},
};
/*
* Defines the highest register to be used, not the count.
* The actual count will probably be smaller because of gaps
* in the implementation (unused register locations).
* This define will safely set the array size of both the parameter
* and data arrays.
* This comes from the data sheet register description table.
*/
#define LAST_REGISTER 0xff
struct asc7621_data {
struct i2c_client client;
struct device *class_dev;
struct mutex update_lock;
int valid; /* !=0 if following fields are valid */
unsigned long last_high_reading; /* In jiffies */
unsigned long last_low_reading; /* In jiffies */
/*
* Registers we care about occupy the corresponding index
* in the array. Registers we don't care about are left
* at 0.
*/
u8 reg[LAST_REGISTER + 1];
};
/*
* Macro to get the parent asc7621_param structure
* from a sensor_device_attribute passed into the
* show/store functions.
*/
#define to_asc7621_param(_sda) \
container_of(_sda, struct asc7621_param, sda)
/*
* Each parameter to be retrieved needs an asc7621_param structure
* allocated. It contains the sensor_device_attribute structure
* and the control info needed to retrieve the value from the register map.
*/
struct asc7621_param {
struct sensor_device_attribute sda;
u8 priority;
u8 msb[3];
u8 lsb[3];
u8 mask[3];
u8 shift[3];
};
/*
* This is the map that ultimately indicates whether we'll be
* retrieving a register value or not, and at what frequency.
*/
static u8 asc7621_register_priorities[255];
static struct asc7621_data *asc7621_update_device(struct device *dev);
static inline u8 read_byte(struct i2c_client *client, u8 reg)
{
int res = i2c_smbus_read_byte_data(client, reg);
if (res < 0) {
dev_err(&client->dev,
"Unable to read from register 0x%02x.\n", reg);
return 0;
};
return res & 0xff;
}
static inline int write_byte(struct i2c_client *client, u8 reg, u8 data)
{
int res = i2c_smbus_write_byte_data(client, reg, data);
if (res < 0) {
dev_err(&client->dev,
"Unable to write value 0x%02x to register 0x%02x.\n",
data, reg);
};
return res;
}
/*
* Data Handlers
* Each function handles the formatting, storage
* and retrieval of like parameters.
*/
#define SETUP_SHOW_DATA_PARAM(d, a) \
struct sensor_device_attribute *sda = to_sensor_dev_attr(a); \
struct asc7621_data *data = asc7621_update_device(d); \
struct asc7621_param *param = to_asc7621_param(sda)
#define SETUP_STORE_DATA_PARAM(d, a) \
struct sensor_device_attribute *sda = to_sensor_dev_attr(a); \
struct i2c_client *client = to_i2c_client(d); \
struct asc7621_data *data = i2c_get_clientdata(client); \
struct asc7621_param *param = to_asc7621_param(sda)
/*
* u8 is just what it sounds like...an unsigned byte with no
* special formatting.
*/
static ssize_t show_u8(struct device *dev, struct device_attribute *attr,
char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
return sprintf(buf, "%u\n", data->reg[param->msb[0]]);
}
static ssize_t store_u8(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
reqval = clamp_val(reqval, 0, 255);
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = reqval;
write_byte(client, param->msb[0], reqval);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Many of the config values occupy only a few bits of a register.
*/
static ssize_t show_bitmask(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
return sprintf(buf, "%u\n",
(data->reg[param->msb[0]] >> param->
shift[0]) & param->mask[0]);
}
static ssize_t store_bitmask(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval;
u8 currval;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
reqval = clamp_val(reqval, 0, param->mask[0]);
reqval = (reqval & param->mask[0]) << param->shift[0];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
reqval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = reqval;
write_byte(client, param->msb[0], reqval);
mutex_unlock(&data->update_lock);
return count;
}
/*
* 16 bit fan rpm values
* reported by the device as the number of 11.111us periods (90khz)
* between full fan rotations. Therefore...
* RPM = (90000 * 60) / register value
*/
static ssize_t show_fan16(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u16 regval;
mutex_lock(&data->update_lock);
regval = (data->reg[param->msb[0]] << 8) | data->reg[param->lsb[0]];
mutex_unlock(&data->update_lock);
return sprintf(buf, "%u\n",
(regval == 0 ? -1 : (regval) ==
0xffff ? 0 : 5400000 / regval));
}
static ssize_t store_fan16(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
/*
* If a minimum RPM of zero is requested, then we set the register to
* 0xffff. This value allows the fan to be stopped completely without
* generating an alarm.
*/
reqval =
(reqval <= 0 ? 0xffff : clamp_val(5400000 / reqval, 0, 0xfffe));
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = (reqval >> 8) & 0xff;
data->reg[param->lsb[0]] = reqval & 0xff;
write_byte(client, param->msb[0], data->reg[param->msb[0]]);
write_byte(client, param->lsb[0], data->reg[param->lsb[0]]);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Voltages are scaled in the device so that the nominal voltage
* is 3/4ths of the 0-255 range (i.e. 192).
* If all voltages are 'normal' then all voltage registers will
* read 0xC0.
*
* The data sheet provides us with the 3/4 scale value for each voltage
* which is stored in in_scaling. The sda->index parameter value provides
* the index into in_scaling.
*
* NOTE: The chip expects the first 2 inputs be 2.5 and 2.25 volts
* respectively. That doesn't mean that's what the motherboard provides. :)
*/
static int asc7621_in_scaling[] = {
2500, 2250, 3300, 5000, 12000
};
static ssize_t show_in10(struct device *dev, struct device_attribute *attr,
char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u16 regval;
u8 nr = sda->index;
mutex_lock(&data->update_lock);
regval = (data->reg[param->msb[0]] << 8) | (data->reg[param->lsb[0]]);
mutex_unlock(&data->update_lock);
/* The LSB value is a 2-bit scaling of the MSB's LSbit value. */
regval = (regval >> 6) * asc7621_in_scaling[nr] / (0xc0 << 2);
return sprintf(buf, "%u\n", regval);
}
/* 8 bit voltage values (the mins and maxs) */
static ssize_t show_in8(struct device *dev, struct device_attribute *attr,
char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u8 nr = sda->index;
return sprintf(buf, "%u\n",
((data->reg[param->msb[0]] *
asc7621_in_scaling[nr]) / 0xc0));
}
static ssize_t store_in8(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval;
u8 nr = sda->index;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
reqval = clamp_val(reqval, 0, 0xffff);
reqval = reqval * 0xc0 / asc7621_in_scaling[nr];
reqval = clamp_val(reqval, 0, 0xff);
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = reqval;
write_byte(client, param->msb[0], reqval);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp8(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
return sprintf(buf, "%d\n", ((s8) data->reg[param->msb[0]]) * 1000);
}
static ssize_t store_temp8(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval;
s8 temp;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
reqval = clamp_val(reqval, -127000, 127000);
temp = reqval / 1000;
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = temp;
write_byte(client, param->msb[0], temp);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Temperatures that occupy 2 bytes always have the whole
* number of degrees in the MSB with some part of the LSB
* indicating fractional degrees.
*/
/* mmmmmmmm.llxxxxxx */
static ssize_t show_temp10(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u8 msb, lsb;
int temp;
mutex_lock(&data->update_lock);
msb = data->reg[param->msb[0]];
lsb = (data->reg[param->lsb[0]] >> 6) & 0x03;
temp = (((s8) msb) * 1000) + (lsb * 250);
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp);
}
/* mmmmmm.ll */
static ssize_t show_temp62(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u8 regval = data->reg[param->msb[0]];
int temp = ((s8) (regval & 0xfc) * 1000) + ((regval & 0x03) * 250);
return sprintf(buf, "%d\n", temp);
}
static ssize_t store_temp62(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval, i, f;
s8 temp;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
reqval = clamp_val(reqval, -32000, 31750);
i = reqval / 1000;
f = reqval - (i * 1000);
temp = i << 2;
temp |= f / 250;
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = temp;
write_byte(client, param->msb[0], temp);
mutex_unlock(&data->update_lock);
return count;
}
/*
* The aSC7621 doesn't provide an "auto_point2". Instead, you
* specify the auto_point1 and a range. To keep with the sysfs
* hwmon specs, we synthesize the auto_point_2 from them.
*/
static u32 asc7621_range_map[] = {
2000, 2500, 3330, 4000, 5000, 6670, 8000, 10000,
13330, 16000, 20000, 26670, 32000, 40000, 53330, 80000,
};
static ssize_t show_ap2_temp(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
long auto_point1;
u8 regval;
int temp;
mutex_lock(&data->update_lock);
auto_point1 = ((s8) data->reg[param->msb[1]]) * 1000;
regval =
((data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0]);
temp = auto_point1 + asc7621_range_map[clamp_val(regval, 0, 15)];
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp);
}
static ssize_t store_ap2_temp(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval, auto_point1;
int i;
u8 currval, newval = 0;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
mutex_lock(&data->update_lock);
auto_point1 = data->reg[param->msb[1]] * 1000;
reqval = clamp_val(reqval, auto_point1 + 2000, auto_point1 + 80000);
for (i = ARRAY_SIZE(asc7621_range_map) - 1; i >= 0; i--) {
if (reqval >= auto_point1 + asc7621_range_map[i]) {
newval = i;
break;
}
}
newval = (newval & param->mask[0]) << param->shift[0];
currval = read_byte(client, param->msb[0]);
newval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_ac(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u8 config, altbit, regval;
u8 map[] = {
0x01, 0x02, 0x04, 0x1f, 0x00, 0x06, 0x07, 0x10,
0x08, 0x0f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f
};
mutex_lock(&data->update_lock);
config = (data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
altbit = (data->reg[param->msb[1]] >> param->shift[1]) & param->mask[1];
regval = config | (altbit << 3);
mutex_unlock(&data->update_lock);
return sprintf(buf, "%u\n", map[clamp_val(regval, 0, 15)]);
}
static ssize_t store_pwm_ac(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
unsigned long reqval;
u8 currval, config, altbit, newval;
u16 map[] = {
0x04, 0x00, 0x01, 0xff, 0x02, 0xff, 0x05, 0x06,
0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f,
0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03,
};
if (kstrtoul(buf, 10, &reqval))
return -EINVAL;
if (reqval > 31)
return -EINVAL;
reqval = map[reqval];
if (reqval == 0xff)
return -EINVAL;
config = reqval & 0x07;
altbit = (reqval >> 3) & 0x01;
config = (config & param->mask[0]) << param->shift[0];
altbit = (altbit & param->mask[1]) << param->shift[1];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
newval = config | (currval & ~(param->mask[0] << param->shift[0]));
newval = altbit | (newval & ~(param->mask[1] << param->shift[1]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u8 config, altbit, minoff, val, newval;
mutex_lock(&data->update_lock);
config = (data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
altbit = (data->reg[param->msb[1]] >> param->shift[1]) & param->mask[1];
minoff = (data->reg[param->msb[2]] >> param->shift[2]) & param->mask[2];
mutex_unlock(&data->update_lock);
val = config | (altbit << 3);
newval = 0;
if (val == 3 || val >= 10)
newval = 255;
else if (val == 4)
newval = 0;
else if (val == 7)
newval = 1;
else if (minoff == 1)
newval = 2;
else
newval = 3;
return sprintf(buf, "%u\n", newval);
}
static ssize_t store_pwm_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval;
u8 currval, config, altbit, newval, minoff = 255;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
switch (reqval) {
case 0:
newval = 0x04;
break;
case 1:
newval = 0x07;
break;
case 2:
newval = 0x00;
minoff = 1;
break;
case 3:
newval = 0x00;
minoff = 0;
break;
case 255:
newval = 0x03;
break;
default:
return -EINVAL;
}
config = newval & 0x07;
altbit = (newval >> 3) & 0x01;
mutex_lock(&data->update_lock);
config = (config & param->mask[0]) << param->shift[0];
altbit = (altbit & param->mask[1]) << param->shift[1];
currval = read_byte(client, param->msb[0]);
newval = config | (currval & ~(param->mask[0] << param->shift[0]));
newval = altbit | (newval & ~(param->mask[1] << param->shift[1]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
if (minoff < 255) {
minoff = (minoff & param->mask[2]) << param->shift[2];
currval = read_byte(client, param->msb[2]);
newval =
minoff | (currval & ~(param->mask[2] << param->shift[2]));
data->reg[param->msb[2]] = newval;
write_byte(client, param->msb[2], newval);
}
mutex_unlock(&data->update_lock);
return count;
}
static u32 asc7621_pwm_freq_map[] = {
10, 15, 23, 30, 38, 47, 62, 94,
23000, 24000, 25000, 26000, 27000, 28000, 29000, 30000
};
static ssize_t show_pwm_freq(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u8 regval =
(data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
regval = clamp_val(regval, 0, 15);
return sprintf(buf, "%u\n", asc7621_pwm_freq_map[regval]);
}
static ssize_t store_pwm_freq(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
unsigned long reqval;
u8 currval, newval = 255;
int i;
if (kstrtoul(buf, 10, &reqval))
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(asc7621_pwm_freq_map); i++) {
if (reqval == asc7621_pwm_freq_map[i]) {
newval = i;
break;
}
}
if (newval == 255)
return -EINVAL;
newval = (newval & param->mask[0]) << param->shift[0];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
newval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
static u32 asc7621_pwm_auto_spinup_map[] = {
0, 100, 250, 400, 700, 1000, 2000, 4000
};
static ssize_t show_pwm_ast(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u8 regval =
(data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
regval = clamp_val(regval, 0, 7);
return sprintf(buf, "%u\n", asc7621_pwm_auto_spinup_map[regval]);
}
static ssize_t store_pwm_ast(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval;
u8 currval, newval = 255;
u32 i;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(asc7621_pwm_auto_spinup_map); i++) {
if (reqval == asc7621_pwm_auto_spinup_map[i]) {
newval = i;
break;
}
}
if (newval == 255)
return -EINVAL;
newval = (newval & param->mask[0]) << param->shift[0];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
newval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
static u32 asc7621_temp_smoothing_time_map[] = {
35000, 17600, 11800, 7000, 4400, 3000, 1600, 800
};
static ssize_t show_temp_st(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_DATA_PARAM(dev, attr);
u8 regval =
(data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
regval = clamp_val(regval, 0, 7);
return sprintf(buf, "%u\n", asc7621_temp_smoothing_time_map[regval]);
}
static ssize_t store_temp_st(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_DATA_PARAM(dev, attr);
long reqval;
u8 currval, newval = 255;
u32 i;
if (kstrtol(buf, 10, &reqval))
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(asc7621_temp_smoothing_time_map); i++) {
if (reqval == asc7621_temp_smoothing_time_map[i]) {
newval = i;
break;
}
}
if (newval == 255)
return -EINVAL;
newval = (newval & param->mask[0]) << param->shift[0];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
newval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
/*
* End of data handlers
*
* These defines do nothing more than make the table easier
* to read when wrapped at column 80.
*/
/*
* Creates a variable length array inititalizer.
* VAA(1,3,5,7) would produce {1,3,5,7}
*/
#define VAA(args...) {args}
#define PREAD(name, n, pri, rm, rl, m, s, r) \
{.sda = SENSOR_ATTR(name, S_IRUGO, show_##r, NULL, n), \
.priority = pri, .msb[0] = rm, .lsb[0] = rl, .mask[0] = m, \
.shift[0] = s,}
#define PWRITE(name, n, pri, rm, rl, m, s, r) \
{.sda = SENSOR_ATTR(name, S_IRUGO | S_IWUSR, show_##r, store_##r, n), \
.priority = pri, .msb[0] = rm, .lsb[0] = rl, .mask[0] = m, \
.shift[0] = s,}
/*
* PWRITEM assumes that the initializers for the .msb, .lsb, .mask and .shift
* were created using the VAA macro.
*/
#define PWRITEM(name, n, pri, rm, rl, m, s, r) \
{.sda = SENSOR_ATTR(name, S_IRUGO | S_IWUSR, show_##r, store_##r, n), \
.priority = pri, .msb = rm, .lsb = rl, .mask = m, .shift = s,}
static struct asc7621_param asc7621_params[] = {
PREAD(in0_input, 0, PRI_HIGH, 0x20, 0x13, 0, 0, in10),
PREAD(in1_input, 1, PRI_HIGH, 0x21, 0x18, 0, 0, in10),
PREAD(in2_input, 2, PRI_HIGH, 0x22, 0x11, 0, 0, in10),
PREAD(in3_input, 3, PRI_HIGH, 0x23, 0x12, 0, 0, in10),
PREAD(in4_input, 4, PRI_HIGH, 0x24, 0x14, 0, 0, in10),
PWRITE(in0_min, 0, PRI_LOW, 0x44, 0, 0, 0, in8),
PWRITE(in1_min, 1, PRI_LOW, 0x46, 0, 0, 0, in8),
PWRITE(in2_min, 2, PRI_LOW, 0x48, 0, 0, 0, in8),
PWRITE(in3_min, 3, PRI_LOW, 0x4a, 0, 0, 0, in8),
PWRITE(in4_min, 4, PRI_LOW, 0x4c, 0, 0, 0, in8),
PWRITE(in0_max, 0, PRI_LOW, 0x45, 0, 0, 0, in8),
PWRITE(in1_max, 1, PRI_LOW, 0x47, 0, 0, 0, in8),
PWRITE(in2_max, 2, PRI_LOW, 0x49, 0, 0, 0, in8),
PWRITE(in3_max, 3, PRI_LOW, 0x4b, 0, 0, 0, in8),
PWRITE(in4_max, 4, PRI_LOW, 0x4d, 0, 0, 0, in8),
PREAD(in0_alarm, 0, PRI_HIGH, 0x41, 0, 0x01, 0, bitmask),
PREAD(in1_alarm, 1, PRI_HIGH, 0x41, 0, 0x01, 1, bitmask),
PREAD(in2_alarm, 2, PRI_HIGH, 0x41, 0, 0x01, 2, bitmask),
PREAD(in3_alarm, 3, PRI_HIGH, 0x41, 0, 0x01, 3, bitmask),
PREAD(in4_alarm, 4, PRI_HIGH, 0x42, 0, 0x01, 0, bitmask),
PREAD(fan1_input, 0, PRI_HIGH, 0x29, 0x28, 0, 0, fan16),
PREAD(fan2_input, 1, PRI_HIGH, 0x2b, 0x2a, 0, 0, fan16),
PREAD(fan3_input, 2, PRI_HIGH, 0x2d, 0x2c, 0, 0, fan16),
PREAD(fan4_input, 3, PRI_HIGH, 0x2f, 0x2e, 0, 0, fan16),
PWRITE(fan1_min, 0, PRI_LOW, 0x55, 0x54, 0, 0, fan16),
PWRITE(fan2_min, 1, PRI_LOW, 0x57, 0x56, 0, 0, fan16),
PWRITE(fan3_min, 2, PRI_LOW, 0x59, 0x58, 0, 0, fan16),
PWRITE(fan4_min, 3, PRI_LOW, 0x5b, 0x5a, 0, 0, fan16),
PREAD(fan1_alarm, 0, PRI_HIGH, 0x42, 0, 0x01, 2, bitmask),
PREAD(fan2_alarm, 1, PRI_HIGH, 0x42, 0, 0x01, 3, bitmask),
PREAD(fan3_alarm, 2, PRI_HIGH, 0x42, 0, 0x01, 4, bitmask),
PREAD(fan4_alarm, 3, PRI_HIGH, 0x42, 0, 0x01, 5, bitmask),
PREAD(temp1_input, 0, PRI_HIGH, 0x25, 0x10, 0, 0, temp10),
PREAD(temp2_input, 1, PRI_HIGH, 0x26, 0x15, 0, 0, temp10),
PREAD(temp3_input, 2, PRI_HIGH, 0x27, 0x16, 0, 0, temp10),
PREAD(temp4_input, 3, PRI_HIGH, 0x33, 0x17, 0, 0, temp10),
PREAD(temp5_input, 4, PRI_HIGH, 0xf7, 0xf6, 0, 0, temp10),
PREAD(temp6_input, 5, PRI_HIGH, 0xf9, 0xf8, 0, 0, temp10),
PREAD(temp7_input, 6, PRI_HIGH, 0xfb, 0xfa, 0, 0, temp10),
PREAD(temp8_input, 7, PRI_HIGH, 0xfd, 0xfc, 0, 0, temp10),
PWRITE(temp1_min, 0, PRI_LOW, 0x4e, 0, 0, 0, temp8),
PWRITE(temp2_min, 1, PRI_LOW, 0x50, 0, 0, 0, temp8),
PWRITE(temp3_min, 2, PRI_LOW, 0x52, 0, 0, 0, temp8),
PWRITE(temp4_min, 3, PRI_LOW, 0x34, 0, 0, 0, temp8),
PWRITE(temp1_max, 0, PRI_LOW, 0x4f, 0, 0, 0, temp8),
PWRITE(temp2_max, 1, PRI_LOW, 0x51, 0, 0, 0, temp8),
PWRITE(temp3_max, 2, PRI_LOW, 0x53, 0, 0, 0, temp8),
PWRITE(temp4_max, 3, PRI_LOW, 0x35, 0, 0, 0, temp8),
PREAD(temp1_alarm, 0, PRI_HIGH, 0x41, 0, 0x01, 4, bitmask),
PREAD(temp2_alarm, 1, PRI_HIGH, 0x41, 0, 0x01, 5, bitmask),
PREAD(temp3_alarm, 2, PRI_HIGH, 0x41, 0, 0x01, 6, bitmask),
PREAD(temp4_alarm, 3, PRI_HIGH, 0x43, 0, 0x01, 0, bitmask),
PWRITE(temp1_source, 0, PRI_LOW, 0x02, 0, 0x07, 4, bitmask),
PWRITE(temp2_source, 1, PRI_LOW, 0x02, 0, 0x07, 0, bitmask),
PWRITE(temp3_source, 2, PRI_LOW, 0x03, 0, 0x07, 4, bitmask),
PWRITE(temp4_source, 3, PRI_LOW, 0x03, 0, 0x07, 0, bitmask),
PWRITE(temp1_smoothing_enable, 0, PRI_LOW, 0x62, 0, 0x01, 3, bitmask),
PWRITE(temp2_smoothing_enable, 1, PRI_LOW, 0x63, 0, 0x01, 7, bitmask),
PWRITE(temp3_smoothing_enable, 2, PRI_LOW, 0x63, 0, 0x01, 3, bitmask),
PWRITE(temp4_smoothing_enable, 3, PRI_LOW, 0x3c, 0, 0x01, 3, bitmask),
PWRITE(temp1_smoothing_time, 0, PRI_LOW, 0x62, 0, 0x07, 0, temp_st),
PWRITE(temp2_smoothing_time, 1, PRI_LOW, 0x63, 0, 0x07, 4, temp_st),
PWRITE(temp3_smoothing_time, 2, PRI_LOW, 0x63, 0, 0x07, 0, temp_st),
PWRITE(temp4_smoothing_time, 3, PRI_LOW, 0x3c, 0, 0x07, 0, temp_st),
PWRITE(temp1_auto_point1_temp_hyst, 0, PRI_LOW, 0x6d, 0, 0x0f, 4,
bitmask),
PWRITE(temp2_auto_point1_temp_hyst, 1, PRI_LOW, 0x6d, 0, 0x0f, 0,
bitmask),
PWRITE(temp3_auto_point1_temp_hyst, 2, PRI_LOW, 0x6e, 0, 0x0f, 4,
bitmask),
PWRITE(temp4_auto_point1_temp_hyst, 3, PRI_LOW, 0x6e, 0, 0x0f, 0,
bitmask),
PREAD(temp1_auto_point2_temp_hyst, 0, PRI_LOW, 0x6d, 0, 0x0f, 4,
bitmask),
PREAD(temp2_auto_point2_temp_hyst, 1, PRI_LOW, 0x6d, 0, 0x0f, 0,
bitmask),
PREAD(temp3_auto_point2_temp_hyst, 2, PRI_LOW, 0x6e, 0, 0x0f, 4,
bitmask),
PREAD(temp4_auto_point2_temp_hyst, 3, PRI_LOW, 0x6e, 0, 0x0f, 0,
bitmask),
PWRITE(temp1_auto_point1_temp, 0, PRI_LOW, 0x67, 0, 0, 0, temp8),
PWRITE(temp2_auto_point1_temp, 1, PRI_LOW, 0x68, 0, 0, 0, temp8),
PWRITE(temp3_auto_point1_temp, 2, PRI_LOW, 0x69, 0, 0, 0, temp8),
PWRITE(temp4_auto_point1_temp, 3, PRI_LOW, 0x3b, 0, 0, 0, temp8),
PWRITEM(temp1_auto_point2_temp, 0, PRI_LOW, VAA(0x5f, 0x67), VAA(0),
VAA(0x0f), VAA(4), ap2_temp),
PWRITEM(temp2_auto_point2_temp, 1, PRI_LOW, VAA(0x60, 0x68), VAA(0),
VAA(0x0f), VAA(4), ap2_temp),
PWRITEM(temp3_auto_point2_temp, 2, PRI_LOW, VAA(0x61, 0x69), VAA(0),
VAA(0x0f), VAA(4), ap2_temp),
PWRITEM(temp4_auto_point2_temp, 3, PRI_LOW, VAA(0x3c, 0x3b), VAA(0),
VAA(0x0f), VAA(4), ap2_temp),
PWRITE(temp1_crit, 0, PRI_LOW, 0x6a, 0, 0, 0, temp8),
PWRITE(temp2_crit, 1, PRI_LOW, 0x6b, 0, 0, 0, temp8),
PWRITE(temp3_crit, 2, PRI_LOW, 0x6c, 0, 0, 0, temp8),
PWRITE(temp4_crit, 3, PRI_LOW, 0x3d, 0, 0, 0, temp8),
PWRITE(temp5_enable, 4, PRI_LOW, 0x0e, 0, 0x01, 0, bitmask),
PWRITE(temp6_enable, 5, PRI_LOW, 0x0e, 0, 0x01, 1, bitmask),
PWRITE(temp7_enable, 6, PRI_LOW, 0x0e, 0, 0x01, 2, bitmask),
PWRITE(temp8_enable, 7, PRI_LOW, 0x0e, 0, 0x01, 3, bitmask),
PWRITE(remote1_offset, 0, PRI_LOW, 0x1c, 0, 0, 0, temp62),
PWRITE(remote2_offset, 1, PRI_LOW, 0x1d, 0, 0, 0, temp62),
PWRITE(pwm1, 0, PRI_HIGH, 0x30, 0, 0, 0, u8),
PWRITE(pwm2, 1, PRI_HIGH, 0x31, 0, 0, 0, u8),
PWRITE(pwm3, 2, PRI_HIGH, 0x32, 0, 0, 0, u8),
PWRITE(pwm1_invert, 0, PRI_LOW, 0x5c, 0, 0x01, 4, bitmask),
PWRITE(pwm2_invert, 1, PRI_LOW, 0x5d, 0, 0x01, 4, bitmask),
PWRITE(pwm3_invert, 2, PRI_LOW, 0x5e, 0, 0x01, 4, bitmask),
PWRITEM(pwm1_enable, 0, PRI_LOW, VAA(0x5c, 0x5c, 0x62), VAA(0, 0, 0),
VAA(0x07, 0x01, 0x01), VAA(5, 3, 5), pwm_enable),
PWRITEM(pwm2_enable, 1, PRI_LOW, VAA(0x5d, 0x5d, 0x62), VAA(0, 0, 0),
VAA(0x07, 0x01, 0x01), VAA(5, 3, 6), pwm_enable),
PWRITEM(pwm3_enable, 2, PRI_LOW, VAA(0x5e, 0x5e, 0x62), VAA(0, 0, 0),
VAA(0x07, 0x01, 0x01), VAA(5, 3, 7), pwm_enable),
PWRITEM(pwm1_auto_channels, 0, PRI_LOW, VAA(0x5c, 0x5c), VAA(0, 0),
VAA(0x07, 0x01), VAA(5, 3), pwm_ac),
PWRITEM(pwm2_auto_channels, 1, PRI_LOW, VAA(0x5d, 0x5d), VAA(0, 0),
VAA(0x07, 0x01), VAA(5, 3), pwm_ac),
PWRITEM(pwm3_auto_channels, 2, PRI_LOW, VAA(0x5e, 0x5e), VAA(0, 0),
VAA(0x07, 0x01), VAA(5, 3), pwm_ac),
PWRITE(pwm1_auto_point1_pwm, 0, PRI_LOW, 0x64, 0, 0, 0, u8),
PWRITE(pwm2_auto_point1_pwm, 1, PRI_LOW, 0x65, 0, 0, 0, u8),
PWRITE(pwm3_auto_point1_pwm, 2, PRI_LOW, 0x66, 0, 0, 0, u8),
PWRITE(pwm1_auto_point2_pwm, 0, PRI_LOW, 0x38, 0, 0, 0, u8),
PWRITE(pwm2_auto_point2_pwm, 1, PRI_LOW, 0x39, 0, 0, 0, u8),
PWRITE(pwm3_auto_point2_pwm, 2, PRI_LOW, 0x3a, 0, 0, 0, u8),
PWRITE(pwm1_freq, 0, PRI_LOW, 0x5f, 0, 0x0f, 0, pwm_freq),
PWRITE(pwm2_freq, 1, PRI_LOW, 0x60, 0, 0x0f, 0, pwm_freq),
PWRITE(pwm3_freq, 2, PRI_LOW, 0x61, 0, 0x0f, 0, pwm_freq),
PREAD(pwm1_auto_zone_assigned, 0, PRI_LOW, 0, 0, 0x03, 2, bitmask),
PREAD(pwm2_auto_zone_assigned, 1, PRI_LOW, 0, 0, 0x03, 4, bitmask),
PREAD(pwm3_auto_zone_assigned, 2, PRI_LOW, 0, 0, 0x03, 6, bitmask),
PWRITE(pwm1_auto_spinup_time, 0, PRI_LOW, 0x5c, 0, 0x07, 0, pwm_ast),
PWRITE(pwm2_auto_spinup_time, 1, PRI_LOW, 0x5d, 0, 0x07, 0, pwm_ast),
PWRITE(pwm3_auto_spinup_time, 2, PRI_LOW, 0x5e, 0, 0x07, 0, pwm_ast),
PWRITE(peci_enable, 0, PRI_LOW, 0x40, 0, 0x01, 4, bitmask),
PWRITE(peci_avg, 0, PRI_LOW, 0x36, 0, 0x07, 0, bitmask),
PWRITE(peci_domain, 0, PRI_LOW, 0x36, 0, 0x01, 3, bitmask),
PWRITE(peci_legacy, 0, PRI_LOW, 0x36, 0, 0x01, 4, bitmask),
PWRITE(peci_diode, 0, PRI_LOW, 0x0e, 0, 0x07, 4, bitmask),
PWRITE(peci_4domain, 0, PRI_LOW, 0x0e, 0, 0x01, 4, bitmask),
};
static struct asc7621_data *asc7621_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct asc7621_data *data = i2c_get_clientdata(client);
int i;
/*
* The asc7621 chips guarantee consistent reads of multi-byte values
* regardless of the order of the reads. No special logic is needed
* so we can just read the registers in whatever order they appear
* in the asc7621_params array.
*/
mutex_lock(&data->update_lock);
/* Read all the high priority registers */
if (!data->valid ||
time_after(jiffies, data->last_high_reading + INTERVAL_HIGH)) {
for (i = 0; i < ARRAY_SIZE(asc7621_register_priorities); i++) {
if (asc7621_register_priorities[i] == PRI_HIGH) {
data->reg[i] =
i2c_smbus_read_byte_data(client, i) & 0xff;
}
}
data->last_high_reading = jiffies;
}; /* last_reading */
/* Read all the low priority registers. */
if (!data->valid ||
time_after(jiffies, data->last_low_reading + INTERVAL_LOW)) {
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
if (asc7621_register_priorities[i] == PRI_LOW) {
data->reg[i] =
i2c_smbus_read_byte_data(client, i) & 0xff;
}
}
data->last_low_reading = jiffies;
}; /* last_reading */
data->valid = 1;
mutex_unlock(&data->update_lock);
return data;
}
/*
* Standard detection and initialization below
*
* Helper function that checks if an address is valid
* for a particular chip.
*/
static inline int valid_address_for_chip(int chip_type, int address)
{
int i;
for (i = 0; asc7621_chips[chip_type].addresses[i] != I2C_CLIENT_END;
i++) {
if (asc7621_chips[chip_type].addresses[i] == address)
return 1;
}
return 0;
}
static void asc7621_init_client(struct i2c_client *client)
{
int value;
/* Warn if part was not "READY" */
value = read_byte(client, 0x40);
if (value & 0x02) {
dev_err(&client->dev,
"Client (%d,0x%02x) config is locked.\n",
i2c_adapter_id(client->adapter), client->addr);
};
if (!(value & 0x04)) {
dev_err(&client->dev, "Client (%d,0x%02x) is not ready.\n",
i2c_adapter_id(client->adapter), client->addr);
};
/*
* Start monitoring
*
* Try to clear LOCK, Set START, save everything else
*/
value = (value & ~0x02) | 0x01;
write_byte(client, 0x40, value & 0xff);
}
static int
asc7621_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct asc7621_data *data;
int i, err;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
data = devm_kzalloc(&client->dev, sizeof(struct asc7621_data),
GFP_KERNEL);
if (data == NULL)
return -ENOMEM;
i2c_set_clientdata(client, data);
data->valid = 0;
mutex_init(&data->update_lock);
/* Initialize the asc7621 chip */
asc7621_init_client(client);
/* Create the sysfs entries */
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
err =
device_create_file(&client->dev,
&(asc7621_params[i].sda.dev_attr));
if (err)
goto exit_remove;
}
data->class_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->class_dev)) {
err = PTR_ERR(data->class_dev);
goto exit_remove;
}
return 0;
exit_remove:
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
device_remove_file(&client->dev,
&(asc7621_params[i].sda.dev_attr));
}
return err;
}
static int asc7621_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
int company, verstep, chip_index;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
for (chip_index = FIRST_CHIP; chip_index <= LAST_CHIP; chip_index++) {
if (!valid_address_for_chip(chip_index, client->addr))
continue;
company = read_byte(client,
asc7621_chips[chip_index].company_reg);
verstep = read_byte(client,
asc7621_chips[chip_index].verstep_reg);
if (company == asc7621_chips[chip_index].company_id &&
verstep == asc7621_chips[chip_index].verstep_id) {
strlcpy(info->type, asc7621_chips[chip_index].name,
I2C_NAME_SIZE);
dev_info(&adapter->dev, "Matched %s at 0x%02x\n",
asc7621_chips[chip_index].name, client->addr);
return 0;
}
}
return -ENODEV;
}
static int asc7621_remove(struct i2c_client *client)
{
struct asc7621_data *data = i2c_get_clientdata(client);
int i;
hwmon_device_unregister(data->class_dev);
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
device_remove_file(&client->dev,
&(asc7621_params[i].sda.dev_attr));
}
return 0;
}
static const struct i2c_device_id asc7621_id[] = {
{"asc7621", asc7621},
{"asc7621a", asc7621a},
{},
};
MODULE_DEVICE_TABLE(i2c, asc7621_id);
static struct i2c_driver asc7621_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "asc7621",
},
.probe = asc7621_probe,
.remove = asc7621_remove,
.id_table = asc7621_id,
.detect = asc7621_detect,
.address_list = normal_i2c,
};
static int __init sm_asc7621_init(void)
{
int i, j;
/*
* Collect all the registers needed into a single array.
* This way, if a register isn't actually used for anything,
* we don't retrieve it.
*/
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
for (j = 0; j < ARRAY_SIZE(asc7621_params[i].msb); j++)
asc7621_register_priorities[asc7621_params[i].msb[j]] =
asc7621_params[i].priority;
for (j = 0; j < ARRAY_SIZE(asc7621_params[i].lsb); j++)
asc7621_register_priorities[asc7621_params[i].lsb[j]] =
asc7621_params[i].priority;
}
return i2c_add_driver(&asc7621_driver);
}
static void __exit sm_asc7621_exit(void)
{
i2c_del_driver(&asc7621_driver);
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("George Joseph");
MODULE_DESCRIPTION("Andigilog aSC7621 and aSC7621a driver");
module_init(sm_asc7621_init);
module_exit(sm_asc7621_exit);
| gpl-2.0 |
javelinanddart/shamu | drivers/scsi/atari_NCR5380.c | 2499 | 92227 | /*
* NCR 5380 generic driver routines. These should make it *trivial*
* to implement 5380 SCSI drivers under Linux with a non-trantor
* architecture.
*
* Note that these routines also work with NR53c400 family chips.
*
* Copyright 1993, Drew Eckhardt
* Visionary Computing
* (Unix and Linux consulting and custom programming)
* drew@colorado.edu
* +1 (303) 666-5836
*
* DISTRIBUTION RELEASE 6.
*
* For more information, please consult
*
* NCR 5380 Family
* SCSI Protocol Controller
* Databook
*
* NCR Microelectronics
* 1635 Aeroplaza Drive
* Colorado Springs, CO 80916
* 1+ (719) 578-3400
* 1+ (800) 334-5454
*/
/*
* ++roman: To port the 5380 driver to the Atari, I had to do some changes in
* this file, too:
*
* - Some of the debug statements were incorrect (undefined variables and the
* like). I fixed that.
*
* - In information_transfer(), I think a #ifdef was wrong. Looking at the
* possible DMA transfer size should also happen for REAL_DMA. I added this
* in the #if statement.
*
* - When using real DMA, information_transfer() should return in a DATAOUT
* phase after starting the DMA. It has nothing more to do.
*
* - The interrupt service routine should run main after end of DMA, too (not
* only after RESELECTION interrupts). Additionally, it should _not_ test
* for more interrupts after running main, since a DMA process may have
* been started and interrupts are turned on now. The new int could happen
* inside the execution of NCR5380_intr(), leading to recursive
* calls.
*
* - I've added a function merge_contiguous_buffers() that tries to
* merge scatter-gather buffers that are located at contiguous
* physical addresses and can be processed with the same DMA setup.
* Since most scatter-gather operations work on a page (4K) of
* 4 buffers (1K), in more than 90% of all cases three interrupts and
* DMA setup actions are saved.
*
* - I've deleted all the stuff for AUTOPROBE_IRQ, REAL_DMA_POLL, PSEUDO_DMA
* and USLEEP, because these were messing up readability and will never be
* needed for Atari SCSI.
*
* - I've revised the NCR5380_main() calling scheme (relax the 'main_running'
* stuff), and 'main' is executed in a bottom half if awoken by an
* interrupt.
*
* - The code was quite cluttered up by "#if (NDEBUG & NDEBUG_*) printk..."
* constructs. In my eyes, this made the source rather unreadable, so I
* finally replaced that by the *_PRINTK() macros.
*
*/
/*
* Further development / testing that should be done :
* 1. Test linked command handling code after Eric is ready with
* the high level code.
*/
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_transport_spi.h>
#if (NDEBUG & NDEBUG_LISTS)
#define LIST(x, y) \
do { \
printk("LINE:%d Adding %p to %p\n", \
__LINE__, (void*)(x), (void*)(y)); \
if ((x) == (y)) \
udelay(5); \
} while (0)
#define REMOVE(w, x, y, z) \
do { \
printk("LINE:%d Removing: %p->%p %p->%p \n", \
__LINE__, (void*)(w), (void*)(x), \
(void*)(y), (void*)(z)); \
if ((x) == (y)) \
udelay(5); \
} while (0)
#else
#define LIST(x,y)
#define REMOVE(w,x,y,z)
#endif
#ifndef notyet
#undef LINKED
#endif
/*
* Design
* Issues :
*
* The other Linux SCSI drivers were written when Linux was Intel PC-only,
* and specifically for each board rather than each chip. This makes their
* adaptation to platforms like the Mac (Some of which use NCR5380's)
* more difficult than it has to be.
*
* Also, many of the SCSI drivers were written before the command queuing
* routines were implemented, meaning their implementations of queued
* commands were hacked on rather than designed in from the start.
*
* When I designed the Linux SCSI drivers I figured that
* while having two different SCSI boards in a system might be useful
* for debugging things, two of the same type wouldn't be used.
* Well, I was wrong and a number of users have mailed me about running
* multiple high-performance SCSI boards in a server.
*
* Finally, when I get questions from users, I have no idea what
* revision of my driver they are running.
*
* This driver attempts to address these problems :
* This is a generic 5380 driver. To use it on a different platform,
* one simply writes appropriate system specific macros (ie, data
* transfer - some PC's will use the I/O bus, 68K's must use
* memory mapped) and drops this file in their 'C' wrapper.
*
* As far as command queueing, two queues are maintained for
* each 5380 in the system - commands that haven't been issued yet,
* and commands that are currently executing. This means that an
* unlimited number of commands may be queued, letting
* more commands propagate from the higher driver levels giving higher
* throughput. Note that both I_T_L and I_T_L_Q nexuses are supported,
* allowing multiple commands to propagate all the way to a SCSI-II device
* while a command is already executing.
*
* To solve the multiple-boards-in-the-same-system problem,
* there is a separate instance structure for each instance
* of a 5380 in the system. So, multiple NCR5380 drivers will
* be able to coexist with appropriate changes to the high level
* SCSI code.
*
* A NCR5380_PUBLIC_REVISION macro is provided, with the release
* number (updated for each public release) printed by the
* NCR5380_print_options command, which should be called from the
* wrapper detect function, so that I know what release of the driver
* users are using.
*
* Issues specific to the NCR5380 :
*
* When used in a PIO or pseudo-dma mode, the NCR5380 is a braindead
* piece of hardware that requires you to sit in a loop polling for
* the REQ signal as long as you are connected. Some devices are
* brain dead (ie, many TEXEL CD ROM drives) and won't disconnect
* while doing long seek operations.
*
* The workaround for this is to keep track of devices that have
* disconnected. If the device hasn't disconnected, for commands that
* should disconnect, we do something like
*
* while (!REQ is asserted) { sleep for N usecs; poll for M usecs }
*
* Some tweaking of N and M needs to be done. An algorithm based
* on "time to data" would give the best results as long as short time
* to datas (ie, on the same track) were considered, however these
* broken devices are the exception rather than the rule and I'd rather
* spend my time optimizing for the normal case.
*
* Architecture :
*
* At the heart of the design is a coroutine, NCR5380_main,
* which is started when not running by the interrupt handler,
* timer, and queue command function. It attempts to establish
* I_T_L or I_T_L_Q nexuses by removing the commands from the
* issue queue and calling NCR5380_select() if a nexus
* is not established.
*
* Once a nexus is established, the NCR5380_information_transfer()
* phase goes through the various phases as instructed by the target.
* if the target goes into MSG IN and sends a DISCONNECT message,
* the command structure is placed into the per instance disconnected
* queue, and NCR5380_main tries to find more work. If USLEEP
* was defined, and the target is idle for too long, the system
* will try to sleep.
*
* If a command has disconnected, eventually an interrupt will trigger,
* calling NCR5380_intr() which will in turn call NCR5380_reselect
* to reestablish a nexus. This will run main if necessary.
*
* On command termination, the done function will be called as
* appropriate.
*
* SCSI pointers are maintained in the SCp field of SCSI command
* structures, being initialized after the command is connected
* in NCR5380_select, and set as appropriate in NCR5380_information_transfer.
* Note that in violation of the standard, an implicit SAVE POINTERS operation
* is done, since some BROKEN disks fail to issue an explicit SAVE POINTERS.
*/
/*
* Using this file :
* This file a skeleton Linux SCSI driver for the NCR 5380 series
* of chips. To use it, you write an architecture specific functions
* and macros and include this file in your driver.
*
* These macros control options :
* AUTOSENSE - if defined, REQUEST SENSE will be performed automatically
* for commands that return with a CHECK CONDITION status.
*
* LINKED - if defined, linked commands are supported.
*
* REAL_DMA - if defined, REAL DMA is used during the data transfer phases.
*
* SUPPORT_TAGS - if defined, SCSI-2 tagged queuing is used where possible
*
* These macros MUST be defined :
*
* NCR5380_read(register) - read from the specified register
*
* NCR5380_write(register, value) - write to the specific register
*
* Either real DMA *or* pseudo DMA may be implemented
* REAL functions :
* NCR5380_REAL_DMA should be defined if real DMA is to be used.
* Note that the DMA setup functions should return the number of bytes
* that they were able to program the controller for.
*
* Also note that generic i386/PC versions of these macros are
* available as NCR5380_i386_dma_write_setup,
* NCR5380_i386_dma_read_setup, and NCR5380_i386_dma_residual.
*
* NCR5380_dma_write_setup(instance, src, count) - initialize
* NCR5380_dma_read_setup(instance, dst, count) - initialize
* NCR5380_dma_residual(instance); - residual count
*
* PSEUDO functions :
* NCR5380_pwrite(instance, src, count)
* NCR5380_pread(instance, dst, count);
*
* If nothing specific to this implementation needs doing (ie, with external
* hardware), you must also define
*
* NCR5380_queue_command
* NCR5380_reset
* NCR5380_abort
* NCR5380_proc_info
*
* to be the global entry points into the specific driver, ie
* #define NCR5380_queue_command t128_queue_command.
*
* If this is not done, the routines will be defined as static functions
* with the NCR5380* names and the user must provide a globally
* accessible wrapper function.
*
* The generic driver is initialized by calling NCR5380_init(instance),
* after setting the appropriate host specific fields and ID. If the
* driver wishes to autoprobe for an IRQ line, the NCR5380_probe_irq(instance,
* possible) function may be used. Before the specific driver initialization
* code finishes, NCR5380_print_options should be called.
*/
static struct Scsi_Host *first_instance = NULL;
static struct scsi_host_template *the_template = NULL;
/* Macros ease life... :-) */
#define SETUP_HOSTDATA(in) \
struct NCR5380_hostdata *hostdata = \
(struct NCR5380_hostdata *)(in)->hostdata
#define HOSTDATA(in) ((struct NCR5380_hostdata *)(in)->hostdata)
#define NEXT(cmd) ((Scsi_Cmnd *)(cmd)->host_scribble)
#define SET_NEXT(cmd,next) ((cmd)->host_scribble = (void *)(next))
#define NEXTADDR(cmd) ((Scsi_Cmnd **)&(cmd)->host_scribble)
#define HOSTNO instance->host_no
#define H_NO(cmd) (cmd)->device->host->host_no
#ifdef SUPPORT_TAGS
/*
* Functions for handling tagged queuing
* =====================================
*
* ++roman (01/96): Now I've implemented SCSI-2 tagged queuing. Some notes:
*
* Using consecutive numbers for the tags is no good idea in my eyes. There
* could be wrong re-usings if the counter (8 bit!) wraps and some early
* command has been preempted for a long time. My solution: a bitfield for
* remembering used tags.
*
* There's also the problem that each target has a certain queue size, but we
* cannot know it in advance :-( We just see a QUEUE_FULL status being
* returned. So, in this case, the driver internal queue size assumption is
* reduced to the number of active tags if QUEUE_FULL is returned by the
* target. The command is returned to the mid-level, but with status changed
* to BUSY, since --as I've seen-- the mid-level can't handle QUEUE_FULL
* correctly.
*
* We're also not allowed running tagged commands as long as an untagged
* command is active. And REQUEST SENSE commands after a contingent allegiance
* condition _must_ be untagged. To keep track whether an untagged command has
* been issued, the host->busy array is still employed, as it is without
* support for tagged queuing.
*
* One could suspect that there are possible race conditions between
* is_lun_busy(), cmd_get_tag() and cmd_free_tag(). But I think this isn't the
* case: is_lun_busy() and cmd_get_tag() are both called from NCR5380_main(),
* which already guaranteed to be running at most once. It is also the only
* place where tags/LUNs are allocated. So no other allocation can slip
* between that pair, there could only happen a reselection, which can free a
* tag, but that doesn't hurt. Only the sequence in cmd_free_tag() becomes
* important: the tag bit must be cleared before 'nr_allocated' is decreased.
*/
/* -1 for TAG_NONE is not possible with unsigned char cmd->tag */
#undef TAG_NONE
#define TAG_NONE 0xff
typedef struct {
DECLARE_BITMAP(allocated, MAX_TAGS);
int nr_allocated;
int queue_size;
} TAG_ALLOC;
static TAG_ALLOC TagAlloc[8][8]; /* 8 targets and 8 LUNs */
static void __init init_tags(void)
{
int target, lun;
TAG_ALLOC *ta;
if (!setup_use_tagged_queuing)
return;
for (target = 0; target < 8; ++target) {
for (lun = 0; lun < 8; ++lun) {
ta = &TagAlloc[target][lun];
bitmap_zero(ta->allocated, MAX_TAGS);
ta->nr_allocated = 0;
/* At the beginning, assume the maximum queue size we could
* support (MAX_TAGS). This value will be decreased if the target
* returns QUEUE_FULL status.
*/
ta->queue_size = MAX_TAGS;
}
}
}
/* Check if we can issue a command to this LUN: First see if the LUN is marked
* busy by an untagged command. If the command should use tagged queuing, also
* check that there is a free tag and the target's queue won't overflow. This
* function should be called with interrupts disabled to avoid race
* conditions.
*/
static int is_lun_busy(Scsi_Cmnd *cmd, int should_be_tagged)
{
SETUP_HOSTDATA(cmd->device->host);
if (hostdata->busy[cmd->device->id] & (1 << cmd->device->lun))
return 1;
if (!should_be_tagged ||
!setup_use_tagged_queuing || !cmd->device->tagged_supported)
return 0;
if (TagAlloc[cmd->device->id][cmd->device->lun].nr_allocated >=
TagAlloc[cmd->device->id][cmd->device->lun].queue_size) {
TAG_PRINTK("scsi%d: target %d lun %d: no free tags\n",
H_NO(cmd), cmd->device->id, cmd->device->lun);
return 1;
}
return 0;
}
/* Allocate a tag for a command (there are no checks anymore, check_lun_busy()
* must be called before!), or reserve the LUN in 'busy' if the command is
* untagged.
*/
static void cmd_get_tag(Scsi_Cmnd *cmd, int should_be_tagged)
{
SETUP_HOSTDATA(cmd->device->host);
/* If we or the target don't support tagged queuing, allocate the LUN for
* an untagged command.
*/
if (!should_be_tagged ||
!setup_use_tagged_queuing || !cmd->device->tagged_supported) {
cmd->tag = TAG_NONE;
hostdata->busy[cmd->device->id] |= (1 << cmd->device->lun);
TAG_PRINTK("scsi%d: target %d lun %d now allocated by untagged "
"command\n", H_NO(cmd), cmd->device->id, cmd->device->lun);
} else {
TAG_ALLOC *ta = &TagAlloc[cmd->device->id][cmd->device->lun];
cmd->tag = find_first_zero_bit(ta->allocated, MAX_TAGS);
set_bit(cmd->tag, ta->allocated);
ta->nr_allocated++;
TAG_PRINTK("scsi%d: using tag %d for target %d lun %d "
"(now %d tags in use)\n",
H_NO(cmd), cmd->tag, cmd->device->id,
cmd->device->lun, ta->nr_allocated);
}
}
/* Mark the tag of command 'cmd' as free, or in case of an untagged command,
* unlock the LUN.
*/
static void cmd_free_tag(Scsi_Cmnd *cmd)
{
SETUP_HOSTDATA(cmd->device->host);
if (cmd->tag == TAG_NONE) {
hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
TAG_PRINTK("scsi%d: target %d lun %d untagged cmd finished\n",
H_NO(cmd), cmd->device->id, cmd->device->lun);
} else if (cmd->tag >= MAX_TAGS) {
printk(KERN_NOTICE "scsi%d: trying to free bad tag %d!\n",
H_NO(cmd), cmd->tag);
} else {
TAG_ALLOC *ta = &TagAlloc[cmd->device->id][cmd->device->lun];
clear_bit(cmd->tag, ta->allocated);
ta->nr_allocated--;
TAG_PRINTK("scsi%d: freed tag %d for target %d lun %d\n",
H_NO(cmd), cmd->tag, cmd->device->id, cmd->device->lun);
}
}
static void free_all_tags(void)
{
int target, lun;
TAG_ALLOC *ta;
if (!setup_use_tagged_queuing)
return;
for (target = 0; target < 8; ++target) {
for (lun = 0; lun < 8; ++lun) {
ta = &TagAlloc[target][lun];
bitmap_zero(ta->allocated, MAX_TAGS);
ta->nr_allocated = 0;
}
}
}
#endif /* SUPPORT_TAGS */
/*
* Function: void merge_contiguous_buffers( Scsi_Cmnd *cmd )
*
* Purpose: Try to merge several scatter-gather requests into one DMA
* transfer. This is possible if the scatter buffers lie on
* physical contiguous addresses.
*
* Parameters: Scsi_Cmnd *cmd
* The command to work on. The first scatter buffer's data are
* assumed to be already transferred into ptr/this_residual.
*/
static void merge_contiguous_buffers(Scsi_Cmnd *cmd)
{
unsigned long endaddr;
#if (NDEBUG & NDEBUG_MERGING)
unsigned long oldlen = cmd->SCp.this_residual;
int cnt = 1;
#endif
for (endaddr = virt_to_phys(cmd->SCp.ptr + cmd->SCp.this_residual - 1) + 1;
cmd->SCp.buffers_residual &&
virt_to_phys(sg_virt(&cmd->SCp.buffer[1])) == endaddr;) {
MER_PRINTK("VTOP(%p) == %08lx -> merging\n",
page_address(sg_page(&cmd->SCp.buffer[1])), endaddr);
#if (NDEBUG & NDEBUG_MERGING)
++cnt;
#endif
++cmd->SCp.buffer;
--cmd->SCp.buffers_residual;
cmd->SCp.this_residual += cmd->SCp.buffer->length;
endaddr += cmd->SCp.buffer->length;
}
#if (NDEBUG & NDEBUG_MERGING)
if (oldlen != cmd->SCp.this_residual)
MER_PRINTK("merged %d buffers from %p, new length %08x\n",
cnt, cmd->SCp.ptr, cmd->SCp.this_residual);
#endif
}
/*
* Function : void initialize_SCp(Scsi_Cmnd *cmd)
*
* Purpose : initialize the saved data pointers for cmd to point to the
* start of the buffer.
*
* Inputs : cmd - Scsi_Cmnd structure to have pointers reset.
*/
static inline void initialize_SCp(Scsi_Cmnd *cmd)
{
/*
* Initialize the Scsi Pointer field so that all of the commands in the
* various queues are valid.
*/
if (scsi_bufflen(cmd)) {
cmd->SCp.buffer = scsi_sglist(cmd);
cmd->SCp.buffers_residual = scsi_sg_count(cmd) - 1;
cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
cmd->SCp.this_residual = cmd->SCp.buffer->length;
/* ++roman: Try to merge some scatter-buffers if they are at
* contiguous physical addresses.
*/
merge_contiguous_buffers(cmd);
} else {
cmd->SCp.buffer = NULL;
cmd->SCp.buffers_residual = 0;
cmd->SCp.ptr = NULL;
cmd->SCp.this_residual = 0;
}
}
#include <linux/delay.h>
#if NDEBUG
static struct {
unsigned char mask;
const char *name;
} signals[] = {
{ SR_DBP, "PARITY"}, { SR_RST, "RST" }, { SR_BSY, "BSY" },
{ SR_REQ, "REQ" }, { SR_MSG, "MSG" }, { SR_CD, "CD" }, { SR_IO, "IO" },
{ SR_SEL, "SEL" }, {0, NULL}
}, basrs[] = {
{BASR_ATN, "ATN"}, {BASR_ACK, "ACK"}, {0, NULL}
}, icrs[] = {
{ICR_ASSERT_RST, "ASSERT RST"},{ICR_ASSERT_ACK, "ASSERT ACK"},
{ICR_ASSERT_BSY, "ASSERT BSY"}, {ICR_ASSERT_SEL, "ASSERT SEL"},
{ICR_ASSERT_ATN, "ASSERT ATN"}, {ICR_ASSERT_DATA, "ASSERT DATA"},
{0, NULL}
}, mrs[] = {
{MR_BLOCK_DMA_MODE, "MODE BLOCK DMA"}, {MR_TARGET, "MODE TARGET"},
{MR_ENABLE_PAR_CHECK, "MODE PARITY CHECK"}, {MR_ENABLE_PAR_INTR,
"MODE PARITY INTR"}, {MR_ENABLE_EOP_INTR,"MODE EOP INTR"},
{MR_MONITOR_BSY, "MODE MONITOR BSY"},
{MR_DMA_MODE, "MODE DMA"}, {MR_ARBITRATE, "MODE ARBITRATION"},
{0, NULL}
};
/*
* Function : void NCR5380_print(struct Scsi_Host *instance)
*
* Purpose : print the SCSI bus signals for debugging purposes
*
* Input : instance - which NCR5380
*/
static void NCR5380_print(struct Scsi_Host *instance)
{
unsigned char status, data, basr, mr, icr, i;
unsigned long flags;
local_irq_save(flags);
data = NCR5380_read(CURRENT_SCSI_DATA_REG);
status = NCR5380_read(STATUS_REG);
mr = NCR5380_read(MODE_REG);
icr = NCR5380_read(INITIATOR_COMMAND_REG);
basr = NCR5380_read(BUS_AND_STATUS_REG);
local_irq_restore(flags);
printk("STATUS_REG: %02x ", status);
for (i = 0; signals[i].mask; ++i)
if (status & signals[i].mask)
printk(",%s", signals[i].name);
printk("\nBASR: %02x ", basr);
for (i = 0; basrs[i].mask; ++i)
if (basr & basrs[i].mask)
printk(",%s", basrs[i].name);
printk("\nICR: %02x ", icr);
for (i = 0; icrs[i].mask; ++i)
if (icr & icrs[i].mask)
printk(",%s", icrs[i].name);
printk("\nMODE: %02x ", mr);
for (i = 0; mrs[i].mask; ++i)
if (mr & mrs[i].mask)
printk(",%s", mrs[i].name);
printk("\n");
}
static struct {
unsigned char value;
const char *name;
} phases[] = {
{PHASE_DATAOUT, "DATAOUT"}, {PHASE_DATAIN, "DATAIN"}, {PHASE_CMDOUT, "CMDOUT"},
{PHASE_STATIN, "STATIN"}, {PHASE_MSGOUT, "MSGOUT"}, {PHASE_MSGIN, "MSGIN"},
{PHASE_UNKNOWN, "UNKNOWN"}
};
/*
* Function : void NCR5380_print_phase(struct Scsi_Host *instance)
*
* Purpose : print the current SCSI phase for debugging purposes
*
* Input : instance - which NCR5380
*/
static void NCR5380_print_phase(struct Scsi_Host *instance)
{
unsigned char status;
int i;
status = NCR5380_read(STATUS_REG);
if (!(status & SR_REQ))
printk(KERN_DEBUG "scsi%d: REQ not asserted, phase unknown.\n", HOSTNO);
else {
for (i = 0; (phases[i].value != PHASE_UNKNOWN) &&
(phases[i].value != (status & PHASE_MASK)); ++i)
;
printk(KERN_DEBUG "scsi%d: phase %s\n", HOSTNO, phases[i].name);
}
}
#else /* !NDEBUG */
/* dummies... */
static inline void NCR5380_print(struct Scsi_Host *instance)
{
};
static inline void NCR5380_print_phase(struct Scsi_Host *instance)
{
};
#endif
/*
* ++roman: New scheme of calling NCR5380_main()
*
* If we're not in an interrupt, we can call our main directly, it cannot be
* already running. Else, we queue it on a task queue, if not 'main_running'
* tells us that a lower level is already executing it. This way,
* 'main_running' needs not be protected in a special way.
*
* queue_main() is a utility function for putting our main onto the task
* queue, if main_running is false. It should be called only from a
* interrupt or bottom half.
*/
#include <linux/gfp.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
static volatile int main_running;
static DECLARE_WORK(NCR5380_tqueue, NCR5380_main);
static inline void queue_main(void)
{
if (!main_running) {
/* If in interrupt and NCR5380_main() not already running,
queue it on the 'immediate' task queue, to be processed
immediately after the current interrupt processing has
finished. */
schedule_work(&NCR5380_tqueue);
}
/* else: nothing to do: the running NCR5380_main() will pick up
any newly queued command. */
}
static inline void NCR5380_all_init(void)
{
static int done = 0;
if (!done) {
INI_PRINTK("scsi : NCR5380_all_init()\n");
done = 1;
}
}
/*
* Function : void NCR58380_print_options (struct Scsi_Host *instance)
*
* Purpose : called by probe code indicating the NCR5380 driver
* options that were selected.
*
* Inputs : instance, pointer to this instance. Unused.
*/
static void __init NCR5380_print_options(struct Scsi_Host *instance)
{
printk(" generic options"
#ifdef AUTOSENSE
" AUTOSENSE"
#endif
#ifdef REAL_DMA
" REAL DMA"
#endif
#ifdef PARITY
" PARITY"
#endif
#ifdef SUPPORT_TAGS
" SCSI-2 TAGGED QUEUING"
#endif
);
printk(" generic release=%d", NCR5380_PUBLIC_RELEASE);
}
/*
* Function : void NCR5380_print_status (struct Scsi_Host *instance)
*
* Purpose : print commands in the various queues, called from
* NCR5380_abort and NCR5380_debug to aid debugging.
*
* Inputs : instance, pointer to this instance.
*/
static void lprint_Scsi_Cmnd(Scsi_Cmnd *cmd)
{
int i, s;
unsigned char *command;
printk("scsi%d: destination target %d, lun %d\n",
H_NO(cmd), cmd->device->id, cmd->device->lun);
printk(KERN_CONT " command = ");
command = cmd->cmnd;
printk(KERN_CONT "%2d (0x%02x)", command[0], command[0]);
for (i = 1, s = COMMAND_SIZE(command[0]); i < s; ++i)
printk(KERN_CONT " %02x", command[i]);
printk("\n");
}
static void NCR5380_print_status(struct Scsi_Host *instance)
{
struct NCR5380_hostdata *hostdata;
Scsi_Cmnd *ptr;
unsigned long flags;
NCR_PRINT(NDEBUG_ANY);
NCR_PRINT_PHASE(NDEBUG_ANY);
hostdata = (struct NCR5380_hostdata *)instance->hostdata;
printk("\nNCR5380 core release=%d.\n", NCR5380_PUBLIC_RELEASE);
local_irq_save(flags);
printk("NCR5380: coroutine is%s running.\n",
main_running ? "" : "n't");
if (!hostdata->connected)
printk("scsi%d: no currently connected command\n", HOSTNO);
else
lprint_Scsi_Cmnd((Scsi_Cmnd *) hostdata->connected);
printk("scsi%d: issue_queue\n", HOSTNO);
for (ptr = (Scsi_Cmnd *)hostdata->issue_queue; ptr; ptr = NEXT(ptr))
lprint_Scsi_Cmnd(ptr);
printk("scsi%d: disconnected_queue\n", HOSTNO);
for (ptr = (Scsi_Cmnd *) hostdata->disconnected_queue; ptr;
ptr = NEXT(ptr))
lprint_Scsi_Cmnd(ptr);
local_irq_restore(flags);
printk("\n");
}
static void show_Scsi_Cmnd(Scsi_Cmnd *cmd, struct seq_file *m)
{
int i, s;
unsigned char *command;
seq_printf(m, "scsi%d: destination target %d, lun %d\n",
H_NO(cmd), cmd->device->id, cmd->device->lun);
seq_printf(m, " command = ");
command = cmd->cmnd;
seq_printf(m, "%2d (0x%02x)", command[0], command[0]);
for (i = 1, s = COMMAND_SIZE(command[0]); i < s; ++i)
seq_printf(m, " %02x", command[i]);
seq_printf(m, "\n");
}
static int NCR5380_show_info(struct seq_file *m, struct Scsi_Host *instance)
{
struct NCR5380_hostdata *hostdata;
Scsi_Cmnd *ptr;
unsigned long flags;
hostdata = (struct NCR5380_hostdata *)instance->hostdata;
seq_printf(m, "NCR5380 core release=%d.\n", NCR5380_PUBLIC_RELEASE);
local_irq_save(flags);
seq_printf(m, "NCR5380: coroutine is%s running.\n",
main_running ? "" : "n't");
if (!hostdata->connected)
seq_printf(m, "scsi%d: no currently connected command\n", HOSTNO);
else
show_Scsi_Cmnd((Scsi_Cmnd *) hostdata->connected, m);
seq_printf(m, "scsi%d: issue_queue\n", HOSTNO);
for (ptr = (Scsi_Cmnd *)hostdata->issue_queue; ptr; ptr = NEXT(ptr))
show_Scsi_Cmnd(ptr, m);
seq_printf(m, "scsi%d: disconnected_queue\n", HOSTNO);
for (ptr = (Scsi_Cmnd *) hostdata->disconnected_queue; ptr;
ptr = NEXT(ptr))
show_Scsi_Cmnd(ptr, m);
local_irq_restore(flags);
return 0;
}
/*
* Function : void NCR5380_init (struct Scsi_Host *instance)
*
* Purpose : initializes *instance and corresponding 5380 chip.
*
* Inputs : instance - instantiation of the 5380 driver.
*
* Notes : I assume that the host, hostno, and id bits have been
* set correctly. I don't care about the irq and other fields.
*
*/
static int __init NCR5380_init(struct Scsi_Host *instance, int flags)
{
int i;
SETUP_HOSTDATA(instance);
NCR5380_all_init();
hostdata->aborted = 0;
hostdata->id_mask = 1 << instance->this_id;
hostdata->id_higher_mask = 0;
for (i = hostdata->id_mask; i <= 0x80; i <<= 1)
if (i > hostdata->id_mask)
hostdata->id_higher_mask |= i;
for (i = 0; i < 8; ++i)
hostdata->busy[i] = 0;
#ifdef SUPPORT_TAGS
init_tags();
#endif
#if defined (REAL_DMA)
hostdata->dma_len = 0;
#endif
hostdata->targets_present = 0;
hostdata->connected = NULL;
hostdata->issue_queue = NULL;
hostdata->disconnected_queue = NULL;
hostdata->flags = FLAG_CHECK_LAST_BYTE_SENT;
if (!the_template) {
the_template = instance->hostt;
first_instance = instance;
}
#ifndef AUTOSENSE
if ((instance->cmd_per_lun > 1) || (instance->can_queue > 1))
printk("scsi%d: WARNING : support for multiple outstanding commands enabled\n"
" without AUTOSENSE option, contingent allegiance conditions may\n"
" be incorrectly cleared.\n", HOSTNO);
#endif /* def AUTOSENSE */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
NCR5380_write(MODE_REG, MR_BASE);
NCR5380_write(TARGET_COMMAND_REG, 0);
NCR5380_write(SELECT_ENABLE_REG, 0);
return 0;
}
static void NCR5380_exit(struct Scsi_Host *instance)
{
/* Empty, as we didn't schedule any delayed work */
}
/*
* Function : int NCR5380_queue_command (Scsi_Cmnd *cmd,
* void (*done)(Scsi_Cmnd *))
*
* Purpose : enqueues a SCSI command
*
* Inputs : cmd - SCSI command, done - function called on completion, with
* a pointer to the command descriptor.
*
* Returns : 0
*
* Side effects :
* cmd is added to the per instance issue_queue, with minor
* twiddling done to the host specific fields of cmd. If the
* main coroutine is not running, it is restarted.
*
*/
static int NCR5380_queue_command_lck(Scsi_Cmnd *cmd, void (*done)(Scsi_Cmnd *))
{
SETUP_HOSTDATA(cmd->device->host);
Scsi_Cmnd *tmp;
unsigned long flags;
#if (NDEBUG & NDEBUG_NO_WRITE)
switch (cmd->cmnd[0]) {
case WRITE_6:
case WRITE_10:
printk(KERN_NOTICE "scsi%d: WRITE attempted with NO_WRITE debugging flag set\n",
H_NO(cmd));
cmd->result = (DID_ERROR << 16);
done(cmd);
return 0;
}
#endif /* (NDEBUG & NDEBUG_NO_WRITE) */
#ifdef NCR5380_STATS
# if 0
if (!hostdata->connected && !hostdata->issue_queue &&
!hostdata->disconnected_queue) {
hostdata->timebase = jiffies;
}
# endif
# ifdef NCR5380_STAT_LIMIT
if (scsi_bufflen(cmd) > NCR5380_STAT_LIMIT)
# endif
switch (cmd->cmnd[0]) {
case WRITE:
case WRITE_6:
case WRITE_10:
hostdata->time_write[cmd->device->id] -= (jiffies - hostdata->timebase);
hostdata->bytes_write[cmd->device->id] += scsi_bufflen(cmd);
hostdata->pendingw++;
break;
case READ:
case READ_6:
case READ_10:
hostdata->time_read[cmd->device->id] -= (jiffies - hostdata->timebase);
hostdata->bytes_read[cmd->device->id] += scsi_bufflen(cmd);
hostdata->pendingr++;
break;
}
#endif
/*
* We use the host_scribble field as a pointer to the next command
* in a queue
*/
SET_NEXT(cmd, NULL);
cmd->scsi_done = done;
cmd->result = 0;
/*
* Insert the cmd into the issue queue. Note that REQUEST SENSE
* commands are added to the head of the queue since any command will
* clear the contingent allegiance condition that exists and the
* sense data is only guaranteed to be valid while the condition exists.
*/
local_irq_save(flags);
/* ++guenther: now that the issue queue is being set up, we can lock ST-DMA.
* Otherwise a running NCR5380_main may steal the lock.
* Lock before actually inserting due to fairness reasons explained in
* atari_scsi.c. If we insert first, then it's impossible for this driver
* to release the lock.
* Stop timer for this command while waiting for the lock, or timeouts
* may happen (and they really do), and it's no good if the command doesn't
* appear in any of the queues.
* ++roman: Just disabling the NCR interrupt isn't sufficient here,
* because also a timer int can trigger an abort or reset, which would
* alter queues and touch the lock.
*/
if (!IS_A_TT()) {
/* perhaps stop command timer here */
falcon_get_lock();
/* perhaps restart command timer here */
}
if (!(hostdata->issue_queue) || (cmd->cmnd[0] == REQUEST_SENSE)) {
LIST(cmd, hostdata->issue_queue);
SET_NEXT(cmd, hostdata->issue_queue);
hostdata->issue_queue = cmd;
} else {
for (tmp = (Scsi_Cmnd *)hostdata->issue_queue;
NEXT(tmp); tmp = NEXT(tmp))
;
LIST(cmd, tmp);
SET_NEXT(tmp, cmd);
}
local_irq_restore(flags);
QU_PRINTK("scsi%d: command added to %s of queue\n", H_NO(cmd),
(cmd->cmnd[0] == REQUEST_SENSE) ? "head" : "tail");
/* If queue_command() is called from an interrupt (real one or bottom
* half), we let queue_main() do the job of taking care about main. If it
* is already running, this is a no-op, else main will be queued.
*
* If we're not in an interrupt, we can call NCR5380_main()
* unconditionally, because it cannot be already running.
*/
if (in_interrupt() || ((flags >> 8) & 7) >= 6)
queue_main();
else
NCR5380_main(NULL);
return 0;
}
static DEF_SCSI_QCMD(NCR5380_queue_command)
/*
* Function : NCR5380_main (void)
*
* Purpose : NCR5380_main is a coroutine that runs as long as more work can
* be done on the NCR5380 host adapters in a system. Both
* NCR5380_queue_command() and NCR5380_intr() will try to start it
* in case it is not running.
*
* NOTE : NCR5380_main exits with interrupts *disabled*, the caller should
* reenable them. This prevents reentrancy and kernel stack overflow.
*/
static void NCR5380_main(struct work_struct *work)
{
Scsi_Cmnd *tmp, *prev;
struct Scsi_Host *instance = first_instance;
struct NCR5380_hostdata *hostdata = HOSTDATA(instance);
int done;
unsigned long flags;
/*
* We run (with interrupts disabled) until we're sure that none of
* the host adapters have anything that can be done, at which point
* we set main_running to 0 and exit.
*
* Interrupts are enabled before doing various other internal
* instructions, after we've decided that we need to run through
* the loop again.
*
* this should prevent any race conditions.
*
* ++roman: Just disabling the NCR interrupt isn't sufficient here,
* because also a timer int can trigger an abort or reset, which can
* alter queues and touch the Falcon lock.
*/
/* Tell int handlers main() is now already executing. Note that
no races are possible here. If an int comes in before
'main_running' is set here, and queues/executes main via the
task queue, it doesn't do any harm, just this instance of main
won't find any work left to do. */
if (main_running)
return;
main_running = 1;
local_save_flags(flags);
do {
local_irq_disable(); /* Freeze request queues */
done = 1;
if (!hostdata->connected) {
MAIN_PRINTK("scsi%d: not connected\n", HOSTNO);
/*
* Search through the issue_queue for a command destined
* for a target that's not busy.
*/
#if (NDEBUG & NDEBUG_LISTS)
for (tmp = (Scsi_Cmnd *) hostdata->issue_queue, prev = NULL;
tmp && (tmp != prev); prev = tmp, tmp = NEXT(tmp))
;
/*printk("%p ", tmp);*/
if ((tmp == prev) && tmp)
printk(" LOOP\n");
/* else printk("\n"); */
#endif
for (tmp = (Scsi_Cmnd *) hostdata->issue_queue,
prev = NULL; tmp; prev = tmp, tmp = NEXT(tmp)) {
#if (NDEBUG & NDEBUG_LISTS)
if (prev != tmp)
printk("MAIN tmp=%p target=%d busy=%d lun=%d\n",
tmp, tmp->device->id, hostdata->busy[tmp->device->id],
tmp->device->lun);
#endif
/* When we find one, remove it from the issue queue. */
/* ++guenther: possible race with Falcon locking */
if (
#ifdef SUPPORT_TAGS
!is_lun_busy( tmp, tmp->cmnd[0] != REQUEST_SENSE)
#else
!(hostdata->busy[tmp->device->id] & (1 << tmp->device->lun))
#endif
) {
/* ++guenther: just to be sure, this must be atomic */
local_irq_disable();
if (prev) {
REMOVE(prev, NEXT(prev), tmp, NEXT(tmp));
SET_NEXT(prev, NEXT(tmp));
} else {
REMOVE(-1, hostdata->issue_queue, tmp, NEXT(tmp));
hostdata->issue_queue = NEXT(tmp);
}
SET_NEXT(tmp, NULL);
falcon_dont_release++;
/* reenable interrupts after finding one */
local_irq_restore(flags);
/*
* Attempt to establish an I_T_L nexus here.
* On success, instance->hostdata->connected is set.
* On failure, we must add the command back to the
* issue queue so we can keep trying.
*/
MAIN_PRINTK("scsi%d: main(): command for target %d "
"lun %d removed from issue_queue\n",
HOSTNO, tmp->device->id, tmp->device->lun);
/*
* REQUEST SENSE commands are issued without tagged
* queueing, even on SCSI-II devices because the
* contingent allegiance condition exists for the
* entire unit.
*/
/* ++roman: ...and the standard also requires that
* REQUEST SENSE command are untagged.
*/
#ifdef SUPPORT_TAGS
cmd_get_tag(tmp, tmp->cmnd[0] != REQUEST_SENSE);
#endif
if (!NCR5380_select(instance, tmp,
(tmp->cmnd[0] == REQUEST_SENSE) ? TAG_NONE :
TAG_NEXT)) {
falcon_dont_release--;
/* release if target did not response! */
falcon_release_lock_if_possible(hostdata);
break;
} else {
local_irq_disable();
LIST(tmp, hostdata->issue_queue);
SET_NEXT(tmp, hostdata->issue_queue);
hostdata->issue_queue = tmp;
#ifdef SUPPORT_TAGS
cmd_free_tag(tmp);
#endif
falcon_dont_release--;
local_irq_restore(flags);
MAIN_PRINTK("scsi%d: main(): select() failed, "
"returned to issue_queue\n", HOSTNO);
if (hostdata->connected)
break;
}
} /* if target/lun/target queue is not busy */
} /* for issue_queue */
} /* if (!hostdata->connected) */
if (hostdata->connected
#ifdef REAL_DMA
&& !hostdata->dma_len
#endif
) {
local_irq_restore(flags);
MAIN_PRINTK("scsi%d: main: performing information transfer\n",
HOSTNO);
NCR5380_information_transfer(instance);
MAIN_PRINTK("scsi%d: main: done set false\n", HOSTNO);
done = 0;
}
} while (!done);
/* Better allow ints _after_ 'main_running' has been cleared, else
an interrupt could believe we'll pick up the work it left for
us, but we won't see it anymore here... */
main_running = 0;
local_irq_restore(flags);
}
#ifdef REAL_DMA
/*
* Function : void NCR5380_dma_complete (struct Scsi_Host *instance)
*
* Purpose : Called by interrupt handler when DMA finishes or a phase
* mismatch occurs (which would finish the DMA transfer).
*
* Inputs : instance - this instance of the NCR5380.
*
*/
static void NCR5380_dma_complete(struct Scsi_Host *instance)
{
SETUP_HOSTDATA(instance);
int transfered, saved_data = 0, overrun = 0, cnt, toPIO;
unsigned char **data, p;
volatile int *count;
if (!hostdata->connected) {
printk(KERN_WARNING "scsi%d: received end of DMA interrupt with "
"no connected cmd\n", HOSTNO);
return;
}
if (atari_read_overruns) {
p = hostdata->connected->SCp.phase;
if (p & SR_IO) {
udelay(10);
if ((NCR5380_read(BUS_AND_STATUS_REG) &
(BASR_PHASE_MATCH|BASR_ACK)) ==
(BASR_PHASE_MATCH|BASR_ACK)) {
saved_data = NCR5380_read(INPUT_DATA_REG);
overrun = 1;
DMA_PRINTK("scsi%d: read overrun handled\n", HOSTNO);
}
}
}
DMA_PRINTK("scsi%d: real DMA transfer complete, basr 0x%X, sr 0x%X\n",
HOSTNO, NCR5380_read(BUS_AND_STATUS_REG),
NCR5380_read(STATUS_REG));
(void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
NCR5380_write(MODE_REG, MR_BASE);
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
transfered = hostdata->dma_len - NCR5380_dma_residual(instance);
hostdata->dma_len = 0;
data = (unsigned char **)&hostdata->connected->SCp.ptr;
count = &hostdata->connected->SCp.this_residual;
*data += transfered;
*count -= transfered;
if (atari_read_overruns) {
if ((NCR5380_read(STATUS_REG) & PHASE_MASK) == p && (p & SR_IO)) {
cnt = toPIO = atari_read_overruns;
if (overrun) {
DMA_PRINTK("Got an input overrun, using saved byte\n");
*(*data)++ = saved_data;
(*count)--;
cnt--;
toPIO--;
}
DMA_PRINTK("Doing %d-byte PIO to 0x%08lx\n", cnt, (long)*data);
NCR5380_transfer_pio(instance, &p, &cnt, data);
*count -= toPIO - cnt;
}
}
}
#endif /* REAL_DMA */
/*
* Function : void NCR5380_intr (int irq)
*
* Purpose : handle interrupts, reestablishing I_T_L or I_T_L_Q nexuses
* from the disconnected queue, and restarting NCR5380_main()
* as required.
*
* Inputs : int irq, irq that caused this interrupt.
*
*/
static irqreturn_t NCR5380_intr(int irq, void *dev_id)
{
struct Scsi_Host *instance = first_instance;
int done = 1, handled = 0;
unsigned char basr;
INT_PRINTK("scsi%d: NCR5380 irq triggered\n", HOSTNO);
/* Look for pending interrupts */
basr = NCR5380_read(BUS_AND_STATUS_REG);
INT_PRINTK("scsi%d: BASR=%02x\n", HOSTNO, basr);
/* dispatch to appropriate routine if found and done=0 */
if (basr & BASR_IRQ) {
NCR_PRINT(NDEBUG_INTR);
if ((NCR5380_read(STATUS_REG) & (SR_SEL|SR_IO)) == (SR_SEL|SR_IO)) {
done = 0;
ENABLE_IRQ();
INT_PRINTK("scsi%d: SEL interrupt\n", HOSTNO);
NCR5380_reselect(instance);
(void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
} else if (basr & BASR_PARITY_ERROR) {
INT_PRINTK("scsi%d: PARITY interrupt\n", HOSTNO);
(void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
} else if ((NCR5380_read(STATUS_REG) & SR_RST) == SR_RST) {
INT_PRINTK("scsi%d: RESET interrupt\n", HOSTNO);
(void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
} else {
/*
* The rest of the interrupt conditions can occur only during a
* DMA transfer
*/
#if defined(REAL_DMA)
/*
* We should only get PHASE MISMATCH and EOP interrupts if we have
* DMA enabled, so do a sanity check based on the current setting
* of the MODE register.
*/
if ((NCR5380_read(MODE_REG) & MR_DMA_MODE) &&
((basr & BASR_END_DMA_TRANSFER) ||
!(basr & BASR_PHASE_MATCH))) {
INT_PRINTK("scsi%d: PHASE MISM or EOP interrupt\n", HOSTNO);
NCR5380_dma_complete( instance );
done = 0;
ENABLE_IRQ();
} else
#endif /* REAL_DMA */
{
/* MS: Ignore unknown phase mismatch interrupts (caused by EOP interrupt) */
if (basr & BASR_PHASE_MATCH)
printk(KERN_NOTICE "scsi%d: unknown interrupt, "
"BASR 0x%x, MR 0x%x, SR 0x%x\n",
HOSTNO, basr, NCR5380_read(MODE_REG),
NCR5380_read(STATUS_REG));
(void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
}
} /* if !(SELECTION || PARITY) */
handled = 1;
} /* BASR & IRQ */ else {
printk(KERN_NOTICE "scsi%d: interrupt without IRQ bit set in BASR, "
"BASR 0x%X, MR 0x%X, SR 0x%x\n", HOSTNO, basr,
NCR5380_read(MODE_REG), NCR5380_read(STATUS_REG));
(void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
}
if (!done) {
INT_PRINTK("scsi%d: in int routine, calling main\n", HOSTNO);
/* Put a call to NCR5380_main() on the queue... */
queue_main();
}
return IRQ_RETVAL(handled);
}
#ifdef NCR5380_STATS
static void collect_stats(struct NCR5380_hostdata* hostdata, Scsi_Cmnd *cmd)
{
# ifdef NCR5380_STAT_LIMIT
if (scsi_bufflen(cmd) > NCR5380_STAT_LIMIT)
# endif
switch (cmd->cmnd[0]) {
case WRITE:
case WRITE_6:
case WRITE_10:
hostdata->time_write[cmd->device->id] += (jiffies - hostdata->timebase);
/*hostdata->bytes_write[cmd->device->id] += scsi_bufflen(cmd);*/
hostdata->pendingw--;
break;
case READ:
case READ_6:
case READ_10:
hostdata->time_read[cmd->device->id] += (jiffies - hostdata->timebase);
/*hostdata->bytes_read[cmd->device->id] += scsi_bufflen(cmd);*/
hostdata->pendingr--;
break;
}
}
#endif
/*
* Function : int NCR5380_select (struct Scsi_Host *instance, Scsi_Cmnd *cmd,
* int tag);
*
* Purpose : establishes I_T_L or I_T_L_Q nexus for new or existing command,
* including ARBITRATION, SELECTION, and initial message out for
* IDENTIFY and queue messages.
*
* Inputs : instance - instantiation of the 5380 driver on which this
* target lives, cmd - SCSI command to execute, tag - set to TAG_NEXT for
* new tag, TAG_NONE for untagged queueing, otherwise set to the tag for
* the command that is presently connected.
*
* Returns : -1 if selection could not execute for some reason,
* 0 if selection succeeded or failed because the target
* did not respond.
*
* Side effects :
* If bus busy, arbitration failed, etc, NCR5380_select() will exit
* with registers as they should have been on entry - ie
* SELECT_ENABLE will be set appropriately, the NCR5380
* will cease to drive any SCSI bus signals.
*
* If successful : I_T_L or I_T_L_Q nexus will be established,
* instance->connected will be set to cmd.
* SELECT interrupt will be disabled.
*
* If failed (no target) : cmd->scsi_done() will be called, and the
* cmd->result host byte set to DID_BAD_TARGET.
*/
static int NCR5380_select(struct Scsi_Host *instance, Scsi_Cmnd *cmd, int tag)
{
SETUP_HOSTDATA(instance);
unsigned char tmp[3], phase;
unsigned char *data;
int len;
unsigned long timeout;
unsigned long flags;
hostdata->restart_select = 0;
NCR_PRINT(NDEBUG_ARBITRATION);
ARB_PRINTK("scsi%d: starting arbitration, id = %d\n", HOSTNO,
instance->this_id);
/*
* Set the phase bits to 0, otherwise the NCR5380 won't drive the
* data bus during SELECTION.
*/
local_irq_save(flags);
if (hostdata->connected) {
local_irq_restore(flags);
return -1;
}
NCR5380_write(TARGET_COMMAND_REG, 0);
/*
* Start arbitration.
*/
NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask);
NCR5380_write(MODE_REG, MR_ARBITRATE);
local_irq_restore(flags);
/* Wait for arbitration logic to complete */
#if defined(NCR_TIMEOUT)
{
unsigned long timeout = jiffies + 2*NCR_TIMEOUT;
while (!(NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_PROGRESS) &&
time_before(jiffies, timeout) && !hostdata->connected)
;
if (time_after_eq(jiffies, timeout)) {
printk("scsi : arbitration timeout at %d\n", __LINE__);
NCR5380_write(MODE_REG, MR_BASE);
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
return -1;
}
}
#else /* NCR_TIMEOUT */
while (!(NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_PROGRESS) &&
!hostdata->connected)
;
#endif
ARB_PRINTK("scsi%d: arbitration complete\n", HOSTNO);
if (hostdata->connected) {
NCR5380_write(MODE_REG, MR_BASE);
return -1;
}
/*
* The arbitration delay is 2.2us, but this is a minimum and there is
* no maximum so we can safely sleep for ceil(2.2) usecs to accommodate
* the integral nature of udelay().
*
*/
udelay(3);
/* Check for lost arbitration */
if ((NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) ||
(NCR5380_read(CURRENT_SCSI_DATA_REG) & hostdata->id_higher_mask) ||
(NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) ||
hostdata->connected) {
NCR5380_write(MODE_REG, MR_BASE);
ARB_PRINTK("scsi%d: lost arbitration, deasserting MR_ARBITRATE\n",
HOSTNO);
return -1;
}
/* after/during arbitration, BSY should be asserted.
IBM DPES-31080 Version S31Q works now */
/* Tnx to Thomas_Roesch@m2.maus.de for finding this! (Roman) */
NCR5380_write(INITIATOR_COMMAND_REG,
ICR_BASE | ICR_ASSERT_SEL | ICR_ASSERT_BSY);
if ((NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) ||
hostdata->connected) {
NCR5380_write(MODE_REG, MR_BASE);
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
ARB_PRINTK("scsi%d: lost arbitration, deasserting ICR_ASSERT_SEL\n",
HOSTNO);
return -1;
}
/*
* Again, bus clear + bus settle time is 1.2us, however, this is
* a minimum so we'll udelay ceil(1.2)
*/
#ifdef CONFIG_ATARI_SCSI_TOSHIBA_DELAY
/* ++roman: But some targets (see above :-) seem to need a bit more... */
udelay(15);
#else
udelay(2);
#endif
if (hostdata->connected) {
NCR5380_write(MODE_REG, MR_BASE);
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
return -1;
}
ARB_PRINTK("scsi%d: won arbitration\n", HOSTNO);
/*
* Now that we have won arbitration, start Selection process, asserting
* the host and target ID's on the SCSI bus.
*/
NCR5380_write(OUTPUT_DATA_REG, (hostdata->id_mask | (1 << cmd->device->id)));
/*
* Raise ATN while SEL is true before BSY goes false from arbitration,
* since this is the only way to guarantee that we'll get a MESSAGE OUT
* phase immediately after selection.
*/
NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_BSY |
ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_SEL ));
NCR5380_write(MODE_REG, MR_BASE);
/*
* Reselect interrupts must be turned off prior to the dropping of BSY,
* otherwise we will trigger an interrupt.
*/
if (hostdata->connected) {
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
return -1;
}
NCR5380_write(SELECT_ENABLE_REG, 0);
/*
* The initiator shall then wait at least two deskew delays and release
* the BSY signal.
*/
udelay(1); /* wingel -- wait two bus deskew delay >2*45ns */
/* Reset BSY */
NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_DATA |
ICR_ASSERT_ATN | ICR_ASSERT_SEL));
/*
* Something weird happens when we cease to drive BSY - looks
* like the board/chip is letting us do another read before the
* appropriate propagation delay has expired, and we're confusing
* a BSY signal from ourselves as the target's response to SELECTION.
*
* A small delay (the 'C++' frontend breaks the pipeline with an
* unnecessary jump, making it work on my 386-33/Trantor T128, the
* tighter 'C' code breaks and requires this) solves the problem -
* the 1 us delay is arbitrary, and only used because this delay will
* be the same on other platforms and since it works here, it should
* work there.
*
* wingel suggests that this could be due to failing to wait
* one deskew delay.
*/
udelay(1);
SEL_PRINTK("scsi%d: selecting target %d\n", HOSTNO, cmd->device->id);
/*
* The SCSI specification calls for a 250 ms timeout for the actual
* selection.
*/
timeout = jiffies + 25;
/*
* XXX very interesting - we're seeing a bounce where the BSY we
* asserted is being reflected / still asserted (propagation delay?)
* and it's detecting as true. Sigh.
*/
#if 0
/* ++roman: If a target conformed to the SCSI standard, it wouldn't assert
* IO while SEL is true. But again, there are some disks out the in the
* world that do that nevertheless. (Somebody claimed that this announces
* reselection capability of the target.) So we better skip that test and
* only wait for BSY... (Famous german words: Der Klügere gibt nach :-)
*/
while (time_before(jiffies, timeout) &&
!(NCR5380_read(STATUS_REG) & (SR_BSY | SR_IO)))
;
if ((NCR5380_read(STATUS_REG) & (SR_SEL | SR_IO)) == (SR_SEL | SR_IO)) {
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
NCR5380_reselect(instance);
printk(KERN_ERR "scsi%d: reselection after won arbitration?\n",
HOSTNO);
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
return -1;
}
#else
while (time_before(jiffies, timeout) && !(NCR5380_read(STATUS_REG) & SR_BSY))
;
#endif
/*
* No less than two deskew delays after the initiator detects the
* BSY signal is true, it shall release the SEL signal and may
* change the DATA BUS. -wingel
*/
udelay(1);
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
if (!(NCR5380_read(STATUS_REG) & SR_BSY)) {
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
if (hostdata->targets_present & (1 << cmd->device->id)) {
printk(KERN_ERR "scsi%d: weirdness\n", HOSTNO);
if (hostdata->restart_select)
printk(KERN_NOTICE "\trestart select\n");
NCR_PRINT(NDEBUG_ANY);
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
return -1;
}
cmd->result = DID_BAD_TARGET << 16;
#ifdef NCR5380_STATS
collect_stats(hostdata, cmd);
#endif
#ifdef SUPPORT_TAGS
cmd_free_tag(cmd);
#endif
cmd->scsi_done(cmd);
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
SEL_PRINTK("scsi%d: target did not respond within 250ms\n", HOSTNO);
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
return 0;
}
hostdata->targets_present |= (1 << cmd->device->id);
/*
* Since we followed the SCSI spec, and raised ATN while SEL
* was true but before BSY was false during selection, the information
* transfer phase should be a MESSAGE OUT phase so that we can send the
* IDENTIFY message.
*
* If SCSI-II tagged queuing is enabled, we also send a SIMPLE_QUEUE_TAG
* message (2 bytes) with a tag ID that we increment with every command
* until it wraps back to 0.
*
* XXX - it turns out that there are some broken SCSI-II devices,
* which claim to support tagged queuing but fail when more than
* some number of commands are issued at once.
*/
/* Wait for start of REQ/ACK handshake */
while (!(NCR5380_read(STATUS_REG) & SR_REQ))
;
SEL_PRINTK("scsi%d: target %d selected, going into MESSAGE OUT phase.\n",
HOSTNO, cmd->device->id);
tmp[0] = IDENTIFY(1, cmd->device->lun);
#ifdef SUPPORT_TAGS
if (cmd->tag != TAG_NONE) {
tmp[1] = hostdata->last_message = SIMPLE_QUEUE_TAG;
tmp[2] = cmd->tag;
len = 3;
} else
len = 1;
#else
len = 1;
cmd->tag = 0;
#endif /* SUPPORT_TAGS */
/* Send message(s) */
data = tmp;
phase = PHASE_MSGOUT;
NCR5380_transfer_pio(instance, &phase, &len, &data);
SEL_PRINTK("scsi%d: nexus established.\n", HOSTNO);
/* XXX need to handle errors here */
hostdata->connected = cmd;
#ifndef SUPPORT_TAGS
hostdata->busy[cmd->device->id] |= (1 << cmd->device->lun);
#endif
initialize_SCp(cmd);
return 0;
}
/*
* Function : int NCR5380_transfer_pio (struct Scsi_Host *instance,
* unsigned char *phase, int *count, unsigned char **data)
*
* Purpose : transfers data in given phase using polled I/O
*
* Inputs : instance - instance of driver, *phase - pointer to
* what phase is expected, *count - pointer to number of
* bytes to transfer, **data - pointer to data pointer.
*
* Returns : -1 when different phase is entered without transferring
* maximum number of bytes, 0 if all bytes are transferred or exit
* is in same phase.
*
* Also, *phase, *count, *data are modified in place.
*
* XXX Note : handling for bus free may be useful.
*/
/*
* Note : this code is not as quick as it could be, however it
* IS 100% reliable, and for the actual data transfer where speed
* counts, we will always do a pseudo DMA or DMA transfer.
*/
static int NCR5380_transfer_pio(struct Scsi_Host *instance,
unsigned char *phase, int *count,
unsigned char **data)
{
register unsigned char p = *phase, tmp;
register int c = *count;
register unsigned char *d = *data;
/*
* The NCR5380 chip will only drive the SCSI bus when the
* phase specified in the appropriate bits of the TARGET COMMAND
* REGISTER match the STATUS REGISTER
*/
NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
do {
/*
* Wait for assertion of REQ, after which the phase bits will be
* valid
*/
while (!((tmp = NCR5380_read(STATUS_REG)) & SR_REQ))
;
HSH_PRINTK("scsi%d: REQ detected\n", HOSTNO);
/* Check for phase mismatch */
if ((tmp & PHASE_MASK) != p) {
PIO_PRINTK("scsi%d: phase mismatch\n", HOSTNO);
NCR_PRINT_PHASE(NDEBUG_PIO);
break;
}
/* Do actual transfer from SCSI bus to / from memory */
if (!(p & SR_IO))
NCR5380_write(OUTPUT_DATA_REG, *d);
else
*d = NCR5380_read(CURRENT_SCSI_DATA_REG);
++d;
/*
* The SCSI standard suggests that in MSGOUT phase, the initiator
* should drop ATN on the last byte of the message phase
* after REQ has been asserted for the handshake but before
* the initiator raises ACK.
*/
if (!(p & SR_IO)) {
if (!((p & SR_MSG) && c > 1)) {
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
NCR_PRINT(NDEBUG_PIO);
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
ICR_ASSERT_DATA | ICR_ASSERT_ACK);
} else {
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
ICR_ASSERT_DATA | ICR_ASSERT_ATN);
NCR_PRINT(NDEBUG_PIO);
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_ACK);
}
} else {
NCR_PRINT(NDEBUG_PIO);
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ACK);
}
while (NCR5380_read(STATUS_REG) & SR_REQ)
;
HSH_PRINTK("scsi%d: req false, handshake complete\n", HOSTNO);
/*
* We have several special cases to consider during REQ/ACK handshaking :
* 1. We were in MSGOUT phase, and we are on the last byte of the
* message. ATN must be dropped as ACK is dropped.
*
* 2. We are in a MSGIN phase, and we are on the last byte of the
* message. We must exit with ACK asserted, so that the calling
* code may raise ATN before dropping ACK to reject the message.
*
* 3. ACK and ATN are clear and the target may proceed as normal.
*/
if (!(p == PHASE_MSGIN && c == 1)) {
if (p == PHASE_MSGOUT && c > 1)
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
else
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
}
} while (--c);
PIO_PRINTK("scsi%d: residual %d\n", HOSTNO, c);
*count = c;
*data = d;
tmp = NCR5380_read(STATUS_REG);
/* The phase read from the bus is valid if either REQ is (already)
* asserted or if ACK hasn't been released yet. The latter is the case if
* we're in MSGIN and all wanted bytes have been received.
*/
if ((tmp & SR_REQ) || (p == PHASE_MSGIN && c == 0))
*phase = tmp & PHASE_MASK;
else
*phase = PHASE_UNKNOWN;
if (!c || (*phase == p))
return 0;
else
return -1;
}
/*
* Function : do_abort (Scsi_Host *host)
*
* Purpose : abort the currently established nexus. Should only be
* called from a routine which can drop into a
*
* Returns : 0 on success, -1 on failure.
*/
static int do_abort(struct Scsi_Host *host)
{
unsigned char tmp, *msgptr, phase;
int len;
/* Request message out phase */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
/*
* Wait for the target to indicate a valid phase by asserting
* REQ. Once this happens, we'll have either a MSGOUT phase
* and can immediately send the ABORT message, or we'll have some
* other phase and will have to source/sink data.
*
* We really don't care what value was on the bus or what value
* the target sees, so we just handshake.
*/
while (!((tmp = NCR5380_read(STATUS_REG)) & SR_REQ))
;
NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
if ((tmp & PHASE_MASK) != PHASE_MSGOUT) {
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN |
ICR_ASSERT_ACK);
while (NCR5380_read(STATUS_REG) & SR_REQ)
;
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
}
tmp = ABORT;
msgptr = &tmp;
len = 1;
phase = PHASE_MSGOUT;
NCR5380_transfer_pio(host, &phase, &len, &msgptr);
/*
* If we got here, and the command completed successfully,
* we're about to go into bus free state.
*/
return len ? -1 : 0;
}
#if defined(REAL_DMA)
/*
* Function : int NCR5380_transfer_dma (struct Scsi_Host *instance,
* unsigned char *phase, int *count, unsigned char **data)
*
* Purpose : transfers data in given phase using either real
* or pseudo DMA.
*
* Inputs : instance - instance of driver, *phase - pointer to
* what phase is expected, *count - pointer to number of
* bytes to transfer, **data - pointer to data pointer.
*
* Returns : -1 when different phase is entered without transferring
* maximum number of bytes, 0 if all bytes or transferred or exit
* is in same phase.
*
* Also, *phase, *count, *data are modified in place.
*
*/
static int NCR5380_transfer_dma(struct Scsi_Host *instance,
unsigned char *phase, int *count,
unsigned char **data)
{
SETUP_HOSTDATA(instance);
register int c = *count;
register unsigned char p = *phase;
register unsigned char *d = *data;
unsigned char tmp;
unsigned long flags;
if ((tmp = (NCR5380_read(STATUS_REG) & PHASE_MASK)) != p) {
*phase = tmp;
return -1;
}
if (atari_read_overruns && (p & SR_IO))
c -= atari_read_overruns;
DMA_PRINTK("scsi%d: initializing DMA for %s, %d bytes %s %p\n",
HOSTNO, (p & SR_IO) ? "reading" : "writing",
c, (p & SR_IO) ? "to" : "from", d);
NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
#ifdef REAL_DMA
NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_ENABLE_EOP_INTR | MR_MONITOR_BSY);
#endif /* def REAL_DMA */
if (IS_A_TT()) {
/* On the Medusa, it is a must to initialize the DMA before
* starting the NCR. This is also the cleaner way for the TT.
*/
local_irq_save(flags);
hostdata->dma_len = (p & SR_IO) ?
NCR5380_dma_read_setup(instance, d, c) :
NCR5380_dma_write_setup(instance, d, c);
local_irq_restore(flags);
}
if (p & SR_IO)
NCR5380_write(START_DMA_INITIATOR_RECEIVE_REG, 0);
else {
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
NCR5380_write(START_DMA_SEND_REG, 0);
}
if (!IS_A_TT()) {
/* On the Falcon, the DMA setup must be done after the last */
/* NCR access, else the DMA setup gets trashed!
*/
local_irq_save(flags);
hostdata->dma_len = (p & SR_IO) ?
NCR5380_dma_read_setup(instance, d, c) :
NCR5380_dma_write_setup(instance, d, c);
local_irq_restore(flags);
}
return 0;
}
#endif /* defined(REAL_DMA) */
/*
* Function : NCR5380_information_transfer (struct Scsi_Host *instance)
*
* Purpose : run through the various SCSI phases and do as the target
* directs us to. Operates on the currently connected command,
* instance->connected.
*
* Inputs : instance, instance for which we are doing commands
*
* Side effects : SCSI things happen, the disconnected queue will be
* modified if a command disconnects, *instance->connected will
* change.
*
* XXX Note : we need to watch for bus free or a reset condition here
* to recover from an unexpected bus free condition.
*/
static void NCR5380_information_transfer(struct Scsi_Host *instance)
{
SETUP_HOSTDATA(instance);
unsigned long flags;
unsigned char msgout = NOP;
int sink = 0;
int len;
#if defined(REAL_DMA)
int transfersize;
#endif
unsigned char *data;
unsigned char phase, tmp, extended_msg[10], old_phase = 0xff;
Scsi_Cmnd *cmd = (Scsi_Cmnd *) hostdata->connected;
while (1) {
tmp = NCR5380_read(STATUS_REG);
/* We only have a valid SCSI phase when REQ is asserted */
if (tmp & SR_REQ) {
phase = (tmp & PHASE_MASK);
if (phase != old_phase) {
old_phase = phase;
NCR_PRINT_PHASE(NDEBUG_INFORMATION);
}
if (sink && (phase != PHASE_MSGOUT)) {
NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN |
ICR_ASSERT_ACK);
while (NCR5380_read(STATUS_REG) & SR_REQ)
;
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
ICR_ASSERT_ATN);
sink = 0;
continue;
}
switch (phase) {
case PHASE_DATAOUT:
#if (NDEBUG & NDEBUG_NO_DATAOUT)
printk("scsi%d: NDEBUG_NO_DATAOUT set, attempted DATAOUT "
"aborted\n", HOSTNO);
sink = 1;
do_abort(instance);
cmd->result = DID_ERROR << 16;
cmd->scsi_done(cmd);
return;
#endif
case PHASE_DATAIN:
/*
* If there is no room left in the current buffer in the
* scatter-gather list, move onto the next one.
*/
if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) {
++cmd->SCp.buffer;
--cmd->SCp.buffers_residual;
cmd->SCp.this_residual = cmd->SCp.buffer->length;
cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
/* ++roman: Try to merge some scatter-buffers if
* they are at contiguous physical addresses.
*/
merge_contiguous_buffers(cmd);
INF_PRINTK("scsi%d: %d bytes and %d buffers left\n",
HOSTNO, cmd->SCp.this_residual,
cmd->SCp.buffers_residual);
}
/*
* The preferred transfer method is going to be
* PSEUDO-DMA for systems that are strictly PIO,
* since we can let the hardware do the handshaking.
*
* For this to work, we need to know the transfersize
* ahead of time, since the pseudo-DMA code will sit
* in an unconditional loop.
*/
/* ++roman: I suggest, this should be
* #if def(REAL_DMA)
* instead of leaving REAL_DMA out.
*/
#if defined(REAL_DMA)
if (!cmd->device->borken &&
(transfersize = NCR5380_dma_xfer_len(instance,cmd,phase)) > 31) {
len = transfersize;
cmd->SCp.phase = phase;
if (NCR5380_transfer_dma(instance, &phase,
&len, (unsigned char **)&cmd->SCp.ptr)) {
/*
* If the watchdog timer fires, all future
* accesses to this device will use the
* polled-IO. */
printk(KERN_NOTICE "scsi%d: switching target %d "
"lun %d to slow handshake\n", HOSTNO,
cmd->device->id, cmd->device->lun);
cmd->device->borken = 1;
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
ICR_ASSERT_ATN);
sink = 1;
do_abort(instance);
cmd->result = DID_ERROR << 16;
cmd->scsi_done(cmd);
/* XXX - need to source or sink data here, as appropriate */
} else {
#ifdef REAL_DMA
/* ++roman: When using real DMA,
* information_transfer() should return after
* starting DMA since it has nothing more to
* do.
*/
return;
#else
cmd->SCp.this_residual -= transfersize - len;
#endif
}
} else
#endif /* defined(REAL_DMA) */
NCR5380_transfer_pio(instance, &phase,
(int *)&cmd->SCp.this_residual,
(unsigned char **)&cmd->SCp.ptr);
break;
case PHASE_MSGIN:
len = 1;
data = &tmp;
NCR5380_write(SELECT_ENABLE_REG, 0); /* disable reselects */
NCR5380_transfer_pio(instance, &phase, &len, &data);
cmd->SCp.Message = tmp;
switch (tmp) {
/*
* Linking lets us reduce the time required to get the
* next command out to the device, hopefully this will
* mean we don't waste another revolution due to the delays
* required by ARBITRATION and another SELECTION.
*
* In the current implementation proposal, low level drivers
* merely have to start the next command, pointed to by
* next_link, done() is called as with unlinked commands.
*/
#ifdef LINKED
case LINKED_CMD_COMPLETE:
case LINKED_FLG_CMD_COMPLETE:
/* Accept message by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
LNK_PRINTK("scsi%d: target %d lun %d linked command "
"complete.\n", HOSTNO, cmd->device->id, cmd->device->lun);
/* Enable reselect interrupts */
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
/*
* Sanity check : A linked command should only terminate
* with one of these messages if there are more linked
* commands available.
*/
if (!cmd->next_link) {
printk(KERN_NOTICE "scsi%d: target %d lun %d "
"linked command complete, no next_link\n",
HOSTNO, cmd->device->id, cmd->device->lun);
sink = 1;
do_abort(instance);
return;
}
initialize_SCp(cmd->next_link);
/* The next command is still part of this process; copy it
* and don't free it! */
cmd->next_link->tag = cmd->tag;
cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8);
LNK_PRINTK("scsi%d: target %d lun %d linked request "
"done, calling scsi_done().\n",
HOSTNO, cmd->device->id, cmd->device->lun);
#ifdef NCR5380_STATS
collect_stats(hostdata, cmd);
#endif
cmd->scsi_done(cmd);
cmd = hostdata->connected;
break;
#endif /* def LINKED */
case ABORT:
case COMMAND_COMPLETE:
/* Accept message by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
/* ++guenther: possible race with Falcon locking */
falcon_dont_release++;
hostdata->connected = NULL;
QU_PRINTK("scsi%d: command for target %d, lun %d "
"completed\n", HOSTNO, cmd->device->id, cmd->device->lun);
#ifdef SUPPORT_TAGS
cmd_free_tag(cmd);
if (status_byte(cmd->SCp.Status) == QUEUE_FULL) {
/* Turn a QUEUE FULL status into BUSY, I think the
* mid level cannot handle QUEUE FULL :-( (The
* command is retried after BUSY). Also update our
* queue size to the number of currently issued
* commands now.
*/
/* ++Andreas: the mid level code knows about
QUEUE_FULL now. */
TAG_ALLOC *ta = &TagAlloc[cmd->device->id][cmd->device->lun];
TAG_PRINTK("scsi%d: target %d lun %d returned "
"QUEUE_FULL after %d commands\n",
HOSTNO, cmd->device->id, cmd->device->lun,
ta->nr_allocated);
if (ta->queue_size > ta->nr_allocated)
ta->nr_allocated = ta->queue_size;
}
#else
hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
#endif
/* Enable reselect interrupts */
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
/*
* I'm not sure what the correct thing to do here is :
*
* If the command that just executed is NOT a request
* sense, the obvious thing to do is to set the result
* code to the values of the stored parameters.
*
* If it was a REQUEST SENSE command, we need some way to
* differentiate between the failure code of the original
* and the failure code of the REQUEST sense - the obvious
* case is success, where we fall through and leave the
* result code unchanged.
*
* The non-obvious place is where the REQUEST SENSE failed
*/
if (cmd->cmnd[0] != REQUEST_SENSE)
cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8);
else if (status_byte(cmd->SCp.Status) != GOOD)
cmd->result = (cmd->result & 0x00ffff) | (DID_ERROR << 16);
#ifdef AUTOSENSE
if ((cmd->cmnd[0] == REQUEST_SENSE) &&
hostdata->ses.cmd_len) {
scsi_eh_restore_cmnd(cmd, &hostdata->ses);
hostdata->ses.cmd_len = 0 ;
}
if ((cmd->cmnd[0] != REQUEST_SENSE) &&
(status_byte(cmd->SCp.Status) == CHECK_CONDITION)) {
scsi_eh_prep_cmnd(cmd, &hostdata->ses, NULL, 0, ~0);
ASEN_PRINTK("scsi%d: performing request sense\n", HOSTNO);
local_irq_save(flags);
LIST(cmd,hostdata->issue_queue);
SET_NEXT(cmd, hostdata->issue_queue);
hostdata->issue_queue = (Scsi_Cmnd *) cmd;
local_irq_restore(flags);
QU_PRINTK("scsi%d: REQUEST SENSE added to head of "
"issue queue\n", H_NO(cmd));
} else
#endif /* def AUTOSENSE */
{
#ifdef NCR5380_STATS
collect_stats(hostdata, cmd);
#endif
cmd->scsi_done(cmd);
}
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
/*
* Restore phase bits to 0 so an interrupted selection,
* arbitration can resume.
*/
NCR5380_write(TARGET_COMMAND_REG, 0);
while ((NCR5380_read(STATUS_REG) & SR_BSY) && !hostdata->connected)
barrier();
falcon_dont_release--;
/* ++roman: For Falcon SCSI, release the lock on the
* ST-DMA here if no other commands are waiting on the
* disconnected queue.
*/
falcon_release_lock_if_possible(hostdata);
return;
case MESSAGE_REJECT:
/* Accept message by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
/* Enable reselect interrupts */
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
switch (hostdata->last_message) {
case HEAD_OF_QUEUE_TAG:
case ORDERED_QUEUE_TAG:
case SIMPLE_QUEUE_TAG:
/* The target obviously doesn't support tagged
* queuing, even though it announced this ability in
* its INQUIRY data ?!? (maybe only this LUN?) Ok,
* clear 'tagged_supported' and lock the LUN, since
* the command is treated as untagged further on.
*/
cmd->device->tagged_supported = 0;
hostdata->busy[cmd->device->id] |= (1 << cmd->device->lun);
cmd->tag = TAG_NONE;
TAG_PRINTK("scsi%d: target %d lun %d rejected "
"QUEUE_TAG message; tagged queuing "
"disabled\n",
HOSTNO, cmd->device->id, cmd->device->lun);
break;
}
break;
case DISCONNECT:
/* Accept message by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
local_irq_save(flags);
cmd->device->disconnect = 1;
LIST(cmd,hostdata->disconnected_queue);
SET_NEXT(cmd, hostdata->disconnected_queue);
hostdata->connected = NULL;
hostdata->disconnected_queue = cmd;
local_irq_restore(flags);
QU_PRINTK("scsi%d: command for target %d lun %d was "
"moved from connected to the "
"disconnected_queue\n", HOSTNO,
cmd->device->id, cmd->device->lun);
/*
* Restore phase bits to 0 so an interrupted selection,
* arbitration can resume.
*/
NCR5380_write(TARGET_COMMAND_REG, 0);
/* Enable reselect interrupts */
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
/* Wait for bus free to avoid nasty timeouts */
while ((NCR5380_read(STATUS_REG) & SR_BSY) && !hostdata->connected)
barrier();
return;
/*
* The SCSI data pointer is *IMPLICITLY* saved on a disconnect
* operation, in violation of the SCSI spec so we can safely
* ignore SAVE/RESTORE pointers calls.
*
* Unfortunately, some disks violate the SCSI spec and
* don't issue the required SAVE_POINTERS message before
* disconnecting, and we have to break spec to remain
* compatible.
*/
case SAVE_POINTERS:
case RESTORE_POINTERS:
/* Accept message by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
/* Enable reselect interrupts */
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
break;
case EXTENDED_MESSAGE:
/*
* Extended messages are sent in the following format :
* Byte
* 0 EXTENDED_MESSAGE == 1
* 1 length (includes one byte for code, doesn't
* include first two bytes)
* 2 code
* 3..length+1 arguments
*
* Start the extended message buffer with the EXTENDED_MESSAGE
* byte, since spi_print_msg() wants the whole thing.
*/
extended_msg[0] = EXTENDED_MESSAGE;
/* Accept first byte by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
EXT_PRINTK("scsi%d: receiving extended message\n", HOSTNO);
len = 2;
data = extended_msg + 1;
phase = PHASE_MSGIN;
NCR5380_transfer_pio(instance, &phase, &len, &data);
EXT_PRINTK("scsi%d: length=%d, code=0x%02x\n", HOSTNO,
(int)extended_msg[1], (int)extended_msg[2]);
if (!len && extended_msg[1] <=
(sizeof(extended_msg) - 1)) {
/* Accept third byte by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
len = extended_msg[1] - 1;
data = extended_msg + 3;
phase = PHASE_MSGIN;
NCR5380_transfer_pio(instance, &phase, &len, &data);
EXT_PRINTK("scsi%d: message received, residual %d\n",
HOSTNO, len);
switch (extended_msg[2]) {
case EXTENDED_SDTR:
case EXTENDED_WDTR:
case EXTENDED_MODIFY_DATA_POINTER:
case EXTENDED_EXTENDED_IDENTIFY:
tmp = 0;
}
} else if (len) {
printk(KERN_NOTICE "scsi%d: error receiving "
"extended message\n", HOSTNO);
tmp = 0;
} else {
printk(KERN_NOTICE "scsi%d: extended message "
"code %02x length %d is too long\n",
HOSTNO, extended_msg[2], extended_msg[1]);
tmp = 0;
}
/* Fall through to reject message */
/*
* If we get something weird that we aren't expecting,
* reject it.
*/
default:
if (!tmp) {
printk(KERN_DEBUG "scsi%d: rejecting message ", HOSTNO);
spi_print_msg(extended_msg);
printk("\n");
} else if (tmp != EXTENDED_MESSAGE)
printk(KERN_DEBUG "scsi%d: rejecting unknown "
"message %02x from target %d, lun %d\n",
HOSTNO, tmp, cmd->device->id, cmd->device->lun);
else
printk(KERN_DEBUG "scsi%d: rejecting unknown "
"extended message "
"code %02x, length %d from target %d, lun %d\n",
HOSTNO, extended_msg[1], extended_msg[0],
cmd->device->id, cmd->device->lun);
msgout = MESSAGE_REJECT;
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
break;
} /* switch (tmp) */
break;
case PHASE_MSGOUT:
len = 1;
data = &msgout;
hostdata->last_message = msgout;
NCR5380_transfer_pio(instance, &phase, &len, &data);
if (msgout == ABORT) {
#ifdef SUPPORT_TAGS
cmd_free_tag(cmd);
#else
hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
#endif
hostdata->connected = NULL;
cmd->result = DID_ERROR << 16;
#ifdef NCR5380_STATS
collect_stats(hostdata, cmd);
#endif
cmd->scsi_done(cmd);
NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
falcon_release_lock_if_possible(hostdata);
return;
}
msgout = NOP;
break;
case PHASE_CMDOUT:
len = cmd->cmd_len;
data = cmd->cmnd;
/*
* XXX for performance reasons, on machines with a
* PSEUDO-DMA architecture we should probably
* use the dma transfer function.
*/
NCR5380_transfer_pio(instance, &phase, &len, &data);
break;
case PHASE_STATIN:
len = 1;
data = &tmp;
NCR5380_transfer_pio(instance, &phase, &len, &data);
cmd->SCp.Status = tmp;
break;
default:
printk("scsi%d: unknown phase\n", HOSTNO);
NCR_PRINT(NDEBUG_ANY);
} /* switch(phase) */
} /* if (tmp * SR_REQ) */
} /* while (1) */
}
/*
* Function : void NCR5380_reselect (struct Scsi_Host *instance)
*
* Purpose : does reselection, initializing the instance->connected
* field to point to the Scsi_Cmnd for which the I_T_L or I_T_L_Q
* nexus has been reestablished,
*
* Inputs : instance - this instance of the NCR5380.
*
*/
static void NCR5380_reselect(struct Scsi_Host *instance)
{
SETUP_HOSTDATA(instance);
unsigned char target_mask;
unsigned char lun, phase;
int len;
#ifdef SUPPORT_TAGS
unsigned char tag;
#endif
unsigned char msg[3];
unsigned char *data;
Scsi_Cmnd *tmp = NULL, *prev;
/* unsigned long flags; */
/*
* Disable arbitration, etc. since the host adapter obviously
* lost, and tell an interrupted NCR5380_select() to restart.
*/
NCR5380_write(MODE_REG, MR_BASE);
hostdata->restart_select = 1;
target_mask = NCR5380_read(CURRENT_SCSI_DATA_REG) & ~(hostdata->id_mask);
RSL_PRINTK("scsi%d: reselect\n", HOSTNO);
/*
* At this point, we have detected that our SCSI ID is on the bus,
* SEL is true and BSY was false for at least one bus settle delay
* (400 ns).
*
* We must assert BSY ourselves, until the target drops the SEL
* signal.
*/
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_BSY);
while (NCR5380_read(STATUS_REG) & SR_SEL)
;
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
/*
* Wait for target to go into MSGIN.
*/
while (!(NCR5380_read(STATUS_REG) & SR_REQ))
;
len = 1;
data = msg;
phase = PHASE_MSGIN;
NCR5380_transfer_pio(instance, &phase, &len, &data);
if (!(msg[0] & 0x80)) {
printk(KERN_DEBUG "scsi%d: expecting IDENTIFY message, got ", HOSTNO);
spi_print_msg(msg);
do_abort(instance);
return;
}
lun = (msg[0] & 0x07);
#ifdef SUPPORT_TAGS
/* If the phase is still MSGIN, the target wants to send some more
* messages. In case it supports tagged queuing, this is probably a
* SIMPLE_QUEUE_TAG for the I_T_L_Q nexus.
*/
tag = TAG_NONE;
if (phase == PHASE_MSGIN && setup_use_tagged_queuing) {
/* Accept previous IDENTIFY message by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
len = 2;
data = msg + 1;
if (!NCR5380_transfer_pio(instance, &phase, &len, &data) &&
msg[1] == SIMPLE_QUEUE_TAG)
tag = msg[2];
TAG_PRINTK("scsi%d: target mask %02x, lun %d sent tag %d at "
"reselection\n", HOSTNO, target_mask, lun, tag);
}
#endif
/*
* Find the command corresponding to the I_T_L or I_T_L_Q nexus we
* just reestablished, and remove it from the disconnected queue.
*/
for (tmp = (Scsi_Cmnd *) hostdata->disconnected_queue, prev = NULL;
tmp; prev = tmp, tmp = NEXT(tmp)) {
if ((target_mask == (1 << tmp->device->id)) && (lun == tmp->device->lun)
#ifdef SUPPORT_TAGS
&& (tag == tmp->tag)
#endif
) {
/* ++guenther: prevent race with falcon_release_lock */
falcon_dont_release++;
if (prev) {
REMOVE(prev, NEXT(prev), tmp, NEXT(tmp));
SET_NEXT(prev, NEXT(tmp));
} else {
REMOVE(-1, hostdata->disconnected_queue, tmp, NEXT(tmp));
hostdata->disconnected_queue = NEXT(tmp);
}
SET_NEXT(tmp, NULL);
break;
}
}
if (!tmp) {
printk(KERN_WARNING "scsi%d: warning: target bitmask %02x lun %d "
#ifdef SUPPORT_TAGS
"tag %d "
#endif
"not in disconnected_queue.\n",
HOSTNO, target_mask, lun
#ifdef SUPPORT_TAGS
, tag
#endif
);
/*
* Since we have an established nexus that we can't do anything
* with, we must abort it.
*/
do_abort(instance);
return;
}
/* Accept message by clearing ACK */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
hostdata->connected = tmp;
RSL_PRINTK("scsi%d: nexus established, target = %d, lun = %d, tag = %d\n",
HOSTNO, tmp->device->id, tmp->device->lun, tmp->tag);
falcon_dont_release--;
}
/*
* Function : int NCR5380_abort (Scsi_Cmnd *cmd)
*
* Purpose : abort a command
*
* Inputs : cmd - the Scsi_Cmnd to abort, code - code to set the
* host byte of the result field to, if zero DID_ABORTED is
* used.
*
* Returns : 0 - success, -1 on failure.
*
* XXX - there is no way to abort the command that is currently
* connected, you have to wait for it to complete. If this is
* a problem, we could implement longjmp() / setjmp(), setjmp()
* called where the loop started in NCR5380_main().
*/
static
int NCR5380_abort(Scsi_Cmnd *cmd)
{
struct Scsi_Host *instance = cmd->device->host;
SETUP_HOSTDATA(instance);
Scsi_Cmnd *tmp, **prev;
unsigned long flags;
printk(KERN_NOTICE "scsi%d: aborting command\n", HOSTNO);
scsi_print_command(cmd);
NCR5380_print_status(instance);
local_irq_save(flags);
if (!IS_A_TT() && !falcon_got_lock)
printk(KERN_ERR "scsi%d: !!BINGO!! Falcon has no lock in NCR5380_abort\n",
HOSTNO);
ABRT_PRINTK("scsi%d: abort called basr 0x%02x, sr 0x%02x\n", HOSTNO,
NCR5380_read(BUS_AND_STATUS_REG),
NCR5380_read(STATUS_REG));
#if 1
/*
* Case 1 : If the command is the currently executing command,
* we'll set the aborted flag and return control so that
* information transfer routine can exit cleanly.
*/
if (hostdata->connected == cmd) {
ABRT_PRINTK("scsi%d: aborting connected command\n", HOSTNO);
/*
* We should perform BSY checking, and make sure we haven't slipped
* into BUS FREE.
*/
/* NCR5380_write(INITIATOR_COMMAND_REG, ICR_ASSERT_ATN); */
/*
* Since we can't change phases until we've completed the current
* handshake, we have to source or sink a byte of data if the current
* phase is not MSGOUT.
*/
/*
* Return control to the executing NCR drive so we can clear the
* aborted flag and get back into our main loop.
*/
if (do_abort(instance) == 0) {
hostdata->aborted = 1;
hostdata->connected = NULL;
cmd->result = DID_ABORT << 16;
#ifdef SUPPORT_TAGS
cmd_free_tag(cmd);
#else
hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
#endif
local_irq_restore(flags);
cmd->scsi_done(cmd);
falcon_release_lock_if_possible(hostdata);
return SCSI_ABORT_SUCCESS;
} else {
/* local_irq_restore(flags); */
printk("scsi%d: abort of connected command failed!\n", HOSTNO);
return SCSI_ABORT_ERROR;
}
}
#endif
/*
* Case 2 : If the command hasn't been issued yet, we simply remove it
* from the issue queue.
*/
for (prev = (Scsi_Cmnd **)&(hostdata->issue_queue),
tmp = (Scsi_Cmnd *)hostdata->issue_queue;
tmp; prev = NEXTADDR(tmp), tmp = NEXT(tmp)) {
if (cmd == tmp) {
REMOVE(5, *prev, tmp, NEXT(tmp));
(*prev) = NEXT(tmp);
SET_NEXT(tmp, NULL);
tmp->result = DID_ABORT << 16;
local_irq_restore(flags);
ABRT_PRINTK("scsi%d: abort removed command from issue queue.\n",
HOSTNO);
/* Tagged queuing note: no tag to free here, hasn't been assigned
* yet... */
tmp->scsi_done(tmp);
falcon_release_lock_if_possible(hostdata);
return SCSI_ABORT_SUCCESS;
}
}
/*
* Case 3 : If any commands are connected, we're going to fail the abort
* and let the high level SCSI driver retry at a later time or
* issue a reset.
*
* Timeouts, and therefore aborted commands, will be highly unlikely
* and handling them cleanly in this situation would make the common
* case of noresets less efficient, and would pollute our code. So,
* we fail.
*/
if (hostdata->connected) {
local_irq_restore(flags);
ABRT_PRINTK("scsi%d: abort failed, command connected.\n", HOSTNO);
return SCSI_ABORT_SNOOZE;
}
/*
* Case 4: If the command is currently disconnected from the bus, and
* there are no connected commands, we reconnect the I_T_L or
* I_T_L_Q nexus associated with it, go into message out, and send
* an abort message.
*
* This case is especially ugly. In order to reestablish the nexus, we
* need to call NCR5380_select(). The easiest way to implement this
* function was to abort if the bus was busy, and let the interrupt
* handler triggered on the SEL for reselect take care of lost arbitrations
* where necessary, meaning interrupts need to be enabled.
*
* When interrupts are enabled, the queues may change - so we
* can't remove it from the disconnected queue before selecting it
* because that could cause a failure in hashing the nexus if that
* device reselected.
*
* Since the queues may change, we can't use the pointers from when we
* first locate it.
*
* So, we must first locate the command, and if NCR5380_select()
* succeeds, then issue the abort, relocate the command and remove
* it from the disconnected queue.
*/
for (tmp = (Scsi_Cmnd *) hostdata->disconnected_queue; tmp;
tmp = NEXT(tmp)) {
if (cmd == tmp) {
local_irq_restore(flags);
ABRT_PRINTK("scsi%d: aborting disconnected command.\n", HOSTNO);
if (NCR5380_select(instance, cmd, (int)cmd->tag))
return SCSI_ABORT_BUSY;
ABRT_PRINTK("scsi%d: nexus reestablished.\n", HOSTNO);
do_abort(instance);
local_irq_save(flags);
for (prev = (Scsi_Cmnd **)&(hostdata->disconnected_queue),
tmp = (Scsi_Cmnd *)hostdata->disconnected_queue;
tmp; prev = NEXTADDR(tmp), tmp = NEXT(tmp)) {
if (cmd == tmp) {
REMOVE(5, *prev, tmp, NEXT(tmp));
*prev = NEXT(tmp);
SET_NEXT(tmp, NULL);
tmp->result = DID_ABORT << 16;
/* We must unlock the tag/LUN immediately here, since the
* target goes to BUS FREE and doesn't send us another
* message (COMMAND_COMPLETE or the like)
*/
#ifdef SUPPORT_TAGS
cmd_free_tag(tmp);
#else
hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
#endif
local_irq_restore(flags);
tmp->scsi_done(tmp);
falcon_release_lock_if_possible(hostdata);
return SCSI_ABORT_SUCCESS;
}
}
}
}
/*
* Case 5 : If we reached this point, the command was not found in any of
* the queues.
*
* We probably reached this point because of an unlikely race condition
* between the command completing successfully and the abortion code,
* so we won't panic, but we will notify the user in case something really
* broke.
*/
local_irq_restore(flags);
printk(KERN_INFO "scsi%d: warning : SCSI command probably completed successfully before abortion\n", HOSTNO);
/* Maybe it is sufficient just to release the ST-DMA lock... (if
* possible at all) At least, we should check if the lock could be
* released after the abort, in case it is kept due to some bug.
*/
falcon_release_lock_if_possible(hostdata);
return SCSI_ABORT_NOT_RUNNING;
}
/*
* Function : int NCR5380_reset (Scsi_Cmnd *cmd)
*
* Purpose : reset the SCSI bus.
*
* Returns : SCSI_RESET_WAKEUP
*
*/
static int NCR5380_bus_reset(Scsi_Cmnd *cmd)
{
SETUP_HOSTDATA(cmd->device->host);
int i;
unsigned long flags;
#if 1
Scsi_Cmnd *connected, *disconnected_queue;
#endif
if (!IS_A_TT() && !falcon_got_lock)
printk(KERN_ERR "scsi%d: !!BINGO!! Falcon has no lock in NCR5380_reset\n",
H_NO(cmd));
NCR5380_print_status(cmd->device->host);
/* get in phase */
NCR5380_write(TARGET_COMMAND_REG,
PHASE_SR_TO_TCR(NCR5380_read(STATUS_REG)));
/* assert RST */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_RST);
udelay(40);
/* reset NCR registers */
NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
NCR5380_write(MODE_REG, MR_BASE);
NCR5380_write(TARGET_COMMAND_REG, 0);
NCR5380_write(SELECT_ENABLE_REG, 0);
/* ++roman: reset interrupt condition! otherwise no interrupts don't get
* through anymore ... */
(void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
#if 1 /* XXX Should now be done by midlevel code, but it's broken XXX */
/* XXX see below XXX */
/* MSch: old-style reset: actually abort all command processing here */
/* After the reset, there are no more connected or disconnected commands
* and no busy units; to avoid problems with re-inserting the commands
* into the issue_queue (via scsi_done()), the aborted commands are
* remembered in local variables first.
*/
local_irq_save(flags);
connected = (Scsi_Cmnd *)hostdata->connected;
hostdata->connected = NULL;
disconnected_queue = (Scsi_Cmnd *)hostdata->disconnected_queue;
hostdata->disconnected_queue = NULL;
#ifdef SUPPORT_TAGS
free_all_tags();
#endif
for (i = 0; i < 8; ++i)
hostdata->busy[i] = 0;
#ifdef REAL_DMA
hostdata->dma_len = 0;
#endif
local_irq_restore(flags);
/* In order to tell the mid-level code which commands were aborted,
* set the command status to DID_RESET and call scsi_done() !!!
* This ultimately aborts processing of these commands in the mid-level.
*/
if ((cmd = connected)) {
ABRT_PRINTK("scsi%d: reset aborted a connected command\n", H_NO(cmd));
cmd->result = (cmd->result & 0xffff) | (DID_RESET << 16);
cmd->scsi_done(cmd);
}
for (i = 0; (cmd = disconnected_queue); ++i) {
disconnected_queue = NEXT(cmd);
SET_NEXT(cmd, NULL);
cmd->result = (cmd->result & 0xffff) | (DID_RESET << 16);
cmd->scsi_done(cmd);
}
if (i > 0)
ABRT_PRINTK("scsi: reset aborted %d disconnected command(s)\n", i);
/* The Falcon lock should be released after a reset...
*/
/* ++guenther: moved to atari_scsi_reset(), to prevent a race between
* unlocking and enabling dma interrupt.
*/
/* falcon_release_lock_if_possible( hostdata );*/
/* since all commands have been explicitly terminated, we need to tell
* the midlevel code that the reset was SUCCESSFUL, and there is no
* need to 'wake up' the commands by a request_sense
*/
return SCSI_RESET_SUCCESS | SCSI_RESET_BUS_RESET;
#else /* 1 */
/* MSch: new-style reset handling: let the mid-level do what it can */
/* ++guenther: MID-LEVEL IS STILL BROKEN.
* Mid-level is supposed to requeue all commands that were active on the
* various low-level queues. In fact it does this, but that's not enough
* because all these commands are subject to timeout. And if a timeout
* happens for any removed command, *_abort() is called but all queues
* are now empty. Abort then gives up the falcon lock, which is fatal,
* since the mid-level will queue more commands and must have the lock
* (it's all happening inside timer interrupt handler!!).
* Even worse, abort will return NOT_RUNNING for all those commands not
* on any queue, so they won't be retried ...
*
* Conclusion: either scsi.c disables timeout for all resetted commands
* immediately, or we lose! As of linux-2.0.20 it doesn't.
*/
/* After the reset, there are no more connected or disconnected commands
* and no busy units; so clear the low-level status here to avoid
* conflicts when the mid-level code tries to wake up the affected
* commands!
*/
if (hostdata->issue_queue)
ABRT_PRINTK("scsi%d: reset aborted issued command(s)\n", H_NO(cmd));
if (hostdata->connected)
ABRT_PRINTK("scsi%d: reset aborted a connected command\n", H_NO(cmd));
if (hostdata->disconnected_queue)
ABRT_PRINTK("scsi%d: reset aborted disconnected command(s)\n", H_NO(cmd));
local_irq_save(flags);
hostdata->issue_queue = NULL;
hostdata->connected = NULL;
hostdata->disconnected_queue = NULL;
#ifdef SUPPORT_TAGS
free_all_tags();
#endif
for (i = 0; i < 8; ++i)
hostdata->busy[i] = 0;
#ifdef REAL_DMA
hostdata->dma_len = 0;
#endif
local_irq_restore(flags);
/* we did no complete reset of all commands, so a wakeup is required */
return SCSI_RESET_WAKEUP | SCSI_RESET_BUS_RESET;
#endif /* 1 */
}
| gpl-2.0 |
dalingrin/hp-kernel-tenderloin | drivers/hwmon/ads7871.c | 3011 | 6992 | /*
* ads7871 - driver for TI ADS7871 A/D converter
*
* Copyright (c) 2010 Paul Thomas <pthomas8589@gmail.com>
*
* 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.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 or
* later as publishhed by the Free Software Foundation.
*
* You need to have something like this in struct spi_board_info
* {
* .modalias = "ads7871",
* .max_speed_hz = 2*1000*1000,
* .chip_select = 0,
* .bus_num = 1,
* },
*/
/*From figure 18 in the datasheet*/
/*Register addresses*/
#define REG_LS_BYTE 0 /*A/D Output Data, LS Byte*/
#define REG_MS_BYTE 1 /*A/D Output Data, MS Byte*/
#define REG_PGA_VALID 2 /*PGA Valid Register*/
#define REG_AD_CONTROL 3 /*A/D Control Register*/
#define REG_GAIN_MUX 4 /*Gain/Mux Register*/
#define REG_IO_STATE 5 /*Digital I/O State Register*/
#define REG_IO_CONTROL 6 /*Digital I/O Control Register*/
#define REG_OSC_CONTROL 7 /*Rev/Oscillator Control Register*/
#define REG_SER_CONTROL 24 /*Serial Interface Control Register*/
#define REG_ID 31 /*ID Register*/
/*From figure 17 in the datasheet
* These bits get ORed with the address to form
* the instruction byte */
/*Instruction Bit masks*/
#define INST_MODE_bm (1<<7)
#define INST_READ_bm (1<<6)
#define INST_16BIT_bm (1<<5)
/*From figure 18 in the datasheet*/
/*bit masks for Rev/Oscillator Control Register*/
#define MUX_CNV_bv 7
#define MUX_CNV_bm (1<<MUX_CNV_bv)
#define MUX_M3_bm (1<<3) /*M3 selects single ended*/
#define MUX_G_bv 4 /*allows for reg = (gain << MUX_G_bv) | ...*/
/*From figure 18 in the datasheet*/
/*bit masks for Rev/Oscillator Control Register*/
#define OSC_OSCR_bm (1<<5)
#define OSC_OSCE_bm (1<<4)
#define OSC_REFE_bm (1<<3)
#define OSC_BUFE_bm (1<<2)
#define OSC_R2V_bm (1<<1)
#define OSC_RBG_bm (1<<0)
#include <linux/module.h>
#include <linux/init.h>
#include <linux/spi/spi.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#define DEVICE_NAME "ads7871"
struct ads7871_data {
struct device *hwmon_dev;
struct mutex update_lock;
};
static int ads7871_read_reg8(struct spi_device *spi, int reg)
{
int ret;
reg = reg | INST_READ_bm;
ret = spi_w8r8(spi, reg);
return ret;
}
static int ads7871_read_reg16(struct spi_device *spi, int reg)
{
int ret;
reg = reg | INST_READ_bm | INST_16BIT_bm;
ret = spi_w8r16(spi, reg);
return ret;
}
static int ads7871_write_reg8(struct spi_device *spi, int reg, u8 val)
{
u8 tmp[2] = {reg, val};
return spi_write(spi, tmp, sizeof(tmp));
}
static ssize_t show_voltage(struct device *dev,
struct device_attribute *da, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int ret, val, i = 0;
uint8_t channel, mux_cnv;
channel = attr->index;
/*TODO: add support for conversions
*other than single ended with a gain of 1*/
/*MUX_M3_bm forces single ended*/
/*This is also where the gain of the PGA would be set*/
ads7871_write_reg8(spi, REG_GAIN_MUX,
(MUX_CNV_bm | MUX_M3_bm | channel));
ret = ads7871_read_reg8(spi, REG_GAIN_MUX);
mux_cnv = ((ret & MUX_CNV_bm)>>MUX_CNV_bv);
/*on 400MHz arm9 platform the conversion
*is already done when we do this test*/
while ((i < 2) && mux_cnv) {
i++;
ret = ads7871_read_reg8(spi, REG_GAIN_MUX);
mux_cnv = ((ret & MUX_CNV_bm)>>MUX_CNV_bv);
msleep_interruptible(1);
}
if (mux_cnv == 0) {
val = ads7871_read_reg16(spi, REG_LS_BYTE);
/*result in volts*10000 = (val/8192)*2.5*10000*/
val = ((val>>2) * 25000) / 8192;
return sprintf(buf, "%d\n", val);
} else {
return -1;
}
}
static SENSOR_DEVICE_ATTR(in0_input, S_IRUGO, show_voltage, NULL, 0);
static SENSOR_DEVICE_ATTR(in1_input, S_IRUGO, show_voltage, NULL, 1);
static SENSOR_DEVICE_ATTR(in2_input, S_IRUGO, show_voltage, NULL, 2);
static SENSOR_DEVICE_ATTR(in3_input, S_IRUGO, show_voltage, NULL, 3);
static SENSOR_DEVICE_ATTR(in4_input, S_IRUGO, show_voltage, NULL, 4);
static SENSOR_DEVICE_ATTR(in5_input, S_IRUGO, show_voltage, NULL, 5);
static SENSOR_DEVICE_ATTR(in6_input, S_IRUGO, show_voltage, NULL, 6);
static SENSOR_DEVICE_ATTR(in7_input, S_IRUGO, show_voltage, NULL, 7);
static struct attribute *ads7871_attributes[] = {
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in3_input.dev_attr.attr,
&sensor_dev_attr_in4_input.dev_attr.attr,
&sensor_dev_attr_in5_input.dev_attr.attr,
&sensor_dev_attr_in6_input.dev_attr.attr,
&sensor_dev_attr_in7_input.dev_attr.attr,
NULL
};
static const struct attribute_group ads7871_group = {
.attrs = ads7871_attributes,
};
static int __devinit ads7871_probe(struct spi_device *spi)
{
int ret, err;
uint8_t val;
struct ads7871_data *pdata;
dev_dbg(&spi->dev, "probe\n");
/* Configure the SPI bus */
spi->mode = (SPI_MODE_0);
spi->bits_per_word = 8;
spi_setup(spi);
ads7871_write_reg8(spi, REG_SER_CONTROL, 0);
ads7871_write_reg8(spi, REG_AD_CONTROL, 0);
val = (OSC_OSCR_bm | OSC_OSCE_bm | OSC_REFE_bm | OSC_BUFE_bm);
ads7871_write_reg8(spi, REG_OSC_CONTROL, val);
ret = ads7871_read_reg8(spi, REG_OSC_CONTROL);
dev_dbg(&spi->dev, "REG_OSC_CONTROL write:%x, read:%x\n", val, ret);
/*because there is no other error checking on an SPI bus
we need to make sure we really have a chip*/
if (val != ret) {
err = -ENODEV;
goto exit;
}
pdata = kzalloc(sizeof(struct ads7871_data), GFP_KERNEL);
if (!pdata) {
err = -ENOMEM;
goto exit;
}
err = sysfs_create_group(&spi->dev.kobj, &ads7871_group);
if (err < 0)
goto error_free;
spi_set_drvdata(spi, pdata);
pdata->hwmon_dev = hwmon_device_register(&spi->dev);
if (IS_ERR(pdata->hwmon_dev)) {
err = PTR_ERR(pdata->hwmon_dev);
goto error_remove;
}
return 0;
error_remove:
sysfs_remove_group(&spi->dev.kobj, &ads7871_group);
error_free:
kfree(pdata);
exit:
return err;
}
static int __devexit ads7871_remove(struct spi_device *spi)
{
struct ads7871_data *pdata = spi_get_drvdata(spi);
hwmon_device_unregister(pdata->hwmon_dev);
sysfs_remove_group(&spi->dev.kobj, &ads7871_group);
kfree(pdata);
return 0;
}
static struct spi_driver ads7871_driver = {
.driver = {
.name = DEVICE_NAME,
.bus = &spi_bus_type,
.owner = THIS_MODULE,
},
.probe = ads7871_probe,
.remove = __devexit_p(ads7871_remove),
};
static int __init ads7871_init(void)
{
return spi_register_driver(&ads7871_driver);
}
static void __exit ads7871_exit(void)
{
spi_unregister_driver(&ads7871_driver);
}
module_init(ads7871_init);
module_exit(ads7871_exit);
MODULE_AUTHOR("Paul Thomas <pthomas8589@gmail.com>");
MODULE_DESCRIPTION("TI ADS7871 A/D driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jrior001/android_kernel_samsung_d2 | net/tipc/port.c | 4803 | 33105 | /*
* net/tipc/port.c: TIPC port code
*
* Copyright (c) 1992-2007, Ericsson AB
* Copyright (c) 2004-2008, 2010-2011, 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"
#include "config.h"
#include "port.h"
#include "name_table.h"
/* Connection management: */
#define PROBING_INTERVAL 3600000 /* [ms] => 1 h */
#define CONFIRMED 0
#define PROBING 1
#define MAX_REJECT_SIZE 1024
static struct sk_buff *msg_queue_head;
static struct sk_buff *msg_queue_tail;
DEFINE_SPINLOCK(tipc_port_list_lock);
static DEFINE_SPINLOCK(queue_lock);
static LIST_HEAD(ports);
static void port_handle_node_down(unsigned long ref);
static struct sk_buff *port_build_self_abort_msg(struct tipc_port *, u32 err);
static struct sk_buff *port_build_peer_abort_msg(struct tipc_port *, u32 err);
static void port_timeout(unsigned long ref);
static u32 port_peernode(struct tipc_port *p_ptr)
{
return msg_destnode(&p_ptr->phdr);
}
static u32 port_peerport(struct tipc_port *p_ptr)
{
return msg_destport(&p_ptr->phdr);
}
/**
* tipc_multicast - send a multicast message to local and remote destinations
*/
int tipc_multicast(u32 ref, struct tipc_name_seq const *seq,
u32 num_sect, struct iovec const *msg_sect,
unsigned int total_len)
{
struct tipc_msg *hdr;
struct sk_buff *buf;
struct sk_buff *ibuf = NULL;
struct tipc_port_list dports = {0, NULL, };
struct tipc_port *oport = tipc_port_deref(ref);
int ext_targets;
int res;
if (unlikely(!oport))
return -EINVAL;
/* Create multicast message */
hdr = &oport->phdr;
msg_set_type(hdr, TIPC_MCAST_MSG);
msg_set_lookup_scope(hdr, TIPC_CLUSTER_SCOPE);
msg_set_destport(hdr, 0);
msg_set_destnode(hdr, 0);
msg_set_nametype(hdr, seq->type);
msg_set_namelower(hdr, seq->lower);
msg_set_nameupper(hdr, seq->upper);
msg_set_hdr_sz(hdr, MCAST_H_SIZE);
res = tipc_msg_build(hdr, msg_sect, num_sect, total_len, MAX_MSG_SIZE,
!oport->user_port, &buf);
if (unlikely(!buf))
return res;
/* Figure out where to send multicast message */
ext_targets = tipc_nametbl_mc_translate(seq->type, seq->lower, seq->upper,
TIPC_NODE_SCOPE, &dports);
/* Send message to destinations (duplicate it only if necessary) */
if (ext_targets) {
if (dports.count != 0) {
ibuf = skb_copy(buf, GFP_ATOMIC);
if (ibuf == NULL) {
tipc_port_list_free(&dports);
kfree_skb(buf);
return -ENOMEM;
}
}
res = tipc_bclink_send_msg(buf);
if ((res < 0) && (dports.count != 0))
kfree_skb(ibuf);
} else {
ibuf = buf;
}
if (res >= 0) {
if (ibuf)
tipc_port_recv_mcast(ibuf, &dports);
} else {
tipc_port_list_free(&dports);
}
return res;
}
/**
* tipc_port_recv_mcast - deliver multicast message to all destination ports
*
* If there is no port list, perform a lookup to create one
*/
void tipc_port_recv_mcast(struct sk_buff *buf, struct tipc_port_list *dp)
{
struct tipc_msg *msg;
struct tipc_port_list dports = {0, NULL, };
struct tipc_port_list *item = dp;
int cnt = 0;
msg = buf_msg(buf);
/* Create destination port list, if one wasn't supplied */
if (dp == NULL) {
tipc_nametbl_mc_translate(msg_nametype(msg),
msg_namelower(msg),
msg_nameupper(msg),
TIPC_CLUSTER_SCOPE,
&dports);
item = dp = &dports;
}
/* Deliver a copy of message to each destination port */
if (dp->count != 0) {
msg_set_destnode(msg, tipc_own_addr);
if (dp->count == 1) {
msg_set_destport(msg, dp->ports[0]);
tipc_port_recv_msg(buf);
tipc_port_list_free(dp);
return;
}
for (; cnt < dp->count; cnt++) {
int index = cnt % PLSIZE;
struct sk_buff *b = skb_clone(buf, GFP_ATOMIC);
if (b == NULL) {
warn("Unable to deliver multicast message(s)\n");
goto exit;
}
if ((index == 0) && (cnt != 0))
item = item->next;
msg_set_destport(buf_msg(b), item->ports[index]);
tipc_port_recv_msg(b);
}
}
exit:
kfree_skb(buf);
tipc_port_list_free(dp);
}
/**
* tipc_createport_raw - create a generic TIPC port
*
* Returns pointer to (locked) TIPC port, or NULL if unable to create it
*/
struct tipc_port *tipc_createport_raw(void *usr_handle,
u32 (*dispatcher)(struct tipc_port *, struct sk_buff *),
void (*wakeup)(struct tipc_port *),
const u32 importance)
{
struct tipc_port *p_ptr;
struct tipc_msg *msg;
u32 ref;
p_ptr = kzalloc(sizeof(*p_ptr), GFP_ATOMIC);
if (!p_ptr) {
warn("Port creation failed, no memory\n");
return NULL;
}
ref = tipc_ref_acquire(p_ptr, &p_ptr->lock);
if (!ref) {
warn("Port creation failed, reference table exhausted\n");
kfree(p_ptr);
return NULL;
}
p_ptr->usr_handle = usr_handle;
p_ptr->max_pkt = MAX_PKT_DEFAULT;
p_ptr->ref = ref;
msg = &p_ptr->phdr;
tipc_msg_init(msg, importance, TIPC_NAMED_MSG, NAMED_H_SIZE, 0);
msg_set_origport(msg, ref);
INIT_LIST_HEAD(&p_ptr->wait_list);
INIT_LIST_HEAD(&p_ptr->subscription.nodesub_list);
p_ptr->dispatcher = dispatcher;
p_ptr->wakeup = wakeup;
p_ptr->user_port = NULL;
k_init_timer(&p_ptr->timer, (Handler)port_timeout, ref);
spin_lock_bh(&tipc_port_list_lock);
INIT_LIST_HEAD(&p_ptr->publications);
INIT_LIST_HEAD(&p_ptr->port_list);
list_add_tail(&p_ptr->port_list, &ports);
spin_unlock_bh(&tipc_port_list_lock);
return p_ptr;
}
int tipc_deleteport(u32 ref)
{
struct tipc_port *p_ptr;
struct sk_buff *buf = NULL;
tipc_withdraw(ref, 0, NULL);
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
tipc_ref_discard(ref);
tipc_port_unlock(p_ptr);
k_cancel_timer(&p_ptr->timer);
if (p_ptr->connected) {
buf = port_build_peer_abort_msg(p_ptr, TIPC_ERR_NO_PORT);
tipc_nodesub_unsubscribe(&p_ptr->subscription);
}
kfree(p_ptr->user_port);
spin_lock_bh(&tipc_port_list_lock);
list_del(&p_ptr->port_list);
list_del(&p_ptr->wait_list);
spin_unlock_bh(&tipc_port_list_lock);
k_term_timer(&p_ptr->timer);
kfree(p_ptr);
tipc_net_route_msg(buf);
return 0;
}
static int port_unreliable(struct tipc_port *p_ptr)
{
return msg_src_droppable(&p_ptr->phdr);
}
int tipc_portunreliable(u32 ref, unsigned int *isunreliable)
{
struct tipc_port *p_ptr;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
*isunreliable = port_unreliable(p_ptr);
tipc_port_unlock(p_ptr);
return 0;
}
int tipc_set_portunreliable(u32 ref, unsigned int isunreliable)
{
struct tipc_port *p_ptr;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
msg_set_src_droppable(&p_ptr->phdr, (isunreliable != 0));
tipc_port_unlock(p_ptr);
return 0;
}
static int port_unreturnable(struct tipc_port *p_ptr)
{
return msg_dest_droppable(&p_ptr->phdr);
}
int tipc_portunreturnable(u32 ref, unsigned int *isunrejectable)
{
struct tipc_port *p_ptr;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
*isunrejectable = port_unreturnable(p_ptr);
tipc_port_unlock(p_ptr);
return 0;
}
int tipc_set_portunreturnable(u32 ref, unsigned int isunrejectable)
{
struct tipc_port *p_ptr;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
msg_set_dest_droppable(&p_ptr->phdr, (isunrejectable != 0));
tipc_port_unlock(p_ptr);
return 0;
}
/*
* port_build_proto_msg(): create connection protocol message for port
*
* On entry the port must be locked and connected.
*/
static struct sk_buff *port_build_proto_msg(struct tipc_port *p_ptr,
u32 type, u32 ack)
{
struct sk_buff *buf;
struct tipc_msg *msg;
buf = tipc_buf_acquire(INT_H_SIZE);
if (buf) {
msg = buf_msg(buf);
tipc_msg_init(msg, CONN_MANAGER, type, INT_H_SIZE,
port_peernode(p_ptr));
msg_set_destport(msg, port_peerport(p_ptr));
msg_set_origport(msg, p_ptr->ref);
msg_set_msgcnt(msg, ack);
}
return buf;
}
int tipc_reject_msg(struct sk_buff *buf, u32 err)
{
struct tipc_msg *msg = buf_msg(buf);
struct sk_buff *rbuf;
struct tipc_msg *rmsg;
int hdr_sz;
u32 imp;
u32 data_sz = msg_data_sz(msg);
u32 src_node;
u32 rmsg_sz;
/* discard rejected message if it shouldn't be returned to sender */
if (WARN(!msg_isdata(msg),
"attempt to reject message with user=%u", msg_user(msg))) {
dump_stack();
goto exit;
}
if (msg_errcode(msg) || msg_dest_droppable(msg))
goto exit;
/*
* construct returned message by copying rejected message header and
* data (or subset), then updating header fields that need adjusting
*/
hdr_sz = msg_hdr_sz(msg);
rmsg_sz = hdr_sz + min_t(u32, data_sz, MAX_REJECT_SIZE);
rbuf = tipc_buf_acquire(rmsg_sz);
if (rbuf == NULL)
goto exit;
rmsg = buf_msg(rbuf);
skb_copy_to_linear_data(rbuf, msg, rmsg_sz);
if (msg_connected(rmsg)) {
imp = msg_importance(rmsg);
if (imp < TIPC_CRITICAL_IMPORTANCE)
msg_set_importance(rmsg, ++imp);
}
msg_set_non_seq(rmsg, 0);
msg_set_size(rmsg, rmsg_sz);
msg_set_errcode(rmsg, err);
msg_set_prevnode(rmsg, tipc_own_addr);
msg_swap_words(rmsg, 4, 5);
if (!msg_short(rmsg))
msg_swap_words(rmsg, 6, 7);
/* send self-abort message when rejecting on a connected port */
if (msg_connected(msg)) {
struct tipc_port *p_ptr = tipc_port_lock(msg_destport(msg));
if (p_ptr) {
struct sk_buff *abuf = NULL;
if (p_ptr->connected)
abuf = port_build_self_abort_msg(p_ptr, err);
tipc_port_unlock(p_ptr);
tipc_net_route_msg(abuf);
}
}
/* send returned message & dispose of rejected message */
src_node = msg_prevnode(msg);
if (src_node == tipc_own_addr)
tipc_port_recv_msg(rbuf);
else
tipc_link_send(rbuf, src_node, msg_link_selector(rmsg));
exit:
kfree_skb(buf);
return data_sz;
}
int tipc_port_reject_sections(struct tipc_port *p_ptr, struct tipc_msg *hdr,
struct iovec const *msg_sect, u32 num_sect,
unsigned int total_len, int err)
{
struct sk_buff *buf;
int res;
res = tipc_msg_build(hdr, msg_sect, num_sect, total_len, MAX_MSG_SIZE,
!p_ptr->user_port, &buf);
if (!buf)
return res;
return tipc_reject_msg(buf, err);
}
static void port_timeout(unsigned long ref)
{
struct tipc_port *p_ptr = tipc_port_lock(ref);
struct sk_buff *buf = NULL;
if (!p_ptr)
return;
if (!p_ptr->connected) {
tipc_port_unlock(p_ptr);
return;
}
/* Last probe answered ? */
if (p_ptr->probing_state == PROBING) {
buf = port_build_self_abort_msg(p_ptr, TIPC_ERR_NO_PORT);
} else {
buf = port_build_proto_msg(p_ptr, CONN_PROBE, 0);
p_ptr->probing_state = PROBING;
k_start_timer(&p_ptr->timer, p_ptr->probing_interval);
}
tipc_port_unlock(p_ptr);
tipc_net_route_msg(buf);
}
static void port_handle_node_down(unsigned long ref)
{
struct tipc_port *p_ptr = tipc_port_lock(ref);
struct sk_buff *buf = NULL;
if (!p_ptr)
return;
buf = port_build_self_abort_msg(p_ptr, TIPC_ERR_NO_NODE);
tipc_port_unlock(p_ptr);
tipc_net_route_msg(buf);
}
static struct sk_buff *port_build_self_abort_msg(struct tipc_port *p_ptr, u32 err)
{
struct sk_buff *buf = port_build_peer_abort_msg(p_ptr, err);
if (buf) {
struct tipc_msg *msg = buf_msg(buf);
msg_swap_words(msg, 4, 5);
msg_swap_words(msg, 6, 7);
}
return buf;
}
static struct sk_buff *port_build_peer_abort_msg(struct tipc_port *p_ptr, u32 err)
{
struct sk_buff *buf;
struct tipc_msg *msg;
u32 imp;
if (!p_ptr->connected)
return NULL;
buf = tipc_buf_acquire(BASIC_H_SIZE);
if (buf) {
msg = buf_msg(buf);
memcpy(msg, &p_ptr->phdr, BASIC_H_SIZE);
msg_set_hdr_sz(msg, BASIC_H_SIZE);
msg_set_size(msg, BASIC_H_SIZE);
imp = msg_importance(msg);
if (imp < TIPC_CRITICAL_IMPORTANCE)
msg_set_importance(msg, ++imp);
msg_set_errcode(msg, err);
}
return buf;
}
void tipc_port_recv_proto_msg(struct sk_buff *buf)
{
struct tipc_msg *msg = buf_msg(buf);
struct tipc_port *p_ptr;
struct sk_buff *r_buf = NULL;
u32 orignode = msg_orignode(msg);
u32 origport = msg_origport(msg);
u32 destport = msg_destport(msg);
int wakeable;
/* Validate connection */
p_ptr = tipc_port_lock(destport);
if (!p_ptr || !p_ptr->connected ||
(port_peernode(p_ptr) != orignode) ||
(port_peerport(p_ptr) != origport)) {
r_buf = tipc_buf_acquire(BASIC_H_SIZE);
if (r_buf) {
msg = buf_msg(r_buf);
tipc_msg_init(msg, TIPC_HIGH_IMPORTANCE, TIPC_CONN_MSG,
BASIC_H_SIZE, orignode);
msg_set_errcode(msg, TIPC_ERR_NO_PORT);
msg_set_origport(msg, destport);
msg_set_destport(msg, origport);
}
if (p_ptr)
tipc_port_unlock(p_ptr);
goto exit;
}
/* Process protocol message sent by peer */
switch (msg_type(msg)) {
case CONN_ACK:
wakeable = tipc_port_congested(p_ptr) && p_ptr->congested &&
p_ptr->wakeup;
p_ptr->acked += msg_msgcnt(msg);
if (!tipc_port_congested(p_ptr)) {
p_ptr->congested = 0;
if (wakeable)
p_ptr->wakeup(p_ptr);
}
break;
case CONN_PROBE:
r_buf = port_build_proto_msg(p_ptr, CONN_PROBE_REPLY, 0);
break;
default:
/* CONN_PROBE_REPLY or unrecognized - no action required */
break;
}
p_ptr->probing_state = CONFIRMED;
tipc_port_unlock(p_ptr);
exit:
tipc_net_route_msg(r_buf);
kfree_skb(buf);
}
static void port_print(struct tipc_port *p_ptr, struct print_buf *buf, int full_id)
{
struct publication *publ;
if (full_id)
tipc_printf(buf, "<%u.%u.%u:%u>:",
tipc_zone(tipc_own_addr), tipc_cluster(tipc_own_addr),
tipc_node(tipc_own_addr), p_ptr->ref);
else
tipc_printf(buf, "%-10u:", p_ptr->ref);
if (p_ptr->connected) {
u32 dport = port_peerport(p_ptr);
u32 destnode = port_peernode(p_ptr);
tipc_printf(buf, " connected to <%u.%u.%u:%u>",
tipc_zone(destnode), tipc_cluster(destnode),
tipc_node(destnode), dport);
if (p_ptr->conn_type != 0)
tipc_printf(buf, " via {%u,%u}",
p_ptr->conn_type,
p_ptr->conn_instance);
} else if (p_ptr->published) {
tipc_printf(buf, " bound to");
list_for_each_entry(publ, &p_ptr->publications, pport_list) {
if (publ->lower == publ->upper)
tipc_printf(buf, " {%u,%u}", publ->type,
publ->lower);
else
tipc_printf(buf, " {%u,%u,%u}", publ->type,
publ->lower, publ->upper);
}
}
tipc_printf(buf, "\n");
}
#define MAX_PORT_QUERY 32768
struct sk_buff *tipc_port_get_ports(void)
{
struct sk_buff *buf;
struct tlv_desc *rep_tlv;
struct print_buf pb;
struct tipc_port *p_ptr;
int str_len;
buf = tipc_cfg_reply_alloc(TLV_SPACE(MAX_PORT_QUERY));
if (!buf)
return NULL;
rep_tlv = (struct tlv_desc *)buf->data;
tipc_printbuf_init(&pb, TLV_DATA(rep_tlv), MAX_PORT_QUERY);
spin_lock_bh(&tipc_port_list_lock);
list_for_each_entry(p_ptr, &ports, port_list) {
spin_lock_bh(p_ptr->lock);
port_print(p_ptr, &pb, 0);
spin_unlock_bh(p_ptr->lock);
}
spin_unlock_bh(&tipc_port_list_lock);
str_len = tipc_printbuf_validate(&pb);
skb_put(buf, TLV_SPACE(str_len));
TLV_SET(rep_tlv, TIPC_TLV_ULTRA_STRING, NULL, str_len);
return buf;
}
void tipc_port_reinit(void)
{
struct tipc_port *p_ptr;
struct tipc_msg *msg;
spin_lock_bh(&tipc_port_list_lock);
list_for_each_entry(p_ptr, &ports, port_list) {
msg = &p_ptr->phdr;
if (msg_orignode(msg) == tipc_own_addr)
break;
msg_set_prevnode(msg, tipc_own_addr);
msg_set_orignode(msg, tipc_own_addr);
}
spin_unlock_bh(&tipc_port_list_lock);
}
/*
* port_dispatcher_sigh(): Signal handler for messages destinated
* to the tipc_port interface.
*/
static void port_dispatcher_sigh(void *dummy)
{
struct sk_buff *buf;
spin_lock_bh(&queue_lock);
buf = msg_queue_head;
msg_queue_head = NULL;
spin_unlock_bh(&queue_lock);
while (buf) {
struct tipc_port *p_ptr;
struct user_port *up_ptr;
struct tipc_portid orig;
struct tipc_name_seq dseq;
void *usr_handle;
int connected;
int published;
u32 message_type;
struct sk_buff *next = buf->next;
struct tipc_msg *msg = buf_msg(buf);
u32 dref = msg_destport(msg);
message_type = msg_type(msg);
if (message_type > TIPC_DIRECT_MSG)
goto reject; /* Unsupported message type */
p_ptr = tipc_port_lock(dref);
if (!p_ptr)
goto reject; /* Port deleted while msg in queue */
orig.ref = msg_origport(msg);
orig.node = msg_orignode(msg);
up_ptr = p_ptr->user_port;
usr_handle = up_ptr->usr_handle;
connected = p_ptr->connected;
published = p_ptr->published;
if (unlikely(msg_errcode(msg)))
goto err;
switch (message_type) {
case TIPC_CONN_MSG:{
tipc_conn_msg_event cb = up_ptr->conn_msg_cb;
u32 peer_port = port_peerport(p_ptr);
u32 peer_node = port_peernode(p_ptr);
u32 dsz;
tipc_port_unlock(p_ptr);
if (unlikely(!cb))
goto reject;
if (unlikely(!connected)) {
if (tipc_connect2port(dref, &orig))
goto reject;
} else if ((msg_origport(msg) != peer_port) ||
(msg_orignode(msg) != peer_node))
goto reject;
dsz = msg_data_sz(msg);
if (unlikely(dsz &&
(++p_ptr->conn_unacked >=
TIPC_FLOW_CONTROL_WIN)))
tipc_acknowledge(dref,
p_ptr->conn_unacked);
skb_pull(buf, msg_hdr_sz(msg));
cb(usr_handle, dref, &buf, msg_data(msg), dsz);
break;
}
case TIPC_DIRECT_MSG:{
tipc_msg_event cb = up_ptr->msg_cb;
tipc_port_unlock(p_ptr);
if (unlikely(!cb || connected))
goto reject;
skb_pull(buf, msg_hdr_sz(msg));
cb(usr_handle, dref, &buf, msg_data(msg),
msg_data_sz(msg), msg_importance(msg),
&orig);
break;
}
case TIPC_MCAST_MSG:
case TIPC_NAMED_MSG:{
tipc_named_msg_event cb = up_ptr->named_msg_cb;
tipc_port_unlock(p_ptr);
if (unlikely(!cb || connected || !published))
goto reject;
dseq.type = msg_nametype(msg);
dseq.lower = msg_nameinst(msg);
dseq.upper = (message_type == TIPC_NAMED_MSG)
? dseq.lower : msg_nameupper(msg);
skb_pull(buf, msg_hdr_sz(msg));
cb(usr_handle, dref, &buf, msg_data(msg),
msg_data_sz(msg), msg_importance(msg),
&orig, &dseq);
break;
}
}
if (buf)
kfree_skb(buf);
buf = next;
continue;
err:
switch (message_type) {
case TIPC_CONN_MSG:{
tipc_conn_shutdown_event cb =
up_ptr->conn_err_cb;
u32 peer_port = port_peerport(p_ptr);
u32 peer_node = port_peernode(p_ptr);
tipc_port_unlock(p_ptr);
if (!cb || !connected)
break;
if ((msg_origport(msg) != peer_port) ||
(msg_orignode(msg) != peer_node))
break;
tipc_disconnect(dref);
skb_pull(buf, msg_hdr_sz(msg));
cb(usr_handle, dref, &buf, msg_data(msg),
msg_data_sz(msg), msg_errcode(msg));
break;
}
case TIPC_DIRECT_MSG:{
tipc_msg_err_event cb = up_ptr->err_cb;
tipc_port_unlock(p_ptr);
if (!cb || connected)
break;
skb_pull(buf, msg_hdr_sz(msg));
cb(usr_handle, dref, &buf, msg_data(msg),
msg_data_sz(msg), msg_errcode(msg), &orig);
break;
}
case TIPC_MCAST_MSG:
case TIPC_NAMED_MSG:{
tipc_named_msg_err_event cb =
up_ptr->named_err_cb;
tipc_port_unlock(p_ptr);
if (!cb || connected)
break;
dseq.type = msg_nametype(msg);
dseq.lower = msg_nameinst(msg);
dseq.upper = (message_type == TIPC_NAMED_MSG)
? dseq.lower : msg_nameupper(msg);
skb_pull(buf, msg_hdr_sz(msg));
cb(usr_handle, dref, &buf, msg_data(msg),
msg_data_sz(msg), msg_errcode(msg), &dseq);
break;
}
}
if (buf)
kfree_skb(buf);
buf = next;
continue;
reject:
tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
buf = next;
}
}
/*
* port_dispatcher(): Dispatcher for messages destinated
* to the tipc_port interface. Called with port locked.
*/
static u32 port_dispatcher(struct tipc_port *dummy, struct sk_buff *buf)
{
buf->next = NULL;
spin_lock_bh(&queue_lock);
if (msg_queue_head) {
msg_queue_tail->next = buf;
msg_queue_tail = buf;
} else {
msg_queue_tail = msg_queue_head = buf;
tipc_k_signal((Handler)port_dispatcher_sigh, 0);
}
spin_unlock_bh(&queue_lock);
return 0;
}
/*
* Wake up port after congestion: Called with port locked,
*
*/
static void port_wakeup_sh(unsigned long ref)
{
struct tipc_port *p_ptr;
struct user_port *up_ptr;
tipc_continue_event cb = NULL;
void *uh = NULL;
p_ptr = tipc_port_lock(ref);
if (p_ptr) {
up_ptr = p_ptr->user_port;
if (up_ptr) {
cb = up_ptr->continue_event_cb;
uh = up_ptr->usr_handle;
}
tipc_port_unlock(p_ptr);
}
if (cb)
cb(uh, ref);
}
static void port_wakeup(struct tipc_port *p_ptr)
{
tipc_k_signal((Handler)port_wakeup_sh, p_ptr->ref);
}
void tipc_acknowledge(u32 ref, u32 ack)
{
struct tipc_port *p_ptr;
struct sk_buff *buf = NULL;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return;
if (p_ptr->connected) {
p_ptr->conn_unacked -= ack;
buf = port_build_proto_msg(p_ptr, CONN_ACK, ack);
}
tipc_port_unlock(p_ptr);
tipc_net_route_msg(buf);
}
/*
* tipc_createport(): user level call.
*/
int tipc_createport(void *usr_handle,
unsigned int importance,
tipc_msg_err_event error_cb,
tipc_named_msg_err_event named_error_cb,
tipc_conn_shutdown_event conn_error_cb,
tipc_msg_event msg_cb,
tipc_named_msg_event named_msg_cb,
tipc_conn_msg_event conn_msg_cb,
tipc_continue_event continue_event_cb,/* May be zero */
u32 *portref)
{
struct user_port *up_ptr;
struct tipc_port *p_ptr;
up_ptr = kmalloc(sizeof(*up_ptr), GFP_ATOMIC);
if (!up_ptr) {
warn("Port creation failed, no memory\n");
return -ENOMEM;
}
p_ptr = (struct tipc_port *)tipc_createport_raw(NULL, port_dispatcher,
port_wakeup, importance);
if (!p_ptr) {
kfree(up_ptr);
return -ENOMEM;
}
p_ptr->user_port = up_ptr;
up_ptr->usr_handle = usr_handle;
up_ptr->ref = p_ptr->ref;
up_ptr->err_cb = error_cb;
up_ptr->named_err_cb = named_error_cb;
up_ptr->conn_err_cb = conn_error_cb;
up_ptr->msg_cb = msg_cb;
up_ptr->named_msg_cb = named_msg_cb;
up_ptr->conn_msg_cb = conn_msg_cb;
up_ptr->continue_event_cb = continue_event_cb;
*portref = p_ptr->ref;
tipc_port_unlock(p_ptr);
return 0;
}
int tipc_portimportance(u32 ref, unsigned int *importance)
{
struct tipc_port *p_ptr;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
*importance = (unsigned int)msg_importance(&p_ptr->phdr);
tipc_port_unlock(p_ptr);
return 0;
}
int tipc_set_portimportance(u32 ref, unsigned int imp)
{
struct tipc_port *p_ptr;
if (imp > TIPC_CRITICAL_IMPORTANCE)
return -EINVAL;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
msg_set_importance(&p_ptr->phdr, (u32)imp);
tipc_port_unlock(p_ptr);
return 0;
}
int tipc_publish(u32 ref, unsigned int scope, struct tipc_name_seq const *seq)
{
struct tipc_port *p_ptr;
struct publication *publ;
u32 key;
int res = -EINVAL;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
if (p_ptr->connected)
goto exit;
if (seq->lower > seq->upper)
goto exit;
if ((scope < TIPC_ZONE_SCOPE) || (scope > TIPC_NODE_SCOPE))
goto exit;
key = ref + p_ptr->pub_count + 1;
if (key == ref) {
res = -EADDRINUSE;
goto exit;
}
publ = tipc_nametbl_publish(seq->type, seq->lower, seq->upper,
scope, p_ptr->ref, key);
if (publ) {
list_add(&publ->pport_list, &p_ptr->publications);
p_ptr->pub_count++;
p_ptr->published = 1;
res = 0;
}
exit:
tipc_port_unlock(p_ptr);
return res;
}
int tipc_withdraw(u32 ref, unsigned int scope, struct tipc_name_seq const *seq)
{
struct tipc_port *p_ptr;
struct publication *publ;
struct publication *tpubl;
int res = -EINVAL;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
if (!seq) {
list_for_each_entry_safe(publ, tpubl,
&p_ptr->publications, pport_list) {
tipc_nametbl_withdraw(publ->type, publ->lower,
publ->ref, publ->key);
}
res = 0;
} else {
list_for_each_entry_safe(publ, tpubl,
&p_ptr->publications, pport_list) {
if (publ->scope != scope)
continue;
if (publ->type != seq->type)
continue;
if (publ->lower != seq->lower)
continue;
if (publ->upper != seq->upper)
break;
tipc_nametbl_withdraw(publ->type, publ->lower,
publ->ref, publ->key);
res = 0;
break;
}
}
if (list_empty(&p_ptr->publications))
p_ptr->published = 0;
tipc_port_unlock(p_ptr);
return res;
}
int tipc_connect2port(u32 ref, struct tipc_portid const *peer)
{
struct tipc_port *p_ptr;
struct tipc_msg *msg;
int res = -EINVAL;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
if (p_ptr->published || p_ptr->connected)
goto exit;
if (!peer->ref)
goto exit;
msg = &p_ptr->phdr;
msg_set_destnode(msg, peer->node);
msg_set_destport(msg, peer->ref);
msg_set_type(msg, TIPC_CONN_MSG);
msg_set_lookup_scope(msg, 0);
msg_set_hdr_sz(msg, SHORT_H_SIZE);
p_ptr->probing_interval = PROBING_INTERVAL;
p_ptr->probing_state = CONFIRMED;
p_ptr->connected = 1;
k_start_timer(&p_ptr->timer, p_ptr->probing_interval);
tipc_nodesub_subscribe(&p_ptr->subscription, peer->node,
(void *)(unsigned long)ref,
(net_ev_handler)port_handle_node_down);
res = 0;
exit:
tipc_port_unlock(p_ptr);
p_ptr->max_pkt = tipc_link_get_max_pkt(peer->node, ref);
return res;
}
/**
* tipc_disconnect_port - disconnect port from peer
*
* Port must be locked.
*/
int tipc_disconnect_port(struct tipc_port *tp_ptr)
{
int res;
if (tp_ptr->connected) {
tp_ptr->connected = 0;
/* let timer expire on it's own to avoid deadlock! */
tipc_nodesub_unsubscribe(
&((struct tipc_port *)tp_ptr)->subscription);
res = 0;
} else {
res = -ENOTCONN;
}
return res;
}
/*
* tipc_disconnect(): Disconnect port form peer.
* This is a node local operation.
*/
int tipc_disconnect(u32 ref)
{
struct tipc_port *p_ptr;
int res;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
res = tipc_disconnect_port((struct tipc_port *)p_ptr);
tipc_port_unlock(p_ptr);
return res;
}
/*
* tipc_shutdown(): Send a SHUTDOWN msg to peer and disconnect
*/
int tipc_shutdown(u32 ref)
{
struct tipc_port *p_ptr;
struct sk_buff *buf = NULL;
p_ptr = tipc_port_lock(ref);
if (!p_ptr)
return -EINVAL;
buf = port_build_peer_abort_msg(p_ptr, TIPC_CONN_SHUTDOWN);
tipc_port_unlock(p_ptr);
tipc_net_route_msg(buf);
return tipc_disconnect(ref);
}
/**
* tipc_port_recv_msg - receive message from lower layer and deliver to port user
*/
int tipc_port_recv_msg(struct sk_buff *buf)
{
struct tipc_port *p_ptr;
struct tipc_msg *msg = buf_msg(buf);
u32 destport = msg_destport(msg);
u32 dsz = msg_data_sz(msg);
u32 err;
/* forward unresolved named message */
if (unlikely(!destport)) {
tipc_net_route_msg(buf);
return dsz;
}
/* validate destination & pass to port, otherwise reject message */
p_ptr = tipc_port_lock(destport);
if (likely(p_ptr)) {
if (likely(p_ptr->connected)) {
if ((unlikely(msg_origport(msg) !=
tipc_peer_port(p_ptr))) ||
(unlikely(msg_orignode(msg) !=
tipc_peer_node(p_ptr))) ||
(unlikely(!msg_connected(msg)))) {
err = TIPC_ERR_NO_PORT;
tipc_port_unlock(p_ptr);
goto reject;
}
}
err = p_ptr->dispatcher(p_ptr, buf);
tipc_port_unlock(p_ptr);
if (likely(!err))
return dsz;
} else {
err = TIPC_ERR_NO_PORT;
}
reject:
return tipc_reject_msg(buf, err);
}
/*
* tipc_port_recv_sections(): Concatenate and deliver sectioned
* message for this node.
*/
static int tipc_port_recv_sections(struct tipc_port *sender, unsigned int num_sect,
struct iovec const *msg_sect,
unsigned int total_len)
{
struct sk_buff *buf;
int res;
res = tipc_msg_build(&sender->phdr, msg_sect, num_sect, total_len,
MAX_MSG_SIZE, !sender->user_port, &buf);
if (likely(buf))
tipc_port_recv_msg(buf);
return res;
}
/**
* tipc_send - send message sections on connection
*/
int tipc_send(u32 ref, unsigned int num_sect, struct iovec const *msg_sect,
unsigned int total_len)
{
struct tipc_port *p_ptr;
u32 destnode;
int res;
p_ptr = tipc_port_deref(ref);
if (!p_ptr || !p_ptr->connected)
return -EINVAL;
p_ptr->congested = 1;
if (!tipc_port_congested(p_ptr)) {
destnode = port_peernode(p_ptr);
if (likely(destnode != tipc_own_addr))
res = tipc_link_send_sections_fast(p_ptr, msg_sect, num_sect,
total_len, destnode);
else
res = tipc_port_recv_sections(p_ptr, num_sect, msg_sect,
total_len);
if (likely(res != -ELINKCONG)) {
p_ptr->congested = 0;
if (res > 0)
p_ptr->sent++;
return res;
}
}
if (port_unreliable(p_ptr)) {
p_ptr->congested = 0;
return total_len;
}
return -ELINKCONG;
}
/**
* tipc_send2name - send message sections to port name
*/
int tipc_send2name(u32 ref, struct tipc_name const *name, unsigned int domain,
unsigned int num_sect, struct iovec const *msg_sect,
unsigned int total_len)
{
struct tipc_port *p_ptr;
struct tipc_msg *msg;
u32 destnode = domain;
u32 destport;
int res;
p_ptr = tipc_port_deref(ref);
if (!p_ptr || p_ptr->connected)
return -EINVAL;
msg = &p_ptr->phdr;
msg_set_type(msg, TIPC_NAMED_MSG);
msg_set_hdr_sz(msg, NAMED_H_SIZE);
msg_set_nametype(msg, name->type);
msg_set_nameinst(msg, name->instance);
msg_set_lookup_scope(msg, tipc_addr_scope(domain));
destport = tipc_nametbl_translate(name->type, name->instance, &destnode);
msg_set_destnode(msg, destnode);
msg_set_destport(msg, destport);
if (likely(destport || destnode)) {
if (likely(destnode == tipc_own_addr))
res = tipc_port_recv_sections(p_ptr, num_sect,
msg_sect, total_len);
else
res = tipc_link_send_sections_fast(p_ptr, msg_sect,
num_sect, total_len,
destnode);
if (likely(res != -ELINKCONG)) {
if (res > 0)
p_ptr->sent++;
return res;
}
if (port_unreliable(p_ptr)) {
return total_len;
}
return -ELINKCONG;
}
return tipc_port_reject_sections(p_ptr, msg, msg_sect, num_sect,
total_len, TIPC_ERR_NO_NAME);
}
/**
* tipc_send2port - send message sections to port identity
*/
int tipc_send2port(u32 ref, struct tipc_portid const *dest,
unsigned int num_sect, struct iovec const *msg_sect,
unsigned int total_len)
{
struct tipc_port *p_ptr;
struct tipc_msg *msg;
int res;
p_ptr = tipc_port_deref(ref);
if (!p_ptr || p_ptr->connected)
return -EINVAL;
msg = &p_ptr->phdr;
msg_set_type(msg, TIPC_DIRECT_MSG);
msg_set_lookup_scope(msg, 0);
msg_set_destnode(msg, dest->node);
msg_set_destport(msg, dest->ref);
msg_set_hdr_sz(msg, BASIC_H_SIZE);
if (dest->node == tipc_own_addr)
res = tipc_port_recv_sections(p_ptr, num_sect, msg_sect,
total_len);
else
res = tipc_link_send_sections_fast(p_ptr, msg_sect, num_sect,
total_len, dest->node);
if (likely(res != -ELINKCONG)) {
if (res > 0)
p_ptr->sent++;
return res;
}
if (port_unreliable(p_ptr)) {
return total_len;
}
return -ELINKCONG;
}
/**
* tipc_send_buf2port - send message buffer to port identity
*/
int tipc_send_buf2port(u32 ref, struct tipc_portid const *dest,
struct sk_buff *buf, unsigned int dsz)
{
struct tipc_port *p_ptr;
struct tipc_msg *msg;
int res;
p_ptr = (struct tipc_port *)tipc_ref_deref(ref);
if (!p_ptr || p_ptr->connected)
return -EINVAL;
msg = &p_ptr->phdr;
msg_set_type(msg, TIPC_DIRECT_MSG);
msg_set_destnode(msg, dest->node);
msg_set_destport(msg, dest->ref);
msg_set_hdr_sz(msg, BASIC_H_SIZE);
msg_set_size(msg, BASIC_H_SIZE + dsz);
if (skb_cow(buf, BASIC_H_SIZE))
return -ENOMEM;
skb_push(buf, BASIC_H_SIZE);
skb_copy_to_linear_data(buf, msg, BASIC_H_SIZE);
if (dest->node == tipc_own_addr)
res = tipc_port_recv_msg(buf);
else
res = tipc_send_buf_fast(buf, dest->node);
if (likely(res != -ELINKCONG)) {
if (res > 0)
p_ptr->sent++;
return res;
}
if (port_unreliable(p_ptr))
return dsz;
return -ELINKCONG;
}
| gpl-2.0 |
talnoah/Sprint-One-4.2.2-Sense | drivers/media/dvb/frontends/stb0899_drv.c | 4803 | 45882 | /*
STB0899 Multistandard Frontend driver
Copyright (C) Manu Abraham (abraham.manu@gmail.com)
Copyright (C) ST Microelectronics
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/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/dvb/frontend.h>
#include "dvb_frontend.h"
#include "stb0899_drv.h"
#include "stb0899_priv.h"
#include "stb0899_reg.h"
static unsigned int verbose = 0;//1;
module_param(verbose, int, 0644);
/* C/N in dB/10, NIRM/NIRL */
static const struct stb0899_tab stb0899_cn_tab[] = {
{ 200, 2600 },
{ 190, 2700 },
{ 180, 2860 },
{ 170, 3020 },
{ 160, 3210 },
{ 150, 3440 },
{ 140, 3710 },
{ 130, 4010 },
{ 120, 4360 },
{ 110, 4740 },
{ 100, 5190 },
{ 90, 5670 },
{ 80, 6200 },
{ 70, 6770 },
{ 60, 7360 },
{ 50, 7970 },
{ 40, 8250 },
{ 30, 9000 },
{ 20, 9450 },
{ 15, 9600 },
};
/* DVB-S AGCIQ_VALUE vs. signal level in dBm/10.
* As measured, connected to a modulator.
* -8.0 to -50.0 dBm directly connected,
* -52.0 to -74.8 with extra attenuation.
* Cut-off to AGCIQ_VALUE = 0x80 below -74.8dBm.
* Crude linear extrapolation below -84.8dBm and above -8.0dBm.
*/
static const struct stb0899_tab stb0899_dvbsrf_tab[] = {
{ -750, -128 },
{ -748, -94 },
{ -745, -92 },
{ -735, -90 },
{ -720, -87 },
{ -670, -77 },
{ -640, -70 },
{ -610, -62 },
{ -600, -60 },
{ -590, -56 },
{ -560, -41 },
{ -540, -25 },
{ -530, -17 },
{ -520, -11 },
{ -500, 1 },
{ -490, 6 },
{ -480, 10 },
{ -440, 22 },
{ -420, 27 },
{ -400, 31 },
{ -380, 34 },
{ -340, 40 },
{ -320, 43 },
{ -280, 48 },
{ -250, 52 },
{ -230, 55 },
{ -180, 61 },
{ -140, 66 },
{ -90, 73 },
{ -80, 74 },
{ 500, 127 }
};
/* DVB-S2 IF_AGC_GAIN vs. signal level in dBm/10.
* As measured, connected to a modulator.
* -8.0 to -50.1 dBm directly connected,
* -53.0 to -76.6 with extra attenuation.
* Cut-off to IF_AGC_GAIN = 0x3fff below -76.6dBm.
* Crude linear extrapolation below -76.6dBm and above -8.0dBm.
*/
static const struct stb0899_tab stb0899_dvbs2rf_tab[] = {
{ 700, 0 },
{ -80, 3217 },
{ -150, 3893 },
{ -190, 4217 },
{ -240, 4621 },
{ -280, 4945 },
{ -320, 5273 },
{ -350, 5545 },
{ -370, 5741 },
{ -410, 6147 },
{ -450, 6671 },
{ -490, 7413 },
{ -501, 7665 },
{ -530, 8767 },
{ -560, 10219 },
{ -580, 10939 },
{ -590, 11518 },
{ -600, 11723 },
{ -650, 12659 },
{ -690, 13219 },
{ -730, 13645 },
{ -750, 13909 },
{ -766, 14153 },
{ -950, 16383 }
};
/* DVB-S2 Es/N0 quant in dB/100 vs read value * 100*/
static struct stb0899_tab stb0899_quant_tab[] = {
{ 0, 0 },
{ 0, 100 },
{ 600, 200 },
{ 950, 299 },
{ 1200, 398 },
{ 1400, 501 },
{ 1560, 603 },
{ 1690, 700 },
{ 1810, 804 },
{ 1910, 902 },
{ 2000, 1000 },
{ 2080, 1096 },
{ 2160, 1202 },
{ 2230, 1303 },
{ 2350, 1496 },
{ 2410, 1603 },
{ 2460, 1698 },
{ 2510, 1799 },
{ 2600, 1995 },
{ 2650, 2113 },
{ 2690, 2213 },
{ 2720, 2291 },
{ 2760, 2399 },
{ 2800, 2512 },
{ 2860, 2692 },
{ 2930, 2917 },
{ 2960, 3020 },
{ 3010, 3199 },
{ 3040, 3311 },
{ 3060, 3388 },
{ 3120, 3631 },
{ 3190, 3936 },
{ 3400, 5012 },
{ 3610, 6383 },
{ 3800, 7943 },
{ 4210, 12735 },
{ 4500, 17783 },
{ 4690, 22131 },
{ 4810, 25410 }
};
/* DVB-S2 Es/N0 estimate in dB/100 vs read value */
static struct stb0899_tab stb0899_est_tab[] = {
{ 0, 0 },
{ 0, 1 },
{ 301, 2 },
{ 1204, 16 },
{ 1806, 64 },
{ 2408, 256 },
{ 2709, 512 },
{ 3010, 1023 },
{ 3311, 2046 },
{ 3612, 4093 },
{ 3823, 6653 },
{ 3913, 8185 },
{ 4010, 10233 },
{ 4107, 12794 },
{ 4214, 16368 },
{ 4266, 18450 },
{ 4311, 20464 },
{ 4353, 22542 },
{ 4391, 24604 },
{ 4425, 26607 },
{ 4457, 28642 },
{ 4487, 30690 },
{ 4515, 32734 },
{ 4612, 40926 },
{ 4692, 49204 },
{ 4816, 65464 },
{ 4913, 81846 },
{ 4993, 98401 },
{ 5060, 114815 },
{ 5118, 131220 },
{ 5200, 158489 },
{ 5300, 199526 },
{ 5400, 251189 },
{ 5500, 316228 },
{ 5600, 398107 },
{ 5720, 524807 },
{ 5721, 526017 },
};
static int _stb0899_read_reg(struct stb0899_state *state, unsigned int reg)
{
int ret;
u8 b0[] = { reg >> 8, reg & 0xff };
u8 buf;
struct i2c_msg msg[] = {
{
.addr = state->config->demod_address,
.flags = 0,
.buf = b0,
.len = 2
},{
.addr = state->config->demod_address,
.flags = I2C_M_RD,
.buf = &buf,
.len = 1
}
};
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
if (ret != -ERESTARTSYS)
dprintk(state->verbose, FE_ERROR, 1,
"Read error, Reg=[0x%02x], Status=%d",
reg, ret);
return ret < 0 ? ret : -EREMOTEIO;
}
if (unlikely(*state->verbose >= FE_DEBUGREG))
dprintk(state->verbose, FE_ERROR, 1, "Reg=[0x%02x], data=%02x",
reg, buf);
return (unsigned int)buf;
}
int stb0899_read_reg(struct stb0899_state *state, unsigned int reg)
{
int result;
result = _stb0899_read_reg(state, reg);
/*
* Bug ID 9:
* access to 0xf2xx/0xf6xx
* must be followed by read from 0xf2ff/0xf6ff.
*/
if ((reg != 0xf2ff) && (reg != 0xf6ff) &&
(((reg & 0xff00) == 0xf200) || ((reg & 0xff00) == 0xf600)))
_stb0899_read_reg(state, (reg | 0x00ff));
return result;
}
u32 _stb0899_read_s2reg(struct stb0899_state *state,
u32 stb0899_i2cdev,
u32 stb0899_base_addr,
u16 stb0899_reg_offset)
{
int status;
u32 data;
u8 buf[7] = { 0 };
u16 tmpaddr;
u8 buf_0[] = {
GETBYTE(stb0899_i2cdev, BYTE1), /* 0xf3 S2 Base Address (MSB) */
GETBYTE(stb0899_i2cdev, BYTE0), /* 0xfc S2 Base Address (LSB) */
GETBYTE(stb0899_base_addr, BYTE0), /* 0x00 Base Address (LSB) */
GETBYTE(stb0899_base_addr, BYTE1), /* 0x04 Base Address (LSB) */
GETBYTE(stb0899_base_addr, BYTE2), /* 0x00 Base Address (MSB) */
GETBYTE(stb0899_base_addr, BYTE3), /* 0x00 Base Address (MSB) */
};
u8 buf_1[] = {
0x00, /* 0xf3 Reg Offset */
0x00, /* 0x44 Reg Offset */
};
struct i2c_msg msg_0 = {
.addr = state->config->demod_address,
.flags = 0,
.buf = buf_0,
.len = 6
};
struct i2c_msg msg_1 = {
.addr = state->config->demod_address,
.flags = 0,
.buf = buf_1,
.len = 2
};
struct i2c_msg msg_r = {
.addr = state->config->demod_address,
.flags = I2C_M_RD,
.buf = buf,
.len = 4
};
tmpaddr = stb0899_reg_offset & 0xff00;
if (!(stb0899_reg_offset & 0x8))
tmpaddr = stb0899_reg_offset | 0x20;
buf_1[0] = GETBYTE(tmpaddr, BYTE1);
buf_1[1] = GETBYTE(tmpaddr, BYTE0);
status = i2c_transfer(state->i2c, &msg_0, 1);
if (status < 1) {
if (status != -ERESTARTSYS)
printk(KERN_ERR "%s ERR(1), Device=[0x%04x], Base address=[0x%08x], Offset=[0x%04x], Status=%d\n",
__func__, stb0899_i2cdev, stb0899_base_addr, stb0899_reg_offset, status);
goto err;
}
/* Dummy */
status = i2c_transfer(state->i2c, &msg_1, 1);
if (status < 1)
goto err;
status = i2c_transfer(state->i2c, &msg_r, 1);
if (status < 1)
goto err;
buf_1[0] = GETBYTE(stb0899_reg_offset, BYTE1);
buf_1[1] = GETBYTE(stb0899_reg_offset, BYTE0);
/* Actual */
status = i2c_transfer(state->i2c, &msg_1, 1);
if (status < 1) {
if (status != -ERESTARTSYS)
printk(KERN_ERR "%s ERR(2), Device=[0x%04x], Base address=[0x%08x], Offset=[0x%04x], Status=%d\n",
__func__, stb0899_i2cdev, stb0899_base_addr, stb0899_reg_offset, status);
goto err;
}
status = i2c_transfer(state->i2c, &msg_r, 1);
if (status < 1) {
if (status != -ERESTARTSYS)
printk(KERN_ERR "%s ERR(3), Device=[0x%04x], Base address=[0x%08x], Offset=[0x%04x], Status=%d\n",
__func__, stb0899_i2cdev, stb0899_base_addr, stb0899_reg_offset, status);
return status < 0 ? status : -EREMOTEIO;
}
data = MAKEWORD32(buf[3], buf[2], buf[1], buf[0]);
if (unlikely(*state->verbose >= FE_DEBUGREG))
printk(KERN_DEBUG "%s Device=[0x%04x], Base address=[0x%08x], Offset=[0x%04x], Data=[0x%08x]\n",
__func__, stb0899_i2cdev, stb0899_base_addr, stb0899_reg_offset, data);
return data;
err:
return status < 0 ? status : -EREMOTEIO;
}
int stb0899_write_s2reg(struct stb0899_state *state,
u32 stb0899_i2cdev,
u32 stb0899_base_addr,
u16 stb0899_reg_offset,
u32 stb0899_data)
{
int status;
/* Base Address Setup */
u8 buf_0[] = {
GETBYTE(stb0899_i2cdev, BYTE1), /* 0xf3 S2 Base Address (MSB) */
GETBYTE(stb0899_i2cdev, BYTE0), /* 0xfc S2 Base Address (LSB) */
GETBYTE(stb0899_base_addr, BYTE0), /* 0x00 Base Address (LSB) */
GETBYTE(stb0899_base_addr, BYTE1), /* 0x04 Base Address (LSB) */
GETBYTE(stb0899_base_addr, BYTE2), /* 0x00 Base Address (MSB) */
GETBYTE(stb0899_base_addr, BYTE3), /* 0x00 Base Address (MSB) */
};
u8 buf_1[] = {
0x00, /* 0xf3 Reg Offset */
0x00, /* 0x44 Reg Offset */
0x00, /* data */
0x00, /* data */
0x00, /* data */
0x00, /* data */
};
struct i2c_msg msg_0 = {
.addr = state->config->demod_address,
.flags = 0,
.buf = buf_0,
.len = 6
};
struct i2c_msg msg_1 = {
.addr = state->config->demod_address,
.flags = 0,
.buf = buf_1,
.len = 6
};
buf_1[0] = GETBYTE(stb0899_reg_offset, BYTE1);
buf_1[1] = GETBYTE(stb0899_reg_offset, BYTE0);
buf_1[2] = GETBYTE(stb0899_data, BYTE0);
buf_1[3] = GETBYTE(stb0899_data, BYTE1);
buf_1[4] = GETBYTE(stb0899_data, BYTE2);
buf_1[5] = GETBYTE(stb0899_data, BYTE3);
if (unlikely(*state->verbose >= FE_DEBUGREG))
printk(KERN_DEBUG "%s Device=[0x%04x], Base Address=[0x%08x], Offset=[0x%04x], Data=[0x%08x]\n",
__func__, stb0899_i2cdev, stb0899_base_addr, stb0899_reg_offset, stb0899_data);
status = i2c_transfer(state->i2c, &msg_0, 1);
if (unlikely(status < 1)) {
if (status != -ERESTARTSYS)
printk(KERN_ERR "%s ERR (1), Device=[0x%04x], Base Address=[0x%08x], Offset=[0x%04x], Data=[0x%08x], status=%d\n",
__func__, stb0899_i2cdev, stb0899_base_addr, stb0899_reg_offset, stb0899_data, status);
goto err;
}
status = i2c_transfer(state->i2c, &msg_1, 1);
if (unlikely(status < 1)) {
if (status != -ERESTARTSYS)
printk(KERN_ERR "%s ERR (2), Device=[0x%04x], Base Address=[0x%08x], Offset=[0x%04x], Data=[0x%08x], status=%d\n",
__func__, stb0899_i2cdev, stb0899_base_addr, stb0899_reg_offset, stb0899_data, status);
return status < 0 ? status : -EREMOTEIO;
}
return 0;
err:
return status < 0 ? status : -EREMOTEIO;
}
int stb0899_read_regs(struct stb0899_state *state, unsigned int reg, u8 *buf, u32 count)
{
int status;
u8 b0[] = { reg >> 8, reg & 0xff };
struct i2c_msg msg[] = {
{
.addr = state->config->demod_address,
.flags = 0,
.buf = b0,
.len = 2
},{
.addr = state->config->demod_address,
.flags = I2C_M_RD,
.buf = buf,
.len = count
}
};
status = i2c_transfer(state->i2c, msg, 2);
if (status != 2) {
if (status != -ERESTARTSYS)
printk(KERN_ERR "%s Read error, Reg=[0x%04x], Count=%u, Status=%d\n",
__func__, reg, count, status);
goto err;
}
/*
* Bug ID 9:
* access to 0xf2xx/0xf6xx
* must be followed by read from 0xf2ff/0xf6ff.
*/
if ((reg != 0xf2ff) && (reg != 0xf6ff) &&
(((reg & 0xff00) == 0xf200) || ((reg & 0xff00) == 0xf600)))
_stb0899_read_reg(state, (reg | 0x00ff));
if (unlikely(*state->verbose >= FE_DEBUGREG)) {
int i;
printk(KERN_DEBUG "%s [0x%04x]:", __func__, reg);
for (i = 0; i < count; i++) {
printk(" %02x", buf[i]);
}
printk("\n");
}
return 0;
err:
return status < 0 ? status : -EREMOTEIO;
}
int stb0899_write_regs(struct stb0899_state *state, unsigned int reg, u8 *data, u32 count)
{
int ret;
u8 buf[2 + count];
struct i2c_msg i2c_msg = {
.addr = state->config->demod_address,
.flags = 0,
.buf = buf,
.len = 2 + count
};
buf[0] = reg >> 8;
buf[1] = reg & 0xff;
memcpy(&buf[2], data, count);
if (unlikely(*state->verbose >= FE_DEBUGREG)) {
int i;
printk(KERN_DEBUG "%s [0x%04x]:", __func__, reg);
for (i = 0; i < count; i++)
printk(" %02x", data[i]);
printk("\n");
}
ret = i2c_transfer(state->i2c, &i2c_msg, 1);
/*
* Bug ID 9:
* access to 0xf2xx/0xf6xx
* must be followed by read from 0xf2ff/0xf6ff.
*/
if ((((reg & 0xff00) == 0xf200) || ((reg & 0xff00) == 0xf600)))
stb0899_read_reg(state, (reg | 0x00ff));
if (ret != 1) {
if (ret != -ERESTARTSYS)
dprintk(state->verbose, FE_ERROR, 1, "Reg=[0x%04x], Data=[0x%02x ...], Count=%u, Status=%d",
reg, data[0], count, ret);
return ret < 0 ? ret : -EREMOTEIO;
}
return 0;
}
int stb0899_write_reg(struct stb0899_state *state, unsigned int reg, u8 data)
{
return stb0899_write_regs(state, reg, &data, 1);
}
/*
* stb0899_get_mclk
* Get STB0899 master clock frequency
* ExtClk: external clock frequency (Hz)
*/
static u32 stb0899_get_mclk(struct stb0899_state *state)
{
u32 mclk = 0, div = 0;
div = stb0899_read_reg(state, STB0899_NCOARSE);
mclk = (div + 1) * state->config->xtal_freq / 6;
dprintk(state->verbose, FE_DEBUG, 1, "div=%d, mclk=%d", div, mclk);
return mclk;
}
/*
* stb0899_set_mclk
* Set STB0899 master Clock frequency
* Mclk: demodulator master clock
* ExtClk: external clock frequency (Hz)
*/
static void stb0899_set_mclk(struct stb0899_state *state, u32 Mclk)
{
struct stb0899_internal *internal = &state->internal;
u8 mdiv = 0;
dprintk(state->verbose, FE_DEBUG, 1, "state->config=%p", state->config);
mdiv = ((6 * Mclk) / state->config->xtal_freq) - 1;
dprintk(state->verbose, FE_DEBUG, 1, "mdiv=%d", mdiv);
stb0899_write_reg(state, STB0899_NCOARSE, mdiv);
internal->master_clk = stb0899_get_mclk(state);
dprintk(state->verbose, FE_DEBUG, 1, "MasterCLOCK=%d", internal->master_clk);
}
static int stb0899_postproc(struct stb0899_state *state, u8 ctl, int enable)
{
struct stb0899_config *config = state->config;
const struct stb0899_postproc *postproc = config->postproc;
/* post process event */
if (postproc) {
if (enable) {
if (postproc[ctl].level == STB0899_GPIOPULLUP)
stb0899_write_reg(state, postproc[ctl].gpio, 0x02);
else
stb0899_write_reg(state, postproc[ctl].gpio, 0x82);
} else {
if (postproc[ctl].level == STB0899_GPIOPULLUP)
stb0899_write_reg(state, postproc[ctl].gpio, 0x82);
else
stb0899_write_reg(state, postproc[ctl].gpio, 0x02);
}
}
return 0;
}
static void stb0899_release(struct dvb_frontend *fe)
{
struct stb0899_state *state = fe->demodulator_priv;
dprintk(state->verbose, FE_DEBUG, 1, "Release Frontend");
/* post process event */
stb0899_postproc(state, STB0899_POSTPROC_GPIO_POWER, 0);
kfree(state);
}
/*
* stb0899_get_alpha
* return: rolloff
*/
static int stb0899_get_alpha(struct stb0899_state *state)
{
u8 mode_coeff;
mode_coeff = stb0899_read_reg(state, STB0899_DEMOD);
if (STB0899_GETFIELD(MODECOEFF, mode_coeff) == 1)
return 20;
else
return 35;
}
/*
* stb0899_init_calc
*/
static void stb0899_init_calc(struct stb0899_state *state)
{
struct stb0899_internal *internal = &state->internal;
int master_clk;
u8 agc[2];
u8 agc1cn;
u32 reg;
/* Read registers (in burst mode) */
agc1cn = stb0899_read_reg(state, STB0899_AGC1CN);
stb0899_read_regs(state, STB0899_AGC1REF, agc, 2); /* AGC1R and AGC2O */
/* Initial calculations */
master_clk = stb0899_get_mclk(state);
internal->t_agc1 = 0;
internal->t_agc2 = 0;
internal->master_clk = master_clk;
internal->mclk = master_clk / 65536L;
internal->rolloff = stb0899_get_alpha(state);
/* DVBS2 Initial calculations */
/* Set AGC value to the middle */
internal->agc_gain = 8154;
reg = STB0899_READ_S2REG(STB0899_S2DEMOD, IF_AGC_CNTRL);
STB0899_SETFIELD_VAL(IF_GAIN_INIT, reg, internal->agc_gain);
stb0899_write_s2reg(state, STB0899_S2DEMOD, STB0899_BASE_IF_AGC_CNTRL, STB0899_OFF0_IF_AGC_CNTRL, reg);
reg = STB0899_READ_S2REG(STB0899_S2DEMOD, RRC_ALPHA);
internal->rrc_alpha = STB0899_GETFIELD(RRC_ALPHA, reg);
internal->center_freq = 0;
internal->av_frame_coarse = 10;
internal->av_frame_fine = 20;
internal->step_size = 2;
/*
if ((pParams->SpectralInv == FE_IQ_NORMAL) || (pParams->SpectralInv == FE_IQ_AUTO))
pParams->IQLocked = 0;
else
pParams->IQLocked = 1;
*/
}
static int stb0899_wait_diseqc_fifo_empty(struct stb0899_state *state, int timeout)
{
u8 reg = 0;
unsigned long start = jiffies;
while (1) {
reg = stb0899_read_reg(state, STB0899_DISSTATUS);
if (!STB0899_GETFIELD(FIFOFULL, reg))
break;
if ((jiffies - start) > timeout) {
dprintk(state->verbose, FE_ERROR, 1, "timed out !!");
return -ETIMEDOUT;
}
}
return 0;
}
static int stb0899_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *cmd)
{
struct stb0899_state *state = fe->demodulator_priv;
u8 reg, i;
if (cmd->msg_len > 8)
return -EINVAL;
/* enable FIFO precharge */
reg = stb0899_read_reg(state, STB0899_DISCNTRL1);
STB0899_SETFIELD_VAL(DISPRECHARGE, reg, 1);
stb0899_write_reg(state, STB0899_DISCNTRL1, reg);
for (i = 0; i < cmd->msg_len; i++) {
/* wait for FIFO empty */
if (stb0899_wait_diseqc_fifo_empty(state, 100) < 0)
return -ETIMEDOUT;
stb0899_write_reg(state, STB0899_DISFIFO, cmd->msg[i]);
}
reg = stb0899_read_reg(state, STB0899_DISCNTRL1);
STB0899_SETFIELD_VAL(DISPRECHARGE, reg, 0);
stb0899_write_reg(state, STB0899_DISCNTRL1, reg);
msleep(100);
return 0;
}
static int stb0899_wait_diseqc_rxidle(struct stb0899_state *state, int timeout)
{
u8 reg = 0;
unsigned long start = jiffies;
while (!STB0899_GETFIELD(RXEND, reg)) {
reg = stb0899_read_reg(state, STB0899_DISRX_ST0);
if (jiffies - start > timeout) {
dprintk(state->verbose, FE_ERROR, 1, "timed out!!");
return -ETIMEDOUT;
}
msleep(10);
}
return 0;
}
static int stb0899_recv_slave_reply(struct dvb_frontend *fe, struct dvb_diseqc_slave_reply *reply)
{
struct stb0899_state *state = fe->demodulator_priv;
u8 reg, length = 0, i;
int result;
if (stb0899_wait_diseqc_rxidle(state, 100) < 0)
return -ETIMEDOUT;
reg = stb0899_read_reg(state, STB0899_DISRX_ST0);
if (STB0899_GETFIELD(RXEND, reg)) {
reg = stb0899_read_reg(state, STB0899_DISRX_ST1);
length = STB0899_GETFIELD(FIFOBYTENBR, reg);
if (length > sizeof (reply->msg)) {
result = -EOVERFLOW;
goto exit;
}
reply->msg_len = length;
/* extract data */
for (i = 0; i < length; i++)
reply->msg[i] = stb0899_read_reg(state, STB0899_DISFIFO);
}
return 0;
exit:
return result;
}
static int stb0899_wait_diseqc_txidle(struct stb0899_state *state, int timeout)
{
u8 reg = 0;
unsigned long start = jiffies;
while (!STB0899_GETFIELD(TXIDLE, reg)) {
reg = stb0899_read_reg(state, STB0899_DISSTATUS);
if (jiffies - start > timeout) {
dprintk(state->verbose, FE_ERROR, 1, "timed out!!");
return -ETIMEDOUT;
}
msleep(10);
}
return 0;
}
static int stb0899_send_diseqc_burst(struct dvb_frontend *fe, fe_sec_mini_cmd_t burst)
{
struct stb0899_state *state = fe->demodulator_priv;
u8 reg, old_state;
/* wait for diseqc idle */
if (stb0899_wait_diseqc_txidle(state, 100) < 0)
return -ETIMEDOUT;
reg = stb0899_read_reg(state, STB0899_DISCNTRL1);
old_state = reg;
/* set to burst mode */
STB0899_SETFIELD_VAL(DISEQCMODE, reg, 0x03);
STB0899_SETFIELD_VAL(DISPRECHARGE, reg, 0x01);
stb0899_write_reg(state, STB0899_DISCNTRL1, reg);
switch (burst) {
case SEC_MINI_A:
/* unmodulated */
stb0899_write_reg(state, STB0899_DISFIFO, 0x00);
break;
case SEC_MINI_B:
/* modulated */
stb0899_write_reg(state, STB0899_DISFIFO, 0xff);
break;
}
reg = stb0899_read_reg(state, STB0899_DISCNTRL1);
STB0899_SETFIELD_VAL(DISPRECHARGE, reg, 0x00);
stb0899_write_reg(state, STB0899_DISCNTRL1, reg);
/* wait for diseqc idle */
if (stb0899_wait_diseqc_txidle(state, 100) < 0)
return -ETIMEDOUT;
/* restore state */
stb0899_write_reg(state, STB0899_DISCNTRL1, old_state);
return 0;
}
static int stb0899_diseqc_init(struct stb0899_state *state)
{
struct dvb_diseqc_master_cmd tx_data;
/*
struct dvb_diseqc_slave_reply rx_data;
*/
u8 f22_tx, f22_rx, reg;
u32 mclk, tx_freq = 22000;/* count = 0, i; */
tx_data.msg[0] = 0xe2;
tx_data.msg_len = 3;
reg = stb0899_read_reg(state, STB0899_DISCNTRL2);
STB0899_SETFIELD_VAL(ONECHIP_TRX, reg, 0);
stb0899_write_reg(state, STB0899_DISCNTRL2, reg);
/* disable Tx spy */
reg = stb0899_read_reg(state, STB0899_DISCNTRL1);
STB0899_SETFIELD_VAL(DISEQCRESET, reg, 1);
stb0899_write_reg(state, STB0899_DISCNTRL1, reg);
reg = stb0899_read_reg(state, STB0899_DISCNTRL1);
STB0899_SETFIELD_VAL(DISEQCRESET, reg, 0);
stb0899_write_reg(state, STB0899_DISCNTRL1, reg);
mclk = stb0899_get_mclk(state);
f22_tx = mclk / (tx_freq * 32);
stb0899_write_reg(state, STB0899_DISF22, f22_tx); /* DiSEqC Tx freq */
state->rx_freq = 20000;
f22_rx = mclk / (state->rx_freq * 32);
return 0;
}
static int stb0899_sleep(struct dvb_frontend *fe)
{
struct stb0899_state *state = fe->demodulator_priv;
/*
u8 reg;
*/
dprintk(state->verbose, FE_DEBUG, 1, "Going to Sleep .. (Really tired .. :-))");
/* post process event */
stb0899_postproc(state, STB0899_POSTPROC_GPIO_POWER, 0);
return 0;
}
static int stb0899_wakeup(struct dvb_frontend *fe)
{
int rc;
struct stb0899_state *state = fe->demodulator_priv;
if ((rc = stb0899_write_reg(state, STB0899_SYNTCTRL, STB0899_SELOSCI)))
return rc;
/* Activate all clocks; DVB-S2 registers are inaccessible otherwise. */
if ((rc = stb0899_write_reg(state, STB0899_STOPCLK1, 0x00)))
return rc;
if ((rc = stb0899_write_reg(state, STB0899_STOPCLK2, 0x00)))
return rc;
/* post process event */
stb0899_postproc(state, STB0899_POSTPROC_GPIO_POWER, 1);
return 0;
}
static int stb0899_init(struct dvb_frontend *fe)
{
int i;
struct stb0899_state *state = fe->demodulator_priv;
struct stb0899_config *config = state->config;
dprintk(state->verbose, FE_DEBUG, 1, "Initializing STB0899 ... ");
/* init device */
dprintk(state->verbose, FE_DEBUG, 1, "init device");
for (i = 0; config->init_dev[i].address != 0xffff; i++)
stb0899_write_reg(state, config->init_dev[i].address, config->init_dev[i].data);
dprintk(state->verbose, FE_DEBUG, 1, "init S2 demod");
/* init S2 demod */
for (i = 0; config->init_s2_demod[i].offset != 0xffff; i++)
stb0899_write_s2reg(state, STB0899_S2DEMOD,
config->init_s2_demod[i].base_address,
config->init_s2_demod[i].offset,
config->init_s2_demod[i].data);
dprintk(state->verbose, FE_DEBUG, 1, "init S1 demod");
/* init S1 demod */
for (i = 0; config->init_s1_demod[i].address != 0xffff; i++)
stb0899_write_reg(state, config->init_s1_demod[i].address, config->init_s1_demod[i].data);
dprintk(state->verbose, FE_DEBUG, 1, "init S2 FEC");
/* init S2 fec */
for (i = 0; config->init_s2_fec[i].offset != 0xffff; i++)
stb0899_write_s2reg(state, STB0899_S2FEC,
config->init_s2_fec[i].base_address,
config->init_s2_fec[i].offset,
config->init_s2_fec[i].data);
dprintk(state->verbose, FE_DEBUG, 1, "init TST");
/* init test */
for (i = 0; config->init_tst[i].address != 0xffff; i++)
stb0899_write_reg(state, config->init_tst[i].address, config->init_tst[i].data);
stb0899_init_calc(state);
stb0899_diseqc_init(state);
return 0;
}
static int stb0899_table_lookup(const struct stb0899_tab *tab, int max, int val)
{
int res = 0;
int min = 0, med;
if (val < tab[min].read)
res = tab[min].real;
else if (val >= tab[max].read)
res = tab[max].real;
else {
while ((max - min) > 1) {
med = (max + min) / 2;
if (val >= tab[min].read && val < tab[med].read)
max = med;
else
min = med;
}
res = ((val - tab[min].read) *
(tab[max].real - tab[min].real) /
(tab[max].read - tab[min].read)) +
tab[min].real;
}
return res;
}
static int stb0899_read_signal_strength(struct dvb_frontend *fe, u16 *strength)
{
struct stb0899_state *state = fe->demodulator_priv;
struct stb0899_internal *internal = &state->internal;
int val;
u32 reg;
*strength = 0;
switch (state->delsys) {
case SYS_DVBS:
case SYS_DSS:
if (internal->lock) {
reg = stb0899_read_reg(state, STB0899_VSTATUS);
if (STB0899_GETFIELD(VSTATUS_LOCKEDVIT, reg)) {
reg = stb0899_read_reg(state, STB0899_AGCIQIN);
val = (s32)(s8)STB0899_GETFIELD(AGCIQVALUE, reg);
*strength = stb0899_table_lookup(stb0899_dvbsrf_tab, ARRAY_SIZE(stb0899_dvbsrf_tab) - 1, val);
*strength += 750;
dprintk(state->verbose, FE_DEBUG, 1, "AGCIQVALUE = 0x%02x, C = %d * 0.1 dBm",
val & 0xff, *strength);
}
}
break;
case SYS_DVBS2:
if (internal->lock) {
reg = STB0899_READ_S2REG(STB0899_S2DEMOD, IF_AGC_GAIN);
val = STB0899_GETFIELD(IF_AGC_GAIN, reg);
*strength = stb0899_table_lookup(stb0899_dvbs2rf_tab, ARRAY_SIZE(stb0899_dvbs2rf_tab) - 1, val);
*strength += 950;
dprintk(state->verbose, FE_DEBUG, 1, "IF_AGC_GAIN = 0x%04x, C = %d * 0.1 dBm",
val & 0x3fff, *strength);
}
break;
default:
dprintk(state->verbose, FE_DEBUG, 1, "Unsupported delivery system");
return -EINVAL;
}
return 0;
}
static int stb0899_read_snr(struct dvb_frontend *fe, u16 *snr)
{
struct stb0899_state *state = fe->demodulator_priv;
struct stb0899_internal *internal = &state->internal;
unsigned int val, quant, quantn = -1, est, estn = -1;
u8 buf[2];
u32 reg;
*snr = 0;
reg = stb0899_read_reg(state, STB0899_VSTATUS);
switch (state->delsys) {
case SYS_DVBS:
case SYS_DSS:
if (internal->lock) {
if (STB0899_GETFIELD(VSTATUS_LOCKEDVIT, reg)) {
stb0899_read_regs(state, STB0899_NIRM, buf, 2);
val = MAKEWORD16(buf[0], buf[1]);
*snr = stb0899_table_lookup(stb0899_cn_tab, ARRAY_SIZE(stb0899_cn_tab) - 1, val);
dprintk(state->verbose, FE_DEBUG, 1, "NIR = 0x%02x%02x = %u, C/N = %d * 0.1 dBm\n",
buf[0], buf[1], val, *snr);
}
}
break;
case SYS_DVBS2:
if (internal->lock) {
reg = STB0899_READ_S2REG(STB0899_S2DEMOD, UWP_CNTRL1);
quant = STB0899_GETFIELD(UWP_ESN0_QUANT, reg);
reg = STB0899_READ_S2REG(STB0899_S2DEMOD, UWP_STAT2);
est = STB0899_GETFIELD(ESN0_EST, reg);
if (est == 1)
val = 301; /* C/N = 30.1 dB */
else if (est == 2)
val = 270; /* C/N = 27.0 dB */
else {
/* quantn = 100 * log(quant^2) */
quantn = stb0899_table_lookup(stb0899_quant_tab, ARRAY_SIZE(stb0899_quant_tab) - 1, quant * 100);
/* estn = 100 * log(est) */
estn = stb0899_table_lookup(stb0899_est_tab, ARRAY_SIZE(stb0899_est_tab) - 1, est);
/* snr(dBm/10) = -10*(log(est)-log(quant^2)) => snr(dBm/10) = (100*log(quant^2)-100*log(est))/10 */
val = (quantn - estn) / 10;
}
*snr = val;
dprintk(state->verbose, FE_DEBUG, 1, "Es/N0 quant = %d (%d) estimate = %u (%d), C/N = %d * 0.1 dBm",
quant, quantn, est, estn, val);
}
break;
default:
dprintk(state->verbose, FE_DEBUG, 1, "Unsupported delivery system");
return -EINVAL;
}
return 0;
}
static int stb0899_read_status(struct dvb_frontend *fe, enum fe_status *status)
{
struct stb0899_state *state = fe->demodulator_priv;
struct stb0899_internal *internal = &state->internal;
u8 reg;
*status = 0;
switch (state->delsys) {
case SYS_DVBS:
case SYS_DSS:
dprintk(state->verbose, FE_DEBUG, 1, "Delivery system DVB-S/DSS");
if (internal->lock) {
reg = stb0899_read_reg(state, STB0899_VSTATUS);
if (STB0899_GETFIELD(VSTATUS_LOCKEDVIT, reg)) {
dprintk(state->verbose, FE_DEBUG, 1, "--------> FE_HAS_CARRIER | FE_HAS_LOCK");
*status |= FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_LOCK;
reg = stb0899_read_reg(state, STB0899_PLPARM);
if (STB0899_GETFIELD(VITCURPUN, reg)) {
dprintk(state->verbose, FE_DEBUG, 1, "--------> FE_HAS_VITERBI | FE_HAS_SYNC");
*status |= FE_HAS_VITERBI | FE_HAS_SYNC;
/* post process event */
stb0899_postproc(state, STB0899_POSTPROC_GPIO_LOCK, 1);
}
}
}
break;
case SYS_DVBS2:
dprintk(state->verbose, FE_DEBUG, 1, "Delivery system DVB-S2");
if (internal->lock) {
reg = STB0899_READ_S2REG(STB0899_S2DEMOD, DMD_STAT2);
if (STB0899_GETFIELD(UWP_LOCK, reg) && STB0899_GETFIELD(CSM_LOCK, reg)) {
*status |= FE_HAS_CARRIER;
dprintk(state->verbose, FE_DEBUG, 1,
"UWP & CSM Lock ! ---> DVB-S2 FE_HAS_CARRIER");
reg = stb0899_read_reg(state, STB0899_CFGPDELSTATUS1);
if (STB0899_GETFIELD(CFGPDELSTATUS_LOCK, reg)) {
*status |= FE_HAS_LOCK;
dprintk(state->verbose, FE_DEBUG, 1,
"Packet Delineator Locked ! -----> DVB-S2 FE_HAS_LOCK");
}
if (STB0899_GETFIELD(CONTINUOUS_STREAM, reg)) {
*status |= FE_HAS_VITERBI;
dprintk(state->verbose, FE_DEBUG, 1,
"Packet Delineator found VITERBI ! -----> DVB-S2 FE_HAS_VITERBI");
}
if (STB0899_GETFIELD(ACCEPTED_STREAM, reg)) {
*status |= FE_HAS_SYNC;
dprintk(state->verbose, FE_DEBUG, 1,
"Packet Delineator found SYNC ! -----> DVB-S2 FE_HAS_SYNC");
/* post process event */
stb0899_postproc(state, STB0899_POSTPROC_GPIO_LOCK, 1);
}
}
}
break;
default:
dprintk(state->verbose, FE_DEBUG, 1, "Unsupported delivery system");
return -EINVAL;
}
return 0;
}
/*
* stb0899_get_error
* viterbi error for DVB-S/DSS
* packet error for DVB-S2
* Bit Error Rate or Packet Error Rate * 10 ^ 7
*/
static int stb0899_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct stb0899_state *state = fe->demodulator_priv;
struct stb0899_internal *internal = &state->internal;
u8 lsb, msb;
u32 i;
*ber = 0;
switch (state->delsys) {
case SYS_DVBS:
case SYS_DSS:
if (internal->lock) {
/* average 5 BER values */
for (i = 0; i < 5; i++) {
msleep(100);
lsb = stb0899_read_reg(state, STB0899_ECNT1L);
msb = stb0899_read_reg(state, STB0899_ECNT1M);
*ber += MAKEWORD16(msb, lsb);
}
*ber /= 5;
/* Viterbi Check */
if (STB0899_GETFIELD(VSTATUS_PRFVIT, internal->v_status)) {
/* Error Rate */
*ber *= 9766;
/* ber = ber * 10 ^ 7 */
*ber /= (-1 + (1 << (2 * STB0899_GETFIELD(NOE, internal->err_ctrl))));
*ber /= 8;
}
}
break;
case SYS_DVBS2:
if (internal->lock) {
/* Average 5 PER values */
for (i = 0; i < 5; i++) {
msleep(100);
lsb = stb0899_read_reg(state, STB0899_ECNT1L);
msb = stb0899_read_reg(state, STB0899_ECNT1M);
*ber += MAKEWORD16(msb, lsb);
}
/* ber = ber * 10 ^ 7 */
*ber *= 10000000;
*ber /= (-1 + (1 << (4 + 2 * STB0899_GETFIELD(NOE, internal->err_ctrl))));
}
break;
default:
dprintk(state->verbose, FE_DEBUG, 1, "Unsupported delivery system");
return -EINVAL;
}
return 0;
}
static int stb0899_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
struct stb0899_state *state = fe->demodulator_priv;
switch (voltage) {
case SEC_VOLTAGE_13:
stb0899_write_reg(state, STB0899_GPIO00CFG, 0x82);
stb0899_write_reg(state, STB0899_GPIO01CFG, 0x02);
stb0899_write_reg(state, STB0899_GPIO02CFG, 0x00);
break;
case SEC_VOLTAGE_18:
stb0899_write_reg(state, STB0899_GPIO00CFG, 0x02);
stb0899_write_reg(state, STB0899_GPIO01CFG, 0x02);
stb0899_write_reg(state, STB0899_GPIO02CFG, 0x82);
break;
case SEC_VOLTAGE_OFF:
stb0899_write_reg(state, STB0899_GPIO00CFG, 0x82);
stb0899_write_reg(state, STB0899_GPIO01CFG, 0x82);
stb0899_write_reg(state, STB0899_GPIO02CFG, 0x82);
break;
default:
return -EINVAL;
}
return 0;
}
static int stb0899_set_tone(struct dvb_frontend *fe, fe_sec_tone_mode_t tone)
{
struct stb0899_state *state = fe->demodulator_priv;
struct stb0899_internal *internal = &state->internal;
u8 div, reg;
/* wait for diseqc idle */
if (stb0899_wait_diseqc_txidle(state, 100) < 0)
return -ETIMEDOUT;
switch (tone) {
case SEC_TONE_ON:
div = (internal->master_clk / 100) / 5632;
div = (div + 5) / 10;
stb0899_write_reg(state, STB0899_DISEQCOCFG, 0x66);
reg = stb0899_read_reg(state, STB0899_ACRPRESC);
STB0899_SETFIELD_VAL(ACRPRESC, reg, 0x03);
stb0899_write_reg(state, STB0899_ACRPRESC, reg);
stb0899_write_reg(state, STB0899_ACRDIV1, div);
break;
case SEC_TONE_OFF:
stb0899_write_reg(state, STB0899_DISEQCOCFG, 0x20);
break;
default:
return -EINVAL;
}
return 0;
}
int stb0899_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
int i2c_stat;
struct stb0899_state *state = fe->demodulator_priv;
i2c_stat = stb0899_read_reg(state, STB0899_I2CRPT);
if (i2c_stat < 0)
goto err;
if (enable) {
dprintk(state->verbose, FE_DEBUG, 1, "Enabling I2C Repeater ...");
i2c_stat |= STB0899_I2CTON;
if (stb0899_write_reg(state, STB0899_I2CRPT, i2c_stat) < 0)
goto err;
} else {
dprintk(state->verbose, FE_DEBUG, 1, "Disabling I2C Repeater ...");
i2c_stat &= ~STB0899_I2CTON;
if (stb0899_write_reg(state, STB0899_I2CRPT, i2c_stat) < 0)
goto err;
}
return 0;
err:
dprintk(state->verbose, FE_ERROR, 1, "I2C Repeater control failed");
return -EREMOTEIO;
}
static inline void CONVERT32(u32 x, char *str)
{
*str++ = (x >> 24) & 0xff;
*str++ = (x >> 16) & 0xff;
*str++ = (x >> 8) & 0xff;
*str++ = (x >> 0) & 0xff;
*str = '\0';
}
int stb0899_get_dev_id(struct stb0899_state *state)
{
u8 chip_id, release;
u16 id;
u32 demod_ver = 0, fec_ver = 0;
char demod_str[5] = { 0 };
char fec_str[5] = { 0 };
id = stb0899_read_reg(state, STB0899_DEV_ID);
dprintk(state->verbose, FE_DEBUG, 1, "ID reg=[0x%02x]", id);
chip_id = STB0899_GETFIELD(CHIP_ID, id);
release = STB0899_GETFIELD(CHIP_REL, id);
dprintk(state->verbose, FE_ERROR, 1, "Device ID=[%d], Release=[%d]",
chip_id, release);
CONVERT32(STB0899_READ_S2REG(STB0899_S2DEMOD, DMD_CORE_ID), (char *)&demod_str);
demod_ver = STB0899_READ_S2REG(STB0899_S2DEMOD, DMD_VERSION_ID);
dprintk(state->verbose, FE_ERROR, 1, "Demodulator Core ID=[%s], Version=[%d]", (char *) &demod_str, demod_ver);
CONVERT32(STB0899_READ_S2REG(STB0899_S2FEC, FEC_CORE_ID_REG), (char *)&fec_str);
fec_ver = STB0899_READ_S2REG(STB0899_S2FEC, FEC_VER_ID_REG);
if (! (chip_id > 0)) {
dprintk(state->verbose, FE_ERROR, 1, "couldn't find a STB 0899");
return -ENODEV;
}
dprintk(state->verbose, FE_ERROR, 1, "FEC Core ID=[%s], Version=[%d]", (char*) &fec_str, fec_ver);
return 0;
}
static void stb0899_set_delivery(struct stb0899_state *state)
{
u8 reg;
u8 stop_clk[2];
stop_clk[0] = stb0899_read_reg(state, STB0899_STOPCLK1);
stop_clk[1] = stb0899_read_reg(state, STB0899_STOPCLK2);
switch (state->delsys) {
case SYS_DVBS:
dprintk(state->verbose, FE_DEBUG, 1, "Delivery System -- DVB-S");
/* FECM/Viterbi ON */
reg = stb0899_read_reg(state, STB0899_FECM);
STB0899_SETFIELD_VAL(FECM_RSVD0, reg, 0);
STB0899_SETFIELD_VAL(FECM_VITERBI_ON, reg, 1);
stb0899_write_reg(state, STB0899_FECM, reg);
stb0899_write_reg(state, STB0899_RSULC, 0xb1);
stb0899_write_reg(state, STB0899_TSULC, 0x40);
stb0899_write_reg(state, STB0899_RSLLC, 0x42);
stb0899_write_reg(state, STB0899_TSLPL, 0x12);
reg = stb0899_read_reg(state, STB0899_TSTRES);
STB0899_SETFIELD_VAL(FRESLDPC, reg, 1);
stb0899_write_reg(state, STB0899_TSTRES, reg);
STB0899_SETFIELD_VAL(STOP_CHK8PSK, stop_clk[0], 1);
STB0899_SETFIELD_VAL(STOP_CKFEC108, stop_clk[0], 1);
STB0899_SETFIELD_VAL(STOP_CKFEC216, stop_clk[0], 1);
STB0899_SETFIELD_VAL(STOP_CKPKDLIN108, stop_clk[1], 1);
STB0899_SETFIELD_VAL(STOP_CKPKDLIN216, stop_clk[1], 1);
STB0899_SETFIELD_VAL(STOP_CKINTBUF216, stop_clk[0], 1);
STB0899_SETFIELD_VAL(STOP_CKCORE216, stop_clk[0], 0);
STB0899_SETFIELD_VAL(STOP_CKS2DMD108, stop_clk[1], 1);
break;
case SYS_DVBS2:
/* FECM/Viterbi OFF */
reg = stb0899_read_reg(state, STB0899_FECM);
STB0899_SETFIELD_VAL(FECM_RSVD0, reg, 0);
STB0899_SETFIELD_VAL(FECM_VITERBI_ON, reg, 0);
stb0899_write_reg(state, STB0899_FECM, reg);
stb0899_write_reg(state, STB0899_RSULC, 0xb1);
stb0899_write_reg(state, STB0899_TSULC, 0x42);
stb0899_write_reg(state, STB0899_RSLLC, 0x40);
stb0899_write_reg(state, STB0899_TSLPL, 0x02);
reg = stb0899_read_reg(state, STB0899_TSTRES);
STB0899_SETFIELD_VAL(FRESLDPC, reg, 0);
stb0899_write_reg(state, STB0899_TSTRES, reg);
STB0899_SETFIELD_VAL(STOP_CHK8PSK, stop_clk[0], 1);
STB0899_SETFIELD_VAL(STOP_CKFEC108, stop_clk[0], 0);
STB0899_SETFIELD_VAL(STOP_CKFEC216, stop_clk[0], 0);
STB0899_SETFIELD_VAL(STOP_CKPKDLIN108, stop_clk[1], 0);
STB0899_SETFIELD_VAL(STOP_CKPKDLIN216, stop_clk[1], 0);
STB0899_SETFIELD_VAL(STOP_CKINTBUF216, stop_clk[0], 0);
STB0899_SETFIELD_VAL(STOP_CKCORE216, stop_clk[0], 0);
STB0899_SETFIELD_VAL(STOP_CKS2DMD108, stop_clk[1], 0);
break;
case SYS_DSS:
/* FECM/Viterbi ON */
reg = stb0899_read_reg(state, STB0899_FECM);
STB0899_SETFIELD_VAL(FECM_RSVD0, reg, 1);
STB0899_SETFIELD_VAL(FECM_VITERBI_ON, reg, 1);
stb0899_write_reg(state, STB0899_FECM, reg);
stb0899_write_reg(state, STB0899_RSULC, 0xa1);
stb0899_write_reg(state, STB0899_TSULC, 0x61);
stb0899_write_reg(state, STB0899_RSLLC, 0x42);
reg = stb0899_read_reg(state, STB0899_TSTRES);
STB0899_SETFIELD_VAL(FRESLDPC, reg, 1);
stb0899_write_reg(state, STB0899_TSTRES, reg);
STB0899_SETFIELD_VAL(STOP_CHK8PSK, stop_clk[0], 1);
STB0899_SETFIELD_VAL(STOP_CKFEC108, stop_clk[0], 1);
STB0899_SETFIELD_VAL(STOP_CKFEC216, stop_clk[0], 1);
STB0899_SETFIELD_VAL(STOP_CKPKDLIN108, stop_clk[1], 1);
STB0899_SETFIELD_VAL(STOP_CKPKDLIN216, stop_clk[1], 1);
STB0899_SETFIELD_VAL(STOP_CKCORE216, stop_clk[0], 0);
STB0899_SETFIELD_VAL(STOP_CKS2DMD108, stop_clk[1], 1);
break;
default:
dprintk(state->verbose, FE_ERROR, 1, "Unsupported delivery system");
break;
}
STB0899_SETFIELD_VAL(STOP_CKADCI108, stop_clk[0], 0);
stb0899_write_regs(state, STB0899_STOPCLK1, stop_clk, 2);
}
/*
* stb0899_set_iterations
* set the LDPC iteration scale function
*/
static void stb0899_set_iterations(struct stb0899_state *state)
{
struct stb0899_internal *internal = &state->internal;
struct stb0899_config *config = state->config;
s32 iter_scale;
u32 reg;
iter_scale = 17 * (internal->master_clk / 1000);
iter_scale += 410000;
iter_scale /= (internal->srate / 1000000);
iter_scale /= 1000;
if (iter_scale > config->ldpc_max_iter)
iter_scale = config->ldpc_max_iter;
reg = STB0899_READ_S2REG(STB0899_S2FEC, MAX_ITER);
STB0899_SETFIELD_VAL(MAX_ITERATIONS, reg, iter_scale);
stb0899_write_s2reg(state, STB0899_S2FEC, STB0899_BASE_MAX_ITER, STB0899_OFF0_MAX_ITER, reg);
}
static enum dvbfe_search stb0899_search(struct dvb_frontend *fe)
{
struct stb0899_state *state = fe->demodulator_priv;
struct stb0899_params *i_params = &state->params;
struct stb0899_internal *internal = &state->internal;
struct stb0899_config *config = state->config;
struct dtv_frontend_properties *props = &fe->dtv_property_cache;
u32 SearchRange, gain;
i_params->freq = props->frequency;
i_params->srate = props->symbol_rate;
state->delsys = props->delivery_system;
dprintk(state->verbose, FE_DEBUG, 1, "delivery system=%d", state->delsys);
SearchRange = 10000000;
dprintk(state->verbose, FE_DEBUG, 1, "Frequency=%d, Srate=%d", i_params->freq, i_params->srate);
/* checking Search Range is meaningless for a fixed 3 Mhz */
if (INRANGE(i_params->srate, 1000000, 45000000)) {
dprintk(state->verbose, FE_DEBUG, 1, "Parameters IN RANGE");
stb0899_set_delivery(state);
if (state->config->tuner_set_rfsiggain) {
if (internal->srate > 15000000)
gain = 8; /* 15Mb < srate < 45Mb, gain = 8dB */
else if (internal->srate > 5000000)
gain = 12; /* 5Mb < srate < 15Mb, gain = 12dB */
else
gain = 14; /* 1Mb < srate < 5Mb, gain = 14db */
state->config->tuner_set_rfsiggain(fe, gain);
}
if (i_params->srate <= 5000000)
stb0899_set_mclk(state, config->lo_clk);
else
stb0899_set_mclk(state, config->hi_clk);
switch (state->delsys) {
case SYS_DVBS:
case SYS_DSS:
dprintk(state->verbose, FE_DEBUG, 1, "DVB-S delivery system");
internal->freq = i_params->freq;
internal->srate = i_params->srate;
/*
* search = user search range +
* 500Khz +
* 2 * Tuner_step_size +
* 10% of the symbol rate
*/
internal->srch_range = SearchRange + 1500000 + (i_params->srate / 5);
internal->derot_percent = 30;
/* What to do for tuners having no bandwidth setup ? */
/* enable tuner I/O */
stb0899_i2c_gate_ctrl(&state->frontend, 1);
if (state->config->tuner_set_bandwidth)
state->config->tuner_set_bandwidth(fe, (13 * (stb0899_carr_width(state) + SearchRange)) / 10);
if (state->config->tuner_get_bandwidth)
state->config->tuner_get_bandwidth(fe, &internal->tuner_bw);
/* disable tuner I/O */
stb0899_i2c_gate_ctrl(&state->frontend, 0);
/* Set DVB-S1 AGC */
stb0899_write_reg(state, STB0899_AGCRFCFG, 0x11);
/* Run the search algorithm */
dprintk(state->verbose, FE_DEBUG, 1, "running DVB-S search algo ..");
if (stb0899_dvbs_algo(state) == RANGEOK) {
internal->lock = 1;
dprintk(state->verbose, FE_DEBUG, 1,
"-------------------------------------> DVB-S LOCK !");
// stb0899_write_reg(state, STB0899_ERRCTRL1, 0x3d); /* Viterbi Errors */
// internal->v_status = stb0899_read_reg(state, STB0899_VSTATUS);
// internal->err_ctrl = stb0899_read_reg(state, STB0899_ERRCTRL1);
// dprintk(state->verbose, FE_DEBUG, 1, "VSTATUS=0x%02x", internal->v_status);
// dprintk(state->verbose, FE_DEBUG, 1, "ERR_CTRL=0x%02x", internal->err_ctrl);
return DVBFE_ALGO_SEARCH_SUCCESS;
} else {
internal->lock = 0;
return DVBFE_ALGO_SEARCH_FAILED;
}
break;
case SYS_DVBS2:
internal->freq = i_params->freq;
internal->srate = i_params->srate;
internal->srch_range = SearchRange;
/* enable tuner I/O */
stb0899_i2c_gate_ctrl(&state->frontend, 1);
if (state->config->tuner_set_bandwidth)
state->config->tuner_set_bandwidth(fe, (stb0899_carr_width(state) + SearchRange));
if (state->config->tuner_get_bandwidth)
state->config->tuner_get_bandwidth(fe, &internal->tuner_bw);
/* disable tuner I/O */
stb0899_i2c_gate_ctrl(&state->frontend, 0);
// pParams->SpectralInv = pSearch->IQ_Inversion;
/* Set DVB-S2 AGC */
stb0899_write_reg(state, STB0899_AGCRFCFG, 0x1c);
/* Set IterScale =f(MCLK,SYMB) */
stb0899_set_iterations(state);
/* Run the search algorithm */
dprintk(state->verbose, FE_DEBUG, 1, "running DVB-S2 search algo ..");
if (stb0899_dvbs2_algo(state) == DVBS2_FEC_LOCK) {
internal->lock = 1;
dprintk(state->verbose, FE_DEBUG, 1,
"-------------------------------------> DVB-S2 LOCK !");
// stb0899_write_reg(state, STB0899_ERRCTRL1, 0xb6); /* Packet Errors */
// internal->v_status = stb0899_read_reg(state, STB0899_VSTATUS);
// internal->err_ctrl = stb0899_read_reg(state, STB0899_ERRCTRL1);
return DVBFE_ALGO_SEARCH_SUCCESS;
} else {
internal->lock = 0;
return DVBFE_ALGO_SEARCH_FAILED;
}
break;
default:
dprintk(state->verbose, FE_ERROR, 1, "Unsupported delivery system");
return DVBFE_ALGO_SEARCH_INVALID;
}
}
return DVBFE_ALGO_SEARCH_ERROR;
}
static int stb0899_get_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct stb0899_state *state = fe->demodulator_priv;
struct stb0899_internal *internal = &state->internal;
dprintk(state->verbose, FE_DEBUG, 1, "Get params");
p->symbol_rate = internal->srate;
return 0;
}
static enum dvbfe_algo stb0899_frontend_algo(struct dvb_frontend *fe)
{
return DVBFE_ALGO_CUSTOM;
}
static struct dvb_frontend_ops stb0899_ops = {
.delsys = { SYS_DVBS, SYS_DVBS2, SYS_DSS },
.info = {
.name = "STB0899 Multistandard",
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_stepsize = 0,
.frequency_tolerance = 0,
.symbol_rate_min = 5000000,
.symbol_rate_max = 45000000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_AUTO |
FE_CAN_2G_MODULATION |
FE_CAN_QPSK
},
.release = stb0899_release,
.init = stb0899_init,
.sleep = stb0899_sleep,
// .wakeup = stb0899_wakeup,
.i2c_gate_ctrl = stb0899_i2c_gate_ctrl,
.get_frontend_algo = stb0899_frontend_algo,
.search = stb0899_search,
.get_frontend = stb0899_get_frontend,
.read_status = stb0899_read_status,
.read_snr = stb0899_read_snr,
.read_signal_strength = stb0899_read_signal_strength,
.read_ber = stb0899_read_ber,
.set_voltage = stb0899_set_voltage,
.set_tone = stb0899_set_tone,
.diseqc_send_master_cmd = stb0899_send_diseqc_msg,
.diseqc_recv_slave_reply = stb0899_recv_slave_reply,
.diseqc_send_burst = stb0899_send_diseqc_burst,
};
struct dvb_frontend *stb0899_attach(struct stb0899_config *config, struct i2c_adapter *i2c)
{
struct stb0899_state *state = NULL;
enum stb0899_inversion inversion;
state = kzalloc(sizeof (struct stb0899_state), GFP_KERNEL);
if (state == NULL)
goto error;
inversion = config->inversion;
state->verbose = &verbose;
state->config = config;
state->i2c = i2c;
state->frontend.ops = stb0899_ops;
state->frontend.demodulator_priv = state;
state->internal.inversion = inversion;
stb0899_wakeup(&state->frontend);
if (stb0899_get_dev_id(state) == -ENODEV) {
printk("%s: Exiting .. !\n", __func__);
goto error;
}
printk("%s: Attaching STB0899 \n", __func__);
return &state->frontend;
error:
kfree(state);
return NULL;
}
EXPORT_SYMBOL(stb0899_attach);
MODULE_PARM_DESC(verbose, "Set Verbosity level");
MODULE_AUTHOR("Manu Abraham");
MODULE_DESCRIPTION("STB0899 Multi-Std frontend");
MODULE_LICENSE("GPL");
| gpl-2.0 |
boa19861105/BOA-A4TW | drivers/regulator/max8925-regulator.c | 4803 | 8875 | /*
* Regulators driver for Maxim max8925
*
* Copyright (C) 2009 Marvell International Ltd.
* Haojian Zhuang <haojian.zhuang@marvell.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/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#include <linux/mfd/max8925.h>
#define SD1_DVM_VMIN 850000
#define SD1_DVM_VMAX 1000000
#define SD1_DVM_STEP 50000
#define SD1_DVM_SHIFT 5 /* SDCTL1 bit5 */
#define SD1_DVM_EN 6 /* SDV1 bit 6 */
/* bit definitions in LDO control registers */
#define LDO_SEQ_I2C 0x7 /* Power U/D by i2c */
#define LDO_SEQ_MASK 0x7 /* Power U/D sequence mask */
#define LDO_SEQ_SHIFT 2 /* Power U/D sequence offset */
#define LDO_I2C_EN 0x1 /* Enable by i2c */
#define LDO_I2C_EN_MASK 0x1 /* Enable mask by i2c */
#define LDO_I2C_EN_SHIFT 0 /* Enable offset by i2c */
struct max8925_regulator_info {
struct regulator_desc desc;
struct regulator_dev *regulator;
struct i2c_client *i2c;
struct max8925_chip *chip;
int min_uV;
int max_uV;
int step_uV;
int vol_reg;
int vol_shift;
int vol_nbits;
int enable_reg;
};
static inline int check_range(struct max8925_regulator_info *info,
int min_uV, int max_uV)
{
if (min_uV < info->min_uV || min_uV > info->max_uV)
return -EINVAL;
return 0;
}
static int max8925_list_voltage(struct regulator_dev *rdev, unsigned index)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
return info->min_uV + index * info->step_uV;
}
static int max8925_set_voltage(struct regulator_dev *rdev,
int min_uV, int max_uV, unsigned int *selector)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
unsigned char data, mask;
if (check_range(info, min_uV, max_uV)) {
dev_err(info->chip->dev, "invalid voltage range (%d, %d) uV\n",
min_uV, max_uV);
return -EINVAL;
}
data = DIV_ROUND_UP(min_uV - info->min_uV, info->step_uV);
*selector = data;
data <<= info->vol_shift;
mask = ((1 << info->vol_nbits) - 1) << info->vol_shift;
return max8925_set_bits(info->i2c, info->vol_reg, mask, data);
}
static int max8925_get_voltage(struct regulator_dev *rdev)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
unsigned char data, mask;
int ret;
ret = max8925_reg_read(info->i2c, info->vol_reg);
if (ret < 0)
return ret;
mask = ((1 << info->vol_nbits) - 1) << info->vol_shift;
data = (ret & mask) >> info->vol_shift;
return max8925_list_voltage(rdev, data);
}
static int max8925_enable(struct regulator_dev *rdev)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
return max8925_set_bits(info->i2c, info->enable_reg,
LDO_SEQ_MASK << LDO_SEQ_SHIFT |
LDO_I2C_EN_MASK << LDO_I2C_EN_SHIFT,
LDO_SEQ_I2C << LDO_SEQ_SHIFT |
LDO_I2C_EN << LDO_I2C_EN_SHIFT);
}
static int max8925_disable(struct regulator_dev *rdev)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
return max8925_set_bits(info->i2c, info->enable_reg,
LDO_SEQ_MASK << LDO_SEQ_SHIFT |
LDO_I2C_EN_MASK << LDO_I2C_EN_SHIFT,
LDO_SEQ_I2C << LDO_SEQ_SHIFT);
}
static int max8925_is_enabled(struct regulator_dev *rdev)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
int ldo_seq, ret;
ret = max8925_reg_read(info->i2c, info->enable_reg);
if (ret < 0)
return ret;
ldo_seq = (ret >> LDO_SEQ_SHIFT) & LDO_SEQ_MASK;
if (ldo_seq != LDO_SEQ_I2C)
return 1;
else
return ret & (LDO_I2C_EN_MASK << LDO_I2C_EN_SHIFT);
}
static int max8925_set_dvm_voltage(struct regulator_dev *rdev, int uV)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
unsigned char data, mask;
if (uV < SD1_DVM_VMIN || uV > SD1_DVM_VMAX)
return -EINVAL;
data = DIV_ROUND_UP(uV - SD1_DVM_VMIN, SD1_DVM_STEP);
data <<= SD1_DVM_SHIFT;
mask = 3 << SD1_DVM_SHIFT;
return max8925_set_bits(info->i2c, info->enable_reg, mask, data);
}
static int max8925_set_dvm_enable(struct regulator_dev *rdev)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
return max8925_set_bits(info->i2c, info->vol_reg, 1 << SD1_DVM_EN,
1 << SD1_DVM_EN);
}
static int max8925_set_dvm_disable(struct regulator_dev *rdev)
{
struct max8925_regulator_info *info = rdev_get_drvdata(rdev);
return max8925_set_bits(info->i2c, info->vol_reg, 1 << SD1_DVM_EN, 0);
}
static struct regulator_ops max8925_regulator_sdv_ops = {
.set_voltage = max8925_set_voltage,
.get_voltage = max8925_get_voltage,
.enable = max8925_enable,
.disable = max8925_disable,
.is_enabled = max8925_is_enabled,
.set_suspend_voltage = max8925_set_dvm_voltage,
.set_suspend_enable = max8925_set_dvm_enable,
.set_suspend_disable = max8925_set_dvm_disable,
};
static struct regulator_ops max8925_regulator_ldo_ops = {
.set_voltage = max8925_set_voltage,
.get_voltage = max8925_get_voltage,
.enable = max8925_enable,
.disable = max8925_disable,
.is_enabled = max8925_is_enabled,
};
#define MAX8925_SDV(_id, min, max, step) \
{ \
.desc = { \
.name = "SDV" #_id, \
.ops = &max8925_regulator_sdv_ops, \
.type = REGULATOR_VOLTAGE, \
.id = MAX8925_ID_SD##_id, \
.owner = THIS_MODULE, \
}, \
.min_uV = min * 1000, \
.max_uV = max * 1000, \
.step_uV = step * 1000, \
.vol_reg = MAX8925_SDV##_id, \
.vol_shift = 0, \
.vol_nbits = 6, \
.enable_reg = MAX8925_SDCTL##_id, \
}
#define MAX8925_LDO(_id, min, max, step) \
{ \
.desc = { \
.name = "LDO" #_id, \
.ops = &max8925_regulator_ldo_ops, \
.type = REGULATOR_VOLTAGE, \
.id = MAX8925_ID_LDO##_id, \
.owner = THIS_MODULE, \
}, \
.min_uV = min * 1000, \
.max_uV = max * 1000, \
.step_uV = step * 1000, \
.vol_reg = MAX8925_LDOVOUT##_id, \
.vol_shift = 0, \
.vol_nbits = 6, \
.enable_reg = MAX8925_LDOCTL##_id, \
}
static struct max8925_regulator_info max8925_regulator_info[] = {
MAX8925_SDV(1, 637.5, 1425, 12.5),
MAX8925_SDV(2, 650, 2225, 25),
MAX8925_SDV(3, 750, 3900, 50),
MAX8925_LDO(1, 750, 3900, 50),
MAX8925_LDO(2, 650, 2250, 25),
MAX8925_LDO(3, 650, 2250, 25),
MAX8925_LDO(4, 750, 3900, 50),
MAX8925_LDO(5, 750, 3900, 50),
MAX8925_LDO(6, 750, 3900, 50),
MAX8925_LDO(7, 750, 3900, 50),
MAX8925_LDO(8, 750, 3900, 50),
MAX8925_LDO(9, 750, 3900, 50),
MAX8925_LDO(10, 750, 3900, 50),
MAX8925_LDO(11, 750, 3900, 50),
MAX8925_LDO(12, 750, 3900, 50),
MAX8925_LDO(13, 750, 3900, 50),
MAX8925_LDO(14, 750, 3900, 50),
MAX8925_LDO(15, 750, 3900, 50),
MAX8925_LDO(16, 750, 3900, 50),
MAX8925_LDO(17, 650, 2250, 25),
MAX8925_LDO(18, 650, 2250, 25),
MAX8925_LDO(19, 750, 3900, 50),
MAX8925_LDO(20, 750, 3900, 50),
};
static struct max8925_regulator_info * __devinit find_regulator_info(int id)
{
struct max8925_regulator_info *ri;
int i;
for (i = 0; i < ARRAY_SIZE(max8925_regulator_info); i++) {
ri = &max8925_regulator_info[i];
if (ri->desc.id == id)
return ri;
}
return NULL;
}
static int __devinit max8925_regulator_probe(struct platform_device *pdev)
{
struct max8925_chip *chip = dev_get_drvdata(pdev->dev.parent);
struct max8925_platform_data *pdata = chip->dev->platform_data;
struct max8925_regulator_info *ri;
struct regulator_dev *rdev;
ri = find_regulator_info(pdev->id);
if (ri == NULL) {
dev_err(&pdev->dev, "invalid regulator ID specified\n");
return -EINVAL;
}
ri->i2c = chip->i2c;
ri->chip = chip;
rdev = regulator_register(&ri->desc, &pdev->dev,
pdata->regulator[pdev->id], ri, NULL);
if (IS_ERR(rdev)) {
dev_err(&pdev->dev, "failed to register regulator %s\n",
ri->desc.name);
return PTR_ERR(rdev);
}
platform_set_drvdata(pdev, rdev);
return 0;
}
static int __devexit max8925_regulator_remove(struct platform_device *pdev)
{
struct regulator_dev *rdev = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
regulator_unregister(rdev);
return 0;
}
static struct platform_driver max8925_regulator_driver = {
.driver = {
.name = "max8925-regulator",
.owner = THIS_MODULE,
},
.probe = max8925_regulator_probe,
.remove = __devexit_p(max8925_regulator_remove),
};
static int __init max8925_regulator_init(void)
{
return platform_driver_register(&max8925_regulator_driver);
}
subsys_initcall(max8925_regulator_init);
static void __exit max8925_regulator_exit(void)
{
platform_driver_unregister(&max8925_regulator_driver);
}
module_exit(max8925_regulator_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Haojian Zhuang <haojian.zhuang@marvell.com>");
MODULE_DESCRIPTION("Regulator Driver for Maxim 8925 PMIC");
MODULE_ALIAS("platform:max8925-regulator");
| gpl-2.0 |
tamirda/G900F_PhoeniX_Kernel_Lollipop | drivers/staging/asus_oled/asus_oled.c | 4803 | 19511 | /*
* Asus OLED USB driver
*
* Copyright (C) 2007,2008 Jakub Schmidtke (sjakub@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; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*
*
* This module is based on usbled and asus-laptop modules.
*
*
* Asus OLED support is based on asusoled program taken from
* <http://lapsus.berlios.de/asus_oled.html>.
*
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/platform_device.h>
#include <linux/ctype.h>
#define ASUS_OLED_VERSION "0.04-dev"
#define ASUS_OLED_NAME "asus-oled"
#define ASUS_OLED_UNDERSCORE_NAME "asus_oled"
#define ASUS_OLED_ERROR "Asus OLED Display Error: "
#define ASUS_OLED_STATIC 's'
#define ASUS_OLED_ROLL 'r'
#define ASUS_OLED_FLASH 'f'
#define ASUS_OLED_MAX_WIDTH 1792
#define ASUS_OLED_DISP_HEIGHT 32
#define ASUS_OLED_PACKET_BUF_SIZE 256
#define USB_VENDOR_ID_ASUS 0x0b05
#define USB_DEVICE_ID_ASUS_LCM 0x1726
#define USB_DEVICE_ID_ASUS_LCM2 0x175b
MODULE_AUTHOR("Jakub Schmidtke, sjakub@gmail.com");
MODULE_DESCRIPTION("Asus OLED Driver v" ASUS_OLED_VERSION);
MODULE_LICENSE("GPL");
static struct class *oled_class;
static int oled_num;
static uint start_off;
module_param(start_off, uint, 0644);
MODULE_PARM_DESC(start_off,
"Set to 1 to switch off OLED display after it is attached");
enum oled_pack_mode {
PACK_MODE_G1,
PACK_MODE_G50,
PACK_MODE_LAST
};
struct oled_dev_desc_str {
uint16_t idVendor;
uint16_t idProduct;
/* width of display */
uint16_t devWidth;
/* formula to be used while packing the picture */
enum oled_pack_mode packMode;
const char *devDesc;
};
/* table of devices that work with this driver */
static const struct usb_device_id id_table[] = {
/* Asus G1/G2 (and variants)*/
{ USB_DEVICE(USB_VENDOR_ID_ASUS, USB_DEVICE_ID_ASUS_LCM) },
/* Asus G50V (and possibly others - G70? G71?)*/
{ USB_DEVICE(USB_VENDOR_ID_ASUS, USB_DEVICE_ID_ASUS_LCM2) },
{ },
};
/* parameters of specific devices */
static struct oled_dev_desc_str oled_dev_desc_table[] = {
{ USB_VENDOR_ID_ASUS, USB_DEVICE_ID_ASUS_LCM, 128, PACK_MODE_G1,
"G1/G2" },
{ USB_VENDOR_ID_ASUS, USB_DEVICE_ID_ASUS_LCM2, 256, PACK_MODE_G50,
"G50" },
{ },
};
MODULE_DEVICE_TABLE(usb, id_table);
struct asus_oled_header {
uint8_t magic1;
uint8_t magic2;
uint8_t flags;
uint8_t value3;
uint8_t buffer1;
uint8_t buffer2;
uint8_t value6;
uint8_t value7;
uint8_t value8;
uint8_t padding2[7];
} __attribute((packed));
struct asus_oled_packet {
struct asus_oled_header header;
uint8_t bitmap[ASUS_OLED_PACKET_BUF_SIZE];
} __attribute((packed));
struct asus_oled_dev {
struct usb_device *udev;
uint8_t pic_mode;
uint16_t dev_width;
enum oled_pack_mode pack_mode;
size_t height;
size_t width;
size_t x_shift;
size_t y_shift;
size_t buf_offs;
uint8_t last_val;
size_t buf_size;
char *buf;
uint8_t enabled;
struct device *dev;
};
static void setup_packet_header(struct asus_oled_packet *packet, char flags,
char value3, char buffer1, char buffer2, char value6,
char value7, char value8)
{
memset(packet, 0, sizeof(struct asus_oled_header));
packet->header.magic1 = 0x55;
packet->header.magic2 = 0xaa;
packet->header.flags = flags;
packet->header.value3 = value3;
packet->header.buffer1 = buffer1;
packet->header.buffer2 = buffer2;
packet->header.value6 = value6;
packet->header.value7 = value7;
packet->header.value8 = value8;
}
static void enable_oled(struct asus_oled_dev *odev, uint8_t enabl)
{
int retval;
int act_len;
struct asus_oled_packet *packet;
packet = kzalloc(sizeof(struct asus_oled_packet), GFP_KERNEL);
if (!packet) {
dev_err(&odev->udev->dev, "out of memory\n");
return;
}
setup_packet_header(packet, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00);
if (enabl)
packet->bitmap[0] = 0xaf;
else
packet->bitmap[0] = 0xae;
retval = usb_bulk_msg(odev->udev,
usb_sndbulkpipe(odev->udev, 2),
packet,
sizeof(struct asus_oled_header) + 1,
&act_len,
-1);
if (retval)
dev_dbg(&odev->udev->dev, "retval = %d\n", retval);
odev->enabled = enabl;
kfree(packet);
}
static ssize_t set_enabled(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct asus_oled_dev *odev = usb_get_intfdata(intf);
unsigned long value;
if (kstrtoul(buf, 10, &value))
return -EINVAL;
enable_oled(odev, value);
return count;
}
static ssize_t class_set_enabled(struct device *device,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct asus_oled_dev *odev =
(struct asus_oled_dev *) dev_get_drvdata(device);
unsigned long value;
if (kstrtoul(buf, 10, &value))
return -EINVAL;
enable_oled(odev, value);
return count;
}
static ssize_t get_enabled(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct asus_oled_dev *odev = usb_get_intfdata(intf);
return sprintf(buf, "%d\n", odev->enabled);
}
static ssize_t class_get_enabled(struct device *device,
struct device_attribute *attr, char *buf)
{
struct asus_oled_dev *odev =
(struct asus_oled_dev *) dev_get_drvdata(device);
return sprintf(buf, "%d\n", odev->enabled);
}
static void send_packets(struct usb_device *udev,
struct asus_oled_packet *packet,
char *buf, uint8_t p_type, size_t p_num)
{
size_t i;
int act_len;
for (i = 0; i < p_num; i++) {
int retval;
switch (p_type) {
case ASUS_OLED_ROLL:
setup_packet_header(packet, 0x40, 0x80, p_num,
i + 1, 0x00, 0x01, 0xff);
break;
case ASUS_OLED_STATIC:
setup_packet_header(packet, 0x10 + i, 0x80, 0x01,
0x01, 0x00, 0x01, 0x00);
break;
case ASUS_OLED_FLASH:
setup_packet_header(packet, 0x10 + i, 0x80, 0x01,
0x01, 0x00, 0x00, 0xff);
break;
}
memcpy(packet->bitmap, buf + (ASUS_OLED_PACKET_BUF_SIZE*i),
ASUS_OLED_PACKET_BUF_SIZE);
retval = usb_bulk_msg(udev, usb_sndctrlpipe(udev, 2),
packet, sizeof(struct asus_oled_packet),
&act_len, -1);
if (retval)
dev_dbg(&udev->dev, "retval = %d\n", retval);
}
}
static void send_packet(struct usb_device *udev,
struct asus_oled_packet *packet,
size_t offset, size_t len, char *buf, uint8_t b1,
uint8_t b2, uint8_t b3, uint8_t b4, uint8_t b5,
uint8_t b6) {
int retval;
int act_len;
setup_packet_header(packet, b1, b2, b3, b4, b5, b6, 0x00);
memcpy(packet->bitmap, buf + offset, len);
retval = usb_bulk_msg(udev,
usb_sndctrlpipe(udev, 2),
packet,
sizeof(struct asus_oled_packet),
&act_len,
-1);
if (retval)
dev_dbg(&udev->dev, "retval = %d\n", retval);
}
static void send_packets_g50(struct usb_device *udev,
struct asus_oled_packet *packet, char *buf)
{
send_packet(udev, packet, 0, 0x100, buf,
0x10, 0x00, 0x02, 0x01, 0x00, 0x01);
send_packet(udev, packet, 0x100, 0x080, buf,
0x10, 0x00, 0x02, 0x02, 0x80, 0x00);
send_packet(udev, packet, 0x180, 0x100, buf,
0x11, 0x00, 0x03, 0x01, 0x00, 0x01);
send_packet(udev, packet, 0x280, 0x100, buf,
0x11, 0x00, 0x03, 0x02, 0x00, 0x01);
send_packet(udev, packet, 0x380, 0x080, buf,
0x11, 0x00, 0x03, 0x03, 0x80, 0x00);
}
static void send_data(struct asus_oled_dev *odev)
{
size_t packet_num = odev->buf_size / ASUS_OLED_PACKET_BUF_SIZE;
struct asus_oled_packet *packet;
packet = kzalloc(sizeof(struct asus_oled_packet), GFP_KERNEL);
if (!packet) {
dev_err(&odev->udev->dev, "out of memory\n");
return;
}
if (odev->pack_mode == PACK_MODE_G1) {
/* When sending roll-mode data the display updated only
first packet. I have no idea why, but when static picture
is sent just before rolling picture everything works fine. */
if (odev->pic_mode == ASUS_OLED_ROLL)
send_packets(odev->udev, packet, odev->buf,
ASUS_OLED_STATIC, 2);
/* Only ROLL mode can use more than 2 packets.*/
if (odev->pic_mode != ASUS_OLED_ROLL && packet_num > 2)
packet_num = 2;
send_packets(odev->udev, packet, odev->buf,
odev->pic_mode, packet_num);
} else if (odev->pack_mode == PACK_MODE_G50) {
send_packets_g50(odev->udev, packet, odev->buf);
}
kfree(packet);
}
static int append_values(struct asus_oled_dev *odev, uint8_t val, size_t count)
{
odev->last_val = val;
if (val == 0) {
odev->buf_offs += count;
return 0;
}
while (count-- > 0) {
size_t x = odev->buf_offs % odev->width;
size_t y = odev->buf_offs / odev->width;
size_t i;
x += odev->x_shift;
y += odev->y_shift;
switch (odev->pack_mode) {
case PACK_MODE_G1:
/* i = (x/128)*640 + 127 - x + (y/8)*128;
This one for 128 is the same, but might be better
for different widths? */
i = (x/odev->dev_width)*640 +
odev->dev_width - 1 - x +
(y/8)*odev->dev_width;
break;
case PACK_MODE_G50:
i = (odev->dev_width - 1 - x)/8 + y*odev->dev_width/8;
break;
default:
i = 0;
printk(ASUS_OLED_ERROR "Unknown OLED Pack Mode: %d!\n",
odev->pack_mode);
break;
}
if (i >= odev->buf_size) {
printk(ASUS_OLED_ERROR "Buffer overflow! Report a bug:"
"offs: %d >= %d i: %d (x: %d y: %d)\n",
(int) odev->buf_offs, (int) odev->buf_size,
(int) i, (int) x, (int) y);
return -EIO;
}
switch (odev->pack_mode) {
case PACK_MODE_G1:
odev->buf[i] &= ~(1<<(y%8));
break;
case PACK_MODE_G50:
odev->buf[i] &= ~(1<<(x%8));
break;
default:
/* cannot get here; stops gcc complaining*/
;
}
odev->buf_offs++;
}
return 0;
}
static ssize_t odev_set_picture(struct asus_oled_dev *odev,
const char *buf, size_t count)
{
size_t offs = 0, max_offs;
if (count < 1)
return 0;
if (tolower(buf[0]) == 'b') {
/* binary mode, set the entire memory*/
size_t i;
odev->buf_size = (odev->dev_width * ASUS_OLED_DISP_HEIGHT) / 8;
kfree(odev->buf);
odev->buf = kmalloc(odev->buf_size, GFP_KERNEL);
if (odev->buf == NULL) {
odev->buf_size = 0;
printk(ASUS_OLED_ERROR "Out of memory!\n");
return -ENOMEM;
}
memset(odev->buf, 0xff, odev->buf_size);
for (i = 1; i < count && i <= 32 * 32; i++) {
odev->buf[i-1] = buf[i];
odev->buf_offs = i-1;
}
odev->width = odev->dev_width / 8;
odev->height = ASUS_OLED_DISP_HEIGHT;
odev->x_shift = 0;
odev->y_shift = 0;
odev->last_val = 0;
send_data(odev);
return count;
}
if (buf[0] == '<') {
size_t i;
size_t w = 0, h = 0;
size_t w_mem, h_mem;
if (count < 10 || buf[2] != ':')
goto error_header;
switch (tolower(buf[1])) {
case ASUS_OLED_STATIC:
case ASUS_OLED_ROLL:
case ASUS_OLED_FLASH:
odev->pic_mode = buf[1];
break;
default:
printk(ASUS_OLED_ERROR "Wrong picture mode: '%c'.\n",
buf[1]);
return -EIO;
break;
}
for (i = 3; i < count; ++i) {
if (buf[i] >= '0' && buf[i] <= '9') {
w = 10*w + (buf[i] - '0');
if (w > ASUS_OLED_MAX_WIDTH)
goto error_width;
} else if (tolower(buf[i]) == 'x') {
break;
} else {
goto error_width;
}
}
for (++i; i < count; ++i) {
if (buf[i] >= '0' && buf[i] <= '9') {
h = 10*h + (buf[i] - '0');
if (h > ASUS_OLED_DISP_HEIGHT)
goto error_height;
} else if (tolower(buf[i]) == '>') {
break;
} else {
goto error_height;
}
}
if (w < 1 || w > ASUS_OLED_MAX_WIDTH)
goto error_width;
if (h < 1 || h > ASUS_OLED_DISP_HEIGHT)
goto error_height;
if (i >= count || buf[i] != '>')
goto error_header;
offs = i+1;
if (w % (odev->dev_width) != 0)
w_mem = (w/(odev->dev_width) + 1)*(odev->dev_width);
else
w_mem = w;
if (h < ASUS_OLED_DISP_HEIGHT)
h_mem = ASUS_OLED_DISP_HEIGHT;
else
h_mem = h;
odev->buf_size = w_mem * h_mem / 8;
kfree(odev->buf);
odev->buf = kmalloc(odev->buf_size, GFP_KERNEL);
if (odev->buf == NULL) {
odev->buf_size = 0;
printk(ASUS_OLED_ERROR "Out of memory!\n");
return -ENOMEM;
}
memset(odev->buf, 0xff, odev->buf_size);
odev->buf_offs = 0;
odev->width = w;
odev->height = h;
odev->x_shift = 0;
odev->y_shift = 0;
odev->last_val = 0;
if (odev->pic_mode == ASUS_OLED_FLASH) {
if (h < ASUS_OLED_DISP_HEIGHT/2)
odev->y_shift = (ASUS_OLED_DISP_HEIGHT/2 - h)/2;
} else {
if (h < ASUS_OLED_DISP_HEIGHT)
odev->y_shift = (ASUS_OLED_DISP_HEIGHT - h)/2;
}
if (w < (odev->dev_width))
odev->x_shift = ((odev->dev_width) - w)/2;
}
max_offs = odev->width * odev->height;
while (offs < count && odev->buf_offs < max_offs) {
int ret = 0;
if (buf[offs] == '1' || buf[offs] == '#') {
ret = append_values(odev, 1, 1);
if (ret < 0)
return ret;
} else if (buf[offs] == '0' || buf[offs] == ' ') {
ret = append_values(odev, 0, 1);
if (ret < 0)
return ret;
} else if (buf[offs] == '\n') {
/* New line detected. Lets assume, that all characters
till the end of the line were equal to the last
character in this line.*/
if (odev->buf_offs % odev->width != 0)
ret = append_values(odev, odev->last_val,
odev->width -
(odev->buf_offs %
odev->width));
if (ret < 0)
return ret;
}
offs++;
}
if (odev->buf_offs >= max_offs)
send_data(odev);
return count;
error_width:
printk(ASUS_OLED_ERROR "Wrong picture width specified.\n");
return -EIO;
error_height:
printk(ASUS_OLED_ERROR "Wrong picture height specified.\n");
return -EIO;
error_header:
printk(ASUS_OLED_ERROR "Wrong picture header.\n");
return -EIO;
}
static ssize_t set_picture(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
return odev_set_picture(usb_get_intfdata(intf), buf, count);
}
static ssize_t class_set_picture(struct device *device,
struct device_attribute *attr,
const char *buf, size_t count)
{
return odev_set_picture((struct asus_oled_dev *)
dev_get_drvdata(device), buf, count);
}
#define ASUS_OLED_DEVICE_ATTR(_file) dev_attr_asus_oled_##_file
static DEVICE_ATTR(asus_oled_enabled, S_IWUSR | S_IRUGO,
get_enabled, set_enabled);
static DEVICE_ATTR(asus_oled_picture, S_IWUSR , NULL, set_picture);
static DEVICE_ATTR(enabled, S_IWUSR | S_IRUGO,
class_get_enabled, class_set_enabled);
static DEVICE_ATTR(picture, S_IWUSR, NULL, class_set_picture);
static int asus_oled_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(interface);
struct asus_oled_dev *odev = NULL;
int retval = -ENOMEM;
uint16_t dev_width = 0;
enum oled_pack_mode pack_mode = PACK_MODE_LAST;
const struct oled_dev_desc_str *dev_desc = oled_dev_desc_table;
const char *desc = NULL;
if (!id) {
/* Even possible? Just to make sure...*/
dev_err(&interface->dev, "No usb_device_id provided!\n");
return -ENODEV;
}
for (; dev_desc->idVendor; dev_desc++) {
if (dev_desc->idVendor == id->idVendor
&& dev_desc->idProduct == id->idProduct) {
dev_width = dev_desc->devWidth;
desc = dev_desc->devDesc;
pack_mode = dev_desc->packMode;
break;
}
}
if (!desc || dev_width < 1 || pack_mode == PACK_MODE_LAST) {
dev_err(&interface->dev,
"Missing or incomplete device description!\n");
return -ENODEV;
}
odev = kzalloc(sizeof(struct asus_oled_dev), GFP_KERNEL);
if (odev == NULL) {
dev_err(&interface->dev, "Out of memory\n");
return -ENOMEM;
}
odev->udev = usb_get_dev(udev);
odev->pic_mode = ASUS_OLED_STATIC;
odev->dev_width = dev_width;
odev->pack_mode = pack_mode;
odev->height = 0;
odev->width = 0;
odev->x_shift = 0;
odev->y_shift = 0;
odev->buf_offs = 0;
odev->buf_size = 0;
odev->last_val = 0;
odev->buf = NULL;
odev->enabled = 1;
odev->dev = NULL;
usb_set_intfdata(interface, odev);
retval = device_create_file(&interface->dev,
&ASUS_OLED_DEVICE_ATTR(enabled));
if (retval)
goto err_files;
retval = device_create_file(&interface->dev,
&ASUS_OLED_DEVICE_ATTR(picture));
if (retval)
goto err_files;
odev->dev = device_create(oled_class, &interface->dev, MKDEV(0, 0),
NULL, "oled_%d", ++oled_num);
if (IS_ERR(odev->dev)) {
retval = PTR_ERR(odev->dev);
goto err_files;
}
dev_set_drvdata(odev->dev, odev);
retval = device_create_file(odev->dev, &dev_attr_enabled);
if (retval)
goto err_class_enabled;
retval = device_create_file(odev->dev, &dev_attr_picture);
if (retval)
goto err_class_picture;
dev_info(&interface->dev,
"Attached Asus OLED device: %s [width %u, pack_mode %d]\n",
desc, odev->dev_width, odev->pack_mode);
if (start_off)
enable_oled(odev, 0);
return 0;
err_class_picture:
device_remove_file(odev->dev, &dev_attr_picture);
err_class_enabled:
device_remove_file(odev->dev, &dev_attr_enabled);
device_unregister(odev->dev);
err_files:
device_remove_file(&interface->dev, &ASUS_OLED_DEVICE_ATTR(enabled));
device_remove_file(&interface->dev, &ASUS_OLED_DEVICE_ATTR(picture));
usb_set_intfdata(interface, NULL);
usb_put_dev(odev->udev);
kfree(odev);
return retval;
}
static void asus_oled_disconnect(struct usb_interface *interface)
{
struct asus_oled_dev *odev;
odev = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
device_remove_file(odev->dev, &dev_attr_picture);
device_remove_file(odev->dev, &dev_attr_enabled);
device_unregister(odev->dev);
device_remove_file(&interface->dev, &ASUS_OLED_DEVICE_ATTR(picture));
device_remove_file(&interface->dev, &ASUS_OLED_DEVICE_ATTR(enabled));
usb_put_dev(odev->udev);
kfree(odev->buf);
kfree(odev);
dev_info(&interface->dev, "Disconnected Asus OLED device\n");
}
static struct usb_driver oled_driver = {
.name = ASUS_OLED_NAME,
.probe = asus_oled_probe,
.disconnect = asus_oled_disconnect,
.id_table = id_table,
};
static CLASS_ATTR_STRING(version, S_IRUGO,
ASUS_OLED_UNDERSCORE_NAME " " ASUS_OLED_VERSION);
static int __init asus_oled_init(void)
{
int retval = 0;
oled_class = class_create(THIS_MODULE, ASUS_OLED_UNDERSCORE_NAME);
if (IS_ERR(oled_class)) {
err("Error creating " ASUS_OLED_UNDERSCORE_NAME " class");
return PTR_ERR(oled_class);
}
retval = class_create_file(oled_class, &class_attr_version.attr);
if (retval) {
err("Error creating class version file");
goto error;
}
retval = usb_register(&oled_driver);
if (retval) {
err("usb_register failed. Error number %d", retval);
goto error;
}
return retval;
error:
class_destroy(oled_class);
return retval;
}
static void __exit asus_oled_exit(void)
{
usb_deregister(&oled_driver);
class_remove_file(oled_class, &class_attr_version.attr);
class_destroy(oled_class);
}
module_init(asus_oled_init);
module_exit(asus_oled_exit);
| gpl-2.0 |
chucktr/android_kernel_htc_msm8960 | arch/x86/boot/cmdline.c | 8387 | 3355 | /* -*- linux-c -*- ------------------------------------------------------- *
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright 2007 rPath, Inc. - All Rights Reserved
*
* This file is part of the Linux kernel, and is made available under
* the terms of the GNU General Public License version 2.
*
* ----------------------------------------------------------------------- */
/*
* Simple command-line parser for early boot.
*/
#include "boot.h"
static inline int myisspace(u8 c)
{
return c <= ' '; /* Close enough approximation */
}
/*
* Find a non-boolean option, that is, "option=argument". In accordance
* with standard Linux practice, if this option is repeated, this returns
* the last instance on the command line.
*
* Returns the length of the argument (regardless of if it was
* truncated to fit in the buffer), or -1 on not found.
*/
int __cmdline_find_option(u32 cmdline_ptr, const char *option, char *buffer, int bufsize)
{
addr_t cptr;
char c;
int len = -1;
const char *opptr = NULL;
char *bufptr = buffer;
enum {
st_wordstart, /* Start of word/after whitespace */
st_wordcmp, /* Comparing this word */
st_wordskip, /* Miscompare, skip */
st_bufcpy /* Copying this to buffer */
} state = st_wordstart;
if (!cmdline_ptr || cmdline_ptr >= 0x100000)
return -1; /* No command line, or inaccessible */
cptr = cmdline_ptr & 0xf;
set_fs(cmdline_ptr >> 4);
while (cptr < 0x10000 && (c = rdfs8(cptr++))) {
switch (state) {
case st_wordstart:
if (myisspace(c))
break;
/* else */
state = st_wordcmp;
opptr = option;
/* fall through */
case st_wordcmp:
if (c == '=' && !*opptr) {
len = 0;
bufptr = buffer;
state = st_bufcpy;
} else if (myisspace(c)) {
state = st_wordstart;
} else if (c != *opptr++) {
state = st_wordskip;
}
break;
case st_wordskip:
if (myisspace(c))
state = st_wordstart;
break;
case st_bufcpy:
if (myisspace(c)) {
state = st_wordstart;
} else {
if (len < bufsize-1)
*bufptr++ = c;
len++;
}
break;
}
}
if (bufsize)
*bufptr = '\0';
return len;
}
/*
* Find a boolean option (like quiet,noapic,nosmp....)
*
* Returns the position of that option (starts counting with 1)
* or 0 on not found
*/
int __cmdline_find_option_bool(u32 cmdline_ptr, const char *option)
{
addr_t cptr;
char c;
int pos = 0, wstart = 0;
const char *opptr = NULL;
enum {
st_wordstart, /* Start of word/after whitespace */
st_wordcmp, /* Comparing this word */
st_wordskip, /* Miscompare, skip */
} state = st_wordstart;
if (!cmdline_ptr || cmdline_ptr >= 0x100000)
return -1; /* No command line, or inaccessible */
cptr = cmdline_ptr & 0xf;
set_fs(cmdline_ptr >> 4);
while (cptr < 0x10000) {
c = rdfs8(cptr++);
pos++;
switch (state) {
case st_wordstart:
if (!c)
return 0;
else if (myisspace(c))
break;
state = st_wordcmp;
opptr = option;
wstart = pos;
/* fall through */
case st_wordcmp:
if (!*opptr)
if (!c || myisspace(c))
return wstart;
else
state = st_wordskip;
else if (!c)
return 0;
else if (c != *opptr++)
state = st_wordskip;
break;
case st_wordskip:
if (!c)
return 0;
else if (myisspace(c))
state = st_wordstart;
break;
}
}
return 0; /* Buffer overrun */
}
| gpl-2.0 |
KylinUI/android_kernel_oppo_n1 | arch/x86/boot/cmdline.c | 8387 | 3355 | /* -*- linux-c -*- ------------------------------------------------------- *
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright 2007 rPath, Inc. - All Rights Reserved
*
* This file is part of the Linux kernel, and is made available under
* the terms of the GNU General Public License version 2.
*
* ----------------------------------------------------------------------- */
/*
* Simple command-line parser for early boot.
*/
#include "boot.h"
static inline int myisspace(u8 c)
{
return c <= ' '; /* Close enough approximation */
}
/*
* Find a non-boolean option, that is, "option=argument". In accordance
* with standard Linux practice, if this option is repeated, this returns
* the last instance on the command line.
*
* Returns the length of the argument (regardless of if it was
* truncated to fit in the buffer), or -1 on not found.
*/
int __cmdline_find_option(u32 cmdline_ptr, const char *option, char *buffer, int bufsize)
{
addr_t cptr;
char c;
int len = -1;
const char *opptr = NULL;
char *bufptr = buffer;
enum {
st_wordstart, /* Start of word/after whitespace */
st_wordcmp, /* Comparing this word */
st_wordskip, /* Miscompare, skip */
st_bufcpy /* Copying this to buffer */
} state = st_wordstart;
if (!cmdline_ptr || cmdline_ptr >= 0x100000)
return -1; /* No command line, or inaccessible */
cptr = cmdline_ptr & 0xf;
set_fs(cmdline_ptr >> 4);
while (cptr < 0x10000 && (c = rdfs8(cptr++))) {
switch (state) {
case st_wordstart:
if (myisspace(c))
break;
/* else */
state = st_wordcmp;
opptr = option;
/* fall through */
case st_wordcmp:
if (c == '=' && !*opptr) {
len = 0;
bufptr = buffer;
state = st_bufcpy;
} else if (myisspace(c)) {
state = st_wordstart;
} else if (c != *opptr++) {
state = st_wordskip;
}
break;
case st_wordskip:
if (myisspace(c))
state = st_wordstart;
break;
case st_bufcpy:
if (myisspace(c)) {
state = st_wordstart;
} else {
if (len < bufsize-1)
*bufptr++ = c;
len++;
}
break;
}
}
if (bufsize)
*bufptr = '\0';
return len;
}
/*
* Find a boolean option (like quiet,noapic,nosmp....)
*
* Returns the position of that option (starts counting with 1)
* or 0 on not found
*/
int __cmdline_find_option_bool(u32 cmdline_ptr, const char *option)
{
addr_t cptr;
char c;
int pos = 0, wstart = 0;
const char *opptr = NULL;
enum {
st_wordstart, /* Start of word/after whitespace */
st_wordcmp, /* Comparing this word */
st_wordskip, /* Miscompare, skip */
} state = st_wordstart;
if (!cmdline_ptr || cmdline_ptr >= 0x100000)
return -1; /* No command line, or inaccessible */
cptr = cmdline_ptr & 0xf;
set_fs(cmdline_ptr >> 4);
while (cptr < 0x10000) {
c = rdfs8(cptr++);
pos++;
switch (state) {
case st_wordstart:
if (!c)
return 0;
else if (myisspace(c))
break;
state = st_wordcmp;
opptr = option;
wstart = pos;
/* fall through */
case st_wordcmp:
if (!*opptr)
if (!c || myisspace(c))
return wstart;
else
state = st_wordskip;
else if (!c)
return 0;
else if (c != *opptr++)
state = st_wordskip;
break;
case st_wordskip:
if (!c)
return 0;
else if (myisspace(c))
state = st_wordstart;
break;
}
}
return 0; /* Buffer overrun */
}
| gpl-2.0 |
flar2/flo-ElementalX | fs/nls/nls_ascii.c | 12227 | 5874 | /*
* linux/fs/nls/nls_ascii.c
*
* Charset ascii translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
};
static const unsigned char *const page_uni2charset[256] = {
page00,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "ascii",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_ascii(void)
{
return register_nls(&table);
}
static void __exit exit_nls_ascii(void)
{
unregister_nls(&table);
}
module_init(init_nls_ascii)
module_exit(exit_nls_ascii)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
SHAYDER/i9300 | drivers/infiniband/hw/ipath/ipath_stats.c | 14275 | 11237 | /*
* 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.
*/
#include "ipath_kernel.h"
struct infinipath_stats ipath_stats;
/**
* ipath_snap_cntr - snapshot a chip counter
* @dd: the infinipath device
* @creg: the counter to snapshot
*
* called from add_timer and user counter read calls, to deal with
* counters that wrap in "human time". The words sent and received, and
* the packets sent and received are all that we worry about. For now,
* at least, we don't worry about error counters, because if they wrap
* that quickly, we probably don't care. We may eventually just make this
* handle all the counters. word counters can wrap in about 20 seconds
* of full bandwidth traffic, packet counters in a few hours.
*/
u64 ipath_snap_cntr(struct ipath_devdata *dd, ipath_creg creg)
{
u32 val, reg64 = 0;
u64 val64;
unsigned long t0, t1;
u64 ret;
t0 = jiffies;
/* If fast increment counters are only 32 bits, snapshot them,
* and maintain them as 64bit values in the driver */
if (!(dd->ipath_flags & IPATH_32BITCOUNTERS) &&
(creg == dd->ipath_cregs->cr_wordsendcnt ||
creg == dd->ipath_cregs->cr_wordrcvcnt ||
creg == dd->ipath_cregs->cr_pktsendcnt ||
creg == dd->ipath_cregs->cr_pktrcvcnt)) {
val64 = ipath_read_creg(dd, creg);
val = val64 == ~0ULL ? ~0U : 0;
reg64 = 1;
} else /* val64 just to keep gcc quiet... */
val64 = val = ipath_read_creg32(dd, creg);
/*
* See if a second has passed. This is just a way to detect things
* that are quite broken. Normally this should take just a few
* cycles (the check is for long enough that we don't care if we get
* pre-empted.) An Opteron HT O read timeout is 4 seconds with
* normal NB values
*/
t1 = jiffies;
if (time_before(t0 + HZ, t1) && val == -1) {
ipath_dev_err(dd, "Error! Read counter 0x%x timed out\n",
creg);
ret = 0ULL;
goto bail;
}
if (reg64) {
ret = val64;
goto bail;
}
if (creg == dd->ipath_cregs->cr_wordsendcnt) {
if (val != dd->ipath_lastsword) {
dd->ipath_sword += val - dd->ipath_lastsword;
dd->ipath_lastsword = val;
}
val64 = dd->ipath_sword;
} else if (creg == dd->ipath_cregs->cr_wordrcvcnt) {
if (val != dd->ipath_lastrword) {
dd->ipath_rword += val - dd->ipath_lastrword;
dd->ipath_lastrword = val;
}
val64 = dd->ipath_rword;
} else if (creg == dd->ipath_cregs->cr_pktsendcnt) {
if (val != dd->ipath_lastspkts) {
dd->ipath_spkts += val - dd->ipath_lastspkts;
dd->ipath_lastspkts = val;
}
val64 = dd->ipath_spkts;
} else if (creg == dd->ipath_cregs->cr_pktrcvcnt) {
if (val != dd->ipath_lastrpkts) {
dd->ipath_rpkts += val - dd->ipath_lastrpkts;
dd->ipath_lastrpkts = val;
}
val64 = dd->ipath_rpkts;
} else if (creg == dd->ipath_cregs->cr_ibsymbolerrcnt) {
if (dd->ibdeltainprog)
val64 -= val64 - dd->ibsymsnap;
val64 -= dd->ibsymdelta;
} else if (creg == dd->ipath_cregs->cr_iblinkerrrecovcnt) {
if (dd->ibdeltainprog)
val64 -= val64 - dd->iblnkerrsnap;
val64 -= dd->iblnkerrdelta;
} else
val64 = (u64) val;
ret = val64;
bail:
return ret;
}
/**
* ipath_qcheck - print delta of egrfull/hdrqfull errors for kernel ports
* @dd: the infinipath device
*
* print the delta of egrfull/hdrqfull errors for kernel ports no more than
* every 5 seconds. User processes are printed at close, but kernel doesn't
* close, so... Separate routine so may call from other places someday, and
* so function name when printed by _IPATH_INFO is meaningfull
*/
static void ipath_qcheck(struct ipath_devdata *dd)
{
static u64 last_tot_hdrqfull;
struct ipath_portdata *pd = dd->ipath_pd[0];
size_t blen = 0;
char buf[128];
u32 hdrqtail;
*buf = 0;
if (pd->port_hdrqfull != dd->ipath_p0_hdrqfull) {
blen = snprintf(buf, sizeof buf, "port 0 hdrqfull %u",
pd->port_hdrqfull -
dd->ipath_p0_hdrqfull);
dd->ipath_p0_hdrqfull = pd->port_hdrqfull;
}
if (ipath_stats.sps_etidfull != dd->ipath_last_tidfull) {
blen += snprintf(buf + blen, sizeof buf - blen,
"%srcvegrfull %llu",
blen ? ", " : "",
(unsigned long long)
(ipath_stats.sps_etidfull -
dd->ipath_last_tidfull));
dd->ipath_last_tidfull = ipath_stats.sps_etidfull;
}
/*
* this is actually the number of hdrq full interrupts, not actual
* events, but at the moment that's mostly what I'm interested in.
* Actual count, etc. is in the counters, if needed. For production
* users this won't ordinarily be printed.
*/
if ((ipath_debug & (__IPATH_PKTDBG | __IPATH_DBG)) &&
ipath_stats.sps_hdrqfull != last_tot_hdrqfull) {
blen += snprintf(buf + blen, sizeof buf - blen,
"%shdrqfull %llu (all ports)",
blen ? ", " : "",
(unsigned long long)
(ipath_stats.sps_hdrqfull -
last_tot_hdrqfull));
last_tot_hdrqfull = ipath_stats.sps_hdrqfull;
}
if (blen)
ipath_dbg("%s\n", buf);
hdrqtail = ipath_get_hdrqtail(pd);
if (pd->port_head != hdrqtail) {
if (dd->ipath_lastport0rcv_cnt ==
ipath_stats.sps_port0pkts) {
ipath_cdbg(PKT, "missing rcv interrupts? "
"port0 hd=%x tl=%x; port0pkts %llx; write"
" hd (w/intr)\n",
pd->port_head, hdrqtail,
(unsigned long long)
ipath_stats.sps_port0pkts);
ipath_write_ureg(dd, ur_rcvhdrhead, hdrqtail |
dd->ipath_rhdrhead_intr_off, pd->port_port);
}
dd->ipath_lastport0rcv_cnt = ipath_stats.sps_port0pkts;
}
}
static void ipath_chk_errormask(struct ipath_devdata *dd)
{
static u32 fixed;
u32 ctrl;
unsigned long errormask;
unsigned long hwerrs;
if (!dd->ipath_errormask || !(dd->ipath_flags & IPATH_INITTED))
return;
errormask = ipath_read_kreg64(dd, dd->ipath_kregs->kr_errormask);
if (errormask == dd->ipath_errormask)
return;
fixed++;
hwerrs = ipath_read_kreg64(dd, dd->ipath_kregs->kr_hwerrstatus);
ctrl = ipath_read_kreg32(dd, dd->ipath_kregs->kr_control);
ipath_write_kreg(dd, dd->ipath_kregs->kr_errormask,
dd->ipath_errormask);
if ((hwerrs & dd->ipath_hwerrmask) ||
(ctrl & INFINIPATH_C_FREEZEMODE)) {
/* force re-interrupt of pending events, just in case */
ipath_write_kreg(dd, dd->ipath_kregs->kr_hwerrclear, 0ULL);
ipath_write_kreg(dd, dd->ipath_kregs->kr_errorclear, 0ULL);
ipath_write_kreg(dd, dd->ipath_kregs->kr_intclear, 0ULL);
dev_info(&dd->pcidev->dev,
"errormask fixed(%u) %lx -> %lx, ctrl %x hwerr %lx\n",
fixed, errormask, (unsigned long)dd->ipath_errormask,
ctrl, hwerrs);
} else
ipath_dbg("errormask fixed(%u) %lx -> %lx, no freeze\n",
fixed, errormask,
(unsigned long)dd->ipath_errormask);
}
/**
* ipath_get_faststats - get word counters from chip before they overflow
* @opaque - contains a pointer to the infinipath device ipath_devdata
*
* called from add_timer
*/
void ipath_get_faststats(unsigned long opaque)
{
struct ipath_devdata *dd = (struct ipath_devdata *) opaque;
int i;
static unsigned cnt;
unsigned long flags;
u64 traffic_wds;
/*
* don't access the chip while running diags, or memory diags can
* fail
*/
if (!dd->ipath_kregbase || !(dd->ipath_flags & IPATH_INITTED) ||
ipath_diag_inuse)
/* but re-arm the timer, for diags case; won't hurt other */
goto done;
/*
* We now try to maintain a "active timer", based on traffic
* exceeding a threshold, so we need to check the word-counts
* even if they are 64-bit.
*/
traffic_wds = ipath_snap_cntr(dd, dd->ipath_cregs->cr_wordsendcnt) +
ipath_snap_cntr(dd, dd->ipath_cregs->cr_wordrcvcnt);
spin_lock_irqsave(&dd->ipath_eep_st_lock, flags);
traffic_wds -= dd->ipath_traffic_wds;
dd->ipath_traffic_wds += traffic_wds;
if (traffic_wds >= IPATH_TRAFFIC_ACTIVE_THRESHOLD)
atomic_add(5, &dd->ipath_active_time); /* S/B #define */
spin_unlock_irqrestore(&dd->ipath_eep_st_lock, flags);
if (dd->ipath_flags & IPATH_32BITCOUNTERS) {
ipath_snap_cntr(dd, dd->ipath_cregs->cr_pktsendcnt);
ipath_snap_cntr(dd, dd->ipath_cregs->cr_pktrcvcnt);
}
ipath_qcheck(dd);
/*
* deal with repeat error suppression. Doesn't really matter if
* last error was almost a full interval ago, or just a few usecs
* ago; still won't get more than 2 per interval. We may want
* longer intervals for this eventually, could do with mod, counter
* or separate timer. Also see code in ipath_handle_errors() and
* ipath_handle_hwerrors().
*/
if (dd->ipath_lasterror)
dd->ipath_lasterror = 0;
if (dd->ipath_lasthwerror)
dd->ipath_lasthwerror = 0;
if (dd->ipath_maskederrs
&& time_after(jiffies, dd->ipath_unmasktime)) {
char ebuf[256];
int iserr;
iserr = ipath_decode_err(dd, ebuf, sizeof ebuf,
dd->ipath_maskederrs);
if (dd->ipath_maskederrs &
~(INFINIPATH_E_RRCVEGRFULL | INFINIPATH_E_RRCVHDRFULL |
INFINIPATH_E_PKTERRS))
ipath_dev_err(dd, "Re-enabling masked errors "
"(%s)\n", ebuf);
else {
/*
* rcvegrfull and rcvhdrqfull are "normal", for some
* types of processes (mostly benchmarks) that send
* huge numbers of messages, while not processing
* them. So only complain about these at debug
* level.
*/
if (iserr)
ipath_dbg(
"Re-enabling queue full errors (%s)\n",
ebuf);
else
ipath_cdbg(ERRPKT, "Re-enabling packet"
" problem interrupt (%s)\n", ebuf);
}
/* re-enable masked errors */
dd->ipath_errormask |= dd->ipath_maskederrs;
ipath_write_kreg(dd, dd->ipath_kregs->kr_errormask,
dd->ipath_errormask);
dd->ipath_maskederrs = 0;
}
/* limit qfull messages to ~one per minute per port */
if ((++cnt & 0x10)) {
for (i = (int) dd->ipath_cfgports; --i >= 0; ) {
struct ipath_portdata *pd = dd->ipath_pd[i];
if (pd && pd->port_lastrcvhdrqtail != -1)
pd->port_lastrcvhdrqtail = -1;
}
}
ipath_chk_errormask(dd);
done:
mod_timer(&dd->ipath_stats_timer, jiffies + HZ * 5);
}
| gpl-2.0 |
forfivo/v500_kernel_aosp | security/integrity/evm/evm_main.c | 196 | 12591 | /*
* Copyright (C) 2005-2010 IBM Corporation
*
* Author:
* 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: evm_main.c
* implements evm_inode_setxattr, evm_inode_post_setxattr,
* evm_inode_removexattr, and evm_verifyxattr
*/
#include <linux/module.h>
#include <linux/crypto.h>
#include <linux/xattr.h>
#include <linux/integrity.h>
#include <linux/evm.h>
#include <crypto/hash.h>
#include "evm.h"
int evm_initialized;
char *evm_hmac = "hmac(sha1)";
char *evm_hash = "sha1";
char *evm_config_xattrnames[] = {
#ifdef CONFIG_SECURITY_SELINUX
XATTR_NAME_SELINUX,
#endif
#ifdef CONFIG_SECURITY_SMACK
XATTR_NAME_SMACK,
#endif
XATTR_NAME_CAPS,
NULL
};
static int evm_fixmode;
static int __init evm_set_fixmode(char *str)
{
if (strncmp(str, "fix", 3) == 0)
evm_fixmode = 1;
return 0;
}
__setup("evm=", evm_set_fixmode);
static int evm_find_protected_xattrs(struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
char **xattr;
int error;
int count = 0;
if (!inode->i_op || !inode->i_op->getxattr)
return -EOPNOTSUPP;
for (xattr = evm_config_xattrnames; *xattr != NULL; xattr++) {
error = inode->i_op->getxattr(dentry, *xattr, NULL, 0);
if (error < 0) {
if (error == -ENODATA)
continue;
return error;
}
count++;
}
return count;
}
/*
* evm_verify_hmac - calculate and compare the HMAC with the EVM xattr
*
* Compute the HMAC on the dentry's protected set of extended attributes
* and compare it against the stored security.evm xattr.
*
* For performance:
* - use the previoulsy retrieved xattr value and length to calculate the
* HMAC.)
* - cache the verification result in the iint, when available.
*
* Returns integrity status
*/
static enum integrity_status evm_verify_hmac(struct dentry *dentry,
const char *xattr_name,
char *xattr_value,
size_t xattr_value_len,
struct integrity_iint_cache *iint)
{
struct evm_ima_xattr_data *xattr_data = NULL;
struct evm_ima_xattr_data calc;
enum integrity_status evm_status = INTEGRITY_PASS;
int rc, xattr_len;
if (iint && iint->evm_status == INTEGRITY_PASS)
return iint->evm_status;
/* if status is not PASS, try to check again - against -ENOMEM */
/* first need to know the sig type */
rc = vfs_getxattr_alloc(dentry, XATTR_NAME_EVM, (char **)&xattr_data, 0,
GFP_NOFS);
if (rc <= 0) {
if (rc == 0)
evm_status = INTEGRITY_FAIL; /* empty */
else if (rc == -ENODATA) {
rc = evm_find_protected_xattrs(dentry);
if (rc > 0)
evm_status = INTEGRITY_NOLABEL;
else if (rc == 0)
evm_status = INTEGRITY_NOXATTRS; /* new file */
}
goto out;
}
xattr_len = rc - 1;
/* check value type */
switch (xattr_data->type) {
case EVM_XATTR_HMAC:
rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = memcmp(xattr_data->digest, calc.digest,
sizeof(calc.digest));
if (rc)
rc = -EINVAL;
break;
case EVM_IMA_XATTR_DIGSIG:
rc = evm_calc_hash(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM,
xattr_data->digest, xattr_len,
calc.digest, sizeof(calc.digest));
if (!rc) {
/* we probably want to replace rsa with hmac here */
evm_update_evmxattr(dentry, xattr_name, xattr_value,
xattr_value_len);
}
break;
default:
rc = -EINVAL;
break;
}
if (rc)
evm_status = (rc == -ENODATA) ?
INTEGRITY_NOXATTRS : INTEGRITY_FAIL;
out:
if (iint)
iint->evm_status = evm_status;
kfree(xattr_data);
return evm_status;
}
static int evm_protected_xattr(const char *req_xattr_name)
{
char **xattrname;
int namelen;
int found = 0;
namelen = strlen(req_xattr_name);
for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
if ((strlen(*xattrname) == namelen)
&& (strncmp(req_xattr_name, *xattrname, namelen) == 0)) {
found = 1;
break;
}
if (strncmp(req_xattr_name,
*xattrname + XATTR_SECURITY_PREFIX_LEN,
strlen(req_xattr_name)) == 0) {
found = 1;
break;
}
}
return found;
}
/**
* evm_verifyxattr - verify the integrity of the requested xattr
* @dentry: object of the verify xattr
* @xattr_name: requested xattr
* @xattr_value: requested xattr value
* @xattr_value_len: requested xattr value length
*
* Calculate the HMAC for the given dentry and verify it against the stored
* security.evm xattr. For performance, use the xattr value and length
* previously retrieved to calculate the HMAC.
*
* Returns the xattr integrity status.
*
* This function requires the caller to lock the inode's i_mutex before it
* is executed.
*/
enum integrity_status evm_verifyxattr(struct dentry *dentry,
const char *xattr_name,
void *xattr_value, size_t xattr_value_len,
struct integrity_iint_cache *iint)
{
if (!evm_initialized || !evm_protected_xattr(xattr_name))
return INTEGRITY_UNKNOWN;
if (!iint) {
iint = integrity_iint_find(dentry->d_inode);
if (!iint)
return INTEGRITY_UNKNOWN;
}
return evm_verify_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, iint);
}
EXPORT_SYMBOL_GPL(evm_verifyxattr);
/*
* evm_verify_current_integrity - verify the dentry's metadata integrity
* @dentry: pointer to the affected dentry
*
* Verify and return the dentry's metadata integrity. The exceptions are
* before EVM is initialized or in 'fix' mode.
*/
static enum integrity_status evm_verify_current_integrity(struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
if (!evm_initialized || !S_ISREG(inode->i_mode) || evm_fixmode)
return 0;
return evm_verify_hmac(dentry, NULL, NULL, 0, NULL);
}
/*
* evm_protect_xattr - protect the EVM extended attribute
*
* Prevent security.evm from being modified or removed without the
* necessary permissions or when the existing value is invalid.
*
* The posix xattr acls are 'system' prefixed, which normally would not
* affect security.evm. An interesting side affect of writing posix xattr
* acls is their modifying of the i_mode, which is included in security.evm.
* For posix xattr acls only, permit security.evm, even if it currently
* doesn't exist, to be updated.
*/
static int evm_protect_xattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
enum integrity_status evm_status;
if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
} else if (!evm_protected_xattr(xattr_name)) {
if (!posix_xattr_acl(xattr_name))
return 0;
evm_status = evm_verify_current_integrity(dentry);
if ((evm_status == INTEGRITY_PASS) ||
(evm_status == INTEGRITY_NOXATTRS))
return 0;
return -EPERM;
}
evm_status = evm_verify_current_integrity(dentry);
return evm_status == INTEGRITY_PASS ? 0 : -EPERM;
}
/**
* evm_inode_setxattr - protect the EVM extended attribute
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
* @xattr_value: pointer to the new extended attribute value
* @xattr_value_len: pointer to the new extended attribute value length
*
* Before allowing the 'security.evm' protected xattr to be updated,
* verify the existing value is valid. As only the kernel should have
* access to the EVM encrypted key needed to calculate the HMAC, prevent
* userspace from writing HMAC value. Writing 'security.evm' requires
* requires CAP_SYS_ADMIN privileges.
*/
int evm_inode_setxattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
const struct evm_ima_xattr_data *xattr_data = xattr_value;
if ((strcmp(xattr_name, XATTR_NAME_EVM) == 0)
&& (xattr_data->type == EVM_XATTR_HMAC))
return -EPERM;
return evm_protect_xattr(dentry, xattr_name, xattr_value,
xattr_value_len);
}
/**
* evm_inode_removexattr - protect the EVM extended attribute
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
*
* Removing 'security.evm' requires CAP_SYS_ADMIN privileges and that
* the current value is valid.
*/
int evm_inode_removexattr(struct dentry *dentry, const char *xattr_name)
{
return evm_protect_xattr(dentry, xattr_name, NULL, 0);
}
/**
* evm_inode_post_setxattr - update 'security.evm' to reflect the changes
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
* @xattr_value: pointer to the new extended attribute value
* @xattr_value_len: pointer to the new extended attribute value length
*
* Update the HMAC stored in 'security.evm' to reflect the change.
*
* No need to take the i_mutex lock here, as this function is called from
* __vfs_setxattr_noperm(). The caller of which has taken the inode's
* i_mutex lock.
*/
void evm_inode_post_setxattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
if (!evm_initialized || (!evm_protected_xattr(xattr_name)
&& !posix_xattr_acl(xattr_name)))
return;
evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len);
return;
}
/**
* evm_inode_post_removexattr - update 'security.evm' after removing the xattr
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
*
* Update the HMAC stored in 'security.evm' to reflect removal of the xattr.
*/
void evm_inode_post_removexattr(struct dentry *dentry, const char *xattr_name)
{
struct inode *inode = dentry->d_inode;
if (!evm_initialized || !evm_protected_xattr(xattr_name))
return;
mutex_lock(&inode->i_mutex);
evm_update_evmxattr(dentry, xattr_name, NULL, 0);
mutex_unlock(&inode->i_mutex);
return;
}
/**
* evm_inode_setattr - prevent updating an invalid EVM extended attribute
* @dentry: pointer to the affected dentry
*/
int evm_inode_setattr(struct dentry *dentry, struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
enum integrity_status evm_status;
if (!(ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)))
return 0;
evm_status = evm_verify_current_integrity(dentry);
if ((evm_status == INTEGRITY_PASS) ||
(evm_status == INTEGRITY_NOXATTRS))
return 0;
return -EPERM;
}
/**
* evm_inode_post_setattr - update 'security.evm' after modifying metadata
* @dentry: pointer to the affected dentry
* @ia_valid: for the UID and GID status
*
* For now, update the HMAC stored in 'security.evm' to reflect UID/GID
* changes.
*
* This function is called from notify_change(), which expects the caller
* to lock the inode's i_mutex.
*/
void evm_inode_post_setattr(struct dentry *dentry, int ia_valid)
{
if (!evm_initialized)
return;
if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
evm_update_evmxattr(dentry, NULL, NULL, 0);
return;
}
/*
* evm_inode_init_security - initializes security.evm
*/
int evm_inode_init_security(struct inode *inode,
const struct xattr *lsm_xattr,
struct xattr *evm_xattr)
{
struct evm_ima_xattr_data *xattr_data;
int rc;
if (!evm_initialized || !evm_protected_xattr(lsm_xattr->name))
return 0;
xattr_data = kzalloc(sizeof(*xattr_data), GFP_NOFS);
if (!xattr_data)
return -ENOMEM;
xattr_data->type = EVM_XATTR_HMAC;
rc = evm_init_hmac(inode, lsm_xattr, xattr_data->digest);
if (rc < 0)
goto out;
evm_xattr->value = xattr_data;
evm_xattr->value_len = sizeof(*xattr_data);
evm_xattr->name = kstrdup(XATTR_EVM_SUFFIX, GFP_NOFS);
return 0;
out:
kfree(xattr_data);
return rc;
}
EXPORT_SYMBOL_GPL(evm_inode_init_security);
static int __init init_evm(void)
{
int error;
error = evm_init_secfs();
if (error < 0) {
printk(KERN_INFO "EVM: Error registering secfs\n");
goto err;
}
return 0;
err:
return error;
}
static void __exit cleanup_evm(void)
{
evm_cleanup_secfs();
if (hmac_tfm)
crypto_free_shash(hmac_tfm);
if (hash_tfm)
crypto_free_shash(hash_tfm);
}
/*
* evm_display_config - list the EVM protected security extended attributes
*/
static int __init evm_display_config(void)
{
char **xattrname;
for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++)
printk(KERN_INFO "EVM: %s\n", *xattrname);
return 0;
}
pure_initcall(evm_display_config);
late_initcall(init_evm);
MODULE_DESCRIPTION("Extended Verification Module");
MODULE_LICENSE("GPL");
| gpl-2.0 |
EPDCenter/android_kernel_archos_97_titan | drivers/pci/pcie/aspm.c | 708 | 27955 | /*
* File: drivers/pci/pcie/aspm.c
* Enabling PCIe link L0s/L1 state and Clock Power Management
*
* Copyright (C) 2007 Intel
* Copyright (C) Zhang Yanmin (yanmin.zhang@intel.com)
* Copyright (C) Shaohua Li (shaohua.li@intel.com)
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/pci.h>
#include <linux/pci_regs.h>
#include <linux/errno.h>
#include <linux/pm.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/pci-aspm.h>
#include "../pci.h"
#ifdef MODULE_PARAM_PREFIX
#undef MODULE_PARAM_PREFIX
#endif
#define MODULE_PARAM_PREFIX "pcie_aspm."
/* Note: those are not register definitions */
#define ASPM_STATE_L0S_UP (1) /* Upstream direction L0s state */
#define ASPM_STATE_L0S_DW (2) /* Downstream direction L0s state */
#define ASPM_STATE_L1 (4) /* L1 state */
#define ASPM_STATE_L0S (ASPM_STATE_L0S_UP | ASPM_STATE_L0S_DW)
#define ASPM_STATE_ALL (ASPM_STATE_L0S | ASPM_STATE_L1)
struct aspm_latency {
u32 l0s; /* L0s latency (nsec) */
u32 l1; /* L1 latency (nsec) */
};
struct pcie_link_state {
struct pci_dev *pdev; /* Upstream component of the Link */
struct pcie_link_state *root; /* pointer to the root port link */
struct pcie_link_state *parent; /* pointer to the parent Link state */
struct list_head sibling; /* node in link_list */
struct list_head children; /* list of child link states */
struct list_head link; /* node in parent's children list */
/* ASPM state */
u32 aspm_support:3; /* Supported ASPM state */
u32 aspm_enabled:3; /* Enabled ASPM state */
u32 aspm_capable:3; /* Capable ASPM state with latency */
u32 aspm_default:3; /* Default ASPM state by BIOS */
u32 aspm_disable:3; /* Disabled ASPM state */
/* Clock PM state */
u32 clkpm_capable:1; /* Clock PM capable? */
u32 clkpm_enabled:1; /* Current Clock PM state */
u32 clkpm_default:1; /* Default Clock PM state by BIOS */
/* Exit latencies */
struct aspm_latency latency_up; /* Upstream direction exit latency */
struct aspm_latency latency_dw; /* Downstream direction exit latency */
/*
* Endpoint acceptable latencies. A pcie downstream port only
* has one slot under it, so at most there are 8 functions.
*/
struct aspm_latency acceptable[8];
};
static int aspm_disabled, aspm_force;
static bool aspm_support_enabled = true;
static DEFINE_MUTEX(aspm_lock);
static LIST_HEAD(link_list);
#define POLICY_DEFAULT 0 /* BIOS default setting */
#define POLICY_PERFORMANCE 1 /* high performance */
#define POLICY_POWERSAVE 2 /* high power saving */
static int aspm_policy;
static const char *policy_str[] = {
[POLICY_DEFAULT] = "default",
[POLICY_PERFORMANCE] = "performance",
[POLICY_POWERSAVE] = "powersave"
};
#define LINK_RETRAIN_TIMEOUT HZ
static int policy_to_aspm_state(struct pcie_link_state *link)
{
switch (aspm_policy) {
case POLICY_PERFORMANCE:
/* Disable ASPM and Clock PM */
return 0;
case POLICY_POWERSAVE:
/* Enable ASPM L0s/L1 */
return ASPM_STATE_ALL;
case POLICY_DEFAULT:
return link->aspm_default;
}
return 0;
}
static int policy_to_clkpm_state(struct pcie_link_state *link)
{
switch (aspm_policy) {
case POLICY_PERFORMANCE:
/* Disable ASPM and Clock PM */
return 0;
case POLICY_POWERSAVE:
/* Disable Clock PM */
return 1;
case POLICY_DEFAULT:
return link->clkpm_default;
}
return 0;
}
static void pcie_set_clkpm_nocheck(struct pcie_link_state *link, int enable)
{
int pos;
u16 reg16;
struct pci_dev *child;
struct pci_bus *linkbus = link->pdev->subordinate;
list_for_each_entry(child, &linkbus->devices, bus_list) {
pos = pci_pcie_cap(child);
if (!pos)
return;
pci_read_config_word(child, pos + PCI_EXP_LNKCTL, ®16);
if (enable)
reg16 |= PCI_EXP_LNKCTL_CLKREQ_EN;
else
reg16 &= ~PCI_EXP_LNKCTL_CLKREQ_EN;
pci_write_config_word(child, pos + PCI_EXP_LNKCTL, reg16);
}
link->clkpm_enabled = !!enable;
}
static void pcie_set_clkpm(struct pcie_link_state *link, int enable)
{
/* Don't enable Clock PM if the link is not Clock PM capable */
if (!link->clkpm_capable && enable)
enable = 0;
/* Need nothing if the specified equals to current state */
if (link->clkpm_enabled == enable)
return;
pcie_set_clkpm_nocheck(link, enable);
}
static void pcie_clkpm_cap_init(struct pcie_link_state *link, int blacklist)
{
int pos, capable = 1, enabled = 1;
u32 reg32;
u16 reg16;
struct pci_dev *child;
struct pci_bus *linkbus = link->pdev->subordinate;
/* All functions should have the same cap and state, take the worst */
list_for_each_entry(child, &linkbus->devices, bus_list) {
pos = pci_pcie_cap(child);
if (!pos)
return;
pci_read_config_dword(child, pos + PCI_EXP_LNKCAP, ®32);
if (!(reg32 & PCI_EXP_LNKCAP_CLKPM)) {
capable = 0;
enabled = 0;
break;
}
pci_read_config_word(child, pos + PCI_EXP_LNKCTL, ®16);
if (!(reg16 & PCI_EXP_LNKCTL_CLKREQ_EN))
enabled = 0;
}
link->clkpm_enabled = enabled;
link->clkpm_default = enabled;
link->clkpm_capable = (blacklist) ? 0 : capable;
}
/*
* pcie_aspm_configure_common_clock: check if the 2 ends of a link
* could use common clock. If they are, configure them to use the
* common clock. That will reduce the ASPM state exit latency.
*/
static void pcie_aspm_configure_common_clock(struct pcie_link_state *link)
{
int ppos, cpos, same_clock = 1;
u16 reg16, parent_reg, child_reg[8];
unsigned long start_jiffies;
struct pci_dev *child, *parent = link->pdev;
struct pci_bus *linkbus = parent->subordinate;
/*
* All functions of a slot should have the same Slot Clock
* Configuration, so just check one function
*/
child = list_entry(linkbus->devices.next, struct pci_dev, bus_list);
BUG_ON(!pci_is_pcie(child));
/* Check downstream component if bit Slot Clock Configuration is 1 */
cpos = pci_pcie_cap(child);
pci_read_config_word(child, cpos + PCI_EXP_LNKSTA, ®16);
if (!(reg16 & PCI_EXP_LNKSTA_SLC))
same_clock = 0;
/* Check upstream component if bit Slot Clock Configuration is 1 */
ppos = pci_pcie_cap(parent);
pci_read_config_word(parent, ppos + PCI_EXP_LNKSTA, ®16);
if (!(reg16 & PCI_EXP_LNKSTA_SLC))
same_clock = 0;
/* Configure downstream component, all functions */
list_for_each_entry(child, &linkbus->devices, bus_list) {
cpos = pci_pcie_cap(child);
pci_read_config_word(child, cpos + PCI_EXP_LNKCTL, ®16);
child_reg[PCI_FUNC(child->devfn)] = reg16;
if (same_clock)
reg16 |= PCI_EXP_LNKCTL_CCC;
else
reg16 &= ~PCI_EXP_LNKCTL_CCC;
pci_write_config_word(child, cpos + PCI_EXP_LNKCTL, reg16);
}
/* Configure upstream component */
pci_read_config_word(parent, ppos + PCI_EXP_LNKCTL, ®16);
parent_reg = reg16;
if (same_clock)
reg16 |= PCI_EXP_LNKCTL_CCC;
else
reg16 &= ~PCI_EXP_LNKCTL_CCC;
pci_write_config_word(parent, ppos + PCI_EXP_LNKCTL, reg16);
/* Retrain link */
reg16 |= PCI_EXP_LNKCTL_RL;
pci_write_config_word(parent, ppos + PCI_EXP_LNKCTL, reg16);
/* Wait for link training end. Break out after waiting for timeout */
start_jiffies = jiffies;
for (;;) {
pci_read_config_word(parent, ppos + PCI_EXP_LNKSTA, ®16);
if (!(reg16 & PCI_EXP_LNKSTA_LT))
break;
if (time_after(jiffies, start_jiffies + LINK_RETRAIN_TIMEOUT))
break;
msleep(1);
}
if (!(reg16 & PCI_EXP_LNKSTA_LT))
return;
/* Training failed. Restore common clock configurations */
dev_printk(KERN_ERR, &parent->dev,
"ASPM: Could not configure common clock\n");
list_for_each_entry(child, &linkbus->devices, bus_list) {
cpos = pci_pcie_cap(child);
pci_write_config_word(child, cpos + PCI_EXP_LNKCTL,
child_reg[PCI_FUNC(child->devfn)]);
}
pci_write_config_word(parent, ppos + PCI_EXP_LNKCTL, parent_reg);
}
/* Convert L0s latency encoding to ns */
static u32 calc_l0s_latency(u32 encoding)
{
if (encoding == 0x7)
return (5 * 1000); /* > 4us */
return (64 << encoding);
}
/* Convert L0s acceptable latency encoding to ns */
static u32 calc_l0s_acceptable(u32 encoding)
{
if (encoding == 0x7)
return -1U;
return (64 << encoding);
}
/* Convert L1 latency encoding to ns */
static u32 calc_l1_latency(u32 encoding)
{
if (encoding == 0x7)
return (65 * 1000); /* > 64us */
return (1000 << encoding);
}
/* Convert L1 acceptable latency encoding to ns */
static u32 calc_l1_acceptable(u32 encoding)
{
if (encoding == 0x7)
return -1U;
return (1000 << encoding);
}
struct aspm_register_info {
u32 support:2;
u32 enabled:2;
u32 latency_encoding_l0s;
u32 latency_encoding_l1;
};
static void pcie_get_aspm_reg(struct pci_dev *pdev,
struct aspm_register_info *info)
{
int pos;
u16 reg16;
u32 reg32;
pos = pci_pcie_cap(pdev);
pci_read_config_dword(pdev, pos + PCI_EXP_LNKCAP, ®32);
info->support = (reg32 & PCI_EXP_LNKCAP_ASPMS) >> 10;
info->latency_encoding_l0s = (reg32 & PCI_EXP_LNKCAP_L0SEL) >> 12;
info->latency_encoding_l1 = (reg32 & PCI_EXP_LNKCAP_L1EL) >> 15;
pci_read_config_word(pdev, pos + PCI_EXP_LNKCTL, ®16);
info->enabled = reg16 & PCI_EXP_LNKCTL_ASPMC;
}
static void pcie_aspm_check_latency(struct pci_dev *endpoint)
{
u32 latency, l1_switch_latency = 0;
struct aspm_latency *acceptable;
struct pcie_link_state *link;
/* Device not in D0 doesn't need latency check */
if ((endpoint->current_state != PCI_D0) &&
(endpoint->current_state != PCI_UNKNOWN))
return;
link = endpoint->bus->self->link_state;
acceptable = &link->acceptable[PCI_FUNC(endpoint->devfn)];
while (link) {
/* Check upstream direction L0s latency */
if ((link->aspm_capable & ASPM_STATE_L0S_UP) &&
(link->latency_up.l0s > acceptable->l0s))
link->aspm_capable &= ~ASPM_STATE_L0S_UP;
/* Check downstream direction L0s latency */
if ((link->aspm_capable & ASPM_STATE_L0S_DW) &&
(link->latency_dw.l0s > acceptable->l0s))
link->aspm_capable &= ~ASPM_STATE_L0S_DW;
/*
* Check L1 latency.
* Every switch on the path to root complex need 1
* more microsecond for L1. Spec doesn't mention L0s.
*/
latency = max_t(u32, link->latency_up.l1, link->latency_dw.l1);
if ((link->aspm_capable & ASPM_STATE_L1) &&
(latency + l1_switch_latency > acceptable->l1))
link->aspm_capable &= ~ASPM_STATE_L1;
l1_switch_latency += 1000;
link = link->parent;
}
}
static void pcie_aspm_cap_init(struct pcie_link_state *link, int blacklist)
{
struct pci_dev *child, *parent = link->pdev;
struct pci_bus *linkbus = parent->subordinate;
struct aspm_register_info upreg, dwreg;
if (blacklist) {
/* Set enabled/disable so that we will disable ASPM later */
link->aspm_enabled = ASPM_STATE_ALL;
link->aspm_disable = ASPM_STATE_ALL;
return;
}
/* Configure common clock before checking latencies */
pcie_aspm_configure_common_clock(link);
/* Get upstream/downstream components' register state */
pcie_get_aspm_reg(parent, &upreg);
child = list_entry(linkbus->devices.next, struct pci_dev, bus_list);
pcie_get_aspm_reg(child, &dwreg);
/*
* Setup L0s state
*
* Note that we must not enable L0s in either direction on a
* given link unless components on both sides of the link each
* support L0s.
*/
if (dwreg.support & upreg.support & PCIE_LINK_STATE_L0S)
link->aspm_support |= ASPM_STATE_L0S;
if (dwreg.enabled & PCIE_LINK_STATE_L0S)
link->aspm_enabled |= ASPM_STATE_L0S_UP;
if (upreg.enabled & PCIE_LINK_STATE_L0S)
link->aspm_enabled |= ASPM_STATE_L0S_DW;
link->latency_up.l0s = calc_l0s_latency(upreg.latency_encoding_l0s);
link->latency_dw.l0s = calc_l0s_latency(dwreg.latency_encoding_l0s);
/* Setup L1 state */
if (upreg.support & dwreg.support & PCIE_LINK_STATE_L1)
link->aspm_support |= ASPM_STATE_L1;
if (upreg.enabled & dwreg.enabled & PCIE_LINK_STATE_L1)
link->aspm_enabled |= ASPM_STATE_L1;
link->latency_up.l1 = calc_l1_latency(upreg.latency_encoding_l1);
link->latency_dw.l1 = calc_l1_latency(dwreg.latency_encoding_l1);
/* Save default state */
link->aspm_default = link->aspm_enabled;
/* Setup initial capable state. Will be updated later */
link->aspm_capable = link->aspm_support;
/*
* If the downstream component has pci bridge function, don't
* do ASPM for now.
*/
list_for_each_entry(child, &linkbus->devices, bus_list) {
if (child->pcie_type == PCI_EXP_TYPE_PCI_BRIDGE) {
link->aspm_disable = ASPM_STATE_ALL;
break;
}
}
/* Get and check endpoint acceptable latencies */
list_for_each_entry(child, &linkbus->devices, bus_list) {
int pos;
u32 reg32, encoding;
struct aspm_latency *acceptable =
&link->acceptable[PCI_FUNC(child->devfn)];
if (child->pcie_type != PCI_EXP_TYPE_ENDPOINT &&
child->pcie_type != PCI_EXP_TYPE_LEG_END)
continue;
pos = pci_pcie_cap(child);
pci_read_config_dword(child, pos + PCI_EXP_DEVCAP, ®32);
/* Calculate endpoint L0s acceptable latency */
encoding = (reg32 & PCI_EXP_DEVCAP_L0S) >> 6;
acceptable->l0s = calc_l0s_acceptable(encoding);
/* Calculate endpoint L1 acceptable latency */
encoding = (reg32 & PCI_EXP_DEVCAP_L1) >> 9;
acceptable->l1 = calc_l1_acceptable(encoding);
pcie_aspm_check_latency(child);
}
}
static void pcie_config_aspm_dev(struct pci_dev *pdev, u32 val)
{
u16 reg16;
int pos = pci_pcie_cap(pdev);
pci_read_config_word(pdev, pos + PCI_EXP_LNKCTL, ®16);
reg16 &= ~0x3;
reg16 |= val;
pci_write_config_word(pdev, pos + PCI_EXP_LNKCTL, reg16);
}
static void pcie_config_aspm_link(struct pcie_link_state *link, u32 state)
{
u32 upstream = 0, dwstream = 0;
struct pci_dev *child, *parent = link->pdev;
struct pci_bus *linkbus = parent->subordinate;
/* Nothing to do if the link is already in the requested state */
state &= (link->aspm_capable & ~link->aspm_disable);
if (link->aspm_enabled == state)
return;
/* Convert ASPM state to upstream/downstream ASPM register state */
if (state & ASPM_STATE_L0S_UP)
dwstream |= PCIE_LINK_STATE_L0S;
if (state & ASPM_STATE_L0S_DW)
upstream |= PCIE_LINK_STATE_L0S;
if (state & ASPM_STATE_L1) {
upstream |= PCIE_LINK_STATE_L1;
dwstream |= PCIE_LINK_STATE_L1;
}
/*
* Spec 2.0 suggests all functions should be configured the
* same setting for ASPM. Enabling ASPM L1 should be done in
* upstream component first and then downstream, and vice
* versa for disabling ASPM L1. Spec doesn't mention L0S.
*/
if (state & ASPM_STATE_L1)
pcie_config_aspm_dev(parent, upstream);
list_for_each_entry(child, &linkbus->devices, bus_list)
pcie_config_aspm_dev(child, dwstream);
if (!(state & ASPM_STATE_L1))
pcie_config_aspm_dev(parent, upstream);
link->aspm_enabled = state;
}
static void pcie_config_aspm_path(struct pcie_link_state *link)
{
while (link) {
pcie_config_aspm_link(link, policy_to_aspm_state(link));
link = link->parent;
}
}
static void free_link_state(struct pcie_link_state *link)
{
link->pdev->link_state = NULL;
kfree(link);
}
static int pcie_aspm_sanity_check(struct pci_dev *pdev)
{
struct pci_dev *child;
int pos;
u32 reg32;
/*
* Some functions in a slot might not all be PCIe functions,
* very strange. Disable ASPM for the whole slot
*/
list_for_each_entry(child, &pdev->subordinate->devices, bus_list) {
pos = pci_pcie_cap(child);
if (!pos)
return -EINVAL;
/*
* If ASPM is disabled then we're not going to change
* the BIOS state. It's safe to continue even if it's a
* pre-1.1 device
*/
if (aspm_disabled)
continue;
/*
* Disable ASPM for pre-1.1 PCIe device, we follow MS to use
* RBER bit to determine if a function is 1.1 version device
*/
pci_read_config_dword(child, pos + PCI_EXP_DEVCAP, ®32);
if (!(reg32 & PCI_EXP_DEVCAP_RBER) && !aspm_force) {
dev_printk(KERN_INFO, &child->dev, "disabling ASPM"
" on pre-1.1 PCIe device. You can enable it"
" with 'pcie_aspm=force'\n");
return -EINVAL;
}
}
return 0;
}
static struct pcie_link_state *alloc_pcie_link_state(struct pci_dev *pdev)
{
struct pcie_link_state *link;
link = kzalloc(sizeof(*link), GFP_KERNEL);
if (!link)
return NULL;
INIT_LIST_HEAD(&link->sibling);
INIT_LIST_HEAD(&link->children);
INIT_LIST_HEAD(&link->link);
link->pdev = pdev;
if (pdev->pcie_type == PCI_EXP_TYPE_DOWNSTREAM) {
struct pcie_link_state *parent;
parent = pdev->bus->parent->self->link_state;
if (!parent) {
kfree(link);
return NULL;
}
link->parent = parent;
list_add(&link->link, &parent->children);
}
/* Setup a pointer to the root port link */
if (!link->parent)
link->root = link;
else
link->root = link->parent->root;
list_add(&link->sibling, &link_list);
pdev->link_state = link;
return link;
}
/*
* pcie_aspm_init_link_state: Initiate PCI express link state.
* It is called after the pcie and its children devices are scaned.
* @pdev: the root port or switch downstream port
*/
void pcie_aspm_init_link_state(struct pci_dev *pdev)
{
struct pcie_link_state *link;
int blacklist = !!pcie_aspm_sanity_check(pdev);
if (!pci_is_pcie(pdev) || pdev->link_state)
return;
if (pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT &&
pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM)
return;
/* VIA has a strange chipset, root port is under a bridge */
if (pdev->pcie_type == PCI_EXP_TYPE_ROOT_PORT &&
pdev->bus->self)
return;
down_read(&pci_bus_sem);
if (list_empty(&pdev->subordinate->devices))
goto out;
mutex_lock(&aspm_lock);
link = alloc_pcie_link_state(pdev);
if (!link)
goto unlock;
/*
* Setup initial ASPM state. Note that we need to configure
* upstream links also because capable state of them can be
* update through pcie_aspm_cap_init().
*/
pcie_aspm_cap_init(link, blacklist);
/* Setup initial Clock PM state */
pcie_clkpm_cap_init(link, blacklist);
/*
* At this stage drivers haven't had an opportunity to change the
* link policy setting. Enabling ASPM on broken hardware can cripple
* it even before the driver has had a chance to disable ASPM, so
* default to a safe level right now. If we're enabling ASPM beyond
* the BIOS's expectation, we'll do so once pci_enable_device() is
* called.
*/
if (aspm_policy != POLICY_POWERSAVE) {
pcie_config_aspm_path(link);
pcie_set_clkpm(link, policy_to_clkpm_state(link));
}
unlock:
mutex_unlock(&aspm_lock);
out:
up_read(&pci_bus_sem);
}
/* Recheck latencies and update aspm_capable for links under the root */
static void pcie_update_aspm_capable(struct pcie_link_state *root)
{
struct pcie_link_state *link;
BUG_ON(root->parent);
list_for_each_entry(link, &link_list, sibling) {
if (link->root != root)
continue;
link->aspm_capable = link->aspm_support;
}
list_for_each_entry(link, &link_list, sibling) {
struct pci_dev *child;
struct pci_bus *linkbus = link->pdev->subordinate;
if (link->root != root)
continue;
list_for_each_entry(child, &linkbus->devices, bus_list) {
if ((child->pcie_type != PCI_EXP_TYPE_ENDPOINT) &&
(child->pcie_type != PCI_EXP_TYPE_LEG_END))
continue;
pcie_aspm_check_latency(child);
}
}
}
/* @pdev: the endpoint device */
void pcie_aspm_exit_link_state(struct pci_dev *pdev)
{
struct pci_dev *parent = pdev->bus->self;
struct pcie_link_state *link, *root, *parent_link;
if (!pci_is_pcie(pdev) || !parent || !parent->link_state)
return;
if ((parent->pcie_type != PCI_EXP_TYPE_ROOT_PORT) &&
(parent->pcie_type != PCI_EXP_TYPE_DOWNSTREAM))
return;
down_read(&pci_bus_sem);
mutex_lock(&aspm_lock);
/*
* All PCIe functions are in one slot, remove one function will remove
* the whole slot, so just wait until we are the last function left.
*/
if (!list_is_last(&pdev->bus_list, &parent->subordinate->devices))
goto out;
link = parent->link_state;
root = link->root;
parent_link = link->parent;
/* All functions are removed, so just disable ASPM for the link */
pcie_config_aspm_link(link, 0);
list_del(&link->sibling);
list_del(&link->link);
/* Clock PM is for endpoint device */
free_link_state(link);
/* Recheck latencies and configure upstream links */
if (parent_link) {
pcie_update_aspm_capable(root);
pcie_config_aspm_path(parent_link);
}
out:
mutex_unlock(&aspm_lock);
up_read(&pci_bus_sem);
}
/* @pdev: the root port or switch downstream port */
void pcie_aspm_pm_state_change(struct pci_dev *pdev)
{
struct pcie_link_state *link = pdev->link_state;
if (aspm_disabled || !pci_is_pcie(pdev) || !link)
return;
if ((pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT) &&
(pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM))
return;
/*
* Devices changed PM state, we should recheck if latency
* meets all functions' requirement
*/
down_read(&pci_bus_sem);
mutex_lock(&aspm_lock);
pcie_update_aspm_capable(link->root);
pcie_config_aspm_path(link);
mutex_unlock(&aspm_lock);
up_read(&pci_bus_sem);
}
void pcie_aspm_powersave_config_link(struct pci_dev *pdev)
{
struct pcie_link_state *link = pdev->link_state;
if (aspm_disabled || !pci_is_pcie(pdev) || !link)
return;
if (aspm_policy != POLICY_POWERSAVE)
return;
if ((pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT) &&
(pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM))
return;
down_read(&pci_bus_sem);
mutex_lock(&aspm_lock);
pcie_config_aspm_path(link);
pcie_set_clkpm(link, policy_to_clkpm_state(link));
mutex_unlock(&aspm_lock);
up_read(&pci_bus_sem);
}
/*
* pci_disable_link_state - disable pci device's link state, so the link will
* never enter specific states
*/
static void __pci_disable_link_state(struct pci_dev *pdev, int state, bool sem,
bool force)
{
struct pci_dev *parent = pdev->bus->self;
struct pcie_link_state *link;
if (aspm_disabled && !force)
return;
if (!pci_is_pcie(pdev))
return;
if (pdev->pcie_type == PCI_EXP_TYPE_ROOT_PORT ||
pdev->pcie_type == PCI_EXP_TYPE_DOWNSTREAM)
parent = pdev;
if (!parent || !parent->link_state)
return;
if (sem)
down_read(&pci_bus_sem);
mutex_lock(&aspm_lock);
link = parent->link_state;
if (state & PCIE_LINK_STATE_L0S)
link->aspm_disable |= ASPM_STATE_L0S;
if (state & PCIE_LINK_STATE_L1)
link->aspm_disable |= ASPM_STATE_L1;
pcie_config_aspm_link(link, policy_to_aspm_state(link));
if (state & PCIE_LINK_STATE_CLKPM) {
link->clkpm_capable = 0;
pcie_set_clkpm(link, 0);
}
mutex_unlock(&aspm_lock);
if (sem)
up_read(&pci_bus_sem);
}
void pci_disable_link_state_locked(struct pci_dev *pdev, int state)
{
__pci_disable_link_state(pdev, state, false, false);
}
EXPORT_SYMBOL(pci_disable_link_state_locked);
void pci_disable_link_state(struct pci_dev *pdev, int state)
{
__pci_disable_link_state(pdev, state, true, false);
}
EXPORT_SYMBOL(pci_disable_link_state);
void pcie_clear_aspm(struct pci_bus *bus)
{
struct pci_dev *child;
/*
* Clear any ASPM setup that the firmware has carried out on this bus
*/
list_for_each_entry(child, &bus->devices, bus_list) {
__pci_disable_link_state(child, PCIE_LINK_STATE_L0S |
PCIE_LINK_STATE_L1 |
PCIE_LINK_STATE_CLKPM,
false, true);
}
}
static int pcie_aspm_set_policy(const char *val, struct kernel_param *kp)
{
int i;
struct pcie_link_state *link;
if (aspm_disabled)
return -EPERM;
for (i = 0; i < ARRAY_SIZE(policy_str); i++)
if (!strncmp(val, policy_str[i], strlen(policy_str[i])))
break;
if (i >= ARRAY_SIZE(policy_str))
return -EINVAL;
if (i == aspm_policy)
return 0;
down_read(&pci_bus_sem);
mutex_lock(&aspm_lock);
aspm_policy = i;
list_for_each_entry(link, &link_list, sibling) {
pcie_config_aspm_link(link, policy_to_aspm_state(link));
pcie_set_clkpm(link, policy_to_clkpm_state(link));
}
mutex_unlock(&aspm_lock);
up_read(&pci_bus_sem);
return 0;
}
static int pcie_aspm_get_policy(char *buffer, struct kernel_param *kp)
{
int i, cnt = 0;
for (i = 0; i < ARRAY_SIZE(policy_str); i++)
if (i == aspm_policy)
cnt += sprintf(buffer + cnt, "[%s] ", policy_str[i]);
else
cnt += sprintf(buffer + cnt, "%s ", policy_str[i]);
return cnt;
}
module_param_call(policy, pcie_aspm_set_policy, pcie_aspm_get_policy,
NULL, 0644);
#ifdef CONFIG_PCIEASPM_DEBUG
static ssize_t link_state_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct pci_dev *pci_device = to_pci_dev(dev);
struct pcie_link_state *link_state = pci_device->link_state;
return sprintf(buf, "%d\n", link_state->aspm_enabled);
}
static ssize_t link_state_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t n)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct pcie_link_state *link, *root = pdev->link_state->root;
u32 val = buf[0] - '0', state = 0;
if (aspm_disabled)
return -EPERM;
if (n < 1 || val > 3)
return -EINVAL;
/* Convert requested state to ASPM state */
if (val & PCIE_LINK_STATE_L0S)
state |= ASPM_STATE_L0S;
if (val & PCIE_LINK_STATE_L1)
state |= ASPM_STATE_L1;
down_read(&pci_bus_sem);
mutex_lock(&aspm_lock);
list_for_each_entry(link, &link_list, sibling) {
if (link->root != root)
continue;
pcie_config_aspm_link(link, state);
}
mutex_unlock(&aspm_lock);
up_read(&pci_bus_sem);
return n;
}
static ssize_t clk_ctl_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct pci_dev *pci_device = to_pci_dev(dev);
struct pcie_link_state *link_state = pci_device->link_state;
return sprintf(buf, "%d\n", link_state->clkpm_enabled);
}
static ssize_t clk_ctl_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t n)
{
struct pci_dev *pdev = to_pci_dev(dev);
int state;
if (n < 1)
return -EINVAL;
state = buf[0]-'0';
down_read(&pci_bus_sem);
mutex_lock(&aspm_lock);
pcie_set_clkpm_nocheck(pdev->link_state, !!state);
mutex_unlock(&aspm_lock);
up_read(&pci_bus_sem);
return n;
}
static DEVICE_ATTR(link_state, 0644, link_state_show, link_state_store);
static DEVICE_ATTR(clk_ctl, 0644, clk_ctl_show, clk_ctl_store);
static char power_group[] = "power";
void pcie_aspm_create_sysfs_dev_files(struct pci_dev *pdev)
{
struct pcie_link_state *link_state = pdev->link_state;
if (!pci_is_pcie(pdev) ||
(pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT &&
pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM) || !link_state)
return;
if (link_state->aspm_support)
sysfs_add_file_to_group(&pdev->dev.kobj,
&dev_attr_link_state.attr, power_group);
if (link_state->clkpm_capable)
sysfs_add_file_to_group(&pdev->dev.kobj,
&dev_attr_clk_ctl.attr, power_group);
}
void pcie_aspm_remove_sysfs_dev_files(struct pci_dev *pdev)
{
struct pcie_link_state *link_state = pdev->link_state;
if (!pci_is_pcie(pdev) ||
(pdev->pcie_type != PCI_EXP_TYPE_ROOT_PORT &&
pdev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM) || !link_state)
return;
if (link_state->aspm_support)
sysfs_remove_file_from_group(&pdev->dev.kobj,
&dev_attr_link_state.attr, power_group);
if (link_state->clkpm_capable)
sysfs_remove_file_from_group(&pdev->dev.kobj,
&dev_attr_clk_ctl.attr, power_group);
}
#endif
static int __init pcie_aspm_disable(char *str)
{
if (!strcmp(str, "off")) {
aspm_policy = POLICY_DEFAULT;
aspm_disabled = 1;
aspm_support_enabled = false;
printk(KERN_INFO "PCIe ASPM is disabled\n");
} else if (!strcmp(str, "force")) {
aspm_force = 1;
printk(KERN_INFO "PCIe ASPM is forcedly enabled\n");
}
return 1;
}
__setup("pcie_aspm=", pcie_aspm_disable);
void pcie_no_aspm(void)
{
/*
* Disabling ASPM is intended to prevent the kernel from modifying
* existing hardware state, not to clear existing state. To that end:
* (a) set policy to POLICY_DEFAULT in order to avoid changing state
* (b) prevent userspace from changing policy
*/
if (!aspm_force) {
aspm_policy = POLICY_DEFAULT;
aspm_disabled = 1;
}
}
/**
* pcie_aspm_enabled - is PCIe ASPM enabled?
*
* Returns true if ASPM has not been disabled by the command-line option
* pcie_aspm=off.
**/
int pcie_aspm_enabled(void)
{
return !aspm_disabled;
}
EXPORT_SYMBOL(pcie_aspm_enabled);
bool pcie_aspm_support_enabled(void)
{
return aspm_support_enabled;
}
EXPORT_SYMBOL(pcie_aspm_support_enabled);
| gpl-2.0 |
SystemTera/SystemTera.Server-S-2.6-Kernel | drivers/staging/dream/camera/mt9d112_reg.c | 1476 | 8377 | /*
* Copyright (C) 2008-2009 QUALCOMM Incorporated.
*/
#include "mt9d112.h"
struct register_address_value_pair
preview_snapshot_mode_reg_settings_array[] = {
{0x338C, 0x2703},
{0x3390, 800}, /* Output Width (P) = 640 */
{0x338C, 0x2705},
{0x3390, 600}, /* Output Height (P) = 480 */
{0x338C, 0x2707},
{0x3390, 0x0640}, /* Output Width (S) = 1600 */
{0x338C, 0x2709},
{0x3390, 0x04B0}, /* Output Height (S) = 1200 */
{0x338C, 0x270D},
{0x3390, 0x0000}, /* Row Start (P) = 0 */
{0x338C, 0x270F},
{0x3390, 0x0000}, /* Column Start (P) = 0 */
{0x338C, 0x2711},
{0x3390, 0x04BD}, /* Row End (P) = 1213 */
{0x338C, 0x2713},
{0x3390, 0x064D}, /* Column End (P) = 1613 */
{0x338C, 0x2715},
{0x3390, 0x0000}, /* Extra Delay (P) = 0 */
{0x338C, 0x2717},
{0x3390, 0x2111}, /* Row Speed (P) = 8465 */
{0x338C, 0x2719},
{0x3390, 0x046C}, /* Read Mode (P) = 1132 */
{0x338C, 0x271B},
{0x3390, 0x024F}, /* Sensor_Sample_Time_pck(P) = 591 */
{0x338C, 0x271D},
{0x3390, 0x0102}, /* Sensor_Fine_Correction(P) = 258 */
{0x338C, 0x271F},
{0x3390, 0x0279}, /* Sensor_Fine_IT_min(P) = 633 */
{0x338C, 0x2721},
{0x3390, 0x0155}, /* Sensor_Fine_IT_max_margin(P) = 341 */
{0x338C, 0x2723},
{0x3390, 659}, /* Frame Lines (P) = 679 */
{0x338C, 0x2725},
{0x3390, 0x0824}, /* Line Length (P) = 2084 */
{0x338C, 0x2727},
{0x3390, 0x2020},
{0x338C, 0x2729},
{0x3390, 0x2020},
{0x338C, 0x272B},
{0x3390, 0x1020},
{0x338C, 0x272D},
{0x3390, 0x2007},
{0x338C, 0x272F},
{0x3390, 0x0004}, /* Row Start(S) = 4 */
{0x338C, 0x2731},
{0x3390, 0x0004}, /* Column Start(S) = 4 */
{0x338C, 0x2733},
{0x3390, 0x04BB}, /* Row End(S) = 1211 */
{0x338C, 0x2735},
{0x3390, 0x064B}, /* Column End(S) = 1611 */
{0x338C, 0x2737},
{0x3390, 0x04CE}, /* Extra Delay(S) = 1230 */
{0x338C, 0x2739},
{0x3390, 0x2111}, /* Row Speed(S) = 8465 */
{0x338C, 0x273B},
{0x3390, 0x0024}, /* Read Mode(S) = 36 */
{0x338C, 0x273D},
{0x3390, 0x0120}, /* Sensor sample time pck(S) = 288 */
{0x338C, 0x2741},
{0x3390, 0x0169}, /* Sensor_Fine_IT_min(P) = 361 */
{0x338C, 0x2745},
{0x3390, 0x04FF}, /* Frame Lines(S) = 1279 */
{0x338C, 0x2747},
{0x3390, 0x0824}, /* Line Length(S) = 2084 */
{0x338C, 0x2751},
{0x3390, 0x0000}, /* Crop_X0(P) = 0 */
{0x338C, 0x2753},
{0x3390, 0x0320}, /* Crop_X1(P) = 800 */
{0x338C, 0x2755},
{0x3390, 0x0000}, /* Crop_Y0(P) = 0 */
{0x338C, 0x2757},
{0x3390, 0x0258}, /* Crop_Y1(P) = 600 */
{0x338C, 0x275F},
{0x3390, 0x0000}, /* Crop_X0(S) = 0 */
{0x338C, 0x2761},
{0x3390, 0x0640}, /* Crop_X1(S) = 1600 */
{0x338C, 0x2763},
{0x3390, 0x0000}, /* Crop_Y0(S) = 0 */
{0x338C, 0x2765},
{0x3390, 0x04B0}, /* Crop_Y1(S) = 1200 */
{0x338C, 0x222E},
{0x3390, 0x00A0}, /* R9 Step = 160 */
{0x338C, 0xA408},
{0x3390, 0x001F},
{0x338C, 0xA409},
{0x3390, 0x0021},
{0x338C, 0xA40A},
{0x3390, 0x0025},
{0x338C, 0xA40B},
{0x3390, 0x0027},
{0x338C, 0x2411},
{0x3390, 0x00A0},
{0x338C, 0x2413},
{0x3390, 0x00C0},
{0x338C, 0x2415},
{0x3390, 0x00A0},
{0x338C, 0x2417},
{0x3390, 0x00C0},
{0x338C, 0x2799},
{0x3390, 0x6408}, /* MODE_SPEC_EFFECTS(P) */
{0x338C, 0x279B},
{0x3390, 0x6408}, /* MODE_SPEC_EFFECTS(S) */
};
static struct register_address_value_pair
noise_reduction_reg_settings_array[] = {
{0x338C, 0xA76D},
{0x3390, 0x0003},
{0x338C, 0xA76E},
{0x3390, 0x0003},
{0x338C, 0xA76F},
{0x3390, 0},
{0x338C, 0xA770},
{0x3390, 21},
{0x338C, 0xA771},
{0x3390, 37},
{0x338C, 0xA772},
{0x3390, 63},
{0x338C, 0xA773},
{0x3390, 100},
{0x338C, 0xA774},
{0x3390, 128},
{0x338C, 0xA775},
{0x3390, 151},
{0x338C, 0xA776},
{0x3390, 169},
{0x338C, 0xA777},
{0x3390, 186},
{0x338C, 0xA778},
{0x3390, 199},
{0x338C, 0xA779},
{0x3390, 210},
{0x338C, 0xA77A},
{0x3390, 220},
{0x338C, 0xA77B},
{0x3390, 228},
{0x338C, 0xA77C},
{0x3390, 234},
{0x338C, 0xA77D},
{0x3390, 240},
{0x338C, 0xA77E},
{0x3390, 244},
{0x338C, 0xA77F},
{0x3390, 248},
{0x338C, 0xA780},
{0x3390, 252},
{0x338C, 0xA781},
{0x3390, 255},
{0x338C, 0xA782},
{0x3390, 0},
{0x338C, 0xA783},
{0x3390, 21},
{0x338C, 0xA784},
{0x3390, 37},
{0x338C, 0xA785},
{0x3390, 63},
{0x338C, 0xA786},
{0x3390, 100},
{0x338C, 0xA787},
{0x3390, 128},
{0x338C, 0xA788},
{0x3390, 151},
{0x338C, 0xA789},
{0x3390, 169},
{0x338C, 0xA78A},
{0x3390, 186},
{0x338C, 0xA78B},
{0x3390, 199},
{0x338C, 0xA78C},
{0x3390, 210},
{0x338C, 0xA78D},
{0x3390, 220},
{0x338C, 0xA78E},
{0x3390, 228},
{0x338C, 0xA78F},
{0x3390, 234},
{0x338C, 0xA790},
{0x3390, 240},
{0x338C, 0xA791},
{0x3390, 244},
{0x338C, 0xA793},
{0x3390, 252},
{0x338C, 0xA794},
{0x3390, 255},
{0x338C, 0xA103},
{0x3390, 6},
};
static const struct mt9d112_i2c_reg_conf const lens_roll_off_tbl[] = {
{ 0x34CE, 0x81A0, WORD_LEN, 0 },
{ 0x34D0, 0x6331, WORD_LEN, 0 },
{ 0x34D2, 0x3394, WORD_LEN, 0 },
{ 0x34D4, 0x9966, WORD_LEN, 0 },
{ 0x34D6, 0x4B25, WORD_LEN, 0 },
{ 0x34D8, 0x2670, WORD_LEN, 0 },
{ 0x34DA, 0x724C, WORD_LEN, 0 },
{ 0x34DC, 0xFFFD, WORD_LEN, 0 },
{ 0x34DE, 0x00CA, WORD_LEN, 0 },
{ 0x34E6, 0x00AC, WORD_LEN, 0 },
{ 0x34EE, 0x0EE1, WORD_LEN, 0 },
{ 0x34F6, 0x0D87, WORD_LEN, 0 },
{ 0x3500, 0xE1F7, WORD_LEN, 0 },
{ 0x3508, 0x1CF4, WORD_LEN, 0 },
{ 0x3510, 0x1D28, WORD_LEN, 0 },
{ 0x3518, 0x1F26, WORD_LEN, 0 },
{ 0x3520, 0x2220, WORD_LEN, 0 },
{ 0x3528, 0x333D, WORD_LEN, 0 },
{ 0x3530, 0x15D9, WORD_LEN, 0 },
{ 0x3538, 0xCFB8, WORD_LEN, 0 },
{ 0x354C, 0x05FE, WORD_LEN, 0 },
{ 0x3544, 0x05F8, WORD_LEN, 0 },
{ 0x355C, 0x0596, WORD_LEN, 0 },
{ 0x3554, 0x0611, WORD_LEN, 0 },
{ 0x34E0, 0x00F2, WORD_LEN, 0 },
{ 0x34E8, 0x00A8, WORD_LEN, 0 },
{ 0x34F0, 0x0F7B, WORD_LEN, 0 },
{ 0x34F8, 0x0CD7, WORD_LEN, 0 },
{ 0x3502, 0xFEDB, WORD_LEN, 0 },
{ 0x350A, 0x13E4, WORD_LEN, 0 },
{ 0x3512, 0x1F2C, WORD_LEN, 0 },
{ 0x351A, 0x1D20, WORD_LEN, 0 },
{ 0x3522, 0x2422, WORD_LEN, 0 },
{ 0x352A, 0x2925, WORD_LEN, 0 },
{ 0x3532, 0x1D04, WORD_LEN, 0 },
{ 0x353A, 0xFBF2, WORD_LEN, 0 },
{ 0x354E, 0x0616, WORD_LEN, 0 },
{ 0x3546, 0x0597, WORD_LEN, 0 },
{ 0x355E, 0x05CD, WORD_LEN, 0 },
{ 0x3556, 0x0529, WORD_LEN, 0 },
{ 0x34E4, 0x00B2, WORD_LEN, 0 },
{ 0x34EC, 0x005E, WORD_LEN, 0 },
{ 0x34F4, 0x0F43, WORD_LEN, 0 },
{ 0x34FC, 0x0E2F, WORD_LEN, 0 },
{ 0x3506, 0xF9FC, WORD_LEN, 0 },
{ 0x350E, 0x0CE4, WORD_LEN, 0 },
{ 0x3516, 0x1E1E, WORD_LEN, 0 },
{ 0x351E, 0x1B19, WORD_LEN, 0 },
{ 0x3526, 0x151B, WORD_LEN, 0 },
{ 0x352E, 0x1416, WORD_LEN, 0 },
{ 0x3536, 0x10FC, WORD_LEN, 0 },
{ 0x353E, 0xC018, WORD_LEN, 0 },
{ 0x3552, 0x06B4, WORD_LEN, 0 },
{ 0x354A, 0x0506, WORD_LEN, 0 },
{ 0x3562, 0x06AB, WORD_LEN, 0 },
{ 0x355A, 0x063A, WORD_LEN, 0 },
{ 0x34E2, 0x00E5, WORD_LEN, 0 },
{ 0x34EA, 0x008B, WORD_LEN, 0 },
{ 0x34F2, 0x0E4C, WORD_LEN, 0 },
{ 0x34FA, 0x0CA3, WORD_LEN, 0 },
{ 0x3504, 0x0907, WORD_LEN, 0 },
{ 0x350C, 0x1DFD, WORD_LEN, 0 },
{ 0x3514, 0x1E24, WORD_LEN, 0 },
{ 0x351C, 0x2529, WORD_LEN, 0 },
{ 0x3524, 0x1D20, WORD_LEN, 0 },
{ 0x352C, 0x2332, WORD_LEN, 0 },
{ 0x3534, 0x10E9, WORD_LEN, 0 },
{ 0x353C, 0x0BCB, WORD_LEN, 0 },
{ 0x3550, 0x04EF, WORD_LEN, 0 },
{ 0x3548, 0x0609, WORD_LEN, 0 },
{ 0x3560, 0x0580, WORD_LEN, 0 },
{ 0x3558, 0x05DD, WORD_LEN, 0 },
{ 0x3540, 0x0000, WORD_LEN, 0 },
{ 0x3542, 0x0000, WORD_LEN, 0 }
};
static const struct mt9d112_i2c_reg_conf const pll_setup_tbl[] = {
{ 0x341E, 0x8F09, WORD_LEN, 0 },
{ 0x341C, 0x0250, WORD_LEN, 0 },
{ 0x341E, 0x8F09, WORD_LEN, 5 },
{ 0x341E, 0x8F08, WORD_LEN, 0 }
};
/* Refresh Sequencer */
static const struct mt9d112_i2c_reg_conf const sequencer_tbl[] = {
{ 0x338C, 0x2799, WORD_LEN, 0},
{ 0x3390, 0x6440, WORD_LEN, 5},
{ 0x338C, 0x279B, WORD_LEN, 0},
{ 0x3390, 0x6440, WORD_LEN, 5},
{ 0x338C, 0xA103, WORD_LEN, 0},
{ 0x3390, 0x0005, WORD_LEN, 5},
{ 0x338C, 0xA103, WORD_LEN, 0},
{ 0x3390, 0x0006, WORD_LEN, 5}
};
struct mt9d112_reg mt9d112_regs = {
.prev_snap_reg_settings = &preview_snapshot_mode_reg_settings_array[0],
.prev_snap_reg_settings_size = ARRAY_SIZE(preview_snapshot_mode_reg_settings_array),
.noise_reduction_reg_settings = &noise_reduction_reg_settings_array[0],
.noise_reduction_reg_settings_size = ARRAY_SIZE(noise_reduction_reg_settings_array),
.plltbl = pll_setup_tbl,
.plltbl_size = ARRAY_SIZE(pll_setup_tbl),
.stbl = sequencer_tbl,
.stbl_size = ARRAY_SIZE(sequencer_tbl),
.rftbl = lens_roll_off_tbl,
.rftbl_size = ARRAY_SIZE(lens_roll_off_tbl)
};
| gpl-2.0 |
hunterhu/linux-sunxi | drivers/video/omap2/dss/apply.c | 1988 | 30491 | /*
* Copyright (C) 2011 Texas Instruments
* Author: Tomi Valkeinen <tomi.valkeinen@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define DSS_SUBSYS_NAME "APPLY"
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/jiffies.h>
#include <video/omapdss.h>
#include "dss.h"
#include "dss_features.h"
/*
* We have 4 levels of cache for the dispc settings. First two are in SW and
* the latter two in HW.
*
* set_info()
* v
* +--------------------+
* | user_info |
* +--------------------+
* v
* apply()
* v
* +--------------------+
* | info |
* +--------------------+
* v
* write_regs()
* v
* +--------------------+
* | shadow registers |
* +--------------------+
* v
* VFP or lcd/digit_enable
* v
* +--------------------+
* | registers |
* +--------------------+
*/
struct ovl_priv_data {
bool user_info_dirty;
struct omap_overlay_info user_info;
bool info_dirty;
struct omap_overlay_info info;
bool shadow_info_dirty;
bool extra_info_dirty;
bool shadow_extra_info_dirty;
bool enabled;
enum omap_channel channel;
u32 fifo_low, fifo_high;
/*
* True if overlay is to be enabled. Used to check and calculate configs
* for the overlay before it is enabled in the HW.
*/
bool enabling;
};
struct mgr_priv_data {
bool user_info_dirty;
struct omap_overlay_manager_info user_info;
bool info_dirty;
struct omap_overlay_manager_info info;
bool shadow_info_dirty;
/* If true, GO bit is up and shadow registers cannot be written.
* Never true for manual update displays */
bool busy;
/* If true, dispc output is enabled */
bool updating;
/* If true, a display is enabled using this manager */
bool enabled;
};
static struct {
struct ovl_priv_data ovl_priv_data_array[MAX_DSS_OVERLAYS];
struct mgr_priv_data mgr_priv_data_array[MAX_DSS_MANAGERS];
bool fifo_merge_dirty;
bool fifo_merge;
bool irq_enabled;
} dss_data;
/* protects dss_data */
static spinlock_t data_lock;
/* lock for blocking functions */
static DEFINE_MUTEX(apply_lock);
static DECLARE_COMPLETION(extra_updated_completion);
static void dss_register_vsync_isr(void);
static struct ovl_priv_data *get_ovl_priv(struct omap_overlay *ovl)
{
return &dss_data.ovl_priv_data_array[ovl->id];
}
static struct mgr_priv_data *get_mgr_priv(struct omap_overlay_manager *mgr)
{
return &dss_data.mgr_priv_data_array[mgr->id];
}
void dss_apply_init(void)
{
const int num_ovls = dss_feat_get_num_ovls();
int i;
spin_lock_init(&data_lock);
for (i = 0; i < num_ovls; ++i) {
struct ovl_priv_data *op;
op = &dss_data.ovl_priv_data_array[i];
op->info.global_alpha = 255;
switch (i) {
case 0:
op->info.zorder = 0;
break;
case 1:
op->info.zorder =
dss_has_feature(FEAT_ALPHA_FREE_ZORDER) ? 3 : 0;
break;
case 2:
op->info.zorder =
dss_has_feature(FEAT_ALPHA_FREE_ZORDER) ? 2 : 0;
break;
case 3:
op->info.zorder =
dss_has_feature(FEAT_ALPHA_FREE_ZORDER) ? 1 : 0;
break;
}
op->user_info = op->info;
}
}
static bool ovl_manual_update(struct omap_overlay *ovl)
{
return ovl->manager->device->caps & OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE;
}
static bool mgr_manual_update(struct omap_overlay_manager *mgr)
{
return mgr->device->caps & OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE;
}
static int dss_check_settings_low(struct omap_overlay_manager *mgr,
struct omap_dss_device *dssdev, bool applying)
{
struct omap_overlay_info *oi;
struct omap_overlay_manager_info *mi;
struct omap_overlay *ovl;
struct omap_overlay_info *ois[MAX_DSS_OVERLAYS];
struct ovl_priv_data *op;
struct mgr_priv_data *mp;
mp = get_mgr_priv(mgr);
if (applying && mp->user_info_dirty)
mi = &mp->user_info;
else
mi = &mp->info;
/* collect the infos to be tested into the array */
list_for_each_entry(ovl, &mgr->overlays, list) {
op = get_ovl_priv(ovl);
if (!op->enabled && !op->enabling)
oi = NULL;
else if (applying && op->user_info_dirty)
oi = &op->user_info;
else
oi = &op->info;
ois[ovl->id] = oi;
}
return dss_mgr_check(mgr, dssdev, mi, ois);
}
/*
* check manager and overlay settings using overlay_info from data->info
*/
static int dss_check_settings(struct omap_overlay_manager *mgr,
struct omap_dss_device *dssdev)
{
return dss_check_settings_low(mgr, dssdev, false);
}
/*
* check manager and overlay settings using overlay_info from ovl->info if
* dirty and from data->info otherwise
*/
static int dss_check_settings_apply(struct omap_overlay_manager *mgr,
struct omap_dss_device *dssdev)
{
return dss_check_settings_low(mgr, dssdev, true);
}
static bool need_isr(void)
{
const int num_mgrs = dss_feat_get_num_mgrs();
int i;
for (i = 0; i < num_mgrs; ++i) {
struct omap_overlay_manager *mgr;
struct mgr_priv_data *mp;
struct omap_overlay *ovl;
mgr = omap_dss_get_overlay_manager(i);
mp = get_mgr_priv(mgr);
if (!mp->enabled)
continue;
if (mgr_manual_update(mgr)) {
/* to catch FRAMEDONE */
if (mp->updating)
return true;
} else {
/* to catch GO bit going down */
if (mp->busy)
return true;
/* to write new values to registers */
if (mp->info_dirty)
return true;
/* to set GO bit */
if (mp->shadow_info_dirty)
return true;
list_for_each_entry(ovl, &mgr->overlays, list) {
struct ovl_priv_data *op;
op = get_ovl_priv(ovl);
/*
* NOTE: we check extra_info flags even for
* disabled overlays, as extra_infos need to be
* always written.
*/
/* to write new values to registers */
if (op->extra_info_dirty)
return true;
/* to set GO bit */
if (op->shadow_extra_info_dirty)
return true;
if (!op->enabled)
continue;
/* to write new values to registers */
if (op->info_dirty)
return true;
/* to set GO bit */
if (op->shadow_info_dirty)
return true;
}
}
}
return false;
}
static bool need_go(struct omap_overlay_manager *mgr)
{
struct omap_overlay *ovl;
struct mgr_priv_data *mp;
struct ovl_priv_data *op;
mp = get_mgr_priv(mgr);
if (mp->shadow_info_dirty)
return true;
list_for_each_entry(ovl, &mgr->overlays, list) {
op = get_ovl_priv(ovl);
if (op->shadow_info_dirty || op->shadow_extra_info_dirty)
return true;
}
return false;
}
/* returns true if an extra_info field is currently being updated */
static bool extra_info_update_ongoing(void)
{
const int num_ovls = omap_dss_get_num_overlays();
struct ovl_priv_data *op;
struct omap_overlay *ovl;
struct mgr_priv_data *mp;
int i;
for (i = 0; i < num_ovls; ++i) {
ovl = omap_dss_get_overlay(i);
op = get_ovl_priv(ovl);
if (!ovl->manager)
continue;
mp = get_mgr_priv(ovl->manager);
if (!mp->enabled)
continue;
if (!mp->updating)
continue;
if (op->extra_info_dirty || op->shadow_extra_info_dirty)
return true;
}
return false;
}
/* wait until no extra_info updates are pending */
static void wait_pending_extra_info_updates(void)
{
bool updating;
unsigned long flags;
unsigned long t;
int r;
spin_lock_irqsave(&data_lock, flags);
updating = extra_info_update_ongoing();
if (!updating) {
spin_unlock_irqrestore(&data_lock, flags);
return;
}
init_completion(&extra_updated_completion);
spin_unlock_irqrestore(&data_lock, flags);
t = msecs_to_jiffies(500);
r = wait_for_completion_timeout(&extra_updated_completion, t);
if (r == 0)
DSSWARN("timeout in wait_pending_extra_info_updates\n");
else if (r < 0)
DSSERR("wait_pending_extra_info_updates failed: %d\n", r);
}
int dss_mgr_wait_for_go(struct omap_overlay_manager *mgr)
{
unsigned long timeout = msecs_to_jiffies(500);
struct mgr_priv_data *mp;
u32 irq;
int r;
int i;
struct omap_dss_device *dssdev = mgr->device;
if (!dssdev || dssdev->state != OMAP_DSS_DISPLAY_ACTIVE)
return 0;
if (mgr_manual_update(mgr))
return 0;
r = dispc_runtime_get();
if (r)
return r;
irq = dispc_mgr_get_vsync_irq(mgr->id);
mp = get_mgr_priv(mgr);
i = 0;
while (1) {
unsigned long flags;
bool shadow_dirty, dirty;
spin_lock_irqsave(&data_lock, flags);
dirty = mp->info_dirty;
shadow_dirty = mp->shadow_info_dirty;
spin_unlock_irqrestore(&data_lock, flags);
if (!dirty && !shadow_dirty) {
r = 0;
break;
}
/* 4 iterations is the worst case:
* 1 - initial iteration, dirty = true (between VFP and VSYNC)
* 2 - first VSYNC, dirty = true
* 3 - dirty = false, shadow_dirty = true
* 4 - shadow_dirty = false */
if (i++ == 3) {
DSSERR("mgr(%d)->wait_for_go() not finishing\n",
mgr->id);
r = 0;
break;
}
r = omap_dispc_wait_for_irq_interruptible_timeout(irq, timeout);
if (r == -ERESTARTSYS)
break;
if (r) {
DSSERR("mgr(%d)->wait_for_go() timeout\n", mgr->id);
break;
}
}
dispc_runtime_put();
return r;
}
int dss_mgr_wait_for_go_ovl(struct omap_overlay *ovl)
{
unsigned long timeout = msecs_to_jiffies(500);
struct ovl_priv_data *op;
struct omap_dss_device *dssdev;
u32 irq;
int r;
int i;
if (!ovl->manager)
return 0;
dssdev = ovl->manager->device;
if (!dssdev || dssdev->state != OMAP_DSS_DISPLAY_ACTIVE)
return 0;
if (ovl_manual_update(ovl))
return 0;
r = dispc_runtime_get();
if (r)
return r;
irq = dispc_mgr_get_vsync_irq(ovl->manager->id);
op = get_ovl_priv(ovl);
i = 0;
while (1) {
unsigned long flags;
bool shadow_dirty, dirty;
spin_lock_irqsave(&data_lock, flags);
dirty = op->info_dirty;
shadow_dirty = op->shadow_info_dirty;
spin_unlock_irqrestore(&data_lock, flags);
if (!dirty && !shadow_dirty) {
r = 0;
break;
}
/* 4 iterations is the worst case:
* 1 - initial iteration, dirty = true (between VFP and VSYNC)
* 2 - first VSYNC, dirty = true
* 3 - dirty = false, shadow_dirty = true
* 4 - shadow_dirty = false */
if (i++ == 3) {
DSSERR("ovl(%d)->wait_for_go() not finishing\n",
ovl->id);
r = 0;
break;
}
r = omap_dispc_wait_for_irq_interruptible_timeout(irq, timeout);
if (r == -ERESTARTSYS)
break;
if (r) {
DSSERR("ovl(%d)->wait_for_go() timeout\n", ovl->id);
break;
}
}
dispc_runtime_put();
return r;
}
static void dss_ovl_write_regs(struct omap_overlay *ovl)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
struct omap_overlay_info *oi;
bool ilace, replication;
struct mgr_priv_data *mp;
int r;
DSSDBGF("%d", ovl->id);
if (!op->enabled || !op->info_dirty)
return;
oi = &op->info;
replication = dss_use_replication(ovl->manager->device, oi->color_mode);
ilace = ovl->manager->device->type == OMAP_DISPLAY_TYPE_VENC;
r = dispc_ovl_setup(ovl->id, oi, ilace, replication);
if (r) {
/*
* We can't do much here, as this function can be called from
* vsync interrupt.
*/
DSSERR("dispc_ovl_setup failed for ovl %d\n", ovl->id);
/* This will leave fifo configurations in a nonoptimal state */
op->enabled = false;
dispc_ovl_enable(ovl->id, false);
return;
}
mp = get_mgr_priv(ovl->manager);
op->info_dirty = false;
if (mp->updating)
op->shadow_info_dirty = true;
}
static void dss_ovl_write_regs_extra(struct omap_overlay *ovl)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
struct mgr_priv_data *mp;
DSSDBGF("%d", ovl->id);
if (!op->extra_info_dirty)
return;
/* note: write also when op->enabled == false, so that the ovl gets
* disabled */
dispc_ovl_enable(ovl->id, op->enabled);
dispc_ovl_set_channel_out(ovl->id, op->channel);
dispc_ovl_set_fifo_threshold(ovl->id, op->fifo_low, op->fifo_high);
mp = get_mgr_priv(ovl->manager);
op->extra_info_dirty = false;
if (mp->updating)
op->shadow_extra_info_dirty = true;
}
static void dss_mgr_write_regs(struct omap_overlay_manager *mgr)
{
struct mgr_priv_data *mp = get_mgr_priv(mgr);
struct omap_overlay *ovl;
DSSDBGF("%d", mgr->id);
if (!mp->enabled)
return;
WARN_ON(mp->busy);
/* Commit overlay settings */
list_for_each_entry(ovl, &mgr->overlays, list) {
dss_ovl_write_regs(ovl);
dss_ovl_write_regs_extra(ovl);
}
if (mp->info_dirty) {
dispc_mgr_setup(mgr->id, &mp->info);
mp->info_dirty = false;
if (mp->updating)
mp->shadow_info_dirty = true;
}
}
static void dss_write_regs_common(void)
{
const int num_mgrs = omap_dss_get_num_overlay_managers();
int i;
if (!dss_data.fifo_merge_dirty)
return;
for (i = 0; i < num_mgrs; ++i) {
struct omap_overlay_manager *mgr;
struct mgr_priv_data *mp;
mgr = omap_dss_get_overlay_manager(i);
mp = get_mgr_priv(mgr);
if (mp->enabled) {
if (dss_data.fifo_merge_dirty) {
dispc_enable_fifomerge(dss_data.fifo_merge);
dss_data.fifo_merge_dirty = false;
}
if (mp->updating)
mp->shadow_info_dirty = true;
}
}
}
static void dss_write_regs(void)
{
const int num_mgrs = omap_dss_get_num_overlay_managers();
int i;
dss_write_regs_common();
for (i = 0; i < num_mgrs; ++i) {
struct omap_overlay_manager *mgr;
struct mgr_priv_data *mp;
int r;
mgr = omap_dss_get_overlay_manager(i);
mp = get_mgr_priv(mgr);
if (!mp->enabled || mgr_manual_update(mgr) || mp->busy)
continue;
r = dss_check_settings(mgr, mgr->device);
if (r) {
DSSERR("cannot write registers for manager %s: "
"illegal configuration\n", mgr->name);
continue;
}
dss_mgr_write_regs(mgr);
}
}
static void dss_set_go_bits(void)
{
const int num_mgrs = omap_dss_get_num_overlay_managers();
int i;
for (i = 0; i < num_mgrs; ++i) {
struct omap_overlay_manager *mgr;
struct mgr_priv_data *mp;
mgr = omap_dss_get_overlay_manager(i);
mp = get_mgr_priv(mgr);
if (!mp->enabled || mgr_manual_update(mgr) || mp->busy)
continue;
if (!need_go(mgr))
continue;
mp->busy = true;
if (!dss_data.irq_enabled && need_isr())
dss_register_vsync_isr();
dispc_mgr_go(mgr->id);
}
}
static void mgr_clear_shadow_dirty(struct omap_overlay_manager *mgr)
{
struct omap_overlay *ovl;
struct mgr_priv_data *mp;
struct ovl_priv_data *op;
mp = get_mgr_priv(mgr);
mp->shadow_info_dirty = false;
list_for_each_entry(ovl, &mgr->overlays, list) {
op = get_ovl_priv(ovl);
op->shadow_info_dirty = false;
op->shadow_extra_info_dirty = false;
}
}
void dss_mgr_start_update(struct omap_overlay_manager *mgr)
{
struct mgr_priv_data *mp = get_mgr_priv(mgr);
unsigned long flags;
int r;
spin_lock_irqsave(&data_lock, flags);
WARN_ON(mp->updating);
r = dss_check_settings(mgr, mgr->device);
if (r) {
DSSERR("cannot start manual update: illegal configuration\n");
spin_unlock_irqrestore(&data_lock, flags);
return;
}
dss_mgr_write_regs(mgr);
dss_write_regs_common();
mp->updating = true;
if (!dss_data.irq_enabled && need_isr())
dss_register_vsync_isr();
dispc_mgr_enable(mgr->id, true);
mgr_clear_shadow_dirty(mgr);
spin_unlock_irqrestore(&data_lock, flags);
}
static void dss_apply_irq_handler(void *data, u32 mask);
static void dss_register_vsync_isr(void)
{
const int num_mgrs = dss_feat_get_num_mgrs();
u32 mask;
int r, i;
mask = 0;
for (i = 0; i < num_mgrs; ++i)
mask |= dispc_mgr_get_vsync_irq(i);
for (i = 0; i < num_mgrs; ++i)
mask |= dispc_mgr_get_framedone_irq(i);
r = omap_dispc_register_isr(dss_apply_irq_handler, NULL, mask);
WARN_ON(r);
dss_data.irq_enabled = true;
}
static void dss_unregister_vsync_isr(void)
{
const int num_mgrs = dss_feat_get_num_mgrs();
u32 mask;
int r, i;
mask = 0;
for (i = 0; i < num_mgrs; ++i)
mask |= dispc_mgr_get_vsync_irq(i);
for (i = 0; i < num_mgrs; ++i)
mask |= dispc_mgr_get_framedone_irq(i);
r = omap_dispc_unregister_isr(dss_apply_irq_handler, NULL, mask);
WARN_ON(r);
dss_data.irq_enabled = false;
}
static void dss_apply_irq_handler(void *data, u32 mask)
{
const int num_mgrs = dss_feat_get_num_mgrs();
int i;
bool extra_updating;
spin_lock(&data_lock);
/* clear busy, updating flags, shadow_dirty flags */
for (i = 0; i < num_mgrs; i++) {
struct omap_overlay_manager *mgr;
struct mgr_priv_data *mp;
bool was_updating;
mgr = omap_dss_get_overlay_manager(i);
mp = get_mgr_priv(mgr);
if (!mp->enabled)
continue;
was_updating = mp->updating;
mp->updating = dispc_mgr_is_enabled(i);
if (!mgr_manual_update(mgr)) {
bool was_busy = mp->busy;
mp->busy = dispc_mgr_go_busy(i);
if (was_busy && !mp->busy)
mgr_clear_shadow_dirty(mgr);
}
}
dss_write_regs();
dss_set_go_bits();
extra_updating = extra_info_update_ongoing();
if (!extra_updating)
complete_all(&extra_updated_completion);
if (!need_isr())
dss_unregister_vsync_isr();
spin_unlock(&data_lock);
}
static void omap_dss_mgr_apply_ovl(struct omap_overlay *ovl)
{
struct ovl_priv_data *op;
op = get_ovl_priv(ovl);
if (!op->user_info_dirty)
return;
op->user_info_dirty = false;
op->info_dirty = true;
op->info = op->user_info;
}
static void omap_dss_mgr_apply_mgr(struct omap_overlay_manager *mgr)
{
struct mgr_priv_data *mp;
mp = get_mgr_priv(mgr);
if (!mp->user_info_dirty)
return;
mp->user_info_dirty = false;
mp->info_dirty = true;
mp->info = mp->user_info;
}
int omap_dss_mgr_apply(struct omap_overlay_manager *mgr)
{
unsigned long flags;
struct omap_overlay *ovl;
int r;
DSSDBG("omap_dss_mgr_apply(%s)\n", mgr->name);
spin_lock_irqsave(&data_lock, flags);
r = dss_check_settings_apply(mgr, mgr->device);
if (r) {
spin_unlock_irqrestore(&data_lock, flags);
DSSERR("failed to apply settings: illegal configuration.\n");
return r;
}
/* Configure overlays */
list_for_each_entry(ovl, &mgr->overlays, list)
omap_dss_mgr_apply_ovl(ovl);
/* Configure manager */
omap_dss_mgr_apply_mgr(mgr);
dss_write_regs();
dss_set_go_bits();
spin_unlock_irqrestore(&data_lock, flags);
return 0;
}
static void dss_apply_ovl_enable(struct omap_overlay *ovl, bool enable)
{
struct ovl_priv_data *op;
op = get_ovl_priv(ovl);
if (op->enabled == enable)
return;
op->enabled = enable;
op->extra_info_dirty = true;
}
static void dss_apply_ovl_fifo_thresholds(struct omap_overlay *ovl,
u32 fifo_low, u32 fifo_high)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
if (op->fifo_low == fifo_low && op->fifo_high == fifo_high)
return;
op->fifo_low = fifo_low;
op->fifo_high = fifo_high;
op->extra_info_dirty = true;
}
static void dss_apply_fifo_merge(bool use_fifo_merge)
{
if (dss_data.fifo_merge == use_fifo_merge)
return;
dss_data.fifo_merge = use_fifo_merge;
dss_data.fifo_merge_dirty = true;
}
static void dss_ovl_setup_fifo(struct omap_overlay *ovl,
bool use_fifo_merge)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
struct omap_dss_device *dssdev;
u32 fifo_low, fifo_high;
if (!op->enabled && !op->enabling)
return;
dssdev = ovl->manager->device;
dispc_ovl_compute_fifo_thresholds(ovl->id, &fifo_low, &fifo_high,
use_fifo_merge, ovl_manual_update(ovl));
dss_apply_ovl_fifo_thresholds(ovl, fifo_low, fifo_high);
}
static void dss_mgr_setup_fifos(struct omap_overlay_manager *mgr,
bool use_fifo_merge)
{
struct omap_overlay *ovl;
struct mgr_priv_data *mp;
mp = get_mgr_priv(mgr);
if (!mp->enabled)
return;
list_for_each_entry(ovl, &mgr->overlays, list)
dss_ovl_setup_fifo(ovl, use_fifo_merge);
}
static void dss_setup_fifos(bool use_fifo_merge)
{
const int num_mgrs = omap_dss_get_num_overlay_managers();
struct omap_overlay_manager *mgr;
int i;
for (i = 0; i < num_mgrs; ++i) {
mgr = omap_dss_get_overlay_manager(i);
dss_mgr_setup_fifos(mgr, use_fifo_merge);
}
}
static int get_num_used_managers(void)
{
const int num_mgrs = omap_dss_get_num_overlay_managers();
struct omap_overlay_manager *mgr;
struct mgr_priv_data *mp;
int i;
int enabled_mgrs;
enabled_mgrs = 0;
for (i = 0; i < num_mgrs; ++i) {
mgr = omap_dss_get_overlay_manager(i);
mp = get_mgr_priv(mgr);
if (!mp->enabled)
continue;
enabled_mgrs++;
}
return enabled_mgrs;
}
static int get_num_used_overlays(void)
{
const int num_ovls = omap_dss_get_num_overlays();
struct omap_overlay *ovl;
struct ovl_priv_data *op;
struct mgr_priv_data *mp;
int i;
int enabled_ovls;
enabled_ovls = 0;
for (i = 0; i < num_ovls; ++i) {
ovl = omap_dss_get_overlay(i);
op = get_ovl_priv(ovl);
if (!op->enabled && !op->enabling)
continue;
mp = get_mgr_priv(ovl->manager);
if (!mp->enabled)
continue;
enabled_ovls++;
}
return enabled_ovls;
}
static bool get_use_fifo_merge(void)
{
int enabled_mgrs = get_num_used_managers();
int enabled_ovls = get_num_used_overlays();
if (!dss_has_feature(FEAT_FIFO_MERGE))
return false;
/*
* In theory the only requirement for fifomerge is enabled_ovls <= 1.
* However, if we have two managers enabled and set/unset the fifomerge,
* we need to set the GO bits in particular sequence for the managers,
* and wait in between.
*
* This is rather difficult as new apply calls can happen at any time,
* so we simplify the problem by requiring also that enabled_mgrs <= 1.
* In practice this shouldn't matter, because when only one overlay is
* enabled, most likely only one output is enabled.
*/
return enabled_mgrs <= 1 && enabled_ovls <= 1;
}
int dss_mgr_enable(struct omap_overlay_manager *mgr)
{
struct mgr_priv_data *mp = get_mgr_priv(mgr);
unsigned long flags;
int r;
bool fifo_merge;
mutex_lock(&apply_lock);
if (mp->enabled)
goto out;
spin_lock_irqsave(&data_lock, flags);
mp->enabled = true;
r = dss_check_settings(mgr, mgr->device);
if (r) {
DSSERR("failed to enable manager %d: check_settings failed\n",
mgr->id);
goto err;
}
/* step 1: setup fifos/fifomerge before enabling the manager */
fifo_merge = get_use_fifo_merge();
dss_setup_fifos(fifo_merge);
dss_apply_fifo_merge(fifo_merge);
dss_write_regs();
dss_set_go_bits();
spin_unlock_irqrestore(&data_lock, flags);
/* wait until fifo config is in */
wait_pending_extra_info_updates();
/* step 2: enable the manager */
spin_lock_irqsave(&data_lock, flags);
if (!mgr_manual_update(mgr))
mp->updating = true;
spin_unlock_irqrestore(&data_lock, flags);
if (!mgr_manual_update(mgr))
dispc_mgr_enable(mgr->id, true);
out:
mutex_unlock(&apply_lock);
return 0;
err:
mp->enabled = false;
spin_unlock_irqrestore(&data_lock, flags);
mutex_unlock(&apply_lock);
return r;
}
void dss_mgr_disable(struct omap_overlay_manager *mgr)
{
struct mgr_priv_data *mp = get_mgr_priv(mgr);
unsigned long flags;
bool fifo_merge;
mutex_lock(&apply_lock);
if (!mp->enabled)
goto out;
if (!mgr_manual_update(mgr))
dispc_mgr_enable(mgr->id, false);
spin_lock_irqsave(&data_lock, flags);
mp->updating = false;
mp->enabled = false;
fifo_merge = get_use_fifo_merge();
dss_setup_fifos(fifo_merge);
dss_apply_fifo_merge(fifo_merge);
dss_write_regs();
dss_set_go_bits();
spin_unlock_irqrestore(&data_lock, flags);
wait_pending_extra_info_updates();
out:
mutex_unlock(&apply_lock);
}
int dss_mgr_set_info(struct omap_overlay_manager *mgr,
struct omap_overlay_manager_info *info)
{
struct mgr_priv_data *mp = get_mgr_priv(mgr);
unsigned long flags;
int r;
r = dss_mgr_simple_check(mgr, info);
if (r)
return r;
spin_lock_irqsave(&data_lock, flags);
mp->user_info = *info;
mp->user_info_dirty = true;
spin_unlock_irqrestore(&data_lock, flags);
return 0;
}
void dss_mgr_get_info(struct omap_overlay_manager *mgr,
struct omap_overlay_manager_info *info)
{
struct mgr_priv_data *mp = get_mgr_priv(mgr);
unsigned long flags;
spin_lock_irqsave(&data_lock, flags);
*info = mp->user_info;
spin_unlock_irqrestore(&data_lock, flags);
}
int dss_mgr_set_device(struct omap_overlay_manager *mgr,
struct omap_dss_device *dssdev)
{
int r;
mutex_lock(&apply_lock);
if (dssdev->manager) {
DSSERR("display '%s' already has a manager '%s'\n",
dssdev->name, dssdev->manager->name);
r = -EINVAL;
goto err;
}
if ((mgr->supported_displays & dssdev->type) == 0) {
DSSERR("display '%s' does not support manager '%s'\n",
dssdev->name, mgr->name);
r = -EINVAL;
goto err;
}
dssdev->manager = mgr;
mgr->device = dssdev;
mutex_unlock(&apply_lock);
return 0;
err:
mutex_unlock(&apply_lock);
return r;
}
int dss_mgr_unset_device(struct omap_overlay_manager *mgr)
{
int r;
mutex_lock(&apply_lock);
if (!mgr->device) {
DSSERR("failed to unset display, display not set.\n");
r = -EINVAL;
goto err;
}
/*
* Don't allow currently enabled displays to have the overlay manager
* pulled out from underneath them
*/
if (mgr->device->state != OMAP_DSS_DISPLAY_DISABLED) {
r = -EINVAL;
goto err;
}
mgr->device->manager = NULL;
mgr->device = NULL;
mutex_unlock(&apply_lock);
return 0;
err:
mutex_unlock(&apply_lock);
return r;
}
int dss_ovl_set_info(struct omap_overlay *ovl,
struct omap_overlay_info *info)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
unsigned long flags;
int r;
r = dss_ovl_simple_check(ovl, info);
if (r)
return r;
spin_lock_irqsave(&data_lock, flags);
op->user_info = *info;
op->user_info_dirty = true;
spin_unlock_irqrestore(&data_lock, flags);
return 0;
}
void dss_ovl_get_info(struct omap_overlay *ovl,
struct omap_overlay_info *info)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
unsigned long flags;
spin_lock_irqsave(&data_lock, flags);
*info = op->user_info;
spin_unlock_irqrestore(&data_lock, flags);
}
int dss_ovl_set_manager(struct omap_overlay *ovl,
struct omap_overlay_manager *mgr)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
unsigned long flags;
int r;
if (!mgr)
return -EINVAL;
mutex_lock(&apply_lock);
if (ovl->manager) {
DSSERR("overlay '%s' already has a manager '%s'\n",
ovl->name, ovl->manager->name);
r = -EINVAL;
goto err;
}
spin_lock_irqsave(&data_lock, flags);
if (op->enabled) {
spin_unlock_irqrestore(&data_lock, flags);
DSSERR("overlay has to be disabled to change the manager\n");
r = -EINVAL;
goto err;
}
op->channel = mgr->id;
op->extra_info_dirty = true;
ovl->manager = mgr;
list_add_tail(&ovl->list, &mgr->overlays);
spin_unlock_irqrestore(&data_lock, flags);
/* XXX: When there is an overlay on a DSI manual update display, and
* the overlay is first disabled, then moved to tv, and enabled, we
* seem to get SYNC_LOST_DIGIT error.
*
* Waiting doesn't seem to help, but updating the manual update display
* after disabling the overlay seems to fix this. This hints that the
* overlay is perhaps somehow tied to the LCD output until the output
* is updated.
*
* Userspace workaround for this is to update the LCD after disabling
* the overlay, but before moving the overlay to TV.
*/
mutex_unlock(&apply_lock);
return 0;
err:
mutex_unlock(&apply_lock);
return r;
}
int dss_ovl_unset_manager(struct omap_overlay *ovl)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
unsigned long flags;
int r;
mutex_lock(&apply_lock);
if (!ovl->manager) {
DSSERR("failed to detach overlay: manager not set\n");
r = -EINVAL;
goto err;
}
spin_lock_irqsave(&data_lock, flags);
if (op->enabled) {
spin_unlock_irqrestore(&data_lock, flags);
DSSERR("overlay has to be disabled to unset the manager\n");
r = -EINVAL;
goto err;
}
op->channel = -1;
ovl->manager = NULL;
list_del(&ovl->list);
spin_unlock_irqrestore(&data_lock, flags);
mutex_unlock(&apply_lock);
return 0;
err:
mutex_unlock(&apply_lock);
return r;
}
bool dss_ovl_is_enabled(struct omap_overlay *ovl)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
unsigned long flags;
bool e;
spin_lock_irqsave(&data_lock, flags);
e = op->enabled;
spin_unlock_irqrestore(&data_lock, flags);
return e;
}
int dss_ovl_enable(struct omap_overlay *ovl)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
unsigned long flags;
bool fifo_merge;
int r;
mutex_lock(&apply_lock);
if (op->enabled) {
r = 0;
goto err1;
}
if (ovl->manager == NULL || ovl->manager->device == NULL) {
r = -EINVAL;
goto err1;
}
spin_lock_irqsave(&data_lock, flags);
op->enabling = true;
r = dss_check_settings(ovl->manager, ovl->manager->device);
if (r) {
DSSERR("failed to enable overlay %d: check_settings failed\n",
ovl->id);
goto err2;
}
/* step 1: configure fifos/fifomerge for currently enabled ovls */
fifo_merge = get_use_fifo_merge();
dss_setup_fifos(fifo_merge);
dss_apply_fifo_merge(fifo_merge);
dss_write_regs();
dss_set_go_bits();
spin_unlock_irqrestore(&data_lock, flags);
/* wait for fifo configs to go in */
wait_pending_extra_info_updates();
/* step 2: enable the overlay */
spin_lock_irqsave(&data_lock, flags);
op->enabling = false;
dss_apply_ovl_enable(ovl, true);
dss_write_regs();
dss_set_go_bits();
spin_unlock_irqrestore(&data_lock, flags);
/* wait for overlay to be enabled */
wait_pending_extra_info_updates();
mutex_unlock(&apply_lock);
return 0;
err2:
op->enabling = false;
spin_unlock_irqrestore(&data_lock, flags);
err1:
mutex_unlock(&apply_lock);
return r;
}
int dss_ovl_disable(struct omap_overlay *ovl)
{
struct ovl_priv_data *op = get_ovl_priv(ovl);
unsigned long flags;
bool fifo_merge;
int r;
mutex_lock(&apply_lock);
if (!op->enabled) {
r = 0;
goto err;
}
if (ovl->manager == NULL || ovl->manager->device == NULL) {
r = -EINVAL;
goto err;
}
/* step 1: disable the overlay */
spin_lock_irqsave(&data_lock, flags);
dss_apply_ovl_enable(ovl, false);
dss_write_regs();
dss_set_go_bits();
spin_unlock_irqrestore(&data_lock, flags);
/* wait for the overlay to be disabled */
wait_pending_extra_info_updates();
/* step 2: configure fifos/fifomerge */
spin_lock_irqsave(&data_lock, flags);
fifo_merge = get_use_fifo_merge();
dss_setup_fifos(fifo_merge);
dss_apply_fifo_merge(fifo_merge);
dss_write_regs();
dss_set_go_bits();
spin_unlock_irqrestore(&data_lock, flags);
/* wait for fifo config to go in */
wait_pending_extra_info_updates();
mutex_unlock(&apply_lock);
return 0;
err:
mutex_unlock(&apply_lock);
return r;
}
| gpl-2.0 |
C-Aniruddh/ace-kernel_lettuce | arch/mips/jz4740/board-qi_lb60.c | 1988 | 12347 | /*
* linux/arch/mips/jz4740/board-qi_lb60.c
*
* QI_LB60 board support
*
* Copyright (c) 2009 Qi Hardware inc.,
* Author: Xiangfu Liu <xiangfu@qi-hardware.com>
* Copyright 2010, Lars-Peter Clausen <lars@metafoo.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 or later
* as published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <linux/input/matrix_keypad.h>
#include <linux/spi/spi.h>
#include <linux/spi/spi_gpio.h>
#include <linux/power_supply.h>
#include <linux/power/jz4740-battery.h>
#include <linux/power/gpio-charger.h>
#include <asm/mach-jz4740/jz4740_fb.h>
#include <asm/mach-jz4740/jz4740_mmc.h>
#include <asm/mach-jz4740/jz4740_nand.h>
#include <linux/regulator/fixed.h>
#include <linux/regulator/machine.h>
#include <linux/leds_pwm.h>
#include <asm/mach-jz4740/platform.h>
#include "clock.h"
static bool is_avt2;
/* GPIOs */
#define QI_LB60_GPIO_SD_CD JZ_GPIO_PORTD(0)
#define QI_LB60_GPIO_SD_VCC_EN_N JZ_GPIO_PORTD(2)
#define QI_LB60_GPIO_KEYOUT(x) (JZ_GPIO_PORTC(10) + (x))
#define QI_LB60_GPIO_KEYIN(x) (JZ_GPIO_PORTD(18) + (x))
#define QI_LB60_GPIO_KEYIN8 JZ_GPIO_PORTD(26)
/* NAND */
static struct nand_ecclayout qi_lb60_ecclayout_1gb = {
.eccbytes = 36,
.eccpos = {
6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41
},
.oobfree = {
{ .offset = 2, .length = 4 },
{ .offset = 42, .length = 22 }
},
};
/* Early prototypes of the QI LB60 had only 1GB of NAND.
* In order to support these devices as well the partition and ecc layout is
* initialized depending on the NAND size */
static struct mtd_partition qi_lb60_partitions_1gb[] = {
{
.name = "NAND BOOT partition",
.offset = 0 * 0x100000,
.size = 4 * 0x100000,
},
{
.name = "NAND KERNEL partition",
.offset = 4 * 0x100000,
.size = 4 * 0x100000,
},
{
.name = "NAND ROOTFS partition",
.offset = 8 * 0x100000,
.size = (504 + 512) * 0x100000,
},
};
static struct nand_ecclayout qi_lb60_ecclayout_2gb = {
.eccbytes = 72,
.eccpos = {
12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75,
76, 77, 78, 79, 80, 81, 82, 83
},
.oobfree = {
{ .offset = 2, .length = 10 },
{ .offset = 84, .length = 44 },
},
};
static struct mtd_partition qi_lb60_partitions_2gb[] = {
{
.name = "NAND BOOT partition",
.offset = 0 * 0x100000,
.size = 4 * 0x100000,
},
{
.name = "NAND KERNEL partition",
.offset = 4 * 0x100000,
.size = 4 * 0x100000,
},
{
.name = "NAND ROOTFS partition",
.offset = 8 * 0x100000,
.size = (504 + 512 + 1024) * 0x100000,
},
};
static void qi_lb60_nand_ident(struct platform_device *pdev,
struct nand_chip *chip, struct mtd_partition **partitions,
int *num_partitions)
{
if (chip->page_shift == 12) {
chip->ecc.layout = &qi_lb60_ecclayout_2gb;
*partitions = qi_lb60_partitions_2gb;
*num_partitions = ARRAY_SIZE(qi_lb60_partitions_2gb);
} else {
chip->ecc.layout = &qi_lb60_ecclayout_1gb;
*partitions = qi_lb60_partitions_1gb;
*num_partitions = ARRAY_SIZE(qi_lb60_partitions_1gb);
}
}
static struct jz_nand_platform_data qi_lb60_nand_pdata = {
.ident_callback = qi_lb60_nand_ident,
.busy_gpio = 94,
.banks = { 1 },
};
/* Keyboard*/
#define KEY_QI_QI KEY_F13
#define KEY_QI_UPRED KEY_RIGHTALT
#define KEY_QI_VOLUP KEY_VOLUMEUP
#define KEY_QI_VOLDOWN KEY_VOLUMEDOWN
#define KEY_QI_FN KEY_LEFTCTRL
static const uint32_t qi_lb60_keymap[] = {
KEY(0, 0, KEY_F1), /* S2 */
KEY(0, 1, KEY_F2), /* S3 */
KEY(0, 2, KEY_F3), /* S4 */
KEY(0, 3, KEY_F4), /* S5 */
KEY(0, 4, KEY_F5), /* S6 */
KEY(0, 5, KEY_F6), /* S7 */
KEY(0, 6, KEY_F7), /* S8 */
KEY(1, 0, KEY_Q), /* S10 */
KEY(1, 1, KEY_W), /* S11 */
KEY(1, 2, KEY_E), /* S12 */
KEY(1, 3, KEY_R), /* S13 */
KEY(1, 4, KEY_T), /* S14 */
KEY(1, 5, KEY_Y), /* S15 */
KEY(1, 6, KEY_U), /* S16 */
KEY(1, 7, KEY_I), /* S17 */
KEY(2, 0, KEY_A), /* S18 */
KEY(2, 1, KEY_S), /* S19 */
KEY(2, 2, KEY_D), /* S20 */
KEY(2, 3, KEY_F), /* S21 */
KEY(2, 4, KEY_G), /* S22 */
KEY(2, 5, KEY_H), /* S23 */
KEY(2, 6, KEY_J), /* S24 */
KEY(2, 7, KEY_K), /* S25 */
KEY(3, 0, KEY_ESC), /* S26 */
KEY(3, 1, KEY_Z), /* S27 */
KEY(3, 2, KEY_X), /* S28 */
KEY(3, 3, KEY_C), /* S29 */
KEY(3, 4, KEY_V), /* S30 */
KEY(3, 5, KEY_B), /* S31 */
KEY(3, 6, KEY_N), /* S32 */
KEY(3, 7, KEY_M), /* S33 */
KEY(4, 0, KEY_TAB), /* S34 */
KEY(4, 1, KEY_CAPSLOCK), /* S35 */
KEY(4, 2, KEY_BACKSLASH), /* S36 */
KEY(4, 3, KEY_APOSTROPHE), /* S37 */
KEY(4, 4, KEY_COMMA), /* S38 */
KEY(4, 5, KEY_DOT), /* S39 */
KEY(4, 6, KEY_SLASH), /* S40 */
KEY(4, 7, KEY_UP), /* S41 */
KEY(5, 0, KEY_O), /* S42 */
KEY(5, 1, KEY_L), /* S43 */
KEY(5, 2, KEY_EQUAL), /* S44 */
KEY(5, 3, KEY_QI_UPRED), /* S45 */
KEY(5, 4, KEY_SPACE), /* S46 */
KEY(5, 5, KEY_QI_QI), /* S47 */
KEY(5, 6, KEY_RIGHTCTRL), /* S48 */
KEY(5, 7, KEY_LEFT), /* S49 */
KEY(6, 0, KEY_F8), /* S50 */
KEY(6, 1, KEY_P), /* S51 */
KEY(6, 2, KEY_BACKSPACE),/* S52 */
KEY(6, 3, KEY_ENTER), /* S53 */
KEY(6, 4, KEY_QI_VOLUP), /* S54 */
KEY(6, 5, KEY_QI_VOLDOWN), /* S55 */
KEY(6, 6, KEY_DOWN), /* S56 */
KEY(6, 7, KEY_RIGHT), /* S57 */
KEY(7, 0, KEY_LEFTSHIFT), /* S58 */
KEY(7, 1, KEY_LEFTALT), /* S59 */
KEY(7, 2, KEY_QI_FN), /* S60 */
};
static const struct matrix_keymap_data qi_lb60_keymap_data = {
.keymap = qi_lb60_keymap,
.keymap_size = ARRAY_SIZE(qi_lb60_keymap),
};
static const unsigned int qi_lb60_keypad_cols[] = {
QI_LB60_GPIO_KEYOUT(0),
QI_LB60_GPIO_KEYOUT(1),
QI_LB60_GPIO_KEYOUT(2),
QI_LB60_GPIO_KEYOUT(3),
QI_LB60_GPIO_KEYOUT(4),
QI_LB60_GPIO_KEYOUT(5),
QI_LB60_GPIO_KEYOUT(6),
QI_LB60_GPIO_KEYOUT(7),
};
static const unsigned int qi_lb60_keypad_rows[] = {
QI_LB60_GPIO_KEYIN(0),
QI_LB60_GPIO_KEYIN(1),
QI_LB60_GPIO_KEYIN(2),
QI_LB60_GPIO_KEYIN(3),
QI_LB60_GPIO_KEYIN(4),
QI_LB60_GPIO_KEYIN(5),
QI_LB60_GPIO_KEYIN(6),
QI_LB60_GPIO_KEYIN8,
};
static struct matrix_keypad_platform_data qi_lb60_pdata = {
.keymap_data = &qi_lb60_keymap_data,
.col_gpios = qi_lb60_keypad_cols,
.row_gpios = qi_lb60_keypad_rows,
.num_col_gpios = ARRAY_SIZE(qi_lb60_keypad_cols),
.num_row_gpios = ARRAY_SIZE(qi_lb60_keypad_rows),
.col_scan_delay_us = 10,
.debounce_ms = 10,
.wakeup = 1,
.active_low = 1,
};
static struct platform_device qi_lb60_keypad = {
.name = "matrix-keypad",
.id = -1,
.dev = {
.platform_data = &qi_lb60_pdata,
},
};
/* Display */
static struct fb_videomode qi_lb60_video_modes[] = {
{
.name = "320x240",
.xres = 320,
.yres = 240,
.refresh = 30,
.left_margin = 140,
.right_margin = 273,
.upper_margin = 20,
.lower_margin = 2,
.hsync_len = 1,
.vsync_len = 1,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
},
};
static struct jz4740_fb_platform_data qi_lb60_fb_pdata = {
.width = 60,
.height = 45,
.num_modes = ARRAY_SIZE(qi_lb60_video_modes),
.modes = qi_lb60_video_modes,
.bpp = 24,
.lcd_type = JZ_LCD_TYPE_8BIT_SERIAL,
.pixclk_falling_edge = 1,
};
struct spi_gpio_platform_data spigpio_platform_data = {
.sck = JZ_GPIO_PORTC(23),
.mosi = JZ_GPIO_PORTC(22),
.miso = -1,
.num_chipselect = 1,
};
static struct platform_device spigpio_device = {
.name = "spi_gpio",
.id = 1,
.dev = {
.platform_data = &spigpio_platform_data,
},
};
static struct spi_board_info qi_lb60_spi_board_info[] = {
{
.modalias = "ili8960",
.controller_data = (void *)JZ_GPIO_PORTC(21),
.chip_select = 0,
.bus_num = 1,
.max_speed_hz = 30 * 1000,
.mode = SPI_3WIRE,
},
};
/* Battery */
static struct jz_battery_platform_data qi_lb60_battery_pdata = {
.gpio_charge = JZ_GPIO_PORTC(27),
.gpio_charge_active_low = 1,
.info = {
.name = "battery",
.technology = POWER_SUPPLY_TECHNOLOGY_LIPO,
.voltage_max_design = 4200000,
.voltage_min_design = 3600000,
},
};
/* GPIO Key: power */
static struct gpio_keys_button qi_lb60_gpio_keys_buttons[] = {
[0] = {
.code = KEY_POWER,
.gpio = JZ_GPIO_PORTD(29),
.active_low = 1,
.desc = "Power",
.wakeup = 1,
},
};
static struct gpio_keys_platform_data qi_lb60_gpio_keys_data = {
.nbuttons = ARRAY_SIZE(qi_lb60_gpio_keys_buttons),
.buttons = qi_lb60_gpio_keys_buttons,
};
static struct platform_device qi_lb60_gpio_keys = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &qi_lb60_gpio_keys_data,
}
};
static struct jz4740_mmc_platform_data qi_lb60_mmc_pdata = {
.gpio_card_detect = QI_LB60_GPIO_SD_CD,
.gpio_read_only = -1,
.gpio_power = QI_LB60_GPIO_SD_VCC_EN_N,
.power_active_low = 1,
};
/* OHCI */
static struct regulator_consumer_supply avt2_usb_regulator_consumer =
REGULATOR_SUPPLY("vbus", "jz4740-ohci");
static struct regulator_init_data avt2_usb_regulator_init_data = {
.num_consumer_supplies = 1,
.consumer_supplies = &avt2_usb_regulator_consumer,
.constraints = {
.name = "USB power",
.min_uV = 5000000,
.max_uV = 5000000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
};
static struct fixed_voltage_config avt2_usb_regulator_data = {
.supply_name = "USB power",
.microvolts = 5000000,
.gpio = JZ_GPIO_PORTB(17),
.init_data = &avt2_usb_regulator_init_data,
};
static struct platform_device avt2_usb_regulator_device = {
.name = "reg-fixed-voltage",
.id = -1,
.dev = {
.platform_data = &avt2_usb_regulator_data,
}
};
/* beeper */
static struct platform_device qi_lb60_pwm_beeper = {
.name = "pwm-beeper",
.id = -1,
.dev = {
.platform_data = (void *)4,
},
};
/* charger */
static char *qi_lb60_batteries[] = {
"battery",
};
static struct gpio_charger_platform_data qi_lb60_charger_pdata = {
.name = "usb",
.type = POWER_SUPPLY_TYPE_USB,
.gpio = JZ_GPIO_PORTD(28),
.gpio_active_low = 1,
.supplied_to = qi_lb60_batteries,
.num_supplicants = ARRAY_SIZE(qi_lb60_batteries),
};
static struct platform_device qi_lb60_charger_device = {
.name = "gpio-charger",
.dev = {
.platform_data = &qi_lb60_charger_pdata,
},
};
/* audio */
static struct platform_device qi_lb60_audio_device = {
.name = "qi-lb60-audio",
.id = -1,
};
static struct platform_device *jz_platform_devices[] __initdata = {
&jz4740_udc_device,
&jz4740_mmc_device,
&jz4740_nand_device,
&qi_lb60_keypad,
&spigpio_device,
&jz4740_framebuffer_device,
&jz4740_pcm_device,
&jz4740_i2s_device,
&jz4740_codec_device,
&jz4740_rtc_device,
&jz4740_adc_device,
&jz4740_pwm_device,
&qi_lb60_gpio_keys,
&qi_lb60_pwm_beeper,
&qi_lb60_charger_device,
&qi_lb60_audio_device,
};
static void __init board_gpio_setup(void)
{
/* We only need to enable/disable pullup here for pins used in generic
* drivers. Everything else is done by the drivers themselves. */
jz_gpio_disable_pullup(QI_LB60_GPIO_SD_VCC_EN_N);
jz_gpio_disable_pullup(QI_LB60_GPIO_SD_CD);
}
static int __init qi_lb60_init_platform_devices(void)
{
jz4740_framebuffer_device.dev.platform_data = &qi_lb60_fb_pdata;
jz4740_nand_device.dev.platform_data = &qi_lb60_nand_pdata;
jz4740_adc_device.dev.platform_data = &qi_lb60_battery_pdata;
jz4740_mmc_device.dev.platform_data = &qi_lb60_mmc_pdata;
jz4740_serial_device_register();
spi_register_board_info(qi_lb60_spi_board_info,
ARRAY_SIZE(qi_lb60_spi_board_info));
if (is_avt2) {
platform_device_register(&avt2_usb_regulator_device);
platform_device_register(&jz4740_usb_ohci_device);
}
return platform_add_devices(jz_platform_devices,
ARRAY_SIZE(jz_platform_devices));
}
struct jz4740_clock_board_data jz4740_clock_bdata = {
.ext_rate = 12000000,
.rtc_rate = 32768,
};
static __init int board_avt2(char *str)
{
qi_lb60_mmc_pdata.card_detect_active_low = 1;
is_avt2 = true;
return 1;
}
__setup("avt2", board_avt2);
static int __init qi_lb60_board_setup(void)
{
printk(KERN_INFO "Qi Hardware JZ4740 QI %s setup\n",
is_avt2 ? "AVT2" : "LB60");
board_gpio_setup();
if (qi_lb60_init_platform_devices())
panic("Failed to initialize platform devices");
return 0;
}
arch_initcall(qi_lb60_board_setup);
| gpl-2.0 |
alexax66/KitKat_kernel_fortunave3g | drivers/crypto/mv_cesa.c | 2244 | 29710 | /*
* Support for Marvell's crypto engine which can be found on some Orion5X
* boards.
*
* Author: Sebastian Andrzej Siewior < sebastian at breakpoint dot cc >
* License: GPLv2
*
*/
#include <crypto/aes.h>
#include <crypto/algapi.h>
#include <linux/crypto.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kthread.h>
#include <linux/platform_device.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/clk.h>
#include <crypto/internal/hash.h>
#include <crypto/sha.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/of_irq.h>
#include "mv_cesa.h"
#define MV_CESA "MV-CESA:"
#define MAX_HW_HASH_SIZE 0xFFFF
#define MV_CESA_EXPIRE 500 /* msec */
/*
* STM:
* /---------------------------------------\
* | | request complete
* \./ |
* IDLE -> new request -> BUSY -> done -> DEQUEUE
* /°\ |
* | | more scatter entries
* \________________/
*/
enum engine_status {
ENGINE_IDLE,
ENGINE_BUSY,
ENGINE_W_DEQUEUE,
};
/**
* struct req_progress - used for every crypt request
* @src_sg_it: sg iterator for src
* @dst_sg_it: sg iterator for dst
* @sg_src_left: bytes left in src to process (scatter list)
* @src_start: offset to add to src start position (scatter list)
* @crypt_len: length of current hw crypt/hash process
* @hw_nbytes: total bytes to process in hw for this request
* @copy_back: whether to copy data back (crypt) or not (hash)
* @sg_dst_left: bytes left dst to process in this scatter list
* @dst_start: offset to add to dst start position (scatter list)
* @hw_processed_bytes: number of bytes processed by hw (request).
*
* sg helper are used to iterate over the scatterlist. Since the size of the
* SRAM may be less than the scatter size, this struct struct is used to keep
* track of progress within current scatterlist.
*/
struct req_progress {
struct sg_mapping_iter src_sg_it;
struct sg_mapping_iter dst_sg_it;
void (*complete) (void);
void (*process) (int is_first);
/* src mostly */
int sg_src_left;
int src_start;
int crypt_len;
int hw_nbytes;
/* dst mostly */
int copy_back;
int sg_dst_left;
int dst_start;
int hw_processed_bytes;
};
struct crypto_priv {
void __iomem *reg;
void __iomem *sram;
int irq;
struct clk *clk;
struct task_struct *queue_th;
/* the lock protects queue and eng_st */
spinlock_t lock;
struct crypto_queue queue;
enum engine_status eng_st;
struct timer_list completion_timer;
struct crypto_async_request *cur_req;
struct req_progress p;
int max_req_size;
int sram_size;
int has_sha1;
int has_hmac_sha1;
};
static struct crypto_priv *cpg;
struct mv_ctx {
u8 aes_enc_key[AES_KEY_LEN];
u32 aes_dec_key[8];
int key_len;
u32 need_calc_aes_dkey;
};
enum crypto_op {
COP_AES_ECB,
COP_AES_CBC,
};
struct mv_req_ctx {
enum crypto_op op;
int decrypt;
};
enum hash_op {
COP_SHA1,
COP_HMAC_SHA1
};
struct mv_tfm_hash_ctx {
struct crypto_shash *fallback;
struct crypto_shash *base_hash;
u32 ivs[2 * SHA1_DIGEST_SIZE / 4];
int count_add;
enum hash_op op;
};
struct mv_req_hash_ctx {
u64 count;
u32 state[SHA1_DIGEST_SIZE / 4];
u8 buffer[SHA1_BLOCK_SIZE];
int first_hash; /* marks that we don't have previous state */
int last_chunk; /* marks that this is the 'final' request */
int extra_bytes; /* unprocessed bytes in buffer */
enum hash_op op;
int count_add;
};
static void mv_completion_timer_callback(unsigned long unused)
{
int active = readl(cpg->reg + SEC_ACCEL_CMD) & SEC_CMD_EN_SEC_ACCL0;
printk(KERN_ERR MV_CESA
"completion timer expired (CESA %sactive), cleaning up.\n",
active ? "" : "in");
del_timer(&cpg->completion_timer);
writel(SEC_CMD_DISABLE_SEC, cpg->reg + SEC_ACCEL_CMD);
while(readl(cpg->reg + SEC_ACCEL_CMD) & SEC_CMD_DISABLE_SEC)
printk(KERN_INFO MV_CESA "%s: waiting for engine finishing\n", __func__);
cpg->eng_st = ENGINE_W_DEQUEUE;
wake_up_process(cpg->queue_th);
}
static void mv_setup_timer(void)
{
setup_timer(&cpg->completion_timer, &mv_completion_timer_callback, 0);
mod_timer(&cpg->completion_timer,
jiffies + msecs_to_jiffies(MV_CESA_EXPIRE));
}
static void compute_aes_dec_key(struct mv_ctx *ctx)
{
struct crypto_aes_ctx gen_aes_key;
int key_pos;
if (!ctx->need_calc_aes_dkey)
return;
crypto_aes_expand_key(&gen_aes_key, ctx->aes_enc_key, ctx->key_len);
key_pos = ctx->key_len + 24;
memcpy(ctx->aes_dec_key, &gen_aes_key.key_enc[key_pos], 4 * 4);
switch (ctx->key_len) {
case AES_KEYSIZE_256:
key_pos -= 2;
/* fall */
case AES_KEYSIZE_192:
key_pos -= 2;
memcpy(&ctx->aes_dec_key[4], &gen_aes_key.key_enc[key_pos],
4 * 4);
break;
}
ctx->need_calc_aes_dkey = 0;
}
static int mv_setkey_aes(struct crypto_ablkcipher *cipher, const u8 *key,
unsigned int len)
{
struct crypto_tfm *tfm = crypto_ablkcipher_tfm(cipher);
struct mv_ctx *ctx = crypto_tfm_ctx(tfm);
switch (len) {
case AES_KEYSIZE_128:
case AES_KEYSIZE_192:
case AES_KEYSIZE_256:
break;
default:
crypto_ablkcipher_set_flags(cipher, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
ctx->key_len = len;
ctx->need_calc_aes_dkey = 1;
memcpy(ctx->aes_enc_key, key, AES_KEY_LEN);
return 0;
}
static void copy_src_to_buf(struct req_progress *p, char *dbuf, int len)
{
int ret;
void *sbuf;
int copy_len;
while (len) {
if (!p->sg_src_left) {
ret = sg_miter_next(&p->src_sg_it);
BUG_ON(!ret);
p->sg_src_left = p->src_sg_it.length;
p->src_start = 0;
}
sbuf = p->src_sg_it.addr + p->src_start;
copy_len = min(p->sg_src_left, len);
memcpy(dbuf, sbuf, copy_len);
p->src_start += copy_len;
p->sg_src_left -= copy_len;
len -= copy_len;
dbuf += copy_len;
}
}
static void setup_data_in(void)
{
struct req_progress *p = &cpg->p;
int data_in_sram =
min(p->hw_nbytes - p->hw_processed_bytes, cpg->max_req_size);
copy_src_to_buf(p, cpg->sram + SRAM_DATA_IN_START + p->crypt_len,
data_in_sram - p->crypt_len);
p->crypt_len = data_in_sram;
}
static void mv_process_current_q(int first_block)
{
struct ablkcipher_request *req = ablkcipher_request_cast(cpg->cur_req);
struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
struct sec_accel_config op;
switch (req_ctx->op) {
case COP_AES_ECB:
op.config = CFG_OP_CRYPT_ONLY | CFG_ENCM_AES | CFG_ENC_MODE_ECB;
break;
case COP_AES_CBC:
default:
op.config = CFG_OP_CRYPT_ONLY | CFG_ENCM_AES | CFG_ENC_MODE_CBC;
op.enc_iv = ENC_IV_POINT(SRAM_DATA_IV) |
ENC_IV_BUF_POINT(SRAM_DATA_IV_BUF);
if (first_block)
memcpy(cpg->sram + SRAM_DATA_IV, req->info, 16);
break;
}
if (req_ctx->decrypt) {
op.config |= CFG_DIR_DEC;
memcpy(cpg->sram + SRAM_DATA_KEY_P, ctx->aes_dec_key,
AES_KEY_LEN);
} else {
op.config |= CFG_DIR_ENC;
memcpy(cpg->sram + SRAM_DATA_KEY_P, ctx->aes_enc_key,
AES_KEY_LEN);
}
switch (ctx->key_len) {
case AES_KEYSIZE_128:
op.config |= CFG_AES_LEN_128;
break;
case AES_KEYSIZE_192:
op.config |= CFG_AES_LEN_192;
break;
case AES_KEYSIZE_256:
op.config |= CFG_AES_LEN_256;
break;
}
op.enc_p = ENC_P_SRC(SRAM_DATA_IN_START) |
ENC_P_DST(SRAM_DATA_OUT_START);
op.enc_key_p = SRAM_DATA_KEY_P;
setup_data_in();
op.enc_len = cpg->p.crypt_len;
memcpy(cpg->sram + SRAM_CONFIG, &op,
sizeof(struct sec_accel_config));
/* GO */
mv_setup_timer();
writel(SEC_CMD_EN_SEC_ACCL0, cpg->reg + SEC_ACCEL_CMD);
}
static void mv_crypto_algo_completion(void)
{
struct ablkcipher_request *req = ablkcipher_request_cast(cpg->cur_req);
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
sg_miter_stop(&cpg->p.src_sg_it);
sg_miter_stop(&cpg->p.dst_sg_it);
if (req_ctx->op != COP_AES_CBC)
return ;
memcpy(req->info, cpg->sram + SRAM_DATA_IV_BUF, 16);
}
static void mv_process_hash_current(int first_block)
{
struct ahash_request *req = ahash_request_cast(cpg->cur_req);
const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_hash_ctx *req_ctx = ahash_request_ctx(req);
struct req_progress *p = &cpg->p;
struct sec_accel_config op = { 0 };
int is_last;
switch (req_ctx->op) {
case COP_SHA1:
default:
op.config = CFG_OP_MAC_ONLY | CFG_MACM_SHA1;
break;
case COP_HMAC_SHA1:
op.config = CFG_OP_MAC_ONLY | CFG_MACM_HMAC_SHA1;
memcpy(cpg->sram + SRAM_HMAC_IV_IN,
tfm_ctx->ivs, sizeof(tfm_ctx->ivs));
break;
}
op.mac_src_p =
MAC_SRC_DATA_P(SRAM_DATA_IN_START) | MAC_SRC_TOTAL_LEN((u32)
req_ctx->
count);
setup_data_in();
op.mac_digest =
MAC_DIGEST_P(SRAM_DIGEST_BUF) | MAC_FRAG_LEN(p->crypt_len);
op.mac_iv =
MAC_INNER_IV_P(SRAM_HMAC_IV_IN) |
MAC_OUTER_IV_P(SRAM_HMAC_IV_OUT);
is_last = req_ctx->last_chunk
&& (p->hw_processed_bytes + p->crypt_len >= p->hw_nbytes)
&& (req_ctx->count <= MAX_HW_HASH_SIZE);
if (req_ctx->first_hash) {
if (is_last)
op.config |= CFG_NOT_FRAG;
else
op.config |= CFG_FIRST_FRAG;
req_ctx->first_hash = 0;
} else {
if (is_last)
op.config |= CFG_LAST_FRAG;
else
op.config |= CFG_MID_FRAG;
if (first_block) {
writel(req_ctx->state[0], cpg->reg + DIGEST_INITIAL_VAL_A);
writel(req_ctx->state[1], cpg->reg + DIGEST_INITIAL_VAL_B);
writel(req_ctx->state[2], cpg->reg + DIGEST_INITIAL_VAL_C);
writel(req_ctx->state[3], cpg->reg + DIGEST_INITIAL_VAL_D);
writel(req_ctx->state[4], cpg->reg + DIGEST_INITIAL_VAL_E);
}
}
memcpy(cpg->sram + SRAM_CONFIG, &op, sizeof(struct sec_accel_config));
/* GO */
mv_setup_timer();
writel(SEC_CMD_EN_SEC_ACCL0, cpg->reg + SEC_ACCEL_CMD);
}
static inline int mv_hash_import_sha1_ctx(const struct mv_req_hash_ctx *ctx,
struct shash_desc *desc)
{
int i;
struct sha1_state shash_state;
shash_state.count = ctx->count + ctx->count_add;
for (i = 0; i < 5; i++)
shash_state.state[i] = ctx->state[i];
memcpy(shash_state.buffer, ctx->buffer, sizeof(shash_state.buffer));
return crypto_shash_import(desc, &shash_state);
}
static int mv_hash_final_fallback(struct ahash_request *req)
{
const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_hash_ctx *req_ctx = ahash_request_ctx(req);
struct {
struct shash_desc shash;
char ctx[crypto_shash_descsize(tfm_ctx->fallback)];
} desc;
int rc;
desc.shash.tfm = tfm_ctx->fallback;
desc.shash.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
if (unlikely(req_ctx->first_hash)) {
crypto_shash_init(&desc.shash);
crypto_shash_update(&desc.shash, req_ctx->buffer,
req_ctx->extra_bytes);
} else {
/* only SHA1 for now....
*/
rc = mv_hash_import_sha1_ctx(req_ctx, &desc.shash);
if (rc)
goto out;
}
rc = crypto_shash_final(&desc.shash, req->result);
out:
return rc;
}
static void mv_save_digest_state(struct mv_req_hash_ctx *ctx)
{
ctx->state[0] = readl(cpg->reg + DIGEST_INITIAL_VAL_A);
ctx->state[1] = readl(cpg->reg + DIGEST_INITIAL_VAL_B);
ctx->state[2] = readl(cpg->reg + DIGEST_INITIAL_VAL_C);
ctx->state[3] = readl(cpg->reg + DIGEST_INITIAL_VAL_D);
ctx->state[4] = readl(cpg->reg + DIGEST_INITIAL_VAL_E);
}
static void mv_hash_algo_completion(void)
{
struct ahash_request *req = ahash_request_cast(cpg->cur_req);
struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);
if (ctx->extra_bytes)
copy_src_to_buf(&cpg->p, ctx->buffer, ctx->extra_bytes);
sg_miter_stop(&cpg->p.src_sg_it);
if (likely(ctx->last_chunk)) {
if (likely(ctx->count <= MAX_HW_HASH_SIZE)) {
memcpy(req->result, cpg->sram + SRAM_DIGEST_BUF,
crypto_ahash_digestsize(crypto_ahash_reqtfm
(req)));
} else {
mv_save_digest_state(ctx);
mv_hash_final_fallback(req);
}
} else {
mv_save_digest_state(ctx);
}
}
static void dequeue_complete_req(void)
{
struct crypto_async_request *req = cpg->cur_req;
void *buf;
int ret;
cpg->p.hw_processed_bytes += cpg->p.crypt_len;
if (cpg->p.copy_back) {
int need_copy_len = cpg->p.crypt_len;
int sram_offset = 0;
do {
int dst_copy;
if (!cpg->p.sg_dst_left) {
ret = sg_miter_next(&cpg->p.dst_sg_it);
BUG_ON(!ret);
cpg->p.sg_dst_left = cpg->p.dst_sg_it.length;
cpg->p.dst_start = 0;
}
buf = cpg->p.dst_sg_it.addr;
buf += cpg->p.dst_start;
dst_copy = min(need_copy_len, cpg->p.sg_dst_left);
memcpy(buf,
cpg->sram + SRAM_DATA_OUT_START + sram_offset,
dst_copy);
sram_offset += dst_copy;
cpg->p.sg_dst_left -= dst_copy;
need_copy_len -= dst_copy;
cpg->p.dst_start += dst_copy;
} while (need_copy_len > 0);
}
cpg->p.crypt_len = 0;
BUG_ON(cpg->eng_st != ENGINE_W_DEQUEUE);
if (cpg->p.hw_processed_bytes < cpg->p.hw_nbytes) {
/* process next scatter list entry */
cpg->eng_st = ENGINE_BUSY;
cpg->p.process(0);
} else {
cpg->p.complete();
cpg->eng_st = ENGINE_IDLE;
local_bh_disable();
req->complete(req, 0);
local_bh_enable();
}
}
static int count_sgs(struct scatterlist *sl, unsigned int total_bytes)
{
int i = 0;
size_t cur_len;
while (sl) {
cur_len = sl[i].length;
++i;
if (total_bytes > cur_len)
total_bytes -= cur_len;
else
break;
}
return i;
}
static void mv_start_new_crypt_req(struct ablkcipher_request *req)
{
struct req_progress *p = &cpg->p;
int num_sgs;
cpg->cur_req = &req->base;
memset(p, 0, sizeof(struct req_progress));
p->hw_nbytes = req->nbytes;
p->complete = mv_crypto_algo_completion;
p->process = mv_process_current_q;
p->copy_back = 1;
num_sgs = count_sgs(req->src, req->nbytes);
sg_miter_start(&p->src_sg_it, req->src, num_sgs, SG_MITER_FROM_SG);
num_sgs = count_sgs(req->dst, req->nbytes);
sg_miter_start(&p->dst_sg_it, req->dst, num_sgs, SG_MITER_TO_SG);
mv_process_current_q(1);
}
static void mv_start_new_hash_req(struct ahash_request *req)
{
struct req_progress *p = &cpg->p;
struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);
int num_sgs, hw_bytes, old_extra_bytes, rc;
cpg->cur_req = &req->base;
memset(p, 0, sizeof(struct req_progress));
hw_bytes = req->nbytes + ctx->extra_bytes;
old_extra_bytes = ctx->extra_bytes;
ctx->extra_bytes = hw_bytes % SHA1_BLOCK_SIZE;
if (ctx->extra_bytes != 0
&& (!ctx->last_chunk || ctx->count > MAX_HW_HASH_SIZE))
hw_bytes -= ctx->extra_bytes;
else
ctx->extra_bytes = 0;
num_sgs = count_sgs(req->src, req->nbytes);
sg_miter_start(&p->src_sg_it, req->src, num_sgs, SG_MITER_FROM_SG);
if (hw_bytes) {
p->hw_nbytes = hw_bytes;
p->complete = mv_hash_algo_completion;
p->process = mv_process_hash_current;
if (unlikely(old_extra_bytes)) {
memcpy(cpg->sram + SRAM_DATA_IN_START, ctx->buffer,
old_extra_bytes);
p->crypt_len = old_extra_bytes;
}
mv_process_hash_current(1);
} else {
copy_src_to_buf(p, ctx->buffer + old_extra_bytes,
ctx->extra_bytes - old_extra_bytes);
sg_miter_stop(&p->src_sg_it);
if (ctx->last_chunk)
rc = mv_hash_final_fallback(req);
else
rc = 0;
cpg->eng_st = ENGINE_IDLE;
local_bh_disable();
req->base.complete(&req->base, rc);
local_bh_enable();
}
}
static int queue_manag(void *data)
{
cpg->eng_st = ENGINE_IDLE;
do {
struct crypto_async_request *async_req = NULL;
struct crypto_async_request *backlog;
__set_current_state(TASK_INTERRUPTIBLE);
if (cpg->eng_st == ENGINE_W_DEQUEUE)
dequeue_complete_req();
spin_lock_irq(&cpg->lock);
if (cpg->eng_st == ENGINE_IDLE) {
backlog = crypto_get_backlog(&cpg->queue);
async_req = crypto_dequeue_request(&cpg->queue);
if (async_req) {
BUG_ON(cpg->eng_st != ENGINE_IDLE);
cpg->eng_st = ENGINE_BUSY;
}
}
spin_unlock_irq(&cpg->lock);
if (backlog) {
backlog->complete(backlog, -EINPROGRESS);
backlog = NULL;
}
if (async_req) {
if (async_req->tfm->__crt_alg->cra_type !=
&crypto_ahash_type) {
struct ablkcipher_request *req =
ablkcipher_request_cast(async_req);
mv_start_new_crypt_req(req);
} else {
struct ahash_request *req =
ahash_request_cast(async_req);
mv_start_new_hash_req(req);
}
async_req = NULL;
}
schedule();
} while (!kthread_should_stop());
return 0;
}
static int mv_handle_req(struct crypto_async_request *req)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&cpg->lock, flags);
ret = crypto_enqueue_request(&cpg->queue, req);
spin_unlock_irqrestore(&cpg->lock, flags);
wake_up_process(cpg->queue_th);
return ret;
}
static int mv_enc_aes_ecb(struct ablkcipher_request *req)
{
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
req_ctx->op = COP_AES_ECB;
req_ctx->decrypt = 0;
return mv_handle_req(&req->base);
}
static int mv_dec_aes_ecb(struct ablkcipher_request *req)
{
struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
req_ctx->op = COP_AES_ECB;
req_ctx->decrypt = 1;
compute_aes_dec_key(ctx);
return mv_handle_req(&req->base);
}
static int mv_enc_aes_cbc(struct ablkcipher_request *req)
{
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
req_ctx->op = COP_AES_CBC;
req_ctx->decrypt = 0;
return mv_handle_req(&req->base);
}
static int mv_dec_aes_cbc(struct ablkcipher_request *req)
{
struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
req_ctx->op = COP_AES_CBC;
req_ctx->decrypt = 1;
compute_aes_dec_key(ctx);
return mv_handle_req(&req->base);
}
static int mv_cra_init(struct crypto_tfm *tfm)
{
tfm->crt_ablkcipher.reqsize = sizeof(struct mv_req_ctx);
return 0;
}
static void mv_init_hash_req_ctx(struct mv_req_hash_ctx *ctx, int op,
int is_last, unsigned int req_len,
int count_add)
{
memset(ctx, 0, sizeof(*ctx));
ctx->op = op;
ctx->count = req_len;
ctx->first_hash = 1;
ctx->last_chunk = is_last;
ctx->count_add = count_add;
}
static void mv_update_hash_req_ctx(struct mv_req_hash_ctx *ctx, int is_last,
unsigned req_len)
{
ctx->last_chunk = is_last;
ctx->count += req_len;
}
static int mv_hash_init(struct ahash_request *req)
{
const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
mv_init_hash_req_ctx(ahash_request_ctx(req), tfm_ctx->op, 0, 0,
tfm_ctx->count_add);
return 0;
}
static int mv_hash_update(struct ahash_request *req)
{
if (!req->nbytes)
return 0;
mv_update_hash_req_ctx(ahash_request_ctx(req), 0, req->nbytes);
return mv_handle_req(&req->base);
}
static int mv_hash_final(struct ahash_request *req)
{
struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);
ahash_request_set_crypt(req, NULL, req->result, 0);
mv_update_hash_req_ctx(ctx, 1, 0);
return mv_handle_req(&req->base);
}
static int mv_hash_finup(struct ahash_request *req)
{
mv_update_hash_req_ctx(ahash_request_ctx(req), 1, req->nbytes);
return mv_handle_req(&req->base);
}
static int mv_hash_digest(struct ahash_request *req)
{
const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
mv_init_hash_req_ctx(ahash_request_ctx(req), tfm_ctx->op, 1,
req->nbytes, tfm_ctx->count_add);
return mv_handle_req(&req->base);
}
static void mv_hash_init_ivs(struct mv_tfm_hash_ctx *ctx, const void *istate,
const void *ostate)
{
const struct sha1_state *isha1_state = istate, *osha1_state = ostate;
int i;
for (i = 0; i < 5; i++) {
ctx->ivs[i] = cpu_to_be32(isha1_state->state[i]);
ctx->ivs[i + 5] = cpu_to_be32(osha1_state->state[i]);
}
}
static int mv_hash_setkey(struct crypto_ahash *tfm, const u8 * key,
unsigned int keylen)
{
int rc;
struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(&tfm->base);
int bs, ds, ss;
if (!ctx->base_hash)
return 0;
rc = crypto_shash_setkey(ctx->fallback, key, keylen);
if (rc)
return rc;
/* Can't see a way to extract the ipad/opad from the fallback tfm
so I'm basically copying code from the hmac module */
bs = crypto_shash_blocksize(ctx->base_hash);
ds = crypto_shash_digestsize(ctx->base_hash);
ss = crypto_shash_statesize(ctx->base_hash);
{
struct {
struct shash_desc shash;
char ctx[crypto_shash_descsize(ctx->base_hash)];
} desc;
unsigned int i;
char ipad[ss];
char opad[ss];
desc.shash.tfm = ctx->base_hash;
desc.shash.flags = crypto_shash_get_flags(ctx->base_hash) &
CRYPTO_TFM_REQ_MAY_SLEEP;
if (keylen > bs) {
int err;
err =
crypto_shash_digest(&desc.shash, key, keylen, ipad);
if (err)
return err;
keylen = ds;
} else
memcpy(ipad, key, keylen);
memset(ipad + keylen, 0, bs - keylen);
memcpy(opad, ipad, bs);
for (i = 0; i < bs; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
rc = crypto_shash_init(&desc.shash) ? :
crypto_shash_update(&desc.shash, ipad, bs) ? :
crypto_shash_export(&desc.shash, ipad) ? :
crypto_shash_init(&desc.shash) ? :
crypto_shash_update(&desc.shash, opad, bs) ? :
crypto_shash_export(&desc.shash, opad);
if (rc == 0)
mv_hash_init_ivs(ctx, ipad, opad);
return rc;
}
}
static int mv_cra_hash_init(struct crypto_tfm *tfm, const char *base_hash_name,
enum hash_op op, int count_add)
{
const char *fallback_driver_name = tfm->__crt_alg->cra_name;
struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_shash *fallback_tfm = NULL;
struct crypto_shash *base_hash = NULL;
int err = -ENOMEM;
ctx->op = op;
ctx->count_add = count_add;
/* Allocate a fallback and abort if it failed. */
fallback_tfm = crypto_alloc_shash(fallback_driver_name, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(fallback_tfm)) {
printk(KERN_WARNING MV_CESA
"Fallback driver '%s' could not be loaded!\n",
fallback_driver_name);
err = PTR_ERR(fallback_tfm);
goto out;
}
ctx->fallback = fallback_tfm;
if (base_hash_name) {
/* Allocate a hash to compute the ipad/opad of hmac. */
base_hash = crypto_alloc_shash(base_hash_name, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(base_hash)) {
printk(KERN_WARNING MV_CESA
"Base driver '%s' could not be loaded!\n",
base_hash_name);
err = PTR_ERR(base_hash);
goto err_bad_base;
}
}
ctx->base_hash = base_hash;
crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
sizeof(struct mv_req_hash_ctx) +
crypto_shash_descsize(ctx->fallback));
return 0;
err_bad_base:
crypto_free_shash(fallback_tfm);
out:
return err;
}
static void mv_cra_hash_exit(struct crypto_tfm *tfm)
{
struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_shash(ctx->fallback);
if (ctx->base_hash)
crypto_free_shash(ctx->base_hash);
}
static int mv_cra_hash_sha1_init(struct crypto_tfm *tfm)
{
return mv_cra_hash_init(tfm, NULL, COP_SHA1, 0);
}
static int mv_cra_hash_hmac_sha1_init(struct crypto_tfm *tfm)
{
return mv_cra_hash_init(tfm, "sha1", COP_HMAC_SHA1, SHA1_BLOCK_SIZE);
}
irqreturn_t crypto_int(int irq, void *priv)
{
u32 val;
val = readl(cpg->reg + SEC_ACCEL_INT_STATUS);
if (!(val & SEC_INT_ACCEL0_DONE))
return IRQ_NONE;
if (!del_timer(&cpg->completion_timer)) {
printk(KERN_WARNING MV_CESA
"got an interrupt but no pending timer?\n");
}
val &= ~SEC_INT_ACCEL0_DONE;
writel(val, cpg->reg + FPGA_INT_STATUS);
writel(val, cpg->reg + SEC_ACCEL_INT_STATUS);
BUG_ON(cpg->eng_st != ENGINE_BUSY);
cpg->eng_st = ENGINE_W_DEQUEUE;
wake_up_process(cpg->queue_th);
return IRQ_HANDLED;
}
struct crypto_alg mv_aes_alg_ecb = {
.cra_name = "ecb(aes)",
.cra_driver_name = "mv-ecb-aes",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC,
.cra_blocksize = 16,
.cra_ctxsize = sizeof(struct mv_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = mv_cra_init,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = mv_setkey_aes,
.encrypt = mv_enc_aes_ecb,
.decrypt = mv_dec_aes_ecb,
},
},
};
struct crypto_alg mv_aes_alg_cbc = {
.cra_name = "cbc(aes)",
.cra_driver_name = "mv-cbc-aes",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct mv_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = mv_cra_init,
.cra_u = {
.ablkcipher = {
.ivsize = AES_BLOCK_SIZE,
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = mv_setkey_aes,
.encrypt = mv_enc_aes_cbc,
.decrypt = mv_dec_aes_cbc,
},
},
};
struct ahash_alg mv_sha1_alg = {
.init = mv_hash_init,
.update = mv_hash_update,
.final = mv_hash_final,
.finup = mv_hash_finup,
.digest = mv_hash_digest,
.halg = {
.digestsize = SHA1_DIGEST_SIZE,
.base = {
.cra_name = "sha1",
.cra_driver_name = "mv-sha1",
.cra_priority = 300,
.cra_flags =
CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct mv_tfm_hash_ctx),
.cra_init = mv_cra_hash_sha1_init,
.cra_exit = mv_cra_hash_exit,
.cra_module = THIS_MODULE,
}
}
};
struct ahash_alg mv_hmac_sha1_alg = {
.init = mv_hash_init,
.update = mv_hash_update,
.final = mv_hash_final,
.finup = mv_hash_finup,
.digest = mv_hash_digest,
.setkey = mv_hash_setkey,
.halg = {
.digestsize = SHA1_DIGEST_SIZE,
.base = {
.cra_name = "hmac(sha1)",
.cra_driver_name = "mv-hmac-sha1",
.cra_priority = 300,
.cra_flags =
CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct mv_tfm_hash_ctx),
.cra_init = mv_cra_hash_hmac_sha1_init,
.cra_exit = mv_cra_hash_exit,
.cra_module = THIS_MODULE,
}
}
};
static int mv_probe(struct platform_device *pdev)
{
struct crypto_priv *cp;
struct resource *res;
int irq;
int ret;
if (cpg) {
printk(KERN_ERR MV_CESA "Second crypto dev?\n");
return -EEXIST;
}
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "regs");
if (!res)
return -ENXIO;
cp = kzalloc(sizeof(*cp), GFP_KERNEL);
if (!cp)
return -ENOMEM;
spin_lock_init(&cp->lock);
crypto_init_queue(&cp->queue, 50);
cp->reg = ioremap(res->start, resource_size(res));
if (!cp->reg) {
ret = -ENOMEM;
goto err;
}
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "sram");
if (!res) {
ret = -ENXIO;
goto err_unmap_reg;
}
cp->sram_size = resource_size(res);
cp->max_req_size = cp->sram_size - SRAM_CFG_SPACE;
cp->sram = ioremap(res->start, cp->sram_size);
if (!cp->sram) {
ret = -ENOMEM;
goto err_unmap_reg;
}
if (pdev->dev.of_node)
irq = irq_of_parse_and_map(pdev->dev.of_node, 0);
else
irq = platform_get_irq(pdev, 0);
if (irq < 0 || irq == NO_IRQ) {
ret = irq;
goto err_unmap_sram;
}
cp->irq = irq;
platform_set_drvdata(pdev, cp);
cpg = cp;
cp->queue_th = kthread_run(queue_manag, cp, "mv_crypto");
if (IS_ERR(cp->queue_th)) {
ret = PTR_ERR(cp->queue_th);
goto err_unmap_sram;
}
ret = request_irq(irq, crypto_int, IRQF_DISABLED, dev_name(&pdev->dev),
cp);
if (ret)
goto err_thread;
/* Not all platforms can gate the clock, so it is not
an error if the clock does not exists. */
cp->clk = clk_get(&pdev->dev, NULL);
if (!IS_ERR(cp->clk))
clk_prepare_enable(cp->clk);
writel(0, cpg->reg + SEC_ACCEL_INT_STATUS);
writel(SEC_INT_ACCEL0_DONE, cpg->reg + SEC_ACCEL_INT_MASK);
writel(SEC_CFG_STOP_DIG_ERR, cpg->reg + SEC_ACCEL_CFG);
writel(SRAM_CONFIG, cpg->reg + SEC_ACCEL_DESC_P0);
ret = crypto_register_alg(&mv_aes_alg_ecb);
if (ret) {
printk(KERN_WARNING MV_CESA
"Could not register aes-ecb driver\n");
goto err_irq;
}
ret = crypto_register_alg(&mv_aes_alg_cbc);
if (ret) {
printk(KERN_WARNING MV_CESA
"Could not register aes-cbc driver\n");
goto err_unreg_ecb;
}
ret = crypto_register_ahash(&mv_sha1_alg);
if (ret == 0)
cpg->has_sha1 = 1;
else
printk(KERN_WARNING MV_CESA "Could not register sha1 driver\n");
ret = crypto_register_ahash(&mv_hmac_sha1_alg);
if (ret == 0) {
cpg->has_hmac_sha1 = 1;
} else {
printk(KERN_WARNING MV_CESA
"Could not register hmac-sha1 driver\n");
}
return 0;
err_unreg_ecb:
crypto_unregister_alg(&mv_aes_alg_ecb);
err_irq:
free_irq(irq, cp);
if (!IS_ERR(cp->clk)) {
clk_disable_unprepare(cp->clk);
clk_put(cp->clk);
}
err_thread:
kthread_stop(cp->queue_th);
err_unmap_sram:
iounmap(cp->sram);
err_unmap_reg:
iounmap(cp->reg);
err:
kfree(cp);
cpg = NULL;
platform_set_drvdata(pdev, NULL);
return ret;
}
static int mv_remove(struct platform_device *pdev)
{
struct crypto_priv *cp = platform_get_drvdata(pdev);
crypto_unregister_alg(&mv_aes_alg_ecb);
crypto_unregister_alg(&mv_aes_alg_cbc);
if (cp->has_sha1)
crypto_unregister_ahash(&mv_sha1_alg);
if (cp->has_hmac_sha1)
crypto_unregister_ahash(&mv_hmac_sha1_alg);
kthread_stop(cp->queue_th);
free_irq(cp->irq, cp);
memset(cp->sram, 0, cp->sram_size);
iounmap(cp->sram);
iounmap(cp->reg);
if (!IS_ERR(cp->clk)) {
clk_disable_unprepare(cp->clk);
clk_put(cp->clk);
}
kfree(cp);
cpg = NULL;
return 0;
}
static const struct of_device_id mv_cesa_of_match_table[] = {
{ .compatible = "marvell,orion-crypto", },
{}
};
MODULE_DEVICE_TABLE(of, mv_cesa_of_match_table);
static struct platform_driver marvell_crypto = {
.probe = mv_probe,
.remove = mv_remove,
.driver = {
.owner = THIS_MODULE,
.name = "mv_crypto",
.of_match_table = of_match_ptr(mv_cesa_of_match_table),
},
};
MODULE_ALIAS("platform:mv_crypto");
module_platform_driver(marvell_crypto);
MODULE_AUTHOR("Sebastian Andrzej Siewior <sebastian@breakpoint.cc>");
MODULE_DESCRIPTION("Support for Marvell's cryptographic engine");
MODULE_LICENSE("GPL");
| gpl-2.0 |
bju2000/kernel_lge_msm8994 | drivers/s390/cio/qdio_setup.c | 2244 | 14648 | /*
* qdio queue initialization
*
* Copyright IBM Corp. 2008
* Author(s): Jan Glauber <jang@linux.vnet.ibm.com>
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <asm/qdio.h>
#include "cio.h"
#include "css.h"
#include "device.h"
#include "ioasm.h"
#include "chsc.h"
#include "qdio.h"
#include "qdio_debug.h"
static struct kmem_cache *qdio_q_cache;
static struct kmem_cache *qdio_aob_cache;
struct qaob *qdio_allocate_aob(void)
{
return kmem_cache_zalloc(qdio_aob_cache, GFP_ATOMIC);
}
EXPORT_SYMBOL_GPL(qdio_allocate_aob);
void qdio_release_aob(struct qaob *aob)
{
kmem_cache_free(qdio_aob_cache, aob);
}
EXPORT_SYMBOL_GPL(qdio_release_aob);
/*
* qebsm is only available under 64bit but the adapter sets the feature
* flag anyway, so we manually override it.
*/
static inline int qebsm_possible(void)
{
#ifdef CONFIG_64BIT
return css_general_characteristics.qebsm;
#endif
return 0;
}
/*
* qib_param_field: pointer to 128 bytes or NULL, if no param field
* nr_input_qs: pointer to nr_queues*128 words of data or NULL
*/
static void set_impl_params(struct qdio_irq *irq_ptr,
unsigned int qib_param_field_format,
unsigned char *qib_param_field,
unsigned long *input_slib_elements,
unsigned long *output_slib_elements)
{
struct qdio_q *q;
int i, j;
if (!irq_ptr)
return;
irq_ptr->qib.pfmt = qib_param_field_format;
if (qib_param_field)
memcpy(irq_ptr->qib.parm, qib_param_field,
QDIO_MAX_BUFFERS_PER_Q);
if (!input_slib_elements)
goto output;
for_each_input_queue(irq_ptr, q, i) {
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; j++)
q->slib->slibe[j].parms =
input_slib_elements[i * QDIO_MAX_BUFFERS_PER_Q + j];
}
output:
if (!output_slib_elements)
return;
for_each_output_queue(irq_ptr, q, i) {
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; j++)
q->slib->slibe[j].parms =
output_slib_elements[i * QDIO_MAX_BUFFERS_PER_Q + j];
}
}
static int __qdio_allocate_qs(struct qdio_q **irq_ptr_qs, int nr_queues)
{
struct qdio_q *q;
int i;
for (i = 0; i < nr_queues; i++) {
q = kmem_cache_alloc(qdio_q_cache, GFP_KERNEL);
if (!q)
return -ENOMEM;
q->slib = (struct slib *) __get_free_page(GFP_KERNEL);
if (!q->slib) {
kmem_cache_free(qdio_q_cache, q);
return -ENOMEM;
}
irq_ptr_qs[i] = q;
}
return 0;
}
int qdio_allocate_qs(struct qdio_irq *irq_ptr, int nr_input_qs, int nr_output_qs)
{
int rc;
rc = __qdio_allocate_qs(irq_ptr->input_qs, nr_input_qs);
if (rc)
return rc;
rc = __qdio_allocate_qs(irq_ptr->output_qs, nr_output_qs);
return rc;
}
static void setup_queues_misc(struct qdio_q *q, struct qdio_irq *irq_ptr,
qdio_handler_t *handler, int i)
{
struct slib *slib = q->slib;
/* queue must be cleared for qdio_establish */
memset(q, 0, sizeof(*q));
memset(slib, 0, PAGE_SIZE);
q->slib = slib;
q->irq_ptr = irq_ptr;
q->mask = 1 << (31 - i);
q->nr = i;
q->handler = handler;
}
static void setup_storage_lists(struct qdio_q *q, struct qdio_irq *irq_ptr,
void **sbals_array, int i)
{
struct qdio_q *prev;
int j;
DBF_HEX(&q, sizeof(void *));
q->sl = (struct sl *)((char *)q->slib + PAGE_SIZE / 2);
/* fill in sbal */
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; j++)
q->sbal[j] = *sbals_array++;
/* fill in slib */
if (i > 0) {
prev = (q->is_input_q) ? irq_ptr->input_qs[i - 1]
: irq_ptr->output_qs[i - 1];
prev->slib->nsliba = (unsigned long)q->slib;
}
q->slib->sla = (unsigned long)q->sl;
q->slib->slsba = (unsigned long)&q->slsb.val[0];
/* fill in sl */
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; j++)
q->sl->element[j].sbal = (unsigned long)q->sbal[j];
}
static void setup_queues(struct qdio_irq *irq_ptr,
struct qdio_initialize *qdio_init)
{
struct qdio_q *q;
void **input_sbal_array = qdio_init->input_sbal_addr_array;
void **output_sbal_array = qdio_init->output_sbal_addr_array;
struct qdio_outbuf_state *output_sbal_state_array =
qdio_init->output_sbal_state_array;
int i;
for_each_input_queue(irq_ptr, q, i) {
DBF_EVENT("inq:%1d", i);
setup_queues_misc(q, irq_ptr, qdio_init->input_handler, i);
q->is_input_q = 1;
q->u.in.queue_start_poll = qdio_init->queue_start_poll_array ?
qdio_init->queue_start_poll_array[i] : NULL;
setup_storage_lists(q, irq_ptr, input_sbal_array, i);
input_sbal_array += QDIO_MAX_BUFFERS_PER_Q;
if (is_thinint_irq(irq_ptr)) {
tasklet_init(&q->tasklet, tiqdio_inbound_processing,
(unsigned long) q);
} else {
tasklet_init(&q->tasklet, qdio_inbound_processing,
(unsigned long) q);
}
}
for_each_output_queue(irq_ptr, q, i) {
DBF_EVENT("outq:%1d", i);
setup_queues_misc(q, irq_ptr, qdio_init->output_handler, i);
q->u.out.sbal_state = output_sbal_state_array;
output_sbal_state_array += QDIO_MAX_BUFFERS_PER_Q;
q->is_input_q = 0;
q->u.out.scan_threshold = qdio_init->scan_threshold;
setup_storage_lists(q, irq_ptr, output_sbal_array, i);
output_sbal_array += QDIO_MAX_BUFFERS_PER_Q;
tasklet_init(&q->tasklet, qdio_outbound_processing,
(unsigned long) q);
setup_timer(&q->u.out.timer, (void(*)(unsigned long))
&qdio_outbound_timer, (unsigned long)q);
}
}
static void process_ac_flags(struct qdio_irq *irq_ptr, unsigned char qdioac)
{
if (qdioac & AC1_SIGA_INPUT_NEEDED)
irq_ptr->siga_flag.input = 1;
if (qdioac & AC1_SIGA_OUTPUT_NEEDED)
irq_ptr->siga_flag.output = 1;
if (qdioac & AC1_SIGA_SYNC_NEEDED)
irq_ptr->siga_flag.sync = 1;
if (!(qdioac & AC1_AUTOMATIC_SYNC_ON_THININT))
irq_ptr->siga_flag.sync_after_ai = 1;
if (!(qdioac & AC1_AUTOMATIC_SYNC_ON_OUT_PCI))
irq_ptr->siga_flag.sync_out_after_pci = 1;
}
static void check_and_setup_qebsm(struct qdio_irq *irq_ptr,
unsigned char qdioac, unsigned long token)
{
if (!(irq_ptr->qib.rflags & QIB_RFLAGS_ENABLE_QEBSM))
goto no_qebsm;
if (!(qdioac & AC1_SC_QEBSM_AVAILABLE) ||
(!(qdioac & AC1_SC_QEBSM_ENABLED)))
goto no_qebsm;
irq_ptr->sch_token = token;
DBF_EVENT("V=V:1");
DBF_EVENT("%8lx", irq_ptr->sch_token);
return;
no_qebsm:
irq_ptr->sch_token = 0;
irq_ptr->qib.rflags &= ~QIB_RFLAGS_ENABLE_QEBSM;
DBF_EVENT("noV=V");
}
/*
* If there is a qdio_irq we use the chsc_page and store the information
* in the qdio_irq, otherwise we copy it to the specified structure.
*/
int qdio_setup_get_ssqd(struct qdio_irq *irq_ptr,
struct subchannel_id *schid,
struct qdio_ssqd_desc *data)
{
struct chsc_ssqd_area *ssqd;
int rc;
DBF_EVENT("getssqd:%4x", schid->sch_no);
if (irq_ptr != NULL)
ssqd = (struct chsc_ssqd_area *)irq_ptr->chsc_page;
else
ssqd = (struct chsc_ssqd_area *)__get_free_page(GFP_KERNEL);
memset(ssqd, 0, PAGE_SIZE);
ssqd->request = (struct chsc_header) {
.length = 0x0010,
.code = 0x0024,
};
ssqd->first_sch = schid->sch_no;
ssqd->last_sch = schid->sch_no;
ssqd->ssid = schid->ssid;
if (chsc(ssqd))
return -EIO;
rc = chsc_error_from_response(ssqd->response.code);
if (rc)
return rc;
if (!(ssqd->qdio_ssqd.flags & CHSC_FLAG_QDIO_CAPABILITY) ||
!(ssqd->qdio_ssqd.flags & CHSC_FLAG_VALIDITY) ||
(ssqd->qdio_ssqd.sch != schid->sch_no))
return -EINVAL;
if (irq_ptr != NULL)
memcpy(&irq_ptr->ssqd_desc, &ssqd->qdio_ssqd,
sizeof(struct qdio_ssqd_desc));
else {
memcpy(data, &ssqd->qdio_ssqd,
sizeof(struct qdio_ssqd_desc));
free_page((unsigned long)ssqd);
}
return 0;
}
void qdio_setup_ssqd_info(struct qdio_irq *irq_ptr)
{
unsigned char qdioac;
int rc;
rc = qdio_setup_get_ssqd(irq_ptr, &irq_ptr->schid, NULL);
if (rc) {
DBF_ERROR("%4x ssqd ERR", irq_ptr->schid.sch_no);
DBF_ERROR("rc:%x", rc);
/* all flags set, worst case */
qdioac = AC1_SIGA_INPUT_NEEDED | AC1_SIGA_OUTPUT_NEEDED |
AC1_SIGA_SYNC_NEEDED;
} else
qdioac = irq_ptr->ssqd_desc.qdioac1;
check_and_setup_qebsm(irq_ptr, qdioac, irq_ptr->ssqd_desc.sch_token);
process_ac_flags(irq_ptr, qdioac);
DBF_EVENT("ac 1:%2x 2:%4x", qdioac, irq_ptr->ssqd_desc.qdioac2);
DBF_EVENT("3:%4x qib:%4x", irq_ptr->ssqd_desc.qdioac3, irq_ptr->qib.ac);
}
void qdio_release_memory(struct qdio_irq *irq_ptr)
{
struct qdio_q *q;
int i;
/*
* Must check queue array manually since irq_ptr->nr_input_queues /
* irq_ptr->nr_input_queues may not yet be set.
*/
for (i = 0; i < QDIO_MAX_QUEUES_PER_IRQ; i++) {
q = irq_ptr->input_qs[i];
if (q) {
free_page((unsigned long) q->slib);
kmem_cache_free(qdio_q_cache, q);
}
}
for (i = 0; i < QDIO_MAX_QUEUES_PER_IRQ; i++) {
q = irq_ptr->output_qs[i];
if (q) {
if (q->u.out.use_cq) {
int n;
for (n = 0; n < QDIO_MAX_BUFFERS_PER_Q; ++n) {
struct qaob *aob = q->u.out.aobs[n];
if (aob) {
qdio_release_aob(aob);
q->u.out.aobs[n] = NULL;
}
}
qdio_disable_async_operation(&q->u.out);
}
free_page((unsigned long) q->slib);
kmem_cache_free(qdio_q_cache, q);
}
}
free_page((unsigned long) irq_ptr->qdr);
free_page(irq_ptr->chsc_page);
free_page((unsigned long) irq_ptr);
}
static void __qdio_allocate_fill_qdr(struct qdio_irq *irq_ptr,
struct qdio_q **irq_ptr_qs,
int i, int nr)
{
irq_ptr->qdr->qdf0[i + nr].sliba =
(unsigned long)irq_ptr_qs[i]->slib;
irq_ptr->qdr->qdf0[i + nr].sla =
(unsigned long)irq_ptr_qs[i]->sl;
irq_ptr->qdr->qdf0[i + nr].slsba =
(unsigned long)&irq_ptr_qs[i]->slsb.val[0];
irq_ptr->qdr->qdf0[i + nr].akey = PAGE_DEFAULT_KEY >> 4;
irq_ptr->qdr->qdf0[i + nr].bkey = PAGE_DEFAULT_KEY >> 4;
irq_ptr->qdr->qdf0[i + nr].ckey = PAGE_DEFAULT_KEY >> 4;
irq_ptr->qdr->qdf0[i + nr].dkey = PAGE_DEFAULT_KEY >> 4;
}
static void setup_qdr(struct qdio_irq *irq_ptr,
struct qdio_initialize *qdio_init)
{
int i;
irq_ptr->qdr->qfmt = qdio_init->q_format;
irq_ptr->qdr->ac = qdio_init->qdr_ac;
irq_ptr->qdr->iqdcnt = qdio_init->no_input_qs;
irq_ptr->qdr->oqdcnt = qdio_init->no_output_qs;
irq_ptr->qdr->iqdsz = sizeof(struct qdesfmt0) / 4; /* size in words */
irq_ptr->qdr->oqdsz = sizeof(struct qdesfmt0) / 4;
irq_ptr->qdr->qiba = (unsigned long)&irq_ptr->qib;
irq_ptr->qdr->qkey = PAGE_DEFAULT_KEY >> 4;
for (i = 0; i < qdio_init->no_input_qs; i++)
__qdio_allocate_fill_qdr(irq_ptr, irq_ptr->input_qs, i, 0);
for (i = 0; i < qdio_init->no_output_qs; i++)
__qdio_allocate_fill_qdr(irq_ptr, irq_ptr->output_qs, i,
qdio_init->no_input_qs);
}
static void setup_qib(struct qdio_irq *irq_ptr,
struct qdio_initialize *init_data)
{
if (qebsm_possible())
irq_ptr->qib.rflags |= QIB_RFLAGS_ENABLE_QEBSM;
irq_ptr->qib.rflags |= init_data->qib_rflags;
irq_ptr->qib.qfmt = init_data->q_format;
if (init_data->no_input_qs)
irq_ptr->qib.isliba =
(unsigned long)(irq_ptr->input_qs[0]->slib);
if (init_data->no_output_qs)
irq_ptr->qib.osliba =
(unsigned long)(irq_ptr->output_qs[0]->slib);
memcpy(irq_ptr->qib.ebcnam, init_data->adapter_name, 8);
}
int qdio_setup_irq(struct qdio_initialize *init_data)
{
struct ciw *ciw;
struct qdio_irq *irq_ptr = init_data->cdev->private->qdio_data;
int rc;
memset(&irq_ptr->qib, 0, sizeof(irq_ptr->qib));
memset(&irq_ptr->siga_flag, 0, sizeof(irq_ptr->siga_flag));
memset(&irq_ptr->ccw, 0, sizeof(irq_ptr->ccw));
memset(&irq_ptr->ssqd_desc, 0, sizeof(irq_ptr->ssqd_desc));
memset(&irq_ptr->perf_stat, 0, sizeof(irq_ptr->perf_stat));
irq_ptr->debugfs_dev = irq_ptr->debugfs_perf = NULL;
irq_ptr->sch_token = irq_ptr->state = irq_ptr->perf_stat_enabled = 0;
/* wipes qib.ac, required by ar7063 */
memset(irq_ptr->qdr, 0, sizeof(struct qdr));
irq_ptr->int_parm = init_data->int_parm;
irq_ptr->nr_input_qs = init_data->no_input_qs;
irq_ptr->nr_output_qs = init_data->no_output_qs;
irq_ptr->cdev = init_data->cdev;
ccw_device_get_schid(irq_ptr->cdev, &irq_ptr->schid);
setup_queues(irq_ptr, init_data);
setup_qib(irq_ptr, init_data);
qdio_setup_thinint(irq_ptr);
set_impl_params(irq_ptr, init_data->qib_param_field_format,
init_data->qib_param_field,
init_data->input_slib_elements,
init_data->output_slib_elements);
/* fill input and output descriptors */
setup_qdr(irq_ptr, init_data);
/* qdr, qib, sls, slsbs, slibs, sbales are filled now */
/* get qdio commands */
ciw = ccw_device_get_ciw(init_data->cdev, CIW_TYPE_EQUEUE);
if (!ciw) {
DBF_ERROR("%4x NO EQ", irq_ptr->schid.sch_no);
rc = -EINVAL;
goto out_err;
}
irq_ptr->equeue = *ciw;
ciw = ccw_device_get_ciw(init_data->cdev, CIW_TYPE_AQUEUE);
if (!ciw) {
DBF_ERROR("%4x NO AQ", irq_ptr->schid.sch_no);
rc = -EINVAL;
goto out_err;
}
irq_ptr->aqueue = *ciw;
/* set new interrupt handler */
irq_ptr->orig_handler = init_data->cdev->handler;
init_data->cdev->handler = qdio_int_handler;
return 0;
out_err:
qdio_release_memory(irq_ptr);
return rc;
}
void qdio_print_subchannel_info(struct qdio_irq *irq_ptr,
struct ccw_device *cdev)
{
char s[80];
snprintf(s, 80, "qdio: %s %s on SC %x using "
"AI:%d QEBSM:%d PRI:%d TDD:%d SIGA:%s%s%s%s%s\n",
dev_name(&cdev->dev),
(irq_ptr->qib.qfmt == QDIO_QETH_QFMT) ? "OSA" :
((irq_ptr->qib.qfmt == QDIO_ZFCP_QFMT) ? "ZFCP" : "HS"),
irq_ptr->schid.sch_no,
is_thinint_irq(irq_ptr),
(irq_ptr->sch_token) ? 1 : 0,
(irq_ptr->qib.ac & QIB_AC_OUTBOUND_PCI_SUPPORTED) ? 1 : 0,
css_general_characteristics.aif_tdd,
(irq_ptr->siga_flag.input) ? "R" : " ",
(irq_ptr->siga_flag.output) ? "W" : " ",
(irq_ptr->siga_flag.sync) ? "S" : " ",
(irq_ptr->siga_flag.sync_after_ai) ? "A" : " ",
(irq_ptr->siga_flag.sync_out_after_pci) ? "P" : " ");
printk(KERN_INFO "%s", s);
}
int qdio_enable_async_operation(struct qdio_output_q *outq)
{
outq->aobs = kzalloc(sizeof(struct qaob *) * QDIO_MAX_BUFFERS_PER_Q,
GFP_ATOMIC);
if (!outq->aobs) {
outq->use_cq = 0;
return -ENOMEM;
}
outq->use_cq = 1;
return 0;
}
void qdio_disable_async_operation(struct qdio_output_q *q)
{
kfree(q->aobs);
q->aobs = NULL;
q->use_cq = 0;
}
int __init qdio_setup_init(void)
{
int rc;
qdio_q_cache = kmem_cache_create("qdio_q", sizeof(struct qdio_q),
256, 0, NULL);
if (!qdio_q_cache)
return -ENOMEM;
qdio_aob_cache = kmem_cache_create("qdio_aob",
sizeof(struct qaob),
sizeof(struct qaob),
0,
NULL);
if (!qdio_aob_cache) {
rc = -ENOMEM;
goto free_qdio_q_cache;
}
/* Check for OSA/FCP thin interrupts (bit 67). */
DBF_EVENT("thinint:%1d",
(css_general_characteristics.aif_osa) ? 1 : 0);
/* Check for QEBSM support in general (bit 58). */
DBF_EVENT("cssQEBSM:%1d", (qebsm_possible()) ? 1 : 0);
rc = 0;
out:
return rc;
free_qdio_q_cache:
kmem_cache_destroy(qdio_q_cache);
goto out;
}
void qdio_setup_exit(void)
{
kmem_cache_destroy(qdio_aob_cache);
kmem_cache_destroy(qdio_q_cache);
}
| gpl-2.0 |
coinlake/xperia-tipo-kernel | drivers/ata/ahci_platform.c | 3012 | 4712 | /*
* AHCI SATA platform driver
*
* Copyright 2004-2005 Red Hat, Inc.
* Jeff Garzik <jgarzik@pobox.com>
* Copyright 2010 MontaVista Software, LLC.
* Anton Vorontsov <avorontsov@ru.mvista.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*/
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/libata.h>
#include <linux/ahci_platform.h>
#include "ahci.h"
static struct scsi_host_template ahci_platform_sht = {
AHCI_SHT("ahci_platform"),
};
static int __init ahci_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct ahci_platform_data *pdata = dev->platform_data;
struct ata_port_info pi = {
.flags = AHCI_FLAG_COMMON,
.pio_mask = ATA_PIO4,
.udma_mask = ATA_UDMA6,
.port_ops = &ahci_ops,
};
const struct ata_port_info *ppi[] = { &pi, NULL };
struct ahci_host_priv *hpriv;
struct ata_host *host;
struct resource *mem;
int irq;
int n_ports;
int i;
int rc;
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(dev, "no mmio space\n");
return -EINVAL;
}
irq = platform_get_irq(pdev, 0);
if (irq <= 0) {
dev_err(dev, "no irq\n");
return -EINVAL;
}
if (pdata && pdata->ata_port_info)
pi = *pdata->ata_port_info;
hpriv = devm_kzalloc(dev, sizeof(*hpriv), GFP_KERNEL);
if (!hpriv) {
dev_err(dev, "can't alloc ahci_host_priv\n");
return -ENOMEM;
}
hpriv->flags |= (unsigned long)pi.private_data;
hpriv->mmio = devm_ioremap(dev, mem->start, resource_size(mem));
if (!hpriv->mmio) {
dev_err(dev, "can't map %pR\n", mem);
return -ENOMEM;
}
/*
* Some platforms might need to prepare for mmio region access,
* which could be done in the following init call. So, the mmio
* region shouldn't be accessed before init (if provided) has
* returned successfully.
*/
if (pdata && pdata->init) {
rc = pdata->init(dev, hpriv->mmio);
if (rc)
return rc;
}
ahci_save_initial_config(dev, hpriv,
pdata ? pdata->force_port_map : 0,
pdata ? pdata->mask_port_map : 0);
/* prepare host */
if (hpriv->cap & HOST_CAP_NCQ)
pi.flags |= ATA_FLAG_NCQ;
if (hpriv->cap & HOST_CAP_PMP)
pi.flags |= ATA_FLAG_PMP;
ahci_set_em_messages(hpriv, &pi);
/* CAP.NP sometimes indicate the index of the last enabled
* port, at other times, that of the last possible port, so
* determining the maximum port number requires looking at
* both CAP.NP and port_map.
*/
n_ports = max(ahci_nr_ports(hpriv->cap), fls(hpriv->port_map));
host = ata_host_alloc_pinfo(dev, ppi, n_ports);
if (!host) {
rc = -ENOMEM;
goto err0;
}
host->private_data = hpriv;
if (!(hpriv->cap & HOST_CAP_SSS) || ahci_ignore_sss)
host->flags |= ATA_HOST_PARALLEL_SCAN;
else
printk(KERN_INFO "ahci: SSS flag set, parallel bus scan disabled\n");
if (pi.flags & ATA_FLAG_EM)
ahci_reset_em(host);
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
ata_port_desc(ap, "mmio %pR", mem);
ata_port_desc(ap, "port 0x%x", 0x100 + ap->port_no * 0x80);
/* set enclosure management message type */
if (ap->flags & ATA_FLAG_EM)
ap->em_message_type = hpriv->em_msg_type;
/* disabled/not-implemented port */
if (!(hpriv->port_map & (1 << i)))
ap->ops = &ata_dummy_port_ops;
}
rc = ahci_reset_controller(host);
if (rc)
goto err0;
ahci_init_controller(host);
ahci_print_info(host, "platform");
rc = ata_host_activate(host, irq, ahci_interrupt, IRQF_SHARED,
&ahci_platform_sht);
if (rc)
goto err0;
return 0;
err0:
if (pdata && pdata->exit)
pdata->exit(dev);
return rc;
}
static int __devexit ahci_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct ahci_platform_data *pdata = dev->platform_data;
struct ata_host *host = dev_get_drvdata(dev);
ata_host_detach(host);
if (pdata && pdata->exit)
pdata->exit(dev);
return 0;
}
static struct platform_driver ahci_driver = {
.remove = __devexit_p(ahci_remove),
.driver = {
.name = "ahci",
.owner = THIS_MODULE,
},
};
static int __init ahci_init(void)
{
return platform_driver_probe(&ahci_driver, ahci_probe);
}
module_init(ahci_init);
static void __exit ahci_exit(void)
{
platform_driver_unregister(&ahci_driver);
}
module_exit(ahci_exit);
MODULE_DESCRIPTION("AHCI SATA platform driver");
MODULE_AUTHOR("Anton Vorontsov <avorontsov@ru.mvista.com>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:ahci");
| gpl-2.0 |
talexop/talexop_kernel_i9505_4_4_2 | kernel/sched/cpupri.c | 3780 | 6844 | /*
* kernel/sched/cpupri.c
*
* CPU priority management
*
* Copyright (C) 2007-2008 Novell
*
* Author: Gregory Haskins <ghaskins@novell.com>
*
* This code tracks the priority of each CPU so that global migration
* decisions are easy to calculate. Each CPU can be in a state as follows:
*
* (INVALID), IDLE, NORMAL, RT1, ... RT99
*
* going from the lowest priority to the highest. CPUs in the INVALID state
* are not eligible for routing. The system maintains this state with
* a 2 dimensional bitmap (the first for priority class, the second for cpus
* in that class). Therefore a typical application without affinity
* restrictions can find a suitable CPU with O(1) complexity (e.g. two bit
* searches). For tasks with affinity restrictions, the algorithm has a
* worst case complexity of O(min(102, nr_domcpus)), though the scenario that
* yields the worst case search is fairly contrived.
*
* 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/gfp.h>
#include "cpupri.h"
/* Convert between a 140 based task->prio, and our 102 based cpupri */
static int convert_prio(int prio)
{
int cpupri;
if (prio == CPUPRI_INVALID)
cpupri = CPUPRI_INVALID;
else if (prio == MAX_PRIO)
cpupri = CPUPRI_IDLE;
else if (prio >= MAX_RT_PRIO)
cpupri = CPUPRI_NORMAL;
else
cpupri = MAX_RT_PRIO - prio + 1;
return cpupri;
}
/**
* cpupri_find - find the best (lowest-pri) CPU in the system
* @cp: The cpupri context
* @p: The task
* @lowest_mask: A mask to fill in with selected CPUs (or NULL)
*
* Note: This function returns the recommended CPUs as calculated during the
* current invocation. By the time the call returns, the CPUs may have in
* fact changed priorities any number of times. While not ideal, it is not
* an issue of correctness since the normal rebalancer logic will correct
* any discrepancies created by racing against the uncertainty of the current
* priority configuration.
*
* Returns: (int)bool - CPUs were found
*/
int cpupri_find(struct cpupri *cp, struct task_struct *p,
struct cpumask *lowest_mask)
{
int idx = 0;
int task_pri = convert_prio(p->prio);
if (task_pri >= MAX_RT_PRIO)
return 0;
for (idx = 0; idx < task_pri; idx++) {
struct cpupri_vec *vec = &cp->pri_to_cpu[idx];
int skip = 0;
if (!atomic_read(&(vec)->count))
skip = 1;
/*
* When looking at the vector, we need to read the counter,
* do a memory barrier, then read the mask.
*
* Note: This is still all racey, but we can deal with it.
* Ideally, we only want to look at masks that are set.
*
* If a mask is not set, then the only thing wrong is that we
* did a little more work than necessary.
*
* If we read a zero count but the mask is set, because of the
* memory barriers, that can only happen when the highest prio
* task for a run queue has left the run queue, in which case,
* it will be followed by a pull. If the task we are processing
* fails to find a proper place to go, that pull request will
* pull this task if the run queue is running at a lower
* priority.
*/
smp_rmb();
/* Need to do the rmb for every iteration */
if (skip)
continue;
if (cpumask_any_and(&p->cpus_allowed, vec->mask) >= nr_cpu_ids)
continue;
if (lowest_mask) {
cpumask_and(lowest_mask, &p->cpus_allowed, vec->mask);
/*
* We have to ensure that we have at least one bit
* still set in the array, since the map could have
* been concurrently emptied between the first and
* second reads of vec->mask. If we hit this
* condition, simply act as though we never hit this
* priority level and continue on.
*/
if (cpumask_any(lowest_mask) >= nr_cpu_ids)
continue;
}
return 1;
}
return 0;
}
/**
* cpupri_set - update the cpu priority setting
* @cp: The cpupri context
* @cpu: The target cpu
* @newpri: The priority (INVALID-RT99) to assign to this CPU
*
* Note: Assumes cpu_rq(cpu)->lock is locked
*
* Returns: (void)
*/
void cpupri_set(struct cpupri *cp, int cpu, int newpri)
{
int *currpri = &cp->cpu_to_pri[cpu];
int oldpri = *currpri;
int do_mb = 0;
newpri = convert_prio(newpri);
BUG_ON(newpri >= CPUPRI_NR_PRIORITIES);
if (newpri == oldpri)
return;
/*
* If the cpu was currently mapped to a different value, we
* need to map it to the new value then remove the old value.
* Note, we must add the new value first, otherwise we risk the
* cpu being missed by the priority loop in cpupri_find.
*/
if (likely(newpri != CPUPRI_INVALID)) {
struct cpupri_vec *vec = &cp->pri_to_cpu[newpri];
cpumask_set_cpu(cpu, vec->mask);
/*
* When adding a new vector, we update the mask first,
* do a write memory barrier, and then update the count, to
* make sure the vector is visible when count is set.
*/
smp_mb__before_atomic_inc();
atomic_inc(&(vec)->count);
do_mb = 1;
}
if (likely(oldpri != CPUPRI_INVALID)) {
struct cpupri_vec *vec = &cp->pri_to_cpu[oldpri];
/*
* Because the order of modification of the vec->count
* is important, we must make sure that the update
* of the new prio is seen before we decrement the
* old prio. This makes sure that the loop sees
* one or the other when we raise the priority of
* the run queue. We don't care about when we lower the
* priority, as that will trigger an rt pull anyway.
*
* We only need to do a memory barrier if we updated
* the new priority vec.
*/
if (do_mb)
smp_mb__after_atomic_inc();
/*
* When removing from the vector, we decrement the counter first
* do a memory barrier and then clear the mask.
*/
atomic_dec(&(vec)->count);
smp_mb__after_atomic_inc();
cpumask_clear_cpu(cpu, vec->mask);
}
*currpri = newpri;
}
/**
* cpupri_init - initialize the cpupri structure
* @cp: The cpupri context
*
* Returns: -ENOMEM if memory fails.
*/
int cpupri_init(struct cpupri *cp)
{
int i;
memset(cp, 0, sizeof(*cp));
for (i = 0; i < CPUPRI_NR_PRIORITIES; i++) {
struct cpupri_vec *vec = &cp->pri_to_cpu[i];
atomic_set(&vec->count, 0);
if (!zalloc_cpumask_var(&vec->mask, GFP_KERNEL))
goto cleanup;
}
for_each_possible_cpu(i)
cp->cpu_to_pri[i] = CPUPRI_INVALID;
return 0;
cleanup:
for (i--; i >= 0; i--)
free_cpumask_var(cp->pri_to_cpu[i].mask);
return -ENOMEM;
}
/**
* cpupri_cleanup - clean up the cpupri structure
* @cp: The cpupri context
*/
void cpupri_cleanup(struct cpupri *cp)
{
int i;
for (i = 0; i < CPUPRI_NR_PRIORITIES; i++)
free_cpumask_var(cp->pri_to_cpu[i].mask);
}
| gpl-2.0 |
CardinalTesting/kernel_lge_msm8974 | net/netfilter/nf_conntrack_h323_main.c | 4036 | 53239 | /*
* H.323 connection tracking helper
*
* Copyright (c) 2006 Jing Min Zhao <zhaojingmin@users.sourceforge.net>
*
* This source code is licensed under General Public License version 2.
*
* Based on the 'brute force' H.323 connection tracking module by
* Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* For more information, please see http://nath323.sourceforge.net/
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/ctype.h>
#include <linux/inet.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/slab.h>
#include <linux/udp.h>
#include <linux/tcp.h>
#include <linux/skbuff.h>
#include <net/route.h>
#include <net/ip6_route.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/nf_conntrack_tuple.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <net/netfilter/nf_conntrack_ecache.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_zones.h>
#include <linux/netfilter/nf_conntrack_h323.h>
/* Parameters */
static unsigned int default_rrq_ttl __read_mostly = 300;
module_param(default_rrq_ttl, uint, 0600);
MODULE_PARM_DESC(default_rrq_ttl, "use this TTL if it's missing in RRQ");
static int gkrouted_only __read_mostly = 1;
module_param(gkrouted_only, int, 0600);
MODULE_PARM_DESC(gkrouted_only, "only accept calls from gatekeeper");
static bool callforward_filter __read_mostly = true;
module_param(callforward_filter, bool, 0600);
MODULE_PARM_DESC(callforward_filter, "only create call forwarding expectations "
"if both endpoints are on different sides "
"(determined by routing information)");
/* Hooks for NAT */
int (*set_h245_addr_hook) (struct sk_buff *skb,
unsigned char **data, int dataoff,
H245_TransportAddress *taddr,
union nf_inet_addr *addr, __be16 port)
__read_mostly;
int (*set_h225_addr_hook) (struct sk_buff *skb,
unsigned char **data, int dataoff,
TransportAddress *taddr,
union nf_inet_addr *addr, __be16 port)
__read_mostly;
int (*set_sig_addr_hook) (struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data,
TransportAddress *taddr, int count) __read_mostly;
int (*set_ras_addr_hook) (struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data,
TransportAddress *taddr, int count) __read_mostly;
int (*nat_rtp_rtcp_hook) (struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
H245_TransportAddress *taddr,
__be16 port, __be16 rtp_port,
struct nf_conntrack_expect *rtp_exp,
struct nf_conntrack_expect *rtcp_exp) __read_mostly;
int (*nat_t120_hook) (struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
H245_TransportAddress *taddr, __be16 port,
struct nf_conntrack_expect *exp) __read_mostly;
int (*nat_h245_hook) (struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
TransportAddress *taddr, __be16 port,
struct nf_conntrack_expect *exp) __read_mostly;
int (*nat_callforwarding_hook) (struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
TransportAddress *taddr, __be16 port,
struct nf_conntrack_expect *exp) __read_mostly;
int (*nat_q931_hook) (struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, TransportAddress *taddr, int idx,
__be16 port, struct nf_conntrack_expect *exp)
__read_mostly;
static DEFINE_SPINLOCK(nf_h323_lock);
static char *h323_buffer;
static struct nf_conntrack_helper nf_conntrack_helper_h245;
static struct nf_conntrack_helper nf_conntrack_helper_q931[];
static struct nf_conntrack_helper nf_conntrack_helper_ras[];
/****************************************************************************/
static int get_tpkt_data(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct, enum ip_conntrack_info ctinfo,
unsigned char **data, int *datalen, int *dataoff)
{
struct nf_ct_h323_master *info = &nfct_help(ct)->help.ct_h323_info;
int dir = CTINFO2DIR(ctinfo);
const struct tcphdr *th;
struct tcphdr _tcph;
int tcpdatalen;
int tcpdataoff;
unsigned char *tpkt;
int tpktlen;
int tpktoff;
/* Get TCP header */
th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
if (th == NULL)
return 0;
/* Get TCP data offset */
tcpdataoff = protoff + th->doff * 4;
/* Get TCP data length */
tcpdatalen = skb->len - tcpdataoff;
if (tcpdatalen <= 0) /* No TCP data */
goto clear_out;
if (*data == NULL) { /* first TPKT */
/* Get first TPKT pointer */
tpkt = skb_header_pointer(skb, tcpdataoff, tcpdatalen,
h323_buffer);
BUG_ON(tpkt == NULL);
/* Validate TPKT identifier */
if (tcpdatalen < 4 || tpkt[0] != 0x03 || tpkt[1] != 0) {
/* Netmeeting sends TPKT header and data separately */
if (info->tpkt_len[dir] > 0) {
pr_debug("nf_ct_h323: previous packet "
"indicated separate TPKT data of %hu "
"bytes\n", info->tpkt_len[dir]);
if (info->tpkt_len[dir] <= tcpdatalen) {
/* Yes, there was a TPKT header
* received */
*data = tpkt;
*datalen = info->tpkt_len[dir];
*dataoff = 0;
goto out;
}
/* Fragmented TPKT */
pr_debug("nf_ct_h323: fragmented TPKT\n");
goto clear_out;
}
/* It is not even a TPKT */
return 0;
}
tpktoff = 0;
} else { /* Next TPKT */
tpktoff = *dataoff + *datalen;
tcpdatalen -= tpktoff;
if (tcpdatalen <= 4) /* No more TPKT */
goto clear_out;
tpkt = *data + *datalen;
/* Validate TPKT identifier */
if (tpkt[0] != 0x03 || tpkt[1] != 0)
goto clear_out;
}
/* Validate TPKT length */
tpktlen = tpkt[2] * 256 + tpkt[3];
if (tpktlen < 4)
goto clear_out;
if (tpktlen > tcpdatalen) {
if (tcpdatalen == 4) { /* Separate TPKT header */
/* Netmeeting sends TPKT header and data separately */
pr_debug("nf_ct_h323: separate TPKT header indicates "
"there will be TPKT data of %hu bytes\n",
tpktlen - 4);
info->tpkt_len[dir] = tpktlen - 4;
return 0;
}
pr_debug("nf_ct_h323: incomplete TPKT (fragmented?)\n");
goto clear_out;
}
/* This is the encapsulated data */
*data = tpkt + 4;
*datalen = tpktlen - 4;
*dataoff = tpktoff + 4;
out:
/* Clear TPKT length */
info->tpkt_len[dir] = 0;
return 1;
clear_out:
info->tpkt_len[dir] = 0;
return 0;
}
/****************************************************************************/
static int get_h245_addr(struct nf_conn *ct, const unsigned char *data,
H245_TransportAddress *taddr,
union nf_inet_addr *addr, __be16 *port)
{
const unsigned char *p;
int len;
if (taddr->choice != eH245_TransportAddress_unicastAddress)
return 0;
switch (taddr->unicastAddress.choice) {
case eUnicastAddress_iPAddress:
if (nf_ct_l3num(ct) != AF_INET)
return 0;
p = data + taddr->unicastAddress.iPAddress.network;
len = 4;
break;
case eUnicastAddress_iP6Address:
if (nf_ct_l3num(ct) != AF_INET6)
return 0;
p = data + taddr->unicastAddress.iP6Address.network;
len = 16;
break;
default:
return 0;
}
memcpy(addr, p, len);
memset((void *)addr + len, 0, sizeof(*addr) - len);
memcpy(port, p + len, sizeof(__be16));
return 1;
}
/****************************************************************************/
static int expect_rtp_rtcp(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
H245_TransportAddress *taddr)
{
int dir = CTINFO2DIR(ctinfo);
int ret = 0;
__be16 port;
__be16 rtp_port, rtcp_port;
union nf_inet_addr addr;
struct nf_conntrack_expect *rtp_exp;
struct nf_conntrack_expect *rtcp_exp;
typeof(nat_rtp_rtcp_hook) nat_rtp_rtcp;
/* Read RTP or RTCP address */
if (!get_h245_addr(ct, *data, taddr, &addr, &port) ||
memcmp(&addr, &ct->tuplehash[dir].tuple.src.u3, sizeof(addr)) ||
port == 0)
return 0;
/* RTP port is even */
port &= htons(~1);
rtp_port = port;
rtcp_port = htons(ntohs(port) + 1);
/* Create expect for RTP */
if ((rtp_exp = nf_ct_expect_alloc(ct)) == NULL)
return -1;
nf_ct_expect_init(rtp_exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
&ct->tuplehash[!dir].tuple.src.u3,
&ct->tuplehash[!dir].tuple.dst.u3,
IPPROTO_UDP, NULL, &rtp_port);
/* Create expect for RTCP */
if ((rtcp_exp = nf_ct_expect_alloc(ct)) == NULL) {
nf_ct_expect_put(rtp_exp);
return -1;
}
nf_ct_expect_init(rtcp_exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
&ct->tuplehash[!dir].tuple.src.u3,
&ct->tuplehash[!dir].tuple.dst.u3,
IPPROTO_UDP, NULL, &rtcp_port);
if (memcmp(&ct->tuplehash[dir].tuple.src.u3,
&ct->tuplehash[!dir].tuple.dst.u3,
sizeof(ct->tuplehash[dir].tuple.src.u3)) &&
(nat_rtp_rtcp = rcu_dereference(nat_rtp_rtcp_hook)) &&
ct->status & IPS_NAT_MASK) {
/* NAT needed */
ret = nat_rtp_rtcp(skb, ct, ctinfo, data, dataoff,
taddr, port, rtp_port, rtp_exp, rtcp_exp);
} else { /* Conntrack only */
if (nf_ct_expect_related(rtp_exp) == 0) {
if (nf_ct_expect_related(rtcp_exp) == 0) {
pr_debug("nf_ct_h323: expect RTP ");
nf_ct_dump_tuple(&rtp_exp->tuple);
pr_debug("nf_ct_h323: expect RTCP ");
nf_ct_dump_tuple(&rtcp_exp->tuple);
} else {
nf_ct_unexpect_related(rtp_exp);
ret = -1;
}
} else
ret = -1;
}
nf_ct_expect_put(rtp_exp);
nf_ct_expect_put(rtcp_exp);
return ret;
}
/****************************************************************************/
static int expect_t120(struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
H245_TransportAddress *taddr)
{
int dir = CTINFO2DIR(ctinfo);
int ret = 0;
__be16 port;
union nf_inet_addr addr;
struct nf_conntrack_expect *exp;
typeof(nat_t120_hook) nat_t120;
/* Read T.120 address */
if (!get_h245_addr(ct, *data, taddr, &addr, &port) ||
memcmp(&addr, &ct->tuplehash[dir].tuple.src.u3, sizeof(addr)) ||
port == 0)
return 0;
/* Create expect for T.120 connections */
if ((exp = nf_ct_expect_alloc(ct)) == NULL)
return -1;
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
&ct->tuplehash[!dir].tuple.src.u3,
&ct->tuplehash[!dir].tuple.dst.u3,
IPPROTO_TCP, NULL, &port);
exp->flags = NF_CT_EXPECT_PERMANENT; /* Accept multiple channels */
if (memcmp(&ct->tuplehash[dir].tuple.src.u3,
&ct->tuplehash[!dir].tuple.dst.u3,
sizeof(ct->tuplehash[dir].tuple.src.u3)) &&
(nat_t120 = rcu_dereference(nat_t120_hook)) &&
ct->status & IPS_NAT_MASK) {
/* NAT needed */
ret = nat_t120(skb, ct, ctinfo, data, dataoff, taddr,
port, exp);
} else { /* Conntrack only */
if (nf_ct_expect_related(exp) == 0) {
pr_debug("nf_ct_h323: expect T.120 ");
nf_ct_dump_tuple(&exp->tuple);
} else
ret = -1;
}
nf_ct_expect_put(exp);
return ret;
}
/****************************************************************************/
static int process_h245_channel(struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
H2250LogicalChannelParameters *channel)
{
int ret;
if (channel->options & eH2250LogicalChannelParameters_mediaChannel) {
/* RTP */
ret = expect_rtp_rtcp(skb, ct, ctinfo, data, dataoff,
&channel->mediaChannel);
if (ret < 0)
return -1;
}
if (channel->
options & eH2250LogicalChannelParameters_mediaControlChannel) {
/* RTCP */
ret = expect_rtp_rtcp(skb, ct, ctinfo, data, dataoff,
&channel->mediaControlChannel);
if (ret < 0)
return -1;
}
return 0;
}
/****************************************************************************/
static int process_olc(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
OpenLogicalChannel *olc)
{
int ret;
pr_debug("nf_ct_h323: OpenLogicalChannel\n");
if (olc->forwardLogicalChannelParameters.multiplexParameters.choice ==
eOpenLogicalChannel_forwardLogicalChannelParameters_multiplexParameters_h2250LogicalChannelParameters)
{
ret = process_h245_channel(skb, ct, ctinfo, data, dataoff,
&olc->
forwardLogicalChannelParameters.
multiplexParameters.
h2250LogicalChannelParameters);
if (ret < 0)
return -1;
}
if ((olc->options &
eOpenLogicalChannel_reverseLogicalChannelParameters) &&
(olc->reverseLogicalChannelParameters.options &
eOpenLogicalChannel_reverseLogicalChannelParameters_multiplexParameters)
&& (olc->reverseLogicalChannelParameters.multiplexParameters.
choice ==
eOpenLogicalChannel_reverseLogicalChannelParameters_multiplexParameters_h2250LogicalChannelParameters))
{
ret =
process_h245_channel(skb, ct, ctinfo, data, dataoff,
&olc->
reverseLogicalChannelParameters.
multiplexParameters.
h2250LogicalChannelParameters);
if (ret < 0)
return -1;
}
if ((olc->options & eOpenLogicalChannel_separateStack) &&
olc->forwardLogicalChannelParameters.dataType.choice ==
eDataType_data &&
olc->forwardLogicalChannelParameters.dataType.data.application.
choice == eDataApplicationCapability_application_t120 &&
olc->forwardLogicalChannelParameters.dataType.data.application.
t120.choice == eDataProtocolCapability_separateLANStack &&
olc->separateStack.networkAddress.choice ==
eNetworkAccessParameters_networkAddress_localAreaAddress) {
ret = expect_t120(skb, ct, ctinfo, data, dataoff,
&olc->separateStack.networkAddress.
localAreaAddress);
if (ret < 0)
return -1;
}
return 0;
}
/****************************************************************************/
static int process_olca(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
OpenLogicalChannelAck *olca)
{
H2250LogicalChannelAckParameters *ack;
int ret;
pr_debug("nf_ct_h323: OpenLogicalChannelAck\n");
if ((olca->options &
eOpenLogicalChannelAck_reverseLogicalChannelParameters) &&
(olca->reverseLogicalChannelParameters.options &
eOpenLogicalChannelAck_reverseLogicalChannelParameters_multiplexParameters)
&& (olca->reverseLogicalChannelParameters.multiplexParameters.
choice ==
eOpenLogicalChannelAck_reverseLogicalChannelParameters_multiplexParameters_h2250LogicalChannelParameters))
{
ret = process_h245_channel(skb, ct, ctinfo, data, dataoff,
&olca->
reverseLogicalChannelParameters.
multiplexParameters.
h2250LogicalChannelParameters);
if (ret < 0)
return -1;
}
if ((olca->options &
eOpenLogicalChannelAck_forwardMultiplexAckParameters) &&
(olca->forwardMultiplexAckParameters.choice ==
eOpenLogicalChannelAck_forwardMultiplexAckParameters_h2250LogicalChannelAckParameters))
{
ack = &olca->forwardMultiplexAckParameters.
h2250LogicalChannelAckParameters;
if (ack->options &
eH2250LogicalChannelAckParameters_mediaChannel) {
/* RTP */
ret = expect_rtp_rtcp(skb, ct, ctinfo, data, dataoff,
&ack->mediaChannel);
if (ret < 0)
return -1;
}
if (ack->options &
eH2250LogicalChannelAckParameters_mediaControlChannel) {
/* RTCP */
ret = expect_rtp_rtcp(skb, ct, ctinfo, data, dataoff,
&ack->mediaControlChannel);
if (ret < 0)
return -1;
}
}
if ((olca->options & eOpenLogicalChannelAck_separateStack) &&
olca->separateStack.networkAddress.choice ==
eNetworkAccessParameters_networkAddress_localAreaAddress) {
ret = expect_t120(skb, ct, ctinfo, data, dataoff,
&olca->separateStack.networkAddress.
localAreaAddress);
if (ret < 0)
return -1;
}
return 0;
}
/****************************************************************************/
static int process_h245(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
MultimediaSystemControlMessage *mscm)
{
switch (mscm->choice) {
case eMultimediaSystemControlMessage_request:
if (mscm->request.choice ==
eRequestMessage_openLogicalChannel) {
return process_olc(skb, ct, ctinfo, data, dataoff,
&mscm->request.openLogicalChannel);
}
pr_debug("nf_ct_h323: H.245 Request %d\n",
mscm->request.choice);
break;
case eMultimediaSystemControlMessage_response:
if (mscm->response.choice ==
eResponseMessage_openLogicalChannelAck) {
return process_olca(skb, ct, ctinfo, data, dataoff,
&mscm->response.
openLogicalChannelAck);
}
pr_debug("nf_ct_h323: H.245 Response %d\n",
mscm->response.choice);
break;
default:
pr_debug("nf_ct_h323: H.245 signal %d\n", mscm->choice);
break;
}
return 0;
}
/****************************************************************************/
static int h245_help(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct, enum ip_conntrack_info ctinfo)
{
static MultimediaSystemControlMessage mscm;
unsigned char *data = NULL;
int datalen;
int dataoff;
int ret;
/* Until there's been traffic both ways, don't look in packets. */
if (ctinfo != IP_CT_ESTABLISHED && ctinfo != IP_CT_ESTABLISHED_REPLY)
return NF_ACCEPT;
pr_debug("nf_ct_h245: skblen = %u\n", skb->len);
spin_lock_bh(&nf_h323_lock);
/* Process each TPKT */
while (get_tpkt_data(skb, protoff, ct, ctinfo,
&data, &datalen, &dataoff)) {
pr_debug("nf_ct_h245: TPKT len=%d ", datalen);
nf_ct_dump_tuple(&ct->tuplehash[CTINFO2DIR(ctinfo)].tuple);
/* Decode H.245 signal */
ret = DecodeMultimediaSystemControlMessage(data, datalen,
&mscm);
if (ret < 0) {
pr_debug("nf_ct_h245: decoding error: %s\n",
ret == H323_ERROR_BOUND ?
"out of bound" : "out of range");
/* We don't drop when decoding error */
break;
}
/* Process H.245 signal */
if (process_h245(skb, ct, ctinfo, &data, dataoff, &mscm) < 0)
goto drop;
}
spin_unlock_bh(&nf_h323_lock);
return NF_ACCEPT;
drop:
spin_unlock_bh(&nf_h323_lock);
if (net_ratelimit())
pr_info("nf_ct_h245: packet dropped\n");
return NF_DROP;
}
/****************************************************************************/
static const struct nf_conntrack_expect_policy h245_exp_policy = {
.max_expected = H323_RTP_CHANNEL_MAX * 4 + 2 /* T.120 */,
.timeout = 240,
};
static struct nf_conntrack_helper nf_conntrack_helper_h245 __read_mostly = {
.name = "H.245",
.me = THIS_MODULE,
.tuple.src.l3num = AF_UNSPEC,
.tuple.dst.protonum = IPPROTO_UDP,
.help = h245_help,
.expect_policy = &h245_exp_policy,
};
/****************************************************************************/
int get_h225_addr(struct nf_conn *ct, unsigned char *data,
TransportAddress *taddr,
union nf_inet_addr *addr, __be16 *port)
{
const unsigned char *p;
int len;
switch (taddr->choice) {
case eTransportAddress_ipAddress:
if (nf_ct_l3num(ct) != AF_INET)
return 0;
p = data + taddr->ipAddress.ip;
len = 4;
break;
case eTransportAddress_ip6Address:
if (nf_ct_l3num(ct) != AF_INET6)
return 0;
p = data + taddr->ip6Address.ip;
len = 16;
break;
default:
return 0;
}
memcpy(addr, p, len);
memset((void *)addr + len, 0, sizeof(*addr) - len);
memcpy(port, p + len, sizeof(__be16));
return 1;
}
/****************************************************************************/
static int expect_h245(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
TransportAddress *taddr)
{
int dir = CTINFO2DIR(ctinfo);
int ret = 0;
__be16 port;
union nf_inet_addr addr;
struct nf_conntrack_expect *exp;
typeof(nat_h245_hook) nat_h245;
/* Read h245Address */
if (!get_h225_addr(ct, *data, taddr, &addr, &port) ||
memcmp(&addr, &ct->tuplehash[dir].tuple.src.u3, sizeof(addr)) ||
port == 0)
return 0;
/* Create expect for h245 connection */
if ((exp = nf_ct_expect_alloc(ct)) == NULL)
return -1;
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
&ct->tuplehash[!dir].tuple.src.u3,
&ct->tuplehash[!dir].tuple.dst.u3,
IPPROTO_TCP, NULL, &port);
exp->helper = &nf_conntrack_helper_h245;
if (memcmp(&ct->tuplehash[dir].tuple.src.u3,
&ct->tuplehash[!dir].tuple.dst.u3,
sizeof(ct->tuplehash[dir].tuple.src.u3)) &&
(nat_h245 = rcu_dereference(nat_h245_hook)) &&
ct->status & IPS_NAT_MASK) {
/* NAT needed */
ret = nat_h245(skb, ct, ctinfo, data, dataoff, taddr,
port, exp);
} else { /* Conntrack only */
if (nf_ct_expect_related(exp) == 0) {
pr_debug("nf_ct_q931: expect H.245 ");
nf_ct_dump_tuple(&exp->tuple);
} else
ret = -1;
}
nf_ct_expect_put(exp);
return ret;
}
/* If the calling party is on the same side of the forward-to party,
* we don't need to track the second call */
static int callforward_do_filter(const union nf_inet_addr *src,
const union nf_inet_addr *dst,
u_int8_t family)
{
const struct nf_afinfo *afinfo;
int ret = 0;
/* rcu_read_lock()ed by nf_hook_slow() */
afinfo = nf_get_afinfo(family);
if (!afinfo)
return 0;
switch (family) {
case AF_INET: {
struct flowi4 fl1, fl2;
struct rtable *rt1, *rt2;
memset(&fl1, 0, sizeof(fl1));
fl1.daddr = src->ip;
memset(&fl2, 0, sizeof(fl2));
fl2.daddr = dst->ip;
if (!afinfo->route(&init_net, (struct dst_entry **)&rt1,
flowi4_to_flowi(&fl1), false)) {
if (!afinfo->route(&init_net, (struct dst_entry **)&rt2,
flowi4_to_flowi(&fl2), false)) {
if (rt1->rt_gateway == rt2->rt_gateway &&
rt1->dst.dev == rt2->dst.dev)
ret = 1;
dst_release(&rt2->dst);
}
dst_release(&rt1->dst);
}
break;
}
#if IS_ENABLED(CONFIG_NF_CONNTRACK_IPV6)
case AF_INET6: {
struct flowi6 fl1, fl2;
struct rt6_info *rt1, *rt2;
memset(&fl1, 0, sizeof(fl1));
fl1.daddr = src->in6;
memset(&fl2, 0, sizeof(fl2));
fl2.daddr = dst->in6;
if (!afinfo->route(&init_net, (struct dst_entry **)&rt1,
flowi6_to_flowi(&fl1), false)) {
if (!afinfo->route(&init_net, (struct dst_entry **)&rt2,
flowi6_to_flowi(&fl2), false)) {
if (!memcmp(&rt1->rt6i_gateway, &rt2->rt6i_gateway,
sizeof(rt1->rt6i_gateway)) &&
rt1->dst.dev == rt2->dst.dev)
ret = 1;
dst_release(&rt2->dst);
}
dst_release(&rt1->dst);
}
break;
}
#endif
}
return ret;
}
/****************************************************************************/
static int expect_callforwarding(struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
TransportAddress *taddr)
{
int dir = CTINFO2DIR(ctinfo);
int ret = 0;
__be16 port;
union nf_inet_addr addr;
struct nf_conntrack_expect *exp;
typeof(nat_callforwarding_hook) nat_callforwarding;
/* Read alternativeAddress */
if (!get_h225_addr(ct, *data, taddr, &addr, &port) || port == 0)
return 0;
/* If the calling party is on the same side of the forward-to party,
* we don't need to track the second call */
if (callforward_filter &&
callforward_do_filter(&addr, &ct->tuplehash[!dir].tuple.src.u3,
nf_ct_l3num(ct))) {
pr_debug("nf_ct_q931: Call Forwarding not tracked\n");
return 0;
}
/* Create expect for the second call leg */
if ((exp = nf_ct_expect_alloc(ct)) == NULL)
return -1;
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
&ct->tuplehash[!dir].tuple.src.u3, &addr,
IPPROTO_TCP, NULL, &port);
exp->helper = nf_conntrack_helper_q931;
if (memcmp(&ct->tuplehash[dir].tuple.src.u3,
&ct->tuplehash[!dir].tuple.dst.u3,
sizeof(ct->tuplehash[dir].tuple.src.u3)) &&
(nat_callforwarding = rcu_dereference(nat_callforwarding_hook)) &&
ct->status & IPS_NAT_MASK) {
/* Need NAT */
ret = nat_callforwarding(skb, ct, ctinfo, data, dataoff,
taddr, port, exp);
} else { /* Conntrack only */
if (nf_ct_expect_related(exp) == 0) {
pr_debug("nf_ct_q931: expect Call Forwarding ");
nf_ct_dump_tuple(&exp->tuple);
} else
ret = -1;
}
nf_ct_expect_put(exp);
return ret;
}
/****************************************************************************/
static int process_setup(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
Setup_UUIE *setup)
{
int dir = CTINFO2DIR(ctinfo);
int ret;
int i;
__be16 port;
union nf_inet_addr addr;
typeof(set_h225_addr_hook) set_h225_addr;
pr_debug("nf_ct_q931: Setup\n");
if (setup->options & eSetup_UUIE_h245Address) {
ret = expect_h245(skb, ct, ctinfo, data, dataoff,
&setup->h245Address);
if (ret < 0)
return -1;
}
set_h225_addr = rcu_dereference(set_h225_addr_hook);
if ((setup->options & eSetup_UUIE_destCallSignalAddress) &&
(set_h225_addr) && ct->status & IPS_NAT_MASK &&
get_h225_addr(ct, *data, &setup->destCallSignalAddress,
&addr, &port) &&
memcmp(&addr, &ct->tuplehash[!dir].tuple.src.u3, sizeof(addr))) {
pr_debug("nf_ct_q931: set destCallSignalAddress %pI6:%hu->%pI6:%hu\n",
&addr, ntohs(port), &ct->tuplehash[!dir].tuple.src.u3,
ntohs(ct->tuplehash[!dir].tuple.src.u.tcp.port));
ret = set_h225_addr(skb, data, dataoff,
&setup->destCallSignalAddress,
&ct->tuplehash[!dir].tuple.src.u3,
ct->tuplehash[!dir].tuple.src.u.tcp.port);
if (ret < 0)
return -1;
}
if ((setup->options & eSetup_UUIE_sourceCallSignalAddress) &&
(set_h225_addr) && ct->status & IPS_NAT_MASK &&
get_h225_addr(ct, *data, &setup->sourceCallSignalAddress,
&addr, &port) &&
memcmp(&addr, &ct->tuplehash[!dir].tuple.dst.u3, sizeof(addr))) {
pr_debug("nf_ct_q931: set sourceCallSignalAddress %pI6:%hu->%pI6:%hu\n",
&addr, ntohs(port), &ct->tuplehash[!dir].tuple.dst.u3,
ntohs(ct->tuplehash[!dir].tuple.dst.u.tcp.port));
ret = set_h225_addr(skb, data, dataoff,
&setup->sourceCallSignalAddress,
&ct->tuplehash[!dir].tuple.dst.u3,
ct->tuplehash[!dir].tuple.dst.u.tcp.port);
if (ret < 0)
return -1;
}
if (setup->options & eSetup_UUIE_fastStart) {
for (i = 0; i < setup->fastStart.count; i++) {
ret = process_olc(skb, ct, ctinfo, data, dataoff,
&setup->fastStart.item[i]);
if (ret < 0)
return -1;
}
}
return 0;
}
/****************************************************************************/
static int process_callproceeding(struct sk_buff *skb,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
CallProceeding_UUIE *callproc)
{
int ret;
int i;
pr_debug("nf_ct_q931: CallProceeding\n");
if (callproc->options & eCallProceeding_UUIE_h245Address) {
ret = expect_h245(skb, ct, ctinfo, data, dataoff,
&callproc->h245Address);
if (ret < 0)
return -1;
}
if (callproc->options & eCallProceeding_UUIE_fastStart) {
for (i = 0; i < callproc->fastStart.count; i++) {
ret = process_olc(skb, ct, ctinfo, data, dataoff,
&callproc->fastStart.item[i]);
if (ret < 0)
return -1;
}
}
return 0;
}
/****************************************************************************/
static int process_connect(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
Connect_UUIE *connect)
{
int ret;
int i;
pr_debug("nf_ct_q931: Connect\n");
if (connect->options & eConnect_UUIE_h245Address) {
ret = expect_h245(skb, ct, ctinfo, data, dataoff,
&connect->h245Address);
if (ret < 0)
return -1;
}
if (connect->options & eConnect_UUIE_fastStart) {
for (i = 0; i < connect->fastStart.count; i++) {
ret = process_olc(skb, ct, ctinfo, data, dataoff,
&connect->fastStart.item[i]);
if (ret < 0)
return -1;
}
}
return 0;
}
/****************************************************************************/
static int process_alerting(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
Alerting_UUIE *alert)
{
int ret;
int i;
pr_debug("nf_ct_q931: Alerting\n");
if (alert->options & eAlerting_UUIE_h245Address) {
ret = expect_h245(skb, ct, ctinfo, data, dataoff,
&alert->h245Address);
if (ret < 0)
return -1;
}
if (alert->options & eAlerting_UUIE_fastStart) {
for (i = 0; i < alert->fastStart.count; i++) {
ret = process_olc(skb, ct, ctinfo, data, dataoff,
&alert->fastStart.item[i]);
if (ret < 0)
return -1;
}
}
return 0;
}
/****************************************************************************/
static int process_facility(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
Facility_UUIE *facility)
{
int ret;
int i;
pr_debug("nf_ct_q931: Facility\n");
if (facility->reason.choice == eFacilityReason_callForwarded) {
if (facility->options & eFacility_UUIE_alternativeAddress)
return expect_callforwarding(skb, ct, ctinfo, data,
dataoff,
&facility->
alternativeAddress);
return 0;
}
if (facility->options & eFacility_UUIE_h245Address) {
ret = expect_h245(skb, ct, ctinfo, data, dataoff,
&facility->h245Address);
if (ret < 0)
return -1;
}
if (facility->options & eFacility_UUIE_fastStart) {
for (i = 0; i < facility->fastStart.count; i++) {
ret = process_olc(skb, ct, ctinfo, data, dataoff,
&facility->fastStart.item[i]);
if (ret < 0)
return -1;
}
}
return 0;
}
/****************************************************************************/
static int process_progress(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff,
Progress_UUIE *progress)
{
int ret;
int i;
pr_debug("nf_ct_q931: Progress\n");
if (progress->options & eProgress_UUIE_h245Address) {
ret = expect_h245(skb, ct, ctinfo, data, dataoff,
&progress->h245Address);
if (ret < 0)
return -1;
}
if (progress->options & eProgress_UUIE_fastStart) {
for (i = 0; i < progress->fastStart.count; i++) {
ret = process_olc(skb, ct, ctinfo, data, dataoff,
&progress->fastStart.item[i]);
if (ret < 0)
return -1;
}
}
return 0;
}
/****************************************************************************/
static int process_q931(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, int dataoff, Q931 *q931)
{
H323_UU_PDU *pdu = &q931->UUIE.h323_uu_pdu;
int i;
int ret = 0;
switch (pdu->h323_message_body.choice) {
case eH323_UU_PDU_h323_message_body_setup:
ret = process_setup(skb, ct, ctinfo, data, dataoff,
&pdu->h323_message_body.setup);
break;
case eH323_UU_PDU_h323_message_body_callProceeding:
ret = process_callproceeding(skb, ct, ctinfo, data, dataoff,
&pdu->h323_message_body.
callProceeding);
break;
case eH323_UU_PDU_h323_message_body_connect:
ret = process_connect(skb, ct, ctinfo, data, dataoff,
&pdu->h323_message_body.connect);
break;
case eH323_UU_PDU_h323_message_body_alerting:
ret = process_alerting(skb, ct, ctinfo, data, dataoff,
&pdu->h323_message_body.alerting);
break;
case eH323_UU_PDU_h323_message_body_facility:
ret = process_facility(skb, ct, ctinfo, data, dataoff,
&pdu->h323_message_body.facility);
break;
case eH323_UU_PDU_h323_message_body_progress:
ret = process_progress(skb, ct, ctinfo, data, dataoff,
&pdu->h323_message_body.progress);
break;
default:
pr_debug("nf_ct_q931: Q.931 signal %d\n",
pdu->h323_message_body.choice);
break;
}
if (ret < 0)
return -1;
if (pdu->options & eH323_UU_PDU_h245Control) {
for (i = 0; i < pdu->h245Control.count; i++) {
ret = process_h245(skb, ct, ctinfo, data, dataoff,
&pdu->h245Control.item[i]);
if (ret < 0)
return -1;
}
}
return 0;
}
/****************************************************************************/
static int q931_help(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct, enum ip_conntrack_info ctinfo)
{
static Q931 q931;
unsigned char *data = NULL;
int datalen;
int dataoff;
int ret;
/* Until there's been traffic both ways, don't look in packets. */
if (ctinfo != IP_CT_ESTABLISHED && ctinfo != IP_CT_ESTABLISHED_REPLY)
return NF_ACCEPT;
pr_debug("nf_ct_q931: skblen = %u\n", skb->len);
spin_lock_bh(&nf_h323_lock);
/* Process each TPKT */
while (get_tpkt_data(skb, protoff, ct, ctinfo,
&data, &datalen, &dataoff)) {
pr_debug("nf_ct_q931: TPKT len=%d ", datalen);
nf_ct_dump_tuple(&ct->tuplehash[CTINFO2DIR(ctinfo)].tuple);
/* Decode Q.931 signal */
ret = DecodeQ931(data, datalen, &q931);
if (ret < 0) {
pr_debug("nf_ct_q931: decoding error: %s\n",
ret == H323_ERROR_BOUND ?
"out of bound" : "out of range");
/* We don't drop when decoding error */
break;
}
/* Process Q.931 signal */
if (process_q931(skb, ct, ctinfo, &data, dataoff, &q931) < 0)
goto drop;
}
spin_unlock_bh(&nf_h323_lock);
return NF_ACCEPT;
drop:
spin_unlock_bh(&nf_h323_lock);
if (net_ratelimit())
pr_info("nf_ct_q931: packet dropped\n");
return NF_DROP;
}
/****************************************************************************/
static const struct nf_conntrack_expect_policy q931_exp_policy = {
/* T.120 and H.245 */
.max_expected = H323_RTP_CHANNEL_MAX * 4 + 4,
.timeout = 240,
};
static struct nf_conntrack_helper nf_conntrack_helper_q931[] __read_mostly = {
{
.name = "Q.931",
.me = THIS_MODULE,
.tuple.src.l3num = AF_INET,
.tuple.src.u.tcp.port = cpu_to_be16(Q931_PORT),
.tuple.dst.protonum = IPPROTO_TCP,
.help = q931_help,
.expect_policy = &q931_exp_policy,
},
{
.name = "Q.931",
.me = THIS_MODULE,
.tuple.src.l3num = AF_INET6,
.tuple.src.u.tcp.port = cpu_to_be16(Q931_PORT),
.tuple.dst.protonum = IPPROTO_TCP,
.help = q931_help,
.expect_policy = &q931_exp_policy,
},
};
/****************************************************************************/
static unsigned char *get_udp_data(struct sk_buff *skb, unsigned int protoff,
int *datalen)
{
const struct udphdr *uh;
struct udphdr _uh;
int dataoff;
uh = skb_header_pointer(skb, protoff, sizeof(_uh), &_uh);
if (uh == NULL)
return NULL;
dataoff = protoff + sizeof(_uh);
if (dataoff >= skb->len)
return NULL;
*datalen = skb->len - dataoff;
return skb_header_pointer(skb, dataoff, *datalen, h323_buffer);
}
/****************************************************************************/
static struct nf_conntrack_expect *find_expect(struct nf_conn *ct,
union nf_inet_addr *addr,
__be16 port)
{
struct net *net = nf_ct_net(ct);
struct nf_conntrack_expect *exp;
struct nf_conntrack_tuple tuple;
memset(&tuple.src.u3, 0, sizeof(tuple.src.u3));
tuple.src.u.tcp.port = 0;
memcpy(&tuple.dst.u3, addr, sizeof(tuple.dst.u3));
tuple.dst.u.tcp.port = port;
tuple.dst.protonum = IPPROTO_TCP;
exp = __nf_ct_expect_find(net, nf_ct_zone(ct), &tuple);
if (exp && exp->master == ct)
return exp;
return NULL;
}
/****************************************************************************/
static int set_expect_timeout(struct nf_conntrack_expect *exp,
unsigned timeout)
{
if (!exp || !del_timer(&exp->timeout))
return 0;
exp->timeout.expires = jiffies + timeout * HZ;
add_timer(&exp->timeout);
return 1;
}
/****************************************************************************/
static int expect_q931(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data,
TransportAddress *taddr, int count)
{
struct nf_ct_h323_master *info = &nfct_help(ct)->help.ct_h323_info;
int dir = CTINFO2DIR(ctinfo);
int ret = 0;
int i;
__be16 port;
union nf_inet_addr addr;
struct nf_conntrack_expect *exp;
typeof(nat_q931_hook) nat_q931;
/* Look for the first related address */
for (i = 0; i < count; i++) {
if (get_h225_addr(ct, *data, &taddr[i], &addr, &port) &&
memcmp(&addr, &ct->tuplehash[dir].tuple.src.u3,
sizeof(addr)) == 0 && port != 0)
break;
}
if (i >= count) /* Not found */
return 0;
/* Create expect for Q.931 */
if ((exp = nf_ct_expect_alloc(ct)) == NULL)
return -1;
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
gkrouted_only ? /* only accept calls from GK? */
&ct->tuplehash[!dir].tuple.src.u3 : NULL,
&ct->tuplehash[!dir].tuple.dst.u3,
IPPROTO_TCP, NULL, &port);
exp->helper = nf_conntrack_helper_q931;
exp->flags = NF_CT_EXPECT_PERMANENT; /* Accept multiple calls */
nat_q931 = rcu_dereference(nat_q931_hook);
if (nat_q931 && ct->status & IPS_NAT_MASK) { /* Need NAT */
ret = nat_q931(skb, ct, ctinfo, data, taddr, i, port, exp);
} else { /* Conntrack only */
if (nf_ct_expect_related(exp) == 0) {
pr_debug("nf_ct_ras: expect Q.931 ");
nf_ct_dump_tuple(&exp->tuple);
/* Save port for looking up expect in processing RCF */
info->sig_port[dir] = port;
} else
ret = -1;
}
nf_ct_expect_put(exp);
return ret;
}
/****************************************************************************/
static int process_grq(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, GatekeeperRequest *grq)
{
typeof(set_ras_addr_hook) set_ras_addr;
pr_debug("nf_ct_ras: GRQ\n");
set_ras_addr = rcu_dereference(set_ras_addr_hook);
if (set_ras_addr && ct->status & IPS_NAT_MASK) /* NATed */
return set_ras_addr(skb, ct, ctinfo, data,
&grq->rasAddress, 1);
return 0;
}
/****************************************************************************/
static int process_gcf(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, GatekeeperConfirm *gcf)
{
int dir = CTINFO2DIR(ctinfo);
int ret = 0;
__be16 port;
union nf_inet_addr addr;
struct nf_conntrack_expect *exp;
pr_debug("nf_ct_ras: GCF\n");
if (!get_h225_addr(ct, *data, &gcf->rasAddress, &addr, &port))
return 0;
/* Registration port is the same as discovery port */
if (!memcmp(&addr, &ct->tuplehash[dir].tuple.src.u3, sizeof(addr)) &&
port == ct->tuplehash[dir].tuple.src.u.udp.port)
return 0;
/* Avoid RAS expectation loops. A GCF is never expected. */
if (test_bit(IPS_EXPECTED_BIT, &ct->status))
return 0;
/* Need new expect */
if ((exp = nf_ct_expect_alloc(ct)) == NULL)
return -1;
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
&ct->tuplehash[!dir].tuple.src.u3, &addr,
IPPROTO_UDP, NULL, &port);
exp->helper = nf_conntrack_helper_ras;
if (nf_ct_expect_related(exp) == 0) {
pr_debug("nf_ct_ras: expect RAS ");
nf_ct_dump_tuple(&exp->tuple);
} else
ret = -1;
nf_ct_expect_put(exp);
return ret;
}
/****************************************************************************/
static int process_rrq(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, RegistrationRequest *rrq)
{
struct nf_ct_h323_master *info = &nfct_help(ct)->help.ct_h323_info;
int ret;
typeof(set_ras_addr_hook) set_ras_addr;
pr_debug("nf_ct_ras: RRQ\n");
ret = expect_q931(skb, ct, ctinfo, data,
rrq->callSignalAddress.item,
rrq->callSignalAddress.count);
if (ret < 0)
return -1;
set_ras_addr = rcu_dereference(set_ras_addr_hook);
if (set_ras_addr && ct->status & IPS_NAT_MASK) {
ret = set_ras_addr(skb, ct, ctinfo, data,
rrq->rasAddress.item,
rrq->rasAddress.count);
if (ret < 0)
return -1;
}
if (rrq->options & eRegistrationRequest_timeToLive) {
pr_debug("nf_ct_ras: RRQ TTL = %u seconds\n", rrq->timeToLive);
info->timeout = rrq->timeToLive;
} else
info->timeout = default_rrq_ttl;
return 0;
}
/****************************************************************************/
static int process_rcf(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, RegistrationConfirm *rcf)
{
struct nf_ct_h323_master *info = &nfct_help(ct)->help.ct_h323_info;
int dir = CTINFO2DIR(ctinfo);
int ret;
struct nf_conntrack_expect *exp;
typeof(set_sig_addr_hook) set_sig_addr;
pr_debug("nf_ct_ras: RCF\n");
set_sig_addr = rcu_dereference(set_sig_addr_hook);
if (set_sig_addr && ct->status & IPS_NAT_MASK) {
ret = set_sig_addr(skb, ct, ctinfo, data,
rcf->callSignalAddress.item,
rcf->callSignalAddress.count);
if (ret < 0)
return -1;
}
if (rcf->options & eRegistrationConfirm_timeToLive) {
pr_debug("nf_ct_ras: RCF TTL = %u seconds\n", rcf->timeToLive);
info->timeout = rcf->timeToLive;
}
if (info->timeout > 0) {
pr_debug("nf_ct_ras: set RAS connection timeout to "
"%u seconds\n", info->timeout);
nf_ct_refresh(ct, skb, info->timeout * HZ);
/* Set expect timeout */
spin_lock_bh(&nf_conntrack_lock);
exp = find_expect(ct, &ct->tuplehash[dir].tuple.dst.u3,
info->sig_port[!dir]);
if (exp) {
pr_debug("nf_ct_ras: set Q.931 expect "
"timeout to %u seconds for",
info->timeout);
nf_ct_dump_tuple(&exp->tuple);
set_expect_timeout(exp, info->timeout);
}
spin_unlock_bh(&nf_conntrack_lock);
}
return 0;
}
/****************************************************************************/
static int process_urq(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, UnregistrationRequest *urq)
{
struct nf_ct_h323_master *info = &nfct_help(ct)->help.ct_h323_info;
int dir = CTINFO2DIR(ctinfo);
int ret;
typeof(set_sig_addr_hook) set_sig_addr;
pr_debug("nf_ct_ras: URQ\n");
set_sig_addr = rcu_dereference(set_sig_addr_hook);
if (set_sig_addr && ct->status & IPS_NAT_MASK) {
ret = set_sig_addr(skb, ct, ctinfo, data,
urq->callSignalAddress.item,
urq->callSignalAddress.count);
if (ret < 0)
return -1;
}
/* Clear old expect */
nf_ct_remove_expectations(ct);
info->sig_port[dir] = 0;
info->sig_port[!dir] = 0;
/* Give it 30 seconds for UCF or URJ */
nf_ct_refresh(ct, skb, 30 * HZ);
return 0;
}
/****************************************************************************/
static int process_arq(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, AdmissionRequest *arq)
{
const struct nf_ct_h323_master *info = &nfct_help(ct)->help.ct_h323_info;
int dir = CTINFO2DIR(ctinfo);
__be16 port;
union nf_inet_addr addr;
typeof(set_h225_addr_hook) set_h225_addr;
pr_debug("nf_ct_ras: ARQ\n");
set_h225_addr = rcu_dereference(set_h225_addr_hook);
if ((arq->options & eAdmissionRequest_destCallSignalAddress) &&
get_h225_addr(ct, *data, &arq->destCallSignalAddress,
&addr, &port) &&
!memcmp(&addr, &ct->tuplehash[dir].tuple.src.u3, sizeof(addr)) &&
port == info->sig_port[dir] &&
set_h225_addr && ct->status & IPS_NAT_MASK) {
/* Answering ARQ */
return set_h225_addr(skb, data, 0,
&arq->destCallSignalAddress,
&ct->tuplehash[!dir].tuple.dst.u3,
info->sig_port[!dir]);
}
if ((arq->options & eAdmissionRequest_srcCallSignalAddress) &&
get_h225_addr(ct, *data, &arq->srcCallSignalAddress,
&addr, &port) &&
!memcmp(&addr, &ct->tuplehash[dir].tuple.src.u3, sizeof(addr)) &&
set_h225_addr && ct->status & IPS_NAT_MASK) {
/* Calling ARQ */
return set_h225_addr(skb, data, 0,
&arq->srcCallSignalAddress,
&ct->tuplehash[!dir].tuple.dst.u3,
port);
}
return 0;
}
/****************************************************************************/
static int process_acf(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, AdmissionConfirm *acf)
{
int dir = CTINFO2DIR(ctinfo);
int ret = 0;
__be16 port;
union nf_inet_addr addr;
struct nf_conntrack_expect *exp;
typeof(set_sig_addr_hook) set_sig_addr;
pr_debug("nf_ct_ras: ACF\n");
if (!get_h225_addr(ct, *data, &acf->destCallSignalAddress,
&addr, &port))
return 0;
if (!memcmp(&addr, &ct->tuplehash[dir].tuple.dst.u3, sizeof(addr))) {
/* Answering ACF */
set_sig_addr = rcu_dereference(set_sig_addr_hook);
if (set_sig_addr && ct->status & IPS_NAT_MASK)
return set_sig_addr(skb, ct, ctinfo, data,
&acf->destCallSignalAddress, 1);
return 0;
}
/* Need new expect */
if ((exp = nf_ct_expect_alloc(ct)) == NULL)
return -1;
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
&ct->tuplehash[!dir].tuple.src.u3, &addr,
IPPROTO_TCP, NULL, &port);
exp->flags = NF_CT_EXPECT_PERMANENT;
exp->helper = nf_conntrack_helper_q931;
if (nf_ct_expect_related(exp) == 0) {
pr_debug("nf_ct_ras: expect Q.931 ");
nf_ct_dump_tuple(&exp->tuple);
} else
ret = -1;
nf_ct_expect_put(exp);
return ret;
}
/****************************************************************************/
static int process_lrq(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, LocationRequest *lrq)
{
typeof(set_ras_addr_hook) set_ras_addr;
pr_debug("nf_ct_ras: LRQ\n");
set_ras_addr = rcu_dereference(set_ras_addr_hook);
if (set_ras_addr && ct->status & IPS_NAT_MASK)
return set_ras_addr(skb, ct, ctinfo, data,
&lrq->replyAddress, 1);
return 0;
}
/****************************************************************************/
static int process_lcf(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, LocationConfirm *lcf)
{
int dir = CTINFO2DIR(ctinfo);
int ret = 0;
__be16 port;
union nf_inet_addr addr;
struct nf_conntrack_expect *exp;
pr_debug("nf_ct_ras: LCF\n");
if (!get_h225_addr(ct, *data, &lcf->callSignalAddress,
&addr, &port))
return 0;
/* Need new expect for call signal */
if ((exp = nf_ct_expect_alloc(ct)) == NULL)
return -1;
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, nf_ct_l3num(ct),
&ct->tuplehash[!dir].tuple.src.u3, &addr,
IPPROTO_TCP, NULL, &port);
exp->flags = NF_CT_EXPECT_PERMANENT;
exp->helper = nf_conntrack_helper_q931;
if (nf_ct_expect_related(exp) == 0) {
pr_debug("nf_ct_ras: expect Q.931 ");
nf_ct_dump_tuple(&exp->tuple);
} else
ret = -1;
nf_ct_expect_put(exp);
/* Ignore rasAddress */
return ret;
}
/****************************************************************************/
static int process_irr(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, InfoRequestResponse *irr)
{
int ret;
typeof(set_ras_addr_hook) set_ras_addr;
typeof(set_sig_addr_hook) set_sig_addr;
pr_debug("nf_ct_ras: IRR\n");
set_ras_addr = rcu_dereference(set_ras_addr_hook);
if (set_ras_addr && ct->status & IPS_NAT_MASK) {
ret = set_ras_addr(skb, ct, ctinfo, data,
&irr->rasAddress, 1);
if (ret < 0)
return -1;
}
set_sig_addr = rcu_dereference(set_sig_addr_hook);
if (set_sig_addr && ct->status & IPS_NAT_MASK) {
ret = set_sig_addr(skb, ct, ctinfo, data,
irr->callSignalAddress.item,
irr->callSignalAddress.count);
if (ret < 0)
return -1;
}
return 0;
}
/****************************************************************************/
static int process_ras(struct sk_buff *skb, struct nf_conn *ct,
enum ip_conntrack_info ctinfo,
unsigned char **data, RasMessage *ras)
{
switch (ras->choice) {
case eRasMessage_gatekeeperRequest:
return process_grq(skb, ct, ctinfo, data,
&ras->gatekeeperRequest);
case eRasMessage_gatekeeperConfirm:
return process_gcf(skb, ct, ctinfo, data,
&ras->gatekeeperConfirm);
case eRasMessage_registrationRequest:
return process_rrq(skb, ct, ctinfo, data,
&ras->registrationRequest);
case eRasMessage_registrationConfirm:
return process_rcf(skb, ct, ctinfo, data,
&ras->registrationConfirm);
case eRasMessage_unregistrationRequest:
return process_urq(skb, ct, ctinfo, data,
&ras->unregistrationRequest);
case eRasMessage_admissionRequest:
return process_arq(skb, ct, ctinfo, data,
&ras->admissionRequest);
case eRasMessage_admissionConfirm:
return process_acf(skb, ct, ctinfo, data,
&ras->admissionConfirm);
case eRasMessage_locationRequest:
return process_lrq(skb, ct, ctinfo, data,
&ras->locationRequest);
case eRasMessage_locationConfirm:
return process_lcf(skb, ct, ctinfo, data,
&ras->locationConfirm);
case eRasMessage_infoRequestResponse:
return process_irr(skb, ct, ctinfo, data,
&ras->infoRequestResponse);
default:
pr_debug("nf_ct_ras: RAS message %d\n", ras->choice);
break;
}
return 0;
}
/****************************************************************************/
static int ras_help(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct, enum ip_conntrack_info ctinfo)
{
static RasMessage ras;
unsigned char *data;
int datalen = 0;
int ret;
pr_debug("nf_ct_ras: skblen = %u\n", skb->len);
spin_lock_bh(&nf_h323_lock);
/* Get UDP data */
data = get_udp_data(skb, protoff, &datalen);
if (data == NULL)
goto accept;
pr_debug("nf_ct_ras: RAS message len=%d ", datalen);
nf_ct_dump_tuple(&ct->tuplehash[CTINFO2DIR(ctinfo)].tuple);
/* Decode RAS message */
ret = DecodeRasMessage(data, datalen, &ras);
if (ret < 0) {
pr_debug("nf_ct_ras: decoding error: %s\n",
ret == H323_ERROR_BOUND ?
"out of bound" : "out of range");
goto accept;
}
/* Process RAS message */
if (process_ras(skb, ct, ctinfo, &data, &ras) < 0)
goto drop;
accept:
spin_unlock_bh(&nf_h323_lock);
return NF_ACCEPT;
drop:
spin_unlock_bh(&nf_h323_lock);
if (net_ratelimit())
pr_info("nf_ct_ras: packet dropped\n");
return NF_DROP;
}
/****************************************************************************/
static const struct nf_conntrack_expect_policy ras_exp_policy = {
.max_expected = 32,
.timeout = 240,
};
static struct nf_conntrack_helper nf_conntrack_helper_ras[] __read_mostly = {
{
.name = "RAS",
.me = THIS_MODULE,
.tuple.src.l3num = AF_INET,
.tuple.src.u.udp.port = cpu_to_be16(RAS_PORT),
.tuple.dst.protonum = IPPROTO_UDP,
.help = ras_help,
.expect_policy = &ras_exp_policy,
},
{
.name = "RAS",
.me = THIS_MODULE,
.tuple.src.l3num = AF_INET6,
.tuple.src.u.udp.port = cpu_to_be16(RAS_PORT),
.tuple.dst.protonum = IPPROTO_UDP,
.help = ras_help,
.expect_policy = &ras_exp_policy,
},
};
/****************************************************************************/
static void __exit nf_conntrack_h323_fini(void)
{
nf_conntrack_helper_unregister(&nf_conntrack_helper_ras[1]);
nf_conntrack_helper_unregister(&nf_conntrack_helper_ras[0]);
nf_conntrack_helper_unregister(&nf_conntrack_helper_q931[1]);
nf_conntrack_helper_unregister(&nf_conntrack_helper_q931[0]);
nf_conntrack_helper_unregister(&nf_conntrack_helper_h245);
kfree(h323_buffer);
pr_debug("nf_ct_h323: fini\n");
}
/****************************************************************************/
static int __init nf_conntrack_h323_init(void)
{
int ret;
h323_buffer = kmalloc(65536, GFP_KERNEL);
if (!h323_buffer)
return -ENOMEM;
ret = nf_conntrack_helper_register(&nf_conntrack_helper_h245);
if (ret < 0)
goto err1;
ret = nf_conntrack_helper_register(&nf_conntrack_helper_q931[0]);
if (ret < 0)
goto err2;
ret = nf_conntrack_helper_register(&nf_conntrack_helper_q931[1]);
if (ret < 0)
goto err3;
ret = nf_conntrack_helper_register(&nf_conntrack_helper_ras[0]);
if (ret < 0)
goto err4;
ret = nf_conntrack_helper_register(&nf_conntrack_helper_ras[1]);
if (ret < 0)
goto err5;
pr_debug("nf_ct_h323: init success\n");
return 0;
err5:
nf_conntrack_helper_unregister(&nf_conntrack_helper_ras[0]);
err4:
nf_conntrack_helper_unregister(&nf_conntrack_helper_q931[1]);
err3:
nf_conntrack_helper_unregister(&nf_conntrack_helper_q931[0]);
err2:
nf_conntrack_helper_unregister(&nf_conntrack_helper_h245);
err1:
kfree(h323_buffer);
return ret;
}
/****************************************************************************/
module_init(nf_conntrack_h323_init);
module_exit(nf_conntrack_h323_fini);
EXPORT_SYMBOL_GPL(get_h225_addr);
EXPORT_SYMBOL_GPL(set_h245_addr_hook);
EXPORT_SYMBOL_GPL(set_h225_addr_hook);
EXPORT_SYMBOL_GPL(set_sig_addr_hook);
EXPORT_SYMBOL_GPL(set_ras_addr_hook);
EXPORT_SYMBOL_GPL(nat_rtp_rtcp_hook);
EXPORT_SYMBOL_GPL(nat_t120_hook);
EXPORT_SYMBOL_GPL(nat_h245_hook);
EXPORT_SYMBOL_GPL(nat_callforwarding_hook);
EXPORT_SYMBOL_GPL(nat_q931_hook);
MODULE_AUTHOR("Jing Min Zhao <zhaojingmin@users.sourceforge.net>");
MODULE_DESCRIPTION("H.323 connection tracking helper");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ip_conntrack_h323");
MODULE_ALIAS_NFCT_HELPER("h323");
| gpl-2.0 |
MyAOSP/kernel_moto_wingray | net/rose/rose_out.c | 4292 | 2864 | /*
* 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.
*
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/gfp.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <asm/system.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <net/rose.h>
/*
* This procedure is passed a buffer descriptor for an iframe. It builds
* the rest of the control part of the frame and then writes it out.
*/
static void rose_send_iframe(struct sock *sk, struct sk_buff *skb)
{
struct rose_sock *rose = rose_sk(sk);
if (skb == NULL)
return;
skb->data[2] |= (rose->vr << 5) & 0xE0;
skb->data[2] |= (rose->vs << 1) & 0x0E;
rose_start_idletimer(sk);
rose_transmit_link(skb, rose->neighbour);
}
void rose_kick(struct sock *sk)
{
struct rose_sock *rose = rose_sk(sk);
struct sk_buff *skb, *skbn;
unsigned short start, end;
if (rose->state != ROSE_STATE_3)
return;
if (rose->condition & ROSE_COND_PEER_RX_BUSY)
return;
if (!skb_peek(&sk->sk_write_queue))
return;
start = (skb_peek(&rose->ack_queue) == NULL) ? rose->va : rose->vs;
end = (rose->va + sysctl_rose_window_size) % ROSE_MODULUS;
if (start == end)
return;
rose->vs = start;
/*
* Transmit data until either we're out of data to send or
* the window is full.
*/
skb = skb_dequeue(&sk->sk_write_queue);
do {
if ((skbn = skb_clone(skb, GFP_ATOMIC)) == NULL) {
skb_queue_head(&sk->sk_write_queue, skb);
break;
}
skb_set_owner_w(skbn, sk);
/*
* Transmit the frame copy.
*/
rose_send_iframe(sk, skbn);
rose->vs = (rose->vs + 1) % ROSE_MODULUS;
/*
* Requeue the original data frame.
*/
skb_queue_tail(&rose->ack_queue, skb);
} while (rose->vs != end &&
(skb = skb_dequeue(&sk->sk_write_queue)) != NULL);
rose->vl = rose->vr;
rose->condition &= ~ROSE_COND_ACK_PENDING;
rose_stop_timer(sk);
}
/*
* The following routines are taken from page 170 of the 7th ARRL Computer
* Networking Conference paper, as is the whole state machine.
*/
void rose_enquiry_response(struct sock *sk)
{
struct rose_sock *rose = rose_sk(sk);
if (rose->condition & ROSE_COND_OWN_RX_BUSY)
rose_write_internal(sk, ROSE_RNR);
else
rose_write_internal(sk, ROSE_RR);
rose->vl = rose->vr;
rose->condition &= ~ROSE_COND_ACK_PENDING;
rose_stop_timer(sk);
}
| gpl-2.0 |
cmartinbaughman/shooter-ics-sense | arch/mips/pmc-sierra/msp71xx/msp_serial.c | 4548 | 3205 | /*
* The setup file for serial related hardware on PMC-Sierra MSP processors.
*
* Copyright 2005 PMC-Sierra, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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.
*
* 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/serial.h>
#include <linux/serial_core.h>
#include <linux/serial_reg.h>
#include <asm/bootinfo.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/serial.h>
#include <linux/serial_8250.h>
#include <msp_prom.h>
#include <msp_int.h>
#include <msp_regs.h>
void __init msp_serial_setup(void)
{
char *s;
char *endp;
struct uart_port up;
unsigned int uartclk;
memset(&up, 0, sizeof(up));
/* Check if clock was specified in environment */
s = prom_getenv("uartfreqhz");
if(!(s && *s && (uartclk = simple_strtoul(s, &endp, 10)) && *endp == 0))
uartclk = MSP_BASE_BAUD;
ppfinit("UART clock set to %d\n", uartclk);
/* Initialize first serial port */
up.mapbase = MSP_UART0_BASE;
up.membase = ioremap_nocache(up.mapbase, MSP_UART_REG_LEN);
up.irq = MSP_INT_UART0;
up.uartclk = uartclk;
up.regshift = 2;
up.iotype = UPIO_DWAPB; /* UPIO_MEM like */
up.flags = ASYNC_BOOT_AUTOCONF | ASYNC_SKIP_TEST;
up.type = PORT_16550A;
up.line = 0;
up.private_data = (void*)UART0_STATUS_REG;
if (early_serial_setup(&up))
printk(KERN_ERR "Early serial init of port 0 failed\n");
/* Initialize the second serial port, if one exists */
switch (mips_machtype) {
case MACH_MSP4200_EVAL:
case MACH_MSP4200_GW:
case MACH_MSP4200_FPGA:
case MACH_MSP7120_EVAL:
case MACH_MSP7120_GW:
case MACH_MSP7120_FPGA:
/* Enable UART1 on MSP4200 and MSP7120 */
*GPIO_CFG2_REG = 0x00002299;
break;
default:
return; /* No second serial port, good-bye. */
}
up.mapbase = MSP_UART1_BASE;
up.membase = ioremap_nocache(up.mapbase, MSP_UART_REG_LEN);
up.irq = MSP_INT_UART1;
up.line = 1;
up.private_data = (void*)UART1_STATUS_REG;
if (early_serial_setup(&up))
printk(KERN_ERR "Early serial init of port 1 failed\n");
}
| gpl-2.0 |
mobius1484/Satori | drivers/watchdog/wm831x_wdt.c | 4804 | 7930 | /*
* Watchdog driver for the wm831x PMICs
*
* Copyright (C) 2009 Wolfson Microelectronics
*
* 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
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/watchdog.h>
#include <linux/uaccess.h>
#include <linux/gpio.h>
#include <linux/mfd/wm831x/core.h>
#include <linux/mfd/wm831x/pdata.h>
#include <linux/mfd/wm831x/watchdog.h>
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
struct wm831x_wdt_drvdata {
struct watchdog_device wdt;
struct wm831x *wm831x;
struct mutex lock;
int update_gpio;
int update_state;
};
/* We can't use the sub-second values here but they're included
* for completeness. */
static struct {
unsigned int time; /* Seconds */
u16 val; /* WDOG_TO value */
} wm831x_wdt_cfgs[] = {
{ 1, 2 },
{ 2, 3 },
{ 4, 4 },
{ 8, 5 },
{ 16, 6 },
{ 32, 7 },
{ 33, 7 }, /* Actually 32.768s so include both, others round down */
};
static int wm831x_wdt_start(struct watchdog_device *wdt_dev)
{
struct wm831x_wdt_drvdata *driver_data = watchdog_get_drvdata(wdt_dev);
struct wm831x *wm831x = driver_data->wm831x;
int ret;
mutex_lock(&driver_data->lock);
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_set_bits(wm831x, WM831X_WATCHDOG,
WM831X_WDOG_ENA, WM831X_WDOG_ENA);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev, "Failed to unlock security key: %d\n",
ret);
}
mutex_unlock(&driver_data->lock);
return ret;
}
static int wm831x_wdt_stop(struct watchdog_device *wdt_dev)
{
struct wm831x_wdt_drvdata *driver_data = watchdog_get_drvdata(wdt_dev);
struct wm831x *wm831x = driver_data->wm831x;
int ret;
mutex_lock(&driver_data->lock);
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_set_bits(wm831x, WM831X_WATCHDOG,
WM831X_WDOG_ENA, 0);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev, "Failed to unlock security key: %d\n",
ret);
}
mutex_unlock(&driver_data->lock);
return ret;
}
static int wm831x_wdt_ping(struct watchdog_device *wdt_dev)
{
struct wm831x_wdt_drvdata *driver_data = watchdog_get_drvdata(wdt_dev);
struct wm831x *wm831x = driver_data->wm831x;
int ret;
u16 reg;
mutex_lock(&driver_data->lock);
if (driver_data->update_gpio) {
gpio_set_value_cansleep(driver_data->update_gpio,
driver_data->update_state);
driver_data->update_state = !driver_data->update_state;
ret = 0;
goto out;
}
reg = wm831x_reg_read(wm831x, WM831X_WATCHDOG);
if (!(reg & WM831X_WDOG_RST_SRC)) {
dev_err(wm831x->dev, "Hardware watchdog update unsupported\n");
ret = -EINVAL;
goto out;
}
reg |= WM831X_WDOG_RESET;
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_reg_write(wm831x, WM831X_WATCHDOG, reg);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev, "Failed to unlock security key: %d\n",
ret);
}
out:
mutex_unlock(&driver_data->lock);
return ret;
}
static int wm831x_wdt_set_timeout(struct watchdog_device *wdt_dev,
unsigned int timeout)
{
struct wm831x_wdt_drvdata *driver_data = watchdog_get_drvdata(wdt_dev);
struct wm831x *wm831x = driver_data->wm831x;
int ret, i;
for (i = 0; i < ARRAY_SIZE(wm831x_wdt_cfgs); i++)
if (wm831x_wdt_cfgs[i].time == timeout)
break;
if (i == ARRAY_SIZE(wm831x_wdt_cfgs))
return -EINVAL;
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_set_bits(wm831x, WM831X_WATCHDOG,
WM831X_WDOG_TO_MASK,
wm831x_wdt_cfgs[i].val);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev, "Failed to unlock security key: %d\n",
ret);
}
wdt_dev->timeout = timeout;
return ret;
}
static const struct watchdog_info wm831x_wdt_info = {
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE,
.identity = "WM831x Watchdog",
};
static const struct watchdog_ops wm831x_wdt_ops = {
.owner = THIS_MODULE,
.start = wm831x_wdt_start,
.stop = wm831x_wdt_stop,
.ping = wm831x_wdt_ping,
.set_timeout = wm831x_wdt_set_timeout,
};
static int __devinit wm831x_wdt_probe(struct platform_device *pdev)
{
struct wm831x *wm831x = dev_get_drvdata(pdev->dev.parent);
struct wm831x_pdata *chip_pdata;
struct wm831x_watchdog_pdata *pdata;
struct wm831x_wdt_drvdata *driver_data;
struct watchdog_device *wm831x_wdt;
int reg, ret, i;
ret = wm831x_reg_read(wm831x, WM831X_WATCHDOG);
if (ret < 0) {
dev_err(wm831x->dev, "Failed to read watchdog status: %d\n",
ret);
goto err;
}
reg = ret;
if (reg & WM831X_WDOG_DEBUG)
dev_warn(wm831x->dev, "Watchdog is paused\n");
driver_data = devm_kzalloc(&pdev->dev, sizeof(*driver_data),
GFP_KERNEL);
if (!driver_data) {
dev_err(wm831x->dev, "Unable to alloacate watchdog device\n");
ret = -ENOMEM;
goto err;
}
mutex_init(&driver_data->lock);
driver_data->wm831x = wm831x;
wm831x_wdt = &driver_data->wdt;
wm831x_wdt->info = &wm831x_wdt_info;
wm831x_wdt->ops = &wm831x_wdt_ops;
watchdog_set_nowayout(wm831x_wdt, nowayout);
watchdog_set_drvdata(wm831x_wdt, driver_data);
reg = wm831x_reg_read(wm831x, WM831X_WATCHDOG);
reg &= WM831X_WDOG_TO_MASK;
for (i = 0; i < ARRAY_SIZE(wm831x_wdt_cfgs); i++)
if (wm831x_wdt_cfgs[i].val == reg)
break;
if (i == ARRAY_SIZE(wm831x_wdt_cfgs))
dev_warn(wm831x->dev,
"Unknown watchdog timeout: %x\n", reg);
else
wm831x_wdt->timeout = wm831x_wdt_cfgs[i].time;
/* Apply any configuration */
if (pdev->dev.parent->platform_data) {
chip_pdata = pdev->dev.parent->platform_data;
pdata = chip_pdata->watchdog;
} else {
pdata = NULL;
}
if (pdata) {
reg &= ~(WM831X_WDOG_SECACT_MASK | WM831X_WDOG_PRIMACT_MASK |
WM831X_WDOG_RST_SRC);
reg |= pdata->primary << WM831X_WDOG_PRIMACT_SHIFT;
reg |= pdata->secondary << WM831X_WDOG_SECACT_SHIFT;
reg |= pdata->software << WM831X_WDOG_RST_SRC_SHIFT;
if (pdata->update_gpio) {
ret = gpio_request(pdata->update_gpio,
"Watchdog update");
if (ret < 0) {
dev_err(wm831x->dev,
"Failed to request update GPIO: %d\n",
ret);
goto err;
}
ret = gpio_direction_output(pdata->update_gpio, 0);
if (ret != 0) {
dev_err(wm831x->dev,
"gpio_direction_output returned: %d\n",
ret);
goto err_gpio;
}
driver_data->update_gpio = pdata->update_gpio;
/* Make sure the watchdog takes hardware updates */
reg |= WM831X_WDOG_RST_SRC;
}
ret = wm831x_reg_unlock(wm831x);
if (ret == 0) {
ret = wm831x_reg_write(wm831x, WM831X_WATCHDOG, reg);
wm831x_reg_lock(wm831x);
} else {
dev_err(wm831x->dev,
"Failed to unlock security key: %d\n", ret);
goto err_gpio;
}
}
ret = watchdog_register_device(&driver_data->wdt);
if (ret != 0) {
dev_err(wm831x->dev, "watchdog_register_device() failed: %d\n",
ret);
goto err_gpio;
}
dev_set_drvdata(&pdev->dev, driver_data);
return 0;
err_gpio:
if (driver_data->update_gpio)
gpio_free(driver_data->update_gpio);
err:
return ret;
}
static int __devexit wm831x_wdt_remove(struct platform_device *pdev)
{
struct wm831x_wdt_drvdata *driver_data = dev_get_drvdata(&pdev->dev);
watchdog_unregister_device(&driver_data->wdt);
if (driver_data->update_gpio)
gpio_free(driver_data->update_gpio);
return 0;
}
static struct platform_driver wm831x_wdt_driver = {
.probe = wm831x_wdt_probe,
.remove = __devexit_p(wm831x_wdt_remove),
.driver = {
.name = "wm831x-watchdog",
},
};
module_platform_driver(wm831x_wdt_driver);
MODULE_AUTHOR("Mark Brown");
MODULE_DESCRIPTION("WM831x Watchdog");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:wm831x-watchdog");
| gpl-2.0 |
TEAM-RAZOR-DEVICES/kernel_lge_g3 | drivers/mtd/nand/docg4.c | 4804 | 39237 | /*
* Copyright © 2012 Mike Dunn <mikedunn@newsguy.com>
*
* mtd nand driver for M-Systems DiskOnChip G4
*
* 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.
*
* Tested on the Palm Treo 680. The G4 is also present on Toshiba Portege, Asus
* P526, some HTC smartphones (Wizard, Prophet, ...), O2 XDA Zinc, maybe others.
* Should work on these as well. Let me know!
*
* TODO:
*
* Mechanism for management of password-protected areas
*
* Hamming ecc when reading oob only
*
* According to the M-Sys documentation, this device is also available in a
* "dual-die" configuration having a 256MB capacity, but no mechanism for
* detecting this variant is documented. Currently this driver assumes 128MB
* capacity.
*
* Support for multiple cascaded devices ("floors"). Not sure which gadgets
* contain multiple G4s in a cascaded configuration, if any.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/export.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/bitops.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/bch.h>
#include <linux/bitrev.h>
/*
* You'll want to ignore badblocks if you're reading a partition that contains
* data written by the TrueFFS library (i.e., by PalmOS, Windows, etc), since
* it does not use mtd nand's method for marking bad blocks (using oob area).
* This will also skip the check of the "page written" flag.
*/
static bool ignore_badblocks;
module_param(ignore_badblocks, bool, 0);
MODULE_PARM_DESC(ignore_badblocks, "no badblock checking performed");
struct docg4_priv {
struct mtd_info *mtd;
struct device *dev;
void __iomem *virtadr;
int status;
struct {
unsigned int command;
int column;
int page;
} last_command;
uint8_t oob_buf[16];
uint8_t ecc_buf[7];
int oob_page;
struct bch_control *bch;
};
/*
* Defines prefixed with DOCG4 are unique to the diskonchip G4. All others are
* shared with other diskonchip devices (P3, G3 at least).
*
* Functions with names prefixed with docg4_ are mtd / nand interface functions
* (though they may also be called internally). All others are internal.
*/
#define DOC_IOSPACE_DATA 0x0800
/* register offsets */
#define DOC_CHIPID 0x1000
#define DOC_DEVICESELECT 0x100a
#define DOC_ASICMODE 0x100c
#define DOC_DATAEND 0x101e
#define DOC_NOP 0x103e
#define DOC_FLASHSEQUENCE 0x1032
#define DOC_FLASHCOMMAND 0x1034
#define DOC_FLASHADDRESS 0x1036
#define DOC_FLASHCONTROL 0x1038
#define DOC_ECCCONF0 0x1040
#define DOC_ECCCONF1 0x1042
#define DOC_HAMMINGPARITY 0x1046
#define DOC_BCH_SYNDROM(idx) (0x1048 + idx)
#define DOC_ASICMODECONFIRM 0x1072
#define DOC_CHIPID_INV 0x1074
#define DOC_POWERMODE 0x107c
#define DOCG4_MYSTERY_REG 0x1050
/* apparently used only to write oob bytes 6 and 7 */
#define DOCG4_OOB_6_7 0x1052
/* DOC_FLASHSEQUENCE register commands */
#define DOC_SEQ_RESET 0x00
#define DOCG4_SEQ_PAGE_READ 0x03
#define DOCG4_SEQ_FLUSH 0x29
#define DOCG4_SEQ_PAGEWRITE 0x16
#define DOCG4_SEQ_PAGEPROG 0x1e
#define DOCG4_SEQ_BLOCKERASE 0x24
/* DOC_FLASHCOMMAND register commands */
#define DOCG4_CMD_PAGE_READ 0x00
#define DOC_CMD_ERASECYCLE2 0xd0
#define DOCG4_CMD_FLUSH 0x70
#define DOCG4_CMD_READ2 0x30
#define DOC_CMD_PROG_BLOCK_ADDR 0x60
#define DOCG4_CMD_PAGEWRITE 0x80
#define DOC_CMD_PROG_CYCLE2 0x10
#define DOC_CMD_RESET 0xff
/* DOC_POWERMODE register bits */
#define DOC_POWERDOWN_READY 0x80
/* DOC_FLASHCONTROL register bits */
#define DOC_CTRL_CE 0x10
#define DOC_CTRL_UNKNOWN 0x40
#define DOC_CTRL_FLASHREADY 0x01
/* DOC_ECCCONF0 register bits */
#define DOC_ECCCONF0_READ_MODE 0x8000
#define DOC_ECCCONF0_UNKNOWN 0x2000
#define DOC_ECCCONF0_ECC_ENABLE 0x1000
#define DOC_ECCCONF0_DATA_BYTES_MASK 0x07ff
/* DOC_ECCCONF1 register bits */
#define DOC_ECCCONF1_BCH_SYNDROM_ERR 0x80
#define DOC_ECCCONF1_ECC_ENABLE 0x07
#define DOC_ECCCONF1_PAGE_IS_WRITTEN 0x20
/* DOC_ASICMODE register bits */
#define DOC_ASICMODE_RESET 0x00
#define DOC_ASICMODE_NORMAL 0x01
#define DOC_ASICMODE_POWERDOWN 0x02
#define DOC_ASICMODE_MDWREN 0x04
#define DOC_ASICMODE_BDETCT_RESET 0x08
#define DOC_ASICMODE_RSTIN_RESET 0x10
#define DOC_ASICMODE_RAM_WE 0x20
/* good status values read after read/write/erase operations */
#define DOCG4_PROGSTATUS_GOOD 0x51
#define DOCG4_PROGSTATUS_GOOD_2 0xe0
/*
* On read operations (page and oob-only), the first byte read from I/O reg is a
* status. On error, it reads 0x73; otherwise, it reads either 0x71 (first read
* after reset only) or 0x51, so bit 1 is presumed to be an error indicator.
*/
#define DOCG4_READ_ERROR 0x02 /* bit 1 indicates read error */
/* anatomy of the device */
#define DOCG4_CHIP_SIZE 0x8000000
#define DOCG4_PAGE_SIZE 0x200
#define DOCG4_PAGES_PER_BLOCK 0x200
#define DOCG4_BLOCK_SIZE (DOCG4_PAGES_PER_BLOCK * DOCG4_PAGE_SIZE)
#define DOCG4_NUMBLOCKS (DOCG4_CHIP_SIZE / DOCG4_BLOCK_SIZE)
#define DOCG4_OOB_SIZE 0x10
#define DOCG4_CHIP_SHIFT 27 /* log_2(DOCG4_CHIP_SIZE) */
#define DOCG4_PAGE_SHIFT 9 /* log_2(DOCG4_PAGE_SIZE) */
#define DOCG4_ERASE_SHIFT 18 /* log_2(DOCG4_BLOCK_SIZE) */
/* all but the last byte is included in ecc calculation */
#define DOCG4_BCH_SIZE (DOCG4_PAGE_SIZE + DOCG4_OOB_SIZE - 1)
#define DOCG4_USERDATA_LEN 520 /* 512 byte page plus 8 oob avail to user */
/* expected values from the ID registers */
#define DOCG4_IDREG1_VALUE 0x0400
#define DOCG4_IDREG2_VALUE 0xfbff
/* primitive polynomial used to build the Galois field used by hw ecc gen */
#define DOCG4_PRIMITIVE_POLY 0x4443
#define DOCG4_M 14 /* Galois field is of order 2^14 */
#define DOCG4_T 4 /* BCH alg corrects up to 4 bit errors */
#define DOCG4_FACTORY_BBT_PAGE 16 /* page where read-only factory bbt lives */
/*
* Oob bytes 0 - 6 are available to the user.
* Byte 7 is hamming ecc for first 7 bytes. Bytes 8 - 14 are hw-generated ecc.
* Byte 15 (the last) is used by the driver as a "page written" flag.
*/
static struct nand_ecclayout docg4_oobinfo = {
.eccbytes = 9,
.eccpos = {7, 8, 9, 10, 11, 12, 13, 14, 15},
.oobavail = 7,
.oobfree = { {0, 7} }
};
/*
* The device has a nop register which M-Sys claims is for the purpose of
* inserting precise delays. But beware; at least some operations fail if the
* nop writes are replaced with a generic delay!
*/
static inline void write_nop(void __iomem *docptr)
{
writew(0, docptr + DOC_NOP);
}
static void docg4_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
{
int i;
struct nand_chip *nand = mtd->priv;
uint16_t *p = (uint16_t *) buf;
len >>= 1;
for (i = 0; i < len; i++)
p[i] = readw(nand->IO_ADDR_R);
}
static void docg4_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
{
int i;
struct nand_chip *nand = mtd->priv;
uint16_t *p = (uint16_t *) buf;
len >>= 1;
for (i = 0; i < len; i++)
writew(p[i], nand->IO_ADDR_W);
}
static int poll_status(struct docg4_priv *doc)
{
/*
* Busy-wait for the FLASHREADY bit to be set in the FLASHCONTROL
* register. Operations known to take a long time (e.g., block erase)
* should sleep for a while before calling this.
*/
uint16_t flash_status;
unsigned int timeo;
void __iomem *docptr = doc->virtadr;
dev_dbg(doc->dev, "%s...\n", __func__);
/* hardware quirk requires reading twice initially */
flash_status = readw(docptr + DOC_FLASHCONTROL);
timeo = 1000;
do {
cpu_relax();
flash_status = readb(docptr + DOC_FLASHCONTROL);
} while (!(flash_status & DOC_CTRL_FLASHREADY) && --timeo);
if (!timeo) {
dev_err(doc->dev, "%s: timed out!\n", __func__);
return NAND_STATUS_FAIL;
}
if (unlikely(timeo < 50))
dev_warn(doc->dev, "%s: nearly timed out; %d remaining\n",
__func__, timeo);
return 0;
}
static int docg4_wait(struct mtd_info *mtd, struct nand_chip *nand)
{
struct docg4_priv *doc = nand->priv;
int status = NAND_STATUS_WP; /* inverse logic?? */
dev_dbg(doc->dev, "%s...\n", __func__);
/* report any previously unreported error */
if (doc->status) {
status |= doc->status;
doc->status = 0;
return status;
}
status |= poll_status(doc);
return status;
}
static void docg4_select_chip(struct mtd_info *mtd, int chip)
{
/*
* Select among multiple cascaded chips ("floors"). Multiple floors are
* not yet supported, so the only valid non-negative value is 0.
*/
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
dev_dbg(doc->dev, "%s: chip %d\n", __func__, chip);
if (chip < 0)
return; /* deselected */
if (chip > 0)
dev_warn(doc->dev, "multiple floors currently unsupported\n");
writew(0, docptr + DOC_DEVICESELECT);
}
static void reset(struct mtd_info *mtd)
{
/* full device reset */
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
writew(DOC_ASICMODE_RESET | DOC_ASICMODE_MDWREN,
docptr + DOC_ASICMODE);
writew(~(DOC_ASICMODE_RESET | DOC_ASICMODE_MDWREN),
docptr + DOC_ASICMODECONFIRM);
write_nop(docptr);
writew(DOC_ASICMODE_NORMAL | DOC_ASICMODE_MDWREN,
docptr + DOC_ASICMODE);
writew(~(DOC_ASICMODE_NORMAL | DOC_ASICMODE_MDWREN),
docptr + DOC_ASICMODECONFIRM);
writew(DOC_ECCCONF1_ECC_ENABLE, docptr + DOC_ECCCONF1);
poll_status(doc);
}
static void read_hw_ecc(void __iomem *docptr, uint8_t *ecc_buf)
{
/* read the 7 hw-generated ecc bytes */
int i;
for (i = 0; i < 7; i++) { /* hw quirk; read twice */
ecc_buf[i] = readb(docptr + DOC_BCH_SYNDROM(i));
ecc_buf[i] = readb(docptr + DOC_BCH_SYNDROM(i));
}
}
static int correct_data(struct mtd_info *mtd, uint8_t *buf, int page)
{
/*
* Called after a page read when hardware reports bitflips.
* Up to four bitflips can be corrected.
*/
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
int i, numerrs, errpos[4];
const uint8_t blank_read_hwecc[8] = {
0xcf, 0x72, 0xfc, 0x1b, 0xa9, 0xc7, 0xb9, 0 };
read_hw_ecc(docptr, doc->ecc_buf); /* read 7 hw-generated ecc bytes */
/* check if read error is due to a blank page */
if (!memcmp(doc->ecc_buf, blank_read_hwecc, 7))
return 0; /* yes */
/* skip additional check of "written flag" if ignore_badblocks */
if (ignore_badblocks == false) {
/*
* If the hw ecc bytes are not those of a blank page, there's
* still a chance that the page is blank, but was read with
* errors. Check the "written flag" in last oob byte, which
* is set to zero when a page is written. If more than half
* the bits are set, assume a blank page. Unfortunately, the
* bit flips(s) are not reported in stats.
*/
if (doc->oob_buf[15]) {
int bit, numsetbits = 0;
unsigned long written_flag = doc->oob_buf[15];
for_each_set_bit(bit, &written_flag, 8)
numsetbits++;
if (numsetbits > 4) { /* assume blank */
dev_warn(doc->dev,
"error(s) in blank page "
"at offset %08x\n",
page * DOCG4_PAGE_SIZE);
return 0;
}
}
}
/*
* The hardware ecc unit produces oob_ecc ^ calc_ecc. The kernel's bch
* algorithm is used to decode this. However the hw operates on page
* data in a bit order that is the reverse of that of the bch alg,
* requiring that the bits be reversed on the result. Thanks to Ivan
* Djelic for his analysis!
*/
for (i = 0; i < 7; i++)
doc->ecc_buf[i] = bitrev8(doc->ecc_buf[i]);
numerrs = decode_bch(doc->bch, NULL, DOCG4_USERDATA_LEN, NULL,
doc->ecc_buf, NULL, errpos);
if (numerrs == -EBADMSG) {
dev_warn(doc->dev, "uncorrectable errors at offset %08x\n",
page * DOCG4_PAGE_SIZE);
return -EBADMSG;
}
BUG_ON(numerrs < 0); /* -EINVAL, or anything other than -EBADMSG */
/* undo last step in BCH alg (modulo mirroring not needed) */
for (i = 0; i < numerrs; i++)
errpos[i] = (errpos[i] & ~7)|(7-(errpos[i] & 7));
/* fix the errors */
for (i = 0; i < numerrs; i++) {
/* ignore if error within oob ecc bytes */
if (errpos[i] > DOCG4_USERDATA_LEN * 8)
continue;
/* if error within oob area preceeding ecc bytes... */
if (errpos[i] > DOCG4_PAGE_SIZE * 8)
change_bit(errpos[i] - DOCG4_PAGE_SIZE * 8,
(unsigned long *)doc->oob_buf);
else /* error in page data */
change_bit(errpos[i], (unsigned long *)buf);
}
dev_notice(doc->dev, "%d error(s) corrected at offset %08x\n",
numerrs, page * DOCG4_PAGE_SIZE);
return numerrs;
}
static uint8_t docg4_read_byte(struct mtd_info *mtd)
{
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
dev_dbg(doc->dev, "%s\n", __func__);
if (doc->last_command.command == NAND_CMD_STATUS) {
int status;
/*
* Previous nand command was status request, so nand
* infrastructure code expects to read the status here. If an
* error occurred in a previous operation, report it.
*/
doc->last_command.command = 0;
if (doc->status) {
status = doc->status;
doc->status = 0;
}
/* why is NAND_STATUS_WP inverse logic?? */
else
status = NAND_STATUS_WP | NAND_STATUS_READY;
return status;
}
dev_warn(doc->dev, "unexpectd call to read_byte()\n");
return 0;
}
static void write_addr(struct docg4_priv *doc, uint32_t docg4_addr)
{
/* write the four address bytes packed in docg4_addr to the device */
void __iomem *docptr = doc->virtadr;
writeb(docg4_addr & 0xff, docptr + DOC_FLASHADDRESS);
docg4_addr >>= 8;
writeb(docg4_addr & 0xff, docptr + DOC_FLASHADDRESS);
docg4_addr >>= 8;
writeb(docg4_addr & 0xff, docptr + DOC_FLASHADDRESS);
docg4_addr >>= 8;
writeb(docg4_addr & 0xff, docptr + DOC_FLASHADDRESS);
}
static int read_progstatus(struct docg4_priv *doc)
{
/*
* This apparently checks the status of programming. Done after an
* erasure, and after page data is written. On error, the status is
* saved, to be later retrieved by the nand infrastructure code.
*/
void __iomem *docptr = doc->virtadr;
/* status is read from the I/O reg */
uint16_t status1 = readw(docptr + DOC_IOSPACE_DATA);
uint16_t status2 = readw(docptr + DOC_IOSPACE_DATA);
uint16_t status3 = readw(docptr + DOCG4_MYSTERY_REG);
dev_dbg(doc->dev, "docg4: %s: %02x %02x %02x\n",
__func__, status1, status2, status3);
if (status1 != DOCG4_PROGSTATUS_GOOD
|| status2 != DOCG4_PROGSTATUS_GOOD_2
|| status3 != DOCG4_PROGSTATUS_GOOD_2) {
doc->status = NAND_STATUS_FAIL;
dev_warn(doc->dev, "read_progstatus failed: "
"%02x, %02x, %02x\n", status1, status2, status3);
return -EIO;
}
return 0;
}
static int pageprog(struct mtd_info *mtd)
{
/*
* Final step in writing a page. Writes the contents of its
* internal buffer out to the flash array, or some such.
*/
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
int retval = 0;
dev_dbg(doc->dev, "docg4: %s\n", __func__);
writew(DOCG4_SEQ_PAGEPROG, docptr + DOC_FLASHSEQUENCE);
writew(DOC_CMD_PROG_CYCLE2, docptr + DOC_FLASHCOMMAND);
write_nop(docptr);
write_nop(docptr);
/* Just busy-wait; usleep_range() slows things down noticeably. */
poll_status(doc);
writew(DOCG4_SEQ_FLUSH, docptr + DOC_FLASHSEQUENCE);
writew(DOCG4_CMD_FLUSH, docptr + DOC_FLASHCOMMAND);
writew(DOC_ECCCONF0_READ_MODE | 4, docptr + DOC_ECCCONF0);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
retval = read_progstatus(doc);
writew(0, docptr + DOC_DATAEND);
write_nop(docptr);
poll_status(doc);
write_nop(docptr);
return retval;
}
static void sequence_reset(struct mtd_info *mtd)
{
/* common starting sequence for all operations */
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
writew(DOC_CTRL_UNKNOWN | DOC_CTRL_CE, docptr + DOC_FLASHCONTROL);
writew(DOC_SEQ_RESET, docptr + DOC_FLASHSEQUENCE);
writew(DOC_CMD_RESET, docptr + DOC_FLASHCOMMAND);
write_nop(docptr);
write_nop(docptr);
poll_status(doc);
write_nop(docptr);
}
static void read_page_prologue(struct mtd_info *mtd, uint32_t docg4_addr)
{
/* first step in reading a page */
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
dev_dbg(doc->dev,
"docg4: %s: g4 page %08x\n", __func__, docg4_addr);
sequence_reset(mtd);
writew(DOCG4_SEQ_PAGE_READ, docptr + DOC_FLASHSEQUENCE);
writew(DOCG4_CMD_PAGE_READ, docptr + DOC_FLASHCOMMAND);
write_nop(docptr);
write_addr(doc, docg4_addr);
write_nop(docptr);
writew(DOCG4_CMD_READ2, docptr + DOC_FLASHCOMMAND);
write_nop(docptr);
write_nop(docptr);
poll_status(doc);
}
static void write_page_prologue(struct mtd_info *mtd, uint32_t docg4_addr)
{
/* first step in writing a page */
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
dev_dbg(doc->dev,
"docg4: %s: g4 addr: %x\n", __func__, docg4_addr);
sequence_reset(mtd);
writew(DOCG4_SEQ_PAGEWRITE, docptr + DOC_FLASHSEQUENCE);
writew(DOCG4_CMD_PAGEWRITE, docptr + DOC_FLASHCOMMAND);
write_nop(docptr);
write_addr(doc, docg4_addr);
write_nop(docptr);
write_nop(docptr);
poll_status(doc);
}
static uint32_t mtd_to_docg4_address(int page, int column)
{
/*
* Convert mtd address to format used by the device, 32 bit packed.
*
* Some notes on G4 addressing... The M-Sys documentation on this device
* claims that pages are 2K in length, and indeed, the format of the
* address used by the device reflects that. But within each page are
* four 512 byte "sub-pages", each with its own oob data that is
* read/written immediately after the 512 bytes of page data. This oob
* data contains the ecc bytes for the preceeding 512 bytes.
*
* Rather than tell the mtd nand infrastructure that page size is 2k,
* with four sub-pages each, we engage in a little subterfuge and tell
* the infrastructure code that pages are 512 bytes in size. This is
* done because during the course of reverse-engineering the device, I
* never observed an instance where an entire 2K "page" was read or
* written as a unit. Each "sub-page" is always addressed individually,
* its data read/written, and ecc handled before the next "sub-page" is
* addressed.
*
* This requires us to convert addresses passed by the mtd nand
* infrastructure code to those used by the device.
*
* The address that is written to the device consists of four bytes: the
* first two are the 2k page number, and the second is the index into
* the page. The index is in terms of 16-bit half-words and includes
* the preceeding oob data, so e.g., the index into the second
* "sub-page" is 0x108, and the full device address of the start of mtd
* page 0x201 is 0x00800108.
*/
int g4_page = page / 4; /* device's 2K page */
int g4_index = (page % 4) * 0x108 + column/2; /* offset into page */
return (g4_page << 16) | g4_index; /* pack */
}
static void docg4_command(struct mtd_info *mtd, unsigned command, int column,
int page_addr)
{
/* handle standard nand commands */
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
uint32_t g4_addr = mtd_to_docg4_address(page_addr, column);
dev_dbg(doc->dev, "%s %x, page_addr=%x, column=%x\n",
__func__, command, page_addr, column);
/*
* Save the command and its arguments. This enables emulation of
* standard flash devices, and also some optimizations.
*/
doc->last_command.command = command;
doc->last_command.column = column;
doc->last_command.page = page_addr;
switch (command) {
case NAND_CMD_RESET:
reset(mtd);
break;
case NAND_CMD_READ0:
read_page_prologue(mtd, g4_addr);
break;
case NAND_CMD_STATUS:
/* next call to read_byte() will expect a status */
break;
case NAND_CMD_SEQIN:
write_page_prologue(mtd, g4_addr);
/* hack for deferred write of oob bytes */
if (doc->oob_page == page_addr)
memcpy(nand->oob_poi, doc->oob_buf, 16);
break;
case NAND_CMD_PAGEPROG:
pageprog(mtd);
break;
/* we don't expect these, based on review of nand_base.c */
case NAND_CMD_READOOB:
case NAND_CMD_READID:
case NAND_CMD_ERASE1:
case NAND_CMD_ERASE2:
dev_warn(doc->dev, "docg4_command: "
"unexpected nand command 0x%x\n", command);
break;
}
}
static int read_page(struct mtd_info *mtd, struct nand_chip *nand,
uint8_t *buf, int page, bool use_ecc)
{
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
uint16_t status, edc_err, *buf16;
dev_dbg(doc->dev, "%s: page %08x\n", __func__, page);
writew(DOC_ECCCONF0_READ_MODE |
DOC_ECCCONF0_ECC_ENABLE |
DOC_ECCCONF0_UNKNOWN |
DOCG4_BCH_SIZE,
docptr + DOC_ECCCONF0);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
/* the 1st byte from the I/O reg is a status; the rest is page data */
status = readw(docptr + DOC_IOSPACE_DATA);
if (status & DOCG4_READ_ERROR) {
dev_err(doc->dev,
"docg4_read_page: bad status: 0x%02x\n", status);
writew(0, docptr + DOC_DATAEND);
return -EIO;
}
dev_dbg(doc->dev, "%s: status = 0x%x\n", __func__, status);
docg4_read_buf(mtd, buf, DOCG4_PAGE_SIZE); /* read the page data */
/*
* Diskonchips read oob immediately after a page read. Mtd
* infrastructure issues a separate command for reading oob after the
* page is read. So we save the oob bytes in a local buffer and just
* copy it if the next command reads oob from the same page.
*/
/* first 14 oob bytes read from I/O reg */
docg4_read_buf(mtd, doc->oob_buf, 14);
/* last 2 read from another reg */
buf16 = (uint16_t *)(doc->oob_buf + 14);
*buf16 = readw(docptr + DOCG4_MYSTERY_REG);
write_nop(docptr);
if (likely(use_ecc == true)) {
/* read the register that tells us if bitflip(s) detected */
edc_err = readw(docptr + DOC_ECCCONF1);
edc_err = readw(docptr + DOC_ECCCONF1);
dev_dbg(doc->dev, "%s: edc_err = 0x%02x\n", __func__, edc_err);
/* If bitflips are reported, attempt to correct with ecc */
if (edc_err & DOC_ECCCONF1_BCH_SYNDROM_ERR) {
int bits_corrected = correct_data(mtd, buf, page);
if (bits_corrected == -EBADMSG)
mtd->ecc_stats.failed++;
else
mtd->ecc_stats.corrected += bits_corrected;
}
}
writew(0, docptr + DOC_DATAEND);
return 0;
}
static int docg4_read_page_raw(struct mtd_info *mtd, struct nand_chip *nand,
uint8_t *buf, int page)
{
return read_page(mtd, nand, buf, page, false);
}
static int docg4_read_page(struct mtd_info *mtd, struct nand_chip *nand,
uint8_t *buf, int page)
{
return read_page(mtd, nand, buf, page, true);
}
static int docg4_read_oob(struct mtd_info *mtd, struct nand_chip *nand,
int page, int sndcmd)
{
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
uint16_t status;
dev_dbg(doc->dev, "%s: page %x\n", __func__, page);
/*
* Oob bytes are read as part of a normal page read. If the previous
* nand command was a read of the page whose oob is now being read, just
* copy the oob bytes that we saved in a local buffer and avoid a
* separate oob read.
*/
if (doc->last_command.command == NAND_CMD_READ0 &&
doc->last_command.page == page) {
memcpy(nand->oob_poi, doc->oob_buf, 16);
return 0;
}
/*
* Separate read of oob data only.
*/
docg4_command(mtd, NAND_CMD_READ0, nand->ecc.size, page);
writew(DOC_ECCCONF0_READ_MODE | DOCG4_OOB_SIZE, docptr + DOC_ECCCONF0);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
/* the 1st byte from the I/O reg is a status; the rest is oob data */
status = readw(docptr + DOC_IOSPACE_DATA);
if (status & DOCG4_READ_ERROR) {
dev_warn(doc->dev,
"docg4_read_oob failed: status = 0x%02x\n", status);
return -EIO;
}
dev_dbg(doc->dev, "%s: status = 0x%x\n", __func__, status);
docg4_read_buf(mtd, nand->oob_poi, 16);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
writew(0, docptr + DOC_DATAEND);
write_nop(docptr);
return 0;
}
static void docg4_erase_block(struct mtd_info *mtd, int page)
{
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
uint16_t g4_page;
dev_dbg(doc->dev, "%s: page %04x\n", __func__, page);
sequence_reset(mtd);
writew(DOCG4_SEQ_BLOCKERASE, docptr + DOC_FLASHSEQUENCE);
writew(DOC_CMD_PROG_BLOCK_ADDR, docptr + DOC_FLASHCOMMAND);
write_nop(docptr);
/* only 2 bytes of address are written to specify erase block */
g4_page = (uint16_t)(page / 4); /* to g4's 2k page addressing */
writeb(g4_page & 0xff, docptr + DOC_FLASHADDRESS);
g4_page >>= 8;
writeb(g4_page & 0xff, docptr + DOC_FLASHADDRESS);
write_nop(docptr);
/* start the erasure */
writew(DOC_CMD_ERASECYCLE2, docptr + DOC_FLASHCOMMAND);
write_nop(docptr);
write_nop(docptr);
usleep_range(500, 1000); /* erasure is long; take a snooze */
poll_status(doc);
writew(DOCG4_SEQ_FLUSH, docptr + DOC_FLASHSEQUENCE);
writew(DOCG4_CMD_FLUSH, docptr + DOC_FLASHCOMMAND);
writew(DOC_ECCCONF0_READ_MODE | 4, docptr + DOC_ECCCONF0);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
write_nop(docptr);
read_progstatus(doc);
writew(0, docptr + DOC_DATAEND);
write_nop(docptr);
poll_status(doc);
write_nop(docptr);
}
static void write_page(struct mtd_info *mtd, struct nand_chip *nand,
const uint8_t *buf, bool use_ecc)
{
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
uint8_t ecc_buf[8];
dev_dbg(doc->dev, "%s...\n", __func__);
writew(DOC_ECCCONF0_ECC_ENABLE |
DOC_ECCCONF0_UNKNOWN |
DOCG4_BCH_SIZE,
docptr + DOC_ECCCONF0);
write_nop(docptr);
/* write the page data */
docg4_write_buf16(mtd, buf, DOCG4_PAGE_SIZE);
/* oob bytes 0 through 5 are written to I/O reg */
docg4_write_buf16(mtd, nand->oob_poi, 6);
/* oob byte 6 written to a separate reg */
writew(nand->oob_poi[6], docptr + DOCG4_OOB_6_7);
write_nop(docptr);
write_nop(docptr);
/* write hw-generated ecc bytes to oob */
if (likely(use_ecc == true)) {
/* oob byte 7 is hamming code */
uint8_t hamming = readb(docptr + DOC_HAMMINGPARITY);
hamming = readb(docptr + DOC_HAMMINGPARITY); /* 2nd read */
writew(hamming, docptr + DOCG4_OOB_6_7);
write_nop(docptr);
/* read the 7 bch bytes from ecc regs */
read_hw_ecc(docptr, ecc_buf);
ecc_buf[7] = 0; /* clear the "page written" flag */
}
/* write user-supplied bytes to oob */
else {
writew(nand->oob_poi[7], docptr + DOCG4_OOB_6_7);
write_nop(docptr);
memcpy(ecc_buf, &nand->oob_poi[8], 8);
}
docg4_write_buf16(mtd, ecc_buf, 8);
write_nop(docptr);
write_nop(docptr);
writew(0, docptr + DOC_DATAEND);
write_nop(docptr);
}
static void docg4_write_page_raw(struct mtd_info *mtd, struct nand_chip *nand,
const uint8_t *buf)
{
return write_page(mtd, nand, buf, false);
}
static void docg4_write_page(struct mtd_info *mtd, struct nand_chip *nand,
const uint8_t *buf)
{
return write_page(mtd, nand, buf, true);
}
static int docg4_write_oob(struct mtd_info *mtd, struct nand_chip *nand,
int page)
{
/*
* Writing oob-only is not really supported, because MLC nand must write
* oob bytes at the same time as page data. Nonetheless, we save the
* oob buffer contents here, and then write it along with the page data
* if the same page is subsequently written. This allows user space
* utilities that write the oob data prior to the page data to work
* (e.g., nandwrite). The disdvantage is that, if the intention was to
* write oob only, the operation is quietly ignored. Also, oob can get
* corrupted if two concurrent processes are running nandwrite.
*/
/* note that bytes 7..14 are hw generated hamming/ecc and overwritten */
struct docg4_priv *doc = nand->priv;
doc->oob_page = page;
memcpy(doc->oob_buf, nand->oob_poi, 16);
return 0;
}
static int __init read_factory_bbt(struct mtd_info *mtd)
{
/*
* The device contains a read-only factory bad block table. Read it and
* update the memory-based bbt accordingly.
*/
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
uint32_t g4_addr = mtd_to_docg4_address(DOCG4_FACTORY_BBT_PAGE, 0);
uint8_t *buf;
int i, block, status;
buf = kzalloc(DOCG4_PAGE_SIZE, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
read_page_prologue(mtd, g4_addr);
status = docg4_read_page(mtd, nand, buf, DOCG4_FACTORY_BBT_PAGE);
if (status)
goto exit;
/*
* If no memory-based bbt was created, exit. This will happen if module
* parameter ignore_badblocks is set. Then why even call this function?
* For an unknown reason, block erase always fails if it's the first
* operation after device power-up. The above read ensures it never is.
* Ugly, I know.
*/
if (nand->bbt == NULL) /* no memory-based bbt */
goto exit;
/*
* Parse factory bbt and update memory-based bbt. Factory bbt format is
* simple: one bit per block, block numbers increase left to right (msb
* to lsb). Bit clear means bad block.
*/
for (i = block = 0; block < DOCG4_NUMBLOCKS; block += 8, i++) {
int bitnum;
unsigned long bits = ~buf[i];
for_each_set_bit(bitnum, &bits, 8) {
int badblock = block + 7 - bitnum;
nand->bbt[badblock / 4] |=
0x03 << ((badblock % 4) * 2);
mtd->ecc_stats.badblocks++;
dev_notice(doc->dev, "factory-marked bad block: %d\n",
badblock);
}
}
exit:
kfree(buf);
return status;
}
static int docg4_block_markbad(struct mtd_info *mtd, loff_t ofs)
{
/*
* Mark a block as bad. Bad blocks are marked in the oob area of the
* first page of the block. The default scan_bbt() in the nand
* infrastructure code works fine for building the memory-based bbt
* during initialization, as does the nand infrastructure function that
* checks if a block is bad by reading the bbt. This function replaces
* the nand default because writes to oob-only are not supported.
*/
int ret, i;
uint8_t *buf;
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
struct nand_bbt_descr *bbtd = nand->badblock_pattern;
int block = (int)(ofs >> nand->bbt_erase_shift);
int page = (int)(ofs >> nand->page_shift);
uint32_t g4_addr = mtd_to_docg4_address(page, 0);
dev_dbg(doc->dev, "%s: %08llx\n", __func__, ofs);
if (unlikely(ofs & (DOCG4_BLOCK_SIZE - 1)))
dev_warn(doc->dev, "%s: ofs %llx not start of block!\n",
__func__, ofs);
/* allocate blank buffer for page data */
buf = kzalloc(DOCG4_PAGE_SIZE, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
/* update bbt in memory */
nand->bbt[block / 4] |= 0x01 << ((block & 0x03) * 2);
/* write bit-wise negation of pattern to oob buffer */
memset(nand->oob_poi, 0xff, mtd->oobsize);
for (i = 0; i < bbtd->len; i++)
nand->oob_poi[bbtd->offs + i] = ~bbtd->pattern[i];
/* write first page of block */
write_page_prologue(mtd, g4_addr);
docg4_write_page(mtd, nand, buf);
ret = pageprog(mtd);
if (!ret)
mtd->ecc_stats.badblocks++;
kfree(buf);
return ret;
}
static int docg4_block_neverbad(struct mtd_info *mtd, loff_t ofs, int getchip)
{
/* only called when module_param ignore_badblocks is set */
return 0;
}
static int docg4_suspend(struct platform_device *pdev, pm_message_t state)
{
/*
* Put the device into "deep power-down" mode. Note that CE# must be
* deasserted for this to take effect. The xscale, e.g., can be
* configured to float this signal when the processor enters power-down,
* and a suitable pull-up ensures its deassertion.
*/
int i;
uint8_t pwr_down;
struct docg4_priv *doc = platform_get_drvdata(pdev);
void __iomem *docptr = doc->virtadr;
dev_dbg(doc->dev, "%s...\n", __func__);
/* poll the register that tells us we're ready to go to sleep */
for (i = 0; i < 10; i++) {
pwr_down = readb(docptr + DOC_POWERMODE);
if (pwr_down & DOC_POWERDOWN_READY)
break;
usleep_range(1000, 4000);
}
if (pwr_down & DOC_POWERDOWN_READY) {
dev_err(doc->dev, "suspend failed; "
"timeout polling DOC_POWERDOWN_READY\n");
return -EIO;
}
writew(DOC_ASICMODE_POWERDOWN | DOC_ASICMODE_MDWREN,
docptr + DOC_ASICMODE);
writew(~(DOC_ASICMODE_POWERDOWN | DOC_ASICMODE_MDWREN),
docptr + DOC_ASICMODECONFIRM);
write_nop(docptr);
return 0;
}
static int docg4_resume(struct platform_device *pdev)
{
/*
* Exit power-down. Twelve consecutive reads of the address below
* accomplishes this, assuming CE# has been asserted.
*/
struct docg4_priv *doc = platform_get_drvdata(pdev);
void __iomem *docptr = doc->virtadr;
int i;
dev_dbg(doc->dev, "%s...\n", __func__);
for (i = 0; i < 12; i++)
readb(docptr + 0x1fff);
return 0;
}
static void __init init_mtd_structs(struct mtd_info *mtd)
{
/* initialize mtd and nand data structures */
/*
* Note that some of the following initializations are not usually
* required within a nand driver because they are performed by the nand
* infrastructure code as part of nand_scan(). In this case they need
* to be initialized here because we skip call to nand_scan_ident() (the
* first half of nand_scan()). The call to nand_scan_ident() is skipped
* because for this device the chip id is not read in the manner of a
* standard nand device. Unfortunately, nand_scan_ident() does other
* things as well, such as call nand_set_defaults().
*/
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
mtd->size = DOCG4_CHIP_SIZE;
mtd->name = "Msys_Diskonchip_G4";
mtd->writesize = DOCG4_PAGE_SIZE;
mtd->erasesize = DOCG4_BLOCK_SIZE;
mtd->oobsize = DOCG4_OOB_SIZE;
nand->chipsize = DOCG4_CHIP_SIZE;
nand->chip_shift = DOCG4_CHIP_SHIFT;
nand->bbt_erase_shift = nand->phys_erase_shift = DOCG4_ERASE_SHIFT;
nand->chip_delay = 20;
nand->page_shift = DOCG4_PAGE_SHIFT;
nand->pagemask = 0x3ffff;
nand->badblockpos = NAND_LARGE_BADBLOCK_POS;
nand->badblockbits = 8;
nand->ecc.layout = &docg4_oobinfo;
nand->ecc.mode = NAND_ECC_HW_SYNDROME;
nand->ecc.size = DOCG4_PAGE_SIZE;
nand->ecc.prepad = 8;
nand->ecc.bytes = 8;
nand->ecc.strength = DOCG4_T;
nand->options =
NAND_BUSWIDTH_16 | NAND_NO_SUBPAGE_WRITE | NAND_NO_AUTOINCR;
nand->IO_ADDR_R = nand->IO_ADDR_W = doc->virtadr + DOC_IOSPACE_DATA;
nand->controller = &nand->hwcontrol;
spin_lock_init(&nand->controller->lock);
init_waitqueue_head(&nand->controller->wq);
/* methods */
nand->cmdfunc = docg4_command;
nand->waitfunc = docg4_wait;
nand->select_chip = docg4_select_chip;
nand->read_byte = docg4_read_byte;
nand->block_markbad = docg4_block_markbad;
nand->read_buf = docg4_read_buf;
nand->write_buf = docg4_write_buf16;
nand->scan_bbt = nand_default_bbt;
nand->erase_cmd = docg4_erase_block;
nand->ecc.read_page = docg4_read_page;
nand->ecc.write_page = docg4_write_page;
nand->ecc.read_page_raw = docg4_read_page_raw;
nand->ecc.write_page_raw = docg4_write_page_raw;
nand->ecc.read_oob = docg4_read_oob;
nand->ecc.write_oob = docg4_write_oob;
/*
* The way the nand infrastructure code is written, a memory-based bbt
* is not created if NAND_SKIP_BBTSCAN is set. With no memory bbt,
* nand->block_bad() is used. So when ignoring bad blocks, we skip the
* scan and define a dummy block_bad() which always returns 0.
*/
if (ignore_badblocks) {
nand->options |= NAND_SKIP_BBTSCAN;
nand->block_bad = docg4_block_neverbad;
}
}
static int __init read_id_reg(struct mtd_info *mtd)
{
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
void __iomem *docptr = doc->virtadr;
uint16_t id1, id2;
/* check for presence of g4 chip by reading id registers */
id1 = readw(docptr + DOC_CHIPID);
id1 = readw(docptr + DOCG4_MYSTERY_REG);
id2 = readw(docptr + DOC_CHIPID_INV);
id2 = readw(docptr + DOCG4_MYSTERY_REG);
if (id1 == DOCG4_IDREG1_VALUE && id2 == DOCG4_IDREG2_VALUE) {
dev_info(doc->dev,
"NAND device: 128MiB Diskonchip G4 detected\n");
return 0;
}
return -ENODEV;
}
static char const *part_probes[] = { "cmdlinepart", "saftlpart", NULL };
static int __init probe_docg4(struct platform_device *pdev)
{
struct mtd_info *mtd;
struct nand_chip *nand;
void __iomem *virtadr;
struct docg4_priv *doc;
int len, retval;
struct resource *r;
struct device *dev = &pdev->dev;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (r == NULL) {
dev_err(dev, "no io memory resource defined!\n");
return -ENODEV;
}
virtadr = ioremap(r->start, resource_size(r));
if (!virtadr) {
dev_err(dev, "Diskonchip ioremap failed: %pR\n", r);
return -EIO;
}
len = sizeof(struct mtd_info) + sizeof(struct nand_chip) +
sizeof(struct docg4_priv);
mtd = kzalloc(len, GFP_KERNEL);
if (mtd == NULL) {
retval = -ENOMEM;
goto fail;
}
nand = (struct nand_chip *) (mtd + 1);
doc = (struct docg4_priv *) (nand + 1);
mtd->priv = nand;
nand->priv = doc;
mtd->owner = THIS_MODULE;
doc->virtadr = virtadr;
doc->dev = dev;
init_mtd_structs(mtd);
/* initialize kernel bch algorithm */
doc->bch = init_bch(DOCG4_M, DOCG4_T, DOCG4_PRIMITIVE_POLY);
if (doc->bch == NULL) {
retval = -EINVAL;
goto fail;
}
platform_set_drvdata(pdev, doc);
reset(mtd);
retval = read_id_reg(mtd);
if (retval == -ENODEV) {
dev_warn(dev, "No diskonchip G4 device found.\n");
goto fail;
}
retval = nand_scan_tail(mtd);
if (retval)
goto fail;
retval = read_factory_bbt(mtd);
if (retval)
goto fail;
retval = mtd_device_parse_register(mtd, part_probes, NULL, NULL, 0);
if (retval)
goto fail;
doc->mtd = mtd;
return 0;
fail:
iounmap(virtadr);
if (mtd) {
/* re-declarations avoid compiler warning */
struct nand_chip *nand = mtd->priv;
struct docg4_priv *doc = nand->priv;
nand_release(mtd); /* deletes partitions and mtd devices */
platform_set_drvdata(pdev, NULL);
free_bch(doc->bch);
kfree(mtd);
}
return retval;
}
static int __exit cleanup_docg4(struct platform_device *pdev)
{
struct docg4_priv *doc = platform_get_drvdata(pdev);
nand_release(doc->mtd);
platform_set_drvdata(pdev, NULL);
free_bch(doc->bch);
kfree(doc->mtd);
iounmap(doc->virtadr);
return 0;
}
static struct platform_driver docg4_driver = {
.driver = {
.name = "docg4",
.owner = THIS_MODULE,
},
.suspend = docg4_suspend,
.resume = docg4_resume,
.remove = __exit_p(cleanup_docg4),
};
static int __init docg4_init(void)
{
return platform_driver_probe(&docg4_driver, probe_docg4);
}
static void __exit docg4_exit(void)
{
platform_driver_unregister(&docg4_driver);
}
module_init(docg4_init);
module_exit(docg4_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mike Dunn");
MODULE_DESCRIPTION("M-Systems DiskOnChip G4 device driver");
| gpl-2.0 |
smac0628/htc_gpe_51 | drivers/usb/serial/symbolserial.c | 4804 | 7880 | /*
* Symbol USB barcode to serial driver
*
* Copyright (C) 2009 Greg Kroah-Hartman <gregkh@suse.de>
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/slab.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/uaccess.h>
static bool debug;
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(0x05e0, 0x0600) },
{ },
};
MODULE_DEVICE_TABLE(usb, id_table);
/* This structure holds all of the individual device information */
struct symbol_private {
struct usb_device *udev;
struct usb_serial *serial;
struct usb_serial_port *port;
unsigned char *int_buffer;
struct urb *int_urb;
int buffer_size;
u8 bInterval;
u8 int_address;
spinlock_t lock; /* protects the following flags */
bool throttled;
bool actually_throttled;
bool rts;
};
static void symbol_int_callback(struct urb *urb)
{
struct symbol_private *priv = urb->context;
unsigned char *data = urb->transfer_buffer;
struct usb_serial_port *port = priv->port;
int status = urb->status;
struct tty_struct *tty;
int result;
int data_length;
dbg("%s - port %d", __func__, port->number);
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dbg("%s - urb shutting down with status: %d",
__func__, status);
return;
default:
dbg("%s - nonzero urb status received: %d",
__func__, status);
goto exit;
}
usb_serial_debug_data(debug, &port->dev, __func__, urb->actual_length,
data);
if (urb->actual_length > 1) {
data_length = urb->actual_length - 1;
/*
* Data from the device comes with a 1 byte header:
*
* <size of data>data...
* This is real data to be sent to the tty layer
* we pretty much just ignore the size and send everything
* else to the tty layer.
*/
tty = tty_port_tty_get(&port->port);
if (tty) {
tty_insert_flip_string(tty, &data[1], data_length);
tty_flip_buffer_push(tty);
tty_kref_put(tty);
}
} else {
dev_dbg(&priv->udev->dev,
"Improper amount of data received from the device, "
"%d bytes", urb->actual_length);
}
exit:
spin_lock(&priv->lock);
/* Continue trying to always read if we should */
if (!priv->throttled) {
usb_fill_int_urb(priv->int_urb, priv->udev,
usb_rcvintpipe(priv->udev,
priv->int_address),
priv->int_buffer, priv->buffer_size,
symbol_int_callback, priv, priv->bInterval);
result = usb_submit_urb(priv->int_urb, GFP_ATOMIC);
if (result)
dev_err(&port->dev,
"%s - failed resubmitting read urb, error %d\n",
__func__, result);
} else
priv->actually_throttled = true;
spin_unlock(&priv->lock);
}
static int symbol_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct symbol_private *priv = usb_get_serial_data(port->serial);
unsigned long flags;
int result = 0;
dbg("%s - port %d", __func__, port->number);
spin_lock_irqsave(&priv->lock, flags);
priv->throttled = false;
priv->actually_throttled = false;
priv->port = port;
spin_unlock_irqrestore(&priv->lock, flags);
/* Start reading from the device */
usb_fill_int_urb(priv->int_urb, priv->udev,
usb_rcvintpipe(priv->udev, priv->int_address),
priv->int_buffer, priv->buffer_size,
symbol_int_callback, priv, priv->bInterval);
result = usb_submit_urb(priv->int_urb, GFP_KERNEL);
if (result)
dev_err(&port->dev,
"%s - failed resubmitting read urb, error %d\n",
__func__, result);
return result;
}
static void symbol_close(struct usb_serial_port *port)
{
struct symbol_private *priv = usb_get_serial_data(port->serial);
dbg("%s - port %d", __func__, port->number);
/* shutdown our urbs */
usb_kill_urb(priv->int_urb);
}
static void symbol_throttle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct symbol_private *priv = usb_get_serial_data(port->serial);
dbg("%s - port %d", __func__, port->number);
spin_lock_irq(&priv->lock);
priv->throttled = true;
spin_unlock_irq(&priv->lock);
}
static void symbol_unthrottle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct symbol_private *priv = usb_get_serial_data(port->serial);
int result;
bool was_throttled;
dbg("%s - port %d", __func__, port->number);
spin_lock_irq(&priv->lock);
priv->throttled = false;
was_throttled = priv->actually_throttled;
priv->actually_throttled = false;
spin_unlock_irq(&priv->lock);
if (was_throttled) {
result = usb_submit_urb(priv->int_urb, GFP_KERNEL);
if (result)
dev_err(&port->dev,
"%s - failed submitting read urb, error %d\n",
__func__, result);
}
}
static int symbol_startup(struct usb_serial *serial)
{
struct symbol_private *priv;
struct usb_host_interface *intf;
int i;
int retval = -ENOMEM;
bool int_in_found = false;
/* create our private serial structure */
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (priv == NULL) {
dev_err(&serial->dev->dev, "%s - Out of memory\n", __func__);
return -ENOMEM;
}
spin_lock_init(&priv->lock);
priv->serial = serial;
priv->port = serial->port[0];
priv->udev = serial->dev;
/* find our interrupt endpoint */
intf = serial->interface->altsetting;
for (i = 0; i < intf->desc.bNumEndpoints; ++i) {
struct usb_endpoint_descriptor *endpoint;
endpoint = &intf->endpoint[i].desc;
if (!usb_endpoint_is_int_in(endpoint))
continue;
priv->int_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!priv->int_urb) {
dev_err(&priv->udev->dev, "out of memory\n");
goto error;
}
priv->buffer_size = usb_endpoint_maxp(endpoint) * 2;
priv->int_buffer = kmalloc(priv->buffer_size, GFP_KERNEL);
if (!priv->int_buffer) {
dev_err(&priv->udev->dev, "out of memory\n");
goto error;
}
priv->int_address = endpoint->bEndpointAddress;
priv->bInterval = endpoint->bInterval;
/* set up our int urb */
usb_fill_int_urb(priv->int_urb, priv->udev,
usb_rcvintpipe(priv->udev,
endpoint->bEndpointAddress),
priv->int_buffer, priv->buffer_size,
symbol_int_callback, priv, priv->bInterval);
int_in_found = true;
break;
}
if (!int_in_found) {
dev_err(&priv->udev->dev,
"Error - the proper endpoints were not found!\n");
goto error;
}
usb_set_serial_data(serial, priv);
return 0;
error:
usb_free_urb(priv->int_urb);
kfree(priv->int_buffer);
kfree(priv);
return retval;
}
static void symbol_disconnect(struct usb_serial *serial)
{
struct symbol_private *priv = usb_get_serial_data(serial);
dbg("%s", __func__);
usb_kill_urb(priv->int_urb);
usb_free_urb(priv->int_urb);
}
static void symbol_release(struct usb_serial *serial)
{
struct symbol_private *priv = usb_get_serial_data(serial);
dbg("%s", __func__);
kfree(priv->int_buffer);
kfree(priv);
}
static struct usb_driver symbol_driver = {
.name = "symbol",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table,
};
static struct usb_serial_driver symbol_device = {
.driver = {
.owner = THIS_MODULE,
.name = "symbol",
},
.id_table = id_table,
.num_ports = 1,
.attach = symbol_startup,
.open = symbol_open,
.close = symbol_close,
.disconnect = symbol_disconnect,
.release = symbol_release,
.throttle = symbol_throttle,
.unthrottle = symbol_unthrottle,
};
static struct usb_serial_driver * const serial_drivers[] = {
&symbol_device, NULL
};
module_usb_serial_driver(symbol_driver, serial_drivers);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
| gpl-2.0 |
lodr/codeaurora_kernel_msm | drivers/mtd/maps/lantiq-flash.c | 4804 | 5974 | /*
* 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.
*
* Copyright (C) 2004 Liu Peng Infineon IFAP DC COM CPE
* Copyright (C) 2010 John Crispin <blogic@openwrt.org>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/cfi.h>
#include <linux/platform_device.h>
#include <linux/mtd/physmap.h>
#include <lantiq_soc.h>
#include <lantiq_platform.h>
/*
* The NOR flash is connected to the same external bus unit (EBU) as PCI.
* To make PCI work we need to enable the endianness swapping for the address
* written to the EBU. This endianness swapping works for PCI correctly but
* fails for attached NOR devices. To workaround this we need to use a complex
* map. The workaround involves swapping all addresses whilst probing the chip.
* Once probing is complete we stop swapping the addresses but swizzle the
* unlock addresses to ensure that access to the NOR device works correctly.
*/
enum {
LTQ_NOR_PROBING,
LTQ_NOR_NORMAL
};
struct ltq_mtd {
struct resource *res;
struct mtd_info *mtd;
struct map_info *map;
};
static char ltq_map_name[] = "ltq_nor";
static const char *ltq_probe_types[] __devinitconst = { "cmdlinepart", NULL };
static map_word
ltq_read16(struct map_info *map, unsigned long adr)
{
unsigned long flags;
map_word temp;
if (map->map_priv_1 == LTQ_NOR_PROBING)
adr ^= 2;
spin_lock_irqsave(&ebu_lock, flags);
temp.x[0] = *(u16 *)(map->virt + adr);
spin_unlock_irqrestore(&ebu_lock, flags);
return temp;
}
static void
ltq_write16(struct map_info *map, map_word d, unsigned long adr)
{
unsigned long flags;
if (map->map_priv_1 == LTQ_NOR_PROBING)
adr ^= 2;
spin_lock_irqsave(&ebu_lock, flags);
*(u16 *)(map->virt + adr) = d.x[0];
spin_unlock_irqrestore(&ebu_lock, flags);
}
/*
* The following 2 functions copy data between iomem and a cached memory
* section. As memcpy() makes use of pre-fetching we cannot use it here.
* The normal alternative of using memcpy_{to,from}io also makes use of
* memcpy() on MIPS so it is not applicable either. We are therefore stuck
* with having to use our own loop.
*/
static void
ltq_copy_from(struct map_info *map, void *to,
unsigned long from, ssize_t len)
{
unsigned char *f = (unsigned char *)map->virt + from;
unsigned char *t = (unsigned char *)to;
unsigned long flags;
spin_lock_irqsave(&ebu_lock, flags);
while (len--)
*t++ = *f++;
spin_unlock_irqrestore(&ebu_lock, flags);
}
static void
ltq_copy_to(struct map_info *map, unsigned long to,
const void *from, ssize_t len)
{
unsigned char *f = (unsigned char *)from;
unsigned char *t = (unsigned char *)map->virt + to;
unsigned long flags;
spin_lock_irqsave(&ebu_lock, flags);
while (len--)
*t++ = *f++;
spin_unlock_irqrestore(&ebu_lock, flags);
}
static int __init
ltq_mtd_probe(struct platform_device *pdev)
{
struct physmap_flash_data *ltq_mtd_data = dev_get_platdata(&pdev->dev);
struct ltq_mtd *ltq_mtd;
struct resource *res;
struct cfi_private *cfi;
int err;
ltq_mtd = kzalloc(sizeof(struct ltq_mtd), GFP_KERNEL);
platform_set_drvdata(pdev, ltq_mtd);
ltq_mtd->res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!ltq_mtd->res) {
dev_err(&pdev->dev, "failed to get memory resource");
err = -ENOENT;
goto err_out;
}
res = devm_request_mem_region(&pdev->dev, ltq_mtd->res->start,
resource_size(ltq_mtd->res), dev_name(&pdev->dev));
if (!ltq_mtd->res) {
dev_err(&pdev->dev, "failed to request mem resource");
err = -EBUSY;
goto err_out;
}
ltq_mtd->map = kzalloc(sizeof(struct map_info), GFP_KERNEL);
ltq_mtd->map->phys = res->start;
ltq_mtd->map->size = resource_size(res);
ltq_mtd->map->virt = devm_ioremap_nocache(&pdev->dev,
ltq_mtd->map->phys, ltq_mtd->map->size);
if (!ltq_mtd->map->virt) {
dev_err(&pdev->dev, "failed to ioremap!\n");
err = -ENOMEM;
goto err_free;
}
ltq_mtd->map->name = ltq_map_name;
ltq_mtd->map->bankwidth = 2;
ltq_mtd->map->read = ltq_read16;
ltq_mtd->map->write = ltq_write16;
ltq_mtd->map->copy_from = ltq_copy_from;
ltq_mtd->map->copy_to = ltq_copy_to;
ltq_mtd->map->map_priv_1 = LTQ_NOR_PROBING;
ltq_mtd->mtd = do_map_probe("cfi_probe", ltq_mtd->map);
ltq_mtd->map->map_priv_1 = LTQ_NOR_NORMAL;
if (!ltq_mtd->mtd) {
dev_err(&pdev->dev, "probing failed\n");
err = -ENXIO;
goto err_free;
}
ltq_mtd->mtd->owner = THIS_MODULE;
cfi = ltq_mtd->map->fldrv_priv;
cfi->addr_unlock1 ^= 1;
cfi->addr_unlock2 ^= 1;
err = mtd_device_parse_register(ltq_mtd->mtd, ltq_probe_types, NULL,
ltq_mtd_data->parts,
ltq_mtd_data->nr_parts);
if (err) {
dev_err(&pdev->dev, "failed to add partitions\n");
goto err_destroy;
}
return 0;
err_destroy:
map_destroy(ltq_mtd->mtd);
err_free:
kfree(ltq_mtd->map);
err_out:
kfree(ltq_mtd);
return err;
}
static int __devexit
ltq_mtd_remove(struct platform_device *pdev)
{
struct ltq_mtd *ltq_mtd = platform_get_drvdata(pdev);
if (ltq_mtd) {
if (ltq_mtd->mtd) {
mtd_device_unregister(ltq_mtd->mtd);
map_destroy(ltq_mtd->mtd);
}
kfree(ltq_mtd->map);
kfree(ltq_mtd);
}
return 0;
}
static struct platform_driver ltq_mtd_driver = {
.remove = __devexit_p(ltq_mtd_remove),
.driver = {
.name = "ltq_nor",
.owner = THIS_MODULE,
},
};
static int __init
init_ltq_mtd(void)
{
int ret = platform_driver_probe(<q_mtd_driver, ltq_mtd_probe);
if (ret)
pr_err("ltq_nor: error registering platform driver");
return ret;
}
static void __exit
exit_ltq_mtd(void)
{
platform_driver_unregister(<q_mtd_driver);
}
module_init(init_ltq_mtd);
module_exit(exit_ltq_mtd);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("John Crispin <blogic@openwrt.org>");
MODULE_DESCRIPTION("Lantiq SoC NOR");
| gpl-2.0 |
jamison904/android_kernel_samsung_hlte | drivers/gpu/drm/exynos/exynos_drm_core.c | 5060 | 5461 | /* exynos_drm_core.c
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* Author:
* Inki Dae <inki.dae@samsung.com>
* Joonyoung Shim <jy0922.shim@samsung.com>
* Seung-Woo Kim <sw0312.kim@samsung.com>
*
* 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
* VA LINUX SYSTEMS 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.
*/
#include "drmP.h"
#include "exynos_drm_drv.h"
#include "exynos_drm_encoder.h"
#include "exynos_drm_connector.h"
#include "exynos_drm_fbdev.h"
static LIST_HEAD(exynos_drm_subdrv_list);
static struct drm_device *drm_dev;
static int exynos_drm_subdrv_probe(struct drm_device *dev,
struct exynos_drm_subdrv *subdrv)
{
struct drm_encoder *encoder;
struct drm_connector *connector;
DRM_DEBUG_DRIVER("%s\n", __FILE__);
if (subdrv->probe) {
int ret;
/*
* this probe callback would be called by sub driver
* after setting of all resources to this sub driver,
* such as clock, irq and register map are done or by load()
* of exynos drm driver.
*
* P.S. note that this driver is considered for modularization.
*/
ret = subdrv->probe(dev, subdrv->dev);
if (ret)
return ret;
}
if (!subdrv->manager)
return 0;
subdrv->manager->dev = subdrv->dev;
/* create and initialize a encoder for this sub driver. */
encoder = exynos_drm_encoder_create(dev, subdrv->manager,
(1 << MAX_CRTC) - 1);
if (!encoder) {
DRM_ERROR("failed to create encoder\n");
return -EFAULT;
}
/*
* create and initialize a connector for this sub driver and
* attach the encoder created above to the connector.
*/
connector = exynos_drm_connector_create(dev, encoder);
if (!connector) {
DRM_ERROR("failed to create connector\n");
encoder->funcs->destroy(encoder);
return -EFAULT;
}
subdrv->encoder = encoder;
subdrv->connector = connector;
return 0;
}
static void exynos_drm_subdrv_remove(struct drm_device *dev,
struct exynos_drm_subdrv *subdrv)
{
DRM_DEBUG_DRIVER("%s\n", __FILE__);
if (subdrv->remove)
subdrv->remove(dev);
if (subdrv->encoder) {
struct drm_encoder *encoder = subdrv->encoder;
encoder->funcs->destroy(encoder);
subdrv->encoder = NULL;
}
if (subdrv->connector) {
struct drm_connector *connector = subdrv->connector;
connector->funcs->destroy(connector);
subdrv->connector = NULL;
}
}
int exynos_drm_device_register(struct drm_device *dev)
{
struct exynos_drm_subdrv *subdrv, *n;
int err;
DRM_DEBUG_DRIVER("%s\n", __FILE__);
if (!dev)
return -EINVAL;
drm_dev = dev;
list_for_each_entry_safe(subdrv, n, &exynos_drm_subdrv_list, list) {
subdrv->drm_dev = dev;
err = exynos_drm_subdrv_probe(dev, subdrv);
if (err) {
DRM_DEBUG("exynos drm subdrv probe failed.\n");
list_del(&subdrv->list);
}
}
return 0;
}
EXPORT_SYMBOL_GPL(exynos_drm_device_register);
int exynos_drm_device_unregister(struct drm_device *dev)
{
struct exynos_drm_subdrv *subdrv;
DRM_DEBUG_DRIVER("%s\n", __FILE__);
if (!dev) {
WARN(1, "Unexpected drm device unregister!\n");
return -EINVAL;
}
list_for_each_entry(subdrv, &exynos_drm_subdrv_list, list)
exynos_drm_subdrv_remove(dev, subdrv);
drm_dev = NULL;
return 0;
}
EXPORT_SYMBOL_GPL(exynos_drm_device_unregister);
int exynos_drm_subdrv_register(struct exynos_drm_subdrv *subdrv)
{
DRM_DEBUG_DRIVER("%s\n", __FILE__);
if (!subdrv)
return -EINVAL;
list_add_tail(&subdrv->list, &exynos_drm_subdrv_list);
return 0;
}
EXPORT_SYMBOL_GPL(exynos_drm_subdrv_register);
int exynos_drm_subdrv_unregister(struct exynos_drm_subdrv *subdrv)
{
DRM_DEBUG_DRIVER("%s\n", __FILE__);
if (!subdrv)
return -EINVAL;
list_del(&subdrv->list);
return 0;
}
EXPORT_SYMBOL_GPL(exynos_drm_subdrv_unregister);
int exynos_drm_subdrv_open(struct drm_device *dev, struct drm_file *file)
{
struct exynos_drm_subdrv *subdrv;
int ret;
list_for_each_entry(subdrv, &exynos_drm_subdrv_list, list) {
if (subdrv->open) {
ret = subdrv->open(dev, subdrv->dev, file);
if (ret)
goto err;
}
}
return 0;
err:
list_for_each_entry_reverse(subdrv, &subdrv->list, list) {
if (subdrv->close)
subdrv->close(dev, subdrv->dev, file);
}
return ret;
}
EXPORT_SYMBOL_GPL(exynos_drm_subdrv_open);
void exynos_drm_subdrv_close(struct drm_device *dev, struct drm_file *file)
{
struct exynos_drm_subdrv *subdrv;
list_for_each_entry(subdrv, &exynos_drm_subdrv_list, list) {
if (subdrv->close)
subdrv->close(dev, subdrv->dev, file);
}
}
EXPORT_SYMBOL_GPL(exynos_drm_subdrv_close);
| gpl-2.0 |
Altaf-Mahdi/mako-kernel-old | arch/ia64/kernel/unwind_decoder.c | 14020 | 12293 | /*
* Copyright (C) 2000 Hewlett-Packard Co
* Copyright (C) 2000 David Mosberger-Tang <davidm@hpl.hp.com>
*
* Generic IA-64 unwind info decoder.
*
* This file is used both by the Linux kernel and objdump. Please keep
* the two copies of this file in sync.
*
* You need to customize the decoder by defining the following
* macros/constants before including this file:
*
* Types:
* unw_word Unsigned integer type with at least 64 bits
*
* Register names:
* UNW_REG_BSP
* UNW_REG_BSPSTORE
* UNW_REG_FPSR
* UNW_REG_LC
* UNW_REG_PFS
* UNW_REG_PR
* UNW_REG_RNAT
* UNW_REG_PSP
* UNW_REG_RP
* UNW_REG_UNAT
*
* Decoder action macros:
* UNW_DEC_BAD_CODE(code)
* UNW_DEC_ABI(fmt,abi,context,arg)
* UNW_DEC_BR_GR(fmt,brmask,gr,arg)
* UNW_DEC_BR_MEM(fmt,brmask,arg)
* UNW_DEC_COPY_STATE(fmt,label,arg)
* UNW_DEC_EPILOGUE(fmt,t,ecount,arg)
* UNW_DEC_FRGR_MEM(fmt,grmask,frmask,arg)
* UNW_DEC_FR_MEM(fmt,frmask,arg)
* UNW_DEC_GR_GR(fmt,grmask,gr,arg)
* UNW_DEC_GR_MEM(fmt,grmask,arg)
* UNW_DEC_LABEL_STATE(fmt,label,arg)
* UNW_DEC_MEM_STACK_F(fmt,t,size,arg)
* UNW_DEC_MEM_STACK_V(fmt,t,arg)
* UNW_DEC_PRIUNAT_GR(fmt,r,arg)
* UNW_DEC_PRIUNAT_WHEN_GR(fmt,t,arg)
* UNW_DEC_PRIUNAT_WHEN_MEM(fmt,t,arg)
* UNW_DEC_PRIUNAT_WHEN_PSPREL(fmt,pspoff,arg)
* UNW_DEC_PRIUNAT_WHEN_SPREL(fmt,spoff,arg)
* UNW_DEC_PROLOGUE(fmt,body,rlen,arg)
* UNW_DEC_PROLOGUE_GR(fmt,rlen,mask,grsave,arg)
* UNW_DEC_REG_PSPREL(fmt,reg,pspoff,arg)
* UNW_DEC_REG_REG(fmt,src,dst,arg)
* UNW_DEC_REG_SPREL(fmt,reg,spoff,arg)
* UNW_DEC_REG_WHEN(fmt,reg,t,arg)
* UNW_DEC_RESTORE(fmt,t,abreg,arg)
* UNW_DEC_RESTORE_P(fmt,qp,t,abreg,arg)
* UNW_DEC_SPILL_BASE(fmt,pspoff,arg)
* UNW_DEC_SPILL_MASK(fmt,imaskp,arg)
* UNW_DEC_SPILL_PSPREL(fmt,t,abreg,pspoff,arg)
* UNW_DEC_SPILL_PSPREL_P(fmt,qp,t,abreg,pspoff,arg)
* UNW_DEC_SPILL_REG(fmt,t,abreg,x,ytreg,arg)
* UNW_DEC_SPILL_REG_P(fmt,qp,t,abreg,x,ytreg,arg)
* UNW_DEC_SPILL_SPREL(fmt,t,abreg,spoff,arg)
* UNW_DEC_SPILL_SPREL_P(fmt,qp,t,abreg,pspoff,arg)
*/
static unw_word
unw_decode_uleb128 (unsigned char **dpp)
{
unsigned shift = 0;
unw_word byte, result = 0;
unsigned char *bp = *dpp;
while (1)
{
byte = *bp++;
result |= (byte & 0x7f) << shift;
if ((byte & 0x80) == 0)
break;
shift += 7;
}
*dpp = bp;
return result;
}
static unsigned char *
unw_decode_x1 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, abreg;
unw_word t, off;
byte1 = *dp++;
t = unw_decode_uleb128 (&dp);
off = unw_decode_uleb128 (&dp);
abreg = (byte1 & 0x7f);
if (byte1 & 0x80)
UNW_DEC_SPILL_SPREL(X1, t, abreg, off, arg);
else
UNW_DEC_SPILL_PSPREL(X1, t, abreg, off, arg);
return dp;
}
static unsigned char *
unw_decode_x2 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, byte2, abreg, x, ytreg;
unw_word t;
byte1 = *dp++; byte2 = *dp++;
t = unw_decode_uleb128 (&dp);
abreg = (byte1 & 0x7f);
ytreg = byte2;
x = (byte1 >> 7) & 1;
if ((byte1 & 0x80) == 0 && ytreg == 0)
UNW_DEC_RESTORE(X2, t, abreg, arg);
else
UNW_DEC_SPILL_REG(X2, t, abreg, x, ytreg, arg);
return dp;
}
static unsigned char *
unw_decode_x3 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, byte2, abreg, qp;
unw_word t, off;
byte1 = *dp++; byte2 = *dp++;
t = unw_decode_uleb128 (&dp);
off = unw_decode_uleb128 (&dp);
qp = (byte1 & 0x3f);
abreg = (byte2 & 0x7f);
if (byte1 & 0x80)
UNW_DEC_SPILL_SPREL_P(X3, qp, t, abreg, off, arg);
else
UNW_DEC_SPILL_PSPREL_P(X3, qp, t, abreg, off, arg);
return dp;
}
static unsigned char *
unw_decode_x4 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, byte2, byte3, qp, abreg, x, ytreg;
unw_word t;
byte1 = *dp++; byte2 = *dp++; byte3 = *dp++;
t = unw_decode_uleb128 (&dp);
qp = (byte1 & 0x3f);
abreg = (byte2 & 0x7f);
x = (byte2 >> 7) & 1;
ytreg = byte3;
if ((byte2 & 0x80) == 0 && byte3 == 0)
UNW_DEC_RESTORE_P(X4, qp, t, abreg, arg);
else
UNW_DEC_SPILL_REG_P(X4, qp, t, abreg, x, ytreg, arg);
return dp;
}
static unsigned char *
unw_decode_r1 (unsigned char *dp, unsigned char code, void *arg)
{
int body = (code & 0x20) != 0;
unw_word rlen;
rlen = (code & 0x1f);
UNW_DEC_PROLOGUE(R1, body, rlen, arg);
return dp;
}
static unsigned char *
unw_decode_r2 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, mask, grsave;
unw_word rlen;
byte1 = *dp++;
mask = ((code & 0x7) << 1) | ((byte1 >> 7) & 1);
grsave = (byte1 & 0x7f);
rlen = unw_decode_uleb128 (&dp);
UNW_DEC_PROLOGUE_GR(R2, rlen, mask, grsave, arg);
return dp;
}
static unsigned char *
unw_decode_r3 (unsigned char *dp, unsigned char code, void *arg)
{
unw_word rlen;
rlen = unw_decode_uleb128 (&dp);
UNW_DEC_PROLOGUE(R3, ((code & 0x3) == 1), rlen, arg);
return dp;
}
static unsigned char *
unw_decode_p1 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char brmask = (code & 0x1f);
UNW_DEC_BR_MEM(P1, brmask, arg);
return dp;
}
static unsigned char *
unw_decode_p2_p5 (unsigned char *dp, unsigned char code, void *arg)
{
if ((code & 0x10) == 0)
{
unsigned char byte1 = *dp++;
UNW_DEC_BR_GR(P2, ((code & 0xf) << 1) | ((byte1 >> 7) & 1),
(byte1 & 0x7f), arg);
}
else if ((code & 0x08) == 0)
{
unsigned char byte1 = *dp++, r, dst;
r = ((code & 0x7) << 1) | ((byte1 >> 7) & 1);
dst = (byte1 & 0x7f);
switch (r)
{
case 0: UNW_DEC_REG_GR(P3, UNW_REG_PSP, dst, arg); break;
case 1: UNW_DEC_REG_GR(P3, UNW_REG_RP, dst, arg); break;
case 2: UNW_DEC_REG_GR(P3, UNW_REG_PFS, dst, arg); break;
case 3: UNW_DEC_REG_GR(P3, UNW_REG_PR, dst, arg); break;
case 4: UNW_DEC_REG_GR(P3, UNW_REG_UNAT, dst, arg); break;
case 5: UNW_DEC_REG_GR(P3, UNW_REG_LC, dst, arg); break;
case 6: UNW_DEC_RP_BR(P3, dst, arg); break;
case 7: UNW_DEC_REG_GR(P3, UNW_REG_RNAT, dst, arg); break;
case 8: UNW_DEC_REG_GR(P3, UNW_REG_BSP, dst, arg); break;
case 9: UNW_DEC_REG_GR(P3, UNW_REG_BSPSTORE, dst, arg); break;
case 10: UNW_DEC_REG_GR(P3, UNW_REG_FPSR, dst, arg); break;
case 11: UNW_DEC_PRIUNAT_GR(P3, dst, arg); break;
default: UNW_DEC_BAD_CODE(r); break;
}
}
else if ((code & 0x7) == 0)
UNW_DEC_SPILL_MASK(P4, dp, arg);
else if ((code & 0x7) == 1)
{
unw_word grmask, frmask, byte1, byte2, byte3;
byte1 = *dp++; byte2 = *dp++; byte3 = *dp++;
grmask = ((byte1 >> 4) & 0xf);
frmask = ((byte1 & 0xf) << 16) | (byte2 << 8) | byte3;
UNW_DEC_FRGR_MEM(P5, grmask, frmask, arg);
}
else
UNW_DEC_BAD_CODE(code);
return dp;
}
static unsigned char *
unw_decode_p6 (unsigned char *dp, unsigned char code, void *arg)
{
int gregs = (code & 0x10) != 0;
unsigned char mask = (code & 0x0f);
if (gregs)
UNW_DEC_GR_MEM(P6, mask, arg);
else
UNW_DEC_FR_MEM(P6, mask, arg);
return dp;
}
static unsigned char *
unw_decode_p7_p10 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char r, byte1, byte2;
unw_word t, size;
if ((code & 0x10) == 0)
{
r = (code & 0xf);
t = unw_decode_uleb128 (&dp);
switch (r)
{
case 0:
size = unw_decode_uleb128 (&dp);
UNW_DEC_MEM_STACK_F(P7, t, size, arg);
break;
case 1: UNW_DEC_MEM_STACK_V(P7, t, arg); break;
case 2: UNW_DEC_SPILL_BASE(P7, t, arg); break;
case 3: UNW_DEC_REG_SPREL(P7, UNW_REG_PSP, t, arg); break;
case 4: UNW_DEC_REG_WHEN(P7, UNW_REG_RP, t, arg); break;
case 5: UNW_DEC_REG_PSPREL(P7, UNW_REG_RP, t, arg); break;
case 6: UNW_DEC_REG_WHEN(P7, UNW_REG_PFS, t, arg); break;
case 7: UNW_DEC_REG_PSPREL(P7, UNW_REG_PFS, t, arg); break;
case 8: UNW_DEC_REG_WHEN(P7, UNW_REG_PR, t, arg); break;
case 9: UNW_DEC_REG_PSPREL(P7, UNW_REG_PR, t, arg); break;
case 10: UNW_DEC_REG_WHEN(P7, UNW_REG_LC, t, arg); break;
case 11: UNW_DEC_REG_PSPREL(P7, UNW_REG_LC, t, arg); break;
case 12: UNW_DEC_REG_WHEN(P7, UNW_REG_UNAT, t, arg); break;
case 13: UNW_DEC_REG_PSPREL(P7, UNW_REG_UNAT, t, arg); break;
case 14: UNW_DEC_REG_WHEN(P7, UNW_REG_FPSR, t, arg); break;
case 15: UNW_DEC_REG_PSPREL(P7, UNW_REG_FPSR, t, arg); break;
default: UNW_DEC_BAD_CODE(r); break;
}
}
else
{
switch (code & 0xf)
{
case 0x0: /* p8 */
{
r = *dp++;
t = unw_decode_uleb128 (&dp);
switch (r)
{
case 1: UNW_DEC_REG_SPREL(P8, UNW_REG_RP, t, arg); break;
case 2: UNW_DEC_REG_SPREL(P8, UNW_REG_PFS, t, arg); break;
case 3: UNW_DEC_REG_SPREL(P8, UNW_REG_PR, t, arg); break;
case 4: UNW_DEC_REG_SPREL(P8, UNW_REG_LC, t, arg); break;
case 5: UNW_DEC_REG_SPREL(P8, UNW_REG_UNAT, t, arg); break;
case 6: UNW_DEC_REG_SPREL(P8, UNW_REG_FPSR, t, arg); break;
case 7: UNW_DEC_REG_WHEN(P8, UNW_REG_BSP, t, arg); break;
case 8: UNW_DEC_REG_PSPREL(P8, UNW_REG_BSP, t, arg); break;
case 9: UNW_DEC_REG_SPREL(P8, UNW_REG_BSP, t, arg); break;
case 10: UNW_DEC_REG_WHEN(P8, UNW_REG_BSPSTORE, t, arg); break;
case 11: UNW_DEC_REG_PSPREL(P8, UNW_REG_BSPSTORE, t, arg); break;
case 12: UNW_DEC_REG_SPREL(P8, UNW_REG_BSPSTORE, t, arg); break;
case 13: UNW_DEC_REG_WHEN(P8, UNW_REG_RNAT, t, arg); break;
case 14: UNW_DEC_REG_PSPREL(P8, UNW_REG_RNAT, t, arg); break;
case 15: UNW_DEC_REG_SPREL(P8, UNW_REG_RNAT, t, arg); break;
case 16: UNW_DEC_PRIUNAT_WHEN_GR(P8, t, arg); break;
case 17: UNW_DEC_PRIUNAT_PSPREL(P8, t, arg); break;
case 18: UNW_DEC_PRIUNAT_SPREL(P8, t, arg); break;
case 19: UNW_DEC_PRIUNAT_WHEN_MEM(P8, t, arg); break;
default: UNW_DEC_BAD_CODE(r); break;
}
}
break;
case 0x1:
byte1 = *dp++; byte2 = *dp++;
UNW_DEC_GR_GR(P9, (byte1 & 0xf), (byte2 & 0x7f), arg);
break;
case 0xf: /* p10 */
byte1 = *dp++; byte2 = *dp++;
UNW_DEC_ABI(P10, byte1, byte2, arg);
break;
case 0x9:
return unw_decode_x1 (dp, code, arg);
case 0xa:
return unw_decode_x2 (dp, code, arg);
case 0xb:
return unw_decode_x3 (dp, code, arg);
case 0xc:
return unw_decode_x4 (dp, code, arg);
default:
UNW_DEC_BAD_CODE(code);
break;
}
}
return dp;
}
static unsigned char *
unw_decode_b1 (unsigned char *dp, unsigned char code, void *arg)
{
unw_word label = (code & 0x1f);
if ((code & 0x20) != 0)
UNW_DEC_COPY_STATE(B1, label, arg);
else
UNW_DEC_LABEL_STATE(B1, label, arg);
return dp;
}
static unsigned char *
unw_decode_b2 (unsigned char *dp, unsigned char code, void *arg)
{
unw_word t;
t = unw_decode_uleb128 (&dp);
UNW_DEC_EPILOGUE(B2, t, (code & 0x1f), arg);
return dp;
}
static unsigned char *
unw_decode_b3_x4 (unsigned char *dp, unsigned char code, void *arg)
{
unw_word t, ecount, label;
if ((code & 0x10) == 0)
{
t = unw_decode_uleb128 (&dp);
ecount = unw_decode_uleb128 (&dp);
UNW_DEC_EPILOGUE(B3, t, ecount, arg);
}
else if ((code & 0x07) == 0)
{
label = unw_decode_uleb128 (&dp);
if ((code & 0x08) != 0)
UNW_DEC_COPY_STATE(B4, label, arg);
else
UNW_DEC_LABEL_STATE(B4, label, arg);
}
else
switch (code & 0x7)
{
case 1: return unw_decode_x1 (dp, code, arg);
case 2: return unw_decode_x2 (dp, code, arg);
case 3: return unw_decode_x3 (dp, code, arg);
case 4: return unw_decode_x4 (dp, code, arg);
default: UNW_DEC_BAD_CODE(code); break;
}
return dp;
}
typedef unsigned char *(*unw_decoder) (unsigned char *, unsigned char, void *);
static unw_decoder unw_decode_table[2][8] =
{
/* prologue table: */
{
unw_decode_r1, /* 0 */
unw_decode_r1,
unw_decode_r2,
unw_decode_r3,
unw_decode_p1, /* 4 */
unw_decode_p2_p5,
unw_decode_p6,
unw_decode_p7_p10
},
{
unw_decode_r1, /* 0 */
unw_decode_r1,
unw_decode_r2,
unw_decode_r3,
unw_decode_b1, /* 4 */
unw_decode_b1,
unw_decode_b2,
unw_decode_b3_x4
}
};
/*
* Decode one descriptor and return address of next descriptor.
*/
static inline unsigned char *
unw_decode (unsigned char *dp, int inside_body, void *arg)
{
unw_decoder decoder;
unsigned char code;
code = *dp++;
decoder = unw_decode_table[inside_body][code >> 5];
dp = (*decoder) (dp, code, arg);
return dp;
}
| gpl-2.0 |
spezi77/hellspawn-N4 | arch/ia64/kernel/unwind_decoder.c | 14020 | 12293 | /*
* Copyright (C) 2000 Hewlett-Packard Co
* Copyright (C) 2000 David Mosberger-Tang <davidm@hpl.hp.com>
*
* Generic IA-64 unwind info decoder.
*
* This file is used both by the Linux kernel and objdump. Please keep
* the two copies of this file in sync.
*
* You need to customize the decoder by defining the following
* macros/constants before including this file:
*
* Types:
* unw_word Unsigned integer type with at least 64 bits
*
* Register names:
* UNW_REG_BSP
* UNW_REG_BSPSTORE
* UNW_REG_FPSR
* UNW_REG_LC
* UNW_REG_PFS
* UNW_REG_PR
* UNW_REG_RNAT
* UNW_REG_PSP
* UNW_REG_RP
* UNW_REG_UNAT
*
* Decoder action macros:
* UNW_DEC_BAD_CODE(code)
* UNW_DEC_ABI(fmt,abi,context,arg)
* UNW_DEC_BR_GR(fmt,brmask,gr,arg)
* UNW_DEC_BR_MEM(fmt,brmask,arg)
* UNW_DEC_COPY_STATE(fmt,label,arg)
* UNW_DEC_EPILOGUE(fmt,t,ecount,arg)
* UNW_DEC_FRGR_MEM(fmt,grmask,frmask,arg)
* UNW_DEC_FR_MEM(fmt,frmask,arg)
* UNW_DEC_GR_GR(fmt,grmask,gr,arg)
* UNW_DEC_GR_MEM(fmt,grmask,arg)
* UNW_DEC_LABEL_STATE(fmt,label,arg)
* UNW_DEC_MEM_STACK_F(fmt,t,size,arg)
* UNW_DEC_MEM_STACK_V(fmt,t,arg)
* UNW_DEC_PRIUNAT_GR(fmt,r,arg)
* UNW_DEC_PRIUNAT_WHEN_GR(fmt,t,arg)
* UNW_DEC_PRIUNAT_WHEN_MEM(fmt,t,arg)
* UNW_DEC_PRIUNAT_WHEN_PSPREL(fmt,pspoff,arg)
* UNW_DEC_PRIUNAT_WHEN_SPREL(fmt,spoff,arg)
* UNW_DEC_PROLOGUE(fmt,body,rlen,arg)
* UNW_DEC_PROLOGUE_GR(fmt,rlen,mask,grsave,arg)
* UNW_DEC_REG_PSPREL(fmt,reg,pspoff,arg)
* UNW_DEC_REG_REG(fmt,src,dst,arg)
* UNW_DEC_REG_SPREL(fmt,reg,spoff,arg)
* UNW_DEC_REG_WHEN(fmt,reg,t,arg)
* UNW_DEC_RESTORE(fmt,t,abreg,arg)
* UNW_DEC_RESTORE_P(fmt,qp,t,abreg,arg)
* UNW_DEC_SPILL_BASE(fmt,pspoff,arg)
* UNW_DEC_SPILL_MASK(fmt,imaskp,arg)
* UNW_DEC_SPILL_PSPREL(fmt,t,abreg,pspoff,arg)
* UNW_DEC_SPILL_PSPREL_P(fmt,qp,t,abreg,pspoff,arg)
* UNW_DEC_SPILL_REG(fmt,t,abreg,x,ytreg,arg)
* UNW_DEC_SPILL_REG_P(fmt,qp,t,abreg,x,ytreg,arg)
* UNW_DEC_SPILL_SPREL(fmt,t,abreg,spoff,arg)
* UNW_DEC_SPILL_SPREL_P(fmt,qp,t,abreg,pspoff,arg)
*/
static unw_word
unw_decode_uleb128 (unsigned char **dpp)
{
unsigned shift = 0;
unw_word byte, result = 0;
unsigned char *bp = *dpp;
while (1)
{
byte = *bp++;
result |= (byte & 0x7f) << shift;
if ((byte & 0x80) == 0)
break;
shift += 7;
}
*dpp = bp;
return result;
}
static unsigned char *
unw_decode_x1 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, abreg;
unw_word t, off;
byte1 = *dp++;
t = unw_decode_uleb128 (&dp);
off = unw_decode_uleb128 (&dp);
abreg = (byte1 & 0x7f);
if (byte1 & 0x80)
UNW_DEC_SPILL_SPREL(X1, t, abreg, off, arg);
else
UNW_DEC_SPILL_PSPREL(X1, t, abreg, off, arg);
return dp;
}
static unsigned char *
unw_decode_x2 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, byte2, abreg, x, ytreg;
unw_word t;
byte1 = *dp++; byte2 = *dp++;
t = unw_decode_uleb128 (&dp);
abreg = (byte1 & 0x7f);
ytreg = byte2;
x = (byte1 >> 7) & 1;
if ((byte1 & 0x80) == 0 && ytreg == 0)
UNW_DEC_RESTORE(X2, t, abreg, arg);
else
UNW_DEC_SPILL_REG(X2, t, abreg, x, ytreg, arg);
return dp;
}
static unsigned char *
unw_decode_x3 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, byte2, abreg, qp;
unw_word t, off;
byte1 = *dp++; byte2 = *dp++;
t = unw_decode_uleb128 (&dp);
off = unw_decode_uleb128 (&dp);
qp = (byte1 & 0x3f);
abreg = (byte2 & 0x7f);
if (byte1 & 0x80)
UNW_DEC_SPILL_SPREL_P(X3, qp, t, abreg, off, arg);
else
UNW_DEC_SPILL_PSPREL_P(X3, qp, t, abreg, off, arg);
return dp;
}
static unsigned char *
unw_decode_x4 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, byte2, byte3, qp, abreg, x, ytreg;
unw_word t;
byte1 = *dp++; byte2 = *dp++; byte3 = *dp++;
t = unw_decode_uleb128 (&dp);
qp = (byte1 & 0x3f);
abreg = (byte2 & 0x7f);
x = (byte2 >> 7) & 1;
ytreg = byte3;
if ((byte2 & 0x80) == 0 && byte3 == 0)
UNW_DEC_RESTORE_P(X4, qp, t, abreg, arg);
else
UNW_DEC_SPILL_REG_P(X4, qp, t, abreg, x, ytreg, arg);
return dp;
}
static unsigned char *
unw_decode_r1 (unsigned char *dp, unsigned char code, void *arg)
{
int body = (code & 0x20) != 0;
unw_word rlen;
rlen = (code & 0x1f);
UNW_DEC_PROLOGUE(R1, body, rlen, arg);
return dp;
}
static unsigned char *
unw_decode_r2 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char byte1, mask, grsave;
unw_word rlen;
byte1 = *dp++;
mask = ((code & 0x7) << 1) | ((byte1 >> 7) & 1);
grsave = (byte1 & 0x7f);
rlen = unw_decode_uleb128 (&dp);
UNW_DEC_PROLOGUE_GR(R2, rlen, mask, grsave, arg);
return dp;
}
static unsigned char *
unw_decode_r3 (unsigned char *dp, unsigned char code, void *arg)
{
unw_word rlen;
rlen = unw_decode_uleb128 (&dp);
UNW_DEC_PROLOGUE(R3, ((code & 0x3) == 1), rlen, arg);
return dp;
}
static unsigned char *
unw_decode_p1 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char brmask = (code & 0x1f);
UNW_DEC_BR_MEM(P1, brmask, arg);
return dp;
}
static unsigned char *
unw_decode_p2_p5 (unsigned char *dp, unsigned char code, void *arg)
{
if ((code & 0x10) == 0)
{
unsigned char byte1 = *dp++;
UNW_DEC_BR_GR(P2, ((code & 0xf) << 1) | ((byte1 >> 7) & 1),
(byte1 & 0x7f), arg);
}
else if ((code & 0x08) == 0)
{
unsigned char byte1 = *dp++, r, dst;
r = ((code & 0x7) << 1) | ((byte1 >> 7) & 1);
dst = (byte1 & 0x7f);
switch (r)
{
case 0: UNW_DEC_REG_GR(P3, UNW_REG_PSP, dst, arg); break;
case 1: UNW_DEC_REG_GR(P3, UNW_REG_RP, dst, arg); break;
case 2: UNW_DEC_REG_GR(P3, UNW_REG_PFS, dst, arg); break;
case 3: UNW_DEC_REG_GR(P3, UNW_REG_PR, dst, arg); break;
case 4: UNW_DEC_REG_GR(P3, UNW_REG_UNAT, dst, arg); break;
case 5: UNW_DEC_REG_GR(P3, UNW_REG_LC, dst, arg); break;
case 6: UNW_DEC_RP_BR(P3, dst, arg); break;
case 7: UNW_DEC_REG_GR(P3, UNW_REG_RNAT, dst, arg); break;
case 8: UNW_DEC_REG_GR(P3, UNW_REG_BSP, dst, arg); break;
case 9: UNW_DEC_REG_GR(P3, UNW_REG_BSPSTORE, dst, arg); break;
case 10: UNW_DEC_REG_GR(P3, UNW_REG_FPSR, dst, arg); break;
case 11: UNW_DEC_PRIUNAT_GR(P3, dst, arg); break;
default: UNW_DEC_BAD_CODE(r); break;
}
}
else if ((code & 0x7) == 0)
UNW_DEC_SPILL_MASK(P4, dp, arg);
else if ((code & 0x7) == 1)
{
unw_word grmask, frmask, byte1, byte2, byte3;
byte1 = *dp++; byte2 = *dp++; byte3 = *dp++;
grmask = ((byte1 >> 4) & 0xf);
frmask = ((byte1 & 0xf) << 16) | (byte2 << 8) | byte3;
UNW_DEC_FRGR_MEM(P5, grmask, frmask, arg);
}
else
UNW_DEC_BAD_CODE(code);
return dp;
}
static unsigned char *
unw_decode_p6 (unsigned char *dp, unsigned char code, void *arg)
{
int gregs = (code & 0x10) != 0;
unsigned char mask = (code & 0x0f);
if (gregs)
UNW_DEC_GR_MEM(P6, mask, arg);
else
UNW_DEC_FR_MEM(P6, mask, arg);
return dp;
}
static unsigned char *
unw_decode_p7_p10 (unsigned char *dp, unsigned char code, void *arg)
{
unsigned char r, byte1, byte2;
unw_word t, size;
if ((code & 0x10) == 0)
{
r = (code & 0xf);
t = unw_decode_uleb128 (&dp);
switch (r)
{
case 0:
size = unw_decode_uleb128 (&dp);
UNW_DEC_MEM_STACK_F(P7, t, size, arg);
break;
case 1: UNW_DEC_MEM_STACK_V(P7, t, arg); break;
case 2: UNW_DEC_SPILL_BASE(P7, t, arg); break;
case 3: UNW_DEC_REG_SPREL(P7, UNW_REG_PSP, t, arg); break;
case 4: UNW_DEC_REG_WHEN(P7, UNW_REG_RP, t, arg); break;
case 5: UNW_DEC_REG_PSPREL(P7, UNW_REG_RP, t, arg); break;
case 6: UNW_DEC_REG_WHEN(P7, UNW_REG_PFS, t, arg); break;
case 7: UNW_DEC_REG_PSPREL(P7, UNW_REG_PFS, t, arg); break;
case 8: UNW_DEC_REG_WHEN(P7, UNW_REG_PR, t, arg); break;
case 9: UNW_DEC_REG_PSPREL(P7, UNW_REG_PR, t, arg); break;
case 10: UNW_DEC_REG_WHEN(P7, UNW_REG_LC, t, arg); break;
case 11: UNW_DEC_REG_PSPREL(P7, UNW_REG_LC, t, arg); break;
case 12: UNW_DEC_REG_WHEN(P7, UNW_REG_UNAT, t, arg); break;
case 13: UNW_DEC_REG_PSPREL(P7, UNW_REG_UNAT, t, arg); break;
case 14: UNW_DEC_REG_WHEN(P7, UNW_REG_FPSR, t, arg); break;
case 15: UNW_DEC_REG_PSPREL(P7, UNW_REG_FPSR, t, arg); break;
default: UNW_DEC_BAD_CODE(r); break;
}
}
else
{
switch (code & 0xf)
{
case 0x0: /* p8 */
{
r = *dp++;
t = unw_decode_uleb128 (&dp);
switch (r)
{
case 1: UNW_DEC_REG_SPREL(P8, UNW_REG_RP, t, arg); break;
case 2: UNW_DEC_REG_SPREL(P8, UNW_REG_PFS, t, arg); break;
case 3: UNW_DEC_REG_SPREL(P8, UNW_REG_PR, t, arg); break;
case 4: UNW_DEC_REG_SPREL(P8, UNW_REG_LC, t, arg); break;
case 5: UNW_DEC_REG_SPREL(P8, UNW_REG_UNAT, t, arg); break;
case 6: UNW_DEC_REG_SPREL(P8, UNW_REG_FPSR, t, arg); break;
case 7: UNW_DEC_REG_WHEN(P8, UNW_REG_BSP, t, arg); break;
case 8: UNW_DEC_REG_PSPREL(P8, UNW_REG_BSP, t, arg); break;
case 9: UNW_DEC_REG_SPREL(P8, UNW_REG_BSP, t, arg); break;
case 10: UNW_DEC_REG_WHEN(P8, UNW_REG_BSPSTORE, t, arg); break;
case 11: UNW_DEC_REG_PSPREL(P8, UNW_REG_BSPSTORE, t, arg); break;
case 12: UNW_DEC_REG_SPREL(P8, UNW_REG_BSPSTORE, t, arg); break;
case 13: UNW_DEC_REG_WHEN(P8, UNW_REG_RNAT, t, arg); break;
case 14: UNW_DEC_REG_PSPREL(P8, UNW_REG_RNAT, t, arg); break;
case 15: UNW_DEC_REG_SPREL(P8, UNW_REG_RNAT, t, arg); break;
case 16: UNW_DEC_PRIUNAT_WHEN_GR(P8, t, arg); break;
case 17: UNW_DEC_PRIUNAT_PSPREL(P8, t, arg); break;
case 18: UNW_DEC_PRIUNAT_SPREL(P8, t, arg); break;
case 19: UNW_DEC_PRIUNAT_WHEN_MEM(P8, t, arg); break;
default: UNW_DEC_BAD_CODE(r); break;
}
}
break;
case 0x1:
byte1 = *dp++; byte2 = *dp++;
UNW_DEC_GR_GR(P9, (byte1 & 0xf), (byte2 & 0x7f), arg);
break;
case 0xf: /* p10 */
byte1 = *dp++; byte2 = *dp++;
UNW_DEC_ABI(P10, byte1, byte2, arg);
break;
case 0x9:
return unw_decode_x1 (dp, code, arg);
case 0xa:
return unw_decode_x2 (dp, code, arg);
case 0xb:
return unw_decode_x3 (dp, code, arg);
case 0xc:
return unw_decode_x4 (dp, code, arg);
default:
UNW_DEC_BAD_CODE(code);
break;
}
}
return dp;
}
static unsigned char *
unw_decode_b1 (unsigned char *dp, unsigned char code, void *arg)
{
unw_word label = (code & 0x1f);
if ((code & 0x20) != 0)
UNW_DEC_COPY_STATE(B1, label, arg);
else
UNW_DEC_LABEL_STATE(B1, label, arg);
return dp;
}
static unsigned char *
unw_decode_b2 (unsigned char *dp, unsigned char code, void *arg)
{
unw_word t;
t = unw_decode_uleb128 (&dp);
UNW_DEC_EPILOGUE(B2, t, (code & 0x1f), arg);
return dp;
}
static unsigned char *
unw_decode_b3_x4 (unsigned char *dp, unsigned char code, void *arg)
{
unw_word t, ecount, label;
if ((code & 0x10) == 0)
{
t = unw_decode_uleb128 (&dp);
ecount = unw_decode_uleb128 (&dp);
UNW_DEC_EPILOGUE(B3, t, ecount, arg);
}
else if ((code & 0x07) == 0)
{
label = unw_decode_uleb128 (&dp);
if ((code & 0x08) != 0)
UNW_DEC_COPY_STATE(B4, label, arg);
else
UNW_DEC_LABEL_STATE(B4, label, arg);
}
else
switch (code & 0x7)
{
case 1: return unw_decode_x1 (dp, code, arg);
case 2: return unw_decode_x2 (dp, code, arg);
case 3: return unw_decode_x3 (dp, code, arg);
case 4: return unw_decode_x4 (dp, code, arg);
default: UNW_DEC_BAD_CODE(code); break;
}
return dp;
}
typedef unsigned char *(*unw_decoder) (unsigned char *, unsigned char, void *);
static unw_decoder unw_decode_table[2][8] =
{
/* prologue table: */
{
unw_decode_r1, /* 0 */
unw_decode_r1,
unw_decode_r2,
unw_decode_r3,
unw_decode_p1, /* 4 */
unw_decode_p2_p5,
unw_decode_p6,
unw_decode_p7_p10
},
{
unw_decode_r1, /* 0 */
unw_decode_r1,
unw_decode_r2,
unw_decode_r3,
unw_decode_b1, /* 4 */
unw_decode_b1,
unw_decode_b2,
unw_decode_b3_x4
}
};
/*
* Decode one descriptor and return address of next descriptor.
*/
static inline unsigned char *
unw_decode (unsigned char *dp, int inside_body, void *arg)
{
unw_decoder decoder;
unsigned char code;
code = *dp++;
decoder = unw_decode_table[inside_body][code >> 5];
dp = (*decoder) (dp, code, arg);
return dp;
}
| gpl-2.0 |
HyochanPyo/kernel_3.18.9 | fs/xfs/xfs_qm.c | 197 | 48691 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_shared.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_bit.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_inode.h"
#include "xfs_ialloc.h"
#include "xfs_itable.h"
#include "xfs_quota.h"
#include "xfs_error.h"
#include "xfs_bmap.h"
#include "xfs_bmap_btree.h"
#include "xfs_trans.h"
#include "xfs_trans_space.h"
#include "xfs_qm.h"
#include "xfs_trace.h"
#include "xfs_icache.h"
#include "xfs_cksum.h"
#include "xfs_dinode.h"
/*
* The global quota manager. There is only one of these for the entire
* system, _not_ one per file system. XQM keeps track of the overall
* quota functionality, including maintaining the freelist and hash
* tables of dquots.
*/
STATIC int xfs_qm_init_quotainos(xfs_mount_t *);
STATIC int xfs_qm_init_quotainfo(xfs_mount_t *);
STATIC void xfs_qm_dqfree_one(struct xfs_dquot *dqp);
/*
* We use the batch lookup interface to iterate over the dquots as it
* currently is the only interface into the radix tree code that allows
* fuzzy lookups instead of exact matches. Holding the lock over multiple
* operations is fine as all callers are used either during mount/umount
* or quotaoff.
*/
#define XFS_DQ_LOOKUP_BATCH 32
STATIC int
xfs_qm_dquot_walk(
struct xfs_mount *mp,
int type,
int (*execute)(struct xfs_dquot *dqp, void *data),
void *data)
{
struct xfs_quotainfo *qi = mp->m_quotainfo;
struct radix_tree_root *tree = xfs_dquot_tree(qi, type);
uint32_t next_index;
int last_error = 0;
int skipped;
int nr_found;
restart:
skipped = 0;
next_index = 0;
nr_found = 0;
while (1) {
struct xfs_dquot *batch[XFS_DQ_LOOKUP_BATCH];
int error = 0;
int i;
mutex_lock(&qi->qi_tree_lock);
nr_found = radix_tree_gang_lookup(tree, (void **)batch,
next_index, XFS_DQ_LOOKUP_BATCH);
if (!nr_found) {
mutex_unlock(&qi->qi_tree_lock);
break;
}
for (i = 0; i < nr_found; i++) {
struct xfs_dquot *dqp = batch[i];
next_index = be32_to_cpu(dqp->q_core.d_id) + 1;
error = execute(batch[i], data);
if (error == -EAGAIN) {
skipped++;
continue;
}
if (error && last_error != -EFSCORRUPTED)
last_error = error;
}
mutex_unlock(&qi->qi_tree_lock);
/* bail out if the filesystem is corrupted. */
if (last_error == -EFSCORRUPTED) {
skipped = 0;
break;
}
}
if (skipped) {
delay(1);
goto restart;
}
return last_error;
}
/*
* Purge a dquot from all tracking data structures and free it.
*/
STATIC int
xfs_qm_dqpurge(
struct xfs_dquot *dqp,
void *data)
{
struct xfs_mount *mp = dqp->q_mount;
struct xfs_quotainfo *qi = mp->m_quotainfo;
xfs_dqlock(dqp);
if ((dqp->dq_flags & XFS_DQ_FREEING) || dqp->q_nrefs != 0) {
xfs_dqunlock(dqp);
return -EAGAIN;
}
dqp->dq_flags |= XFS_DQ_FREEING;
xfs_dqflock(dqp);
/*
* If we are turning this type of quotas off, we don't care
* about the dirty metadata sitting in this dquot. OTOH, if
* we're unmounting, we do care, so we flush it and wait.
*/
if (XFS_DQ_IS_DIRTY(dqp)) {
struct xfs_buf *bp = NULL;
int error;
/*
* We don't care about getting disk errors here. We need
* to purge this dquot anyway, so we go ahead regardless.
*/
error = xfs_qm_dqflush(dqp, &bp);
if (error) {
xfs_warn(mp, "%s: dquot %p flush failed",
__func__, dqp);
} else {
error = xfs_bwrite(bp);
xfs_buf_relse(bp);
}
xfs_dqflock(dqp);
}
ASSERT(atomic_read(&dqp->q_pincount) == 0);
ASSERT(XFS_FORCED_SHUTDOWN(mp) ||
!(dqp->q_logitem.qli_item.li_flags & XFS_LI_IN_AIL));
xfs_dqfunlock(dqp);
xfs_dqunlock(dqp);
radix_tree_delete(xfs_dquot_tree(qi, dqp->q_core.d_flags),
be32_to_cpu(dqp->q_core.d_id));
qi->qi_dquots--;
/*
* We move dquots to the freelist as soon as their reference count
* hits zero, so it really should be on the freelist here.
*/
ASSERT(!list_empty(&dqp->q_lru));
list_lru_del(&qi->qi_lru, &dqp->q_lru);
XFS_STATS_DEC(xs_qm_dquot_unused);
xfs_qm_dqdestroy(dqp);
return 0;
}
/*
* Purge the dquot cache.
*/
void
xfs_qm_dqpurge_all(
struct xfs_mount *mp,
uint flags)
{
if (flags & XFS_QMOPT_UQUOTA)
xfs_qm_dquot_walk(mp, XFS_DQ_USER, xfs_qm_dqpurge, NULL);
if (flags & XFS_QMOPT_GQUOTA)
xfs_qm_dquot_walk(mp, XFS_DQ_GROUP, xfs_qm_dqpurge, NULL);
if (flags & XFS_QMOPT_PQUOTA)
xfs_qm_dquot_walk(mp, XFS_DQ_PROJ, xfs_qm_dqpurge, NULL);
}
/*
* Just destroy the quotainfo structure.
*/
void
xfs_qm_unmount(
struct xfs_mount *mp)
{
if (mp->m_quotainfo) {
xfs_qm_dqpurge_all(mp, XFS_QMOPT_QUOTALL);
xfs_qm_destroy_quotainfo(mp);
}
}
/*
* Called from the vfsops layer.
*/
void
xfs_qm_unmount_quotas(
xfs_mount_t *mp)
{
/*
* Release the dquots that root inode, et al might be holding,
* before we flush quotas and blow away the quotainfo structure.
*/
ASSERT(mp->m_rootip);
xfs_qm_dqdetach(mp->m_rootip);
if (mp->m_rbmip)
xfs_qm_dqdetach(mp->m_rbmip);
if (mp->m_rsumip)
xfs_qm_dqdetach(mp->m_rsumip);
/*
* Release the quota inodes.
*/
if (mp->m_quotainfo) {
if (mp->m_quotainfo->qi_uquotaip) {
IRELE(mp->m_quotainfo->qi_uquotaip);
mp->m_quotainfo->qi_uquotaip = NULL;
}
if (mp->m_quotainfo->qi_gquotaip) {
IRELE(mp->m_quotainfo->qi_gquotaip);
mp->m_quotainfo->qi_gquotaip = NULL;
}
if (mp->m_quotainfo->qi_pquotaip) {
IRELE(mp->m_quotainfo->qi_pquotaip);
mp->m_quotainfo->qi_pquotaip = NULL;
}
}
}
STATIC int
xfs_qm_dqattach_one(
xfs_inode_t *ip,
xfs_dqid_t id,
uint type,
uint doalloc,
xfs_dquot_t **IO_idqpp)
{
xfs_dquot_t *dqp;
int error;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
error = 0;
/*
* See if we already have it in the inode itself. IO_idqpp is &i_udquot
* or &i_gdquot. This made the code look weird, but made the logic a lot
* simpler.
*/
dqp = *IO_idqpp;
if (dqp) {
trace_xfs_dqattach_found(dqp);
return 0;
}
/*
* Find the dquot from somewhere. This bumps the reference count of
* dquot and returns it locked. This can return ENOENT if dquot didn't
* exist on disk and we didn't ask it to allocate; ESRCH if quotas got
* turned off suddenly.
*/
error = xfs_qm_dqget(ip->i_mount, ip, id, type,
doalloc | XFS_QMOPT_DOWARN, &dqp);
if (error)
return error;
trace_xfs_dqattach_get(dqp);
/*
* dqget may have dropped and re-acquired the ilock, but it guarantees
* that the dquot returned is the one that should go in the inode.
*/
*IO_idqpp = dqp;
xfs_dqunlock(dqp);
return 0;
}
static bool
xfs_qm_need_dqattach(
struct xfs_inode *ip)
{
struct xfs_mount *mp = ip->i_mount;
if (!XFS_IS_QUOTA_RUNNING(mp))
return false;
if (!XFS_IS_QUOTA_ON(mp))
return false;
if (!XFS_NOT_DQATTACHED(mp, ip))
return false;
if (xfs_is_quota_inode(&mp->m_sb, ip->i_ino))
return false;
return true;
}
/*
* Given a locked inode, attach dquot(s) to it, taking U/G/P-QUOTAON
* into account.
* If XFS_QMOPT_DQALLOC, the dquot(s) will be allocated if needed.
* Inode may get unlocked and relocked in here, and the caller must deal with
* the consequences.
*/
int
xfs_qm_dqattach_locked(
xfs_inode_t *ip,
uint flags)
{
xfs_mount_t *mp = ip->i_mount;
int error = 0;
if (!xfs_qm_need_dqattach(ip))
return 0;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
if (XFS_IS_UQUOTA_ON(mp) && !ip->i_udquot) {
error = xfs_qm_dqattach_one(ip, ip->i_d.di_uid, XFS_DQ_USER,
flags & XFS_QMOPT_DQALLOC,
&ip->i_udquot);
if (error)
goto done;
ASSERT(ip->i_udquot);
}
if (XFS_IS_GQUOTA_ON(mp) && !ip->i_gdquot) {
error = xfs_qm_dqattach_one(ip, ip->i_d.di_gid, XFS_DQ_GROUP,
flags & XFS_QMOPT_DQALLOC,
&ip->i_gdquot);
if (error)
goto done;
ASSERT(ip->i_gdquot);
}
if (XFS_IS_PQUOTA_ON(mp) && !ip->i_pdquot) {
error = xfs_qm_dqattach_one(ip, xfs_get_projid(ip), XFS_DQ_PROJ,
flags & XFS_QMOPT_DQALLOC,
&ip->i_pdquot);
if (error)
goto done;
ASSERT(ip->i_pdquot);
}
done:
/*
* Don't worry about the dquots that we may have attached before any
* error - they'll get detached later if it has not already been done.
*/
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
return error;
}
int
xfs_qm_dqattach(
struct xfs_inode *ip,
uint flags)
{
int error;
if (!xfs_qm_need_dqattach(ip))
return 0;
xfs_ilock(ip, XFS_ILOCK_EXCL);
error = xfs_qm_dqattach_locked(ip, flags);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
return error;
}
/*
* Release dquots (and their references) if any.
* The inode should be locked EXCL except when this's called by
* xfs_ireclaim.
*/
void
xfs_qm_dqdetach(
xfs_inode_t *ip)
{
if (!(ip->i_udquot || ip->i_gdquot || ip->i_pdquot))
return;
trace_xfs_dquot_dqdetach(ip);
ASSERT(!xfs_is_quota_inode(&ip->i_mount->m_sb, ip->i_ino));
if (ip->i_udquot) {
xfs_qm_dqrele(ip->i_udquot);
ip->i_udquot = NULL;
}
if (ip->i_gdquot) {
xfs_qm_dqrele(ip->i_gdquot);
ip->i_gdquot = NULL;
}
if (ip->i_pdquot) {
xfs_qm_dqrele(ip->i_pdquot);
ip->i_pdquot = NULL;
}
}
struct xfs_qm_isolate {
struct list_head buffers;
struct list_head dispose;
};
static enum lru_status
xfs_qm_dquot_isolate(
struct list_head *item,
spinlock_t *lru_lock,
void *arg)
__releases(lru_lock) __acquires(lru_lock)
{
struct xfs_dquot *dqp = container_of(item,
struct xfs_dquot, q_lru);
struct xfs_qm_isolate *isol = arg;
if (!xfs_dqlock_nowait(dqp))
goto out_miss_busy;
/*
* This dquot has acquired a reference in the meantime remove it from
* the freelist and try again.
*/
if (dqp->q_nrefs) {
xfs_dqunlock(dqp);
XFS_STATS_INC(xs_qm_dqwants);
trace_xfs_dqreclaim_want(dqp);
list_del_init(&dqp->q_lru);
XFS_STATS_DEC(xs_qm_dquot_unused);
return LRU_REMOVED;
}
/*
* If the dquot is dirty, flush it. If it's already being flushed, just
* skip it so there is time for the IO to complete before we try to
* reclaim it again on the next LRU pass.
*/
if (!xfs_dqflock_nowait(dqp)) {
xfs_dqunlock(dqp);
goto out_miss_busy;
}
if (XFS_DQ_IS_DIRTY(dqp)) {
struct xfs_buf *bp = NULL;
int error;
trace_xfs_dqreclaim_dirty(dqp);
/* we have to drop the LRU lock to flush the dquot */
spin_unlock(lru_lock);
error = xfs_qm_dqflush(dqp, &bp);
if (error) {
xfs_warn(dqp->q_mount, "%s: dquot %p flush failed",
__func__, dqp);
goto out_unlock_dirty;
}
xfs_buf_delwri_queue(bp, &isol->buffers);
xfs_buf_relse(bp);
goto out_unlock_dirty;
}
xfs_dqfunlock(dqp);
/*
* Prevent lookups now that we are past the point of no return.
*/
dqp->dq_flags |= XFS_DQ_FREEING;
xfs_dqunlock(dqp);
ASSERT(dqp->q_nrefs == 0);
list_move_tail(&dqp->q_lru, &isol->dispose);
XFS_STATS_DEC(xs_qm_dquot_unused);
trace_xfs_dqreclaim_done(dqp);
XFS_STATS_INC(xs_qm_dqreclaims);
return LRU_REMOVED;
out_miss_busy:
trace_xfs_dqreclaim_busy(dqp);
XFS_STATS_INC(xs_qm_dqreclaim_misses);
return LRU_SKIP;
out_unlock_dirty:
trace_xfs_dqreclaim_busy(dqp);
XFS_STATS_INC(xs_qm_dqreclaim_misses);
xfs_dqunlock(dqp);
spin_lock(lru_lock);
return LRU_RETRY;
}
static unsigned long
xfs_qm_shrink_scan(
struct shrinker *shrink,
struct shrink_control *sc)
{
struct xfs_quotainfo *qi = container_of(shrink,
struct xfs_quotainfo, qi_shrinker);
struct xfs_qm_isolate isol;
unsigned long freed;
int error;
unsigned long nr_to_scan = sc->nr_to_scan;
if ((sc->gfp_mask & (__GFP_FS|__GFP_WAIT)) != (__GFP_FS|__GFP_WAIT))
return 0;
INIT_LIST_HEAD(&isol.buffers);
INIT_LIST_HEAD(&isol.dispose);
freed = list_lru_walk_node(&qi->qi_lru, sc->nid, xfs_qm_dquot_isolate, &isol,
&nr_to_scan);
error = xfs_buf_delwri_submit(&isol.buffers);
if (error)
xfs_warn(NULL, "%s: dquot reclaim failed", __func__);
while (!list_empty(&isol.dispose)) {
struct xfs_dquot *dqp;
dqp = list_first_entry(&isol.dispose, struct xfs_dquot, q_lru);
list_del_init(&dqp->q_lru);
xfs_qm_dqfree_one(dqp);
}
return freed;
}
static unsigned long
xfs_qm_shrink_count(
struct shrinker *shrink,
struct shrink_control *sc)
{
struct xfs_quotainfo *qi = container_of(shrink,
struct xfs_quotainfo, qi_shrinker);
return list_lru_count_node(&qi->qi_lru, sc->nid);
}
/*
* This initializes all the quota information that's kept in the
* mount structure
*/
STATIC int
xfs_qm_init_quotainfo(
xfs_mount_t *mp)
{
xfs_quotainfo_t *qinf;
int error;
xfs_dquot_t *dqp;
ASSERT(XFS_IS_QUOTA_RUNNING(mp));
qinf = mp->m_quotainfo = kmem_zalloc(sizeof(xfs_quotainfo_t), KM_SLEEP);
error = list_lru_init(&qinf->qi_lru);
if (error)
goto out_free_qinf;
/*
* See if quotainodes are setup, and if not, allocate them,
* and change the superblock accordingly.
*/
error = xfs_qm_init_quotainos(mp);
if (error)
goto out_free_lru;
INIT_RADIX_TREE(&qinf->qi_uquota_tree, GFP_NOFS);
INIT_RADIX_TREE(&qinf->qi_gquota_tree, GFP_NOFS);
INIT_RADIX_TREE(&qinf->qi_pquota_tree, GFP_NOFS);
mutex_init(&qinf->qi_tree_lock);
/* mutex used to serialize quotaoffs */
mutex_init(&qinf->qi_quotaofflock);
/* Precalc some constants */
qinf->qi_dqchunklen = XFS_FSB_TO_BB(mp, XFS_DQUOT_CLUSTER_SIZE_FSB);
qinf->qi_dqperchunk = xfs_calc_dquots_per_chunk(qinf->qi_dqchunklen);
mp->m_qflags |= (mp->m_sb.sb_qflags & XFS_ALL_QUOTA_CHKD);
/*
* We try to get the limits from the superuser's limits fields.
* This is quite hacky, but it is standard quota practice.
*
* We look at the USR dquot with id == 0 first, but if user quotas
* are not enabled we goto the GRP dquot with id == 0.
* We don't really care to keep separate default limits for user
* and group quotas, at least not at this point.
*
* Since we may not have done a quotacheck by this point, just read
* the dquot without attaching it to any hashtables or lists.
*/
error = xfs_qm_dqread(mp, 0,
XFS_IS_UQUOTA_RUNNING(mp) ? XFS_DQ_USER :
(XFS_IS_GQUOTA_RUNNING(mp) ? XFS_DQ_GROUP :
XFS_DQ_PROJ),
XFS_QMOPT_DOWARN, &dqp);
if (!error) {
xfs_disk_dquot_t *ddqp = &dqp->q_core;
/*
* The warnings and timers set the grace period given to
* a user or group before he or she can not perform any
* more writing. If it is zero, a default is used.
*/
qinf->qi_btimelimit = ddqp->d_btimer ?
be32_to_cpu(ddqp->d_btimer) : XFS_QM_BTIMELIMIT;
qinf->qi_itimelimit = ddqp->d_itimer ?
be32_to_cpu(ddqp->d_itimer) : XFS_QM_ITIMELIMIT;
qinf->qi_rtbtimelimit = ddqp->d_rtbtimer ?
be32_to_cpu(ddqp->d_rtbtimer) : XFS_QM_RTBTIMELIMIT;
qinf->qi_bwarnlimit = ddqp->d_bwarns ?
be16_to_cpu(ddqp->d_bwarns) : XFS_QM_BWARNLIMIT;
qinf->qi_iwarnlimit = ddqp->d_iwarns ?
be16_to_cpu(ddqp->d_iwarns) : XFS_QM_IWARNLIMIT;
qinf->qi_rtbwarnlimit = ddqp->d_rtbwarns ?
be16_to_cpu(ddqp->d_rtbwarns) : XFS_QM_RTBWARNLIMIT;
qinf->qi_bhardlimit = be64_to_cpu(ddqp->d_blk_hardlimit);
qinf->qi_bsoftlimit = be64_to_cpu(ddqp->d_blk_softlimit);
qinf->qi_ihardlimit = be64_to_cpu(ddqp->d_ino_hardlimit);
qinf->qi_isoftlimit = be64_to_cpu(ddqp->d_ino_softlimit);
qinf->qi_rtbhardlimit = be64_to_cpu(ddqp->d_rtb_hardlimit);
qinf->qi_rtbsoftlimit = be64_to_cpu(ddqp->d_rtb_softlimit);
xfs_qm_dqdestroy(dqp);
} else {
qinf->qi_btimelimit = XFS_QM_BTIMELIMIT;
qinf->qi_itimelimit = XFS_QM_ITIMELIMIT;
qinf->qi_rtbtimelimit = XFS_QM_RTBTIMELIMIT;
qinf->qi_bwarnlimit = XFS_QM_BWARNLIMIT;
qinf->qi_iwarnlimit = XFS_QM_IWARNLIMIT;
qinf->qi_rtbwarnlimit = XFS_QM_RTBWARNLIMIT;
}
qinf->qi_shrinker.count_objects = xfs_qm_shrink_count;
qinf->qi_shrinker.scan_objects = xfs_qm_shrink_scan;
qinf->qi_shrinker.seeks = DEFAULT_SEEKS;
qinf->qi_shrinker.flags = SHRINKER_NUMA_AWARE;
register_shrinker(&qinf->qi_shrinker);
return 0;
out_free_lru:
list_lru_destroy(&qinf->qi_lru);
out_free_qinf:
kmem_free(qinf);
mp->m_quotainfo = NULL;
return error;
}
/*
* Gets called when unmounting a filesystem or when all quotas get
* turned off.
* This purges the quota inodes, destroys locks and frees itself.
*/
void
xfs_qm_destroy_quotainfo(
xfs_mount_t *mp)
{
xfs_quotainfo_t *qi;
qi = mp->m_quotainfo;
ASSERT(qi != NULL);
unregister_shrinker(&qi->qi_shrinker);
list_lru_destroy(&qi->qi_lru);
if (qi->qi_uquotaip) {
IRELE(qi->qi_uquotaip);
qi->qi_uquotaip = NULL; /* paranoia */
}
if (qi->qi_gquotaip) {
IRELE(qi->qi_gquotaip);
qi->qi_gquotaip = NULL;
}
if (qi->qi_pquotaip) {
IRELE(qi->qi_pquotaip);
qi->qi_pquotaip = NULL;
}
mutex_destroy(&qi->qi_quotaofflock);
kmem_free(qi);
mp->m_quotainfo = NULL;
}
/*
* Create an inode and return with a reference already taken, but unlocked
* This is how we create quota inodes
*/
STATIC int
xfs_qm_qino_alloc(
xfs_mount_t *mp,
xfs_inode_t **ip,
__int64_t sbfields,
uint flags)
{
xfs_trans_t *tp;
int error;
int committed;
*ip = NULL;
/*
* With superblock that doesn't have separate pquotino, we
* share an inode between gquota and pquota. If the on-disk
* superblock has GQUOTA and the filesystem is now mounted
* with PQUOTA, just use sb_gquotino for sb_pquotino and
* vice-versa.
*/
if (!xfs_sb_version_has_pquotino(&mp->m_sb) &&
(flags & (XFS_QMOPT_PQUOTA|XFS_QMOPT_GQUOTA))) {
xfs_ino_t ino = NULLFSINO;
if ((flags & XFS_QMOPT_PQUOTA) &&
(mp->m_sb.sb_gquotino != NULLFSINO)) {
ino = mp->m_sb.sb_gquotino;
ASSERT(mp->m_sb.sb_pquotino == NULLFSINO);
} else if ((flags & XFS_QMOPT_GQUOTA) &&
(mp->m_sb.sb_pquotino != NULLFSINO)) {
ino = mp->m_sb.sb_pquotino;
ASSERT(mp->m_sb.sb_gquotino == NULLFSINO);
}
if (ino != NULLFSINO) {
error = xfs_iget(mp, NULL, ino, 0, 0, ip);
if (error)
return error;
mp->m_sb.sb_gquotino = NULLFSINO;
mp->m_sb.sb_pquotino = NULLFSINO;
}
}
tp = xfs_trans_alloc(mp, XFS_TRANS_QM_QINOCREATE);
error = xfs_trans_reserve(tp, &M_RES(mp)->tr_create,
XFS_QM_QINOCREATE_SPACE_RES(mp), 0);
if (error) {
xfs_trans_cancel(tp, 0);
return error;
}
if (!*ip) {
error = xfs_dir_ialloc(&tp, NULL, S_IFREG, 1, 0, 0, 1, ip,
&committed);
if (error) {
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES |
XFS_TRANS_ABORT);
return error;
}
}
/*
* Make the changes in the superblock, and log those too.
* sbfields arg may contain fields other than *QUOTINO;
* VERSIONNUM for example.
*/
spin_lock(&mp->m_sb_lock);
if (flags & XFS_QMOPT_SBVERSION) {
ASSERT(!xfs_sb_version_hasquota(&mp->m_sb));
ASSERT((sbfields & (XFS_SB_VERSIONNUM | XFS_SB_UQUOTINO |
XFS_SB_GQUOTINO | XFS_SB_PQUOTINO | XFS_SB_QFLAGS)) ==
(XFS_SB_VERSIONNUM | XFS_SB_UQUOTINO |
XFS_SB_GQUOTINO | XFS_SB_PQUOTINO |
XFS_SB_QFLAGS));
xfs_sb_version_addquota(&mp->m_sb);
mp->m_sb.sb_uquotino = NULLFSINO;
mp->m_sb.sb_gquotino = NULLFSINO;
mp->m_sb.sb_pquotino = NULLFSINO;
/* qflags will get updated fully _after_ quotacheck */
mp->m_sb.sb_qflags = mp->m_qflags & XFS_ALL_QUOTA_ACCT;
}
if (flags & XFS_QMOPT_UQUOTA)
mp->m_sb.sb_uquotino = (*ip)->i_ino;
else if (flags & XFS_QMOPT_GQUOTA)
mp->m_sb.sb_gquotino = (*ip)->i_ino;
else
mp->m_sb.sb_pquotino = (*ip)->i_ino;
spin_unlock(&mp->m_sb_lock);
xfs_mod_sb(tp, sbfields);
if ((error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES))) {
xfs_alert(mp, "%s failed (error %d)!", __func__, error);
return error;
}
return 0;
}
STATIC void
xfs_qm_reset_dqcounts(
xfs_mount_t *mp,
xfs_buf_t *bp,
xfs_dqid_t id,
uint type)
{
struct xfs_dqblk *dqb;
int j;
trace_xfs_reset_dqcounts(bp, _RET_IP_);
/*
* Reset all counters and timers. They'll be
* started afresh by xfs_qm_quotacheck.
*/
#ifdef DEBUG
j = XFS_FSB_TO_B(mp, XFS_DQUOT_CLUSTER_SIZE_FSB);
do_div(j, sizeof(xfs_dqblk_t));
ASSERT(mp->m_quotainfo->qi_dqperchunk == j);
#endif
dqb = bp->b_addr;
for (j = 0; j < mp->m_quotainfo->qi_dqperchunk; j++) {
struct xfs_disk_dquot *ddq;
ddq = (struct xfs_disk_dquot *)&dqb[j];
/*
* Do a sanity check, and if needed, repair the dqblk. Don't
* output any warnings because it's perfectly possible to
* find uninitialised dquot blks. See comment in xfs_dqcheck.
*/
xfs_dqcheck(mp, ddq, id+j, type, XFS_QMOPT_DQREPAIR,
"xfs_quotacheck");
/*
* Reset type in case we are reusing group quota file for
* project quotas or vice versa
*/
ddq->d_flags = type;
ddq->d_bcount = 0;
ddq->d_icount = 0;
ddq->d_rtbcount = 0;
ddq->d_btimer = 0;
ddq->d_itimer = 0;
ddq->d_rtbtimer = 0;
ddq->d_bwarns = 0;
ddq->d_iwarns = 0;
ddq->d_rtbwarns = 0;
if (xfs_sb_version_hascrc(&mp->m_sb)) {
xfs_update_cksum((char *)&dqb[j],
sizeof(struct xfs_dqblk),
XFS_DQUOT_CRC_OFF);
}
}
}
STATIC int
xfs_qm_dqiter_bufs(
struct xfs_mount *mp,
xfs_dqid_t firstid,
xfs_fsblock_t bno,
xfs_filblks_t blkcnt,
uint flags,
struct list_head *buffer_list)
{
struct xfs_buf *bp;
int error;
int type;
ASSERT(blkcnt > 0);
type = flags & XFS_QMOPT_UQUOTA ? XFS_DQ_USER :
(flags & XFS_QMOPT_PQUOTA ? XFS_DQ_PROJ : XFS_DQ_GROUP);
error = 0;
/*
* Blkcnt arg can be a very big number, and might even be
* larger than the log itself. So, we have to break it up into
* manageable-sized transactions.
* Note that we don't start a permanent transaction here; we might
* not be able to get a log reservation for the whole thing up front,
* and we don't really care to either, because we just discard
* everything if we were to crash in the middle of this loop.
*/
while (blkcnt--) {
error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,
XFS_FSB_TO_DADDR(mp, bno),
mp->m_quotainfo->qi_dqchunklen, 0, &bp,
&xfs_dquot_buf_ops);
/*
* CRC and validation errors will return a EFSCORRUPTED here. If
* this occurs, re-read without CRC validation so that we can
* repair the damage via xfs_qm_reset_dqcounts(). This process
* will leave a trace in the log indicating corruption has
* been detected.
*/
if (error == -EFSCORRUPTED) {
error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,
XFS_FSB_TO_DADDR(mp, bno),
mp->m_quotainfo->qi_dqchunklen, 0, &bp,
NULL);
}
if (error)
break;
/*
* A corrupt buffer might not have a verifier attached, so
* make sure we have the correct one attached before writeback
* occurs.
*/
bp->b_ops = &xfs_dquot_buf_ops;
xfs_qm_reset_dqcounts(mp, bp, firstid, type);
xfs_buf_delwri_queue(bp, buffer_list);
xfs_buf_relse(bp);
/* goto the next block. */
bno++;
firstid += mp->m_quotainfo->qi_dqperchunk;
}
return error;
}
/*
* Iterate over all allocated USR/GRP/PRJ dquots in the system, calling a
* caller supplied function for every chunk of dquots that we find.
*/
STATIC int
xfs_qm_dqiterate(
struct xfs_mount *mp,
struct xfs_inode *qip,
uint flags,
struct list_head *buffer_list)
{
struct xfs_bmbt_irec *map;
int i, nmaps; /* number of map entries */
int error; /* return value */
xfs_fileoff_t lblkno;
xfs_filblks_t maxlblkcnt;
xfs_dqid_t firstid;
xfs_fsblock_t rablkno;
xfs_filblks_t rablkcnt;
error = 0;
/*
* This looks racy, but we can't keep an inode lock across a
* trans_reserve. But, this gets called during quotacheck, and that
* happens only at mount time which is single threaded.
*/
if (qip->i_d.di_nblocks == 0)
return 0;
map = kmem_alloc(XFS_DQITER_MAP_SIZE * sizeof(*map), KM_SLEEP);
lblkno = 0;
maxlblkcnt = XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
do {
uint lock_mode;
nmaps = XFS_DQITER_MAP_SIZE;
/*
* We aren't changing the inode itself. Just changing
* some of its data. No new blocks are added here, and
* the inode is never added to the transaction.
*/
lock_mode = xfs_ilock_data_map_shared(qip);
error = xfs_bmapi_read(qip, lblkno, maxlblkcnt - lblkno,
map, &nmaps, 0);
xfs_iunlock(qip, lock_mode);
if (error)
break;
ASSERT(nmaps <= XFS_DQITER_MAP_SIZE);
for (i = 0; i < nmaps; i++) {
ASSERT(map[i].br_startblock != DELAYSTARTBLOCK);
ASSERT(map[i].br_blockcount);
lblkno += map[i].br_blockcount;
if (map[i].br_startblock == HOLESTARTBLOCK)
continue;
firstid = (xfs_dqid_t) map[i].br_startoff *
mp->m_quotainfo->qi_dqperchunk;
/*
* Do a read-ahead on the next extent.
*/
if ((i+1 < nmaps) &&
(map[i+1].br_startblock != HOLESTARTBLOCK)) {
rablkcnt = map[i+1].br_blockcount;
rablkno = map[i+1].br_startblock;
while (rablkcnt--) {
xfs_buf_readahead(mp->m_ddev_targp,
XFS_FSB_TO_DADDR(mp, rablkno),
mp->m_quotainfo->qi_dqchunklen,
&xfs_dquot_buf_ops);
rablkno++;
}
}
/*
* Iterate thru all the blks in the extent and
* reset the counters of all the dquots inside them.
*/
error = xfs_qm_dqiter_bufs(mp, firstid,
map[i].br_startblock,
map[i].br_blockcount,
flags, buffer_list);
if (error)
goto out;
}
} while (nmaps > 0);
out:
kmem_free(map);
return error;
}
/*
* Called by dqusage_adjust in doing a quotacheck.
*
* Given the inode, and a dquot id this updates both the incore dqout as well
* as the buffer copy. This is so that once the quotacheck is done, we can
* just log all the buffers, as opposed to logging numerous updates to
* individual dquots.
*/
STATIC int
xfs_qm_quotacheck_dqadjust(
struct xfs_inode *ip,
xfs_dqid_t id,
uint type,
xfs_qcnt_t nblks,
xfs_qcnt_t rtblks)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_dquot *dqp;
int error;
error = xfs_qm_dqget(mp, ip, id, type,
XFS_QMOPT_DQALLOC | XFS_QMOPT_DOWARN, &dqp);
if (error) {
/*
* Shouldn't be able to turn off quotas here.
*/
ASSERT(error != -ESRCH);
ASSERT(error != -ENOENT);
return error;
}
trace_xfs_dqadjust(dqp);
/*
* Adjust the inode count and the block count to reflect this inode's
* resource usage.
*/
be64_add_cpu(&dqp->q_core.d_icount, 1);
dqp->q_res_icount++;
if (nblks) {
be64_add_cpu(&dqp->q_core.d_bcount, nblks);
dqp->q_res_bcount += nblks;
}
if (rtblks) {
be64_add_cpu(&dqp->q_core.d_rtbcount, rtblks);
dqp->q_res_rtbcount += rtblks;
}
/*
* Set default limits, adjust timers (since we changed usages)
*
* There are no timers for the default values set in the root dquot.
*/
if (dqp->q_core.d_id) {
xfs_qm_adjust_dqlimits(mp, dqp);
xfs_qm_adjust_dqtimers(mp, &dqp->q_core);
}
dqp->dq_flags |= XFS_DQ_DIRTY;
xfs_qm_dqput(dqp);
return 0;
}
STATIC int
xfs_qm_get_rtblks(
xfs_inode_t *ip,
xfs_qcnt_t *O_rtblks)
{
xfs_filblks_t rtblks; /* total rt blks */
xfs_extnum_t idx; /* extent record index */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_extnum_t nextents; /* number of extent entries */
int error;
ASSERT(XFS_IS_REALTIME_INODE(ip));
ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
if ((error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK)))
return error;
}
rtblks = 0;
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
for (idx = 0; idx < nextents; idx++)
rtblks += xfs_bmbt_get_blockcount(xfs_iext_get_ext(ifp, idx));
*O_rtblks = (xfs_qcnt_t)rtblks;
return 0;
}
/*
* callback routine supplied to bulkstat(). Given an inumber, find its
* dquots and update them to account for resources taken by that inode.
*/
/* ARGSUSED */
STATIC int
xfs_qm_dqusage_adjust(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_ino_t ino, /* inode number to get data for */
void __user *buffer, /* not used */
int ubsize, /* not used */
int *ubused, /* not used */
int *res) /* result code value */
{
xfs_inode_t *ip;
xfs_qcnt_t nblks, rtblks = 0;
int error;
ASSERT(XFS_IS_QUOTA_RUNNING(mp));
/*
* rootino must have its resources accounted for, not so with the quota
* inodes.
*/
if (xfs_is_quota_inode(&mp->m_sb, ino)) {
*res = BULKSTAT_RV_NOTHING;
return -EINVAL;
}
/*
* We don't _need_ to take the ilock EXCL. However, the xfs_qm_dqget
* interface expects the inode to be exclusively locked because that's
* the case in all other instances. It's OK that we do this because
* quotacheck is done only at mount time.
*/
error = xfs_iget(mp, NULL, ino, 0, XFS_ILOCK_EXCL, &ip);
if (error) {
*res = BULKSTAT_RV_NOTHING;
return error;
}
ASSERT(ip->i_delayed_blks == 0);
if (XFS_IS_REALTIME_INODE(ip)) {
/*
* Walk thru the extent list and count the realtime blocks.
*/
error = xfs_qm_get_rtblks(ip, &rtblks);
if (error)
goto error0;
}
nblks = (xfs_qcnt_t)ip->i_d.di_nblocks - rtblks;
/*
* Add the (disk blocks and inode) resources occupied by this
* inode to its dquots. We do this adjustment in the incore dquot,
* and also copy the changes to its buffer.
* We don't care about putting these changes in a transaction
* envelope because if we crash in the middle of a 'quotacheck'
* we have to start from the beginning anyway.
* Once we're done, we'll log all the dquot bufs.
*
* The *QUOTA_ON checks below may look pretty racy, but quotachecks
* and quotaoffs don't race. (Quotachecks happen at mount time only).
*/
if (XFS_IS_UQUOTA_ON(mp)) {
error = xfs_qm_quotacheck_dqadjust(ip, ip->i_d.di_uid,
XFS_DQ_USER, nblks, rtblks);
if (error)
goto error0;
}
if (XFS_IS_GQUOTA_ON(mp)) {
error = xfs_qm_quotacheck_dqadjust(ip, ip->i_d.di_gid,
XFS_DQ_GROUP, nblks, rtblks);
if (error)
goto error0;
}
if (XFS_IS_PQUOTA_ON(mp)) {
error = xfs_qm_quotacheck_dqadjust(ip, xfs_get_projid(ip),
XFS_DQ_PROJ, nblks, rtblks);
if (error)
goto error0;
}
xfs_iunlock(ip, XFS_ILOCK_EXCL);
IRELE(ip);
*res = BULKSTAT_RV_DIDONE;
return 0;
error0:
xfs_iunlock(ip, XFS_ILOCK_EXCL);
IRELE(ip);
*res = BULKSTAT_RV_GIVEUP;
return error;
}
STATIC int
xfs_qm_flush_one(
struct xfs_dquot *dqp,
void *data)
{
struct list_head *buffer_list = data;
struct xfs_buf *bp = NULL;
int error = 0;
xfs_dqlock(dqp);
if (dqp->dq_flags & XFS_DQ_FREEING)
goto out_unlock;
if (!XFS_DQ_IS_DIRTY(dqp))
goto out_unlock;
xfs_dqflock(dqp);
error = xfs_qm_dqflush(dqp, &bp);
if (error)
goto out_unlock;
xfs_buf_delwri_queue(bp, buffer_list);
xfs_buf_relse(bp);
out_unlock:
xfs_dqunlock(dqp);
return error;
}
/*
* Walk thru all the filesystem inodes and construct a consistent view
* of the disk quota world. If the quotacheck fails, disable quotas.
*/
STATIC int
xfs_qm_quotacheck(
xfs_mount_t *mp)
{
int done, count, error, error2;
xfs_ino_t lastino;
size_t structsz;
uint flags;
LIST_HEAD (buffer_list);
struct xfs_inode *uip = mp->m_quotainfo->qi_uquotaip;
struct xfs_inode *gip = mp->m_quotainfo->qi_gquotaip;
struct xfs_inode *pip = mp->m_quotainfo->qi_pquotaip;
count = INT_MAX;
structsz = 1;
lastino = 0;
flags = 0;
ASSERT(uip || gip || pip);
ASSERT(XFS_IS_QUOTA_RUNNING(mp));
xfs_notice(mp, "Quotacheck needed: Please wait.");
/*
* First we go thru all the dquots on disk, USR and GRP/PRJ, and reset
* their counters to zero. We need a clean slate.
* We don't log our changes till later.
*/
if (uip) {
error = xfs_qm_dqiterate(mp, uip, XFS_QMOPT_UQUOTA,
&buffer_list);
if (error)
goto error_return;
flags |= XFS_UQUOTA_CHKD;
}
if (gip) {
error = xfs_qm_dqiterate(mp, gip, XFS_QMOPT_GQUOTA,
&buffer_list);
if (error)
goto error_return;
flags |= XFS_GQUOTA_CHKD;
}
if (pip) {
error = xfs_qm_dqiterate(mp, pip, XFS_QMOPT_PQUOTA,
&buffer_list);
if (error)
goto error_return;
flags |= XFS_PQUOTA_CHKD;
}
do {
/*
* Iterate thru all the inodes in the file system,
* adjusting the corresponding dquot counters in core.
*/
error = xfs_bulkstat(mp, &lastino, &count,
xfs_qm_dqusage_adjust,
structsz, NULL, &done);
if (error)
break;
} while (!done);
/*
* We've made all the changes that we need to make incore. Flush them
* down to disk buffers if everything was updated successfully.
*/
if (XFS_IS_UQUOTA_ON(mp)) {
error = xfs_qm_dquot_walk(mp, XFS_DQ_USER, xfs_qm_flush_one,
&buffer_list);
}
if (XFS_IS_GQUOTA_ON(mp)) {
error2 = xfs_qm_dquot_walk(mp, XFS_DQ_GROUP, xfs_qm_flush_one,
&buffer_list);
if (!error)
error = error2;
}
if (XFS_IS_PQUOTA_ON(mp)) {
error2 = xfs_qm_dquot_walk(mp, XFS_DQ_PROJ, xfs_qm_flush_one,
&buffer_list);
if (!error)
error = error2;
}
error2 = xfs_buf_delwri_submit(&buffer_list);
if (!error)
error = error2;
/*
* We can get this error if we couldn't do a dquot allocation inside
* xfs_qm_dqusage_adjust (via bulkstat). We don't care about the
* dirty dquots that might be cached, we just want to get rid of them
* and turn quotaoff. The dquots won't be attached to any of the inodes
* at this point (because we intentionally didn't in dqget_noattach).
*/
if (error) {
xfs_qm_dqpurge_all(mp, XFS_QMOPT_QUOTALL);
goto error_return;
}
/*
* If one type of quotas is off, then it will lose its
* quotachecked status, since we won't be doing accounting for
* that type anymore.
*/
mp->m_qflags &= ~XFS_ALL_QUOTA_CHKD;
mp->m_qflags |= flags;
error_return:
while (!list_empty(&buffer_list)) {
struct xfs_buf *bp =
list_first_entry(&buffer_list, struct xfs_buf, b_list);
list_del_init(&bp->b_list);
xfs_buf_relse(bp);
}
if (error) {
xfs_warn(mp,
"Quotacheck: Unsuccessful (Error %d): Disabling quotas.",
error);
/*
* We must turn off quotas.
*/
ASSERT(mp->m_quotainfo != NULL);
xfs_qm_destroy_quotainfo(mp);
if (xfs_mount_reset_sbqflags(mp)) {
xfs_warn(mp,
"Quotacheck: Failed to reset quota flags.");
}
} else
xfs_notice(mp, "Quotacheck: Done.");
return error;
}
/*
* This is called from xfs_mountfs to start quotas and initialize all
* necessary data structures like quotainfo. This is also responsible for
* running a quotacheck as necessary. We are guaranteed that the superblock
* is consistently read in at this point.
*
* If we fail here, the mount will continue with quota turned off. We don't
* need to inidicate success or failure at all.
*/
void
xfs_qm_mount_quotas(
struct xfs_mount *mp)
{
int error = 0;
uint sbf;
/*
* If quotas on realtime volumes is not supported, we disable
* quotas immediately.
*/
if (mp->m_sb.sb_rextents) {
xfs_notice(mp, "Cannot turn on quotas for realtime filesystem");
mp->m_qflags = 0;
goto write_changes;
}
ASSERT(XFS_IS_QUOTA_RUNNING(mp));
/*
* Allocate the quotainfo structure inside the mount struct, and
* create quotainode(s), and change/rev superblock if necessary.
*/
error = xfs_qm_init_quotainfo(mp);
if (error) {
/*
* We must turn off quotas.
*/
ASSERT(mp->m_quotainfo == NULL);
mp->m_qflags = 0;
goto write_changes;
}
/*
* If any of the quotas are not consistent, do a quotacheck.
*/
if (XFS_QM_NEED_QUOTACHECK(mp)) {
error = xfs_qm_quotacheck(mp);
if (error) {
/* Quotacheck failed and disabled quotas. */
return;
}
}
/*
* If one type of quotas is off, then it will lose its
* quotachecked status, since we won't be doing accounting for
* that type anymore.
*/
if (!XFS_IS_UQUOTA_ON(mp))
mp->m_qflags &= ~XFS_UQUOTA_CHKD;
if (!XFS_IS_GQUOTA_ON(mp))
mp->m_qflags &= ~XFS_GQUOTA_CHKD;
if (!XFS_IS_PQUOTA_ON(mp))
mp->m_qflags &= ~XFS_PQUOTA_CHKD;
write_changes:
/*
* We actually don't have to acquire the m_sb_lock at all.
* This can only be called from mount, and that's single threaded. XXX
*/
spin_lock(&mp->m_sb_lock);
sbf = mp->m_sb.sb_qflags;
mp->m_sb.sb_qflags = mp->m_qflags & XFS_MOUNT_QUOTA_ALL;
spin_unlock(&mp->m_sb_lock);
if (sbf != (mp->m_qflags & XFS_MOUNT_QUOTA_ALL)) {
if (xfs_qm_write_sb_changes(mp, XFS_SB_QFLAGS)) {
/*
* We could only have been turning quotas off.
* We aren't in very good shape actually because
* the incore structures are convinced that quotas are
* off, but the on disk superblock doesn't know that !
*/
ASSERT(!(XFS_IS_QUOTA_RUNNING(mp)));
xfs_alert(mp, "%s: Superblock update failed!",
__func__);
}
}
if (error) {
xfs_warn(mp, "Failed to initialize disk quotas.");
return;
}
}
/*
* This is called after the superblock has been read in and we're ready to
* iget the quota inodes.
*/
STATIC int
xfs_qm_init_quotainos(
xfs_mount_t *mp)
{
struct xfs_inode *uip = NULL;
struct xfs_inode *gip = NULL;
struct xfs_inode *pip = NULL;
int error;
__int64_t sbflags = 0;
uint flags = 0;
ASSERT(mp->m_quotainfo);
/*
* Get the uquota and gquota inodes
*/
if (xfs_sb_version_hasquota(&mp->m_sb)) {
if (XFS_IS_UQUOTA_ON(mp) &&
mp->m_sb.sb_uquotino != NULLFSINO) {
ASSERT(mp->m_sb.sb_uquotino > 0);
error = xfs_iget(mp, NULL, mp->m_sb.sb_uquotino,
0, 0, &uip);
if (error)
return error;
}
if (XFS_IS_GQUOTA_ON(mp) &&
mp->m_sb.sb_gquotino != NULLFSINO) {
ASSERT(mp->m_sb.sb_gquotino > 0);
error = xfs_iget(mp, NULL, mp->m_sb.sb_gquotino,
0, 0, &gip);
if (error)
goto error_rele;
}
if (XFS_IS_PQUOTA_ON(mp) &&
mp->m_sb.sb_pquotino != NULLFSINO) {
ASSERT(mp->m_sb.sb_pquotino > 0);
error = xfs_iget(mp, NULL, mp->m_sb.sb_pquotino,
0, 0, &pip);
if (error)
goto error_rele;
}
} else {
flags |= XFS_QMOPT_SBVERSION;
sbflags |= (XFS_SB_VERSIONNUM | XFS_SB_UQUOTINO |
XFS_SB_GQUOTINO | XFS_SB_PQUOTINO |
XFS_SB_QFLAGS);
}
/*
* Create the three inodes, if they don't exist already. The changes
* made above will get added to a transaction and logged in one of
* the qino_alloc calls below. If the device is readonly,
* temporarily switch to read-write to do this.
*/
if (XFS_IS_UQUOTA_ON(mp) && uip == NULL) {
error = xfs_qm_qino_alloc(mp, &uip,
sbflags | XFS_SB_UQUOTINO,
flags | XFS_QMOPT_UQUOTA);
if (error)
goto error_rele;
flags &= ~XFS_QMOPT_SBVERSION;
}
if (XFS_IS_GQUOTA_ON(mp) && gip == NULL) {
error = xfs_qm_qino_alloc(mp, &gip,
sbflags | XFS_SB_GQUOTINO,
flags | XFS_QMOPT_GQUOTA);
if (error)
goto error_rele;
flags &= ~XFS_QMOPT_SBVERSION;
}
if (XFS_IS_PQUOTA_ON(mp) && pip == NULL) {
error = xfs_qm_qino_alloc(mp, &pip,
sbflags | XFS_SB_PQUOTINO,
flags | XFS_QMOPT_PQUOTA);
if (error)
goto error_rele;
}
mp->m_quotainfo->qi_uquotaip = uip;
mp->m_quotainfo->qi_gquotaip = gip;
mp->m_quotainfo->qi_pquotaip = pip;
return 0;
error_rele:
if (uip)
IRELE(uip);
if (gip)
IRELE(gip);
if (pip)
IRELE(pip);
return error;
}
STATIC void
xfs_qm_dqfree_one(
struct xfs_dquot *dqp)
{
struct xfs_mount *mp = dqp->q_mount;
struct xfs_quotainfo *qi = mp->m_quotainfo;
mutex_lock(&qi->qi_tree_lock);
radix_tree_delete(xfs_dquot_tree(qi, dqp->q_core.d_flags),
be32_to_cpu(dqp->q_core.d_id));
qi->qi_dquots--;
mutex_unlock(&qi->qi_tree_lock);
xfs_qm_dqdestroy(dqp);
}
/*
* Start a transaction and write the incore superblock changes to
* disk. flags parameter indicates which fields have changed.
*/
int
xfs_qm_write_sb_changes(
xfs_mount_t *mp,
__int64_t flags)
{
xfs_trans_t *tp;
int error;
tp = xfs_trans_alloc(mp, XFS_TRANS_QM_SBCHANGE);
error = xfs_trans_reserve(tp, &M_RES(mp)->tr_qm_sbchange, 0, 0);
if (error) {
xfs_trans_cancel(tp, 0);
return error;
}
xfs_mod_sb(tp, flags);
error = xfs_trans_commit(tp, 0);
return error;
}
/* --------------- utility functions for vnodeops ---------------- */
/*
* Given an inode, a uid, gid and prid make sure that we have
* allocated relevant dquot(s) on disk, and that we won't exceed inode
* quotas by creating this file.
* This also attaches dquot(s) to the given inode after locking it,
* and returns the dquots corresponding to the uid and/or gid.
*
* in : inode (unlocked)
* out : udquot, gdquot with references taken and unlocked
*/
int
xfs_qm_vop_dqalloc(
struct xfs_inode *ip,
xfs_dqid_t uid,
xfs_dqid_t gid,
prid_t prid,
uint flags,
struct xfs_dquot **O_udqpp,
struct xfs_dquot **O_gdqpp,
struct xfs_dquot **O_pdqpp)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_dquot *uq = NULL;
struct xfs_dquot *gq = NULL;
struct xfs_dquot *pq = NULL;
int error;
uint lockflags;
if (!XFS_IS_QUOTA_RUNNING(mp) || !XFS_IS_QUOTA_ON(mp))
return 0;
lockflags = XFS_ILOCK_EXCL;
xfs_ilock(ip, lockflags);
if ((flags & XFS_QMOPT_INHERIT) && XFS_INHERIT_GID(ip))
gid = ip->i_d.di_gid;
/*
* Attach the dquot(s) to this inode, doing a dquot allocation
* if necessary. The dquot(s) will not be locked.
*/
if (XFS_NOT_DQATTACHED(mp, ip)) {
error = xfs_qm_dqattach_locked(ip, XFS_QMOPT_DQALLOC);
if (error) {
xfs_iunlock(ip, lockflags);
return error;
}
}
if ((flags & XFS_QMOPT_UQUOTA) && XFS_IS_UQUOTA_ON(mp)) {
if (ip->i_d.di_uid != uid) {
/*
* What we need is the dquot that has this uid, and
* if we send the inode to dqget, the uid of the inode
* takes priority over what's sent in the uid argument.
* We must unlock inode here before calling dqget if
* we're not sending the inode, because otherwise
* we'll deadlock by doing trans_reserve while
* holding ilock.
*/
xfs_iunlock(ip, lockflags);
error = xfs_qm_dqget(mp, NULL, uid,
XFS_DQ_USER,
XFS_QMOPT_DQALLOC |
XFS_QMOPT_DOWARN,
&uq);
if (error) {
ASSERT(error != -ENOENT);
return error;
}
/*
* Get the ilock in the right order.
*/
xfs_dqunlock(uq);
lockflags = XFS_ILOCK_SHARED;
xfs_ilock(ip, lockflags);
} else {
/*
* Take an extra reference, because we'll return
* this to caller
*/
ASSERT(ip->i_udquot);
uq = xfs_qm_dqhold(ip->i_udquot);
}
}
if ((flags & XFS_QMOPT_GQUOTA) && XFS_IS_GQUOTA_ON(mp)) {
if (ip->i_d.di_gid != gid) {
xfs_iunlock(ip, lockflags);
error = xfs_qm_dqget(mp, NULL, gid,
XFS_DQ_GROUP,
XFS_QMOPT_DQALLOC |
XFS_QMOPT_DOWARN,
&gq);
if (error) {
ASSERT(error != -ENOENT);
goto error_rele;
}
xfs_dqunlock(gq);
lockflags = XFS_ILOCK_SHARED;
xfs_ilock(ip, lockflags);
} else {
ASSERT(ip->i_gdquot);
gq = xfs_qm_dqhold(ip->i_gdquot);
}
}
if ((flags & XFS_QMOPT_PQUOTA) && XFS_IS_PQUOTA_ON(mp)) {
if (xfs_get_projid(ip) != prid) {
xfs_iunlock(ip, lockflags);
error = xfs_qm_dqget(mp, NULL, (xfs_dqid_t)prid,
XFS_DQ_PROJ,
XFS_QMOPT_DQALLOC |
XFS_QMOPT_DOWARN,
&pq);
if (error) {
ASSERT(error != -ENOENT);
goto error_rele;
}
xfs_dqunlock(pq);
lockflags = XFS_ILOCK_SHARED;
xfs_ilock(ip, lockflags);
} else {
ASSERT(ip->i_pdquot);
pq = xfs_qm_dqhold(ip->i_pdquot);
}
}
if (uq)
trace_xfs_dquot_dqalloc(ip);
xfs_iunlock(ip, lockflags);
if (O_udqpp)
*O_udqpp = uq;
else if (uq)
xfs_qm_dqrele(uq);
if (O_gdqpp)
*O_gdqpp = gq;
else if (gq)
xfs_qm_dqrele(gq);
if (O_pdqpp)
*O_pdqpp = pq;
else if (pq)
xfs_qm_dqrele(pq);
return 0;
error_rele:
if (gq)
xfs_qm_dqrele(gq);
if (uq)
xfs_qm_dqrele(uq);
return error;
}
/*
* Actually transfer ownership, and do dquot modifications.
* These were already reserved.
*/
xfs_dquot_t *
xfs_qm_vop_chown(
xfs_trans_t *tp,
xfs_inode_t *ip,
xfs_dquot_t **IO_olddq,
xfs_dquot_t *newdq)
{
xfs_dquot_t *prevdq;
uint bfield = XFS_IS_REALTIME_INODE(ip) ?
XFS_TRANS_DQ_RTBCOUNT : XFS_TRANS_DQ_BCOUNT;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
ASSERT(XFS_IS_QUOTA_RUNNING(ip->i_mount));
/* old dquot */
prevdq = *IO_olddq;
ASSERT(prevdq);
ASSERT(prevdq != newdq);
xfs_trans_mod_dquot(tp, prevdq, bfield, -(ip->i_d.di_nblocks));
xfs_trans_mod_dquot(tp, prevdq, XFS_TRANS_DQ_ICOUNT, -1);
/* the sparkling new dquot */
xfs_trans_mod_dquot(tp, newdq, bfield, ip->i_d.di_nblocks);
xfs_trans_mod_dquot(tp, newdq, XFS_TRANS_DQ_ICOUNT, 1);
/*
* Take an extra reference, because the inode is going to keep
* this dquot pointer even after the trans_commit.
*/
*IO_olddq = xfs_qm_dqhold(newdq);
return prevdq;
}
/*
* Quota reservations for setattr(AT_UID|AT_GID|AT_PROJID).
*/
int
xfs_qm_vop_chown_reserve(
struct xfs_trans *tp,
struct xfs_inode *ip,
struct xfs_dquot *udqp,
struct xfs_dquot *gdqp,
struct xfs_dquot *pdqp,
uint flags)
{
struct xfs_mount *mp = ip->i_mount;
uint delblks, blkflags, prjflags = 0;
struct xfs_dquot *udq_unres = NULL;
struct xfs_dquot *gdq_unres = NULL;
struct xfs_dquot *pdq_unres = NULL;
struct xfs_dquot *udq_delblks = NULL;
struct xfs_dquot *gdq_delblks = NULL;
struct xfs_dquot *pdq_delblks = NULL;
int error;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
ASSERT(XFS_IS_QUOTA_RUNNING(mp));
delblks = ip->i_delayed_blks;
blkflags = XFS_IS_REALTIME_INODE(ip) ?
XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS;
if (XFS_IS_UQUOTA_ON(mp) && udqp &&
ip->i_d.di_uid != be32_to_cpu(udqp->q_core.d_id)) {
udq_delblks = udqp;
/*
* If there are delayed allocation blocks, then we have to
* unreserve those from the old dquot, and add them to the
* new dquot.
*/
if (delblks) {
ASSERT(ip->i_udquot);
udq_unres = ip->i_udquot;
}
}
if (XFS_IS_GQUOTA_ON(ip->i_mount) && gdqp &&
ip->i_d.di_gid != be32_to_cpu(gdqp->q_core.d_id)) {
gdq_delblks = gdqp;
if (delblks) {
ASSERT(ip->i_gdquot);
gdq_unres = ip->i_gdquot;
}
}
if (XFS_IS_PQUOTA_ON(ip->i_mount) && pdqp &&
xfs_get_projid(ip) != be32_to_cpu(pdqp->q_core.d_id)) {
prjflags = XFS_QMOPT_ENOSPC;
pdq_delblks = pdqp;
if (delblks) {
ASSERT(ip->i_pdquot);
pdq_unres = ip->i_pdquot;
}
}
error = xfs_trans_reserve_quota_bydquots(tp, ip->i_mount,
udq_delblks, gdq_delblks, pdq_delblks,
ip->i_d.di_nblocks, 1,
flags | blkflags | prjflags);
if (error)
return error;
/*
* Do the delayed blks reservations/unreservations now. Since, these
* are done without the help of a transaction, if a reservation fails
* its previous reservations won't be automatically undone by trans
* code. So, we have to do it manually here.
*/
if (delblks) {
/*
* Do the reservations first. Unreservation can't fail.
*/
ASSERT(udq_delblks || gdq_delblks || pdq_delblks);
ASSERT(udq_unres || gdq_unres || pdq_unres);
error = xfs_trans_reserve_quota_bydquots(NULL, ip->i_mount,
udq_delblks, gdq_delblks, pdq_delblks,
(xfs_qcnt_t)delblks, 0,
flags | blkflags | prjflags);
if (error)
return error;
xfs_trans_reserve_quota_bydquots(NULL, ip->i_mount,
udq_unres, gdq_unres, pdq_unres,
-((xfs_qcnt_t)delblks), 0, blkflags);
}
return 0;
}
int
xfs_qm_vop_rename_dqattach(
struct xfs_inode **i_tab)
{
struct xfs_mount *mp = i_tab[0]->i_mount;
int i;
if (!XFS_IS_QUOTA_RUNNING(mp) || !XFS_IS_QUOTA_ON(mp))
return 0;
for (i = 0; (i < 4 && i_tab[i]); i++) {
struct xfs_inode *ip = i_tab[i];
int error;
/*
* Watch out for duplicate entries in the table.
*/
if (i == 0 || ip != i_tab[i-1]) {
if (XFS_NOT_DQATTACHED(mp, ip)) {
error = xfs_qm_dqattach(ip, 0);
if (error)
return error;
}
}
}
return 0;
}
void
xfs_qm_vop_create_dqattach(
struct xfs_trans *tp,
struct xfs_inode *ip,
struct xfs_dquot *udqp,
struct xfs_dquot *gdqp,
struct xfs_dquot *pdqp)
{
struct xfs_mount *mp = tp->t_mountp;
if (!XFS_IS_QUOTA_RUNNING(mp) || !XFS_IS_QUOTA_ON(mp))
return;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
ASSERT(XFS_IS_QUOTA_RUNNING(mp));
if (udqp && XFS_IS_UQUOTA_ON(mp)) {
ASSERT(ip->i_udquot == NULL);
ASSERT(ip->i_d.di_uid == be32_to_cpu(udqp->q_core.d_id));
ip->i_udquot = xfs_qm_dqhold(udqp);
xfs_trans_mod_dquot(tp, udqp, XFS_TRANS_DQ_ICOUNT, 1);
}
if (gdqp && XFS_IS_GQUOTA_ON(mp)) {
ASSERT(ip->i_gdquot == NULL);
ASSERT(ip->i_d.di_gid == be32_to_cpu(gdqp->q_core.d_id));
ip->i_gdquot = xfs_qm_dqhold(gdqp);
xfs_trans_mod_dquot(tp, gdqp, XFS_TRANS_DQ_ICOUNT, 1);
}
if (pdqp && XFS_IS_PQUOTA_ON(mp)) {
ASSERT(ip->i_pdquot == NULL);
ASSERT(xfs_get_projid(ip) == be32_to_cpu(pdqp->q_core.d_id));
ip->i_pdquot = xfs_qm_dqhold(pdqp);
xfs_trans_mod_dquot(tp, pdqp, XFS_TRANS_DQ_ICOUNT, 1);
}
}
| gpl-2.0 |
Grace5921/android_kernel_kylevexx | drivers/infiniband/hw/qib/qib_eeprom.c | 453 | 7478 | /*
* Copyright (c) 2006, 2007, 2008, 2009 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.
*/
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include "qib.h"
/*
* Functions specific to the serial EEPROM on cards handled by ib_qib.
* The actual serail interface code is in qib_twsi.c. This file is a client
*/
/**
* qib_eeprom_read - receives bytes from the eeprom via I2C
* @dd: the qlogic_ib device
* @eeprom_offset: address to read from
* @buffer: where to store result
* @len: number of bytes to receive
*/
int qib_eeprom_read(struct qib_devdata *dd, u8 eeprom_offset,
void *buff, int len)
{
int ret;
ret = mutex_lock_interruptible(&dd->eep_lock);
if (!ret) {
ret = qib_twsi_reset(dd);
if (ret)
qib_dev_err(dd, "EEPROM Reset for read failed\n");
else
ret = qib_twsi_blk_rd(dd, dd->twsi_eeprom_dev,
eeprom_offset, buff, len);
mutex_unlock(&dd->eep_lock);
}
return ret;
}
/*
* Actually update the eeprom, first doing write enable if
* needed, then restoring write enable state.
* Must be called with eep_lock held
*/
static int eeprom_write_with_enable(struct qib_devdata *dd, u8 offset,
const void *buf, int len)
{
int ret, pwen;
pwen = dd->f_eeprom_wen(dd, 1);
ret = qib_twsi_reset(dd);
if (ret)
qib_dev_err(dd, "EEPROM Reset for write failed\n");
else
ret = qib_twsi_blk_wr(dd, dd->twsi_eeprom_dev,
offset, buf, len);
dd->f_eeprom_wen(dd, pwen);
return ret;
}
/**
* qib_eeprom_write - writes data to the eeprom via I2C
* @dd: the qlogic_ib device
* @eeprom_offset: where to place data
* @buffer: data to write
* @len: number of bytes to write
*/
int qib_eeprom_write(struct qib_devdata *dd, u8 eeprom_offset,
const void *buff, int len)
{
int ret;
ret = mutex_lock_interruptible(&dd->eep_lock);
if (!ret) {
ret = eeprom_write_with_enable(dd, eeprom_offset, buff, len);
mutex_unlock(&dd->eep_lock);
}
return ret;
}
static u8 flash_csum(struct qib_flash *ifp, int adjust)
{
u8 *ip = (u8 *) ifp;
u8 csum = 0, len;
/*
* Limit length checksummed to max length of actual data.
* Checksum of erased eeprom will still be bad, but we avoid
* reading past the end of the buffer we were passed.
*/
len = ifp->if_length;
if (len > sizeof(struct qib_flash))
len = sizeof(struct qib_flash);
while (len--)
csum += *ip++;
csum -= ifp->if_csum;
csum = ~csum;
if (adjust)
ifp->if_csum = csum;
return csum;
}
/**
* qib_get_eeprom_info- get the GUID et al. from the TSWI EEPROM device
* @dd: the qlogic_ib device
*
* We have the capability to use the nguid field, and get
* the guid from the first chip's flash, to use for all of them.
*/
void qib_get_eeprom_info(struct qib_devdata *dd)
{
void *buf;
struct qib_flash *ifp;
__be64 guid;
int len, eep_stat;
u8 csum, *bguid;
int t = dd->unit;
struct qib_devdata *dd0 = qib_lookup(0);
if (t && dd0->nguid > 1 && t <= dd0->nguid) {
u8 oguid;
dd->base_guid = dd0->base_guid;
bguid = (u8 *) &dd->base_guid;
oguid = bguid[7];
bguid[7] += t;
if (oguid > bguid[7]) {
if (bguid[6] == 0xff) {
if (bguid[5] == 0xff) {
qib_dev_err(dd, "Can't set %s GUID"
" from base, wraps to"
" OUI!\n",
qib_get_unit_name(t));
dd->base_guid = 0;
goto bail;
}
bguid[5]++;
}
bguid[6]++;
}
dd->nguid = 1;
goto bail;
}
/*
* Read full flash, not just currently used part, since it may have
* been written with a newer definition.
* */
len = sizeof(struct qib_flash);
buf = vmalloc(len);
if (!buf) {
qib_dev_err(dd, "Couldn't allocate memory to read %u "
"bytes from eeprom for GUID\n", len);
goto bail;
}
/*
* Use "public" eeprom read function, which does locking and
* figures out device. This will migrate to chip-specific.
*/
eep_stat = qib_eeprom_read(dd, 0, buf, len);
if (eep_stat) {
qib_dev_err(dd, "Failed reading GUID from eeprom\n");
goto done;
}
ifp = (struct qib_flash *)buf;
csum = flash_csum(ifp, 0);
if (csum != ifp->if_csum) {
qib_devinfo(dd->pcidev, "Bad I2C flash checksum: "
"0x%x, not 0x%x\n", csum, ifp->if_csum);
goto done;
}
if (*(__be64 *) ifp->if_guid == cpu_to_be64(0) ||
*(__be64 *) ifp->if_guid == ~cpu_to_be64(0)) {
qib_dev_err(dd, "Invalid GUID %llx from flash; ignoring\n",
*(unsigned long long *) ifp->if_guid);
/* don't allow GUID if all 0 or all 1's */
goto done;
}
/* complain, but allow it */
if (*(u64 *) ifp->if_guid == 0x100007511000000ULL)
qib_devinfo(dd->pcidev, "Warning, GUID %llx is "
"default, probably not correct!\n",
*(unsigned long long *) ifp->if_guid);
bguid = ifp->if_guid;
if (!bguid[0] && !bguid[1] && !bguid[2]) {
/*
* Original incorrect GUID format in flash; fix in
* core copy, by shifting up 2 octets; don't need to
* change top octet, since both it and shifted are 0.
*/
bguid[1] = bguid[3];
bguid[2] = bguid[4];
bguid[3] = 0;
bguid[4] = 0;
guid = *(__be64 *) ifp->if_guid;
} else
guid = *(__be64 *) ifp->if_guid;
dd->base_guid = guid;
dd->nguid = ifp->if_numguid;
/*
* Things are slightly complicated by the desire to transparently
* support both the Pathscale 10-digit serial number and the QLogic
* 13-character version.
*/
if ((ifp->if_fversion > 1) && ifp->if_sprefix[0] &&
((u8 *) ifp->if_sprefix)[0] != 0xFF) {
char *snp = dd->serial;
/*
* This board has a Serial-prefix, which is stored
* elsewhere for backward-compatibility.
*/
memcpy(snp, ifp->if_sprefix, sizeof ifp->if_sprefix);
snp[sizeof ifp->if_sprefix] = '\0';
len = strlen(snp);
snp += len;
len = (sizeof dd->serial) - len;
if (len > sizeof ifp->if_serial)
len = sizeof ifp->if_serial;
memcpy(snp, ifp->if_serial, len);
} else
memcpy(dd->serial, ifp->if_serial,
sizeof ifp->if_serial);
if (!strstr(ifp->if_comment, "Tested successfully"))
qib_dev_err(dd, "Board SN %s did not pass functional "
"test: %s\n", dd->serial, ifp->if_comment);
done:
vfree(buf);
bail:;
}
| gpl-2.0 |
0xD34D/kernel_omap | fs/ocfs2/dlm/dlmrecovery.c | 965 | 87538 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* dlmrecovery.c
*
* recovery stuff
*
* Copyright (C) 2004 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/highmem.h>
#include <linux/init.h>
#include <linux/sysctl.h>
#include <linux/random.h>
#include <linux/blkdev.h>
#include <linux/socket.h>
#include <linux/inet.h>
#include <linux/timer.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include "cluster/heartbeat.h"
#include "cluster/nodemanager.h"
#include "cluster/tcp.h"
#include "dlmapi.h"
#include "dlmcommon.h"
#include "dlmdomain.h"
#define MLOG_MASK_PREFIX (ML_DLM|ML_DLM_RECOVERY)
#include "cluster/masklog.h"
static void dlm_do_local_recovery_cleanup(struct dlm_ctxt *dlm, u8 dead_node);
static int dlm_recovery_thread(void *data);
void dlm_complete_recovery_thread(struct dlm_ctxt *dlm);
int dlm_launch_recovery_thread(struct dlm_ctxt *dlm);
void dlm_kick_recovery_thread(struct dlm_ctxt *dlm);
static int dlm_do_recovery(struct dlm_ctxt *dlm);
static int dlm_pick_recovery_master(struct dlm_ctxt *dlm);
static int dlm_remaster_locks(struct dlm_ctxt *dlm, u8 dead_node);
static int dlm_init_recovery_area(struct dlm_ctxt *dlm, u8 dead_node);
static int dlm_request_all_locks(struct dlm_ctxt *dlm,
u8 request_from, u8 dead_node);
static void dlm_destroy_recovery_area(struct dlm_ctxt *dlm, u8 dead_node);
static inline int dlm_num_locks_in_lockres(struct dlm_lock_resource *res);
static void dlm_init_migratable_lockres(struct dlm_migratable_lockres *mres,
const char *lockname, int namelen,
int total_locks, u64 cookie,
u8 flags, u8 master);
static int dlm_send_mig_lockres_msg(struct dlm_ctxt *dlm,
struct dlm_migratable_lockres *mres,
u8 send_to,
struct dlm_lock_resource *res,
int total_locks);
static int dlm_process_recovery_data(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_migratable_lockres *mres);
static int dlm_send_finalize_reco_message(struct dlm_ctxt *dlm);
static int dlm_send_all_done_msg(struct dlm_ctxt *dlm,
u8 dead_node, u8 send_to);
static int dlm_send_begin_reco_message(struct dlm_ctxt *dlm, u8 dead_node);
static void dlm_move_reco_locks_to_list(struct dlm_ctxt *dlm,
struct list_head *list, u8 dead_node);
static void dlm_finish_local_lockres_recovery(struct dlm_ctxt *dlm,
u8 dead_node, u8 new_master);
static void dlm_reco_ast(void *astdata);
static void dlm_reco_bast(void *astdata, int blocked_type);
static void dlm_reco_unlock_ast(void *astdata, enum dlm_status st);
static void dlm_request_all_locks_worker(struct dlm_work_item *item,
void *data);
static void dlm_mig_lockres_worker(struct dlm_work_item *item, void *data);
static int dlm_lockres_master_requery(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 *real_master);
static u64 dlm_get_next_mig_cookie(void);
static DEFINE_SPINLOCK(dlm_reco_state_lock);
static DEFINE_SPINLOCK(dlm_mig_cookie_lock);
static u64 dlm_mig_cookie = 1;
static u64 dlm_get_next_mig_cookie(void)
{
u64 c;
spin_lock(&dlm_mig_cookie_lock);
c = dlm_mig_cookie;
if (dlm_mig_cookie == (~0ULL))
dlm_mig_cookie = 1;
else
dlm_mig_cookie++;
spin_unlock(&dlm_mig_cookie_lock);
return c;
}
static inline void dlm_set_reco_dead_node(struct dlm_ctxt *dlm,
u8 dead_node)
{
assert_spin_locked(&dlm->spinlock);
if (dlm->reco.dead_node != dead_node)
mlog(0, "%s: changing dead_node from %u to %u\n",
dlm->name, dlm->reco.dead_node, dead_node);
dlm->reco.dead_node = dead_node;
}
static inline void dlm_set_reco_master(struct dlm_ctxt *dlm,
u8 master)
{
assert_spin_locked(&dlm->spinlock);
mlog(0, "%s: changing new_master from %u to %u\n",
dlm->name, dlm->reco.new_master, master);
dlm->reco.new_master = master;
}
static inline void __dlm_reset_recovery(struct dlm_ctxt *dlm)
{
assert_spin_locked(&dlm->spinlock);
clear_bit(dlm->reco.dead_node, dlm->recovery_map);
dlm_set_reco_dead_node(dlm, O2NM_INVALID_NODE_NUM);
dlm_set_reco_master(dlm, O2NM_INVALID_NODE_NUM);
}
static inline void dlm_reset_recovery(struct dlm_ctxt *dlm)
{
spin_lock(&dlm->spinlock);
__dlm_reset_recovery(dlm);
spin_unlock(&dlm->spinlock);
}
/* Worker function used during recovery. */
void dlm_dispatch_work(struct work_struct *work)
{
struct dlm_ctxt *dlm =
container_of(work, struct dlm_ctxt, dispatched_work);
LIST_HEAD(tmp_list);
struct dlm_work_item *item, *next;
dlm_workfunc_t *workfunc;
int tot=0;
spin_lock(&dlm->work_lock);
list_splice_init(&dlm->work_list, &tmp_list);
spin_unlock(&dlm->work_lock);
list_for_each_entry(item, &tmp_list, list) {
tot++;
}
mlog(0, "%s: work thread has %d work items\n", dlm->name, tot);
list_for_each_entry_safe(item, next, &tmp_list, list) {
workfunc = item->func;
list_del_init(&item->list);
/* already have ref on dlm to avoid having
* it disappear. just double-check. */
BUG_ON(item->dlm != dlm);
/* this is allowed to sleep and
* call network stuff */
workfunc(item, item->data);
dlm_put(dlm);
kfree(item);
}
}
/*
* RECOVERY THREAD
*/
void dlm_kick_recovery_thread(struct dlm_ctxt *dlm)
{
/* wake the recovery thread
* this will wake the reco thread in one of three places
* 1) sleeping with no recovery happening
* 2) sleeping with recovery mastered elsewhere
* 3) recovery mastered here, waiting on reco data */
wake_up(&dlm->dlm_reco_thread_wq);
}
/* Launch the recovery thread */
int dlm_launch_recovery_thread(struct dlm_ctxt *dlm)
{
mlog(0, "starting dlm recovery thread...\n");
dlm->dlm_reco_thread_task = kthread_run(dlm_recovery_thread, dlm,
"dlm_reco_thread");
if (IS_ERR(dlm->dlm_reco_thread_task)) {
mlog_errno(PTR_ERR(dlm->dlm_reco_thread_task));
dlm->dlm_reco_thread_task = NULL;
return -EINVAL;
}
return 0;
}
void dlm_complete_recovery_thread(struct dlm_ctxt *dlm)
{
if (dlm->dlm_reco_thread_task) {
mlog(0, "waiting for dlm recovery thread to exit\n");
kthread_stop(dlm->dlm_reco_thread_task);
dlm->dlm_reco_thread_task = NULL;
}
}
/*
* this is lame, but here's how recovery works...
* 1) all recovery threads cluster wide will work on recovering
* ONE node at a time
* 2) negotiate who will take over all the locks for the dead node.
* thats right... ALL the locks.
* 3) once a new master is chosen, everyone scans all locks
* and moves aside those mastered by the dead guy
* 4) each of these locks should be locked until recovery is done
* 5) the new master collects up all of secondary lock queue info
* one lock at a time, forcing each node to communicate back
* before continuing
* 6) each secondary lock queue responds with the full known lock info
* 7) once the new master has run all its locks, it sends a ALLDONE!
* message to everyone
* 8) upon receiving this message, the secondary queue node unlocks
* and responds to the ALLDONE
* 9) once the new master gets responses from everyone, he unlocks
* everything and recovery for this dead node is done
*10) go back to 2) while there are still dead nodes
*
*/
static void dlm_print_reco_node_status(struct dlm_ctxt *dlm)
{
struct dlm_reco_node_data *ndata;
struct dlm_lock_resource *res;
mlog(ML_NOTICE, "%s(%d): recovery info, state=%s, dead=%u, master=%u\n",
dlm->name, task_pid_nr(dlm->dlm_reco_thread_task),
dlm->reco.state & DLM_RECO_STATE_ACTIVE ? "ACTIVE" : "inactive",
dlm->reco.dead_node, dlm->reco.new_master);
list_for_each_entry(ndata, &dlm->reco.node_data, list) {
char *st = "unknown";
switch (ndata->state) {
case DLM_RECO_NODE_DATA_INIT:
st = "init";
break;
case DLM_RECO_NODE_DATA_REQUESTING:
st = "requesting";
break;
case DLM_RECO_NODE_DATA_DEAD:
st = "dead";
break;
case DLM_RECO_NODE_DATA_RECEIVING:
st = "receiving";
break;
case DLM_RECO_NODE_DATA_REQUESTED:
st = "requested";
break;
case DLM_RECO_NODE_DATA_DONE:
st = "done";
break;
case DLM_RECO_NODE_DATA_FINALIZE_SENT:
st = "finalize-sent";
break;
default:
st = "bad";
break;
}
mlog(ML_NOTICE, "%s: reco state, node %u, state=%s\n",
dlm->name, ndata->node_num, st);
}
list_for_each_entry(res, &dlm->reco.resources, recovering) {
mlog(ML_NOTICE, "%s: lockres %.*s on recovering list\n",
dlm->name, res->lockname.len, res->lockname.name);
}
}
#define DLM_RECO_THREAD_TIMEOUT_MS (5 * 1000)
static int dlm_recovery_thread(void *data)
{
int status;
struct dlm_ctxt *dlm = data;
unsigned long timeout = msecs_to_jiffies(DLM_RECO_THREAD_TIMEOUT_MS);
mlog(0, "dlm thread running for %s...\n", dlm->name);
while (!kthread_should_stop()) {
if (dlm_domain_fully_joined(dlm)) {
status = dlm_do_recovery(dlm);
if (status == -EAGAIN) {
/* do not sleep, recheck immediately. */
continue;
}
if (status < 0)
mlog_errno(status);
}
wait_event_interruptible_timeout(dlm->dlm_reco_thread_wq,
kthread_should_stop(),
timeout);
}
mlog(0, "quitting DLM recovery thread\n");
return 0;
}
/* returns true when the recovery master has contacted us */
static int dlm_reco_master_ready(struct dlm_ctxt *dlm)
{
int ready;
spin_lock(&dlm->spinlock);
ready = (dlm->reco.new_master != O2NM_INVALID_NODE_NUM);
spin_unlock(&dlm->spinlock);
return ready;
}
/* returns true if node is no longer in the domain
* could be dead or just not joined */
int dlm_is_node_dead(struct dlm_ctxt *dlm, u8 node)
{
int dead;
spin_lock(&dlm->spinlock);
dead = !test_bit(node, dlm->domain_map);
spin_unlock(&dlm->spinlock);
return dead;
}
/* returns true if node is no longer in the domain
* could be dead or just not joined */
static int dlm_is_node_recovered(struct dlm_ctxt *dlm, u8 node)
{
int recovered;
spin_lock(&dlm->spinlock);
recovered = !test_bit(node, dlm->recovery_map);
spin_unlock(&dlm->spinlock);
return recovered;
}
int dlm_wait_for_node_death(struct dlm_ctxt *dlm, u8 node, int timeout)
{
if (timeout) {
mlog(ML_NOTICE, "%s: waiting %dms for notification of "
"death of node %u\n", dlm->name, timeout, node);
wait_event_timeout(dlm->dlm_reco_thread_wq,
dlm_is_node_dead(dlm, node),
msecs_to_jiffies(timeout));
} else {
mlog(ML_NOTICE, "%s: waiting indefinitely for notification "
"of death of node %u\n", dlm->name, node);
wait_event(dlm->dlm_reco_thread_wq,
dlm_is_node_dead(dlm, node));
}
/* for now, return 0 */
return 0;
}
int dlm_wait_for_node_recovery(struct dlm_ctxt *dlm, u8 node, int timeout)
{
if (timeout) {
mlog(0, "%s: waiting %dms for notification of "
"recovery of node %u\n", dlm->name, timeout, node);
wait_event_timeout(dlm->dlm_reco_thread_wq,
dlm_is_node_recovered(dlm, node),
msecs_to_jiffies(timeout));
} else {
mlog(0, "%s: waiting indefinitely for notification "
"of recovery of node %u\n", dlm->name, node);
wait_event(dlm->dlm_reco_thread_wq,
dlm_is_node_recovered(dlm, node));
}
/* for now, return 0 */
return 0;
}
/* callers of the top-level api calls (dlmlock/dlmunlock) should
* block on the dlm->reco.event when recovery is in progress.
* the dlm recovery thread will set this state when it begins
* recovering a dead node (as the new master or not) and clear
* the state and wake as soon as all affected lock resources have
* been marked with the RECOVERY flag */
static int dlm_in_recovery(struct dlm_ctxt *dlm)
{
int in_recovery;
spin_lock(&dlm->spinlock);
in_recovery = !!(dlm->reco.state & DLM_RECO_STATE_ACTIVE);
spin_unlock(&dlm->spinlock);
return in_recovery;
}
void dlm_wait_for_recovery(struct dlm_ctxt *dlm)
{
if (dlm_in_recovery(dlm)) {
mlog(0, "%s: reco thread %d in recovery: "
"state=%d, master=%u, dead=%u\n",
dlm->name, task_pid_nr(dlm->dlm_reco_thread_task),
dlm->reco.state, dlm->reco.new_master,
dlm->reco.dead_node);
}
wait_event(dlm->reco.event, !dlm_in_recovery(dlm));
}
static void dlm_begin_recovery(struct dlm_ctxt *dlm)
{
spin_lock(&dlm->spinlock);
BUG_ON(dlm->reco.state & DLM_RECO_STATE_ACTIVE);
dlm->reco.state |= DLM_RECO_STATE_ACTIVE;
spin_unlock(&dlm->spinlock);
}
static void dlm_end_recovery(struct dlm_ctxt *dlm)
{
spin_lock(&dlm->spinlock);
BUG_ON(!(dlm->reco.state & DLM_RECO_STATE_ACTIVE));
dlm->reco.state &= ~DLM_RECO_STATE_ACTIVE;
spin_unlock(&dlm->spinlock);
wake_up(&dlm->reco.event);
}
static int dlm_do_recovery(struct dlm_ctxt *dlm)
{
int status = 0;
int ret;
spin_lock(&dlm->spinlock);
/* check to see if the new master has died */
if (dlm->reco.new_master != O2NM_INVALID_NODE_NUM &&
test_bit(dlm->reco.new_master, dlm->recovery_map)) {
mlog(0, "new master %u died while recovering %u!\n",
dlm->reco.new_master, dlm->reco.dead_node);
/* unset the new_master, leave dead_node */
dlm_set_reco_master(dlm, O2NM_INVALID_NODE_NUM);
}
/* select a target to recover */
if (dlm->reco.dead_node == O2NM_INVALID_NODE_NUM) {
int bit;
bit = find_next_bit (dlm->recovery_map, O2NM_MAX_NODES, 0);
if (bit >= O2NM_MAX_NODES || bit < 0)
dlm_set_reco_dead_node(dlm, O2NM_INVALID_NODE_NUM);
else
dlm_set_reco_dead_node(dlm, bit);
} else if (!test_bit(dlm->reco.dead_node, dlm->recovery_map)) {
/* BUG? */
mlog(ML_ERROR, "dead_node %u no longer in recovery map!\n",
dlm->reco.dead_node);
dlm_set_reco_dead_node(dlm, O2NM_INVALID_NODE_NUM);
}
if (dlm->reco.dead_node == O2NM_INVALID_NODE_NUM) {
// mlog(0, "nothing to recover! sleeping now!\n");
spin_unlock(&dlm->spinlock);
/* return to main thread loop and sleep. */
return 0;
}
mlog(0, "%s(%d):recovery thread found node %u in the recovery map!\n",
dlm->name, task_pid_nr(dlm->dlm_reco_thread_task),
dlm->reco.dead_node);
spin_unlock(&dlm->spinlock);
/* take write barrier */
/* (stops the list reshuffling thread, proxy ast handling) */
dlm_begin_recovery(dlm);
if (dlm->reco.new_master == dlm->node_num)
goto master_here;
if (dlm->reco.new_master == O2NM_INVALID_NODE_NUM) {
/* choose a new master, returns 0 if this node
* is the master, -EEXIST if it's another node.
* this does not return until a new master is chosen
* or recovery completes entirely. */
ret = dlm_pick_recovery_master(dlm);
if (!ret) {
/* already notified everyone. go. */
goto master_here;
}
mlog(0, "another node will master this recovery session.\n");
}
mlog(0, "dlm=%s (%d), new_master=%u, this node=%u, dead_node=%u\n",
dlm->name, task_pid_nr(dlm->dlm_reco_thread_task), dlm->reco.new_master,
dlm->node_num, dlm->reco.dead_node);
/* it is safe to start everything back up here
* because all of the dead node's lock resources
* have been marked as in-recovery */
dlm_end_recovery(dlm);
/* sleep out in main dlm_recovery_thread loop. */
return 0;
master_here:
mlog(ML_NOTICE, "(%d) Node %u is the Recovery Master for the Dead Node "
"%u for Domain %s\n", task_pid_nr(dlm->dlm_reco_thread_task),
dlm->node_num, dlm->reco.dead_node, dlm->name);
status = dlm_remaster_locks(dlm, dlm->reco.dead_node);
if (status < 0) {
/* we should never hit this anymore */
mlog(ML_ERROR, "error %d remastering locks for node %u, "
"retrying.\n", status, dlm->reco.dead_node);
/* yield a bit to allow any final network messages
* to get handled on remaining nodes */
msleep(100);
} else {
/* success! see if any other nodes need recovery */
mlog(0, "DONE mastering recovery of %s:%u here(this=%u)!\n",
dlm->name, dlm->reco.dead_node, dlm->node_num);
dlm_reset_recovery(dlm);
}
dlm_end_recovery(dlm);
/* continue and look for another dead node */
return -EAGAIN;
}
static int dlm_remaster_locks(struct dlm_ctxt *dlm, u8 dead_node)
{
int status = 0;
struct dlm_reco_node_data *ndata;
int all_nodes_done;
int destroy = 0;
int pass = 0;
do {
/* we have become recovery master. there is no escaping
* this, so just keep trying until we get it. */
status = dlm_init_recovery_area(dlm, dead_node);
if (status < 0) {
mlog(ML_ERROR, "%s: failed to alloc recovery area, "
"retrying\n", dlm->name);
msleep(1000);
}
} while (status != 0);
/* safe to access the node data list without a lock, since this
* process is the only one to change the list */
list_for_each_entry(ndata, &dlm->reco.node_data, list) {
BUG_ON(ndata->state != DLM_RECO_NODE_DATA_INIT);
ndata->state = DLM_RECO_NODE_DATA_REQUESTING;
mlog(0, "requesting lock info from node %u\n",
ndata->node_num);
if (ndata->node_num == dlm->node_num) {
ndata->state = DLM_RECO_NODE_DATA_DONE;
continue;
}
do {
status = dlm_request_all_locks(dlm, ndata->node_num,
dead_node);
if (status < 0) {
mlog_errno(status);
if (dlm_is_host_down(status)) {
/* node died, ignore it for recovery */
status = 0;
ndata->state = DLM_RECO_NODE_DATA_DEAD;
/* wait for the domain map to catch up
* with the network state. */
wait_event_timeout(dlm->dlm_reco_thread_wq,
dlm_is_node_dead(dlm,
ndata->node_num),
msecs_to_jiffies(1000));
mlog(0, "waited 1 sec for %u, "
"dead? %s\n", ndata->node_num,
dlm_is_node_dead(dlm, ndata->node_num) ?
"yes" : "no");
} else {
/* -ENOMEM on the other node */
mlog(0, "%s: node %u returned "
"%d during recovery, retrying "
"after a short wait\n",
dlm->name, ndata->node_num,
status);
msleep(100);
}
}
} while (status != 0);
spin_lock(&dlm_reco_state_lock);
switch (ndata->state) {
case DLM_RECO_NODE_DATA_INIT:
case DLM_RECO_NODE_DATA_FINALIZE_SENT:
case DLM_RECO_NODE_DATA_REQUESTED:
BUG();
break;
case DLM_RECO_NODE_DATA_DEAD:
mlog(0, "node %u died after requesting "
"recovery info for node %u\n",
ndata->node_num, dead_node);
/* fine. don't need this node's info.
* continue without it. */
break;
case DLM_RECO_NODE_DATA_REQUESTING:
ndata->state = DLM_RECO_NODE_DATA_REQUESTED;
mlog(0, "now receiving recovery data from "
"node %u for dead node %u\n",
ndata->node_num, dead_node);
break;
case DLM_RECO_NODE_DATA_RECEIVING:
mlog(0, "already receiving recovery data from "
"node %u for dead node %u\n",
ndata->node_num, dead_node);
break;
case DLM_RECO_NODE_DATA_DONE:
mlog(0, "already DONE receiving recovery data "
"from node %u for dead node %u\n",
ndata->node_num, dead_node);
break;
}
spin_unlock(&dlm_reco_state_lock);
}
mlog(0, "done requesting all lock info\n");
/* nodes should be sending reco data now
* just need to wait */
while (1) {
/* check all the nodes now to see if we are
* done, or if anyone died */
all_nodes_done = 1;
spin_lock(&dlm_reco_state_lock);
list_for_each_entry(ndata, &dlm->reco.node_data, list) {
mlog(0, "checking recovery state of node %u\n",
ndata->node_num);
switch (ndata->state) {
case DLM_RECO_NODE_DATA_INIT:
case DLM_RECO_NODE_DATA_REQUESTING:
mlog(ML_ERROR, "bad ndata state for "
"node %u: state=%d\n",
ndata->node_num, ndata->state);
BUG();
break;
case DLM_RECO_NODE_DATA_DEAD:
mlog(0, "node %u died after "
"requesting recovery info for "
"node %u\n", ndata->node_num,
dead_node);
break;
case DLM_RECO_NODE_DATA_RECEIVING:
case DLM_RECO_NODE_DATA_REQUESTED:
mlog(0, "%s: node %u still in state %s\n",
dlm->name, ndata->node_num,
ndata->state==DLM_RECO_NODE_DATA_RECEIVING ?
"receiving" : "requested");
all_nodes_done = 0;
break;
case DLM_RECO_NODE_DATA_DONE:
mlog(0, "%s: node %u state is done\n",
dlm->name, ndata->node_num);
break;
case DLM_RECO_NODE_DATA_FINALIZE_SENT:
mlog(0, "%s: node %u state is finalize\n",
dlm->name, ndata->node_num);
break;
}
}
spin_unlock(&dlm_reco_state_lock);
mlog(0, "pass #%d, all_nodes_done?: %s\n", ++pass,
all_nodes_done?"yes":"no");
if (all_nodes_done) {
int ret;
/* all nodes are now in DLM_RECO_NODE_DATA_DONE state
* just send a finalize message to everyone and
* clean up */
mlog(0, "all nodes are done! send finalize\n");
ret = dlm_send_finalize_reco_message(dlm);
if (ret < 0)
mlog_errno(ret);
spin_lock(&dlm->spinlock);
dlm_finish_local_lockres_recovery(dlm, dead_node,
dlm->node_num);
spin_unlock(&dlm->spinlock);
mlog(0, "should be done with recovery!\n");
mlog(0, "finishing recovery of %s at %lu, "
"dead=%u, this=%u, new=%u\n", dlm->name,
jiffies, dlm->reco.dead_node,
dlm->node_num, dlm->reco.new_master);
destroy = 1;
status = 0;
/* rescan everything marked dirty along the way */
dlm_kick_thread(dlm, NULL);
break;
}
/* wait to be signalled, with periodic timeout
* to check for node death */
wait_event_interruptible_timeout(dlm->dlm_reco_thread_wq,
kthread_should_stop(),
msecs_to_jiffies(DLM_RECO_THREAD_TIMEOUT_MS));
}
if (destroy)
dlm_destroy_recovery_area(dlm, dead_node);
mlog_exit(status);
return status;
}
static int dlm_init_recovery_area(struct dlm_ctxt *dlm, u8 dead_node)
{
int num=0;
struct dlm_reco_node_data *ndata;
spin_lock(&dlm->spinlock);
memcpy(dlm->reco.node_map, dlm->domain_map, sizeof(dlm->domain_map));
/* nodes can only be removed (by dying) after dropping
* this lock, and death will be trapped later, so this should do */
spin_unlock(&dlm->spinlock);
while (1) {
num = find_next_bit (dlm->reco.node_map, O2NM_MAX_NODES, num);
if (num >= O2NM_MAX_NODES) {
break;
}
BUG_ON(num == dead_node);
ndata = kzalloc(sizeof(*ndata), GFP_NOFS);
if (!ndata) {
dlm_destroy_recovery_area(dlm, dead_node);
return -ENOMEM;
}
ndata->node_num = num;
ndata->state = DLM_RECO_NODE_DATA_INIT;
spin_lock(&dlm_reco_state_lock);
list_add_tail(&ndata->list, &dlm->reco.node_data);
spin_unlock(&dlm_reco_state_lock);
num++;
}
return 0;
}
static void dlm_destroy_recovery_area(struct dlm_ctxt *dlm, u8 dead_node)
{
struct dlm_reco_node_data *ndata, *next;
LIST_HEAD(tmplist);
spin_lock(&dlm_reco_state_lock);
list_splice_init(&dlm->reco.node_data, &tmplist);
spin_unlock(&dlm_reco_state_lock);
list_for_each_entry_safe(ndata, next, &tmplist, list) {
list_del_init(&ndata->list);
kfree(ndata);
}
}
static int dlm_request_all_locks(struct dlm_ctxt *dlm, u8 request_from,
u8 dead_node)
{
struct dlm_lock_request lr;
enum dlm_status ret;
mlog(0, "\n");
mlog(0, "dlm_request_all_locks: dead node is %u, sending request "
"to %u\n", dead_node, request_from);
memset(&lr, 0, sizeof(lr));
lr.node_idx = dlm->node_num;
lr.dead_node = dead_node;
// send message
ret = DLM_NOLOCKMGR;
ret = o2net_send_message(DLM_LOCK_REQUEST_MSG, dlm->key,
&lr, sizeof(lr), request_from, NULL);
/* negative status is handled by caller */
if (ret < 0)
mlog(ML_ERROR, "Error %d when sending message %u (key "
"0x%x) to node %u\n", ret, DLM_LOCK_REQUEST_MSG,
dlm->key, request_from);
// return from here, then
// sleep until all received or error
return ret;
}
int dlm_request_all_locks_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_lock_request *lr = (struct dlm_lock_request *)msg->buf;
char *buf = NULL;
struct dlm_work_item *item = NULL;
if (!dlm_grab(dlm))
return -EINVAL;
if (lr->dead_node != dlm->reco.dead_node) {
mlog(ML_ERROR, "%s: node %u sent dead_node=%u, but local "
"dead_node is %u\n", dlm->name, lr->node_idx,
lr->dead_node, dlm->reco.dead_node);
dlm_print_reco_node_status(dlm);
/* this is a hack */
dlm_put(dlm);
return -ENOMEM;
}
BUG_ON(lr->dead_node != dlm->reco.dead_node);
item = kzalloc(sizeof(*item), GFP_NOFS);
if (!item) {
dlm_put(dlm);
return -ENOMEM;
}
/* this will get freed by dlm_request_all_locks_worker */
buf = (char *) __get_free_page(GFP_NOFS);
if (!buf) {
kfree(item);
dlm_put(dlm);
return -ENOMEM;
}
/* queue up work for dlm_request_all_locks_worker */
dlm_grab(dlm); /* get an extra ref for the work item */
dlm_init_work_item(dlm, item, dlm_request_all_locks_worker, buf);
item->u.ral.reco_master = lr->node_idx;
item->u.ral.dead_node = lr->dead_node;
spin_lock(&dlm->work_lock);
list_add_tail(&item->list, &dlm->work_list);
spin_unlock(&dlm->work_lock);
queue_work(dlm->dlm_worker, &dlm->dispatched_work);
dlm_put(dlm);
return 0;
}
static void dlm_request_all_locks_worker(struct dlm_work_item *item, void *data)
{
struct dlm_migratable_lockres *mres;
struct dlm_lock_resource *res;
struct dlm_ctxt *dlm;
LIST_HEAD(resources);
int ret;
u8 dead_node, reco_master;
int skip_all_done = 0;
dlm = item->dlm;
dead_node = item->u.ral.dead_node;
reco_master = item->u.ral.reco_master;
mres = (struct dlm_migratable_lockres *)data;
mlog(0, "%s: recovery worker started, dead=%u, master=%u\n",
dlm->name, dead_node, reco_master);
if (dead_node != dlm->reco.dead_node ||
reco_master != dlm->reco.new_master) {
/* worker could have been created before the recovery master
* died. if so, do not continue, but do not error. */
if (dlm->reco.new_master == O2NM_INVALID_NODE_NUM) {
mlog(ML_NOTICE, "%s: will not send recovery state, "
"recovery master %u died, thread=(dead=%u,mas=%u)"
" current=(dead=%u,mas=%u)\n", dlm->name,
reco_master, dead_node, reco_master,
dlm->reco.dead_node, dlm->reco.new_master);
} else {
mlog(ML_NOTICE, "%s: reco state invalid: reco(dead=%u, "
"master=%u), request(dead=%u, master=%u)\n",
dlm->name, dlm->reco.dead_node,
dlm->reco.new_master, dead_node, reco_master);
}
goto leave;
}
/* lock resources should have already been moved to the
* dlm->reco.resources list. now move items from that list
* to a temp list if the dead owner matches. note that the
* whole cluster recovers only one node at a time, so we
* can safely move UNKNOWN lock resources for each recovery
* session. */
dlm_move_reco_locks_to_list(dlm, &resources, dead_node);
/* now we can begin blasting lockreses without the dlm lock */
/* any errors returned will be due to the new_master dying,
* the dlm_reco_thread should detect this */
list_for_each_entry(res, &resources, recovering) {
ret = dlm_send_one_lockres(dlm, res, mres, reco_master,
DLM_MRES_RECOVERY);
if (ret < 0) {
mlog(ML_ERROR, "%s: node %u went down while sending "
"recovery state for dead node %u, ret=%d\n", dlm->name,
reco_master, dead_node, ret);
skip_all_done = 1;
break;
}
}
/* move the resources back to the list */
spin_lock(&dlm->spinlock);
list_splice_init(&resources, &dlm->reco.resources);
spin_unlock(&dlm->spinlock);
if (!skip_all_done) {
ret = dlm_send_all_done_msg(dlm, dead_node, reco_master);
if (ret < 0) {
mlog(ML_ERROR, "%s: node %u went down while sending "
"recovery all-done for dead node %u, ret=%d\n",
dlm->name, reco_master, dead_node, ret);
}
}
leave:
free_page((unsigned long)data);
}
static int dlm_send_all_done_msg(struct dlm_ctxt *dlm, u8 dead_node, u8 send_to)
{
int ret, tmpret;
struct dlm_reco_data_done done_msg;
memset(&done_msg, 0, sizeof(done_msg));
done_msg.node_idx = dlm->node_num;
done_msg.dead_node = dead_node;
mlog(0, "sending DATA DONE message to %u, "
"my node=%u, dead node=%u\n", send_to, done_msg.node_idx,
done_msg.dead_node);
ret = o2net_send_message(DLM_RECO_DATA_DONE_MSG, dlm->key, &done_msg,
sizeof(done_msg), send_to, &tmpret);
if (ret < 0) {
mlog(ML_ERROR, "Error %d when sending message %u (key "
"0x%x) to node %u\n", ret, DLM_RECO_DATA_DONE_MSG,
dlm->key, send_to);
if (!dlm_is_host_down(ret)) {
BUG();
}
} else
ret = tmpret;
return ret;
}
int dlm_reco_data_done_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_reco_data_done *done = (struct dlm_reco_data_done *)msg->buf;
struct dlm_reco_node_data *ndata = NULL;
int ret = -EINVAL;
if (!dlm_grab(dlm))
return -EINVAL;
mlog(0, "got DATA DONE: dead_node=%u, reco.dead_node=%u, "
"node_idx=%u, this node=%u\n", done->dead_node,
dlm->reco.dead_node, done->node_idx, dlm->node_num);
mlog_bug_on_msg((done->dead_node != dlm->reco.dead_node),
"Got DATA DONE: dead_node=%u, reco.dead_node=%u, "
"node_idx=%u, this node=%u\n", done->dead_node,
dlm->reco.dead_node, done->node_idx, dlm->node_num);
spin_lock(&dlm_reco_state_lock);
list_for_each_entry(ndata, &dlm->reco.node_data, list) {
if (ndata->node_num != done->node_idx)
continue;
switch (ndata->state) {
/* should have moved beyond INIT but not to FINALIZE yet */
case DLM_RECO_NODE_DATA_INIT:
case DLM_RECO_NODE_DATA_DEAD:
case DLM_RECO_NODE_DATA_FINALIZE_SENT:
mlog(ML_ERROR, "bad ndata state for node %u:"
" state=%d\n", ndata->node_num,
ndata->state);
BUG();
break;
/* these states are possible at this point, anywhere along
* the line of recovery */
case DLM_RECO_NODE_DATA_DONE:
case DLM_RECO_NODE_DATA_RECEIVING:
case DLM_RECO_NODE_DATA_REQUESTED:
case DLM_RECO_NODE_DATA_REQUESTING:
mlog(0, "node %u is DONE sending "
"recovery data!\n",
ndata->node_num);
ndata->state = DLM_RECO_NODE_DATA_DONE;
ret = 0;
break;
}
}
spin_unlock(&dlm_reco_state_lock);
/* wake the recovery thread, some node is done */
if (!ret)
dlm_kick_recovery_thread(dlm);
if (ret < 0)
mlog(ML_ERROR, "failed to find recovery node data for node "
"%u\n", done->node_idx);
dlm_put(dlm);
mlog(0, "leaving reco data done handler, ret=%d\n", ret);
return ret;
}
static void dlm_move_reco_locks_to_list(struct dlm_ctxt *dlm,
struct list_head *list,
u8 dead_node)
{
struct dlm_lock_resource *res, *next;
struct dlm_lock *lock;
spin_lock(&dlm->spinlock);
list_for_each_entry_safe(res, next, &dlm->reco.resources, recovering) {
/* always prune any $RECOVERY entries for dead nodes,
* otherwise hangs can occur during later recovery */
if (dlm_is_recovery_lock(res->lockname.name,
res->lockname.len)) {
spin_lock(&res->spinlock);
list_for_each_entry(lock, &res->granted, list) {
if (lock->ml.node == dead_node) {
mlog(0, "AHA! there was "
"a $RECOVERY lock for dead "
"node %u (%s)!\n",
dead_node, dlm->name);
list_del_init(&lock->list);
dlm_lock_put(lock);
break;
}
}
spin_unlock(&res->spinlock);
continue;
}
if (res->owner == dead_node) {
mlog(0, "found lockres owned by dead node while "
"doing recovery for node %u. sending it.\n",
dead_node);
list_move_tail(&res->recovering, list);
} else if (res->owner == DLM_LOCK_RES_OWNER_UNKNOWN) {
mlog(0, "found UNKNOWN owner while doing recovery "
"for node %u. sending it.\n", dead_node);
list_move_tail(&res->recovering, list);
}
}
spin_unlock(&dlm->spinlock);
}
static inline int dlm_num_locks_in_lockres(struct dlm_lock_resource *res)
{
int total_locks = 0;
struct list_head *iter, *queue = &res->granted;
int i;
for (i=0; i<3; i++) {
list_for_each(iter, queue)
total_locks++;
queue++;
}
return total_locks;
}
static int dlm_send_mig_lockres_msg(struct dlm_ctxt *dlm,
struct dlm_migratable_lockres *mres,
u8 send_to,
struct dlm_lock_resource *res,
int total_locks)
{
u64 mig_cookie = be64_to_cpu(mres->mig_cookie);
int mres_total_locks = be32_to_cpu(mres->total_locks);
int sz, ret = 0, status = 0;
u8 orig_flags = mres->flags,
orig_master = mres->master;
BUG_ON(mres->num_locks > DLM_MAX_MIGRATABLE_LOCKS);
if (!mres->num_locks)
return 0;
sz = sizeof(struct dlm_migratable_lockres) +
(mres->num_locks * sizeof(struct dlm_migratable_lock));
/* add an all-done flag if we reached the last lock */
orig_flags = mres->flags;
BUG_ON(total_locks > mres_total_locks);
if (total_locks == mres_total_locks)
mres->flags |= DLM_MRES_ALL_DONE;
mlog(0, "%s:%.*s: sending mig lockres (%s) to %u\n",
dlm->name, res->lockname.len, res->lockname.name,
orig_flags & DLM_MRES_MIGRATION ? "migration" : "recovery",
send_to);
/* send it */
ret = o2net_send_message(DLM_MIG_LOCKRES_MSG, dlm->key, mres,
sz, send_to, &status);
if (ret < 0) {
/* XXX: negative status is not handled.
* this will end up killing this node. */
mlog(ML_ERROR, "Error %d when sending message %u (key "
"0x%x) to node %u\n", ret, DLM_MIG_LOCKRES_MSG,
dlm->key, send_to);
} else {
/* might get an -ENOMEM back here */
ret = status;
if (ret < 0) {
mlog_errno(ret);
if (ret == -EFAULT) {
mlog(ML_ERROR, "node %u told me to kill "
"myself!\n", send_to);
BUG();
}
}
}
/* zero and reinit the message buffer */
dlm_init_migratable_lockres(mres, res->lockname.name,
res->lockname.len, mres_total_locks,
mig_cookie, orig_flags, orig_master);
return ret;
}
static void dlm_init_migratable_lockres(struct dlm_migratable_lockres *mres,
const char *lockname, int namelen,
int total_locks, u64 cookie,
u8 flags, u8 master)
{
/* mres here is one full page */
clear_page(mres);
mres->lockname_len = namelen;
memcpy(mres->lockname, lockname, namelen);
mres->num_locks = 0;
mres->total_locks = cpu_to_be32(total_locks);
mres->mig_cookie = cpu_to_be64(cookie);
mres->flags = flags;
mres->master = master;
}
static void dlm_prepare_lvb_for_migration(struct dlm_lock *lock,
struct dlm_migratable_lockres *mres,
int queue)
{
if (!lock->lksb)
return;
/* Ignore lvb in all locks in the blocked list */
if (queue == DLM_BLOCKED_LIST)
return;
/* Only consider lvbs in locks with granted EX or PR lock levels */
if (lock->ml.type != LKM_EXMODE && lock->ml.type != LKM_PRMODE)
return;
if (dlm_lvb_is_empty(mres->lvb)) {
memcpy(mres->lvb, lock->lksb->lvb, DLM_LVB_LEN);
return;
}
/* Ensure the lvb copied for migration matches in other valid locks */
if (!memcmp(mres->lvb, lock->lksb->lvb, DLM_LVB_LEN))
return;
mlog(ML_ERROR, "Mismatched lvb in lock cookie=%u:%llu, name=%.*s, "
"node=%u\n",
dlm_get_lock_cookie_node(be64_to_cpu(lock->ml.cookie)),
dlm_get_lock_cookie_seq(be64_to_cpu(lock->ml.cookie)),
lock->lockres->lockname.len, lock->lockres->lockname.name,
lock->ml.node);
dlm_print_one_lock_resource(lock->lockres);
BUG();
}
/* returns 1 if this lock fills the network structure,
* 0 otherwise */
static int dlm_add_lock_to_array(struct dlm_lock *lock,
struct dlm_migratable_lockres *mres, int queue)
{
struct dlm_migratable_lock *ml;
int lock_num = mres->num_locks;
ml = &(mres->ml[lock_num]);
ml->cookie = lock->ml.cookie;
ml->type = lock->ml.type;
ml->convert_type = lock->ml.convert_type;
ml->highest_blocked = lock->ml.highest_blocked;
ml->list = queue;
if (lock->lksb) {
ml->flags = lock->lksb->flags;
dlm_prepare_lvb_for_migration(lock, mres, queue);
}
ml->node = lock->ml.node;
mres->num_locks++;
/* we reached the max, send this network message */
if (mres->num_locks == DLM_MAX_MIGRATABLE_LOCKS)
return 1;
return 0;
}
static void dlm_add_dummy_lock(struct dlm_ctxt *dlm,
struct dlm_migratable_lockres *mres)
{
struct dlm_lock dummy;
memset(&dummy, 0, sizeof(dummy));
dummy.ml.cookie = 0;
dummy.ml.type = LKM_IVMODE;
dummy.ml.convert_type = LKM_IVMODE;
dummy.ml.highest_blocked = LKM_IVMODE;
dummy.lksb = NULL;
dummy.ml.node = dlm->node_num;
dlm_add_lock_to_array(&dummy, mres, DLM_BLOCKED_LIST);
}
static inline int dlm_is_dummy_lock(struct dlm_ctxt *dlm,
struct dlm_migratable_lock *ml,
u8 *nodenum)
{
if (unlikely(ml->cookie == 0 &&
ml->type == LKM_IVMODE &&
ml->convert_type == LKM_IVMODE &&
ml->highest_blocked == LKM_IVMODE &&
ml->list == DLM_BLOCKED_LIST)) {
*nodenum = ml->node;
return 1;
}
return 0;
}
int dlm_send_one_lockres(struct dlm_ctxt *dlm, struct dlm_lock_resource *res,
struct dlm_migratable_lockres *mres,
u8 send_to, u8 flags)
{
struct list_head *queue;
int total_locks, i;
u64 mig_cookie = 0;
struct dlm_lock *lock;
int ret = 0;
BUG_ON(!(flags & (DLM_MRES_RECOVERY|DLM_MRES_MIGRATION)));
mlog(0, "sending to %u\n", send_to);
total_locks = dlm_num_locks_in_lockres(res);
if (total_locks > DLM_MAX_MIGRATABLE_LOCKS) {
/* rare, but possible */
mlog(0, "argh. lockres has %d locks. this will "
"require more than one network packet to "
"migrate\n", total_locks);
mig_cookie = dlm_get_next_mig_cookie();
}
dlm_init_migratable_lockres(mres, res->lockname.name,
res->lockname.len, total_locks,
mig_cookie, flags, res->owner);
total_locks = 0;
for (i=DLM_GRANTED_LIST; i<=DLM_BLOCKED_LIST; i++) {
queue = dlm_list_idx_to_ptr(res, i);
list_for_each_entry(lock, queue, list) {
/* add another lock. */
total_locks++;
if (!dlm_add_lock_to_array(lock, mres, i))
continue;
/* this filled the lock message,
* we must send it immediately. */
ret = dlm_send_mig_lockres_msg(dlm, mres, send_to,
res, total_locks);
if (ret < 0)
goto error;
}
}
if (total_locks == 0) {
/* send a dummy lock to indicate a mastery reference only */
mlog(0, "%s:%.*s: sending dummy lock to %u, %s\n",
dlm->name, res->lockname.len, res->lockname.name,
send_to, flags & DLM_MRES_RECOVERY ? "recovery" :
"migration");
dlm_add_dummy_lock(dlm, mres);
}
/* flush any remaining locks */
ret = dlm_send_mig_lockres_msg(dlm, mres, send_to, res, total_locks);
if (ret < 0)
goto error;
return ret;
error:
mlog(ML_ERROR, "%s: dlm_send_mig_lockres_msg returned %d\n",
dlm->name, ret);
if (!dlm_is_host_down(ret))
BUG();
mlog(0, "%s: node %u went down while sending %s "
"lockres %.*s\n", dlm->name, send_to,
flags & DLM_MRES_RECOVERY ? "recovery" : "migration",
res->lockname.len, res->lockname.name);
return ret;
}
/*
* this message will contain no more than one page worth of
* recovery data, and it will work on only one lockres.
* there may be many locks in this page, and we may need to wait
* for additional packets to complete all the locks (rare, but
* possible).
*/
/*
* NOTE: the allocation error cases here are scary
* we really cannot afford to fail an alloc in recovery
* do we spin? returning an error only delays the problem really
*/
int dlm_mig_lockres_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_migratable_lockres *mres =
(struct dlm_migratable_lockres *)msg->buf;
int ret = 0;
u8 real_master;
u8 extra_refs = 0;
char *buf = NULL;
struct dlm_work_item *item = NULL;
struct dlm_lock_resource *res = NULL;
if (!dlm_grab(dlm))
return -EINVAL;
BUG_ON(!(mres->flags & (DLM_MRES_RECOVERY|DLM_MRES_MIGRATION)));
real_master = mres->master;
if (real_master == DLM_LOCK_RES_OWNER_UNKNOWN) {
/* cannot migrate a lockres with no master */
BUG_ON(!(mres->flags & DLM_MRES_RECOVERY));
}
mlog(0, "%s message received from node %u\n",
(mres->flags & DLM_MRES_RECOVERY) ?
"recovery" : "migration", mres->master);
if (mres->flags & DLM_MRES_ALL_DONE)
mlog(0, "all done flag. all lockres data received!\n");
ret = -ENOMEM;
buf = kmalloc(be16_to_cpu(msg->data_len), GFP_NOFS);
item = kzalloc(sizeof(*item), GFP_NOFS);
if (!buf || !item)
goto leave;
/* lookup the lock to see if we have a secondary queue for this
* already... just add the locks in and this will have its owner
* and RECOVERY flag changed when it completes. */
res = dlm_lookup_lockres(dlm, mres->lockname, mres->lockname_len);
if (res) {
/* this will get a ref on res */
/* mark it as recovering/migrating and hash it */
spin_lock(&res->spinlock);
if (mres->flags & DLM_MRES_RECOVERY) {
res->state |= DLM_LOCK_RES_RECOVERING;
} else {
if (res->state & DLM_LOCK_RES_MIGRATING) {
/* this is at least the second
* lockres message */
mlog(0, "lock %.*s is already migrating\n",
mres->lockname_len,
mres->lockname);
} else if (res->state & DLM_LOCK_RES_RECOVERING) {
/* caller should BUG */
mlog(ML_ERROR, "node is attempting to migrate "
"lock %.*s, but marked as recovering!\n",
mres->lockname_len, mres->lockname);
ret = -EFAULT;
spin_unlock(&res->spinlock);
goto leave;
}
res->state |= DLM_LOCK_RES_MIGRATING;
}
spin_unlock(&res->spinlock);
} else {
/* need to allocate, just like if it was
* mastered here normally */
res = dlm_new_lockres(dlm, mres->lockname, mres->lockname_len);
if (!res)
goto leave;
/* to match the ref that we would have gotten if
* dlm_lookup_lockres had succeeded */
dlm_lockres_get(res);
/* mark it as recovering/migrating and hash it */
if (mres->flags & DLM_MRES_RECOVERY)
res->state |= DLM_LOCK_RES_RECOVERING;
else
res->state |= DLM_LOCK_RES_MIGRATING;
spin_lock(&dlm->spinlock);
__dlm_insert_lockres(dlm, res);
spin_unlock(&dlm->spinlock);
/* Add an extra ref for this lock-less lockres lest the
* dlm_thread purges it before we get the chance to add
* locks to it */
dlm_lockres_get(res);
/* There are three refs that need to be put.
* 1. Taken above.
* 2. kref_init in dlm_new_lockres()->dlm_init_lockres().
* 3. dlm_lookup_lockres()
* The first one is handled at the end of this function. The
* other two are handled in the worker thread after locks have
* been attached. Yes, we don't wait for purge time to match
* kref_init. The lockres will still have atleast one ref
* added because it is in the hash __dlm_insert_lockres() */
extra_refs++;
/* now that the new lockres is inserted,
* make it usable by other processes */
spin_lock(&res->spinlock);
res->state &= ~DLM_LOCK_RES_IN_PROGRESS;
spin_unlock(&res->spinlock);
wake_up(&res->wq);
}
/* at this point we have allocated everything we need,
* and we have a hashed lockres with an extra ref and
* the proper res->state flags. */
ret = 0;
spin_lock(&res->spinlock);
/* drop this either when master requery finds a different master
* or when a lock is added by the recovery worker */
dlm_lockres_grab_inflight_ref(dlm, res);
if (mres->master == DLM_LOCK_RES_OWNER_UNKNOWN) {
/* migration cannot have an unknown master */
BUG_ON(!(mres->flags & DLM_MRES_RECOVERY));
mlog(0, "recovery has passed me a lockres with an "
"unknown owner.. will need to requery: "
"%.*s\n", mres->lockname_len, mres->lockname);
} else {
/* take a reference now to pin the lockres, drop it
* when locks are added in the worker */
dlm_change_lockres_owner(dlm, res, dlm->node_num);
}
spin_unlock(&res->spinlock);
/* queue up work for dlm_mig_lockres_worker */
dlm_grab(dlm); /* get an extra ref for the work item */
memcpy(buf, msg->buf, be16_to_cpu(msg->data_len)); /* copy the whole message */
dlm_init_work_item(dlm, item, dlm_mig_lockres_worker, buf);
item->u.ml.lockres = res; /* already have a ref */
item->u.ml.real_master = real_master;
item->u.ml.extra_ref = extra_refs;
spin_lock(&dlm->work_lock);
list_add_tail(&item->list, &dlm->work_list);
spin_unlock(&dlm->work_lock);
queue_work(dlm->dlm_worker, &dlm->dispatched_work);
leave:
/* One extra ref taken needs to be put here */
if (extra_refs)
dlm_lockres_put(res);
dlm_put(dlm);
if (ret < 0) {
if (buf)
kfree(buf);
if (item)
kfree(item);
}
mlog_exit(ret);
return ret;
}
static void dlm_mig_lockres_worker(struct dlm_work_item *item, void *data)
{
struct dlm_ctxt *dlm;
struct dlm_migratable_lockres *mres;
int ret = 0;
struct dlm_lock_resource *res;
u8 real_master;
u8 extra_ref;
dlm = item->dlm;
mres = (struct dlm_migratable_lockres *)data;
res = item->u.ml.lockres;
real_master = item->u.ml.real_master;
extra_ref = item->u.ml.extra_ref;
if (real_master == DLM_LOCK_RES_OWNER_UNKNOWN) {
/* this case is super-rare. only occurs if
* node death happens during migration. */
again:
ret = dlm_lockres_master_requery(dlm, res, &real_master);
if (ret < 0) {
mlog(0, "dlm_lockres_master_requery ret=%d\n",
ret);
goto again;
}
if (real_master == DLM_LOCK_RES_OWNER_UNKNOWN) {
mlog(0, "lockres %.*s not claimed. "
"this node will take it.\n",
res->lockname.len, res->lockname.name);
} else {
spin_lock(&res->spinlock);
dlm_lockres_drop_inflight_ref(dlm, res);
spin_unlock(&res->spinlock);
mlog(0, "master needs to respond to sender "
"that node %u still owns %.*s\n",
real_master, res->lockname.len,
res->lockname.name);
/* cannot touch this lockres */
goto leave;
}
}
ret = dlm_process_recovery_data(dlm, res, mres);
if (ret < 0)
mlog(0, "dlm_process_recovery_data returned %d\n", ret);
else
mlog(0, "dlm_process_recovery_data succeeded\n");
if ((mres->flags & (DLM_MRES_MIGRATION|DLM_MRES_ALL_DONE)) ==
(DLM_MRES_MIGRATION|DLM_MRES_ALL_DONE)) {
ret = dlm_finish_migration(dlm, res, mres->master);
if (ret < 0)
mlog_errno(ret);
}
leave:
/* See comment in dlm_mig_lockres_handler() */
if (res) {
if (extra_ref)
dlm_lockres_put(res);
dlm_lockres_put(res);
}
kfree(data);
mlog_exit(ret);
}
static int dlm_lockres_master_requery(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 *real_master)
{
struct dlm_node_iter iter;
int nodenum;
int ret = 0;
*real_master = DLM_LOCK_RES_OWNER_UNKNOWN;
/* we only reach here if one of the two nodes in a
* migration died while the migration was in progress.
* at this point we need to requery the master. we
* know that the new_master got as far as creating
* an mle on at least one node, but we do not know
* if any nodes had actually cleared the mle and set
* the master to the new_master. the old master
* is supposed to set the owner to UNKNOWN in the
* event of a new_master death, so the only possible
* responses that we can get from nodes here are
* that the master is new_master, or that the master
* is UNKNOWN.
* if all nodes come back with UNKNOWN then we know
* the lock needs remastering here.
* if any node comes back with a valid master, check
* to see if that master is the one that we are
* recovering. if so, then the new_master died and
* we need to remaster this lock. if not, then the
* new_master survived and that node will respond to
* other nodes about the owner.
* if there is an owner, this node needs to dump this
* lockres and alert the sender that this lockres
* was rejected. */
spin_lock(&dlm->spinlock);
dlm_node_iter_init(dlm->domain_map, &iter);
spin_unlock(&dlm->spinlock);
while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
/* do not send to self */
if (nodenum == dlm->node_num)
continue;
ret = dlm_do_master_requery(dlm, res, nodenum, real_master);
if (ret < 0) {
mlog_errno(ret);
if (!dlm_is_host_down(ret))
BUG();
/* host is down, so answer for that node would be
* DLM_LOCK_RES_OWNER_UNKNOWN. continue. */
}
if (*real_master != DLM_LOCK_RES_OWNER_UNKNOWN) {
mlog(0, "lock master is %u\n", *real_master);
break;
}
}
return ret;
}
int dlm_do_master_requery(struct dlm_ctxt *dlm, struct dlm_lock_resource *res,
u8 nodenum, u8 *real_master)
{
int ret = -EINVAL;
struct dlm_master_requery req;
int status = DLM_LOCK_RES_OWNER_UNKNOWN;
memset(&req, 0, sizeof(req));
req.node_idx = dlm->node_num;
req.namelen = res->lockname.len;
memcpy(req.name, res->lockname.name, res->lockname.len);
ret = o2net_send_message(DLM_MASTER_REQUERY_MSG, dlm->key,
&req, sizeof(req), nodenum, &status);
/* XXX: negative status not handled properly here. */
if (ret < 0)
mlog(ML_ERROR, "Error %d when sending message %u (key "
"0x%x) to node %u\n", ret, DLM_MASTER_REQUERY_MSG,
dlm->key, nodenum);
else {
BUG_ON(status < 0);
BUG_ON(status > DLM_LOCK_RES_OWNER_UNKNOWN);
*real_master = (u8) (status & 0xff);
mlog(0, "node %u responded to master requery with %u\n",
nodenum, *real_master);
ret = 0;
}
return ret;
}
/* this function cannot error, so unless the sending
* or receiving of the message failed, the owner can
* be trusted */
int dlm_master_requery_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_master_requery *req = (struct dlm_master_requery *)msg->buf;
struct dlm_lock_resource *res = NULL;
unsigned int hash;
int master = DLM_LOCK_RES_OWNER_UNKNOWN;
u32 flags = DLM_ASSERT_MASTER_REQUERY;
if (!dlm_grab(dlm)) {
/* since the domain has gone away on this
* node, the proper response is UNKNOWN */
return master;
}
hash = dlm_lockid_hash(req->name, req->namelen);
spin_lock(&dlm->spinlock);
res = __dlm_lookup_lockres(dlm, req->name, req->namelen, hash);
if (res) {
spin_lock(&res->spinlock);
master = res->owner;
if (master == dlm->node_num) {
int ret = dlm_dispatch_assert_master(dlm, res,
0, 0, flags);
if (ret < 0) {
mlog_errno(-ENOMEM);
/* retry!? */
BUG();
}
} else /* put.. incase we are not the master */
dlm_lockres_put(res);
spin_unlock(&res->spinlock);
}
spin_unlock(&dlm->spinlock);
dlm_put(dlm);
return master;
}
static inline struct list_head *
dlm_list_num_to_pointer(struct dlm_lock_resource *res, int list_num)
{
struct list_head *ret;
BUG_ON(list_num < 0);
BUG_ON(list_num > 2);
ret = &(res->granted);
ret += list_num;
return ret;
}
/* TODO: do ast flush business
* TODO: do MIGRATING and RECOVERING spinning
*/
/*
* NOTE about in-flight requests during migration:
*
* Before attempting the migrate, the master has marked the lockres as
* MIGRATING and then flushed all of its pending ASTS. So any in-flight
* requests either got queued before the MIGRATING flag got set, in which
* case the lock data will reflect the change and a return message is on
* the way, or the request failed to get in before MIGRATING got set. In
* this case, the caller will be told to spin and wait for the MIGRATING
* flag to be dropped, then recheck the master.
* This holds true for the convert, cancel and unlock cases, and since lvb
* updates are tied to these same messages, it applies to lvb updates as
* well. For the lock case, there is no way a lock can be on the master
* queue and not be on the secondary queue since the lock is always added
* locally first. This means that the new target node will never be sent
* a lock that he doesn't already have on the list.
* In total, this means that the local lock is correct and should not be
* updated to match the one sent by the master. Any messages sent back
* from the master before the MIGRATING flag will bring the lock properly
* up-to-date, and the change will be ordered properly for the waiter.
* We will *not* attempt to modify the lock underneath the waiter.
*/
static int dlm_process_recovery_data(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_migratable_lockres *mres)
{
struct dlm_migratable_lock *ml;
struct list_head *queue;
struct list_head *tmpq = NULL;
struct dlm_lock *newlock = NULL;
struct dlm_lockstatus *lksb = NULL;
int ret = 0;
int i, j, bad;
struct dlm_lock *lock = NULL;
u8 from = O2NM_MAX_NODES;
unsigned int added = 0;
__be64 c;
mlog(0, "running %d locks for this lockres\n", mres->num_locks);
for (i=0; i<mres->num_locks; i++) {
ml = &(mres->ml[i]);
if (dlm_is_dummy_lock(dlm, ml, &from)) {
/* placeholder, just need to set the refmap bit */
BUG_ON(mres->num_locks != 1);
mlog(0, "%s:%.*s: dummy lock for %u\n",
dlm->name, mres->lockname_len, mres->lockname,
from);
spin_lock(&res->spinlock);
dlm_lockres_set_refmap_bit(from, res);
spin_unlock(&res->spinlock);
added++;
break;
}
BUG_ON(ml->highest_blocked != LKM_IVMODE);
newlock = NULL;
lksb = NULL;
queue = dlm_list_num_to_pointer(res, ml->list);
tmpq = NULL;
/* if the lock is for the local node it needs to
* be moved to the proper location within the queue.
* do not allocate a new lock structure. */
if (ml->node == dlm->node_num) {
/* MIGRATION ONLY! */
BUG_ON(!(mres->flags & DLM_MRES_MIGRATION));
spin_lock(&res->spinlock);
for (j = DLM_GRANTED_LIST; j <= DLM_BLOCKED_LIST; j++) {
tmpq = dlm_list_idx_to_ptr(res, j);
list_for_each_entry(lock, tmpq, list) {
if (lock->ml.cookie != ml->cookie)
lock = NULL;
else
break;
}
if (lock)
break;
}
/* lock is always created locally first, and
* destroyed locally last. it must be on the list */
if (!lock) {
c = ml->cookie;
mlog(ML_ERROR, "Could not find local lock "
"with cookie %u:%llu, node %u, "
"list %u, flags 0x%x, type %d, "
"conv %d, highest blocked %d\n",
dlm_get_lock_cookie_node(be64_to_cpu(c)),
dlm_get_lock_cookie_seq(be64_to_cpu(c)),
ml->node, ml->list, ml->flags, ml->type,
ml->convert_type, ml->highest_blocked);
__dlm_print_one_lock_resource(res);
BUG();
}
if (lock->ml.node != ml->node) {
c = lock->ml.cookie;
mlog(ML_ERROR, "Mismatched node# in lock "
"cookie %u:%llu, name %.*s, node %u\n",
dlm_get_lock_cookie_node(be64_to_cpu(c)),
dlm_get_lock_cookie_seq(be64_to_cpu(c)),
res->lockname.len, res->lockname.name,
lock->ml.node);
c = ml->cookie;
mlog(ML_ERROR, "Migrate lock cookie %u:%llu, "
"node %u, list %u, flags 0x%x, type %d, "
"conv %d, highest blocked %d\n",
dlm_get_lock_cookie_node(be64_to_cpu(c)),
dlm_get_lock_cookie_seq(be64_to_cpu(c)),
ml->node, ml->list, ml->flags, ml->type,
ml->convert_type, ml->highest_blocked);
__dlm_print_one_lock_resource(res);
BUG();
}
if (tmpq != queue) {
c = ml->cookie;
mlog(0, "Lock cookie %u:%llu was on list %u "
"instead of list %u for %.*s\n",
dlm_get_lock_cookie_node(be64_to_cpu(c)),
dlm_get_lock_cookie_seq(be64_to_cpu(c)),
j, ml->list, res->lockname.len,
res->lockname.name);
__dlm_print_one_lock_resource(res);
spin_unlock(&res->spinlock);
continue;
}
/* see NOTE above about why we do not update
* to match the master here */
/* move the lock to its proper place */
/* do not alter lock refcount. switching lists. */
list_move_tail(&lock->list, queue);
spin_unlock(&res->spinlock);
added++;
mlog(0, "just reordered a local lock!\n");
continue;
}
/* lock is for another node. */
newlock = dlm_new_lock(ml->type, ml->node,
be64_to_cpu(ml->cookie), NULL);
if (!newlock) {
ret = -ENOMEM;
goto leave;
}
lksb = newlock->lksb;
dlm_lock_attach_lockres(newlock, res);
if (ml->convert_type != LKM_IVMODE) {
BUG_ON(queue != &res->converting);
newlock->ml.convert_type = ml->convert_type;
}
lksb->flags |= (ml->flags &
(DLM_LKSB_PUT_LVB|DLM_LKSB_GET_LVB));
if (ml->type == LKM_NLMODE)
goto skip_lvb;
if (!dlm_lvb_is_empty(mres->lvb)) {
if (lksb->flags & DLM_LKSB_PUT_LVB) {
/* other node was trying to update
* lvb when node died. recreate the
* lksb with the updated lvb. */
memcpy(lksb->lvb, mres->lvb, DLM_LVB_LEN);
/* the lock resource lvb update must happen
* NOW, before the spinlock is dropped.
* we no longer wait for the AST to update
* the lvb. */
memcpy(res->lvb, mres->lvb, DLM_LVB_LEN);
} else {
/* otherwise, the node is sending its
* most recent valid lvb info */
BUG_ON(ml->type != LKM_EXMODE &&
ml->type != LKM_PRMODE);
if (!dlm_lvb_is_empty(res->lvb) &&
(ml->type == LKM_EXMODE ||
memcmp(res->lvb, mres->lvb, DLM_LVB_LEN))) {
int i;
mlog(ML_ERROR, "%s:%.*s: received bad "
"lvb! type=%d\n", dlm->name,
res->lockname.len,
res->lockname.name, ml->type);
printk("lockres lvb=[");
for (i=0; i<DLM_LVB_LEN; i++)
printk("%02x", res->lvb[i]);
printk("]\nmigrated lvb=[");
for (i=0; i<DLM_LVB_LEN; i++)
printk("%02x", mres->lvb[i]);
printk("]\n");
dlm_print_one_lock_resource(res);
BUG();
}
memcpy(res->lvb, mres->lvb, DLM_LVB_LEN);
}
}
skip_lvb:
/* NOTE:
* wrt lock queue ordering and recovery:
* 1. order of locks on granted queue is
* meaningless.
* 2. order of locks on converting queue is
* LOST with the node death. sorry charlie.
* 3. order of locks on the blocked queue is
* also LOST.
* order of locks does not affect integrity, it
* just means that a lock request may get pushed
* back in line as a result of the node death.
* also note that for a given node the lock order
* for its secondary queue locks is preserved
* relative to each other, but clearly *not*
* preserved relative to locks from other nodes.
*/
bad = 0;
spin_lock(&res->spinlock);
list_for_each_entry(lock, queue, list) {
if (lock->ml.cookie == ml->cookie) {
c = lock->ml.cookie;
mlog(ML_ERROR, "%s:%.*s: %u:%llu: lock already "
"exists on this lockres!\n", dlm->name,
res->lockname.len, res->lockname.name,
dlm_get_lock_cookie_node(be64_to_cpu(c)),
dlm_get_lock_cookie_seq(be64_to_cpu(c)));
mlog(ML_NOTICE, "sent lock: type=%d, conv=%d, "
"node=%u, cookie=%u:%llu, queue=%d\n",
ml->type, ml->convert_type, ml->node,
dlm_get_lock_cookie_node(be64_to_cpu(ml->cookie)),
dlm_get_lock_cookie_seq(be64_to_cpu(ml->cookie)),
ml->list);
__dlm_print_one_lock_resource(res);
bad = 1;
break;
}
}
if (!bad) {
dlm_lock_get(newlock);
list_add_tail(&newlock->list, queue);
mlog(0, "%s:%.*s: added lock for node %u, "
"setting refmap bit\n", dlm->name,
res->lockname.len, res->lockname.name, ml->node);
dlm_lockres_set_refmap_bit(ml->node, res);
added++;
}
spin_unlock(&res->spinlock);
}
mlog(0, "done running all the locks\n");
leave:
/* balance the ref taken when the work was queued */
spin_lock(&res->spinlock);
dlm_lockres_drop_inflight_ref(dlm, res);
spin_unlock(&res->spinlock);
if (ret < 0) {
mlog_errno(ret);
if (newlock)
dlm_lock_put(newlock);
}
mlog_exit(ret);
return ret;
}
void dlm_move_lockres_to_recovery_list(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
int i;
struct list_head *queue;
struct dlm_lock *lock, *next;
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&res->spinlock);
res->state |= DLM_LOCK_RES_RECOVERING;
if (!list_empty(&res->recovering)) {
mlog(0,
"Recovering res %s:%.*s, is already on recovery list!\n",
dlm->name, res->lockname.len, res->lockname.name);
list_del_init(&res->recovering);
dlm_lockres_put(res);
}
/* We need to hold a reference while on the recovery list */
dlm_lockres_get(res);
list_add_tail(&res->recovering, &dlm->reco.resources);
/* find any pending locks and put them back on proper list */
for (i=DLM_BLOCKED_LIST; i>=DLM_GRANTED_LIST; i--) {
queue = dlm_list_idx_to_ptr(res, i);
list_for_each_entry_safe(lock, next, queue, list) {
dlm_lock_get(lock);
if (lock->convert_pending) {
/* move converting lock back to granted */
BUG_ON(i != DLM_CONVERTING_LIST);
mlog(0, "node died with convert pending "
"on %.*s. move back to granted list.\n",
res->lockname.len, res->lockname.name);
dlm_revert_pending_convert(res, lock);
lock->convert_pending = 0;
} else if (lock->lock_pending) {
/* remove pending lock requests completely */
BUG_ON(i != DLM_BLOCKED_LIST);
mlog(0, "node died with lock pending "
"on %.*s. remove from blocked list and skip.\n",
res->lockname.len, res->lockname.name);
/* lock will be floating until ref in
* dlmlock_remote is freed after the network
* call returns. ok for it to not be on any
* list since no ast can be called
* (the master is dead). */
dlm_revert_pending_lock(res, lock);
lock->lock_pending = 0;
} else if (lock->unlock_pending) {
/* if an unlock was in progress, treat as
* if this had completed successfully
* before sending this lock state to the
* new master. note that the dlm_unlock
* call is still responsible for calling
* the unlockast. that will happen after
* the network call times out. for now,
* just move lists to prepare the new
* recovery master. */
BUG_ON(i != DLM_GRANTED_LIST);
mlog(0, "node died with unlock pending "
"on %.*s. remove from blocked list and skip.\n",
res->lockname.len, res->lockname.name);
dlm_commit_pending_unlock(res, lock);
lock->unlock_pending = 0;
} else if (lock->cancel_pending) {
/* if a cancel was in progress, treat as
* if this had completed successfully
* before sending this lock state to the
* new master */
BUG_ON(i != DLM_CONVERTING_LIST);
mlog(0, "node died with cancel pending "
"on %.*s. move back to granted list.\n",
res->lockname.len, res->lockname.name);
dlm_commit_pending_cancel(res, lock);
lock->cancel_pending = 0;
}
dlm_lock_put(lock);
}
}
}
/* removes all recovered locks from the recovery list.
* sets the res->owner to the new master.
* unsets the RECOVERY flag and wakes waiters. */
static void dlm_finish_local_lockres_recovery(struct dlm_ctxt *dlm,
u8 dead_node, u8 new_master)
{
int i;
struct hlist_node *hash_iter;
struct hlist_head *bucket;
struct dlm_lock_resource *res, *next;
mlog_entry_void();
assert_spin_locked(&dlm->spinlock);
list_for_each_entry_safe(res, next, &dlm->reco.resources, recovering) {
if (res->owner == dead_node) {
list_del_init(&res->recovering);
spin_lock(&res->spinlock);
/* new_master has our reference from
* the lock state sent during recovery */
dlm_change_lockres_owner(dlm, res, new_master);
res->state &= ~DLM_LOCK_RES_RECOVERING;
if (__dlm_lockres_has_locks(res))
__dlm_dirty_lockres(dlm, res);
spin_unlock(&res->spinlock);
wake_up(&res->wq);
dlm_lockres_put(res);
}
}
/* this will become unnecessary eventually, but
* for now we need to run the whole hash, clear
* the RECOVERING state and set the owner
* if necessary */
for (i = 0; i < DLM_HASH_BUCKETS; i++) {
bucket = dlm_lockres_hash(dlm, i);
hlist_for_each_entry(res, hash_iter, bucket, hash_node) {
if (res->state & DLM_LOCK_RES_RECOVERING) {
if (res->owner == dead_node) {
mlog(0, "(this=%u) res %.*s owner=%u "
"was not on recovering list, but "
"clearing state anyway\n",
dlm->node_num, res->lockname.len,
res->lockname.name, new_master);
} else if (res->owner == dlm->node_num) {
mlog(0, "(this=%u) res %.*s owner=%u "
"was not on recovering list, "
"owner is THIS node, clearing\n",
dlm->node_num, res->lockname.len,
res->lockname.name, new_master);
} else
continue;
if (!list_empty(&res->recovering)) {
mlog(0, "%s:%.*s: lockres was "
"marked RECOVERING, owner=%u\n",
dlm->name, res->lockname.len,
res->lockname.name, res->owner);
list_del_init(&res->recovering);
dlm_lockres_put(res);
}
spin_lock(&res->spinlock);
/* new_master has our reference from
* the lock state sent during recovery */
dlm_change_lockres_owner(dlm, res, new_master);
res->state &= ~DLM_LOCK_RES_RECOVERING;
if (__dlm_lockres_has_locks(res))
__dlm_dirty_lockres(dlm, res);
spin_unlock(&res->spinlock);
wake_up(&res->wq);
}
}
}
}
static inline int dlm_lvb_needs_invalidation(struct dlm_lock *lock, int local)
{
if (local) {
if (lock->ml.type != LKM_EXMODE &&
lock->ml.type != LKM_PRMODE)
return 1;
} else if (lock->ml.type == LKM_EXMODE)
return 1;
return 0;
}
static void dlm_revalidate_lvb(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res, u8 dead_node)
{
struct list_head *queue;
struct dlm_lock *lock;
int blank_lvb = 0, local = 0;
int i;
u8 search_node;
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&res->spinlock);
if (res->owner == dlm->node_num)
/* if this node owned the lockres, and if the dead node
* had an EX when he died, blank out the lvb */
search_node = dead_node;
else {
/* if this is a secondary lockres, and we had no EX or PR
* locks granted, we can no longer trust the lvb */
search_node = dlm->node_num;
local = 1; /* check local state for valid lvb */
}
for (i=DLM_GRANTED_LIST; i<=DLM_CONVERTING_LIST; i++) {
queue = dlm_list_idx_to_ptr(res, i);
list_for_each_entry(lock, queue, list) {
if (lock->ml.node == search_node) {
if (dlm_lvb_needs_invalidation(lock, local)) {
/* zero the lksb lvb and lockres lvb */
blank_lvb = 1;
memset(lock->lksb->lvb, 0, DLM_LVB_LEN);
}
}
}
}
if (blank_lvb) {
mlog(0, "clearing %.*s lvb, dead node %u had EX\n",
res->lockname.len, res->lockname.name, dead_node);
memset(res->lvb, 0, DLM_LVB_LEN);
}
}
static void dlm_free_dead_locks(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res, u8 dead_node)
{
struct dlm_lock *lock, *next;
unsigned int freed = 0;
/* this node is the lockres master:
* 1) remove any stale locks for the dead node
* 2) if the dead node had an EX when he died, blank out the lvb
*/
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&res->spinlock);
/* We do two dlm_lock_put(). One for removing from list and the other is
* to force the DLM_UNLOCK_FREE_LOCK action so as to free the locks */
/* TODO: check pending_asts, pending_basts here */
list_for_each_entry_safe(lock, next, &res->granted, list) {
if (lock->ml.node == dead_node) {
list_del_init(&lock->list);
dlm_lock_put(lock);
/* Can't schedule DLM_UNLOCK_FREE_LOCK - do manually */
dlm_lock_put(lock);
freed++;
}
}
list_for_each_entry_safe(lock, next, &res->converting, list) {
if (lock->ml.node == dead_node) {
list_del_init(&lock->list);
dlm_lock_put(lock);
/* Can't schedule DLM_UNLOCK_FREE_LOCK - do manually */
dlm_lock_put(lock);
freed++;
}
}
list_for_each_entry_safe(lock, next, &res->blocked, list) {
if (lock->ml.node == dead_node) {
list_del_init(&lock->list);
dlm_lock_put(lock);
/* Can't schedule DLM_UNLOCK_FREE_LOCK - do manually */
dlm_lock_put(lock);
freed++;
}
}
if (freed) {
mlog(0, "%s:%.*s: freed %u locks for dead node %u, "
"dropping ref from lockres\n", dlm->name,
res->lockname.len, res->lockname.name, freed, dead_node);
if(!test_bit(dead_node, res->refmap)) {
mlog(ML_ERROR, "%s:%.*s: freed %u locks for dead node %u, "
"but ref was not set\n", dlm->name,
res->lockname.len, res->lockname.name, freed, dead_node);
__dlm_print_one_lock_resource(res);
}
dlm_lockres_clear_refmap_bit(dead_node, res);
} else if (test_bit(dead_node, res->refmap)) {
mlog(0, "%s:%.*s: dead node %u had a ref, but had "
"no locks and had not purged before dying\n", dlm->name,
res->lockname.len, res->lockname.name, dead_node);
dlm_lockres_clear_refmap_bit(dead_node, res);
}
/* do not kick thread yet */
__dlm_dirty_lockres(dlm, res);
}
/* if this node is the recovery master, and there are no
* locks for a given lockres owned by this node that are in
* either PR or EX mode, zero out the lvb before requesting.
*
*/
static void dlm_do_local_recovery_cleanup(struct dlm_ctxt *dlm, u8 dead_node)
{
struct hlist_node *iter;
struct dlm_lock_resource *res;
int i;
struct hlist_head *bucket;
struct dlm_lock *lock;
/* purge any stale mles */
dlm_clean_master_list(dlm, dead_node);
/*
* now clean up all lock resources. there are two rules:
*
* 1) if the dead node was the master, move the lockres
* to the recovering list. set the RECOVERING flag.
* this lockres needs to be cleaned up before it can
* be used further.
*
* 2) if this node was the master, remove all locks from
* each of the lockres queues that were owned by the
* dead node. once recovery finishes, the dlm thread
* can be kicked again to see if any ASTs or BASTs
* need to be fired as a result.
*/
for (i = 0; i < DLM_HASH_BUCKETS; i++) {
bucket = dlm_lockres_hash(dlm, i);
hlist_for_each_entry(res, iter, bucket, hash_node) {
/* always prune any $RECOVERY entries for dead nodes,
* otherwise hangs can occur during later recovery */
if (dlm_is_recovery_lock(res->lockname.name,
res->lockname.len)) {
spin_lock(&res->spinlock);
list_for_each_entry(lock, &res->granted, list) {
if (lock->ml.node == dead_node) {
mlog(0, "AHA! there was "
"a $RECOVERY lock for dead "
"node %u (%s)!\n",
dead_node, dlm->name);
list_del_init(&lock->list);
dlm_lock_put(lock);
break;
}
}
spin_unlock(&res->spinlock);
continue;
}
spin_lock(&res->spinlock);
/* zero the lvb if necessary */
dlm_revalidate_lvb(dlm, res, dead_node);
if (res->owner == dead_node) {
if (res->state & DLM_LOCK_RES_DROPPING_REF) {
mlog(ML_NOTICE, "Ignore %.*s for "
"recovery as it is being freed\n",
res->lockname.len,
res->lockname.name);
} else
dlm_move_lockres_to_recovery_list(dlm,
res);
} else if (res->owner == dlm->node_num) {
dlm_free_dead_locks(dlm, res, dead_node);
__dlm_lockres_calc_usage(dlm, res);
}
spin_unlock(&res->spinlock);
}
}
}
static void __dlm_hb_node_down(struct dlm_ctxt *dlm, int idx)
{
assert_spin_locked(&dlm->spinlock);
if (dlm->reco.new_master == idx) {
mlog(0, "%s: recovery master %d just died\n",
dlm->name, idx);
if (dlm->reco.state & DLM_RECO_STATE_FINALIZE) {
/* finalize1 was reached, so it is safe to clear
* the new_master and dead_node. that recovery
* is complete. */
mlog(0, "%s: dead master %d had reached "
"finalize1 state, clearing\n", dlm->name, idx);
dlm->reco.state &= ~DLM_RECO_STATE_FINALIZE;
__dlm_reset_recovery(dlm);
}
}
/* Clean up join state on node death. */
if (dlm->joining_node == idx) {
mlog(0, "Clearing join state for node %u\n", idx);
__dlm_set_joining_node(dlm, DLM_LOCK_RES_OWNER_UNKNOWN);
}
/* check to see if the node is already considered dead */
if (!test_bit(idx, dlm->live_nodes_map)) {
mlog(0, "for domain %s, node %d is already dead. "
"another node likely did recovery already.\n",
dlm->name, idx);
return;
}
/* check to see if we do not care about this node */
if (!test_bit(idx, dlm->domain_map)) {
/* This also catches the case that we get a node down
* but haven't joined the domain yet. */
mlog(0, "node %u already removed from domain!\n", idx);
return;
}
clear_bit(idx, dlm->live_nodes_map);
/* make sure local cleanup occurs before the heartbeat events */
if (!test_bit(idx, dlm->recovery_map))
dlm_do_local_recovery_cleanup(dlm, idx);
/* notify anything attached to the heartbeat events */
dlm_hb_event_notify_attached(dlm, idx, 0);
mlog(0, "node %u being removed from domain map!\n", idx);
clear_bit(idx, dlm->domain_map);
/* wake up migration waiters if a node goes down.
* perhaps later we can genericize this for other waiters. */
wake_up(&dlm->migration_wq);
if (test_bit(idx, dlm->recovery_map))
mlog(0, "domain %s, node %u already added "
"to recovery map!\n", dlm->name, idx);
else
set_bit(idx, dlm->recovery_map);
}
void dlm_hb_node_down_cb(struct o2nm_node *node, int idx, void *data)
{
struct dlm_ctxt *dlm = data;
if (!dlm_grab(dlm))
return;
/*
* This will notify any dlm users that a node in our domain
* went away without notifying us first.
*/
if (test_bit(idx, dlm->domain_map))
dlm_fire_domain_eviction_callbacks(dlm, idx);
spin_lock(&dlm->spinlock);
__dlm_hb_node_down(dlm, idx);
spin_unlock(&dlm->spinlock);
dlm_put(dlm);
}
void dlm_hb_node_up_cb(struct o2nm_node *node, int idx, void *data)
{
struct dlm_ctxt *dlm = data;
if (!dlm_grab(dlm))
return;
spin_lock(&dlm->spinlock);
set_bit(idx, dlm->live_nodes_map);
/* do NOT notify mle attached to the heartbeat events.
* new nodes are not interesting in mastery until joined. */
spin_unlock(&dlm->spinlock);
dlm_put(dlm);
}
static void dlm_reco_ast(void *astdata)
{
struct dlm_ctxt *dlm = astdata;
mlog(0, "ast for recovery lock fired!, this=%u, dlm=%s\n",
dlm->node_num, dlm->name);
}
static void dlm_reco_bast(void *astdata, int blocked_type)
{
struct dlm_ctxt *dlm = astdata;
mlog(0, "bast for recovery lock fired!, this=%u, dlm=%s\n",
dlm->node_num, dlm->name);
}
static void dlm_reco_unlock_ast(void *astdata, enum dlm_status st)
{
mlog(0, "unlockast for recovery lock fired!\n");
}
/*
* dlm_pick_recovery_master will continually attempt to use
* dlmlock() on the special "$RECOVERY" lockres with the
* LKM_NOQUEUE flag to get an EX. every thread that enters
* this function on each node racing to become the recovery
* master will not stop attempting this until either:
* a) this node gets the EX (and becomes the recovery master),
* or b) dlm->reco.new_master gets set to some nodenum
* != O2NM_INVALID_NODE_NUM (another node will do the reco).
* so each time a recovery master is needed, the entire cluster
* will sync at this point. if the new master dies, that will
* be detected in dlm_do_recovery */
static int dlm_pick_recovery_master(struct dlm_ctxt *dlm)
{
enum dlm_status ret;
struct dlm_lockstatus lksb;
int status = -EINVAL;
mlog(0, "starting recovery of %s at %lu, dead=%u, this=%u\n",
dlm->name, jiffies, dlm->reco.dead_node, dlm->node_num);
again:
memset(&lksb, 0, sizeof(lksb));
ret = dlmlock(dlm, LKM_EXMODE, &lksb, LKM_NOQUEUE|LKM_RECOVERY,
DLM_RECOVERY_LOCK_NAME, DLM_RECOVERY_LOCK_NAME_LEN,
dlm_reco_ast, dlm, dlm_reco_bast);
mlog(0, "%s: dlmlock($RECOVERY) returned %d, lksb=%d\n",
dlm->name, ret, lksb.status);
if (ret == DLM_NORMAL) {
mlog(0, "dlm=%s dlmlock says I got it (this=%u)\n",
dlm->name, dlm->node_num);
/* got the EX lock. check to see if another node
* just became the reco master */
if (dlm_reco_master_ready(dlm)) {
mlog(0, "%s: got reco EX lock, but %u will "
"do the recovery\n", dlm->name,
dlm->reco.new_master);
status = -EEXIST;
} else {
status = 0;
/* see if recovery was already finished elsewhere */
spin_lock(&dlm->spinlock);
if (dlm->reco.dead_node == O2NM_INVALID_NODE_NUM) {
status = -EINVAL;
mlog(0, "%s: got reco EX lock, but "
"node got recovered already\n", dlm->name);
if (dlm->reco.new_master != O2NM_INVALID_NODE_NUM) {
mlog(ML_ERROR, "%s: new master is %u "
"but no dead node!\n",
dlm->name, dlm->reco.new_master);
BUG();
}
}
spin_unlock(&dlm->spinlock);
}
/* if this node has actually become the recovery master,
* set the master and send the messages to begin recovery */
if (!status) {
mlog(0, "%s: dead=%u, this=%u, sending "
"begin_reco now\n", dlm->name,
dlm->reco.dead_node, dlm->node_num);
status = dlm_send_begin_reco_message(dlm,
dlm->reco.dead_node);
/* this always succeeds */
BUG_ON(status);
/* set the new_master to this node */
spin_lock(&dlm->spinlock);
dlm_set_reco_master(dlm, dlm->node_num);
spin_unlock(&dlm->spinlock);
}
/* recovery lock is a special case. ast will not get fired,
* so just go ahead and unlock it. */
ret = dlmunlock(dlm, &lksb, 0, dlm_reco_unlock_ast, dlm);
if (ret == DLM_DENIED) {
mlog(0, "got DLM_DENIED, trying LKM_CANCEL\n");
ret = dlmunlock(dlm, &lksb, LKM_CANCEL, dlm_reco_unlock_ast, dlm);
}
if (ret != DLM_NORMAL) {
/* this would really suck. this could only happen
* if there was a network error during the unlock
* because of node death. this means the unlock
* is actually "done" and the lock structure is
* even freed. we can continue, but only
* because this specific lock name is special. */
mlog(ML_ERROR, "dlmunlock returned %d\n", ret);
}
} else if (ret == DLM_NOTQUEUED) {
mlog(0, "dlm=%s dlmlock says another node got it (this=%u)\n",
dlm->name, dlm->node_num);
/* another node is master. wait on
* reco.new_master != O2NM_INVALID_NODE_NUM
* for at most one second */
wait_event_timeout(dlm->dlm_reco_thread_wq,
dlm_reco_master_ready(dlm),
msecs_to_jiffies(1000));
if (!dlm_reco_master_ready(dlm)) {
mlog(0, "%s: reco master taking awhile\n",
dlm->name);
goto again;
}
/* another node has informed this one that it is reco master */
mlog(0, "%s: reco master %u is ready to recover %u\n",
dlm->name, dlm->reco.new_master, dlm->reco.dead_node);
status = -EEXIST;
} else if (ret == DLM_RECOVERING) {
mlog(0, "dlm=%s dlmlock says master node died (this=%u)\n",
dlm->name, dlm->node_num);
goto again;
} else {
struct dlm_lock_resource *res;
/* dlmlock returned something other than NOTQUEUED or NORMAL */
mlog(ML_ERROR, "%s: got %s from dlmlock($RECOVERY), "
"lksb.status=%s\n", dlm->name, dlm_errname(ret),
dlm_errname(lksb.status));
res = dlm_lookup_lockres(dlm, DLM_RECOVERY_LOCK_NAME,
DLM_RECOVERY_LOCK_NAME_LEN);
if (res) {
dlm_print_one_lock_resource(res);
dlm_lockres_put(res);
} else {
mlog(ML_ERROR, "recovery lock not found\n");
}
BUG();
}
return status;
}
static int dlm_send_begin_reco_message(struct dlm_ctxt *dlm, u8 dead_node)
{
struct dlm_begin_reco br;
int ret = 0;
struct dlm_node_iter iter;
int nodenum;
int status;
mlog_entry("%u\n", dead_node);
mlog(0, "%s: dead node is %u\n", dlm->name, dead_node);
spin_lock(&dlm->spinlock);
dlm_node_iter_init(dlm->domain_map, &iter);
spin_unlock(&dlm->spinlock);
clear_bit(dead_node, iter.node_map);
memset(&br, 0, sizeof(br));
br.node_idx = dlm->node_num;
br.dead_node = dead_node;
while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
ret = 0;
if (nodenum == dead_node) {
mlog(0, "not sending begin reco to dead node "
"%u\n", dead_node);
continue;
}
if (nodenum == dlm->node_num) {
mlog(0, "not sending begin reco to self\n");
continue;
}
retry:
ret = -EINVAL;
mlog(0, "attempting to send begin reco msg to %d\n",
nodenum);
ret = o2net_send_message(DLM_BEGIN_RECO_MSG, dlm->key,
&br, sizeof(br), nodenum, &status);
/* negative status is handled ok by caller here */
if (ret >= 0)
ret = status;
if (dlm_is_host_down(ret)) {
/* node is down. not involved in recovery
* so just keep going */
mlog(ML_NOTICE, "%s: node %u was down when sending "
"begin reco msg (%d)\n", dlm->name, nodenum, ret);
ret = 0;
}
/*
* Prior to commit aad1b15310b9bcd59fa81ab8f2b1513b59553ea8,
* dlm_begin_reco_handler() returned EAGAIN and not -EAGAIN.
* We are handling both for compatibility reasons.
*/
if (ret == -EAGAIN || ret == EAGAIN) {
mlog(0, "%s: trying to start recovery of node "
"%u, but node %u is waiting for last recovery "
"to complete, backoff for a bit\n", dlm->name,
dead_node, nodenum);
msleep(100);
goto retry;
}
if (ret < 0) {
struct dlm_lock_resource *res;
/* this is now a serious problem, possibly ENOMEM
* in the network stack. must retry */
mlog_errno(ret);
mlog(ML_ERROR, "begin reco of dlm %s to node %u "
"returned %d\n", dlm->name, nodenum, ret);
res = dlm_lookup_lockres(dlm, DLM_RECOVERY_LOCK_NAME,
DLM_RECOVERY_LOCK_NAME_LEN);
if (res) {
dlm_print_one_lock_resource(res);
dlm_lockres_put(res);
} else {
mlog(ML_ERROR, "recovery lock not found\n");
}
/* sleep for a bit in hopes that we can avoid
* another ENOMEM */
msleep(100);
goto retry;
}
}
return ret;
}
int dlm_begin_reco_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_begin_reco *br = (struct dlm_begin_reco *)msg->buf;
/* ok to return 0, domain has gone away */
if (!dlm_grab(dlm))
return 0;
spin_lock(&dlm->spinlock);
if (dlm->reco.state & DLM_RECO_STATE_FINALIZE) {
mlog(0, "%s: node %u wants to recover node %u (%u:%u) "
"but this node is in finalize state, waiting on finalize2\n",
dlm->name, br->node_idx, br->dead_node,
dlm->reco.dead_node, dlm->reco.new_master);
spin_unlock(&dlm->spinlock);
return -EAGAIN;
}
spin_unlock(&dlm->spinlock);
mlog(0, "%s: node %u wants to recover node %u (%u:%u)\n",
dlm->name, br->node_idx, br->dead_node,
dlm->reco.dead_node, dlm->reco.new_master);
dlm_fire_domain_eviction_callbacks(dlm, br->dead_node);
spin_lock(&dlm->spinlock);
if (dlm->reco.new_master != O2NM_INVALID_NODE_NUM) {
if (test_bit(dlm->reco.new_master, dlm->recovery_map)) {
mlog(0, "%s: new_master %u died, changing "
"to %u\n", dlm->name, dlm->reco.new_master,
br->node_idx);
} else {
mlog(0, "%s: new_master %u NOT DEAD, changing "
"to %u\n", dlm->name, dlm->reco.new_master,
br->node_idx);
/* may not have seen the new master as dead yet */
}
}
if (dlm->reco.dead_node != O2NM_INVALID_NODE_NUM) {
mlog(ML_NOTICE, "%s: dead_node previously set to %u, "
"node %u changing it to %u\n", dlm->name,
dlm->reco.dead_node, br->node_idx, br->dead_node);
}
dlm_set_reco_master(dlm, br->node_idx);
dlm_set_reco_dead_node(dlm, br->dead_node);
if (!test_bit(br->dead_node, dlm->recovery_map)) {
mlog(0, "recovery master %u sees %u as dead, but this "
"node has not yet. marking %u as dead\n",
br->node_idx, br->dead_node, br->dead_node);
if (!test_bit(br->dead_node, dlm->domain_map) ||
!test_bit(br->dead_node, dlm->live_nodes_map))
mlog(0, "%u not in domain/live_nodes map "
"so setting it in reco map manually\n",
br->dead_node);
/* force the recovery cleanup in __dlm_hb_node_down
* both of these will be cleared in a moment */
set_bit(br->dead_node, dlm->domain_map);
set_bit(br->dead_node, dlm->live_nodes_map);
__dlm_hb_node_down(dlm, br->dead_node);
}
spin_unlock(&dlm->spinlock);
dlm_kick_recovery_thread(dlm);
mlog(0, "%s: recovery started by node %u, for %u (%u:%u)\n",
dlm->name, br->node_idx, br->dead_node,
dlm->reco.dead_node, dlm->reco.new_master);
dlm_put(dlm);
return 0;
}
#define DLM_FINALIZE_STAGE2 0x01
static int dlm_send_finalize_reco_message(struct dlm_ctxt *dlm)
{
int ret = 0;
struct dlm_finalize_reco fr;
struct dlm_node_iter iter;
int nodenum;
int status;
int stage = 1;
mlog(0, "finishing recovery for node %s:%u, "
"stage %d\n", dlm->name, dlm->reco.dead_node, stage);
spin_lock(&dlm->spinlock);
dlm_node_iter_init(dlm->domain_map, &iter);
spin_unlock(&dlm->spinlock);
stage2:
memset(&fr, 0, sizeof(fr));
fr.node_idx = dlm->node_num;
fr.dead_node = dlm->reco.dead_node;
if (stage == 2)
fr.flags |= DLM_FINALIZE_STAGE2;
while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
if (nodenum == dlm->node_num)
continue;
ret = o2net_send_message(DLM_FINALIZE_RECO_MSG, dlm->key,
&fr, sizeof(fr), nodenum, &status);
if (ret >= 0)
ret = status;
if (ret < 0) {
mlog(ML_ERROR, "Error %d when sending message %u (key "
"0x%x) to node %u\n", ret, DLM_FINALIZE_RECO_MSG,
dlm->key, nodenum);
if (dlm_is_host_down(ret)) {
/* this has no effect on this recovery
* session, so set the status to zero to
* finish out the last recovery */
mlog(ML_ERROR, "node %u went down after this "
"node finished recovery.\n", nodenum);
ret = 0;
continue;
}
break;
}
}
if (stage == 1) {
/* reset the node_iter back to the top and send finalize2 */
iter.curnode = -1;
stage = 2;
goto stage2;
}
return ret;
}
int dlm_finalize_reco_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_finalize_reco *fr = (struct dlm_finalize_reco *)msg->buf;
int stage = 1;
/* ok to return 0, domain has gone away */
if (!dlm_grab(dlm))
return 0;
if (fr->flags & DLM_FINALIZE_STAGE2)
stage = 2;
mlog(0, "%s: node %u finalizing recovery stage%d of "
"node %u (%u:%u)\n", dlm->name, fr->node_idx, stage,
fr->dead_node, dlm->reco.dead_node, dlm->reco.new_master);
spin_lock(&dlm->spinlock);
if (dlm->reco.new_master != fr->node_idx) {
mlog(ML_ERROR, "node %u sent recovery finalize msg, but node "
"%u is supposed to be the new master, dead=%u\n",
fr->node_idx, dlm->reco.new_master, fr->dead_node);
BUG();
}
if (dlm->reco.dead_node != fr->dead_node) {
mlog(ML_ERROR, "node %u sent recovery finalize msg for dead "
"node %u, but node %u is supposed to be dead\n",
fr->node_idx, fr->dead_node, dlm->reco.dead_node);
BUG();
}
switch (stage) {
case 1:
dlm_finish_local_lockres_recovery(dlm, fr->dead_node, fr->node_idx);
if (dlm->reco.state & DLM_RECO_STATE_FINALIZE) {
mlog(ML_ERROR, "%s: received finalize1 from "
"new master %u for dead node %u, but "
"this node has already received it!\n",
dlm->name, fr->node_idx, fr->dead_node);
dlm_print_reco_node_status(dlm);
BUG();
}
dlm->reco.state |= DLM_RECO_STATE_FINALIZE;
spin_unlock(&dlm->spinlock);
break;
case 2:
if (!(dlm->reco.state & DLM_RECO_STATE_FINALIZE)) {
mlog(ML_ERROR, "%s: received finalize2 from "
"new master %u for dead node %u, but "
"this node did not have finalize1!\n",
dlm->name, fr->node_idx, fr->dead_node);
dlm_print_reco_node_status(dlm);
BUG();
}
dlm->reco.state &= ~DLM_RECO_STATE_FINALIZE;
spin_unlock(&dlm->spinlock);
dlm_reset_recovery(dlm);
dlm_kick_recovery_thread(dlm);
break;
default:
BUG();
}
mlog(0, "%s: recovery done, reco master was %u, dead now %u, master now %u\n",
dlm->name, fr->node_idx, dlm->reco.dead_node, dlm->reco.new_master);
dlm_put(dlm);
return 0;
}
| gpl-2.0 |
mastero9017/expectus_kernel_hammerhead | fs/jbd2/commit.c | 1989 | 33695 | /*
* linux/fs/jbd2/commit.c
*
* Written by Stephen C. Tweedie <sct@redhat.com>, 1998
*
* Copyright 1998 Red Hat corp --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Journal commit routines for the generic filesystem journaling code;
* part of the ext2fs journaling system.
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/jbd2.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/jiffies.h>
#include <linux/crc32.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/bitops.h>
#include <trace/events/jbd2.h>
/*
* Default IO end handler for temporary BJ_IO buffer_heads.
*/
static void journal_end_buffer_io_sync(struct buffer_head *bh, int uptodate)
{
BUFFER_TRACE(bh, "");
if (uptodate)
set_buffer_uptodate(bh);
else
clear_buffer_uptodate(bh);
unlock_buffer(bh);
}
/*
* When an ext4 file is truncated, it is possible that some pages are not
* successfully freed, because they are attached to a committing transaction.
* After the transaction commits, these pages are left on the LRU, with no
* ->mapping, and with attached buffers. These pages are trivially reclaimable
* by the VM, but their apparent absence upsets the VM accounting, and it makes
* the numbers in /proc/meminfo look odd.
*
* So here, we have a buffer which has just come off the forget list. Look to
* see if we can strip all buffers from the backing page.
*
* Called under lock_journal(), and possibly under journal_datalist_lock. The
* caller provided us with a ref against the buffer, and we drop that here.
*/
static void release_buffer_page(struct buffer_head *bh)
{
struct page *page;
if (buffer_dirty(bh))
goto nope;
if (atomic_read(&bh->b_count) != 1)
goto nope;
page = bh->b_page;
if (!page)
goto nope;
if (page->mapping)
goto nope;
/* OK, it's a truncated page */
if (!trylock_page(page))
goto nope;
page_cache_get(page);
__brelse(bh);
try_to_free_buffers(page);
unlock_page(page);
page_cache_release(page);
return;
nope:
__brelse(bh);
}
/*
* Done it all: now submit the commit record. We should have
* cleaned up our previous buffers by now, so if we are in abort
* mode we can now just skip the rest of the journal write
* entirely.
*
* Returns 1 if the journal needs to be aborted or 0 on success
*/
static int journal_submit_commit_record(journal_t *journal,
transaction_t *commit_transaction,
struct buffer_head **cbh,
__u32 crc32_sum)
{
struct journal_head *descriptor;
struct commit_header *tmp;
struct buffer_head *bh;
int ret;
struct timespec now = current_kernel_time();
*cbh = NULL;
if (is_journal_aborted(journal))
return 0;
descriptor = jbd2_journal_get_descriptor_buffer(journal);
if (!descriptor)
return 1;
bh = jh2bh(descriptor);
tmp = (struct commit_header *)bh->b_data;
tmp->h_magic = cpu_to_be32(JBD2_MAGIC_NUMBER);
tmp->h_blocktype = cpu_to_be32(JBD2_COMMIT_BLOCK);
tmp->h_sequence = cpu_to_be32(commit_transaction->t_tid);
tmp->h_commit_sec = cpu_to_be64(now.tv_sec);
tmp->h_commit_nsec = cpu_to_be32(now.tv_nsec);
if (JBD2_HAS_COMPAT_FEATURE(journal,
JBD2_FEATURE_COMPAT_CHECKSUM)) {
tmp->h_chksum_type = JBD2_CRC32_CHKSUM;
tmp->h_chksum_size = JBD2_CRC32_CHKSUM_SIZE;
tmp->h_chksum[0] = cpu_to_be32(crc32_sum);
}
JBUFFER_TRACE(descriptor, "submit commit block");
lock_buffer(bh);
clear_buffer_dirty(bh);
set_buffer_uptodate(bh);
bh->b_end_io = journal_end_buffer_io_sync;
if (journal->j_flags & JBD2_BARRIER &&
!JBD2_HAS_INCOMPAT_FEATURE(journal,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT))
ret = submit_bh(WRITE_SYNC | WRITE_FLUSH_FUA, bh);
else
ret = submit_bh(WRITE_SYNC, bh);
*cbh = bh;
return ret;
}
/*
* This function along with journal_submit_commit_record
* allows to write the commit record asynchronously.
*/
static int journal_wait_on_commit_record(journal_t *journal,
struct buffer_head *bh)
{
int ret = 0;
clear_buffer_dirty(bh);
wait_on_buffer(bh);
if (unlikely(!buffer_uptodate(bh)))
ret = -EIO;
put_bh(bh); /* One for getblk() */
jbd2_journal_put_journal_head(bh2jh(bh));
return ret;
}
/*
* write the filemap data using writepage() address_space_operations.
* We don't do block allocation here even for delalloc. We don't
* use writepages() because with dealyed allocation we may be doing
* block allocation in writepages().
*/
static int journal_submit_inode_data_buffers(struct address_space *mapping)
{
int ret;
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = mapping->nrpages * 2,
.range_start = 0,
.range_end = i_size_read(mapping->host),
};
ret = generic_writepages(mapping, &wbc);
return ret;
}
/*
* Submit all the data buffers of inode associated with the transaction to
* disk.
*
* We are in a committing transaction. Therefore no new inode can be added to
* our inode list. We use JI_COMMIT_RUNNING flag to protect inode we currently
* operate on from being released while we write out pages.
*/
static int journal_submit_data_buffers(journal_t *journal,
transaction_t *commit_transaction)
{
struct jbd2_inode *jinode;
int err, ret = 0;
struct address_space *mapping;
spin_lock(&journal->j_list_lock);
list_for_each_entry(jinode, &commit_transaction->t_inode_list, i_list) {
mapping = jinode->i_vfs_inode->i_mapping;
set_bit(__JI_COMMIT_RUNNING, &jinode->i_flags);
spin_unlock(&journal->j_list_lock);
/*
* submit the inode data buffers. We use writepage
* instead of writepages. Because writepages can do
* block allocation with delalloc. We need to write
* only allocated blocks here.
*/
trace_jbd2_submit_inode_data(jinode->i_vfs_inode);
err = journal_submit_inode_data_buffers(mapping);
if (!ret)
ret = err;
spin_lock(&journal->j_list_lock);
J_ASSERT(jinode->i_transaction == commit_transaction);
clear_bit(__JI_COMMIT_RUNNING, &jinode->i_flags);
smp_mb__after_clear_bit();
wake_up_bit(&jinode->i_flags, __JI_COMMIT_RUNNING);
}
spin_unlock(&journal->j_list_lock);
return ret;
}
/*
* Wait for data submitted for writeout, refile inodes to proper
* transaction if needed.
*
*/
static int journal_finish_inode_data_buffers(journal_t *journal,
transaction_t *commit_transaction)
{
struct jbd2_inode *jinode, *next_i;
int err, ret = 0;
/* For locking, see the comment in journal_submit_data_buffers() */
spin_lock(&journal->j_list_lock);
list_for_each_entry(jinode, &commit_transaction->t_inode_list, i_list) {
set_bit(__JI_COMMIT_RUNNING, &jinode->i_flags);
spin_unlock(&journal->j_list_lock);
err = filemap_fdatawait(jinode->i_vfs_inode->i_mapping);
if (err) {
/*
* Because AS_EIO is cleared by
* filemap_fdatawait_range(), set it again so
* that user process can get -EIO from fsync().
*/
set_bit(AS_EIO,
&jinode->i_vfs_inode->i_mapping->flags);
if (!ret)
ret = err;
}
spin_lock(&journal->j_list_lock);
clear_bit(__JI_COMMIT_RUNNING, &jinode->i_flags);
smp_mb__after_clear_bit();
wake_up_bit(&jinode->i_flags, __JI_COMMIT_RUNNING);
}
/* Now refile inode to proper lists */
list_for_each_entry_safe(jinode, next_i,
&commit_transaction->t_inode_list, i_list) {
list_del(&jinode->i_list);
if (jinode->i_next_transaction) {
jinode->i_transaction = jinode->i_next_transaction;
jinode->i_next_transaction = NULL;
list_add(&jinode->i_list,
&jinode->i_transaction->t_inode_list);
} else {
jinode->i_transaction = NULL;
}
}
spin_unlock(&journal->j_list_lock);
return ret;
}
static __u32 jbd2_checksum_data(__u32 crc32_sum, struct buffer_head *bh)
{
struct page *page = bh->b_page;
char *addr;
__u32 checksum;
addr = kmap_atomic(page);
checksum = crc32_be(crc32_sum,
(void *)(addr + offset_in_page(bh->b_data)), bh->b_size);
kunmap_atomic(addr);
return checksum;
}
static void write_tag_block(int tag_bytes, journal_block_tag_t *tag,
unsigned long long block)
{
tag->t_blocknr = cpu_to_be32(block & (u32)~0);
if (tag_bytes > JBD2_TAG_SIZE32)
tag->t_blocknr_high = cpu_to_be32((block >> 31) >> 1);
}
/*
* jbd2_journal_commit_transaction
*
* The primary function for committing a transaction to the log. This
* function is called by the journal thread to begin a complete commit.
*/
void jbd2_journal_commit_transaction(journal_t *journal)
{
struct transaction_stats_s stats;
transaction_t *commit_transaction;
struct journal_head *jh, *new_jh, *descriptor;
struct buffer_head **wbuf = journal->j_wbuf;
int bufs;
int flags;
int err;
unsigned long long blocknr;
ktime_t start_time;
u64 commit_time;
char *tagp = NULL;
journal_header_t *header;
journal_block_tag_t *tag = NULL;
int space_left = 0;
int first_tag = 0;
int tag_flag;
int i, to_free = 0;
int tag_bytes = journal_tag_bytes(journal);
struct buffer_head *cbh = NULL; /* For transactional checksums */
__u32 crc32_sum = ~0;
struct blk_plug plug;
/* Tail of the journal */
unsigned long first_block;
tid_t first_tid;
int update_tail;
/*
* First job: lock down the current transaction and wait for
* all outstanding updates to complete.
*/
/* Do we need to erase the effects of a prior jbd2_journal_flush? */
if (journal->j_flags & JBD2_FLUSHED) {
jbd_debug(3, "super block updated\n");
mutex_lock(&journal->j_checkpoint_mutex);
/*
* We hold j_checkpoint_mutex so tail cannot change under us.
* We don't need any special data guarantees for writing sb
* since journal is empty and it is ok for write to be
* flushed only with transaction commit.
*/
jbd2_journal_update_sb_log_tail(journal,
journal->j_tail_sequence,
journal->j_tail,
WRITE_SYNC);
mutex_unlock(&journal->j_checkpoint_mutex);
} else {
jbd_debug(3, "superblock not updated\n");
}
J_ASSERT(journal->j_running_transaction != NULL);
J_ASSERT(journal->j_committing_transaction == NULL);
commit_transaction = journal->j_running_transaction;
J_ASSERT(commit_transaction->t_state == T_RUNNING);
trace_jbd2_start_commit(journal, commit_transaction);
jbd_debug(1, "JBD2: starting commit of transaction %d\n",
commit_transaction->t_tid);
write_lock(&journal->j_state_lock);
commit_transaction->t_state = T_LOCKED;
trace_jbd2_commit_locking(journal, commit_transaction);
stats.run.rs_wait = commit_transaction->t_max_wait;
stats.run.rs_locked = jiffies;
stats.run.rs_running = jbd2_time_diff(commit_transaction->t_start,
stats.run.rs_locked);
spin_lock(&commit_transaction->t_handle_lock);
while (atomic_read(&commit_transaction->t_updates)) {
DEFINE_WAIT(wait);
prepare_to_wait(&journal->j_wait_updates, &wait,
TASK_UNINTERRUPTIBLE);
if (atomic_read(&commit_transaction->t_updates)) {
spin_unlock(&commit_transaction->t_handle_lock);
write_unlock(&journal->j_state_lock);
schedule();
write_lock(&journal->j_state_lock);
spin_lock(&commit_transaction->t_handle_lock);
}
finish_wait(&journal->j_wait_updates, &wait);
}
spin_unlock(&commit_transaction->t_handle_lock);
J_ASSERT (atomic_read(&commit_transaction->t_outstanding_credits) <=
journal->j_max_transaction_buffers);
/*
* First thing we are allowed to do is to discard any remaining
* BJ_Reserved buffers. Note, it is _not_ permissible to assume
* that there are no such buffers: if a large filesystem
* operation like a truncate needs to split itself over multiple
* transactions, then it may try to do a jbd2_journal_restart() while
* there are still BJ_Reserved buffers outstanding. These must
* be released cleanly from the current transaction.
*
* In this case, the filesystem must still reserve write access
* again before modifying the buffer in the new transaction, but
* we do not require it to remember exactly which old buffers it
* has reserved. This is consistent with the existing behaviour
* that multiple jbd2_journal_get_write_access() calls to the same
* buffer are perfectly permissible.
*/
while (commit_transaction->t_reserved_list) {
jh = commit_transaction->t_reserved_list;
JBUFFER_TRACE(jh, "reserved, unused: refile");
/*
* A jbd2_journal_get_undo_access()+jbd2_journal_release_buffer() may
* leave undo-committed data.
*/
if (jh->b_committed_data) {
struct buffer_head *bh = jh2bh(jh);
jbd_lock_bh_state(bh);
jbd2_free(jh->b_committed_data, bh->b_size);
jh->b_committed_data = NULL;
jbd_unlock_bh_state(bh);
}
jbd2_journal_refile_buffer(journal, jh);
}
/*
* Now try to drop any written-back buffers from the journal's
* checkpoint lists. We do this *before* commit because it potentially
* frees some memory
*/
spin_lock(&journal->j_list_lock);
__jbd2_journal_clean_checkpoint_list(journal);
spin_unlock(&journal->j_list_lock);
jbd_debug(3, "JBD2: commit phase 1\n");
/*
* Clear revoked flag to reflect there is no revoked buffers
* in the next transaction which is going to be started.
*/
jbd2_clear_buffer_revoked_flags(journal);
/*
* Switch to a new revoke table.
*/
jbd2_journal_switch_revoke_table(journal);
trace_jbd2_commit_flushing(journal, commit_transaction);
stats.run.rs_flushing = jiffies;
stats.run.rs_locked = jbd2_time_diff(stats.run.rs_locked,
stats.run.rs_flushing);
commit_transaction->t_state = T_FLUSH;
journal->j_committing_transaction = commit_transaction;
journal->j_running_transaction = NULL;
start_time = ktime_get();
commit_transaction->t_log_start = journal->j_head;
wake_up(&journal->j_wait_transaction_locked);
write_unlock(&journal->j_state_lock);
jbd_debug(3, "JBD2: commit phase 2\n");
/*
* Now start flushing things to disk, in the order they appear
* on the transaction lists. Data blocks go first.
*/
err = journal_submit_data_buffers(journal, commit_transaction);
if (err)
jbd2_journal_abort(journal, err);
blk_start_plug(&plug);
jbd2_journal_write_revoke_records(journal, commit_transaction,
WRITE_SYNC);
blk_finish_plug(&plug);
jbd_debug(3, "JBD2: commit phase 2\n");
/*
* Way to go: we have now written out all of the data for a
* transaction! Now comes the tricky part: we need to write out
* metadata. Loop over the transaction's entire buffer list:
*/
write_lock(&journal->j_state_lock);
commit_transaction->t_state = T_COMMIT;
write_unlock(&journal->j_state_lock);
trace_jbd2_commit_logging(journal, commit_transaction);
stats.run.rs_logging = jiffies;
stats.run.rs_flushing = jbd2_time_diff(stats.run.rs_flushing,
stats.run.rs_logging);
stats.run.rs_blocks =
atomic_read(&commit_transaction->t_outstanding_credits);
stats.run.rs_blocks_logged = 0;
J_ASSERT(commit_transaction->t_nr_buffers <=
atomic_read(&commit_transaction->t_outstanding_credits));
err = 0;
descriptor = NULL;
bufs = 0;
blk_start_plug(&plug);
while (commit_transaction->t_buffers) {
/* Find the next buffer to be journaled... */
jh = commit_transaction->t_buffers;
/* If we're in abort mode, we just un-journal the buffer and
release it. */
if (is_journal_aborted(journal)) {
clear_buffer_jbddirty(jh2bh(jh));
JBUFFER_TRACE(jh, "journal is aborting: refile");
jbd2_buffer_abort_trigger(jh,
jh->b_frozen_data ?
jh->b_frozen_triggers :
jh->b_triggers);
jbd2_journal_refile_buffer(journal, jh);
/* If that was the last one, we need to clean up
* any descriptor buffers which may have been
* already allocated, even if we are now
* aborting. */
if (!commit_transaction->t_buffers)
goto start_journal_io;
continue;
}
/* Make sure we have a descriptor block in which to
record the metadata buffer. */
if (!descriptor) {
struct buffer_head *bh;
J_ASSERT (bufs == 0);
jbd_debug(4, "JBD2: get descriptor\n");
descriptor = jbd2_journal_get_descriptor_buffer(journal);
if (!descriptor) {
jbd2_journal_abort(journal, -EIO);
continue;
}
bh = jh2bh(descriptor);
jbd_debug(4, "JBD2: got buffer %llu (%p)\n",
(unsigned long long)bh->b_blocknr, bh->b_data);
header = (journal_header_t *)&bh->b_data[0];
header->h_magic = cpu_to_be32(JBD2_MAGIC_NUMBER);
header->h_blocktype = cpu_to_be32(JBD2_DESCRIPTOR_BLOCK);
header->h_sequence = cpu_to_be32(commit_transaction->t_tid);
tagp = &bh->b_data[sizeof(journal_header_t)];
space_left = bh->b_size - sizeof(journal_header_t);
first_tag = 1;
set_buffer_jwrite(bh);
set_buffer_dirty(bh);
wbuf[bufs++] = bh;
/* Record it so that we can wait for IO
completion later */
BUFFER_TRACE(bh, "ph3: file as descriptor");
jbd2_journal_file_buffer(descriptor, commit_transaction,
BJ_LogCtl);
}
/* Where is the buffer to be written? */
err = jbd2_journal_next_log_block(journal, &blocknr);
/* If the block mapping failed, just abandon the buffer
and repeat this loop: we'll fall into the
refile-on-abort condition above. */
if (err) {
jbd2_journal_abort(journal, err);
continue;
}
/*
* start_this_handle() uses t_outstanding_credits to determine
* the free space in the log, but this counter is changed
* by jbd2_journal_next_log_block() also.
*/
atomic_dec(&commit_transaction->t_outstanding_credits);
/* Bump b_count to prevent truncate from stumbling over
the shadowed buffer! @@@ This can go if we ever get
rid of the BJ_IO/BJ_Shadow pairing of buffers. */
atomic_inc(&jh2bh(jh)->b_count);
/* Make a temporary IO buffer with which to write it out
(this will requeue both the metadata buffer and the
temporary IO buffer). new_bh goes on BJ_IO*/
set_bit(BH_JWrite, &jh2bh(jh)->b_state);
/*
* akpm: jbd2_journal_write_metadata_buffer() sets
* new_bh->b_transaction to commit_transaction.
* We need to clean this up before we release new_bh
* (which is of type BJ_IO)
*/
JBUFFER_TRACE(jh, "ph3: write metadata");
flags = jbd2_journal_write_metadata_buffer(commit_transaction,
jh, &new_jh, blocknr);
if (flags < 0) {
jbd2_journal_abort(journal, flags);
continue;
}
set_bit(BH_JWrite, &jh2bh(new_jh)->b_state);
wbuf[bufs++] = jh2bh(new_jh);
/* Record the new block's tag in the current descriptor
buffer */
tag_flag = 0;
if (flags & 1)
tag_flag |= JBD2_FLAG_ESCAPE;
if (!first_tag)
tag_flag |= JBD2_FLAG_SAME_UUID;
tag = (journal_block_tag_t *) tagp;
write_tag_block(tag_bytes, tag, jh2bh(jh)->b_blocknr);
tag->t_flags = cpu_to_be32(tag_flag);
tagp += tag_bytes;
space_left -= tag_bytes;
if (first_tag) {
memcpy (tagp, journal->j_uuid, 16);
tagp += 16;
space_left -= 16;
first_tag = 0;
}
/* If there's no more to do, or if the descriptor is full,
let the IO rip! */
if (bufs == journal->j_wbufsize ||
commit_transaction->t_buffers == NULL ||
space_left < tag_bytes + 16) {
jbd_debug(4, "JBD2: Submit %d IOs\n", bufs);
/* Write an end-of-descriptor marker before
submitting the IOs. "tag" still points to
the last tag we set up. */
tag->t_flags |= cpu_to_be32(JBD2_FLAG_LAST_TAG);
start_journal_io:
for (i = 0; i < bufs; i++) {
struct buffer_head *bh = wbuf[i];
/*
* Compute checksum.
*/
if (JBD2_HAS_COMPAT_FEATURE(journal,
JBD2_FEATURE_COMPAT_CHECKSUM)) {
crc32_sum =
jbd2_checksum_data(crc32_sum, bh);
}
lock_buffer(bh);
clear_buffer_dirty(bh);
set_buffer_uptodate(bh);
bh->b_end_io = journal_end_buffer_io_sync;
submit_bh(WRITE_SYNC, bh);
}
cond_resched();
stats.run.rs_blocks_logged += bufs;
/* Force a new descriptor to be generated next
time round the loop. */
descriptor = NULL;
bufs = 0;
}
}
err = journal_finish_inode_data_buffers(journal, commit_transaction);
if (err) {
printk(KERN_WARNING
"JBD2: Detected IO errors while flushing file data "
"on %s\n", journal->j_devname);
if (journal->j_flags & JBD2_ABORT_ON_SYNCDATA_ERR)
jbd2_journal_abort(journal, err);
err = 0;
}
/*
* Get current oldest transaction in the log before we issue flush
* to the filesystem device. After the flush we can be sure that
* blocks of all older transactions are checkpointed to persistent
* storage and we will be safe to update journal start in the
* superblock with the numbers we get here.
*/
update_tail =
jbd2_journal_get_log_tail(journal, &first_tid, &first_block);
write_lock(&journal->j_state_lock);
if (update_tail) {
long freed = first_block - journal->j_tail;
if (first_block < journal->j_tail)
freed += journal->j_last - journal->j_first;
/* Update tail only if we free significant amount of space */
if (freed < journal->j_maxlen / 4)
update_tail = 0;
}
J_ASSERT(commit_transaction->t_state == T_COMMIT);
commit_transaction->t_state = T_COMMIT_DFLUSH;
write_unlock(&journal->j_state_lock);
/*
* If the journal is not located on the file system device,
* then we must flush the file system device before we issue
* the commit record
*/
if (commit_transaction->t_need_data_flush &&
(journal->j_fs_dev != journal->j_dev) &&
(journal->j_flags & JBD2_BARRIER))
blkdev_issue_flush(journal->j_fs_dev, GFP_NOFS, NULL);
/* Done it all: now write the commit record asynchronously. */
if (JBD2_HAS_INCOMPAT_FEATURE(journal,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT)) {
err = journal_submit_commit_record(journal, commit_transaction,
&cbh, crc32_sum);
if (err)
__jbd2_journal_abort_hard(journal);
}
blk_finish_plug(&plug);
/* Lo and behold: we have just managed to send a transaction to
the log. Before we can commit it, wait for the IO so far to
complete. Control buffers being written are on the
transaction's t_log_list queue, and metadata buffers are on
the t_iobuf_list queue.
Wait for the buffers in reverse order. That way we are
less likely to be woken up until all IOs have completed, and
so we incur less scheduling load.
*/
jbd_debug(3, "JBD2: commit phase 3\n");
/*
* akpm: these are BJ_IO, and j_list_lock is not needed.
* See __journal_try_to_free_buffer.
*/
wait_for_iobuf:
while (commit_transaction->t_iobuf_list != NULL) {
struct buffer_head *bh;
jh = commit_transaction->t_iobuf_list->b_tprev;
bh = jh2bh(jh);
if (buffer_locked(bh)) {
wait_on_buffer(bh);
goto wait_for_iobuf;
}
if (cond_resched())
goto wait_for_iobuf;
if (unlikely(!buffer_uptodate(bh)))
err = -EIO;
clear_buffer_jwrite(bh);
JBUFFER_TRACE(jh, "ph4: unfile after journal write");
jbd2_journal_unfile_buffer(journal, jh);
/*
* ->t_iobuf_list should contain only dummy buffer_heads
* which were created by jbd2_journal_write_metadata_buffer().
*/
BUFFER_TRACE(bh, "dumping temporary bh");
jbd2_journal_put_journal_head(jh);
__brelse(bh);
J_ASSERT_BH(bh, atomic_read(&bh->b_count) == 0);
free_buffer_head(bh);
/* We also have to unlock and free the corresponding
shadowed buffer */
jh = commit_transaction->t_shadow_list->b_tprev;
bh = jh2bh(jh);
clear_bit(BH_JWrite, &bh->b_state);
J_ASSERT_BH(bh, buffer_jbddirty(bh));
/* The metadata is now released for reuse, but we need
to remember it against this transaction so that when
we finally commit, we can do any checkpointing
required. */
JBUFFER_TRACE(jh, "file as BJ_Forget");
jbd2_journal_file_buffer(jh, commit_transaction, BJ_Forget);
/*
* Wake up any transactions which were waiting for this IO to
* complete. The barrier must be here so that changes by
* jbd2_journal_file_buffer() take effect before wake_up_bit()
* does the waitqueue check.
*/
smp_mb();
wake_up_bit(&bh->b_state, BH_Unshadow);
JBUFFER_TRACE(jh, "brelse shadowed buffer");
__brelse(bh);
}
J_ASSERT (commit_transaction->t_shadow_list == NULL);
jbd_debug(3, "JBD2: commit phase 4\n");
/* Here we wait for the revoke record and descriptor record buffers */
wait_for_ctlbuf:
while (commit_transaction->t_log_list != NULL) {
struct buffer_head *bh;
jh = commit_transaction->t_log_list->b_tprev;
bh = jh2bh(jh);
if (buffer_locked(bh)) {
wait_on_buffer(bh);
goto wait_for_ctlbuf;
}
if (cond_resched())
goto wait_for_ctlbuf;
if (unlikely(!buffer_uptodate(bh)))
err = -EIO;
BUFFER_TRACE(bh, "ph5: control buffer writeout done: unfile");
clear_buffer_jwrite(bh);
jbd2_journal_unfile_buffer(journal, jh);
jbd2_journal_put_journal_head(jh);
__brelse(bh); /* One for getblk */
/* AKPM: bforget here */
}
if (err)
jbd2_journal_abort(journal, err);
jbd_debug(3, "JBD2: commit phase 5\n");
write_lock(&journal->j_state_lock);
J_ASSERT(commit_transaction->t_state == T_COMMIT_DFLUSH);
commit_transaction->t_state = T_COMMIT_JFLUSH;
write_unlock(&journal->j_state_lock);
if (!JBD2_HAS_INCOMPAT_FEATURE(journal,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT)) {
err = journal_submit_commit_record(journal, commit_transaction,
&cbh, crc32_sum);
if (err)
__jbd2_journal_abort_hard(journal);
}
if (cbh)
err = journal_wait_on_commit_record(journal, cbh);
if (JBD2_HAS_INCOMPAT_FEATURE(journal,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT) &&
journal->j_flags & JBD2_BARRIER) {
blkdev_issue_flush(journal->j_dev, GFP_NOFS, NULL);
}
if (err)
jbd2_journal_abort(journal, err);
/*
* Now disk caches for filesystem device are flushed so we are safe to
* erase checkpointed transactions from the log by updating journal
* superblock.
*/
if (update_tail)
jbd2_update_log_tail(journal, first_tid, first_block);
/* End of a transaction! Finally, we can do checkpoint
processing: any buffers committed as a result of this
transaction can be removed from any checkpoint list it was on
before. */
jbd_debug(3, "JBD2: commit phase 6\n");
J_ASSERT(list_empty(&commit_transaction->t_inode_list));
J_ASSERT(commit_transaction->t_buffers == NULL);
J_ASSERT(commit_transaction->t_checkpoint_list == NULL);
J_ASSERT(commit_transaction->t_iobuf_list == NULL);
J_ASSERT(commit_transaction->t_shadow_list == NULL);
J_ASSERT(commit_transaction->t_log_list == NULL);
restart_loop:
/*
* As there are other places (journal_unmap_buffer()) adding buffers
* to this list we have to be careful and hold the j_list_lock.
*/
spin_lock(&journal->j_list_lock);
while (commit_transaction->t_forget) {
transaction_t *cp_transaction;
struct buffer_head *bh;
int try_to_free = 0;
jh = commit_transaction->t_forget;
spin_unlock(&journal->j_list_lock);
bh = jh2bh(jh);
/*
* Get a reference so that bh cannot be freed before we are
* done with it.
*/
get_bh(bh);
jbd_lock_bh_state(bh);
J_ASSERT_JH(jh, jh->b_transaction == commit_transaction);
/*
* If there is undo-protected committed data against
* this buffer, then we can remove it now. If it is a
* buffer needing such protection, the old frozen_data
* field now points to a committed version of the
* buffer, so rotate that field to the new committed
* data.
*
* Otherwise, we can just throw away the frozen data now.
*
* We also know that the frozen data has already fired
* its triggers if they exist, so we can clear that too.
*/
if (jh->b_committed_data) {
jbd2_free(jh->b_committed_data, bh->b_size);
jh->b_committed_data = NULL;
if (jh->b_frozen_data) {
jh->b_committed_data = jh->b_frozen_data;
jh->b_frozen_data = NULL;
jh->b_frozen_triggers = NULL;
}
} else if (jh->b_frozen_data) {
jbd2_free(jh->b_frozen_data, bh->b_size);
jh->b_frozen_data = NULL;
jh->b_frozen_triggers = NULL;
}
spin_lock(&journal->j_list_lock);
cp_transaction = jh->b_cp_transaction;
if (cp_transaction) {
JBUFFER_TRACE(jh, "remove from old cp transaction");
cp_transaction->t_chp_stats.cs_dropped++;
__jbd2_journal_remove_checkpoint(jh);
}
/* Only re-checkpoint the buffer_head if it is marked
* dirty. If the buffer was added to the BJ_Forget list
* by jbd2_journal_forget, it may no longer be dirty and
* there's no point in keeping a checkpoint record for
* it. */
/* A buffer which has been freed while still being
* journaled by a previous transaction may end up still
* being dirty here, but we want to avoid writing back
* that buffer in the future after the "add to orphan"
* operation been committed, That's not only a performance
* gain, it also stops aliasing problems if the buffer is
* left behind for writeback and gets reallocated for another
* use in a different page. */
if (buffer_freed(bh) && !jh->b_next_transaction) {
clear_buffer_freed(bh);
clear_buffer_jbddirty(bh);
}
if (buffer_jbddirty(bh)) {
JBUFFER_TRACE(jh, "add to new checkpointing trans");
__jbd2_journal_insert_checkpoint(jh, commit_transaction);
if (is_journal_aborted(journal))
clear_buffer_jbddirty(bh);
} else {
J_ASSERT_BH(bh, !buffer_dirty(bh));
/*
* The buffer on BJ_Forget list and not jbddirty means
* it has been freed by this transaction and hence it
* could not have been reallocated until this
* transaction has committed. *BUT* it could be
* reallocated once we have written all the data to
* disk and before we process the buffer on BJ_Forget
* list.
*/
if (!jh->b_next_transaction)
try_to_free = 1;
}
JBUFFER_TRACE(jh, "refile or unfile buffer");
__jbd2_journal_refile_buffer(jh);
jbd_unlock_bh_state(bh);
if (try_to_free)
release_buffer_page(bh); /* Drops bh reference */
else
__brelse(bh);
cond_resched_lock(&journal->j_list_lock);
}
spin_unlock(&journal->j_list_lock);
/*
* This is a bit sleazy. We use j_list_lock to protect transition
* of a transaction into T_FINISHED state and calling
* __jbd2_journal_drop_transaction(). Otherwise we could race with
* other checkpointing code processing the transaction...
*/
write_lock(&journal->j_state_lock);
spin_lock(&journal->j_list_lock);
/*
* Now recheck if some buffers did not get attached to the transaction
* while the lock was dropped...
*/
if (commit_transaction->t_forget) {
spin_unlock(&journal->j_list_lock);
write_unlock(&journal->j_state_lock);
goto restart_loop;
}
/* Done with this transaction! */
jbd_debug(3, "JBD2: commit phase 7\n");
J_ASSERT(commit_transaction->t_state == T_COMMIT_JFLUSH);
commit_transaction->t_start = jiffies;
stats.run.rs_logging = jbd2_time_diff(stats.run.rs_logging,
commit_transaction->t_start);
/*
* File the transaction statistics
*/
stats.ts_tid = commit_transaction->t_tid;
stats.run.rs_handle_count =
atomic_read(&commit_transaction->t_handle_count);
trace_jbd2_run_stats(journal->j_fs_dev->bd_dev,
commit_transaction->t_tid, &stats.run);
/*
* Calculate overall stats
*/
spin_lock(&journal->j_history_lock);
journal->j_stats.ts_tid++;
journal->j_stats.run.rs_wait += stats.run.rs_wait;
journal->j_stats.run.rs_running += stats.run.rs_running;
journal->j_stats.run.rs_locked += stats.run.rs_locked;
journal->j_stats.run.rs_flushing += stats.run.rs_flushing;
journal->j_stats.run.rs_logging += stats.run.rs_logging;
journal->j_stats.run.rs_handle_count += stats.run.rs_handle_count;
journal->j_stats.run.rs_blocks += stats.run.rs_blocks;
journal->j_stats.run.rs_blocks_logged += stats.run.rs_blocks_logged;
spin_unlock(&journal->j_history_lock);
commit_transaction->t_state = T_FINISHED;
J_ASSERT(commit_transaction == journal->j_committing_transaction);
journal->j_commit_sequence = commit_transaction->t_tid;
journal->j_committing_transaction = NULL;
commit_time = ktime_to_ns(ktime_sub(ktime_get(), start_time));
/*
* weight the commit time higher than the average time so we don't
* react too strongly to vast changes in the commit time
*/
if (likely(journal->j_average_commit_time))
journal->j_average_commit_time = (commit_time +
journal->j_average_commit_time*3) / 4;
else
journal->j_average_commit_time = commit_time;
write_unlock(&journal->j_state_lock);
if (commit_transaction->t_checkpoint_list == NULL &&
commit_transaction->t_checkpoint_io_list == NULL) {
__jbd2_journal_drop_transaction(journal, commit_transaction);
to_free = 1;
} else {
if (journal->j_checkpoint_transactions == NULL) {
journal->j_checkpoint_transactions = commit_transaction;
commit_transaction->t_cpnext = commit_transaction;
commit_transaction->t_cpprev = commit_transaction;
} else {
commit_transaction->t_cpnext =
journal->j_checkpoint_transactions;
commit_transaction->t_cpprev =
commit_transaction->t_cpnext->t_cpprev;
commit_transaction->t_cpnext->t_cpprev =
commit_transaction;
commit_transaction->t_cpprev->t_cpnext =
commit_transaction;
}
}
spin_unlock(&journal->j_list_lock);
if (journal->j_commit_callback)
journal->j_commit_callback(journal, commit_transaction);
trace_jbd2_end_commit(journal, commit_transaction);
jbd_debug(1, "JBD2: commit %d complete, head %d\n",
journal->j_commit_sequence, journal->j_tail_sequence);
if (to_free)
jbd2_journal_free_transaction(commit_transaction);
wake_up(&journal->j_wait_done_commit);
}
| gpl-2.0 |
TV-LP51-Devices/android_kernel_mediatek_sprout | drivers/input/keyboard/jornada680_kbd.c | 2245 | 8054 | /*
* drivers/input/keyboard/jornada680_kbd.c
*
* HP Jornada 620/660/680/690 scan keyboard platform driver
* Copyright (C) 2007 Kristoffer Ericson <Kristoffer.Ericson@gmail.com>
*
* Based on hp680_keyb.c
* Copyright (C) 2006 Paul Mundt
* Copyright (C) 2005 Andriy Skulysh
* Split from drivers/input/keyboard/hp600_keyb.c
* Copyright (C) 2000 Yaegashi Takeshi (hp6xx kbd scan routine and translation table)
* Copyright (C) 2000 Niibe Yutaka (HP620 Keyb translation table)
*
* 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/input.h>
#include <linux/input-polldev.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/delay.h>
#include <asm/io.h>
#define PCCR 0xa4000104
#define PDCR 0xa4000106
#define PECR 0xa4000108
#define PFCR 0xa400010a
#define PCDR 0xa4000124
#define PDDR 0xa4000126
#define PEDR 0xa4000128
#define PFDR 0xa400012a
#define PGDR 0xa400012c
#define PHDR 0xa400012e
#define PJDR 0xa4000130
#define PKDR 0xa4000132
#define PLDR 0xa4000134
static const unsigned short jornada_scancodes[] = {
/* PTD1 */ KEY_CAPSLOCK, KEY_MACRO, KEY_LEFTCTRL, 0, KEY_ESC, KEY_KP5, 0, 0, /* 1 -> 8 */
KEY_F1, KEY_F2, KEY_F3, KEY_F8, KEY_F7, KEY_F6, KEY_F4, KEY_F5, /* 9 -> 16 */
/* PTD5 */ KEY_SLASH, KEY_APOSTROPHE, KEY_ENTER, 0, KEY_Z, 0, 0, 0, /* 17 -> 24 */
KEY_X, KEY_C, KEY_V, KEY_DOT, KEY_COMMA, KEY_M, KEY_B, KEY_N, /* 25 -> 32 */
/* PTD7 */ KEY_KP2, KEY_KP6, KEY_KP3, 0, 0, 0, 0, 0, /* 33 -> 40 */
KEY_F10, KEY_RO, KEY_F9, KEY_KP4, KEY_NUMLOCK, KEY_SCROLLLOCK, KEY_LEFTALT, KEY_HANJA, /* 41 -> 48 */
/* PTE0 */ KEY_KATAKANA, KEY_KP0, KEY_GRAVE, 0, KEY_FINANCE, 0, 0, 0, /* 49 -> 56 */
KEY_KPMINUS, KEY_HIRAGANA, KEY_SPACE, KEY_KPDOT, KEY_VOLUMEUP, 249, 0, 0, /* 57 -> 64 */
/* PTE1 */ KEY_SEMICOLON, KEY_RIGHTBRACE, KEY_BACKSLASH, 0, KEY_A, 0, 0, 0, /* 65 -> 72 */
KEY_S, KEY_D, KEY_F, KEY_L, KEY_K, KEY_J, KEY_G, KEY_H, /* 73 -> 80 */
/* PTE3 */ KEY_KP8, KEY_LEFTMETA, KEY_RIGHTSHIFT, 0, KEY_TAB, 0, 0, 0, /* 81 -> 88 */
0, KEY_LEFTSHIFT, KEY_KP7, KEY_KP9, KEY_KP1, KEY_F11, KEY_KPPLUS, KEY_KPASTERISK, /* 89 -> 96 */
/* PTE6 */ KEY_P, KEY_LEFTBRACE, KEY_BACKSPACE, 0, KEY_Q, 0, 0, 0, /* 97 -> 104 */
KEY_W, KEY_E, KEY_R, KEY_O, KEY_I, KEY_U, KEY_T, KEY_Y, /* 105 -> 112 */
/* PTE7 */ KEY_0, KEY_MINUS, KEY_EQUAL, 0, KEY_1, 0, 0, 0, /* 113 -> 120 */
KEY_2, KEY_3, KEY_4, KEY_9, KEY_8, KEY_7, KEY_5, KEY_6, /* 121 -> 128 */
/* **** */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
#define JORNADA_SCAN_SIZE 18
struct jornadakbd {
struct input_polled_dev *poll_dev;
unsigned short keymap[ARRAY_SIZE(jornada_scancodes)];
unsigned char length;
unsigned char old_scan[JORNADA_SCAN_SIZE];
unsigned char new_scan[JORNADA_SCAN_SIZE];
};
static void jornada_parse_kbd(struct jornadakbd *jornadakbd)
{
struct input_dev *input_dev = jornadakbd->poll_dev->input;
unsigned short *keymap = jornadakbd->keymap;
unsigned int sync_me = 0;
unsigned int i, j;
for (i = 0; i < JORNADA_SCAN_SIZE; i++) {
unsigned char new = jornadakbd->new_scan[i];
unsigned char old = jornadakbd->old_scan[i];
unsigned int xor = new ^ old;
if (xor == 0)
continue;
for (j = 0; j < 8; j++) {
unsigned int bit = 1 << j;
if (xor & bit) {
unsigned int scancode = (i << 3) + j;
input_event(input_dev,
EV_MSC, MSC_SCAN, scancode);
input_report_key(input_dev,
keymap[scancode],
!(new & bit));
sync_me = 1;
}
}
}
if (sync_me)
input_sync(input_dev);
}
static void jornada_scan_keyb(unsigned char *s)
{
int i;
unsigned short ec_static, dc_static; /* = UINT16_t */
unsigned char matrix_switch[] = {
0xfd, 0xff, /* PTD1 PD(1) */
0xdf, 0xff, /* PTD5 PD(5) */
0x7f, 0xff, /* PTD7 PD(7) */
0xff, 0xfe, /* PTE0 PE(0) */
0xff, 0xfd, /* PTE1 PE(1) */
0xff, 0xf7, /* PTE3 PE(3) */
0xff, 0xbf, /* PTE6 PE(6) */
0xff, 0x7f, /* PTE7 PE(7) */
}, *t = matrix_switch;
/* PD(x) :
1. 0xcc0c & (1~(1 << (2*(x)+1)))))
2. (0xf0cf & 0xfffff) */
/* PE(x) :
1. 0xcc0c & 0xffff
2. 0xf0cf & (1~(1 << (2*(x)+1))))) */
unsigned short matrix_PDE[] = {
0xcc04, 0xf0cf, /* PD(1) */
0xc40c, 0xf0cf, /* PD(5) */
0x4c0c, 0xf0cf, /* PD(7) */
0xcc0c, 0xf0cd, /* PE(0) */
0xcc0c, 0xf0c7, /* PE(1) */
0xcc0c, 0xf04f, /* PE(3) */
0xcc0c, 0xd0cf, /* PE(6) */
0xcc0c, 0x70cf, /* PE(7) */
}, *y = matrix_PDE;
/* Save these control reg bits */
dc_static = (__raw_readw(PDCR) & (~0xcc0c));
ec_static = (__raw_readw(PECR) & (~0xf0cf));
for (i = 0; i < 8; i++) {
/* disable output for all but the one we want to scan */
__raw_writew((dc_static | *y++), PDCR);
__raw_writew((ec_static | *y++), PECR);
udelay(5);
/* Get scanline row */
__raw_writeb(*t++, PDDR);
__raw_writeb(*t++, PEDR);
udelay(50);
/* Read data */
*s++ = __raw_readb(PCDR);
*s++ = __raw_readb(PFDR);
}
/* Scan no lines */
__raw_writeb(0xff, PDDR);
__raw_writeb(0xff, PEDR);
/* Enable all scanlines */
__raw_writew((dc_static | (0x5555 & 0xcc0c)),PDCR);
__raw_writew((ec_static | (0x5555 & 0xf0cf)),PECR);
/* Ignore extra keys and events */
*s++ = __raw_readb(PGDR);
*s++ = __raw_readb(PHDR);
}
static void jornadakbd680_poll(struct input_polled_dev *dev)
{
struct jornadakbd *jornadakbd = dev->private;
jornada_scan_keyb(jornadakbd->new_scan);
jornada_parse_kbd(jornadakbd);
memcpy(jornadakbd->old_scan, jornadakbd->new_scan, JORNADA_SCAN_SIZE);
}
static int jornada680kbd_probe(struct platform_device *pdev)
{
struct jornadakbd *jornadakbd;
struct input_polled_dev *poll_dev;
struct input_dev *input_dev;
int i, error;
jornadakbd = kzalloc(sizeof(struct jornadakbd), GFP_KERNEL);
if (!jornadakbd)
return -ENOMEM;
poll_dev = input_allocate_polled_device();
if (!poll_dev) {
error = -ENOMEM;
goto failed;
}
platform_set_drvdata(pdev, jornadakbd);
jornadakbd->poll_dev = poll_dev;
memcpy(jornadakbd->keymap, jornada_scancodes,
sizeof(jornadakbd->keymap));
poll_dev->private = jornadakbd;
poll_dev->poll = jornadakbd680_poll;
poll_dev->poll_interval = 50; /* msec */
input_dev = poll_dev->input;
input_dev->evbit[0] = BIT(EV_KEY) | BIT(EV_REP);
input_dev->name = "HP Jornada 680 keyboard";
input_dev->phys = "jornadakbd/input0";
input_dev->keycode = jornadakbd->keymap;
input_dev->keycodesize = sizeof(unsigned short);
input_dev->keycodemax = ARRAY_SIZE(jornada_scancodes);
input_dev->dev.parent = &pdev->dev;
input_dev->id.bustype = BUS_HOST;
for (i = 0; i < 128; i++)
if (jornadakbd->keymap[i])
__set_bit(jornadakbd->keymap[i], input_dev->keybit);
__clear_bit(KEY_RESERVED, input_dev->keybit);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
error = input_register_polled_device(jornadakbd->poll_dev);
if (error)
goto failed;
return 0;
failed:
printk(KERN_ERR "Jornadakbd: failed to register driver, error: %d\n",
error);
platform_set_drvdata(pdev, NULL);
input_free_polled_device(poll_dev);
kfree(jornadakbd);
return error;
}
static int jornada680kbd_remove(struct platform_device *pdev)
{
struct jornadakbd *jornadakbd = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
input_unregister_polled_device(jornadakbd->poll_dev);
input_free_polled_device(jornadakbd->poll_dev);
kfree(jornadakbd);
return 0;
}
static struct platform_driver jornada680kbd_driver = {
.driver = {
.name = "jornada680_kbd",
.owner = THIS_MODULE,
},
.probe = jornada680kbd_probe,
.remove = jornada680kbd_remove,
};
module_platform_driver(jornada680kbd_driver);
MODULE_AUTHOR("Kristoffer Ericson <kristoffer.ericson@gmail.com>");
MODULE_DESCRIPTION("HP Jornada 620/660/680/690 Keyboard Driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:jornada680_kbd");
| gpl-2.0 |
Fevax/kernel_samsung_exynos5422 | drivers/staging/iio/iio_simple_dummy.c | 2245 | 14864 | /**
* Copyright (c) 2011 Jonathan Cameron
*
* 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.
*
* A reference industrial I/O driver to illustrate the functionality available.
*
* There are numerous real drivers to illustrate the finer points.
* The purpose of this driver is to provide a driver with far more comments
* and explanatory notes than any 'real' driver would have.
* Anyone starting out writing an IIO driver should first make sure they
* understand all of this driver except those bits specifically marked
* as being present to allow us to 'fake' the presence of hardware.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/events.h>
#include <linux/iio/buffer.h>
#include "iio_simple_dummy.h"
/*
* A few elements needed to fake a bus for this driver
* Note instances parameter controls how many of these
* dummy devices are registered.
*/
static unsigned instances = 1;
module_param(instances, int, 0);
/* Pointer array used to fake bus elements */
static struct iio_dev **iio_dummy_devs;
/* Fake a name for the part number, usually obtained from the id table */
static const char *iio_dummy_part_number = "iio_dummy_part_no";
/**
* struct iio_dummy_accel_calibscale - realworld to register mapping
* @val: first value in read_raw - here integer part.
* @val2: second value in read_raw etc - here micro part.
* @regval: register value - magic device specific numbers.
*/
struct iio_dummy_accel_calibscale {
int val;
int val2;
int regval; /* what would be written to hardware */
};
static const struct iio_dummy_accel_calibscale dummy_scales[] = {
{ 0, 100, 0x8 }, /* 0.000100 */
{ 0, 133, 0x7 }, /* 0.000133 */
{ 733, 13, 0x9 }, /* 733.000013 */
};
/*
* iio_dummy_channels - Description of available channels
*
* This array of structures tells the IIO core about what the device
* actually provides for a given channel.
*/
static const struct iio_chan_spec iio_dummy_channels[] = {
/* indexed ADC channel in_voltage0_raw etc */
{
.type = IIO_VOLTAGE,
/* Channel has a numeric index of 0 */
.indexed = 1,
.channel = 0,
/* What other information is available? */
.info_mask_separate =
/*
* in_voltage0_raw
* Raw (unscaled no bias removal etc) measurement
* from the device.
*/
BIT(IIO_CHAN_INFO_RAW) |
/*
* in_voltage0_offset
* Offset for userspace to apply prior to scale
* when converting to standard units (microvolts)
*/
BIT(IIO_CHAN_INFO_OFFSET) |
/*
* in_voltage0_scale
* Multipler for userspace to apply post offset
* when converting to standard units (microvolts)
*/
BIT(IIO_CHAN_INFO_SCALE),
/* The ordering of elements in the buffer via an enum */
.scan_index = voltage0,
.scan_type = { /* Description of storage in buffer */
.sign = 'u', /* unsigned */
.realbits = 13, /* 13 bits */
.storagebits = 16, /* 16 bits used for storage */
.shift = 0, /* zero shift */
},
#ifdef CONFIG_IIO_SIMPLE_DUMMY_EVENTS
/*
* simple event - triggered when value rises above
* a threshold
*/
.event_mask = IIO_EV_BIT(IIO_EV_TYPE_THRESH,
IIO_EV_DIR_RISING),
#endif /* CONFIG_IIO_SIMPLE_DUMMY_EVENTS */
},
/* Differential ADC channel in_voltage1-voltage2_raw etc*/
{
.type = IIO_VOLTAGE,
.differential = 1,
/*
* Indexing for differential channels uses channel
* for the positive part, channel2 for the negative.
*/
.indexed = 1,
.channel = 1,
.channel2 = 2,
/*
* in_voltage1-voltage2_raw
* Raw (unscaled no bias removal etc) measurement
* from the device.
*/
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
/*
* in_voltage-voltage_scale
* Shared version of scale - shared by differential
* input channels of type IIO_VOLTAGE.
*/
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),
.scan_index = diffvoltage1m2,
.scan_type = { /* Description of storage in buffer */
.sign = 's', /* signed */
.realbits = 12, /* 12 bits */
.storagebits = 16, /* 16 bits used for storage */
.shift = 0, /* zero shift */
},
},
/* Differential ADC channel in_voltage3-voltage4_raw etc*/
{
.type = IIO_VOLTAGE,
.differential = 1,
.indexed = 1,
.channel = 3,
.channel2 = 4,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),
.scan_index = diffvoltage3m4,
.scan_type = {
.sign = 's',
.realbits = 11,
.storagebits = 16,
.shift = 0,
},
},
/*
* 'modified' (i.e. axis specified) acceleration channel
* in_accel_z_raw
*/
{
.type = IIO_ACCEL,
.modified = 1,
/* Channel 2 is use for modifiers */
.channel2 = IIO_MOD_X,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
/*
* Internal bias and gain correction values. Applied
* by the hardware or driver prior to userspace
* seeing the readings. Typically part of hardware
* calibration.
*/
BIT(IIO_CHAN_INFO_CALIBSCALE) |
BIT(IIO_CHAN_INFO_CALIBBIAS),
.scan_index = accelx,
.scan_type = { /* Description of storage in buffer */
.sign = 's', /* signed */
.realbits = 16, /* 16 bits */
.storagebits = 16, /* 16 bits used for storage */
.shift = 0, /* zero shift */
},
},
/*
* Convenience macro for timestamps. 4 is the index in
* the buffer.
*/
IIO_CHAN_SOFT_TIMESTAMP(4),
/* DAC channel out_voltage0_raw */
{
.type = IIO_VOLTAGE,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
.output = 1,
.indexed = 1,
.channel = 0,
},
};
/**
* iio_dummy_read_raw() - data read function.
* @indio_dev: the struct iio_dev associated with this device instance
* @chan: the channel whose data is to be read
* @val: first element of returned value (typically INT)
* @val2: second element of returned value (typically MICRO)
* @mask: what we actually want to read as per the info_mask_*
* in iio_chan_spec.
*/
static int iio_dummy_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val,
int *val2,
long mask)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
int ret = -EINVAL;
mutex_lock(&st->lock);
switch (mask) {
case IIO_CHAN_INFO_RAW: /* magic value - channel value read */
switch (chan->type) {
case IIO_VOLTAGE:
if (chan->output) {
/* Set integer part to cached value */
*val = st->dac_val;
ret = IIO_VAL_INT;
} else if (chan->differential) {
if (chan->channel == 1)
*val = st->differential_adc_val[0];
else
*val = st->differential_adc_val[1];
ret = IIO_VAL_INT;
} else {
*val = st->single_ended_adc_val;
ret = IIO_VAL_INT;
}
break;
case IIO_ACCEL:
*val = st->accel_val;
ret = IIO_VAL_INT;
break;
default:
break;
}
break;
case IIO_CHAN_INFO_OFFSET:
/* only single ended adc -> 7 */
*val = 7;
ret = IIO_VAL_INT;
break;
case IIO_CHAN_INFO_SCALE:
switch (chan->differential) {
case 0:
/* only single ended adc -> 0.001333 */
*val = 0;
*val2 = 1333;
ret = IIO_VAL_INT_PLUS_MICRO;
break;
case 1:
/* all differential adc channels -> 0.000001344 */
*val = 0;
*val2 = 1344;
ret = IIO_VAL_INT_PLUS_NANO;
}
break;
case IIO_CHAN_INFO_CALIBBIAS:
/* only the acceleration axis - read from cache */
*val = st->accel_calibbias;
ret = IIO_VAL_INT;
break;
case IIO_CHAN_INFO_CALIBSCALE:
*val = st->accel_calibscale->val;
*val2 = st->accel_calibscale->val2;
ret = IIO_VAL_INT_PLUS_MICRO;
break;
default:
break;
}
mutex_unlock(&st->lock);
return ret;
}
/**
* iio_dummy_write_raw() - data write function.
* @indio_dev: the struct iio_dev associated with this device instance
* @chan: the channel whose data is to be written
* @val: first element of value to set (typically INT)
* @val2: second element of value to set (typically MICRO)
* @mask: what we actually want to write as per the info_mask_*
* in iio_chan_spec.
*
* Note that all raw writes are assumed IIO_VAL_INT and info mask elements
* are assumed to be IIO_INT_PLUS_MICRO unless the callback write_raw_get_fmt
* in struct iio_info is provided by the driver.
*/
static int iio_dummy_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val,
int val2,
long mask)
{
int i;
int ret = 0;
struct iio_dummy_state *st = iio_priv(indio_dev);
switch (mask) {
case IIO_CHAN_INFO_RAW:
if (chan->output == 0)
return -EINVAL;
/* Locking not required as writing single value */
mutex_lock(&st->lock);
st->dac_val = val;
mutex_unlock(&st->lock);
return 0;
case IIO_CHAN_INFO_CALIBSCALE:
mutex_lock(&st->lock);
/* Compare against table - hard matching here */
for (i = 0; i < ARRAY_SIZE(dummy_scales); i++)
if (val == dummy_scales[i].val &&
val2 == dummy_scales[i].val2)
break;
if (i == ARRAY_SIZE(dummy_scales))
ret = -EINVAL;
else
st->accel_calibscale = &dummy_scales[i];
mutex_unlock(&st->lock);
return ret;
case IIO_CHAN_INFO_CALIBBIAS:
mutex_lock(&st->lock);
st->accel_calibbias = val;
mutex_unlock(&st->lock);
return 0;
default:
return -EINVAL;
}
}
/*
* Device type specific information.
*/
static const struct iio_info iio_dummy_info = {
.driver_module = THIS_MODULE,
.read_raw = &iio_dummy_read_raw,
.write_raw = &iio_dummy_write_raw,
#ifdef CONFIG_IIO_SIMPLE_DUMMY_EVENTS
.read_event_config = &iio_simple_dummy_read_event_config,
.write_event_config = &iio_simple_dummy_write_event_config,
.read_event_value = &iio_simple_dummy_read_event_value,
.write_event_value = &iio_simple_dummy_write_event_value,
#endif /* CONFIG_IIO_SIMPLE_DUMMY_EVENTS */
};
/**
* iio_dummy_init_device() - device instance specific init
* @indio_dev: the iio device structure
*
* Most drivers have one of these to set up default values,
* reset the device to known state etc.
*/
static int iio_dummy_init_device(struct iio_dev *indio_dev)
{
struct iio_dummy_state *st = iio_priv(indio_dev);
st->dac_val = 0;
st->single_ended_adc_val = 73;
st->differential_adc_val[0] = 33;
st->differential_adc_val[1] = -34;
st->accel_val = 34;
st->accel_calibbias = -7;
st->accel_calibscale = &dummy_scales[0];
return 0;
}
/**
* iio_dummy_probe() - device instance probe
* @index: an id number for this instance.
*
* Arguments are bus type specific.
* I2C: iio_dummy_probe(struct i2c_client *client,
* const struct i2c_device_id *id)
* SPI: iio_dummy_probe(struct spi_device *spi)
*/
static int iio_dummy_probe(int index)
{
int ret;
struct iio_dev *indio_dev;
struct iio_dummy_state *st;
/*
* Allocate an IIO device.
*
* This structure contains all generic state
* information about the device instance.
* It also has a region (accessed by iio_priv()
* for chip specific state information.
*/
indio_dev = iio_device_alloc(sizeof(*st));
if (indio_dev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
st = iio_priv(indio_dev);
mutex_init(&st->lock);
iio_dummy_init_device(indio_dev);
/*
* With hardware: Set the parent device.
* indio_dev->dev.parent = &spi->dev;
* indio_dev->dev.parent = &client->dev;
*/
/*
* Make the iio_dev struct available to remove function.
* Bus equivalents
* i2c_set_clientdata(client, indio_dev);
* spi_set_drvdata(spi, indio_dev);
*/
iio_dummy_devs[index] = indio_dev;
/*
* Set the device name.
*
* This is typically a part number and obtained from the module
* id table.
* e.g. for i2c and spi:
* indio_dev->name = id->name;
* indio_dev->name = spi_get_device_id(spi)->name;
*/
indio_dev->name = iio_dummy_part_number;
/* Provide description of available channels */
indio_dev->channels = iio_dummy_channels;
indio_dev->num_channels = ARRAY_SIZE(iio_dummy_channels);
/*
* Provide device type specific interface functions and
* constant data.
*/
indio_dev->info = &iio_dummy_info;
/* Specify that device provides sysfs type interfaces */
indio_dev->modes = INDIO_DIRECT_MODE;
ret = iio_simple_dummy_events_register(indio_dev);
if (ret < 0)
goto error_free_device;
/*
* Configure buffered capture support and register the channels with the
* buffer, but avoid the output channel being registered by reducing the
* number of channels by 1.
*/
ret = iio_simple_dummy_configure_buffer(indio_dev, iio_dummy_channels, 5);
if (ret < 0)
goto error_unregister_events;
ret = iio_device_register(indio_dev);
if (ret < 0)
goto error_unconfigure_buffer;
return 0;
error_unconfigure_buffer:
iio_simple_dummy_unconfigure_buffer(indio_dev);
error_unregister_events:
iio_simple_dummy_events_unregister(indio_dev);
error_free_device:
iio_device_free(indio_dev);
error_ret:
return ret;
}
/**
* iio_dummy_remove() - device instance removal function
* @index: device index.
*
* Parameters follow those of iio_dummy_probe for buses.
*/
static int iio_dummy_remove(int index)
{
int ret;
/*
* Get a pointer to the device instance iio_dev structure
* from the bus subsystem. E.g.
* struct iio_dev *indio_dev = i2c_get_clientdata(client);
* struct iio_dev *indio_dev = spi_get_drvdata(spi);
*/
struct iio_dev *indio_dev = iio_dummy_devs[index];
/* Unregister the device */
iio_device_unregister(indio_dev);
/* Device specific code to power down etc */
/* Buffered capture related cleanup */
iio_simple_dummy_unconfigure_buffer(indio_dev);
ret = iio_simple_dummy_events_unregister(indio_dev);
if (ret)
goto error_ret;
/* Free all structures */
iio_device_free(indio_dev);
error_ret:
return ret;
}
/**
* iio_dummy_init() - device driver registration
*
* Varies depending on bus type of the device. As there is no device
* here, call probe directly. For information on device registration
* i2c:
* Documentation/i2c/writing-clients
* spi:
* Documentation/spi/spi-summary
*/
static __init int iio_dummy_init(void)
{
int i, ret;
if (instances > 10) {
instances = 1;
return -EINVAL;
}
/* Fake a bus */
iio_dummy_devs = kcalloc(instances, sizeof(*iio_dummy_devs),
GFP_KERNEL);
/* Here we have no actual device so call probe */
for (i = 0; i < instances; i++) {
ret = iio_dummy_probe(i);
if (ret < 0)
return ret;
}
return 0;
}
module_init(iio_dummy_init);
/**
* iio_dummy_exit() - device driver removal
*
* Varies depending on bus type of the device.
* As there is no device here, call remove directly.
*/
static __exit void iio_dummy_exit(void)
{
int i;
for (i = 0; i < instances; i++)
iio_dummy_remove(i);
kfree(iio_dummy_devs);
}
module_exit(iio_dummy_exit);
MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
MODULE_DESCRIPTION("IIO dummy driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
brinlyaus/sturdy-eureka | drivers/input/keyboard/jornada680_kbd.c | 2245 | 8054 | /*
* drivers/input/keyboard/jornada680_kbd.c
*
* HP Jornada 620/660/680/690 scan keyboard platform driver
* Copyright (C) 2007 Kristoffer Ericson <Kristoffer.Ericson@gmail.com>
*
* Based on hp680_keyb.c
* Copyright (C) 2006 Paul Mundt
* Copyright (C) 2005 Andriy Skulysh
* Split from drivers/input/keyboard/hp600_keyb.c
* Copyright (C) 2000 Yaegashi Takeshi (hp6xx kbd scan routine and translation table)
* Copyright (C) 2000 Niibe Yutaka (HP620 Keyb translation table)
*
* 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/input.h>
#include <linux/input-polldev.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/delay.h>
#include <asm/io.h>
#define PCCR 0xa4000104
#define PDCR 0xa4000106
#define PECR 0xa4000108
#define PFCR 0xa400010a
#define PCDR 0xa4000124
#define PDDR 0xa4000126
#define PEDR 0xa4000128
#define PFDR 0xa400012a
#define PGDR 0xa400012c
#define PHDR 0xa400012e
#define PJDR 0xa4000130
#define PKDR 0xa4000132
#define PLDR 0xa4000134
static const unsigned short jornada_scancodes[] = {
/* PTD1 */ KEY_CAPSLOCK, KEY_MACRO, KEY_LEFTCTRL, 0, KEY_ESC, KEY_KP5, 0, 0, /* 1 -> 8 */
KEY_F1, KEY_F2, KEY_F3, KEY_F8, KEY_F7, KEY_F6, KEY_F4, KEY_F5, /* 9 -> 16 */
/* PTD5 */ KEY_SLASH, KEY_APOSTROPHE, KEY_ENTER, 0, KEY_Z, 0, 0, 0, /* 17 -> 24 */
KEY_X, KEY_C, KEY_V, KEY_DOT, KEY_COMMA, KEY_M, KEY_B, KEY_N, /* 25 -> 32 */
/* PTD7 */ KEY_KP2, KEY_KP6, KEY_KP3, 0, 0, 0, 0, 0, /* 33 -> 40 */
KEY_F10, KEY_RO, KEY_F9, KEY_KP4, KEY_NUMLOCK, KEY_SCROLLLOCK, KEY_LEFTALT, KEY_HANJA, /* 41 -> 48 */
/* PTE0 */ KEY_KATAKANA, KEY_KP0, KEY_GRAVE, 0, KEY_FINANCE, 0, 0, 0, /* 49 -> 56 */
KEY_KPMINUS, KEY_HIRAGANA, KEY_SPACE, KEY_KPDOT, KEY_VOLUMEUP, 249, 0, 0, /* 57 -> 64 */
/* PTE1 */ KEY_SEMICOLON, KEY_RIGHTBRACE, KEY_BACKSLASH, 0, KEY_A, 0, 0, 0, /* 65 -> 72 */
KEY_S, KEY_D, KEY_F, KEY_L, KEY_K, KEY_J, KEY_G, KEY_H, /* 73 -> 80 */
/* PTE3 */ KEY_KP8, KEY_LEFTMETA, KEY_RIGHTSHIFT, 0, KEY_TAB, 0, 0, 0, /* 81 -> 88 */
0, KEY_LEFTSHIFT, KEY_KP7, KEY_KP9, KEY_KP1, KEY_F11, KEY_KPPLUS, KEY_KPASTERISK, /* 89 -> 96 */
/* PTE6 */ KEY_P, KEY_LEFTBRACE, KEY_BACKSPACE, 0, KEY_Q, 0, 0, 0, /* 97 -> 104 */
KEY_W, KEY_E, KEY_R, KEY_O, KEY_I, KEY_U, KEY_T, KEY_Y, /* 105 -> 112 */
/* PTE7 */ KEY_0, KEY_MINUS, KEY_EQUAL, 0, KEY_1, 0, 0, 0, /* 113 -> 120 */
KEY_2, KEY_3, KEY_4, KEY_9, KEY_8, KEY_7, KEY_5, KEY_6, /* 121 -> 128 */
/* **** */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
#define JORNADA_SCAN_SIZE 18
struct jornadakbd {
struct input_polled_dev *poll_dev;
unsigned short keymap[ARRAY_SIZE(jornada_scancodes)];
unsigned char length;
unsigned char old_scan[JORNADA_SCAN_SIZE];
unsigned char new_scan[JORNADA_SCAN_SIZE];
};
static void jornada_parse_kbd(struct jornadakbd *jornadakbd)
{
struct input_dev *input_dev = jornadakbd->poll_dev->input;
unsigned short *keymap = jornadakbd->keymap;
unsigned int sync_me = 0;
unsigned int i, j;
for (i = 0; i < JORNADA_SCAN_SIZE; i++) {
unsigned char new = jornadakbd->new_scan[i];
unsigned char old = jornadakbd->old_scan[i];
unsigned int xor = new ^ old;
if (xor == 0)
continue;
for (j = 0; j < 8; j++) {
unsigned int bit = 1 << j;
if (xor & bit) {
unsigned int scancode = (i << 3) + j;
input_event(input_dev,
EV_MSC, MSC_SCAN, scancode);
input_report_key(input_dev,
keymap[scancode],
!(new & bit));
sync_me = 1;
}
}
}
if (sync_me)
input_sync(input_dev);
}
static void jornada_scan_keyb(unsigned char *s)
{
int i;
unsigned short ec_static, dc_static; /* = UINT16_t */
unsigned char matrix_switch[] = {
0xfd, 0xff, /* PTD1 PD(1) */
0xdf, 0xff, /* PTD5 PD(5) */
0x7f, 0xff, /* PTD7 PD(7) */
0xff, 0xfe, /* PTE0 PE(0) */
0xff, 0xfd, /* PTE1 PE(1) */
0xff, 0xf7, /* PTE3 PE(3) */
0xff, 0xbf, /* PTE6 PE(6) */
0xff, 0x7f, /* PTE7 PE(7) */
}, *t = matrix_switch;
/* PD(x) :
1. 0xcc0c & (1~(1 << (2*(x)+1)))))
2. (0xf0cf & 0xfffff) */
/* PE(x) :
1. 0xcc0c & 0xffff
2. 0xf0cf & (1~(1 << (2*(x)+1))))) */
unsigned short matrix_PDE[] = {
0xcc04, 0xf0cf, /* PD(1) */
0xc40c, 0xf0cf, /* PD(5) */
0x4c0c, 0xf0cf, /* PD(7) */
0xcc0c, 0xf0cd, /* PE(0) */
0xcc0c, 0xf0c7, /* PE(1) */
0xcc0c, 0xf04f, /* PE(3) */
0xcc0c, 0xd0cf, /* PE(6) */
0xcc0c, 0x70cf, /* PE(7) */
}, *y = matrix_PDE;
/* Save these control reg bits */
dc_static = (__raw_readw(PDCR) & (~0xcc0c));
ec_static = (__raw_readw(PECR) & (~0xf0cf));
for (i = 0; i < 8; i++) {
/* disable output for all but the one we want to scan */
__raw_writew((dc_static | *y++), PDCR);
__raw_writew((ec_static | *y++), PECR);
udelay(5);
/* Get scanline row */
__raw_writeb(*t++, PDDR);
__raw_writeb(*t++, PEDR);
udelay(50);
/* Read data */
*s++ = __raw_readb(PCDR);
*s++ = __raw_readb(PFDR);
}
/* Scan no lines */
__raw_writeb(0xff, PDDR);
__raw_writeb(0xff, PEDR);
/* Enable all scanlines */
__raw_writew((dc_static | (0x5555 & 0xcc0c)),PDCR);
__raw_writew((ec_static | (0x5555 & 0xf0cf)),PECR);
/* Ignore extra keys and events */
*s++ = __raw_readb(PGDR);
*s++ = __raw_readb(PHDR);
}
static void jornadakbd680_poll(struct input_polled_dev *dev)
{
struct jornadakbd *jornadakbd = dev->private;
jornada_scan_keyb(jornadakbd->new_scan);
jornada_parse_kbd(jornadakbd);
memcpy(jornadakbd->old_scan, jornadakbd->new_scan, JORNADA_SCAN_SIZE);
}
static int jornada680kbd_probe(struct platform_device *pdev)
{
struct jornadakbd *jornadakbd;
struct input_polled_dev *poll_dev;
struct input_dev *input_dev;
int i, error;
jornadakbd = kzalloc(sizeof(struct jornadakbd), GFP_KERNEL);
if (!jornadakbd)
return -ENOMEM;
poll_dev = input_allocate_polled_device();
if (!poll_dev) {
error = -ENOMEM;
goto failed;
}
platform_set_drvdata(pdev, jornadakbd);
jornadakbd->poll_dev = poll_dev;
memcpy(jornadakbd->keymap, jornada_scancodes,
sizeof(jornadakbd->keymap));
poll_dev->private = jornadakbd;
poll_dev->poll = jornadakbd680_poll;
poll_dev->poll_interval = 50; /* msec */
input_dev = poll_dev->input;
input_dev->evbit[0] = BIT(EV_KEY) | BIT(EV_REP);
input_dev->name = "HP Jornada 680 keyboard";
input_dev->phys = "jornadakbd/input0";
input_dev->keycode = jornadakbd->keymap;
input_dev->keycodesize = sizeof(unsigned short);
input_dev->keycodemax = ARRAY_SIZE(jornada_scancodes);
input_dev->dev.parent = &pdev->dev;
input_dev->id.bustype = BUS_HOST;
for (i = 0; i < 128; i++)
if (jornadakbd->keymap[i])
__set_bit(jornadakbd->keymap[i], input_dev->keybit);
__clear_bit(KEY_RESERVED, input_dev->keybit);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
error = input_register_polled_device(jornadakbd->poll_dev);
if (error)
goto failed;
return 0;
failed:
printk(KERN_ERR "Jornadakbd: failed to register driver, error: %d\n",
error);
platform_set_drvdata(pdev, NULL);
input_free_polled_device(poll_dev);
kfree(jornadakbd);
return error;
}
static int jornada680kbd_remove(struct platform_device *pdev)
{
struct jornadakbd *jornadakbd = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
input_unregister_polled_device(jornadakbd->poll_dev);
input_free_polled_device(jornadakbd->poll_dev);
kfree(jornadakbd);
return 0;
}
static struct platform_driver jornada680kbd_driver = {
.driver = {
.name = "jornada680_kbd",
.owner = THIS_MODULE,
},
.probe = jornada680kbd_probe,
.remove = jornada680kbd_remove,
};
module_platform_driver(jornada680kbd_driver);
MODULE_AUTHOR("Kristoffer Ericson <kristoffer.ericson@gmail.com>");
MODULE_DESCRIPTION("HP Jornada 620/660/680/690 Keyboard Driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:jornada680_kbd");
| gpl-2.0 |
Dee-UK/RK3288_Lollipop_Kernel | drivers/gpu/drm/nouveau/core/subdev/instmem/base.c | 2501 | 3790 | /*
* 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 <subdev/instmem.h>
int
nouveau_instobj_create_(struct nouveau_object *parent,
struct nouveau_object *engine,
struct nouveau_oclass *oclass,
int length, void **pobject)
{
struct nouveau_instmem *imem = (void *)engine;
struct nouveau_instobj *iobj;
int ret;
ret = nouveau_object_create_(parent, engine, oclass, NV_MEMOBJ_CLASS,
length, pobject);
iobj = *pobject;
if (ret)
return ret;
mutex_lock(&imem->base.mutex);
list_add(&iobj->head, &imem->list);
mutex_unlock(&imem->base.mutex);
return 0;
}
void
nouveau_instobj_destroy(struct nouveau_instobj *iobj)
{
struct nouveau_subdev *subdev = nv_subdev(iobj->base.engine);
mutex_lock(&subdev->mutex);
list_del(&iobj->head);
mutex_unlock(&subdev->mutex);
return nouveau_object_destroy(&iobj->base);
}
void
_nouveau_instobj_dtor(struct nouveau_object *object)
{
struct nouveau_instobj *iobj = (void *)object;
return nouveau_instobj_destroy(iobj);
}
int
nouveau_instmem_create_(struct nouveau_object *parent,
struct nouveau_object *engine,
struct nouveau_oclass *oclass,
int length, void **pobject)
{
struct nouveau_instmem *imem;
int ret;
ret = nouveau_subdev_create_(parent, engine, oclass, 0,
"INSTMEM", "instmem", length, pobject);
imem = *pobject;
if (ret)
return ret;
INIT_LIST_HEAD(&imem->list);
return 0;
}
int
nouveau_instmem_init(struct nouveau_instmem *imem)
{
struct nouveau_instobj *iobj;
int ret, i;
ret = nouveau_subdev_init(&imem->base);
if (ret)
return ret;
mutex_lock(&imem->base.mutex);
list_for_each_entry(iobj, &imem->list, head) {
if (iobj->suspend) {
for (i = 0; i < iobj->size; i += 4)
nv_wo32(iobj, i, iobj->suspend[i / 4]);
vfree(iobj->suspend);
iobj->suspend = NULL;
}
}
mutex_unlock(&imem->base.mutex);
return 0;
}
int
nouveau_instmem_fini(struct nouveau_instmem *imem, bool suspend)
{
struct nouveau_instobj *iobj;
int i, ret = 0;
if (suspend) {
mutex_lock(&imem->base.mutex);
list_for_each_entry(iobj, &imem->list, head) {
iobj->suspend = vmalloc(iobj->size);
if (!iobj->suspend) {
ret = -ENOMEM;
break;
}
for (i = 0; i < iobj->size; i += 4)
iobj->suspend[i / 4] = nv_ro32(iobj, i);
}
mutex_unlock(&imem->base.mutex);
if (ret)
return ret;
}
return nouveau_subdev_fini(&imem->base, suspend);
}
int
_nouveau_instmem_init(struct nouveau_object *object)
{
struct nouveau_instmem *imem = (void *)object;
return nouveau_instmem_init(imem);
}
int
_nouveau_instmem_fini(struct nouveau_object *object, bool suspend)
{
struct nouveau_instmem *imem = (void *)object;
return nouveau_instmem_fini(imem, suspend);
}
| gpl-2.0 |
TamCore/android_kernel_htc_msm8660 | drivers/net/wireless/libertas_tf/cmd.c | 3525 | 20545 | /*
* Copyright (C) 2008, cozybit Inc.
* Copyright (C) 2003-2006, Marvell International Ltd.
*
* 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/slab.h>
#include "libertas_tf.h"
static const struct channel_range channel_ranges[] = {
{ LBTF_REGDOMAIN_US, 1, 12 },
{ LBTF_REGDOMAIN_CA, 1, 12 },
{ LBTF_REGDOMAIN_EU, 1, 14 },
{ LBTF_REGDOMAIN_JP, 1, 14 },
{ LBTF_REGDOMAIN_SP, 1, 14 },
{ LBTF_REGDOMAIN_FR, 1, 14 },
};
static u16 lbtf_region_code_to_index[MRVDRV_MAX_REGION_CODE] =
{
LBTF_REGDOMAIN_US, LBTF_REGDOMAIN_CA, LBTF_REGDOMAIN_EU,
LBTF_REGDOMAIN_SP, LBTF_REGDOMAIN_FR, LBTF_REGDOMAIN_JP,
};
static struct cmd_ctrl_node *lbtf_get_cmd_ctrl_node(struct lbtf_private *priv);
/**
* lbtf_cmd_copyback - Simple callback that copies response back into command
*
* @priv A pointer to struct lbtf_private structure
* @extra A pointer to the original command structure for which
* 'resp' is a response
* @resp A pointer to the command response
*
* Returns: 0 on success, error on failure
*/
int lbtf_cmd_copyback(struct lbtf_private *priv, unsigned long extra,
struct cmd_header *resp)
{
struct cmd_header *buf = (void *)extra;
uint16_t copy_len;
copy_len = min(le16_to_cpu(buf->size), le16_to_cpu(resp->size));
memcpy(buf, resp, copy_len);
return 0;
}
EXPORT_SYMBOL_GPL(lbtf_cmd_copyback);
#define CHAN_TO_IDX(chan) ((chan) - 1)
static void lbtf_geo_init(struct lbtf_private *priv)
{
const struct channel_range *range = channel_ranges;
u8 ch;
int i;
for (i = 0; i < ARRAY_SIZE(channel_ranges); i++)
if (channel_ranges[i].regdomain == priv->regioncode) {
range = &channel_ranges[i];
break;
}
for (ch = priv->range.start; ch < priv->range.end; ch++)
priv->channels[CHAN_TO_IDX(ch)].flags = 0;
}
/**
* lbtf_update_hw_spec: Updates the hardware details.
*
* @priv A pointer to struct lbtf_private structure
*
* Returns: 0 on success, error on failure
*/
int lbtf_update_hw_spec(struct lbtf_private *priv)
{
struct cmd_ds_get_hw_spec cmd;
int ret = -1;
u32 i;
lbtf_deb_enter(LBTF_DEB_CMD);
memset(&cmd, 0, sizeof(cmd));
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
memcpy(cmd.permanentaddr, priv->current_addr, ETH_ALEN);
ret = lbtf_cmd_with_response(priv, CMD_GET_HW_SPEC, &cmd);
if (ret)
goto out;
priv->fwcapinfo = le32_to_cpu(cmd.fwcapinfo);
/* The firmware release is in an interesting format: the patch
* level is in the most significant nibble ... so fix that: */
priv->fwrelease = le32_to_cpu(cmd.fwrelease);
priv->fwrelease = (priv->fwrelease << 8) |
(priv->fwrelease >> 24 & 0xff);
printk(KERN_INFO "libertastf: %pM, fw %u.%u.%up%u, cap 0x%08x\n",
cmd.permanentaddr,
priv->fwrelease >> 24 & 0xff,
priv->fwrelease >> 16 & 0xff,
priv->fwrelease >> 8 & 0xff,
priv->fwrelease & 0xff,
priv->fwcapinfo);
lbtf_deb_cmd("GET_HW_SPEC: hardware interface 0x%x, hardware spec 0x%04x\n",
cmd.hwifversion, cmd.version);
/* Clamp region code to 8-bit since FW spec indicates that it should
* only ever be 8-bit, even though the field size is 16-bit. Some
* firmware returns non-zero high 8 bits here.
*/
priv->regioncode = le16_to_cpu(cmd.regioncode) & 0xFF;
for (i = 0; i < MRVDRV_MAX_REGION_CODE; i++) {
/* use the region code to search for the index */
if (priv->regioncode == lbtf_region_code_to_index[i])
break;
}
/* if it's unidentified region code, use the default (USA) */
if (i >= MRVDRV_MAX_REGION_CODE) {
priv->regioncode = 0x10;
pr_info("unidentified region code; using the default (USA)\n");
}
if (priv->current_addr[0] == 0xff)
memmove(priv->current_addr, cmd.permanentaddr, ETH_ALEN);
SET_IEEE80211_PERM_ADDR(priv->hw, priv->current_addr);
lbtf_geo_init(priv);
out:
lbtf_deb_leave(LBTF_DEB_CMD);
return ret;
}
/**
* lbtf_set_channel: Set the radio channel
*
* @priv A pointer to struct lbtf_private structure
* @channel The desired channel, or 0 to clear a locked channel
*
* Returns: 0 on success, error on failure
*/
int lbtf_set_channel(struct lbtf_private *priv, u8 channel)
{
int ret = 0;
struct cmd_ds_802_11_rf_channel cmd;
lbtf_deb_enter(LBTF_DEB_CMD);
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.action = cpu_to_le16(CMD_OPT_802_11_RF_CHANNEL_SET);
cmd.channel = cpu_to_le16(channel);
ret = lbtf_cmd_with_response(priv, CMD_802_11_RF_CHANNEL, &cmd);
lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", ret);
return ret;
}
int lbtf_beacon_set(struct lbtf_private *priv, struct sk_buff *beacon)
{
struct cmd_ds_802_11_beacon_set cmd;
int size;
lbtf_deb_enter(LBTF_DEB_CMD);
if (beacon->len > MRVL_MAX_BCN_SIZE) {
lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", -1);
return -1;
}
size = sizeof(cmd) - sizeof(cmd.beacon) + beacon->len;
cmd.hdr.size = cpu_to_le16(size);
cmd.len = cpu_to_le16(beacon->len);
memcpy(cmd.beacon, (u8 *) beacon->data, beacon->len);
lbtf_cmd_async(priv, CMD_802_11_BEACON_SET, &cmd.hdr, size);
lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", 0);
return 0;
}
int lbtf_beacon_ctrl(struct lbtf_private *priv, bool beacon_enable,
int beacon_int)
{
struct cmd_ds_802_11_beacon_control cmd;
lbtf_deb_enter(LBTF_DEB_CMD);
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.action = cpu_to_le16(CMD_ACT_SET);
cmd.beacon_enable = cpu_to_le16(beacon_enable);
cmd.beacon_period = cpu_to_le16(beacon_int);
lbtf_cmd_async(priv, CMD_802_11_BEACON_CTRL, &cmd.hdr, sizeof(cmd));
lbtf_deb_leave(LBTF_DEB_CMD);
return 0;
}
static void lbtf_queue_cmd(struct lbtf_private *priv,
struct cmd_ctrl_node *cmdnode)
{
unsigned long flags;
lbtf_deb_enter(LBTF_DEB_HOST);
if (!cmdnode) {
lbtf_deb_host("QUEUE_CMD: cmdnode is NULL\n");
goto qcmd_done;
}
if (!cmdnode->cmdbuf->size) {
lbtf_deb_host("DNLD_CMD: cmd size is zero\n");
goto qcmd_done;
}
cmdnode->result = 0;
spin_lock_irqsave(&priv->driver_lock, flags);
list_add_tail(&cmdnode->list, &priv->cmdpendingq);
spin_unlock_irqrestore(&priv->driver_lock, flags);
lbtf_deb_host("QUEUE_CMD: inserted command 0x%04x into cmdpendingq\n",
le16_to_cpu(cmdnode->cmdbuf->command));
qcmd_done:
lbtf_deb_leave(LBTF_DEB_HOST);
}
static void lbtf_submit_command(struct lbtf_private *priv,
struct cmd_ctrl_node *cmdnode)
{
unsigned long flags;
struct cmd_header *cmd;
uint16_t cmdsize;
uint16_t command;
int timeo = 5 * HZ;
int ret;
lbtf_deb_enter(LBTF_DEB_HOST);
cmd = cmdnode->cmdbuf;
spin_lock_irqsave(&priv->driver_lock, flags);
priv->cur_cmd = cmdnode;
cmdsize = le16_to_cpu(cmd->size);
command = le16_to_cpu(cmd->command);
lbtf_deb_cmd("DNLD_CMD: command 0x%04x, seq %d, size %d\n",
command, le16_to_cpu(cmd->seqnum), cmdsize);
lbtf_deb_hex(LBTF_DEB_CMD, "DNLD_CMD", (void *) cmdnode->cmdbuf, cmdsize);
ret = priv->hw_host_to_card(priv, MVMS_CMD, (u8 *) cmd, cmdsize);
spin_unlock_irqrestore(&priv->driver_lock, flags);
if (ret) {
pr_info("DNLD_CMD: hw_host_to_card failed: %d\n", ret);
/* Let the timer kick in and retry, and potentially reset
the whole thing if the condition persists */
timeo = HZ;
}
/* Setup the timer after transmit command */
mod_timer(&priv->command_timer, jiffies + timeo);
lbtf_deb_leave(LBTF_DEB_HOST);
}
/**
* This function inserts command node to cmdfreeq
* after cleans it. Requires priv->driver_lock held.
*/
static void __lbtf_cleanup_and_insert_cmd(struct lbtf_private *priv,
struct cmd_ctrl_node *cmdnode)
{
lbtf_deb_enter(LBTF_DEB_HOST);
if (!cmdnode)
goto cl_ins_out;
cmdnode->callback = NULL;
cmdnode->callback_arg = 0;
memset(cmdnode->cmdbuf, 0, LBS_CMD_BUFFER_SIZE);
list_add_tail(&cmdnode->list, &priv->cmdfreeq);
cl_ins_out:
lbtf_deb_leave(LBTF_DEB_HOST);
}
static void lbtf_cleanup_and_insert_cmd(struct lbtf_private *priv,
struct cmd_ctrl_node *ptempcmd)
{
unsigned long flags;
spin_lock_irqsave(&priv->driver_lock, flags);
__lbtf_cleanup_and_insert_cmd(priv, ptempcmd);
spin_unlock_irqrestore(&priv->driver_lock, flags);
}
void lbtf_complete_command(struct lbtf_private *priv, struct cmd_ctrl_node *cmd,
int result)
{
cmd->result = result;
cmd->cmdwaitqwoken = 1;
wake_up_interruptible(&cmd->cmdwait_q);
if (!cmd->callback)
__lbtf_cleanup_and_insert_cmd(priv, cmd);
priv->cur_cmd = NULL;
}
int lbtf_cmd_set_mac_multicast_addr(struct lbtf_private *priv)
{
struct cmd_ds_mac_multicast_addr cmd;
lbtf_deb_enter(LBTF_DEB_CMD);
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.action = cpu_to_le16(CMD_ACT_SET);
cmd.nr_of_adrs = cpu_to_le16((u16) priv->nr_of_multicastmacaddr);
lbtf_deb_cmd("MULTICAST_ADR: setting %d addresses\n", cmd.nr_of_adrs);
memcpy(cmd.maclist, priv->multicastlist,
priv->nr_of_multicastmacaddr * ETH_ALEN);
lbtf_cmd_async(priv, CMD_MAC_MULTICAST_ADR, &cmd.hdr, sizeof(cmd));
lbtf_deb_leave(LBTF_DEB_CMD);
return 0;
}
void lbtf_set_mode(struct lbtf_private *priv, enum lbtf_mode mode)
{
struct cmd_ds_set_mode cmd;
lbtf_deb_enter(LBTF_DEB_WEXT);
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.mode = cpu_to_le16(mode);
lbtf_deb_wext("Switching to mode: 0x%x\n", mode);
lbtf_cmd_async(priv, CMD_802_11_SET_MODE, &cmd.hdr, sizeof(cmd));
lbtf_deb_leave(LBTF_DEB_WEXT);
}
void lbtf_set_bssid(struct lbtf_private *priv, bool activate, const u8 *bssid)
{
struct cmd_ds_set_bssid cmd;
lbtf_deb_enter(LBTF_DEB_CMD);
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.activate = activate ? 1 : 0;
if (activate)
memcpy(cmd.bssid, bssid, ETH_ALEN);
lbtf_cmd_async(priv, CMD_802_11_SET_BSSID, &cmd.hdr, sizeof(cmd));
lbtf_deb_leave(LBTF_DEB_CMD);
}
int lbtf_set_mac_address(struct lbtf_private *priv, uint8_t *mac_addr)
{
struct cmd_ds_802_11_mac_address cmd;
lbtf_deb_enter(LBTF_DEB_CMD);
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.action = cpu_to_le16(CMD_ACT_SET);
memcpy(cmd.macadd, mac_addr, ETH_ALEN);
lbtf_cmd_async(priv, CMD_802_11_MAC_ADDRESS, &cmd.hdr, sizeof(cmd));
lbtf_deb_leave(LBTF_DEB_CMD);
return 0;
}
int lbtf_set_radio_control(struct lbtf_private *priv)
{
int ret = 0;
struct cmd_ds_802_11_radio_control cmd;
lbtf_deb_enter(LBTF_DEB_CMD);
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.action = cpu_to_le16(CMD_ACT_SET);
switch (priv->preamble) {
case CMD_TYPE_SHORT_PREAMBLE:
cmd.control = cpu_to_le16(SET_SHORT_PREAMBLE);
break;
case CMD_TYPE_LONG_PREAMBLE:
cmd.control = cpu_to_le16(SET_LONG_PREAMBLE);
break;
case CMD_TYPE_AUTO_PREAMBLE:
default:
cmd.control = cpu_to_le16(SET_AUTO_PREAMBLE);
break;
}
if (priv->radioon)
cmd.control |= cpu_to_le16(TURN_ON_RF);
else
cmd.control &= cpu_to_le16(~TURN_ON_RF);
lbtf_deb_cmd("RADIO_SET: radio %d, preamble %d\n", priv->radioon,
priv->preamble);
ret = lbtf_cmd_with_response(priv, CMD_802_11_RADIO_CONTROL, &cmd);
lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", ret);
return ret;
}
void lbtf_set_mac_control(struct lbtf_private *priv)
{
struct cmd_ds_mac_control cmd;
lbtf_deb_enter(LBTF_DEB_CMD);
cmd.hdr.size = cpu_to_le16(sizeof(cmd));
cmd.action = cpu_to_le16(priv->mac_control);
cmd.reserved = 0;
lbtf_cmd_async(priv, CMD_MAC_CONTROL,
&cmd.hdr, sizeof(cmd));
lbtf_deb_leave(LBTF_DEB_CMD);
}
/**
* lbtf_allocate_cmd_buffer - Allocates cmd buffer, links it to free cmd queue
*
* @priv A pointer to struct lbtf_private structure
*
* Returns: 0 on success.
*/
int lbtf_allocate_cmd_buffer(struct lbtf_private *priv)
{
int ret = 0;
u32 bufsize;
u32 i;
struct cmd_ctrl_node *cmdarray;
lbtf_deb_enter(LBTF_DEB_HOST);
/* Allocate and initialize the command array */
bufsize = sizeof(struct cmd_ctrl_node) * LBS_NUM_CMD_BUFFERS;
cmdarray = kzalloc(bufsize, GFP_KERNEL);
if (!cmdarray) {
lbtf_deb_host("ALLOC_CMD_BUF: tempcmd_array is NULL\n");
ret = -1;
goto done;
}
priv->cmd_array = cmdarray;
/* Allocate and initialize each command buffer in the command array */
for (i = 0; i < LBS_NUM_CMD_BUFFERS; i++) {
cmdarray[i].cmdbuf = kzalloc(LBS_CMD_BUFFER_SIZE, GFP_KERNEL);
if (!cmdarray[i].cmdbuf) {
lbtf_deb_host("ALLOC_CMD_BUF: ptempvirtualaddr is NULL\n");
ret = -1;
goto done;
}
}
for (i = 0; i < LBS_NUM_CMD_BUFFERS; i++) {
init_waitqueue_head(&cmdarray[i].cmdwait_q);
lbtf_cleanup_and_insert_cmd(priv, &cmdarray[i]);
}
ret = 0;
done:
lbtf_deb_leave_args(LBTF_DEB_HOST, "ret %d", ret);
return ret;
}
/**
* lbtf_free_cmd_buffer - Frees the cmd buffer.
*
* @priv A pointer to struct lbtf_private structure
*
* Returns: 0
*/
int lbtf_free_cmd_buffer(struct lbtf_private *priv)
{
struct cmd_ctrl_node *cmdarray;
unsigned int i;
lbtf_deb_enter(LBTF_DEB_HOST);
/* need to check if cmd array is allocated or not */
if (priv->cmd_array == NULL) {
lbtf_deb_host("FREE_CMD_BUF: cmd_array is NULL\n");
goto done;
}
cmdarray = priv->cmd_array;
/* Release shared memory buffers */
for (i = 0; i < LBS_NUM_CMD_BUFFERS; i++) {
kfree(cmdarray[i].cmdbuf);
cmdarray[i].cmdbuf = NULL;
}
/* Release cmd_ctrl_node */
kfree(priv->cmd_array);
priv->cmd_array = NULL;
done:
lbtf_deb_leave(LBTF_DEB_HOST);
return 0;
}
/**
* lbtf_get_cmd_ctrl_node - Gets free cmd node from free cmd queue.
*
* @priv A pointer to struct lbtf_private structure
*
* Returns: pointer to a struct cmd_ctrl_node or NULL if none available.
*/
static struct cmd_ctrl_node *lbtf_get_cmd_ctrl_node(struct lbtf_private *priv)
{
struct cmd_ctrl_node *tempnode;
unsigned long flags;
lbtf_deb_enter(LBTF_DEB_HOST);
if (!priv)
return NULL;
spin_lock_irqsave(&priv->driver_lock, flags);
if (!list_empty(&priv->cmdfreeq)) {
tempnode = list_first_entry(&priv->cmdfreeq,
struct cmd_ctrl_node, list);
list_del(&tempnode->list);
} else {
lbtf_deb_host("GET_CMD_NODE: cmd_ctrl_node is not available\n");
tempnode = NULL;
}
spin_unlock_irqrestore(&priv->driver_lock, flags);
lbtf_deb_leave(LBTF_DEB_HOST);
return tempnode;
}
/**
* lbtf_execute_next_command: execute next command in cmd pending queue.
*
* @priv A pointer to struct lbtf_private structure
*
* Returns: 0 on success.
*/
int lbtf_execute_next_command(struct lbtf_private *priv)
{
struct cmd_ctrl_node *cmdnode = NULL;
struct cmd_header *cmd;
unsigned long flags;
int ret = 0;
/* Debug group is lbtf_deb_THREAD and not lbtf_deb_HOST, because the
* only caller to us is lbtf_thread() and we get even when a
* data packet is received */
lbtf_deb_enter(LBTF_DEB_THREAD);
spin_lock_irqsave(&priv->driver_lock, flags);
if (priv->cur_cmd) {
pr_alert("EXEC_NEXT_CMD: already processing command!\n");
spin_unlock_irqrestore(&priv->driver_lock, flags);
ret = -1;
goto done;
}
if (!list_empty(&priv->cmdpendingq)) {
cmdnode = list_first_entry(&priv->cmdpendingq,
struct cmd_ctrl_node, list);
}
if (cmdnode) {
cmd = cmdnode->cmdbuf;
list_del(&cmdnode->list);
lbtf_deb_host("EXEC_NEXT_CMD: sending command 0x%04x\n",
le16_to_cpu(cmd->command));
spin_unlock_irqrestore(&priv->driver_lock, flags);
lbtf_submit_command(priv, cmdnode);
} else
spin_unlock_irqrestore(&priv->driver_lock, flags);
ret = 0;
done:
lbtf_deb_leave(LBTF_DEB_THREAD);
return ret;
}
static struct cmd_ctrl_node *__lbtf_cmd_async(struct lbtf_private *priv,
uint16_t command, struct cmd_header *in_cmd, int in_cmd_size,
int (*callback)(struct lbtf_private *, unsigned long,
struct cmd_header *),
unsigned long callback_arg)
{
struct cmd_ctrl_node *cmdnode;
lbtf_deb_enter(LBTF_DEB_HOST);
if (priv->surpriseremoved) {
lbtf_deb_host("PREP_CMD: card removed\n");
cmdnode = ERR_PTR(-ENOENT);
goto done;
}
cmdnode = lbtf_get_cmd_ctrl_node(priv);
if (cmdnode == NULL) {
lbtf_deb_host("PREP_CMD: cmdnode is NULL\n");
/* Wake up main thread to execute next command */
queue_work(lbtf_wq, &priv->cmd_work);
cmdnode = ERR_PTR(-ENOBUFS);
goto done;
}
cmdnode->callback = callback;
cmdnode->callback_arg = callback_arg;
/* Copy the incoming command to the buffer */
memcpy(cmdnode->cmdbuf, in_cmd, in_cmd_size);
/* Set sequence number, clean result, move to buffer */
priv->seqnum++;
cmdnode->cmdbuf->command = cpu_to_le16(command);
cmdnode->cmdbuf->size = cpu_to_le16(in_cmd_size);
cmdnode->cmdbuf->seqnum = cpu_to_le16(priv->seqnum);
cmdnode->cmdbuf->result = 0;
lbtf_deb_host("PREP_CMD: command 0x%04x\n", command);
cmdnode->cmdwaitqwoken = 0;
lbtf_queue_cmd(priv, cmdnode);
queue_work(lbtf_wq, &priv->cmd_work);
done:
lbtf_deb_leave_args(LBTF_DEB_HOST, "ret %p", cmdnode);
return cmdnode;
}
void lbtf_cmd_async(struct lbtf_private *priv, uint16_t command,
struct cmd_header *in_cmd, int in_cmd_size)
{
lbtf_deb_enter(LBTF_DEB_CMD);
__lbtf_cmd_async(priv, command, in_cmd, in_cmd_size, NULL, 0);
lbtf_deb_leave(LBTF_DEB_CMD);
}
int __lbtf_cmd(struct lbtf_private *priv, uint16_t command,
struct cmd_header *in_cmd, int in_cmd_size,
int (*callback)(struct lbtf_private *,
unsigned long, struct cmd_header *),
unsigned long callback_arg)
{
struct cmd_ctrl_node *cmdnode;
unsigned long flags;
int ret = 0;
lbtf_deb_enter(LBTF_DEB_HOST);
cmdnode = __lbtf_cmd_async(priv, command, in_cmd, in_cmd_size,
callback, callback_arg);
if (IS_ERR(cmdnode)) {
ret = PTR_ERR(cmdnode);
goto done;
}
might_sleep();
ret = wait_event_interruptible(cmdnode->cmdwait_q,
cmdnode->cmdwaitqwoken);
if (ret) {
pr_info("PREP_CMD: command 0x%04x interrupted by signal: %d\n",
command, ret);
goto done;
}
spin_lock_irqsave(&priv->driver_lock, flags);
ret = cmdnode->result;
if (ret)
pr_info("PREP_CMD: command 0x%04x failed: %d\n",
command, ret);
__lbtf_cleanup_and_insert_cmd(priv, cmdnode);
spin_unlock_irqrestore(&priv->driver_lock, flags);
done:
lbtf_deb_leave_args(LBTF_DEB_HOST, "ret %d", ret);
return ret;
}
EXPORT_SYMBOL_GPL(__lbtf_cmd);
/* Call holding driver_lock */
void lbtf_cmd_response_rx(struct lbtf_private *priv)
{
priv->cmd_response_rxed = 1;
queue_work(lbtf_wq, &priv->cmd_work);
}
EXPORT_SYMBOL_GPL(lbtf_cmd_response_rx);
int lbtf_process_rx_command(struct lbtf_private *priv)
{
uint16_t respcmd, curcmd;
struct cmd_header *resp;
int ret = 0;
unsigned long flags;
uint16_t result;
lbtf_deb_enter(LBTF_DEB_CMD);
mutex_lock(&priv->lock);
spin_lock_irqsave(&priv->driver_lock, flags);
if (!priv->cur_cmd) {
ret = -1;
spin_unlock_irqrestore(&priv->driver_lock, flags);
goto done;
}
resp = (void *)priv->cmd_resp_buff;
curcmd = le16_to_cpu(priv->cur_cmd->cmdbuf->command);
respcmd = le16_to_cpu(resp->command);
result = le16_to_cpu(resp->result);
if (net_ratelimit())
pr_info("libertastf: cmd response 0x%04x, seq %d, size %d\n",
respcmd, le16_to_cpu(resp->seqnum),
le16_to_cpu(resp->size));
if (resp->seqnum != priv->cur_cmd->cmdbuf->seqnum) {
spin_unlock_irqrestore(&priv->driver_lock, flags);
ret = -1;
goto done;
}
if (respcmd != CMD_RET(curcmd)) {
spin_unlock_irqrestore(&priv->driver_lock, flags);
ret = -1;
goto done;
}
if (resp->result == cpu_to_le16(0x0004)) {
/* 0x0004 means -EAGAIN. Drop the response, let it time out
and be resubmitted */
spin_unlock_irqrestore(&priv->driver_lock, flags);
ret = -1;
goto done;
}
/* Now we got response from FW, cancel the command timer */
del_timer(&priv->command_timer);
priv->cmd_timed_out = 0;
if (priv->nr_retries)
priv->nr_retries = 0;
/* If the command is not successful, cleanup and return failure */
if ((result != 0 || !(respcmd & 0x8000))) {
/*
* Handling errors here
*/
switch (respcmd) {
case CMD_RET(CMD_GET_HW_SPEC):
case CMD_RET(CMD_802_11_RESET):
pr_info("libertastf: reset failed\n");
break;
}
lbtf_complete_command(priv, priv->cur_cmd, result);
spin_unlock_irqrestore(&priv->driver_lock, flags);
ret = -1;
goto done;
}
spin_unlock_irqrestore(&priv->driver_lock, flags);
if (priv->cur_cmd && priv->cur_cmd->callback) {
ret = priv->cur_cmd->callback(priv, priv->cur_cmd->callback_arg,
resp);
}
spin_lock_irqsave(&priv->driver_lock, flags);
if (priv->cur_cmd) {
/* Clean up and Put current command back to cmdfreeq */
lbtf_complete_command(priv, priv->cur_cmd, result);
}
spin_unlock_irqrestore(&priv->driver_lock, flags);
done:
mutex_unlock(&priv->lock);
lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", ret);
return ret;
}
| gpl-2.0 |
DutchDanny/Holiday-ICE | arch/powerpc/platforms/86xx/gef_sbc610.c | 4037 | 5313 | /*
* GE SBC610 board support
*
* Author: Martyn Welch <martyn.welch@ge.com>
*
* Copyright 2008 GE Intelligent Platforms Embedded Systems, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Based on: mpc86xx_hpcn.c (MPC86xx HPCN board specific routines)
* Copyright 2006 Freescale Semiconductor Inc.
*
* NEC fixup adapted from arch/mips/pci/fixup-lm2e.c
*/
#include <linux/stddef.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/kdev_t.h>
#include <linux/delay.h>
#include <linux/seq_file.h>
#include <linux/of_platform.h>
#include <asm/system.h>
#include <asm/time.h>
#include <asm/machdep.h>
#include <asm/pci-bridge.h>
#include <asm/prom.h>
#include <mm/mmu_decl.h>
#include <asm/udbg.h>
#include <asm/mpic.h>
#include <asm/nvram.h>
#include <sysdev/fsl_pci.h>
#include <sysdev/fsl_soc.h>
#include "mpc86xx.h"
#include "gef_pic.h"
#undef DEBUG
#ifdef DEBUG
#define DBG (fmt...) do { printk(KERN_ERR "SBC610: " fmt); } while (0)
#else
#define DBG (fmt...) do { } while (0)
#endif
void __iomem *sbc610_regs;
static void __init gef_sbc610_init_irq(void)
{
struct device_node *cascade_node = NULL;
mpc86xx_init_irq();
/*
* There is a simple interrupt handler in the main FPGA, this needs
* to be cascaded into the MPIC
*/
cascade_node = of_find_compatible_node(NULL, NULL, "gef,fpga-pic");
if (!cascade_node) {
printk(KERN_WARNING "SBC610: No FPGA PIC\n");
return;
}
gef_pic_init(cascade_node);
of_node_put(cascade_node);
}
static void __init gef_sbc610_setup_arch(void)
{
struct device_node *regs;
#ifdef CONFIG_PCI
struct device_node *np;
for_each_compatible_node(np, "pci", "fsl,mpc8641-pcie") {
fsl_add_bridge(np, 1);
}
#endif
printk(KERN_INFO "GE Intelligent Platforms SBC610 6U VPX SBC\n");
#ifdef CONFIG_SMP
mpc86xx_smp_init();
#endif
/* Remap basic board registers */
regs = of_find_compatible_node(NULL, NULL, "gef,fpga-regs");
if (regs) {
sbc610_regs = of_iomap(regs, 0);
if (sbc610_regs == NULL)
printk(KERN_WARNING "Unable to map board registers\n");
of_node_put(regs);
}
#if defined(CONFIG_MMIO_NVRAM)
mmio_nvram_init();
#endif
}
/* Return the PCB revision */
static unsigned int gef_sbc610_get_pcb_rev(void)
{
unsigned int reg;
reg = ioread32(sbc610_regs);
return (reg >> 8) & 0xff;
}
/* Return the board (software) revision */
static unsigned int gef_sbc610_get_board_rev(void)
{
unsigned int reg;
reg = ioread32(sbc610_regs);
return (reg >> 16) & 0xff;
}
/* Return the FPGA revision */
static unsigned int gef_sbc610_get_fpga_rev(void)
{
unsigned int reg;
reg = ioread32(sbc610_regs);
return (reg >> 24) & 0xf;
}
static void gef_sbc610_show_cpuinfo(struct seq_file *m)
{
uint svid = mfspr(SPRN_SVR);
seq_printf(m, "Vendor\t\t: GE Intelligent Platforms\n");
seq_printf(m, "Revision\t: %u%c\n", gef_sbc610_get_pcb_rev(),
('A' + gef_sbc610_get_board_rev() - 1));
seq_printf(m, "FPGA Revision\t: %u\n", gef_sbc610_get_fpga_rev());
seq_printf(m, "SVR\t\t: 0x%x\n", svid);
}
static void __init gef_sbc610_nec_fixup(struct pci_dev *pdev)
{
unsigned int val;
/* Do not do the fixup on other platforms! */
if (!machine_is(gef_sbc610))
return;
printk(KERN_INFO "Running NEC uPD720101 Fixup\n");
/* Ensure ports 1, 2, 3, 4 & 5 are enabled */
pci_read_config_dword(pdev, 0xe0, &val);
pci_write_config_dword(pdev, 0xe0, (val & ~7) | 0x5);
/* System clock is 48-MHz Oscillator and EHCI Enabled. */
pci_write_config_dword(pdev, 0xe4, 1 << 5);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_USB,
gef_sbc610_nec_fixup);
/*
* Called very early, device-tree isn't unflattened
*
* This function is called to determine whether the BSP is compatible with the
* supplied device-tree, which is assumed to be the correct one for the actual
* board. It is expected thati, in the future, a kernel may support multiple
* boards.
*/
static int __init gef_sbc610_probe(void)
{
unsigned long root = of_get_flat_dt_root();
if (of_flat_dt_is_compatible(root, "gef,sbc610"))
return 1;
return 0;
}
static long __init mpc86xx_time_init(void)
{
unsigned int temp;
/* Set the time base to zero */
mtspr(SPRN_TBWL, 0);
mtspr(SPRN_TBWU, 0);
temp = mfspr(SPRN_HID0);
temp |= HID0_TBEN;
mtspr(SPRN_HID0, temp);
asm volatile("isync");
return 0;
}
static __initdata struct of_device_id of_bus_ids[] = {
{ .compatible = "simple-bus", },
{ .compatible = "gianfar", },
{},
};
static int __init declare_of_platform_devices(void)
{
printk(KERN_DEBUG "Probe platform devices\n");
of_platform_bus_probe(NULL, of_bus_ids, NULL);
return 0;
}
machine_device_initcall(gef_sbc610, declare_of_platform_devices);
define_machine(gef_sbc610) {
.name = "GE SBC610",
.probe = gef_sbc610_probe,
.setup_arch = gef_sbc610_setup_arch,
.init_IRQ = gef_sbc610_init_irq,
.show_cpuinfo = gef_sbc610_show_cpuinfo,
.get_irq = mpic_get_irq,
.restart = fsl_rstcr_restart,
.time_init = mpc86xx_time_init,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
#ifdef CONFIG_PCI
.pcibios_fixup_bus = fsl_pcibios_fixup_bus,
#endif
};
| gpl-2.0 |
championswimmer/android_kernel_sony_msm8260 | drivers/media/rc/ir-sanyo-decoder.c | 4549 | 5392 | /* ir-sanyo-decoder.c - handle SANYO IR Pulse/Space protocol
*
* Copyright (C) 2011 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This protocol uses the NEC protocol timings. However, data is formatted as:
* 13 bits Custom Code
* 13 bits NOT(Custom Code)
* 8 bits Key data
* 8 bits NOT(Key data)
*
* According with LIRC, this protocol is used on Sanyo, Aiwa and Chinon
* Information for this protocol is available at the Sanyo LC7461 datasheet.
*/
#include <linux/module.h>
#include <linux/bitrev.h>
#include "rc-core-priv.h"
#define SANYO_NBITS (13+13+8+8)
#define SANYO_UNIT 562500 /* ns */
#define SANYO_HEADER_PULSE (16 * SANYO_UNIT)
#define SANYO_HEADER_SPACE (8 * SANYO_UNIT)
#define SANYO_BIT_PULSE (1 * SANYO_UNIT)
#define SANYO_BIT_0_SPACE (1 * SANYO_UNIT)
#define SANYO_BIT_1_SPACE (3 * SANYO_UNIT)
#define SANYO_REPEAT_SPACE (150 * SANYO_UNIT)
#define SANYO_TRAILER_PULSE (1 * SANYO_UNIT)
#define SANYO_TRAILER_SPACE (10 * SANYO_UNIT) /* in fact, 42 */
enum sanyo_state {
STATE_INACTIVE,
STATE_HEADER_SPACE,
STATE_BIT_PULSE,
STATE_BIT_SPACE,
STATE_TRAILER_PULSE,
STATE_TRAILER_SPACE,
};
/**
* ir_sanyo_decode() - Decode one SANYO pulse or space
* @dev: the struct rc_dev descriptor of the device
* @duration: the struct ir_raw_event descriptor of the pulse/space
*
* This function returns -EINVAL if the pulse violates the state machine
*/
static int ir_sanyo_decode(struct rc_dev *dev, struct ir_raw_event ev)
{
struct sanyo_dec *data = &dev->raw->sanyo;
u32 scancode;
u8 address, not_address, command, not_command;
if (!(dev->raw->enabled_protocols & RC_TYPE_SANYO))
return 0;
if (!is_timing_event(ev)) {
if (ev.reset) {
IR_dprintk(1, "SANYO event reset received. reset to state 0\n");
data->state = STATE_INACTIVE;
}
return 0;
}
IR_dprintk(2, "SANYO decode started at state %d (%uus %s)\n",
data->state, TO_US(ev.duration), TO_STR(ev.pulse));
switch (data->state) {
case STATE_INACTIVE:
if (!ev.pulse)
break;
if (eq_margin(ev.duration, SANYO_HEADER_PULSE, SANYO_UNIT / 2)) {
data->count = 0;
data->state = STATE_HEADER_SPACE;
return 0;
}
break;
case STATE_HEADER_SPACE:
if (ev.pulse)
break;
if (eq_margin(ev.duration, SANYO_HEADER_SPACE, SANYO_UNIT / 2)) {
data->state = STATE_BIT_PULSE;
return 0;
}
break;
case STATE_BIT_PULSE:
if (!ev.pulse)
break;
if (!eq_margin(ev.duration, SANYO_BIT_PULSE, SANYO_UNIT / 2))
break;
data->state = STATE_BIT_SPACE;
return 0;
case STATE_BIT_SPACE:
if (ev.pulse)
break;
if (!data->count && geq_margin(ev.duration, SANYO_REPEAT_SPACE, SANYO_UNIT / 2)) {
if (!dev->keypressed) {
IR_dprintk(1, "SANYO discarding last key repeat: event after key up\n");
} else {
rc_repeat(dev);
IR_dprintk(1, "SANYO repeat last key\n");
data->state = STATE_INACTIVE;
}
return 0;
}
data->bits <<= 1;
if (eq_margin(ev.duration, SANYO_BIT_1_SPACE, SANYO_UNIT / 2))
data->bits |= 1;
else if (!eq_margin(ev.duration, SANYO_BIT_0_SPACE, SANYO_UNIT / 2))
break;
data->count++;
if (data->count == SANYO_NBITS)
data->state = STATE_TRAILER_PULSE;
else
data->state = STATE_BIT_PULSE;
return 0;
case STATE_TRAILER_PULSE:
if (!ev.pulse)
break;
if (!eq_margin(ev.duration, SANYO_TRAILER_PULSE, SANYO_UNIT / 2))
break;
data->state = STATE_TRAILER_SPACE;
return 0;
case STATE_TRAILER_SPACE:
if (ev.pulse)
break;
if (!geq_margin(ev.duration, SANYO_TRAILER_SPACE, SANYO_UNIT / 2))
break;
address = bitrev16((data->bits >> 29) & 0x1fff) >> 3;
not_address = bitrev16((data->bits >> 16) & 0x1fff) >> 3;
command = bitrev8((data->bits >> 8) & 0xff);
not_command = bitrev8((data->bits >> 0) & 0xff);
if ((command ^ not_command) != 0xff) {
IR_dprintk(1, "SANYO checksum error: received 0x%08Lx\n",
data->bits);
data->state = STATE_INACTIVE;
return 0;
}
scancode = address << 8 | command;
IR_dprintk(1, "SANYO scancode: 0x%06x\n", scancode);
rc_keydown(dev, scancode, 0);
data->state = STATE_INACTIVE;
return 0;
}
IR_dprintk(1, "SANYO decode failed at count %d state %d (%uus %s)\n",
data->count, data->state, TO_US(ev.duration), TO_STR(ev.pulse));
data->state = STATE_INACTIVE;
return -EINVAL;
}
static struct ir_raw_handler sanyo_handler = {
.protocols = RC_TYPE_SANYO,
.decode = ir_sanyo_decode,
};
static int __init ir_sanyo_decode_init(void)
{
ir_raw_handler_register(&sanyo_handler);
printk(KERN_INFO "IR SANYO protocol handler initialized\n");
return 0;
}
static void __exit ir_sanyo_decode_exit(void)
{
ir_raw_handler_unregister(&sanyo_handler);
}
module_init(ir_sanyo_decode_init);
module_exit(ir_sanyo_decode_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
MODULE_AUTHOR("Red Hat Inc. (http://www.redhat.com)");
MODULE_DESCRIPTION("SANYO IR protocol decoder");
| gpl-2.0 |
holyangel/M8-GPE_M | arch/ia64/xen/irq_xen.c | 4549 | 11976 | /******************************************************************************
* arch/ia64/xen/irq_xen.c
*
* Copyright (c) 2008 Isaku Yamahata <yamahata at valinux co jp>
* VA Linux Systems Japan K.K.
*
* 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/cpu.h>
#include <xen/interface/xen.h>
#include <xen/interface/callback.h>
#include <xen/events.h>
#include <asm/xen/privop.h>
#include "irq_xen.h"
/***************************************************************************
* pv_irq_ops
* irq operations
*/
static int
xen_assign_irq_vector(int irq)
{
struct physdev_irq irq_op;
irq_op.irq = irq;
if (HYPERVISOR_physdev_op(PHYSDEVOP_alloc_irq_vector, &irq_op))
return -ENOSPC;
return irq_op.vector;
}
static void
xen_free_irq_vector(int vector)
{
struct physdev_irq irq_op;
if (vector < IA64_FIRST_DEVICE_VECTOR ||
vector > IA64_LAST_DEVICE_VECTOR)
return;
irq_op.vector = vector;
if (HYPERVISOR_physdev_op(PHYSDEVOP_free_irq_vector, &irq_op))
printk(KERN_WARNING "%s: xen_free_irq_vector fail vector=%d\n",
__func__, vector);
}
static DEFINE_PER_CPU(int, xen_timer_irq) = -1;
static DEFINE_PER_CPU(int, xen_ipi_irq) = -1;
static DEFINE_PER_CPU(int, xen_resched_irq) = -1;
static DEFINE_PER_CPU(int, xen_cmc_irq) = -1;
static DEFINE_PER_CPU(int, xen_cmcp_irq) = -1;
static DEFINE_PER_CPU(int, xen_cpep_irq) = -1;
#define NAME_SIZE 15
static DEFINE_PER_CPU(char[NAME_SIZE], xen_timer_name);
static DEFINE_PER_CPU(char[NAME_SIZE], xen_ipi_name);
static DEFINE_PER_CPU(char[NAME_SIZE], xen_resched_name);
static DEFINE_PER_CPU(char[NAME_SIZE], xen_cmc_name);
static DEFINE_PER_CPU(char[NAME_SIZE], xen_cmcp_name);
static DEFINE_PER_CPU(char[NAME_SIZE], xen_cpep_name);
#undef NAME_SIZE
struct saved_irq {
unsigned int irq;
struct irqaction *action;
};
/* 16 should be far optimistic value, since only several percpu irqs
* are registered early.
*/
#define MAX_LATE_IRQ 16
static struct saved_irq saved_percpu_irqs[MAX_LATE_IRQ];
static unsigned short late_irq_cnt;
static unsigned short saved_irq_cnt;
static int xen_slab_ready;
#ifdef CONFIG_SMP
#include <linux/sched.h>
/* Dummy stub. Though we may check XEN_RESCHEDULE_VECTOR before __do_IRQ,
* it ends up to issue several memory accesses upon percpu data and
* thus adds unnecessary traffic to other paths.
*/
static irqreturn_t
xen_dummy_handler(int irq, void *dev_id)
{
return IRQ_HANDLED;
}
static irqreturn_t
xen_resched_handler(int irq, void *dev_id)
{
scheduler_ipi();
return IRQ_HANDLED;
}
static struct irqaction xen_ipi_irqaction = {
.handler = handle_IPI,
.flags = IRQF_DISABLED,
.name = "IPI"
};
static struct irqaction xen_resched_irqaction = {
.handler = xen_resched_handler,
.flags = IRQF_DISABLED,
.name = "resched"
};
static struct irqaction xen_tlb_irqaction = {
.handler = xen_dummy_handler,
.flags = IRQF_DISABLED,
.name = "tlb_flush"
};
#endif
/*
* This is xen version percpu irq registration, which needs bind
* to xen specific evtchn sub-system. One trick here is that xen
* evtchn binding interface depends on kmalloc because related
* port needs to be freed at device/cpu down. So we cache the
* registration on BSP before slab is ready and then deal them
* at later point. For rest instances happening after slab ready,
* we hook them to xen evtchn immediately.
*
* FIXME: MCA is not supported by far, and thus "nomca" boot param is
* required.
*/
static void
__xen_register_percpu_irq(unsigned int cpu, unsigned int vec,
struct irqaction *action, int save)
{
int irq = 0;
if (xen_slab_ready) {
switch (vec) {
case IA64_TIMER_VECTOR:
snprintf(per_cpu(xen_timer_name, cpu),
sizeof(per_cpu(xen_timer_name, cpu)),
"%s%d", action->name, cpu);
irq = bind_virq_to_irqhandler(VIRQ_ITC, cpu,
action->handler, action->flags,
per_cpu(xen_timer_name, cpu), action->dev_id);
per_cpu(xen_timer_irq, cpu) = irq;
break;
case IA64_IPI_RESCHEDULE:
snprintf(per_cpu(xen_resched_name, cpu),
sizeof(per_cpu(xen_resched_name, cpu)),
"%s%d", action->name, cpu);
irq = bind_ipi_to_irqhandler(XEN_RESCHEDULE_VECTOR, cpu,
action->handler, action->flags,
per_cpu(xen_resched_name, cpu), action->dev_id);
per_cpu(xen_resched_irq, cpu) = irq;
break;
case IA64_IPI_VECTOR:
snprintf(per_cpu(xen_ipi_name, cpu),
sizeof(per_cpu(xen_ipi_name, cpu)),
"%s%d", action->name, cpu);
irq = bind_ipi_to_irqhandler(XEN_IPI_VECTOR, cpu,
action->handler, action->flags,
per_cpu(xen_ipi_name, cpu), action->dev_id);
per_cpu(xen_ipi_irq, cpu) = irq;
break;
case IA64_CMC_VECTOR:
snprintf(per_cpu(xen_cmc_name, cpu),
sizeof(per_cpu(xen_cmc_name, cpu)),
"%s%d", action->name, cpu);
irq = bind_virq_to_irqhandler(VIRQ_MCA_CMC, cpu,
action->handler,
action->flags,
per_cpu(xen_cmc_name, cpu),
action->dev_id);
per_cpu(xen_cmc_irq, cpu) = irq;
break;
case IA64_CMCP_VECTOR:
snprintf(per_cpu(xen_cmcp_name, cpu),
sizeof(per_cpu(xen_cmcp_name, cpu)),
"%s%d", action->name, cpu);
irq = bind_ipi_to_irqhandler(XEN_CMCP_VECTOR, cpu,
action->handler,
action->flags,
per_cpu(xen_cmcp_name, cpu),
action->dev_id);
per_cpu(xen_cmcp_irq, cpu) = irq;
break;
case IA64_CPEP_VECTOR:
snprintf(per_cpu(xen_cpep_name, cpu),
sizeof(per_cpu(xen_cpep_name, cpu)),
"%s%d", action->name, cpu);
irq = bind_ipi_to_irqhandler(XEN_CPEP_VECTOR, cpu,
action->handler,
action->flags,
per_cpu(xen_cpep_name, cpu),
action->dev_id);
per_cpu(xen_cpep_irq, cpu) = irq;
break;
case IA64_CPE_VECTOR:
case IA64_MCA_RENDEZ_VECTOR:
case IA64_PERFMON_VECTOR:
case IA64_MCA_WAKEUP_VECTOR:
case IA64_SPURIOUS_INT_VECTOR:
/* No need to complain, these aren't supported. */
break;
default:
printk(KERN_WARNING "Percpu irq %d is unsupported "
"by xen!\n", vec);
break;
}
BUG_ON(irq < 0);
if (irq > 0) {
/*
* Mark percpu. Without this, migrate_irqs() will
* mark the interrupt for migrations and trigger it
* on cpu hotplug.
*/
irq_set_status_flags(irq, IRQ_PER_CPU);
}
}
/* For BSP, we cache registered percpu irqs, and then re-walk
* them when initializing APs
*/
if (!cpu && save) {
BUG_ON(saved_irq_cnt == MAX_LATE_IRQ);
saved_percpu_irqs[saved_irq_cnt].irq = vec;
saved_percpu_irqs[saved_irq_cnt].action = action;
saved_irq_cnt++;
if (!xen_slab_ready)
late_irq_cnt++;
}
}
static void
xen_register_percpu_irq(ia64_vector vec, struct irqaction *action)
{
__xen_register_percpu_irq(smp_processor_id(), vec, action, 1);
}
static void
xen_bind_early_percpu_irq(void)
{
int i;
xen_slab_ready = 1;
/* There's no race when accessing this cached array, since only
* BSP will face with such step shortly
*/
for (i = 0; i < late_irq_cnt; i++)
__xen_register_percpu_irq(smp_processor_id(),
saved_percpu_irqs[i].irq,
saved_percpu_irqs[i].action, 0);
}
/* FIXME: There's no obvious point to check whether slab is ready. So
* a hack is used here by utilizing a late time hook.
*/
#ifdef CONFIG_HOTPLUG_CPU
static int __devinit
unbind_evtchn_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
if (action == CPU_DEAD) {
/* Unregister evtchn. */
if (per_cpu(xen_cpep_irq, cpu) >= 0) {
unbind_from_irqhandler(per_cpu(xen_cpep_irq, cpu),
NULL);
per_cpu(xen_cpep_irq, cpu) = -1;
}
if (per_cpu(xen_cmcp_irq, cpu) >= 0) {
unbind_from_irqhandler(per_cpu(xen_cmcp_irq, cpu),
NULL);
per_cpu(xen_cmcp_irq, cpu) = -1;
}
if (per_cpu(xen_cmc_irq, cpu) >= 0) {
unbind_from_irqhandler(per_cpu(xen_cmc_irq, cpu), NULL);
per_cpu(xen_cmc_irq, cpu) = -1;
}
if (per_cpu(xen_ipi_irq, cpu) >= 0) {
unbind_from_irqhandler(per_cpu(xen_ipi_irq, cpu), NULL);
per_cpu(xen_ipi_irq, cpu) = -1;
}
if (per_cpu(xen_resched_irq, cpu) >= 0) {
unbind_from_irqhandler(per_cpu(xen_resched_irq, cpu),
NULL);
per_cpu(xen_resched_irq, cpu) = -1;
}
if (per_cpu(xen_timer_irq, cpu) >= 0) {
unbind_from_irqhandler(per_cpu(xen_timer_irq, cpu),
NULL);
per_cpu(xen_timer_irq, cpu) = -1;
}
}
return NOTIFY_OK;
}
static struct notifier_block unbind_evtchn_notifier = {
.notifier_call = unbind_evtchn_callback,
.priority = 0
};
#endif
void xen_smp_intr_init_early(unsigned int cpu)
{
#ifdef CONFIG_SMP
unsigned int i;
for (i = 0; i < saved_irq_cnt; i++)
__xen_register_percpu_irq(cpu, saved_percpu_irqs[i].irq,
saved_percpu_irqs[i].action, 0);
#endif
}
void xen_smp_intr_init(void)
{
#ifdef CONFIG_SMP
unsigned int cpu = smp_processor_id();
struct callback_register event = {
.type = CALLBACKTYPE_event,
.address = { .ip = (unsigned long)&xen_event_callback },
};
if (cpu == 0) {
/* Initialization was already done for boot cpu. */
#ifdef CONFIG_HOTPLUG_CPU
/* Register the notifier only once. */
register_cpu_notifier(&unbind_evtchn_notifier);
#endif
return;
}
/* This should be piggyback when setup vcpu guest context */
BUG_ON(HYPERVISOR_callback_op(CALLBACKOP_register, &event));
#endif /* CONFIG_SMP */
}
void __init
xen_irq_init(void)
{
struct callback_register event = {
.type = CALLBACKTYPE_event,
.address = { .ip = (unsigned long)&xen_event_callback },
};
xen_init_IRQ();
BUG_ON(HYPERVISOR_callback_op(CALLBACKOP_register, &event));
late_time_init = xen_bind_early_percpu_irq;
}
void
xen_platform_send_ipi(int cpu, int vector, int delivery_mode, int redirect)
{
#ifdef CONFIG_SMP
/* TODO: we need to call vcpu_up here */
if (unlikely(vector == ap_wakeup_vector)) {
/* XXX
* This should be in __cpu_up(cpu) in ia64 smpboot.c
* like x86. But don't want to modify it,
* keep it untouched.
*/
xen_smp_intr_init_early(cpu);
xen_send_ipi(cpu, vector);
/* vcpu_prepare_and_up(cpu); */
return;
}
#endif
switch (vector) {
case IA64_IPI_VECTOR:
xen_send_IPI_one(cpu, XEN_IPI_VECTOR);
break;
case IA64_IPI_RESCHEDULE:
xen_send_IPI_one(cpu, XEN_RESCHEDULE_VECTOR);
break;
case IA64_CMCP_VECTOR:
xen_send_IPI_one(cpu, XEN_CMCP_VECTOR);
break;
case IA64_CPEP_VECTOR:
xen_send_IPI_one(cpu, XEN_CPEP_VECTOR);
break;
case IA64_TIMER_VECTOR: {
/* this is used only once by check_sal_cache_flush()
at boot time */
static int used = 0;
if (!used) {
xen_send_ipi(cpu, IA64_TIMER_VECTOR);
used = 1;
break;
}
/* fallthrough */
}
default:
printk(KERN_WARNING "Unsupported IPI type 0x%x\n",
vector);
notify_remote_via_irq(0); /* defaults to 0 irq */
break;
}
}
static void __init
xen_register_ipi(void)
{
#ifdef CONFIG_SMP
register_percpu_irq(IA64_IPI_VECTOR, &xen_ipi_irqaction);
register_percpu_irq(IA64_IPI_RESCHEDULE, &xen_resched_irqaction);
register_percpu_irq(IA64_IPI_LOCAL_TLB_FLUSH, &xen_tlb_irqaction);
#endif
}
static void
xen_resend_irq(unsigned int vector)
{
(void)resend_irq_on_evtchn(vector);
}
const struct pv_irq_ops xen_irq_ops __initdata = {
.register_ipi = xen_register_ipi,
.assign_irq_vector = xen_assign_irq_vector,
.free_irq_vector = xen_free_irq_vector,
.register_percpu_irq = xen_register_percpu_irq,
.resend_irq = xen_resend_irq,
};
| gpl-2.0 |
Jackeagle/msm8226-caf | drivers/mtd/maps/intel_vr_nor.c | 4805 | 7271 | /*
* drivers/mtd/maps/intel_vr_nor.c
*
* An MTD map driver for a NOR flash bank on the Expansion Bus of the Intel
* Vermilion Range chipset.
*
* The Vermilion Range Expansion Bus supports four chip selects, each of which
* has 64MiB of address space. The 2nd BAR of the Expansion Bus PCI Device
* is a 256MiB memory region containing the address spaces for all four of the
* chip selects, with start addresses hardcoded on 64MiB boundaries.
*
* This map driver only supports NOR flash on chip select 0. The buswidth
* (either 8 bits or 16 bits) is determined by reading the Expansion Bus Timing
* and Control Register for Chip Select 0 (EXP_TIMING_CS0). This driver does
* not modify the value in the EXP_TIMING_CS0 register except to enable writing
* and disable boot acceleration. The timing parameters in the register are
* assumed to have been properly initialized by the BIOS. The reset default
* timing parameters are maximally conservative (slow), so access to the flash
* will be slower than it should be if the BIOS has not initialized the timing
* parameters.
*
* Author: Andy Lowe <alowe@mvista.com>
*
* 2006 (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/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/cfi.h>
#include <linux/mtd/flashchip.h>
#define DRV_NAME "vr_nor"
struct vr_nor_mtd {
void __iomem *csr_base;
struct map_info map;
struct mtd_info *info;
struct pci_dev *dev;
};
/* Expansion Bus Configuration and Status Registers are in BAR 0 */
#define EXP_CSR_MBAR 0
/* Expansion Bus Memory Window is BAR 1 */
#define EXP_WIN_MBAR 1
/* Maximum address space for Chip Select 0 is 64MiB */
#define CS0_SIZE 0x04000000
/* Chip Select 0 is at offset 0 in the Memory Window */
#define CS0_START 0x0
/* Chip Select 0 Timing Register is at offset 0 in CSR */
#define EXP_TIMING_CS0 0x00
#define TIMING_CS_EN (1 << 31) /* Chip Select Enable */
#define TIMING_BOOT_ACCEL_DIS (1 << 8) /* Boot Acceleration Disable */
#define TIMING_WR_EN (1 << 1) /* Write Enable */
#define TIMING_BYTE_EN (1 << 0) /* 8-bit vs 16-bit bus */
#define TIMING_MASK 0x3FFF0000
static void __devexit vr_nor_destroy_partitions(struct vr_nor_mtd *p)
{
mtd_device_unregister(p->info);
}
static int __devinit vr_nor_init_partitions(struct vr_nor_mtd *p)
{
/* register the flash bank */
/* partition the flash bank */
return mtd_device_parse_register(p->info, NULL, NULL, NULL, 0);
}
static void __devexit vr_nor_destroy_mtd_setup(struct vr_nor_mtd *p)
{
map_destroy(p->info);
}
static int __devinit vr_nor_mtd_setup(struct vr_nor_mtd *p)
{
static const char *probe_types[] =
{ "cfi_probe", "jedec_probe", NULL };
const char **type;
for (type = probe_types; !p->info && *type; type++)
p->info = do_map_probe(*type, &p->map);
if (!p->info)
return -ENODEV;
p->info->owner = THIS_MODULE;
return 0;
}
static void __devexit vr_nor_destroy_maps(struct vr_nor_mtd *p)
{
unsigned int exp_timing_cs0;
/* write-protect the flash bank */
exp_timing_cs0 = readl(p->csr_base + EXP_TIMING_CS0);
exp_timing_cs0 &= ~TIMING_WR_EN;
writel(exp_timing_cs0, p->csr_base + EXP_TIMING_CS0);
/* unmap the flash window */
iounmap(p->map.virt);
/* unmap the csr window */
iounmap(p->csr_base);
}
/*
* Initialize the map_info structure and map the flash.
* Returns 0 on success, nonzero otherwise.
*/
static int __devinit vr_nor_init_maps(struct vr_nor_mtd *p)
{
unsigned long csr_phys, csr_len;
unsigned long win_phys, win_len;
unsigned int exp_timing_cs0;
int err;
csr_phys = pci_resource_start(p->dev, EXP_CSR_MBAR);
csr_len = pci_resource_len(p->dev, EXP_CSR_MBAR);
win_phys = pci_resource_start(p->dev, EXP_WIN_MBAR);
win_len = pci_resource_len(p->dev, EXP_WIN_MBAR);
if (!csr_phys || !csr_len || !win_phys || !win_len)
return -ENODEV;
if (win_len < (CS0_START + CS0_SIZE))
return -ENXIO;
p->csr_base = ioremap_nocache(csr_phys, csr_len);
if (!p->csr_base)
return -ENOMEM;
exp_timing_cs0 = readl(p->csr_base + EXP_TIMING_CS0);
if (!(exp_timing_cs0 & TIMING_CS_EN)) {
dev_warn(&p->dev->dev, "Expansion Bus Chip Select 0 "
"is disabled.\n");
err = -ENODEV;
goto release;
}
if ((exp_timing_cs0 & TIMING_MASK) == TIMING_MASK) {
dev_warn(&p->dev->dev, "Expansion Bus Chip Select 0 "
"is configured for maximally slow access times.\n");
}
p->map.name = DRV_NAME;
p->map.bankwidth = (exp_timing_cs0 & TIMING_BYTE_EN) ? 1 : 2;
p->map.phys = win_phys + CS0_START;
p->map.size = CS0_SIZE;
p->map.virt = ioremap_nocache(p->map.phys, p->map.size);
if (!p->map.virt) {
err = -ENOMEM;
goto release;
}
simple_map_init(&p->map);
/* Enable writes to flash bank */
exp_timing_cs0 |= TIMING_BOOT_ACCEL_DIS | TIMING_WR_EN;
writel(exp_timing_cs0, p->csr_base + EXP_TIMING_CS0);
return 0;
release:
iounmap(p->csr_base);
return err;
}
static struct pci_device_id vr_nor_pci_ids[] = {
{PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x500D)},
{0,}
};
static void __devexit vr_nor_pci_remove(struct pci_dev *dev)
{
struct vr_nor_mtd *p = pci_get_drvdata(dev);
pci_set_drvdata(dev, NULL);
vr_nor_destroy_partitions(p);
vr_nor_destroy_mtd_setup(p);
vr_nor_destroy_maps(p);
kfree(p);
pci_release_regions(dev);
pci_disable_device(dev);
}
static int __devinit
vr_nor_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
struct vr_nor_mtd *p = NULL;
unsigned int exp_timing_cs0;
int err;
err = pci_enable_device(dev);
if (err)
goto out;
err = pci_request_regions(dev, DRV_NAME);
if (err)
goto disable_dev;
p = kzalloc(sizeof(*p), GFP_KERNEL);
err = -ENOMEM;
if (!p)
goto release;
p->dev = dev;
err = vr_nor_init_maps(p);
if (err)
goto release;
err = vr_nor_mtd_setup(p);
if (err)
goto destroy_maps;
err = vr_nor_init_partitions(p);
if (err)
goto destroy_mtd_setup;
pci_set_drvdata(dev, p);
return 0;
destroy_mtd_setup:
map_destroy(p->info);
destroy_maps:
/* write-protect the flash bank */
exp_timing_cs0 = readl(p->csr_base + EXP_TIMING_CS0);
exp_timing_cs0 &= ~TIMING_WR_EN;
writel(exp_timing_cs0, p->csr_base + EXP_TIMING_CS0);
/* unmap the flash window */
iounmap(p->map.virt);
/* unmap the csr window */
iounmap(p->csr_base);
release:
kfree(p);
pci_release_regions(dev);
disable_dev:
pci_disable_device(dev);
out:
return err;
}
static struct pci_driver vr_nor_pci_driver = {
.name = DRV_NAME,
.probe = vr_nor_pci_probe,
.remove = __devexit_p(vr_nor_pci_remove),
.id_table = vr_nor_pci_ids,
};
static int __init vr_nor_mtd_init(void)
{
return pci_register_driver(&vr_nor_pci_driver);
}
static void __exit vr_nor_mtd_exit(void)
{
pci_unregister_driver(&vr_nor_pci_driver);
}
module_init(vr_nor_mtd_init);
module_exit(vr_nor_mtd_exit);
MODULE_AUTHOR("Andy Lowe");
MODULE_DESCRIPTION("MTD map driver for NOR flash on Intel Vermilion Range");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, vr_nor_pci_ids);
| gpl-2.0 |
davidmueller13/Fulgor_Kernel_Lollipop | sound/soc/fsl/mpc8610_hpcd.c | 4805 | 17451 | /**
* Freescale MPC8610HPCD ALSA SoC Machine driver
*
* Author: Timur Tabi <timur@freescale.com>
*
* Copyright 2007-2010 Freescale Semiconductor, 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/module.h>
#include <linux/interrupt.h>
#include <linux/of_device.h>
#include <linux/slab.h>
#include <linux/of_i2c.h>
#include <sound/soc.h>
#include <asm/fsl_guts.h>
#include "fsl_dma.h"
#include "fsl_ssi.h"
/* There's only one global utilities register */
static phys_addr_t guts_phys;
#define DAI_NAME_SIZE 32
/**
* mpc8610_hpcd_data: machine-specific ASoC device data
*
* This structure contains data for a single sound platform device on an
* MPC8610 HPCD. Some of the data is taken from the device tree.
*/
struct mpc8610_hpcd_data {
struct snd_soc_dai_link dai[2];
struct snd_soc_card card;
unsigned int dai_format;
unsigned int codec_clk_direction;
unsigned int cpu_clk_direction;
unsigned int clk_frequency;
unsigned int ssi_id; /* 0 = SSI1, 1 = SSI2, etc */
unsigned int dma_id[2]; /* 0 = DMA1, 1 = DMA2, etc */
unsigned int dma_channel_id[2]; /* 0 = ch 0, 1 = ch 1, etc*/
char codec_dai_name[DAI_NAME_SIZE];
char codec_name[DAI_NAME_SIZE];
char platform_name[2][DAI_NAME_SIZE]; /* One for each DMA channel */
};
/**
* mpc8610_hpcd_machine_probe: initialize the board
*
* This function is used to initialize the board-specific hardware.
*
* Here we program the DMACR and PMUXCR registers.
*/
static int mpc8610_hpcd_machine_probe(struct snd_soc_card *card)
{
struct mpc8610_hpcd_data *machine_data =
container_of(card, struct mpc8610_hpcd_data, card);
struct ccsr_guts __iomem *guts;
guts = ioremap(guts_phys, sizeof(struct ccsr_guts));
if (!guts) {
dev_err(card->dev, "could not map global utilities\n");
return -ENOMEM;
}
/* Program the signal routing between the SSI and the DMA */
guts_set_dmacr(guts, machine_data->dma_id[0],
machine_data->dma_channel_id[0],
CCSR_GUTS_DMACR_DEV_SSI);
guts_set_dmacr(guts, machine_data->dma_id[1],
machine_data->dma_channel_id[1],
CCSR_GUTS_DMACR_DEV_SSI);
guts_set_pmuxcr_dma(guts, machine_data->dma_id[0],
machine_data->dma_channel_id[0], 0);
guts_set_pmuxcr_dma(guts, machine_data->dma_id[1],
machine_data->dma_channel_id[1], 0);
switch (machine_data->ssi_id) {
case 0:
clrsetbits_be32(&guts->pmuxcr,
CCSR_GUTS_PMUXCR_SSI1_MASK, CCSR_GUTS_PMUXCR_SSI1_SSI);
break;
case 1:
clrsetbits_be32(&guts->pmuxcr,
CCSR_GUTS_PMUXCR_SSI2_MASK, CCSR_GUTS_PMUXCR_SSI2_SSI);
break;
}
iounmap(guts);
return 0;
}
/**
* mpc8610_hpcd_startup: program the board with various hardware parameters
*
* This function takes board-specific information, like clock frequencies
* and serial data formats, and passes that information to the codec and
* transport drivers.
*/
static int mpc8610_hpcd_startup(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct mpc8610_hpcd_data *machine_data =
container_of(rtd->card, struct mpc8610_hpcd_data, card);
struct device *dev = rtd->card->dev;
int ret = 0;
/* Tell the codec driver what the serial protocol is. */
ret = snd_soc_dai_set_fmt(rtd->codec_dai, machine_data->dai_format);
if (ret < 0) {
dev_err(dev, "could not set codec driver audio format\n");
return ret;
}
/*
* Tell the codec driver what the MCLK frequency is, and whether it's
* a slave or master.
*/
ret = snd_soc_dai_set_sysclk(rtd->codec_dai, 0,
machine_data->clk_frequency,
machine_data->codec_clk_direction);
if (ret < 0) {
dev_err(dev, "could not set codec driver clock params\n");
return ret;
}
return 0;
}
/**
* mpc8610_hpcd_machine_remove: Remove the sound device
*
* This function is called to remove the sound device for one SSI. We
* de-program the DMACR and PMUXCR register.
*/
static int mpc8610_hpcd_machine_remove(struct snd_soc_card *card)
{
struct mpc8610_hpcd_data *machine_data =
container_of(card, struct mpc8610_hpcd_data, card);
struct ccsr_guts __iomem *guts;
guts = ioremap(guts_phys, sizeof(struct ccsr_guts));
if (!guts) {
dev_err(card->dev, "could not map global utilities\n");
return -ENOMEM;
}
/* Restore the signal routing */
guts_set_dmacr(guts, machine_data->dma_id[0],
machine_data->dma_channel_id[0], 0);
guts_set_dmacr(guts, machine_data->dma_id[1],
machine_data->dma_channel_id[1], 0);
switch (machine_data->ssi_id) {
case 0:
clrsetbits_be32(&guts->pmuxcr,
CCSR_GUTS_PMUXCR_SSI1_MASK, CCSR_GUTS_PMUXCR_SSI1_LA);
break;
case 1:
clrsetbits_be32(&guts->pmuxcr,
CCSR_GUTS_PMUXCR_SSI2_MASK, CCSR_GUTS_PMUXCR_SSI2_LA);
break;
}
iounmap(guts);
return 0;
}
/**
* mpc8610_hpcd_ops: ASoC machine driver operations
*/
static struct snd_soc_ops mpc8610_hpcd_ops = {
.startup = mpc8610_hpcd_startup,
};
/**
* get_node_by_phandle_name - get a node by its phandle name
*
* This function takes a node, the name of a property in that node, and a
* compatible string. Assuming the property is a phandle to another node,
* it returns that node, (optionally) if that node is compatible.
*
* If the property is not a phandle, or the node it points to is not compatible
* with the specific string, then NULL is returned.
*/
static struct device_node *get_node_by_phandle_name(struct device_node *np,
const char *name,
const char *compatible)
{
const phandle *ph;
int len;
ph = of_get_property(np, name, &len);
if (!ph || (len != sizeof(phandle)))
return NULL;
np = of_find_node_by_phandle(*ph);
if (!np)
return NULL;
if (compatible && !of_device_is_compatible(np, compatible)) {
of_node_put(np);
return NULL;
}
return np;
}
/**
* get_parent_cell_index -- return the cell-index of the parent of a node
*
* Return the value of the cell-index property of the parent of the given
* node. This is used for DMA channel nodes that need to know the DMA ID
* of the controller they are on.
*/
static int get_parent_cell_index(struct device_node *np)
{
struct device_node *parent = of_get_parent(np);
const u32 *iprop;
if (!parent)
return -1;
iprop = of_get_property(parent, "cell-index", NULL);
of_node_put(parent);
if (!iprop)
return -1;
return be32_to_cpup(iprop);
}
/**
* codec_node_dev_name - determine the dev_name for a codec node
*
* This function determines the dev_name for an I2C node. This is the name
* that would be returned by dev_name() if this device_node were part of a
* 'struct device' It's ugly and hackish, but it works.
*
* The dev_name for such devices include the bus number and I2C address. For
* example, "cs4270.0-004f".
*/
static int codec_node_dev_name(struct device_node *np, char *buf, size_t len)
{
const u32 *iprop;
int addr;
char temp[DAI_NAME_SIZE];
struct i2c_client *i2c;
of_modalias_node(np, temp, DAI_NAME_SIZE);
iprop = of_get_property(np, "reg", NULL);
if (!iprop)
return -EINVAL;
addr = be32_to_cpup(iprop);
/* We need the adapter number */
i2c = of_find_i2c_device_by_node(np);
if (!i2c)
return -ENODEV;
snprintf(buf, len, "%s.%u-%04x", temp, i2c->adapter->nr, addr);
return 0;
}
static int get_dma_channel(struct device_node *ssi_np,
const char *name,
struct snd_soc_dai_link *dai,
unsigned int *dma_channel_id,
unsigned int *dma_id)
{
struct resource res;
struct device_node *dma_channel_np;
const u32 *iprop;
int ret;
dma_channel_np = get_node_by_phandle_name(ssi_np, name,
"fsl,ssi-dma-channel");
if (!dma_channel_np)
return -EINVAL;
/* Determine the dev_name for the device_node. This code mimics the
* behavior of of_device_make_bus_id(). We need this because ASoC uses
* the dev_name() of the device to match the platform (DMA) device with
* the CPU (SSI) device. It's all ugly and hackish, but it works (for
* now).
*
* dai->platform name should already point to an allocated buffer.
*/
ret = of_address_to_resource(dma_channel_np, 0, &res);
if (ret)
return ret;
snprintf((char *)dai->platform_name, DAI_NAME_SIZE, "%llx.%s",
(unsigned long long) res.start, dma_channel_np->name);
iprop = of_get_property(dma_channel_np, "cell-index", NULL);
if (!iprop) {
of_node_put(dma_channel_np);
return -EINVAL;
}
*dma_channel_id = be32_to_cpup(iprop);
*dma_id = get_parent_cell_index(dma_channel_np);
of_node_put(dma_channel_np);
return 0;
}
/**
* mpc8610_hpcd_probe: platform probe function for the machine driver
*
* Although this is a machine driver, the SSI node is the "master" node with
* respect to audio hardware connections. Therefore, we create a new ASoC
* device for each new SSI node that has a codec attached.
*/
static int mpc8610_hpcd_probe(struct platform_device *pdev)
{
struct device *dev = pdev->dev.parent;
/* ssi_pdev is the platform device for the SSI node that probed us */
struct platform_device *ssi_pdev =
container_of(dev, struct platform_device, dev);
struct device_node *np = ssi_pdev->dev.of_node;
struct device_node *codec_np = NULL;
struct platform_device *sound_device = NULL;
struct mpc8610_hpcd_data *machine_data;
int ret = -ENODEV;
const char *sprop;
const u32 *iprop;
/* Find the codec node for this SSI. */
codec_np = of_parse_phandle(np, "codec-handle", 0);
if (!codec_np) {
dev_err(dev, "invalid codec node\n");
return -EINVAL;
}
machine_data = kzalloc(sizeof(struct mpc8610_hpcd_data), GFP_KERNEL);
if (!machine_data) {
ret = -ENOMEM;
goto error_alloc;
}
machine_data->dai[0].cpu_dai_name = dev_name(&ssi_pdev->dev);
machine_data->dai[0].ops = &mpc8610_hpcd_ops;
/* Determine the codec name, it will be used as the codec DAI name */
ret = codec_node_dev_name(codec_np, machine_data->codec_name,
DAI_NAME_SIZE);
if (ret) {
dev_err(&pdev->dev, "invalid codec node %s\n",
codec_np->full_name);
ret = -EINVAL;
goto error;
}
machine_data->dai[0].codec_name = machine_data->codec_name;
/* The DAI name from the codec (snd_soc_dai_driver.name) */
machine_data->dai[0].codec_dai_name = "cs4270-hifi";
/* We register two DAIs per SSI, one for playback and the other for
* capture. Currently, we only support codecs that have one DAI for
* both playback and capture.
*/
memcpy(&machine_data->dai[1], &machine_data->dai[0],
sizeof(struct snd_soc_dai_link));
/* Get the device ID */
iprop = of_get_property(np, "cell-index", NULL);
if (!iprop) {
dev_err(&pdev->dev, "cell-index property not found\n");
ret = -EINVAL;
goto error;
}
machine_data->ssi_id = be32_to_cpup(iprop);
/* Get the serial format and clock direction. */
sprop = of_get_property(np, "fsl,mode", NULL);
if (!sprop) {
dev_err(&pdev->dev, "fsl,mode property not found\n");
ret = -EINVAL;
goto error;
}
if (strcasecmp(sprop, "i2s-slave") == 0) {
machine_data->dai_format =
SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBM_CFM;
machine_data->codec_clk_direction = SND_SOC_CLOCK_OUT;
machine_data->cpu_clk_direction = SND_SOC_CLOCK_IN;
/* In i2s-slave mode, the codec has its own clock source, so we
* need to get the frequency from the device tree and pass it to
* the codec driver.
*/
iprop = of_get_property(codec_np, "clock-frequency", NULL);
if (!iprop || !*iprop) {
dev_err(&pdev->dev, "codec bus-frequency "
"property is missing or invalid\n");
ret = -EINVAL;
goto error;
}
machine_data->clk_frequency = be32_to_cpup(iprop);
} else if (strcasecmp(sprop, "i2s-master") == 0) {
machine_data->dai_format =
SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBS_CFS;
machine_data->codec_clk_direction = SND_SOC_CLOCK_IN;
machine_data->cpu_clk_direction = SND_SOC_CLOCK_OUT;
} else if (strcasecmp(sprop, "lj-slave") == 0) {
machine_data->dai_format =
SND_SOC_DAIFMT_LEFT_J | SND_SOC_DAIFMT_CBM_CFM;
machine_data->codec_clk_direction = SND_SOC_CLOCK_OUT;
machine_data->cpu_clk_direction = SND_SOC_CLOCK_IN;
} else if (strcasecmp(sprop, "lj-master") == 0) {
machine_data->dai_format =
SND_SOC_DAIFMT_LEFT_J | SND_SOC_DAIFMT_CBS_CFS;
machine_data->codec_clk_direction = SND_SOC_CLOCK_IN;
machine_data->cpu_clk_direction = SND_SOC_CLOCK_OUT;
} else if (strcasecmp(sprop, "rj-slave") == 0) {
machine_data->dai_format =
SND_SOC_DAIFMT_RIGHT_J | SND_SOC_DAIFMT_CBM_CFM;
machine_data->codec_clk_direction = SND_SOC_CLOCK_OUT;
machine_data->cpu_clk_direction = SND_SOC_CLOCK_IN;
} else if (strcasecmp(sprop, "rj-master") == 0) {
machine_data->dai_format =
SND_SOC_DAIFMT_RIGHT_J | SND_SOC_DAIFMT_CBS_CFS;
machine_data->codec_clk_direction = SND_SOC_CLOCK_IN;
machine_data->cpu_clk_direction = SND_SOC_CLOCK_OUT;
} else if (strcasecmp(sprop, "ac97-slave") == 0) {
machine_data->dai_format =
SND_SOC_DAIFMT_AC97 | SND_SOC_DAIFMT_CBM_CFM;
machine_data->codec_clk_direction = SND_SOC_CLOCK_OUT;
machine_data->cpu_clk_direction = SND_SOC_CLOCK_IN;
} else if (strcasecmp(sprop, "ac97-master") == 0) {
machine_data->dai_format =
SND_SOC_DAIFMT_AC97 | SND_SOC_DAIFMT_CBS_CFS;
machine_data->codec_clk_direction = SND_SOC_CLOCK_IN;
machine_data->cpu_clk_direction = SND_SOC_CLOCK_OUT;
} else {
dev_err(&pdev->dev,
"unrecognized fsl,mode property '%s'\n", sprop);
ret = -EINVAL;
goto error;
}
if (!machine_data->clk_frequency) {
dev_err(&pdev->dev, "unknown clock frequency\n");
ret = -EINVAL;
goto error;
}
/* Find the playback DMA channel to use. */
machine_data->dai[0].platform_name = machine_data->platform_name[0];
ret = get_dma_channel(np, "fsl,playback-dma", &machine_data->dai[0],
&machine_data->dma_channel_id[0],
&machine_data->dma_id[0]);
if (ret) {
dev_err(&pdev->dev, "missing/invalid playback DMA phandle\n");
goto error;
}
/* Find the capture DMA channel to use. */
machine_data->dai[1].platform_name = machine_data->platform_name[1];
ret = get_dma_channel(np, "fsl,capture-dma", &machine_data->dai[1],
&machine_data->dma_channel_id[1],
&machine_data->dma_id[1]);
if (ret) {
dev_err(&pdev->dev, "missing/invalid capture DMA phandle\n");
goto error;
}
/* Initialize our DAI data structure. */
machine_data->dai[0].stream_name = "playback";
machine_data->dai[1].stream_name = "capture";
machine_data->dai[0].name = machine_data->dai[0].stream_name;
machine_data->dai[1].name = machine_data->dai[1].stream_name;
machine_data->card.probe = mpc8610_hpcd_machine_probe;
machine_data->card.remove = mpc8610_hpcd_machine_remove;
machine_data->card.name = pdev->name; /* The platform driver name */
machine_data->card.num_links = 2;
machine_data->card.dai_link = machine_data->dai;
/* Allocate a new audio platform device structure */
sound_device = platform_device_alloc("soc-audio", -1);
if (!sound_device) {
dev_err(&pdev->dev, "platform device alloc failed\n");
ret = -ENOMEM;
goto error;
}
/* Associate the card data with the sound device */
platform_set_drvdata(sound_device, &machine_data->card);
/* Register with ASoC */
ret = platform_device_add(sound_device);
if (ret) {
dev_err(&pdev->dev, "platform device add failed\n");
goto error_sound;
}
dev_set_drvdata(&pdev->dev, sound_device);
of_node_put(codec_np);
return 0;
error_sound:
platform_device_put(sound_device);
error:
kfree(machine_data);
error_alloc:
of_node_put(codec_np);
return ret;
}
/**
* mpc8610_hpcd_remove: remove the platform device
*
* This function is called when the platform device is removed.
*/
static int __devexit mpc8610_hpcd_remove(struct platform_device *pdev)
{
struct platform_device *sound_device = dev_get_drvdata(&pdev->dev);
struct snd_soc_card *card = platform_get_drvdata(sound_device);
struct mpc8610_hpcd_data *machine_data =
container_of(card, struct mpc8610_hpcd_data, card);
platform_device_unregister(sound_device);
kfree(machine_data);
sound_device->dev.platform_data = NULL;
dev_set_drvdata(&pdev->dev, NULL);
return 0;
}
static struct platform_driver mpc8610_hpcd_driver = {
.probe = mpc8610_hpcd_probe,
.remove = __devexit_p(mpc8610_hpcd_remove),
.driver = {
/* The name must match 'compatible' property in the device tree,
* in lowercase letters.
*/
.name = "snd-soc-mpc8610hpcd",
.owner = THIS_MODULE,
},
};
/**
* mpc8610_hpcd_init: machine driver initialization.
*
* This function is called when this module is loaded.
*/
static int __init mpc8610_hpcd_init(void)
{
struct device_node *guts_np;
struct resource res;
pr_info("Freescale MPC8610 HPCD ALSA SoC machine driver\n");
/* Get the physical address of the global utilities registers */
guts_np = of_find_compatible_node(NULL, NULL, "fsl,mpc8610-guts");
if (of_address_to_resource(guts_np, 0, &res)) {
pr_err("mpc8610-hpcd: missing/invalid global utilities node\n");
return -EINVAL;
}
guts_phys = res.start;
return platform_driver_register(&mpc8610_hpcd_driver);
}
/**
* mpc8610_hpcd_exit: machine driver exit
*
* This function is called when this driver is unloaded.
*/
static void __exit mpc8610_hpcd_exit(void)
{
platform_driver_unregister(&mpc8610_hpcd_driver);
}
module_init(mpc8610_hpcd_init);
module_exit(mpc8610_hpcd_exit);
MODULE_AUTHOR("Timur Tabi <timur@freescale.com>");
MODULE_DESCRIPTION("Freescale MPC8610 HPCD ALSA SoC machine driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
agat63/GS4_test | arch/powerpc/platforms/512x/mpc512x_shared.c | 4805 | 11722 | /*
* Copyright (C) 2007,2008 Freescale Semiconductor, Inc. All rights reserved.
*
* Author: John Rigby <jrigby@freescale.com>
*
* Description:
* MPC512x Shared code
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/of_platform.h>
#include <linux/fsl-diu-fb.h>
#include <linux/bootmem.h>
#include <sysdev/fsl_soc.h>
#include <asm/cacheflush.h>
#include <asm/machdep.h>
#include <asm/ipic.h>
#include <asm/prom.h>
#include <asm/time.h>
#include <asm/mpc5121.h>
#include <asm/mpc52xx_psc.h>
#include "mpc512x.h"
static struct mpc512x_reset_module __iomem *reset_module_base;
static void __init mpc512x_restart_init(void)
{
struct device_node *np;
np = of_find_compatible_node(NULL, NULL, "fsl,mpc5121-reset");
if (!np)
return;
reset_module_base = of_iomap(np, 0);
of_node_put(np);
}
void mpc512x_restart(char *cmd)
{
if (reset_module_base) {
/* Enable software reset "RSTE" */
out_be32(&reset_module_base->rpr, 0x52535445);
/* Set software hard reset */
out_be32(&reset_module_base->rcr, 0x2);
} else {
pr_err("Restart module not mapped.\n");
}
for (;;)
;
}
struct fsl_diu_shared_fb {
u8 gamma[0x300]; /* 32-bit aligned! */
struct diu_ad ad0; /* 32-bit aligned! */
phys_addr_t fb_phys;
size_t fb_len;
bool in_use;
};
u32 mpc512x_get_pixel_format(enum fsl_diu_monitor_port port,
unsigned int bits_per_pixel)
{
switch (bits_per_pixel) {
case 32:
return 0x88883316;
case 24:
return 0x88082219;
case 16:
return 0x65053118;
}
return 0x00000400;
}
void mpc512x_set_gamma_table(enum fsl_diu_monitor_port port,
char *gamma_table_base)
{
}
void mpc512x_set_monitor_port(enum fsl_diu_monitor_port port)
{
}
#define DIU_DIV_MASK 0x000000ff
void mpc512x_set_pixel_clock(unsigned int pixclock)
{
unsigned long bestval, bestfreq, speed, busfreq;
unsigned long minpixclock, maxpixclock, pixval;
struct mpc512x_ccm __iomem *ccm;
struct device_node *np;
u32 temp;
long err;
int i;
np = of_find_compatible_node(NULL, NULL, "fsl,mpc5121-clock");
if (!np) {
pr_err("Can't find clock control module.\n");
return;
}
ccm = of_iomap(np, 0);
of_node_put(np);
if (!ccm) {
pr_err("Can't map clock control module reg.\n");
return;
}
np = of_find_node_by_type(NULL, "cpu");
if (np) {
const unsigned int *prop =
of_get_property(np, "bus-frequency", NULL);
of_node_put(np);
if (prop) {
busfreq = *prop;
} else {
pr_err("Can't get bus-frequency property\n");
return;
}
} else {
pr_err("Can't find 'cpu' node.\n");
return;
}
/* Pixel Clock configuration */
pr_debug("DIU: Bus Frequency = %lu\n", busfreq);
speed = busfreq * 4; /* DIU_DIV ratio is 4 * CSB_CLK / DIU_CLK */
/* Calculate the pixel clock with the smallest error */
/* calculate the following in steps to avoid overflow */
pr_debug("DIU pixclock in ps - %d\n", pixclock);
temp = (1000000000 / pixclock) * 1000;
pixclock = temp;
pr_debug("DIU pixclock freq - %u\n", pixclock);
temp = temp / 20; /* pixclock * 0.05 */
pr_debug("deviation = %d\n", temp);
minpixclock = pixclock - temp;
maxpixclock = pixclock + temp;
pr_debug("DIU minpixclock - %lu\n", minpixclock);
pr_debug("DIU maxpixclock - %lu\n", maxpixclock);
pixval = speed/pixclock;
pr_debug("DIU pixval = %lu\n", pixval);
err = LONG_MAX;
bestval = pixval;
pr_debug("DIU bestval = %lu\n", bestval);
bestfreq = 0;
for (i = -1; i <= 1; i++) {
temp = speed / (pixval+i);
pr_debug("DIU test pixval i=%d, pixval=%lu, temp freq. = %u\n",
i, pixval, temp);
if ((temp < minpixclock) || (temp > maxpixclock))
pr_debug("DIU exceeds monitor range (%lu to %lu)\n",
minpixclock, maxpixclock);
else if (abs(temp - pixclock) < err) {
pr_debug("Entered the else if block %d\n", i);
err = abs(temp - pixclock);
bestval = pixval + i;
bestfreq = temp;
}
}
pr_debug("DIU chose = %lx\n", bestval);
pr_debug("DIU error = %ld\n NomPixClk ", err);
pr_debug("DIU: Best Freq = %lx\n", bestfreq);
/* Modify DIU_DIV in CCM SCFR1 */
temp = in_be32(&ccm->scfr1);
pr_debug("DIU: Current value of SCFR1: 0x%08x\n", temp);
temp &= ~DIU_DIV_MASK;
temp |= (bestval & DIU_DIV_MASK);
out_be32(&ccm->scfr1, temp);
pr_debug("DIU: Modified value of SCFR1: 0x%08x\n", temp);
iounmap(ccm);
}
enum fsl_diu_monitor_port
mpc512x_valid_monitor_port(enum fsl_diu_monitor_port port)
{
return FSL_DIU_PORT_DVI;
}
static struct fsl_diu_shared_fb __attribute__ ((__aligned__(8))) diu_shared_fb;
#if defined(CONFIG_FB_FSL_DIU) || \
defined(CONFIG_FB_FSL_DIU_MODULE)
static inline void mpc512x_free_bootmem(struct page *page)
{
__ClearPageReserved(page);
BUG_ON(PageTail(page));
BUG_ON(atomic_read(&page->_count) > 1);
atomic_set(&page->_count, 1);
__free_page(page);
totalram_pages++;
}
void mpc512x_release_bootmem(void)
{
unsigned long addr = diu_shared_fb.fb_phys & PAGE_MASK;
unsigned long size = diu_shared_fb.fb_len;
unsigned long start, end;
if (diu_shared_fb.in_use) {
start = PFN_UP(addr);
end = PFN_DOWN(addr + size);
for (; start < end; start++)
mpc512x_free_bootmem(pfn_to_page(start));
diu_shared_fb.in_use = false;
}
diu_ops.release_bootmem = NULL;
}
#endif
/*
* Check if DIU was pre-initialized. If so, perform steps
* needed to continue displaying through the whole boot process.
* Move area descriptor and gamma table elsewhere, they are
* destroyed by bootmem allocator otherwise. The frame buffer
* address range will be reserved in setup_arch() after bootmem
* allocator is up.
*/
void __init mpc512x_init_diu(void)
{
struct device_node *np;
struct diu __iomem *diu_reg;
phys_addr_t desc;
void __iomem *vaddr;
unsigned long mode, pix_fmt, res, bpp;
unsigned long dst;
np = of_find_compatible_node(NULL, NULL, "fsl,mpc5121-diu");
if (!np) {
pr_err("No DIU node\n");
return;
}
diu_reg = of_iomap(np, 0);
of_node_put(np);
if (!diu_reg) {
pr_err("Can't map DIU\n");
return;
}
mode = in_be32(&diu_reg->diu_mode);
if (mode == MFB_MODE0) {
pr_info("%s: DIU OFF\n", __func__);
goto out;
}
desc = in_be32(&diu_reg->desc[0]);
vaddr = ioremap(desc, sizeof(struct diu_ad));
if (!vaddr) {
pr_err("Can't map DIU area desc.\n");
goto out;
}
memcpy(&diu_shared_fb.ad0, vaddr, sizeof(struct diu_ad));
/* flush fb area descriptor */
dst = (unsigned long)&diu_shared_fb.ad0;
flush_dcache_range(dst, dst + sizeof(struct diu_ad) - 1);
res = in_be32(&diu_reg->disp_size);
pix_fmt = in_le32(vaddr);
bpp = ((pix_fmt >> 16) & 0x3) + 1;
diu_shared_fb.fb_phys = in_le32(vaddr + 4);
diu_shared_fb.fb_len = ((res & 0xfff0000) >> 16) * (res & 0xfff) * bpp;
diu_shared_fb.in_use = true;
iounmap(vaddr);
desc = in_be32(&diu_reg->gamma);
vaddr = ioremap(desc, sizeof(diu_shared_fb.gamma));
if (!vaddr) {
pr_err("Can't map DIU area desc.\n");
diu_shared_fb.in_use = false;
goto out;
}
memcpy(&diu_shared_fb.gamma, vaddr, sizeof(diu_shared_fb.gamma));
/* flush gamma table */
dst = (unsigned long)&diu_shared_fb.gamma;
flush_dcache_range(dst, dst + sizeof(diu_shared_fb.gamma) - 1);
iounmap(vaddr);
out_be32(&diu_reg->gamma, virt_to_phys(&diu_shared_fb.gamma));
out_be32(&diu_reg->desc[1], 0);
out_be32(&diu_reg->desc[2], 0);
out_be32(&diu_reg->desc[0], virt_to_phys(&diu_shared_fb.ad0));
out:
iounmap(diu_reg);
}
void __init mpc512x_setup_diu(void)
{
int ret;
/*
* We do not allocate and configure new area for bitmap buffer
* because it would requere copying bitmap data (splash image)
* and so negatively affect boot time. Instead we reserve the
* already configured frame buffer area so that it won't be
* destroyed. The starting address of the area to reserve and
* also it's length is passed to reserve_bootmem(). It will be
* freed later on first open of fbdev, when splash image is not
* needed any more.
*/
if (diu_shared_fb.in_use) {
ret = reserve_bootmem(diu_shared_fb.fb_phys,
diu_shared_fb.fb_len,
BOOTMEM_EXCLUSIVE);
if (ret) {
pr_err("%s: reserve bootmem failed\n", __func__);
diu_shared_fb.in_use = false;
}
}
#if defined(CONFIG_FB_FSL_DIU) || \
defined(CONFIG_FB_FSL_DIU_MODULE)
diu_ops.get_pixel_format = mpc512x_get_pixel_format;
diu_ops.set_gamma_table = mpc512x_set_gamma_table;
diu_ops.set_monitor_port = mpc512x_set_monitor_port;
diu_ops.set_pixel_clock = mpc512x_set_pixel_clock;
diu_ops.valid_monitor_port = mpc512x_valid_monitor_port;
diu_ops.release_bootmem = mpc512x_release_bootmem;
#endif
}
void __init mpc512x_init_IRQ(void)
{
struct device_node *np;
np = of_find_compatible_node(NULL, NULL, "fsl,mpc5121-ipic");
if (!np)
return;
ipic_init(np, 0);
of_node_put(np);
/*
* Initialize the default interrupt mapping priorities,
* in case the boot rom changed something on us.
*/
ipic_set_default_priority();
}
/*
* Nodes to do bus probe on, soc and localbus
*/
static struct of_device_id __initdata of_bus_ids[] = {
{ .compatible = "fsl,mpc5121-immr", },
{ .compatible = "fsl,mpc5121-localbus", },
{},
};
void __init mpc512x_declare_of_platform_devices(void)
{
struct device_node *np;
if (of_platform_bus_probe(NULL, of_bus_ids, NULL))
printk(KERN_ERR __FILE__ ": "
"Error while probing of_platform bus\n");
np = of_find_compatible_node(NULL, NULL, "fsl,mpc5121-nfc");
if (np) {
of_platform_device_create(np, NULL, NULL);
of_node_put(np);
}
}
#define DEFAULT_FIFO_SIZE 16
static unsigned int __init get_fifo_size(struct device_node *np,
char *prop_name)
{
const unsigned int *fp;
fp = of_get_property(np, prop_name, NULL);
if (fp)
return *fp;
pr_warning("no %s property in %s node, defaulting to %d\n",
prop_name, np->full_name, DEFAULT_FIFO_SIZE);
return DEFAULT_FIFO_SIZE;
}
#define FIFOC(_base) ((struct mpc512x_psc_fifo __iomem *) \
((u32)(_base) + sizeof(struct mpc52xx_psc)))
/* Init PSC FIFO space for TX and RX slices */
void __init mpc512x_psc_fifo_init(void)
{
struct device_node *np;
void __iomem *psc;
unsigned int tx_fifo_size;
unsigned int rx_fifo_size;
int fifobase = 0; /* current fifo address in 32 bit words */
for_each_compatible_node(np, NULL, "fsl,mpc5121-psc") {
tx_fifo_size = get_fifo_size(np, "fsl,tx-fifo-size");
rx_fifo_size = get_fifo_size(np, "fsl,rx-fifo-size");
/* size in register is in 4 byte units */
tx_fifo_size /= 4;
rx_fifo_size /= 4;
if (!tx_fifo_size)
tx_fifo_size = 1;
if (!rx_fifo_size)
rx_fifo_size = 1;
psc = of_iomap(np, 0);
if (!psc) {
pr_err("%s: Can't map %s device\n",
__func__, np->full_name);
continue;
}
/* FIFO space is 4KiB, check if requested size is available */
if ((fifobase + tx_fifo_size + rx_fifo_size) > 0x1000) {
pr_err("%s: no fifo space available for %s\n",
__func__, np->full_name);
iounmap(psc);
/*
* chances are that another device requests less
* fifo space, so we continue.
*/
continue;
}
/* set tx and rx fifo size registers */
out_be32(&FIFOC(psc)->txsz, (fifobase << 16) | tx_fifo_size);
fifobase += tx_fifo_size;
out_be32(&FIFOC(psc)->rxsz, (fifobase << 16) | rx_fifo_size);
fifobase += rx_fifo_size;
/* reset and enable the slices */
out_be32(&FIFOC(psc)->txcmd, 0x80);
out_be32(&FIFOC(psc)->txcmd, 0x01);
out_be32(&FIFOC(psc)->rxcmd, 0x80);
out_be32(&FIFOC(psc)->rxcmd, 0x01);
iounmap(psc);
}
}
void __init mpc512x_init(void)
{
mpc512x_declare_of_platform_devices();
mpc5121_clk_init();
mpc512x_restart_init();
mpc512x_psc_fifo_init();
}
| gpl-2.0 |
michaelspeed/EntityMobile_hammerhead_kernel | net/tipc/discover.c | 4805 | 11748 | /*
* net/tipc/discover.c
*
* Copyright (c) 2003-2006, Ericsson AB
* Copyright (c) 2005-2006, 2010-2011, 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"
#include "link.h"
#include "discover.h"
#define TIPC_LINK_REQ_INIT 125 /* min delay during bearer start up */
#define TIPC_LINK_REQ_FAST 1000 /* max delay if bearer has no links */
#define TIPC_LINK_REQ_SLOW 60000 /* max delay if bearer has links */
#define TIPC_LINK_REQ_INACTIVE 0xffffffff /* indicates no timer in use */
/**
* struct tipc_link_req - information about an ongoing link setup request
* @bearer: bearer issuing requests
* @dest: destination address for request messages
* @domain: network domain to which links can be established
* @num_nodes: number of nodes currently discovered (i.e. with an active link)
* @buf: request message to be (repeatedly) sent
* @timer: timer governing period between requests
* @timer_intv: current interval between requests (in ms)
*/
struct tipc_link_req {
struct tipc_bearer *bearer;
struct tipc_media_addr dest;
u32 domain;
int num_nodes;
struct sk_buff *buf;
struct timer_list timer;
unsigned int timer_intv;
};
/**
* tipc_disc_init_msg - initialize a link setup message
* @type: message type (request or response)
* @dest_domain: network domain of node(s) which should respond to message
* @b_ptr: ptr to bearer issuing message
*/
static struct sk_buff *tipc_disc_init_msg(u32 type,
u32 dest_domain,
struct tipc_bearer *b_ptr)
{
struct sk_buff *buf = tipc_buf_acquire(INT_H_SIZE);
struct tipc_msg *msg;
if (buf) {
msg = buf_msg(buf);
tipc_msg_init(msg, LINK_CONFIG, type, INT_H_SIZE, dest_domain);
msg_set_non_seq(msg, 1);
msg_set_node_sig(msg, tipc_random);
msg_set_dest_domain(msg, dest_domain);
msg_set_bc_netid(msg, tipc_net_id);
b_ptr->media->addr2msg(&b_ptr->addr, msg_media_addr(msg));
}
return buf;
}
/**
* disc_dupl_alert - issue node address duplication alert
* @b_ptr: pointer to bearer detecting duplication
* @node_addr: duplicated node address
* @media_addr: media address advertised by duplicated node
*/
static void disc_dupl_alert(struct tipc_bearer *b_ptr, u32 node_addr,
struct tipc_media_addr *media_addr)
{
char node_addr_str[16];
char media_addr_str[64];
struct print_buf pb;
tipc_addr_string_fill(node_addr_str, node_addr);
tipc_printbuf_init(&pb, media_addr_str, sizeof(media_addr_str));
tipc_media_addr_printf(&pb, media_addr);
tipc_printbuf_validate(&pb);
warn("Duplicate %s using %s seen on <%s>\n",
node_addr_str, media_addr_str, b_ptr->name);
}
/**
* tipc_disc_recv_msg - handle incoming link setup message (request or response)
* @buf: buffer containing message
* @b_ptr: bearer that message arrived on
*/
void tipc_disc_recv_msg(struct sk_buff *buf, struct tipc_bearer *b_ptr)
{
struct tipc_node *n_ptr;
struct tipc_link *link;
struct tipc_media_addr media_addr;
struct sk_buff *rbuf;
struct tipc_msg *msg = buf_msg(buf);
u32 dest = msg_dest_domain(msg);
u32 orig = msg_prevnode(msg);
u32 net_id = msg_bc_netid(msg);
u32 type = msg_type(msg);
u32 signature = msg_node_sig(msg);
int addr_mismatch;
int link_fully_up;
media_addr.broadcast = 1;
b_ptr->media->msg2addr(&media_addr, msg_media_addr(msg));
kfree_skb(buf);
/* Ensure message from node is valid and communication is permitted */
if (net_id != tipc_net_id)
return;
if (media_addr.broadcast)
return;
if (!tipc_addr_domain_valid(dest))
return;
if (!tipc_addr_node_valid(orig))
return;
if (orig == tipc_own_addr) {
if (memcmp(&media_addr, &b_ptr->addr, sizeof(media_addr)))
disc_dupl_alert(b_ptr, tipc_own_addr, &media_addr);
return;
}
if (!tipc_in_scope(dest, tipc_own_addr))
return;
if (!tipc_in_scope(b_ptr->link_req->domain, orig))
return;
/* Locate structure corresponding to requesting node */
n_ptr = tipc_node_find(orig);
if (!n_ptr) {
n_ptr = tipc_node_create(orig);
if (!n_ptr)
return;
}
tipc_node_lock(n_ptr);
/* Prepare to validate requesting node's signature and media address */
link = n_ptr->links[b_ptr->identity];
addr_mismatch = (link != NULL) &&
memcmp(&link->media_addr, &media_addr, sizeof(media_addr));
/*
* Ensure discovery message's signature is correct
*
* If signature is incorrect and there is no working link to the node,
* accept the new signature but invalidate all existing links to the
* node so they won't re-activate without a new discovery message.
*
* If signature is incorrect and the requested link to the node is
* working, accept the new signature. (This is an instance of delayed
* rediscovery, where a link endpoint was able to re-establish contact
* with its peer endpoint on a node that rebooted before receiving a
* discovery message from that node.)
*
* If signature is incorrect and there is a working link to the node
* that is not the requested link, reject the request (must be from
* a duplicate node).
*/
if (signature != n_ptr->signature) {
if (n_ptr->working_links == 0) {
struct tipc_link *curr_link;
int i;
for (i = 0; i < MAX_BEARERS; i++) {
curr_link = n_ptr->links[i];
if (curr_link) {
memset(&curr_link->media_addr, 0,
sizeof(media_addr));
tipc_link_reset(curr_link);
}
}
addr_mismatch = (link != NULL);
} else if (tipc_link_is_up(link) && !addr_mismatch) {
/* delayed rediscovery */
} else {
disc_dupl_alert(b_ptr, orig, &media_addr);
tipc_node_unlock(n_ptr);
return;
}
n_ptr->signature = signature;
}
/*
* Ensure requesting node's media address is correct
*
* If media address doesn't match and the link is working, reject the
* request (must be from a duplicate node).
*
* If media address doesn't match and the link is not working, accept
* the new media address and reset the link to ensure it starts up
* cleanly.
*/
if (addr_mismatch) {
if (tipc_link_is_up(link)) {
disc_dupl_alert(b_ptr, orig, &media_addr);
tipc_node_unlock(n_ptr);
return;
} else {
memcpy(&link->media_addr, &media_addr,
sizeof(media_addr));
tipc_link_reset(link);
}
}
/* Create a link endpoint for this bearer, if necessary */
if (!link) {
link = tipc_link_create(n_ptr, b_ptr, &media_addr);
if (!link) {
tipc_node_unlock(n_ptr);
return;
}
}
/* Accept discovery message & send response, if necessary */
link_fully_up = link_working_working(link);
if ((type == DSC_REQ_MSG) && !link_fully_up && !b_ptr->blocked) {
rbuf = tipc_disc_init_msg(DSC_RESP_MSG, orig, b_ptr);
if (rbuf) {
b_ptr->media->send_msg(rbuf, b_ptr, &media_addr);
kfree_skb(rbuf);
}
}
tipc_node_unlock(n_ptr);
}
/**
* disc_update - update frequency of periodic link setup requests
* @req: ptr to link request structure
*
* Reinitiates discovery process if discovery object has no associated nodes
* and is either not currently searching or is searching at a slow rate
*/
static void disc_update(struct tipc_link_req *req)
{
if (!req->num_nodes) {
if ((req->timer_intv == TIPC_LINK_REQ_INACTIVE) ||
(req->timer_intv > TIPC_LINK_REQ_FAST)) {
req->timer_intv = TIPC_LINK_REQ_INIT;
k_start_timer(&req->timer, req->timer_intv);
}
}
}
/**
* tipc_disc_add_dest - increment set of discovered nodes
* @req: ptr to link request structure
*/
void tipc_disc_add_dest(struct tipc_link_req *req)
{
req->num_nodes++;
}
/**
* tipc_disc_remove_dest - decrement set of discovered nodes
* @req: ptr to link request structure
*/
void tipc_disc_remove_dest(struct tipc_link_req *req)
{
req->num_nodes--;
disc_update(req);
}
/**
* disc_send_msg - send link setup request message
* @req: ptr to link request structure
*/
static void disc_send_msg(struct tipc_link_req *req)
{
if (!req->bearer->blocked)
tipc_bearer_send(req->bearer, req->buf, &req->dest);
}
/**
* disc_timeout - send a periodic link setup request
* @req: ptr to link request structure
*
* Called whenever a link setup request timer associated with a bearer expires.
*/
static void disc_timeout(struct tipc_link_req *req)
{
int max_delay;
spin_lock_bh(&req->bearer->lock);
/* Stop searching if only desired node has been found */
if (tipc_node(req->domain) && req->num_nodes) {
req->timer_intv = TIPC_LINK_REQ_INACTIVE;
goto exit;
}
/*
* Send discovery message, then update discovery timer
*
* Keep doubling time between requests until limit is reached;
* hold at fast polling rate if don't have any associated nodes,
* otherwise hold at slow polling rate
*/
disc_send_msg(req);
req->timer_intv *= 2;
if (req->num_nodes)
max_delay = TIPC_LINK_REQ_SLOW;
else
max_delay = TIPC_LINK_REQ_FAST;
if (req->timer_intv > max_delay)
req->timer_intv = max_delay;
k_start_timer(&req->timer, req->timer_intv);
exit:
spin_unlock_bh(&req->bearer->lock);
}
/**
* tipc_disc_create - create object to send periodic link setup requests
* @b_ptr: ptr to bearer issuing requests
* @dest: destination address for request messages
* @dest_domain: network domain to which links can be established
*
* Returns 0 if successful, otherwise -errno.
*/
int tipc_disc_create(struct tipc_bearer *b_ptr,
struct tipc_media_addr *dest, u32 dest_domain)
{
struct tipc_link_req *req;
req = kmalloc(sizeof(*req), GFP_ATOMIC);
if (!req)
return -ENOMEM;
req->buf = tipc_disc_init_msg(DSC_REQ_MSG, dest_domain, b_ptr);
if (!req->buf) {
kfree(req);
return -ENOMSG;
}
memcpy(&req->dest, dest, sizeof(*dest));
req->bearer = b_ptr;
req->domain = dest_domain;
req->num_nodes = 0;
req->timer_intv = TIPC_LINK_REQ_INIT;
k_init_timer(&req->timer, (Handler)disc_timeout, (unsigned long)req);
k_start_timer(&req->timer, req->timer_intv);
b_ptr->link_req = req;
disc_send_msg(req);
return 0;
}
/**
* tipc_disc_delete - destroy object sending periodic link setup requests
* @req: ptr to link request structure
*/
void tipc_disc_delete(struct tipc_link_req *req)
{
k_cancel_timer(&req->timer);
k_term_timer(&req->timer);
kfree_skb(req->buf);
kfree(req);
}
| gpl-2.0 |
Team-SennyC2/senny_kernel-3.4 | drivers/net/ethernet/smsc/epic100.c | 4805 | 46126 | /* epic100.c: A SMC 83c170 EPIC/100 Fast Ethernet driver for Linux. */
/*
Written/copyright 1997-2001 by Donald Becker.
This software may be used and distributed according to the terms of
the GNU General Public License (GPL), incorporated herein by reference.
Drivers based on or derived from this code fall under the GPL and must
retain the authorship, copyright and license notice. This file is not
a complete program and may only be used when the entire operating
system is licensed under the GPL.
This driver is for the SMC83c170/175 "EPIC" series, as used on the
SMC EtherPower II 9432 PCI adapter, and several CardBus cards.
The author may be reached as becker@scyld.com, or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
Information and updates available at
http://www.scyld.com/network/epic100.html
[this link no longer provides anything useful -jgarzik]
---------------------------------------------------------------------
*/
#define DRV_NAME "epic100"
#define DRV_VERSION "2.1"
#define DRV_RELDATE "Sept 11, 2006"
/* The user-configurable values.
These may be modified when a driver module is loaded.*/
static int debug = 1; /* 1 normal messages, 0 quiet .. 7 verbose. */
/* Used to pass the full-duplex flag, etc. */
#define MAX_UNITS 8 /* More are supported, limit only on options */
static int options[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
/* Set the copy breakpoint for the copy-only-tiny-frames scheme.
Setting to > 1518 effectively disables this feature. */
static int rx_copybreak;
/* Operational parameters that are set at compile time. */
/* Keep the ring sizes a power of two for operational efficiency.
The compiler will convert <unsigned>'%'<2^N> into a bit mask.
Making the Tx ring too large decreases the effectiveness of channel
bonding and packet priority.
There are no ill effects from too-large receive rings. */
#define TX_RING_SIZE 256
#define TX_QUEUE_LEN 240 /* Limit ring entries actually used. */
#define RX_RING_SIZE 256
#define TX_TOTAL_SIZE TX_RING_SIZE*sizeof(struct epic_tx_desc)
#define RX_TOTAL_SIZE RX_RING_SIZE*sizeof(struct epic_rx_desc)
/* Operational parameters that usually are not changed. */
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT (2*HZ)
#define PKT_BUF_SZ 1536 /* Size of each temporary Rx buffer.*/
/* Bytes transferred to chip before transmission starts. */
/* Initial threshold, increased on underflow, rounded down to 4 byte units. */
#define TX_FIFO_THRESH 256
#define RX_FIFO_THRESH 1 /* 0-3, 0==32, 64,96, or 3==128 bytes */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/crc32.h>
#include <linux/bitops.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/byteorder.h>
/* These identify the driver base version and may not be removed. */
static char version[] __devinitdata =
DRV_NAME ".c:v1.11 1/7/2001 Written by Donald Becker <becker@scyld.com>\n";
static char version2[] __devinitdata =
" (unofficial 2.4.x kernel port, version " DRV_VERSION ", " DRV_RELDATE ")\n";
MODULE_AUTHOR("Donald Becker <becker@scyld.com>");
MODULE_DESCRIPTION("SMC 83c170 EPIC series Ethernet driver");
MODULE_LICENSE("GPL");
module_param(debug, int, 0);
module_param(rx_copybreak, int, 0);
module_param_array(options, int, NULL, 0);
module_param_array(full_duplex, int, NULL, 0);
MODULE_PARM_DESC(debug, "EPIC/100 debug level (0-5)");
MODULE_PARM_DESC(options, "EPIC/100: Bits 0-3: media type, bit 4: full duplex");
MODULE_PARM_DESC(rx_copybreak, "EPIC/100 copy breakpoint for copy-only-tiny-frames");
MODULE_PARM_DESC(full_duplex, "EPIC/100 full duplex setting(s) (1)");
/*
Theory of Operation
I. Board Compatibility
This device driver is designed for the SMC "EPIC/100", the SMC
single-chip Ethernet controllers for PCI. This chip is used on
the SMC EtherPower II boards.
II. Board-specific settings
PCI bus devices are configured by the system at boot time, so no jumpers
need to be set on the board. The system BIOS will assign the
PCI INTA signal to a (preferably otherwise unused) system IRQ line.
Note: Kernel versions earlier than 1.3.73 do not support shared PCI
interrupt lines.
III. Driver operation
IIIa. Ring buffers
IVb. References
http://www.smsc.com/media/Downloads_Public/discontinued/83c171.pdf
http://www.smsc.com/media/Downloads_Public/discontinued/83c175.pdf
http://scyld.com/expert/NWay.html
http://www.national.com/pf/DP/DP83840A.html
IVc. Errata
*/
enum chip_capability_flags { MII_PWRDWN=1, TYPE2_INTR=2, NO_MII=4 };
#define EPIC_TOTAL_SIZE 0x100
#define USE_IO_OPS 1
typedef enum {
SMSC_83C170_0,
SMSC_83C170,
SMSC_83C175,
} chip_t;
struct epic_chip_info {
const char *name;
int drv_flags; /* Driver use, intended as capability flags. */
};
/* indexed by chip_t */
static const struct epic_chip_info pci_id_tbl[] = {
{ "SMSC EPIC/100 83c170", TYPE2_INTR | NO_MII | MII_PWRDWN },
{ "SMSC EPIC/100 83c170", TYPE2_INTR },
{ "SMSC EPIC/C 83c175", TYPE2_INTR | MII_PWRDWN },
};
static DEFINE_PCI_DEVICE_TABLE(epic_pci_tbl) = {
{ 0x10B8, 0x0005, 0x1092, 0x0AB4, 0, 0, SMSC_83C170_0 },
{ 0x10B8, 0x0005, PCI_ANY_ID, PCI_ANY_ID, 0, 0, SMSC_83C170 },
{ 0x10B8, 0x0006, PCI_ANY_ID, PCI_ANY_ID,
PCI_CLASS_NETWORK_ETHERNET << 8, 0xffff00, SMSC_83C175 },
{ 0,}
};
MODULE_DEVICE_TABLE (pci, epic_pci_tbl);
#ifndef USE_IO_OPS
#undef inb
#undef inw
#undef inl
#undef outb
#undef outw
#undef outl
#define inb readb
#define inw readw
#define inl readl
#define outb writeb
#define outw writew
#define outl writel
#endif
/* Offsets to registers, using the (ugh) SMC names. */
enum epic_registers {
COMMAND=0, INTSTAT=4, INTMASK=8, GENCTL=0x0C, NVCTL=0x10, EECTL=0x14,
PCIBurstCnt=0x18,
TEST1=0x1C, CRCCNT=0x20, ALICNT=0x24, MPCNT=0x28, /* Rx error counters. */
MIICtrl=0x30, MIIData=0x34, MIICfg=0x38,
LAN0=64, /* MAC address. */
MC0=80, /* Multicast filter table. */
RxCtrl=96, TxCtrl=112, TxSTAT=0x74,
PRxCDAR=0x84, RxSTAT=0xA4, EarlyRx=0xB0, PTxCDAR=0xC4, TxThresh=0xDC,
};
/* Interrupt register bits, using my own meaningful names. */
enum IntrStatus {
TxIdle=0x40000, RxIdle=0x20000, IntrSummary=0x010000,
PCIBusErr170=0x7000, PCIBusErr175=0x1000, PhyEvent175=0x8000,
RxStarted=0x0800, RxEarlyWarn=0x0400, CntFull=0x0200, TxUnderrun=0x0100,
TxEmpty=0x0080, TxDone=0x0020, RxError=0x0010,
RxOverflow=0x0008, RxFull=0x0004, RxHeader=0x0002, RxDone=0x0001,
};
enum CommandBits {
StopRx=1, StartRx=2, TxQueued=4, RxQueued=8,
StopTxDMA=0x20, StopRxDMA=0x40, RestartTx=0x80,
};
#define EpicRemoved 0xffffffff /* Chip failed or removed (CardBus) */
#define EpicNapiEvent (TxEmpty | TxDone | \
RxDone | RxStarted | RxEarlyWarn | RxOverflow | RxFull)
#define EpicNormalEvent (0x0000ffff & ~EpicNapiEvent)
static const u16 media2miictl[16] = {
0, 0x0C00, 0x0C00, 0x2000, 0x0100, 0x2100, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 };
/*
* The EPIC100 Rx and Tx buffer descriptors. Note that these
* really ARE host-endian; it's not a misannotation. We tell
* the card to byteswap them internally on big-endian hosts -
* look for #ifdef __BIG_ENDIAN in epic_open().
*/
struct epic_tx_desc {
u32 txstatus;
u32 bufaddr;
u32 buflength;
u32 next;
};
struct epic_rx_desc {
u32 rxstatus;
u32 bufaddr;
u32 buflength;
u32 next;
};
enum desc_status_bits {
DescOwn=0x8000,
};
#define PRIV_ALIGN 15 /* Required alignment mask */
struct epic_private {
struct epic_rx_desc *rx_ring;
struct epic_tx_desc *tx_ring;
/* The saved address of a sent-in-place packet/buffer, for skfree(). */
struct sk_buff* tx_skbuff[TX_RING_SIZE];
/* The addresses of receive-in-place skbuffs. */
struct sk_buff* rx_skbuff[RX_RING_SIZE];
dma_addr_t tx_ring_dma;
dma_addr_t rx_ring_dma;
/* Ring pointers. */
spinlock_t lock; /* Group with Tx control cache line. */
spinlock_t napi_lock;
struct napi_struct napi;
unsigned int reschedule_in_poll;
unsigned int cur_tx, dirty_tx;
unsigned int cur_rx, dirty_rx;
u32 irq_mask;
unsigned int rx_buf_sz; /* Based on MTU+slack. */
struct pci_dev *pci_dev; /* PCI bus location. */
int chip_id, chip_flags;
struct timer_list timer; /* Media selection timer. */
int tx_threshold;
unsigned char mc_filter[8];
signed char phys[4]; /* MII device addresses. */
u16 advertising; /* NWay media advertisement */
int mii_phy_cnt;
struct mii_if_info mii;
unsigned int tx_full:1; /* The Tx queue is full. */
unsigned int default_port:4; /* Last dev->if_port value. */
};
static int epic_open(struct net_device *dev);
static int read_eeprom(long ioaddr, int location);
static int mdio_read(struct net_device *dev, int phy_id, int location);
static void mdio_write(struct net_device *dev, int phy_id, int loc, int val);
static void epic_restart(struct net_device *dev);
static void epic_timer(unsigned long data);
static void epic_tx_timeout(struct net_device *dev);
static void epic_init_ring(struct net_device *dev);
static netdev_tx_t epic_start_xmit(struct sk_buff *skb,
struct net_device *dev);
static int epic_rx(struct net_device *dev, int budget);
static int epic_poll(struct napi_struct *napi, int budget);
static irqreturn_t epic_interrupt(int irq, void *dev_instance);
static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static const struct ethtool_ops netdev_ethtool_ops;
static int epic_close(struct net_device *dev);
static struct net_device_stats *epic_get_stats(struct net_device *dev);
static void set_rx_mode(struct net_device *dev);
static const struct net_device_ops epic_netdev_ops = {
.ndo_open = epic_open,
.ndo_stop = epic_close,
.ndo_start_xmit = epic_start_xmit,
.ndo_tx_timeout = epic_tx_timeout,
.ndo_get_stats = epic_get_stats,
.ndo_set_rx_mode = set_rx_mode,
.ndo_do_ioctl = netdev_ioctl,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static int __devinit epic_init_one (struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static int card_idx = -1;
long ioaddr;
int chip_idx = (int) ent->driver_data;
int irq;
struct net_device *dev;
struct epic_private *ep;
int i, ret, option = 0, duplex = 0;
void *ring_space;
dma_addr_t ring_dma;
/* when built into the kernel, we only print version if device is found */
#ifndef MODULE
static int printed_version;
if (!printed_version++)
printk(KERN_INFO "%s%s", version, version2);
#endif
card_idx++;
ret = pci_enable_device(pdev);
if (ret)
goto out;
irq = pdev->irq;
if (pci_resource_len(pdev, 0) < EPIC_TOTAL_SIZE) {
dev_err(&pdev->dev, "no PCI region space\n");
ret = -ENODEV;
goto err_out_disable;
}
pci_set_master(pdev);
ret = pci_request_regions(pdev, DRV_NAME);
if (ret < 0)
goto err_out_disable;
ret = -ENOMEM;
dev = alloc_etherdev(sizeof (*ep));
if (!dev)
goto err_out_free_res;
SET_NETDEV_DEV(dev, &pdev->dev);
#ifdef USE_IO_OPS
ioaddr = pci_resource_start (pdev, 0);
#else
ioaddr = pci_resource_start (pdev, 1);
ioaddr = (long) pci_ioremap_bar(pdev, 1);
if (!ioaddr) {
dev_err(&pdev->dev, "ioremap failed\n");
goto err_out_free_netdev;
}
#endif
pci_set_drvdata(pdev, dev);
ep = netdev_priv(dev);
ep->mii.dev = dev;
ep->mii.mdio_read = mdio_read;
ep->mii.mdio_write = mdio_write;
ep->mii.phy_id_mask = 0x1f;
ep->mii.reg_num_mask = 0x1f;
ring_space = pci_alloc_consistent(pdev, TX_TOTAL_SIZE, &ring_dma);
if (!ring_space)
goto err_out_iounmap;
ep->tx_ring = ring_space;
ep->tx_ring_dma = ring_dma;
ring_space = pci_alloc_consistent(pdev, RX_TOTAL_SIZE, &ring_dma);
if (!ring_space)
goto err_out_unmap_tx;
ep->rx_ring = ring_space;
ep->rx_ring_dma = ring_dma;
if (dev->mem_start) {
option = dev->mem_start;
duplex = (dev->mem_start & 16) ? 1 : 0;
} else if (card_idx >= 0 && card_idx < MAX_UNITS) {
if (options[card_idx] >= 0)
option = options[card_idx];
if (full_duplex[card_idx] >= 0)
duplex = full_duplex[card_idx];
}
dev->base_addr = ioaddr;
dev->irq = irq;
spin_lock_init(&ep->lock);
spin_lock_init(&ep->napi_lock);
ep->reschedule_in_poll = 0;
/* Bring the chip out of low-power mode. */
outl(0x4200, ioaddr + GENCTL);
/* Magic?! If we don't set this bit the MII interface won't work. */
/* This magic is documented in SMSC app note 7.15 */
for (i = 16; i > 0; i--)
outl(0x0008, ioaddr + TEST1);
/* Turn on the MII transceiver. */
outl(0x12, ioaddr + MIICfg);
if (chip_idx == 1)
outl((inl(ioaddr + NVCTL) & ~0x003C) | 0x4800, ioaddr + NVCTL);
outl(0x0200, ioaddr + GENCTL);
/* Note: the '175 does not have a serial EEPROM. */
for (i = 0; i < 3; i++)
((__le16 *)dev->dev_addr)[i] = cpu_to_le16(inw(ioaddr + LAN0 + i*4));
if (debug > 2) {
dev_printk(KERN_DEBUG, &pdev->dev, "EEPROM contents:\n");
for (i = 0; i < 64; i++)
printk(" %4.4x%s", read_eeprom(ioaddr, i),
i % 16 == 15 ? "\n" : "");
}
ep->pci_dev = pdev;
ep->chip_id = chip_idx;
ep->chip_flags = pci_id_tbl[chip_idx].drv_flags;
ep->irq_mask =
(ep->chip_flags & TYPE2_INTR ? PCIBusErr175 : PCIBusErr170)
| CntFull | TxUnderrun | EpicNapiEvent;
/* Find the connected MII xcvrs.
Doing this in open() would allow detecting external xcvrs later, but
takes much time and no cards have external MII. */
{
int phy, phy_idx = 0;
for (phy = 1; phy < 32 && phy_idx < sizeof(ep->phys); phy++) {
int mii_status = mdio_read(dev, phy, MII_BMSR);
if (mii_status != 0xffff && mii_status != 0x0000) {
ep->phys[phy_idx++] = phy;
dev_info(&pdev->dev,
"MII transceiver #%d control "
"%4.4x status %4.4x.\n",
phy, mdio_read(dev, phy, 0), mii_status);
}
}
ep->mii_phy_cnt = phy_idx;
if (phy_idx != 0) {
phy = ep->phys[0];
ep->mii.advertising = mdio_read(dev, phy, MII_ADVERTISE);
dev_info(&pdev->dev,
"Autonegotiation advertising %4.4x link "
"partner %4.4x.\n",
ep->mii.advertising, mdio_read(dev, phy, 5));
} else if ( ! (ep->chip_flags & NO_MII)) {
dev_warn(&pdev->dev,
"***WARNING***: No MII transceiver found!\n");
/* Use the known PHY address of the EPII. */
ep->phys[0] = 3;
}
ep->mii.phy_id = ep->phys[0];
}
/* Turn off the MII xcvr (175 only!), leave the chip in low-power mode. */
if (ep->chip_flags & MII_PWRDWN)
outl(inl(ioaddr + NVCTL) & ~0x483C, ioaddr + NVCTL);
outl(0x0008, ioaddr + GENCTL);
/* The lower four bits are the media type. */
if (duplex) {
ep->mii.force_media = ep->mii.full_duplex = 1;
dev_info(&pdev->dev, "Forced full duplex requested.\n");
}
dev->if_port = ep->default_port = option;
/* The Epic-specific entries in the device structure. */
dev->netdev_ops = &epic_netdev_ops;
dev->ethtool_ops = &netdev_ethtool_ops;
dev->watchdog_timeo = TX_TIMEOUT;
netif_napi_add(dev, &ep->napi, epic_poll, 64);
ret = register_netdev(dev);
if (ret < 0)
goto err_out_unmap_rx;
printk(KERN_INFO "%s: %s at %#lx, IRQ %d, %pM\n",
dev->name, pci_id_tbl[chip_idx].name, ioaddr, dev->irq,
dev->dev_addr);
out:
return ret;
err_out_unmap_rx:
pci_free_consistent(pdev, RX_TOTAL_SIZE, ep->rx_ring, ep->rx_ring_dma);
err_out_unmap_tx:
pci_free_consistent(pdev, TX_TOTAL_SIZE, ep->tx_ring, ep->tx_ring_dma);
err_out_iounmap:
#ifndef USE_IO_OPS
iounmap(ioaddr);
err_out_free_netdev:
#endif
free_netdev(dev);
err_out_free_res:
pci_release_regions(pdev);
err_out_disable:
pci_disable_device(pdev);
goto out;
}
/* Serial EEPROM section. */
/* EEPROM_Ctrl bits. */
#define EE_SHIFT_CLK 0x04 /* EEPROM shift clock. */
#define EE_CS 0x02 /* EEPROM chip select. */
#define EE_DATA_WRITE 0x08 /* EEPROM chip data in. */
#define EE_WRITE_0 0x01
#define EE_WRITE_1 0x09
#define EE_DATA_READ 0x10 /* EEPROM chip data out. */
#define EE_ENB (0x0001 | EE_CS)
/* Delay between EEPROM clock transitions.
This serves to flush the operation to the PCI bus.
*/
#define eeprom_delay() inl(ee_addr)
/* The EEPROM commands include the alway-set leading bit. */
#define EE_WRITE_CMD (5 << 6)
#define EE_READ64_CMD (6 << 6)
#define EE_READ256_CMD (6 << 8)
#define EE_ERASE_CMD (7 << 6)
static void epic_disable_int(struct net_device *dev, struct epic_private *ep)
{
long ioaddr = dev->base_addr;
outl(0x00000000, ioaddr + INTMASK);
}
static inline void __epic_pci_commit(long ioaddr)
{
#ifndef USE_IO_OPS
inl(ioaddr + INTMASK);
#endif
}
static inline void epic_napi_irq_off(struct net_device *dev,
struct epic_private *ep)
{
long ioaddr = dev->base_addr;
outl(ep->irq_mask & ~EpicNapiEvent, ioaddr + INTMASK);
__epic_pci_commit(ioaddr);
}
static inline void epic_napi_irq_on(struct net_device *dev,
struct epic_private *ep)
{
long ioaddr = dev->base_addr;
/* No need to commit possible posted write */
outl(ep->irq_mask | EpicNapiEvent, ioaddr + INTMASK);
}
static int __devinit read_eeprom(long ioaddr, int location)
{
int i;
int retval = 0;
long ee_addr = ioaddr + EECTL;
int read_cmd = location |
(inl(ee_addr) & 0x40 ? EE_READ64_CMD : EE_READ256_CMD);
outl(EE_ENB & ~EE_CS, ee_addr);
outl(EE_ENB, ee_addr);
/* Shift the read command bits out. */
for (i = 12; i >= 0; i--) {
short dataval = (read_cmd & (1 << i)) ? EE_WRITE_1 : EE_WRITE_0;
outl(EE_ENB | dataval, ee_addr);
eeprom_delay();
outl(EE_ENB | dataval | EE_SHIFT_CLK, ee_addr);
eeprom_delay();
}
outl(EE_ENB, ee_addr);
for (i = 16; i > 0; i--) {
outl(EE_ENB | EE_SHIFT_CLK, ee_addr);
eeprom_delay();
retval = (retval << 1) | ((inl(ee_addr) & EE_DATA_READ) ? 1 : 0);
outl(EE_ENB, ee_addr);
eeprom_delay();
}
/* Terminate the EEPROM access. */
outl(EE_ENB & ~EE_CS, ee_addr);
return retval;
}
#define MII_READOP 1
#define MII_WRITEOP 2
static int mdio_read(struct net_device *dev, int phy_id, int location)
{
long ioaddr = dev->base_addr;
int read_cmd = (phy_id << 9) | (location << 4) | MII_READOP;
int i;
outl(read_cmd, ioaddr + MIICtrl);
/* Typical operation takes 25 loops. */
for (i = 400; i > 0; i--) {
barrier();
if ((inl(ioaddr + MIICtrl) & MII_READOP) == 0) {
/* Work around read failure bug. */
if (phy_id == 1 && location < 6 &&
inw(ioaddr + MIIData) == 0xffff) {
outl(read_cmd, ioaddr + MIICtrl);
continue;
}
return inw(ioaddr + MIIData);
}
}
return 0xffff;
}
static void mdio_write(struct net_device *dev, int phy_id, int loc, int value)
{
long ioaddr = dev->base_addr;
int i;
outw(value, ioaddr + MIIData);
outl((phy_id << 9) | (loc << 4) | MII_WRITEOP, ioaddr + MIICtrl);
for (i = 10000; i > 0; i--) {
barrier();
if ((inl(ioaddr + MIICtrl) & MII_WRITEOP) == 0)
break;
}
}
static int epic_open(struct net_device *dev)
{
struct epic_private *ep = netdev_priv(dev);
long ioaddr = dev->base_addr;
int i;
int retval;
/* Soft reset the chip. */
outl(0x4001, ioaddr + GENCTL);
napi_enable(&ep->napi);
if ((retval = request_irq(dev->irq, epic_interrupt, IRQF_SHARED, dev->name, dev))) {
napi_disable(&ep->napi);
return retval;
}
epic_init_ring(dev);
outl(0x4000, ioaddr + GENCTL);
/* This magic is documented in SMSC app note 7.15 */
for (i = 16; i > 0; i--)
outl(0x0008, ioaddr + TEST1);
/* Pull the chip out of low-power mode, enable interrupts, and set for
PCI read multiple. The MIIcfg setting and strange write order are
required by the details of which bits are reset and the transceiver
wiring on the Ositech CardBus card.
*/
#if 0
outl(dev->if_port == 1 ? 0x13 : 0x12, ioaddr + MIICfg);
#endif
if (ep->chip_flags & MII_PWRDWN)
outl((inl(ioaddr + NVCTL) & ~0x003C) | 0x4800, ioaddr + NVCTL);
/* Tell the chip to byteswap descriptors on big-endian hosts */
#ifdef __BIG_ENDIAN
outl(0x4432 | (RX_FIFO_THRESH<<8), ioaddr + GENCTL);
inl(ioaddr + GENCTL);
outl(0x0432 | (RX_FIFO_THRESH<<8), ioaddr + GENCTL);
#else
outl(0x4412 | (RX_FIFO_THRESH<<8), ioaddr + GENCTL);
inl(ioaddr + GENCTL);
outl(0x0412 | (RX_FIFO_THRESH<<8), ioaddr + GENCTL);
#endif
udelay(20); /* Looks like EPII needs that if you want reliable RX init. FIXME: pci posting bug? */
for (i = 0; i < 3; i++)
outl(le16_to_cpu(((__le16*)dev->dev_addr)[i]), ioaddr + LAN0 + i*4);
ep->tx_threshold = TX_FIFO_THRESH;
outl(ep->tx_threshold, ioaddr + TxThresh);
if (media2miictl[dev->if_port & 15]) {
if (ep->mii_phy_cnt)
mdio_write(dev, ep->phys[0], MII_BMCR, media2miictl[dev->if_port&15]);
if (dev->if_port == 1) {
if (debug > 1)
printk(KERN_INFO "%s: Using the 10base2 transceiver, MII "
"status %4.4x.\n",
dev->name, mdio_read(dev, ep->phys[0], MII_BMSR));
}
} else {
int mii_lpa = mdio_read(dev, ep->phys[0], MII_LPA);
if (mii_lpa != 0xffff) {
if ((mii_lpa & LPA_100FULL) || (mii_lpa & 0x01C0) == LPA_10FULL)
ep->mii.full_duplex = 1;
else if (! (mii_lpa & LPA_LPACK))
mdio_write(dev, ep->phys[0], MII_BMCR, BMCR_ANENABLE|BMCR_ANRESTART);
if (debug > 1)
printk(KERN_INFO "%s: Setting %s-duplex based on MII xcvr %d"
" register read of %4.4x.\n", dev->name,
ep->mii.full_duplex ? "full" : "half",
ep->phys[0], mii_lpa);
}
}
outl(ep->mii.full_duplex ? 0x7F : 0x79, ioaddr + TxCtrl);
outl(ep->rx_ring_dma, ioaddr + PRxCDAR);
outl(ep->tx_ring_dma, ioaddr + PTxCDAR);
/* Start the chip's Rx process. */
set_rx_mode(dev);
outl(StartRx | RxQueued, ioaddr + COMMAND);
netif_start_queue(dev);
/* Enable interrupts by setting the interrupt mask. */
outl((ep->chip_flags & TYPE2_INTR ? PCIBusErr175 : PCIBusErr170)
| CntFull | TxUnderrun
| RxError | RxHeader | EpicNapiEvent, ioaddr + INTMASK);
if (debug > 1)
printk(KERN_DEBUG "%s: epic_open() ioaddr %lx IRQ %d status %4.4x "
"%s-duplex.\n",
dev->name, ioaddr, dev->irq, (int)inl(ioaddr + GENCTL),
ep->mii.full_duplex ? "full" : "half");
/* Set the timer to switch to check for link beat and perhaps switch
to an alternate media type. */
init_timer(&ep->timer);
ep->timer.expires = jiffies + 3*HZ;
ep->timer.data = (unsigned long)dev;
ep->timer.function = epic_timer; /* timer handler */
add_timer(&ep->timer);
return 0;
}
/* Reset the chip to recover from a PCI transaction error.
This may occur at interrupt time. */
static void epic_pause(struct net_device *dev)
{
long ioaddr = dev->base_addr;
netif_stop_queue (dev);
/* Disable interrupts by clearing the interrupt mask. */
outl(0x00000000, ioaddr + INTMASK);
/* Stop the chip's Tx and Rx DMA processes. */
outw(StopRx | StopTxDMA | StopRxDMA, ioaddr + COMMAND);
/* Update the error counts. */
if (inw(ioaddr + COMMAND) != 0xffff) {
dev->stats.rx_missed_errors += inb(ioaddr + MPCNT);
dev->stats.rx_frame_errors += inb(ioaddr + ALICNT);
dev->stats.rx_crc_errors += inb(ioaddr + CRCCNT);
}
/* Remove the packets on the Rx queue. */
epic_rx(dev, RX_RING_SIZE);
}
static void epic_restart(struct net_device *dev)
{
long ioaddr = dev->base_addr;
struct epic_private *ep = netdev_priv(dev);
int i;
/* Soft reset the chip. */
outl(0x4001, ioaddr + GENCTL);
printk(KERN_DEBUG "%s: Restarting the EPIC chip, Rx %d/%d Tx %d/%d.\n",
dev->name, ep->cur_rx, ep->dirty_rx, ep->dirty_tx, ep->cur_tx);
udelay(1);
/* This magic is documented in SMSC app note 7.15 */
for (i = 16; i > 0; i--)
outl(0x0008, ioaddr + TEST1);
#ifdef __BIG_ENDIAN
outl(0x0432 | (RX_FIFO_THRESH<<8), ioaddr + GENCTL);
#else
outl(0x0412 | (RX_FIFO_THRESH<<8), ioaddr + GENCTL);
#endif
outl(dev->if_port == 1 ? 0x13 : 0x12, ioaddr + MIICfg);
if (ep->chip_flags & MII_PWRDWN)
outl((inl(ioaddr + NVCTL) & ~0x003C) | 0x4800, ioaddr + NVCTL);
for (i = 0; i < 3; i++)
outl(le16_to_cpu(((__le16*)dev->dev_addr)[i]), ioaddr + LAN0 + i*4);
ep->tx_threshold = TX_FIFO_THRESH;
outl(ep->tx_threshold, ioaddr + TxThresh);
outl(ep->mii.full_duplex ? 0x7F : 0x79, ioaddr + TxCtrl);
outl(ep->rx_ring_dma + (ep->cur_rx%RX_RING_SIZE)*
sizeof(struct epic_rx_desc), ioaddr + PRxCDAR);
outl(ep->tx_ring_dma + (ep->dirty_tx%TX_RING_SIZE)*
sizeof(struct epic_tx_desc), ioaddr + PTxCDAR);
/* Start the chip's Rx process. */
set_rx_mode(dev);
outl(StartRx | RxQueued, ioaddr + COMMAND);
/* Enable interrupts by setting the interrupt mask. */
outl((ep->chip_flags & TYPE2_INTR ? PCIBusErr175 : PCIBusErr170)
| CntFull | TxUnderrun
| RxError | RxHeader | EpicNapiEvent, ioaddr + INTMASK);
printk(KERN_DEBUG "%s: epic_restart() done, cmd status %4.4x, ctl %4.4x"
" interrupt %4.4x.\n",
dev->name, (int)inl(ioaddr + COMMAND), (int)inl(ioaddr + GENCTL),
(int)inl(ioaddr + INTSTAT));
}
static void check_media(struct net_device *dev)
{
struct epic_private *ep = netdev_priv(dev);
long ioaddr = dev->base_addr;
int mii_lpa = ep->mii_phy_cnt ? mdio_read(dev, ep->phys[0], MII_LPA) : 0;
int negotiated = mii_lpa & ep->mii.advertising;
int duplex = (negotiated & 0x0100) || (negotiated & 0x01C0) == 0x0040;
if (ep->mii.force_media)
return;
if (mii_lpa == 0xffff) /* Bogus read */
return;
if (ep->mii.full_duplex != duplex) {
ep->mii.full_duplex = duplex;
printk(KERN_INFO "%s: Setting %s-duplex based on MII #%d link"
" partner capability of %4.4x.\n", dev->name,
ep->mii.full_duplex ? "full" : "half", ep->phys[0], mii_lpa);
outl(ep->mii.full_duplex ? 0x7F : 0x79, ioaddr + TxCtrl);
}
}
static void epic_timer(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct epic_private *ep = netdev_priv(dev);
long ioaddr = dev->base_addr;
int next_tick = 5*HZ;
if (debug > 3) {
printk(KERN_DEBUG "%s: Media monitor tick, Tx status %8.8x.\n",
dev->name, (int)inl(ioaddr + TxSTAT));
printk(KERN_DEBUG "%s: Other registers are IntMask %4.4x "
"IntStatus %4.4x RxStatus %4.4x.\n",
dev->name, (int)inl(ioaddr + INTMASK),
(int)inl(ioaddr + INTSTAT), (int)inl(ioaddr + RxSTAT));
}
check_media(dev);
ep->timer.expires = jiffies + next_tick;
add_timer(&ep->timer);
}
static void epic_tx_timeout(struct net_device *dev)
{
struct epic_private *ep = netdev_priv(dev);
long ioaddr = dev->base_addr;
if (debug > 0) {
printk(KERN_WARNING "%s: Transmit timeout using MII device, "
"Tx status %4.4x.\n",
dev->name, (int)inw(ioaddr + TxSTAT));
if (debug > 1) {
printk(KERN_DEBUG "%s: Tx indices: dirty_tx %d, cur_tx %d.\n",
dev->name, ep->dirty_tx, ep->cur_tx);
}
}
if (inw(ioaddr + TxSTAT) & 0x10) { /* Tx FIFO underflow. */
dev->stats.tx_fifo_errors++;
outl(RestartTx, ioaddr + COMMAND);
} else {
epic_restart(dev);
outl(TxQueued, dev->base_addr + COMMAND);
}
dev->trans_start = jiffies; /* prevent tx timeout */
dev->stats.tx_errors++;
if (!ep->tx_full)
netif_wake_queue(dev);
}
/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
static void epic_init_ring(struct net_device *dev)
{
struct epic_private *ep = netdev_priv(dev);
int i;
ep->tx_full = 0;
ep->dirty_tx = ep->cur_tx = 0;
ep->cur_rx = ep->dirty_rx = 0;
ep->rx_buf_sz = (dev->mtu <= 1500 ? PKT_BUF_SZ : dev->mtu + 32);
/* Initialize all Rx descriptors. */
for (i = 0; i < RX_RING_SIZE; i++) {
ep->rx_ring[i].rxstatus = 0;
ep->rx_ring[i].buflength = ep->rx_buf_sz;
ep->rx_ring[i].next = ep->rx_ring_dma +
(i+1)*sizeof(struct epic_rx_desc);
ep->rx_skbuff[i] = NULL;
}
/* Mark the last entry as wrapping the ring. */
ep->rx_ring[i-1].next = ep->rx_ring_dma;
/* Fill in the Rx buffers. Handle allocation failure gracefully. */
for (i = 0; i < RX_RING_SIZE; i++) {
struct sk_buff *skb = netdev_alloc_skb(dev, ep->rx_buf_sz + 2);
ep->rx_skbuff[i] = skb;
if (skb == NULL)
break;
skb_reserve(skb, 2); /* 16 byte align the IP header. */
ep->rx_ring[i].bufaddr = pci_map_single(ep->pci_dev,
skb->data, ep->rx_buf_sz, PCI_DMA_FROMDEVICE);
ep->rx_ring[i].rxstatus = DescOwn;
}
ep->dirty_rx = (unsigned int)(i - RX_RING_SIZE);
/* The Tx buffer descriptor is filled in as needed, but we
do need to clear the ownership bit. */
for (i = 0; i < TX_RING_SIZE; i++) {
ep->tx_skbuff[i] = NULL;
ep->tx_ring[i].txstatus = 0x0000;
ep->tx_ring[i].next = ep->tx_ring_dma +
(i+1)*sizeof(struct epic_tx_desc);
}
ep->tx_ring[i-1].next = ep->tx_ring_dma;
}
static netdev_tx_t epic_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct epic_private *ep = netdev_priv(dev);
int entry, free_count;
u32 ctrl_word;
unsigned long flags;
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
/* Caution: the write order is important here, set the field with the
"ownership" bit last. */
/* Calculate the next Tx descriptor entry. */
spin_lock_irqsave(&ep->lock, flags);
free_count = ep->cur_tx - ep->dirty_tx;
entry = ep->cur_tx % TX_RING_SIZE;
ep->tx_skbuff[entry] = skb;
ep->tx_ring[entry].bufaddr = pci_map_single(ep->pci_dev, skb->data,
skb->len, PCI_DMA_TODEVICE);
if (free_count < TX_QUEUE_LEN/2) {/* Typical path */
ctrl_word = 0x100000; /* No interrupt */
} else if (free_count == TX_QUEUE_LEN/2) {
ctrl_word = 0x140000; /* Tx-done intr. */
} else if (free_count < TX_QUEUE_LEN - 1) {
ctrl_word = 0x100000; /* No Tx-done intr. */
} else {
/* Leave room for an additional entry. */
ctrl_word = 0x140000; /* Tx-done intr. */
ep->tx_full = 1;
}
ep->tx_ring[entry].buflength = ctrl_word | skb->len;
ep->tx_ring[entry].txstatus =
((skb->len >= ETH_ZLEN ? skb->len : ETH_ZLEN) << 16)
| DescOwn;
ep->cur_tx++;
if (ep->tx_full)
netif_stop_queue(dev);
spin_unlock_irqrestore(&ep->lock, flags);
/* Trigger an immediate transmit demand. */
outl(TxQueued, dev->base_addr + COMMAND);
if (debug > 4)
printk(KERN_DEBUG "%s: Queued Tx packet size %d to slot %d, "
"flag %2.2x Tx status %8.8x.\n",
dev->name, (int)skb->len, entry, ctrl_word,
(int)inl(dev->base_addr + TxSTAT));
return NETDEV_TX_OK;
}
static void epic_tx_error(struct net_device *dev, struct epic_private *ep,
int status)
{
struct net_device_stats *stats = &dev->stats;
#ifndef final_version
/* There was an major error, log it. */
if (debug > 1)
printk(KERN_DEBUG "%s: Transmit error, Tx status %8.8x.\n",
dev->name, status);
#endif
stats->tx_errors++;
if (status & 0x1050)
stats->tx_aborted_errors++;
if (status & 0x0008)
stats->tx_carrier_errors++;
if (status & 0x0040)
stats->tx_window_errors++;
if (status & 0x0010)
stats->tx_fifo_errors++;
}
static void epic_tx(struct net_device *dev, struct epic_private *ep)
{
unsigned int dirty_tx, cur_tx;
/*
* Note: if this lock becomes a problem we can narrow the locked
* region at the cost of occasionally grabbing the lock more times.
*/
cur_tx = ep->cur_tx;
for (dirty_tx = ep->dirty_tx; cur_tx - dirty_tx > 0; dirty_tx++) {
struct sk_buff *skb;
int entry = dirty_tx % TX_RING_SIZE;
int txstatus = ep->tx_ring[entry].txstatus;
if (txstatus & DescOwn)
break; /* It still hasn't been Txed */
if (likely(txstatus & 0x0001)) {
dev->stats.collisions += (txstatus >> 8) & 15;
dev->stats.tx_packets++;
dev->stats.tx_bytes += ep->tx_skbuff[entry]->len;
} else
epic_tx_error(dev, ep, txstatus);
/* Free the original skb. */
skb = ep->tx_skbuff[entry];
pci_unmap_single(ep->pci_dev, ep->tx_ring[entry].bufaddr,
skb->len, PCI_DMA_TODEVICE);
dev_kfree_skb_irq(skb);
ep->tx_skbuff[entry] = NULL;
}
#ifndef final_version
if (cur_tx - dirty_tx > TX_RING_SIZE) {
printk(KERN_WARNING
"%s: Out-of-sync dirty pointer, %d vs. %d, full=%d.\n",
dev->name, dirty_tx, cur_tx, ep->tx_full);
dirty_tx += TX_RING_SIZE;
}
#endif
ep->dirty_tx = dirty_tx;
if (ep->tx_full && cur_tx - dirty_tx < TX_QUEUE_LEN - 4) {
/* The ring is no longer full, allow new TX entries. */
ep->tx_full = 0;
netif_wake_queue(dev);
}
}
/* The interrupt handler does all of the Rx thread work and cleans up
after the Tx thread. */
static irqreturn_t epic_interrupt(int irq, void *dev_instance)
{
struct net_device *dev = dev_instance;
struct epic_private *ep = netdev_priv(dev);
long ioaddr = dev->base_addr;
unsigned int handled = 0;
int status;
status = inl(ioaddr + INTSTAT);
/* Acknowledge all of the current interrupt sources ASAP. */
outl(status & EpicNormalEvent, ioaddr + INTSTAT);
if (debug > 4) {
printk(KERN_DEBUG "%s: Interrupt, status=%#8.8x new "
"intstat=%#8.8x.\n", dev->name, status,
(int)inl(ioaddr + INTSTAT));
}
if ((status & IntrSummary) == 0)
goto out;
handled = 1;
if ((status & EpicNapiEvent) && !ep->reschedule_in_poll) {
spin_lock(&ep->napi_lock);
if (napi_schedule_prep(&ep->napi)) {
epic_napi_irq_off(dev, ep);
__napi_schedule(&ep->napi);
} else
ep->reschedule_in_poll++;
spin_unlock(&ep->napi_lock);
}
status &= ~EpicNapiEvent;
/* Check uncommon events all at once. */
if (status & (CntFull | TxUnderrun | PCIBusErr170 | PCIBusErr175)) {
if (status == EpicRemoved)
goto out;
/* Always update the error counts to avoid overhead later. */
dev->stats.rx_missed_errors += inb(ioaddr + MPCNT);
dev->stats.rx_frame_errors += inb(ioaddr + ALICNT);
dev->stats.rx_crc_errors += inb(ioaddr + CRCCNT);
if (status & TxUnderrun) { /* Tx FIFO underflow. */
dev->stats.tx_fifo_errors++;
outl(ep->tx_threshold += 128, ioaddr + TxThresh);
/* Restart the transmit process. */
outl(RestartTx, ioaddr + COMMAND);
}
if (status & PCIBusErr170) {
printk(KERN_ERR "%s: PCI Bus Error! status %4.4x.\n",
dev->name, status);
epic_pause(dev);
epic_restart(dev);
}
/* Clear all error sources. */
outl(status & 0x7f18, ioaddr + INTSTAT);
}
out:
if (debug > 3) {
printk(KERN_DEBUG "%s: exit interrupt, intr_status=%#4.4x.\n",
dev->name, status);
}
return IRQ_RETVAL(handled);
}
static int epic_rx(struct net_device *dev, int budget)
{
struct epic_private *ep = netdev_priv(dev);
int entry = ep->cur_rx % RX_RING_SIZE;
int rx_work_limit = ep->dirty_rx + RX_RING_SIZE - ep->cur_rx;
int work_done = 0;
if (debug > 4)
printk(KERN_DEBUG " In epic_rx(), entry %d %8.8x.\n", entry,
ep->rx_ring[entry].rxstatus);
if (rx_work_limit > budget)
rx_work_limit = budget;
/* If we own the next entry, it's a new packet. Send it up. */
while ((ep->rx_ring[entry].rxstatus & DescOwn) == 0) {
int status = ep->rx_ring[entry].rxstatus;
if (debug > 4)
printk(KERN_DEBUG " epic_rx() status was %8.8x.\n", status);
if (--rx_work_limit < 0)
break;
if (status & 0x2006) {
if (debug > 2)
printk(KERN_DEBUG "%s: epic_rx() error status was %8.8x.\n",
dev->name, status);
if (status & 0x2000) {
printk(KERN_WARNING "%s: Oversized Ethernet frame spanned "
"multiple buffers, status %4.4x!\n", dev->name, status);
dev->stats.rx_length_errors++;
} else if (status & 0x0006)
/* Rx Frame errors are counted in hardware. */
dev->stats.rx_errors++;
} else {
/* Malloc up new buffer, compatible with net-2e. */
/* Omit the four octet CRC from the length. */
short pkt_len = (status >> 16) - 4;
struct sk_buff *skb;
if (pkt_len > PKT_BUF_SZ - 4) {
printk(KERN_ERR "%s: Oversized Ethernet frame, status %x "
"%d bytes.\n",
dev->name, status, pkt_len);
pkt_len = 1514;
}
/* Check if the packet is long enough to accept without copying
to a minimally-sized skbuff. */
if (pkt_len < rx_copybreak &&
(skb = netdev_alloc_skb(dev, pkt_len + 2)) != NULL) {
skb_reserve(skb, 2); /* 16 byte align the IP header */
pci_dma_sync_single_for_cpu(ep->pci_dev,
ep->rx_ring[entry].bufaddr,
ep->rx_buf_sz,
PCI_DMA_FROMDEVICE);
skb_copy_to_linear_data(skb, ep->rx_skbuff[entry]->data, pkt_len);
skb_put(skb, pkt_len);
pci_dma_sync_single_for_device(ep->pci_dev,
ep->rx_ring[entry].bufaddr,
ep->rx_buf_sz,
PCI_DMA_FROMDEVICE);
} else {
pci_unmap_single(ep->pci_dev,
ep->rx_ring[entry].bufaddr,
ep->rx_buf_sz, PCI_DMA_FROMDEVICE);
skb_put(skb = ep->rx_skbuff[entry], pkt_len);
ep->rx_skbuff[entry] = NULL;
}
skb->protocol = eth_type_trans(skb, dev);
netif_receive_skb(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += pkt_len;
}
work_done++;
entry = (++ep->cur_rx) % RX_RING_SIZE;
}
/* Refill the Rx ring buffers. */
for (; ep->cur_rx - ep->dirty_rx > 0; ep->dirty_rx++) {
entry = ep->dirty_rx % RX_RING_SIZE;
if (ep->rx_skbuff[entry] == NULL) {
struct sk_buff *skb;
skb = ep->rx_skbuff[entry] = netdev_alloc_skb(dev, ep->rx_buf_sz + 2);
if (skb == NULL)
break;
skb_reserve(skb, 2); /* Align IP on 16 byte boundaries */
ep->rx_ring[entry].bufaddr = pci_map_single(ep->pci_dev,
skb->data, ep->rx_buf_sz, PCI_DMA_FROMDEVICE);
work_done++;
}
/* AV: shouldn't we add a barrier here? */
ep->rx_ring[entry].rxstatus = DescOwn;
}
return work_done;
}
static void epic_rx_err(struct net_device *dev, struct epic_private *ep)
{
long ioaddr = dev->base_addr;
int status;
status = inl(ioaddr + INTSTAT);
if (status == EpicRemoved)
return;
if (status & RxOverflow) /* Missed a Rx frame. */
dev->stats.rx_errors++;
if (status & (RxOverflow | RxFull))
outw(RxQueued, ioaddr + COMMAND);
}
static int epic_poll(struct napi_struct *napi, int budget)
{
struct epic_private *ep = container_of(napi, struct epic_private, napi);
struct net_device *dev = ep->mii.dev;
int work_done = 0;
long ioaddr = dev->base_addr;
rx_action:
epic_tx(dev, ep);
work_done += epic_rx(dev, budget);
epic_rx_err(dev, ep);
if (work_done < budget) {
unsigned long flags;
int more;
/* A bit baroque but it avoids a (space hungry) spin_unlock */
spin_lock_irqsave(&ep->napi_lock, flags);
more = ep->reschedule_in_poll;
if (!more) {
__napi_complete(napi);
outl(EpicNapiEvent, ioaddr + INTSTAT);
epic_napi_irq_on(dev, ep);
} else
ep->reschedule_in_poll--;
spin_unlock_irqrestore(&ep->napi_lock, flags);
if (more)
goto rx_action;
}
return work_done;
}
static int epic_close(struct net_device *dev)
{
long ioaddr = dev->base_addr;
struct epic_private *ep = netdev_priv(dev);
struct sk_buff *skb;
int i;
netif_stop_queue(dev);
napi_disable(&ep->napi);
if (debug > 1)
printk(KERN_DEBUG "%s: Shutting down ethercard, status was %2.2x.\n",
dev->name, (int)inl(ioaddr + INTSTAT));
del_timer_sync(&ep->timer);
epic_disable_int(dev, ep);
free_irq(dev->irq, dev);
epic_pause(dev);
/* Free all the skbuffs in the Rx queue. */
for (i = 0; i < RX_RING_SIZE; i++) {
skb = ep->rx_skbuff[i];
ep->rx_skbuff[i] = NULL;
ep->rx_ring[i].rxstatus = 0; /* Not owned by Epic chip. */
ep->rx_ring[i].buflength = 0;
if (skb) {
pci_unmap_single(ep->pci_dev, ep->rx_ring[i].bufaddr,
ep->rx_buf_sz, PCI_DMA_FROMDEVICE);
dev_kfree_skb(skb);
}
ep->rx_ring[i].bufaddr = 0xBADF00D0; /* An invalid address. */
}
for (i = 0; i < TX_RING_SIZE; i++) {
skb = ep->tx_skbuff[i];
ep->tx_skbuff[i] = NULL;
if (!skb)
continue;
pci_unmap_single(ep->pci_dev, ep->tx_ring[i].bufaddr,
skb->len, PCI_DMA_TODEVICE);
dev_kfree_skb(skb);
}
/* Green! Leave the chip in low-power mode. */
outl(0x0008, ioaddr + GENCTL);
return 0;
}
static struct net_device_stats *epic_get_stats(struct net_device *dev)
{
long ioaddr = dev->base_addr;
if (netif_running(dev)) {
/* Update the error counts. */
dev->stats.rx_missed_errors += inb(ioaddr + MPCNT);
dev->stats.rx_frame_errors += inb(ioaddr + ALICNT);
dev->stats.rx_crc_errors += inb(ioaddr + CRCCNT);
}
return &dev->stats;
}
/* Set or clear the multicast filter for this adaptor.
Note that we only use exclusion around actually queueing the
new frame, not around filling ep->setup_frame. This is non-deterministic
when re-entered but still correct. */
static void set_rx_mode(struct net_device *dev)
{
long ioaddr = dev->base_addr;
struct epic_private *ep = netdev_priv(dev);
unsigned char mc_filter[8]; /* Multicast hash filter */
int i;
if (dev->flags & IFF_PROMISC) { /* Set promiscuous. */
outl(0x002C, ioaddr + RxCtrl);
/* Unconditionally log net taps. */
memset(mc_filter, 0xff, sizeof(mc_filter));
} else if ((!netdev_mc_empty(dev)) || (dev->flags & IFF_ALLMULTI)) {
/* There is apparently a chip bug, so the multicast filter
is never enabled. */
/* Too many to filter perfectly -- accept all multicasts. */
memset(mc_filter, 0xff, sizeof(mc_filter));
outl(0x000C, ioaddr + RxCtrl);
} else if (netdev_mc_empty(dev)) {
outl(0x0004, ioaddr + RxCtrl);
return;
} else { /* Never executed, for now. */
struct netdev_hw_addr *ha;
memset(mc_filter, 0, sizeof(mc_filter));
netdev_for_each_mc_addr(ha, dev) {
unsigned int bit_nr =
ether_crc_le(ETH_ALEN, ha->addr) & 0x3f;
mc_filter[bit_nr >> 3] |= (1 << bit_nr);
}
}
/* ToDo: perhaps we need to stop the Tx and Rx process here? */
if (memcmp(mc_filter, ep->mc_filter, sizeof(mc_filter))) {
for (i = 0; i < 4; i++)
outw(((u16 *)mc_filter)[i], ioaddr + MC0 + i*4);
memcpy(ep->mc_filter, mc_filter, sizeof(mc_filter));
}
}
static void netdev_get_drvinfo (struct net_device *dev, struct ethtool_drvinfo *info)
{
struct epic_private *np = netdev_priv(dev);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pci_name(np->pci_dev), sizeof(info->bus_info));
}
static int netdev_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct epic_private *np = netdev_priv(dev);
int rc;
spin_lock_irq(&np->lock);
rc = mii_ethtool_gset(&np->mii, cmd);
spin_unlock_irq(&np->lock);
return rc;
}
static int netdev_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct epic_private *np = netdev_priv(dev);
int rc;
spin_lock_irq(&np->lock);
rc = mii_ethtool_sset(&np->mii, cmd);
spin_unlock_irq(&np->lock);
return rc;
}
static int netdev_nway_reset(struct net_device *dev)
{
struct epic_private *np = netdev_priv(dev);
return mii_nway_restart(&np->mii);
}
static u32 netdev_get_link(struct net_device *dev)
{
struct epic_private *np = netdev_priv(dev);
return mii_link_ok(&np->mii);
}
static u32 netdev_get_msglevel(struct net_device *dev)
{
return debug;
}
static void netdev_set_msglevel(struct net_device *dev, u32 value)
{
debug = value;
}
static int ethtool_begin(struct net_device *dev)
{
unsigned long ioaddr = dev->base_addr;
/* power-up, if interface is down */
if (! netif_running(dev)) {
outl(0x0200, ioaddr + GENCTL);
outl((inl(ioaddr + NVCTL) & ~0x003C) | 0x4800, ioaddr + NVCTL);
}
return 0;
}
static void ethtool_complete(struct net_device *dev)
{
unsigned long ioaddr = dev->base_addr;
/* power-down, if interface is down */
if (! netif_running(dev)) {
outl(0x0008, ioaddr + GENCTL);
outl((inl(ioaddr + NVCTL) & ~0x483C) | 0x0000, ioaddr + NVCTL);
}
}
static const struct ethtool_ops netdev_ethtool_ops = {
.get_drvinfo = netdev_get_drvinfo,
.get_settings = netdev_get_settings,
.set_settings = netdev_set_settings,
.nway_reset = netdev_nway_reset,
.get_link = netdev_get_link,
.get_msglevel = netdev_get_msglevel,
.set_msglevel = netdev_set_msglevel,
.begin = ethtool_begin,
.complete = ethtool_complete
};
static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct epic_private *np = netdev_priv(dev);
long ioaddr = dev->base_addr;
struct mii_ioctl_data *data = if_mii(rq);
int rc;
/* power-up, if interface is down */
if (! netif_running(dev)) {
outl(0x0200, ioaddr + GENCTL);
outl((inl(ioaddr + NVCTL) & ~0x003C) | 0x4800, ioaddr + NVCTL);
}
/* all non-ethtool ioctls (the SIOC[GS]MIIxxx ioctls) */
spin_lock_irq(&np->lock);
rc = generic_mii_ioctl(&np->mii, data, cmd, NULL);
spin_unlock_irq(&np->lock);
/* power-down, if interface is down */
if (! netif_running(dev)) {
outl(0x0008, ioaddr + GENCTL);
outl((inl(ioaddr + NVCTL) & ~0x483C) | 0x0000, ioaddr + NVCTL);
}
return rc;
}
static void __devexit epic_remove_one (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct epic_private *ep = netdev_priv(dev);
pci_free_consistent(pdev, TX_TOTAL_SIZE, ep->tx_ring, ep->tx_ring_dma);
pci_free_consistent(pdev, RX_TOTAL_SIZE, ep->rx_ring, ep->rx_ring_dma);
unregister_netdev(dev);
#ifndef USE_IO_OPS
iounmap((void*) dev->base_addr);
#endif
pci_release_regions(pdev);
free_netdev(dev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
/* pci_power_off(pdev, -1); */
}
#ifdef CONFIG_PM
static int epic_suspend (struct pci_dev *pdev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata(pdev);
long ioaddr = dev->base_addr;
if (!netif_running(dev))
return 0;
epic_pause(dev);
/* Put the chip into low-power mode. */
outl(0x0008, ioaddr + GENCTL);
/* pci_power_off(pdev, -1); */
return 0;
}
static int epic_resume (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
if (!netif_running(dev))
return 0;
epic_restart(dev);
/* pci_power_on(pdev); */
return 0;
}
#endif /* CONFIG_PM */
static struct pci_driver epic_driver = {
.name = DRV_NAME,
.id_table = epic_pci_tbl,
.probe = epic_init_one,
.remove = __devexit_p(epic_remove_one),
#ifdef CONFIG_PM
.suspend = epic_suspend,
.resume = epic_resume,
#endif /* CONFIG_PM */
};
static int __init epic_init (void)
{
/* when a module, this is printed whether or not devices are found in probe */
#ifdef MODULE
printk (KERN_INFO "%s%s",
version, version2);
#endif
return pci_register_driver(&epic_driver);
}
static void __exit epic_cleanup (void)
{
pci_unregister_driver (&epic_driver);
}
module_init(epic_init);
module_exit(epic_cleanup);
| gpl-2.0 |
lexmazter/dellstreak5-kernel-3.4 | drivers/net/ethernet/dec/tulip/dmfe.c | 4805 | 60542 | /*
A Davicom DM9102/DM9102A/DM9102A+DM9801/DM9102A+DM9802 NIC fast
ethernet driver for Linux.
Copyright (C) 1997 Sten Wang
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.
DAVICOM Web-Site: www.davicom.com.tw
Author: Sten Wang, 886-3-5798797-8517, E-mail: sten_wang@davicom.com.tw
Maintainer: Tobias Ringstrom <tori@unhappy.mine.nu>
(C)Copyright 1997-1998 DAVICOM Semiconductor,Inc. All Rights Reserved.
Marcelo Tosatti <marcelo@conectiva.com.br> :
Made it compile in 2.3 (device to net_device)
Alan Cox <alan@lxorguk.ukuu.org.uk> :
Cleaned up for kernel merge.
Removed the back compatibility support
Reformatted, fixing spelling etc as I went
Removed IRQ 0-15 assumption
Jeff Garzik <jgarzik@pobox.com> :
Updated to use new PCI driver API.
Resource usage cleanups.
Report driver version to user.
Tobias Ringstrom <tori@unhappy.mine.nu> :
Cleaned up and added SMP safety. Thanks go to Jeff Garzik,
Andrew Morton and Frank Davis for the SMP safety fixes.
Vojtech Pavlik <vojtech@suse.cz> :
Cleaned up pointer arithmetics.
Fixed a lot of 64bit issues.
Cleaned up printk()s a bit.
Fixed some obvious big endian problems.
Tobias Ringstrom <tori@unhappy.mine.nu> :
Use time_after for jiffies calculation. Added ethtool
support. Updated PCI resource allocation. Do not
forget to unmap PCI mapped skbs.
Alan Cox <alan@lxorguk.ukuu.org.uk>
Added new PCI identifiers provided by Clear Zhang at ALi
for their 1563 ethernet device.
TODO
Check on 64 bit boxes.
Check and fix on big endian boxes.
Test and make sure PCI latency is now correct for all cases.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define DRV_NAME "dmfe"
#define DRV_VERSION "1.36.4"
#define DRV_RELDATE "2002-01-17"
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/ptrace.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/skbuff.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/crc32.h>
#include <linux/bitops.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#ifdef CONFIG_TULIP_DM910X
#include <linux/of.h>
#endif
/* Board/System/Debug information/definition ---------------- */
#define PCI_DM9132_ID 0x91321282 /* Davicom DM9132 ID */
#define PCI_DM9102_ID 0x91021282 /* Davicom DM9102 ID */
#define PCI_DM9100_ID 0x91001282 /* Davicom DM9100 ID */
#define PCI_DM9009_ID 0x90091282 /* Davicom DM9009 ID */
#define DM9102_IO_SIZE 0x80
#define DM9102A_IO_SIZE 0x100
#define TX_MAX_SEND_CNT 0x1 /* Maximum tx packet per time */
#define TX_DESC_CNT 0x10 /* Allocated Tx descriptors */
#define RX_DESC_CNT 0x20 /* Allocated Rx descriptors */
#define TX_FREE_DESC_CNT (TX_DESC_CNT - 2) /* Max TX packet count */
#define TX_WAKE_DESC_CNT (TX_DESC_CNT - 3) /* TX wakeup count */
#define DESC_ALL_CNT (TX_DESC_CNT + RX_DESC_CNT)
#define TX_BUF_ALLOC 0x600
#define RX_ALLOC_SIZE 0x620
#define DM910X_RESET 1
#define CR0_DEFAULT 0x00E00000 /* TX & RX burst mode */
#define CR6_DEFAULT 0x00080000 /* HD */
#define CR7_DEFAULT 0x180c1
#define CR15_DEFAULT 0x06 /* TxJabber RxWatchdog */
#define TDES0_ERR_MASK 0x4302 /* TXJT, LC, EC, FUE */
#define MAX_PACKET_SIZE 1514
#define DMFE_MAX_MULTICAST 14
#define RX_COPY_SIZE 100
#define MAX_CHECK_PACKET 0x8000
#define DM9801_NOISE_FLOOR 8
#define DM9802_NOISE_FLOOR 5
#define DMFE_WOL_LINKCHANGE 0x20000000
#define DMFE_WOL_SAMPLEPACKET 0x10000000
#define DMFE_WOL_MAGICPACKET 0x08000000
#define DMFE_10MHF 0
#define DMFE_100MHF 1
#define DMFE_10MFD 4
#define DMFE_100MFD 5
#define DMFE_AUTO 8
#define DMFE_1M_HPNA 0x10
#define DMFE_TXTH_72 0x400000 /* TX TH 72 byte */
#define DMFE_TXTH_96 0x404000 /* TX TH 96 byte */
#define DMFE_TXTH_128 0x0000 /* TX TH 128 byte */
#define DMFE_TXTH_256 0x4000 /* TX TH 256 byte */
#define DMFE_TXTH_512 0x8000 /* TX TH 512 byte */
#define DMFE_TXTH_1K 0xC000 /* TX TH 1K byte */
#define DMFE_TIMER_WUT (jiffies + HZ * 1)/* timer wakeup time : 1 second */
#define DMFE_TX_TIMEOUT ((3*HZ)/2) /* tx packet time-out time 1.5 s" */
#define DMFE_TX_KICK (HZ/2) /* tx packet Kick-out time 0.5 s" */
#define DMFE_DBUG(dbug_now, msg, value) \
do { \
if (dmfe_debug || (dbug_now)) \
pr_err("%s %lx\n", \
(msg), (long) (value)); \
} while (0)
#define SHOW_MEDIA_TYPE(mode) \
pr_info("Change Speed to %sMhz %s duplex\n" , \
(mode & 1) ? "100":"10", \
(mode & 4) ? "full":"half");
/* CR9 definition: SROM/MII */
#define CR9_SROM_READ 0x4800
#define CR9_SRCS 0x1
#define CR9_SRCLK 0x2
#define CR9_CRDOUT 0x8
#define SROM_DATA_0 0x0
#define SROM_DATA_1 0x4
#define PHY_DATA_1 0x20000
#define PHY_DATA_0 0x00000
#define MDCLKH 0x10000
#define PHY_POWER_DOWN 0x800
#define SROM_V41_CODE 0x14
#define SROM_CLK_WRITE(data, ioaddr) \
outl(data|CR9_SROM_READ|CR9_SRCS,ioaddr); \
udelay(5); \
outl(data|CR9_SROM_READ|CR9_SRCS|CR9_SRCLK,ioaddr); \
udelay(5); \
outl(data|CR9_SROM_READ|CR9_SRCS,ioaddr); \
udelay(5);
#define __CHK_IO_SIZE(pci_id, dev_rev) \
(( ((pci_id)==PCI_DM9132_ID) || ((dev_rev) >= 0x30) ) ? \
DM9102A_IO_SIZE: DM9102_IO_SIZE)
#define CHK_IO_SIZE(pci_dev) \
(__CHK_IO_SIZE(((pci_dev)->device << 16) | (pci_dev)->vendor, \
(pci_dev)->revision))
/* Sten Check */
#define DEVICE net_device
/* Structure/enum declaration ------------------------------- */
struct tx_desc {
__le32 tdes0, tdes1, tdes2, tdes3; /* Data for the card */
char *tx_buf_ptr; /* Data for us */
struct tx_desc *next_tx_desc;
} __attribute__(( aligned(32) ));
struct rx_desc {
__le32 rdes0, rdes1, rdes2, rdes3; /* Data for the card */
struct sk_buff *rx_skb_ptr; /* Data for us */
struct rx_desc *next_rx_desc;
} __attribute__(( aligned(32) ));
struct dmfe_board_info {
u32 chip_id; /* Chip vendor/Device ID */
u8 chip_revision; /* Chip revision */
struct DEVICE *next_dev; /* next device */
struct pci_dev *pdev; /* PCI device */
spinlock_t lock;
long ioaddr; /* I/O base address */
u32 cr0_data;
u32 cr5_data;
u32 cr6_data;
u32 cr7_data;
u32 cr15_data;
/* pointer for memory physical address */
dma_addr_t buf_pool_dma_ptr; /* Tx buffer pool memory */
dma_addr_t buf_pool_dma_start; /* Tx buffer pool align dword */
dma_addr_t desc_pool_dma_ptr; /* descriptor pool memory */
dma_addr_t first_tx_desc_dma;
dma_addr_t first_rx_desc_dma;
/* descriptor pointer */
unsigned char *buf_pool_ptr; /* Tx buffer pool memory */
unsigned char *buf_pool_start; /* Tx buffer pool align dword */
unsigned char *desc_pool_ptr; /* descriptor pool memory */
struct tx_desc *first_tx_desc;
struct tx_desc *tx_insert_ptr;
struct tx_desc *tx_remove_ptr;
struct rx_desc *first_rx_desc;
struct rx_desc *rx_insert_ptr;
struct rx_desc *rx_ready_ptr; /* packet come pointer */
unsigned long tx_packet_cnt; /* transmitted packet count */
unsigned long tx_queue_cnt; /* wait to send packet count */
unsigned long rx_avail_cnt; /* available rx descriptor count */
unsigned long interval_rx_cnt; /* rx packet count a callback time */
u16 HPNA_command; /* For HPNA register 16 */
u16 HPNA_timer; /* For HPNA remote device check */
u16 dbug_cnt;
u16 NIC_capability; /* NIC media capability */
u16 PHY_reg4; /* Saved Phyxcer register 4 value */
u8 HPNA_present; /* 0:none, 1:DM9801, 2:DM9802 */
u8 chip_type; /* Keep DM9102A chip type */
u8 media_mode; /* user specify media mode */
u8 op_mode; /* real work media mode */
u8 phy_addr;
u8 wait_reset; /* Hardware failed, need to reset */
u8 dm910x_chk_mode; /* Operating mode check */
u8 first_in_callback; /* Flag to record state */
u8 wol_mode; /* user WOL settings */
struct timer_list timer;
/* Driver defined statistic counter */
unsigned long tx_fifo_underrun;
unsigned long tx_loss_carrier;
unsigned long tx_no_carrier;
unsigned long tx_late_collision;
unsigned long tx_excessive_collision;
unsigned long tx_jabber_timeout;
unsigned long reset_count;
unsigned long reset_cr8;
unsigned long reset_fatal;
unsigned long reset_TXtimeout;
/* NIC SROM data */
unsigned char srom[128];
};
enum dmfe_offsets {
DCR0 = 0x00, DCR1 = 0x08, DCR2 = 0x10, DCR3 = 0x18, DCR4 = 0x20,
DCR5 = 0x28, DCR6 = 0x30, DCR7 = 0x38, DCR8 = 0x40, DCR9 = 0x48,
DCR10 = 0x50, DCR11 = 0x58, DCR12 = 0x60, DCR13 = 0x68, DCR14 = 0x70,
DCR15 = 0x78
};
enum dmfe_CR6_bits {
CR6_RXSC = 0x2, CR6_PBF = 0x8, CR6_PM = 0x40, CR6_PAM = 0x80,
CR6_FDM = 0x200, CR6_TXSC = 0x2000, CR6_STI = 0x100000,
CR6_SFT = 0x200000, CR6_RXA = 0x40000000, CR6_NO_PURGE = 0x20000000
};
/* Global variable declaration ----------------------------- */
static int __devinitdata printed_version;
static const char version[] __devinitconst =
"Davicom DM9xxx net driver, version " DRV_VERSION " (" DRV_RELDATE ")";
static int dmfe_debug;
static unsigned char dmfe_media_mode = DMFE_AUTO;
static u32 dmfe_cr6_user_set;
/* For module input parameter */
static int debug;
static u32 cr6set;
static unsigned char mode = 8;
static u8 chkmode = 1;
static u8 HPNA_mode; /* Default: Low Power/High Speed */
static u8 HPNA_rx_cmd; /* Default: Disable Rx remote command */
static u8 HPNA_tx_cmd; /* Default: Don't issue remote command */
static u8 HPNA_NoiseFloor; /* Default: HPNA NoiseFloor */
static u8 SF_mode; /* Special Function: 1:VLAN, 2:RX Flow Control
4: TX pause packet */
/* function declaration ------------------------------------- */
static int dmfe_open(struct DEVICE *);
static netdev_tx_t dmfe_start_xmit(struct sk_buff *, struct DEVICE *);
static int dmfe_stop(struct DEVICE *);
static void dmfe_set_filter_mode(struct DEVICE *);
static const struct ethtool_ops netdev_ethtool_ops;
static u16 read_srom_word(long ,int);
static irqreturn_t dmfe_interrupt(int , void *);
#ifdef CONFIG_NET_POLL_CONTROLLER
static void poll_dmfe (struct net_device *dev);
#endif
static void dmfe_descriptor_init(struct net_device *, unsigned long);
static void allocate_rx_buffer(struct net_device *);
static void update_cr6(u32, unsigned long);
static void send_filter_frame(struct DEVICE *);
static void dm9132_id_table(struct DEVICE *);
static u16 phy_read(unsigned long, u8, u8, u32);
static void phy_write(unsigned long, u8, u8, u16, u32);
static void phy_write_1bit(unsigned long, u32);
static u16 phy_read_1bit(unsigned long);
static u8 dmfe_sense_speed(struct dmfe_board_info *);
static void dmfe_process_mode(struct dmfe_board_info *);
static void dmfe_timer(unsigned long);
static inline u32 cal_CRC(unsigned char *, unsigned int, u8);
static void dmfe_rx_packet(struct DEVICE *, struct dmfe_board_info *);
static void dmfe_free_tx_pkt(struct DEVICE *, struct dmfe_board_info *);
static void dmfe_reuse_skb(struct dmfe_board_info *, struct sk_buff *);
static void dmfe_dynamic_reset(struct DEVICE *);
static void dmfe_free_rxbuffer(struct dmfe_board_info *);
static void dmfe_init_dm910x(struct DEVICE *);
static void dmfe_parse_srom(struct dmfe_board_info *);
static void dmfe_program_DM9801(struct dmfe_board_info *, int);
static void dmfe_program_DM9802(struct dmfe_board_info *);
static void dmfe_HPNA_remote_cmd_chk(struct dmfe_board_info * );
static void dmfe_set_phyxcer(struct dmfe_board_info *);
/* DM910X network board routine ---------------------------- */
static const struct net_device_ops netdev_ops = {
.ndo_open = dmfe_open,
.ndo_stop = dmfe_stop,
.ndo_start_xmit = dmfe_start_xmit,
.ndo_set_rx_mode = dmfe_set_filter_mode,
.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 = poll_dmfe,
#endif
};
/*
* Search DM910X board ,allocate space and register it
*/
static int __devinit dmfe_init_one (struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct dmfe_board_info *db; /* board information structure */
struct net_device *dev;
u32 pci_pmr;
int i, err;
DMFE_DBUG(0, "dmfe_init_one()", 0);
if (!printed_version++)
pr_info("%s\n", version);
/*
* SPARC on-board DM910x chips should be handled by the main
* tulip driver, except for early DM9100s.
*/
#ifdef CONFIG_TULIP_DM910X
if ((ent->driver_data == PCI_DM9100_ID && pdev->revision >= 0x30) ||
ent->driver_data == PCI_DM9102_ID) {
struct device_node *dp = pci_device_to_OF_node(pdev);
if (dp && of_get_property(dp, "local-mac-address", NULL)) {
pr_info("skipping on-board DM910x (use tulip)\n");
return -ENODEV;
}
}
#endif
/* Init network device */
dev = alloc_etherdev(sizeof(*db));
if (dev == NULL)
return -ENOMEM;
SET_NETDEV_DEV(dev, &pdev->dev);
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) {
pr_warn("32-bit PCI DMA not available\n");
err = -ENODEV;
goto err_out_free;
}
/* Enable Master/IO access, Disable memory access */
err = pci_enable_device(pdev);
if (err)
goto err_out_free;
if (!pci_resource_start(pdev, 0)) {
pr_err("I/O base is zero\n");
err = -ENODEV;
goto err_out_disable;
}
if (pci_resource_len(pdev, 0) < (CHK_IO_SIZE(pdev)) ) {
pr_err("Allocated I/O size too small\n");
err = -ENODEV;
goto err_out_disable;
}
#if 0 /* pci_{enable_device,set_master} sets minimum latency for us now */
/* Set Latency Timer 80h */
/* FIXME: setting values > 32 breaks some SiS 559x stuff.
Need a PCI quirk.. */
pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0x80);
#endif
if (pci_request_regions(pdev, DRV_NAME)) {
pr_err("Failed to request PCI regions\n");
err = -ENODEV;
goto err_out_disable;
}
/* Init system & device */
db = netdev_priv(dev);
/* Allocate Tx/Rx descriptor memory */
db->desc_pool_ptr = pci_alloc_consistent(pdev, sizeof(struct tx_desc) *
DESC_ALL_CNT + 0x20, &db->desc_pool_dma_ptr);
if (!db->desc_pool_ptr)
goto err_out_res;
db->buf_pool_ptr = pci_alloc_consistent(pdev, TX_BUF_ALLOC *
TX_DESC_CNT + 4, &db->buf_pool_dma_ptr);
if (!db->buf_pool_ptr)
goto err_out_free_desc;
db->first_tx_desc = (struct tx_desc *) db->desc_pool_ptr;
db->first_tx_desc_dma = db->desc_pool_dma_ptr;
db->buf_pool_start = db->buf_pool_ptr;
db->buf_pool_dma_start = db->buf_pool_dma_ptr;
db->chip_id = ent->driver_data;
db->ioaddr = pci_resource_start(pdev, 0);
db->chip_revision = pdev->revision;
db->wol_mode = 0;
db->pdev = pdev;
dev->base_addr = db->ioaddr;
dev->irq = pdev->irq;
pci_set_drvdata(pdev, dev);
dev->netdev_ops = &netdev_ops;
dev->ethtool_ops = &netdev_ethtool_ops;
netif_carrier_off(dev);
spin_lock_init(&db->lock);
pci_read_config_dword(pdev, 0x50, &pci_pmr);
pci_pmr &= 0x70000;
if ( (pci_pmr == 0x10000) && (db->chip_revision == 0x31) )
db->chip_type = 1; /* DM9102A E3 */
else
db->chip_type = 0;
/* read 64 word srom data */
for (i = 0; i < 64; i++)
((__le16 *) db->srom)[i] =
cpu_to_le16(read_srom_word(db->ioaddr, i));
/* Set Node address */
for (i = 0; i < 6; i++)
dev->dev_addr[i] = db->srom[20 + i];
err = register_netdev (dev);
if (err)
goto err_out_free_buf;
dev_info(&dev->dev, "Davicom DM%04lx at pci%s, %pM, irq %d\n",
ent->driver_data >> 16,
pci_name(pdev), dev->dev_addr, dev->irq);
pci_set_master(pdev);
return 0;
err_out_free_buf:
pci_free_consistent(pdev, TX_BUF_ALLOC * TX_DESC_CNT + 4,
db->buf_pool_ptr, db->buf_pool_dma_ptr);
err_out_free_desc:
pci_free_consistent(pdev, sizeof(struct tx_desc) * DESC_ALL_CNT + 0x20,
db->desc_pool_ptr, db->desc_pool_dma_ptr);
err_out_res:
pci_release_regions(pdev);
err_out_disable:
pci_disable_device(pdev);
err_out_free:
pci_set_drvdata(pdev, NULL);
free_netdev(dev);
return err;
}
static void __devexit dmfe_remove_one (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct dmfe_board_info *db = netdev_priv(dev);
DMFE_DBUG(0, "dmfe_remove_one()", 0);
if (dev) {
unregister_netdev(dev);
pci_free_consistent(db->pdev, sizeof(struct tx_desc) *
DESC_ALL_CNT + 0x20, db->desc_pool_ptr,
db->desc_pool_dma_ptr);
pci_free_consistent(db->pdev, TX_BUF_ALLOC * TX_DESC_CNT + 4,
db->buf_pool_ptr, db->buf_pool_dma_ptr);
pci_release_regions(pdev);
free_netdev(dev); /* free board information */
pci_set_drvdata(pdev, NULL);
}
DMFE_DBUG(0, "dmfe_remove_one() exit", 0);
}
/*
* Open the interface.
* The interface is opened whenever "ifconfig" actives it.
*/
static int dmfe_open(struct DEVICE *dev)
{
int ret;
struct dmfe_board_info *db = netdev_priv(dev);
DMFE_DBUG(0, "dmfe_open", 0);
ret = request_irq(dev->irq, dmfe_interrupt,
IRQF_SHARED, dev->name, dev);
if (ret)
return ret;
/* system variable init */
db->cr6_data = CR6_DEFAULT | dmfe_cr6_user_set;
db->tx_packet_cnt = 0;
db->tx_queue_cnt = 0;
db->rx_avail_cnt = 0;
db->wait_reset = 0;
db->first_in_callback = 0;
db->NIC_capability = 0xf; /* All capability*/
db->PHY_reg4 = 0x1e0;
/* CR6 operation mode decision */
if ( !chkmode || (db->chip_id == PCI_DM9132_ID) ||
(db->chip_revision >= 0x30) ) {
db->cr6_data |= DMFE_TXTH_256;
db->cr0_data = CR0_DEFAULT;
db->dm910x_chk_mode=4; /* Enter the normal mode */
} else {
db->cr6_data |= CR6_SFT; /* Store & Forward mode */
db->cr0_data = 0;
db->dm910x_chk_mode = 1; /* Enter the check mode */
}
/* Initialize DM910X board */
dmfe_init_dm910x(dev);
/* Active System Interface */
netif_wake_queue(dev);
/* set and active a timer process */
init_timer(&db->timer);
db->timer.expires = DMFE_TIMER_WUT + HZ * 2;
db->timer.data = (unsigned long)dev;
db->timer.function = dmfe_timer;
add_timer(&db->timer);
return 0;
}
/* Initialize DM910X board
* Reset DM910X board
* Initialize TX/Rx descriptor chain structure
* Send the set-up frame
* Enable Tx/Rx machine
*/
static void dmfe_init_dm910x(struct DEVICE *dev)
{
struct dmfe_board_info *db = netdev_priv(dev);
unsigned long ioaddr = db->ioaddr;
DMFE_DBUG(0, "dmfe_init_dm910x()", 0);
/* Reset DM910x MAC controller */
outl(DM910X_RESET, ioaddr + DCR0); /* RESET MAC */
udelay(100);
outl(db->cr0_data, ioaddr + DCR0);
udelay(5);
/* Phy addr : DM910(A)2/DM9132/9801, phy address = 1 */
db->phy_addr = 1;
/* Parser SROM and media mode */
dmfe_parse_srom(db);
db->media_mode = dmfe_media_mode;
/* RESET Phyxcer Chip by GPR port bit 7 */
outl(0x180, ioaddr + DCR12); /* Let bit 7 output port */
if (db->chip_id == PCI_DM9009_ID) {
outl(0x80, ioaddr + DCR12); /* Issue RESET signal */
mdelay(300); /* Delay 300 ms */
}
outl(0x0, ioaddr + DCR12); /* Clear RESET signal */
/* Process Phyxcer Media Mode */
if ( !(db->media_mode & 0x10) ) /* Force 1M mode */
dmfe_set_phyxcer(db);
/* Media Mode Process */
if ( !(db->media_mode & DMFE_AUTO) )
db->op_mode = db->media_mode; /* Force Mode */
/* Initialize Transmit/Receive decriptor and CR3/4 */
dmfe_descriptor_init(dev, ioaddr);
/* Init CR6 to program DM910x operation */
update_cr6(db->cr6_data, ioaddr);
/* Send setup frame */
if (db->chip_id == PCI_DM9132_ID)
dm9132_id_table(dev); /* DM9132 */
else
send_filter_frame(dev); /* DM9102/DM9102A */
/* Init CR7, interrupt active bit */
db->cr7_data = CR7_DEFAULT;
outl(db->cr7_data, ioaddr + DCR7);
/* Init CR15, Tx jabber and Rx watchdog timer */
outl(db->cr15_data, ioaddr + DCR15);
/* Enable DM910X Tx/Rx function */
db->cr6_data |= CR6_RXSC | CR6_TXSC | 0x40000;
update_cr6(db->cr6_data, ioaddr);
}
/*
* Hardware start transmission.
* Send a packet to media from the upper layer.
*/
static netdev_tx_t dmfe_start_xmit(struct sk_buff *skb,
struct DEVICE *dev)
{
struct dmfe_board_info *db = netdev_priv(dev);
struct tx_desc *txptr;
unsigned long flags;
DMFE_DBUG(0, "dmfe_start_xmit", 0);
/* Too large packet check */
if (skb->len > MAX_PACKET_SIZE) {
pr_err("big packet = %d\n", (u16)skb->len);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/* Resource flag check */
netif_stop_queue(dev);
spin_lock_irqsave(&db->lock, flags);
/* No Tx resource check, it never happen nromally */
if (db->tx_queue_cnt >= TX_FREE_DESC_CNT) {
spin_unlock_irqrestore(&db->lock, flags);
pr_err("No Tx resource %ld\n", db->tx_queue_cnt);
return NETDEV_TX_BUSY;
}
/* Disable NIC interrupt */
outl(0, dev->base_addr + DCR7);
/* transmit this packet */
txptr = db->tx_insert_ptr;
skb_copy_from_linear_data(skb, txptr->tx_buf_ptr, skb->len);
txptr->tdes1 = cpu_to_le32(0xe1000000 | skb->len);
/* Point to next transmit free descriptor */
db->tx_insert_ptr = txptr->next_tx_desc;
/* Transmit Packet Process */
if ( (!db->tx_queue_cnt) && (db->tx_packet_cnt < TX_MAX_SEND_CNT) ) {
txptr->tdes0 = cpu_to_le32(0x80000000); /* Set owner bit */
db->tx_packet_cnt++; /* Ready to send */
outl(0x1, dev->base_addr + DCR1); /* Issue Tx polling */
dev->trans_start = jiffies; /* saved time stamp */
} else {
db->tx_queue_cnt++; /* queue TX packet */
outl(0x1, dev->base_addr + DCR1); /* Issue Tx polling */
}
/* Tx resource check */
if ( db->tx_queue_cnt < TX_FREE_DESC_CNT )
netif_wake_queue(dev);
/* Restore CR7 to enable interrupt */
spin_unlock_irqrestore(&db->lock, flags);
outl(db->cr7_data, dev->base_addr + DCR7);
/* free this SKB */
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/*
* Stop the interface.
* The interface is stopped when it is brought.
*/
static int dmfe_stop(struct DEVICE *dev)
{
struct dmfe_board_info *db = netdev_priv(dev);
unsigned long ioaddr = dev->base_addr;
DMFE_DBUG(0, "dmfe_stop", 0);
/* disable system */
netif_stop_queue(dev);
/* deleted timer */
del_timer_sync(&db->timer);
/* Reset & stop DM910X board */
outl(DM910X_RESET, ioaddr + DCR0);
udelay(5);
phy_write(db->ioaddr, db->phy_addr, 0, 0x8000, db->chip_id);
/* free interrupt */
free_irq(dev->irq, dev);
/* free allocated rx buffer */
dmfe_free_rxbuffer(db);
#if 0
/* show statistic counter */
printk("FU:%lx EC:%lx LC:%lx NC:%lx LOC:%lx TXJT:%lx RESET:%lx RCR8:%lx FAL:%lx TT:%lx\n",
db->tx_fifo_underrun, db->tx_excessive_collision,
db->tx_late_collision, db->tx_no_carrier, db->tx_loss_carrier,
db->tx_jabber_timeout, db->reset_count, db->reset_cr8,
db->reset_fatal, db->reset_TXtimeout);
#endif
return 0;
}
/*
* DM9102 insterrupt handler
* receive the packet to upper layer, free the transmitted packet
*/
static irqreturn_t dmfe_interrupt(int irq, void *dev_id)
{
struct DEVICE *dev = dev_id;
struct dmfe_board_info *db = netdev_priv(dev);
unsigned long ioaddr = dev->base_addr;
unsigned long flags;
DMFE_DBUG(0, "dmfe_interrupt()", 0);
spin_lock_irqsave(&db->lock, flags);
/* Got DM910X status */
db->cr5_data = inl(ioaddr + DCR5);
outl(db->cr5_data, ioaddr + DCR5);
if ( !(db->cr5_data & 0xc1) ) {
spin_unlock_irqrestore(&db->lock, flags);
return IRQ_HANDLED;
}
/* Disable all interrupt in CR7 to solve the interrupt edge problem */
outl(0, ioaddr + DCR7);
/* Check system status */
if (db->cr5_data & 0x2000) {
/* system bus error happen */
DMFE_DBUG(1, "System bus error happen. CR5=", db->cr5_data);
db->reset_fatal++;
db->wait_reset = 1; /* Need to RESET */
spin_unlock_irqrestore(&db->lock, flags);
return IRQ_HANDLED;
}
/* Received the coming packet */
if ( (db->cr5_data & 0x40) && db->rx_avail_cnt )
dmfe_rx_packet(dev, db);
/* reallocate rx descriptor buffer */
if (db->rx_avail_cnt<RX_DESC_CNT)
allocate_rx_buffer(dev);
/* Free the transmitted descriptor */
if ( db->cr5_data & 0x01)
dmfe_free_tx_pkt(dev, db);
/* Mode Check */
if (db->dm910x_chk_mode & 0x2) {
db->dm910x_chk_mode = 0x4;
db->cr6_data |= 0x100;
update_cr6(db->cr6_data, db->ioaddr);
}
/* Restore CR7 to enable interrupt mask */
outl(db->cr7_data, ioaddr + DCR7);
spin_unlock_irqrestore(&db->lock, flags);
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* 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 poll_dmfe (struct net_device *dev)
{
/* disable_irq here is not very nice, but with the lockless
interrupt handler we have no other choice. */
disable_irq(dev->irq);
dmfe_interrupt (dev->irq, dev);
enable_irq(dev->irq);
}
#endif
/*
* Free TX resource after TX complete
*/
static void dmfe_free_tx_pkt(struct DEVICE *dev, struct dmfe_board_info * db)
{
struct tx_desc *txptr;
unsigned long ioaddr = dev->base_addr;
u32 tdes0;
txptr = db->tx_remove_ptr;
while(db->tx_packet_cnt) {
tdes0 = le32_to_cpu(txptr->tdes0);
if (tdes0 & 0x80000000)
break;
/* A packet sent completed */
db->tx_packet_cnt--;
dev->stats.tx_packets++;
/* Transmit statistic counter */
if ( tdes0 != 0x7fffffff ) {
dev->stats.collisions += (tdes0 >> 3) & 0xf;
dev->stats.tx_bytes += le32_to_cpu(txptr->tdes1) & 0x7ff;
if (tdes0 & TDES0_ERR_MASK) {
dev->stats.tx_errors++;
if (tdes0 & 0x0002) { /* UnderRun */
db->tx_fifo_underrun++;
if ( !(db->cr6_data & CR6_SFT) ) {
db->cr6_data = db->cr6_data | CR6_SFT;
update_cr6(db->cr6_data, db->ioaddr);
}
}
if (tdes0 & 0x0100)
db->tx_excessive_collision++;
if (tdes0 & 0x0200)
db->tx_late_collision++;
if (tdes0 & 0x0400)
db->tx_no_carrier++;
if (tdes0 & 0x0800)
db->tx_loss_carrier++;
if (tdes0 & 0x4000)
db->tx_jabber_timeout++;
}
}
txptr = txptr->next_tx_desc;
}/* End of while */
/* Update TX remove pointer to next */
db->tx_remove_ptr = txptr;
/* Send the Tx packet in queue */
if ( (db->tx_packet_cnt < TX_MAX_SEND_CNT) && db->tx_queue_cnt ) {
txptr->tdes0 = cpu_to_le32(0x80000000); /* Set owner bit */
db->tx_packet_cnt++; /* Ready to send */
db->tx_queue_cnt--;
outl(0x1, ioaddr + DCR1); /* Issue Tx polling */
dev->trans_start = jiffies; /* saved time stamp */
}
/* Resource available check */
if ( db->tx_queue_cnt < TX_WAKE_DESC_CNT )
netif_wake_queue(dev); /* Active upper layer, send again */
}
/*
* Calculate the CRC valude of the Rx packet
* flag = 1 : return the reverse CRC (for the received packet CRC)
* 0 : return the normal CRC (for Hash Table index)
*/
static inline u32 cal_CRC(unsigned char * Data, unsigned int Len, u8 flag)
{
u32 crc = crc32(~0, Data, Len);
if (flag) crc = ~crc;
return crc;
}
/*
* Receive the come packet and pass to upper layer
*/
static void dmfe_rx_packet(struct DEVICE *dev, struct dmfe_board_info * db)
{
struct rx_desc *rxptr;
struct sk_buff *skb, *newskb;
int rxlen;
u32 rdes0;
rxptr = db->rx_ready_ptr;
while(db->rx_avail_cnt) {
rdes0 = le32_to_cpu(rxptr->rdes0);
if (rdes0 & 0x80000000) /* packet owner check */
break;
db->rx_avail_cnt--;
db->interval_rx_cnt++;
pci_unmap_single(db->pdev, le32_to_cpu(rxptr->rdes2),
RX_ALLOC_SIZE, PCI_DMA_FROMDEVICE);
if ( (rdes0 & 0x300) != 0x300) {
/* A packet without First/Last flag */
/* reuse this SKB */
DMFE_DBUG(0, "Reuse SK buffer, rdes0", rdes0);
dmfe_reuse_skb(db, rxptr->rx_skb_ptr);
} else {
/* A packet with First/Last flag */
rxlen = ( (rdes0 >> 16) & 0x3fff) - 4;
/* error summary bit check */
if (rdes0 & 0x8000) {
/* This is a error packet */
dev->stats.rx_errors++;
if (rdes0 & 1)
dev->stats.rx_fifo_errors++;
if (rdes0 & 2)
dev->stats.rx_crc_errors++;
if (rdes0 & 0x80)
dev->stats.rx_length_errors++;
}
if ( !(rdes0 & 0x8000) ||
((db->cr6_data & CR6_PM) && (rxlen>6)) ) {
skb = rxptr->rx_skb_ptr;
/* Received Packet CRC check need or not */
if ( (db->dm910x_chk_mode & 1) &&
(cal_CRC(skb->data, rxlen, 1) !=
(*(u32 *) (skb->data+rxlen) ))) { /* FIXME (?) */
/* Found a error received packet */
dmfe_reuse_skb(db, rxptr->rx_skb_ptr);
db->dm910x_chk_mode = 3;
} else {
/* Good packet, send to upper layer */
/* Shorst packet used new SKB */
if ((rxlen < RX_COPY_SIZE) &&
((newskb = netdev_alloc_skb(dev, rxlen + 2))
!= NULL)) {
skb = newskb;
/* size less than COPY_SIZE, allocate a rxlen SKB */
skb_reserve(skb, 2); /* 16byte align */
skb_copy_from_linear_data(rxptr->rx_skb_ptr,
skb_put(skb, rxlen),
rxlen);
dmfe_reuse_skb(db, rxptr->rx_skb_ptr);
} else
skb_put(skb, rxlen);
skb->protocol = eth_type_trans(skb, dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += rxlen;
}
} else {
/* Reuse SKB buffer when the packet is error */
DMFE_DBUG(0, "Reuse SK buffer, rdes0", rdes0);
dmfe_reuse_skb(db, rxptr->rx_skb_ptr);
}
}
rxptr = rxptr->next_rx_desc;
}
db->rx_ready_ptr = rxptr;
}
/*
* Set DM910X multicast address
*/
static void dmfe_set_filter_mode(struct DEVICE * dev)
{
struct dmfe_board_info *db = netdev_priv(dev);
unsigned long flags;
int mc_count = netdev_mc_count(dev);
DMFE_DBUG(0, "dmfe_set_filter_mode()", 0);
spin_lock_irqsave(&db->lock, flags);
if (dev->flags & IFF_PROMISC) {
DMFE_DBUG(0, "Enable PROM Mode", 0);
db->cr6_data |= CR6_PM | CR6_PBF;
update_cr6(db->cr6_data, db->ioaddr);
spin_unlock_irqrestore(&db->lock, flags);
return;
}
if (dev->flags & IFF_ALLMULTI || mc_count > DMFE_MAX_MULTICAST) {
DMFE_DBUG(0, "Pass all multicast address", mc_count);
db->cr6_data &= ~(CR6_PM | CR6_PBF);
db->cr6_data |= CR6_PAM;
spin_unlock_irqrestore(&db->lock, flags);
return;
}
DMFE_DBUG(0, "Set multicast address", mc_count);
if (db->chip_id == PCI_DM9132_ID)
dm9132_id_table(dev); /* DM9132 */
else
send_filter_frame(dev); /* DM9102/DM9102A */
spin_unlock_irqrestore(&db->lock, flags);
}
/*
* Ethtool interace
*/
static void dmfe_ethtool_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct dmfe_board_info *np = netdev_priv(dev);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
if (np->pdev)
strlcpy(info->bus_info, pci_name(np->pdev),
sizeof(info->bus_info));
else
sprintf(info->bus_info, "EISA 0x%lx %d",
dev->base_addr, dev->irq);
}
static int dmfe_ethtool_set_wol(struct net_device *dev,
struct ethtool_wolinfo *wolinfo)
{
struct dmfe_board_info *db = netdev_priv(dev);
if (wolinfo->wolopts & (WAKE_UCAST | WAKE_MCAST | WAKE_BCAST |
WAKE_ARP | WAKE_MAGICSECURE))
return -EOPNOTSUPP;
db->wol_mode = wolinfo->wolopts;
return 0;
}
static void dmfe_ethtool_get_wol(struct net_device *dev,
struct ethtool_wolinfo *wolinfo)
{
struct dmfe_board_info *db = netdev_priv(dev);
wolinfo->supported = WAKE_PHY | WAKE_MAGIC;
wolinfo->wolopts = db->wol_mode;
}
static const struct ethtool_ops netdev_ethtool_ops = {
.get_drvinfo = dmfe_ethtool_get_drvinfo,
.get_link = ethtool_op_get_link,
.set_wol = dmfe_ethtool_set_wol,
.get_wol = dmfe_ethtool_get_wol,
};
/*
* A periodic timer routine
* Dynamic media sense, allocate Rx buffer...
*/
static void dmfe_timer(unsigned long data)
{
u32 tmp_cr8;
unsigned char tmp_cr12;
struct DEVICE *dev = (struct DEVICE *) data;
struct dmfe_board_info *db = netdev_priv(dev);
unsigned long flags;
int link_ok, link_ok_phy;
DMFE_DBUG(0, "dmfe_timer()", 0);
spin_lock_irqsave(&db->lock, flags);
/* Media mode process when Link OK before enter this route */
if (db->first_in_callback == 0) {
db->first_in_callback = 1;
if (db->chip_type && (db->chip_id==PCI_DM9102_ID)) {
db->cr6_data &= ~0x40000;
update_cr6(db->cr6_data, db->ioaddr);
phy_write(db->ioaddr,
db->phy_addr, 0, 0x1000, db->chip_id);
db->cr6_data |= 0x40000;
update_cr6(db->cr6_data, db->ioaddr);
db->timer.expires = DMFE_TIMER_WUT + HZ * 2;
add_timer(&db->timer);
spin_unlock_irqrestore(&db->lock, flags);
return;
}
}
/* Operating Mode Check */
if ( (db->dm910x_chk_mode & 0x1) &&
(dev->stats.rx_packets > MAX_CHECK_PACKET) )
db->dm910x_chk_mode = 0x4;
/* Dynamic reset DM910X : system error or transmit time-out */
tmp_cr8 = inl(db->ioaddr + DCR8);
if ( (db->interval_rx_cnt==0) && (tmp_cr8) ) {
db->reset_cr8++;
db->wait_reset = 1;
}
db->interval_rx_cnt = 0;
/* TX polling kick monitor */
if ( db->tx_packet_cnt &&
time_after(jiffies, dev_trans_start(dev) + DMFE_TX_KICK) ) {
outl(0x1, dev->base_addr + DCR1); /* Tx polling again */
/* TX Timeout */
if (time_after(jiffies, dev_trans_start(dev) + DMFE_TX_TIMEOUT) ) {
db->reset_TXtimeout++;
db->wait_reset = 1;
dev_warn(&dev->dev, "Tx timeout - resetting\n");
}
}
if (db->wait_reset) {
DMFE_DBUG(0, "Dynamic Reset device", db->tx_packet_cnt);
db->reset_count++;
dmfe_dynamic_reset(dev);
db->first_in_callback = 0;
db->timer.expires = DMFE_TIMER_WUT;
add_timer(&db->timer);
spin_unlock_irqrestore(&db->lock, flags);
return;
}
/* Link status check, Dynamic media type change */
if (db->chip_id == PCI_DM9132_ID)
tmp_cr12 = inb(db->ioaddr + DCR9 + 3); /* DM9132 */
else
tmp_cr12 = inb(db->ioaddr + DCR12); /* DM9102/DM9102A */
if ( ((db->chip_id == PCI_DM9102_ID) &&
(db->chip_revision == 0x30)) ||
((db->chip_id == PCI_DM9132_ID) &&
(db->chip_revision == 0x10)) ) {
/* DM9102A Chip */
if (tmp_cr12 & 2)
link_ok = 0;
else
link_ok = 1;
}
else
/*0x43 is used instead of 0x3 because bit 6 should represent
link status of external PHY */
link_ok = (tmp_cr12 & 0x43) ? 1 : 0;
/* If chip reports that link is failed it could be because external
PHY link status pin is not connected correctly to chip
To be sure ask PHY too.
*/
/* need a dummy read because of PHY's register latch*/
phy_read (db->ioaddr, db->phy_addr, 1, db->chip_id);
link_ok_phy = (phy_read (db->ioaddr,
db->phy_addr, 1, db->chip_id) & 0x4) ? 1 : 0;
if (link_ok_phy != link_ok) {
DMFE_DBUG (0, "PHY and chip report different link status", 0);
link_ok = link_ok | link_ok_phy;
}
if ( !link_ok && netif_carrier_ok(dev)) {
/* Link Failed */
DMFE_DBUG(0, "Link Failed", tmp_cr12);
netif_carrier_off(dev);
/* For Force 10/100M Half/Full mode: Enable Auto-Nego mode */
/* AUTO or force 1M Homerun/Longrun don't need */
if ( !(db->media_mode & 0x38) )
phy_write(db->ioaddr, db->phy_addr,
0, 0x1000, db->chip_id);
/* AUTO mode, if INT phyxcer link failed, select EXT device */
if (db->media_mode & DMFE_AUTO) {
/* 10/100M link failed, used 1M Home-Net */
db->cr6_data|=0x00040000; /* bit18=1, MII */
db->cr6_data&=~0x00000200; /* bit9=0, HD mode */
update_cr6(db->cr6_data, db->ioaddr);
}
} else if (!netif_carrier_ok(dev)) {
DMFE_DBUG(0, "Link link OK", tmp_cr12);
/* Auto Sense Speed */
if ( !(db->media_mode & DMFE_AUTO) || !dmfe_sense_speed(db)) {
netif_carrier_on(dev);
SHOW_MEDIA_TYPE(db->op_mode);
}
dmfe_process_mode(db);
}
/* HPNA remote command check */
if (db->HPNA_command & 0xf00) {
db->HPNA_timer--;
if (!db->HPNA_timer)
dmfe_HPNA_remote_cmd_chk(db);
}
/* Timer active again */
db->timer.expires = DMFE_TIMER_WUT;
add_timer(&db->timer);
spin_unlock_irqrestore(&db->lock, flags);
}
/*
* Dynamic reset the DM910X board
* Stop DM910X board
* Free Tx/Rx allocated memory
* Reset DM910X board
* Re-initialize DM910X board
*/
static void dmfe_dynamic_reset(struct DEVICE *dev)
{
struct dmfe_board_info *db = netdev_priv(dev);
DMFE_DBUG(0, "dmfe_dynamic_reset()", 0);
/* Sopt MAC controller */
db->cr6_data &= ~(CR6_RXSC | CR6_TXSC); /* Disable Tx/Rx */
update_cr6(db->cr6_data, dev->base_addr);
outl(0, dev->base_addr + DCR7); /* Disable Interrupt */
outl(inl(dev->base_addr + DCR5), dev->base_addr + DCR5);
/* Disable upper layer interface */
netif_stop_queue(dev);
/* Free Rx Allocate buffer */
dmfe_free_rxbuffer(db);
/* system variable init */
db->tx_packet_cnt = 0;
db->tx_queue_cnt = 0;
db->rx_avail_cnt = 0;
netif_carrier_off(dev);
db->wait_reset = 0;
/* Re-initialize DM910X board */
dmfe_init_dm910x(dev);
/* Restart upper layer interface */
netif_wake_queue(dev);
}
/*
* free all allocated rx buffer
*/
static void dmfe_free_rxbuffer(struct dmfe_board_info * db)
{
DMFE_DBUG(0, "dmfe_free_rxbuffer()", 0);
/* free allocated rx buffer */
while (db->rx_avail_cnt) {
dev_kfree_skb(db->rx_ready_ptr->rx_skb_ptr);
db->rx_ready_ptr = db->rx_ready_ptr->next_rx_desc;
db->rx_avail_cnt--;
}
}
/*
* Reuse the SK buffer
*/
static void dmfe_reuse_skb(struct dmfe_board_info *db, struct sk_buff * skb)
{
struct rx_desc *rxptr = db->rx_insert_ptr;
if (!(rxptr->rdes0 & cpu_to_le32(0x80000000))) {
rxptr->rx_skb_ptr = skb;
rxptr->rdes2 = cpu_to_le32( pci_map_single(db->pdev,
skb->data, RX_ALLOC_SIZE, PCI_DMA_FROMDEVICE) );
wmb();
rxptr->rdes0 = cpu_to_le32(0x80000000);
db->rx_avail_cnt++;
db->rx_insert_ptr = rxptr->next_rx_desc;
} else
DMFE_DBUG(0, "SK Buffer reuse method error", db->rx_avail_cnt);
}
/*
* Initialize transmit/Receive descriptor
* Using Chain structure, and allocate Tx/Rx buffer
*/
static void dmfe_descriptor_init(struct net_device *dev, unsigned long ioaddr)
{
struct dmfe_board_info *db = netdev_priv(dev);
struct tx_desc *tmp_tx;
struct rx_desc *tmp_rx;
unsigned char *tmp_buf;
dma_addr_t tmp_tx_dma, tmp_rx_dma;
dma_addr_t tmp_buf_dma;
int i;
DMFE_DBUG(0, "dmfe_descriptor_init()", 0);
/* tx descriptor start pointer */
db->tx_insert_ptr = db->first_tx_desc;
db->tx_remove_ptr = db->first_tx_desc;
outl(db->first_tx_desc_dma, ioaddr + DCR4); /* TX DESC address */
/* rx descriptor start pointer */
db->first_rx_desc = (void *)db->first_tx_desc +
sizeof(struct tx_desc) * TX_DESC_CNT;
db->first_rx_desc_dma = db->first_tx_desc_dma +
sizeof(struct tx_desc) * TX_DESC_CNT;
db->rx_insert_ptr = db->first_rx_desc;
db->rx_ready_ptr = db->first_rx_desc;
outl(db->first_rx_desc_dma, ioaddr + DCR3); /* RX DESC address */
/* Init Transmit chain */
tmp_buf = db->buf_pool_start;
tmp_buf_dma = db->buf_pool_dma_start;
tmp_tx_dma = db->first_tx_desc_dma;
for (tmp_tx = db->first_tx_desc, i = 0; i < TX_DESC_CNT; i++, tmp_tx++) {
tmp_tx->tx_buf_ptr = tmp_buf;
tmp_tx->tdes0 = cpu_to_le32(0);
tmp_tx->tdes1 = cpu_to_le32(0x81000000); /* IC, chain */
tmp_tx->tdes2 = cpu_to_le32(tmp_buf_dma);
tmp_tx_dma += sizeof(struct tx_desc);
tmp_tx->tdes3 = cpu_to_le32(tmp_tx_dma);
tmp_tx->next_tx_desc = tmp_tx + 1;
tmp_buf = tmp_buf + TX_BUF_ALLOC;
tmp_buf_dma = tmp_buf_dma + TX_BUF_ALLOC;
}
(--tmp_tx)->tdes3 = cpu_to_le32(db->first_tx_desc_dma);
tmp_tx->next_tx_desc = db->first_tx_desc;
/* Init Receive descriptor chain */
tmp_rx_dma=db->first_rx_desc_dma;
for (tmp_rx = db->first_rx_desc, i = 0; i < RX_DESC_CNT; i++, tmp_rx++) {
tmp_rx->rdes0 = cpu_to_le32(0);
tmp_rx->rdes1 = cpu_to_le32(0x01000600);
tmp_rx_dma += sizeof(struct rx_desc);
tmp_rx->rdes3 = cpu_to_le32(tmp_rx_dma);
tmp_rx->next_rx_desc = tmp_rx + 1;
}
(--tmp_rx)->rdes3 = cpu_to_le32(db->first_rx_desc_dma);
tmp_rx->next_rx_desc = db->first_rx_desc;
/* pre-allocate Rx buffer */
allocate_rx_buffer(dev);
}
/*
* Update CR6 value
* Firstly stop DM910X , then written value and start
*/
static void update_cr6(u32 cr6_data, unsigned long ioaddr)
{
u32 cr6_tmp;
cr6_tmp = cr6_data & ~0x2002; /* stop Tx/Rx */
outl(cr6_tmp, ioaddr + DCR6);
udelay(5);
outl(cr6_data, ioaddr + DCR6);
udelay(5);
}
/*
* Send a setup frame for DM9132
* This setup frame initialize DM910X address filter mode
*/
static void dm9132_id_table(struct DEVICE *dev)
{
struct netdev_hw_addr *ha;
u16 * addrptr;
unsigned long ioaddr = dev->base_addr+0xc0; /* ID Table */
u32 hash_val;
u16 i, hash_table[4];
DMFE_DBUG(0, "dm9132_id_table()", 0);
/* Node address */
addrptr = (u16 *) dev->dev_addr;
outw(addrptr[0], ioaddr);
ioaddr += 4;
outw(addrptr[1], ioaddr);
ioaddr += 4;
outw(addrptr[2], ioaddr);
ioaddr += 4;
/* Clear Hash Table */
memset(hash_table, 0, sizeof(hash_table));
/* broadcast address */
hash_table[3] = 0x8000;
/* the multicast address in Hash Table : 64 bits */
netdev_for_each_mc_addr(ha, dev) {
hash_val = cal_CRC((char *) ha->addr, 6, 0) & 0x3f;
hash_table[hash_val / 16] |= (u16) 1 << (hash_val % 16);
}
/* Write the hash table to MAC MD table */
for (i = 0; i < 4; i++, ioaddr += 4)
outw(hash_table[i], ioaddr);
}
/*
* Send a setup frame for DM9102/DM9102A
* This setup frame initialize DM910X address filter mode
*/
static void send_filter_frame(struct DEVICE *dev)
{
struct dmfe_board_info *db = netdev_priv(dev);
struct netdev_hw_addr *ha;
struct tx_desc *txptr;
u16 * addrptr;
u32 * suptr;
int i;
DMFE_DBUG(0, "send_filter_frame()", 0);
txptr = db->tx_insert_ptr;
suptr = (u32 *) txptr->tx_buf_ptr;
/* Node address */
addrptr = (u16 *) dev->dev_addr;
*suptr++ = addrptr[0];
*suptr++ = addrptr[1];
*suptr++ = addrptr[2];
/* broadcast address */
*suptr++ = 0xffff;
*suptr++ = 0xffff;
*suptr++ = 0xffff;
/* fit the multicast address */
netdev_for_each_mc_addr(ha, dev) {
addrptr = (u16 *) ha->addr;
*suptr++ = addrptr[0];
*suptr++ = addrptr[1];
*suptr++ = addrptr[2];
}
for (i = netdev_mc_count(dev); i < 14; i++) {
*suptr++ = 0xffff;
*suptr++ = 0xffff;
*suptr++ = 0xffff;
}
/* prepare the setup frame */
db->tx_insert_ptr = txptr->next_tx_desc;
txptr->tdes1 = cpu_to_le32(0x890000c0);
/* Resource Check and Send the setup packet */
if (!db->tx_packet_cnt) {
/* Resource Empty */
db->tx_packet_cnt++;
txptr->tdes0 = cpu_to_le32(0x80000000);
update_cr6(db->cr6_data | 0x2000, dev->base_addr);
outl(0x1, dev->base_addr + DCR1); /* Issue Tx polling */
update_cr6(db->cr6_data, dev->base_addr);
dev->trans_start = jiffies;
} else
db->tx_queue_cnt++; /* Put in TX queue */
}
/*
* Allocate rx buffer,
* As possible as allocate maxiumn Rx buffer
*/
static void allocate_rx_buffer(struct net_device *dev)
{
struct dmfe_board_info *db = netdev_priv(dev);
struct rx_desc *rxptr;
struct sk_buff *skb;
rxptr = db->rx_insert_ptr;
while(db->rx_avail_cnt < RX_DESC_CNT) {
if ( ( skb = netdev_alloc_skb(dev, RX_ALLOC_SIZE) ) == NULL )
break;
rxptr->rx_skb_ptr = skb; /* FIXME (?) */
rxptr->rdes2 = cpu_to_le32( pci_map_single(db->pdev, skb->data,
RX_ALLOC_SIZE, PCI_DMA_FROMDEVICE) );
wmb();
rxptr->rdes0 = cpu_to_le32(0x80000000);
rxptr = rxptr->next_rx_desc;
db->rx_avail_cnt++;
}
db->rx_insert_ptr = rxptr;
}
/*
* Read one word data from the serial ROM
*/
static u16 read_srom_word(long ioaddr, int offset)
{
int i;
u16 srom_data = 0;
long cr9_ioaddr = ioaddr + DCR9;
outl(CR9_SROM_READ, cr9_ioaddr);
outl(CR9_SROM_READ | CR9_SRCS, cr9_ioaddr);
/* Send the Read Command 110b */
SROM_CLK_WRITE(SROM_DATA_1, cr9_ioaddr);
SROM_CLK_WRITE(SROM_DATA_1, cr9_ioaddr);
SROM_CLK_WRITE(SROM_DATA_0, cr9_ioaddr);
/* Send the offset */
for (i = 5; i >= 0; i--) {
srom_data = (offset & (1 << i)) ? SROM_DATA_1 : SROM_DATA_0;
SROM_CLK_WRITE(srom_data, cr9_ioaddr);
}
outl(CR9_SROM_READ | CR9_SRCS, cr9_ioaddr);
for (i = 16; i > 0; i--) {
outl(CR9_SROM_READ | CR9_SRCS | CR9_SRCLK, cr9_ioaddr);
udelay(5);
srom_data = (srom_data << 1) |
((inl(cr9_ioaddr) & CR9_CRDOUT) ? 1 : 0);
outl(CR9_SROM_READ | CR9_SRCS, cr9_ioaddr);
udelay(5);
}
outl(CR9_SROM_READ, cr9_ioaddr);
return srom_data;
}
/*
* Auto sense the media mode
*/
static u8 dmfe_sense_speed(struct dmfe_board_info * db)
{
u8 ErrFlag = 0;
u16 phy_mode;
/* CR6 bit18=0, select 10/100M */
update_cr6( (db->cr6_data & ~0x40000), db->ioaddr);
phy_mode = phy_read(db->ioaddr, db->phy_addr, 1, db->chip_id);
phy_mode = phy_read(db->ioaddr, db->phy_addr, 1, db->chip_id);
if ( (phy_mode & 0x24) == 0x24 ) {
if (db->chip_id == PCI_DM9132_ID) /* DM9132 */
phy_mode = phy_read(db->ioaddr,
db->phy_addr, 7, db->chip_id) & 0xf000;
else /* DM9102/DM9102A */
phy_mode = phy_read(db->ioaddr,
db->phy_addr, 17, db->chip_id) & 0xf000;
switch (phy_mode) {
case 0x1000: db->op_mode = DMFE_10MHF; break;
case 0x2000: db->op_mode = DMFE_10MFD; break;
case 0x4000: db->op_mode = DMFE_100MHF; break;
case 0x8000: db->op_mode = DMFE_100MFD; break;
default: db->op_mode = DMFE_10MHF;
ErrFlag = 1;
break;
}
} else {
db->op_mode = DMFE_10MHF;
DMFE_DBUG(0, "Link Failed :", phy_mode);
ErrFlag = 1;
}
return ErrFlag;
}
/*
* Set 10/100 phyxcer capability
* AUTO mode : phyxcer register4 is NIC capability
* Force mode: phyxcer register4 is the force media
*/
static void dmfe_set_phyxcer(struct dmfe_board_info *db)
{
u16 phy_reg;
/* Select 10/100M phyxcer */
db->cr6_data &= ~0x40000;
update_cr6(db->cr6_data, db->ioaddr);
/* DM9009 Chip: Phyxcer reg18 bit12=0 */
if (db->chip_id == PCI_DM9009_ID) {
phy_reg = phy_read(db->ioaddr,
db->phy_addr, 18, db->chip_id) & ~0x1000;
phy_write(db->ioaddr,
db->phy_addr, 18, phy_reg, db->chip_id);
}
/* Phyxcer capability setting */
phy_reg = phy_read(db->ioaddr, db->phy_addr, 4, db->chip_id) & ~0x01e0;
if (db->media_mode & DMFE_AUTO) {
/* AUTO Mode */
phy_reg |= db->PHY_reg4;
} else {
/* Force Mode */
switch(db->media_mode) {
case DMFE_10MHF: phy_reg |= 0x20; break;
case DMFE_10MFD: phy_reg |= 0x40; break;
case DMFE_100MHF: phy_reg |= 0x80; break;
case DMFE_100MFD: phy_reg |= 0x100; break;
}
if (db->chip_id == PCI_DM9009_ID) phy_reg &= 0x61;
}
/* Write new capability to Phyxcer Reg4 */
if ( !(phy_reg & 0x01e0)) {
phy_reg|=db->PHY_reg4;
db->media_mode|=DMFE_AUTO;
}
phy_write(db->ioaddr, db->phy_addr, 4, phy_reg, db->chip_id);
/* Restart Auto-Negotiation */
if ( db->chip_type && (db->chip_id == PCI_DM9102_ID) )
phy_write(db->ioaddr, db->phy_addr, 0, 0x1800, db->chip_id);
if ( !db->chip_type )
phy_write(db->ioaddr, db->phy_addr, 0, 0x1200, db->chip_id);
}
/*
* Process op-mode
* AUTO mode : PHY controller in Auto-negotiation Mode
* Force mode: PHY controller in force mode with HUB
* N-way force capability with SWITCH
*/
static void dmfe_process_mode(struct dmfe_board_info *db)
{
u16 phy_reg;
/* Full Duplex Mode Check */
if (db->op_mode & 0x4)
db->cr6_data |= CR6_FDM; /* Set Full Duplex Bit */
else
db->cr6_data &= ~CR6_FDM; /* Clear Full Duplex Bit */
/* Transciver Selection */
if (db->op_mode & 0x10) /* 1M HomePNA */
db->cr6_data |= 0x40000;/* External MII select */
else
db->cr6_data &= ~0x40000;/* Internal 10/100 transciver */
update_cr6(db->cr6_data, db->ioaddr);
/* 10/100M phyxcer force mode need */
if ( !(db->media_mode & 0x18)) {
/* Forece Mode */
phy_reg = phy_read(db->ioaddr, db->phy_addr, 6, db->chip_id);
if ( !(phy_reg & 0x1) ) {
/* parter without N-Way capability */
phy_reg = 0x0;
switch(db->op_mode) {
case DMFE_10MHF: phy_reg = 0x0; break;
case DMFE_10MFD: phy_reg = 0x100; break;
case DMFE_100MHF: phy_reg = 0x2000; break;
case DMFE_100MFD: phy_reg = 0x2100; break;
}
phy_write(db->ioaddr,
db->phy_addr, 0, phy_reg, db->chip_id);
if ( db->chip_type && (db->chip_id == PCI_DM9102_ID) )
mdelay(20);
phy_write(db->ioaddr,
db->phy_addr, 0, phy_reg, db->chip_id);
}
}
}
/*
* Write a word to Phy register
*/
static void phy_write(unsigned long iobase, u8 phy_addr, u8 offset,
u16 phy_data, u32 chip_id)
{
u16 i;
unsigned long ioaddr;
if (chip_id == PCI_DM9132_ID) {
ioaddr = iobase + 0x80 + offset * 4;
outw(phy_data, ioaddr);
} else {
/* DM9102/DM9102A Chip */
ioaddr = iobase + DCR9;
/* Send 33 synchronization clock to Phy controller */
for (i = 0; i < 35; i++)
phy_write_1bit(ioaddr, PHY_DATA_1);
/* Send start command(01) to Phy */
phy_write_1bit(ioaddr, PHY_DATA_0);
phy_write_1bit(ioaddr, PHY_DATA_1);
/* Send write command(01) to Phy */
phy_write_1bit(ioaddr, PHY_DATA_0);
phy_write_1bit(ioaddr, PHY_DATA_1);
/* Send Phy address */
for (i = 0x10; i > 0; i = i >> 1)
phy_write_1bit(ioaddr,
phy_addr & i ? PHY_DATA_1 : PHY_DATA_0);
/* Send register address */
for (i = 0x10; i > 0; i = i >> 1)
phy_write_1bit(ioaddr,
offset & i ? PHY_DATA_1 : PHY_DATA_0);
/* written trasnition */
phy_write_1bit(ioaddr, PHY_DATA_1);
phy_write_1bit(ioaddr, PHY_DATA_0);
/* Write a word data to PHY controller */
for ( i = 0x8000; i > 0; i >>= 1)
phy_write_1bit(ioaddr,
phy_data & i ? PHY_DATA_1 : PHY_DATA_0);
}
}
/*
* Read a word data from phy register
*/
static u16 phy_read(unsigned long iobase, u8 phy_addr, u8 offset, u32 chip_id)
{
int i;
u16 phy_data;
unsigned long ioaddr;
if (chip_id == PCI_DM9132_ID) {
/* DM9132 Chip */
ioaddr = iobase + 0x80 + offset * 4;
phy_data = inw(ioaddr);
} else {
/* DM9102/DM9102A Chip */
ioaddr = iobase + DCR9;
/* Send 33 synchronization clock to Phy controller */
for (i = 0; i < 35; i++)
phy_write_1bit(ioaddr, PHY_DATA_1);
/* Send start command(01) to Phy */
phy_write_1bit(ioaddr, PHY_DATA_0);
phy_write_1bit(ioaddr, PHY_DATA_1);
/* Send read command(10) to Phy */
phy_write_1bit(ioaddr, PHY_DATA_1);
phy_write_1bit(ioaddr, PHY_DATA_0);
/* Send Phy address */
for (i = 0x10; i > 0; i = i >> 1)
phy_write_1bit(ioaddr,
phy_addr & i ? PHY_DATA_1 : PHY_DATA_0);
/* Send register address */
for (i = 0x10; i > 0; i = i >> 1)
phy_write_1bit(ioaddr,
offset & i ? PHY_DATA_1 : PHY_DATA_0);
/* Skip transition state */
phy_read_1bit(ioaddr);
/* read 16bit data */
for (phy_data = 0, i = 0; i < 16; i++) {
phy_data <<= 1;
phy_data |= phy_read_1bit(ioaddr);
}
}
return phy_data;
}
/*
* Write one bit data to Phy Controller
*/
static void phy_write_1bit(unsigned long ioaddr, u32 phy_data)
{
outl(phy_data, ioaddr); /* MII Clock Low */
udelay(1);
outl(phy_data | MDCLKH, ioaddr); /* MII Clock High */
udelay(1);
outl(phy_data, ioaddr); /* MII Clock Low */
udelay(1);
}
/*
* Read one bit phy data from PHY controller
*/
static u16 phy_read_1bit(unsigned long ioaddr)
{
u16 phy_data;
outl(0x50000, ioaddr);
udelay(1);
phy_data = ( inl(ioaddr) >> 19 ) & 0x1;
outl(0x40000, ioaddr);
udelay(1);
return phy_data;
}
/*
* Parser SROM and media mode
*/
static void dmfe_parse_srom(struct dmfe_board_info * db)
{
char * srom = db->srom;
int dmfe_mode, tmp_reg;
DMFE_DBUG(0, "dmfe_parse_srom() ", 0);
/* Init CR15 */
db->cr15_data = CR15_DEFAULT;
/* Check SROM Version */
if ( ( (int) srom[18] & 0xff) == SROM_V41_CODE) {
/* SROM V4.01 */
/* Get NIC support media mode */
db->NIC_capability = le16_to_cpup((__le16 *) (srom + 34));
db->PHY_reg4 = 0;
for (tmp_reg = 1; tmp_reg < 0x10; tmp_reg <<= 1) {
switch( db->NIC_capability & tmp_reg ) {
case 0x1: db->PHY_reg4 |= 0x0020; break;
case 0x2: db->PHY_reg4 |= 0x0040; break;
case 0x4: db->PHY_reg4 |= 0x0080; break;
case 0x8: db->PHY_reg4 |= 0x0100; break;
}
}
/* Media Mode Force or not check */
dmfe_mode = (le32_to_cpup((__le32 *) (srom + 34)) &
le32_to_cpup((__le32 *) (srom + 36)));
switch(dmfe_mode) {
case 0x4: dmfe_media_mode = DMFE_100MHF; break; /* 100MHF */
case 0x2: dmfe_media_mode = DMFE_10MFD; break; /* 10MFD */
case 0x8: dmfe_media_mode = DMFE_100MFD; break; /* 100MFD */
case 0x100:
case 0x200: dmfe_media_mode = DMFE_1M_HPNA; break;/* HomePNA */
}
/* Special Function setting */
/* VLAN function */
if ( (SF_mode & 0x1) || (srom[43] & 0x80) )
db->cr15_data |= 0x40;
/* Flow Control */
if ( (SF_mode & 0x2) || (srom[40] & 0x1) )
db->cr15_data |= 0x400;
/* TX pause packet */
if ( (SF_mode & 0x4) || (srom[40] & 0xe) )
db->cr15_data |= 0x9800;
}
/* Parse HPNA parameter */
db->HPNA_command = 1;
/* Accept remote command or not */
if (HPNA_rx_cmd == 0)
db->HPNA_command |= 0x8000;
/* Issue remote command & operation mode */
if (HPNA_tx_cmd == 1)
switch(HPNA_mode) { /* Issue Remote Command */
case 0: db->HPNA_command |= 0x0904; break;
case 1: db->HPNA_command |= 0x0a00; break;
case 2: db->HPNA_command |= 0x0506; break;
case 3: db->HPNA_command |= 0x0602; break;
}
else
switch(HPNA_mode) { /* Don't Issue */
case 0: db->HPNA_command |= 0x0004; break;
case 1: db->HPNA_command |= 0x0000; break;
case 2: db->HPNA_command |= 0x0006; break;
case 3: db->HPNA_command |= 0x0002; break;
}
/* Check DM9801 or DM9802 present or not */
db->HPNA_present = 0;
update_cr6(db->cr6_data|0x40000, db->ioaddr);
tmp_reg = phy_read(db->ioaddr, db->phy_addr, 3, db->chip_id);
if ( ( tmp_reg & 0xfff0 ) == 0xb900 ) {
/* DM9801 or DM9802 present */
db->HPNA_timer = 8;
if ( phy_read(db->ioaddr, db->phy_addr, 31, db->chip_id) == 0x4404) {
/* DM9801 HomeRun */
db->HPNA_present = 1;
dmfe_program_DM9801(db, tmp_reg);
} else {
/* DM9802 LongRun */
db->HPNA_present = 2;
dmfe_program_DM9802(db);
}
}
}
/*
* Init HomeRun DM9801
*/
static void dmfe_program_DM9801(struct dmfe_board_info * db, int HPNA_rev)
{
uint reg17, reg25;
if ( !HPNA_NoiseFloor ) HPNA_NoiseFloor = DM9801_NOISE_FLOOR;
switch(HPNA_rev) {
case 0xb900: /* DM9801 E3 */
db->HPNA_command |= 0x1000;
reg25 = phy_read(db->ioaddr, db->phy_addr, 24, db->chip_id);
reg25 = ( (reg25 + HPNA_NoiseFloor) & 0xff) | 0xf000;
reg17 = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id);
break;
case 0xb901: /* DM9801 E4 */
reg25 = phy_read(db->ioaddr, db->phy_addr, 25, db->chip_id);
reg25 = (reg25 & 0xff00) + HPNA_NoiseFloor;
reg17 = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id);
reg17 = (reg17 & 0xfff0) + HPNA_NoiseFloor + 3;
break;
case 0xb902: /* DM9801 E5 */
case 0xb903: /* DM9801 E6 */
default:
db->HPNA_command |= 0x1000;
reg25 = phy_read(db->ioaddr, db->phy_addr, 25, db->chip_id);
reg25 = (reg25 & 0xff00) + HPNA_NoiseFloor - 5;
reg17 = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id);
reg17 = (reg17 & 0xfff0) + HPNA_NoiseFloor;
break;
}
phy_write(db->ioaddr, db->phy_addr, 16, db->HPNA_command, db->chip_id);
phy_write(db->ioaddr, db->phy_addr, 17, reg17, db->chip_id);
phy_write(db->ioaddr, db->phy_addr, 25, reg25, db->chip_id);
}
/*
* Init HomeRun DM9802
*/
static void dmfe_program_DM9802(struct dmfe_board_info * db)
{
uint phy_reg;
if ( !HPNA_NoiseFloor ) HPNA_NoiseFloor = DM9802_NOISE_FLOOR;
phy_write(db->ioaddr, db->phy_addr, 16, db->HPNA_command, db->chip_id);
phy_reg = phy_read(db->ioaddr, db->phy_addr, 25, db->chip_id);
phy_reg = ( phy_reg & 0xff00) + HPNA_NoiseFloor;
phy_write(db->ioaddr, db->phy_addr, 25, phy_reg, db->chip_id);
}
/*
* Check remote HPNA power and speed status. If not correct,
* issue command again.
*/
static void dmfe_HPNA_remote_cmd_chk(struct dmfe_board_info * db)
{
uint phy_reg;
/* Got remote device status */
phy_reg = phy_read(db->ioaddr, db->phy_addr, 17, db->chip_id) & 0x60;
switch(phy_reg) {
case 0x00: phy_reg = 0x0a00;break; /* LP/LS */
case 0x20: phy_reg = 0x0900;break; /* LP/HS */
case 0x40: phy_reg = 0x0600;break; /* HP/LS */
case 0x60: phy_reg = 0x0500;break; /* HP/HS */
}
/* Check remote device status match our setting ot not */
if ( phy_reg != (db->HPNA_command & 0x0f00) ) {
phy_write(db->ioaddr, db->phy_addr, 16, db->HPNA_command,
db->chip_id);
db->HPNA_timer=8;
} else
db->HPNA_timer=600; /* Match, every 10 minutes, check */
}
static DEFINE_PCI_DEVICE_TABLE(dmfe_pci_tbl) = {
{ 0x1282, 0x9132, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PCI_DM9132_ID },
{ 0x1282, 0x9102, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PCI_DM9102_ID },
{ 0x1282, 0x9100, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PCI_DM9100_ID },
{ 0x1282, 0x9009, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PCI_DM9009_ID },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, dmfe_pci_tbl);
#ifdef CONFIG_PM
static int dmfe_suspend(struct pci_dev *pci_dev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata(pci_dev);
struct dmfe_board_info *db = netdev_priv(dev);
u32 tmp;
/* Disable upper layer interface */
netif_device_detach(dev);
/* Disable Tx/Rx */
db->cr6_data &= ~(CR6_RXSC | CR6_TXSC);
update_cr6(db->cr6_data, dev->base_addr);
/* Disable Interrupt */
outl(0, dev->base_addr + DCR7);
outl(inl (dev->base_addr + DCR5), dev->base_addr + DCR5);
/* Fre RX buffers */
dmfe_free_rxbuffer(db);
/* Enable WOL */
pci_read_config_dword(pci_dev, 0x40, &tmp);
tmp &= ~(DMFE_WOL_LINKCHANGE|DMFE_WOL_MAGICPACKET);
if (db->wol_mode & WAKE_PHY)
tmp |= DMFE_WOL_LINKCHANGE;
if (db->wol_mode & WAKE_MAGIC)
tmp |= DMFE_WOL_MAGICPACKET;
pci_write_config_dword(pci_dev, 0x40, tmp);
pci_enable_wake(pci_dev, PCI_D3hot, 1);
pci_enable_wake(pci_dev, PCI_D3cold, 1);
/* Power down device*/
pci_save_state(pci_dev);
pci_set_power_state(pci_dev, pci_choose_state (pci_dev, state));
return 0;
}
static int dmfe_resume(struct pci_dev *pci_dev)
{
struct net_device *dev = pci_get_drvdata(pci_dev);
u32 tmp;
pci_set_power_state(pci_dev, PCI_D0);
pci_restore_state(pci_dev);
/* Re-initialize DM910X board */
dmfe_init_dm910x(dev);
/* Disable WOL */
pci_read_config_dword(pci_dev, 0x40, &tmp);
tmp &= ~(DMFE_WOL_LINKCHANGE | DMFE_WOL_MAGICPACKET);
pci_write_config_dword(pci_dev, 0x40, tmp);
pci_enable_wake(pci_dev, PCI_D3hot, 0);
pci_enable_wake(pci_dev, PCI_D3cold, 0);
/* Restart upper layer interface */
netif_device_attach(dev);
return 0;
}
#else
#define dmfe_suspend NULL
#define dmfe_resume NULL
#endif
static struct pci_driver dmfe_driver = {
.name = "dmfe",
.id_table = dmfe_pci_tbl,
.probe = dmfe_init_one,
.remove = __devexit_p(dmfe_remove_one),
.suspend = dmfe_suspend,
.resume = dmfe_resume
};
MODULE_AUTHOR("Sten Wang, sten_wang@davicom.com.tw");
MODULE_DESCRIPTION("Davicom DM910X fast ethernet driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
module_param(debug, int, 0);
module_param(mode, byte, 0);
module_param(cr6set, int, 0);
module_param(chkmode, byte, 0);
module_param(HPNA_mode, byte, 0);
module_param(HPNA_rx_cmd, byte, 0);
module_param(HPNA_tx_cmd, byte, 0);
module_param(HPNA_NoiseFloor, byte, 0);
module_param(SF_mode, byte, 0);
MODULE_PARM_DESC(debug, "Davicom DM9xxx enable debugging (0-1)");
MODULE_PARM_DESC(mode, "Davicom DM9xxx: "
"Bit 0: 10/100Mbps, bit 2: duplex, bit 8: HomePNA");
MODULE_PARM_DESC(SF_mode, "Davicom DM9xxx special function "
"(bit 0: VLAN, bit 1 Flow Control, bit 2: TX pause packet)");
/* Description:
* when user used insmod to add module, system invoked init_module()
* to initialize and register.
*/
static int __init dmfe_init_module(void)
{
int rc;
pr_info("%s\n", version);
printed_version = 1;
DMFE_DBUG(0, "init_module() ", debug);
if (debug)
dmfe_debug = debug; /* set debug flag */
if (cr6set)
dmfe_cr6_user_set = cr6set;
switch(mode) {
case DMFE_10MHF:
case DMFE_100MHF:
case DMFE_10MFD:
case DMFE_100MFD:
case DMFE_1M_HPNA:
dmfe_media_mode = mode;
break;
default:dmfe_media_mode = DMFE_AUTO;
break;
}
if (HPNA_mode > 4)
HPNA_mode = 0; /* Default: LP/HS */
if (HPNA_rx_cmd > 1)
HPNA_rx_cmd = 0; /* Default: Ignored remote cmd */
if (HPNA_tx_cmd > 1)
HPNA_tx_cmd = 0; /* Default: Don't issue remote cmd */
if (HPNA_NoiseFloor > 15)
HPNA_NoiseFloor = 0;
rc = pci_register_driver(&dmfe_driver);
if (rc < 0)
return rc;
return 0;
}
/*
* Description:
* when user used rmmod to delete module, system invoked clean_module()
* to un-register all registered services.
*/
static void __exit dmfe_cleanup_module(void)
{
DMFE_DBUG(0, "dmfe_clean_module() ", debug);
pci_unregister_driver(&dmfe_driver);
}
module_init(dmfe_init_module);
module_exit(dmfe_cleanup_module);
| gpl-2.0 |
Validus-Lollipop/android_kernel_motorola_msm8960dt-common | fs/squashfs/dir.c | 5061 | 6349 | /*
* 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.
*
* dir.c
*/
/*
* This file implements code to read directories from disk.
*
* See namei.c for a description of directory organisation on disk.
*/
#include <linux/fs.h>
#include <linux/vfs.h>
#include <linux/slab.h>
#include "squashfs_fs.h"
#include "squashfs_fs_sb.h"
#include "squashfs_fs_i.h"
#include "squashfs.h"
static const unsigned char squashfs_filetype_table[] = {
DT_UNKNOWN, DT_DIR, DT_REG, DT_LNK, DT_BLK, DT_CHR, DT_FIFO, DT_SOCK
};
/*
* Lookup offset (f_pos) in the directory index, returning the
* metadata block containing it.
*
* If we get an error reading the index then return the part of the index
* (if any) we have managed to read - the index isn't essential, just
* quicker.
*/
static int get_dir_index_using_offset(struct super_block *sb,
u64 *next_block, int *next_offset, u64 index_start, int index_offset,
int i_count, u64 f_pos)
{
struct squashfs_sb_info *msblk = sb->s_fs_info;
int err, i, index, length = 0;
struct squashfs_dir_index dir_index;
TRACE("Entered get_dir_index_using_offset, i_count %d, f_pos %lld\n",
i_count, f_pos);
/*
* Translate from external f_pos to the internal f_pos. This
* is offset by 3 because we invent "." and ".." entries which are
* not actually stored in the directory.
*/
if (f_pos <= 3)
return f_pos;
f_pos -= 3;
for (i = 0; i < i_count; i++) {
err = squashfs_read_metadata(sb, &dir_index, &index_start,
&index_offset, sizeof(dir_index));
if (err < 0)
break;
index = le32_to_cpu(dir_index.index);
if (index > f_pos)
/*
* Found the index we're looking for.
*/
break;
err = squashfs_read_metadata(sb, NULL, &index_start,
&index_offset, le32_to_cpu(dir_index.size) + 1);
if (err < 0)
break;
length = index;
*next_block = le32_to_cpu(dir_index.start_block) +
msblk->directory_table;
}
*next_offset = (length + *next_offset) % SQUASHFS_METADATA_SIZE;
/*
* Translate back from internal f_pos to external f_pos.
*/
return length + 3;
}
static int squashfs_readdir(struct file *file, void *dirent, filldir_t filldir)
{
struct inode *inode = file->f_dentry->d_inode;
struct squashfs_sb_info *msblk = inode->i_sb->s_fs_info;
u64 block = squashfs_i(inode)->start + msblk->directory_table;
int offset = squashfs_i(inode)->offset, length, dir_count, size,
type, err;
unsigned int inode_number;
struct squashfs_dir_header dirh;
struct squashfs_dir_entry *dire;
TRACE("Entered squashfs_readdir [%llx:%x]\n", block, offset);
dire = kmalloc(sizeof(*dire) + SQUASHFS_NAME_LEN + 1, GFP_KERNEL);
if (dire == NULL) {
ERROR("Failed to allocate squashfs_dir_entry\n");
goto finish;
}
/*
* Return "." and ".." entries as the first two filenames in the
* directory. To maximise compression these two entries are not
* stored in the directory, and so we invent them here.
*
* It also means that the external f_pos is offset by 3 from the
* on-disk directory f_pos.
*/
while (file->f_pos < 3) {
char *name;
int i_ino;
if (file->f_pos == 0) {
name = ".";
size = 1;
i_ino = inode->i_ino;
} else {
name = "..";
size = 2;
i_ino = squashfs_i(inode)->parent;
}
TRACE("Calling filldir(%p, %s, %d, %lld, %d, %d)\n",
dirent, name, size, file->f_pos, i_ino,
squashfs_filetype_table[1]);
if (filldir(dirent, name, size, file->f_pos, i_ino,
squashfs_filetype_table[1]) < 0) {
TRACE("Filldir returned less than 0\n");
goto finish;
}
file->f_pos += size;
}
length = get_dir_index_using_offset(inode->i_sb, &block, &offset,
squashfs_i(inode)->dir_idx_start,
squashfs_i(inode)->dir_idx_offset,
squashfs_i(inode)->dir_idx_cnt,
file->f_pos);
while (length < i_size_read(inode)) {
/*
* Read directory header
*/
err = squashfs_read_metadata(inode->i_sb, &dirh, &block,
&offset, sizeof(dirh));
if (err < 0)
goto failed_read;
length += sizeof(dirh);
dir_count = le32_to_cpu(dirh.count) + 1;
if (dir_count > SQUASHFS_DIR_COUNT)
goto failed_read;
while (dir_count--) {
/*
* Read directory entry.
*/
err = squashfs_read_metadata(inode->i_sb, dire, &block,
&offset, sizeof(*dire));
if (err < 0)
goto failed_read;
size = le16_to_cpu(dire->size) + 1;
/* size should never be larger than SQUASHFS_NAME_LEN */
if (size > SQUASHFS_NAME_LEN)
goto failed_read;
err = squashfs_read_metadata(inode->i_sb, dire->name,
&block, &offset, size);
if (err < 0)
goto failed_read;
length += sizeof(*dire) + size;
if (file->f_pos >= length)
continue;
dire->name[size] = '\0';
inode_number = le32_to_cpu(dirh.inode_number) +
((short) le16_to_cpu(dire->inode_number));
type = le16_to_cpu(dire->type);
TRACE("Calling filldir(%p, %s, %d, %lld, %x:%x, %d, %d)"
"\n", dirent, dire->name, size,
file->f_pos,
le32_to_cpu(dirh.start_block),
le16_to_cpu(dire->offset),
inode_number,
squashfs_filetype_table[type]);
if (filldir(dirent, dire->name, size, file->f_pos,
inode_number,
squashfs_filetype_table[type]) < 0) {
TRACE("Filldir returned less than 0\n");
goto finish;
}
file->f_pos = length;
}
}
finish:
kfree(dire);
return 0;
failed_read:
ERROR("Unable to read directory block [%llx:%x]\n", block, offset);
kfree(dire);
return 0;
}
const struct file_operations squashfs_dir_ops = {
.read = generic_read_dir,
.readdir = squashfs_readdir,
.llseek = default_llseek,
};
| gpl-2.0 |
emceethemouth/kernel_msm | drivers/video/sis/sis_main.c | 5061 | 188301 | /*
* SiS 300/540/630[S]/730[S],
* SiS 315[E|PRO]/550/[M]65x/[M]66x[F|M|G]X/[M]74x[GX]/330/[M]76x[GX],
* XGI V3XT/V5/V8, Z7
* frame buffer driver for Linux kernels >= 2.4.14 and >=2.6.3
*
* Copyright (C) 2001-2005 Thomas Winischhofer, Vienna, Austria.
*
* 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 named License,
* or 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: Thomas Winischhofer <thomas@winischhofer.net>
*
* Author of (practically wiped) code base:
* SiS (www.sis.com)
* Copyright (C) 1999 Silicon Integrated Systems, Inc.
*
* See http://www.winischhofer.net/ for more information and updates
*
* Originally based on the VBE 2.0 compliant graphic boards framebuffer driver,
* which is (c) 1998 Gerd Knorr <kraxel@goldbach.in-berlin.de>
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/screen_info.h>
#include <linux/slab.h>
#include <linux/fb.h>
#include <linux/selection.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/capability.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/uaccess.h>
#include <asm/io.h>
#ifdef CONFIG_MTRR
#include <asm/mtrr.h>
#endif
#include "sis.h"
#include "sis_main.h"
#if !defined(CONFIG_FB_SIS_300) && !defined(CONFIG_FB_SIS_315)
#warning Neither CONFIG_FB_SIS_300 nor CONFIG_FB_SIS_315 is set
#warning sisfb will not work!
#endif
static void sisfb_handle_command(struct sis_video_info *ivideo,
struct sisfb_cmd *sisfb_command);
/* ------------------ Internal helper routines ----------------- */
static void __init
sisfb_setdefaultparms(void)
{
sisfb_off = 0;
sisfb_parm_mem = 0;
sisfb_accel = -1;
sisfb_ypan = -1;
sisfb_max = -1;
sisfb_userom = -1;
sisfb_useoem = -1;
sisfb_mode_idx = -1;
sisfb_parm_rate = -1;
sisfb_crt1off = 0;
sisfb_forcecrt1 = -1;
sisfb_crt2type = -1;
sisfb_crt2flags = 0;
sisfb_pdc = 0xff;
sisfb_pdca = 0xff;
sisfb_scalelcd = -1;
sisfb_specialtiming = CUT_NONE;
sisfb_lvdshl = -1;
sisfb_dstn = 0;
sisfb_fstn = 0;
sisfb_tvplug = -1;
sisfb_tvstd = -1;
sisfb_tvxposoffset = 0;
sisfb_tvyposoffset = 0;
sisfb_nocrt2rate = 0;
#if !defined(__i386__) && !defined(__x86_64__)
sisfb_resetcard = 0;
sisfb_videoram = 0;
#endif
}
/* ------------- Parameter parsing -------------- */
static void __devinit
sisfb_search_vesamode(unsigned int vesamode, bool quiet)
{
int i = 0, j = 0;
/* We don't know the hardware specs yet and there is no ivideo */
if(vesamode == 0) {
if(!quiet)
printk(KERN_ERR "sisfb: Invalid mode. Using default.\n");
sisfb_mode_idx = DEFAULT_MODE;
return;
}
vesamode &= 0x1dff; /* Clean VESA mode number from other flags */
while(sisbios_mode[i++].mode_no[0] != 0) {
if( (sisbios_mode[i-1].vesa_mode_no_1 == vesamode) ||
(sisbios_mode[i-1].vesa_mode_no_2 == vesamode) ) {
if(sisfb_fstn) {
if(sisbios_mode[i-1].mode_no[1] == 0x50 ||
sisbios_mode[i-1].mode_no[1] == 0x56 ||
sisbios_mode[i-1].mode_no[1] == 0x53)
continue;
} else {
if(sisbios_mode[i-1].mode_no[1] == 0x5a ||
sisbios_mode[i-1].mode_no[1] == 0x5b)
continue;
}
sisfb_mode_idx = i - 1;
j = 1;
break;
}
}
if((!j) && !quiet)
printk(KERN_ERR "sisfb: Invalid VESA mode 0x%x'\n", vesamode);
}
static void __devinit
sisfb_search_mode(char *name, bool quiet)
{
unsigned int j = 0, xres = 0, yres = 0, depth = 0, rate = 0;
int i = 0;
char strbuf[16], strbuf1[20];
char *nameptr = name;
/* We don't know the hardware specs yet and there is no ivideo */
if(name == NULL) {
if(!quiet)
printk(KERN_ERR "sisfb: Internal error, using default mode.\n");
sisfb_mode_idx = DEFAULT_MODE;
return;
}
if(!strnicmp(name, sisbios_mode[MODE_INDEX_NONE].name, strlen(name))) {
if(!quiet)
printk(KERN_ERR "sisfb: Mode 'none' not supported anymore. Using default.\n");
sisfb_mode_idx = DEFAULT_MODE;
return;
}
if(strlen(name) <= 19) {
strcpy(strbuf1, name);
for(i = 0; i < strlen(strbuf1); i++) {
if(strbuf1[i] < '0' || strbuf1[i] > '9') strbuf1[i] = ' ';
}
/* This does some fuzzy mode naming detection */
if(sscanf(strbuf1, "%u %u %u %u", &xres, &yres, &depth, &rate) == 4) {
if((rate <= 32) || (depth > 32)) {
j = rate; rate = depth; depth = j;
}
sprintf(strbuf, "%ux%ux%u", xres, yres, depth);
nameptr = strbuf;
sisfb_parm_rate = rate;
} else if(sscanf(strbuf1, "%u %u %u", &xres, &yres, &depth) == 3) {
sprintf(strbuf, "%ux%ux%u", xres, yres, depth);
nameptr = strbuf;
} else {
xres = 0;
if((sscanf(strbuf1, "%u %u", &xres, &yres) == 2) && (xres != 0)) {
sprintf(strbuf, "%ux%ux8", xres, yres);
nameptr = strbuf;
} else {
sisfb_search_vesamode(simple_strtoul(name, NULL, 0), quiet);
return;
}
}
}
i = 0; j = 0;
while(sisbios_mode[i].mode_no[0] != 0) {
if(!strnicmp(nameptr, sisbios_mode[i++].name, strlen(nameptr))) {
if(sisfb_fstn) {
if(sisbios_mode[i-1].mode_no[1] == 0x50 ||
sisbios_mode[i-1].mode_no[1] == 0x56 ||
sisbios_mode[i-1].mode_no[1] == 0x53)
continue;
} else {
if(sisbios_mode[i-1].mode_no[1] == 0x5a ||
sisbios_mode[i-1].mode_no[1] == 0x5b)
continue;
}
sisfb_mode_idx = i - 1;
j = 1;
break;
}
}
if((!j) && !quiet)
printk(KERN_ERR "sisfb: Invalid mode '%s'\n", nameptr);
}
#ifndef MODULE
static void __devinit
sisfb_get_vga_mode_from_kernel(void)
{
#ifdef CONFIG_X86
char mymode[32];
int mydepth = screen_info.lfb_depth;
if(screen_info.orig_video_isVGA != VIDEO_TYPE_VLFB) return;
if( (screen_info.lfb_width >= 320) && (screen_info.lfb_width <= 2048) &&
(screen_info.lfb_height >= 200) && (screen_info.lfb_height <= 1536) &&
(mydepth >= 8) && (mydepth <= 32) ) {
if(mydepth == 24) mydepth = 32;
sprintf(mymode, "%ux%ux%u", screen_info.lfb_width,
screen_info.lfb_height,
mydepth);
printk(KERN_DEBUG
"sisfb: Using vga mode %s pre-set by kernel as default\n",
mymode);
sisfb_search_mode(mymode, true);
}
#endif
return;
}
#endif
static void __init
sisfb_search_crt2type(const char *name)
{
int i = 0;
/* We don't know the hardware specs yet and there is no ivideo */
if(name == NULL) return;
while(sis_crt2type[i].type_no != -1) {
if(!strnicmp(name, sis_crt2type[i].name, strlen(sis_crt2type[i].name))) {
sisfb_crt2type = sis_crt2type[i].type_no;
sisfb_tvplug = sis_crt2type[i].tvplug_no;
sisfb_crt2flags = sis_crt2type[i].flags;
break;
}
i++;
}
sisfb_dstn = (sisfb_crt2flags & FL_550_DSTN) ? 1 : 0;
sisfb_fstn = (sisfb_crt2flags & FL_550_FSTN) ? 1 : 0;
if(sisfb_crt2type < 0)
printk(KERN_ERR "sisfb: Invalid CRT2 type: %s\n", name);
}
static void __init
sisfb_search_tvstd(const char *name)
{
int i = 0;
/* We don't know the hardware specs yet and there is no ivideo */
if(name == NULL)
return;
while(sis_tvtype[i].type_no != -1) {
if(!strnicmp(name, sis_tvtype[i].name, strlen(sis_tvtype[i].name))) {
sisfb_tvstd = sis_tvtype[i].type_no;
break;
}
i++;
}
}
static void __init
sisfb_search_specialtiming(const char *name)
{
int i = 0;
bool found = false;
/* We don't know the hardware specs yet and there is no ivideo */
if(name == NULL)
return;
if(!strnicmp(name, "none", 4)) {
sisfb_specialtiming = CUT_FORCENONE;
printk(KERN_DEBUG "sisfb: Special timing disabled\n");
} else {
while(mycustomttable[i].chipID != 0) {
if(!strnicmp(name,mycustomttable[i].optionName,
strlen(mycustomttable[i].optionName))) {
sisfb_specialtiming = mycustomttable[i].SpecialID;
found = true;
printk(KERN_INFO "sisfb: Special timing for %s %s forced (\"%s\")\n",
mycustomttable[i].vendorName,
mycustomttable[i].cardName,
mycustomttable[i].optionName);
break;
}
i++;
}
if(!found) {
printk(KERN_WARNING "sisfb: Invalid SpecialTiming parameter, valid are:");
printk(KERN_WARNING "\t\"none\" (to disable special timings)\n");
i = 0;
while(mycustomttable[i].chipID != 0) {
printk(KERN_WARNING "\t\"%s\" (for %s %s)\n",
mycustomttable[i].optionName,
mycustomttable[i].vendorName,
mycustomttable[i].cardName);
i++;
}
}
}
}
/* ----------- Various detection routines ----------- */
static void __devinit
sisfb_detect_custom_timing(struct sis_video_info *ivideo)
{
unsigned char *biosver = NULL;
unsigned char *biosdate = NULL;
bool footprint;
u32 chksum = 0;
int i, j;
if(ivideo->SiS_Pr.UseROM) {
biosver = ivideo->SiS_Pr.VirtualRomBase + 0x06;
biosdate = ivideo->SiS_Pr.VirtualRomBase + 0x2c;
for(i = 0; i < 32768; i++)
chksum += ivideo->SiS_Pr.VirtualRomBase[i];
}
i = 0;
do {
if( (mycustomttable[i].chipID == ivideo->chip) &&
((!strlen(mycustomttable[i].biosversion)) ||
(ivideo->SiS_Pr.UseROM &&
(!strncmp(mycustomttable[i].biosversion, biosver,
strlen(mycustomttable[i].biosversion))))) &&
((!strlen(mycustomttable[i].biosdate)) ||
(ivideo->SiS_Pr.UseROM &&
(!strncmp(mycustomttable[i].biosdate, biosdate,
strlen(mycustomttable[i].biosdate))))) &&
((!mycustomttable[i].bioschksum) ||
(ivideo->SiS_Pr.UseROM &&
(mycustomttable[i].bioschksum == chksum))) &&
(mycustomttable[i].pcisubsysvendor == ivideo->subsysvendor) &&
(mycustomttable[i].pcisubsyscard == ivideo->subsysdevice) ) {
footprint = true;
for(j = 0; j < 5; j++) {
if(mycustomttable[i].biosFootprintAddr[j]) {
if(ivideo->SiS_Pr.UseROM) {
if(ivideo->SiS_Pr.VirtualRomBase[mycustomttable[i].biosFootprintAddr[j]] !=
mycustomttable[i].biosFootprintData[j]) {
footprint = false;
}
} else
footprint = false;
}
}
if(footprint) {
ivideo->SiS_Pr.SiS_CustomT = mycustomttable[i].SpecialID;
printk(KERN_DEBUG "sisfb: Identified [%s %s], special timing applies\n",
mycustomttable[i].vendorName,
mycustomttable[i].cardName);
printk(KERN_DEBUG "sisfb: [specialtiming parameter name: %s]\n",
mycustomttable[i].optionName);
break;
}
}
i++;
} while(mycustomttable[i].chipID);
}
static bool __devinit
sisfb_interpret_edid(struct sisfb_monitor *monitor, u8 *buffer)
{
int i, j, xres, yres, refresh, index;
u32 emodes;
if(buffer[0] != 0x00 || buffer[1] != 0xff ||
buffer[2] != 0xff || buffer[3] != 0xff ||
buffer[4] != 0xff || buffer[5] != 0xff ||
buffer[6] != 0xff || buffer[7] != 0x00) {
printk(KERN_DEBUG "sisfb: Bad EDID header\n");
return false;
}
if(buffer[0x12] != 0x01) {
printk(KERN_INFO "sisfb: EDID version %d not supported\n",
buffer[0x12]);
return false;
}
monitor->feature = buffer[0x18];
if(!(buffer[0x14] & 0x80)) {
if(!(buffer[0x14] & 0x08)) {
printk(KERN_INFO
"sisfb: WARNING: Monitor does not support separate syncs\n");
}
}
if(buffer[0x13] >= 0x01) {
/* EDID V1 rev 1 and 2: Search for monitor descriptor
* to extract ranges
*/
j = 0x36;
for(i=0; i<4; i++) {
if(buffer[j] == 0x00 && buffer[j + 1] == 0x00 &&
buffer[j + 2] == 0x00 && buffer[j + 3] == 0xfd &&
buffer[j + 4] == 0x00) {
monitor->hmin = buffer[j + 7];
monitor->hmax = buffer[j + 8];
monitor->vmin = buffer[j + 5];
monitor->vmax = buffer[j + 6];
monitor->dclockmax = buffer[j + 9] * 10 * 1000;
monitor->datavalid = true;
break;
}
j += 18;
}
}
if(!monitor->datavalid) {
/* Otherwise: Get a range from the list of supported
* Estabished Timings. This is not entirely accurate,
* because fixed frequency monitors are not supported
* that way.
*/
monitor->hmin = 65535; monitor->hmax = 0;
monitor->vmin = 65535; monitor->vmax = 0;
monitor->dclockmax = 0;
emodes = buffer[0x23] | (buffer[0x24] << 8) | (buffer[0x25] << 16);
for(i = 0; i < 13; i++) {
if(emodes & sisfb_ddcsmodes[i].mask) {
if(monitor->hmin > sisfb_ddcsmodes[i].h) monitor->hmin = sisfb_ddcsmodes[i].h;
if(monitor->hmax < sisfb_ddcsmodes[i].h) monitor->hmax = sisfb_ddcsmodes[i].h + 1;
if(monitor->vmin > sisfb_ddcsmodes[i].v) monitor->vmin = sisfb_ddcsmodes[i].v;
if(monitor->vmax < sisfb_ddcsmodes[i].v) monitor->vmax = sisfb_ddcsmodes[i].v;
if(monitor->dclockmax < sisfb_ddcsmodes[i].d) monitor->dclockmax = sisfb_ddcsmodes[i].d;
}
}
index = 0x26;
for(i = 0; i < 8; i++) {
xres = (buffer[index] + 31) * 8;
switch(buffer[index + 1] & 0xc0) {
case 0xc0: yres = (xres * 9) / 16; break;
case 0x80: yres = (xres * 4) / 5; break;
case 0x40: yres = (xres * 3) / 4; break;
default: yres = xres; break;
}
refresh = (buffer[index + 1] & 0x3f) + 60;
if((xres >= 640) && (yres >= 480)) {
for(j = 0; j < 8; j++) {
if((xres == sisfb_ddcfmodes[j].x) &&
(yres == sisfb_ddcfmodes[j].y) &&
(refresh == sisfb_ddcfmodes[j].v)) {
if(monitor->hmin > sisfb_ddcfmodes[j].h) monitor->hmin = sisfb_ddcfmodes[j].h;
if(monitor->hmax < sisfb_ddcfmodes[j].h) monitor->hmax = sisfb_ddcfmodes[j].h + 1;
if(monitor->vmin > sisfb_ddcsmodes[j].v) monitor->vmin = sisfb_ddcsmodes[j].v;
if(monitor->vmax < sisfb_ddcsmodes[j].v) monitor->vmax = sisfb_ddcsmodes[j].v;
if(monitor->dclockmax < sisfb_ddcsmodes[j].d) monitor->dclockmax = sisfb_ddcsmodes[j].d;
}
}
}
index += 2;
}
if((monitor->hmin <= monitor->hmax) && (monitor->vmin <= monitor->vmax)) {
monitor->datavalid = true;
}
}
return monitor->datavalid;
}
static void __devinit
sisfb_handle_ddc(struct sis_video_info *ivideo, struct sisfb_monitor *monitor, int crtno)
{
unsigned short temp, i, realcrtno = crtno;
unsigned char buffer[256];
monitor->datavalid = false;
if(crtno) {
if(ivideo->vbflags & CRT2_LCD) realcrtno = 1;
else if(ivideo->vbflags & CRT2_VGA) realcrtno = 2;
else return;
}
if((ivideo->sisfb_crt1off) && (!crtno))
return;
temp = SiS_HandleDDC(&ivideo->SiS_Pr, ivideo->vbflags, ivideo->sisvga_engine,
realcrtno, 0, &buffer[0], ivideo->vbflags2);
if((!temp) || (temp == 0xffff)) {
printk(KERN_INFO "sisfb: CRT%d DDC probing failed\n", crtno + 1);
return;
} else {
printk(KERN_INFO "sisfb: CRT%d DDC supported\n", crtno + 1);
printk(KERN_INFO "sisfb: CRT%d DDC level: %s%s%s%s\n",
crtno + 1,
(temp & 0x1a) ? "" : "[none of the supported]",
(temp & 0x02) ? "2 " : "",
(temp & 0x08) ? "D&P" : "",
(temp & 0x10) ? "FPDI-2" : "");
if(temp & 0x02) {
i = 3; /* Number of retrys */
do {
temp = SiS_HandleDDC(&ivideo->SiS_Pr, ivideo->vbflags, ivideo->sisvga_engine,
realcrtno, 1, &buffer[0], ivideo->vbflags2);
} while((temp) && i--);
if(!temp) {
if(sisfb_interpret_edid(monitor, &buffer[0])) {
printk(KERN_INFO "sisfb: Monitor range H %d-%dKHz, V %d-%dHz, Max. dotclock %dMHz\n",
monitor->hmin, monitor->hmax, monitor->vmin, monitor->vmax,
monitor->dclockmax / 1000);
} else {
printk(KERN_INFO "sisfb: CRT%d DDC EDID corrupt\n", crtno + 1);
}
} else {
printk(KERN_INFO "sisfb: CRT%d DDC reading failed\n", crtno + 1);
}
} else {
printk(KERN_INFO "sisfb: VESA D&P and FPDI-2 not supported yet\n");
}
}
}
/* -------------- Mode validation --------------- */
static bool
sisfb_verify_rate(struct sis_video_info *ivideo, struct sisfb_monitor *monitor,
int mode_idx, int rate_idx, int rate)
{
int htotal, vtotal;
unsigned int dclock, hsync;
if(!monitor->datavalid)
return true;
if(mode_idx < 0)
return false;
/* Skip for 320x200, 320x240, 640x400 */
switch(sisbios_mode[mode_idx].mode_no[ivideo->mni]) {
case 0x59:
case 0x41:
case 0x4f:
case 0x50:
case 0x56:
case 0x53:
case 0x2f:
case 0x5d:
case 0x5e:
return true;
#ifdef CONFIG_FB_SIS_315
case 0x5a:
case 0x5b:
if(ivideo->sisvga_engine == SIS_315_VGA) return true;
#endif
}
if(rate < (monitor->vmin - 1))
return false;
if(rate > (monitor->vmax + 1))
return false;
if(sisfb_gettotalfrommode(&ivideo->SiS_Pr,
sisbios_mode[mode_idx].mode_no[ivideo->mni],
&htotal, &vtotal, rate_idx)) {
dclock = (htotal * vtotal * rate) / 1000;
if(dclock > (monitor->dclockmax + 1000))
return false;
hsync = dclock / htotal;
if(hsync < (monitor->hmin - 1))
return false;
if(hsync > (monitor->hmax + 1))
return false;
} else {
return false;
}
return true;
}
static int
sisfb_validate_mode(struct sis_video_info *ivideo, int myindex, u32 vbflags)
{
u16 xres=0, yres, myres;
#ifdef CONFIG_FB_SIS_300
if(ivideo->sisvga_engine == SIS_300_VGA) {
if(!(sisbios_mode[myindex].chipset & MD_SIS300))
return -1 ;
}
#endif
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
if(!(sisbios_mode[myindex].chipset & MD_SIS315))
return -1;
}
#endif
myres = sisbios_mode[myindex].yres;
switch(vbflags & VB_DISPTYPE_DISP2) {
case CRT2_LCD:
xres = ivideo->lcdxres; yres = ivideo->lcdyres;
if((ivideo->SiS_Pr.SiS_CustomT != CUT_PANEL848) &&
(ivideo->SiS_Pr.SiS_CustomT != CUT_PANEL856)) {
if(sisbios_mode[myindex].xres > xres)
return -1;
if(myres > yres)
return -1;
}
if(ivideo->sisfb_fstn) {
if(sisbios_mode[myindex].xres == 320) {
if(myres == 240) {
switch(sisbios_mode[myindex].mode_no[1]) {
case 0x50: myindex = MODE_FSTN_8; break;
case 0x56: myindex = MODE_FSTN_16; break;
case 0x53: return -1;
}
}
}
}
if(SiS_GetModeID_LCD(ivideo->sisvga_engine, vbflags, sisbios_mode[myindex].xres,
sisbios_mode[myindex].yres, 0, ivideo->sisfb_fstn,
ivideo->SiS_Pr.SiS_CustomT, xres, yres, ivideo->vbflags2) < 0x14) {
return -1;
}
break;
case CRT2_TV:
if(SiS_GetModeID_TV(ivideo->sisvga_engine, vbflags, sisbios_mode[myindex].xres,
sisbios_mode[myindex].yres, 0, ivideo->vbflags2) < 0x14) {
return -1;
}
break;
case CRT2_VGA:
if(SiS_GetModeID_VGA2(ivideo->sisvga_engine, vbflags, sisbios_mode[myindex].xres,
sisbios_mode[myindex].yres, 0, ivideo->vbflags2) < 0x14) {
return -1;
}
break;
}
return myindex;
}
static u8
sisfb_search_refresh_rate(struct sis_video_info *ivideo, unsigned int rate, int mode_idx)
{
int i = 0;
u16 xres = sisbios_mode[mode_idx].xres;
u16 yres = sisbios_mode[mode_idx].yres;
ivideo->rate_idx = 0;
while((sisfb_vrate[i].idx != 0) && (sisfb_vrate[i].xres <= xres)) {
if((sisfb_vrate[i].xres == xres) && (sisfb_vrate[i].yres == yres)) {
if(sisfb_vrate[i].refresh == rate) {
ivideo->rate_idx = sisfb_vrate[i].idx;
break;
} else if(sisfb_vrate[i].refresh > rate) {
if((sisfb_vrate[i].refresh - rate) <= 3) {
DPRINTK("sisfb: Adjusting rate from %d up to %d\n",
rate, sisfb_vrate[i].refresh);
ivideo->rate_idx = sisfb_vrate[i].idx;
ivideo->refresh_rate = sisfb_vrate[i].refresh;
} else if((sisfb_vrate[i].idx != 1) &&
((rate - sisfb_vrate[i-1].refresh) <= 2)) {
DPRINTK("sisfb: Adjusting rate from %d down to %d\n",
rate, sisfb_vrate[i-1].refresh);
ivideo->rate_idx = sisfb_vrate[i-1].idx;
ivideo->refresh_rate = sisfb_vrate[i-1].refresh;
}
break;
} else if((rate - sisfb_vrate[i].refresh) <= 2) {
DPRINTK("sisfb: Adjusting rate from %d down to %d\n",
rate, sisfb_vrate[i].refresh);
ivideo->rate_idx = sisfb_vrate[i].idx;
break;
}
}
i++;
}
if(ivideo->rate_idx > 0) {
return ivideo->rate_idx;
} else {
printk(KERN_INFO "sisfb: Unsupported rate %d for %dx%d\n",
rate, xres, yres);
return 0;
}
}
static bool
sisfb_bridgeisslave(struct sis_video_info *ivideo)
{
unsigned char P1_00;
if(!(ivideo->vbflags2 & VB2_VIDEOBRIDGE))
return false;
P1_00 = SiS_GetReg(SISPART1, 0x00);
if( ((ivideo->sisvga_engine == SIS_300_VGA) && (P1_00 & 0xa0) == 0x20) ||
((ivideo->sisvga_engine == SIS_315_VGA) && (P1_00 & 0x50) == 0x10) ) {
return true;
} else {
return false;
}
}
static bool
sisfballowretracecrt1(struct sis_video_info *ivideo)
{
u8 temp;
temp = SiS_GetReg(SISCR, 0x17);
if(!(temp & 0x80))
return false;
temp = SiS_GetReg(SISSR, 0x1f);
if(temp & 0xc0)
return false;
return true;
}
static bool
sisfbcheckvretracecrt1(struct sis_video_info *ivideo)
{
if(!sisfballowretracecrt1(ivideo))
return false;
if (SiS_GetRegByte(SISINPSTAT) & 0x08)
return true;
else
return false;
}
static void
sisfbwaitretracecrt1(struct sis_video_info *ivideo)
{
int watchdog;
if(!sisfballowretracecrt1(ivideo))
return;
watchdog = 65536;
while ((!(SiS_GetRegByte(SISINPSTAT) & 0x08)) && --watchdog);
watchdog = 65536;
while ((SiS_GetRegByte(SISINPSTAT) & 0x08) && --watchdog);
}
static bool
sisfbcheckvretracecrt2(struct sis_video_info *ivideo)
{
unsigned char temp, reg;
switch(ivideo->sisvga_engine) {
case SIS_300_VGA: reg = 0x25; break;
case SIS_315_VGA: reg = 0x30; break;
default: return false;
}
temp = SiS_GetReg(SISPART1, reg);
if(temp & 0x02)
return true;
else
return false;
}
static bool
sisfb_CheckVBRetrace(struct sis_video_info *ivideo)
{
if(ivideo->currentvbflags & VB_DISPTYPE_DISP2) {
if(!sisfb_bridgeisslave(ivideo)) {
return sisfbcheckvretracecrt2(ivideo);
}
}
return sisfbcheckvretracecrt1(ivideo);
}
static u32
sisfb_setupvbblankflags(struct sis_video_info *ivideo, u32 *vcount, u32 *hcount)
{
u8 idx, reg1, reg2, reg3, reg4;
u32 ret = 0;
(*vcount) = (*hcount) = 0;
if((ivideo->currentvbflags & VB_DISPTYPE_DISP2) && (!(sisfb_bridgeisslave(ivideo)))) {
ret |= (FB_VBLANK_HAVE_VSYNC |
FB_VBLANK_HAVE_HBLANK |
FB_VBLANK_HAVE_VBLANK |
FB_VBLANK_HAVE_VCOUNT |
FB_VBLANK_HAVE_HCOUNT);
switch(ivideo->sisvga_engine) {
case SIS_300_VGA: idx = 0x25; break;
default:
case SIS_315_VGA: idx = 0x30; break;
}
reg1 = SiS_GetReg(SISPART1, (idx+0)); /* 30 */
reg2 = SiS_GetReg(SISPART1, (idx+1)); /* 31 */
reg3 = SiS_GetReg(SISPART1, (idx+2)); /* 32 */
reg4 = SiS_GetReg(SISPART1, (idx+3)); /* 33 */
if(reg1 & 0x01) ret |= FB_VBLANK_VBLANKING;
if(reg1 & 0x02) ret |= FB_VBLANK_VSYNCING;
if(reg4 & 0x80) ret |= FB_VBLANK_HBLANKING;
(*vcount) = reg3 | ((reg4 & 0x70) << 4);
(*hcount) = reg2 | ((reg4 & 0x0f) << 8);
} else if(sisfballowretracecrt1(ivideo)) {
ret |= (FB_VBLANK_HAVE_VSYNC |
FB_VBLANK_HAVE_VBLANK |
FB_VBLANK_HAVE_VCOUNT |
FB_VBLANK_HAVE_HCOUNT);
reg1 = SiS_GetRegByte(SISINPSTAT);
if(reg1 & 0x08) ret |= FB_VBLANK_VSYNCING;
if(reg1 & 0x01) ret |= FB_VBLANK_VBLANKING;
reg1 = SiS_GetReg(SISCR, 0x20);
reg1 = SiS_GetReg(SISCR, 0x1b);
reg2 = SiS_GetReg(SISCR, 0x1c);
reg3 = SiS_GetReg(SISCR, 0x1d);
(*vcount) = reg2 | ((reg3 & 0x07) << 8);
(*hcount) = (reg1 | ((reg3 & 0x10) << 4)) << 3;
}
return ret;
}
static int
sisfb_myblank(struct sis_video_info *ivideo, int blank)
{
u8 sr01, sr11, sr1f, cr63=0, p2_0, p1_13;
bool backlight = true;
switch(blank) {
case FB_BLANK_UNBLANK: /* on */
sr01 = 0x00;
sr11 = 0x00;
sr1f = 0x00;
cr63 = 0x00;
p2_0 = 0x20;
p1_13 = 0x00;
backlight = true;
break;
case FB_BLANK_NORMAL: /* blank */
sr01 = 0x20;
sr11 = 0x00;
sr1f = 0x00;
cr63 = 0x00;
p2_0 = 0x20;
p1_13 = 0x00;
backlight = true;
break;
case FB_BLANK_VSYNC_SUSPEND: /* no vsync */
sr01 = 0x20;
sr11 = 0x08;
sr1f = 0x80;
cr63 = 0x40;
p2_0 = 0x40;
p1_13 = 0x80;
backlight = false;
break;
case FB_BLANK_HSYNC_SUSPEND: /* no hsync */
sr01 = 0x20;
sr11 = 0x08;
sr1f = 0x40;
cr63 = 0x40;
p2_0 = 0x80;
p1_13 = 0x40;
backlight = false;
break;
case FB_BLANK_POWERDOWN: /* off */
sr01 = 0x20;
sr11 = 0x08;
sr1f = 0xc0;
cr63 = 0x40;
p2_0 = 0xc0;
p1_13 = 0xc0;
backlight = false;
break;
default:
return 1;
}
if(ivideo->currentvbflags & VB_DISPTYPE_CRT1) {
if( (!ivideo->sisfb_thismonitor.datavalid) ||
((ivideo->sisfb_thismonitor.datavalid) &&
(ivideo->sisfb_thismonitor.feature & 0xe0))) {
if(ivideo->sisvga_engine == SIS_315_VGA) {
SiS_SetRegANDOR(SISCR, ivideo->SiS_Pr.SiS_MyCR63, 0xbf, cr63);
}
if(!(sisfb_bridgeisslave(ivideo))) {
SiS_SetRegANDOR(SISSR, 0x01, ~0x20, sr01);
SiS_SetRegANDOR(SISSR, 0x1f, 0x3f, sr1f);
}
}
}
if(ivideo->currentvbflags & CRT2_LCD) {
if(ivideo->vbflags2 & VB2_SISLVDSBRIDGE) {
if(backlight) {
SiS_SiS30xBLOn(&ivideo->SiS_Pr);
} else {
SiS_SiS30xBLOff(&ivideo->SiS_Pr);
}
} else if(ivideo->sisvga_engine == SIS_315_VGA) {
#ifdef CONFIG_FB_SIS_315
if(ivideo->vbflags2 & VB2_CHRONTEL) {
if(backlight) {
SiS_Chrontel701xBLOn(&ivideo->SiS_Pr);
} else {
SiS_Chrontel701xBLOff(&ivideo->SiS_Pr);
}
}
#endif
}
if(((ivideo->sisvga_engine == SIS_300_VGA) &&
(ivideo->vbflags2 & (VB2_301|VB2_30xBDH|VB2_LVDS))) ||
((ivideo->sisvga_engine == SIS_315_VGA) &&
((ivideo->vbflags2 & (VB2_LVDS | VB2_CHRONTEL)) == VB2_LVDS))) {
SiS_SetRegANDOR(SISSR, 0x11, ~0x0c, sr11);
}
if(ivideo->sisvga_engine == SIS_300_VGA) {
if((ivideo->vbflags2 & VB2_30xB) &&
(!(ivideo->vbflags2 & VB2_30xBDH))) {
SiS_SetRegANDOR(SISPART1, 0x13, 0x3f, p1_13);
}
} else if(ivideo->sisvga_engine == SIS_315_VGA) {
if((ivideo->vbflags2 & VB2_30xB) &&
(!(ivideo->vbflags2 & VB2_30xBDH))) {
SiS_SetRegANDOR(SISPART2, 0x00, 0x1f, p2_0);
}
}
} else if(ivideo->currentvbflags & CRT2_VGA) {
if(ivideo->vbflags2 & VB2_30xB) {
SiS_SetRegANDOR(SISPART2, 0x00, 0x1f, p2_0);
}
}
return 0;
}
/* ------------- Callbacks from init.c/init301.c -------------- */
#ifdef CONFIG_FB_SIS_300
unsigned int
sisfb_read_nbridge_pci_dword(struct SiS_Private *SiS_Pr, int reg)
{
struct sis_video_info *ivideo = (struct sis_video_info *)SiS_Pr->ivideo;
u32 val = 0;
pci_read_config_dword(ivideo->nbridge, reg, &val);
return (unsigned int)val;
}
void
sisfb_write_nbridge_pci_dword(struct SiS_Private *SiS_Pr, int reg, unsigned int val)
{
struct sis_video_info *ivideo = (struct sis_video_info *)SiS_Pr->ivideo;
pci_write_config_dword(ivideo->nbridge, reg, (u32)val);
}
unsigned int
sisfb_read_lpc_pci_dword(struct SiS_Private *SiS_Pr, int reg)
{
struct sis_video_info *ivideo = (struct sis_video_info *)SiS_Pr->ivideo;
u32 val = 0;
if(!ivideo->lpcdev) return 0;
pci_read_config_dword(ivideo->lpcdev, reg, &val);
return (unsigned int)val;
}
#endif
#ifdef CONFIG_FB_SIS_315
void
sisfb_write_nbridge_pci_byte(struct SiS_Private *SiS_Pr, int reg, unsigned char val)
{
struct sis_video_info *ivideo = (struct sis_video_info *)SiS_Pr->ivideo;
pci_write_config_byte(ivideo->nbridge, reg, (u8)val);
}
unsigned int
sisfb_read_mio_pci_word(struct SiS_Private *SiS_Pr, int reg)
{
struct sis_video_info *ivideo = (struct sis_video_info *)SiS_Pr->ivideo;
u16 val = 0;
if(!ivideo->lpcdev) return 0;
pci_read_config_word(ivideo->lpcdev, reg, &val);
return (unsigned int)val;
}
#endif
/* ----------- FBDev related routines for all series ----------- */
static int
sisfb_get_cmap_len(const struct fb_var_screeninfo *var)
{
return (var->bits_per_pixel == 8) ? 256 : 16;
}
static void
sisfb_set_vparms(struct sis_video_info *ivideo)
{
switch(ivideo->video_bpp) {
case 8:
ivideo->DstColor = 0x0000;
ivideo->SiS310_AccelDepth = 0x00000000;
ivideo->video_cmap_len = 256;
break;
case 16:
ivideo->DstColor = 0x8000;
ivideo->SiS310_AccelDepth = 0x00010000;
ivideo->video_cmap_len = 16;
break;
case 32:
ivideo->DstColor = 0xC000;
ivideo->SiS310_AccelDepth = 0x00020000;
ivideo->video_cmap_len = 16;
break;
default:
ivideo->video_cmap_len = 16;
printk(KERN_ERR "sisfb: Unsupported depth %d", ivideo->video_bpp);
ivideo->accel = 0;
}
}
static int
sisfb_calc_maxyres(struct sis_video_info *ivideo, struct fb_var_screeninfo *var)
{
int maxyres = ivideo->sisfb_mem / (var->xres_virtual * (var->bits_per_pixel >> 3));
if(maxyres > 32767) maxyres = 32767;
return maxyres;
}
static void
sisfb_calc_pitch(struct sis_video_info *ivideo, struct fb_var_screeninfo *var)
{
ivideo->video_linelength = var->xres_virtual * (var->bits_per_pixel >> 3);
ivideo->scrnpitchCRT1 = ivideo->video_linelength;
if(!(ivideo->currentvbflags & CRT1_LCDA)) {
if((var->vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED) {
ivideo->scrnpitchCRT1 <<= 1;
}
}
}
static void
sisfb_set_pitch(struct sis_video_info *ivideo)
{
bool isslavemode = false;
unsigned short HDisplay1 = ivideo->scrnpitchCRT1 >> 3;
unsigned short HDisplay2 = ivideo->video_linelength >> 3;
if(sisfb_bridgeisslave(ivideo)) isslavemode = true;
/* We need to set pitch for CRT1 if bridge is in slave mode, too */
if((ivideo->currentvbflags & VB_DISPTYPE_DISP1) || (isslavemode)) {
SiS_SetReg(SISCR, 0x13, (HDisplay1 & 0xFF));
SiS_SetRegANDOR(SISSR, 0x0E, 0xF0, (HDisplay1 >> 8));
}
/* We must not set the pitch for CRT2 if bridge is in slave mode */
if((ivideo->currentvbflags & VB_DISPTYPE_DISP2) && (!isslavemode)) {
SiS_SetRegOR(SISPART1, ivideo->CRT2_write_enable, 0x01);
SiS_SetReg(SISPART1, 0x07, (HDisplay2 & 0xFF));
SiS_SetRegANDOR(SISPART1, 0x09, 0xF0, (HDisplay2 >> 8));
}
}
static void
sisfb_bpp_to_var(struct sis_video_info *ivideo, struct fb_var_screeninfo *var)
{
ivideo->video_cmap_len = sisfb_get_cmap_len(var);
switch(var->bits_per_pixel) {
case 8:
var->red.offset = var->green.offset = var->blue.offset = 0;
var->red.length = var->green.length = var->blue.length = 8;
break;
case 16:
var->red.offset = 11;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 6;
var->blue.offset = 0;
var->blue.length = 5;
var->transp.offset = 0;
var->transp.length = 0;
break;
case 32:
var->red.offset = 16;
var->red.length = 8;
var->green.offset = 8;
var->green.length = 8;
var->blue.offset = 0;
var->blue.length = 8;
var->transp.offset = 24;
var->transp.length = 8;
break;
}
}
static int
sisfb_set_mode(struct sis_video_info *ivideo, int clrscrn)
{
unsigned short modeno = ivideo->mode_no;
/* >=2.6.12's fbcon clears the screen anyway */
modeno |= 0x80;
SiS_SetReg(SISSR, IND_SIS_PASSWORD, SIS_PASSWORD);
sisfb_pre_setmode(ivideo);
if(!SiSSetMode(&ivideo->SiS_Pr, modeno)) {
printk(KERN_ERR "sisfb: Setting mode[0x%x] failed\n", ivideo->mode_no);
return -EINVAL;
}
SiS_SetReg(SISSR, IND_SIS_PASSWORD, SIS_PASSWORD);
sisfb_post_setmode(ivideo);
return 0;
}
static int
sisfb_do_set_var(struct fb_var_screeninfo *var, int isactive, struct fb_info *info)
{
struct sis_video_info *ivideo = (struct sis_video_info *)info->par;
unsigned int htotal = 0, vtotal = 0;
unsigned int drate = 0, hrate = 0;
int found_mode = 0, ret;
int old_mode;
u32 pixclock;
htotal = var->left_margin + var->xres + var->right_margin + var->hsync_len;
vtotal = var->upper_margin + var->lower_margin + var->vsync_len;
pixclock = var->pixclock;
if((var->vmode & FB_VMODE_MASK) == FB_VMODE_NONINTERLACED) {
vtotal += var->yres;
vtotal <<= 1;
} else if((var->vmode & FB_VMODE_MASK) == FB_VMODE_DOUBLE) {
vtotal += var->yres;
vtotal <<= 2;
} else if((var->vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED) {
vtotal += var->yres;
vtotal <<= 1;
} else vtotal += var->yres;
if(!(htotal) || !(vtotal)) {
DPRINTK("sisfb: Invalid 'var' information\n");
return -EINVAL;
}
if(pixclock && htotal && vtotal) {
drate = 1000000000 / pixclock;
hrate = (drate * 1000) / htotal;
ivideo->refresh_rate = (unsigned int) (hrate * 2 / vtotal);
} else {
ivideo->refresh_rate = 60;
}
old_mode = ivideo->sisfb_mode_idx;
ivideo->sisfb_mode_idx = 0;
while( (sisbios_mode[ivideo->sisfb_mode_idx].mode_no[0] != 0) &&
(sisbios_mode[ivideo->sisfb_mode_idx].xres <= var->xres) ) {
if( (sisbios_mode[ivideo->sisfb_mode_idx].xres == var->xres) &&
(sisbios_mode[ivideo->sisfb_mode_idx].yres == var->yres) &&
(sisbios_mode[ivideo->sisfb_mode_idx].bpp == var->bits_per_pixel)) {
ivideo->mode_no = sisbios_mode[ivideo->sisfb_mode_idx].mode_no[ivideo->mni];
found_mode = 1;
break;
}
ivideo->sisfb_mode_idx++;
}
if(found_mode) {
ivideo->sisfb_mode_idx = sisfb_validate_mode(ivideo,
ivideo->sisfb_mode_idx, ivideo->currentvbflags);
} else {
ivideo->sisfb_mode_idx = -1;
}
if(ivideo->sisfb_mode_idx < 0) {
printk(KERN_ERR "sisfb: Mode %dx%dx%d not supported\n", var->xres,
var->yres, var->bits_per_pixel);
ivideo->sisfb_mode_idx = old_mode;
return -EINVAL;
}
ivideo->mode_no = sisbios_mode[ivideo->sisfb_mode_idx].mode_no[ivideo->mni];
if(sisfb_search_refresh_rate(ivideo, ivideo->refresh_rate, ivideo->sisfb_mode_idx) == 0) {
ivideo->rate_idx = sisbios_mode[ivideo->sisfb_mode_idx].rate_idx;
ivideo->refresh_rate = 60;
}
if(isactive) {
/* If acceleration to be used? Need to know
* before pre/post_set_mode()
*/
ivideo->accel = 0;
#if defined(FBINFO_HWACCEL_DISABLED) && defined(FBINFO_HWACCEL_XPAN)
#ifdef STUPID_ACCELF_TEXT_SHIT
if(var->accel_flags & FB_ACCELF_TEXT) {
info->flags &= ~FBINFO_HWACCEL_DISABLED;
} else {
info->flags |= FBINFO_HWACCEL_DISABLED;
}
#endif
if(!(info->flags & FBINFO_HWACCEL_DISABLED)) ivideo->accel = -1;
#else
if(var->accel_flags & FB_ACCELF_TEXT) ivideo->accel = -1;
#endif
if((ret = sisfb_set_mode(ivideo, 1))) {
return ret;
}
ivideo->video_bpp = sisbios_mode[ivideo->sisfb_mode_idx].bpp;
ivideo->video_width = sisbios_mode[ivideo->sisfb_mode_idx].xres;
ivideo->video_height = sisbios_mode[ivideo->sisfb_mode_idx].yres;
sisfb_calc_pitch(ivideo, var);
sisfb_set_pitch(ivideo);
sisfb_set_vparms(ivideo);
ivideo->current_width = ivideo->video_width;
ivideo->current_height = ivideo->video_height;
ivideo->current_bpp = ivideo->video_bpp;
ivideo->current_htotal = htotal;
ivideo->current_vtotal = vtotal;
ivideo->current_linelength = ivideo->video_linelength;
ivideo->current_pixclock = var->pixclock;
ivideo->current_refresh_rate = ivideo->refresh_rate;
ivideo->sisfb_lastrates[ivideo->mode_no] = ivideo->refresh_rate;
}
return 0;
}
static void
sisfb_set_base_CRT1(struct sis_video_info *ivideo, unsigned int base)
{
SiS_SetReg(SISSR, IND_SIS_PASSWORD, SIS_PASSWORD);
SiS_SetReg(SISCR, 0x0D, base & 0xFF);
SiS_SetReg(SISCR, 0x0C, (base >> 8) & 0xFF);
SiS_SetReg(SISSR, 0x0D, (base >> 16) & 0xFF);
if(ivideo->sisvga_engine == SIS_315_VGA) {
SiS_SetRegANDOR(SISSR, 0x37, 0xFE, (base >> 24) & 0x01);
}
}
static void
sisfb_set_base_CRT2(struct sis_video_info *ivideo, unsigned int base)
{
if(ivideo->currentvbflags & VB_DISPTYPE_DISP2) {
SiS_SetRegOR(SISPART1, ivideo->CRT2_write_enable, 0x01);
SiS_SetReg(SISPART1, 0x06, (base & 0xFF));
SiS_SetReg(SISPART1, 0x05, ((base >> 8) & 0xFF));
SiS_SetReg(SISPART1, 0x04, ((base >> 16) & 0xFF));
if(ivideo->sisvga_engine == SIS_315_VGA) {
SiS_SetRegANDOR(SISPART1, 0x02, 0x7F, ((base >> 24) & 0x01) << 7);
}
}
}
static int
sisfb_pan_var(struct sis_video_info *ivideo, struct fb_info *info,
struct fb_var_screeninfo *var)
{
ivideo->current_base = var->yoffset * info->var.xres_virtual
+ var->xoffset;
/* calculate base bpp dep. */
switch (info->var.bits_per_pixel) {
case 32:
break;
case 16:
ivideo->current_base >>= 1;
break;
case 8:
default:
ivideo->current_base >>= 2;
break;
}
ivideo->current_base += (ivideo->video_offset >> 2);
sisfb_set_base_CRT1(ivideo, ivideo->current_base);
sisfb_set_base_CRT2(ivideo, ivideo->current_base);
return 0;
}
static int
sisfb_open(struct fb_info *info, int user)
{
return 0;
}
static int
sisfb_release(struct fb_info *info, int user)
{
return 0;
}
static int
sisfb_setcolreg(unsigned regno, unsigned red, unsigned green, unsigned blue,
unsigned transp, struct fb_info *info)
{
struct sis_video_info *ivideo = (struct sis_video_info *)info->par;
if(regno >= sisfb_get_cmap_len(&info->var))
return 1;
switch(info->var.bits_per_pixel) {
case 8:
SiS_SetRegByte(SISDACA, regno);
SiS_SetRegByte(SISDACD, (red >> 10));
SiS_SetRegByte(SISDACD, (green >> 10));
SiS_SetRegByte(SISDACD, (blue >> 10));
if(ivideo->currentvbflags & VB_DISPTYPE_DISP2) {
SiS_SetRegByte(SISDAC2A, regno);
SiS_SetRegByte(SISDAC2D, (red >> 8));
SiS_SetRegByte(SISDAC2D, (green >> 8));
SiS_SetRegByte(SISDAC2D, (blue >> 8));
}
break;
case 16:
if (regno >= 16)
break;
((u32 *)(info->pseudo_palette))[regno] =
(red & 0xf800) |
((green & 0xfc00) >> 5) |
((blue & 0xf800) >> 11);
break;
case 32:
if (regno >= 16)
break;
red >>= 8;
green >>= 8;
blue >>= 8;
((u32 *)(info->pseudo_palette))[regno] =
(red << 16) | (green << 8) | (blue);
break;
}
return 0;
}
static int
sisfb_set_par(struct fb_info *info)
{
int err;
if((err = sisfb_do_set_var(&info->var, 1, info)))
return err;
sisfb_get_fix(&info->fix, -1, info);
return 0;
}
static int
sisfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
struct sis_video_info *ivideo = (struct sis_video_info *)info->par;
unsigned int htotal = 0, vtotal = 0, myrateindex = 0;
unsigned int drate = 0, hrate = 0, maxyres;
int found_mode = 0;
int refresh_rate, search_idx, tidx;
bool recalc_clock = false;
u32 pixclock;
htotal = var->left_margin + var->xres + var->right_margin + var->hsync_len;
vtotal = var->upper_margin + var->lower_margin + var->vsync_len;
pixclock = var->pixclock;
if((var->vmode & FB_VMODE_MASK) == FB_VMODE_NONINTERLACED) {
vtotal += var->yres;
vtotal <<= 1;
} else if((var->vmode & FB_VMODE_MASK) == FB_VMODE_DOUBLE) {
vtotal += var->yres;
vtotal <<= 2;
} else if((var->vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED) {
vtotal += var->yres;
vtotal <<= 1;
} else
vtotal += var->yres;
if(!(htotal) || !(vtotal)) {
SISFAIL("sisfb: no valid timing data");
}
search_idx = 0;
while( (sisbios_mode[search_idx].mode_no[0] != 0) &&
(sisbios_mode[search_idx].xres <= var->xres) ) {
if( (sisbios_mode[search_idx].xres == var->xres) &&
(sisbios_mode[search_idx].yres == var->yres) &&
(sisbios_mode[search_idx].bpp == var->bits_per_pixel)) {
if((tidx = sisfb_validate_mode(ivideo, search_idx,
ivideo->currentvbflags)) > 0) {
found_mode = 1;
search_idx = tidx;
break;
}
}
search_idx++;
}
if(!found_mode) {
search_idx = 0;
while(sisbios_mode[search_idx].mode_no[0] != 0) {
if( (var->xres <= sisbios_mode[search_idx].xres) &&
(var->yres <= sisbios_mode[search_idx].yres) &&
(var->bits_per_pixel == sisbios_mode[search_idx].bpp) ) {
if((tidx = sisfb_validate_mode(ivideo,search_idx,
ivideo->currentvbflags)) > 0) {
found_mode = 1;
search_idx = tidx;
break;
}
}
search_idx++;
}
if(found_mode) {
printk(KERN_DEBUG
"sisfb: Adapted from %dx%dx%d to %dx%dx%d\n",
var->xres, var->yres, var->bits_per_pixel,
sisbios_mode[search_idx].xres,
sisbios_mode[search_idx].yres,
var->bits_per_pixel);
var->xres = sisbios_mode[search_idx].xres;
var->yres = sisbios_mode[search_idx].yres;
} else {
printk(KERN_ERR
"sisfb: Failed to find supported mode near %dx%dx%d\n",
var->xres, var->yres, var->bits_per_pixel);
return -EINVAL;
}
}
if( ((ivideo->vbflags2 & VB2_LVDS) ||
((ivideo->vbflags2 & VB2_30xBDH) && (ivideo->currentvbflags & CRT2_LCD))) &&
(var->bits_per_pixel == 8) ) {
/* Slave modes on LVDS and 301B-DH */
refresh_rate = 60;
recalc_clock = true;
} else if( (ivideo->current_htotal == htotal) &&
(ivideo->current_vtotal == vtotal) &&
(ivideo->current_pixclock == pixclock) ) {
/* x=x & y=y & c=c -> assume depth change */
drate = 1000000000 / pixclock;
hrate = (drate * 1000) / htotal;
refresh_rate = (unsigned int) (hrate * 2 / vtotal);
} else if( ( (ivideo->current_htotal != htotal) ||
(ivideo->current_vtotal != vtotal) ) &&
(ivideo->current_pixclock == var->pixclock) ) {
/* x!=x | y!=y & c=c -> invalid pixclock */
if(ivideo->sisfb_lastrates[sisbios_mode[search_idx].mode_no[ivideo->mni]]) {
refresh_rate =
ivideo->sisfb_lastrates[sisbios_mode[search_idx].mode_no[ivideo->mni]];
} else if(ivideo->sisfb_parm_rate != -1) {
/* Sic, sisfb_parm_rate - want to know originally desired rate here */
refresh_rate = ivideo->sisfb_parm_rate;
} else {
refresh_rate = 60;
}
recalc_clock = true;
} else if((pixclock) && (htotal) && (vtotal)) {
drate = 1000000000 / pixclock;
hrate = (drate * 1000) / htotal;
refresh_rate = (unsigned int) (hrate * 2 / vtotal);
} else if(ivideo->current_refresh_rate) {
refresh_rate = ivideo->current_refresh_rate;
recalc_clock = true;
} else {
refresh_rate = 60;
recalc_clock = true;
}
myrateindex = sisfb_search_refresh_rate(ivideo, refresh_rate, search_idx);
/* Eventually recalculate timing and clock */
if(recalc_clock) {
if(!myrateindex) myrateindex = sisbios_mode[search_idx].rate_idx;
var->pixclock = (u32) (1000000000 / sisfb_mode_rate_to_dclock(&ivideo->SiS_Pr,
sisbios_mode[search_idx].mode_no[ivideo->mni],
myrateindex));
sisfb_mode_rate_to_ddata(&ivideo->SiS_Pr,
sisbios_mode[search_idx].mode_no[ivideo->mni],
myrateindex, var);
if((var->vmode & FB_VMODE_MASK) == FB_VMODE_DOUBLE) {
var->pixclock <<= 1;
}
}
if(ivideo->sisfb_thismonitor.datavalid) {
if(!sisfb_verify_rate(ivideo, &ivideo->sisfb_thismonitor, search_idx,
myrateindex, refresh_rate)) {
printk(KERN_INFO
"sisfb: WARNING: Refresh rate exceeds monitor specs!\n");
}
}
/* Adapt RGB settings */
sisfb_bpp_to_var(ivideo, var);
/* Sanity check for offsets */
if(var->xoffset < 0) var->xoffset = 0;
if(var->yoffset < 0) var->yoffset = 0;
if(var->xres > var->xres_virtual)
var->xres_virtual = var->xres;
if(ivideo->sisfb_ypan) {
maxyres = sisfb_calc_maxyres(ivideo, var);
if(ivideo->sisfb_max) {
var->yres_virtual = maxyres;
} else {
if(var->yres_virtual > maxyres) {
var->yres_virtual = maxyres;
}
}
if(var->yres_virtual <= var->yres) {
var->yres_virtual = var->yres;
}
} else {
if(var->yres != var->yres_virtual) {
var->yres_virtual = var->yres;
}
var->xoffset = 0;
var->yoffset = 0;
}
/* Truncate offsets to maximum if too high */
if(var->xoffset > var->xres_virtual - var->xres) {
var->xoffset = var->xres_virtual - var->xres - 1;
}
if(var->yoffset > var->yres_virtual - var->yres) {
var->yoffset = var->yres_virtual - var->yres - 1;
}
/* Set everything else to 0 */
var->red.msb_right =
var->green.msb_right =
var->blue.msb_right =
var->transp.offset =
var->transp.length =
var->transp.msb_right = 0;
return 0;
}
static int
sisfb_pan_display(struct fb_var_screeninfo *var, struct fb_info* info)
{
struct sis_video_info *ivideo = (struct sis_video_info *)info->par;
int err;
if (var->vmode & FB_VMODE_YWRAP)
return -EINVAL;
if (var->xoffset + info->var.xres > info->var.xres_virtual ||
var->yoffset + info->var.yres > info->var.yres_virtual)
return -EINVAL;
err = sisfb_pan_var(ivideo, info, var);
if (err < 0)
return err;
info->var.xoffset = var->xoffset;
info->var.yoffset = var->yoffset;
return 0;
}
static int
sisfb_blank(int blank, struct fb_info *info)
{
struct sis_video_info *ivideo = (struct sis_video_info *)info->par;
return sisfb_myblank(ivideo, blank);
}
/* ----------- FBDev related routines for all series ---------- */
static int sisfb_ioctl(struct fb_info *info, unsigned int cmd,
unsigned long arg)
{
struct sis_video_info *ivideo = (struct sis_video_info *)info->par;
struct sis_memreq sismemreq;
struct fb_vblank sisvbblank;
u32 gpu32 = 0;
#ifndef __user
#define __user
#endif
u32 __user *argp = (u32 __user *)arg;
switch(cmd) {
case FBIO_ALLOC:
if(!capable(CAP_SYS_RAWIO))
return -EPERM;
if(copy_from_user(&sismemreq, (void __user *)arg, sizeof(sismemreq)))
return -EFAULT;
sis_malloc(&sismemreq);
if(copy_to_user((void __user *)arg, &sismemreq, sizeof(sismemreq))) {
sis_free((u32)sismemreq.offset);
return -EFAULT;
}
break;
case FBIO_FREE:
if(!capable(CAP_SYS_RAWIO))
return -EPERM;
if(get_user(gpu32, argp))
return -EFAULT;
sis_free(gpu32);
break;
case FBIOGET_VBLANK:
memset(&sisvbblank, 0, sizeof(struct fb_vblank));
sisvbblank.count = 0;
sisvbblank.flags = sisfb_setupvbblankflags(ivideo, &sisvbblank.vcount, &sisvbblank.hcount);
if(copy_to_user((void __user *)arg, &sisvbblank, sizeof(sisvbblank)))
return -EFAULT;
break;
case SISFB_GET_INFO_SIZE:
return put_user(sizeof(struct sisfb_info), argp);
case SISFB_GET_INFO_OLD:
if(ivideo->warncount++ < 10)
printk(KERN_INFO
"sisfb: Deprecated ioctl call received - update your application!\n");
case SISFB_GET_INFO: /* For communication with X driver */
ivideo->sisfb_infoblock.sisfb_id = SISFB_ID;
ivideo->sisfb_infoblock.sisfb_version = VER_MAJOR;
ivideo->sisfb_infoblock.sisfb_revision = VER_MINOR;
ivideo->sisfb_infoblock.sisfb_patchlevel = VER_LEVEL;
ivideo->sisfb_infoblock.chip_id = ivideo->chip_id;
ivideo->sisfb_infoblock.sisfb_pci_vendor = ivideo->chip_vendor;
ivideo->sisfb_infoblock.memory = ivideo->video_size / 1024;
ivideo->sisfb_infoblock.heapstart = ivideo->heapstart / 1024;
if(ivideo->modechanged) {
ivideo->sisfb_infoblock.fbvidmode = ivideo->mode_no;
} else {
ivideo->sisfb_infoblock.fbvidmode = ivideo->modeprechange;
}
ivideo->sisfb_infoblock.sisfb_caps = ivideo->caps;
ivideo->sisfb_infoblock.sisfb_tqlen = ivideo->cmdQueueSize / 1024;
ivideo->sisfb_infoblock.sisfb_pcibus = ivideo->pcibus;
ivideo->sisfb_infoblock.sisfb_pcislot = ivideo->pcislot;
ivideo->sisfb_infoblock.sisfb_pcifunc = ivideo->pcifunc;
ivideo->sisfb_infoblock.sisfb_lcdpdc = ivideo->detectedpdc;
ivideo->sisfb_infoblock.sisfb_lcdpdca = ivideo->detectedpdca;
ivideo->sisfb_infoblock.sisfb_lcda = ivideo->detectedlcda;
ivideo->sisfb_infoblock.sisfb_vbflags = ivideo->vbflags;
ivideo->sisfb_infoblock.sisfb_currentvbflags = ivideo->currentvbflags;
ivideo->sisfb_infoblock.sisfb_scalelcd = ivideo->SiS_Pr.UsePanelScaler;
ivideo->sisfb_infoblock.sisfb_specialtiming = ivideo->SiS_Pr.SiS_CustomT;
ivideo->sisfb_infoblock.sisfb_haveemi = ivideo->SiS_Pr.HaveEMI ? 1 : 0;
ivideo->sisfb_infoblock.sisfb_haveemilcd = ivideo->SiS_Pr.HaveEMILCD ? 1 : 0;
ivideo->sisfb_infoblock.sisfb_emi30 = ivideo->SiS_Pr.EMI_30;
ivideo->sisfb_infoblock.sisfb_emi31 = ivideo->SiS_Pr.EMI_31;
ivideo->sisfb_infoblock.sisfb_emi32 = ivideo->SiS_Pr.EMI_32;
ivideo->sisfb_infoblock.sisfb_emi33 = ivideo->SiS_Pr.EMI_33;
ivideo->sisfb_infoblock.sisfb_tvxpos = (u16)(ivideo->tvxpos + 32);
ivideo->sisfb_infoblock.sisfb_tvypos = (u16)(ivideo->tvypos + 32);
ivideo->sisfb_infoblock.sisfb_heapsize = ivideo->sisfb_heap_size / 1024;
ivideo->sisfb_infoblock.sisfb_videooffset = ivideo->video_offset;
ivideo->sisfb_infoblock.sisfb_curfstn = ivideo->curFSTN;
ivideo->sisfb_infoblock.sisfb_curdstn = ivideo->curDSTN;
ivideo->sisfb_infoblock.sisfb_vbflags2 = ivideo->vbflags2;
ivideo->sisfb_infoblock.sisfb_can_post = ivideo->sisfb_can_post ? 1 : 0;
ivideo->sisfb_infoblock.sisfb_card_posted = ivideo->sisfb_card_posted ? 1 : 0;
ivideo->sisfb_infoblock.sisfb_was_boot_device = ivideo->sisfb_was_boot_device ? 1 : 0;
if(copy_to_user((void __user *)arg, &ivideo->sisfb_infoblock,
sizeof(ivideo->sisfb_infoblock)))
return -EFAULT;
break;
case SISFB_GET_VBRSTATUS_OLD:
if(ivideo->warncount++ < 10)
printk(KERN_INFO
"sisfb: Deprecated ioctl call received - update your application!\n");
case SISFB_GET_VBRSTATUS:
if(sisfb_CheckVBRetrace(ivideo))
return put_user((u32)1, argp);
else
return put_user((u32)0, argp);
case SISFB_GET_AUTOMAXIMIZE_OLD:
if(ivideo->warncount++ < 10)
printk(KERN_INFO
"sisfb: Deprecated ioctl call received - update your application!\n");
case SISFB_GET_AUTOMAXIMIZE:
if(ivideo->sisfb_max)
return put_user((u32)1, argp);
else
return put_user((u32)0, argp);
case SISFB_SET_AUTOMAXIMIZE_OLD:
if(ivideo->warncount++ < 10)
printk(KERN_INFO
"sisfb: Deprecated ioctl call received - update your application!\n");
case SISFB_SET_AUTOMAXIMIZE:
if(get_user(gpu32, argp))
return -EFAULT;
ivideo->sisfb_max = (gpu32) ? 1 : 0;
break;
case SISFB_SET_TVPOSOFFSET:
if(get_user(gpu32, argp))
return -EFAULT;
sisfb_set_TVxposoffset(ivideo, ((int)(gpu32 >> 16)) - 32);
sisfb_set_TVyposoffset(ivideo, ((int)(gpu32 & 0xffff)) - 32);
break;
case SISFB_GET_TVPOSOFFSET:
return put_user((u32)(((ivideo->tvxpos+32)<<16)|((ivideo->tvypos+32)&0xffff)),
argp);
case SISFB_COMMAND:
if(copy_from_user(&ivideo->sisfb_command, (void __user *)arg,
sizeof(struct sisfb_cmd)))
return -EFAULT;
sisfb_handle_command(ivideo, &ivideo->sisfb_command);
if(copy_to_user((void __user *)arg, &ivideo->sisfb_command,
sizeof(struct sisfb_cmd)))
return -EFAULT;
break;
case SISFB_SET_LOCK:
if(get_user(gpu32, argp))
return -EFAULT;
ivideo->sisfblocked = (gpu32) ? 1 : 0;
break;
default:
#ifdef SIS_NEW_CONFIG_COMPAT
return -ENOIOCTLCMD;
#else
return -EINVAL;
#endif
}
return 0;
}
static int
sisfb_get_fix(struct fb_fix_screeninfo *fix, int con, struct fb_info *info)
{
struct sis_video_info *ivideo = (struct sis_video_info *)info->par;
memset(fix, 0, sizeof(struct fb_fix_screeninfo));
strlcpy(fix->id, ivideo->myid, sizeof(fix->id));
mutex_lock(&info->mm_lock);
fix->smem_start = ivideo->video_base + ivideo->video_offset;
fix->smem_len = ivideo->sisfb_mem;
mutex_unlock(&info->mm_lock);
fix->type = FB_TYPE_PACKED_PIXELS;
fix->type_aux = 0;
fix->visual = (ivideo->video_bpp == 8) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_TRUECOLOR;
fix->xpanstep = 1;
fix->ypanstep = (ivideo->sisfb_ypan) ? 1 : 0;
fix->ywrapstep = 0;
fix->line_length = ivideo->video_linelength;
fix->mmio_start = ivideo->mmio_base;
fix->mmio_len = ivideo->mmio_size;
if(ivideo->sisvga_engine == SIS_300_VGA) {
fix->accel = FB_ACCEL_SIS_GLAMOUR;
} else if((ivideo->chip == SIS_330) ||
(ivideo->chip == SIS_760) ||
(ivideo->chip == SIS_761)) {
fix->accel = FB_ACCEL_SIS_XABRE;
} else if(ivideo->chip == XGI_20) {
fix->accel = FB_ACCEL_XGI_VOLARI_Z;
} else if(ivideo->chip >= XGI_40) {
fix->accel = FB_ACCEL_XGI_VOLARI_V;
} else {
fix->accel = FB_ACCEL_SIS_GLAMOUR_2;
}
return 0;
}
/* ---------------- fb_ops structures ----------------- */
static struct fb_ops sisfb_ops = {
.owner = THIS_MODULE,
.fb_open = sisfb_open,
.fb_release = sisfb_release,
.fb_check_var = sisfb_check_var,
.fb_set_par = sisfb_set_par,
.fb_setcolreg = sisfb_setcolreg,
.fb_pan_display = sisfb_pan_display,
.fb_blank = sisfb_blank,
.fb_fillrect = fbcon_sis_fillrect,
.fb_copyarea = fbcon_sis_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_sync = fbcon_sis_sync,
#ifdef SIS_NEW_CONFIG_COMPAT
.fb_compat_ioctl= sisfb_ioctl,
#endif
.fb_ioctl = sisfb_ioctl
};
/* ---------------- Chip generation dependent routines ---------------- */
static struct pci_dev * __devinit
sisfb_get_northbridge(int basechipid)
{
struct pci_dev *pdev = NULL;
int nbridgenum, nbridgeidx, i;
static const unsigned short nbridgeids[] = {
PCI_DEVICE_ID_SI_540, /* for SiS 540 VGA */
PCI_DEVICE_ID_SI_630, /* for SiS 630/730 VGA */
PCI_DEVICE_ID_SI_730,
PCI_DEVICE_ID_SI_550, /* for SiS 550 VGA */
PCI_DEVICE_ID_SI_650, /* for SiS 650/651/740 VGA */
PCI_DEVICE_ID_SI_651,
PCI_DEVICE_ID_SI_740,
PCI_DEVICE_ID_SI_661, /* for SiS 661/741/660/760/761 VGA */
PCI_DEVICE_ID_SI_741,
PCI_DEVICE_ID_SI_660,
PCI_DEVICE_ID_SI_760,
PCI_DEVICE_ID_SI_761
};
switch(basechipid) {
#ifdef CONFIG_FB_SIS_300
case SIS_540: nbridgeidx = 0; nbridgenum = 1; break;
case SIS_630: nbridgeidx = 1; nbridgenum = 2; break;
#endif
#ifdef CONFIG_FB_SIS_315
case SIS_550: nbridgeidx = 3; nbridgenum = 1; break;
case SIS_650: nbridgeidx = 4; nbridgenum = 3; break;
case SIS_660: nbridgeidx = 7; nbridgenum = 5; break;
#endif
default: return NULL;
}
for(i = 0; i < nbridgenum; i++) {
if((pdev = pci_get_device(PCI_VENDOR_ID_SI,
nbridgeids[nbridgeidx+i], NULL)))
break;
}
return pdev;
}
static int __devinit
sisfb_get_dram_size(struct sis_video_info *ivideo)
{
#if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315)
u8 reg;
#endif
ivideo->video_size = 0;
ivideo->UMAsize = ivideo->LFBsize = 0;
switch(ivideo->chip) {
#ifdef CONFIG_FB_SIS_300
case SIS_300:
reg = SiS_GetReg(SISSR, 0x14);
ivideo->video_size = ((reg & 0x3F) + 1) << 20;
break;
case SIS_540:
case SIS_630:
case SIS_730:
if(!ivideo->nbridge)
return -1;
pci_read_config_byte(ivideo->nbridge, 0x63, ®);
ivideo->video_size = 1 << (((reg & 0x70) >> 4) + 21);
break;
#endif
#ifdef CONFIG_FB_SIS_315
case SIS_315H:
case SIS_315PRO:
case SIS_315:
reg = SiS_GetReg(SISSR, 0x14);
ivideo->video_size = (1 << ((reg & 0xf0) >> 4)) << 20;
switch((reg >> 2) & 0x03) {
case 0x01:
case 0x03:
ivideo->video_size <<= 1;
break;
case 0x02:
ivideo->video_size += (ivideo->video_size/2);
}
break;
case SIS_330:
reg = SiS_GetReg(SISSR, 0x14);
ivideo->video_size = (1 << ((reg & 0xf0) >> 4)) << 20;
if(reg & 0x0c) ivideo->video_size <<= 1;
break;
case SIS_550:
case SIS_650:
case SIS_740:
reg = SiS_GetReg(SISSR, 0x14);
ivideo->video_size = (((reg & 0x3f) + 1) << 2) << 20;
break;
case SIS_661:
case SIS_741:
reg = SiS_GetReg(SISCR, 0x79);
ivideo->video_size = (1 << ((reg & 0xf0) >> 4)) << 20;
break;
case SIS_660:
case SIS_760:
case SIS_761:
reg = SiS_GetReg(SISCR, 0x79);
reg = (reg & 0xf0) >> 4;
if(reg) {
ivideo->video_size = (1 << reg) << 20;
ivideo->UMAsize = ivideo->video_size;
}
reg = SiS_GetReg(SISCR, 0x78);
reg &= 0x30;
if(reg) {
if(reg == 0x10) {
ivideo->LFBsize = (32 << 20);
} else {
ivideo->LFBsize = (64 << 20);
}
ivideo->video_size += ivideo->LFBsize;
}
break;
case SIS_340:
case XGI_20:
case XGI_40:
reg = SiS_GetReg(SISSR, 0x14);
ivideo->video_size = (1 << ((reg & 0xf0) >> 4)) << 20;
if(ivideo->chip != XGI_20) {
reg = (reg & 0x0c) >> 2;
if(ivideo->revision_id == 2) {
if(reg & 0x01) reg = 0x02;
else reg = 0x00;
}
if(reg == 0x02) ivideo->video_size <<= 1;
else if(reg == 0x03) ivideo->video_size <<= 2;
}
break;
#endif
default:
return -1;
}
return 0;
}
/* -------------- video bridge device detection --------------- */
static void __devinit
sisfb_detect_VB_connect(struct sis_video_info *ivideo)
{
u8 cr32, temp;
/* No CRT2 on XGI Z7 */
if(ivideo->chip == XGI_20) {
ivideo->sisfb_crt1off = 0;
return;
}
#ifdef CONFIG_FB_SIS_300
if(ivideo->sisvga_engine == SIS_300_VGA) {
temp = SiS_GetReg(SISSR, 0x17);
if((temp & 0x0F) && (ivideo->chip != SIS_300)) {
/* PAL/NTSC is stored on SR16 on such machines */
if(!(ivideo->vbflags & (TV_PAL | TV_NTSC | TV_PALM | TV_PALN))) {
temp = SiS_GetReg(SISSR, 0x16);
if(temp & 0x20)
ivideo->vbflags |= TV_PAL;
else
ivideo->vbflags |= TV_NTSC;
}
}
}
#endif
cr32 = SiS_GetReg(SISCR, 0x32);
if(cr32 & SIS_CRT1) {
ivideo->sisfb_crt1off = 0;
} else {
ivideo->sisfb_crt1off = (cr32 & 0xDF) ? 1 : 0;
}
ivideo->vbflags &= ~(CRT2_TV | CRT2_LCD | CRT2_VGA);
if(cr32 & SIS_VB_TV) ivideo->vbflags |= CRT2_TV;
if(cr32 & SIS_VB_LCD) ivideo->vbflags |= CRT2_LCD;
if(cr32 & SIS_VB_CRT2) ivideo->vbflags |= CRT2_VGA;
/* Check given parms for hardware compatibility.
* (Cannot do this in the search_xx routines since we don't
* know what hardware we are running on then)
*/
if(ivideo->chip != SIS_550) {
ivideo->sisfb_dstn = ivideo->sisfb_fstn = 0;
}
if(ivideo->sisfb_tvplug != -1) {
if( (ivideo->sisvga_engine != SIS_315_VGA) ||
(!(ivideo->vbflags2 & VB2_SISYPBPRBRIDGE)) ) {
if(ivideo->sisfb_tvplug & TV_YPBPR) {
ivideo->sisfb_tvplug = -1;
printk(KERN_ERR "sisfb: YPbPr not supported\n");
}
}
}
if(ivideo->sisfb_tvplug != -1) {
if( (ivideo->sisvga_engine != SIS_315_VGA) ||
(!(ivideo->vbflags2 & VB2_SISHIVISIONBRIDGE)) ) {
if(ivideo->sisfb_tvplug & TV_HIVISION) {
ivideo->sisfb_tvplug = -1;
printk(KERN_ERR "sisfb: HiVision not supported\n");
}
}
}
if(ivideo->sisfb_tvstd != -1) {
if( (!(ivideo->vbflags2 & VB2_SISBRIDGE)) &&
(!((ivideo->sisvga_engine == SIS_315_VGA) &&
(ivideo->vbflags2 & VB2_CHRONTEL))) ) {
if(ivideo->sisfb_tvstd & (TV_PALM | TV_PALN | TV_NTSCJ)) {
ivideo->sisfb_tvstd = -1;
printk(KERN_ERR "sisfb: PALM/PALN/NTSCJ not supported\n");
}
}
}
/* Detect/set TV plug & type */
if(ivideo->sisfb_tvplug != -1) {
ivideo->vbflags |= ivideo->sisfb_tvplug;
} else {
if(cr32 & SIS_VB_YPBPR) ivideo->vbflags |= (TV_YPBPR|TV_YPBPR525I); /* default: 480i */
else if(cr32 & SIS_VB_HIVISION) ivideo->vbflags |= TV_HIVISION;
else if(cr32 & SIS_VB_SCART) ivideo->vbflags |= TV_SCART;
else {
if(cr32 & SIS_VB_SVIDEO) ivideo->vbflags |= TV_SVIDEO;
if(cr32 & SIS_VB_COMPOSITE) ivideo->vbflags |= TV_AVIDEO;
}
}
if(!(ivideo->vbflags & (TV_YPBPR | TV_HIVISION))) {
if(ivideo->sisfb_tvstd != -1) {
ivideo->vbflags &= ~(TV_NTSC | TV_PAL | TV_PALM | TV_PALN | TV_NTSCJ);
ivideo->vbflags |= ivideo->sisfb_tvstd;
}
if(ivideo->vbflags & TV_SCART) {
ivideo->vbflags &= ~(TV_NTSC | TV_PALM | TV_PALN | TV_NTSCJ);
ivideo->vbflags |= TV_PAL;
}
if(!(ivideo->vbflags & (TV_PAL | TV_NTSC | TV_PALM | TV_PALN | TV_NTSCJ))) {
if(ivideo->sisvga_engine == SIS_300_VGA) {
temp = SiS_GetReg(SISSR, 0x38);
if(temp & 0x01) ivideo->vbflags |= TV_PAL;
else ivideo->vbflags |= TV_NTSC;
} else if((ivideo->chip <= SIS_315PRO) || (ivideo->chip >= SIS_330)) {
temp = SiS_GetReg(SISSR, 0x38);
if(temp & 0x01) ivideo->vbflags |= TV_PAL;
else ivideo->vbflags |= TV_NTSC;
} else {
temp = SiS_GetReg(SISCR, 0x79);
if(temp & 0x20) ivideo->vbflags |= TV_PAL;
else ivideo->vbflags |= TV_NTSC;
}
}
}
/* Copy forceCRT1 option to CRT1off if option is given */
if(ivideo->sisfb_forcecrt1 != -1) {
ivideo->sisfb_crt1off = (ivideo->sisfb_forcecrt1) ? 0 : 1;
}
}
/* ------------------ Sensing routines ------------------ */
static bool __devinit
sisfb_test_DDC1(struct sis_video_info *ivideo)
{
unsigned short old;
int count = 48;
old = SiS_ReadDDC1Bit(&ivideo->SiS_Pr);
do {
if(old != SiS_ReadDDC1Bit(&ivideo->SiS_Pr)) break;
} while(count--);
return (count != -1);
}
static void __devinit
sisfb_sense_crt1(struct sis_video_info *ivideo)
{
bool mustwait = false;
u8 sr1F, cr17;
#ifdef CONFIG_FB_SIS_315
u8 cr63=0;
#endif
u16 temp = 0xffff;
int i;
sr1F = SiS_GetReg(SISSR, 0x1F);
SiS_SetRegOR(SISSR, 0x1F, 0x04);
SiS_SetRegAND(SISSR, 0x1F, 0x3F);
if(sr1F & 0xc0) mustwait = true;
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
cr63 = SiS_GetReg(SISCR, ivideo->SiS_Pr.SiS_MyCR63);
cr63 &= 0x40;
SiS_SetRegAND(SISCR, ivideo->SiS_Pr.SiS_MyCR63, 0xBF);
}
#endif
cr17 = SiS_GetReg(SISCR, 0x17);
cr17 &= 0x80;
if(!cr17) {
SiS_SetRegOR(SISCR, 0x17, 0x80);
mustwait = true;
SiS_SetReg(SISSR, 0x00, 0x01);
SiS_SetReg(SISSR, 0x00, 0x03);
}
if(mustwait) {
for(i=0; i < 10; i++) sisfbwaitretracecrt1(ivideo);
}
#ifdef CONFIG_FB_SIS_315
if(ivideo->chip >= SIS_330) {
SiS_SetRegAND(SISCR, 0x32, ~0x20);
if(ivideo->chip >= SIS_340) {
SiS_SetReg(SISCR, 0x57, 0x4a);
} else {
SiS_SetReg(SISCR, 0x57, 0x5f);
}
SiS_SetRegOR(SISCR, 0x53, 0x02);
while ((SiS_GetRegByte(SISINPSTAT)) & 0x01) break;
while (!((SiS_GetRegByte(SISINPSTAT)) & 0x01)) break;
if ((SiS_GetRegByte(SISMISCW)) & 0x10) temp = 1;
SiS_SetRegAND(SISCR, 0x53, 0xfd);
SiS_SetRegAND(SISCR, 0x57, 0x00);
}
#endif
if(temp == 0xffff) {
i = 3;
do {
temp = SiS_HandleDDC(&ivideo->SiS_Pr, ivideo->vbflags,
ivideo->sisvga_engine, 0, 0, NULL, ivideo->vbflags2);
} while(((temp == 0) || (temp == 0xffff)) && i--);
if((temp == 0) || (temp == 0xffff)) {
if(sisfb_test_DDC1(ivideo)) temp = 1;
}
}
if((temp) && (temp != 0xffff)) {
SiS_SetRegOR(SISCR, 0x32, 0x20);
}
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
SiS_SetRegANDOR(SISCR, ivideo->SiS_Pr.SiS_MyCR63, 0xBF, cr63);
}
#endif
SiS_SetRegANDOR(SISCR, 0x17, 0x7F, cr17);
SiS_SetReg(SISSR, 0x1F, sr1F);
}
/* Determine and detect attached devices on SiS30x */
static void __devinit
SiS_SenseLCD(struct sis_video_info *ivideo)
{
unsigned char buffer[256];
unsigned short temp, realcrtno, i;
u8 reg, cr37 = 0, paneltype = 0;
u16 xres, yres;
ivideo->SiS_Pr.PanelSelfDetected = false;
/* LCD detection only for TMDS bridges */
if(!(ivideo->vbflags2 & VB2_SISTMDSBRIDGE))
return;
if(ivideo->vbflags2 & VB2_30xBDH)
return;
/* If LCD already set up by BIOS, skip it */
reg = SiS_GetReg(SISCR, 0x32);
if(reg & 0x08)
return;
realcrtno = 1;
if(ivideo->SiS_Pr.DDCPortMixup)
realcrtno = 0;
/* Check DDC capabilities */
temp = SiS_HandleDDC(&ivideo->SiS_Pr, ivideo->vbflags, ivideo->sisvga_engine,
realcrtno, 0, &buffer[0], ivideo->vbflags2);
if((!temp) || (temp == 0xffff) || (!(temp & 0x02)))
return;
/* Read DDC data */
i = 3; /* Number of retrys */
do {
temp = SiS_HandleDDC(&ivideo->SiS_Pr, ivideo->vbflags,
ivideo->sisvga_engine, realcrtno, 1,
&buffer[0], ivideo->vbflags2);
} while((temp) && i--);
if(temp)
return;
/* No digital device */
if(!(buffer[0x14] & 0x80))
return;
/* First detailed timing preferred timing? */
if(!(buffer[0x18] & 0x02))
return;
xres = buffer[0x38] | ((buffer[0x3a] & 0xf0) << 4);
yres = buffer[0x3b] | ((buffer[0x3d] & 0xf0) << 4);
switch(xres) {
case 1024:
if(yres == 768)
paneltype = 0x02;
break;
case 1280:
if(yres == 1024)
paneltype = 0x03;
break;
case 1600:
if((yres == 1200) && (ivideo->vbflags2 & VB2_30xC))
paneltype = 0x0b;
break;
}
if(!paneltype)
return;
if(buffer[0x23])
cr37 |= 0x10;
if((buffer[0x47] & 0x18) == 0x18)
cr37 |= ((((buffer[0x47] & 0x06) ^ 0x06) << 5) | 0x20);
else
cr37 |= 0xc0;
SiS_SetReg(SISCR, 0x36, paneltype);
cr37 &= 0xf1;
SiS_SetRegANDOR(SISCR, 0x37, 0x0c, cr37);
SiS_SetRegOR(SISCR, 0x32, 0x08);
ivideo->SiS_Pr.PanelSelfDetected = true;
}
static int __devinit
SISDoSense(struct sis_video_info *ivideo, u16 type, u16 test)
{
int temp, mytest, result, i, j;
for(j = 0; j < 10; j++) {
result = 0;
for(i = 0; i < 3; i++) {
mytest = test;
SiS_SetReg(SISPART4, 0x11, (type & 0x00ff));
temp = (type >> 8) | (mytest & 0x00ff);
SiS_SetRegANDOR(SISPART4, 0x10, 0xe0, temp);
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x1500);
mytest >>= 8;
mytest &= 0x7f;
temp = SiS_GetReg(SISPART4, 0x03);
temp ^= 0x0e;
temp &= mytest;
if(temp == mytest) result++;
#if 1
SiS_SetReg(SISPART4, 0x11, 0x00);
SiS_SetRegAND(SISPART4, 0x10, 0xe0);
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x1000);
#endif
}
if((result == 0) || (result >= 2)) break;
}
return result;
}
static void __devinit
SiS_Sense30x(struct sis_video_info *ivideo)
{
u8 backupP4_0d,backupP2_00,backupP2_4d,backupSR_1e,biosflag=0;
u16 svhs=0, svhs_c=0;
u16 cvbs=0, cvbs_c=0;
u16 vga2=0, vga2_c=0;
int myflag, result;
char stdstr[] = "sisfb: Detected";
char tvstr[] = "TV connected to";
if(ivideo->vbflags2 & VB2_301) {
svhs = 0x00b9; cvbs = 0x00b3; vga2 = 0x00d1;
myflag = SiS_GetReg(SISPART4, 0x01);
if(myflag & 0x04) {
svhs = 0x00dd; cvbs = 0x00ee; vga2 = 0x00fd;
}
} else if(ivideo->vbflags2 & (VB2_301B | VB2_302B)) {
svhs = 0x016b; cvbs = 0x0174; vga2 = 0x0190;
} else if(ivideo->vbflags2 & (VB2_301LV | VB2_302LV)) {
svhs = 0x0200; cvbs = 0x0100;
} else if(ivideo->vbflags2 & (VB2_301C | VB2_302ELV | VB2_307T | VB2_307LV)) {
svhs = 0x016b; cvbs = 0x0110; vga2 = 0x0190;
} else
return;
vga2_c = 0x0e08; svhs_c = 0x0404; cvbs_c = 0x0804;
if(ivideo->vbflags & (VB2_301LV|VB2_302LV|VB2_302ELV|VB2_307LV)) {
svhs_c = 0x0408; cvbs_c = 0x0808;
}
biosflag = 2;
if(ivideo->haveXGIROM) {
biosflag = ivideo->bios_abase[0x58] & 0x03;
} else if(ivideo->newrom) {
if(ivideo->bios_abase[0x5d] & 0x04) biosflag |= 0x01;
} else if(ivideo->sisvga_engine == SIS_300_VGA) {
if(ivideo->bios_abase) {
biosflag = ivideo->bios_abase[0xfe] & 0x03;
}
}
if(ivideo->chip == SIS_300) {
myflag = SiS_GetReg(SISSR, 0x3b);
if(!(myflag & 0x01)) vga2 = vga2_c = 0;
}
if(!(ivideo->vbflags2 & VB2_SISVGA2BRIDGE)) {
vga2 = vga2_c = 0;
}
backupSR_1e = SiS_GetReg(SISSR, 0x1e);
SiS_SetRegOR(SISSR, 0x1e, 0x20);
backupP4_0d = SiS_GetReg(SISPART4, 0x0d);
if(ivideo->vbflags2 & VB2_30xC) {
SiS_SetRegANDOR(SISPART4, 0x0d, ~0x07, 0x01);
} else {
SiS_SetRegOR(SISPART4, 0x0d, 0x04);
}
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x2000);
backupP2_00 = SiS_GetReg(SISPART2, 0x00);
SiS_SetReg(SISPART2, 0x00, ((backupP2_00 | 0x1c) & 0xfc));
backupP2_4d = SiS_GetReg(SISPART2, 0x4d);
if(ivideo->vbflags2 & VB2_SISYPBPRBRIDGE) {
SiS_SetReg(SISPART2, 0x4d, (backupP2_4d & ~0x10));
}
if(!(ivideo->vbflags2 & VB2_30xCLV)) {
SISDoSense(ivideo, 0, 0);
}
SiS_SetRegAND(SISCR, 0x32, ~0x14);
if(vga2_c || vga2) {
if(SISDoSense(ivideo, vga2, vga2_c)) {
if(biosflag & 0x01) {
printk(KERN_INFO "%s %s SCART output\n", stdstr, tvstr);
SiS_SetRegOR(SISCR, 0x32, 0x04);
} else {
printk(KERN_INFO "%s secondary VGA connection\n", stdstr);
SiS_SetRegOR(SISCR, 0x32, 0x10);
}
}
}
SiS_SetRegAND(SISCR, 0x32, 0x3f);
if(ivideo->vbflags2 & VB2_30xCLV) {
SiS_SetRegOR(SISPART4, 0x0d, 0x04);
}
if((ivideo->sisvga_engine == SIS_315_VGA) && (ivideo->vbflags2 & VB2_SISYPBPRBRIDGE)) {
SiS_SetReg(SISPART2, 0x4d, (backupP2_4d | 0x10));
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x2000);
if((result = SISDoSense(ivideo, svhs, 0x0604))) {
if((result = SISDoSense(ivideo, cvbs, 0x0804))) {
printk(KERN_INFO "%s %s YPbPr component output\n", stdstr, tvstr);
SiS_SetRegOR(SISCR, 0x32, 0x80);
}
}
SiS_SetReg(SISPART2, 0x4d, backupP2_4d);
}
SiS_SetRegAND(SISCR, 0x32, ~0x03);
if(!(ivideo->vbflags & TV_YPBPR)) {
if((result = SISDoSense(ivideo, svhs, svhs_c))) {
printk(KERN_INFO "%s %s SVIDEO output\n", stdstr, tvstr);
SiS_SetRegOR(SISCR, 0x32, 0x02);
}
if((biosflag & 0x02) || (!result)) {
if(SISDoSense(ivideo, cvbs, cvbs_c)) {
printk(KERN_INFO "%s %s COMPOSITE output\n", stdstr, tvstr);
SiS_SetRegOR(SISCR, 0x32, 0x01);
}
}
}
SISDoSense(ivideo, 0, 0);
SiS_SetReg(SISPART2, 0x00, backupP2_00);
SiS_SetReg(SISPART4, 0x0d, backupP4_0d);
SiS_SetReg(SISSR, 0x1e, backupSR_1e);
if(ivideo->vbflags2 & VB2_30xCLV) {
biosflag = SiS_GetReg(SISPART2, 0x00);
if(biosflag & 0x20) {
for(myflag = 2; myflag > 0; myflag--) {
biosflag ^= 0x20;
SiS_SetReg(SISPART2, 0x00, biosflag);
}
}
}
SiS_SetReg(SISPART2, 0x00, backupP2_00);
}
/* Determine and detect attached TV's on Chrontel */
static void __devinit
SiS_SenseCh(struct sis_video_info *ivideo)
{
#if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315)
u8 temp1, temp2;
char stdstr[] = "sisfb: Chrontel: Detected TV connected to";
#endif
#ifdef CONFIG_FB_SIS_300
unsigned char test[3];
int i;
#endif
if(ivideo->chip < SIS_315H) {
#ifdef CONFIG_FB_SIS_300
ivideo->SiS_Pr.SiS_IF_DEF_CH70xx = 1; /* Chrontel 700x */
SiS_SetChrontelGPIO(&ivideo->SiS_Pr, 0x9c); /* Set general purpose IO for Chrontel communication */
SiS_DDC2Delay(&ivideo->SiS_Pr, 1000);
temp1 = SiS_GetCH700x(&ivideo->SiS_Pr, 0x25);
/* See Chrontel TB31 for explanation */
temp2 = SiS_GetCH700x(&ivideo->SiS_Pr, 0x0e);
if(((temp2 & 0x07) == 0x01) || (temp2 & 0x04)) {
SiS_SetCH700x(&ivideo->SiS_Pr, 0x0e, 0x0b);
SiS_DDC2Delay(&ivideo->SiS_Pr, 300);
}
temp2 = SiS_GetCH700x(&ivideo->SiS_Pr, 0x25);
if(temp2 != temp1) temp1 = temp2;
if((temp1 >= 0x22) && (temp1 <= 0x50)) {
/* Read power status */
temp1 = SiS_GetCH700x(&ivideo->SiS_Pr, 0x0e);
if((temp1 & 0x03) != 0x03) {
/* Power all outputs */
SiS_SetCH700x(&ivideo->SiS_Pr, 0x0e,0x0b);
SiS_DDC2Delay(&ivideo->SiS_Pr, 300);
}
/* Sense connected TV devices */
for(i = 0; i < 3; i++) {
SiS_SetCH700x(&ivideo->SiS_Pr, 0x10, 0x01);
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x96);
SiS_SetCH700x(&ivideo->SiS_Pr, 0x10, 0x00);
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x96);
temp1 = SiS_GetCH700x(&ivideo->SiS_Pr, 0x10);
if(!(temp1 & 0x08)) test[i] = 0x02;
else if(!(temp1 & 0x02)) test[i] = 0x01;
else test[i] = 0;
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x96);
}
if(test[0] == test[1]) temp1 = test[0];
else if(test[0] == test[2]) temp1 = test[0];
else if(test[1] == test[2]) temp1 = test[1];
else {
printk(KERN_INFO
"sisfb: TV detection unreliable - test results varied\n");
temp1 = test[2];
}
if(temp1 == 0x02) {
printk(KERN_INFO "%s SVIDEO output\n", stdstr);
ivideo->vbflags |= TV_SVIDEO;
SiS_SetRegOR(SISCR, 0x32, 0x02);
SiS_SetRegAND(SISCR, 0x32, ~0x05);
} else if (temp1 == 0x01) {
printk(KERN_INFO "%s CVBS output\n", stdstr);
ivideo->vbflags |= TV_AVIDEO;
SiS_SetRegOR(SISCR, 0x32, 0x01);
SiS_SetRegAND(SISCR, 0x32, ~0x06);
} else {
SiS_SetCH70xxANDOR(&ivideo->SiS_Pr, 0x0e, 0x01, 0xF8);
SiS_SetRegAND(SISCR, 0x32, ~0x07);
}
} else if(temp1 == 0) {
SiS_SetCH70xxANDOR(&ivideo->SiS_Pr, 0x0e, 0x01, 0xF8);
SiS_SetRegAND(SISCR, 0x32, ~0x07);
}
/* Set general purpose IO for Chrontel communication */
SiS_SetChrontelGPIO(&ivideo->SiS_Pr, 0x00);
#endif
} else {
#ifdef CONFIG_FB_SIS_315
ivideo->SiS_Pr.SiS_IF_DEF_CH70xx = 2; /* Chrontel 7019 */
temp1 = SiS_GetCH701x(&ivideo->SiS_Pr, 0x49);
SiS_SetCH701x(&ivideo->SiS_Pr, 0x49, 0x20);
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x96);
temp2 = SiS_GetCH701x(&ivideo->SiS_Pr, 0x20);
temp2 |= 0x01;
SiS_SetCH701x(&ivideo->SiS_Pr, 0x20, temp2);
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x96);
temp2 ^= 0x01;
SiS_SetCH701x(&ivideo->SiS_Pr, 0x20, temp2);
SiS_DDC2Delay(&ivideo->SiS_Pr, 0x96);
temp2 = SiS_GetCH701x(&ivideo->SiS_Pr, 0x20);
SiS_SetCH701x(&ivideo->SiS_Pr, 0x49, temp1);
temp1 = 0;
if(temp2 & 0x02) temp1 |= 0x01;
if(temp2 & 0x10) temp1 |= 0x01;
if(temp2 & 0x04) temp1 |= 0x02;
if( (temp1 & 0x01) && (temp1 & 0x02) ) temp1 = 0x04;
switch(temp1) {
case 0x01:
printk(KERN_INFO "%s CVBS output\n", stdstr);
ivideo->vbflags |= TV_AVIDEO;
SiS_SetRegOR(SISCR, 0x32, 0x01);
SiS_SetRegAND(SISCR, 0x32, ~0x06);
break;
case 0x02:
printk(KERN_INFO "%s SVIDEO output\n", stdstr);
ivideo->vbflags |= TV_SVIDEO;
SiS_SetRegOR(SISCR, 0x32, 0x02);
SiS_SetRegAND(SISCR, 0x32, ~0x05);
break;
case 0x04:
printk(KERN_INFO "%s SCART output\n", stdstr);
SiS_SetRegOR(SISCR, 0x32, 0x04);
SiS_SetRegAND(SISCR, 0x32, ~0x03);
break;
default:
SiS_SetRegAND(SISCR, 0x32, ~0x07);
}
#endif
}
}
static void __devinit
sisfb_get_VB_type(struct sis_video_info *ivideo)
{
char stdstr[] = "sisfb: Detected";
char bridgestr[] = "video bridge";
u8 vb_chipid;
u8 reg;
/* No CRT2 on XGI Z7 */
if(ivideo->chip == XGI_20)
return;
vb_chipid = SiS_GetReg(SISPART4, 0x00);
switch(vb_chipid) {
case 0x01:
reg = SiS_GetReg(SISPART4, 0x01);
if(reg < 0xb0) {
ivideo->vbflags |= VB_301; /* Deprecated */
ivideo->vbflags2 |= VB2_301;
printk(KERN_INFO "%s SiS301 %s\n", stdstr, bridgestr);
} else if(reg < 0xc0) {
ivideo->vbflags |= VB_301B; /* Deprecated */
ivideo->vbflags2 |= VB2_301B;
reg = SiS_GetReg(SISPART4, 0x23);
if(!(reg & 0x02)) {
ivideo->vbflags |= VB_30xBDH; /* Deprecated */
ivideo->vbflags2 |= VB2_30xBDH;
printk(KERN_INFO "%s SiS301B-DH %s\n", stdstr, bridgestr);
} else {
printk(KERN_INFO "%s SiS301B %s\n", stdstr, bridgestr);
}
} else if(reg < 0xd0) {
ivideo->vbflags |= VB_301C; /* Deprecated */
ivideo->vbflags2 |= VB2_301C;
printk(KERN_INFO "%s SiS301C %s\n", stdstr, bridgestr);
} else if(reg < 0xe0) {
ivideo->vbflags |= VB_301LV; /* Deprecated */
ivideo->vbflags2 |= VB2_301LV;
printk(KERN_INFO "%s SiS301LV %s\n", stdstr, bridgestr);
} else if(reg <= 0xe1) {
reg = SiS_GetReg(SISPART4, 0x39);
if(reg == 0xff) {
ivideo->vbflags |= VB_302LV; /* Deprecated */
ivideo->vbflags2 |= VB2_302LV;
printk(KERN_INFO "%s SiS302LV %s\n", stdstr, bridgestr);
} else {
ivideo->vbflags |= VB_301C; /* Deprecated */
ivideo->vbflags2 |= VB2_301C;
printk(KERN_INFO "%s SiS301C(P4) %s\n", stdstr, bridgestr);
#if 0
ivideo->vbflags |= VB_302ELV; /* Deprecated */
ivideo->vbflags2 |= VB2_302ELV;
printk(KERN_INFO "%s SiS302ELV %s\n", stdstr, bridgestr);
#endif
}
}
break;
case 0x02:
ivideo->vbflags |= VB_302B; /* Deprecated */
ivideo->vbflags2 |= VB2_302B;
printk(KERN_INFO "%s SiS302B %s\n", stdstr, bridgestr);
break;
}
if((!(ivideo->vbflags2 & VB2_VIDEOBRIDGE)) && (ivideo->chip != SIS_300)) {
reg = SiS_GetReg(SISCR, 0x37);
reg &= SIS_EXTERNAL_CHIP_MASK;
reg >>= 1;
if(ivideo->sisvga_engine == SIS_300_VGA) {
#ifdef CONFIG_FB_SIS_300
switch(reg) {
case SIS_EXTERNAL_CHIP_LVDS:
ivideo->vbflags |= VB_LVDS; /* Deprecated */
ivideo->vbflags2 |= VB2_LVDS;
break;
case SIS_EXTERNAL_CHIP_TRUMPION:
ivideo->vbflags |= (VB_LVDS | VB_TRUMPION); /* Deprecated */
ivideo->vbflags2 |= (VB2_LVDS | VB2_TRUMPION);
break;
case SIS_EXTERNAL_CHIP_CHRONTEL:
ivideo->vbflags |= VB_CHRONTEL; /* Deprecated */
ivideo->vbflags2 |= VB2_CHRONTEL;
break;
case SIS_EXTERNAL_CHIP_LVDS_CHRONTEL:
ivideo->vbflags |= (VB_LVDS | VB_CHRONTEL); /* Deprecated */
ivideo->vbflags2 |= (VB2_LVDS | VB2_CHRONTEL);
break;
}
if(ivideo->vbflags2 & VB2_CHRONTEL) ivideo->chronteltype = 1;
#endif
} else if(ivideo->chip < SIS_661) {
#ifdef CONFIG_FB_SIS_315
switch (reg) {
case SIS310_EXTERNAL_CHIP_LVDS:
ivideo->vbflags |= VB_LVDS; /* Deprecated */
ivideo->vbflags2 |= VB2_LVDS;
break;
case SIS310_EXTERNAL_CHIP_LVDS_CHRONTEL:
ivideo->vbflags |= (VB_LVDS | VB_CHRONTEL); /* Deprecated */
ivideo->vbflags2 |= (VB2_LVDS | VB2_CHRONTEL);
break;
}
if(ivideo->vbflags2 & VB2_CHRONTEL) ivideo->chronteltype = 2;
#endif
} else if(ivideo->chip >= SIS_661) {
#ifdef CONFIG_FB_SIS_315
reg = SiS_GetReg(SISCR, 0x38);
reg >>= 5;
switch(reg) {
case 0x02:
ivideo->vbflags |= VB_LVDS; /* Deprecated */
ivideo->vbflags2 |= VB2_LVDS;
break;
case 0x03:
ivideo->vbflags |= (VB_LVDS | VB_CHRONTEL); /* Deprecated */
ivideo->vbflags2 |= (VB2_LVDS | VB2_CHRONTEL);
break;
case 0x04:
ivideo->vbflags |= (VB_LVDS | VB_CONEXANT); /* Deprecated */
ivideo->vbflags2 |= (VB2_LVDS | VB2_CONEXANT);
break;
}
if(ivideo->vbflags2 & VB2_CHRONTEL) ivideo->chronteltype = 2;
#endif
}
if(ivideo->vbflags2 & VB2_LVDS) {
printk(KERN_INFO "%s LVDS transmitter\n", stdstr);
}
if((ivideo->sisvga_engine == SIS_300_VGA) && (ivideo->vbflags2 & VB2_TRUMPION)) {
printk(KERN_INFO "%s Trumpion Zurac LCD scaler\n", stdstr);
}
if(ivideo->vbflags2 & VB2_CHRONTEL) {
printk(KERN_INFO "%s Chrontel TV encoder\n", stdstr);
}
if((ivideo->chip >= SIS_661) && (ivideo->vbflags2 & VB2_CONEXANT)) {
printk(KERN_INFO "%s Conexant external device\n", stdstr);
}
}
if(ivideo->vbflags2 & VB2_SISBRIDGE) {
SiS_SenseLCD(ivideo);
SiS_Sense30x(ivideo);
} else if(ivideo->vbflags2 & VB2_CHRONTEL) {
SiS_SenseCh(ivideo);
}
}
/* ---------- Engine initialization routines ------------ */
static void
sisfb_engine_init(struct sis_video_info *ivideo)
{
/* Initialize command queue (we use MMIO only) */
/* BEFORE THIS IS CALLED, THE ENGINES *MUST* BE SYNC'ED */
ivideo->caps &= ~(TURBO_QUEUE_CAP |
MMIO_CMD_QUEUE_CAP |
VM_CMD_QUEUE_CAP |
AGP_CMD_QUEUE_CAP);
#ifdef CONFIG_FB_SIS_300
if(ivideo->sisvga_engine == SIS_300_VGA) {
u32 tqueue_pos;
u8 tq_state;
tqueue_pos = (ivideo->video_size - ivideo->cmdQueueSize) / (64 * 1024);
tq_state = SiS_GetReg(SISSR, IND_SIS_TURBOQUEUE_SET);
tq_state |= 0xf0;
tq_state &= 0xfc;
tq_state |= (u8)(tqueue_pos >> 8);
SiS_SetReg(SISSR, IND_SIS_TURBOQUEUE_SET, tq_state);
SiS_SetReg(SISSR, IND_SIS_TURBOQUEUE_ADR, (u8)(tqueue_pos & 0xff));
ivideo->caps |= TURBO_QUEUE_CAP;
}
#endif
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
u32 tempq = 0, templ;
u8 temp;
if(ivideo->chip == XGI_20) {
switch(ivideo->cmdQueueSize) {
case (64 * 1024):
temp = SIS_CMD_QUEUE_SIZE_Z7_64k;
break;
case (128 * 1024):
default:
temp = SIS_CMD_QUEUE_SIZE_Z7_128k;
}
} else {
switch(ivideo->cmdQueueSize) {
case (4 * 1024 * 1024):
temp = SIS_CMD_QUEUE_SIZE_4M;
break;
case (2 * 1024 * 1024):
temp = SIS_CMD_QUEUE_SIZE_2M;
break;
case (1 * 1024 * 1024):
temp = SIS_CMD_QUEUE_SIZE_1M;
break;
default:
case (512 * 1024):
temp = SIS_CMD_QUEUE_SIZE_512k;
}
}
SiS_SetReg(SISSR, IND_SIS_CMDQUEUE_THRESHOLD, COMMAND_QUEUE_THRESHOLD);
SiS_SetReg(SISSR, IND_SIS_CMDQUEUE_SET, SIS_CMD_QUEUE_RESET);
if((ivideo->chip >= XGI_40) && ivideo->modechanged) {
/* Must disable dual pipe on XGI_40. Can't do
* this in MMIO mode, because it requires
* setting/clearing a bit in the MMIO fire trigger
* register.
*/
if(!((templ = MMIO_IN32(ivideo->mmio_vbase, 0x8240)) & (1 << 10))) {
MMIO_OUT32(ivideo->mmio_vbase, Q_WRITE_PTR, 0);
SiS_SetReg(SISSR, IND_SIS_CMDQUEUE_SET, (temp | SIS_VRAM_CMDQUEUE_ENABLE));
tempq = MMIO_IN32(ivideo->mmio_vbase, Q_READ_PTR);
MMIO_OUT32(ivideo->mmio_vbase, Q_WRITE_PTR, tempq);
tempq = (u32)(ivideo->video_size - ivideo->cmdQueueSize);
MMIO_OUT32(ivideo->mmio_vbase, Q_BASE_ADDR, tempq);
writel(0x16800000 + 0x8240, ivideo->video_vbase + tempq);
writel(templ | (1 << 10), ivideo->video_vbase + tempq + 4);
writel(0x168F0000, ivideo->video_vbase + tempq + 8);
writel(0x168F0000, ivideo->video_vbase + tempq + 12);
MMIO_OUT32(ivideo->mmio_vbase, Q_WRITE_PTR, (tempq + 16));
sisfb_syncaccel(ivideo);
SiS_SetReg(SISSR, IND_SIS_CMDQUEUE_SET, SIS_CMD_QUEUE_RESET);
}
}
tempq = MMIO_IN32(ivideo->mmio_vbase, MMIO_QUEUE_READPORT);
MMIO_OUT32(ivideo->mmio_vbase, MMIO_QUEUE_WRITEPORT, tempq);
temp |= (SIS_MMIO_CMD_ENABLE | SIS_CMD_AUTO_CORR);
SiS_SetReg(SISSR, IND_SIS_CMDQUEUE_SET, temp);
tempq = (u32)(ivideo->video_size - ivideo->cmdQueueSize);
MMIO_OUT32(ivideo->mmio_vbase, MMIO_QUEUE_PHYBASE, tempq);
ivideo->caps |= MMIO_CMD_QUEUE_CAP;
}
#endif
ivideo->engineok = 1;
}
static void __devinit
sisfb_detect_lcd_type(struct sis_video_info *ivideo)
{
u8 reg;
int i;
reg = SiS_GetReg(SISCR, 0x36);
reg &= 0x0f;
if(ivideo->sisvga_engine == SIS_300_VGA) {
ivideo->CRT2LCDType = sis300paneltype[reg];
} else if(ivideo->chip >= SIS_661) {
ivideo->CRT2LCDType = sis661paneltype[reg];
} else {
ivideo->CRT2LCDType = sis310paneltype[reg];
if((ivideo->chip == SIS_550) && (sisfb_fstn)) {
if((ivideo->CRT2LCDType != LCD_320x240_2) &&
(ivideo->CRT2LCDType != LCD_320x240_3)) {
ivideo->CRT2LCDType = LCD_320x240;
}
}
}
if(ivideo->CRT2LCDType == LCD_UNKNOWN) {
/* For broken BIOSes: Assume 1024x768, RGB18 */
ivideo->CRT2LCDType = LCD_1024x768;
SiS_SetRegANDOR(SISCR, 0x36, 0xf0, 0x02);
SiS_SetRegANDOR(SISCR, 0x37, 0xee, 0x01);
printk(KERN_DEBUG "sisfb: Invalid panel ID (%02x), assuming 1024x768, RGB18\n", reg);
}
for(i = 0; i < SIS_LCD_NUMBER; i++) {
if(ivideo->CRT2LCDType == sis_lcd_data[i].lcdtype) {
ivideo->lcdxres = sis_lcd_data[i].xres;
ivideo->lcdyres = sis_lcd_data[i].yres;
ivideo->lcddefmodeidx = sis_lcd_data[i].default_mode_idx;
break;
}
}
#ifdef CONFIG_FB_SIS_300
if(ivideo->SiS_Pr.SiS_CustomT == CUT_BARCO1366) {
ivideo->lcdxres = 1360; ivideo->lcdyres = 1024;
ivideo->lcddefmodeidx = DEFAULT_MODE_1360;
} else if(ivideo->SiS_Pr.SiS_CustomT == CUT_PANEL848) {
ivideo->lcdxres = 848; ivideo->lcdyres = 480;
ivideo->lcddefmodeidx = DEFAULT_MODE_848;
} else if(ivideo->SiS_Pr.SiS_CustomT == CUT_PANEL856) {
ivideo->lcdxres = 856; ivideo->lcdyres = 480;
ivideo->lcddefmodeidx = DEFAULT_MODE_856;
}
#endif
printk(KERN_DEBUG "sisfb: Detected %dx%d flat panel\n",
ivideo->lcdxres, ivideo->lcdyres);
}
static void __devinit
sisfb_save_pdc_emi(struct sis_video_info *ivideo)
{
#ifdef CONFIG_FB_SIS_300
/* Save the current PanelDelayCompensation if the LCD is currently used */
if(ivideo->sisvga_engine == SIS_300_VGA) {
if(ivideo->vbflags2 & (VB2_LVDS | VB2_30xBDH)) {
int tmp;
tmp = SiS_GetReg(SISCR, 0x30);
if(tmp & 0x20) {
/* Currently on LCD? If yes, read current pdc */
ivideo->detectedpdc = SiS_GetReg(SISPART1, 0x13);
ivideo->detectedpdc &= 0x3c;
if(ivideo->SiS_Pr.PDC == -1) {
/* Let option override detection */
ivideo->SiS_Pr.PDC = ivideo->detectedpdc;
}
printk(KERN_INFO "sisfb: Detected LCD PDC 0x%02x\n",
ivideo->detectedpdc);
}
if((ivideo->SiS_Pr.PDC != -1) &&
(ivideo->SiS_Pr.PDC != ivideo->detectedpdc)) {
printk(KERN_INFO "sisfb: Using LCD PDC 0x%02x\n",
ivideo->SiS_Pr.PDC);
}
}
}
#endif
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
/* Try to find about LCDA */
if(ivideo->vbflags2 & VB2_SISLCDABRIDGE) {
int tmp;
tmp = SiS_GetReg(SISPART1, 0x13);
if(tmp & 0x04) {
ivideo->SiS_Pr.SiS_UseLCDA = true;
ivideo->detectedlcda = 0x03;
}
}
/* Save PDC */
if(ivideo->vbflags2 & VB2_SISLVDSBRIDGE) {
int tmp;
tmp = SiS_GetReg(SISCR, 0x30);
if((tmp & 0x20) || (ivideo->detectedlcda != 0xff)) {
/* Currently on LCD? If yes, read current pdc */
u8 pdc;
pdc = SiS_GetReg(SISPART1, 0x2D);
ivideo->detectedpdc = (pdc & 0x0f) << 1;
ivideo->detectedpdca = (pdc & 0xf0) >> 3;
pdc = SiS_GetReg(SISPART1, 0x35);
ivideo->detectedpdc |= ((pdc >> 7) & 0x01);
pdc = SiS_GetReg(SISPART1, 0x20);
ivideo->detectedpdca |= ((pdc >> 6) & 0x01);
if(ivideo->newrom) {
/* New ROM invalidates other PDC resp. */
if(ivideo->detectedlcda != 0xff) {
ivideo->detectedpdc = 0xff;
} else {
ivideo->detectedpdca = 0xff;
}
}
if(ivideo->SiS_Pr.PDC == -1) {
if(ivideo->detectedpdc != 0xff) {
ivideo->SiS_Pr.PDC = ivideo->detectedpdc;
}
}
if(ivideo->SiS_Pr.PDCA == -1) {
if(ivideo->detectedpdca != 0xff) {
ivideo->SiS_Pr.PDCA = ivideo->detectedpdca;
}
}
if(ivideo->detectedpdc != 0xff) {
printk(KERN_INFO
"sisfb: Detected LCD PDC 0x%02x (for LCD=CRT2)\n",
ivideo->detectedpdc);
}
if(ivideo->detectedpdca != 0xff) {
printk(KERN_INFO
"sisfb: Detected LCD PDC1 0x%02x (for LCD=CRT1)\n",
ivideo->detectedpdca);
}
}
/* Save EMI */
if(ivideo->vbflags2 & VB2_SISEMIBRIDGE) {
ivideo->SiS_Pr.EMI_30 = SiS_GetReg(SISPART4, 0x30);
ivideo->SiS_Pr.EMI_31 = SiS_GetReg(SISPART4, 0x31);
ivideo->SiS_Pr.EMI_32 = SiS_GetReg(SISPART4, 0x32);
ivideo->SiS_Pr.EMI_33 = SiS_GetReg(SISPART4, 0x33);
ivideo->SiS_Pr.HaveEMI = true;
if((tmp & 0x20) || (ivideo->detectedlcda != 0xff)) {
ivideo->SiS_Pr.HaveEMILCD = true;
}
}
}
/* Let user override detected PDCs (all bridges) */
if(ivideo->vbflags2 & VB2_30xBLV) {
if((ivideo->SiS_Pr.PDC != -1) &&
(ivideo->SiS_Pr.PDC != ivideo->detectedpdc)) {
printk(KERN_INFO "sisfb: Using LCD PDC 0x%02x (for LCD=CRT2)\n",
ivideo->SiS_Pr.PDC);
}
if((ivideo->SiS_Pr.PDCA != -1) &&
(ivideo->SiS_Pr.PDCA != ivideo->detectedpdca)) {
printk(KERN_INFO "sisfb: Using LCD PDC1 0x%02x (for LCD=CRT1)\n",
ivideo->SiS_Pr.PDCA);
}
}
}
#endif
}
/* -------------------- Memory manager routines ---------------------- */
static u32 __devinit
sisfb_getheapstart(struct sis_video_info *ivideo)
{
u32 ret = ivideo->sisfb_parm_mem * 1024;
u32 maxoffs = ivideo->video_size - ivideo->hwcursor_size - ivideo->cmdQueueSize;
u32 def;
/* Calculate heap start = end of memory for console
*
* CCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDHHHHQQQQQQQQQQ
* C = console, D = heap, H = HWCursor, Q = cmd-queue
*
* On 76x in UMA+LFB mode, the layout is as follows:
* DDDDDDDDDDDCCCCCCCCCCCCCCCCCCCCCCCCHHHHQQQQQQQQQQQ
* where the heap is the entire UMA area, eventually
* into the LFB area if the given mem parameter is
* higher than the size of the UMA memory.
*
* Basically given by "mem" parameter
*
* maximum = videosize - cmd_queue - hwcursor
* (results in a heap of size 0)
* default = SiS 300: depends on videosize
* SiS 315/330/340/XGI: 32k below max
*/
if(ivideo->sisvga_engine == SIS_300_VGA) {
if(ivideo->video_size > 0x1000000) {
def = 0xc00000;
} else if(ivideo->video_size > 0x800000) {
def = 0x800000;
} else {
def = 0x400000;
}
} else if(ivideo->UMAsize && ivideo->LFBsize) {
ret = def = 0;
} else {
def = maxoffs - 0x8000;
}
/* Use default for secondary card for now (FIXME) */
if((!ret) || (ret > maxoffs) || (ivideo->cardnumber != 0))
ret = def;
return ret;
}
static u32 __devinit
sisfb_getheapsize(struct sis_video_info *ivideo)
{
u32 max = ivideo->video_size - ivideo->hwcursor_size - ivideo->cmdQueueSize;
u32 ret = 0;
if(ivideo->UMAsize && ivideo->LFBsize) {
if( (!ivideo->sisfb_parm_mem) ||
((ivideo->sisfb_parm_mem * 1024) > max) ||
((max - (ivideo->sisfb_parm_mem * 1024)) < ivideo->UMAsize) ) {
ret = ivideo->UMAsize;
max -= ivideo->UMAsize;
} else {
ret = max - (ivideo->sisfb_parm_mem * 1024);
max = ivideo->sisfb_parm_mem * 1024;
}
ivideo->video_offset = ret;
ivideo->sisfb_mem = max;
} else {
ret = max - ivideo->heapstart;
ivideo->sisfb_mem = ivideo->heapstart;
}
return ret;
}
static int __devinit
sisfb_heap_init(struct sis_video_info *ivideo)
{
struct SIS_OH *poh;
ivideo->video_offset = 0;
if(ivideo->sisfb_parm_mem) {
if( (ivideo->sisfb_parm_mem < (2 * 1024 * 1024)) ||
(ivideo->sisfb_parm_mem > ivideo->video_size) ) {
ivideo->sisfb_parm_mem = 0;
}
}
ivideo->heapstart = sisfb_getheapstart(ivideo);
ivideo->sisfb_heap_size = sisfb_getheapsize(ivideo);
ivideo->sisfb_heap_start = ivideo->video_vbase + ivideo->heapstart;
ivideo->sisfb_heap_end = ivideo->sisfb_heap_start + ivideo->sisfb_heap_size;
printk(KERN_INFO "sisfb: Memory heap starting at %dK, size %dK\n",
(int)(ivideo->heapstart / 1024), (int)(ivideo->sisfb_heap_size / 1024));
ivideo->sisfb_heap.vinfo = ivideo;
ivideo->sisfb_heap.poha_chain = NULL;
ivideo->sisfb_heap.poh_freelist = NULL;
poh = sisfb_poh_new_node(&ivideo->sisfb_heap);
if(poh == NULL)
return 1;
poh->poh_next = &ivideo->sisfb_heap.oh_free;
poh->poh_prev = &ivideo->sisfb_heap.oh_free;
poh->size = ivideo->sisfb_heap_size;
poh->offset = ivideo->heapstart;
ivideo->sisfb_heap.oh_free.poh_next = poh;
ivideo->sisfb_heap.oh_free.poh_prev = poh;
ivideo->sisfb_heap.oh_free.size = 0;
ivideo->sisfb_heap.max_freesize = poh->size;
ivideo->sisfb_heap.oh_used.poh_next = &ivideo->sisfb_heap.oh_used;
ivideo->sisfb_heap.oh_used.poh_prev = &ivideo->sisfb_heap.oh_used;
ivideo->sisfb_heap.oh_used.size = SENTINEL;
if(ivideo->cardnumber == 0) {
/* For the first card, make this heap the "global" one
* for old DRM (which could handle only one card)
*/
sisfb_heap = &ivideo->sisfb_heap;
}
return 0;
}
static struct SIS_OH *
sisfb_poh_new_node(struct SIS_HEAP *memheap)
{
struct SIS_OHALLOC *poha;
struct SIS_OH *poh;
unsigned long cOhs;
int i;
if(memheap->poh_freelist == NULL) {
poha = kmalloc(SIS_OH_ALLOC_SIZE, GFP_KERNEL);
if(!poha)
return NULL;
poha->poha_next = memheap->poha_chain;
memheap->poha_chain = poha;
cOhs = (SIS_OH_ALLOC_SIZE - sizeof(struct SIS_OHALLOC)) / sizeof(struct SIS_OH) + 1;
poh = &poha->aoh[0];
for(i = cOhs - 1; i != 0; i--) {
poh->poh_next = poh + 1;
poh = poh + 1;
}
poh->poh_next = NULL;
memheap->poh_freelist = &poha->aoh[0];
}
poh = memheap->poh_freelist;
memheap->poh_freelist = poh->poh_next;
return poh;
}
static struct SIS_OH *
sisfb_poh_allocate(struct SIS_HEAP *memheap, u32 size)
{
struct SIS_OH *pohThis;
struct SIS_OH *pohRoot;
int bAllocated = 0;
if(size > memheap->max_freesize) {
DPRINTK("sisfb: Can't allocate %dk video memory\n",
(unsigned int) size / 1024);
return NULL;
}
pohThis = memheap->oh_free.poh_next;
while(pohThis != &memheap->oh_free) {
if(size <= pohThis->size) {
bAllocated = 1;
break;
}
pohThis = pohThis->poh_next;
}
if(!bAllocated) {
DPRINTK("sisfb: Can't allocate %dk video memory\n",
(unsigned int) size / 1024);
return NULL;
}
if(size == pohThis->size) {
pohRoot = pohThis;
sisfb_delete_node(pohThis);
} else {
pohRoot = sisfb_poh_new_node(memheap);
if(pohRoot == NULL)
return NULL;
pohRoot->offset = pohThis->offset;
pohRoot->size = size;
pohThis->offset += size;
pohThis->size -= size;
}
memheap->max_freesize -= size;
pohThis = &memheap->oh_used;
sisfb_insert_node(pohThis, pohRoot);
return pohRoot;
}
static void
sisfb_delete_node(struct SIS_OH *poh)
{
poh->poh_prev->poh_next = poh->poh_next;
poh->poh_next->poh_prev = poh->poh_prev;
}
static void
sisfb_insert_node(struct SIS_OH *pohList, struct SIS_OH *poh)
{
struct SIS_OH *pohTemp = pohList->poh_next;
pohList->poh_next = poh;
pohTemp->poh_prev = poh;
poh->poh_prev = pohList;
poh->poh_next = pohTemp;
}
static struct SIS_OH *
sisfb_poh_free(struct SIS_HEAP *memheap, u32 base)
{
struct SIS_OH *pohThis;
struct SIS_OH *poh_freed;
struct SIS_OH *poh_prev;
struct SIS_OH *poh_next;
u32 ulUpper;
u32 ulLower;
int foundNode = 0;
poh_freed = memheap->oh_used.poh_next;
while(poh_freed != &memheap->oh_used) {
if(poh_freed->offset == base) {
foundNode = 1;
break;
}
poh_freed = poh_freed->poh_next;
}
if(!foundNode)
return NULL;
memheap->max_freesize += poh_freed->size;
poh_prev = poh_next = NULL;
ulUpper = poh_freed->offset + poh_freed->size;
ulLower = poh_freed->offset;
pohThis = memheap->oh_free.poh_next;
while(pohThis != &memheap->oh_free) {
if(pohThis->offset == ulUpper) {
poh_next = pohThis;
} else if((pohThis->offset + pohThis->size) == ulLower) {
poh_prev = pohThis;
}
pohThis = pohThis->poh_next;
}
sisfb_delete_node(poh_freed);
if(poh_prev && poh_next) {
poh_prev->size += (poh_freed->size + poh_next->size);
sisfb_delete_node(poh_next);
sisfb_free_node(memheap, poh_freed);
sisfb_free_node(memheap, poh_next);
return poh_prev;
}
if(poh_prev) {
poh_prev->size += poh_freed->size;
sisfb_free_node(memheap, poh_freed);
return poh_prev;
}
if(poh_next) {
poh_next->size += poh_freed->size;
poh_next->offset = poh_freed->offset;
sisfb_free_node(memheap, poh_freed);
return poh_next;
}
sisfb_insert_node(&memheap->oh_free, poh_freed);
return poh_freed;
}
static void
sisfb_free_node(struct SIS_HEAP *memheap, struct SIS_OH *poh)
{
if(poh == NULL)
return;
poh->poh_next = memheap->poh_freelist;
memheap->poh_freelist = poh;
}
static void
sis_int_malloc(struct sis_video_info *ivideo, struct sis_memreq *req)
{
struct SIS_OH *poh = NULL;
if((ivideo) && (ivideo->sisfb_id == SISFB_ID) && (!ivideo->havenoheap))
poh = sisfb_poh_allocate(&ivideo->sisfb_heap, (u32)req->size);
if(poh == NULL) {
req->offset = req->size = 0;
DPRINTK("sisfb: Video RAM allocation failed\n");
} else {
req->offset = poh->offset;
req->size = poh->size;
DPRINTK("sisfb: Video RAM allocation succeeded: 0x%lx\n",
(poh->offset + ivideo->video_vbase));
}
}
void
sis_malloc(struct sis_memreq *req)
{
struct sis_video_info *ivideo = sisfb_heap->vinfo;
if(&ivideo->sisfb_heap == sisfb_heap)
sis_int_malloc(ivideo, req);
else
req->offset = req->size = 0;
}
void
sis_malloc_new(struct pci_dev *pdev, struct sis_memreq *req)
{
struct sis_video_info *ivideo = pci_get_drvdata(pdev);
sis_int_malloc(ivideo, req);
}
/* sis_free: u32 because "base" is offset inside video ram, can never be >4GB */
static void
sis_int_free(struct sis_video_info *ivideo, u32 base)
{
struct SIS_OH *poh;
if((!ivideo) || (ivideo->sisfb_id != SISFB_ID) || (ivideo->havenoheap))
return;
poh = sisfb_poh_free(&ivideo->sisfb_heap, base);
if(poh == NULL) {
DPRINTK("sisfb: sisfb_poh_free() failed at base 0x%x\n",
(unsigned int) base);
}
}
void
sis_free(u32 base)
{
struct sis_video_info *ivideo = sisfb_heap->vinfo;
sis_int_free(ivideo, base);
}
void
sis_free_new(struct pci_dev *pdev, u32 base)
{
struct sis_video_info *ivideo = pci_get_drvdata(pdev);
sis_int_free(ivideo, base);
}
/* --------------------- SetMode routines ------------------------- */
static void
sisfb_check_engine_and_sync(struct sis_video_info *ivideo)
{
u8 cr30, cr31;
/* Check if MMIO and engines are enabled,
* and sync in case they are. Can't use
* ivideo->accel here, as this might have
* been changed before this is called.
*/
cr30 = SiS_GetReg(SISSR, IND_SIS_PCI_ADDRESS_SET);
cr31 = SiS_GetReg(SISSR, IND_SIS_MODULE_ENABLE);
/* MMIO and 2D/3D engine enabled? */
if((cr30 & SIS_MEM_MAP_IO_ENABLE) && (cr31 & 0x42)) {
#ifdef CONFIG_FB_SIS_300
if(ivideo->sisvga_engine == SIS_300_VGA) {
/* Don't care about TurboQueue. It's
* enough to know that the engines
* are enabled
*/
sisfb_syncaccel(ivideo);
}
#endif
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
/* Check that any queue mode is
* enabled, and that the queue
* is not in the state of "reset"
*/
cr30 = SiS_GetReg(SISSR, 0x26);
if((cr30 & 0xe0) && (!(cr30 & 0x01))) {
sisfb_syncaccel(ivideo);
}
}
#endif
}
}
static void
sisfb_pre_setmode(struct sis_video_info *ivideo)
{
u8 cr30 = 0, cr31 = 0, cr33 = 0, cr35 = 0, cr38 = 0;
int tvregnum = 0;
ivideo->currentvbflags &= (VB_VIDEOBRIDGE | VB_DISPTYPE_DISP2);
SiS_SetReg(SISSR, 0x05, 0x86);
cr31 = SiS_GetReg(SISCR, 0x31);
cr31 &= ~0x60;
cr31 |= 0x04;
cr33 = ivideo->rate_idx & 0x0F;
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
if(ivideo->chip >= SIS_661) {
cr38 = SiS_GetReg(SISCR, 0x38);
cr38 &= ~0x07; /* Clear LCDA/DualEdge and YPbPr bits */
} else {
tvregnum = 0x38;
cr38 = SiS_GetReg(SISCR, tvregnum);
cr38 &= ~0x3b; /* Clear LCDA/DualEdge and YPbPr bits */
}
}
#endif
#ifdef CONFIG_FB_SIS_300
if(ivideo->sisvga_engine == SIS_300_VGA) {
tvregnum = 0x35;
cr38 = SiS_GetReg(SISCR, tvregnum);
}
#endif
SiS_SetEnableDstn(&ivideo->SiS_Pr, false);
SiS_SetEnableFstn(&ivideo->SiS_Pr, false);
ivideo->curFSTN = ivideo->curDSTN = 0;
switch(ivideo->currentvbflags & VB_DISPTYPE_DISP2) {
case CRT2_TV:
cr38 &= ~0xc0; /* Clear PAL-M / PAL-N bits */
if((ivideo->vbflags & TV_YPBPR) && (ivideo->vbflags2 & VB2_SISYPBPRBRIDGE)) {
#ifdef CONFIG_FB_SIS_315
if(ivideo->chip >= SIS_661) {
cr38 |= 0x04;
if(ivideo->vbflags & TV_YPBPR525P) cr35 |= 0x20;
else if(ivideo->vbflags & TV_YPBPR750P) cr35 |= 0x40;
else if(ivideo->vbflags & TV_YPBPR1080I) cr35 |= 0x60;
cr30 |= SIS_SIMULTANEOUS_VIEW_ENABLE;
cr35 &= ~0x01;
ivideo->currentvbflags |= (TV_YPBPR | (ivideo->vbflags & TV_YPBPRALL));
} else if(ivideo->sisvga_engine == SIS_315_VGA) {
cr30 |= (0x80 | SIS_SIMULTANEOUS_VIEW_ENABLE);
cr38 |= 0x08;
if(ivideo->vbflags & TV_YPBPR525P) cr38 |= 0x10;
else if(ivideo->vbflags & TV_YPBPR750P) cr38 |= 0x20;
else if(ivideo->vbflags & TV_YPBPR1080I) cr38 |= 0x30;
cr31 &= ~0x01;
ivideo->currentvbflags |= (TV_YPBPR | (ivideo->vbflags & TV_YPBPRALL));
}
#endif
} else if((ivideo->vbflags & TV_HIVISION) &&
(ivideo->vbflags2 & VB2_SISHIVISIONBRIDGE)) {
if(ivideo->chip >= SIS_661) {
cr38 |= 0x04;
cr35 |= 0x60;
} else {
cr30 |= 0x80;
}
cr30 |= SIS_SIMULTANEOUS_VIEW_ENABLE;
cr31 |= 0x01;
cr35 |= 0x01;
ivideo->currentvbflags |= TV_HIVISION;
} else if(ivideo->vbflags & TV_SCART) {
cr30 = (SIS_VB_OUTPUT_SCART | SIS_SIMULTANEOUS_VIEW_ENABLE);
cr31 |= 0x01;
cr35 |= 0x01;
ivideo->currentvbflags |= TV_SCART;
} else {
if(ivideo->vbflags & TV_SVIDEO) {
cr30 = (SIS_VB_OUTPUT_SVIDEO | SIS_SIMULTANEOUS_VIEW_ENABLE);
ivideo->currentvbflags |= TV_SVIDEO;
}
if(ivideo->vbflags & TV_AVIDEO) {
cr30 = (SIS_VB_OUTPUT_COMPOSITE | SIS_SIMULTANEOUS_VIEW_ENABLE);
ivideo->currentvbflags |= TV_AVIDEO;
}
}
cr31 |= SIS_DRIVER_MODE;
if(ivideo->vbflags & (TV_AVIDEO | TV_SVIDEO)) {
if(ivideo->vbflags & TV_PAL) {
cr31 |= 0x01; cr35 |= 0x01;
ivideo->currentvbflags |= TV_PAL;
if(ivideo->vbflags & TV_PALM) {
cr38 |= 0x40; cr35 |= 0x04;
ivideo->currentvbflags |= TV_PALM;
} else if(ivideo->vbflags & TV_PALN) {
cr38 |= 0x80; cr35 |= 0x08;
ivideo->currentvbflags |= TV_PALN;
}
} else {
cr31 &= ~0x01; cr35 &= ~0x01;
ivideo->currentvbflags |= TV_NTSC;
if(ivideo->vbflags & TV_NTSCJ) {
cr38 |= 0x40; cr35 |= 0x02;
ivideo->currentvbflags |= TV_NTSCJ;
}
}
}
break;
case CRT2_LCD:
cr30 = (SIS_VB_OUTPUT_LCD | SIS_SIMULTANEOUS_VIEW_ENABLE);
cr31 |= SIS_DRIVER_MODE;
SiS_SetEnableDstn(&ivideo->SiS_Pr, ivideo->sisfb_dstn);
SiS_SetEnableFstn(&ivideo->SiS_Pr, ivideo->sisfb_fstn);
ivideo->curFSTN = ivideo->sisfb_fstn;
ivideo->curDSTN = ivideo->sisfb_dstn;
break;
case CRT2_VGA:
cr30 = (SIS_VB_OUTPUT_CRT2 | SIS_SIMULTANEOUS_VIEW_ENABLE);
cr31 |= SIS_DRIVER_MODE;
if(ivideo->sisfb_nocrt2rate) {
cr33 |= (sisbios_mode[ivideo->sisfb_mode_idx].rate_idx << 4);
} else {
cr33 |= ((ivideo->rate_idx & 0x0F) << 4);
}
break;
default: /* disable CRT2 */
cr30 = 0x00;
cr31 |= (SIS_DRIVER_MODE | SIS_VB_OUTPUT_DISABLE);
}
SiS_SetReg(SISCR, 0x30, cr30);
SiS_SetReg(SISCR, 0x33, cr33);
if(ivideo->chip >= SIS_661) {
#ifdef CONFIG_FB_SIS_315
cr31 &= ~0x01; /* Clear PAL flag (now in CR35) */
SiS_SetRegANDOR(SISCR, 0x35, ~0x10, cr35); /* Leave overscan bit alone */
cr38 &= 0x07; /* Use only LCDA and HiVision/YPbPr bits */
SiS_SetRegANDOR(SISCR, 0x38, 0xf8, cr38);
#endif
} else if(ivideo->chip != SIS_300) {
SiS_SetReg(SISCR, tvregnum, cr38);
}
SiS_SetReg(SISCR, 0x31, cr31);
ivideo->SiS_Pr.SiS_UseOEM = ivideo->sisfb_useoem;
sisfb_check_engine_and_sync(ivideo);
}
/* Fix SR11 for 661 and later */
#ifdef CONFIG_FB_SIS_315
static void
sisfb_fixup_SR11(struct sis_video_info *ivideo)
{
u8 tmpreg;
if(ivideo->chip >= SIS_661) {
tmpreg = SiS_GetReg(SISSR, 0x11);
if(tmpreg & 0x20) {
tmpreg = SiS_GetReg(SISSR, 0x3e);
tmpreg = (tmpreg + 1) & 0xff;
SiS_SetReg(SISSR, 0x3e, tmpreg);
tmpreg = SiS_GetReg(SISSR, 0x11);
}
if(tmpreg & 0xf0) {
SiS_SetRegAND(SISSR, 0x11, 0x0f);
}
}
}
#endif
static void
sisfb_set_TVxposoffset(struct sis_video_info *ivideo, int val)
{
if(val > 32) val = 32;
if(val < -32) val = -32;
ivideo->tvxpos = val;
if(ivideo->sisfblocked) return;
if(!ivideo->modechanged) return;
if(ivideo->currentvbflags & CRT2_TV) {
if(ivideo->vbflags2 & VB2_CHRONTEL) {
int x = ivideo->tvx;
switch(ivideo->chronteltype) {
case 1:
x += val;
if(x < 0) x = 0;
SiS_SetReg(SISSR, 0x05, 0x86);
SiS_SetCH700x(&ivideo->SiS_Pr, 0x0a, (x & 0xff));
SiS_SetCH70xxANDOR(&ivideo->SiS_Pr, 0x08, ((x & 0x0100) >> 7), 0xFD);
break;
case 2:
/* Not supported by hardware */
break;
}
} else if(ivideo->vbflags2 & VB2_SISBRIDGE) {
u8 p2_1f,p2_20,p2_2b,p2_42,p2_43;
unsigned short temp;
p2_1f = ivideo->p2_1f;
p2_20 = ivideo->p2_20;
p2_2b = ivideo->p2_2b;
p2_42 = ivideo->p2_42;
p2_43 = ivideo->p2_43;
temp = p2_1f | ((p2_20 & 0xf0) << 4);
temp += (val * 2);
p2_1f = temp & 0xff;
p2_20 = (temp & 0xf00) >> 4;
p2_2b = ((p2_2b & 0x0f) + (val * 2)) & 0x0f;
temp = p2_43 | ((p2_42 & 0xf0) << 4);
temp += (val * 2);
p2_43 = temp & 0xff;
p2_42 = (temp & 0xf00) >> 4;
SiS_SetReg(SISPART2, 0x1f, p2_1f);
SiS_SetRegANDOR(SISPART2, 0x20, 0x0F, p2_20);
SiS_SetRegANDOR(SISPART2, 0x2b, 0xF0, p2_2b);
SiS_SetRegANDOR(SISPART2, 0x42, 0x0F, p2_42);
SiS_SetReg(SISPART2, 0x43, p2_43);
}
}
}
static void
sisfb_set_TVyposoffset(struct sis_video_info *ivideo, int val)
{
if(val > 32) val = 32;
if(val < -32) val = -32;
ivideo->tvypos = val;
if(ivideo->sisfblocked) return;
if(!ivideo->modechanged) return;
if(ivideo->currentvbflags & CRT2_TV) {
if(ivideo->vbflags2 & VB2_CHRONTEL) {
int y = ivideo->tvy;
switch(ivideo->chronteltype) {
case 1:
y -= val;
if(y < 0) y = 0;
SiS_SetReg(SISSR, 0x05, 0x86);
SiS_SetCH700x(&ivideo->SiS_Pr, 0x0b, (y & 0xff));
SiS_SetCH70xxANDOR(&ivideo->SiS_Pr, 0x08, ((y & 0x0100) >> 8), 0xFE);
break;
case 2:
/* Not supported by hardware */
break;
}
} else if(ivideo->vbflags2 & VB2_SISBRIDGE) {
char p2_01, p2_02;
val /= 2;
p2_01 = ivideo->p2_01;
p2_02 = ivideo->p2_02;
p2_01 += val;
p2_02 += val;
if(!(ivideo->currentvbflags & (TV_HIVISION | TV_YPBPR))) {
while((p2_01 <= 0) || (p2_02 <= 0)) {
p2_01 += 2;
p2_02 += 2;
}
}
SiS_SetReg(SISPART2, 0x01, p2_01);
SiS_SetReg(SISPART2, 0x02, p2_02);
}
}
}
static void
sisfb_post_setmode(struct sis_video_info *ivideo)
{
bool crt1isoff = false;
bool doit = true;
#if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315)
u8 reg;
#endif
#ifdef CONFIG_FB_SIS_315
u8 reg1;
#endif
SiS_SetReg(SISSR, 0x05, 0x86);
#ifdef CONFIG_FB_SIS_315
sisfb_fixup_SR11(ivideo);
#endif
/* Now we actually HAVE changed the display mode */
ivideo->modechanged = 1;
/* We can't switch off CRT1 if bridge is in slave mode */
if(ivideo->vbflags2 & VB2_VIDEOBRIDGE) {
if(sisfb_bridgeisslave(ivideo)) doit = false;
} else
ivideo->sisfb_crt1off = 0;
#ifdef CONFIG_FB_SIS_300
if(ivideo->sisvga_engine == SIS_300_VGA) {
if((ivideo->sisfb_crt1off) && (doit)) {
crt1isoff = true;
reg = 0x00;
} else {
crt1isoff = false;
reg = 0x80;
}
SiS_SetRegANDOR(SISCR, 0x17, 0x7f, reg);
}
#endif
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
if((ivideo->sisfb_crt1off) && (doit)) {
crt1isoff = true;
reg = 0x40;
reg1 = 0xc0;
} else {
crt1isoff = false;
reg = 0x00;
reg1 = 0x00;
}
SiS_SetRegANDOR(SISCR, ivideo->SiS_Pr.SiS_MyCR63, ~0x40, reg);
SiS_SetRegANDOR(SISSR, 0x1f, 0x3f, reg1);
}
#endif
if(crt1isoff) {
ivideo->currentvbflags &= ~VB_DISPTYPE_CRT1;
ivideo->currentvbflags |= VB_SINGLE_MODE;
} else {
ivideo->currentvbflags |= VB_DISPTYPE_CRT1;
if(ivideo->currentvbflags & VB_DISPTYPE_CRT2) {
ivideo->currentvbflags |= VB_MIRROR_MODE;
} else {
ivideo->currentvbflags |= VB_SINGLE_MODE;
}
}
SiS_SetRegAND(SISSR, IND_SIS_RAMDAC_CONTROL, ~0x04);
if(ivideo->currentvbflags & CRT2_TV) {
if(ivideo->vbflags2 & VB2_SISBRIDGE) {
ivideo->p2_1f = SiS_GetReg(SISPART2, 0x1f);
ivideo->p2_20 = SiS_GetReg(SISPART2, 0x20);
ivideo->p2_2b = SiS_GetReg(SISPART2, 0x2b);
ivideo->p2_42 = SiS_GetReg(SISPART2, 0x42);
ivideo->p2_43 = SiS_GetReg(SISPART2, 0x43);
ivideo->p2_01 = SiS_GetReg(SISPART2, 0x01);
ivideo->p2_02 = SiS_GetReg(SISPART2, 0x02);
} else if(ivideo->vbflags2 & VB2_CHRONTEL) {
if(ivideo->chronteltype == 1) {
ivideo->tvx = SiS_GetCH700x(&ivideo->SiS_Pr, 0x0a);
ivideo->tvx |= (((SiS_GetCH700x(&ivideo->SiS_Pr, 0x08) & 0x02) >> 1) << 8);
ivideo->tvy = SiS_GetCH700x(&ivideo->SiS_Pr, 0x0b);
ivideo->tvy |= ((SiS_GetCH700x(&ivideo->SiS_Pr, 0x08) & 0x01) << 8);
}
}
}
if(ivideo->tvxpos) {
sisfb_set_TVxposoffset(ivideo, ivideo->tvxpos);
}
if(ivideo->tvypos) {
sisfb_set_TVyposoffset(ivideo, ivideo->tvypos);
}
/* Eventually sync engines */
sisfb_check_engine_and_sync(ivideo);
/* (Re-)Initialize chip engines */
if(ivideo->accel) {
sisfb_engine_init(ivideo);
} else {
ivideo->engineok = 0;
}
}
static int
sisfb_reset_mode(struct sis_video_info *ivideo)
{
if(sisfb_set_mode(ivideo, 0))
return 1;
sisfb_set_pitch(ivideo);
sisfb_set_base_CRT1(ivideo, ivideo->current_base);
sisfb_set_base_CRT2(ivideo, ivideo->current_base);
return 0;
}
static void
sisfb_handle_command(struct sis_video_info *ivideo, struct sisfb_cmd *sisfb_command)
{
int mycrt1off;
switch(sisfb_command->sisfb_cmd) {
case SISFB_CMD_GETVBFLAGS:
if(!ivideo->modechanged) {
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_EARLY;
} else {
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_OK;
sisfb_command->sisfb_result[1] = ivideo->currentvbflags;
sisfb_command->sisfb_result[2] = ivideo->vbflags2;
}
break;
case SISFB_CMD_SWITCHCRT1:
/* arg[0]: 0 = off, 1 = on, 99 = query */
if(!ivideo->modechanged) {
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_EARLY;
} else if(sisfb_command->sisfb_arg[0] == 99) {
/* Query */
sisfb_command->sisfb_result[1] = ivideo->sisfb_crt1off ? 0 : 1;
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_OK;
} else if(ivideo->sisfblocked) {
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_LOCKED;
} else if((!(ivideo->currentvbflags & CRT2_ENABLE)) &&
(sisfb_command->sisfb_arg[0] == 0)) {
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_NOCRT2;
} else {
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_OK;
mycrt1off = sisfb_command->sisfb_arg[0] ? 0 : 1;
if( ((ivideo->currentvbflags & VB_DISPTYPE_CRT1) && mycrt1off) ||
((!(ivideo->currentvbflags & VB_DISPTYPE_CRT1)) && !mycrt1off) ) {
ivideo->sisfb_crt1off = mycrt1off;
if(sisfb_reset_mode(ivideo)) {
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_OTHER;
}
}
sisfb_command->sisfb_result[1] = ivideo->sisfb_crt1off ? 0 : 1;
}
break;
/* more to come */
default:
sisfb_command->sisfb_result[0] = SISFB_CMD_ERR_UNKNOWN;
printk(KERN_ERR "sisfb: Unknown command 0x%x\n",
sisfb_command->sisfb_cmd);
}
}
#ifndef MODULE
static int __init sisfb_setup(char *options)
{
char *this_opt;
sisfb_setdefaultparms();
if(!options || !(*options))
return 0;
while((this_opt = strsep(&options, ",")) != NULL) {
if(!(*this_opt)) continue;
if(!strnicmp(this_opt, "off", 3)) {
sisfb_off = 1;
} else if(!strnicmp(this_opt, "forcecrt2type:", 14)) {
/* Need to check crt2 type first for fstn/dstn */
sisfb_search_crt2type(this_opt + 14);
} else if(!strnicmp(this_opt, "tvmode:",7)) {
sisfb_search_tvstd(this_opt + 7);
} else if(!strnicmp(this_opt, "tvstandard:",11)) {
sisfb_search_tvstd(this_opt + 11);
} else if(!strnicmp(this_opt, "mode:", 5)) {
sisfb_search_mode(this_opt + 5, false);
} else if(!strnicmp(this_opt, "vesa:", 5)) {
sisfb_search_vesamode(simple_strtoul(this_opt + 5, NULL, 0), false);
} else if(!strnicmp(this_opt, "rate:", 5)) {
sisfb_parm_rate = simple_strtoul(this_opt + 5, NULL, 0);
} else if(!strnicmp(this_opt, "forcecrt1:", 10)) {
sisfb_forcecrt1 = (int)simple_strtoul(this_opt + 10, NULL, 0);
} else if(!strnicmp(this_opt, "mem:",4)) {
sisfb_parm_mem = simple_strtoul(this_opt + 4, NULL, 0);
} else if(!strnicmp(this_opt, "pdc:", 4)) {
sisfb_pdc = simple_strtoul(this_opt + 4, NULL, 0);
} else if(!strnicmp(this_opt, "pdc1:", 5)) {
sisfb_pdca = simple_strtoul(this_opt + 5, NULL, 0);
} else if(!strnicmp(this_opt, "noaccel", 7)) {
sisfb_accel = 0;
} else if(!strnicmp(this_opt, "accel", 5)) {
sisfb_accel = -1;
} else if(!strnicmp(this_opt, "noypan", 6)) {
sisfb_ypan = 0;
} else if(!strnicmp(this_opt, "ypan", 4)) {
sisfb_ypan = -1;
} else if(!strnicmp(this_opt, "nomax", 5)) {
sisfb_max = 0;
} else if(!strnicmp(this_opt, "max", 3)) {
sisfb_max = -1;
} else if(!strnicmp(this_opt, "userom:", 7)) {
sisfb_userom = (int)simple_strtoul(this_opt + 7, NULL, 0);
} else if(!strnicmp(this_opt, "useoem:", 7)) {
sisfb_useoem = (int)simple_strtoul(this_opt + 7, NULL, 0);
} else if(!strnicmp(this_opt, "nocrt2rate", 10)) {
sisfb_nocrt2rate = 1;
} else if(!strnicmp(this_opt, "scalelcd:", 9)) {
unsigned long temp = 2;
temp = simple_strtoul(this_opt + 9, NULL, 0);
if((temp == 0) || (temp == 1)) {
sisfb_scalelcd = temp ^ 1;
}
} else if(!strnicmp(this_opt, "tvxposoffset:", 13)) {
int temp = 0;
temp = (int)simple_strtol(this_opt + 13, NULL, 0);
if((temp >= -32) && (temp <= 32)) {
sisfb_tvxposoffset = temp;
}
} else if(!strnicmp(this_opt, "tvyposoffset:", 13)) {
int temp = 0;
temp = (int)simple_strtol(this_opt + 13, NULL, 0);
if((temp >= -32) && (temp <= 32)) {
sisfb_tvyposoffset = temp;
}
} else if(!strnicmp(this_opt, "specialtiming:", 14)) {
sisfb_search_specialtiming(this_opt + 14);
} else if(!strnicmp(this_opt, "lvdshl:", 7)) {
int temp = 4;
temp = simple_strtoul(this_opt + 7, NULL, 0);
if((temp >= 0) && (temp <= 3)) {
sisfb_lvdshl = temp;
}
} else if(this_opt[0] >= '0' && this_opt[0] <= '9') {
sisfb_search_mode(this_opt, true);
#if !defined(__i386__) && !defined(__x86_64__)
} else if(!strnicmp(this_opt, "resetcard", 9)) {
sisfb_resetcard = 1;
} else if(!strnicmp(this_opt, "videoram:", 9)) {
sisfb_videoram = simple_strtoul(this_opt + 9, NULL, 0);
#endif
} else {
printk(KERN_INFO "sisfb: Invalid option %s\n", this_opt);
}
}
return 0;
}
#endif
static int __devinit
sisfb_check_rom(void __iomem *rom_base, struct sis_video_info *ivideo)
{
void __iomem *rom;
int romptr;
if((readb(rom_base) != 0x55) || (readb(rom_base + 1) != 0xaa))
return 0;
romptr = (readb(rom_base + 0x18) | (readb(rom_base + 0x19) << 8));
if(romptr > (0x10000 - 8))
return 0;
rom = rom_base + romptr;
if((readb(rom) != 'P') || (readb(rom + 1) != 'C') ||
(readb(rom + 2) != 'I') || (readb(rom + 3) != 'R'))
return 0;
if((readb(rom + 4) | (readb(rom + 5) << 8)) != ivideo->chip_vendor)
return 0;
if((readb(rom + 6) | (readb(rom + 7) << 8)) != ivideo->chip_id)
return 0;
return 1;
}
static unsigned char * __devinit
sisfb_find_rom(struct pci_dev *pdev)
{
struct sis_video_info *ivideo = pci_get_drvdata(pdev);
void __iomem *rom_base;
unsigned char *myrombase = NULL;
size_t romsize;
/* First, try the official pci ROM functions (except
* on integrated chipsets which have no ROM).
*/
if(!ivideo->nbridge) {
if((rom_base = pci_map_rom(pdev, &romsize))) {
if(sisfb_check_rom(rom_base, ivideo)) {
if((myrombase = vmalloc(65536))) {
memcpy_fromio(myrombase, rom_base,
(romsize > 65536) ? 65536 : romsize);
}
}
pci_unmap_rom(pdev, rom_base);
}
}
if(myrombase) return myrombase;
/* Otherwise do it the conventional way. */
#if defined(__i386__) || defined(__x86_64__)
{
u32 temp;
for (temp = 0x000c0000; temp < 0x000f0000; temp += 0x00001000) {
rom_base = ioremap(temp, 65536);
if (!rom_base)
continue;
if (!sisfb_check_rom(rom_base, ivideo)) {
iounmap(rom_base);
continue;
}
if ((myrombase = vmalloc(65536)))
memcpy_fromio(myrombase, rom_base, 65536);
iounmap(rom_base);
break;
}
}
#endif
return myrombase;
}
static void __devinit
sisfb_post_map_vram(struct sis_video_info *ivideo, unsigned int *mapsize,
unsigned int min)
{
if (*mapsize < (min << 20))
return;
ivideo->video_vbase = ioremap(ivideo->video_base, (*mapsize));
if(!ivideo->video_vbase) {
printk(KERN_ERR
"sisfb: Unable to map maximum video RAM for size detection\n");
(*mapsize) >>= 1;
while((!(ivideo->video_vbase = ioremap(ivideo->video_base, (*mapsize))))) {
(*mapsize) >>= 1;
if((*mapsize) < (min << 20))
break;
}
if(ivideo->video_vbase) {
printk(KERN_ERR
"sisfb: Video RAM size detection limited to %dMB\n",
(int)((*mapsize) >> 20));
}
}
}
#ifdef CONFIG_FB_SIS_300
static int __devinit
sisfb_post_300_buswidth(struct sis_video_info *ivideo)
{
void __iomem *FBAddress = ivideo->video_vbase;
unsigned short temp;
unsigned char reg;
int i, j;
SiS_SetRegAND(SISSR, 0x15, 0xFB);
SiS_SetRegOR(SISSR, 0x15, 0x04);
SiS_SetReg(SISSR, 0x13, 0x00);
SiS_SetReg(SISSR, 0x14, 0xBF);
for(i = 0; i < 2; i++) {
temp = 0x1234;
for(j = 0; j < 4; j++) {
writew(temp, FBAddress);
if(readw(FBAddress) == temp)
break;
SiS_SetRegOR(SISSR, 0x3c, 0x01);
reg = SiS_GetReg(SISSR, 0x05);
reg = SiS_GetReg(SISSR, 0x05);
SiS_SetRegAND(SISSR, 0x3c, 0xfe);
reg = SiS_GetReg(SISSR, 0x05);
reg = SiS_GetReg(SISSR, 0x05);
temp++;
}
}
writel(0x01234567L, FBAddress);
writel(0x456789ABL, (FBAddress + 4));
writel(0x89ABCDEFL, (FBAddress + 8));
writel(0xCDEF0123L, (FBAddress + 12));
reg = SiS_GetReg(SISSR, 0x3b);
if(reg & 0x01) {
if(readl((FBAddress + 12)) == 0xCDEF0123L)
return 4; /* Channel A 128bit */
}
if(readl((FBAddress + 4)) == 0x456789ABL)
return 2; /* Channel B 64bit */
return 1; /* 32bit */
}
static int __devinit
sisfb_post_300_rwtest(struct sis_video_info *ivideo, int iteration, int buswidth,
int PseudoRankCapacity, int PseudoAdrPinCount,
unsigned int mapsize)
{
void __iomem *FBAddr = ivideo->video_vbase;
unsigned short sr14;
unsigned int k, RankCapacity, PageCapacity, BankNumHigh, BankNumMid;
unsigned int PhysicalAdrOtherPage, PhysicalAdrHigh, PhysicalAdrHalfPage;
static const unsigned short SiS_DRAMType[17][5] = {
{0x0C,0x0A,0x02,0x40,0x39},
{0x0D,0x0A,0x01,0x40,0x48},
{0x0C,0x09,0x02,0x20,0x35},
{0x0D,0x09,0x01,0x20,0x44},
{0x0C,0x08,0x02,0x10,0x31},
{0x0D,0x08,0x01,0x10,0x40},
{0x0C,0x0A,0x01,0x20,0x34},
{0x0C,0x09,0x01,0x08,0x32},
{0x0B,0x08,0x02,0x08,0x21},
{0x0C,0x08,0x01,0x08,0x30},
{0x0A,0x08,0x02,0x04,0x11},
{0x0B,0x0A,0x01,0x10,0x28},
{0x09,0x08,0x02,0x02,0x01},
{0x0B,0x09,0x01,0x08,0x24},
{0x0B,0x08,0x01,0x04,0x20},
{0x0A,0x08,0x01,0x02,0x10},
{0x09,0x08,0x01,0x01,0x00}
};
for(k = 0; k <= 16; k++) {
RankCapacity = buswidth * SiS_DRAMType[k][3];
if(RankCapacity != PseudoRankCapacity)
continue;
if((SiS_DRAMType[k][2] + SiS_DRAMType[k][0]) > PseudoAdrPinCount)
continue;
BankNumHigh = RankCapacity * 16 * iteration - 1;
if(iteration == 3) { /* Rank No */
BankNumMid = RankCapacity * 16 - 1;
} else {
BankNumMid = RankCapacity * 16 * iteration / 2 - 1;
}
PageCapacity = (1 << SiS_DRAMType[k][1]) * buswidth * 4;
PhysicalAdrHigh = BankNumHigh;
PhysicalAdrHalfPage = (PageCapacity / 2 + PhysicalAdrHigh) % PageCapacity;
PhysicalAdrOtherPage = PageCapacity * SiS_DRAMType[k][2] + PhysicalAdrHigh;
SiS_SetRegAND(SISSR, 0x15, 0xFB); /* Test */
SiS_SetRegOR(SISSR, 0x15, 0x04); /* Test */
sr14 = (SiS_DRAMType[k][3] * buswidth) - 1;
if(buswidth == 4) sr14 |= 0x80;
else if(buswidth == 2) sr14 |= 0x40;
SiS_SetReg(SISSR, 0x13, SiS_DRAMType[k][4]);
SiS_SetReg(SISSR, 0x14, sr14);
BankNumHigh <<= 16;
BankNumMid <<= 16;
if((BankNumHigh + PhysicalAdrHigh >= mapsize) ||
(BankNumMid + PhysicalAdrHigh >= mapsize) ||
(BankNumHigh + PhysicalAdrHalfPage >= mapsize) ||
(BankNumHigh + PhysicalAdrOtherPage >= mapsize))
continue;
/* Write data */
writew(((unsigned short)PhysicalAdrHigh),
(FBAddr + BankNumHigh + PhysicalAdrHigh));
writew(((unsigned short)BankNumMid),
(FBAddr + BankNumMid + PhysicalAdrHigh));
writew(((unsigned short)PhysicalAdrHalfPage),
(FBAddr + BankNumHigh + PhysicalAdrHalfPage));
writew(((unsigned short)PhysicalAdrOtherPage),
(FBAddr + BankNumHigh + PhysicalAdrOtherPage));
/* Read data */
if(readw(FBAddr + BankNumHigh + PhysicalAdrHigh) == PhysicalAdrHigh)
return 1;
}
return 0;
}
static void __devinit
sisfb_post_300_ramsize(struct pci_dev *pdev, unsigned int mapsize)
{
struct sis_video_info *ivideo = pci_get_drvdata(pdev);
int i, j, buswidth;
int PseudoRankCapacity, PseudoAdrPinCount;
buswidth = sisfb_post_300_buswidth(ivideo);
for(i = 6; i >= 0; i--) {
PseudoRankCapacity = 1 << i;
for(j = 4; j >= 1; j--) {
PseudoAdrPinCount = 15 - j;
if((PseudoRankCapacity * j) <= 64) {
if(sisfb_post_300_rwtest(ivideo,
j,
buswidth,
PseudoRankCapacity,
PseudoAdrPinCount,
mapsize))
return;
}
}
}
}
static void __devinit
sisfb_post_sis300(struct pci_dev *pdev)
{
struct sis_video_info *ivideo = pci_get_drvdata(pdev);
unsigned char *bios = ivideo->SiS_Pr.VirtualRomBase;
u8 reg, v1, v2, v3, v4, v5, v6, v7, v8;
u16 index, rindex, memtype = 0;
unsigned int mapsize;
if(!ivideo->SiS_Pr.UseROM)
bios = NULL;
SiS_SetReg(SISSR, 0x05, 0x86);
if(bios) {
if(bios[0x52] & 0x80) {
memtype = bios[0x52];
} else {
memtype = SiS_GetReg(SISSR, 0x3a);
}
memtype &= 0x07;
}
v3 = 0x80; v6 = 0x80;
if(ivideo->revision_id <= 0x13) {
v1 = 0x44; v2 = 0x42;
v4 = 0x44; v5 = 0x42;
} else {
v1 = 0x68; v2 = 0x43; /* Assume 125Mhz MCLK */
v4 = 0x68; v5 = 0x43; /* Assume 125Mhz ECLK */
if(bios) {
index = memtype * 5;
rindex = index + 0x54;
v1 = bios[rindex++];
v2 = bios[rindex++];
v3 = bios[rindex++];
rindex = index + 0x7c;
v4 = bios[rindex++];
v5 = bios[rindex++];
v6 = bios[rindex++];
}
}
SiS_SetReg(SISSR, 0x28, v1);
SiS_SetReg(SISSR, 0x29, v2);
SiS_SetReg(SISSR, 0x2a, v3);
SiS_SetReg(SISSR, 0x2e, v4);
SiS_SetReg(SISSR, 0x2f, v5);
SiS_SetReg(SISSR, 0x30, v6);
v1 = 0x10;
if(bios)
v1 = bios[0xa4];
SiS_SetReg(SISSR, 0x07, v1); /* DAC speed */
SiS_SetReg(SISSR, 0x11, 0x0f); /* DDC, power save */
v1 = 0x01; v2 = 0x43; v3 = 0x1e; v4 = 0x2a;
v5 = 0x06; v6 = 0x00; v7 = 0x00; v8 = 0x00;
if(bios) {
memtype += 0xa5;
v1 = bios[memtype];
v2 = bios[memtype + 8];
v3 = bios[memtype + 16];
v4 = bios[memtype + 24];
v5 = bios[memtype + 32];
v6 = bios[memtype + 40];
v7 = bios[memtype + 48];
v8 = bios[memtype + 56];
}
if(ivideo->revision_id >= 0x80)
v3 &= 0xfd;
SiS_SetReg(SISSR, 0x15, v1); /* Ram type (assuming 0, BIOS 0xa5 step 8) */
SiS_SetReg(SISSR, 0x16, v2);
SiS_SetReg(SISSR, 0x17, v3);
SiS_SetReg(SISSR, 0x18, v4);
SiS_SetReg(SISSR, 0x19, v5);
SiS_SetReg(SISSR, 0x1a, v6);
SiS_SetReg(SISSR, 0x1b, v7);
SiS_SetReg(SISSR, 0x1c, v8); /* ---- */
SiS_SetRegAND(SISSR, 0x15, 0xfb);
SiS_SetRegOR(SISSR, 0x15, 0x04);
if(bios) {
if(bios[0x53] & 0x02) {
SiS_SetRegOR(SISSR, 0x19, 0x20);
}
}
v1 = 0x04; /* DAC pedestal (BIOS 0xe5) */
if(ivideo->revision_id >= 0x80)
v1 |= 0x01;
SiS_SetReg(SISSR, 0x1f, v1);
SiS_SetReg(SISSR, 0x20, 0xa4); /* linear & relocated io & disable a0000 */
v1 = 0xf6; v2 = 0x0d; v3 = 0x00;
if(bios) {
v1 = bios[0xe8];
v2 = bios[0xe9];
v3 = bios[0xea];
}
SiS_SetReg(SISSR, 0x23, v1);
SiS_SetReg(SISSR, 0x24, v2);
SiS_SetReg(SISSR, 0x25, v3);
SiS_SetReg(SISSR, 0x21, 0x84);
SiS_SetReg(SISSR, 0x22, 0x00);
SiS_SetReg(SISCR, 0x37, 0x00);
SiS_SetRegOR(SISPART1, 0x24, 0x01); /* unlock crt2 */
SiS_SetReg(SISPART1, 0x00, 0x00);
v1 = 0x40; v2 = 0x11;
if(bios) {
v1 = bios[0xec];
v2 = bios[0xeb];
}
SiS_SetReg(SISPART1, 0x02, v1);
if(ivideo->revision_id >= 0x80)
v2 &= ~0x01;
reg = SiS_GetReg(SISPART4, 0x00);
if((reg == 1) || (reg == 2)) {
SiS_SetReg(SISCR, 0x37, 0x02);
SiS_SetReg(SISPART2, 0x00, 0x1c);
v4 = 0x00; v5 = 0x00; v6 = 0x10;
if(ivideo->SiS_Pr.UseROM) {
v4 = bios[0xf5];
v5 = bios[0xf6];
v6 = bios[0xf7];
}
SiS_SetReg(SISPART4, 0x0d, v4);
SiS_SetReg(SISPART4, 0x0e, v5);
SiS_SetReg(SISPART4, 0x10, v6);
SiS_SetReg(SISPART4, 0x0f, 0x3f);
reg = SiS_GetReg(SISPART4, 0x01);
if(reg >= 0xb0) {
reg = SiS_GetReg(SISPART4, 0x23);
reg &= 0x20;
reg <<= 1;
SiS_SetReg(SISPART4, 0x23, reg);
}
} else {
v2 &= ~0x10;
}
SiS_SetReg(SISSR, 0x32, v2);
SiS_SetRegAND(SISPART1, 0x24, 0xfe); /* Lock CRT2 */
reg = SiS_GetReg(SISSR, 0x16);
reg &= 0xc3;
SiS_SetReg(SISCR, 0x35, reg);
SiS_SetReg(SISCR, 0x83, 0x00);
#if !defined(__i386__) && !defined(__x86_64__)
if(sisfb_videoram) {
SiS_SetReg(SISSR, 0x13, 0x28); /* ? */
reg = ((sisfb_videoram >> 10) - 1) | 0x40;
SiS_SetReg(SISSR, 0x14, reg);
} else {
#endif
/* Need to map max FB size for finding out about RAM size */
mapsize = ivideo->video_size;
sisfb_post_map_vram(ivideo, &mapsize, 4);
if(ivideo->video_vbase) {
sisfb_post_300_ramsize(pdev, mapsize);
iounmap(ivideo->video_vbase);
} else {
printk(KERN_DEBUG
"sisfb: Failed to map memory for size detection, assuming 8MB\n");
SiS_SetReg(SISSR, 0x13, 0x28); /* ? */
SiS_SetReg(SISSR, 0x14, 0x47); /* 8MB, 64bit default */
}
#if !defined(__i386__) && !defined(__x86_64__)
}
#endif
if(bios) {
v1 = bios[0xe6];
v2 = bios[0xe7];
} else {
reg = SiS_GetReg(SISSR, 0x3a);
if((reg & 0x30) == 0x30) {
v1 = 0x04; /* PCI */
v2 = 0x92;
} else {
v1 = 0x14; /* AGP */
v2 = 0xb2;
}
}
SiS_SetReg(SISSR, 0x21, v1);
SiS_SetReg(SISSR, 0x22, v2);
/* Sense CRT1 */
sisfb_sense_crt1(ivideo);
/* Set default mode, don't clear screen */
ivideo->SiS_Pr.SiS_UseOEM = false;
SiS_SetEnableDstn(&ivideo->SiS_Pr, false);
SiS_SetEnableFstn(&ivideo->SiS_Pr, false);
ivideo->curFSTN = ivideo->curDSTN = 0;
ivideo->SiS_Pr.VideoMemorySize = 8 << 20;
SiSSetMode(&ivideo->SiS_Pr, 0x2e | 0x80);
SiS_SetReg(SISSR, 0x05, 0x86);
/* Display off */
SiS_SetRegOR(SISSR, 0x01, 0x20);
/* Save mode number in CR34 */
SiS_SetReg(SISCR, 0x34, 0x2e);
/* Let everyone know what the current mode is */
ivideo->modeprechange = 0x2e;
}
#endif
#ifdef CONFIG_FB_SIS_315
#if 0
static void __devinit
sisfb_post_sis315330(struct pci_dev *pdev)
{
/* TODO */
}
#endif
static inline int sisfb_xgi_is21(struct sis_video_info *ivideo)
{
return ivideo->chip_real_id == XGI_21;
}
static void __devinit
sisfb_post_xgi_delay(struct sis_video_info *ivideo, int delay)
{
unsigned int i;
u8 reg;
for(i = 0; i <= (delay * 10 * 36); i++) {
reg = SiS_GetReg(SISSR, 0x05);
reg++;
}
}
static int __devinit
sisfb_find_host_bridge(struct sis_video_info *ivideo, struct pci_dev *mypdev,
unsigned short pcivendor)
{
struct pci_dev *pdev = NULL;
unsigned short temp;
int ret = 0;
while((pdev = pci_get_class(PCI_CLASS_BRIDGE_HOST, pdev))) {
temp = pdev->vendor;
if(temp == pcivendor) {
ret = 1;
pci_dev_put(pdev);
break;
}
}
return ret;
}
static int __devinit
sisfb_post_xgi_rwtest(struct sis_video_info *ivideo, int starta,
unsigned int enda, unsigned int mapsize)
{
unsigned int pos;
int i;
writel(0, ivideo->video_vbase);
for(i = starta; i <= enda; i++) {
pos = 1 << i;
if(pos < mapsize)
writel(pos, ivideo->video_vbase + pos);
}
sisfb_post_xgi_delay(ivideo, 150);
if(readl(ivideo->video_vbase) != 0)
return 0;
for(i = starta; i <= enda; i++) {
pos = 1 << i;
if(pos < mapsize) {
if(readl(ivideo->video_vbase + pos) != pos)
return 0;
} else
return 0;
}
return 1;
}
static int __devinit
sisfb_post_xgi_ramsize(struct sis_video_info *ivideo)
{
unsigned int buswidth, ranksize, channelab, mapsize;
int i, j, k, l, status;
u8 reg, sr14;
static const u8 dramsr13[12 * 5] = {
0x02, 0x0e, 0x0b, 0x80, 0x5d,
0x02, 0x0e, 0x0a, 0x40, 0x59,
0x02, 0x0d, 0x0b, 0x40, 0x4d,
0x02, 0x0e, 0x09, 0x20, 0x55,
0x02, 0x0d, 0x0a, 0x20, 0x49,
0x02, 0x0c, 0x0b, 0x20, 0x3d,
0x02, 0x0e, 0x08, 0x10, 0x51,
0x02, 0x0d, 0x09, 0x10, 0x45,
0x02, 0x0c, 0x0a, 0x10, 0x39,
0x02, 0x0d, 0x08, 0x08, 0x41,
0x02, 0x0c, 0x09, 0x08, 0x35,
0x02, 0x0c, 0x08, 0x04, 0x31
};
static const u8 dramsr13_4[4 * 5] = {
0x02, 0x0d, 0x09, 0x40, 0x45,
0x02, 0x0c, 0x09, 0x20, 0x35,
0x02, 0x0c, 0x08, 0x10, 0x31,
0x02, 0x0b, 0x08, 0x08, 0x21
};
/* Enable linear mode, disable 0xa0000 address decoding */
/* We disable a0000 address decoding, because
* - if running on x86, if the card is disabled, it means
* that another card is in the system. We don't want
* to interphere with that primary card's textmode.
* - if running on non-x86, there usually is no VGA window
* at a0000.
*/
SiS_SetRegOR(SISSR, 0x20, (0x80 | 0x04));
/* Need to map max FB size for finding out about RAM size */
mapsize = ivideo->video_size;
sisfb_post_map_vram(ivideo, &mapsize, 32);
if(!ivideo->video_vbase) {
printk(KERN_ERR "sisfb: Unable to detect RAM size. Setting default.\n");
SiS_SetReg(SISSR, 0x13, 0x35);
SiS_SetReg(SISSR, 0x14, 0x41);
/* TODO */
return -ENOMEM;
}
/* Non-interleaving */
SiS_SetReg(SISSR, 0x15, 0x00);
/* No tiling */
SiS_SetReg(SISSR, 0x1c, 0x00);
if(ivideo->chip == XGI_20) {
channelab = 1;
reg = SiS_GetReg(SISCR, 0x97);
if(!(reg & 0x01)) { /* Single 32/16 */
buswidth = 32;
SiS_SetReg(SISSR, 0x13, 0xb1);
SiS_SetReg(SISSR, 0x14, 0x52);
sisfb_post_xgi_delay(ivideo, 1);
sr14 = 0x02;
if(sisfb_post_xgi_rwtest(ivideo, 23, 24, mapsize))
goto bail_out;
SiS_SetReg(SISSR, 0x13, 0x31);
SiS_SetReg(SISSR, 0x14, 0x42);
sisfb_post_xgi_delay(ivideo, 1);
if(sisfb_post_xgi_rwtest(ivideo, 23, 23, mapsize))
goto bail_out;
buswidth = 16;
SiS_SetReg(SISSR, 0x13, 0xb1);
SiS_SetReg(SISSR, 0x14, 0x41);
sisfb_post_xgi_delay(ivideo, 1);
sr14 = 0x01;
if(sisfb_post_xgi_rwtest(ivideo, 22, 23, mapsize))
goto bail_out;
else
SiS_SetReg(SISSR, 0x13, 0x31);
} else { /* Dual 16/8 */
buswidth = 16;
SiS_SetReg(SISSR, 0x13, 0xb1);
SiS_SetReg(SISSR, 0x14, 0x41);
sisfb_post_xgi_delay(ivideo, 1);
sr14 = 0x01;
if(sisfb_post_xgi_rwtest(ivideo, 22, 23, mapsize))
goto bail_out;
SiS_SetReg(SISSR, 0x13, 0x31);
SiS_SetReg(SISSR, 0x14, 0x31);
sisfb_post_xgi_delay(ivideo, 1);
if(sisfb_post_xgi_rwtest(ivideo, 22, 22, mapsize))
goto bail_out;
buswidth = 8;
SiS_SetReg(SISSR, 0x13, 0xb1);
SiS_SetReg(SISSR, 0x14, 0x30);
sisfb_post_xgi_delay(ivideo, 1);
sr14 = 0x00;
if(sisfb_post_xgi_rwtest(ivideo, 21, 22, mapsize))
goto bail_out;
else
SiS_SetReg(SISSR, 0x13, 0x31);
}
} else { /* XGI_40 */
reg = SiS_GetReg(SISCR, 0x97);
if(!(reg & 0x10)) {
reg = SiS_GetReg(SISSR, 0x39);
reg >>= 1;
}
if(reg & 0x01) { /* DDRII */
buswidth = 32;
if(ivideo->revision_id == 2) {
channelab = 2;
SiS_SetReg(SISSR, 0x13, 0xa1);
SiS_SetReg(SISSR, 0x14, 0x44);
sr14 = 0x04;
sisfb_post_xgi_delay(ivideo, 1);
if(sisfb_post_xgi_rwtest(ivideo, 23, 24, mapsize))
goto bail_out;
SiS_SetReg(SISSR, 0x13, 0x21);
SiS_SetReg(SISSR, 0x14, 0x34);
if(sisfb_post_xgi_rwtest(ivideo, 22, 23, mapsize))
goto bail_out;
channelab = 1;
SiS_SetReg(SISSR, 0x13, 0xa1);
SiS_SetReg(SISSR, 0x14, 0x40);
sr14 = 0x00;
if(sisfb_post_xgi_rwtest(ivideo, 22, 23, mapsize))
goto bail_out;
SiS_SetReg(SISSR, 0x13, 0x21);
SiS_SetReg(SISSR, 0x14, 0x30);
} else {
channelab = 3;
SiS_SetReg(SISSR, 0x13, 0xa1);
SiS_SetReg(SISSR, 0x14, 0x4c);
sr14 = 0x0c;
sisfb_post_xgi_delay(ivideo, 1);
if(sisfb_post_xgi_rwtest(ivideo, 23, 25, mapsize))
goto bail_out;
channelab = 2;
SiS_SetReg(SISSR, 0x14, 0x48);
sisfb_post_xgi_delay(ivideo, 1);
sr14 = 0x08;
if(sisfb_post_xgi_rwtest(ivideo, 23, 24, mapsize))
goto bail_out;
SiS_SetReg(SISSR, 0x13, 0x21);
SiS_SetReg(SISSR, 0x14, 0x3c);
sr14 = 0x0c;
if(sisfb_post_xgi_rwtest(ivideo, 23, 24, mapsize)) {
channelab = 3;
} else {
channelab = 2;
SiS_SetReg(SISSR, 0x14, 0x38);
sr14 = 0x08;
}
}
sisfb_post_xgi_delay(ivideo, 1);
} else { /* DDR */
buswidth = 64;
if(ivideo->revision_id == 2) {
channelab = 1;
SiS_SetReg(SISSR, 0x13, 0xa1);
SiS_SetReg(SISSR, 0x14, 0x52);
sisfb_post_xgi_delay(ivideo, 1);
sr14 = 0x02;
if(sisfb_post_xgi_rwtest(ivideo, 23, 24, mapsize))
goto bail_out;
SiS_SetReg(SISSR, 0x13, 0x21);
SiS_SetReg(SISSR, 0x14, 0x42);
} else {
channelab = 2;
SiS_SetReg(SISSR, 0x13, 0xa1);
SiS_SetReg(SISSR, 0x14, 0x5a);
sisfb_post_xgi_delay(ivideo, 1);
sr14 = 0x0a;
if(sisfb_post_xgi_rwtest(ivideo, 24, 25, mapsize))
goto bail_out;
SiS_SetReg(SISSR, 0x13, 0x21);
SiS_SetReg(SISSR, 0x14, 0x4a);
}
sisfb_post_xgi_delay(ivideo, 1);
}
}
bail_out:
SiS_SetRegANDOR(SISSR, 0x14, 0xf0, sr14);
sisfb_post_xgi_delay(ivideo, 1);
j = (ivideo->chip == XGI_20) ? 5 : 9;
k = (ivideo->chip == XGI_20) ? 12 : 4;
status = -EIO;
for(i = 0; i < k; i++) {
reg = (ivideo->chip == XGI_20) ?
dramsr13[(i * 5) + 4] : dramsr13_4[(i * 5) + 4];
SiS_SetRegANDOR(SISSR, 0x13, 0x80, reg);
sisfb_post_xgi_delay(ivideo, 50);
ranksize = (ivideo->chip == XGI_20) ?
dramsr13[(i * 5) + 3] : dramsr13_4[(i * 5) + 3];
reg = SiS_GetReg(SISSR, 0x13);
if(reg & 0x80) ranksize <<= 1;
if(ivideo->chip == XGI_20) {
if(buswidth == 16) ranksize <<= 1;
else if(buswidth == 32) ranksize <<= 2;
} else {
if(buswidth == 64) ranksize <<= 1;
}
reg = 0;
l = channelab;
if(l == 3) l = 4;
if((ranksize * l) <= 256) {
while((ranksize >>= 1)) reg += 0x10;
}
if(!reg) continue;
SiS_SetRegANDOR(SISSR, 0x14, 0x0f, (reg & 0xf0));
sisfb_post_xgi_delay(ivideo, 1);
if (sisfb_post_xgi_rwtest(ivideo, j, ((reg >> 4) + channelab - 2 + 20), mapsize)) {
status = 0;
break;
}
}
iounmap(ivideo->video_vbase);
return status;
}
static void __devinit
sisfb_post_xgi_setclocks(struct sis_video_info *ivideo, u8 regb)
{
u8 v1, v2, v3;
int index;
static const u8 cs90[8 * 3] = {
0x16, 0x01, 0x01,
0x3e, 0x03, 0x01,
0x7c, 0x08, 0x01,
0x79, 0x06, 0x01,
0x29, 0x01, 0x81,
0x5c, 0x23, 0x01,
0x5c, 0x23, 0x01,
0x5c, 0x23, 0x01
};
static const u8 csb8[8 * 3] = {
0x5c, 0x23, 0x01,
0x29, 0x01, 0x01,
0x7c, 0x08, 0x01,
0x79, 0x06, 0x01,
0x29, 0x01, 0x81,
0x5c, 0x23, 0x01,
0x5c, 0x23, 0x01,
0x5c, 0x23, 0x01
};
regb = 0; /* ! */
index = regb * 3;
v1 = cs90[index]; v2 = cs90[index + 1]; v3 = cs90[index + 2];
if(ivideo->haveXGIROM) {
v1 = ivideo->bios_abase[0x90 + index];
v2 = ivideo->bios_abase[0x90 + index + 1];
v3 = ivideo->bios_abase[0x90 + index + 2];
}
SiS_SetReg(SISSR, 0x28, v1);
SiS_SetReg(SISSR, 0x29, v2);
SiS_SetReg(SISSR, 0x2a, v3);
sisfb_post_xgi_delay(ivideo, 0x43);
sisfb_post_xgi_delay(ivideo, 0x43);
sisfb_post_xgi_delay(ivideo, 0x43);
index = regb * 3;
v1 = csb8[index]; v2 = csb8[index + 1]; v3 = csb8[index + 2];
if(ivideo->haveXGIROM) {
v1 = ivideo->bios_abase[0xb8 + index];
v2 = ivideo->bios_abase[0xb8 + index + 1];
v3 = ivideo->bios_abase[0xb8 + index + 2];
}
SiS_SetReg(SISSR, 0x2e, v1);
SiS_SetReg(SISSR, 0x2f, v2);
SiS_SetReg(SISSR, 0x30, v3);
sisfb_post_xgi_delay(ivideo, 0x43);
sisfb_post_xgi_delay(ivideo, 0x43);
sisfb_post_xgi_delay(ivideo, 0x43);
}
static void __devinit
sisfb_post_xgi_ddr2_mrs_default(struct sis_video_info *ivideo, u8 regb)
{
unsigned char *bios = ivideo->bios_abase;
u8 v1;
SiS_SetReg(SISSR, 0x28, 0x64);
SiS_SetReg(SISSR, 0x29, 0x63);
sisfb_post_xgi_delay(ivideo, 15);
SiS_SetReg(SISSR, 0x18, 0x00);
SiS_SetReg(SISSR, 0x19, 0x20);
SiS_SetReg(SISSR, 0x16, 0x00);
SiS_SetReg(SISSR, 0x16, 0x80);
SiS_SetReg(SISSR, 0x18, 0xc5);
SiS_SetReg(SISSR, 0x19, 0x23);
SiS_SetReg(SISSR, 0x16, 0x00);
SiS_SetReg(SISSR, 0x16, 0x80);
sisfb_post_xgi_delay(ivideo, 1);
SiS_SetReg(SISCR, 0x97, 0x11);
sisfb_post_xgi_setclocks(ivideo, regb);
sisfb_post_xgi_delay(ivideo, 0x46);
SiS_SetReg(SISSR, 0x18, 0xc5);
SiS_SetReg(SISSR, 0x19, 0x23);
SiS_SetReg(SISSR, 0x16, 0x00);
SiS_SetReg(SISSR, 0x16, 0x80);
sisfb_post_xgi_delay(ivideo, 1);
SiS_SetReg(SISSR, 0x1b, 0x04);
sisfb_post_xgi_delay(ivideo, 1);
SiS_SetReg(SISSR, 0x1b, 0x00);
sisfb_post_xgi_delay(ivideo, 1);
v1 = 0x31;
if (ivideo->haveXGIROM) {
v1 = bios[0xf0];
}
SiS_SetReg(SISSR, 0x18, v1);
SiS_SetReg(SISSR, 0x19, 0x06);
SiS_SetReg(SISSR, 0x16, 0x04);
SiS_SetReg(SISSR, 0x16, 0x84);
sisfb_post_xgi_delay(ivideo, 1);
}
static void __devinit
sisfb_post_xgi_ddr2_mrs_xg21(struct sis_video_info *ivideo)
{
sisfb_post_xgi_setclocks(ivideo, 1);
SiS_SetReg(SISCR, 0x97, 0x11);
sisfb_post_xgi_delay(ivideo, 0x46);
SiS_SetReg(SISSR, 0x18, 0x00); /* EMRS2 */
SiS_SetReg(SISSR, 0x19, 0x80);
SiS_SetReg(SISSR, 0x16, 0x05);
SiS_SetReg(SISSR, 0x16, 0x85);
SiS_SetReg(SISSR, 0x18, 0x00); /* EMRS3 */
SiS_SetReg(SISSR, 0x19, 0xc0);
SiS_SetReg(SISSR, 0x16, 0x05);
SiS_SetReg(SISSR, 0x16, 0x85);
SiS_SetReg(SISSR, 0x18, 0x00); /* EMRS1 */
SiS_SetReg(SISSR, 0x19, 0x40);
SiS_SetReg(SISSR, 0x16, 0x05);
SiS_SetReg(SISSR, 0x16, 0x85);
SiS_SetReg(SISSR, 0x18, 0x42); /* MRS1 */
SiS_SetReg(SISSR, 0x19, 0x02);
SiS_SetReg(SISSR, 0x16, 0x05);
SiS_SetReg(SISSR, 0x16, 0x85);
sisfb_post_xgi_delay(ivideo, 1);
SiS_SetReg(SISSR, 0x1b, 0x04);
sisfb_post_xgi_delay(ivideo, 1);
SiS_SetReg(SISSR, 0x1b, 0x00);
sisfb_post_xgi_delay(ivideo, 1);
SiS_SetReg(SISSR, 0x18, 0x42); /* MRS1 */
SiS_SetReg(SISSR, 0x19, 0x00);
SiS_SetReg(SISSR, 0x16, 0x05);
SiS_SetReg(SISSR, 0x16, 0x85);
sisfb_post_xgi_delay(ivideo, 1);
}
static void __devinit
sisfb_post_xgi_ddr2(struct sis_video_info *ivideo, u8 regb)
{
unsigned char *bios = ivideo->bios_abase;
static const u8 cs158[8] = {
0x88, 0xaa, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs160[8] = {
0x44, 0x77, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs168[8] = {
0x48, 0x78, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00
};
u8 reg;
u8 v1;
u8 v2;
u8 v3;
SiS_SetReg(SISCR, 0xb0, 0x80); /* DDR2 dual frequency mode */
SiS_SetReg(SISCR, 0x82, 0x77);
SiS_SetReg(SISCR, 0x86, 0x00);
reg = SiS_GetReg(SISCR, 0x86);
SiS_SetReg(SISCR, 0x86, 0x88);
reg = SiS_GetReg(SISCR, 0x86);
v1 = cs168[regb]; v2 = cs160[regb]; v3 = cs158[regb];
if (ivideo->haveXGIROM) {
v1 = bios[regb + 0x168];
v2 = bios[regb + 0x160];
v3 = bios[regb + 0x158];
}
SiS_SetReg(SISCR, 0x86, v1);
SiS_SetReg(SISCR, 0x82, 0x77);
SiS_SetReg(SISCR, 0x85, 0x00);
reg = SiS_GetReg(SISCR, 0x85);
SiS_SetReg(SISCR, 0x85, 0x88);
reg = SiS_GetReg(SISCR, 0x85);
SiS_SetReg(SISCR, 0x85, v2);
SiS_SetReg(SISCR, 0x82, v3);
SiS_SetReg(SISCR, 0x98, 0x01);
SiS_SetReg(SISCR, 0x9a, 0x02);
if (sisfb_xgi_is21(ivideo))
sisfb_post_xgi_ddr2_mrs_xg21(ivideo);
else
sisfb_post_xgi_ddr2_mrs_default(ivideo, regb);
}
static u8 __devinit
sisfb_post_xgi_ramtype(struct sis_video_info *ivideo)
{
unsigned char *bios = ivideo->bios_abase;
u8 ramtype;
u8 reg;
u8 v1;
ramtype = 0x00; v1 = 0x10;
if (ivideo->haveXGIROM) {
ramtype = bios[0x62];
v1 = bios[0x1d2];
}
if (!(ramtype & 0x80)) {
if (sisfb_xgi_is21(ivideo)) {
SiS_SetRegAND(SISCR, 0xb4, 0xfd); /* GPIO control */
SiS_SetRegOR(SISCR, 0x4a, 0x80); /* GPIOH EN */
reg = SiS_GetReg(SISCR, 0x48);
SiS_SetRegOR(SISCR, 0xb4, 0x02);
ramtype = reg & 0x01; /* GPIOH */
} else if (ivideo->chip == XGI_20) {
SiS_SetReg(SISCR, 0x97, v1);
reg = SiS_GetReg(SISCR, 0x97);
if (reg & 0x10) {
ramtype = (reg & 0x01) << 1;
}
} else {
reg = SiS_GetReg(SISSR, 0x39);
ramtype = reg & 0x02;
if (!(ramtype)) {
reg = SiS_GetReg(SISSR, 0x3a);
ramtype = (reg >> 1) & 0x01;
}
}
}
ramtype &= 0x07;
return ramtype;
}
static int __devinit
sisfb_post_xgi(struct pci_dev *pdev)
{
struct sis_video_info *ivideo = pci_get_drvdata(pdev);
unsigned char *bios = ivideo->bios_abase;
struct pci_dev *mypdev = NULL;
const u8 *ptr, *ptr2;
u8 v1, v2, v3, v4, v5, reg, ramtype;
u32 rega, regb, regd;
int i, j, k, index;
static const u8 cs78[3] = { 0xf6, 0x0d, 0x00 };
static const u8 cs76[2] = { 0xa3, 0xfb };
static const u8 cs7b[3] = { 0xc0, 0x11, 0x00 };
static const u8 cs158[8] = {
0x88, 0xaa, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs160[8] = {
0x44, 0x77, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs168[8] = {
0x48, 0x78, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs128[3 * 8] = {
0x90, 0x28, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00,
0x77, 0x44, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00,
0x77, 0x44, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs148[2 * 8] = {
0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs31a[8 * 4] = {
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs33a[8 * 4] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs45a[8 * 2] = {
0x00, 0x00, 0xa0, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs170[7 * 8] = {
0x54, 0x32, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00,
0x54, 0x43, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0a, 0x05, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x34, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00,
0x10, 0x0a, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00,
0x11, 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs1a8[3 * 8] = {
0xf0, 0xf0, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const u8 cs100[2 * 8] = {
0xc4, 0x04, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
0xc4, 0x04, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00
};
/* VGA enable */
reg = SiS_GetRegByte(SISVGAENABLE) | 0x01;
SiS_SetRegByte(SISVGAENABLE, reg);
/* Misc */
reg = SiS_GetRegByte(SISMISCR) | 0x01;
SiS_SetRegByte(SISMISCW, reg);
/* Unlock SR */
SiS_SetReg(SISSR, 0x05, 0x86);
reg = SiS_GetReg(SISSR, 0x05);
if(reg != 0xa1)
return 0;
/* Clear some regs */
for(i = 0; i < 0x22; i++) {
if(0x06 + i == 0x20) continue;
SiS_SetReg(SISSR, 0x06 + i, 0x00);
}
for(i = 0; i < 0x0b; i++) {
SiS_SetReg(SISSR, 0x31 + i, 0x00);
}
for(i = 0; i < 0x10; i++) {
SiS_SetReg(SISCR, 0x30 + i, 0x00);
}
ptr = cs78;
if(ivideo->haveXGIROM) {
ptr = (const u8 *)&bios[0x78];
}
for(i = 0; i < 3; i++) {
SiS_SetReg(SISSR, 0x23 + i, ptr[i]);
}
ptr = cs76;
if(ivideo->haveXGIROM) {
ptr = (const u8 *)&bios[0x76];
}
for(i = 0; i < 2; i++) {
SiS_SetReg(SISSR, 0x21 + i, ptr[i]);
}
v1 = 0x18; v2 = 0x00;
if(ivideo->haveXGIROM) {
v1 = bios[0x74];
v2 = bios[0x75];
}
SiS_SetReg(SISSR, 0x07, v1);
SiS_SetReg(SISSR, 0x11, 0x0f);
SiS_SetReg(SISSR, 0x1f, v2);
/* PCI linear mode, RelIO enabled, A0000 decoding disabled */
SiS_SetReg(SISSR, 0x20, 0x80 | 0x20 | 0x04);
SiS_SetReg(SISSR, 0x27, 0x74);
ptr = cs7b;
if(ivideo->haveXGIROM) {
ptr = (const u8 *)&bios[0x7b];
}
for(i = 0; i < 3; i++) {
SiS_SetReg(SISSR, 0x31 + i, ptr[i]);
}
if(ivideo->chip == XGI_40) {
if(ivideo->revision_id == 2) {
SiS_SetRegANDOR(SISSR, 0x3b, 0x3f, 0xc0);
}
SiS_SetReg(SISCR, 0x7d, 0xfe);
SiS_SetReg(SISCR, 0x7e, 0x0f);
}
if(ivideo->revision_id == 0) { /* 40 *and* 20? */
SiS_SetRegAND(SISCR, 0x58, 0xd7);
reg = SiS_GetReg(SISCR, 0xcb);
if(reg & 0x20) {
SiS_SetRegANDOR(SISCR, 0x58, 0xd7, (reg & 0x10) ? 0x08 : 0x20); /* =0x28 Z7 ? */
}
}
reg = (ivideo->chip == XGI_40) ? 0x20 : 0x00;
SiS_SetRegANDOR(SISCR, 0x38, 0x1f, reg);
if(ivideo->chip == XGI_20) {
SiS_SetReg(SISSR, 0x36, 0x70);
} else {
SiS_SetReg(SISVID, 0x00, 0x86);
SiS_SetReg(SISVID, 0x32, 0x00);
SiS_SetReg(SISVID, 0x30, 0x00);
SiS_SetReg(SISVID, 0x32, 0x01);
SiS_SetReg(SISVID, 0x30, 0x00);
SiS_SetRegAND(SISVID, 0x2f, 0xdf);
SiS_SetRegAND(SISCAP, 0x00, 0x3f);
SiS_SetReg(SISPART1, 0x2f, 0x01);
SiS_SetReg(SISPART1, 0x00, 0x00);
SiS_SetReg(SISPART1, 0x02, bios[0x7e]);
SiS_SetReg(SISPART1, 0x2e, 0x08);
SiS_SetRegAND(SISPART1, 0x35, 0x7f);
SiS_SetRegAND(SISPART1, 0x50, 0xfe);
reg = SiS_GetReg(SISPART4, 0x00);
if(reg == 1 || reg == 2) {
SiS_SetReg(SISPART2, 0x00, 0x1c);
SiS_SetReg(SISPART4, 0x0d, bios[0x7f]);
SiS_SetReg(SISPART4, 0x0e, bios[0x80]);
SiS_SetReg(SISPART4, 0x10, bios[0x81]);
SiS_SetRegAND(SISPART4, 0x0f, 0x3f);
reg = SiS_GetReg(SISPART4, 0x01);
if((reg & 0xf0) >= 0xb0) {
reg = SiS_GetReg(SISPART4, 0x23);
if(reg & 0x20) reg |= 0x40;
SiS_SetReg(SISPART4, 0x23, reg);
reg = (reg & 0x20) ? 0x02 : 0x00;
SiS_SetRegANDOR(SISPART1, 0x1e, 0xfd, reg);
}
}
v1 = bios[0x77];
reg = SiS_GetReg(SISSR, 0x3b);
if(reg & 0x02) {
reg = SiS_GetReg(SISSR, 0x3a);
v2 = (reg & 0x30) >> 3;
if(!(v2 & 0x04)) v2 ^= 0x02;
reg = SiS_GetReg(SISSR, 0x39);
if(reg & 0x80) v2 |= 0x80;
v2 |= 0x01;
if((mypdev = pci_get_device(PCI_VENDOR_ID_SI, 0x0730, NULL))) {
pci_dev_put(mypdev);
if(((v2 & 0x06) == 2) || ((v2 & 0x06) == 4))
v2 &= 0xf9;
v2 |= 0x08;
v1 &= 0xfe;
} else {
mypdev = pci_get_device(PCI_VENDOR_ID_SI, 0x0735, NULL);
if(!mypdev)
mypdev = pci_get_device(PCI_VENDOR_ID_SI, 0x0645, NULL);
if(!mypdev)
mypdev = pci_get_device(PCI_VENDOR_ID_SI, 0x0650, NULL);
if(mypdev) {
pci_read_config_dword(mypdev, 0x94, ®d);
regd &= 0xfffffeff;
pci_write_config_dword(mypdev, 0x94, regd);
v1 &= 0xfe;
pci_dev_put(mypdev);
} else if(sisfb_find_host_bridge(ivideo, pdev, PCI_VENDOR_ID_SI)) {
v1 &= 0xfe;
} else if(sisfb_find_host_bridge(ivideo, pdev, 0x1106) ||
sisfb_find_host_bridge(ivideo, pdev, 0x1022) ||
sisfb_find_host_bridge(ivideo, pdev, 0x700e) ||
sisfb_find_host_bridge(ivideo, pdev, 0x10de)) {
if((v2 & 0x06) == 4)
v2 ^= 0x06;
v2 |= 0x08;
}
}
SiS_SetRegANDOR(SISCR, 0x5f, 0xf0, v2);
}
SiS_SetReg(SISSR, 0x22, v1);
if(ivideo->revision_id == 2) {
v1 = SiS_GetReg(SISSR, 0x3b);
v2 = SiS_GetReg(SISSR, 0x3a);
regd = bios[0x90 + 3] | (bios[0x90 + 4] << 8);
if( (!(v1 & 0x02)) && (v2 & 0x30) && (regd < 0xcf) )
SiS_SetRegANDOR(SISCR, 0x5f, 0xf1, 0x01);
if((mypdev = pci_get_device(0x10de, 0x01e0, NULL))) {
/* TODO: set CR5f &0xf1 | 0x01 for version 6570
* of nforce 2 ROM
*/
if(0)
SiS_SetRegANDOR(SISCR, 0x5f, 0xf1, 0x01);
pci_dev_put(mypdev);
}
}
v1 = 0x30;
reg = SiS_GetReg(SISSR, 0x3b);
v2 = SiS_GetReg(SISCR, 0x5f);
if((!(reg & 0x02)) && (v2 & 0x0e))
v1 |= 0x08;
SiS_SetReg(SISSR, 0x27, v1);
if(bios[0x64] & 0x01) {
SiS_SetRegANDOR(SISCR, 0x5f, 0xf0, bios[0x64]);
}
v1 = bios[0x4f7];
pci_read_config_dword(pdev, 0x50, ®d);
regd = (regd >> 20) & 0x0f;
if(regd == 1) {
v1 &= 0xfc;
SiS_SetRegOR(SISCR, 0x5f, 0x08);
}
SiS_SetReg(SISCR, 0x48, v1);
SiS_SetRegANDOR(SISCR, 0x47, 0x04, bios[0x4f6] & 0xfb);
SiS_SetRegANDOR(SISCR, 0x49, 0xf0, bios[0x4f8] & 0x0f);
SiS_SetRegANDOR(SISCR, 0x4a, 0x60, bios[0x4f9] & 0x9f);
SiS_SetRegANDOR(SISCR, 0x4b, 0x08, bios[0x4fa] & 0xf7);
SiS_SetRegANDOR(SISCR, 0x4c, 0x80, bios[0x4fb] & 0x7f);
SiS_SetReg(SISCR, 0x70, bios[0x4fc]);
SiS_SetRegANDOR(SISCR, 0x71, 0xf0, bios[0x4fd] & 0x0f);
SiS_SetReg(SISCR, 0x74, 0xd0);
SiS_SetRegANDOR(SISCR, 0x74, 0xcf, bios[0x4fe] & 0x30);
SiS_SetRegANDOR(SISCR, 0x75, 0xe0, bios[0x4ff] & 0x1f);
SiS_SetRegANDOR(SISCR, 0x76, 0xe0, bios[0x500] & 0x1f);
v1 = bios[0x501];
if((mypdev = pci_get_device(0x8086, 0x2530, NULL))) {
v1 = 0xf0;
pci_dev_put(mypdev);
}
SiS_SetReg(SISCR, 0x77, v1);
}
/* RAM type:
*
* 0 == DDR1, 1 == DDR2, 2..7 == reserved?
*
* The code seems to written so that regb should equal ramtype,
* however, so far it has been hardcoded to 0. Enable other values only
* on XGI Z9, as it passes the POST, and add a warning for others.
*/
ramtype = sisfb_post_xgi_ramtype(ivideo);
if (!sisfb_xgi_is21(ivideo) && ramtype) {
dev_warn(&pdev->dev,
"RAM type something else than expected: %d\n",
ramtype);
regb = 0;
} else {
regb = ramtype;
}
v1 = 0xff;
if(ivideo->haveXGIROM) {
v1 = bios[0x140 + regb];
}
SiS_SetReg(SISCR, 0x6d, v1);
ptr = cs128;
if(ivideo->haveXGIROM) {
ptr = (const u8 *)&bios[0x128];
}
for(i = 0, j = 0; i < 3; i++, j += 8) {
SiS_SetReg(SISCR, 0x68 + i, ptr[j + regb]);
}
ptr = cs31a;
ptr2 = cs33a;
if(ivideo->haveXGIROM) {
index = (ivideo->chip == XGI_20) ? 0x31a : 0x3a6;
ptr = (const u8 *)&bios[index];
ptr2 = (const u8 *)&bios[index + 0x20];
}
for(i = 0; i < 2; i++) {
if(i == 0) {
regd = le32_to_cpu(((u32 *)ptr)[regb]);
rega = 0x6b;
} else {
regd = le32_to_cpu(((u32 *)ptr2)[regb]);
rega = 0x6e;
}
reg = 0x00;
for(j = 0; j < 16; j++) {
reg &= 0xf3;
if(regd & 0x01) reg |= 0x04;
if(regd & 0x02) reg |= 0x08;
regd >>= 2;
SiS_SetReg(SISCR, rega, reg);
reg = SiS_GetReg(SISCR, rega);
reg = SiS_GetReg(SISCR, rega);
reg += 0x10;
}
}
SiS_SetRegAND(SISCR, 0x6e, 0xfc);
ptr = NULL;
if(ivideo->haveXGIROM) {
index = (ivideo->chip == XGI_20) ? 0x35a : 0x3e6;
ptr = (const u8 *)&bios[index];
}
for(i = 0; i < 4; i++) {
SiS_SetRegANDOR(SISCR, 0x6e, 0xfc, i);
reg = 0x00;
for(j = 0; j < 2; j++) {
regd = 0;
if(ptr) {
regd = le32_to_cpu(((u32 *)ptr)[regb * 8]);
ptr += 4;
}
/* reg = 0x00; */
for(k = 0; k < 16; k++) {
reg &= 0xfc;
if(regd & 0x01) reg |= 0x01;
if(regd & 0x02) reg |= 0x02;
regd >>= 2;
SiS_SetReg(SISCR, 0x6f, reg);
reg = SiS_GetReg(SISCR, 0x6f);
reg = SiS_GetReg(SISCR, 0x6f);
reg += 0x08;
}
}
}
ptr = cs148;
if(ivideo->haveXGIROM) {
ptr = (const u8 *)&bios[0x148];
}
for(i = 0, j = 0; i < 2; i++, j += 8) {
SiS_SetReg(SISCR, 0x80 + i, ptr[j + regb]);
}
SiS_SetRegAND(SISCR, 0x89, 0x8f);
ptr = cs45a;
if(ivideo->haveXGIROM) {
index = (ivideo->chip == XGI_20) ? 0x45a : 0x4e6;
ptr = (const u8 *)&bios[index];
}
regd = le16_to_cpu(((const u16 *)ptr)[regb]);
reg = 0x80;
for(i = 0; i < 5; i++) {
reg &= 0xfc;
if(regd & 0x01) reg |= 0x01;
if(regd & 0x02) reg |= 0x02;
regd >>= 2;
SiS_SetReg(SISCR, 0x89, reg);
reg = SiS_GetReg(SISCR, 0x89);
reg = SiS_GetReg(SISCR, 0x89);
reg += 0x10;
}
v1 = 0xb5; v2 = 0x20; v3 = 0xf0; v4 = 0x13;
if(ivideo->haveXGIROM) {
v1 = bios[0x118 + regb];
v2 = bios[0xf8 + regb];
v3 = bios[0x120 + regb];
v4 = bios[0x1ca];
}
SiS_SetReg(SISCR, 0x45, v1 & 0x0f);
SiS_SetReg(SISCR, 0x99, (v1 >> 4) & 0x07);
SiS_SetRegOR(SISCR, 0x40, v1 & 0x80);
SiS_SetReg(SISCR, 0x41, v2);
ptr = cs170;
if(ivideo->haveXGIROM) {
ptr = (const u8 *)&bios[0x170];
}
for(i = 0, j = 0; i < 7; i++, j += 8) {
SiS_SetReg(SISCR, 0x90 + i, ptr[j + regb]);
}
SiS_SetReg(SISCR, 0x59, v3);
ptr = cs1a8;
if(ivideo->haveXGIROM) {
ptr = (const u8 *)&bios[0x1a8];
}
for(i = 0, j = 0; i < 3; i++, j += 8) {
SiS_SetReg(SISCR, 0xc3 + i, ptr[j + regb]);
}
ptr = cs100;
if(ivideo->haveXGIROM) {
ptr = (const u8 *)&bios[0x100];
}
for(i = 0, j = 0; i < 2; i++, j += 8) {
SiS_SetReg(SISCR, 0x8a + i, ptr[j + regb]);
}
SiS_SetReg(SISCR, 0xcf, v4);
SiS_SetReg(SISCR, 0x83, 0x09);
SiS_SetReg(SISCR, 0x87, 0x00);
if(ivideo->chip == XGI_40) {
if( (ivideo->revision_id == 1) ||
(ivideo->revision_id == 2) ) {
SiS_SetReg(SISCR, 0x8c, 0x87);
}
}
if (regb == 1)
SiS_SetReg(SISSR, 0x17, 0x80); /* DDR2 */
else
SiS_SetReg(SISSR, 0x17, 0x00); /* DDR1 */
SiS_SetReg(SISSR, 0x1a, 0x87);
if(ivideo->chip == XGI_20) {
SiS_SetReg(SISSR, 0x15, 0x00);
SiS_SetReg(SISSR, 0x1c, 0x00);
}
switch(ramtype) {
case 0:
sisfb_post_xgi_setclocks(ivideo, regb);
if((ivideo->chip == XGI_20) ||
(ivideo->revision_id == 1) ||
(ivideo->revision_id == 2)) {
v1 = cs158[regb]; v2 = cs160[regb]; v3 = cs168[regb];
if(ivideo->haveXGIROM) {
v1 = bios[regb + 0x158];
v2 = bios[regb + 0x160];
v3 = bios[regb + 0x168];
}
SiS_SetReg(SISCR, 0x82, v1);
SiS_SetReg(SISCR, 0x85, v2);
SiS_SetReg(SISCR, 0x86, v3);
} else {
SiS_SetReg(SISCR, 0x82, 0x88);
SiS_SetReg(SISCR, 0x86, 0x00);
reg = SiS_GetReg(SISCR, 0x86);
SiS_SetReg(SISCR, 0x86, 0x88);
reg = SiS_GetReg(SISCR, 0x86);
SiS_SetReg(SISCR, 0x86, bios[regb + 0x168]);
SiS_SetReg(SISCR, 0x82, 0x77);
SiS_SetReg(SISCR, 0x85, 0x00);
reg = SiS_GetReg(SISCR, 0x85);
SiS_SetReg(SISCR, 0x85, 0x88);
reg = SiS_GetReg(SISCR, 0x85);
SiS_SetReg(SISCR, 0x85, bios[regb + 0x160]);
SiS_SetReg(SISCR, 0x82, bios[regb + 0x158]);
}
if(ivideo->chip == XGI_40) {
SiS_SetReg(SISCR, 0x97, 0x00);
}
SiS_SetReg(SISCR, 0x98, 0x01);
SiS_SetReg(SISCR, 0x9a, 0x02);
SiS_SetReg(SISSR, 0x18, 0x01);
if((ivideo->chip == XGI_20) ||
(ivideo->revision_id == 2)) {
SiS_SetReg(SISSR, 0x19, 0x40);
} else {
SiS_SetReg(SISSR, 0x19, 0x20);
}
SiS_SetReg(SISSR, 0x16, 0x00);
SiS_SetReg(SISSR, 0x16, 0x80);
if((ivideo->chip == XGI_20) || (bios[0x1cb] != 0x0c)) {
sisfb_post_xgi_delay(ivideo, 0x43);
sisfb_post_xgi_delay(ivideo, 0x43);
sisfb_post_xgi_delay(ivideo, 0x43);
SiS_SetReg(SISSR, 0x18, 0x00);
if((ivideo->chip == XGI_20) ||
(ivideo->revision_id == 2)) {
SiS_SetReg(SISSR, 0x19, 0x40);
} else {
SiS_SetReg(SISSR, 0x19, 0x20);
}
} else if((ivideo->chip == XGI_40) && (bios[0x1cb] == 0x0c)) {
/* SiS_SetReg(SISSR, 0x16, 0x0c); */ /* ? */
}
SiS_SetReg(SISSR, 0x16, 0x00);
SiS_SetReg(SISSR, 0x16, 0x80);
sisfb_post_xgi_delay(ivideo, 4);
v1 = 0x31; v2 = 0x03; v3 = 0x83; v4 = 0x03; v5 = 0x83;
if(ivideo->haveXGIROM) {
v1 = bios[0xf0];
index = (ivideo->chip == XGI_20) ? 0x4b2 : 0x53e;
v2 = bios[index];
v3 = bios[index + 1];
v4 = bios[index + 2];
v5 = bios[index + 3];
}
SiS_SetReg(SISSR, 0x18, v1);
SiS_SetReg(SISSR, 0x19, ((ivideo->chip == XGI_20) ? 0x02 : 0x01));
SiS_SetReg(SISSR, 0x16, v2);
SiS_SetReg(SISSR, 0x16, v3);
sisfb_post_xgi_delay(ivideo, 0x43);
SiS_SetReg(SISSR, 0x1b, 0x03);
sisfb_post_xgi_delay(ivideo, 0x22);
SiS_SetReg(SISSR, 0x18, v1);
SiS_SetReg(SISSR, 0x19, 0x00);
SiS_SetReg(SISSR, 0x16, v4);
SiS_SetReg(SISSR, 0x16, v5);
SiS_SetReg(SISSR, 0x1b, 0x00);
break;
case 1:
sisfb_post_xgi_ddr2(ivideo, regb);
break;
default:
sisfb_post_xgi_setclocks(ivideo, regb);
if((ivideo->chip == XGI_40) &&
((ivideo->revision_id == 1) ||
(ivideo->revision_id == 2))) {
SiS_SetReg(SISCR, 0x82, bios[regb + 0x158]);
SiS_SetReg(SISCR, 0x85, bios[regb + 0x160]);
SiS_SetReg(SISCR, 0x86, bios[regb + 0x168]);
} else {
SiS_SetReg(SISCR, 0x82, 0x88);
SiS_SetReg(SISCR, 0x86, 0x00);
reg = SiS_GetReg(SISCR, 0x86);
SiS_SetReg(SISCR, 0x86, 0x88);
SiS_SetReg(SISCR, 0x82, 0x77);
SiS_SetReg(SISCR, 0x85, 0x00);
reg = SiS_GetReg(SISCR, 0x85);
SiS_SetReg(SISCR, 0x85, 0x88);
reg = SiS_GetReg(SISCR, 0x85);
v1 = cs160[regb]; v2 = cs158[regb];
if(ivideo->haveXGIROM) {
v1 = bios[regb + 0x160];
v2 = bios[regb + 0x158];
}
SiS_SetReg(SISCR, 0x85, v1);
SiS_SetReg(SISCR, 0x82, v2);
}
if(ivideo->chip == XGI_40) {
SiS_SetReg(SISCR, 0x97, 0x11);
}
if((ivideo->chip == XGI_40) && (ivideo->revision_id == 2)) {
SiS_SetReg(SISCR, 0x98, 0x01);
} else {
SiS_SetReg(SISCR, 0x98, 0x03);
}
SiS_SetReg(SISCR, 0x9a, 0x02);
if(ivideo->chip == XGI_40) {
SiS_SetReg(SISSR, 0x18, 0x01);
} else {
SiS_SetReg(SISSR, 0x18, 0x00);
}
SiS_SetReg(SISSR, 0x19, 0x40);
SiS_SetReg(SISSR, 0x16, 0x00);
SiS_SetReg(SISSR, 0x16, 0x80);
if((ivideo->chip == XGI_40) && (bios[0x1cb] != 0x0c)) {
sisfb_post_xgi_delay(ivideo, 0x43);
sisfb_post_xgi_delay(ivideo, 0x43);
sisfb_post_xgi_delay(ivideo, 0x43);
SiS_SetReg(SISSR, 0x18, 0x00);
SiS_SetReg(SISSR, 0x19, 0x40);
SiS_SetReg(SISSR, 0x16, 0x00);
SiS_SetReg(SISSR, 0x16, 0x80);
}
sisfb_post_xgi_delay(ivideo, 4);
v1 = 0x31;
if(ivideo->haveXGIROM) {
v1 = bios[0xf0];
}
SiS_SetReg(SISSR, 0x18, v1);
SiS_SetReg(SISSR, 0x19, 0x01);
if(ivideo->chip == XGI_40) {
SiS_SetReg(SISSR, 0x16, bios[0x53e]);
SiS_SetReg(SISSR, 0x16, bios[0x53f]);
} else {
SiS_SetReg(SISSR, 0x16, 0x05);
SiS_SetReg(SISSR, 0x16, 0x85);
}
sisfb_post_xgi_delay(ivideo, 0x43);
if(ivideo->chip == XGI_40) {
SiS_SetReg(SISSR, 0x1b, 0x01);
} else {
SiS_SetReg(SISSR, 0x1b, 0x03);
}
sisfb_post_xgi_delay(ivideo, 0x22);
SiS_SetReg(SISSR, 0x18, v1);
SiS_SetReg(SISSR, 0x19, 0x00);
if(ivideo->chip == XGI_40) {
SiS_SetReg(SISSR, 0x16, bios[0x540]);
SiS_SetReg(SISSR, 0x16, bios[0x541]);
} else {
SiS_SetReg(SISSR, 0x16, 0x05);
SiS_SetReg(SISSR, 0x16, 0x85);
}
SiS_SetReg(SISSR, 0x1b, 0x00);
}
regb = 0; /* ! */
v1 = 0x03;
if(ivideo->haveXGIROM) {
v1 = bios[0x110 + regb];
}
SiS_SetReg(SISSR, 0x1b, v1);
/* RAM size */
v1 = 0x00; v2 = 0x00;
if(ivideo->haveXGIROM) {
v1 = bios[0x62];
v2 = bios[0x63];
}
regb = 0; /* ! */
regd = 1 << regb;
if((v1 & 0x40) && (v2 & regd) && ivideo->haveXGIROM) {
SiS_SetReg(SISSR, 0x13, bios[regb + 0xe0]);
SiS_SetReg(SISSR, 0x14, bios[regb + 0xe0 + 8]);
} else {
int err;
/* Set default mode, don't clear screen */
ivideo->SiS_Pr.SiS_UseOEM = false;
SiS_SetEnableDstn(&ivideo->SiS_Pr, false);
SiS_SetEnableFstn(&ivideo->SiS_Pr, false);
ivideo->curFSTN = ivideo->curDSTN = 0;
ivideo->SiS_Pr.VideoMemorySize = 8 << 20;
SiSSetMode(&ivideo->SiS_Pr, 0x2e | 0x80);
SiS_SetReg(SISSR, 0x05, 0x86);
/* Disable read-cache */
SiS_SetRegAND(SISSR, 0x21, 0xdf);
err = sisfb_post_xgi_ramsize(ivideo);
/* Enable read-cache */
SiS_SetRegOR(SISSR, 0x21, 0x20);
if (err) {
dev_err(&pdev->dev,
"%s: RAM size detection failed: %d\n",
__func__, err);
return 0;
}
}
#if 0
printk(KERN_DEBUG "-----------------\n");
for(i = 0; i < 0xff; i++) {
reg = SiS_GetReg(SISCR, i);
printk(KERN_DEBUG "CR%02x(%x) = 0x%02x\n", i, SISCR, reg);
}
for(i = 0; i < 0x40; i++) {
reg = SiS_GetReg(SISSR, i);
printk(KERN_DEBUG "SR%02x(%x) = 0x%02x\n", i, SISSR, reg);
}
printk(KERN_DEBUG "-----------------\n");
#endif
/* Sense CRT1 */
if(ivideo->chip == XGI_20) {
SiS_SetRegOR(SISCR, 0x32, 0x20);
} else {
reg = SiS_GetReg(SISPART4, 0x00);
if((reg == 1) || (reg == 2)) {
sisfb_sense_crt1(ivideo);
} else {
SiS_SetRegOR(SISCR, 0x32, 0x20);
}
}
/* Set default mode, don't clear screen */
ivideo->SiS_Pr.SiS_UseOEM = false;
SiS_SetEnableDstn(&ivideo->SiS_Pr, false);
SiS_SetEnableFstn(&ivideo->SiS_Pr, false);
ivideo->curFSTN = ivideo->curDSTN = 0;
SiSSetMode(&ivideo->SiS_Pr, 0x2e | 0x80);
SiS_SetReg(SISSR, 0x05, 0x86);
/* Display off */
SiS_SetRegOR(SISSR, 0x01, 0x20);
/* Save mode number in CR34 */
SiS_SetReg(SISCR, 0x34, 0x2e);
/* Let everyone know what the current mode is */
ivideo->modeprechange = 0x2e;
if(ivideo->chip == XGI_40) {
reg = SiS_GetReg(SISCR, 0xca);
v1 = SiS_GetReg(SISCR, 0xcc);
if((reg & 0x10) && (!(v1 & 0x04))) {
printk(KERN_ERR
"sisfb: Please connect power to the card.\n");
return 0;
}
}
return 1;
}
#endif
static int __devinit
sisfb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct sisfb_chip_info *chipinfo = &sisfb_chip_info[ent->driver_data];
struct sis_video_info *ivideo = NULL;
struct fb_info *sis_fb_info = NULL;
u16 reg16;
u8 reg;
int i, ret;
if(sisfb_off)
return -ENXIO;
sis_fb_info = framebuffer_alloc(sizeof(*ivideo), &pdev->dev);
if(!sis_fb_info)
return -ENOMEM;
ivideo = (struct sis_video_info *)sis_fb_info->par;
ivideo->memyselfandi = sis_fb_info;
ivideo->sisfb_id = SISFB_ID;
if(card_list == NULL) {
ivideo->cardnumber = 0;
} else {
struct sis_video_info *countvideo = card_list;
ivideo->cardnumber = 1;
while((countvideo = countvideo->next) != NULL)
ivideo->cardnumber++;
}
strncpy(ivideo->myid, chipinfo->chip_name, 30);
ivideo->warncount = 0;
ivideo->chip_id = pdev->device;
ivideo->chip_vendor = pdev->vendor;
ivideo->revision_id = pdev->revision;
ivideo->SiS_Pr.ChipRevision = ivideo->revision_id;
pci_read_config_word(pdev, PCI_COMMAND, ®16);
ivideo->sisvga_enabled = reg16 & 0x01;
ivideo->pcibus = pdev->bus->number;
ivideo->pcislot = PCI_SLOT(pdev->devfn);
ivideo->pcifunc = PCI_FUNC(pdev->devfn);
ivideo->subsysvendor = pdev->subsystem_vendor;
ivideo->subsysdevice = pdev->subsystem_device;
#ifndef MODULE
if(sisfb_mode_idx == -1) {
sisfb_get_vga_mode_from_kernel();
}
#endif
ivideo->chip = chipinfo->chip;
ivideo->chip_real_id = chipinfo->chip;
ivideo->sisvga_engine = chipinfo->vgaengine;
ivideo->hwcursor_size = chipinfo->hwcursor_size;
ivideo->CRT2_write_enable = chipinfo->CRT2_write_enable;
ivideo->mni = chipinfo->mni;
ivideo->detectedpdc = 0xff;
ivideo->detectedpdca = 0xff;
ivideo->detectedlcda = 0xff;
ivideo->sisfb_thismonitor.datavalid = false;
ivideo->current_base = 0;
ivideo->engineok = 0;
ivideo->sisfb_was_boot_device = 0;
if(pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW) {
if(ivideo->sisvga_enabled)
ivideo->sisfb_was_boot_device = 1;
else {
printk(KERN_DEBUG "sisfb: PCI device is disabled, "
"but marked as boot video device ???\n");
printk(KERN_DEBUG "sisfb: I will not accept this "
"as the primary VGA device\n");
}
}
ivideo->sisfb_parm_mem = sisfb_parm_mem;
ivideo->sisfb_accel = sisfb_accel;
ivideo->sisfb_ypan = sisfb_ypan;
ivideo->sisfb_max = sisfb_max;
ivideo->sisfb_userom = sisfb_userom;
ivideo->sisfb_useoem = sisfb_useoem;
ivideo->sisfb_mode_idx = sisfb_mode_idx;
ivideo->sisfb_parm_rate = sisfb_parm_rate;
ivideo->sisfb_crt1off = sisfb_crt1off;
ivideo->sisfb_forcecrt1 = sisfb_forcecrt1;
ivideo->sisfb_crt2type = sisfb_crt2type;
ivideo->sisfb_crt2flags = sisfb_crt2flags;
/* pdc(a), scalelcd, special timing, lvdshl handled below */
ivideo->sisfb_dstn = sisfb_dstn;
ivideo->sisfb_fstn = sisfb_fstn;
ivideo->sisfb_tvplug = sisfb_tvplug;
ivideo->sisfb_tvstd = sisfb_tvstd;
ivideo->tvxpos = sisfb_tvxposoffset;
ivideo->tvypos = sisfb_tvyposoffset;
ivideo->sisfb_nocrt2rate = sisfb_nocrt2rate;
ivideo->refresh_rate = 0;
if(ivideo->sisfb_parm_rate != -1) {
ivideo->refresh_rate = ivideo->sisfb_parm_rate;
}
ivideo->SiS_Pr.UsePanelScaler = sisfb_scalelcd;
ivideo->SiS_Pr.CenterScreen = -1;
ivideo->SiS_Pr.SiS_CustomT = sisfb_specialtiming;
ivideo->SiS_Pr.LVDSHL = sisfb_lvdshl;
ivideo->SiS_Pr.SiS_Backup70xx = 0xff;
ivideo->SiS_Pr.SiS_CHOverScan = -1;
ivideo->SiS_Pr.SiS_ChSW = false;
ivideo->SiS_Pr.SiS_UseLCDA = false;
ivideo->SiS_Pr.HaveEMI = false;
ivideo->SiS_Pr.HaveEMILCD = false;
ivideo->SiS_Pr.OverruleEMI = false;
ivideo->SiS_Pr.SiS_SensibleSR11 = false;
ivideo->SiS_Pr.SiS_MyCR63 = 0x63;
ivideo->SiS_Pr.PDC = -1;
ivideo->SiS_Pr.PDCA = -1;
ivideo->SiS_Pr.DDCPortMixup = false;
#ifdef CONFIG_FB_SIS_315
if(ivideo->chip >= SIS_330) {
ivideo->SiS_Pr.SiS_MyCR63 = 0x53;
if(ivideo->chip >= SIS_661) {
ivideo->SiS_Pr.SiS_SensibleSR11 = true;
}
}
#endif
memcpy(&ivideo->default_var, &my_default_var, sizeof(my_default_var));
pci_set_drvdata(pdev, ivideo);
/* Patch special cases */
if((ivideo->nbridge = sisfb_get_northbridge(ivideo->chip))) {
switch(ivideo->nbridge->device) {
#ifdef CONFIG_FB_SIS_300
case PCI_DEVICE_ID_SI_730:
ivideo->chip = SIS_730;
strcpy(ivideo->myid, "SiS 730");
break;
#endif
#ifdef CONFIG_FB_SIS_315
case PCI_DEVICE_ID_SI_651:
/* ivideo->chip is ok */
strcpy(ivideo->myid, "SiS 651");
break;
case PCI_DEVICE_ID_SI_740:
ivideo->chip = SIS_740;
strcpy(ivideo->myid, "SiS 740");
break;
case PCI_DEVICE_ID_SI_661:
ivideo->chip = SIS_661;
strcpy(ivideo->myid, "SiS 661");
break;
case PCI_DEVICE_ID_SI_741:
ivideo->chip = SIS_741;
strcpy(ivideo->myid, "SiS 741");
break;
case PCI_DEVICE_ID_SI_760:
ivideo->chip = SIS_760;
strcpy(ivideo->myid, "SiS 760");
break;
case PCI_DEVICE_ID_SI_761:
ivideo->chip = SIS_761;
strcpy(ivideo->myid, "SiS 761");
break;
#endif
default:
break;
}
}
ivideo->SiS_Pr.ChipType = ivideo->chip;
ivideo->SiS_Pr.ivideo = (void *)ivideo;
#ifdef CONFIG_FB_SIS_315
if((ivideo->SiS_Pr.ChipType == SIS_315PRO) ||
(ivideo->SiS_Pr.ChipType == SIS_315)) {
ivideo->SiS_Pr.ChipType = SIS_315H;
}
#endif
if(!ivideo->sisvga_enabled) {
if(pci_enable_device(pdev)) {
if(ivideo->nbridge) pci_dev_put(ivideo->nbridge);
pci_set_drvdata(pdev, NULL);
framebuffer_release(sis_fb_info);
return -EIO;
}
}
ivideo->video_base = pci_resource_start(pdev, 0);
ivideo->video_size = pci_resource_len(pdev, 0);
ivideo->mmio_base = pci_resource_start(pdev, 1);
ivideo->mmio_size = pci_resource_len(pdev, 1);
ivideo->SiS_Pr.RelIO = pci_resource_start(pdev, 2) + 0x30;
ivideo->SiS_Pr.IOAddress = ivideo->vga_base = ivideo->SiS_Pr.RelIO;
SiSRegInit(&ivideo->SiS_Pr, ivideo->SiS_Pr.IOAddress);
#ifdef CONFIG_FB_SIS_300
/* Find PCI systems for Chrontel/GPIO communication setup */
if(ivideo->chip == SIS_630) {
i = 0;
do {
if(mychswtable[i].subsysVendor == ivideo->subsysvendor &&
mychswtable[i].subsysCard == ivideo->subsysdevice) {
ivideo->SiS_Pr.SiS_ChSW = true;
printk(KERN_DEBUG "sisfb: Identified [%s %s] "
"requiring Chrontel/GPIO setup\n",
mychswtable[i].vendorName,
mychswtable[i].cardName);
ivideo->lpcdev = pci_get_device(PCI_VENDOR_ID_SI, 0x0008, NULL);
break;
}
i++;
} while(mychswtable[i].subsysVendor != 0);
}
#endif
#ifdef CONFIG_FB_SIS_315
if((ivideo->chip == SIS_760) && (ivideo->nbridge)) {
ivideo->lpcdev = pci_get_slot(ivideo->nbridge->bus, (2 << 3));
}
#endif
SiS_SetReg(SISSR, 0x05, 0x86);
if( (!ivideo->sisvga_enabled)
#if !defined(__i386__) && !defined(__x86_64__)
|| (sisfb_resetcard)
#endif
) {
for(i = 0x30; i <= 0x3f; i++) {
SiS_SetReg(SISCR, i, 0x00);
}
}
/* Find out about current video mode */
ivideo->modeprechange = 0x03;
reg = SiS_GetReg(SISCR, 0x34);
if(reg & 0x7f) {
ivideo->modeprechange = reg & 0x7f;
} else if(ivideo->sisvga_enabled) {
#if defined(__i386__) || defined(__x86_64__)
unsigned char __iomem *tt = ioremap(0x400, 0x100);
if(tt) {
ivideo->modeprechange = readb(tt + 0x49);
iounmap(tt);
}
#endif
}
/* Search and copy ROM image */
ivideo->bios_abase = NULL;
ivideo->SiS_Pr.VirtualRomBase = NULL;
ivideo->SiS_Pr.UseROM = false;
ivideo->haveXGIROM = ivideo->SiS_Pr.SiS_XGIROM = false;
if(ivideo->sisfb_userom) {
ivideo->SiS_Pr.VirtualRomBase = sisfb_find_rom(pdev);
ivideo->bios_abase = ivideo->SiS_Pr.VirtualRomBase;
ivideo->SiS_Pr.UseROM = (bool)(ivideo->SiS_Pr.VirtualRomBase);
printk(KERN_INFO "sisfb: Video ROM %sfound\n",
ivideo->SiS_Pr.UseROM ? "" : "not ");
if((ivideo->SiS_Pr.UseROM) && (ivideo->chip >= XGI_20)) {
ivideo->SiS_Pr.UseROM = false;
ivideo->haveXGIROM = ivideo->SiS_Pr.SiS_XGIROM = true;
if( (ivideo->revision_id == 2) &&
(!(ivideo->bios_abase[0x1d1] & 0x01)) ) {
ivideo->SiS_Pr.DDCPortMixup = true;
}
}
} else {
printk(KERN_INFO "sisfb: Video ROM usage disabled\n");
}
/* Find systems for special custom timing */
if(ivideo->SiS_Pr.SiS_CustomT == CUT_NONE) {
sisfb_detect_custom_timing(ivideo);
}
#ifdef CONFIG_FB_SIS_315
if (ivideo->chip == XGI_20) {
/* Check if our Z7 chip is actually Z9 */
SiS_SetRegOR(SISCR, 0x4a, 0x40); /* GPIOG EN */
reg = SiS_GetReg(SISCR, 0x48);
if (reg & 0x02) { /* GPIOG */
ivideo->chip_real_id = XGI_21;
dev_info(&pdev->dev, "Z9 detected\n");
}
}
#endif
/* POST card in case this has not been done by the BIOS */
if( (!ivideo->sisvga_enabled)
#if !defined(__i386__) && !defined(__x86_64__)
|| (sisfb_resetcard)
#endif
) {
#ifdef CONFIG_FB_SIS_300
if(ivideo->sisvga_engine == SIS_300_VGA) {
if(ivideo->chip == SIS_300) {
sisfb_post_sis300(pdev);
ivideo->sisfb_can_post = 1;
}
}
#endif
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
int result = 1;
/* if((ivideo->chip == SIS_315H) ||
(ivideo->chip == SIS_315) ||
(ivideo->chip == SIS_315PRO) ||
(ivideo->chip == SIS_330)) {
sisfb_post_sis315330(pdev);
} else */ if(ivideo->chip == XGI_20) {
result = sisfb_post_xgi(pdev);
ivideo->sisfb_can_post = 1;
} else if((ivideo->chip == XGI_40) && ivideo->haveXGIROM) {
result = sisfb_post_xgi(pdev);
ivideo->sisfb_can_post = 1;
} else {
printk(KERN_INFO "sisfb: Card is not "
"POSTed and sisfb can't do this either.\n");
}
if(!result) {
printk(KERN_ERR "sisfb: Failed to POST card\n");
ret = -ENODEV;
goto error_3;
}
}
#endif
}
ivideo->sisfb_card_posted = 1;
/* Find out about RAM size */
if(sisfb_get_dram_size(ivideo)) {
printk(KERN_INFO "sisfb: Fatal error: Unable to determine VRAM size.\n");
ret = -ENODEV;
goto error_3;
}
/* Enable PCI addressing and MMIO */
if((ivideo->sisfb_mode_idx < 0) ||
((sisbios_mode[ivideo->sisfb_mode_idx].mode_no[ivideo->mni]) != 0xFF)) {
/* Enable PCI_LINEAR_ADDRESSING and MMIO_ENABLE */
SiS_SetRegOR(SISSR, IND_SIS_PCI_ADDRESS_SET, (SIS_PCI_ADDR_ENABLE | SIS_MEM_MAP_IO_ENABLE));
/* Enable 2D accelerator engine */
SiS_SetRegOR(SISSR, IND_SIS_MODULE_ENABLE, SIS_ENABLE_2D);
}
if(sisfb_pdc != 0xff) {
if(ivideo->sisvga_engine == SIS_300_VGA)
sisfb_pdc &= 0x3c;
else
sisfb_pdc &= 0x1f;
ivideo->SiS_Pr.PDC = sisfb_pdc;
}
#ifdef CONFIG_FB_SIS_315
if(ivideo->sisvga_engine == SIS_315_VGA) {
if(sisfb_pdca != 0xff)
ivideo->SiS_Pr.PDCA = sisfb_pdca & 0x1f;
}
#endif
if(!request_mem_region(ivideo->video_base, ivideo->video_size, "sisfb FB")) {
printk(KERN_ERR "sisfb: Fatal error: Unable to reserve %dMB framebuffer memory\n",
(int)(ivideo->video_size >> 20));
printk(KERN_ERR "sisfb: Is there another framebuffer driver active?\n");
ret = -ENODEV;
goto error_3;
}
if(!request_mem_region(ivideo->mmio_base, ivideo->mmio_size, "sisfb MMIO")) {
printk(KERN_ERR "sisfb: Fatal error: Unable to reserve MMIO region\n");
ret = -ENODEV;
goto error_2;
}
ivideo->video_vbase = ioremap(ivideo->video_base, ivideo->video_size);
ivideo->SiS_Pr.VideoMemoryAddress = ivideo->video_vbase;
if(!ivideo->video_vbase) {
printk(KERN_ERR "sisfb: Fatal error: Unable to map framebuffer memory\n");
ret = -ENODEV;
goto error_1;
}
ivideo->mmio_vbase = ioremap(ivideo->mmio_base, ivideo->mmio_size);
if(!ivideo->mmio_vbase) {
printk(KERN_ERR "sisfb: Fatal error: Unable to map MMIO region\n");
ret = -ENODEV;
error_0: iounmap(ivideo->video_vbase);
error_1: release_mem_region(ivideo->video_base, ivideo->video_size);
error_2: release_mem_region(ivideo->mmio_base, ivideo->mmio_size);
error_3: vfree(ivideo->bios_abase);
if(ivideo->lpcdev)
pci_dev_put(ivideo->lpcdev);
if(ivideo->nbridge)
pci_dev_put(ivideo->nbridge);
pci_set_drvdata(pdev, NULL);
if(!ivideo->sisvga_enabled)
pci_disable_device(pdev);
framebuffer_release(sis_fb_info);
return ret;
}
printk(KERN_INFO "sisfb: Video RAM at 0x%lx, mapped to 0x%lx, size %ldk\n",
ivideo->video_base, (unsigned long)ivideo->video_vbase, ivideo->video_size / 1024);
if(ivideo->video_offset) {
printk(KERN_INFO "sisfb: Viewport offset %ldk\n",
ivideo->video_offset / 1024);
}
printk(KERN_INFO "sisfb: MMIO at 0x%lx, mapped to 0x%lx, size %ldk\n",
ivideo->mmio_base, (unsigned long)ivideo->mmio_vbase, ivideo->mmio_size / 1024);
/* Determine the size of the command queue */
if(ivideo->sisvga_engine == SIS_300_VGA) {
ivideo->cmdQueueSize = TURBO_QUEUE_AREA_SIZE;
} else {
if(ivideo->chip == XGI_20) {
ivideo->cmdQueueSize = COMMAND_QUEUE_AREA_SIZE_Z7;
} else {
ivideo->cmdQueueSize = COMMAND_QUEUE_AREA_SIZE;
}
}
/* Engines are no longer initialized here; this is
* now done after the first mode-switch (if the
* submitted var has its acceleration flags set).
*/
/* Calculate the base of the (unused) hw cursor */
ivideo->hwcursor_vbase = ivideo->video_vbase
+ ivideo->video_size
- ivideo->cmdQueueSize
- ivideo->hwcursor_size;
ivideo->caps |= HW_CURSOR_CAP;
/* Initialize offscreen memory manager */
if((ivideo->havenoheap = sisfb_heap_init(ivideo))) {
printk(KERN_WARNING "sisfb: Failed to initialize offscreen memory heap\n");
}
/* Used for clearing the screen only, therefore respect our mem limit */
ivideo->SiS_Pr.VideoMemoryAddress += ivideo->video_offset;
ivideo->SiS_Pr.VideoMemorySize = ivideo->sisfb_mem;
ivideo->mtrr = -1;
ivideo->vbflags = 0;
ivideo->lcddefmodeidx = DEFAULT_LCDMODE;
ivideo->tvdefmodeidx = DEFAULT_TVMODE;
ivideo->defmodeidx = DEFAULT_MODE;
ivideo->newrom = 0;
if(ivideo->chip < XGI_20) {
if(ivideo->bios_abase) {
ivideo->newrom = SiSDetermineROMLayout661(&ivideo->SiS_Pr);
}
}
if((ivideo->sisfb_mode_idx < 0) ||
((sisbios_mode[ivideo->sisfb_mode_idx].mode_no[ivideo->mni]) != 0xFF)) {
sisfb_sense_crt1(ivideo);
sisfb_get_VB_type(ivideo);
if(ivideo->vbflags2 & VB2_VIDEOBRIDGE) {
sisfb_detect_VB_connect(ivideo);
}
ivideo->currentvbflags = ivideo->vbflags & (VB_VIDEOBRIDGE | TV_STANDARD);
/* Decide on which CRT2 device to use */
if(ivideo->vbflags2 & VB2_VIDEOBRIDGE) {
if(ivideo->sisfb_crt2type != -1) {
if((ivideo->sisfb_crt2type == CRT2_LCD) &&
(ivideo->vbflags & CRT2_LCD)) {
ivideo->currentvbflags |= CRT2_LCD;
} else if(ivideo->sisfb_crt2type != CRT2_LCD) {
ivideo->currentvbflags |= ivideo->sisfb_crt2type;
}
} else {
/* Chrontel 700x TV detection often unreliable, therefore
* use a different default order on such machines
*/
if((ivideo->sisvga_engine == SIS_300_VGA) &&
(ivideo->vbflags2 & VB2_CHRONTEL)) {
if(ivideo->vbflags & CRT2_LCD)
ivideo->currentvbflags |= CRT2_LCD;
else if(ivideo->vbflags & CRT2_TV)
ivideo->currentvbflags |= CRT2_TV;
else if(ivideo->vbflags & CRT2_VGA)
ivideo->currentvbflags |= CRT2_VGA;
} else {
if(ivideo->vbflags & CRT2_TV)
ivideo->currentvbflags |= CRT2_TV;
else if(ivideo->vbflags & CRT2_LCD)
ivideo->currentvbflags |= CRT2_LCD;
else if(ivideo->vbflags & CRT2_VGA)
ivideo->currentvbflags |= CRT2_VGA;
}
}
}
if(ivideo->vbflags & CRT2_LCD) {
sisfb_detect_lcd_type(ivideo);
}
sisfb_save_pdc_emi(ivideo);
if(!ivideo->sisfb_crt1off) {
sisfb_handle_ddc(ivideo, &ivideo->sisfb_thismonitor, 0);
} else {
if((ivideo->vbflags2 & VB2_SISTMDSBRIDGE) &&
(ivideo->vbflags & (CRT2_VGA | CRT2_LCD))) {
sisfb_handle_ddc(ivideo, &ivideo->sisfb_thismonitor, 1);
}
}
if(ivideo->sisfb_mode_idx >= 0) {
int bu = ivideo->sisfb_mode_idx;
ivideo->sisfb_mode_idx = sisfb_validate_mode(ivideo,
ivideo->sisfb_mode_idx, ivideo->currentvbflags);
if(bu != ivideo->sisfb_mode_idx) {
printk(KERN_ERR "Mode %dx%dx%d failed validation\n",
sisbios_mode[bu].xres,
sisbios_mode[bu].yres,
sisbios_mode[bu].bpp);
}
}
if(ivideo->sisfb_mode_idx < 0) {
switch(ivideo->currentvbflags & VB_DISPTYPE_DISP2) {
case CRT2_LCD:
ivideo->sisfb_mode_idx = ivideo->lcddefmodeidx;
break;
case CRT2_TV:
ivideo->sisfb_mode_idx = ivideo->tvdefmodeidx;
break;
default:
ivideo->sisfb_mode_idx = ivideo->defmodeidx;
break;
}
}
ivideo->mode_no = sisbios_mode[ivideo->sisfb_mode_idx].mode_no[ivideo->mni];
if(ivideo->refresh_rate != 0) {
sisfb_search_refresh_rate(ivideo, ivideo->refresh_rate,
ivideo->sisfb_mode_idx);
}
if(ivideo->rate_idx == 0) {
ivideo->rate_idx = sisbios_mode[ivideo->sisfb_mode_idx].rate_idx;
ivideo->refresh_rate = 60;
}
if(ivideo->sisfb_thismonitor.datavalid) {
if(!sisfb_verify_rate(ivideo, &ivideo->sisfb_thismonitor,
ivideo->sisfb_mode_idx,
ivideo->rate_idx,
ivideo->refresh_rate)) {
printk(KERN_INFO "sisfb: WARNING: Refresh rate "
"exceeds monitor specs!\n");
}
}
ivideo->video_bpp = sisbios_mode[ivideo->sisfb_mode_idx].bpp;
ivideo->video_width = sisbios_mode[ivideo->sisfb_mode_idx].xres;
ivideo->video_height = sisbios_mode[ivideo->sisfb_mode_idx].yres;
sisfb_set_vparms(ivideo);
printk(KERN_INFO "sisfb: Default mode is %dx%dx%d (%dHz)\n",
ivideo->video_width, ivideo->video_height, ivideo->video_bpp,
ivideo->refresh_rate);
/* Set up the default var according to chosen default display mode */
ivideo->default_var.xres = ivideo->default_var.xres_virtual = ivideo->video_width;
ivideo->default_var.yres = ivideo->default_var.yres_virtual = ivideo->video_height;
ivideo->default_var.bits_per_pixel = ivideo->video_bpp;
sisfb_bpp_to_var(ivideo, &ivideo->default_var);
ivideo->default_var.pixclock = (u32) (1000000000 /
sisfb_mode_rate_to_dclock(&ivideo->SiS_Pr, ivideo->mode_no, ivideo->rate_idx));
if(sisfb_mode_rate_to_ddata(&ivideo->SiS_Pr, ivideo->mode_no,
ivideo->rate_idx, &ivideo->default_var)) {
if((ivideo->default_var.vmode & FB_VMODE_MASK) == FB_VMODE_DOUBLE) {
ivideo->default_var.pixclock <<= 1;
}
}
if(ivideo->sisfb_ypan) {
/* Maximize regardless of sisfb_max at startup */
ivideo->default_var.yres_virtual =
sisfb_calc_maxyres(ivideo, &ivideo->default_var);
if(ivideo->default_var.yres_virtual < ivideo->default_var.yres) {
ivideo->default_var.yres_virtual = ivideo->default_var.yres;
}
}
sisfb_calc_pitch(ivideo, &ivideo->default_var);
ivideo->accel = 0;
if(ivideo->sisfb_accel) {
ivideo->accel = -1;
#ifdef STUPID_ACCELF_TEXT_SHIT
ivideo->default_var.accel_flags |= FB_ACCELF_TEXT;
#endif
}
sisfb_initaccel(ivideo);
#if defined(FBINFO_HWACCEL_DISABLED) && defined(FBINFO_HWACCEL_XPAN)
sis_fb_info->flags = FBINFO_DEFAULT |
FBINFO_HWACCEL_YPAN |
FBINFO_HWACCEL_XPAN |
FBINFO_HWACCEL_COPYAREA |
FBINFO_HWACCEL_FILLRECT |
((ivideo->accel) ? 0 : FBINFO_HWACCEL_DISABLED);
#else
sis_fb_info->flags = FBINFO_FLAG_DEFAULT;
#endif
sis_fb_info->var = ivideo->default_var;
sis_fb_info->fix = ivideo->sisfb_fix;
sis_fb_info->screen_base = ivideo->video_vbase + ivideo->video_offset;
sis_fb_info->fbops = &sisfb_ops;
sis_fb_info->pseudo_palette = ivideo->pseudo_palette;
fb_alloc_cmap(&sis_fb_info->cmap, 256 , 0);
printk(KERN_DEBUG "sisfb: Initial vbflags 0x%x\n", (int)ivideo->vbflags);
#ifdef CONFIG_MTRR
ivideo->mtrr = mtrr_add(ivideo->video_base, ivideo->video_size,
MTRR_TYPE_WRCOMB, 1);
if(ivideo->mtrr < 0) {
printk(KERN_DEBUG "sisfb: Failed to add MTRRs\n");
}
#endif
if(register_framebuffer(sis_fb_info) < 0) {
printk(KERN_ERR "sisfb: Fatal error: Failed to register framebuffer\n");
ret = -EINVAL;
iounmap(ivideo->mmio_vbase);
goto error_0;
}
ivideo->registered = 1;
/* Enlist us */
ivideo->next = card_list;
card_list = ivideo;
printk(KERN_INFO "sisfb: 2D acceleration is %s, y-panning %s\n",
ivideo->sisfb_accel ? "enabled" : "disabled",
ivideo->sisfb_ypan ?
(ivideo->sisfb_max ? "enabled (auto-max)" :
"enabled (no auto-max)") :
"disabled");
printk(KERN_INFO "fb%d: %s frame buffer device version %d.%d.%d\n",
sis_fb_info->node, ivideo->myid, VER_MAJOR, VER_MINOR, VER_LEVEL);
printk(KERN_INFO "sisfb: Copyright (C) 2001-2005 Thomas Winischhofer\n");
} /* if mode = "none" */
return 0;
}
/*****************************************************/
/* PCI DEVICE HANDLING */
/*****************************************************/
static void __devexit sisfb_remove(struct pci_dev *pdev)
{
struct sis_video_info *ivideo = pci_get_drvdata(pdev);
struct fb_info *sis_fb_info = ivideo->memyselfandi;
int registered = ivideo->registered;
int modechanged = ivideo->modechanged;
/* Unmap */
iounmap(ivideo->mmio_vbase);
iounmap(ivideo->video_vbase);
/* Release mem regions */
release_mem_region(ivideo->video_base, ivideo->video_size);
release_mem_region(ivideo->mmio_base, ivideo->mmio_size);
vfree(ivideo->bios_abase);
if(ivideo->lpcdev)
pci_dev_put(ivideo->lpcdev);
if(ivideo->nbridge)
pci_dev_put(ivideo->nbridge);
#ifdef CONFIG_MTRR
/* Release MTRR region */
if(ivideo->mtrr >= 0)
mtrr_del(ivideo->mtrr, ivideo->video_base, ivideo->video_size);
#endif
pci_set_drvdata(pdev, NULL);
/* If device was disabled when starting, disable
* it when quitting.
*/
if(!ivideo->sisvga_enabled)
pci_disable_device(pdev);
/* Unregister the framebuffer */
if(ivideo->registered) {
unregister_framebuffer(sis_fb_info);
framebuffer_release(sis_fb_info);
}
/* OK, our ivideo is gone for good from here. */
/* TODO: Restore the initial mode
* This sounds easy but is as good as impossible
* on many machines with SiS chip and video bridge
* since text modes are always set up differently
* from machine to machine. Depends on the type
* of integration between chipset and bridge.
*/
if(registered && modechanged)
printk(KERN_INFO
"sisfb: Restoring of text mode not supported yet\n");
};
static struct pci_driver sisfb_driver = {
.name = "sisfb",
.id_table = sisfb_pci_table,
.probe = sisfb_probe,
.remove = __devexit_p(sisfb_remove)
};
static int __init sisfb_init(void)
{
#ifndef MODULE
char *options = NULL;
if(fb_get_options("sisfb", &options))
return -ENODEV;
sisfb_setup(options);
#endif
return pci_register_driver(&sisfb_driver);
}
#ifndef MODULE
module_init(sisfb_init);
#endif
/*****************************************************/
/* MODULE */
/*****************************************************/
#ifdef MODULE
static char *mode = NULL;
static int vesa = -1;
static unsigned int rate = 0;
static unsigned int crt1off = 1;
static unsigned int mem = 0;
static char *forcecrt2type = NULL;
static int forcecrt1 = -1;
static int pdc = -1;
static int pdc1 = -1;
static int noaccel = -1;
static int noypan = -1;
static int nomax = -1;
static int userom = -1;
static int useoem = -1;
static char *tvstandard = NULL;
static int nocrt2rate = 0;
static int scalelcd = -1;
static char *specialtiming = NULL;
static int lvdshl = -1;
static int tvxposoffset = 0, tvyposoffset = 0;
#if !defined(__i386__) && !defined(__x86_64__)
static int resetcard = 0;
static int videoram = 0;
#endif
static int __init sisfb_init_module(void)
{
sisfb_setdefaultparms();
if(rate)
sisfb_parm_rate = rate;
if((scalelcd == 0) || (scalelcd == 1))
sisfb_scalelcd = scalelcd ^ 1;
/* Need to check crt2 type first for fstn/dstn */
if(forcecrt2type)
sisfb_search_crt2type(forcecrt2type);
if(tvstandard)
sisfb_search_tvstd(tvstandard);
if(mode)
sisfb_search_mode(mode, false);
else if(vesa != -1)
sisfb_search_vesamode(vesa, false);
sisfb_crt1off = (crt1off == 0) ? 1 : 0;
sisfb_forcecrt1 = forcecrt1;
if(forcecrt1 == 1)
sisfb_crt1off = 0;
else if(forcecrt1 == 0)
sisfb_crt1off = 1;
if(noaccel == 1)
sisfb_accel = 0;
else if(noaccel == 0)
sisfb_accel = 1;
if(noypan == 1)
sisfb_ypan = 0;
else if(noypan == 0)
sisfb_ypan = 1;
if(nomax == 1)
sisfb_max = 0;
else if(nomax == 0)
sisfb_max = 1;
if(mem)
sisfb_parm_mem = mem;
if(userom != -1)
sisfb_userom = userom;
if(useoem != -1)
sisfb_useoem = useoem;
if(pdc != -1)
sisfb_pdc = (pdc & 0x7f);
if(pdc1 != -1)
sisfb_pdca = (pdc1 & 0x1f);
sisfb_nocrt2rate = nocrt2rate;
if(specialtiming)
sisfb_search_specialtiming(specialtiming);
if((lvdshl >= 0) && (lvdshl <= 3))
sisfb_lvdshl = lvdshl;
sisfb_tvxposoffset = tvxposoffset;
sisfb_tvyposoffset = tvyposoffset;
#if !defined(__i386__) && !defined(__x86_64__)
sisfb_resetcard = (resetcard) ? 1 : 0;
if(videoram)
sisfb_videoram = videoram;
#endif
return sisfb_init();
}
static void __exit sisfb_remove_module(void)
{
pci_unregister_driver(&sisfb_driver);
printk(KERN_DEBUG "sisfb: Module unloaded\n");
}
module_init(sisfb_init_module);
module_exit(sisfb_remove_module);
MODULE_DESCRIPTION("SiS 300/540/630/730/315/55x/65x/661/74x/330/76x/34x, XGI V3XT/V5/V8/Z7 framebuffer device driver");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Thomas Winischhofer <thomas@winischhofer.net>, Others");
module_param(mem, int, 0);
module_param(noaccel, int, 0);
module_param(noypan, int, 0);
module_param(nomax, int, 0);
module_param(userom, int, 0);
module_param(useoem, int, 0);
module_param(mode, charp, 0);
module_param(vesa, int, 0);
module_param(rate, int, 0);
module_param(forcecrt1, int, 0);
module_param(forcecrt2type, charp, 0);
module_param(scalelcd, int, 0);
module_param(pdc, int, 0);
module_param(pdc1, int, 0);
module_param(specialtiming, charp, 0);
module_param(lvdshl, int, 0);
module_param(tvstandard, charp, 0);
module_param(tvxposoffset, int, 0);
module_param(tvyposoffset, int, 0);
module_param(nocrt2rate, int, 0);
#if !defined(__i386__) && !defined(__x86_64__)
module_param(resetcard, int, 0);
module_param(videoram, int, 0);
#endif
MODULE_PARM_DESC(mem,
"\nDetermines the beginning of the video memory heap in KB. This heap is used\n"
"for video RAM management for eg. DRM/DRI. On 300 series, the default depends\n"
"on the amount of video RAM available. If 8MB of video RAM or less is available,\n"
"the heap starts at 4096KB, if between 8 and 16MB are available at 8192KB,\n"
"otherwise at 12288KB. On 315/330/340 series, the heap size is 32KB by default.\n"
"The value is to be specified without 'KB'.\n");
MODULE_PARM_DESC(noaccel,
"\nIf set to anything other than 0, 2D acceleration will be disabled.\n"
"(default: 0)\n");
MODULE_PARM_DESC(noypan,
"\nIf set to anything other than 0, y-panning will be disabled and scrolling\n"
"will be performed by redrawing the screen. (default: 0)\n");
MODULE_PARM_DESC(nomax,
"\nIf y-panning is enabled, sisfb will by default use the entire available video\n"
"memory for the virtual screen in order to optimize scrolling performance. If\n"
"this is set to anything other than 0, sisfb will not do this and thereby \n"
"enable the user to positively specify a virtual Y size of the screen using\n"
"fbset. (default: 0)\n");
MODULE_PARM_DESC(mode,
"\nSelects the desired default display mode in the format XxYxDepth,\n"
"eg. 1024x768x16. Other formats supported include XxY-Depth and\n"
"XxY-Depth@Rate. If the parameter is only one (decimal or hexadecimal)\n"
"number, it will be interpreted as a VESA mode number. (default: 800x600x8)\n");
MODULE_PARM_DESC(vesa,
"\nSelects the desired default display mode by VESA defined mode number, eg.\n"
"0x117 (default: 0x0103)\n");
MODULE_PARM_DESC(rate,
"\nSelects the desired vertical refresh rate for CRT1 (external VGA) in Hz.\n"
"If the mode is specified in the format XxY-Depth@Rate, this parameter\n"
"will be ignored (default: 60)\n");
MODULE_PARM_DESC(forcecrt1,
"\nNormally, the driver autodetects whether or not CRT1 (external VGA) is \n"
"connected. With this option, the detection can be overridden (1=CRT1 ON,\n"
"0=CRT1 OFF) (default: [autodetected])\n");
MODULE_PARM_DESC(forcecrt2type,
"\nIf this option is omitted, the driver autodetects CRT2 output devices, such as\n"
"LCD, TV or secondary VGA. With this option, this autodetection can be\n"
"overridden. Possible parameters are LCD, TV, VGA or NONE. NONE disables CRT2.\n"
"On systems with a SiS video bridge, parameters SVIDEO, COMPOSITE or SCART can\n"
"be used instead of TV to override the TV detection. Furthermore, on systems\n"
"with a SiS video bridge, SVIDEO+COMPOSITE, HIVISION, YPBPR480I, YPBPR480P,\n"
"YPBPR720P and YPBPR1080I are understood. However, whether or not these work\n"
"depends on the very hardware in use. (default: [autodetected])\n");
MODULE_PARM_DESC(scalelcd,
"\nSetting this to 1 will force the driver to scale the LCD image to the panel's\n"
"native resolution. Setting it to 0 will disable scaling; LVDS panels will\n"
"show black bars around the image, TMDS panels will probably do the scaling\n"
"themselves. Default: 1 on LVDS panels, 0 on TMDS panels\n");
MODULE_PARM_DESC(pdc,
"\nThis is for manually selecting the LCD panel delay compensation. The driver\n"
"should detect this correctly in most cases; however, sometimes this is not\n"
"possible. If you see 'small waves' on the LCD, try setting this to 4, 32 or 24\n"
"on a 300 series chipset; 6 on other chipsets. If the problem persists, try\n"
"other values (on 300 series: between 4 and 60 in steps of 4; otherwise: any\n"
"value from 0 to 31). (default: autodetected, if LCD is active during start)\n");
#ifdef CONFIG_FB_SIS_315
MODULE_PARM_DESC(pdc1,
"\nThis is same as pdc, but for LCD-via CRT1. Hence, this is for the 315/330/340\n"
"series only. (default: autodetected if LCD is in LCD-via-CRT1 mode during\n"
"startup) - Note: currently, this has no effect because LCD-via-CRT1 is not\n"
"implemented yet.\n");
#endif
MODULE_PARM_DESC(specialtiming,
"\nPlease refer to documentation for more information on this option.\n");
MODULE_PARM_DESC(lvdshl,
"\nPlease refer to documentation for more information on this option.\n");
MODULE_PARM_DESC(tvstandard,
"\nThis allows overriding the BIOS default for the TV standard. Valid choices are\n"
"pal, ntsc, palm and paln. (default: [auto; pal or ntsc only])\n");
MODULE_PARM_DESC(tvxposoffset,
"\nRelocate TV output horizontally. Possible parameters: -32 through 32.\n"
"Default: 0\n");
MODULE_PARM_DESC(tvyposoffset,
"\nRelocate TV output vertically. Possible parameters: -32 through 32.\n"
"Default: 0\n");
MODULE_PARM_DESC(nocrt2rate,
"\nSetting this to 1 will force the driver to use the default refresh rate for\n"
"CRT2 if CRT2 type is VGA. (default: 0, use same rate as CRT1)\n");
#if !defined(__i386__) && !defined(__x86_64__)
#ifdef CONFIG_FB_SIS_300
MODULE_PARM_DESC(resetcard,
"\nSet this to 1 in order to reset (POST) the card on non-x86 machines where\n"
"the BIOS did not POST the card (only supported for SiS 300/305 and XGI cards\n"
"currently). Default: 0\n");
MODULE_PARM_DESC(videoram,
"\nSet this to the amount of video RAM (in kilobyte) the card has. Required on\n"
"some non-x86 architectures where the memory auto detection fails. Only\n"
"relevant if resetcard is set, too. SiS300/305 only. Default: [auto-detect]\n");
#endif
#endif
#endif /* /MODULE */
/* _GPL only for new symbols. */
EXPORT_SYMBOL(sis_malloc);
EXPORT_SYMBOL(sis_free);
EXPORT_SYMBOL_GPL(sis_malloc_new);
EXPORT_SYMBOL_GPL(sis_free_new);
| gpl-2.0 |
keiranFTW/sony-kernel-msm8660 | arch/x86/kernel/cpu/mtrr/centaur.c | 13253 | 3027 | #include <linux/init.h>
#include <linux/mm.h>
#include <asm/mtrr.h>
#include <asm/msr.h>
#include "mtrr.h"
static struct {
unsigned long high;
unsigned long low;
} centaur_mcr[8];
static u8 centaur_mcr_reserved;
static u8 centaur_mcr_type; /* 0 for winchip, 1 for winchip2 */
/**
* centaur_get_free_region - Get a free MTRR.
*
* @base: The starting (base) address of the region.
* @size: The size (in bytes) of the region.
*
* Returns: the index of the region on success, else -1 on error.
*/
static int
centaur_get_free_region(unsigned long base, unsigned long size, int replace_reg)
{
unsigned long lbase, lsize;
mtrr_type ltype;
int i, max;
max = num_var_ranges;
if (replace_reg >= 0 && replace_reg < max)
return replace_reg;
for (i = 0; i < max; ++i) {
if (centaur_mcr_reserved & (1 << i))
continue;
mtrr_if->get(i, &lbase, &lsize, <ype);
if (lsize == 0)
return i;
}
return -ENOSPC;
}
/*
* Report boot time MCR setups
*/
void mtrr_centaur_report_mcr(int mcr, u32 lo, u32 hi)
{
centaur_mcr[mcr].low = lo;
centaur_mcr[mcr].high = hi;
}
static void
centaur_get_mcr(unsigned int reg, unsigned long *base,
unsigned long *size, mtrr_type * type)
{
*base = centaur_mcr[reg].high >> PAGE_SHIFT;
*size = -(centaur_mcr[reg].low & 0xfffff000) >> PAGE_SHIFT;
*type = MTRR_TYPE_WRCOMB; /* write-combining */
if (centaur_mcr_type == 1 && ((centaur_mcr[reg].low & 31) & 2))
*type = MTRR_TYPE_UNCACHABLE;
if (centaur_mcr_type == 1 && (centaur_mcr[reg].low & 31) == 25)
*type = MTRR_TYPE_WRBACK;
if (centaur_mcr_type == 0 && (centaur_mcr[reg].low & 31) == 31)
*type = MTRR_TYPE_WRBACK;
}
static void
centaur_set_mcr(unsigned int reg, unsigned long base,
unsigned long size, mtrr_type type)
{
unsigned long low, high;
if (size == 0) {
/* Disable */
high = low = 0;
} else {
high = base << PAGE_SHIFT;
if (centaur_mcr_type == 0) {
/* Only support write-combining... */
low = -size << PAGE_SHIFT | 0x1f;
} else {
if (type == MTRR_TYPE_UNCACHABLE)
low = -size << PAGE_SHIFT | 0x02; /* NC */
else
low = -size << PAGE_SHIFT | 0x09; /* WWO, WC */
}
}
centaur_mcr[reg].high = high;
centaur_mcr[reg].low = low;
wrmsr(MSR_IDT_MCR0 + reg, low, high);
}
static int
centaur_validate_add_page(unsigned long base, unsigned long size, unsigned int type)
{
/*
* FIXME: Winchip2 supports uncached
*/
if (type != MTRR_TYPE_WRCOMB &&
(centaur_mcr_type == 0 || type != MTRR_TYPE_UNCACHABLE)) {
pr_warning("mtrr: only write-combining%s supported\n",
centaur_mcr_type ? " and uncacheable are" : " is");
return -EINVAL;
}
return 0;
}
static const struct mtrr_ops centaur_mtrr_ops = {
.vendor = X86_VENDOR_CENTAUR,
.set = centaur_set_mcr,
.get = centaur_get_mcr,
.get_free_region = centaur_get_free_region,
.validate_add_page = centaur_validate_add_page,
.have_wrcomb = positive_have_wrcomb,
};
int __init centaur_init_mtrr(void)
{
set_mtrr_ops(¢aur_mtrr_ops);
return 0;
}
| gpl-2.0 |
KanoComputing/raspberrypi-linux | arch/tile/kernel/setup.c | 198 | 49469 | /*
* 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/sched.h>
#include <linux/kernel.h>
#include <linux/mmzone.h>
#include <linux/bootmem.h>
#include <linux/module.h>
#include <linux/node.h>
#include <linux/cpu.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/kexec.h>
#include <linux/pci.h>
#include <linux/swiotlb.h>
#include <linux/initrd.h>
#include <linux/io.h>
#include <linux/highmem.h>
#include <linux/smp.h>
#include <linux/timex.h>
#include <linux/hugetlb.h>
#include <linux/start_kernel.h>
#include <linux/screen_info.h>
#include <asm/setup.h>
#include <asm/sections.h>
#include <asm/cacheflush.h>
#include <asm/pgalloc.h>
#include <asm/mmu_context.h>
#include <hv/hypervisor.h>
#include <arch/interrupts.h>
/* <linux/smp.h> doesn't provide this definition. */
#ifndef CONFIG_SMP
#define setup_max_cpus 1
#endif
static inline int ABS(int x) { return x >= 0 ? x : -x; }
/* Chip information */
char chip_model[64] __write_once;
#ifdef CONFIG_VT
struct screen_info screen_info;
#endif
struct pglist_data node_data[MAX_NUMNODES] __read_mostly;
EXPORT_SYMBOL(node_data);
/* Information on the NUMA nodes that we compute early */
unsigned long node_start_pfn[MAX_NUMNODES];
unsigned long node_end_pfn[MAX_NUMNODES];
unsigned long __initdata node_memmap_pfn[MAX_NUMNODES];
unsigned long __initdata node_percpu_pfn[MAX_NUMNODES];
unsigned long __initdata node_free_pfn[MAX_NUMNODES];
static unsigned long __initdata node_percpu[MAX_NUMNODES];
/*
* per-CPU stack and boot info.
*/
DEFINE_PER_CPU(unsigned long, boot_sp) =
(unsigned long)init_stack + THREAD_SIZE;
#ifdef CONFIG_SMP
DEFINE_PER_CPU(unsigned long, boot_pc) = (unsigned long)start_kernel;
#else
/*
* The variable must be __initdata since it references __init code.
* With CONFIG_SMP it is per-cpu data, which is exempt from validation.
*/
unsigned long __initdata boot_pc = (unsigned long)start_kernel;
#endif
#ifdef CONFIG_HIGHMEM
/* Page frame index of end of lowmem on each controller. */
unsigned long node_lowmem_end_pfn[MAX_NUMNODES];
/* Number of pages that can be mapped into lowmem. */
static unsigned long __initdata mappable_physpages;
#endif
/* Data on which physical memory controller corresponds to which NUMA node */
int node_controller[MAX_NUMNODES] = { [0 ... MAX_NUMNODES-1] = -1 };
#ifdef CONFIG_HIGHMEM
/* Map information from VAs to PAs */
unsigned long pbase_map[1 << (32 - HPAGE_SHIFT)]
__write_once __attribute__((aligned(L2_CACHE_BYTES)));
EXPORT_SYMBOL(pbase_map);
/* Map information from PAs to VAs */
void *vbase_map[NR_PA_HIGHBIT_VALUES]
__write_once __attribute__((aligned(L2_CACHE_BYTES)));
EXPORT_SYMBOL(vbase_map);
#endif
/* Node number as a function of the high PA bits */
int highbits_to_node[NR_PA_HIGHBIT_VALUES] __write_once;
EXPORT_SYMBOL(highbits_to_node);
static unsigned int __initdata maxmem_pfn = -1U;
static unsigned int __initdata maxnodemem_pfn[MAX_NUMNODES] = {
[0 ... MAX_NUMNODES-1] = -1U
};
static nodemask_t __initdata isolnodes;
#if defined(CONFIG_PCI) && !defined(__tilegx__)
enum { DEFAULT_PCI_RESERVE_MB = 64 };
static unsigned int __initdata pci_reserve_mb = DEFAULT_PCI_RESERVE_MB;
unsigned long __initdata pci_reserve_start_pfn = -1U;
unsigned long __initdata pci_reserve_end_pfn = -1U;
#endif
static int __init setup_maxmem(char *str)
{
unsigned long long maxmem;
if (str == NULL || (maxmem = memparse(str, NULL)) == 0)
return -EINVAL;
maxmem_pfn = (maxmem >> HPAGE_SHIFT) << (HPAGE_SHIFT - PAGE_SHIFT);
pr_info("Forcing RAM used to no more than %dMB\n",
maxmem_pfn >> (20 - PAGE_SHIFT));
return 0;
}
early_param("maxmem", setup_maxmem);
static int __init setup_maxnodemem(char *str)
{
char *endp;
unsigned long long maxnodemem;
long node;
node = str ? simple_strtoul(str, &endp, 0) : INT_MAX;
if (node >= MAX_NUMNODES || *endp != ':')
return -EINVAL;
maxnodemem = memparse(endp+1, NULL);
maxnodemem_pfn[node] = (maxnodemem >> HPAGE_SHIFT) <<
(HPAGE_SHIFT - PAGE_SHIFT);
pr_info("Forcing RAM used on node %ld to no more than %dMB\n",
node, maxnodemem_pfn[node] >> (20 - PAGE_SHIFT));
return 0;
}
early_param("maxnodemem", setup_maxnodemem);
struct memmap_entry {
u64 addr; /* start of memory segment */
u64 size; /* size of memory segment */
};
static struct memmap_entry memmap_map[64];
static int memmap_nr;
static void add_memmap_region(u64 addr, u64 size)
{
if (memmap_nr >= ARRAY_SIZE(memmap_map)) {
pr_err("Ooops! Too many entries in the memory map!\n");
return;
}
memmap_map[memmap_nr].addr = addr;
memmap_map[memmap_nr].size = size;
memmap_nr++;
}
static int __init setup_memmap(char *p)
{
char *oldp;
u64 start_at, mem_size;
if (!p)
return -EINVAL;
if (!strncmp(p, "exactmap", 8)) {
pr_err("\"memmap=exactmap\" not valid on tile\n");
return 0;
}
oldp = p;
mem_size = memparse(p, &p);
if (p == oldp)
return -EINVAL;
if (*p == '@') {
pr_err("\"memmap=nn@ss\" (force RAM) invalid on tile\n");
} else if (*p == '#') {
pr_err("\"memmap=nn#ss\" (force ACPI data) invalid on tile\n");
} else if (*p == '$') {
start_at = memparse(p+1, &p);
add_memmap_region(start_at, mem_size);
} else {
if (mem_size == 0)
return -EINVAL;
maxmem_pfn = (mem_size >> HPAGE_SHIFT) <<
(HPAGE_SHIFT - PAGE_SHIFT);
}
return *p == '\0' ? 0 : -EINVAL;
}
early_param("memmap", setup_memmap);
static int __init setup_mem(char *str)
{
return setup_maxmem(str);
}
early_param("mem", setup_mem); /* compatibility with x86 */
static int __init setup_isolnodes(char *str)
{
char buf[MAX_NUMNODES * 5];
if (str == NULL || nodelist_parse(str, isolnodes) != 0)
return -EINVAL;
nodelist_scnprintf(buf, sizeof(buf), isolnodes);
pr_info("Set isolnodes value to '%s'\n", buf);
return 0;
}
early_param("isolnodes", setup_isolnodes);
#if defined(CONFIG_PCI) && !defined(__tilegx__)
static int __init setup_pci_reserve(char* str)
{
if (str == NULL || kstrtouint(str, 0, &pci_reserve_mb) != 0 ||
pci_reserve_mb > 3 * 1024)
return -EINVAL;
pr_info("Reserving %dMB for PCIE root complex mappings\n",
pci_reserve_mb);
return 0;
}
early_param("pci_reserve", setup_pci_reserve);
#endif
#ifndef __tilegx__
/*
* vmalloc=size forces the vmalloc area to be exactly 'size' bytes.
* This can be used to increase (or decrease) the vmalloc area.
*/
static int __init parse_vmalloc(char *arg)
{
if (!arg)
return -EINVAL;
VMALLOC_RESERVE = (memparse(arg, &arg) + PGDIR_SIZE - 1) & PGDIR_MASK;
/* See validate_va() for more on this test. */
if ((long)_VMALLOC_START >= 0)
early_panic("\"vmalloc=%#lx\" value too large: maximum %#lx\n",
VMALLOC_RESERVE, _VMALLOC_END - 0x80000000UL);
return 0;
}
early_param("vmalloc", parse_vmalloc);
#endif
#ifdef CONFIG_HIGHMEM
/*
* Determine for each controller where its lowmem is mapped and how much of
* it is mapped there. On controller zero, the first few megabytes are
* already mapped in as code at MEM_SV_START, so in principle we could
* start our data mappings higher up, but for now we don't bother, to avoid
* additional confusion.
*
* One question is whether, on systems with more than 768 Mb and
* controllers of different sizes, to map in a proportionate amount of
* each one, or to try to map the same amount from each controller.
* (E.g. if we have three controllers with 256MB, 1GB, and 256MB
* respectively, do we map 256MB from each, or do we map 128 MB, 512
* MB, and 128 MB respectively?) For now we use a proportionate
* solution like the latter.
*
* The VA/PA mapping demands that we align our decisions at 16 MB
* boundaries so that we can rapidly convert VA to PA.
*/
static void *__init setup_pa_va_mapping(void)
{
unsigned long curr_pages = 0;
unsigned long vaddr = PAGE_OFFSET;
nodemask_t highonlynodes = isolnodes;
int i, j;
memset(pbase_map, -1, sizeof(pbase_map));
memset(vbase_map, -1, sizeof(vbase_map));
/* Node zero cannot be isolated for LOWMEM purposes. */
node_clear(0, highonlynodes);
/* Count up the number of pages on non-highonlynodes controllers. */
mappable_physpages = 0;
for_each_online_node(i) {
if (!node_isset(i, highonlynodes))
mappable_physpages +=
node_end_pfn[i] - node_start_pfn[i];
}
for_each_online_node(i) {
unsigned long start = node_start_pfn[i];
unsigned long end = node_end_pfn[i];
unsigned long size = end - start;
unsigned long vaddr_end;
if (node_isset(i, highonlynodes)) {
/* Mark this controller as having no lowmem. */
node_lowmem_end_pfn[i] = start;
continue;
}
curr_pages += size;
if (mappable_physpages > MAXMEM_PFN) {
vaddr_end = PAGE_OFFSET +
(((u64)curr_pages * MAXMEM_PFN /
mappable_physpages)
<< PAGE_SHIFT);
} else {
vaddr_end = PAGE_OFFSET + (curr_pages << PAGE_SHIFT);
}
for (j = 0; vaddr < vaddr_end; vaddr += HPAGE_SIZE, ++j) {
unsigned long this_pfn =
start + (j << HUGETLB_PAGE_ORDER);
pbase_map[vaddr >> HPAGE_SHIFT] = this_pfn;
if (vbase_map[__pfn_to_highbits(this_pfn)] ==
(void *)-1)
vbase_map[__pfn_to_highbits(this_pfn)] =
(void *)(vaddr & HPAGE_MASK);
}
node_lowmem_end_pfn[i] = start + (j << HUGETLB_PAGE_ORDER);
BUG_ON(node_lowmem_end_pfn[i] > end);
}
/* Return highest address of any mapped memory. */
return (void *)vaddr;
}
#endif /* CONFIG_HIGHMEM */
/*
* Register our most important memory mappings with the debug stub.
*
* This is up to 4 mappings for lowmem, one mapping per memory
* controller, plus one for our text segment.
*/
static void store_permanent_mappings(void)
{
int i;
for_each_online_node(i) {
HV_PhysAddr pa = ((HV_PhysAddr)node_start_pfn[i]) << PAGE_SHIFT;
#ifdef CONFIG_HIGHMEM
HV_PhysAddr high_mapped_pa = node_lowmem_end_pfn[i];
#else
HV_PhysAddr high_mapped_pa = node_end_pfn[i];
#endif
unsigned long pages = high_mapped_pa - node_start_pfn[i];
HV_VirtAddr addr = (HV_VirtAddr) __va(pa);
hv_store_mapping(addr, pages << PAGE_SHIFT, pa);
}
hv_store_mapping((HV_VirtAddr)_text,
(uint32_t)(_einittext - _text), 0);
}
/*
* Use hv_inquire_physical() to populate node_{start,end}_pfn[]
* and node_online_map, doing suitable sanity-checking.
* Also set min_low_pfn, max_low_pfn, and max_pfn.
*/
static void __init setup_memory(void)
{
int i, j;
int highbits_seen[NR_PA_HIGHBIT_VALUES] = { 0 };
#ifdef CONFIG_HIGHMEM
long highmem_pages;
#endif
#ifndef __tilegx__
int cap;
#endif
#if defined(CONFIG_HIGHMEM) || defined(__tilegx__)
long lowmem_pages;
#endif
unsigned long physpages = 0;
/* We are using a char to hold the cpu_2_node[] mapping */
BUILD_BUG_ON(MAX_NUMNODES > 127);
/* Discover the ranges of memory available to us */
for (i = 0; ; ++i) {
unsigned long start, size, end, highbits;
HV_PhysAddrRange range = hv_inquire_physical(i);
if (range.size == 0)
break;
#ifdef CONFIG_FLATMEM
if (i > 0) {
pr_err("Can't use discontiguous PAs: %#llx..%#llx\n",
range.size, range.start + range.size);
continue;
}
#endif
#ifndef __tilegx__
if ((unsigned long)range.start) {
pr_err("Range not at 4GB multiple: %#llx..%#llx\n",
range.start, range.start + range.size);
continue;
}
#endif
if ((range.start & (HPAGE_SIZE-1)) != 0 ||
(range.size & (HPAGE_SIZE-1)) != 0) {
unsigned long long start_pa = range.start;
unsigned long long orig_size = range.size;
range.start = (start_pa + HPAGE_SIZE - 1) & HPAGE_MASK;
range.size -= (range.start - start_pa);
range.size &= HPAGE_MASK;
pr_err("Range not hugepage-aligned: %#llx..%#llx:"
" now %#llx-%#llx\n",
start_pa, start_pa + orig_size,
range.start, range.start + range.size);
}
highbits = __pa_to_highbits(range.start);
if (highbits >= NR_PA_HIGHBIT_VALUES) {
pr_err("PA high bits too high: %#llx..%#llx\n",
range.start, range.start + range.size);
continue;
}
if (highbits_seen[highbits]) {
pr_err("Range overlaps in high bits: %#llx..%#llx\n",
range.start, range.start + range.size);
continue;
}
highbits_seen[highbits] = 1;
if (PFN_DOWN(range.size) > maxnodemem_pfn[i]) {
int max_size = maxnodemem_pfn[i];
if (max_size > 0) {
pr_err("Maxnodemem reduced node %d to"
" %d pages\n", i, max_size);
range.size = PFN_PHYS(max_size);
} else {
pr_err("Maxnodemem disabled node %d\n", i);
continue;
}
}
if (physpages + PFN_DOWN(range.size) > maxmem_pfn) {
int max_size = maxmem_pfn - physpages;
if (max_size > 0) {
pr_err("Maxmem reduced node %d to %d pages\n",
i, max_size);
range.size = PFN_PHYS(max_size);
} else {
pr_err("Maxmem disabled node %d\n", i);
continue;
}
}
if (i >= MAX_NUMNODES) {
pr_err("Too many PA nodes (#%d): %#llx...%#llx\n",
i, range.size, range.size + range.start);
continue;
}
start = range.start >> PAGE_SHIFT;
size = range.size >> PAGE_SHIFT;
end = start + size;
#ifndef __tilegx__
if (((HV_PhysAddr)end << PAGE_SHIFT) !=
(range.start + range.size)) {
pr_err("PAs too high to represent: %#llx..%#llx\n",
range.start, range.start + range.size);
continue;
}
#endif
#if defined(CONFIG_PCI) && !defined(__tilegx__)
/*
* Blocks that overlap the pci reserved region must
* have enough space to hold the maximum percpu data
* region at the top of the range. If there isn't
* enough space above the reserved region, just
* truncate the node.
*/
if (start <= pci_reserve_start_pfn &&
end > pci_reserve_start_pfn) {
unsigned int per_cpu_size =
__per_cpu_end - __per_cpu_start;
unsigned int percpu_pages =
NR_CPUS * (PFN_UP(per_cpu_size) >> PAGE_SHIFT);
if (end < pci_reserve_end_pfn + percpu_pages) {
end = pci_reserve_start_pfn;
pr_err("PCI mapping region reduced node %d to"
" %ld pages\n", i, end - start);
}
}
#endif
for (j = __pfn_to_highbits(start);
j <= __pfn_to_highbits(end - 1); j++)
highbits_to_node[j] = i;
node_start_pfn[i] = start;
node_end_pfn[i] = end;
node_controller[i] = range.controller;
physpages += size;
max_pfn = end;
/* Mark node as online */
node_set(i, node_online_map);
node_set(i, node_possible_map);
}
#ifndef __tilegx__
/*
* For 4KB pages, mem_map "struct page" data is 1% of the size
* of the physical memory, so can be quite big (640 MB for
* four 16G zones). These structures must be mapped in
* lowmem, and since we currently cap out at about 768 MB,
* it's impractical to try to use this much address space.
* For now, arbitrarily cap the amount of physical memory
* we're willing to use at 8 million pages (32GB of 4KB pages).
*/
cap = 8 * 1024 * 1024; /* 8 million pages */
if (physpages > cap) {
int num_nodes = num_online_nodes();
int cap_each = cap / num_nodes;
unsigned long dropped_pages = 0;
for (i = 0; i < num_nodes; ++i) {
int size = node_end_pfn[i] - node_start_pfn[i];
if (size > cap_each) {
dropped_pages += (size - cap_each);
node_end_pfn[i] = node_start_pfn[i] + cap_each;
}
}
physpages -= dropped_pages;
pr_warning("Only using %ldMB memory;"
" ignoring %ldMB.\n",
physpages >> (20 - PAGE_SHIFT),
dropped_pages >> (20 - PAGE_SHIFT));
pr_warning("Consider using a larger page size.\n");
}
#endif
/* Heap starts just above the last loaded address. */
min_low_pfn = PFN_UP((unsigned long)_end - PAGE_OFFSET);
#ifdef CONFIG_HIGHMEM
/* Find where we map lowmem from each controller. */
high_memory = setup_pa_va_mapping();
/* Set max_low_pfn based on what node 0 can directly address. */
max_low_pfn = node_lowmem_end_pfn[0];
lowmem_pages = (mappable_physpages > MAXMEM_PFN) ?
MAXMEM_PFN : mappable_physpages;
highmem_pages = (long) (physpages - lowmem_pages);
pr_notice("%ldMB HIGHMEM available.\n",
pages_to_mb(highmem_pages > 0 ? highmem_pages : 0));
pr_notice("%ldMB LOWMEM available.\n",
pages_to_mb(lowmem_pages));
#else
/* Set max_low_pfn based on what node 0 can directly address. */
max_low_pfn = node_end_pfn[0];
#ifndef __tilegx__
if (node_end_pfn[0] > MAXMEM_PFN) {
pr_warning("Only using %ldMB LOWMEM.\n",
MAXMEM>>20);
pr_warning("Use a HIGHMEM enabled kernel.\n");
max_low_pfn = MAXMEM_PFN;
max_pfn = MAXMEM_PFN;
node_end_pfn[0] = MAXMEM_PFN;
} else {
pr_notice("%ldMB memory available.\n",
pages_to_mb(node_end_pfn[0]));
}
for (i = 1; i < MAX_NUMNODES; ++i) {
node_start_pfn[i] = 0;
node_end_pfn[i] = 0;
}
high_memory = __va(node_end_pfn[0]);
#else
lowmem_pages = 0;
for (i = 0; i < MAX_NUMNODES; ++i) {
int pages = node_end_pfn[i] - node_start_pfn[i];
lowmem_pages += pages;
if (pages)
high_memory = pfn_to_kaddr(node_end_pfn[i]);
}
pr_notice("%ldMB memory available.\n",
pages_to_mb(lowmem_pages));
#endif
#endif
}
/*
* On 32-bit machines, we only put bootmem on the low controller,
* since PAs > 4GB can't be used in bootmem. In principle one could
* imagine, e.g., multiple 1 GB controllers all of which could support
* bootmem, but in practice using controllers this small isn't a
* particularly interesting scenario, so we just keep it simple and
* use only the first controller for bootmem on 32-bit machines.
*/
static inline int node_has_bootmem(int nid)
{
#ifdef CONFIG_64BIT
return 1;
#else
return nid == 0;
#endif
}
static inline unsigned long alloc_bootmem_pfn(int nid,
unsigned long size,
unsigned long goal)
{
void *kva = __alloc_bootmem_node(NODE_DATA(nid), size,
PAGE_SIZE, goal);
unsigned long pfn = kaddr_to_pfn(kva);
BUG_ON(goal && PFN_PHYS(pfn) != goal);
return pfn;
}
static void __init setup_bootmem_allocator_node(int i)
{
unsigned long start, end, mapsize, mapstart;
if (node_has_bootmem(i)) {
NODE_DATA(i)->bdata = &bootmem_node_data[i];
} else {
/* Share controller zero's bdata for now. */
NODE_DATA(i)->bdata = &bootmem_node_data[0];
return;
}
/* Skip up to after the bss in node 0. */
start = (i == 0) ? min_low_pfn : node_start_pfn[i];
/* Only lowmem, if we're a HIGHMEM build. */
#ifdef CONFIG_HIGHMEM
end = node_lowmem_end_pfn[i];
#else
end = node_end_pfn[i];
#endif
/* No memory here. */
if (end == start)
return;
/* Figure out where the bootmem bitmap is located. */
mapsize = bootmem_bootmap_pages(end - start);
if (i == 0) {
/* Use some space right before the heap on node 0. */
mapstart = start;
start += mapsize;
} else {
/* Allocate bitmap on node 0 to avoid page table issues. */
mapstart = alloc_bootmem_pfn(0, PFN_PHYS(mapsize), 0);
}
/* Initialize a node. */
init_bootmem_node(NODE_DATA(i), mapstart, start, end);
/* Free all the space back into the allocator. */
free_bootmem(PFN_PHYS(start), PFN_PHYS(end - start));
#if defined(CONFIG_PCI) && !defined(__tilegx__)
/*
* Throw away any memory aliased by the PCI region.
*/
if (pci_reserve_start_pfn < end && pci_reserve_end_pfn > start) {
start = max(pci_reserve_start_pfn, start);
end = min(pci_reserve_end_pfn, end);
reserve_bootmem(PFN_PHYS(start), PFN_PHYS(end - start),
BOOTMEM_EXCLUSIVE);
}
#endif
}
static void __init setup_bootmem_allocator(void)
{
int i;
for (i = 0; i < MAX_NUMNODES; ++i)
setup_bootmem_allocator_node(i);
/* Reserve any memory excluded by "memmap" arguments. */
for (i = 0; i < memmap_nr; ++i) {
struct memmap_entry *m = &memmap_map[i];
reserve_bootmem(m->addr, m->size, BOOTMEM_DEFAULT);
}
#ifdef CONFIG_BLK_DEV_INITRD
if (initrd_start) {
/* Make sure the initrd memory region is not modified. */
if (reserve_bootmem(initrd_start, initrd_end - initrd_start,
BOOTMEM_EXCLUSIVE)) {
pr_crit("The initrd memory region has been polluted. Disabling it.\n");
initrd_start = 0;
initrd_end = 0;
} else {
/*
* Translate initrd_start & initrd_end from PA to VA for
* future access.
*/
initrd_start += PAGE_OFFSET;
initrd_end += PAGE_OFFSET;
}
}
#endif
#ifdef CONFIG_KEXEC
if (crashk_res.start != crashk_res.end)
reserve_bootmem(crashk_res.start, resource_size(&crashk_res),
BOOTMEM_DEFAULT);
#endif
}
void *__init alloc_remap(int nid, unsigned long size)
{
int pages = node_end_pfn[nid] - node_start_pfn[nid];
void *map = pfn_to_kaddr(node_memmap_pfn[nid]);
BUG_ON(size != pages * sizeof(struct page));
memset(map, 0, size);
return map;
}
static int __init percpu_size(void)
{
int size = __per_cpu_end - __per_cpu_start;
size += PERCPU_MODULE_RESERVE;
size += PERCPU_DYNAMIC_EARLY_SIZE;
if (size < PCPU_MIN_UNIT_SIZE)
size = PCPU_MIN_UNIT_SIZE;
size = roundup(size, PAGE_SIZE);
/* In several places we assume the per-cpu data fits on a huge page. */
BUG_ON(kdata_huge && size > HPAGE_SIZE);
return size;
}
static void __init zone_sizes_init(void)
{
unsigned long zones_size[MAX_NR_ZONES] = { 0 };
int size = percpu_size();
int num_cpus = smp_height * smp_width;
const unsigned long dma_end = (1UL << (32 - PAGE_SHIFT));
int i;
for (i = 0; i < num_cpus; ++i)
node_percpu[cpu_to_node(i)] += size;
for_each_online_node(i) {
unsigned long start = node_start_pfn[i];
unsigned long end = node_end_pfn[i];
#ifdef CONFIG_HIGHMEM
unsigned long lowmem_end = node_lowmem_end_pfn[i];
#else
unsigned long lowmem_end = end;
#endif
int memmap_size = (end - start) * sizeof(struct page);
node_free_pfn[i] = start;
/*
* Set aside pages for per-cpu data and the mem_map array.
*
* Since the per-cpu data requires special homecaching,
* if we are in kdata_huge mode, we put it at the end of
* the lowmem region. If we're not in kdata_huge mode,
* we take the per-cpu pages from the bottom of the
* controller, since that avoids fragmenting a huge page
* that users might want. We always take the memmap
* from the bottom of the controller, since with
* kdata_huge that lets it be under a huge TLB entry.
*
* If the user has requested isolnodes for a controller,
* though, there'll be no lowmem, so we just alloc_bootmem
* the memmap. There will be no percpu memory either.
*/
if (i != 0 && cpu_isset(i, isolnodes)) {
node_memmap_pfn[i] =
alloc_bootmem_pfn(0, memmap_size, 0);
BUG_ON(node_percpu[i] != 0);
} else if (node_has_bootmem(start)) {
unsigned long goal = 0;
node_memmap_pfn[i] =
alloc_bootmem_pfn(i, memmap_size, 0);
if (kdata_huge)
goal = PFN_PHYS(lowmem_end) - node_percpu[i];
if (node_percpu[i])
node_percpu_pfn[i] =
alloc_bootmem_pfn(i, node_percpu[i],
goal);
} else {
/* In non-bootmem zones, just reserve some pages. */
node_memmap_pfn[i] = node_free_pfn[i];
node_free_pfn[i] += PFN_UP(memmap_size);
if (!kdata_huge) {
node_percpu_pfn[i] = node_free_pfn[i];
node_free_pfn[i] += PFN_UP(node_percpu[i]);
} else {
node_percpu_pfn[i] =
lowmem_end - PFN_UP(node_percpu[i]);
}
}
#ifdef CONFIG_HIGHMEM
if (start > lowmem_end) {
zones_size[ZONE_NORMAL] = 0;
zones_size[ZONE_HIGHMEM] = end - start;
} else {
zones_size[ZONE_NORMAL] = lowmem_end - start;
zones_size[ZONE_HIGHMEM] = end - lowmem_end;
}
#else
zones_size[ZONE_NORMAL] = end - start;
#endif
if (start < dma_end) {
zones_size[ZONE_DMA] = min(zones_size[ZONE_NORMAL],
dma_end - start);
zones_size[ZONE_NORMAL] -= zones_size[ZONE_DMA];
} else {
zones_size[ZONE_DMA] = 0;
}
/* Take zone metadata from controller 0 if we're isolnode. */
if (node_isset(i, isolnodes))
NODE_DATA(i)->bdata = &bootmem_node_data[0];
free_area_init_node(i, zones_size, start, NULL);
printk(KERN_DEBUG " Normal zone: %ld per-cpu pages\n",
PFN_UP(node_percpu[i]));
/* Track the type of memory on each node */
if (zones_size[ZONE_NORMAL] || zones_size[ZONE_DMA])
node_set_state(i, N_NORMAL_MEMORY);
#ifdef CONFIG_HIGHMEM
if (end != start)
node_set_state(i, N_HIGH_MEMORY);
#endif
node_set_online(i);
}
}
#ifdef CONFIG_NUMA
/* which logical CPUs are on which nodes */
struct cpumask node_2_cpu_mask[MAX_NUMNODES] __write_once;
EXPORT_SYMBOL(node_2_cpu_mask);
/* which node each logical CPU is on */
char cpu_2_node[NR_CPUS] __write_once __attribute__((aligned(L2_CACHE_BYTES)));
EXPORT_SYMBOL(cpu_2_node);
/* Return cpu_to_node() except for cpus not yet assigned, which return -1 */
static int __init cpu_to_bound_node(int cpu, struct cpumask* unbound_cpus)
{
if (!cpu_possible(cpu) || cpumask_test_cpu(cpu, unbound_cpus))
return -1;
else
return cpu_to_node(cpu);
}
/* Return number of immediately-adjacent tiles sharing the same NUMA node. */
static int __init node_neighbors(int node, int cpu,
struct cpumask *unbound_cpus)
{
int neighbors = 0;
int w = smp_width;
int h = smp_height;
int x = cpu % w;
int y = cpu / w;
if (x > 0 && cpu_to_bound_node(cpu-1, unbound_cpus) == node)
++neighbors;
if (x < w-1 && cpu_to_bound_node(cpu+1, unbound_cpus) == node)
++neighbors;
if (y > 0 && cpu_to_bound_node(cpu-w, unbound_cpus) == node)
++neighbors;
if (y < h-1 && cpu_to_bound_node(cpu+w, unbound_cpus) == node)
++neighbors;
return neighbors;
}
static void __init setup_numa_mapping(void)
{
int distance[MAX_NUMNODES][NR_CPUS];
HV_Coord coord;
int cpu, node, cpus, i, x, y;
int num_nodes = num_online_nodes();
struct cpumask unbound_cpus;
nodemask_t default_nodes;
cpumask_clear(&unbound_cpus);
/* Get set of nodes we will use for defaults */
nodes_andnot(default_nodes, node_online_map, isolnodes);
if (nodes_empty(default_nodes)) {
BUG_ON(!node_isset(0, node_online_map));
pr_err("Forcing NUMA node zero available as a default node\n");
node_set(0, default_nodes);
}
/* Populate the distance[] array */
memset(distance, -1, sizeof(distance));
cpu = 0;
for (coord.y = 0; coord.y < smp_height; ++coord.y) {
for (coord.x = 0; coord.x < smp_width;
++coord.x, ++cpu) {
BUG_ON(cpu >= nr_cpu_ids);
if (!cpu_possible(cpu)) {
cpu_2_node[cpu] = -1;
continue;
}
for_each_node_mask(node, default_nodes) {
HV_MemoryControllerInfo info =
hv_inquire_memory_controller(
coord, node_controller[node]);
distance[node][cpu] =
ABS(info.coord.x) + ABS(info.coord.y);
}
cpumask_set_cpu(cpu, &unbound_cpus);
}
}
cpus = cpu;
/*
* Round-robin through the NUMA nodes until all the cpus are
* assigned. We could be more clever here (e.g. create four
* sorted linked lists on the same set of cpu nodes, and pull
* off them in round-robin sequence, removing from all four
* lists each time) but given the relatively small numbers
* involved, O(n^2) seem OK for a one-time cost.
*/
node = first_node(default_nodes);
while (!cpumask_empty(&unbound_cpus)) {
int best_cpu = -1;
int best_distance = INT_MAX;
for (cpu = 0; cpu < cpus; ++cpu) {
if (cpumask_test_cpu(cpu, &unbound_cpus)) {
/*
* Compute metric, which is how much
* closer the cpu is to this memory
* controller than the others, shifted
* up, and then the number of
* neighbors already in the node as an
* epsilon adjustment to try to keep
* the nodes compact.
*/
int d = distance[node][cpu] * num_nodes;
for_each_node_mask(i, default_nodes) {
if (i != node)
d -= distance[i][cpu];
}
d *= 8; /* allow space for epsilon */
d -= node_neighbors(node, cpu, &unbound_cpus);
if (d < best_distance) {
best_cpu = cpu;
best_distance = d;
}
}
}
BUG_ON(best_cpu < 0);
cpumask_set_cpu(best_cpu, &node_2_cpu_mask[node]);
cpu_2_node[best_cpu] = node;
cpumask_clear_cpu(best_cpu, &unbound_cpus);
node = next_node(node, default_nodes);
if (node == MAX_NUMNODES)
node = first_node(default_nodes);
}
/* Print out node assignments and set defaults for disabled cpus */
cpu = 0;
for (y = 0; y < smp_height; ++y) {
printk(KERN_DEBUG "NUMA cpu-to-node row %d:", y);
for (x = 0; x < smp_width; ++x, ++cpu) {
if (cpu_to_node(cpu) < 0) {
pr_cont(" -");
cpu_2_node[cpu] = first_node(default_nodes);
} else {
pr_cont(" %d", cpu_to_node(cpu));
}
}
pr_cont("\n");
}
}
static struct cpu cpu_devices[NR_CPUS];
static int __init topology_init(void)
{
int i;
for_each_online_node(i)
register_one_node(i);
for (i = 0; i < smp_height * smp_width; ++i)
register_cpu(&cpu_devices[i], i);
return 0;
}
subsys_initcall(topology_init);
#else /* !CONFIG_NUMA */
#define setup_numa_mapping() do { } while (0)
#endif /* CONFIG_NUMA */
/*
* Initialize hugepage support on this cpu. We do this on all cores
* early in boot: before argument parsing for the boot cpu, and after
* argument parsing but before the init functions run on the secondaries.
* So the values we set up here in the hypervisor may be overridden on
* the boot cpu as arguments are parsed.
*/
static void init_super_pages(void)
{
#ifdef CONFIG_HUGETLB_SUPER_PAGES
int i;
for (i = 0; i < HUGE_SHIFT_ENTRIES; ++i)
hv_set_pte_super_shift(i, huge_shift[i]);
#endif
}
/**
* setup_cpu() - Do all necessary per-cpu, tile-specific initialization.
* @boot: Is this the boot cpu?
*
* Called from setup_arch() on the boot cpu, or online_secondary().
*/
void setup_cpu(int boot)
{
/* The boot cpu sets up its permanent mappings much earlier. */
if (!boot)
store_permanent_mappings();
/* Allow asynchronous TLB interrupts. */
#if CHIP_HAS_TILE_DMA()
arch_local_irq_unmask(INT_DMATLB_MISS);
arch_local_irq_unmask(INT_DMATLB_ACCESS);
#endif
#ifdef __tilegx__
arch_local_irq_unmask(INT_SINGLE_STEP_K);
#endif
/*
* Allow user access to many generic SPRs, like the cycle
* counter, PASS/FAIL/DONE, INTERRUPT_CRITICAL_SECTION, etc.
*/
__insn_mtspr(SPR_MPL_WORLD_ACCESS_SET_0, 1);
#if CHIP_HAS_SN()
/* Static network is not restricted. */
__insn_mtspr(SPR_MPL_SN_ACCESS_SET_0, 1);
#endif
/*
* Set the MPL for interrupt control 0 & 1 to the corresponding
* values. This includes access to the SYSTEM_SAVE and EX_CONTEXT
* SPRs, as well as the interrupt mask.
*/
__insn_mtspr(SPR_MPL_INTCTRL_0_SET_0, 1);
__insn_mtspr(SPR_MPL_INTCTRL_1_SET_1, 1);
/* Initialize IRQ support for this cpu. */
setup_irq_regs();
#ifdef CONFIG_HARDWALL
/* Reset the network state on this cpu. */
reset_network_state();
#endif
init_super_pages();
}
#ifdef CONFIG_BLK_DEV_INITRD
static int __initdata set_initramfs_file;
static char __initdata initramfs_file[128] = "initramfs";
static int __init setup_initramfs_file(char *str)
{
if (str == NULL)
return -EINVAL;
strncpy(initramfs_file, str, sizeof(initramfs_file) - 1);
set_initramfs_file = 1;
return 0;
}
early_param("initramfs_file", setup_initramfs_file);
/*
* We look for a file called "initramfs" in the hvfs. If there is one, we
* allocate some memory for it and it will be unpacked to the initramfs.
* If it's compressed, the initd code will uncompress it first.
*/
static void __init load_hv_initrd(void)
{
HV_FS_StatInfo stat;
int fd, rc;
void *initrd;
/* If initrd has already been set, skip initramfs file in hvfs. */
if (initrd_start)
return;
fd = hv_fs_findfile((HV_VirtAddr) initramfs_file);
if (fd == HV_ENOENT) {
if (set_initramfs_file) {
pr_warning("No such hvfs initramfs file '%s'\n",
initramfs_file);
return;
} else {
/* Try old backwards-compatible name. */
fd = hv_fs_findfile((HV_VirtAddr)"initramfs.cpio.gz");
if (fd == HV_ENOENT)
return;
}
}
BUG_ON(fd < 0);
stat = hv_fs_fstat(fd);
BUG_ON(stat.size < 0);
if (stat.flags & HV_FS_ISDIR) {
pr_warning("Ignoring hvfs file '%s': it's a directory.\n",
initramfs_file);
return;
}
initrd = alloc_bootmem_pages(stat.size);
rc = hv_fs_pread(fd, (HV_VirtAddr) initrd, stat.size, 0);
if (rc != stat.size) {
pr_err("Error reading %d bytes from hvfs file '%s': %d\n",
stat.size, initramfs_file, rc);
free_initrd_mem((unsigned long) initrd, stat.size);
return;
}
initrd_start = (unsigned long) initrd;
initrd_end = initrd_start + stat.size;
}
void __init free_initrd_mem(unsigned long begin, unsigned long end)
{
free_bootmem(__pa(begin), end - begin);
}
static int __init setup_initrd(char *str)
{
char *endp;
unsigned long initrd_size;
initrd_size = str ? simple_strtoul(str, &endp, 0) : 0;
if (initrd_size == 0 || *endp != '@')
return -EINVAL;
initrd_start = simple_strtoul(endp+1, &endp, 0);
if (initrd_start == 0)
return -EINVAL;
initrd_end = initrd_start + initrd_size;
return 0;
}
early_param("initrd", setup_initrd);
#else
static inline void load_hv_initrd(void) {}
#endif /* CONFIG_BLK_DEV_INITRD */
static void __init validate_hv(void)
{
/*
* It may already be too late, but let's check our built-in
* configuration against what the hypervisor is providing.
*/
unsigned long glue_size = hv_sysconf(HV_SYSCONF_GLUE_SIZE);
int hv_page_size = hv_sysconf(HV_SYSCONF_PAGE_SIZE_SMALL);
int hv_hpage_size = hv_sysconf(HV_SYSCONF_PAGE_SIZE_LARGE);
HV_ASIDRange asid_range;
#ifndef CONFIG_SMP
HV_Topology topology = hv_inquire_topology();
BUG_ON(topology.coord.x != 0 || topology.coord.y != 0);
if (topology.width != 1 || topology.height != 1) {
pr_warning("Warning: booting UP kernel on %dx%d grid;"
" will ignore all but first tile.\n",
topology.width, topology.height);
}
#endif
if (PAGE_OFFSET + HV_GLUE_START_CPA + glue_size > (unsigned long)_text)
early_panic("Hypervisor glue size %ld is too big!\n",
glue_size);
if (hv_page_size != PAGE_SIZE)
early_panic("Hypervisor page size %#x != our %#lx\n",
hv_page_size, PAGE_SIZE);
if (hv_hpage_size != HPAGE_SIZE)
early_panic("Hypervisor huge page size %#x != our %#lx\n",
hv_hpage_size, HPAGE_SIZE);
#ifdef CONFIG_SMP
/*
* Some hypervisor APIs take a pointer to a bitmap array
* whose size is at least the number of cpus on the chip.
* We use a struct cpumask for this, so it must be big enough.
*/
if ((smp_height * smp_width) > nr_cpu_ids)
early_panic("Hypervisor %d x %d grid too big for Linux"
" NR_CPUS %d\n", smp_height, smp_width,
nr_cpu_ids);
#endif
/*
* Check that we're using allowed ASIDs, and initialize the
* various asid variables to their appropriate initial states.
*/
asid_range = hv_inquire_asid(0);
min_asid = asid_range.start;
__this_cpu_write(current_asid, min_asid);
max_asid = asid_range.start + asid_range.size - 1;
if (hv_confstr(HV_CONFSTR_CHIP_MODEL, (HV_VirtAddr)chip_model,
sizeof(chip_model)) < 0) {
pr_err("Warning: HV_CONFSTR_CHIP_MODEL not available\n");
strlcpy(chip_model, "unknown", sizeof(chip_model));
}
}
static void __init validate_va(void)
{
#ifndef __tilegx__ /* FIXME: GX: probably some validation relevant here */
/*
* Similarly, make sure we're only using allowed VAs.
* We assume we can contiguously use MEM_USER_INTRPT .. MEM_HV_START,
* and 0 .. KERNEL_HIGH_VADDR.
* In addition, make sure we CAN'T use the end of memory, since
* we use the last chunk of each pgd for the pgd_list.
*/
int i, user_kernel_ok = 0;
unsigned long max_va = 0;
unsigned long list_va =
((PGD_LIST_OFFSET / sizeof(pgd_t)) << PGDIR_SHIFT);
for (i = 0; ; ++i) {
HV_VirtAddrRange range = hv_inquire_virtual(i);
if (range.size == 0)
break;
if (range.start <= MEM_USER_INTRPT &&
range.start + range.size >= MEM_HV_START)
user_kernel_ok = 1;
if (range.start == 0)
max_va = range.size;
BUG_ON(range.start + range.size > list_va);
}
if (!user_kernel_ok)
early_panic("Hypervisor not configured for user/kernel VAs\n");
if (max_va == 0)
early_panic("Hypervisor not configured for low VAs\n");
if (max_va < KERNEL_HIGH_VADDR)
early_panic("Hypervisor max VA %#lx smaller than %#lx\n",
max_va, KERNEL_HIGH_VADDR);
/* Kernel PCs must have their high bit set; see intvec.S. */
if ((long)VMALLOC_START >= 0)
early_panic(
"Linux VMALLOC region below the 2GB line (%#lx)!\n"
"Reconfigure the kernel with smaller VMALLOC_RESERVE.\n",
VMALLOC_START);
#endif
}
/*
* cpu_lotar_map lists all the cpus that are valid for the supervisor
* to cache data on at a page level, i.e. what cpus can be placed in
* the LOTAR field of a PTE. It is equivalent to the set of possible
* cpus plus any other cpus that are willing to share their cache.
* It is set by hv_inquire_tiles(HV_INQ_TILES_LOTAR).
*/
struct cpumask __write_once cpu_lotar_map;
EXPORT_SYMBOL(cpu_lotar_map);
/*
* hash_for_home_map lists all the tiles that hash-for-home data
* will be cached on. Note that this may includes tiles that are not
* valid for this supervisor to use otherwise (e.g. if a hypervisor
* device is being shared between multiple supervisors).
* It is set by hv_inquire_tiles(HV_INQ_TILES_HFH_CACHE).
*/
struct cpumask hash_for_home_map;
EXPORT_SYMBOL(hash_for_home_map);
/*
* cpu_cacheable_map lists all the cpus whose caches the hypervisor can
* flush on our behalf. It is set to cpu_possible_mask OR'ed with
* hash_for_home_map, and it is what should be passed to
* hv_flush_remote() to flush all caches. Note that if there are
* dedicated hypervisor driver tiles that have authorized use of their
* cache, those tiles will only appear in cpu_lotar_map, NOT in
* cpu_cacheable_map, as they are a special case.
*/
struct cpumask __write_once cpu_cacheable_map;
EXPORT_SYMBOL(cpu_cacheable_map);
static __initdata struct cpumask disabled_map;
static int __init disabled_cpus(char *str)
{
int boot_cpu = smp_processor_id();
if (str == NULL || cpulist_parse_crop(str, &disabled_map) != 0)
return -EINVAL;
if (cpumask_test_cpu(boot_cpu, &disabled_map)) {
pr_err("disabled_cpus: can't disable boot cpu %d\n", boot_cpu);
cpumask_clear_cpu(boot_cpu, &disabled_map);
}
return 0;
}
early_param("disabled_cpus", disabled_cpus);
void __init print_disabled_cpus(void)
{
if (!cpumask_empty(&disabled_map)) {
char buf[100];
cpulist_scnprintf(buf, sizeof(buf), &disabled_map);
pr_info("CPUs not available for Linux: %s\n", buf);
}
}
static void __init setup_cpu_maps(void)
{
struct cpumask hv_disabled_map, cpu_possible_init;
int boot_cpu = smp_processor_id();
int cpus, i, rc;
/* Learn which cpus are allowed by the hypervisor. */
rc = hv_inquire_tiles(HV_INQ_TILES_AVAIL,
(HV_VirtAddr) cpumask_bits(&cpu_possible_init),
sizeof(cpu_cacheable_map));
if (rc < 0)
early_panic("hv_inquire_tiles(AVAIL) failed: rc %d\n", rc);
if (!cpumask_test_cpu(boot_cpu, &cpu_possible_init))
early_panic("Boot CPU %d disabled by hypervisor!\n", boot_cpu);
/* Compute the cpus disabled by the hvconfig file. */
cpumask_complement(&hv_disabled_map, &cpu_possible_init);
/* Include them with the cpus disabled by "disabled_cpus". */
cpumask_or(&disabled_map, &disabled_map, &hv_disabled_map);
/*
* Disable every cpu after "setup_max_cpus". But don't mark
* as disabled the cpus that are outside of our initial rectangle,
* since that turns out to be confusing.
*/
cpus = 1; /* this cpu */
cpumask_set_cpu(boot_cpu, &disabled_map); /* ignore this cpu */
for (i = 0; cpus < setup_max_cpus; ++i)
if (!cpumask_test_cpu(i, &disabled_map))
++cpus;
for (; i < smp_height * smp_width; ++i)
cpumask_set_cpu(i, &disabled_map);
cpumask_clear_cpu(boot_cpu, &disabled_map); /* reset this cpu */
for (i = smp_height * smp_width; i < NR_CPUS; ++i)
cpumask_clear_cpu(i, &disabled_map);
/*
* Setup cpu_possible map as every cpu allocated to us, minus
* the results of any "disabled_cpus" settings.
*/
cpumask_andnot(&cpu_possible_init, &cpu_possible_init, &disabled_map);
init_cpu_possible(&cpu_possible_init);
/* Learn which cpus are valid for LOTAR caching. */
rc = hv_inquire_tiles(HV_INQ_TILES_LOTAR,
(HV_VirtAddr) cpumask_bits(&cpu_lotar_map),
sizeof(cpu_lotar_map));
if (rc < 0) {
pr_err("warning: no HV_INQ_TILES_LOTAR; using AVAIL\n");
cpu_lotar_map = *cpu_possible_mask;
}
/* Retrieve set of CPUs used for hash-for-home caching */
rc = hv_inquire_tiles(HV_INQ_TILES_HFH_CACHE,
(HV_VirtAddr) hash_for_home_map.bits,
sizeof(hash_for_home_map));
if (rc < 0)
early_panic("hv_inquire_tiles(HFH_CACHE) failed: rc %d\n", rc);
cpumask_or(&cpu_cacheable_map, cpu_possible_mask, &hash_for_home_map);
}
static int __init dataplane(char *str)
{
pr_warning("WARNING: dataplane support disabled in this kernel\n");
return 0;
}
early_param("dataplane", dataplane);
#ifdef CONFIG_CMDLINE_BOOL
static char __initdata builtin_cmdline[COMMAND_LINE_SIZE] = CONFIG_CMDLINE;
#endif
void __init setup_arch(char **cmdline_p)
{
int len;
#if defined(CONFIG_CMDLINE_BOOL) && defined(CONFIG_CMDLINE_OVERRIDE)
len = hv_get_command_line((HV_VirtAddr) boot_command_line,
COMMAND_LINE_SIZE);
if (boot_command_line[0])
pr_warning("WARNING: ignoring dynamic command line \"%s\"\n",
boot_command_line);
strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE);
#else
char *hv_cmdline;
#if defined(CONFIG_CMDLINE_BOOL)
if (builtin_cmdline[0]) {
int builtin_len = strlcpy(boot_command_line, builtin_cmdline,
COMMAND_LINE_SIZE);
if (builtin_len < COMMAND_LINE_SIZE-1)
boot_command_line[builtin_len++] = ' ';
hv_cmdline = &boot_command_line[builtin_len];
len = COMMAND_LINE_SIZE - builtin_len;
} else
#endif
{
hv_cmdline = boot_command_line;
len = COMMAND_LINE_SIZE;
}
len = hv_get_command_line((HV_VirtAddr) hv_cmdline, len);
if (len < 0 || len > COMMAND_LINE_SIZE)
early_panic("hv_get_command_line failed: %d\n", len);
#endif
*cmdline_p = boot_command_line;
/* Set disabled_map and setup_max_cpus very early */
parse_early_param();
/* Make sure the kernel is compatible with the hypervisor. */
validate_hv();
validate_va();
setup_cpu_maps();
#if defined(CONFIG_PCI) && !defined(__tilegx__)
/*
* Initialize the PCI structures. This is done before memory
* setup so that we know whether or not a pci_reserve region
* is necessary.
*/
if (tile_pci_init() == 0)
pci_reserve_mb = 0;
/* PCI systems reserve a region just below 4GB for mapping iomem. */
pci_reserve_end_pfn = (1 << (32 - PAGE_SHIFT));
pci_reserve_start_pfn = pci_reserve_end_pfn -
(pci_reserve_mb << (20 - PAGE_SHIFT));
#endif
init_mm.start_code = (unsigned long) _text;
init_mm.end_code = (unsigned long) _etext;
init_mm.end_data = (unsigned long) _edata;
init_mm.brk = (unsigned long) _end;
setup_memory();
store_permanent_mappings();
setup_bootmem_allocator();
/*
* NOTE: before this point _nobody_ is allowed to allocate
* any memory using the bootmem allocator.
*/
#ifdef CONFIG_SWIOTLB
swiotlb_init(0);
#endif
paging_init();
setup_numa_mapping();
zone_sizes_init();
set_page_homes();
setup_cpu(1);
setup_clock();
load_hv_initrd();
}
/*
* Set up per-cpu memory.
*/
unsigned long __per_cpu_offset[NR_CPUS] __write_once;
EXPORT_SYMBOL(__per_cpu_offset);
static size_t __initdata pfn_offset[MAX_NUMNODES] = { 0 };
static unsigned long __initdata percpu_pfn[NR_CPUS] = { 0 };
/*
* As the percpu code allocates pages, we return the pages from the
* end of the node for the specified cpu.
*/
static void *__init pcpu_fc_alloc(unsigned int cpu, size_t size, size_t align)
{
int nid = cpu_to_node(cpu);
unsigned long pfn = node_percpu_pfn[nid] + pfn_offset[nid];
BUG_ON(size % PAGE_SIZE != 0);
pfn_offset[nid] += size / PAGE_SIZE;
BUG_ON(node_percpu[nid] < size);
node_percpu[nid] -= size;
if (percpu_pfn[cpu] == 0)
percpu_pfn[cpu] = pfn;
return pfn_to_kaddr(pfn);
}
/*
* Pages reserved for percpu memory are not freeable, and in any case we are
* on a short path to panic() in setup_per_cpu_area() at this point anyway.
*/
static void __init pcpu_fc_free(void *ptr, size_t size)
{
}
/*
* Set up vmalloc page tables using bootmem for the percpu code.
*/
static void __init pcpu_fc_populate_pte(unsigned long addr)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
BUG_ON(pgd_addr_invalid(addr));
if (addr < VMALLOC_START || addr >= VMALLOC_END)
panic("PCPU addr %#lx outside vmalloc range %#lx..%#lx;"
" try increasing CONFIG_VMALLOC_RESERVE\n",
addr, VMALLOC_START, VMALLOC_END);
pgd = swapper_pg_dir + pgd_index(addr);
pud = pud_offset(pgd, addr);
BUG_ON(!pud_present(*pud));
pmd = pmd_offset(pud, addr);
if (pmd_present(*pmd)) {
BUG_ON(pmd_huge_page(*pmd));
} else {
pte = __alloc_bootmem(L2_KERNEL_PGTABLE_SIZE,
HV_PAGE_TABLE_ALIGN, 0);
pmd_populate_kernel(&init_mm, pmd, pte);
}
}
void __init setup_per_cpu_areas(void)
{
struct page *pg;
unsigned long delta, pfn, lowmem_va;
unsigned long size = percpu_size();
char *ptr;
int rc, cpu, i;
rc = pcpu_page_first_chunk(PERCPU_MODULE_RESERVE, pcpu_fc_alloc,
pcpu_fc_free, pcpu_fc_populate_pte);
if (rc < 0)
panic("Cannot initialize percpu area (err=%d)", rc);
delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
for_each_possible_cpu(cpu) {
__per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
/* finv the copy out of cache so we can change homecache */
ptr = pcpu_base_addr + pcpu_unit_offsets[cpu];
__finv_buffer(ptr, size);
pfn = percpu_pfn[cpu];
/* Rewrite the page tables to cache on that cpu */
pg = pfn_to_page(pfn);
for (i = 0; i < size; i += PAGE_SIZE, ++pfn, ++pg) {
/* Update the vmalloc mapping and page home. */
unsigned long addr = (unsigned long)ptr + i;
pte_t *ptep = virt_to_kpte(addr);
pte_t pte = *ptep;
BUG_ON(pfn != pte_pfn(pte));
pte = hv_pte_set_mode(pte, HV_PTE_MODE_CACHE_TILE_L3);
pte = set_remote_cache_cpu(pte, cpu);
set_pte_at(&init_mm, addr, ptep, pte);
/* Update the lowmem mapping for consistency. */
lowmem_va = (unsigned long)pfn_to_kaddr(pfn);
ptep = virt_to_kpte(lowmem_va);
if (pte_huge(*ptep)) {
printk(KERN_DEBUG "early shatter of huge page"
" at %#lx\n", lowmem_va);
shatter_pmd((pmd_t *)ptep);
ptep = virt_to_kpte(lowmem_va);
BUG_ON(pte_huge(*ptep));
}
BUG_ON(pfn != pte_pfn(*ptep));
set_pte_at(&init_mm, lowmem_va, ptep, pte);
}
}
/* Set our thread pointer appropriately. */
set_my_cpu_offset(__per_cpu_offset[smp_processor_id()]);
/* Make sure the finv's have completed. */
mb_incoherent();
/* Flush the TLB so we reference it properly from here on out. */
local_flush_tlb_all();
}
static struct resource data_resource = {
.name = "Kernel data",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
static struct resource code_resource = {
.name = "Kernel code",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
/*
* On Pro, we reserve all resources above 4GB so that PCI won't try to put
* mappings above 4GB.
*/
#if defined(CONFIG_PCI) && !defined(__tilegx__)
static struct resource* __init
insert_non_bus_resource(void)
{
struct resource *res =
kzalloc(sizeof(struct resource), GFP_ATOMIC);
if (!res)
return NULL;
res->name = "Non-Bus Physical Address Space";
res->start = (1ULL << 32);
res->end = -1LL;
res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
if (insert_resource(&iomem_resource, res)) {
kfree(res);
return NULL;
}
return res;
}
#endif
static struct resource* __init
insert_ram_resource(u64 start_pfn, u64 end_pfn, bool reserved)
{
struct resource *res =
kzalloc(sizeof(struct resource), GFP_ATOMIC);
if (!res)
return NULL;
res->name = reserved ? "Reserved" : "System RAM";
res->start = start_pfn << PAGE_SHIFT;
res->end = (end_pfn << PAGE_SHIFT) - 1;
res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
if (insert_resource(&iomem_resource, res)) {
kfree(res);
return NULL;
}
return res;
}
/*
* Request address space for all standard resources
*
* If the system includes PCI root complex drivers, we need to create
* a window just below 4GB where PCI BARs can be mapped.
*/
static int __init request_standard_resources(void)
{
int i;
enum { CODE_DELTA = MEM_SV_START - PAGE_OFFSET };
#if defined(CONFIG_PCI) && !defined(__tilegx__)
insert_non_bus_resource();
#endif
for_each_online_node(i) {
u64 start_pfn = node_start_pfn[i];
u64 end_pfn = node_end_pfn[i];
#if defined(CONFIG_PCI) && !defined(__tilegx__)
if (start_pfn <= pci_reserve_start_pfn &&
end_pfn > pci_reserve_start_pfn) {
if (end_pfn > pci_reserve_end_pfn)
insert_ram_resource(pci_reserve_end_pfn,
end_pfn, 0);
end_pfn = pci_reserve_start_pfn;
}
#endif
insert_ram_resource(start_pfn, end_pfn, 0);
}
code_resource.start = __pa(_text - CODE_DELTA);
code_resource.end = __pa(_etext - CODE_DELTA)-1;
data_resource.start = __pa(_sdata);
data_resource.end = __pa(_end)-1;
insert_resource(&iomem_resource, &code_resource);
insert_resource(&iomem_resource, &data_resource);
/* Mark any "memmap" regions busy for the resource manager. */
for (i = 0; i < memmap_nr; ++i) {
struct memmap_entry *m = &memmap_map[i];
insert_ram_resource(PFN_DOWN(m->addr),
PFN_UP(m->addr + m->size - 1), 1);
}
#ifdef CONFIG_KEXEC
insert_resource(&iomem_resource, &crashk_res);
#endif
return 0;
}
subsys_initcall(request_standard_resources);
| gpl-2.0 |
TomGiordano/kernel_huawei_u8220 | drivers/pci/hotplug/cpci_hotplug_core.c | 198 | 17290 | /*
* CompactPCI Hot Plug Driver
*
* Copyright (C) 2002,2005 SOMA Networks, Inc.
* 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 <scottm@somanetworks.com>
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/smp_lock.h>
#include <asm/atomic.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include "cpci_hotplug.h"
#define DRIVER_AUTHOR "Scott Murray <scottm@somanetworks.com>"
#define DRIVER_DESC "CompactPCI Hot Plug Core"
#define MY_NAME "cpci_hotplug"
#define dbg(format, arg...) \
do { \
if (cpci_debug) \
printk (KERN_DEBUG "%s: " format "\n", \
MY_NAME , ## arg); \
} while (0)
#define err(format, arg...) printk(KERN_ERR "%s: " format "\n", MY_NAME , ## arg)
#define info(format, arg...) printk(KERN_INFO "%s: " format "\n", MY_NAME , ## arg)
#define warn(format, arg...) printk(KERN_WARNING "%s: " format "\n", MY_NAME , ## arg)
/* local variables */
static DECLARE_RWSEM(list_rwsem);
static LIST_HEAD(slot_list);
static int slots;
static atomic_t extracting;
int cpci_debug;
static struct cpci_hp_controller *controller;
static struct task_struct *cpci_thread;
static int thread_finished;
static int enable_slot(struct hotplug_slot *slot);
static int disable_slot(struct hotplug_slot *slot);
static int set_attention_status(struct hotplug_slot *slot, u8 value);
static int get_power_status(struct hotplug_slot *slot, u8 * value);
static int get_attention_status(struct hotplug_slot *slot, u8 * value);
static int get_adapter_status(struct hotplug_slot *slot, u8 * value);
static int get_latch_status(struct hotplug_slot *slot, u8 * value);
static struct hotplug_slot_ops cpci_hotplug_slot_ops = {
.owner = THIS_MODULE,
.enable_slot = enable_slot,
.disable_slot = disable_slot,
.set_attention_status = set_attention_status,
.get_power_status = get_power_status,
.get_attention_status = get_attention_status,
.get_adapter_status = get_adapter_status,
.get_latch_status = get_latch_status,
};
static int
update_latch_status(struct hotplug_slot *hotplug_slot, u8 value)
{
struct hotplug_slot_info info;
memcpy(&info, hotplug_slot->info, sizeof(struct hotplug_slot_info));
info.latch_status = value;
return pci_hp_change_slot_info(hotplug_slot, &info);
}
static int
update_adapter_status(struct hotplug_slot *hotplug_slot, u8 value)
{
struct hotplug_slot_info info;
memcpy(&info, hotplug_slot->info, sizeof(struct hotplug_slot_info));
info.adapter_status = value;
return pci_hp_change_slot_info(hotplug_slot, &info);
}
static int
enable_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
int retval = 0;
dbg("%s - physical_slot = %s", __func__, slot_name(slot));
if (controller->ops->set_power)
retval = controller->ops->set_power(slot, 1);
return retval;
}
static int
disable_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
int retval = 0;
dbg("%s - physical_slot = %s", __func__, slot_name(slot));
down_write(&list_rwsem);
/* Unconfigure device */
dbg("%s - unconfiguring slot %s", __func__, slot_name(slot));
if ((retval = cpci_unconfigure_slot(slot))) {
err("%s - could not unconfigure slot %s",
__func__, slot_name(slot));
goto disable_error;
}
dbg("%s - finished unconfiguring slot %s", __func__, slot_name(slot));
/* Clear EXT (by setting it) */
if (cpci_clear_ext(slot)) {
err("%s - could not clear EXT for slot %s",
__func__, slot_name(slot));
retval = -ENODEV;
goto disable_error;
}
cpci_led_on(slot);
if (controller->ops->set_power)
if ((retval = controller->ops->set_power(slot, 0)))
goto disable_error;
if (update_adapter_status(slot->hotplug_slot, 0))
warn("failure to update adapter file");
if (slot->extracting) {
slot->extracting = 0;
atomic_dec(&extracting);
}
disable_error:
up_write(&list_rwsem);
return retval;
}
static u8
cpci_get_power_status(struct slot *slot)
{
u8 power = 1;
if (controller->ops->get_power)
power = controller->ops->get_power(slot);
return power;
}
static int
get_power_status(struct hotplug_slot *hotplug_slot, u8 * value)
{
struct slot *slot = hotplug_slot->private;
*value = cpci_get_power_status(slot);
return 0;
}
static int
get_attention_status(struct hotplug_slot *hotplug_slot, u8 * value)
{
struct slot *slot = hotplug_slot->private;
*value = cpci_get_attention_status(slot);
return 0;
}
static int
set_attention_status(struct hotplug_slot *hotplug_slot, u8 status)
{
return cpci_set_attention_status(hotplug_slot->private, status);
}
static int
get_adapter_status(struct hotplug_slot *hotplug_slot, u8 * value)
{
*value = hotplug_slot->info->adapter_status;
return 0;
}
static int
get_latch_status(struct hotplug_slot *hotplug_slot, u8 * value)
{
*value = hotplug_slot->info->latch_status;
return 0;
}
static void release_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
kfree(slot->hotplug_slot->info);
kfree(slot->hotplug_slot);
if (slot->dev)
pci_dev_put(slot->dev);
kfree(slot);
}
#define SLOT_NAME_SIZE 6
int
cpci_hp_register_bus(struct pci_bus *bus, u8 first, u8 last)
{
struct slot *slot;
struct hotplug_slot *hotplug_slot;
struct hotplug_slot_info *info;
char name[SLOT_NAME_SIZE];
int status = -ENOMEM;
int i;
if (!(controller && bus))
return -ENODEV;
/*
* Create a structure for each slot, and register that slot
* with the pci_hotplug subsystem.
*/
for (i = first; i <= last; ++i) {
slot = kzalloc(sizeof (struct slot), GFP_KERNEL);
if (!slot)
goto error;
hotplug_slot =
kzalloc(sizeof (struct hotplug_slot), GFP_KERNEL);
if (!hotplug_slot)
goto error_slot;
slot->hotplug_slot = hotplug_slot;
info = kzalloc(sizeof (struct hotplug_slot_info), GFP_KERNEL);
if (!info)
goto error_hpslot;
hotplug_slot->info = info;
slot->bus = bus;
slot->number = i;
slot->devfn = PCI_DEVFN(i, 0);
snprintf(name, SLOT_NAME_SIZE, "%02x:%02x", bus->number, i);
hotplug_slot->private = slot;
hotplug_slot->release = &release_slot;
hotplug_slot->ops = &cpci_hotplug_slot_ops;
/*
* Initialize the slot info structure with some known
* good values.
*/
dbg("initializing slot %s", name);
info->power_status = cpci_get_power_status(slot);
info->attention_status = cpci_get_attention_status(slot);
dbg("registering slot %s", name);
status = pci_hp_register(slot->hotplug_slot, bus, i, name);
if (status) {
err("pci_hp_register failed with error %d", status);
goto error_info;
}
dbg("slot registered with name: %s", slot_name(slot));
/* Add slot to our internal list */
down_write(&list_rwsem);
list_add(&slot->slot_list, &slot_list);
slots++;
up_write(&list_rwsem);
}
return 0;
error_info:
kfree(info);
error_hpslot:
kfree(hotplug_slot);
error_slot:
kfree(slot);
error:
return status;
}
int
cpci_hp_unregister_bus(struct pci_bus *bus)
{
struct slot *slot;
struct slot *tmp;
int status = 0;
down_write(&list_rwsem);
if (!slots) {
up_write(&list_rwsem);
return -1;
}
list_for_each_entry_safe(slot, tmp, &slot_list, slot_list) {
if (slot->bus == bus) {
list_del(&slot->slot_list);
slots--;
dbg("deregistering slot %s", slot_name(slot));
status = pci_hp_deregister(slot->hotplug_slot);
if (status) {
err("pci_hp_deregister failed with error %d",
status);
break;
}
}
}
up_write(&list_rwsem);
return status;
}
/* This is the interrupt mode interrupt handler */
static irqreturn_t
cpci_hp_intr(int irq, void *data)
{
dbg("entered cpci_hp_intr");
/* Check to see if it was our interrupt */
if ((controller->irq_flags & IRQF_SHARED) &&
!controller->ops->check_irq(controller->dev_id)) {
dbg("exited cpci_hp_intr, not our interrupt");
return IRQ_NONE;
}
/* Disable ENUM interrupt */
controller->ops->disable_irq();
/* Trigger processing by the event thread */
wake_up_process(cpci_thread);
return IRQ_HANDLED;
}
/*
* According to PICMG 2.1 R2.0, section 6.3.2, upon
* initialization, the system driver shall clear the
* INS bits of the cold-inserted devices.
*/
static int
init_slots(int clear_ins)
{
struct slot *slot;
struct pci_dev* dev;
dbg("%s - enter", __func__);
down_read(&list_rwsem);
if (!slots) {
up_read(&list_rwsem);
return -1;
}
list_for_each_entry(slot, &slot_list, slot_list) {
dbg("%s - looking at slot %s", __func__, slot_name(slot));
if (clear_ins && cpci_check_and_clear_ins(slot))
dbg("%s - cleared INS for slot %s",
__func__, slot_name(slot));
dev = pci_get_slot(slot->bus, PCI_DEVFN(slot->number, 0));
if (dev) {
if (update_adapter_status(slot->hotplug_slot, 1))
warn("failure to update adapter file");
if (update_latch_status(slot->hotplug_slot, 1))
warn("failure to update latch file");
slot->dev = dev;
}
}
up_read(&list_rwsem);
dbg("%s - exit", __func__);
return 0;
}
static int
check_slots(void)
{
struct slot *slot;
int extracted;
int inserted;
u16 hs_csr;
down_read(&list_rwsem);
if (!slots) {
up_read(&list_rwsem);
err("no slots registered, shutting down");
return -1;
}
extracted = inserted = 0;
list_for_each_entry(slot, &slot_list, slot_list) {
dbg("%s - looking at slot %s", __func__, slot_name(slot));
if (cpci_check_and_clear_ins(slot)) {
/*
* Some broken hardware (e.g. PLX 9054AB) asserts
* ENUM# twice...
*/
if (slot->dev) {
warn("slot %s already inserted",
slot_name(slot));
inserted++;
continue;
}
/* Process insertion */
dbg("%s - slot %s inserted", __func__, slot_name(slot));
/* GSM, debug */
hs_csr = cpci_get_hs_csr(slot);
dbg("%s - slot %s HS_CSR (1) = %04x",
__func__, slot_name(slot), hs_csr);
/* Configure device */
dbg("%s - configuring slot %s",
__func__, slot_name(slot));
if (cpci_configure_slot(slot)) {
err("%s - could not configure slot %s",
__func__, slot_name(slot));
continue;
}
dbg("%s - finished configuring slot %s",
__func__, slot_name(slot));
/* GSM, debug */
hs_csr = cpci_get_hs_csr(slot);
dbg("%s - slot %s HS_CSR (2) = %04x",
__func__, slot_name(slot), hs_csr);
if (update_latch_status(slot->hotplug_slot, 1))
warn("failure to update latch file");
if (update_adapter_status(slot->hotplug_slot, 1))
warn("failure to update adapter file");
cpci_led_off(slot);
/* GSM, debug */
hs_csr = cpci_get_hs_csr(slot);
dbg("%s - slot %s HS_CSR (3) = %04x",
__func__, slot_name(slot), hs_csr);
inserted++;
} else if (cpci_check_ext(slot)) {
/* Process extraction request */
dbg("%s - slot %s extracted",
__func__, slot_name(slot));
/* GSM, debug */
hs_csr = cpci_get_hs_csr(slot);
dbg("%s - slot %s HS_CSR = %04x",
__func__, slot_name(slot), hs_csr);
if (!slot->extracting) {
if (update_latch_status(slot->hotplug_slot, 0)) {
warn("failure to update latch file");
}
slot->extracting = 1;
atomic_inc(&extracting);
}
extracted++;
} else if (slot->extracting) {
hs_csr = cpci_get_hs_csr(slot);
if (hs_csr == 0xffff) {
/*
* Hmmm, we're likely hosed at this point, should we
* bother trying to tell the driver or not?
*/
err("card in slot %s was improperly removed",
slot_name(slot));
if (update_adapter_status(slot->hotplug_slot, 0))
warn("failure to update adapter file");
slot->extracting = 0;
atomic_dec(&extracting);
}
}
}
up_read(&list_rwsem);
dbg("inserted=%d, extracted=%d, extracting=%d",
inserted, extracted, atomic_read(&extracting));
if (inserted || extracted)
return extracted;
else if (!atomic_read(&extracting)) {
err("cannot find ENUM# source, shutting down");
return -1;
}
return 0;
}
/* This is the interrupt mode worker thread body */
static int
event_thread(void *data)
{
int rc;
dbg("%s - event thread started", __func__);
while (1) {
dbg("event thread sleeping");
set_current_state(TASK_INTERRUPTIBLE);
schedule();
if (kthread_should_stop())
break;
do {
rc = check_slots();
if (rc > 0) {
/* Give userspace a chance to handle extraction */
msleep(500);
} else if (rc < 0) {
dbg("%s - error checking slots", __func__);
thread_finished = 1;
goto out;
}
} while (atomic_read(&extracting) && !kthread_should_stop());
if (kthread_should_stop())
break;
/* Re-enable ENUM# interrupt */
dbg("%s - re-enabling irq", __func__);
controller->ops->enable_irq();
}
out:
return 0;
}
/* This is the polling mode worker thread body */
static int
poll_thread(void *data)
{
int rc;
while (1) {
if (kthread_should_stop() || signal_pending(current))
break;
if (controller->ops->query_enum()) {
do {
rc = check_slots();
if (rc > 0) {
/* Give userspace a chance to handle extraction */
msleep(500);
} else if (rc < 0) {
dbg("%s - error checking slots", __func__);
thread_finished = 1;
goto out;
}
} while (atomic_read(&extracting) && !kthread_should_stop());
}
msleep(100);
}
out:
return 0;
}
static int
cpci_start_thread(void)
{
if (controller->irq)
cpci_thread = kthread_run(event_thread, NULL, "cpci_hp_eventd");
else
cpci_thread = kthread_run(poll_thread, NULL, "cpci_hp_polld");
if (IS_ERR(cpci_thread)) {
err("Can't start up our thread");
return PTR_ERR(cpci_thread);
}
thread_finished = 0;
return 0;
}
static void
cpci_stop_thread(void)
{
kthread_stop(cpci_thread);
thread_finished = 1;
}
int
cpci_hp_register_controller(struct cpci_hp_controller *new_controller)
{
int status = 0;
if (controller)
return -1;
if (!(new_controller && new_controller->ops))
return -EINVAL;
if (new_controller->irq) {
if (!(new_controller->ops->enable_irq &&
new_controller->ops->disable_irq))
status = -EINVAL;
if (request_irq(new_controller->irq,
cpci_hp_intr,
new_controller->irq_flags,
MY_NAME,
new_controller->dev_id)) {
err("Can't get irq %d for the hotplug cPCI controller",
new_controller->irq);
status = -ENODEV;
}
dbg("%s - acquired controller irq %d",
__func__, new_controller->irq);
}
if (!status)
controller = new_controller;
return status;
}
static void
cleanup_slots(void)
{
struct slot *slot;
struct slot *tmp;
/*
* Unregister all of our slots with the pci_hotplug subsystem,
* and free up all memory that we had allocated.
*/
down_write(&list_rwsem);
if (!slots)
goto cleanup_null;
list_for_each_entry_safe(slot, tmp, &slot_list, slot_list) {
list_del(&slot->slot_list);
pci_hp_deregister(slot->hotplug_slot);
}
cleanup_null:
up_write(&list_rwsem);
return;
}
int
cpci_hp_unregister_controller(struct cpci_hp_controller *old_controller)
{
int status = 0;
if (controller) {
if (!thread_finished)
cpci_stop_thread();
if (controller->irq)
free_irq(controller->irq, controller->dev_id);
controller = NULL;
cleanup_slots();
} else
status = -ENODEV;
return status;
}
int
cpci_hp_start(void)
{
static int first = 1;
int status;
dbg("%s - enter", __func__);
if (!controller)
return -ENODEV;
down_read(&list_rwsem);
if (list_empty(&slot_list)) {
up_read(&list_rwsem);
return -ENODEV;
}
up_read(&list_rwsem);
status = init_slots(first);
if (first)
first = 0;
if (status)
return status;
status = cpci_start_thread();
if (status)
return status;
dbg("%s - thread started", __func__);
if (controller->irq) {
/* Start enum interrupt processing */
dbg("%s - enabling irq", __func__);
controller->ops->enable_irq();
}
dbg("%s - exit", __func__);
return 0;
}
int
cpci_hp_stop(void)
{
if (!controller)
return -ENODEV;
if (controller->irq) {
/* Stop enum interrupt processing */
dbg("%s - disabling irq", __func__);
controller->ops->disable_irq();
}
cpci_stop_thread();
return 0;
}
int __init
cpci_hotplug_init(int debug)
{
cpci_debug = debug;
return 0;
}
void __exit
cpci_hotplug_exit(void)
{
/*
* Clean everything up.
*/
cpci_hp_stop();
cpci_hp_unregister_controller(controller);
}
EXPORT_SYMBOL_GPL(cpci_hp_register_controller);
EXPORT_SYMBOL_GPL(cpci_hp_unregister_controller);
EXPORT_SYMBOL_GPL(cpci_hp_register_bus);
EXPORT_SYMBOL_GPL(cpci_hp_unregister_bus);
EXPORT_SYMBOL_GPL(cpci_hp_start);
EXPORT_SYMBOL_GPL(cpci_hp_stop);
| gpl-2.0 |
jprukner/linux | arch/arm/mach-s3c24xx/mach-mini2440.c | 1478 | 17695 | /* linux/arch/arm/mach-s3c2440/mach-mini2440.c
*
* Copyright (c) 2008 Ramax Lo <ramaxlo@gmail.com>
* Based on mach-anubis.c by Ben Dooks <ben@simtec.co.uk>
* and modifications by SBZ <sbz@spgui.org> and
* Weibing <http://weibing.blogbus.com> and
* Michel Pollet <buserror@gmail.com>
*
* For product information, visit http://code.google.com/p/mini2440/
*
* 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/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/input.h>
#include <linux/io.h>
#include <linux/serial_core.h>
#include <linux/serial_s3c.h>
#include <linux/dm9000.h>
#include <linux/platform_data/at24.h>
#include <linux/platform_device.h>
#include <linux/gpio_keys.h>
#include <linux/i2c.h>
#include <linux/mmc/host.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/hardware.h>
#include <mach/fb.h>
#include <asm/mach-types.h>
#include <mach/regs-gpio.h>
#include <linux/platform_data/leds-s3c24xx.h>
#include <mach/regs-lcd.h>
#include <mach/irqs.h>
#include <mach/gpio-samsung.h>
#include <linux/platform_data/mtd-nand-s3c2410.h>
#include <linux/platform_data/i2c-s3c2410.h>
#include <linux/platform_data/mmc-s3cmci.h>
#include <linux/platform_data/usb-s3c2410_udc.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <plat/gpio-cfg.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/samsung-time.h>
#include <sound/s3c24xx_uda134x.h>
#include "common.h"
#define MACH_MINI2440_DM9K_BASE (S3C2410_CS4 + 0x300)
static struct map_desc mini2440_iodesc[] __initdata = {
/* nothing to declare, move along */
};
#define UCON S3C2410_UCON_DEFAULT
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg mini2440_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
};
/* USB device UDC support */
static struct s3c2410_udc_mach_info mini2440_udc_cfg __initdata = {
.pullup_pin = S3C2410_GPC(5),
};
/* LCD timing and setup */
/*
* This macro simplifies the table bellow
*/
#define _LCD_DECLARE(_clock,_xres,margin_left,margin_right,hsync, \
_yres,margin_top,margin_bottom,vsync, refresh) \
.width = _xres, \
.xres = _xres, \
.height = _yres, \
.yres = _yres, \
.left_margin = margin_left, \
.right_margin = margin_right, \
.upper_margin = margin_top, \
.lower_margin = margin_bottom, \
.hsync_len = hsync, \
.vsync_len = vsync, \
.pixclock = ((_clock*100000000000LL) / \
((refresh) * \
(hsync + margin_left + _xres + margin_right) * \
(vsync + margin_top + _yres + margin_bottom))), \
.bpp = 16,\
.type = (S3C2410_LCDCON1_TFT16BPP |\
S3C2410_LCDCON1_TFT)
static struct s3c2410fb_display mini2440_lcd_cfg[] __initdata = {
[0] = { /* mini2440 + 3.5" TFT + touchscreen */
_LCD_DECLARE(
7, /* The 3.5 is quite fast */
240, 21, 38, 6, /* x timing */
320, 4, 4, 2, /* y timing */
60), /* refresh rate */
.lcdcon5 = (S3C2410_LCDCON5_FRM565 |
S3C2410_LCDCON5_INVVLINE |
S3C2410_LCDCON5_INVVFRAME |
S3C2410_LCDCON5_INVVDEN |
S3C2410_LCDCON5_PWREN),
},
[1] = { /* mini2440 + 7" TFT + touchscreen */
_LCD_DECLARE(
10, /* the 7" runs slower */
800, 40, 40, 48, /* x timing */
480, 29, 3, 3, /* y timing */
50), /* refresh rate */
.lcdcon5 = (S3C2410_LCDCON5_FRM565 |
S3C2410_LCDCON5_INVVLINE |
S3C2410_LCDCON5_INVVFRAME |
S3C2410_LCDCON5_PWREN),
},
/* The VGA shield can outout at several resolutions. All share
* the same timings, however, anything smaller than 1024x768
* will only be displayed in the top left corner of a 1024x768
* XGA output unless you add optional dip switches to the shield.
* Therefore timings for other resolutions have been omitted here.
*/
[2] = {
_LCD_DECLARE(
10,
1024, 1, 2, 2, /* y timing */
768, 200, 16, 16, /* x timing */
24), /* refresh rate, maximum stable,
tested with the FPGA shield */
.lcdcon5 = (S3C2410_LCDCON5_FRM565 |
S3C2410_LCDCON5_HWSWP),
},
/* mini2440 + 3.5" TFT (LCD-W35i, LQ035Q1DG06 type) + touchscreen*/
[3] = {
_LCD_DECLARE(
/* clock */
7,
/* xres, margin_right, margin_left, hsync */
320, 68, 66, 4,
/* yres, margin_top, margin_bottom, vsync */
240, 4, 4, 9,
/* refresh rate */
60),
.lcdcon5 = (S3C2410_LCDCON5_FRM565 |
S3C2410_LCDCON5_INVVDEN |
S3C2410_LCDCON5_INVVFRAME |
S3C2410_LCDCON5_INVVLINE |
S3C2410_LCDCON5_INVVCLK |
S3C2410_LCDCON5_HWSWP),
},
};
/* todo - put into gpio header */
#define S3C2410_GPCCON_MASK(x) (3 << ((x) * 2))
#define S3C2410_GPDCON_MASK(x) (3 << ((x) * 2))
static struct s3c2410fb_mach_info mini2440_fb_info __initdata = {
.displays = &mini2440_lcd_cfg[0], /* not constant! see init */
.num_displays = 1,
.default_display = 0,
/* Enable VD[2..7], VD[10..15], VD[18..23] and VCLK, syncs, VDEN
* and disable the pull down resistors on pins we are using for LCD
* data. */
.gpcup = (0xf << 1) | (0x3f << 10),
.gpccon = (S3C2410_GPC1_VCLK | S3C2410_GPC2_VLINE |
S3C2410_GPC3_VFRAME | S3C2410_GPC4_VM |
S3C2410_GPC10_VD2 | S3C2410_GPC11_VD3 |
S3C2410_GPC12_VD4 | S3C2410_GPC13_VD5 |
S3C2410_GPC14_VD6 | S3C2410_GPC15_VD7),
.gpccon_mask = (S3C2410_GPCCON_MASK(1) | S3C2410_GPCCON_MASK(2) |
S3C2410_GPCCON_MASK(3) | S3C2410_GPCCON_MASK(4) |
S3C2410_GPCCON_MASK(10) | S3C2410_GPCCON_MASK(11) |
S3C2410_GPCCON_MASK(12) | S3C2410_GPCCON_MASK(13) |
S3C2410_GPCCON_MASK(14) | S3C2410_GPCCON_MASK(15)),
.gpdup = (0x3f << 2) | (0x3f << 10),
.gpdcon = (S3C2410_GPD2_VD10 | S3C2410_GPD3_VD11 |
S3C2410_GPD4_VD12 | S3C2410_GPD5_VD13 |
S3C2410_GPD6_VD14 | S3C2410_GPD7_VD15 |
S3C2410_GPD10_VD18 | S3C2410_GPD11_VD19 |
S3C2410_GPD12_VD20 | S3C2410_GPD13_VD21 |
S3C2410_GPD14_VD22 | S3C2410_GPD15_VD23),
.gpdcon_mask = (S3C2410_GPDCON_MASK(2) | S3C2410_GPDCON_MASK(3) |
S3C2410_GPDCON_MASK(4) | S3C2410_GPDCON_MASK(5) |
S3C2410_GPDCON_MASK(6) | S3C2410_GPDCON_MASK(7) |
S3C2410_GPDCON_MASK(10) | S3C2410_GPDCON_MASK(11)|
S3C2410_GPDCON_MASK(12) | S3C2410_GPDCON_MASK(13)|
S3C2410_GPDCON_MASK(14) | S3C2410_GPDCON_MASK(15)),
};
/* MMC/SD */
static struct s3c24xx_mci_pdata mini2440_mmc_cfg __initdata = {
.gpio_detect = S3C2410_GPG(8),
.gpio_wprotect = S3C2410_GPH(8),
.set_power = NULL,
.ocr_avail = MMC_VDD_32_33|MMC_VDD_33_34,
};
/* NAND Flash on MINI2440 board */
static struct mtd_partition mini2440_default_nand_part[] __initdata = {
[0] = {
.name = "u-boot",
.size = SZ_256K,
.offset = 0,
},
[1] = {
.name = "u-boot-env",
.size = SZ_128K,
.offset = SZ_256K,
},
[2] = {
.name = "kernel",
/* 5 megabytes, for a kernel with no modules
* or a uImage with a ramdisk attached */
.size = 0x00500000,
.offset = SZ_256K + SZ_128K,
},
[3] = {
.name = "root",
.offset = SZ_256K + SZ_128K + 0x00500000,
.size = MTDPART_SIZ_FULL,
},
};
static struct s3c2410_nand_set mini2440_nand_sets[] __initdata = {
[0] = {
.name = "nand",
.nr_chips = 1,
.nr_partitions = ARRAY_SIZE(mini2440_default_nand_part),
.partitions = mini2440_default_nand_part,
.flash_bbt = 1, /* we use u-boot to create a BBT */
},
};
static struct s3c2410_platform_nand mini2440_nand_info __initdata = {
.tacls = 0,
.twrph0 = 25,
.twrph1 = 15,
.nr_sets = ARRAY_SIZE(mini2440_nand_sets),
.sets = mini2440_nand_sets,
.ignore_unset_ecc = 1,
};
/* DM9000AEP 10/100 ethernet controller */
static struct resource mini2440_dm9k_resource[] = {
[0] = DEFINE_RES_MEM(MACH_MINI2440_DM9K_BASE, 4),
[1] = DEFINE_RES_MEM(MACH_MINI2440_DM9K_BASE + 4, 4),
[2] = DEFINE_RES_NAMED(IRQ_EINT7, 1, NULL, IORESOURCE_IRQ \
| IORESOURCE_IRQ_HIGHEDGE),
};
/*
* The DM9000 has no eeprom, and it's MAC address is set by
* the bootloader before starting the kernel.
*/
static struct dm9000_plat_data mini2440_dm9k_pdata = {
.flags = (DM9000_PLATF_16BITONLY | DM9000_PLATF_NO_EEPROM),
};
static struct platform_device mini2440_device_eth = {
.name = "dm9000",
.id = -1,
.num_resources = ARRAY_SIZE(mini2440_dm9k_resource),
.resource = mini2440_dm9k_resource,
.dev = {
.platform_data = &mini2440_dm9k_pdata,
},
};
/* CON5
* +--+ /-----\
* | | | |
* | | | BAT |
* | | \_____/
* | |
* | | +----+ +----+
* | | | K5 | | K1 |
* | | +----+ +----+
* | | +----+ +----+
* | | | K4 | | K2 |
* | | +----+ +----+
* | | +----+ +----+
* | | | K6 | | K3 |
* | | +----+ +----+
* .....
*/
static struct gpio_keys_button mini2440_buttons[] = {
{
.gpio = S3C2410_GPG(0), /* K1 */
.code = KEY_F1,
.desc = "Button 1",
.active_low = 1,
},
{
.gpio = S3C2410_GPG(3), /* K2 */
.code = KEY_F2,
.desc = "Button 2",
.active_low = 1,
},
{
.gpio = S3C2410_GPG(5), /* K3 */
.code = KEY_F3,
.desc = "Button 3",
.active_low = 1,
},
{
.gpio = S3C2410_GPG(6), /* K4 */
.code = KEY_POWER,
.desc = "Power",
.active_low = 1,
},
{
.gpio = S3C2410_GPG(7), /* K5 */
.code = KEY_F5,
.desc = "Button 5",
.active_low = 1,
},
#if 0
/* this pin is also known as TCLK1 and seems to already
* marked as "in use" somehow in the kernel -- possibly wrongly */
{
.gpio = S3C2410_GPG(11), /* K6 */
.code = KEY_F6,
.desc = "Button 6",
.active_low = 1,
},
#endif
};
static struct gpio_keys_platform_data mini2440_button_data = {
.buttons = mini2440_buttons,
.nbuttons = ARRAY_SIZE(mini2440_buttons),
};
static struct platform_device mini2440_button_device = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &mini2440_button_data,
}
};
/* LEDS */
static struct s3c24xx_led_platdata mini2440_led1_pdata = {
.name = "led1",
.gpio = S3C2410_GPB(5),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.def_trigger = "heartbeat",
};
static struct s3c24xx_led_platdata mini2440_led2_pdata = {
.name = "led2",
.gpio = S3C2410_GPB(6),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.def_trigger = "nand-disk",
};
static struct s3c24xx_led_platdata mini2440_led3_pdata = {
.name = "led3",
.gpio = S3C2410_GPB(7),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.def_trigger = "mmc0",
};
static struct s3c24xx_led_platdata mini2440_led4_pdata = {
.name = "led4",
.gpio = S3C2410_GPB(8),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.def_trigger = "",
};
static struct s3c24xx_led_platdata mini2440_led_backlight_pdata = {
.name = "backlight",
.gpio = S3C2410_GPG(4),
.def_trigger = "backlight",
};
static struct platform_device mini2440_led1 = {
.name = "s3c24xx_led",
.id = 1,
.dev = {
.platform_data = &mini2440_led1_pdata,
},
};
static struct platform_device mini2440_led2 = {
.name = "s3c24xx_led",
.id = 2,
.dev = {
.platform_data = &mini2440_led2_pdata,
},
};
static struct platform_device mini2440_led3 = {
.name = "s3c24xx_led",
.id = 3,
.dev = {
.platform_data = &mini2440_led3_pdata,
},
};
static struct platform_device mini2440_led4 = {
.name = "s3c24xx_led",
.id = 4,
.dev = {
.platform_data = &mini2440_led4_pdata,
},
};
static struct platform_device mini2440_led_backlight = {
.name = "s3c24xx_led",
.id = 5,
.dev = {
.platform_data = &mini2440_led_backlight_pdata,
},
};
/* AUDIO */
static struct s3c24xx_uda134x_platform_data mini2440_audio_pins = {
.l3_clk = S3C2410_GPB(4),
.l3_mode = S3C2410_GPB(2),
.l3_data = S3C2410_GPB(3),
.model = UDA134X_UDA1341
};
static struct platform_device mini2440_audio = {
.name = "s3c24xx_uda134x",
.id = 0,
.dev = {
.platform_data = &mini2440_audio_pins,
},
};
/*
* I2C devices
*/
static struct at24_platform_data at24c08 = {
.byte_len = SZ_8K / 8,
.page_size = 16,
};
static struct i2c_board_info mini2440_i2c_devs[] __initdata = {
{
I2C_BOARD_INFO("24c08", 0x50),
.platform_data = &at24c08,
},
};
static struct platform_device uda1340_codec = {
.name = "uda134x-codec",
.id = -1,
};
static struct platform_device *mini2440_devices[] __initdata = {
&s3c_device_ohci,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_rtc,
&s3c_device_usbgadget,
&mini2440_device_eth,
&mini2440_led1,
&mini2440_led2,
&mini2440_led3,
&mini2440_led4,
&mini2440_button_device,
&s3c_device_nand,
&s3c_device_sdi,
&s3c_device_iis,
&uda1340_codec,
&mini2440_audio,
};
static void __init mini2440_map_io(void)
{
s3c24xx_init_io(mini2440_iodesc, ARRAY_SIZE(mini2440_iodesc));
s3c24xx_init_uarts(mini2440_uartcfgs, ARRAY_SIZE(mini2440_uartcfgs));
samsung_set_timer_source(SAMSUNG_PWM3, SAMSUNG_PWM4);
}
static void __init mini2440_init_time(void)
{
s3c2440_init_clocks(12000000);
samsung_timer_init();
}
/*
* mini2440_features string
*
* t = Touchscreen present
* b = backlight control
* c = camera [TODO]
* 0-9 LCD configuration
*
*/
static char mini2440_features_str[12] __initdata = "0tb";
static int __init mini2440_features_setup(char *str)
{
if (str)
strlcpy(mini2440_features_str, str, sizeof(mini2440_features_str));
return 1;
}
__setup("mini2440=", mini2440_features_setup);
#define FEATURE_SCREEN (1 << 0)
#define FEATURE_BACKLIGHT (1 << 1)
#define FEATURE_TOUCH (1 << 2)
#define FEATURE_CAMERA (1 << 3)
struct mini2440_features_t {
int count;
int done;
int lcd_index;
struct platform_device *optional[8];
};
static void __init mini2440_parse_features(
struct mini2440_features_t * features,
const char * features_str )
{
const char * fp = features_str;
features->count = 0;
features->done = 0;
features->lcd_index = -1;
while (*fp) {
char f = *fp++;
switch (f) {
case '0'...'9': /* tft screen */
if (features->done & FEATURE_SCREEN) {
printk(KERN_INFO "MINI2440: '%c' ignored, "
"screen type already set\n", f);
} else {
int li = f - '0';
if (li >= ARRAY_SIZE(mini2440_lcd_cfg))
printk(KERN_INFO "MINI2440: "
"'%c' out of range LCD mode\n", f);
else {
features->optional[features->count++] =
&s3c_device_lcd;
features->lcd_index = li;
}
}
features->done |= FEATURE_SCREEN;
break;
case 'b':
if (features->done & FEATURE_BACKLIGHT)
printk(KERN_INFO "MINI2440: '%c' ignored, "
"backlight already set\n", f);
else {
features->optional[features->count++] =
&mini2440_led_backlight;
}
features->done |= FEATURE_BACKLIGHT;
break;
case 't':
printk(KERN_INFO "MINI2440: '%c' ignored, "
"touchscreen not compiled in\n", f);
break;
case 'c':
if (features->done & FEATURE_CAMERA)
printk(KERN_INFO "MINI2440: '%c' ignored, "
"camera already registered\n", f);
else
features->optional[features->count++] =
&s3c_device_camif;
features->done |= FEATURE_CAMERA;
break;
}
}
}
static void __init mini2440_init(void)
{
struct mini2440_features_t features = { 0 };
int i;
printk(KERN_INFO "MINI2440: Option string mini2440=%s\n",
mini2440_features_str);
/* Parse the feature string */
mini2440_parse_features(&features, mini2440_features_str);
/* turn LCD on */
s3c_gpio_cfgpin(S3C2410_GPC(0), S3C2410_GPC0_LEND);
/* Turn the backlight early on */
WARN_ON(gpio_request_one(S3C2410_GPG(4), GPIOF_OUT_INIT_HIGH, NULL));
gpio_free(S3C2410_GPG(4));
/* remove pullup on optional PWM backlight -- unused on 3.5 and 7"s */
gpio_request_one(S3C2410_GPB(1), GPIOF_IN, NULL);
s3c_gpio_setpull(S3C2410_GPB(1), S3C_GPIO_PULL_UP);
gpio_free(S3C2410_GPB(1));
/* mark the key as input, without pullups (there is one on the board) */
for (i = 0; i < ARRAY_SIZE(mini2440_buttons); i++) {
s3c_gpio_setpull(mini2440_buttons[i].gpio, S3C_GPIO_PULL_UP);
s3c_gpio_cfgpin(mini2440_buttons[i].gpio, S3C2410_GPIO_INPUT);
}
if (features.lcd_index != -1) {
int li;
mini2440_fb_info.displays =
&mini2440_lcd_cfg[features.lcd_index];
printk(KERN_INFO "MINI2440: LCD");
for (li = 0; li < ARRAY_SIZE(mini2440_lcd_cfg); li++)
if (li == features.lcd_index)
printk(" [%d:%dx%d]", li,
mini2440_lcd_cfg[li].width,
mini2440_lcd_cfg[li].height);
else
printk(" %d:%dx%d", li,
mini2440_lcd_cfg[li].width,
mini2440_lcd_cfg[li].height);
printk("\n");
s3c24xx_fb_set_platdata(&mini2440_fb_info);
}
s3c24xx_udc_set_platdata(&mini2440_udc_cfg);
s3c24xx_mci_set_platdata(&mini2440_mmc_cfg);
s3c_nand_set_platdata(&mini2440_nand_info);
s3c_i2c0_set_platdata(NULL);
i2c_register_board_info(0, mini2440_i2c_devs,
ARRAY_SIZE(mini2440_i2c_devs));
platform_add_devices(mini2440_devices, ARRAY_SIZE(mini2440_devices));
if (features.count) /* the optional features */
platform_add_devices(features.optional, features.count);
}
MACHINE_START(MINI2440, "MINI2440")
/* Maintainer: Michel Pollet <buserror@gmail.com> */
.atag_offset = 0x100,
.map_io = mini2440_map_io,
.init_machine = mini2440_init,
.init_irq = s3c2440_init_irq,
.init_time = mini2440_init_time,
MACHINE_END
| gpl-2.0 |
NUBIANX404H/NX507J_5.1_kernel | drivers/video/omap2/dss/dispc.c | 1990 | 81735 | /*
* linux/drivers/video/omap2/dss/dispc.c
*
* Copyright (C) 2009 Nokia Corporation
* Author: Tomi Valkeinen <tomi.valkeinen@nokia.com>
*
* Some code and ideas taken from drivers/video/omap/ driver
* by Imre Deak.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define DSS_SUBSYS_NAME "DISPC"
#include <linux/kernel.h>
#include <linux/dma-mapping.h>
#include <linux/vmalloc.h>
#include <linux/export.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/seq_file.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/hardirq.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <plat/clock.h>
#include <video/omapdss.h>
#include "dss.h"
#include "dss_features.h"
#include "dispc.h"
/* DISPC */
#define DISPC_SZ_REGS SZ_4K
#define DISPC_IRQ_MASK_ERROR (DISPC_IRQ_GFX_FIFO_UNDERFLOW | \
DISPC_IRQ_OCP_ERR | \
DISPC_IRQ_VID1_FIFO_UNDERFLOW | \
DISPC_IRQ_VID2_FIFO_UNDERFLOW | \
DISPC_IRQ_SYNC_LOST | \
DISPC_IRQ_SYNC_LOST_DIGIT)
#define DISPC_MAX_NR_ISRS 8
struct omap_dispc_isr_data {
omap_dispc_isr_t isr;
void *arg;
u32 mask;
};
enum omap_burst_size {
BURST_SIZE_X2 = 0,
BURST_SIZE_X4 = 1,
BURST_SIZE_X8 = 2,
};
#define REG_GET(idx, start, end) \
FLD_GET(dispc_read_reg(idx), start, end)
#define REG_FLD_MOD(idx, val, start, end) \
dispc_write_reg(idx, FLD_MOD(dispc_read_reg(idx), val, start, end))
struct dispc_irq_stats {
unsigned long last_reset;
unsigned irq_count;
unsigned irqs[32];
};
static struct {
struct platform_device *pdev;
void __iomem *base;
int ctx_loss_cnt;
int irq;
struct clk *dss_clk;
u32 fifo_size[MAX_DSS_OVERLAYS];
spinlock_t irq_lock;
u32 irq_error_mask;
struct omap_dispc_isr_data registered_isr[DISPC_MAX_NR_ISRS];
u32 error_irqs;
struct work_struct error_work;
bool ctx_valid;
u32 ctx[DISPC_SZ_REGS / sizeof(u32)];
#ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS
spinlock_t irq_stats_lock;
struct dispc_irq_stats irq_stats;
#endif
} dispc;
enum omap_color_component {
/* used for all color formats for OMAP3 and earlier
* and for RGB and Y color component on OMAP4
*/
DISPC_COLOR_COMPONENT_RGB_Y = 1 << 0,
/* used for UV component for
* OMAP_DSS_COLOR_YUV2, OMAP_DSS_COLOR_UYVY, OMAP_DSS_COLOR_NV12
* color formats on OMAP4
*/
DISPC_COLOR_COMPONENT_UV = 1 << 1,
};
static void _omap_dispc_set_irqs(void);
static inline void dispc_write_reg(const u16 idx, u32 val)
{
__raw_writel(val, dispc.base + idx);
}
static inline u32 dispc_read_reg(const u16 idx)
{
return __raw_readl(dispc.base + idx);
}
static int dispc_get_ctx_loss_count(void)
{
struct device *dev = &dispc.pdev->dev;
struct omap_display_platform_data *pdata = dev->platform_data;
struct omap_dss_board_info *board_data = pdata->board_data;
int cnt;
if (!board_data->get_context_loss_count)
return -ENOENT;
cnt = board_data->get_context_loss_count(dev);
WARN_ONCE(cnt < 0, "get_context_loss_count failed: %d\n", cnt);
return cnt;
}
#define SR(reg) \
dispc.ctx[DISPC_##reg / sizeof(u32)] = dispc_read_reg(DISPC_##reg)
#define RR(reg) \
dispc_write_reg(DISPC_##reg, dispc.ctx[DISPC_##reg / sizeof(u32)])
static void dispc_save_context(void)
{
int i, j;
DSSDBG("dispc_save_context\n");
SR(IRQENABLE);
SR(CONTROL);
SR(CONFIG);
SR(LINE_NUMBER);
if (dss_has_feature(FEAT_ALPHA_FIXED_ZORDER) ||
dss_has_feature(FEAT_ALPHA_FREE_ZORDER))
SR(GLOBAL_ALPHA);
if (dss_has_feature(FEAT_MGR_LCD2)) {
SR(CONTROL2);
SR(CONFIG2);
}
for (i = 0; i < dss_feat_get_num_mgrs(); i++) {
SR(DEFAULT_COLOR(i));
SR(TRANS_COLOR(i));
SR(SIZE_MGR(i));
if (i == OMAP_DSS_CHANNEL_DIGIT)
continue;
SR(TIMING_H(i));
SR(TIMING_V(i));
SR(POL_FREQ(i));
SR(DIVISORo(i));
SR(DATA_CYCLE1(i));
SR(DATA_CYCLE2(i));
SR(DATA_CYCLE3(i));
if (dss_has_feature(FEAT_CPR)) {
SR(CPR_COEF_R(i));
SR(CPR_COEF_G(i));
SR(CPR_COEF_B(i));
}
}
for (i = 0; i < dss_feat_get_num_ovls(); i++) {
SR(OVL_BA0(i));
SR(OVL_BA1(i));
SR(OVL_POSITION(i));
SR(OVL_SIZE(i));
SR(OVL_ATTRIBUTES(i));
SR(OVL_FIFO_THRESHOLD(i));
SR(OVL_ROW_INC(i));
SR(OVL_PIXEL_INC(i));
if (dss_has_feature(FEAT_PRELOAD))
SR(OVL_PRELOAD(i));
if (i == OMAP_DSS_GFX) {
SR(OVL_WINDOW_SKIP(i));
SR(OVL_TABLE_BA(i));
continue;
}
SR(OVL_FIR(i));
SR(OVL_PICTURE_SIZE(i));
SR(OVL_ACCU0(i));
SR(OVL_ACCU1(i));
for (j = 0; j < 8; j++)
SR(OVL_FIR_COEF_H(i, j));
for (j = 0; j < 8; j++)
SR(OVL_FIR_COEF_HV(i, j));
for (j = 0; j < 5; j++)
SR(OVL_CONV_COEF(i, j));
if (dss_has_feature(FEAT_FIR_COEF_V)) {
for (j = 0; j < 8; j++)
SR(OVL_FIR_COEF_V(i, j));
}
if (dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) {
SR(OVL_BA0_UV(i));
SR(OVL_BA1_UV(i));
SR(OVL_FIR2(i));
SR(OVL_ACCU2_0(i));
SR(OVL_ACCU2_1(i));
for (j = 0; j < 8; j++)
SR(OVL_FIR_COEF_H2(i, j));
for (j = 0; j < 8; j++)
SR(OVL_FIR_COEF_HV2(i, j));
for (j = 0; j < 8; j++)
SR(OVL_FIR_COEF_V2(i, j));
}
if (dss_has_feature(FEAT_ATTR2))
SR(OVL_ATTRIBUTES2(i));
}
if (dss_has_feature(FEAT_CORE_CLK_DIV))
SR(DIVISOR);
dispc.ctx_loss_cnt = dispc_get_ctx_loss_count();
dispc.ctx_valid = true;
DSSDBG("context saved, ctx_loss_count %d\n", dispc.ctx_loss_cnt);
}
static void dispc_restore_context(void)
{
int i, j, ctx;
DSSDBG("dispc_restore_context\n");
if (!dispc.ctx_valid)
return;
ctx = dispc_get_ctx_loss_count();
if (ctx >= 0 && ctx == dispc.ctx_loss_cnt)
return;
DSSDBG("ctx_loss_count: saved %d, current %d\n",
dispc.ctx_loss_cnt, ctx);
/*RR(IRQENABLE);*/
/*RR(CONTROL);*/
RR(CONFIG);
RR(LINE_NUMBER);
if (dss_has_feature(FEAT_ALPHA_FIXED_ZORDER) ||
dss_has_feature(FEAT_ALPHA_FREE_ZORDER))
RR(GLOBAL_ALPHA);
if (dss_has_feature(FEAT_MGR_LCD2))
RR(CONFIG2);
for (i = 0; i < dss_feat_get_num_mgrs(); i++) {
RR(DEFAULT_COLOR(i));
RR(TRANS_COLOR(i));
RR(SIZE_MGR(i));
if (i == OMAP_DSS_CHANNEL_DIGIT)
continue;
RR(TIMING_H(i));
RR(TIMING_V(i));
RR(POL_FREQ(i));
RR(DIVISORo(i));
RR(DATA_CYCLE1(i));
RR(DATA_CYCLE2(i));
RR(DATA_CYCLE3(i));
if (dss_has_feature(FEAT_CPR)) {
RR(CPR_COEF_R(i));
RR(CPR_COEF_G(i));
RR(CPR_COEF_B(i));
}
}
for (i = 0; i < dss_feat_get_num_ovls(); i++) {
RR(OVL_BA0(i));
RR(OVL_BA1(i));
RR(OVL_POSITION(i));
RR(OVL_SIZE(i));
RR(OVL_ATTRIBUTES(i));
RR(OVL_FIFO_THRESHOLD(i));
RR(OVL_ROW_INC(i));
RR(OVL_PIXEL_INC(i));
if (dss_has_feature(FEAT_PRELOAD))
RR(OVL_PRELOAD(i));
if (i == OMAP_DSS_GFX) {
RR(OVL_WINDOW_SKIP(i));
RR(OVL_TABLE_BA(i));
continue;
}
RR(OVL_FIR(i));
RR(OVL_PICTURE_SIZE(i));
RR(OVL_ACCU0(i));
RR(OVL_ACCU1(i));
for (j = 0; j < 8; j++)
RR(OVL_FIR_COEF_H(i, j));
for (j = 0; j < 8; j++)
RR(OVL_FIR_COEF_HV(i, j));
for (j = 0; j < 5; j++)
RR(OVL_CONV_COEF(i, j));
if (dss_has_feature(FEAT_FIR_COEF_V)) {
for (j = 0; j < 8; j++)
RR(OVL_FIR_COEF_V(i, j));
}
if (dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) {
RR(OVL_BA0_UV(i));
RR(OVL_BA1_UV(i));
RR(OVL_FIR2(i));
RR(OVL_ACCU2_0(i));
RR(OVL_ACCU2_1(i));
for (j = 0; j < 8; j++)
RR(OVL_FIR_COEF_H2(i, j));
for (j = 0; j < 8; j++)
RR(OVL_FIR_COEF_HV2(i, j));
for (j = 0; j < 8; j++)
RR(OVL_FIR_COEF_V2(i, j));
}
if (dss_has_feature(FEAT_ATTR2))
RR(OVL_ATTRIBUTES2(i));
}
if (dss_has_feature(FEAT_CORE_CLK_DIV))
RR(DIVISOR);
/* enable last, because LCD & DIGIT enable are here */
RR(CONTROL);
if (dss_has_feature(FEAT_MGR_LCD2))
RR(CONTROL2);
/* clear spurious SYNC_LOST_DIGIT interrupts */
dispc_write_reg(DISPC_IRQSTATUS, DISPC_IRQ_SYNC_LOST_DIGIT);
/*
* enable last so IRQs won't trigger before
* the context is fully restored
*/
RR(IRQENABLE);
DSSDBG("context restored\n");
}
#undef SR
#undef RR
int dispc_runtime_get(void)
{
int r;
DSSDBG("dispc_runtime_get\n");
r = pm_runtime_get_sync(&dispc.pdev->dev);
WARN_ON(r < 0);
return r < 0 ? r : 0;
}
void dispc_runtime_put(void)
{
int r;
DSSDBG("dispc_runtime_put\n");
r = pm_runtime_put_sync(&dispc.pdev->dev);
WARN_ON(r < 0);
}
static inline bool dispc_mgr_is_lcd(enum omap_channel channel)
{
if (channel == OMAP_DSS_CHANNEL_LCD ||
channel == OMAP_DSS_CHANNEL_LCD2)
return true;
else
return false;
}
static struct omap_dss_device *dispc_mgr_get_device(enum omap_channel channel)
{
struct omap_overlay_manager *mgr =
omap_dss_get_overlay_manager(channel);
return mgr ? mgr->device : NULL;
}
u32 dispc_mgr_get_vsync_irq(enum omap_channel channel)
{
switch (channel) {
case OMAP_DSS_CHANNEL_LCD:
return DISPC_IRQ_VSYNC;
case OMAP_DSS_CHANNEL_LCD2:
return DISPC_IRQ_VSYNC2;
case OMAP_DSS_CHANNEL_DIGIT:
return DISPC_IRQ_EVSYNC_ODD | DISPC_IRQ_EVSYNC_EVEN;
default:
BUG();
}
}
u32 dispc_mgr_get_framedone_irq(enum omap_channel channel)
{
switch (channel) {
case OMAP_DSS_CHANNEL_LCD:
return DISPC_IRQ_FRAMEDONE;
case OMAP_DSS_CHANNEL_LCD2:
return DISPC_IRQ_FRAMEDONE2;
case OMAP_DSS_CHANNEL_DIGIT:
return 0;
default:
BUG();
}
}
bool dispc_mgr_go_busy(enum omap_channel channel)
{
int bit;
if (dispc_mgr_is_lcd(channel))
bit = 5; /* GOLCD */
else
bit = 6; /* GODIGIT */
if (channel == OMAP_DSS_CHANNEL_LCD2)
return REG_GET(DISPC_CONTROL2, bit, bit) == 1;
else
return REG_GET(DISPC_CONTROL, bit, bit) == 1;
}
void dispc_mgr_go(enum omap_channel channel)
{
int bit;
bool enable_bit, go_bit;
if (dispc_mgr_is_lcd(channel))
bit = 0; /* LCDENABLE */
else
bit = 1; /* DIGITALENABLE */
/* if the channel is not enabled, we don't need GO */
if (channel == OMAP_DSS_CHANNEL_LCD2)
enable_bit = REG_GET(DISPC_CONTROL2, bit, bit) == 1;
else
enable_bit = REG_GET(DISPC_CONTROL, bit, bit) == 1;
if (!enable_bit)
return;
if (dispc_mgr_is_lcd(channel))
bit = 5; /* GOLCD */
else
bit = 6; /* GODIGIT */
if (channel == OMAP_DSS_CHANNEL_LCD2)
go_bit = REG_GET(DISPC_CONTROL2, bit, bit) == 1;
else
go_bit = REG_GET(DISPC_CONTROL, bit, bit) == 1;
if (go_bit) {
DSSERR("GO bit not down for channel %d\n", channel);
return;
}
DSSDBG("GO %s\n", channel == OMAP_DSS_CHANNEL_LCD ? "LCD" :
(channel == OMAP_DSS_CHANNEL_LCD2 ? "LCD2" : "DIGIT"));
if (channel == OMAP_DSS_CHANNEL_LCD2)
REG_FLD_MOD(DISPC_CONTROL2, 1, bit, bit);
else
REG_FLD_MOD(DISPC_CONTROL, 1, bit, bit);
}
static void dispc_ovl_write_firh_reg(enum omap_plane plane, int reg, u32 value)
{
dispc_write_reg(DISPC_OVL_FIR_COEF_H(plane, reg), value);
}
static void dispc_ovl_write_firhv_reg(enum omap_plane plane, int reg, u32 value)
{
dispc_write_reg(DISPC_OVL_FIR_COEF_HV(plane, reg), value);
}
static void dispc_ovl_write_firv_reg(enum omap_plane plane, int reg, u32 value)
{
dispc_write_reg(DISPC_OVL_FIR_COEF_V(plane, reg), value);
}
static void dispc_ovl_write_firh2_reg(enum omap_plane plane, int reg, u32 value)
{
BUG_ON(plane == OMAP_DSS_GFX);
dispc_write_reg(DISPC_OVL_FIR_COEF_H2(plane, reg), value);
}
static void dispc_ovl_write_firhv2_reg(enum omap_plane plane, int reg,
u32 value)
{
BUG_ON(plane == OMAP_DSS_GFX);
dispc_write_reg(DISPC_OVL_FIR_COEF_HV2(plane, reg), value);
}
static void dispc_ovl_write_firv2_reg(enum omap_plane plane, int reg, u32 value)
{
BUG_ON(plane == OMAP_DSS_GFX);
dispc_write_reg(DISPC_OVL_FIR_COEF_V2(plane, reg), value);
}
static void dispc_ovl_set_scale_coef(enum omap_plane plane, int fir_hinc,
int fir_vinc, int five_taps,
enum omap_color_component color_comp)
{
const struct dispc_coef *h_coef, *v_coef;
int i;
h_coef = dispc_ovl_get_scale_coef(fir_hinc, true);
v_coef = dispc_ovl_get_scale_coef(fir_vinc, five_taps);
for (i = 0; i < 8; i++) {
u32 h, hv;
h = FLD_VAL(h_coef[i].hc0_vc00, 7, 0)
| FLD_VAL(h_coef[i].hc1_vc0, 15, 8)
| FLD_VAL(h_coef[i].hc2_vc1, 23, 16)
| FLD_VAL(h_coef[i].hc3_vc2, 31, 24);
hv = FLD_VAL(h_coef[i].hc4_vc22, 7, 0)
| FLD_VAL(v_coef[i].hc1_vc0, 15, 8)
| FLD_VAL(v_coef[i].hc2_vc1, 23, 16)
| FLD_VAL(v_coef[i].hc3_vc2, 31, 24);
if (color_comp == DISPC_COLOR_COMPONENT_RGB_Y) {
dispc_ovl_write_firh_reg(plane, i, h);
dispc_ovl_write_firhv_reg(plane, i, hv);
} else {
dispc_ovl_write_firh2_reg(plane, i, h);
dispc_ovl_write_firhv2_reg(plane, i, hv);
}
}
if (five_taps) {
for (i = 0; i < 8; i++) {
u32 v;
v = FLD_VAL(v_coef[i].hc0_vc00, 7, 0)
| FLD_VAL(v_coef[i].hc4_vc22, 15, 8);
if (color_comp == DISPC_COLOR_COMPONENT_RGB_Y)
dispc_ovl_write_firv_reg(plane, i, v);
else
dispc_ovl_write_firv2_reg(plane, i, v);
}
}
}
static void _dispc_setup_color_conv_coef(void)
{
int i;
const struct color_conv_coef {
int ry, rcr, rcb, gy, gcr, gcb, by, bcr, bcb;
int full_range;
} ctbl_bt601_5 = {
298, 409, 0, 298, -208, -100, 298, 0, 517, 0,
};
const struct color_conv_coef *ct;
#define CVAL(x, y) (FLD_VAL(x, 26, 16) | FLD_VAL(y, 10, 0))
ct = &ctbl_bt601_5;
for (i = 1; i < dss_feat_get_num_ovls(); i++) {
dispc_write_reg(DISPC_OVL_CONV_COEF(i, 0),
CVAL(ct->rcr, ct->ry));
dispc_write_reg(DISPC_OVL_CONV_COEF(i, 1),
CVAL(ct->gy, ct->rcb));
dispc_write_reg(DISPC_OVL_CONV_COEF(i, 2),
CVAL(ct->gcb, ct->gcr));
dispc_write_reg(DISPC_OVL_CONV_COEF(i, 3),
CVAL(ct->bcr, ct->by));
dispc_write_reg(DISPC_OVL_CONV_COEF(i, 4),
CVAL(0, ct->bcb));
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(i), ct->full_range,
11, 11);
}
#undef CVAL
}
static void dispc_ovl_set_ba0(enum omap_plane plane, u32 paddr)
{
dispc_write_reg(DISPC_OVL_BA0(plane), paddr);
}
static void dispc_ovl_set_ba1(enum omap_plane plane, u32 paddr)
{
dispc_write_reg(DISPC_OVL_BA1(plane), paddr);
}
static void dispc_ovl_set_ba0_uv(enum omap_plane plane, u32 paddr)
{
dispc_write_reg(DISPC_OVL_BA0_UV(plane), paddr);
}
static void dispc_ovl_set_ba1_uv(enum omap_plane plane, u32 paddr)
{
dispc_write_reg(DISPC_OVL_BA1_UV(plane), paddr);
}
static void dispc_ovl_set_pos(enum omap_plane plane, int x, int y)
{
u32 val = FLD_VAL(y, 26, 16) | FLD_VAL(x, 10, 0);
dispc_write_reg(DISPC_OVL_POSITION(plane), val);
}
static void dispc_ovl_set_pic_size(enum omap_plane plane, int width, int height)
{
u32 val = FLD_VAL(height - 1, 26, 16) | FLD_VAL(width - 1, 10, 0);
if (plane == OMAP_DSS_GFX)
dispc_write_reg(DISPC_OVL_SIZE(plane), val);
else
dispc_write_reg(DISPC_OVL_PICTURE_SIZE(plane), val);
}
static void dispc_ovl_set_vid_size(enum omap_plane plane, int width, int height)
{
u32 val;
BUG_ON(plane == OMAP_DSS_GFX);
val = FLD_VAL(height - 1, 26, 16) | FLD_VAL(width - 1, 10, 0);
dispc_write_reg(DISPC_OVL_SIZE(plane), val);
}
static void dispc_ovl_set_zorder(enum omap_plane plane, u8 zorder)
{
struct omap_overlay *ovl = omap_dss_get_overlay(plane);
if ((ovl->caps & OMAP_DSS_OVL_CAP_ZORDER) == 0)
return;
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), zorder, 27, 26);
}
static void dispc_ovl_enable_zorder_planes(void)
{
int i;
if (!dss_has_feature(FEAT_ALPHA_FREE_ZORDER))
return;
for (i = 0; i < dss_feat_get_num_ovls(); i++)
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(i), 1, 25, 25);
}
static void dispc_ovl_set_pre_mult_alpha(enum omap_plane plane, bool enable)
{
struct omap_overlay *ovl = omap_dss_get_overlay(plane);
if ((ovl->caps & OMAP_DSS_OVL_CAP_PRE_MULT_ALPHA) == 0)
return;
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), enable ? 1 : 0, 28, 28);
}
static void dispc_ovl_setup_global_alpha(enum omap_plane plane, u8 global_alpha)
{
static const unsigned shifts[] = { 0, 8, 16, 24, };
int shift;
struct omap_overlay *ovl = omap_dss_get_overlay(plane);
if ((ovl->caps & OMAP_DSS_OVL_CAP_GLOBAL_ALPHA) == 0)
return;
shift = shifts[plane];
REG_FLD_MOD(DISPC_GLOBAL_ALPHA, global_alpha, shift + 7, shift);
}
static void dispc_ovl_set_pix_inc(enum omap_plane plane, s32 inc)
{
dispc_write_reg(DISPC_OVL_PIXEL_INC(plane), inc);
}
static void dispc_ovl_set_row_inc(enum omap_plane plane, s32 inc)
{
dispc_write_reg(DISPC_OVL_ROW_INC(plane), inc);
}
static void dispc_ovl_set_color_mode(enum omap_plane plane,
enum omap_color_mode color_mode)
{
u32 m = 0;
if (plane != OMAP_DSS_GFX) {
switch (color_mode) {
case OMAP_DSS_COLOR_NV12:
m = 0x0; break;
case OMAP_DSS_COLOR_RGBX16:
m = 0x1; break;
case OMAP_DSS_COLOR_RGBA16:
m = 0x2; break;
case OMAP_DSS_COLOR_RGB12U:
m = 0x4; break;
case OMAP_DSS_COLOR_ARGB16:
m = 0x5; break;
case OMAP_DSS_COLOR_RGB16:
m = 0x6; break;
case OMAP_DSS_COLOR_ARGB16_1555:
m = 0x7; break;
case OMAP_DSS_COLOR_RGB24U:
m = 0x8; break;
case OMAP_DSS_COLOR_RGB24P:
m = 0x9; break;
case OMAP_DSS_COLOR_YUV2:
m = 0xa; break;
case OMAP_DSS_COLOR_UYVY:
m = 0xb; break;
case OMAP_DSS_COLOR_ARGB32:
m = 0xc; break;
case OMAP_DSS_COLOR_RGBA32:
m = 0xd; break;
case OMAP_DSS_COLOR_RGBX32:
m = 0xe; break;
case OMAP_DSS_COLOR_XRGB16_1555:
m = 0xf; break;
default:
BUG(); break;
}
} else {
switch (color_mode) {
case OMAP_DSS_COLOR_CLUT1:
m = 0x0; break;
case OMAP_DSS_COLOR_CLUT2:
m = 0x1; break;
case OMAP_DSS_COLOR_CLUT4:
m = 0x2; break;
case OMAP_DSS_COLOR_CLUT8:
m = 0x3; break;
case OMAP_DSS_COLOR_RGB12U:
m = 0x4; break;
case OMAP_DSS_COLOR_ARGB16:
m = 0x5; break;
case OMAP_DSS_COLOR_RGB16:
m = 0x6; break;
case OMAP_DSS_COLOR_ARGB16_1555:
m = 0x7; break;
case OMAP_DSS_COLOR_RGB24U:
m = 0x8; break;
case OMAP_DSS_COLOR_RGB24P:
m = 0x9; break;
case OMAP_DSS_COLOR_RGBX16:
m = 0xa; break;
case OMAP_DSS_COLOR_RGBA16:
m = 0xb; break;
case OMAP_DSS_COLOR_ARGB32:
m = 0xc; break;
case OMAP_DSS_COLOR_RGBA32:
m = 0xd; break;
case OMAP_DSS_COLOR_RGBX32:
m = 0xe; break;
case OMAP_DSS_COLOR_XRGB16_1555:
m = 0xf; break;
default:
BUG(); break;
}
}
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), m, 4, 1);
}
void dispc_ovl_set_channel_out(enum omap_plane plane, enum omap_channel channel)
{
int shift;
u32 val;
int chan = 0, chan2 = 0;
switch (plane) {
case OMAP_DSS_GFX:
shift = 8;
break;
case OMAP_DSS_VIDEO1:
case OMAP_DSS_VIDEO2:
case OMAP_DSS_VIDEO3:
shift = 16;
break;
default:
BUG();
return;
}
val = dispc_read_reg(DISPC_OVL_ATTRIBUTES(plane));
if (dss_has_feature(FEAT_MGR_LCD2)) {
switch (channel) {
case OMAP_DSS_CHANNEL_LCD:
chan = 0;
chan2 = 0;
break;
case OMAP_DSS_CHANNEL_DIGIT:
chan = 1;
chan2 = 0;
break;
case OMAP_DSS_CHANNEL_LCD2:
chan = 0;
chan2 = 1;
break;
default:
BUG();
}
val = FLD_MOD(val, chan, shift, shift);
val = FLD_MOD(val, chan2, 31, 30);
} else {
val = FLD_MOD(val, channel, shift, shift);
}
dispc_write_reg(DISPC_OVL_ATTRIBUTES(plane), val);
}
static enum omap_channel dispc_ovl_get_channel_out(enum omap_plane plane)
{
int shift;
u32 val;
enum omap_channel channel;
switch (plane) {
case OMAP_DSS_GFX:
shift = 8;
break;
case OMAP_DSS_VIDEO1:
case OMAP_DSS_VIDEO2:
case OMAP_DSS_VIDEO3:
shift = 16;
break;
default:
BUG();
}
val = dispc_read_reg(DISPC_OVL_ATTRIBUTES(plane));
if (dss_has_feature(FEAT_MGR_LCD2)) {
if (FLD_GET(val, 31, 30) == 0)
channel = FLD_GET(val, shift, shift);
else
channel = OMAP_DSS_CHANNEL_LCD2;
} else {
channel = FLD_GET(val, shift, shift);
}
return channel;
}
static void dispc_ovl_set_burst_size(enum omap_plane plane,
enum omap_burst_size burst_size)
{
static const unsigned shifts[] = { 6, 14, 14, 14, };
int shift;
shift = shifts[plane];
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), burst_size, shift + 1, shift);
}
static void dispc_configure_burst_sizes(void)
{
int i;
const int burst_size = BURST_SIZE_X8;
/* Configure burst size always to maximum size */
for (i = 0; i < omap_dss_get_num_overlays(); ++i)
dispc_ovl_set_burst_size(i, burst_size);
}
static u32 dispc_ovl_get_burst_size(enum omap_plane plane)
{
unsigned unit = dss_feat_get_burst_size_unit();
/* burst multiplier is always x8 (see dispc_configure_burst_sizes()) */
return unit * 8;
}
void dispc_enable_gamma_table(bool enable)
{
/*
* This is partially implemented to support only disabling of
* the gamma table.
*/
if (enable) {
DSSWARN("Gamma table enabling for TV not yet supported");
return;
}
REG_FLD_MOD(DISPC_CONFIG, enable, 9, 9);
}
static void dispc_mgr_enable_cpr(enum omap_channel channel, bool enable)
{
u16 reg;
if (channel == OMAP_DSS_CHANNEL_LCD)
reg = DISPC_CONFIG;
else if (channel == OMAP_DSS_CHANNEL_LCD2)
reg = DISPC_CONFIG2;
else
return;
REG_FLD_MOD(reg, enable, 15, 15);
}
static void dispc_mgr_set_cpr_coef(enum omap_channel channel,
struct omap_dss_cpr_coefs *coefs)
{
u32 coef_r, coef_g, coef_b;
if (!dispc_mgr_is_lcd(channel))
return;
coef_r = FLD_VAL(coefs->rr, 31, 22) | FLD_VAL(coefs->rg, 20, 11) |
FLD_VAL(coefs->rb, 9, 0);
coef_g = FLD_VAL(coefs->gr, 31, 22) | FLD_VAL(coefs->gg, 20, 11) |
FLD_VAL(coefs->gb, 9, 0);
coef_b = FLD_VAL(coefs->br, 31, 22) | FLD_VAL(coefs->bg, 20, 11) |
FLD_VAL(coefs->bb, 9, 0);
dispc_write_reg(DISPC_CPR_COEF_R(channel), coef_r);
dispc_write_reg(DISPC_CPR_COEF_G(channel), coef_g);
dispc_write_reg(DISPC_CPR_COEF_B(channel), coef_b);
}
static void dispc_ovl_set_vid_color_conv(enum omap_plane plane, bool enable)
{
u32 val;
BUG_ON(plane == OMAP_DSS_GFX);
val = dispc_read_reg(DISPC_OVL_ATTRIBUTES(plane));
val = FLD_MOD(val, enable, 9, 9);
dispc_write_reg(DISPC_OVL_ATTRIBUTES(plane), val);
}
static void dispc_ovl_enable_replication(enum omap_plane plane, bool enable)
{
static const unsigned shifts[] = { 5, 10, 10, 10 };
int shift;
shift = shifts[plane];
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), enable, shift, shift);
}
void dispc_mgr_set_lcd_size(enum omap_channel channel, u16 width, u16 height)
{
u32 val;
BUG_ON((width > (1 << 11)) || (height > (1 << 11)));
val = FLD_VAL(height - 1, 26, 16) | FLD_VAL(width - 1, 10, 0);
dispc_write_reg(DISPC_SIZE_MGR(channel), val);
}
void dispc_set_digit_size(u16 width, u16 height)
{
u32 val;
BUG_ON((width > (1 << 11)) || (height > (1 << 11)));
val = FLD_VAL(height - 1, 26, 16) | FLD_VAL(width - 1, 10, 0);
dispc_write_reg(DISPC_SIZE_MGR(OMAP_DSS_CHANNEL_DIGIT), val);
}
static void dispc_read_plane_fifo_sizes(void)
{
u32 size;
int plane;
u8 start, end;
u32 unit;
unit = dss_feat_get_buffer_size_unit();
dss_feat_get_reg_field(FEAT_REG_FIFOSIZE, &start, &end);
for (plane = 0; plane < dss_feat_get_num_ovls(); ++plane) {
size = REG_GET(DISPC_OVL_FIFO_SIZE_STATUS(plane), start, end);
size *= unit;
dispc.fifo_size[plane] = size;
}
}
static u32 dispc_ovl_get_fifo_size(enum omap_plane plane)
{
return dispc.fifo_size[plane];
}
void dispc_ovl_set_fifo_threshold(enum omap_plane plane, u32 low, u32 high)
{
u8 hi_start, hi_end, lo_start, lo_end;
u32 unit;
unit = dss_feat_get_buffer_size_unit();
WARN_ON(low % unit != 0);
WARN_ON(high % unit != 0);
low /= unit;
high /= unit;
dss_feat_get_reg_field(FEAT_REG_FIFOHIGHTHRESHOLD, &hi_start, &hi_end);
dss_feat_get_reg_field(FEAT_REG_FIFOLOWTHRESHOLD, &lo_start, &lo_end);
DSSDBG("fifo(%d) threshold (bytes), old %u/%u, new %u/%u\n",
plane,
REG_GET(DISPC_OVL_FIFO_THRESHOLD(plane),
lo_start, lo_end) * unit,
REG_GET(DISPC_OVL_FIFO_THRESHOLD(plane),
hi_start, hi_end) * unit,
low * unit, high * unit);
dispc_write_reg(DISPC_OVL_FIFO_THRESHOLD(plane),
FLD_VAL(high, hi_start, hi_end) |
FLD_VAL(low, lo_start, lo_end));
}
void dispc_enable_fifomerge(bool enable)
{
if (!dss_has_feature(FEAT_FIFO_MERGE)) {
WARN_ON(enable);
return;
}
DSSDBG("FIFO merge %s\n", enable ? "enabled" : "disabled");
REG_FLD_MOD(DISPC_CONFIG, enable ? 1 : 0, 14, 14);
}
void dispc_ovl_compute_fifo_thresholds(enum omap_plane plane,
u32 *fifo_low, u32 *fifo_high, bool use_fifomerge,
bool manual_update)
{
/*
* All sizes are in bytes. Both the buffer and burst are made of
* buffer_units, and the fifo thresholds must be buffer_unit aligned.
*/
unsigned buf_unit = dss_feat_get_buffer_size_unit();
unsigned ovl_fifo_size, total_fifo_size, burst_size;
int i;
burst_size = dispc_ovl_get_burst_size(plane);
ovl_fifo_size = dispc_ovl_get_fifo_size(plane);
if (use_fifomerge) {
total_fifo_size = 0;
for (i = 0; i < omap_dss_get_num_overlays(); ++i)
total_fifo_size += dispc_ovl_get_fifo_size(i);
} else {
total_fifo_size = ovl_fifo_size;
}
/*
* We use the same low threshold for both fifomerge and non-fifomerge
* cases, but for fifomerge we calculate the high threshold using the
* combined fifo size
*/
if (manual_update && dss_has_feature(FEAT_OMAP3_DSI_FIFO_BUG)) {
*fifo_low = ovl_fifo_size - burst_size * 2;
*fifo_high = total_fifo_size - burst_size;
} else {
*fifo_low = ovl_fifo_size - burst_size;
*fifo_high = total_fifo_size - buf_unit;
}
}
static void dispc_ovl_set_fir(enum omap_plane plane,
int hinc, int vinc,
enum omap_color_component color_comp)
{
u32 val;
if (color_comp == DISPC_COLOR_COMPONENT_RGB_Y) {
u8 hinc_start, hinc_end, vinc_start, vinc_end;
dss_feat_get_reg_field(FEAT_REG_FIRHINC,
&hinc_start, &hinc_end);
dss_feat_get_reg_field(FEAT_REG_FIRVINC,
&vinc_start, &vinc_end);
val = FLD_VAL(vinc, vinc_start, vinc_end) |
FLD_VAL(hinc, hinc_start, hinc_end);
dispc_write_reg(DISPC_OVL_FIR(plane), val);
} else {
val = FLD_VAL(vinc, 28, 16) | FLD_VAL(hinc, 12, 0);
dispc_write_reg(DISPC_OVL_FIR2(plane), val);
}
}
static void dispc_ovl_set_vid_accu0(enum omap_plane plane, int haccu, int vaccu)
{
u32 val;
u8 hor_start, hor_end, vert_start, vert_end;
dss_feat_get_reg_field(FEAT_REG_HORIZONTALACCU, &hor_start, &hor_end);
dss_feat_get_reg_field(FEAT_REG_VERTICALACCU, &vert_start, &vert_end);
val = FLD_VAL(vaccu, vert_start, vert_end) |
FLD_VAL(haccu, hor_start, hor_end);
dispc_write_reg(DISPC_OVL_ACCU0(plane), val);
}
static void dispc_ovl_set_vid_accu1(enum omap_plane plane, int haccu, int vaccu)
{
u32 val;
u8 hor_start, hor_end, vert_start, vert_end;
dss_feat_get_reg_field(FEAT_REG_HORIZONTALACCU, &hor_start, &hor_end);
dss_feat_get_reg_field(FEAT_REG_VERTICALACCU, &vert_start, &vert_end);
val = FLD_VAL(vaccu, vert_start, vert_end) |
FLD_VAL(haccu, hor_start, hor_end);
dispc_write_reg(DISPC_OVL_ACCU1(plane), val);
}
static void dispc_ovl_set_vid_accu2_0(enum omap_plane plane, int haccu,
int vaccu)
{
u32 val;
val = FLD_VAL(vaccu, 26, 16) | FLD_VAL(haccu, 10, 0);
dispc_write_reg(DISPC_OVL_ACCU2_0(plane), val);
}
static void dispc_ovl_set_vid_accu2_1(enum omap_plane plane, int haccu,
int vaccu)
{
u32 val;
val = FLD_VAL(vaccu, 26, 16) | FLD_VAL(haccu, 10, 0);
dispc_write_reg(DISPC_OVL_ACCU2_1(plane), val);
}
static void dispc_ovl_set_scale_param(enum omap_plane plane,
u16 orig_width, u16 orig_height,
u16 out_width, u16 out_height,
bool five_taps, u8 rotation,
enum omap_color_component color_comp)
{
int fir_hinc, fir_vinc;
fir_hinc = 1024 * orig_width / out_width;
fir_vinc = 1024 * orig_height / out_height;
dispc_ovl_set_scale_coef(plane, fir_hinc, fir_vinc, five_taps,
color_comp);
dispc_ovl_set_fir(plane, fir_hinc, fir_vinc, color_comp);
}
static void dispc_ovl_set_scaling_common(enum omap_plane plane,
u16 orig_width, u16 orig_height,
u16 out_width, u16 out_height,
bool ilace, bool five_taps,
bool fieldmode, enum omap_color_mode color_mode,
u8 rotation)
{
int accu0 = 0;
int accu1 = 0;
u32 l;
dispc_ovl_set_scale_param(plane, orig_width, orig_height,
out_width, out_height, five_taps,
rotation, DISPC_COLOR_COMPONENT_RGB_Y);
l = dispc_read_reg(DISPC_OVL_ATTRIBUTES(plane));
/* RESIZEENABLE and VERTICALTAPS */
l &= ~((0x3 << 5) | (0x1 << 21));
l |= (orig_width != out_width) ? (1 << 5) : 0;
l |= (orig_height != out_height) ? (1 << 6) : 0;
l |= five_taps ? (1 << 21) : 0;
/* VRESIZECONF and HRESIZECONF */
if (dss_has_feature(FEAT_RESIZECONF)) {
l &= ~(0x3 << 7);
l |= (orig_width <= out_width) ? 0 : (1 << 7);
l |= (orig_height <= out_height) ? 0 : (1 << 8);
}
/* LINEBUFFERSPLIT */
if (dss_has_feature(FEAT_LINEBUFFERSPLIT)) {
l &= ~(0x1 << 22);
l |= five_taps ? (1 << 22) : 0;
}
dispc_write_reg(DISPC_OVL_ATTRIBUTES(plane), l);
/*
* field 0 = even field = bottom field
* field 1 = odd field = top field
*/
if (ilace && !fieldmode) {
accu1 = 0;
accu0 = ((1024 * orig_height / out_height) / 2) & 0x3ff;
if (accu0 >= 1024/2) {
accu1 = 1024/2;
accu0 -= accu1;
}
}
dispc_ovl_set_vid_accu0(plane, 0, accu0);
dispc_ovl_set_vid_accu1(plane, 0, accu1);
}
static void dispc_ovl_set_scaling_uv(enum omap_plane plane,
u16 orig_width, u16 orig_height,
u16 out_width, u16 out_height,
bool ilace, bool five_taps,
bool fieldmode, enum omap_color_mode color_mode,
u8 rotation)
{
int scale_x = out_width != orig_width;
int scale_y = out_height != orig_height;
if (!dss_has_feature(FEAT_HANDLE_UV_SEPARATE))
return;
if ((color_mode != OMAP_DSS_COLOR_YUV2 &&
color_mode != OMAP_DSS_COLOR_UYVY &&
color_mode != OMAP_DSS_COLOR_NV12)) {
/* reset chroma resampling for RGB formats */
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES2(plane), 0, 8, 8);
return;
}
switch (color_mode) {
case OMAP_DSS_COLOR_NV12:
/* UV is subsampled by 2 vertically*/
orig_height >>= 1;
/* UV is subsampled by 2 horz.*/
orig_width >>= 1;
break;
case OMAP_DSS_COLOR_YUV2:
case OMAP_DSS_COLOR_UYVY:
/*For YUV422 with 90/270 rotation,
*we don't upsample chroma
*/
if (rotation == OMAP_DSS_ROT_0 ||
rotation == OMAP_DSS_ROT_180)
/* UV is subsampled by 2 hrz*/
orig_width >>= 1;
/* must use FIR for YUV422 if rotated */
if (rotation != OMAP_DSS_ROT_0)
scale_x = scale_y = true;
break;
default:
BUG();
}
if (out_width != orig_width)
scale_x = true;
if (out_height != orig_height)
scale_y = true;
dispc_ovl_set_scale_param(plane, orig_width, orig_height,
out_width, out_height, five_taps,
rotation, DISPC_COLOR_COMPONENT_UV);
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES2(plane),
(scale_x || scale_y) ? 1 : 0, 8, 8);
/* set H scaling */
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), scale_x ? 1 : 0, 5, 5);
/* set V scaling */
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), scale_y ? 1 : 0, 6, 6);
dispc_ovl_set_vid_accu2_0(plane, 0x80, 0);
dispc_ovl_set_vid_accu2_1(plane, 0x80, 0);
}
static void dispc_ovl_set_scaling(enum omap_plane plane,
u16 orig_width, u16 orig_height,
u16 out_width, u16 out_height,
bool ilace, bool five_taps,
bool fieldmode, enum omap_color_mode color_mode,
u8 rotation)
{
BUG_ON(plane == OMAP_DSS_GFX);
dispc_ovl_set_scaling_common(plane,
orig_width, orig_height,
out_width, out_height,
ilace, five_taps,
fieldmode, color_mode,
rotation);
dispc_ovl_set_scaling_uv(plane,
orig_width, orig_height,
out_width, out_height,
ilace, five_taps,
fieldmode, color_mode,
rotation);
}
static void dispc_ovl_set_rotation_attrs(enum omap_plane plane, u8 rotation,
bool mirroring, enum omap_color_mode color_mode)
{
bool row_repeat = false;
int vidrot = 0;
if (color_mode == OMAP_DSS_COLOR_YUV2 ||
color_mode == OMAP_DSS_COLOR_UYVY) {
if (mirroring) {
switch (rotation) {
case OMAP_DSS_ROT_0:
vidrot = 2;
break;
case OMAP_DSS_ROT_90:
vidrot = 1;
break;
case OMAP_DSS_ROT_180:
vidrot = 0;
break;
case OMAP_DSS_ROT_270:
vidrot = 3;
break;
}
} else {
switch (rotation) {
case OMAP_DSS_ROT_0:
vidrot = 0;
break;
case OMAP_DSS_ROT_90:
vidrot = 1;
break;
case OMAP_DSS_ROT_180:
vidrot = 2;
break;
case OMAP_DSS_ROT_270:
vidrot = 3;
break;
}
}
if (rotation == OMAP_DSS_ROT_90 || rotation == OMAP_DSS_ROT_270)
row_repeat = true;
else
row_repeat = false;
}
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), vidrot, 13, 12);
if (dss_has_feature(FEAT_ROWREPEATENABLE))
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane),
row_repeat ? 1 : 0, 18, 18);
}
static int color_mode_to_bpp(enum omap_color_mode color_mode)
{
switch (color_mode) {
case OMAP_DSS_COLOR_CLUT1:
return 1;
case OMAP_DSS_COLOR_CLUT2:
return 2;
case OMAP_DSS_COLOR_CLUT4:
return 4;
case OMAP_DSS_COLOR_CLUT8:
case OMAP_DSS_COLOR_NV12:
return 8;
case OMAP_DSS_COLOR_RGB12U:
case OMAP_DSS_COLOR_RGB16:
case OMAP_DSS_COLOR_ARGB16:
case OMAP_DSS_COLOR_YUV2:
case OMAP_DSS_COLOR_UYVY:
case OMAP_DSS_COLOR_RGBA16:
case OMAP_DSS_COLOR_RGBX16:
case OMAP_DSS_COLOR_ARGB16_1555:
case OMAP_DSS_COLOR_XRGB16_1555:
return 16;
case OMAP_DSS_COLOR_RGB24P:
return 24;
case OMAP_DSS_COLOR_RGB24U:
case OMAP_DSS_COLOR_ARGB32:
case OMAP_DSS_COLOR_RGBA32:
case OMAP_DSS_COLOR_RGBX32:
return 32;
default:
BUG();
}
}
static s32 pixinc(int pixels, u8 ps)
{
if (pixels == 1)
return 1;
else if (pixels > 1)
return 1 + (pixels - 1) * ps;
else if (pixels < 0)
return 1 - (-pixels + 1) * ps;
else
BUG();
}
static void calc_vrfb_rotation_offset(u8 rotation, bool mirror,
u16 screen_width,
u16 width, u16 height,
enum omap_color_mode color_mode, bool fieldmode,
unsigned int field_offset,
unsigned *offset0, unsigned *offset1,
s32 *row_inc, s32 *pix_inc)
{
u8 ps;
/* FIXME CLUT formats */
switch (color_mode) {
case OMAP_DSS_COLOR_CLUT1:
case OMAP_DSS_COLOR_CLUT2:
case OMAP_DSS_COLOR_CLUT4:
case OMAP_DSS_COLOR_CLUT8:
BUG();
return;
case OMAP_DSS_COLOR_YUV2:
case OMAP_DSS_COLOR_UYVY:
ps = 4;
break;
default:
ps = color_mode_to_bpp(color_mode) / 8;
break;
}
DSSDBG("calc_rot(%d): scrw %d, %dx%d\n", rotation, screen_width,
width, height);
/*
* field 0 = even field = bottom field
* field 1 = odd field = top field
*/
switch (rotation + mirror * 4) {
case OMAP_DSS_ROT_0:
case OMAP_DSS_ROT_180:
/*
* If the pixel format is YUV or UYVY divide the width
* of the image by 2 for 0 and 180 degree rotation.
*/
if (color_mode == OMAP_DSS_COLOR_YUV2 ||
color_mode == OMAP_DSS_COLOR_UYVY)
width = width >> 1;
case OMAP_DSS_ROT_90:
case OMAP_DSS_ROT_270:
*offset1 = 0;
if (field_offset)
*offset0 = field_offset * screen_width * ps;
else
*offset0 = 0;
*row_inc = pixinc(1 + (screen_width - width) +
(fieldmode ? screen_width : 0),
ps);
*pix_inc = pixinc(1, ps);
break;
case OMAP_DSS_ROT_0 + 4:
case OMAP_DSS_ROT_180 + 4:
/* If the pixel format is YUV or UYVY divide the width
* of the image by 2 for 0 degree and 180 degree
*/
if (color_mode == OMAP_DSS_COLOR_YUV2 ||
color_mode == OMAP_DSS_COLOR_UYVY)
width = width >> 1;
case OMAP_DSS_ROT_90 + 4:
case OMAP_DSS_ROT_270 + 4:
*offset1 = 0;
if (field_offset)
*offset0 = field_offset * screen_width * ps;
else
*offset0 = 0;
*row_inc = pixinc(1 - (screen_width + width) -
(fieldmode ? screen_width : 0),
ps);
*pix_inc = pixinc(1, ps);
break;
default:
BUG();
}
}
static void calc_dma_rotation_offset(u8 rotation, bool mirror,
u16 screen_width,
u16 width, u16 height,
enum omap_color_mode color_mode, bool fieldmode,
unsigned int field_offset,
unsigned *offset0, unsigned *offset1,
s32 *row_inc, s32 *pix_inc)
{
u8 ps;
u16 fbw, fbh;
/* FIXME CLUT formats */
switch (color_mode) {
case OMAP_DSS_COLOR_CLUT1:
case OMAP_DSS_COLOR_CLUT2:
case OMAP_DSS_COLOR_CLUT4:
case OMAP_DSS_COLOR_CLUT8:
BUG();
return;
default:
ps = color_mode_to_bpp(color_mode) / 8;
break;
}
DSSDBG("calc_rot(%d): scrw %d, %dx%d\n", rotation, screen_width,
width, height);
/* width & height are overlay sizes, convert to fb sizes */
if (rotation == OMAP_DSS_ROT_0 || rotation == OMAP_DSS_ROT_180) {
fbw = width;
fbh = height;
} else {
fbw = height;
fbh = width;
}
/*
* field 0 = even field = bottom field
* field 1 = odd field = top field
*/
switch (rotation + mirror * 4) {
case OMAP_DSS_ROT_0:
*offset1 = 0;
if (field_offset)
*offset0 = *offset1 + field_offset * screen_width * ps;
else
*offset0 = *offset1;
*row_inc = pixinc(1 + (screen_width - fbw) +
(fieldmode ? screen_width : 0),
ps);
*pix_inc = pixinc(1, ps);
break;
case OMAP_DSS_ROT_90:
*offset1 = screen_width * (fbh - 1) * ps;
if (field_offset)
*offset0 = *offset1 + field_offset * ps;
else
*offset0 = *offset1;
*row_inc = pixinc(screen_width * (fbh - 1) + 1 +
(fieldmode ? 1 : 0), ps);
*pix_inc = pixinc(-screen_width, ps);
break;
case OMAP_DSS_ROT_180:
*offset1 = (screen_width * (fbh - 1) + fbw - 1) * ps;
if (field_offset)
*offset0 = *offset1 - field_offset * screen_width * ps;
else
*offset0 = *offset1;
*row_inc = pixinc(-1 -
(screen_width - fbw) -
(fieldmode ? screen_width : 0),
ps);
*pix_inc = pixinc(-1, ps);
break;
case OMAP_DSS_ROT_270:
*offset1 = (fbw - 1) * ps;
if (field_offset)
*offset0 = *offset1 - field_offset * ps;
else
*offset0 = *offset1;
*row_inc = pixinc(-screen_width * (fbh - 1) - 1 -
(fieldmode ? 1 : 0), ps);
*pix_inc = pixinc(screen_width, ps);
break;
/* mirroring */
case OMAP_DSS_ROT_0 + 4:
*offset1 = (fbw - 1) * ps;
if (field_offset)
*offset0 = *offset1 + field_offset * screen_width * ps;
else
*offset0 = *offset1;
*row_inc = pixinc(screen_width * 2 - 1 +
(fieldmode ? screen_width : 0),
ps);
*pix_inc = pixinc(-1, ps);
break;
case OMAP_DSS_ROT_90 + 4:
*offset1 = 0;
if (field_offset)
*offset0 = *offset1 + field_offset * ps;
else
*offset0 = *offset1;
*row_inc = pixinc(-screen_width * (fbh - 1) + 1 +
(fieldmode ? 1 : 0),
ps);
*pix_inc = pixinc(screen_width, ps);
break;
case OMAP_DSS_ROT_180 + 4:
*offset1 = screen_width * (fbh - 1) * ps;
if (field_offset)
*offset0 = *offset1 - field_offset * screen_width * ps;
else
*offset0 = *offset1;
*row_inc = pixinc(1 - screen_width * 2 -
(fieldmode ? screen_width : 0),
ps);
*pix_inc = pixinc(1, ps);
break;
case OMAP_DSS_ROT_270 + 4:
*offset1 = (screen_width * (fbh - 1) + fbw - 1) * ps;
if (field_offset)
*offset0 = *offset1 - field_offset * ps;
else
*offset0 = *offset1;
*row_inc = pixinc(screen_width * (fbh - 1) - 1 -
(fieldmode ? 1 : 0),
ps);
*pix_inc = pixinc(-screen_width, ps);
break;
default:
BUG();
}
}
static unsigned long calc_fclk_five_taps(enum omap_channel channel, u16 width,
u16 height, u16 out_width, u16 out_height,
enum omap_color_mode color_mode)
{
u32 fclk = 0;
u64 tmp, pclk = dispc_mgr_pclk_rate(channel);
if (height <= out_height && width <= out_width)
return (unsigned long) pclk;
if (height > out_height) {
struct omap_dss_device *dssdev = dispc_mgr_get_device(channel);
unsigned int ppl = dssdev->panel.timings.x_res;
tmp = pclk * height * out_width;
do_div(tmp, 2 * out_height * ppl);
fclk = tmp;
if (height > 2 * out_height) {
if (ppl == out_width)
return 0;
tmp = pclk * (height - 2 * out_height) * out_width;
do_div(tmp, 2 * out_height * (ppl - out_width));
fclk = max(fclk, (u32) tmp);
}
}
if (width > out_width) {
tmp = pclk * width;
do_div(tmp, out_width);
fclk = max(fclk, (u32) tmp);
if (color_mode == OMAP_DSS_COLOR_RGB24U)
fclk <<= 1;
}
return fclk;
}
static unsigned long calc_fclk(enum omap_channel channel, u16 width,
u16 height, u16 out_width, u16 out_height)
{
unsigned int hf, vf;
unsigned long pclk = dispc_mgr_pclk_rate(channel);
/*
* FIXME how to determine the 'A' factor
* for the no downscaling case ?
*/
if (width > 3 * out_width)
hf = 4;
else if (width > 2 * out_width)
hf = 3;
else if (width > out_width)
hf = 2;
else
hf = 1;
if (height > out_height)
vf = 2;
else
vf = 1;
if (cpu_is_omap24xx()) {
if (vf > 1 && hf > 1)
return pclk * 4;
else
return pclk * 2;
} else if (cpu_is_omap34xx()) {
return pclk * vf * hf;
} else {
if (hf > 1)
return DIV_ROUND_UP(pclk, out_width) * width;
else
return pclk;
}
}
static int dispc_ovl_calc_scaling(enum omap_plane plane,
enum omap_channel channel, u16 width, u16 height,
u16 out_width, u16 out_height,
enum omap_color_mode color_mode, bool *five_taps)
{
struct omap_overlay *ovl = omap_dss_get_overlay(plane);
const int maxdownscale = dss_feat_get_param_max(FEAT_PARAM_DOWNSCALE);
const int maxsinglelinewidth =
dss_feat_get_param_max(FEAT_PARAM_LINEWIDTH);
unsigned long fclk = 0;
if (width == out_width && height == out_height)
return 0;
if ((ovl->caps & OMAP_DSS_OVL_CAP_SCALE) == 0)
return -EINVAL;
if (out_width < width / maxdownscale ||
out_width > width * 8)
return -EINVAL;
if (out_height < height / maxdownscale ||
out_height > height * 8)
return -EINVAL;
if (cpu_is_omap24xx()) {
if (width > maxsinglelinewidth)
DSSERR("Cannot scale max input width exceeded");
*five_taps = false;
fclk = calc_fclk(channel, width, height, out_width,
out_height);
} else if (cpu_is_omap34xx()) {
if (width > (maxsinglelinewidth * 2)) {
DSSERR("Cannot setup scaling");
DSSERR("width exceeds maximum width possible");
return -EINVAL;
}
fclk = calc_fclk_five_taps(channel, width, height, out_width,
out_height, color_mode);
if (width > maxsinglelinewidth) {
if (height > out_height && height < out_height * 2)
*five_taps = false;
else {
DSSERR("cannot setup scaling with five taps");
return -EINVAL;
}
}
if (!*five_taps)
fclk = calc_fclk(channel, width, height, out_width,
out_height);
} else {
if (width > maxsinglelinewidth) {
DSSERR("Cannot scale width exceeds max line width");
return -EINVAL;
}
fclk = calc_fclk(channel, width, height, out_width,
out_height);
}
DSSDBG("required fclk rate = %lu Hz\n", fclk);
DSSDBG("current fclk rate = %lu Hz\n", dispc_fclk_rate());
if (!fclk || fclk > dispc_fclk_rate()) {
DSSERR("failed to set up scaling, "
"required fclk rate = %lu Hz, "
"current fclk rate = %lu Hz\n",
fclk, dispc_fclk_rate());
return -EINVAL;
}
return 0;
}
int dispc_ovl_setup(enum omap_plane plane, struct omap_overlay_info *oi,
bool ilace, bool replication)
{
struct omap_overlay *ovl = omap_dss_get_overlay(plane);
bool five_taps = true;
bool fieldmode = 0;
int r, cconv = 0;
unsigned offset0, offset1;
s32 row_inc;
s32 pix_inc;
u16 frame_height = oi->height;
unsigned int field_offset = 0;
u16 outw, outh;
enum omap_channel channel;
channel = dispc_ovl_get_channel_out(plane);
DSSDBG("dispc_ovl_setup %d, pa %x, pa_uv %x, sw %d, %d,%d, %dx%d -> "
"%dx%d, cmode %x, rot %d, mir %d, ilace %d chan %d repl %d\n",
plane, oi->paddr, oi->p_uv_addr,
oi->screen_width, oi->pos_x, oi->pos_y, oi->width, oi->height,
oi->out_width, oi->out_height, oi->color_mode, oi->rotation,
oi->mirror, ilace, channel, replication);
if (oi->paddr == 0)
return -EINVAL;
outw = oi->out_width == 0 ? oi->width : oi->out_width;
outh = oi->out_height == 0 ? oi->height : oi->out_height;
if (ilace && oi->height == outh)
fieldmode = 1;
if (ilace) {
if (fieldmode)
oi->height /= 2;
oi->pos_y /= 2;
outh /= 2;
DSSDBG("adjusting for ilace: height %d, pos_y %d, "
"out_height %d\n",
oi->height, oi->pos_y, outh);
}
if (!dss_feat_color_mode_supported(plane, oi->color_mode))
return -EINVAL;
r = dispc_ovl_calc_scaling(plane, channel, oi->width, oi->height,
outw, outh, oi->color_mode,
&five_taps);
if (r)
return r;
if (oi->color_mode == OMAP_DSS_COLOR_YUV2 ||
oi->color_mode == OMAP_DSS_COLOR_UYVY ||
oi->color_mode == OMAP_DSS_COLOR_NV12)
cconv = 1;
if (ilace && !fieldmode) {
/*
* when downscaling the bottom field may have to start several
* source lines below the top field. Unfortunately ACCUI
* registers will only hold the fractional part of the offset
* so the integer part must be added to the base address of the
* bottom field.
*/
if (!oi->height || oi->height == outh)
field_offset = 0;
else
field_offset = oi->height / outh / 2;
}
/* Fields are independent but interleaved in memory. */
if (fieldmode)
field_offset = 1;
if (oi->rotation_type == OMAP_DSS_ROT_DMA)
calc_dma_rotation_offset(oi->rotation, oi->mirror,
oi->screen_width, oi->width, frame_height,
oi->color_mode, fieldmode, field_offset,
&offset0, &offset1, &row_inc, &pix_inc);
else
calc_vrfb_rotation_offset(oi->rotation, oi->mirror,
oi->screen_width, oi->width, frame_height,
oi->color_mode, fieldmode, field_offset,
&offset0, &offset1, &row_inc, &pix_inc);
DSSDBG("offset0 %u, offset1 %u, row_inc %d, pix_inc %d\n",
offset0, offset1, row_inc, pix_inc);
dispc_ovl_set_color_mode(plane, oi->color_mode);
dispc_ovl_set_ba0(plane, oi->paddr + offset0);
dispc_ovl_set_ba1(plane, oi->paddr + offset1);
if (OMAP_DSS_COLOR_NV12 == oi->color_mode) {
dispc_ovl_set_ba0_uv(plane, oi->p_uv_addr + offset0);
dispc_ovl_set_ba1_uv(plane, oi->p_uv_addr + offset1);
}
dispc_ovl_set_row_inc(plane, row_inc);
dispc_ovl_set_pix_inc(plane, pix_inc);
DSSDBG("%d,%d %dx%d -> %dx%d\n", oi->pos_x, oi->pos_y, oi->width,
oi->height, outw, outh);
dispc_ovl_set_pos(plane, oi->pos_x, oi->pos_y);
dispc_ovl_set_pic_size(plane, oi->width, oi->height);
if (ovl->caps & OMAP_DSS_OVL_CAP_SCALE) {
dispc_ovl_set_scaling(plane, oi->width, oi->height,
outw, outh,
ilace, five_taps, fieldmode,
oi->color_mode, oi->rotation);
dispc_ovl_set_vid_size(plane, outw, outh);
dispc_ovl_set_vid_color_conv(plane, cconv);
}
dispc_ovl_set_rotation_attrs(plane, oi->rotation, oi->mirror,
oi->color_mode);
dispc_ovl_set_zorder(plane, oi->zorder);
dispc_ovl_set_pre_mult_alpha(plane, oi->pre_mult_alpha);
dispc_ovl_setup_global_alpha(plane, oi->global_alpha);
dispc_ovl_enable_replication(plane, replication);
return 0;
}
int dispc_ovl_enable(enum omap_plane plane, bool enable)
{
DSSDBG("dispc_enable_plane %d, %d\n", plane, enable);
REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), enable ? 1 : 0, 0, 0);
return 0;
}
static void dispc_disable_isr(void *data, u32 mask)
{
struct completion *compl = data;
complete(compl);
}
static void _enable_lcd_out(enum omap_channel channel, bool enable)
{
if (channel == OMAP_DSS_CHANNEL_LCD2) {
REG_FLD_MOD(DISPC_CONTROL2, enable ? 1 : 0, 0, 0);
/* flush posted write */
dispc_read_reg(DISPC_CONTROL2);
} else {
REG_FLD_MOD(DISPC_CONTROL, enable ? 1 : 0, 0, 0);
dispc_read_reg(DISPC_CONTROL);
}
}
static void dispc_mgr_enable_lcd_out(enum omap_channel channel, bool enable)
{
struct completion frame_done_completion;
bool is_on;
int r;
u32 irq;
/* When we disable LCD output, we need to wait until frame is done.
* Otherwise the DSS is still working, and turning off the clocks
* prevents DSS from going to OFF mode */
is_on = channel == OMAP_DSS_CHANNEL_LCD2 ?
REG_GET(DISPC_CONTROL2, 0, 0) :
REG_GET(DISPC_CONTROL, 0, 0);
irq = channel == OMAP_DSS_CHANNEL_LCD2 ? DISPC_IRQ_FRAMEDONE2 :
DISPC_IRQ_FRAMEDONE;
if (!enable && is_on) {
init_completion(&frame_done_completion);
r = omap_dispc_register_isr(dispc_disable_isr,
&frame_done_completion, irq);
if (r)
DSSERR("failed to register FRAMEDONE isr\n");
}
_enable_lcd_out(channel, enable);
if (!enable && is_on) {
if (!wait_for_completion_timeout(&frame_done_completion,
msecs_to_jiffies(100)))
DSSERR("timeout waiting for FRAME DONE\n");
r = omap_dispc_unregister_isr(dispc_disable_isr,
&frame_done_completion, irq);
if (r)
DSSERR("failed to unregister FRAMEDONE isr\n");
}
}
static void _enable_digit_out(bool enable)
{
REG_FLD_MOD(DISPC_CONTROL, enable ? 1 : 0, 1, 1);
/* flush posted write */
dispc_read_reg(DISPC_CONTROL);
}
static void dispc_mgr_enable_digit_out(bool enable)
{
struct completion frame_done_completion;
enum dss_hdmi_venc_clk_source_select src;
int r, i;
u32 irq_mask;
int num_irqs;
if (REG_GET(DISPC_CONTROL, 1, 1) == enable)
return;
src = dss_get_hdmi_venc_clk_source();
if (enable) {
unsigned long flags;
/* When we enable digit output, we'll get an extra digit
* sync lost interrupt, that we need to ignore */
spin_lock_irqsave(&dispc.irq_lock, flags);
dispc.irq_error_mask &= ~DISPC_IRQ_SYNC_LOST_DIGIT;
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc.irq_lock, flags);
}
/* When we disable digit output, we need to wait until fields are done.
* Otherwise the DSS is still working, and turning off the clocks
* prevents DSS from going to OFF mode. And when enabling, we need to
* wait for the extra sync losts */
init_completion(&frame_done_completion);
if (src == DSS_HDMI_M_PCLK && enable == false) {
irq_mask = DISPC_IRQ_FRAMEDONETV;
num_irqs = 1;
} else {
irq_mask = DISPC_IRQ_EVSYNC_EVEN | DISPC_IRQ_EVSYNC_ODD;
/* XXX I understand from TRM that we should only wait for the
* current field to complete. But it seems we have to wait for
* both fields */
num_irqs = 2;
}
r = omap_dispc_register_isr(dispc_disable_isr, &frame_done_completion,
irq_mask);
if (r)
DSSERR("failed to register %x isr\n", irq_mask);
_enable_digit_out(enable);
for (i = 0; i < num_irqs; ++i) {
if (!wait_for_completion_timeout(&frame_done_completion,
msecs_to_jiffies(100)))
DSSERR("timeout waiting for digit out to %s\n",
enable ? "start" : "stop");
}
r = omap_dispc_unregister_isr(dispc_disable_isr, &frame_done_completion,
irq_mask);
if (r)
DSSERR("failed to unregister %x isr\n", irq_mask);
if (enable) {
unsigned long flags;
spin_lock_irqsave(&dispc.irq_lock, flags);
dispc.irq_error_mask |= DISPC_IRQ_SYNC_LOST_DIGIT;
dispc_write_reg(DISPC_IRQSTATUS, DISPC_IRQ_SYNC_LOST_DIGIT);
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc.irq_lock, flags);
}
}
bool dispc_mgr_is_enabled(enum omap_channel channel)
{
if (channel == OMAP_DSS_CHANNEL_LCD)
return !!REG_GET(DISPC_CONTROL, 0, 0);
else if (channel == OMAP_DSS_CHANNEL_DIGIT)
return !!REG_GET(DISPC_CONTROL, 1, 1);
else if (channel == OMAP_DSS_CHANNEL_LCD2)
return !!REG_GET(DISPC_CONTROL2, 0, 0);
else
BUG();
}
void dispc_mgr_enable(enum omap_channel channel, bool enable)
{
if (dispc_mgr_is_lcd(channel))
dispc_mgr_enable_lcd_out(channel, enable);
else if (channel == OMAP_DSS_CHANNEL_DIGIT)
dispc_mgr_enable_digit_out(enable);
else
BUG();
}
void dispc_lcd_enable_signal_polarity(bool act_high)
{
if (!dss_has_feature(FEAT_LCDENABLEPOL))
return;
REG_FLD_MOD(DISPC_CONTROL, act_high ? 1 : 0, 29, 29);
}
void dispc_lcd_enable_signal(bool enable)
{
if (!dss_has_feature(FEAT_LCDENABLESIGNAL))
return;
REG_FLD_MOD(DISPC_CONTROL, enable ? 1 : 0, 28, 28);
}
void dispc_pck_free_enable(bool enable)
{
if (!dss_has_feature(FEAT_PCKFREEENABLE))
return;
REG_FLD_MOD(DISPC_CONTROL, enable ? 1 : 0, 27, 27);
}
void dispc_mgr_enable_fifohandcheck(enum omap_channel channel, bool enable)
{
if (channel == OMAP_DSS_CHANNEL_LCD2)
REG_FLD_MOD(DISPC_CONFIG2, enable ? 1 : 0, 16, 16);
else
REG_FLD_MOD(DISPC_CONFIG, enable ? 1 : 0, 16, 16);
}
void dispc_mgr_set_lcd_display_type(enum omap_channel channel,
enum omap_lcd_display_type type)
{
int mode;
switch (type) {
case OMAP_DSS_LCD_DISPLAY_STN:
mode = 0;
break;
case OMAP_DSS_LCD_DISPLAY_TFT:
mode = 1;
break;
default:
BUG();
return;
}
if (channel == OMAP_DSS_CHANNEL_LCD2)
REG_FLD_MOD(DISPC_CONTROL2, mode, 3, 3);
else
REG_FLD_MOD(DISPC_CONTROL, mode, 3, 3);
}
void dispc_set_loadmode(enum omap_dss_load_mode mode)
{
REG_FLD_MOD(DISPC_CONFIG, mode, 2, 1);
}
static void dispc_mgr_set_default_color(enum omap_channel channel, u32 color)
{
dispc_write_reg(DISPC_DEFAULT_COLOR(channel), color);
}
static void dispc_mgr_set_trans_key(enum omap_channel ch,
enum omap_dss_trans_key_type type,
u32 trans_key)
{
if (ch == OMAP_DSS_CHANNEL_LCD)
REG_FLD_MOD(DISPC_CONFIG, type, 11, 11);
else if (ch == OMAP_DSS_CHANNEL_DIGIT)
REG_FLD_MOD(DISPC_CONFIG, type, 13, 13);
else /* OMAP_DSS_CHANNEL_LCD2 */
REG_FLD_MOD(DISPC_CONFIG2, type, 11, 11);
dispc_write_reg(DISPC_TRANS_COLOR(ch), trans_key);
}
static void dispc_mgr_enable_trans_key(enum omap_channel ch, bool enable)
{
if (ch == OMAP_DSS_CHANNEL_LCD)
REG_FLD_MOD(DISPC_CONFIG, enable, 10, 10);
else if (ch == OMAP_DSS_CHANNEL_DIGIT)
REG_FLD_MOD(DISPC_CONFIG, enable, 12, 12);
else /* OMAP_DSS_CHANNEL_LCD2 */
REG_FLD_MOD(DISPC_CONFIG2, enable, 10, 10);
}
static void dispc_mgr_enable_alpha_fixed_zorder(enum omap_channel ch,
bool enable)
{
if (!dss_has_feature(FEAT_ALPHA_FIXED_ZORDER))
return;
if (ch == OMAP_DSS_CHANNEL_LCD)
REG_FLD_MOD(DISPC_CONFIG, enable, 18, 18);
else if (ch == OMAP_DSS_CHANNEL_DIGIT)
REG_FLD_MOD(DISPC_CONFIG, enable, 19, 19);
}
void dispc_mgr_setup(enum omap_channel channel,
struct omap_overlay_manager_info *info)
{
dispc_mgr_set_default_color(channel, info->default_color);
dispc_mgr_set_trans_key(channel, info->trans_key_type, info->trans_key);
dispc_mgr_enable_trans_key(channel, info->trans_enabled);
dispc_mgr_enable_alpha_fixed_zorder(channel,
info->partial_alpha_enabled);
if (dss_has_feature(FEAT_CPR)) {
dispc_mgr_enable_cpr(channel, info->cpr_enable);
dispc_mgr_set_cpr_coef(channel, &info->cpr_coefs);
}
}
void dispc_mgr_set_tft_data_lines(enum omap_channel channel, u8 data_lines)
{
int code;
switch (data_lines) {
case 12:
code = 0;
break;
case 16:
code = 1;
break;
case 18:
code = 2;
break;
case 24:
code = 3;
break;
default:
BUG();
return;
}
if (channel == OMAP_DSS_CHANNEL_LCD2)
REG_FLD_MOD(DISPC_CONTROL2, code, 9, 8);
else
REG_FLD_MOD(DISPC_CONTROL, code, 9, 8);
}
void dispc_mgr_set_io_pad_mode(enum dss_io_pad_mode mode)
{
u32 l;
int gpout0, gpout1;
switch (mode) {
case DSS_IO_PAD_MODE_RESET:
gpout0 = 0;
gpout1 = 0;
break;
case DSS_IO_PAD_MODE_RFBI:
gpout0 = 1;
gpout1 = 0;
break;
case DSS_IO_PAD_MODE_BYPASS:
gpout0 = 1;
gpout1 = 1;
break;
default:
BUG();
return;
}
l = dispc_read_reg(DISPC_CONTROL);
l = FLD_MOD(l, gpout0, 15, 15);
l = FLD_MOD(l, gpout1, 16, 16);
dispc_write_reg(DISPC_CONTROL, l);
}
void dispc_mgr_enable_stallmode(enum omap_channel channel, bool enable)
{
if (channel == OMAP_DSS_CHANNEL_LCD2)
REG_FLD_MOD(DISPC_CONTROL2, enable, 11, 11);
else
REG_FLD_MOD(DISPC_CONTROL, enable, 11, 11);
}
static bool _dispc_lcd_timings_ok(int hsw, int hfp, int hbp,
int vsw, int vfp, int vbp)
{
if (cpu_is_omap24xx() || omap_rev() < OMAP3430_REV_ES3_0) {
if (hsw < 1 || hsw > 64 ||
hfp < 1 || hfp > 256 ||
hbp < 1 || hbp > 256 ||
vsw < 1 || vsw > 64 ||
vfp < 0 || vfp > 255 ||
vbp < 0 || vbp > 255)
return false;
} else {
if (hsw < 1 || hsw > 256 ||
hfp < 1 || hfp > 4096 ||
hbp < 1 || hbp > 4096 ||
vsw < 1 || vsw > 256 ||
vfp < 0 || vfp > 4095 ||
vbp < 0 || vbp > 4095)
return false;
}
return true;
}
bool dispc_lcd_timings_ok(struct omap_video_timings *timings)
{
return _dispc_lcd_timings_ok(timings->hsw, timings->hfp,
timings->hbp, timings->vsw,
timings->vfp, timings->vbp);
}
static void _dispc_mgr_set_lcd_timings(enum omap_channel channel, int hsw,
int hfp, int hbp, int vsw, int vfp, int vbp)
{
u32 timing_h, timing_v;
if (cpu_is_omap24xx() || omap_rev() < OMAP3430_REV_ES3_0) {
timing_h = FLD_VAL(hsw-1, 5, 0) | FLD_VAL(hfp-1, 15, 8) |
FLD_VAL(hbp-1, 27, 20);
timing_v = FLD_VAL(vsw-1, 5, 0) | FLD_VAL(vfp, 15, 8) |
FLD_VAL(vbp, 27, 20);
} else {
timing_h = FLD_VAL(hsw-1, 7, 0) | FLD_VAL(hfp-1, 19, 8) |
FLD_VAL(hbp-1, 31, 20);
timing_v = FLD_VAL(vsw-1, 7, 0) | FLD_VAL(vfp, 19, 8) |
FLD_VAL(vbp, 31, 20);
}
dispc_write_reg(DISPC_TIMING_H(channel), timing_h);
dispc_write_reg(DISPC_TIMING_V(channel), timing_v);
}
/* change name to mode? */
void dispc_mgr_set_lcd_timings(enum omap_channel channel,
struct omap_video_timings *timings)
{
unsigned xtot, ytot;
unsigned long ht, vt;
if (!_dispc_lcd_timings_ok(timings->hsw, timings->hfp,
timings->hbp, timings->vsw,
timings->vfp, timings->vbp))
BUG();
_dispc_mgr_set_lcd_timings(channel, timings->hsw, timings->hfp,
timings->hbp, timings->vsw, timings->vfp,
timings->vbp);
dispc_mgr_set_lcd_size(channel, timings->x_res, timings->y_res);
xtot = timings->x_res + timings->hfp + timings->hsw + timings->hbp;
ytot = timings->y_res + timings->vfp + timings->vsw + timings->vbp;
ht = (timings->pixel_clock * 1000) / xtot;
vt = (timings->pixel_clock * 1000) / xtot / ytot;
DSSDBG("channel %d xres %u yres %u\n", channel, timings->x_res,
timings->y_res);
DSSDBG("pck %u\n", timings->pixel_clock);
DSSDBG("hsw %d hfp %d hbp %d vsw %d vfp %d vbp %d\n",
timings->hsw, timings->hfp, timings->hbp,
timings->vsw, timings->vfp, timings->vbp);
DSSDBG("hsync %luHz, vsync %luHz\n", ht, vt);
}
static void dispc_mgr_set_lcd_divisor(enum omap_channel channel, u16 lck_div,
u16 pck_div)
{
BUG_ON(lck_div < 1);
BUG_ON(pck_div < 1);
dispc_write_reg(DISPC_DIVISORo(channel),
FLD_VAL(lck_div, 23, 16) | FLD_VAL(pck_div, 7, 0));
}
static void dispc_mgr_get_lcd_divisor(enum omap_channel channel, int *lck_div,
int *pck_div)
{
u32 l;
l = dispc_read_reg(DISPC_DIVISORo(channel));
*lck_div = FLD_GET(l, 23, 16);
*pck_div = FLD_GET(l, 7, 0);
}
unsigned long dispc_fclk_rate(void)
{
struct platform_device *dsidev;
unsigned long r = 0;
switch (dss_get_dispc_clk_source()) {
case OMAP_DSS_CLK_SRC_FCK:
r = clk_get_rate(dispc.dss_clk);
break;
case OMAP_DSS_CLK_SRC_DSI_PLL_HSDIV_DISPC:
dsidev = dsi_get_dsidev_from_id(0);
r = dsi_get_pll_hsdiv_dispc_rate(dsidev);
break;
case OMAP_DSS_CLK_SRC_DSI2_PLL_HSDIV_DISPC:
dsidev = dsi_get_dsidev_from_id(1);
r = dsi_get_pll_hsdiv_dispc_rate(dsidev);
break;
default:
BUG();
}
return r;
}
unsigned long dispc_mgr_lclk_rate(enum omap_channel channel)
{
struct platform_device *dsidev;
int lcd;
unsigned long r;
u32 l;
l = dispc_read_reg(DISPC_DIVISORo(channel));
lcd = FLD_GET(l, 23, 16);
switch (dss_get_lcd_clk_source(channel)) {
case OMAP_DSS_CLK_SRC_FCK:
r = clk_get_rate(dispc.dss_clk);
break;
case OMAP_DSS_CLK_SRC_DSI_PLL_HSDIV_DISPC:
dsidev = dsi_get_dsidev_from_id(0);
r = dsi_get_pll_hsdiv_dispc_rate(dsidev);
break;
case OMAP_DSS_CLK_SRC_DSI2_PLL_HSDIV_DISPC:
dsidev = dsi_get_dsidev_from_id(1);
r = dsi_get_pll_hsdiv_dispc_rate(dsidev);
break;
default:
BUG();
}
return r / lcd;
}
unsigned long dispc_mgr_pclk_rate(enum omap_channel channel)
{
unsigned long r;
if (dispc_mgr_is_lcd(channel)) {
int pcd;
u32 l;
l = dispc_read_reg(DISPC_DIVISORo(channel));
pcd = FLD_GET(l, 7, 0);
r = dispc_mgr_lclk_rate(channel);
return r / pcd;
} else {
struct omap_dss_device *dssdev =
dispc_mgr_get_device(channel);
switch (dssdev->type) {
case OMAP_DISPLAY_TYPE_VENC:
return venc_get_pixel_clock();
case OMAP_DISPLAY_TYPE_HDMI:
return hdmi_get_pixel_clock();
default:
BUG();
}
}
}
void dispc_dump_clocks(struct seq_file *s)
{
int lcd, pcd;
u32 l;
enum omap_dss_clk_source dispc_clk_src = dss_get_dispc_clk_source();
enum omap_dss_clk_source lcd_clk_src;
if (dispc_runtime_get())
return;
seq_printf(s, "- DISPC -\n");
seq_printf(s, "dispc fclk source = %s (%s)\n",
dss_get_generic_clk_source_name(dispc_clk_src),
dss_feat_get_clk_source_name(dispc_clk_src));
seq_printf(s, "fck\t\t%-16lu\n", dispc_fclk_rate());
if (dss_has_feature(FEAT_CORE_CLK_DIV)) {
seq_printf(s, "- DISPC-CORE-CLK -\n");
l = dispc_read_reg(DISPC_DIVISOR);
lcd = FLD_GET(l, 23, 16);
seq_printf(s, "lck\t\t%-16lulck div\t%u\n",
(dispc_fclk_rate()/lcd), lcd);
}
seq_printf(s, "- LCD1 -\n");
lcd_clk_src = dss_get_lcd_clk_source(OMAP_DSS_CHANNEL_LCD);
seq_printf(s, "lcd1_clk source = %s (%s)\n",
dss_get_generic_clk_source_name(lcd_clk_src),
dss_feat_get_clk_source_name(lcd_clk_src));
dispc_mgr_get_lcd_divisor(OMAP_DSS_CHANNEL_LCD, &lcd, &pcd);
seq_printf(s, "lck\t\t%-16lulck div\t%u\n",
dispc_mgr_lclk_rate(OMAP_DSS_CHANNEL_LCD), lcd);
seq_printf(s, "pck\t\t%-16lupck div\t%u\n",
dispc_mgr_pclk_rate(OMAP_DSS_CHANNEL_LCD), pcd);
if (dss_has_feature(FEAT_MGR_LCD2)) {
seq_printf(s, "- LCD2 -\n");
lcd_clk_src = dss_get_lcd_clk_source(OMAP_DSS_CHANNEL_LCD2);
seq_printf(s, "lcd2_clk source = %s (%s)\n",
dss_get_generic_clk_source_name(lcd_clk_src),
dss_feat_get_clk_source_name(lcd_clk_src));
dispc_mgr_get_lcd_divisor(OMAP_DSS_CHANNEL_LCD2, &lcd, &pcd);
seq_printf(s, "lck\t\t%-16lulck div\t%u\n",
dispc_mgr_lclk_rate(OMAP_DSS_CHANNEL_LCD2), lcd);
seq_printf(s, "pck\t\t%-16lupck div\t%u\n",
dispc_mgr_pclk_rate(OMAP_DSS_CHANNEL_LCD2), pcd);
}
dispc_runtime_put();
}
#ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS
void dispc_dump_irqs(struct seq_file *s)
{
unsigned long flags;
struct dispc_irq_stats stats;
spin_lock_irqsave(&dispc.irq_stats_lock, flags);
stats = dispc.irq_stats;
memset(&dispc.irq_stats, 0, sizeof(dispc.irq_stats));
dispc.irq_stats.last_reset = jiffies;
spin_unlock_irqrestore(&dispc.irq_stats_lock, flags);
seq_printf(s, "period %u ms\n",
jiffies_to_msecs(jiffies - stats.last_reset));
seq_printf(s, "irqs %d\n", stats.irq_count);
#define PIS(x) \
seq_printf(s, "%-20s %10d\n", #x, stats.irqs[ffs(DISPC_IRQ_##x)-1]);
PIS(FRAMEDONE);
PIS(VSYNC);
PIS(EVSYNC_EVEN);
PIS(EVSYNC_ODD);
PIS(ACBIAS_COUNT_STAT);
PIS(PROG_LINE_NUM);
PIS(GFX_FIFO_UNDERFLOW);
PIS(GFX_END_WIN);
PIS(PAL_GAMMA_MASK);
PIS(OCP_ERR);
PIS(VID1_FIFO_UNDERFLOW);
PIS(VID1_END_WIN);
PIS(VID2_FIFO_UNDERFLOW);
PIS(VID2_END_WIN);
if (dss_feat_get_num_ovls() > 3) {
PIS(VID3_FIFO_UNDERFLOW);
PIS(VID3_END_WIN);
}
PIS(SYNC_LOST);
PIS(SYNC_LOST_DIGIT);
PIS(WAKEUP);
if (dss_has_feature(FEAT_MGR_LCD2)) {
PIS(FRAMEDONE2);
PIS(VSYNC2);
PIS(ACBIAS_COUNT_STAT2);
PIS(SYNC_LOST2);
}
#undef PIS
}
#endif
void dispc_dump_regs(struct seq_file *s)
{
int i, j;
const char *mgr_names[] = {
[OMAP_DSS_CHANNEL_LCD] = "LCD",
[OMAP_DSS_CHANNEL_DIGIT] = "TV",
[OMAP_DSS_CHANNEL_LCD2] = "LCD2",
};
const char *ovl_names[] = {
[OMAP_DSS_GFX] = "GFX",
[OMAP_DSS_VIDEO1] = "VID1",
[OMAP_DSS_VIDEO2] = "VID2",
[OMAP_DSS_VIDEO3] = "VID3",
};
const char **p_names;
#define DUMPREG(r) seq_printf(s, "%-50s %08x\n", #r, dispc_read_reg(r))
if (dispc_runtime_get())
return;
/* DISPC common registers */
DUMPREG(DISPC_REVISION);
DUMPREG(DISPC_SYSCONFIG);
DUMPREG(DISPC_SYSSTATUS);
DUMPREG(DISPC_IRQSTATUS);
DUMPREG(DISPC_IRQENABLE);
DUMPREG(DISPC_CONTROL);
DUMPREG(DISPC_CONFIG);
DUMPREG(DISPC_CAPABLE);
DUMPREG(DISPC_LINE_STATUS);
DUMPREG(DISPC_LINE_NUMBER);
if (dss_has_feature(FEAT_ALPHA_FIXED_ZORDER) ||
dss_has_feature(FEAT_ALPHA_FREE_ZORDER))
DUMPREG(DISPC_GLOBAL_ALPHA);
if (dss_has_feature(FEAT_MGR_LCD2)) {
DUMPREG(DISPC_CONTROL2);
DUMPREG(DISPC_CONFIG2);
}
#undef DUMPREG
#define DISPC_REG(i, name) name(i)
#define DUMPREG(i, r) seq_printf(s, "%s(%s)%*s %08x\n", #r, p_names[i], \
48 - strlen(#r) - strlen(p_names[i]), " ", \
dispc_read_reg(DISPC_REG(i, r)))
p_names = mgr_names;
/* DISPC channel specific registers */
for (i = 0; i < dss_feat_get_num_mgrs(); i++) {
DUMPREG(i, DISPC_DEFAULT_COLOR);
DUMPREG(i, DISPC_TRANS_COLOR);
DUMPREG(i, DISPC_SIZE_MGR);
if (i == OMAP_DSS_CHANNEL_DIGIT)
continue;
DUMPREG(i, DISPC_DEFAULT_COLOR);
DUMPREG(i, DISPC_TRANS_COLOR);
DUMPREG(i, DISPC_TIMING_H);
DUMPREG(i, DISPC_TIMING_V);
DUMPREG(i, DISPC_POL_FREQ);
DUMPREG(i, DISPC_DIVISORo);
DUMPREG(i, DISPC_SIZE_MGR);
DUMPREG(i, DISPC_DATA_CYCLE1);
DUMPREG(i, DISPC_DATA_CYCLE2);
DUMPREG(i, DISPC_DATA_CYCLE3);
if (dss_has_feature(FEAT_CPR)) {
DUMPREG(i, DISPC_CPR_COEF_R);
DUMPREG(i, DISPC_CPR_COEF_G);
DUMPREG(i, DISPC_CPR_COEF_B);
}
}
p_names = ovl_names;
for (i = 0; i < dss_feat_get_num_ovls(); i++) {
DUMPREG(i, DISPC_OVL_BA0);
DUMPREG(i, DISPC_OVL_BA1);
DUMPREG(i, DISPC_OVL_POSITION);
DUMPREG(i, DISPC_OVL_SIZE);
DUMPREG(i, DISPC_OVL_ATTRIBUTES);
DUMPREG(i, DISPC_OVL_FIFO_THRESHOLD);
DUMPREG(i, DISPC_OVL_FIFO_SIZE_STATUS);
DUMPREG(i, DISPC_OVL_ROW_INC);
DUMPREG(i, DISPC_OVL_PIXEL_INC);
if (dss_has_feature(FEAT_PRELOAD))
DUMPREG(i, DISPC_OVL_PRELOAD);
if (i == OMAP_DSS_GFX) {
DUMPREG(i, DISPC_OVL_WINDOW_SKIP);
DUMPREG(i, DISPC_OVL_TABLE_BA);
continue;
}
DUMPREG(i, DISPC_OVL_FIR);
DUMPREG(i, DISPC_OVL_PICTURE_SIZE);
DUMPREG(i, DISPC_OVL_ACCU0);
DUMPREG(i, DISPC_OVL_ACCU1);
if (dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) {
DUMPREG(i, DISPC_OVL_BA0_UV);
DUMPREG(i, DISPC_OVL_BA1_UV);
DUMPREG(i, DISPC_OVL_FIR2);
DUMPREG(i, DISPC_OVL_ACCU2_0);
DUMPREG(i, DISPC_OVL_ACCU2_1);
}
if (dss_has_feature(FEAT_ATTR2))
DUMPREG(i, DISPC_OVL_ATTRIBUTES2);
if (dss_has_feature(FEAT_PRELOAD))
DUMPREG(i, DISPC_OVL_PRELOAD);
}
#undef DISPC_REG
#undef DUMPREG
#define DISPC_REG(plane, name, i) name(plane, i)
#define DUMPREG(plane, name, i) \
seq_printf(s, "%s_%d(%s)%*s %08x\n", #name, i, p_names[plane], \
46 - strlen(#name) - strlen(p_names[plane]), " ", \
dispc_read_reg(DISPC_REG(plane, name, i)))
/* Video pipeline coefficient registers */
/* start from OMAP_DSS_VIDEO1 */
for (i = 1; i < dss_feat_get_num_ovls(); i++) {
for (j = 0; j < 8; j++)
DUMPREG(i, DISPC_OVL_FIR_COEF_H, j);
for (j = 0; j < 8; j++)
DUMPREG(i, DISPC_OVL_FIR_COEF_HV, j);
for (j = 0; j < 5; j++)
DUMPREG(i, DISPC_OVL_CONV_COEF, j);
if (dss_has_feature(FEAT_FIR_COEF_V)) {
for (j = 0; j < 8; j++)
DUMPREG(i, DISPC_OVL_FIR_COEF_V, j);
}
if (dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) {
for (j = 0; j < 8; j++)
DUMPREG(i, DISPC_OVL_FIR_COEF_H2, j);
for (j = 0; j < 8; j++)
DUMPREG(i, DISPC_OVL_FIR_COEF_HV2, j);
for (j = 0; j < 8; j++)
DUMPREG(i, DISPC_OVL_FIR_COEF_V2, j);
}
}
dispc_runtime_put();
#undef DISPC_REG
#undef DUMPREG
}
static void _dispc_mgr_set_pol_freq(enum omap_channel channel, bool onoff,
bool rf, bool ieo, bool ipc, bool ihs, bool ivs, u8 acbi,
u8 acb)
{
u32 l = 0;
DSSDBG("onoff %d rf %d ieo %d ipc %d ihs %d ivs %d acbi %d acb %d\n",
onoff, rf, ieo, ipc, ihs, ivs, acbi, acb);
l |= FLD_VAL(onoff, 17, 17);
l |= FLD_VAL(rf, 16, 16);
l |= FLD_VAL(ieo, 15, 15);
l |= FLD_VAL(ipc, 14, 14);
l |= FLD_VAL(ihs, 13, 13);
l |= FLD_VAL(ivs, 12, 12);
l |= FLD_VAL(acbi, 11, 8);
l |= FLD_VAL(acb, 7, 0);
dispc_write_reg(DISPC_POL_FREQ(channel), l);
}
void dispc_mgr_set_pol_freq(enum omap_channel channel,
enum omap_panel_config config, u8 acbi, u8 acb)
{
_dispc_mgr_set_pol_freq(channel, (config & OMAP_DSS_LCD_ONOFF) != 0,
(config & OMAP_DSS_LCD_RF) != 0,
(config & OMAP_DSS_LCD_IEO) != 0,
(config & OMAP_DSS_LCD_IPC) != 0,
(config & OMAP_DSS_LCD_IHS) != 0,
(config & OMAP_DSS_LCD_IVS) != 0,
acbi, acb);
}
/* with fck as input clock rate, find dispc dividers that produce req_pck */
void dispc_find_clk_divs(bool is_tft, unsigned long req_pck, unsigned long fck,
struct dispc_clock_info *cinfo)
{
u16 pcd_min, pcd_max;
unsigned long best_pck;
u16 best_ld, cur_ld;
u16 best_pd, cur_pd;
pcd_min = dss_feat_get_param_min(FEAT_PARAM_DSS_PCD);
pcd_max = dss_feat_get_param_max(FEAT_PARAM_DSS_PCD);
if (!is_tft)
pcd_min = 3;
best_pck = 0;
best_ld = 0;
best_pd = 0;
for (cur_ld = 1; cur_ld <= 255; ++cur_ld) {
unsigned long lck = fck / cur_ld;
for (cur_pd = pcd_min; cur_pd <= pcd_max; ++cur_pd) {
unsigned long pck = lck / cur_pd;
long old_delta = abs(best_pck - req_pck);
long new_delta = abs(pck - req_pck);
if (best_pck == 0 || new_delta < old_delta) {
best_pck = pck;
best_ld = cur_ld;
best_pd = cur_pd;
if (pck == req_pck)
goto found;
}
if (pck < req_pck)
break;
}
if (lck / pcd_min < req_pck)
break;
}
found:
cinfo->lck_div = best_ld;
cinfo->pck_div = best_pd;
cinfo->lck = fck / cinfo->lck_div;
cinfo->pck = cinfo->lck / cinfo->pck_div;
}
/* calculate clock rates using dividers in cinfo */
int dispc_calc_clock_rates(unsigned long dispc_fclk_rate,
struct dispc_clock_info *cinfo)
{
if (cinfo->lck_div > 255 || cinfo->lck_div == 0)
return -EINVAL;
if (cinfo->pck_div < 1 || cinfo->pck_div > 255)
return -EINVAL;
cinfo->lck = dispc_fclk_rate / cinfo->lck_div;
cinfo->pck = cinfo->lck / cinfo->pck_div;
return 0;
}
int dispc_mgr_set_clock_div(enum omap_channel channel,
struct dispc_clock_info *cinfo)
{
DSSDBG("lck = %lu (%u)\n", cinfo->lck, cinfo->lck_div);
DSSDBG("pck = %lu (%u)\n", cinfo->pck, cinfo->pck_div);
dispc_mgr_set_lcd_divisor(channel, cinfo->lck_div, cinfo->pck_div);
return 0;
}
int dispc_mgr_get_clock_div(enum omap_channel channel,
struct dispc_clock_info *cinfo)
{
unsigned long fck;
fck = dispc_fclk_rate();
cinfo->lck_div = REG_GET(DISPC_DIVISORo(channel), 23, 16);
cinfo->pck_div = REG_GET(DISPC_DIVISORo(channel), 7, 0);
cinfo->lck = fck / cinfo->lck_div;
cinfo->pck = cinfo->lck / cinfo->pck_div;
return 0;
}
/* dispc.irq_lock has to be locked by the caller */
static void _omap_dispc_set_irqs(void)
{
u32 mask;
u32 old_mask;
int i;
struct omap_dispc_isr_data *isr_data;
mask = dispc.irq_error_mask;
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = &dispc.registered_isr[i];
if (isr_data->isr == NULL)
continue;
mask |= isr_data->mask;
}
old_mask = dispc_read_reg(DISPC_IRQENABLE);
/* clear the irqstatus for newly enabled irqs */
dispc_write_reg(DISPC_IRQSTATUS, (mask ^ old_mask) & mask);
dispc_write_reg(DISPC_IRQENABLE, mask);
}
int omap_dispc_register_isr(omap_dispc_isr_t isr, void *arg, u32 mask)
{
int i;
int ret;
unsigned long flags;
struct omap_dispc_isr_data *isr_data;
if (isr == NULL)
return -EINVAL;
spin_lock_irqsave(&dispc.irq_lock, flags);
/* check for duplicate entry */
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = &dispc.registered_isr[i];
if (isr_data->isr == isr && isr_data->arg == arg &&
isr_data->mask == mask) {
ret = -EINVAL;
goto err;
}
}
isr_data = NULL;
ret = -EBUSY;
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = &dispc.registered_isr[i];
if (isr_data->isr != NULL)
continue;
isr_data->isr = isr;
isr_data->arg = arg;
isr_data->mask = mask;
ret = 0;
break;
}
if (ret)
goto err;
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc.irq_lock, flags);
return 0;
err:
spin_unlock_irqrestore(&dispc.irq_lock, flags);
return ret;
}
EXPORT_SYMBOL(omap_dispc_register_isr);
int omap_dispc_unregister_isr(omap_dispc_isr_t isr, void *arg, u32 mask)
{
int i;
unsigned long flags;
int ret = -EINVAL;
struct omap_dispc_isr_data *isr_data;
spin_lock_irqsave(&dispc.irq_lock, flags);
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = &dispc.registered_isr[i];
if (isr_data->isr != isr || isr_data->arg != arg ||
isr_data->mask != mask)
continue;
/* found the correct isr */
isr_data->isr = NULL;
isr_data->arg = NULL;
isr_data->mask = 0;
ret = 0;
break;
}
if (ret == 0)
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc.irq_lock, flags);
return ret;
}
EXPORT_SYMBOL(omap_dispc_unregister_isr);
#ifdef DEBUG
static void print_irq_status(u32 status)
{
if ((status & dispc.irq_error_mask) == 0)
return;
printk(KERN_DEBUG "DISPC IRQ: 0x%x: ", status);
#define PIS(x) \
if (status & DISPC_IRQ_##x) \
printk(#x " ");
PIS(GFX_FIFO_UNDERFLOW);
PIS(OCP_ERR);
PIS(VID1_FIFO_UNDERFLOW);
PIS(VID2_FIFO_UNDERFLOW);
if (dss_feat_get_num_ovls() > 3)
PIS(VID3_FIFO_UNDERFLOW);
PIS(SYNC_LOST);
PIS(SYNC_LOST_DIGIT);
if (dss_has_feature(FEAT_MGR_LCD2))
PIS(SYNC_LOST2);
#undef PIS
printk("\n");
}
#endif
/* Called from dss.c. Note that we don't touch clocks here,
* but we presume they are on because we got an IRQ. However,
* an irq handler may turn the clocks off, so we may not have
* clock later in the function. */
static irqreturn_t omap_dispc_irq_handler(int irq, void *arg)
{
int i;
u32 irqstatus, irqenable;
u32 handledirqs = 0;
u32 unhandled_errors;
struct omap_dispc_isr_data *isr_data;
struct omap_dispc_isr_data registered_isr[DISPC_MAX_NR_ISRS];
spin_lock(&dispc.irq_lock);
irqstatus = dispc_read_reg(DISPC_IRQSTATUS);
irqenable = dispc_read_reg(DISPC_IRQENABLE);
/* IRQ is not for us */
if (!(irqstatus & irqenable)) {
spin_unlock(&dispc.irq_lock);
return IRQ_NONE;
}
#ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS
spin_lock(&dispc.irq_stats_lock);
dispc.irq_stats.irq_count++;
dss_collect_irq_stats(irqstatus, dispc.irq_stats.irqs);
spin_unlock(&dispc.irq_stats_lock);
#endif
#ifdef DEBUG
if (dss_debug)
print_irq_status(irqstatus);
#endif
/* Ack the interrupt. Do it here before clocks are possibly turned
* off */
dispc_write_reg(DISPC_IRQSTATUS, irqstatus);
/* flush posted write */
dispc_read_reg(DISPC_IRQSTATUS);
/* make a copy and unlock, so that isrs can unregister
* themselves */
memcpy(registered_isr, dispc.registered_isr,
sizeof(registered_isr));
spin_unlock(&dispc.irq_lock);
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = ®istered_isr[i];
if (!isr_data->isr)
continue;
if (isr_data->mask & irqstatus) {
isr_data->isr(isr_data->arg, irqstatus);
handledirqs |= isr_data->mask;
}
}
spin_lock(&dispc.irq_lock);
unhandled_errors = irqstatus & ~handledirqs & dispc.irq_error_mask;
if (unhandled_errors) {
dispc.error_irqs |= unhandled_errors;
dispc.irq_error_mask &= ~unhandled_errors;
_omap_dispc_set_irqs();
schedule_work(&dispc.error_work);
}
spin_unlock(&dispc.irq_lock);
return IRQ_HANDLED;
}
static void dispc_error_worker(struct work_struct *work)
{
int i;
u32 errors;
unsigned long flags;
static const unsigned fifo_underflow_bits[] = {
DISPC_IRQ_GFX_FIFO_UNDERFLOW,
DISPC_IRQ_VID1_FIFO_UNDERFLOW,
DISPC_IRQ_VID2_FIFO_UNDERFLOW,
DISPC_IRQ_VID3_FIFO_UNDERFLOW,
};
static const unsigned sync_lost_bits[] = {
DISPC_IRQ_SYNC_LOST,
DISPC_IRQ_SYNC_LOST_DIGIT,
DISPC_IRQ_SYNC_LOST2,
};
spin_lock_irqsave(&dispc.irq_lock, flags);
errors = dispc.error_irqs;
dispc.error_irqs = 0;
spin_unlock_irqrestore(&dispc.irq_lock, flags);
dispc_runtime_get();
for (i = 0; i < omap_dss_get_num_overlays(); ++i) {
struct omap_overlay *ovl;
unsigned bit;
ovl = omap_dss_get_overlay(i);
bit = fifo_underflow_bits[i];
if (bit & errors) {
DSSERR("FIFO UNDERFLOW on %s, disabling the overlay\n",
ovl->name);
dispc_ovl_enable(ovl->id, false);
dispc_mgr_go(ovl->manager->id);
mdelay(50);
}
}
for (i = 0; i < omap_dss_get_num_overlay_managers(); ++i) {
struct omap_overlay_manager *mgr;
unsigned bit;
mgr = omap_dss_get_overlay_manager(i);
bit = sync_lost_bits[i];
if (bit & errors) {
struct omap_dss_device *dssdev = mgr->device;
bool enable;
DSSERR("SYNC_LOST on channel %s, restarting the output "
"with video overlays disabled\n",
mgr->name);
enable = dssdev->state == OMAP_DSS_DISPLAY_ACTIVE;
dssdev->driver->disable(dssdev);
for (i = 0; i < omap_dss_get_num_overlays(); ++i) {
struct omap_overlay *ovl;
ovl = omap_dss_get_overlay(i);
if (ovl->id != OMAP_DSS_GFX &&
ovl->manager == mgr)
dispc_ovl_enable(ovl->id, false);
}
dispc_mgr_go(mgr->id);
mdelay(50);
if (enable)
dssdev->driver->enable(dssdev);
}
}
if (errors & DISPC_IRQ_OCP_ERR) {
DSSERR("OCP_ERR\n");
for (i = 0; i < omap_dss_get_num_overlay_managers(); ++i) {
struct omap_overlay_manager *mgr;
mgr = omap_dss_get_overlay_manager(i);
if (mgr->device && mgr->device->driver)
mgr->device->driver->disable(mgr->device);
}
}
spin_lock_irqsave(&dispc.irq_lock, flags);
dispc.irq_error_mask |= errors;
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc.irq_lock, flags);
dispc_runtime_put();
}
int omap_dispc_wait_for_irq_timeout(u32 irqmask, unsigned long timeout)
{
void dispc_irq_wait_handler(void *data, u32 mask)
{
complete((struct completion *)data);
}
int r;
DECLARE_COMPLETION_ONSTACK(completion);
r = omap_dispc_register_isr(dispc_irq_wait_handler, &completion,
irqmask);
if (r)
return r;
timeout = wait_for_completion_timeout(&completion, timeout);
omap_dispc_unregister_isr(dispc_irq_wait_handler, &completion, irqmask);
if (timeout == 0)
return -ETIMEDOUT;
if (timeout == -ERESTARTSYS)
return -ERESTARTSYS;
return 0;
}
int omap_dispc_wait_for_irq_interruptible_timeout(u32 irqmask,
unsigned long timeout)
{
void dispc_irq_wait_handler(void *data, u32 mask)
{
complete((struct completion *)data);
}
int r;
DECLARE_COMPLETION_ONSTACK(completion);
r = omap_dispc_register_isr(dispc_irq_wait_handler, &completion,
irqmask);
if (r)
return r;
timeout = wait_for_completion_interruptible_timeout(&completion,
timeout);
omap_dispc_unregister_isr(dispc_irq_wait_handler, &completion, irqmask);
if (timeout == 0)
return -ETIMEDOUT;
if (timeout == -ERESTARTSYS)
return -ERESTARTSYS;
return 0;
}
#ifdef CONFIG_OMAP2_DSS_FAKE_VSYNC
void dispc_fake_vsync_irq(void)
{
u32 irqstatus = DISPC_IRQ_VSYNC;
int i;
WARN_ON(!in_interrupt());
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
struct omap_dispc_isr_data *isr_data;
isr_data = &dispc.registered_isr[i];
if (!isr_data->isr)
continue;
if (isr_data->mask & irqstatus)
isr_data->isr(isr_data->arg, irqstatus);
}
}
#endif
static void _omap_dispc_initialize_irq(void)
{
unsigned long flags;
spin_lock_irqsave(&dispc.irq_lock, flags);
memset(dispc.registered_isr, 0, sizeof(dispc.registered_isr));
dispc.irq_error_mask = DISPC_IRQ_MASK_ERROR;
if (dss_has_feature(FEAT_MGR_LCD2))
dispc.irq_error_mask |= DISPC_IRQ_SYNC_LOST2;
if (dss_feat_get_num_ovls() > 3)
dispc.irq_error_mask |= DISPC_IRQ_VID3_FIFO_UNDERFLOW;
/* there's SYNC_LOST_DIGIT waiting after enabling the DSS,
* so clear it */
dispc_write_reg(DISPC_IRQSTATUS, dispc_read_reg(DISPC_IRQSTATUS));
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc.irq_lock, flags);
}
void dispc_enable_sidle(void)
{
REG_FLD_MOD(DISPC_SYSCONFIG, 2, 4, 3); /* SIDLEMODE: smart idle */
}
void dispc_disable_sidle(void)
{
REG_FLD_MOD(DISPC_SYSCONFIG, 1, 4, 3); /* SIDLEMODE: no idle */
}
static void _omap_dispc_initial_config(void)
{
u32 l;
/* Exclusively enable DISPC_CORE_CLK and set divider to 1 */
if (dss_has_feature(FEAT_CORE_CLK_DIV)) {
l = dispc_read_reg(DISPC_DIVISOR);
/* Use DISPC_DIVISOR.LCD, instead of DISPC_DIVISOR1.LCD */
l = FLD_MOD(l, 1, 0, 0);
l = FLD_MOD(l, 1, 23, 16);
dispc_write_reg(DISPC_DIVISOR, l);
}
/* FUNCGATED */
if (dss_has_feature(FEAT_FUNCGATED))
REG_FLD_MOD(DISPC_CONFIG, 1, 9, 9);
_dispc_setup_color_conv_coef();
dispc_set_loadmode(OMAP_DSS_LOAD_FRAME_ONLY);
dispc_read_plane_fifo_sizes();
dispc_configure_burst_sizes();
dispc_ovl_enable_zorder_planes();
}
/* DISPC HW IP initialisation */
static int omap_dispchw_probe(struct platform_device *pdev)
{
u32 rev;
int r = 0;
struct resource *dispc_mem;
struct clk *clk;
dispc.pdev = pdev;
spin_lock_init(&dispc.irq_lock);
#ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS
spin_lock_init(&dispc.irq_stats_lock);
dispc.irq_stats.last_reset = jiffies;
#endif
INIT_WORK(&dispc.error_work, dispc_error_worker);
dispc_mem = platform_get_resource(dispc.pdev, IORESOURCE_MEM, 0);
if (!dispc_mem) {
DSSERR("can't get IORESOURCE_MEM DISPC\n");
return -EINVAL;
}
dispc.base = devm_ioremap(&pdev->dev, dispc_mem->start,
resource_size(dispc_mem));
if (!dispc.base) {
DSSERR("can't ioremap DISPC\n");
return -ENOMEM;
}
dispc.irq = platform_get_irq(dispc.pdev, 0);
if (dispc.irq < 0) {
DSSERR("platform_get_irq failed\n");
return -ENODEV;
}
r = devm_request_irq(&pdev->dev, dispc.irq, omap_dispc_irq_handler,
IRQF_SHARED, "OMAP DISPC", dispc.pdev);
if (r < 0) {
DSSERR("request_irq failed\n");
return r;
}
clk = clk_get(&pdev->dev, "fck");
if (IS_ERR(clk)) {
DSSERR("can't get fck\n");
r = PTR_ERR(clk);
return r;
}
dispc.dss_clk = clk;
pm_runtime_enable(&pdev->dev);
r = dispc_runtime_get();
if (r)
goto err_runtime_get;
_omap_dispc_initial_config();
_omap_dispc_initialize_irq();
rev = dispc_read_reg(DISPC_REVISION);
dev_dbg(&pdev->dev, "OMAP DISPC rev %d.%d\n",
FLD_GET(rev, 7, 4), FLD_GET(rev, 3, 0));
dispc_runtime_put();
return 0;
err_runtime_get:
pm_runtime_disable(&pdev->dev);
clk_put(dispc.dss_clk);
return r;
}
static int omap_dispchw_remove(struct platform_device *pdev)
{
pm_runtime_disable(&pdev->dev);
clk_put(dispc.dss_clk);
return 0;
}
static int dispc_runtime_suspend(struct device *dev)
{
dispc_save_context();
dss_runtime_put();
return 0;
}
static int dispc_runtime_resume(struct device *dev)
{
int r;
r = dss_runtime_get();
if (r < 0)
return r;
dispc_restore_context();
return 0;
}
static const struct dev_pm_ops dispc_pm_ops = {
.runtime_suspend = dispc_runtime_suspend,
.runtime_resume = dispc_runtime_resume,
};
static struct platform_driver omap_dispchw_driver = {
.probe = omap_dispchw_probe,
.remove = omap_dispchw_remove,
.driver = {
.name = "omapdss_dispc",
.owner = THIS_MODULE,
.pm = &dispc_pm_ops,
},
};
int dispc_init_platform_driver(void)
{
return platform_driver_register(&omap_dispchw_driver);
}
void dispc_uninit_platform_driver(void)
{
return platform_driver_unregister(&omap_dispchw_driver);
}
| gpl-2.0 |
AICP/kernel_yu_msm8916 | drivers/gpio/gpio-lpc32xx.c | 2246 | 15141 | /*
* GPIO driver for LPC32xx SoC
*
* Author: Kevin Wells <kevin.wells@nxp.com>
*
* Copyright (C) 2010 NXP Semiconductors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <mach/hardware.h>
#include <mach/platform.h>
#include <mach/gpio-lpc32xx.h>
#include <mach/irqs.h>
#define LPC32XX_GPIO_P3_INP_STATE _GPREG(0x000)
#define LPC32XX_GPIO_P3_OUTP_SET _GPREG(0x004)
#define LPC32XX_GPIO_P3_OUTP_CLR _GPREG(0x008)
#define LPC32XX_GPIO_P3_OUTP_STATE _GPREG(0x00C)
#define LPC32XX_GPIO_P2_DIR_SET _GPREG(0x010)
#define LPC32XX_GPIO_P2_DIR_CLR _GPREG(0x014)
#define LPC32XX_GPIO_P2_DIR_STATE _GPREG(0x018)
#define LPC32XX_GPIO_P2_INP_STATE _GPREG(0x01C)
#define LPC32XX_GPIO_P2_OUTP_SET _GPREG(0x020)
#define LPC32XX_GPIO_P2_OUTP_CLR _GPREG(0x024)
#define LPC32XX_GPIO_P2_MUX_SET _GPREG(0x028)
#define LPC32XX_GPIO_P2_MUX_CLR _GPREG(0x02C)
#define LPC32XX_GPIO_P2_MUX_STATE _GPREG(0x030)
#define LPC32XX_GPIO_P0_INP_STATE _GPREG(0x040)
#define LPC32XX_GPIO_P0_OUTP_SET _GPREG(0x044)
#define LPC32XX_GPIO_P0_OUTP_CLR _GPREG(0x048)
#define LPC32XX_GPIO_P0_OUTP_STATE _GPREG(0x04C)
#define LPC32XX_GPIO_P0_DIR_SET _GPREG(0x050)
#define LPC32XX_GPIO_P0_DIR_CLR _GPREG(0x054)
#define LPC32XX_GPIO_P0_DIR_STATE _GPREG(0x058)
#define LPC32XX_GPIO_P1_INP_STATE _GPREG(0x060)
#define LPC32XX_GPIO_P1_OUTP_SET _GPREG(0x064)
#define LPC32XX_GPIO_P1_OUTP_CLR _GPREG(0x068)
#define LPC32XX_GPIO_P1_OUTP_STATE _GPREG(0x06C)
#define LPC32XX_GPIO_P1_DIR_SET _GPREG(0x070)
#define LPC32XX_GPIO_P1_DIR_CLR _GPREG(0x074)
#define LPC32XX_GPIO_P1_DIR_STATE _GPREG(0x078)
#define GPIO012_PIN_TO_BIT(x) (1 << (x))
#define GPIO3_PIN_TO_BIT(x) (1 << ((x) + 25))
#define GPO3_PIN_TO_BIT(x) (1 << (x))
#define GPIO012_PIN_IN_SEL(x, y) (((x) >> (y)) & 1)
#define GPIO3_PIN_IN_SHIFT(x) ((x) == 5 ? 24 : 10 + (x))
#define GPIO3_PIN_IN_SEL(x, y) (((x) >> GPIO3_PIN_IN_SHIFT(y)) & 1)
#define GPIO3_PIN5_IN_SEL(x) (((x) >> 24) & 1)
#define GPI3_PIN_IN_SEL(x, y) (((x) >> (y)) & 1)
#define GPO3_PIN_IN_SEL(x, y) (((x) >> (y)) & 1)
struct gpio_regs {
void __iomem *inp_state;
void __iomem *outp_state;
void __iomem *outp_set;
void __iomem *outp_clr;
void __iomem *dir_set;
void __iomem *dir_clr;
};
/*
* GPIO names
*/
static const char *gpio_p0_names[LPC32XX_GPIO_P0_MAX] = {
"p0.0", "p0.1", "p0.2", "p0.3",
"p0.4", "p0.5", "p0.6", "p0.7"
};
static const char *gpio_p1_names[LPC32XX_GPIO_P1_MAX] = {
"p1.0", "p1.1", "p1.2", "p1.3",
"p1.4", "p1.5", "p1.6", "p1.7",
"p1.8", "p1.9", "p1.10", "p1.11",
"p1.12", "p1.13", "p1.14", "p1.15",
"p1.16", "p1.17", "p1.18", "p1.19",
"p1.20", "p1.21", "p1.22", "p1.23",
};
static const char *gpio_p2_names[LPC32XX_GPIO_P2_MAX] = {
"p2.0", "p2.1", "p2.2", "p2.3",
"p2.4", "p2.5", "p2.6", "p2.7",
"p2.8", "p2.9", "p2.10", "p2.11",
"p2.12"
};
static const char *gpio_p3_names[LPC32XX_GPIO_P3_MAX] = {
"gpio00", "gpio01", "gpio02", "gpio03",
"gpio04", "gpio05"
};
static const char *gpi_p3_names[LPC32XX_GPI_P3_MAX] = {
"gpi00", "gpi01", "gpi02", "gpi03",
"gpi04", "gpi05", "gpi06", "gpi07",
"gpi08", "gpi09", NULL, NULL,
NULL, NULL, NULL, "gpi15",
"gpi16", "gpi17", "gpi18", "gpi19",
"gpi20", "gpi21", "gpi22", "gpi23",
"gpi24", "gpi25", "gpi26", "gpi27",
"gpi28"
};
static const char *gpo_p3_names[LPC32XX_GPO_P3_MAX] = {
"gpo00", "gpo01", "gpo02", "gpo03",
"gpo04", "gpo05", "gpo06", "gpo07",
"gpo08", "gpo09", "gpo10", "gpo11",
"gpo12", "gpo13", "gpo14", "gpo15",
"gpo16", "gpo17", "gpo18", "gpo19",
"gpo20", "gpo21", "gpo22", "gpo23"
};
static struct gpio_regs gpio_grp_regs_p0 = {
.inp_state = LPC32XX_GPIO_P0_INP_STATE,
.outp_set = LPC32XX_GPIO_P0_OUTP_SET,
.outp_clr = LPC32XX_GPIO_P0_OUTP_CLR,
.dir_set = LPC32XX_GPIO_P0_DIR_SET,
.dir_clr = LPC32XX_GPIO_P0_DIR_CLR,
};
static struct gpio_regs gpio_grp_regs_p1 = {
.inp_state = LPC32XX_GPIO_P1_INP_STATE,
.outp_set = LPC32XX_GPIO_P1_OUTP_SET,
.outp_clr = LPC32XX_GPIO_P1_OUTP_CLR,
.dir_set = LPC32XX_GPIO_P1_DIR_SET,
.dir_clr = LPC32XX_GPIO_P1_DIR_CLR,
};
static struct gpio_regs gpio_grp_regs_p2 = {
.inp_state = LPC32XX_GPIO_P2_INP_STATE,
.outp_set = LPC32XX_GPIO_P2_OUTP_SET,
.outp_clr = LPC32XX_GPIO_P2_OUTP_CLR,
.dir_set = LPC32XX_GPIO_P2_DIR_SET,
.dir_clr = LPC32XX_GPIO_P2_DIR_CLR,
};
static struct gpio_regs gpio_grp_regs_p3 = {
.inp_state = LPC32XX_GPIO_P3_INP_STATE,
.outp_state = LPC32XX_GPIO_P3_OUTP_STATE,
.outp_set = LPC32XX_GPIO_P3_OUTP_SET,
.outp_clr = LPC32XX_GPIO_P3_OUTP_CLR,
.dir_set = LPC32XX_GPIO_P2_DIR_SET,
.dir_clr = LPC32XX_GPIO_P2_DIR_CLR,
};
struct lpc32xx_gpio_chip {
struct gpio_chip chip;
struct gpio_regs *gpio_grp;
};
static inline struct lpc32xx_gpio_chip *to_lpc32xx_gpio(
struct gpio_chip *gpc)
{
return container_of(gpc, struct lpc32xx_gpio_chip, chip);
}
static void __set_gpio_dir_p012(struct lpc32xx_gpio_chip *group,
unsigned pin, int input)
{
if (input)
__raw_writel(GPIO012_PIN_TO_BIT(pin),
group->gpio_grp->dir_clr);
else
__raw_writel(GPIO012_PIN_TO_BIT(pin),
group->gpio_grp->dir_set);
}
static void __set_gpio_dir_p3(struct lpc32xx_gpio_chip *group,
unsigned pin, int input)
{
u32 u = GPIO3_PIN_TO_BIT(pin);
if (input)
__raw_writel(u, group->gpio_grp->dir_clr);
else
__raw_writel(u, group->gpio_grp->dir_set);
}
static void __set_gpio_level_p012(struct lpc32xx_gpio_chip *group,
unsigned pin, int high)
{
if (high)
__raw_writel(GPIO012_PIN_TO_BIT(pin),
group->gpio_grp->outp_set);
else
__raw_writel(GPIO012_PIN_TO_BIT(pin),
group->gpio_grp->outp_clr);
}
static void __set_gpio_level_p3(struct lpc32xx_gpio_chip *group,
unsigned pin, int high)
{
u32 u = GPIO3_PIN_TO_BIT(pin);
if (high)
__raw_writel(u, group->gpio_grp->outp_set);
else
__raw_writel(u, group->gpio_grp->outp_clr);
}
static void __set_gpo_level_p3(struct lpc32xx_gpio_chip *group,
unsigned pin, int high)
{
if (high)
__raw_writel(GPO3_PIN_TO_BIT(pin), group->gpio_grp->outp_set);
else
__raw_writel(GPO3_PIN_TO_BIT(pin), group->gpio_grp->outp_clr);
}
static int __get_gpio_state_p012(struct lpc32xx_gpio_chip *group,
unsigned pin)
{
return GPIO012_PIN_IN_SEL(__raw_readl(group->gpio_grp->inp_state),
pin);
}
static int __get_gpio_state_p3(struct lpc32xx_gpio_chip *group,
unsigned pin)
{
int state = __raw_readl(group->gpio_grp->inp_state);
/*
* P3 GPIO pin input mapping is not contiguous, GPIOP3-0..4 is mapped
* to bits 10..14, while GPIOP3-5 is mapped to bit 24.
*/
return GPIO3_PIN_IN_SEL(state, pin);
}
static int __get_gpi_state_p3(struct lpc32xx_gpio_chip *group,
unsigned pin)
{
return GPI3_PIN_IN_SEL(__raw_readl(group->gpio_grp->inp_state), pin);
}
static int __get_gpo_state_p3(struct lpc32xx_gpio_chip *group,
unsigned pin)
{
return GPO3_PIN_IN_SEL(__raw_readl(group->gpio_grp->outp_state), pin);
}
/*
* GPIO primitives.
*/
static int lpc32xx_gpio_dir_input_p012(struct gpio_chip *chip,
unsigned pin)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
__set_gpio_dir_p012(group, pin, 1);
return 0;
}
static int lpc32xx_gpio_dir_input_p3(struct gpio_chip *chip,
unsigned pin)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
__set_gpio_dir_p3(group, pin, 1);
return 0;
}
static int lpc32xx_gpio_dir_in_always(struct gpio_chip *chip,
unsigned pin)
{
return 0;
}
static int lpc32xx_gpio_get_value_p012(struct gpio_chip *chip, unsigned pin)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
return __get_gpio_state_p012(group, pin);
}
static int lpc32xx_gpio_get_value_p3(struct gpio_chip *chip, unsigned pin)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
return __get_gpio_state_p3(group, pin);
}
static int lpc32xx_gpi_get_value(struct gpio_chip *chip, unsigned pin)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
return __get_gpi_state_p3(group, pin);
}
static int lpc32xx_gpio_dir_output_p012(struct gpio_chip *chip, unsigned pin,
int value)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
__set_gpio_level_p012(group, pin, value);
__set_gpio_dir_p012(group, pin, 0);
return 0;
}
static int lpc32xx_gpio_dir_output_p3(struct gpio_chip *chip, unsigned pin,
int value)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
__set_gpio_level_p3(group, pin, value);
__set_gpio_dir_p3(group, pin, 0);
return 0;
}
static int lpc32xx_gpio_dir_out_always(struct gpio_chip *chip, unsigned pin,
int value)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
__set_gpo_level_p3(group, pin, value);
return 0;
}
static void lpc32xx_gpio_set_value_p012(struct gpio_chip *chip, unsigned pin,
int value)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
__set_gpio_level_p012(group, pin, value);
}
static void lpc32xx_gpio_set_value_p3(struct gpio_chip *chip, unsigned pin,
int value)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
__set_gpio_level_p3(group, pin, value);
}
static void lpc32xx_gpo_set_value(struct gpio_chip *chip, unsigned pin,
int value)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
__set_gpo_level_p3(group, pin, value);
}
static int lpc32xx_gpo_get_value(struct gpio_chip *chip, unsigned pin)
{
struct lpc32xx_gpio_chip *group = to_lpc32xx_gpio(chip);
return __get_gpo_state_p3(group, pin);
}
static int lpc32xx_gpio_request(struct gpio_chip *chip, unsigned pin)
{
if (pin < chip->ngpio)
return 0;
return -EINVAL;
}
static int lpc32xx_gpio_to_irq_p01(struct gpio_chip *chip, unsigned offset)
{
return IRQ_LPC32XX_P0_P1_IRQ;
}
static const char lpc32xx_gpio_to_irq_gpio_p3_table[] = {
IRQ_LPC32XX_GPIO_00,
IRQ_LPC32XX_GPIO_01,
IRQ_LPC32XX_GPIO_02,
IRQ_LPC32XX_GPIO_03,
IRQ_LPC32XX_GPIO_04,
IRQ_LPC32XX_GPIO_05,
};
static int lpc32xx_gpio_to_irq_gpio_p3(struct gpio_chip *chip, unsigned offset)
{
if (offset < ARRAY_SIZE(lpc32xx_gpio_to_irq_gpio_p3_table))
return lpc32xx_gpio_to_irq_gpio_p3_table[offset];
return -ENXIO;
}
static const char lpc32xx_gpio_to_irq_gpi_p3_table[] = {
IRQ_LPC32XX_GPI_00,
IRQ_LPC32XX_GPI_01,
IRQ_LPC32XX_GPI_02,
IRQ_LPC32XX_GPI_03,
IRQ_LPC32XX_GPI_04,
IRQ_LPC32XX_GPI_05,
IRQ_LPC32XX_GPI_06,
IRQ_LPC32XX_GPI_07,
IRQ_LPC32XX_GPI_08,
IRQ_LPC32XX_GPI_09,
-ENXIO, /* 10 */
-ENXIO, /* 11 */
-ENXIO, /* 12 */
-ENXIO, /* 13 */
-ENXIO, /* 14 */
-ENXIO, /* 15 */
-ENXIO, /* 16 */
-ENXIO, /* 17 */
-ENXIO, /* 18 */
IRQ_LPC32XX_GPI_19,
-ENXIO, /* 20 */
-ENXIO, /* 21 */
-ENXIO, /* 22 */
-ENXIO, /* 23 */
-ENXIO, /* 24 */
-ENXIO, /* 25 */
-ENXIO, /* 26 */
-ENXIO, /* 27 */
IRQ_LPC32XX_GPI_28,
};
static int lpc32xx_gpio_to_irq_gpi_p3(struct gpio_chip *chip, unsigned offset)
{
if (offset < ARRAY_SIZE(lpc32xx_gpio_to_irq_gpi_p3_table))
return lpc32xx_gpio_to_irq_gpi_p3_table[offset];
return -ENXIO;
}
static struct lpc32xx_gpio_chip lpc32xx_gpiochip[] = {
{
.chip = {
.label = "gpio_p0",
.direction_input = lpc32xx_gpio_dir_input_p012,
.get = lpc32xx_gpio_get_value_p012,
.direction_output = lpc32xx_gpio_dir_output_p012,
.set = lpc32xx_gpio_set_value_p012,
.request = lpc32xx_gpio_request,
.to_irq = lpc32xx_gpio_to_irq_p01,
.base = LPC32XX_GPIO_P0_GRP,
.ngpio = LPC32XX_GPIO_P0_MAX,
.names = gpio_p0_names,
.can_sleep = 0,
},
.gpio_grp = &gpio_grp_regs_p0,
},
{
.chip = {
.label = "gpio_p1",
.direction_input = lpc32xx_gpio_dir_input_p012,
.get = lpc32xx_gpio_get_value_p012,
.direction_output = lpc32xx_gpio_dir_output_p012,
.set = lpc32xx_gpio_set_value_p012,
.request = lpc32xx_gpio_request,
.to_irq = lpc32xx_gpio_to_irq_p01,
.base = LPC32XX_GPIO_P1_GRP,
.ngpio = LPC32XX_GPIO_P1_MAX,
.names = gpio_p1_names,
.can_sleep = 0,
},
.gpio_grp = &gpio_grp_regs_p1,
},
{
.chip = {
.label = "gpio_p2",
.direction_input = lpc32xx_gpio_dir_input_p012,
.get = lpc32xx_gpio_get_value_p012,
.direction_output = lpc32xx_gpio_dir_output_p012,
.set = lpc32xx_gpio_set_value_p012,
.request = lpc32xx_gpio_request,
.base = LPC32XX_GPIO_P2_GRP,
.ngpio = LPC32XX_GPIO_P2_MAX,
.names = gpio_p2_names,
.can_sleep = 0,
},
.gpio_grp = &gpio_grp_regs_p2,
},
{
.chip = {
.label = "gpio_p3",
.direction_input = lpc32xx_gpio_dir_input_p3,
.get = lpc32xx_gpio_get_value_p3,
.direction_output = lpc32xx_gpio_dir_output_p3,
.set = lpc32xx_gpio_set_value_p3,
.request = lpc32xx_gpio_request,
.to_irq = lpc32xx_gpio_to_irq_gpio_p3,
.base = LPC32XX_GPIO_P3_GRP,
.ngpio = LPC32XX_GPIO_P3_MAX,
.names = gpio_p3_names,
.can_sleep = 0,
},
.gpio_grp = &gpio_grp_regs_p3,
},
{
.chip = {
.label = "gpi_p3",
.direction_input = lpc32xx_gpio_dir_in_always,
.get = lpc32xx_gpi_get_value,
.request = lpc32xx_gpio_request,
.to_irq = lpc32xx_gpio_to_irq_gpi_p3,
.base = LPC32XX_GPI_P3_GRP,
.ngpio = LPC32XX_GPI_P3_MAX,
.names = gpi_p3_names,
.can_sleep = 0,
},
.gpio_grp = &gpio_grp_regs_p3,
},
{
.chip = {
.label = "gpo_p3",
.direction_output = lpc32xx_gpio_dir_out_always,
.set = lpc32xx_gpo_set_value,
.get = lpc32xx_gpo_get_value,
.request = lpc32xx_gpio_request,
.base = LPC32XX_GPO_P3_GRP,
.ngpio = LPC32XX_GPO_P3_MAX,
.names = gpo_p3_names,
.can_sleep = 0,
},
.gpio_grp = &gpio_grp_regs_p3,
},
};
static int lpc32xx_of_xlate(struct gpio_chip *gc,
const struct of_phandle_args *gpiospec, u32 *flags)
{
/* Is this the correct bank? */
u32 bank = gpiospec->args[0];
if ((bank >= ARRAY_SIZE(lpc32xx_gpiochip) ||
(gc != &lpc32xx_gpiochip[bank].chip)))
return -EINVAL;
if (flags)
*flags = gpiospec->args[2];
return gpiospec->args[1];
}
static int lpc32xx_gpio_probe(struct platform_device *pdev)
{
int i;
for (i = 0; i < ARRAY_SIZE(lpc32xx_gpiochip); i++) {
if (pdev->dev.of_node) {
lpc32xx_gpiochip[i].chip.of_xlate = lpc32xx_of_xlate;
lpc32xx_gpiochip[i].chip.of_gpio_n_cells = 3;
lpc32xx_gpiochip[i].chip.of_node = pdev->dev.of_node;
}
gpiochip_add(&lpc32xx_gpiochip[i].chip);
}
return 0;
}
#ifdef CONFIG_OF
static struct of_device_id lpc32xx_gpio_of_match[] = {
{ .compatible = "nxp,lpc3220-gpio", },
{ },
};
#endif
static struct platform_driver lpc32xx_gpio_driver = {
.driver = {
.name = "lpc32xx-gpio",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(lpc32xx_gpio_of_match),
},
.probe = lpc32xx_gpio_probe,
};
module_platform_driver(lpc32xx_gpio_driver);
| gpl-2.0 |
akhilnarang/ThugLife_sprout | tools/power/cpupower/utils/helpers/sysfs.c | 2246 | 7854 | /*
* (C) 2004-2009 Dominik Brodowski <linux@dominikbrodowski.de>
* (C) 2011 Thomas Renninger <trenn@novell.com> Novell Inc.
*
* Licensed under the terms of the GNU GPL License version 2.
*/
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "helpers/sysfs.h"
unsigned int sysfs_read_file(const char *path, char *buf, size_t buflen)
{
int fd;
ssize_t numread;
fd = open(path, O_RDONLY);
if (fd == -1)
return 0;
numread = read(fd, buf, buflen - 1);
if (numread < 1) {
close(fd);
return 0;
}
buf[numread] = '\0';
close(fd);
return (unsigned int) numread;
}
/*
* Detect whether a CPU is online
*
* Returns:
* 1 -> if CPU is online
* 0 -> if CPU is offline
* negative errno values in error case
*/
int sysfs_is_cpu_online(unsigned int cpu)
{
char path[SYSFS_PATH_MAX];
int fd;
ssize_t numread;
unsigned long long value;
char linebuf[MAX_LINE_LEN];
char *endp;
struct stat statbuf;
snprintf(path, sizeof(path), PATH_TO_CPU "cpu%u", cpu);
if (stat(path, &statbuf) != 0)
return 0;
/*
* kernel without CONFIG_HOTPLUG_CPU
* -> cpuX directory exists, but not cpuX/online file
*/
snprintf(path, sizeof(path), PATH_TO_CPU "cpu%u/online", cpu);
if (stat(path, &statbuf) != 0)
return 1;
fd = open(path, O_RDONLY);
if (fd == -1)
return -errno;
numread = read(fd, linebuf, MAX_LINE_LEN - 1);
if (numread < 1) {
close(fd);
return -EIO;
}
linebuf[numread] = '\0';
close(fd);
value = strtoull(linebuf, &endp, 0);
if (value > 1 || value < 0)
return -EINVAL;
return value;
}
/* CPUidle idlestate specific /sys/devices/system/cpu/cpuX/cpuidle/ access */
/*
* helper function to read file from /sys into given buffer
* fname is a relative path under "cpuX/cpuidle/stateX/" dir
* cstates starting with 0, C0 is not counted as cstate.
* This means if you want C1 info, pass 0 as idlestate param
*/
unsigned int sysfs_idlestate_read_file(unsigned int cpu, unsigned int idlestate,
const char *fname, char *buf, size_t buflen)
{
char path[SYSFS_PATH_MAX];
int fd;
ssize_t numread;
snprintf(path, sizeof(path), PATH_TO_CPU "cpu%u/cpuidle/state%u/%s",
cpu, idlestate, fname);
fd = open(path, O_RDONLY);
if (fd == -1)
return 0;
numread = read(fd, buf, buflen - 1);
if (numread < 1) {
close(fd);
return 0;
}
buf[numread] = '\0';
close(fd);
return (unsigned int) numread;
}
/* read access to files which contain one numeric value */
enum idlestate_value {
IDLESTATE_USAGE,
IDLESTATE_POWER,
IDLESTATE_LATENCY,
IDLESTATE_TIME,
MAX_IDLESTATE_VALUE_FILES
};
static const char *idlestate_value_files[MAX_IDLESTATE_VALUE_FILES] = {
[IDLESTATE_USAGE] = "usage",
[IDLESTATE_POWER] = "power",
[IDLESTATE_LATENCY] = "latency",
[IDLESTATE_TIME] = "time",
};
static unsigned long long sysfs_idlestate_get_one_value(unsigned int cpu,
unsigned int idlestate,
enum idlestate_value which)
{
unsigned long long value;
unsigned int len;
char linebuf[MAX_LINE_LEN];
char *endp;
if (which >= MAX_IDLESTATE_VALUE_FILES)
return 0;
len = sysfs_idlestate_read_file(cpu, idlestate,
idlestate_value_files[which],
linebuf, sizeof(linebuf));
if (len == 0)
return 0;
value = strtoull(linebuf, &endp, 0);
if (endp == linebuf || errno == ERANGE)
return 0;
return value;
}
/* read access to files which contain one string */
enum idlestate_string {
IDLESTATE_DESC,
IDLESTATE_NAME,
MAX_IDLESTATE_STRING_FILES
};
static const char *idlestate_string_files[MAX_IDLESTATE_STRING_FILES] = {
[IDLESTATE_DESC] = "desc",
[IDLESTATE_NAME] = "name",
};
static char *sysfs_idlestate_get_one_string(unsigned int cpu,
unsigned int idlestate,
enum idlestate_string which)
{
char linebuf[MAX_LINE_LEN];
char *result;
unsigned int len;
if (which >= MAX_IDLESTATE_STRING_FILES)
return NULL;
len = sysfs_idlestate_read_file(cpu, idlestate,
idlestate_string_files[which],
linebuf, sizeof(linebuf));
if (len == 0)
return NULL;
result = strdup(linebuf);
if (result == NULL)
return NULL;
if (result[strlen(result) - 1] == '\n')
result[strlen(result) - 1] = '\0';
return result;
}
unsigned long sysfs_get_idlestate_latency(unsigned int cpu,
unsigned int idlestate)
{
return sysfs_idlestate_get_one_value(cpu, idlestate, IDLESTATE_LATENCY);
}
unsigned long sysfs_get_idlestate_usage(unsigned int cpu,
unsigned int idlestate)
{
return sysfs_idlestate_get_one_value(cpu, idlestate, IDLESTATE_USAGE);
}
unsigned long long sysfs_get_idlestate_time(unsigned int cpu,
unsigned int idlestate)
{
return sysfs_idlestate_get_one_value(cpu, idlestate, IDLESTATE_TIME);
}
char *sysfs_get_idlestate_name(unsigned int cpu, unsigned int idlestate)
{
return sysfs_idlestate_get_one_string(cpu, idlestate, IDLESTATE_NAME);
}
char *sysfs_get_idlestate_desc(unsigned int cpu, unsigned int idlestate)
{
return sysfs_idlestate_get_one_string(cpu, idlestate, IDLESTATE_DESC);
}
/*
* Returns number of supported C-states of CPU core cpu
* Negativ in error case
* Zero if cpuidle does not export any C-states
*/
int sysfs_get_idlestate_count(unsigned int cpu)
{
char file[SYSFS_PATH_MAX];
struct stat statbuf;
int idlestates = 1;
snprintf(file, SYSFS_PATH_MAX, PATH_TO_CPU "cpuidle");
if (stat(file, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
return -ENODEV;
snprintf(file, SYSFS_PATH_MAX, PATH_TO_CPU "cpu%u/cpuidle/state0", cpu);
if (stat(file, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
return 0;
while (stat(file, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) {
snprintf(file, SYSFS_PATH_MAX, PATH_TO_CPU
"cpu%u/cpuidle/state%d", cpu, idlestates);
idlestates++;
}
idlestates--;
return idlestates;
}
/* CPUidle general /sys/devices/system/cpu/cpuidle/ sysfs access ********/
/*
* helper function to read file from /sys into given buffer
* fname is a relative path under "cpu/cpuidle/" dir
*/
static unsigned int sysfs_cpuidle_read_file(const char *fname, char *buf,
size_t buflen)
{
char path[SYSFS_PATH_MAX];
snprintf(path, sizeof(path), PATH_TO_CPU "cpuidle/%s", fname);
return sysfs_read_file(path, buf, buflen);
}
/* read access to files which contain one string */
enum cpuidle_string {
CPUIDLE_GOVERNOR,
CPUIDLE_GOVERNOR_RO,
CPUIDLE_DRIVER,
MAX_CPUIDLE_STRING_FILES
};
static const char *cpuidle_string_files[MAX_CPUIDLE_STRING_FILES] = {
[CPUIDLE_GOVERNOR] = "current_governor",
[CPUIDLE_GOVERNOR_RO] = "current_governor_ro",
[CPUIDLE_DRIVER] = "current_driver",
};
static char *sysfs_cpuidle_get_one_string(enum cpuidle_string which)
{
char linebuf[MAX_LINE_LEN];
char *result;
unsigned int len;
if (which >= MAX_CPUIDLE_STRING_FILES)
return NULL;
len = sysfs_cpuidle_read_file(cpuidle_string_files[which],
linebuf, sizeof(linebuf));
if (len == 0)
return NULL;
result = strdup(linebuf);
if (result == NULL)
return NULL;
if (result[strlen(result) - 1] == '\n')
result[strlen(result) - 1] = '\0';
return result;
}
char *sysfs_get_cpuidle_governor(void)
{
char *tmp = sysfs_cpuidle_get_one_string(CPUIDLE_GOVERNOR_RO);
if (!tmp)
return sysfs_cpuidle_get_one_string(CPUIDLE_GOVERNOR);
else
return tmp;
}
char *sysfs_get_cpuidle_driver(void)
{
return sysfs_cpuidle_get_one_string(CPUIDLE_DRIVER);
}
/* CPUidle idlestate specific /sys/devices/system/cpu/cpuX/cpuidle/ access */
/*
* Get sched_mc or sched_smt settings
* Pass "mc" or "smt" as argument
*
* Returns negative value on failure
*/
int sysfs_get_sched(const char *smt_mc)
{
return -ENODEV;
}
/*
* Get sched_mc or sched_smt settings
* Pass "mc" or "smt" as argument
*
* Returns negative value on failure
*/
int sysfs_set_sched(const char *smt_mc, int val)
{
return -ENODEV;
}
| gpl-2.0 |
nicholaschw/jared-rA | drivers/media/dvb/dvb-usb/friio-fe.c | 3270 | 11155 | /* DVB USB compliant Linux driver for the Friio USB2.0 ISDB-T receiver.
*
* Copyright (C) 2009 Akihiro Tsukada <tskd2@yahoo.co.jp>
*
* This module is based off the the gl861 and vp702x modules.
*
* 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.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include <linux/init.h>
#include <linux/string.h>
#include <linux/slab.h>
#include "friio.h"
struct jdvbt90502_state {
struct i2c_adapter *i2c;
struct dvb_frontend frontend;
struct jdvbt90502_config config;
};
/* NOTE: TC90502 has 16bit register-address? */
/* register 0x0100 is used for reading PLL status, so reg is u16 here */
static int jdvbt90502_reg_read(struct jdvbt90502_state *state,
const u16 reg, u8 *buf, const size_t count)
{
int ret;
u8 wbuf[3];
struct i2c_msg msg[2];
wbuf[0] = reg & 0xFF;
wbuf[1] = 0;
wbuf[2] = reg >> 8;
msg[0].addr = state->config.demod_address;
msg[0].flags = 0;
msg[0].buf = wbuf;
msg[0].len = sizeof(wbuf);
msg[1].addr = msg[0].addr;
msg[1].flags = I2C_M_RD;
msg[1].buf = buf;
msg[1].len = count;
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
deb_fe(" reg read failed.\n");
return -EREMOTEIO;
}
return 0;
}
/* currently 16bit register-address is not used, so reg is u8 here */
static int jdvbt90502_single_reg_write(struct jdvbt90502_state *state,
const u8 reg, const u8 val)
{
struct i2c_msg msg;
u8 wbuf[2];
wbuf[0] = reg;
wbuf[1] = val;
msg.addr = state->config.demod_address;
msg.flags = 0;
msg.buf = wbuf;
msg.len = sizeof(wbuf);
if (i2c_transfer(state->i2c, &msg, 1) != 1) {
deb_fe(" reg write failed.");
return -EREMOTEIO;
}
return 0;
}
static int _jdvbt90502_write(struct dvb_frontend *fe, const u8 buf[], int len)
{
struct jdvbt90502_state *state = fe->demodulator_priv;
int err, i;
for (i = 0; i < len - 1; i++) {
err = jdvbt90502_single_reg_write(state,
buf[0] + i, buf[i + 1]);
if (err)
return err;
}
return 0;
}
/* read pll status byte via the demodulator's I2C register */
/* note: Win box reads it by 8B block at the I2C addr 0x30 from reg:0x80 */
static int jdvbt90502_pll_read(struct jdvbt90502_state *state, u8 *result)
{
int ret;
/* +1 for reading */
u8 pll_addr_byte = (state->config.pll_address << 1) + 1;
*result = 0;
ret = jdvbt90502_single_reg_write(state, JDVBT90502_2ND_I2C_REG,
pll_addr_byte);
if (ret)
goto error;
ret = jdvbt90502_reg_read(state, 0x0100, result, 1);
if (ret)
goto error;
deb_fe("PLL read val:%02x\n", *result);
return 0;
error:
deb_fe("%s:ret == %d\n", __func__, ret);
return -EREMOTEIO;
}
/* set pll frequency via the demodulator's I2C register */
static int jdvbt90502_pll_set_freq(struct jdvbt90502_state *state, u32 freq)
{
int ret;
int retry;
u8 res1;
u8 res2[9];
u8 pll_freq_cmd[PLL_CMD_LEN];
u8 pll_agc_cmd[PLL_CMD_LEN];
struct i2c_msg msg[2];
u32 f;
deb_fe("%s: freq=%d, step=%d\n", __func__, freq,
state->frontend.ops.info.frequency_stepsize);
/* freq -> oscilator frequency conversion. */
/* freq: 473,000,000 + n*6,000,000 [+ 142857 (center freq. shift)] */
f = freq / state->frontend.ops.info.frequency_stepsize;
/* add 399[1/7 MHZ] = 57MHz for the IF */
f += 399;
/* add center frequency shift if necessary */
if (f % 7 == 0)
f++;
pll_freq_cmd[DEMOD_REDIRECT_REG] = JDVBT90502_2ND_I2C_REG; /* 0xFE */
pll_freq_cmd[ADDRESS_BYTE] = state->config.pll_address << 1;
pll_freq_cmd[DIVIDER_BYTE1] = (f >> 8) & 0x7F;
pll_freq_cmd[DIVIDER_BYTE2] = f & 0xFF;
pll_freq_cmd[CONTROL_BYTE] = 0xB2; /* ref.divider:28, 4MHz/28=1/7MHz */
pll_freq_cmd[BANDSWITCH_BYTE] = 0x08; /* UHF band */
msg[0].addr = state->config.demod_address;
msg[0].flags = 0;
msg[0].buf = pll_freq_cmd;
msg[0].len = sizeof(pll_freq_cmd);
ret = i2c_transfer(state->i2c, &msg[0], 1);
if (ret != 1)
goto error;
udelay(50);
pll_agc_cmd[DEMOD_REDIRECT_REG] = pll_freq_cmd[DEMOD_REDIRECT_REG];
pll_agc_cmd[ADDRESS_BYTE] = pll_freq_cmd[ADDRESS_BYTE];
pll_agc_cmd[DIVIDER_BYTE1] = pll_freq_cmd[DIVIDER_BYTE1];
pll_agc_cmd[DIVIDER_BYTE2] = pll_freq_cmd[DIVIDER_BYTE2];
pll_agc_cmd[CONTROL_BYTE] = 0x9A; /* AGC_CTRL instead of BANDSWITCH */
pll_agc_cmd[AGC_CTRL_BYTE] = 0x50;
/* AGC Time Constant 2s, AGC take-over point:103dBuV(lowest) */
msg[1].addr = msg[0].addr;
msg[1].flags = 0;
msg[1].buf = pll_agc_cmd;
msg[1].len = sizeof(pll_agc_cmd);
ret = i2c_transfer(state->i2c, &msg[1], 1);
if (ret != 1)
goto error;
/* I don't know what these cmds are for, */
/* but the USB log on a windows box contains them */
ret = jdvbt90502_single_reg_write(state, 0x01, 0x40);
ret |= jdvbt90502_single_reg_write(state, 0x01, 0x00);
if (ret)
goto error;
udelay(100);
/* wait for the demod to be ready? */
#define RETRY_COUNT 5
for (retry = 0; retry < RETRY_COUNT; retry++) {
ret = jdvbt90502_reg_read(state, 0x0096, &res1, 1);
if (ret)
goto error;
/* if (res1 != 0x00) goto error; */
ret = jdvbt90502_reg_read(state, 0x00B0, res2, sizeof(res2));
if (ret)
goto error;
if (res2[0] >= 0xA7)
break;
msleep(100);
}
if (retry >= RETRY_COUNT) {
deb_fe("%s: FE does not get ready after freq setting.\n",
__func__);
return -EREMOTEIO;
}
return 0;
error:
deb_fe("%s:ret == %d\n", __func__, ret);
return -EREMOTEIO;
}
static int jdvbt90502_read_status(struct dvb_frontend *fe, fe_status_t *state)
{
u8 result;
int ret;
*state = FE_HAS_SIGNAL;
ret = jdvbt90502_pll_read(fe->demodulator_priv, &result);
if (ret) {
deb_fe("%s:ret == %d\n", __func__, ret);
return -EREMOTEIO;
}
*state = FE_HAS_SIGNAL
| FE_HAS_CARRIER
| FE_HAS_VITERBI
| FE_HAS_SYNC;
if (result & PLL_STATUS_LOCKED)
*state |= FE_HAS_LOCK;
return 0;
}
static int jdvbt90502_read_signal_strength(struct dvb_frontend *fe,
u16 *strength)
{
int ret;
u8 rbuf[37];
*strength = 0;
/* status register (incl. signal strength) : 0x89 */
/* TODO: read just the necessary registers [0x8B..0x8D]? */
ret = jdvbt90502_reg_read(fe->demodulator_priv, 0x0089,
rbuf, sizeof(rbuf));
if (ret) {
deb_fe("%s:ret == %d\n", __func__, ret);
return -EREMOTEIO;
}
/* signal_strength: rbuf[2-4] (24bit BE), use lower 16bit for now. */
*strength = (rbuf[3] << 8) + rbuf[4];
if (rbuf[2])
*strength = 0xffff;
return 0;
}
/* filter out un-supported properties to notify users */
static int jdvbt90502_set_property(struct dvb_frontend *fe,
struct dtv_property *tvp)
{
int r = 0;
switch (tvp->cmd) {
case DTV_DELIVERY_SYSTEM:
if (tvp->u.data != SYS_ISDBT)
r = -EINVAL;
break;
case DTV_CLEAR:
case DTV_TUNE:
case DTV_FREQUENCY:
break;
default:
r = -EINVAL;
}
return r;
}
static int jdvbt90502_get_frontend(struct dvb_frontend *fe,
struct dvb_frontend_parameters *p)
{
p->inversion = INVERSION_AUTO;
p->u.ofdm.bandwidth = BANDWIDTH_6_MHZ;
p->u.ofdm.code_rate_HP = FEC_AUTO;
p->u.ofdm.code_rate_LP = FEC_AUTO;
p->u.ofdm.constellation = QAM_64;
p->u.ofdm.transmission_mode = TRANSMISSION_MODE_AUTO;
p->u.ofdm.guard_interval = GUARD_INTERVAL_AUTO;
p->u.ofdm.hierarchy_information = HIERARCHY_AUTO;
return 0;
}
static int jdvbt90502_set_frontend(struct dvb_frontend *fe,
struct dvb_frontend_parameters *p)
{
/**
* NOTE: ignore all the parameters except frequency.
* others should be fixed to the proper value for ISDB-T,
* but don't check here.
*/
struct jdvbt90502_state *state = fe->demodulator_priv;
int ret;
deb_fe("%s: Freq:%d\n", __func__, p->frequency);
/* for recovery from DTV_CLEAN */
fe->dtv_property_cache.delivery_system = SYS_ISDBT;
ret = jdvbt90502_pll_set_freq(state, p->frequency);
if (ret) {
deb_fe("%s:ret == %d\n", __func__, ret);
return -EREMOTEIO;
}
return 0;
}
/**
* (reg, val) commad list to initialize this module.
* captured on a Windows box.
*/
static u8 init_code[][2] = {
{0x01, 0x40},
{0x04, 0x38},
{0x05, 0x40},
{0x07, 0x40},
{0x0F, 0x4F},
{0x11, 0x21},
{0x12, 0x0B},
{0x13, 0x2F},
{0x14, 0x31},
{0x16, 0x02},
{0x21, 0xC4},
{0x22, 0x20},
{0x2C, 0x79},
{0x2D, 0x34},
{0x2F, 0x00},
{0x30, 0x28},
{0x31, 0x31},
{0x32, 0xDF},
{0x38, 0x01},
{0x39, 0x78},
{0x3B, 0x33},
{0x3C, 0x33},
{0x48, 0x90},
{0x51, 0x68},
{0x5E, 0x38},
{0x71, 0x00},
{0x72, 0x08},
{0x77, 0x00},
{0xC0, 0x21},
{0xC1, 0x10},
{0xE4, 0x1A},
{0xEA, 0x1F},
{0x77, 0x00},
{0x71, 0x00},
{0x71, 0x00},
{0x76, 0x0C},
};
static const int init_code_len = sizeof(init_code) / sizeof(u8[2]);
static int jdvbt90502_init(struct dvb_frontend *fe)
{
int i = -1;
int ret;
struct i2c_msg msg;
struct jdvbt90502_state *state = fe->demodulator_priv;
deb_fe("%s called.\n", __func__);
msg.addr = state->config.demod_address;
msg.flags = 0;
msg.len = 2;
for (i = 0; i < init_code_len; i++) {
msg.buf = init_code[i];
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1)
goto error;
}
fe->dtv_property_cache.delivery_system = SYS_ISDBT;
msleep(100);
return 0;
error:
deb_fe("%s: init_code[%d] failed. ret==%d\n", __func__, i, ret);
return -EREMOTEIO;
}
static void jdvbt90502_release(struct dvb_frontend *fe)
{
struct jdvbt90502_state *state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops jdvbt90502_ops;
struct dvb_frontend *jdvbt90502_attach(struct dvb_usb_device *d)
{
struct jdvbt90502_state *state = NULL;
deb_info("%s called.\n", __func__);
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct jdvbt90502_state), GFP_KERNEL);
if (state == NULL)
goto error;
/* setup the state */
state->i2c = &d->i2c_adap;
memcpy(&state->config, &friio_fe_config, sizeof(friio_fe_config));
/* create dvb_frontend */
memcpy(&state->frontend.ops, &jdvbt90502_ops,
sizeof(jdvbt90502_ops));
state->frontend.demodulator_priv = state;
if (jdvbt90502_init(&state->frontend) < 0)
goto error;
return &state->frontend;
error:
kfree(state);
return NULL;
}
static struct dvb_frontend_ops jdvbt90502_ops = {
.info = {
.name = "Comtech JDVBT90502 ISDB-T",
.type = FE_OFDM,
.frequency_min = 473000000, /* UHF 13ch, center */
.frequency_max = 767142857, /* UHF 62ch, center */
.frequency_stepsize = JDVBT90502_PLL_CLK /
JDVBT90502_PLL_DIVIDER,
.frequency_tolerance = 0,
/* NOTE: this driver ignores all parameters but frequency. */
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_4_5 | FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 |
FE_CAN_FEC_7_8 | FE_CAN_FEC_8_9 | FE_CAN_FEC_AUTO |
FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_HIERARCHY_AUTO,
},
.release = jdvbt90502_release,
.init = jdvbt90502_init,
.write = _jdvbt90502_write,
.set_property = jdvbt90502_set_property,
.set_frontend = jdvbt90502_set_frontend,
.get_frontend = jdvbt90502_get_frontend,
.read_status = jdvbt90502_read_status,
.read_signal_strength = jdvbt90502_read_signal_strength,
};
| gpl-2.0 |
sktjdgns1189/android_kernel_samsung_c1skt | arch/powerpc/platforms/cell/spu_priv1_mmio.c | 3782 | 4771 | /*
* spu hypervisor abstraction for direct hardware access.
*
* (C) Copyright IBM Deutschland Entwicklung GmbH 2005
* Copyright 2006 Sony Corp.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/ptrace.h>
#include <linux/wait.h>
#include <linux/mm.h>
#include <linux/io.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/sched.h>
#include <asm/spu.h>
#include <asm/spu_priv1.h>
#include <asm/firmware.h>
#include <asm/prom.h>
#include "interrupt.h"
#include "spu_priv1_mmio.h"
static void int_mask_and(struct spu *spu, int class, u64 mask)
{
u64 old_mask;
old_mask = in_be64(&spu->priv1->int_mask_RW[class]);
out_be64(&spu->priv1->int_mask_RW[class], old_mask & mask);
}
static void int_mask_or(struct spu *spu, int class, u64 mask)
{
u64 old_mask;
old_mask = in_be64(&spu->priv1->int_mask_RW[class]);
out_be64(&spu->priv1->int_mask_RW[class], old_mask | mask);
}
static void int_mask_set(struct spu *spu, int class, u64 mask)
{
out_be64(&spu->priv1->int_mask_RW[class], mask);
}
static u64 int_mask_get(struct spu *spu, int class)
{
return in_be64(&spu->priv1->int_mask_RW[class]);
}
static void int_stat_clear(struct spu *spu, int class, u64 stat)
{
out_be64(&spu->priv1->int_stat_RW[class], stat);
}
static u64 int_stat_get(struct spu *spu, int class)
{
return in_be64(&spu->priv1->int_stat_RW[class]);
}
static void cpu_affinity_set(struct spu *spu, int cpu)
{
u64 target;
u64 route;
if (nr_cpus_node(spu->node)) {
const struct cpumask *spumask = cpumask_of_node(spu->node),
*cpumask = cpumask_of_node(cpu_to_node(cpu));
if (!cpumask_intersects(spumask, cpumask))
return;
}
target = iic_get_target_id(cpu);
route = target << 48 | target << 32 | target << 16;
out_be64(&spu->priv1->int_route_RW, route);
}
static u64 mfc_dar_get(struct spu *spu)
{
return in_be64(&spu->priv1->mfc_dar_RW);
}
static u64 mfc_dsisr_get(struct spu *spu)
{
return in_be64(&spu->priv1->mfc_dsisr_RW);
}
static void mfc_dsisr_set(struct spu *spu, u64 dsisr)
{
out_be64(&spu->priv1->mfc_dsisr_RW, dsisr);
}
static void mfc_sdr_setup(struct spu *spu)
{
out_be64(&spu->priv1->mfc_sdr_RW, mfspr(SPRN_SDR1));
}
static void mfc_sr1_set(struct spu *spu, u64 sr1)
{
out_be64(&spu->priv1->mfc_sr1_RW, sr1);
}
static u64 mfc_sr1_get(struct spu *spu)
{
return in_be64(&spu->priv1->mfc_sr1_RW);
}
static void mfc_tclass_id_set(struct spu *spu, u64 tclass_id)
{
out_be64(&spu->priv1->mfc_tclass_id_RW, tclass_id);
}
static u64 mfc_tclass_id_get(struct spu *spu)
{
return in_be64(&spu->priv1->mfc_tclass_id_RW);
}
static void tlb_invalidate(struct spu *spu)
{
out_be64(&spu->priv1->tlb_invalidate_entry_W, 0ul);
}
static void resource_allocation_groupID_set(struct spu *spu, u64 id)
{
out_be64(&spu->priv1->resource_allocation_groupID_RW, id);
}
static u64 resource_allocation_groupID_get(struct spu *spu)
{
return in_be64(&spu->priv1->resource_allocation_groupID_RW);
}
static void resource_allocation_enable_set(struct spu *spu, u64 enable)
{
out_be64(&spu->priv1->resource_allocation_enable_RW, enable);
}
static u64 resource_allocation_enable_get(struct spu *spu)
{
return in_be64(&spu->priv1->resource_allocation_enable_RW);
}
const struct spu_priv1_ops spu_priv1_mmio_ops =
{
.int_mask_and = int_mask_and,
.int_mask_or = int_mask_or,
.int_mask_set = int_mask_set,
.int_mask_get = int_mask_get,
.int_stat_clear = int_stat_clear,
.int_stat_get = int_stat_get,
.cpu_affinity_set = cpu_affinity_set,
.mfc_dar_get = mfc_dar_get,
.mfc_dsisr_get = mfc_dsisr_get,
.mfc_dsisr_set = mfc_dsisr_set,
.mfc_sdr_setup = mfc_sdr_setup,
.mfc_sr1_set = mfc_sr1_set,
.mfc_sr1_get = mfc_sr1_get,
.mfc_tclass_id_set = mfc_tclass_id_set,
.mfc_tclass_id_get = mfc_tclass_id_get,
.tlb_invalidate = tlb_invalidate,
.resource_allocation_groupID_set = resource_allocation_groupID_set,
.resource_allocation_groupID_get = resource_allocation_groupID_get,
.resource_allocation_enable_set = resource_allocation_enable_set,
.resource_allocation_enable_get = resource_allocation_enable_get,
};
| gpl-2.0 |
Rockr172/villeu-4.2 | drivers/platform/x86/hdaps.c | 4806 | 17127 | /*
* hdaps.c - driver for IBM's Hard Drive Active Protection System
*
* Copyright (C) 2005 Robert Love <rml@novell.com>
* Copyright (C) 2005 Jesper Juhl <jesper.juhl@gmail.com>
*
* The HardDisk Active Protection System (hdaps) is present in IBM ThinkPads
* starting with the R40, T41, and X40. It provides a basic two-axis
* accelerometer and other data, such as the device's temperature.
*
* This driver is based on the document by Mark A. Smith available at
* http://www.almaden.ibm.com/cs/people/marksmith/tpaps.html and a lot of trial
* and error.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License v2 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/input-polldev.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/module.h>
#include <linux/timer.h>
#include <linux/dmi.h>
#include <linux/jiffies.h>
#include <linux/io.h>
#define HDAPS_LOW_PORT 0x1600 /* first port used by hdaps */
#define HDAPS_NR_PORTS 0x30 /* number of ports: 0x1600 - 0x162f */
#define HDAPS_PORT_STATE 0x1611 /* device state */
#define HDAPS_PORT_YPOS 0x1612 /* y-axis position */
#define HDAPS_PORT_XPOS 0x1614 /* x-axis position */
#define HDAPS_PORT_TEMP1 0x1616 /* device temperature, in Celsius */
#define HDAPS_PORT_YVAR 0x1617 /* y-axis variance (what is this?) */
#define HDAPS_PORT_XVAR 0x1619 /* x-axis variance (what is this?) */
#define HDAPS_PORT_TEMP2 0x161b /* device temperature (again?) */
#define HDAPS_PORT_UNKNOWN 0x161c /* what is this? */
#define HDAPS_PORT_KMACT 0x161d /* keyboard or mouse activity */
#define STATE_FRESH 0x50 /* accelerometer data is fresh */
#define KEYBD_MASK 0x20 /* set if keyboard activity */
#define MOUSE_MASK 0x40 /* set if mouse activity */
#define KEYBD_ISSET(n) (!! (n & KEYBD_MASK)) /* keyboard used? */
#define MOUSE_ISSET(n) (!! (n & MOUSE_MASK)) /* mouse used? */
#define INIT_TIMEOUT_MSECS 4000 /* wait up to 4s for device init ... */
#define INIT_WAIT_MSECS 200 /* ... in 200ms increments */
#define HDAPS_POLL_INTERVAL 50 /* poll for input every 1/20s (50 ms)*/
#define HDAPS_INPUT_FUZZ 4 /* input event threshold */
#define HDAPS_INPUT_FLAT 4
#define HDAPS_X_AXIS (1 << 0)
#define HDAPS_Y_AXIS (1 << 1)
#define HDAPS_BOTH_AXES (HDAPS_X_AXIS | HDAPS_Y_AXIS)
static struct platform_device *pdev;
static struct input_polled_dev *hdaps_idev;
static unsigned int hdaps_invert;
static u8 km_activity;
static int rest_x;
static int rest_y;
static DEFINE_MUTEX(hdaps_mtx);
/*
* __get_latch - Get the value from a given port. Callers must hold hdaps_mtx.
*/
static inline u8 __get_latch(u16 port)
{
return inb(port) & 0xff;
}
/*
* __check_latch - Check a port latch for a given value. Returns zero if the
* port contains the given value. Callers must hold hdaps_mtx.
*/
static inline int __check_latch(u16 port, u8 val)
{
if (__get_latch(port) == val)
return 0;
return -EINVAL;
}
/*
* __wait_latch - Wait up to 100us for a port latch to get a certain value,
* returning zero if the value is obtained. Callers must hold hdaps_mtx.
*/
static int __wait_latch(u16 port, u8 val)
{
unsigned int i;
for (i = 0; i < 20; i++) {
if (!__check_latch(port, val))
return 0;
udelay(5);
}
return -EIO;
}
/*
* __device_refresh - request a refresh from the accelerometer. Does not wait
* for refresh to complete. Callers must hold hdaps_mtx.
*/
static void __device_refresh(void)
{
udelay(200);
if (inb(0x1604) != STATE_FRESH) {
outb(0x11, 0x1610);
outb(0x01, 0x161f);
}
}
/*
* __device_refresh_sync - request a synchronous refresh from the
* accelerometer. We wait for the refresh to complete. Returns zero if
* successful and nonzero on error. Callers must hold hdaps_mtx.
*/
static int __device_refresh_sync(void)
{
__device_refresh();
return __wait_latch(0x1604, STATE_FRESH);
}
/*
* __device_complete - indicate to the accelerometer that we are done reading
* data, and then initiate an async refresh. Callers must hold hdaps_mtx.
*/
static inline void __device_complete(void)
{
inb(0x161f);
inb(0x1604);
__device_refresh();
}
/*
* hdaps_readb_one - reads a byte from a single I/O port, placing the value in
* the given pointer. Returns zero on success or a negative error on failure.
* Can sleep.
*/
static int hdaps_readb_one(unsigned int port, u8 *val)
{
int ret;
mutex_lock(&hdaps_mtx);
/* do a sync refresh -- we need to be sure that we read fresh data */
ret = __device_refresh_sync();
if (ret)
goto out;
*val = inb(port);
__device_complete();
out:
mutex_unlock(&hdaps_mtx);
return ret;
}
/* __hdaps_read_pair - internal lockless helper for hdaps_read_pair(). */
static int __hdaps_read_pair(unsigned int port1, unsigned int port2,
int *x, int *y)
{
/* do a sync refresh -- we need to be sure that we read fresh data */
if (__device_refresh_sync())
return -EIO;
*y = inw(port2);
*x = inw(port1);
km_activity = inb(HDAPS_PORT_KMACT);
__device_complete();
/* hdaps_invert is a bitvector to negate the axes */
if (hdaps_invert & HDAPS_X_AXIS)
*x = -*x;
if (hdaps_invert & HDAPS_Y_AXIS)
*y = -*y;
return 0;
}
/*
* hdaps_read_pair - reads the values from a pair of ports, placing the values
* in the given pointers. Returns zero on success. Can sleep.
*/
static int hdaps_read_pair(unsigned int port1, unsigned int port2,
int *val1, int *val2)
{
int ret;
mutex_lock(&hdaps_mtx);
ret = __hdaps_read_pair(port1, port2, val1, val2);
mutex_unlock(&hdaps_mtx);
return ret;
}
/*
* hdaps_device_init - initialize the accelerometer. Returns zero on success
* and negative error code on failure. Can sleep.
*/
static int hdaps_device_init(void)
{
int total, ret = -ENXIO;
mutex_lock(&hdaps_mtx);
outb(0x13, 0x1610);
outb(0x01, 0x161f);
if (__wait_latch(0x161f, 0x00))
goto out;
/*
* Most ThinkPads return 0x01.
*
* Others--namely the R50p, T41p, and T42p--return 0x03. These laptops
* have "inverted" axises.
*
* The 0x02 value occurs when the chip has been previously initialized.
*/
if (__check_latch(0x1611, 0x03) &&
__check_latch(0x1611, 0x02) &&
__check_latch(0x1611, 0x01))
goto out;
printk(KERN_DEBUG "hdaps: initial latch check good (0x%02x)\n",
__get_latch(0x1611));
outb(0x17, 0x1610);
outb(0x81, 0x1611);
outb(0x01, 0x161f);
if (__wait_latch(0x161f, 0x00))
goto out;
if (__wait_latch(0x1611, 0x00))
goto out;
if (__wait_latch(0x1612, 0x60))
goto out;
if (__wait_latch(0x1613, 0x00))
goto out;
outb(0x14, 0x1610);
outb(0x01, 0x1611);
outb(0x01, 0x161f);
if (__wait_latch(0x161f, 0x00))
goto out;
outb(0x10, 0x1610);
outb(0xc8, 0x1611);
outb(0x00, 0x1612);
outb(0x02, 0x1613);
outb(0x01, 0x161f);
if (__wait_latch(0x161f, 0x00))
goto out;
if (__device_refresh_sync())
goto out;
if (__wait_latch(0x1611, 0x00))
goto out;
/* we have done our dance, now let's wait for the applause */
for (total = INIT_TIMEOUT_MSECS; total > 0; total -= INIT_WAIT_MSECS) {
int x, y;
/* a read of the device helps push it into action */
__hdaps_read_pair(HDAPS_PORT_XPOS, HDAPS_PORT_YPOS, &x, &y);
if (!__wait_latch(0x1611, 0x02)) {
ret = 0;
break;
}
msleep(INIT_WAIT_MSECS);
}
out:
mutex_unlock(&hdaps_mtx);
return ret;
}
/* Device model stuff */
static int hdaps_probe(struct platform_device *dev)
{
int ret;
ret = hdaps_device_init();
if (ret)
return ret;
pr_info("device successfully initialized\n");
return 0;
}
static int hdaps_resume(struct platform_device *dev)
{
return hdaps_device_init();
}
static struct platform_driver hdaps_driver = {
.probe = hdaps_probe,
.resume = hdaps_resume,
.driver = {
.name = "hdaps",
.owner = THIS_MODULE,
},
};
/*
* hdaps_calibrate - Set our "resting" values. Callers must hold hdaps_mtx.
*/
static void hdaps_calibrate(void)
{
__hdaps_read_pair(HDAPS_PORT_XPOS, HDAPS_PORT_YPOS, &rest_x, &rest_y);
}
static void hdaps_mousedev_poll(struct input_polled_dev *dev)
{
struct input_dev *input_dev = dev->input;
int x, y;
mutex_lock(&hdaps_mtx);
if (__hdaps_read_pair(HDAPS_PORT_XPOS, HDAPS_PORT_YPOS, &x, &y))
goto out;
input_report_abs(input_dev, ABS_X, x - rest_x);
input_report_abs(input_dev, ABS_Y, y - rest_y);
input_sync(input_dev);
out:
mutex_unlock(&hdaps_mtx);
}
/* Sysfs Files */
static ssize_t hdaps_position_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret, x, y;
ret = hdaps_read_pair(HDAPS_PORT_XPOS, HDAPS_PORT_YPOS, &x, &y);
if (ret)
return ret;
return sprintf(buf, "(%d,%d)\n", x, y);
}
static ssize_t hdaps_variance_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret, x, y;
ret = hdaps_read_pair(HDAPS_PORT_XVAR, HDAPS_PORT_YVAR, &x, &y);
if (ret)
return ret;
return sprintf(buf, "(%d,%d)\n", x, y);
}
static ssize_t hdaps_temp1_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
u8 uninitialized_var(temp);
int ret;
ret = hdaps_readb_one(HDAPS_PORT_TEMP1, &temp);
if (ret)
return ret;
return sprintf(buf, "%u\n", temp);
}
static ssize_t hdaps_temp2_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
u8 uninitialized_var(temp);
int ret;
ret = hdaps_readb_one(HDAPS_PORT_TEMP2, &temp);
if (ret)
return ret;
return sprintf(buf, "%u\n", temp);
}
static ssize_t hdaps_keyboard_activity_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", KEYBD_ISSET(km_activity));
}
static ssize_t hdaps_mouse_activity_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
return sprintf(buf, "%u\n", MOUSE_ISSET(km_activity));
}
static ssize_t hdaps_calibrate_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "(%d,%d)\n", rest_x, rest_y);
}
static ssize_t hdaps_calibrate_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
mutex_lock(&hdaps_mtx);
hdaps_calibrate();
mutex_unlock(&hdaps_mtx);
return count;
}
static ssize_t hdaps_invert_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%u\n", hdaps_invert);
}
static ssize_t hdaps_invert_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int invert;
if (sscanf(buf, "%d", &invert) != 1 ||
invert < 0 || invert > HDAPS_BOTH_AXES)
return -EINVAL;
hdaps_invert = invert;
hdaps_calibrate();
return count;
}
static DEVICE_ATTR(position, 0444, hdaps_position_show, NULL);
static DEVICE_ATTR(variance, 0444, hdaps_variance_show, NULL);
static DEVICE_ATTR(temp1, 0444, hdaps_temp1_show, NULL);
static DEVICE_ATTR(temp2, 0444, hdaps_temp2_show, NULL);
static DEVICE_ATTR(keyboard_activity, 0444, hdaps_keyboard_activity_show, NULL);
static DEVICE_ATTR(mouse_activity, 0444, hdaps_mouse_activity_show, NULL);
static DEVICE_ATTR(calibrate, 0644, hdaps_calibrate_show,hdaps_calibrate_store);
static DEVICE_ATTR(invert, 0644, hdaps_invert_show, hdaps_invert_store);
static struct attribute *hdaps_attributes[] = {
&dev_attr_position.attr,
&dev_attr_variance.attr,
&dev_attr_temp1.attr,
&dev_attr_temp2.attr,
&dev_attr_keyboard_activity.attr,
&dev_attr_mouse_activity.attr,
&dev_attr_calibrate.attr,
&dev_attr_invert.attr,
NULL,
};
static struct attribute_group hdaps_attribute_group = {
.attrs = hdaps_attributes,
};
/* Module stuff */
/* hdaps_dmi_match - found a match. return one, short-circuiting the hunt. */
static int __init hdaps_dmi_match(const struct dmi_system_id *id)
{
pr_info("%s detected\n", id->ident);
return 1;
}
/* hdaps_dmi_match_invert - found an inverted match. */
static int __init hdaps_dmi_match_invert(const struct dmi_system_id *id)
{
hdaps_invert = (unsigned long)id->driver_data;
pr_info("inverting axis (%u) readings\n", hdaps_invert);
return hdaps_dmi_match(id);
}
#define HDAPS_DMI_MATCH_INVERT(vendor, model, axes) { \
.ident = vendor " " model, \
.callback = hdaps_dmi_match_invert, \
.driver_data = (void *)axes, \
.matches = { \
DMI_MATCH(DMI_BOARD_VENDOR, vendor), \
DMI_MATCH(DMI_PRODUCT_VERSION, model) \
} \
}
#define HDAPS_DMI_MATCH_NORMAL(vendor, model) \
HDAPS_DMI_MATCH_INVERT(vendor, model, 0)
/* Note that HDAPS_DMI_MATCH_NORMAL("ThinkPad T42") would match
"ThinkPad T42p", so the order of the entries matters.
If your ThinkPad is not recognized, please update to latest
BIOS. This is especially the case for some R52 ThinkPads. */
static struct dmi_system_id __initdata hdaps_whitelist[] = {
HDAPS_DMI_MATCH_INVERT("IBM", "ThinkPad R50p", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad R50"),
HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad R51"),
HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad R52"),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad R61i", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad R61", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_INVERT("IBM", "ThinkPad T41p", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad T41"),
HDAPS_DMI_MATCH_INVERT("IBM", "ThinkPad T42p", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad T42"),
HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad T43"),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad T400", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad T60", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad T61p", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad T61", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad X40"),
HDAPS_DMI_MATCH_INVERT("IBM", "ThinkPad X41", HDAPS_Y_AXIS),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad X60", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad X61s", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad X61", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad Z60m"),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad Z61m", HDAPS_BOTH_AXES),
HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad Z61p", HDAPS_BOTH_AXES),
{ .ident = NULL }
};
static int __init hdaps_init(void)
{
struct input_dev *idev;
int ret;
if (!dmi_check_system(hdaps_whitelist)) {
pr_warn("supported laptop not found!\n");
ret = -ENODEV;
goto out;
}
if (!request_region(HDAPS_LOW_PORT, HDAPS_NR_PORTS, "hdaps")) {
ret = -ENXIO;
goto out;
}
ret = platform_driver_register(&hdaps_driver);
if (ret)
goto out_region;
pdev = platform_device_register_simple("hdaps", -1, NULL, 0);
if (IS_ERR(pdev)) {
ret = PTR_ERR(pdev);
goto out_driver;
}
ret = sysfs_create_group(&pdev->dev.kobj, &hdaps_attribute_group);
if (ret)
goto out_device;
hdaps_idev = input_allocate_polled_device();
if (!hdaps_idev) {
ret = -ENOMEM;
goto out_group;
}
hdaps_idev->poll = hdaps_mousedev_poll;
hdaps_idev->poll_interval = HDAPS_POLL_INTERVAL;
/* initial calibrate for the input device */
hdaps_calibrate();
/* initialize the input class */
idev = hdaps_idev->input;
idev->name = "hdaps";
idev->phys = "isa1600/input0";
idev->id.bustype = BUS_ISA;
idev->dev.parent = &pdev->dev;
idev->evbit[0] = BIT_MASK(EV_ABS);
input_set_abs_params(idev, ABS_X,
-256, 256, HDAPS_INPUT_FUZZ, HDAPS_INPUT_FLAT);
input_set_abs_params(idev, ABS_Y,
-256, 256, HDAPS_INPUT_FUZZ, HDAPS_INPUT_FLAT);
ret = input_register_polled_device(hdaps_idev);
if (ret)
goto out_idev;
pr_info("driver successfully loaded\n");
return 0;
out_idev:
input_free_polled_device(hdaps_idev);
out_group:
sysfs_remove_group(&pdev->dev.kobj, &hdaps_attribute_group);
out_device:
platform_device_unregister(pdev);
out_driver:
platform_driver_unregister(&hdaps_driver);
out_region:
release_region(HDAPS_LOW_PORT, HDAPS_NR_PORTS);
out:
pr_warn("driver init failed (ret=%d)!\n", ret);
return ret;
}
static void __exit hdaps_exit(void)
{
input_unregister_polled_device(hdaps_idev);
input_free_polled_device(hdaps_idev);
sysfs_remove_group(&pdev->dev.kobj, &hdaps_attribute_group);
platform_device_unregister(pdev);
platform_driver_unregister(&hdaps_driver);
release_region(HDAPS_LOW_PORT, HDAPS_NR_PORTS);
pr_info("driver unloaded\n");
}
module_init(hdaps_init);
module_exit(hdaps_exit);
module_param_named(invert, hdaps_invert, int, 0);
MODULE_PARM_DESC(invert, "invert data along each axis. 1 invert x-axis, "
"2 invert y-axis, 3 invert both axes.");
MODULE_AUTHOR("Robert Love");
MODULE_DESCRIPTION("IBM Hard Drive Active Protection System (HDAPS) driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
baselsayeh/Kyleopen-4.4 | drivers/net/wireless/mwifiex/sta_cmdresp.c | 4806 | 28307 | /*
* Marvell Wireless LAN device driver: station command response handling
*
* Copyright (C) 2011, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
/*
* This function handles the command response error case.
*
* For scan response error, the function cancels all the pending
* scan commands and generates an event to inform the applications
* of the scan completion.
*
* For Power Save command failure, we do not retry enter PS
* command in case of Ad-hoc mode.
*
* For all other response errors, the current command buffer is freed
* and returned to the free command queue.
*/
static void
mwifiex_process_cmdresp_error(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct cmd_ctrl_node *cmd_node = NULL, *tmp_node;
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_802_11_ps_mode_enh *pm;
unsigned long flags;
dev_err(adapter->dev, "CMD_RESP: cmd %#x error, result=%#x\n",
resp->command, resp->result);
if (adapter->curr_cmd->wait_q_enabled)
adapter->cmd_wait_q.status = -1;
switch (le16_to_cpu(resp->command)) {
case HostCmd_CMD_802_11_PS_MODE_ENH:
pm = &resp->params.psmode_enh;
dev_err(adapter->dev,
"PS_MODE_ENH cmd failed: result=0x%x action=0x%X\n",
resp->result, le16_to_cpu(pm->action));
/* We do not re-try enter-ps command in ad-hoc mode. */
if (le16_to_cpu(pm->action) == EN_AUTO_PS &&
(le16_to_cpu(pm->params.ps_bitmap) & BITMAP_STA_PS) &&
priv->bss_mode == NL80211_IFTYPE_ADHOC)
adapter->ps_mode = MWIFIEX_802_11_POWER_MODE_CAM;
break;
case HostCmd_CMD_802_11_SCAN:
/* Cancel all pending scan command */
spin_lock_irqsave(&adapter->scan_pending_q_lock, flags);
list_for_each_entry_safe(cmd_node, tmp_node,
&adapter->scan_pending_q, list) {
list_del(&cmd_node->list);
spin_unlock_irqrestore(&adapter->scan_pending_q_lock,
flags);
mwifiex_insert_cmd_to_free_q(adapter, cmd_node);
spin_lock_irqsave(&adapter->scan_pending_q_lock, flags);
}
spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags);
spin_lock_irqsave(&adapter->mwifiex_cmd_lock, flags);
adapter->scan_processing = false;
spin_unlock_irqrestore(&adapter->mwifiex_cmd_lock, flags);
if (priv->report_scan_result)
priv->report_scan_result = false;
if (priv->scan_pending_on_block) {
priv->scan_pending_on_block = false;
up(&priv->async_sem);
}
break;
case HostCmd_CMD_MAC_CONTROL:
break;
default:
break;
}
/* Handling errors here */
mwifiex_insert_cmd_to_free_q(adapter, adapter->curr_cmd);
spin_lock_irqsave(&adapter->mwifiex_cmd_lock, flags);
adapter->curr_cmd = NULL;
spin_unlock_irqrestore(&adapter->mwifiex_cmd_lock, flags);
}
/*
* This function handles the command response of get RSSI info.
*
* Handling includes changing the header fields into CPU format
* and saving the following parameters in driver -
* - Last data and beacon RSSI value
* - Average data and beacon RSSI value
* - Last data and beacon NF value
* - Average data and beacon NF value
*
* The parameters are send to the application as well, along with
* calculated SNR values.
*/
static int mwifiex_ret_802_11_rssi_info(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp,
struct mwifiex_ds_get_signal *signal)
{
struct host_cmd_ds_802_11_rssi_info_rsp *rssi_info_rsp =
&resp->params.rssi_info_rsp;
priv->data_rssi_last = le16_to_cpu(rssi_info_rsp->data_rssi_last);
priv->data_nf_last = le16_to_cpu(rssi_info_rsp->data_nf_last);
priv->data_rssi_avg = le16_to_cpu(rssi_info_rsp->data_rssi_avg);
priv->data_nf_avg = le16_to_cpu(rssi_info_rsp->data_nf_avg);
priv->bcn_rssi_last = le16_to_cpu(rssi_info_rsp->bcn_rssi_last);
priv->bcn_nf_last = le16_to_cpu(rssi_info_rsp->bcn_nf_last);
priv->bcn_rssi_avg = le16_to_cpu(rssi_info_rsp->bcn_rssi_avg);
priv->bcn_nf_avg = le16_to_cpu(rssi_info_rsp->bcn_nf_avg);
/* Need to indicate IOCTL complete */
if (signal) {
memset(signal, 0, sizeof(*signal));
signal->selector = ALL_RSSI_INFO_MASK;
/* RSSI */
signal->bcn_rssi_last = priv->bcn_rssi_last;
signal->bcn_rssi_avg = priv->bcn_rssi_avg;
signal->data_rssi_last = priv->data_rssi_last;
signal->data_rssi_avg = priv->data_rssi_avg;
/* SNR */
signal->bcn_snr_last =
CAL_SNR(priv->bcn_rssi_last, priv->bcn_nf_last);
signal->bcn_snr_avg =
CAL_SNR(priv->bcn_rssi_avg, priv->bcn_nf_avg);
signal->data_snr_last =
CAL_SNR(priv->data_rssi_last, priv->data_nf_last);
signal->data_snr_avg =
CAL_SNR(priv->data_rssi_avg, priv->data_nf_avg);
/* NF */
signal->bcn_nf_last = priv->bcn_nf_last;
signal->bcn_nf_avg = priv->bcn_nf_avg;
signal->data_nf_last = priv->data_nf_last;
signal->data_nf_avg = priv->data_nf_avg;
}
return 0;
}
/*
* This function handles the command response of set/get SNMP
* MIB parameters.
*
* Handling includes changing the header fields into CPU format
* and saving the parameter in driver.
*
* The following parameters are supported -
* - Fragmentation threshold
* - RTS threshold
* - Short retry limit
*/
static int mwifiex_ret_802_11_snmp_mib(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp,
u32 *data_buf)
{
struct host_cmd_ds_802_11_snmp_mib *smib = &resp->params.smib;
u16 oid = le16_to_cpu(smib->oid);
u16 query_type = le16_to_cpu(smib->query_type);
u32 ul_temp;
dev_dbg(priv->adapter->dev, "info: SNMP_RESP: oid value = %#x,"
" query_type = %#x, buf size = %#x\n",
oid, query_type, le16_to_cpu(smib->buf_size));
if (query_type == HostCmd_ACT_GEN_GET) {
ul_temp = le16_to_cpu(*((__le16 *) (smib->value)));
if (data_buf)
*data_buf = ul_temp;
switch (oid) {
case FRAG_THRESH_I:
dev_dbg(priv->adapter->dev,
"info: SNMP_RESP: FragThsd =%u\n", ul_temp);
break;
case RTS_THRESH_I:
dev_dbg(priv->adapter->dev,
"info: SNMP_RESP: RTSThsd =%u\n", ul_temp);
break;
case SHORT_RETRY_LIM_I:
dev_dbg(priv->adapter->dev,
"info: SNMP_RESP: TxRetryCount=%u\n", ul_temp);
break;
case DTIM_PERIOD_I:
dev_dbg(priv->adapter->dev,
"info: SNMP_RESP: DTIM period=%u\n", ul_temp);
default:
break;
}
}
return 0;
}
/*
* This function handles the command response of get log request
*
* Handling includes changing the header fields into CPU format
* and sending the received parameters to application.
*/
static int mwifiex_ret_get_log(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp,
struct mwifiex_ds_get_stats *stats)
{
struct host_cmd_ds_802_11_get_log *get_log =
(struct host_cmd_ds_802_11_get_log *) &resp->params.get_log;
if (stats) {
stats->mcast_tx_frame = le32_to_cpu(get_log->mcast_tx_frame);
stats->failed = le32_to_cpu(get_log->failed);
stats->retry = le32_to_cpu(get_log->retry);
stats->multi_retry = le32_to_cpu(get_log->multi_retry);
stats->frame_dup = le32_to_cpu(get_log->frame_dup);
stats->rts_success = le32_to_cpu(get_log->rts_success);
stats->rts_failure = le32_to_cpu(get_log->rts_failure);
stats->ack_failure = le32_to_cpu(get_log->ack_failure);
stats->rx_frag = le32_to_cpu(get_log->rx_frag);
stats->mcast_rx_frame = le32_to_cpu(get_log->mcast_rx_frame);
stats->fcs_error = le32_to_cpu(get_log->fcs_error);
stats->tx_frame = le32_to_cpu(get_log->tx_frame);
stats->wep_icv_error[0] =
le32_to_cpu(get_log->wep_icv_err_cnt[0]);
stats->wep_icv_error[1] =
le32_to_cpu(get_log->wep_icv_err_cnt[1]);
stats->wep_icv_error[2] =
le32_to_cpu(get_log->wep_icv_err_cnt[2]);
stats->wep_icv_error[3] =
le32_to_cpu(get_log->wep_icv_err_cnt[3]);
}
return 0;
}
/*
* This function handles the command response of set/get Tx rate
* configurations.
*
* Handling includes changing the header fields into CPU format
* and saving the following parameters in driver -
* - DSSS rate bitmap
* - OFDM rate bitmap
* - HT MCS rate bitmaps
*
* Based on the new rate bitmaps, the function re-evaluates if
* auto data rate has been activated. If not, it sends another
* query to the firmware to get the current Tx data rate and updates
* the driver value.
*/
static int mwifiex_ret_tx_rate_cfg(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp,
struct mwifiex_rate_cfg *ds_rate)
{
struct host_cmd_ds_tx_rate_cfg *rate_cfg = &resp->params.tx_rate_cfg;
struct mwifiex_rate_scope *rate_scope;
struct mwifiex_ie_types_header *head;
u16 tlv, tlv_buf_len;
u8 *tlv_buf;
u32 i;
int ret = 0;
tlv_buf = (u8 *) ((u8 *) rate_cfg) +
sizeof(struct host_cmd_ds_tx_rate_cfg);
tlv_buf_len = *(u16 *) (tlv_buf + sizeof(u16));
while (tlv_buf && tlv_buf_len > 0) {
tlv = (*tlv_buf);
tlv = tlv | (*(tlv_buf + 1) << 8);
switch (tlv) {
case TLV_TYPE_RATE_SCOPE:
rate_scope = (struct mwifiex_rate_scope *) tlv_buf;
priv->bitmap_rates[0] =
le16_to_cpu(rate_scope->hr_dsss_rate_bitmap);
priv->bitmap_rates[1] =
le16_to_cpu(rate_scope->ofdm_rate_bitmap);
for (i = 0;
i <
sizeof(rate_scope->ht_mcs_rate_bitmap) /
sizeof(u16); i++)
priv->bitmap_rates[2 + i] =
le16_to_cpu(rate_scope->
ht_mcs_rate_bitmap[i]);
break;
/* Add RATE_DROP tlv here */
}
head = (struct mwifiex_ie_types_header *) tlv_buf;
tlv_buf += le16_to_cpu(head->len) + sizeof(*head);
tlv_buf_len -= le16_to_cpu(head->len);
}
priv->is_data_rate_auto = mwifiex_is_rate_auto(priv);
if (priv->is_data_rate_auto)
priv->data_rate = 0;
else
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_TX_RATE_QUERY,
HostCmd_ACT_GEN_GET, 0, NULL);
if (!ds_rate)
return ret;
if (le16_to_cpu(rate_cfg->action) == HostCmd_ACT_GEN_GET) {
if (priv->is_data_rate_auto) {
ds_rate->is_rate_auto = 1;
return ret;
}
ds_rate->rate = mwifiex_get_rate_index(priv->bitmap_rates,
sizeof(priv->bitmap_rates));
if (ds_rate->rate >= MWIFIEX_RATE_BITMAP_OFDM0 &&
ds_rate->rate <= MWIFIEX_RATE_BITMAP_OFDM7)
ds_rate->rate -= (MWIFIEX_RATE_BITMAP_OFDM0 -
MWIFIEX_RATE_INDEX_OFDM0);
if (ds_rate->rate >= MWIFIEX_RATE_BITMAP_MCS0 &&
ds_rate->rate <= MWIFIEX_RATE_BITMAP_MCS127)
ds_rate->rate -= (MWIFIEX_RATE_BITMAP_MCS0 -
MWIFIEX_RATE_INDEX_MCS0);
}
return ret;
}
/*
* This function handles the command response of get Tx power level.
*
* Handling includes saving the maximum and minimum Tx power levels
* in driver, as well as sending the values to user.
*/
static int mwifiex_get_power_level(struct mwifiex_private *priv, void *data_buf)
{
int length, max_power = -1, min_power = -1;
struct mwifiex_types_power_group *pg_tlv_hdr;
struct mwifiex_power_group *pg;
if (!data_buf)
return -1;
pg_tlv_hdr = (struct mwifiex_types_power_group *)
((u8 *) data_buf + sizeof(struct host_cmd_ds_txpwr_cfg));
pg = (struct mwifiex_power_group *)
((u8 *) pg_tlv_hdr + sizeof(struct mwifiex_types_power_group));
length = pg_tlv_hdr->length;
if (length > 0) {
max_power = pg->power_max;
min_power = pg->power_min;
length -= sizeof(struct mwifiex_power_group);
}
while (length) {
pg++;
if (max_power < pg->power_max)
max_power = pg->power_max;
if (min_power > pg->power_min)
min_power = pg->power_min;
length -= sizeof(struct mwifiex_power_group);
}
if (pg_tlv_hdr->length > 0) {
priv->min_tx_power_level = (u8) min_power;
priv->max_tx_power_level = (u8) max_power;
}
return 0;
}
/*
* This function handles the command response of set/get Tx power
* configurations.
*
* Handling includes changing the header fields into CPU format
* and saving the current Tx power level in driver.
*/
static int mwifiex_ret_tx_power_cfg(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct host_cmd_ds_txpwr_cfg *txp_cfg = &resp->params.txp_cfg;
struct mwifiex_types_power_group *pg_tlv_hdr;
struct mwifiex_power_group *pg;
u16 action = le16_to_cpu(txp_cfg->action);
switch (action) {
case HostCmd_ACT_GEN_GET:
pg_tlv_hdr = (struct mwifiex_types_power_group *)
((u8 *) txp_cfg +
sizeof(struct host_cmd_ds_txpwr_cfg));
pg = (struct mwifiex_power_group *)
((u8 *) pg_tlv_hdr +
sizeof(struct mwifiex_types_power_group));
if (adapter->hw_status == MWIFIEX_HW_STATUS_INITIALIZING)
mwifiex_get_power_level(priv, txp_cfg);
priv->tx_power_level = (u16) pg->power_min;
break;
case HostCmd_ACT_GEN_SET:
if (!le32_to_cpu(txp_cfg->mode))
break;
pg_tlv_hdr = (struct mwifiex_types_power_group *)
((u8 *) txp_cfg +
sizeof(struct host_cmd_ds_txpwr_cfg));
pg = (struct mwifiex_power_group *)
((u8 *) pg_tlv_hdr +
sizeof(struct mwifiex_types_power_group));
if (pg->power_max == pg->power_min)
priv->tx_power_level = (u16) pg->power_min;
break;
default:
dev_err(adapter->dev, "CMD_RESP: unknown cmd action %d\n",
action);
return 0;
}
dev_dbg(adapter->dev,
"info: Current TxPower Level = %d, Max Power=%d, Min Power=%d\n",
priv->tx_power_level, priv->max_tx_power_level,
priv->min_tx_power_level);
return 0;
}
/*
* This function handles the command response of set/get MAC address.
*
* Handling includes saving the MAC address in driver.
*/
static int mwifiex_ret_802_11_mac_address(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct host_cmd_ds_802_11_mac_address *cmd_mac_addr =
&resp->params.mac_addr;
memcpy(priv->curr_addr, cmd_mac_addr->mac_addr, ETH_ALEN);
dev_dbg(priv->adapter->dev,
"info: set mac address: %pM\n", priv->curr_addr);
return 0;
}
/*
* This function handles the command response of set/get MAC multicast
* address.
*/
static int mwifiex_ret_mac_multicast_adr(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
return 0;
}
/*
* This function handles the command response of get Tx rate query.
*
* Handling includes changing the header fields into CPU format
* and saving the Tx rate and HT information parameters in driver.
*
* Both rate configuration and current data rate can be retrieved
* with this request.
*/
static int mwifiex_ret_802_11_tx_rate_query(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
priv->tx_rate = resp->params.tx_rate.tx_rate;
priv->tx_htinfo = resp->params.tx_rate.ht_info;
if (!priv->is_data_rate_auto)
priv->data_rate =
mwifiex_index_to_data_rate(priv, priv->tx_rate,
priv->tx_htinfo);
return 0;
}
/*
* This function handles the command response of a deauthenticate
* command.
*
* If the deauthenticated MAC matches the current BSS MAC, the connection
* state is reset.
*/
static int mwifiex_ret_802_11_deauthenticate(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct mwifiex_adapter *adapter = priv->adapter;
adapter->dbg.num_cmd_deauth++;
if (!memcmp(resp->params.deauth.mac_addr,
&priv->curr_bss_params.bss_descriptor.mac_address,
sizeof(resp->params.deauth.mac_addr)))
mwifiex_reset_connect_state(priv);
return 0;
}
/*
* This function handles the command response of ad-hoc stop.
*
* The function resets the connection state in driver.
*/
static int mwifiex_ret_802_11_ad_hoc_stop(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
mwifiex_reset_connect_state(priv);
return 0;
}
/*
* This function handles the command response of set/get key material.
*
* Handling includes updating the driver parameters to reflect the
* changes.
*/
static int mwifiex_ret_802_11_key_material(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct host_cmd_ds_802_11_key_material *key =
&resp->params.key_material;
if (le16_to_cpu(key->action) == HostCmd_ACT_GEN_SET) {
if ((le16_to_cpu(key->key_param_set.key_info) & KEY_MCAST)) {
dev_dbg(priv->adapter->dev, "info: key: GTK is set\n");
priv->wpa_is_gtk_set = true;
priv->scan_block = false;
}
}
memset(priv->aes_key.key_param_set.key, 0,
sizeof(key->key_param_set.key));
priv->aes_key.key_param_set.key_len = key->key_param_set.key_len;
memcpy(priv->aes_key.key_param_set.key, key->key_param_set.key,
le16_to_cpu(priv->aes_key.key_param_set.key_len));
return 0;
}
/*
* This function handles the command response of get 11d domain information.
*/
static int mwifiex_ret_802_11d_domain_info(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct host_cmd_ds_802_11d_domain_info_rsp *domain_info =
&resp->params.domain_info_resp;
struct mwifiex_ietypes_domain_param_set *domain = &domain_info->domain;
u16 action = le16_to_cpu(domain_info->action);
u8 no_of_triplet;
no_of_triplet = (u8) ((le16_to_cpu(domain->header.len)
- IEEE80211_COUNTRY_STRING_LEN)
/ sizeof(struct ieee80211_country_ie_triplet));
dev_dbg(priv->adapter->dev,
"info: 11D Domain Info Resp: no_of_triplet=%d\n",
no_of_triplet);
if (no_of_triplet > MWIFIEX_MAX_TRIPLET_802_11D) {
dev_warn(priv->adapter->dev,
"11D: invalid number of triplets %d returned\n",
no_of_triplet);
return -1;
}
switch (action) {
case HostCmd_ACT_GEN_SET: /* Proc Set Action */
break;
case HostCmd_ACT_GEN_GET:
break;
default:
dev_err(priv->adapter->dev,
"11D: invalid action:%d\n", domain_info->action);
return -1;
}
return 0;
}
/*
* This function handles the command response of get RF channel.
*
* Handling includes changing the header fields into CPU format
* and saving the new channel in driver.
*/
static int mwifiex_ret_802_11_rf_channel(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp,
u16 *data_buf)
{
struct host_cmd_ds_802_11_rf_channel *rf_channel =
&resp->params.rf_channel;
u16 new_channel = le16_to_cpu(rf_channel->current_channel);
if (priv->curr_bss_params.bss_descriptor.channel != new_channel) {
dev_dbg(priv->adapter->dev, "cmd: Channel Switch: %d to %d\n",
priv->curr_bss_params.bss_descriptor.channel,
new_channel);
/* Update the channel again */
priv->curr_bss_params.bss_descriptor.channel = new_channel;
}
if (data_buf)
*data_buf = new_channel;
return 0;
}
/*
* This function handles the command response of get extended version.
*
* Handling includes forming the extended version string and sending it
* to application.
*/
static int mwifiex_ret_ver_ext(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp,
struct host_cmd_ds_version_ext *version_ext)
{
struct host_cmd_ds_version_ext *ver_ext = &resp->params.verext;
if (version_ext) {
version_ext->version_str_sel = ver_ext->version_str_sel;
memcpy(version_ext->version_str, ver_ext->version_str,
sizeof(char) * 128);
memcpy(priv->version_str, ver_ext->version_str, 128);
}
return 0;
}
/*
* This function handles the command response of register access.
*
* The register value and offset are returned to the user. For EEPROM
* access, the byte count is also returned.
*/
static int mwifiex_ret_reg_access(u16 type, struct host_cmd_ds_command *resp,
void *data_buf)
{
struct mwifiex_ds_reg_rw *reg_rw;
struct mwifiex_ds_read_eeprom *eeprom;
union reg {
struct host_cmd_ds_mac_reg_access *mac;
struct host_cmd_ds_bbp_reg_access *bbp;
struct host_cmd_ds_rf_reg_access *rf;
struct host_cmd_ds_pmic_reg_access *pmic;
struct host_cmd_ds_802_11_eeprom_access *eeprom;
} r;
if (!data_buf)
return 0;
reg_rw = data_buf;
eeprom = data_buf;
switch (type) {
case HostCmd_CMD_MAC_REG_ACCESS:
r.mac = (struct host_cmd_ds_mac_reg_access *)
&resp->params.mac_reg;
reg_rw->offset = cpu_to_le32((u32) le16_to_cpu(r.mac->offset));
reg_rw->value = r.mac->value;
break;
case HostCmd_CMD_BBP_REG_ACCESS:
r.bbp = (struct host_cmd_ds_bbp_reg_access *)
&resp->params.bbp_reg;
reg_rw->offset = cpu_to_le32((u32) le16_to_cpu(r.bbp->offset));
reg_rw->value = cpu_to_le32((u32) r.bbp->value);
break;
case HostCmd_CMD_RF_REG_ACCESS:
r.rf = (struct host_cmd_ds_rf_reg_access *)
&resp->params.rf_reg;
reg_rw->offset = cpu_to_le32((u32) le16_to_cpu(r.rf->offset));
reg_rw->value = cpu_to_le32((u32) r.bbp->value);
break;
case HostCmd_CMD_PMIC_REG_ACCESS:
r.pmic = (struct host_cmd_ds_pmic_reg_access *)
&resp->params.pmic_reg;
reg_rw->offset = cpu_to_le32((u32) le16_to_cpu(r.pmic->offset));
reg_rw->value = cpu_to_le32((u32) r.pmic->value);
break;
case HostCmd_CMD_CAU_REG_ACCESS:
r.rf = (struct host_cmd_ds_rf_reg_access *)
&resp->params.rf_reg;
reg_rw->offset = cpu_to_le32((u32) le16_to_cpu(r.rf->offset));
reg_rw->value = cpu_to_le32((u32) r.rf->value);
break;
case HostCmd_CMD_802_11_EEPROM_ACCESS:
r.eeprom = (struct host_cmd_ds_802_11_eeprom_access *)
&resp->params.eeprom;
pr_debug("info: EEPROM read len=%x\n", r.eeprom->byte_count);
if (le16_to_cpu(eeprom->byte_count) <
le16_to_cpu(r.eeprom->byte_count)) {
eeprom->byte_count = cpu_to_le16(0);
pr_debug("info: EEPROM read length is too big\n");
return -1;
}
eeprom->offset = r.eeprom->offset;
eeprom->byte_count = r.eeprom->byte_count;
if (le16_to_cpu(eeprom->byte_count) > 0)
memcpy(&eeprom->value, &r.eeprom->value,
le16_to_cpu(r.eeprom->byte_count));
break;
default:
return -1;
}
return 0;
}
/*
* This function handles the command response of get IBSS coalescing status.
*
* If the received BSSID is different than the current one, the current BSSID,
* beacon interval, ATIM window and ERP information are updated, along with
* changing the ad-hoc state accordingly.
*/
static int mwifiex_ret_ibss_coalescing_status(struct mwifiex_private *priv,
struct host_cmd_ds_command *resp)
{
struct host_cmd_ds_802_11_ibss_status *ibss_coal_resp =
&(resp->params.ibss_coalescing);
u8 zero_mac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };
if (le16_to_cpu(ibss_coal_resp->action) == HostCmd_ACT_GEN_SET)
return 0;
dev_dbg(priv->adapter->dev,
"info: new BSSID %pM\n", ibss_coal_resp->bssid);
/* If rsp has NULL BSSID, Just return..... No Action */
if (!memcmp(ibss_coal_resp->bssid, zero_mac, ETH_ALEN)) {
dev_warn(priv->adapter->dev, "new BSSID is NULL\n");
return 0;
}
/* If BSSID is diff, modify current BSS parameters */
if (memcmp(priv->curr_bss_params.bss_descriptor.mac_address,
ibss_coal_resp->bssid, ETH_ALEN)) {
/* BSSID */
memcpy(priv->curr_bss_params.bss_descriptor.mac_address,
ibss_coal_resp->bssid, ETH_ALEN);
/* Beacon Interval */
priv->curr_bss_params.bss_descriptor.beacon_period
= le16_to_cpu(ibss_coal_resp->beacon_interval);
/* ERP Information */
priv->curr_bss_params.bss_descriptor.erp_flags =
(u8) le16_to_cpu(ibss_coal_resp->use_g_rate_protect);
priv->adhoc_state = ADHOC_COALESCED;
}
return 0;
}
/*
* This function handles the command responses.
*
* This is a generic function, which calls command specific
* response handlers based on the command ID.
*/
int mwifiex_process_sta_cmdresp(struct mwifiex_private *priv, u16 cmdresp_no,
struct host_cmd_ds_command *resp)
{
int ret = 0;
struct mwifiex_adapter *adapter = priv->adapter;
void *data_buf = adapter->curr_cmd->data_buf;
/* If the command is not successful, cleanup and return failure */
if (resp->result != HostCmd_RESULT_OK) {
mwifiex_process_cmdresp_error(priv, resp);
return -1;
}
/* Command successful, handle response */
switch (cmdresp_no) {
case HostCmd_CMD_GET_HW_SPEC:
ret = mwifiex_ret_get_hw_spec(priv, resp);
break;
case HostCmd_CMD_MAC_CONTROL:
break;
case HostCmd_CMD_802_11_MAC_ADDRESS:
ret = mwifiex_ret_802_11_mac_address(priv, resp);
break;
case HostCmd_CMD_MAC_MULTICAST_ADR:
ret = mwifiex_ret_mac_multicast_adr(priv, resp);
break;
case HostCmd_CMD_TX_RATE_CFG:
ret = mwifiex_ret_tx_rate_cfg(priv, resp, data_buf);
break;
case HostCmd_CMD_802_11_SCAN:
ret = mwifiex_ret_802_11_scan(priv, resp);
adapter->curr_cmd->wait_q_enabled = false;
break;
case HostCmd_CMD_802_11_BG_SCAN_QUERY:
ret = mwifiex_ret_802_11_scan(priv, resp);
dev_dbg(adapter->dev,
"info: CMD_RESP: BG_SCAN result is ready!\n");
break;
case HostCmd_CMD_TXPWR_CFG:
ret = mwifiex_ret_tx_power_cfg(priv, resp);
break;
case HostCmd_CMD_802_11_PS_MODE_ENH:
ret = mwifiex_ret_enh_power_mode(priv, resp, data_buf);
break;
case HostCmd_CMD_802_11_HS_CFG_ENH:
ret = mwifiex_ret_802_11_hs_cfg(priv, resp);
break;
case HostCmd_CMD_802_11_ASSOCIATE:
ret = mwifiex_ret_802_11_associate(priv, resp);
break;
case HostCmd_CMD_802_11_DEAUTHENTICATE:
ret = mwifiex_ret_802_11_deauthenticate(priv, resp);
break;
case HostCmd_CMD_802_11_AD_HOC_START:
case HostCmd_CMD_802_11_AD_HOC_JOIN:
ret = mwifiex_ret_802_11_ad_hoc(priv, resp);
break;
case HostCmd_CMD_802_11_AD_HOC_STOP:
ret = mwifiex_ret_802_11_ad_hoc_stop(priv, resp);
break;
case HostCmd_CMD_802_11_GET_LOG:
ret = mwifiex_ret_get_log(priv, resp, data_buf);
break;
case HostCmd_CMD_RSSI_INFO:
ret = mwifiex_ret_802_11_rssi_info(priv, resp, data_buf);
break;
case HostCmd_CMD_802_11_SNMP_MIB:
ret = mwifiex_ret_802_11_snmp_mib(priv, resp, data_buf);
break;
case HostCmd_CMD_802_11_TX_RATE_QUERY:
ret = mwifiex_ret_802_11_tx_rate_query(priv, resp);
break;
case HostCmd_CMD_802_11_RF_CHANNEL:
ret = mwifiex_ret_802_11_rf_channel(priv, resp, data_buf);
break;
case HostCmd_CMD_VERSION_EXT:
ret = mwifiex_ret_ver_ext(priv, resp, data_buf);
break;
case HostCmd_CMD_FUNC_INIT:
case HostCmd_CMD_FUNC_SHUTDOWN:
break;
case HostCmd_CMD_802_11_KEY_MATERIAL:
ret = mwifiex_ret_802_11_key_material(priv, resp);
break;
case HostCmd_CMD_802_11D_DOMAIN_INFO:
ret = mwifiex_ret_802_11d_domain_info(priv, resp);
break;
case HostCmd_CMD_11N_ADDBA_REQ:
ret = mwifiex_ret_11n_addba_req(priv, resp);
break;
case HostCmd_CMD_11N_DELBA:
ret = mwifiex_ret_11n_delba(priv, resp);
break;
case HostCmd_CMD_11N_ADDBA_RSP:
ret = mwifiex_ret_11n_addba_resp(priv, resp);
break;
case HostCmd_CMD_RECONFIGURE_TX_BUFF:
adapter->tx_buf_size = (u16) le16_to_cpu(resp->params.
tx_buf.buff_size);
adapter->tx_buf_size = (adapter->tx_buf_size
/ MWIFIEX_SDIO_BLOCK_SIZE)
* MWIFIEX_SDIO_BLOCK_SIZE;
adapter->curr_tx_buf_size = adapter->tx_buf_size;
dev_dbg(adapter->dev,
"cmd: max_tx_buf_size=%d, tx_buf_size=%d\n",
adapter->max_tx_buf_size, adapter->tx_buf_size);
if (adapter->if_ops.update_mp_end_port)
adapter->if_ops.update_mp_end_port(adapter,
le16_to_cpu(resp->params.tx_buf.mp_end_port));
break;
case HostCmd_CMD_AMSDU_AGGR_CTRL:
ret = mwifiex_ret_amsdu_aggr_ctrl(resp, data_buf);
break;
case HostCmd_CMD_WMM_GET_STATUS:
ret = mwifiex_ret_wmm_get_status(priv, resp);
break;
case HostCmd_CMD_802_11_IBSS_COALESCING_STATUS:
ret = mwifiex_ret_ibss_coalescing_status(priv, resp);
break;
case HostCmd_CMD_MAC_REG_ACCESS:
case HostCmd_CMD_BBP_REG_ACCESS:
case HostCmd_CMD_RF_REG_ACCESS:
case HostCmd_CMD_PMIC_REG_ACCESS:
case HostCmd_CMD_CAU_REG_ACCESS:
case HostCmd_CMD_802_11_EEPROM_ACCESS:
ret = mwifiex_ret_reg_access(cmdresp_no, resp, data_buf);
break;
case HostCmd_CMD_SET_BSS_MODE:
break;
case HostCmd_CMD_11N_CFG:
ret = mwifiex_ret_11n_cfg(resp, data_buf);
break;
case HostCmd_CMD_PCIE_DESC_DETAILS:
break;
default:
dev_err(adapter->dev, "CMD_RESP: unknown cmd response %#x\n",
resp->command);
break;
}
return ret;
}
| gpl-2.0 |
mujeebulhasan/kernel | net/atm/pppoatm.c | 4806 | 11092 | /* net/atm/pppoatm.c - RFC2364 PPP over ATM/AAL5 */
/* Copyright 1999-2000 by Mitchell Blank Jr */
/* Based on clip.c; 1995-1999 by Werner Almesberger, EPFL LRC/ICA */
/* And on ppp_async.c; Copyright 1999 Paul Mackerras */
/* And help from Jens Axboe */
/*
* 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 provides the encapsulation and framing for sending
* and receiving PPP frames in ATM AAL5 PDUs.
*/
/*
* One shortcoming of this driver is that it does not comply with
* section 8 of RFC2364 - we are supposed to detect a change
* in encapsulation and immediately abort the connection (in order
* to avoid a black-hole being created if our peer loses state
* and changes encapsulation unilaterally. However, since the
* ppp_generic layer actually does the decapsulation, we need
* a way of notifying it when we _think_ there might be a problem)
* There's two cases:
* 1. LLC-encapsulation was missing when it was enabled. In
* this case, we should tell the upper layer "tear down
* this session if this skb looks ok to you"
* 2. LLC-encapsulation was present when it was disabled. Then
* we need to tell the upper layer "this packet may be
* ok, but if its in error tear down the session"
* These hooks are not yet available in ppp_generic
*/
#define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/atm.h>
#include <linux/atmdev.h>
#include <linux/capability.h>
#include <linux/ppp_defs.h>
#include <linux/ppp-ioctl.h>
#include <linux/ppp_channel.h>
#include <linux/atmppp.h>
#include "common.h"
enum pppoatm_encaps {
e_autodetect = PPPOATM_ENCAPS_AUTODETECT,
e_vc = PPPOATM_ENCAPS_VC,
e_llc = PPPOATM_ENCAPS_LLC,
};
struct pppoatm_vcc {
struct atm_vcc *atmvcc; /* VCC descriptor */
void (*old_push)(struct atm_vcc *, struct sk_buff *);
void (*old_pop)(struct atm_vcc *, struct sk_buff *);
/* keep old push/pop for detaching */
enum pppoatm_encaps encaps;
int flags; /* SC_COMP_PROT - compress protocol */
struct ppp_channel chan; /* interface to generic ppp layer */
struct tasklet_struct wakeup_tasklet;
};
/*
* Header used for LLC Encapsulated PPP (4 bytes) followed by the LCP protocol
* ID (0xC021) used in autodetection
*/
static const unsigned char pppllc[6] = { 0xFE, 0xFE, 0x03, 0xCF, 0xC0, 0x21 };
#define LLC_LEN (4)
static inline struct pppoatm_vcc *atmvcc_to_pvcc(const struct atm_vcc *atmvcc)
{
return (struct pppoatm_vcc *) (atmvcc->user_back);
}
static inline struct pppoatm_vcc *chan_to_pvcc(const struct ppp_channel *chan)
{
return (struct pppoatm_vcc *) (chan->private);
}
/*
* We can't do this directly from our _pop handler, since the ppp code
* doesn't want to be called in interrupt context, so we do it from
* a tasklet
*/
static void pppoatm_wakeup_sender(unsigned long arg)
{
ppp_output_wakeup((struct ppp_channel *) arg);
}
/*
* This gets called every time the ATM card has finished sending our
* skb. The ->old_pop will take care up normal atm flow control,
* but we also need to wake up the device if we blocked it
*/
static void pppoatm_pop(struct atm_vcc *atmvcc, struct sk_buff *skb)
{
struct pppoatm_vcc *pvcc = atmvcc_to_pvcc(atmvcc);
pvcc->old_pop(atmvcc, skb);
/*
* We don't really always want to do this since it's
* really inefficient - it would be much better if we could
* test if we had actually throttled the generic layer.
* Unfortunately then there would be a nasty SMP race where
* we could clear that flag just as we refuse another packet.
* For now we do the safe thing.
*/
tasklet_schedule(&pvcc->wakeup_tasklet);
}
/*
* Unbind from PPP - currently we only do this when closing the socket,
* but we could put this into an ioctl if need be
*/
static void pppoatm_unassign_vcc(struct atm_vcc *atmvcc)
{
struct pppoatm_vcc *pvcc;
pvcc = atmvcc_to_pvcc(atmvcc);
atmvcc->push = pvcc->old_push;
atmvcc->pop = pvcc->old_pop;
tasklet_kill(&pvcc->wakeup_tasklet);
ppp_unregister_channel(&pvcc->chan);
atmvcc->user_back = NULL;
kfree(pvcc);
/* Gee, I hope we have the big kernel lock here... */
module_put(THIS_MODULE);
}
/* Called when an AAL5 PDU comes in */
static void pppoatm_push(struct atm_vcc *atmvcc, struct sk_buff *skb)
{
struct pppoatm_vcc *pvcc = atmvcc_to_pvcc(atmvcc);
pr_debug("\n");
if (skb == NULL) { /* VCC was closed */
pr_debug("removing ATMPPP VCC %p\n", pvcc);
pppoatm_unassign_vcc(atmvcc);
atmvcc->push(atmvcc, NULL); /* Pass along bad news */
return;
}
atm_return(atmvcc, skb->truesize);
switch (pvcc->encaps) {
case e_llc:
if (skb->len < LLC_LEN ||
memcmp(skb->data, pppllc, LLC_LEN))
goto error;
skb_pull(skb, LLC_LEN);
break;
case e_autodetect:
if (pvcc->chan.ppp == NULL) { /* Not bound yet! */
kfree_skb(skb);
return;
}
if (skb->len >= sizeof(pppllc) &&
!memcmp(skb->data, pppllc, sizeof(pppllc))) {
pvcc->encaps = e_llc;
skb_pull(skb, LLC_LEN);
break;
}
if (skb->len >= (sizeof(pppllc) - LLC_LEN) &&
!memcmp(skb->data, &pppllc[LLC_LEN],
sizeof(pppllc) - LLC_LEN)) {
pvcc->encaps = e_vc;
pvcc->chan.mtu += LLC_LEN;
break;
}
pr_debug("Couldn't autodetect yet (skb: %02X %02X %02X %02X %02X %02X)\n",
skb->data[0], skb->data[1], skb->data[2],
skb->data[3], skb->data[4], skb->data[5]);
goto error;
case e_vc:
break;
}
ppp_input(&pvcc->chan, skb);
return;
error:
kfree_skb(skb);
ppp_input_error(&pvcc->chan, 0);
}
/*
* Called by the ppp_generic.c to send a packet - returns true if packet
* was accepted. If we return false, then it's our job to call
* ppp_output_wakeup(chan) when we're feeling more up to it.
* Note that in the ENOMEM case (as opposed to the !atm_may_send case)
* we should really drop the packet, but the generic layer doesn't
* support this yet. We just return 'DROP_PACKET' which we actually define
* as success, just to be clear what we're really doing.
*/
#define DROP_PACKET 1
static int pppoatm_send(struct ppp_channel *chan, struct sk_buff *skb)
{
struct pppoatm_vcc *pvcc = chan_to_pvcc(chan);
ATM_SKB(skb)->vcc = pvcc->atmvcc;
pr_debug("(skb=0x%p, vcc=0x%p)\n", skb, pvcc->atmvcc);
if (skb->data[0] == '\0' && (pvcc->flags & SC_COMP_PROT))
(void) skb_pull(skb, 1);
switch (pvcc->encaps) { /* LLC encapsulation needed */
case e_llc:
if (skb_headroom(skb) < LLC_LEN) {
struct sk_buff *n;
n = skb_realloc_headroom(skb, LLC_LEN);
if (n != NULL &&
!atm_may_send(pvcc->atmvcc, n->truesize)) {
kfree_skb(n);
goto nospace;
}
kfree_skb(skb);
skb = n;
if (skb == NULL)
return DROP_PACKET;
} else if (!atm_may_send(pvcc->atmvcc, skb->truesize))
goto nospace;
memcpy(skb_push(skb, LLC_LEN), pppllc, LLC_LEN);
break;
case e_vc:
if (!atm_may_send(pvcc->atmvcc, skb->truesize))
goto nospace;
break;
case e_autodetect:
pr_debug("Trying to send without setting encaps!\n");
kfree_skb(skb);
return 1;
}
atomic_add(skb->truesize, &sk_atm(ATM_SKB(skb)->vcc)->sk_wmem_alloc);
ATM_SKB(skb)->atm_options = ATM_SKB(skb)->vcc->atm_options;
pr_debug("atm_skb(%p)->vcc(%p)->dev(%p)\n",
skb, ATM_SKB(skb)->vcc, ATM_SKB(skb)->vcc->dev);
return ATM_SKB(skb)->vcc->send(ATM_SKB(skb)->vcc, skb)
? DROP_PACKET : 1;
nospace:
/*
* We don't have space to send this SKB now, but we might have
* already applied SC_COMP_PROT compression, so may need to undo
*/
if ((pvcc->flags & SC_COMP_PROT) && skb_headroom(skb) > 0 &&
skb->data[-1] == '\0')
(void) skb_push(skb, 1);
return 0;
}
/* This handles ioctls sent to the /dev/ppp interface */
static int pppoatm_devppp_ioctl(struct ppp_channel *chan, unsigned int cmd,
unsigned long arg)
{
switch (cmd) {
case PPPIOCGFLAGS:
return put_user(chan_to_pvcc(chan)->flags, (int __user *) arg)
? -EFAULT : 0;
case PPPIOCSFLAGS:
return get_user(chan_to_pvcc(chan)->flags, (int __user *) arg)
? -EFAULT : 0;
}
return -ENOTTY;
}
static const struct ppp_channel_ops pppoatm_ops = {
.start_xmit = pppoatm_send,
.ioctl = pppoatm_devppp_ioctl,
};
static int pppoatm_assign_vcc(struct atm_vcc *atmvcc, void __user *arg)
{
struct atm_backend_ppp be;
struct pppoatm_vcc *pvcc;
int err;
/*
* Each PPPoATM instance has its own tasklet - this is just a
* prototypical one used to initialize them
*/
static const DECLARE_TASKLET(tasklet_proto, pppoatm_wakeup_sender, 0);
if (copy_from_user(&be, arg, sizeof be))
return -EFAULT;
if (be.encaps != PPPOATM_ENCAPS_AUTODETECT &&
be.encaps != PPPOATM_ENCAPS_VC && be.encaps != PPPOATM_ENCAPS_LLC)
return -EINVAL;
pvcc = kzalloc(sizeof(*pvcc), GFP_KERNEL);
if (pvcc == NULL)
return -ENOMEM;
pvcc->atmvcc = atmvcc;
pvcc->old_push = atmvcc->push;
pvcc->old_pop = atmvcc->pop;
pvcc->encaps = (enum pppoatm_encaps) be.encaps;
pvcc->chan.private = pvcc;
pvcc->chan.ops = &pppoatm_ops;
pvcc->chan.mtu = atmvcc->qos.txtp.max_sdu - PPP_HDRLEN -
(be.encaps == e_vc ? 0 : LLC_LEN);
pvcc->wakeup_tasklet = tasklet_proto;
pvcc->wakeup_tasklet.data = (unsigned long) &pvcc->chan;
err = ppp_register_channel(&pvcc->chan);
if (err != 0) {
kfree(pvcc);
return err;
}
atmvcc->user_back = pvcc;
atmvcc->push = pppoatm_push;
atmvcc->pop = pppoatm_pop;
__module_get(THIS_MODULE);
/* re-process everything received between connection setup and
backend setup */
vcc_process_recv_queue(atmvcc);
return 0;
}
/*
* This handles ioctls actually performed on our vcc - we must return
* -ENOIOCTLCMD for any unrecognized ioctl
*/
static int pppoatm_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct atm_vcc *atmvcc = ATM_SD(sock);
void __user *argp = (void __user *)arg;
if (cmd != ATM_SETBACKEND && atmvcc->push != pppoatm_push)
return -ENOIOCTLCMD;
switch (cmd) {
case ATM_SETBACKEND: {
atm_backend_t b;
if (get_user(b, (atm_backend_t __user *) argp))
return -EFAULT;
if (b != ATM_BACKEND_PPP)
return -ENOIOCTLCMD;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return pppoatm_assign_vcc(atmvcc, argp);
}
case PPPIOCGCHAN:
return put_user(ppp_channel_index(&atmvcc_to_pvcc(atmvcc)->
chan), (int __user *) argp) ? -EFAULT : 0;
case PPPIOCGUNIT:
return put_user(ppp_unit_number(&atmvcc_to_pvcc(atmvcc)->
chan), (int __user *) argp) ? -EFAULT : 0;
}
return -ENOIOCTLCMD;
}
static struct atm_ioctl pppoatm_ioctl_ops = {
.owner = THIS_MODULE,
.ioctl = pppoatm_ioctl,
};
static int __init pppoatm_init(void)
{
register_atm_ioctl(&pppoatm_ioctl_ops);
return 0;
}
static void __exit pppoatm_exit(void)
{
deregister_atm_ioctl(&pppoatm_ioctl_ops);
}
module_init(pppoatm_init);
module_exit(pppoatm_exit);
MODULE_AUTHOR("Mitchell Blank Jr <mitch@sfgoth.com>");
MODULE_DESCRIPTION("RFC2364 PPP over ATM/AAL5");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ashhher3/linux | arch/arm/plat-samsung/platformdata.c | 4806 | 1517 | /* linux/arch/arm/plat-samsung/platformdata.c
*
* Copyright 2010 Ben Dooks <ben-linux <at> fluff.org>
*
* Helper for platform data setting
*
* 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/slab.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <plat/devs.h>
#include <plat/sdhci.h>
void __init *s3c_set_platdata(void *pd, size_t pdsize,
struct platform_device *pdev)
{
void *npd;
if (!pd) {
/* too early to use dev_name(), may not be registered */
printk(KERN_ERR "%s: no platform data supplied\n", pdev->name);
return NULL;
}
npd = kmemdup(pd, pdsize, GFP_KERNEL);
if (!npd) {
printk(KERN_ERR "%s: cannot clone platform data\n", pdev->name);
return NULL;
}
pdev->dev.platform_data = npd;
return npd;
}
void s3c_sdhci_set_platdata(struct s3c_sdhci_platdata *pd,
struct s3c_sdhci_platdata *set)
{
set->cd_type = pd->cd_type;
set->ext_cd_init = pd->ext_cd_init;
set->ext_cd_cleanup = pd->ext_cd_cleanup;
set->ext_cd_gpio = pd->ext_cd_gpio;
set->ext_cd_gpio_invert = pd->ext_cd_gpio_invert;
if (pd->max_width)
set->max_width = pd->max_width;
if (pd->cfg_gpio)
set->cfg_gpio = pd->cfg_gpio;
if (pd->host_caps)
set->host_caps |= pd->host_caps;
if (pd->host_caps2)
set->host_caps2 |= pd->host_caps2;
if (pd->pm_caps)
set->pm_caps |= pd->pm_caps;
}
| gpl-2.0 |
greg17477/kernel_franco_mako | drivers/net/ethernet/emulex/benet/be_ethtool.c | 4806 | 22196 | /*
* Copyright (C) 2005 - 2011 Emulex
* 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. The full GNU General
* Public License is included in this distribution in the file called COPYING.
*
* Contact Information:
* linux-drivers@emulex.com
*
* Emulex
* 3333 Susan Street
* Costa Mesa, CA 92626
*/
#include "be.h"
#include "be_cmds.h"
#include <linux/ethtool.h>
struct be_ethtool_stat {
char desc[ETH_GSTRING_LEN];
int type;
int size;
int offset;
};
enum {DRVSTAT_TX, DRVSTAT_RX, DRVSTAT};
#define FIELDINFO(_struct, field) FIELD_SIZEOF(_struct, field), \
offsetof(_struct, field)
#define DRVSTAT_TX_INFO(field) #field, DRVSTAT_TX,\
FIELDINFO(struct be_tx_stats, field)
#define DRVSTAT_RX_INFO(field) #field, DRVSTAT_RX,\
FIELDINFO(struct be_rx_stats, field)
#define DRVSTAT_INFO(field) #field, DRVSTAT,\
FIELDINFO(struct be_drv_stats, field)
static const struct be_ethtool_stat et_stats[] = {
{DRVSTAT_INFO(rx_crc_errors)},
{DRVSTAT_INFO(rx_alignment_symbol_errors)},
{DRVSTAT_INFO(rx_pause_frames)},
{DRVSTAT_INFO(rx_control_frames)},
/* Received packets dropped when the Ethernet length field
* is not equal to the actual Ethernet data length.
*/
{DRVSTAT_INFO(rx_in_range_errors)},
/* Received packets dropped when their length field is >= 1501 bytes
* and <= 1535 bytes.
*/
{DRVSTAT_INFO(rx_out_range_errors)},
/* Received packets dropped when they are longer than 9216 bytes */
{DRVSTAT_INFO(rx_frame_too_long)},
/* Received packets dropped when they don't pass the unicast or
* multicast address filtering.
*/
{DRVSTAT_INFO(rx_address_mismatch_drops)},
/* Received packets dropped when IP packet length field is less than
* the IP header length field.
*/
{DRVSTAT_INFO(rx_dropped_too_small)},
/* Received packets dropped when IP length field is greater than
* the actual packet length.
*/
{DRVSTAT_INFO(rx_dropped_too_short)},
/* Received packets dropped when the IP header length field is less
* than 5.
*/
{DRVSTAT_INFO(rx_dropped_header_too_small)},
/* Received packets dropped when the TCP header length field is less
* than 5 or the TCP header length + IP header length is more
* than IP packet length.
*/
{DRVSTAT_INFO(rx_dropped_tcp_length)},
{DRVSTAT_INFO(rx_dropped_runt)},
/* Number of received packets dropped when a fifo for descriptors going
* into the packet demux block overflows. In normal operation, this
* fifo must never overflow.
*/
{DRVSTAT_INFO(rxpp_fifo_overflow_drop)},
{DRVSTAT_INFO(rx_input_fifo_overflow_drop)},
{DRVSTAT_INFO(rx_ip_checksum_errs)},
{DRVSTAT_INFO(rx_tcp_checksum_errs)},
{DRVSTAT_INFO(rx_udp_checksum_errs)},
{DRVSTAT_INFO(tx_pauseframes)},
{DRVSTAT_INFO(tx_controlframes)},
{DRVSTAT_INFO(rx_priority_pause_frames)},
/* Received packets dropped when an internal fifo going into
* main packet buffer tank (PMEM) overflows.
*/
{DRVSTAT_INFO(pmem_fifo_overflow_drop)},
{DRVSTAT_INFO(jabber_events)},
/* Received packets dropped due to lack of available HW packet buffers
* used to temporarily hold the received packets.
*/
{DRVSTAT_INFO(rx_drops_no_pbuf)},
/* Received packets dropped due to input receive buffer
* descriptor fifo overflowing.
*/
{DRVSTAT_INFO(rx_drops_no_erx_descr)},
/* Packets dropped because the internal FIFO to the offloaded TCP
* receive processing block is full. This could happen only for
* offloaded iSCSI or FCoE trarffic.
*/
{DRVSTAT_INFO(rx_drops_no_tpre_descr)},
/* Received packets dropped when they need more than 8
* receive buffers. This cannot happen as the driver configures
* 2048 byte receive buffers.
*/
{DRVSTAT_INFO(rx_drops_too_many_frags)},
{DRVSTAT_INFO(forwarded_packets)},
/* Received packets dropped when the frame length
* is more than 9018 bytes
*/
{DRVSTAT_INFO(rx_drops_mtu)},
/* Number of packets dropped due to random early drop function */
{DRVSTAT_INFO(eth_red_drops)},
{DRVSTAT_INFO(be_on_die_temperature)}
};
#define ETHTOOL_STATS_NUM ARRAY_SIZE(et_stats)
/* Stats related to multi RX queues: get_stats routine assumes bytes, pkts
* are first and second members respectively.
*/
static const struct be_ethtool_stat et_rx_stats[] = {
{DRVSTAT_RX_INFO(rx_bytes)},/* If moving this member see above note */
{DRVSTAT_RX_INFO(rx_pkts)}, /* If moving this member see above note */
{DRVSTAT_RX_INFO(rx_compl)},
{DRVSTAT_RX_INFO(rx_mcast_pkts)},
/* Number of page allocation failures while posting receive buffers
* to HW.
*/
{DRVSTAT_RX_INFO(rx_post_fail)},
/* Recevied packets dropped due to skb allocation failure */
{DRVSTAT_RX_INFO(rx_drops_no_skbs)},
/* Received packets dropped due to lack of available fetched buffers
* posted by the driver.
*/
{DRVSTAT_RX_INFO(rx_drops_no_frags)}
};
#define ETHTOOL_RXSTATS_NUM (ARRAY_SIZE(et_rx_stats))
/* Stats related to multi TX queues: get_stats routine assumes compl is the
* first member
*/
static const struct be_ethtool_stat et_tx_stats[] = {
{DRVSTAT_TX_INFO(tx_compl)}, /* If moving this member see above note */
{DRVSTAT_TX_INFO(tx_bytes)},
{DRVSTAT_TX_INFO(tx_pkts)},
/* Number of skbs queued for trasmission by the driver */
{DRVSTAT_TX_INFO(tx_reqs)},
/* Number of TX work request blocks DMAed to HW */
{DRVSTAT_TX_INFO(tx_wrbs)},
/* Number of times the TX queue was stopped due to lack
* of spaces in the TXQ.
*/
{DRVSTAT_TX_INFO(tx_stops)}
};
#define ETHTOOL_TXSTATS_NUM (ARRAY_SIZE(et_tx_stats))
static const char et_self_tests[][ETH_GSTRING_LEN] = {
"MAC Loopback test",
"PHY Loopback test",
"External Loopback test",
"DDR DMA test",
"Link test"
};
#define ETHTOOL_TESTS_NUM ARRAY_SIZE(et_self_tests)
#define BE_MAC_LOOPBACK 0x0
#define BE_PHY_LOOPBACK 0x1
#define BE_ONE_PORT_EXT_LOOPBACK 0x2
#define BE_NO_LOOPBACK 0xff
static void be_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct be_adapter *adapter = netdev_priv(netdev);
char fw_on_flash[FW_VER_LEN];
memset(fw_on_flash, 0 , sizeof(fw_on_flash));
be_cmd_get_fw_ver(adapter, adapter->fw_ver, fw_on_flash);
strlcpy(drvinfo->driver, DRV_NAME, sizeof(drvinfo->driver));
strlcpy(drvinfo->version, DRV_VER, sizeof(drvinfo->version));
strncpy(drvinfo->fw_version, adapter->fw_ver, FW_VER_LEN);
if (memcmp(adapter->fw_ver, fw_on_flash, FW_VER_LEN) != 0) {
strcat(drvinfo->fw_version, " [");
strcat(drvinfo->fw_version, fw_on_flash);
strcat(drvinfo->fw_version, "]");
}
strlcpy(drvinfo->bus_info, pci_name(adapter->pdev),
sizeof(drvinfo->bus_info));
drvinfo->testinfo_len = 0;
drvinfo->regdump_len = 0;
drvinfo->eedump_len = 0;
}
static u32
lancer_cmd_get_file_len(struct be_adapter *adapter, u8 *file_name)
{
u32 data_read = 0, eof;
u8 addn_status;
struct be_dma_mem data_len_cmd;
int status;
memset(&data_len_cmd, 0, sizeof(data_len_cmd));
/* data_offset and data_size should be 0 to get reg len */
status = lancer_cmd_read_object(adapter, &data_len_cmd, 0, 0,
file_name, &data_read, &eof, &addn_status);
return data_read;
}
static int
lancer_cmd_read_file(struct be_adapter *adapter, u8 *file_name,
u32 buf_len, void *buf)
{
struct be_dma_mem read_cmd;
u32 read_len = 0, total_read_len = 0, chunk_size;
u32 eof = 0;
u8 addn_status;
int status = 0;
read_cmd.size = LANCER_READ_FILE_CHUNK;
read_cmd.va = pci_alloc_consistent(adapter->pdev, read_cmd.size,
&read_cmd.dma);
if (!read_cmd.va) {
dev_err(&adapter->pdev->dev,
"Memory allocation failure while reading dump\n");
return -ENOMEM;
}
while ((total_read_len < buf_len) && !eof) {
chunk_size = min_t(u32, (buf_len - total_read_len),
LANCER_READ_FILE_CHUNK);
chunk_size = ALIGN(chunk_size, 4);
status = lancer_cmd_read_object(adapter, &read_cmd, chunk_size,
total_read_len, file_name, &read_len,
&eof, &addn_status);
if (!status) {
memcpy(buf + total_read_len, read_cmd.va, read_len);
total_read_len += read_len;
eof &= LANCER_READ_FILE_EOF_MASK;
} else {
status = -EIO;
break;
}
}
pci_free_consistent(adapter->pdev, read_cmd.size, read_cmd.va,
read_cmd.dma);
return status;
}
static int
be_get_reg_len(struct net_device *netdev)
{
struct be_adapter *adapter = netdev_priv(netdev);
u32 log_size = 0;
if (be_physfn(adapter)) {
if (lancer_chip(adapter))
log_size = lancer_cmd_get_file_len(adapter,
LANCER_FW_DUMP_FILE);
else
be_cmd_get_reg_len(adapter, &log_size);
}
return log_size;
}
static void
be_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *buf)
{
struct be_adapter *adapter = netdev_priv(netdev);
if (be_physfn(adapter)) {
memset(buf, 0, regs->len);
if (lancer_chip(adapter))
lancer_cmd_read_file(adapter, LANCER_FW_DUMP_FILE,
regs->len, buf);
else
be_cmd_get_regs(adapter, regs->len, buf);
}
}
static int be_get_coalesce(struct net_device *netdev,
struct ethtool_coalesce *et)
{
struct be_adapter *adapter = netdev_priv(netdev);
struct be_eq_obj *eqo = &adapter->eq_obj[0];
et->rx_coalesce_usecs = eqo->cur_eqd;
et->rx_coalesce_usecs_high = eqo->max_eqd;
et->rx_coalesce_usecs_low = eqo->min_eqd;
et->tx_coalesce_usecs = eqo->cur_eqd;
et->tx_coalesce_usecs_high = eqo->max_eqd;
et->tx_coalesce_usecs_low = eqo->min_eqd;
et->use_adaptive_rx_coalesce = eqo->enable_aic;
et->use_adaptive_tx_coalesce = eqo->enable_aic;
return 0;
}
/* TX attributes are ignored. Only RX attributes are considered
* eqd cmd is issued in the worker thread.
*/
static int be_set_coalesce(struct net_device *netdev,
struct ethtool_coalesce *et)
{
struct be_adapter *adapter = netdev_priv(netdev);
struct be_eq_obj *eqo;
int i;
for_all_evt_queues(adapter, eqo, i) {
eqo->enable_aic = et->use_adaptive_rx_coalesce;
eqo->max_eqd = min(et->rx_coalesce_usecs_high, BE_MAX_EQD);
eqo->min_eqd = min(et->rx_coalesce_usecs_low, eqo->max_eqd);
eqo->eqd = et->rx_coalesce_usecs;
}
return 0;
}
static void
be_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats, uint64_t *data)
{
struct be_adapter *adapter = netdev_priv(netdev);
struct be_rx_obj *rxo;
struct be_tx_obj *txo;
void *p;
unsigned int i, j, base = 0, start;
for (i = 0; i < ETHTOOL_STATS_NUM; i++) {
p = (u8 *)&adapter->drv_stats + et_stats[i].offset;
data[i] = *(u32 *)p;
}
base += ETHTOOL_STATS_NUM;
for_all_rx_queues(adapter, rxo, j) {
struct be_rx_stats *stats = rx_stats(rxo);
do {
start = u64_stats_fetch_begin_bh(&stats->sync);
data[base] = stats->rx_bytes;
data[base + 1] = stats->rx_pkts;
} while (u64_stats_fetch_retry_bh(&stats->sync, start));
for (i = 2; i < ETHTOOL_RXSTATS_NUM; i++) {
p = (u8 *)stats + et_rx_stats[i].offset;
data[base + i] = *(u32 *)p;
}
base += ETHTOOL_RXSTATS_NUM;
}
for_all_tx_queues(adapter, txo, j) {
struct be_tx_stats *stats = tx_stats(txo);
do {
start = u64_stats_fetch_begin_bh(&stats->sync_compl);
data[base] = stats->tx_compl;
} while (u64_stats_fetch_retry_bh(&stats->sync_compl, start));
do {
start = u64_stats_fetch_begin_bh(&stats->sync);
for (i = 1; i < ETHTOOL_TXSTATS_NUM; i++) {
p = (u8 *)stats + et_tx_stats[i].offset;
data[base + i] =
(et_tx_stats[i].size == sizeof(u64)) ?
*(u64 *)p : *(u32 *)p;
}
} while (u64_stats_fetch_retry_bh(&stats->sync, start));
base += ETHTOOL_TXSTATS_NUM;
}
}
static void
be_get_stat_strings(struct net_device *netdev, uint32_t stringset,
uint8_t *data)
{
struct be_adapter *adapter = netdev_priv(netdev);
int i, j;
switch (stringset) {
case ETH_SS_STATS:
for (i = 0; i < ETHTOOL_STATS_NUM; i++) {
memcpy(data, et_stats[i].desc, ETH_GSTRING_LEN);
data += ETH_GSTRING_LEN;
}
for (i = 0; i < adapter->num_rx_qs; i++) {
for (j = 0; j < ETHTOOL_RXSTATS_NUM; j++) {
sprintf(data, "rxq%d: %s", i,
et_rx_stats[j].desc);
data += ETH_GSTRING_LEN;
}
}
for (i = 0; i < adapter->num_tx_qs; i++) {
for (j = 0; j < ETHTOOL_TXSTATS_NUM; j++) {
sprintf(data, "txq%d: %s", i,
et_tx_stats[j].desc);
data += ETH_GSTRING_LEN;
}
}
break;
case ETH_SS_TEST:
for (i = 0; i < ETHTOOL_TESTS_NUM; i++) {
memcpy(data, et_self_tests[i], ETH_GSTRING_LEN);
data += ETH_GSTRING_LEN;
}
break;
}
}
static int be_get_sset_count(struct net_device *netdev, int stringset)
{
struct be_adapter *adapter = netdev_priv(netdev);
switch (stringset) {
case ETH_SS_TEST:
return ETHTOOL_TESTS_NUM;
case ETH_SS_STATS:
return ETHTOOL_STATS_NUM +
adapter->num_rx_qs * ETHTOOL_RXSTATS_NUM +
adapter->num_tx_qs * ETHTOOL_TXSTATS_NUM;
default:
return -EINVAL;
}
}
static int be_get_settings(struct net_device *netdev, struct ethtool_cmd *ecmd)
{
struct be_adapter *adapter = netdev_priv(netdev);
struct be_phy_info phy_info;
u8 mac_speed = 0;
u16 link_speed = 0;
u8 link_status;
int status;
if ((adapter->link_speed < 0) || (!(netdev->flags & IFF_UP))) {
status = be_cmd_link_status_query(adapter, &mac_speed,
&link_speed, &link_status, 0);
if (!status)
be_link_status_update(adapter, link_status);
/* link_speed is in units of 10 Mbps */
if (link_speed) {
ethtool_cmd_speed_set(ecmd, link_speed*10);
} else {
switch (mac_speed) {
case PHY_LINK_SPEED_10MBPS:
ethtool_cmd_speed_set(ecmd, SPEED_10);
break;
case PHY_LINK_SPEED_100MBPS:
ethtool_cmd_speed_set(ecmd, SPEED_100);
break;
case PHY_LINK_SPEED_1GBPS:
ethtool_cmd_speed_set(ecmd, SPEED_1000);
break;
case PHY_LINK_SPEED_10GBPS:
ethtool_cmd_speed_set(ecmd, SPEED_10000);
break;
case PHY_LINK_SPEED_ZERO:
ethtool_cmd_speed_set(ecmd, 0);
break;
}
}
status = be_cmd_get_phy_info(adapter, &phy_info);
if (!status) {
switch (phy_info.interface_type) {
case PHY_TYPE_XFP_10GB:
case PHY_TYPE_SFP_1GB:
case PHY_TYPE_SFP_PLUS_10GB:
ecmd->port = PORT_FIBRE;
break;
default:
ecmd->port = PORT_TP;
break;
}
switch (phy_info.interface_type) {
case PHY_TYPE_KR_10GB:
case PHY_TYPE_KX4_10GB:
ecmd->autoneg = AUTONEG_ENABLE;
ecmd->transceiver = XCVR_INTERNAL;
break;
default:
ecmd->autoneg = AUTONEG_DISABLE;
ecmd->transceiver = XCVR_EXTERNAL;
break;
}
}
/* Save for future use */
adapter->link_speed = ethtool_cmd_speed(ecmd);
adapter->port_type = ecmd->port;
adapter->transceiver = ecmd->transceiver;
adapter->autoneg = ecmd->autoneg;
} else {
ethtool_cmd_speed_set(ecmd, adapter->link_speed);
ecmd->port = adapter->port_type;
ecmd->transceiver = adapter->transceiver;
ecmd->autoneg = adapter->autoneg;
}
ecmd->duplex = DUPLEX_FULL;
ecmd->phy_address = adapter->port_num;
switch (ecmd->port) {
case PORT_FIBRE:
ecmd->supported = (SUPPORTED_10000baseT_Full | SUPPORTED_FIBRE);
break;
case PORT_TP:
ecmd->supported = (SUPPORTED_10000baseT_Full | SUPPORTED_TP);
break;
case PORT_AUI:
ecmd->supported = (SUPPORTED_10000baseT_Full | SUPPORTED_AUI);
break;
}
if (ecmd->autoneg) {
ecmd->supported |= SUPPORTED_1000baseT_Full;
ecmd->supported |= SUPPORTED_Autoneg;
ecmd->advertising |= (ADVERTISED_10000baseT_Full |
ADVERTISED_1000baseT_Full);
}
return 0;
}
static void be_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct be_adapter *adapter = netdev_priv(netdev);
ring->rx_max_pending = ring->rx_pending = adapter->rx_obj[0].q.len;
ring->tx_max_pending = ring->tx_pending = adapter->tx_obj[0].q.len;
}
static void
be_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *ecmd)
{
struct be_adapter *adapter = netdev_priv(netdev);
be_cmd_get_flow_control(adapter, &ecmd->tx_pause, &ecmd->rx_pause);
ecmd->autoneg = 0;
}
static int
be_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *ecmd)
{
struct be_adapter *adapter = netdev_priv(netdev);
int status;
if (ecmd->autoneg != 0)
return -EINVAL;
adapter->tx_fc = ecmd->tx_pause;
adapter->rx_fc = ecmd->rx_pause;
status = be_cmd_set_flow_control(adapter,
adapter->tx_fc, adapter->rx_fc);
if (status)
dev_warn(&adapter->pdev->dev, "Pause param set failed.\n");
return status;
}
static int
be_set_phys_id(struct net_device *netdev,
enum ethtool_phys_id_state state)
{
struct be_adapter *adapter = netdev_priv(netdev);
switch (state) {
case ETHTOOL_ID_ACTIVE:
be_cmd_get_beacon_state(adapter, adapter->hba_port_num,
&adapter->beacon_state);
return 1; /* cycle on/off once per second */
case ETHTOOL_ID_ON:
be_cmd_set_beacon_state(adapter, adapter->hba_port_num, 0, 0,
BEACON_STATE_ENABLED);
break;
case ETHTOOL_ID_OFF:
be_cmd_set_beacon_state(adapter, adapter->hba_port_num, 0, 0,
BEACON_STATE_DISABLED);
break;
case ETHTOOL_ID_INACTIVE:
be_cmd_set_beacon_state(adapter, adapter->hba_port_num, 0, 0,
adapter->beacon_state);
}
return 0;
}
static void
be_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct be_adapter *adapter = netdev_priv(netdev);
if (be_is_wol_supported(adapter)) {
wol->supported |= WAKE_MAGIC;
wol->wolopts |= WAKE_MAGIC;
} else
wol->wolopts = 0;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int
be_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct be_adapter *adapter = netdev_priv(netdev);
if (wol->wolopts & ~WAKE_MAGIC)
return -EOPNOTSUPP;
if (!be_is_wol_supported(adapter)) {
dev_warn(&adapter->pdev->dev, "WOL not supported\n");
return -EOPNOTSUPP;
}
if (wol->wolopts & WAKE_MAGIC)
adapter->wol = true;
else
adapter->wol = false;
return 0;
}
static int
be_test_ddr_dma(struct be_adapter *adapter)
{
int ret, i;
struct be_dma_mem ddrdma_cmd;
static const u64 pattern[2] = {
0x5a5a5a5a5a5a5a5aULL, 0xa5a5a5a5a5a5a5a5ULL
};
ddrdma_cmd.size = sizeof(struct be_cmd_req_ddrdma_test);
ddrdma_cmd.va = dma_alloc_coherent(&adapter->pdev->dev, ddrdma_cmd.size,
&ddrdma_cmd.dma, GFP_KERNEL);
if (!ddrdma_cmd.va) {
dev_err(&adapter->pdev->dev, "Memory allocation failure\n");
return -ENOMEM;
}
for (i = 0; i < 2; i++) {
ret = be_cmd_ddr_dma_test(adapter, pattern[i],
4096, &ddrdma_cmd);
if (ret != 0)
goto err;
}
err:
dma_free_coherent(&adapter->pdev->dev, ddrdma_cmd.size, ddrdma_cmd.va,
ddrdma_cmd.dma);
return ret;
}
static u64 be_loopback_test(struct be_adapter *adapter, u8 loopback_type,
u64 *status)
{
be_cmd_set_loopback(adapter, adapter->hba_port_num,
loopback_type, 1);
*status = be_cmd_loopback_test(adapter, adapter->hba_port_num,
loopback_type, 1500,
2, 0xabc);
be_cmd_set_loopback(adapter, adapter->hba_port_num,
BE_NO_LOOPBACK, 1);
return *status;
}
static void
be_self_test(struct net_device *netdev, struct ethtool_test *test, u64 *data)
{
struct be_adapter *adapter = netdev_priv(netdev);
u8 mac_speed = 0;
u16 qos_link_speed = 0;
memset(data, 0, sizeof(u64) * ETHTOOL_TESTS_NUM);
if (test->flags & ETH_TEST_FL_OFFLINE) {
if (be_loopback_test(adapter, BE_MAC_LOOPBACK,
&data[0]) != 0) {
test->flags |= ETH_TEST_FL_FAILED;
}
if (be_loopback_test(adapter, BE_PHY_LOOPBACK,
&data[1]) != 0) {
test->flags |= ETH_TEST_FL_FAILED;
}
if (be_loopback_test(adapter, BE_ONE_PORT_EXT_LOOPBACK,
&data[2]) != 0) {
test->flags |= ETH_TEST_FL_FAILED;
}
}
if (be_test_ddr_dma(adapter) != 0) {
data[3] = 1;
test->flags |= ETH_TEST_FL_FAILED;
}
if (be_cmd_link_status_query(adapter, &mac_speed,
&qos_link_speed, NULL, 0) != 0) {
test->flags |= ETH_TEST_FL_FAILED;
data[4] = -1;
} else if (!mac_speed) {
test->flags |= ETH_TEST_FL_FAILED;
data[4] = 1;
}
}
static int
be_do_flash(struct net_device *netdev, struct ethtool_flash *efl)
{
struct be_adapter *adapter = netdev_priv(netdev);
return be_load_fw(adapter, efl->data);
}
static int
be_get_eeprom_len(struct net_device *netdev)
{
struct be_adapter *adapter = netdev_priv(netdev);
if (lancer_chip(adapter)) {
if (be_physfn(adapter))
return lancer_cmd_get_file_len(adapter,
LANCER_VPD_PF_FILE);
else
return lancer_cmd_get_file_len(adapter,
LANCER_VPD_VF_FILE);
} else {
return BE_READ_SEEPROM_LEN;
}
}
static int
be_read_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom,
uint8_t *data)
{
struct be_adapter *adapter = netdev_priv(netdev);
struct be_dma_mem eeprom_cmd;
struct be_cmd_resp_seeprom_read *resp;
int status;
if (!eeprom->len)
return -EINVAL;
if (lancer_chip(adapter)) {
if (be_physfn(adapter))
return lancer_cmd_read_file(adapter, LANCER_VPD_PF_FILE,
eeprom->len, data);
else
return lancer_cmd_read_file(adapter, LANCER_VPD_VF_FILE,
eeprom->len, data);
}
eeprom->magic = BE_VENDOR_ID | (adapter->pdev->device<<16);
memset(&eeprom_cmd, 0, sizeof(struct be_dma_mem));
eeprom_cmd.size = sizeof(struct be_cmd_req_seeprom_read);
eeprom_cmd.va = dma_alloc_coherent(&adapter->pdev->dev, eeprom_cmd.size,
&eeprom_cmd.dma, GFP_KERNEL);
if (!eeprom_cmd.va) {
dev_err(&adapter->pdev->dev,
"Memory allocation failure. Could not read eeprom\n");
return -ENOMEM;
}
status = be_cmd_get_seeprom_data(adapter, &eeprom_cmd);
if (!status) {
resp = eeprom_cmd.va;
memcpy(data, resp->seeprom_data + eeprom->offset, eeprom->len);
}
dma_free_coherent(&adapter->pdev->dev, eeprom_cmd.size, eeprom_cmd.va,
eeprom_cmd.dma);
return status;
}
const struct ethtool_ops be_ethtool_ops = {
.get_settings = be_get_settings,
.get_drvinfo = be_get_drvinfo,
.get_wol = be_get_wol,
.set_wol = be_set_wol,
.get_link = ethtool_op_get_link,
.get_eeprom_len = be_get_eeprom_len,
.get_eeprom = be_read_eeprom,
.get_coalesce = be_get_coalesce,
.set_coalesce = be_set_coalesce,
.get_ringparam = be_get_ringparam,
.get_pauseparam = be_get_pauseparam,
.set_pauseparam = be_set_pauseparam,
.get_strings = be_get_stat_strings,
.set_phys_id = be_set_phys_id,
.get_sset_count = be_get_sset_count,
.get_ethtool_stats = be_get_ethtool_stats,
.get_regs_len = be_get_reg_len,
.get_regs = be_get_regs,
.flash_device = be_do_flash,
.self_test = be_self_test,
};
| gpl-2.0 |
boa19861105/android_442_KitKat_kernel_htc_B2_UHL | tools/perf/builtin-lock.c | 4806 | 23578 | #include "builtin.h"
#include "perf.h"
#include "util/util.h"
#include "util/cache.h"
#include "util/symbol.h"
#include "util/thread.h"
#include "util/header.h"
#include "util/parse-options.h"
#include "util/trace-event.h"
#include "util/debug.h"
#include "util/session.h"
#include "util/tool.h"
#include <sys/types.h>
#include <sys/prctl.h>
#include <semaphore.h>
#include <pthread.h>
#include <math.h>
#include <limits.h>
#include <linux/list.h>
#include <linux/hash.h>
static struct perf_session *session;
/* based on kernel/lockdep.c */
#define LOCKHASH_BITS 12
#define LOCKHASH_SIZE (1UL << LOCKHASH_BITS)
static struct list_head lockhash_table[LOCKHASH_SIZE];
#define __lockhashfn(key) hash_long((unsigned long)key, LOCKHASH_BITS)
#define lockhashentry(key) (lockhash_table + __lockhashfn((key)))
struct lock_stat {
struct list_head hash_entry;
struct rb_node rb; /* used for sorting */
/*
* FIXME: raw_field_value() returns unsigned long long,
* so address of lockdep_map should be dealed as 64bit.
* Is there more better solution?
*/
void *addr; /* address of lockdep_map, used as ID */
char *name; /* for strcpy(), we cannot use const */
unsigned int nr_acquire;
unsigned int nr_acquired;
unsigned int nr_contended;
unsigned int nr_release;
unsigned int nr_readlock;
unsigned int nr_trylock;
/* these times are in nano sec. */
u64 wait_time_total;
u64 wait_time_min;
u64 wait_time_max;
int discard; /* flag of blacklist */
};
/*
* States of lock_seq_stat
*
* UNINITIALIZED is required for detecting first event of acquire.
* As the nature of lock events, there is no guarantee
* that the first event for the locks are acquire,
* it can be acquired, contended or release.
*/
#define SEQ_STATE_UNINITIALIZED 0 /* initial state */
#define SEQ_STATE_RELEASED 1
#define SEQ_STATE_ACQUIRING 2
#define SEQ_STATE_ACQUIRED 3
#define SEQ_STATE_READ_ACQUIRED 4
#define SEQ_STATE_CONTENDED 5
/*
* MAX_LOCK_DEPTH
* Imported from include/linux/sched.h.
* Should this be synchronized?
*/
#define MAX_LOCK_DEPTH 48
/*
* struct lock_seq_stat:
* Place to put on state of one lock sequence
* 1) acquire -> acquired -> release
* 2) acquire -> contended -> acquired -> release
* 3) acquire (with read or try) -> release
* 4) Are there other patterns?
*/
struct lock_seq_stat {
struct list_head list;
int state;
u64 prev_event_time;
void *addr;
int read_count;
};
struct thread_stat {
struct rb_node rb;
u32 tid;
struct list_head seq_list;
};
static struct rb_root thread_stats;
static struct thread_stat *thread_stat_find(u32 tid)
{
struct rb_node *node;
struct thread_stat *st;
node = thread_stats.rb_node;
while (node) {
st = container_of(node, struct thread_stat, rb);
if (st->tid == tid)
return st;
else if (tid < st->tid)
node = node->rb_left;
else
node = node->rb_right;
}
return NULL;
}
static void thread_stat_insert(struct thread_stat *new)
{
struct rb_node **rb = &thread_stats.rb_node;
struct rb_node *parent = NULL;
struct thread_stat *p;
while (*rb) {
p = container_of(*rb, struct thread_stat, rb);
parent = *rb;
if (new->tid < p->tid)
rb = &(*rb)->rb_left;
else if (new->tid > p->tid)
rb = &(*rb)->rb_right;
else
BUG_ON("inserting invalid thread_stat\n");
}
rb_link_node(&new->rb, parent, rb);
rb_insert_color(&new->rb, &thread_stats);
}
static struct thread_stat *thread_stat_findnew_after_first(u32 tid)
{
struct thread_stat *st;
st = thread_stat_find(tid);
if (st)
return st;
st = zalloc(sizeof(struct thread_stat));
if (!st)
die("memory allocation failed\n");
st->tid = tid;
INIT_LIST_HEAD(&st->seq_list);
thread_stat_insert(st);
return st;
}
static struct thread_stat *thread_stat_findnew_first(u32 tid);
static struct thread_stat *(*thread_stat_findnew)(u32 tid) =
thread_stat_findnew_first;
static struct thread_stat *thread_stat_findnew_first(u32 tid)
{
struct thread_stat *st;
st = zalloc(sizeof(struct thread_stat));
if (!st)
die("memory allocation failed\n");
st->tid = tid;
INIT_LIST_HEAD(&st->seq_list);
rb_link_node(&st->rb, NULL, &thread_stats.rb_node);
rb_insert_color(&st->rb, &thread_stats);
thread_stat_findnew = thread_stat_findnew_after_first;
return st;
}
/* build simple key function one is bigger than two */
#define SINGLE_KEY(member) \
static int lock_stat_key_ ## member(struct lock_stat *one, \
struct lock_stat *two) \
{ \
return one->member > two->member; \
}
SINGLE_KEY(nr_acquired)
SINGLE_KEY(nr_contended)
SINGLE_KEY(wait_time_total)
SINGLE_KEY(wait_time_max)
static int lock_stat_key_wait_time_min(struct lock_stat *one,
struct lock_stat *two)
{
u64 s1 = one->wait_time_min;
u64 s2 = two->wait_time_min;
if (s1 == ULLONG_MAX)
s1 = 0;
if (s2 == ULLONG_MAX)
s2 = 0;
return s1 > s2;
}
struct lock_key {
/*
* name: the value for specify by user
* this should be simpler than raw name of member
* e.g. nr_acquired -> acquired, wait_time_total -> wait_total
*/
const char *name;
int (*key)(struct lock_stat*, struct lock_stat*);
};
static const char *sort_key = "acquired";
static int (*compare)(struct lock_stat *, struct lock_stat *);
static struct rb_root result; /* place to store sorted data */
#define DEF_KEY_LOCK(name, fn_suffix) \
{ #name, lock_stat_key_ ## fn_suffix }
struct lock_key keys[] = {
DEF_KEY_LOCK(acquired, nr_acquired),
DEF_KEY_LOCK(contended, nr_contended),
DEF_KEY_LOCK(wait_total, wait_time_total),
DEF_KEY_LOCK(wait_min, wait_time_min),
DEF_KEY_LOCK(wait_max, wait_time_max),
/* extra comparisons much complicated should be here */
{ NULL, NULL }
};
static void select_key(void)
{
int i;
for (i = 0; keys[i].name; i++) {
if (!strcmp(keys[i].name, sort_key)) {
compare = keys[i].key;
return;
}
}
die("Unknown compare key:%s\n", sort_key);
}
static void insert_to_result(struct lock_stat *st,
int (*bigger)(struct lock_stat *, struct lock_stat *))
{
struct rb_node **rb = &result.rb_node;
struct rb_node *parent = NULL;
struct lock_stat *p;
while (*rb) {
p = container_of(*rb, struct lock_stat, rb);
parent = *rb;
if (bigger(st, p))
rb = &(*rb)->rb_left;
else
rb = &(*rb)->rb_right;
}
rb_link_node(&st->rb, parent, rb);
rb_insert_color(&st->rb, &result);
}
/* returns left most element of result, and erase it */
static struct lock_stat *pop_from_result(void)
{
struct rb_node *node = result.rb_node;
if (!node)
return NULL;
while (node->rb_left)
node = node->rb_left;
rb_erase(node, &result);
return container_of(node, struct lock_stat, rb);
}
static struct lock_stat *lock_stat_findnew(void *addr, const char *name)
{
struct list_head *entry = lockhashentry(addr);
struct lock_stat *ret, *new;
list_for_each_entry(ret, entry, hash_entry) {
if (ret->addr == addr)
return ret;
}
new = zalloc(sizeof(struct lock_stat));
if (!new)
goto alloc_failed;
new->addr = addr;
new->name = zalloc(sizeof(char) * strlen(name) + 1);
if (!new->name)
goto alloc_failed;
strcpy(new->name, name);
new->wait_time_min = ULLONG_MAX;
list_add(&new->hash_entry, entry);
return new;
alloc_failed:
die("memory allocation failed\n");
}
static const char *input_name;
struct raw_event_sample {
u32 size;
char data[0];
};
struct trace_acquire_event {
void *addr;
const char *name;
int flag;
};
struct trace_acquired_event {
void *addr;
const char *name;
};
struct trace_contended_event {
void *addr;
const char *name;
};
struct trace_release_event {
void *addr;
const char *name;
};
struct trace_lock_handler {
void (*acquire_event)(struct trace_acquire_event *,
struct event *,
int cpu,
u64 timestamp,
struct thread *thread);
void (*acquired_event)(struct trace_acquired_event *,
struct event *,
int cpu,
u64 timestamp,
struct thread *thread);
void (*contended_event)(struct trace_contended_event *,
struct event *,
int cpu,
u64 timestamp,
struct thread *thread);
void (*release_event)(struct trace_release_event *,
struct event *,
int cpu,
u64 timestamp,
struct thread *thread);
};
static struct lock_seq_stat *get_seq(struct thread_stat *ts, void *addr)
{
struct lock_seq_stat *seq;
list_for_each_entry(seq, &ts->seq_list, list) {
if (seq->addr == addr)
return seq;
}
seq = zalloc(sizeof(struct lock_seq_stat));
if (!seq)
die("Not enough memory\n");
seq->state = SEQ_STATE_UNINITIALIZED;
seq->addr = addr;
list_add(&seq->list, &ts->seq_list);
return seq;
}
enum broken_state {
BROKEN_ACQUIRE,
BROKEN_ACQUIRED,
BROKEN_CONTENDED,
BROKEN_RELEASE,
BROKEN_MAX,
};
static int bad_hist[BROKEN_MAX];
enum acquire_flags {
TRY_LOCK = 1,
READ_LOCK = 2,
};
static void
report_lock_acquire_event(struct trace_acquire_event *acquire_event,
struct event *__event __used,
int cpu __used,
u64 timestamp __used,
struct thread *thread __used)
{
struct lock_stat *ls;
struct thread_stat *ts;
struct lock_seq_stat *seq;
ls = lock_stat_findnew(acquire_event->addr, acquire_event->name);
if (ls->discard)
return;
ts = thread_stat_findnew(thread->pid);
seq = get_seq(ts, acquire_event->addr);
switch (seq->state) {
case SEQ_STATE_UNINITIALIZED:
case SEQ_STATE_RELEASED:
if (!acquire_event->flag) {
seq->state = SEQ_STATE_ACQUIRING;
} else {
if (acquire_event->flag & TRY_LOCK)
ls->nr_trylock++;
if (acquire_event->flag & READ_LOCK)
ls->nr_readlock++;
seq->state = SEQ_STATE_READ_ACQUIRED;
seq->read_count = 1;
ls->nr_acquired++;
}
break;
case SEQ_STATE_READ_ACQUIRED:
if (acquire_event->flag & READ_LOCK) {
seq->read_count++;
ls->nr_acquired++;
goto end;
} else {
goto broken;
}
break;
case SEQ_STATE_ACQUIRED:
case SEQ_STATE_ACQUIRING:
case SEQ_STATE_CONTENDED:
broken:
/* broken lock sequence, discard it */
ls->discard = 1;
bad_hist[BROKEN_ACQUIRE]++;
list_del(&seq->list);
free(seq);
goto end;
break;
default:
BUG_ON("Unknown state of lock sequence found!\n");
break;
}
ls->nr_acquire++;
seq->prev_event_time = timestamp;
end:
return;
}
static void
report_lock_acquired_event(struct trace_acquired_event *acquired_event,
struct event *__event __used,
int cpu __used,
u64 timestamp __used,
struct thread *thread __used)
{
struct lock_stat *ls;
struct thread_stat *ts;
struct lock_seq_stat *seq;
u64 contended_term;
ls = lock_stat_findnew(acquired_event->addr, acquired_event->name);
if (ls->discard)
return;
ts = thread_stat_findnew(thread->pid);
seq = get_seq(ts, acquired_event->addr);
switch (seq->state) {
case SEQ_STATE_UNINITIALIZED:
/* orphan event, do nothing */
return;
case SEQ_STATE_ACQUIRING:
break;
case SEQ_STATE_CONTENDED:
contended_term = timestamp - seq->prev_event_time;
ls->wait_time_total += contended_term;
if (contended_term < ls->wait_time_min)
ls->wait_time_min = contended_term;
if (ls->wait_time_max < contended_term)
ls->wait_time_max = contended_term;
break;
case SEQ_STATE_RELEASED:
case SEQ_STATE_ACQUIRED:
case SEQ_STATE_READ_ACQUIRED:
/* broken lock sequence, discard it */
ls->discard = 1;
bad_hist[BROKEN_ACQUIRED]++;
list_del(&seq->list);
free(seq);
goto end;
break;
default:
BUG_ON("Unknown state of lock sequence found!\n");
break;
}
seq->state = SEQ_STATE_ACQUIRED;
ls->nr_acquired++;
seq->prev_event_time = timestamp;
end:
return;
}
static void
report_lock_contended_event(struct trace_contended_event *contended_event,
struct event *__event __used,
int cpu __used,
u64 timestamp __used,
struct thread *thread __used)
{
struct lock_stat *ls;
struct thread_stat *ts;
struct lock_seq_stat *seq;
ls = lock_stat_findnew(contended_event->addr, contended_event->name);
if (ls->discard)
return;
ts = thread_stat_findnew(thread->pid);
seq = get_seq(ts, contended_event->addr);
switch (seq->state) {
case SEQ_STATE_UNINITIALIZED:
/* orphan event, do nothing */
return;
case SEQ_STATE_ACQUIRING:
break;
case SEQ_STATE_RELEASED:
case SEQ_STATE_ACQUIRED:
case SEQ_STATE_READ_ACQUIRED:
case SEQ_STATE_CONTENDED:
/* broken lock sequence, discard it */
ls->discard = 1;
bad_hist[BROKEN_CONTENDED]++;
list_del(&seq->list);
free(seq);
goto end;
break;
default:
BUG_ON("Unknown state of lock sequence found!\n");
break;
}
seq->state = SEQ_STATE_CONTENDED;
ls->nr_contended++;
seq->prev_event_time = timestamp;
end:
return;
}
static void
report_lock_release_event(struct trace_release_event *release_event,
struct event *__event __used,
int cpu __used,
u64 timestamp __used,
struct thread *thread __used)
{
struct lock_stat *ls;
struct thread_stat *ts;
struct lock_seq_stat *seq;
ls = lock_stat_findnew(release_event->addr, release_event->name);
if (ls->discard)
return;
ts = thread_stat_findnew(thread->pid);
seq = get_seq(ts, release_event->addr);
switch (seq->state) {
case SEQ_STATE_UNINITIALIZED:
goto end;
break;
case SEQ_STATE_ACQUIRED:
break;
case SEQ_STATE_READ_ACQUIRED:
seq->read_count--;
BUG_ON(seq->read_count < 0);
if (!seq->read_count) {
ls->nr_release++;
goto end;
}
break;
case SEQ_STATE_ACQUIRING:
case SEQ_STATE_CONTENDED:
case SEQ_STATE_RELEASED:
/* broken lock sequence, discard it */
ls->discard = 1;
bad_hist[BROKEN_RELEASE]++;
goto free_seq;
break;
default:
BUG_ON("Unknown state of lock sequence found!\n");
break;
}
ls->nr_release++;
free_seq:
list_del(&seq->list);
free(seq);
end:
return;
}
/* lock oriented handlers */
/* TODO: handlers for CPU oriented, thread oriented */
static struct trace_lock_handler report_lock_ops = {
.acquire_event = report_lock_acquire_event,
.acquired_event = report_lock_acquired_event,
.contended_event = report_lock_contended_event,
.release_event = report_lock_release_event,
};
static struct trace_lock_handler *trace_handler;
static void
process_lock_acquire_event(void *data,
struct event *event __used,
int cpu __used,
u64 timestamp __used,
struct thread *thread __used)
{
struct trace_acquire_event acquire_event;
u64 tmp; /* this is required for casting... */
tmp = raw_field_value(event, "lockdep_addr", data);
memcpy(&acquire_event.addr, &tmp, sizeof(void *));
acquire_event.name = (char *)raw_field_ptr(event, "name", data);
acquire_event.flag = (int)raw_field_value(event, "flag", data);
if (trace_handler->acquire_event)
trace_handler->acquire_event(&acquire_event, event, cpu, timestamp, thread);
}
static void
process_lock_acquired_event(void *data,
struct event *event __used,
int cpu __used,
u64 timestamp __used,
struct thread *thread __used)
{
struct trace_acquired_event acquired_event;
u64 tmp; /* this is required for casting... */
tmp = raw_field_value(event, "lockdep_addr", data);
memcpy(&acquired_event.addr, &tmp, sizeof(void *));
acquired_event.name = (char *)raw_field_ptr(event, "name", data);
if (trace_handler->acquire_event)
trace_handler->acquired_event(&acquired_event, event, cpu, timestamp, thread);
}
static void
process_lock_contended_event(void *data,
struct event *event __used,
int cpu __used,
u64 timestamp __used,
struct thread *thread __used)
{
struct trace_contended_event contended_event;
u64 tmp; /* this is required for casting... */
tmp = raw_field_value(event, "lockdep_addr", data);
memcpy(&contended_event.addr, &tmp, sizeof(void *));
contended_event.name = (char *)raw_field_ptr(event, "name", data);
if (trace_handler->acquire_event)
trace_handler->contended_event(&contended_event, event, cpu, timestamp, thread);
}
static void
process_lock_release_event(void *data,
struct event *event __used,
int cpu __used,
u64 timestamp __used,
struct thread *thread __used)
{
struct trace_release_event release_event;
u64 tmp; /* this is required for casting... */
tmp = raw_field_value(event, "lockdep_addr", data);
memcpy(&release_event.addr, &tmp, sizeof(void *));
release_event.name = (char *)raw_field_ptr(event, "name", data);
if (trace_handler->acquire_event)
trace_handler->release_event(&release_event, event, cpu, timestamp, thread);
}
static void
process_raw_event(void *data, int cpu, u64 timestamp, struct thread *thread)
{
struct event *event;
int type;
type = trace_parse_common_type(data);
event = trace_find_event(type);
if (!strcmp(event->name, "lock_acquire"))
process_lock_acquire_event(data, event, cpu, timestamp, thread);
if (!strcmp(event->name, "lock_acquired"))
process_lock_acquired_event(data, event, cpu, timestamp, thread);
if (!strcmp(event->name, "lock_contended"))
process_lock_contended_event(data, event, cpu, timestamp, thread);
if (!strcmp(event->name, "lock_release"))
process_lock_release_event(data, event, cpu, timestamp, thread);
}
static void print_bad_events(int bad, int total)
{
/* Output for debug, this have to be removed */
int i;
const char *name[4] =
{ "acquire", "acquired", "contended", "release" };
pr_info("\n=== output for debug===\n\n");
pr_info("bad: %d, total: %d\n", bad, total);
pr_info("bad rate: %f %%\n", (double)bad / (double)total * 100);
pr_info("histogram of events caused bad sequence\n");
for (i = 0; i < BROKEN_MAX; i++)
pr_info(" %10s: %d\n", name[i], bad_hist[i]);
}
/* TODO: various way to print, coloring, nano or milli sec */
static void print_result(void)
{
struct lock_stat *st;
char cut_name[20];
int bad, total;
pr_info("%20s ", "Name");
pr_info("%10s ", "acquired");
pr_info("%10s ", "contended");
pr_info("%15s ", "total wait (ns)");
pr_info("%15s ", "max wait (ns)");
pr_info("%15s ", "min wait (ns)");
pr_info("\n\n");
bad = total = 0;
while ((st = pop_from_result())) {
total++;
if (st->discard) {
bad++;
continue;
}
bzero(cut_name, 20);
if (strlen(st->name) < 16) {
/* output raw name */
pr_info("%20s ", st->name);
} else {
strncpy(cut_name, st->name, 16);
cut_name[16] = '.';
cut_name[17] = '.';
cut_name[18] = '.';
cut_name[19] = '\0';
/* cut off name for saving output style */
pr_info("%20s ", cut_name);
}
pr_info("%10u ", st->nr_acquired);
pr_info("%10u ", st->nr_contended);
pr_info("%15" PRIu64 " ", st->wait_time_total);
pr_info("%15" PRIu64 " ", st->wait_time_max);
pr_info("%15" PRIu64 " ", st->wait_time_min == ULLONG_MAX ?
0 : st->wait_time_min);
pr_info("\n");
}
print_bad_events(bad, total);
}
static bool info_threads, info_map;
static void dump_threads(void)
{
struct thread_stat *st;
struct rb_node *node;
struct thread *t;
pr_info("%10s: comm\n", "Thread ID");
node = rb_first(&thread_stats);
while (node) {
st = container_of(node, struct thread_stat, rb);
t = perf_session__findnew(session, st->tid);
pr_info("%10d: %s\n", st->tid, t->comm);
node = rb_next(node);
};
}
static void dump_map(void)
{
unsigned int i;
struct lock_stat *st;
pr_info("Address of instance: name of class\n");
for (i = 0; i < LOCKHASH_SIZE; i++) {
list_for_each_entry(st, &lockhash_table[i], hash_entry) {
pr_info(" %p: %s\n", st->addr, st->name);
}
}
}
static void dump_info(void)
{
if (info_threads)
dump_threads();
else if (info_map)
dump_map();
else
die("Unknown type of information\n");
}
static int process_sample_event(struct perf_tool *tool __used,
union perf_event *event,
struct perf_sample *sample,
struct perf_evsel *evsel __used,
struct machine *machine)
{
struct thread *thread = machine__findnew_thread(machine, sample->tid);
if (thread == NULL) {
pr_debug("problem processing %d event, skipping it.\n",
event->header.type);
return -1;
}
process_raw_event(sample->raw_data, sample->cpu, sample->time, thread);
return 0;
}
static struct perf_tool eops = {
.sample = process_sample_event,
.comm = perf_event__process_comm,
.ordered_samples = true,
};
static int read_events(void)
{
session = perf_session__new(input_name, O_RDONLY, 0, false, &eops);
if (!session)
die("Initializing perf session failed\n");
return perf_session__process_events(session, &eops);
}
static void sort_result(void)
{
unsigned int i;
struct lock_stat *st;
for (i = 0; i < LOCKHASH_SIZE; i++) {
list_for_each_entry(st, &lockhash_table[i], hash_entry) {
insert_to_result(st, compare);
}
}
}
static void __cmd_report(void)
{
setup_pager();
select_key();
read_events();
sort_result();
print_result();
}
static const char * const report_usage[] = {
"perf lock report [<options>]",
NULL
};
static const struct option report_options[] = {
OPT_STRING('k', "key", &sort_key, "acquired",
"key for sorting (acquired / contended / wait_total / wait_max / wait_min)"),
/* TODO: type */
OPT_END()
};
static const char * const info_usage[] = {
"perf lock info [<options>]",
NULL
};
static const struct option info_options[] = {
OPT_BOOLEAN('t', "threads", &info_threads,
"dump thread list in perf.data"),
OPT_BOOLEAN('m', "map", &info_map,
"map of lock instances (address:name table)"),
OPT_END()
};
static const char * const lock_usage[] = {
"perf lock [<options>] {record|report|script|info}",
NULL
};
static const struct option lock_options[] = {
OPT_STRING('i', "input", &input_name, "file", "input file name"),
OPT_INCR('v', "verbose", &verbose, "be more verbose (show symbol address, etc)"),
OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace, "dump raw trace in ASCII"),
OPT_END()
};
static const char *record_args[] = {
"record",
"-R",
"-f",
"-m", "1024",
"-c", "1",
"-e", "lock:lock_acquire",
"-e", "lock:lock_acquired",
"-e", "lock:lock_contended",
"-e", "lock:lock_release",
};
static int __cmd_record(int argc, const char **argv)
{
unsigned int rec_argc, i, j;
const char **rec_argv;
rec_argc = ARRAY_SIZE(record_args) + argc - 1;
rec_argv = calloc(rec_argc + 1, sizeof(char *));
if (rec_argv == NULL)
return -ENOMEM;
for (i = 0; i < ARRAY_SIZE(record_args); i++)
rec_argv[i] = strdup(record_args[i]);
for (j = 1; j < (unsigned int)argc; j++, i++)
rec_argv[i] = argv[j];
BUG_ON(i != rec_argc);
return cmd_record(i, rec_argv, NULL);
}
int cmd_lock(int argc, const char **argv, const char *prefix __used)
{
unsigned int i;
symbol__init();
for (i = 0; i < LOCKHASH_SIZE; i++)
INIT_LIST_HEAD(lockhash_table + i);
argc = parse_options(argc, argv, lock_options, lock_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
if (!argc)
usage_with_options(lock_usage, lock_options);
if (!strncmp(argv[0], "rec", 3)) {
return __cmd_record(argc, argv);
} else if (!strncmp(argv[0], "report", 6)) {
trace_handler = &report_lock_ops;
if (argc) {
argc = parse_options(argc, argv,
report_options, report_usage, 0);
if (argc)
usage_with_options(report_usage, report_options);
}
__cmd_report();
} else if (!strcmp(argv[0], "script")) {
/* Aliased to 'perf script' */
return cmd_script(argc, argv, prefix);
} else if (!strcmp(argv[0], "info")) {
if (argc) {
argc = parse_options(argc, argv,
info_options, info_usage, 0);
if (argc)
usage_with_options(info_usage, info_options);
}
/* recycling report_lock_ops */
trace_handler = &report_lock_ops;
setup_pager();
read_events();
dump_info();
} else {
usage_with_options(lock_usage, lock_options);
}
return 0;
}
| gpl-2.0 |
santod/android_kernel_htc_dlxwl | drivers/edac/i5400_edac.c | 4806 | 40522 | /*
* Intel 5400 class Memory Controllers kernel module (Seaburg)
*
* This file may be distributed under the terms of the
* GNU General Public License.
*
* Copyright (c) 2008 by:
* Ben Woodard <woodard@redhat.com>
* Mauro Carvalho Chehab <mchehab@redhat.com>
*
* Red Hat Inc. http://www.redhat.com
*
* Forked and adapted from the i5000_edac driver which was
* written by Douglas Thompson Linux Networx <norsk5@xmission.com>
*
* This module is based on the following document:
*
* Intel 5400 Chipset Memory Controller Hub (MCH) - Datasheet
* http://developer.intel.com/design/chipsets/datashts/313070.htm
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/slab.h>
#include <linux/edac.h>
#include <linux/mmzone.h>
#include "edac_core.h"
/*
* Alter this version for the I5400 module when modifications are made
*/
#define I5400_REVISION " Ver: 1.0.0"
#define EDAC_MOD_STR "i5400_edac"
#define i5400_printk(level, fmt, arg...) \
edac_printk(level, "i5400", fmt, ##arg)
#define i5400_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "i5400", fmt, ##arg)
/* Limits for i5400 */
#define NUM_MTRS_PER_BRANCH 4
#define CHANNELS_PER_BRANCH 2
#define MAX_DIMMS_PER_CHANNEL NUM_MTRS_PER_BRANCH
#define MAX_CHANNELS 4
/* max possible csrows per channel */
#define MAX_CSROWS (MAX_DIMMS_PER_CHANNEL)
/* Device 16,
* Function 0: System Address
* Function 1: Memory Branch Map, Control, Errors Register
* Function 2: FSB Error Registers
*
* All 3 functions of Device 16 (0,1,2) share the SAME DID and
* uses PCI_DEVICE_ID_INTEL_5400_ERR for device 16 (0,1,2),
* PCI_DEVICE_ID_INTEL_5400_FBD0 and PCI_DEVICE_ID_INTEL_5400_FBD1
* for device 21 (0,1).
*/
/* OFFSETS for Function 0 */
#define AMBASE 0x48 /* AMB Mem Mapped Reg Region Base */
#define MAXCH 0x56 /* Max Channel Number */
#define MAXDIMMPERCH 0x57 /* Max DIMM PER Channel Number */
/* OFFSETS for Function 1 */
#define TOLM 0x6C
#define REDMEMB 0x7C
#define REC_ECC_LOCATOR_ODD(x) ((x) & 0x3fe00) /* bits [17:9] indicate ODD, [8:0] indicate EVEN */
#define MIR0 0x80
#define MIR1 0x84
#define AMIR0 0x8c
#define AMIR1 0x90
/* Fatal error registers */
#define FERR_FAT_FBD 0x98 /* also called as FERR_FAT_FB_DIMM at datasheet */
#define FERR_FAT_FBDCHAN (3<<28) /* channel index where the highest-order error occurred */
#define NERR_FAT_FBD 0x9c
#define FERR_NF_FBD 0xa0 /* also called as FERR_NFAT_FB_DIMM at datasheet */
/* Non-fatal error register */
#define NERR_NF_FBD 0xa4
/* Enable error mask */
#define EMASK_FBD 0xa8
#define ERR0_FBD 0xac
#define ERR1_FBD 0xb0
#define ERR2_FBD 0xb4
#define MCERR_FBD 0xb8
/* No OFFSETS for Device 16 Function 2 */
/*
* Device 21,
* Function 0: Memory Map Branch 0
*
* Device 22,
* Function 0: Memory Map Branch 1
*/
/* OFFSETS for Function 0 */
#define AMBPRESENT_0 0x64
#define AMBPRESENT_1 0x66
#define MTR0 0x80
#define MTR1 0x82
#define MTR2 0x84
#define MTR3 0x86
/* OFFSETS for Function 1 */
#define NRECFGLOG 0x74
#define RECFGLOG 0x78
#define NRECMEMA 0xbe
#define NRECMEMB 0xc0
#define NRECFB_DIMMA 0xc4
#define NRECFB_DIMMB 0xc8
#define NRECFB_DIMMC 0xcc
#define NRECFB_DIMMD 0xd0
#define NRECFB_DIMME 0xd4
#define NRECFB_DIMMF 0xd8
#define REDMEMA 0xdC
#define RECMEMA 0xf0
#define RECMEMB 0xf4
#define RECFB_DIMMA 0xf8
#define RECFB_DIMMB 0xec
#define RECFB_DIMMC 0xf0
#define RECFB_DIMMD 0xf4
#define RECFB_DIMME 0xf8
#define RECFB_DIMMF 0xfC
/*
* Error indicator bits and masks
* Error masks are according with Table 5-17 of i5400 datasheet
*/
enum error_mask {
EMASK_M1 = 1<<0, /* Memory Write error on non-redundant retry */
EMASK_M2 = 1<<1, /* Memory or FB-DIMM configuration CRC read error */
EMASK_M3 = 1<<2, /* Reserved */
EMASK_M4 = 1<<3, /* Uncorrectable Data ECC on Replay */
EMASK_M5 = 1<<4, /* Aliased Uncorrectable Non-Mirrored Demand Data ECC */
EMASK_M6 = 1<<5, /* Unsupported on i5400 */
EMASK_M7 = 1<<6, /* Aliased Uncorrectable Resilver- or Spare-Copy Data ECC */
EMASK_M8 = 1<<7, /* Aliased Uncorrectable Patrol Data ECC */
EMASK_M9 = 1<<8, /* Non-Aliased Uncorrectable Non-Mirrored Demand Data ECC */
EMASK_M10 = 1<<9, /* Unsupported on i5400 */
EMASK_M11 = 1<<10, /* Non-Aliased Uncorrectable Resilver- or Spare-Copy Data ECC */
EMASK_M12 = 1<<11, /* Non-Aliased Uncorrectable Patrol Data ECC */
EMASK_M13 = 1<<12, /* Memory Write error on first attempt */
EMASK_M14 = 1<<13, /* FB-DIMM Configuration Write error on first attempt */
EMASK_M15 = 1<<14, /* Memory or FB-DIMM configuration CRC read error */
EMASK_M16 = 1<<15, /* Channel Failed-Over Occurred */
EMASK_M17 = 1<<16, /* Correctable Non-Mirrored Demand Data ECC */
EMASK_M18 = 1<<17, /* Unsupported on i5400 */
EMASK_M19 = 1<<18, /* Correctable Resilver- or Spare-Copy Data ECC */
EMASK_M20 = 1<<19, /* Correctable Patrol Data ECC */
EMASK_M21 = 1<<20, /* FB-DIMM Northbound parity error on FB-DIMM Sync Status */
EMASK_M22 = 1<<21, /* SPD protocol Error */
EMASK_M23 = 1<<22, /* Non-Redundant Fast Reset Timeout */
EMASK_M24 = 1<<23, /* Refresh error */
EMASK_M25 = 1<<24, /* Memory Write error on redundant retry */
EMASK_M26 = 1<<25, /* Redundant Fast Reset Timeout */
EMASK_M27 = 1<<26, /* Correctable Counter Threshold Exceeded */
EMASK_M28 = 1<<27, /* DIMM-Spare Copy Completed */
EMASK_M29 = 1<<28, /* DIMM-Isolation Completed */
};
/*
* Names to translate bit error into something useful
*/
static const char *error_name[] = {
[0] = "Memory Write error on non-redundant retry",
[1] = "Memory or FB-DIMM configuration CRC read error",
/* Reserved */
[3] = "Uncorrectable Data ECC on Replay",
[4] = "Aliased Uncorrectable Non-Mirrored Demand Data ECC",
/* M6 Unsupported on i5400 */
[6] = "Aliased Uncorrectable Resilver- or Spare-Copy Data ECC",
[7] = "Aliased Uncorrectable Patrol Data ECC",
[8] = "Non-Aliased Uncorrectable Non-Mirrored Demand Data ECC",
/* M10 Unsupported on i5400 */
[10] = "Non-Aliased Uncorrectable Resilver- or Spare-Copy Data ECC",
[11] = "Non-Aliased Uncorrectable Patrol Data ECC",
[12] = "Memory Write error on first attempt",
[13] = "FB-DIMM Configuration Write error on first attempt",
[14] = "Memory or FB-DIMM configuration CRC read error",
[15] = "Channel Failed-Over Occurred",
[16] = "Correctable Non-Mirrored Demand Data ECC",
/* M18 Unsupported on i5400 */
[18] = "Correctable Resilver- or Spare-Copy Data ECC",
[19] = "Correctable Patrol Data ECC",
[20] = "FB-DIMM Northbound parity error on FB-DIMM Sync Status",
[21] = "SPD protocol Error",
[22] = "Non-Redundant Fast Reset Timeout",
[23] = "Refresh error",
[24] = "Memory Write error on redundant retry",
[25] = "Redundant Fast Reset Timeout",
[26] = "Correctable Counter Threshold Exceeded",
[27] = "DIMM-Spare Copy Completed",
[28] = "DIMM-Isolation Completed",
};
/* Fatal errors */
#define ERROR_FAT_MASK (EMASK_M1 | \
EMASK_M2 | \
EMASK_M23)
/* Correctable errors */
#define ERROR_NF_CORRECTABLE (EMASK_M27 | \
EMASK_M20 | \
EMASK_M19 | \
EMASK_M18 | \
EMASK_M17 | \
EMASK_M16)
#define ERROR_NF_DIMM_SPARE (EMASK_M29 | \
EMASK_M28)
#define ERROR_NF_SPD_PROTOCOL (EMASK_M22)
#define ERROR_NF_NORTH_CRC (EMASK_M21)
/* Recoverable errors */
#define ERROR_NF_RECOVERABLE (EMASK_M26 | \
EMASK_M25 | \
EMASK_M24 | \
EMASK_M15 | \
EMASK_M14 | \
EMASK_M13 | \
EMASK_M12 | \
EMASK_M11 | \
EMASK_M9 | \
EMASK_M8 | \
EMASK_M7 | \
EMASK_M5)
/* uncorrectable errors */
#define ERROR_NF_UNCORRECTABLE (EMASK_M4)
/* mask to all non-fatal errors */
#define ERROR_NF_MASK (ERROR_NF_CORRECTABLE | \
ERROR_NF_UNCORRECTABLE | \
ERROR_NF_RECOVERABLE | \
ERROR_NF_DIMM_SPARE | \
ERROR_NF_SPD_PROTOCOL | \
ERROR_NF_NORTH_CRC)
/*
* Define error masks for the several registers
*/
/* Enable all fatal and non fatal errors */
#define ENABLE_EMASK_ALL (ERROR_FAT_MASK | ERROR_NF_MASK)
/* mask for fatal error registers */
#define FERR_FAT_MASK ERROR_FAT_MASK
/* masks for non-fatal error register */
static inline int to_nf_mask(unsigned int mask)
{
return (mask & EMASK_M29) | (mask >> 3);
};
static inline int from_nf_ferr(unsigned int mask)
{
return (mask & EMASK_M29) | /* Bit 28 */
(mask & ((1 << 28) - 1) << 3); /* Bits 0 to 27 */
};
#define FERR_NF_MASK to_nf_mask(ERROR_NF_MASK)
#define FERR_NF_CORRECTABLE to_nf_mask(ERROR_NF_CORRECTABLE)
#define FERR_NF_DIMM_SPARE to_nf_mask(ERROR_NF_DIMM_SPARE)
#define FERR_NF_SPD_PROTOCOL to_nf_mask(ERROR_NF_SPD_PROTOCOL)
#define FERR_NF_NORTH_CRC to_nf_mask(ERROR_NF_NORTH_CRC)
#define FERR_NF_RECOVERABLE to_nf_mask(ERROR_NF_RECOVERABLE)
#define FERR_NF_UNCORRECTABLE to_nf_mask(ERROR_NF_UNCORRECTABLE)
/* Defines to extract the vaious fields from the
* MTRx - Memory Technology Registers
*/
#define MTR_DIMMS_PRESENT(mtr) ((mtr) & (1 << 10))
#define MTR_DIMMS_ETHROTTLE(mtr) ((mtr) & (1 << 9))
#define MTR_DRAM_WIDTH(mtr) (((mtr) & (1 << 8)) ? 8 : 4)
#define MTR_DRAM_BANKS(mtr) (((mtr) & (1 << 6)) ? 8 : 4)
#define MTR_DRAM_BANKS_ADDR_BITS(mtr) ((MTR_DRAM_BANKS(mtr) == 8) ? 3 : 2)
#define MTR_DIMM_RANK(mtr) (((mtr) >> 5) & 0x1)
#define MTR_DIMM_RANK_ADDR_BITS(mtr) (MTR_DIMM_RANK(mtr) ? 2 : 1)
#define MTR_DIMM_ROWS(mtr) (((mtr) >> 2) & 0x3)
#define MTR_DIMM_ROWS_ADDR_BITS(mtr) (MTR_DIMM_ROWS(mtr) + 13)
#define MTR_DIMM_COLS(mtr) ((mtr) & 0x3)
#define MTR_DIMM_COLS_ADDR_BITS(mtr) (MTR_DIMM_COLS(mtr) + 10)
/* This applies to FERR_NF_FB-DIMM as well as FERR_FAT_FB-DIMM */
static inline int extract_fbdchan_indx(u32 x)
{
return (x>>28) & 0x3;
}
#ifdef CONFIG_EDAC_DEBUG
/* MTR NUMROW */
static const char *numrow_toString[] = {
"8,192 - 13 rows",
"16,384 - 14 rows",
"32,768 - 15 rows",
"65,536 - 16 rows"
};
/* MTR NUMCOL */
static const char *numcol_toString[] = {
"1,024 - 10 columns",
"2,048 - 11 columns",
"4,096 - 12 columns",
"reserved"
};
#endif
/* Device name and register DID (Device ID) */
struct i5400_dev_info {
const char *ctl_name; /* name for this device */
u16 fsb_mapping_errors; /* DID for the branchmap,control */
};
/* Table of devices attributes supported by this driver */
static const struct i5400_dev_info i5400_devs[] = {
{
.ctl_name = "I5400",
.fsb_mapping_errors = PCI_DEVICE_ID_INTEL_5400_ERR,
},
};
struct i5400_dimm_info {
int megabytes; /* size, 0 means not present */
};
/* driver private data structure */
struct i5400_pvt {
struct pci_dev *system_address; /* 16.0 */
struct pci_dev *branchmap_werrors; /* 16.1 */
struct pci_dev *fsb_error_regs; /* 16.2 */
struct pci_dev *branch_0; /* 21.0 */
struct pci_dev *branch_1; /* 22.0 */
u16 tolm; /* top of low memory */
u64 ambase; /* AMB BAR */
u16 mir0, mir1;
u16 b0_mtr[NUM_MTRS_PER_BRANCH]; /* Memory Technlogy Reg */
u16 b0_ambpresent0; /* Branch 0, Channel 0 */
u16 b0_ambpresent1; /* Brnach 0, Channel 1 */
u16 b1_mtr[NUM_MTRS_PER_BRANCH]; /* Memory Technlogy Reg */
u16 b1_ambpresent0; /* Branch 1, Channel 8 */
u16 b1_ambpresent1; /* Branch 1, Channel 1 */
/* DIMM information matrix, allocating architecture maximums */
struct i5400_dimm_info dimm_info[MAX_CSROWS][MAX_CHANNELS];
/* Actual values for this controller */
int maxch; /* Max channels */
int maxdimmperch; /* Max DIMMs per channel */
};
/* I5400 MCH error information retrieved from Hardware */
struct i5400_error_info {
/* These registers are always read from the MC */
u32 ferr_fat_fbd; /* First Errors Fatal */
u32 nerr_fat_fbd; /* Next Errors Fatal */
u32 ferr_nf_fbd; /* First Errors Non-Fatal */
u32 nerr_nf_fbd; /* Next Errors Non-Fatal */
/* These registers are input ONLY if there was a Recoverable Error */
u32 redmemb; /* Recoverable Mem Data Error log B */
u16 recmema; /* Recoverable Mem Error log A */
u32 recmemb; /* Recoverable Mem Error log B */
/* These registers are input ONLY if there was a Non-Rec Error */
u16 nrecmema; /* Non-Recoverable Mem log A */
u16 nrecmemb; /* Non-Recoverable Mem log B */
};
/* note that nrec_rdwr changed from NRECMEMA to NRECMEMB between the 5000 and
5400 better to use an inline function than a macro in this case */
static inline int nrec_bank(struct i5400_error_info *info)
{
return ((info->nrecmema) >> 12) & 0x7;
}
static inline int nrec_rank(struct i5400_error_info *info)
{
return ((info->nrecmema) >> 8) & 0xf;
}
static inline int nrec_buf_id(struct i5400_error_info *info)
{
return ((info->nrecmema)) & 0xff;
}
static inline int nrec_rdwr(struct i5400_error_info *info)
{
return (info->nrecmemb) >> 31;
}
/* This applies to both NREC and REC string so it can be used with nrec_rdwr
and rec_rdwr */
static inline const char *rdwr_str(int rdwr)
{
return rdwr ? "Write" : "Read";
}
static inline int nrec_cas(struct i5400_error_info *info)
{
return ((info->nrecmemb) >> 16) & 0x1fff;
}
static inline int nrec_ras(struct i5400_error_info *info)
{
return (info->nrecmemb) & 0xffff;
}
static inline int rec_bank(struct i5400_error_info *info)
{
return ((info->recmema) >> 12) & 0x7;
}
static inline int rec_rank(struct i5400_error_info *info)
{
return ((info->recmema) >> 8) & 0xf;
}
static inline int rec_rdwr(struct i5400_error_info *info)
{
return (info->recmemb) >> 31;
}
static inline int rec_cas(struct i5400_error_info *info)
{
return ((info->recmemb) >> 16) & 0x1fff;
}
static inline int rec_ras(struct i5400_error_info *info)
{
return (info->recmemb) & 0xffff;
}
static struct edac_pci_ctl_info *i5400_pci;
/*
* i5400_get_error_info Retrieve the hardware error information from
* the hardware and cache it in the 'info'
* structure
*/
static void i5400_get_error_info(struct mem_ctl_info *mci,
struct i5400_error_info *info)
{
struct i5400_pvt *pvt;
u32 value;
pvt = mci->pvt_info;
/* read in the 1st FATAL error register */
pci_read_config_dword(pvt->branchmap_werrors, FERR_FAT_FBD, &value);
/* Mask only the bits that the doc says are valid
*/
value &= (FERR_FAT_FBDCHAN | FERR_FAT_MASK);
/* If there is an error, then read in the
NEXT FATAL error register and the Memory Error Log Register A
*/
if (value & FERR_FAT_MASK) {
info->ferr_fat_fbd = value;
/* harvest the various error data we need */
pci_read_config_dword(pvt->branchmap_werrors,
NERR_FAT_FBD, &info->nerr_fat_fbd);
pci_read_config_word(pvt->branchmap_werrors,
NRECMEMA, &info->nrecmema);
pci_read_config_word(pvt->branchmap_werrors,
NRECMEMB, &info->nrecmemb);
/* Clear the error bits, by writing them back */
pci_write_config_dword(pvt->branchmap_werrors,
FERR_FAT_FBD, value);
} else {
info->ferr_fat_fbd = 0;
info->nerr_fat_fbd = 0;
info->nrecmema = 0;
info->nrecmemb = 0;
}
/* read in the 1st NON-FATAL error register */
pci_read_config_dword(pvt->branchmap_werrors, FERR_NF_FBD, &value);
/* If there is an error, then read in the 1st NON-FATAL error
* register as well */
if (value & FERR_NF_MASK) {
info->ferr_nf_fbd = value;
/* harvest the various error data we need */
pci_read_config_dword(pvt->branchmap_werrors,
NERR_NF_FBD, &info->nerr_nf_fbd);
pci_read_config_word(pvt->branchmap_werrors,
RECMEMA, &info->recmema);
pci_read_config_dword(pvt->branchmap_werrors,
RECMEMB, &info->recmemb);
pci_read_config_dword(pvt->branchmap_werrors,
REDMEMB, &info->redmemb);
/* Clear the error bits, by writing them back */
pci_write_config_dword(pvt->branchmap_werrors,
FERR_NF_FBD, value);
} else {
info->ferr_nf_fbd = 0;
info->nerr_nf_fbd = 0;
info->recmema = 0;
info->recmemb = 0;
info->redmemb = 0;
}
}
/*
* i5400_proccess_non_recoverable_info(struct mem_ctl_info *mci,
* struct i5400_error_info *info,
* int handle_errors);
*
* handle the Intel FATAL and unrecoverable errors, if any
*/
static void i5400_proccess_non_recoverable_info(struct mem_ctl_info *mci,
struct i5400_error_info *info,
unsigned long allErrors)
{
char msg[EDAC_MC_LABEL_LEN + 1 + 90 + 80];
int branch;
int channel;
int bank;
int buf_id;
int rank;
int rdwr;
int ras, cas;
int errnum;
char *type = NULL;
if (!allErrors)
return; /* if no error, return now */
if (allErrors & ERROR_FAT_MASK)
type = "FATAL";
else if (allErrors & FERR_NF_UNCORRECTABLE)
type = "NON-FATAL uncorrected";
else
type = "NON-FATAL recoverable";
/* ONLY ONE of the possible error bits will be set, as per the docs */
branch = extract_fbdchan_indx(info->ferr_fat_fbd);
channel = branch;
/* Use the NON-Recoverable macros to extract data */
bank = nrec_bank(info);
rank = nrec_rank(info);
buf_id = nrec_buf_id(info);
rdwr = nrec_rdwr(info);
ras = nrec_ras(info);
cas = nrec_cas(info);
debugf0("\t\tCSROW= %d Channels= %d,%d (Branch= %d "
"DRAM Bank= %d Buffer ID = %d rdwr= %s ras= %d cas= %d)\n",
rank, channel, channel + 1, branch >> 1, bank,
buf_id, rdwr_str(rdwr), ras, cas);
/* Only 1 bit will be on */
errnum = find_first_bit(&allErrors, ARRAY_SIZE(error_name));
/* Form out message */
snprintf(msg, sizeof(msg),
"%s (Branch=%d DRAM-Bank=%d Buffer ID = %d RDWR=%s "
"RAS=%d CAS=%d %s Err=0x%lx (%s))",
type, branch >> 1, bank, buf_id, rdwr_str(rdwr), ras, cas,
type, allErrors, error_name[errnum]);
/* Call the helper to output message */
edac_mc_handle_fbd_ue(mci, rank, channel, channel + 1, msg);
}
/*
* i5400_process_fatal_error_info(struct mem_ctl_info *mci,
* struct i5400_error_info *info,
* int handle_errors);
*
* handle the Intel NON-FATAL errors, if any
*/
static void i5400_process_nonfatal_error_info(struct mem_ctl_info *mci,
struct i5400_error_info *info)
{
char msg[EDAC_MC_LABEL_LEN + 1 + 90 + 80];
unsigned long allErrors;
int branch;
int channel;
int bank;
int rank;
int rdwr;
int ras, cas;
int errnum;
/* mask off the Error bits that are possible */
allErrors = from_nf_ferr(info->ferr_nf_fbd & FERR_NF_MASK);
if (!allErrors)
return; /* if no error, return now */
/* ONLY ONE of the possible error bits will be set, as per the docs */
if (allErrors & (ERROR_NF_UNCORRECTABLE | ERROR_NF_RECOVERABLE)) {
i5400_proccess_non_recoverable_info(mci, info, allErrors);
return;
}
/* Correctable errors */
if (allErrors & ERROR_NF_CORRECTABLE) {
debugf0("\tCorrected bits= 0x%lx\n", allErrors);
branch = extract_fbdchan_indx(info->ferr_nf_fbd);
channel = 0;
if (REC_ECC_LOCATOR_ODD(info->redmemb))
channel = 1;
/* Convert channel to be based from zero, instead of
* from branch base of 0 */
channel += branch;
bank = rec_bank(info);
rank = rec_rank(info);
rdwr = rec_rdwr(info);
ras = rec_ras(info);
cas = rec_cas(info);
/* Only 1 bit will be on */
errnum = find_first_bit(&allErrors, ARRAY_SIZE(error_name));
debugf0("\t\tCSROW= %d Channel= %d (Branch %d "
"DRAM Bank= %d rdwr= %s ras= %d cas= %d)\n",
rank, channel, branch >> 1, bank,
rdwr_str(rdwr), ras, cas);
/* Form out message */
snprintf(msg, sizeof(msg),
"Corrected error (Branch=%d DRAM-Bank=%d RDWR=%s "
"RAS=%d CAS=%d, CE Err=0x%lx (%s))",
branch >> 1, bank, rdwr_str(rdwr), ras, cas,
allErrors, error_name[errnum]);
/* Call the helper to output message */
edac_mc_handle_fbd_ce(mci, rank, channel, msg);
return;
}
/* Miscellaneous errors */
errnum = find_first_bit(&allErrors, ARRAY_SIZE(error_name));
branch = extract_fbdchan_indx(info->ferr_nf_fbd);
i5400_mc_printk(mci, KERN_EMERG,
"Non-Fatal misc error (Branch=%d Err=%#lx (%s))",
branch >> 1, allErrors, error_name[errnum]);
}
/*
* i5400_process_error_info Process the error info that is
* in the 'info' structure, previously retrieved from hardware
*/
static void i5400_process_error_info(struct mem_ctl_info *mci,
struct i5400_error_info *info)
{ u32 allErrors;
/* First handle any fatal errors that occurred */
allErrors = (info->ferr_fat_fbd & FERR_FAT_MASK);
i5400_proccess_non_recoverable_info(mci, info, allErrors);
/* now handle any non-fatal errors that occurred */
i5400_process_nonfatal_error_info(mci, info);
}
/*
* i5400_clear_error Retrieve any error from the hardware
* but do NOT process that error.
* Used for 'clearing' out of previous errors
* Called by the Core module.
*/
static void i5400_clear_error(struct mem_ctl_info *mci)
{
struct i5400_error_info info;
i5400_get_error_info(mci, &info);
}
/*
* i5400_check_error Retrieve and process errors reported by the
* hardware. Called by the Core module.
*/
static void i5400_check_error(struct mem_ctl_info *mci)
{
struct i5400_error_info info;
debugf4("MC%d: %s: %s()\n", mci->mc_idx, __FILE__, __func__);
i5400_get_error_info(mci, &info);
i5400_process_error_info(mci, &info);
}
/*
* i5400_put_devices 'put' all the devices that we have
* reserved via 'get'
*/
static void i5400_put_devices(struct mem_ctl_info *mci)
{
struct i5400_pvt *pvt;
pvt = mci->pvt_info;
/* Decrement usage count for devices */
pci_dev_put(pvt->branch_1);
pci_dev_put(pvt->branch_0);
pci_dev_put(pvt->fsb_error_regs);
pci_dev_put(pvt->branchmap_werrors);
}
/*
* i5400_get_devices Find and perform 'get' operation on the MCH's
* device/functions we want to reference for this driver
*
* Need to 'get' device 16 func 1 and func 2
*/
static int i5400_get_devices(struct mem_ctl_info *mci, int dev_idx)
{
struct i5400_pvt *pvt;
struct pci_dev *pdev;
pvt = mci->pvt_info;
pvt->branchmap_werrors = NULL;
pvt->fsb_error_regs = NULL;
pvt->branch_0 = NULL;
pvt->branch_1 = NULL;
/* Attempt to 'get' the MCH register we want */
pdev = NULL;
while (1) {
pdev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_ERR, pdev);
if (!pdev) {
/* End of list, leave */
i5400_printk(KERN_ERR,
"'system address,Process Bus' "
"device not found:"
"vendor 0x%x device 0x%x ERR func 1 "
"(broken BIOS?)\n",
PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_ERR);
return -ENODEV;
}
/* Store device 16 func 1 */
if (PCI_FUNC(pdev->devfn) == 1)
break;
}
pvt->branchmap_werrors = pdev;
pdev = NULL;
while (1) {
pdev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_ERR, pdev);
if (!pdev) {
/* End of list, leave */
i5400_printk(KERN_ERR,
"'system address,Process Bus' "
"device not found:"
"vendor 0x%x device 0x%x ERR func 2 "
"(broken BIOS?)\n",
PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_ERR);
pci_dev_put(pvt->branchmap_werrors);
return -ENODEV;
}
/* Store device 16 func 2 */
if (PCI_FUNC(pdev->devfn) == 2)
break;
}
pvt->fsb_error_regs = pdev;
debugf1("System Address, processor bus- PCI Bus ID: %s %x:%x\n",
pci_name(pvt->system_address),
pvt->system_address->vendor, pvt->system_address->device);
debugf1("Branchmap, control and errors - PCI Bus ID: %s %x:%x\n",
pci_name(pvt->branchmap_werrors),
pvt->branchmap_werrors->vendor, pvt->branchmap_werrors->device);
debugf1("FSB Error Regs - PCI Bus ID: %s %x:%x\n",
pci_name(pvt->fsb_error_regs),
pvt->fsb_error_regs->vendor, pvt->fsb_error_regs->device);
pvt->branch_0 = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_FBD0, NULL);
if (!pvt->branch_0) {
i5400_printk(KERN_ERR,
"MC: 'BRANCH 0' device not found:"
"vendor 0x%x device 0x%x Func 0 (broken BIOS?)\n",
PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_5400_FBD0);
pci_dev_put(pvt->fsb_error_regs);
pci_dev_put(pvt->branchmap_werrors);
return -ENODEV;
}
/* If this device claims to have more than 2 channels then
* fetch Branch 1's information
*/
if (pvt->maxch < CHANNELS_PER_BRANCH)
return 0;
pvt->branch_1 = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_FBD1, NULL);
if (!pvt->branch_1) {
i5400_printk(KERN_ERR,
"MC: 'BRANCH 1' device not found:"
"vendor 0x%x device 0x%x Func 0 "
"(broken BIOS?)\n",
PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_5400_FBD1);
pci_dev_put(pvt->branch_0);
pci_dev_put(pvt->fsb_error_regs);
pci_dev_put(pvt->branchmap_werrors);
return -ENODEV;
}
return 0;
}
/*
* determine_amb_present
*
* the information is contained in NUM_MTRS_PER_BRANCH different
* registers determining which of the NUM_MTRS_PER_BRANCH requires
* knowing which channel is in question
*
* 2 branches, each with 2 channels
* b0_ambpresent0 for channel '0'
* b0_ambpresent1 for channel '1'
* b1_ambpresent0 for channel '2'
* b1_ambpresent1 for channel '3'
*/
static int determine_amb_present_reg(struct i5400_pvt *pvt, int channel)
{
int amb_present;
if (channel < CHANNELS_PER_BRANCH) {
if (channel & 0x1)
amb_present = pvt->b0_ambpresent1;
else
amb_present = pvt->b0_ambpresent0;
} else {
if (channel & 0x1)
amb_present = pvt->b1_ambpresent1;
else
amb_present = pvt->b1_ambpresent0;
}
return amb_present;
}
/*
* determine_mtr(pvt, csrow, channel)
*
* return the proper MTR register as determine by the csrow and desired channel
*/
static int determine_mtr(struct i5400_pvt *pvt, int csrow, int channel)
{
int mtr;
int n;
/* There is one MTR for each slot pair of FB-DIMMs,
Each slot pair may be at branch 0 or branch 1.
*/
n = csrow;
if (n >= NUM_MTRS_PER_BRANCH) {
debugf0("ERROR: trying to access an invalid csrow: %d\n",
csrow);
return 0;
}
if (channel < CHANNELS_PER_BRANCH)
mtr = pvt->b0_mtr[n];
else
mtr = pvt->b1_mtr[n];
return mtr;
}
/*
*/
static void decode_mtr(int slot_row, u16 mtr)
{
int ans;
ans = MTR_DIMMS_PRESENT(mtr);
debugf2("\tMTR%d=0x%x: DIMMs are %s\n", slot_row, mtr,
ans ? "Present" : "NOT Present");
if (!ans)
return;
debugf2("\t\tWIDTH: x%d\n", MTR_DRAM_WIDTH(mtr));
debugf2("\t\tELECTRICAL THROTTLING is %s\n",
MTR_DIMMS_ETHROTTLE(mtr) ? "enabled" : "disabled");
debugf2("\t\tNUMBANK: %d bank(s)\n", MTR_DRAM_BANKS(mtr));
debugf2("\t\tNUMRANK: %s\n", MTR_DIMM_RANK(mtr) ? "double" : "single");
debugf2("\t\tNUMROW: %s\n", numrow_toString[MTR_DIMM_ROWS(mtr)]);
debugf2("\t\tNUMCOL: %s\n", numcol_toString[MTR_DIMM_COLS(mtr)]);
}
static void handle_channel(struct i5400_pvt *pvt, int csrow, int channel,
struct i5400_dimm_info *dinfo)
{
int mtr;
int amb_present_reg;
int addrBits;
mtr = determine_mtr(pvt, csrow, channel);
if (MTR_DIMMS_PRESENT(mtr)) {
amb_present_reg = determine_amb_present_reg(pvt, channel);
/* Determine if there is a DIMM present in this DIMM slot */
if (amb_present_reg & (1 << csrow)) {
/* Start with the number of bits for a Bank
* on the DRAM */
addrBits = MTR_DRAM_BANKS_ADDR_BITS(mtr);
/* Add thenumber of ROW bits */
addrBits += MTR_DIMM_ROWS_ADDR_BITS(mtr);
/* add the number of COLUMN bits */
addrBits += MTR_DIMM_COLS_ADDR_BITS(mtr);
/* add the number of RANK bits */
addrBits += MTR_DIMM_RANK(mtr);
addrBits += 6; /* add 64 bits per DIMM */
addrBits -= 20; /* divide by 2^^20 */
addrBits -= 3; /* 8 bits per bytes */
dinfo->megabytes = 1 << addrBits;
}
}
}
/*
* calculate_dimm_size
*
* also will output a DIMM matrix map, if debug is enabled, for viewing
* how the DIMMs are populated
*/
static void calculate_dimm_size(struct i5400_pvt *pvt)
{
struct i5400_dimm_info *dinfo;
int csrow, max_csrows;
char *p, *mem_buffer;
int space, n;
int channel;
/* ================= Generate some debug output ================= */
space = PAGE_SIZE;
mem_buffer = p = kmalloc(space, GFP_KERNEL);
if (p == NULL) {
i5400_printk(KERN_ERR, "MC: %s:%s() kmalloc() failed\n",
__FILE__, __func__);
return;
}
/* Scan all the actual CSROWS
* and calculate the information for each DIMM
* Start with the highest csrow first, to display it first
* and work toward the 0th csrow
*/
max_csrows = pvt->maxdimmperch;
for (csrow = max_csrows - 1; csrow >= 0; csrow--) {
/* on an odd csrow, first output a 'boundary' marker,
* then reset the message buffer */
if (csrow & 0x1) {
n = snprintf(p, space, "---------------------------"
"--------------------------------");
p += n;
space -= n;
debugf2("%s\n", mem_buffer);
p = mem_buffer;
space = PAGE_SIZE;
}
n = snprintf(p, space, "csrow %2d ", csrow);
p += n;
space -= n;
for (channel = 0; channel < pvt->maxch; channel++) {
dinfo = &pvt->dimm_info[csrow][channel];
handle_channel(pvt, csrow, channel, dinfo);
n = snprintf(p, space, "%4d MB | ", dinfo->megabytes);
p += n;
space -= n;
}
debugf2("%s\n", mem_buffer);
p = mem_buffer;
space = PAGE_SIZE;
}
/* Output the last bottom 'boundary' marker */
n = snprintf(p, space, "---------------------------"
"--------------------------------");
p += n;
space -= n;
debugf2("%s\n", mem_buffer);
p = mem_buffer;
space = PAGE_SIZE;
/* now output the 'channel' labels */
n = snprintf(p, space, " ");
p += n;
space -= n;
for (channel = 0; channel < pvt->maxch; channel++) {
n = snprintf(p, space, "channel %d | ", channel);
p += n;
space -= n;
}
/* output the last message and free buffer */
debugf2("%s\n", mem_buffer);
kfree(mem_buffer);
}
/*
* i5400_get_mc_regs read in the necessary registers and
* cache locally
*
* Fills in the private data members
*/
static void i5400_get_mc_regs(struct mem_ctl_info *mci)
{
struct i5400_pvt *pvt;
u32 actual_tolm;
u16 limit;
int slot_row;
int maxch;
int maxdimmperch;
int way0, way1;
pvt = mci->pvt_info;
pci_read_config_dword(pvt->system_address, AMBASE,
(u32 *) &pvt->ambase);
pci_read_config_dword(pvt->system_address, AMBASE + sizeof(u32),
((u32 *) &pvt->ambase) + sizeof(u32));
maxdimmperch = pvt->maxdimmperch;
maxch = pvt->maxch;
debugf2("AMBASE= 0x%lx MAXCH= %d MAX-DIMM-Per-CH= %d\n",
(long unsigned int)pvt->ambase, pvt->maxch, pvt->maxdimmperch);
/* Get the Branch Map regs */
pci_read_config_word(pvt->branchmap_werrors, TOLM, &pvt->tolm);
pvt->tolm >>= 12;
debugf2("\nTOLM (number of 256M regions) =%u (0x%x)\n", pvt->tolm,
pvt->tolm);
actual_tolm = (u32) ((1000l * pvt->tolm) >> (30 - 28));
debugf2("Actual TOLM byte addr=%u.%03u GB (0x%x)\n",
actual_tolm/1000, actual_tolm % 1000, pvt->tolm << 28);
pci_read_config_word(pvt->branchmap_werrors, MIR0, &pvt->mir0);
pci_read_config_word(pvt->branchmap_werrors, MIR1, &pvt->mir1);
/* Get the MIR[0-1] regs */
limit = (pvt->mir0 >> 4) & 0x0fff;
way0 = pvt->mir0 & 0x1;
way1 = pvt->mir0 & 0x2;
debugf2("MIR0: limit= 0x%x WAY1= %u WAY0= %x\n", limit, way1, way0);
limit = (pvt->mir1 >> 4) & 0xfff;
way0 = pvt->mir1 & 0x1;
way1 = pvt->mir1 & 0x2;
debugf2("MIR1: limit= 0x%x WAY1= %u WAY0= %x\n", limit, way1, way0);
/* Get the set of MTR[0-3] regs by each branch */
for (slot_row = 0; slot_row < NUM_MTRS_PER_BRANCH; slot_row++) {
int where = MTR0 + (slot_row * sizeof(u16));
/* Branch 0 set of MTR registers */
pci_read_config_word(pvt->branch_0, where,
&pvt->b0_mtr[slot_row]);
debugf2("MTR%d where=0x%x B0 value=0x%x\n", slot_row, where,
pvt->b0_mtr[slot_row]);
if (pvt->maxch < CHANNELS_PER_BRANCH) {
pvt->b1_mtr[slot_row] = 0;
continue;
}
/* Branch 1 set of MTR registers */
pci_read_config_word(pvt->branch_1, where,
&pvt->b1_mtr[slot_row]);
debugf2("MTR%d where=0x%x B1 value=0x%x\n", slot_row, where,
pvt->b1_mtr[slot_row]);
}
/* Read and dump branch 0's MTRs */
debugf2("\nMemory Technology Registers:\n");
debugf2(" Branch 0:\n");
for (slot_row = 0; slot_row < NUM_MTRS_PER_BRANCH; slot_row++)
decode_mtr(slot_row, pvt->b0_mtr[slot_row]);
pci_read_config_word(pvt->branch_0, AMBPRESENT_0,
&pvt->b0_ambpresent0);
debugf2("\t\tAMB-Branch 0-present0 0x%x:\n", pvt->b0_ambpresent0);
pci_read_config_word(pvt->branch_0, AMBPRESENT_1,
&pvt->b0_ambpresent1);
debugf2("\t\tAMB-Branch 0-present1 0x%x:\n", pvt->b0_ambpresent1);
/* Only if we have 2 branchs (4 channels) */
if (pvt->maxch < CHANNELS_PER_BRANCH) {
pvt->b1_ambpresent0 = 0;
pvt->b1_ambpresent1 = 0;
} else {
/* Read and dump branch 1's MTRs */
debugf2(" Branch 1:\n");
for (slot_row = 0; slot_row < NUM_MTRS_PER_BRANCH; slot_row++)
decode_mtr(slot_row, pvt->b1_mtr[slot_row]);
pci_read_config_word(pvt->branch_1, AMBPRESENT_0,
&pvt->b1_ambpresent0);
debugf2("\t\tAMB-Branch 1-present0 0x%x:\n",
pvt->b1_ambpresent0);
pci_read_config_word(pvt->branch_1, AMBPRESENT_1,
&pvt->b1_ambpresent1);
debugf2("\t\tAMB-Branch 1-present1 0x%x:\n",
pvt->b1_ambpresent1);
}
/* Go and determine the size of each DIMM and place in an
* orderly matrix */
calculate_dimm_size(pvt);
}
/*
* i5400_init_csrows Initialize the 'csrows' table within
* the mci control structure with the
* addressing of memory.
*
* return:
* 0 success
* 1 no actual memory found on this MC
*/
static int i5400_init_csrows(struct mem_ctl_info *mci)
{
struct i5400_pvt *pvt;
struct csrow_info *p_csrow;
int empty, channel_count;
int max_csrows;
int mtr;
int csrow_megs;
int channel;
int csrow;
pvt = mci->pvt_info;
channel_count = pvt->maxch;
max_csrows = pvt->maxdimmperch;
empty = 1; /* Assume NO memory */
for (csrow = 0; csrow < max_csrows; csrow++) {
p_csrow = &mci->csrows[csrow];
p_csrow->csrow_idx = csrow;
/* use branch 0 for the basis */
mtr = determine_mtr(pvt, csrow, 0);
/* if no DIMMS on this row, continue */
if (!MTR_DIMMS_PRESENT(mtr))
continue;
/* FAKE OUT VALUES, FIXME */
p_csrow->first_page = 0 + csrow * 20;
p_csrow->last_page = 9 + csrow * 20;
p_csrow->page_mask = 0xFFF;
p_csrow->grain = 8;
csrow_megs = 0;
for (channel = 0; channel < pvt->maxch; channel++)
csrow_megs += pvt->dimm_info[csrow][channel].megabytes;
p_csrow->nr_pages = csrow_megs << 8;
/* Assume DDR2 for now */
p_csrow->mtype = MEM_FB_DDR2;
/* ask what device type on this row */
if (MTR_DRAM_WIDTH(mtr))
p_csrow->dtype = DEV_X8;
else
p_csrow->dtype = DEV_X4;
p_csrow->edac_mode = EDAC_S8ECD8ED;
empty = 0;
}
return empty;
}
/*
* i5400_enable_error_reporting
* Turn on the memory reporting features of the hardware
*/
static void i5400_enable_error_reporting(struct mem_ctl_info *mci)
{
struct i5400_pvt *pvt;
u32 fbd_error_mask;
pvt = mci->pvt_info;
/* Read the FBD Error Mask Register */
pci_read_config_dword(pvt->branchmap_werrors, EMASK_FBD,
&fbd_error_mask);
/* Enable with a '0' */
fbd_error_mask &= ~(ENABLE_EMASK_ALL);
pci_write_config_dword(pvt->branchmap_werrors, EMASK_FBD,
fbd_error_mask);
}
/*
* i5400_probe1 Probe for ONE instance of device to see if it is
* present.
* return:
* 0 for FOUND a device
* < 0 for error code
*/
static int i5400_probe1(struct pci_dev *pdev, int dev_idx)
{
struct mem_ctl_info *mci;
struct i5400_pvt *pvt;
int num_channels;
int num_dimms_per_channel;
int num_csrows;
if (dev_idx >= ARRAY_SIZE(i5400_devs))
return -EINVAL;
debugf0("MC: %s: %s(), pdev bus %u dev=0x%x fn=0x%x\n",
__FILE__, __func__,
pdev->bus->number,
PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
/* We only are looking for func 0 of the set */
if (PCI_FUNC(pdev->devfn) != 0)
return -ENODEV;
/* As we don't have a motherboard identification routine to determine
* actual number of slots/dimms per channel, we thus utilize the
* resource as specified by the chipset. Thus, we might have
* have more DIMMs per channel than actually on the mobo, but this
* allows the driver to support up to the chipset max, without
* some fancy mobo determination.
*/
num_dimms_per_channel = MAX_DIMMS_PER_CHANNEL;
num_channels = MAX_CHANNELS;
num_csrows = num_dimms_per_channel;
debugf0("MC: %s(): Number of - Channels= %d DIMMS= %d CSROWS= %d\n",
__func__, num_channels, num_dimms_per_channel, num_csrows);
/* allocate a new MC control structure */
mci = edac_mc_alloc(sizeof(*pvt), num_csrows, num_channels, 0);
if (mci == NULL)
return -ENOMEM;
debugf0("MC: %s: %s(): mci = %p\n", __FILE__, __func__, mci);
mci->dev = &pdev->dev; /* record ptr to the generic device */
pvt = mci->pvt_info;
pvt->system_address = pdev; /* Record this device in our private */
pvt->maxch = num_channels;
pvt->maxdimmperch = num_dimms_per_channel;
/* 'get' the pci devices we want to reserve for our use */
if (i5400_get_devices(mci, dev_idx))
goto fail0;
/* Time to get serious */
i5400_get_mc_regs(mci); /* retrieve the hardware registers */
mci->mc_idx = 0;
mci->mtype_cap = MEM_FLAG_FB_DDR2;
mci->edac_ctl_cap = EDAC_FLAG_NONE;
mci->edac_cap = EDAC_FLAG_NONE;
mci->mod_name = "i5400_edac.c";
mci->mod_ver = I5400_REVISION;
mci->ctl_name = i5400_devs[dev_idx].ctl_name;
mci->dev_name = pci_name(pdev);
mci->ctl_page_to_phys = NULL;
/* Set the function pointer to an actual operation function */
mci->edac_check = i5400_check_error;
/* initialize the MC control structure 'csrows' table
* with the mapping and control information */
if (i5400_init_csrows(mci)) {
debugf0("MC: Setting mci->edac_cap to EDAC_FLAG_NONE\n"
" because i5400_init_csrows() returned nonzero "
"value\n");
mci->edac_cap = EDAC_FLAG_NONE; /* no csrows found */
} else {
debugf1("MC: Enable error reporting now\n");
i5400_enable_error_reporting(mci);
}
/* add this new MC control structure to EDAC's list of MCs */
if (edac_mc_add_mc(mci)) {
debugf0("MC: %s: %s(): failed edac_mc_add_mc()\n",
__FILE__, __func__);
/* FIXME: perhaps some code should go here that disables error
* reporting if we just enabled it
*/
goto fail1;
}
i5400_clear_error(mci);
/* allocating generic PCI control info */
i5400_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!i5400_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__);
}
return 0;
/* Error exit unwinding stack */
fail1:
i5400_put_devices(mci);
fail0:
edac_mc_free(mci);
return -ENODEV;
}
/*
* i5400_init_one constructor for one instance of device
*
* returns:
* negative on error
* count (>= 0)
*/
static int __devinit i5400_init_one(struct pci_dev *pdev,
const struct pci_device_id *id)
{
int rc;
debugf0("MC: %s: %s()\n", __FILE__, __func__);
/* wake up device */
rc = pci_enable_device(pdev);
if (rc)
return rc;
/* now probe and enable the device */
return i5400_probe1(pdev, id->driver_data);
}
/*
* i5400_remove_one destructor for one instance of device
*
*/
static void __devexit i5400_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
debugf0("%s: %s()\n", __FILE__, __func__);
if (i5400_pci)
edac_pci_release_generic_ctl(i5400_pci);
mci = edac_mc_del_mc(&pdev->dev);
if (!mci)
return;
/* retrieve references to resources, and free those resources */
i5400_put_devices(mci);
edac_mc_free(mci);
}
/*
* pci_device_id table for which devices we are looking for
*
* The "E500P" device is the first device supported.
*/
static DEFINE_PCI_DEVICE_TABLE(i5400_pci_tbl) = {
{PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_5400_ERR)},
{0,} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, i5400_pci_tbl);
/*
* i5400_driver pci_driver structure for this module
*
*/
static struct pci_driver i5400_driver = {
.name = "i5400_edac",
.probe = i5400_init_one,
.remove = __devexit_p(i5400_remove_one),
.id_table = i5400_pci_tbl,
};
/*
* i5400_init Module entry function
* Try to initialize this module for its devices
*/
static int __init i5400_init(void)
{
int pci_rc;
debugf2("MC: %s: %s()\n", __FILE__, __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
pci_rc = pci_register_driver(&i5400_driver);
return (pci_rc < 0) ? pci_rc : 0;
}
/*
* i5400_exit() Module exit function
* Unregister the driver
*/
static void __exit i5400_exit(void)
{
debugf2("MC: %s: %s()\n", __FILE__, __func__);
pci_unregister_driver(&i5400_driver);
}
module_init(i5400_init);
module_exit(i5400_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ben Woodard <woodard@redhat.com>");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
MODULE_AUTHOR("Red Hat Inc. (http://www.redhat.com)");
MODULE_DESCRIPTION("MC Driver for Intel I5400 memory controllers - "
I5400_REVISION);
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| gpl-2.0 |
htc-msm8960/android_kernel_htc_m7 | drivers/watchdog/imx2_wdt.c | 4806 | 9531 | /*
* Watchdog driver for IMX2 and later processors
*
* Copyright (C) 2010 Wolfram Sang, Pengutronix e.K. <w.sang@pengutronix.de>
*
* some parts adapted by similar drivers from Darius Augulis and Vladimir
* Zapolskiy, additional improvements by Wim Van Sebroeck.
*
* 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.
*
* NOTE: MX1 has a slightly different Watchdog than MX2 and later:
*
* MX1: MX2+:
* ---- -----
* Registers: 32-bit 16-bit
* Stopable timer: Yes No
* Need to enable clk: No Yes
* Halt on suspend: Manual Can be automatic
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/platform_device.h>
#include <linux/watchdog.h>
#include <linux/clk.h>
#include <linux/fs.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <mach/hardware.h>
#define DRIVER_NAME "imx2-wdt"
#define IMX2_WDT_WCR 0x00 /* Control Register */
#define IMX2_WDT_WCR_WT (0xFF << 8) /* -> Watchdog Timeout Field */
#define IMX2_WDT_WCR_WRE (1 << 3) /* -> WDOG Reset Enable */
#define IMX2_WDT_WCR_WDE (1 << 2) /* -> Watchdog Enable */
#define IMX2_WDT_WSR 0x02 /* Service Register */
#define IMX2_WDT_SEQ1 0x5555 /* -> service sequence 1 */
#define IMX2_WDT_SEQ2 0xAAAA /* -> service sequence 2 */
#define IMX2_WDT_WRSR 0x04 /* Reset Status Register */
#define IMX2_WDT_WRSR_TOUT (1 << 1) /* -> Reset due to Timeout */
#define IMX2_WDT_MAX_TIME 128
#define IMX2_WDT_DEFAULT_TIME 60 /* in seconds */
#define WDOG_SEC_TO_COUNT(s) ((s * 2 - 1) << 8)
#define IMX2_WDT_STATUS_OPEN 0
#define IMX2_WDT_STATUS_STARTED 1
#define IMX2_WDT_EXPECT_CLOSE 2
static struct {
struct clk *clk;
void __iomem *base;
unsigned timeout;
unsigned long status;
struct timer_list timer; /* Pings the watchdog when closed */
} imx2_wdt;
static struct miscdevice imx2_wdt_miscdev;
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static unsigned timeout = IMX2_WDT_DEFAULT_TIME;
module_param(timeout, uint, 0);
MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds (default="
__MODULE_STRING(IMX2_WDT_DEFAULT_TIME) ")");
static const struct watchdog_info imx2_wdt_info = {
.identity = "imx2+ watchdog",
.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT | WDIOF_MAGICCLOSE,
};
static inline void imx2_wdt_setup(void)
{
u16 val = __raw_readw(imx2_wdt.base + IMX2_WDT_WCR);
/* Strip the old watchdog Time-Out value */
val &= ~IMX2_WDT_WCR_WT;
/* Generate reset if WDOG times out */
val &= ~IMX2_WDT_WCR_WRE;
/* Keep Watchdog Disabled */
val &= ~IMX2_WDT_WCR_WDE;
/* Set the watchdog's Time-Out value */
val |= WDOG_SEC_TO_COUNT(imx2_wdt.timeout);
__raw_writew(val, imx2_wdt.base + IMX2_WDT_WCR);
/* enable the watchdog */
val |= IMX2_WDT_WCR_WDE;
__raw_writew(val, imx2_wdt.base + IMX2_WDT_WCR);
}
static inline void imx2_wdt_ping(void)
{
__raw_writew(IMX2_WDT_SEQ1, imx2_wdt.base + IMX2_WDT_WSR);
__raw_writew(IMX2_WDT_SEQ2, imx2_wdt.base + IMX2_WDT_WSR);
}
static void imx2_wdt_timer_ping(unsigned long arg)
{
/* ping it every imx2_wdt.timeout / 2 seconds to prevent reboot */
imx2_wdt_ping();
mod_timer(&imx2_wdt.timer, jiffies + imx2_wdt.timeout * HZ / 2);
}
static void imx2_wdt_start(void)
{
if (!test_and_set_bit(IMX2_WDT_STATUS_STARTED, &imx2_wdt.status)) {
/* at our first start we enable clock and do initialisations */
clk_enable(imx2_wdt.clk);
imx2_wdt_setup();
} else /* delete the timer that pings the watchdog after close */
del_timer_sync(&imx2_wdt.timer);
/* Watchdog is enabled - time to reload the timeout value */
imx2_wdt_ping();
}
static void imx2_wdt_stop(void)
{
/* we don't need a clk_disable, it cannot be disabled once started.
* We use a timer to ping the watchdog while /dev/watchdog is closed */
imx2_wdt_timer_ping(0);
}
static void imx2_wdt_set_timeout(int new_timeout)
{
u16 val = __raw_readw(imx2_wdt.base + IMX2_WDT_WCR);
/* set the new timeout value in the WSR */
val &= ~IMX2_WDT_WCR_WT;
val |= WDOG_SEC_TO_COUNT(new_timeout);
__raw_writew(val, imx2_wdt.base + IMX2_WDT_WCR);
}
static int imx2_wdt_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(IMX2_WDT_STATUS_OPEN, &imx2_wdt.status))
return -EBUSY;
imx2_wdt_start();
return nonseekable_open(inode, file);
}
static int imx2_wdt_close(struct inode *inode, struct file *file)
{
if (test_bit(IMX2_WDT_EXPECT_CLOSE, &imx2_wdt.status) && !nowayout)
imx2_wdt_stop();
else {
dev_crit(imx2_wdt_miscdev.parent,
"Unexpected close: Expect reboot!\n");
imx2_wdt_ping();
}
clear_bit(IMX2_WDT_EXPECT_CLOSE, &imx2_wdt.status);
clear_bit(IMX2_WDT_STATUS_OPEN, &imx2_wdt.status);
return 0;
}
static long imx2_wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *)arg;
int __user *p = argp;
int new_value;
u16 val;
switch (cmd) {
case WDIOC_GETSUPPORT:
return copy_to_user(argp, &imx2_wdt_info,
sizeof(struct watchdog_info)) ? -EFAULT : 0;
case WDIOC_GETSTATUS:
return put_user(0, p);
case WDIOC_GETBOOTSTATUS:
val = __raw_readw(imx2_wdt.base + IMX2_WDT_WRSR);
new_value = val & IMX2_WDT_WRSR_TOUT ? WDIOF_CARDRESET : 0;
return put_user(new_value, p);
case WDIOC_KEEPALIVE:
imx2_wdt_ping();
return 0;
case WDIOC_SETTIMEOUT:
if (get_user(new_value, p))
return -EFAULT;
if ((new_value < 1) || (new_value > IMX2_WDT_MAX_TIME))
return -EINVAL;
imx2_wdt_set_timeout(new_value);
imx2_wdt.timeout = new_value;
imx2_wdt_ping();
/* Fallthrough to return current value */
case WDIOC_GETTIMEOUT:
return put_user(imx2_wdt.timeout, p);
default:
return -ENOTTY;
}
}
static ssize_t imx2_wdt_write(struct file *file, const char __user *data,
size_t len, loff_t *ppos)
{
size_t i;
char c;
if (len == 0) /* Can we see this even ? */
return 0;
clear_bit(IMX2_WDT_EXPECT_CLOSE, &imx2_wdt.status);
/* scan to see whether or not we got the magic character */
for (i = 0; i != len; i++) {
if (get_user(c, data + i))
return -EFAULT;
if (c == 'V')
set_bit(IMX2_WDT_EXPECT_CLOSE, &imx2_wdt.status);
}
imx2_wdt_ping();
return len;
}
static const struct file_operations imx2_wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.unlocked_ioctl = imx2_wdt_ioctl,
.open = imx2_wdt_open,
.release = imx2_wdt_close,
.write = imx2_wdt_write,
};
static struct miscdevice imx2_wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &imx2_wdt_fops,
};
static int __init imx2_wdt_probe(struct platform_device *pdev)
{
int ret;
struct resource *res;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "can't get device resources\n");
return -ENODEV;
}
imx2_wdt.base = devm_request_and_ioremap(&pdev->dev, res);
if (!imx2_wdt.base) {
dev_err(&pdev->dev, "ioremap failed\n");
return -ENOMEM;
}
imx2_wdt.clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(imx2_wdt.clk)) {
dev_err(&pdev->dev, "can't get Watchdog clock\n");
return PTR_ERR(imx2_wdt.clk);
}
imx2_wdt.timeout = clamp_t(unsigned, timeout, 1, IMX2_WDT_MAX_TIME);
if (imx2_wdt.timeout != timeout)
dev_warn(&pdev->dev, "Initial timeout out of range! "
"Clamped from %u to %u\n", timeout, imx2_wdt.timeout);
setup_timer(&imx2_wdt.timer, imx2_wdt_timer_ping, 0);
imx2_wdt_miscdev.parent = &pdev->dev;
ret = misc_register(&imx2_wdt_miscdev);
if (ret)
goto fail;
dev_info(&pdev->dev,
"IMX2+ Watchdog Timer enabled. timeout=%ds (nowayout=%d)\n",
imx2_wdt.timeout, nowayout);
return 0;
fail:
imx2_wdt_miscdev.parent = NULL;
clk_put(imx2_wdt.clk);
return ret;
}
static int __exit imx2_wdt_remove(struct platform_device *pdev)
{
misc_deregister(&imx2_wdt_miscdev);
if (test_bit(IMX2_WDT_STATUS_STARTED, &imx2_wdt.status)) {
del_timer_sync(&imx2_wdt.timer);
dev_crit(imx2_wdt_miscdev.parent,
"Device removed: Expect reboot!\n");
} else
clk_put(imx2_wdt.clk);
imx2_wdt_miscdev.parent = NULL;
return 0;
}
static void imx2_wdt_shutdown(struct platform_device *pdev)
{
if (test_bit(IMX2_WDT_STATUS_STARTED, &imx2_wdt.status)) {
/* we are running, we need to delete the timer but will give
* max timeout before reboot will take place */
del_timer_sync(&imx2_wdt.timer);
imx2_wdt_set_timeout(IMX2_WDT_MAX_TIME);
imx2_wdt_ping();
dev_crit(imx2_wdt_miscdev.parent,
"Device shutdown: Expect reboot!\n");
}
}
static const struct of_device_id imx2_wdt_dt_ids[] = {
{ .compatible = "fsl,imx21-wdt", },
{ /* sentinel */ }
};
static struct platform_driver imx2_wdt_driver = {
.remove = __exit_p(imx2_wdt_remove),
.shutdown = imx2_wdt_shutdown,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
.of_match_table = imx2_wdt_dt_ids,
},
};
static int __init imx2_wdt_init(void)
{
return platform_driver_probe(&imx2_wdt_driver, imx2_wdt_probe);
}
module_init(imx2_wdt_init);
static void __exit imx2_wdt_exit(void)
{
platform_driver_unregister(&imx2_wdt_driver);
}
module_exit(imx2_wdt_exit);
MODULE_AUTHOR("Wolfram Sang");
MODULE_DESCRIPTION("Watchdog driver for IMX2 and later");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
MODULE_ALIAS("platform:" DRIVER_NAME);
| gpl-2.0 |
googyanas/Googy-Max3-Kernel-for-CM | net/lapb/lapb_in.c | 4806 | 17905 | /*
* LAPB release 002
*
* This code REQUIRES 2.1.15 or higher/ NET3.038
*
* This module:
* This module 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.
*
* History
* LAPB 001 Jonathan Naulor Started Coding
* LAPB 002 Jonathan Naylor New timer architecture.
* 2000-10-29 Henner Eisen lapb_data_indication() return status.
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <net/lapb.h>
/*
* State machine for state 0, Disconnected State.
* The handling of the timer(s) is in file lapb_timer.c.
*/
static void lapb_state0_machine(struct lapb_cb *lapb, struct sk_buff *skb,
struct lapb_frame *frame)
{
switch (frame->type) {
case LAPB_SABM:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S0 RX SABM(%d)\n",
lapb->dev, frame->pf);
#endif
if (lapb->mode & LAPB_EXTENDED) {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S0 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S0 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S0 -> S3\n", lapb->dev);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf,
LAPB_RESPONSE);
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_3;
lapb->condition = 0x00;
lapb->n2count = 0;
lapb->vs = 0;
lapb->vr = 0;
lapb->va = 0;
lapb_connect_indication(lapb, LAPB_OK);
}
break;
case LAPB_SABME:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S0 RX SABME(%d)\n",
lapb->dev, frame->pf);
#endif
if (lapb->mode & LAPB_EXTENDED) {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S0 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S0 -> S3\n", lapb->dev);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf,
LAPB_RESPONSE);
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_3;
lapb->condition = 0x00;
lapb->n2count = 0;
lapb->vs = 0;
lapb->vr = 0;
lapb->va = 0;
lapb_connect_indication(lapb, LAPB_OK);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S0 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
}
break;
case LAPB_DISC:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S0 RX DISC(%d)\n",
lapb->dev, frame->pf);
printk(KERN_DEBUG "lapb: (%p) S0 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf, LAPB_RESPONSE);
break;
default:
break;
}
kfree_skb(skb);
}
/*
* State machine for state 1, Awaiting Connection State.
* The handling of the timer(s) is in file lapb_timer.c.
*/
static void lapb_state1_machine(struct lapb_cb *lapb, struct sk_buff *skb,
struct lapb_frame *frame)
{
switch (frame->type) {
case LAPB_SABM:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 RX SABM(%d)\n",
lapb->dev, frame->pf);
#endif
if (lapb->mode & LAPB_EXTENDED) {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf,
LAPB_RESPONSE);
}
break;
case LAPB_SABME:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 RX SABME(%d)\n",
lapb->dev, frame->pf);
#endif
if (lapb->mode & LAPB_EXTENDED) {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf,
LAPB_RESPONSE);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
}
break;
case LAPB_DISC:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 RX DISC(%d)\n",
lapb->dev, frame->pf);
printk(KERN_DEBUG "lapb: (%p) S1 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf, LAPB_RESPONSE);
break;
case LAPB_UA:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 RX UA(%d)\n",
lapb->dev, frame->pf);
#endif
if (frame->pf) {
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S1 -> S3\n", lapb->dev);
#endif
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_3;
lapb->condition = 0x00;
lapb->n2count = 0;
lapb->vs = 0;
lapb->vr = 0;
lapb->va = 0;
lapb_connect_confirmation(lapb, LAPB_OK);
}
break;
case LAPB_DM:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S1 RX DM(%d)\n",
lapb->dev, frame->pf);
#endif
if (frame->pf) {
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S1 -> S0\n", lapb->dev);
#endif
lapb_clear_queues(lapb);
lapb->state = LAPB_STATE_0;
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb_disconnect_indication(lapb, LAPB_REFUSED);
}
break;
}
kfree_skb(skb);
}
/*
* State machine for state 2, Awaiting Release State.
* The handling of the timer(s) is in file lapb_timer.c
*/
static void lapb_state2_machine(struct lapb_cb *lapb, struct sk_buff *skb,
struct lapb_frame *frame)
{
switch (frame->type) {
case LAPB_SABM:
case LAPB_SABME:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S2 RX {SABM,SABME}(%d)\n",
lapb->dev, frame->pf);
printk(KERN_DEBUG "lapb: (%p) S2 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf, LAPB_RESPONSE);
break;
case LAPB_DISC:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S2 RX DISC(%d)\n",
lapb->dev, frame->pf);
printk(KERN_DEBUG "lapb: (%p) S2 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf, LAPB_RESPONSE);
break;
case LAPB_UA:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S2 RX UA(%d)\n",
lapb->dev, frame->pf);
#endif
if (frame->pf) {
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S2 -> S0\n", lapb->dev);
#endif
lapb->state = LAPB_STATE_0;
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb_disconnect_confirmation(lapb, LAPB_OK);
}
break;
case LAPB_DM:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S2 RX DM(%d)\n",
lapb->dev, frame->pf);
#endif
if (frame->pf) {
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S2 -> S0\n", lapb->dev);
#endif
lapb->state = LAPB_STATE_0;
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb_disconnect_confirmation(lapb, LAPB_NOTCONNECTED);
}
break;
case LAPB_I:
case LAPB_REJ:
case LAPB_RNR:
case LAPB_RR:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S2 RX {I,REJ,RNR,RR}(%d)\n",
lapb->dev, frame->pf);
printk(KERN_DEBUG "lapb: (%p) S2 RX DM(%d)\n",
lapb->dev, frame->pf);
#endif
if (frame->pf)
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
break;
}
kfree_skb(skb);
}
/*
* State machine for state 3, Connected State.
* The handling of the timer(s) is in file lapb_timer.c
*/
static void lapb_state3_machine(struct lapb_cb *lapb, struct sk_buff *skb,
struct lapb_frame *frame)
{
int queued = 0;
int modulus = (lapb->mode & LAPB_EXTENDED) ? LAPB_EMODULUS :
LAPB_SMODULUS;
switch (frame->type) {
case LAPB_SABM:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX SABM(%d)\n",
lapb->dev, frame->pf);
#endif
if (lapb->mode & LAPB_EXTENDED) {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf,
LAPB_RESPONSE);
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->condition = 0x00;
lapb->n2count = 0;
lapb->vs = 0;
lapb->vr = 0;
lapb->va = 0;
lapb_requeue_frames(lapb);
}
break;
case LAPB_SABME:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX SABME(%d)\n",
lapb->dev, frame->pf);
#endif
if (lapb->mode & LAPB_EXTENDED) {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf,
LAPB_RESPONSE);
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->condition = 0x00;
lapb->n2count = 0;
lapb->vs = 0;
lapb->vr = 0;
lapb->va = 0;
lapb_requeue_frames(lapb);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
}
break;
case LAPB_DISC:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX DISC(%d)\n",
lapb->dev, frame->pf);
#endif
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S3 -> S0\n", lapb->dev);
#endif
lapb_clear_queues(lapb);
lapb_send_control(lapb, LAPB_UA, frame->pf, LAPB_RESPONSE);
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_0;
lapb_disconnect_indication(lapb, LAPB_OK);
break;
case LAPB_DM:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX DM(%d)\n",
lapb->dev, frame->pf);
#endif
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S3 -> S0\n", lapb->dev);
#endif
lapb_clear_queues(lapb);
lapb->state = LAPB_STATE_0;
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb_disconnect_indication(lapb, LAPB_NOTCONNECTED);
break;
case LAPB_RNR:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX RNR(%d) R%d\n",
lapb->dev, frame->pf, frame->nr);
#endif
lapb->condition |= LAPB_PEER_RX_BUSY_CONDITION;
lapb_check_need_response(lapb, frame->cr, frame->pf);
if (lapb_validate_nr(lapb, frame->nr)) {
lapb_check_iframes_acked(lapb, frame->nr);
} else {
lapb->frmr_data = *frame;
lapb->frmr_type = LAPB_FRMR_Z;
lapb_transmit_frmr(lapb);
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S3 -> S4\n", lapb->dev);
#endif
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_4;
lapb->n2count = 0;
}
break;
case LAPB_RR:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX RR(%d) R%d\n",
lapb->dev, frame->pf, frame->nr);
#endif
lapb->condition &= ~LAPB_PEER_RX_BUSY_CONDITION;
lapb_check_need_response(lapb, frame->cr, frame->pf);
if (lapb_validate_nr(lapb, frame->nr)) {
lapb_check_iframes_acked(lapb, frame->nr);
} else {
lapb->frmr_data = *frame;
lapb->frmr_type = LAPB_FRMR_Z;
lapb_transmit_frmr(lapb);
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S3 -> S4\n", lapb->dev);
#endif
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_4;
lapb->n2count = 0;
}
break;
case LAPB_REJ:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX REJ(%d) R%d\n",
lapb->dev, frame->pf, frame->nr);
#endif
lapb->condition &= ~LAPB_PEER_RX_BUSY_CONDITION;
lapb_check_need_response(lapb, frame->cr, frame->pf);
if (lapb_validate_nr(lapb, frame->nr)) {
lapb_frames_acked(lapb, frame->nr);
lapb_stop_t1timer(lapb);
lapb->n2count = 0;
lapb_requeue_frames(lapb);
} else {
lapb->frmr_data = *frame;
lapb->frmr_type = LAPB_FRMR_Z;
lapb_transmit_frmr(lapb);
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S3 -> S4\n", lapb->dev);
#endif
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_4;
lapb->n2count = 0;
}
break;
case LAPB_I:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX I(%d) S%d R%d\n",
lapb->dev, frame->pf, frame->ns, frame->nr);
#endif
if (!lapb_validate_nr(lapb, frame->nr)) {
lapb->frmr_data = *frame;
lapb->frmr_type = LAPB_FRMR_Z;
lapb_transmit_frmr(lapb);
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S3 -> S4\n", lapb->dev);
#endif
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_4;
lapb->n2count = 0;
break;
}
if (lapb->condition & LAPB_PEER_RX_BUSY_CONDITION)
lapb_frames_acked(lapb, frame->nr);
else
lapb_check_iframes_acked(lapb, frame->nr);
if (frame->ns == lapb->vr) {
int cn;
cn = lapb_data_indication(lapb, skb);
queued = 1;
/*
* If upper layer has dropped the frame, we
* basically ignore any further protocol
* processing. This will cause the peer
* to re-transmit the frame later like
* a frame lost on the wire.
*/
if (cn == NET_RX_DROP) {
printk(KERN_DEBUG "LAPB: rx congestion\n");
break;
}
lapb->vr = (lapb->vr + 1) % modulus;
lapb->condition &= ~LAPB_REJECT_CONDITION;
if (frame->pf)
lapb_enquiry_response(lapb);
else {
if (!(lapb->condition &
LAPB_ACK_PENDING_CONDITION)) {
lapb->condition |= LAPB_ACK_PENDING_CONDITION;
lapb_start_t2timer(lapb);
}
}
} else {
if (lapb->condition & LAPB_REJECT_CONDITION) {
if (frame->pf)
lapb_enquiry_response(lapb);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG
"lapb: (%p) S3 TX REJ(%d) R%d\n",
lapb->dev, frame->pf, lapb->vr);
#endif
lapb->condition |= LAPB_REJECT_CONDITION;
lapb_send_control(lapb, LAPB_REJ, frame->pf,
LAPB_RESPONSE);
lapb->condition &= ~LAPB_ACK_PENDING_CONDITION;
}
}
break;
case LAPB_FRMR:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX FRMR(%d) %02X "
"%02X %02X %02X %02X\n", lapb->dev, frame->pf,
skb->data[0], skb->data[1], skb->data[2],
skb->data[3], skb->data[4]);
#endif
lapb_establish_data_link(lapb);
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S3 -> S1\n", lapb->dev);
#endif
lapb_requeue_frames(lapb);
lapb->state = LAPB_STATE_1;
break;
case LAPB_ILLEGAL:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S3 RX ILLEGAL(%d)\n",
lapb->dev, frame->pf);
#endif
lapb->frmr_data = *frame;
lapb->frmr_type = LAPB_FRMR_W;
lapb_transmit_frmr(lapb);
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S3 -> S4\n", lapb->dev);
#endif
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_4;
lapb->n2count = 0;
break;
}
if (!queued)
kfree_skb(skb);
}
/*
* State machine for state 4, Frame Reject State.
* The handling of the timer(s) is in file lapb_timer.c.
*/
static void lapb_state4_machine(struct lapb_cb *lapb, struct sk_buff *skb,
struct lapb_frame *frame)
{
switch (frame->type) {
case LAPB_SABM:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S4 RX SABM(%d)\n",
lapb->dev, frame->pf);
#endif
if (lapb->mode & LAPB_EXTENDED) {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S4 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S4 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S4 -> S3\n", lapb->dev);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf,
LAPB_RESPONSE);
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_3;
lapb->condition = 0x00;
lapb->n2count = 0;
lapb->vs = 0;
lapb->vr = 0;
lapb->va = 0;
lapb_connect_indication(lapb, LAPB_OK);
}
break;
case LAPB_SABME:
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S4 RX SABME(%d)\n",
lapb->dev, frame->pf);
#endif
if (lapb->mode & LAPB_EXTENDED) {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S4 TX UA(%d)\n",
lapb->dev, frame->pf);
#endif
#if LAPB_DEBUG > 0
printk(KERN_DEBUG "lapb: (%p) S4 -> S3\n", lapb->dev);
#endif
lapb_send_control(lapb, LAPB_UA, frame->pf,
LAPB_RESPONSE);
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_3;
lapb->condition = 0x00;
lapb->n2count = 0;
lapb->vs = 0;
lapb->vr = 0;
lapb->va = 0;
lapb_connect_indication(lapb, LAPB_OK);
} else {
#if LAPB_DEBUG > 1
printk(KERN_DEBUG "lapb: (%p) S4 TX DM(%d)\n",
lapb->dev, frame->pf);
#endif
lapb_send_control(lapb, LAPB_DM, frame->pf,
LAPB_RESPONSE);
}
break;
}
kfree_skb(skb);
}
/*
* Process an incoming LAPB frame
*/
void lapb_data_input(struct lapb_cb *lapb, struct sk_buff *skb)
{
struct lapb_frame frame;
if (lapb_decode(lapb, skb, &frame) < 0) {
kfree_skb(skb);
return;
}
switch (lapb->state) {
case LAPB_STATE_0:
lapb_state0_machine(lapb, skb, &frame); break;
case LAPB_STATE_1:
lapb_state1_machine(lapb, skb, &frame); break;
case LAPB_STATE_2:
lapb_state2_machine(lapb, skb, &frame); break;
case LAPB_STATE_3:
lapb_state3_machine(lapb, skb, &frame); break;
case LAPB_STATE_4:
lapb_state4_machine(lapb, skb, &frame); break;
}
lapb_kick(lapb);
}
| gpl-2.0 |
TeamOrion-Devices/kernel_sony_msm8x27 | drivers/media/video/cx25840/cx25840-ir.c | 5062 | 36370 | /*
* Driver for the Conexant CX2584x Audio/Video decoder chip and related cores
*
* Integrated Consumer Infrared Controller
*
* Copyright (C) 2010 Andy Walls <awalls@md.metrocast.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/slab.h>
#include <linux/kfifo.h>
#include <linux/module.h>
#include <media/cx25840.h>
#include <media/rc-core.h>
#include "cx25840-core.h"
static unsigned int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug, "enable integrated IR debug messages");
#define CX25840_IR_REG_BASE 0x200
#define CX25840_IR_CNTRL_REG 0x200
#define CNTRL_WIN_3_3 0x00000000
#define CNTRL_WIN_4_3 0x00000001
#define CNTRL_WIN_3_4 0x00000002
#define CNTRL_WIN_4_4 0x00000003
#define CNTRL_WIN 0x00000003
#define CNTRL_EDG_NONE 0x00000000
#define CNTRL_EDG_FALL 0x00000004
#define CNTRL_EDG_RISE 0x00000008
#define CNTRL_EDG_BOTH 0x0000000C
#define CNTRL_EDG 0x0000000C
#define CNTRL_DMD 0x00000010
#define CNTRL_MOD 0x00000020
#define CNTRL_RFE 0x00000040
#define CNTRL_TFE 0x00000080
#define CNTRL_RXE 0x00000100
#define CNTRL_TXE 0x00000200
#define CNTRL_RIC 0x00000400
#define CNTRL_TIC 0x00000800
#define CNTRL_CPL 0x00001000
#define CNTRL_LBM 0x00002000
#define CNTRL_R 0x00004000
#define CX25840_IR_TXCLK_REG 0x204
#define TXCLK_TCD 0x0000FFFF
#define CX25840_IR_RXCLK_REG 0x208
#define RXCLK_RCD 0x0000FFFF
#define CX25840_IR_CDUTY_REG 0x20C
#define CDUTY_CDC 0x0000000F
#define CX25840_IR_STATS_REG 0x210
#define STATS_RTO 0x00000001
#define STATS_ROR 0x00000002
#define STATS_RBY 0x00000004
#define STATS_TBY 0x00000008
#define STATS_RSR 0x00000010
#define STATS_TSR 0x00000020
#define CX25840_IR_IRQEN_REG 0x214
#define IRQEN_RTE 0x00000001
#define IRQEN_ROE 0x00000002
#define IRQEN_RSE 0x00000010
#define IRQEN_TSE 0x00000020
#define IRQEN_MSK 0x00000033
#define CX25840_IR_FILTR_REG 0x218
#define FILTR_LPF 0x0000FFFF
#define CX25840_IR_FIFO_REG 0x23C
#define FIFO_RXTX 0x0000FFFF
#define FIFO_RXTX_LVL 0x00010000
#define FIFO_RXTX_RTO 0x0001FFFF
#define FIFO_RX_NDV 0x00020000
#define FIFO_RX_DEPTH 8
#define FIFO_TX_DEPTH 8
#define CX25840_VIDCLK_FREQ 108000000 /* 108 MHz, BT.656 */
#define CX25840_IR_REFCLK_FREQ (CX25840_VIDCLK_FREQ / 2)
/*
* We use this union internally for convenience, but callers to tx_write
* and rx_read will be expecting records of type struct ir_raw_event.
* Always ensure the size of this union is dictated by struct ir_raw_event.
*/
union cx25840_ir_fifo_rec {
u32 hw_fifo_data;
struct ir_raw_event ir_core_data;
};
#define CX25840_IR_RX_KFIFO_SIZE (256 * sizeof(union cx25840_ir_fifo_rec))
#define CX25840_IR_TX_KFIFO_SIZE (256 * sizeof(union cx25840_ir_fifo_rec))
struct cx25840_ir_state {
struct i2c_client *c;
struct v4l2_subdev_ir_parameters rx_params;
struct mutex rx_params_lock; /* protects Rx parameter settings cache */
atomic_t rxclk_divider;
atomic_t rx_invert;
struct kfifo rx_kfifo;
spinlock_t rx_kfifo_lock; /* protect Rx data kfifo */
struct v4l2_subdev_ir_parameters tx_params;
struct mutex tx_params_lock; /* protects Tx parameter settings cache */
atomic_t txclk_divider;
};
static inline struct cx25840_ir_state *to_ir_state(struct v4l2_subdev *sd)
{
struct cx25840_state *state = to_state(sd);
return state ? state->ir_state : NULL;
}
/*
* Rx and Tx Clock Divider register computations
*
* Note the largest clock divider value of 0xffff corresponds to:
* (0xffff + 1) * 1000 / 108/2 MHz = 1,213,629.629... ns
* which fits in 21 bits, so we'll use unsigned int for time arguments.
*/
static inline u16 count_to_clock_divider(unsigned int d)
{
if (d > RXCLK_RCD + 1)
d = RXCLK_RCD;
else if (d < 2)
d = 1;
else
d--;
return (u16) d;
}
static inline u16 ns_to_clock_divider(unsigned int ns)
{
return count_to_clock_divider(
DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ / 1000000 * ns, 1000));
}
static inline unsigned int clock_divider_to_ns(unsigned int divider)
{
/* Period of the Rx or Tx clock in ns */
return DIV_ROUND_CLOSEST((divider + 1) * 1000,
CX25840_IR_REFCLK_FREQ / 1000000);
}
static inline u16 carrier_freq_to_clock_divider(unsigned int freq)
{
return count_to_clock_divider(
DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, freq * 16));
}
static inline unsigned int clock_divider_to_carrier_freq(unsigned int divider)
{
return DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, (divider + 1) * 16);
}
static inline u16 freq_to_clock_divider(unsigned int freq,
unsigned int rollovers)
{
return count_to_clock_divider(
DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, freq * rollovers));
}
static inline unsigned int clock_divider_to_freq(unsigned int divider,
unsigned int rollovers)
{
return DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ,
(divider + 1) * rollovers);
}
/*
* Low Pass Filter register calculations
*
* Note the largest count value of 0xffff corresponds to:
* 0xffff * 1000 / 108/2 MHz = 1,213,611.11... ns
* which fits in 21 bits, so we'll use unsigned int for time arguments.
*/
static inline u16 count_to_lpf_count(unsigned int d)
{
if (d > FILTR_LPF)
d = FILTR_LPF;
else if (d < 4)
d = 0;
return (u16) d;
}
static inline u16 ns_to_lpf_count(unsigned int ns)
{
return count_to_lpf_count(
DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ / 1000000 * ns, 1000));
}
static inline unsigned int lpf_count_to_ns(unsigned int count)
{
/* Duration of the Low Pass Filter rejection window in ns */
return DIV_ROUND_CLOSEST(count * 1000,
CX25840_IR_REFCLK_FREQ / 1000000);
}
static inline unsigned int lpf_count_to_us(unsigned int count)
{
/* Duration of the Low Pass Filter rejection window in us */
return DIV_ROUND_CLOSEST(count, CX25840_IR_REFCLK_FREQ / 1000000);
}
/*
* FIFO register pulse width count compuations
*/
static u32 clock_divider_to_resolution(u16 divider)
{
/*
* Resolution is the duration of 1 tick of the readable portion of
* of the pulse width counter as read from the FIFO. The two lsb's are
* not readable, hence the << 2. This function returns ns.
*/
return DIV_ROUND_CLOSEST((1 << 2) * ((u32) divider + 1) * 1000,
CX25840_IR_REFCLK_FREQ / 1000000);
}
static u64 pulse_width_count_to_ns(u16 count, u16 divider)
{
u64 n;
u32 rem;
/*
* The 2 lsb's of the pulse width timer count are not readable, hence
* the (count << 2) | 0x3
*/
n = (((u64) count << 2) | 0x3) * (divider + 1) * 1000; /* millicycles */
rem = do_div(n, CX25840_IR_REFCLK_FREQ / 1000000); /* / MHz => ns */
if (rem >= CX25840_IR_REFCLK_FREQ / 1000000 / 2)
n++;
return n;
}
#if 0
/* Keep as we will need this for Transmit functionality */
static u16 ns_to_pulse_width_count(u32 ns, u16 divider)
{
u64 n;
u32 d;
u32 rem;
/*
* The 2 lsb's of the pulse width timer count are not accessible, hence
* the (1 << 2)
*/
n = ((u64) ns) * CX25840_IR_REFCLK_FREQ / 1000000; /* millicycles */
d = (1 << 2) * ((u32) divider + 1) * 1000; /* millicycles/count */
rem = do_div(n, d);
if (rem >= d / 2)
n++;
if (n > FIFO_RXTX)
n = FIFO_RXTX;
else if (n == 0)
n = 1;
return (u16) n;
}
#endif
static unsigned int pulse_width_count_to_us(u16 count, u16 divider)
{
u64 n;
u32 rem;
/*
* The 2 lsb's of the pulse width timer count are not readable, hence
* the (count << 2) | 0x3
*/
n = (((u64) count << 2) | 0x3) * (divider + 1); /* cycles */
rem = do_div(n, CX25840_IR_REFCLK_FREQ / 1000000); /* / MHz => us */
if (rem >= CX25840_IR_REFCLK_FREQ / 1000000 / 2)
n++;
return (unsigned int) n;
}
/*
* Pulse Clocks computations: Combined Pulse Width Count & Rx Clock Counts
*
* The total pulse clock count is an 18 bit pulse width timer count as the most
* significant part and (up to) 16 bit clock divider count as a modulus.
* When the Rx clock divider ticks down to 0, it increments the 18 bit pulse
* width timer count's least significant bit.
*/
static u64 ns_to_pulse_clocks(u32 ns)
{
u64 clocks;
u32 rem;
clocks = CX25840_IR_REFCLK_FREQ / 1000000 * (u64) ns; /* millicycles */
rem = do_div(clocks, 1000); /* /1000 = cycles */
if (rem >= 1000 / 2)
clocks++;
return clocks;
}
static u16 pulse_clocks_to_clock_divider(u64 count)
{
u32 rem;
rem = do_div(count, (FIFO_RXTX << 2) | 0x3);
/* net result needs to be rounded down and decremented by 1 */
if (count > RXCLK_RCD + 1)
count = RXCLK_RCD;
else if (count < 2)
count = 1;
else
count--;
return (u16) count;
}
/*
* IR Control Register helpers
*/
enum tx_fifo_watermark {
TX_FIFO_HALF_EMPTY = 0,
TX_FIFO_EMPTY = CNTRL_TIC,
};
enum rx_fifo_watermark {
RX_FIFO_HALF_FULL = 0,
RX_FIFO_NOT_EMPTY = CNTRL_RIC,
};
static inline void control_tx_irq_watermark(struct i2c_client *c,
enum tx_fifo_watermark level)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_TIC, level);
}
static inline void control_rx_irq_watermark(struct i2c_client *c,
enum rx_fifo_watermark level)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_RIC, level);
}
static inline void control_tx_enable(struct i2c_client *c, bool enable)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~(CNTRL_TXE | CNTRL_TFE),
enable ? (CNTRL_TXE | CNTRL_TFE) : 0);
}
static inline void control_rx_enable(struct i2c_client *c, bool enable)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~(CNTRL_RXE | CNTRL_RFE),
enable ? (CNTRL_RXE | CNTRL_RFE) : 0);
}
static inline void control_tx_modulation_enable(struct i2c_client *c,
bool enable)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_MOD,
enable ? CNTRL_MOD : 0);
}
static inline void control_rx_demodulation_enable(struct i2c_client *c,
bool enable)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_DMD,
enable ? CNTRL_DMD : 0);
}
static inline void control_rx_s_edge_detection(struct i2c_client *c,
u32 edge_types)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_EDG_BOTH,
edge_types & CNTRL_EDG_BOTH);
}
static void control_rx_s_carrier_window(struct i2c_client *c,
unsigned int carrier,
unsigned int *carrier_range_low,
unsigned int *carrier_range_high)
{
u32 v;
unsigned int c16 = carrier * 16;
if (*carrier_range_low < DIV_ROUND_CLOSEST(c16, 16 + 3)) {
v = CNTRL_WIN_3_4;
*carrier_range_low = DIV_ROUND_CLOSEST(c16, 16 + 4);
} else {
v = CNTRL_WIN_3_3;
*carrier_range_low = DIV_ROUND_CLOSEST(c16, 16 + 3);
}
if (*carrier_range_high > DIV_ROUND_CLOSEST(c16, 16 - 3)) {
v |= CNTRL_WIN_4_3;
*carrier_range_high = DIV_ROUND_CLOSEST(c16, 16 - 4);
} else {
v |= CNTRL_WIN_3_3;
*carrier_range_high = DIV_ROUND_CLOSEST(c16, 16 - 3);
}
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_WIN, v);
}
static inline void control_tx_polarity_invert(struct i2c_client *c,
bool invert)
{
cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_CPL,
invert ? CNTRL_CPL : 0);
}
/*
* IR Rx & Tx Clock Register helpers
*/
static unsigned int txclk_tx_s_carrier(struct i2c_client *c,
unsigned int freq,
u16 *divider)
{
*divider = carrier_freq_to_clock_divider(freq);
cx25840_write4(c, CX25840_IR_TXCLK_REG, *divider);
return clock_divider_to_carrier_freq(*divider);
}
static unsigned int rxclk_rx_s_carrier(struct i2c_client *c,
unsigned int freq,
u16 *divider)
{
*divider = carrier_freq_to_clock_divider(freq);
cx25840_write4(c, CX25840_IR_RXCLK_REG, *divider);
return clock_divider_to_carrier_freq(*divider);
}
static u32 txclk_tx_s_max_pulse_width(struct i2c_client *c, u32 ns,
u16 *divider)
{
u64 pulse_clocks;
if (ns > IR_MAX_DURATION)
ns = IR_MAX_DURATION;
pulse_clocks = ns_to_pulse_clocks(ns);
*divider = pulse_clocks_to_clock_divider(pulse_clocks);
cx25840_write4(c, CX25840_IR_TXCLK_REG, *divider);
return (u32) pulse_width_count_to_ns(FIFO_RXTX, *divider);
}
static u32 rxclk_rx_s_max_pulse_width(struct i2c_client *c, u32 ns,
u16 *divider)
{
u64 pulse_clocks;
if (ns > IR_MAX_DURATION)
ns = IR_MAX_DURATION;
pulse_clocks = ns_to_pulse_clocks(ns);
*divider = pulse_clocks_to_clock_divider(pulse_clocks);
cx25840_write4(c, CX25840_IR_RXCLK_REG, *divider);
return (u32) pulse_width_count_to_ns(FIFO_RXTX, *divider);
}
/*
* IR Tx Carrier Duty Cycle register helpers
*/
static unsigned int cduty_tx_s_duty_cycle(struct i2c_client *c,
unsigned int duty_cycle)
{
u32 n;
n = DIV_ROUND_CLOSEST(duty_cycle * 100, 625); /* 16ths of 100% */
if (n != 0)
n--;
if (n > 15)
n = 15;
cx25840_write4(c, CX25840_IR_CDUTY_REG, n);
return DIV_ROUND_CLOSEST((n + 1) * 100, 16);
}
/*
* IR Filter Register helpers
*/
static u32 filter_rx_s_min_width(struct i2c_client *c, u32 min_width_ns)
{
u32 count = ns_to_lpf_count(min_width_ns);
cx25840_write4(c, CX25840_IR_FILTR_REG, count);
return lpf_count_to_ns(count);
}
/*
* IR IRQ Enable Register helpers
*/
static inline void irqenable_rx(struct v4l2_subdev *sd, u32 mask)
{
struct cx25840_state *state = to_state(sd);
if (is_cx23885(state) || is_cx23887(state))
mask ^= IRQEN_MSK;
mask &= (IRQEN_RTE | IRQEN_ROE | IRQEN_RSE);
cx25840_and_or4(state->c, CX25840_IR_IRQEN_REG,
~(IRQEN_RTE | IRQEN_ROE | IRQEN_RSE), mask);
}
static inline void irqenable_tx(struct v4l2_subdev *sd, u32 mask)
{
struct cx25840_state *state = to_state(sd);
if (is_cx23885(state) || is_cx23887(state))
mask ^= IRQEN_MSK;
mask &= IRQEN_TSE;
cx25840_and_or4(state->c, CX25840_IR_IRQEN_REG, ~IRQEN_TSE, mask);
}
/*
* V4L2 Subdevice IR Ops
*/
int cx25840_ir_irq_handler(struct v4l2_subdev *sd, u32 status, bool *handled)
{
struct cx25840_state *state = to_state(sd);
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c = NULL;
unsigned long flags;
union cx25840_ir_fifo_rec rx_data[FIFO_RX_DEPTH];
unsigned int i, j, k;
u32 events, v;
int tsr, rsr, rto, ror, tse, rse, rte, roe, kror;
u32 cntrl, irqen, stats;
*handled = false;
if (ir_state == NULL)
return -ENODEV;
c = ir_state->c;
/* Only support the IR controller for the CX2388[57] AV Core for now */
if (!(is_cx23885(state) || is_cx23887(state)))
return -ENODEV;
cntrl = cx25840_read4(c, CX25840_IR_CNTRL_REG);
irqen = cx25840_read4(c, CX25840_IR_IRQEN_REG);
if (is_cx23885(state) || is_cx23887(state))
irqen ^= IRQEN_MSK;
stats = cx25840_read4(c, CX25840_IR_STATS_REG);
tsr = stats & STATS_TSR; /* Tx FIFO Service Request */
rsr = stats & STATS_RSR; /* Rx FIFO Service Request */
rto = stats & STATS_RTO; /* Rx Pulse Width Timer Time Out */
ror = stats & STATS_ROR; /* Rx FIFO Over Run */
tse = irqen & IRQEN_TSE; /* Tx FIFO Service Request IRQ Enable */
rse = irqen & IRQEN_RSE; /* Rx FIFO Service Reuqest IRQ Enable */
rte = irqen & IRQEN_RTE; /* Rx Pulse Width Timer Time Out IRQ Enable */
roe = irqen & IRQEN_ROE; /* Rx FIFO Over Run IRQ Enable */
v4l2_dbg(2, ir_debug, sd, "IR IRQ Status: %s %s %s %s %s %s\n",
tsr ? "tsr" : " ", rsr ? "rsr" : " ",
rto ? "rto" : " ", ror ? "ror" : " ",
stats & STATS_TBY ? "tby" : " ",
stats & STATS_RBY ? "rby" : " ");
v4l2_dbg(2, ir_debug, sd, "IR IRQ Enables: %s %s %s %s\n",
tse ? "tse" : " ", rse ? "rse" : " ",
rte ? "rte" : " ", roe ? "roe" : " ");
/*
* Transmitter interrupt service
*/
if (tse && tsr) {
/*
* TODO:
* Check the watermark threshold setting
* Pull FIFO_TX_DEPTH or FIFO_TX_DEPTH/2 entries from tx_kfifo
* Push the data to the hardware FIFO.
* If there was nothing more to send in the tx_kfifo, disable
* the TSR IRQ and notify the v4l2_device.
* If there was something in the tx_kfifo, check the tx_kfifo
* level and notify the v4l2_device, if it is low.
*/
/* For now, inhibit TSR interrupt until Tx is implemented */
irqenable_tx(sd, 0);
events = V4L2_SUBDEV_IR_TX_FIFO_SERVICE_REQ;
v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_TX_NOTIFY, &events);
*handled = true;
}
/*
* Receiver interrupt service
*/
kror = 0;
if ((rse && rsr) || (rte && rto)) {
/*
* Receive data on RSR to clear the STATS_RSR.
* Receive data on RTO, since we may not have yet hit the RSR
* watermark when we receive the RTO.
*/
for (i = 0, v = FIFO_RX_NDV;
(v & FIFO_RX_NDV) && !kror; i = 0) {
for (j = 0;
(v & FIFO_RX_NDV) && j < FIFO_RX_DEPTH; j++) {
v = cx25840_read4(c, CX25840_IR_FIFO_REG);
rx_data[i].hw_fifo_data = v & ~FIFO_RX_NDV;
i++;
}
if (i == 0)
break;
j = i * sizeof(union cx25840_ir_fifo_rec);
k = kfifo_in_locked(&ir_state->rx_kfifo,
(unsigned char *) rx_data, j,
&ir_state->rx_kfifo_lock);
if (k != j)
kror++; /* rx_kfifo over run */
}
*handled = true;
}
events = 0;
v = 0;
if (kror) {
events |= V4L2_SUBDEV_IR_RX_SW_FIFO_OVERRUN;
v4l2_err(sd, "IR receiver software FIFO overrun\n");
}
if (roe && ror) {
/*
* The RX FIFO Enable (CNTRL_RFE) must be toggled to clear
* the Rx FIFO Over Run status (STATS_ROR)
*/
v |= CNTRL_RFE;
events |= V4L2_SUBDEV_IR_RX_HW_FIFO_OVERRUN;
v4l2_err(sd, "IR receiver hardware FIFO overrun\n");
}
if (rte && rto) {
/*
* The IR Receiver Enable (CNTRL_RXE) must be toggled to clear
* the Rx Pulse Width Timer Time Out (STATS_RTO)
*/
v |= CNTRL_RXE;
events |= V4L2_SUBDEV_IR_RX_END_OF_RX_DETECTED;
}
if (v) {
/* Clear STATS_ROR & STATS_RTO as needed by reseting hardware */
cx25840_write4(c, CX25840_IR_CNTRL_REG, cntrl & ~v);
cx25840_write4(c, CX25840_IR_CNTRL_REG, cntrl);
*handled = true;
}
spin_lock_irqsave(&ir_state->rx_kfifo_lock, flags);
if (kfifo_len(&ir_state->rx_kfifo) >= CX25840_IR_RX_KFIFO_SIZE / 2)
events |= V4L2_SUBDEV_IR_RX_FIFO_SERVICE_REQ;
spin_unlock_irqrestore(&ir_state->rx_kfifo_lock, flags);
if (events)
v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_RX_NOTIFY, &events);
return 0;
}
/* Receiver */
static int cx25840_ir_rx_read(struct v4l2_subdev *sd, u8 *buf, size_t count,
ssize_t *num)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
bool invert;
u16 divider;
unsigned int i, n;
union cx25840_ir_fifo_rec *p;
unsigned u, v, w;
if (ir_state == NULL)
return -ENODEV;
invert = (bool) atomic_read(&ir_state->rx_invert);
divider = (u16) atomic_read(&ir_state->rxclk_divider);
n = count / sizeof(union cx25840_ir_fifo_rec)
* sizeof(union cx25840_ir_fifo_rec);
if (n == 0) {
*num = 0;
return 0;
}
n = kfifo_out_locked(&ir_state->rx_kfifo, buf, n,
&ir_state->rx_kfifo_lock);
n /= sizeof(union cx25840_ir_fifo_rec);
*num = n * sizeof(union cx25840_ir_fifo_rec);
for (p = (union cx25840_ir_fifo_rec *) buf, i = 0; i < n; p++, i++) {
if ((p->hw_fifo_data & FIFO_RXTX_RTO) == FIFO_RXTX_RTO) {
/* Assume RTO was because of no IR light input */
u = 0;
w = 1;
} else {
u = (p->hw_fifo_data & FIFO_RXTX_LVL) ? 1 : 0;
if (invert)
u = u ? 0 : 1;
w = 0;
}
v = (unsigned) pulse_width_count_to_ns(
(u16) (p->hw_fifo_data & FIFO_RXTX), divider);
if (v > IR_MAX_DURATION)
v = IR_MAX_DURATION;
init_ir_raw_event(&p->ir_core_data);
p->ir_core_data.pulse = u;
p->ir_core_data.duration = v;
p->ir_core_data.timeout = w;
v4l2_dbg(2, ir_debug, sd, "rx read: %10u ns %s %s\n",
v, u ? "mark" : "space", w ? "(timed out)" : "");
if (w)
v4l2_dbg(2, ir_debug, sd, "rx read: end of rx\n");
}
return 0;
}
static int cx25840_ir_rx_g_parameters(struct v4l2_subdev *sd,
struct v4l2_subdev_ir_parameters *p)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
if (ir_state == NULL)
return -ENODEV;
mutex_lock(&ir_state->rx_params_lock);
memcpy(p, &ir_state->rx_params,
sizeof(struct v4l2_subdev_ir_parameters));
mutex_unlock(&ir_state->rx_params_lock);
return 0;
}
static int cx25840_ir_rx_shutdown(struct v4l2_subdev *sd)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
if (ir_state == NULL)
return -ENODEV;
c = ir_state->c;
mutex_lock(&ir_state->rx_params_lock);
/* Disable or slow down all IR Rx circuits and counters */
irqenable_rx(sd, 0);
control_rx_enable(c, false);
control_rx_demodulation_enable(c, false);
control_rx_s_edge_detection(c, CNTRL_EDG_NONE);
filter_rx_s_min_width(c, 0);
cx25840_write4(c, CX25840_IR_RXCLK_REG, RXCLK_RCD);
ir_state->rx_params.shutdown = true;
mutex_unlock(&ir_state->rx_params_lock);
return 0;
}
static int cx25840_ir_rx_s_parameters(struct v4l2_subdev *sd,
struct v4l2_subdev_ir_parameters *p)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
struct v4l2_subdev_ir_parameters *o;
u16 rxclk_divider;
if (ir_state == NULL)
return -ENODEV;
if (p->shutdown)
return cx25840_ir_rx_shutdown(sd);
if (p->mode != V4L2_SUBDEV_IR_MODE_PULSE_WIDTH)
return -ENOSYS;
c = ir_state->c;
o = &ir_state->rx_params;
mutex_lock(&ir_state->rx_params_lock);
o->shutdown = p->shutdown;
p->mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH;
o->mode = p->mode;
p->bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec);
o->bytes_per_data_element = p->bytes_per_data_element;
/* Before we tweak the hardware, we have to disable the receiver */
irqenable_rx(sd, 0);
control_rx_enable(c, false);
control_rx_demodulation_enable(c, p->modulation);
o->modulation = p->modulation;
if (p->modulation) {
p->carrier_freq = rxclk_rx_s_carrier(c, p->carrier_freq,
&rxclk_divider);
o->carrier_freq = p->carrier_freq;
p->duty_cycle = 50;
o->duty_cycle = p->duty_cycle;
control_rx_s_carrier_window(c, p->carrier_freq,
&p->carrier_range_lower,
&p->carrier_range_upper);
o->carrier_range_lower = p->carrier_range_lower;
o->carrier_range_upper = p->carrier_range_upper;
p->max_pulse_width =
(u32) pulse_width_count_to_ns(FIFO_RXTX, rxclk_divider);
} else {
p->max_pulse_width =
rxclk_rx_s_max_pulse_width(c, p->max_pulse_width,
&rxclk_divider);
}
o->max_pulse_width = p->max_pulse_width;
atomic_set(&ir_state->rxclk_divider, rxclk_divider);
p->noise_filter_min_width =
filter_rx_s_min_width(c, p->noise_filter_min_width);
o->noise_filter_min_width = p->noise_filter_min_width;
p->resolution = clock_divider_to_resolution(rxclk_divider);
o->resolution = p->resolution;
/* FIXME - make this dependent on resolution for better performance */
control_rx_irq_watermark(c, RX_FIFO_HALF_FULL);
control_rx_s_edge_detection(c, CNTRL_EDG_BOTH);
o->invert_level = p->invert_level;
atomic_set(&ir_state->rx_invert, p->invert_level);
o->interrupt_enable = p->interrupt_enable;
o->enable = p->enable;
if (p->enable) {
unsigned long flags;
spin_lock_irqsave(&ir_state->rx_kfifo_lock, flags);
kfifo_reset(&ir_state->rx_kfifo);
spin_unlock_irqrestore(&ir_state->rx_kfifo_lock, flags);
if (p->interrupt_enable)
irqenable_rx(sd, IRQEN_RSE | IRQEN_RTE | IRQEN_ROE);
control_rx_enable(c, p->enable);
}
mutex_unlock(&ir_state->rx_params_lock);
return 0;
}
/* Transmitter */
static int cx25840_ir_tx_write(struct v4l2_subdev *sd, u8 *buf, size_t count,
ssize_t *num)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
if (ir_state == NULL)
return -ENODEV;
c = ir_state->c;
#if 0
/*
* FIXME - the code below is an incomplete and untested sketch of what
* may need to be done. The critical part is to get 4 (or 8) pulses
* from the tx_kfifo, or converted from ns to the proper units from the
* input, and push them off to the hardware Tx FIFO right away, if the
* HW TX fifo needs service. The rest can be pushed to the tx_kfifo in
* a less critical timeframe. Also watch out for overruning the
* tx_kfifo - don't let it happen and let the caller know not all his
* pulses were written.
*/
u32 *ns_pulse = (u32 *) buf;
unsigned int n;
u32 fifo_pulse[FIFO_TX_DEPTH];
u32 mark;
/* Compute how much we can fit in the tx kfifo */
n = CX25840_IR_TX_KFIFO_SIZE - kfifo_len(ir_state->tx_kfifo);
n = min(n, (unsigned int) count);
n /= sizeof(u32);
/* FIXME - turn on Tx Fifo service interrupt
* check hardware fifo level, and other stuff
*/
for (i = 0; i < n; ) {
for (j = 0; j < FIFO_TX_DEPTH / 2 && i < n; j++) {
mark = ns_pulse[i] & LEVEL_MASK;
fifo_pulse[j] = ns_to_pulse_width_count(
ns_pulse[i] &
~LEVEL_MASK,
ir_state->txclk_divider);
if (mark)
fifo_pulse[j] &= FIFO_RXTX_LVL;
i++;
}
kfifo_put(ir_state->tx_kfifo, (u8 *) fifo_pulse,
j * sizeof(u32));
}
*num = n * sizeof(u32);
#else
/* For now enable the Tx FIFO Service interrupt & pretend we did work */
irqenable_tx(sd, IRQEN_TSE);
*num = count;
#endif
return 0;
}
static int cx25840_ir_tx_g_parameters(struct v4l2_subdev *sd,
struct v4l2_subdev_ir_parameters *p)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
if (ir_state == NULL)
return -ENODEV;
mutex_lock(&ir_state->tx_params_lock);
memcpy(p, &ir_state->tx_params,
sizeof(struct v4l2_subdev_ir_parameters));
mutex_unlock(&ir_state->tx_params_lock);
return 0;
}
static int cx25840_ir_tx_shutdown(struct v4l2_subdev *sd)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
if (ir_state == NULL)
return -ENODEV;
c = ir_state->c;
mutex_lock(&ir_state->tx_params_lock);
/* Disable or slow down all IR Tx circuits and counters */
irqenable_tx(sd, 0);
control_tx_enable(c, false);
control_tx_modulation_enable(c, false);
cx25840_write4(c, CX25840_IR_TXCLK_REG, TXCLK_TCD);
ir_state->tx_params.shutdown = true;
mutex_unlock(&ir_state->tx_params_lock);
return 0;
}
static int cx25840_ir_tx_s_parameters(struct v4l2_subdev *sd,
struct v4l2_subdev_ir_parameters *p)
{
struct cx25840_ir_state *ir_state = to_ir_state(sd);
struct i2c_client *c;
struct v4l2_subdev_ir_parameters *o;
u16 txclk_divider;
if (ir_state == NULL)
return -ENODEV;
if (p->shutdown)
return cx25840_ir_tx_shutdown(sd);
if (p->mode != V4L2_SUBDEV_IR_MODE_PULSE_WIDTH)
return -ENOSYS;
c = ir_state->c;
o = &ir_state->tx_params;
mutex_lock(&ir_state->tx_params_lock);
o->shutdown = p->shutdown;
p->mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH;
o->mode = p->mode;
p->bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec);
o->bytes_per_data_element = p->bytes_per_data_element;
/* Before we tweak the hardware, we have to disable the transmitter */
irqenable_tx(sd, 0);
control_tx_enable(c, false);
control_tx_modulation_enable(c, p->modulation);
o->modulation = p->modulation;
if (p->modulation) {
p->carrier_freq = txclk_tx_s_carrier(c, p->carrier_freq,
&txclk_divider);
o->carrier_freq = p->carrier_freq;
p->duty_cycle = cduty_tx_s_duty_cycle(c, p->duty_cycle);
o->duty_cycle = p->duty_cycle;
p->max_pulse_width =
(u32) pulse_width_count_to_ns(FIFO_RXTX, txclk_divider);
} else {
p->max_pulse_width =
txclk_tx_s_max_pulse_width(c, p->max_pulse_width,
&txclk_divider);
}
o->max_pulse_width = p->max_pulse_width;
atomic_set(&ir_state->txclk_divider, txclk_divider);
p->resolution = clock_divider_to_resolution(txclk_divider);
o->resolution = p->resolution;
/* FIXME - make this dependent on resolution for better performance */
control_tx_irq_watermark(c, TX_FIFO_HALF_EMPTY);
control_tx_polarity_invert(c, p->invert_carrier_sense);
o->invert_carrier_sense = p->invert_carrier_sense;
/*
* FIXME: we don't have hardware help for IO pin level inversion
* here like we have on the CX23888.
* Act on this with some mix of logical inversion of data levels,
* carrier polarity, and carrier duty cycle.
*/
o->invert_level = p->invert_level;
o->interrupt_enable = p->interrupt_enable;
o->enable = p->enable;
if (p->enable) {
/* reset tx_fifo here */
if (p->interrupt_enable)
irqenable_tx(sd, IRQEN_TSE);
control_tx_enable(c, p->enable);
}
mutex_unlock(&ir_state->tx_params_lock);
return 0;
}
/*
* V4L2 Subdevice Core Ops support
*/
int cx25840_ir_log_status(struct v4l2_subdev *sd)
{
struct cx25840_state *state = to_state(sd);
struct i2c_client *c = state->c;
char *s;
int i, j;
u32 cntrl, txclk, rxclk, cduty, stats, irqen, filtr;
/* The CX23888 chip doesn't have an IR controller on the A/V core */
if (is_cx23888(state))
return 0;
cntrl = cx25840_read4(c, CX25840_IR_CNTRL_REG);
txclk = cx25840_read4(c, CX25840_IR_TXCLK_REG) & TXCLK_TCD;
rxclk = cx25840_read4(c, CX25840_IR_RXCLK_REG) & RXCLK_RCD;
cduty = cx25840_read4(c, CX25840_IR_CDUTY_REG) & CDUTY_CDC;
stats = cx25840_read4(c, CX25840_IR_STATS_REG);
irqen = cx25840_read4(c, CX25840_IR_IRQEN_REG);
if (is_cx23885(state) || is_cx23887(state))
irqen ^= IRQEN_MSK;
filtr = cx25840_read4(c, CX25840_IR_FILTR_REG) & FILTR_LPF;
v4l2_info(sd, "IR Receiver:\n");
v4l2_info(sd, "\tEnabled: %s\n",
cntrl & CNTRL_RXE ? "yes" : "no");
v4l2_info(sd, "\tDemodulation from a carrier: %s\n",
cntrl & CNTRL_DMD ? "enabled" : "disabled");
v4l2_info(sd, "\tFIFO: %s\n",
cntrl & CNTRL_RFE ? "enabled" : "disabled");
switch (cntrl & CNTRL_EDG) {
case CNTRL_EDG_NONE:
s = "disabled";
break;
case CNTRL_EDG_FALL:
s = "falling edge";
break;
case CNTRL_EDG_RISE:
s = "rising edge";
break;
case CNTRL_EDG_BOTH:
s = "rising & falling edges";
break;
default:
s = "??? edge";
break;
}
v4l2_info(sd, "\tPulse timers' start/stop trigger: %s\n", s);
v4l2_info(sd, "\tFIFO data on pulse timer overflow: %s\n",
cntrl & CNTRL_R ? "not loaded" : "overflow marker");
v4l2_info(sd, "\tFIFO interrupt watermark: %s\n",
cntrl & CNTRL_RIC ? "not empty" : "half full or greater");
v4l2_info(sd, "\tLoopback mode: %s\n",
cntrl & CNTRL_LBM ? "loopback active" : "normal receive");
if (cntrl & CNTRL_DMD) {
v4l2_info(sd, "\tExpected carrier (16 clocks): %u Hz\n",
clock_divider_to_carrier_freq(rxclk));
switch (cntrl & CNTRL_WIN) {
case CNTRL_WIN_3_3:
i = 3;
j = 3;
break;
case CNTRL_WIN_4_3:
i = 4;
j = 3;
break;
case CNTRL_WIN_3_4:
i = 3;
j = 4;
break;
case CNTRL_WIN_4_4:
i = 4;
j = 4;
break;
default:
i = 0;
j = 0;
break;
}
v4l2_info(sd, "\tNext carrier edge window: 16 clocks "
"-%1d/+%1d, %u to %u Hz\n", i, j,
clock_divider_to_freq(rxclk, 16 + j),
clock_divider_to_freq(rxclk, 16 - i));
}
v4l2_info(sd, "\tMax measurable pulse width: %u us, %llu ns\n",
pulse_width_count_to_us(FIFO_RXTX, rxclk),
pulse_width_count_to_ns(FIFO_RXTX, rxclk));
v4l2_info(sd, "\tLow pass filter: %s\n",
filtr ? "enabled" : "disabled");
if (filtr)
v4l2_info(sd, "\tMin acceptable pulse width (LPF): %u us, "
"%u ns\n",
lpf_count_to_us(filtr),
lpf_count_to_ns(filtr));
v4l2_info(sd, "\tPulse width timer timed-out: %s\n",
stats & STATS_RTO ? "yes" : "no");
v4l2_info(sd, "\tPulse width timer time-out intr: %s\n",
irqen & IRQEN_RTE ? "enabled" : "disabled");
v4l2_info(sd, "\tFIFO overrun: %s\n",
stats & STATS_ROR ? "yes" : "no");
v4l2_info(sd, "\tFIFO overrun interrupt: %s\n",
irqen & IRQEN_ROE ? "enabled" : "disabled");
v4l2_info(sd, "\tBusy: %s\n",
stats & STATS_RBY ? "yes" : "no");
v4l2_info(sd, "\tFIFO service requested: %s\n",
stats & STATS_RSR ? "yes" : "no");
v4l2_info(sd, "\tFIFO service request interrupt: %s\n",
irqen & IRQEN_RSE ? "enabled" : "disabled");
v4l2_info(sd, "IR Transmitter:\n");
v4l2_info(sd, "\tEnabled: %s\n",
cntrl & CNTRL_TXE ? "yes" : "no");
v4l2_info(sd, "\tModulation onto a carrier: %s\n",
cntrl & CNTRL_MOD ? "enabled" : "disabled");
v4l2_info(sd, "\tFIFO: %s\n",
cntrl & CNTRL_TFE ? "enabled" : "disabled");
v4l2_info(sd, "\tFIFO interrupt watermark: %s\n",
cntrl & CNTRL_TIC ? "not empty" : "half full or less");
v4l2_info(sd, "\tCarrier polarity: %s\n",
cntrl & CNTRL_CPL ? "space:burst mark:noburst"
: "space:noburst mark:burst");
if (cntrl & CNTRL_MOD) {
v4l2_info(sd, "\tCarrier (16 clocks): %u Hz\n",
clock_divider_to_carrier_freq(txclk));
v4l2_info(sd, "\tCarrier duty cycle: %2u/16\n",
cduty + 1);
}
v4l2_info(sd, "\tMax pulse width: %u us, %llu ns\n",
pulse_width_count_to_us(FIFO_RXTX, txclk),
pulse_width_count_to_ns(FIFO_RXTX, txclk));
v4l2_info(sd, "\tBusy: %s\n",
stats & STATS_TBY ? "yes" : "no");
v4l2_info(sd, "\tFIFO service requested: %s\n",
stats & STATS_TSR ? "yes" : "no");
v4l2_info(sd, "\tFIFO service request interrupt: %s\n",
irqen & IRQEN_TSE ? "enabled" : "disabled");
return 0;
}
const struct v4l2_subdev_ir_ops cx25840_ir_ops = {
.rx_read = cx25840_ir_rx_read,
.rx_g_parameters = cx25840_ir_rx_g_parameters,
.rx_s_parameters = cx25840_ir_rx_s_parameters,
.tx_write = cx25840_ir_tx_write,
.tx_g_parameters = cx25840_ir_tx_g_parameters,
.tx_s_parameters = cx25840_ir_tx_s_parameters,
};
static const struct v4l2_subdev_ir_parameters default_rx_params = {
.bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec),
.mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH,
.enable = false,
.interrupt_enable = false,
.shutdown = true,
.modulation = true,
.carrier_freq = 36000, /* 36 kHz - RC-5, and RC-6 carrier */
/* RC-5: 666,667 ns = 1/36 kHz * 32 cycles * 1 mark * 0.75 */
/* RC-6: 333,333 ns = 1/36 kHz * 16 cycles * 1 mark * 0.75 */
.noise_filter_min_width = 333333, /* ns */
.carrier_range_lower = 35000,
.carrier_range_upper = 37000,
.invert_level = false,
};
static const struct v4l2_subdev_ir_parameters default_tx_params = {
.bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec),
.mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH,
.enable = false,
.interrupt_enable = false,
.shutdown = true,
.modulation = true,
.carrier_freq = 36000, /* 36 kHz - RC-5 carrier */
.duty_cycle = 25, /* 25 % - RC-5 carrier */
.invert_level = false,
.invert_carrier_sense = false,
};
int cx25840_ir_probe(struct v4l2_subdev *sd)
{
struct cx25840_state *state = to_state(sd);
struct cx25840_ir_state *ir_state;
struct v4l2_subdev_ir_parameters default_params;
/* Only init the IR controller for the CX2388[57] AV Core for now */
if (!(is_cx23885(state) || is_cx23887(state)))
return 0;
ir_state = kzalloc(sizeof(struct cx25840_ir_state), GFP_KERNEL);
if (ir_state == NULL)
return -ENOMEM;
spin_lock_init(&ir_state->rx_kfifo_lock);
if (kfifo_alloc(&ir_state->rx_kfifo,
CX25840_IR_RX_KFIFO_SIZE, GFP_KERNEL)) {
kfree(ir_state);
return -ENOMEM;
}
ir_state->c = state->c;
state->ir_state = ir_state;
/* Ensure no interrupts arrive yet */
if (is_cx23885(state) || is_cx23887(state))
cx25840_write4(ir_state->c, CX25840_IR_IRQEN_REG, IRQEN_MSK);
else
cx25840_write4(ir_state->c, CX25840_IR_IRQEN_REG, 0);
mutex_init(&ir_state->rx_params_lock);
memcpy(&default_params, &default_rx_params,
sizeof(struct v4l2_subdev_ir_parameters));
v4l2_subdev_call(sd, ir, rx_s_parameters, &default_params);
mutex_init(&ir_state->tx_params_lock);
memcpy(&default_params, &default_tx_params,
sizeof(struct v4l2_subdev_ir_parameters));
v4l2_subdev_call(sd, ir, tx_s_parameters, &default_params);
return 0;
}
int cx25840_ir_remove(struct v4l2_subdev *sd)
{
struct cx25840_state *state = to_state(sd);
struct cx25840_ir_state *ir_state = to_ir_state(sd);
if (ir_state == NULL)
return -ENODEV;
cx25840_ir_rx_shutdown(sd);
cx25840_ir_tx_shutdown(sd);
kfifo_free(&ir_state->rx_kfifo);
kfree(ir_state);
state->ir_state = NULL;
return 0;
}
| gpl-2.0 |
SoloProject/platform_kernel_lge_hammerhead | arch/sh/kernel/cpu/sh4/setup-sh7750.c | 5062 | 11672 | /*
* SH7091/SH7750/SH7750S/SH7750R/SH7751/SH7751R Setup
*
* Copyright (C) 2006 Paul Mundt
* Copyright (C) 2006 Jamie Lenehan
*
* 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/platform_device.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/io.h>
#include <linux/sh_timer.h>
#include <linux/serial_sci.h>
#include <generated/machtypes.h>
static struct resource rtc_resources[] = {
[0] = {
.start = 0xffc80000,
.end = 0xffc80000 + 0x58 - 1,
.flags = IORESOURCE_IO,
},
[1] = {
/* Shared Period/Carry/Alarm IRQ */
.start = 20,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device rtc_device = {
.name = "sh-rtc",
.id = -1,
.num_resources = ARRAY_SIZE(rtc_resources),
.resource = rtc_resources,
};
static struct plat_sci_port sci_platform_data = {
.mapbase = 0xffe00000,
.port_reg = 0xffe0001C,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_TE | SCSCR_RE,
.scbrr_algo_id = SCBRR_ALGO_2,
.type = PORT_SCI,
.irqs = { 23, 23, 23, 0 },
.regshift = 2,
};
static struct platform_device sci_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &sci_platform_data,
},
};
static struct plat_sci_port scif_platform_data = {
.mapbase = 0xffe80000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_TE | SCSCR_RE | SCSCR_REIE,
.scbrr_algo_id = SCBRR_ALGO_2,
.type = PORT_SCIF,
.irqs = { 40, 40, 40, 40 },
};
static struct platform_device scif_device = {
.name = "sh-sci",
.id = 1,
.dev = {
.platform_data = &scif_platform_data,
},
};
static struct sh_timer_config tmu0_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
.clockevent_rating = 200,
};
static struct resource tmu0_resources[] = {
[0] = {
.start = 0xffd80008,
.end = 0xffd80013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 16,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu0_device = {
.name = "sh_tmu",
.id = 0,
.dev = {
.platform_data = &tmu0_platform_data,
},
.resource = tmu0_resources,
.num_resources = ARRAY_SIZE(tmu0_resources),
};
static struct sh_timer_config tmu1_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
.clocksource_rating = 200,
};
static struct resource tmu1_resources[] = {
[0] = {
.start = 0xffd80014,
.end = 0xffd8001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 17,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu1_device = {
.name = "sh_tmu",
.id = 1,
.dev = {
.platform_data = &tmu1_platform_data,
},
.resource = tmu1_resources,
.num_resources = ARRAY_SIZE(tmu1_resources),
};
static struct sh_timer_config tmu2_platform_data = {
.channel_offset = 0x1c,
.timer_bit = 2,
};
static struct resource tmu2_resources[] = {
[0] = {
.start = 0xffd80020,
.end = 0xffd8002f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 18,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu2_device = {
.name = "sh_tmu",
.id = 2,
.dev = {
.platform_data = &tmu2_platform_data,
},
.resource = tmu2_resources,
.num_resources = ARRAY_SIZE(tmu2_resources),
};
/* SH7750R, SH7751 and SH7751R all have two extra timer channels */
#if defined(CONFIG_CPU_SUBTYPE_SH7750R) || \
defined(CONFIG_CPU_SUBTYPE_SH7751) || \
defined(CONFIG_CPU_SUBTYPE_SH7751R)
static struct sh_timer_config tmu3_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
};
static struct resource tmu3_resources[] = {
[0] = {
.start = 0xfe100008,
.end = 0xfe100013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 72,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu3_device = {
.name = "sh_tmu",
.id = 3,
.dev = {
.platform_data = &tmu3_platform_data,
},
.resource = tmu3_resources,
.num_resources = ARRAY_SIZE(tmu3_resources),
};
static struct sh_timer_config tmu4_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
};
static struct resource tmu4_resources[] = {
[0] = {
.start = 0xfe100014,
.end = 0xfe10001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 76,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu4_device = {
.name = "sh_tmu",
.id = 4,
.dev = {
.platform_data = &tmu4_platform_data,
},
.resource = tmu4_resources,
.num_resources = ARRAY_SIZE(tmu4_resources),
};
#endif
static struct platform_device *sh7750_devices[] __initdata = {
&rtc_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
#if defined(CONFIG_CPU_SUBTYPE_SH7750R) || \
defined(CONFIG_CPU_SUBTYPE_SH7751) || \
defined(CONFIG_CPU_SUBTYPE_SH7751R)
&tmu3_device,
&tmu4_device,
#endif
};
static int __init sh7750_devices_setup(void)
{
if (mach_is_rts7751r2d()) {
platform_device_register(&scif_device);
} else {
platform_device_register(&sci_device);
platform_device_register(&scif_device);
}
return platform_add_devices(sh7750_devices,
ARRAY_SIZE(sh7750_devices));
}
arch_initcall(sh7750_devices_setup);
static struct platform_device *sh7750_early_devices[] __initdata = {
&tmu0_device,
&tmu1_device,
&tmu2_device,
#if defined(CONFIG_CPU_SUBTYPE_SH7750R) || \
defined(CONFIG_CPU_SUBTYPE_SH7751) || \
defined(CONFIG_CPU_SUBTYPE_SH7751R)
&tmu3_device,
&tmu4_device,
#endif
};
void __init plat_early_device_setup(void)
{
struct platform_device *dev[1];
if (mach_is_rts7751r2d()) {
scif_platform_data.scscr |= SCSCR_CKE1;
dev[0] = &scif_device;
early_platform_add_devices(dev, 1);
} else {
dev[0] = &sci_device;
early_platform_add_devices(dev, 1);
dev[0] = &scif_device;
early_platform_add_devices(dev, 1);
}
early_platform_add_devices(sh7750_early_devices,
ARRAY_SIZE(sh7750_early_devices));
}
enum {
UNUSED = 0,
/* interrupt sources */
IRL0, IRL1, IRL2, IRL3, /* only IRLM mode supported */
HUDI, GPIOI, DMAC,
PCIC0_PCISERR, PCIC1_PCIERR, PCIC1_PCIPWDWN, PCIC1_PCIPWON,
PCIC1_PCIDMA0, PCIC1_PCIDMA1, PCIC1_PCIDMA2, PCIC1_PCIDMA3,
TMU3, TMU4, TMU0, TMU1, TMU2, RTC, SCI1, SCIF, WDT, REF,
/* interrupt groups */
PCIC1,
};
static struct intc_vect vectors[] __initdata = {
INTC_VECT(HUDI, 0x600), INTC_VECT(GPIOI, 0x620),
INTC_VECT(TMU0, 0x400), INTC_VECT(TMU1, 0x420),
INTC_VECT(TMU2, 0x440), INTC_VECT(TMU2, 0x460),
INTC_VECT(RTC, 0x480), INTC_VECT(RTC, 0x4a0),
INTC_VECT(RTC, 0x4c0),
INTC_VECT(SCI1, 0x4e0), INTC_VECT(SCI1, 0x500),
INTC_VECT(SCI1, 0x520), INTC_VECT(SCI1, 0x540),
INTC_VECT(SCIF, 0x700), INTC_VECT(SCIF, 0x720),
INTC_VECT(SCIF, 0x740), INTC_VECT(SCIF, 0x760),
INTC_VECT(WDT, 0x560),
INTC_VECT(REF, 0x580), INTC_VECT(REF, 0x5a0),
};
static struct intc_prio_reg prio_registers[] __initdata = {
{ 0xffd00004, 0, 16, 4, /* IPRA */ { TMU0, TMU1, TMU2, RTC } },
{ 0xffd00008, 0, 16, 4, /* IPRB */ { WDT, REF, SCI1, 0 } },
{ 0xffd0000c, 0, 16, 4, /* IPRC */ { GPIOI, DMAC, SCIF, HUDI } },
{ 0xffd00010, 0, 16, 4, /* IPRD */ { IRL0, IRL1, IRL2, IRL3 } },
{ 0xfe080000, 0, 32, 4, /* INTPRI00 */ { 0, 0, 0, 0,
TMU4, TMU3,
PCIC1, PCIC0_PCISERR } },
};
static DECLARE_INTC_DESC(intc_desc, "sh7750", vectors, NULL,
NULL, prio_registers, NULL);
/* SH7750, SH7750S, SH7751 and SH7091 all have 4-channel DMA controllers */
#if defined(CONFIG_CPU_SUBTYPE_SH7750) || \
defined(CONFIG_CPU_SUBTYPE_SH7750S) || \
defined(CONFIG_CPU_SUBTYPE_SH7751) || \
defined(CONFIG_CPU_SUBTYPE_SH7091)
static struct intc_vect vectors_dma4[] __initdata = {
INTC_VECT(DMAC, 0x640), INTC_VECT(DMAC, 0x660),
INTC_VECT(DMAC, 0x680), INTC_VECT(DMAC, 0x6a0),
INTC_VECT(DMAC, 0x6c0),
};
static DECLARE_INTC_DESC(intc_desc_dma4, "sh7750_dma4",
vectors_dma4, NULL,
NULL, prio_registers, NULL);
#endif
/* SH7750R and SH7751R both have 8-channel DMA controllers */
#if defined(CONFIG_CPU_SUBTYPE_SH7750R) || defined(CONFIG_CPU_SUBTYPE_SH7751R)
static struct intc_vect vectors_dma8[] __initdata = {
INTC_VECT(DMAC, 0x640), INTC_VECT(DMAC, 0x660),
INTC_VECT(DMAC, 0x680), INTC_VECT(DMAC, 0x6a0),
INTC_VECT(DMAC, 0x780), INTC_VECT(DMAC, 0x7a0),
INTC_VECT(DMAC, 0x7c0), INTC_VECT(DMAC, 0x7e0),
INTC_VECT(DMAC, 0x6c0),
};
static DECLARE_INTC_DESC(intc_desc_dma8, "sh7750_dma8",
vectors_dma8, NULL,
NULL, prio_registers, NULL);
#endif
/* SH7750R, SH7751 and SH7751R all have two extra timer channels */
#if defined(CONFIG_CPU_SUBTYPE_SH7750R) || \
defined(CONFIG_CPU_SUBTYPE_SH7751) || \
defined(CONFIG_CPU_SUBTYPE_SH7751R)
static struct intc_vect vectors_tmu34[] __initdata = {
INTC_VECT(TMU3, 0xb00), INTC_VECT(TMU4, 0xb80),
};
static struct intc_mask_reg mask_registers[] __initdata = {
{ 0xfe080040, 0xfe080060, 32, /* INTMSK00 / INTMSKCLR00 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, TMU4, TMU3,
PCIC1_PCIERR, PCIC1_PCIPWDWN, PCIC1_PCIPWON,
PCIC1_PCIDMA0, PCIC1_PCIDMA1, PCIC1_PCIDMA2,
PCIC1_PCIDMA3, PCIC0_PCISERR } },
};
static DECLARE_INTC_DESC(intc_desc_tmu34, "sh7750_tmu34",
vectors_tmu34, NULL,
mask_registers, prio_registers, NULL);
#endif
/* SH7750S, SH7750R, SH7751 and SH7751R all have IRLM priority registers */
static struct intc_vect vectors_irlm[] __initdata = {
INTC_VECT(IRL0, 0x240), INTC_VECT(IRL1, 0x2a0),
INTC_VECT(IRL2, 0x300), INTC_VECT(IRL3, 0x360),
};
static DECLARE_INTC_DESC(intc_desc_irlm, "sh7750_irlm", vectors_irlm, NULL,
NULL, prio_registers, NULL);
/* SH7751 and SH7751R both have PCI */
#if defined(CONFIG_CPU_SUBTYPE_SH7751) || defined(CONFIG_CPU_SUBTYPE_SH7751R)
static struct intc_vect vectors_pci[] __initdata = {
INTC_VECT(PCIC0_PCISERR, 0xa00), INTC_VECT(PCIC1_PCIERR, 0xae0),
INTC_VECT(PCIC1_PCIPWDWN, 0xac0), INTC_VECT(PCIC1_PCIPWON, 0xaa0),
INTC_VECT(PCIC1_PCIDMA0, 0xa80), INTC_VECT(PCIC1_PCIDMA1, 0xa60),
INTC_VECT(PCIC1_PCIDMA2, 0xa40), INTC_VECT(PCIC1_PCIDMA3, 0xa20),
};
static struct intc_group groups_pci[] __initdata = {
INTC_GROUP(PCIC1, PCIC1_PCIERR, PCIC1_PCIPWDWN, PCIC1_PCIPWON,
PCIC1_PCIDMA0, PCIC1_PCIDMA1, PCIC1_PCIDMA2, PCIC1_PCIDMA3),
};
static DECLARE_INTC_DESC(intc_desc_pci, "sh7750_pci", vectors_pci, groups_pci,
mask_registers, prio_registers, NULL);
#endif
#if defined(CONFIG_CPU_SUBTYPE_SH7750) || \
defined(CONFIG_CPU_SUBTYPE_SH7750S) || \
defined(CONFIG_CPU_SUBTYPE_SH7091)
void __init plat_irq_setup(void)
{
/*
* same vectors for SH7750, SH7750S and SH7091 except for IRLM,
* see below..
*/
register_intc_controller(&intc_desc);
register_intc_controller(&intc_desc_dma4);
}
#endif
#if defined(CONFIG_CPU_SUBTYPE_SH7750R)
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
register_intc_controller(&intc_desc_dma8);
register_intc_controller(&intc_desc_tmu34);
}
#endif
#if defined(CONFIG_CPU_SUBTYPE_SH7751)
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
register_intc_controller(&intc_desc_dma4);
register_intc_controller(&intc_desc_tmu34);
register_intc_controller(&intc_desc_pci);
}
#endif
#if defined(CONFIG_CPU_SUBTYPE_SH7751R)
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
register_intc_controller(&intc_desc_dma8);
register_intc_controller(&intc_desc_tmu34);
register_intc_controller(&intc_desc_pci);
}
#endif
#define INTC_ICR 0xffd00000UL
#define INTC_ICR_IRLM (1<<7)
void __init plat_irq_setup_pins(int mode)
{
#if defined(CONFIG_CPU_SUBTYPE_SH7750) || defined(CONFIG_CPU_SUBTYPE_SH7091)
BUG(); /* impossible to mask interrupts on SH7750 and SH7091 */
return;
#endif
switch (mode) {
case IRQ_MODE_IRQ: /* individual interrupt mode for IRL3-0 */
__raw_writew(__raw_readw(INTC_ICR) | INTC_ICR_IRLM, INTC_ICR);
register_intc_controller(&intc_desc_irlm);
break;
default:
BUG();
}
}
| gpl-2.0 |
smaeul/kernel_samsung_tuna | sound/oss/msnd_pinnacle.c | 5062 | 48543 | /*********************************************************************
*
* Turtle Beach MultiSound Sound Card Driver for Linux
* Linux 2.0/2.2 Version
*
* msnd_pinnacle.c / msnd_classic.c
*
* -- If MSND_CLASSIC is defined:
*
* -> driver for Turtle Beach Classic/Monterey/Tahiti
*
* -- Else
*
* -> driver for Turtle Beach Pinnacle/Fiji
*
* Copyright (C) 1998 Andrew Veliath
*
* 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.
*
* 12-3-2000 Modified IO port validation Steve Sycamore
*
********************************************************************/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/mutex.h>
#include <linux/gfp.h>
#include <asm/irq.h>
#include <asm/io.h>
#include "sound_config.h"
#include "sound_firmware.h"
#ifdef MSND_CLASSIC
# ifndef __alpha__
# define SLOWIO
# endif
#endif
#include "msnd.h"
#ifdef MSND_CLASSIC
# ifdef CONFIG_MSNDCLAS_HAVE_BOOT
# define HAVE_DSPCODEH
# endif
# include "msnd_classic.h"
# define LOGNAME "msnd_classic"
#else
# ifdef CONFIG_MSNDPIN_HAVE_BOOT
# define HAVE_DSPCODEH
# endif
# include "msnd_pinnacle.h"
# define LOGNAME "msnd_pinnacle"
#endif
#ifndef CONFIG_MSND_WRITE_NDELAY
# define CONFIG_MSND_WRITE_NDELAY 1
#endif
#define get_play_delay_jiffies(size) ((size) * HZ * \
dev.play_sample_size / 8 / \
dev.play_sample_rate / \
dev.play_channels)
#define get_rec_delay_jiffies(size) ((size) * HZ * \
dev.rec_sample_size / 8 / \
dev.rec_sample_rate / \
dev.rec_channels)
static DEFINE_MUTEX(msnd_pinnacle_mutex);
static multisound_dev_t dev;
#ifndef HAVE_DSPCODEH
static char *dspini, *permini;
static int sizeof_dspini, sizeof_permini;
#endif
static int dsp_full_reset(void);
static void dsp_write_flush(void);
static __inline__ int chk_send_dsp_cmd(multisound_dev_t *dev, register BYTE cmd)
{
if (msnd_send_dsp_cmd(dev, cmd) == 0)
return 0;
dsp_full_reset();
return msnd_send_dsp_cmd(dev, cmd);
}
static void reset_play_queue(void)
{
int n;
LPDAQD lpDAQ;
dev.last_playbank = -1;
writew(PCTODSP_OFFSET(0 * DAQDS__size), dev.DAPQ + JQS_wHead);
writew(PCTODSP_OFFSET(0 * DAQDS__size), dev.DAPQ + JQS_wTail);
for (n = 0, lpDAQ = dev.base + DAPQ_DATA_BUFF; n < 3; ++n, lpDAQ += DAQDS__size) {
writew(PCTODSP_BASED((DWORD)(DAP_BUFF_SIZE * n)), lpDAQ + DAQDS_wStart);
writew(0, lpDAQ + DAQDS_wSize);
writew(1, lpDAQ + DAQDS_wFormat);
writew(dev.play_sample_size, lpDAQ + DAQDS_wSampleSize);
writew(dev.play_channels, lpDAQ + DAQDS_wChannels);
writew(dev.play_sample_rate, lpDAQ + DAQDS_wSampleRate);
writew(HIMT_PLAY_DONE * 0x100 + n, lpDAQ + DAQDS_wIntMsg);
writew(n, lpDAQ + DAQDS_wFlags);
}
}
static void reset_record_queue(void)
{
int n;
LPDAQD lpDAQ;
unsigned long flags;
dev.last_recbank = 2;
writew(PCTODSP_OFFSET(0 * DAQDS__size), dev.DARQ + JQS_wHead);
writew(PCTODSP_OFFSET(dev.last_recbank * DAQDS__size), dev.DARQ + JQS_wTail);
/* Critical section: bank 1 access */
spin_lock_irqsave(&dev.lock, flags);
msnd_outb(HPBLKSEL_1, dev.io + HP_BLKS);
memset_io(dev.base, 0, DAR_BUFF_SIZE * 3);
msnd_outb(HPBLKSEL_0, dev.io + HP_BLKS);
spin_unlock_irqrestore(&dev.lock, flags);
for (n = 0, lpDAQ = dev.base + DARQ_DATA_BUFF; n < 3; ++n, lpDAQ += DAQDS__size) {
writew(PCTODSP_BASED((DWORD)(DAR_BUFF_SIZE * n)) + 0x4000, lpDAQ + DAQDS_wStart);
writew(DAR_BUFF_SIZE, lpDAQ + DAQDS_wSize);
writew(1, lpDAQ + DAQDS_wFormat);
writew(dev.rec_sample_size, lpDAQ + DAQDS_wSampleSize);
writew(dev.rec_channels, lpDAQ + DAQDS_wChannels);
writew(dev.rec_sample_rate, lpDAQ + DAQDS_wSampleRate);
writew(HIMT_RECORD_DONE * 0x100 + n, lpDAQ + DAQDS_wIntMsg);
writew(n, lpDAQ + DAQDS_wFlags);
}
}
static void reset_queues(void)
{
if (dev.mode & FMODE_WRITE) {
msnd_fifo_make_empty(&dev.DAPF);
reset_play_queue();
}
if (dev.mode & FMODE_READ) {
msnd_fifo_make_empty(&dev.DARF);
reset_record_queue();
}
}
static int dsp_set_format(struct file *file, int val)
{
int data, i;
LPDAQD lpDAQ, lpDARQ;
lpDAQ = dev.base + DAPQ_DATA_BUFF;
lpDARQ = dev.base + DARQ_DATA_BUFF;
switch (val) {
case AFMT_U8:
case AFMT_S16_LE:
data = val;
break;
default:
data = DEFSAMPLESIZE;
break;
}
for (i = 0; i < 3; ++i, lpDAQ += DAQDS__size, lpDARQ += DAQDS__size) {
if (file->f_mode & FMODE_WRITE)
writew(data, lpDAQ + DAQDS_wSampleSize);
if (file->f_mode & FMODE_READ)
writew(data, lpDARQ + DAQDS_wSampleSize);
}
if (file->f_mode & FMODE_WRITE)
dev.play_sample_size = data;
if (file->f_mode & FMODE_READ)
dev.rec_sample_size = data;
return data;
}
static int dsp_get_frag_size(void)
{
int size;
size = dev.fifosize / 4;
if (size > 32 * 1024)
size = 32 * 1024;
return size;
}
static int dsp_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int val, i, data, tmp;
LPDAQD lpDAQ, lpDARQ;
audio_buf_info abinfo;
unsigned long flags;
int __user *p = (int __user *)arg;
lpDAQ = dev.base + DAPQ_DATA_BUFF;
lpDARQ = dev.base + DARQ_DATA_BUFF;
switch (cmd) {
case SNDCTL_DSP_SUBDIVIDE:
case SNDCTL_DSP_SETFRAGMENT:
case SNDCTL_DSP_SETDUPLEX:
case SNDCTL_DSP_POST:
return 0;
case SNDCTL_DSP_GETIPTR:
case SNDCTL_DSP_GETOPTR:
case SNDCTL_DSP_MAPINBUF:
case SNDCTL_DSP_MAPOUTBUF:
return -EINVAL;
case SNDCTL_DSP_GETOSPACE:
if (!(file->f_mode & FMODE_WRITE))
return -EINVAL;
spin_lock_irqsave(&dev.lock, flags);
abinfo.fragsize = dsp_get_frag_size();
abinfo.bytes = dev.DAPF.n - dev.DAPF.len;
abinfo.fragstotal = dev.DAPF.n / abinfo.fragsize;
abinfo.fragments = abinfo.bytes / abinfo.fragsize;
spin_unlock_irqrestore(&dev.lock, flags);
return copy_to_user((void __user *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
case SNDCTL_DSP_GETISPACE:
if (!(file->f_mode & FMODE_READ))
return -EINVAL;
spin_lock_irqsave(&dev.lock, flags);
abinfo.fragsize = dsp_get_frag_size();
abinfo.bytes = dev.DARF.n - dev.DARF.len;
abinfo.fragstotal = dev.DARF.n / abinfo.fragsize;
abinfo.fragments = abinfo.bytes / abinfo.fragsize;
spin_unlock_irqrestore(&dev.lock, flags);
return copy_to_user((void __user *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
case SNDCTL_DSP_RESET:
dev.nresets = 0;
reset_queues();
return 0;
case SNDCTL_DSP_SYNC:
dsp_write_flush();
return 0;
case SNDCTL_DSP_GETBLKSIZE:
tmp = dsp_get_frag_size();
if (put_user(tmp, p))
return -EFAULT;
return 0;
case SNDCTL_DSP_GETFMTS:
val = AFMT_S16_LE | AFMT_U8;
if (put_user(val, p))
return -EFAULT;
return 0;
case SNDCTL_DSP_SETFMT:
if (get_user(val, p))
return -EFAULT;
if (file->f_mode & FMODE_WRITE)
data = val == AFMT_QUERY
? dev.play_sample_size
: dsp_set_format(file, val);
else
data = val == AFMT_QUERY
? dev.rec_sample_size
: dsp_set_format(file, val);
if (put_user(data, p))
return -EFAULT;
return 0;
case SNDCTL_DSP_NONBLOCK:
if (!test_bit(F_DISABLE_WRITE_NDELAY, &dev.flags) &&
file->f_mode & FMODE_WRITE)
dev.play_ndelay = 1;
if (file->f_mode & FMODE_READ)
dev.rec_ndelay = 1;
return 0;
case SNDCTL_DSP_GETCAPS:
val = DSP_CAP_DUPLEX | DSP_CAP_BATCH;
if (put_user(val, p))
return -EFAULT;
return 0;
case SNDCTL_DSP_SPEED:
if (get_user(val, p))
return -EFAULT;
if (val < 8000)
val = 8000;
if (val > 48000)
val = 48000;
data = val;
for (i = 0; i < 3; ++i, lpDAQ += DAQDS__size, lpDARQ += DAQDS__size) {
if (file->f_mode & FMODE_WRITE)
writew(data, lpDAQ + DAQDS_wSampleRate);
if (file->f_mode & FMODE_READ)
writew(data, lpDARQ + DAQDS_wSampleRate);
}
if (file->f_mode & FMODE_WRITE)
dev.play_sample_rate = data;
if (file->f_mode & FMODE_READ)
dev.rec_sample_rate = data;
if (put_user(data, p))
return -EFAULT;
return 0;
case SNDCTL_DSP_CHANNELS:
case SNDCTL_DSP_STEREO:
if (get_user(val, p))
return -EFAULT;
if (cmd == SNDCTL_DSP_CHANNELS) {
switch (val) {
case 1:
case 2:
data = val;
break;
default:
val = data = 2;
break;
}
} else {
switch (val) {
case 0:
data = 1;
break;
default:
val = 1;
case 1:
data = 2;
break;
}
}
for (i = 0; i < 3; ++i, lpDAQ += DAQDS__size, lpDARQ += DAQDS__size) {
if (file->f_mode & FMODE_WRITE)
writew(data, lpDAQ + DAQDS_wChannels);
if (file->f_mode & FMODE_READ)
writew(data, lpDARQ + DAQDS_wChannels);
}
if (file->f_mode & FMODE_WRITE)
dev.play_channels = data;
if (file->f_mode & FMODE_READ)
dev.rec_channels = data;
if (put_user(val, p))
return -EFAULT;
return 0;
}
return -EINVAL;
}
static int mixer_get(int d)
{
if (d > 31)
return -EINVAL;
switch (d) {
case SOUND_MIXER_VOLUME:
case SOUND_MIXER_PCM:
case SOUND_MIXER_LINE:
case SOUND_MIXER_IMIX:
case SOUND_MIXER_LINE1:
#ifndef MSND_CLASSIC
case SOUND_MIXER_MIC:
case SOUND_MIXER_SYNTH:
#endif
return (dev.left_levels[d] >> 8) * 100 / 0xff |
(((dev.right_levels[d] >> 8) * 100 / 0xff) << 8);
default:
return 0;
}
}
#define update_volm(a,b) \
writew((dev.left_levels[a] >> 1) * \
readw(dev.SMA + SMA_wCurrMastVolLeft) / 0xffff, \
dev.SMA + SMA_##b##Left); \
writew((dev.right_levels[a] >> 1) * \
readw(dev.SMA + SMA_wCurrMastVolRight) / 0xffff, \
dev.SMA + SMA_##b##Right);
#define update_potm(d,s,ar) \
writeb((dev.left_levels[d] >> 8) * \
readw(dev.SMA + SMA_wCurrMastVolLeft) / 0xffff, \
dev.SMA + SMA_##s##Left); \
writeb((dev.right_levels[d] >> 8) * \
readw(dev.SMA + SMA_wCurrMastVolRight) / 0xffff, \
dev.SMA + SMA_##s##Right); \
if (msnd_send_word(&dev, 0, 0, ar) == 0) \
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ);
#define update_pot(d,s,ar) \
writeb(dev.left_levels[d] >> 8, \
dev.SMA + SMA_##s##Left); \
writeb(dev.right_levels[d] >> 8, \
dev.SMA + SMA_##s##Right); \
if (msnd_send_word(&dev, 0, 0, ar) == 0) \
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ);
static int mixer_set(int d, int value)
{
int left = value & 0x000000ff;
int right = (value & 0x0000ff00) >> 8;
int bLeft, bRight;
int wLeft, wRight;
int updatemaster = 0;
if (d > 31)
return -EINVAL;
bLeft = left * 0xff / 100;
wLeft = left * 0xffff / 100;
bRight = right * 0xff / 100;
wRight = right * 0xffff / 100;
dev.left_levels[d] = wLeft;
dev.right_levels[d] = wRight;
switch (d) {
/* master volume unscaled controls */
case SOUND_MIXER_LINE: /* line pot control */
/* scaled by IMIX in digital mix */
writeb(bLeft, dev.SMA + SMA_bInPotPosLeft);
writeb(bRight, dev.SMA + SMA_bInPotPosRight);
if (msnd_send_word(&dev, 0, 0, HDEXAR_IN_SET_POTS) == 0)
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ);
break;
#ifndef MSND_CLASSIC
case SOUND_MIXER_MIC: /* mic pot control */
/* scaled by IMIX in digital mix */
writeb(bLeft, dev.SMA + SMA_bMicPotPosLeft);
writeb(bRight, dev.SMA + SMA_bMicPotPosRight);
if (msnd_send_word(&dev, 0, 0, HDEXAR_MIC_SET_POTS) == 0)
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ);
break;
#endif
case SOUND_MIXER_VOLUME: /* master volume */
writew(wLeft, dev.SMA + SMA_wCurrMastVolLeft);
writew(wRight, dev.SMA + SMA_wCurrMastVolRight);
/* fall through */
case SOUND_MIXER_LINE1: /* aux pot control */
/* scaled by master volume */
/* fall through */
/* digital controls */
case SOUND_MIXER_SYNTH: /* synth vol (dsp mix) */
case SOUND_MIXER_PCM: /* pcm vol (dsp mix) */
case SOUND_MIXER_IMIX: /* input monitor (dsp mix) */
/* scaled by master volume */
updatemaster = 1;
break;
default:
return 0;
}
if (updatemaster) {
/* update master volume scaled controls */
update_volm(SOUND_MIXER_PCM, wCurrPlayVol);
update_volm(SOUND_MIXER_IMIX, wCurrInVol);
#ifndef MSND_CLASSIC
update_volm(SOUND_MIXER_SYNTH, wCurrMHdrVol);
#endif
update_potm(SOUND_MIXER_LINE1, bAuxPotPos, HDEXAR_AUX_SET_POTS);
}
return mixer_get(d);
}
static void mixer_setup(void)
{
update_pot(SOUND_MIXER_LINE, bInPotPos, HDEXAR_IN_SET_POTS);
update_potm(SOUND_MIXER_LINE1, bAuxPotPos, HDEXAR_AUX_SET_POTS);
update_volm(SOUND_MIXER_PCM, wCurrPlayVol);
update_volm(SOUND_MIXER_IMIX, wCurrInVol);
#ifndef MSND_CLASSIC
update_pot(SOUND_MIXER_MIC, bMicPotPos, HDEXAR_MIC_SET_POTS);
update_volm(SOUND_MIXER_SYNTH, wCurrMHdrVol);
#endif
}
static unsigned long set_recsrc(unsigned long recsrc)
{
if (dev.recsrc == recsrc)
return dev.recsrc;
#ifdef HAVE_NORECSRC
else if (recsrc == 0)
dev.recsrc = 0;
#endif
else
dev.recsrc ^= recsrc;
#ifndef MSND_CLASSIC
if (dev.recsrc & SOUND_MASK_IMIX) {
if (msnd_send_word(&dev, 0, 0, HDEXAR_SET_ANA_IN) == 0)
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ);
}
else if (dev.recsrc & SOUND_MASK_SYNTH) {
if (msnd_send_word(&dev, 0, 0, HDEXAR_SET_SYNTH_IN) == 0)
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ);
}
else if ((dev.recsrc & SOUND_MASK_DIGITAL1) && test_bit(F_HAVEDIGITAL, &dev.flags)) {
if (msnd_send_word(&dev, 0, 0, HDEXAR_SET_DAT_IN) == 0)
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ);
}
else {
#ifdef HAVE_NORECSRC
/* Select no input (?) */
dev.recsrc = 0;
#else
dev.recsrc = SOUND_MASK_IMIX;
if (msnd_send_word(&dev, 0, 0, HDEXAR_SET_ANA_IN) == 0)
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ);
#endif
}
#endif /* MSND_CLASSIC */
return dev.recsrc;
}
static unsigned long force_recsrc(unsigned long recsrc)
{
dev.recsrc = 0;
return set_recsrc(recsrc);
}
#define set_mixer_info() \
memset(&info, 0, sizeof(info)); \
strlcpy(info.id, "MSNDMIXER", sizeof(info.id)); \
strlcpy(info.name, "MultiSound Mixer", sizeof(info.name));
static int mixer_ioctl(unsigned int cmd, unsigned long arg)
{
if (cmd == SOUND_MIXER_INFO) {
mixer_info info;
set_mixer_info();
info.modify_counter = dev.mixer_mod_count;
if (copy_to_user((void __user *)arg, &info, sizeof(info)))
return -EFAULT;
return 0;
} else if (cmd == SOUND_OLD_MIXER_INFO) {
_old_mixer_info info;
set_mixer_info();
if (copy_to_user((void __user *)arg, &info, sizeof(info)))
return -EFAULT;
return 0;
} else if (cmd == SOUND_MIXER_PRIVATE1) {
dev.nresets = 0;
dsp_full_reset();
return 0;
} else if (((cmd >> 8) & 0xff) == 'M') {
int val = 0;
if (_SIOC_DIR(cmd) & _SIOC_WRITE) {
switch (cmd & 0xff) {
case SOUND_MIXER_RECSRC:
if (get_user(val, (int __user *)arg))
return -EFAULT;
val = set_recsrc(val);
break;
default:
if (get_user(val, (int __user *)arg))
return -EFAULT;
val = mixer_set(cmd & 0xff, val);
break;
}
++dev.mixer_mod_count;
return put_user(val, (int __user *)arg);
} else {
switch (cmd & 0xff) {
case SOUND_MIXER_RECSRC:
val = dev.recsrc;
break;
case SOUND_MIXER_DEVMASK:
case SOUND_MIXER_STEREODEVS:
val = SOUND_MASK_PCM |
SOUND_MASK_LINE |
SOUND_MASK_IMIX |
SOUND_MASK_LINE1 |
#ifndef MSND_CLASSIC
SOUND_MASK_MIC |
SOUND_MASK_SYNTH |
#endif
SOUND_MASK_VOLUME;
break;
case SOUND_MIXER_RECMASK:
#ifdef MSND_CLASSIC
val = 0;
#else
val = SOUND_MASK_IMIX |
SOUND_MASK_SYNTH;
if (test_bit(F_HAVEDIGITAL, &dev.flags))
val |= SOUND_MASK_DIGITAL1;
#endif
break;
case SOUND_MIXER_CAPS:
val = SOUND_CAP_EXCL_INPUT;
break;
default:
if ((val = mixer_get(cmd & 0xff)) < 0)
return -EINVAL;
break;
}
}
return put_user(val, (int __user *)arg);
}
return -EINVAL;
}
static long dev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int minor = iminor(file->f_path.dentry->d_inode);
int ret;
if (cmd == OSS_GETVERSION) {
int sound_version = SOUND_VERSION;
return put_user(sound_version, (int __user *)arg);
}
ret = -EINVAL;
mutex_lock(&msnd_pinnacle_mutex);
if (minor == dev.dsp_minor)
ret = dsp_ioctl(file, cmd, arg);
else if (minor == dev.mixer_minor)
ret = mixer_ioctl(cmd, arg);
mutex_unlock(&msnd_pinnacle_mutex);
return ret;
}
static void dsp_write_flush(void)
{
if (!(dev.mode & FMODE_WRITE) || !test_bit(F_WRITING, &dev.flags))
return;
set_bit(F_WRITEFLUSH, &dev.flags);
interruptible_sleep_on_timeout(
&dev.writeflush,
get_play_delay_jiffies(dev.DAPF.len));
clear_bit(F_WRITEFLUSH, &dev.flags);
if (!signal_pending(current)) {
current->state = TASK_INTERRUPTIBLE;
schedule_timeout(get_play_delay_jiffies(DAP_BUFF_SIZE));
}
clear_bit(F_WRITING, &dev.flags);
}
static void dsp_halt(struct file *file)
{
if ((file ? file->f_mode : dev.mode) & FMODE_READ) {
clear_bit(F_READING, &dev.flags);
chk_send_dsp_cmd(&dev, HDEX_RECORD_STOP);
msnd_disable_irq(&dev);
if (file) {
printk(KERN_DEBUG LOGNAME ": Stopping read for %p\n", file);
dev.mode &= ~FMODE_READ;
}
clear_bit(F_AUDIO_READ_INUSE, &dev.flags);
}
if ((file ? file->f_mode : dev.mode) & FMODE_WRITE) {
if (test_bit(F_WRITING, &dev.flags)) {
dsp_write_flush();
chk_send_dsp_cmd(&dev, HDEX_PLAY_STOP);
}
msnd_disable_irq(&dev);
if (file) {
printk(KERN_DEBUG LOGNAME ": Stopping write for %p\n", file);
dev.mode &= ~FMODE_WRITE;
}
clear_bit(F_AUDIO_WRITE_INUSE, &dev.flags);
}
}
static int dsp_release(struct file *file)
{
dsp_halt(file);
return 0;
}
static int dsp_open(struct file *file)
{
if ((file ? file->f_mode : dev.mode) & FMODE_WRITE) {
set_bit(F_AUDIO_WRITE_INUSE, &dev.flags);
clear_bit(F_WRITING, &dev.flags);
msnd_fifo_make_empty(&dev.DAPF);
reset_play_queue();
if (file) {
printk(KERN_DEBUG LOGNAME ": Starting write for %p\n", file);
dev.mode |= FMODE_WRITE;
}
msnd_enable_irq(&dev);
}
if ((file ? file->f_mode : dev.mode) & FMODE_READ) {
set_bit(F_AUDIO_READ_INUSE, &dev.flags);
clear_bit(F_READING, &dev.flags);
msnd_fifo_make_empty(&dev.DARF);
reset_record_queue();
if (file) {
printk(KERN_DEBUG LOGNAME ": Starting read for %p\n", file);
dev.mode |= FMODE_READ;
}
msnd_enable_irq(&dev);
}
return 0;
}
static void set_default_play_audio_parameters(void)
{
dev.play_sample_size = DEFSAMPLESIZE;
dev.play_sample_rate = DEFSAMPLERATE;
dev.play_channels = DEFCHANNELS;
}
static void set_default_rec_audio_parameters(void)
{
dev.rec_sample_size = DEFSAMPLESIZE;
dev.rec_sample_rate = DEFSAMPLERATE;
dev.rec_channels = DEFCHANNELS;
}
static void set_default_audio_parameters(void)
{
set_default_play_audio_parameters();
set_default_rec_audio_parameters();
}
static int dev_open(struct inode *inode, struct file *file)
{
int minor = iminor(inode);
int err = 0;
mutex_lock(&msnd_pinnacle_mutex);
if (minor == dev.dsp_minor) {
if ((file->f_mode & FMODE_WRITE &&
test_bit(F_AUDIO_WRITE_INUSE, &dev.flags)) ||
(file->f_mode & FMODE_READ &&
test_bit(F_AUDIO_READ_INUSE, &dev.flags))) {
err = -EBUSY;
goto out;
}
if ((err = dsp_open(file)) >= 0) {
dev.nresets = 0;
if (file->f_mode & FMODE_WRITE) {
set_default_play_audio_parameters();
if (!test_bit(F_DISABLE_WRITE_NDELAY, &dev.flags))
dev.play_ndelay = (file->f_flags & O_NDELAY) ? 1 : 0;
else
dev.play_ndelay = 0;
}
if (file->f_mode & FMODE_READ) {
set_default_rec_audio_parameters();
dev.rec_ndelay = (file->f_flags & O_NDELAY) ? 1 : 0;
}
}
}
else if (minor == dev.mixer_minor) {
/* nothing */
} else
err = -EINVAL;
out:
mutex_unlock(&msnd_pinnacle_mutex);
return err;
}
static int dev_release(struct inode *inode, struct file *file)
{
int minor = iminor(inode);
int err = 0;
mutex_lock(&msnd_pinnacle_mutex);
if (minor == dev.dsp_minor)
err = dsp_release(file);
else if (minor == dev.mixer_minor) {
/* nothing */
} else
err = -EINVAL;
mutex_unlock(&msnd_pinnacle_mutex);
return err;
}
static __inline__ int pack_DARQ_to_DARF(register int bank)
{
register int size, timeout = 3;
register WORD wTmp;
LPDAQD DAQD;
/* Increment the tail and check for queue wrap */
wTmp = readw(dev.DARQ + JQS_wTail) + PCTODSP_OFFSET(DAQDS__size);
if (wTmp > readw(dev.DARQ + JQS_wSize))
wTmp = 0;
while (wTmp == readw(dev.DARQ + JQS_wHead) && timeout--)
udelay(1);
writew(wTmp, dev.DARQ + JQS_wTail);
/* Get our digital audio queue struct */
DAQD = bank * DAQDS__size + dev.base + DARQ_DATA_BUFF;
/* Get length of data */
size = readw(DAQD + DAQDS_wSize);
/* Read data from the head (unprotected bank 1 access okay
since this is only called inside an interrupt) */
msnd_outb(HPBLKSEL_1, dev.io + HP_BLKS);
msnd_fifo_write_io(
&dev.DARF,
dev.base + bank * DAR_BUFF_SIZE,
size);
msnd_outb(HPBLKSEL_0, dev.io + HP_BLKS);
return 1;
}
static __inline__ int pack_DAPF_to_DAPQ(register int start)
{
register WORD DAPQ_tail;
register int protect = start, nbanks = 0;
LPDAQD DAQD;
DAPQ_tail = readw(dev.DAPQ + JQS_wTail);
while (DAPQ_tail != readw(dev.DAPQ + JQS_wHead) || start) {
register int bank_num = DAPQ_tail / PCTODSP_OFFSET(DAQDS__size);
register int n;
unsigned long flags;
/* Write the data to the new tail */
if (protect) {
/* Critical section: protect fifo in non-interrupt */
spin_lock_irqsave(&dev.lock, flags);
n = msnd_fifo_read_io(
&dev.DAPF,
dev.base + bank_num * DAP_BUFF_SIZE,
DAP_BUFF_SIZE);
spin_unlock_irqrestore(&dev.lock, flags);
} else {
n = msnd_fifo_read_io(
&dev.DAPF,
dev.base + bank_num * DAP_BUFF_SIZE,
DAP_BUFF_SIZE);
}
if (!n)
break;
if (start)
start = 0;
/* Get our digital audio queue struct */
DAQD = bank_num * DAQDS__size + dev.base + DAPQ_DATA_BUFF;
/* Write size of this bank */
writew(n, DAQD + DAQDS_wSize);
++nbanks;
/* Then advance the tail */
DAPQ_tail = (++bank_num % 3) * PCTODSP_OFFSET(DAQDS__size);
writew(DAPQ_tail, dev.DAPQ + JQS_wTail);
/* Tell the DSP to play the bank */
msnd_send_dsp_cmd(&dev, HDEX_PLAY_START);
}
return nbanks;
}
static int dsp_read(char __user *buf, size_t len)
{
int count = len;
char *page = (char *)__get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
while (count > 0) {
int n, k;
unsigned long flags;
k = PAGE_SIZE;
if (k > count)
k = count;
/* Critical section: protect fifo in non-interrupt */
spin_lock_irqsave(&dev.lock, flags);
n = msnd_fifo_read(&dev.DARF, page, k);
spin_unlock_irqrestore(&dev.lock, flags);
if (copy_to_user(buf, page, n)) {
free_page((unsigned long)page);
return -EFAULT;
}
buf += n;
count -= n;
if (n == k && count)
continue;
if (!test_bit(F_READING, &dev.flags) && dev.mode & FMODE_READ) {
dev.last_recbank = -1;
if (chk_send_dsp_cmd(&dev, HDEX_RECORD_START) == 0)
set_bit(F_READING, &dev.flags);
}
if (dev.rec_ndelay) {
free_page((unsigned long)page);
return count == len ? -EAGAIN : len - count;
}
if (count > 0) {
set_bit(F_READBLOCK, &dev.flags);
if (!interruptible_sleep_on_timeout(
&dev.readblock,
get_rec_delay_jiffies(DAR_BUFF_SIZE)))
clear_bit(F_READING, &dev.flags);
clear_bit(F_READBLOCK, &dev.flags);
if (signal_pending(current)) {
free_page((unsigned long)page);
return -EINTR;
}
}
}
free_page((unsigned long)page);
return len - count;
}
static int dsp_write(const char __user *buf, size_t len)
{
int count = len;
char *page = (char *)__get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
while (count > 0) {
int n, k;
unsigned long flags;
k = PAGE_SIZE;
if (k > count)
k = count;
if (copy_from_user(page, buf, k)) {
free_page((unsigned long)page);
return -EFAULT;
}
/* Critical section: protect fifo in non-interrupt */
spin_lock_irqsave(&dev.lock, flags);
n = msnd_fifo_write(&dev.DAPF, page, k);
spin_unlock_irqrestore(&dev.lock, flags);
buf += n;
count -= n;
if (count && n == k)
continue;
if (!test_bit(F_WRITING, &dev.flags) && (dev.mode & FMODE_WRITE)) {
dev.last_playbank = -1;
if (pack_DAPF_to_DAPQ(1) > 0)
set_bit(F_WRITING, &dev.flags);
}
if (dev.play_ndelay) {
free_page((unsigned long)page);
return count == len ? -EAGAIN : len - count;
}
if (count > 0) {
set_bit(F_WRITEBLOCK, &dev.flags);
interruptible_sleep_on_timeout(
&dev.writeblock,
get_play_delay_jiffies(DAP_BUFF_SIZE));
clear_bit(F_WRITEBLOCK, &dev.flags);
if (signal_pending(current)) {
free_page((unsigned long)page);
return -EINTR;
}
}
}
free_page((unsigned long)page);
return len - count;
}
static ssize_t dev_read(struct file *file, char __user *buf, size_t count, loff_t *off)
{
int minor = iminor(file->f_path.dentry->d_inode);
if (minor == dev.dsp_minor)
return dsp_read(buf, count);
else
return -EINVAL;
}
static ssize_t dev_write(struct file *file, const char __user *buf, size_t count, loff_t *off)
{
int minor = iminor(file->f_path.dentry->d_inode);
if (minor == dev.dsp_minor)
return dsp_write(buf, count);
else
return -EINVAL;
}
static __inline__ void eval_dsp_msg(register WORD wMessage)
{
switch (HIBYTE(wMessage)) {
case HIMT_PLAY_DONE:
if (dev.last_playbank == LOBYTE(wMessage) || !test_bit(F_WRITING, &dev.flags))
break;
dev.last_playbank = LOBYTE(wMessage);
if (pack_DAPF_to_DAPQ(0) <= 0) {
if (!test_bit(F_WRITEBLOCK, &dev.flags)) {
if (test_and_clear_bit(F_WRITEFLUSH, &dev.flags))
wake_up_interruptible(&dev.writeflush);
}
clear_bit(F_WRITING, &dev.flags);
}
if (test_bit(F_WRITEBLOCK, &dev.flags))
wake_up_interruptible(&dev.writeblock);
break;
case HIMT_RECORD_DONE:
if (dev.last_recbank == LOBYTE(wMessage))
break;
dev.last_recbank = LOBYTE(wMessage);
pack_DARQ_to_DARF(dev.last_recbank);
if (test_bit(F_READBLOCK, &dev.flags))
wake_up_interruptible(&dev.readblock);
break;
case HIMT_DSP:
switch (LOBYTE(wMessage)) {
#ifndef MSND_CLASSIC
case HIDSP_PLAY_UNDER:
#endif
case HIDSP_INT_PLAY_UNDER:
/* printk(KERN_DEBUG LOGNAME ": Play underflow\n"); */
clear_bit(F_WRITING, &dev.flags);
break;
case HIDSP_INT_RECORD_OVER:
/* printk(KERN_DEBUG LOGNAME ": Record overflow\n"); */
clear_bit(F_READING, &dev.flags);
break;
default:
/* printk(KERN_DEBUG LOGNAME ": DSP message %d 0x%02x\n",
LOBYTE(wMessage), LOBYTE(wMessage)); */
break;
}
break;
case HIMT_MIDI_IN_UCHAR:
if (dev.midi_in_interrupt)
(*dev.midi_in_interrupt)(&dev);
break;
default:
/* printk(KERN_DEBUG LOGNAME ": HIMT message %d 0x%02x\n", HIBYTE(wMessage), HIBYTE(wMessage)); */
break;
}
}
static irqreturn_t intr(int irq, void *dev_id)
{
/* Send ack to DSP */
msnd_inb(dev.io + HP_RXL);
/* Evaluate queued DSP messages */
while (readw(dev.DSPQ + JQS_wTail) != readw(dev.DSPQ + JQS_wHead)) {
register WORD wTmp;
eval_dsp_msg(readw(dev.pwDSPQData + 2*readw(dev.DSPQ + JQS_wHead)));
if ((wTmp = readw(dev.DSPQ + JQS_wHead) + 1) > readw(dev.DSPQ + JQS_wSize))
writew(0, dev.DSPQ + JQS_wHead);
else
writew(wTmp, dev.DSPQ + JQS_wHead);
}
return IRQ_HANDLED;
}
static const struct file_operations dev_fileops = {
.owner = THIS_MODULE,
.read = dev_read,
.write = dev_write,
.unlocked_ioctl = dev_ioctl,
.open = dev_open,
.release = dev_release,
.llseek = noop_llseek,
};
static int reset_dsp(void)
{
int timeout = 100;
msnd_outb(HPDSPRESET_ON, dev.io + HP_DSPR);
mdelay(1);
#ifndef MSND_CLASSIC
dev.info = msnd_inb(dev.io + HP_INFO);
#endif
msnd_outb(HPDSPRESET_OFF, dev.io + HP_DSPR);
mdelay(1);
while (timeout-- > 0) {
if (msnd_inb(dev.io + HP_CVR) == HP_CVR_DEF)
return 0;
mdelay(1);
}
printk(KERN_ERR LOGNAME ": Cannot reset DSP\n");
return -EIO;
}
static int __init probe_multisound(void)
{
#ifndef MSND_CLASSIC
char *xv, *rev = NULL;
char *pin = "Pinnacle", *fiji = "Fiji";
char *pinfiji = "Pinnacle/Fiji";
#endif
if (!request_region(dev.io, dev.numio, "probing")) {
printk(KERN_ERR LOGNAME ": I/O port conflict\n");
return -ENODEV;
}
if (reset_dsp() < 0) {
release_region(dev.io, dev.numio);
return -ENODEV;
}
#ifdef MSND_CLASSIC
dev.name = "Classic/Tahiti/Monterey";
printk(KERN_INFO LOGNAME ": %s, "
#else
switch (dev.info >> 4) {
case 0xf: xv = "<= 1.15"; break;
case 0x1: xv = "1.18/1.2"; break;
case 0x2: xv = "1.3"; break;
case 0x3: xv = "1.4"; break;
default: xv = "unknown"; break;
}
switch (dev.info & 0x7) {
case 0x0: rev = "I"; dev.name = pin; break;
case 0x1: rev = "F"; dev.name = pin; break;
case 0x2: rev = "G"; dev.name = pin; break;
case 0x3: rev = "H"; dev.name = pin; break;
case 0x4: rev = "E"; dev.name = fiji; break;
case 0x5: rev = "C"; dev.name = fiji; break;
case 0x6: rev = "D"; dev.name = fiji; break;
case 0x7:
rev = "A-B (Fiji) or A-E (Pinnacle)";
dev.name = pinfiji;
break;
}
printk(KERN_INFO LOGNAME ": %s revision %s, Xilinx version %s, "
#endif /* MSND_CLASSIC */
"I/O 0x%x-0x%x, IRQ %d, memory mapped to %p-%p\n",
dev.name,
#ifndef MSND_CLASSIC
rev, xv,
#endif
dev.io, dev.io + dev.numio - 1,
dev.irq,
dev.base, dev.base + 0x7fff);
release_region(dev.io, dev.numio);
return 0;
}
static int init_sma(void)
{
static int initted;
WORD mastVolLeft, mastVolRight;
unsigned long flags;
#ifdef MSND_CLASSIC
msnd_outb(dev.memid, dev.io + HP_MEMM);
#endif
msnd_outb(HPBLKSEL_0, dev.io + HP_BLKS);
if (initted) {
mastVolLeft = readw(dev.SMA + SMA_wCurrMastVolLeft);
mastVolRight = readw(dev.SMA + SMA_wCurrMastVolRight);
} else
mastVolLeft = mastVolRight = 0;
memset_io(dev.base, 0, 0x8000);
/* Critical section: bank 1 access */
spin_lock_irqsave(&dev.lock, flags);
msnd_outb(HPBLKSEL_1, dev.io + HP_BLKS);
memset_io(dev.base, 0, 0x8000);
msnd_outb(HPBLKSEL_0, dev.io + HP_BLKS);
spin_unlock_irqrestore(&dev.lock, flags);
dev.pwDSPQData = (dev.base + DSPQ_DATA_BUFF);
dev.pwMODQData = (dev.base + MODQ_DATA_BUFF);
dev.pwMIDQData = (dev.base + MIDQ_DATA_BUFF);
/* Motorola 56k shared memory base */
dev.SMA = dev.base + SMA_STRUCT_START;
/* Digital audio play queue */
dev.DAPQ = dev.base + DAPQ_OFFSET;
msnd_init_queue(dev.DAPQ, DAPQ_DATA_BUFF, DAPQ_BUFF_SIZE);
/* Digital audio record queue */
dev.DARQ = dev.base + DARQ_OFFSET;
msnd_init_queue(dev.DARQ, DARQ_DATA_BUFF, DARQ_BUFF_SIZE);
/* MIDI out queue */
dev.MODQ = dev.base + MODQ_OFFSET;
msnd_init_queue(dev.MODQ, MODQ_DATA_BUFF, MODQ_BUFF_SIZE);
/* MIDI in queue */
dev.MIDQ = dev.base + MIDQ_OFFSET;
msnd_init_queue(dev.MIDQ, MIDQ_DATA_BUFF, MIDQ_BUFF_SIZE);
/* DSP -> host message queue */
dev.DSPQ = dev.base + DSPQ_OFFSET;
msnd_init_queue(dev.DSPQ, DSPQ_DATA_BUFF, DSPQ_BUFF_SIZE);
/* Setup some DSP values */
#ifndef MSND_CLASSIC
writew(1, dev.SMA + SMA_wCurrPlayFormat);
writew(dev.play_sample_size, dev.SMA + SMA_wCurrPlaySampleSize);
writew(dev.play_channels, dev.SMA + SMA_wCurrPlayChannels);
writew(dev.play_sample_rate, dev.SMA + SMA_wCurrPlaySampleRate);
#endif
writew(dev.play_sample_rate, dev.SMA + SMA_wCalFreqAtoD);
writew(mastVolLeft, dev.SMA + SMA_wCurrMastVolLeft);
writew(mastVolRight, dev.SMA + SMA_wCurrMastVolRight);
#ifndef MSND_CLASSIC
writel(0x00010000, dev.SMA + SMA_dwCurrPlayPitch);
writel(0x00000001, dev.SMA + SMA_dwCurrPlayRate);
#endif
writew(0x303, dev.SMA + SMA_wCurrInputTagBits);
initted = 1;
return 0;
}
static int __init calibrate_adc(WORD srate)
{
writew(srate, dev.SMA + SMA_wCalFreqAtoD);
if (dev.calibrate_signal == 0)
writew(readw(dev.SMA + SMA_wCurrHostStatusFlags)
| 0x0001, dev.SMA + SMA_wCurrHostStatusFlags);
else
writew(readw(dev.SMA + SMA_wCurrHostStatusFlags)
& ~0x0001, dev.SMA + SMA_wCurrHostStatusFlags);
if (msnd_send_word(&dev, 0, 0, HDEXAR_CAL_A_TO_D) == 0 &&
chk_send_dsp_cmd(&dev, HDEX_AUX_REQ) == 0) {
current->state = TASK_INTERRUPTIBLE;
schedule_timeout(HZ / 3);
return 0;
}
printk(KERN_WARNING LOGNAME ": ADC calibration failed\n");
return -EIO;
}
static int upload_dsp_code(void)
{
int ret = 0;
msnd_outb(HPBLKSEL_0, dev.io + HP_BLKS);
#ifndef HAVE_DSPCODEH
INITCODESIZE = mod_firmware_load(INITCODEFILE, &INITCODE);
if (!INITCODE) {
printk(KERN_ERR LOGNAME ": Error loading " INITCODEFILE);
return -EBUSY;
}
PERMCODESIZE = mod_firmware_load(PERMCODEFILE, &PERMCODE);
if (!PERMCODE) {
printk(KERN_ERR LOGNAME ": Error loading " PERMCODEFILE);
vfree(INITCODE);
return -EBUSY;
}
#endif
memcpy_toio(dev.base, PERMCODE, PERMCODESIZE);
if (msnd_upload_host(&dev, INITCODE, INITCODESIZE) < 0) {
printk(KERN_WARNING LOGNAME ": Error uploading to DSP\n");
ret = -ENODEV;
goto out;
}
#ifdef HAVE_DSPCODEH
printk(KERN_INFO LOGNAME ": DSP firmware uploaded (resident)\n");
#else
printk(KERN_INFO LOGNAME ": DSP firmware uploaded\n");
#endif
out:
#ifndef HAVE_DSPCODEH
vfree(INITCODE);
vfree(PERMCODE);
#endif
return ret;
}
#ifdef MSND_CLASSIC
static void reset_proteus(void)
{
msnd_outb(HPPRORESET_ON, dev.io + HP_PROR);
mdelay(TIME_PRO_RESET);
msnd_outb(HPPRORESET_OFF, dev.io + HP_PROR);
mdelay(TIME_PRO_RESET_DONE);
}
#endif
static int initialize(void)
{
int err, timeout;
#ifdef MSND_CLASSIC
msnd_outb(HPWAITSTATE_0, dev.io + HP_WAIT);
msnd_outb(HPBITMODE_16, dev.io + HP_BITM);
reset_proteus();
#endif
if ((err = init_sma()) < 0) {
printk(KERN_WARNING LOGNAME ": Cannot initialize SMA\n");
return err;
}
if ((err = reset_dsp()) < 0)
return err;
if ((err = upload_dsp_code()) < 0) {
printk(KERN_WARNING LOGNAME ": Cannot upload DSP code\n");
return err;
}
timeout = 200;
while (readw(dev.base)) {
mdelay(1);
if (!timeout--) {
printk(KERN_DEBUG LOGNAME ": DSP reset timeout\n");
return -EIO;
}
}
mixer_setup();
return 0;
}
static int dsp_full_reset(void)
{
int rv;
if (test_bit(F_RESETTING, &dev.flags) || ++dev.nresets > 10)
return 0;
set_bit(F_RESETTING, &dev.flags);
printk(KERN_INFO LOGNAME ": DSP reset\n");
dsp_halt(NULL); /* Unconditionally halt */
if ((rv = initialize()))
printk(KERN_WARNING LOGNAME ": DSP reset failed\n");
force_recsrc(dev.recsrc);
dsp_open(NULL);
clear_bit(F_RESETTING, &dev.flags);
return rv;
}
static int __init attach_multisound(void)
{
int err;
if ((err = request_irq(dev.irq, intr, 0, dev.name, &dev)) < 0) {
printk(KERN_ERR LOGNAME ": Couldn't grab IRQ %d\n", dev.irq);
return err;
}
if (request_region(dev.io, dev.numio, dev.name) == NULL) {
free_irq(dev.irq, &dev);
return -EBUSY;
}
err = dsp_full_reset();
if (err < 0) {
release_region(dev.io, dev.numio);
free_irq(dev.irq, &dev);
return err;
}
if ((err = msnd_register(&dev)) < 0) {
printk(KERN_ERR LOGNAME ": Unable to register MultiSound\n");
release_region(dev.io, dev.numio);
free_irq(dev.irq, &dev);
return err;
}
if ((dev.dsp_minor = register_sound_dsp(&dev_fileops, -1)) < 0) {
printk(KERN_ERR LOGNAME ": Unable to register DSP operations\n");
msnd_unregister(&dev);
release_region(dev.io, dev.numio);
free_irq(dev.irq, &dev);
return dev.dsp_minor;
}
if ((dev.mixer_minor = register_sound_mixer(&dev_fileops, -1)) < 0) {
printk(KERN_ERR LOGNAME ": Unable to register mixer operations\n");
unregister_sound_mixer(dev.mixer_minor);
msnd_unregister(&dev);
release_region(dev.io, dev.numio);
free_irq(dev.irq, &dev);
return dev.mixer_minor;
}
dev.ext_midi_dev = dev.hdr_midi_dev = -1;
disable_irq(dev.irq);
calibrate_adc(dev.play_sample_rate);
#ifndef MSND_CLASSIC
force_recsrc(SOUND_MASK_IMIX);
#endif
return 0;
}
static void __exit unload_multisound(void)
{
release_region(dev.io, dev.numio);
free_irq(dev.irq, &dev);
unregister_sound_mixer(dev.mixer_minor);
unregister_sound_dsp(dev.dsp_minor);
msnd_unregister(&dev);
}
#ifndef MSND_CLASSIC
/* Pinnacle/Fiji Logical Device Configuration */
static int __init msnd_write_cfg(int cfg, int reg, int value)
{
msnd_outb(reg, cfg);
msnd_outb(value, cfg + 1);
if (value != msnd_inb(cfg + 1)) {
printk(KERN_ERR LOGNAME ": msnd_write_cfg: I/O error\n");
return -EIO;
}
return 0;
}
static int __init msnd_write_cfg_io0(int cfg, int num, WORD io)
{
if (msnd_write_cfg(cfg, IREG_LOGDEVICE, num))
return -EIO;
if (msnd_write_cfg(cfg, IREG_IO0_BASEHI, HIBYTE(io)))
return -EIO;
if (msnd_write_cfg(cfg, IREG_IO0_BASELO, LOBYTE(io)))
return -EIO;
return 0;
}
static int __init msnd_write_cfg_io1(int cfg, int num, WORD io)
{
if (msnd_write_cfg(cfg, IREG_LOGDEVICE, num))
return -EIO;
if (msnd_write_cfg(cfg, IREG_IO1_BASEHI, HIBYTE(io)))
return -EIO;
if (msnd_write_cfg(cfg, IREG_IO1_BASELO, LOBYTE(io)))
return -EIO;
return 0;
}
static int __init msnd_write_cfg_irq(int cfg, int num, WORD irq)
{
if (msnd_write_cfg(cfg, IREG_LOGDEVICE, num))
return -EIO;
if (msnd_write_cfg(cfg, IREG_IRQ_NUMBER, LOBYTE(irq)))
return -EIO;
if (msnd_write_cfg(cfg, IREG_IRQ_TYPE, IRQTYPE_EDGE))
return -EIO;
return 0;
}
static int __init msnd_write_cfg_mem(int cfg, int num, int mem)
{
WORD wmem;
mem >>= 8;
mem &= 0xfff;
wmem = (WORD)mem;
if (msnd_write_cfg(cfg, IREG_LOGDEVICE, num))
return -EIO;
if (msnd_write_cfg(cfg, IREG_MEMBASEHI, HIBYTE(wmem)))
return -EIO;
if (msnd_write_cfg(cfg, IREG_MEMBASELO, LOBYTE(wmem)))
return -EIO;
if (wmem && msnd_write_cfg(cfg, IREG_MEMCONTROL, (MEMTYPE_HIADDR | MEMTYPE_16BIT)))
return -EIO;
return 0;
}
static int __init msnd_activate_logical(int cfg, int num)
{
if (msnd_write_cfg(cfg, IREG_LOGDEVICE, num))
return -EIO;
if (msnd_write_cfg(cfg, IREG_ACTIVATE, LD_ACTIVATE))
return -EIO;
return 0;
}
static int __init msnd_write_cfg_logical(int cfg, int num, WORD io0, WORD io1, WORD irq, int mem)
{
if (msnd_write_cfg(cfg, IREG_LOGDEVICE, num))
return -EIO;
if (msnd_write_cfg_io0(cfg, num, io0))
return -EIO;
if (msnd_write_cfg_io1(cfg, num, io1))
return -EIO;
if (msnd_write_cfg_irq(cfg, num, irq))
return -EIO;
if (msnd_write_cfg_mem(cfg, num, mem))
return -EIO;
if (msnd_activate_logical(cfg, num))
return -EIO;
return 0;
}
typedef struct msnd_pinnacle_cfg_device {
WORD io0, io1, irq;
int mem;
} msnd_pinnacle_cfg_t[4];
static int __init msnd_pinnacle_cfg_devices(int cfg, int reset, msnd_pinnacle_cfg_t device)
{
int i;
/* Reset devices if told to */
if (reset) {
printk(KERN_INFO LOGNAME ": Resetting all devices\n");
for (i = 0; i < 4; ++i)
if (msnd_write_cfg_logical(cfg, i, 0, 0, 0, 0))
return -EIO;
}
/* Configure specified devices */
for (i = 0; i < 4; ++i) {
switch (i) {
case 0: /* DSP */
if (!(device[i].io0 && device[i].irq && device[i].mem))
continue;
break;
case 1: /* MPU */
if (!(device[i].io0 && device[i].irq))
continue;
printk(KERN_INFO LOGNAME
": Configuring MPU to I/O 0x%x IRQ %d\n",
device[i].io0, device[i].irq);
break;
case 2: /* IDE */
if (!(device[i].io0 && device[i].io1 && device[i].irq))
continue;
printk(KERN_INFO LOGNAME
": Configuring IDE to I/O 0x%x, 0x%x IRQ %d\n",
device[i].io0, device[i].io1, device[i].irq);
break;
case 3: /* Joystick */
if (!(device[i].io0))
continue;
printk(KERN_INFO LOGNAME
": Configuring joystick to I/O 0x%x\n",
device[i].io0);
break;
}
/* Configure the device */
if (msnd_write_cfg_logical(cfg, i, device[i].io0, device[i].io1, device[i].irq, device[i].mem))
return -EIO;
}
return 0;
}
#endif
#ifdef MODULE
MODULE_AUTHOR ("Andrew Veliath <andrewtv@usa.net>");
MODULE_DESCRIPTION ("Turtle Beach " LONGNAME " Linux Driver");
MODULE_LICENSE("GPL");
static int io __initdata = -1;
static int irq __initdata = -1;
static int mem __initdata = -1;
static int write_ndelay __initdata = -1;
#ifndef MSND_CLASSIC
/* Pinnacle/Fiji non-PnP Config Port */
static int cfg __initdata = -1;
/* Extra Peripheral Configuration */
static int reset __initdata = 0;
static int mpu_io __initdata = 0;
static int mpu_irq __initdata = 0;
static int ide_io0 __initdata = 0;
static int ide_io1 __initdata = 0;
static int ide_irq __initdata = 0;
static int joystick_io __initdata = 0;
/* If we have the digital daugherboard... */
static bool digital __initdata = false;
#endif
static int fifosize __initdata = DEFFIFOSIZE;
static int calibrate_signal __initdata = 0;
#else /* not a module */
static int write_ndelay __initdata = -1;
#ifdef MSND_CLASSIC
static int io __initdata = CONFIG_MSNDCLAS_IO;
static int irq __initdata = CONFIG_MSNDCLAS_IRQ;
static int mem __initdata = CONFIG_MSNDCLAS_MEM;
#else /* Pinnacle/Fiji */
static int io __initdata = CONFIG_MSNDPIN_IO;
static int irq __initdata = CONFIG_MSNDPIN_IRQ;
static int mem __initdata = CONFIG_MSNDPIN_MEM;
/* Pinnacle/Fiji non-PnP Config Port */
#ifdef CONFIG_MSNDPIN_NONPNP
# ifndef CONFIG_MSNDPIN_CFG
# define CONFIG_MSNDPIN_CFG 0x250
# endif
#else
# ifdef CONFIG_MSNDPIN_CFG
# undef CONFIG_MSNDPIN_CFG
# endif
# define CONFIG_MSNDPIN_CFG -1
#endif
static int cfg __initdata = CONFIG_MSNDPIN_CFG;
/* If not a module, we don't need to bother with reset=1 */
static int reset;
/* Extra Peripheral Configuration (Default: Disable) */
#ifndef CONFIG_MSNDPIN_MPU_IO
# define CONFIG_MSNDPIN_MPU_IO 0
#endif
static int mpu_io __initdata = CONFIG_MSNDPIN_MPU_IO;
#ifndef CONFIG_MSNDPIN_MPU_IRQ
# define CONFIG_MSNDPIN_MPU_IRQ 0
#endif
static int mpu_irq __initdata = CONFIG_MSNDPIN_MPU_IRQ;
#ifndef CONFIG_MSNDPIN_IDE_IO0
# define CONFIG_MSNDPIN_IDE_IO0 0
#endif
static int ide_io0 __initdata = CONFIG_MSNDPIN_IDE_IO0;
#ifndef CONFIG_MSNDPIN_IDE_IO1
# define CONFIG_MSNDPIN_IDE_IO1 0
#endif
static int ide_io1 __initdata = CONFIG_MSNDPIN_IDE_IO1;
#ifndef CONFIG_MSNDPIN_IDE_IRQ
# define CONFIG_MSNDPIN_IDE_IRQ 0
#endif
static int ide_irq __initdata = CONFIG_MSNDPIN_IDE_IRQ;
#ifndef CONFIG_MSNDPIN_JOYSTICK_IO
# define CONFIG_MSNDPIN_JOYSTICK_IO 0
#endif
static int joystick_io __initdata = CONFIG_MSNDPIN_JOYSTICK_IO;
/* Have SPDIF (Digital) Daughterboard */
#ifndef CONFIG_MSNDPIN_DIGITAL
# define CONFIG_MSNDPIN_DIGITAL 0
#endif
static bool digital __initdata = CONFIG_MSNDPIN_DIGITAL;
#endif /* MSND_CLASSIC */
#ifndef CONFIG_MSND_FIFOSIZE
# define CONFIG_MSND_FIFOSIZE DEFFIFOSIZE
#endif
static int fifosize __initdata = CONFIG_MSND_FIFOSIZE;
#ifndef CONFIG_MSND_CALSIGNAL
# define CONFIG_MSND_CALSIGNAL 0
#endif
static int
calibrate_signal __initdata = CONFIG_MSND_CALSIGNAL;
#endif /* MODULE */
module_param (io, int, 0);
module_param (irq, int, 0);
module_param (mem, int, 0);
module_param (write_ndelay, int, 0);
module_param (fifosize, int, 0);
module_param (calibrate_signal, int, 0);
#ifndef MSND_CLASSIC
module_param (digital, bool, 0);
module_param (cfg, int, 0);
module_param (reset, int, 0);
module_param (mpu_io, int, 0);
module_param (mpu_irq, int, 0);
module_param (ide_io0, int, 0);
module_param (ide_io1, int, 0);
module_param (ide_irq, int, 0);
module_param (joystick_io, int, 0);
#endif
static int __init msnd_init(void)
{
int err;
#ifndef MSND_CLASSIC
static msnd_pinnacle_cfg_t pinnacle_devs;
#endif /* MSND_CLASSIC */
printk(KERN_INFO LOGNAME ": Turtle Beach " LONGNAME " Linux Driver Version "
VERSION ", Copyright (C) 1998 Andrew Veliath\n");
if (io == -1 || irq == -1 || mem == -1)
printk(KERN_WARNING LOGNAME ": io, irq and mem must be set\n");
#ifdef MSND_CLASSIC
if (io == -1 ||
!(io == 0x290 ||
io == 0x260 ||
io == 0x250 ||
io == 0x240 ||
io == 0x230 ||
io == 0x220 ||
io == 0x210 ||
io == 0x3e0)) {
printk(KERN_ERR LOGNAME ": \"io\" - DSP I/O base must be set to 0x210, 0x220, 0x230, 0x240, 0x250, 0x260, 0x290, or 0x3E0\n");
return -EINVAL;
}
#else
if (io == -1 ||
io < 0x100 ||
io > 0x3e0 ||
(io % 0x10) != 0) {
printk(KERN_ERR LOGNAME ": \"io\" - DSP I/O base must within the range 0x100 to 0x3E0 and must be evenly divisible by 0x10\n");
return -EINVAL;
}
#endif /* MSND_CLASSIC */
if (irq == -1 ||
!(irq == 5 ||
irq == 7 ||
irq == 9 ||
irq == 10 ||
irq == 11 ||
irq == 12)) {
printk(KERN_ERR LOGNAME ": \"irq\" - must be set to 5, 7, 9, 10, 11 or 12\n");
return -EINVAL;
}
if (mem == -1 ||
!(mem == 0xb0000 ||
mem == 0xc8000 ||
mem == 0xd0000 ||
mem == 0xd8000 ||
mem == 0xe0000 ||
mem == 0xe8000)) {
printk(KERN_ERR LOGNAME ": \"mem\" - must be set to "
"0xb0000, 0xc8000, 0xd0000, 0xd8000, 0xe0000 or 0xe8000\n");
return -EINVAL;
}
#ifdef MSND_CLASSIC
switch (irq) {
case 5: dev.irqid = HPIRQ_5; break;
case 7: dev.irqid = HPIRQ_7; break;
case 9: dev.irqid = HPIRQ_9; break;
case 10: dev.irqid = HPIRQ_10; break;
case 11: dev.irqid = HPIRQ_11; break;
case 12: dev.irqid = HPIRQ_12; break;
}
switch (mem) {
case 0xb0000: dev.memid = HPMEM_B000; break;
case 0xc8000: dev.memid = HPMEM_C800; break;
case 0xd0000: dev.memid = HPMEM_D000; break;
case 0xd8000: dev.memid = HPMEM_D800; break;
case 0xe0000: dev.memid = HPMEM_E000; break;
case 0xe8000: dev.memid = HPMEM_E800; break;
}
#else
if (cfg == -1) {
printk(KERN_INFO LOGNAME ": Assuming PnP mode\n");
} else if (cfg != 0x250 && cfg != 0x260 && cfg != 0x270) {
printk(KERN_INFO LOGNAME ": Config port must be 0x250, 0x260 or 0x270 (or unspecified for PnP mode)\n");
return -EINVAL;
} else {
printk(KERN_INFO LOGNAME ": Non-PnP mode: configuring at port 0x%x\n", cfg);
/* DSP */
pinnacle_devs[0].io0 = io;
pinnacle_devs[0].irq = irq;
pinnacle_devs[0].mem = mem;
/* The following are Pinnacle specific */
/* MPU */
pinnacle_devs[1].io0 = mpu_io;
pinnacle_devs[1].irq = mpu_irq;
/* IDE */
pinnacle_devs[2].io0 = ide_io0;
pinnacle_devs[2].io1 = ide_io1;
pinnacle_devs[2].irq = ide_irq;
/* Joystick */
pinnacle_devs[3].io0 = joystick_io;
if (!request_region(cfg, 2, "Pinnacle/Fiji Config")) {
printk(KERN_ERR LOGNAME ": Config port 0x%x conflict\n", cfg);
return -EIO;
}
if (msnd_pinnacle_cfg_devices(cfg, reset, pinnacle_devs)) {
printk(KERN_ERR LOGNAME ": Device configuration error\n");
release_region(cfg, 2);
return -EIO;
}
release_region(cfg, 2);
}
#endif /* MSND_CLASSIC */
if (fifosize < 16)
fifosize = 16;
if (fifosize > 1024)
fifosize = 1024;
set_default_audio_parameters();
#ifdef MSND_CLASSIC
dev.type = msndClassic;
#else
dev.type = msndPinnacle;
#endif
dev.io = io;
dev.numio = DSP_NUMIO;
dev.irq = irq;
dev.base = ioremap(mem, 0x8000);
dev.fifosize = fifosize * 1024;
dev.calibrate_signal = calibrate_signal ? 1 : 0;
dev.recsrc = 0;
dev.dspq_data_buff = DSPQ_DATA_BUFF;
dev.dspq_buff_size = DSPQ_BUFF_SIZE;
if (write_ndelay == -1)
write_ndelay = CONFIG_MSND_WRITE_NDELAY;
if (write_ndelay)
clear_bit(F_DISABLE_WRITE_NDELAY, &dev.flags);
else
set_bit(F_DISABLE_WRITE_NDELAY, &dev.flags);
#ifndef MSND_CLASSIC
if (digital)
set_bit(F_HAVEDIGITAL, &dev.flags);
#endif
init_waitqueue_head(&dev.writeblock);
init_waitqueue_head(&dev.readblock);
init_waitqueue_head(&dev.writeflush);
msnd_fifo_init(&dev.DAPF);
msnd_fifo_init(&dev.DARF);
spin_lock_init(&dev.lock);
printk(KERN_INFO LOGNAME ": %u byte audio FIFOs (x2)\n", dev.fifosize);
if ((err = msnd_fifo_alloc(&dev.DAPF, dev.fifosize)) < 0) {
printk(KERN_ERR LOGNAME ": Couldn't allocate write FIFO\n");
return err;
}
if ((err = msnd_fifo_alloc(&dev.DARF, dev.fifosize)) < 0) {
printk(KERN_ERR LOGNAME ": Couldn't allocate read FIFO\n");
msnd_fifo_free(&dev.DAPF);
return err;
}
if ((err = probe_multisound()) < 0) {
printk(KERN_ERR LOGNAME ": Probe failed\n");
msnd_fifo_free(&dev.DAPF);
msnd_fifo_free(&dev.DARF);
return err;
}
if ((err = attach_multisound()) < 0) {
printk(KERN_ERR LOGNAME ": Attach failed\n");
msnd_fifo_free(&dev.DAPF);
msnd_fifo_free(&dev.DARF);
return err;
}
return 0;
}
static void __exit msdn_cleanup(void)
{
unload_multisound();
msnd_fifo_free(&dev.DAPF);
msnd_fifo_free(&dev.DARF);
}
module_init(msnd_init);
module_exit(msdn_cleanup);
| gpl-2.0 |
robcore/S4-AEL-Kernel-Lollipop | drivers/spi/spi-tegra.c | 5062 | 16018 | /*
* Driver for Nvidia TEGRA spi controller.
*
* Copyright (C) 2010 Google, Inc.
*
* Author:
* Erik Gilling <konkers@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <mach/dma.h>
#define SLINK_COMMAND 0x000
#define SLINK_BIT_LENGTH(x) (((x) & 0x1f) << 0)
#define SLINK_WORD_SIZE(x) (((x) & 0x1f) << 5)
#define SLINK_BOTH_EN (1 << 10)
#define SLINK_CS_SW (1 << 11)
#define SLINK_CS_VALUE (1 << 12)
#define SLINK_CS_POLARITY (1 << 13)
#define SLINK_IDLE_SDA_DRIVE_LOW (0 << 16)
#define SLINK_IDLE_SDA_DRIVE_HIGH (1 << 16)
#define SLINK_IDLE_SDA_PULL_LOW (2 << 16)
#define SLINK_IDLE_SDA_PULL_HIGH (3 << 16)
#define SLINK_IDLE_SDA_MASK (3 << 16)
#define SLINK_CS_POLARITY1 (1 << 20)
#define SLINK_CK_SDA (1 << 21)
#define SLINK_CS_POLARITY2 (1 << 22)
#define SLINK_CS_POLARITY3 (1 << 23)
#define SLINK_IDLE_SCLK_DRIVE_LOW (0 << 24)
#define SLINK_IDLE_SCLK_DRIVE_HIGH (1 << 24)
#define SLINK_IDLE_SCLK_PULL_LOW (2 << 24)
#define SLINK_IDLE_SCLK_PULL_HIGH (3 << 24)
#define SLINK_IDLE_SCLK_MASK (3 << 24)
#define SLINK_M_S (1 << 28)
#define SLINK_WAIT (1 << 29)
#define SLINK_GO (1 << 30)
#define SLINK_ENB (1 << 31)
#define SLINK_COMMAND2 0x004
#define SLINK_LSBFE (1 << 0)
#define SLINK_SSOE (1 << 1)
#define SLINK_SPIE (1 << 4)
#define SLINK_BIDIROE (1 << 6)
#define SLINK_MODFEN (1 << 7)
#define SLINK_INT_SIZE(x) (((x) & 0x1f) << 8)
#define SLINK_CS_ACTIVE_BETWEEN (1 << 17)
#define SLINK_SS_EN_CS(x) (((x) & 0x3) << 18)
#define SLINK_SS_SETUP(x) (((x) & 0x3) << 20)
#define SLINK_FIFO_REFILLS_0 (0 << 22)
#define SLINK_FIFO_REFILLS_1 (1 << 22)
#define SLINK_FIFO_REFILLS_2 (2 << 22)
#define SLINK_FIFO_REFILLS_3 (3 << 22)
#define SLINK_FIFO_REFILLS_MASK (3 << 22)
#define SLINK_WAIT_PACK_INT(x) (((x) & 0x7) << 26)
#define SLINK_SPC0 (1 << 29)
#define SLINK_TXEN (1 << 30)
#define SLINK_RXEN (1 << 31)
#define SLINK_STATUS 0x008
#define SLINK_COUNT(val) (((val) >> 0) & 0x1f)
#define SLINK_WORD(val) (((val) >> 5) & 0x1f)
#define SLINK_BLK_CNT(val) (((val) >> 0) & 0xffff)
#define SLINK_MODF (1 << 16)
#define SLINK_RX_UNF (1 << 18)
#define SLINK_TX_OVF (1 << 19)
#define SLINK_TX_FULL (1 << 20)
#define SLINK_TX_EMPTY (1 << 21)
#define SLINK_RX_FULL (1 << 22)
#define SLINK_RX_EMPTY (1 << 23)
#define SLINK_TX_UNF (1 << 24)
#define SLINK_RX_OVF (1 << 25)
#define SLINK_TX_FLUSH (1 << 26)
#define SLINK_RX_FLUSH (1 << 27)
#define SLINK_SCLK (1 << 28)
#define SLINK_ERR (1 << 29)
#define SLINK_RDY (1 << 30)
#define SLINK_BSY (1 << 31)
#define SLINK_MAS_DATA 0x010
#define SLINK_SLAVE_DATA 0x014
#define SLINK_DMA_CTL 0x018
#define SLINK_DMA_BLOCK_SIZE(x) (((x) & 0xffff) << 0)
#define SLINK_TX_TRIG_1 (0 << 16)
#define SLINK_TX_TRIG_4 (1 << 16)
#define SLINK_TX_TRIG_8 (2 << 16)
#define SLINK_TX_TRIG_16 (3 << 16)
#define SLINK_TX_TRIG_MASK (3 << 16)
#define SLINK_RX_TRIG_1 (0 << 18)
#define SLINK_RX_TRIG_4 (1 << 18)
#define SLINK_RX_TRIG_8 (2 << 18)
#define SLINK_RX_TRIG_16 (3 << 18)
#define SLINK_RX_TRIG_MASK (3 << 18)
#define SLINK_PACKED (1 << 20)
#define SLINK_PACK_SIZE_4 (0 << 21)
#define SLINK_PACK_SIZE_8 (1 << 21)
#define SLINK_PACK_SIZE_16 (2 << 21)
#define SLINK_PACK_SIZE_32 (3 << 21)
#define SLINK_PACK_SIZE_MASK (3 << 21)
#define SLINK_IE_TXC (1 << 26)
#define SLINK_IE_RXC (1 << 27)
#define SLINK_DMA_EN (1 << 31)
#define SLINK_STATUS2 0x01c
#define SLINK_TX_FIFO_EMPTY_COUNT(val) (((val) & 0x3f) >> 0)
#define SLINK_RX_FIFO_FULL_COUNT(val) (((val) & 0x3f) >> 16)
#define SLINK_TX_FIFO 0x100
#define SLINK_RX_FIFO 0x180
static const unsigned long spi_tegra_req_sels[] = {
TEGRA_DMA_REQ_SEL_SL2B1,
TEGRA_DMA_REQ_SEL_SL2B2,
TEGRA_DMA_REQ_SEL_SL2B3,
TEGRA_DMA_REQ_SEL_SL2B4,
};
#define BB_LEN 32
struct spi_tegra_data {
struct spi_master *master;
struct platform_device *pdev;
spinlock_t lock;
struct clk *clk;
void __iomem *base;
unsigned long phys;
u32 cur_speed;
struct list_head queue;
struct spi_transfer *cur;
unsigned cur_pos;
unsigned cur_len;
unsigned cur_bytes_per_word;
/* The tegra spi controller has a bug which causes the first word
* in PIO transactions to be garbage. Since packed DMA transactions
* require transfers to be 4 byte aligned we need a bounce buffer
* for the generic case.
*/
struct tegra_dma_req rx_dma_req;
struct tegra_dma_channel *rx_dma;
u32 *rx_bb;
dma_addr_t rx_bb_phys;
};
static inline unsigned long spi_tegra_readl(struct spi_tegra_data *tspi,
unsigned long reg)
{
return readl(tspi->base + reg);
}
static inline void spi_tegra_writel(struct spi_tegra_data *tspi,
unsigned long val,
unsigned long reg)
{
writel(val, tspi->base + reg);
}
static void spi_tegra_go(struct spi_tegra_data *tspi)
{
unsigned long val;
wmb();
val = spi_tegra_readl(tspi, SLINK_DMA_CTL);
val &= ~SLINK_DMA_BLOCK_SIZE(~0) & ~SLINK_DMA_EN;
val |= SLINK_DMA_BLOCK_SIZE(tspi->rx_dma_req.size / 4 - 1);
spi_tegra_writel(tspi, val, SLINK_DMA_CTL);
tegra_dma_enqueue_req(tspi->rx_dma, &tspi->rx_dma_req);
val |= SLINK_DMA_EN;
spi_tegra_writel(tspi, val, SLINK_DMA_CTL);
}
static unsigned spi_tegra_fill_tx_fifo(struct spi_tegra_data *tspi,
struct spi_transfer *t)
{
unsigned len = min(t->len - tspi->cur_pos, BB_LEN *
tspi->cur_bytes_per_word);
u8 *tx_buf = (u8 *)t->tx_buf + tspi->cur_pos;
int i, j;
unsigned long val;
val = spi_tegra_readl(tspi, SLINK_COMMAND);
val &= ~SLINK_WORD_SIZE(~0);
val |= SLINK_WORD_SIZE(len / tspi->cur_bytes_per_word - 1);
spi_tegra_writel(tspi, val, SLINK_COMMAND);
for (i = 0; i < len; i += tspi->cur_bytes_per_word) {
val = 0;
for (j = 0; j < tspi->cur_bytes_per_word; j++)
val |= tx_buf[i + j] << j * 8;
spi_tegra_writel(tspi, val, SLINK_TX_FIFO);
}
tspi->rx_dma_req.size = len / tspi->cur_bytes_per_word * 4;
return len;
}
static unsigned spi_tegra_drain_rx_fifo(struct spi_tegra_data *tspi,
struct spi_transfer *t)
{
unsigned len = tspi->cur_len;
u8 *rx_buf = (u8 *)t->rx_buf + tspi->cur_pos;
int i, j;
unsigned long val;
for (i = 0; i < len; i += tspi->cur_bytes_per_word) {
val = tspi->rx_bb[i / tspi->cur_bytes_per_word];
for (j = 0; j < tspi->cur_bytes_per_word; j++)
rx_buf[i + j] = (val >> (j * 8)) & 0xff;
}
return len;
}
static void spi_tegra_start_transfer(struct spi_device *spi,
struct spi_transfer *t)
{
struct spi_tegra_data *tspi = spi_master_get_devdata(spi->master);
u32 speed;
u8 bits_per_word;
unsigned long val;
speed = t->speed_hz ? t->speed_hz : spi->max_speed_hz;
bits_per_word = t->bits_per_word ? t->bits_per_word :
spi->bits_per_word;
tspi->cur_bytes_per_word = (bits_per_word - 1) / 8 + 1;
if (speed != tspi->cur_speed)
clk_set_rate(tspi->clk, speed);
if (tspi->cur_speed == 0)
clk_enable(tspi->clk);
tspi->cur_speed = speed;
val = spi_tegra_readl(tspi, SLINK_COMMAND2);
val &= ~SLINK_SS_EN_CS(~0) | SLINK_RXEN | SLINK_TXEN;
if (t->rx_buf)
val |= SLINK_RXEN;
if (t->tx_buf)
val |= SLINK_TXEN;
val |= SLINK_SS_EN_CS(spi->chip_select);
val |= SLINK_SPIE;
spi_tegra_writel(tspi, val, SLINK_COMMAND2);
val = spi_tegra_readl(tspi, SLINK_COMMAND);
val &= ~SLINK_BIT_LENGTH(~0);
val |= SLINK_BIT_LENGTH(bits_per_word - 1);
/* FIXME: should probably control CS manually so that we can be sure
* it does not go low between transfer and to support delay_usecs
* correctly.
*/
val &= ~SLINK_IDLE_SCLK_MASK & ~SLINK_CK_SDA & ~SLINK_CS_SW;
if (spi->mode & SPI_CPHA)
val |= SLINK_CK_SDA;
if (spi->mode & SPI_CPOL)
val |= SLINK_IDLE_SCLK_DRIVE_HIGH;
else
val |= SLINK_IDLE_SCLK_DRIVE_LOW;
val |= SLINK_M_S;
spi_tegra_writel(tspi, val, SLINK_COMMAND);
spi_tegra_writel(tspi, SLINK_RX_FLUSH | SLINK_TX_FLUSH, SLINK_STATUS);
tspi->cur = t;
tspi->cur_pos = 0;
tspi->cur_len = spi_tegra_fill_tx_fifo(tspi, t);
spi_tegra_go(tspi);
}
static void spi_tegra_start_message(struct spi_device *spi,
struct spi_message *m)
{
struct spi_transfer *t;
m->actual_length = 0;
m->status = 0;
t = list_first_entry(&m->transfers, struct spi_transfer, transfer_list);
spi_tegra_start_transfer(spi, t);
}
static void tegra_spi_rx_dma_complete(struct tegra_dma_req *req)
{
struct spi_tegra_data *tspi = req->dev;
unsigned long flags;
struct spi_message *m;
struct spi_device *spi;
int timeout = 0;
unsigned long val;
/* the SPI controller may come back with both the BSY and RDY bits
* set. In this case we need to wait for the BSY bit to clear so
* that we are sure the DMA is finished. 1000 reads was empirically
* determined to be long enough.
*/
while (timeout++ < 1000) {
if (!(spi_tegra_readl(tspi, SLINK_STATUS) & SLINK_BSY))
break;
}
spin_lock_irqsave(&tspi->lock, flags);
val = spi_tegra_readl(tspi, SLINK_STATUS);
val |= SLINK_RDY;
spi_tegra_writel(tspi, val, SLINK_STATUS);
m = list_first_entry(&tspi->queue, struct spi_message, queue);
if (timeout >= 1000)
m->status = -EIO;
spi = m->state;
tspi->cur_pos += spi_tegra_drain_rx_fifo(tspi, tspi->cur);
m->actual_length += tspi->cur_pos;
if (tspi->cur_pos < tspi->cur->len) {
tspi->cur_len = spi_tegra_fill_tx_fifo(tspi, tspi->cur);
spi_tegra_go(tspi);
} else if (!list_is_last(&tspi->cur->transfer_list,
&m->transfers)) {
tspi->cur = list_first_entry(&tspi->cur->transfer_list,
struct spi_transfer,
transfer_list);
spi_tegra_start_transfer(spi, tspi->cur);
} else {
list_del(&m->queue);
m->complete(m->context);
if (!list_empty(&tspi->queue)) {
m = list_first_entry(&tspi->queue, struct spi_message,
queue);
spi = m->state;
spi_tegra_start_message(spi, m);
} else {
clk_disable(tspi->clk);
tspi->cur_speed = 0;
}
}
spin_unlock_irqrestore(&tspi->lock, flags);
}
static int spi_tegra_setup(struct spi_device *spi)
{
struct spi_tegra_data *tspi = spi_master_get_devdata(spi->master);
unsigned long cs_bit;
unsigned long val;
unsigned long flags;
dev_dbg(&spi->dev, "setup %d bpw, %scpol, %scpha, %dHz\n",
spi->bits_per_word,
spi->mode & SPI_CPOL ? "" : "~",
spi->mode & SPI_CPHA ? "" : "~",
spi->max_speed_hz);
switch (spi->chip_select) {
case 0:
cs_bit = SLINK_CS_POLARITY;
break;
case 1:
cs_bit = SLINK_CS_POLARITY1;
break;
case 2:
cs_bit = SLINK_CS_POLARITY2;
break;
case 4:
cs_bit = SLINK_CS_POLARITY3;
break;
default:
return -EINVAL;
}
spin_lock_irqsave(&tspi->lock, flags);
val = spi_tegra_readl(tspi, SLINK_COMMAND);
if (spi->mode & SPI_CS_HIGH)
val |= cs_bit;
else
val &= ~cs_bit;
spi_tegra_writel(tspi, val, SLINK_COMMAND);
spin_unlock_irqrestore(&tspi->lock, flags);
return 0;
}
static int spi_tegra_transfer(struct spi_device *spi, struct spi_message *m)
{
struct spi_tegra_data *tspi = spi_master_get_devdata(spi->master);
struct spi_transfer *t;
unsigned long flags;
int was_empty;
if (list_empty(&m->transfers) || !m->complete)
return -EINVAL;
list_for_each_entry(t, &m->transfers, transfer_list) {
if (t->bits_per_word < 0 || t->bits_per_word > 32)
return -EINVAL;
if (t->len == 0)
return -EINVAL;
if (!t->rx_buf && !t->tx_buf)
return -EINVAL;
}
m->state = spi;
spin_lock_irqsave(&tspi->lock, flags);
was_empty = list_empty(&tspi->queue);
list_add_tail(&m->queue, &tspi->queue);
if (was_empty)
spi_tegra_start_message(spi, m);
spin_unlock_irqrestore(&tspi->lock, flags);
return 0;
}
static int __devinit spi_tegra_probe(struct platform_device *pdev)
{
struct spi_master *master;
struct spi_tegra_data *tspi;
struct resource *r;
int ret;
master = spi_alloc_master(&pdev->dev, sizeof *tspi);
if (master == NULL) {
dev_err(&pdev->dev, "master allocation failed\n");
return -ENOMEM;
}
/* the spi->mode bits understood by this driver: */
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
master->bus_num = pdev->id;
master->setup = spi_tegra_setup;
master->transfer = spi_tegra_transfer;
master->num_chipselect = 4;
dev_set_drvdata(&pdev->dev, master);
tspi = spi_master_get_devdata(master);
tspi->master = master;
tspi->pdev = pdev;
spin_lock_init(&tspi->lock);
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (r == NULL) {
ret = -ENODEV;
goto err0;
}
if (!request_mem_region(r->start, resource_size(r),
dev_name(&pdev->dev))) {
ret = -EBUSY;
goto err0;
}
tspi->phys = r->start;
tspi->base = ioremap(r->start, resource_size(r));
if (!tspi->base) {
dev_err(&pdev->dev, "can't ioremap iomem\n");
ret = -ENOMEM;
goto err1;
}
tspi->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(tspi->clk)) {
dev_err(&pdev->dev, "can not get clock\n");
ret = PTR_ERR(tspi->clk);
goto err2;
}
INIT_LIST_HEAD(&tspi->queue);
tspi->rx_dma = tegra_dma_allocate_channel(TEGRA_DMA_MODE_ONESHOT);
if (!tspi->rx_dma) {
dev_err(&pdev->dev, "can not allocate rx dma channel\n");
ret = -ENODEV;
goto err3;
}
tspi->rx_bb = dma_alloc_coherent(&pdev->dev, sizeof(u32) * BB_LEN,
&tspi->rx_bb_phys, GFP_KERNEL);
if (!tspi->rx_bb) {
dev_err(&pdev->dev, "can not allocate rx bounce buffer\n");
ret = -ENOMEM;
goto err4;
}
tspi->rx_dma_req.complete = tegra_spi_rx_dma_complete;
tspi->rx_dma_req.to_memory = 1;
tspi->rx_dma_req.dest_addr = tspi->rx_bb_phys;
tspi->rx_dma_req.dest_bus_width = 32;
tspi->rx_dma_req.source_addr = tspi->phys + SLINK_RX_FIFO;
tspi->rx_dma_req.source_bus_width = 32;
tspi->rx_dma_req.source_wrap = 4;
tspi->rx_dma_req.req_sel = spi_tegra_req_sels[pdev->id];
tspi->rx_dma_req.dev = tspi;
master->dev.of_node = pdev->dev.of_node;
ret = spi_register_master(master);
if (ret < 0)
goto err5;
return ret;
err5:
dma_free_coherent(&pdev->dev, sizeof(u32) * BB_LEN,
tspi->rx_bb, tspi->rx_bb_phys);
err4:
tegra_dma_free_channel(tspi->rx_dma);
err3:
clk_put(tspi->clk);
err2:
iounmap(tspi->base);
err1:
release_mem_region(r->start, resource_size(r));
err0:
spi_master_put(master);
return ret;
}
static int __devexit spi_tegra_remove(struct platform_device *pdev)
{
struct spi_master *master;
struct spi_tegra_data *tspi;
struct resource *r;
master = dev_get_drvdata(&pdev->dev);
tspi = spi_master_get_devdata(master);
spi_unregister_master(master);
tegra_dma_free_channel(tspi->rx_dma);
dma_free_coherent(&pdev->dev, sizeof(u32) * BB_LEN,
tspi->rx_bb, tspi->rx_bb_phys);
clk_put(tspi->clk);
iounmap(tspi->base);
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(r->start, resource_size(r));
return 0;
}
MODULE_ALIAS("platform:spi_tegra");
#ifdef CONFIG_OF
static struct of_device_id spi_tegra_of_match_table[] __devinitdata = {
{ .compatible = "nvidia,tegra20-spi", },
{}
};
MODULE_DEVICE_TABLE(of, spi_tegra_of_match_table);
#else /* CONFIG_OF */
#define spi_tegra_of_match_table NULL
#endif /* CONFIG_OF */
static struct platform_driver spi_tegra_driver = {
.driver = {
.name = "spi_tegra",
.owner = THIS_MODULE,
.of_match_table = spi_tegra_of_match_table,
},
.probe = spi_tegra_probe,
.remove = __devexit_p(spi_tegra_remove),
};
module_platform_driver(spi_tegra_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Radium-Devices/Radium_jflte | arch/sh/kernel/cpu/sh3/setup-sh7705.c | 5062 | 5837 | /*
* SH7705 Setup
*
* Copyright (C) 2006 - 2009 Paul Mundt
* Copyright (C) 2007 Nobuhiro Iwamatsu
*
* 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/platform_device.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/serial.h>
#include <linux/serial_sci.h>
#include <linux/sh_timer.h>
#include <asm/rtc.h>
#include <cpu/serial.h>
enum {
UNUSED = 0,
/* interrupt sources */
IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5,
PINT07, PINT815,
DMAC, SCIF0, SCIF2, ADC_ADI, USB,
TPU0, TPU1, TPU2, TPU3,
TMU0, TMU1, TMU2,
RTC, WDT, REF_RCMI,
};
static struct intc_vect vectors[] __initdata = {
/* IRQ0->5 are handled in setup-sh3.c */
INTC_VECT(PINT07, 0x700), INTC_VECT(PINT815, 0x720),
INTC_VECT(DMAC, 0x800), INTC_VECT(DMAC, 0x820),
INTC_VECT(DMAC, 0x840), INTC_VECT(DMAC, 0x860),
INTC_VECT(SCIF0, 0x880), INTC_VECT(SCIF0, 0x8a0),
INTC_VECT(SCIF0, 0x8e0),
INTC_VECT(SCIF2, 0x900), INTC_VECT(SCIF2, 0x920),
INTC_VECT(SCIF2, 0x960),
INTC_VECT(ADC_ADI, 0x980),
INTC_VECT(USB, 0xa20), INTC_VECT(USB, 0xa40),
INTC_VECT(TPU0, 0xc00), INTC_VECT(TPU1, 0xc20),
INTC_VECT(TPU2, 0xc80), INTC_VECT(TPU3, 0xca0),
INTC_VECT(TMU0, 0x400), INTC_VECT(TMU1, 0x420),
INTC_VECT(TMU2, 0x440), INTC_VECT(TMU2, 0x460),
INTC_VECT(RTC, 0x480), INTC_VECT(RTC, 0x4a0),
INTC_VECT(RTC, 0x4c0),
INTC_VECT(WDT, 0x560),
INTC_VECT(REF_RCMI, 0x580),
};
static struct intc_prio_reg prio_registers[] __initdata = {
{ 0xfffffee2, 0, 16, 4, /* IPRA */ { TMU0, TMU1, TMU2, RTC } },
{ 0xfffffee4, 0, 16, 4, /* IPRB */ { WDT, REF_RCMI, 0, 0 } },
{ 0xa4000016, 0, 16, 4, /* IPRC */ { IRQ3, IRQ2, IRQ1, IRQ0 } },
{ 0xa4000018, 0, 16, 4, /* IPRD */ { PINT07, PINT815, IRQ5, IRQ4 } },
{ 0xa400001a, 0, 16, 4, /* IPRE */ { DMAC, SCIF0, SCIF2, ADC_ADI } },
{ 0xa4080000, 0, 16, 4, /* IPRF */ { 0, 0, USB } },
{ 0xa4080002, 0, 16, 4, /* IPRG */ { TPU0, TPU1 } },
{ 0xa4080004, 0, 16, 4, /* IPRH */ { TPU2, TPU3 } },
};
static DECLARE_INTC_DESC(intc_desc, "sh7705", vectors, NULL,
NULL, prio_registers, NULL);
static struct plat_sci_port scif0_platform_data = {
.mapbase = 0xa4410000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_TIE | SCSCR_RIE | SCSCR_TE |
SCSCR_RE | SCSCR_CKE1 | SCSCR_CKE0,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIF,
.irqs = { 56, 56, 56 },
.ops = &sh770x_sci_port_ops,
.regtype = SCIx_SH7705_SCIF_REGTYPE,
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &scif0_platform_data,
},
};
static struct plat_sci_port scif1_platform_data = {
.mapbase = 0xa4400000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_TIE | SCSCR_RIE | SCSCR_TE | SCSCR_RE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIF,
.irqs = { 52, 52, 52 },
.ops = &sh770x_sci_port_ops,
.regtype = SCIx_SH7705_SCIF_REGTYPE,
};
static struct platform_device scif1_device = {
.name = "sh-sci",
.id = 1,
.dev = {
.platform_data = &scif1_platform_data,
},
};
static struct resource rtc_resources[] = {
[0] = {
.start = 0xfffffec0,
.end = 0xfffffec0 + 0x1e,
.flags = IORESOURCE_IO,
},
[1] = {
.start = 20,
.flags = IORESOURCE_IRQ,
},
};
static struct sh_rtc_platform_info rtc_info = {
.capabilities = RTC_CAP_4_DIGIT_YEAR,
};
static struct platform_device rtc_device = {
.name = "sh-rtc",
.id = -1,
.num_resources = ARRAY_SIZE(rtc_resources),
.resource = rtc_resources,
.dev = {
.platform_data = &rtc_info,
},
};
static struct sh_timer_config tmu0_platform_data = {
.channel_offset = 0x02,
.timer_bit = 0,
.clockevent_rating = 200,
};
static struct resource tmu0_resources[] = {
[0] = {
.start = 0xfffffe94,
.end = 0xfffffe9f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 16,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu0_device = {
.name = "sh_tmu",
.id = 0,
.dev = {
.platform_data = &tmu0_platform_data,
},
.resource = tmu0_resources,
.num_resources = ARRAY_SIZE(tmu0_resources),
};
static struct sh_timer_config tmu1_platform_data = {
.channel_offset = 0xe,
.timer_bit = 1,
.clocksource_rating = 200,
};
static struct resource tmu1_resources[] = {
[0] = {
.start = 0xfffffea0,
.end = 0xfffffeab,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 17,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu1_device = {
.name = "sh_tmu",
.id = 1,
.dev = {
.platform_data = &tmu1_platform_data,
},
.resource = tmu1_resources,
.num_resources = ARRAY_SIZE(tmu1_resources),
};
static struct sh_timer_config tmu2_platform_data = {
.channel_offset = 0x1a,
.timer_bit = 2,
};
static struct resource tmu2_resources[] = {
[0] = {
.start = 0xfffffeac,
.end = 0xfffffebb,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 18,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu2_device = {
.name = "sh_tmu",
.id = 2,
.dev = {
.platform_data = &tmu2_platform_data,
},
.resource = tmu2_resources,
.num_resources = ARRAY_SIZE(tmu2_resources),
};
static struct platform_device *sh7705_devices[] __initdata = {
&scif0_device,
&scif1_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
&rtc_device,
};
static int __init sh7705_devices_setup(void)
{
return platform_add_devices(sh7705_devices,
ARRAY_SIZE(sh7705_devices));
}
arch_initcall(sh7705_devices_setup);
static struct platform_device *sh7705_early_devices[] __initdata = {
&scif0_device,
&scif1_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
};
void __init plat_early_device_setup(void)
{
early_platform_add_devices(sh7705_early_devices,
ARRAY_SIZE(sh7705_early_devices));
}
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
plat_irq_setup_sh3();
}
| gpl-2.0 |
aditisstillalive/android_kernel_lge_hammerhead_wake | fs/ext3/ioctl.c | 5062 | 7622 | /*
* linux/fs/ext3/ioctl.c
*
* Copyright (C) 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*/
#include <linux/mount.h>
#include <linux/compat.h>
#include <asm/uaccess.h>
#include "ext3.h"
long ext3_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = filp->f_dentry->d_inode;
struct ext3_inode_info *ei = EXT3_I(inode);
unsigned int flags;
unsigned short rsv_window_size;
ext3_debug ("cmd = %u, arg = %lu\n", cmd, arg);
switch (cmd) {
case EXT3_IOC_GETFLAGS:
ext3_get_inode_flags(ei);
flags = ei->i_flags & EXT3_FL_USER_VISIBLE;
return put_user(flags, (int __user *) arg);
case EXT3_IOC_SETFLAGS: {
handle_t *handle = NULL;
int err;
struct ext3_iloc iloc;
unsigned int oldflags;
unsigned int jflag;
if (!inode_owner_or_capable(inode))
return -EACCES;
if (get_user(flags, (int __user *) arg))
return -EFAULT;
err = mnt_want_write_file(filp);
if (err)
return err;
flags = ext3_mask_flags(inode->i_mode, flags);
mutex_lock(&inode->i_mutex);
/* Is it quota file? Do not allow user to mess with it */
err = -EPERM;
if (IS_NOQUOTA(inode))
goto flags_out;
oldflags = ei->i_flags;
/* The JOURNAL_DATA flag is modifiable only by root */
jflag = flags & EXT3_JOURNAL_DATA_FL;
/*
* The IMMUTABLE and APPEND_ONLY flags can only be changed by
* the relevant capability.
*
* This test looks nicer. Thanks to Pauline Middelink
*/
if ((flags ^ oldflags) & (EXT3_APPEND_FL | EXT3_IMMUTABLE_FL)) {
if (!capable(CAP_LINUX_IMMUTABLE))
goto flags_out;
}
/*
* The JOURNAL_DATA flag can only be changed by
* the relevant capability.
*/
if ((jflag ^ oldflags) & (EXT3_JOURNAL_DATA_FL)) {
if (!capable(CAP_SYS_RESOURCE))
goto flags_out;
}
handle = ext3_journal_start(inode, 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto flags_out;
}
if (IS_SYNC(inode))
handle->h_sync = 1;
err = ext3_reserve_inode_write(handle, inode, &iloc);
if (err)
goto flags_err;
flags = flags & EXT3_FL_USER_MODIFIABLE;
flags |= oldflags & ~EXT3_FL_USER_MODIFIABLE;
ei->i_flags = flags;
ext3_set_inode_flags(inode);
inode->i_ctime = CURRENT_TIME_SEC;
err = ext3_mark_iloc_dirty(handle, inode, &iloc);
flags_err:
ext3_journal_stop(handle);
if (err)
goto flags_out;
if ((jflag ^ oldflags) & (EXT3_JOURNAL_DATA_FL))
err = ext3_change_inode_journal_flag(inode, jflag);
flags_out:
mutex_unlock(&inode->i_mutex);
mnt_drop_write_file(filp);
return err;
}
case EXT3_IOC_GETVERSION:
case EXT3_IOC_GETVERSION_OLD:
return put_user(inode->i_generation, (int __user *) arg);
case EXT3_IOC_SETVERSION:
case EXT3_IOC_SETVERSION_OLD: {
handle_t *handle;
struct ext3_iloc iloc;
__u32 generation;
int err;
if (!inode_owner_or_capable(inode))
return -EPERM;
err = mnt_want_write_file(filp);
if (err)
return err;
if (get_user(generation, (int __user *) arg)) {
err = -EFAULT;
goto setversion_out;
}
mutex_lock(&inode->i_mutex);
handle = ext3_journal_start(inode, 1);
if (IS_ERR(handle)) {
err = PTR_ERR(handle);
goto unlock_out;
}
err = ext3_reserve_inode_write(handle, inode, &iloc);
if (err == 0) {
inode->i_ctime = CURRENT_TIME_SEC;
inode->i_generation = generation;
err = ext3_mark_iloc_dirty(handle, inode, &iloc);
}
ext3_journal_stop(handle);
unlock_out:
mutex_unlock(&inode->i_mutex);
setversion_out:
mnt_drop_write_file(filp);
return err;
}
case EXT3_IOC_GETRSVSZ:
if (test_opt(inode->i_sb, RESERVATION)
&& S_ISREG(inode->i_mode)
&& ei->i_block_alloc_info) {
rsv_window_size = ei->i_block_alloc_info->rsv_window_node.rsv_goal_size;
return put_user(rsv_window_size, (int __user *)arg);
}
return -ENOTTY;
case EXT3_IOC_SETRSVSZ: {
int err;
if (!test_opt(inode->i_sb, RESERVATION) ||!S_ISREG(inode->i_mode))
return -ENOTTY;
err = mnt_want_write_file(filp);
if (err)
return err;
if (!inode_owner_or_capable(inode)) {
err = -EACCES;
goto setrsvsz_out;
}
if (get_user(rsv_window_size, (int __user *)arg)) {
err = -EFAULT;
goto setrsvsz_out;
}
if (rsv_window_size > EXT3_MAX_RESERVE_BLOCKS)
rsv_window_size = EXT3_MAX_RESERVE_BLOCKS;
/*
* need to allocate reservation structure for this inode
* before set the window size
*/
mutex_lock(&ei->truncate_mutex);
if (!ei->i_block_alloc_info)
ext3_init_block_alloc_info(inode);
if (ei->i_block_alloc_info){
struct ext3_reserve_window_node *rsv = &ei->i_block_alloc_info->rsv_window_node;
rsv->rsv_goal_size = rsv_window_size;
}
mutex_unlock(&ei->truncate_mutex);
setrsvsz_out:
mnt_drop_write_file(filp);
return err;
}
case EXT3_IOC_GROUP_EXTEND: {
ext3_fsblk_t n_blocks_count;
struct super_block *sb = inode->i_sb;
int err, err2;
if (!capable(CAP_SYS_RESOURCE))
return -EPERM;
err = mnt_want_write_file(filp);
if (err)
return err;
if (get_user(n_blocks_count, (__u32 __user *)arg)) {
err = -EFAULT;
goto group_extend_out;
}
err = ext3_group_extend(sb, EXT3_SB(sb)->s_es, n_blocks_count);
journal_lock_updates(EXT3_SB(sb)->s_journal);
err2 = journal_flush(EXT3_SB(sb)->s_journal);
journal_unlock_updates(EXT3_SB(sb)->s_journal);
if (err == 0)
err = err2;
group_extend_out:
mnt_drop_write_file(filp);
return err;
}
case EXT3_IOC_GROUP_ADD: {
struct ext3_new_group_data input;
struct super_block *sb = inode->i_sb;
int err, err2;
if (!capable(CAP_SYS_RESOURCE))
return -EPERM;
err = mnt_want_write_file(filp);
if (err)
return err;
if (copy_from_user(&input, (struct ext3_new_group_input __user *)arg,
sizeof(input))) {
err = -EFAULT;
goto group_add_out;
}
err = ext3_group_add(sb, &input);
journal_lock_updates(EXT3_SB(sb)->s_journal);
err2 = journal_flush(EXT3_SB(sb)->s_journal);
journal_unlock_updates(EXT3_SB(sb)->s_journal);
if (err == 0)
err = err2;
group_add_out:
mnt_drop_write_file(filp);
return err;
}
case FITRIM: {
struct super_block *sb = inode->i_sb;
struct fstrim_range range;
int ret = 0;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (copy_from_user(&range, (struct fstrim_range __user *)arg,
sizeof(range)))
return -EFAULT;
ret = ext3_trim_fs(sb, &range);
if (ret < 0)
return ret;
if (copy_to_user((struct fstrim_range __user *)arg, &range,
sizeof(range)))
return -EFAULT;
return 0;
}
default:
return -ENOTTY;
}
}
#ifdef CONFIG_COMPAT
long ext3_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
/* These are just misnamed, they actually get/put from/to user an int */
switch (cmd) {
case EXT3_IOC32_GETFLAGS:
cmd = EXT3_IOC_GETFLAGS;
break;
case EXT3_IOC32_SETFLAGS:
cmd = EXT3_IOC_SETFLAGS;
break;
case EXT3_IOC32_GETVERSION:
cmd = EXT3_IOC_GETVERSION;
break;
case EXT3_IOC32_SETVERSION:
cmd = EXT3_IOC_SETVERSION;
break;
case EXT3_IOC32_GROUP_EXTEND:
cmd = EXT3_IOC_GROUP_EXTEND;
break;
case EXT3_IOC32_GETVERSION_OLD:
cmd = EXT3_IOC_GETVERSION_OLD;
break;
case EXT3_IOC32_SETVERSION_OLD:
cmd = EXT3_IOC_SETVERSION_OLD;
break;
#ifdef CONFIG_JBD_DEBUG
case EXT3_IOC32_WAIT_FOR_READONLY:
cmd = EXT3_IOC_WAIT_FOR_READONLY;
break;
#endif
case EXT3_IOC32_GETRSVSZ:
cmd = EXT3_IOC_GETRSVSZ;
break;
case EXT3_IOC32_SETRSVSZ:
cmd = EXT3_IOC_SETRSVSZ;
break;
case EXT3_IOC_GROUP_ADD:
break;
default:
return -ENOIOCTLCMD;
}
return ext3_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
}
#endif
| gpl-2.0 |
sinutech/sinuos-kernel | drivers/spi/spi-tegra.c | 5062 | 16018 | /*
* Driver for Nvidia TEGRA spi controller.
*
* Copyright (C) 2010 Google, Inc.
*
* Author:
* Erik Gilling <konkers@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <mach/dma.h>
#define SLINK_COMMAND 0x000
#define SLINK_BIT_LENGTH(x) (((x) & 0x1f) << 0)
#define SLINK_WORD_SIZE(x) (((x) & 0x1f) << 5)
#define SLINK_BOTH_EN (1 << 10)
#define SLINK_CS_SW (1 << 11)
#define SLINK_CS_VALUE (1 << 12)
#define SLINK_CS_POLARITY (1 << 13)
#define SLINK_IDLE_SDA_DRIVE_LOW (0 << 16)
#define SLINK_IDLE_SDA_DRIVE_HIGH (1 << 16)
#define SLINK_IDLE_SDA_PULL_LOW (2 << 16)
#define SLINK_IDLE_SDA_PULL_HIGH (3 << 16)
#define SLINK_IDLE_SDA_MASK (3 << 16)
#define SLINK_CS_POLARITY1 (1 << 20)
#define SLINK_CK_SDA (1 << 21)
#define SLINK_CS_POLARITY2 (1 << 22)
#define SLINK_CS_POLARITY3 (1 << 23)
#define SLINK_IDLE_SCLK_DRIVE_LOW (0 << 24)
#define SLINK_IDLE_SCLK_DRIVE_HIGH (1 << 24)
#define SLINK_IDLE_SCLK_PULL_LOW (2 << 24)
#define SLINK_IDLE_SCLK_PULL_HIGH (3 << 24)
#define SLINK_IDLE_SCLK_MASK (3 << 24)
#define SLINK_M_S (1 << 28)
#define SLINK_WAIT (1 << 29)
#define SLINK_GO (1 << 30)
#define SLINK_ENB (1 << 31)
#define SLINK_COMMAND2 0x004
#define SLINK_LSBFE (1 << 0)
#define SLINK_SSOE (1 << 1)
#define SLINK_SPIE (1 << 4)
#define SLINK_BIDIROE (1 << 6)
#define SLINK_MODFEN (1 << 7)
#define SLINK_INT_SIZE(x) (((x) & 0x1f) << 8)
#define SLINK_CS_ACTIVE_BETWEEN (1 << 17)
#define SLINK_SS_EN_CS(x) (((x) & 0x3) << 18)
#define SLINK_SS_SETUP(x) (((x) & 0x3) << 20)
#define SLINK_FIFO_REFILLS_0 (0 << 22)
#define SLINK_FIFO_REFILLS_1 (1 << 22)
#define SLINK_FIFO_REFILLS_2 (2 << 22)
#define SLINK_FIFO_REFILLS_3 (3 << 22)
#define SLINK_FIFO_REFILLS_MASK (3 << 22)
#define SLINK_WAIT_PACK_INT(x) (((x) & 0x7) << 26)
#define SLINK_SPC0 (1 << 29)
#define SLINK_TXEN (1 << 30)
#define SLINK_RXEN (1 << 31)
#define SLINK_STATUS 0x008
#define SLINK_COUNT(val) (((val) >> 0) & 0x1f)
#define SLINK_WORD(val) (((val) >> 5) & 0x1f)
#define SLINK_BLK_CNT(val) (((val) >> 0) & 0xffff)
#define SLINK_MODF (1 << 16)
#define SLINK_RX_UNF (1 << 18)
#define SLINK_TX_OVF (1 << 19)
#define SLINK_TX_FULL (1 << 20)
#define SLINK_TX_EMPTY (1 << 21)
#define SLINK_RX_FULL (1 << 22)
#define SLINK_RX_EMPTY (1 << 23)
#define SLINK_TX_UNF (1 << 24)
#define SLINK_RX_OVF (1 << 25)
#define SLINK_TX_FLUSH (1 << 26)
#define SLINK_RX_FLUSH (1 << 27)
#define SLINK_SCLK (1 << 28)
#define SLINK_ERR (1 << 29)
#define SLINK_RDY (1 << 30)
#define SLINK_BSY (1 << 31)
#define SLINK_MAS_DATA 0x010
#define SLINK_SLAVE_DATA 0x014
#define SLINK_DMA_CTL 0x018
#define SLINK_DMA_BLOCK_SIZE(x) (((x) & 0xffff) << 0)
#define SLINK_TX_TRIG_1 (0 << 16)
#define SLINK_TX_TRIG_4 (1 << 16)
#define SLINK_TX_TRIG_8 (2 << 16)
#define SLINK_TX_TRIG_16 (3 << 16)
#define SLINK_TX_TRIG_MASK (3 << 16)
#define SLINK_RX_TRIG_1 (0 << 18)
#define SLINK_RX_TRIG_4 (1 << 18)
#define SLINK_RX_TRIG_8 (2 << 18)
#define SLINK_RX_TRIG_16 (3 << 18)
#define SLINK_RX_TRIG_MASK (3 << 18)
#define SLINK_PACKED (1 << 20)
#define SLINK_PACK_SIZE_4 (0 << 21)
#define SLINK_PACK_SIZE_8 (1 << 21)
#define SLINK_PACK_SIZE_16 (2 << 21)
#define SLINK_PACK_SIZE_32 (3 << 21)
#define SLINK_PACK_SIZE_MASK (3 << 21)
#define SLINK_IE_TXC (1 << 26)
#define SLINK_IE_RXC (1 << 27)
#define SLINK_DMA_EN (1 << 31)
#define SLINK_STATUS2 0x01c
#define SLINK_TX_FIFO_EMPTY_COUNT(val) (((val) & 0x3f) >> 0)
#define SLINK_RX_FIFO_FULL_COUNT(val) (((val) & 0x3f) >> 16)
#define SLINK_TX_FIFO 0x100
#define SLINK_RX_FIFO 0x180
static const unsigned long spi_tegra_req_sels[] = {
TEGRA_DMA_REQ_SEL_SL2B1,
TEGRA_DMA_REQ_SEL_SL2B2,
TEGRA_DMA_REQ_SEL_SL2B3,
TEGRA_DMA_REQ_SEL_SL2B4,
};
#define BB_LEN 32
struct spi_tegra_data {
struct spi_master *master;
struct platform_device *pdev;
spinlock_t lock;
struct clk *clk;
void __iomem *base;
unsigned long phys;
u32 cur_speed;
struct list_head queue;
struct spi_transfer *cur;
unsigned cur_pos;
unsigned cur_len;
unsigned cur_bytes_per_word;
/* The tegra spi controller has a bug which causes the first word
* in PIO transactions to be garbage. Since packed DMA transactions
* require transfers to be 4 byte aligned we need a bounce buffer
* for the generic case.
*/
struct tegra_dma_req rx_dma_req;
struct tegra_dma_channel *rx_dma;
u32 *rx_bb;
dma_addr_t rx_bb_phys;
};
static inline unsigned long spi_tegra_readl(struct spi_tegra_data *tspi,
unsigned long reg)
{
return readl(tspi->base + reg);
}
static inline void spi_tegra_writel(struct spi_tegra_data *tspi,
unsigned long val,
unsigned long reg)
{
writel(val, tspi->base + reg);
}
static void spi_tegra_go(struct spi_tegra_data *tspi)
{
unsigned long val;
wmb();
val = spi_tegra_readl(tspi, SLINK_DMA_CTL);
val &= ~SLINK_DMA_BLOCK_SIZE(~0) & ~SLINK_DMA_EN;
val |= SLINK_DMA_BLOCK_SIZE(tspi->rx_dma_req.size / 4 - 1);
spi_tegra_writel(tspi, val, SLINK_DMA_CTL);
tegra_dma_enqueue_req(tspi->rx_dma, &tspi->rx_dma_req);
val |= SLINK_DMA_EN;
spi_tegra_writel(tspi, val, SLINK_DMA_CTL);
}
static unsigned spi_tegra_fill_tx_fifo(struct spi_tegra_data *tspi,
struct spi_transfer *t)
{
unsigned len = min(t->len - tspi->cur_pos, BB_LEN *
tspi->cur_bytes_per_word);
u8 *tx_buf = (u8 *)t->tx_buf + tspi->cur_pos;
int i, j;
unsigned long val;
val = spi_tegra_readl(tspi, SLINK_COMMAND);
val &= ~SLINK_WORD_SIZE(~0);
val |= SLINK_WORD_SIZE(len / tspi->cur_bytes_per_word - 1);
spi_tegra_writel(tspi, val, SLINK_COMMAND);
for (i = 0; i < len; i += tspi->cur_bytes_per_word) {
val = 0;
for (j = 0; j < tspi->cur_bytes_per_word; j++)
val |= tx_buf[i + j] << j * 8;
spi_tegra_writel(tspi, val, SLINK_TX_FIFO);
}
tspi->rx_dma_req.size = len / tspi->cur_bytes_per_word * 4;
return len;
}
static unsigned spi_tegra_drain_rx_fifo(struct spi_tegra_data *tspi,
struct spi_transfer *t)
{
unsigned len = tspi->cur_len;
u8 *rx_buf = (u8 *)t->rx_buf + tspi->cur_pos;
int i, j;
unsigned long val;
for (i = 0; i < len; i += tspi->cur_bytes_per_word) {
val = tspi->rx_bb[i / tspi->cur_bytes_per_word];
for (j = 0; j < tspi->cur_bytes_per_word; j++)
rx_buf[i + j] = (val >> (j * 8)) & 0xff;
}
return len;
}
static void spi_tegra_start_transfer(struct spi_device *spi,
struct spi_transfer *t)
{
struct spi_tegra_data *tspi = spi_master_get_devdata(spi->master);
u32 speed;
u8 bits_per_word;
unsigned long val;
speed = t->speed_hz ? t->speed_hz : spi->max_speed_hz;
bits_per_word = t->bits_per_word ? t->bits_per_word :
spi->bits_per_word;
tspi->cur_bytes_per_word = (bits_per_word - 1) / 8 + 1;
if (speed != tspi->cur_speed)
clk_set_rate(tspi->clk, speed);
if (tspi->cur_speed == 0)
clk_enable(tspi->clk);
tspi->cur_speed = speed;
val = spi_tegra_readl(tspi, SLINK_COMMAND2);
val &= ~SLINK_SS_EN_CS(~0) | SLINK_RXEN | SLINK_TXEN;
if (t->rx_buf)
val |= SLINK_RXEN;
if (t->tx_buf)
val |= SLINK_TXEN;
val |= SLINK_SS_EN_CS(spi->chip_select);
val |= SLINK_SPIE;
spi_tegra_writel(tspi, val, SLINK_COMMAND2);
val = spi_tegra_readl(tspi, SLINK_COMMAND);
val &= ~SLINK_BIT_LENGTH(~0);
val |= SLINK_BIT_LENGTH(bits_per_word - 1);
/* FIXME: should probably control CS manually so that we can be sure
* it does not go low between transfer and to support delay_usecs
* correctly.
*/
val &= ~SLINK_IDLE_SCLK_MASK & ~SLINK_CK_SDA & ~SLINK_CS_SW;
if (spi->mode & SPI_CPHA)
val |= SLINK_CK_SDA;
if (spi->mode & SPI_CPOL)
val |= SLINK_IDLE_SCLK_DRIVE_HIGH;
else
val |= SLINK_IDLE_SCLK_DRIVE_LOW;
val |= SLINK_M_S;
spi_tegra_writel(tspi, val, SLINK_COMMAND);
spi_tegra_writel(tspi, SLINK_RX_FLUSH | SLINK_TX_FLUSH, SLINK_STATUS);
tspi->cur = t;
tspi->cur_pos = 0;
tspi->cur_len = spi_tegra_fill_tx_fifo(tspi, t);
spi_tegra_go(tspi);
}
static void spi_tegra_start_message(struct spi_device *spi,
struct spi_message *m)
{
struct spi_transfer *t;
m->actual_length = 0;
m->status = 0;
t = list_first_entry(&m->transfers, struct spi_transfer, transfer_list);
spi_tegra_start_transfer(spi, t);
}
static void tegra_spi_rx_dma_complete(struct tegra_dma_req *req)
{
struct spi_tegra_data *tspi = req->dev;
unsigned long flags;
struct spi_message *m;
struct spi_device *spi;
int timeout = 0;
unsigned long val;
/* the SPI controller may come back with both the BSY and RDY bits
* set. In this case we need to wait for the BSY bit to clear so
* that we are sure the DMA is finished. 1000 reads was empirically
* determined to be long enough.
*/
while (timeout++ < 1000) {
if (!(spi_tegra_readl(tspi, SLINK_STATUS) & SLINK_BSY))
break;
}
spin_lock_irqsave(&tspi->lock, flags);
val = spi_tegra_readl(tspi, SLINK_STATUS);
val |= SLINK_RDY;
spi_tegra_writel(tspi, val, SLINK_STATUS);
m = list_first_entry(&tspi->queue, struct spi_message, queue);
if (timeout >= 1000)
m->status = -EIO;
spi = m->state;
tspi->cur_pos += spi_tegra_drain_rx_fifo(tspi, tspi->cur);
m->actual_length += tspi->cur_pos;
if (tspi->cur_pos < tspi->cur->len) {
tspi->cur_len = spi_tegra_fill_tx_fifo(tspi, tspi->cur);
spi_tegra_go(tspi);
} else if (!list_is_last(&tspi->cur->transfer_list,
&m->transfers)) {
tspi->cur = list_first_entry(&tspi->cur->transfer_list,
struct spi_transfer,
transfer_list);
spi_tegra_start_transfer(spi, tspi->cur);
} else {
list_del(&m->queue);
m->complete(m->context);
if (!list_empty(&tspi->queue)) {
m = list_first_entry(&tspi->queue, struct spi_message,
queue);
spi = m->state;
spi_tegra_start_message(spi, m);
} else {
clk_disable(tspi->clk);
tspi->cur_speed = 0;
}
}
spin_unlock_irqrestore(&tspi->lock, flags);
}
static int spi_tegra_setup(struct spi_device *spi)
{
struct spi_tegra_data *tspi = spi_master_get_devdata(spi->master);
unsigned long cs_bit;
unsigned long val;
unsigned long flags;
dev_dbg(&spi->dev, "setup %d bpw, %scpol, %scpha, %dHz\n",
spi->bits_per_word,
spi->mode & SPI_CPOL ? "" : "~",
spi->mode & SPI_CPHA ? "" : "~",
spi->max_speed_hz);
switch (spi->chip_select) {
case 0:
cs_bit = SLINK_CS_POLARITY;
break;
case 1:
cs_bit = SLINK_CS_POLARITY1;
break;
case 2:
cs_bit = SLINK_CS_POLARITY2;
break;
case 4:
cs_bit = SLINK_CS_POLARITY3;
break;
default:
return -EINVAL;
}
spin_lock_irqsave(&tspi->lock, flags);
val = spi_tegra_readl(tspi, SLINK_COMMAND);
if (spi->mode & SPI_CS_HIGH)
val |= cs_bit;
else
val &= ~cs_bit;
spi_tegra_writel(tspi, val, SLINK_COMMAND);
spin_unlock_irqrestore(&tspi->lock, flags);
return 0;
}
static int spi_tegra_transfer(struct spi_device *spi, struct spi_message *m)
{
struct spi_tegra_data *tspi = spi_master_get_devdata(spi->master);
struct spi_transfer *t;
unsigned long flags;
int was_empty;
if (list_empty(&m->transfers) || !m->complete)
return -EINVAL;
list_for_each_entry(t, &m->transfers, transfer_list) {
if (t->bits_per_word < 0 || t->bits_per_word > 32)
return -EINVAL;
if (t->len == 0)
return -EINVAL;
if (!t->rx_buf && !t->tx_buf)
return -EINVAL;
}
m->state = spi;
spin_lock_irqsave(&tspi->lock, flags);
was_empty = list_empty(&tspi->queue);
list_add_tail(&m->queue, &tspi->queue);
if (was_empty)
spi_tegra_start_message(spi, m);
spin_unlock_irqrestore(&tspi->lock, flags);
return 0;
}
static int __devinit spi_tegra_probe(struct platform_device *pdev)
{
struct spi_master *master;
struct spi_tegra_data *tspi;
struct resource *r;
int ret;
master = spi_alloc_master(&pdev->dev, sizeof *tspi);
if (master == NULL) {
dev_err(&pdev->dev, "master allocation failed\n");
return -ENOMEM;
}
/* the spi->mode bits understood by this driver: */
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
master->bus_num = pdev->id;
master->setup = spi_tegra_setup;
master->transfer = spi_tegra_transfer;
master->num_chipselect = 4;
dev_set_drvdata(&pdev->dev, master);
tspi = spi_master_get_devdata(master);
tspi->master = master;
tspi->pdev = pdev;
spin_lock_init(&tspi->lock);
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (r == NULL) {
ret = -ENODEV;
goto err0;
}
if (!request_mem_region(r->start, resource_size(r),
dev_name(&pdev->dev))) {
ret = -EBUSY;
goto err0;
}
tspi->phys = r->start;
tspi->base = ioremap(r->start, resource_size(r));
if (!tspi->base) {
dev_err(&pdev->dev, "can't ioremap iomem\n");
ret = -ENOMEM;
goto err1;
}
tspi->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(tspi->clk)) {
dev_err(&pdev->dev, "can not get clock\n");
ret = PTR_ERR(tspi->clk);
goto err2;
}
INIT_LIST_HEAD(&tspi->queue);
tspi->rx_dma = tegra_dma_allocate_channel(TEGRA_DMA_MODE_ONESHOT);
if (!tspi->rx_dma) {
dev_err(&pdev->dev, "can not allocate rx dma channel\n");
ret = -ENODEV;
goto err3;
}
tspi->rx_bb = dma_alloc_coherent(&pdev->dev, sizeof(u32) * BB_LEN,
&tspi->rx_bb_phys, GFP_KERNEL);
if (!tspi->rx_bb) {
dev_err(&pdev->dev, "can not allocate rx bounce buffer\n");
ret = -ENOMEM;
goto err4;
}
tspi->rx_dma_req.complete = tegra_spi_rx_dma_complete;
tspi->rx_dma_req.to_memory = 1;
tspi->rx_dma_req.dest_addr = tspi->rx_bb_phys;
tspi->rx_dma_req.dest_bus_width = 32;
tspi->rx_dma_req.source_addr = tspi->phys + SLINK_RX_FIFO;
tspi->rx_dma_req.source_bus_width = 32;
tspi->rx_dma_req.source_wrap = 4;
tspi->rx_dma_req.req_sel = spi_tegra_req_sels[pdev->id];
tspi->rx_dma_req.dev = tspi;
master->dev.of_node = pdev->dev.of_node;
ret = spi_register_master(master);
if (ret < 0)
goto err5;
return ret;
err5:
dma_free_coherent(&pdev->dev, sizeof(u32) * BB_LEN,
tspi->rx_bb, tspi->rx_bb_phys);
err4:
tegra_dma_free_channel(tspi->rx_dma);
err3:
clk_put(tspi->clk);
err2:
iounmap(tspi->base);
err1:
release_mem_region(r->start, resource_size(r));
err0:
spi_master_put(master);
return ret;
}
static int __devexit spi_tegra_remove(struct platform_device *pdev)
{
struct spi_master *master;
struct spi_tegra_data *tspi;
struct resource *r;
master = dev_get_drvdata(&pdev->dev);
tspi = spi_master_get_devdata(master);
spi_unregister_master(master);
tegra_dma_free_channel(tspi->rx_dma);
dma_free_coherent(&pdev->dev, sizeof(u32) * BB_LEN,
tspi->rx_bb, tspi->rx_bb_phys);
clk_put(tspi->clk);
iounmap(tspi->base);
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(r->start, resource_size(r));
return 0;
}
MODULE_ALIAS("platform:spi_tegra");
#ifdef CONFIG_OF
static struct of_device_id spi_tegra_of_match_table[] __devinitdata = {
{ .compatible = "nvidia,tegra20-spi", },
{}
};
MODULE_DEVICE_TABLE(of, spi_tegra_of_match_table);
#else /* CONFIG_OF */
#define spi_tegra_of_match_table NULL
#endif /* CONFIG_OF */
static struct platform_driver spi_tegra_driver = {
.driver = {
.name = "spi_tegra",
.owner = THIS_MODULE,
.of_match_table = spi_tegra_of_match_table,
},
.probe = spi_tegra_probe,
.remove = __devexit_p(spi_tegra_remove),
};
module_platform_driver(spi_tegra_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
ReVolt-ROM/android_kernel_htc_m7 | drivers/staging/media/easycap/easycap_testcard.c | 8134 | 3628 | /******************************************************************************
* *
* easycap_testcard.c *
* *
******************************************************************************/
/*
*
* Copyright (C) 2010 R.M. Thomas <rmthomas@sciolus.org>
*
*
* 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.
*
* The software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*****************************************************************************/
#include "easycap.h"
/*****************************************************************************/
#define TESTCARD_BYTESPERLINE (2 * 720)
void
easycap_testcard(struct easycap *peasycap, int field)
{
int total;
int y, u, v, r, g, b;
unsigned char uyvy[4];
int i1, line, k, m, n, more, much, barwidth, barheight;
unsigned char bfbar[TESTCARD_BYTESPERLINE / 8], *p1, *p2;
struct data_buffer *pfield_buffer;
if (!peasycap) {
SAY("ERROR: peasycap is NULL\n");
return;
}
JOM(8, "%i=field\n", field);
switch (peasycap->width) {
case 720:
case 360: {
barwidth = (2 * 720) / 8;
break;
}
case 704:
case 352: {
barwidth = (2 * 704) / 8;
break;
}
case 640:
case 320: {
barwidth = (2 * 640) / 8;
break;
}
default: {
SAM("ERROR: cannot set barwidth\n");
return;
}
}
if (TESTCARD_BYTESPERLINE < barwidth) {
SAM("ERROR: barwidth is too large\n");
return;
}
switch (peasycap->height) {
case 576:
case 288: {
barheight = 576;
break;
}
case 480:
case 240: {
barheight = 480;
break;
}
default: {
SAM("ERROR: cannot set barheight\n");
return;
}
}
total = 0;
k = field;
m = 0;
n = 0;
for (line = 0; line < (barheight / 2); line++) {
for (i1 = 0; i1 < 8; i1++) {
r = (i1 * 256)/8;
g = (i1 * 256)/8;
b = (i1 * 256)/8;
y = 299*r/1000 + 587*g/1000 + 114*b/1000 ;
u = -147*r/1000 - 289*g/1000 + 436*b/1000 ;
u = u + 128;
v = 615*r/1000 - 515*g/1000 - 100*b/1000 ;
v = v + 128;
uyvy[0] = 0xFF & u ;
uyvy[1] = 0xFF & y ;
uyvy[2] = 0xFF & v ;
uyvy[3] = 0xFF & y ;
p1 = &bfbar[0];
while (p1 < &bfbar[barwidth]) {
*p1++ = uyvy[0] ;
*p1++ = uyvy[1] ;
*p1++ = uyvy[2] ;
*p1++ = uyvy[3] ;
total += 4;
}
p1 = &bfbar[0];
more = barwidth;
while (more) {
if ((FIELD_BUFFER_SIZE/PAGE_SIZE) <= m) {
SAM("ERROR: bad m reached\n");
return;
}
if (PAGE_SIZE < n) {
SAM("ERROR: bad n reached\n");
return;
}
if (0 > more) {
SAM("ERROR: internal fault\n");
return;
}
much = PAGE_SIZE - n;
if (much > more)
much = more;
pfield_buffer = &peasycap->field_buffer[k][m];
p2 = pfield_buffer->pgo + n;
memcpy(p2, p1, much);
p1 += much;
n += much;
more -= much;
if (PAGE_SIZE == n) {
m++;
n = 0;
}
}
}
}
return;
}
| gpl-2.0 |
willizambranoback/evolution_CM13 | drivers/block/aoe/aoemain.c | 9926 | 2032 | /* Copyright (c) 2007 Coraid, Inc. See COPYING for GPL terms. */
/*
* aoemain.c
* Module initialization routines, discover timer
*/
#include <linux/hdreg.h>
#include <linux/blkdev.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include "aoe.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Sam Hopkins <sah@coraid.com>");
MODULE_DESCRIPTION("AoE block/char driver for 2.6.2 and newer 2.6 kernels");
MODULE_VERSION(VERSION);
enum { TINIT, TRUN, TKILL };
static void
discover_timer(ulong vp)
{
static struct timer_list t;
static volatile ulong die;
static spinlock_t lock;
ulong flags;
enum { DTIMERTICK = HZ * 60 }; /* one minute */
switch (vp) {
case TINIT:
init_timer(&t);
spin_lock_init(&lock);
t.data = TRUN;
t.function = discover_timer;
die = 0;
case TRUN:
spin_lock_irqsave(&lock, flags);
if (!die) {
t.expires = jiffies + DTIMERTICK;
add_timer(&t);
}
spin_unlock_irqrestore(&lock, flags);
aoecmd_cfg(0xffff, 0xff);
return;
case TKILL:
spin_lock_irqsave(&lock, flags);
die = 1;
spin_unlock_irqrestore(&lock, flags);
del_timer_sync(&t);
default:
return;
}
}
static void
aoe_exit(void)
{
discover_timer(TKILL);
aoenet_exit();
unregister_blkdev(AOE_MAJOR, DEVICE_NAME);
aoechr_exit();
aoedev_exit();
aoeblk_exit(); /* free cache after de-allocating bufs */
}
static int __init
aoe_init(void)
{
int ret;
ret = aoedev_init();
if (ret)
return ret;
ret = aoechr_init();
if (ret)
goto chr_fail;
ret = aoeblk_init();
if (ret)
goto blk_fail;
ret = aoenet_init();
if (ret)
goto net_fail;
ret = register_blkdev(AOE_MAJOR, DEVICE_NAME);
if (ret < 0) {
printk(KERN_ERR "aoe: can't register major\n");
goto blkreg_fail;
}
printk(KERN_INFO "aoe: AoE v%s initialised.\n", VERSION);
discover_timer(TINIT);
return 0;
blkreg_fail:
aoenet_exit();
net_fail:
aoeblk_exit();
blk_fail:
aoechr_exit();
chr_fail:
aoedev_exit();
printk(KERN_INFO "aoe: initialisation failure.\n");
return ret;
}
module_init(aoe_init);
module_exit(aoe_exit);
| gpl-2.0 |
IxLabs/lguest64 | arch/frv/mm/mmu-context.c | 13766 | 5333 | /* mmu-context.c: MMU context allocation and management
*
* Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/sched.h>
#include <linux/mm.h>
#include <asm/tlbflush.h>
#define NR_CXN 4096
static unsigned long cxn_bitmap[NR_CXN / (sizeof(unsigned long) * 8)];
static LIST_HEAD(cxn_owners_lru);
static DEFINE_SPINLOCK(cxn_owners_lock);
int __nongpreldata cxn_pinned = -1;
/*****************************************************************************/
/*
* initialise a new context
*/
int init_new_context(struct task_struct *tsk, struct mm_struct *mm)
{
memset(&mm->context, 0, sizeof(mm->context));
INIT_LIST_HEAD(&mm->context.id_link);
mm->context.itlb_cached_pge = 0xffffffffUL;
mm->context.dtlb_cached_pge = 0xffffffffUL;
return 0;
} /* end init_new_context() */
/*****************************************************************************/
/*
* make sure a kernel MMU context has a CPU context number
* - call with cxn_owners_lock held
*/
static unsigned get_cxn(mm_context_t *ctx)
{
struct list_head *_p;
mm_context_t *p;
unsigned cxn;
if (!list_empty(&ctx->id_link)) {
list_move_tail(&ctx->id_link, &cxn_owners_lru);
}
else {
/* find the first unallocated context number
* - 0 is reserved for the kernel
*/
cxn = find_next_zero_bit(cxn_bitmap, NR_CXN, 1);
if (cxn < NR_CXN) {
set_bit(cxn, cxn_bitmap);
}
else {
/* none remaining - need to steal someone else's cxn */
p = NULL;
list_for_each(_p, &cxn_owners_lru) {
p = list_entry(_p, mm_context_t, id_link);
if (!p->id_busy && p->id != cxn_pinned)
break;
}
BUG_ON(_p == &cxn_owners_lru);
cxn = p->id;
p->id = 0;
list_del_init(&p->id_link);
__flush_tlb_mm(cxn);
}
ctx->id = cxn;
list_add_tail(&ctx->id_link, &cxn_owners_lru);
}
return ctx->id;
} /* end get_cxn() */
/*****************************************************************************/
/*
* restore the current TLB miss handler mapped page tables into the MMU context and set up a
* mapping for the page directory
*/
void change_mm_context(mm_context_t *old, mm_context_t *ctx, pgd_t *pgd)
{
unsigned long _pgd;
_pgd = virt_to_phys(pgd);
/* save the state of the outgoing MMU context */
old->id_busy = 0;
asm volatile("movsg scr0,%0" : "=r"(old->itlb_cached_pge));
asm volatile("movsg dampr4,%0" : "=r"(old->itlb_ptd_mapping));
asm volatile("movsg scr1,%0" : "=r"(old->dtlb_cached_pge));
asm volatile("movsg dampr5,%0" : "=r"(old->dtlb_ptd_mapping));
/* select an MMU context number */
spin_lock(&cxn_owners_lock);
get_cxn(ctx);
ctx->id_busy = 1;
spin_unlock(&cxn_owners_lock);
asm volatile("movgs %0,cxnr" : : "r"(ctx->id));
/* restore the state of the incoming MMU context */
asm volatile("movgs %0,scr0" : : "r"(ctx->itlb_cached_pge));
asm volatile("movgs %0,dampr4" : : "r"(ctx->itlb_ptd_mapping));
asm volatile("movgs %0,scr1" : : "r"(ctx->dtlb_cached_pge));
asm volatile("movgs %0,dampr5" : : "r"(ctx->dtlb_ptd_mapping));
/* map the PGD into uncached virtual memory */
asm volatile("movgs %0,ttbr" : : "r"(_pgd));
asm volatile("movgs %0,dampr3"
:: "r"(_pgd | xAMPRx_L | xAMPRx_M | xAMPRx_SS_16Kb |
xAMPRx_S | xAMPRx_C | xAMPRx_V));
} /* end change_mm_context() */
/*****************************************************************************/
/*
* finished with an MMU context number
*/
void destroy_context(struct mm_struct *mm)
{
mm_context_t *ctx = &mm->context;
spin_lock(&cxn_owners_lock);
if (!list_empty(&ctx->id_link)) {
if (ctx->id == cxn_pinned)
cxn_pinned = -1;
list_del_init(&ctx->id_link);
clear_bit(ctx->id, cxn_bitmap);
__flush_tlb_mm(ctx->id);
ctx->id = 0;
}
spin_unlock(&cxn_owners_lock);
} /* end destroy_context() */
/*****************************************************************************/
/*
* display the MMU context currently a process is currently using
*/
#ifdef CONFIG_PROC_FS
char *proc_pid_status_frv_cxnr(struct mm_struct *mm, char *buffer)
{
spin_lock(&cxn_owners_lock);
buffer += sprintf(buffer, "CXNR: %u\n", mm->context.id);
spin_unlock(&cxn_owners_lock);
return buffer;
} /* end proc_pid_status_frv_cxnr() */
#endif
/*****************************************************************************/
/*
* (un)pin a process's mm_struct's MMU context ID
*/
int cxn_pin_by_pid(pid_t pid)
{
struct task_struct *tsk;
struct mm_struct *mm = NULL;
int ret;
/* unpin if pid is zero */
if (pid == 0) {
cxn_pinned = -1;
return 0;
}
ret = -ESRCH;
/* get a handle on the mm_struct */
read_lock(&tasklist_lock);
tsk = find_task_by_vpid(pid);
if (tsk) {
ret = -EINVAL;
task_lock(tsk);
if (tsk->mm) {
mm = tsk->mm;
atomic_inc(&mm->mm_users);
ret = 0;
}
task_unlock(tsk);
}
read_unlock(&tasklist_lock);
if (ret < 0)
return ret;
/* make sure it has a CXN and pin it */
spin_lock(&cxn_owners_lock);
cxn_pinned = get_cxn(&mm->context);
spin_unlock(&cxn_owners_lock);
mmput(mm);
return 0;
} /* end cxn_pin_by_pid() */
| gpl-2.0 |
Ninpo/ninphetamine3 | arch/arm/mvp/mvpkm/mvpkm_main.c | 199 | 76680 | /*
* Linux 2.6.32 and later Kernel module for VMware MVP Hypervisor Support
*
* Copyright (C) 2010-2012 VMware, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License 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; see the file COPYING. If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#line 5
/**
* @file
*
* @brief The kernel level driver.
*/
#define __KERNEL_SYSCALLS__
#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/fcntl.h>
#include <linux/syscalls.h>
#include <linux/kmod.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/miscdevice.h>
#include <linux/poll.h>
#include <linux/smp.h>
#include <linux/capability.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/sysfs.h>
#include <linux/pid.h>
#include <linux/highmem.h>
#include <linux/syscalls.h>
#ifdef CONFIG_HAS_WAKELOCK
#include <linux/wakelock.h>
#endif
#include <net/sock.h>
#include <asm/cacheflush.h>
#include <asm/memory.h>
#include <asm/pgtable.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include "mvp.h"
#include "mvp_version.h"
#include "mvpkm_types.h"
#include "mvpkm_private.h"
#include "mvpkm_kernel.h"
#include "actions.h"
#include "wscalls.h"
#include "arm_inline.h"
#include "tsc.h"
#include "mksck_kernel.h"
#include "mmu_types.h"
#include "mvp_timer.h"
#include "qp.h"
#include "qp_host_kernel.h"
#include "cpufreq_kernel.h"
#include "mvpkm_comm_ev.h"
#ifdef CONFIG_ANDROID_LOW_MEMORY_KILLER
#include "mvp_balloon.h"
#endif
/*********************************************************************
*
* Definition of the file operations
*
*********************************************************************/
static _Bool LockedListAdd(MvpkmVM *vm,
__u32 mpn,
__u32 order,
PhysMem_RegionType forRegion);
static _Bool LockedListDel(MvpkmVM *vm, __u32 mpn);
static void LockedListUnlockAll(MvpkmVM *vm);
static _Bool LockedListLookup(MvpkmVM *vm, __u32 mpn);
static int SetupMonitor(MvpkmVM *vm);
static int RunMonitor(MvpkmVM *vm);
static MPN AllocZeroedFreePages(MvpkmVM *vm,
uint32 order,
_Bool highmem,
PhysMem_RegionType forRegion,
HKVA *hkvaRet);
static HKVA MapWSPHKVA(MvpkmVM *vm, HkvaMapInfo *mapInfo);
static void UnmapWSPHKVA(MvpkmVM *vm);
static int MvpkmWaitForInt(MvpkmVM *vm, _Bool suspend);
static void ReleaseVM(MvpkmVM *vm);
/*
* Mksck open request must come from this uid. It must be root until
* it is set via an ioctl from mvpd.
*/
uid_t Mvpkm_vmwareUid = 0;
EXPORT_SYMBOL(Mvpkm_vmwareUid);
/*
* Minimum hidden app oom_adj, provided by mvpd, since we can't get it directly
* from the lowmemorykiller module.
*/
static int minHiddenAppOOMAdj;
/*
* vCPU cpu affinity to let monitor/guest run on some CPUs only (when possible)
*/
static DECLARE_BITMAP(vcpuAffinity, NR_CPUS);
/*********************************************************************
*
* Sysfs nodes
*
*********************************************************************/
/*
* kobject for our sysfs representation, used for global nodes.
*/
static struct kobject *mvpkmKObj;
/*
* kobject for the balloon exports.
*/
static struct kobject *balloonKObj;
/**
* @brief sysfs show function for global version attribute.
*
* @param kobj reference to kobj nested in MvpkmVM struct.
* @param attr kobj_attribute reference, not used.
* @param buf PAGE_SIZEd buffer to write to.
*
* @return number of characters printed (not including trailing null character).
*/
static ssize_t
version_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, MVP_VERSION_FORMATSTR "\n", MVP_VERSION_FORMATARGS);
}
static struct kobj_attribute versionAttr = __ATTR_RO(version);
/**
* @brief sysfs show function for global background_pages attribute.
*
* Used by vmx balloon policy controller to gauge the amount of freeable
* anonymous memory.
*
* @param kobj reference to kobj nested in MvpkmVM struct.
* @param attr kobj_attribute reference, not used.
* @param buf PAGE_SIZEd buffer to write to.
*
* @return number of characters printed (not including trailing null character).
*/
static ssize_t
background_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
#ifndef CONFIG_ANDROID_LOW_MEMORY_KILLER
return snprintf(buf, PAGE_SIZE, "0\n");
#else
return snprintf(buf, PAGE_SIZE, "%d\n", Balloon_AndroidBackgroundPages(minHiddenAppOOMAdj));
#endif
}
static struct kobj_attribute backgroundAttr = __ATTR_RO(background);
/**
* @brief sysfs show function to export the other_file calculation in
* lowmemorykiller.
*
* It's helpful, in the balloon controller, to know what the lowmemorykiller
* module is using to know when the system has crossed a minfree threshold.
* Since there exists a number of different other_file calculations in various
* lowmemorykiller patches (@see{MVP-1674}), and the module itself doesn't
* provide a clean export of this figure, we provide it on a case-by-case basis
* for the various supported hosts here.
*
* @param kobj reference to kobj nested in MvpkmVM struct.
* @param attr kobj_attribute reference, not used.
* @param buf PAGE_SIZEd buffer to write to.
*
* @return number of characters printed (not including trailing null character).
*/
static ssize_t
other_file_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
int32 other_file = 0;
#ifndef LOWMEMKILLER_VARIANT
#define LOWMEMKILLER_VARIANT 0
#endif
#ifndef LOWMEMKILLER_MD5
#define LOWMEMKILLER_MD5 0
#endif
#ifndef LOWMEMKILLER_SHRINK_MD5
#define LOWMEMKILLER_SHRINK_MD5 0
#endif
/*
* The build system hashes the lowmemorykiller section related to the
* other_file calculation in the kernel source for us, here we have to
* provide the code.
*/
#if LOWMEMKILLER_VARIANT == 1
/*
* This is the same as the non-exported global_reclaimable_pages() when there
* is no swap.
*/
other_file = global_page_state(NR_ACTIVE_FILE) +
global_page_state(NR_INACTIVE_FILE);
#elif LOWMEMKILLER_VARIANT == 2
other_file = global_page_state(NR_FILE_PAGES);
#elif LOWMEMKILLER_VARIANT == 3
other_file = global_page_state(NR_FILE_PAGES) - global_page_state(NR_SHMEM);
#elif LOWMEMKILLER_VARIANT == 4
/*
* Here free/file pages are fungible and max(free, file) isn't used, but we
* can continue to use max(free, file) since max(free, file) = other_file in
* this case.
*/
other_file = global_page_state(NR_FREE_PAGES) + global_page_state(NR_FILE_PAGES);
#elif defined(NONANDROID)
/*
* Non-Android host platforms don't have ballooning enabled.
*/
#else
/*
* If you get this message, you need to run 'make lowmem-info' and inspect
* lowmemorykiller.c. If the "other_file = ..." calculation in lowmem_shrink
* appears above, simply add the "Shrink#" to an existing entry in
* lowmemkiller-variant.sh, pointing to the variant number above. Otherwise,
* provide a new entry above and variant number, with the appropriate
* other_file calculation and update lowmemkiller-variant.sh accordingly.
*/
//#warning "Unknown lowmemorykiller variant in hosted/module/mvpkm_main.c, falling back on default (see other_file_show for the remedy)"
/*
* Fall back on default - this may bias strangely for/against the host, but
* nothing catastrophic should result.
*/
other_file = global_page_state(NR_FILE_PAGES);
#endif
#define _STRINGIFY(x) #x
#define STRINGIFY(x) _STRINGIFY(x)
return snprintf(buf,
PAGE_SIZE,
"%d %d %s %s\n",
other_file,
LOWMEMKILLER_VARIANT,
STRINGIFY(LOWMEMKILLER_MD5),
STRINGIFY(LOWMEMKILLER_SHRINK_MD5));
#undef _STRINGIFY
#undef STRINGIFY
}
static struct kobj_attribute otherFileAttr = __ATTR_RO(other_file);
/*
* kset for our sysfs representation, used for per-VM nodes.
*/
static struct kset *mvpkmKSet;
static ssize_t MvpkmAttrShow(struct kobject *kobj,
struct attribute *attr,
char *buf);
static ssize_t MvpkmAttrStore(struct kobject *kobj,
struct attribute *attr,
const char *buf,
size_t count);
static void MvpkmKObjRelease(struct kobject *kobj)
__attribute__ ((optimize ("-fomit-frame-pointer")));
/**
* @brief Releases the vm structure containing the kobject.
*
* @param kobj the vm's kobject.
*/
static void
MvpkmKObjRelease(struct kobject *kobj)
{
MvpkmVM *vm = container_of(kobj, MvpkmVM, kobj);
ReleaseVM(vm);
module_put(THIS_MODULE);
}
/**
* @name mvpkm ktype attribute structures for locked_pages.
*
* @{
*/
static struct sysfs_ops mvpkmSysfsOps = {
.show = MvpkmAttrShow,
.store = MvpkmAttrStore
};
static struct attribute mvpkmLockedPagesAttr = {
.name = "locked_pages",
.mode = 0444,
};
static struct attribute mvpkmBalloonWatchdogAttr = {
.name = "balloon_watchdog",
.mode = 0666
};
static struct attribute mvpkmMonitorAttr = {
.name = "monitor",
.mode = 0400,
};
static struct attribute *mvpkmDefaultAttrs[] = {
&mvpkmLockedPagesAttr,
&mvpkmBalloonWatchdogAttr,
&mvpkmMonitorAttr,
NULL,
};
static struct kobj_type mvpkmKType = {
.sysfs_ops = &mvpkmSysfsOps,
.release = MvpkmKObjRelease,
.default_attrs = mvpkmDefaultAttrs,
};
/*@}*/
/*
* As it is not very common for host kernels to have SYS_HYPERVISOR enabled and
* you have to "hack" a Kconfig file to enable it, just include the
* functionality inline if it is not enabled.
*/
#ifndef CONFIG_SYS_HYPERVISOR
struct kobject *hypervisor_kobj;
EXPORT_SYMBOL_GPL(hypervisor_kobj);
#endif
/*
* kobject and kset utilities.
*/
extern struct kobject *kset_find_obj(struct kset *, const char *)
__attribute__((weak));
/**
* @brief Finds a kobject in a kset. The actual implementation is copied from
* kernel source in lib/kobject.c. Although the symbol is extern-declared,
* it is not EXPORT_SYMBOL-ed. We use a weak reference in case the symbol
* might be exported in future kernel versions.
*
* @param kset set to search.
* @param name object name.
*
* @return retained kobject if found, NULL otherwise.
*/
struct kobject *
kset_find_obj(struct kset *kset,
const char *name)
{
struct kobject *k;
struct kobject *ret = NULL;
spin_lock(&kset->list_lock);
list_for_each_entry(k, &kset->list, entry) {
if (kobject_name(k) && !strcmp(kobject_name(k), name)) {
ret = kobject_get(k);
break;
}
}
spin_unlock(&kset->list_lock);
return ret;
}
/**
* @brief Finds one of the VM's pre-defined ksets.
*
* @param vmID a VM ID.
* @param name name of one of the VM's pre-defined ksets.
*
* @return retained kset if found, NULL otherwise.
*/
struct kset *
Mvpkm_FindVMNamedKSet(int vmID,
const char *name)
{
MvpkmVM *vm;
struct kobject *kobj;
char vmName[32] = {}; /* Large enough to hold externally-formatted int32. */
struct kset *res = NULL;
if (!mvpkmKSet) {
return NULL;
}
snprintf(vmName, sizeof vmName, "%d", vmID);
vmName[sizeof vmName - 1] = '\0'; /* Always null-terminate, no overflow. */
kobj = kset_find_obj(mvpkmKSet, vmName);
if (!kobj) {
return NULL;
}
vm = container_of(kobj, MvpkmVM, kobj);
if (!strcmp(name, "devices")) {
res = kset_get(vm->devicesKSet);
} else if (!strcmp(name, "misc")) {
res = kset_get(vm->miscKSet);
}
kobject_put(kobj);
return res;
}
EXPORT_SYMBOL(Mvpkm_FindVMNamedKSet);
/*********************************************************************
*
* Standard Linux miscellaneous device registration
*
*********************************************************************/
MODULE_LICENSE("GPL"); // for kallsyms_lookup_name
static int MvpkmFault(struct vm_area_struct *vma, struct vm_fault *vmf);
/**
* @brief Linux vma operations for /dev/mem-like kernel module mmap. We
* enforce the restriction that only MPNs that have been allocated
* to the opened VM may be mapped and also increment the reference
* count (via vm_insert_page), so that even if the memory is later
* freed by the VM, host process vma's containing the MPN can't
* compromise the system.
*
* However, only trusted host processes (e.g. the vmx) should be allowed
* to use this interface, since you can mmap the monitor's code/data/
* page tables etc. with it. Untrusted host processes are limited to
* typed messages for sharing memory with the monitor. Unix file system
* access permissions are the intended method of restricting access.
* Unfortunately, today _any_ host process utilizing Mksck requires
* access to mvpkm to setup its Mksck pages and obtain socket info via
* ioctls - we probably should be exporting two devices, one for trusted
* and one for arbitrary host processes to avoid this confusion of
* concerns.
*/
static struct vm_operations_struct mvpkmVMOps = {
.fault = MvpkmFault
};
/*
* Generic kernel module file ops. These functions will be registered
* at the time the kernel module is loaded.
*/
static long MvpkmUnlockedIoctl(struct file *filep,
unsigned int cmd,
unsigned long arg);
static int MvpkmOpen(struct inode *inode, struct file *filp);
static int MvpkmRelease(struct inode *inode, struct file *filp);
static int MvpkmMMap(struct file *file, struct vm_area_struct *vma);
/**
* @brief the file_operation structure contains the callback functions
* that are registered with Linux to handle file operations on
* the mvpkm device.
*
* The structure contains other members that the mvpkm device
* does not use. Those members are auto-initialized to NULL.
*
* WARNING, this structure has changed after Linux kernel 2.6.19:
* readv/writev are changed to aio_read/aio_write (neither is used here).
*/
static const struct file_operations mvpkmFileOps = {
.owner = THIS_MODULE,
.unlocked_ioctl = MvpkmUnlockedIoctl,
.open = MvpkmOpen,
.release = MvpkmRelease,
.mmap = MvpkmMMap
};
/**
* @brief The mvpkm device identifying information to be used to register
* the device with the Linux kernel.
*/
static struct miscdevice mvpkmDev = {
.minor = 165,
.name = "mvpkm",
.fops = &mvpkmFileOps
};
/**
* Mvpkm is loaded by mvpd and only mvpd will be allowed to open
* it. There is a very simple way to verify that: record the process
* id (thread group id) at the time the module is loaded and test it
* at the time the module is opened.
*/
static struct pid *initTgid;
#ifdef CONFIG_ANDROID_LOW_MEMORY_KILLER
/**
* @name Slab shrinker for triggering balloon adjustment.
*
* @note shrinker us used as a trigger for guest balloon.
*
* @{
*/
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 0, 0)
static int MvpkmShrink(struct shrinker *this, struct shrink_control *sc);
#else
static int MvpkmShrink(struct shrinker *this, int nrToScan, gfp_t gfpMask);
#endif
static struct shrinker mvpkmShrinker = {
.shrink = MvpkmShrink,
.seeks = DEFAULT_SEEKS
};
/*@}*/
#endif
module_param_array(vcpuAffinity, ulong, NULL, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(vcpuAffinity, "vCPU affinity");
/**
* @brief Initialize the mvpkm device, register it with the Linux kernel.
*
* @return A zero is returned on success and a negative errno code for failure.
* (Same as the return policy of misc_register(9).)
*/
static int __init
MvpkmInit(void)
{
int err = 0;
_Bool mksckInited = false;
_Bool cpuFreqInited = false;
printk(KERN_INFO "Mvpkm: " MVP_VERSION_FORMATSTR "\n", MVP_VERSION_FORMATARGS);
printk(KERN_INFO "Mvpkm: loaded from process %s tgid=%d, pid=%d\n",
current->comm,
task_tgid_vnr(current),
task_pid_vnr(current));
if (bitmap_empty(vcpuAffinity, NR_CPUS)) {
bitmap_copy(vcpuAffinity, cpumask_bits(cpu_possible_mask), NR_CPUS);
}
if ((err = misc_register(&mvpkmDev))) {
return -ENOENT;
}
if ((err = Mksck_Init())) {
goto error;
} else {
mksckInited = true;
}
QP_HostInit();
CpuFreq_Init();
cpuFreqInited = true;
/*
* Reference mvpd (module loader) tgid struct, so that we can avoid
* attacks based on pid number wraparound.
*/
initTgid = get_pid(task_tgid(current));
#ifndef CONFIG_SYS_HYPERVISOR
hypervisor_kobj = kobject_create_and_add("hypervisor", NULL);
if (!hypervisor_kobj) {
err = -ENOMEM;
goto error;
}
#endif
if (!(mvpkmKObj = kobject_create_and_add("mvp", hypervisor_kobj)) ||
!(balloonKObj = kobject_create_and_add("lowmem", mvpkmKObj)) ||
!(mvpkmKSet = kset_create_and_add("vm", NULL, mvpkmKObj))) {
err = -ENOMEM;
goto error;
}
if ((err = sysfs_create_file(mvpkmKObj, &versionAttr.attr))) {
goto error;
}
if ((err = sysfs_create_file(balloonKObj, &backgroundAttr.attr))) {
goto error;
}
if ((err = sysfs_create_file(balloonKObj, &otherFileAttr.attr))) {
goto error;
}
#ifdef CONFIG_ANDROID_LOW_MEMORY_KILLER
register_shrinker(&mvpkmShrinker);
#endif
MksckPageInfo_Init();
return 0;
error:
if (mvpkmKSet) {
kset_unregister(mvpkmKSet);
}
if (balloonKObj) {
kobject_del(balloonKObj);
kobject_put(balloonKObj);
}
if (mvpkmKObj) {
kobject_del(mvpkmKObj);
kobject_put(mvpkmKObj);
}
#ifndef CONFIG_SYS_HYPERVISOR
if (hypervisor_kobj) {
kobject_del(hypervisor_kobj);
kobject_put(hypervisor_kobj);
}
#endif
if (cpuFreqInited) {
CpuFreq_Exit();
}
if (mksckInited) {
Mksck_Exit();
}
if (initTgid) {
put_pid(initTgid);
}
misc_deregister(&mvpkmDev);
return err;
}
/**
* @brief De-register the mvpkm device with the Linux kernel.
*/
void
MvpkmExit(void)
{
PRINTK(KERN_INFO "MvpkmExit called !\n");
MksckPageInfo_Exit();
#ifdef CONFIG_ANDROID_LOW_MEMORY_KILLER
unregister_shrinker(&mvpkmShrinker);
#endif
kset_unregister(mvpkmKSet);
kobject_del(balloonKObj);
kobject_put(balloonKObj);
kobject_del(mvpkmKObj);
kobject_put(mvpkmKObj);
#ifndef CONFIG_SYS_HYPERVISOR
kobject_del(hypervisor_kobj);
kobject_put(hypervisor_kobj);
#endif
CpuFreq_Exit();
Mksck_Exit();
put_pid(initTgid);
misc_deregister(&mvpkmDev);
}
/*
* The standard module registration macros of Linux.
*/
module_init(MvpkmInit);
module_exit(MvpkmExit);
module_param_named(minHiddenAppOOMAdj, minHiddenAppOOMAdj, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(minHiddenAppOOMAdj, "minimum hidden app oom_adj, as per lowmemorykiller");
#ifdef CONFIG_ANDROID_LOW_MEMORY_KILLER
/**
* @brief Balloon watchdog timeout callback.
*
* Terminate the VM since it's not responsive.
*
* @param data vm reference representation.
*/
static void
WatchdogCB(unsigned long data)
{
MvpkmVM *vm = (MvpkmVM *)data;
printk("Balloon watchdog expired (%d s)!\n", BALLOON_WATCHDOG_TIMEOUT_SECS);
Mvpkm_WakeGuest(vm, ACTION_ABORT);
}
/**
* @brief Slab shrinker.
*
* Called by Linux kernel when we're under memory pressure. We treat all locked
* pages as a slab for this purpose, similar to the Android low memory killer.
*
* @param this reference to registered shrinker for callback context.
* @param nrToScan number of entries to scan. If 0 then just return the number
* of present entries. We ignore the value of nrToScan when > 1
* since the shrinker is a trigger to readjust guest balloons,
* where the actual balloon size is determined in conjunction
* with the guest.
* @param gfpMask ignored.
*
* @return number of locked pages.
*/
static int
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 0, 0)
MvpkmShrink(struct shrinker *this, struct shrink_control *sc)
#else
MvpkmShrink(struct shrinker *this, int nrToScan, gfp_t gfpMask)
#endif
{
uint32 locked = 0;
struct kobject *k;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 0, 0)
int nrToScan = sc->nr_to_scan;
#endif
spin_lock(&mvpkmKSet->list_lock);
list_for_each_entry(k, &mvpkmKSet->list, entry) {
MvpkmVM *vm = container_of(k, MvpkmVM, kobj);
locked += ATOMIC_GETO(vm->usedPages);
/*
* Try and grab the WSP semaphore - if we fail, we must be VM setup or
* teardown, no point trying to wake the guest.
*/
if (nrToScan > 0 &&
down_read_trylock(&vm->wspSem)) {
if (vm->wsp) {
Mvpkm_WakeGuest(vm, ACTION_BALLOON);
/*
* Balloon watchdog.
*/
if (vm->balloonWDEnabled) {
struct timer_list *t = &vm->balloonWDTimer;
if (!timer_pending(t)) {
t->data = (unsigned long)vm;
t->function = WatchdogCB;
t->expires = jiffies + BALLOON_WATCHDOG_TIMEOUT_SECS * HZ;
add_timer(t);
}
}
}
up_read(&vm->wspSem);
}
}
spin_unlock(&mvpkmKSet->list_lock);
return locked;
}
#endif
/**
* @brief The open file operation. Initializes the vm specific structure.
*/
int
MvpkmOpen(struct inode *inode, struct file *filp)
{
MvpkmVM *vm;
if (initTgid != task_tgid(current)) {
printk(KERN_ERR "%s: MVPKM can be opened only from MVPD (process %d).\n",
__FUNCTION__, pid_vnr(initTgid));
return -EPERM;
}
printk(KERN_DEBUG "%s: Allocating an MvpkmVM structure from process %s tgid=%d, pid=%d\n",
__FUNCTION__,
current->comm,
task_tgid_vnr(current),
task_pid_vnr(current));
vm = kmalloc(sizeof(MvpkmVM), GFP_KERNEL);
if (!vm) {
return -ENOMEM;
}
memset(vm, 0, sizeof *vm);
init_timer(&vm->balloonWDTimer);
init_rwsem(&vm->lockedSem);
init_rwsem(&vm->wspSem);
init_rwsem(&vm->monThreadTaskSem);
vm->monThreadTask = NULL;
vm->isMonitorInited = false;
filp->private_data = vm;
if (!Mvpkm_vmwareUid) {
Mvpkm_vmwareUid = current_euid();
}
return 0;
}
/**
* @brief Releases a VMs resources
* @param vm vm to release
*/
static void
ReleaseVM(MvpkmVM *vm)
{
del_timer_sync(&vm->balloonWDTimer);
down_write(&vm->wspSem);
if (vm->isMonitorInited) {
MonitorTimer_Request(&vm->monTimer, 0);
#ifdef CONFIG_HAS_WAKELOCK
wake_lock_destroy(&vm->wakeLock);
#endif
Mksck_WspRelease(vm->wsp);
vm->wsp = NULL;
}
up_write(&vm->wspSem);
LockedListUnlockAll(vm);
UnmapWSPHKVA(vm);
/*
* All sockets potentially connected to sockets of this vm's vmId will fail
* at send now. DGRAM sockets are note required to tear down connection
* explicitly.
*/
kfree(vm);
}
/**
* @brief The release file operation. Releases the vm specific
* structure including all the locked pages.
*
* @param inode Unused
* @param filp which VM we're dealing with
* @return 0
*/
int
MvpkmRelease(struct inode *inode, struct file *filp)
{
MvpkmVM *vm = filp->private_data;
/*
* Tear down any queue pairs associated with this VM
*/
if (vm->isMonitorInited) {
ASSERT(vm->wsp);
QP_DetachAll(vm->wsp->guestId);
}
/*
* Release the VM's ksets.
*/
kset_unregister(vm->miscKSet);
kset_unregister(vm->devicesKSet);
if (vm->haveKObj) {
/*
* Release the VM's kobject.
* 'vm' will be kfree-d in its kobject's release function.
*/
kobject_del(&vm->kobj);
kobject_put(&vm->kobj);
} else {
ReleaseVM(vm);
}
filp->private_data = NULL;
printk(KERN_INFO "%s: Released MvpkmVM structure from process %s tgid=%d, pid=%d\n",
__FUNCTION__,
current->comm,
task_tgid_vnr(current),
task_pid_vnr(current));
return 0;
}
/**
* @brief Page fault handler for /dev/mem-like regions (see mvpkmVMOps
* block comment).
*/
static int
MvpkmFault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
unsigned long address = (unsigned long)vmf->virtual_address;
MPN mpn = vmf->pgoff;
MvpkmVM *vm = vma->vm_file->private_data;
/*
* Only insert pages belonging to the VM. The check is slow, O(n) in the
* number of MPNs associated with the VM, but it doesn't matter - the mmap
* interface should only be used by trusted processes at initialization
* time and for debugging.
*
* The mpn can be either in the memory reserved the monitor or mvpd
* through the regular mechanisms or it could be a mksck page.
*/
if (!pfn_valid(mpn)) {
printk(KERN_ERR "MvpkmMMap: Failed to insert %x @ %lx, mpn invalid\n",
mpn,
address);
} else if (LockedListLookup(vm, mpn)) {
if (vm_insert_page(vma, address, pfn_to_page(mpn)) == 0) {
return VM_FAULT_NOPAGE;
}
printk(KERN_ERR "MvpkmMMap: Failed to insert %x @ %lx \n",
mpn,
address);
} else if (MksckPage_LookupAndInsertPage(vma, address, mpn) == 0) {
return VM_FAULT_NOPAGE;
}
if (vm->stubPageMPN) {
if (vm_insert_page(vma, address, pfn_to_page(vm->stubPageMPN)) == 0) {
printk(KERN_INFO "MvpkmMMap: mapped the stub page at %x @ %lx \n",
mpn,
address);
return VM_FAULT_NOPAGE;
}
printk(KERN_ERR "MvpkmMMap: Could not insert stub page %x @ %lx \n",
mpn,
address);
}
return VM_FAULT_SIGBUS;
}
/**
* @brief sysfs show function for per-VM locked_pages attribute.
*
* @param kobj reference to kobj nested in MvpkmVM struct.
* @param attr attribute reference.
* @param buf PAGE_SIZEd buffer to write to.
*
* @return number of characters printed (not including trailing null character).
*/
static ssize_t
MvpkmAttrShow(struct kobject *kobj,
struct attribute *attr,
char *buf)
{
if (attr == &mvpkmLockedPagesAttr) {
MvpkmVM *vm = container_of(kobj, MvpkmVM, kobj);
return snprintf(buf, PAGE_SIZE, "%d\n", ATOMIC_GETO(vm->usedPages));
} else if (attr == &mvpkmMonitorAttr) {
MvpkmVM *vm = container_of(kobj, MvpkmVM, kobj);
return snprintf(buf,
PAGE_SIZE,
"hostActions %x callno %d\n",
ATOMIC_GETO(vm->wsp->hostActions),
WSP_Params(vm->wsp)->callno);
} else {
return -EPERM;
}
}
/**
* @brief sysfs store function for per-VM locked_pages attribute.
*
* @param kobj reference to kobj nested in MvpkmVM struct.
* @param attr attribute reference.
* @param buf PAGE_SIZEd buffer to write to.
* @param buf input buffer.
* @param count input buffer length.
*
* @return number of bytes consumed or negative error code.
*/
static ssize_t
MvpkmAttrStore(struct kobject *kobj,
struct attribute *attr,
const char *buf,
size_t count)
{
if (attr == &mvpkmBalloonWatchdogAttr) {
MvpkmVM *vm = container_of(kobj, MvpkmVM, kobj);
/*
* Enable balloon watchdog on first write. This includes all ballooning
* capable guest.
*/
vm->balloonWDEnabled = true;
del_timer_sync(&vm->balloonWDTimer);
return 1;
} else {
return -EPERM;
}
}
/**
* @brief Map machine address space region into host process.
*
* @param file file reference (ignored).
* @param vma Linux virtual memory area defining the region.
*
* @return 0 on success, otherwise error code.
*/
static int
MvpkmMMap(struct file *file, struct vm_area_struct *vma)
{
vma->vm_ops = &mvpkmVMOps;
return 0;
}
#ifdef CONFIG_ARM_LPAE
/**
* @brief Determine host cacheability/shareability attributes.
*
* Used to ensure monitor/guest shared mappings are consistent with
* those of host user/kernel.
*
* @param[out] attribMAN when setting up the HW monitor this provides the
* attributes in the generic ARM_MemAttrNormal form,
* suitable for configuring the monitor and guest's
* [H]MAIR0 and setting the shareability attributes of
* the LPAE descriptors.
*/
static void
DetermineMemAttrLPAE(ARM_MemAttrNormal *attribMAN)
{
/*
* We use set_pte_ext to sample what {S,TEX,CB} bits Linux is using for
* normal kernel/user L2D mappings. These bits should be consistent both
* with each other and what we use in the monitor since we share various
* pages with both host processes, the kernel module and monitor, and the
* ARM ARM requires that synonyms have the same cacheability attributes,
* see end of A3.5.{4,7} ARM DDI 0406A.
*/
HKVA hkva = __get_free_pages(GFP_KERNEL, 0);
ARM_LPAE_L3D *pt = (ARM_LPAE_L3D *)hkva;
ARM_LPAE_L3D *kernL3D = &pt[0], *userL3D = &pt[1];
uint32 attr, mair0, mair1;
set_pte_ext((pte_t *)kernL3D, pfn_pte(0, PAGE_KERNEL), 0);
set_pte_ext((pte_t *)userL3D, pfn_pte(0, PAGE_NONE), 0);
printk(KERN_INFO
"DetermineMemAttr: Kernel L3D AttrIndx=%x SH=%x\n",
kernL3D->blockS1.attrIndx,
kernL3D->blockS1.sh);
printk(KERN_INFO
"DetermineMemAttr: User L3D AttrIndx=%x SH=%x\n",
userL3D->blockS1.attrIndx,
userL3D->blockS1.sh);
ASSERT(kernL3D->blockS1.attrIndx == userL3D->blockS1.attrIndx);
ASSERT(kernL3D->blockS1.sh == userL3D->blockS1.sh);
switch (kernL3D->blockS1.sh) {
case 0: {
attribMAN->share = ARM_SHARE_ATTR_NONE;
break;
}
case 2: {
attribMAN->share = ARM_SHARE_ATTR_OUTER;
break;
}
case 3: {
attribMAN->share = ARM_SHARE_ATTR_INNER;
break;
}
default: {
FATAL();
}
}
ARM_MRC_CP15(MAIR0, mair0);
ARM_MRC_CP15(MAIR1, mair1);
attr = MVP_EXTRACT_FIELD(kernL3D->blockS1.attrIndx >= 4 ? mair1 : mair0,
8 * (kernL3D->blockS1.attrIndx % 4),
8);
/*
* See B4-1615 ARM DDI 0406C-2c for magic.
*/
#define MAIR_ATTR_2_CACHE_ATTR(x, y) \
switch (x) { \
case 2: { \
(y) = ARM_CACHE_ATTR_NORMAL_WT; \
break; \
} \
case 3: { \
(y) = ARM_CACHE_ATTR_NORMAL_WB; \
break; \
} \
default: { \
FATAL(); \
} \
}
MAIR_ATTR_2_CACHE_ATTR(MVP_EXTRACT_FIELD(attr, 2, 2), attribMAN->innerCache);
MAIR_ATTR_2_CACHE_ATTR(MVP_EXTRACT_FIELD(attr, 6, 2), attribMAN->outerCache);
#undef MAIR_ATTR_2_CACHE_ATTR
printk(KERN_INFO
"DetermineMemAttr: innerCache %x outerCache %x share %x\n",
attribMAN->innerCache,
attribMAN->outerCache,
attribMAN->share);
free_pages(hkva, 0);
}
#else
/**
* @brief Determine host cacheability/shareability attributes.
*
* Used to ensure monitor/guest shared mappings are consistent with
* those of host user/kernel.
*
* @param[out] attribL2D when setting up the LPV monitor a template L2D
* containing cacheability attributes {S, TEX,CB} used by
* host kernel for normal memory mappings. These may be
* used directly for monitor/guest mappings, since both
* worlds share a common {TRE, PRRR, NMRR}.
* @param[out] attribMAN when setting up TTBR0 in the LPV monitor and the page
* tables for the HW monitor this provides the attributes
* in the generic ARM_MemAttrNormal form, suitable for
* configuring TTBR0 + the monitor and guest's [H]MAIR0
* and setting the shareability attributes of the LPAE
* descriptors.
*/
static void
DetermineMemAttrNonLPAE(ARM_L2D *attribL2D, ARM_MemAttrNormal *attribMAN)
{
/*
* We use set_pte_ext to sample what {S,TEX,CB} bits Linux is using for
* normal kernel/user L2D mappings. These bits should be consistent both
* with each other and what we use in the monitor since we share various
* pages with both host processes, the kernel module and monitor, and the
* ARM ARM requires that synonyms have the same cacheability attributes,
* see end of A3.5.{4,7} ARM DDI 0406A.
*/
HKVA hkva = __get_free_pages(GFP_KERNEL, 0);
uint32 sctlr;
ARM_L2D *pt = (ARM_L2D *)hkva;
ARM_L2D *kernL2D = &pt[0], *userL2D = &pt[1];
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 38)
/*
* Linux uses the magic 2048 offset in set_pte_ext. See include/asm/pgtable.h
* for PAGE_NONE and PAGE_KERNEL semantics.
*/
const uint32 set_pte_ext_offset = 2048;
#else
/*
* Linux 2.6.38 switched the order of Linux vs hardware page tables.
* See mainline d30e45eeabefadc6039d7f876a59e5f5f6cb11c6.
*/
const uint32 set_pte_ext_offset = 0;
#endif
set_pte_ext((pte_t *)(kernL2D + set_pte_ext_offset/sizeof(ARM_L2D)),
pfn_pte(0, PAGE_KERNEL),
0);
set_pte_ext((pte_t *)(userL2D + set_pte_ext_offset/sizeof(ARM_L2D)),
pfn_pte(0, PAGE_NONE),
0);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 38)
/*
* Linux 2.6.38 switched the order of Linux vs hardware page tables.
* See mainline d30e45eeabefadc6039d7f876a59e5f5f6cb11c6.
*/
kernL2D += 2048/sizeof(ARM_L2D);
userL2D += 2048/sizeof(ARM_L2D);
#endif
printk(KERN_INFO
"DetermineMemAttr: Kernel L2D TEX=%x CB=%x S=%x\n",
kernL2D->small.tex,
kernL2D->small.cb,
kernL2D->small.s);
printk(KERN_INFO
"DetermineMemAttr: User L2D TEX=%x CB=%x S=%x\n",
userL2D->small.tex,
userL2D->small.cb,
userL2D->small.s);
ASSERT((kernL2D->small.tex & 1) == (userL2D->small.tex & 1));
ASSERT(kernL2D->small.cb == userL2D->small.cb);
ASSERT(kernL2D->small.s == userL2D->small.s);
*attribL2D = *kernL2D;
/*
* We now decode TEX remap and obtain the more generic form for use in
* the LPV monitor's TTBR0 initialization and the HW monitor.
*/
ARM_MRC_CP15(CONTROL_REGISTER, sctlr);
if (sctlr & ARM_CP15_CNTL_TRE) {
uint32 prrr, nmrr, indx, type, innerCache, outerCache, outerShare,
share;
printk(KERN_INFO
"DetermineMemAttr: TEX remapping enabled\n");
ARM_MRC_CP15(PRIMARY_REGION_REMAP, prrr);
ARM_MRC_CP15(NORMAL_MEMORY_REMAP, nmrr);
printk(KERN_INFO
"DetermineMemAttr: PRRR=%x NMRR=%x\n",
prrr,
nmrr);
/*
* Decode PRRR/NMRR below. See B3.7 ARM DDI 0406B for register
* encodings, tables and magic numbers.
*/
indx = (MVP_BIT(kernL2D->small.tex, 0) << 2) | kernL2D->small.cb;
/*
* Only normal memory makes sense here.
*/
type = MVP_EXTRACT_FIELD(prrr, 2 * indx, 2);
ASSERT(type == 2);
innerCache = MVP_EXTRACT_FIELD(nmrr, 2 * indx, 2);
outerCache = MVP_EXTRACT_FIELD(nmrr, 16 + 2 * indx, 2);
outerShare = !MVP_BIT(prrr, 24 + indx);
share = MVP_BIT(prrr, 18 + kernL2D->small.s);
printk(KERN_INFO
"DetermineMemAttr: type %x innerCache %x outerCache %x"
" share %x outerShare %x\n",
type,
innerCache,
outerCache,
share,
outerShare);
if (share) {
if (outerShare) {
attribMAN->share = ARM_SHARE_ATTR_OUTER;
} else {
attribMAN->share = ARM_SHARE_ATTR_INNER;
}
} else {
attribMAN->share = ARM_SHARE_ATTR_NONE;
}
attribMAN->innerCache = innerCache;
attribMAN->outerCache = outerCache;
} else {
NOT_IMPLEMENTED_JIRA(1849);
}
free_pages(hkva, 0);
}
#endif
/**
* @brief The ioctl file operation.
*
* The ioctl command is the main communication method between the
* vmx and the mvpkm kernel module.
*
* @param filp which VM we're dealing with
* @param cmd select which cmd function needs to be performed
* @param arg argument for command
* @return error code, 0 on success
*/
long
MvpkmUnlockedIoctl(struct file *filp,
unsigned int cmd,
unsigned long arg)
{
MvpkmVM *vm = filp->private_data;
int retval = 0;
switch (cmd) {
case MVPKM_DISABLE_FAULT: {
if (!vm->stubPageMPN) {
uint32 *ptr;
vm->stubPageMPN =
AllocZeroedFreePages(vm, 0, false, MEMREGION_MAINMEM, (HKVA*)&ptr);
if (!vm->stubPageMPN) {
break;
}
ptr[0] = MVPKM_STUBPAGE_BEG;
ptr[PAGE_SIZE/sizeof(uint32) - 1] = MVPKM_STUBPAGE_END;
}
break;
}
/*
* Allocate some pinned pages from kernel.
* Returns -ENOMEM if no host pages available for allocation.
*/
case MVPKM_LOCK_MPN: {
struct MvpkmLockMPN buf;
if (copy_from_user(&buf, (void *)arg, sizeof buf)) {
return -EFAULT;
}
buf.mpn = AllocZeroedFreePages(vm,
buf.order,
false,
buf.forRegion,
NULL);
if (buf.mpn == 0) {
return -ENOMEM;
}
if (copy_to_user((void *)arg, &buf, sizeof buf)) {
return -EFAULT;
}
break;
}
case MVPKM_UNLOCK_MPN: {
struct MvpkmLockMPN buf;
if (copy_from_user(&buf, (void *)arg, sizeof buf)) {
return -EFAULT;
}
if (!LockedListDel(vm, buf.mpn)) {
return -EINVAL;
}
break;
}
case MVPKM_MAP_WSPHKVA: {
MvpkmMapHKVA mvpkmMapInfo;
HkvaMapInfo mapInfo[WSP_PAGE_COUNT];
if (copy_from_user(&mvpkmMapInfo, (void *)arg, sizeof mvpkmMapInfo)) {
return -EFAULT;
}
if (copy_from_user(mapInfo, (void *)mvpkmMapInfo.mapInfo, sizeof mapInfo)) {
return -EFAULT;
}
mvpkmMapInfo.hkva = MapWSPHKVA(vm, mapInfo);
BUG_ON(mvpkmMapInfo.hkva == 0);
if (mvpkmMapInfo.forRegion == MEMREGION_WSP) {
vm->wsp = (WorldSwitchPage *) mvpkmMapInfo.hkva;
}
if (copy_to_user((void *)arg, &mvpkmMapInfo, sizeof mvpkmMapInfo)) {
return -EFAULT;
}
break;
}
case MVPKM_RUN_MONITOR: {
if (!vm->isMonitorInited) {
vm->isMonitorInited = ((retval = SetupMonitor(vm)) == 0);
}
if (vm->isMonitorInited) {
retval = RunMonitor(vm);
}
break;
}
case MVPKM_ABORT_MONITOR: {
if (!vm->isMonitorInited) {
return -EINVAL;
}
ASSERT(vm->wsp != NULL);
Mvpkm_WakeGuest(vm, ACTION_ABORT);
break;
}
case MVPKM_CPU_INFO: {
struct MvpkmCpuInfo buf;
uint32 mpidr;
#ifdef CONFIG_ARM_LPAE
DetermineMemAttrLPAE(&buf.attribMAN);
/**
* We need to add support to the LPV monitor for LPAE page tables if we
* want to use it on a LPAE host, due to the costs involved in
* transitioning between LPAE and non-LPAE page tables without Hyp
* assistance.
*
* @knownjira{MVP-2184}
*/
buf.attribL2D.u = 0;
#else
DetermineMemAttrNonLPAE(&buf.attribL2D, &buf.attribMAN);
#endif
/*
* Are MP extensions implemented? See B4-1618 ARM DDI 0406C-2c for
* magic.
*/
ARM_MRC_CP15(MPIDR, mpidr);
buf.mpExt = mpidr & ARM_CP15_MPIDR_MP;
if (copy_to_user((int *)arg, &buf, sizeof(struct MvpkmCpuInfo))) {
retval = -EFAULT;
}
break;
}
default: {
retval = -EINVAL;
break;
}
}
PRINTK(KERN_INFO "returning from IOCTL(%d) retval = %d %s\n",
cmd, retval, signal_pending(current)?"(pending signal)":"" );
return retval;
}
/*********************************************************************
*
* Locked page management
*
*********************************************************************/
/*
* Pages locked by the kernel module are remembered so an unlockAll
* operation can be performed when the vmm is closed. The locked page
* identifiers are stored in a red-black tree to support O(log n)
* removal and search (required for /dev/mem-like mmap).
*/
/**
* @brief Descriptor of a locked page range
*/
typedef struct {
struct {
__u32 mpn : 20; ///< MPN.
__u32 order : 6; ///< Size/alignment exponent for page.
__u32 forRegion : 6; ///< Annotation to identify guest page allocation
} page;
struct rb_node rb;
} LockedPage;
static void FreeLockedPages(LockedPage *lp);
/**
* @brief Search for an mpn inside a RB tree of LockedPages. The mpn
* will match a LockedPage as long as it is covered by the
* entry, i.e. in a non-zero order entry it doesn't have to be
* the base MPN.
*
* This must be called with the relevant vm->lockedSem held.
*
* @param root RB tree root.
* @param mpn MPN to search for.
*
* @return reference to LockedPage entry if found, otherwise NULL.
*/
static LockedPage *
LockedListSearch(struct rb_root *root, __u32 mpn)
{
struct rb_node *n = root->rb_node;
while (n) {
LockedPage *lp = rb_entry(n, LockedPage, rb);
if (lp->page.mpn == (mpn & (~0UL << lp->page.order))) {
return lp;
}
if (mpn < lp->page.mpn) {
n = n->rb_left;
} else {
n = n->rb_right;
}
}
return NULL;
}
/**
* @brief Delete an mpn from the list of locked pages.
*
* @param vm Mvpkm module control structure pointer
* @param mpn MPN to be unlocked and freed for reuse
* @return true if list contained MPN and it was deleted from list
*/
static _Bool
LockedListDel(MvpkmVM *vm, __u32 mpn)
{
LockedPage *lp;
down_write(&vm->lockedSem);
lp = LockedListSearch(&vm->lockedRoot, mpn);
/*
* The MPN should be in the locked pages RB tree and it should be the
* base of an entry, i.e. we can't fragment existing allocations for
* a VM.
*/
if (lp == NULL || lp->page.mpn != mpn) {
up_write(&vm->lockedSem);
return false;
}
FreeLockedPages(lp);
if (lp->page.forRegion == MEMREGION_MAINMEM) {
ATOMIC_SUBV(vm->usedPages, 1U << lp->page.order);
}
rb_erase(&lp->rb, &vm->lockedRoot);
kfree(lp);
up_write(&vm->lockedSem);
return true;
}
/**
* @brief Scan the list of locked pages to see if an MPN matches.
*
* @param vm Mvpkm module control structure pointer
* @param mpn MPN to check
*
* @return true iff list contains MPN.
*/
static _Bool
LockedListLookup(MvpkmVM *vm, __u32 mpn)
{
LockedPage *lp;
down_read(&vm->lockedSem);
lp = LockedListSearch(&vm->lockedRoot, mpn);
up_read(&vm->lockedSem);
return lp != NULL;
}
/**
* @brief Add a new mpn to the locked pages RB tree.
*
* @param vm control structure pointer
*
* @param mpn mpn of page that was locked with get_user_pages or some sort of
* get that is undone by put_page.
* The mpn is assumed to be non-zero
* @param order size/alignment exponent for page
* @param forRegion Annotation for Page pool to identify guest page allocations
*
* @return false: couldn't allocate internal memory to record mpn in<br>
* true: successful.
*/
static _Bool
LockedListAdd(MvpkmVM *vm,
__u32 mpn,
__u32 order,
PhysMem_RegionType forRegion)
{
struct rb_node *parent, **p;
LockedPage *tp, *lp = kmalloc(sizeof *lp, GFP_KERNEL);
if (!lp) {
return false;
}
lp->page.mpn = mpn;
lp->page.order = order;
lp->page.forRegion = forRegion;
down_write(&vm->lockedSem);
if (forRegion == MEMREGION_MAINMEM) {
ATOMIC_ADDV(vm->usedPages, 1U << order);
}
/*
* Insert as a red leaf in the tree (see include/linux/rbtree.h).
*/
p = &vm->lockedRoot.rb_node;
parent = NULL;
while (*p) {
parent = *p;
tp = rb_entry(parent, LockedPage, rb);
/*
* MPN should not already exist in the tree.
*/
ASSERT(tp->page.mpn != (mpn & (~0UL << tp->page.order)));
if (mpn < tp->page.mpn) {
p = &(*p)->rb_left;
} else {
p = &(*p)->rb_right;
}
}
rb_link_node(&lp->rb, parent, p);
/*
* Restructure tree if necessary (see include/linux/rbtree.h).
*/
rb_insert_color(&lp->rb, &vm->lockedRoot);
up_write(&vm->lockedSem);
return true;
}
/**
* @brief Traverse RB locked tree, freeing every entry.
*
* This must be called with the relevant vm->lockedSem held.
*
* @param node reference to RB node at root of subtree.
*/
static void
LockedListNuke(struct rb_node *node)
{
while (node) {
if (node->rb_left) {
node = node->rb_left;
} else if (node->rb_right) {
node = node->rb_right;
} else {
/*
* We found a leaf, free it and go back to parent.
*/
LockedPage *lp = rb_entry(node, LockedPage, rb);
if ((node = rb_parent(node))) {
if (node->rb_left) {
node->rb_left = NULL;
} else {
node->rb_right = NULL;
}
}
FreeLockedPages(lp);
kfree(lp);
}
}
}
/**
* @brief Unlock all pages at vm close time.
*
* @param vm control structure pointer
*/
static void
LockedListUnlockAll(MvpkmVM *vm)
{
down_write(&vm->lockedSem);
LockedListNuke(vm->lockedRoot.rb_node);
ATOMIC_SETV(vm->usedPages, 0);
up_write(&vm->lockedSem);
}
/**
* @brief Allocate zeroed free pages
*
* @param[in] vm which VM the pages are for so they will be freed when the vm
* closes
* @param[in] order log2(number of contiguous pages to allocate)
* @param[in] highmem is it OK to allocate this page in ZONE_HIGHMEM? This
* option should only be specified for pages the host kernel
* will not need to address directly.
* @param[out] hkvaRet where to return host kernel virtual address of the
* allocated pages, if non-NULL, and ONLY IF !highmem.
* @param forRegion Annotation for Page pool to identify guest page allocations
* @return 0: no host memory available<br>
* else: starting MPN<br>
* *hkvaRet = filled in
*/
static MPN
AllocZeroedFreePages(MvpkmVM *vm,
uint32 order,
_Bool highmem,
PhysMem_RegionType forRegion,
HKVA *hkvaRet)
{
MPN mpn;
struct page *page;
if (order > PAGE_ALLOC_COSTLY_ORDER) {
printk(KERN_WARNING "Order %d allocation for region %d exceeds the safe "
"maximum order %d\n",
order,
forRegion,
PAGE_ALLOC_COSTLY_ORDER);
}
/*
* Get some pages for the requested range. They will be physically
* contiguous and have the requested alignment. They will also
* have a kernel virtual mapping if !highmem.
*
* We allocate out of ZONE_MOVABLE even though we can't just pick up our
* bags. We do this to support platforms that explicitly configure
* ZONE_MOVABLE, such as the Qualcomm MSM8960, to enable deep power down of
* memory banks. When the kernel attempts to take a memory bank offline, it
* will try and place the pages on the isolate LRU - only pages already on an
* LRU, such as anon/file, can get there, so it will not be able to
* migrate/move our pages (and hence the bank will not be offlined). The
* other alternative is to live withing ZONE_NORMAL, and only have available
* a small fraction of system memory. Long term we plan on hooking the
* offlining callback in mvpkm and perform our own migration with the
* cooperation of the monitor, but we don't have dev board to support this
* today.
*
* @knownjira{MVP-3477}
*/
page = alloc_pages(GFP_USER | __GFP_COMP | __GFP_ZERO |
(highmem ? __GFP_HIGHMEM | __GFP_MOVABLE : 0),
order);
if (page == NULL) {
return 0;
}
/*
* Return the corresponding page number.
*/
mpn = page_to_pfn(page);
ASSERT(mpn != 0);
/*
* Remember to unlock the pages when the FD is closed.
*/
if (!LockedListAdd(vm, mpn, order, forRegion)) {
__free_pages(page, order);
return 0;
}
if (hkvaRet) {
*hkvaRet = highmem ? 0 : __phys_to_virt(page_to_phys(page));
}
return mpn;
}
/**
* @brief Map already-pinned WSP memory in host kernel virtual address(HKVA)
* space. Assumes 2 world switch pages on an 8k boundary.
*
* @param[in] vm which VM the HKVA Area is to be mapped for
* @param[in] mapInfo array of MPNs and execute permission flags to be used in
inserting a new contiguous map in HKVA space
* @return 0: HKVA space could not be mapped
else: HKVA where mapping was inserted
*/
static HKVA
MapWSPHKVA(MvpkmVM *vm, HkvaMapInfo *mapInfo)
{
unsigned int i;
struct page **pages = NULL;
struct page **pagesPtr;
pgprot_t prot;
int retval;
int allocateCount = WSP_PAGE_COUNT + 1; // Reserve one page for alignment
int pageIndex = 0;
HKVA dummyPage = (HKVA)NULL;
HKVA start;
HKVA startSegment;
HKVA endSegment;
/*
* Add one page for alignment purposes in case __get_vm_area returns an
* unaligned address.
*/
ASSERT(allocateCount == 3);
ASSERT_ON_COMPILE(WSP_PAGE_COUNT == 2);
/*
* NOT_IMPLEMENTED if MapHKVA is called more than once.
*/
BUG_ON(vm->wspHkvaArea);
/*
* Reserve virtual address space.
*/
vm->wspHkvaArea = __get_vm_area((allocateCount * PAGE_SIZE), VM_ALLOC, MODULES_VADDR, MODULES_END);
if (!vm->wspHkvaArea) {
return 0;
}
pages = kmalloc(allocateCount * sizeof(struct page *), GFP_TEMPORARY);
if (!pages) {
goto err;
}
pagesPtr = pages;
/*
* Use a dummy page to boundary align the section, if needed.
*/
dummyPage = __get_free_pages(GFP_KERNEL, 0);
if (!dummyPage) {
goto err;
}
vm->wspHKVADummyPage = dummyPage;
/*
* Back every entry with the dummy page.
*/
for (i = 0; i < allocateCount; i++) {
pages[i] = virt_to_page(dummyPage);
}
/*
* World switch pages must not span a 1MB boundary in order to maintain only
* a single L2 page table.
*/
start = (HKVA)vm->wspHkvaArea->addr;
startSegment = start & ~(ARM_L1D_SECTION_SIZE - 1);
endSegment = (start + PAGE_SIZE) & ~(ARM_L1D_SECTION_SIZE - 1);
/*
* Insert dummy page at pageIndex, if needed.
*/
pageIndex = (startSegment != endSegment);
/*
* Back the rest with the actual world switch pages
*/
for (i = pageIndex; i < pageIndex + WSP_PAGE_COUNT; i++) {
pages[i] = pfn_to_page(mapInfo[i - pageIndex].mpn);
}
/*
* Given the lack of functionality in the kernel for being able to mark
* mappings for a given vm area with different sets of protection bits,
* we simply mark the entire vm area as PAGE_KERNEL_EXEC for now
* (i.e., union of all the protection bits). Given that the kernel
* itself does something similar while loading modules, this should be a
* reasonable workaround for now. In the future, we should set the
* protection bits to strictly adhere to what has been requested in the
* mapInfo parameter.
*/
prot = PAGE_KERNEL_EXEC;
retval = map_vm_area(vm->wspHkvaArea, prot, &pagesPtr);
if (retval < 0) {
goto err;
}
kfree(pages);
return (HKVA)(vm->wspHkvaArea->addr) + pageIndex * PAGE_SIZE;
err:
if (dummyPage) {
free_pages(dummyPage, 0);
vm->wspHKVADummyPage = (HKVA)NULL;
}
if (pages) {
kfree(pages);
}
free_vm_area(vm->wspHkvaArea);
vm->wspHkvaArea = (HKVA)NULL;
return 0;
}
static void
UnmapWSPHKVA(MvpkmVM *vm)
{
if (vm->wspHkvaArea) {
free_vm_area(vm->wspHkvaArea);
}
if (vm->wspHKVADummyPage) {
free_pages(vm->wspHKVADummyPage, 0);
vm->wspHKVADummyPage = (HKVA)NULL;
}
}
/**
* @brief Clean and release locked pages
*
* @param lp Reference to the locked pages
*/
static void
FreeLockedPages(LockedPage *lp)
{
struct page *page;
int count;
page = pfn_to_page(lp->page.mpn);
count = page_count(page);
if (count == 0) {
printk(KERN_ERR "%s: found locked page with 0 reference (mpn %05x)\n",
__func__, lp->page.mpn);
return;
}
if (count == 1) {
int i;
/*
* There is no other user for this page, clean it.
*
* We don't bother checking if the page was highmem or not, clear_highmem
* works for both.
* We clear the content of the page, and rely on the fact that the previous
* worldswitch has cleaned the potential VIVT I-CACHE.
*/
for (i = 0; i < (1 << lp->page.order); i++) {
clear_highpage(page + i);
}
} else if (lp->page.forRegion != MEMREGION_MAINMEM) {
printk(KERN_WARNING "%s: mpn 0x%05x for region %d is still in use\n",
__func__, lp->page.mpn, lp->page.forRegion);
}
__free_pages(page, lp->page.order);
}
/*********************************************************************
*
* Communicate with monitor
*
*********************************************************************/
/**
* @brief Register a new monitor page.
*
* @param vm which virtual machine we're running
* @return 0: successful<br>
* else: -errno
*/
static int
SetupMonitor(MvpkmVM *vm)
{
int retval;
WorldSwitchPage *wsp = vm->wsp;
if (!wsp ||
wsp->wspHKVA != (HKVA)wsp) {
return -EINVAL;
}
if ((retval = Mksck_WspInitialize(vm))) {
return retval;
}
vm->kobj.kset = mvpkmKSet;
retval = kobject_init_and_add(&vm->kobj, &mvpkmKType, NULL, "%d", wsp->guestId);
if (retval) {
goto error;
}
/*
* Get a reference to this module such that it cannot be unloaded until
* our kobject's release function completes.
*/
__module_get(THIS_MODULE);
vm->haveKObj = true;
/*
* Caution: From here on, if we fail, we must not call kobject_put()
* on vm->kobj since that may / will deallocate 'vm'. Unregistering VM
* ksets on failures, is fine and should be done for proper ref counting.
*/
vm->devicesKSet = kset_create_and_add("devices", NULL, &vm->kobj);
if (!vm->devicesKSet) {
retval = -ENOMEM;
goto error;
}
vm->miscKSet = kset_create_and_add("misc", NULL, &vm->kobj);
if (!vm->miscKSet) {
kset_unregister(vm->devicesKSet);
vm->devicesKSet = NULL;
retval = -ENOMEM;
goto error;
}
down_write(&vm->wspSem);
/*
* The VE monitor needs to issue a SMC to bootstrap Hyp mode.
*/
if (wsp->monType == MONITOR_TYPE_VE) {
/*
* Here we assemble the monitor's HMAIR0 based on wsp->memAttr. We map
* from the inner/outer normal page cacheability attributes obtained
* from DetermineCacheabilityAttribs to the format required in 4.2.8
* ARM PRD03-GENC-008469 13.0 (see this document for the magic numbers).
*
* Where a choice is available, we opt for read and/or write allocation.
*/
static const uint32 normalCacheAttr2MAIR[4] = { 0x4, 0xf, 0xa, 0xe };
uint32 hmair0 =
((normalCacheAttr2MAIR[wsp->memAttr.innerCache] |
(normalCacheAttr2MAIR[wsp->memAttr.outerCache] << 4))
<< 8 * MVA_MEMORY) |
(0x4 << 8 * MVA_DEVICE);
/*
* See B4.1.74 ARM DDI 0406C-2c for the HTCR magic.
*/
uint32 htcr =
0x80000000 |
(wsp->memAttr.innerCache << 8) |
(wsp->memAttr.outerCache << 10) |
(wsp->memAttr.share << 12);
/**
* @knownjira{MVP-377}
* Set HSCTLR to enable MMU and caches. We should really run the
* monitor WXN, in non-MVP_DEVEL builds. See
* 13.18 ARM PRD03-GENC-008353 11.0 for the magic.
*/
static const uint32 hsctlr = 0x30c5187d;
register uint32 r0 asm("r0") = wsp->monVA.excVec;
register uint32 r1 asm("r1") = wsp->regSave.ve.mHTTBR;
register uint32 r2 asm("r2") = htcr;
register uint32 r3 asm("r3") = hmair0;
register uint32 r4 asm("r4") = hsctlr;
asm volatile (
"smc 0"
:
: "r" (r0), "r" (r1), "r" (r2), "r" (r3), "r" (r4)
: "memory"
);
}
/*
* Initialize guest wait-for-interrupt waitqueue.
*/
init_waitqueue_head(&vm->wfiWaitQ);
MonitorTimer_Setup(vm);
#ifdef CONFIG_HAS_WAKELOCK
wake_lock_init(&vm->wakeLock, WAKE_LOCK_SUSPEND, "mvpkm");
#endif
wsp->mvpkmVersion = MVP_VERSION_CODE;
up_write(&vm->wspSem);
/*
* Ensure coherence of monitor loading and page tables.
*/
flush_cache_all();
return 0;
error:
Mksck_WspRelease(wsp);
vm->wsp = NULL;
return retval;
}
/**
* @brief dummy function to drop the info parameter
* @param info ignored
*/
static
void FlushAllCpuCaches(void *info)
{
flush_cache_all();
}
/**
* @brief return to where monitor called worldswitch
*
* @param vm which virtual machine we're running
* @return 0: successful, just call back when ready<br>
* 1: successful, process code in WSP_Params(wsp)->callno<br>
* else: -errno
*/
static int
RunMonitor(MvpkmVM *vm)
{
int ii;
unsigned long flags;
WorldSwitchPage *wsp = vm->wsp;
int retval = 0;
ASSERT(wsp);
#ifdef CONFIG_HAS_WAKELOCK
wake_lock(&vm->wakeLock);
#endif
/*
* Set VCPUThread affinity
*/
if (cpumask_intersects(to_cpumask(vcpuAffinity), cpu_active_mask)) {
set_cpus_allowed_ptr(current, to_cpumask(vcpuAffinity));
}
/*
* Record the the current task structure, so an ABORT will know,
* who to wake.
*/
down_write(&vm->monThreadTaskSem);
vm->monThreadTask = get_current();
up_write(&vm->monThreadTaskSem);
/*
* Keep going as long as the monitor is in critical section or
* there are no pending signals such as SIGINT or SIGKILL. Block
* interrupts before checking so any IPI sent will remain pending
* if our check just misses detecting the signal.
*/
local_irq_save(flags);
while (wsp->critSecCount > 0 ||
(!signal_pending(current) &&
!(ATOMIC_GETO(wsp->hostActions) & ACTION_ABORT))) {
/*
* ARMv7 Performance counters are per CPU core and might be disabled over
* CPU core sleep if there is nothing else in the system to re-enable
* them, so now that we have been allocated a CPU core to run the guest,
* enable them and in particular the TSC (CCNT) which is used for monitor
* timing between world switches.
*/
{
uint32 pmnc;
uint32 pmcnt;
/* make sure that the Performance Counters are enabled */
ARM_MRC_CP15(PERF_MON_CONTROL_REGISTER, pmnc);
if ((pmnc & (ARM_PMNC_E | ARM_PMNC_D)) != (ARM_PMNC_E)) {
pmnc |= ARM_PMNC_E; // Enable TSC
pmnc &= ~ARM_PMNC_D; // Disable cycle count divider
ARM_MCR_CP15(PERF_MON_CONTROL_REGISTER, pmnc);
}
/* make sure that the CCNT is enabled */
ARM_MRC_CP15(PERF_MON_COUNT_SET, pmcnt);
if ((pmcnt & ARM_PMCNT_C) != ARM_PMCNT_C) {
pmcnt |= ARM_PMCNT_C;
ARM_MCR_CP15(PERF_MON_COUNT_SET, pmcnt);
}
}
/*
* Update TSC to RATE64 ratio
*/
{
struct TscToRate64Cb *ttr = &__get_cpu_var(tscToRate64);
wsp->tscToRate64Mult = ttr->mult;
wsp->tscToRate64Shift = ttr->shift;
}
/*
* Save the time of day for the monitor's timer facility. The timing
* facility in the vmm needs to compute current time in the host linux's
* time representation. It uses the formula:
* now = wsp->switchedAt64 + (uint32)(TSC_READ() - wsp->lowerTSC)
*
* Read the timestamp counter *immediately after* ktime_get() as that
* will give the most consistent offset between reading the hardware
* clock register in ktime_get() and reading the hardware timestamp
* counter with TSC_READ().
*/
ASSERT_ON_COMPILE(MVP_TIMER_RATE64 == NSEC_PER_SEC);
{
ktime_t now = ktime_get();
TSC_READ(wsp->switchedAtTSC);
wsp->switchedAt64 = ktime_to_ns(now);
}
/*
* Save host FPU contents and load monitor contents.
*/
SWITCH_VFP_TO_MONITOR;
/*
* Call into the monitor to run guest instructions until it wants us to
* do something for it. Note that any hardware interrupt request will
* cause it to volunteer.
*/
switch (wsp->monType) {
case MONITOR_TYPE_LPV: {
uint32 hostVBAR;
ARM_MRC_CP15(VECTOR_BASE, hostVBAR);
(*wsp->switchToMonitor)(&wsp->regSave);
ARM_MCR_CP15(VECTOR_BASE, hostVBAR);
break;
}
case MONITOR_TYPE_VE: {
register uint32 r1 asm("r1") = wsp->regSave.ve.mHTTBR;
asm volatile (
".word " MVP_STRINGIFY(ARM_INSTR_HVC_A1_ENC(0))
: "=r" (r1) : "r" (r1) : "r0", "r2", "memory"
);
break;
}
default: FATAL();
}
/*
* Save monitor FPU contents and load host contents.
*/
SWITCH_VFP_TO_HOST;
/*
* Re-enable local interrupts now that we are back in the host world
*/
local_irq_restore(flags);
/*
* Maybe the monitor wrote some messages to monitor->host sockets.
* This will wake the corresponding host threads to receive them.
*/
/**
* @todo This lousy loop is in the critical path. It should be changed
* to some faster algorithm to wake blocked host sockets.
*/
for (ii = 0; ii < MKSCK_MAX_SHARES; ii++) {
if (wsp->isPageMapped[ii]) {
Mksck_WakeBlockedSockets(MksckPage_GetFromIdx(ii));
}
}
switch (WSP_Params(wsp)->callno) {
case WSCALL_ACQUIRE_PAGE: {
uint32 i;
for (i = 0; i < WSP_Params(wsp)->pages.pages; ++i) {
MPN mpn = AllocZeroedFreePages(vm,
WSP_Params(wsp)->pages.order,
true,
WSP_Params(wsp)->pages.forRegion,
NULL);
if (mpn == 0) {
printk(KERN_WARNING "WSCALL_ACQUIRE_PAGE: no order %u pages available\n",
WSP_Params(wsp)->pages.order);
WSP_Params(wsp)->pages.pages = i;
break;
}
WSP_Params(wsp)->pages.mpns[i] = mpn;
}
break;
}
case WSCALL_RELEASE_PAGE: {
uint32 i;
for (i = 0; i < WSP_Params(wsp)->pages.pages; ++i) {
if (!LockedListDel(vm, WSP_Params(wsp)->pages.mpns[i])) {
WSP_Params(wsp)->pages.pages = i;
break;
}
}
break;
}
case WSCALL_MUTEXLOCK: {
retval = Mutex_Lock((void *)WSP_Params(wsp)->mutex.mtxHKVA,
WSP_Params(wsp)->mutex.mode);
if (retval < 0) {
WSP_Params(wsp)->mutex.ok = false;
goto monitorExit;
}
/*
* The locking succeeded. From this point on the monitor
* is in critical section. Even if an interrupt comes
* right here, it must return to the monitor to unlock the
* mutex.
*/
wsp->critSecCount++;
WSP_Params(wsp)->mutex.ok = true;
break;
}
case WSCALL_MUTEXUNLOCK: {
Mutex_Unlock((void *)WSP_Params(wsp)->mutex.mtxHKVA,
WSP_Params(wsp)->mutex.mode);
break;
}
case WSCALL_MUTEXUNLSLEEP: {
/*
* The vcpu has just come back from the monitor. During
* the transition interrupts were disabled. Above,
* however, interrupts were enabled again and it is
* possible that a context switch happened into a thread
* (serve_vmx) that instructed the vcpu thread to
* abort. After returning to this thread the vcpu may
* enter a sleep below never to return from it. To avoid
* this deadlock we need to test the abort flag in
* Mutex_UnlSleepTest.
*/
retval =
Mutex_UnlSleepTest((void *)WSP_Params(wsp)->mutex.mtxHKVA,
WSP_Params(wsp)->mutex.mode,
WSP_Params(wsp)->mutex.cvi,
&wsp->hostActions,
ACTION_ABORT);
if (retval < 0) {
goto monitorExit;
}
break;
}
case WSCALL_MUTEXUNLWAKE: {
Mutex_UnlWake((void *)WSP_Params(wsp)->mutex.mtxHKVA,
WSP_Params(wsp)->mutex.mode,
WSP_Params(wsp)->mutex.cvi,
WSP_Params(wsp)->mutex.all);
break;
}
/*
* The monitor wants us to block (allowing other host threads to run)
* until an async message is waiting for the monitor to process.
*
* If MvpkmWaitForInt() returns an error, it should only be if there
* is another signal pending (such as SIGINT). So we pretend it
* completed normally, as the monitor is ready to be called again (it
* will see no messages to process and wait again), and return to user
* mode so the signals can be processed.
*/
case WSCALL_WAIT: {
#ifdef CONFIG_HAS_WAKELOCK
if (WSP_Params(wsp)->wait.suspendMode) {
/* guest has ok'ed suspend mode, so release SUSPEND wakelock */
wake_unlock(&vm->wakeLock);
retval = MvpkmWaitForInt(vm, true);
wake_lock(&vm->wakeLock);
WSP_Params(wsp)->wait.suspendMode = 0;
} else {
/* guest has asked for WFI not suspend so keep holding SUSPEND
* wakelock */
retval = MvpkmWaitForInt(vm, false);
}
#else
retval = MvpkmWaitForInt(vm, WSP_Params(wsp)->wait.suspendMode);
#endif
if (retval < 0) {
goto monitorExit;
}
break;
}
/*
* The only reason the monitor returned was because there was a
* pending hardware interrupt. The host serviced and cleared that
* interrupt when we enabled interrupts above. Now we call the
* scheduler in case that interrupt woke another thread, we want to
* allow that thread to run before returning to do more guest code.
*/
case WSCALL_IRQ: {
break;
}
case WSCALL_GET_PAGE_FROM_VMID: {
MksckPage *mksckPage;
mksckPage = MksckPage_GetFromVmIdIncRefc(WSP_Params(wsp)->pageMgmnt.vmId);
if (mksckPage) {
int ii;
WSP_Params(wsp)->pageMgmnt.found = true;
for (ii = 0; ii < MKSCKPAGE_TOTAL; ii++) {
WSP_Params(wsp)->pageMgmnt.mpn[ii] =
vmalloc_to_pfn( (void*)(((HKVA)mksckPage) + ii*PAGE_SIZE) );
}
ASSERT(!wsp->isPageMapped[MKSCK_VMID2IDX(mksckPage->vmId)]);
wsp->isPageMapped[MKSCK_VMID2IDX(mksckPage->vmId)] = true;
} else {
WSP_Params(wsp)->pageMgmnt.found = false;
}
break;
}
case WSCALL_REMOVE_PAGE_FROM_VMID: {
MksckPage *mksckPage;
mksckPage = MksckPage_GetFromVmId(WSP_Params(wsp)->pageMgmnt.vmId);
ASSERT(wsp->isPageMapped[MKSCK_VMID2IDX(mksckPage->vmId)]);
wsp->isPageMapped[MKSCK_VMID2IDX(mksckPage->vmId)] = false;
MksckPage_DecRefc(mksckPage);
break;
}
/*
* Read current wallclock time.
*/
case WSCALL_READTOD: {
struct timeval nowTV;
do_gettimeofday(&nowTV);
WSP_Params(wsp)->tod.now = nowTV.tv_sec;
WSP_Params(wsp)->tod.nowusec = nowTV.tv_usec;
break;
}
case WSCALL_LOG: {
int len = strlen(WSP_Params(wsp)->log.messg);
printk(KERN_INFO
"VMM: %s%s",
WSP_Params(wsp)->log.messg,
(WSP_Params(wsp)->log.messg[len-1] == '\n') ? "" : "\n");
break;
}
case WSCALL_ABORT: {
retval = WSP_Params(wsp)->abort.status;
goto monitorExit;
}
case WSCALL_QP_GUEST_ATTACH: {
int32 rc;
QPInitArgs args;
uint32 base;
uint32 nrPages;
args.id = WSP_Params(wsp)->qp.id;
args.capacity = WSP_Params(wsp)->qp.capacity;
args.type = WSP_Params(wsp)->qp.type;
base = WSP_Params(wsp)->qp.base;
nrPages = WSP_Params(wsp)->qp.nrPages;
rc = QP_GuestAttachRequest(vm, &args, base, nrPages);
WSP_Params(wsp)->qp.rc = rc;
WSP_Params(wsp)->qp.id = args.id;
break;
}
case WSCALL_QP_NOTIFY: {
QPInitArgs args;
args.id = WSP_Params(wsp)->qp.id;
args.capacity = WSP_Params(wsp)->qp.capacity;
args.type = WSP_Params(wsp)->qp.type;
WSP_Params(wsp)->qp.rc = QP_NotifyListener(&args);
break;
}
case WSCALL_MONITOR_TIMER: {
MonitorTimer_Request(&vm->monTimer, WSP_Params(wsp)->timer.when64);
break;
}
case WSCALL_COMM_SIGNAL: {
Mvpkm_CommEvSignal(&WSP_Params(wsp)->commEvent.transpID,
WSP_Params(wsp)->commEvent.event);
break;
}
case WSCALL_FLUSH_ALL_DCACHES: {
/*
* Broadcast Flush DCache request to all cores.
* Block while waiting for all of them to get done.
*/
on_each_cpu(FlushAllCpuCaches, NULL, 1);
break;
}
default: {
retval = -EPIPE;
goto monitorExit;
}
}
/*
* The params.callno callback was handled in kernel mode and completed
* successfully. Repeat for another call without returning to user mode,
* unless there are signals pending.
*
* But first, call the Linux scheduler to switch threads if there is
* some other thread Linux wants to run now.
*/
if (need_resched()) {
schedule();
}
/*
* Check if cpus allowed mask has to be updated.
* Updating it must be done outside of an atomic context.
*/
if (cpumask_intersects(to_cpumask(vcpuAffinity), cpu_active_mask) &&
!cpumask_equal(to_cpumask(vcpuAffinity), ¤t->cpus_allowed)) {
set_cpus_allowed_ptr(current, to_cpumask(vcpuAffinity));
}
local_irq_save(flags);
}
/*
* There are signals pending so don't try to do any more monitor/guest
* stuff. But since we were at the point of just about to run the monitor,
* return success status as user mode can simply call us back to run the
* monitor again.
*/
local_irq_restore(flags);
monitorExit:
ASSERT(wsp->critSecCount == 0);
if (ATOMIC_GETO(wsp->hostActions) & ACTION_ABORT) {
PRINTK(KERN_INFO "Monitor has ABORT flag set.\n");
retval = ExitStatusHostRequest;
}
#ifdef CONFIG_HAS_WAKELOCK
wake_unlock(&vm->wakeLock);
#endif
down_write(&vm->monThreadTaskSem);
vm->monThreadTask = NULL;
up_write(&vm->monThreadTaskSem);
return retval;
}
/**
* @brief Guest is waiting for interrupts, sleep if necessary
*
* @param vm which virtual machine we're running
* @param suspend is the guest entering suspend or just WFI?
* @return 0: woken up, hostActions should have pending events
* -ERESTARTSYS: broke out because other signals are pending
*
* This function is called in the VCPU context after the world switch to wait
* for an incoming message. If any message gets queued to this VCPU, the
* sender will wake us up.
*/
int
MvpkmWaitForInt(MvpkmVM *vm, _Bool suspend)
{
WorldSwitchPage *wsp = vm->wsp;
wait_queue_head_t *q = &vm->wfiWaitQ;
if (suspend) {
return wait_event_interruptible(*q, ATOMIC_GETO(wsp->hostActions) != 0);
} else {
int ret;
ret = wait_event_interruptible_timeout(*q, ATOMIC_GETO(wsp->hostActions) != 0, 10*HZ);
if (ret == 0) {
printk("MvpkmWaitForInt: guest stuck for 10s in WFI! (hostActions %08x)\n",
ATOMIC_GETO(wsp->hostActions));
}
return ret > 0 ? 0 : ret;
}
}
/**
* @brief Force the guest to evaluate its hostActions flag field
*
* @param vm which guest needs waking
* @param why why should be guest be woken up?
*
* This function updates the hostAction flag field as and wakes up the guest as
* required so that it can evaluate it. The guest could be executing guest
* code in an SMP system, in that case send an IPI; or it could be sleeping, in
* the case wake it up.
*/
void
Mvpkm_WakeGuest(MvpkmVM *vm, int why)
{
ASSERT(why != 0);
/* set the host action */
if (ATOMIC_ORO(vm->wsp->hostActions, why) & why) {
/* guest has already been woken up so no need to do it again */
return;
}
/*
* VCPU is certainly in 'wait for interrupt' wait. Wake it up !
*/
#ifdef CONFIG_HAS_WAKELOCK
/*
* To prevent the system to go in suspend mode before the monitor had a
* chance on being scheduled, we will hold the VM wakelock from now.
* As the wakelocks are not managed as reference counts, this is not an
* an issue to take a wake_lock twice in a row.
*/
wake_lock(&vm->wakeLock);
#endif
/*
* On a UP system, we ensure the monitor thread isn't blocked.
*
* On an MP system the other CPU might be running the guest. This
* is noop on UP.
*
* When the guest is running, it is an invariant that monThreadTaskSem is not
* held as a write lock, so we should not fail to acquire the lock.
* Mvpkm_WakeGuest may be called from an atomic context, so we can't sleep
* here.
*/
if (down_read_trylock(&vm->monThreadTaskSem)) {
if (vm->monThreadTask) {
wake_up_process(vm->monThreadTask);
kick_process(vm->monThreadTask);
}
up_read(&vm->monThreadTaskSem);
} else {
printk("Unexpected failure to acquire monThreadTaskSem!\n");
}
}
| gpl-2.0 |
sguiriec/linux-audio | drivers/s390/char/monreader.c | 199 | 16832 | /*
* Character device driver for reading z/VM *MONITOR service records.
*
* Copyright IBM Corp. 2004, 2009
*
* Author: Gerald Schaefer <gerald.schaefer@de.ibm.com>
*/
#define KMSG_COMPONENT "monreader"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/ctype.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/poll.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <net/iucv/iucv.h>
#include <asm/uaccess.h>
#include <asm/ebcdic.h>
#include <asm/extmem.h>
#define MON_COLLECT_SAMPLE 0x80
#define MON_COLLECT_EVENT 0x40
#define MON_SERVICE "*MONITOR"
#define MON_IN_USE 0x01
#define MON_MSGLIM 255
static char mon_dcss_name[9] = "MONDCSS\0";
struct mon_msg {
u32 pos;
u32 mca_offset;
struct iucv_message msg;
char msglim_reached;
char replied_msglim;
};
struct mon_private {
struct iucv_path *path;
struct mon_msg *msg_array[MON_MSGLIM];
unsigned int write_index;
unsigned int read_index;
atomic_t msglim_count;
atomic_t read_ready;
atomic_t iucv_connected;
atomic_t iucv_severed;
};
static unsigned long mon_in_use = 0;
static unsigned long mon_dcss_start;
static unsigned long mon_dcss_end;
static DECLARE_WAIT_QUEUE_HEAD(mon_read_wait_queue);
static DECLARE_WAIT_QUEUE_HEAD(mon_conn_wait_queue);
static u8 user_data_connect[16] = {
/* Version code, must be 0x01 for shared mode */
0x01,
/* what to collect */
MON_COLLECT_SAMPLE | MON_COLLECT_EVENT,
/* DCSS name in EBCDIC, 8 bytes padded with blanks */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
static u8 user_data_sever[16] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
static struct device *monreader_device;
/******************************************************************************
* helper functions *
*****************************************************************************/
/*
* Create the 8 bytes EBCDIC DCSS segment name from
* an ASCII name, incl. padding
*/
static void dcss_mkname(char *ascii_name, char *ebcdic_name)
{
int i;
for (i = 0; i < 8; i++) {
if (ascii_name[i] == '\0')
break;
ebcdic_name[i] = toupper(ascii_name[i]);
}
for (; i < 8; i++)
ebcdic_name[i] = ' ';
ASCEBC(ebcdic_name, 8);
}
static inline unsigned long mon_mca_start(struct mon_msg *monmsg)
{
return *(u32 *) &monmsg->msg.rmmsg;
}
static inline unsigned long mon_mca_end(struct mon_msg *monmsg)
{
return *(u32 *) &monmsg->msg.rmmsg[4];
}
static inline u8 mon_mca_type(struct mon_msg *monmsg, u8 index)
{
return *((u8 *) mon_mca_start(monmsg) + monmsg->mca_offset + index);
}
static inline u32 mon_mca_size(struct mon_msg *monmsg)
{
return mon_mca_end(monmsg) - mon_mca_start(monmsg) + 1;
}
static inline u32 mon_rec_start(struct mon_msg *monmsg)
{
return *((u32 *) (mon_mca_start(monmsg) + monmsg->mca_offset + 4));
}
static inline u32 mon_rec_end(struct mon_msg *monmsg)
{
return *((u32 *) (mon_mca_start(monmsg) + monmsg->mca_offset + 8));
}
static int mon_check_mca(struct mon_msg *monmsg)
{
if ((mon_rec_end(monmsg) <= mon_rec_start(monmsg)) ||
(mon_rec_start(monmsg) < mon_dcss_start) ||
(mon_rec_end(monmsg) > mon_dcss_end) ||
(mon_mca_type(monmsg, 0) == 0) ||
(mon_mca_size(monmsg) % 12 != 0) ||
(mon_mca_end(monmsg) <= mon_mca_start(monmsg)) ||
(mon_mca_end(monmsg) > mon_dcss_end) ||
(mon_mca_start(monmsg) < mon_dcss_start) ||
((mon_mca_type(monmsg, 1) == 0) && (mon_mca_type(monmsg, 2) == 0)))
return -EINVAL;
return 0;
}
static int mon_send_reply(struct mon_msg *monmsg,
struct mon_private *monpriv)
{
int rc;
rc = iucv_message_reply(monpriv->path, &monmsg->msg,
IUCV_IPRMDATA, NULL, 0);
atomic_dec(&monpriv->msglim_count);
if (likely(!monmsg->msglim_reached)) {
monmsg->pos = 0;
monmsg->mca_offset = 0;
monpriv->read_index = (monpriv->read_index + 1) %
MON_MSGLIM;
atomic_dec(&monpriv->read_ready);
} else
monmsg->replied_msglim = 1;
if (rc) {
pr_err("Reading monitor data failed with rc=%i\n", rc);
return -EIO;
}
return 0;
}
static void mon_free_mem(struct mon_private *monpriv)
{
int i;
for (i = 0; i < MON_MSGLIM; i++)
kfree(monpriv->msg_array[i]);
kfree(monpriv);
}
static struct mon_private *mon_alloc_mem(void)
{
int i;
struct mon_private *monpriv;
monpriv = kzalloc(sizeof(struct mon_private), GFP_KERNEL);
if (!monpriv)
return NULL;
for (i = 0; i < MON_MSGLIM; i++) {
monpriv->msg_array[i] = kzalloc(sizeof(struct mon_msg),
GFP_KERNEL);
if (!monpriv->msg_array[i]) {
mon_free_mem(monpriv);
return NULL;
}
}
return monpriv;
}
static inline void mon_next_mca(struct mon_msg *monmsg)
{
if (likely((mon_mca_size(monmsg) - monmsg->mca_offset) == 12))
return;
monmsg->mca_offset += 12;
monmsg->pos = 0;
}
static struct mon_msg *mon_next_message(struct mon_private *monpriv)
{
struct mon_msg *monmsg;
if (!atomic_read(&monpriv->read_ready))
return NULL;
monmsg = monpriv->msg_array[monpriv->read_index];
if (unlikely(monmsg->replied_msglim)) {
monmsg->replied_msglim = 0;
monmsg->msglim_reached = 0;
monmsg->pos = 0;
monmsg->mca_offset = 0;
monpriv->read_index = (monpriv->read_index + 1) %
MON_MSGLIM;
atomic_dec(&monpriv->read_ready);
return ERR_PTR(-EOVERFLOW);
}
return monmsg;
}
/******************************************************************************
* IUCV handler *
*****************************************************************************/
static void mon_iucv_path_complete(struct iucv_path *path, u8 *ipuser)
{
struct mon_private *monpriv = path->private;
atomic_set(&monpriv->iucv_connected, 1);
wake_up(&mon_conn_wait_queue);
}
static void mon_iucv_path_severed(struct iucv_path *path, u8 *ipuser)
{
struct mon_private *monpriv = path->private;
pr_err("z/VM *MONITOR system service disconnected with rc=%i\n",
ipuser[0]);
iucv_path_sever(path, NULL);
atomic_set(&monpriv->iucv_severed, 1);
wake_up(&mon_conn_wait_queue);
wake_up_interruptible(&mon_read_wait_queue);
}
static void mon_iucv_message_pending(struct iucv_path *path,
struct iucv_message *msg)
{
struct mon_private *monpriv = path->private;
memcpy(&monpriv->msg_array[monpriv->write_index]->msg,
msg, sizeof(*msg));
if (atomic_inc_return(&monpriv->msglim_count) == MON_MSGLIM) {
pr_warning("The read queue for monitor data is full\n");
monpriv->msg_array[monpriv->write_index]->msglim_reached = 1;
}
monpriv->write_index = (monpriv->write_index + 1) % MON_MSGLIM;
atomic_inc(&monpriv->read_ready);
wake_up_interruptible(&mon_read_wait_queue);
}
static struct iucv_handler monreader_iucv_handler = {
.path_complete = mon_iucv_path_complete,
.path_severed = mon_iucv_path_severed,
.message_pending = mon_iucv_message_pending,
};
/******************************************************************************
* file operations *
*****************************************************************************/
static int mon_open(struct inode *inode, struct file *filp)
{
struct mon_private *monpriv;
int rc;
/*
* only one user allowed
*/
rc = -EBUSY;
if (test_and_set_bit(MON_IN_USE, &mon_in_use))
goto out;
rc = -ENOMEM;
monpriv = mon_alloc_mem();
if (!monpriv)
goto out_use;
/*
* Connect to *MONITOR service
*/
monpriv->path = iucv_path_alloc(MON_MSGLIM, IUCV_IPRMDATA, GFP_KERNEL);
if (!monpriv->path)
goto out_priv;
rc = iucv_path_connect(monpriv->path, &monreader_iucv_handler,
MON_SERVICE, NULL, user_data_connect, monpriv);
if (rc) {
pr_err("Connecting to the z/VM *MONITOR system service "
"failed with rc=%i\n", rc);
rc = -EIO;
goto out_path;
}
/*
* Wait for connection confirmation
*/
wait_event(mon_conn_wait_queue,
atomic_read(&monpriv->iucv_connected) ||
atomic_read(&monpriv->iucv_severed));
if (atomic_read(&monpriv->iucv_severed)) {
atomic_set(&monpriv->iucv_severed, 0);
atomic_set(&monpriv->iucv_connected, 0);
rc = -EIO;
goto out_path;
}
filp->private_data = monpriv;
dev_set_drvdata(monreader_device, monpriv);
return nonseekable_open(inode, filp);
out_path:
iucv_path_free(monpriv->path);
out_priv:
mon_free_mem(monpriv);
out_use:
clear_bit(MON_IN_USE, &mon_in_use);
out:
return rc;
}
static int mon_close(struct inode *inode, struct file *filp)
{
int rc, i;
struct mon_private *monpriv = filp->private_data;
/*
* Close IUCV connection and unregister
*/
if (monpriv->path) {
rc = iucv_path_sever(monpriv->path, user_data_sever);
if (rc)
pr_warning("Disconnecting the z/VM *MONITOR system "
"service failed with rc=%i\n", rc);
iucv_path_free(monpriv->path);
}
atomic_set(&monpriv->iucv_severed, 0);
atomic_set(&monpriv->iucv_connected, 0);
atomic_set(&monpriv->read_ready, 0);
atomic_set(&monpriv->msglim_count, 0);
monpriv->write_index = 0;
monpriv->read_index = 0;
dev_set_drvdata(monreader_device, NULL);
for (i = 0; i < MON_MSGLIM; i++)
kfree(monpriv->msg_array[i]);
kfree(monpriv);
clear_bit(MON_IN_USE, &mon_in_use);
return 0;
}
static ssize_t mon_read(struct file *filp, char __user *data,
size_t count, loff_t *ppos)
{
struct mon_private *monpriv = filp->private_data;
struct mon_msg *monmsg;
int ret;
u32 mce_start;
monmsg = mon_next_message(monpriv);
if (IS_ERR(monmsg))
return PTR_ERR(monmsg);
if (!monmsg) {
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
ret = wait_event_interruptible(mon_read_wait_queue,
atomic_read(&monpriv->read_ready) ||
atomic_read(&monpriv->iucv_severed));
if (ret)
return ret;
if (unlikely(atomic_read(&monpriv->iucv_severed)))
return -EIO;
monmsg = monpriv->msg_array[monpriv->read_index];
}
if (!monmsg->pos)
monmsg->pos = mon_mca_start(monmsg) + monmsg->mca_offset;
if (mon_check_mca(monmsg))
goto reply;
/* read monitor control element (12 bytes) first */
mce_start = mon_mca_start(monmsg) + monmsg->mca_offset;
if ((monmsg->pos >= mce_start) && (monmsg->pos < mce_start + 12)) {
count = min(count, (size_t) mce_start + 12 - monmsg->pos);
ret = copy_to_user(data, (void *) (unsigned long) monmsg->pos,
count);
if (ret)
return -EFAULT;
monmsg->pos += count;
if (monmsg->pos == mce_start + 12)
monmsg->pos = mon_rec_start(monmsg);
goto out_copy;
}
/* read records */
if (monmsg->pos <= mon_rec_end(monmsg)) {
count = min(count, (size_t) mon_rec_end(monmsg) - monmsg->pos
+ 1);
ret = copy_to_user(data, (void *) (unsigned long) monmsg->pos,
count);
if (ret)
return -EFAULT;
monmsg->pos += count;
if (monmsg->pos > mon_rec_end(monmsg))
mon_next_mca(monmsg);
goto out_copy;
}
reply:
ret = mon_send_reply(monmsg, monpriv);
return ret;
out_copy:
*ppos += count;
return count;
}
static unsigned int mon_poll(struct file *filp, struct poll_table_struct *p)
{
struct mon_private *monpriv = filp->private_data;
poll_wait(filp, &mon_read_wait_queue, p);
if (unlikely(atomic_read(&monpriv->iucv_severed)))
return POLLERR;
if (atomic_read(&monpriv->read_ready))
return POLLIN | POLLRDNORM;
return 0;
}
static const struct file_operations mon_fops = {
.owner = THIS_MODULE,
.open = &mon_open,
.release = &mon_close,
.read = &mon_read,
.poll = &mon_poll,
.llseek = noop_llseek,
};
static struct miscdevice mon_dev = {
.name = "monreader",
.fops = &mon_fops,
.minor = MISC_DYNAMIC_MINOR,
};
/******************************************************************************
* suspend / resume *
*****************************************************************************/
static int monreader_freeze(struct device *dev)
{
struct mon_private *monpriv = dev_get_drvdata(dev);
int rc;
if (!monpriv)
return 0;
if (monpriv->path) {
rc = iucv_path_sever(monpriv->path, user_data_sever);
if (rc)
pr_warning("Disconnecting the z/VM *MONITOR system "
"service failed with rc=%i\n", rc);
iucv_path_free(monpriv->path);
}
atomic_set(&monpriv->iucv_severed, 0);
atomic_set(&monpriv->iucv_connected, 0);
atomic_set(&monpriv->read_ready, 0);
atomic_set(&monpriv->msglim_count, 0);
monpriv->write_index = 0;
monpriv->read_index = 0;
monpriv->path = NULL;
return 0;
}
static int monreader_thaw(struct device *dev)
{
struct mon_private *monpriv = dev_get_drvdata(dev);
int rc;
if (!monpriv)
return 0;
rc = -ENOMEM;
monpriv->path = iucv_path_alloc(MON_MSGLIM, IUCV_IPRMDATA, GFP_KERNEL);
if (!monpriv->path)
goto out;
rc = iucv_path_connect(monpriv->path, &monreader_iucv_handler,
MON_SERVICE, NULL, user_data_connect, monpriv);
if (rc) {
pr_err("Connecting to the z/VM *MONITOR system service "
"failed with rc=%i\n", rc);
goto out_path;
}
wait_event(mon_conn_wait_queue,
atomic_read(&monpriv->iucv_connected) ||
atomic_read(&monpriv->iucv_severed));
if (atomic_read(&monpriv->iucv_severed))
goto out_path;
return 0;
out_path:
rc = -EIO;
iucv_path_free(monpriv->path);
monpriv->path = NULL;
out:
atomic_set(&monpriv->iucv_severed, 1);
return rc;
}
static int monreader_restore(struct device *dev)
{
int rc;
segment_unload(mon_dcss_name);
rc = segment_load(mon_dcss_name, SEGMENT_SHARED,
&mon_dcss_start, &mon_dcss_end);
if (rc < 0) {
segment_warning(rc, mon_dcss_name);
panic("fatal monreader resume error: no monitor dcss\n");
}
return monreader_thaw(dev);
}
static const struct dev_pm_ops monreader_pm_ops = {
.freeze = monreader_freeze,
.thaw = monreader_thaw,
.restore = monreader_restore,
};
static struct device_driver monreader_driver = {
.name = "monreader",
.bus = &iucv_bus,
.pm = &monreader_pm_ops,
};
/******************************************************************************
* module init/exit *
*****************************************************************************/
static int __init mon_init(void)
{
int rc;
if (!MACHINE_IS_VM) {
pr_err("The z/VM *MONITOR record device driver cannot be "
"loaded without z/VM\n");
return -ENODEV;
}
/*
* Register with IUCV and connect to *MONITOR service
*/
rc = iucv_register(&monreader_iucv_handler, 1);
if (rc) {
pr_err("The z/VM *MONITOR record device driver failed to "
"register with IUCV\n");
return rc;
}
rc = driver_register(&monreader_driver);
if (rc)
goto out_iucv;
monreader_device = kzalloc(sizeof(struct device), GFP_KERNEL);
if (!monreader_device) {
rc = -ENOMEM;
goto out_driver;
}
dev_set_name(monreader_device, "monreader-dev");
monreader_device->bus = &iucv_bus;
monreader_device->parent = iucv_root;
monreader_device->driver = &monreader_driver;
monreader_device->release = (void (*)(struct device *))kfree;
rc = device_register(monreader_device);
if (rc) {
put_device(monreader_device);
goto out_driver;
}
rc = segment_type(mon_dcss_name);
if (rc < 0) {
segment_warning(rc, mon_dcss_name);
goto out_device;
}
if (rc != SEG_TYPE_SC) {
pr_err("The specified *MONITOR DCSS %s does not have the "
"required type SC\n", mon_dcss_name);
rc = -EINVAL;
goto out_device;
}
rc = segment_load(mon_dcss_name, SEGMENT_SHARED,
&mon_dcss_start, &mon_dcss_end);
if (rc < 0) {
segment_warning(rc, mon_dcss_name);
rc = -EINVAL;
goto out_device;
}
dcss_mkname(mon_dcss_name, &user_data_connect[8]);
/*
* misc_register() has to be the last action in module_init(), because
* file operations will be available right after this.
*/
rc = misc_register(&mon_dev);
if (rc < 0 )
goto out;
return 0;
out:
segment_unload(mon_dcss_name);
out_device:
device_unregister(monreader_device);
out_driver:
driver_unregister(&monreader_driver);
out_iucv:
iucv_unregister(&monreader_iucv_handler, 1);
return rc;
}
static void __exit mon_exit(void)
{
segment_unload(mon_dcss_name);
misc_deregister(&mon_dev);
device_unregister(monreader_device);
driver_unregister(&monreader_driver);
iucv_unregister(&monreader_iucv_handler, 1);
return;
}
module_init(mon_init);
module_exit(mon_exit);
module_param_string(mondcss, mon_dcss_name, 9, 0444);
MODULE_PARM_DESC(mondcss, "Name of DCSS segment to be used for *MONITOR "
"service, max. 8 chars. Default is MONDCSS");
MODULE_AUTHOR("Gerald Schaefer <geraldsc@de.ibm.com>");
MODULE_DESCRIPTION("Character device driver for reading z/VM "
"monitor service records.");
MODULE_LICENSE("GPL");
| gpl-2.0 |
5y/linux | kernel/groups.c | 455 | 6133 | /*
* Supplementary group IDs
*/
#include <linux/cred.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/user_namespace.h>
#include <asm/uaccess.h>
/* init to 2 - one for init_task, one to ensure it is never freed */
struct group_info init_groups = { .usage = ATOMIC_INIT(2) };
struct group_info *groups_alloc(int gidsetsize)
{
struct group_info *group_info;
int nblocks;
int i;
nblocks = (gidsetsize + NGROUPS_PER_BLOCK - 1) / NGROUPS_PER_BLOCK;
/* Make sure we always allocate at least one indirect block pointer */
nblocks = nblocks ? : 1;
group_info = kmalloc(sizeof(*group_info) + nblocks*sizeof(gid_t *), GFP_USER);
if (!group_info)
return NULL;
group_info->ngroups = gidsetsize;
group_info->nblocks = nblocks;
atomic_set(&group_info->usage, 1);
if (gidsetsize <= NGROUPS_SMALL)
group_info->blocks[0] = group_info->small_block;
else {
for (i = 0; i < nblocks; i++) {
kgid_t *b;
b = (void *)__get_free_page(GFP_USER);
if (!b)
goto out_undo_partial_alloc;
group_info->blocks[i] = b;
}
}
return group_info;
out_undo_partial_alloc:
while (--i >= 0) {
free_page((unsigned long)group_info->blocks[i]);
}
kfree(group_info);
return NULL;
}
EXPORT_SYMBOL(groups_alloc);
void groups_free(struct group_info *group_info)
{
if (group_info->blocks[0] != group_info->small_block) {
int i;
for (i = 0; i < group_info->nblocks; i++)
free_page((unsigned long)group_info->blocks[i]);
}
kfree(group_info);
}
EXPORT_SYMBOL(groups_free);
/* export the group_info to a user-space array */
static int groups_to_user(gid_t __user *grouplist,
const struct group_info *group_info)
{
struct user_namespace *user_ns = current_user_ns();
int i;
unsigned int count = group_info->ngroups;
for (i = 0; i < count; i++) {
gid_t gid;
gid = from_kgid_munged(user_ns, GROUP_AT(group_info, i));
if (put_user(gid, grouplist+i))
return -EFAULT;
}
return 0;
}
/* fill a group_info from a user-space array - it must be allocated already */
static int groups_from_user(struct group_info *group_info,
gid_t __user *grouplist)
{
struct user_namespace *user_ns = current_user_ns();
int i;
unsigned int count = group_info->ngroups;
for (i = 0; i < count; i++) {
gid_t gid;
kgid_t kgid;
if (get_user(gid, grouplist+i))
return -EFAULT;
kgid = make_kgid(user_ns, gid);
if (!gid_valid(kgid))
return -EINVAL;
GROUP_AT(group_info, i) = kgid;
}
return 0;
}
/* a simple Shell sort */
static void groups_sort(struct group_info *group_info)
{
int base, max, stride;
int gidsetsize = group_info->ngroups;
for (stride = 1; stride < gidsetsize; stride = 3 * stride + 1)
; /* nothing */
stride /= 3;
while (stride) {
max = gidsetsize - stride;
for (base = 0; base < max; base++) {
int left = base;
int right = left + stride;
kgid_t tmp = GROUP_AT(group_info, right);
while (left >= 0 && gid_gt(GROUP_AT(group_info, left), tmp)) {
GROUP_AT(group_info, right) =
GROUP_AT(group_info, left);
right = left;
left -= stride;
}
GROUP_AT(group_info, right) = tmp;
}
stride /= 3;
}
}
/* a simple bsearch */
int groups_search(const struct group_info *group_info, kgid_t grp)
{
unsigned int left, right;
if (!group_info)
return 0;
left = 0;
right = group_info->ngroups;
while (left < right) {
unsigned int mid = (left+right)/2;
if (gid_gt(grp, GROUP_AT(group_info, mid)))
left = mid + 1;
else if (gid_lt(grp, GROUP_AT(group_info, mid)))
right = mid;
else
return 1;
}
return 0;
}
/**
* set_groups - Change a group subscription in a set of credentials
* @new: The newly prepared set of credentials to alter
* @group_info: The group list to install
*/
void set_groups(struct cred *new, struct group_info *group_info)
{
put_group_info(new->group_info);
groups_sort(group_info);
get_group_info(group_info);
new->group_info = group_info;
}
EXPORT_SYMBOL(set_groups);
/**
* set_current_groups - Change current's group subscription
* @group_info: The group list to impose
*
* Validate a group subscription and, if valid, impose it upon current's task
* security record.
*/
int set_current_groups(struct group_info *group_info)
{
struct cred *new;
new = prepare_creds();
if (!new)
return -ENOMEM;
set_groups(new, group_info);
return commit_creds(new);
}
EXPORT_SYMBOL(set_current_groups);
SYSCALL_DEFINE2(getgroups, int, gidsetsize, gid_t __user *, grouplist)
{
const struct cred *cred = current_cred();
int i;
if (gidsetsize < 0)
return -EINVAL;
/* no need to grab task_lock here; it cannot change */
i = cred->group_info->ngroups;
if (gidsetsize) {
if (i > gidsetsize) {
i = -EINVAL;
goto out;
}
if (groups_to_user(grouplist, cred->group_info)) {
i = -EFAULT;
goto out;
}
}
out:
return i;
}
bool may_setgroups(void)
{
struct user_namespace *user_ns = current_user_ns();
return ns_capable(user_ns, CAP_SETGID) &&
userns_may_setgroups(user_ns);
}
/*
* SMP: Our groups are copy-on-write. We can set them safely
* without another task interfering.
*/
SYSCALL_DEFINE2(setgroups, int, gidsetsize, gid_t __user *, grouplist)
{
struct group_info *group_info;
int retval;
if (!may_setgroups())
return -EPERM;
if ((unsigned)gidsetsize > NGROUPS_MAX)
return -EINVAL;
group_info = groups_alloc(gidsetsize);
if (!group_info)
return -ENOMEM;
retval = groups_from_user(group_info, grouplist);
if (retval) {
put_group_info(group_info);
return retval;
}
retval = set_current_groups(group_info);
put_group_info(group_info);
return retval;
}
/*
* Check whether we're fsgid/egid or in the supplemental group..
*/
int in_group_p(kgid_t grp)
{
const struct cred *cred = current_cred();
int retval = 1;
if (!gid_eq(grp, cred->fsgid))
retval = groups_search(cred->group_info, grp);
return retval;
}
EXPORT_SYMBOL(in_group_p);
int in_egroup_p(kgid_t grp)
{
const struct cred *cred = current_cred();
int retval = 1;
if (!gid_eq(grp, cred->egid))
retval = groups_search(cred->group_info, grp);
return retval;
}
EXPORT_SYMBOL(in_egroup_p);
| gpl-2.0 |
SlimSaber/kernel_samsung_smdk4412 | drivers/edac/i7core_edac.c | 967 | 56410 | /* Intel i7 core/Nehalem Memory Controller kernel module
*
* This driver supports the memory controllers found on the Intel
* processor families i7core, i7core 7xx/8xx, i5core, Xeon 35xx,
* Xeon 55xx and Xeon 56xx also known as Nehalem, Nehalem-EP, Lynnfield
* and Westmere-EP.
*
* This file may be distributed under the terms of the
* GNU General Public License version 2 only.
*
* Copyright (c) 2009-2010 by:
* Mauro Carvalho Chehab <mchehab@redhat.com>
*
* Red Hat Inc. http://www.redhat.com
*
* Forked and adapted from the i5400_edac driver
*
* Based on the following public Intel datasheets:
* Intel Core i7 Processor Extreme Edition and Intel Core i7 Processor
* Datasheet, Volume 2:
* http://download.intel.com/design/processor/datashts/320835.pdf
* Intel Xeon Processor 5500 Series Datasheet Volume 2
* http://www.intel.com/Assets/PDF/datasheet/321322.pdf
* also available at:
* http://www.arrownac.com/manufacturers/intel/s/nehalem/5500-datasheet-v2.pdf
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/edac.h>
#include <linux/mmzone.h>
#include <linux/edac_mce.h>
#include <linux/smp.h>
#include <asm/processor.h>
#include "edac_core.h"
/* Static vars */
static LIST_HEAD(i7core_edac_list);
static DEFINE_MUTEX(i7core_edac_lock);
static int probed;
static int use_pci_fixup;
module_param(use_pci_fixup, int, 0444);
MODULE_PARM_DESC(use_pci_fixup, "Enable PCI fixup to seek for hidden devices");
/*
* This is used for Nehalem-EP and Nehalem-EX devices, where the non-core
* registers start at bus 255, and are not reported by BIOS.
* We currently find devices with only 2 sockets. In order to support more QPI
* Quick Path Interconnect, just increment this number.
*/
#define MAX_SOCKET_BUSES 2
/*
* Alter this version for the module when modifications are made
*/
#define I7CORE_REVISION " Ver: 1.0.0"
#define EDAC_MOD_STR "i7core_edac"
/*
* Debug macros
*/
#define i7core_printk(level, fmt, arg...) \
edac_printk(level, "i7core", fmt, ##arg)
#define i7core_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "i7core", fmt, ##arg)
/*
* i7core Memory Controller Registers
*/
/* OFFSETS for Device 0 Function 0 */
#define MC_CFG_CONTROL 0x90
/* OFFSETS for Device 3 Function 0 */
#define MC_CONTROL 0x48
#define MC_STATUS 0x4c
#define MC_MAX_DOD 0x64
/*
* OFFSETS for Device 3 Function 4, as inicated on Xeon 5500 datasheet:
* http://www.arrownac.com/manufacturers/intel/s/nehalem/5500-datasheet-v2.pdf
*/
#define MC_TEST_ERR_RCV1 0x60
#define DIMM2_COR_ERR(r) ((r) & 0x7fff)
#define MC_TEST_ERR_RCV0 0x64
#define DIMM1_COR_ERR(r) (((r) >> 16) & 0x7fff)
#define DIMM0_COR_ERR(r) ((r) & 0x7fff)
/* OFFSETS for Device 3 Function 2, as inicated on Xeon 5500 datasheet */
#define MC_COR_ECC_CNT_0 0x80
#define MC_COR_ECC_CNT_1 0x84
#define MC_COR_ECC_CNT_2 0x88
#define MC_COR_ECC_CNT_3 0x8c
#define MC_COR_ECC_CNT_4 0x90
#define MC_COR_ECC_CNT_5 0x94
#define DIMM_TOP_COR_ERR(r) (((r) >> 16) & 0x7fff)
#define DIMM_BOT_COR_ERR(r) ((r) & 0x7fff)
/* OFFSETS for Devices 4,5 and 6 Function 0 */
#define MC_CHANNEL_DIMM_INIT_PARAMS 0x58
#define THREE_DIMMS_PRESENT (1 << 24)
#define SINGLE_QUAD_RANK_PRESENT (1 << 23)
#define QUAD_RANK_PRESENT (1 << 22)
#define REGISTERED_DIMM (1 << 15)
#define MC_CHANNEL_MAPPER 0x60
#define RDLCH(r, ch) ((((r) >> (3 + (ch * 6))) & 0x07) - 1)
#define WRLCH(r, ch) ((((r) >> (ch * 6)) & 0x07) - 1)
#define MC_CHANNEL_RANK_PRESENT 0x7c
#define RANK_PRESENT_MASK 0xffff
#define MC_CHANNEL_ADDR_MATCH 0xf0
#define MC_CHANNEL_ERROR_MASK 0xf8
#define MC_CHANNEL_ERROR_INJECT 0xfc
#define INJECT_ADDR_PARITY 0x10
#define INJECT_ECC 0x08
#define MASK_CACHELINE 0x06
#define MASK_FULL_CACHELINE 0x06
#define MASK_MSB32_CACHELINE 0x04
#define MASK_LSB32_CACHELINE 0x02
#define NO_MASK_CACHELINE 0x00
#define REPEAT_EN 0x01
/* OFFSETS for Devices 4,5 and 6 Function 1 */
#define MC_DOD_CH_DIMM0 0x48
#define MC_DOD_CH_DIMM1 0x4c
#define MC_DOD_CH_DIMM2 0x50
#define RANKOFFSET_MASK ((1 << 12) | (1 << 11) | (1 << 10))
#define RANKOFFSET(x) ((x & RANKOFFSET_MASK) >> 10)
#define DIMM_PRESENT_MASK (1 << 9)
#define DIMM_PRESENT(x) (((x) & DIMM_PRESENT_MASK) >> 9)
#define MC_DOD_NUMBANK_MASK ((1 << 8) | (1 << 7))
#define MC_DOD_NUMBANK(x) (((x) & MC_DOD_NUMBANK_MASK) >> 7)
#define MC_DOD_NUMRANK_MASK ((1 << 6) | (1 << 5))
#define MC_DOD_NUMRANK(x) (((x) & MC_DOD_NUMRANK_MASK) >> 5)
#define MC_DOD_NUMROW_MASK ((1 << 4) | (1 << 3) | (1 << 2))
#define MC_DOD_NUMROW(x) (((x) & MC_DOD_NUMROW_MASK) >> 2)
#define MC_DOD_NUMCOL_MASK 3
#define MC_DOD_NUMCOL(x) ((x) & MC_DOD_NUMCOL_MASK)
#define MC_RANK_PRESENT 0x7c
#define MC_SAG_CH_0 0x80
#define MC_SAG_CH_1 0x84
#define MC_SAG_CH_2 0x88
#define MC_SAG_CH_3 0x8c
#define MC_SAG_CH_4 0x90
#define MC_SAG_CH_5 0x94
#define MC_SAG_CH_6 0x98
#define MC_SAG_CH_7 0x9c
#define MC_RIR_LIMIT_CH_0 0x40
#define MC_RIR_LIMIT_CH_1 0x44
#define MC_RIR_LIMIT_CH_2 0x48
#define MC_RIR_LIMIT_CH_3 0x4C
#define MC_RIR_LIMIT_CH_4 0x50
#define MC_RIR_LIMIT_CH_5 0x54
#define MC_RIR_LIMIT_CH_6 0x58
#define MC_RIR_LIMIT_CH_7 0x5C
#define MC_RIR_LIMIT_MASK ((1 << 10) - 1)
#define MC_RIR_WAY_CH 0x80
#define MC_RIR_WAY_OFFSET_MASK (((1 << 14) - 1) & ~0x7)
#define MC_RIR_WAY_RANK_MASK 0x7
/*
* i7core structs
*/
#define NUM_CHANS 3
#define MAX_DIMMS 3 /* Max DIMMS per channel */
#define MAX_MCR_FUNC 4
#define MAX_CHAN_FUNC 3
struct i7core_info {
u32 mc_control;
u32 mc_status;
u32 max_dod;
u32 ch_map;
};
struct i7core_inject {
int enable;
u32 section;
u32 type;
u32 eccmask;
/* Error address mask */
int channel, dimm, rank, bank, page, col;
};
struct i7core_channel {
u32 ranks;
u32 dimms;
};
struct pci_id_descr {
int dev;
int func;
int dev_id;
int optional;
};
struct pci_id_table {
const struct pci_id_descr *descr;
int n_devs;
};
struct i7core_dev {
struct list_head list;
u8 socket;
struct pci_dev **pdev;
int n_devs;
struct mem_ctl_info *mci;
};
struct i7core_pvt {
struct pci_dev *pci_noncore;
struct pci_dev *pci_mcr[MAX_MCR_FUNC + 1];
struct pci_dev *pci_ch[NUM_CHANS][MAX_CHAN_FUNC + 1];
struct i7core_dev *i7core_dev;
struct i7core_info info;
struct i7core_inject inject;
struct i7core_channel channel[NUM_CHANS];
int ce_count_available;
int csrow_map[NUM_CHANS][MAX_DIMMS];
/* ECC corrected errors counts per udimm */
unsigned long udimm_ce_count[MAX_DIMMS];
int udimm_last_ce_count[MAX_DIMMS];
/* ECC corrected errors counts per rdimm */
unsigned long rdimm_ce_count[NUM_CHANS][MAX_DIMMS];
int rdimm_last_ce_count[NUM_CHANS][MAX_DIMMS];
unsigned int is_registered;
/* mcelog glue */
struct edac_mce edac_mce;
/* Fifo double buffers */
struct mce mce_entry[MCE_LOG_LEN];
struct mce mce_outentry[MCE_LOG_LEN];
/* Fifo in/out counters */
unsigned mce_in, mce_out;
/* Count indicator to show errors not got */
unsigned mce_overrun;
/* Struct to control EDAC polling */
struct edac_pci_ctl_info *i7core_pci;
};
#define PCI_DESCR(device, function, device_id) \
.dev = (device), \
.func = (function), \
.dev_id = (device_id)
static const struct pci_id_descr pci_dev_descr_i7core_nehalem[] = {
/* Memory controller */
{ PCI_DESCR(3, 0, PCI_DEVICE_ID_INTEL_I7_MCR) },
{ PCI_DESCR(3, 1, PCI_DEVICE_ID_INTEL_I7_MC_TAD) },
/* Exists only for RDIMM */
{ PCI_DESCR(3, 2, PCI_DEVICE_ID_INTEL_I7_MC_RAS), .optional = 1 },
{ PCI_DESCR(3, 4, PCI_DEVICE_ID_INTEL_I7_MC_TEST) },
/* Channel 0 */
{ PCI_DESCR(4, 0, PCI_DEVICE_ID_INTEL_I7_MC_CH0_CTRL) },
{ PCI_DESCR(4, 1, PCI_DEVICE_ID_INTEL_I7_MC_CH0_ADDR) },
{ PCI_DESCR(4, 2, PCI_DEVICE_ID_INTEL_I7_MC_CH0_RANK) },
{ PCI_DESCR(4, 3, PCI_DEVICE_ID_INTEL_I7_MC_CH0_TC) },
/* Channel 1 */
{ PCI_DESCR(5, 0, PCI_DEVICE_ID_INTEL_I7_MC_CH1_CTRL) },
{ PCI_DESCR(5, 1, PCI_DEVICE_ID_INTEL_I7_MC_CH1_ADDR) },
{ PCI_DESCR(5, 2, PCI_DEVICE_ID_INTEL_I7_MC_CH1_RANK) },
{ PCI_DESCR(5, 3, PCI_DEVICE_ID_INTEL_I7_MC_CH1_TC) },
/* Channel 2 */
{ PCI_DESCR(6, 0, PCI_DEVICE_ID_INTEL_I7_MC_CH2_CTRL) },
{ PCI_DESCR(6, 1, PCI_DEVICE_ID_INTEL_I7_MC_CH2_ADDR) },
{ PCI_DESCR(6, 2, PCI_DEVICE_ID_INTEL_I7_MC_CH2_RANK) },
{ PCI_DESCR(6, 3, PCI_DEVICE_ID_INTEL_I7_MC_CH2_TC) },
};
static const struct pci_id_descr pci_dev_descr_lynnfield[] = {
{ PCI_DESCR( 3, 0, PCI_DEVICE_ID_INTEL_LYNNFIELD_MCR) },
{ PCI_DESCR( 3, 1, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_TAD) },
{ PCI_DESCR( 3, 4, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_TEST) },
{ PCI_DESCR( 4, 0, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH0_CTRL) },
{ PCI_DESCR( 4, 1, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH0_ADDR) },
{ PCI_DESCR( 4, 2, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH0_RANK) },
{ PCI_DESCR( 4, 3, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH0_TC) },
{ PCI_DESCR( 5, 0, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH1_CTRL) },
{ PCI_DESCR( 5, 1, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH1_ADDR) },
{ PCI_DESCR( 5, 2, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH1_RANK) },
{ PCI_DESCR( 5, 3, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH1_TC) },
};
static const struct pci_id_descr pci_dev_descr_i7core_westmere[] = {
/* Memory controller */
{ PCI_DESCR(3, 0, PCI_DEVICE_ID_INTEL_LYNNFIELD_MCR_REV2) },
{ PCI_DESCR(3, 1, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_TAD_REV2) },
/* Exists only for RDIMM */
{ PCI_DESCR(3, 2, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_RAS_REV2), .optional = 1 },
{ PCI_DESCR(3, 4, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_TEST_REV2) },
/* Channel 0 */
{ PCI_DESCR(4, 0, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH0_CTRL_REV2) },
{ PCI_DESCR(4, 1, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH0_ADDR_REV2) },
{ PCI_DESCR(4, 2, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH0_RANK_REV2) },
{ PCI_DESCR(4, 3, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH0_TC_REV2) },
/* Channel 1 */
{ PCI_DESCR(5, 0, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH1_CTRL_REV2) },
{ PCI_DESCR(5, 1, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH1_ADDR_REV2) },
{ PCI_DESCR(5, 2, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH1_RANK_REV2) },
{ PCI_DESCR(5, 3, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH1_TC_REV2) },
/* Channel 2 */
{ PCI_DESCR(6, 0, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH2_CTRL_REV2) },
{ PCI_DESCR(6, 1, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH2_ADDR_REV2) },
{ PCI_DESCR(6, 2, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH2_RANK_REV2) },
{ PCI_DESCR(6, 3, PCI_DEVICE_ID_INTEL_LYNNFIELD_MC_CH2_TC_REV2) },
};
#define PCI_ID_TABLE_ENTRY(A) { .descr=A, .n_devs = ARRAY_SIZE(A) }
static const struct pci_id_table pci_dev_table[] = {
PCI_ID_TABLE_ENTRY(pci_dev_descr_i7core_nehalem),
PCI_ID_TABLE_ENTRY(pci_dev_descr_lynnfield),
PCI_ID_TABLE_ENTRY(pci_dev_descr_i7core_westmere),
{0,} /* 0 terminated list. */
};
/*
* pci_device_id table for which devices we are looking for
*/
static const struct pci_device_id i7core_pci_tbl[] __devinitdata = {
{PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_X58_HUB_MGMT)},
{PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_LYNNFIELD_QPI_LINK0)},
{0,} /* 0 terminated list. */
};
/****************************************************************************
Anciliary status routines
****************************************************************************/
/* MC_CONTROL bits */
#define CH_ACTIVE(pvt, ch) ((pvt)->info.mc_control & (1 << (8 + ch)))
#define ECCx8(pvt) ((pvt)->info.mc_control & (1 << 1))
/* MC_STATUS bits */
#define ECC_ENABLED(pvt) ((pvt)->info.mc_status & (1 << 4))
#define CH_DISABLED(pvt, ch) ((pvt)->info.mc_status & (1 << ch))
/* MC_MAX_DOD read functions */
static inline int numdimms(u32 dimms)
{
return (dimms & 0x3) + 1;
}
static inline int numrank(u32 rank)
{
static int ranks[4] = { 1, 2, 4, -EINVAL };
return ranks[rank & 0x3];
}
static inline int numbank(u32 bank)
{
static int banks[4] = { 4, 8, 16, -EINVAL };
return banks[bank & 0x3];
}
static inline int numrow(u32 row)
{
static int rows[8] = {
1 << 12, 1 << 13, 1 << 14, 1 << 15,
1 << 16, -EINVAL, -EINVAL, -EINVAL,
};
return rows[row & 0x7];
}
static inline int numcol(u32 col)
{
static int cols[8] = {
1 << 10, 1 << 11, 1 << 12, -EINVAL,
};
return cols[col & 0x3];
}
static struct i7core_dev *get_i7core_dev(u8 socket)
{
struct i7core_dev *i7core_dev;
list_for_each_entry(i7core_dev, &i7core_edac_list, list) {
if (i7core_dev->socket == socket)
return i7core_dev;
}
return NULL;
}
static struct i7core_dev *alloc_i7core_dev(u8 socket,
const struct pci_id_table *table)
{
struct i7core_dev *i7core_dev;
i7core_dev = kzalloc(sizeof(*i7core_dev), GFP_KERNEL);
if (!i7core_dev)
return NULL;
i7core_dev->pdev = kzalloc(sizeof(*i7core_dev->pdev) * table->n_devs,
GFP_KERNEL);
if (!i7core_dev->pdev) {
kfree(i7core_dev);
return NULL;
}
i7core_dev->socket = socket;
i7core_dev->n_devs = table->n_devs;
list_add_tail(&i7core_dev->list, &i7core_edac_list);
return i7core_dev;
}
static void free_i7core_dev(struct i7core_dev *i7core_dev)
{
list_del(&i7core_dev->list);
kfree(i7core_dev->pdev);
kfree(i7core_dev);
}
/****************************************************************************
Memory check routines
****************************************************************************/
static struct pci_dev *get_pdev_slot_func(u8 socket, unsigned slot,
unsigned func)
{
struct i7core_dev *i7core_dev = get_i7core_dev(socket);
int i;
if (!i7core_dev)
return NULL;
for (i = 0; i < i7core_dev->n_devs; i++) {
if (!i7core_dev->pdev[i])
continue;
if (PCI_SLOT(i7core_dev->pdev[i]->devfn) == slot &&
PCI_FUNC(i7core_dev->pdev[i]->devfn) == func) {
return i7core_dev->pdev[i];
}
}
return NULL;
}
/**
* i7core_get_active_channels() - gets the number of channels and csrows
* @socket: Quick Path Interconnect socket
* @channels: Number of channels that will be returned
* @csrows: Number of csrows found
*
* Since EDAC core needs to know in advance the number of available channels
* and csrows, in order to allocate memory for csrows/channels, it is needed
* to run two similar steps. At the first step, implemented on this function,
* it checks the number of csrows/channels present at one socket.
* this is used in order to properly allocate the size of mci components.
*
* It should be noticed that none of the current available datasheets explain
* or even mention how csrows are seen by the memory controller. So, we need
* to add a fake description for csrows.
* So, this driver is attributing one DIMM memory for one csrow.
*/
static int i7core_get_active_channels(const u8 socket, unsigned *channels,
unsigned *csrows)
{
struct pci_dev *pdev = NULL;
int i, j;
u32 status, control;
*channels = 0;
*csrows = 0;
pdev = get_pdev_slot_func(socket, 3, 0);
if (!pdev) {
i7core_printk(KERN_ERR, "Couldn't find socket %d fn 3.0!!!\n",
socket);
return -ENODEV;
}
/* Device 3 function 0 reads */
pci_read_config_dword(pdev, MC_STATUS, &status);
pci_read_config_dword(pdev, MC_CONTROL, &control);
for (i = 0; i < NUM_CHANS; i++) {
u32 dimm_dod[3];
/* Check if the channel is active */
if (!(control & (1 << (8 + i))))
continue;
/* Check if the channel is disabled */
if (status & (1 << i))
continue;
pdev = get_pdev_slot_func(socket, i + 4, 1);
if (!pdev) {
i7core_printk(KERN_ERR, "Couldn't find socket %d "
"fn %d.%d!!!\n",
socket, i + 4, 1);
return -ENODEV;
}
/* Devices 4-6 function 1 */
pci_read_config_dword(pdev,
MC_DOD_CH_DIMM0, &dimm_dod[0]);
pci_read_config_dword(pdev,
MC_DOD_CH_DIMM1, &dimm_dod[1]);
pci_read_config_dword(pdev,
MC_DOD_CH_DIMM2, &dimm_dod[2]);
(*channels)++;
for (j = 0; j < 3; j++) {
if (!DIMM_PRESENT(dimm_dod[j]))
continue;
(*csrows)++;
}
}
debugf0("Number of active channels on socket %d: %d\n",
socket, *channels);
return 0;
}
static int get_dimm_config(const struct mem_ctl_info *mci)
{
struct i7core_pvt *pvt = mci->pvt_info;
struct csrow_info *csr;
struct pci_dev *pdev;
int i, j;
int csrow = 0;
unsigned long last_page = 0;
enum edac_type mode;
enum mem_type mtype;
/* Get data from the MC register, function 0 */
pdev = pvt->pci_mcr[0];
if (!pdev)
return -ENODEV;
/* Device 3 function 0 reads */
pci_read_config_dword(pdev, MC_CONTROL, &pvt->info.mc_control);
pci_read_config_dword(pdev, MC_STATUS, &pvt->info.mc_status);
pci_read_config_dword(pdev, MC_MAX_DOD, &pvt->info.max_dod);
pci_read_config_dword(pdev, MC_CHANNEL_MAPPER, &pvt->info.ch_map);
debugf0("QPI %d control=0x%08x status=0x%08x dod=0x%08x map=0x%08x\n",
pvt->i7core_dev->socket, pvt->info.mc_control, pvt->info.mc_status,
pvt->info.max_dod, pvt->info.ch_map);
if (ECC_ENABLED(pvt)) {
debugf0("ECC enabled with x%d SDCC\n", ECCx8(pvt) ? 8 : 4);
if (ECCx8(pvt))
mode = EDAC_S8ECD8ED;
else
mode = EDAC_S4ECD4ED;
} else {
debugf0("ECC disabled\n");
mode = EDAC_NONE;
}
/* FIXME: need to handle the error codes */
debugf0("DOD Max limits: DIMMS: %d, %d-ranked, %d-banked "
"x%x x 0x%x\n",
numdimms(pvt->info.max_dod),
numrank(pvt->info.max_dod >> 2),
numbank(pvt->info.max_dod >> 4),
numrow(pvt->info.max_dod >> 6),
numcol(pvt->info.max_dod >> 9));
for (i = 0; i < NUM_CHANS; i++) {
u32 data, dimm_dod[3], value[8];
if (!pvt->pci_ch[i][0])
continue;
if (!CH_ACTIVE(pvt, i)) {
debugf0("Channel %i is not active\n", i);
continue;
}
if (CH_DISABLED(pvt, i)) {
debugf0("Channel %i is disabled\n", i);
continue;
}
/* Devices 4-6 function 0 */
pci_read_config_dword(pvt->pci_ch[i][0],
MC_CHANNEL_DIMM_INIT_PARAMS, &data);
pvt->channel[i].ranks = (data & QUAD_RANK_PRESENT) ?
4 : 2;
if (data & REGISTERED_DIMM)
mtype = MEM_RDDR3;
else
mtype = MEM_DDR3;
#if 0
if (data & THREE_DIMMS_PRESENT)
pvt->channel[i].dimms = 3;
else if (data & SINGLE_QUAD_RANK_PRESENT)
pvt->channel[i].dimms = 1;
else
pvt->channel[i].dimms = 2;
#endif
/* Devices 4-6 function 1 */
pci_read_config_dword(pvt->pci_ch[i][1],
MC_DOD_CH_DIMM0, &dimm_dod[0]);
pci_read_config_dword(pvt->pci_ch[i][1],
MC_DOD_CH_DIMM1, &dimm_dod[1]);
pci_read_config_dword(pvt->pci_ch[i][1],
MC_DOD_CH_DIMM2, &dimm_dod[2]);
debugf0("Ch%d phy rd%d, wr%d (0x%08x): "
"%d ranks, %cDIMMs\n",
i,
RDLCH(pvt->info.ch_map, i), WRLCH(pvt->info.ch_map, i),
data,
pvt->channel[i].ranks,
(data & REGISTERED_DIMM) ? 'R' : 'U');
for (j = 0; j < 3; j++) {
u32 banks, ranks, rows, cols;
u32 size, npages;
if (!DIMM_PRESENT(dimm_dod[j]))
continue;
banks = numbank(MC_DOD_NUMBANK(dimm_dod[j]));
ranks = numrank(MC_DOD_NUMRANK(dimm_dod[j]));
rows = numrow(MC_DOD_NUMROW(dimm_dod[j]));
cols = numcol(MC_DOD_NUMCOL(dimm_dod[j]));
/* DDR3 has 8 I/O banks */
size = (rows * cols * banks * ranks) >> (20 - 3);
pvt->channel[i].dimms++;
debugf0("\tdimm %d %d Mb offset: %x, "
"bank: %d, rank: %d, row: %#x, col: %#x\n",
j, size,
RANKOFFSET(dimm_dod[j]),
banks, ranks, rows, cols);
npages = MiB_TO_PAGES(size);
csr = &mci->csrows[csrow];
csr->first_page = last_page + 1;
last_page += npages;
csr->last_page = last_page;
csr->nr_pages = npages;
csr->page_mask = 0;
csr->grain = 8;
csr->csrow_idx = csrow;
csr->nr_channels = 1;
csr->channels[0].chan_idx = i;
csr->channels[0].ce_count = 0;
pvt->csrow_map[i][j] = csrow;
switch (banks) {
case 4:
csr->dtype = DEV_X4;
break;
case 8:
csr->dtype = DEV_X8;
break;
case 16:
csr->dtype = DEV_X16;
break;
default:
csr->dtype = DEV_UNKNOWN;
}
csr->edac_mode = mode;
csr->mtype = mtype;
csrow++;
}
pci_read_config_dword(pdev, MC_SAG_CH_0, &value[0]);
pci_read_config_dword(pdev, MC_SAG_CH_1, &value[1]);
pci_read_config_dword(pdev, MC_SAG_CH_2, &value[2]);
pci_read_config_dword(pdev, MC_SAG_CH_3, &value[3]);
pci_read_config_dword(pdev, MC_SAG_CH_4, &value[4]);
pci_read_config_dword(pdev, MC_SAG_CH_5, &value[5]);
pci_read_config_dword(pdev, MC_SAG_CH_6, &value[6]);
pci_read_config_dword(pdev, MC_SAG_CH_7, &value[7]);
debugf1("\t[%i] DIVBY3\tREMOVED\tOFFSET\n", i);
for (j = 0; j < 8; j++)
debugf1("\t\t%#x\t%#x\t%#x\n",
(value[j] >> 27) & 0x1,
(value[j] >> 24) & 0x7,
(value[j] && ((1 << 24) - 1)));
}
return 0;
}
/****************************************************************************
Error insertion routines
****************************************************************************/
/* The i7core has independent error injection features per channel.
However, to have a simpler code, we don't allow enabling error injection
on more than one channel.
Also, since a change at an inject parameter will be applied only at enable,
we're disabling error injection on all write calls to the sysfs nodes that
controls the error code injection.
*/
static int disable_inject(const struct mem_ctl_info *mci)
{
struct i7core_pvt *pvt = mci->pvt_info;
pvt->inject.enable = 0;
if (!pvt->pci_ch[pvt->inject.channel][0])
return -ENODEV;
pci_write_config_dword(pvt->pci_ch[pvt->inject.channel][0],
MC_CHANNEL_ERROR_INJECT, 0);
return 0;
}
/*
* i7core inject inject.section
*
* accept and store error injection inject.section value
* bit 0 - refers to the lower 32-byte half cacheline
* bit 1 - refers to the upper 32-byte half cacheline
*/
static ssize_t i7core_inject_section_store(struct mem_ctl_info *mci,
const char *data, size_t count)
{
struct i7core_pvt *pvt = mci->pvt_info;
unsigned long value;
int rc;
if (pvt->inject.enable)
disable_inject(mci);
rc = strict_strtoul(data, 10, &value);
if ((rc < 0) || (value > 3))
return -EIO;
pvt->inject.section = (u32) value;
return count;
}
static ssize_t i7core_inject_section_show(struct mem_ctl_info *mci,
char *data)
{
struct i7core_pvt *pvt = mci->pvt_info;
return sprintf(data, "0x%08x\n", pvt->inject.section);
}
/*
* i7core inject.type
*
* accept and store error injection inject.section value
* bit 0 - repeat enable - Enable error repetition
* bit 1 - inject ECC error
* bit 2 - inject parity error
*/
static ssize_t i7core_inject_type_store(struct mem_ctl_info *mci,
const char *data, size_t count)
{
struct i7core_pvt *pvt = mci->pvt_info;
unsigned long value;
int rc;
if (pvt->inject.enable)
disable_inject(mci);
rc = strict_strtoul(data, 10, &value);
if ((rc < 0) || (value > 7))
return -EIO;
pvt->inject.type = (u32) value;
return count;
}
static ssize_t i7core_inject_type_show(struct mem_ctl_info *mci,
char *data)
{
struct i7core_pvt *pvt = mci->pvt_info;
return sprintf(data, "0x%08x\n", pvt->inject.type);
}
/*
* i7core_inject_inject.eccmask_store
*
* The type of error (UE/CE) will depend on the inject.eccmask value:
* Any bits set to a 1 will flip the corresponding ECC bit
* Correctable errors can be injected by flipping 1 bit or the bits within
* a symbol pair (2 consecutive aligned 8-bit pairs - i.e. 7:0 and 15:8 or
* 23:16 and 31:24). Flipping bits in two symbol pairs will cause an
* uncorrectable error to be injected.
*/
static ssize_t i7core_inject_eccmask_store(struct mem_ctl_info *mci,
const char *data, size_t count)
{
struct i7core_pvt *pvt = mci->pvt_info;
unsigned long value;
int rc;
if (pvt->inject.enable)
disable_inject(mci);
rc = strict_strtoul(data, 10, &value);
if (rc < 0)
return -EIO;
pvt->inject.eccmask = (u32) value;
return count;
}
static ssize_t i7core_inject_eccmask_show(struct mem_ctl_info *mci,
char *data)
{
struct i7core_pvt *pvt = mci->pvt_info;
return sprintf(data, "0x%08x\n", pvt->inject.eccmask);
}
/*
* i7core_addrmatch
*
* The type of error (UE/CE) will depend on the inject.eccmask value:
* Any bits set to a 1 will flip the corresponding ECC bit
* Correctable errors can be injected by flipping 1 bit or the bits within
* a symbol pair (2 consecutive aligned 8-bit pairs - i.e. 7:0 and 15:8 or
* 23:16 and 31:24). Flipping bits in two symbol pairs will cause an
* uncorrectable error to be injected.
*/
#define DECLARE_ADDR_MATCH(param, limit) \
static ssize_t i7core_inject_store_##param( \
struct mem_ctl_info *mci, \
const char *data, size_t count) \
{ \
struct i7core_pvt *pvt; \
long value; \
int rc; \
\
debugf1("%s()\n", __func__); \
pvt = mci->pvt_info; \
\
if (pvt->inject.enable) \
disable_inject(mci); \
\
if (!strcasecmp(data, "any") || !strcasecmp(data, "any\n"))\
value = -1; \
else { \
rc = strict_strtoul(data, 10, &value); \
if ((rc < 0) || (value >= limit)) \
return -EIO; \
} \
\
pvt->inject.param = value; \
\
return count; \
} \
\
static ssize_t i7core_inject_show_##param( \
struct mem_ctl_info *mci, \
char *data) \
{ \
struct i7core_pvt *pvt; \
\
pvt = mci->pvt_info; \
debugf1("%s() pvt=%p\n", __func__, pvt); \
if (pvt->inject.param < 0) \
return sprintf(data, "any\n"); \
else \
return sprintf(data, "%d\n", pvt->inject.param);\
}
#define ATTR_ADDR_MATCH(param) \
{ \
.attr = { \
.name = #param, \
.mode = (S_IRUGO | S_IWUSR) \
}, \
.show = i7core_inject_show_##param, \
.store = i7core_inject_store_##param, \
}
DECLARE_ADDR_MATCH(channel, 3);
DECLARE_ADDR_MATCH(dimm, 3);
DECLARE_ADDR_MATCH(rank, 4);
DECLARE_ADDR_MATCH(bank, 32);
DECLARE_ADDR_MATCH(page, 0x10000);
DECLARE_ADDR_MATCH(col, 0x4000);
static int write_and_test(struct pci_dev *dev, const int where, const u32 val)
{
u32 read;
int count;
debugf0("setting pci %02x:%02x.%x reg=%02x value=%08x\n",
dev->bus->number, PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
where, val);
for (count = 0; count < 10; count++) {
if (count)
msleep(100);
pci_write_config_dword(dev, where, val);
pci_read_config_dword(dev, where, &read);
if (read == val)
return 0;
}
i7core_printk(KERN_ERR, "Error during set pci %02x:%02x.%x reg=%02x "
"write=%08x. Read=%08x\n",
dev->bus->number, PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
where, val, read);
return -EINVAL;
}
/*
* This routine prepares the Memory Controller for error injection.
* The error will be injected when some process tries to write to the
* memory that matches the given criteria.
* The criteria can be set in terms of a mask where dimm, rank, bank, page
* and col can be specified.
* A -1 value for any of the mask items will make the MCU to ignore
* that matching criteria for error injection.
*
* It should be noticed that the error will only happen after a write operation
* on a memory that matches the condition. if REPEAT_EN is not enabled at
* inject mask, then it will produce just one error. Otherwise, it will repeat
* until the injectmask would be cleaned.
*
* FIXME: This routine assumes that MAXNUMDIMMS value of MC_MAX_DOD
* is reliable enough to check if the MC is using the
* three channels. However, this is not clear at the datasheet.
*/
static ssize_t i7core_inject_enable_store(struct mem_ctl_info *mci,
const char *data, size_t count)
{
struct i7core_pvt *pvt = mci->pvt_info;
u32 injectmask;
u64 mask = 0;
int rc;
long enable;
if (!pvt->pci_ch[pvt->inject.channel][0])
return 0;
rc = strict_strtoul(data, 10, &enable);
if ((rc < 0))
return 0;
if (enable) {
pvt->inject.enable = 1;
} else {
disable_inject(mci);
return count;
}
/* Sets pvt->inject.dimm mask */
if (pvt->inject.dimm < 0)
mask |= 1LL << 41;
else {
if (pvt->channel[pvt->inject.channel].dimms > 2)
mask |= (pvt->inject.dimm & 0x3LL) << 35;
else
mask |= (pvt->inject.dimm & 0x1LL) << 36;
}
/* Sets pvt->inject.rank mask */
if (pvt->inject.rank < 0)
mask |= 1LL << 40;
else {
if (pvt->channel[pvt->inject.channel].dimms > 2)
mask |= (pvt->inject.rank & 0x1LL) << 34;
else
mask |= (pvt->inject.rank & 0x3LL) << 34;
}
/* Sets pvt->inject.bank mask */
if (pvt->inject.bank < 0)
mask |= 1LL << 39;
else
mask |= (pvt->inject.bank & 0x15LL) << 30;
/* Sets pvt->inject.page mask */
if (pvt->inject.page < 0)
mask |= 1LL << 38;
else
mask |= (pvt->inject.page & 0xffff) << 14;
/* Sets pvt->inject.column mask */
if (pvt->inject.col < 0)
mask |= 1LL << 37;
else
mask |= (pvt->inject.col & 0x3fff);
/*
* bit 0: REPEAT_EN
* bits 1-2: MASK_HALF_CACHELINE
* bit 3: INJECT_ECC
* bit 4: INJECT_ADDR_PARITY
*/
injectmask = (pvt->inject.type & 1) |
(pvt->inject.section & 0x3) << 1 |
(pvt->inject.type & 0x6) << (3 - 1);
/* Unlock writes to registers - this register is write only */
pci_write_config_dword(pvt->pci_noncore,
MC_CFG_CONTROL, 0x2);
write_and_test(pvt->pci_ch[pvt->inject.channel][0],
MC_CHANNEL_ADDR_MATCH, mask);
write_and_test(pvt->pci_ch[pvt->inject.channel][0],
MC_CHANNEL_ADDR_MATCH + 4, mask >> 32L);
write_and_test(pvt->pci_ch[pvt->inject.channel][0],
MC_CHANNEL_ERROR_MASK, pvt->inject.eccmask);
write_and_test(pvt->pci_ch[pvt->inject.channel][0],
MC_CHANNEL_ERROR_INJECT, injectmask);
/*
* This is something undocumented, based on my tests
* Without writing 8 to this register, errors aren't injected. Not sure
* why.
*/
pci_write_config_dword(pvt->pci_noncore,
MC_CFG_CONTROL, 8);
debugf0("Error inject addr match 0x%016llx, ecc 0x%08x,"
" inject 0x%08x\n",
mask, pvt->inject.eccmask, injectmask);
return count;
}
static ssize_t i7core_inject_enable_show(struct mem_ctl_info *mci,
char *data)
{
struct i7core_pvt *pvt = mci->pvt_info;
u32 injectmask;
if (!pvt->pci_ch[pvt->inject.channel][0])
return 0;
pci_read_config_dword(pvt->pci_ch[pvt->inject.channel][0],
MC_CHANNEL_ERROR_INJECT, &injectmask);
debugf0("Inject error read: 0x%018x\n", injectmask);
if (injectmask & 0x0c)
pvt->inject.enable = 1;
return sprintf(data, "%d\n", pvt->inject.enable);
}
#define DECLARE_COUNTER(param) \
static ssize_t i7core_show_counter_##param( \
struct mem_ctl_info *mci, \
char *data) \
{ \
struct i7core_pvt *pvt = mci->pvt_info; \
\
debugf1("%s() \n", __func__); \
if (!pvt->ce_count_available || (pvt->is_registered)) \
return sprintf(data, "data unavailable\n"); \
return sprintf(data, "%lu\n", \
pvt->udimm_ce_count[param]); \
}
#define ATTR_COUNTER(param) \
{ \
.attr = { \
.name = __stringify(udimm##param), \
.mode = (S_IRUGO | S_IWUSR) \
}, \
.show = i7core_show_counter_##param \
}
DECLARE_COUNTER(0);
DECLARE_COUNTER(1);
DECLARE_COUNTER(2);
/*
* Sysfs struct
*/
static const struct mcidev_sysfs_attribute i7core_addrmatch_attrs[] = {
ATTR_ADDR_MATCH(channel),
ATTR_ADDR_MATCH(dimm),
ATTR_ADDR_MATCH(rank),
ATTR_ADDR_MATCH(bank),
ATTR_ADDR_MATCH(page),
ATTR_ADDR_MATCH(col),
{ } /* End of list */
};
static const struct mcidev_sysfs_group i7core_inject_addrmatch = {
.name = "inject_addrmatch",
.mcidev_attr = i7core_addrmatch_attrs,
};
static const struct mcidev_sysfs_attribute i7core_udimm_counters_attrs[] = {
ATTR_COUNTER(0),
ATTR_COUNTER(1),
ATTR_COUNTER(2),
{ .attr = { .name = NULL } }
};
static const struct mcidev_sysfs_group i7core_udimm_counters = {
.name = "all_channel_counts",
.mcidev_attr = i7core_udimm_counters_attrs,
};
static const struct mcidev_sysfs_attribute i7core_sysfs_rdimm_attrs[] = {
{
.attr = {
.name = "inject_section",
.mode = (S_IRUGO | S_IWUSR)
},
.show = i7core_inject_section_show,
.store = i7core_inject_section_store,
}, {
.attr = {
.name = "inject_type",
.mode = (S_IRUGO | S_IWUSR)
},
.show = i7core_inject_type_show,
.store = i7core_inject_type_store,
}, {
.attr = {
.name = "inject_eccmask",
.mode = (S_IRUGO | S_IWUSR)
},
.show = i7core_inject_eccmask_show,
.store = i7core_inject_eccmask_store,
}, {
.grp = &i7core_inject_addrmatch,
}, {
.attr = {
.name = "inject_enable",
.mode = (S_IRUGO | S_IWUSR)
},
.show = i7core_inject_enable_show,
.store = i7core_inject_enable_store,
},
{ } /* End of list */
};
static const struct mcidev_sysfs_attribute i7core_sysfs_udimm_attrs[] = {
{
.attr = {
.name = "inject_section",
.mode = (S_IRUGO | S_IWUSR)
},
.show = i7core_inject_section_show,
.store = i7core_inject_section_store,
}, {
.attr = {
.name = "inject_type",
.mode = (S_IRUGO | S_IWUSR)
},
.show = i7core_inject_type_show,
.store = i7core_inject_type_store,
}, {
.attr = {
.name = "inject_eccmask",
.mode = (S_IRUGO | S_IWUSR)
},
.show = i7core_inject_eccmask_show,
.store = i7core_inject_eccmask_store,
}, {
.grp = &i7core_inject_addrmatch,
}, {
.attr = {
.name = "inject_enable",
.mode = (S_IRUGO | S_IWUSR)
},
.show = i7core_inject_enable_show,
.store = i7core_inject_enable_store,
}, {
.grp = &i7core_udimm_counters,
},
{ } /* End of list */
};
/****************************************************************************
Device initialization routines: put/get, init/exit
****************************************************************************/
/*
* i7core_put_all_devices 'put' all the devices that we have
* reserved via 'get'
*/
static void i7core_put_devices(struct i7core_dev *i7core_dev)
{
int i;
debugf0(__FILE__ ": %s()\n", __func__);
for (i = 0; i < i7core_dev->n_devs; i++) {
struct pci_dev *pdev = i7core_dev->pdev[i];
if (!pdev)
continue;
debugf0("Removing dev %02x:%02x.%d\n",
pdev->bus->number,
PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
pci_dev_put(pdev);
}
}
static void i7core_put_all_devices(void)
{
struct i7core_dev *i7core_dev, *tmp;
list_for_each_entry_safe(i7core_dev, tmp, &i7core_edac_list, list) {
i7core_put_devices(i7core_dev);
free_i7core_dev(i7core_dev);
}
}
static void __init i7core_xeon_pci_fixup(const struct pci_id_table *table)
{
struct pci_dev *pdev = NULL;
int i;
/*
* On Xeon 55xx, the Intel Quick Path Arch Generic Non-core pci buses
* aren't announced by acpi. So, we need to use a legacy scan probing
* to detect them
*/
while (table && table->descr) {
pdev = pci_get_device(PCI_VENDOR_ID_INTEL, table->descr[0].dev_id, NULL);
if (unlikely(!pdev)) {
for (i = 0; i < MAX_SOCKET_BUSES; i++)
pcibios_scan_specific_bus(255-i);
}
pci_dev_put(pdev);
table++;
}
}
static unsigned i7core_pci_lastbus(void)
{
int last_bus = 0, bus;
struct pci_bus *b = NULL;
while ((b = pci_find_next_bus(b)) != NULL) {
bus = b->number;
debugf0("Found bus %d\n", bus);
if (bus > last_bus)
last_bus = bus;
}
debugf0("Last bus %d\n", last_bus);
return last_bus;
}
/*
* i7core_get_all_devices Find and perform 'get' operation on the MCH's
* device/functions we want to reference for this driver
*
* Need to 'get' device 16 func 1 and func 2
*/
static int i7core_get_onedevice(struct pci_dev **prev,
const struct pci_id_table *table,
const unsigned devno,
const unsigned last_bus)
{
struct i7core_dev *i7core_dev;
const struct pci_id_descr *dev_descr = &table->descr[devno];
struct pci_dev *pdev = NULL;
u8 bus = 0;
u8 socket = 0;
pdev = pci_get_device(PCI_VENDOR_ID_INTEL,
dev_descr->dev_id, *prev);
if (!pdev) {
if (*prev) {
*prev = pdev;
return 0;
}
if (dev_descr->optional)
return 0;
if (devno == 0)
return -ENODEV;
i7core_printk(KERN_INFO,
"Device not found: dev %02x.%d PCI ID %04x:%04x\n",
dev_descr->dev, dev_descr->func,
PCI_VENDOR_ID_INTEL, dev_descr->dev_id);
/* End of list, leave */
return -ENODEV;
}
bus = pdev->bus->number;
socket = last_bus - bus;
i7core_dev = get_i7core_dev(socket);
if (!i7core_dev) {
i7core_dev = alloc_i7core_dev(socket, table);
if (!i7core_dev) {
pci_dev_put(pdev);
return -ENOMEM;
}
}
if (i7core_dev->pdev[devno]) {
i7core_printk(KERN_ERR,
"Duplicated device for "
"dev %02x:%02x.%d PCI ID %04x:%04x\n",
bus, dev_descr->dev, dev_descr->func,
PCI_VENDOR_ID_INTEL, dev_descr->dev_id);
pci_dev_put(pdev);
return -ENODEV;
}
i7core_dev->pdev[devno] = pdev;
/* Sanity check */
if (unlikely(PCI_SLOT(pdev->devfn) != dev_descr->dev ||
PCI_FUNC(pdev->devfn) != dev_descr->func)) {
i7core_printk(KERN_ERR,
"Device PCI ID %04x:%04x "
"has dev %02x:%02x.%d instead of dev %02x:%02x.%d\n",
PCI_VENDOR_ID_INTEL, dev_descr->dev_id,
bus, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
bus, dev_descr->dev, dev_descr->func);
return -ENODEV;
}
/* Be sure that the device is enabled */
if (unlikely(pci_enable_device(pdev) < 0)) {
i7core_printk(KERN_ERR,
"Couldn't enable "
"dev %02x:%02x.%d PCI ID %04x:%04x\n",
bus, dev_descr->dev, dev_descr->func,
PCI_VENDOR_ID_INTEL, dev_descr->dev_id);
return -ENODEV;
}
debugf0("Detected socket %d dev %02x:%02x.%d PCI ID %04x:%04x\n",
socket, bus, dev_descr->dev,
dev_descr->func,
PCI_VENDOR_ID_INTEL, dev_descr->dev_id);
/*
* As stated on drivers/pci/search.c, the reference count for
* @from is always decremented if it is not %NULL. So, as we need
* to get all devices up to null, we need to do a get for the device
*/
pci_dev_get(pdev);
*prev = pdev;
return 0;
}
static int i7core_get_all_devices(void)
{
int i, rc, last_bus;
struct pci_dev *pdev = NULL;
const struct pci_id_table *table = pci_dev_table;
last_bus = i7core_pci_lastbus();
while (table && table->descr) {
for (i = 0; i < table->n_devs; i++) {
pdev = NULL;
do {
rc = i7core_get_onedevice(&pdev, table, i,
last_bus);
if (rc < 0) {
if (i == 0) {
i = table->n_devs;
break;
}
i7core_put_all_devices();
return -ENODEV;
}
} while (pdev);
}
table++;
}
return 0;
}
static int mci_bind_devs(struct mem_ctl_info *mci,
struct i7core_dev *i7core_dev)
{
struct i7core_pvt *pvt = mci->pvt_info;
struct pci_dev *pdev;
int i, func, slot;
pvt->is_registered = 0;
for (i = 0; i < i7core_dev->n_devs; i++) {
pdev = i7core_dev->pdev[i];
if (!pdev)
continue;
func = PCI_FUNC(pdev->devfn);
slot = PCI_SLOT(pdev->devfn);
if (slot == 3) {
if (unlikely(func > MAX_MCR_FUNC))
goto error;
pvt->pci_mcr[func] = pdev;
} else if (likely(slot >= 4 && slot < 4 + NUM_CHANS)) {
if (unlikely(func > MAX_CHAN_FUNC))
goto error;
pvt->pci_ch[slot - 4][func] = pdev;
} else if (!slot && !func)
pvt->pci_noncore = pdev;
else
goto error;
debugf0("Associated fn %d.%d, dev = %p, socket %d\n",
PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
pdev, i7core_dev->socket);
if (PCI_SLOT(pdev->devfn) == 3 &&
PCI_FUNC(pdev->devfn) == 2)
pvt->is_registered = 1;
}
return 0;
error:
i7core_printk(KERN_ERR, "Device %d, function %d "
"is out of the expected range\n",
slot, func);
return -EINVAL;
}
/****************************************************************************
Error check routines
****************************************************************************/
static void i7core_rdimm_update_csrow(struct mem_ctl_info *mci,
const int chan,
const int dimm,
const int add)
{
char *msg;
struct i7core_pvt *pvt = mci->pvt_info;
int row = pvt->csrow_map[chan][dimm], i;
for (i = 0; i < add; i++) {
msg = kasprintf(GFP_KERNEL, "Corrected error "
"(Socket=%d channel=%d dimm=%d)",
pvt->i7core_dev->socket, chan, dimm);
edac_mc_handle_fbd_ce(mci, row, 0, msg);
kfree (msg);
}
}
static void i7core_rdimm_update_ce_count(struct mem_ctl_info *mci,
const int chan,
const int new0,
const int new1,
const int new2)
{
struct i7core_pvt *pvt = mci->pvt_info;
int add0 = 0, add1 = 0, add2 = 0;
/* Updates CE counters if it is not the first time here */
if (pvt->ce_count_available) {
/* Updates CE counters */
add2 = new2 - pvt->rdimm_last_ce_count[chan][2];
add1 = new1 - pvt->rdimm_last_ce_count[chan][1];
add0 = new0 - pvt->rdimm_last_ce_count[chan][0];
if (add2 < 0)
add2 += 0x7fff;
pvt->rdimm_ce_count[chan][2] += add2;
if (add1 < 0)
add1 += 0x7fff;
pvt->rdimm_ce_count[chan][1] += add1;
if (add0 < 0)
add0 += 0x7fff;
pvt->rdimm_ce_count[chan][0] += add0;
} else
pvt->ce_count_available = 1;
/* Store the new values */
pvt->rdimm_last_ce_count[chan][2] = new2;
pvt->rdimm_last_ce_count[chan][1] = new1;
pvt->rdimm_last_ce_count[chan][0] = new0;
/*updated the edac core */
if (add0 != 0)
i7core_rdimm_update_csrow(mci, chan, 0, add0);
if (add1 != 0)
i7core_rdimm_update_csrow(mci, chan, 1, add1);
if (add2 != 0)
i7core_rdimm_update_csrow(mci, chan, 2, add2);
}
static void i7core_rdimm_check_mc_ecc_err(struct mem_ctl_info *mci)
{
struct i7core_pvt *pvt = mci->pvt_info;
u32 rcv[3][2];
int i, new0, new1, new2;
/*Read DEV 3: FUN 2: MC_COR_ECC_CNT regs directly*/
pci_read_config_dword(pvt->pci_mcr[2], MC_COR_ECC_CNT_0,
&rcv[0][0]);
pci_read_config_dword(pvt->pci_mcr[2], MC_COR_ECC_CNT_1,
&rcv[0][1]);
pci_read_config_dword(pvt->pci_mcr[2], MC_COR_ECC_CNT_2,
&rcv[1][0]);
pci_read_config_dword(pvt->pci_mcr[2], MC_COR_ECC_CNT_3,
&rcv[1][1]);
pci_read_config_dword(pvt->pci_mcr[2], MC_COR_ECC_CNT_4,
&rcv[2][0]);
pci_read_config_dword(pvt->pci_mcr[2], MC_COR_ECC_CNT_5,
&rcv[2][1]);
for (i = 0 ; i < 3; i++) {
debugf3("MC_COR_ECC_CNT%d = 0x%x; MC_COR_ECC_CNT%d = 0x%x\n",
(i * 2), rcv[i][0], (i * 2) + 1, rcv[i][1]);
/*if the channel has 3 dimms*/
if (pvt->channel[i].dimms > 2) {
new0 = DIMM_BOT_COR_ERR(rcv[i][0]);
new1 = DIMM_TOP_COR_ERR(rcv[i][0]);
new2 = DIMM_BOT_COR_ERR(rcv[i][1]);
} else {
new0 = DIMM_TOP_COR_ERR(rcv[i][0]) +
DIMM_BOT_COR_ERR(rcv[i][0]);
new1 = DIMM_TOP_COR_ERR(rcv[i][1]) +
DIMM_BOT_COR_ERR(rcv[i][1]);
new2 = 0;
}
i7core_rdimm_update_ce_count(mci, i, new0, new1, new2);
}
}
/* This function is based on the device 3 function 4 registers as described on:
* Intel Xeon Processor 5500 Series Datasheet Volume 2
* http://www.intel.com/Assets/PDF/datasheet/321322.pdf
* also available at:
* http://www.arrownac.com/manufacturers/intel/s/nehalem/5500-datasheet-v2.pdf
*/
static void i7core_udimm_check_mc_ecc_err(struct mem_ctl_info *mci)
{
struct i7core_pvt *pvt = mci->pvt_info;
u32 rcv1, rcv0;
int new0, new1, new2;
if (!pvt->pci_mcr[4]) {
debugf0("%s MCR registers not found\n", __func__);
return;
}
/* Corrected test errors */
pci_read_config_dword(pvt->pci_mcr[4], MC_TEST_ERR_RCV1, &rcv1);
pci_read_config_dword(pvt->pci_mcr[4], MC_TEST_ERR_RCV0, &rcv0);
/* Store the new values */
new2 = DIMM2_COR_ERR(rcv1);
new1 = DIMM1_COR_ERR(rcv0);
new0 = DIMM0_COR_ERR(rcv0);
/* Updates CE counters if it is not the first time here */
if (pvt->ce_count_available) {
/* Updates CE counters */
int add0, add1, add2;
add2 = new2 - pvt->udimm_last_ce_count[2];
add1 = new1 - pvt->udimm_last_ce_count[1];
add0 = new0 - pvt->udimm_last_ce_count[0];
if (add2 < 0)
add2 += 0x7fff;
pvt->udimm_ce_count[2] += add2;
if (add1 < 0)
add1 += 0x7fff;
pvt->udimm_ce_count[1] += add1;
if (add0 < 0)
add0 += 0x7fff;
pvt->udimm_ce_count[0] += add0;
if (add0 | add1 | add2)
i7core_printk(KERN_ERR, "New Corrected error(s): "
"dimm0: +%d, dimm1: +%d, dimm2 +%d\n",
add0, add1, add2);
} else
pvt->ce_count_available = 1;
/* Store the new values */
pvt->udimm_last_ce_count[2] = new2;
pvt->udimm_last_ce_count[1] = new1;
pvt->udimm_last_ce_count[0] = new0;
}
/*
* According with tables E-11 and E-12 of chapter E.3.3 of Intel 64 and IA-32
* Architectures Software Developer’s Manual Volume 3B.
* Nehalem are defined as family 0x06, model 0x1a
*
* The MCA registers used here are the following ones:
* struct mce field MCA Register
* m->status MSR_IA32_MC8_STATUS
* m->addr MSR_IA32_MC8_ADDR
* m->misc MSR_IA32_MC8_MISC
* In the case of Nehalem, the error information is masked at .status and .misc
* fields
*/
static void i7core_mce_output_error(struct mem_ctl_info *mci,
const struct mce *m)
{
struct i7core_pvt *pvt = mci->pvt_info;
char *type, *optype, *err, *msg;
unsigned long error = m->status & 0x1ff0000l;
u32 optypenum = (m->status >> 4) & 0x07;
u32 core_err_cnt = (m->status >> 38) & 0x7fff;
u32 dimm = (m->misc >> 16) & 0x3;
u32 channel = (m->misc >> 18) & 0x3;
u32 syndrome = m->misc >> 32;
u32 errnum = find_first_bit(&error, 32);
int csrow;
if (m->mcgstatus & 1)
type = "FATAL";
else
type = "NON_FATAL";
switch (optypenum) {
case 0:
optype = "generic undef request";
break;
case 1:
optype = "read error";
break;
case 2:
optype = "write error";
break;
case 3:
optype = "addr/cmd error";
break;
case 4:
optype = "scrubbing error";
break;
default:
optype = "reserved";
break;
}
switch (errnum) {
case 16:
err = "read ECC error";
break;
case 17:
err = "RAS ECC error";
break;
case 18:
err = "write parity error";
break;
case 19:
err = "redundacy loss";
break;
case 20:
err = "reserved";
break;
case 21:
err = "memory range error";
break;
case 22:
err = "RTID out of range";
break;
case 23:
err = "address parity error";
break;
case 24:
err = "byte enable parity error";
break;
default:
err = "unknown";
}
/* FIXME: should convert addr into bank and rank information */
msg = kasprintf(GFP_ATOMIC,
"%s (addr = 0x%08llx, cpu=%d, Dimm=%d, Channel=%d, "
"syndrome=0x%08x, count=%d, Err=%08llx:%08llx (%s: %s))\n",
type, (long long) m->addr, m->cpu, dimm, channel,
syndrome, core_err_cnt, (long long)m->status,
(long long)m->misc, optype, err);
debugf0("%s", msg);
csrow = pvt->csrow_map[channel][dimm];
/* Call the helper to output message */
if (m->mcgstatus & 1)
edac_mc_handle_fbd_ue(mci, csrow, 0,
0 /* FIXME: should be channel here */, msg);
else if (!pvt->is_registered)
edac_mc_handle_fbd_ce(mci, csrow,
0 /* FIXME: should be channel here */, msg);
kfree(msg);
}
/*
* i7core_check_error Retrieve and process errors reported by the
* hardware. Called by the Core module.
*/
static void i7core_check_error(struct mem_ctl_info *mci)
{
struct i7core_pvt *pvt = mci->pvt_info;
int i;
unsigned count = 0;
struct mce *m;
/*
* MCE first step: Copy all mce errors into a temporary buffer
* We use a double buffering here, to reduce the risk of
* losing an error.
*/
smp_rmb();
count = (pvt->mce_out + MCE_LOG_LEN - pvt->mce_in)
% MCE_LOG_LEN;
if (!count)
goto check_ce_error;
m = pvt->mce_outentry;
if (pvt->mce_in + count > MCE_LOG_LEN) {
unsigned l = MCE_LOG_LEN - pvt->mce_in;
memcpy(m, &pvt->mce_entry[pvt->mce_in], sizeof(*m) * l);
smp_wmb();
pvt->mce_in = 0;
count -= l;
m += l;
}
memcpy(m, &pvt->mce_entry[pvt->mce_in], sizeof(*m) * count);
smp_wmb();
pvt->mce_in += count;
smp_rmb();
if (pvt->mce_overrun) {
i7core_printk(KERN_ERR, "Lost %d memory errors\n",
pvt->mce_overrun);
smp_wmb();
pvt->mce_overrun = 0;
}
/*
* MCE second step: parse errors and display
*/
for (i = 0; i < count; i++)
i7core_mce_output_error(mci, &pvt->mce_outentry[i]);
/*
* Now, let's increment CE error counts
*/
check_ce_error:
if (!pvt->is_registered)
i7core_udimm_check_mc_ecc_err(mci);
else
i7core_rdimm_check_mc_ecc_err(mci);
}
/*
* i7core_mce_check_error Replicates mcelog routine to get errors
* This routine simply queues mcelog errors, and
* return. The error itself should be handled later
* by i7core_check_error.
* WARNING: As this routine should be called at NMI time, extra care should
* be taken to avoid deadlocks, and to be as fast as possible.
*/
static int i7core_mce_check_error(void *priv, struct mce *mce)
{
struct mem_ctl_info *mci = priv;
struct i7core_pvt *pvt = mci->pvt_info;
/*
* Just let mcelog handle it if the error is
* outside the memory controller
*/
if (((mce->status & 0xffff) >> 7) != 1)
return 0;
/* Bank 8 registers are the only ones that we know how to handle */
if (mce->bank != 8)
return 0;
/* Only handle if it is the right mc controller */
if (cpu_data(mce->cpu).phys_proc_id != pvt->i7core_dev->socket)
return 0;
smp_rmb();
if ((pvt->mce_out + 1) % MCE_LOG_LEN == pvt->mce_in) {
smp_wmb();
pvt->mce_overrun++;
return 0;
}
/* Copy memory error at the ringbuffer */
memcpy(&pvt->mce_entry[pvt->mce_out], mce, sizeof(*mce));
smp_wmb();
pvt->mce_out = (pvt->mce_out + 1) % MCE_LOG_LEN;
/* Handle fatal errors immediately */
if (mce->mcgstatus & 1)
i7core_check_error(mci);
/* Advise mcelog that the errors were handled */
return 1;
}
static void i7core_pci_ctl_create(struct i7core_pvt *pvt)
{
pvt->i7core_pci = edac_pci_create_generic_ctl(
&pvt->i7core_dev->pdev[0]->dev,
EDAC_MOD_STR);
if (unlikely(!pvt->i7core_pci))
pr_warn("Unable to setup PCI error report via EDAC\n");
}
static void i7core_pci_ctl_release(struct i7core_pvt *pvt)
{
if (likely(pvt->i7core_pci))
edac_pci_release_generic_ctl(pvt->i7core_pci);
else
i7core_printk(KERN_ERR,
"Couldn't find mem_ctl_info for socket %d\n",
pvt->i7core_dev->socket);
pvt->i7core_pci = NULL;
}
static void i7core_unregister_mci(struct i7core_dev *i7core_dev)
{
struct mem_ctl_info *mci = i7core_dev->mci;
struct i7core_pvt *pvt;
if (unlikely(!mci || !mci->pvt_info)) {
debugf0("MC: " __FILE__ ": %s(): dev = %p\n",
__func__, &i7core_dev->pdev[0]->dev);
i7core_printk(KERN_ERR, "Couldn't find mci handler\n");
return;
}
pvt = mci->pvt_info;
debugf0("MC: " __FILE__ ": %s(): mci = %p, dev = %p\n",
__func__, mci, &i7core_dev->pdev[0]->dev);
/* Disable MCE NMI handler */
edac_mce_unregister(&pvt->edac_mce);
/* Disable EDAC polling */
i7core_pci_ctl_release(pvt);
/* Remove MC sysfs nodes */
edac_mc_del_mc(mci->dev);
debugf1("%s: free mci struct\n", mci->ctl_name);
kfree(mci->ctl_name);
edac_mc_free(mci);
i7core_dev->mci = NULL;
}
static int i7core_register_mci(struct i7core_dev *i7core_dev)
{
struct mem_ctl_info *mci;
struct i7core_pvt *pvt;
int rc, channels, csrows;
/* Check the number of active and not disabled channels */
rc = i7core_get_active_channels(i7core_dev->socket, &channels, &csrows);
if (unlikely(rc < 0))
return rc;
/* allocate a new MC control structure */
mci = edac_mc_alloc(sizeof(*pvt), csrows, channels, i7core_dev->socket);
if (unlikely(!mci))
return -ENOMEM;
debugf0("MC: " __FILE__ ": %s(): mci = %p, dev = %p\n",
__func__, mci, &i7core_dev->pdev[0]->dev);
pvt = mci->pvt_info;
memset(pvt, 0, sizeof(*pvt));
/* Associates i7core_dev and mci for future usage */
pvt->i7core_dev = i7core_dev;
i7core_dev->mci = mci;
/*
* FIXME: how to handle RDDR3 at MCI level? It is possible to have
* Mixed RDDR3/UDDR3 with Nehalem, provided that they are on different
* memory channels
*/
mci->mtype_cap = MEM_FLAG_DDR3;
mci->edac_ctl_cap = EDAC_FLAG_NONE;
mci->edac_cap = EDAC_FLAG_NONE;
mci->mod_name = "i7core_edac.c";
mci->mod_ver = I7CORE_REVISION;
mci->ctl_name = kasprintf(GFP_KERNEL, "i7 core #%d",
i7core_dev->socket);
mci->dev_name = pci_name(i7core_dev->pdev[0]);
mci->ctl_page_to_phys = NULL;
/* Store pci devices at mci for faster access */
rc = mci_bind_devs(mci, i7core_dev);
if (unlikely(rc < 0))
goto fail0;
if (pvt->is_registered)
mci->mc_driver_sysfs_attributes = i7core_sysfs_rdimm_attrs;
else
mci->mc_driver_sysfs_attributes = i7core_sysfs_udimm_attrs;
/* Get dimm basic config */
get_dimm_config(mci);
/* record ptr to the generic device */
mci->dev = &i7core_dev->pdev[0]->dev;
/* Set the function pointer to an actual operation function */
mci->edac_check = i7core_check_error;
/* add this new MC control structure to EDAC's list of MCs */
if (unlikely(edac_mc_add_mc(mci))) {
debugf0("MC: " __FILE__
": %s(): failed edac_mc_add_mc()\n", __func__);
/* FIXME: perhaps some code should go here that disables error
* reporting if we just enabled it
*/
rc = -EINVAL;
goto fail0;
}
/* Default error mask is any memory */
pvt->inject.channel = 0;
pvt->inject.dimm = -1;
pvt->inject.rank = -1;
pvt->inject.bank = -1;
pvt->inject.page = -1;
pvt->inject.col = -1;
/* allocating generic PCI control info */
i7core_pci_ctl_create(pvt);
/* Registers on edac_mce in order to receive memory errors */
pvt->edac_mce.priv = mci;
pvt->edac_mce.check_error = i7core_mce_check_error;
rc = edac_mce_register(&pvt->edac_mce);
if (unlikely(rc < 0)) {
debugf0("MC: " __FILE__
": %s(): failed edac_mce_register()\n", __func__);
goto fail1;
}
return 0;
fail1:
i7core_pci_ctl_release(pvt);
edac_mc_del_mc(mci->dev);
fail0:
kfree(mci->ctl_name);
edac_mc_free(mci);
i7core_dev->mci = NULL;
return rc;
}
/*
* i7core_probe Probe for ONE instance of device to see if it is
* present.
* return:
* 0 for FOUND a device
* < 0 for error code
*/
static int __devinit i7core_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
int rc;
struct i7core_dev *i7core_dev;
/* get the pci devices we want to reserve for our use */
mutex_lock(&i7core_edac_lock);
/*
* All memory controllers are allocated at the first pass.
*/
if (unlikely(probed >= 1)) {
mutex_unlock(&i7core_edac_lock);
return -ENODEV;
}
probed++;
rc = i7core_get_all_devices();
if (unlikely(rc < 0))
goto fail0;
list_for_each_entry(i7core_dev, &i7core_edac_list, list) {
rc = i7core_register_mci(i7core_dev);
if (unlikely(rc < 0))
goto fail1;
}
i7core_printk(KERN_INFO, "Driver loaded.\n");
mutex_unlock(&i7core_edac_lock);
return 0;
fail1:
list_for_each_entry(i7core_dev, &i7core_edac_list, list)
i7core_unregister_mci(i7core_dev);
i7core_put_all_devices();
fail0:
mutex_unlock(&i7core_edac_lock);
return rc;
}
/*
* i7core_remove destructor for one instance of device
*
*/
static void __devexit i7core_remove(struct pci_dev *pdev)
{
struct i7core_dev *i7core_dev;
debugf0(__FILE__ ": %s()\n", __func__);
/*
* we have a trouble here: pdev value for removal will be wrong, since
* it will point to the X58 register used to detect that the machine
* is a Nehalem or upper design. However, due to the way several PCI
* devices are grouped together to provide MC functionality, we need
* to use a different method for releasing the devices
*/
mutex_lock(&i7core_edac_lock);
if (unlikely(!probed)) {
mutex_unlock(&i7core_edac_lock);
return;
}
list_for_each_entry(i7core_dev, &i7core_edac_list, list)
i7core_unregister_mci(i7core_dev);
/* Release PCI resources */
i7core_put_all_devices();
probed--;
mutex_unlock(&i7core_edac_lock);
}
MODULE_DEVICE_TABLE(pci, i7core_pci_tbl);
/*
* i7core_driver pci_driver structure for this module
*
*/
static struct pci_driver i7core_driver = {
.name = "i7core_edac",
.probe = i7core_probe,
.remove = __devexit_p(i7core_remove),
.id_table = i7core_pci_tbl,
};
/*
* i7core_init Module entry function
* Try to initialize this module for its devices
*/
static int __init i7core_init(void)
{
int pci_rc;
debugf2("MC: " __FILE__ ": %s()\n", __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
if (use_pci_fixup)
i7core_xeon_pci_fixup(pci_dev_table);
pci_rc = pci_register_driver(&i7core_driver);
if (pci_rc >= 0)
return 0;
i7core_printk(KERN_ERR, "Failed to register device with error %d.\n",
pci_rc);
return pci_rc;
}
/*
* i7core_exit() Module exit function
* Unregister the driver
*/
static void __exit i7core_exit(void)
{
debugf2("MC: " __FILE__ ": %s()\n", __func__);
pci_unregister_driver(&i7core_driver);
}
module_init(i7core_init);
module_exit(i7core_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
MODULE_AUTHOR("Red Hat Inc. (http://www.redhat.com)");
MODULE_DESCRIPTION("MC Driver for Intel i7 Core memory controllers - "
I7CORE_REVISION);
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| gpl-2.0 |
extremetempz/Wingray-Kernel | arch/x86/kernel/cpu/cpufreq/speedstep-centrino.c | 1223 | 15634 | /*
* cpufreq driver for Enhanced SpeedStep, as found in Intel's Pentium
* M (part of the Centrino chipset).
*
* Since the original Pentium M, most new Intel CPUs support Enhanced
* SpeedStep.
*
* Despite the "SpeedStep" in the name, this is almost entirely unlike
* traditional SpeedStep.
*
* Modelled on speedstep.c
*
* Copyright (C) 2003 Jeremy Fitzhardinge <jeremy@goop.org>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/cpufreq.h>
#include <linux/sched.h> /* current */
#include <linux/delay.h>
#include <linux/compiler.h>
#include <linux/gfp.h>
#include <asm/msr.h>
#include <asm/processor.h>
#include <asm/cpufeature.h>
#define PFX "speedstep-centrino: "
#define MAINTAINER "cpufreq@vger.kernel.org"
#define dprintk(msg...) \
cpufreq_debug_printk(CPUFREQ_DEBUG_DRIVER, "speedstep-centrino", msg)
#define INTEL_MSR_RANGE (0xffff)
struct cpu_id
{
__u8 x86; /* CPU family */
__u8 x86_model; /* model */
__u8 x86_mask; /* stepping */
};
enum {
CPU_BANIAS,
CPU_DOTHAN_A1,
CPU_DOTHAN_A2,
CPU_DOTHAN_B0,
CPU_MP4HT_D0,
CPU_MP4HT_E0,
};
static const struct cpu_id cpu_ids[] = {
[CPU_BANIAS] = { 6, 9, 5 },
[CPU_DOTHAN_A1] = { 6, 13, 1 },
[CPU_DOTHAN_A2] = { 6, 13, 2 },
[CPU_DOTHAN_B0] = { 6, 13, 6 },
[CPU_MP4HT_D0] = {15, 3, 4 },
[CPU_MP4HT_E0] = {15, 4, 1 },
};
#define N_IDS ARRAY_SIZE(cpu_ids)
struct cpu_model
{
const struct cpu_id *cpu_id;
const char *model_name;
unsigned max_freq; /* max clock in kHz */
struct cpufreq_frequency_table *op_points; /* clock/voltage pairs */
};
static int centrino_verify_cpu_id(const struct cpuinfo_x86 *c,
const struct cpu_id *x);
/* Operating points for current CPU */
static DEFINE_PER_CPU(struct cpu_model *, centrino_model);
static DEFINE_PER_CPU(const struct cpu_id *, centrino_cpu);
static struct cpufreq_driver centrino_driver;
#ifdef CONFIG_X86_SPEEDSTEP_CENTRINO_TABLE
/* Computes the correct form for IA32_PERF_CTL MSR for a particular
frequency/voltage operating point; frequency in MHz, volts in mV.
This is stored as "index" in the structure. */
#define OP(mhz, mv) \
{ \
.frequency = (mhz) * 1000, \
.index = (((mhz)/100) << 8) | ((mv - 700) / 16) \
}
/*
* These voltage tables were derived from the Intel Pentium M
* datasheet, document 25261202.pdf, Table 5. I have verified they
* are consistent with my IBM ThinkPad X31, which has a 1.3GHz Pentium
* M.
*/
/* Ultra Low Voltage Intel Pentium M processor 900MHz (Banias) */
static struct cpufreq_frequency_table banias_900[] =
{
OP(600, 844),
OP(800, 988),
OP(900, 1004),
{ .frequency = CPUFREQ_TABLE_END }
};
/* Ultra Low Voltage Intel Pentium M processor 1000MHz (Banias) */
static struct cpufreq_frequency_table banias_1000[] =
{
OP(600, 844),
OP(800, 972),
OP(900, 988),
OP(1000, 1004),
{ .frequency = CPUFREQ_TABLE_END }
};
/* Low Voltage Intel Pentium M processor 1.10GHz (Banias) */
static struct cpufreq_frequency_table banias_1100[] =
{
OP( 600, 956),
OP( 800, 1020),
OP( 900, 1100),
OP(1000, 1164),
OP(1100, 1180),
{ .frequency = CPUFREQ_TABLE_END }
};
/* Low Voltage Intel Pentium M processor 1.20GHz (Banias) */
static struct cpufreq_frequency_table banias_1200[] =
{
OP( 600, 956),
OP( 800, 1004),
OP( 900, 1020),
OP(1000, 1100),
OP(1100, 1164),
OP(1200, 1180),
{ .frequency = CPUFREQ_TABLE_END }
};
/* Intel Pentium M processor 1.30GHz (Banias) */
static struct cpufreq_frequency_table banias_1300[] =
{
OP( 600, 956),
OP( 800, 1260),
OP(1000, 1292),
OP(1200, 1356),
OP(1300, 1388),
{ .frequency = CPUFREQ_TABLE_END }
};
/* Intel Pentium M processor 1.40GHz (Banias) */
static struct cpufreq_frequency_table banias_1400[] =
{
OP( 600, 956),
OP( 800, 1180),
OP(1000, 1308),
OP(1200, 1436),
OP(1400, 1484),
{ .frequency = CPUFREQ_TABLE_END }
};
/* Intel Pentium M processor 1.50GHz (Banias) */
static struct cpufreq_frequency_table banias_1500[] =
{
OP( 600, 956),
OP( 800, 1116),
OP(1000, 1228),
OP(1200, 1356),
OP(1400, 1452),
OP(1500, 1484),
{ .frequency = CPUFREQ_TABLE_END }
};
/* Intel Pentium M processor 1.60GHz (Banias) */
static struct cpufreq_frequency_table banias_1600[] =
{
OP( 600, 956),
OP( 800, 1036),
OP(1000, 1164),
OP(1200, 1276),
OP(1400, 1420),
OP(1600, 1484),
{ .frequency = CPUFREQ_TABLE_END }
};
/* Intel Pentium M processor 1.70GHz (Banias) */
static struct cpufreq_frequency_table banias_1700[] =
{
OP( 600, 956),
OP( 800, 1004),
OP(1000, 1116),
OP(1200, 1228),
OP(1400, 1308),
OP(1700, 1484),
{ .frequency = CPUFREQ_TABLE_END }
};
#undef OP
#define _BANIAS(cpuid, max, name) \
{ .cpu_id = cpuid, \
.model_name = "Intel(R) Pentium(R) M processor " name "MHz", \
.max_freq = (max)*1000, \
.op_points = banias_##max, \
}
#define BANIAS(max) _BANIAS(&cpu_ids[CPU_BANIAS], max, #max)
/* CPU models, their operating frequency range, and freq/voltage
operating points */
static struct cpu_model models[] =
{
_BANIAS(&cpu_ids[CPU_BANIAS], 900, " 900"),
BANIAS(1000),
BANIAS(1100),
BANIAS(1200),
BANIAS(1300),
BANIAS(1400),
BANIAS(1500),
BANIAS(1600),
BANIAS(1700),
/* NULL model_name is a wildcard */
{ &cpu_ids[CPU_DOTHAN_A1], NULL, 0, NULL },
{ &cpu_ids[CPU_DOTHAN_A2], NULL, 0, NULL },
{ &cpu_ids[CPU_DOTHAN_B0], NULL, 0, NULL },
{ &cpu_ids[CPU_MP4HT_D0], NULL, 0, NULL },
{ &cpu_ids[CPU_MP4HT_E0], NULL, 0, NULL },
{ NULL, }
};
#undef _BANIAS
#undef BANIAS
static int centrino_cpu_init_table(struct cpufreq_policy *policy)
{
struct cpuinfo_x86 *cpu = &cpu_data(policy->cpu);
struct cpu_model *model;
for(model = models; model->cpu_id != NULL; model++)
if (centrino_verify_cpu_id(cpu, model->cpu_id) &&
(model->model_name == NULL ||
strcmp(cpu->x86_model_id, model->model_name) == 0))
break;
if (model->cpu_id == NULL) {
/* No match at all */
dprintk("no support for CPU model \"%s\": "
"send /proc/cpuinfo to " MAINTAINER "\n",
cpu->x86_model_id);
return -ENOENT;
}
if (model->op_points == NULL) {
/* Matched a non-match */
dprintk("no table support for CPU model \"%s\"\n",
cpu->x86_model_id);
dprintk("try using the acpi-cpufreq driver\n");
return -ENOENT;
}
per_cpu(centrino_model, policy->cpu) = model;
dprintk("found \"%s\": max frequency: %dkHz\n",
model->model_name, model->max_freq);
return 0;
}
#else
static inline int centrino_cpu_init_table(struct cpufreq_policy *policy)
{
return -ENODEV;
}
#endif /* CONFIG_X86_SPEEDSTEP_CENTRINO_TABLE */
static int centrino_verify_cpu_id(const struct cpuinfo_x86 *c,
const struct cpu_id *x)
{
if ((c->x86 == x->x86) &&
(c->x86_model == x->x86_model) &&
(c->x86_mask == x->x86_mask))
return 1;
return 0;
}
/* To be called only after centrino_model is initialized */
static unsigned extract_clock(unsigned msr, unsigned int cpu, int failsafe)
{
int i;
/*
* Extract clock in kHz from PERF_CTL value
* for centrino, as some DSDTs are buggy.
* Ideally, this can be done using the acpi_data structure.
*/
if ((per_cpu(centrino_cpu, cpu) == &cpu_ids[CPU_BANIAS]) ||
(per_cpu(centrino_cpu, cpu) == &cpu_ids[CPU_DOTHAN_A1]) ||
(per_cpu(centrino_cpu, cpu) == &cpu_ids[CPU_DOTHAN_B0])) {
msr = (msr >> 8) & 0xff;
return msr * 100000;
}
if ((!per_cpu(centrino_model, cpu)) ||
(!per_cpu(centrino_model, cpu)->op_points))
return 0;
msr &= 0xffff;
for (i = 0;
per_cpu(centrino_model, cpu)->op_points[i].frequency
!= CPUFREQ_TABLE_END;
i++) {
if (msr == per_cpu(centrino_model, cpu)->op_points[i].index)
return per_cpu(centrino_model, cpu)->
op_points[i].frequency;
}
if (failsafe)
return per_cpu(centrino_model, cpu)->op_points[i-1].frequency;
else
return 0;
}
/* Return the current CPU frequency in kHz */
static unsigned int get_cur_freq(unsigned int cpu)
{
unsigned l, h;
unsigned clock_freq;
rdmsr_on_cpu(cpu, MSR_IA32_PERF_STATUS, &l, &h);
clock_freq = extract_clock(l, cpu, 0);
if (unlikely(clock_freq == 0)) {
/*
* On some CPUs, we can see transient MSR values (which are
* not present in _PSS), while CPU is doing some automatic
* P-state transition (like TM2). Get the last freq set
* in PERF_CTL.
*/
rdmsr_on_cpu(cpu, MSR_IA32_PERF_CTL, &l, &h);
clock_freq = extract_clock(l, cpu, 1);
}
return clock_freq;
}
static int centrino_cpu_init(struct cpufreq_policy *policy)
{
struct cpuinfo_x86 *cpu = &cpu_data(policy->cpu);
unsigned freq;
unsigned l, h;
int ret;
int i;
/* Only Intel makes Enhanced Speedstep-capable CPUs */
if (cpu->x86_vendor != X86_VENDOR_INTEL ||
!cpu_has(cpu, X86_FEATURE_EST))
return -ENODEV;
if (cpu_has(cpu, X86_FEATURE_CONSTANT_TSC))
centrino_driver.flags |= CPUFREQ_CONST_LOOPS;
if (policy->cpu != 0)
return -ENODEV;
for (i = 0; i < N_IDS; i++)
if (centrino_verify_cpu_id(cpu, &cpu_ids[i]))
break;
if (i != N_IDS)
per_cpu(centrino_cpu, policy->cpu) = &cpu_ids[i];
if (!per_cpu(centrino_cpu, policy->cpu)) {
dprintk("found unsupported CPU with "
"Enhanced SpeedStep: send /proc/cpuinfo to "
MAINTAINER "\n");
return -ENODEV;
}
if (centrino_cpu_init_table(policy)) {
return -ENODEV;
}
/* Check to see if Enhanced SpeedStep is enabled, and try to
enable it if not. */
rdmsr(MSR_IA32_MISC_ENABLE, l, h);
if (!(l & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP)) {
l |= MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP;
dprintk("trying to enable Enhanced SpeedStep (%x)\n", l);
wrmsr(MSR_IA32_MISC_ENABLE, l, h);
/* check to see if it stuck */
rdmsr(MSR_IA32_MISC_ENABLE, l, h);
if (!(l & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP)) {
printk(KERN_INFO PFX
"couldn't enable Enhanced SpeedStep\n");
return -ENODEV;
}
}
freq = get_cur_freq(policy->cpu);
policy->cpuinfo.transition_latency = 10000;
/* 10uS transition latency */
policy->cur = freq;
dprintk("centrino_cpu_init: cur=%dkHz\n", policy->cur);
ret = cpufreq_frequency_table_cpuinfo(policy,
per_cpu(centrino_model, policy->cpu)->op_points);
if (ret)
return (ret);
cpufreq_frequency_table_get_attr(
per_cpu(centrino_model, policy->cpu)->op_points, policy->cpu);
return 0;
}
static int centrino_cpu_exit(struct cpufreq_policy *policy)
{
unsigned int cpu = policy->cpu;
if (!per_cpu(centrino_model, cpu))
return -ENODEV;
cpufreq_frequency_table_put_attr(cpu);
per_cpu(centrino_model, cpu) = NULL;
return 0;
}
/**
* centrino_verify - verifies a new CPUFreq policy
* @policy: new policy
*
* Limit must be within this model's frequency range at least one
* border included.
*/
static int centrino_verify (struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy,
per_cpu(centrino_model, policy->cpu)->op_points);
}
/**
* centrino_setpolicy - set a new CPUFreq policy
* @policy: new policy
* @target_freq: the target frequency
* @relation: how that frequency relates to achieved frequency
* (CPUFREQ_RELATION_L or CPUFREQ_RELATION_H)
*
* Sets a new CPUFreq policy.
*/
static int centrino_target (struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
unsigned int newstate = 0;
unsigned int msr, oldmsr = 0, h = 0, cpu = policy->cpu;
struct cpufreq_freqs freqs;
int retval = 0;
unsigned int j, k, first_cpu, tmp;
cpumask_var_t covered_cpus;
if (unlikely(!zalloc_cpumask_var(&covered_cpus, GFP_KERNEL)))
return -ENOMEM;
if (unlikely(per_cpu(centrino_model, cpu) == NULL)) {
retval = -ENODEV;
goto out;
}
if (unlikely(cpufreq_frequency_table_target(policy,
per_cpu(centrino_model, cpu)->op_points,
target_freq,
relation,
&newstate))) {
retval = -EINVAL;
goto out;
}
first_cpu = 1;
for_each_cpu(j, policy->cpus) {
int good_cpu;
/* cpufreq holds the hotplug lock, so we are safe here */
if (!cpu_online(j))
continue;
/*
* Support for SMP systems.
* Make sure we are running on CPU that wants to change freq
*/
if (policy->shared_type == CPUFREQ_SHARED_TYPE_ANY)
good_cpu = cpumask_any_and(policy->cpus,
cpu_online_mask);
else
good_cpu = j;
if (good_cpu >= nr_cpu_ids) {
dprintk("couldn't limit to CPUs in this domain\n");
retval = -EAGAIN;
if (first_cpu) {
/* We haven't started the transition yet. */
goto out;
}
break;
}
msr = per_cpu(centrino_model, cpu)->op_points[newstate].index;
if (first_cpu) {
rdmsr_on_cpu(good_cpu, MSR_IA32_PERF_CTL, &oldmsr, &h);
if (msr == (oldmsr & 0xffff)) {
dprintk("no change needed - msr was and needs "
"to be %x\n", oldmsr);
retval = 0;
goto out;
}
freqs.old = extract_clock(oldmsr, cpu, 0);
freqs.new = extract_clock(msr, cpu, 0);
dprintk("target=%dkHz old=%d new=%d msr=%04x\n",
target_freq, freqs.old, freqs.new, msr);
for_each_cpu(k, policy->cpus) {
if (!cpu_online(k))
continue;
freqs.cpu = k;
cpufreq_notify_transition(&freqs,
CPUFREQ_PRECHANGE);
}
first_cpu = 0;
/* all but 16 LSB are reserved, treat them with care */
oldmsr &= ~0xffff;
msr &= 0xffff;
oldmsr |= msr;
}
wrmsr_on_cpu(good_cpu, MSR_IA32_PERF_CTL, oldmsr, h);
if (policy->shared_type == CPUFREQ_SHARED_TYPE_ANY)
break;
cpumask_set_cpu(j, covered_cpus);
}
for_each_cpu(k, policy->cpus) {
if (!cpu_online(k))
continue;
freqs.cpu = k;
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
}
if (unlikely(retval)) {
/*
* We have failed halfway through the frequency change.
* We have sent callbacks to policy->cpus and
* MSRs have already been written on coverd_cpus.
* Best effort undo..
*/
for_each_cpu(j, covered_cpus)
wrmsr_on_cpu(j, MSR_IA32_PERF_CTL, oldmsr, h);
tmp = freqs.new;
freqs.new = freqs.old;
freqs.old = tmp;
for_each_cpu(j, policy->cpus) {
if (!cpu_online(j))
continue;
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
}
}
retval = 0;
out:
free_cpumask_var(covered_cpus);
return retval;
}
static struct freq_attr* centrino_attr[] = {
&cpufreq_freq_attr_scaling_available_freqs,
NULL,
};
static struct cpufreq_driver centrino_driver = {
.name = "centrino", /* should be speedstep-centrino,
but there's a 16 char limit */
.init = centrino_cpu_init,
.exit = centrino_cpu_exit,
.verify = centrino_verify,
.target = centrino_target,
.get = get_cur_freq,
.attr = centrino_attr,
.owner = THIS_MODULE,
};
/**
* centrino_init - initializes the Enhanced SpeedStep CPUFreq driver
*
* Initializes the Enhanced SpeedStep support. Returns -ENODEV on
* unsupported devices, -ENOENT if there's no voltage table for this
* particular CPU model, -EINVAL on problems during initiatization,
* and zero on success.
*
* This is quite picky. Not only does the CPU have to advertise the
* "est" flag in the cpuid capability flags, we look for a specific
* CPU model and stepping, and we need to have the exact model name in
* our voltage tables. That is, be paranoid about not releasing
* someone's valuable magic smoke.
*/
static int __init centrino_init(void)
{
struct cpuinfo_x86 *cpu = &cpu_data(0);
if (!cpu_has(cpu, X86_FEATURE_EST))
return -ENODEV;
return cpufreq_register_driver(¢rino_driver);
}
static void __exit centrino_exit(void)
{
cpufreq_unregister_driver(¢rino_driver);
}
MODULE_AUTHOR ("Jeremy Fitzhardinge <jeremy@goop.org>");
MODULE_DESCRIPTION ("Enhanced SpeedStep driver for Intel Pentium M processors.");
MODULE_LICENSE ("GPL");
late_initcall(centrino_init);
module_exit(centrino_exit);
| gpl-2.0 |
jakeclawson/linux | sound/drivers/pcsp/pcsp_input.c | 1479 | 2304 | /*
* PC Speaker beeper driver for Linux
*
* Copyright (c) 2002 Vojtech Pavlik
* Copyright (c) 1992 Orest Zborowski
*
*/
/*
* 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/input.h>
#include <linux/io.h>
#include "pcsp.h"
#include "pcsp_input.h"
static void pcspkr_do_sound(unsigned int count)
{
unsigned long flags;
raw_spin_lock_irqsave(&i8253_lock, flags);
if (count) {
/* set command for counter 2, 2 byte write */
outb_p(0xB6, 0x43);
/* select desired HZ */
outb_p(count & 0xff, 0x42);
outb((count >> 8) & 0xff, 0x42);
/* enable counter 2 */
outb_p(inb_p(0x61) | 3, 0x61);
} else {
/* disable counter 2 */
outb(inb_p(0x61) & 0xFC, 0x61);
}
raw_spin_unlock_irqrestore(&i8253_lock, flags);
}
void pcspkr_stop_sound(void)
{
pcspkr_do_sound(0);
}
static int pcspkr_input_event(struct input_dev *dev, unsigned int type,
unsigned int code, int value)
{
unsigned int count = 0;
if (atomic_read(&pcsp_chip.timer_active) || !pcsp_chip.pcspkr)
return 0;
switch (type) {
case EV_SND:
switch (code) {
case SND_BELL:
if (value)
value = 1000;
case SND_TONE:
break;
default:
return -1;
}
break;
default:
return -1;
}
if (value > 20 && value < 32767)
count = PIT_TICK_RATE / value;
pcspkr_do_sound(count);
return 0;
}
int pcspkr_input_init(struct input_dev **rdev, struct device *dev)
{
int err;
struct input_dev *input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
input_dev->name = "PC Speaker";
input_dev->phys = "isa0061/input0";
input_dev->id.bustype = BUS_ISA;
input_dev->id.vendor = 0x001f;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = dev;
input_dev->evbit[0] = BIT(EV_SND);
input_dev->sndbit[0] = BIT(SND_BELL) | BIT(SND_TONE);
input_dev->event = pcspkr_input_event;
err = input_register_device(input_dev);
if (err) {
input_free_device(input_dev);
return err;
}
*rdev = input_dev;
return 0;
}
int pcspkr_input_remove(struct input_dev *dev)
{
pcspkr_stop_sound();
input_unregister_device(dev); /* this also does kfree() */
return 0;
}
| gpl-2.0 |
nuxeh/linux | arch/sh/kernel/hw_breakpoint.c | 1735 | 8818 | /*
* arch/sh/kernel/hw_breakpoint.c
*
* Unified kernel/user-space hardware breakpoint facility for the on-chip UBC.
*
* Copyright (C) 2009 - 2010 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/perf_event.h>
#include <linux/hw_breakpoint.h>
#include <linux/percpu.h>
#include <linux/kallsyms.h>
#include <linux/notifier.h>
#include <linux/kprobes.h>
#include <linux/kdebug.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <asm/hw_breakpoint.h>
#include <asm/mmu_context.h>
#include <asm/ptrace.h>
#include <asm/traps.h>
/*
* Stores the breakpoints currently in use on each breakpoint address
* register for each cpus
*/
static DEFINE_PER_CPU(struct perf_event *, bp_per_reg[HBP_NUM]);
/*
* A dummy placeholder for early accesses until the CPUs get a chance to
* register their UBCs later in the boot process.
*/
static struct sh_ubc ubc_dummy = { .num_events = 0 };
static struct sh_ubc *sh_ubc __read_mostly = &ubc_dummy;
/*
* Install a perf counter breakpoint.
*
* We seek a free UBC channel and use it for this breakpoint.
*
* Atomic: we hold the counter->ctx->lock and we only handle variables
* and registers local to this cpu.
*/
int arch_install_hw_breakpoint(struct perf_event *bp)
{
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
int i;
for (i = 0; i < sh_ubc->num_events; i++) {
struct perf_event **slot = this_cpu_ptr(&bp_per_reg[i]);
if (!*slot) {
*slot = bp;
break;
}
}
if (WARN_ONCE(i == sh_ubc->num_events, "Can't find any breakpoint slot"))
return -EBUSY;
clk_enable(sh_ubc->clk);
sh_ubc->enable(info, i);
return 0;
}
/*
* Uninstall the breakpoint contained in the given counter.
*
* First we search the debug address register it uses and then we disable
* it.
*
* Atomic: we hold the counter->ctx->lock and we only handle variables
* and registers local to this cpu.
*/
void arch_uninstall_hw_breakpoint(struct perf_event *bp)
{
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
int i;
for (i = 0; i < sh_ubc->num_events; i++) {
struct perf_event **slot = this_cpu_ptr(&bp_per_reg[i]);
if (*slot == bp) {
*slot = NULL;
break;
}
}
if (WARN_ONCE(i == sh_ubc->num_events, "Can't find any breakpoint slot"))
return;
sh_ubc->disable(info, i);
clk_disable(sh_ubc->clk);
}
static int get_hbp_len(u16 hbp_len)
{
unsigned int len_in_bytes = 0;
switch (hbp_len) {
case SH_BREAKPOINT_LEN_1:
len_in_bytes = 1;
break;
case SH_BREAKPOINT_LEN_2:
len_in_bytes = 2;
break;
case SH_BREAKPOINT_LEN_4:
len_in_bytes = 4;
break;
case SH_BREAKPOINT_LEN_8:
len_in_bytes = 8;
break;
}
return len_in_bytes;
}
/*
* Check for virtual address in kernel space.
*/
int arch_check_bp_in_kernelspace(struct perf_event *bp)
{
unsigned int len;
unsigned long va;
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
va = info->address;
len = get_hbp_len(info->len);
return (va >= TASK_SIZE) && ((va + len - 1) >= TASK_SIZE);
}
int arch_bp_generic_fields(int sh_len, int sh_type,
int *gen_len, int *gen_type)
{
/* Len */
switch (sh_len) {
case SH_BREAKPOINT_LEN_1:
*gen_len = HW_BREAKPOINT_LEN_1;
break;
case SH_BREAKPOINT_LEN_2:
*gen_len = HW_BREAKPOINT_LEN_2;
break;
case SH_BREAKPOINT_LEN_4:
*gen_len = HW_BREAKPOINT_LEN_4;
break;
case SH_BREAKPOINT_LEN_8:
*gen_len = HW_BREAKPOINT_LEN_8;
break;
default:
return -EINVAL;
}
/* Type */
switch (sh_type) {
case SH_BREAKPOINT_READ:
*gen_type = HW_BREAKPOINT_R;
case SH_BREAKPOINT_WRITE:
*gen_type = HW_BREAKPOINT_W;
break;
case SH_BREAKPOINT_RW:
*gen_type = HW_BREAKPOINT_W | HW_BREAKPOINT_R;
break;
default:
return -EINVAL;
}
return 0;
}
static int arch_build_bp_info(struct perf_event *bp)
{
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
info->address = bp->attr.bp_addr;
/* Len */
switch (bp->attr.bp_len) {
case HW_BREAKPOINT_LEN_1:
info->len = SH_BREAKPOINT_LEN_1;
break;
case HW_BREAKPOINT_LEN_2:
info->len = SH_BREAKPOINT_LEN_2;
break;
case HW_BREAKPOINT_LEN_4:
info->len = SH_BREAKPOINT_LEN_4;
break;
case HW_BREAKPOINT_LEN_8:
info->len = SH_BREAKPOINT_LEN_8;
break;
default:
return -EINVAL;
}
/* Type */
switch (bp->attr.bp_type) {
case HW_BREAKPOINT_R:
info->type = SH_BREAKPOINT_READ;
break;
case HW_BREAKPOINT_W:
info->type = SH_BREAKPOINT_WRITE;
break;
case HW_BREAKPOINT_W | HW_BREAKPOINT_R:
info->type = SH_BREAKPOINT_RW;
break;
default:
return -EINVAL;
}
return 0;
}
/*
* Validate the arch-specific HW Breakpoint register settings
*/
int arch_validate_hwbkpt_settings(struct perf_event *bp)
{
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
unsigned int align;
int ret;
ret = arch_build_bp_info(bp);
if (ret)
return ret;
ret = -EINVAL;
switch (info->len) {
case SH_BREAKPOINT_LEN_1:
align = 0;
break;
case SH_BREAKPOINT_LEN_2:
align = 1;
break;
case SH_BREAKPOINT_LEN_4:
align = 3;
break;
case SH_BREAKPOINT_LEN_8:
align = 7;
break;
default:
return ret;
}
/*
* For kernel-addresses, either the address or symbol name can be
* specified.
*/
if (info->name)
info->address = (unsigned long)kallsyms_lookup_name(info->name);
/*
* Check that the low-order bits of the address are appropriate
* for the alignment implied by len.
*/
if (info->address & align)
return -EINVAL;
return 0;
}
/*
* Release the user breakpoints used by ptrace
*/
void flush_ptrace_hw_breakpoint(struct task_struct *tsk)
{
int i;
struct thread_struct *t = &tsk->thread;
for (i = 0; i < sh_ubc->num_events; i++) {
unregister_hw_breakpoint(t->ptrace_bps[i]);
t->ptrace_bps[i] = NULL;
}
}
static int __kprobes hw_breakpoint_handler(struct die_args *args)
{
int cpu, i, rc = NOTIFY_STOP;
struct perf_event *bp;
unsigned int cmf, resume_mask;
/*
* Do an early return if none of the channels triggered.
*/
cmf = sh_ubc->triggered_mask();
if (unlikely(!cmf))
return NOTIFY_DONE;
/*
* By default, resume all of the active channels.
*/
resume_mask = sh_ubc->active_mask();
/*
* Disable breakpoints during exception handling.
*/
sh_ubc->disable_all();
cpu = get_cpu();
for (i = 0; i < sh_ubc->num_events; i++) {
unsigned long event_mask = (1 << i);
if (likely(!(cmf & event_mask)))
continue;
/*
* The counter may be concurrently released but that can only
* occur from a call_rcu() path. We can then safely fetch
* the breakpoint, use its callback, touch its counter
* while we are in an rcu_read_lock() path.
*/
rcu_read_lock();
bp = per_cpu(bp_per_reg[i], cpu);
if (bp)
rc = NOTIFY_DONE;
/*
* Reset the condition match flag to denote completion of
* exception handling.
*/
sh_ubc->clear_triggered_mask(event_mask);
/*
* bp can be NULL due to concurrent perf counter
* removing.
*/
if (!bp) {
rcu_read_unlock();
break;
}
/*
* Don't restore the channel if the breakpoint is from
* ptrace, as it always operates in one-shot mode.
*/
if (bp->overflow_handler == ptrace_triggered)
resume_mask &= ~(1 << i);
perf_bp_event(bp, args->regs);
/* Deliver the signal to userspace */
if (!arch_check_bp_in_kernelspace(bp)) {
siginfo_t info;
info.si_signo = args->signr;
info.si_errno = notifier_to_errno(rc);
info.si_code = TRAP_HWBKPT;
force_sig_info(args->signr, &info, current);
}
rcu_read_unlock();
}
if (cmf == 0)
rc = NOTIFY_DONE;
sh_ubc->enable_all(resume_mask);
put_cpu();
return rc;
}
BUILD_TRAP_HANDLER(breakpoint)
{
unsigned long ex = lookup_exception_vector();
TRAP_HANDLER_DECL;
notify_die(DIE_BREAKPOINT, "breakpoint", regs, 0, ex, SIGTRAP);
}
/*
* Handle debug exception notifications.
*/
int __kprobes hw_breakpoint_exceptions_notify(struct notifier_block *unused,
unsigned long val, void *data)
{
struct die_args *args = data;
if (val != DIE_BREAKPOINT)
return NOTIFY_DONE;
/*
* If the breakpoint hasn't been triggered by the UBC, it's
* probably from a debugger, so don't do anything more here.
*
* This also permits the UBC interface clock to remain off for
* non-UBC breakpoints, as we don't need to check the triggered
* or active channel masks.
*/
if (args->trapnr != sh_ubc->trap_nr)
return NOTIFY_DONE;
return hw_breakpoint_handler(data);
}
void hw_breakpoint_pmu_read(struct perf_event *bp)
{
/* TODO */
}
int register_sh_ubc(struct sh_ubc *ubc)
{
/* Bail if it's already assigned */
if (sh_ubc != &ubc_dummy)
return -EBUSY;
sh_ubc = ubc;
pr_info("HW Breakpoints: %s UBC support registered\n", ubc->name);
WARN_ON(ubc->num_events > HBP_NUM);
return 0;
}
| gpl-2.0 |
DespairFactor/N6 | sound/soc/codecs/stac9766.c | 2247 | 12548 | /*
* stac9766.c -- ALSA SoC STAC9766 codec support
*
* Copyright 2009 Jon Smirl, Digispeaker
* Author: Jon Smirl <jonsmirl@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; either version 2 of the License, or (at your
* option) any later version.
*
* Features:-
*
* o Support for AC97 Codec, S/PDIF
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/ac97_codec.h>
#include <sound/initval.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/tlv.h>
#include "stac9766.h"
#define STAC9766_VERSION "0.10"
/*
* STAC9766 register cache
*/
static const u16 stac9766_reg[] = {
0x6A90, 0x8000, 0x8000, 0x8000, /* 6 */
0x0000, 0x0000, 0x8008, 0x8008, /* e */
0x8808, 0x8808, 0x8808, 0x8808, /* 16 */
0x8808, 0x0000, 0x8000, 0x0000, /* 1e */
0x0000, 0x0000, 0x0000, 0x000f, /* 26 */
0x0a05, 0x0400, 0xbb80, 0x0000, /* 2e */
0x0000, 0xbb80, 0x0000, 0x0000, /* 36 */
0x0000, 0x2000, 0x0000, 0x0100, /* 3e */
0x0000, 0x0000, 0x0080, 0x0000, /* 46 */
0x0000, 0x0000, 0x0003, 0xffff, /* 4e */
0x0000, 0x0000, 0x0000, 0x0000, /* 56 */
0x4000, 0x0000, 0x0000, 0x0000, /* 5e */
0x1201, 0xFFFF, 0xFFFF, 0x0000, /* 66 */
0x0000, 0x0000, 0x0000, 0x0000, /* 6e */
0x0000, 0x0000, 0x0000, 0x0006, /* 76 */
0x0000, 0x0000, 0x0000, 0x0000, /* 7e */
};
static const char *stac9766_record_mux[] = {"Mic", "CD", "Video", "AUX",
"Line", "Stereo Mix", "Mono Mix", "Phone"};
static const char *stac9766_mono_mux[] = {"Mix", "Mic"};
static const char *stac9766_mic_mux[] = {"Mic1", "Mic2"};
static const char *stac9766_SPDIF_mux[] = {"PCM", "ADC Record"};
static const char *stac9766_popbypass_mux[] = {"Normal", "Bypass Mixer"};
static const char *stac9766_record_all_mux[] = {"All analog",
"Analog plus DAC"};
static const char *stac9766_boost1[] = {"0dB", "10dB"};
static const char *stac9766_boost2[] = {"0dB", "20dB"};
static const char *stac9766_stereo_mic[] = {"Off", "On"};
static const struct soc_enum stac9766_record_enum =
SOC_ENUM_DOUBLE(AC97_REC_SEL, 8, 0, 8, stac9766_record_mux);
static const struct soc_enum stac9766_mono_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 9, 2, stac9766_mono_mux);
static const struct soc_enum stac9766_mic_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 8, 2, stac9766_mic_mux);
static const struct soc_enum stac9766_SPDIF_enum =
SOC_ENUM_SINGLE(AC97_STAC_DA_CONTROL, 1, 2, stac9766_SPDIF_mux);
static const struct soc_enum stac9766_popbypass_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 15, 2, stac9766_popbypass_mux);
static const struct soc_enum stac9766_record_all_enum =
SOC_ENUM_SINGLE(AC97_STAC_ANALOG_SPECIAL, 12, 2,
stac9766_record_all_mux);
static const struct soc_enum stac9766_boost1_enum =
SOC_ENUM_SINGLE(AC97_MIC, 6, 2, stac9766_boost1); /* 0/10dB */
static const struct soc_enum stac9766_boost2_enum =
SOC_ENUM_SINGLE(AC97_STAC_ANALOG_SPECIAL, 2, 2, stac9766_boost2); /* 0/20dB */
static const struct soc_enum stac9766_stereo_mic_enum =
SOC_ENUM_SINGLE(AC97_STAC_STEREO_MIC, 2, 1, stac9766_stereo_mic);
static const DECLARE_TLV_DB_LINEAR(master_tlv, -4600, 0);
static const DECLARE_TLV_DB_LINEAR(record_tlv, 0, 2250);
static const DECLARE_TLV_DB_LINEAR(beep_tlv, -4500, 0);
static const DECLARE_TLV_DB_LINEAR(mix_tlv, -3450, 1200);
static const struct snd_kcontrol_new stac9766_snd_ac97_controls[] = {
SOC_DOUBLE_TLV("Speaker Volume", AC97_MASTER, 8, 0, 31, 1, master_tlv),
SOC_SINGLE("Speaker Switch", AC97_MASTER, 15, 1, 1),
SOC_DOUBLE_TLV("Headphone Volume", AC97_HEADPHONE, 8, 0, 31, 1,
master_tlv),
SOC_SINGLE("Headphone Switch", AC97_HEADPHONE, 15, 1, 1),
SOC_SINGLE_TLV("Mono Out Volume", AC97_MASTER_MONO, 0, 31, 1,
master_tlv),
SOC_SINGLE("Mono Out Switch", AC97_MASTER_MONO, 15, 1, 1),
SOC_DOUBLE_TLV("Record Volume", AC97_REC_GAIN, 8, 0, 15, 0, record_tlv),
SOC_SINGLE("Record Switch", AC97_REC_GAIN, 15, 1, 1),
SOC_SINGLE_TLV("Beep Volume", AC97_PC_BEEP, 1, 15, 1, beep_tlv),
SOC_SINGLE("Beep Switch", AC97_PC_BEEP, 15, 1, 1),
SOC_SINGLE("Beep Frequency", AC97_PC_BEEP, 5, 127, 1),
SOC_SINGLE_TLV("Phone Volume", AC97_PHONE, 0, 31, 1, mix_tlv),
SOC_SINGLE("Phone Switch", AC97_PHONE, 15, 1, 1),
SOC_ENUM("Mic Boost1", stac9766_boost1_enum),
SOC_ENUM("Mic Boost2", stac9766_boost2_enum),
SOC_SINGLE_TLV("Mic Volume", AC97_MIC, 0, 31, 1, mix_tlv),
SOC_SINGLE("Mic Switch", AC97_MIC, 15, 1, 1),
SOC_ENUM("Stereo Mic", stac9766_stereo_mic_enum),
SOC_DOUBLE_TLV("Line Volume", AC97_LINE, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("Line Switch", AC97_LINE, 15, 1, 1),
SOC_DOUBLE_TLV("CD Volume", AC97_CD, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("CD Switch", AC97_CD, 15, 1, 1),
SOC_DOUBLE_TLV("AUX Volume", AC97_AUX, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("AUX Switch", AC97_AUX, 15, 1, 1),
SOC_DOUBLE_TLV("Video Volume", AC97_VIDEO, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("Video Switch", AC97_VIDEO, 15, 1, 1),
SOC_DOUBLE_TLV("DAC Volume", AC97_PCM, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("DAC Switch", AC97_PCM, 15, 1, 1),
SOC_SINGLE("Loopback Test Switch", AC97_GENERAL_PURPOSE, 7, 1, 0),
SOC_SINGLE("3D Volume", AC97_3D_CONTROL, 3, 2, 1),
SOC_SINGLE("3D Switch", AC97_GENERAL_PURPOSE, 13, 1, 0),
SOC_ENUM("SPDIF Mux", stac9766_SPDIF_enum),
SOC_ENUM("Mic1/2 Mux", stac9766_mic_enum),
SOC_ENUM("Record All Mux", stac9766_record_all_enum),
SOC_ENUM("Record Mux", stac9766_record_enum),
SOC_ENUM("Mono Mux", stac9766_mono_enum),
SOC_ENUM("Pop Bypass Mux", stac9766_popbypass_enum),
};
static int stac9766_ac97_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int val)
{
u16 *cache = codec->reg_cache;
if (reg > AC97_STAC_PAGE0) {
stac9766_ac97_write(codec, AC97_INT_PAGING, 0);
soc_ac97_ops.write(codec->ac97, reg, val);
stac9766_ac97_write(codec, AC97_INT_PAGING, 1);
return 0;
}
if (reg / 2 >= ARRAY_SIZE(stac9766_reg))
return -EIO;
soc_ac97_ops.write(codec->ac97, reg, val);
cache[reg / 2] = val;
return 0;
}
static unsigned int stac9766_ac97_read(struct snd_soc_codec *codec,
unsigned int reg)
{
u16 val = 0, *cache = codec->reg_cache;
if (reg > AC97_STAC_PAGE0) {
stac9766_ac97_write(codec, AC97_INT_PAGING, 0);
val = soc_ac97_ops.read(codec->ac97, reg - AC97_STAC_PAGE0);
stac9766_ac97_write(codec, AC97_INT_PAGING, 1);
return val;
}
if (reg / 2 >= ARRAY_SIZE(stac9766_reg))
return -EIO;
if (reg == AC97_RESET || reg == AC97_GPIO_STATUS ||
reg == AC97_INT_PAGING || reg == AC97_VENDOR_ID1 ||
reg == AC97_VENDOR_ID2) {
val = soc_ac97_ops.read(codec->ac97, reg);
return val;
}
return cache[reg / 2];
}
static int ac97_analog_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned short reg, vra;
vra = stac9766_ac97_read(codec, AC97_EXTENDED_STATUS);
vra |= 0x1; /* enable variable rate audio */
vra &= ~0x4; /* disable SPDIF output */
stac9766_ac97_write(codec, AC97_EXTENDED_STATUS, vra);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
reg = AC97_PCM_FRONT_DAC_RATE;
else
reg = AC97_PCM_LR_ADC_RATE;
return stac9766_ac97_write(codec, reg, runtime->rate);
}
static int ac97_digital_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned short reg, vra;
stac9766_ac97_write(codec, AC97_SPDIF, 0x2002);
vra = stac9766_ac97_read(codec, AC97_EXTENDED_STATUS);
vra |= 0x5; /* Enable VRA and SPDIF out */
stac9766_ac97_write(codec, AC97_EXTENDED_STATUS, vra);
reg = AC97_PCM_FRONT_DAC_RATE;
return stac9766_ac97_write(codec, reg, runtime->rate);
}
static int stac9766_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
switch (level) {
case SND_SOC_BIAS_ON: /* full On */
case SND_SOC_BIAS_PREPARE: /* partial On */
case SND_SOC_BIAS_STANDBY: /* Off, with power */
stac9766_ac97_write(codec, AC97_POWERDOWN, 0x0000);
break;
case SND_SOC_BIAS_OFF: /* Off, without power */
/* disable everything including AC link */
stac9766_ac97_write(codec, AC97_POWERDOWN, 0xffff);
break;
}
codec->dapm.bias_level = level;
return 0;
}
static int stac9766_reset(struct snd_soc_codec *codec, int try_warm)
{
if (try_warm && soc_ac97_ops.warm_reset) {
soc_ac97_ops.warm_reset(codec->ac97);
if (stac9766_ac97_read(codec, 0) == stac9766_reg[0])
return 1;
}
soc_ac97_ops.reset(codec->ac97);
if (soc_ac97_ops.warm_reset)
soc_ac97_ops.warm_reset(codec->ac97);
if (stac9766_ac97_read(codec, 0) != stac9766_reg[0])
return -EIO;
return 0;
}
static int stac9766_codec_suspend(struct snd_soc_codec *codec)
{
stac9766_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int stac9766_codec_resume(struct snd_soc_codec *codec)
{
u16 id, reset;
reset = 0;
/* give the codec an AC97 warm reset to start the link */
reset:
if (reset > 5) {
printk(KERN_ERR "stac9766 failed to resume");
return -EIO;
}
codec->ac97->bus->ops->warm_reset(codec->ac97);
id = soc_ac97_ops.read(codec->ac97, AC97_VENDOR_ID2);
if (id != 0x4c13) {
stac9766_reset(codec, 0);
reset++;
goto reset;
}
stac9766_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static const struct snd_soc_dai_ops stac9766_dai_ops_analog = {
.prepare = ac97_analog_prepare,
};
static const struct snd_soc_dai_ops stac9766_dai_ops_digital = {
.prepare = ac97_digital_prepare,
};
static struct snd_soc_dai_driver stac9766_dai[] = {
{
.name = "stac9766-hifi-analog",
.ac97_control = 1,
/* stream cababilities */
.playback = {
.stream_name = "stac9766 analog",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SND_SOC_STD_AC97_FMTS,
},
.capture = {
.stream_name = "stac9766 analog",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SND_SOC_STD_AC97_FMTS,
},
/* alsa ops */
.ops = &stac9766_dai_ops_analog,
},
{
.name = "stac9766-hifi-IEC958",
.ac97_control = 1,
/* stream cababilities */
.playback = {
.stream_name = "stac9766 IEC958",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_32000 | \
SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FORMAT_IEC958_SUBFRAME_BE,
},
/* alsa ops */
.ops = &stac9766_dai_ops_digital,
}
};
static int stac9766_codec_probe(struct snd_soc_codec *codec)
{
int ret = 0;
printk(KERN_INFO "STAC9766 SoC Audio Codec %s\n", STAC9766_VERSION);
ret = snd_soc_new_ac97_codec(codec, &soc_ac97_ops, 0);
if (ret < 0)
goto codec_err;
/* do a cold reset for the controller and then try
* a warm reset followed by an optional cold reset for codec */
stac9766_reset(codec, 0);
ret = stac9766_reset(codec, 1);
if (ret < 0) {
printk(KERN_ERR "Failed to reset STAC9766: AC97 link error\n");
goto codec_err;
}
stac9766_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
snd_soc_add_codec_controls(codec, stac9766_snd_ac97_controls,
ARRAY_SIZE(stac9766_snd_ac97_controls));
return 0;
codec_err:
snd_soc_free_ac97_codec(codec);
return ret;
}
static int stac9766_codec_remove(struct snd_soc_codec *codec)
{
snd_soc_free_ac97_codec(codec);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_stac9766 = {
.write = stac9766_ac97_write,
.read = stac9766_ac97_read,
.set_bias_level = stac9766_set_bias_level,
.probe = stac9766_codec_probe,
.remove = stac9766_codec_remove,
.suspend = stac9766_codec_suspend,
.resume = stac9766_codec_resume,
.reg_cache_size = ARRAY_SIZE(stac9766_reg),
.reg_word_size = sizeof(u16),
.reg_cache_step = 2,
.reg_cache_default = stac9766_reg,
};
static int stac9766_probe(struct platform_device *pdev)
{
return snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_stac9766, stac9766_dai, ARRAY_SIZE(stac9766_dai));
}
static int stac9766_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver stac9766_codec_driver = {
.driver = {
.name = "stac9766-codec",
.owner = THIS_MODULE,
},
.probe = stac9766_probe,
.remove = stac9766_remove,
};
module_platform_driver(stac9766_codec_driver);
MODULE_DESCRIPTION("ASoC stac9766 driver");
MODULE_AUTHOR("Jon Smirl <jonsmirl@gmail.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
przemo27/mid712-kernel | drivers/staging/msm/tv_ntsc.c | 3015 | 3886 | /* Copyright (c) 2008-2009, 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <mach/hardware.h>
#include <linux/io.h>
#include <asm/system.h>
#include <asm/mach-types.h>
#include <linux/semaphore.h>
#include <linux/uaccess.h>
#include <linux/clk.h>
#include "msm_fb.h"
#include "tvenc.h"
#define NTSC_TV_DIMENSION_WIDTH 720
#define NTSC_TV_DIMENSION_HEIGHT 480
static int ntsc_off(struct platform_device *pdev);
static int ntsc_on(struct platform_device *pdev);
static int ntsc_on(struct platform_device *pdev)
{
uint32 reg = 0;
int ret = 0;
struct msm_fb_data_type *mfd;
mfd = platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
TV_OUT(TV_ENC_CTL, 0); /* disable TV encoder */
if (mfd->panel.id == NTSC_M) {
/* Cr gain 11, Cb gain C6, y_gain 97 */
TV_OUT(TV_GAIN, 0x0081B697);
} else {
/* Cr gain 11, Cb gain C6, y_gain 97 */
TV_OUT(TV_GAIN, 0x008bc4a3);
reg |= TVENC_CTL_NTSCJ_MODE;
}
TV_OUT(TV_CGMS, 0x0);
/* NTSC Timing */
TV_OUT(TV_SYNC_1, 0x0020009e);
TV_OUT(TV_SYNC_2, 0x011306B4);
TV_OUT(TV_SYNC_3, 0x0006000C);
TV_OUT(TV_SYNC_4, 0x0028020D);
TV_OUT(TV_SYNC_5, 0x005E02FB);
TV_OUT(TV_SYNC_6, 0x0006000C);
TV_OUT(TV_SYNC_7, 0x00000012);
TV_OUT(TV_BURST_V1, 0x0013020D);
TV_OUT(TV_BURST_V2, 0x0014020C);
TV_OUT(TV_BURST_V3, 0x0013020D);
TV_OUT(TV_BURST_V4, 0x0014020C);
TV_OUT(TV_BURST_H, 0x00AE00F2);
TV_OUT(TV_SOL_REQ_ODD, 0x00280208);
TV_OUT(TV_SOL_REQ_EVEN, 0x00290209);
reg |= TVENC_CTL_TV_MODE_NTSC_M_PAL60;
reg |= TVENC_CTL_Y_FILTER_EN |
TVENC_CTL_CR_FILTER_EN |
TVENC_CTL_CB_FILTER_EN | TVENC_CTL_SINX_FILTER_EN;
#ifdef CONFIG_FB_MSM_TVOUT_SVIDEO
reg |= TVENC_CTL_S_VIDEO_EN;
#endif
TV_OUT(TV_LEVEL, 0x00000000); /* DC offset to 0. */
TV_OUT(TV_OFFSET, 0x008080f0);
#ifdef CONFIG_FB_MSM_MDP31
TV_OUT(TV_DAC_INTF, 0x29);
#endif
TV_OUT(TV_ENC_CTL, reg);
reg |= TVENC_CTL_ENC_EN;
TV_OUT(TV_ENC_CTL, reg);
return ret;
}
static int ntsc_off(struct platform_device *pdev)
{
TV_OUT(TV_ENC_CTL, 0); /* disable TV encoder */
return 0;
}
static int __init ntsc_probe(struct platform_device *pdev)
{
msm_fb_add_device(pdev);
return 0;
}
static struct platform_driver this_driver = {
.probe = ntsc_probe,
.driver = {
.name = "tv_ntsc",
},
};
static struct msm_fb_panel_data ntsc_panel_data = {
.panel_info.xres = NTSC_TV_DIMENSION_WIDTH,
.panel_info.yres = NTSC_TV_DIMENSION_HEIGHT,
.panel_info.type = TV_PANEL,
.panel_info.pdest = DISPLAY_1,
.panel_info.wait_cycle = 0,
.panel_info.bpp = 16,
.panel_info.fb_num = 2,
.on = ntsc_on,
.off = ntsc_off,
};
static struct platform_device this_device = {
.name = "tv_ntsc",
.id = 0,
.dev = {
.platform_data = &ntsc_panel_data,
}
};
static int __init ntsc_init(void)
{
int ret;
ret = platform_driver_register(&this_driver);
if (!ret) {
ret = platform_device_register(&this_device);
if (ret)
platform_driver_unregister(&this_driver);
}
return ret;
}
module_init(ntsc_init); | gpl-2.0 |
AmperificSuperKANG/lge_kernel_loki | drivers/staging/comedi/drivers/ni_labpc.c | 3527 | 62708 | /*
comedi/drivers/ni_labpc.c
Driver for National Instruments Lab-PC series boards and compatibles
Copyright (C) 2001, 2002, 2003 Frank Mori Hess <fmhess@users.sourceforge.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************
*/
/*
Driver: ni_labpc
Description: National Instruments Lab-PC (& compatibles)
Author: Frank Mori Hess <fmhess@users.sourceforge.net>
Devices: [National Instruments] Lab-PC-1200 (labpc-1200),
Lab-PC-1200AI (labpc-1200ai), Lab-PC+ (lab-pc+), PCI-1200 (ni_labpc)
Status: works
Tested with lab-pc-1200. For the older Lab-PC+, not all input ranges
and analog references will work, the available ranges/arefs will
depend on how you have configured the jumpers on your board
(see your owner's manual).
Kernel-level ISA plug-and-play support for the lab-pc-1200
boards has not
yet been added to the driver, mainly due to the fact that
I don't know the device id numbers. If you have one
of these boards,
please file a bug report at http://comedi.org/
so I can get the necessary information from you.
The 1200 series boards have onboard calibration dacs for correcting
analog input/output offsets and gains. The proper settings for these
caldacs are stored on the board's eeprom. To read the caldac values
from the eeprom and store them into a file that can be then be used by
comedilib, use the comedi_calibrate program.
Configuration options - ISA boards:
[0] - I/O port base address
[1] - IRQ (optional, required for timed or externally triggered conversions)
[2] - DMA channel (optional)
Configuration options - PCI boards:
[0] - bus (optional)
[1] - slot (optional)
The Lab-pc+ has quirky chanlist requirements
when scanning multiple channels. Multiple channel scan
sequence must start at highest channel, then decrement down to
channel 0. The rest of the cards can scan down like lab-pc+ or scan
up from channel zero. Chanlists consisting of all one channel
are also legal, and allow you to pace conversions in bursts.
*/
/*
NI manuals:
341309a (labpc-1200 register manual)
340914a (pci-1200)
320502b (lab-pc+)
*/
#undef LABPC_DEBUG
/* #define LABPC_DEBUG enable debugging messages */
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/io.h>
#include "../comedidev.h"
#include <linux/delay.h>
#include <asm/dma.h>
#include "8253.h"
#include "8255.h"
#include "mite.h"
#include "comedi_fc.h"
#include "ni_labpc.h"
#define DRV_NAME "ni_labpc"
/* size of io region used by board */
#define LABPC_SIZE 32
/* 2 MHz master clock */
#define LABPC_TIMER_BASE 500
/* Registers for the lab-pc+ */
/* write-only registers */
#define COMMAND1_REG 0x0
#define ADC_GAIN_MASK (0x7 << 4)
#define ADC_CHAN_BITS(x) ((x) & 0x7)
/* enables multi channel scans */
#define ADC_SCAN_EN_BIT 0x80
#define COMMAND2_REG 0x1
/* enable pretriggering (used in conjunction with SWTRIG) */
#define PRETRIG_BIT 0x1
/* enable paced conversions on external trigger */
#define HWTRIG_BIT 0x2
/* enable paced conversions */
#define SWTRIG_BIT 0x4
/* use two cascaded counters for pacing */
#define CASCADE_BIT 0x8
#define DAC_PACED_BIT(channel) (0x40 << ((channel) & 0x1))
#define COMMAND3_REG 0x2
/* enable dma transfers */
#define DMA_EN_BIT 0x1
/* enable interrupts for 8255 */
#define DIO_INTR_EN_BIT 0x2
/* enable dma terminal count interrupt */
#define DMATC_INTR_EN_BIT 0x4
/* enable timer interrupt */
#define TIMER_INTR_EN_BIT 0x8
/* enable error interrupt */
#define ERR_INTR_EN_BIT 0x10
/* enable fifo not empty interrupt */
#define ADC_FNE_INTR_EN_BIT 0x20
#define ADC_CONVERT_REG 0x3
#define DAC_LSB_REG(channel) (0x4 + 2 * ((channel) & 0x1))
#define DAC_MSB_REG(channel) (0x5 + 2 * ((channel) & 0x1))
#define ADC_CLEAR_REG 0x8
#define DMATC_CLEAR_REG 0xa
#define TIMER_CLEAR_REG 0xc
/* 1200 boards only */
#define COMMAND6_REG 0xe
/* select ground or common-mode reference */
#define ADC_COMMON_BIT 0x1
/* adc unipolar */
#define ADC_UNIP_BIT 0x2
/* dac unipolar */
#define DAC_UNIP_BIT(channel) (0x4 << ((channel) & 0x1))
/* enable fifo half full interrupt */
#define ADC_FHF_INTR_EN_BIT 0x20
/* enable interrupt on end of hardware count */
#define A1_INTR_EN_BIT 0x40
/* scan up from channel zero instead of down to zero */
#define ADC_SCAN_UP_BIT 0x80
#define COMMAND4_REG 0xf
/* enables 'interval' scanning */
#define INTERVAL_SCAN_EN_BIT 0x1
/* enables external signal on counter b1 output to trigger scan */
#define EXT_SCAN_EN_BIT 0x2
/* chooses direction (output or input) for EXTCONV* line */
#define EXT_CONVERT_OUT_BIT 0x4
/* chooses differential inputs for adc (in conjunction with board jumper) */
#define ADC_DIFF_BIT 0x8
#define EXT_CONVERT_DISABLE_BIT 0x10
/* 1200 boards only, calibration stuff */
#define COMMAND5_REG 0x1c
/* enable eeprom for write */
#define EEPROM_WRITE_UNPROTECT_BIT 0x4
/* enable dithering */
#define DITHER_EN_BIT 0x8
/* load calibration dac */
#define CALDAC_LOAD_BIT 0x10
/* serial clock - rising edge writes, falling edge reads */
#define SCLOCK_BIT 0x20
/* serial data bit for writing to eeprom or calibration dacs */
#define SDATA_BIT 0x40
/* enable eeprom for read/write */
#define EEPROM_EN_BIT 0x80
#define INTERVAL_COUNT_REG 0x1e
#define INTERVAL_LOAD_REG 0x1f
#define INTERVAL_LOAD_BITS 0x1
/* read-only registers */
#define STATUS1_REG 0x0
/* data is available in fifo */
#define DATA_AVAIL_BIT 0x1
/* overrun has occurred */
#define OVERRUN_BIT 0x2
/* fifo overflow */
#define OVERFLOW_BIT 0x4
/* timer interrupt has occurred */
#define TIMER_BIT 0x8
/* dma terminal count has occurred */
#define DMATC_BIT 0x10
/* external trigger has occurred */
#define EXT_TRIG_BIT 0x40
/* 1200 boards only */
#define STATUS2_REG 0x1d
/* programmable eeprom serial output */
#define EEPROM_OUT_BIT 0x1
/* counter A1 terminal count */
#define A1_TC_BIT 0x2
/* fifo not half full */
#define FNHF_BIT 0x4
#define ADC_FIFO_REG 0xa
#define DIO_BASE_REG 0x10
#define COUNTER_A_BASE_REG 0x14
#define COUNTER_A_CONTROL_REG (COUNTER_A_BASE_REG + 0x3)
/* check modes put conversion pacer output in harmless state (a0 mode 2) */
#define INIT_A0_BITS 0x14
/* put hardware conversion counter output in harmless state (a1 mode 0) */
#define INIT_A1_BITS 0x70
#define COUNTER_B_BASE_REG 0x18
static int labpc_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static int labpc_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
static irqreturn_t labpc_interrupt(int irq, void *d);
static int labpc_drain_fifo(struct comedi_device *dev);
#ifdef CONFIG_ISA_DMA_API
static void labpc_drain_dma(struct comedi_device *dev);
static void handle_isa_dma(struct comedi_device *dev);
#endif
static void labpc_drain_dregs(struct comedi_device *dev);
static int labpc_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd);
static int labpc_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
static int labpc_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_calib_read_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_calib_write_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_eeprom_read_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int labpc_eeprom_write_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data);
static void labpc_adc_timing(struct comedi_device *dev, struct comedi_cmd *cmd);
#ifdef CONFIG_ISA_DMA_API
static unsigned int labpc_suggest_transfer_size(struct comedi_cmd cmd);
#endif
#ifdef CONFIG_COMEDI_PCI_DRIVERS
static int labpc_find_device(struct comedi_device *dev, int bus, int slot);
#endif
static int labpc_dio_mem_callback(int dir, int port, int data,
unsigned long arg);
static void labpc_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits);
static unsigned int labpc_serial_in(struct comedi_device *dev);
static unsigned int labpc_eeprom_read(struct comedi_device *dev,
unsigned int address);
static unsigned int labpc_eeprom_read_status(struct comedi_device *dev);
static int labpc_eeprom_write(struct comedi_device *dev,
unsigned int address,
unsigned int value);
static void write_caldac(struct comedi_device *dev, unsigned int channel,
unsigned int value);
enum scan_mode {
MODE_SINGLE_CHAN,
MODE_SINGLE_CHAN_INTERVAL,
MODE_MULT_CHAN_UP,
MODE_MULT_CHAN_DOWN,
};
/* analog input ranges */
#define NUM_LABPC_PLUS_AI_RANGES 16
/* indicates unipolar ranges */
static const int labpc_plus_is_unipolar[NUM_LABPC_PLUS_AI_RANGES] = {
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
};
/* map range index to gain bits */
static const int labpc_plus_ai_gain_bits[NUM_LABPC_PLUS_AI_RANGES] = {
0x00,
0x10,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
0x00,
0x10,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
};
static const struct comedi_lrange range_labpc_plus_ai = {
NUM_LABPC_PLUS_AI_RANGES,
{
BIP_RANGE(5),
BIP_RANGE(4),
BIP_RANGE(2.5),
BIP_RANGE(1),
BIP_RANGE(0.5),
BIP_RANGE(0.25),
BIP_RANGE(0.1),
BIP_RANGE(0.05),
UNI_RANGE(10),
UNI_RANGE(8),
UNI_RANGE(5),
UNI_RANGE(2),
UNI_RANGE(1),
UNI_RANGE(0.5),
UNI_RANGE(0.2),
UNI_RANGE(0.1),
}
};
#define NUM_LABPC_1200_AI_RANGES 14
/* indicates unipolar ranges */
const int labpc_1200_is_unipolar[NUM_LABPC_1200_AI_RANGES] = {
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
};
EXPORT_SYMBOL_GPL(labpc_1200_is_unipolar);
/* map range index to gain bits */
const int labpc_1200_ai_gain_bits[NUM_LABPC_1200_AI_RANGES] = {
0x00,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
0x00,
0x20,
0x30,
0x40,
0x50,
0x60,
0x70,
};
EXPORT_SYMBOL_GPL(labpc_1200_ai_gain_bits);
const struct comedi_lrange range_labpc_1200_ai = {
NUM_LABPC_1200_AI_RANGES,
{
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1),
BIP_RANGE(0.5),
BIP_RANGE(0.25),
BIP_RANGE(0.1),
BIP_RANGE(0.05),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2),
UNI_RANGE(1),
UNI_RANGE(0.5),
UNI_RANGE(0.2),
UNI_RANGE(0.1),
}
};
EXPORT_SYMBOL_GPL(range_labpc_1200_ai);
/* analog output ranges */
#define AO_RANGE_IS_UNIPOLAR 0x1
static const struct comedi_lrange range_labpc_ao = {
2,
{
BIP_RANGE(5),
UNI_RANGE(10),
}
};
/* functions that do inb/outb and readb/writeb so we can use
* function pointers to decide which to use */
static inline unsigned int labpc_inb(unsigned long address)
{
return inb(address);
}
static inline void labpc_outb(unsigned int byte, unsigned long address)
{
outb(byte, address);
}
static inline unsigned int labpc_readb(unsigned long address)
{
return readb((void *)address);
}
static inline void labpc_writeb(unsigned int byte, unsigned long address)
{
writeb(byte, (void *)address);
}
static const struct labpc_board_struct labpc_boards[] = {
{
.name = "lab-pc-1200",
.ai_speed = 10000,
.bustype = isa_bustype,
.register_layout = labpc_1200_layout,
.has_ao = 1,
.ai_range_table = &range_labpc_1200_ai,
.ai_range_code = labpc_1200_ai_gain_bits,
.ai_range_is_unipolar = labpc_1200_is_unipolar,
.ai_scan_up = 1,
.memory_mapped_io = 0,
},
{
.name = "lab-pc-1200ai",
.ai_speed = 10000,
.bustype = isa_bustype,
.register_layout = labpc_1200_layout,
.has_ao = 0,
.ai_range_table = &range_labpc_1200_ai,
.ai_range_code = labpc_1200_ai_gain_bits,
.ai_range_is_unipolar = labpc_1200_is_unipolar,
.ai_scan_up = 1,
.memory_mapped_io = 0,
},
{
.name = "lab-pc+",
.ai_speed = 12000,
.bustype = isa_bustype,
.register_layout = labpc_plus_layout,
.has_ao = 1,
.ai_range_table = &range_labpc_plus_ai,
.ai_range_code = labpc_plus_ai_gain_bits,
.ai_range_is_unipolar = labpc_plus_is_unipolar,
.ai_scan_up = 0,
.memory_mapped_io = 0,
},
#ifdef CONFIG_COMEDI_PCI_DRIVERS
{
.name = "pci-1200",
.device_id = 0x161,
.ai_speed = 10000,
.bustype = pci_bustype,
.register_layout = labpc_1200_layout,
.has_ao = 1,
.ai_range_table = &range_labpc_1200_ai,
.ai_range_code = labpc_1200_ai_gain_bits,
.ai_range_is_unipolar = labpc_1200_is_unipolar,
.ai_scan_up = 1,
.memory_mapped_io = 1,
},
/* dummy entry so pci board works when comedi_config is passed driver name */
{
.name = DRV_NAME,
.bustype = pci_bustype,
},
#endif
};
/*
* Useful for shorthand access to the particular board structure
*/
#define thisboard ((struct labpc_board_struct *)dev->board_ptr)
/* size in bytes of dma buffer */
static const int dma_buffer_size = 0xff00;
/* 2 bytes per sample */
static const int sample_size = 2;
#define devpriv ((struct labpc_private *)dev->private)
static struct comedi_driver driver_labpc = {
.driver_name = DRV_NAME,
.module = THIS_MODULE,
.attach = labpc_attach,
.detach = labpc_common_detach,
.num_names = ARRAY_SIZE(labpc_boards),
.board_name = &labpc_boards[0].name,
.offset = sizeof(struct labpc_board_struct),
};
#ifdef CONFIG_COMEDI_PCI_DRIVERS
static DEFINE_PCI_DEVICE_TABLE(labpc_pci_table) = {
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x161)},
{0}
};
MODULE_DEVICE_TABLE(pci, labpc_pci_table);
#endif /* CONFIG_COMEDI_PCI_DRIVERS */
static inline int labpc_counter_load(struct comedi_device *dev,
unsigned long base_address,
unsigned int counter_number,
unsigned int count, unsigned int mode)
{
if (thisboard->memory_mapped_io)
return i8254_mm_load((void *)base_address, 0, counter_number,
count, mode);
else
return i8254_load(base_address, 0, counter_number, count, mode);
}
int labpc_common_attach(struct comedi_device *dev, unsigned long iobase,
unsigned int irq, unsigned int dma_chan)
{
struct comedi_subdevice *s;
int i;
unsigned long isr_flags;
#ifdef CONFIG_ISA_DMA_API
unsigned long dma_flags;
#endif
short lsb, msb;
printk(KERN_ERR "comedi%d: ni_labpc: %s, io 0x%lx", dev->minor,
thisboard->name,
iobase);
if (irq)
printk(", irq %u", irq);
if (dma_chan)
printk(", dma %u", dma_chan);
printk("\n");
if (iobase == 0) {
printk(KERN_ERR "io base address is zero!\n");
return -EINVAL;
}
/* request io regions for isa boards */
if (thisboard->bustype == isa_bustype) {
/* check if io addresses are available */
if (!request_region(iobase, LABPC_SIZE,
driver_labpc.driver_name)) {
printk(KERN_ERR "I/O port conflict\n");
return -EIO;
}
}
dev->iobase = iobase;
if (thisboard->memory_mapped_io) {
devpriv->read_byte = labpc_readb;
devpriv->write_byte = labpc_writeb;
} else {
devpriv->read_byte = labpc_inb;
devpriv->write_byte = labpc_outb;
}
/* initialize board's command registers */
devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
devpriv->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
if (thisboard->register_layout == labpc_1200_layout) {
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
devpriv->write_byte(devpriv->command6_bits,
dev->iobase + COMMAND6_REG);
}
/* grab our IRQ */
if (irq) {
isr_flags = 0;
if (thisboard->bustype == pci_bustype
|| thisboard->bustype == pcmcia_bustype)
isr_flags |= IRQF_SHARED;
if (request_irq(irq, labpc_interrupt, isr_flags,
driver_labpc.driver_name, dev)) {
printk(KERN_ERR "unable to allocate irq %u\n", irq);
return -EINVAL;
}
}
dev->irq = irq;
#ifdef CONFIG_ISA_DMA_API
/* grab dma channel */
if (dma_chan > 3) {
printk(KERN_ERR " invalid dma channel %u\n", dma_chan);
return -EINVAL;
} else if (dma_chan) {
/* allocate dma buffer */
devpriv->dma_buffer =
kmalloc(dma_buffer_size, GFP_KERNEL | GFP_DMA);
if (devpriv->dma_buffer == NULL) {
printk(KERN_ERR " failed to allocate dma buffer\n");
return -ENOMEM;
}
if (request_dma(dma_chan, driver_labpc.driver_name)) {
printk(KERN_ERR " failed to allocate dma channel %u\n",
dma_chan);
return -EINVAL;
}
devpriv->dma_chan = dma_chan;
dma_flags = claim_dma_lock();
disable_dma(devpriv->dma_chan);
set_dma_mode(devpriv->dma_chan, DMA_MODE_READ);
release_dma_lock(dma_flags);
}
#endif
dev->board_name = thisboard->name;
if (alloc_subdevices(dev, 5) < 0)
return -ENOMEM;
/* analog input subdevice */
s = dev->subdevices + 0;
dev->read_subdev = s;
s->type = COMEDI_SUBD_AI;
s->subdev_flags =
SDF_READABLE | SDF_GROUND | SDF_COMMON | SDF_DIFF | SDF_CMD_READ;
s->n_chan = 8;
s->len_chanlist = 8;
s->maxdata = (1 << 12) - 1; /* 12 bit resolution */
s->range_table = thisboard->ai_range_table;
s->do_cmd = labpc_ai_cmd;
s->do_cmdtest = labpc_ai_cmdtest;
s->insn_read = labpc_ai_rinsn;
s->cancel = labpc_cancel;
/* analog output */
s = dev->subdevices + 1;
if (thisboard->has_ao) {
/*
* Could provide command support, except it only has a
* one sample hardware buffer for analog output and no
* underrun flag.
*/
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_GROUND;
s->n_chan = NUM_AO_CHAN;
s->maxdata = (1 << 12) - 1; /* 12 bit resolution */
s->range_table = &range_labpc_ao;
s->insn_read = labpc_ao_rinsn;
s->insn_write = labpc_ao_winsn;
/* initialize analog outputs to a known value */
for (i = 0; i < s->n_chan; i++) {
devpriv->ao_value[i] = s->maxdata / 2;
lsb = devpriv->ao_value[i] & 0xff;
msb = (devpriv->ao_value[i] >> 8) & 0xff;
devpriv->write_byte(lsb, dev->iobase + DAC_LSB_REG(i));
devpriv->write_byte(msb, dev->iobase + DAC_MSB_REG(i));
}
} else {
s->type = COMEDI_SUBD_UNUSED;
}
/* 8255 dio */
s = dev->subdevices + 2;
/* if board uses io memory we have to give a custom callback
* function to the 8255 driver */
if (thisboard->memory_mapped_io)
subdev_8255_init(dev, s, labpc_dio_mem_callback,
(unsigned long)(dev->iobase + DIO_BASE_REG));
else
subdev_8255_init(dev, s, NULL, dev->iobase + DIO_BASE_REG);
/* calibration subdevices for boards that have one */
s = dev->subdevices + 3;
if (thisboard->register_layout == labpc_1200_layout) {
s->type = COMEDI_SUBD_CALIB;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
s->n_chan = 16;
s->maxdata = 0xff;
s->insn_read = labpc_calib_read_insn;
s->insn_write = labpc_calib_write_insn;
for (i = 0; i < s->n_chan; i++)
write_caldac(dev, i, s->maxdata / 2);
} else
s->type = COMEDI_SUBD_UNUSED;
/* EEPROM */
s = dev->subdevices + 4;
if (thisboard->register_layout == labpc_1200_layout) {
s->type = COMEDI_SUBD_MEMORY;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
s->n_chan = EEPROM_SIZE;
s->maxdata = 0xff;
s->insn_read = labpc_eeprom_read_insn;
s->insn_write = labpc_eeprom_write_insn;
for (i = 0; i < EEPROM_SIZE; i++)
devpriv->eeprom_data[i] = labpc_eeprom_read(dev, i);
#ifdef LABPC_DEBUG
printk(KERN_ERR " eeprom:");
for (i = 0; i < EEPROM_SIZE; i++)
printk(" %i:0x%x ", i, devpriv->eeprom_data[i]);
printk("\n");
#endif
} else
s->type = COMEDI_SUBD_UNUSED;
return 0;
}
EXPORT_SYMBOL_GPL(labpc_common_attach);
static int labpc_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
unsigned long iobase = 0;
unsigned int irq = 0;
unsigned int dma_chan = 0;
#ifdef CONFIG_COMEDI_PCI_DRIVERS
int retval;
#endif
/* allocate and initialize dev->private */
if (alloc_private(dev, sizeof(struct labpc_private)) < 0)
return -ENOMEM;
/* get base address, irq etc. based on bustype */
switch (thisboard->bustype) {
case isa_bustype:
#ifdef CONFIG_ISA_DMA_API
iobase = it->options[0];
irq = it->options[1];
dma_chan = it->options[2];
#else
printk(KERN_ERR " this driver has not been built with ISA DMA "
"support.\n");
return -EINVAL;
#endif
break;
case pci_bustype:
#ifdef CONFIG_COMEDI_PCI_DRIVERS
retval = labpc_find_device(dev, it->options[0], it->options[1]);
if (retval < 0)
return retval;
retval = mite_setup(devpriv->mite);
if (retval < 0)
return retval;
iobase = (unsigned long)devpriv->mite->daq_io_addr;
irq = mite_irq(devpriv->mite);
#else
printk(KERN_ERR " this driver has not been built with PCI "
"support.\n");
return -EINVAL;
#endif
break;
case pcmcia_bustype:
printk
(" this driver does not support pcmcia cards, use ni_labpc_cs.o\n");
return -EINVAL;
break;
default:
printk(KERN_ERR "bug! couldn't determine board type\n");
return -EINVAL;
break;
}
return labpc_common_attach(dev, iobase, irq, dma_chan);
}
/* adapted from ni_pcimio for finding mite based boards (pc-1200) */
#ifdef CONFIG_COMEDI_PCI_DRIVERS
static int labpc_find_device(struct comedi_device *dev, int bus, int slot)
{
struct mite_struct *mite;
int i;
for (mite = mite_devices; mite; mite = mite->next) {
if (mite->used)
continue;
/* if bus/slot are specified then make sure we have the right bus/slot */
if (bus || slot) {
if (bus != mite->pcidev->bus->number
|| slot != PCI_SLOT(mite->pcidev->devfn))
continue;
}
for (i = 0; i < driver_labpc.num_names; i++) {
if (labpc_boards[i].bustype != pci_bustype)
continue;
if (mite_device_id(mite) == labpc_boards[i].device_id) {
devpriv->mite = mite;
/* fixup board pointer, in case we were using the dummy "ni_labpc" entry */
dev->board_ptr = &labpc_boards[i];
return 0;
}
}
}
printk(KERN_ERR "no device found\n");
mite_list_devices();
return -EIO;
}
#endif
int labpc_common_detach(struct comedi_device *dev)
{
printk(KERN_ERR "comedi%d: ni_labpc: detach\n", dev->minor);
if (dev->subdevices)
subdev_8255_cleanup(dev, dev->subdevices + 2);
#ifdef CONFIG_ISA_DMA_API
/* only free stuff if it has been allocated by _attach */
kfree(devpriv->dma_buffer);
if (devpriv->dma_chan)
free_dma(devpriv->dma_chan);
#endif
if (dev->irq)
free_irq(dev->irq, dev);
if (thisboard->bustype == isa_bustype && dev->iobase)
release_region(dev->iobase, LABPC_SIZE);
#ifdef CONFIG_COMEDI_PCI_DRIVERS
if (devpriv->mite)
mite_unsetup(devpriv->mite);
#endif
return 0;
};
EXPORT_SYMBOL_GPL(labpc_common_detach);
static void labpc_clear_adc_fifo(const struct comedi_device *dev)
{
devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
}
static int labpc_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
unsigned long flags;
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
devpriv->command3_bits = 0;
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
return 0;
}
static enum scan_mode labpc_ai_scan_mode(const struct comedi_cmd *cmd)
{
if (cmd->chanlist_len == 1)
return MODE_SINGLE_CHAN;
/* chanlist may be NULL during cmdtest. */
if (cmd->chanlist == NULL)
return MODE_MULT_CHAN_UP;
if (CR_CHAN(cmd->chanlist[0]) == CR_CHAN(cmd->chanlist[1]))
return MODE_SINGLE_CHAN_INTERVAL;
if (CR_CHAN(cmd->chanlist[0]) < CR_CHAN(cmd->chanlist[1]))
return MODE_MULT_CHAN_UP;
if (CR_CHAN(cmd->chanlist[0]) > CR_CHAN(cmd->chanlist[1]))
return MODE_MULT_CHAN_DOWN;
printk(KERN_ERR "ni_labpc: bug! this should never happen\n");
return 0;
}
static int labpc_ai_chanlist_invalid(const struct comedi_device *dev,
const struct comedi_cmd *cmd)
{
int mode, channel, range, aref, i;
if (cmd->chanlist == NULL)
return 0;
mode = labpc_ai_scan_mode(cmd);
if (mode == MODE_SINGLE_CHAN)
return 0;
if (mode == MODE_SINGLE_CHAN_INTERVAL) {
if (cmd->chanlist_len > 0xff) {
comedi_error(dev,
"ni_labpc: chanlist too long for single channel interval mode\n");
return 1;
}
}
channel = CR_CHAN(cmd->chanlist[0]);
range = CR_RANGE(cmd->chanlist[0]);
aref = CR_AREF(cmd->chanlist[0]);
for (i = 0; i < cmd->chanlist_len; i++) {
switch (mode) {
case MODE_SINGLE_CHAN_INTERVAL:
if (CR_CHAN(cmd->chanlist[i]) != channel) {
comedi_error(dev,
"channel scanning order specified in chanlist is not supported by hardware.\n");
return 1;
}
break;
case MODE_MULT_CHAN_UP:
if (CR_CHAN(cmd->chanlist[i]) != i) {
comedi_error(dev,
"channel scanning order specified in chanlist is not supported by hardware.\n");
return 1;
}
break;
case MODE_MULT_CHAN_DOWN:
if (CR_CHAN(cmd->chanlist[i]) !=
cmd->chanlist_len - i - 1) {
comedi_error(dev,
"channel scanning order specified in chanlist is not supported by hardware.\n");
return 1;
}
break;
default:
printk(KERN_ERR "ni_labpc: bug! in chanlist check\n");
return 1;
break;
}
if (CR_RANGE(cmd->chanlist[i]) != range) {
comedi_error(dev,
"entries in chanlist must all have the same range\n");
return 1;
}
if (CR_AREF(cmd->chanlist[i]) != aref) {
comedi_error(dev,
"entries in chanlist must all have the same reference\n");
return 1;
}
}
return 0;
}
static int labpc_use_continuous_mode(const struct comedi_cmd *cmd)
{
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN)
return 1;
if (cmd->scan_begin_src == TRIG_FOLLOW)
return 1;
return 0;
}
static unsigned int labpc_ai_convert_period(const struct comedi_cmd *cmd)
{
if (cmd->convert_src != TRIG_TIMER)
return 0;
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN &&
cmd->scan_begin_src == TRIG_TIMER)
return cmd->scan_begin_arg;
return cmd->convert_arg;
}
static void labpc_set_ai_convert_period(struct comedi_cmd *cmd, unsigned int ns)
{
if (cmd->convert_src != TRIG_TIMER)
return;
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN &&
cmd->scan_begin_src == TRIG_TIMER) {
cmd->scan_begin_arg = ns;
if (cmd->convert_arg > cmd->scan_begin_arg)
cmd->convert_arg = cmd->scan_begin_arg;
} else
cmd->convert_arg = ns;
}
static unsigned int labpc_ai_scan_period(const struct comedi_cmd *cmd)
{
if (cmd->scan_begin_src != TRIG_TIMER)
return 0;
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN &&
cmd->convert_src == TRIG_TIMER)
return 0;
return cmd->scan_begin_arg;
}
static void labpc_set_ai_scan_period(struct comedi_cmd *cmd, unsigned int ns)
{
if (cmd->scan_begin_src != TRIG_TIMER)
return;
if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN &&
cmd->convert_src == TRIG_TIMER)
return;
cmd->scan_begin_arg = ns;
}
static int labpc_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
int err = 0;
int tmp, tmp2;
int stop_mask;
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW | TRIG_EXT;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_FOLLOW | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
stop_mask = TRIG_COUNT | TRIG_NONE;
if (thisboard->register_layout == labpc_1200_layout)
stop_mask |= TRIG_EXT;
cmd->stop_src &= stop_mask;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually compatible */
if (cmd->start_src != TRIG_NOW && cmd->start_src != TRIG_EXT)
err++;
if (cmd->scan_begin_src != TRIG_TIMER &&
cmd->scan_begin_src != TRIG_FOLLOW &&
cmd->scan_begin_src != TRIG_EXT)
err++;
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->stop_src != TRIG_COUNT &&
cmd->stop_src != TRIG_EXT && cmd->stop_src != TRIG_NONE)
err++;
/* can't have external stop and start triggers at once */
if (cmd->start_src == TRIG_EXT && cmd->stop_src == TRIG_EXT)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_arg == TRIG_NOW && cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
if (!cmd->chanlist_len)
err++;
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < thisboard->ai_speed) {
cmd->convert_arg = thisboard->ai_speed;
err++;
}
}
/* make sure scan timing is not too fast */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->convert_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->chanlist_len) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->chanlist_len;
err++;
}
if (cmd->scan_begin_arg <
thisboard->ai_speed * cmd->chanlist_len) {
cmd->scan_begin_arg =
thisboard->ai_speed * cmd->chanlist_len;
err++;
}
}
/* stop source */
switch (cmd->stop_src) {
case TRIG_COUNT:
if (!cmd->stop_arg) {
cmd->stop_arg = 1;
err++;
}
break;
case TRIG_NONE:
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
break;
/*
* TRIG_EXT doesn't care since it doesn't
* trigger off a numbered channel
*/
default:
break;
}
if (err)
return 3;
/* step 4: fix up any arguments */
tmp = cmd->convert_arg;
tmp2 = cmd->scan_begin_arg;
labpc_adc_timing(dev, cmd);
if (tmp != cmd->convert_arg || tmp2 != cmd->scan_begin_arg)
err++;
if (err)
return 4;
if (labpc_ai_chanlist_invalid(dev, cmd))
return 5;
return 0;
}
static int labpc_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
int channel, range, aref;
#ifdef CONFIG_ISA_DMA_API
unsigned long irq_flags;
#endif
int ret;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
enum transfer_type xfer;
unsigned long flags;
if (!dev->irq) {
comedi_error(dev, "no irq assigned, cannot perform command");
return -1;
}
range = CR_RANGE(cmd->chanlist[0]);
aref = CR_AREF(cmd->chanlist[0]);
/* make sure board is disabled before setting up acquisition */
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
devpriv->command3_bits = 0;
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
/* initialize software conversion count */
if (cmd->stop_src == TRIG_COUNT)
devpriv->count = cmd->stop_arg * cmd->chanlist_len;
/* setup hardware conversion counter */
if (cmd->stop_src == TRIG_EXT) {
/*
* load counter a1 with count of 3
* (pc+ manual says this is minimum allowed) using mode 0
*/
ret = labpc_counter_load(dev, dev->iobase + COUNTER_A_BASE_REG,
1, 3, 0);
if (ret < 0) {
comedi_error(dev, "error loading counter a1");
return -1;
}
} else /*
* otherwise, just put a1 in mode 0
* with no count to set its output low
*/
devpriv->write_byte(INIT_A1_BITS,
dev->iobase + COUNTER_A_CONTROL_REG);
#ifdef CONFIG_ISA_DMA_API
/* figure out what method we will use to transfer data */
if (devpriv->dma_chan && /* need a dma channel allocated */
/*
* dma unsafe at RT priority,
* and too much setup time for TRIG_WAKE_EOS for
*/
(cmd->flags & (TRIG_WAKE_EOS | TRIG_RT)) == 0 &&
/* only available on the isa boards */
thisboard->bustype == isa_bustype) {
xfer = isa_dma_transfer;
/* pc-plus has no fifo-half full interrupt */
} else
#endif
if (thisboard->register_layout == labpc_1200_layout &&
/* wake-end-of-scan should interrupt on fifo not empty */
(cmd->flags & TRIG_WAKE_EOS) == 0 &&
/* make sure we are taking more than just a few points */
(cmd->stop_src != TRIG_COUNT || devpriv->count > 256)) {
xfer = fifo_half_full_transfer;
} else
xfer = fifo_not_empty_transfer;
devpriv->current_transfer = xfer;
/* setup command6 register for 1200 boards */
if (thisboard->register_layout == labpc_1200_layout) {
/* reference inputs to ground or common? */
if (aref != AREF_GROUND)
devpriv->command6_bits |= ADC_COMMON_BIT;
else
devpriv->command6_bits &= ~ADC_COMMON_BIT;
/* bipolar or unipolar range? */
if (thisboard->ai_range_is_unipolar[range])
devpriv->command6_bits |= ADC_UNIP_BIT;
else
devpriv->command6_bits &= ~ADC_UNIP_BIT;
/* interrupt on fifo half full? */
if (xfer == fifo_half_full_transfer)
devpriv->command6_bits |= ADC_FHF_INTR_EN_BIT;
else
devpriv->command6_bits &= ~ADC_FHF_INTR_EN_BIT;
/* enable interrupt on counter a1 terminal count? */
if (cmd->stop_src == TRIG_EXT)
devpriv->command6_bits |= A1_INTR_EN_BIT;
else
devpriv->command6_bits &= ~A1_INTR_EN_BIT;
/* are we scanning up or down through channels? */
if (labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_UP)
devpriv->command6_bits |= ADC_SCAN_UP_BIT;
else
devpriv->command6_bits &= ~ADC_SCAN_UP_BIT;
/* write to register */
devpriv->write_byte(devpriv->command6_bits,
dev->iobase + COMMAND6_REG);
}
/* setup channel list, etc (command1 register) */
devpriv->command1_bits = 0;
if (labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_UP)
channel = CR_CHAN(cmd->chanlist[cmd->chanlist_len - 1]);
else
channel = CR_CHAN(cmd->chanlist[0]);
/* munge channel bits for differential / scan disabled mode */
if (labpc_ai_scan_mode(cmd) != MODE_SINGLE_CHAN && aref == AREF_DIFF)
channel *= 2;
devpriv->command1_bits |= ADC_CHAN_BITS(channel);
devpriv->command1_bits |= thisboard->ai_range_code[range];
devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
/* manual says to set scan enable bit on second pass */
if (labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_UP ||
labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_DOWN) {
devpriv->command1_bits |= ADC_SCAN_EN_BIT;
/* need a brief delay before enabling scan, or scan
* list will get screwed when you switch
* between scan up to scan down mode - dunno why */
udelay(1);
devpriv->write_byte(devpriv->command1_bits,
dev->iobase + COMMAND1_REG);
}
/* setup any external triggering/pacing (command4 register) */
devpriv->command4_bits = 0;
if (cmd->convert_src != TRIG_EXT)
devpriv->command4_bits |= EXT_CONVERT_DISABLE_BIT;
/* XXX should discard first scan when using interval scanning
* since manual says it is not synced with scan clock */
if (labpc_use_continuous_mode(cmd) == 0) {
devpriv->command4_bits |= INTERVAL_SCAN_EN_BIT;
if (cmd->scan_begin_src == TRIG_EXT)
devpriv->command4_bits |= EXT_SCAN_EN_BIT;
}
/* single-ended/differential */
if (aref == AREF_DIFF)
devpriv->command4_bits |= ADC_DIFF_BIT;
devpriv->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
devpriv->write_byte(cmd->chanlist_len,
dev->iobase + INTERVAL_COUNT_REG);
/* load count */
devpriv->write_byte(INTERVAL_LOAD_BITS,
dev->iobase + INTERVAL_LOAD_REG);
if (cmd->convert_src == TRIG_TIMER || cmd->scan_begin_src == TRIG_TIMER) {
/* set up pacing */
labpc_adc_timing(dev, cmd);
/* load counter b0 in mode 3 */
ret = labpc_counter_load(dev, dev->iobase + COUNTER_B_BASE_REG,
0, devpriv->divisor_b0, 3);
if (ret < 0) {
comedi_error(dev, "error loading counter b0");
return -1;
}
}
/* set up conversion pacing */
if (labpc_ai_convert_period(cmd)) {
/* load counter a0 in mode 2 */
ret = labpc_counter_load(dev, dev->iobase + COUNTER_A_BASE_REG,
0, devpriv->divisor_a0, 2);
if (ret < 0) {
comedi_error(dev, "error loading counter a0");
return -1;
}
} else
devpriv->write_byte(INIT_A0_BITS,
dev->iobase + COUNTER_A_CONTROL_REG);
/* set up scan pacing */
if (labpc_ai_scan_period(cmd)) {
/* load counter b1 in mode 2 */
ret = labpc_counter_load(dev, dev->iobase + COUNTER_B_BASE_REG,
1, devpriv->divisor_b1, 2);
if (ret < 0) {
comedi_error(dev, "error loading counter b1");
return -1;
}
}
labpc_clear_adc_fifo(dev);
#ifdef CONFIG_ISA_DMA_API
/* set up dma transfer */
if (xfer == isa_dma_transfer) {
irq_flags = claim_dma_lock();
disable_dma(devpriv->dma_chan);
/* clear flip-flop to make sure 2-byte registers for
* count and address get set correctly */
clear_dma_ff(devpriv->dma_chan);
set_dma_addr(devpriv->dma_chan,
virt_to_bus(devpriv->dma_buffer));
/* set appropriate size of transfer */
devpriv->dma_transfer_size = labpc_suggest_transfer_size(*cmd);
if (cmd->stop_src == TRIG_COUNT &&
devpriv->count * sample_size < devpriv->dma_transfer_size) {
devpriv->dma_transfer_size =
devpriv->count * sample_size;
}
set_dma_count(devpriv->dma_chan, devpriv->dma_transfer_size);
enable_dma(devpriv->dma_chan);
release_dma_lock(irq_flags);
/* enable board's dma */
devpriv->command3_bits |= DMA_EN_BIT | DMATC_INTR_EN_BIT;
} else
devpriv->command3_bits &= ~DMA_EN_BIT & ~DMATC_INTR_EN_BIT;
#endif
/* enable error interrupts */
devpriv->command3_bits |= ERR_INTR_EN_BIT;
/* enable fifo not empty interrupt? */
if (xfer == fifo_not_empty_transfer)
devpriv->command3_bits |= ADC_FNE_INTR_EN_BIT;
else
devpriv->command3_bits &= ~ADC_FNE_INTR_EN_BIT;
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
/* startup acquisition */
/* command2 reg */
/* use 2 cascaded counters for pacing */
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits |= CASCADE_BIT;
switch (cmd->start_src) {
case TRIG_EXT:
devpriv->command2_bits |= HWTRIG_BIT;
devpriv->command2_bits &= ~PRETRIG_BIT & ~SWTRIG_BIT;
break;
case TRIG_NOW:
devpriv->command2_bits |= SWTRIG_BIT;
devpriv->command2_bits &= ~PRETRIG_BIT & ~HWTRIG_BIT;
break;
default:
comedi_error(dev, "bug with start_src");
return -1;
break;
}
switch (cmd->stop_src) {
case TRIG_EXT:
devpriv->command2_bits |= HWTRIG_BIT | PRETRIG_BIT;
break;
case TRIG_COUNT:
case TRIG_NONE:
break;
default:
comedi_error(dev, "bug with stop_src");
return -1;
}
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
return 0;
}
/* interrupt service routine */
static irqreturn_t labpc_interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
struct comedi_subdevice *s = dev->read_subdev;
struct comedi_async *async;
struct comedi_cmd *cmd;
if (dev->attached == 0) {
comedi_error(dev, "premature interrupt");
return IRQ_HANDLED;
}
async = s->async;
cmd = &async->cmd;
async->events = 0;
/* read board status */
devpriv->status1_bits = devpriv->read_byte(dev->iobase + STATUS1_REG);
if (thisboard->register_layout == labpc_1200_layout)
devpriv->status2_bits =
devpriv->read_byte(dev->iobase + STATUS2_REG);
if ((devpriv->status1_bits & (DMATC_BIT | TIMER_BIT | OVERFLOW_BIT |
OVERRUN_BIT | DATA_AVAIL_BIT)) == 0
&& (devpriv->status2_bits & A1_TC_BIT) == 0
&& (devpriv->status2_bits & FNHF_BIT)) {
return IRQ_NONE;
}
if (devpriv->status1_bits & OVERRUN_BIT) {
/* clear error interrupt */
devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
comedi_event(dev, s);
comedi_error(dev, "overrun");
return IRQ_HANDLED;
}
#ifdef CONFIG_ISA_DMA_API
if (devpriv->current_transfer == isa_dma_transfer) {
/*
* if a dma terminal count of external stop trigger
* has occurred
*/
if (devpriv->status1_bits & DMATC_BIT ||
(thisboard->register_layout == labpc_1200_layout
&& devpriv->status2_bits & A1_TC_BIT)) {
handle_isa_dma(dev);
}
} else
#endif
labpc_drain_fifo(dev);
if (devpriv->status1_bits & TIMER_BIT) {
comedi_error(dev, "handled timer interrupt?");
/* clear it */
devpriv->write_byte(0x1, dev->iobase + TIMER_CLEAR_REG);
}
if (devpriv->status1_bits & OVERFLOW_BIT) {
/* clear error interrupt */
devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
comedi_event(dev, s);
comedi_error(dev, "overflow");
return IRQ_HANDLED;
}
/* handle external stop trigger */
if (cmd->stop_src == TRIG_EXT) {
if (devpriv->status2_bits & A1_TC_BIT) {
labpc_drain_dregs(dev);
labpc_cancel(dev, s);
async->events |= COMEDI_CB_EOA;
}
}
/* TRIG_COUNT end of acquisition */
if (cmd->stop_src == TRIG_COUNT) {
if (devpriv->count == 0) {
labpc_cancel(dev, s);
async->events |= COMEDI_CB_EOA;
}
}
comedi_event(dev, s);
return IRQ_HANDLED;
}
/* read all available samples from ai fifo */
static int labpc_drain_fifo(struct comedi_device *dev)
{
unsigned int lsb, msb;
short data;
struct comedi_async *async = dev->read_subdev->async;
const int timeout = 10000;
unsigned int i;
devpriv->status1_bits = devpriv->read_byte(dev->iobase + STATUS1_REG);
for (i = 0; (devpriv->status1_bits & DATA_AVAIL_BIT) && i < timeout;
i++) {
/* quit if we have all the data we want */
if (async->cmd.stop_src == TRIG_COUNT) {
if (devpriv->count == 0)
break;
devpriv->count--;
}
lsb = devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
msb = devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
data = (msb << 8) | lsb;
cfc_write_to_buffer(dev->read_subdev, data);
devpriv->status1_bits =
devpriv->read_byte(dev->iobase + STATUS1_REG);
}
if (i == timeout) {
comedi_error(dev, "ai timeout, fifo never empties");
async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
return -1;
}
return 0;
}
#ifdef CONFIG_ISA_DMA_API
static void labpc_drain_dma(struct comedi_device *dev)
{
struct comedi_subdevice *s = dev->read_subdev;
struct comedi_async *async = s->async;
int status;
unsigned long flags;
unsigned int max_points, num_points, residue, leftover;
int i;
status = devpriv->status1_bits;
flags = claim_dma_lock();
disable_dma(devpriv->dma_chan);
/* clear flip-flop to make sure 2-byte registers for
* count and address get set correctly */
clear_dma_ff(devpriv->dma_chan);
/* figure out how many points to read */
max_points = devpriv->dma_transfer_size / sample_size;
/* residue is the number of points left to be done on the dma
* transfer. It should always be zero at this point unless
* the stop_src is set to external triggering.
*/
residue = get_dma_residue(devpriv->dma_chan) / sample_size;
num_points = max_points - residue;
if (devpriv->count < num_points && async->cmd.stop_src == TRIG_COUNT)
num_points = devpriv->count;
/* figure out how many points will be stored next time */
leftover = 0;
if (async->cmd.stop_src != TRIG_COUNT) {
leftover = devpriv->dma_transfer_size / sample_size;
} else if (devpriv->count > num_points) {
leftover = devpriv->count - num_points;
if (leftover > max_points)
leftover = max_points;
}
/* write data to comedi buffer */
for (i = 0; i < num_points; i++)
cfc_write_to_buffer(s, devpriv->dma_buffer[i]);
if (async->cmd.stop_src == TRIG_COUNT)
devpriv->count -= num_points;
/* set address and count for next transfer */
set_dma_addr(devpriv->dma_chan, virt_to_bus(devpriv->dma_buffer));
set_dma_count(devpriv->dma_chan, leftover * sample_size);
release_dma_lock(flags);
async->events |= COMEDI_CB_BLOCK;
}
static void handle_isa_dma(struct comedi_device *dev)
{
labpc_drain_dma(dev);
enable_dma(devpriv->dma_chan);
/* clear dma tc interrupt */
devpriv->write_byte(0x1, dev->iobase + DMATC_CLEAR_REG);
}
#endif
/* makes sure all data acquired by board is transferred to comedi (used
* when acquisition is terminated by stop_src == TRIG_EXT). */
static void labpc_drain_dregs(struct comedi_device *dev)
{
#ifdef CONFIG_ISA_DMA_API
if (devpriv->current_transfer == isa_dma_transfer)
labpc_drain_dma(dev);
#endif
labpc_drain_fifo(dev);
}
static int labpc_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i, n;
int chan, range;
int lsb, msb;
int timeout = 1000;
unsigned long flags;
/* disable timed conversions */
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
/* disable interrupt generation and dma */
devpriv->command3_bits = 0;
devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
/* set gain and channel */
devpriv->command1_bits = 0;
chan = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
devpriv->command1_bits |= thisboard->ai_range_code[range];
/* munge channel bits for differential/scan disabled mode */
if (CR_AREF(insn->chanspec) == AREF_DIFF)
chan *= 2;
devpriv->command1_bits |= ADC_CHAN_BITS(chan);
devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
/* setup command6 register for 1200 boards */
if (thisboard->register_layout == labpc_1200_layout) {
/* reference inputs to ground or common? */
if (CR_AREF(insn->chanspec) != AREF_GROUND)
devpriv->command6_bits |= ADC_COMMON_BIT;
else
devpriv->command6_bits &= ~ADC_COMMON_BIT;
/* bipolar or unipolar range? */
if (thisboard->ai_range_is_unipolar[range])
devpriv->command6_bits |= ADC_UNIP_BIT;
else
devpriv->command6_bits &= ~ADC_UNIP_BIT;
/* don't interrupt on fifo half full */
devpriv->command6_bits &= ~ADC_FHF_INTR_EN_BIT;
/* don't enable interrupt on counter a1 terminal count? */
devpriv->command6_bits &= ~A1_INTR_EN_BIT;
/* write to register */
devpriv->write_byte(devpriv->command6_bits,
dev->iobase + COMMAND6_REG);
}
/* setup command4 register */
devpriv->command4_bits = 0;
devpriv->command4_bits |= EXT_CONVERT_DISABLE_BIT;
/* single-ended/differential */
if (CR_AREF(insn->chanspec) == AREF_DIFF)
devpriv->command4_bits |= ADC_DIFF_BIT;
devpriv->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
/*
* initialize pacer counter output to make sure it doesn't
* cause any problems
*/
devpriv->write_byte(INIT_A0_BITS, dev->iobase + COUNTER_A_CONTROL_REG);
labpc_clear_adc_fifo(dev);
for (n = 0; n < insn->n; n++) {
/* trigger conversion */
devpriv->write_byte(0x1, dev->iobase + ADC_CONVERT_REG);
for (i = 0; i < timeout; i++) {
if (devpriv->read_byte(dev->iobase +
STATUS1_REG) & DATA_AVAIL_BIT)
break;
udelay(1);
}
if (i == timeout) {
comedi_error(dev, "timeout");
return -ETIME;
}
lsb = devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
msb = devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
data[n] = (msb << 8) | lsb;
}
return n;
}
/* analog output insn */
static int labpc_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int channel, range;
unsigned long flags;
int lsb, msb;
channel = CR_CHAN(insn->chanspec);
/* turn off pacing of analog output channel */
/* note: hardware bug in daqcard-1200 means pacing cannot
* be independently enabled/disabled for its the two channels */
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->command2_bits &= ~DAC_PACED_BIT(channel);
devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
/* set range */
if (thisboard->register_layout == labpc_1200_layout) {
range = CR_RANGE(insn->chanspec);
if (range & AO_RANGE_IS_UNIPOLAR)
devpriv->command6_bits |= DAC_UNIP_BIT(channel);
else
devpriv->command6_bits &= ~DAC_UNIP_BIT(channel);
/* write to register */
devpriv->write_byte(devpriv->command6_bits,
dev->iobase + COMMAND6_REG);
}
/* send data */
lsb = data[0] & 0xff;
msb = (data[0] >> 8) & 0xff;
devpriv->write_byte(lsb, dev->iobase + DAC_LSB_REG(channel));
devpriv->write_byte(msb, dev->iobase + DAC_MSB_REG(channel));
/* remember value for readback */
devpriv->ao_value[channel] = data[0];
return 1;
}
/* analog output readback insn */
static int labpc_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[0] = devpriv->ao_value[CR_CHAN(insn->chanspec)];
return 1;
}
static int labpc_calib_read_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[0] = devpriv->caldac[CR_CHAN(insn->chanspec)];
return 1;
}
static int labpc_calib_write_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int channel = CR_CHAN(insn->chanspec);
write_caldac(dev, channel, data[0]);
return 1;
}
static int labpc_eeprom_read_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[0] = devpriv->eeprom_data[CR_CHAN(insn->chanspec)];
return 1;
}
static int labpc_eeprom_write_insn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int channel = CR_CHAN(insn->chanspec);
int ret;
/* only allow writes to user area of eeprom */
if (channel < 16 || channel > 127) {
printk
("eeprom writes are only allowed to channels 16 through 127 (the pointer and user areas)");
return -EINVAL;
}
ret = labpc_eeprom_write(dev, channel, data[0]);
if (ret < 0)
return ret;
return 1;
}
#ifdef CONFIG_ISA_DMA_API
/* utility function that suggests a dma transfer size in bytes */
static unsigned int labpc_suggest_transfer_size(struct comedi_cmd cmd)
{
unsigned int size;
unsigned int freq;
if (cmd.convert_src == TRIG_TIMER)
freq = 1000000000 / cmd.convert_arg;
/* return some default value */
else
freq = 0xffffffff;
/* make buffer fill in no more than 1/3 second */
size = (freq / 3) * sample_size;
/* set a minimum and maximum size allowed */
if (size > dma_buffer_size)
size = dma_buffer_size - dma_buffer_size % sample_size;
else if (size < sample_size)
size = sample_size;
return size;
}
#endif
/* figures out what counter values to use based on command */
static void labpc_adc_timing(struct comedi_device *dev, struct comedi_cmd *cmd)
{
/* max value for 16 bit counter in mode 2 */
const int max_counter_value = 0x10000;
/* min value for 16 bit counter in mode 2 */
const int min_counter_value = 2;
unsigned int base_period;
/*
* if both convert and scan triggers are TRIG_TIMER, then they
* both rely on counter b0
*/
if (labpc_ai_convert_period(cmd) && labpc_ai_scan_period(cmd)) {
/*
* pick the lowest b0 divisor value we can (for maximum input
* clock speed on convert and scan counters)
*/
devpriv->divisor_b0 = (labpc_ai_scan_period(cmd) - 1) /
(LABPC_TIMER_BASE * max_counter_value) + 1;
if (devpriv->divisor_b0 < min_counter_value)
devpriv->divisor_b0 = min_counter_value;
if (devpriv->divisor_b0 > max_counter_value)
devpriv->divisor_b0 = max_counter_value;
base_period = LABPC_TIMER_BASE * devpriv->divisor_b0;
/* set a0 for conversion frequency and b1 for scan frequency */
switch (cmd->flags & TRIG_ROUND_MASK) {
default:
case TRIG_ROUND_NEAREST:
devpriv->divisor_a0 =
(labpc_ai_convert_period(cmd) +
(base_period / 2)) / base_period;
devpriv->divisor_b1 =
(labpc_ai_scan_period(cmd) +
(base_period / 2)) / base_period;
break;
case TRIG_ROUND_UP:
devpriv->divisor_a0 =
(labpc_ai_convert_period(cmd) + (base_period -
1)) / base_period;
devpriv->divisor_b1 =
(labpc_ai_scan_period(cmd) + (base_period -
1)) / base_period;
break;
case TRIG_ROUND_DOWN:
devpriv->divisor_a0 =
labpc_ai_convert_period(cmd) / base_period;
devpriv->divisor_b1 =
labpc_ai_scan_period(cmd) / base_period;
break;
}
/* make sure a0 and b1 values are acceptable */
if (devpriv->divisor_a0 < min_counter_value)
devpriv->divisor_a0 = min_counter_value;
if (devpriv->divisor_a0 > max_counter_value)
devpriv->divisor_a0 = max_counter_value;
if (devpriv->divisor_b1 < min_counter_value)
devpriv->divisor_b1 = min_counter_value;
if (devpriv->divisor_b1 > max_counter_value)
devpriv->divisor_b1 = max_counter_value;
/* write corrected timings to command */
labpc_set_ai_convert_period(cmd,
base_period * devpriv->divisor_a0);
labpc_set_ai_scan_period(cmd,
base_period * devpriv->divisor_b1);
/*
* if only one TRIG_TIMER is used, we can employ the generic
* cascaded timing functions
*/
} else if (labpc_ai_scan_period(cmd)) {
unsigned int scan_period;
scan_period = labpc_ai_scan_period(cmd);
/*
* calculate cascaded counter values
* that give desired scan timing
*/
i8253_cascade_ns_to_timer_2div(LABPC_TIMER_BASE,
&(devpriv->divisor_b1),
&(devpriv->divisor_b0),
&scan_period,
cmd->flags & TRIG_ROUND_MASK);
labpc_set_ai_scan_period(cmd, scan_period);
} else if (labpc_ai_convert_period(cmd)) {
unsigned int convert_period;
convert_period = labpc_ai_convert_period(cmd);
/*
* calculate cascaded counter values
* that give desired conversion timing
*/
i8253_cascade_ns_to_timer_2div(LABPC_TIMER_BASE,
&(devpriv->divisor_a0),
&(devpriv->divisor_b0),
&convert_period,
cmd->flags & TRIG_ROUND_MASK);
labpc_set_ai_convert_period(cmd, convert_period);
}
}
static int labpc_dio_mem_callback(int dir, int port, int data,
unsigned long iobase)
{
if (dir) {
writeb(data, (void *)(iobase + port));
return 0;
} else {
return readb((void *)(iobase + port));
}
}
/* lowlevel write to eeprom/dac */
static void labpc_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int value_width)
{
int i;
for (i = 1; i <= value_width; i++) {
/* clear serial clock */
devpriv->command5_bits &= ~SCLOCK_BIT;
/* send bits most significant bit first */
if (value & (1 << (value_width - i)))
devpriv->command5_bits |= SDATA_BIT;
else
devpriv->command5_bits &= ~SDATA_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
/* set clock to load bit */
devpriv->command5_bits |= SCLOCK_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
}
}
/* lowlevel read from eeprom */
static unsigned int labpc_serial_in(struct comedi_device *dev)
{
unsigned int value = 0;
int i;
const int value_width = 8; /* number of bits wide values are */
for (i = 1; i <= value_width; i++) {
/* set serial clock */
devpriv->command5_bits |= SCLOCK_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
/* clear clock bit */
devpriv->command5_bits &= ~SCLOCK_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits,
dev->iobase + COMMAND5_REG);
/* read bits most significant bit first */
udelay(1);
devpriv->status2_bits =
devpriv->read_byte(dev->iobase + STATUS2_REG);
if (devpriv->status2_bits & EEPROM_OUT_BIT)
value |= 1 << (value_width - i);
}
return value;
}
static unsigned int labpc_eeprom_read(struct comedi_device *dev,
unsigned int address)
{
unsigned int value;
/* bits to tell eeprom to expect a read */
const int read_instruction = 0x3;
/* 8 bit write lengths to eeprom */
const int write_length = 8;
/* enable read/write to eeprom */
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
/* send read instruction */
labpc_serial_out(dev, read_instruction, write_length);
/* send 8 bit address to read from */
labpc_serial_out(dev, address, write_length);
/* read result */
value = labpc_serial_in(dev);
/* disable read/write to eeprom */
devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
return value;
}
static int labpc_eeprom_write(struct comedi_device *dev,
unsigned int address, unsigned int value)
{
const int write_enable_instruction = 0x6;
const int write_instruction = 0x2;
const int write_length = 8; /* 8 bit write lengths to eeprom */
const int write_in_progress_bit = 0x1;
const int timeout = 10000;
int i;
/* make sure there isn't already a write in progress */
for (i = 0; i < timeout; i++) {
if ((labpc_eeprom_read_status(dev) & write_in_progress_bit) ==
0)
break;
}
if (i == timeout) {
comedi_error(dev, "eeprom write timed out");
return -ETIME;
}
/* update software copy of eeprom */
devpriv->eeprom_data[address] = value;
/* enable read/write to eeprom */
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
/* send write_enable instruction */
labpc_serial_out(dev, write_enable_instruction, write_length);
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
/* send write instruction */
devpriv->command5_bits |= EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
labpc_serial_out(dev, write_instruction, write_length);
/* send 8 bit address to write to */
labpc_serial_out(dev, address, write_length);
/* write value */
labpc_serial_out(dev, value, write_length);
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
/* disable read/write to eeprom */
devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
return 0;
}
static unsigned int labpc_eeprom_read_status(struct comedi_device *dev)
{
unsigned int value;
const int read_status_instruction = 0x5;
const int write_length = 8; /* 8 bit write lengths to eeprom */
/* enable read/write to eeprom */
devpriv->command5_bits &= ~EEPROM_EN_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
/* send read status instruction */
labpc_serial_out(dev, read_status_instruction, write_length);
/* read result */
value = labpc_serial_in(dev);
/* disable read/write to eeprom */
devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
return value;
}
/* writes to 8 bit calibration dacs */
static void write_caldac(struct comedi_device *dev, unsigned int channel,
unsigned int value)
{
if (value == devpriv->caldac[channel])
return;
devpriv->caldac[channel] = value;
/* clear caldac load bit and make sure we don't write to eeprom */
devpriv->command5_bits &=
~CALDAC_LOAD_BIT & ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
/* write 4 bit channel */
labpc_serial_out(dev, channel, 4);
/* write 8 bit caldac value */
labpc_serial_out(dev, value, 8);
/* set and clear caldac bit to load caldac value */
devpriv->command5_bits |= CALDAC_LOAD_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
devpriv->command5_bits &= ~CALDAC_LOAD_BIT;
udelay(1);
devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
}
#ifdef CONFIG_COMEDI_PCI_DRIVERS
static int __devinit driver_labpc_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, driver_labpc.driver_name);
}
static void __devexit driver_labpc_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_labpc_pci_driver = {
.id_table = labpc_pci_table,
.probe = &driver_labpc_pci_probe,
.remove = __devexit_p(&driver_labpc_pci_remove)
};
static int __init driver_labpc_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_labpc);
if (retval < 0)
return retval;
driver_labpc_pci_driver.name = (char *)driver_labpc.driver_name;
return pci_register_driver(&driver_labpc_pci_driver);
}
static void __exit driver_labpc_cleanup_module(void)
{
pci_unregister_driver(&driver_labpc_pci_driver);
comedi_driver_unregister(&driver_labpc);
}
module_init(driver_labpc_init_module);
module_exit(driver_labpc_cleanup_module);
#else
static int __init driver_labpc_init_module(void)
{
return comedi_driver_register(&driver_labpc);
}
static void __exit driver_labpc_cleanup_module(void)
{
comedi_driver_unregister(&driver_labpc);
}
module_init(driver_labpc_init_module);
module_exit(driver_labpc_cleanup_module);
#endif
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
dizgustipated/BOCA-2.6.35.14 | drivers/switch/switch_class.c | 4039 | 4393 | /*
* drivers/switch/switch_class.c
*
* Copyright (C) 2008 Google, Inc.
* Author: Mike Lockwood <lockwood@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/err.h>
#include <linux/switch.h>
struct class *switch_class;
static atomic_t device_count;
static ssize_t state_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_state) {
int ret = sdev->print_state(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%d\n", sdev->state);
}
static ssize_t name_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_name) {
int ret = sdev->print_name(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%s\n", sdev->name);
}
static DEVICE_ATTR(state, S_IRUGO | S_IWUSR, state_show, NULL);
static DEVICE_ATTR(name, S_IRUGO | S_IWUSR, name_show, NULL);
void switch_set_state(struct switch_dev *sdev, int state)
{
char name_buf[120];
char state_buf[120];
char *prop_buf;
char *envp[3];
int env_offset = 0;
int length;
if (sdev->state != state) {
sdev->state = state;
prop_buf = (char *)get_zeroed_page(GFP_KERNEL);
if (prop_buf) {
length = name_show(sdev->dev, NULL, prop_buf);
if (length > 0) {
if (prop_buf[length - 1] == '\n')
prop_buf[length - 1] = 0;
snprintf(name_buf, sizeof(name_buf),
"SWITCH_NAME=%s", prop_buf);
envp[env_offset++] = name_buf;
}
length = state_show(sdev->dev, NULL, prop_buf);
if (length > 0) {
if (prop_buf[length - 1] == '\n')
prop_buf[length - 1] = 0;
snprintf(state_buf, sizeof(state_buf),
"SWITCH_STATE=%s", prop_buf);
envp[env_offset++] = state_buf;
}
envp[env_offset] = NULL;
kobject_uevent_env(&sdev->dev->kobj, KOBJ_CHANGE, envp);
free_page((unsigned long)prop_buf);
} else {
printk(KERN_ERR "out of memory in switch_set_state\n");
kobject_uevent(&sdev->dev->kobj, KOBJ_CHANGE);
}
}
}
EXPORT_SYMBOL_GPL(switch_set_state);
static int create_switch_class(void)
{
if (!switch_class) {
switch_class = class_create(THIS_MODULE, "switch");
if (IS_ERR(switch_class))
return PTR_ERR(switch_class);
atomic_set(&device_count, 0);
}
return 0;
}
int switch_dev_register(struct switch_dev *sdev)
{
int ret;
if (!switch_class) {
ret = create_switch_class();
if (ret < 0)
return ret;
}
sdev->index = atomic_inc_return(&device_count);
sdev->dev = device_create(switch_class, NULL,
MKDEV(0, sdev->index), NULL, sdev->name);
if (IS_ERR(sdev->dev))
return PTR_ERR(sdev->dev);
ret = device_create_file(sdev->dev, &dev_attr_state);
if (ret < 0)
goto err_create_file_1;
ret = device_create_file(sdev->dev, &dev_attr_name);
if (ret < 0)
goto err_create_file_2;
dev_set_drvdata(sdev->dev, sdev);
sdev->state = 0;
return 0;
err_create_file_2:
device_remove_file(sdev->dev, &dev_attr_state);
err_create_file_1:
device_destroy(switch_class, MKDEV(0, sdev->index));
printk(KERN_ERR "switch: Failed to register driver %s\n", sdev->name);
return ret;
}
EXPORT_SYMBOL_GPL(switch_dev_register);
void switch_dev_unregister(struct switch_dev *sdev)
{
device_remove_file(sdev->dev, &dev_attr_name);
device_remove_file(sdev->dev, &dev_attr_state);
device_destroy(switch_class, MKDEV(0, sdev->index));
dev_set_drvdata(sdev->dev, NULL);
}
EXPORT_SYMBOL_GPL(switch_dev_unregister);
static int __init switch_class_init(void)
{
return create_switch_class();
}
static void __exit switch_class_exit(void)
{
class_destroy(switch_class);
}
module_init(switch_class_init);
module_exit(switch_class_exit);
MODULE_AUTHOR("Mike Lockwood <lockwood@android.com>");
MODULE_DESCRIPTION("Switch class driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
aapav01/android_kernel_samsung_ms013g_stock | drivers/net/ethernet/sis/sis190.c | 4807 | 47506 | /*
sis190.c: Silicon Integrated Systems SiS190 ethernet driver
Copyright (c) 2003 K.M. Liu <kmliu@sis.com>
Copyright (c) 2003, 2004 Jeff Garzik <jgarzik@pobox.com>
Copyright (c) 2003, 2004, 2005 Francois Romieu <romieu@fr.zoreil.com>
Based on r8169.c, tg3.c, 8139cp.c, skge.c, epic100.c and SiS 190/191
genuine driver.
This software may be used and distributed according to the terms of
the GNU General Public License (GPL), incorporated herein by reference.
Drivers based on or derived from this code fall under the GPL and must
retain the authorship, copyright and license notice. This file is not
a complete program and may only be used when the entire operating
system is licensed under the GPL.
See the file COPYING in this distribution for more information.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/pci.h>
#include <linux/mii.h>
#include <linux/delay.h>
#include <linux/crc32.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <asm/irq.h>
#define PHY_MAX_ADDR 32
#define PHY_ID_ANY 0x1f
#define MII_REG_ANY 0x1f
#define DRV_VERSION "1.4"
#define DRV_NAME "sis190"
#define SIS190_DRIVER_NAME DRV_NAME " Gigabit Ethernet driver " DRV_VERSION
#define sis190_rx_skb netif_rx
#define sis190_rx_quota(count, quota) count
#define NUM_TX_DESC 64 /* [8..1024] */
#define NUM_RX_DESC 64 /* [8..8192] */
#define TX_RING_BYTES (NUM_TX_DESC * sizeof(struct TxDesc))
#define RX_RING_BYTES (NUM_RX_DESC * sizeof(struct RxDesc))
#define RX_BUF_SIZE 1536
#define RX_BUF_MASK 0xfff8
#define SIS190_REGS_SIZE 0x80
#define SIS190_TX_TIMEOUT (6*HZ)
#define SIS190_PHY_TIMEOUT (10*HZ)
#define SIS190_MSG_DEFAULT (NETIF_MSG_DRV | NETIF_MSG_PROBE | \
NETIF_MSG_LINK | NETIF_MSG_IFUP | \
NETIF_MSG_IFDOWN)
/* Enhanced PHY access register bit definitions */
#define EhnMIIread 0x0000
#define EhnMIIwrite 0x0020
#define EhnMIIdataShift 16
#define EhnMIIpmdShift 6 /* 7016 only */
#define EhnMIIregShift 11
#define EhnMIIreq 0x0010
#define EhnMIInotDone 0x0010
/* Write/read MMIO register */
#define SIS_W8(reg, val) writeb ((val), ioaddr + (reg))
#define SIS_W16(reg, val) writew ((val), ioaddr + (reg))
#define SIS_W32(reg, val) writel ((val), ioaddr + (reg))
#define SIS_R8(reg) readb (ioaddr + (reg))
#define SIS_R16(reg) readw (ioaddr + (reg))
#define SIS_R32(reg) readl (ioaddr + (reg))
#define SIS_PCI_COMMIT() SIS_R32(IntrControl)
enum sis190_registers {
TxControl = 0x00,
TxDescStartAddr = 0x04,
rsv0 = 0x08, // reserved
TxSts = 0x0c, // unused (Control/Status)
RxControl = 0x10,
RxDescStartAddr = 0x14,
rsv1 = 0x18, // reserved
RxSts = 0x1c, // unused
IntrStatus = 0x20,
IntrMask = 0x24,
IntrControl = 0x28,
IntrTimer = 0x2c, // unused (Interrupt Timer)
PMControl = 0x30, // unused (Power Mgmt Control/Status)
rsv2 = 0x34, // reserved
ROMControl = 0x38,
ROMInterface = 0x3c,
StationControl = 0x40,
GMIIControl = 0x44,
GIoCR = 0x48, // unused (GMAC IO Compensation)
GIoCtrl = 0x4c, // unused (GMAC IO Control)
TxMacControl = 0x50,
TxLimit = 0x54, // unused (Tx MAC Timer/TryLimit)
RGDelay = 0x58, // unused (RGMII Tx Internal Delay)
rsv3 = 0x5c, // reserved
RxMacControl = 0x60,
RxMacAddr = 0x62,
RxHashTable = 0x68,
// Undocumented = 0x6c,
RxWolCtrl = 0x70,
RxWolData = 0x74, // unused (Rx WOL Data Access)
RxMPSControl = 0x78, // unused (Rx MPS Control)
rsv4 = 0x7c, // reserved
};
enum sis190_register_content {
/* IntrStatus */
SoftInt = 0x40000000, // unused
Timeup = 0x20000000, // unused
PauseFrame = 0x00080000, // unused
MagicPacket = 0x00040000, // unused
WakeupFrame = 0x00020000, // unused
LinkChange = 0x00010000,
RxQEmpty = 0x00000080,
RxQInt = 0x00000040,
TxQ1Empty = 0x00000020, // unused
TxQ1Int = 0x00000010,
TxQ0Empty = 0x00000008, // unused
TxQ0Int = 0x00000004,
RxHalt = 0x00000002,
TxHalt = 0x00000001,
/* {Rx/Tx}CmdBits */
CmdReset = 0x10,
CmdRxEnb = 0x08, // unused
CmdTxEnb = 0x01,
RxBufEmpty = 0x01, // unused
/* Cfg9346Bits */
Cfg9346_Lock = 0x00, // unused
Cfg9346_Unlock = 0xc0, // unused
/* RxMacControl */
AcceptErr = 0x20, // unused
AcceptRunt = 0x10, // unused
AcceptBroadcast = 0x0800,
AcceptMulticast = 0x0400,
AcceptMyPhys = 0x0200,
AcceptAllPhys = 0x0100,
/* RxConfigBits */
RxCfgFIFOShift = 13,
RxCfgDMAShift = 8, // 0x1a in RxControl ?
/* TxConfigBits */
TxInterFrameGapShift = 24,
TxDMAShift = 8, /* DMA burst value (0-7) is shift this many bits */
LinkStatus = 0x02, // unused
FullDup = 0x01, // unused
/* TBICSRBit */
TBILinkOK = 0x02000000, // unused
};
struct TxDesc {
__le32 PSize;
__le32 status;
__le32 addr;
__le32 size;
};
struct RxDesc {
__le32 PSize;
__le32 status;
__le32 addr;
__le32 size;
};
enum _DescStatusBit {
/* _Desc.status */
OWNbit = 0x80000000, // RXOWN/TXOWN
INTbit = 0x40000000, // RXINT/TXINT
CRCbit = 0x00020000, // CRCOFF/CRCEN
PADbit = 0x00010000, // PREADD/PADEN
/* _Desc.size */
RingEnd = 0x80000000,
/* TxDesc.status */
LSEN = 0x08000000, // TSO ? -- FR
IPCS = 0x04000000,
TCPCS = 0x02000000,
UDPCS = 0x01000000,
BSTEN = 0x00800000,
EXTEN = 0x00400000,
DEFEN = 0x00200000,
BKFEN = 0x00100000,
CRSEN = 0x00080000,
COLEN = 0x00040000,
THOL3 = 0x30000000,
THOL2 = 0x20000000,
THOL1 = 0x10000000,
THOL0 = 0x00000000,
WND = 0x00080000,
TABRT = 0x00040000,
FIFO = 0x00020000,
LINK = 0x00010000,
ColCountMask = 0x0000ffff,
/* RxDesc.status */
IPON = 0x20000000,
TCPON = 0x10000000,
UDPON = 0x08000000,
Wakup = 0x00400000,
Magic = 0x00200000,
Pause = 0x00100000,
DEFbit = 0x00200000,
BCAST = 0x000c0000,
MCAST = 0x00080000,
UCAST = 0x00040000,
/* RxDesc.PSize */
TAGON = 0x80000000,
RxDescCountMask = 0x7f000000, // multi-desc pkt when > 1 ? -- FR
ABORT = 0x00800000,
SHORT = 0x00400000,
LIMIT = 0x00200000,
MIIER = 0x00100000,
OVRUN = 0x00080000,
NIBON = 0x00040000,
COLON = 0x00020000,
CRCOK = 0x00010000,
RxSizeMask = 0x0000ffff
/*
* The asic could apparently do vlan, TSO, jumbo (sis191 only) and
* provide two (unused with Linux) Tx queues. No publicly
* available documentation alas.
*/
};
enum sis190_eeprom_access_register_bits {
EECS = 0x00000001, // unused
EECLK = 0x00000002, // unused
EEDO = 0x00000008, // unused
EEDI = 0x00000004, // unused
EEREQ = 0x00000080,
EEROP = 0x00000200,
EEWOP = 0x00000100 // unused
};
/* EEPROM Addresses */
enum sis190_eeprom_address {
EEPROMSignature = 0x00,
EEPROMCLK = 0x01, // unused
EEPROMInfo = 0x02,
EEPROMMACAddr = 0x03
};
enum sis190_feature {
F_HAS_RGMII = 1,
F_PHY_88E1111 = 2,
F_PHY_BCM5461 = 4
};
struct sis190_private {
void __iomem *mmio_addr;
struct pci_dev *pci_dev;
struct net_device *dev;
spinlock_t lock;
u32 rx_buf_sz;
u32 cur_rx;
u32 cur_tx;
u32 dirty_rx;
u32 dirty_tx;
dma_addr_t rx_dma;
dma_addr_t tx_dma;
struct RxDesc *RxDescRing;
struct TxDesc *TxDescRing;
struct sk_buff *Rx_skbuff[NUM_RX_DESC];
struct sk_buff *Tx_skbuff[NUM_TX_DESC];
struct work_struct phy_task;
struct timer_list timer;
u32 msg_enable;
struct mii_if_info mii_if;
struct list_head first_phy;
u32 features;
u32 negotiated_lpa;
enum {
LNK_OFF,
LNK_ON,
LNK_AUTONEG,
} link_status;
};
struct sis190_phy {
struct list_head list;
int phy_id;
u16 id[2];
u16 status;
u8 type;
};
enum sis190_phy_type {
UNKNOWN = 0x00,
HOME = 0x01,
LAN = 0x02,
MIX = 0x03
};
static struct mii_chip_info {
const char *name;
u16 id[2];
unsigned int type;
u32 feature;
} mii_chip_table[] = {
{ "Atheros PHY", { 0x004d, 0xd010 }, LAN, 0 },
{ "Atheros PHY AR8012", { 0x004d, 0xd020 }, LAN, 0 },
{ "Broadcom PHY BCM5461", { 0x0020, 0x60c0 }, LAN, F_PHY_BCM5461 },
{ "Broadcom PHY AC131", { 0x0143, 0xbc70 }, LAN, 0 },
{ "Agere PHY ET1101B", { 0x0282, 0xf010 }, LAN, 0 },
{ "Marvell PHY 88E1111", { 0x0141, 0x0cc0 }, LAN, F_PHY_88E1111 },
{ "Realtek PHY RTL8201", { 0x0000, 0x8200 }, LAN, 0 },
{ NULL, }
};
static const struct {
const char *name;
} sis_chip_info[] = {
{ "SiS 190 PCI Fast Ethernet adapter" },
{ "SiS 191 PCI Gigabit Ethernet adapter" },
};
static DEFINE_PCI_DEVICE_TABLE(sis190_pci_tbl) = {
{ PCI_DEVICE(PCI_VENDOR_ID_SI, 0x0190), 0, 0, 0 },
{ PCI_DEVICE(PCI_VENDOR_ID_SI, 0x0191), 0, 0, 1 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, sis190_pci_tbl);
static int rx_copybreak = 200;
static struct {
u32 msg_enable;
} debug = { -1 };
MODULE_DESCRIPTION("SiS sis190/191 Gigabit Ethernet driver");
module_param(rx_copybreak, int, 0);
MODULE_PARM_DESC(rx_copybreak, "Copy breakpoint for copy-only-tiny-frames");
module_param_named(debug, debug.msg_enable, int, 0);
MODULE_PARM_DESC(debug, "Debug verbosity level (0=none, ..., 16=all)");
MODULE_AUTHOR("K.M. Liu <kmliu@sis.com>, Ueimor <romieu@fr.zoreil.com>");
MODULE_VERSION(DRV_VERSION);
MODULE_LICENSE("GPL");
static const u32 sis190_intr_mask =
RxQEmpty | RxQInt | TxQ1Int | TxQ0Int | RxHalt | TxHalt | LinkChange;
/*
* Maximum number of multicast addresses to filter (vs. Rx-all-multicast).
* The chips use a 64 element hash table based on the Ethernet CRC.
*/
static const int multicast_filter_limit = 32;
static void __mdio_cmd(void __iomem *ioaddr, u32 ctl)
{
unsigned int i;
SIS_W32(GMIIControl, ctl);
msleep(1);
for (i = 0; i < 100; i++) {
if (!(SIS_R32(GMIIControl) & EhnMIInotDone))
break;
msleep(1);
}
if (i > 99)
pr_err("PHY command failed !\n");
}
static void mdio_write(void __iomem *ioaddr, int phy_id, int reg, int val)
{
__mdio_cmd(ioaddr, EhnMIIreq | EhnMIIwrite |
(((u32) reg) << EhnMIIregShift) | (phy_id << EhnMIIpmdShift) |
(((u32) val) << EhnMIIdataShift));
}
static int mdio_read(void __iomem *ioaddr, int phy_id, int reg)
{
__mdio_cmd(ioaddr, EhnMIIreq | EhnMIIread |
(((u32) reg) << EhnMIIregShift) | (phy_id << EhnMIIpmdShift));
return (u16) (SIS_R32(GMIIControl) >> EhnMIIdataShift);
}
static void __mdio_write(struct net_device *dev, int phy_id, int reg, int val)
{
struct sis190_private *tp = netdev_priv(dev);
mdio_write(tp->mmio_addr, phy_id, reg, val);
}
static int __mdio_read(struct net_device *dev, int phy_id, int reg)
{
struct sis190_private *tp = netdev_priv(dev);
return mdio_read(tp->mmio_addr, phy_id, reg);
}
static u16 mdio_read_latched(void __iomem *ioaddr, int phy_id, int reg)
{
mdio_read(ioaddr, phy_id, reg);
return mdio_read(ioaddr, phy_id, reg);
}
static u16 __devinit sis190_read_eeprom(void __iomem *ioaddr, u32 reg)
{
u16 data = 0xffff;
unsigned int i;
if (!(SIS_R32(ROMControl) & 0x0002))
return 0;
SIS_W32(ROMInterface, EEREQ | EEROP | (reg << 10));
for (i = 0; i < 200; i++) {
if (!(SIS_R32(ROMInterface) & EEREQ)) {
data = (SIS_R32(ROMInterface) & 0xffff0000) >> 16;
break;
}
msleep(1);
}
return data;
}
static void sis190_irq_mask_and_ack(void __iomem *ioaddr)
{
SIS_W32(IntrMask, 0x00);
SIS_W32(IntrStatus, 0xffffffff);
SIS_PCI_COMMIT();
}
static void sis190_asic_down(void __iomem *ioaddr)
{
/* Stop the chip's Tx and Rx DMA processes. */
SIS_W32(TxControl, 0x1a00);
SIS_W32(RxControl, 0x1a00);
sis190_irq_mask_and_ack(ioaddr);
}
static void sis190_mark_as_last_descriptor(struct RxDesc *desc)
{
desc->size |= cpu_to_le32(RingEnd);
}
static inline void sis190_give_to_asic(struct RxDesc *desc, u32 rx_buf_sz)
{
u32 eor = le32_to_cpu(desc->size) & RingEnd;
desc->PSize = 0x0;
desc->size = cpu_to_le32((rx_buf_sz & RX_BUF_MASK) | eor);
wmb();
desc->status = cpu_to_le32(OWNbit | INTbit);
}
static inline void sis190_map_to_asic(struct RxDesc *desc, dma_addr_t mapping,
u32 rx_buf_sz)
{
desc->addr = cpu_to_le32(mapping);
sis190_give_to_asic(desc, rx_buf_sz);
}
static inline void sis190_make_unusable_by_asic(struct RxDesc *desc)
{
desc->PSize = 0x0;
desc->addr = cpu_to_le32(0xdeadbeef);
desc->size &= cpu_to_le32(RingEnd);
wmb();
desc->status = 0x0;
}
static struct sk_buff *sis190_alloc_rx_skb(struct sis190_private *tp,
struct RxDesc *desc)
{
u32 rx_buf_sz = tp->rx_buf_sz;
struct sk_buff *skb;
dma_addr_t mapping;
skb = netdev_alloc_skb(tp->dev, rx_buf_sz);
if (unlikely(!skb))
goto skb_alloc_failed;
mapping = pci_map_single(tp->pci_dev, skb->data, tp->rx_buf_sz,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(tp->pci_dev, mapping))
goto out;
sis190_map_to_asic(desc, mapping, rx_buf_sz);
return skb;
out:
dev_kfree_skb_any(skb);
skb_alloc_failed:
sis190_make_unusable_by_asic(desc);
return NULL;
}
static u32 sis190_rx_fill(struct sis190_private *tp, struct net_device *dev,
u32 start, u32 end)
{
u32 cur;
for (cur = start; cur < end; cur++) {
unsigned int i = cur % NUM_RX_DESC;
if (tp->Rx_skbuff[i])
continue;
tp->Rx_skbuff[i] = sis190_alloc_rx_skb(tp, tp->RxDescRing + i);
if (!tp->Rx_skbuff[i])
break;
}
return cur - start;
}
static bool sis190_try_rx_copy(struct sis190_private *tp,
struct sk_buff **sk_buff, int pkt_size,
dma_addr_t addr)
{
struct sk_buff *skb;
bool done = false;
if (pkt_size >= rx_copybreak)
goto out;
skb = netdev_alloc_skb_ip_align(tp->dev, pkt_size);
if (!skb)
goto out;
pci_dma_sync_single_for_cpu(tp->pci_dev, addr, tp->rx_buf_sz,
PCI_DMA_FROMDEVICE);
skb_copy_to_linear_data(skb, sk_buff[0]->data, pkt_size);
*sk_buff = skb;
done = true;
out:
return done;
}
static inline int sis190_rx_pkt_err(u32 status, struct net_device_stats *stats)
{
#define ErrMask (OVRUN | SHORT | LIMIT | MIIER | NIBON | COLON | ABORT)
if ((status & CRCOK) && !(status & ErrMask))
return 0;
if (!(status & CRCOK))
stats->rx_crc_errors++;
else if (status & OVRUN)
stats->rx_over_errors++;
else if (status & (SHORT | LIMIT))
stats->rx_length_errors++;
else if (status & (MIIER | NIBON | COLON))
stats->rx_frame_errors++;
stats->rx_errors++;
return -1;
}
static int sis190_rx_interrupt(struct net_device *dev,
struct sis190_private *tp, void __iomem *ioaddr)
{
struct net_device_stats *stats = &dev->stats;
u32 rx_left, cur_rx = tp->cur_rx;
u32 delta, count;
rx_left = NUM_RX_DESC + tp->dirty_rx - cur_rx;
rx_left = sis190_rx_quota(rx_left, (u32) dev->quota);
for (; rx_left > 0; rx_left--, cur_rx++) {
unsigned int entry = cur_rx % NUM_RX_DESC;
struct RxDesc *desc = tp->RxDescRing + entry;
u32 status;
if (le32_to_cpu(desc->status) & OWNbit)
break;
status = le32_to_cpu(desc->PSize);
//netif_info(tp, intr, dev, "Rx PSize = %08x\n", status);
if (sis190_rx_pkt_err(status, stats) < 0)
sis190_give_to_asic(desc, tp->rx_buf_sz);
else {
struct sk_buff *skb = tp->Rx_skbuff[entry];
dma_addr_t addr = le32_to_cpu(desc->addr);
int pkt_size = (status & RxSizeMask) - 4;
struct pci_dev *pdev = tp->pci_dev;
if (unlikely(pkt_size > tp->rx_buf_sz)) {
netif_info(tp, intr, dev,
"(frag) status = %08x\n", status);
stats->rx_dropped++;
stats->rx_length_errors++;
sis190_give_to_asic(desc, tp->rx_buf_sz);
continue;
}
if (sis190_try_rx_copy(tp, &skb, pkt_size, addr)) {
pci_dma_sync_single_for_device(pdev, addr,
tp->rx_buf_sz, PCI_DMA_FROMDEVICE);
sis190_give_to_asic(desc, tp->rx_buf_sz);
} else {
pci_unmap_single(pdev, addr, tp->rx_buf_sz,
PCI_DMA_FROMDEVICE);
tp->Rx_skbuff[entry] = NULL;
sis190_make_unusable_by_asic(desc);
}
skb_put(skb, pkt_size);
skb->protocol = eth_type_trans(skb, dev);
sis190_rx_skb(skb);
stats->rx_packets++;
stats->rx_bytes += pkt_size;
if ((status & BCAST) == MCAST)
stats->multicast++;
}
}
count = cur_rx - tp->cur_rx;
tp->cur_rx = cur_rx;
delta = sis190_rx_fill(tp, dev, tp->dirty_rx, tp->cur_rx);
if (!delta && count)
netif_info(tp, intr, dev, "no Rx buffer allocated\n");
tp->dirty_rx += delta;
if ((tp->dirty_rx + NUM_RX_DESC) == tp->cur_rx)
netif_emerg(tp, intr, dev, "Rx buffers exhausted\n");
return count;
}
static void sis190_unmap_tx_skb(struct pci_dev *pdev, struct sk_buff *skb,
struct TxDesc *desc)
{
unsigned int len;
len = skb->len < ETH_ZLEN ? ETH_ZLEN : skb->len;
pci_unmap_single(pdev, le32_to_cpu(desc->addr), len, PCI_DMA_TODEVICE);
memset(desc, 0x00, sizeof(*desc));
}
static inline int sis190_tx_pkt_err(u32 status, struct net_device_stats *stats)
{
#define TxErrMask (WND | TABRT | FIFO | LINK)
if (!unlikely(status & TxErrMask))
return 0;
if (status & WND)
stats->tx_window_errors++;
if (status & TABRT)
stats->tx_aborted_errors++;
if (status & FIFO)
stats->tx_fifo_errors++;
if (status & LINK)
stats->tx_carrier_errors++;
stats->tx_errors++;
return -1;
}
static void sis190_tx_interrupt(struct net_device *dev,
struct sis190_private *tp, void __iomem *ioaddr)
{
struct net_device_stats *stats = &dev->stats;
u32 pending, dirty_tx = tp->dirty_tx;
/*
* It would not be needed if queueing was allowed to be enabled
* again too early (hint: think preempt and unclocked smp systems).
*/
unsigned int queue_stopped;
smp_rmb();
pending = tp->cur_tx - dirty_tx;
queue_stopped = (pending == NUM_TX_DESC);
for (; pending; pending--, dirty_tx++) {
unsigned int entry = dirty_tx % NUM_TX_DESC;
struct TxDesc *txd = tp->TxDescRing + entry;
u32 status = le32_to_cpu(txd->status);
struct sk_buff *skb;
if (status & OWNbit)
break;
skb = tp->Tx_skbuff[entry];
if (likely(sis190_tx_pkt_err(status, stats) == 0)) {
stats->tx_packets++;
stats->tx_bytes += skb->len;
stats->collisions += ((status & ColCountMask) - 1);
}
sis190_unmap_tx_skb(tp->pci_dev, skb, txd);
tp->Tx_skbuff[entry] = NULL;
dev_kfree_skb_irq(skb);
}
if (tp->dirty_tx != dirty_tx) {
tp->dirty_tx = dirty_tx;
smp_wmb();
if (queue_stopped)
netif_wake_queue(dev);
}
}
/*
* The interrupt handler does all of the Rx thread work and cleans up after
* the Tx thread.
*/
static irqreturn_t sis190_interrupt(int irq, void *__dev)
{
struct net_device *dev = __dev;
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned int handled = 0;
u32 status;
status = SIS_R32(IntrStatus);
if ((status == 0xffffffff) || !status)
goto out;
handled = 1;
if (unlikely(!netif_running(dev))) {
sis190_asic_down(ioaddr);
goto out;
}
SIS_W32(IntrStatus, status);
// netif_info(tp, intr, dev, "status = %08x\n", status);
if (status & LinkChange) {
netif_info(tp, intr, dev, "link change\n");
del_timer(&tp->timer);
schedule_work(&tp->phy_task);
}
if (status & RxQInt)
sis190_rx_interrupt(dev, tp, ioaddr);
if (status & TxQ0Int)
sis190_tx_interrupt(dev, tp, ioaddr);
out:
return IRQ_RETVAL(handled);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void sis190_netpoll(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct pci_dev *pdev = tp->pci_dev;
disable_irq(pdev->irq);
sis190_interrupt(pdev->irq, dev);
enable_irq(pdev->irq);
}
#endif
static void sis190_free_rx_skb(struct sis190_private *tp,
struct sk_buff **sk_buff, struct RxDesc *desc)
{
struct pci_dev *pdev = tp->pci_dev;
pci_unmap_single(pdev, le32_to_cpu(desc->addr), tp->rx_buf_sz,
PCI_DMA_FROMDEVICE);
dev_kfree_skb(*sk_buff);
*sk_buff = NULL;
sis190_make_unusable_by_asic(desc);
}
static void sis190_rx_clear(struct sis190_private *tp)
{
unsigned int i;
for (i = 0; i < NUM_RX_DESC; i++) {
if (!tp->Rx_skbuff[i])
continue;
sis190_free_rx_skb(tp, tp->Rx_skbuff + i, tp->RxDescRing + i);
}
}
static void sis190_init_ring_indexes(struct sis190_private *tp)
{
tp->dirty_tx = tp->dirty_rx = tp->cur_tx = tp->cur_rx = 0;
}
static int sis190_init_ring(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
sis190_init_ring_indexes(tp);
memset(tp->Tx_skbuff, 0x0, NUM_TX_DESC * sizeof(struct sk_buff *));
memset(tp->Rx_skbuff, 0x0, NUM_RX_DESC * sizeof(struct sk_buff *));
if (sis190_rx_fill(tp, dev, 0, NUM_RX_DESC) != NUM_RX_DESC)
goto err_rx_clear;
sis190_mark_as_last_descriptor(tp->RxDescRing + NUM_RX_DESC - 1);
return 0;
err_rx_clear:
sis190_rx_clear(tp);
return -ENOMEM;
}
static void sis190_set_rx_mode(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned long flags;
u32 mc_filter[2]; /* Multicast hash filter */
u16 rx_mode;
if (dev->flags & IFF_PROMISC) {
rx_mode =
AcceptBroadcast | AcceptMulticast | AcceptMyPhys |
AcceptAllPhys;
mc_filter[1] = mc_filter[0] = 0xffffffff;
} else if ((netdev_mc_count(dev) > multicast_filter_limit) ||
(dev->flags & IFF_ALLMULTI)) {
/* Too many to filter perfectly -- accept all multicasts. */
rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
mc_filter[1] = mc_filter[0] = 0xffffffff;
} else {
struct netdev_hw_addr *ha;
rx_mode = AcceptBroadcast | AcceptMyPhys;
mc_filter[1] = mc_filter[0] = 0;
netdev_for_each_mc_addr(ha, dev) {
int bit_nr =
ether_crc(ETH_ALEN, ha->addr) & 0x3f;
mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31);
rx_mode |= AcceptMulticast;
}
}
spin_lock_irqsave(&tp->lock, flags);
SIS_W16(RxMacControl, rx_mode | 0x2);
SIS_W32(RxHashTable, mc_filter[0]);
SIS_W32(RxHashTable + 4, mc_filter[1]);
spin_unlock_irqrestore(&tp->lock, flags);
}
static void sis190_soft_reset(void __iomem *ioaddr)
{
SIS_W32(IntrControl, 0x8000);
SIS_PCI_COMMIT();
SIS_W32(IntrControl, 0x0);
sis190_asic_down(ioaddr);
}
static void sis190_hw_start(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
sis190_soft_reset(ioaddr);
SIS_W32(TxDescStartAddr, tp->tx_dma);
SIS_W32(RxDescStartAddr, tp->rx_dma);
SIS_W32(IntrStatus, 0xffffffff);
SIS_W32(IntrMask, 0x0);
SIS_W32(GMIIControl, 0x0);
SIS_W32(TxMacControl, 0x60);
SIS_W16(RxMacControl, 0x02);
SIS_W32(RxHashTable, 0x0);
SIS_W32(0x6c, 0x0);
SIS_W32(RxWolCtrl, 0x0);
SIS_W32(RxWolData, 0x0);
SIS_PCI_COMMIT();
sis190_set_rx_mode(dev);
/* Enable all known interrupts by setting the interrupt mask. */
SIS_W32(IntrMask, sis190_intr_mask);
SIS_W32(TxControl, 0x1a00 | CmdTxEnb);
SIS_W32(RxControl, 0x1a1d);
netif_start_queue(dev);
}
static void sis190_phy_task(struct work_struct *work)
{
struct sis190_private *tp =
container_of(work, struct sis190_private, phy_task);
struct net_device *dev = tp->dev;
void __iomem *ioaddr = tp->mmio_addr;
int phy_id = tp->mii_if.phy_id;
u16 val;
rtnl_lock();
if (!netif_running(dev))
goto out_unlock;
val = mdio_read(ioaddr, phy_id, MII_BMCR);
if (val & BMCR_RESET) {
// FIXME: needlessly high ? -- FR 02/07/2005
mod_timer(&tp->timer, jiffies + HZ/10);
goto out_unlock;
}
val = mdio_read_latched(ioaddr, phy_id, MII_BMSR);
if (!(val & BMSR_ANEGCOMPLETE) && tp->link_status != LNK_AUTONEG) {
netif_carrier_off(dev);
netif_warn(tp, link, dev, "auto-negotiating...\n");
tp->link_status = LNK_AUTONEG;
} else if ((val & BMSR_LSTATUS) && tp->link_status != LNK_ON) {
/* Rejoice ! */
struct {
int val;
u32 ctl;
const char *msg;
} reg31[] = {
{ LPA_1000FULL, 0x07000c00 | 0x00001000,
"1000 Mbps Full Duplex" },
{ LPA_1000HALF, 0x07000c00,
"1000 Mbps Half Duplex" },
{ LPA_100FULL, 0x04000800 | 0x00001000,
"100 Mbps Full Duplex" },
{ LPA_100HALF, 0x04000800,
"100 Mbps Half Duplex" },
{ LPA_10FULL, 0x04000400 | 0x00001000,
"10 Mbps Full Duplex" },
{ LPA_10HALF, 0x04000400,
"10 Mbps Half Duplex" },
{ 0, 0x04000400, "unknown" }
}, *p = NULL;
u16 adv, autoexp, gigadv, gigrec;
val = mdio_read(ioaddr, phy_id, 0x1f);
netif_info(tp, link, dev, "mii ext = %04x\n", val);
val = mdio_read(ioaddr, phy_id, MII_LPA);
adv = mdio_read(ioaddr, phy_id, MII_ADVERTISE);
autoexp = mdio_read(ioaddr, phy_id, MII_EXPANSION);
netif_info(tp, link, dev, "mii lpa=%04x adv=%04x exp=%04x\n",
val, adv, autoexp);
if (val & LPA_NPAGE && autoexp & EXPANSION_NWAY) {
/* check for gigabit speed */
gigadv = mdio_read(ioaddr, phy_id, MII_CTRL1000);
gigrec = mdio_read(ioaddr, phy_id, MII_STAT1000);
val = (gigadv & (gigrec >> 2));
if (val & ADVERTISE_1000FULL)
p = reg31;
else if (val & ADVERTISE_1000HALF)
p = reg31 + 1;
}
if (!p) {
val &= adv;
for (p = reg31; p->val; p++) {
if ((val & p->val) == p->val)
break;
}
}
p->ctl |= SIS_R32(StationControl) & ~0x0f001c00;
if ((tp->features & F_HAS_RGMII) &&
(tp->features & F_PHY_BCM5461)) {
// Set Tx Delay in RGMII mode.
mdio_write(ioaddr, phy_id, 0x18, 0xf1c7);
udelay(200);
mdio_write(ioaddr, phy_id, 0x1c, 0x8c00);
p->ctl |= 0x03000000;
}
SIS_W32(StationControl, p->ctl);
if (tp->features & F_HAS_RGMII) {
SIS_W32(RGDelay, 0x0441);
SIS_W32(RGDelay, 0x0440);
}
tp->negotiated_lpa = p->val;
netif_info(tp, link, dev, "link on %s mode\n", p->msg);
netif_carrier_on(dev);
tp->link_status = LNK_ON;
} else if (!(val & BMSR_LSTATUS) && tp->link_status != LNK_AUTONEG)
tp->link_status = LNK_OFF;
mod_timer(&tp->timer, jiffies + SIS190_PHY_TIMEOUT);
out_unlock:
rtnl_unlock();
}
static void sis190_phy_timer(unsigned long __opaque)
{
struct net_device *dev = (struct net_device *)__opaque;
struct sis190_private *tp = netdev_priv(dev);
if (likely(netif_running(dev)))
schedule_work(&tp->phy_task);
}
static inline void sis190_delete_timer(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
del_timer_sync(&tp->timer);
}
static inline void sis190_request_timer(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct timer_list *timer = &tp->timer;
init_timer(timer);
timer->expires = jiffies + SIS190_PHY_TIMEOUT;
timer->data = (unsigned long)dev;
timer->function = sis190_phy_timer;
add_timer(timer);
}
static void sis190_set_rxbufsize(struct sis190_private *tp,
struct net_device *dev)
{
unsigned int mtu = dev->mtu;
tp->rx_buf_sz = (mtu > RX_BUF_SIZE) ? mtu + ETH_HLEN + 8 : RX_BUF_SIZE;
/* RxDesc->size has a licence to kill the lower bits */
if (tp->rx_buf_sz & 0x07) {
tp->rx_buf_sz += 8;
tp->rx_buf_sz &= RX_BUF_MASK;
}
}
static int sis190_open(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct pci_dev *pdev = tp->pci_dev;
int rc = -ENOMEM;
sis190_set_rxbufsize(tp, dev);
/*
* Rx and Tx descriptors need 256 bytes alignment.
* pci_alloc_consistent() guarantees a stronger alignment.
*/
tp->TxDescRing = pci_alloc_consistent(pdev, TX_RING_BYTES, &tp->tx_dma);
if (!tp->TxDescRing)
goto out;
tp->RxDescRing = pci_alloc_consistent(pdev, RX_RING_BYTES, &tp->rx_dma);
if (!tp->RxDescRing)
goto err_free_tx_0;
rc = sis190_init_ring(dev);
if (rc < 0)
goto err_free_rx_1;
sis190_request_timer(dev);
rc = request_irq(dev->irq, sis190_interrupt, IRQF_SHARED, dev->name, dev);
if (rc < 0)
goto err_release_timer_2;
sis190_hw_start(dev);
out:
return rc;
err_release_timer_2:
sis190_delete_timer(dev);
sis190_rx_clear(tp);
err_free_rx_1:
pci_free_consistent(tp->pci_dev, RX_RING_BYTES, tp->RxDescRing,
tp->rx_dma);
err_free_tx_0:
pci_free_consistent(tp->pci_dev, TX_RING_BYTES, tp->TxDescRing,
tp->tx_dma);
goto out;
}
static void sis190_tx_clear(struct sis190_private *tp)
{
unsigned int i;
for (i = 0; i < NUM_TX_DESC; i++) {
struct sk_buff *skb = tp->Tx_skbuff[i];
if (!skb)
continue;
sis190_unmap_tx_skb(tp->pci_dev, skb, tp->TxDescRing + i);
tp->Tx_skbuff[i] = NULL;
dev_kfree_skb(skb);
tp->dev->stats.tx_dropped++;
}
tp->cur_tx = tp->dirty_tx = 0;
}
static void sis190_down(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned int poll_locked = 0;
sis190_delete_timer(dev);
netif_stop_queue(dev);
do {
spin_lock_irq(&tp->lock);
sis190_asic_down(ioaddr);
spin_unlock_irq(&tp->lock);
synchronize_irq(dev->irq);
if (!poll_locked)
poll_locked++;
synchronize_sched();
} while (SIS_R32(IntrMask));
sis190_tx_clear(tp);
sis190_rx_clear(tp);
}
static int sis190_close(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct pci_dev *pdev = tp->pci_dev;
sis190_down(dev);
free_irq(dev->irq, dev);
pci_free_consistent(pdev, TX_RING_BYTES, tp->TxDescRing, tp->tx_dma);
pci_free_consistent(pdev, RX_RING_BYTES, tp->RxDescRing, tp->rx_dma);
tp->TxDescRing = NULL;
tp->RxDescRing = NULL;
return 0;
}
static netdev_tx_t sis190_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u32 len, entry, dirty_tx;
struct TxDesc *desc;
dma_addr_t mapping;
if (unlikely(skb->len < ETH_ZLEN)) {
if (skb_padto(skb, ETH_ZLEN)) {
dev->stats.tx_dropped++;
goto out;
}
len = ETH_ZLEN;
} else {
len = skb->len;
}
entry = tp->cur_tx % NUM_TX_DESC;
desc = tp->TxDescRing + entry;
if (unlikely(le32_to_cpu(desc->status) & OWNbit)) {
netif_stop_queue(dev);
netif_err(tp, tx_err, dev,
"BUG! Tx Ring full when queue awake!\n");
return NETDEV_TX_BUSY;
}
mapping = pci_map_single(tp->pci_dev, skb->data, len, PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(tp->pci_dev, mapping)) {
netif_err(tp, tx_err, dev,
"PCI mapping failed, dropping packet");
return NETDEV_TX_BUSY;
}
tp->Tx_skbuff[entry] = skb;
desc->PSize = cpu_to_le32(len);
desc->addr = cpu_to_le32(mapping);
desc->size = cpu_to_le32(len);
if (entry == (NUM_TX_DESC - 1))
desc->size |= cpu_to_le32(RingEnd);
wmb();
desc->status = cpu_to_le32(OWNbit | INTbit | DEFbit | CRCbit | PADbit);
if (tp->negotiated_lpa & (LPA_1000HALF | LPA_100HALF | LPA_10HALF)) {
/* Half Duplex */
desc->status |= cpu_to_le32(COLEN | CRSEN | BKFEN);
if (tp->negotiated_lpa & (LPA_1000HALF | LPA_1000FULL))
desc->status |= cpu_to_le32(EXTEN | BSTEN); /* gigabit HD */
}
tp->cur_tx++;
smp_wmb();
SIS_W32(TxControl, 0x1a00 | CmdReset | CmdTxEnb);
dirty_tx = tp->dirty_tx;
if ((tp->cur_tx - NUM_TX_DESC) == dirty_tx) {
netif_stop_queue(dev);
smp_rmb();
if (dirty_tx != tp->dirty_tx)
netif_wake_queue(dev);
}
out:
return NETDEV_TX_OK;
}
static void sis190_free_phy(struct list_head *first_phy)
{
struct sis190_phy *cur, *next;
list_for_each_entry_safe(cur, next, first_phy, list) {
kfree(cur);
}
}
/**
* sis190_default_phy - Select default PHY for sis190 mac.
* @dev: the net device to probe for
*
* Select first detected PHY with link as default.
* If no one is link on, select PHY whose types is HOME as default.
* If HOME doesn't exist, select LAN.
*/
static u16 sis190_default_phy(struct net_device *dev)
{
struct sis190_phy *phy, *phy_home, *phy_default, *phy_lan;
struct sis190_private *tp = netdev_priv(dev);
struct mii_if_info *mii_if = &tp->mii_if;
void __iomem *ioaddr = tp->mmio_addr;
u16 status;
phy_home = phy_default = phy_lan = NULL;
list_for_each_entry(phy, &tp->first_phy, list) {
status = mdio_read_latched(ioaddr, phy->phy_id, MII_BMSR);
// Link ON & Not select default PHY & not ghost PHY.
if ((status & BMSR_LSTATUS) &&
!phy_default &&
(phy->type != UNKNOWN)) {
phy_default = phy;
} else {
status = mdio_read(ioaddr, phy->phy_id, MII_BMCR);
mdio_write(ioaddr, phy->phy_id, MII_BMCR,
status | BMCR_ANENABLE | BMCR_ISOLATE);
if (phy->type == HOME)
phy_home = phy;
else if (phy->type == LAN)
phy_lan = phy;
}
}
if (!phy_default) {
if (phy_home)
phy_default = phy_home;
else if (phy_lan)
phy_default = phy_lan;
else
phy_default = list_first_entry(&tp->first_phy,
struct sis190_phy, list);
}
if (mii_if->phy_id != phy_default->phy_id) {
mii_if->phy_id = phy_default->phy_id;
if (netif_msg_probe(tp))
pr_info("%s: Using transceiver at address %d as default\n",
pci_name(tp->pci_dev), mii_if->phy_id);
}
status = mdio_read(ioaddr, mii_if->phy_id, MII_BMCR);
status &= (~BMCR_ISOLATE);
mdio_write(ioaddr, mii_if->phy_id, MII_BMCR, status);
status = mdio_read_latched(ioaddr, mii_if->phy_id, MII_BMSR);
return status;
}
static void sis190_init_phy(struct net_device *dev, struct sis190_private *tp,
struct sis190_phy *phy, unsigned int phy_id,
u16 mii_status)
{
void __iomem *ioaddr = tp->mmio_addr;
struct mii_chip_info *p;
INIT_LIST_HEAD(&phy->list);
phy->status = mii_status;
phy->phy_id = phy_id;
phy->id[0] = mdio_read(ioaddr, phy_id, MII_PHYSID1);
phy->id[1] = mdio_read(ioaddr, phy_id, MII_PHYSID2);
for (p = mii_chip_table; p->type; p++) {
if ((p->id[0] == phy->id[0]) &&
(p->id[1] == (phy->id[1] & 0xfff0))) {
break;
}
}
if (p->id[1]) {
phy->type = (p->type == MIX) ?
((mii_status & (BMSR_100FULL | BMSR_100HALF)) ?
LAN : HOME) : p->type;
tp->features |= p->feature;
if (netif_msg_probe(tp))
pr_info("%s: %s transceiver at address %d\n",
pci_name(tp->pci_dev), p->name, phy_id);
} else {
phy->type = UNKNOWN;
if (netif_msg_probe(tp))
pr_info("%s: unknown PHY 0x%x:0x%x transceiver at address %d\n",
pci_name(tp->pci_dev),
phy->id[0], (phy->id[1] & 0xfff0), phy_id);
}
}
static void sis190_mii_probe_88e1111_fixup(struct sis190_private *tp)
{
if (tp->features & F_PHY_88E1111) {
void __iomem *ioaddr = tp->mmio_addr;
int phy_id = tp->mii_if.phy_id;
u16 reg[2][2] = {
{ 0x808b, 0x0ce1 },
{ 0x808f, 0x0c60 }
}, *p;
p = (tp->features & F_HAS_RGMII) ? reg[0] : reg[1];
mdio_write(ioaddr, phy_id, 0x1b, p[0]);
udelay(200);
mdio_write(ioaddr, phy_id, 0x14, p[1]);
udelay(200);
}
}
/**
* sis190_mii_probe - Probe MII PHY for sis190
* @dev: the net device to probe for
*
* Search for total of 32 possible mii phy addresses.
* Identify and set current phy if found one,
* return error if it failed to found.
*/
static int __devinit sis190_mii_probe(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct mii_if_info *mii_if = &tp->mii_if;
void __iomem *ioaddr = tp->mmio_addr;
int phy_id;
int rc = 0;
INIT_LIST_HEAD(&tp->first_phy);
for (phy_id = 0; phy_id < PHY_MAX_ADDR; phy_id++) {
struct sis190_phy *phy;
u16 status;
status = mdio_read_latched(ioaddr, phy_id, MII_BMSR);
// Try next mii if the current one is not accessible.
if (status == 0xffff || status == 0x0000)
continue;
phy = kmalloc(sizeof(*phy), GFP_KERNEL);
if (!phy) {
sis190_free_phy(&tp->first_phy);
rc = -ENOMEM;
goto out;
}
sis190_init_phy(dev, tp, phy, phy_id, status);
list_add(&tp->first_phy, &phy->list);
}
if (list_empty(&tp->first_phy)) {
if (netif_msg_probe(tp))
pr_info("%s: No MII transceivers found!\n",
pci_name(tp->pci_dev));
rc = -EIO;
goto out;
}
/* Select default PHY for mac */
sis190_default_phy(dev);
sis190_mii_probe_88e1111_fixup(tp);
mii_if->dev = dev;
mii_if->mdio_read = __mdio_read;
mii_if->mdio_write = __mdio_write;
mii_if->phy_id_mask = PHY_ID_ANY;
mii_if->reg_num_mask = MII_REG_ANY;
out:
return rc;
}
static void sis190_mii_remove(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
sis190_free_phy(&tp->first_phy);
}
static void sis190_release_board(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct sis190_private *tp = netdev_priv(dev);
iounmap(tp->mmio_addr);
pci_release_regions(pdev);
pci_disable_device(pdev);
free_netdev(dev);
}
static struct net_device * __devinit sis190_init_board(struct pci_dev *pdev)
{
struct sis190_private *tp;
struct net_device *dev;
void __iomem *ioaddr;
int rc;
dev = alloc_etherdev(sizeof(*tp));
if (!dev) {
rc = -ENOMEM;
goto err_out_0;
}
SET_NETDEV_DEV(dev, &pdev->dev);
tp = netdev_priv(dev);
tp->dev = dev;
tp->msg_enable = netif_msg_init(debug.msg_enable, SIS190_MSG_DEFAULT);
rc = pci_enable_device(pdev);
if (rc < 0) {
if (netif_msg_probe(tp))
pr_err("%s: enable failure\n", pci_name(pdev));
goto err_free_dev_1;
}
rc = -ENODEV;
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
if (netif_msg_probe(tp))
pr_err("%s: region #0 is no MMIO resource\n",
pci_name(pdev));
goto err_pci_disable_2;
}
if (pci_resource_len(pdev, 0) < SIS190_REGS_SIZE) {
if (netif_msg_probe(tp))
pr_err("%s: invalid PCI region size(s)\n",
pci_name(pdev));
goto err_pci_disable_2;
}
rc = pci_request_regions(pdev, DRV_NAME);
if (rc < 0) {
if (netif_msg_probe(tp))
pr_err("%s: could not request regions\n",
pci_name(pdev));
goto err_pci_disable_2;
}
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc < 0) {
if (netif_msg_probe(tp))
pr_err("%s: DMA configuration failed\n",
pci_name(pdev));
goto err_free_res_3;
}
pci_set_master(pdev);
ioaddr = ioremap(pci_resource_start(pdev, 0), SIS190_REGS_SIZE);
if (!ioaddr) {
if (netif_msg_probe(tp))
pr_err("%s: cannot remap MMIO, aborting\n",
pci_name(pdev));
rc = -EIO;
goto err_free_res_3;
}
tp->pci_dev = pdev;
tp->mmio_addr = ioaddr;
tp->link_status = LNK_OFF;
sis190_irq_mask_and_ack(ioaddr);
sis190_soft_reset(ioaddr);
out:
return dev;
err_free_res_3:
pci_release_regions(pdev);
err_pci_disable_2:
pci_disable_device(pdev);
err_free_dev_1:
free_netdev(dev);
err_out_0:
dev = ERR_PTR(rc);
goto out;
}
static void sis190_tx_timeout(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u8 tmp8;
/* Disable Tx, if not already */
tmp8 = SIS_R8(TxControl);
if (tmp8 & CmdTxEnb)
SIS_W8(TxControl, tmp8 & ~CmdTxEnb);
netif_info(tp, tx_err, dev, "Transmit timeout, status %08x %08x\n",
SIS_R32(TxControl), SIS_R32(TxSts));
/* Disable interrupts by clearing the interrupt mask. */
SIS_W32(IntrMask, 0x0000);
/* Stop a shared interrupt from scavenging while we are. */
spin_lock_irq(&tp->lock);
sis190_tx_clear(tp);
spin_unlock_irq(&tp->lock);
/* ...and finally, reset everything. */
sis190_hw_start(dev);
netif_wake_queue(dev);
}
static void sis190_set_rgmii(struct sis190_private *tp, u8 reg)
{
tp->features |= (reg & 0x80) ? F_HAS_RGMII : 0;
}
static int __devinit sis190_get_mac_addr_from_eeprom(struct pci_dev *pdev,
struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u16 sig;
int i;
if (netif_msg_probe(tp))
pr_info("%s: Read MAC address from EEPROM\n", pci_name(pdev));
/* Check to see if there is a sane EEPROM */
sig = (u16) sis190_read_eeprom(ioaddr, EEPROMSignature);
if ((sig == 0xffff) || (sig == 0x0000)) {
if (netif_msg_probe(tp))
pr_info("%s: Error EEPROM read %x\n",
pci_name(pdev), sig);
return -EIO;
}
/* Get MAC address from EEPROM */
for (i = 0; i < ETH_ALEN / 2; i++) {
u16 w = sis190_read_eeprom(ioaddr, EEPROMMACAddr + i);
((__le16 *)dev->dev_addr)[i] = cpu_to_le16(w);
}
sis190_set_rgmii(tp, sis190_read_eeprom(ioaddr, EEPROMInfo));
return 0;
}
/**
* sis190_get_mac_addr_from_apc - Get MAC address for SiS96x model
* @pdev: PCI device
* @dev: network device to get address for
*
* SiS96x model, use APC CMOS RAM to store MAC address.
* APC CMOS RAM is accessed through ISA bridge.
* MAC address is read into @net_dev->dev_addr.
*/
static int __devinit sis190_get_mac_addr_from_apc(struct pci_dev *pdev,
struct net_device *dev)
{
static const u16 __devinitdata ids[] = { 0x0965, 0x0966, 0x0968 };
struct sis190_private *tp = netdev_priv(dev);
struct pci_dev *isa_bridge;
u8 reg, tmp8;
unsigned int i;
if (netif_msg_probe(tp))
pr_info("%s: Read MAC address from APC\n", pci_name(pdev));
for (i = 0; i < ARRAY_SIZE(ids); i++) {
isa_bridge = pci_get_device(PCI_VENDOR_ID_SI, ids[i], NULL);
if (isa_bridge)
break;
}
if (!isa_bridge) {
if (netif_msg_probe(tp))
pr_info("%s: Can not find ISA bridge\n",
pci_name(pdev));
return -EIO;
}
/* Enable port 78h & 79h to access APC Registers. */
pci_read_config_byte(isa_bridge, 0x48, &tmp8);
reg = (tmp8 & ~0x02);
pci_write_config_byte(isa_bridge, 0x48, reg);
udelay(50);
pci_read_config_byte(isa_bridge, 0x48, ®);
for (i = 0; i < ETH_ALEN; i++) {
outb(0x9 + i, 0x78);
dev->dev_addr[i] = inb(0x79);
}
outb(0x12, 0x78);
reg = inb(0x79);
sis190_set_rgmii(tp, reg);
/* Restore the value to ISA Bridge */
pci_write_config_byte(isa_bridge, 0x48, tmp8);
pci_dev_put(isa_bridge);
return 0;
}
/**
* sis190_init_rxfilter - Initialize the Rx filter
* @dev: network device to initialize
*
* Set receive filter address to our MAC address
* and enable packet filtering.
*/
static inline void sis190_init_rxfilter(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u16 ctl;
int i;
ctl = SIS_R16(RxMacControl);
/*
* Disable packet filtering before setting filter.
* Note: SiS's driver writes 32 bits but RxMacControl is 16 bits
* only and followed by RxMacAddr (6 bytes). Strange. -- FR
*/
SIS_W16(RxMacControl, ctl & ~0x0f00);
for (i = 0; i < ETH_ALEN; i++)
SIS_W8(RxMacAddr + i, dev->dev_addr[i]);
SIS_W16(RxMacControl, ctl);
SIS_PCI_COMMIT();
}
static int __devinit sis190_get_mac_addr(struct pci_dev *pdev,
struct net_device *dev)
{
int rc;
rc = sis190_get_mac_addr_from_eeprom(pdev, dev);
if (rc < 0) {
u8 reg;
pci_read_config_byte(pdev, 0x73, ®);
if (reg & 0x00000001)
rc = sis190_get_mac_addr_from_apc(pdev, dev);
}
return rc;
}
static void sis190_set_speed_auto(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
int phy_id = tp->mii_if.phy_id;
int val;
netif_info(tp, link, dev, "Enabling Auto-negotiation\n");
val = mdio_read(ioaddr, phy_id, MII_ADVERTISE);
// Enable 10/100 Full/Half Mode, leave MII_ADVERTISE bit4:0
// unchanged.
mdio_write(ioaddr, phy_id, MII_ADVERTISE, (val & ADVERTISE_SLCT) |
ADVERTISE_100FULL | ADVERTISE_10FULL |
ADVERTISE_100HALF | ADVERTISE_10HALF);
// Enable 1000 Full Mode.
mdio_write(ioaddr, phy_id, MII_CTRL1000, ADVERTISE_1000FULL);
// Enable auto-negotiation and restart auto-negotiation.
mdio_write(ioaddr, phy_id, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART | BMCR_RESET);
}
static int sis190_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct sis190_private *tp = netdev_priv(dev);
return mii_ethtool_gset(&tp->mii_if, cmd);
}
static int sis190_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct sis190_private *tp = netdev_priv(dev);
return mii_ethtool_sset(&tp->mii_if, cmd);
}
static void sis190_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct sis190_private *tp = netdev_priv(dev);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pci_name(tp->pci_dev),
sizeof(info->bus_info));
}
static int sis190_get_regs_len(struct net_device *dev)
{
return SIS190_REGS_SIZE;
}
static void sis190_get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *p)
{
struct sis190_private *tp = netdev_priv(dev);
unsigned long flags;
if (regs->len > SIS190_REGS_SIZE)
regs->len = SIS190_REGS_SIZE;
spin_lock_irqsave(&tp->lock, flags);
memcpy_fromio(p, tp->mmio_addr, regs->len);
spin_unlock_irqrestore(&tp->lock, flags);
}
static int sis190_nway_reset(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
return mii_nway_restart(&tp->mii_if);
}
static u32 sis190_get_msglevel(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
return tp->msg_enable;
}
static void sis190_set_msglevel(struct net_device *dev, u32 value)
{
struct sis190_private *tp = netdev_priv(dev);
tp->msg_enable = value;
}
static const struct ethtool_ops sis190_ethtool_ops = {
.get_settings = sis190_get_settings,
.set_settings = sis190_set_settings,
.get_drvinfo = sis190_get_drvinfo,
.get_regs_len = sis190_get_regs_len,
.get_regs = sis190_get_regs,
.get_link = ethtool_op_get_link,
.get_msglevel = sis190_get_msglevel,
.set_msglevel = sis190_set_msglevel,
.nway_reset = sis190_nway_reset,
};
static int sis190_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct sis190_private *tp = netdev_priv(dev);
return !netif_running(dev) ? -EINVAL :
generic_mii_ioctl(&tp->mii_if, if_mii(ifr), cmd, NULL);
}
static int sis190_mac_addr(struct net_device *dev, void *p)
{
int rc;
rc = eth_mac_addr(dev, p);
if (!rc)
sis190_init_rxfilter(dev);
return rc;
}
static const struct net_device_ops sis190_netdev_ops = {
.ndo_open = sis190_open,
.ndo_stop = sis190_close,
.ndo_do_ioctl = sis190_ioctl,
.ndo_start_xmit = sis190_start_xmit,
.ndo_tx_timeout = sis190_tx_timeout,
.ndo_set_rx_mode = sis190_set_rx_mode,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = sis190_mac_addr,
.ndo_validate_addr = eth_validate_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = sis190_netpoll,
#endif
};
static int __devinit sis190_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static int printed_version = 0;
struct sis190_private *tp;
struct net_device *dev;
void __iomem *ioaddr;
int rc;
if (!printed_version) {
if (netif_msg_drv(&debug))
pr_info(SIS190_DRIVER_NAME " loaded\n");
printed_version = 1;
}
dev = sis190_init_board(pdev);
if (IS_ERR(dev)) {
rc = PTR_ERR(dev);
goto out;
}
pci_set_drvdata(pdev, dev);
tp = netdev_priv(dev);
ioaddr = tp->mmio_addr;
rc = sis190_get_mac_addr(pdev, dev);
if (rc < 0)
goto err_release_board;
sis190_init_rxfilter(dev);
INIT_WORK(&tp->phy_task, sis190_phy_task);
dev->netdev_ops = &sis190_netdev_ops;
SET_ETHTOOL_OPS(dev, &sis190_ethtool_ops);
dev->irq = pdev->irq;
dev->base_addr = (unsigned long) 0xdead;
dev->watchdog_timeo = SIS190_TX_TIMEOUT;
spin_lock_init(&tp->lock);
rc = sis190_mii_probe(dev);
if (rc < 0)
goto err_release_board;
rc = register_netdev(dev);
if (rc < 0)
goto err_remove_mii;
if (netif_msg_probe(tp)) {
netdev_info(dev, "%s: %s at %p (IRQ: %d), %pM\n",
pci_name(pdev),
sis_chip_info[ent->driver_data].name,
ioaddr, dev->irq, dev->dev_addr);
netdev_info(dev, "%s mode.\n",
(tp->features & F_HAS_RGMII) ? "RGMII" : "GMII");
}
netif_carrier_off(dev);
sis190_set_speed_auto(dev);
out:
return rc;
err_remove_mii:
sis190_mii_remove(dev);
err_release_board:
sis190_release_board(pdev);
goto out;
}
static void __devexit sis190_remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct sis190_private *tp = netdev_priv(dev);
sis190_mii_remove(dev);
cancel_work_sync(&tp->phy_task);
unregister_netdev(dev);
sis190_release_board(pdev);
pci_set_drvdata(pdev, NULL);
}
static struct pci_driver sis190_pci_driver = {
.name = DRV_NAME,
.id_table = sis190_pci_tbl,
.probe = sis190_init_one,
.remove = __devexit_p(sis190_remove_one),
};
static int __init sis190_init_module(void)
{
return pci_register_driver(&sis190_pci_driver);
}
static void __exit sis190_cleanup_module(void)
{
pci_unregister_driver(&sis190_pci_driver);
}
module_init(sis190_init_module);
module_exit(sis190_cleanup_module);
| gpl-2.0 |
Haifen/android_kernel_google_msm | drivers/scsi/qla4xxx/ql4_init.c | 4807 | 32213 | /*
* QLogic iSCSI HBA Driver
* Copyright (c) 2003-2010 QLogic Corporation
*
* See LICENSE.qla4xxx for copyright and licensing details.
*/
#include <scsi/iscsi_if.h>
#include "ql4_def.h"
#include "ql4_glbl.h"
#include "ql4_dbg.h"
#include "ql4_inline.h"
static void ql4xxx_set_mac_number(struct scsi_qla_host *ha)
{
uint32_t value;
uint8_t func_number;
unsigned long flags;
/* Get the function number */
spin_lock_irqsave(&ha->hardware_lock, flags);
value = readw(&ha->reg->ctrl_status);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
func_number = (uint8_t) ((value >> 4) & 0x30);
switch (value & ISP_CONTROL_FN_MASK) {
case ISP_CONTROL_FN0_SCSI:
ha->mac_index = 1;
break;
case ISP_CONTROL_FN1_SCSI:
ha->mac_index = 3;
break;
default:
DEBUG2(printk("scsi%ld: %s: Invalid function number, "
"ispControlStatus = 0x%x\n", ha->host_no,
__func__, value));
break;
}
DEBUG2(printk("scsi%ld: %s: mac_index %d.\n", ha->host_no, __func__,
ha->mac_index));
}
/**
* qla4xxx_free_ddb - deallocate ddb
* @ha: pointer to host adapter structure.
* @ddb_entry: pointer to device database entry
*
* This routine marks a DDB entry INVALID
**/
void qla4xxx_free_ddb(struct scsi_qla_host *ha,
struct ddb_entry *ddb_entry)
{
/* Remove device pointer from index mapping arrays */
ha->fw_ddb_index_map[ddb_entry->fw_ddb_index] =
(struct ddb_entry *) INVALID_ENTRY;
ha->tot_ddbs--;
}
/**
* qla4xxx_init_response_q_entries() - Initializes response queue entries.
* @ha: HA context
*
* Beginning of request ring has initialization control block already built
* by nvram config routine.
**/
static void qla4xxx_init_response_q_entries(struct scsi_qla_host *ha)
{
uint16_t cnt;
struct response *pkt;
pkt = (struct response *)ha->response_ptr;
for (cnt = 0; cnt < RESPONSE_QUEUE_DEPTH; cnt++) {
pkt->signature = RESPONSE_PROCESSED;
pkt++;
}
}
/**
* qla4xxx_init_rings - initialize hw queues
* @ha: pointer to host adapter structure.
*
* This routine initializes the internal queues for the specified adapter.
* The QLA4010 requires us to restart the queues at index 0.
* The QLA4000 doesn't care, so just default to QLA4010's requirement.
**/
int qla4xxx_init_rings(struct scsi_qla_host *ha)
{
unsigned long flags = 0;
int i;
/* Initialize request queue. */
spin_lock_irqsave(&ha->hardware_lock, flags);
ha->request_out = 0;
ha->request_in = 0;
ha->request_ptr = &ha->request_ring[ha->request_in];
ha->req_q_count = REQUEST_QUEUE_DEPTH;
/* Initialize response queue. */
ha->response_in = 0;
ha->response_out = 0;
ha->response_ptr = &ha->response_ring[ha->response_out];
if (is_qla8022(ha)) {
writel(0,
(unsigned long __iomem *)&ha->qla4_8xxx_reg->req_q_out);
writel(0,
(unsigned long __iomem *)&ha->qla4_8xxx_reg->rsp_q_in);
writel(0,
(unsigned long __iomem *)&ha->qla4_8xxx_reg->rsp_q_out);
} else {
/*
* Initialize DMA Shadow registers. The firmware is really
* supposed to take care of this, but on some uniprocessor
* systems, the shadow registers aren't cleared-- causing
* the interrupt_handler to think there are responses to be
* processed when there aren't.
*/
ha->shadow_regs->req_q_out = __constant_cpu_to_le32(0);
ha->shadow_regs->rsp_q_in = __constant_cpu_to_le32(0);
wmb();
writel(0, &ha->reg->req_q_in);
writel(0, &ha->reg->rsp_q_out);
readl(&ha->reg->rsp_q_out);
}
qla4xxx_init_response_q_entries(ha);
/* Initialize mabilbox active array */
for (i = 0; i < MAX_MRB; i++)
ha->active_mrb_array[i] = NULL;
spin_unlock_irqrestore(&ha->hardware_lock, flags);
return QLA_SUCCESS;
}
/**
* qla4xxx_get_sys_info - validate adapter MAC address(es)
* @ha: pointer to host adapter structure.
*
**/
int qla4xxx_get_sys_info(struct scsi_qla_host *ha)
{
struct flash_sys_info *sys_info;
dma_addr_t sys_info_dma;
int status = QLA_ERROR;
sys_info = dma_alloc_coherent(&ha->pdev->dev, sizeof(*sys_info),
&sys_info_dma, GFP_KERNEL);
if (sys_info == NULL) {
DEBUG2(printk("scsi%ld: %s: Unable to allocate dma buffer.\n",
ha->host_no, __func__));
goto exit_get_sys_info_no_free;
}
memset(sys_info, 0, sizeof(*sys_info));
/* Get flash sys info */
if (qla4xxx_get_flash(ha, sys_info_dma, FLASH_OFFSET_SYS_INFO,
sizeof(*sys_info)) != QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: get_flash FLASH_OFFSET_SYS_INFO "
"failed\n", ha->host_no, __func__));
goto exit_get_sys_info;
}
/* Save M.A.C. address & serial_number */
memcpy(ha->my_mac, &sys_info->physAddr[0].address[0],
min(sizeof(ha->my_mac),
sizeof(sys_info->physAddr[0].address)));
memcpy(ha->serial_number, &sys_info->acSerialNumber,
min(sizeof(ha->serial_number),
sizeof(sys_info->acSerialNumber)));
status = QLA_SUCCESS;
exit_get_sys_info:
dma_free_coherent(&ha->pdev->dev, sizeof(*sys_info), sys_info,
sys_info_dma);
exit_get_sys_info_no_free:
return status;
}
/**
* qla4xxx_init_local_data - initialize adapter specific local data
* @ha: pointer to host adapter structure.
*
**/
static int qla4xxx_init_local_data(struct scsi_qla_host *ha)
{
/* Initialize aen queue */
ha->aen_q_count = MAX_AEN_ENTRIES;
return qla4xxx_get_firmware_status(ha);
}
static uint8_t
qla4xxx_wait_for_ip_config(struct scsi_qla_host *ha)
{
uint8_t ipv4_wait = 0;
uint8_t ipv6_wait = 0;
int8_t ip_address[IPv6_ADDR_LEN] = {0} ;
/* If both IPv4 & IPv6 are enabled, possibly only one
* IP address may be acquired, so check to see if we
* need to wait for another */
if (is_ipv4_enabled(ha) && is_ipv6_enabled(ha)) {
if (((ha->addl_fw_state & FW_ADDSTATE_DHCPv4_ENABLED) != 0) &&
((ha->addl_fw_state &
FW_ADDSTATE_DHCPv4_LEASE_ACQUIRED) == 0)) {
ipv4_wait = 1;
}
if (((ha->ip_config.ipv6_addl_options &
IPV6_ADDOPT_NEIGHBOR_DISCOVERY_ADDR_ENABLE) != 0) &&
((ha->ip_config.ipv6_link_local_state ==
IP_ADDRSTATE_ACQUIRING) ||
(ha->ip_config.ipv6_addr0_state ==
IP_ADDRSTATE_ACQUIRING) ||
(ha->ip_config.ipv6_addr1_state ==
IP_ADDRSTATE_ACQUIRING))) {
ipv6_wait = 1;
if ((ha->ip_config.ipv6_link_local_state ==
IP_ADDRSTATE_PREFERRED) ||
(ha->ip_config.ipv6_addr0_state ==
IP_ADDRSTATE_PREFERRED) ||
(ha->ip_config.ipv6_addr1_state ==
IP_ADDRSTATE_PREFERRED)) {
DEBUG2(printk(KERN_INFO "scsi%ld: %s: "
"Preferred IP configured."
" Don't wait!\n", ha->host_no,
__func__));
ipv6_wait = 0;
}
if (memcmp(&ha->ip_config.ipv6_default_router_addr,
ip_address, IPv6_ADDR_LEN) == 0) {
DEBUG2(printk(KERN_INFO "scsi%ld: %s: "
"No Router configured. "
"Don't wait!\n", ha->host_no,
__func__));
ipv6_wait = 0;
}
if ((ha->ip_config.ipv6_default_router_state ==
IPV6_RTRSTATE_MANUAL) &&
(ha->ip_config.ipv6_link_local_state ==
IP_ADDRSTATE_TENTATIVE) &&
(memcmp(&ha->ip_config.ipv6_link_local_addr,
&ha->ip_config.ipv6_default_router_addr, 4) ==
0)) {
DEBUG2(printk("scsi%ld: %s: LinkLocal Router & "
"IP configured. Don't wait!\n",
ha->host_no, __func__));
ipv6_wait = 0;
}
}
if (ipv4_wait || ipv6_wait) {
DEBUG2(printk("scsi%ld: %s: Wait for additional "
"IP(s) \"", ha->host_no, __func__));
if (ipv4_wait)
DEBUG2(printk("IPv4 "));
if (ha->ip_config.ipv6_link_local_state ==
IP_ADDRSTATE_ACQUIRING)
DEBUG2(printk("IPv6LinkLocal "));
if (ha->ip_config.ipv6_addr0_state ==
IP_ADDRSTATE_ACQUIRING)
DEBUG2(printk("IPv6Addr0 "));
if (ha->ip_config.ipv6_addr1_state ==
IP_ADDRSTATE_ACQUIRING)
DEBUG2(printk("IPv6Addr1 "));
DEBUG2(printk("\"\n"));
}
}
return ipv4_wait|ipv6_wait;
}
static int qla4xxx_fw_ready(struct scsi_qla_host *ha)
{
uint32_t timeout_count;
int ready = 0;
DEBUG2(ql4_printk(KERN_INFO, ha, "Waiting for Firmware Ready..\n"));
for (timeout_count = ADAPTER_INIT_TOV; timeout_count > 0;
timeout_count--) {
if (test_and_clear_bit(DPC_GET_DHCP_IP_ADDR, &ha->dpc_flags))
qla4xxx_get_dhcp_ip_address(ha);
/* Get firmware state. */
if (qla4xxx_get_firmware_state(ha) != QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: unable to get firmware "
"state\n", ha->host_no, __func__));
break;
}
if (ha->firmware_state & FW_STATE_ERROR) {
DEBUG2(printk("scsi%ld: %s: an unrecoverable error has"
" occurred\n", ha->host_no, __func__));
break;
}
if (ha->firmware_state & FW_STATE_CONFIG_WAIT) {
/*
* The firmware has not yet been issued an Initialize
* Firmware command, so issue it now.
*/
if (qla4xxx_initialize_fw_cb(ha) == QLA_ERROR)
break;
/* Go back and test for ready state - no wait. */
continue;
}
if (ha->firmware_state & FW_STATE_WAIT_AUTOCONNECT) {
DEBUG2(printk(KERN_INFO "scsi%ld: %s: fwstate:"
"AUTOCONNECT in progress\n",
ha->host_no, __func__));
}
if (ha->firmware_state & FW_STATE_CONFIGURING_IP) {
DEBUG2(printk(KERN_INFO "scsi%ld: %s: fwstate:"
" CONFIGURING IP\n",
ha->host_no, __func__));
/*
* Check for link state after 15 secs and if link is
* still DOWN then, cable is unplugged. Ignore "DHCP
* in Progress/CONFIGURING IP" bit to check if firmware
* is in ready state or not after 15 secs.
* This is applicable for both 2.x & 3.x firmware
*/
if (timeout_count <= (ADAPTER_INIT_TOV - 15)) {
if (ha->addl_fw_state & FW_ADDSTATE_LINK_UP) {
DEBUG2(printk(KERN_INFO "scsi%ld: %s:"
" LINK UP (Cable plugged)\n",
ha->host_no, __func__));
} else if (ha->firmware_state &
(FW_STATE_CONFIGURING_IP |
FW_STATE_READY)) {
DEBUG2(printk(KERN_INFO "scsi%ld: %s: "
"LINK DOWN (Cable unplugged)\n",
ha->host_no, __func__));
ha->firmware_state = FW_STATE_READY;
}
}
}
if (ha->firmware_state == FW_STATE_READY) {
/* If DHCP IP Addr is available, retrieve it now. */
if (test_and_clear_bit(DPC_GET_DHCP_IP_ADDR,
&ha->dpc_flags))
qla4xxx_get_dhcp_ip_address(ha);
if (!qla4xxx_wait_for_ip_config(ha) ||
timeout_count == 1) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"Firmware Ready..\n"));
/* The firmware is ready to process SCSI
commands. */
DEBUG2(ql4_printk(KERN_INFO, ha,
"scsi%ld: %s: MEDIA TYPE"
" - %s\n", ha->host_no,
__func__, (ha->addl_fw_state &
FW_ADDSTATE_OPTICAL_MEDIA)
!= 0 ? "OPTICAL" : "COPPER"));
DEBUG2(ql4_printk(KERN_INFO, ha,
"scsi%ld: %s: DHCPv4 STATE"
" Enabled %s\n", ha->host_no,
__func__, (ha->addl_fw_state &
FW_ADDSTATE_DHCPv4_ENABLED) != 0 ?
"YES" : "NO"));
DEBUG2(ql4_printk(KERN_INFO, ha,
"scsi%ld: %s: LINK %s\n",
ha->host_no, __func__,
(ha->addl_fw_state &
FW_ADDSTATE_LINK_UP) != 0 ?
"UP" : "DOWN"));
DEBUG2(ql4_printk(KERN_INFO, ha,
"scsi%ld: %s: iSNS Service "
"Started %s\n",
ha->host_no, __func__,
(ha->addl_fw_state &
FW_ADDSTATE_ISNS_SVC_ENABLED) != 0 ?
"YES" : "NO"));
ready = 1;
break;
}
}
DEBUG2(printk("scsi%ld: %s: waiting on fw, state=%x:%x - "
"seconds expired= %d\n", ha->host_no, __func__,
ha->firmware_state, ha->addl_fw_state,
timeout_count));
if (is_qla4032(ha) &&
!(ha->addl_fw_state & FW_ADDSTATE_LINK_UP) &&
(timeout_count < ADAPTER_INIT_TOV - 5)) {
break;
}
msleep(1000);
} /* end of for */
if (timeout_count <= 0)
DEBUG2(printk("scsi%ld: %s: FW Initialization timed out!\n",
ha->host_no, __func__));
if (ha->firmware_state & FW_STATE_CONFIGURING_IP) {
DEBUG2(printk("scsi%ld: %s: FW initialized, but is reporting "
"it's waiting to configure an IP address\n",
ha->host_no, __func__));
ready = 1;
} else if (ha->firmware_state & FW_STATE_WAIT_AUTOCONNECT) {
DEBUG2(printk("scsi%ld: %s: FW initialized, but "
"auto-discovery still in process\n",
ha->host_no, __func__));
ready = 1;
}
return ready;
}
/**
* qla4xxx_init_firmware - initializes the firmware.
* @ha: pointer to host adapter structure.
*
**/
static int qla4xxx_init_firmware(struct scsi_qla_host *ha)
{
int status = QLA_ERROR;
if (is_aer_supported(ha) &&
test_bit(AF_PCI_CHANNEL_IO_PERM_FAILURE, &ha->flags))
return status;
/* For 82xx, stop firmware before initializing because if BIOS
* has previously initialized firmware, then driver's initialize
* firmware will fail. */
if (is_qla8022(ha))
qla4_8xxx_stop_firmware(ha);
ql4_printk(KERN_INFO, ha, "Initializing firmware..\n");
if (qla4xxx_initialize_fw_cb(ha) == QLA_ERROR) {
DEBUG2(printk("scsi%ld: %s: Failed to initialize firmware "
"control block\n", ha->host_no, __func__));
return status;
}
if (!qla4xxx_fw_ready(ha))
return status;
return qla4xxx_get_firmware_status(ha);
}
static void qla4xxx_set_model_info(struct scsi_qla_host *ha)
{
uint16_t board_id_string[8];
int i;
int size = sizeof(ha->nvram->isp4022.boardIdStr);
int offset = offsetof(struct eeprom_data, isp4022.boardIdStr) / 2;
for (i = 0; i < (size / 2) ; i++) {
board_id_string[i] = rd_nvram_word(ha, offset);
offset += 1;
}
memcpy(ha->model_name, board_id_string, size);
}
static int qla4xxx_config_nvram(struct scsi_qla_host *ha)
{
unsigned long flags;
union external_hw_config_reg extHwConfig;
DEBUG2(printk("scsi%ld: %s: Get EEProm parameters \n", ha->host_no,
__func__));
if (ql4xxx_lock_flash(ha) != QLA_SUCCESS)
return QLA_ERROR;
if (ql4xxx_lock_nvram(ha) != QLA_SUCCESS) {
ql4xxx_unlock_flash(ha);
return QLA_ERROR;
}
/* Get EEPRom Parameters from NVRAM and validate */
ql4_printk(KERN_INFO, ha, "Configuring NVRAM ...\n");
if (qla4xxx_is_nvram_configuration_valid(ha) == QLA_SUCCESS) {
spin_lock_irqsave(&ha->hardware_lock, flags);
extHwConfig.Asuint32_t =
rd_nvram_word(ha, eeprom_ext_hw_conf_offset(ha));
spin_unlock_irqrestore(&ha->hardware_lock, flags);
} else {
ql4_printk(KERN_WARNING, ha,
"scsi%ld: %s: EEProm checksum invalid. "
"Please update your EEPROM\n", ha->host_no,
__func__);
/* Attempt to set defaults */
if (is_qla4010(ha))
extHwConfig.Asuint32_t = 0x1912;
else if (is_qla4022(ha) | is_qla4032(ha))
extHwConfig.Asuint32_t = 0x0023;
else
return QLA_ERROR;
}
if (is_qla4022(ha) || is_qla4032(ha))
qla4xxx_set_model_info(ha);
else
strcpy(ha->model_name, "QLA4010");
DEBUG(printk("scsi%ld: %s: Setting extHwConfig to 0xFFFF%04x\n",
ha->host_no, __func__, extHwConfig.Asuint32_t));
spin_lock_irqsave(&ha->hardware_lock, flags);
writel((0xFFFF << 16) | extHwConfig.Asuint32_t, isp_ext_hw_conf(ha));
readl(isp_ext_hw_conf(ha));
spin_unlock_irqrestore(&ha->hardware_lock, flags);
ql4xxx_unlock_nvram(ha);
ql4xxx_unlock_flash(ha);
return QLA_SUCCESS;
}
/**
* qla4_8xxx_pci_config() - Setup ISP82xx PCI configuration registers.
* @ha: HA context
*/
void qla4_8xxx_pci_config(struct scsi_qla_host *ha)
{
pci_set_master(ha->pdev);
}
void qla4xxx_pci_config(struct scsi_qla_host *ha)
{
uint16_t w;
int status;
ql4_printk(KERN_INFO, ha, "Configuring PCI space...\n");
pci_set_master(ha->pdev);
status = pci_set_mwi(ha->pdev);
/*
* We want to respect framework's setting of PCI configuration space
* command register and also want to make sure that all bits of
* interest to us are properly set in command register.
*/
pci_read_config_word(ha->pdev, PCI_COMMAND, &w);
w |= PCI_COMMAND_PARITY | PCI_COMMAND_SERR;
w &= ~PCI_COMMAND_INTX_DISABLE;
pci_write_config_word(ha->pdev, PCI_COMMAND, w);
}
static int qla4xxx_start_firmware_from_flash(struct scsi_qla_host *ha)
{
int status = QLA_ERROR;
unsigned long max_wait_time;
unsigned long flags;
uint32_t mbox_status;
ql4_printk(KERN_INFO, ha, "Starting firmware ...\n");
/*
* Start firmware from flash ROM
*
* WORKAROUND: Stuff a non-constant value that the firmware can
* use as a seed for a random number generator in MB7 prior to
* setting BOOT_ENABLE. Fixes problem where the TCP
* connections use the same TCP ports after each reboot,
* causing some connections to not get re-established.
*/
DEBUG(printk("scsi%d: %s: Start firmware from flash ROM\n",
ha->host_no, __func__));
spin_lock_irqsave(&ha->hardware_lock, flags);
writel(jiffies, &ha->reg->mailbox[7]);
if (is_qla4022(ha) | is_qla4032(ha))
writel(set_rmask(NVR_WRITE_ENABLE),
&ha->reg->u1.isp4022.nvram);
writel(2, &ha->reg->mailbox[6]);
readl(&ha->reg->mailbox[6]);
writel(set_rmask(CSR_BOOT_ENABLE), &ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
/* Wait for firmware to come UP. */
DEBUG2(printk(KERN_INFO "scsi%ld: %s: Wait up to %d seconds for "
"boot firmware to complete...\n",
ha->host_no, __func__, FIRMWARE_UP_TOV));
max_wait_time = jiffies + (FIRMWARE_UP_TOV * HZ);
do {
uint32_t ctrl_status;
spin_lock_irqsave(&ha->hardware_lock, flags);
ctrl_status = readw(&ha->reg->ctrl_status);
mbox_status = readw(&ha->reg->mailbox[0]);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
if (ctrl_status & set_rmask(CSR_SCSI_PROCESSOR_INTR))
break;
if (mbox_status == MBOX_STS_COMMAND_COMPLETE)
break;
DEBUG2(printk(KERN_INFO "scsi%ld: %s: Waiting for boot "
"firmware to complete... ctrl_sts=0x%x, remaining=%ld\n",
ha->host_no, __func__, ctrl_status, max_wait_time));
msleep_interruptible(250);
} while (!time_after_eq(jiffies, max_wait_time));
if (mbox_status == MBOX_STS_COMMAND_COMPLETE) {
DEBUG(printk(KERN_INFO "scsi%ld: %s: Firmware has started\n",
ha->host_no, __func__));
spin_lock_irqsave(&ha->hardware_lock, flags);
writel(set_rmask(CSR_SCSI_PROCESSOR_INTR),
&ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
status = QLA_SUCCESS;
} else {
printk(KERN_INFO "scsi%ld: %s: Boot firmware failed "
"- mbox status 0x%x\n", ha->host_no, __func__,
mbox_status);
status = QLA_ERROR;
}
return status;
}
int ql4xxx_lock_drvr_wait(struct scsi_qla_host *a)
{
#define QL4_LOCK_DRVR_WAIT 60
#define QL4_LOCK_DRVR_SLEEP 1
int drvr_wait = QL4_LOCK_DRVR_WAIT;
while (drvr_wait) {
if (ql4xxx_lock_drvr(a) == 0) {
ssleep(QL4_LOCK_DRVR_SLEEP);
if (drvr_wait) {
DEBUG2(printk("scsi%ld: %s: Waiting for "
"Global Init Semaphore(%d)...\n",
a->host_no,
__func__, drvr_wait));
}
drvr_wait -= QL4_LOCK_DRVR_SLEEP;
} else {
DEBUG2(printk("scsi%ld: %s: Global Init Semaphore "
"acquired\n", a->host_no, __func__));
return QLA_SUCCESS;
}
}
return QLA_ERROR;
}
/**
* qla4xxx_start_firmware - starts qla4xxx firmware
* @ha: Pointer to host adapter structure.
*
* This routine performs the necessary steps to start the firmware for
* the QLA4010 adapter.
**/
int qla4xxx_start_firmware(struct scsi_qla_host *ha)
{
unsigned long flags = 0;
uint32_t mbox_status;
int status = QLA_ERROR;
int soft_reset = 1;
int config_chip = 0;
if (is_qla4022(ha) | is_qla4032(ha))
ql4xxx_set_mac_number(ha);
if (ql4xxx_lock_drvr_wait(ha) != QLA_SUCCESS)
return QLA_ERROR;
spin_lock_irqsave(&ha->hardware_lock, flags);
DEBUG2(printk("scsi%ld: %s: port_ctrl = 0x%08X\n", ha->host_no,
__func__, readw(isp_port_ctrl(ha))));
DEBUG(printk("scsi%ld: %s: port_status = 0x%08X\n", ha->host_no,
__func__, readw(isp_port_status(ha))));
/* Is Hardware already initialized? */
if ((readw(isp_port_ctrl(ha)) & 0x8000) != 0) {
DEBUG(printk("scsi%ld: %s: Hardware has already been "
"initialized\n", ha->host_no, __func__));
/* Receive firmware boot acknowledgement */
mbox_status = readw(&ha->reg->mailbox[0]);
DEBUG2(printk("scsi%ld: %s: H/W Config complete - mbox[0]= "
"0x%x\n", ha->host_no, __func__, mbox_status));
/* Is firmware already booted? */
if (mbox_status == 0) {
/* F/W not running, must be config by net driver */
config_chip = 1;
soft_reset = 0;
} else {
writel(set_rmask(CSR_SCSI_PROCESSOR_INTR),
&ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
writel(set_rmask(CSR_SCSI_COMPLETION_INTR),
&ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
if (qla4xxx_get_firmware_state(ha) == QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: Get firmware "
"state -- state = 0x%x\n",
ha->host_no,
__func__, ha->firmware_state));
/* F/W is running */
if (ha->firmware_state &
FW_STATE_CONFIG_WAIT) {
DEBUG2(printk("scsi%ld: %s: Firmware "
"in known state -- "
"config and "
"boot, state = 0x%x\n",
ha->host_no, __func__,
ha->firmware_state));
config_chip = 1;
soft_reset = 0;
}
} else {
DEBUG2(printk("scsi%ld: %s: Firmware in "
"unknown state -- resetting,"
" state = "
"0x%x\n", ha->host_no, __func__,
ha->firmware_state));
}
spin_lock_irqsave(&ha->hardware_lock, flags);
}
} else {
DEBUG(printk("scsi%ld: %s: H/W initialization hasn't been "
"started - resetting\n", ha->host_no, __func__));
}
spin_unlock_irqrestore(&ha->hardware_lock, flags);
DEBUG(printk("scsi%ld: %s: Flags soft_rest=%d, config= %d\n ",
ha->host_no, __func__, soft_reset, config_chip));
if (soft_reset) {
DEBUG(printk("scsi%ld: %s: Issue Soft Reset\n", ha->host_no,
__func__));
status = qla4xxx_soft_reset(ha); /* NOTE: acquires drvr
* lock again, but ok */
if (status == QLA_ERROR) {
DEBUG(printk("scsi%d: %s: Soft Reset failed!\n",
ha->host_no, __func__));
ql4xxx_unlock_drvr(ha);
return QLA_ERROR;
}
config_chip = 1;
/* Reset clears the semaphore, so acquire again */
if (ql4xxx_lock_drvr_wait(ha) != QLA_SUCCESS)
return QLA_ERROR;
}
if (config_chip) {
if ((status = qla4xxx_config_nvram(ha)) == QLA_SUCCESS)
status = qla4xxx_start_firmware_from_flash(ha);
}
ql4xxx_unlock_drvr(ha);
if (status == QLA_SUCCESS) {
if (test_and_clear_bit(AF_GET_CRASH_RECORD, &ha->flags))
qla4xxx_get_crash_record(ha);
} else {
DEBUG(printk("scsi%ld: %s: Firmware has NOT started\n",
ha->host_no, __func__));
}
return status;
}
/**
* qla4xxx_free_ddb_index - Free DDBs reserved by firmware
* @ha: pointer to adapter structure
*
* Since firmware is not running in autoconnect mode the DDB indices should
* be freed so that when login happens from user space there are free DDB
* indices available.
**/
void qla4xxx_free_ddb_index(struct scsi_qla_host *ha)
{
int max_ddbs;
int ret;
uint32_t idx = 0, next_idx = 0;
uint32_t state = 0, conn_err = 0;
max_ddbs = is_qla40XX(ha) ? MAX_DEV_DB_ENTRIES_40XX :
MAX_DEV_DB_ENTRIES;
for (idx = 0; idx < max_ddbs; idx = next_idx) {
ret = qla4xxx_get_fwddb_entry(ha, idx, NULL, 0, NULL,
&next_idx, &state, &conn_err,
NULL, NULL);
if (ret == QLA_ERROR) {
next_idx++;
continue;
}
if (state == DDB_DS_NO_CONNECTION_ACTIVE ||
state == DDB_DS_SESSION_FAILED) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"Freeing DDB index = 0x%x\n", idx));
ret = qla4xxx_clear_ddb_entry(ha, idx);
if (ret == QLA_ERROR)
ql4_printk(KERN_ERR, ha,
"Unable to clear DDB index = "
"0x%x\n", idx);
}
if (next_idx == 0)
break;
}
}
/**
* qla4xxx_initialize_adapter - initiailizes hba
* @ha: Pointer to host adapter structure.
*
* This routine parforms all of the steps necessary to initialize the adapter.
*
**/
int qla4xxx_initialize_adapter(struct scsi_qla_host *ha, int is_reset)
{
int status = QLA_ERROR;
ha->eeprom_cmd_data = 0;
ql4_printk(KERN_INFO, ha, "Configuring PCI space...\n");
ha->isp_ops->pci_config(ha);
ha->isp_ops->disable_intrs(ha);
/* Initialize the Host adapter request/response queues and firmware */
if (ha->isp_ops->start_firmware(ha) == QLA_ERROR)
goto exit_init_hba;
if (qla4xxx_about_firmware(ha) == QLA_ERROR)
goto exit_init_hba;
if (ha->isp_ops->get_sys_info(ha) == QLA_ERROR)
goto exit_init_hba;
if (qla4xxx_init_local_data(ha) == QLA_ERROR)
goto exit_init_hba;
status = qla4xxx_init_firmware(ha);
if (status == QLA_ERROR)
goto exit_init_hba;
if (is_reset == RESET_ADAPTER)
qla4xxx_build_ddb_list(ha, is_reset);
set_bit(AF_ONLINE, &ha->flags);
exit_init_hba:
if (is_qla8022(ha) && (status == QLA_ERROR)) {
/* Since interrupts are registered in start_firmware for
* 82xx, release them here if initialize_adapter fails */
qla4xxx_free_irqs(ha);
}
DEBUG2(printk("scsi%ld: initialize adapter: %s\n", ha->host_no,
status == QLA_ERROR ? "FAILED" : "SUCCEEDED"));
return status;
}
int qla4xxx_ddb_change(struct scsi_qla_host *ha, uint32_t fw_ddb_index,
struct ddb_entry *ddb_entry, uint32_t state)
{
uint32_t old_fw_ddb_device_state;
int status = QLA_ERROR;
old_fw_ddb_device_state = ddb_entry->fw_ddb_device_state;
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s: DDB - old state = 0x%x, new state = 0x%x for "
"index [%d]\n", __func__,
ddb_entry->fw_ddb_device_state, state, fw_ddb_index));
ddb_entry->fw_ddb_device_state = state;
switch (old_fw_ddb_device_state) {
case DDB_DS_LOGIN_IN_PROCESS:
switch (state) {
case DDB_DS_SESSION_ACTIVE:
case DDB_DS_DISCOVERY:
ddb_entry->unblock_sess(ddb_entry->sess);
qla4xxx_update_session_conn_param(ha, ddb_entry);
status = QLA_SUCCESS;
break;
case DDB_DS_SESSION_FAILED:
case DDB_DS_NO_CONNECTION_ACTIVE:
iscsi_conn_login_event(ddb_entry->conn,
ISCSI_CONN_STATE_FREE);
status = QLA_SUCCESS;
break;
}
break;
case DDB_DS_SESSION_ACTIVE:
switch (state) {
case DDB_DS_SESSION_FAILED:
/*
* iscsi_session failure will cause userspace to
* stop the connection which in turn would block the
* iscsi_session and start relogin
*/
iscsi_session_failure(ddb_entry->sess->dd_data,
ISCSI_ERR_CONN_FAILED);
status = QLA_SUCCESS;
break;
case DDB_DS_NO_CONNECTION_ACTIVE:
clear_bit(fw_ddb_index, ha->ddb_idx_map);
status = QLA_SUCCESS;
break;
}
break;
case DDB_DS_SESSION_FAILED:
switch (state) {
case DDB_DS_SESSION_ACTIVE:
case DDB_DS_DISCOVERY:
ddb_entry->unblock_sess(ddb_entry->sess);
qla4xxx_update_session_conn_param(ha, ddb_entry);
status = QLA_SUCCESS;
break;
case DDB_DS_SESSION_FAILED:
iscsi_session_failure(ddb_entry->sess->dd_data,
ISCSI_ERR_CONN_FAILED);
status = QLA_SUCCESS;
break;
}
break;
default:
DEBUG2(ql4_printk(KERN_INFO, ha, "%s: Unknown Event\n",
__func__));
break;
}
return status;
}
void qla4xxx_arm_relogin_timer(struct ddb_entry *ddb_entry)
{
/*
* This triggers a relogin. After the relogin_timer
* expires, the relogin gets scheduled. We must wait a
* minimum amount of time since receiving an 0x8014 AEN
* with failed device_state or a logout response before
* we can issue another relogin.
*
* Firmware pads this timeout: (time2wait +1).
* Driver retry to login should be longer than F/W.
* Otherwise F/W will fail
* set_ddb() mbx cmd with 0x4005 since it still
* counting down its time2wait.
*/
atomic_set(&ddb_entry->relogin_timer, 0);
atomic_set(&ddb_entry->retry_relogin_timer,
ddb_entry->default_time2wait + 4);
}
int qla4xxx_flash_ddb_change(struct scsi_qla_host *ha, uint32_t fw_ddb_index,
struct ddb_entry *ddb_entry, uint32_t state)
{
uint32_t old_fw_ddb_device_state;
int status = QLA_ERROR;
old_fw_ddb_device_state = ddb_entry->fw_ddb_device_state;
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s: DDB - old state = 0x%x, new state = 0x%x for "
"index [%d]\n", __func__,
ddb_entry->fw_ddb_device_state, state, fw_ddb_index));
ddb_entry->fw_ddb_device_state = state;
switch (old_fw_ddb_device_state) {
case DDB_DS_LOGIN_IN_PROCESS:
case DDB_DS_NO_CONNECTION_ACTIVE:
switch (state) {
case DDB_DS_SESSION_ACTIVE:
ddb_entry->unblock_sess(ddb_entry->sess);
qla4xxx_update_session_conn_fwddb_param(ha, ddb_entry);
status = QLA_SUCCESS;
break;
case DDB_DS_SESSION_FAILED:
iscsi_block_session(ddb_entry->sess);
if (!test_bit(DF_RELOGIN, &ddb_entry->flags))
qla4xxx_arm_relogin_timer(ddb_entry);
status = QLA_SUCCESS;
break;
}
break;
case DDB_DS_SESSION_ACTIVE:
switch (state) {
case DDB_DS_SESSION_FAILED:
iscsi_block_session(ddb_entry->sess);
if (!test_bit(DF_RELOGIN, &ddb_entry->flags))
qla4xxx_arm_relogin_timer(ddb_entry);
status = QLA_SUCCESS;
break;
}
break;
case DDB_DS_SESSION_FAILED:
switch (state) {
case DDB_DS_SESSION_ACTIVE:
ddb_entry->unblock_sess(ddb_entry->sess);
qla4xxx_update_session_conn_fwddb_param(ha, ddb_entry);
status = QLA_SUCCESS;
break;
case DDB_DS_SESSION_FAILED:
if (!test_bit(DF_RELOGIN, &ddb_entry->flags))
qla4xxx_arm_relogin_timer(ddb_entry);
status = QLA_SUCCESS;
break;
}
break;
default:
DEBUG2(ql4_printk(KERN_INFO, ha, "%s: Unknown Event\n",
__func__));
break;
}
return status;
}
/**
* qla4xxx_process_ddb_changed - process ddb state change
* @ha - Pointer to host adapter structure.
* @fw_ddb_index - Firmware's device database index
* @state - Device state
*
* This routine processes a Decive Database Changed AEN Event.
**/
int qla4xxx_process_ddb_changed(struct scsi_qla_host *ha,
uint32_t fw_ddb_index,
uint32_t state, uint32_t conn_err)
{
struct ddb_entry *ddb_entry;
int status = QLA_ERROR;
/* check for out of range index */
if (fw_ddb_index >= MAX_DDB_ENTRIES)
goto exit_ddb_event;
/* Get the corresponging ddb entry */
ddb_entry = qla4xxx_lookup_ddb_by_fw_index(ha, fw_ddb_index);
/* Device does not currently exist in our database. */
if (ddb_entry == NULL) {
ql4_printk(KERN_ERR, ha, "%s: No ddb_entry at FW index [%d]\n",
__func__, fw_ddb_index);
if (state == DDB_DS_NO_CONNECTION_ACTIVE)
clear_bit(fw_ddb_index, ha->ddb_idx_map);
goto exit_ddb_event;
}
ddb_entry->ddb_change(ha, fw_ddb_index, ddb_entry, state);
exit_ddb_event:
return status;
}
/**
* qla4xxx_login_flash_ddb - Login to target (DDB)
* @cls_session: Pointer to the session to login
*
* This routine logins to the target.
* Issues setddb and conn open mbx
**/
void qla4xxx_login_flash_ddb(struct iscsi_cls_session *cls_session)
{
struct iscsi_session *sess;
struct ddb_entry *ddb_entry;
struct scsi_qla_host *ha;
struct dev_db_entry *fw_ddb_entry = NULL;
dma_addr_t fw_ddb_dma;
uint32_t mbx_sts = 0;
int ret;
sess = cls_session->dd_data;
ddb_entry = sess->dd_data;
ha = ddb_entry->ha;
if (!test_bit(AF_LINK_UP, &ha->flags))
return;
if (ddb_entry->ddb_type != FLASH_DDB) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"Skipping login to non FLASH DB"));
goto exit_login;
}
fw_ddb_entry = dma_pool_alloc(ha->fw_ddb_dma_pool, GFP_KERNEL,
&fw_ddb_dma);
if (fw_ddb_entry == NULL) {
DEBUG2(ql4_printk(KERN_ERR, ha, "Out of memory\n"));
goto exit_login;
}
if (ddb_entry->fw_ddb_index == INVALID_ENTRY) {
ret = qla4xxx_get_ddb_index(ha, &ddb_entry->fw_ddb_index);
if (ret == QLA_ERROR)
goto exit_login;
ha->fw_ddb_index_map[ddb_entry->fw_ddb_index] = ddb_entry;
ha->tot_ddbs++;
}
memcpy(fw_ddb_entry, &ddb_entry->fw_ddb_entry,
sizeof(struct dev_db_entry));
ddb_entry->sess->target_id = ddb_entry->fw_ddb_index;
ret = qla4xxx_set_ddb_entry(ha, ddb_entry->fw_ddb_index,
fw_ddb_dma, &mbx_sts);
if (ret == QLA_ERROR) {
DEBUG2(ql4_printk(KERN_ERR, ha, "Set DDB failed\n"));
goto exit_login;
}
ddb_entry->fw_ddb_device_state = DDB_DS_LOGIN_IN_PROCESS;
ret = qla4xxx_conn_open(ha, ddb_entry->fw_ddb_index);
if (ret == QLA_ERROR) {
ql4_printk(KERN_ERR, ha, "%s: Login failed: %s\n", __func__,
sess->targetname);
goto exit_login;
}
exit_login:
if (fw_ddb_entry)
dma_pool_free(ha->fw_ddb_dma_pool, fw_ddb_entry, fw_ddb_dma);
}
| gpl-2.0 |
basr/hammerhead_sbr | drivers/net/wireless/wl12xx/scan.c | 4807 | 20193 | /*
* This file is part of wl1271
*
* Copyright (C) 2009-2010 Nokia Corporation
*
* Contact: Luciano Coelho <luciano.coelho@nokia.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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/ieee80211.h>
#include "wl12xx.h"
#include "debug.h"
#include "cmd.h"
#include "scan.h"
#include "acx.h"
#include "ps.h"
#include "tx.h"
void wl1271_scan_complete_work(struct work_struct *work)
{
struct delayed_work *dwork;
struct wl1271 *wl;
struct ieee80211_vif *vif;
struct wl12xx_vif *wlvif;
int ret;
dwork = container_of(work, struct delayed_work, work);
wl = container_of(dwork, struct wl1271, scan_complete_work);
wl1271_debug(DEBUG_SCAN, "Scanning complete");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF)
goto out;
if (wl->scan.state == WL1271_SCAN_STATE_IDLE)
goto out;
vif = wl->scan_vif;
wlvif = wl12xx_vif_to_data(vif);
/*
* Rearm the tx watchdog just before idling scan. This
* prevents just-finished scans from triggering the watchdog
*/
wl12xx_rearm_tx_watchdog_locked(wl);
wl->scan.state = WL1271_SCAN_STATE_IDLE;
memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch));
wl->scan.req = NULL;
wl->scan_vif = NULL;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) {
/* restore hardware connection monitoring template */
wl1271_cmd_build_ap_probe_req(wl, wlvif, wlvif->probereq);
}
wl1271_ps_elp_sleep(wl);
if (wl->scan.failed) {
wl1271_info("Scan completed due to error.");
wl12xx_queue_recovery_work(wl);
}
ieee80211_scan_completed(wl->hw, false);
out:
mutex_unlock(&wl->mutex);
}
static int wl1271_get_scan_channels(struct wl1271 *wl,
struct cfg80211_scan_request *req,
struct basic_scan_channel_params *channels,
enum ieee80211_band band, bool passive)
{
struct conf_scan_settings *c = &wl->conf.scan;
int i, j;
u32 flags;
for (i = 0, j = 0;
i < req->n_channels && j < WL1271_SCAN_MAX_CHANNELS;
i++) {
flags = req->channels[i]->flags;
if (!test_bit(i, wl->scan.scanned_ch) &&
!(flags & IEEE80211_CHAN_DISABLED) &&
(req->channels[i]->band == band) &&
/*
* In passive scans, we scan all remaining
* channels, even if not marked as such.
* In active scans, we only scan channels not
* marked as passive.
*/
(passive || !(flags & IEEE80211_CHAN_PASSIVE_SCAN))) {
wl1271_debug(DEBUG_SCAN, "band %d, center_freq %d ",
req->channels[i]->band,
req->channels[i]->center_freq);
wl1271_debug(DEBUG_SCAN, "hw_value %d, flags %X",
req->channels[i]->hw_value,
req->channels[i]->flags);
wl1271_debug(DEBUG_SCAN,
"max_antenna_gain %d, max_power %d",
req->channels[i]->max_antenna_gain,
req->channels[i]->max_power);
wl1271_debug(DEBUG_SCAN, "beacon_found %d",
req->channels[i]->beacon_found);
if (!passive) {
channels[j].min_duration =
cpu_to_le32(c->min_dwell_time_active);
channels[j].max_duration =
cpu_to_le32(c->max_dwell_time_active);
} else {
channels[j].min_duration =
cpu_to_le32(c->min_dwell_time_passive);
channels[j].max_duration =
cpu_to_le32(c->max_dwell_time_passive);
}
channels[j].early_termination = 0;
channels[j].tx_power_att = req->channels[i]->max_power;
channels[j].channel = req->channels[i]->hw_value;
memset(&channels[j].bssid_lsb, 0xff, 4);
memset(&channels[j].bssid_msb, 0xff, 2);
/* Mark the channels we already used */
set_bit(i, wl->scan.scanned_ch);
j++;
}
}
return j;
}
#define WL1271_NOTHING_TO_SCAN 1
static int wl1271_scan_send(struct wl1271 *wl, struct ieee80211_vif *vif,
enum ieee80211_band band,
bool passive, u32 basic_rate)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct wl1271_cmd_scan *cmd;
struct wl1271_cmd_trigger_scan_to *trigger;
int ret;
u16 scan_options = 0;
/* skip active scans if we don't have SSIDs */
if (!passive && wl->scan.req->n_ssids == 0)
return WL1271_NOTHING_TO_SCAN;
cmd = kzalloc(sizeof(*cmd), GFP_KERNEL);
trigger = kzalloc(sizeof(*trigger), GFP_KERNEL);
if (!cmd || !trigger) {
ret = -ENOMEM;
goto out;
}
if (wl->conf.scan.split_scan_timeout)
scan_options |= WL1271_SCAN_OPT_SPLIT_SCAN;
if (passive)
scan_options |= WL1271_SCAN_OPT_PASSIVE;
if (wlvif->bss_type == BSS_TYPE_AP_BSS ||
test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
cmd->params.role_id = wlvif->role_id;
else
cmd->params.role_id = wlvif->dev_role_id;
if (WARN_ON(cmd->params.role_id == WL12XX_INVALID_ROLE_ID)) {
ret = -EINVAL;
goto out;
}
cmd->params.scan_options = cpu_to_le16(scan_options);
cmd->params.n_ch = wl1271_get_scan_channels(wl, wl->scan.req,
cmd->channels,
band, passive);
if (cmd->params.n_ch == 0) {
ret = WL1271_NOTHING_TO_SCAN;
goto out;
}
cmd->params.tx_rate = cpu_to_le32(basic_rate);
cmd->params.n_probe_reqs = wl->conf.scan.num_probe_reqs;
cmd->params.tid_trigger = CONF_TX_AC_ANY_TID;
cmd->params.scan_tag = WL1271_SCAN_DEFAULT_TAG;
if (band == IEEE80211_BAND_2GHZ)
cmd->params.band = WL1271_SCAN_BAND_2_4_GHZ;
else
cmd->params.band = WL1271_SCAN_BAND_5_GHZ;
if (wl->scan.ssid_len && wl->scan.ssid) {
cmd->params.ssid_len = wl->scan.ssid_len;
memcpy(cmd->params.ssid, wl->scan.ssid, wl->scan.ssid_len);
}
memcpy(cmd->addr, vif->addr, ETH_ALEN);
ret = wl12xx_cmd_build_probe_req(wl, wlvif,
cmd->params.role_id, band,
wl->scan.ssid, wl->scan.ssid_len,
wl->scan.req->ie,
wl->scan.req->ie_len);
if (ret < 0) {
wl1271_error("PROBE request template failed");
goto out;
}
trigger->timeout = cpu_to_le32(wl->conf.scan.split_scan_timeout);
ret = wl1271_cmd_send(wl, CMD_TRIGGER_SCAN_TO, trigger,
sizeof(*trigger), 0);
if (ret < 0) {
wl1271_error("trigger scan to failed for hw scan");
goto out;
}
wl1271_dump(DEBUG_SCAN, "SCAN: ", cmd, sizeof(*cmd));
ret = wl1271_cmd_send(wl, CMD_SCAN, cmd, sizeof(*cmd), 0);
if (ret < 0) {
wl1271_error("SCAN failed");
goto out;
}
out:
kfree(cmd);
kfree(trigger);
return ret;
}
void wl1271_scan_stm(struct wl1271 *wl, struct ieee80211_vif *vif)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret = 0;
enum ieee80211_band band;
u32 rate, mask;
switch (wl->scan.state) {
case WL1271_SCAN_STATE_IDLE:
break;
case WL1271_SCAN_STATE_2GHZ_ACTIVE:
band = IEEE80211_BAND_2GHZ;
mask = wlvif->bitrate_masks[band];
if (wl->scan.req->no_cck) {
mask &= ~CONF_TX_CCK_RATES;
if (!mask)
mask = CONF_TX_RATE_MASK_BASIC_P2P;
}
rate = wl1271_tx_min_rate_get(wl, mask);
ret = wl1271_scan_send(wl, vif, band, false, rate);
if (ret == WL1271_NOTHING_TO_SCAN) {
wl->scan.state = WL1271_SCAN_STATE_2GHZ_PASSIVE;
wl1271_scan_stm(wl, vif);
}
break;
case WL1271_SCAN_STATE_2GHZ_PASSIVE:
band = IEEE80211_BAND_2GHZ;
mask = wlvif->bitrate_masks[band];
if (wl->scan.req->no_cck) {
mask &= ~CONF_TX_CCK_RATES;
if (!mask)
mask = CONF_TX_RATE_MASK_BASIC_P2P;
}
rate = wl1271_tx_min_rate_get(wl, mask);
ret = wl1271_scan_send(wl, vif, band, true, rate);
if (ret == WL1271_NOTHING_TO_SCAN) {
if (wl->enable_11a)
wl->scan.state = WL1271_SCAN_STATE_5GHZ_ACTIVE;
else
wl->scan.state = WL1271_SCAN_STATE_DONE;
wl1271_scan_stm(wl, vif);
}
break;
case WL1271_SCAN_STATE_5GHZ_ACTIVE:
band = IEEE80211_BAND_5GHZ;
rate = wl1271_tx_min_rate_get(wl, wlvif->bitrate_masks[band]);
ret = wl1271_scan_send(wl, vif, band, false, rate);
if (ret == WL1271_NOTHING_TO_SCAN) {
wl->scan.state = WL1271_SCAN_STATE_5GHZ_PASSIVE;
wl1271_scan_stm(wl, vif);
}
break;
case WL1271_SCAN_STATE_5GHZ_PASSIVE:
band = IEEE80211_BAND_5GHZ;
rate = wl1271_tx_min_rate_get(wl, wlvif->bitrate_masks[band]);
ret = wl1271_scan_send(wl, vif, band, true, rate);
if (ret == WL1271_NOTHING_TO_SCAN) {
wl->scan.state = WL1271_SCAN_STATE_DONE;
wl1271_scan_stm(wl, vif);
}
break;
case WL1271_SCAN_STATE_DONE:
wl->scan.failed = false;
cancel_delayed_work(&wl->scan_complete_work);
ieee80211_queue_delayed_work(wl->hw, &wl->scan_complete_work,
msecs_to_jiffies(0));
break;
default:
wl1271_error("invalid scan state");
break;
}
if (ret < 0) {
cancel_delayed_work(&wl->scan_complete_work);
ieee80211_queue_delayed_work(wl->hw, &wl->scan_complete_work,
msecs_to_jiffies(0));
}
}
int wl1271_scan(struct wl1271 *wl, struct ieee80211_vif *vif,
const u8 *ssid, size_t ssid_len,
struct cfg80211_scan_request *req)
{
/*
* cfg80211 should guarantee that we don't get more channels
* than what we have registered.
*/
BUG_ON(req->n_channels > WL1271_MAX_CHANNELS);
if (wl->scan.state != WL1271_SCAN_STATE_IDLE)
return -EBUSY;
wl->scan.state = WL1271_SCAN_STATE_2GHZ_ACTIVE;
if (ssid_len && ssid) {
wl->scan.ssid_len = ssid_len;
memcpy(wl->scan.ssid, ssid, ssid_len);
} else {
wl->scan.ssid_len = 0;
}
wl->scan_vif = vif;
wl->scan.req = req;
memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch));
/* we assume failure so that timeout scenarios are handled correctly */
wl->scan.failed = true;
ieee80211_queue_delayed_work(wl->hw, &wl->scan_complete_work,
msecs_to_jiffies(WL1271_SCAN_TIMEOUT));
wl1271_scan_stm(wl, vif);
return 0;
}
int wl1271_scan_stop(struct wl1271 *wl)
{
struct wl1271_cmd_header *cmd = NULL;
int ret = 0;
if (WARN_ON(wl->scan.state == WL1271_SCAN_STATE_IDLE))
return -EINVAL;
wl1271_debug(DEBUG_CMD, "cmd scan stop");
cmd = kzalloc(sizeof(*cmd), GFP_KERNEL);
if (!cmd) {
ret = -ENOMEM;
goto out;
}
ret = wl1271_cmd_send(wl, CMD_STOP_SCAN, cmd,
sizeof(*cmd), 0);
if (ret < 0) {
wl1271_error("cmd stop_scan failed");
goto out;
}
out:
kfree(cmd);
return ret;
}
static int
wl1271_scan_get_sched_scan_channels(struct wl1271 *wl,
struct cfg80211_sched_scan_request *req,
struct conn_scan_ch_params *channels,
u32 band, bool radar, bool passive,
int start, int max_channels)
{
struct conf_sched_scan_settings *c = &wl->conf.sched_scan;
int i, j;
u32 flags;
bool force_passive = !req->n_ssids;
for (i = 0, j = start;
i < req->n_channels && j < max_channels;
i++) {
flags = req->channels[i]->flags;
if (force_passive)
flags |= IEEE80211_CHAN_PASSIVE_SCAN;
if ((req->channels[i]->band == band) &&
!(flags & IEEE80211_CHAN_DISABLED) &&
(!!(flags & IEEE80211_CHAN_RADAR) == radar) &&
/* if radar is set, we ignore the passive flag */
(radar ||
!!(flags & IEEE80211_CHAN_PASSIVE_SCAN) == passive)) {
wl1271_debug(DEBUG_SCAN, "band %d, center_freq %d ",
req->channels[i]->band,
req->channels[i]->center_freq);
wl1271_debug(DEBUG_SCAN, "hw_value %d, flags %X",
req->channels[i]->hw_value,
req->channels[i]->flags);
wl1271_debug(DEBUG_SCAN, "max_power %d",
req->channels[i]->max_power);
if (flags & IEEE80211_CHAN_RADAR) {
channels[j].flags |= SCAN_CHANNEL_FLAGS_DFS;
channels[j].passive_duration =
cpu_to_le16(c->dwell_time_dfs);
} else {
channels[j].passive_duration =
cpu_to_le16(c->dwell_time_passive);
}
channels[j].min_duration =
cpu_to_le16(c->min_dwell_time_active);
channels[j].max_duration =
cpu_to_le16(c->max_dwell_time_active);
channels[j].tx_power_att = req->channels[i]->max_power;
channels[j].channel = req->channels[i]->hw_value;
j++;
}
}
return j - start;
}
static bool
wl1271_scan_sched_scan_channels(struct wl1271 *wl,
struct cfg80211_sched_scan_request *req,
struct wl1271_cmd_sched_scan_config *cfg)
{
cfg->passive[0] =
wl1271_scan_get_sched_scan_channels(wl, req, cfg->channels_2,
IEEE80211_BAND_2GHZ,
false, true, 0,
MAX_CHANNELS_2GHZ);
cfg->active[0] =
wl1271_scan_get_sched_scan_channels(wl, req, cfg->channels_2,
IEEE80211_BAND_2GHZ,
false, false,
cfg->passive[0],
MAX_CHANNELS_2GHZ);
cfg->passive[1] =
wl1271_scan_get_sched_scan_channels(wl, req, cfg->channels_5,
IEEE80211_BAND_5GHZ,
false, true, 0,
MAX_CHANNELS_5GHZ);
cfg->dfs =
wl1271_scan_get_sched_scan_channels(wl, req, cfg->channels_5,
IEEE80211_BAND_5GHZ,
true, true,
cfg->passive[1],
MAX_CHANNELS_5GHZ);
cfg->active[1] =
wl1271_scan_get_sched_scan_channels(wl, req, cfg->channels_5,
IEEE80211_BAND_5GHZ,
false, false,
cfg->passive[1] + cfg->dfs,
MAX_CHANNELS_5GHZ);
/* 802.11j channels are not supported yet */
cfg->passive[2] = 0;
cfg->active[2] = 0;
wl1271_debug(DEBUG_SCAN, " 2.4GHz: active %d passive %d",
cfg->active[0], cfg->passive[0]);
wl1271_debug(DEBUG_SCAN, " 5GHz: active %d passive %d",
cfg->active[1], cfg->passive[1]);
wl1271_debug(DEBUG_SCAN, " DFS: %d", cfg->dfs);
return cfg->passive[0] || cfg->active[0] ||
cfg->passive[1] || cfg->active[1] || cfg->dfs ||
cfg->passive[2] || cfg->active[2];
}
/* Returns the scan type to be used or a negative value on error */
static int
wl12xx_scan_sched_scan_ssid_list(struct wl1271 *wl,
struct cfg80211_sched_scan_request *req)
{
struct wl1271_cmd_sched_scan_ssid_list *cmd = NULL;
struct cfg80211_match_set *sets = req->match_sets;
struct cfg80211_ssid *ssids = req->ssids;
int ret = 0, type, i, j, n_match_ssids = 0;
wl1271_debug(DEBUG_CMD, "cmd sched scan ssid list");
/* count the match sets that contain SSIDs */
for (i = 0; i < req->n_match_sets; i++)
if (sets[i].ssid.ssid_len > 0)
n_match_ssids++;
/* No filter, no ssids or only bcast ssid */
if (!n_match_ssids &&
(!req->n_ssids ||
(req->n_ssids == 1 && req->ssids[0].ssid_len == 0))) {
type = SCAN_SSID_FILTER_ANY;
goto out;
}
cmd = kzalloc(sizeof(*cmd), GFP_KERNEL);
if (!cmd) {
ret = -ENOMEM;
goto out;
}
if (!n_match_ssids) {
/* No filter, with ssids */
type = SCAN_SSID_FILTER_DISABLED;
for (i = 0; i < req->n_ssids; i++) {
cmd->ssids[cmd->n_ssids].type = (ssids[i].ssid_len) ?
SCAN_SSID_TYPE_HIDDEN : SCAN_SSID_TYPE_PUBLIC;
cmd->ssids[cmd->n_ssids].len = ssids[i].ssid_len;
memcpy(cmd->ssids[cmd->n_ssids].ssid, ssids[i].ssid,
ssids[i].ssid_len);
cmd->n_ssids++;
}
} else {
type = SCAN_SSID_FILTER_LIST;
/* Add all SSIDs from the filters */
for (i = 0; i < req->n_match_sets; i++) {
/* ignore sets without SSIDs */
if (!sets[i].ssid.ssid_len)
continue;
cmd->ssids[cmd->n_ssids].type = SCAN_SSID_TYPE_PUBLIC;
cmd->ssids[cmd->n_ssids].len = sets[i].ssid.ssid_len;
memcpy(cmd->ssids[cmd->n_ssids].ssid,
sets[i].ssid.ssid, sets[i].ssid.ssid_len);
cmd->n_ssids++;
}
if ((req->n_ssids > 1) ||
(req->n_ssids == 1 && req->ssids[0].ssid_len > 0)) {
/*
* Mark all the SSIDs passed in the SSID list as HIDDEN,
* so they're used in probe requests.
*/
for (i = 0; i < req->n_ssids; i++) {
if (!req->ssids[i].ssid_len)
continue;
for (j = 0; j < cmd->n_ssids; j++)
if (!memcmp(req->ssids[i].ssid,
cmd->ssids[j].ssid,
req->ssids[i].ssid_len)) {
cmd->ssids[j].type =
SCAN_SSID_TYPE_HIDDEN;
break;
}
/* Fail if SSID isn't present in the filters */
if (j == cmd->n_ssids) {
ret = -EINVAL;
goto out_free;
}
}
}
}
wl1271_dump(DEBUG_SCAN, "SSID_LIST: ", cmd, sizeof(*cmd));
ret = wl1271_cmd_send(wl, CMD_CONNECTION_SCAN_SSID_CFG, cmd,
sizeof(*cmd), 0);
if (ret < 0) {
wl1271_error("cmd sched scan ssid list failed");
goto out_free;
}
out_free:
kfree(cmd);
out:
if (ret < 0)
return ret;
return type;
}
int wl1271_scan_sched_scan_config(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct cfg80211_sched_scan_request *req,
struct ieee80211_sched_scan_ies *ies)
{
struct wl1271_cmd_sched_scan_config *cfg = NULL;
struct conf_sched_scan_settings *c = &wl->conf.sched_scan;
int i, ret;
bool force_passive = !req->n_ssids;
wl1271_debug(DEBUG_CMD, "cmd sched_scan scan config");
cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
if (!cfg)
return -ENOMEM;
cfg->rssi_threshold = c->rssi_threshold;
cfg->snr_threshold = c->snr_threshold;
cfg->n_probe_reqs = c->num_probe_reqs;
/* cycles set to 0 it means infinite (until manually stopped) */
cfg->cycles = 0;
/* report APs when at least 1 is found */
cfg->report_after = 1;
/* don't stop scanning automatically when something is found */
cfg->terminate = 0;
cfg->tag = WL1271_SCAN_DEFAULT_TAG;
/* don't filter on BSS type */
cfg->bss_type = SCAN_BSS_TYPE_ANY;
/* currently NL80211 supports only a single interval */
for (i = 0; i < SCAN_MAX_CYCLE_INTERVALS; i++)
cfg->intervals[i] = cpu_to_le32(req->interval);
cfg->ssid_len = 0;
ret = wl12xx_scan_sched_scan_ssid_list(wl, req);
if (ret < 0)
goto out;
cfg->filter_type = ret;
wl1271_debug(DEBUG_SCAN, "filter_type = %d", cfg->filter_type);
if (!wl1271_scan_sched_scan_channels(wl, req, cfg)) {
wl1271_error("scan channel list is empty");
ret = -EINVAL;
goto out;
}
if (!force_passive && cfg->active[0]) {
u8 band = IEEE80211_BAND_2GHZ;
ret = wl12xx_cmd_build_probe_req(wl, wlvif,
wlvif->dev_role_id, band,
req->ssids[0].ssid,
req->ssids[0].ssid_len,
ies->ie[band],
ies->len[band]);
if (ret < 0) {
wl1271_error("2.4GHz PROBE request template failed");
goto out;
}
}
if (!force_passive && cfg->active[1]) {
u8 band = IEEE80211_BAND_5GHZ;
ret = wl12xx_cmd_build_probe_req(wl, wlvif,
wlvif->dev_role_id, band,
req->ssids[0].ssid,
req->ssids[0].ssid_len,
ies->ie[band],
ies->len[band]);
if (ret < 0) {
wl1271_error("5GHz PROBE request template failed");
goto out;
}
}
wl1271_dump(DEBUG_SCAN, "SCAN_CFG: ", cfg, sizeof(*cfg));
ret = wl1271_cmd_send(wl, CMD_CONNECTION_SCAN_CFG, cfg,
sizeof(*cfg), 0);
if (ret < 0) {
wl1271_error("SCAN configuration failed");
goto out;
}
out:
kfree(cfg);
return ret;
}
int wl1271_scan_sched_scan_start(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
struct wl1271_cmd_sched_scan_start *start;
int ret = 0;
wl1271_debug(DEBUG_CMD, "cmd periodic scan start");
if (wlvif->bss_type != BSS_TYPE_STA_BSS)
return -EOPNOTSUPP;
if (test_bit(WLVIF_FLAG_IN_USE, &wlvif->flags))
return -EBUSY;
start = kzalloc(sizeof(*start), GFP_KERNEL);
if (!start)
return -ENOMEM;
start->tag = WL1271_SCAN_DEFAULT_TAG;
ret = wl1271_cmd_send(wl, CMD_START_PERIODIC_SCAN, start,
sizeof(*start), 0);
if (ret < 0) {
wl1271_error("failed to send scan start command");
goto out_free;
}
out_free:
kfree(start);
return ret;
}
void wl1271_scan_sched_scan_results(struct wl1271 *wl)
{
wl1271_debug(DEBUG_SCAN, "got periodic scan results");
ieee80211_sched_scan_results(wl->hw);
}
void wl1271_scan_sched_scan_stop(struct wl1271 *wl)
{
struct wl1271_cmd_sched_scan_stop *stop;
int ret = 0;
wl1271_debug(DEBUG_CMD, "cmd periodic scan stop");
/* FIXME: what to do if alloc'ing to stop fails? */
stop = kzalloc(sizeof(*stop), GFP_KERNEL);
if (!stop) {
wl1271_error("failed to alloc memory to send sched scan stop");
return;
}
stop->tag = WL1271_SCAN_DEFAULT_TAG;
ret = wl1271_cmd_send(wl, CMD_STOP_PERIODIC_SCAN, stop,
sizeof(*stop), 0);
if (ret < 0) {
wl1271_error("failed to send sched scan stop command");
goto out_free;
}
out_free:
kfree(stop);
}
| gpl-2.0 |
D2005-devs/android_kernel_sony_msm8610-old | drivers/staging/comedi/drivers/ni_pcidio.c | 4807 | 37288 | /*
comedi/drivers/ni_pcidio.c
driver for National Instruments PCI-DIO-96/PCI-6508
National Instruments PCI-DIO-32HS
National Instruments PCI-6503
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1999,2002 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: ni_pcidio
Description: National Instruments PCI-DIO32HS, PCI-DIO96, PCI-6533, PCI-6503
Author: ds
Status: works
Devices: [National Instruments] PCI-DIO-32HS (ni_pcidio), PXI-6533,
PCI-DIO-96, PCI-DIO-96B, PXI-6508, PCI-6503, PCI-6503B, PCI-6503X,
PXI-6503, PCI-6533, PCI-6534
Updated: Mon, 09 Jan 2012 14:27:23 +0000
The DIO-96 appears as four 8255 subdevices. See the 8255
driver notes for details.
The DIO32HS board appears as one subdevice, with 32 channels.
Each channel is individually I/O configurable. The channel order
is 0=A0, 1=A1, 2=A2, ... 8=B0, 16=C0, 24=D0. The driver only
supports simple digital I/O; no handshaking is supported.
DMA mostly works for the PCI-DIO32HS, but only in timed input mode.
The PCI-DIO-32HS/PCI-6533 has a configurable external trigger. Setting
scan_begin_arg to 0 or CR_EDGE triggers on the leading edge. Setting
scan_begin_arg to CR_INVERT or (CR_EDGE | CR_INVERT) triggers on the
trailing edge.
This driver could be easily modified to support AT-MIO32HS and
AT-MIO96.
The PCI-6534 requires a firmware upload after power-up to work, the
firmware data and instructions for loading it with comedi_config
it are contained in the
comedi_nonfree_firmware tarball available from http://www.comedi.org
*/
/*
This driver is for both the NI PCI-DIO-32HS and the PCI-DIO-96,
which have very different architectures. But, since the '96 is
so simple, it is included here.
Manuals (available from ftp://ftp.natinst.com/support/manuals)
320938c.pdf PCI-DIO-96/PXI-6508/PCI-6503 User Manual
321464b.pdf AT/PCI-DIO-32HS User Manual
341329A.pdf PCI-6533 Register-Level Programmer Manual
341330A.pdf DAQ-DIO Technical Reference Manual
*/
#define USE_DMA
/* #define DEBUG 1 */
/* #define DEBUG_FLAGS */
#include <linux/interrupt.h>
#include <linux/sched.h>
#include "../comedidev.h"
#include "mite.h"
#include "8255.h"
#undef DPRINTK
#ifdef DEBUG
#define DPRINTK(format, args...) printk(format, ## args)
#else
#define DPRINTK(format, args...)
#endif
#define PCI_DIO_SIZE 4096
#define PCI_MITE_SIZE 4096
/* defines for the PCI-DIO-96 */
#define NIDIO_8255_BASE(x) ((x)*4)
#define NIDIO_A 0
#define NIDIO_B 4
#define NIDIO_C 8
#define NIDIO_D 12
/* defines for the PCI-DIO-32HS */
#define Window_Address 4 /* W */
#define Interrupt_And_Window_Status 4 /* R */
#define IntStatus1 (1<<0)
#define IntStatus2 (1<<1)
#define WindowAddressStatus_mask 0x7c
#define Master_DMA_And_Interrupt_Control 5 /* W */
#define InterruptLine(x) ((x)&3)
#define OpenInt (1<<2)
#define Group_Status 5 /* R */
#define DataLeft (1<<0)
#define Req (1<<2)
#define StopTrig (1<<3)
#define Group_1_Flags 6 /* R */
#define Group_2_Flags 7 /* R */
#define TransferReady (1<<0)
#define CountExpired (1<<1)
#define Waited (1<<5)
#define PrimaryTC (1<<6)
#define SecondaryTC (1<<7)
/* #define SerialRose */
/* #define ReqRose */
/* #define Paused */
#define Group_1_First_Clear 6 /* W */
#define Group_2_First_Clear 7 /* W */
#define ClearWaited (1<<3)
#define ClearPrimaryTC (1<<4)
#define ClearSecondaryTC (1<<5)
#define DMAReset (1<<6)
#define FIFOReset (1<<7)
#define ClearAll 0xf8
#define Group_1_FIFO 8 /* W */
#define Group_2_FIFO 12 /* W */
#define Transfer_Count 20
#define Chip_ID_D 24
#define Chip_ID_I 25
#define Chip_ID_O 26
#define Chip_Version 27
#define Port_IO(x) (28+(x))
#define Port_Pin_Directions(x) (32+(x))
#define Port_Pin_Mask(x) (36+(x))
#define Port_Pin_Polarities(x) (40+(x))
#define Master_Clock_Routing 45
#define RTSIClocking(x) (((x)&3)<<4)
#define Group_1_Second_Clear 46 /* W */
#define Group_2_Second_Clear 47 /* W */
#define ClearExpired (1<<0)
#define Port_Pattern(x) (48+(x))
#define Data_Path 64
#define FIFOEnableA (1<<0)
#define FIFOEnableB (1<<1)
#define FIFOEnableC (1<<2)
#define FIFOEnableD (1<<3)
#define Funneling(x) (((x)&3)<<4)
#define GroupDirection (1<<7)
#define Protocol_Register_1 65
#define OpMode Protocol_Register_1
#define RunMode(x) ((x)&7)
#define Numbered (1<<3)
#define Protocol_Register_2 66
#define ClockReg Protocol_Register_2
#define ClockLine(x) (((x)&3)<<5)
#define InvertStopTrig (1<<7)
#define DataLatching(x) (((x)&3)<<5)
#define Protocol_Register_3 67
#define Sequence Protocol_Register_3
#define Protocol_Register_14 68 /* 16 bit */
#define ClockSpeed Protocol_Register_14
#define Protocol_Register_4 70
#define ReqReg Protocol_Register_4
#define ReqConditioning(x) (((x)&7)<<3)
#define Protocol_Register_5 71
#define BlockMode Protocol_Register_5
#define FIFO_Control 72
#define ReadyLevel(x) ((x)&7)
#define Protocol_Register_6 73
#define LinePolarities Protocol_Register_6
#define InvertAck (1<<0)
#define InvertReq (1<<1)
#define InvertClock (1<<2)
#define InvertSerial (1<<3)
#define OpenAck (1<<4)
#define OpenClock (1<<5)
#define Protocol_Register_7 74
#define AckSer Protocol_Register_7
#define AckLine(x) (((x)&3)<<2)
#define ExchangePins (1<<7)
#define Interrupt_Control 75
/* bits same as flags */
#define DMA_Line_Control_Group1 76
#define DMA_Line_Control_Group2 108
/* channel zero is none */
static inline unsigned primary_DMAChannel_bits(unsigned channel)
{
return channel & 0x3;
}
static inline unsigned secondary_DMAChannel_bits(unsigned channel)
{
return (channel << 2) & 0xc;
}
#define Transfer_Size_Control 77
#define TransferWidth(x) ((x)&3)
#define TransferLength(x) (((x)&3)<<3)
#define RequireRLevel (1<<5)
#define Protocol_Register_15 79
#define DAQOptions Protocol_Register_15
#define StartSource(x) ((x)&0x3)
#define InvertStart (1<<2)
#define StopSource(x) (((x)&0x3)<<3)
#define ReqStart (1<<6)
#define PreStart (1<<7)
#define Pattern_Detection 81
#define DetectionMethod (1<<0)
#define InvertMatch (1<<1)
#define IE_Pattern_Detection (1<<2)
#define Protocol_Register_9 82
#define ReqDelay Protocol_Register_9
#define Protocol_Register_10 83
#define ReqNotDelay Protocol_Register_10
#define Protocol_Register_11 84
#define AckDelay Protocol_Register_11
#define Protocol_Register_12 85
#define AckNotDelay Protocol_Register_12
#define Protocol_Register_13 86
#define Data1Delay Protocol_Register_13
#define Protocol_Register_8 88 /* 32 bit */
#define StartDelay Protocol_Register_8
enum pci_6534_firmware_registers { /* 16 bit */
Firmware_Control_Register = 0x100,
Firmware_Status_Register = 0x104,
Firmware_Data_Register = 0x108,
Firmware_Mask_Register = 0x10c,
Firmware_Debug_Register = 0x110,
};
/* main fpga registers (32 bit)*/
enum pci_6534_fpga_registers {
FPGA_Control1_Register = 0x200,
FPGA_Control2_Register = 0x204,
FPGA_Irq_Mask_Register = 0x208,
FPGA_Status_Register = 0x20c,
FPGA_Signature_Register = 0x210,
FPGA_SCALS_Counter_Register = 0x280, /*write-clear */
FPGA_SCAMS_Counter_Register = 0x284, /*write-clear */
FPGA_SCBLS_Counter_Register = 0x288, /*write-clear */
FPGA_SCBMS_Counter_Register = 0x28c, /*write-clear */
FPGA_Temp_Control_Register = 0x2a0,
FPGA_DAR_Register = 0x2a8,
FPGA_ELC_Read_Register = 0x2b8,
FPGA_ELC_Write_Register = 0x2bc,
};
enum FPGA_Control_Bits {
FPGA_Enable_Bit = 0x8000,
};
#define TIMER_BASE 50 /* nanoseconds */
#ifdef USE_DMA
#define IntEn (CountExpired|Waited|PrimaryTC|SecondaryTC)
#else
#define IntEn (TransferReady|CountExpired|Waited|PrimaryTC|SecondaryTC)
#endif
static int nidio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static int nidio_detach(struct comedi_device *dev);
static int ni_pcidio_cancel(struct comedi_device *dev,
struct comedi_subdevice *s);
static struct comedi_driver driver_pcidio = {
.driver_name = "ni_pcidio",
.module = THIS_MODULE,
.attach = nidio_attach,
.detach = nidio_detach,
};
struct nidio_board {
int dev_id;
const char *name;
int n_8255;
unsigned int is_diodaq:1;
unsigned int uses_firmware:1;
};
static const struct nidio_board nidio_boards[] = {
{
.dev_id = 0x1150,
.name = "pci-dio-32hs",
.n_8255 = 0,
.is_diodaq = 1,
},
{
.dev_id = 0x1320,
.name = "pxi-6533",
.n_8255 = 0,
.is_diodaq = 1,
},
{
.dev_id = 0x12b0,
.name = "pci-6534",
.n_8255 = 0,
.is_diodaq = 1,
.uses_firmware = 1,
},
{
.dev_id = 0x0160,
.name = "pci-dio-96",
.n_8255 = 4,
.is_diodaq = 0,
},
{
.dev_id = 0x1630,
.name = "pci-dio-96b",
.n_8255 = 4,
.is_diodaq = 0,
},
{
.dev_id = 0x13c0,
.name = "pxi-6508",
.n_8255 = 4,
.is_diodaq = 0,
},
{
.dev_id = 0x0400,
.name = "pci-6503",
.n_8255 = 1,
.is_diodaq = 0,
},
{
.dev_id = 0x1250,
.name = "pci-6503b",
.n_8255 = 1,
.is_diodaq = 0,
},
{
.dev_id = 0x17d0,
.name = "pci-6503x",
.n_8255 = 1,
.is_diodaq = 0,
},
{
.dev_id = 0x1800,
.name = "pxi-6503",
.n_8255 = 1,
.is_diodaq = 0,
},
};
#define n_nidio_boards ARRAY_SIZE(nidio_boards)
#define this_board ((const struct nidio_board *)dev->board_ptr)
static DEFINE_PCI_DEVICE_TABLE(ni_pcidio_pci_table) = {
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x1150)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x1320)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x12b0)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x0160)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x1630)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x13c0)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x0400)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x1250)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x17d0)},
{PCI_DEVICE(PCI_VENDOR_ID_NI, 0x1800)},
{0}
};
MODULE_DEVICE_TABLE(pci, ni_pcidio_pci_table);
struct nidio96_private {
struct mite_struct *mite;
int boardtype;
int dio;
unsigned short OpModeBits;
struct mite_channel *di_mite_chan;
struct mite_dma_descriptor_ring *di_mite_ring;
spinlock_t mite_channel_lock;
};
#define devpriv ((struct nidio96_private *)dev->private)
static int ni_pcidio_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd);
static int ni_pcidio_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
static int ni_pcidio_inttrig(struct comedi_device *dev,
struct comedi_subdevice *s, unsigned int trignum);
static int nidio_find_device(struct comedi_device *dev, int bus, int slot);
static int ni_pcidio_ns_to_timer(int *nanosec, int round_mode);
static int setup_mite_dma(struct comedi_device *dev,
struct comedi_subdevice *s);
#ifdef DEBUG_FLAGS
static void ni_pcidio_print_flags(unsigned int flags);
static void ni_pcidio_print_status(unsigned int status);
#else
#define ni_pcidio_print_flags(x)
#define ni_pcidio_print_status(x)
#endif
static int ni_pcidio_request_di_mite_channel(struct comedi_device *dev)
{
unsigned long flags;
spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
BUG_ON(devpriv->di_mite_chan);
devpriv->di_mite_chan =
mite_request_channel_in_range(devpriv->mite,
devpriv->di_mite_ring, 1, 2);
if (devpriv->di_mite_chan == NULL) {
spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
comedi_error(dev, "failed to reserve mite dma channel.");
return -EBUSY;
}
devpriv->di_mite_chan->dir = COMEDI_INPUT;
writeb(primary_DMAChannel_bits(devpriv->di_mite_chan->channel) |
secondary_DMAChannel_bits(devpriv->di_mite_chan->channel),
devpriv->mite->daq_io_addr + DMA_Line_Control_Group1);
mmiowb();
spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
return 0;
}
static void ni_pcidio_release_di_mite_channel(struct comedi_device *dev)
{
unsigned long flags;
spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
if (devpriv->di_mite_chan) {
mite_dma_disarm(devpriv->di_mite_chan);
mite_dma_reset(devpriv->di_mite_chan);
mite_release_channel(devpriv->di_mite_chan);
devpriv->di_mite_chan = NULL;
writeb(primary_DMAChannel_bits(0) |
secondary_DMAChannel_bits(0),
devpriv->mite->daq_io_addr + DMA_Line_Control_Group1);
mmiowb();
}
spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
}
static int nidio96_8255_cb(int dir, int port, int data, unsigned long iobase)
{
if (dir) {
writeb(data, (void *)(iobase + port));
return 0;
} else {
return readb((void *)(iobase + port));
}
}
void ni_pcidio_event(struct comedi_device *dev, struct comedi_subdevice *s)
{
if (s->
async->events & (COMEDI_CB_EOA | COMEDI_CB_ERROR |
COMEDI_CB_OVERFLOW)) {
ni_pcidio_cancel(dev, s);
}
comedi_event(dev, s);
}
static int ni_pcidio_poll(struct comedi_device *dev, struct comedi_subdevice *s)
{
unsigned long irq_flags;
int count;
spin_lock_irqsave(&dev->spinlock, irq_flags);
spin_lock(&devpriv->mite_channel_lock);
if (devpriv->di_mite_chan)
mite_sync_input_dma(devpriv->di_mite_chan, s->async);
spin_unlock(&devpriv->mite_channel_lock);
count = s->async->buf_write_count - s->async->buf_read_count;
spin_unlock_irqrestore(&dev->spinlock, irq_flags);
return count;
}
static irqreturn_t nidio_interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
struct comedi_subdevice *s = dev->subdevices;
struct comedi_async *async = s->async;
struct mite_struct *mite = devpriv->mite;
/* int i, j; */
long int AuxData = 0;
short data1 = 0;
short data2 = 0;
int flags;
int status;
int work = 0;
unsigned int m_status = 0;
/* interrupcions parasites */
if (dev->attached == 0) {
/* assume it's from another card */
return IRQ_NONE;
}
/* Lock to avoid race with comedi_poll */
spin_lock(&dev->spinlock);
status = readb(devpriv->mite->daq_io_addr +
Interrupt_And_Window_Status);
flags = readb(devpriv->mite->daq_io_addr + Group_1_Flags);
DPRINTK("ni_pcidio_interrupt: status=0x%02x,flags=0x%02x\n",
status, flags);
ni_pcidio_print_flags(flags);
ni_pcidio_print_status(status);
/* printk("buf[0]=%08x\n",*(unsigned int *)async->prealloc_buf); */
/* printk("buf[4096]=%08x\n",
*(unsigned int *)(async->prealloc_buf+4096)); */
spin_lock(&devpriv->mite_channel_lock);
if (devpriv->di_mite_chan)
m_status = mite_get_status(devpriv->di_mite_chan);
#ifdef MITE_DEBUG
mite_print_chsr(m_status);
#endif
/* printk("mite_bytes_transferred: %d\n",
mite_bytes_transferred(mite,DI_DMA_CHAN)); */
/* mite_dump_regs(mite); */
if (m_status & CHSR_INT) {
if (m_status & CHSR_LINKC) {
writel(CHOR_CLRLC,
mite->mite_io_addr +
MITE_CHOR(devpriv->di_mite_chan->channel));
mite_sync_input_dma(devpriv->di_mite_chan, s->async);
/* XXX need to byteswap */
}
if (m_status & ~(CHSR_INT | CHSR_LINKC | CHSR_DONE | CHSR_DRDY |
CHSR_DRQ1 | CHSR_MRDY)) {
DPRINTK("unknown mite interrupt, disabling IRQ\n");
async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
disable_irq(dev->irq);
}
}
spin_unlock(&devpriv->mite_channel_lock);
while (status & DataLeft) {
work++;
if (work > 20) {
DPRINTK("too much work in interrupt\n");
writeb(0x00,
devpriv->mite->daq_io_addr +
Master_DMA_And_Interrupt_Control);
break;
}
flags &= IntEn;
if (flags & TransferReady) {
/* DPRINTK("TransferReady\n"); */
while (flags & TransferReady) {
work++;
if (work > 100) {
DPRINTK("too much work in interrupt\n");
writeb(0x00,
devpriv->mite->daq_io_addr +
Master_DMA_And_Interrupt_Control
);
goto out;
}
AuxData =
readl(devpriv->mite->daq_io_addr +
Group_1_FIFO);
data1 = AuxData & 0xffff;
data2 = (AuxData & 0xffff0000) >> 16;
comedi_buf_put(async, data1);
comedi_buf_put(async, data2);
/* DPRINTK("read:%d, %d\n",data1,data2); */
flags = readb(devpriv->mite->daq_io_addr +
Group_1_Flags);
}
/* DPRINTK("buf_int_count: %d\n",
async->buf_int_count); */
/* DPRINTK("1) IntEn=%d,flags=%d,status=%d\n",
IntEn,flags,status); */
/* ni_pcidio_print_flags(flags); */
/* ni_pcidio_print_status(status); */
async->events |= COMEDI_CB_BLOCK;
}
if (flags & CountExpired) {
DPRINTK("CountExpired\n");
writeb(ClearExpired,
devpriv->mite->daq_io_addr +
Group_1_Second_Clear);
async->events |= COMEDI_CB_EOA;
writeb(0x00, devpriv->mite->daq_io_addr + OpMode);
break;
} else if (flags & Waited) {
DPRINTK("Waited\n");
writeb(ClearWaited,
devpriv->mite->daq_io_addr +
Group_1_First_Clear);
async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
break;
} else if (flags & PrimaryTC) {
DPRINTK("PrimaryTC\n");
writeb(ClearPrimaryTC,
devpriv->mite->daq_io_addr +
Group_1_First_Clear);
async->events |= COMEDI_CB_EOA;
} else if (flags & SecondaryTC) {
DPRINTK("SecondaryTC\n");
writeb(ClearSecondaryTC,
devpriv->mite->daq_io_addr +
Group_1_First_Clear);
async->events |= COMEDI_CB_EOA;
}
#if 0
else {
printk("ni_pcidio: unknown interrupt\n");
async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
writeb(0x00,
devpriv->mite->daq_io_addr +
Master_DMA_And_Interrupt_Control);
}
#endif
flags = readb(devpriv->mite->daq_io_addr + Group_1_Flags);
status = readb(devpriv->mite->daq_io_addr +
Interrupt_And_Window_Status);
/* DPRINTK("loop end: IntEn=0x%02x,flags=0x%02x,"
"status=0x%02x\n", IntEn, flags, status); */
/* ni_pcidio_print_flags(flags); */
/* ni_pcidio_print_status(status); */
}
out:
ni_pcidio_event(dev, s);
#if 0
if (!tag) {
writeb(0x03,
devpriv->mite->daq_io_addr +
Master_DMA_And_Interrupt_Control);
}
#endif
spin_unlock(&dev->spinlock);
return IRQ_HANDLED;
}
#ifdef DEBUG_FLAGS
static const char *const flags_strings[] = {
"TransferReady", "CountExpired", "2", "3",
"4", "Waited", "PrimaryTC", "SecondaryTC",
};
static void ni_pcidio_print_flags(unsigned int flags)
{
int i;
printk(KERN_INFO "group_1_flags:");
for (i = 7; i >= 0; i--) {
if (flags & (1 << i))
printk(" %s", flags_strings[i]);
}
printk("\n");
}
static char *status_strings[] = {
"DataLeft1", "Reserved1", "Req1", "StopTrig1",
"DataLeft2", "Reserved2", "Req2", "StopTrig2",
};
static void ni_pcidio_print_status(unsigned int flags)
{
int i;
printk(KERN_INFO "group_status:");
for (i = 7; i >= 0; i--) {
if (flags & (1 << i))
printk(" %s", status_strings[i]);
}
printk("\n");
}
#endif
#ifdef unused
static void debug_int(struct comedi_device *dev)
{
int a, b;
static int n_int;
struct timeval tv;
do_gettimeofday(&tv);
a = readb(devpriv->mite->daq_io_addr + Group_Status);
b = readb(devpriv->mite->daq_io_addr + Group_1_Flags);
if (n_int < 10) {
DPRINTK("status 0x%02x flags 0x%02x time %06d\n", a, b,
(int)tv.tv_usec);
}
while (b & 1) {
writew(0xff, devpriv->mite->daq_io_addr + Group_1_FIFO);
b = readb(devpriv->mite->daq_io_addr + Group_1_Flags);
}
b = readb(devpriv->mite->daq_io_addr + Group_1_Flags);
if (n_int < 10) {
DPRINTK("new status 0x%02x\n", b);
n_int++;
}
}
#endif
static int ni_pcidio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
if (insn->n != 1)
return -EINVAL;
switch (data[0]) {
case INSN_CONFIG_DIO_OUTPUT:
s->io_bits |= 1 << CR_CHAN(insn->chanspec);
break;
case INSN_CONFIG_DIO_INPUT:
s->io_bits &= ~(1 << CR_CHAN(insn->chanspec));
break;
case INSN_CONFIG_DIO_QUERY:
data[1] =
(s->
io_bits & (1 << CR_CHAN(insn->chanspec))) ? COMEDI_OUTPUT :
COMEDI_INPUT;
return insn->n;
break;
default:
return -EINVAL;
}
writel(s->io_bits, devpriv->mite->daq_io_addr + Port_Pin_Directions(0));
return 1;
}
static int ni_pcidio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
if (insn->n != 2)
return -EINVAL;
if (data[0]) {
s->state &= ~data[0];
s->state |= (data[0] & data[1]);
writel(s->state, devpriv->mite->daq_io_addr + Port_IO(0));
}
data[1] = readl(devpriv->mite->daq_io_addr + Port_IO(0));
return 2;
}
static int ni_pcidio_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW | TRIG_INT;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_NOW;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually
compatible */
/* note that mutual compatibility is not an issue here */
if (cmd->start_src != TRIG_NOW && cmd->start_src != TRIG_INT)
err++;
if (cmd->scan_begin_src != TRIG_TIMER &&
cmd->scan_begin_src != TRIG_EXT)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_arg != 0) {
/* same for both TRIG_INT and TRIG_NOW */
cmd->start_arg = 0;
err++;
}
#define MAX_SPEED (TIMER_BASE) /* in nanoseconds */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->scan_begin_arg < MAX_SPEED) {
cmd->scan_begin_arg = MAX_SPEED;
err++;
}
/* no minimum speed */
} else {
/* TRIG_EXT */
/* should be level/edge, hi/lo specification here */
if ((cmd->scan_begin_arg & ~(CR_EDGE | CR_INVERT)) != 0) {
cmd->scan_begin_arg &= (CR_EDGE | CR_INVERT);
err++;
}
}
if (cmd->convert_arg != 0) {
cmd->convert_arg = 0;
err++;
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
/* no limit */
} else {
/* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
tmp = cmd->scan_begin_arg;
ni_pcidio_ns_to_timer(&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->scan_begin_arg)
err++;
}
if (err)
return 4;
return 0;
}
static int ni_pcidio_ns_to_timer(int *nanosec, int round_mode)
{
int divider, base;
base = TIMER_BASE;
switch (round_mode) {
case TRIG_ROUND_NEAREST:
default:
divider = (*nanosec + base / 2) / base;
break;
case TRIG_ROUND_DOWN:
divider = (*nanosec) / base;
break;
case TRIG_ROUND_UP:
divider = (*nanosec + base - 1) / base;
break;
}
*nanosec = base * divider;
return divider;
}
static int ni_pcidio_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_cmd *cmd = &s->async->cmd;
/* XXX configure ports for input */
writel(0x0000, devpriv->mite->daq_io_addr + Port_Pin_Directions(0));
if (1) {
/* enable fifos A B C D */
writeb(0x0f, devpriv->mite->daq_io_addr + Data_Path);
/* set transfer width a 32 bits */
writeb(TransferWidth(0) | TransferLength(0),
devpriv->mite->daq_io_addr + Transfer_Size_Control);
} else {
writeb(0x03, devpriv->mite->daq_io_addr + Data_Path);
writeb(TransferWidth(3) | TransferLength(0),
devpriv->mite->daq_io_addr + Transfer_Size_Control);
}
/* protocol configuration */
if (cmd->scan_begin_src == TRIG_TIMER) {
/* page 4-5, "input with internal REQs" */
writeb(0, devpriv->mite->daq_io_addr + OpMode);
writeb(0x00, devpriv->mite->daq_io_addr + ClockReg);
writeb(1, devpriv->mite->daq_io_addr + Sequence);
writeb(0x04, devpriv->mite->daq_io_addr + ReqReg);
writeb(4, devpriv->mite->daq_io_addr + BlockMode);
writeb(3, devpriv->mite->daq_io_addr + LinePolarities);
writeb(0xc0, devpriv->mite->daq_io_addr + AckSer);
writel(ni_pcidio_ns_to_timer(&cmd->scan_begin_arg,
TRIG_ROUND_NEAREST),
devpriv->mite->daq_io_addr + StartDelay);
writeb(1, devpriv->mite->daq_io_addr + ReqDelay);
writeb(1, devpriv->mite->daq_io_addr + ReqNotDelay);
writeb(1, devpriv->mite->daq_io_addr + AckDelay);
writeb(0x0b, devpriv->mite->daq_io_addr + AckNotDelay);
writeb(0x01, devpriv->mite->daq_io_addr + Data1Delay);
/* manual, page 4-5: ClockSpeed comment is incorrectly listed
* on DAQOptions */
writew(0, devpriv->mite->daq_io_addr + ClockSpeed);
writeb(0, devpriv->mite->daq_io_addr + DAQOptions);
} else {
/* TRIG_EXT */
/* page 4-5, "input with external REQs" */
writeb(0, devpriv->mite->daq_io_addr + OpMode);
writeb(0x00, devpriv->mite->daq_io_addr + ClockReg);
writeb(0, devpriv->mite->daq_io_addr + Sequence);
writeb(0x00, devpriv->mite->daq_io_addr + ReqReg);
writeb(4, devpriv->mite->daq_io_addr + BlockMode);
if (!(cmd->scan_begin_arg & CR_INVERT)) {
/* Leading Edge pulse mode */
writeb(0, devpriv->mite->daq_io_addr + LinePolarities);
} else {
/* Trailing Edge pulse mode */
writeb(2, devpriv->mite->daq_io_addr + LinePolarities);
}
writeb(0x00, devpriv->mite->daq_io_addr + AckSer);
writel(1, devpriv->mite->daq_io_addr + StartDelay);
writeb(1, devpriv->mite->daq_io_addr + ReqDelay);
writeb(1, devpriv->mite->daq_io_addr + ReqNotDelay);
writeb(1, devpriv->mite->daq_io_addr + AckDelay);
writeb(0x0C, devpriv->mite->daq_io_addr + AckNotDelay);
writeb(0x10, devpriv->mite->daq_io_addr + Data1Delay);
writew(0, devpriv->mite->daq_io_addr + ClockSpeed);
writeb(0x60, devpriv->mite->daq_io_addr + DAQOptions);
}
if (cmd->stop_src == TRIG_COUNT) {
writel(cmd->stop_arg,
devpriv->mite->daq_io_addr + Transfer_Count);
} else {
/* XXX */
}
#ifdef USE_DMA
writeb(ClearPrimaryTC | ClearSecondaryTC,
devpriv->mite->daq_io_addr + Group_1_First_Clear);
{
int retval = setup_mite_dma(dev, s);
if (retval)
return retval;
}
#else
writeb(0x00, devpriv->mite->daq_io_addr + DMA_Line_Control_Group1);
#endif
writeb(0x00, devpriv->mite->daq_io_addr + DMA_Line_Control_Group2);
/* clear and enable interrupts */
writeb(0xff, devpriv->mite->daq_io_addr + Group_1_First_Clear);
/* writeb(ClearExpired,
devpriv->mite->daq_io_addr+Group_1_Second_Clear); */
writeb(IntEn, devpriv->mite->daq_io_addr + Interrupt_Control);
writeb(0x03,
devpriv->mite->daq_io_addr + Master_DMA_And_Interrupt_Control);
if (cmd->stop_src == TRIG_NONE) {
devpriv->OpModeBits = DataLatching(0) | RunMode(7);
} else { /* TRIG_TIMER */
devpriv->OpModeBits = Numbered | RunMode(7);
}
if (cmd->start_src == TRIG_NOW) {
/* start */
writeb(devpriv->OpModeBits,
devpriv->mite->daq_io_addr + OpMode);
s->async->inttrig = NULL;
} else {
/* TRIG_INT */
s->async->inttrig = ni_pcidio_inttrig;
}
DPRINTK("ni_pcidio: command started\n");
return 0;
}
static int setup_mite_dma(struct comedi_device *dev, struct comedi_subdevice *s)
{
int retval;
unsigned long flags;
retval = ni_pcidio_request_di_mite_channel(dev);
if (retval)
return retval;
/* write alloc the entire buffer */
comedi_buf_write_alloc(s->async, s->async->prealloc_bufsz);
spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
if (devpriv->di_mite_chan) {
mite_prep_dma(devpriv->di_mite_chan, 32, 32);
mite_dma_arm(devpriv->di_mite_chan);
} else
retval = -EIO;
spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
return retval;
}
static int ni_pcidio_inttrig(struct comedi_device *dev,
struct comedi_subdevice *s, unsigned int trignum)
{
if (trignum != 0)
return -EINVAL;
writeb(devpriv->OpModeBits, devpriv->mite->daq_io_addr + OpMode);
s->async->inttrig = NULL;
return 1;
}
static int ni_pcidio_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
writeb(0x00,
devpriv->mite->daq_io_addr + Master_DMA_And_Interrupt_Control);
ni_pcidio_release_di_mite_channel(dev);
return 0;
}
static int ni_pcidio_change(struct comedi_device *dev,
struct comedi_subdevice *s, unsigned long new_size)
{
int ret;
ret = mite_buf_change(devpriv->di_mite_ring, s->async);
if (ret < 0)
return ret;
memset(s->async->prealloc_buf, 0xaa, s->async->prealloc_bufsz);
return 0;
}
static int pci_6534_load_fpga(struct comedi_device *dev, int fpga_index,
u8 *data, int data_len)
{
static const int timeout = 1000;
int i, j;
writew(0x80 | fpga_index,
devpriv->mite->daq_io_addr + Firmware_Control_Register);
writew(0xc0 | fpga_index,
devpriv->mite->daq_io_addr + Firmware_Control_Register);
for (i = 0;
(readw(devpriv->mite->daq_io_addr +
Firmware_Status_Register) & 0x2) == 0 && i < timeout; ++i) {
udelay(1);
}
if (i == timeout) {
printk(KERN_WARNING "ni_pcidio: failed to load fpga %i, "
"waiting for status 0x2\n", fpga_index);
return -EIO;
}
writew(0x80 | fpga_index,
devpriv->mite->daq_io_addr + Firmware_Control_Register);
for (i = 0;
readw(devpriv->mite->daq_io_addr + Firmware_Status_Register) !=
0x3 && i < timeout; ++i) {
udelay(1);
}
if (i == timeout) {
printk(KERN_WARNING "ni_pcidio: failed to load fpga %i, "
"waiting for status 0x3\n", fpga_index);
return -EIO;
}
for (j = 0; j + 1 < data_len;) {
unsigned int value = data[j++];
value |= data[j++] << 8;
writew(value,
devpriv->mite->daq_io_addr + Firmware_Data_Register);
for (i = 0;
(readw(devpriv->mite->daq_io_addr +
Firmware_Status_Register) & 0x2) == 0
&& i < timeout; ++i) {
udelay(1);
}
if (i == timeout) {
printk("ni_pcidio: failed to load word into fpga %i\n",
fpga_index);
return -EIO;
}
if (need_resched())
schedule();
}
writew(0x0, devpriv->mite->daq_io_addr + Firmware_Control_Register);
return 0;
}
static int pci_6534_reset_fpga(struct comedi_device *dev, int fpga_index)
{
return pci_6534_load_fpga(dev, fpga_index, NULL, 0);
}
static int pci_6534_reset_fpgas(struct comedi_device *dev)
{
int ret;
int i;
writew(0x0, devpriv->mite->daq_io_addr + Firmware_Control_Register);
for (i = 0; i < 3; ++i) {
ret = pci_6534_reset_fpga(dev, i);
if (ret < 0)
break;
}
writew(0x0, devpriv->mite->daq_io_addr + Firmware_Mask_Register);
return ret;
}
static void pci_6534_init_main_fpga(struct comedi_device *dev)
{
writel(0, devpriv->mite->daq_io_addr + FPGA_Control1_Register);
writel(0, devpriv->mite->daq_io_addr + FPGA_Control2_Register);
writel(0, devpriv->mite->daq_io_addr + FPGA_SCALS_Counter_Register);
writel(0, devpriv->mite->daq_io_addr + FPGA_SCAMS_Counter_Register);
writel(0, devpriv->mite->daq_io_addr + FPGA_SCBLS_Counter_Register);
writel(0, devpriv->mite->daq_io_addr + FPGA_SCBMS_Counter_Register);
}
static int pci_6534_upload_firmware(struct comedi_device *dev, int options[])
{
int ret;
void *main_fpga_data, *scarab_a_data, *scarab_b_data;
int main_fpga_data_len, scarab_a_data_len, scarab_b_data_len;
if (options[COMEDI_DEVCONF_AUX_DATA_LENGTH] == 0)
return 0;
ret = pci_6534_reset_fpgas(dev);
if (ret < 0)
return ret;
main_fpga_data = comedi_aux_data(options, 0);
main_fpga_data_len = options[COMEDI_DEVCONF_AUX_DATA0_LENGTH];
ret = pci_6534_load_fpga(dev, 2, main_fpga_data, main_fpga_data_len);
if (ret < 0)
return ret;
pci_6534_init_main_fpga(dev);
scarab_a_data = comedi_aux_data(options, 1);
scarab_a_data_len = options[COMEDI_DEVCONF_AUX_DATA1_LENGTH];
ret = pci_6534_load_fpga(dev, 0, scarab_a_data, scarab_a_data_len);
if (ret < 0)
return ret;
scarab_b_data = comedi_aux_data(options, 2);
scarab_b_data_len = options[COMEDI_DEVCONF_AUX_DATA2_LENGTH];
ret = pci_6534_load_fpga(dev, 1, scarab_b_data, scarab_b_data_len);
if (ret < 0)
return ret;
return 0;
}
static int nidio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
int i;
int ret;
int n_subdevices;
unsigned int irq;
printk(KERN_INFO "comedi%d: nidio:", dev->minor);
ret = alloc_private(dev, sizeof(struct nidio96_private));
if (ret < 0)
return ret;
spin_lock_init(&devpriv->mite_channel_lock);
ret = nidio_find_device(dev, it->options[0], it->options[1]);
if (ret < 0)
return ret;
ret = mite_setup(devpriv->mite);
if (ret < 0) {
printk(KERN_WARNING "error setting up mite\n");
return ret;
}
comedi_set_hw_dev(dev, &devpriv->mite->pcidev->dev);
devpriv->di_mite_ring = mite_alloc_ring(devpriv->mite);
if (devpriv->di_mite_ring == NULL)
return -ENOMEM;
dev->board_name = this_board->name;
irq = mite_irq(devpriv->mite);
printk(KERN_INFO " %s", dev->board_name);
if (this_board->uses_firmware) {
ret = pci_6534_upload_firmware(dev, it->options);
if (ret < 0)
return ret;
}
if (!this_board->is_diodaq)
n_subdevices = this_board->n_8255;
else
n_subdevices = 1;
ret = alloc_subdevices(dev, n_subdevices);
if (ret < 0)
return ret;
if (!this_board->is_diodaq) {
for (i = 0; i < this_board->n_8255; i++) {
subdev_8255_init(dev, dev->subdevices + i,
nidio96_8255_cb,
(unsigned long)(devpriv->mite->
daq_io_addr +
NIDIO_8255_BASE(i)));
}
} else {
printk(KERN_INFO " rev=%d",
readb(devpriv->mite->daq_io_addr + Chip_Version));
s = dev->subdevices + 0;
dev->read_subdev = s;
s->type = COMEDI_SUBD_DIO;
s->subdev_flags =
SDF_READABLE | SDF_WRITABLE | SDF_LSAMPL | SDF_PACKED |
SDF_CMD_READ;
s->n_chan = 32;
s->range_table = &range_digital;
s->maxdata = 1;
s->insn_config = &ni_pcidio_insn_config;
s->insn_bits = &ni_pcidio_insn_bits;
s->do_cmd = &ni_pcidio_cmd;
s->do_cmdtest = &ni_pcidio_cmdtest;
s->cancel = &ni_pcidio_cancel;
s->len_chanlist = 32; /* XXX */
s->buf_change = &ni_pcidio_change;
s->async_dma_dir = DMA_BIDIRECTIONAL;
s->poll = &ni_pcidio_poll;
writel(0, devpriv->mite->daq_io_addr + Port_IO(0));
writel(0, devpriv->mite->daq_io_addr + Port_Pin_Directions(0));
writel(0, devpriv->mite->daq_io_addr + Port_Pin_Mask(0));
/* disable interrupts on board */
writeb(0x00,
devpriv->mite->daq_io_addr +
Master_DMA_And_Interrupt_Control);
ret = request_irq(irq, nidio_interrupt, IRQF_SHARED,
"ni_pcidio", dev);
if (ret < 0)
printk(KERN_WARNING " irq not available");
dev->irq = irq;
}
printk("\n");
return 0;
}
static int nidio_detach(struct comedi_device *dev)
{
int i;
if (this_board && !this_board->is_diodaq) {
for (i = 0; i < this_board->n_8255; i++)
subdev_8255_cleanup(dev, dev->subdevices + i);
}
if (dev->irq)
free_irq(dev->irq, dev);
if (devpriv) {
if (devpriv->di_mite_ring) {
mite_free_ring(devpriv->di_mite_ring);
devpriv->di_mite_ring = NULL;
}
if (devpriv->mite)
mite_unsetup(devpriv->mite);
}
return 0;
}
static int nidio_find_device(struct comedi_device *dev, int bus, int slot)
{
struct mite_struct *mite;
int i;
for (mite = mite_devices; mite; mite = mite->next) {
if (mite->used)
continue;
if (bus || slot) {
if (bus != mite->pcidev->bus->number ||
slot != PCI_SLOT(mite->pcidev->devfn))
continue;
}
for (i = 0; i < n_nidio_boards; i++) {
if (mite_device_id(mite) == nidio_boards[i].dev_id) {
dev->board_ptr = nidio_boards + i;
devpriv->mite = mite;
return 0;
}
}
}
printk(KERN_WARNING "no device found\n");
mite_list_devices();
return -EIO;
}
static int __devinit driver_pcidio_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, driver_pcidio.driver_name);
}
static void __devexit driver_pcidio_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_pcidio_pci_driver = {
.id_table = ni_pcidio_pci_table,
.probe = &driver_pcidio_pci_probe,
.remove = __devexit_p(&driver_pcidio_pci_remove)
};
static int __init driver_pcidio_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_pcidio);
if (retval < 0)
return retval;
driver_pcidio_pci_driver.name = (char *)driver_pcidio.driver_name;
return pci_register_driver(&driver_pcidio_pci_driver);
}
static void __exit driver_pcidio_cleanup_module(void)
{
pci_unregister_driver(&driver_pcidio_pci_driver);
comedi_driver_unregister(&driver_pcidio);
}
module_init(driver_pcidio_init_module);
module_exit(driver_pcidio_cleanup_module);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
htc-mirror/endeavoru-2.6.39-86aa44d | drivers/gpu/drm/nouveau/nv10_fifo.c | 8135 | 7971 | /*
* Copyright (C) 2007 Ben Skeggs.
* 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 COPYRIGHT OWNER(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.
*
*/
#include "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "nouveau_ramht.h"
#define NV10_RAMFC(c) (dev_priv->ramfc->pinst + ((c) * NV10_RAMFC__SIZE))
#define NV10_RAMFC__SIZE ((dev_priv->chipset) >= 0x17 ? 64 : 32)
int
nv10_fifo_channel_id(struct drm_device *dev)
{
return nv_rd32(dev, NV03_PFIFO_CACHE1_PUSH1) &
NV10_PFIFO_CACHE1_PUSH1_CHID_MASK;
}
int
nv10_fifo_create_context(struct nouveau_channel *chan)
{
struct drm_nouveau_private *dev_priv = chan->dev->dev_private;
struct drm_device *dev = chan->dev;
uint32_t fc = NV10_RAMFC(chan->id);
int ret;
ret = nouveau_gpuobj_new_fake(dev, NV10_RAMFC(chan->id), ~0,
NV10_RAMFC__SIZE, NVOBJ_FLAG_ZERO_ALLOC |
NVOBJ_FLAG_ZERO_FREE, &chan->ramfc);
if (ret)
return ret;
chan->user = ioremap(pci_resource_start(dev->pdev, 0) +
NV03_USER(chan->id), PAGE_SIZE);
if (!chan->user)
return -ENOMEM;
/* Fill entries that are seen filled in dumps of nvidia driver just
* after channel's is put into DMA mode
*/
nv_wi32(dev, fc + 0, chan->pushbuf_base);
nv_wi32(dev, fc + 4, chan->pushbuf_base);
nv_wi32(dev, fc + 12, chan->pushbuf->pinst >> 4);
nv_wi32(dev, fc + 20, NV_PFIFO_CACHE1_DMA_FETCH_TRIG_128_BYTES |
NV_PFIFO_CACHE1_DMA_FETCH_SIZE_128_BYTES |
NV_PFIFO_CACHE1_DMA_FETCH_MAX_REQS_8 |
#ifdef __BIG_ENDIAN
NV_PFIFO_CACHE1_BIG_ENDIAN |
#endif
0);
/* enable the fifo dma operation */
nv_wr32(dev, NV04_PFIFO_MODE,
nv_rd32(dev, NV04_PFIFO_MODE) | (1 << chan->id));
return 0;
}
static void
nv10_fifo_do_load_context(struct drm_device *dev, int chid)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
uint32_t fc = NV10_RAMFC(chid), tmp;
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_PUT, nv_ri32(dev, fc + 0));
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_GET, nv_ri32(dev, fc + 4));
nv_wr32(dev, NV10_PFIFO_CACHE1_REF_CNT, nv_ri32(dev, fc + 8));
tmp = nv_ri32(dev, fc + 12);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_INSTANCE, tmp & 0xFFFF);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_DCOUNT, tmp >> 16);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_STATE, nv_ri32(dev, fc + 16));
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_FETCH, nv_ri32(dev, fc + 20));
nv_wr32(dev, NV04_PFIFO_CACHE1_ENGINE, nv_ri32(dev, fc + 24));
nv_wr32(dev, NV04_PFIFO_CACHE1_PULL1, nv_ri32(dev, fc + 28));
if (dev_priv->chipset < 0x17)
goto out;
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_VALUE, nv_ri32(dev, fc + 32));
tmp = nv_ri32(dev, fc + 36);
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMESTAMP, tmp);
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMEOUT, nv_ri32(dev, fc + 40));
nv_wr32(dev, NV10_PFIFO_CACHE1_SEMAPHORE, nv_ri32(dev, fc + 44));
nv_wr32(dev, NV10_PFIFO_CACHE1_DMA_SUBROUTINE, nv_ri32(dev, fc + 48));
out:
nv_wr32(dev, NV03_PFIFO_CACHE1_GET, 0);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUT, 0);
}
int
nv10_fifo_load_context(struct nouveau_channel *chan)
{
struct drm_device *dev = chan->dev;
uint32_t tmp;
nv10_fifo_do_load_context(dev, chan->id);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1,
NV03_PFIFO_CACHE1_PUSH1_DMA | chan->id);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_PUSH, 1);
/* Reset NV04_PFIFO_CACHE1_DMA_CTL_AT_INFO to INVALID */
tmp = nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_CTL) & ~(1 << 31);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_CTL, tmp);
return 0;
}
int
nv10_fifo_unload_context(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
uint32_t fc, tmp;
int chid;
chid = pfifo->channel_id(dev);
if (chid < 0 || chid >= dev_priv->engine.fifo.channels)
return 0;
fc = NV10_RAMFC(chid);
nv_wi32(dev, fc + 0, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_PUT));
nv_wi32(dev, fc + 4, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_GET));
nv_wi32(dev, fc + 8, nv_rd32(dev, NV10_PFIFO_CACHE1_REF_CNT));
tmp = nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_INSTANCE) & 0xFFFF;
tmp |= (nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_DCOUNT) << 16);
nv_wi32(dev, fc + 12, tmp);
nv_wi32(dev, fc + 16, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_STATE));
nv_wi32(dev, fc + 20, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_FETCH));
nv_wi32(dev, fc + 24, nv_rd32(dev, NV04_PFIFO_CACHE1_ENGINE));
nv_wi32(dev, fc + 28, nv_rd32(dev, NV04_PFIFO_CACHE1_PULL1));
if (dev_priv->chipset < 0x17)
goto out;
nv_wi32(dev, fc + 32, nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_VALUE));
tmp = nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMESTAMP);
nv_wi32(dev, fc + 36, tmp);
nv_wi32(dev, fc + 40, nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMEOUT));
nv_wi32(dev, fc + 44, nv_rd32(dev, NV10_PFIFO_CACHE1_SEMAPHORE));
nv_wi32(dev, fc + 48, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_GET));
out:
nv10_fifo_do_load_context(dev, pfifo->channels - 1);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1, pfifo->channels - 1);
return 0;
}
static void
nv10_fifo_init_reset(struct drm_device *dev)
{
nv_wr32(dev, NV03_PMC_ENABLE,
nv_rd32(dev, NV03_PMC_ENABLE) & ~NV_PMC_ENABLE_PFIFO);
nv_wr32(dev, NV03_PMC_ENABLE,
nv_rd32(dev, NV03_PMC_ENABLE) | NV_PMC_ENABLE_PFIFO);
nv_wr32(dev, 0x003224, 0x000f0078);
nv_wr32(dev, 0x002044, 0x0101ffff);
nv_wr32(dev, 0x002040, 0x000000ff);
nv_wr32(dev, 0x002500, 0x00000000);
nv_wr32(dev, 0x003000, 0x00000000);
nv_wr32(dev, 0x003050, 0x00000000);
nv_wr32(dev, 0x003258, 0x00000000);
nv_wr32(dev, 0x003210, 0x00000000);
nv_wr32(dev, 0x003270, 0x00000000);
}
static void
nv10_fifo_init_ramxx(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
nv_wr32(dev, NV03_PFIFO_RAMHT, (0x03 << 24) /* search 128 */ |
((dev_priv->ramht->bits - 9) << 16) |
(dev_priv->ramht->gpuobj->pinst >> 8));
nv_wr32(dev, NV03_PFIFO_RAMRO, dev_priv->ramro->pinst >> 8);
if (dev_priv->chipset < 0x17) {
nv_wr32(dev, NV03_PFIFO_RAMFC, dev_priv->ramfc->pinst >> 8);
} else {
nv_wr32(dev, NV03_PFIFO_RAMFC, (dev_priv->ramfc->pinst >> 8) |
(1 << 16) /* 64 Bytes entry*/);
/* XXX nvidia blob set bit 18, 21,23 for nv20 & nv30 */
}
}
static void
nv10_fifo_init_intr(struct drm_device *dev)
{
nouveau_irq_register(dev, 8, nv04_fifo_isr);
nv_wr32(dev, 0x002100, 0xffffffff);
nv_wr32(dev, 0x002140, 0xffffffff);
}
int
nv10_fifo_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
int i;
nv10_fifo_init_reset(dev);
nv10_fifo_init_ramxx(dev);
nv10_fifo_do_load_context(dev, pfifo->channels - 1);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1, pfifo->channels - 1);
nv10_fifo_init_intr(dev);
pfifo->enable(dev);
pfifo->reassign(dev, true);
for (i = 0; i < dev_priv->engine.fifo.channels; i++) {
if (dev_priv->channels.ptr[i]) {
uint32_t mode = nv_rd32(dev, NV04_PFIFO_MODE);
nv_wr32(dev, NV04_PFIFO_MODE, mode | (1 << i));
}
}
return 0;
}
| gpl-2.0 |
dukie/sun4i-kernel | arch/um/drivers/pcap_kern.c | 9671 | 2588 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL.
*/
#include "linux/init.h"
#include <linux/netdevice.h>
#include "net_kern.h"
#include "pcap_user.h"
struct pcap_init {
char *host_if;
int promisc;
int optimize;
char *filter;
};
void pcap_init(struct net_device *dev, void *data)
{
struct uml_net_private *pri;
struct pcap_data *ppri;
struct pcap_init *init = data;
pri = netdev_priv(dev);
ppri = (struct pcap_data *) pri->user;
ppri->host_if = init->host_if;
ppri->promisc = init->promisc;
ppri->optimize = init->optimize;
ppri->filter = init->filter;
printk("pcap backend, host interface %s\n", ppri->host_if);
}
static int pcap_read(int fd, struct sk_buff *skb, struct uml_net_private *lp)
{
return pcap_user_read(fd, skb_mac_header(skb),
skb->dev->mtu + ETH_HEADER_OTHER,
(struct pcap_data *) &lp->user);
}
static int pcap_write(int fd, struct sk_buff *skb, struct uml_net_private *lp)
{
return -EPERM;
}
static const struct net_kern_info pcap_kern_info = {
.init = pcap_init,
.protocol = eth_protocol,
.read = pcap_read,
.write = pcap_write,
};
int pcap_setup(char *str, char **mac_out, void *data)
{
struct pcap_init *init = data;
char *remain, *host_if = NULL, *options[2] = { NULL, NULL };
int i;
*init = ((struct pcap_init)
{ .host_if = "eth0",
.promisc = 1,
.optimize = 0,
.filter = NULL });
remain = split_if_spec(str, &host_if, &init->filter,
&options[0], &options[1], mac_out, NULL);
if (remain != NULL) {
printk(KERN_ERR "pcap_setup - Extra garbage on "
"specification : '%s'\n", remain);
return 0;
}
if (host_if != NULL)
init->host_if = host_if;
for (i = 0; i < ARRAY_SIZE(options); i++) {
if (options[i] == NULL)
continue;
if (!strcmp(options[i], "promisc"))
init->promisc = 1;
else if (!strcmp(options[i], "nopromisc"))
init->promisc = 0;
else if (!strcmp(options[i], "optimize"))
init->optimize = 1;
else if (!strcmp(options[i], "nooptimize"))
init->optimize = 0;
else {
printk(KERN_ERR "pcap_setup : bad option - '%s'\n",
options[i]);
return 0;
}
}
return 1;
}
static struct transport pcap_transport = {
.list = LIST_HEAD_INIT(pcap_transport.list),
.name = "pcap",
.setup = pcap_setup,
.user = &pcap_user_info,
.kern = &pcap_kern_info,
.private_size = sizeof(struct pcap_data),
.setup_size = sizeof(struct pcap_init),
};
static int register_pcap(void)
{
register_transport(&pcap_transport);
return 0;
}
late_initcall(register_pcap);
| gpl-2.0 |
toejoefull/limbo-android | jni/jpeg/jdphuff.c | 968 | 20559 | /*
* jdphuff.c
*
* Copyright (C) 1995-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains Huffman entropy decoding routines for progressive JPEG.
*
* Much of the complexity here has to do with supporting input suspension.
* If the data source module demands suspension, we want to be able to back
* up to the start of the current MCU. To do this, we copy state variables
* into local working storage, and update them back to the permanent
* storage only upon successful completion of an MCU.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jdhuff.h" /* Declarations shared with jdhuff.c */
#ifdef D_PROGRESSIVE_SUPPORTED
/*
* Expanded entropy decoder object for progressive Huffman decoding.
*
* The savable_state subrecord contains fields that change within an MCU,
* but must not be updated permanently until we complete the MCU.
*/
typedef struct {
unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
} savable_state;
/* This macro is to work around compilers with missing or broken
* structure assignment. You'll need to fix this code if you have
* such a compiler and you change MAX_COMPS_IN_SCAN.
*/
#ifndef NO_STRUCT_ASSIGN
#define ASSIGN_STATE(dest,src) ((dest) = (src))
#else
#if MAX_COMPS_IN_SCAN == 4
#define ASSIGN_STATE(dest,src) \
((dest).EOBRUN = (src).EOBRUN, \
(dest).last_dc_val[0] = (src).last_dc_val[0], \
(dest).last_dc_val[1] = (src).last_dc_val[1], \
(dest).last_dc_val[2] = (src).last_dc_val[2], \
(dest).last_dc_val[3] = (src).last_dc_val[3])
#endif
#endif
typedef struct {
struct jpeg_entropy_decoder pub; /* public fields */
/* These fields are loaded into local variables at start of each MCU.
* In case of suspension, we exit WITHOUT updating them.
*/
bitread_perm_state bitstate; /* Bit buffer at start of MCU */
savable_state saved; /* Other state at start of MCU */
/* These fields are NOT loaded into local working state. */
unsigned int restarts_to_go; /* MCUs left in this restart interval */
/* Pointers to derived tables (these workspaces have image lifespan) */
d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
} phuff_entropy_decoder;
typedef phuff_entropy_decoder * phuff_entropy_ptr;
/* Forward declarations */
METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
JBLOCKROW *MCU_data));
METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
JBLOCKROW *MCU_data));
METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
JBLOCKROW *MCU_data));
METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
JBLOCKROW *MCU_data));
/*
* Initialize for a Huffman-compressed scan.
*/
METHODDEF(void)
start_pass_phuff_decoder (j_decompress_ptr cinfo)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
boolean is_DC_band, bad;
int ci, coefi, tbl;
int *coef_bit_ptr;
jpeg_component_info * compptr;
is_DC_band = (cinfo->Ss == 0);
/* Validate scan parameters */
bad = FALSE;
if (is_DC_band) {
if (cinfo->Se != 0)
bad = TRUE;
} else {
/* need not check Ss/Se < 0 since they came from unsigned bytes */
if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
bad = TRUE;
/* AC scans may have only one component */
if (cinfo->comps_in_scan != 1)
bad = TRUE;
}
if (cinfo->Ah != 0) {
/* Successive approximation refinement scan: must have Al = Ah-1. */
if (cinfo->Al != cinfo->Ah-1)
bad = TRUE;
}
if (cinfo->Al > 13) /* need not check for < 0 */
bad = TRUE;
/* Arguably the maximum Al value should be less than 13 for 8-bit precision,
* but the spec doesn't say so, and we try to be liberal about what we
* accept. Note: large Al values could result in out-of-range DC
* coefficients during early scans, leading to bizarre displays due to
* overflows in the IDCT math. But we won't crash.
*/
if (bad)
ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
/* Update progression status, and verify that scan order is legal.
* Note that inter-scan inconsistencies are treated as warnings
* not fatal errors ... not clear if this is right way to behave.
*/
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
int cindex = cinfo->cur_comp_info[ci]->component_index;
coef_bit_ptr = & cinfo->coef_bits[cindex][0];
if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
if (cinfo->Ah != expected)
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
coef_bit_ptr[coefi] = cinfo->Al;
}
}
/* Select MCU decoding routine */
if (cinfo->Ah == 0) {
if (is_DC_band)
entropy->pub.decode_mcu = decode_mcu_DC_first;
else
entropy->pub.decode_mcu = decode_mcu_AC_first;
} else {
if (is_DC_band)
entropy->pub.decode_mcu = decode_mcu_DC_refine;
else
entropy->pub.decode_mcu = decode_mcu_AC_refine;
}
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
/* Make sure requested tables are present, and compute derived tables.
* We may build same derived table more than once, but it's not expensive.
*/
if (is_DC_band) {
if (cinfo->Ah == 0) { /* DC refinement needs no table */
tbl = compptr->dc_tbl_no;
jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
& entropy->derived_tbls[tbl]);
}
} else {
tbl = compptr->ac_tbl_no;
jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
& entropy->derived_tbls[tbl]);
/* remember the single active table */
entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
}
/* Initialize DC predictions to 0 */
entropy->saved.last_dc_val[ci] = 0;
}
/* Initialize bitread state variables */
entropy->bitstate.bits_left = 0;
entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
entropy->pub.insufficient_data = FALSE;
/* Initialize private state variables */
entropy->saved.EOBRUN = 0;
/* Initialize restart counter */
entropy->restarts_to_go = cinfo->restart_interval;
}
/*
* Figure F.12: extend sign bit.
* On some machines, a shift and add will be faster than a table lookup.
*/
#ifdef AVOID_TABLES
#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
#else
#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
static const int extend_test[16] = /* entry n is 2**(n-1) */
{ 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
{ 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
#endif /* AVOID_TABLES */
/*
* Check for a restart marker & resynchronize decoder.
* Returns FALSE if must suspend.
*/
LOCAL(boolean)
process_restart (j_decompress_ptr cinfo)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int ci;
/* Throw away any unused bits remaining in bit buffer; */
/* include any full bytes in next_marker's count of discarded bytes */
cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
entropy->bitstate.bits_left = 0;
/* Advance past the RSTn marker */
if (! (*cinfo->marker->read_restart_marker) (cinfo))
return FALSE;
/* Re-initialize DC predictions to 0 */
for (ci = 0; ci < cinfo->comps_in_scan; ci++)
entropy->saved.last_dc_val[ci] = 0;
/* Re-init EOB run count, too */
entropy->saved.EOBRUN = 0;
/* Reset restart counter */
entropy->restarts_to_go = cinfo->restart_interval;
/* Reset out-of-data flag, unless read_restart_marker left us smack up
* against a marker. In that case we will end up treating the next data
* segment as empty, and we can avoid producing bogus output pixels by
* leaving the flag set.
*/
if (cinfo->unread_marker == 0)
entropy->pub.insufficient_data = FALSE;
return TRUE;
}
/*
* Huffman MCU decoding.
* Each of these routines decodes and returns one MCU's worth of
* Huffman-compressed coefficients.
* The coefficients are reordered from zigzag order into natural array order,
* but are not dequantized.
*
* The i'th block of the MCU is stored into the block pointed to by
* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
*
* We return FALSE if data source requested suspension. In that case no
* changes have been made to permanent state. (Exception: some output
* coefficients may already have been assigned. This is harmless for
* spectral selection, since we'll just re-assign them on the next call.
* Successive approximation AC refinement has to be more careful, however.)
*/
/*
* MCU decoding for DC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(boolean)
decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int Al = cinfo->Al;
register int s, r;
int blkn, ci;
JBLOCKROW block;
BITREAD_STATE_VARS;
savable_state state;
d_derived_tbl * tbl;
jpeg_component_info * compptr;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, just leave the MCU set to zeroes.
* This way, we return uniform gray for the remainder of the segment.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
ASSIGN_STATE(state, entropy->saved);
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
ci = cinfo->MCU_membership[blkn];
compptr = cinfo->cur_comp_info[ci];
tbl = entropy->derived_tbls[compptr->dc_tbl_no];
/* Decode a single block's worth of coefficients */
/* Section F.2.2.1: decode the DC coefficient difference */
HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
if (s) {
CHECK_BIT_BUFFER(br_state, s, return FALSE);
r = GET_BITS(s);
s = HUFF_EXTEND(r, s);
}
/* Convert DC difference to actual value, update last_dc_val */
s += state.last_dc_val[ci];
state.last_dc_val[ci] = s;
/* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
(*block)[0] = (JCOEF) (s << Al);
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
ASSIGN_STATE(entropy->saved, state);
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for AC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(boolean)
decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int Se = cinfo->Se;
int Al = cinfo->Al;
register int s, k, r;
unsigned int EOBRUN;
JBLOCKROW block;
BITREAD_STATE_VARS;
d_derived_tbl * tbl;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, just leave the MCU set to zeroes.
* This way, we return uniform gray for the remainder of the segment.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state.
* We can avoid loading/saving bitread state if in an EOB run.
*/
EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
/* There is always only one block per MCU */
if (EOBRUN > 0) /* if it's a band of zeroes... */
EOBRUN--; /* ...process it now (we do nothing) */
else {
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
block = MCU_data[0];
tbl = entropy->ac_derived_tbl;
for (k = cinfo->Ss; k <= Se; k++) {
HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
r = s >> 4;
s &= 15;
if (s) {
k += r;
CHECK_BIT_BUFFER(br_state, s, return FALSE);
r = GET_BITS(s);
s = HUFF_EXTEND(r, s);
/* Scale and output coefficient in natural (dezigzagged) order */
(*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
} else {
if (r == 15) { /* ZRL */
k += 15; /* skip 15 zeroes in band */
} else { /* EOBr, run length is 2^r + appended bits */
EOBRUN = 1 << r;
if (r) { /* EOBr, r > 0 */
CHECK_BIT_BUFFER(br_state, r, return FALSE);
r = GET_BITS(r);
EOBRUN += r;
}
EOBRUN--; /* this band is processed at this moment */
break; /* force end-of-band */
}
}
}
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
}
/* Completed MCU, so update state */
entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for DC successive approximation refinement scan.
* Note: we assume such scans can be multi-component, although the spec
* is not very clear on the point.
*/
METHODDEF(boolean)
decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
int blkn;
JBLOCKROW block;
BITREAD_STATE_VARS;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* Not worth the cycles to check insufficient_data here,
* since we will not change the data anyway if we read zeroes.
*/
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
/* Encoded data is simply the next bit of the two's-complement DC value */
CHECK_BIT_BUFFER(br_state, 1, return FALSE);
if (GET_BITS(1))
(*block)[0] |= p1;
/* Note: since we use |=, repeating the assignment later is safe */
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for AC successive approximation refinement scan.
*/
METHODDEF(boolean)
decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int Se = cinfo->Se;
int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
register int s, k, r;
unsigned int EOBRUN;
JBLOCKROW block;
JCOEFPTR thiscoef;
BITREAD_STATE_VARS;
d_derived_tbl * tbl;
int num_newnz;
int newnz_pos[DCTSIZE2];
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, don't modify the MCU.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
/* There is always only one block per MCU */
block = MCU_data[0];
tbl = entropy->ac_derived_tbl;
/* If we are forced to suspend, we must undo the assignments to any newly
* nonzero coefficients in the block, because otherwise we'd get confused
* next time about which coefficients were already nonzero.
* But we need not undo addition of bits to already-nonzero coefficients;
* instead, we can test the current bit to see if we already did it.
*/
num_newnz = 0;
/* initialize coefficient loop counter to start of band */
k = cinfo->Ss;
if (EOBRUN == 0) {
for (; k <= Se; k++) {
HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
r = s >> 4;
s &= 15;
if (s) {
if (s != 1) /* size of new coef should always be 1 */
WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1))
s = p1; /* newly nonzero coef is positive */
else
s = m1; /* newly nonzero coef is negative */
} else {
if (r != 15) {
EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
if (r) {
CHECK_BIT_BUFFER(br_state, r, goto undoit);
r = GET_BITS(r);
EOBRUN += r;
}
break; /* rest of block is handled by EOB logic */
}
/* note s = 0 for processing ZRL */
}
/* Advance over already-nonzero coefs and r still-zero coefs,
* appending correction bits to the nonzeroes. A correction bit is 1
* if the absolute value of the coefficient must be increased.
*/
do {
thiscoef = *block + jpeg_natural_order[k];
if (*thiscoef != 0) {
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1)) {
if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
if (*thiscoef >= 0)
*thiscoef += p1;
else
*thiscoef += m1;
}
}
} else {
if (--r < 0)
break; /* reached target zero coefficient */
}
k++;
} while (k <= Se);
if (s) {
int pos = jpeg_natural_order[k];
/* Output newly nonzero coefficient */
(*block)[pos] = (JCOEF) s;
/* Remember its position in case we have to suspend */
newnz_pos[num_newnz++] = pos;
}
}
}
if (EOBRUN > 0) {
/* Scan any remaining coefficient positions after the end-of-band
* (the last newly nonzero coefficient, if any). Append a correction
* bit to each already-nonzero coefficient. A correction bit is 1
* if the absolute value of the coefficient must be increased.
*/
for (; k <= Se; k++) {
thiscoef = *block + jpeg_natural_order[k];
if (*thiscoef != 0) {
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1)) {
if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
if (*thiscoef >= 0)
*thiscoef += p1;
else
*thiscoef += m1;
}
}
}
}
/* Count one block completed in EOB run */
EOBRUN--;
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
undoit:
/* Re-zero any output coefficients that we made newly nonzero */
while (num_newnz > 0)
(*block)[newnz_pos[--num_newnz]] = 0;
return FALSE;
}
/*
* Module initialization routine for progressive Huffman entropy decoding.
*/
GLOBAL(void)
jinit_phuff_decoder (j_decompress_ptr cinfo)
{
phuff_entropy_ptr entropy;
int *coef_bit_ptr;
int ci, i;
entropy = (phuff_entropy_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(phuff_entropy_decoder));
cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
entropy->pub.start_pass = start_pass_phuff_decoder;
/* Mark derived tables unallocated */
for (i = 0; i < NUM_HUFF_TBLS; i++) {
entropy->derived_tbls[i] = NULL;
}
/* Create progression status table */
cinfo->coef_bits = (int (*)[DCTSIZE2])
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
cinfo->num_components*DCTSIZE2*SIZEOF(int));
coef_bit_ptr = & cinfo->coef_bits[0][0];
for (ci = 0; ci < cinfo->num_components; ci++)
for (i = 0; i < DCTSIZE2; i++)
*coef_bit_ptr++ = -1;
}
#endif /* D_PROGRESSIVE_SUPPORTED */
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.